Upstream version 5.34.92.0
[platform/framework/web/crosswalk.git] / src / third_party / WebKit / Source / core / html / forms / NumberInputType.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/NumberInputType.h"
34
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"
46 #include <limits>
47
48 namespace WebCore {
49
50 using blink::WebLocalizedString;
51 using namespace HTMLNames;
52 using namespace std;
53
54 static const int numberDefaultStep = 1;
55 static const int numberDefaultStepBase = 0;
56 static const int numberStepScaleFactor = 1;
57
58 struct RealNumberRenderSize {
59     unsigned sizeBeforeDecimalPoint;
60     unsigned sizeAfteDecimalPoint;
61
62     RealNumberRenderSize(unsigned before, unsigned after)
63         : sizeBeforeDecimalPoint(before)
64         , sizeAfteDecimalPoint(after)
65     {
66     }
67
68     RealNumberRenderSize max(const RealNumberRenderSize& other) const
69     {
70         return RealNumberRenderSize(
71             std::max(sizeBeforeDecimalPoint, other.sizeBeforeDecimalPoint),
72             std::max(sizeAfteDecimalPoint, other.sizeAfteDecimalPoint));
73     }
74 };
75
76 static RealNumberRenderSize calculateRenderSize(const Decimal& value)
77 {
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();
82     if (exponent >= 0)
83         return RealNumberRenderSize(sizeOfSign + sizeOfDigits, 0);
84
85     const int sizeBeforeDecimalPoint = exponent + sizeOfDigits;
86     if (sizeBeforeDecimalPoint > 0) {
87         // In case of "123.456"
88         return RealNumberRenderSize(sizeOfSign + sizeBeforeDecimalPoint, sizeOfDigits - sizeBeforeDecimalPoint);
89     }
90
91     // In case of "0.00012345"
92     const unsigned sizeOfZero = 1;
93     const unsigned numberOfZeroAfterDecimalPoint = -sizeBeforeDecimalPoint;
94     return RealNumberRenderSize(sizeOfSign + sizeOfZero , numberOfZeroAfterDecimalPoint + sizeOfDigits);
95 }
96
97 PassRefPtr<InputType> NumberInputType::create(HTMLInputElement& element)
98 {
99     return adoptRef(new NumberInputType(element));
100 }
101
102 void NumberInputType::countUsage()
103 {
104     countUsageIfVisible(UseCounter::InputTypeNumber);
105 }
106
107 const AtomicString& NumberInputType::formControlType() const
108 {
109     return InputTypeNames::number;
110 }
111
112 void NumberInputType::setValue(const String& sanitizedValue, bool valueChanged, TextFieldEventBehavior eventBehavior)
113 {
114     if (!valueChanged && sanitizedValue.isEmpty() && !element().innerTextValue().isEmpty())
115         updateView();
116     TextFieldInputType::setValue(sanitizedValue, valueChanged, eventBehavior);
117 }
118
119 double NumberInputType::valueAsDouble() const
120 {
121     return parseToDoubleForNumberType(element().value());
122 }
123
124 void NumberInputType::setValueAsDouble(double newValue, TextFieldEventBehavior eventBehavior, ExceptionState& exceptionState) const
125 {
126     // FIXME: We should use numeric_limits<double>::max for number input type.
127     const double floatMax = numeric_limits<float>::max();
128     if (newValue < -floatMax || newValue > floatMax) {
129         exceptionState.throwDOMException(InvalidStateError, "The value provided (" + String::number(newValue) + ") is outside the range (" + String::number(-floatMax) + ", " + String::number(floatMax) + ").");
130         return;
131     }
132     element().setValue(serializeForNumberType(newValue), eventBehavior);
133 }
134
135 void NumberInputType::setValueAsDecimal(const Decimal& newValue, TextFieldEventBehavior eventBehavior, ExceptionState& exceptionState) const
136 {
137     // FIXME: We should use numeric_limits<double>::max for number input type.
138     const Decimal floatMax = Decimal::fromDouble(numeric_limits<float>::max());
139     if (newValue < -floatMax || newValue > floatMax) {
140         exceptionState.throwDOMException(InvalidStateError, "The value provided (" + newValue.toString() + ") is outside the range (-" + floatMax.toString() + ", " + floatMax.toString() + ").");
141         return;
142     }
143     element().setValue(serializeForNumberType(newValue), eventBehavior);
144 }
145
146 bool NumberInputType::typeMismatchFor(const String& value) const
147 {
148     return !value.isEmpty() && !std::isfinite(parseToDoubleForNumberType(value));
149 }
150
151 bool NumberInputType::typeMismatch() const
152 {
153     ASSERT(!typeMismatchFor(element().value()));
154     return false;
155 }
156
157 StepRange NumberInputType::createStepRange(AnyStepHandling anyStepHandling) const
158 {
159     DEFINE_STATIC_LOCAL(const StepRange::StepDescription, stepDescription, (numberDefaultStep, numberDefaultStepBase, numberStepScaleFactor));
160
161     // FIXME: We should use numeric_limits<double>::max for number input type.
162     const Decimal floatMax = Decimal::fromDouble(numeric_limits<float>::max());
163     return InputType::createStepRange(anyStepHandling, numberDefaultStepBase, -floatMax, floatMax, stepDescription);
164 }
165
166 bool NumberInputType::sizeShouldIncludeDecoration(int defaultSize, int& preferredSize) const
167 {
168     preferredSize = defaultSize;
169
170     const String stepString = element().fastGetAttribute(stepAttr);
171     if (equalIgnoringCase(stepString, "any"))
172         return false;
173
174     const Decimal minimum = parseToDecimalForNumberType(element().fastGetAttribute(minAttr));
175     if (!minimum.isFinite())
176         return false;
177
178     const Decimal maximum = parseToDecimalForNumberType(element().fastGetAttribute(maxAttr));
179     if (!maximum.isFinite())
180         return false;
181
182     const Decimal step = parseToDecimalForNumberType(stepString, 1);
183     ASSERT(step.isFinite());
184
185     RealNumberRenderSize size = calculateRenderSize(minimum).max(calculateRenderSize(maximum).max(calculateRenderSize(step)));
186
187     preferredSize = size.sizeBeforeDecimalPoint + size.sizeAfteDecimalPoint + (size.sizeAfteDecimalPoint ? 1 : 0);
188
189     return true;
190 }
191
192 bool NumberInputType::isSteppable() const
193 {
194     return true;
195 }
196
197 void NumberInputType::handleKeydownEvent(KeyboardEvent* event)
198 {
199     handleKeydownEventForSpinButton(event);
200     if (!event->defaultHandled())
201         TextFieldInputType::handleKeydownEvent(event);
202 }
203
204 Decimal NumberInputType::parseToNumber(const String& src, const Decimal& defaultValue) const
205 {
206     return parseToDecimalForNumberType(src, defaultValue);
207 }
208
209 String NumberInputType::serialize(const Decimal& value) const
210 {
211     if (!value.isFinite())
212         return String();
213     return serializeForNumberType(value);
214 }
215
216 static bool isE(UChar ch)
217 {
218     return ch == 'e' || ch == 'E';
219 }
220
221 String NumberInputType::localizeValue(const String& proposedValue) const
222 {
223     if (proposedValue.isEmpty())
224         return proposedValue;
225     // We don't localize scientific notations.
226     if (proposedValue.find(isE) != kNotFound)
227         return proposedValue;
228     return element().locale().convertToLocalizedNumber(proposedValue);
229 }
230
231 String NumberInputType::visibleValue() const
232 {
233     return localizeValue(element().value());
234 }
235
236 String NumberInputType::convertFromVisibleValue(const String& visibleValue) const
237 {
238     if (visibleValue.isEmpty())
239         return visibleValue;
240     // We don't localize scientific notations.
241     if (visibleValue.find(isE) != kNotFound)
242         return visibleValue;
243     return element().locale().convertFromLocalizedNumber(visibleValue);
244 }
245
246 String NumberInputType::sanitizeValue(const String& proposedValue) const
247 {
248     if (proposedValue.isEmpty())
249         return proposedValue;
250     return std::isfinite(parseToDoubleForNumberType(proposedValue)) ? proposedValue : emptyString();
251 }
252
253 bool NumberInputType::hasBadInput() const
254 {
255     String standardValue = convertFromVisibleValue(element().innerTextValue());
256     return !standardValue.isEmpty() && !std::isfinite(parseToDoubleForNumberType(standardValue));
257 }
258
259 String NumberInputType::badInputText() const
260 {
261     return locale().queryString(WebLocalizedString::ValidationBadInputForNumber);
262 }
263
264 String NumberInputType::rangeOverflowText(const Decimal& maximum) const
265 {
266     return locale().queryString(WebLocalizedString::ValidationRangeOverflow, localizeValue(serialize(maximum)));
267 }
268
269 String NumberInputType::rangeUnderflowText(const Decimal& minimum) const
270 {
271     return locale().queryString(WebLocalizedString::ValidationRangeUnderflow, localizeValue(serialize(minimum)));
272 }
273
274 bool NumberInputType::shouldRespectSpeechAttribute()
275 {
276     return true;
277 }
278
279 bool NumberInputType::supportsPlaceholder() const
280 {
281     return true;
282 }
283
284 bool NumberInputType::isNumberField() const
285 {
286     return true;
287 }
288
289 void NumberInputType::minOrMaxAttributeChanged()
290 {
291     InputType::minOrMaxAttributeChanged();
292
293     if (element().renderer())
294         element().renderer()->setNeedsLayoutAndPrefWidthsRecalc();
295 }
296
297 void NumberInputType::stepAttributeChanged()
298 {
299     InputType::stepAttributeChanged();
300
301     if (element().renderer())
302         element().renderer()->setNeedsLayoutAndPrefWidthsRecalc();
303 }
304
305 bool NumberInputType::supportsSelectionAPI() const
306 {
307     return false;
308 }
309
310 } // namespace WebCore