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/NumberInputType.h"
35 #include "HTMLNames.h"
36 #include "InputTypeNames.h"
37 #include "bindings/v8/ExceptionState.h"
38 #include "core/dom/ExceptionCode.h"
39 #include "core/events/KeyboardEvent.h"
40 #include "core/html/HTMLInputElement.h"
41 #include "core/html/parser/HTMLParserIdioms.h"
42 #include "core/rendering/RenderTextControl.h"
43 #include "platform/text/PlatformLocale.h"
44 #include "wtf/MathExtras.h"
45 #include "wtf/PassOwnPtr.h"
50 using blink::WebLocalizedString;
51 using namespace HTMLNames;
54 static const int numberDefaultStep = 1;
55 static const int numberDefaultStepBase = 0;
56 static const int numberStepScaleFactor = 1;
58 struct RealNumberRenderSize {
59 unsigned sizeBeforeDecimalPoint;
60 unsigned sizeAfteDecimalPoint;
62 RealNumberRenderSize(unsigned before, unsigned after)
63 : sizeBeforeDecimalPoint(before)
64 , sizeAfteDecimalPoint(after)
68 RealNumberRenderSize max(const RealNumberRenderSize& other) const
70 return RealNumberRenderSize(
71 std::max(sizeBeforeDecimalPoint, other.sizeBeforeDecimalPoint),
72 std::max(sizeAfteDecimalPoint, other.sizeAfteDecimalPoint));
76 static RealNumberRenderSize calculateRenderSize(const Decimal& value)
78 ASSERT(value.isFinite());
79 const unsigned sizeOfDigits = String::number(value.value().coefficient()).length();
80 const unsigned sizeOfSign = value.isNegative() ? 1 : 0;
81 const int exponent = value.exponent();
83 return RealNumberRenderSize(sizeOfSign + sizeOfDigits, 0);
85 const int sizeBeforeDecimalPoint = exponent + sizeOfDigits;
86 if (sizeBeforeDecimalPoint > 0) {
87 // In case of "123.456"
88 return RealNumberRenderSize(sizeOfSign + sizeBeforeDecimalPoint, sizeOfDigits - sizeBeforeDecimalPoint);
91 // In case of "0.00012345"
92 const unsigned sizeOfZero = 1;
93 const unsigned numberOfZeroAfterDecimalPoint = -sizeBeforeDecimalPoint;
94 return RealNumberRenderSize(sizeOfSign + sizeOfZero , numberOfZeroAfterDecimalPoint + sizeOfDigits);
97 PassRefPtr<InputType> NumberInputType::create(HTMLInputElement& element)
99 return adoptRef(new NumberInputType(element));
102 void NumberInputType::countUsage()
104 countUsageIfVisible(UseCounter::InputTypeNumber);
107 const AtomicString& NumberInputType::formControlType() const
109 return InputTypeNames::number;
112 void NumberInputType::setValue(const String& sanitizedValue, bool valueChanged, TextFieldEventBehavior eventBehavior)
114 if (!valueChanged && sanitizedValue.isEmpty() && !element().innerTextValue().isEmpty())
115 element().updateView();
116 TextFieldInputType::setValue(sanitizedValue, valueChanged, eventBehavior);
119 double NumberInputType::valueAsDouble() const
121 return parseToDoubleForNumberType(element().value());
124 void NumberInputType::setValueAsDouble(double newValue, TextFieldEventBehavior eventBehavior, ExceptionState& exceptionState) const
126 // FIXME: We should use numeric_limits<double>::max for number input type.
127 // (NOTE: the range check will not be true for NaN.)
128 const double floatMax = numeric_limits<float>::max();
129 if (newValue < -floatMax || newValue > floatMax) {
130 exceptionState.throwDOMException(InvalidStateError, "The value provided (" + String::number(newValue) + ") is outside the range (" + String::number(-floatMax) + ", " + String::number(floatMax) + ").");
133 element().setValue(serializeForNumberType(newValue), eventBehavior);
136 void NumberInputType::setValueAsDecimal(const Decimal& newValue, TextFieldEventBehavior eventBehavior, ExceptionState& exceptionState) const
138 // FIXME: We should use numeric_limits<double>::max for number input type.
139 const Decimal floatMax = Decimal::fromDouble(numeric_limits<float>::max());
140 if (newValue < -floatMax || newValue > floatMax) {
141 exceptionState.throwDOMException(InvalidStateError, "The value provided (" + newValue.toString() + ") is outside the range (-" + floatMax.toString() + ", " + floatMax.toString() + ").");
144 element().setValue(serializeForNumberType(newValue), eventBehavior);
147 bool NumberInputType::typeMismatchFor(const String& value) const
149 return !value.isEmpty() && !std::isfinite(parseToDoubleForNumberType(value));
152 bool NumberInputType::typeMismatch() const
154 ASSERT(!typeMismatchFor(element().value()));
158 StepRange NumberInputType::createStepRange(AnyStepHandling anyStepHandling) const
160 DEFINE_STATIC_LOCAL(const StepRange::StepDescription, stepDescription, (numberDefaultStep, numberDefaultStepBase, numberStepScaleFactor));
162 // FIXME: We should use numeric_limits<double>::max for number input type.
163 const Decimal floatMax = Decimal::fromDouble(numeric_limits<float>::max());
164 return InputType::createStepRange(anyStepHandling, numberDefaultStepBase, -floatMax, floatMax, stepDescription);
167 bool NumberInputType::sizeShouldIncludeDecoration(int defaultSize, int& preferredSize) const
169 preferredSize = defaultSize;
171 const String stepString = element().fastGetAttribute(stepAttr);
172 if (equalIgnoringCase(stepString, "any"))
175 const Decimal minimum = parseToDecimalForNumberType(element().fastGetAttribute(minAttr));
176 if (!minimum.isFinite())
179 const Decimal maximum = parseToDecimalForNumberType(element().fastGetAttribute(maxAttr));
180 if (!maximum.isFinite())
183 const Decimal step = parseToDecimalForNumberType(stepString, 1);
184 ASSERT(step.isFinite());
186 RealNumberRenderSize size = calculateRenderSize(minimum).max(calculateRenderSize(maximum).max(calculateRenderSize(step)));
188 preferredSize = size.sizeBeforeDecimalPoint + size.sizeAfteDecimalPoint + (size.sizeAfteDecimalPoint ? 1 : 0);
193 bool NumberInputType::isSteppable() const
198 void NumberInputType::handleKeydownEvent(KeyboardEvent* event)
200 handleKeydownEventForSpinButton(event);
201 if (!event->defaultHandled())
202 TextFieldInputType::handleKeydownEvent(event);
205 Decimal NumberInputType::parseToNumber(const String& src, const Decimal& defaultValue) const
207 return parseToDecimalForNumberType(src, defaultValue);
210 String NumberInputType::serialize(const Decimal& value) const
212 if (!value.isFinite())
214 return serializeForNumberType(value);
217 static bool isE(UChar ch)
219 return ch == 'e' || ch == 'E';
222 String NumberInputType::localizeValue(const String& proposedValue) const
224 if (proposedValue.isEmpty())
225 return proposedValue;
226 // We don't localize scientific notations.
227 if (proposedValue.find(isE) != kNotFound)
228 return proposedValue;
229 return element().locale().convertToLocalizedNumber(proposedValue);
232 String NumberInputType::visibleValue() const
234 return localizeValue(element().value());
237 String NumberInputType::convertFromVisibleValue(const String& visibleValue) const
239 if (visibleValue.isEmpty())
241 // We don't localize scientific notations.
242 if (visibleValue.find(isE) != kNotFound)
244 return element().locale().convertFromLocalizedNumber(visibleValue);
247 String NumberInputType::sanitizeValue(const String& proposedValue) const
249 if (proposedValue.isEmpty())
250 return proposedValue;
251 return std::isfinite(parseToDoubleForNumberType(proposedValue)) ? proposedValue : emptyString();
254 bool NumberInputType::hasBadInput() const
256 String standardValue = convertFromVisibleValue(element().innerTextValue());
257 return !standardValue.isEmpty() && !std::isfinite(parseToDoubleForNumberType(standardValue));
260 String NumberInputType::badInputText() const
262 return locale().queryString(WebLocalizedString::ValidationBadInputForNumber);
265 String NumberInputType::rangeOverflowText(const Decimal& maximum) const
267 return locale().queryString(WebLocalizedString::ValidationRangeOverflow, localizeValue(serialize(maximum)));
270 String NumberInputType::rangeUnderflowText(const Decimal& minimum) const
272 return locale().queryString(WebLocalizedString::ValidationRangeUnderflow, localizeValue(serialize(minimum)));
275 bool NumberInputType::shouldRespectSpeechAttribute()
280 bool NumberInputType::supportsPlaceholder() const
285 bool NumberInputType::isNumberField() const
290 void NumberInputType::minOrMaxAttributeChanged()
292 InputType::minOrMaxAttributeChanged();
294 if (element().renderer())
295 element().renderer()->setNeedsLayoutAndPrefWidthsRecalc();
298 void NumberInputType::stepAttributeChanged()
300 InputType::stepAttributeChanged();
302 if (element().renderer())
303 element().renderer()->setNeedsLayoutAndPrefWidthsRecalc();
306 bool NumberInputType::supportsSelectionAPI() const
311 } // namespace WebCore