OSDN Git Service

9ae0505264ca3ab2c93b04904eee17cc62a59031
[android-x86/external-webkit.git] / WebCore / css / CSSStyleSelector.cpp
1 /*
2  * Copyright (C) 1999 Lars Knoll (knoll@kde.org)
3  *           (C) 2004-2005 Allan Sandfeld Jensen (kde@carewolf.com)
4  * Copyright (C) 2006, 2007 Nicholas Shanks (webkit@nickshanks.com)
5  * Copyright (C) 2005, 2006, 2007, 2008, 2009, 2010 Apple Inc. All rights reserved.
6  * Copyright (C) 2007 Alexey Proskuryakov <ap@webkit.org>
7  * Copyright (C) 2007, 2008 Eric Seidel <eric@webkit.org>
8  * Copyright (C) 2008, 2009 Torch Mobile Inc. All rights reserved. (http://www.torchmobile.com/)
9  *
10  * This library is free software; you can redistribute it and/or
11  * modify it under the terms of the GNU Library General Public
12  * License as published by the Free Software Foundation; either
13  * version 2 of the License, or (at your option) any later version.
14  *
15  * This library is distributed in the hope that it will be useful,
16  * but WITHOUT ANY WARRANTY; without even the implied warranty of
17  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
18  * Library General Public License for more details.
19  *
20  * You should have received a copy of the GNU Library General Public License
21  * along with this library; see the file COPYING.LIB.  If not, write to
22  * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
23  * Boston, MA 02110-1301, USA.
24  */
25
26 #include "config.h"
27 #include "CSSStyleSelector.h"
28
29 #include "Attribute.h"
30 #include "CSSBorderImageValue.h"
31 #include "CSSCursorImageValue.h"
32 #include "CSSFontFaceRule.h"
33 #include "CSSImportRule.h"
34 #include "CSSMediaRule.h"
35 #include "CSSPageRule.h"
36 #include "CSSParser.h"
37 #include "CSSPrimitiveValueMappings.h"
38 #include "CSSPropertyNames.h"
39 #include "CSSReflectValue.h"
40 #include "CSSRuleList.h"
41 #include "CSSSelector.h"
42 #include "CSSSelectorList.h"
43 #include "CSSStyleRule.h"
44 #include "CSSStyleSheet.h"
45 #include "CSSTimingFunctionValue.h"
46 #include "CSSValueList.h"
47 #include "CSSVariableDependentValue.h"
48 #include "CSSVariablesDeclaration.h"
49 #include "CSSVariablesRule.h"
50 #include "CachedImage.h"
51 #include "Counter.h"
52 #include "FocusController.h"
53 #include "FontFamilyValue.h"
54 #include "FontValue.h"
55 #include "Frame.h"
56 #include "FrameView.h"
57 #include "HTMLDocument.h"
58 #include "HTMLElement.h"
59 #include "HTMLInputElement.h"
60 #include "HTMLNames.h"
61 #include "HTMLTextAreaElement.h"
62 #include "KeyframeList.h"
63 #include "LinkHash.h"
64 #include "Matrix3DTransformOperation.h"
65 #include "MatrixTransformOperation.h"
66 #include "MediaList.h"
67 #include "MediaQueryEvaluator.h"
68 #include "NodeRenderStyle.h"
69 #include "Page.h"
70 #include "PageGroup.h"
71 #include "Pair.h"
72 #include "PerspectiveTransformOperation.h"
73 #include "Rect.h"
74 #include "RenderScrollbar.h"
75 #include "RenderScrollbarTheme.h"
76 #include "RenderStyleConstants.h"
77 #include "RenderTheme.h"
78 #include "RotateTransformOperation.h"
79 #include "ScaleTransformOperation.h"
80 #include "SelectionController.h"
81 #include "Settings.h"
82 #include "ShadowValue.h"
83 #include "SkewTransformOperation.h"
84 #include "StyleCachedImage.h"
85 #include "StylePendingImage.h"
86 #include "StyleGeneratedImage.h"
87 #include "StyleSheetList.h"
88 #include "Text.h"
89 #include "TransformationMatrix.h"
90 #include "TranslateTransformOperation.h"
91 #include "UserAgentStyleSheets.h"
92 #include "WebKitCSSKeyframeRule.h"
93 #include "WebKitCSSKeyframesRule.h"
94 #include "WebKitCSSTransformValue.h"
95 #include "XMLNames.h"
96 #include "loader.h"
97 #include <wtf/StdLibExtras.h>
98 #include <wtf/Vector.h>
99
100 #if USE(PLATFORM_STRATEGIES)
101 #include "PlatformStrategies.h"
102 #include "VisitedLinkStrategy.h"
103 #endif
104
105 #if ENABLE(DASHBOARD_SUPPORT)
106 #include "DashboardRegion.h"
107 #endif
108
109 #if ENABLE(SVG)
110 #include "XLinkNames.h"
111 #include "SVGNames.h"
112 #endif
113
114 #if ENABLE(WML)
115 #include "WMLNames.h"
116 #endif
117
118 #if PLATFORM(QT)
119 #include <qwebhistoryinterface.h>
120 #endif
121
122 using namespace std;
123
124 namespace WebCore {
125
126 using namespace HTMLNames;
127
128 #define HANDLE_INHERIT(prop, Prop) \
129 if (isInherit) { \
130     m_style->set##Prop(m_parentStyle->prop()); \
131     return; \
132 }
133
134 #define HANDLE_INHERIT_AND_INITIAL(prop, Prop) \
135 HANDLE_INHERIT(prop, Prop) \
136 if (isInitial) { \
137     m_style->set##Prop(RenderStyle::initial##Prop()); \
138     return; \
139 }
140
141 #define HANDLE_INHERIT_AND_INITIAL_WITH_VALUE(prop, Prop, Value) \
142 HANDLE_INHERIT(prop, Prop) \
143 if (isInitial) { \
144     m_style->set##Prop(RenderStyle::initial##Value());\
145     return;\
146 }
147
148 #define HANDLE_INHERIT_AND_INITIAL_AND_PRIMITIVE(prop, Prop) \
149 HANDLE_INHERIT_AND_INITIAL(prop, Prop) \
150 if (primitiveValue) \
151     m_style->set##Prop(*primitiveValue);
152
153 #define HANDLE_INHERIT_AND_INITIAL_AND_PRIMITIVE_WITH_VALUE(prop, Prop, Value) \
154 HANDLE_INHERIT_AND_INITIAL_WITH_VALUE(prop, Prop, Value) \
155 if (primitiveValue) \
156     m_style->set##Prop(*primitiveValue);
157
158 #define HANDLE_FILL_LAYER_INHERIT_AND_INITIAL(layerType, LayerType, prop, Prop) \
159 if (isInherit) { \
160     FillLayer* currChild = m_style->access##LayerType##Layers(); \
161     FillLayer* prevChild = 0; \
162     const FillLayer* currParent = m_parentStyle->layerType##Layers(); \
163     while (currParent && currParent->is##Prop##Set()) { \
164         if (!currChild) { \
165             /* Need to make a new layer.*/ \
166             currChild = new FillLayer(LayerType##FillLayer); \
167             prevChild->setNext(currChild); \
168         } \
169         currChild->set##Prop(currParent->prop()); \
170         prevChild = currChild; \
171         currChild = prevChild->next(); \
172         currParent = currParent->next(); \
173     } \
174     \
175     while (currChild) { \
176         /* Reset any remaining layers to not have the property set. */ \
177         currChild->clear##Prop(); \
178         currChild = currChild->next(); \
179     } \
180 } else if (isInitial) { \
181     FillLayer* currChild = m_style->access##LayerType##Layers(); \
182     currChild->set##Prop(FillLayer::initialFill##Prop(LayerType##FillLayer)); \
183     for (currChild = currChild->next(); currChild; currChild = currChild->next()) \
184         currChild->clear##Prop(); \
185 }
186
187 #define HANDLE_FILL_LAYER_VALUE(layerType, LayerType, prop, Prop, value) { \
188 HANDLE_FILL_LAYER_INHERIT_AND_INITIAL(layerType, LayerType, prop, Prop) \
189 if (isInherit || isInitial) \
190     return; \
191 FillLayer* currChild = m_style->access##LayerType##Layers(); \
192 FillLayer* prevChild = 0; \
193 if (value->isValueList()) { \
194     /* Walk each value and put it into a layer, creating new layers as needed. */ \
195     CSSValueList* valueList = static_cast<CSSValueList*>(value); \
196     for (unsigned int i = 0; i < valueList->length(); i++) { \
197         if (!currChild) { \
198             /* Need to make a new layer to hold this value */ \
199             currChild = new FillLayer(LayerType##FillLayer); \
200             prevChild->setNext(currChild); \
201         } \
202         mapFill##Prop(property, currChild, valueList->itemWithoutBoundsCheck(i)); \
203         prevChild = currChild; \
204         currChild = currChild->next(); \
205     } \
206 } else { \
207     mapFill##Prop(property, currChild, value); \
208     currChild = currChild->next(); \
209 } \
210 while (currChild) { \
211     /* Reset all remaining layers to not have the property set. */ \
212     currChild->clear##Prop(); \
213     currChild = currChild->next(); \
214 } }
215
216 #define HANDLE_BACKGROUND_INHERIT_AND_INITIAL(prop, Prop) \
217 HANDLE_FILL_LAYER_INHERIT_AND_INITIAL(background, Background, prop, Prop)
218
219 #define HANDLE_BACKGROUND_VALUE(prop, Prop, value) \
220 HANDLE_FILL_LAYER_VALUE(background, Background, prop, Prop, value)
221
222 #define HANDLE_MASK_INHERIT_AND_INITIAL(prop, Prop) \
223 HANDLE_FILL_LAYER_INHERIT_AND_INITIAL(mask, Mask, prop, Prop)
224
225 #define HANDLE_MASK_VALUE(prop, Prop, value) \
226 HANDLE_FILL_LAYER_VALUE(mask, Mask, prop, Prop, value)
227
228 #define HANDLE_ANIMATION_INHERIT_AND_INITIAL(prop, Prop) \
229 if (isInherit) { \
230     AnimationList* list = m_style->accessAnimations(); \
231     const AnimationList* parentList = m_parentStyle->animations(); \
232     size_t i = 0, parentSize = parentList ? parentList->size() : 0; \
233     for ( ; i < parentSize && parentList->animation(i)->is##Prop##Set(); ++i) { \
234         if (list->size() <= i) \
235             list->append(Animation::create()); \
236         list->animation(i)->set##Prop(parentList->animation(i)->prop()); \
237     } \
238     \
239     /* Reset any remaining animations to not have the property set. */ \
240     for ( ; i < list->size(); ++i) \
241         list->animation(i)->clear##Prop(); \
242 } else if (isInitial) { \
243     AnimationList* list = m_style->accessAnimations(); \
244     if (list->isEmpty()) \
245         list->append(Animation::create()); \
246     list->animation(0)->set##Prop(Animation::initialAnimation##Prop()); \
247     for (size_t i = 1; i < list->size(); ++i) \
248         list->animation(0)->clear##Prop(); \
249 }
250
251 #define HANDLE_ANIMATION_VALUE(prop, Prop, value) { \
252 HANDLE_ANIMATION_INHERIT_AND_INITIAL(prop, Prop) \
253 if (isInherit || isInitial) \
254     return; \
255 AnimationList* list = m_style->accessAnimations(); \
256 size_t childIndex = 0; \
257 if (value->isValueList()) { \
258     /* Walk each value and put it into an animation, creating new animations as needed. */ \
259     CSSValueList* valueList = static_cast<CSSValueList*>(value); \
260     for (unsigned int i = 0; i < valueList->length(); i++) { \
261         if (childIndex <= list->size()) \
262             list->append(Animation::create()); \
263         mapAnimation##Prop(list->animation(childIndex), valueList->itemWithoutBoundsCheck(i)); \
264         ++childIndex; \
265     } \
266 } else { \
267     if (list->isEmpty()) \
268         list->append(Animation::create()); \
269     mapAnimation##Prop(list->animation(childIndex), value); \
270     childIndex = 1; \
271 } \
272 for ( ; childIndex < list->size(); ++childIndex) { \
273     /* Reset all remaining animations to not have the property set. */ \
274     list->animation(childIndex)->clear##Prop(); \
275 } \
276 }
277
278 #define HANDLE_TRANSITION_INHERIT_AND_INITIAL(prop, Prop) \
279 if (isInherit) { \
280     AnimationList* list = m_style->accessTransitions(); \
281     const AnimationList* parentList = m_parentStyle->transitions(); \
282     size_t i = 0, parentSize = parentList ? parentList->size() : 0; \
283     for ( ; i < parentSize && parentList->animation(i)->is##Prop##Set(); ++i) { \
284         if (list->size() <= i) \
285             list->append(Animation::create()); \
286         list->animation(i)->set##Prop(parentList->animation(i)->prop()); \
287     } \
288     \
289     /* Reset any remaining transitions to not have the property set. */ \
290     for ( ; i < list->size(); ++i) \
291         list->animation(i)->clear##Prop(); \
292 } else if (isInitial) { \
293     AnimationList* list = m_style->accessTransitions(); \
294     if (list->isEmpty()) \
295         list->append(Animation::create()); \
296     list->animation(0)->set##Prop(Animation::initialAnimation##Prop()); \
297     for (size_t i = 1; i < list->size(); ++i) \
298         list->animation(0)->clear##Prop(); \
299 }
300
301 #define HANDLE_TRANSITION_VALUE(prop, Prop, value) { \
302 HANDLE_TRANSITION_INHERIT_AND_INITIAL(prop, Prop) \
303 if (isInherit || isInitial) \
304     return; \
305 AnimationList* list = m_style->accessTransitions(); \
306 size_t childIndex = 0; \
307 if (value->isValueList()) { \
308     /* Walk each value and put it into a transition, creating new animations as needed. */ \
309     CSSValueList* valueList = static_cast<CSSValueList*>(value); \
310     for (unsigned int i = 0; i < valueList->length(); i++) { \
311         if (childIndex <= list->size()) \
312             list->append(Animation::create()); \
313         mapAnimation##Prop(list->animation(childIndex), valueList->itemWithoutBoundsCheck(i)); \
314         ++childIndex; \
315     } \
316 } else { \
317     if (list->isEmpty()) \
318         list->append(Animation::create()); \
319     mapAnimation##Prop(list->animation(childIndex), value); \
320     childIndex = 1; \
321 } \
322 for ( ; childIndex < list->size(); ++childIndex) { \
323     /* Reset all remaining transitions to not have the property set. */ \
324     list->animation(childIndex)->clear##Prop(); \
325 } \
326 }
327
328 #define HANDLE_INHERIT_COND(propID, prop, Prop) \
329 if (id == propID) { \
330     m_style->set##Prop(m_parentStyle->prop()); \
331     return; \
332 }
333     
334 #define HANDLE_INHERIT_COND_WITH_BACKUP(propID, prop, propAlt, Prop) \
335 if (id == propID) { \
336     if (m_parentStyle->prop().isValid()) \
337         m_style->set##Prop(m_parentStyle->prop()); \
338     else \
339         m_style->set##Prop(m_parentStyle->propAlt()); \
340     return; \
341 }
342
343 #define HANDLE_INITIAL_COND(propID, Prop) \
344 if (id == propID) { \
345     m_style->set##Prop(RenderStyle::initial##Prop()); \
346     return; \
347 }
348
349 #define HANDLE_INITIAL_COND_WITH_VALUE(propID, Prop, Value) \
350 if (id == propID) { \
351     m_style->set##Prop(RenderStyle::initial##Value()); \
352     return; \
353 }
354
355 class CSSRuleSet : public Noncopyable {
356 public:
357     CSSRuleSet();
358     ~CSSRuleSet();
359     
360     typedef HashMap<AtomicStringImpl*, CSSRuleDataList*> AtomRuleMap;
361     
362     void addRulesFromSheet(CSSStyleSheet*, const MediaQueryEvaluator&, CSSStyleSelector* = 0);
363
364     void addStyleRule(StyleBase* item);
365     void addRule(CSSStyleRule* rule, CSSSelector* sel);
366     void addPageRule(CSSStyleRule* rule, CSSSelector* sel);
367     void addToRuleSet(AtomicStringImpl* key, AtomRuleMap& map,
368                       CSSStyleRule* rule, CSSSelector* sel);
369     
370     CSSRuleDataList* getIDRules(AtomicStringImpl* key) { return m_idRules.get(key); }
371     CSSRuleDataList* getClassRules(AtomicStringImpl* key) { return m_classRules.get(key); }
372     CSSRuleDataList* getTagRules(AtomicStringImpl* key) { return m_tagRules.get(key); }
373     CSSRuleDataList* getUniversalRules() { return m_universalRules.get(); }
374     CSSRuleDataList* getPageRules() { return m_pageRules.get(); }
375     
376 public:
377     AtomRuleMap m_idRules;
378     AtomRuleMap m_classRules;
379     AtomRuleMap m_tagRules;
380     OwnPtr<CSSRuleDataList> m_universalRules;
381     OwnPtr<CSSRuleDataList> m_pageRules;
382     unsigned m_ruleCount;
383     unsigned m_pageRuleCount;
384 };
385
386 static CSSRuleSet* defaultStyle;
387 static CSSRuleSet* defaultQuirksStyle;
388 static CSSRuleSet* defaultPrintStyle;
389 static CSSRuleSet* defaultViewSourceStyle;
390 static CSSStyleSheet* simpleDefaultStyleSheet;
391
392 RenderStyle* CSSStyleSelector::s_styleNotYetAvailable;
393
394 static void loadFullDefaultStyle();
395 static void loadSimpleDefaultStyle();
396 // FIXME: It would be nice to use some mechanism that guarantees this is in sync with the real UA stylesheet.
397 static const char* simpleUserAgentStyleSheet = "html,body,div{display:block}body{margin:8px}div:focus,span:focus{outline:auto 5px -webkit-focus-ring-color}a:-webkit-any-link{color:-webkit-link;text-decoration:underline}a:-webkit-any-link:active{color:-webkit-activelink}";
398
399 static bool elementCanUseSimpleDefaultStyle(Element* e)
400 {
401     return e->hasTagName(htmlTag) || e->hasTagName(bodyTag) || e->hasTagName(divTag) || e->hasTagName(spanTag) || e->hasTagName(brTag) || e->hasTagName(aTag);
402 }
403
404 static const MediaQueryEvaluator& screenEval()
405 {
406     DEFINE_STATIC_LOCAL(const MediaQueryEvaluator, staticScreenEval, ("screen"));
407     return staticScreenEval;
408 }
409
410 static const MediaQueryEvaluator& printEval()
411 {
412     DEFINE_STATIC_LOCAL(const MediaQueryEvaluator, staticPrintEval, ("print"));
413     return staticPrintEval;
414 }
415
416 CSSStyleSelector::CSSStyleSelector(Document* document, StyleSheetList* styleSheets, CSSStyleSheet* mappedElementSheet,
417                                    CSSStyleSheet* pageUserSheet, const Vector<RefPtr<CSSStyleSheet> >* pageGroupUserSheets,
418                                    bool strictParsing, bool matchAuthorAndUserStyles)
419     : m_backgroundData(BackgroundFillLayer)
420     , m_checker(document, strictParsing)
421     , m_element(0)
422     , m_styledElement(0)
423     , m_elementLinkState(NotInsideLink)
424     , m_fontSelector(CSSFontSelector::create(document))
425 {
426     m_matchAuthorAndUserStyles = matchAuthorAndUserStyles;
427     
428     Element* root = document->documentElement();
429
430     if (!defaultStyle) {
431         if (!root || elementCanUseSimpleDefaultStyle(root))
432             loadSimpleDefaultStyle();
433         else
434             loadFullDefaultStyle();
435     }
436
437     // construct document root element default style. this is needed
438     // to evaluate media queries that contain relative constraints, like "screen and (max-width: 10em)"
439     // This is here instead of constructor, because when constructor is run,
440     // document doesn't have documentElement
441     // NOTE: this assumes that element that gets passed to styleForElement -call
442     // is always from the document that owns the style selector
443     FrameView* view = document->view();
444     if (view)
445         m_medium = adoptPtr(new MediaQueryEvaluator(view->mediaType()));
446     else
447         m_medium = adoptPtr(new MediaQueryEvaluator("all"));
448
449     if (root)
450         m_rootDefaultStyle = styleForElement(root, 0, false, true); // don't ref, because the RenderStyle is allocated from global heap
451
452     if (m_rootDefaultStyle && view)
453         m_medium = adoptPtr(new MediaQueryEvaluator(view->mediaType(), view->frame(), m_rootDefaultStyle.get()));
454
455     m_authorStyle = adoptPtr(new CSSRuleSet);
456
457     // FIXME: This sucks! The user sheet is reparsed every time!
458     OwnPtr<CSSRuleSet> tempUserStyle = adoptPtr(new CSSRuleSet);
459     if (pageUserSheet)
460         tempUserStyle->addRulesFromSheet(pageUserSheet, *m_medium, this);
461     if (pageGroupUserSheets) {
462         unsigned length = pageGroupUserSheets->size();
463         for (unsigned i = 0; i < length; i++) {
464             if (pageGroupUserSheets->at(i)->isUserStyleSheet())
465                 tempUserStyle->addRulesFromSheet(pageGroupUserSheets->at(i).get(), *m_medium, this);
466             else
467                 m_authorStyle->addRulesFromSheet(pageGroupUserSheets->at(i).get(), *m_medium, this);
468         }
469     }
470
471     if (tempUserStyle->m_ruleCount > 0 || tempUserStyle->m_pageRuleCount > 0)
472         m_userStyle = tempUserStyle.release();
473
474     // Add rules from elements like SVG's <font-face>
475     if (mappedElementSheet)
476         m_authorStyle->addRulesFromSheet(mappedElementSheet, *m_medium, this);
477
478     // add stylesheets from document
479     unsigned length = styleSheets->length();
480     for (unsigned i = 0; i < length; i++) {
481         StyleSheet* sheet = styleSheets->item(i);
482         if (sheet->isCSSStyleSheet() && !sheet->disabled())
483             m_authorStyle->addRulesFromSheet(static_cast<CSSStyleSheet*>(sheet), *m_medium, this);
484     }
485
486     if (document->renderer() && document->renderer()->style())
487         document->renderer()->style()->font().update(fontSelector());
488 }
489
490 // This is a simplified style setting function for keyframe styles
491 void CSSStyleSelector::addKeyframeStyle(PassRefPtr<WebKitCSSKeyframesRule> rule)
492 {
493     AtomicString s(rule->name());
494     m_keyframesRuleMap.add(s.impl(), rule);
495 }
496
497 CSSStyleSelector::~CSSStyleSelector()
498 {
499     m_fontSelector->clearDocument();
500     deleteAllValues(m_viewportDependentMediaQueryResults);
501 }
502
503 static CSSStyleSheet* parseUASheet(const String& str)
504 {
505     CSSStyleSheet* sheet = CSSStyleSheet::create().releaseRef(); // leak the sheet on purpose
506     sheet->parseString(str);
507     return sheet;
508 }
509
510 static CSSStyleSheet* parseUASheet(const char* characters, unsigned size)
511 {
512     return parseUASheet(String(characters, size));
513 }
514
515 static void loadFullDefaultStyle()
516 {
517     if (simpleDefaultStyleSheet) {
518         ASSERT(defaultStyle);
519         delete defaultStyle;
520         simpleDefaultStyleSheet->deref();
521         defaultStyle = new CSSRuleSet;
522         simpleDefaultStyleSheet = 0;
523     } else {
524         ASSERT(!defaultStyle);
525         defaultStyle = new CSSRuleSet;
526         defaultPrintStyle = new CSSRuleSet;
527         defaultQuirksStyle = new CSSRuleSet;
528     }
529
530     // Strict-mode rules.
531     String defaultRules = String(htmlUserAgentStyleSheet, sizeof(htmlUserAgentStyleSheet)) + RenderTheme::defaultTheme()->extraDefaultStyleSheet();
532     CSSStyleSheet* defaultSheet = parseUASheet(defaultRules);
533     defaultStyle->addRulesFromSheet(defaultSheet, screenEval());
534     defaultPrintStyle->addRulesFromSheet(defaultSheet, printEval());
535
536     // Quirks-mode rules.
537     String quirksRules = String(quirksUserAgentStyleSheet, sizeof(quirksUserAgentStyleSheet)) + RenderTheme::defaultTheme()->extraQuirksStyleSheet();
538     CSSStyleSheet* quirksSheet = parseUASheet(quirksRules);
539     defaultQuirksStyle->addRulesFromSheet(quirksSheet, screenEval());
540     
541 #if ENABLE(FULLSCREEN_API)
542     // Full-screen rules.
543     String fullscreenRules = String(fullscreenUserAgentStyleSheet, sizeof(fullscreenUserAgentStyleSheet)) + RenderTheme::defaultTheme()->extraDefaultStyleSheet();
544     CSSStyleSheet* fullscreenSheet = parseUASheet(fullscreenRules);
545     defaultStyle->addRulesFromSheet(fullscreenSheet, screenEval());
546     defaultQuirksStyle->addRulesFromSheet(fullscreenSheet, screenEval());
547 #endif
548 }
549
550 static void loadSimpleDefaultStyle()
551 {
552     ASSERT(!defaultStyle);
553     ASSERT(!simpleDefaultStyleSheet);
554     
555     defaultStyle = new CSSRuleSet;
556     defaultPrintStyle = new CSSRuleSet;
557     defaultQuirksStyle = new CSSRuleSet;
558
559     simpleDefaultStyleSheet = parseUASheet(simpleUserAgentStyleSheet, strlen(simpleUserAgentStyleSheet));
560     defaultStyle->addRulesFromSheet(simpleDefaultStyleSheet, screenEval());
561     
562     // No need to initialize quirks sheet yet as there are no quirk rules for elements allowed in simple default style.
563 }
564     
565 static void loadViewSourceStyle()
566 {
567     ASSERT(!defaultViewSourceStyle);
568     defaultViewSourceStyle = new CSSRuleSet;
569     defaultViewSourceStyle->addRulesFromSheet(parseUASheet(sourceUserAgentStyleSheet, sizeof(sourceUserAgentStyleSheet)), screenEval());
570 }
571
572 void CSSStyleSelector::addMatchedDeclaration(CSSMutableStyleDeclaration* decl)
573 {
574     if (!decl->hasVariableDependentValue()) {
575         m_matchedDecls.append(decl);
576         return;
577     }
578
579     // See if we have already resolved the variables in this declaration.
580     CSSMutableStyleDeclaration* resolvedDecl = m_resolvedVariablesDeclarations.get(decl).get();
581     if (resolvedDecl) {
582         m_matchedDecls.append(resolvedDecl);
583         return;
584     }
585
586     // If this declaration has any variables in it, then we need to make a cloned
587     // declaration with as many variables resolved as possible for this style selector's media.
588     RefPtr<CSSMutableStyleDeclaration> newDecl = CSSMutableStyleDeclaration::create(decl->parentRule());
589     m_matchedDecls.append(newDecl.get());
590     m_resolvedVariablesDeclarations.set(decl, newDecl);
591
592     HashSet<String> usedBlockVariables;
593     resolveVariablesForDeclaration(decl, newDecl.get(), usedBlockVariables);
594 }
595
596 void CSSStyleSelector::resolveVariablesForDeclaration(CSSMutableStyleDeclaration* decl, CSSMutableStyleDeclaration* newDecl, HashSet<String>& usedBlockVariables)
597 {
598     // Now iterate over the properties in the original declaration.  As we resolve variables we'll end up
599     // mutating the new declaration (possibly expanding shorthands).  The new declaration has no m_node
600     // though, so it can't mistakenly call setChanged on anything.
601     CSSMutableStyleDeclaration::const_iterator end = decl->end();
602     for (CSSMutableStyleDeclaration::const_iterator it = decl->begin(); it != end; ++it) {
603         const CSSProperty& current = *it;
604         if (!current.value()->isVariableDependentValue()) {
605             // We can just add the parsed property directly.
606             newDecl->addParsedProperty(current);
607             continue;
608         }
609         CSSValueList* valueList = static_cast<CSSVariableDependentValue*>(current.value())->valueList();
610         if (!valueList)
611             continue;
612         CSSParserValueList resolvedValueList;
613         unsigned s = valueList->length();
614         bool fullyResolved = true;
615         for (unsigned i = 0; i < s; ++i) {
616             CSSValue* val = valueList->item(i);
617             CSSPrimitiveValue* primitiveValue = val->isPrimitiveValue() ? static_cast<CSSPrimitiveValue*>(val) : 0;
618             if (primitiveValue && primitiveValue->isVariable()) {
619                 CSSVariablesRule* rule = m_variablesMap.get(primitiveValue->getStringValue());
620                 if (!rule || !rule->variables()) {
621                     fullyResolved = false;
622                     break;
623                 }
624                 
625                 if (current.id() == CSSPropertyWebkitVariableDeclarationBlock && s == 1) {
626                     fullyResolved = false;
627                     if (!usedBlockVariables.contains(primitiveValue->getStringValue())) {
628                         CSSMutableStyleDeclaration* declBlock = rule->variables()->getParsedVariableDeclarationBlock(primitiveValue->getStringValue());
629                         if (declBlock) {
630                             usedBlockVariables.add(primitiveValue->getStringValue());
631                             resolveVariablesForDeclaration(declBlock, newDecl, usedBlockVariables);
632                         }
633                     }
634                 }
635
636                 CSSValueList* resolvedVariable = rule->variables()->getParsedVariable(primitiveValue->getStringValue());
637                 if (!resolvedVariable) {
638                     fullyResolved = false;
639                     break;
640                 }
641                 unsigned valueSize = resolvedVariable->length();
642                 for (unsigned j = 0; j < valueSize; ++j)
643                     resolvedValueList.addValue(resolvedVariable->item(j)->parserValue());
644             } else
645                 resolvedValueList.addValue(val->parserValue());
646         }
647         
648         if (!fullyResolved)
649             continue;
650
651         // We now have a fully resolved new value list.  We want the parser to use this value list
652         // and parse our new declaration.
653         CSSParser(m_checker.m_strictParsing).parsePropertyWithResolvedVariables(current.id(), current.isImportant(), newDecl, &resolvedValueList);
654     }
655 }
656
657 void CSSStyleSelector::matchRules(CSSRuleSet* rules, int& firstRuleIndex, int& lastRuleIndex, bool includeEmptyRules)
658 {
659     m_matchedRules.clear();
660
661     if (!rules || !m_element)
662         return;
663     
664     // We need to collect the rules for id, class, tag, and everything else into a buffer and
665     // then sort the buffer.
666     if (m_element->hasID())
667         matchRulesForList(rules->getIDRules(m_element->idForStyleResolution().impl()), firstRuleIndex, lastRuleIndex, includeEmptyRules);
668     if (m_element->hasClass()) {
669         ASSERT(m_styledElement);
670         const SpaceSplitString& classNames = m_styledElement->classNames();
671         size_t size = classNames.size();
672         for (size_t i = 0; i < size; ++i)
673             matchRulesForList(rules->getClassRules(classNames[i].impl()), firstRuleIndex, lastRuleIndex, includeEmptyRules);
674     }
675     matchRulesForList(rules->getTagRules(m_element->localName().impl()), firstRuleIndex, lastRuleIndex, includeEmptyRules);
676     matchRulesForList(rules->getUniversalRules(), firstRuleIndex, lastRuleIndex, includeEmptyRules);
677     
678     // If we didn't match any rules, we're done.
679     if (m_matchedRules.isEmpty())
680         return;
681     
682     // Sort the set of matched rules.
683     sortMatchedRules(0, m_matchedRules.size());
684     
685     // Now transfer the set of matched rules over to our list of decls.
686     if (!m_checker.m_collectRulesOnly) {
687         for (unsigned i = 0; i < m_matchedRules.size(); i++)
688             addMatchedDeclaration(m_matchedRules[i]->rule()->declaration());
689     } else {
690         for (unsigned i = 0; i < m_matchedRules.size(); i++) {
691             if (!m_ruleList)
692                 m_ruleList = CSSRuleList::create();
693             m_ruleList->append(m_matchedRules[i]->rule());
694         }
695     }
696 }
697
698 void CSSStyleSelector::matchRulesForList(CSSRuleDataList* rules, int& firstRuleIndex, int& lastRuleIndex, bool includeEmptyRules)
699 {
700     if (!rules)
701         return;
702
703     for (CSSRuleData* d = rules->first(); d; d = d->next()) {
704         CSSStyleRule* rule = d->rule();
705         if (checkSelector(d->selector())) {
706             // If the rule has no properties to apply, then ignore it in the non-debug mode.
707             CSSMutableStyleDeclaration* decl = rule->declaration();
708             if (!decl || (!decl->length() && !includeEmptyRules))
709                 continue;
710             
711             // If we're matching normal rules, set a pseudo bit if 
712             // we really just matched a pseudo-element.
713             if (m_dynamicPseudo != NOPSEUDO && m_checker.m_pseudoStyle == NOPSEUDO) {
714                 if (m_checker.m_collectRulesOnly)
715                     continue;
716                 if (m_dynamicPseudo < FIRST_INTERNAL_PSEUDOID)
717                     m_style->setHasPseudoStyle(m_dynamicPseudo);
718             } else {
719                 // Update our first/last rule indices in the matched rules array.
720                 lastRuleIndex = m_matchedDecls.size() + m_matchedRules.size();
721                 if (firstRuleIndex == -1)
722                     firstRuleIndex = lastRuleIndex;
723
724                 // Add this rule to our list of matched rules.
725                 addMatchedRule(d);
726             }
727         }
728     }
729 }
730
731 static bool operator >(CSSRuleData& r1, CSSRuleData& r2)
732 {
733     int spec1 = r1.selector()->specificity();
734     int spec2 = r2.selector()->specificity();
735     return (spec1 == spec2) ? r1.position() > r2.position() : spec1 > spec2; 
736 }
737     
738 static bool operator <=(CSSRuleData& r1, CSSRuleData& r2)
739 {
740     return !(r1 > r2);
741 }
742
743 void CSSStyleSelector::sortMatchedRules(unsigned start, unsigned end)
744 {
745     if (start >= end || (end - start == 1))
746         return; // Sanity check.
747
748     if (end - start <= 6) {
749         // Apply a bubble sort for smaller lists.
750         for (unsigned i = end - 1; i > start; i--) {
751             bool sorted = true;
752             for (unsigned j = start; j < i; j++) {
753                 CSSRuleData* elt = m_matchedRules[j];
754                 CSSRuleData* elt2 = m_matchedRules[j + 1];
755                 if (*elt > *elt2) {
756                     sorted = false;
757                     m_matchedRules[j] = elt2;
758                     m_matchedRules[j + 1] = elt;
759                 }
760             }
761             if (sorted)
762                 return;
763         }
764         return;
765     }
766
767     // Perform a merge sort for larger lists.
768     unsigned mid = (start + end) / 2;
769     sortMatchedRules(start, mid);
770     sortMatchedRules(mid, end);
771     
772     CSSRuleData* elt = m_matchedRules[mid - 1];
773     CSSRuleData* elt2 = m_matchedRules[mid];
774     
775     // Handle the fast common case (of equal specificity).  The list may already
776     // be completely sorted.
777     if (*elt <= *elt2)
778         return;
779     
780     // We have to merge sort.  Ensure our merge buffer is big enough to hold
781     // all the items.
782     Vector<CSSRuleData*> rulesMergeBuffer;
783     rulesMergeBuffer.reserveInitialCapacity(end - start); 
784
785     unsigned i1 = start;
786     unsigned i2 = mid;
787     
788     elt = m_matchedRules[i1];
789     elt2 = m_matchedRules[i2];
790     
791     while (i1 < mid || i2 < end) {
792         if (i1 < mid && (i2 == end || *elt <= *elt2)) {
793             rulesMergeBuffer.append(elt);
794             if (++i1 < mid)
795                 elt = m_matchedRules[i1];
796         } else {
797             rulesMergeBuffer.append(elt2);
798             if (++i2 < end)
799                 elt2 = m_matchedRules[i2];
800         }
801     }
802     
803     for (unsigned i = start; i < end; i++)
804         m_matchedRules[i] = rulesMergeBuffer[i - start];
805 }
806
807 inline EInsideLink CSSStyleSelector::SelectorChecker::determineLinkState(Element* element) const
808 {
809     if (!element || !element->isLink())
810         return NotInsideLink;
811     return determineLinkStateSlowCase(element);
812 }
813     
814 inline void CSSStyleSelector::initElement(Element* e)
815 {
816     if (m_element != e) {
817         m_element = e;
818         m_styledElement = m_element && m_element->isStyledElement() ? static_cast<StyledElement*>(m_element) : 0;
819         m_elementLinkState = m_checker.determineLinkState(m_element);
820     }
821 }
822
823 inline void CSSStyleSelector::initForStyleResolve(Element* e, RenderStyle* parentStyle, PseudoId pseudoID)
824 {
825     m_checker.m_pseudoStyle = pseudoID;
826
827     m_parentNode = e ? e->parentNode() : 0;
828
829 #if ENABLE(SVG)
830     if (!m_parentNode && e && e->isSVGElement() && e->isShadowNode())
831         m_parentNode = e->shadowParentNode();
832 #endif
833
834     if (parentStyle)
835         m_parentStyle = parentStyle;
836     else
837         m_parentStyle = m_parentNode ? m_parentNode->renderStyle() : 0;
838
839     Node* docElement = e ? e->document()->documentElement() : 0;
840     RenderStyle* docStyle = m_checker.m_document->renderStyle();
841     m_rootElementStyle = docElement && e != docElement ? docElement->renderStyle() : docStyle;
842
843     m_style = 0;
844
845     m_matchedDecls.clear();
846
847     m_pendingImageProperties.clear();
848
849     m_ruleList = 0;
850
851     m_fontDirty = false;
852 }
853
854 static inline const AtomicString* linkAttribute(Node* node)
855 {
856     if (!node->isLink())
857         return 0;
858
859     ASSERT(node->isElementNode());
860     Element* element = static_cast<Element*>(node);
861     if (element->isHTMLElement())
862         return &element->fastGetAttribute(hrefAttr);
863
864 #if ENABLE(WML)
865     if (element->isWMLElement()) {
866         // <anchor> elements don't have href attributes, but we still want to
867         // appear as link, so linkAttribute() has to return a non-null value!
868         if (element->hasTagName(WMLNames::anchorTag))
869             return &emptyAtom;
870
871         return &element->fastGetAttribute(hrefAttr);
872     }
873 #endif
874
875 #if ENABLE(SVG)
876     if (element->isSVGElement())
877         return &element->fastGetAttribute(XLinkNames::hrefAttr);
878 #endif
879
880     return 0;
881 }
882
883 CSSStyleSelector::SelectorChecker::SelectorChecker(Document* document, bool strictParsing)
884     : m_document(document)
885     , m_strictParsing(strictParsing)
886     , m_collectRulesOnly(false)
887     , m_pseudoStyle(NOPSEUDO)
888     , m_documentIsHTML(document->isHTMLDocument())
889     , m_matchVisitedPseudoClass(false)
890 {
891 }
892
893 EInsideLink CSSStyleSelector::SelectorChecker::determineLinkStateSlowCase(Element* element) const
894 {
895     ASSERT(element->isLink());
896     
897     const AtomicString* attr = linkAttribute(element);
898     if (!attr || attr->isNull())
899         return NotInsideLink;
900
901 #if PLATFORM(QT)
902     Vector<UChar, 512> url;
903     visitedURL(m_document->baseURL(), *attr, url);
904     if (url.isEmpty())
905         return InsideUnvisitedLink;
906
907     // If the Qt4.4 interface for the history is used, we will have to fallback
908     // to the old global history.
909     QWebHistoryInterface* iface = QWebHistoryInterface::defaultInterface();
910     if (iface)
911         return iface->historyContains(QString(reinterpret_cast<QChar*>(url.data()), url.size())) ? InsideVisitedLink : InsideUnvisitedLink;
912
913     LinkHash hash = visitedLinkHash(url.data(), url.size());
914     if (!hash)
915         return InsideUnvisitedLink;
916 #else
917     LinkHash hash = visitedLinkHash(m_document->baseURL(), *attr);
918     if (!hash)
919         return InsideUnvisitedLink;
920 #endif
921
922     Frame* frame = m_document->frame();
923     if (!frame)
924         return InsideUnvisitedLink;
925
926     Page* page = frame->page();
927     if (!page)
928         return InsideUnvisitedLink;
929
930     m_linksCheckedForVisitedState.add(hash);
931
932 #if USE(PLATFORM_STRATEGIES)
933     return platformStrategies()->visitedLinkStrategy()->isLinkVisited(page, hash) ? InsideVisitedLink : InsideUnvisitedLink;
934 #else
935     return page->group().isLinkVisited(hash) ? InsideVisitedLink : InsideUnvisitedLink;
936 #endif
937 }
938
939 bool CSSStyleSelector::SelectorChecker::checkSelector(CSSSelector* sel, Element* element) const
940 {
941     PseudoId dynamicPseudo = NOPSEUDO;
942     return checkSelector(sel, element, 0, dynamicPseudo, false, false) == SelectorMatches;
943 }
944
945 static const unsigned cStyleSearchThreshold = 10;
946
947 Node* CSSStyleSelector::locateCousinList(Element* parent, unsigned depth)
948 {
949     if (parent && parent->isStyledElement()) {
950         StyledElement* p = static_cast<StyledElement*>(parent);
951         if (!p->inlineStyleDecl() && !p->hasID()) {
952             Node* r = p->previousSibling();
953             unsigned subcount = 0;
954             RenderStyle* st = p->renderStyle();
955             while (r) {
956                 if (r->renderStyle() == st)
957                     return r->lastChild();
958                 if (subcount++ == cStyleSearchThreshold)
959                     return 0;
960                 r = r->previousSibling();
961             }
962             if (!r && depth < cStyleSearchThreshold)
963                 r = locateCousinList(parent->parentElement(), depth + 1);
964             while (r) {
965                 if (r->renderStyle() == st)
966                     return r->lastChild();
967                 if (subcount++ == cStyleSearchThreshold)
968                     return 0;
969                 r = r->previousSibling();
970             }
971         }
972     }
973     return 0;
974 }
975
976 bool CSSStyleSelector::canShareStyleWithElement(Node* n)
977 {
978     if (n->isStyledElement()) {
979         StyledElement* s = static_cast<StyledElement*>(n);
980         RenderStyle* style = s->renderStyle();
981         if (style && !style->unique() &&
982             (s->tagQName() == m_element->tagQName()) && !s->hasID() &&
983             (s->hasClass() == m_element->hasClass()) && !s->inlineStyleDecl() &&
984             (s->hasMappedAttributes() == m_styledElement->hasMappedAttributes()) &&
985             (s->isLink() == m_element->isLink()) && 
986             !style->affectedByAttributeSelectors() &&
987             (s->hovered() == m_element->hovered()) &&
988             (s->active() == m_element->active()) &&
989             (s->focused() == m_element->focused()) &&
990             (s != s->document()->cssTarget() && m_element != m_element->document()->cssTarget()) &&
991             (s->fastGetAttribute(typeAttr) == m_element->fastGetAttribute(typeAttr)) &&
992             (s->fastGetAttribute(XMLNames::langAttr) == m_element->fastGetAttribute(XMLNames::langAttr)) &&
993             (s->fastGetAttribute(langAttr) == m_element->fastGetAttribute(langAttr)) &&
994             (s->fastGetAttribute(readonlyAttr) == m_element->fastGetAttribute(readonlyAttr)) &&
995             (s->fastGetAttribute(cellpaddingAttr) == m_element->fastGetAttribute(cellpaddingAttr))) {
996             bool isControl = s->isFormControlElement();
997             if (isControl != m_element->isFormControlElement())
998                 return false;
999             if (isControl) {
1000                 InputElement* thisInputElement = toInputElement(s);
1001                 InputElement* otherInputElement = toInputElement(m_element);
1002                 if (thisInputElement && otherInputElement) {
1003                     if ((thisInputElement->isAutofilled() != otherInputElement->isAutofilled()) ||
1004                         (thisInputElement->isChecked() != otherInputElement->isChecked()) ||
1005                         (thisInputElement->isIndeterminate() != otherInputElement->isIndeterminate()))
1006                     return false;
1007                 } else
1008                     return false;
1009
1010                 if (s->isEnabledFormControl() != m_element->isEnabledFormControl())
1011                     return false;
1012
1013                 if (s->isDefaultButtonForForm() != m_element->isDefaultButtonForForm())
1014                     return false;
1015                 
1016                 if (!m_element->document()->containsValidityStyleRules())
1017                     return false;
1018                 
1019                 bool willValidate = s->willValidate();
1020                 if (willValidate != m_element->willValidate())
1021                     return false;
1022                 
1023                 if (willValidate && (s->isValidFormControlElement() != m_element->isValidFormControlElement()))
1024                     return false;
1025             }
1026
1027             if (style->transitions() || style->animations())
1028                 return false;
1029
1030             bool classesMatch = true;
1031             if (s->hasClass()) {
1032                 const AtomicString& class1 = m_element->fastGetAttribute(classAttr);
1033                 const AtomicString& class2 = s->fastGetAttribute(classAttr);
1034                 classesMatch = (class1 == class2);
1035             }
1036             
1037             if (classesMatch) {
1038                 bool mappedAttrsMatch = true;
1039                 if (s->hasMappedAttributes())
1040                     mappedAttrsMatch = s->attributeMap()->mappedMapsEquivalent(m_styledElement->attributeMap());
1041                 if (mappedAttrsMatch) {
1042                     if (s->isLink()) {
1043                         if (m_elementLinkState != style->insideLink())
1044                             return false;
1045                     }
1046                     return true;
1047                 }
1048             }
1049         }
1050     }
1051     return false;
1052 }
1053
1054 ALWAYS_INLINE RenderStyle* CSSStyleSelector::locateSharedStyle()
1055 {
1056     if (m_styledElement && !m_styledElement->inlineStyleDecl() && !m_styledElement->hasID() && !m_styledElement->document()->usesSiblingRules()) {
1057         // Check previous siblings.
1058         unsigned count = 0;
1059         Node* n;
1060         for (n = m_element->previousSibling(); n && !n->isElementNode(); n = n->previousSibling()) { }
1061         while (n) {
1062             if (canShareStyleWithElement(n))
1063                 return n->renderStyle();
1064             if (count++ == cStyleSearchThreshold)
1065                 return 0;
1066             for (n = n->previousSibling(); n && !n->isElementNode(); n = n->previousSibling()) { }
1067         }
1068         if (!n) 
1069             n = locateCousinList(m_element->parentElement());
1070         while (n) {
1071             if (canShareStyleWithElement(n))
1072                 return n->renderStyle();
1073             if (count++ == cStyleSearchThreshold)
1074                 return 0;
1075             for (n = n->previousSibling(); n && !n->isElementNode(); n = n->previousSibling()) { }
1076         }        
1077     }
1078     return 0;
1079 }
1080
1081 void CSSStyleSelector::matchUARules(int& firstUARule, int& lastUARule)
1082 {
1083     // First we match rules from the user agent sheet.
1084     CSSRuleSet* userAgentStyleSheet = m_medium->mediaTypeMatchSpecific("print")
1085         ? defaultPrintStyle : defaultStyle;
1086     matchRules(userAgentStyleSheet, firstUARule, lastUARule, false);
1087
1088     // In quirks mode, we match rules from the quirks user agent sheet.
1089     if (!m_checker.m_strictParsing)
1090         matchRules(defaultQuirksStyle, firstUARule, lastUARule, false);
1091         
1092     // If we're in view source mode, then we match rules from the view source style sheet.
1093     if (m_checker.m_document->frame() && m_checker.m_document->frame()->inViewSourceMode()) {
1094         if (!defaultViewSourceStyle)
1095             loadViewSourceStyle();
1096         matchRules(defaultViewSourceStyle, firstUARule, lastUARule, false);
1097     }
1098 }
1099
1100 PassRefPtr<RenderStyle> CSSStyleSelector::styleForDocument(Document* document)
1101 {
1102     Frame* frame = document->frame();
1103
1104     RefPtr<RenderStyle> documentStyle = RenderStyle::create();
1105     documentStyle->setDisplay(BLOCK);
1106     documentStyle->setVisuallyOrdered(document->visuallyOrdered());
1107     documentStyle->setZoom(frame ? frame->pageZoomFactor() : 1);
1108     
1109     Element* docElement = document->documentElement();
1110     if (docElement && docElement->renderer()) {
1111         // Use the direction and block-flow of the document element to set the
1112         // viewport's direction and block-flow.
1113         documentStyle->setWritingMode(docElement->renderer()->style()->writingMode());
1114         documentStyle->setDirection(docElement->renderer()->style()->direction());
1115     }
1116
1117     FontDescription fontDescription;
1118     fontDescription.setUsePrinterFont(document->printing());
1119     if (Settings* settings = document->settings()) {
1120         fontDescription.setRenderingMode(settings->fontRenderingMode());
1121         if (document->printing() && !settings->shouldPrintBackgrounds())
1122             documentStyle->setForceBackgroundsToWhite(true);
1123         const AtomicString& stdfont = settings->standardFontFamily();
1124         if (!stdfont.isEmpty()) {
1125             fontDescription.firstFamily().setFamily(stdfont);
1126             fontDescription.firstFamily().appendFamily(0);
1127         }
1128         fontDescription.setKeywordSize(CSSValueMedium - CSSValueXxSmall + 1);
1129         int size = CSSStyleSelector::fontSizeForKeyword(document, CSSValueMedium, false);
1130         fontDescription.setSpecifiedSize(size);
1131         bool useSVGZoomRules = document->isSVGDocument();
1132         fontDescription.setComputedSize(CSSStyleSelector::getComputedSizeFromSpecifiedSize(document, documentStyle.get(), fontDescription.isAbsoluteSize(), size, useSVGZoomRules));
1133     }
1134
1135     documentStyle->setFontDescription(fontDescription);
1136     documentStyle->font().update(0);
1137         
1138     return documentStyle.release();
1139 }
1140
1141 // If resolveForRootDefault is true, style based on user agent style sheet only. This is used in media queries, where
1142 // relative units are interpreted according to document root element style, styled only with UA stylesheet
1143
1144 PassRefPtr<RenderStyle> CSSStyleSelector::styleForElement(Element* e, RenderStyle* defaultParent, bool allowSharing, bool resolveForRootDefault, bool matchVisitedPseudoClass)
1145 {
1146     // Once an element has a renderer, we don't try to destroy it, since otherwise the renderer
1147     // will vanish if a style recalc happens during loading.
1148     if (allowSharing && !e->document()->haveStylesheetsLoaded() && !e->renderer()) {
1149         if (!s_styleNotYetAvailable) {
1150             s_styleNotYetAvailable = RenderStyle::create().releaseRef();
1151             s_styleNotYetAvailable->ref();
1152             s_styleNotYetAvailable->setDisplay(NONE);
1153             s_styleNotYetAvailable->font().update(m_fontSelector);
1154         }
1155         s_styleNotYetAvailable->ref();
1156         e->document()->setHasNodesWithPlaceholderStyle();
1157         return s_styleNotYetAvailable;
1158     }
1159
1160     initElement(e);
1161     if (allowSharing) {
1162         RenderStyle* sharedStyle = locateSharedStyle();
1163         if (sharedStyle)
1164             return sharedStyle;
1165     }
1166     initForStyleResolve(e, defaultParent);
1167
1168     // Compute our style allowing :visited to match first.
1169     RefPtr<RenderStyle> visitedStyle;
1170     if (!matchVisitedPseudoClass && m_parentStyle && (m_parentStyle->insideLink() || e->isLink()) && e->document()->usesLinkRules()) {
1171         // Fetch our parent style.
1172         RenderStyle* parentStyle = m_parentStyle;
1173         if (!e->isLink()) {
1174             // Use the parent's visited style if one exists.
1175             RenderStyle* parentVisitedStyle = m_parentStyle->getCachedPseudoStyle(VISITED_LINK);
1176             if (parentVisitedStyle)
1177                 parentStyle = parentVisitedStyle;
1178         }
1179         visitedStyle = styleForElement(e, parentStyle, false, false, true);
1180         if (visitedStyle) {
1181             if (m_elementLinkState == InsideUnvisitedLink)
1182                 visitedStyle = 0;  // We made the style to avoid timing attacks. Just throw it away now that we did that, since we don't need it.
1183             else
1184                 visitedStyle->setStyleType(VISITED_LINK);
1185         }
1186         initForStyleResolve(e, defaultParent);
1187     }
1188
1189     m_checker.m_matchVisitedPseudoClass = matchVisitedPseudoClass;
1190
1191     m_style = RenderStyle::create();
1192
1193     if (m_parentStyle)
1194         m_style->inheritFrom(m_parentStyle);
1195     else
1196         m_parentStyle = style();
1197
1198     if (e->isLink()) {
1199         m_style->setIsLink(true);
1200         m_style->setInsideLink(m_elementLinkState);
1201     }
1202     
1203     if (simpleDefaultStyleSheet && !elementCanUseSimpleDefaultStyle(e))
1204         loadFullDefaultStyle();
1205
1206 #if ENABLE(SVG)
1207     static bool loadedSVGUserAgentSheet;
1208     if (e->isSVGElement() && !loadedSVGUserAgentSheet) {
1209         // SVG rules.
1210         loadedSVGUserAgentSheet = true;
1211         CSSStyleSheet* svgSheet = parseUASheet(svgUserAgentStyleSheet, sizeof(svgUserAgentStyleSheet));
1212         defaultStyle->addRulesFromSheet(svgSheet, screenEval());
1213         defaultPrintStyle->addRulesFromSheet(svgSheet, printEval());
1214     }
1215 #endif
1216
1217 #if ENABLE(MATHML)
1218     static bool loadedMathMLUserAgentSheet;
1219     if (e->isMathMLElement() && !loadedMathMLUserAgentSheet) {
1220         // MathML rules.
1221         loadedMathMLUserAgentSheet = true;
1222         CSSStyleSheet* mathMLSheet = parseUASheet(mathmlUserAgentStyleSheet, sizeof(mathmlUserAgentStyleSheet));
1223         defaultStyle->addRulesFromSheet(mathMLSheet, screenEval());
1224         defaultPrintStyle->addRulesFromSheet(mathMLSheet, printEval());
1225     }
1226 #endif
1227
1228 #if ENABLE(WML)
1229     static bool loadedWMLUserAgentSheet;
1230     if (e->isWMLElement() && !loadedWMLUserAgentSheet) {
1231         // WML rules.
1232         loadedWMLUserAgentSheet = true;
1233         CSSStyleSheet* wmlSheet = parseUASheet(wmlUserAgentStyleSheet, sizeof(wmlUserAgentStyleSheet));
1234         defaultStyle->addRulesFromSheet(wmlSheet, screenEval());
1235         defaultPrintStyle->addRulesFromSheet(wmlSheet, printEval());
1236     }
1237 #endif
1238
1239 #if ENABLE(VIDEO)
1240     static bool loadedMediaStyleSheet;
1241     if (!loadedMediaStyleSheet && (e->hasTagName(videoTag) || e->hasTagName(audioTag))) {
1242         loadedMediaStyleSheet = true;
1243         String mediaRules = String(mediaControlsUserAgentStyleSheet, sizeof(mediaControlsUserAgentStyleSheet)) + RenderTheme::defaultTheme()->extraMediaControlsStyleSheet();
1244         CSSStyleSheet* mediaControlsSheet = parseUASheet(mediaRules);
1245         defaultStyle->addRulesFromSheet(mediaControlsSheet, screenEval());
1246         defaultPrintStyle->addRulesFromSheet(mediaControlsSheet, printEval());
1247     }
1248 #endif
1249
1250     int firstUARule = -1, lastUARule = -1;
1251     int firstUserRule = -1, lastUserRule = -1;
1252     int firstAuthorRule = -1, lastAuthorRule = -1;
1253     matchUARules(firstUARule, lastUARule);
1254
1255     if (!resolveForRootDefault) {
1256         // 4. Now we check user sheet rules.
1257         if (m_matchAuthorAndUserStyles)
1258             matchRules(m_userStyle.get(), firstUserRule, lastUserRule, false);
1259
1260         // 5. Now check author rules, beginning first with presentational attributes
1261         // mapped from HTML.
1262         if (m_styledElement) {
1263             // Ask if the HTML element has mapped attributes.
1264             if (m_styledElement->hasMappedAttributes()) {
1265                 // Walk our attribute list and add in each decl.
1266                 const NamedNodeMap* map = m_styledElement->attributeMap();
1267                 for (unsigned i = 0; i < map->length(); i++) {
1268                     Attribute* attr = map->attributeItem(i);
1269                     if (attr->isMappedAttribute() && attr->decl()) {
1270                         lastAuthorRule = m_matchedDecls.size();
1271                         if (firstAuthorRule == -1)
1272                             firstAuthorRule = lastAuthorRule;
1273                         addMatchedDeclaration(attr->decl());
1274                     }
1275                 }
1276             }
1277
1278             // Now we check additional mapped declarations.
1279             // Tables and table cells share an additional mapped rule that must be applied
1280             // after all attributes, since their mapped style depends on the values of multiple attributes.
1281             if (m_styledElement->canHaveAdditionalAttributeStyleDecls()) {
1282                 m_additionalAttributeStyleDecls.clear();
1283                 m_styledElement->additionalAttributeStyleDecls(m_additionalAttributeStyleDecls);
1284                 if (!m_additionalAttributeStyleDecls.isEmpty()) {
1285                     unsigned additionalDeclsSize = m_additionalAttributeStyleDecls.size();
1286                     if (firstAuthorRule == -1)
1287                         firstAuthorRule = m_matchedDecls.size();
1288                     lastAuthorRule = m_matchedDecls.size() + additionalDeclsSize - 1;
1289                     for (unsigned i = 0; i < additionalDeclsSize; i++)
1290                         addMatchedDeclaration(m_additionalAttributeStyleDecls[i]);
1291                 }
1292             }
1293         }
1294     
1295         // 6. Check the rules in author sheets next.
1296         if (m_matchAuthorAndUserStyles)
1297             matchRules(m_authorStyle.get(), firstAuthorRule, lastAuthorRule, false);
1298
1299         // 7. Now check our inline style attribute.
1300         if (m_matchAuthorAndUserStyles && m_styledElement) {
1301             CSSMutableStyleDeclaration* inlineDecl = m_styledElement->inlineStyleDecl();
1302             if (inlineDecl) {
1303                 lastAuthorRule = m_matchedDecls.size();
1304                 if (firstAuthorRule == -1)
1305                     firstAuthorRule = lastAuthorRule;
1306                 addMatchedDeclaration(inlineDecl);
1307             }
1308         }
1309     }
1310
1311     // Reset the value back before applying properties, so that -webkit-link knows what color to use.
1312     m_checker.m_matchVisitedPseudoClass = matchVisitedPseudoClass;
1313     
1314     // Now we have all of the matched rules in the appropriate order.  Walk the rules and apply
1315     // high-priority properties first, i.e., those properties that other properties depend on.
1316     // The order is (1) high-priority not important, (2) high-priority important, (3) normal not important
1317     // and (4) normal important.
1318     m_lineHeightValue = 0;
1319     applyDeclarations<true>(false, 0, m_matchedDecls.size() - 1);
1320     if (!resolveForRootDefault) {
1321         applyDeclarations<true>(true, firstAuthorRule, lastAuthorRule);
1322         applyDeclarations<true>(true, firstUserRule, lastUserRule);
1323     }
1324     applyDeclarations<true>(true, firstUARule, lastUARule);
1325     
1326     // If our font got dirtied, go ahead and update it now.
1327     if (m_fontDirty)
1328         updateFont();
1329
1330     // Line-height is set when we are sure we decided on the font-size
1331     if (m_lineHeightValue)
1332         applyProperty(CSSPropertyLineHeight, m_lineHeightValue);
1333
1334     // Now do the normal priority UA properties.
1335     applyDeclarations<false>(false, firstUARule, lastUARule);
1336     
1337     // Cache our border and background so that we can examine them later.
1338     cacheBorderAndBackground();
1339     
1340     // Now do the author and user normal priority properties and all the !important properties.
1341     if (!resolveForRootDefault) {
1342         applyDeclarations<false>(false, lastUARule + 1, m_matchedDecls.size() - 1);
1343         applyDeclarations<false>(true, firstAuthorRule, lastAuthorRule);
1344         applyDeclarations<false>(true, firstUserRule, lastUserRule);
1345     }
1346     applyDeclarations<false>(true, firstUARule, lastUARule);
1347
1348     ASSERT(!m_fontDirty);
1349     // If our font got dirtied by one of the non-essential font props, 
1350     // go ahead and update it a second time.
1351     if (m_fontDirty)
1352         updateFont();
1353     
1354     // Clean up our style object's display and text decorations (among other fixups).
1355     adjustRenderStyle(style(), m_parentStyle, e);
1356
1357     // Start loading images referenced by this style.
1358     loadPendingImages();
1359
1360     // If we have first-letter pseudo style, do not share this style
1361     if (m_style->hasPseudoStyle(FIRST_LETTER))
1362         m_style->setUnique();
1363
1364     if (visitedStyle) {
1365         // Copy any pseudo bits that the visited style has to the primary style so that
1366         // pseudo element styles will continue to work for pseudo elements inside :visited
1367         // links.
1368         for (unsigned pseudo = FIRST_PUBLIC_PSEUDOID; pseudo < FIRST_INTERNAL_PSEUDOID; ++pseudo) {
1369             if (visitedStyle->hasPseudoStyle(static_cast<PseudoId>(pseudo)))
1370                 m_style->setHasPseudoStyle(static_cast<PseudoId>(pseudo));
1371         }
1372         
1373         // Add the visited style off the main style.
1374         m_style->addCachedPseudoStyle(visitedStyle.release());
1375     }
1376
1377     if (!matchVisitedPseudoClass)
1378         initElement(0); // Clear out for the next resolve.
1379
1380     // Now return the style.
1381     return m_style.release();
1382 }
1383
1384 PassRefPtr<RenderStyle> CSSStyleSelector::styleForKeyframe(const RenderStyle* elementStyle, const WebKitCSSKeyframeRule* keyframeRule, KeyframeValue& keyframe)
1385 {
1386     if (keyframeRule->style())
1387         addMatchedDeclaration(keyframeRule->style());
1388
1389     ASSERT(!m_style);
1390
1391     // Create the style
1392     m_style = RenderStyle::clone(elementStyle);
1393
1394     m_lineHeightValue = 0;
1395
1396     // We don't need to bother with !important. Since there is only ever one
1397     // decl, there's nothing to override. So just add the first properties.
1398     if (keyframeRule->style())
1399         applyDeclarations<true>(false, 0, m_matchedDecls.size() - 1);
1400
1401     // If our font got dirtied, go ahead and update it now.
1402     if (m_fontDirty)
1403         updateFont();
1404
1405     // Line-height is set when we are sure we decided on the font-size
1406     if (m_lineHeightValue)
1407         applyProperty(CSSPropertyLineHeight, m_lineHeightValue);
1408
1409     // Now do rest of the properties.
1410     if (keyframeRule->style())
1411         applyDeclarations<false>(false, 0, m_matchedDecls.size() - 1);
1412
1413     // If our font got dirtied by one of the non-essential font props,
1414     // go ahead and update it a second time.
1415     if (m_fontDirty)
1416         updateFont();
1417
1418     // Start loading images referenced by this style.
1419     loadPendingImages();
1420
1421     // Add all the animating properties to the keyframe.
1422     if (keyframeRule->style()) {
1423         CSSMutableStyleDeclaration::const_iterator end = keyframeRule->style()->end();
1424         for (CSSMutableStyleDeclaration::const_iterator it = keyframeRule->style()->begin(); it != end; ++it) {
1425             int property = (*it).id();
1426             // Timing-function within keyframes is special, because it is not animated; it just
1427             // describes the timing function between this keyframe and the next.
1428             if (property != CSSPropertyWebkitAnimationTimingFunction)
1429                 keyframe.addProperty(property);
1430         }
1431     }
1432
1433     return m_style.release();
1434 }
1435
1436 void CSSStyleSelector::keyframeStylesForAnimation(Element* e, const RenderStyle* elementStyle, KeyframeList& list)
1437 {
1438     list.clear();
1439     
1440     // Get the keyframesRule for this name
1441     if (!e || list.animationName().isEmpty())
1442         return;
1443
1444     m_keyframesRuleMap.checkConsistency();
1445    
1446     if (!m_keyframesRuleMap.contains(list.animationName().impl()))
1447         return;
1448         
1449     const WebKitCSSKeyframesRule* rule = m_keyframesRuleMap.find(list.animationName().impl()).get()->second.get();
1450     
1451     // Construct and populate the style for each keyframe
1452     for (unsigned i = 0; i < rule->length(); ++i) {
1453         // Apply the declaration to the style. This is a simplified version of the logic in styleForElement
1454         initElement(e);
1455         initForStyleResolve(e);
1456         
1457         const WebKitCSSKeyframeRule* keyframeRule = rule->item(i);
1458
1459         KeyframeValue keyframe(0, 0);
1460         keyframe.setStyle(styleForKeyframe(elementStyle, keyframeRule, keyframe));
1461
1462         // Add this keyframe style to all the indicated key times
1463         Vector<float> keys;
1464         keyframeRule->getKeys(keys);
1465         for (size_t keyIndex = 0; keyIndex < keys.size(); ++keyIndex) {
1466             keyframe.setKey(keys[keyIndex]);
1467             list.insert(keyframe);
1468         }
1469     }
1470     
1471     // If the 0% keyframe is missing, create it (but only if there is at least one other keyframe)
1472     int initialListSize = list.size();
1473     if (initialListSize > 0 && list[0].key() != 0) {
1474         RefPtr<WebKitCSSKeyframeRule> keyframeRule = WebKitCSSKeyframeRule::create();
1475         keyframeRule->setKeyText("0%");
1476         KeyframeValue keyframe(0, 0);
1477         keyframe.setStyle(styleForKeyframe(elementStyle, keyframeRule.get(), keyframe));
1478         list.insert(keyframe);
1479     }
1480
1481     // If the 100% keyframe is missing, create it (but only if there is at least one other keyframe)
1482     if (initialListSize > 0 && (list[list.size() - 1].key() != 1)) {
1483         RefPtr<WebKitCSSKeyframeRule> keyframeRule = WebKitCSSKeyframeRule::create();
1484         keyframeRule->setKeyText("100%");
1485         KeyframeValue keyframe(1, 0);
1486         keyframe.setStyle(styleForKeyframe(elementStyle, keyframeRule.get(), keyframe));
1487         list.insert(keyframe);
1488     }
1489 }
1490
1491 PassRefPtr<RenderStyle> CSSStyleSelector::pseudoStyleForElement(PseudoId pseudo, Element* e, RenderStyle* parentStyle, bool matchVisitedPseudoClass)
1492 {
1493     if (!e)
1494         return 0;
1495
1496     initElement(e);
1497
1498     // Compute our :visited style first, so that we know whether or not we'll need to create a normal style just to hang it
1499     // off of.
1500     RefPtr<RenderStyle> visitedStyle;
1501     if (!matchVisitedPseudoClass && parentStyle && parentStyle->insideLink()) {
1502         // Fetch our parent style with :visited in effect.
1503         RenderStyle* parentVisitedStyle = parentStyle->getCachedPseudoStyle(VISITED_LINK);
1504         visitedStyle = pseudoStyleForElement(pseudo, e, parentVisitedStyle ? parentVisitedStyle : parentStyle, true);
1505         if (visitedStyle) {
1506             if (m_elementLinkState == InsideUnvisitedLink)
1507                 visitedStyle = 0;  // We made the style to avoid timing attacks. Just throw it away now that we did that.
1508             else
1509                 visitedStyle->setStyleType(VISITED_LINK);
1510         }
1511     }
1512
1513     initForStyleResolve(e, parentStyle, pseudo);
1514     m_style = RenderStyle::create();
1515     if (parentStyle)
1516         m_style->inheritFrom(parentStyle);
1517
1518     m_checker.m_matchVisitedPseudoClass = matchVisitedPseudoClass;
1519
1520     // Since we don't use pseudo-elements in any of our quirk/print user agent rules, don't waste time walking
1521     // those rules.
1522     
1523     // Check UA, user and author rules.
1524     int firstUARule = -1, lastUARule = -1, firstUserRule = -1, lastUserRule = -1, firstAuthorRule = -1, lastAuthorRule = -1;
1525     matchUARules(firstUARule, lastUARule);
1526
1527     if (m_matchAuthorAndUserStyles) {
1528         matchRules(m_userStyle.get(), firstUserRule, lastUserRule, false);
1529         matchRules(m_authorStyle.get(), firstAuthorRule, lastAuthorRule, false);
1530     }
1531
1532     if (m_matchedDecls.isEmpty() && !visitedStyle)
1533         return 0;
1534
1535     m_style->setStyleType(pseudo);
1536     
1537     m_lineHeightValue = 0;
1538     
1539     // Reset the value back before applying properties, so that -webkit-link knows what color to use.
1540     m_checker.m_matchVisitedPseudoClass = matchVisitedPseudoClass;
1541
1542     // High-priority properties.
1543     applyDeclarations<true>(false, 0, m_matchedDecls.size() - 1);
1544     applyDeclarations<true>(true, firstAuthorRule, lastAuthorRule);
1545     applyDeclarations<true>(true, firstUserRule, lastUserRule);
1546     applyDeclarations<true>(true, firstUARule, lastUARule);
1547     
1548     // If our font got dirtied, go ahead and update it now.
1549     if (m_fontDirty)
1550         updateFont();
1551
1552     // Line-height is set when we are sure we decided on the font-size
1553     if (m_lineHeightValue)
1554         applyProperty(CSSPropertyLineHeight, m_lineHeightValue);
1555     
1556     // Now do the normal priority properties.
1557     applyDeclarations<false>(false, firstUARule, lastUARule);
1558     
1559     // Cache our border and background so that we can examine them later.
1560     cacheBorderAndBackground();
1561     
1562     applyDeclarations<false>(false, lastUARule + 1, m_matchedDecls.size() - 1);
1563     applyDeclarations<false>(true, firstAuthorRule, lastAuthorRule);
1564     applyDeclarations<false>(true, firstUserRule, lastUserRule);
1565     applyDeclarations<false>(true, firstUARule, lastUARule);
1566     
1567     // If our font got dirtied by one of the non-essential font props, 
1568     // go ahead and update it a second time.
1569     if (m_fontDirty)
1570         updateFont();
1571
1572     // Clean up our style object's display and text decorations (among other fixups).
1573     adjustRenderStyle(style(), parentStyle, 0);
1574
1575     // Start loading images referenced by this style.
1576     loadPendingImages();
1577
1578     // Hang our visited style off m_style.
1579     if (visitedStyle)
1580         m_style->addCachedPseudoStyle(visitedStyle.release());
1581         
1582     // Now return the style.
1583     return m_style.release();
1584 }
1585
1586 PassRefPtr<RenderStyle> CSSStyleSelector::styleForPage(int pageIndex)
1587 {
1588     initForStyleResolve(m_checker.m_document->body());
1589
1590     m_style = RenderStyle::create();
1591     m_style->inheritFrom(m_rootElementStyle);
1592
1593     const bool isLeft = isLeftPage(pageIndex);
1594     const bool isFirst = isFirstPage(pageIndex);
1595     const String page = pageName(pageIndex);
1596     matchPageRules(defaultPrintStyle, isLeft, isFirst, page);
1597     matchPageRules(m_userStyle.get(), isLeft, isFirst, page);
1598     matchPageRules(m_authorStyle.get(), isLeft, isFirst, page);
1599     m_lineHeightValue = 0;
1600     applyDeclarations<true>(false, 0, m_matchedDecls.size() - 1);
1601
1602     // If our font got dirtied, go ahead and update it now.
1603     if (m_fontDirty)
1604         updateFont();
1605
1606     // Line-height is set when we are sure we decided on the font-size
1607     if (m_lineHeightValue)
1608         applyProperty(CSSPropertyLineHeight, m_lineHeightValue);
1609
1610     applyDeclarations<false>(false, 0, m_matchedDecls.size() - 1);
1611
1612     // Start loading images referenced by this style.
1613     loadPendingImages();
1614
1615     // Now return the style.
1616     return m_style.release();
1617 }
1618
1619 #if ENABLE(DATAGRID)
1620
1621 PassRefPtr<RenderStyle> CSSStyleSelector::pseudoStyleForDataGridColumn(DataGridColumn*, RenderStyle*)
1622 {
1623     // FIXME: Implement
1624     return 0;
1625 }
1626
1627 PassRefPtr<RenderStyle> CSSStyleSelector::pseudoStyleForDataGridColumnHeader(DataGridColumn*, RenderStyle*)
1628 {
1629     // FIXME: Implement
1630     return 0;
1631 }
1632
1633 #endif
1634
1635 static void addIntrinsicMargins(RenderStyle* style)
1636 {
1637     // Intrinsic margin value.
1638     const int intrinsicMargin = 2 * style->effectiveZoom();
1639     
1640     // FIXME: Using width/height alone and not also dealing with min-width/max-width is flawed.
1641     // FIXME: Using "quirk" to decide the margin wasn't set is kind of lame.
1642     if (style->width().isIntrinsicOrAuto()) {
1643         if (style->marginLeft().quirk())
1644             style->setMarginLeft(Length(intrinsicMargin, Fixed));
1645         if (style->marginRight().quirk())
1646             style->setMarginRight(Length(intrinsicMargin, Fixed));
1647     }
1648
1649     if (style->height().isAuto()) {
1650         if (style->marginTop().quirk())
1651             style->setMarginTop(Length(intrinsicMargin, Fixed));
1652         if (style->marginBottom().quirk())
1653             style->setMarginBottom(Length(intrinsicMargin, Fixed));
1654     }
1655 }
1656
1657 void CSSStyleSelector::adjustRenderStyle(RenderStyle* style, RenderStyle* parentStyle, Element *e)
1658 {
1659     // Cache our original display.
1660     style->setOriginalDisplay(style->display());
1661
1662     if (style->display() != NONE) {
1663         // If we have a <td> that specifies a float property, in quirks mode we just drop the float
1664         // property.
1665         // Sites also commonly use display:inline/block on <td>s and <table>s.  In quirks mode we force
1666         // these tags to retain their display types.
1667         if (!m_checker.m_strictParsing && e) {
1668             if (e->hasTagName(tdTag)) {
1669                 style->setDisplay(TABLE_CELL);
1670                 style->setFloating(FNONE);
1671             }
1672             else if (e->hasTagName(tableTag))
1673                 style->setDisplay(style->isDisplayInlineType() ? INLINE_TABLE : TABLE);
1674         }
1675
1676         if (e && (e->hasTagName(tdTag) || e->hasTagName(thTag))) {
1677             if (style->whiteSpace() == KHTML_NOWRAP) {
1678                 // Figure out if we are really nowrapping or if we should just
1679                 // use normal instead.  If the width of the cell is fixed, then
1680                 // we don't actually use NOWRAP.
1681                 if (style->width().isFixed())
1682                     style->setWhiteSpace(NORMAL);
1683                 else
1684                     style->setWhiteSpace(NOWRAP);
1685             }
1686         }
1687
1688         // Tables never support the -webkit-* values for text-align and will reset back to the default.
1689         if (e && e->hasTagName(tableTag) && (style->textAlign() == WEBKIT_LEFT || style->textAlign() == WEBKIT_CENTER || style->textAlign() == WEBKIT_RIGHT))
1690             style->setTextAlign(TAAUTO);
1691
1692         // Frames and framesets never honor position:relative or position:absolute.  This is necessary to
1693         // fix a crash where a site tries to position these objects.  They also never honor display.
1694         if (e && (e->hasTagName(frameTag) || e->hasTagName(framesetTag))) {
1695             style->setPosition(StaticPosition);
1696             style->setDisplay(BLOCK);
1697         }
1698
1699         // Table headers with a text-align of auto will change the text-align to center.
1700         if (e && e->hasTagName(thTag) && style->textAlign() == TAAUTO)
1701             style->setTextAlign(CENTER);
1702
1703         if (e && e->hasTagName(legendTag))
1704             style->setDisplay(BLOCK);
1705
1706         // Mutate the display to BLOCK or TABLE for certain cases, e.g., if someone attempts to
1707         // position or float an inline, compact, or run-in.  Cache the original display, since it
1708         // may be needed for positioned elements that have to compute their static normal flow
1709         // positions.  We also force inline-level roots to be block-level.
1710         if (style->display() != BLOCK && style->display() != TABLE && style->display() != BOX &&
1711             (style->position() == AbsolutePosition || style->position() == FixedPosition || style->floating() != FNONE ||
1712              (e && e->document()->documentElement() == e))) {
1713             if (style->display() == INLINE_TABLE)
1714                 style->setDisplay(TABLE);
1715             else if (style->display() == INLINE_BOX)
1716                 style->setDisplay(BOX);
1717             else if (style->display() == LIST_ITEM) {
1718                 // It is a WinIE bug that floated list items lose their bullets, so we'll emulate the quirk,
1719                 // but only in quirks mode.
1720                 if (!m_checker.m_strictParsing && style->floating() != FNONE)
1721                     style->setDisplay(BLOCK);
1722             }
1723             else
1724                 style->setDisplay(BLOCK);
1725         }
1726         
1727         // FIXME: Don't support this mutation for pseudo styles like first-letter or first-line, since it's not completely
1728         // clear how that should work.
1729         if (style->display() == INLINE && style->styleType() == NOPSEUDO && parentStyle && style->writingMode() != parentStyle->writingMode())
1730             style->setDisplay(INLINE_BLOCK);
1731         
1732         // After performing the display mutation, check table rows.  We do not honor position:relative on
1733         // table rows or cells.  This has been established in CSS2.1 (and caused a crash in containingBlock()
1734         // on some sites).
1735         if ((style->display() == TABLE_HEADER_GROUP || style->display() == TABLE_ROW_GROUP ||
1736              style->display() == TABLE_FOOTER_GROUP || style->display() == TABLE_ROW || style->display() == TABLE_CELL) &&
1737              style->position() == RelativePosition)
1738             style->setPosition(StaticPosition);
1739         
1740         // FIXME: Since we don't support block-flow on either tables or flexible boxes yet, disallow setting
1741         // of block-flow to anything other than TopToBottomWritingMode.
1742         // https://bugs.webkit.org/show_bug.cgi?id=46417 - Tables support
1743         // https://bugs.webkit.org/show_bug.cgi?id=46418 - Flexible box support.
1744         if (style->writingMode() != TopToBottomWritingMode && (style->display() == TABLE || style->display() == INLINE_TABLE
1745             || style->display() == TABLE_HEADER_GROUP || style->display() == TABLE_ROW_GROUP
1746             || style->display() == TABLE_FOOTER_GROUP || style->display() == TABLE_ROW || style->display() == TABLE_CELL
1747             || style->display() == BOX || style->display() == INLINE_BOX))
1748             style->setWritingMode(TopToBottomWritingMode);
1749     }
1750
1751     // Make sure our z-index value is only applied if the object is positioned.
1752     if (style->position() == StaticPosition)
1753         style->setHasAutoZIndex();
1754
1755     // Auto z-index becomes 0 for the root element and transparent objects.  This prevents
1756     // cases where objects that should be blended as a single unit end up with a non-transparent
1757     // object wedged in between them.  Auto z-index also becomes 0 for objects that specify transforms/masks/reflections.
1758     if (style->hasAutoZIndex() && ((e && e->document()->documentElement() == e) || style->opacity() < 1.0f || 
1759         style->hasTransformRelatedProperty() || style->hasMask() || style->boxReflect()))
1760         style->setZIndex(0);
1761     
1762 #if ENABLE(WML)
1763     if (e && (e->hasTagName(WMLNames::insertedLegendTag)
1764               || e->hasTagName(WMLNames::inputTag))
1765             && style->width().isAuto())
1766         style->setWidth(Length(Intrinsic));
1767 #endif
1768
1769     // Textarea considers overflow visible as auto.
1770     if (e && e->hasTagName(textareaTag)) {
1771         style->setOverflowX(style->overflowX() == OVISIBLE ? OAUTO : style->overflowX());
1772         style->setOverflowY(style->overflowY() == OVISIBLE ? OAUTO : style->overflowY());
1773     }
1774
1775     // Finally update our text decorations in effect, but don't allow text-decoration to percolate through
1776     // tables, inline blocks, inline tables, or run-ins.
1777     if (style->display() == TABLE || style->display() == INLINE_TABLE || style->display() == RUN_IN
1778         || style->display() == INLINE_BLOCK || style->display() == INLINE_BOX)
1779         style->setTextDecorationsInEffect(style->textDecoration());
1780     else
1781         style->addToTextDecorationsInEffect(style->textDecoration());
1782     
1783     // If either overflow value is not visible, change to auto.
1784     if (style->overflowX() == OMARQUEE && style->overflowY() != OMARQUEE)
1785         style->setOverflowY(OMARQUEE);
1786     else if (style->overflowY() == OMARQUEE && style->overflowX() != OMARQUEE)
1787         style->setOverflowX(OMARQUEE);
1788     else if (style->overflowX() == OVISIBLE && style->overflowY() != OVISIBLE)
1789         style->setOverflowX(OAUTO);
1790     else if (style->overflowY() == OVISIBLE && style->overflowX() != OVISIBLE)
1791         style->setOverflowY(OAUTO);
1792
1793     // Table rows, sections and the table itself will support overflow:hidden and will ignore scroll/auto.
1794     // FIXME: Eventually table sections will support auto and scroll.
1795     if (style->display() == TABLE || style->display() == INLINE_TABLE ||
1796         style->display() == TABLE_ROW_GROUP || style->display() == TABLE_ROW) {
1797         if (style->overflowX() != OVISIBLE && style->overflowX() != OHIDDEN) 
1798             style->setOverflowX(OVISIBLE);
1799         if (style->overflowY() != OVISIBLE && style->overflowY() != OHIDDEN) 
1800             style->setOverflowY(OVISIBLE);
1801     }
1802
1803     // Menulists should have visible overflow
1804     if (style->appearance() == MenulistPart) {
1805         style->setOverflowX(OVISIBLE);
1806         style->setOverflowY(OVISIBLE);
1807     }
1808
1809     // Cull out any useless layers and also repeat patterns into additional layers.
1810     style->adjustBackgroundLayers();
1811     style->adjustMaskLayers();
1812
1813     // Do the same for animations and transitions.
1814     style->adjustAnimations();
1815     style->adjustTransitions();
1816
1817     // Important: Intrinsic margins get added to controls before the theme has adjusted the style, since the theme will
1818     // alter fonts and heights/widths.
1819     if (e && e->isFormControlElement() && style->fontSize() >= 11) {
1820         // Don't apply intrinsic margins to image buttons.  The designer knows how big the images are,
1821         // so we have to treat all image buttons as though they were explicitly sized.
1822         if (!e->hasTagName(inputTag) || !static_cast<HTMLInputElement*>(e)->isImageButton())
1823             addIntrinsicMargins(style);
1824     }
1825
1826     // Let the theme also have a crack at adjusting the style.
1827     if (style->hasAppearance())
1828         RenderTheme::defaultTheme()->adjustStyle(this, style, e, m_hasUAAppearance, m_borderData, m_backgroundData, m_backgroundColor);
1829
1830 #if ENABLE(SVG)
1831     if (e && e->isSVGElement()) {
1832         // Spec: http://www.w3.org/TR/SVG/masking.html#OverflowProperty
1833         if (style->overflowY() == OSCROLL)
1834             style->setOverflowY(OHIDDEN);
1835         else if (style->overflowY() == OAUTO)
1836             style->setOverflowY(OVISIBLE);
1837
1838         if (style->overflowX() == OSCROLL)
1839             style->setOverflowX(OHIDDEN);
1840         else if (style->overflowX() == OAUTO)
1841             style->setOverflowX(OVISIBLE);
1842
1843         // Only the root <svg> element in an SVG document fragment tree honors css position
1844         if (!(e->hasTagName(SVGNames::svgTag) && e->parentNode() && !e->parentNode()->isSVGElement()))
1845             style->setPosition(RenderStyle::initialPosition());
1846     }
1847 #endif
1848 }
1849
1850 void CSSStyleSelector::updateFont()
1851 {
1852     checkForTextSizeAdjust();
1853     checkForGenericFamilyChange(style(), m_parentStyle);
1854     checkForZoomChange(style(), m_parentStyle);
1855     m_style->font().update(m_fontSelector);
1856     m_fontDirty = false;
1857 }
1858
1859 void CSSStyleSelector::cacheBorderAndBackground()
1860 {
1861     m_hasUAAppearance = m_style->hasAppearance();
1862     if (m_hasUAAppearance) {
1863         m_borderData = m_style->border();
1864         m_backgroundData = *m_style->backgroundLayers();
1865         m_backgroundColor = m_style->backgroundColor();
1866     }
1867 }
1868
1869 PassRefPtr<CSSRuleList> CSSStyleSelector::styleRulesForElement(Element* e, bool authorOnly, bool includeEmptyRules)
1870 {
1871     return pseudoStyleRulesForElement(e, NOPSEUDO, authorOnly, includeEmptyRules);
1872 }
1873
1874 PassRefPtr<CSSRuleList> CSSStyleSelector::pseudoStyleRulesForElement(Element* e, PseudoId pseudoId, bool authorOnly, bool includeEmptyRules)
1875 {
1876     if (!e || !e->document()->haveStylesheetsLoaded())
1877         return 0;
1878
1879     m_checker.m_collectRulesOnly = true;
1880
1881     initElement(e);
1882     initForStyleResolve(e, 0, pseudoId);
1883
1884     if (!authorOnly) {
1885         int firstUARule = -1, lastUARule = -1;
1886         // First we match rules from the user agent sheet.
1887         matchUARules(firstUARule, lastUARule);
1888
1889         // Now we check user sheet rules.
1890         if (m_matchAuthorAndUserStyles) {
1891             int firstUserRule = -1, lastUserRule = -1;
1892             matchRules(m_userStyle.get(), firstUserRule, lastUserRule, includeEmptyRules);
1893         }
1894     }
1895
1896     if (m_matchAuthorAndUserStyles) {
1897         // Check the rules in author sheets.
1898         int firstAuthorRule = -1, lastAuthorRule = -1;
1899         matchRules(m_authorStyle.get(), firstAuthorRule, lastAuthorRule, includeEmptyRules);
1900     }
1901
1902     m_checker.m_collectRulesOnly = false;
1903     
1904     return m_ruleList.release();
1905 }
1906
1907 bool CSSStyleSelector::checkSelector(CSSSelector* sel)
1908 {
1909     m_dynamicPseudo = NOPSEUDO;
1910
1911     // Check the selector
1912     SelectorMatch match = m_checker.checkSelector(sel, m_element, &m_selectorAttrs, m_dynamicPseudo, false, false, style(), m_parentNode ? m_parentNode->renderStyle() : 0);
1913     if (match != SelectorMatches)
1914         return false;
1915
1916     if (m_checker.m_pseudoStyle != NOPSEUDO && m_checker.m_pseudoStyle != m_dynamicPseudo)
1917         return false;
1918
1919     return true;
1920 }
1921
1922 // Recursive check of selectors and combinators
1923 // It can return 3 different values:
1924 // * SelectorMatches         - the selector matches the element e
1925 // * SelectorFailsLocally    - the selector fails for the element e
1926 // * SelectorFailsCompletely - the selector fails for e and any sibling or ancestor of e
1927 CSSStyleSelector::SelectorMatch CSSStyleSelector::SelectorChecker::checkSelector(CSSSelector* sel, Element* e, HashSet<AtomicStringImpl*>* selectorAttrs, PseudoId& dynamicPseudo, bool isSubSelector, bool encounteredLink, RenderStyle* elementStyle, RenderStyle* elementParentStyle) const
1928 {
1929 #if ENABLE(SVG)
1930     // Spec: CSS2 selectors cannot be applied to the (conceptually) cloned DOM tree
1931     // because its contents are not part of the formal document structure.
1932     if (e->isSVGElement() && e->isShadowNode())
1933         return SelectorFailsCompletely;
1934 #endif
1935
1936     // first selector has to match
1937     if (!checkOneSelector(sel, e, selectorAttrs, dynamicPseudo, isSubSelector, elementStyle, elementParentStyle))
1938         return SelectorFailsLocally;
1939
1940     // The rest of the selectors has to match
1941     CSSSelector::Relation relation = sel->relation();
1942
1943     // Prepare next sel
1944     sel = sel->tagHistory();
1945     if (!sel)
1946         return SelectorMatches;
1947
1948     if (relation != CSSSelector::SubSelector)
1949         // Bail-out if this selector is irrelevant for the pseudoStyle
1950         if (m_pseudoStyle != NOPSEUDO && m_pseudoStyle != dynamicPseudo)
1951             return SelectorFailsCompletely;
1952
1953     // Check for nested links.
1954     if (m_matchVisitedPseudoClass && !isSubSelector) {
1955         RenderStyle* currentStyle = elementStyle ? elementStyle : e->renderStyle();
1956         if (currentStyle && currentStyle->insideLink() && e->isLink()) {
1957             if (encounteredLink)
1958                 m_matchVisitedPseudoClass = false; // This link is not relevant to the style being resolved, so disable matching.
1959             else
1960                 encounteredLink = true;
1961         }
1962     }
1963
1964     switch (relation) {
1965         case CSSSelector::Descendant:
1966             while (true) {
1967                 ContainerNode* n = e->parentNode();
1968                 if (!n || !n->isElementNode())
1969                     return SelectorFailsCompletely;
1970                 e = static_cast<Element*>(n);
1971                 SelectorMatch match = checkSelector(sel, e, selectorAttrs, dynamicPseudo, false, encounteredLink);
1972                 if (match != SelectorFailsLocally)
1973                     return match;
1974             }
1975             break;
1976         case CSSSelector::Child:
1977         {
1978             ContainerNode* n = e->parentNode();
1979             if (!n || !n->isElementNode())
1980                 return SelectorFailsCompletely;
1981             e = static_cast<Element*>(n);
1982             return checkSelector(sel, e, selectorAttrs, dynamicPseudo, false, encounteredLink);
1983         }
1984         case CSSSelector::DirectAdjacent:
1985         {
1986             if (!m_collectRulesOnly && e->parentNode() && e->parentNode()->isElementNode()) {
1987                 RenderStyle* parentStyle = elementStyle ? elementParentStyle : e->parentNode()->renderStyle();
1988                 if (parentStyle)
1989                     parentStyle->setChildrenAffectedByDirectAdjacentRules();
1990             }
1991             Node* n = e->previousSibling();
1992             while (n && !n->isElementNode())
1993                 n = n->previousSibling();
1994             if (!n)
1995                 return SelectorFailsLocally;
1996             e = static_cast<Element*>(n);
1997             m_matchVisitedPseudoClass = false;
1998             return checkSelector(sel, e, selectorAttrs, dynamicPseudo, false, encounteredLink); 
1999         }
2000         case CSSSelector::IndirectAdjacent:
2001             if (!m_collectRulesOnly && e->parentNode() && e->parentNode()->isElementNode()) {
2002                 RenderStyle* parentStyle = elementStyle ? elementParentStyle : e->parentNode()->renderStyle();
2003                 if (parentStyle)
2004                     parentStyle->setChildrenAffectedByForwardPositionalRules();
2005             }
2006             while (true) {
2007                 Node* n = e->previousSibling();
2008                 while (n && !n->isElementNode())
2009                     n = n->previousSibling();
2010                 if (!n)
2011                     return SelectorFailsLocally;
2012                 e = static_cast<Element*>(n);
2013                 m_matchVisitedPseudoClass = false;
2014                 SelectorMatch match = checkSelector(sel, e, selectorAttrs, dynamicPseudo, false, encounteredLink);
2015                 if (match != SelectorFailsLocally)
2016                     return match;
2017             };
2018             break;
2019         case CSSSelector::SubSelector:
2020             // a selector is invalid if something follows a pseudo-element
2021             // We make an exception for scrollbar pseudo elements and allow a set of pseudo classes (but nothing else)
2022             // to follow the pseudo elements.
2023             if ((elementStyle || m_collectRulesOnly) && dynamicPseudo != NOPSEUDO && dynamicPseudo != SELECTION &&
2024                 !((RenderScrollbar::scrollbarForStyleResolve() || dynamicPseudo == SCROLLBAR_CORNER || dynamicPseudo == RESIZER) && sel->m_match == CSSSelector::PseudoClass))
2025                 return SelectorFailsCompletely;
2026             return checkSelector(sel, e, selectorAttrs, dynamicPseudo, true, encounteredLink, elementStyle, elementParentStyle);
2027     }
2028
2029     return SelectorFailsCompletely;
2030 }
2031
2032 static void addLocalNameToSet(HashSet<AtomicStringImpl*>* set, const QualifiedName& qName)
2033 {
2034     set->add(qName.localName().impl());
2035 }
2036
2037 static HashSet<AtomicStringImpl*>* createHtmlCaseInsensitiveAttributesSet()
2038 {
2039     // This is the list of attributes in HTML 4.01 with values marked as "[CI]" or case-insensitive
2040     // Mozilla treats all other values as case-sensitive, thus so do we.
2041     HashSet<AtomicStringImpl*>* attrSet = new HashSet<AtomicStringImpl*>;
2042
2043     addLocalNameToSet(attrSet, accept_charsetAttr);
2044     addLocalNameToSet(attrSet, acceptAttr);
2045     addLocalNameToSet(attrSet, alignAttr);
2046     addLocalNameToSet(attrSet, alinkAttr);
2047     addLocalNameToSet(attrSet, axisAttr);
2048     addLocalNameToSet(attrSet, bgcolorAttr);
2049     addLocalNameToSet(attrSet, charsetAttr);
2050     addLocalNameToSet(attrSet, checkedAttr);
2051     addLocalNameToSet(attrSet, clearAttr);
2052     addLocalNameToSet(attrSet, codetypeAttr);
2053     addLocalNameToSet(attrSet, colorAttr);
2054     addLocalNameToSet(attrSet, compactAttr);
2055     addLocalNameToSet(attrSet, declareAttr);
2056     addLocalNameToSet(attrSet, deferAttr);
2057     addLocalNameToSet(attrSet, dirAttr);
2058     addLocalNameToSet(attrSet, disabledAttr);
2059     addLocalNameToSet(attrSet, enctypeAttr);
2060     addLocalNameToSet(attrSet, faceAttr);
2061     addLocalNameToSet(attrSet, frameAttr);
2062     addLocalNameToSet(attrSet, hreflangAttr);
2063     addLocalNameToSet(attrSet, http_equivAttr);
2064     addLocalNameToSet(attrSet, langAttr);
2065     addLocalNameToSet(attrSet, languageAttr);
2066     addLocalNameToSet(attrSet, linkAttr);
2067     addLocalNameToSet(attrSet, mediaAttr);
2068     addLocalNameToSet(attrSet, methodAttr);
2069     addLocalNameToSet(attrSet, multipleAttr);
2070     addLocalNameToSet(attrSet, nohrefAttr);
2071     addLocalNameToSet(attrSet, noresizeAttr);
2072     addLocalNameToSet(attrSet, noshadeAttr);
2073     addLocalNameToSet(attrSet, nowrapAttr);
2074     addLocalNameToSet(attrSet, readonlyAttr);
2075     addLocalNameToSet(attrSet, relAttr);
2076     addLocalNameToSet(attrSet, revAttr);
2077     addLocalNameToSet(attrSet, rulesAttr);
2078     addLocalNameToSet(attrSet, scopeAttr);
2079     addLocalNameToSet(attrSet, scrollingAttr);
2080     addLocalNameToSet(attrSet, selectedAttr);
2081     addLocalNameToSet(attrSet, shapeAttr);
2082     addLocalNameToSet(attrSet, targetAttr);
2083     addLocalNameToSet(attrSet, textAttr);
2084     addLocalNameToSet(attrSet, typeAttr);
2085     addLocalNameToSet(attrSet, valignAttr);
2086     addLocalNameToSet(attrSet, valuetypeAttr);
2087     addLocalNameToSet(attrSet, vlinkAttr);
2088
2089     return attrSet;
2090 }
2091
2092 static bool htmlAttributeHasCaseInsensitiveValue(const QualifiedName& attr)
2093 {
2094     static HashSet<AtomicStringImpl*>* htmlCaseInsensitiveAttributesSet = createHtmlCaseInsensitiveAttributesSet();
2095     bool isPossibleHTMLAttr = !attr.hasPrefix() && (attr.namespaceURI() == nullAtom);
2096     return isPossibleHTMLAttr && htmlCaseInsensitiveAttributesSet->contains(attr.localName().impl());
2097 }
2098
2099 bool CSSStyleSelector::SelectorChecker::checkOneSelector(CSSSelector* sel, Element* e, HashSet<AtomicStringImpl*>* selectorAttrs, PseudoId& dynamicPseudo, bool isSubSelector, RenderStyle* elementStyle, RenderStyle* elementParentStyle) const
2100 {
2101     if (!e)
2102         return false;
2103
2104     if (sel->hasTag()) {
2105         const AtomicString& selLocalName = sel->m_tag.localName();
2106         if (selLocalName != starAtom && selLocalName != e->localName())
2107             return false;
2108         const AtomicString& selNS = sel->m_tag.namespaceURI();
2109         if (selNS != starAtom && selNS != e->namespaceURI())
2110             return false;
2111     }
2112
2113     if (sel->hasAttribute()) {
2114         if (sel->m_match == CSSSelector::Class)
2115             return e->hasClass() && static_cast<StyledElement*>(e)->classNames().contains(sel->m_value);
2116
2117         if (sel->m_match == CSSSelector::Id)
2118             return e->hasID() && e->idForStyleResolution() == sel->m_value;
2119         
2120         const QualifiedName& attr = sel->attribute();
2121
2122         // FIXME: Handle the case were elementStyle is 0.
2123         if (elementStyle && (!e->isStyledElement() || (!static_cast<StyledElement*>(e)->isMappedAttribute(attr) && attr != typeAttr && attr != readonlyAttr))) {
2124             elementStyle->setAffectedByAttributeSelectors(); // Special-case the "type" and "readonly" attributes so input form controls can share style.
2125             if (selectorAttrs)
2126                 selectorAttrs->add(attr.localName().impl());
2127         }
2128
2129         const AtomicString& value = e->getAttribute(attr);
2130         if (value.isNull())
2131             return false; // attribute is not set
2132
2133         bool caseSensitive = !m_documentIsHTML || !htmlAttributeHasCaseInsensitiveValue(attr);
2134
2135         switch (sel->m_match) {
2136         case CSSSelector::Exact:
2137             if (caseSensitive ? sel->m_value != value : !equalIgnoringCase(sel->m_value, value))
2138                 return false;
2139             break;
2140         case CSSSelector::List:
2141         {
2142             // Ignore empty selectors or selectors containing spaces
2143             if (sel->m_value.contains(' ') || sel->m_value.isEmpty())
2144                 return false;
2145
2146             unsigned startSearchAt = 0;
2147             while (true) {
2148                 size_t foundPos = value.find(sel->m_value, startSearchAt, caseSensitive);
2149                 if (foundPos == notFound)
2150                     return false;
2151                 if (foundPos == 0 || value[foundPos - 1] == ' ') {
2152                     unsigned endStr = foundPos + sel->m_value.length();
2153                     if (endStr == value.length() || value[endStr] == ' ')
2154                         break; // We found a match.
2155                 }
2156                 
2157                 // No match. Keep looking.
2158                 startSearchAt = foundPos + 1;
2159             }
2160             break;
2161         }
2162         case CSSSelector::Contain:
2163             if (!value.contains(sel->m_value, caseSensitive) || sel->m_value.isEmpty())
2164                 return false;
2165             break;
2166         case CSSSelector::Begin:
2167             if (!value.startsWith(sel->m_value, caseSensitive) || sel->m_value.isEmpty())
2168                 return false;
2169             break;
2170         case CSSSelector::End:
2171             if (!value.endsWith(sel->m_value, caseSensitive) || sel->m_value.isEmpty())
2172                 return false;
2173             break;
2174         case CSSSelector::Hyphen:
2175             if (value.length() < sel->m_value.length())
2176                 return false;
2177             if (!value.startsWith(sel->m_value, caseSensitive))
2178                 return false;
2179             // It they start the same, check for exact match or following '-':
2180             if (value.length() != sel->m_value.length() && value[sel->m_value.length()] != '-')
2181                 return false;
2182             break;
2183         case CSSSelector::PseudoClass:
2184         case CSSSelector::PseudoElement:
2185         default:
2186             break;
2187         }
2188     }
2189     
2190     if (sel->m_match == CSSSelector::PseudoClass) {
2191         // Handle :not up front.
2192         if (sel->pseudoType() == CSSSelector::PseudoNot) {
2193             // check the simple selector
2194             for (CSSSelector* subSel = sel->simpleSelector(); subSel; subSel = subSel->tagHistory()) {
2195                 // :not cannot nest. I don't really know why this is a
2196                 // restriction in CSS3, but it is, so let's honor it.
2197                 // the parser enforces that this never occurs
2198                 ASSERT(!subSel->simpleSelector());
2199
2200                 if (!checkOneSelector(subSel, e, selectorAttrs, dynamicPseudo, true, elementStyle, elementParentStyle))
2201                     return true;
2202             }
2203         } else if (dynamicPseudo != NOPSEUDO && (RenderScrollbar::scrollbarForStyleResolve() || dynamicPseudo == SCROLLBAR_CORNER || dynamicPseudo == RESIZER)) {
2204             // CSS scrollbars match a specific subset of pseudo classes, and they have specialized rules for each
2205             // (since there are no elements involved).
2206             return checkScrollbarPseudoClass(sel, dynamicPseudo);
2207         } else if (dynamicPseudo == SELECTION) {
2208             if (sel->pseudoType() == CSSSelector::PseudoWindowInactive)
2209                 return !m_document->page()->focusController()->isActive();
2210         }
2211         
2212         // Normal element pseudo class checking.
2213         switch (sel->pseudoType()) {
2214             // Pseudo classes:
2215             case CSSSelector::PseudoNot:
2216                 break; // Already handled up above.
2217             case CSSSelector::PseudoEmpty: {
2218                 bool result = true;
2219                 for (Node* n = e->firstChild(); n; n = n->nextSibling()) {
2220                     if (n->isElementNode()) {
2221                         result = false;
2222                         break;
2223                     } else if (n->isTextNode()) {
2224                         Text* textNode = static_cast<Text*>(n);
2225                         if (!textNode->data().isEmpty()) {
2226                             result = false;
2227                             break;
2228                         }
2229                     }
2230                 }
2231                 if (!m_collectRulesOnly) {
2232                     if (elementStyle)
2233                         elementStyle->setEmptyState(result);
2234                     else if (e->renderStyle() && (e->document()->usesSiblingRules() || e->renderStyle()->unique()))
2235                         e->renderStyle()->setEmptyState(result);
2236                 }
2237                 return result;
2238             }
2239             case CSSSelector::PseudoFirstChild: {
2240                 // first-child matches the first child that is an element
2241                 if (e->parentNode() && e->parentNode()->isElementNode()) {
2242                     bool result = false;
2243                     Node* n = e->previousSibling();
2244                     while (n && !n->isElementNode())
2245                         n = n->previousSibling();
2246                     if (!n)
2247                         result = true;
2248                     if (!m_collectRulesOnly) {
2249                         RenderStyle* childStyle = elementStyle ? elementStyle : e->renderStyle();
2250                         RenderStyle* parentStyle = elementStyle ? elementParentStyle : e->parentNode()->renderStyle();
2251                         if (parentStyle)
2252                             parentStyle->setChildrenAffectedByFirstChildRules();
2253                         if (result && childStyle)
2254                             childStyle->setFirstChildState();
2255                     }
2256                     return result;
2257                 }
2258                 break;
2259             }
2260             case CSSSelector::PseudoFirstOfType: {
2261                 // first-of-type matches the first element of its type
2262                 if (e->parentNode() && e->parentNode()->isElementNode()) {
2263                     bool result = false;
2264                     const QualifiedName& type = e->tagQName();
2265                     Node* n = e->previousSibling();
2266                     while (n) {
2267                         if (n->isElementNode() && static_cast<Element*>(n)->hasTagName(type))
2268                             break;
2269                         n = n->previousSibling();
2270                     }
2271                     if (!n)
2272                         result = true;
2273                     if (!m_collectRulesOnly) {
2274                         RenderStyle* parentStyle = elementStyle ? elementParentStyle : e->parentNode()->renderStyle();
2275                         if (parentStyle)
2276                             parentStyle->setChildrenAffectedByForwardPositionalRules();
2277                     }
2278                     return result;
2279                 }
2280                 break;
2281             }
2282             case CSSSelector::PseudoLastChild: {
2283                 // last-child matches the last child that is an element
2284                 if (Element* parentElement = e->parentElement()) {
2285                     bool result = false;
2286                     if (parentElement->isFinishedParsingChildren()) {
2287                         Node* n = e->nextSibling();
2288                         while (n && !n->isElementNode())
2289                             n = n->nextSibling();
2290                         if (!n)
2291                             result = true;
2292                     }
2293                     if (!m_collectRulesOnly) {
2294                         RenderStyle* childStyle = elementStyle ? elementStyle : e->renderStyle();
2295                         RenderStyle* parentStyle = elementStyle ? elementParentStyle : parentElement->renderStyle();
2296                         if (parentStyle)
2297                             parentStyle->setChildrenAffectedByLastChildRules();
2298                         if (result && childStyle)
2299                             childStyle->setLastChildState();
2300                     }
2301                     return result;
2302                 }
2303                 break;
2304             }
2305             case CSSSelector::PseudoLastOfType: {
2306                 // last-of-type matches the last element of its type
2307                 if (Element* parentElement = e->parentElement()) {
2308                     if (!m_collectRulesOnly) {
2309                         RenderStyle* parentStyle = elementStyle ? elementParentStyle : parentElement->renderStyle();
2310                         if (parentStyle)
2311                             parentStyle->setChildrenAffectedByBackwardPositionalRules();
2312                     }
2313                     if (!parentElement->isFinishedParsingChildren())
2314                         return false;
2315                     bool result = false;
2316                     const QualifiedName& type = e->tagQName();
2317                     Node* n = e->nextSibling();
2318                     while (n) {
2319                         if (n->isElementNode() && static_cast<Element*>(n)->hasTagName(type))
2320                             break;
2321                         n = n->nextSibling();
2322                     }
2323                     if (!n)
2324                         result = true;
2325                     return result;
2326                 }
2327                 break;
2328             }
2329             case CSSSelector::PseudoOnlyChild: {
2330                 if (Element* parentElement = e->parentElement()) {
2331                     bool firstChild = false;
2332                     bool lastChild = false;
2333                     
2334                     Node* n = e->previousSibling();
2335                     while (n && !n->isElementNode())
2336                         n = n->previousSibling();
2337                     if (!n)
2338                         firstChild = true;
2339                     if (firstChild && parentElement->isFinishedParsingChildren()) {
2340                         n = e->nextSibling();
2341                         while (n && !n->isElementNode())
2342                             n = n->nextSibling();
2343                         if (!n)
2344                             lastChild = true;
2345                     }
2346                     if (!m_collectRulesOnly) {
2347                         RenderStyle* childStyle = elementStyle ? elementStyle : e->renderStyle();
2348                         RenderStyle* parentStyle = elementStyle ? elementParentStyle : parentElement->renderStyle();
2349                         if (parentStyle) {
2350                             parentStyle->setChildrenAffectedByFirstChildRules();
2351                             parentStyle->setChildrenAffectedByLastChildRules();
2352                         }
2353                         if (firstChild && childStyle)
2354                             childStyle->setFirstChildState();
2355                         if (lastChild && childStyle)
2356                             childStyle->setLastChildState();
2357                     }
2358                     return firstChild && lastChild;
2359                 }
2360                 break;
2361             }
2362             case CSSSelector::PseudoOnlyOfType: {
2363                 // FIXME: This selector is very slow.
2364                 if (Element* parentElement = e->parentElement()) {
2365                     if (!m_collectRulesOnly) {
2366                         RenderStyle* parentStyle = elementStyle ? elementParentStyle : parentElement->renderStyle();
2367                         if (parentStyle) {
2368                             parentStyle->setChildrenAffectedByForwardPositionalRules();
2369                             parentStyle->setChildrenAffectedByBackwardPositionalRules();
2370                         }
2371                     }
2372                     if (!parentElement->isFinishedParsingChildren())
2373                         return false;
2374                     bool firstChild = false;
2375                     bool lastChild = false;
2376                     const QualifiedName& type = e->tagQName();
2377                     Node* n = e->previousSibling();
2378                     while (n) {
2379                         if (n->isElementNode() && static_cast<Element*>(n)->hasTagName(type))
2380                             break;
2381                         n = n->previousSibling();
2382                     }
2383                     if (!n)
2384                         firstChild = true;
2385                     if (firstChild) {
2386                         n = e->nextSibling();
2387                         while (n) {
2388                             if (n->isElementNode() && static_cast<Element*>(n)->hasTagName(type))
2389                                 break;
2390                             n = n->nextSibling();
2391                         }
2392                         if (!n)
2393                             lastChild = true;
2394                     }
2395                     return firstChild && lastChild;
2396                 }
2397                 break;
2398             }
2399             case CSSSelector::PseudoNthChild: {
2400                 if (!sel->parseNth())
2401                     break;
2402                 if (Element* parentElement = e->parentElement()) {
2403                     int count = 1;
2404                     Node* n = e->previousSibling();
2405                     while (n) {
2406                         if (n->isElementNode()) {
2407                             RenderStyle* s = n->renderStyle();
2408                             unsigned index = s ? s->childIndex() : 0;
2409                             if (index) {
2410                                 count += index;
2411                                 break;
2412                             }
2413                             count++;
2414                         }
2415                         n = n->previousSibling();
2416                     }
2417                     
2418                     if (!m_collectRulesOnly) {
2419                         RenderStyle* childStyle = elementStyle ? elementStyle : e->renderStyle();
2420                         RenderStyle* parentStyle = elementStyle ? elementParentStyle : parentElement->renderStyle();
2421                         if (childStyle)
2422                             childStyle->setChildIndex(count);
2423                         if (parentStyle)
2424                             parentStyle->setChildrenAffectedByForwardPositionalRules();
2425                     }
2426                     
2427                     if (sel->matchNth(count))
2428                         return true;
2429                 }
2430                 break;
2431             }
2432             case CSSSelector::PseudoNthOfType: {
2433                 if (!sel->parseNth())
2434                     break;
2435                 if (Element* parentElement = e->parentElement()) {
2436                     int count = 1;
2437                     const QualifiedName& type = e->tagQName();
2438                     Node* n = e->previousSibling();
2439                     while (n) {
2440                         if (n->isElementNode() && static_cast<Element*>(n)->hasTagName(type))
2441                             count++;
2442                         n = n->previousSibling();
2443                     }
2444                     
2445                     if (!m_collectRulesOnly) {
2446                         RenderStyle* parentStyle = elementStyle ? elementParentStyle : parentElement->renderStyle();
2447                         if (parentStyle)
2448                             parentStyle->setChildrenAffectedByForwardPositionalRules();
2449                     }
2450
2451                     if (sel->matchNth(count))
2452                         return true;
2453                 }
2454                 break;
2455             }
2456             case CSSSelector::PseudoNthLastChild: {
2457                 if (!sel->parseNth())
2458                     break;
2459                 if (Element* parentElement = e->parentElement()) {
2460                     if (!m_collectRulesOnly) {
2461                         RenderStyle* parentStyle = elementStyle ? elementParentStyle : parentElement->renderStyle();
2462                         if (parentStyle)
2463                             parentStyle->setChildrenAffectedByBackwardPositionalRules();
2464                     }
2465                     if (!parentElement->isFinishedParsingChildren())
2466                         return false;
2467                     int count = 1;
2468                     Node* n = e->nextSibling();
2469                     while (n) {
2470                         if (n->isElementNode())
2471                             count++;
2472                         n = n->nextSibling();
2473                     }
2474                     if (sel->matchNth(count))
2475                         return true;
2476                 }
2477                 break;
2478             }
2479             case CSSSelector::PseudoNthLastOfType: {
2480                 if (!sel->parseNth())
2481                     break;
2482                 if (Element* parentElement = e->parentElement()) {
2483                     if (!m_collectRulesOnly) {
2484                         RenderStyle* parentStyle = elementStyle ? elementParentStyle : parentElement->renderStyle();
2485                         if (parentStyle)
2486                             parentStyle->setChildrenAffectedByBackwardPositionalRules();
2487                     }
2488                     if (!parentElement->isFinishedParsingChildren())
2489                         return false;
2490                     int count = 1;
2491                     const QualifiedName& type = e->tagQName();
2492                     Node* n = e->nextSibling();
2493                     while (n) {
2494                         if (n->isElementNode() && static_cast<Element*>(n)->hasTagName(type))
2495                             count++;
2496                         n = n->nextSibling();
2497                     }
2498                     if (sel->matchNth(count))
2499                         return true;
2500                 }
2501                 break;
2502             }
2503             case CSSSelector::PseudoTarget:
2504                 if (e == e->document()->cssTarget())
2505                     return true;
2506                 break;
2507             case CSSSelector::PseudoAnyLink:
2508                 if (e && e->isLink())
2509                     return true;
2510                 break;
2511             case CSSSelector::PseudoAutofill: {
2512                 if (!e || !e->isFormControlElement())
2513                     break;
2514                 if (InputElement* inputElement = toInputElement(e))
2515                     return inputElement->isAutofilled();
2516                 break;
2517             }
2518             case CSSSelector::PseudoLink:
2519                 if (e && e->isLink())
2520                     return !m_matchVisitedPseudoClass;
2521                 break;
2522             case CSSSelector::PseudoVisited:
2523                 if (e && e->isLink())
2524                     return m_matchVisitedPseudoClass;
2525                 break;
2526             case CSSSelector::PseudoDrag: {
2527                 if (elementStyle)
2528                     elementStyle->setAffectedByDragRules(true);
2529                 else if (e->renderStyle())
2530                     e->renderStyle()->setAffectedByDragRules(true);
2531                 if (e->renderer() && e->renderer()->isDragging())
2532                     return true;
2533                 break;
2534             }
2535             case CSSSelector::PseudoFocus:
2536                 if (e && e->focused() && e->document()->frame() && e->document()->frame()->selection()->isFocusedAndActive())
2537                     return true;
2538                 break;
2539             case CSSSelector::PseudoHover: {
2540                 // If we're in quirks mode, then hover should never match anchors with no
2541                 // href and *:hover should not match anything.  This is important for sites like wsj.com.
2542                 if (m_strictParsing || isSubSelector || (sel->hasTag() && !e->hasTagName(aTag)) || e->isLink()) {
2543                     if (elementStyle)
2544                         elementStyle->setAffectedByHoverRules(true);
2545                     else if (e->renderStyle())
2546                         e->renderStyle()->setAffectedByHoverRules(true);
2547                     if (e->hovered())
2548                         return true;
2549                 }
2550                 break;
2551             }
2552             case CSSSelector::PseudoActive:
2553                 // If we're in quirks mode, then :active should never match anchors with no
2554                 // href and *:active should not match anything. 
2555                 if (m_strictParsing || isSubSelector || (sel->hasTag() && !e->hasTagName(aTag)) || e->isLink()) {
2556                     if (elementStyle)
2557                         elementStyle->setAffectedByActiveRules(true);
2558                     else if (e->renderStyle())
2559                         e->renderStyle()->setAffectedByActiveRules(true);
2560                     if (e->active())
2561                         return true;
2562                 }
2563                 break;
2564             case CSSSelector::PseudoEnabled:
2565                 if (e && e->isFormControlElement())
2566                     return e->isEnabledFormControl();
2567                 break;
2568             case CSSSelector::PseudoFullPageMedia:
2569                 return e && e->document() && e->document()->isMediaDocument();
2570                 break;
2571             case CSSSelector::PseudoDefault:
2572                 return e && e->isDefaultButtonForForm();
2573             case CSSSelector::PseudoDisabled:
2574                 if (e && e->isFormControlElement())
2575                     return !e->isEnabledFormControl();
2576                 break;
2577             case CSSSelector::PseudoReadOnly: {
2578                 if (!e || !e->isFormControlElement())
2579                     return false;
2580                 return e->isTextFormControl() && e->isReadOnlyFormControl();
2581             }
2582             case CSSSelector::PseudoReadWrite: {
2583                 if (!e || !e->isFormControlElement())
2584                     return false;
2585                 return e->isTextFormControl() && !e->isReadOnlyFormControl();
2586             }
2587             case CSSSelector::PseudoOptional:
2588                 return e && e->isOptionalFormControl();
2589             case CSSSelector::PseudoRequired:
2590                 return e && e->isRequiredFormControl();
2591             case CSSSelector::PseudoValid: {
2592                 if (!e)
2593                     return false;
2594                 e->document()->setContainsValidityStyleRules();
2595                 return e->willValidate() && e->isValidFormControlElement();
2596             } case CSSSelector::PseudoInvalid: {
2597                 if (!e)
2598                     return false;
2599                 e->document()->setContainsValidityStyleRules();
2600                 return (e->willValidate() && !e->isValidFormControlElement()) || e->hasUnacceptableValue();
2601             } case CSSSelector::PseudoChecked: {
2602                 if (!e || !e->isFormControlElement())
2603                     break;
2604                 // Even though WinIE allows checked and indeterminate to co-exist, the CSS selector spec says that
2605                 // you can't be both checked and indeterminate.  We will behave like WinIE behind the scenes and just
2606                 // obey the CSS spec here in the test for matching the pseudo.
2607                 InputElement* inputElement = toInputElement(e);
2608                 if (inputElement && inputElement->isChecked() && !inputElement->isIndeterminate())
2609                     return true;
2610                 break;
2611             }
2612             case CSSSelector::PseudoIndeterminate: {
2613                 if (!e || !e->isFormControlElement())
2614                     break;
2615                 InputElement* inputElement = toInputElement(e);
2616                 if (inputElement && inputElement->isIndeterminate())
2617                     return true;
2618                 break;
2619             }
2620             case CSSSelector::PseudoRoot:
2621                 if (e == e->document()->documentElement())
2622                     return true;
2623                 break;
2624             case CSSSelector::PseudoLang: {
2625                 AtomicString value = e->computeInheritedLanguage();
2626                 const AtomicString& argument = sel->argument();
2627                 if (value.isEmpty() || !value.startsWith(argument, false))
2628                     break;
2629                 if (value.length() != argument.length() && value[argument.length()] != '-')
2630                     break;
2631                 return true;
2632             }
2633 #if ENABLE(FULLSCREEN_API)
2634             case CSSSelector::PseudoFullScreen:
2635                 // While a Document is in the fullscreen state, and the document's current fullscreen 
2636                 // element is an element in the document, the 'full-screen' pseudoclass applies to 
2637                 // that element. Also, an <iframe>, <object> or <embed> element whose child browsing 
2638                 // context's Document is in the fullscreen state has the 'full-screen' pseudoclass applied.
2639                 if (!e->document()->webkitFullScreen())
2640                     return false;
2641                 if (e != e->document()->webkitCurrentFullScreenElement())
2642                     return false;
2643                 return true;
2644             case CSSSelector::PseudoFullScreenDocument:
2645                 // While a Document is in the fullscreen state, the 'full-screen-document' pseudoclass applies 
2646                 // to the root element of that Document.
2647                 if (!e->document()->webkitFullScreen())
2648                     return false;
2649                 if (e != e->document()->documentElement())
2650                     return false;
2651                 return true;
2652 #endif
2653             case CSSSelector::PseudoUnknown:
2654             case CSSSelector::PseudoNotParsed:
2655             default:
2656                 ASSERT_NOT_REACHED();
2657                 break;
2658         }
2659         return false;
2660     }
2661     if (sel->m_match == CSSSelector::PseudoElement) {
2662         if (!elementStyle && !m_collectRulesOnly)
2663             return false;
2664
2665         PseudoId pseudoId = CSSSelector::pseudoId(sel->pseudoType());
2666         if (pseudoId == FIRST_LETTER) {
2667             if (Document* document = e->document())
2668                 document->setUsesFirstLetterRules(true);
2669         }
2670         if (pseudoId != NOPSEUDO) {
2671             dynamicPseudo = pseudoId;
2672             return true;
2673         }
2674         ASSERT_NOT_REACHED();
2675         return false;
2676     }
2677     // ### add the rest of the checks...
2678     return true;
2679 }
2680
2681 bool CSSStyleSelector::SelectorChecker::checkScrollbarPseudoClass(CSSSelector* sel, PseudoId&) const
2682 {
2683     RenderScrollbar* scrollbar = RenderScrollbar::scrollbarForStyleResolve();
2684     ScrollbarPart part = RenderScrollbar::partForStyleResolve();
2685
2686     // FIXME: This is a temporary hack for resizers and scrollbar corners.  Eventually :window-inactive should become a real
2687     // pseudo class and just apply to everything.
2688     if (sel->pseudoType() == CSSSelector::PseudoWindowInactive)
2689         return !m_document->page()->focusController()->isActive();
2690     
2691     if (!scrollbar)
2692         return false;
2693         
2694     ASSERT(sel->m_match == CSSSelector::PseudoClass);
2695     switch (sel->pseudoType()) {
2696         case CSSSelector::PseudoEnabled:
2697             return scrollbar->enabled();
2698         case CSSSelector::PseudoDisabled:
2699             return !scrollbar->enabled();
2700         case CSSSelector::PseudoHover: {
2701             ScrollbarPart hoveredPart = scrollbar->hoveredPart();
2702             if (part == ScrollbarBGPart)
2703                 return hoveredPart != NoPart;
2704             if (part == TrackBGPart)
2705                 return hoveredPart == BackTrackPart || hoveredPart == ForwardTrackPart || hoveredPart == ThumbPart;
2706             return part == hoveredPart;
2707         }
2708         case CSSSelector::PseudoActive: {
2709             ScrollbarPart pressedPart = scrollbar->pressedPart();
2710             if (part == ScrollbarBGPart)
2711                 return pressedPart != NoPart;
2712             if (part == TrackBGPart)
2713                 return pressedPart == BackTrackPart || pressedPart == ForwardTrackPart || pressedPart == ThumbPart;
2714             return part == pressedPart;
2715         }
2716         case CSSSelector::PseudoHorizontal:
2717             return scrollbar->orientation() == HorizontalScrollbar;
2718         case CSSSelector::PseudoVertical:
2719             return scrollbar->orientation() == VerticalScrollbar;
2720         case CSSSelector::PseudoDecrement:
2721             return part == BackButtonStartPart || part == BackButtonEndPart || part == BackTrackPart;
2722         case CSSSelector::PseudoIncrement:
2723             return part == ForwardButtonStartPart || part == ForwardButtonEndPart || part == ForwardTrackPart;
2724         case CSSSelector::PseudoStart:
2725             return part == BackButtonStartPart || part == ForwardButtonStartPart || part == BackTrackPart;
2726         case CSSSelector::PseudoEnd:
2727             return part == BackButtonEndPart || part == ForwardButtonEndPart || part == ForwardTrackPart;
2728         case CSSSelector::PseudoDoubleButton: {
2729             ScrollbarButtonsPlacement buttonsPlacement = scrollbar->theme()->buttonsPlacement();
2730             if (part == BackButtonStartPart || part == ForwardButtonStartPart || part == BackTrackPart)
2731                 return buttonsPlacement == ScrollbarButtonsDoubleStart || buttonsPlacement == ScrollbarButtonsDoubleBoth;
2732             if (part == BackButtonEndPart || part == ForwardButtonEndPart || part == ForwardTrackPart)
2733                 return buttonsPlacement == ScrollbarButtonsDoubleEnd || buttonsPlacement == ScrollbarButtonsDoubleBoth;
2734             return false;
2735         } 
2736         case CSSSelector::PseudoSingleButton: {
2737             ScrollbarButtonsPlacement buttonsPlacement = scrollbar->theme()->buttonsPlacement();
2738             if (part == BackButtonStartPart || part == ForwardButtonEndPart || part == BackTrackPart || part == ForwardTrackPart)
2739                 return buttonsPlacement == ScrollbarButtonsSingle;
2740             return false;
2741         }
2742         case CSSSelector::PseudoNoButton: {
2743             ScrollbarButtonsPlacement buttonsPlacement = scrollbar->theme()->buttonsPlacement();
2744             if (part == BackTrackPart)
2745                 return buttonsPlacement == ScrollbarButtonsNone || buttonsPlacement == ScrollbarButtonsDoubleEnd;
2746             if (part == ForwardTrackPart)
2747                 return buttonsPlacement == ScrollbarButtonsNone || buttonsPlacement == ScrollbarButtonsDoubleStart;
2748             return false;
2749         }
2750         case CSSSelector::PseudoCornerPresent:
2751             return scrollbar->client()->scrollbarCornerPresent();
2752         default:
2753             return false;
2754     }
2755 }
2756
2757 void CSSStyleSelector::addVariables(CSSVariablesRule* variables)
2758 {
2759     CSSVariablesDeclaration* decl = variables->variables();
2760     if (!decl)
2761         return;
2762     unsigned size = decl->length();
2763     for (unsigned i = 0; i < size; ++i) {
2764         String name = decl->item(i);
2765         m_variablesMap.set(name, variables);
2766     }
2767 }
2768
2769 CSSValue* CSSStyleSelector::resolveVariableDependentValue(CSSVariableDependentValue*)
2770 {
2771     return 0;
2772 }
2773
2774 // -----------------------------------------------------------------
2775
2776 CSSRuleSet::CSSRuleSet()
2777     : m_ruleCount(0)
2778     , m_pageRuleCount(0)
2779 {
2780 }
2781
2782 CSSRuleSet::~CSSRuleSet()
2783
2784     deleteAllValues(m_idRules);
2785     deleteAllValues(m_classRules);
2786     deleteAllValues(m_tagRules);
2787 }
2788
2789
2790 void CSSRuleSet::addToRuleSet(AtomicStringImpl* key, AtomRuleMap& map,
2791                               CSSStyleRule* rule, CSSSelector* sel)
2792 {
2793     if (!key) return;
2794     CSSRuleDataList* rules = map.get(key);
2795     if (!rules) {
2796         rules = new CSSRuleDataList(m_ruleCount++, rule, sel);
2797         map.set(key, rules);
2798     } else
2799         rules->append(m_ruleCount++, rule, sel);
2800 }
2801
2802 void CSSRuleSet::addRule(CSSStyleRule* rule, CSSSelector* sel)
2803 {
2804     if (sel->m_match == CSSSelector::Id) {
2805         addToRuleSet(sel->m_value.impl(), m_idRules, rule, sel);
2806         return;
2807     }
2808     if (sel->m_match == CSSSelector::Class) {
2809         addToRuleSet(sel->m_value.impl(), m_classRules, rule, sel);
2810         return;
2811     }
2812      
2813     const AtomicString& localName = sel->m_tag.localName();
2814     if (localName != starAtom) {
2815         addToRuleSet(localName.impl(), m_tagRules, rule, sel);
2816         return;
2817     }
2818     
2819     // Just put it in the universal rule set.
2820     if (!m_universalRules)
2821         m_universalRules = adoptPtr(new CSSRuleDataList(m_ruleCount++, rule, sel));
2822     else
2823         m_universalRules->append(m_ruleCount++, rule, sel);
2824 }
2825
2826 void CSSRuleSet::addPageRule(CSSStyleRule* rule, CSSSelector* sel)
2827 {
2828     if (!m_pageRules)
2829         m_pageRules = adoptPtr(new CSSRuleDataList(m_pageRuleCount++, rule, sel));
2830     else
2831         m_pageRules->append(m_pageRuleCount++, rule, sel);
2832 }
2833
2834 void CSSRuleSet::addRulesFromSheet(CSSStyleSheet* sheet, const MediaQueryEvaluator& medium, CSSStyleSelector* styleSelector)
2835 {
2836     if (!sheet)
2837         return;
2838
2839     // No media implies "all", but if a media list exists it must
2840     // contain our current medium
2841     if (sheet->media() && !medium.eval(sheet->media(), styleSelector))
2842         return; // the style sheet doesn't apply
2843
2844     int len = sheet->length();
2845
2846     for (int i = 0; i < len; i++) {
2847         StyleBase* item = sheet->item(i);
2848         if (item->isStyleRule()) {
2849             addStyleRule(item);
2850         }
2851         else if (item->isImportRule()) {
2852             CSSImportRule* import = static_cast<CSSImportRule*>(item);
2853             if (!import->media() || medium.eval(import->media(), styleSelector))
2854                 addRulesFromSheet(import->styleSheet(), medium, styleSelector);
2855         }
2856         else if (item->isMediaRule()) {
2857             CSSMediaRule* r = static_cast<CSSMediaRule*>(item);
2858             CSSRuleList* rules = r->cssRules();
2859
2860             if ((!r->media() || medium.eval(r->media(), styleSelector)) && rules) {
2861                 // Traverse child elements of the @media rule.
2862                 for (unsigned j = 0; j < rules->length(); j++) {
2863                     CSSRule *childItem = rules->item(j);
2864                     if (childItem->isStyleRule()) {
2865                         // It is a StyleRule, so append it to our list
2866                         addStyleRule(childItem);
2867                     } else if (childItem->isFontFaceRule() && styleSelector) {
2868                         // Add this font face to our set.
2869                         const CSSFontFaceRule* fontFaceRule = static_cast<CSSFontFaceRule*>(childItem);
2870                         styleSelector->fontSelector()->addFontFaceRule(fontFaceRule);
2871                     } else if (childItem->isKeyframesRule() && styleSelector) {
2872                         // Add this keyframe rule to our set.
2873                         styleSelector->addKeyframeStyle(static_cast<WebKitCSSKeyframesRule*>(childItem));
2874                     }
2875                 }   // for rules
2876             }   // if rules
2877         } else if (item->isFontFaceRule() && styleSelector) {
2878             // Add this font face to our set.
2879             const CSSFontFaceRule* fontFaceRule = static_cast<CSSFontFaceRule*>(item);
2880             styleSelector->fontSelector()->addFontFaceRule(fontFaceRule);
2881         } else if (item->isVariablesRule()) {
2882             // Evaluate the media query and make sure it matches.
2883             CSSVariablesRule* variables = static_cast<CSSVariablesRule*>(item);
2884             if (!variables->media() || medium.eval(variables->media(), styleSelector))
2885                 styleSelector->addVariables(variables);
2886         } else if (item->isKeyframesRule())
2887             styleSelector->addKeyframeStyle(static_cast<WebKitCSSKeyframesRule*>(item));
2888     }
2889 }
2890
2891 void CSSRuleSet::addStyleRule(StyleBase* item)
2892 {
2893     if (item->isPageRule()) {
2894         CSSPageRule* pageRule = static_cast<CSSPageRule*>(item);
2895         addPageRule(pageRule, pageRule->selectorList().first());
2896     } else {
2897         CSSStyleRule* rule = static_cast<CSSStyleRule*>(item);
2898         for (CSSSelector* s = rule->selectorList().first(); s; s = CSSSelectorList::next(s))
2899             addRule(rule, s);
2900     }
2901 }
2902
2903 // -------------------------------------------------------------------------------------
2904 // this is mostly boring stuff on how to apply a certain rule to the renderstyle...
2905
2906 static Length convertToLength(CSSPrimitiveValue* primitiveValue, RenderStyle* style, RenderStyle* rootStyle, double multiplier = 1, bool *ok = 0)
2907 {
2908     // This function is tolerant of a null style value. The only place style is used is in
2909     // length measurements, like 'ems' and 'px'. And in those cases style is only used
2910     // when the units are EMS or EXS. So we will just fail in those cases.
2911     Length l;
2912     if (!primitiveValue) {
2913         if (ok)
2914             *ok = false;
2915     } else {
2916         int type = primitiveValue->primitiveType();
2917         
2918         if (!style && (type == CSSPrimitiveValue::CSS_EMS || type == CSSPrimitiveValue::CSS_EXS || type == CSSPrimitiveValue::CSS_REMS)) {
2919             if (ok)
2920                 *ok = false;
2921         } else if (CSSPrimitiveValue::isUnitTypeLength(type))
2922             l = Length(primitiveValue->computeLengthIntForLength(style, rootStyle, multiplier), Fixed);
2923         else if (type == CSSPrimitiveValue::CSS_PERCENTAGE)
2924             l = Length(primitiveValue->getDoubleValue(), Percent);
2925         else if (type == CSSPrimitiveValue::CSS_NUMBER)
2926             l = Length(primitiveValue->getDoubleValue() * 100.0, Percent);
2927         else if (ok)
2928             *ok = false;
2929     }
2930     return l;
2931 }
2932
2933 template <bool applyFirst>
2934 void CSSStyleSelector::applyDeclarations(bool isImportant, int startIndex, int endIndex)
2935 {
2936     if (startIndex == -1)
2937         return;
2938
2939     for (int i = startIndex; i <= endIndex; i++) {
2940         CSSMutableStyleDeclaration* decl = m_matchedDecls[i];
2941         CSSMutableStyleDeclaration::const_iterator end = decl->end();
2942         for (CSSMutableStyleDeclaration::const_iterator it = decl->begin(); it != end; ++it) {
2943             const CSSProperty& current = *it;
2944             if (isImportant == current.isImportant()) {
2945                 int property = current.id();
2946
2947                 if (applyFirst) {
2948                     COMPILE_ASSERT(firstCSSProperty == CSSPropertyColor, CSS_color_is_first_property);
2949                     COMPILE_ASSERT(CSSPropertyZoom == CSSPropertyColor + 13, CSS_zoom_is_end_of_first_prop_range);
2950                     COMPILE_ASSERT(CSSPropertyLineHeight == CSSPropertyZoom + 1, CSS_line_height_is_after_zoom);
2951
2952                     // give special priority to font-xxx, color properties, etc
2953                     if (property <= CSSPropertyLineHeight) {
2954                         // we apply line-height later
2955                         if (property == CSSPropertyLineHeight)
2956                             m_lineHeightValue = current.value(); 
2957                         else 
2958                             applyProperty(current.id(), current.value());
2959                     }
2960                 } else {
2961                     if (property > CSSPropertyLineHeight)
2962                         applyProperty(current.id(), current.value());
2963                 }
2964             }
2965         }
2966     }
2967 }
2968
2969 void CSSStyleSelector::matchPageRules(CSSRuleSet* rules, bool isLeftPage, bool isFirstPage, const String& pageName)
2970 {
2971     m_matchedRules.clear();
2972
2973     if (!rules)
2974         return;
2975
2976     matchPageRulesForList(rules->getPageRules(), isLeftPage, isFirstPage, pageName);
2977
2978     // If we didn't match any rules, we're done.
2979     if (m_matchedRules.isEmpty())
2980         return;
2981
2982     // Sort the set of matched rules.
2983     sortMatchedRules(0, m_matchedRules.size());
2984
2985     // Now transfer the set of matched rules over to our list of decls.
2986     for (unsigned i = 0; i < m_matchedRules.size(); i++)
2987         addMatchedDeclaration(m_matchedRules[i]->rule()->declaration());
2988 }
2989
2990 void CSSStyleSelector::matchPageRulesForList(CSSRuleDataList* rules, bool isLeftPage, bool isFirstPage, const String& pageName)
2991 {
2992     if (!rules)
2993         return;
2994
2995     for (CSSRuleData* d = rules->first(); d; d = d->next()) {
2996         CSSStyleRule* rule = d->rule();
2997         const AtomicString& selectorLocalName = d->selector()->m_tag.localName();
2998         if (selectorLocalName != starAtom && selectorLocalName != pageName)
2999             continue;
3000         CSSSelector::PseudoType pseudoType = d->selector()->pseudoType();
3001         if ((pseudoType == CSSSelector::PseudoLeftPage && !isLeftPage)
3002             || (pseudoType == CSSSelector::PseudoRightPage && isLeftPage)
3003             || (pseudoType == CSSSelector::PseudoFirstPage && !isFirstPage))
3004             continue;
3005
3006         // If the rule has no properties to apply, then ignore it.
3007         CSSMutableStyleDeclaration* decl = rule->declaration();
3008         if (!decl || !decl->length())
3009             continue;
3010
3011         // Add this rule to our list of matched rules.
3012         addMatchedRule(d);
3013     }
3014 }
3015
3016 bool CSSStyleSelector::isLeftPage(int pageIndex) const
3017 {
3018     bool isFirstPageLeft = false;
3019     if (!m_rootElementStyle->isLeftToRightDirection())
3020         isFirstPageLeft = true;
3021
3022     return (pageIndex + (isFirstPageLeft ? 1 : 0)) % 2;
3023 }
3024
3025 bool CSSStyleSelector::isFirstPage(int pageIndex) const
3026 {
3027     // FIXME: In case of forced left/right page, page at index 1 (not 0) can be the first page.
3028     return (!pageIndex);
3029 }
3030
3031 String CSSStyleSelector::pageName(int /* pageIndex */) const
3032 {
3033     // FIXME: Implement page index to page name mapping.
3034     return "";
3035 }
3036
3037 static void applyCounterList(RenderStyle* style, CSSValueList* list, bool isReset)
3038 {
3039     CounterDirectiveMap& map = style->accessCounterDirectives();
3040     typedef CounterDirectiveMap::iterator Iterator;
3041
3042     Iterator end = map.end();
3043     for (Iterator it = map.begin(); it != end; ++it)
3044         if (isReset)
3045             it->second.m_reset = false;
3046         else
3047             it->second.m_increment = false;
3048
3049     int length = list ? list->length() : 0;
3050     for (int i = 0; i < length; ++i) {
3051         Pair* pair = static_cast<CSSPrimitiveValue*>(list->itemWithoutBoundsCheck(i))->getPairValue();
3052         AtomicString identifier = static_cast<CSSPrimitiveValue*>(pair->first())->getStringValue();
3053         // FIXME: What about overflow?
3054         int value = static_cast<CSSPrimitiveValue*>(pair->second())->getIntValue();
3055         CounterDirectives& directives = map.add(identifier.impl(), CounterDirectives()).first->second;
3056         if (isReset) {
3057             directives.m_reset = true;
3058             directives.m_resetValue = value;
3059         } else {
3060             if (directives.m_increment)
3061                 directives.m_incrementValue += value;
3062             else {
3063                 directives.m_increment = true;
3064                 directives.m_incrementValue = value;
3065             }
3066         }
3067     }
3068 }
3069
3070 void CSSStyleSelector::applyPropertyToStyle(int id, CSSValue *value, RenderStyle* style)
3071 {
3072     initElement(0);
3073     initForStyleResolve(0, style);
3074     m_style = style;
3075     applyProperty(id, value);
3076 }
3077
3078 inline bool isValidVisitedLinkProperty(int id)
3079 {
3080     switch(static_cast<CSSPropertyID>(id)) {
3081         case CSSPropertyBackgroundColor:
3082         case CSSPropertyBorderLeftColor:
3083         case CSSPropertyBorderRightColor:
3084         case CSSPropertyBorderTopColor:
3085         case CSSPropertyBorderBottomColor:
3086         case CSSPropertyColor:
3087         case CSSPropertyOutlineColor:
3088         case CSSPropertyWebkitColumnRuleColor:
3089         case CSSPropertyWebkitTextFillColor:
3090         case CSSPropertyWebkitTextStrokeColor:
3091         // Also allow shorthands so that inherit/initial still work.
3092         case CSSPropertyBackground:
3093         case CSSPropertyBorderLeft:
3094         case CSSPropertyBorderRight:
3095         case CSSPropertyBorderTop:
3096         case CSSPropertyBorderBottom:
3097         case CSSPropertyOutline:
3098         case CSSPropertyWebkitColumnRule:
3099 #if ENABLE(SVG)
3100         case CSSPropertyFill:
3101         case CSSPropertyStroke:
3102 #endif
3103             return true;
3104         default:
3105             break;
3106     }
3107
3108     return false;
3109 }
3110
3111 void CSSStyleSelector::applyProperty(int id, CSSValue *value)
3112 {
3113     CSSPrimitiveValue* primitiveValue = 0;
3114     if (value->isPrimitiveValue())
3115         primitiveValue = static_cast<CSSPrimitiveValue*>(value);
3116
3117     float zoomFactor = m_style->effectiveZoom();
3118
3119     // SVG handles zooming in a different way compared to CSS. The whole document is scaled instead
3120     // of each individual length value in the render style / tree. CSSPrimitiveValue::computeLength*()
3121     // multiplies each resolved length with the zoom multiplier - so for SVG we need to disable that.
3122     // Though all CSS values that can be applied to outermost <svg> elements (width/height/border/padding...)
3123     // need to respect the scaling. RenderBox (the parent class of RenderSVGRoot) grabs values like
3124     // width/height/border/padding/... from the RenderStyle -> for SVG these values would never scale,
3125     // if we'd pass a 1.0 zoom factor everyhwere. So we only pass a zoom factor of 1.0 for specific
3126     // properties that are NOT allowed to scale within a zoomed SVG document (letter/word-spacing/font-size).
3127     bool useSVGZoomRules = m_element && m_element->isSVGElement();
3128
3129     Length l;
3130     bool apply = false;
3131
3132     unsigned short valueType = value->cssValueType();
3133
3134     bool isInherit = m_parentNode && valueType == CSSValue::CSS_INHERIT;
3135     bool isInitial = valueType == CSSValue::CSS_INITIAL || (!m_parentNode && valueType == CSSValue::CSS_INHERIT);
3136     
3137     id = CSSProperty::resolveDirectionAwareProperty(id, m_style->direction(), m_style->writingMode());
3138
3139     if (m_checker.m_matchVisitedPseudoClass && !isValidVisitedLinkProperty(id)) {
3140         // Limit the properties that can be applied to only the ones honored by :visited.
3141         return;
3142     }
3143     
3144     // What follows is a list that maps the CSS properties into their corresponding front-end
3145     // RenderStyle values.  Shorthands (e.g. border, background) occur in this list as well and
3146     // are only hit when mapping "inherit" or "initial" into front-end values.
3147     CSSPropertyID property = static_cast<CSSPropertyID>(id);
3148     switch (property) {
3149 // ident only properties
3150     case CSSPropertyBackgroundAttachment:
3151         HANDLE_BACKGROUND_VALUE(attachment, Attachment, value)
3152         return;
3153     case CSSPropertyBackgroundClip:
3154     case CSSPropertyWebkitBackgroundClip:
3155         HANDLE_BACKGROUND_VALUE(clip, Clip, value)
3156         return;
3157     case CSSPropertyWebkitBackgroundComposite:
3158         HANDLE_BACKGROUND_VALUE(composite, Composite, value)
3159         return;
3160     case CSSPropertyBackgroundOrigin:
3161     case CSSPropertyWebkitBackgroundOrigin:
3162         HANDLE_BACKGROUND_VALUE(origin, Origin, value)
3163         return;
3164     case CSSPropertyBackgroundSize:
3165     case CSSPropertyWebkitBackgroundSize:
3166         HANDLE_BACKGROUND_VALUE(size, Size, value)
3167         return;
3168     case CSSPropertyWebkitMaskAttachment:
3169         HANDLE_MASK_VALUE(attachment, Attachment, value)
3170         return;
3171     case CSSPropertyWebkitMaskClip:
3172         HANDLE_MASK_VALUE(clip, Clip, value)
3173         return;
3174     case CSSPropertyWebkitMaskComposite:
3175         HANDLE_MASK_VALUE(composite, Composite, value)
3176         return;
3177     case CSSPropertyWebkitMaskOrigin:
3178         HANDLE_MASK_VALUE(origin, Origin, value)
3179         return;
3180     case CSSPropertyWebkitMaskSize:
3181         HANDLE_MASK_VALUE(size, Size, value)
3182         return;
3183     case CSSPropertyBorderCollapse:
3184         HANDLE_INHERIT_AND_INITIAL(borderCollapse, BorderCollapse)
3185         if (!primitiveValue)
3186             return;
3187         switch (primitiveValue->getIdent()) {
3188             case CSSValueCollapse:
3189                 m_style->setBorderCollapse(true);
3190                 break;
3191             case CSSValueSeparate:
3192                 m_style->setBorderCollapse(false);
3193                 break;
3194             default:
3195                 return;
3196         }
3197         return;
3198     case CSSPropertyBorderTopStyle:
3199         HANDLE_INHERIT_AND_INITIAL_AND_PRIMITIVE_WITH_VALUE(borderTopStyle, BorderTopStyle, BorderStyle)
3200         return;
3201     case CSSPropertyBorderRightStyle:
3202         HANDLE_INHERIT_AND_INITIAL_AND_PRIMITIVE_WITH_VALUE(borderRightStyle, BorderRightStyle, BorderStyle)
3203         return;
3204     case CSSPropertyBorderBottomStyle:
3205         HANDLE_INHERIT_AND_INITIAL_AND_PRIMITIVE_WITH_VALUE(borderBottomStyle, BorderBottomStyle, BorderStyle)
3206         return;
3207     case CSSPropertyBorderLeftStyle:
3208         HANDLE_INHERIT_AND_INITIAL_AND_PRIMITIVE_WITH_VALUE(borderLeftStyle, BorderLeftStyle, BorderStyle)
3209         return;
3210     case CSSPropertyOutlineStyle:
3211         HANDLE_INHERIT_AND_INITIAL_WITH_VALUE(outlineStyle, OutlineStyle, BorderStyle)
3212         if (primitiveValue) {
3213             if (primitiveValue->getIdent() == CSSValueAuto)
3214                 m_style->setOutlineStyle(DOTTED, true);
3215             else
3216                 m_style->setOutlineStyle(*primitiveValue);
3217         }
3218         return;
3219     case CSSPropertyCaptionSide:
3220         HANDLE_INHERIT_AND_INITIAL_AND_PRIMITIVE(captionSide, CaptionSide)
3221         return;
3222     case CSSPropertyClear:
3223         HANDLE_INHERIT_AND_INITIAL_AND_PRIMITIVE(clear, Clear)
3224         return;
3225     case CSSPropertyDirection:
3226         HANDLE_INHERIT_AND_INITIAL_AND_PRIMITIVE(direction, Direction)
3227         return;
3228     case CSSPropertyDisplay:
3229         HANDLE_INHERIT_AND_INITIAL_AND_PRIMITIVE(display, Display)
3230 #if ENABLE(WCSS)
3231         if (primitiveValue) {
3232             if (primitiveValue->getIdent() == CSSValueWapMarquee) {
3233                 // Initialize WAP Marquee style
3234                 m_style->setOverflowX(OMARQUEE);
3235                 m_style->setOverflowY(OMARQUEE);
3236                 m_style->setWhiteSpace(NOWRAP);
3237                 m_style->setMarqueeDirection(MLEFT);
3238                 m_style->setMarqueeSpeed(85); // Normal speed
3239                 m_style->setMarqueeLoopCount(1);
3240                 m_style->setMarqueeBehavior(MSCROLL);
3241
3242                 if (m_parentStyle)
3243                     m_style->setDisplay(m_parentStyle->display());
3244                 else
3245                     m_style->setDisplay(*primitiveValue);
3246             } else
3247                 m_style->setDisplay(*primitiveValue);
3248         }
3249 #endif
3250         return;
3251     case CSSPropertyEmptyCells:
3252         HANDLE_INHERIT_AND_INITIAL_AND_PRIMITIVE(emptyCells, EmptyCells)
3253         return;
3254     case CSSPropertyFloat:
3255         HANDLE_INHERIT_AND_INITIAL_AND_PRIMITIVE(floating, Floating)
3256         return;
3257     case CSSPropertyFontStyle:
3258     {
3259         FontDescription fontDescription = m_style->fontDescription();
3260         if (isInherit)
3261             fontDescription.setItalic(m_parentStyle->fontDescription().italic());
3262         else if (isInitial)
3263             fontDescription.setItalic(false);
3264         else {
3265             if (!primitiveValue)
3266                 return;
3267             switch (primitiveValue->getIdent()) {
3268                 case CSSValueOblique:
3269                 // FIXME: oblique is the same as italic for the moment...
3270                 case CSSValueItalic:
3271                     fontDescription.setItalic(true);
3272                     break;
3273                 case CSSValueNormal:
3274                     fontDescription.setItalic(false);
3275                     break;
3276                 default:
3277                     return;
3278             }
3279         }
3280         if (m_style->setFontDescription(fontDescription))
3281             m_fontDirty = true;
3282         return;
3283     }
3284
3285     case CSSPropertyFontVariant:
3286     {
3287         FontDescription fontDescription = m_style->fontDescription();
3288         if (isInherit) 
3289             fontDescription.setSmallCaps(m_parentStyle->fontDescription().smallCaps());
3290         else if (isInitial)
3291             fontDescription.setSmallCaps(false);
3292         else {
3293             if (!primitiveValue)
3294                 return;
3295             int id = primitiveValue->getIdent();
3296             if (id == CSSValueNormal)
3297                 fontDescription.setSmallCaps(false);
3298             else if (id == CSSValueSmallCaps)
3299                 fontDescription.setSmallCaps(true);
3300             else
3301                 return;
3302         }
3303         if (m_style->setFontDescription(fontDescription))
3304             m_fontDirty = true;
3305         return;
3306     }
3307
3308     case CSSPropertyFontWeight:
3309     {
3310         FontDescription fontDescription = m_style->fontDescription();
3311         if (isInherit)
3312             fontDescription.setWeight(m_parentStyle->fontDescription().weight());
3313         else if (isInitial)
3314             fontDescription.setWeight(FontWeightNormal);
3315         else {
3316             if (!primitiveValue)
3317                 return;
3318             if (primitiveValue->getIdent()) {
3319                 switch (primitiveValue->getIdent()) {
3320                     case CSSValueBolder:
3321                         fontDescription.setWeight(fontDescription.bolderWeight());
3322                         break;
3323                     case CSSValueLighter:
3324                         fontDescription.setWeight(fontDescription.lighterWeight());
3325                         break;
3326                     case CSSValueBold:
3327                     case CSSValue700:
3328                         fontDescription.setWeight(FontWeightBold);
3329                         break;
3330                     case CSSValueNormal:
3331                     case CSSValue400:
3332                         fontDescription.setWeight(FontWeightNormal);
3333                         break;
3334                     case CSSValue900:
3335                         fontDescription.setWeight(FontWeight900);
3336                         break;
3337                     case CSSValue800:
3338                         fontDescription.setWeight(FontWeight800);
3339                         break;
3340                     case CSSValue600:
3341                         fontDescription.setWeight(FontWeight600);
3342                         break;
3343                     case CSSValue500:
3344                         fontDescription.setWeight(FontWeight500);
3345                         break;
3346                     case CSSValue300:
3347                         fontDescription.setWeight(FontWeight300);
3348                         break;
3349                     case CSSValue200:
3350                         fontDescription.setWeight(FontWeight200);
3351                         break;
3352                     case CSSValue100:
3353                         fontDescription.setWeight(FontWeight100);
3354                         break;
3355                     default:
3356                         return;
3357                 }
3358             } else
3359                 ASSERT_NOT_REACHED();
3360         }
3361         if (m_style->setFontDescription(fontDescription))
3362             m_fontDirty = true;
3363         return;
3364     }
3365         
3366     case CSSPropertyListStylePosition:
3367         HANDLE_INHERIT_AND_INITIAL_AND_PRIMITIVE(listStylePosition, ListStylePosition)
3368         return;
3369     case CSSPropertyListStyleType:
3370         HANDLE_INHERIT_AND_INITIAL_AND_PRIMITIVE(listStyleType, ListStyleType)
3371         return;
3372     case CSSPropertyOverflow:
3373     {
3374         if (isInherit) {
3375             m_style->setOverflowX(m_parentStyle->overflowX());
3376             m_style->setOverflowY(m_parentStyle->overflowY());
3377             return;
3378         }
3379         
3380         if (isInitial) {
3381             m_style->setOverflowX(RenderStyle::initialOverflowX());
3382             m_style->setOverflowY(RenderStyle::initialOverflowY());
3383             return;
3384         }
3385             
3386         EOverflow o = *primitiveValue;
3387
3388         m_style->setOverflowX(o);
3389         m_style->setOverflowY(o);
3390         return;
3391     }
3392
3393     case CSSPropertyOverflowX:
3394         HANDLE_INHERIT_AND_INITIAL_AND_PRIMITIVE(overflowX, OverflowX)
3395         return;
3396     case CSSPropertyOverflowY:
3397         HANDLE_INHERIT_AND_INITIAL_AND_PRIMITIVE(overflowY, OverflowY)
3398         return;
3399     case CSSPropertyPageBreakBefore:
3400         HANDLE_INHERIT_AND_INITIAL_AND_PRIMITIVE_WITH_VALUE(pageBreakBefore, PageBreakBefore, PageBreak)
3401         return;
3402     case CSSPropertyPageBreakAfter:
3403         HANDLE_INHERIT_AND_INITIAL_AND_PRIMITIVE_WITH_VALUE(pageBreakAfter, PageBreakAfter, PageBreak)
3404         return;
3405     case CSSPropertyPageBreakInside: {
3406         HANDLE_INHERIT_AND_INITIAL_WITH_VALUE(pageBreakInside, PageBreakInside, PageBreak)
3407         if (!primitiveValue)
3408             return;
3409         EPageBreak pageBreak = *primitiveValue;
3410         if (pageBreak != PBALWAYS)
3411             m_style->setPageBreakInside(pageBreak);
3412         return;
3413     }
3414         
3415     case CSSPropertyPosition:
3416         HANDLE_INHERIT_AND_INITIAL_AND_PRIMITIVE(position, Position)
3417         return;
3418     case CSSPropertyTableLayout: {
3419         HANDLE_INHERIT_AND_INITIAL(tableLayout, TableLayout)
3420
3421         ETableLayout l = *primitiveValue;
3422         if (l == TAUTO)
3423             l = RenderStyle::initialTableLayout();
3424
3425         m_style->setTableLayout(l);
3426         return;
3427     }
3428         
3429     case CSSPropertyUnicodeBidi: 
3430         HANDLE_INHERIT_AND_INITIAL_AND_PRIMITIVE(unicodeBidi, UnicodeBidi)
3431         return;
3432     case CSSPropertyTextTransform: 
3433         HANDLE_INHERIT_AND_INITIAL_AND_PRIMITIVE(textTransform, TextTransform)
3434         return;
3435     case CSSPropertyVisibility:
3436         HANDLE_INHERIT_AND_INITIAL_AND_PRIMITIVE(visibility, Visibility)
3437         return;
3438     case CSSPropertyWhiteSpace:
3439         HANDLE_INHERIT_AND_INITIAL_AND_PRIMITIVE(whiteSpace, WhiteSpace)
3440         return;
3441
3442     case CSSPropertyBackgroundPosition:
3443         HANDLE_BACKGROUND_INHERIT_AND_INITIAL(xPosition, XPosition);
3444         HANDLE_BACKGROUND_INHERIT_AND_INITIAL(yPosition, YPosition);
3445         return;
3446     case CSSPropertyBackgroundPositionX: {
3447         HANDLE_BACKGROUND_VALUE(xPosition, XPosition, value)
3448         return;
3449     }
3450     case CSSPropertyBackgroundPositionY: {
3451         HANDLE_BACKGROUND_VALUE(yPosition, YPosition, value)
3452         return;
3453     }
3454     case CSSPropertyWebkitMaskPosition:
3455         HANDLE_MASK_INHERIT_AND_INITIAL(xPosition, XPosition);
3456         HANDLE_MASK_INHERIT_AND_INITIAL(yPosition, YPosition);
3457         return;
3458     case CSSPropertyWebkitMaskPositionX: {
3459         HANDLE_MASK_VALUE(xPosition, XPosition, value)
3460         return;
3461     }
3462     case CSSPropertyWebkitMaskPositionY: {
3463         HANDLE_MASK_VALUE(yPosition, YPosition, value)
3464         return;
3465     }
3466     case CSSPropertyBackgroundRepeat:
3467         HANDLE_BACKGROUND_INHERIT_AND_INITIAL(repeatX, RepeatX);
3468         HANDLE_BACKGROUND_INHERIT_AND_INITIAL(repeatY, RepeatY);
3469         return;
3470     case CSSPropertyBackgroundRepeatX:
3471         HANDLE_BACKGROUND_VALUE(repeatX, RepeatX, value)
3472         return;
3473     case CSSPropertyBackgroundRepeatY:
3474         HANDLE_BACKGROUND_VALUE(repeatY, RepeatY, value)
3475         return;
3476     case CSSPropertyWebkitMaskRepeat:
3477         HANDLE_MASK_INHERIT_AND_INITIAL(repeatX, RepeatX);
3478         HANDLE_MASK_INHERIT_AND_INITIAL(repeatY, RepeatY);
3479         return;
3480     case CSSPropertyWebkitMaskRepeatX:
3481         HANDLE_MASK_VALUE(repeatX, RepeatX, value)
3482         return;
3483     case CSSPropertyWebkitMaskRepeatY:
3484         HANDLE_MASK_VALUE(repeatY, RepeatY, value)
3485         return;
3486     case CSSPropertyBorderSpacing: {
3487         if (isInherit) {
3488             m_style->setHorizontalBorderSpacing(m_parentStyle->horizontalBorderSpacing());
3489             m_style->setVerticalBorderSpacing(m_parentStyle->verticalBorderSpacing());
3490         }
3491         else if (isInitial) {
3492             m_style->setHorizontalBorderSpacing(0);
3493             m_style->setVerticalBorderSpacing(0);
3494         }
3495         return;
3496     }
3497     case CSSPropertyWebkitBorderHorizontalSpacing: {
3498         HANDLE_INHERIT_AND_INITIAL(horizontalBorderSpacing, HorizontalBorderSpacing)
3499         if (!primitiveValue)
3500             return;
3501         short spacing = primitiveValue->computeLengthShort(style(), m_rootElementStyle, zoomFactor);
3502         m_style->setHorizontalBorderSpacing(spacing);
3503         return;
3504     }
3505     case CSSPropertyWebkitBorderVerticalSpacing: {
3506         HANDLE_INHERIT_AND_INITIAL(verticalBorderSpacing, VerticalBorderSpacing)
3507         if (!primitiveValue)
3508             return;
3509         short spacing = primitiveValue->computeLengthShort(style(), m_rootElementStyle, zoomFactor);
3510         m_style->setVerticalBorderSpacing(spacing);
3511         return;
3512     }
3513     case CSSPropertyCursor:
3514         if (isInherit) {
3515             m_style->setCursor(m_parentStyle->cursor());
3516             m_style->setCursorList(m_parentStyle->cursors());
3517             return;
3518         }
3519         m_style->clearCursorList();
3520         if (isInitial) {
3521             m_style->setCursor(RenderStyle::initialCursor());
3522             return;
3523         }
3524         if (value->isValueList()) {
3525             CSSValueList* list = static_cast<CSSValueList*>(value);
3526             int len = list->length();
3527             m_style->setCursor(CURSOR_AUTO);
3528             for (int i = 0; i < len; i++) {
3529                 CSSValue* item = list->itemWithoutBoundsCheck(i);
3530                 if (!item->isPrimitiveValue())
3531                     continue;
3532                 primitiveValue = static_cast<CSSPrimitiveValue*>(item);
3533                 int type = primitiveValue->primitiveType();
3534                 if (type == CSSPrimitiveValue::CSS_URI) {
3535                     CSSCursorImageValue* image = static_cast<CSSCursorImageValue*>(primitiveValue);
3536                     if (image->updateIfSVGCursorIsUsed(m_element)) // Elements with SVG cursors are not allowed to share style.
3537                         m_style->setUnique();
3538                     m_style->addCursor(cachedOrPendingFromValue(CSSPropertyCursor, image), image->hotSpot());
3539                 } else if (type == CSSPrimitiveValue::CSS_IDENT)
3540                     m_style->setCursor(*primitiveValue);
3541             }
3542         } else if (primitiveValue) {
3543             int type = primitiveValue->primitiveType();
3544             if (type == CSSPrimitiveValue::CSS_IDENT && m_style->cursor() != ECursor(*primitiveValue))
3545                 m_style->setCursor(*primitiveValue);
3546         }
3547         return;
3548 // colors || inherit
3549     case CSSPropertyColor:
3550         // If the 'currentColor' keyword is set on the 'color' property itself,
3551         // it is treated as 'color:inherit' at parse time
3552         if (primitiveValue && primitiveValue->getIdent() == CSSValueCurrentcolor)
3553             isInherit = true;
3554     case CSSPropertyBackgroundColor:
3555     case CSSPropertyBorderTopColor:
3556     case CSSPropertyBorderRightColor:
3557     case CSSPropertyBorderBottomColor:
3558     case CSSPropertyBorderLeftColor:
3559     case CSSPropertyOutlineColor:
3560     case CSSPropertyWebkitColumnRuleColor:
3561     case CSSPropertyWebkitTextStrokeColor:
3562     case CSSPropertyWebkitTextFillColor: {
3563         Color col;
3564         if (isInherit) {
3565             HANDLE_INHERIT_COND(CSSPropertyBackgroundColor, backgroundColor, BackgroundColor)
3566             HANDLE_INHERIT_COND_WITH_BACKUP(CSSPropertyBorderTopColor, borderTopColor, color, BorderTopColor)
3567             HANDLE_INHERIT_COND_WITH_BACKUP(CSSPropertyBorderBottomColor, borderBottomColor, color, BorderBottomColor)
3568             HANDLE_INHERIT_COND_WITH_BACKUP(CSSPropertyBorderRightColor, borderRightColor, color, BorderRightColor)
3569             HANDLE_INHERIT_COND_WITH_BACKUP(CSSPropertyBorderLeftColor, borderLeftColor, color, BorderLeftColor)
3570             HANDLE_INHERIT_COND(CSSPropertyColor, color, Color)
3571             HANDLE_INHERIT_COND_WITH_BACKUP(CSSPropertyOutlineColor, outlineColor, color, OutlineColor)
3572             HANDLE_INHERIT_COND_WITH_BACKUP(CSSPropertyWebkitColumnRuleColor, columnRuleColor, color, ColumnRuleColor)
3573             HANDLE_INHERIT_COND_WITH_BACKUP(CSSPropertyWebkitTextStrokeColor, textStrokeColor, color, TextStrokeColor)
3574             HANDLE_INHERIT_COND_WITH_BACKUP(CSSPropertyWebkitTextFillColor, textFillColor, color, TextFillColor)
3575             return;
3576         }
3577         if (isInitial) {
3578             // The border/outline colors will just map to the invalid color |col| above.  This will have the
3579             // effect of forcing the use of the currentColor when it comes time to draw the borders (and of
3580             // not painting the background since the color won't be valid).
3581             if (id == CSSPropertyColor)
3582                 col = RenderStyle::initialColor();
3583         } else {
3584             if (!primitiveValue)
3585                 return;
3586             col = getColorFromPrimitiveValue(primitiveValue);
3587         }
3588
3589         switch (id) {
3590         case CSSPropertyBackgroundColor:
3591             m_style->setBackgroundColor(col);
3592             break;
3593         case CSSPropertyBorderTopColor:
3594             m_style->setBorderTopColor(col);
3595             break;
3596         case CSSPropertyBorderRightColor:
3597             m_style->setBorderRightColor(col);
3598             break;
3599         case CSSPropertyBorderBottomColor:
3600             m_style->setBorderBottomColor(col);
3601             break;
3602         case CSSPropertyBorderLeftColor:
3603             m_style->setBorderLeftColor(col);
3604             break;
3605         case CSSPropertyColor:
3606             m_style->setColor(col);
3607             break;
3608         case CSSPropertyOutlineColor:
3609             m_style->setOutlineColor(col);
3610             break;
3611         case CSSPropertyWebkitColumnRuleColor:
3612             m_style->setColumnRuleColor(col);
3613             break;
3614         case CSSPropertyWebkitTextStrokeColor:
3615             m_style->setTextStrokeColor(col);
3616             break;
3617         case CSSPropertyWebkitTextFillColor:
3618             m_style->setTextFillColor(col);
3619             break;
3620         }
3621         
3622         return;
3623     }
3624     
3625 // uri || inherit
3626     case CSSPropertyBackgroundImage:
3627         HANDLE_BACKGROUND_VALUE(image, Image, value)
3628         return;
3629     case CSSPropertyWebkitMaskImage:
3630         HANDLE_MASK_VALUE(image, Image, value)
3631         return;
3632     case CSSPropertyListStyleImage:
3633     {
3634         HANDLE_INHERIT_AND_INITIAL(listStyleImage, ListStyleImage)
3635         m_style->setListStyleImage(styleImage(CSSPropertyListStyleImage, value));
3636         return;
3637     }
3638
3639 // length
3640     case CSSPropertyBorderTopWidth:
3641     case CSSPropertyBorderRightWidth:
3642     case CSSPropertyBorderBottomWidth:
3643     case CSSPropertyBorderLeftWidth:
3644     case CSSPropertyOutlineWidth:
3645     case CSSPropertyWebkitColumnRuleWidth:
3646     {
3647         if (isInherit) {
3648             HANDLE_INHERIT_COND(CSSPropertyBorderTopWidth, borderTopWidth, BorderTopWidth)
3649             HANDLE_INHERIT_COND(CSSPropertyBorderRightWidth, borderRightWidth, BorderRightWidth)
3650             HANDLE_INHERIT_COND(CSSPropertyBorderBottomWidth, borderBottomWidth, BorderBottomWidth)
3651             HANDLE_INHERIT_COND(CSSPropertyBorderLeftWidth, borderLeftWidth, BorderLeftWidth)
3652             HANDLE_INHERIT_COND(CSSPropertyOutlineWidth, outlineWidth, OutlineWidth)
3653             HANDLE_INHERIT_COND(CSSPropertyWebkitColumnRuleWidth, columnRuleWidth, ColumnRuleWidth)
3654             return;
3655         }
3656         else if (isInitial) {
3657             HANDLE_INITIAL_COND_WITH_VALUE(CSSPropertyBorderTopWidth, BorderTopWidth, BorderWidth)
3658             HANDLE_INITIAL_COND_WITH_VALUE(CSSPropertyBorderRightWidth, BorderRightWidth, BorderWidth)
3659             HANDLE_INITIAL_COND_WITH_VALUE(CSSPropertyBorderBottomWidth, BorderBottomWidth, BorderWidth)
3660             HANDLE_INITIAL_COND_WITH_VALUE(CSSPropertyBorderLeftWidth, BorderLeftWidth, BorderWidth)
3661             HANDLE_INITIAL_COND_WITH_VALUE(CSSPropertyOutlineWidth, OutlineWidth, BorderWidth)
3662             HANDLE_INITIAL_COND_WITH_VALUE(CSSPropertyWebkitColumnRuleWidth, ColumnRuleWidth, BorderWidth)
3663             return;
3664         }
3665
3666         if (!primitiveValue)
3667             return;
3668         short width = 3;
3669         switch (primitiveValue->getIdent()) {
3670         case CSSValueThin:
3671             width = 1;
3672             break;
3673         case CSSValueMedium:
3674             width = 3;
3675             break;
3676         case CSSValueThick:
3677             width = 5;
3678             break;
3679         case CSSValueInvalid:
3680             width = primitiveValue->computeLengthShort(style(), m_rootElementStyle, zoomFactor);
3681             break;
3682         default:
3683             return;
3684         }
3685
3686         if (width < 0) return;
3687         switch (id) {
3688         case CSSPropertyBorderTopWidth:
3689             m_style->setBorderTopWidth(width);
3690             break;
3691         case CSSPropertyBorderRightWidth:
3692             m_style->setBorderRightWidth(width);
3693             break;
3694         case CSSPropertyBorderBottomWidth:
3695             m_style->setBorderBottomWidth(width);
3696             break;
3697         case CSSPropertyBorderLeftWidth:
3698             m_style->setBorderLeftWidth(width);
3699             break;
3700         case CSSPropertyOutlineWidth:
3701             m_style->setOutlineWidth(width);
3702             break;
3703         case CSSPropertyWebkitColumnRuleWidth:
3704             m_style->setColumnRuleWidth(width);
3705             break;
3706         default:
3707             return;
3708         }
3709         return;
3710     }
3711
3712     case CSSPropertyWebkitFontSmoothing: {
3713         FontDescription fontDescription = m_style->fontDescription();
3714         if (isInherit) 
3715             fontDescription.setFontSmoothing(m_parentStyle->fontDescription().fontSmoothing());
3716         else if (isInitial)
3717             fontDescription.setFontSmoothing(AutoSmoothing);
3718         else {
3719             if (!primitiveValue)
3720                 return;
3721             int id = primitiveValue->getIdent();
3722             FontSmoothingMode smoothing;
3723             switch (id) {
3724                 case CSSValueAuto:
3725                     smoothing = AutoSmoothing;
3726                     break;
3727                 case CSSValueNone:
3728                     smoothing = NoSmoothing;
3729                     break;
3730                 case CSSValueAntialiased:
3731                     smoothing = Antialiased;
3732                     break;
3733                 case CSSValueSubpixelAntialiased:
3734                     smoothing = SubpixelAntialiased;
3735                     break;
3736                 default:
3737                     ASSERT_NOT_REACHED();
3738                     smoothing = AutoSmoothing;
3739             }
3740             fontDescription.setFontSmoothing(smoothing);
3741         }
3742         if (m_style->setFontDescription(fontDescription))
3743             m_fontDirty = true;
3744         return;
3745     }
3746
3747     case CSSPropertyLetterSpacing:
3748     case CSSPropertyWordSpacing:
3749     {
3750         
3751         if (isInherit) {
3752             HANDLE_INHERIT_COND(CSSPropertyLetterSpacing, letterSpacing, LetterSpacing)
3753             HANDLE_INHERIT_COND(CSSPropertyWordSpacing, wordSpacing, WordSpacing)
3754             return;
3755         }
3756         else if (isInitial) {
3757             HANDLE_INITIAL_COND_WITH_VALUE(CSSPropertyLetterSpacing, LetterSpacing, LetterWordSpacing)
3758             HANDLE_INITIAL_COND_WITH_VALUE(CSSPropertyWordSpacing, WordSpacing, LetterWordSpacing)
3759             return;
3760         }
3761         
3762         int width = 0;
3763         if (primitiveValue && primitiveValue->getIdent() == CSSValueNormal) {
3764             width = 0;
3765         } else {
3766             if (!primitiveValue)
3767                 return;
3768             width = primitiveValue->computeLengthInt(style(), m_rootElementStyle, useSVGZoomRules ? 1.0f : zoomFactor);
3769         }
3770         switch (id) {
3771         case CSSPropertyLetterSpacing:
3772             m_style->setLetterSpacing(width);
3773             break;
3774         case CSSPropertyWordSpacing:
3775             m_style->setWordSpacing(width);
3776             break;
3777             // ### needs the definitions in renderstyle
3778         default: break;
3779         }
3780         return;
3781     }
3782
3783     case CSSPropertyWordBreak:
3784         HANDLE_INHERIT_AND_INITIAL_AND_PRIMITIVE(wordBreak, WordBreak)
3785         return;
3786     case CSSPropertyWordWrap:
3787         HANDLE_INHERIT_AND_INITIAL_AND_PRIMITIVE(wordWrap, WordWrap)
3788         return;
3789     case CSSPropertyWebkitNbspMode:
3790         HANDLE_INHERIT_AND_INITIAL_AND_PRIMITIVE(nbspMode, NBSPMode)
3791         return;
3792     case CSSPropertyWebkitLineBreak:
3793         HANDLE_INHERIT_AND_INITIAL_AND_PRIMITIVE(khtmlLineBreak, KHTMLLineBreak)
3794         return;
3795     case CSSPropertyWebkitMatchNearestMailBlockquoteColor:
3796         HANDLE_INHERIT_AND_INITIAL_AND_PRIMITIVE(matchNearestMailBlockquoteColor, MatchNearestMailBlockquoteColor)
3797         return;
3798
3799     case CSSPropertyResize:
3800     {
3801         HANDLE_INHERIT_AND_INITIAL(resize, Resize)
3802
3803         if (!primitiveValue->getIdent())
3804             return;
3805
3806         EResize r = RESIZE_NONE;
3807         if (primitiveValue->getIdent() == CSSValueAuto) {
3808             if (Settings* settings = m_checker.m_document->settings())
3809                 r = settings->textAreasAreResizable() ? RESIZE_BOTH : RESIZE_NONE;
3810         } else
3811             r = *primitiveValue;
3812             
3813         m_style->setResize(r);
3814         return;
3815     }
3816     
3817     // length, percent
3818     case CSSPropertyMaxWidth:
3819         // +none +inherit
3820         if (primitiveValue && primitiveValue->getIdent() == CSSValueNone)
3821             apply = true;
3822     case CSSPropertyTop:
3823     case CSSPropertyLeft:
3824     case CSSPropertyRight:
3825     case CSSPropertyBottom:
3826     case CSSPropertyWidth:
3827     case CSSPropertyMinWidth:
3828     case CSSPropertyMarginTop:
3829     case CSSPropertyMarginRight:
3830     case CSSPropertyMarginBottom:
3831     case CSSPropertyMarginLeft:
3832         // +inherit +auto
3833         if (id == CSSPropertyWidth || id == CSSPropertyMinWidth || id == CSSPropertyMaxWidth) {
3834             if (primitiveValue && primitiveValue->getIdent() == CSSValueIntrinsic) {
3835                 l = Length(Intrinsic);
3836                 apply = true;
3837             }
3838             else if (primitiveValue && primitiveValue->getIdent() == CSSValueMinIntrinsic) {
3839                 l = Length(MinIntrinsic);
3840                 apply = true;
3841             }
3842         }
3843         if (id != CSSPropertyMaxWidth && primitiveValue && primitiveValue->getIdent() == CSSValueAuto)
3844             apply = true;
3845     case CSSPropertyPaddingTop:
3846     case CSSPropertyPaddingRight:
3847     case CSSPropertyPaddingBottom:
3848     case CSSPropertyPaddingLeft:
3849     case CSSPropertyTextIndent:
3850         // +inherit
3851     {
3852         if (isInherit) {
3853             HANDLE_INHERIT_COND(CSSPropertyMaxWidth, maxWidth, MaxWidth)
3854             HANDLE_INHERIT_COND(CSSPropertyBottom, bottom, Bottom)
3855             HANDLE_INHERIT_COND(CSSPropertyTop, top, Top)
3856             HANDLE_INHERIT_COND(CSSPropertyLeft, left, Left)
3857             HANDLE_INHERIT_COND(CSSPropertyRight, right, Right)
3858             HANDLE_INHERIT_COND(CSSPropertyWidth, width, Width)
3859             HANDLE_INHERIT_COND(CSSPropertyMinWidth, minWidth, MinWidth)
3860             HANDLE_INHERIT_COND(CSSPropertyPaddingTop, paddingTop, PaddingTop)
3861             HANDLE_INHERIT_COND(CSSPropertyPaddingRight, paddingRight, PaddingRight)
3862             HANDLE_INHERIT_COND(CSSPropertyPaddingBottom, paddingBottom, PaddingBottom)
3863             HANDLE_INHERIT_COND(CSSPropertyPaddingLeft, paddingLeft, PaddingLeft)
3864             HANDLE_INHERIT_COND(CSSPropertyMarginTop, marginTop, MarginTop)
3865             HANDLE_INHERIT_COND(CSSPropertyMarginRight, marginRight, MarginRight)
3866             HANDLE_INHERIT_COND(CSSPropertyMarginBottom, marginBottom, MarginBottom)
3867             HANDLE_INHERIT_COND(CSSPropertyMarginLeft, marginLeft, MarginLeft)
3868             HANDLE_INHERIT_COND(CSSPropertyTextIndent, textIndent, TextIndent)
3869             return;
3870         }
3871         else if (isInitial) {
3872             HANDLE_INITIAL_COND_WITH_VALUE(CSSPropertyMaxWidth, MaxWidth, MaxSize)
3873             HANDLE_INITIAL_COND_WITH_VALUE(CSSPropertyBottom, Bottom, Offset)
3874             HANDLE_INITIAL_COND_WITH_VALUE(CSSPropertyTop, Top, Offset)
3875             HANDLE_INITIAL_COND_WITH_VALUE(CSSPropertyLeft, Left, Offset)
3876             HANDLE_INITIAL_COND_WITH_VALUE(CSSPropertyRight, Right, Offset)
3877             HANDLE_INITIAL_COND_WITH_VALUE(CSSPropertyWidth, Width, Size)
3878             HANDLE_INITIAL_COND_WITH_VALUE(CSSPropertyMinWidth, MinWidth, MinSize)
3879             HANDLE_INITIAL_COND_WITH_VALUE(CSSPropertyPaddingTop, PaddingTop, Padding)
3880             HANDLE_INITIAL_COND_WITH_VALUE(CSSPropertyPaddingRight, PaddingRight, Padding)
3881             HANDLE_INITIAL_COND_WITH_VALUE(CSSPropertyPaddingBottom, PaddingBottom, Padding)
3882             HANDLE_INITIAL_COND_WITH_VALUE(CSSPropertyPaddingLeft, PaddingLeft, Padding)
3883             HANDLE_INITIAL_COND_WITH_VALUE(CSSPropertyMarginTop, MarginTop, Margin)
3884             HANDLE_INITIAL_COND_WITH_VALUE(CSSPropertyMarginRight, MarginRight, Margin)
3885             HANDLE_INITIAL_COND_WITH_VALUE(CSSPropertyMarginBottom, MarginBottom, Margin)
3886             HANDLE_INITIAL_COND_WITH_VALUE(CSSPropertyMarginLeft, MarginLeft, Margin)
3887             HANDLE_INITIAL_COND(CSSPropertyTextIndent, TextIndent)
3888             return;
3889         } 
3890
3891         if (primitiveValue && !apply) {
3892             int type = primitiveValue->primitiveType();
3893             if (CSSPrimitiveValue::isUnitTypeLength(type))
3894                 // Handle our quirky margin units if we have them.
3895                 l = Length(primitiveValue->computeLengthIntForLength(style(), m_rootElementStyle, zoomFactor), Fixed, 
3896                            primitiveValue->isQuirkValue());
3897             else if (type == CSSPrimitiveValue::CSS_PERCENTAGE)
3898                 l = Length(primitiveValue->getDoubleValue(), Percent);
3899             else
3900                 return;
3901             apply = true;
3902         }
3903         if (!apply) return;
3904         switch (id) {
3905             case CSSPropertyMaxWidth:
3906                 m_style->setMaxWidth(l);
3907                 break;
3908             case CSSPropertyBottom:
3909                 m_style->setBottom(l);
3910                 break;
3911             case CSSPropertyTop:
3912                 m_style->setTop(l);
3913                 break;
3914             case CSSPropertyLeft:
3915                 m_style->setLeft(l);
3916                 break;
3917             case CSSPropertyRight:
3918                 m_style->setRight(l);
3919                 break;
3920             case CSSPropertyWidth:
3921                 m_style->setWidth(l);
3922                 break;
3923             case CSSPropertyMinWidth:
3924                 m_style->setMinWidth(l);
3925                 break;
3926             case CSSPropertyPaddingTop:
3927                 m_style->setPaddingTop(l);
3928                 break;
3929             case CSSPropertyPaddingRight:
3930                 m_style->setPaddingRight(l);
3931                 break;
3932             case CSSPropertyPaddingBottom:
3933                 m_style->setPaddingBottom(l);
3934                 break;
3935             case CSSPropertyPaddingLeft:
3936                 m_style->setPaddingLeft(l);
3937                 break;
3938             case CSSPropertyMarginTop:
3939                 m_style->setMarginTop(l);
3940                 break;
3941             case CSSPropertyMarginRight:
3942                 m_style->setMarginRight(l);
3943                 break;
3944             case CSSPropertyMarginBottom:
3945                 m_style->setMarginBottom(l);
3946                 break;
3947             case CSSPropertyMarginLeft:
3948                 m_style->setMarginLeft(l);
3949                 break;
3950             case CSSPropertyTextIndent:
3951                 m_style->setTextIndent(l);
3952                 break;
3953             default:
3954                 break;
3955             }
3956         return;
3957     }
3958
3959     case CSSPropertyMaxHeight:
3960         if (primitiveValue && primitiveValue->getIdent() == CSSValueNone) {
3961             l = Length(undefinedLength, Fixed);
3962             apply = true;
3963         }
3964     case CSSPropertyHeight:
3965     case CSSPropertyMinHeight:
3966         if (primitiveValue && primitiveValue->getIdent() == CSSValueIntrinsic) {
3967             l = Length(Intrinsic);
3968             apply = true;
3969         } else if (primitiveValue && primitiveValue->getIdent() == CSSValueMinIntrinsic) {
3970             l = Length(MinIntrinsic);
3971             apply = true;
3972         } else if (id != CSSPropertyMaxHeight && primitiveValue && primitiveValue->getIdent() == CSSValueAuto)
3973             apply = true;
3974         if (isInherit) {
3975             HANDLE_INHERIT_COND(CSSPropertyMaxHeight, maxHeight, MaxHeight)
3976             HANDLE_INHERIT_COND(CSSPropertyHeight, height, Height)
3977             HANDLE_INHERIT_COND(CSSPropertyMinHeight, minHeight, MinHeight)
3978             return;
3979         }
3980         if (isInitial) {
3981             HANDLE_INITIAL_COND_WITH_VALUE(CSSPropertyMaxHeight, MaxHeight, MaxSize)
3982             HANDLE_INITIAL_COND_WITH_VALUE(CSSPropertyHeight, Height, Size)
3983             HANDLE_INITIAL_COND_WITH_VALUE(CSSPropertyMinHeight, MinHeight, MinSize)
3984             return;
3985         }
3986
3987         if (primitiveValue && !apply) {
3988             unsigned short type = primitiveValue->primitiveType();
3989             if (CSSPrimitiveValue::isUnitTypeLength(type))
3990                 l = Length(primitiveValue->computeLengthIntForLength(style(), m_rootElementStyle, zoomFactor), Fixed);
3991             else if (type == CSSPrimitiveValue::CSS_PERCENTAGE)
3992                 l = Length(primitiveValue->getDoubleValue(), Percent);
3993             else
3994                 return;
3995             apply = true;
3996         }
3997         if (apply)
3998             switch (id) {
3999                 case CSSPropertyMaxHeight:
4000                     m_style->setMaxHeight(l);
4001                     break;
4002                 case CSSPropertyHeight:
4003                     m_style->setHeight(l);
4004                     break;
4005                 case CSSPropertyMinHeight:
4006                     m_style->setMinHeight(l);
4007                     break;
4008             }
4009         return;
4010
4011     case CSSPropertyVerticalAlign:
4012         HANDLE_INHERIT_AND_INITIAL(verticalAlign, VerticalAlign)
4013         if (!primitiveValue)
4014             return;
4015         if (primitiveValue->getIdent()) {
4016           EVerticalAlign align;
4017
4018           switch (primitiveValue->getIdent()) {
4019                 case CSSValueTop:
4020                     align = TOP; break;
4021                 case CSSValueBottom:
4022                     align = BOTTOM; break;
4023                 case CSSValueMiddle:
4024                     align = MIDDLE; break;
4025                 case CSSValueBaseline:
4026                     align = BASELINE; break;
4027                 case CSSValueTextBottom:
4028                     align = TEXT_BOTTOM; break;
4029                 case CSSValueTextTop:
4030                     align = TEXT_TOP; break;
4031                 case CSSValueSub:
4032                     align = SUB; break;
4033                 case CSSValueSuper:
4034                     align = SUPER; break;
4035                 case CSSValueWebkitBaselineMiddle:
4036                     align = BASELINE_MIDDLE; break;
4037                 default:
4038                     return;
4039             }
4040           m_style->setVerticalAlign(align);
4041           return;
4042         } else {
4043           int type = primitiveValue->primitiveType();
4044           Length l;
4045           if (CSSPrimitiveValue::isUnitTypeLength(type))
4046             l = Length(primitiveValue->computeLengthIntForLength(style(), m_rootElementStyle, zoomFactor), Fixed);
4047           else if (type == CSSPrimitiveValue::CSS_PERCENTAGE)
4048             l = Length(primitiveValue->getDoubleValue(), Percent);
4049
4050           m_style->setVerticalAlign(LENGTH);
4051           m_style->setVerticalAlignLength(l);
4052         }
4053         return;
4054
4055     case CSSPropertyFontSize:
4056     {
4057         FontDescription fontDescription = m_style->fontDescription();
4058         fontDescription.setKeywordSize(0);
4059         float oldSize = 0;
4060         float size = 0;
4061         
4062         bool parentIsAbsoluteSize = false;
4063         if (m_parentNode) {
4064             oldSize = m_parentStyle->fontDescription().specifiedSize();
4065             parentIsAbsoluteSize = m_parentStyle->fontDescription().isAbsoluteSize();
4066         }
4067
4068         if (isInherit) {
4069             size = oldSize;
4070             if (m_parentNode)
4071                 fontDescription.setKeywordSize(m_parentStyle->fontDescription().keywordSize());
4072         } else if (isInitial) {
4073             size = fontSizeForKeyword(m_checker.m_document, CSSValueMedium, fontDescription.useFixedDefaultSize());
4074             fontDescription.setKeywordSize(CSSValueMedium - CSSValueXxSmall + 1);
4075         } else if (primitiveValue->getIdent()) {
4076             // Keywords are being used.
4077             switch (primitiveValue->getIdent()) {
4078                 case CSSValueXxSmall:
4079                 case CSSValueXSmall:
4080                 case CSSValueSmall:
4081                 case CSSValueMedium:
4082                 case CSSValueLarge:
4083                 case CSSValueXLarge:
4084                 case CSSValueXxLarge:
4085                 case CSSValueWebkitXxxLarge:
4086                     size = fontSizeForKeyword(m_checker.m_document, primitiveValue->getIdent(), fontDescription.useFixedDefaultSize());
4087                     fontDescription.setKeywordSize(primitiveValue->getIdent() - CSSValueXxSmall + 1);
4088                     break;
4089                 case CSSValueLarger:
4090                     size = largerFontSize(oldSize, m_checker.m_document->inQuirksMode());
4091                     break;
4092                 case CSSValueSmaller:
4093                     size = smallerFontSize(oldSize, m_checker.m_document->inQuirksMode());
4094                     break;
4095                 default:
4096                     return;
4097             }
4098
4099             fontDescription.setIsAbsoluteSize(parentIsAbsoluteSize && 
4100                                               (primitiveValue->getIdent() == CSSValueLarger ||
4101                                                primitiveValue->getIdent() == CSSValueSmaller));
4102         } else {
4103             int type = primitiveValue->primitiveType();
4104             fontDescription.setIsAbsoluteSize(parentIsAbsoluteSize ||
4105                                               (type != CSSPrimitiveValue::CSS_PERCENTAGE &&
4106                                                type != CSSPrimitiveValue::CSS_EMS && 
4107                                                type != CSSPrimitiveValue::CSS_EXS &&
4108                                                type != CSSPrimitiveValue::CSS_REMS));
4109             if (CSSPrimitiveValue::isUnitTypeLength(type))
4110                 size = primitiveValue->computeLengthFloat(m_parentStyle, m_rootElementStyle, true);
4111             else if (type == CSSPrimitiveValue::CSS_PERCENTAGE)
4112                 size = (primitiveValue->getFloatValue() * oldSize) / 100.0f;
4113             else
4114                 return;
4115         }
4116
4117         if (size < 0)
4118             return;
4119
4120         setFontSize(fontDescription, size);
4121         if (m_style->setFontDescription(fontDescription))
4122             m_fontDirty = true;
4123         return;
4124     }
4125
4126     case CSSPropertyZIndex: {
4127         if (isInherit) {
4128             if (m_parentStyle->hasAutoZIndex())
4129                 m_style->setHasAutoZIndex();
4130             else
4131                 m_style->setZIndex(m_parentStyle->zIndex());
4132             return;
4133         } else if (isInitial || primitiveValue->getIdent() == CSSValueAuto) {
4134             m_style->setHasAutoZIndex();
4135             return;
4136         }
4137         
4138         // FIXME: Should clamp all sorts of other integer properties too.
4139         const double minIntAsDouble = INT_MIN;
4140         const double maxIntAsDouble = INT_MAX;
4141         m_style->setZIndex(static_cast<int>(max(minIntAsDouble, min(primitiveValue->getDoubleValue(), maxIntAsDouble))));
4142         return;
4143     }
4144     case CSSPropertyWidows:
4145     {
4146         HANDLE_INHERIT_AND_INITIAL(widows, Widows)
4147         if (!primitiveValue || primitiveValue->primitiveType() != CSSPrimitiveValue::CSS_NUMBER)
4148             return;
4149         m_style->setWidows(primitiveValue->getIntValue());
4150         return;
4151     }
4152         
4153     case CSSPropertyOrphans:
4154     {
4155         HANDLE_INHERIT_AND_INITIAL(orphans, Orphans)
4156         if (!primitiveValue || primitiveValue->primitiveType() != CSSPrimitiveValue::CSS_NUMBER)
4157             return;
4158         m_style->setOrphans(primitiveValue->getIntValue());
4159         return;
4160     }        
4161
4162 // length, percent, number
4163     case CSSPropertyLineHeight:
4164     {
4165         HANDLE_INHERIT_AND_INITIAL(lineHeight, LineHeight)
4166         if (!primitiveValue)
4167             return;
4168         Length lineHeight;
4169         int type = primitiveValue->primitiveType();
4170         if (primitiveValue->getIdent() == CSSValueNormal)
4171             lineHeight = Length(-100.0, Percent);
4172         else if (CSSPrimitiveValue::isUnitTypeLength(type)) {
4173             double multiplier = zoomFactor;
4174             if (m_style->textSizeAdjust()) {
4175                 if (Frame* frame = m_checker.m_document->frame())
4176                     multiplier *= frame->textZoomFactor();
4177             }
4178             lineHeight = Length(primitiveValue->computeLengthIntForLength(style(), m_rootElementStyle,  multiplier), Fixed);
4179         } else if (type == CSSPrimitiveValue::CSS_PERCENTAGE)
4180             lineHeight = Length((m_style->fontSize() * primitiveValue->getIntValue()) / 100, Fixed);
4181         else if (type == CSSPrimitiveValue::CSS_NUMBER)
4182             lineHeight = Length(primitiveValue->getDoubleValue() * 100.0, Percent);
4183         else
4184             return;
4185         m_style->setLineHeight(lineHeight);
4186         return;
4187     }
4188
4189 // string
4190     case CSSPropertyTextAlign:
4191     {
4192         HANDLE_INHERIT_AND_INITIAL(textAlign, TextAlign)
4193         if (!primitiveValue)
4194             return;
4195         int id = primitiveValue->getIdent();
4196         if (id == CSSValueStart)
4197             m_style->setTextAlign(m_style->isLeftToRightDirection() ? LEFT : RIGHT);
4198         else if (id == CSSValueEnd)
4199             m_style->setTextAlign(m_style->isLeftToRightDirection() ? RIGHT : LEFT);
4200         else
4201             m_style->setTextAlign(*primitiveValue);
4202         return;
4203     }
4204
4205 // rect
4206     case CSSPropertyClip:
4207     {
4208         Length top;
4209         Length right;
4210         Length bottom;
4211         Length left;
4212         bool hasClip = true;
4213         if (isInherit) {
4214             if (m_parentStyle->hasClip()) {
4215                 top = m_parentStyle->clipTop();
4216                 right = m_parentStyle->clipRight();
4217                 bottom = m_parentStyle->clipBottom();
4218                 left = m_parentStyle->clipLeft();
4219             } else {
4220                 hasClip = false;
4221                 top = right = bottom = left = Length();
4222             }
4223         } else if (isInitial) {
4224             hasClip = false;
4225             top = right = bottom = left = Length();
4226         } else if (!primitiveValue) {
4227             return;
4228         } else if (primitiveValue->primitiveType() == CSSPrimitiveValue::CSS_RECT) {
4229             Rect* rect = primitiveValue->getRectValue();
4230             if (!rect)
4231                 return;
4232             top = convertToLength(rect->top(), style(), m_rootElementStyle, zoomFactor);
4233             right = convertToLength(rect->right(), style(), m_rootElementStyle, zoomFactor);
4234             bottom = convertToLength(rect->bottom(), style(), m_rootElementStyle, zoomFactor);
4235             left = convertToLength(rect->left(), style(), m_rootElementStyle, zoomFactor);
4236         } else if (primitiveValue->getIdent() != CSSValueAuto) {
4237             return;
4238         }
4239         m_style->setClip(top, right, bottom, left);
4240         m_style->setHasClip(hasClip);
4241     
4242         // rect, ident
4243         return;
4244     }
4245
4246 // lists
4247     case CSSPropertyContent:
4248         // list of string, uri, counter, attr, i
4249     {
4250         // FIXME: In CSS3, it will be possible to inherit content.  In CSS2 it is not.  This
4251         // note is a reminder that eventually "inherit" needs to be supported.
4252
4253         if (isInitial) {
4254             m_style->clearContent();
4255             return;
4256         }
4257         
4258         if (!value->isValueList())
4259             return;
4260
4261         CSSValueList* list = static_cast<CSSValueList*>(value);
4262         int len = list->length();
4263
4264         bool didSet = false;
4265         for (int i = 0; i < len; i++) {
4266             CSSValue* item = list->itemWithoutBoundsCheck(i);
4267             if (item->isImageGeneratorValue()) {
4268                 m_style->setContent(static_cast<CSSImageGeneratorValue*>(item)->generatedImage(), didSet);
4269                 didSet = true;
4270             }
4271             
4272             if (!item->isPrimitiveValue())
4273                 continue;
4274             
4275             CSSPrimitiveValue* val = static_cast<CSSPrimitiveValue*>(item);
4276             switch (val->primitiveType()) {
4277                 case CSSPrimitiveValue::CSS_STRING:
4278                     m_style->setContent(val->getStringValue().impl(), didSet);
4279                     didSet = true;
4280                     break;
4281                 case CSSPrimitiveValue::CSS_ATTR: {
4282                     // FIXME: Can a namespace be specified for an attr(foo)?
4283                     if (m_style->styleType() == NOPSEUDO)
4284                         m_style->setUnique();
4285                     else
4286                         m_parentStyle->setUnique();
4287                     QualifiedName attr(nullAtom, val->getStringValue().impl(), nullAtom);
4288                     m_style->setContent(m_element->getAttribute(attr).impl(), didSet);
4289                     didSet = true;
4290                     // register the fact that the attribute value affects the style
4291                     m_selectorAttrs.add(attr.localName().impl());
4292                     break;
4293                 }
4294                 case CSSPrimitiveValue::CSS_URI: {
4295                     m_style->setContent(cachedOrPendingFromValue(CSSPropertyContent, static_cast<CSSImageValue*>(val)), didSet);
4296                     didSet = true;
4297                     break;
4298                 }
4299                 case CSSPrimitiveValue::CSS_COUNTER: {
4300                     Counter* counterValue = val->getCounterValue();
4301                     OwnPtr<CounterContent> counter = adoptPtr(new CounterContent(counterValue->identifier(),
4302                         (EListStyleType)counterValue->listStyleNumber(), counterValue->separator()));
4303                     m_style->setContent(counter.release(), didSet);
4304                     didSet = true;
4305                 }
4306             }
4307         }
4308         if (!didSet)
4309             m_style->clearContent();
4310         return;
4311     }
4312
4313     case CSSPropertyCounterIncrement:
4314         applyCounterList(style(), value->isValueList() ? static_cast<CSSValueList*>(value) : 0, false);
4315         return;
4316     case CSSPropertyCounterReset:
4317         applyCounterList(style(), value->isValueList() ? static_cast<CSSValueList*>(value) : 0, true);
4318         return;
4319
4320     case CSSPropertyFontFamily: {
4321         // list of strings and ids
4322         if (isInherit) {
4323             FontDescription parentFontDescription = m_parentStyle->fontDescription();
4324             FontDescription fontDescription = m_style->fontDescription();
4325             fontDescription.setGenericFamily(parentFontDescription.genericFamily());
4326             fontDescription.setFamily(parentFontDescription.firstFamily());
4327             fontDescription.setIsSpecifiedFont(parentFontDescription.isSpecifiedFont());
4328             if (m_style->setFontDescription(fontDescription))
4329                 m_fontDirty = true;
4330             return;
4331         } else if (isInitial) {
4332             FontDescription initialDesc = FontDescription();
4333             FontDescription fontDescription = m_style->fontDescription();
4334             // We need to adjust the size to account for the generic family change from monospace
4335             // to non-monospace.
4336             if (fontDescription.keywordSize() && fontDescription.useFixedDefaultSize())
4337                 setFontSize(fontDescription, fontSizeForKeyword(m_checker.m_document, CSSValueXxSmall + fontDescription.keywordSize() - 1, false));
4338             fontDescription.setGenericFamily(initialDesc.genericFamily());
4339             if (!initialDesc.firstFamily().familyIsEmpty())
4340                 fontDescription.setFamily(initialDesc.firstFamily());
4341             if (m_style->setFontDescription(fontDescription))
4342                 m_fontDirty = true;
4343             return;
4344         }
4345         
4346         if (!value->isValueList())
4347             return;
4348         FontDescription fontDescription = m_style->fontDescription();
4349         CSSValueList* list = static_cast<CSSValueList*>(value);
4350         int len = list->length();
4351         FontFamily& firstFamily = fontDescription.firstFamily();
4352         FontFamily* currFamily = 0;
4353         
4354         // Before mapping in a new font-family property, we should reset the generic family.
4355         bool oldFamilyUsedFixedDefaultSize = fontDescription.useFixedDefaultSize();
4356         fontDescription.setGenericFamily(FontDescription::NoFamily);
4357
4358         for (int i = 0; i < len; i++) {
4359             CSSValue* item = list->itemWithoutBoundsCheck(i);
4360             if (!item->isPrimitiveValue())
4361                 continue;
4362             CSSPrimitiveValue* val = static_cast<CSSPrimitiveValue*>(item);
4363             AtomicString face;
4364             Settings* settings = m_checker.m_document->settings();
4365             if (val->primitiveType() == CSSPrimitiveValue::CSS_STRING)
4366                 face = static_cast<FontFamilyValue*>(val)->familyName();
4367             else if (val->primitiveType() == CSSPrimitiveValue::CSS_IDENT && settings) {
4368                 switch (val->getIdent()) {
4369                     case CSSValueWebkitBody:
4370                         face = settings->standardFontFamily();
4371                         break;
4372                     case CSSValueSerif:
4373                         face = "-webkit-serif";
4374                         fontDescription.setGenericFamily(FontDescription::SerifFamily);
4375                         break;
4376                     case CSSValueSansSerif:
4377                         face = "-webkit-sans-serif";
4378                         fontDescription.setGenericFamily(FontDescription::SansSerifFamily);
4379                         break;
4380                     case CSSValueCursive:
4381                         face = "-webkit-cursive";
4382                         fontDescription.setGenericFamily(FontDescription::CursiveFamily);
4383                         break;
4384                     case CSSValueFantasy:
4385                         face = "-webkit-fantasy";
4386                         fontDescription.setGenericFamily(FontDescription::FantasyFamily);
4387                         break;
4388                     case CSSValueMonospace:
4389                         face = "-webkit-monospace";
4390                         fontDescription.setGenericFamily(FontDescription::MonospaceFamily);
4391                         break;
4392                 }
4393             }
4394
4395             if (!face.isEmpty()) {
4396                 if (!currFamily) {
4397                     // Filling in the first family.
4398                     firstFamily.setFamily(face);
4399                     firstFamily.appendFamily(0); // Remove any inherited family-fallback list.
4400                     currFamily = &firstFamily;
4401                     fontDescription.setIsSpecifiedFont(fontDescription.genericFamily() == FontDescription::NoFamily);
4402                 } else {
4403                     RefPtr<SharedFontFamily> newFamily = SharedFontFamily::create();
4404                     newFamily->setFamily(face);
4405                     currFamily->appendFamily(newFamily);
4406                     currFamily = newFamily.get();
4407                 }
4408             }
4409         }
4410
4411         // We can't call useFixedDefaultSize() until all new font families have been added
4412         // If currFamily is non-zero then we set at least one family on this description.
4413         if (currFamily) {
4414             if (fontDescription.keywordSize() && fontDescription.useFixedDefaultSize() != oldFamilyUsedFixedDefaultSize)
4415                 setFontSize(fontDescription, fontSizeForKeyword(m_checker.m_document, CSSValueXxSmall + fontDescription.keywordSize() - 1, !oldFamilyUsedFixedDefaultSize));
4416
4417             if (m_style->setFontDescription(fontDescription))
4418                 m_fontDirty = true;
4419         }
4420         return;
4421     }
4422     case CSSPropertyTextDecoration: {
4423         // list of ident
4424         HANDLE_INHERIT_AND_INITIAL(textDecoration, TextDecoration)
4425         int t = RenderStyle::initialTextDecoration();
4426         if (primitiveValue && primitiveValue->getIdent() == CSSValueNone) {
4427             // do nothing
4428         } else {
4429             if (!value->isValueList()) return;
4430             CSSValueList *list = static_cast<CSSValueList*>(value);
4431             int len = list->length();
4432             for (int i = 0; i < len; i++)
4433             {
4434                 CSSValue *item = list->itemWithoutBoundsCheck(i);
4435                 if (!item->isPrimitiveValue()) continue;
4436                 primitiveValue = static_cast<CSSPrimitiveValue*>(item);
4437                 switch (primitiveValue->getIdent()) {
4438                     case CSSValueNone:
4439                         t = TDNONE; break;
4440                     case CSSValueUnderline:
4441                         t |= UNDERLINE; break;
4442                     case CSSValueOverline:
4443                         t |= OVERLINE; break;
4444                     case CSSValueLineThrough:
4445                         t |= LINE_THROUGH; break;
4446                     case CSSValueBlink:
4447                         t |= BLINK; break;
4448                     default:
4449                         return;
4450                 }
4451             }
4452         }
4453
4454         m_style->setTextDecoration(t);
4455         return;
4456     }
4457
4458     case CSSPropertyZoom:
4459     {
4460         // Reset the zoom in effect before we do anything.  This allows the setZoom method to accurately compute a new
4461         // zoom in effect.
4462         m_style->setEffectiveZoom(m_parentStyle ? m_parentStyle->effectiveZoom() : RenderStyle::initialZoom());
4463         
4464         // Now we can handle inherit and initial.
4465         HANDLE_INHERIT_AND_INITIAL(zoom, Zoom)
4466         
4467         // Handle normal/reset, numbers and percentages.
4468         int type = primitiveValue->primitiveType();
4469         if (primitiveValue->getIdent() == CSSValueNormal)
4470             m_style->setZoom(RenderStyle::initialZoom());
4471         else if (primitiveValue->getIdent() == CSSValueReset) {
4472             m_style->setEffectiveZoom(RenderStyle::initialZoom());
4473             m_style->setZoom(RenderStyle::initialZoom());
4474         } else if (primitiveValue->getIdent() == CSSValueDocument) {
4475             float docZoom = m_checker.m_document->renderer()->style()->zoom();
4476             m_style->setEffectiveZoom(docZoom);
4477             m_style->setZoom(docZoom);
4478         } else if (type == CSSPrimitiveValue::CSS_PERCENTAGE) {
4479             if (primitiveValue->getFloatValue())
4480                 m_style->setZoom(primitiveValue->getFloatValue() / 100.0f);
4481         } else if (type == CSSPrimitiveValue::CSS_NUMBER) {
4482             if (primitiveValue->getFloatValue())
4483                 m_style->setZoom(primitiveValue->getFloatValue());
4484         }
4485         
4486         m_fontDirty = true;
4487         return;
4488     }
4489 // shorthand properties
4490     case CSSPropertyBackground:
4491         if (isInitial) {
4492             m_style->clearBackgroundLayers();
4493             m_style->setBackgroundColor(Color());
4494         }
4495         else if (isInherit) {
4496             m_style->inheritBackgroundLayers(*m_parentStyle->backgroundLayers());
4497             m_style->setBackgroundColor(m_parentStyle->backgroundColor());
4498         }
4499         return;
4500     case CSSPropertyWebkitMask:
4501         if (isInitial)
4502             m_style->clearMaskLayers();
4503         else if (isInherit)
4504             m_style->inheritMaskLayers(*m_parentStyle->maskLayers());
4505         return;
4506
4507     case CSSPropertyBorder:
4508     case CSSPropertyBorderStyle:
4509     case CSSPropertyBorderWidth:
4510     case CSSPropertyBorderColor:
4511         if (id == CSSPropertyBorder || id == CSSPropertyBorderColor)
4512         {
4513             if (isInherit) {
4514                 m_style->setBorderTopColor(m_parentStyle->borderTopColor().isValid() ? m_parentStyle->borderTopColor() : m_parentStyle->color());
4515                 m_style->setBorderBottomColor(m_parentStyle->borderBottomColor().isValid() ? m_parentStyle->borderBottomColor() : m_parentStyle->color());
4516                 m_style->setBorderLeftColor(m_parentStyle->borderLeftColor().isValid() ? m_parentStyle->borderLeftColor() : m_parentStyle->color());
4517                 m_style->setBorderRightColor(m_parentStyle->borderRightColor().isValid() ? m_parentStyle->borderRightColor(): m_parentStyle->color());
4518             }
4519             else if (isInitial) {
4520                 m_style->setBorderTopColor(Color()); // Reset to invalid color so currentColor is used instead.
4521                 m_style->setBorderBottomColor(Color());
4522                 m_style->setBorderLeftColor(Color());
4523                 m_style->setBorderRightColor(Color());
4524             }
4525         }
4526         if (id == CSSPropertyBorder || id == CSSPropertyBorderStyle)
4527         {
4528             if (isInherit) {
4529                 m_style->setBorderTopStyle(m_parentStyle->borderTopStyle());
4530                 m_style->setBorderBottomStyle(m_parentStyle->borderBottomStyle());
4531                 m_style->setBorderLeftStyle(m_parentStyle->borderLeftStyle());
4532                 m_style->setBorderRightStyle(m_parentStyle->borderRightStyle());
4533             }
4534             else if (isInitial) {
4535                 m_style->setBorderTopStyle(RenderStyle::initialBorderStyle());
4536                 m_style->setBorderBottomStyle(RenderStyle::initialBorderStyle());
4537                 m_style->setBorderLeftStyle(RenderStyle::initialBorderStyle());
4538                 m_style->setBorderRightStyle(RenderStyle::initialBorderStyle());
4539             }
4540         }
4541         if (id == CSSPropertyBorder || id == CSSPropertyBorderWidth)
4542         {
4543             if (isInherit) {
4544                 m_style->setBorderTopWidth(m_parentStyle->borderTopWidth());
4545                 m_style->setBorderBottomWidth(m_parentStyle->borderBottomWidth());
4546                 m_style->setBorderLeftWidth(m_parentStyle->borderLeftWidth());
4547                 m_style->setBorderRightWidth(m_parentStyle->borderRightWidth());
4548             }
4549             else if (isInitial) {
4550                 m_style->setBorderTopWidth(RenderStyle::initialBorderWidth());
4551                 m_style->setBorderBottomWidth(RenderStyle::initialBorderWidth());
4552                 m_style->setBorderLeftWidth(RenderStyle::initialBorderWidth());
4553                 m_style->setBorderRightWidth(RenderStyle::initialBorderWidth());
4554             }
4555         }
4556         return;
4557     case CSSPropertyBorderTop:
4558         if (isInherit) {
4559             m_style->setBorderTopColor(m_parentStyle->borderTopColor().isValid() ? m_parentStyle->borderTopColor() : m_parentStyle->color());
4560             m_style->setBorderTopStyle(m_parentStyle->borderTopStyle());
4561             m_style->setBorderTopWidth(m_parentStyle->borderTopWidth());
4562         }
4563         else if (isInitial)
4564             m_style->resetBorderTop();
4565         return;
4566     case CSSPropertyBorderRight:
4567         if (isInherit) {
4568             m_style->setBorderRightColor(m_parentStyle->borderRightColor().isValid() ? m_parentStyle->borderRightColor() : m_parentStyle->color());
4569             m_style->setBorderRightStyle(m_parentStyle->borderRightStyle());
4570             m_style->setBorderRightWidth(m_parentStyle->borderRightWidth());
4571         }
4572         else if (isInitial)
4573             m_style->resetBorderRight();
4574         return;
4575     case CSSPropertyBorderBottom:
4576         if (isInherit) {
4577             m_style->setBorderBottomColor(m_parentStyle->borderBottomColor().isValid() ? m_parentStyle->borderBottomColor() : m_parentStyle->color());
4578             m_style->setBorderBottomStyle(m_parentStyle->borderBottomStyle());
4579             m_style->setBorderBottomWidth(m_parentStyle->borderBottomWidth());
4580         }
4581         else if (isInitial)
4582             m_style->resetBorderBottom();
4583         return;
4584     case CSSPropertyBorderLeft:
4585         if (isInherit) {
4586             m_style->setBorderLeftColor(m_parentStyle->borderLeftColor().isValid() ? m_parentStyle->borderLeftColor() : m_parentStyle->color());
4587             m_style->setBorderLeftStyle(m_parentStyle->borderLeftStyle());
4588             m_style->setBorderLeftWidth(m_parentStyle->borderLeftWidth());
4589         }
4590         else if (isInitial)
4591             m_style->resetBorderLeft();
4592         return;
4593     case CSSPropertyMargin:
4594         if (isInherit) {
4595             m_style->setMarginTop(m_parentStyle->marginTop());
4596             m_style->setMarginBottom(m_parentStyle->marginBottom());
4597             m_style->setMarginLeft(m_parentStyle->marginLeft());
4598             m_style->setMarginRight(m_parentStyle->marginRight());
4599         }
4600         else if (isInitial)
4601             m_style->resetMargin();
4602         return;
4603     case CSSPropertyPadding:
4604         if (isInherit) {
4605             m_style->setPaddingTop(m_parentStyle->paddingTop());
4606             m_style->setPaddingBottom(m_parentStyle->paddingBottom());
4607             m_style->setPaddingLeft(m_parentStyle->paddingLeft());
4608             m_style->setPaddingRight(m_parentStyle->paddingRight());
4609         }
4610         else if (isInitial)
4611             m_style->resetPadding();
4612         return;
4613     case CSSPropertyFont:
4614         if (isInherit) {
4615             FontDescription fontDescription = m_parentStyle->fontDescription();
4616             m_style->setLineHeight(m_parentStyle->lineHeight());
4617             m_lineHeightValue = 0;
4618             if (m_style->setFontDescription(fontDescription))
4619                 m_fontDirty = true;
4620         } else if (isInitial) {
4621             Settings* settings = m_checker.m_document->settings();
4622             ASSERT(settings); // If we're doing style resolution, this document should always be in a frame and thus have settings
4623             if (!settings)
4624                 return;
4625             FontDescription fontDescription;
4626             fontDescription.setGenericFamily(FontDescription::StandardFamily);
4627             fontDescription.setRenderingMode(settings->fontRenderingMode());
4628             fontDescription.setUsePrinterFont(m_checker.m_document->printing());
4629             const AtomicString& standardFontFamily = m_checker.m_document->settings()->standardFontFamily();
4630             if (!standardFontFamily.isEmpty()) {
4631                 fontDescription.firstFamily().setFamily(standardFontFamily);
4632                 fontDescription.firstFamily().appendFamily(0);
4633             }
4634             fontDescription.setKeywordSize(CSSValueMedium - CSSValueXxSmall + 1);
4635             setFontSize(fontDescription, fontSizeForKeyword(m_checker.m_document, CSSValueMedium, false));
4636             m_style->setLineHeight(RenderStyle::initialLineHeight());
4637             m_lineHeightValue = 0;
4638             if (m_style->setFontDescription(fontDescription))
4639                 m_fontDirty = true;
4640         } else if (primitiveValue) {
4641             m_style->setLineHeight(RenderStyle::initialLineHeight());
4642             m_lineHeightValue = 0;
4643             
4644             FontDescription fontDescription;
4645             RenderTheme::defaultTheme()->systemFont(primitiveValue->getIdent(), fontDescription);
4646
4647             // Double-check and see if the theme did anything.  If not, don't bother updating the font.
4648             if (fontDescription.isAbsoluteSize()) {
4649                 // Make sure the rendering mode and printer font settings are updated.
4650                 Settings* settings = m_checker.m_document->settings();
4651                 ASSERT(settings); // If we're doing style resolution, this document should always be in a frame and thus have settings
4652                 if (!settings)
4653                     return;
4654                 fontDescription.setRenderingMode(settings->fontRenderingMode());
4655                 fontDescription.setUsePrinterFont(m_checker.m_document->printing());
4656            
4657                 // Handle the zoom factor.
4658                 fontDescription.setComputedSize(getComputedSizeFromSpecifiedSize(m_checker.m_document, m_style.get(), fontDescription.isAbsoluteSize(), fontDescription.specifiedSize(), useSVGZoomRules));
4659                 if (m_style->setFontDescription(fontDescription))
4660                     m_fontDirty = true;
4661             }
4662         } else if (value->isFontValue()) {
4663             FontValue *font = static_cast<FontValue*>(value);
4664             if (!font->style || !font->variant || !font->weight ||
4665                  !font->size || !font->lineHeight || !font->family)
4666                 return;
4667             applyProperty(CSSPropertyFontStyle, font->style.get());
4668             applyProperty(CSSPropertyFontVariant, font->variant.get());
4669             applyProperty(CSSPropertyFontWeight, font->weight.get());
4670             applyProperty(CSSPropertyFontSize, font->size.get());
4671
4672             m_lineHeightValue = font->lineHeight.get();
4673
4674             applyProperty(CSSPropertyFontFamily, font->family.get());
4675         }
4676         return;
4677         
4678     case CSSPropertyListStyle:
4679         if (isInherit) {
4680             m_style->setListStyleType(m_parentStyle->listStyleType());
4681             m_style->setListStyleImage(m_parentStyle->listStyleImage());
4682             m_style->setListStylePosition(m_parentStyle->listStylePosition());
4683         }
4684         else if (isInitial) {
4685             m_style->setListStyleType(RenderStyle::initialListStyleType());
4686             m_style->setListStyleImage(RenderStyle::initialListStyleImage());
4687             m_style->setListStylePosition(RenderStyle::initialListStylePosition());
4688         }
4689         return;
4690     case CSSPropertyOutline:
4691         if (isInherit) {
4692             m_style->setOutlineWidth(m_parentStyle->outlineWidth());
4693             m_style->setOutlineColor(m_parentStyle->outlineColor().isValid() ? m_parentStyle->outlineColor() : m_parentStyle->color());
4694             m_style->setOutlineStyle(m_parentStyle->outlineStyle());
4695         }
4696         else if (isInitial)
4697             m_style->resetOutline();
4698         return;
4699
4700     // CSS3 Properties
4701     case CSSPropertyWebkitAppearance: {
4702         HANDLE_INHERIT_AND_INITIAL(appearance, Appearance)
4703         if (!primitiveValue)
4704             return;
4705         m_style->setAppearance(*primitiveValue);
4706         return;
4707     }
4708
4709     case CSSPropertyWebkitBorderImage:
4710     case CSSPropertyWebkitMaskBoxImage: {
4711         if (isInherit) {
4712             HANDLE_INHERIT_COND(CSSPropertyWebkitBorderImage, borderImage, BorderImage)
4713             HANDLE_INHERIT_COND(CSSPropertyWebkitMaskBoxImage, maskBoxImage, MaskBoxImage)
4714             return;
4715         } else if (isInitial) {
4716             HANDLE_INITIAL_COND_WITH_VALUE(CSSPropertyWebkitBorderImage, BorderImage, NinePieceImage)
4717             HANDLE_INITIAL_COND_WITH_VALUE(CSSPropertyWebkitMaskBoxImage, MaskBoxImage, NinePieceImage)
4718             return;
4719         }
4720
4721         NinePieceImage image;
4722         mapNinePieceImage(property, value, image);
4723         
4724         if (id == CSSPropertyWebkitBorderImage)
4725             m_style->setBorderImage(image);
4726         else
4727             m_style->setMaskBoxImage(image);
4728         return;
4729     }
4730
4731     case CSSPropertyBorderRadius:
4732     case CSSPropertyWebkitBorderRadius:
4733         if (isInherit) {
4734             m_style->setBorderTopLeftRadius(m_parentStyle->borderTopLeftRadius());
4735             m_style->setBorderTopRightRadius(m_parentStyle->borderTopRightRadius());
4736             m_style->setBorderBottomLeftRadius(m_parentStyle->borderBottomLeftRadius());
4737             m_style->setBorderBottomRightRadius(m_parentStyle->borderBottomRightRadius());
4738             return;
4739         }
4740         if (isInitial) {
4741             m_style->resetBorderRadius();
4742             return;
4743         }
4744         // Fall through
4745     case CSSPropertyBorderTopLeftRadius:
4746     case CSSPropertyBorderTopRightRadius:
4747     case CSSPropertyBorderBottomLeftRadius:
4748     case CSSPropertyBorderBottomRightRadius: {
4749         if (isInherit) {
4750             HANDLE_INHERIT_COND(CSSPropertyBorderTopLeftRadius, borderTopLeftRadius, BorderTopLeftRadius)
4751             HANDLE_INHERIT_COND(CSSPropertyBorderTopRightRadius, borderTopRightRadius, BorderTopRightRadius)
4752             HANDLE_INHERIT_COND(CSSPropertyBorderBottomLeftRadius, borderBottomLeftRadius, BorderBottomLeftRadius)
4753             HANDLE_INHERIT_COND(CSSPropertyBorderBottomRightRadius, borderBottomRightRadius, BorderBottomRightRadius)
4754             return;
4755         }
4756         
4757         if (isInitial) {
4758             HANDLE_INITIAL_COND_WITH_VALUE(CSSPropertyBorderTopLeftRadius, BorderTopLeftRadius, BorderRadius)
4759             HANDLE_INITIAL_COND_WITH_VALUE(CSSPropertyBorderTopRightRadius, BorderTopRightRadius, BorderRadius)
4760             HANDLE_INITIAL_COND_WITH_VALUE(CSSPropertyBorderBottomLeftRadius, BorderBottomLeftRadius, BorderRadius)
4761             HANDLE_INITIAL_COND_WITH_VALUE(CSSPropertyBorderBottomRightRadius, BorderBottomRightRadius, BorderRadius)
4762             return;
4763         }
4764
4765         if (!primitiveValue)
4766             return;
4767
4768         Pair* pair = primitiveValue->getPairValue();
4769         if (!pair)
4770             return;
4771
4772         Length radiusWidth;
4773         Length radiusHeight;
4774         if (pair->first()->primitiveType() == CSSPrimitiveValue::CSS_PERCENTAGE)
4775             radiusWidth = Length(pair->first()->getDoubleValue(), Percent);
4776         else
4777             radiusWidth = Length(max(intMinForLength, min(intMaxForLength, pair->first()->computeLengthInt(style(), m_rootElementStyle, zoomFactor))), Fixed);
4778         if (pair->second()->primitiveType() == CSSPrimitiveValue::CSS_PERCENTAGE)
4779             radiusHeight = Length(pair->second()->getDoubleValue(), Percent);
4780         else
4781             radiusHeight = Length(max(intMinForLength, min(intMaxForLength, pair->second()->computeLengthInt(style(), m_rootElementStyle, zoomFactor))), Fixed);
4782         int width = radiusWidth.rawValue();
4783         int height = radiusHeight.rawValue();
4784         if (width < 0 || height < 0)
4785             return;
4786         if (width == 0)
4787             radiusHeight = radiusWidth; // Null out the other value.
4788         else if (height == 0)
4789             radiusWidth = radiusHeight; // Null out the other value.
4790
4791         LengthSize size(radiusWidth, radiusHeight);
4792         switch (id) {
4793             case CSSPropertyBorderTopLeftRadius:
4794                 m_style->setBorderTopLeftRadius(size);
4795                 break;
4796             case CSSPropertyBorderTopRightRadius:
4797                 m_style->setBorderTopRightRadius(size);
4798                 break;
4799             case CSSPropertyBorderBottomLeftRadius:
4800                 m_style->setBorderBottomLeftRadius(size);
4801                 break;
4802             case CSSPropertyBorderBottomRightRadius:
4803                 m_style->setBorderBottomRightRadius(size);
4804                 break;
4805             default:
4806                 m_style->setBorderRadius(size);
4807                 break;
4808         }
4809         return;
4810     }
4811
4812     case CSSPropertyOutlineOffset:
4813         HANDLE_INHERIT_AND_INITIAL(outlineOffset, OutlineOffset)
4814         m_style->setOutlineOffset(primitiveValue->computeLengthInt(style(), m_rootElementStyle, zoomFactor));
4815         return;
4816     case CSSPropertyTextRendering: {
4817         FontDescription fontDescription = m_style->fontDescription();
4818         if (isInherit) 
4819             fontDescription.setTextRenderingMode(m_parentStyle->fontDescription().textRenderingMode());
4820         else if (isInitial)
4821             fontDescription.setTextRenderingMode(AutoTextRendering);
4822         else {
4823             if (!primitiveValue)
4824                 return;
4825             fontDescription.setTextRenderingMode(*primitiveValue);
4826         }
4827         if (m_style->setFontDescription(fontDescription))
4828             m_fontDirty = true;
4829         return;
4830     }
4831     case CSSPropertyTextShadow:
4832     case CSSPropertyWebkitBoxShadow: {
4833         if (isInherit) {
4834             if (id == CSSPropertyTextShadow)
4835                 return m_style->setTextShadow(m_parentStyle->textShadow() ? new ShadowData(*m_parentStyle->textShadow()) : 0);
4836             return m_style->setBoxShadow(m_parentStyle->boxShadow() ? new ShadowData(*m_parentStyle->boxShadow()) : 0);
4837         }
4838         if (isInitial || primitiveValue) // initial | none
4839             return id == CSSPropertyTextShadow ? m_style->setTextShadow(0) : m_style->setBoxShadow(0);
4840
4841         if (!value->isValueList())
4842             return;
4843
4844         CSSValueList *list = static_cast<CSSValueList*>(value);
4845         int len = list->length();
4846         for (int i = 0; i < len; i++) {
4847             ShadowValue* item = static_cast<ShadowValue*>(list->itemWithoutBoundsCheck(i));
4848             int x = item->x->computeLengthInt(style(), m_rootElementStyle, zoomFactor);
4849             int y = item->y->computeLengthInt(style(), m_rootElementStyle, zoomFactor);
4850             int blur = item->blur ? item->blur->computeLengthInt(style(), m_rootElementStyle, zoomFactor) : 0;
4851             int spread = item->spread ? item->spread->computeLengthInt(style(), m_rootElementStyle, zoomFactor) : 0;
4852             ShadowStyle shadowStyle = item->style && item->style->getIdent() == CSSValueInset ? Inset : Normal;
4853             Color color;
4854             if (item->color)
4855                 color = getColorFromPrimitiveValue(item->color.get());
4856             ShadowData* shadowData = new ShadowData(x, y, blur, spread, shadowStyle, color.isValid() ? color : Color::transparent);
4857             if (id == CSSPropertyTextShadow)
4858                 m_style->setTextShadow(shadowData, i != 0);
4859             else
4860                 m_style->setBoxShadow(shadowData, i != 0);
4861         }
4862         return;
4863     }
4864     case CSSPropertyWebkitBoxReflect: {
4865         HANDLE_INHERIT_AND_INITIAL(boxReflect, BoxReflect)
4866         if (primitiveValue) {
4867             m_style->setBoxReflect(RenderStyle::initialBoxReflect());
4868             return;
4869         }
4870         CSSReflectValue* reflectValue = static_cast<CSSReflectValue*>(value);
4871         RefPtr<StyleReflection> reflection = StyleReflection::create();
4872         reflection->setDirection(reflectValue->direction());
4873         if (reflectValue->offset()) {
4874             int type = reflectValue->offset()->primitiveType();
4875             if (type == CSSPrimitiveValue::CSS_PERCENTAGE)
4876                 reflection->setOffset(Length(reflectValue->offset()->getDoubleValue(), Percent));
4877             else
4878                 reflection->setOffset(Length(reflectValue->offset()->computeLengthIntForLength(style(), m_rootElementStyle, zoomFactor), Fixed));
4879         }
4880         NinePieceImage mask;
4881         mapNinePieceImage(property, reflectValue->mask(), mask);
4882         reflection->setMask(mask);
4883         
4884         m_style->setBoxReflect(reflection.release());
4885         return;
4886     }
4887     case CSSPropertyOpacity:
4888         HANDLE_INHERIT_AND_INITIAL(opacity, Opacity)
4889         if (!primitiveValue || primitiveValue->primitiveType() != CSSPrimitiveValue::CSS_NUMBER)
4890             return; // Error case.
4891         // Clamp opacity to the range 0-1
4892         m_style->setOpacity(min(1.0f, max(0.0f, primitiveValue->getFloatValue())));
4893         return;
4894     case CSSPropertyWebkitBoxAlign:
4895     {
4896         HANDLE_INHERIT_AND_INITIAL(boxAlign, BoxAlign)
4897         if (!primitiveValue)
4898             return;
4899         EBoxAlignment boxAlignment = *primitiveValue;
4900         if (boxAlignment != BJUSTIFY)
4901             m_style->setBoxAlign(boxAlignment);
4902         return;
4903     }
4904     case CSSPropertySrc: // Only used in @font-face rules.
4905         return;
4906     case CSSPropertyUnicodeRange: // Only used in @font-face rules.
4907         return;
4908     case CSSPropertyWebkitBackfaceVisibility:
4909         HANDLE_INHERIT_AND_INITIAL(backfaceVisibility, BackfaceVisibility)
4910         if (primitiveValue)
4911             m_style->setBackfaceVisibility((primitiveValue->getIdent() == CSSValueVisible) ? BackfaceVisibilityVisible : BackfaceVisibilityHidden);
4912         return;
4913     case CSSPropertyWebkitBoxDirection:
4914         HANDLE_INHERIT_AND_INITIAL_AND_PRIMITIVE(boxDirection, BoxDirection)
4915         return;
4916     case CSSPropertyWebkitBoxLines:
4917         HANDLE_INHERIT_AND_INITIAL_AND_PRIMITIVE(boxLines, BoxLines)
4918         return;
4919     case CSSPropertyWebkitBoxOrient:
4920         HANDLE_INHERIT_AND_INITIAL_AND_PRIMITIVE(boxOrient, BoxOrient)
4921         return;
4922     case CSSPropertyWebkitBoxPack:
4923     {
4924         HANDLE_INHERIT_AND_INITIAL(boxPack, BoxPack)
4925         if (!primitiveValue)
4926             return;
4927         EBoxAlignment boxPack = *primitiveValue;
4928         if (boxPack != BSTRETCH && boxPack != BBASELINE)
4929             m_style->setBoxPack(boxPack);
4930         return;
4931     }
4932     case CSSPropertyWebkitBoxFlex:
4933         HANDLE_INHERIT_AND_INITIAL(boxFlex, BoxFlex)
4934         if (!primitiveValue || primitiveValue->primitiveType() != CSSPrimitiveValue::CSS_NUMBER)
4935             return; // Error case.
4936         m_style->setBoxFlex(primitiveValue->getFloatValue());
4937         return;
4938     case CSSPropertyWebkitBoxFlexGroup:
4939         HANDLE_INHERIT_AND_INITIAL(boxFlexGroup, BoxFlexGroup)
4940         if (!primitiveValue || primitiveValue->primitiveType() != CSSPrimitiveValue::CSS_NUMBER)
4941             return; // Error case.
4942         m_style->setBoxFlexGroup((unsigned int)(primitiveValue->getDoubleValue()));
4943         return;
4944     case CSSPropertyWebkitBoxOrdinalGroup:
4945         HANDLE_INHERIT_AND_INITIAL(boxOrdinalGroup, BoxOrdinalGroup)
4946         if (!primitiveValue || primitiveValue->primitiveType() != CSSPrimitiveValue::CSS_NUMBER)
4947             return; // Error case.
4948         m_style->setBoxOrdinalGroup((unsigned int)(primitiveValue->getDoubleValue()));
4949         return;
4950     case CSSPropertyWebkitBoxSizing:
4951         HANDLE_INHERIT_AND_INITIAL(boxSizing, BoxSizing)
4952         if (!primitiveValue)
4953             return;
4954         if (primitiveValue->getIdent() == CSSValueContentBox)
4955             m_style->setBoxSizing(CONTENT_BOX);
4956         else
4957             m_style->setBoxSizing(BORDER_BOX);
4958         return;
4959     case CSSPropertyWebkitColumnCount: {
4960         if (isInherit) {
4961             if (m_parentStyle->hasAutoColumnCount())
4962                 m_style->setHasAutoColumnCount();
4963             else
4964                 m_style->setColumnCount(m_parentStyle->columnCount());
4965             return;
4966         } else if (isInitial || primitiveValue->getIdent() == CSSValueAuto) {
4967             m_style->setHasAutoColumnCount();
4968             return;
4969         }
4970         m_style->setColumnCount(static_cast<unsigned short>(primitiveValue->getDoubleValue()));
4971         return;
4972     }
4973     case CSSPropertyWebkitColumnGap: {
4974         if (isInherit) {
4975             if (m_parentStyle->hasNormalColumnGap())
4976                 m_style->setHasNormalColumnGap();
4977             else
4978                 m_style->setColumnGap(m_parentStyle->columnGap());
4979             return;
4980         } else if (isInitial || primitiveValue->getIdent() == CSSValueNormal) {
4981             m_style->setHasNormalColumnGap();
4982             return;
4983         }
4984         m_style->setColumnGap(primitiveValue->computeLengthFloat(style(), m_rootElementStyle, zoomFactor));
4985         return;
4986     }
4987     case CSSPropertyWebkitColumnSpan: {
4988         HANDLE_INHERIT_AND_INITIAL(columnSpan, ColumnSpan)
4989         m_style->setColumnSpan(primitiveValue->getIdent() == CSSValueAll);
4990         return;
4991     }
4992     case CSSPropertyWebkitColumnWidth: {
4993         if (isInherit) {
4994             if (m_parentStyle->hasAutoColumnWidth())
4995                 m_style->setHasAutoColumnWidth();
4996             else
4997                 m_style->setColumnWidth(m_parentStyle->columnWidth());
4998             return;
4999         } else if (isInitial || primitiveValue->getIdent() == CSSValueAuto) {
5000             m_style->setHasAutoColumnWidth();
5001             return;
5002         }
5003         m_style->setColumnWidth(primitiveValue->computeLengthFloat(style(), m_rootElementStyle, zoomFactor));
5004         return;
5005     }
5006     case CSSPropertyWebkitColumnRuleStyle:
5007         HANDLE_INHERIT_AND_INITIAL_AND_PRIMITIVE_WITH_VALUE(columnRuleStyle, ColumnRuleStyle, BorderStyle)
5008         return;
5009     case CSSPropertyWebkitColumnBreakBefore:
5010         HANDLE_INHERIT_AND_INITIAL_AND_PRIMITIVE_WITH_VALUE(columnBreakBefore, ColumnBreakBefore, PageBreak)
5011         return;
5012     case CSSPropertyWebkitColumnBreakAfter:
5013         HANDLE_INHERIT_AND_INITIAL_AND_PRIMITIVE_WITH_VALUE(columnBreakAfter, ColumnBreakAfter, PageBreak)
5014         return;
5015     case CSSPropertyWebkitColumnBreakInside: {
5016         HANDLE_INHERIT_AND_INITIAL_WITH_VALUE(columnBreakInside, ColumnBreakInside, PageBreak)
5017         EPageBreak pb = *primitiveValue;
5018         if (pb != PBALWAYS)
5019             m_style->setColumnBreakInside(pb);
5020         return;
5021     }
5022      case CSSPropertyWebkitColumnRule:
5023         if (isInherit) {
5024             m_style->setColumnRuleColor(m_parentStyle->columnRuleColor().isValid() ? m_parentStyle->columnRuleColor() : m_parentStyle->color());
5025             m_style->setColumnRuleStyle(m_parentStyle->columnRuleStyle());
5026             m_style->setColumnRuleWidth(m_parentStyle->columnRuleWidth());
5027         }
5028         else if (isInitial)
5029             m_style->resetColumnRule();
5030         return;
5031     case CSSPropertyWebkitColumns:
5032         if (isInherit) {
5033             if (m_parentStyle->hasAutoColumnWidth())
5034                 m_style->setHasAutoColumnWidth();
5035             else
5036                 m_style->setColumnWidth(m_parentStyle->columnWidth());
5037             m_style->setColumnCount(m_parentStyle->columnCount());
5038         } else if (isInitial) {
5039             m_style->setHasAutoColumnWidth();
5040             m_style->setColumnCount(RenderStyle::initialColumnCount());
5041         }
5042         return;
5043     case CSSPropertyWebkitMarquee:
5044         if (valueType != CSSValue::CSS_INHERIT || !m_parentNode) return;
5045         m_style->setMarqueeDirection(m_parentStyle->marqueeDirection());
5046         m_style->setMarqueeIncrement(m_parentStyle->marqueeIncrement());
5047         m_style->setMarqueeSpeed(m_parentStyle->marqueeSpeed());
5048         m_style->setMarqueeLoopCount(m_parentStyle->marqueeLoopCount());
5049         m_style->setMarqueeBehavior(m_parentStyle->marqueeBehavior());
5050         return;
5051 #if ENABLE(WCSS)
5052     case CSSPropertyWapMarqueeLoop:
5053 #endif
5054     case CSSPropertyWebkitMarqueeRepetition: {
5055         HANDLE_INHERIT_AND_INITIAL(marqueeLoopCount, MarqueeLoopCount)
5056         if (!primitiveValue)
5057             return;
5058         if (primitiveValue->getIdent() == CSSValueInfinite)
5059             m_style->setMarqueeLoopCount(-1); // -1 means repeat forever.
5060         else if (primitiveValue->primitiveType() == CSSPrimitiveValue::CSS_NUMBER)
5061             m_style->setMarqueeLoopCount(primitiveValue->getIntValue());
5062         return;
5063     }
5064 #if ENABLE(WCSS)
5065     case CSSPropertyWapMarqueeSpeed:
5066 #endif
5067     case CSSPropertyWebkitMarqueeSpeed: {
5068         HANDLE_INHERIT_AND_INITIAL(marqueeSpeed, MarqueeSpeed)      
5069         if (!primitiveValue)
5070             return;
5071         if (primitiveValue->getIdent()) {
5072             switch (primitiveValue->getIdent()) {
5073                 case CSSValueSlow:
5074                     m_style->setMarqueeSpeed(500); // 500 msec.
5075                     break;
5076                 case CSSValueNormal:
5077                     m_style->setMarqueeSpeed(85); // 85msec. The WinIE default.
5078                     break;
5079                 case CSSValueFast:
5080                     m_style->setMarqueeSpeed(10); // 10msec. Super fast.
5081                     break;
5082             }
5083         }
5084         else if (primitiveValue->primitiveType() == CSSPrimitiveValue::CSS_S)
5085             m_style->setMarqueeSpeed(1000 * primitiveValue->getIntValue());
5086         else if (primitiveValue->primitiveType() == CSSPrimitiveValue::CSS_MS)
5087             m_style->setMarqueeSpeed(primitiveValue->getIntValue());
5088         else if (primitiveValue->primitiveType() == CSSPrimitiveValue::CSS_NUMBER) // For scrollamount support.
5089             m_style->setMarqueeSpeed(primitiveValue->getIntValue());
5090         return;
5091     }
5092     case CSSPropertyWebkitMarqueeIncrement: {
5093         HANDLE_INHERIT_AND_INITIAL(marqueeIncrement, MarqueeIncrement)
5094         if (!primitiveValue)
5095             return;
5096         if (primitiveValue->getIdent()) {
5097             switch (primitiveValue->getIdent()) {
5098                 case CSSValueSmall:
5099                     m_style->setMarqueeIncrement(Length(1, Fixed)); // 1px.
5100                     break;
5101                 case CSSValueNormal:
5102                     m_style->setMarqueeIncrement(Length(6, Fixed)); // 6px. The WinIE default.
5103                     break;
5104                 case CSSValueLarge:
5105                     m_style->setMarqueeIncrement(Length(36, Fixed)); // 36px.
5106                     break;
5107             }
5108         }
5109         else {
5110             bool ok = true;
5111             Length l = convertToLength(primitiveValue, style(), m_rootElementStyle, 1, &ok);
5112             if (ok)
5113                 m_style->setMarqueeIncrement(l);
5114         }
5115         return;
5116     }
5117 #if ENABLE(WCSS)
5118     case CSSPropertyWapMarqueeStyle:
5119 #endif
5120     case CSSPropertyWebkitMarqueeStyle:
5121         HANDLE_INHERIT_AND_INITIAL_AND_PRIMITIVE(marqueeBehavior, MarqueeBehavior)      
5122         return;
5123 #if ENABLE(WCSS)
5124     case CSSPropertyWapMarqueeDir:
5125         HANDLE_INHERIT_AND_INITIAL(marqueeDirection, MarqueeDirection)
5126         if (primitiveValue && primitiveValue->getIdent()) {
5127             switch (primitiveValue->getIdent()) {
5128             case CSSValueLtr:
5129                 m_style->setMarqueeDirection(MRIGHT);
5130                 break;
5131             case CSSValueRtl:
5132                 m_style->setMarqueeDirection(MLEFT);
5133                 break;
5134             default:
5135                 m_style->setMarqueeDirection(*primitiveValue);
5136                 break;
5137             }
5138         }
5139         return;
5140 #endif
5141     case CSSPropertyWebkitMarqueeDirection:
5142         HANDLE_INHERIT_AND_INITIAL_AND_PRIMITIVE(marqueeDirection, MarqueeDirection)
5143         return;
5144     case CSSPropertyWebkitUserDrag:
5145         HANDLE_INHERIT_AND_INITIAL_AND_PRIMITIVE(userDrag, UserDrag)      
5146         return;
5147     case CSSPropertyWebkitUserModify:
5148         HANDLE_INHERIT_AND_INITIAL_AND_PRIMITIVE(userModify, UserModify)      
5149         return;
5150     case CSSPropertyWebkitUserSelect:
5151         HANDLE_INHERIT_AND_INITIAL_AND_PRIMITIVE(userSelect, UserSelect)      
5152         return;
5153
5154     case CSSPropertyTextOverflow: {
5155         // This property is supported by WinIE, and so we leave off the "-webkit-" in order to
5156         // work with WinIE-specific pages that use the property.
5157         HANDLE_INHERIT_AND_INITIAL(textOverflow, TextOverflow)
5158         if (!primitiveValue || !primitiveValue->getIdent())
5159             return;
5160         m_style->setTextOverflow(primitiveValue->getIdent() == CSSValueEllipsis);
5161         return;
5162     }
5163     case CSSPropertyWebkitMarginCollapse: {
5164         if (isInherit) {
5165             m_style->setMarginBeforeCollapse(m_parentStyle->marginBeforeCollapse());
5166             m_style->setMarginAfterCollapse(m_parentStyle->marginAfterCollapse());
5167         }
5168         else if (isInitial) {
5169             m_style->setMarginBeforeCollapse(MCOLLAPSE);
5170             m_style->setMarginAfterCollapse(MCOLLAPSE);
5171         }
5172         return;
5173     }
5174
5175     case CSSPropertyWebkitMarginBeforeCollapse:
5176     case CSSPropertyWebkitMarginTopCollapse:
5177         HANDLE_INHERIT_AND_INITIAL_AND_PRIMITIVE(marginBeforeCollapse, MarginBeforeCollapse)
5178         return;
5179     case CSSPropertyWebkitMarginAfterCollapse:
5180     case CSSPropertyWebkitMarginBottomCollapse:
5181         HANDLE_INHERIT_AND_INITIAL_AND_PRIMITIVE(marginAfterCollapse, MarginAfterCollapse)
5182         return;
5183     case CSSPropertyWebkitLineClamp: {
5184         HANDLE_INHERIT_AND_INITIAL(lineClamp, LineClamp)
5185         if (!primitiveValue)
5186             return;
5187         int type = primitiveValue->primitiveType();
5188         if (type == CSSPrimitiveValue::CSS_NUMBER)
5189             m_style->setLineClamp(LineClampValue(primitiveValue->getIntValue(CSSPrimitiveValue::CSS_NUMBER), LineClampLineCount));
5190         else if (type == CSSPrimitiveValue::CSS_PERCENTAGE)
5191             m_style->setLineClamp(LineClampValue(primitiveValue->getIntValue(CSSPrimitiveValue::CSS_PERCENTAGE), LineClampPercentage));
5192         return;
5193     }
5194     case CSSPropertyWebkitHighlight: {
5195         HANDLE_INHERIT_AND_INITIAL(highlight, Highlight);
5196         if (primitiveValue->getIdent() == CSSValueNone)
5197             m_style->setHighlight(nullAtom);
5198         else
5199             m_style->setHighlight(primitiveValue->getStringValue());
5200         return;
5201     }
5202     case CSSPropertyWebkitHyphens: {
5203         HANDLE_INHERIT_AND_INITIAL(hyphens, Hyphens);
5204         m_style->setHyphens(*primitiveValue);
5205         return;
5206     }
5207     case CSSPropertyWebkitHyphenateCharacter: {
5208         HANDLE_INHERIT_AND_INITIAL(hyphenationString, HyphenationString);
5209         if (primitiveValue->getIdent() == CSSValueAuto)
5210             m_style->setHyphenationString(nullAtom);
5211         else
5212             m_style->setHyphenationString(primitiveValue->getStringValue());
5213         return;
5214     }
5215     case CSSPropertyWebkitHyphenateLocale: {
5216         HANDLE_INHERIT_AND_INITIAL(hyphenationLocale, HyphenationLocale);
5217         if (primitiveValue->getIdent() == CSSValueAuto)
5218             m_style->setHyphenationLocale(nullAtom);
5219         else
5220             m_style->setHyphenationLocale(primitiveValue->getStringValue());
5221         return;
5222     }
5223     case CSSPropertyWebkitBorderFit: {
5224         HANDLE_INHERIT_AND_INITIAL(borderFit, BorderFit);
5225         if (primitiveValue->getIdent() == CSSValueBorder)
5226             m_style->setBorderFit(BorderFitBorder);
5227         else
5228             m_style->setBorderFit(BorderFitLines);
5229         return;
5230     }
5231     case CSSPropertyWebkitTextSizeAdjust: {
5232         HANDLE_INHERIT_AND_INITIAL(textSizeAdjust, TextSizeAdjust)
5233         if (!primitiveValue || !primitiveValue->getIdent()) return;
5234         m_style->setTextSizeAdjust(primitiveValue->getIdent() == CSSValueAuto);
5235         m_fontDirty = true;
5236         return;
5237     }
5238     case CSSPropertyWebkitTextSecurity:
5239         HANDLE_INHERIT_AND_INITIAL_AND_PRIMITIVE(textSecurity, TextSecurity)
5240         return;
5241
5242 #if ENABLE(DASHBOARD_SUPPORT)
5243     case CSSPropertyWebkitDashboardRegion: {
5244         HANDLE_INHERIT_AND_INITIAL(dashboardRegions, DashboardRegions)
5245         if (!primitiveValue)
5246             return;
5247
5248         if (primitiveValue->getIdent() == CSSValueNone) {
5249             m_style->setDashboardRegions(RenderStyle::noneDashboardRegions());
5250             return;
5251         }
5252
5253         DashboardRegion *region = primitiveValue->getDashboardRegionValue();
5254         if (!region)
5255             return;
5256             
5257         DashboardRegion *first = region;
5258         while (region) {
5259             Length top = convertToLength(region->top(), style(), m_rootElementStyle);
5260             Length right = convertToLength(region->right(), style(), m_rootElementStyle);
5261             Length bottom = convertToLength(region->bottom(), style(), m_rootElementStyle);
5262             Length left = convertToLength(region->left(), style(), m_rootElementStyle);
5263             if (region->m_isCircle)
5264                 m_style->setDashboardRegion(StyleDashboardRegion::Circle, region->m_label, top, right, bottom, left, region == first ? false : true);
5265             else if (region->m_isRectangle)
5266                 m_style->setDashboardRegion(StyleDashboardRegion::Rectangle, region->m_label, top, right, bottom, left, region == first ? false : true);
5267             region = region->m_next.get();
5268         }
5269         
5270         m_element->document()->setHasDashboardRegions(true);
5271         
5272         return;
5273     }
5274 #endif        
5275     case CSSPropertyWebkitRtlOrdering:
5276         HANDLE_INHERIT_AND_INITIAL(visuallyOrdered, VisuallyOrdered)
5277         if (!primitiveValue || !primitiveValue->getIdent())
5278             return;
5279         m_style->setVisuallyOrdered(primitiveValue->getIdent() == CSSValueVisual);
5280         return;
5281     case CSSPropertyWebkitTextStrokeWidth: {
5282         HANDLE_INHERIT_AND_INITIAL(textStrokeWidth, TextStrokeWidth)
5283         float width = 0;
5284         switch (primitiveValue->getIdent()) {
5285             case CSSValueThin:
5286             case CSSValueMedium:
5287             case CSSValueThick: {
5288                 double result = 1.0 / 48;
5289                 if (primitiveValue->getIdent() == CSSValueMedium)
5290                     result *= 3;
5291                 else if (primitiveValue->getIdent() == CSSValueThick)
5292                     result *= 5;
5293                 width = CSSPrimitiveValue::create(result, CSSPrimitiveValue::CSS_EMS)->computeLengthFloat(style(), m_rootElementStyle, zoomFactor);
5294                 break;
5295             }
5296             default:
5297                 width = primitiveValue->computeLengthFloat(style(), m_rootElementStyle, zoomFactor);
5298                 break;
5299         }
5300         m_style->setTextStrokeWidth(width);
5301         return;
5302     }
5303     case CSSPropertyWebkitTransform: {
5304         HANDLE_INHERIT_AND_INITIAL(transform, Transform);
5305         TransformOperations operations;
5306         createTransformOperations(value, style(), m_rootElementStyle, operations);
5307         m_style->setTransform(operations);
5308         return;
5309     }
5310     case CSSPropertyWebkitTransformOrigin:
5311         HANDLE_INHERIT_AND_INITIAL(transformOriginX, TransformOriginX)
5312         HANDLE_INHERIT_AND_INITIAL(transformOriginY, TransformOriginY)
5313         HANDLE_INHERIT_AND_INITIAL(transformOriginZ, TransformOriginZ)
5314         return;
5315     case CSSPropertyWebkitTransformOriginX: {
5316         HANDLE_INHERIT_AND_INITIAL(transformOriginX, TransformOriginX)
5317         CSSPrimitiveValue* primitiveValue = static_cast<CSSPrimitiveValue*>(value);
5318         Length l;
5319         int type = primitiveValue->primitiveType();
5320         if (CSSPrimitiveValue::isUnitTypeLength(type))
5321             l = Length(primitiveValue->computeLengthIntForLength(style(), m_rootElementStyle, zoomFactor), Fixed);
5322         else if (type == CSSPrimitiveValue::CSS_PERCENTAGE)
5323             l = Length(primitiveValue->getDoubleValue(), Percent);
5324         else
5325             return;
5326         m_style->setTransformOriginX(l);
5327         break;
5328     }
5329     case CSSPropertyWebkitTransformOriginY: {
5330         HANDLE_INHERIT_AND_INITIAL(transformOriginY, TransformOriginY)
5331         CSSPrimitiveValue* primitiveValue = static_cast<CSSPrimitiveValue*>(value);
5332         Length l;
5333         int type = primitiveValue->primitiveType();
5334         if (CSSPrimitiveValue::isUnitTypeLength(type))
5335             l = Length(primitiveValue->computeLengthIntForLength(style(), m_rootElementStyle, zoomFactor), Fixed);
5336         else if (type == CSSPrimitiveValue::CSS_PERCENTAGE)
5337             l = Length(primitiveValue->getDoubleValue(), Percent);
5338         else
5339             return;
5340         m_style->setTransformOriginY(l);
5341         break;
5342     }
5343     case CSSPropertyWebkitTransformOriginZ: {
5344         HANDLE_INHERIT_AND_INITIAL(transformOriginZ, TransformOriginZ)
5345         CSSPrimitiveValue* primitiveValue = static_cast<CSSPrimitiveValue*>(value);
5346         float f;
5347         int type = primitiveValue->primitiveType();
5348         if (CSSPrimitiveValue::isUnitTypeLength(type))
5349             f = static_cast<float>(primitiveValue->computeLengthIntForLength(style(), m_rootElementStyle));
5350         else
5351             return;
5352         m_style->setTransformOriginZ(f);
5353         break;
5354     }
5355     case CSSPropertyWebkitTransformStyle:
5356         HANDLE_INHERIT_AND_INITIAL(transformStyle3D, TransformStyle3D)
5357         if (primitiveValue)
5358             m_style->setTransformStyle3D((primitiveValue->getIdent() == CSSValuePreserve3d) ? TransformStyle3DPreserve3D : TransformStyle3DFlat);
5359         return;
5360     case CSSPropertyWebkitPerspective: {
5361         HANDLE_INHERIT_AND_INITIAL(perspective, Perspective)
5362         if (primitiveValue && primitiveValue->getIdent() == CSSValueNone) {
5363             m_style->setPerspective(0);
5364             return;
5365         }
5366         
5367         float perspectiveValue;
5368         int type = primitiveValue->primitiveType();
5369         if (CSSPrimitiveValue::isUnitTypeLength(type))
5370             perspectiveValue = static_cast<float>(primitiveValue->computeLengthIntForLength(style(), m_rootElementStyle, zoomFactor));
5371         else if (type == CSSPrimitiveValue::CSS_NUMBER) {
5372             // For backward compatibility, treat valueless numbers as px.
5373             perspectiveValue = CSSPrimitiveValue::create(primitiveValue->getDoubleValue(), CSSPrimitiveValue::CSS_PX)->computeLengthFloat(style(), m_rootElementStyle, zoomFactor);
5374         } else
5375             return;
5376
5377         if (perspectiveValue >= 0.0f)
5378             m_style->setPerspective(perspectiveValue);
5379         return;
5380     }
5381     case CSSPropertyWebkitPerspectiveOrigin:
5382         HANDLE_INHERIT_AND_INITIAL(perspectiveOriginX, PerspectiveOriginX)
5383         HANDLE_INHERIT_AND_INITIAL(perspectiveOriginY, PerspectiveOriginY)
5384         return;
5385     case CSSPropertyWebkitPerspectiveOriginX: {
5386         HANDLE_INHERIT_AND_INITIAL(perspectiveOriginX, PerspectiveOriginX)
5387         CSSPrimitiveValue* primitiveValue = static_cast<CSSPrimitiveValue*>(value);
5388         Length l;
5389         int type = primitiveValue->primitiveType();
5390         if (CSSPrimitiveValue::isUnitTypeLength(type))
5391             l = Length(primitiveValue->computeLengthIntForLength(style(), m_rootElementStyle, zoomFactor), Fixed);
5392         else if (type == CSSPrimitiveValue::CSS_PERCENTAGE)
5393             l = Length(primitiveValue->getDoubleValue(), Percent);
5394         else
5395             return;
5396         m_style->setPerspectiveOriginX(l);
5397         return;
5398     }
5399     case CSSPropertyWebkitPerspectiveOriginY: {
5400         HANDLE_INHERIT_AND_INITIAL(perspectiveOriginY, PerspectiveOriginY)
5401         CSSPrimitiveValue* primitiveValue = static_cast<CSSPrimitiveValue*>(value);
5402         Length l;
5403         int type = primitiveValue->primitiveType();
5404         if (CSSPrimitiveValue::isUnitTypeLength(type))
5405             l = Length(primitiveValue->computeLengthIntForLength(style(), m_rootElementStyle, zoomFactor), Fixed);
5406         else if (type == CSSPrimitiveValue::CSS_PERCENTAGE)
5407             l = Length(primitiveValue->getDoubleValue(), Percent);
5408         else
5409             return;
5410         m_style->setPerspectiveOriginY(l);
5411         return;
5412     }
5413     case CSSPropertyWebkitAnimation:
5414         if (isInitial)
5415             m_style->clearAnimations();
5416         else if (isInherit)
5417             m_style->inheritAnimations(m_parentStyle->animations());
5418         return;
5419     case CSSPropertyWebkitAnimationDelay:
5420         HANDLE_ANIMATION_VALUE(delay, Delay, value)
5421         return;
5422     case CSSPropertyWebkitAnimationDirection:
5423         HANDLE_ANIMATION_VALUE(direction, Direction, value)
5424         return;
5425     case CSSPropertyWebkitAnimationDuration:
5426         HANDLE_ANIMATION_VALUE(duration, Duration, value)
5427         return;
5428     case CSSPropertyWebkitAnimationFillMode:
5429         HANDLE_ANIMATION_VALUE(fillMode, FillMode, value)
5430         return;
5431     case CSSPropertyWebkitAnimationIterationCount:
5432         HANDLE_ANIMATION_VALUE(iterationCount, IterationCount, value)
5433         return;
5434     case CSSPropertyWebkitAnimationName:
5435         HANDLE_ANIMATION_VALUE(name, Name, value)
5436         return;
5437     case CSSPropertyWebkitAnimationPlayState:
5438         HANDLE_ANIMATION_VALUE(playState, PlayState, value)
5439         return;
5440     case CSSPropertyWebkitAnimationTimingFunction:
5441         HANDLE_ANIMATION_VALUE(timingFunction, TimingFunction, value)
5442         return;
5443     case CSSPropertyWebkitTransition:
5444         if (isInitial)
5445             m_style->clearTransitions();
5446         else if (isInherit)
5447             m_style->inheritTransitions(m_parentStyle->transitions());
5448         return;
5449     case CSSPropertyWebkitTransitionDelay:
5450         HANDLE_TRANSITION_VALUE(delay, Delay, value)
5451         return;
5452     case CSSPropertyWebkitTransitionDuration:
5453         HANDLE_TRANSITION_VALUE(duration, Duration, value)
5454         return;
5455     case CSSPropertyWebkitTransitionProperty:
5456         HANDLE_TRANSITION_VALUE(property, Property, value)
5457         return;
5458     case CSSPropertyWebkitTransitionTimingFunction:
5459         HANDLE_TRANSITION_VALUE(timingFunction, TimingFunction, value)
5460         return;
5461     case CSSPropertyPointerEvents:
5462     {
5463 #if ENABLE(DASHBOARD_SUPPORT)
5464         // <rdar://problem/6561077> Work around the Stocks widget's misuse of the
5465         // pointer-events property by not applying it in Dashboard.
5466         Settings* settings = m_checker.m_document->settings();
5467         if (settings && settings->usesDashboardBackwardCompatibilityMode())
5468             return;
5469 #endif
5470         HANDLE_INHERIT_AND_INITIAL(pointerEvents, PointerEvents)
5471         if (!primitiveValue)
5472             return;
5473         m_style->setPointerEvents(*primitiveValue);
5474         return;
5475     }
5476     case CSSPropertyWebkitColorCorrection:
5477         if (isInherit) 
5478             m_style->setColorSpace(m_parentStyle->colorSpace());
5479         else if (isInitial)
5480             m_style->setColorSpace(ColorSpaceDeviceRGB);
5481         else {
5482             if (!primitiveValue)
5483                 return;
5484             m_style->setColorSpace(*primitiveValue);
5485         }
5486         return;
5487     case CSSPropertySize:
5488         applyPageSizeProperty(value);
5489         return;
5490     
5491     case CSSPropertySpeak:
5492         HANDLE_INHERIT_AND_INITIAL(speak, Speak);
5493         m_style->setSpeak(*primitiveValue);
5494         return;
5495             
5496     case CSSPropertyInvalid:
5497         return;
5498
5499     // Directional properties are resolved by resolveDirectionAwareProperty() before the switch.
5500     case CSSPropertyWebkitBorderEnd:
5501     case CSSPropertyWebkitBorderEndColor:
5502     case CSSPropertyWebkitBorderEndStyle:
5503     case CSSPropertyWebkitBorderEndWidth:
5504     case CSSPropertyWebkitBorderStart:
5505     case CSSPropertyWebkitBorderStartColor:
5506     case CSSPropertyWebkitBorderStartStyle:
5507     case CSSPropertyWebkitBorderStartWidth:
5508     case CSSPropertyWebkitBorderBefore:
5509     case CSSPropertyWebkitBorderBeforeColor:
5510     case CSSPropertyWebkitBorderBeforeStyle:
5511     case CSSPropertyWebkitBorderBeforeWidth:
5512     case CSSPropertyWebkitBorderAfter:
5513     case CSSPropertyWebkitBorderAfterColor:
5514     case CSSPropertyWebkitBorderAfterStyle:
5515     case CSSPropertyWebkitBorderAfterWidth:
5516     case CSSPropertyWebkitMarginEnd:
5517     case CSSPropertyWebkitMarginStart:
5518     case CSSPropertyWebkitMarginBefore:
5519     case CSSPropertyWebkitMarginAfter:
5520     case CSSPropertyWebkitPaddingEnd:
5521     case CSSPropertyWebkitPaddingStart:
5522     case CSSPropertyWebkitPaddingBefore:
5523     case CSSPropertyWebkitPaddingAfter:
5524     case CSSPropertyWebkitLogicalWidth:
5525     case CSSPropertyWebkitLogicalHeight:
5526     case CSSPropertyWebkitMinLogicalWidth:
5527     case CSSPropertyWebkitMinLogicalHeight:
5528     case CSSPropertyWebkitMaxLogicalWidth:
5529     case CSSPropertyWebkitMaxLogicalHeight:
5530         ASSERT_NOT_REACHED();
5531         break;
5532
5533     case CSSPropertyFontStretch:
5534     case CSSPropertyPage:
5535     case CSSPropertyQuotes:
5536     case CSSPropertyTextLineThrough:
5537     case CSSPropertyTextLineThroughColor:
5538     case CSSPropertyTextLineThroughMode:
5539     case CSSPropertyTextLineThroughStyle:
5540     case CSSPropertyTextLineThroughWidth:
5541     case CSSPropertyTextOverline:
5542     case CSSPropertyTextOverlineColor:
5543     case CSSPropertyTextOverlineMode:
5544     case CSSPropertyTextOverlineStyle:
5545     case CSSPropertyTextOverlineWidth:
5546     case CSSPropertyTextUnderline:
5547     case CSSPropertyTextUnderlineColor:
5548     case CSSPropertyTextUnderlineMode:
5549     case CSSPropertyTextUnderlineStyle:
5550     case CSSPropertyTextUnderlineWidth:
5551     case CSSPropertyWebkitFontSizeDelta:
5552     case CSSPropertyWebkitTextDecorationsInEffect:
5553     case CSSPropertyWebkitTextStroke:
5554     case CSSPropertyWebkitVariableDeclarationBlock:
5555         return;
5556 #if ENABLE(WCSS)
5557     case CSSPropertyWapInputFormat:
5558         if (primitiveValue && m_element->hasTagName(WebCore::inputTag)) {
5559             String mask = primitiveValue->getStringValue();
5560             static_cast<HTMLInputElement*>(m_element)->setWapInputFormat(mask);
5561         }
5562         return;
5563
5564     case CSSPropertyWapInputRequired:
5565         if (primitiveValue && m_element->isFormControlElement()) {
5566             HTMLFormControlElement* element = static_cast<HTMLFormControlElement*>(m_element);
5567             bool required = primitiveValue->getStringValue() == "true";
5568             element->setRequired(required);
5569         }
5570         return;
5571 #endif 
5572
5573     // CSS Text Layout Module Level 3: Vertical writing support
5574     case CSSPropertyWebkitWritingMode:
5575         HANDLE_INHERIT_AND_INITIAL_AND_PRIMITIVE(writingMode, WritingMode)
5576         return;
5577
5578 #ifdef ANDROID_CSS_RING
5579     case CSSPropertyWebkitRing:
5580         if (valueType != CSSValue::CSS_INHERIT || !m_parentNode) return;
5581         m_style->setRingFillColor(m_parentStyle->ringFillColor());
5582         m_style->setRingInnerWidth(m_parentStyle->ringInnerWidth());
5583         m_style->setRingOuterWidth(m_parentStyle->ringOuterWidth());
5584         m_style->setRingOutset(m_parentStyle->ringOutset());
5585         m_style->setRingPressedInnerColor(m_parentStyle->ringPressedInnerColor());
5586         m_style->setRingPressedOuterColor(m_parentStyle->ringPressedOuterColor());
5587         m_style->setRingRadius(m_parentStyle->ringRadius());
5588         m_style->setRingSelectedInnerColor(m_parentStyle->ringSelectedInnerColor());
5589         m_style->setRingSelectedOuterColor(m_parentStyle->ringSelectedOuterColor());
5590         return;
5591     case CSSPropertyWebkitRingFillColor: {
5592         HANDLE_INHERIT_AND_INITIAL(ringFillColor, RingFillColor);
5593         if (!primitiveValue)
5594             break;
5595         Color col = getColorFromPrimitiveValue(primitiveValue).blendWithWhite();
5596         m_style->setRingFillColor(col);
5597         return;
5598     }
5599     case CSSPropertyWebkitRingInnerWidth: {
5600         HANDLE_INHERIT_AND_INITIAL(ringInnerWidth, RingInnerWidth)
5601         if (!primitiveValue)
5602             break;
5603         Length l;
5604         int type = primitiveValue->primitiveType();
5605         if (CSSPrimitiveValue::isUnitTypeLength(type)) {
5606             // width can be specified with fractional px
5607             // scale by 16 here (and unscale in android_graphics) to keep
5608             // 4 bits of fraction
5609             RefPtr<CSSPrimitiveValue> scaledValue = CSSPrimitiveValue::create(
5610                 primitiveValue->getFloatValue() * 16,
5611                 (CSSPrimitiveValue::UnitTypes) type);
5612             l = Length(scaledValue->computeLengthIntForLength(style(),
5613                 m_rootElementStyle, zoomFactor), Fixed);
5614             scaledValue.release();
5615         } else if (type == CSSPrimitiveValue::CSS_PERCENTAGE)
5616             l = Length(primitiveValue->getDoubleValue(), Percent);
5617         else
5618             return;
5619         m_style->setRingInnerWidth(l);
5620         return;
5621     }
5622     case CSSPropertyWebkitRingOuterWidth: {
5623         HANDLE_INHERIT_AND_INITIAL(ringOuterWidth, RingOuterWidth)
5624         if (!primitiveValue)
5625             break;
5626         Length l;
5627         int type = primitiveValue->primitiveType();
5628         if (CSSPrimitiveValue::isUnitTypeLength(type)) {
5629             // width can be specified with fractional px
5630             // scale by 16 here (and unscale in android_graphics) to keep
5631             // 4 bits of fraction
5632             RefPtr<CSSPrimitiveValue> scaledValue = CSSPrimitiveValue::create(
5633                 primitiveValue->getFloatValue() * 16,
5634                 (CSSPrimitiveValue::UnitTypes) type);
5635             l = Length(scaledValue->computeLengthIntForLength(style(),
5636                 m_rootElementStyle, zoomFactor), Fixed);
5637             scaledValue.release();
5638         } else if (type == CSSPrimitiveValue::CSS_PERCENTAGE)
5639             l = Length(primitiveValue->getDoubleValue(), Percent);
5640         else
5641             return;
5642         m_style->setRingOuterWidth(l);
5643         return;
5644     }
5645     case CSSPropertyWebkitRingOutset: {
5646         HANDLE_INHERIT_AND_INITIAL(ringOutset, RingOutset)
5647         if (!primitiveValue)
5648             break;
5649         Length l;
5650         int type = primitiveValue->primitiveType();
5651         if (CSSPrimitiveValue::isUnitTypeLength(type))
5652             l = Length(primitiveValue->computeLengthIntForLength(style(),
5653                 m_rootElementStyle, zoomFactor), Fixed);
5654         else if (type == CSSPrimitiveValue::CSS_PERCENTAGE)
5655             l = Length(primitiveValue->getDoubleValue(), Percent);
5656         else
5657             return;
5658         m_style->setRingOutset(l);
5659         return;
5660     }
5661     case CSSPropertyWebkitRingPressedInnerColor: {
5662         HANDLE_INHERIT_AND_INITIAL(ringPressedInnerColor, RingPressedInnerColor);
5663         if (!primitiveValue)
5664             break;
5665         Color col = getColorFromPrimitiveValue(primitiveValue).blendWithWhite();
5666         m_style->setRingPressedInnerColor(col);
5667         return;
5668     }
5669     case CSSPropertyWebkitRingPressedOuterColor: {
5670         HANDLE_INHERIT_AND_INITIAL(ringPressedOuterColor, RingPressedOuterColor);
5671         if (!primitiveValue)
5672             break;
5673         Color col = getColorFromPrimitiveValue(primitiveValue).blendWithWhite();
5674         m_style->setRingPressedOuterColor(col);
5675         return;
5676     }
5677     case CSSPropertyWebkitRingRadius: {
5678         HANDLE_INHERIT_AND_INITIAL(ringRadius, RingRadius)
5679         if (!primitiveValue)
5680             break;
5681         Length l;
5682         int type = primitiveValue->primitiveType();
5683         if (CSSPrimitiveValue::isUnitTypeLength(type))
5684             l = Length(primitiveValue->computeLengthIntForLength(style(),
5685                 m_rootElementStyle, zoomFactor), Fixed);
5686         else if (type == CSSPrimitiveValue::CSS_PERCENTAGE)
5687             l = Length(primitiveValue->getDoubleValue(), Percent);
5688         else
5689             return;
5690         m_style->setRingRadius(l);
5691         return;
5692     }
5693     case CSSPropertyWebkitRingSelectedInnerColor: {
5694         HANDLE_INHERIT_AND_INITIAL(ringSelectedInnerColor, RingSelectedInnerColor);
5695         if (!primitiveValue)
5696             break;
5697         Color col = getColorFromPrimitiveValue(primitiveValue).blendWithWhite();
5698         m_style->setRingSelectedInnerColor(col);
5699         return;
5700     }
5701     case CSSPropertyWebkitRingSelectedOuterColor: {
5702         HANDLE_INHERIT_AND_INITIAL(ringSelectedOuterColor, RingSelectedOuterColor);
5703         if (!primitiveValue)
5704             break;
5705         Color col = getColorFromPrimitiveValue(primitiveValue).blendWithWhite();
5706         m_style->setRingSelectedOuterColor(col);
5707         return;
5708     }
5709 #endif
5710 #ifdef ANDROID_CSS_TAP_HIGHLIGHT_COLOR
5711     case CSSPropertyWebkitTapHighlightColor: {
5712         HANDLE_INHERIT_AND_INITIAL(tapHighlightColor, TapHighlightColor);
5713         if (!primitiveValue)
5714             break;
5715
5716         Color col = getColorFromPrimitiveValue(primitiveValue).blendWithWhite();
5717         m_style->setTapHighlightColor(col);
5718         return;
5719     }
5720 #endif
5721
5722 #if ENABLE(SVG)
5723     default:
5724         // Try the SVG properties
5725         applySVGProperty(id, value);
5726 #endif
5727     }
5728 }
5729
5730 void CSSStyleSelector::applyPageSizeProperty(CSSValue* value)
5731 {
5732     m_style->resetPageSizeType();
5733     if (!value->isValueList())
5734         return;
5735     CSSValueList* valueList = static_cast<CSSValueList*>(value);
5736     Length width;
5737     Length height;
5738     PageSizeType pageSizeType = PAGE_SIZE_AUTO;
5739     switch (valueList->length()) {
5740     case 2: {
5741         // <length>{2} | <page-size> <orientation>
5742         pageSizeType = PAGE_SIZE_RESOLVED;
5743         if (!valueList->item(0)->isPrimitiveValue() || !valueList->item(1)->isPrimitiveValue())
5744             return;
5745         CSSPrimitiveValue* primitiveValue0 = static_cast<CSSPrimitiveValue*>(valueList->item(0));
5746         CSSPrimitiveValue* primitiveValue1 = static_cast<CSSPrimitiveValue*>(valueList->item(1));
5747         int type0 = primitiveValue0->primitiveType();
5748         int type1 = primitiveValue1->primitiveType();
5749         if (CSSPrimitiveValue::isUnitTypeLength(type0)) {
5750             // <length>{2}
5751             if (!CSSPrimitiveValue::isUnitTypeLength(type1))
5752                 return;
5753             width = Length(primitiveValue0->computeLengthIntForLength(style(), m_rootElementStyle), Fixed);
5754             height = Length(primitiveValue1->computeLengthIntForLength(style(), m_rootElementStyle), Fixed);
5755         } else {
5756             // <page-size> <orientation>
5757             // The value order is guaranteed. See CSSParser::parseSizeParameter.
5758             if (!pageSizeFromName(primitiveValue0, primitiveValue1, width, height))
5759                 return;
5760         }
5761         break;
5762     }
5763     case 1: {
5764         // <length> | auto | <page-size> | [ portrait | landscape]
5765         if (!valueList->item(0)->isPrimitiveValue())
5766             return;
5767         CSSPrimitiveValue* primitiveValue = static_cast<CSSPrimitiveValue*>(valueList->item(0));
5768         int type = primitiveValue->primitiveType();
5769         if (CSSPrimitiveValue::isUnitTypeLength(type)) {
5770             // <length>
5771             pageSizeType = PAGE_SIZE_RESOLVED;
5772             width = height = Length(primitiveValue->computeLengthIntForLength(style(), m_rootElementStyle), Fixed);
5773         } else {
5774             if (type != CSSPrimitiveValue::CSS_IDENT)
5775                 return;
5776             switch (primitiveValue->getIdent()) {
5777             case CSSValueAuto:
5778                 pageSizeType = PAGE_SIZE_AUTO;
5779                 break;
5780             case CSSValuePortrait:
5781                 pageSizeType = PAGE_SIZE_AUTO_PORTRAIT;
5782                 break;
5783             case CSSValueLandscape:
5784                 pageSizeType = PAGE_SIZE_AUTO_LANDSCAPE;
5785                 break;
5786             default:
5787                 // <page-size>
5788                 pageSizeType = PAGE_SIZE_RESOLVED;
5789                 if (!pageSizeFromName(primitiveValue, 0, width, height))
5790                     return;
5791             }
5792         }
5793         break;
5794     }
5795     default:
5796         return;
5797     }
5798     m_style->setPageSizeType(pageSizeType);
5799     m_style->setPageSize(LengthSize(width, height));
5800     return;
5801 }
5802
5803 bool CSSStyleSelector::pageSizeFromName(CSSPrimitiveValue* pageSizeName, CSSPrimitiveValue* pageOrientation, Length& width, Length& height)
5804 {
5805     static const Length a5Width = mmLength(148), a5Height = mmLength(210);
5806     static const Length a4Width = mmLength(210), a4Height = mmLength(297);
5807     static const Length a3Width = mmLength(297), a3Height = mmLength(420);
5808     static const Length b5Width = mmLength(176), b5Height = mmLength(250);
5809     static const Length b4Width = mmLength(250), b4Height = mmLength(353);
5810     static const Length letterWidth = inchLength(8.5), letterHeight = inchLength(11);
5811     static const Length legalWidth = inchLength(8.5), legalHeight = inchLength(14);
5812     static const Length ledgerWidth = inchLength(11), ledgerHeight = inchLength(17);
5813
5814     if (!pageSizeName || pageSizeName->primitiveType() != CSSPrimitiveValue::CSS_IDENT)
5815         return false;
5816
5817     switch (pageSizeName->getIdent()) {
5818     case CSSValueA5:
5819         width = a5Width;
5820         height = a5Height;
5821         break;
5822     case CSSValueA4:
5823         width = a4Width;
5824         height = a4Height;
5825         break;
5826     case CSSValueA3:
5827         width = a3Width;
5828         height = a3Height;
5829         break;
5830     case CSSValueB5:
5831         width = b5Width;
5832         height = b5Height;
5833         break;
5834     case CSSValueB4:
5835         width = b4Width;
5836         height = b4Height;
5837         break;
5838     case CSSValueLetter:
5839         width = letterWidth;
5840         height = letterHeight;
5841         break;
5842     case CSSValueLegal:
5843         width = legalWidth;
5844         height = legalHeight;
5845         break;
5846     case CSSValueLedger:
5847         width = ledgerWidth;
5848         height = ledgerHeight;
5849         break;
5850     default:
5851         return false;
5852     }
5853
5854     if (pageOrientation) {
5855         if (pageOrientation->primitiveType() != CSSPrimitiveValue::CSS_IDENT)
5856             return false;
5857         switch (pageOrientation->getIdent()) {
5858         case CSSValueLandscape:
5859             std::swap(width, height);
5860             break;
5861         case CSSValuePortrait:
5862             // Nothing to do.
5863             break;
5864         default:
5865             return false;
5866         }
5867     }
5868     return true;
5869 }
5870
5871 Length CSSStyleSelector::mmLength(double mm)
5872 {
5873     return Length(CSSPrimitiveValue::create(mm, CSSPrimitiveValue::CSS_MM)->computeLengthIntForLength(style(), m_rootElementStyle), Fixed);
5874 }
5875
5876 Length CSSStyleSelector::inchLength(double inch)
5877 {
5878     return Length(CSSPrimitiveValue::create(inch, CSSPrimitiveValue::CSS_IN)->computeLengthIntForLength(style(), m_rootElementStyle), Fixed);
5879 }
5880
5881 void CSSStyleSelector::mapFillAttachment(CSSPropertyID, FillLayer* layer, CSSValue* value)
5882 {
5883     if (value->cssValueType() == CSSValue::CSS_INITIAL) {
5884         layer->setAttachment(FillLayer::initialFillAttachment(layer->type()));
5885         return;
5886     }
5887
5888     if (!value->isPrimitiveValue())
5889         return;
5890
5891     CSSPrimitiveValue* primitiveValue = static_cast<CSSPrimitiveValue*>(value);
5892     switch (primitiveValue->getIdent()) {
5893         case CSSValueFixed:
5894             layer->setAttachment(FixedBackgroundAttachment);
5895             break;
5896         case CSSValueScroll:
5897             layer->setAttachment(ScrollBackgroundAttachment);
5898             break;
5899         case CSSValueLocal:
5900             layer->setAttachment(LocalBackgroundAttachment);
5901             break;
5902         default:
5903             return;
5904     }
5905 }
5906
5907 void CSSStyleSelector::mapFillClip(CSSPropertyID, FillLayer* layer, CSSValue* value)
5908 {
5909     if (value->cssValueType() == CSSValue::CSS_INITIAL) {
5910         layer->setClip(FillLayer::initialFillClip(layer->type()));
5911         return;
5912     }
5913
5914     if (!value->isPrimitiveValue())
5915         return;
5916
5917     CSSPrimitiveValue* primitiveValue = static_cast<CSSPrimitiveValue*>(value);
5918     layer->setClip(*primitiveValue);
5919 }
5920
5921 void CSSStyleSelector::mapFillComposite(CSSPropertyID, FillLayer* layer, CSSValue* value)
5922 {
5923     if (value->cssValueType() == CSSValue::CSS_INITIAL) {
5924         layer->setComposite(FillLayer::initialFillComposite(layer->type()));
5925         return;
5926     }
5927     
5928     if (!value->isPrimitiveValue())
5929         return;
5930
5931     CSSPrimitiveValue* primitiveValue = static_cast<CSSPrimitiveValue*>(value);
5932     layer->setComposite(*primitiveValue);
5933 }
5934
5935 void CSSStyleSelector::mapFillOrigin(CSSPropertyID, FillLayer* layer, CSSValue* value)
5936 {
5937     if (value->cssValueType() == CSSValue::CSS_INITIAL) {
5938         layer->setOrigin(FillLayer::initialFillOrigin(layer->type()));
5939         return;
5940     }
5941
5942     if (!value->isPrimitiveValue())
5943         return;
5944
5945     CSSPrimitiveValue* primitiveValue = static_cast<CSSPrimitiveValue*>(value);
5946     layer->setOrigin(*primitiveValue);
5947 }
5948
5949 StyleImage* CSSStyleSelector::styleImage(CSSPropertyID property, CSSValue* value)
5950 {
5951     if (value->isImageValue())
5952         return cachedOrPendingFromValue(property, static_cast<CSSImageValue*>(value));
5953
5954     if (value->isImageGeneratorValue())
5955         return static_cast<CSSImageGeneratorValue*>(value)->generatedImage();
5956
5957     return 0;
5958 }
5959
5960 StyleImage* CSSStyleSelector::cachedOrPendingFromValue(CSSPropertyID property, CSSImageValue* value)
5961 {
5962     StyleImage* image = value->cachedOrPendingImage();
5963     if (image && image->isPendingImage())
5964         m_pendingImageProperties.add(property);
5965     return image;
5966 }
5967
5968 void CSSStyleSelector::mapFillImage(CSSPropertyID property, FillLayer* layer, CSSValue* value)
5969 {
5970     if (value->cssValueType() == CSSValue::CSS_INITIAL) {
5971         layer->setImage(FillLayer::initialFillImage(layer->type()));
5972         return;
5973     }
5974
5975     layer->setImage(styleImage(property, value));
5976 }
5977
5978 void CSSStyleSelector::mapFillRepeatX(CSSPropertyID, FillLayer* layer, CSSValue* value)
5979 {
5980     if (value->cssValueType() == CSSValue::CSS_INITIAL) {
5981         layer->setRepeatX(FillLayer::initialFillRepeatX(layer->type()));
5982         return;
5983     }
5984     
5985     if (!value->isPrimitiveValue())
5986         return;
5987
5988     CSSPrimitiveValue* primitiveValue = static_cast<CSSPrimitiveValue*>(value);
5989     layer->setRepeatX(*primitiveValue);
5990 }
5991
5992 void CSSStyleSelector::mapFillRepeatY(CSSPropertyID, FillLayer* layer, CSSValue* value)
5993 {
5994     if (value->cssValueType() == CSSValue::CSS_INITIAL) {
5995         layer->setRepeatY(FillLayer::initialFillRepeatY(layer->type()));
5996         return;
5997     }
5998     
5999     if (!value->isPrimitiveValue())
6000         return;
6001
6002     CSSPrimitiveValue* primitiveValue = static_cast<CSSPrimitiveValue*>(value);
6003     layer->setRepeatY(*primitiveValue);
6004 }
6005
6006 void CSSStyleSelector::mapFillSize(CSSPropertyID, FillLayer* layer, CSSValue* value)
6007 {
6008     if (!value->isPrimitiveValue()) {
6009         layer->setSizeType(SizeNone);
6010         return;
6011     }
6012
6013     CSSPrimitiveValue* primitiveValue = static_cast<CSSPrimitiveValue*>(value);
6014     if (primitiveValue->getIdent() == CSSValueContain)
6015         layer->setSizeType(Contain);
6016     else if (primitiveValue->getIdent() == CSSValueCover)
6017         layer->setSizeType(Cover);
6018     else
6019         layer->setSizeType(SizeLength);
6020     
6021     LengthSize b = FillLayer::initialFillSizeLength(layer->type());
6022     
6023     if (value->cssValueType() == CSSValue::CSS_INITIAL || primitiveValue->getIdent() == CSSValueContain
6024         || primitiveValue->getIdent() == CSSValueCover) {
6025         layer->setSizeLength(b);
6026         return;
6027     }
6028
6029     Pair* pair = primitiveValue->getPairValue();
6030     if (!pair)
6031         return;
6032     
6033     CSSPrimitiveValue* first = static_cast<CSSPrimitiveValue*>(pair->first());
6034     CSSPrimitiveValue* second = static_cast<CSSPrimitiveValue*>(pair->second());
6035     
6036     if (!first || !second)
6037         return;
6038         
6039     Length firstLength, secondLength;
6040     int firstType = first->primitiveType();
6041     int secondType = second->primitiveType();
6042     
6043     float zoomFactor = m_style->effectiveZoom();
6044
6045     if (firstType == CSSPrimitiveValue::CSS_UNKNOWN)
6046         firstLength = Length(Auto);
6047     else if (CSSPrimitiveValue::isUnitTypeLength(firstType))
6048         firstLength = Length(first->computeLengthIntForLength(style(), m_rootElementStyle, zoomFactor), Fixed);
6049     else if (firstType == CSSPrimitiveValue::CSS_PERCENTAGE)
6050         firstLength = Length(first->getDoubleValue(), Percent);
6051     else
6052         return;
6053
6054     if (secondType == CSSPrimitiveValue::CSS_UNKNOWN)
6055         secondLength = Length(Auto);
6056     else if (CSSPrimitiveValue::isUnitTypeLength(secondType))
6057         secondLength = Length(second->computeLengthIntForLength(style(), m_rootElementStyle, zoomFactor), Fixed);
6058     else if (secondType == CSSPrimitiveValue::CSS_PERCENTAGE)
6059         secondLength = Length(second->getDoubleValue(), Percent);
6060     else
6061         return;
6062     
6063     b.setWidth(firstLength);
6064     b.setHeight(secondLength);
6065     layer->setSizeLength(b);
6066 }
6067
6068 void CSSStyleSelector::mapFillXPosition(CSSPropertyID, FillLayer* layer, CSSValue* value)
6069 {
6070     if (value->cssValueType() == CSSValue::CSS_INITIAL) {
6071         layer->setXPosition(FillLayer::initialFillXPosition(layer->type()));
6072         return;
6073     }
6074     
6075     if (!value->isPrimitiveValue())
6076         return;
6077
6078     float zoomFactor = m_style->effectiveZoom();
6079
6080     CSSPrimitiveValue* primitiveValue = static_cast<CSSPrimitiveValue*>(value);
6081     Length l;
6082     int type = primitiveValue->primitiveType();
6083     if (CSSPrimitiveValue::isUnitTypeLength(type))
6084         l = Length(primitiveValue->computeLengthIntForLength(style(), m_rootElementStyle, zoomFactor), Fixed);
6085     else if (type == CSSPrimitiveValue::CSS_PERCENTAGE)
6086         l = Length(primitiveValue->getDoubleValue(), Percent);
6087     else
6088         return;
6089     layer->setXPosition(l);
6090 }
6091
6092 void CSSStyleSelector::mapFillYPosition(CSSPropertyID, FillLayer* layer, CSSValue* value)
6093 {
6094     if (value->cssValueType() == CSSValue::CSS_INITIAL) {
6095         layer->setYPosition(FillLayer::initialFillYPosition(layer->type()));
6096         return;
6097     }
6098     
6099     if (!value->isPrimitiveValue())
6100         return;
6101
6102     float zoomFactor = m_style->effectiveZoom();
6103     
6104     CSSPrimitiveValue* primitiveValue = static_cast<CSSPrimitiveValue*>(value);
6105     Length l;
6106     int type = primitiveValue->primitiveType();
6107     if (CSSPrimitiveValue::isUnitTypeLength(type))
6108         l = Length(primitiveValue->computeLengthIntForLength(style(), m_rootElementStyle, zoomFactor), Fixed);
6109     else if (type == CSSPrimitiveValue::CSS_PERCENTAGE)
6110         l = Length(primitiveValue->getDoubleValue(), Percent);
6111     else
6112         return;
6113     layer->setYPosition(l);
6114 }
6115
6116 void CSSStyleSelector::mapAnimationDelay(Animation* animation, CSSValue* value)
6117 {
6118     if (value->cssValueType() == CSSValue::CSS_INITIAL) {
6119         animation->setDelay(Animation::initialAnimationDelay());
6120         return;
6121     }
6122
6123     CSSPrimitiveValue* primitiveValue = static_cast<CSSPrimitiveValue*>(value);
6124     if (primitiveValue->primitiveType() == CSSPrimitiveValue::CSS_S)
6125         animation->setDelay(primitiveValue->getFloatValue());
6126     else
6127         animation->setDelay(primitiveValue->getFloatValue()/1000.0f);
6128 }
6129
6130 void CSSStyleSelector::mapAnimationDirection(Animation* layer, CSSValue* value)
6131 {
6132     if (value->cssValueType() == CSSValue::CSS_INITIAL) {
6133         layer->setDirection(Animation::initialAnimationDirection());
6134         return;
6135     }
6136
6137     CSSPrimitiveValue* primitiveValue = static_cast<CSSPrimitiveValue*>(value);
6138     layer->setDirection(primitiveValue->getIdent() == CSSValueAlternate ? Animation::AnimationDirectionAlternate : Animation::AnimationDirectionNormal);
6139 }
6140
6141 void CSSStyleSelector::mapAnimationDuration(Animation* animation, CSSValue* value)
6142 {
6143     if (value->cssValueType() == CSSValue::CSS_INITIAL) {
6144         animation->setDuration(Animation::initialAnimationDuration());
6145         return;
6146     }
6147
6148     if (!value->isPrimitiveValue())
6149         return;
6150
6151     CSSPrimitiveValue* primitiveValue = static_cast<CSSPrimitiveValue*>(value);
6152     if (primitiveValue->primitiveType() == CSSPrimitiveValue::CSS_S)
6153         animation->setDuration(primitiveValue->getFloatValue());
6154     else if (primitiveValue->primitiveType() == CSSPrimitiveValue::CSS_MS)
6155         animation->setDuration(primitiveValue->getFloatValue()/1000.0f);
6156 }
6157
6158 void CSSStyleSelector::mapAnimationFillMode(Animation* layer, CSSValue* value)
6159 {
6160     if (value->cssValueType() == CSSValue::CSS_INITIAL) {
6161         layer->setFillMode(Animation::initialAnimationFillMode());
6162         return;
6163     }
6164
6165     CSSPrimitiveValue* primitiveValue = static_cast<CSSPrimitiveValue*>(value);
6166     switch (primitiveValue->getIdent()) {
6167     case CSSValueNone:
6168         layer->setFillMode(AnimationFillModeNone);
6169         break;
6170     case CSSValueForwards:
6171         layer->setFillMode(AnimationFillModeForwards);
6172         break;
6173     case CSSValueBackwards:
6174         layer->setFillMode(AnimationFillModeBackwards);
6175         break;
6176     case CSSValueBoth:
6177         layer->setFillMode(AnimationFillModeBoth);
6178         break;
6179     }
6180 }
6181
6182 void CSSStyleSelector::mapAnimationIterationCount(Animation* animation, CSSValue* value)
6183 {
6184     if (value->cssValueType() == CSSValue::CSS_INITIAL) {
6185         animation->setIterationCount(Animation::initialAnimationIterationCount());
6186         return;
6187     }
6188
6189     if (!value->isPrimitiveValue())
6190         return;
6191
6192     CSSPrimitiveValue* primitiveValue = static_cast<CSSPrimitiveValue*>(value);
6193     if (primitiveValue->getIdent() == CSSValueInfinite)
6194         animation->setIterationCount(-1);
6195     else
6196         animation->setIterationCount(int(primitiveValue->getFloatValue()));
6197 }
6198
6199 void CSSStyleSelector::mapAnimationName(Animation* layer, CSSValue* value)
6200 {
6201     if (value->cssValueType() == CSSValue::CSS_INITIAL) {
6202         layer->setName(Animation::initialAnimationName());
6203         return;
6204     }
6205
6206     CSSPrimitiveValue* primitiveValue = static_cast<CSSPrimitiveValue*>(value);
6207     
6208     if (primitiveValue->getIdent() == CSSValueNone)
6209         layer->setIsNoneAnimation(true);
6210     else
6211         layer->setName(primitiveValue->getStringValue());
6212 }
6213
6214 void CSSStyleSelector::mapAnimationPlayState(Animation* layer, CSSValue* value)
6215 {
6216     if (value->cssValueType() == CSSValue::CSS_INITIAL) {
6217         layer->setPlayState(Animation::initialAnimationPlayState());
6218         return;
6219     }
6220
6221     CSSPrimitiveValue* primitiveValue = static_cast<CSSPrimitiveValue*>(value);
6222     EAnimPlayState playState = (primitiveValue->getIdent() == CSSValuePaused) ? AnimPlayStatePaused : AnimPlayStatePlaying;
6223     layer->setPlayState(playState);
6224 }
6225
6226 void CSSStyleSelector::mapAnimationProperty(Animation* animation, CSSValue* value)
6227 {
6228     if (value->cssValueType() == CSSValue::CSS_INITIAL) {
6229         animation->setProperty(Animation::initialAnimationProperty());
6230         return;
6231     }
6232
6233     if (!value->isPrimitiveValue())
6234         return;
6235
6236     CSSPrimitiveValue* primitiveValue = static_cast<CSSPrimitiveValue*>(value);
6237     if (primitiveValue->getIdent() == CSSValueAll)
6238         animation->setProperty(cAnimateAll);
6239     else if (primitiveValue->getIdent() == CSSValueNone)
6240         animation->setProperty(cAnimateNone);
6241     else
6242         animation->setProperty(static_cast<CSSPropertyID>(primitiveValue->getIdent()));
6243 }
6244
6245 void CSSStyleSelector::mapAnimationTimingFunction(Animation* animation, CSSValue* value)
6246 {
6247     if (value->cssValueType() == CSSValue::CSS_INITIAL) {
6248         animation->setTimingFunction(Animation::initialAnimationTimingFunction());
6249         return;
6250     }
6251     
6252     if (value->isPrimitiveValue()) {
6253         CSSPrimitiveValue* primitiveValue = static_cast<CSSPrimitiveValue*>(value);
6254         switch (primitiveValue->getIdent()) {
6255             case CSSValueLinear:
6256                 animation->setTimingFunction(LinearTimingFunction::create());
6257                 break;
6258             case CSSValueEase:
6259                 animation->setTimingFunction(CubicBezierTimingFunction::create());
6260                 break;
6261             case CSSValueEaseIn:
6262                 animation->setTimingFunction(CubicBezierTimingFunction::create(0.42, 0.0, 1.0, 1.0));
6263                 break;
6264             case CSSValueEaseOut:
6265                 animation->setTimingFunction(CubicBezierTimingFunction::create(0.0, 0.0, 0.58, 1.0));
6266                 break;
6267             case CSSValueEaseInOut:
6268                 animation->setTimingFunction(CubicBezierTimingFunction::create(0.42, 0.0, 0.58, 1.0));
6269                 break;
6270             case CSSValueStepStart:
6271                 animation->setTimingFunction(StepsTimingFunction::create(1, true));
6272                 break;
6273             case CSSValueStepEnd:
6274                 animation->setTimingFunction(StepsTimingFunction::create(1, false));
6275                 break;
6276         }
6277         return;
6278     }
6279     
6280     if (value->isTimingFunctionValue()) {
6281         CSSTimingFunctionValue* timingFunction = static_cast<CSSTimingFunctionValue*>(value);
6282         if (timingFunction->isCubicBezierTimingFunctionValue()) {
6283             CSSCubicBezierTimingFunctionValue* cubicTimingFunction = static_cast<CSSCubicBezierTimingFunctionValue*>(value);
6284             animation->setTimingFunction(CubicBezierTimingFunction::create(cubicTimingFunction->x1(), cubicTimingFunction->y1(), cubicTimingFunction->x2(), cubicTimingFunction->y2()));
6285         } else if (timingFunction->isStepsTimingFunctionValue()) {
6286             CSSStepsTimingFunctionValue* stepsTimingFunction = static_cast<CSSStepsTimingFunctionValue*>(value);
6287             animation->setTimingFunction(StepsTimingFunction::create(stepsTimingFunction->numberOfSteps(), stepsTimingFunction->stepAtStart()));
6288         } else
6289             animation->setTimingFunction(LinearTimingFunction::create());
6290     }
6291 }
6292
6293 void CSSStyleSelector::mapNinePieceImage(CSSPropertyID property, CSSValue* value, NinePieceImage& image)
6294 {
6295     // If we're a primitive value, then we are "none" and don't need to alter the empty image at all.
6296     if (!value || value->isPrimitiveValue())
6297         return;
6298
6299     // Retrieve the border image value.
6300     CSSBorderImageValue* borderImage = static_cast<CSSBorderImageValue*>(value);
6301     
6302     // Set the image (this kicks off the load).
6303     image.setImage(styleImage(property, borderImage->imageValue()));
6304
6305     // Set up a length box to represent our image slices.
6306     LengthBox l;
6307     Rect* r = borderImage->m_imageSliceRect.get();
6308     if (r->top()->primitiveType() == CSSPrimitiveValue::CSS_PERCENTAGE)
6309         l.m_top = Length(r->top()->getDoubleValue(), Percent);
6310     else
6311         l.m_top = Length(r->top()->getIntValue(CSSPrimitiveValue::CSS_NUMBER), Fixed);
6312     if (r->bottom()->primitiveType() == CSSPrimitiveValue::CSS_PERCENTAGE)
6313         l.m_bottom = Length(r->bottom()->getDoubleValue(), Percent);
6314     else
6315         l.m_bottom = Length((int)r->bottom()->getFloatValue(CSSPrimitiveValue::CSS_NUMBER), Fixed);
6316     if (r->left()->primitiveType() == CSSPrimitiveValue::CSS_PERCENTAGE)
6317         l.m_left = Length(r->left()->getDoubleValue(), Percent);
6318     else
6319         l.m_left = Length(r->left()->getIntValue(CSSPrimitiveValue::CSS_NUMBER), Fixed);
6320     if (r->right()->primitiveType() == CSSPrimitiveValue::CSS_PERCENTAGE)
6321         l.m_right = Length(r->right()->getDoubleValue(), Percent);
6322     else
6323         l.m_right = Length(r->right()->getIntValue(CSSPrimitiveValue::CSS_NUMBER), Fixed);
6324     image.setSlices(l);
6325
6326     // Set the appropriate rules for stretch/round/repeat of the slices
6327     ENinePieceImageRule horizontalRule;
6328     switch (borderImage->m_horizontalSizeRule) {
6329         case CSSValueStretch:
6330             horizontalRule = StretchImageRule;
6331             break;
6332         case CSSValueRound:
6333             horizontalRule = RoundImageRule;
6334             break;
6335         default: // CSSValueRepeat
6336             horizontalRule = RepeatImageRule;
6337             break;
6338     }
6339     image.setHorizontalRule(horizontalRule);
6340
6341     ENinePieceImageRule verticalRule;
6342     switch (borderImage->m_verticalSizeRule) {
6343         case CSSValueStretch:
6344             verticalRule = StretchImageRule;
6345             break;
6346         case CSSValueRound:
6347             verticalRule = RoundImageRule;
6348             break;
6349         default: // CSSValueRepeat
6350             verticalRule = RepeatImageRule;
6351             break;
6352     }
6353     image.setVerticalRule(verticalRule);
6354 }
6355
6356 void CSSStyleSelector::checkForTextSizeAdjust()
6357 {
6358     if (m_style->textSizeAdjust())
6359         return;
6360  
6361     FontDescription newFontDescription(m_style->fontDescription());
6362     newFontDescription.setComputedSize(newFontDescription.specifiedSize());
6363     m_style->setFontDescription(newFontDescription);
6364 }
6365
6366 void CSSStyleSelector::checkForZoomChange(RenderStyle* style, RenderStyle* parentStyle)
6367 {
6368     if (style->effectiveZoom() == parentStyle->effectiveZoom())
6369         return;
6370     
6371     const FontDescription& childFont = style->fontDescription();
6372     FontDescription newFontDescription(childFont);
6373     setFontSize(newFontDescription, childFont.specifiedSize());
6374     style->setFontDescription(newFontDescription);
6375 }
6376
6377 void CSSStyleSelector::checkForGenericFamilyChange(RenderStyle* style, RenderStyle* parentStyle)
6378 {
6379     const FontDescription& childFont = style->fontDescription();
6380   
6381     if (childFont.isAbsoluteSize() || !parentStyle)
6382         return;
6383
6384     const FontDescription& parentFont = parentStyle->fontDescription();
6385     if (childFont.useFixedDefaultSize() == parentFont.useFixedDefaultSize())
6386         return;
6387
6388     // For now, lump all families but monospace together.
6389     if (childFont.genericFamily() != FontDescription::MonospaceFamily &&
6390         parentFont.genericFamily() != FontDescription::MonospaceFamily)
6391         return;
6392
6393     // We know the parent is monospace or the child is monospace, and that font
6394     // size was unspecified.  We want to scale our font size as appropriate.
6395     // If the font uses a keyword size, then we refetch from the table rather than
6396     // multiplying by our scale factor.
6397     float size;
6398     if (childFont.keywordSize())
6399         size = fontSizeForKeyword(m_checker.m_document, CSSValueXxSmall + childFont.keywordSize() - 1, childFont.useFixedDefaultSize());
6400     else {
6401         Settings* settings = m_checker.m_document->settings();
6402         float fixedScaleFactor = settings
6403             ? static_cast<float>(settings->defaultFixedFontSize()) / settings->defaultFontSize()
6404             : 1;
6405         size = parentFont.useFixedDefaultSize() ?
6406                 childFont.specifiedSize() / fixedScaleFactor :
6407                 childFont.specifiedSize() * fixedScaleFactor;
6408     }
6409
6410     FontDescription newFontDescription(childFont);
6411     setFontSize(newFontDescription, size);
6412     style->setFontDescription(newFontDescription);
6413 }
6414
6415 void CSSStyleSelector::setFontSize(FontDescription& fontDescription, float size)
6416 {
6417     fontDescription.setSpecifiedSize(size);
6418
6419     bool useSVGZoomRules = m_element && m_element->isSVGElement();
6420     fontDescription.setComputedSize(getComputedSizeFromSpecifiedSize(m_checker.m_document, m_style.get(), fontDescription.isAbsoluteSize(), size, useSVGZoomRules)); 
6421 }
6422
6423 float CSSStyleSelector::getComputedSizeFromSpecifiedSize(Document* document, RenderStyle* style, bool isAbsoluteSize, float specifiedSize, bool useSVGZoomRules)
6424 {
6425     float zoomFactor = 1.0f;
6426     if (!useSVGZoomRules) {
6427         zoomFactor = style->effectiveZoom();
6428         if (Frame* frame = document->frame())
6429             zoomFactor *= frame->textZoomFactor();
6430     }
6431
6432     // We support two types of minimum font size.  The first is a hard override that applies to
6433     // all fonts.  This is "minSize."  The second type of minimum font size is a "smart minimum"
6434     // that is applied only when the Web page can't know what size it really asked for, e.g.,
6435     // when it uses logical sizes like "small" or expresses the font-size as a percentage of
6436     // the user's default font setting.
6437
6438     // With the smart minimum, we never want to get smaller than the minimum font size to keep fonts readable.
6439     // However we always allow the page to set an explicit pixel size that is smaller,
6440     // since sites will mis-render otherwise (e.g., http://www.gamespot.com with a 9px minimum).
6441     
6442     Settings* settings = document->settings();
6443     if (!settings)
6444         return 1.0f;
6445
6446     int minSize = settings->minimumFontSize();
6447     int minLogicalSize = settings->minimumLogicalFontSize();
6448     float zoomedSize = specifiedSize * zoomFactor;
6449
6450     // Apply the hard minimum first.  We only apply the hard minimum if after zooming we're still too small.
6451     if (zoomedSize < minSize)
6452         zoomedSize = minSize;
6453
6454     // Now apply the "smart minimum."  This minimum is also only applied if we're still too small
6455     // after zooming.  The font size must either be relative to the user default or the original size
6456     // must have been acceptable.  In other words, we only apply the smart minimum whenever we're positive
6457     // doing so won't disrupt the layout.
6458     if (zoomedSize < minLogicalSize && (specifiedSize >= minLogicalSize || !isAbsoluteSize))
6459         zoomedSize = minLogicalSize;
6460     
6461     // Also clamp to a reasonable maximum to prevent insane font sizes from causing crashes on various
6462     // platforms (I'm looking at you, Windows.)
6463     return min(1000000.0f, max(zoomedSize, 1.0f));
6464 }
6465
6466 const int fontSizeTableMax = 16;
6467 const int fontSizeTableMin = 9;
6468 const int totalKeywords = 8;
6469
6470 // WinIE/Nav4 table for font sizes.  Designed to match the legacy font mapping system of HTML.
6471 static const int quirksFontSizeTable[fontSizeTableMax - fontSizeTableMin + 1][totalKeywords] =
6472 {
6473       { 9,    9,     9,     9,    11,    14,    18,    28 },
6474       { 9,    9,     9,    10,    12,    15,    20,    31 },
6475       { 9,    9,     9,    11,    13,    17,    22,    34 },
6476       { 9,    9,    10,    12,    14,    18,    24,    37 },
6477       { 9,    9,    10,    13,    16,    20,    26,    40 }, // fixed font default (13)
6478       { 9,    9,    11,    14,    17,    21,    28,    42 },
6479       { 9,   10,    12,    15,    17,    23,    30,    45 },
6480       { 9,   10,    13,    16,    18,    24,    32,    48 }  // proportional font default (16)
6481 };
6482 // HTML       1      2      3      4      5      6      7
6483 // CSS  xxs   xs     s      m      l     xl     xxl
6484 //                          |
6485 //                      user pref
6486
6487 // Strict mode table matches MacIE and Mozilla's settings exactly.
6488 static const int strictFontSizeTable[fontSizeTableMax - fontSizeTableMin + 1][totalKeywords] =
6489 {
6490       { 9,    9,     9,     9,    11,    14,    18,    27 },
6491       { 9,    9,     9,    10,    12,    15,    20,    30 },
6492       { 9,    9,    10,    11,    13,    17,    22,    33 },
6493       { 9,    9,    10,    12,    14,    18,    24,    36 },
6494       { 9,   10,    12,    13,    16,    20,    26,    39 }, // fixed font default (13)
6495       { 9,   10,    12,    14,    17,    21,    28,    42 },
6496       { 9,   10,    13,    15,    18,    23,    30,    45 },
6497       { 9,   10,    13,    16,    18,    24,    32,    48 }  // proportional font default (16)
6498 };
6499 // HTML       1      2      3      4      5      6      7
6500 // CSS  xxs   xs     s      m      l     xl     xxl
6501 //                          |
6502 //                      user pref
6503
6504 // For values outside the range of the table, we use Todd Fahrner's suggested scale
6505 // factors for each keyword value.
6506 static const float fontSizeFactors[totalKeywords] = { 0.60f, 0.75f, 0.89f, 1.0f, 1.2f, 1.5f, 2.0f, 3.0f };
6507
6508 float CSSStyleSelector::fontSizeForKeyword(Document* document, int keyword, bool shouldUseFixedDefaultSize)
6509 {
6510     Settings* settings = document->settings();
6511     if (!settings)
6512         return 1.0f;
6513
6514     bool quirksMode = document->inQuirksMode();
6515     int mediumSize = shouldUseFixedDefaultSize ? settings->defaultFixedFontSize() : settings->defaultFontSize();
6516     if (mediumSize >= fontSizeTableMin && mediumSize <= fontSizeTableMax) {
6517         // Look up the entry in the table.
6518         int row = mediumSize - fontSizeTableMin;
6519         int col = (keyword - CSSValueXxSmall);
6520         return quirksMode ? quirksFontSizeTable[row][col] : strictFontSizeTable[row][col];
6521     }
6522     
6523     // Value is outside the range of the table. Apply the scale factor instead.
6524     float minLogicalSize = max(settings->minimumLogicalFontSize(), 1);
6525     return max(fontSizeFactors[keyword - CSSValueXxSmall]*mediumSize, minLogicalSize);
6526 }
6527
6528 template<typename T>
6529 static int findNearestLegacyFontSize(int pixelFontSize, const T* table, int multiplier)
6530 {
6531     // Ignore table[0] because xx-small does not correspond to any legacy font size.
6532     for (int i = 1; i < totalKeywords - 1; i++) {
6533         if (pixelFontSize * 2 < (table[i] + table[i + 1]) * multiplier)
6534             return i;
6535     }
6536     return totalKeywords - 1;
6537 }
6538
6539 int CSSStyleSelector::legacyFontSize(Document* document, int pixelFontSize, bool shouldUseFixedDefaultSize)
6540 {
6541     Settings* settings = document->settings();
6542     if (!settings)
6543         return 1;
6544
6545     bool quirksMode = document->inQuirksMode();
6546     int mediumSize = shouldUseFixedDefaultSize ? settings->defaultFixedFontSize() : settings->defaultFontSize();
6547     if (mediumSize >= fontSizeTableMin && mediumSize <= fontSizeTableMax) {
6548         int row = mediumSize - fontSizeTableMin;
6549         return findNearestLegacyFontSize<int>(pixelFontSize, quirksMode ? quirksFontSizeTable[row] : strictFontSizeTable[row], 1);
6550     }
6551
6552     return findNearestLegacyFontSize<float>(pixelFontSize, fontSizeFactors, mediumSize);
6553 }
6554
6555 float CSSStyleSelector::largerFontSize(float size, bool) const
6556 {
6557     // FIXME: Figure out where we fall in the size ranges (xx-small to xxx-large) and scale up to
6558     // the next size level.  
6559     return size * 1.2f;
6560 }
6561
6562 float CSSStyleSelector::smallerFontSize(float size, bool) const
6563 {
6564     // FIXME: Figure out where we fall in the size ranges (xx-small to xxx-large) and scale down to
6565     // the next size level. 
6566     return size / 1.2f;
6567 }
6568
6569 static Color colorForCSSValue(int cssValueId)
6570 {
6571     struct ColorValue {
6572         int cssValueId;
6573         RGBA32 color;
6574     };
6575
6576     static const ColorValue colorValues[] = {
6577         { CSSValueAqua, 0xFF00FFFF },
6578         { CSSValueBlack, 0xFF000000 },
6579         { CSSValueBlue, 0xFF0000FF },
6580         { CSSValueFuchsia, 0xFFFF00FF },
6581         { CSSValueGray, 0xFF808080 },
6582         { CSSValueGreen, 0xFF008000  },
6583         { CSSValueGrey, 0xFF808080 },
6584         { CSSValueLime, 0xFF00FF00 },
6585         { CSSValueMaroon, 0xFF800000 },
6586         { CSSValueNavy, 0xFF000080 },
6587         { CSSValueOlive, 0xFF808000  },
6588         { CSSValueOrange, 0xFFFFA500 },
6589         { CSSValuePurple, 0xFF800080 },
6590         { CSSValueRed, 0xFFFF0000 },
6591         { CSSValueSilver, 0xFFC0C0C0 },
6592         { CSSValueTeal, 0xFF008080  },
6593         { CSSValueTransparent, 0x00000000 },
6594         { CSSValueWhite, 0xFFFFFFFF },
6595         { CSSValueYellow, 0xFFFFFF00 },
6596         { 0, 0 }
6597     };
6598
6599     for (const ColorValue* col = colorValues; col->cssValueId; ++col) {
6600         if (col->cssValueId == cssValueId)
6601             return col->color;
6602     }
6603     return RenderTheme::defaultTheme()->systemColor(cssValueId);
6604 }
6605
6606 Color CSSStyleSelector::getColorFromPrimitiveValue(CSSPrimitiveValue* primitiveValue)
6607 {
6608     Color col;
6609     int ident = primitiveValue->getIdent();
6610     if (ident) {
6611         if (ident == CSSValueWebkitText)
6612             col = m_element->document()->textColor();
6613         else if (ident == CSSValueWebkitLink)
6614             col = m_element->isLink() && m_checker.m_matchVisitedPseudoClass ? m_element->document()->visitedLinkColor() : m_element->document()->linkColor();
6615         else if (ident == CSSValueWebkitActivelink)
6616             col = m_element->document()->activeLinkColor();
6617         else if (ident == CSSValueWebkitFocusRingColor)
6618             col = RenderTheme::focusRingColor();
6619         else if (ident == CSSValueCurrentcolor)
6620             col = m_style->color();
6621         else
6622             col = colorForCSSValue(ident);
6623     } else if (primitiveValue->primitiveType() == CSSPrimitiveValue::CSS_RGBCOLOR)
6624         col.setRGB(primitiveValue->getRGBA32Value());
6625     return col;
6626 }
6627
6628 bool CSSStyleSelector::hasSelectorForAttribute(const AtomicString &attrname)
6629 {
6630     return m_selectorAttrs.contains(attrname.impl());
6631 }
6632
6633 void CSSStyleSelector::addViewportDependentMediaQueryResult(const MediaQueryExp* expr, bool result)
6634 {
6635     m_viewportDependentMediaQueryResults.append(new MediaQueryResult(*expr, result));
6636 }
6637
6638 bool CSSStyleSelector::affectedByViewportChange() const
6639 {
6640     unsigned s = m_viewportDependentMediaQueryResults.size();
6641     for (unsigned i = 0; i < s; i++) {
6642         if (m_medium->eval(&m_viewportDependentMediaQueryResults[i]->m_expression) != m_viewportDependentMediaQueryResults[i]->m_result)
6643             return true;
6644     }
6645     return false;
6646 }
6647
6648 void CSSStyleSelector::SelectorChecker::allVisitedStateChanged()
6649 {
6650     if (m_linksCheckedForVisitedState.isEmpty())
6651         return;
6652     for (Node* node = m_document; node; node = node->traverseNextNode()) {
6653         if (node->isLink())
6654             node->setNeedsStyleRecalc();
6655     }
6656 }
6657
6658 void CSSStyleSelector::SelectorChecker::visitedStateChanged(LinkHash visitedHash)
6659 {
6660     if (!m_linksCheckedForVisitedState.contains(visitedHash))
6661         return;
6662     for (Node* node = m_document; node; node = node->traverseNextNode()) {
6663         const AtomicString* attr = linkAttribute(node);
6664         if (attr && visitedLinkHash(m_document->baseURL(), *attr) == visitedHash)
6665             node->setNeedsStyleRecalc();
6666     }
6667 }
6668
6669 static TransformOperation::OperationType getTransformOperationType(WebKitCSSTransformValue::TransformOperationType type)
6670 {
6671     switch (type) {
6672         case WebKitCSSTransformValue::ScaleTransformOperation:          return TransformOperation::SCALE;
6673         case WebKitCSSTransformValue::ScaleXTransformOperation:         return TransformOperation::SCALE_X;
6674         case WebKitCSSTransformValue::ScaleYTransformOperation:         return TransformOperation::SCALE_Y;
6675         case WebKitCSSTransformValue::ScaleZTransformOperation:         return TransformOperation::SCALE_Z;
6676         case WebKitCSSTransformValue::Scale3DTransformOperation:        return TransformOperation::SCALE_3D;
6677         case WebKitCSSTransformValue::TranslateTransformOperation:      return TransformOperation::TRANSLATE;
6678         case WebKitCSSTransformValue::TranslateXTransformOperation:     return TransformOperation::TRANSLATE_X;
6679         case WebKitCSSTransformValue::TranslateYTransformOperation:     return TransformOperation::TRANSLATE_Y;
6680         case WebKitCSSTransformValue::TranslateZTransformOperation:     return TransformOperation::TRANSLATE_Z;
6681         case WebKitCSSTransformValue::Translate3DTransformOperation:    return TransformOperation::TRANSLATE_3D;
6682         case WebKitCSSTransformValue::RotateTransformOperation:         return TransformOperation::ROTATE;
6683         case WebKitCSSTransformValue::RotateXTransformOperation:        return TransformOperation::ROTATE_X;
6684         case WebKitCSSTransformValue::RotateYTransformOperation:        return TransformOperation::ROTATE_Y;
6685         case WebKitCSSTransformValue::RotateZTransformOperation:        return TransformOperation::ROTATE_Z;
6686         case WebKitCSSTransformValue::Rotate3DTransformOperation:       return TransformOperation::ROTATE_3D;
6687         case WebKitCSSTransformValue::SkewTransformOperation:           return TransformOperation::SKEW;
6688         case WebKitCSSTransformValue::SkewXTransformOperation:          return TransformOperation::SKEW_X;
6689         case WebKitCSSTransformValue::SkewYTransformOperation:          return TransformOperation::SKEW_Y;
6690         case WebKitCSSTransformValue::MatrixTransformOperation:         return TransformOperation::MATRIX;
6691         case WebKitCSSTransformValue::Matrix3DTransformOperation:       return TransformOperation::MATRIX_3D;
6692         case WebKitCSSTransformValue::PerspectiveTransformOperation:    return TransformOperation::PERSPECTIVE;
6693         case WebKitCSSTransformValue::UnknownTransformOperation:        return TransformOperation::NONE;
6694     }
6695     return TransformOperation::NONE;
6696 }
6697
6698 bool CSSStyleSelector::createTransformOperations(CSSValue* inValue, RenderStyle* style, RenderStyle* rootStyle, TransformOperations& outOperations)
6699 {
6700     float zoomFactor = style ? style->effectiveZoom() : 1;
6701
6702     TransformOperations operations;
6703     if (inValue && !inValue->isPrimitiveValue()) {
6704         CSSValueList* list = static_cast<CSSValueList*>(inValue);
6705         unsigned size = list->length();
6706         for (unsigned i = 0; i < size; i++) {
6707             WebKitCSSTransformValue* val = static_cast<WebKitCSSTransformValue*>(list->itemWithoutBoundsCheck(i));
6708             
6709             CSSPrimitiveValue* firstValue = static_cast<CSSPrimitiveValue*>(val->itemWithoutBoundsCheck(0));
6710              
6711             switch (val->operationType()) {
6712                 case WebKitCSSTransformValue::ScaleTransformOperation:
6713                 case WebKitCSSTransformValue::ScaleXTransformOperation:
6714                 case WebKitCSSTransformValue::ScaleYTransformOperation: {
6715                     double sx = 1.0;
6716                     double sy = 1.0;
6717                     if (val->operationType() == WebKitCSSTransformValue::ScaleYTransformOperation)
6718                         sy = firstValue->getDoubleValue();
6719                     else { 
6720                         sx = firstValue->getDoubleValue();
6721                         if (val->operationType() != WebKitCSSTransformValue::ScaleXTransformOperation) {
6722                             if (val->length() > 1) {
6723                                 CSSPrimitiveValue* secondValue = static_cast<CSSPrimitiveValue*>(val->itemWithoutBoundsCheck(1));
6724                                 sy = secondValue->getDoubleValue();
6725                             } else 
6726                                 sy = sx;
6727                         }
6728                     }
6729                     operations.operations().append(ScaleTransformOperation::create(sx, sy, 1.0, getTransformOperationType(val->operationType())));
6730                     break;
6731                 }
6732                 case WebKitCSSTransformValue::ScaleZTransformOperation:
6733                 case WebKitCSSTransformValue::Scale3DTransformOperation: {
6734                     double sx = 1.0;
6735                     double sy = 1.0;
6736                     double sz = 1.0;
6737                     if (val->operationType() == WebKitCSSTransformValue::ScaleZTransformOperation)
6738                         sz = firstValue->getDoubleValue();
6739                     else if (val->operationType() == WebKitCSSTransformValue::ScaleYTransformOperation)
6740                         sy = firstValue->getDoubleValue();
6741                     else { 
6742                         sx = firstValue->getDoubleValue();
6743                         if (val->operationType() != WebKitCSSTransformValue::ScaleXTransformOperation) {
6744                             if (val->length() > 2) {
6745                                 CSSPrimitiveValue* thirdValue = static_cast<CSSPrimitiveValue*>(val->itemWithoutBoundsCheck(2));
6746                                 sz = thirdValue->getDoubleValue();
6747                             }
6748                             if (val->length() > 1) {
6749                                 CSSPrimitiveValue* secondValue = static_cast<CSSPrimitiveValue*>(val->itemWithoutBoundsCheck(1));
6750                                 sy = secondValue->getDoubleValue();
6751                             } else 
6752                                 sy = sx;
6753                         }
6754                     }
6755                     operations.operations().append(ScaleTransformOperation::create(sx, sy, sz, getTransformOperationType(val->operationType())));
6756                     break;
6757                 }
6758                 case WebKitCSSTransformValue::TranslateTransformOperation:
6759                 case WebKitCSSTransformValue::TranslateXTransformOperation:
6760                 case WebKitCSSTransformValue::TranslateYTransformOperation: {
6761                     bool ok = true;
6762                     Length tx = Length(0, Fixed);
6763                     Length ty = Length(0, Fixed);
6764                     if (val->operationType() == WebKitCSSTransformValue::TranslateYTransformOperation)
6765                         ty = convertToLength(firstValue, style, rootStyle, zoomFactor, &ok);
6766                     else { 
6767                         tx = convertToLength(firstValue, style, rootStyle, zoomFactor, &ok);
6768                         if (val->operationType() != WebKitCSSTransformValue::TranslateXTransformOperation) {
6769                             if (val->length() > 1) {
6770                                 CSSPrimitiveValue* secondValue = static_cast<CSSPrimitiveValue*>(val->itemWithoutBoundsCheck(1));
6771                                 ty = convertToLength(secondValue, style, rootStyle, zoomFactor, &ok);
6772                             }
6773                         }
6774                     }
6775
6776                     if (!ok)
6777                         return false;
6778
6779                     operations.operations().append(TranslateTransformOperation::create(tx, ty, Length(0, Fixed), getTransformOperationType(val->operationType())));
6780                     break;
6781                 }
6782                 case WebKitCSSTransformValue::TranslateZTransformOperation:
6783                 case WebKitCSSTransformValue::Translate3DTransformOperation: {
6784                     bool ok = true;
6785                     Length tx = Length(0, Fixed);
6786                     Length ty = Length(0, Fixed);
6787                     Length tz = Length(0, Fixed);
6788                     if (val->operationType() == WebKitCSSTransformValue::TranslateZTransformOperation)
6789                         tz = convertToLength(firstValue, style, rootStyle, zoomFactor, &ok);
6790                     else if (val->operationType() == WebKitCSSTransformValue::TranslateYTransformOperation)
6791                         ty = convertToLength(firstValue, style, rootStyle, zoomFactor, &ok);
6792                     else { 
6793                         tx = convertToLength(firstValue, style, rootStyle, zoomFactor, &ok);
6794                         if (val->operationType() != WebKitCSSTransformValue::TranslateXTransformOperation) {
6795                             if (val->length() > 2) {
6796                                 CSSPrimitiveValue* thirdValue = static_cast<CSSPrimitiveValue*>(val->itemWithoutBoundsCheck(2));
6797                                 tz = convertToLength(thirdValue, style, rootStyle, zoomFactor, &ok);
6798                             }
6799                             if (val->length() > 1) {
6800                                 CSSPrimitiveValue* secondValue = static_cast<CSSPrimitiveValue*>(val->itemWithoutBoundsCheck(1));
6801                                 ty = convertToLength(secondValue, style, rootStyle, zoomFactor, &ok);
6802                             }
6803                         }
6804                     }
6805
6806                     if (!ok)
6807                         return false;
6808
6809                     operations.operations().append(TranslateTransformOperation::create(tx, ty, tz, getTransformOperationType(val->operationType())));
6810                     break;
6811                 }
6812                 case WebKitCSSTransformValue::RotateTransformOperation: {
6813                     double angle = firstValue->getDoubleValue();
6814                     if (firstValue->primitiveType() == CSSPrimitiveValue::CSS_RAD)
6815                         angle = rad2deg(angle);
6816                     else if (firstValue->primitiveType() == CSSPrimitiveValue::CSS_GRAD)
6817                         angle = grad2deg(angle);
6818                     else if (firstValue->primitiveType() == CSSPrimitiveValue::CSS_TURN)
6819                         angle = turn2deg(angle);
6820                     
6821                     operations.operations().append(RotateTransformOperation::create(0, 0, 1, angle, getTransformOperationType(val->operationType())));
6822                     break;
6823                 }
6824                 case WebKitCSSTransformValue::RotateXTransformOperation:
6825                 case WebKitCSSTransformValue::RotateYTransformOperation:
6826                 case WebKitCSSTransformValue::RotateZTransformOperation: {
6827                     double x = 0;
6828                     double y = 0;
6829                     double z = 0;
6830                     double angle = firstValue->getDoubleValue();
6831                     if (firstValue->primitiveType() == CSSPrimitiveValue::CSS_RAD)
6832                         angle = rad2deg(angle);
6833                     else if (firstValue->primitiveType() == CSSPrimitiveValue::CSS_GRAD)
6834                         angle = grad2deg(angle);
6835                     
6836                     if (val->operationType() == WebKitCSSTransformValue::RotateXTransformOperation)
6837                         x = 1;
6838                     else if (val->operationType() == WebKitCSSTransformValue::RotateYTransformOperation)
6839                         y = 1;
6840                     else
6841                         z = 1;
6842                     operations.operations().append(RotateTransformOperation::create(x, y, z, angle, getTransformOperationType(val->operationType())));
6843                     break;
6844                 }
6845                 case WebKitCSSTransformValue::Rotate3DTransformOperation: {
6846                     CSSPrimitiveValue* secondValue = static_cast<CSSPrimitiveValue*>(val->itemWithoutBoundsCheck(1));
6847                     CSSPrimitiveValue* thirdValue = static_cast<CSSPrimitiveValue*>(val->itemWithoutBoundsCheck(2));
6848                     CSSPrimitiveValue* fourthValue = static_cast<CSSPrimitiveValue*>(val->itemWithoutBoundsCheck(3));
6849                     double x = firstValue->getDoubleValue();
6850                     double y = secondValue->getDoubleValue();
6851                     double z = thirdValue->getDoubleValue();
6852                     double angle = fourthValue->getDoubleValue();
6853                     if (fourthValue->primitiveType() == CSSPrimitiveValue::CSS_RAD)
6854                         angle = rad2deg(angle);
6855                     else if (fourthValue->primitiveType() == CSSPrimitiveValue::CSS_GRAD)
6856                         angle = grad2deg(angle);
6857                     operations.operations().append(RotateTransformOperation::create(x, y, z, angle, getTransformOperationType(val->operationType())));
6858                     break;
6859                 }
6860                 case WebKitCSSTransformValue::SkewTransformOperation:
6861                 case WebKitCSSTransformValue::SkewXTransformOperation:
6862                 case WebKitCSSTransformValue::SkewYTransformOperation: {
6863                     double angleX = 0;
6864                     double angleY = 0;
6865                     double angle = firstValue->getDoubleValue();
6866                     if (firstValue->primitiveType() == CSSPrimitiveValue::CSS_RAD)
6867                         angle = rad2deg(angle);
6868                     else if (firstValue->primitiveType() == CSSPrimitiveValue::CSS_GRAD)
6869                         angle = grad2deg(angle);
6870                     else if (firstValue->primitiveType() == CSSPrimitiveValue::CSS_TURN)
6871                         angle = turn2deg(angle);
6872                     if (val->operationType() == WebKitCSSTransformValue::SkewYTransformOperation)
6873                         angleY = angle;
6874                     else {
6875                         angleX = angle;
6876                         if (val->operationType() == WebKitCSSTransformValue::SkewTransformOperation) {
6877                             if (val->length() > 1) {
6878                                 CSSPrimitiveValue* secondValue = static_cast<CSSPrimitiveValue*>(val->itemWithoutBoundsCheck(1));
6879                                 angleY = secondValue->getDoubleValue();
6880                                 if (secondValue->primitiveType() == CSSPrimitiveValue::CSS_RAD)
6881                                     angleY = rad2deg(angleY);
6882                                 else if (secondValue->primitiveType() == CSSPrimitiveValue::CSS_GRAD)
6883                                     angleY = grad2deg(angleY);
6884                                 else if (secondValue->primitiveType() == CSSPrimitiveValue::CSS_TURN)
6885                                     angleY = turn2deg(angleY);
6886                             }
6887                         }
6888                     }
6889                     operations.operations().append(SkewTransformOperation::create(angleX, angleY, getTransformOperationType(val->operationType())));
6890                     break;
6891                 }
6892                 case WebKitCSSTransformValue::MatrixTransformOperation: {
6893                     double a = firstValue->getDoubleValue();
6894                     double b = static_cast<CSSPrimitiveValue*>(val->itemWithoutBoundsCheck(1))->getDoubleValue();
6895                     double c = static_cast<CSSPrimitiveValue*>(val->itemWithoutBoundsCheck(2))->getDoubleValue();
6896                     double d = static_cast<CSSPrimitiveValue*>(val->itemWithoutBoundsCheck(3))->getDoubleValue();
6897                     double e = static_cast<CSSPrimitiveValue*>(val->itemWithoutBoundsCheck(4))->getDoubleValue();
6898                     double f = static_cast<CSSPrimitiveValue*>(val->itemWithoutBoundsCheck(5))->getDoubleValue();
6899                     operations.operations().append(MatrixTransformOperation::create(a, b, c, d, e, f));
6900                     break;
6901                 }
6902                 case WebKitCSSTransformValue::Matrix3DTransformOperation: {
6903                     TransformationMatrix matrix(static_cast<CSSPrimitiveValue*>(val->itemWithoutBoundsCheck(0))->getDoubleValue(),
6904                                        static_cast<CSSPrimitiveValue*>(val->itemWithoutBoundsCheck(1))->getDoubleValue(),
6905                                        static_cast<CSSPrimitiveValue*>(val->itemWithoutBoundsCheck(2))->getDoubleValue(),
6906                                        static_cast<CSSPrimitiveValue*>(val->itemWithoutBoundsCheck(3))->getDoubleValue(),
6907                                        static_cast<CSSPrimitiveValue*>(val->itemWithoutBoundsCheck(4))->getDoubleValue(),
6908                                        static_cast<CSSPrimitiveValue*>(val->itemWithoutBoundsCheck(5))->getDoubleValue(),
6909                                        static_cast<CSSPrimitiveValue*>(val->itemWithoutBoundsCheck(6))->getDoubleValue(),
6910                                        static_cast<CSSPrimitiveValue*>(val->itemWithoutBoundsCheck(7))->getDoubleValue(),
6911                                        static_cast<CSSPrimitiveValue*>(val->itemWithoutBoundsCheck(8))->getDoubleValue(),
6912                                        static_cast<CSSPrimitiveValue*>(val->itemWithoutBoundsCheck(9))->getDoubleValue(),
6913                                        static_cast<CSSPrimitiveValue*>(val->itemWithoutBoundsCheck(10))->getDoubleValue(),
6914                                        static_cast<CSSPrimitiveValue*>(val->itemWithoutBoundsCheck(11))->getDoubleValue(),
6915                                        static_cast<CSSPrimitiveValue*>(val->itemWithoutBoundsCheck(12))->getDoubleValue(),
6916                                        static_cast<CSSPrimitiveValue*>(val->itemWithoutBoundsCheck(13))->getDoubleValue(),
6917                                        static_cast<CSSPrimitiveValue*>(val->itemWithoutBoundsCheck(14))->getDoubleValue(),
6918                                        static_cast<CSSPrimitiveValue*>(val->itemWithoutBoundsCheck(15))->getDoubleValue());
6919                     operations.operations().append(Matrix3DTransformOperation::create(matrix));
6920                     break;
6921                 }   
6922                 case WebKitCSSTransformValue::PerspectiveTransformOperation: {
6923                     double p = firstValue->getDoubleValue();
6924                     if (p < 0.0)
6925                         return false;
6926                     operations.operations().append(PerspectiveTransformOperation::create(p));
6927                     break;
6928                 }
6929                 case WebKitCSSTransformValue::UnknownTransformOperation:
6930                     ASSERT_NOT_REACHED();
6931                     break;
6932             }
6933         }
6934     }
6935     outOperations = operations;
6936     return true;
6937 }
6938
6939 void CSSStyleSelector::loadPendingImages()
6940 {
6941     if (m_pendingImageProperties.isEmpty())
6942         return;
6943         
6944     HashSet<int>::const_iterator end = m_pendingImageProperties.end();
6945     for (HashSet<int>::const_iterator it = m_pendingImageProperties.begin(); it != end; ++it) {
6946         CSSPropertyID currentProperty = static_cast<CSSPropertyID>(*it);
6947
6948         CachedResourceLoader* cachedResourceLoader = m_element->document()->cachedResourceLoader();
6949         
6950         switch (currentProperty) {
6951             case CSSPropertyBackgroundImage: {
6952                 for (FillLayer* backgroundLayer = m_style->accessBackgroundLayers(); backgroundLayer; backgroundLayer = backgroundLayer->next()) {
6953                     if (backgroundLayer->image() && backgroundLayer->image()->isPendingImage()) {
6954                         CSSImageValue* imageValue = static_cast<StylePendingImage*>(backgroundLayer->image())->cssImageValue();
6955                         backgroundLayer->setImage(imageValue->cachedImage(cachedResourceLoader));
6956                     }
6957                 }
6958                 break;
6959             }
6960
6961             case CSSPropertyContent: {
6962                 for (ContentData* contentData = const_cast<ContentData*>(m_style->contentData()); contentData; contentData = contentData->next()) {
6963                     if (contentData->isImage() && contentData->image()->isPendingImage()) {
6964                         CSSImageValue* imageValue = static_cast<StylePendingImage*>(contentData->image())->cssImageValue();
6965                         if (StyleCachedImage* cachedImage = imageValue->cachedImage(cachedResourceLoader))
6966                             contentData->setImage(cachedImage);
6967                     }
6968                 }
6969                 break;
6970             }
6971
6972             case CSSPropertyCursor: {
6973                 if (CursorList* cursorList = m_style->cursors()) {
6974                     for (size_t i = 0; i < cursorList->size(); ++i) {
6975                         CursorData& currentCursor = (*cursorList)[i];
6976                         if (currentCursor.image()->isPendingImage()) {
6977                             CSSImageValue* imageValue = static_cast<StylePendingImage*>(currentCursor.image())->cssImageValue();
6978                             currentCursor.setImage(imageValue->cachedImage(cachedResourceLoader));
6979                         }
6980                     }
6981                 }
6982                 break;
6983             }
6984
6985             case CSSPropertyListStyleImage: {
6986                 if (m_style->listStyleImage() && m_style->listStyleImage()->isPendingImage()) {
6987                     CSSImageValue* imageValue = static_cast<StylePendingImage*>(m_style->listStyleImage())->cssImageValue();
6988                     m_style->setListStyleImage(imageValue->cachedImage(cachedResourceLoader));
6989                 }
6990                 break;
6991             }
6992
6993             case CSSPropertyWebkitBorderImage: {
6994                 const NinePieceImage& borderImage = m_style->borderImage();
6995                 if (borderImage.image() && borderImage.image()->isPendingImage()) {
6996                     CSSImageValue* imageValue = static_cast<StylePendingImage*>(borderImage.image())->cssImageValue();
6997                     m_style->setBorderImage(NinePieceImage(imageValue->cachedImage(cachedResourceLoader), borderImage.slices(), borderImage.horizontalRule(), borderImage.verticalRule()));
6998                 }
6999                 break;
7000             }
7001             
7002             case CSSPropertyWebkitBoxReflect: {
7003                 const NinePieceImage& maskImage = m_style->boxReflect()->mask();
7004                 if (maskImage.image() && maskImage.image()->isPendingImage()) {
7005                     CSSImageValue* imageValue = static_cast<StylePendingImage*>(maskImage.image())->cssImageValue();
7006                     m_style->boxReflect()->setMask(NinePieceImage(imageValue->cachedImage(cachedResourceLoader), maskImage.slices(), maskImage.horizontalRule(), maskImage.verticalRule()));
7007                 }
7008                 break;
7009             }
7010
7011             case CSSPropertyWebkitMaskBoxImage: {
7012                 const NinePieceImage& maskBoxImage = m_style->maskBoxImage();
7013                 if (maskBoxImage.image() && maskBoxImage.image()->isPendingImage()) {
7014                     CSSImageValue* imageValue = static_cast<StylePendingImage*>(maskBoxImage.image())->cssImageValue();
7015                     m_style->setMaskBoxImage(NinePieceImage(imageValue->cachedImage(cachedResourceLoader), maskBoxImage.slices(), maskBoxImage.horizontalRule(), maskBoxImage.verticalRule()));
7016                 }
7017                 break;
7018             }
7019             
7020             case CSSPropertyWebkitMaskImage: {
7021                 for (FillLayer* maskLayer = m_style->accessMaskLayers(); maskLayer; maskLayer = maskLayer->next()) {
7022                     if (maskLayer->image() && maskLayer->image()->isPendingImage()) {
7023                         CSSImageValue* imageValue = static_cast<StylePendingImage*>(maskLayer->image())->cssImageValue();
7024                         maskLayer->setImage(imageValue->cachedImage(cachedResourceLoader));
7025                     }
7026                 }
7027                 break;
7028             }
7029             default:
7030                 ASSERT_NOT_REACHED();
7031         }
7032     }
7033
7034     m_pendingImageProperties.clear();
7035 }
7036
7037 } // namespace WebCore