Upstream version 7.36.149.0
[platform/framework/web/crosswalk.git] / src / third_party / WebKit / Source / core / html / shadow / SliderThumbElement.cpp
1 /*
2  * Copyright (C) 2006, 2007, 2008, 2009 Apple Inc. All rights reserved.
3  * Copyright (C) 2010 Google Inc. All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions are
7  * met:
8  *
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
14  * distribution.
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.
18  *
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.
30  */
31
32
33 #include "config.h"
34 #include "core/html/shadow/SliderThumbElement.h"
35
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"
48
49 using namespace std;
50
51 namespace WebCore {
52
53 using namespace HTMLNames;
54
55 inline static Decimal sliderPosition(HTMLInputElement* element)
56 {
57     const StepRange stepRange(element->createStepRange(RejectAny));
58     const Decimal oldValue = parseToDecimalForNumberType(element->value(), stepRange.defaultValue());
59     return stepRange.proportionFromValue(stepRange.clampValue(oldValue));
60 }
61
62 inline static bool hasVerticalAppearance(HTMLInputElement* input)
63 {
64     ASSERT(input->renderer());
65     RenderStyle* sliderStyle = input->renderer()->style();
66
67     return sliderStyle->appearance() == SliderVerticalPart;
68 }
69
70 // --------------------------------
71
72 RenderSliderThumb::RenderSliderThumb(SliderThumbElement* element)
73     : RenderBlockFlow(element)
74 {
75 }
76
77 void RenderSliderThumb::updateAppearance(RenderStyle* parentStyle)
78 {
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()));
91 }
92
93 bool RenderSliderThumb::isSliderThumb() const
94 {
95     return true;
96 }
97
98 // --------------------------------
99
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 {
103 public:
104     RenderSliderContainer(SliderContainerElement* element)
105         : RenderFlexibleBox(element) { }
106 public:
107     virtual void computeLogicalHeight(LayoutUnit logicalHeight, LayoutUnit logicalTop, LogicalExtentComputedValues&) const OVERRIDE;
108
109 private:
110     virtual void layout() OVERRIDE;
111 };
112
113 void RenderSliderContainer::computeLogicalHeight(LayoutUnit logicalHeight, LayoutUnit logicalTop, LogicalExtentComputedValues& computedValues) const
114 {
115     HTMLInputElement* input = toHTMLInputElement(node()->shadowHost());
116     bool isVertical = hasVerticalAppearance(input);
117
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;
123         else {
124             int tickLength = RenderTheme::theme().sliderTickSize().height();
125             trackHeight = 2 * (offsetFromCenter + tickLength);
126         }
127         float zoomFactor = style()->effectiveZoom();
128         if (zoomFactor != 1.0)
129             trackHeight *= zoomFactor;
130
131         // FIXME: The trackHeight should have been added before updateLogicalHeight was called to avoid this hack.
132         updateIntrinsicContentLogicalHeight(trackHeight);
133
134         RenderBox::computeLogicalHeight(trackHeight, logicalTop, computedValues);
135         return;
136     }
137     if (isVertical)
138         logicalHeight = RenderSlider::defaultTrackLength;
139
140     // FIXME: The trackHeight should have been added before updateLogicalHeight was called to avoid this hack.
141     updateIntrinsicContentLogicalHeight(logicalHeight);
142
143     RenderBox::computeLogicalHeight(logicalHeight, logicalTop, computedValues);
144 }
145
146 void RenderSliderContainer::layout()
147 {
148     HTMLInputElement* input = toHTMLInputElement(node()->shadowHost());
149     bool isVertical = hasVerticalAppearance(input);
150     style()->setFlexDirection(isVertical ? FlowColumn : FlowRow);
151     TextDirection oldTextDirection = style()->direction();
152     if (isVertical) {
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);
157     }
158
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;
163
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.
167     if (track)
168         layoutScope.setChildNeedsLayout(track);
169
170     RenderFlexibleBox::layout();
171
172     style()->setDirection(oldTextDirection);
173     // These should always exist, unless someone mutates the shadow DOM (e.g., in the inspector).
174     if (!thumb || !track)
175         return;
176
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();
182     if (isVertical)
183         thumbLocation.setY(thumbLocation.y() + track->contentHeight() - thumb->height() - offset);
184     else if (style()->isLeftToRightDirection())
185         thumbLocation.setX(thumbLocation.x() + offset);
186     else
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.
196         repaint();
197     }
198 }
199
200 // --------------------------------
201
202 inline SliderThumbElement::SliderThumbElement(Document& document)
203     : HTMLDivElement(document)
204     , m_inDragMode(false)
205 {
206 }
207
208 PassRefPtrWillBeRawPtr<SliderThumbElement> SliderThumbElement::create(Document& document)
209 {
210     RefPtrWillBeRawPtr<SliderThumbElement> element = adoptRefWillBeRefCountedGarbageCollected(new SliderThumbElement(document));
211     element->setAttribute(idAttr, ShadowElementNames::sliderThumb());
212     return element.release();
213 }
214
215 void SliderThumbElement::setPositionFromValue()
216 {
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.
220     if (renderer())
221         renderer()->setNeedsLayout();
222 }
223
224 RenderObject* SliderThumbElement::createRenderer(RenderStyle*)
225 {
226     return new RenderSliderThumb(this);
227 }
228
229 bool SliderThumbElement::isDisabledFormControl() const
230 {
231     return hostInput() && hostInput()->isDisabledFormControl();
232 }
233
234 bool SliderThumbElement::matchesReadOnlyPseudoClass() const
235 {
236     return hostInput() && hostInput()->matchesReadOnlyPseudoClass();
237 }
238
239 bool SliderThumbElement::matchesReadWritePseudoClass() const
240 {
241     return hostInput() && hostInput()->matchesReadWritePseudoClass();
242 }
243
244 Node* SliderThumbElement::focusDelegate()
245 {
246     return hostInput();
247 }
248
249 void SliderThumbElement::dragFrom(const LayoutPoint& point)
250 {
251     RefPtr<SliderThumbElement> protector(this);
252     startDragging();
253     setPositionFromPoint(point);
254 }
255
256 void SliderThumbElement::setPositionFromPoint(const LayoutPoint& point)
257 {
258     RefPtr<HTMLInputElement> input(hostInput());
259     Element* trackElement = input->userAgentShadowRoot()->getElementById(ShadowElementNames::sliderTrack());
260
261     if (!input->renderer() || !renderBox() || !trackElement->renderBox())
262         return;
263
264     LayoutPoint offset = roundedLayoutPoint(input->renderer()->absoluteToLocal(point, UseTransforms));
265     bool isVertical = hasVerticalAppearance(input.get());
266     bool isLeftToRightDirection = renderBox()->style()->isLeftToRightDirection();
267     LayoutUnit trackSize;
268     LayoutUnit position;
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
272     // y() are unusable.
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();
278     if (isVertical) {
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();
282     } else {
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();
287     }
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));
293
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)
301             value = closest;
302     }
303
304     String valueString = serializeForNumberType(value);
305     if (valueString == input->value())
306         return;
307
308     // FIXME: This is no longer being set from renderer. Consider updating the method name.
309     input->setValueFromRenderer(valueString);
310     if (renderer())
311         renderer()->setNeedsLayout();
312 }
313
314 void SliderThumbElement::startDragging()
315 {
316     if (LocalFrame* frame = document().frame()) {
317         frame->eventHandler().setCapturingMouseEventsNode(this);
318         m_inDragMode = true;
319     }
320 }
321
322 void SliderThumbElement::stopDragging()
323 {
324     if (!m_inDragMode)
325         return;
326
327     if (LocalFrame* frame = document().frame())
328         frame->eventHandler().setCapturingMouseEventsNode(nullptr);
329     m_inDragMode = false;
330     if (renderer())
331         renderer()->setNeedsLayout();
332     if (hostInput())
333         hostInput()->dispatchFormControlChangeEvent();
334 }
335
336 void SliderThumbElement::defaultEventHandler(Event* event)
337 {
338     if (!event->isMouseEvent()) {
339         HTMLDivElement::defaultEventHandler(event);
340         return;
341     }
342
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()) {
347         stopDragging();
348         HTMLDivElement::defaultEventHandler(event);
349         return;
350     }
351
352     MouseEvent* mouseEvent = toMouseEvent(event);
353     bool isLeftButton = mouseEvent->button() == LeftButton;
354     const AtomicString& eventType = event->type();
355
356     // We intentionally do not call event->setDefaultHandled() here because
357     // MediaControlTimelineElement::defaultEventHandler() wants to handle these
358     // mouse events.
359     if (eventType == EventTypeNames::mousedown && isLeftButton) {
360         startDragging();
361         return;
362     } else if (eventType == EventTypeNames::mouseup && isLeftButton) {
363         stopDragging();
364         return;
365     } else if (eventType == EventTypeNames::mousemove) {
366         if (m_inDragMode)
367             setPositionFromPoint(mouseEvent->absoluteLocation());
368         return;
369     }
370
371     HTMLDivElement::defaultEventHandler(event);
372 }
373
374 bool SliderThumbElement::willRespondToMouseMoveEvents()
375 {
376     const HTMLInputElement* input = hostInput();
377     if (input && !input->isDisabledOrReadOnly() && m_inDragMode)
378         return true;
379
380     return HTMLDivElement::willRespondToMouseMoveEvents();
381 }
382
383 bool SliderThumbElement::willRespondToMouseClickEvents()
384 {
385     const HTMLInputElement* input = hostInput();
386     if (input && !input->isDisabledOrReadOnly())
387         return true;
388
389     return HTMLDivElement::willRespondToMouseClickEvents();
390 }
391
392 void SliderThumbElement::detach(const AttachContext& context)
393 {
394     if (m_inDragMode) {
395         if (LocalFrame* frame = document().frame())
396             frame->eventHandler().setCapturingMouseEventsNode(nullptr);
397     }
398     HTMLDivElement::detach(context);
399 }
400
401 HTMLInputElement* SliderThumbElement::hostInput() const
402 {
403     // Only HTMLInputElement creates SliderThumbElement instances as its shadow nodes.
404     // So, shadowHost() must be an HTMLInputElement.
405     return toHTMLInputElement(shadowHost());
406 }
407
408 static const AtomicString& sliderThumbShadowPartId()
409 {
410     DEFINE_STATIC_LOCAL(const AtomicString, sliderThumb, ("-webkit-slider-thumb", AtomicString::ConstructFromLiteral));
411     return sliderThumb;
412 }
413
414 static const AtomicString& mediaSliderThumbShadowPartId()
415 {
416     DEFINE_STATIC_LOCAL(const AtomicString, mediaSliderThumb, ("-webkit-media-slider-thumb", AtomicString::ConstructFromLiteral));
417     return mediaSliderThumb;
418 }
419
420 const AtomicString& SliderThumbElement::shadowPseudoId() const
421 {
422     HTMLInputElement* input = hostInput();
423     if (!input || !input->renderer())
424         return sliderThumbShadowPartId();
425
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();
435     default:
436         return sliderThumbShadowPartId();
437     }
438 }
439
440 // --------------------------------
441
442 inline SliderContainerElement::SliderContainerElement(Document& document)
443     : HTMLDivElement(document)
444 {
445 }
446
447 PassRefPtrWillBeRawPtr<SliderContainerElement> SliderContainerElement::create(Document& document)
448 {
449     return adoptRefWillBeRefCountedGarbageCollected(new SliderContainerElement(document));
450 }
451
452 RenderObject* SliderContainerElement::createRenderer(RenderStyle*)
453 {
454     return new RenderSliderContainer(this);
455 }
456
457 const AtomicString& SliderContainerElement::shadowPseudoId() const
458 {
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));
461
462     if (!shadowHost() || !shadowHost()->renderer())
463         return sliderContainer;
464
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;
474     default:
475         return sliderContainer;
476     }
477 }
478
479 }