1 /*
2 * Copyright (C) 2006, 2007, 2008, 2009, 2010 Apple Inc. All rights reserved.
3 *
4 * This library is free software; you can redistribute it and/or
5 * modify it under the terms of the GNU Library General Public
6 * License as published by the Free Software Foundation; either
7 * version 2 of the License, or (at your option) any later version.
8 *
9 * This library is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
12 * Library General Public License for more details.
13 *
14 * You should have received a copy of the GNU Library General Public License
15 * along with this library; see the file COPYING.LIB. If not, write to
16 * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
17 * Boston, MA 02110-1301, USA.
18 *
19 */
20
21 #include "config.h"
22 #include "StepRange.h"
23
24 #include "HTMLInputElement.h"
25 #include "HTMLNames.h"
26 #include "HTMLParserIdioms.h"
27 #include <wtf/MathExtras.h>
28 #include <wtf/text/WTFString.h>
29
30 using namespace std;
31
32 namespace WebCore {
33
34 using namespace HTMLNames;
35
StepRange(const HTMLInputElement * element)36 StepRange::StepRange(const HTMLInputElement* element)
37 {
38 if (element->hasAttribute(precisionAttr)) {
39 step = 1.0;
40 hasStep = !equalIgnoringCase(element->getAttribute(precisionAttr), "float");
41 } else
42 hasStep = element->getAllowedValueStep(&step);
43
44 maximum = element->maximum();
45 minimum = element->minimum();
46 }
47
clampValue(double value)48 double StepRange::clampValue(double value)
49 {
50 double clampedValue = max(minimum, min(value, maximum));
51 if (!hasStep)
52 return clampedValue;
53 // Rounds clampedValue to minimum + N * step.
54 clampedValue = minimum + round((clampedValue - minimum) / step) * step;
55 if (clampedValue > maximum)
56 clampedValue -= step;
57 ASSERT(clampedValue >= minimum);
58 ASSERT(clampedValue <= maximum);
59 return clampedValue;
60 }
61
clampValue(const String & stringValue)62 double StepRange::clampValue(const String& stringValue)
63 {
64 double value;
65 bool parseSuccess = parseToDoubleForNumberType(stringValue, &value);
66 if (!parseSuccess)
67 value = (minimum + maximum) / 2;
68 return clampValue(value);
69 }
70
valueFromElement(HTMLInputElement * element,bool * wasClamped)71 double StepRange::valueFromElement(HTMLInputElement* element, bool* wasClamped)
72 {
73 double oldValue;
74 bool parseSuccess = parseToDoubleForNumberType(element->value(), &oldValue);
75 if (!parseSuccess)
76 oldValue = (minimum + maximum) / 2;
77 double newValue = clampValue(oldValue);
78
79 if (wasClamped)
80 *wasClamped = !parseSuccess || newValue != oldValue;
81
82 return newValue;
83 }
84
85 }
86