Upstream version 6.35.121.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         RenderBox::computeLogicalHeight(trackHeight, logicalTop, computedValues);
132         return;
133     }
134     if (isVertical)
135         logicalHeight = RenderSlider::defaultTrackLength;
136     RenderBox::computeLogicalHeight(logicalHeight, logicalTop, computedValues);
137 }
138
139 void RenderSliderContainer::layout()
140 {
141     HTMLInputElement* input = toHTMLInputElement(node()->shadowHost());
142     bool isVertical = hasVerticalAppearance(input);
143     style()->setFlexDirection(isVertical ? FlowColumn : FlowRow);
144     TextDirection oldTextDirection = style()->direction();
145     if (isVertical) {
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);
150     }
151
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;
156
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.
160     if (track)
161         layoutScope.setChildNeedsLayout(track);
162
163     RenderFlexibleBox::layout();
164
165     style()->setDirection(oldTextDirection);
166     // These should always exist, unless someone mutates the shadow DOM (e.g., in the inspector).
167     if (!thumb || !track)
168         return;
169
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();
175     if (isVertical)
176         thumbLocation.setY(thumbLocation.y() + track->contentHeight() - thumb->height() - offset);
177     else if (style()->isLeftToRightDirection())
178         thumbLocation.setX(thumbLocation.x() + offset);
179     else
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.
189         repaint();
190     }
191 }
192
193 // --------------------------------
194
195 inline SliderThumbElement::SliderThumbElement(Document& document)
196     : HTMLDivElement(document)
197     , m_inDragMode(false)
198 {
199 }
200
201 PassRefPtr<SliderThumbElement> SliderThumbElement::create(Document& document)
202 {
203     RefPtr<SliderThumbElement> element = adoptRef(new SliderThumbElement(document));
204     element->setAttribute(idAttr, ShadowElementNames::sliderThumb());
205     return element.release();
206 }
207
208 void SliderThumbElement::setPositionFromValue()
209 {
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.
213     if (renderer())
214         renderer()->setNeedsLayout();
215 }
216
217 RenderObject* SliderThumbElement::createRenderer(RenderStyle*)
218 {
219     return new RenderSliderThumb(this);
220 }
221
222 bool SliderThumbElement::isDisabledFormControl() const
223 {
224     return hostInput() && hostInput()->isDisabledFormControl();
225 }
226
227 bool SliderThumbElement::matchesReadOnlyPseudoClass() const
228 {
229     return hostInput() && hostInput()->matchesReadOnlyPseudoClass();
230 }
231
232 bool SliderThumbElement::matchesReadWritePseudoClass() const
233 {
234     return hostInput() && hostInput()->matchesReadWritePseudoClass();
235 }
236
237 Node* SliderThumbElement::focusDelegate()
238 {
239     return hostInput();
240 }
241
242 void SliderThumbElement::dragFrom(const LayoutPoint& point)
243 {
244     RefPtr<SliderThumbElement> protector(this);
245     startDragging();
246     setPositionFromPoint(point);
247 }
248
249 void SliderThumbElement::setPositionFromPoint(const LayoutPoint& point)
250 {
251     RefPtr<HTMLInputElement> input(hostInput());
252     Element* trackElement = input->userAgentShadowRoot()->getElementById(ShadowElementNames::sliderTrack());
253
254     if (!input->renderer() || !renderBox() || !trackElement->renderBox())
255         return;
256
257     LayoutPoint offset = roundedLayoutPoint(input->renderer()->absoluteToLocal(point, UseTransforms));
258     bool isVertical = hasVerticalAppearance(input.get());
259     bool isLeftToRightDirection = renderBox()->style()->isLeftToRightDirection();
260     LayoutUnit trackSize;
261     LayoutUnit position;
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
265     // y() are unusable.
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();
271     if (isVertical) {
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();
275     } else {
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();
280     }
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));
286
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)
294             value = closest;
295     }
296
297     String valueString = serializeForNumberType(value);
298     if (valueString == input->value())
299         return;
300
301     // FIXME: This is no longer being set from renderer. Consider updating the method name.
302     input->setValueFromRenderer(valueString);
303     if (renderer())
304         renderer()->setNeedsLayout();
305 }
306
307 void SliderThumbElement::startDragging()
308 {
309     if (LocalFrame* frame = document().frame()) {
310         frame->eventHandler().setCapturingMouseEventsNode(this);
311         m_inDragMode = true;
312     }
313 }
314
315 void SliderThumbElement::stopDragging()
316 {
317     if (!m_inDragMode)
318         return;
319
320     if (LocalFrame* frame = document().frame())
321         frame->eventHandler().setCapturingMouseEventsNode(nullptr);
322     m_inDragMode = false;
323     if (renderer())
324         renderer()->setNeedsLayout();
325     if (hostInput())
326         hostInput()->dispatchFormControlChangeEvent();
327 }
328
329 void SliderThumbElement::defaultEventHandler(Event* event)
330 {
331     if (!event->isMouseEvent()) {
332         HTMLDivElement::defaultEventHandler(event);
333         return;
334     }
335
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()) {
340         stopDragging();
341         HTMLDivElement::defaultEventHandler(event);
342         return;
343     }
344
345     MouseEvent* mouseEvent = toMouseEvent(event);
346     bool isLeftButton = mouseEvent->button() == LeftButton;
347     const AtomicString& eventType = event->type();
348
349     // We intentionally do not call event->setDefaultHandled() here because
350     // MediaControlTimelineElement::defaultEventHandler() wants to handle these
351     // mouse events.
352     if (eventType == EventTypeNames::mousedown && isLeftButton) {
353         startDragging();
354         return;
355     } else if (eventType == EventTypeNames::mouseup && isLeftButton) {
356         stopDragging();
357         return;
358     } else if (eventType == EventTypeNames::mousemove) {
359         if (m_inDragMode)
360             setPositionFromPoint(mouseEvent->absoluteLocation());
361         return;
362     }
363
364     HTMLDivElement::defaultEventHandler(event);
365 }
366
367 bool SliderThumbElement::willRespondToMouseMoveEvents()
368 {
369     const HTMLInputElement* input = hostInput();
370     if (input && !input->isDisabledOrReadOnly() && m_inDragMode)
371         return true;
372
373     return HTMLDivElement::willRespondToMouseMoveEvents();
374 }
375
376 bool SliderThumbElement::willRespondToMouseClickEvents()
377 {
378     const HTMLInputElement* input = hostInput();
379     if (input && !input->isDisabledOrReadOnly())
380         return true;
381
382     return HTMLDivElement::willRespondToMouseClickEvents();
383 }
384
385 void SliderThumbElement::detach(const AttachContext& context)
386 {
387     if (m_inDragMode) {
388         if (LocalFrame* frame = document().frame())
389             frame->eventHandler().setCapturingMouseEventsNode(nullptr);
390     }
391     HTMLDivElement::detach(context);
392 }
393
394 HTMLInputElement* SliderThumbElement::hostInput() const
395 {
396     // Only HTMLInputElement creates SliderThumbElement instances as its shadow nodes.
397     // So, shadowHost() must be an HTMLInputElement.
398     return toHTMLInputElement(shadowHost());
399 }
400
401 static const AtomicString& sliderThumbShadowPartId()
402 {
403     DEFINE_STATIC_LOCAL(const AtomicString, sliderThumb, ("-webkit-slider-thumb", AtomicString::ConstructFromLiteral));
404     return sliderThumb;
405 }
406
407 static const AtomicString& mediaSliderThumbShadowPartId()
408 {
409     DEFINE_STATIC_LOCAL(const AtomicString, mediaSliderThumb, ("-webkit-media-slider-thumb", AtomicString::ConstructFromLiteral));
410     return mediaSliderThumb;
411 }
412
413 const AtomicString& SliderThumbElement::shadowPseudoId() const
414 {
415     HTMLInputElement* input = hostInput();
416     if (!input || !input->renderer())
417         return sliderThumbShadowPartId();
418
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();
428     default:
429         return sliderThumbShadowPartId();
430     }
431 }
432
433 // --------------------------------
434
435 inline SliderContainerElement::SliderContainerElement(Document& document)
436     : HTMLDivElement(document)
437 {
438 }
439
440 PassRefPtr<SliderContainerElement> SliderContainerElement::create(Document& document)
441 {
442     return adoptRef(new SliderContainerElement(document));
443 }
444
445 RenderObject* SliderContainerElement::createRenderer(RenderStyle*)
446 {
447     return new RenderSliderContainer(this);
448 }
449
450 const AtomicString& SliderContainerElement::shadowPseudoId() const
451 {
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));
454
455     if (!shadowHost() || !shadowHost()->renderer())
456         return sliderContainer;
457
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;
467     default:
468         return sliderContainer;
469     }
470 }
471
472 }