2 * Copyright (C) 2010 Google Inc. All rights reserved.
3 * Copyright (C) 2011 Apple 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.
33 #include "core/html/forms/RangeInputType.h"
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"
63 using namespace HTMLNames;
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;
72 static Decimal ensureMaximum(const Decimal& proposedValue, const Decimal& minimum, const Decimal& fallbackValue)
74 return proposedValue >= minimum ? proposedValue : std::max(minimum, fallbackValue);
77 PassRefPtr<InputType> RangeInputType::create(HTMLInputElement& element)
79 return adoptRef(new RangeInputType(element));
82 RangeInputType::RangeInputType(HTMLInputElement& element)
84 , m_tickMarkValuesDirty(true)
88 void RangeInputType::countUsage()
90 countUsageIfVisible(UseCounter::InputTypeRange);
93 bool RangeInputType::isRangeControl() const
98 const AtomicString& RangeInputType::formControlType() const
100 return InputTypeNames::range;
103 double RangeInputType::valueAsDouble() const
105 return parseToDoubleForNumberType(element().value());
108 void RangeInputType::setValueAsDouble(double newValue, TextFieldEventBehavior eventBehavior, ExceptionState& exceptionState) const
110 setValueAsDecimal(Decimal::fromDouble(newValue), eventBehavior, exceptionState);
113 bool RangeInputType::typeMismatchFor(const String& value) const
115 return !value.isEmpty() && !std::isfinite(parseToDoubleForNumberType(value));
118 bool RangeInputType::supportsRequired() const
123 StepRange RangeInputType::createStepRange(AnyStepHandling anyStepHandling) const
125 DEFINE_STATIC_LOCAL(const StepRange::StepDescription, stepDescription, (rangeDefaultStep, rangeDefaultStepBase, rangeStepScaleFactor));
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);
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);
137 const Decimal step = StepRange::parseStep(anyStepHandling, stepDescription, element().fastGetAttribute(stepAttr));
138 return StepRange(stepBase, minimum, maximum, step, stepDescription);
141 bool RangeInputType::isSteppable() const
146 void RangeInputType::handleMouseDownEvent(MouseEvent* event)
148 if (element().isDisabledOrReadOnly())
151 Node* targetNode = event->target()->toNode();
152 if (event->button() != LeftButton || !targetNode)
154 ASSERT(element().shadow());
155 if (targetNode != element() && !targetNode->isDescendantOf(element().userAgentShadowRoot()))
157 SliderThumbElement* thumb = sliderThumbElement();
158 if (targetNode == thumb)
160 thumb->dragFrom(event->absoluteLocation());
163 void RangeInputType::handleTouchEvent(TouchEvent* event)
165 if (element().isDisabledOrReadOnly())
168 if (event->type() == EventTypeNames::touchend) {
169 element().dispatchFormControlChangeEvent();
170 event->setDefaultHandled();
174 TouchList* touches = event->targetTouches();
175 if (touches->length() == 1) {
176 sliderThumbElement()->setPositionFromPoint(touches->item(0)->absoluteLocation());
177 event->setDefaultHandled();
181 bool RangeInputType::hasTouchEventHandler() const
186 void RangeInputType::handleKeydownEvent(KeyboardEvent* event)
188 if (element().isDisabledOrReadOnly())
191 const String& key = event->keyIdentifier();
193 const Decimal current = parseToNumberOrNaN(element().value());
194 ASSERT(current.isFinite());
196 StepRange stepRange(createStepRange(RejectAny));
199 // FIXME: We can't use stepUp() for the step value "any". So, we increase
200 // or decrease the value by 1/100 of the value range. Is it reasonable?
201 const Decimal step = equalIgnoringCase(element().fastGetAttribute(stepAttr), "any") ? (stepRange.maximum() - stepRange.minimum()) / 100 : stepRange.step();
202 const Decimal bigStep = max((stepRange.maximum() - stepRange.minimum()) / 10, step);
204 bool isVertical = false;
205 if (element().renderer()) {
206 ControlPart part = element().renderer()->style()->appearance();
207 isVertical = part == SliderVerticalPart || part == MediaVolumeSliderPart;
212 newValue = current + step;
213 else if (key == "Down")
214 newValue = current - step;
215 else if (key == "Left")
216 newValue = isVertical ? current + step : current - step;
217 else if (key == "Right")
218 newValue = isVertical ? current - step : current + step;
219 else if (key == "PageUp")
220 newValue = current + bigStep;
221 else if (key == "PageDown")
222 newValue = current - bigStep;
223 else if (key == "Home")
224 newValue = isVertical ? stepRange.maximum() : stepRange.minimum();
225 else if (key == "End")
226 newValue = isVertical ? stepRange.minimum() : stepRange.maximum();
228 return; // Did not match any key binding.
230 newValue = stepRange.clampValue(newValue);
232 if (newValue != current) {
233 EventQueueScope scope;
234 TextFieldEventBehavior eventBehavior = DispatchInputAndChangeEvent;
235 setValueAsDecimal(newValue, eventBehavior, IGNORE_EXCEPTION);
237 if (AXObjectCache* cache = element().document().existingAXObjectCache())
238 cache->postNotification(&element(), AXObjectCache::AXValueChanged, true);
241 event->setDefaultHandled();
244 void RangeInputType::createShadowSubtree()
246 ASSERT(element().shadow());
248 Document& document = element().document();
249 RefPtr<HTMLDivElement> track = HTMLDivElement::create(document);
250 track->setShadowPseudoId(AtomicString("-webkit-slider-runnable-track", AtomicString::ConstructFromLiteral));
251 track->setAttribute(idAttr, ShadowElementNames::sliderTrack());
252 track->appendChild(SliderThumbElement::create(document));
253 RefPtr<HTMLElement> container = SliderContainerElement::create(document);
254 container->appendChild(track.release());
255 element().userAgentShadowRoot()->appendChild(container.release());
258 RenderObject* RangeInputType::createRenderer(RenderStyle*) const
260 return new RenderSlider(&element());
263 Decimal RangeInputType::parseToNumber(const String& src, const Decimal& defaultValue) const
265 return parseToDecimalForNumberType(src, defaultValue);
268 String RangeInputType::serialize(const Decimal& value) const
270 if (!value.isFinite())
272 return serializeForNumberType(value);
275 // FIXME: Could share this with BaseClickableWithKeyInputType and BaseCheckableInputType if we had a common base class.
276 void RangeInputType::accessKeyAction(bool sendMouseEvents)
278 InputType::accessKeyAction(sendMouseEvents);
280 element().dispatchSimulatedClick(0, sendMouseEvents ? SendMouseUpDownEvents : SendNoEvents);
283 void RangeInputType::sanitizeValueInResponseToMinOrMaxAttributeChange()
285 if (element().hasDirtyValue())
286 element().setValue(element().value());
288 sliderThumbElement()->setPositionFromValue();
291 void RangeInputType::setValue(const String& value, bool valueChanged, TextFieldEventBehavior eventBehavior)
293 InputType::setValue(value, valueChanged, eventBehavior);
298 sliderThumbElement()->setPositionFromValue();
301 String RangeInputType::fallbackValue() const
303 return serializeForNumberType(createStepRange(RejectAny).defaultValue());
306 String RangeInputType::sanitizeValue(const String& proposedValue) const
308 StepRange stepRange(createStepRange(RejectAny));
309 const Decimal proposedNumericValue = parseToNumber(proposedValue, stepRange.defaultValue());
310 return serializeForNumberType(stepRange.clampValue(proposedNumericValue));
313 void RangeInputType::disabledAttributeChanged()
315 if (element().isDisabledFormControl())
316 sliderThumbElement()->stopDragging();
319 bool RangeInputType::shouldRespectListAttribute()
324 inline SliderThumbElement* RangeInputType::sliderThumbElement() const
326 return toSliderThumbElement(element().userAgentShadowRoot()->getElementById(ShadowElementNames::sliderThumb()));
329 inline Element* RangeInputType::sliderTrackElement() const
331 return element().userAgentShadowRoot()->getElementById(ShadowElementNames::sliderTrack());
334 void RangeInputType::listAttributeTargetChanged()
336 m_tickMarkValuesDirty = true;
337 Element* sliderTrackElement = this->sliderTrackElement();
338 if (sliderTrackElement->renderer())
339 sliderTrackElement->renderer()->setNeedsLayout();
342 static bool decimalCompare(const Decimal& a, const Decimal& b)
347 void RangeInputType::updateTickMarkValues()
349 if (!m_tickMarkValuesDirty)
351 m_tickMarkValues.clear();
352 m_tickMarkValuesDirty = false;
353 HTMLDataListElement* dataList = element().dataList();
356 RefPtr<HTMLCollection> options = dataList->options();
357 m_tickMarkValues.reserveCapacity(options->length());
358 for (unsigned i = 0; i < options->length(); ++i) {
359 Element* element = options->item(i);
360 HTMLOptionElement* optionElement = toHTMLOptionElement(element);
361 String optionValue = optionElement->value();
362 if (!this->element().isValidValue(optionValue))
364 m_tickMarkValues.append(parseToNumber(optionValue, Decimal::nan()));
366 m_tickMarkValues.shrinkToFit();
367 nonCopyingSort(m_tickMarkValues.begin(), m_tickMarkValues.end(), decimalCompare);
370 Decimal RangeInputType::findClosestTickMarkValue(const Decimal& value)
372 updateTickMarkValues();
373 if (!m_tickMarkValues.size())
374 return Decimal::nan();
377 size_t right = m_tickMarkValues.size();
380 ASSERT(left <= right);
381 middle = left + (right - left) / 2;
384 if (middle == m_tickMarkValues.size() - 1 && m_tickMarkValues[middle] < value) {
388 if (m_tickMarkValues[middle - 1] <= value && m_tickMarkValues[middle] >= value)
391 if (m_tickMarkValues[middle] < value)
396 const Decimal closestLeft = middle ? m_tickMarkValues[middle - 1] : Decimal::infinity(Decimal::Negative);
397 const Decimal closestRight = middle != m_tickMarkValues.size() ? m_tickMarkValues[middle] : Decimal::infinity(Decimal::Positive);
398 if (closestRight - value < value - closestLeft)
403 } // namespace WebCore