557fb82dbab496b252ec7f6d99e285e9bad5bad8
[platform/framework/web/crosswalk.git] / src / third_party / WebKit / Source / core / html / forms / RangeInputType.cpp
1 /*
2  * Copyright (C) 2010 Google Inc. All rights reserved.
3  * Copyright (C) 2011 Apple 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 #include "config.h"
33 #include "core/html/forms/RangeInputType.h"
34
35 #include "HTMLNames.h"
36 #include "InputTypeNames.h"
37 #include "bindings/v8/ExceptionStatePlaceholder.h"
38 #include "core/accessibility/AXObjectCache.h"
39 #include "core/events/KeyboardEvent.h"
40 #include "core/events/MouseEvent.h"
41 #include "core/events/ScopedEventQueue.h"
42 #include "core/dom/Touch.h"
43 #include "core/events/TouchEvent.h"
44 #include "core/dom/TouchList.h"
45 #include "core/dom/shadow/ShadowRoot.h"
46 #include "core/html/HTMLDataListElement.h"
47 #include "core/html/HTMLDivElement.h"
48 #include "core/html/HTMLInputElement.h"
49 #include "core/html/HTMLOptionElement.h"
50 #include "core/html/forms/StepRange.h"
51 #include "core/html/parser/HTMLParserIdioms.h"
52 #include "core/html/shadow/ShadowElementNames.h"
53 #include "core/html/shadow/SliderThumbElement.h"
54 #include "core/rendering/RenderSlider.h"
55 #include "platform/PlatformMouseEvent.h"
56 #include "wtf/MathExtras.h"
57 #include "wtf/NonCopyingSort.h"
58 #include "wtf/PassOwnPtr.h"
59 #include <limits>
60
61 namespace WebCore {
62
63 using namespace HTMLNames;
64 using namespace std;
65
66 static const int rangeDefaultMinimum = 0;
67 static const int rangeDefaultMaximum = 100;
68 static const int rangeDefaultStep = 1;
69 static const int rangeDefaultStepBase = 0;
70 static const int rangeStepScaleFactor = 1;
71
72 static Decimal ensureMaximum(const Decimal& proposedValue, const Decimal& minimum, const Decimal& fallbackValue)
73 {
74     return proposedValue >= minimum ? proposedValue : std::max(minimum, fallbackValue);
75 }
76
77 PassRefPtr<InputType> RangeInputType::create(HTMLInputElement& element)
78 {
79     return adoptRef(new RangeInputType(element));
80 }
81
82 RangeInputType::RangeInputType(HTMLInputElement& element)
83     : InputType(element)
84     , m_tickMarkValuesDirty(true)
85 {
86 }
87
88 void RangeInputType::countUsage()
89 {
90     countUsageIfVisible(UseCounter::InputTypeRange);
91 }
92
93 bool RangeInputType::isRangeControl() const
94 {
95     return true;
96 }
97
98 const AtomicString& RangeInputType::formControlType() const
99 {
100     return InputTypeNames::range;
101 }
102
103 double RangeInputType::valueAsDouble() const
104 {
105     return parseToDoubleForNumberType(element().value());
106 }
107
108 void RangeInputType::setValueAsDouble(double newValue, TextFieldEventBehavior eventBehavior, ExceptionState& exceptionState) const
109 {
110     setValueAsDecimal(Decimal::fromDouble(newValue), eventBehavior, exceptionState);
111 }
112
113 bool RangeInputType::typeMismatchFor(const String& value) const
114 {
115     return !value.isEmpty() && !std::isfinite(parseToDoubleForNumberType(value));
116 }
117
118 bool RangeInputType::supportsRequired() const
119 {
120     return false;
121 }
122
123 StepRange RangeInputType::createStepRange(AnyStepHandling anyStepHandling) const
124 {
125     DEFINE_STATIC_LOCAL(const StepRange::StepDescription, stepDescription, (rangeDefaultStep, rangeDefaultStepBase, rangeStepScaleFactor));
126
127     const Decimal stepBase = findStepBase(rangeDefaultStepBase);
128     const Decimal minimum = parseToNumber(element().fastGetAttribute(minAttr), rangeDefaultMinimum);
129     const Decimal maximum = ensureMaximum(parseToNumber(element().fastGetAttribute(maxAttr), rangeDefaultMaximum), minimum, rangeDefaultMaximum);
130
131     const AtomicString& precisionValue = element().fastGetAttribute(precisionAttr);
132     if (!precisionValue.isNull()) {
133         const Decimal step = equalIgnoringCase(precisionValue, "float") ? Decimal::nan() : 1;
134         return StepRange(stepBase, minimum, maximum, step, stepDescription);
135     }
136
137     const Decimal step = StepRange::parseStep(anyStepHandling, stepDescription, element().fastGetAttribute(stepAttr));
138     return StepRange(stepBase, minimum, maximum, step, stepDescription);
139 }
140
141 bool RangeInputType::isSteppable() const
142 {
143     return true;
144 }
145
146 void RangeInputType::handleMouseDownEvent(MouseEvent* event)
147 {
148     if (element().isDisabledOrReadOnly())
149         return;
150
151     Node* targetNode = event->target()->toNode();
152     if (event->button() != LeftButton || !targetNode)
153         return;
154     ASSERT(element().shadow());
155     if (targetNode != element() && !targetNode->isDescendantOf(element().userAgentShadowRoot()))
156         return;
157     SliderThumbElement* thumb = sliderThumbElement();
158     if (targetNode == thumb)
159         return;
160     thumb->dragFrom(event->absoluteLocation());
161 }
162
163 void RangeInputType::handleTouchEvent(TouchEvent* event)
164 {
165     if (element().isDisabledOrReadOnly())
166         return;
167
168     if (event->type() == EventTypeNames::touchend) {
169         event->setDefaultHandled();
170         return;
171     }
172
173     TouchList* touches = event->targetTouches();
174     if (touches->length() == 1) {
175         sliderThumbElement()->setPositionFromPoint(touches->item(0)->absoluteLocation());
176         event->setDefaultHandled();
177     }
178 }
179
180 bool RangeInputType::hasTouchEventHandler() const
181 {
182     return true;
183 }
184
185 void RangeInputType::handleKeydownEvent(KeyboardEvent* event)
186 {
187     if (element().isDisabledOrReadOnly())
188         return;
189
190     const String& key = event->keyIdentifier();
191
192     const Decimal current = parseToNumberOrNaN(element().value());
193     ASSERT(current.isFinite());
194
195     StepRange stepRange(createStepRange(RejectAny));
196
197
198     // FIXME: We can't use stepUp() for the step value "any". So, we increase
199     // or decrease the value by 1/100 of the value range. Is it reasonable?
200     const Decimal step = equalIgnoringCase(element().fastGetAttribute(stepAttr), "any") ? (stepRange.maximum() - stepRange.minimum()) / 100 : stepRange.step();
201     const Decimal bigStep = max((stepRange.maximum() - stepRange.minimum()) / 10, step);
202
203     bool isVertical = false;
204     if (element().renderer()) {
205         ControlPart part = element().renderer()->style()->appearance();
206         isVertical = part == SliderVerticalPart || part == MediaVolumeSliderPart;
207     }
208
209     Decimal newValue;
210     if (key == "Up")
211         newValue = current + step;
212     else if (key == "Down")
213         newValue = current - step;
214     else if (key == "Left")
215         newValue = isVertical ? current + step : current - step;
216     else if (key == "Right")
217         newValue = isVertical ? current - step : current + step;
218     else if (key == "PageUp")
219         newValue = current + bigStep;
220     else if (key == "PageDown")
221         newValue = current - bigStep;
222     else if (key == "Home")
223         newValue = isVertical ? stepRange.maximum() : stepRange.minimum();
224     else if (key == "End")
225         newValue = isVertical ? stepRange.minimum() : stepRange.maximum();
226     else
227         return; // Did not match any key binding.
228
229     newValue = stepRange.clampValue(newValue);
230
231     if (newValue != current) {
232         EventQueueScope scope;
233         TextFieldEventBehavior eventBehavior = DispatchInputAndChangeEvent;
234         setValueAsDecimal(newValue, eventBehavior, IGNORE_EXCEPTION);
235
236         if (AXObjectCache* cache = element().document().existingAXObjectCache())
237             cache->postNotification(&element(), AXObjectCache::AXValueChanged, true);
238     }
239
240     event->setDefaultHandled();
241 }
242
243 void RangeInputType::createShadowSubtree()
244 {
245     ASSERT(element().shadow());
246
247     Document& document = element().document();
248     RefPtr<HTMLDivElement> track = HTMLDivElement::create(document);
249     track->setShadowPseudoId(AtomicString("-webkit-slider-runnable-track", AtomicString::ConstructFromLiteral));
250     track->setAttribute(idAttr, ShadowElementNames::sliderTrack());
251     track->appendChild(SliderThumbElement::create(document));
252     RefPtr<HTMLElement> container = SliderContainerElement::create(document);
253     container->appendChild(track.release());
254     element().userAgentShadowRoot()->appendChild(container.release());
255 }
256
257 RenderObject* RangeInputType::createRenderer(RenderStyle*) const
258 {
259     return new RenderSlider(&element());
260 }
261
262 Decimal RangeInputType::parseToNumber(const String& src, const Decimal& defaultValue) const
263 {
264     return parseToDecimalForNumberType(src, defaultValue);
265 }
266
267 String RangeInputType::serialize(const Decimal& value) const
268 {
269     if (!value.isFinite())
270         return String();
271     return serializeForNumberType(value);
272 }
273
274 // FIXME: Could share this with BaseClickableWithKeyInputType and BaseCheckableInputType if we had a common base class.
275 void RangeInputType::accessKeyAction(bool sendMouseEvents)
276 {
277     InputType::accessKeyAction(sendMouseEvents);
278
279     element().dispatchSimulatedClick(0, sendMouseEvents ? SendMouseUpDownEvents : SendNoEvents);
280 }
281
282 void RangeInputType::sanitizeValueInResponseToMinOrMaxAttributeChange()
283 {
284     if (element().hasDirtyValue())
285         element().setValue(element().value());
286
287     sliderThumbElement()->setPositionFromValue();
288 }
289
290 void RangeInputType::setValue(const String& value, bool valueChanged, TextFieldEventBehavior eventBehavior)
291 {
292     InputType::setValue(value, valueChanged, eventBehavior);
293
294     if (!valueChanged)
295         return;
296
297     sliderThumbElement()->setPositionFromValue();
298 }
299
300 String RangeInputType::fallbackValue() const
301 {
302     return serializeForNumberType(createStepRange(RejectAny).defaultValue());
303 }
304
305 String RangeInputType::sanitizeValue(const String& proposedValue) const
306 {
307     StepRange stepRange(createStepRange(RejectAny));
308     const Decimal proposedNumericValue = parseToNumber(proposedValue, stepRange.defaultValue());
309     return serializeForNumberType(stepRange.clampValue(proposedNumericValue));
310 }
311
312 void RangeInputType::disabledAttributeChanged()
313 {
314     if (element().isDisabledFormControl())
315         sliderThumbElement()->stopDragging();
316 }
317
318 bool RangeInputType::shouldRespectListAttribute()
319 {
320     return true;
321 }
322
323 inline SliderThumbElement* RangeInputType::sliderThumbElement() const
324 {
325     return toSliderThumbElement(element().userAgentShadowRoot()->getElementById(ShadowElementNames::sliderThumb()));
326 }
327
328 inline Element* RangeInputType::sliderTrackElement() const
329 {
330     return element().userAgentShadowRoot()->getElementById(ShadowElementNames::sliderTrack());
331 }
332
333 void RangeInputType::listAttributeTargetChanged()
334 {
335     m_tickMarkValuesDirty = true;
336     Element* sliderTrackElement = this->sliderTrackElement();
337     if (sliderTrackElement->renderer())
338         sliderTrackElement->renderer()->setNeedsLayout();
339 }
340
341 static bool decimalCompare(const Decimal& a, const Decimal& b)
342 {
343     return a < b;
344 }
345
346 void RangeInputType::updateTickMarkValues()
347 {
348     if (!m_tickMarkValuesDirty)
349         return;
350     m_tickMarkValues.clear();
351     m_tickMarkValuesDirty = false;
352     HTMLDataListElement* dataList = element().dataList();
353     if (!dataList)
354         return;
355     RefPtr<HTMLCollection> options = dataList->options();
356     m_tickMarkValues.reserveCapacity(options->length());
357     for (unsigned i = 0; i < options->length(); ++i) {
358         Element* element = options->item(i);
359         HTMLOptionElement* optionElement = toHTMLOptionElement(element);
360         String optionValue = optionElement->value();
361         if (!this->element().isValidValue(optionValue))
362             continue;
363         m_tickMarkValues.append(parseToNumber(optionValue, Decimal::nan()));
364     }
365     m_tickMarkValues.shrinkToFit();
366     nonCopyingSort(m_tickMarkValues.begin(), m_tickMarkValues.end(), decimalCompare);
367 }
368
369 Decimal RangeInputType::findClosestTickMarkValue(const Decimal& value)
370 {
371     updateTickMarkValues();
372     if (!m_tickMarkValues.size())
373         return Decimal::nan();
374
375     size_t left = 0;
376     size_t right = m_tickMarkValues.size();
377     size_t middle;
378     while (true) {
379         ASSERT(left <= right);
380         middle = left + (right - left) / 2;
381         if (!middle)
382             break;
383         if (middle == m_tickMarkValues.size() - 1 && m_tickMarkValues[middle] < value) {
384             middle++;
385             break;
386         }
387         if (m_tickMarkValues[middle - 1] <= value && m_tickMarkValues[middle] >= value)
388             break;
389
390         if (m_tickMarkValues[middle] < value)
391             left = middle;
392         else
393             right = middle;
394     }
395     const Decimal closestLeft = middle ? m_tickMarkValues[middle - 1] : Decimal::infinity(Decimal::Negative);
396     const Decimal closestRight = middle != m_tickMarkValues.size() ? m_tickMarkValues[middle] : Decimal::infinity(Decimal::Positive);
397     if (closestRight - value < value - closestLeft)
398         return closestRight;
399     return closestLeft;
400 }
401
402 } // namespace WebCore