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 // FIXME: The trackHeight should have been added before updateLogicalHeight was called to avoid this hack.
132 updateIntrinsicContentLogicalHeight(trackHeight);
134 RenderBox::computeLogicalHeight(trackHeight, logicalTop, computedValues);
138 logicalHeight = RenderSlider::defaultTrackLength;
140 // FIXME: The trackHeight should have been added before updateLogicalHeight was called to avoid this hack.
141 updateIntrinsicContentLogicalHeight(logicalHeight);
143 RenderBox::computeLogicalHeight(logicalHeight, logicalTop, computedValues);
146 void RenderSliderContainer::layout()
148 HTMLInputElement* input = toHTMLInputElement(node()->shadowHost());
149 bool isVertical = hasVerticalAppearance(input);
150 style()->setFlexDirection(isVertical ? FlowColumn : FlowRow);
151 TextDirection oldTextDirection = style()->direction();
153 // FIXME: Work around rounding issues in RTL vertical sliders. We want them to
154 // render identically to LTR vertical sliders. We can remove this work around when
155 // subpixel rendering is enabled on all ports.
156 style()->setDirection(LTR);
159 Element* thumbElement = input->userAgentShadowRoot()->getElementById(ShadowElementNames::sliderThumb());
160 Element* trackElement = input->userAgentShadowRoot()->getElementById(ShadowElementNames::sliderTrack());
161 RenderBox* thumb = thumbElement ? thumbElement->renderBox() : 0;
162 RenderBox* track = trackElement ? trackElement->renderBox() : 0;
164 SubtreeLayoutScope layoutScope(*this);
165 // Force a layout to reset the position of the thumb so the code below doesn't move the thumb to the wrong place.
166 // FIXME: Make a custom Render class for the track and move the thumb positioning code there.
168 layoutScope.setChildNeedsLayout(track);
170 RenderFlexibleBox::layout();
172 style()->setDirection(oldTextDirection);
173 // These should always exist, unless someone mutates the shadow DOM (e.g., in the inspector).
174 if (!thumb || !track)
177 double percentageOffset = sliderPosition(input).toDouble();
178 LayoutUnit availableExtent = isVertical ? track->contentHeight() : track->contentWidth();
179 availableExtent -= isVertical ? thumb->height() : thumb->width();
180 LayoutUnit offset = percentageOffset * availableExtent;
181 LayoutPoint thumbLocation = thumb->location();
183 thumbLocation.setY(thumbLocation.y() + track->contentHeight() - thumb->height() - offset);
184 else if (style()->isLeftToRightDirection())
185 thumbLocation.setX(thumbLocation.x() + offset);
187 thumbLocation.setX(thumbLocation.x() - offset);
188 thumb->setLocation(thumbLocation);
189 if (checkForRepaintDuringLayout() && parent()
190 && (parent()->style()->appearance() == MediaVolumeSliderPart || parent()->style()->appearance() == MediaSliderPart)) {
191 // This will sometimes repaint too much. However, it is necessary to
192 // correctly repaint media controls (volume and timeline sliders) -
193 // they have special painting code in RenderMediaControls.cpp:paintMediaVolumeSlider
194 // and paintMediaSlider that gets called via -webkit-appearance and RenderTheme,
195 // so nothing else would otherwise invalidate the slider.
200 // --------------------------------
202 inline SliderThumbElement::SliderThumbElement(Document& document)
203 : HTMLDivElement(document)
204 , m_inDragMode(false)
208 PassRefPtrWillBeRawPtr<SliderThumbElement> SliderThumbElement::create(Document& document)
210 RefPtrWillBeRawPtr<SliderThumbElement> element = adoptRefWillBeRefCountedGarbageCollected(new SliderThumbElement(document));
211 element->setAttribute(idAttr, ShadowElementNames::sliderThumb());
212 return element.release();
215 void SliderThumbElement::setPositionFromValue()
217 // Since the code to calculate position is in the RenderSliderThumb layout
218 // path, we don't actually update the value here. Instead, we poke at the
219 // renderer directly to trigger layout.
221 renderer()->setNeedsLayout();
224 RenderObject* SliderThumbElement::createRenderer(RenderStyle*)
226 return new RenderSliderThumb(this);
229 bool SliderThumbElement::isDisabledFormControl() const
231 return hostInput() && hostInput()->isDisabledFormControl();
234 bool SliderThumbElement::matchesReadOnlyPseudoClass() const
236 return hostInput() && hostInput()->matchesReadOnlyPseudoClass();
239 bool SliderThumbElement::matchesReadWritePseudoClass() const
241 return hostInput() && hostInput()->matchesReadWritePseudoClass();
244 Node* SliderThumbElement::focusDelegate()
249 void SliderThumbElement::dragFrom(const LayoutPoint& point)
251 RefPtr<SliderThumbElement> protector(this);
253 setPositionFromPoint(point);
256 void SliderThumbElement::setPositionFromPoint(const LayoutPoint& point)
258 RefPtr<HTMLInputElement> input(hostInput());
259 Element* trackElement = input->userAgentShadowRoot()->getElementById(ShadowElementNames::sliderTrack());
261 if (!input->renderer() || !renderBox() || !trackElement->renderBox())
264 LayoutPoint offset = roundedLayoutPoint(input->renderer()->absoluteToLocal(point, UseTransforms));
265 bool isVertical = hasVerticalAppearance(input.get());
266 bool isLeftToRightDirection = renderBox()->style()->isLeftToRightDirection();
267 LayoutUnit trackSize;
269 LayoutUnit currentPosition;
270 // We need to calculate currentPosition from absolute points becaue the
271 // renderer for this node is usually on a layer and renderBox()->x() and
273 // FIXME: This should probably respect transforms.
274 LayoutPoint absoluteThumbOrigin = renderBox()->absoluteBoundingBoxRectIgnoringTransforms().location();
275 LayoutPoint absoluteSliderContentOrigin = roundedLayoutPoint(input->renderer()->localToAbsolute());
276 IntRect trackBoundingBox = trackElement->renderer()->absoluteBoundingBoxRectIgnoringTransforms();
277 IntRect inputBoundingBox = input->renderer()->absoluteBoundingBoxRectIgnoringTransforms();
279 trackSize = trackElement->renderBox()->contentHeight() - renderBox()->height();
280 position = offset.y() - renderBox()->height() / 2 - trackBoundingBox.y() + inputBoundingBox.y() - renderBox()->marginBottom();
281 currentPosition = absoluteThumbOrigin.y() - absoluteSliderContentOrigin.y();
283 trackSize = trackElement->renderBox()->contentWidth() - renderBox()->width();
284 position = offset.x() - renderBox()->width() / 2 - trackBoundingBox.x() + inputBoundingBox.x();
285 position -= isLeftToRightDirection ? renderBox()->marginLeft() : renderBox()->marginRight();
286 currentPosition = absoluteThumbOrigin.x() - absoluteSliderContentOrigin.x();
288 position = max<LayoutUnit>(0, min(position, trackSize));
289 const Decimal ratio = Decimal::fromDouble(static_cast<double>(position) / trackSize);
290 const Decimal fraction = isVertical || !isLeftToRightDirection ? Decimal(1) - ratio : ratio;
291 StepRange stepRange(input->createStepRange(RejectAny));
292 Decimal value = stepRange.clampValue(stepRange.valueFromProportion(fraction));
294 Decimal closest = input->findClosestTickMarkValue(value);
295 if (closest.isFinite()) {
296 double closestFraction = stepRange.proportionFromValue(closest).toDouble();
297 double closestRatio = isVertical || !isLeftToRightDirection ? 1.0 - closestFraction : closestFraction;
298 LayoutUnit closestPosition = trackSize * closestRatio;
299 const LayoutUnit snappingThreshold = 5;
300 if ((closestPosition - position).abs() <= snappingThreshold)
304 String valueString = serializeForNumberType(value);
305 if (valueString == input->value())
308 // FIXME: This is no longer being set from renderer. Consider updating the method name.
309 input->setValueFromRenderer(valueString);
311 renderer()->setNeedsLayout();
314 void SliderThumbElement::startDragging()
316 if (LocalFrame* frame = document().frame()) {
317 frame->eventHandler().setCapturingMouseEventsNode(this);
322 void SliderThumbElement::stopDragging()
327 if (LocalFrame* frame = document().frame())
328 frame->eventHandler().setCapturingMouseEventsNode(nullptr);
329 m_inDragMode = false;
331 renderer()->setNeedsLayout();
333 hostInput()->dispatchFormControlChangeEvent();
336 void SliderThumbElement::defaultEventHandler(Event* event)
338 if (!event->isMouseEvent()) {
339 HTMLDivElement::defaultEventHandler(event);
343 // FIXME: Should handle this readonly/disabled check in more general way.
344 // Missing this kind of check is likely to occur elsewhere if adding it in each shadow element.
345 HTMLInputElement* input = hostInput();
346 if (!input || input->isDisabledOrReadOnly()) {
348 HTMLDivElement::defaultEventHandler(event);
352 MouseEvent* mouseEvent = toMouseEvent(event);
353 bool isLeftButton = mouseEvent->button() == LeftButton;
354 const AtomicString& eventType = event->type();
356 // We intentionally do not call event->setDefaultHandled() here because
357 // MediaControlTimelineElement::defaultEventHandler() wants to handle these
359 if (eventType == EventTypeNames::mousedown && isLeftButton) {
362 } else if (eventType == EventTypeNames::mouseup && isLeftButton) {
365 } else if (eventType == EventTypeNames::mousemove) {
367 setPositionFromPoint(mouseEvent->absoluteLocation());
371 HTMLDivElement::defaultEventHandler(event);
374 bool SliderThumbElement::willRespondToMouseMoveEvents()
376 const HTMLInputElement* input = hostInput();
377 if (input && !input->isDisabledOrReadOnly() && m_inDragMode)
380 return HTMLDivElement::willRespondToMouseMoveEvents();
383 bool SliderThumbElement::willRespondToMouseClickEvents()
385 const HTMLInputElement* input = hostInput();
386 if (input && !input->isDisabledOrReadOnly())
389 return HTMLDivElement::willRespondToMouseClickEvents();
392 void SliderThumbElement::detach(const AttachContext& context)
395 if (LocalFrame* frame = document().frame())
396 frame->eventHandler().setCapturingMouseEventsNode(nullptr);
398 HTMLDivElement::detach(context);
401 HTMLInputElement* SliderThumbElement::hostInput() const
403 // Only HTMLInputElement creates SliderThumbElement instances as its shadow nodes.
404 // So, shadowHost() must be an HTMLInputElement.
405 return toHTMLInputElement(shadowHost());
408 static const AtomicString& sliderThumbShadowPartId()
410 DEFINE_STATIC_LOCAL(const AtomicString, sliderThumb, ("-webkit-slider-thumb", AtomicString::ConstructFromLiteral));
414 static const AtomicString& mediaSliderThumbShadowPartId()
416 DEFINE_STATIC_LOCAL(const AtomicString, mediaSliderThumb, ("-webkit-media-slider-thumb", AtomicString::ConstructFromLiteral));
417 return mediaSliderThumb;
420 const AtomicString& SliderThumbElement::shadowPseudoId() const
422 HTMLInputElement* input = hostInput();
423 if (!input || !input->renderer())
424 return sliderThumbShadowPartId();
426 RenderStyle* sliderStyle = input->renderer()->style();
427 switch (sliderStyle->appearance()) {
428 case MediaSliderPart:
429 case MediaSliderThumbPart:
430 case MediaVolumeSliderPart:
431 case MediaVolumeSliderThumbPart:
432 case MediaFullScreenVolumeSliderPart:
433 case MediaFullScreenVolumeSliderThumbPart:
434 return mediaSliderThumbShadowPartId();
436 return sliderThumbShadowPartId();
440 // --------------------------------
442 inline SliderContainerElement::SliderContainerElement(Document& document)
443 : HTMLDivElement(document)
447 PassRefPtrWillBeRawPtr<SliderContainerElement> SliderContainerElement::create(Document& document)
449 return adoptRefWillBeRefCountedGarbageCollected(new SliderContainerElement(document));
452 RenderObject* SliderContainerElement::createRenderer(RenderStyle*)
454 return new RenderSliderContainer(this);
457 const AtomicString& SliderContainerElement::shadowPseudoId() const
459 DEFINE_STATIC_LOCAL(const AtomicString, mediaSliderContainer, ("-webkit-media-slider-container", AtomicString::ConstructFromLiteral));
460 DEFINE_STATIC_LOCAL(const AtomicString, sliderContainer, ("-webkit-slider-container", AtomicString::ConstructFromLiteral));
462 if (!shadowHost() || !shadowHost()->renderer())
463 return sliderContainer;
465 RenderStyle* sliderStyle = shadowHost()->renderer()->style();
466 switch (sliderStyle->appearance()) {
467 case MediaSliderPart:
468 case MediaSliderThumbPart:
469 case MediaVolumeSliderPart:
470 case MediaVolumeSliderThumbPart:
471 case MediaFullScreenVolumeSliderPart:
472 case MediaFullScreenVolumeSliderThumbPart:
473 return mediaSliderContainer;
475 return sliderContainer;