1/*
2 * (C) 1999-2003 Lars Knoll (knoll@kde.org)
3 * Copyright (C) 2004, 2005, 2006, 2008 Apple Inc. All rights reserved.
4 * Copyright (C) 2007 Alexey Proskuryakov <ap@webkit.org>
5 *
6 * This library is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU Library General Public
8 * License as published by the Free Software Foundation; either
9 * version 2 of the License, or (at your option) any later version.
10 *
11 * This library is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14 * Library General Public License for more details.
15 *
16 * You should have received a copy of the GNU Library General Public License
17 * along with this library; see the file COPYING.LIB.  If not, write to
18 * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
19 * Boston, MA 02110-1301, USA.
20 */
21
22#ifndef CSSPrimitiveValue_h
23#define CSSPrimitiveValue_h
24
25#include "CSSValue.h"
26#include "Color.h"
27#include <wtf/Forward.h>
28#include <wtf/MathExtras.h>
29#include <wtf/PassRefPtr.h>
30
31namespace WebCore {
32
33class CSSCalcValue;
34class Counter;
35class DashboardRegion;
36class Pair;
37class Quad;
38class RGBColor;
39class Rect;
40class RenderStyle;
41class CSSBasicShape;
42
43struct Length;
44
45// Dimension calculations are imprecise, often resulting in values of e.g.
46// 44.99998. We need to go ahead and round if we're really close to the next
47// integer value.
48template<typename T> inline T roundForImpreciseConversion(double value)
49{
50    value += (value < 0) ? -0.01 : +0.01;
51    return ((value > std::numeric_limits<T>::max()) || (value < std::numeric_limits<T>::min())) ? 0 : static_cast<T>(value);
52}
53
54template<> inline float roundForImpreciseConversion(double value)
55{
56    double ceiledValue = ceil(value);
57    double proximityToNextInt = ceiledValue - value;
58    if (proximityToNextInt <= 0.01 && value > 0)
59        return static_cast<float>(ceiledValue);
60    if (proximityToNextInt >= 0.99 && value < 0)
61        return static_cast<float>(floor(value));
62    return static_cast<float>(value);
63}
64
65class CSSPrimitiveValue : public CSSValue {
66public:
67    enum UnitTypes {
68        CSS_UNKNOWN = 0,
69        CSS_NUMBER = 1,
70        CSS_PERCENTAGE = 2,
71        CSS_EMS = 3,
72        CSS_EXS = 4,
73        CSS_PX = 5,
74        CSS_CM = 6,
75        CSS_MM = 7,
76        CSS_IN = 8,
77        CSS_PT = 9,
78        CSS_PC = 10,
79        CSS_DEG = 11,
80        CSS_RAD = 12,
81        CSS_GRAD = 13,
82        CSS_MS = 14,
83        CSS_S = 15,
84        CSS_HZ = 16,
85        CSS_KHZ = 17,
86        CSS_DIMENSION = 18,
87        CSS_STRING = 19,
88        CSS_URI = 20,
89        CSS_IDENT = 21,
90        CSS_ATTR = 22,
91        CSS_COUNTER = 23,
92        CSS_RECT = 24,
93        CSS_RGBCOLOR = 25,
94        // From CSS Values and Units. Viewport-percentage Lengths (vw/vh/vmin/vmax).
95        CSS_VW = 26,
96        CSS_VH = 27,
97        CSS_VMIN = 28,
98        CSS_VMAX = 29,
99        CSS_DPPX = 30,
100        CSS_DPI = 31,
101        CSS_DPCM = 32,
102        CSS_PAIR = 100, // We envision this being exposed as a means of getting computed style values for pairs (border-spacing/radius, background-position, etc.)
103#if ENABLE(DASHBOARD_SUPPORT)
104        CSS_DASHBOARD_REGION = 101, // FIXME: Dashboard region should not be a primitive value.
105#endif
106        CSS_UNICODE_RANGE = 102,
107
108        // These next types are just used internally to allow us to translate back and forth from CSSPrimitiveValues to CSSParserValues.
109        CSS_PARSER_OPERATOR = 103,
110        CSS_PARSER_INTEGER = 104,
111        CSS_PARSER_HEXCOLOR = 105,
112
113        // This is used internally for unknown identifiers
114        CSS_PARSER_IDENTIFIER = 106,
115
116        // These are from CSS3 Values and Units, but that isn't a finished standard yet
117        CSS_TURN = 107,
118        CSS_REMS = 108,
119        CSS_CHS = 109,
120
121        // This is used internally for counter names (as opposed to counter values)
122        CSS_COUNTER_NAME = 110,
123
124        // This is used by the CSS Shapes draft
125        CSS_SHAPE = 111,
126
127        // Used by border images.
128        CSS_QUAD = 112,
129
130        CSS_CALC = 113,
131        CSS_CALC_PERCENTAGE_WITH_NUMBER = 114,
132        CSS_CALC_PERCENTAGE_WITH_LENGTH = 115,
133
134#if ENABLE(CSS_VARIABLES)
135        CSS_VARIABLE_NAME = 116,
136#endif
137    };
138
139    // This enum follows the CSSParser::Units enum augmented with UNIT_FREQUENCY for frequencies.
140    enum UnitCategory {
141        UNumber,
142        UPercent,
143        ULength,
144        UAngle,
145        UTime,
146        UFrequency,
147        UViewportPercentageLength,
148#if ENABLE(CSS_IMAGE_RESOLUTION) || ENABLE(RESOLUTION_MEDIA_QUERY)
149        UResolution,
150#endif
151        UOther
152    };
153
154    bool isAngle() const
155    {
156        return m_primitiveUnitType == CSS_DEG
157               || m_primitiveUnitType == CSS_RAD
158               || m_primitiveUnitType == CSS_GRAD
159               || m_primitiveUnitType == CSS_TURN;
160    }
161    bool isAttr() const { return m_primitiveUnitType == CSS_ATTR; }
162    bool isCounter() const { return m_primitiveUnitType == CSS_COUNTER; }
163    bool isFontIndependentLength() const { return m_primitiveUnitType >= CSS_PX && m_primitiveUnitType <= CSS_PC; }
164    bool isFontRelativeLength() const
165    {
166        return m_primitiveUnitType == CSS_EMS
167            || m_primitiveUnitType == CSS_EXS
168            || m_primitiveUnitType == CSS_REMS
169            || m_primitiveUnitType == CSS_CHS;
170    }
171    bool isIdent() const { return m_primitiveUnitType == CSS_IDENT; }
172    bool isLength() const
173    {
174        unsigned short type = primitiveType();
175        return (type >= CSS_EMS && type <= CSS_PC) || type == CSS_REMS || type == CSS_CHS;
176    }
177    bool isNumber() const { return primitiveType() == CSS_NUMBER; }
178    bool isPercentage() const { return primitiveType() == CSS_PERCENTAGE; }
179    bool isPx() const { return primitiveType() == CSS_PX; }
180    bool isRect() const { return m_primitiveUnitType == CSS_RECT; }
181    bool isRGBColor() const { return m_primitiveUnitType == CSS_RGBCOLOR; }
182    bool isShape() const { return m_primitiveUnitType == CSS_SHAPE; }
183    bool isString() const { return m_primitiveUnitType == CSS_STRING; }
184    bool isTime() const { return m_primitiveUnitType == CSS_S || m_primitiveUnitType == CSS_MS; }
185    bool isURI() const { return m_primitiveUnitType == CSS_URI; }
186    bool isCalculated() const { return m_primitiveUnitType == CSS_CALC; }
187    bool isCalculatedPercentageWithNumber() const { return primitiveType() == CSS_CALC_PERCENTAGE_WITH_NUMBER; }
188    bool isCalculatedPercentageWithLength() const { return primitiveType() == CSS_CALC_PERCENTAGE_WITH_LENGTH; }
189    bool isDotsPerInch() const { return primitiveType() == CSS_DPI; }
190    bool isDotsPerPixel() const { return primitiveType() == CSS_DPPX; }
191    bool isDotsPerCentimeter() const { return primitiveType() == CSS_DPCM; }
192    bool isResolution() const
193    {
194        unsigned short type = primitiveType();
195        return type >= CSS_DPPX && type <= CSS_DPCM;
196    }
197
198#if ENABLE(CSS_VARIABLES)
199    bool isVariableName() const { return primitiveType() == CSS_VARIABLE_NAME; }
200#endif
201    bool isViewportPercentageLength() const { return m_primitiveUnitType >= CSS_VW && m_primitiveUnitType <= CSS_VMAX; }
202
203    static PassRefPtr<CSSPrimitiveValue> createIdentifier(int identifier) { return adoptRef(new CSSPrimitiveValue(identifier)); }
204    static PassRefPtr<CSSPrimitiveValue> createColor(unsigned rgbValue) { return adoptRef(new CSSPrimitiveValue(rgbValue)); }
205    static PassRefPtr<CSSPrimitiveValue> create(double value, UnitTypes type) { return adoptRef(new CSSPrimitiveValue(value, type)); }
206    static PassRefPtr<CSSPrimitiveValue> create(const String& value, UnitTypes type) { return adoptRef(new CSSPrimitiveValue(value, type)); }
207
208    template<typename T> static PassRefPtr<CSSPrimitiveValue> create(T value)
209    {
210        return adoptRef(new CSSPrimitiveValue(value));
211    }
212
213    // This value is used to handle quirky margins in reflow roots (body, td, and th) like WinIE.
214    // The basic idea is that a stylesheet can use the value __qem (for quirky em) instead of em.
215    // When the quirky value is used, if you're in quirks mode, the margin will collapse away
216    // inside a table cell.
217    static PassRefPtr<CSSPrimitiveValue> createAllowingMarginQuirk(double value, UnitTypes type)
218    {
219        CSSPrimitiveValue* quirkValue = new CSSPrimitiveValue(value, type);
220        quirkValue->m_isQuirkValue = true;
221        return adoptRef(quirkValue);
222    }
223
224    ~CSSPrimitiveValue();
225
226    void cleanup();
227
228    unsigned short primitiveType() const;
229
230    double computeDegrees();
231
232    enum TimeUnit { Seconds, Milliseconds };
233    template <typename T, TimeUnit timeUnit> T computeTime()
234    {
235        if (timeUnit == Seconds && m_primitiveUnitType == CSS_S)
236            return getValue<T>();
237        if (timeUnit == Seconds && m_primitiveUnitType == CSS_MS)
238            return getValue<T>() / 1000;
239        if (timeUnit == Milliseconds && m_primitiveUnitType == CSS_MS)
240            return getValue<T>();
241        if (timeUnit == Milliseconds && m_primitiveUnitType == CSS_S)
242            return getValue<T>() * 1000;
243        ASSERT_NOT_REACHED();
244        return 0;
245    }
246
247    /*
248     * computes a length in pixels out of the given CSSValue. Need the RenderStyle to get
249     * the fontinfo in case val is defined in em or ex.
250     *
251     * The metrics have to be a bit different for screen and printer output.
252     * For screen output we assume 1 inch == 72 px, for printer we assume 300 dpi
253     *
254     * this is screen/printer dependent, so we probably need a config option for this,
255     * and some tool to calibrate.
256     */
257    template<typename T> T computeLength(const RenderStyle* currStyle, const RenderStyle* rootStyle, float multiplier = 1.0f, bool computingFontSize = false) const;
258
259    // Converts to a Length, mapping various unit types appropriately.
260    template<int> Length convertToLength(const RenderStyle* currStyle, const RenderStyle* rootStyle, double multiplier = 1.0, bool computingFontSize = false) const;
261
262    // use with care!!!
263    void setPrimitiveType(unsigned short type) { m_primitiveUnitType = type; }
264
265    double getDoubleValue(unsigned short unitType, ExceptionCode&) const;
266    double getDoubleValue(unsigned short unitType) const;
267    double getDoubleValue() const;
268
269    void setFloatValue(unsigned short unitType, double floatValue, ExceptionCode&);
270    float getFloatValue(unsigned short unitType, ExceptionCode& ec) const { return getValue<float>(unitType, ec); }
271    float getFloatValue(unsigned short unitType) const { return getValue<float>(unitType); }
272    float getFloatValue() const { return getValue<float>(); }
273
274    int getIntValue(unsigned short unitType, ExceptionCode& ec) const { return getValue<int>(unitType, ec); }
275    int getIntValue(unsigned short unitType) const { return getValue<int>(unitType); }
276    int getIntValue() const { return getValue<int>(); }
277
278    template<typename T> inline T getValue(unsigned short unitType, ExceptionCode& ec) const { return clampTo<T>(getDoubleValue(unitType, ec)); }
279    template<typename T> inline T getValue(unsigned short unitType) const { return clampTo<T>(getDoubleValue(unitType)); }
280    template<typename T> inline T getValue() const { return clampTo<T>(getDoubleValue()); }
281
282    void setStringValue(unsigned short stringType, const String& stringValue, ExceptionCode&);
283    String getStringValue(ExceptionCode&) const;
284    String getStringValue() const;
285
286    Counter* getCounterValue(ExceptionCode&) const;
287    Counter* getCounterValue() const { return m_primitiveUnitType != CSS_COUNTER ? 0 : m_value.counter; }
288
289    Rect* getRectValue(ExceptionCode&) const;
290    Rect* getRectValue() const { return m_primitiveUnitType != CSS_RECT ? 0 : m_value.rect; }
291
292    Quad* getQuadValue(ExceptionCode&) const;
293    Quad* getQuadValue() const { return m_primitiveUnitType != CSS_QUAD ? 0 : m_value.quad; }
294
295    PassRefPtr<RGBColor> getRGBColorValue(ExceptionCode&) const;
296    RGBA32 getRGBA32Value() const { return m_primitiveUnitType != CSS_RGBCOLOR ? 0 : m_value.rgbcolor; }
297
298    Pair* getPairValue(ExceptionCode&) const;
299    Pair* getPairValue() const { return m_primitiveUnitType != CSS_PAIR ? 0 : m_value.pair; }
300
301#if ENABLE(DASHBOARD_SUPPORT)
302    DashboardRegion* getDashboardRegionValue() const { return m_primitiveUnitType != CSS_DASHBOARD_REGION ? 0 : m_value.region; }
303#endif
304
305    CSSBasicShape* getShapeValue() const { return m_primitiveUnitType != CSS_SHAPE ? 0 : m_value.shape; }
306
307    CSSCalcValue* cssCalcValue() const { return m_primitiveUnitType != CSS_CALC ? 0 : m_value.calc; }
308
309    int getIdent() const { return m_primitiveUnitType == CSS_IDENT ? m_value.ident : 0; }
310
311    template<typename T> inline operator T() const; // Defined in CSSPrimitiveValueMappings.h
312
313    String customCssText() const;
314#if ENABLE(CSS_VARIABLES)
315    String customSerializeResolvingVariables(const HashMap<AtomicString, String>&) const;
316    bool hasVariableReference() const;
317#endif
318
319    bool isQuirkValue() { return m_isQuirkValue; }
320
321    void addSubresourceStyleURLs(ListHashSet<KURL>&, const StyleSheetContents*) const;
322
323    Length viewportPercentageLength() const;
324
325    PassRefPtr<CSSPrimitiveValue> cloneForCSSOM() const;
326    void setCSSOMSafe() { m_isCSSOMSafe = true; }
327
328    bool equals(const CSSPrimitiveValue&) const;
329
330private:
331    // FIXME: int vs. unsigned overloading is too subtle to distinguish the color and identifier cases.
332    CSSPrimitiveValue(int ident);
333    CSSPrimitiveValue(unsigned color); // RGB value
334    CSSPrimitiveValue(const Length&);
335    CSSPrimitiveValue(const String&, UnitTypes);
336    CSSPrimitiveValue(double, UnitTypes);
337
338    template<typename T> CSSPrimitiveValue(T); // Defined in CSSPrimitiveValueMappings.h
339    template<typename T> CSSPrimitiveValue(T* val)
340        : CSSValue(PrimitiveClass)
341    {
342        init(PassRefPtr<T>(val));
343    }
344
345    template<typename T> CSSPrimitiveValue(PassRefPtr<T> val)
346        : CSSValue(PrimitiveClass)
347    {
348        init(val);
349    }
350
351    static void create(int); // compile-time guard
352    static void create(unsigned); // compile-time guard
353    template<typename T> operator T*(); // compile-time guard
354
355    static UnitTypes canonicalUnitTypeForCategory(UnitCategory category);
356
357    void init(PassRefPtr<Counter>);
358    void init(PassRefPtr<Rect>);
359    void init(PassRefPtr<Pair>);
360    void init(PassRefPtr<Quad>);
361    void init(PassRefPtr<DashboardRegion>); // FIXME: Dashboard region should not be a primitive value.
362    void init(PassRefPtr<CSSBasicShape>);
363    void init(PassRefPtr<CSSCalcValue>);
364    bool getDoubleValueInternal(UnitTypes targetUnitType, double* result) const;
365
366    double computeLengthDouble(const RenderStyle* currentStyle, const RenderStyle* rootStyle, float multiplier, bool computingFontSize) const;
367
368    union {
369        int ident;
370        double num;
371        StringImpl* string;
372        Counter* counter;
373        Rect* rect;
374        Quad* quad;
375        unsigned rgbcolor;
376        Pair* pair;
377        DashboardRegion* region;
378        CSSBasicShape* shape;
379        CSSCalcValue* calc;
380    } m_value;
381};
382
383} // namespace WebCore
384
385#endif // CSSPrimitiveValue_h
386