2 * Copyright (C) 2006, 2007, 2008, 2009 Apple Inc. All rights reserved.
3 * Copyright (C) 2010 Google Inc. All rights reserved.
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions are
9 * * Redistributions of source code must retain the above copyright
10 * notice, this list of conditions and the following disclaimer.
11 * * Redistributions in binary form must reproduce the above
12 * copyright notice, this list of conditions and the following disclaimer
13 * in the documentation and/or other materials provided with the
15 * * Neither the name of Google Inc. nor the names of its
16 * contributors may be used to endorse or promote products derived from
17 * this software without specific prior written permission.
19 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
20 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
21 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
22 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
23 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
24 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
25 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
26 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
27 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
28 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
29 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
34 #include "core/html/shadow/SliderThumbElement.h"
36 #include "core/events/Event.h"
37 #include "core/events/MouseEvent.h"
38 #include "core/dom/shadow/ShadowRoot.h"
39 #include "core/frame/LocalFrame.h"
40 #include "core/html/HTMLInputElement.h"
41 #include "core/html/forms/StepRange.h"
42 #include "core/html/parser/HTMLParserIdioms.h"
43 #include "core/html/shadow/ShadowElementNames.h"
44 #include "core/page/EventHandler.h"
45 #include "core/rendering/RenderFlexibleBox.h"
46 #include "core/rendering/RenderSlider.h"
47 #include "core/rendering/RenderTheme.h"
53 using namespace HTMLNames;
55 inline static Decimal sliderPosition(HTMLInputElement* element)
57 const StepRange stepRange(element->createStepRange(RejectAny));
58 const Decimal oldValue = parseToDecimalForNumberType(element->value(), stepRange.defaultValue());
59 return stepRange.proportionFromValue(stepRange.clampValue(oldValue));
62 inline static bool hasVerticalAppearance(HTMLInputElement* input)
64 ASSERT(input->renderer());
65 RenderStyle* sliderStyle = input->renderer()->style();
67 return sliderStyle->appearance() == SliderVerticalPart;
70 // --------------------------------
72 RenderSliderThumb::RenderSliderThumb(SliderThumbElement* element)
73 : RenderBlockFlow(element)
77 void RenderSliderThumb::updateAppearance(RenderStyle* parentStyle)
79 if (parentStyle->appearance() == SliderVerticalPart)
80 style()->setAppearance(SliderThumbVerticalPart);
81 else if (parentStyle->appearance() == SliderHorizontalPart)
82 style()->setAppearance(SliderThumbHorizontalPart);
83 else if (parentStyle->appearance() == MediaSliderPart)
84 style()->setAppearance(MediaSliderThumbPart);
85 else if (parentStyle->appearance() == MediaVolumeSliderPart)
86 style()->setAppearance(MediaVolumeSliderThumbPart);
87 else if (parentStyle->appearance() == MediaFullScreenVolumeSliderPart)
88 style()->setAppearance(MediaFullScreenVolumeSliderThumbPart);
89 if (style()->hasAppearance())
90 RenderTheme::theme().adjustSliderThumbSize(style(), toElement(node()));
93 bool RenderSliderThumb::isSliderThumb() const
98 // --------------------------------
100 // FIXME: Find a way to cascade appearance and adjust heights, and get rid of this class.
101 // http://webkit.org/b/62535
102 class RenderSliderContainer : public RenderFlexibleBox {
104 RenderSliderContainer(SliderContainerElement* element)
105 : RenderFlexibleBox(element) { }
107 virtual void computeLogicalHeight(LayoutUnit logicalHeight, LayoutUnit logicalTop, LogicalExtentComputedValues&) const OVERRIDE;
110 virtual void layout() OVERRIDE;
113 void RenderSliderContainer::computeLogicalHeight(LayoutUnit logicalHeight, LayoutUnit logicalTop, LogicalExtentComputedValues& computedValues) const
115 HTMLInputElement* input = toHTMLInputElement(node()->shadowHost());
116 bool isVertical = hasVerticalAppearance(input);
118 if (input->renderer()->isSlider() && !isVertical && input->list()) {
119 int offsetFromCenter = RenderTheme::theme().sliderTickOffsetFromTrackCenter();
120 LayoutUnit trackHeight = 0;
121 if (offsetFromCenter < 0)
122 trackHeight = -2 * offsetFromCenter;
124 int tickLength = RenderTheme::theme().sliderTickSize().height();
125 trackHeight = 2 * (offsetFromCenter + tickLength);
127 float zoomFactor = style()->effectiveZoom();
128 if (zoomFactor != 1.0)
129 trackHeight *= zoomFactor;
131 RenderBox::computeLogicalHeight(trackHeight, logicalTop, computedValues);
135 logicalHeight = RenderSlider::defaultTrackLength;
136 RenderBox::computeLogicalHeight(logicalHeight, logicalTop, computedValues);
139 void RenderSliderContainer::layout()
141 HTMLInputElement* input = toHTMLInputElement(node()->shadowHost());
142 bool isVertical = hasVerticalAppearance(input);
143 style()->setFlexDirection(isVertical ? FlowColumn : FlowRow);
144 TextDirection oldTextDirection = style()->direction();
146 // FIXME: Work around rounding issues in RTL vertical sliders. We want them to
147 // render identically to LTR vertical sliders. We can remove this work around when
148 // subpixel rendering is enabled on all ports.
149 style()->setDirection(LTR);
152 Element* thumbElement = input->userAgentShadowRoot()->getElementById(ShadowElementNames::sliderThumb());
153 Element* trackElement = input->userAgentShadowRoot()->getElementById(ShadowElementNames::sliderTrack());
154 RenderBox* thumb = thumbElement ? thumbElement->renderBox() : 0;
155 RenderBox* track = trackElement ? trackElement->renderBox() : 0;
157 SubtreeLayoutScope layoutScope(this);
158 // Force a layout to reset the position of the thumb so the code below doesn't move the thumb to the wrong place.
159 // FIXME: Make a custom Render class for the track and move the thumb positioning code there.
161 layoutScope.setChildNeedsLayout(track);
163 RenderFlexibleBox::layout();
165 style()->setDirection(oldTextDirection);
166 // These should always exist, unless someone mutates the shadow DOM (e.g., in the inspector).
167 if (!thumb || !track)
170 double percentageOffset = sliderPosition(input).toDouble();
171 LayoutUnit availableExtent = isVertical ? track->contentHeight() : track->contentWidth();
172 availableExtent -= isVertical ? thumb->height() : thumb->width();
173 LayoutUnit offset = percentageOffset * availableExtent;
174 LayoutPoint thumbLocation = thumb->location();
176 thumbLocation.setY(thumbLocation.y() + track->contentHeight() - thumb->height() - offset);
177 else if (style()->isLeftToRightDirection())
178 thumbLocation.setX(thumbLocation.x() + offset);
180 thumbLocation.setX(thumbLocation.x() - offset);
181 thumb->setLocation(thumbLocation);
182 if (checkForRepaintDuringLayout() && parent()
183 && (parent()->style()->appearance() == MediaVolumeSliderPart || parent()->style()->appearance() == MediaSliderPart)) {
184 // This will sometimes repaint too much. However, it is necessary to
185 // correctly repaint media controls (volume and timeline sliders) -
186 // they have special painting code in RenderMediaControls.cpp:paintMediaVolumeSlider
187 // and paintMediaSlider that gets called via -webkit-appearance and RenderTheme,
188 // so nothing else would otherwise invalidate the slider.
193 // --------------------------------
195 inline SliderThumbElement::SliderThumbElement(Document& document)
196 : HTMLDivElement(document)
197 , m_inDragMode(false)
201 PassRefPtr<SliderThumbElement> SliderThumbElement::create(Document& document)
203 RefPtr<SliderThumbElement> element = adoptRef(new SliderThumbElement(document));
204 element->setAttribute(idAttr, ShadowElementNames::sliderThumb());
205 return element.release();
208 void SliderThumbElement::setPositionFromValue()
210 // Since the code to calculate position is in the RenderSliderThumb layout
211 // path, we don't actually update the value here. Instead, we poke at the
212 // renderer directly to trigger layout.
214 renderer()->setNeedsLayout();
217 RenderObject* SliderThumbElement::createRenderer(RenderStyle*)
219 return new RenderSliderThumb(this);
222 bool SliderThumbElement::isDisabledFormControl() const
224 return hostInput() && hostInput()->isDisabledFormControl();
227 bool SliderThumbElement::matchesReadOnlyPseudoClass() const
229 return hostInput() && hostInput()->matchesReadOnlyPseudoClass();
232 bool SliderThumbElement::matchesReadWritePseudoClass() const
234 return hostInput() && hostInput()->matchesReadWritePseudoClass();
237 Node* SliderThumbElement::focusDelegate()
242 void SliderThumbElement::dragFrom(const LayoutPoint& point)
244 RefPtr<SliderThumbElement> protector(this);
246 setPositionFromPoint(point);
249 void SliderThumbElement::setPositionFromPoint(const LayoutPoint& point)
251 RefPtr<HTMLInputElement> input(hostInput());
252 Element* trackElement = input->userAgentShadowRoot()->getElementById(ShadowElementNames::sliderTrack());
254 if (!input->renderer() || !renderBox() || !trackElement->renderBox())
257 LayoutPoint offset = roundedLayoutPoint(input->renderer()->absoluteToLocal(point, UseTransforms));
258 bool isVertical = hasVerticalAppearance(input.get());
259 bool isLeftToRightDirection = renderBox()->style()->isLeftToRightDirection();
260 LayoutUnit trackSize;
262 LayoutUnit currentPosition;
263 // We need to calculate currentPosition from absolute points becaue the
264 // renderer for this node is usually on a layer and renderBox()->x() and
266 // FIXME: This should probably respect transforms.
267 LayoutPoint absoluteThumbOrigin = renderBox()->absoluteBoundingBoxRectIgnoringTransforms().location();
268 LayoutPoint absoluteSliderContentOrigin = roundedLayoutPoint(input->renderer()->localToAbsolute());
269 IntRect trackBoundingBox = trackElement->renderer()->absoluteBoundingBoxRectIgnoringTransforms();
270 IntRect inputBoundingBox = input->renderer()->absoluteBoundingBoxRectIgnoringTransforms();
272 trackSize = trackElement->renderBox()->contentHeight() - renderBox()->height();
273 position = offset.y() - renderBox()->height() / 2 - trackBoundingBox.y() + inputBoundingBox.y() - renderBox()->marginBottom();
274 currentPosition = absoluteThumbOrigin.y() - absoluteSliderContentOrigin.y();
276 trackSize = trackElement->renderBox()->contentWidth() - renderBox()->width();
277 position = offset.x() - renderBox()->width() / 2 - trackBoundingBox.x() + inputBoundingBox.x();
278 position -= isLeftToRightDirection ? renderBox()->marginLeft() : renderBox()->marginRight();
279 currentPosition = absoluteThumbOrigin.x() - absoluteSliderContentOrigin.x();
281 position = max<LayoutUnit>(0, min(position, trackSize));
282 const Decimal ratio = Decimal::fromDouble(static_cast<double>(position) / trackSize);
283 const Decimal fraction = isVertical || !isLeftToRightDirection ? Decimal(1) - ratio : ratio;
284 StepRange stepRange(input->createStepRange(RejectAny));
285 Decimal value = stepRange.clampValue(stepRange.valueFromProportion(fraction));
287 Decimal closest = input->findClosestTickMarkValue(value);
288 if (closest.isFinite()) {
289 double closestFraction = stepRange.proportionFromValue(closest).toDouble();
290 double closestRatio = isVertical || !isLeftToRightDirection ? 1.0 - closestFraction : closestFraction;
291 LayoutUnit closestPosition = trackSize * closestRatio;
292 const LayoutUnit snappingThreshold = 5;
293 if ((closestPosition - position).abs() <= snappingThreshold)
297 String valueString = serializeForNumberType(value);
298 if (valueString == input->value())
301 // FIXME: This is no longer being set from renderer. Consider updating the method name.
302 input->setValueFromRenderer(valueString);
304 renderer()->setNeedsLayout();
307 void SliderThumbElement::startDragging()
309 if (LocalFrame* frame = document().frame()) {
310 frame->eventHandler().setCapturingMouseEventsNode(this);
315 void SliderThumbElement::stopDragging()
320 if (LocalFrame* frame = document().frame())
321 frame->eventHandler().setCapturingMouseEventsNode(nullptr);
322 m_inDragMode = false;
324 renderer()->setNeedsLayout();
326 hostInput()->dispatchFormControlChangeEvent();
329 void SliderThumbElement::defaultEventHandler(Event* event)
331 if (!event->isMouseEvent()) {
332 HTMLDivElement::defaultEventHandler(event);
336 // FIXME: Should handle this readonly/disabled check in more general way.
337 // Missing this kind of check is likely to occur elsewhere if adding it in each shadow element.
338 HTMLInputElement* input = hostInput();
339 if (!input || input->isDisabledOrReadOnly()) {
341 HTMLDivElement::defaultEventHandler(event);
345 MouseEvent* mouseEvent = toMouseEvent(event);
346 bool isLeftButton = mouseEvent->button() == LeftButton;
347 const AtomicString& eventType = event->type();
349 // We intentionally do not call event->setDefaultHandled() here because
350 // MediaControlTimelineElement::defaultEventHandler() wants to handle these
352 if (eventType == EventTypeNames::mousedown && isLeftButton) {
355 } else if (eventType == EventTypeNames::mouseup && isLeftButton) {
358 } else if (eventType == EventTypeNames::mousemove) {
360 setPositionFromPoint(mouseEvent->absoluteLocation());
364 HTMLDivElement::defaultEventHandler(event);
367 bool SliderThumbElement::willRespondToMouseMoveEvents()
369 const HTMLInputElement* input = hostInput();
370 if (input && !input->isDisabledOrReadOnly() && m_inDragMode)
373 return HTMLDivElement::willRespondToMouseMoveEvents();
376 bool SliderThumbElement::willRespondToMouseClickEvents()
378 const HTMLInputElement* input = hostInput();
379 if (input && !input->isDisabledOrReadOnly())
382 return HTMLDivElement::willRespondToMouseClickEvents();
385 void SliderThumbElement::detach(const AttachContext& context)
388 if (LocalFrame* frame = document().frame())
389 frame->eventHandler().setCapturingMouseEventsNode(nullptr);
391 HTMLDivElement::detach(context);
394 HTMLInputElement* SliderThumbElement::hostInput() const
396 // Only HTMLInputElement creates SliderThumbElement instances as its shadow nodes.
397 // So, shadowHost() must be an HTMLInputElement.
398 return toHTMLInputElement(shadowHost());
401 static const AtomicString& sliderThumbShadowPartId()
403 DEFINE_STATIC_LOCAL(const AtomicString, sliderThumb, ("-webkit-slider-thumb", AtomicString::ConstructFromLiteral));
407 static const AtomicString& mediaSliderThumbShadowPartId()
409 DEFINE_STATIC_LOCAL(const AtomicString, mediaSliderThumb, ("-webkit-media-slider-thumb", AtomicString::ConstructFromLiteral));
410 return mediaSliderThumb;
413 const AtomicString& SliderThumbElement::shadowPseudoId() const
415 HTMLInputElement* input = hostInput();
416 if (!input || !input->renderer())
417 return sliderThumbShadowPartId();
419 RenderStyle* sliderStyle = input->renderer()->style();
420 switch (sliderStyle->appearance()) {
421 case MediaSliderPart:
422 case MediaSliderThumbPart:
423 case MediaVolumeSliderPart:
424 case MediaVolumeSliderThumbPart:
425 case MediaFullScreenVolumeSliderPart:
426 case MediaFullScreenVolumeSliderThumbPart:
427 return mediaSliderThumbShadowPartId();
429 return sliderThumbShadowPartId();
433 // --------------------------------
435 inline SliderContainerElement::SliderContainerElement(Document& document)
436 : HTMLDivElement(document)
440 PassRefPtr<SliderContainerElement> SliderContainerElement::create(Document& document)
442 return adoptRef(new SliderContainerElement(document));
445 RenderObject* SliderContainerElement::createRenderer(RenderStyle*)
447 return new RenderSliderContainer(this);
450 const AtomicString& SliderContainerElement::shadowPseudoId() const
452 DEFINE_STATIC_LOCAL(const AtomicString, mediaSliderContainer, ("-webkit-media-slider-container", AtomicString::ConstructFromLiteral));
453 DEFINE_STATIC_LOCAL(const AtomicString, sliderContainer, ("-webkit-slider-container", AtomicString::ConstructFromLiteral));
455 if (!shadowHost() || !shadowHost()->renderer())
456 return sliderContainer;
458 RenderStyle* sliderStyle = shadowHost()->renderer()->style();
459 switch (sliderStyle->appearance()) {
460 case MediaSliderPart:
461 case MediaSliderThumbPart:
462 case MediaVolumeSliderPart:
463 case MediaVolumeSliderThumbPart:
464 case MediaFullScreenVolumeSliderPart:
465 case MediaFullScreenVolumeSliderThumbPart:
466 return mediaSliderContainer;
468 return sliderContainer;