452ed1d1c141739824605c7ae7ef70dfb13fd125
[WebKit-https.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 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 "CounterContent.h"
53 #include "FocusController.h"
54 #include "FontFamilyValue.h"
55 #include "FontValue.h"
56 #include "Frame.h"
57 #include "FrameView.h"
58 #include "HTMLDocument.h"
59 #include "HTMLElement.h"
60 #include "HTMLInputElement.h"
61 #include "HTMLNames.h"
62 #include "HTMLTextAreaElement.h"
63 #include "KeyframeList.h"
64 #include "LinkHash.h"
65 #include "Matrix3DTransformOperation.h"
66 #include "MatrixTransformOperation.h"
67 #include "MediaList.h"
68 #include "MediaQueryEvaluator.h"
69 #include "NodeRenderStyle.h"
70 #include "Page.h"
71 #include "PageGroup.h"
72 #include "Pair.h"
73 #include "PerspectiveTransformOperation.h"
74 #include "Rect.h"
75 #include "RenderScrollbar.h"
76 #include "RenderScrollbarTheme.h"
77 #include "RenderStyleConstants.h"
78 #include "RenderTheme.h"
79 #include "RotateTransformOperation.h"
80 #include "ScaleTransformOperation.h"
81 #include "SelectionController.h"
82 #include "Settings.h"
83 #include "ShadowValue.h"
84 #include "SkewTransformOperation.h"
85 #include "StyleCachedImage.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 ENABLE(DASHBOARD_SUPPORT)
101 #include "DashboardRegion.h"
102 #endif
103
104 #if ENABLE(SVG)
105 #include "XLinkNames.h"
106 #include "SVGNames.h"
107 #endif
108
109 #if ENABLE(WML)
110 #include "WMLNames.h"
111 #endif
112
113 #if PLATFORM(QT)
114 #include <qwebhistoryinterface.h>
115 #endif
116
117 using namespace std;
118
119 namespace WebCore {
120
121 using namespace HTMLNames;
122
123 // #define STYLE_SHARING_STATS 1
124
125 #define HANDLE_INHERIT(prop, Prop) \
126 if (isInherit) { \
127     m_style->set##Prop(m_parentStyle->prop()); \
128     return; \
129 }
130
131 #define HANDLE_INHERIT_AND_INITIAL(prop, Prop) \
132 HANDLE_INHERIT(prop, Prop) \
133 if (isInitial) { \
134     m_style->set##Prop(RenderStyle::initial##Prop()); \
135     return; \
136 }
137
138 #define HANDLE_INHERIT_AND_INITIAL_WITH_VALUE(prop, Prop, Value) \
139 HANDLE_INHERIT(prop, Prop) \
140 if (isInitial) { \
141     m_style->set##Prop(RenderStyle::initial##Value());\
142     return;\
143 }
144
145 #define HANDLE_INHERIT_AND_INITIAL_AND_PRIMITIVE(prop, Prop) \
146 HANDLE_INHERIT_AND_INITIAL(prop, Prop) \
147 if (primitiveValue) \
148     m_style->set##Prop(*primitiveValue);
149
150 #define HANDLE_INHERIT_AND_INITIAL_AND_PRIMITIVE_WITH_VALUE(prop, Prop, Value) \
151 HANDLE_INHERIT_AND_INITIAL_WITH_VALUE(prop, Prop, Value) \
152 if (primitiveValue) \
153     m_style->set##Prop(*primitiveValue);
154
155 #define HANDLE_FILL_LAYER_INHERIT_AND_INITIAL(layerType, LayerType, prop, Prop) \
156 if (isInherit) { \
157     FillLayer* currChild = m_style->access##LayerType##Layers(); \
158     FillLayer* prevChild = 0; \
159     const FillLayer* currParent = m_parentStyle->layerType##Layers(); \
160     while (currParent && currParent->is##Prop##Set()) { \
161         if (!currChild) { \
162             /* Need to make a new layer.*/ \
163             currChild = new FillLayer(LayerType##FillLayer); \
164             prevChild->setNext(currChild); \
165         } \
166         currChild->set##Prop(currParent->prop()); \
167         prevChild = currChild; \
168         currChild = prevChild->next(); \
169         currParent = currParent->next(); \
170     } \
171     \
172     while (currChild) { \
173         /* Reset any remaining layers to not have the property set. */ \
174         currChild->clear##Prop(); \
175         currChild = currChild->next(); \
176     } \
177 } else if (isInitial) { \
178     FillLayer* currChild = m_style->access##LayerType##Layers(); \
179     currChild->set##Prop(FillLayer::initialFill##Prop(LayerType##FillLayer)); \
180     for (currChild = currChild->next(); currChild; currChild = currChild->next()) \
181         currChild->clear##Prop(); \
182 }
183
184 #define HANDLE_FILL_LAYER_VALUE(layerType, LayerType, prop, Prop, value) { \
185 HANDLE_FILL_LAYER_INHERIT_AND_INITIAL(layerType, LayerType, prop, Prop) \
186 if (isInherit || isInitial) \
187     return; \
188 FillLayer* currChild = m_style->access##LayerType##Layers(); \
189 FillLayer* prevChild = 0; \
190 if (value->isValueList()) { \
191     /* Walk each value and put it into a layer, creating new layers as needed. */ \
192     CSSValueList* valueList = static_cast<CSSValueList*>(value); \
193     for (unsigned int i = 0; i < valueList->length(); i++) { \
194         if (!currChild) { \
195             /* Need to make a new layer to hold this value */ \
196             currChild = new FillLayer(LayerType##FillLayer); \
197             prevChild->setNext(currChild); \
198         } \
199         mapFill##Prop(currChild, valueList->itemWithoutBoundsCheck(i)); \
200         prevChild = currChild; \
201         currChild = currChild->next(); \
202     } \
203 } else { \
204     mapFill##Prop(currChild, value); \
205     currChild = currChild->next(); \
206 } \
207 while (currChild) { \
208     /* Reset all remaining layers to not have the property set. */ \
209     currChild->clear##Prop(); \
210     currChild = currChild->next(); \
211 } }
212
213 #define HANDLE_BACKGROUND_INHERIT_AND_INITIAL(prop, Prop) \
214 HANDLE_FILL_LAYER_INHERIT_AND_INITIAL(background, Background, prop, Prop)
215
216 #define HANDLE_BACKGROUND_VALUE(prop, Prop, value) \
217 HANDLE_FILL_LAYER_VALUE(background, Background, prop, Prop, value)
218
219 #define HANDLE_MASK_INHERIT_AND_INITIAL(prop, Prop) \
220 HANDLE_FILL_LAYER_INHERIT_AND_INITIAL(mask, Mask, prop, Prop)
221
222 #define HANDLE_MASK_VALUE(prop, Prop, value) \
223 HANDLE_FILL_LAYER_VALUE(mask, Mask, prop, Prop, value)
224
225 #define HANDLE_ANIMATION_INHERIT_AND_INITIAL(prop, Prop) \
226 if (isInherit) { \
227     AnimationList* list = m_style->accessAnimations(); \
228     const AnimationList* parentList = m_parentStyle->animations(); \
229     size_t i = 0, parentSize = parentList ? parentList->size() : 0; \
230     for ( ; i < parentSize && parentList->animation(i)->is##Prop##Set(); ++i) { \
231         if (list->size() <= i) \
232             list->append(Animation::create()); \
233         list->animation(i)->set##Prop(parentList->animation(i)->prop()); \
234     } \
235     \
236     /* Reset any remaining animations to not have the property set. */ \
237     for ( ; i < list->size(); ++i) \
238         list->animation(i)->clear##Prop(); \
239 } else if (isInitial) { \
240     AnimationList* list = m_style->accessAnimations(); \
241     if (list->isEmpty()) \
242         list->append(Animation::create()); \
243     list->animation(0)->set##Prop(Animation::initialAnimation##Prop()); \
244     for (size_t i = 1; i < list->size(); ++i) \
245         list->animation(0)->clear##Prop(); \
246 }
247
248 #define HANDLE_ANIMATION_VALUE(prop, Prop, value) { \
249 HANDLE_ANIMATION_INHERIT_AND_INITIAL(prop, Prop) \
250 if (isInherit || isInitial) \
251     return; \
252 AnimationList* list = m_style->accessAnimations(); \
253 size_t childIndex = 0; \
254 if (value->isValueList()) { \
255     /* Walk each value and put it into an animation, creating new animations as needed. */ \
256     CSSValueList* valueList = static_cast<CSSValueList*>(value); \
257     for (unsigned int i = 0; i < valueList->length(); i++) { \
258         if (childIndex <= list->size()) \
259             list->append(Animation::create()); \
260         mapAnimation##Prop(list->animation(childIndex), valueList->itemWithoutBoundsCheck(i)); \
261         ++childIndex; \
262     } \
263 } else { \
264     if (list->isEmpty()) \
265         list->append(Animation::create()); \
266     mapAnimation##Prop(list->animation(childIndex), value); \
267     childIndex = 1; \
268 } \
269 for ( ; childIndex < list->size(); ++childIndex) { \
270     /* Reset all remaining animations to not have the property set. */ \
271     list->animation(childIndex)->clear##Prop(); \
272 } \
273 }
274
275 #define HANDLE_TRANSITION_INHERIT_AND_INITIAL(prop, Prop) \
276 if (isInherit) { \
277     AnimationList* list = m_style->accessTransitions(); \
278     const AnimationList* parentList = m_parentStyle->transitions(); \
279     size_t i = 0, parentSize = parentList ? parentList->size() : 0; \
280     for ( ; i < parentSize && parentList->animation(i)->is##Prop##Set(); ++i) { \
281         if (list->size() <= i) \
282             list->append(Animation::create()); \
283         list->animation(i)->set##Prop(parentList->animation(i)->prop()); \
284     } \
285     \
286     /* Reset any remaining transitions to not have the property set. */ \
287     for ( ; i < list->size(); ++i) \
288         list->animation(i)->clear##Prop(); \
289 } else if (isInitial) { \
290     AnimationList* list = m_style->accessTransitions(); \
291     if (list->isEmpty()) \
292         list->append(Animation::create()); \
293     list->animation(0)->set##Prop(Animation::initialAnimation##Prop()); \
294     for (size_t i = 1; i < list->size(); ++i) \
295         list->animation(0)->clear##Prop(); \
296 }
297
298 #define HANDLE_TRANSITION_VALUE(prop, Prop, value) { \
299 HANDLE_TRANSITION_INHERIT_AND_INITIAL(prop, Prop) \
300 if (isInherit || isInitial) \
301     return; \
302 AnimationList* list = m_style->accessTransitions(); \
303 size_t childIndex = 0; \
304 if (value->isValueList()) { \
305     /* Walk each value and put it into a transition, creating new animations as needed. */ \
306     CSSValueList* valueList = static_cast<CSSValueList*>(value); \
307     for (unsigned int i = 0; i < valueList->length(); i++) { \
308         if (childIndex <= list->size()) \
309             list->append(Animation::create()); \
310         mapAnimation##Prop(list->animation(childIndex), valueList->itemWithoutBoundsCheck(i)); \
311         ++childIndex; \
312     } \
313 } else { \
314     if (list->isEmpty()) \
315         list->append(Animation::create()); \
316     mapAnimation##Prop(list->animation(childIndex), value); \
317     childIndex = 1; \
318 } \
319 for ( ; childIndex < list->size(); ++childIndex) { \
320     /* Reset all remaining transitions to not have the property set. */ \
321     list->animation(childIndex)->clear##Prop(); \
322 } \
323 }
324
325 #define HANDLE_INHERIT_COND(propID, prop, Prop) \
326 if (id == propID) { \
327     m_style->set##Prop(m_parentStyle->prop()); \
328     return; \
329 }
330     
331 #define HANDLE_INHERIT_COND_WITH_BACKUP(propID, prop, propAlt, Prop) \
332 if (id == propID) { \
333     if (m_parentStyle->prop().isValid()) \
334         m_style->set##Prop(m_parentStyle->prop()); \
335     else \
336         m_style->set##Prop(m_parentStyle->propAlt()); \
337     return; \
338 }
339
340 #define HANDLE_INITIAL_COND(propID, Prop) \
341 if (id == propID) { \
342     m_style->set##Prop(RenderStyle::initial##Prop()); \
343     return; \
344 }
345
346 #define HANDLE_INITIAL_COND_WITH_VALUE(propID, Prop, Value) \
347 if (id == propID) { \
348     m_style->set##Prop(RenderStyle::initial##Value()); \
349     return; \
350 }
351
352 class CSSRuleSet : public Noncopyable {
353 public:
354     CSSRuleSet();
355     ~CSSRuleSet();
356     
357     typedef HashMap<AtomicStringImpl*, CSSRuleDataList*> AtomRuleMap;
358     
359     void addRulesFromSheet(CSSStyleSheet*, const MediaQueryEvaluator&, CSSStyleSelector* = 0);
360     
361     void addRule(CSSStyleRule* rule, CSSSelector* sel);
362     void addPageRule(CSSStyleRule* rule, CSSSelector* sel);
363     void addToRuleSet(AtomicStringImpl* key, AtomRuleMap& map,
364                       CSSStyleRule* rule, CSSSelector* sel);
365     
366     CSSRuleDataList* getIDRules(AtomicStringImpl* key) { return m_idRules.get(key); }
367     CSSRuleDataList* getClassRules(AtomicStringImpl* key) { return m_classRules.get(key); }
368     CSSRuleDataList* getTagRules(AtomicStringImpl* key) { return m_tagRules.get(key); }
369     CSSRuleDataList* getUniversalRules() { return m_universalRules; }
370     CSSRuleDataList* getPageRules() { return m_pageRules; }
371     
372 public:
373     AtomRuleMap m_idRules;
374     AtomRuleMap m_classRules;
375     AtomRuleMap m_tagRules;
376     CSSRuleDataList* m_universalRules;
377     CSSRuleDataList* m_pageRules;
378     unsigned m_ruleCount;
379     unsigned m_pageRuleCount;
380 };
381
382 static CSSRuleSet* defaultStyle;
383 static CSSRuleSet* defaultQuirksStyle;
384 static CSSRuleSet* defaultPrintStyle;
385 static CSSRuleSet* defaultViewSourceStyle;
386 static CSSStyleSheet* simpleDefaultStyleSheet;
387
388 RenderStyle* CSSStyleSelector::s_styleNotYetAvailable;
389
390 static void loadFullDefaultStyle();
391 static void loadSimpleDefaultStyle();
392 // FIXME: It would be nice to use some mechanism that guarantees this is in sync with the real UA stylesheet.
393 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}";
394
395 static bool elementCanUseSimpleDefaultStyle(Element* e)
396 {
397     return e->hasTagName(htmlTag) || e->hasTagName(bodyTag) || e->hasTagName(divTag) || e->hasTagName(spanTag) || e->hasTagName(brTag) || e->hasTagName(aTag);
398 }
399
400 static const MediaQueryEvaluator& screenEval()
401 {
402     DEFINE_STATIC_LOCAL(const MediaQueryEvaluator, staticScreenEval, ("screen"));
403     return staticScreenEval;
404 }
405
406 static const MediaQueryEvaluator& printEval()
407 {
408     DEFINE_STATIC_LOCAL(const MediaQueryEvaluator, staticPrintEval, ("print"));
409     return staticPrintEval;
410 }
411
412 CSSStyleSelector::CSSStyleSelector(Document* doc, StyleSheetList* styleSheets, CSSStyleSheet* mappedElementSheet,
413                                    CSSStyleSheet* pageUserSheet, const Vector<RefPtr<CSSStyleSheet> >* pageGroupUserSheets,
414                                    bool strictParsing, bool matchAuthorAndUserStyles)
415     : m_backgroundData(BackgroundFillLayer)
416     , m_checker(doc, strictParsing)
417     , m_element(0)
418     , m_styledElement(0)
419     , m_elementLinkState(NotInsideLink)
420     , m_fontSelector(CSSFontSelector::create(doc))
421 {
422     init();
423         
424     m_matchAuthorAndUserStyles = matchAuthorAndUserStyles;
425     
426     Element* root = doc->documentElement();
427
428     if (!defaultStyle) {
429         if (!root || elementCanUseSimpleDefaultStyle(root))
430             loadSimpleDefaultStyle();
431         else
432             loadFullDefaultStyle();
433     }
434
435     m_userStyle = 0;
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 = doc->view();
444     if (view)
445         m_medium = new MediaQueryEvaluator(view->mediaType());
446     else
447         m_medium = 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         delete m_medium;
454         m_medium = new MediaQueryEvaluator(view->mediaType(), view->frame(), m_rootDefaultStyle.get());
455     }
456
457     // FIXME: This sucks! The user sheet is reparsed every time!
458     if (pageUserSheet || pageGroupUserSheets) {
459         m_userStyle = new CSSRuleSet();
460         if (pageUserSheet)
461             m_userStyle->addRulesFromSheet(pageUserSheet, *m_medium, this);
462         if (pageGroupUserSheets) {
463             unsigned length = pageGroupUserSheets->size();
464             for (unsigned i = 0; i < length; i++)
465                 m_userStyle->addRulesFromSheet(pageGroupUserSheets->at(i).get(), *m_medium, this);
466         }
467     }
468
469     // add stylesheets from document
470     m_authorStyle = new CSSRuleSet();
471     
472     // Add rules from elements like SVG's <font-face>
473     if (mappedElementSheet)
474         m_authorStyle->addRulesFromSheet(mappedElementSheet, *m_medium, this);
475
476     unsigned length = styleSheets->length();
477     for (unsigned i = 0; i < length; i++) {
478         StyleSheet* sheet = styleSheets->item(i);
479         if (sheet->isCSSStyleSheet() && !sheet->disabled())
480             m_authorStyle->addRulesFromSheet(static_cast<CSSStyleSheet*>(sheet), *m_medium, this);
481     }
482     
483     if (doc->renderer() && doc->renderer()->style())
484         doc->renderer()->style()->font().update(fontSelector());
485 }
486
487 // This is a simplified style setting function for keyframe styles
488 void CSSStyleSelector::addKeyframeStyle(PassRefPtr<WebKitCSSKeyframesRule> rule)
489 {
490     AtomicString s(rule->name());
491     m_keyframesRuleMap.add(s.impl(), rule);
492 }
493
494 void CSSStyleSelector::init()
495 {
496     initElement(0);
497     m_matchedDecls.clear();
498     m_ruleList = 0;
499     m_rootDefaultStyle = 0;
500     m_medium = 0;
501 }
502
503 CSSStyleSelector::~CSSStyleSelector()
504 {
505     m_fontSelector->clearDocument();
506     delete m_medium;
507     delete m_authorStyle;
508     delete m_userStyle;
509     deleteAllValues(m_viewportDependentMediaQueryResults);
510     m_keyframesRuleMap.clear();
511 }
512
513 static CSSStyleSheet* parseUASheet(const String& str)
514 {
515     CSSStyleSheet* sheet = CSSStyleSheet::create().releaseRef(); // leak the sheet on purpose
516     sheet->parseString(str);
517     return sheet;
518 }
519
520 static CSSStyleSheet* parseUASheet(const char* characters, unsigned size)
521 {
522     return parseUASheet(String(characters, size));
523 }
524
525 static void loadFullDefaultStyle()
526 {
527     if (simpleDefaultStyleSheet) {
528         ASSERT(defaultStyle);
529         delete defaultStyle;
530         delete simpleDefaultStyleSheet;
531         defaultStyle = new CSSRuleSet;
532         simpleDefaultStyleSheet = 0;
533     } else {
534         ASSERT(!defaultStyle);
535         defaultStyle = new CSSRuleSet;
536         defaultPrintStyle = new CSSRuleSet;
537         defaultQuirksStyle = new CSSRuleSet;
538     }
539
540     // Strict-mode rules.
541     String defaultRules = String(htmlUserAgentStyleSheet, sizeof(htmlUserAgentStyleSheet)) + RenderTheme::defaultTheme()->extraDefaultStyleSheet();
542     CSSStyleSheet* defaultSheet = parseUASheet(defaultRules);
543     defaultStyle->addRulesFromSheet(defaultSheet, screenEval());
544     defaultPrintStyle->addRulesFromSheet(defaultSheet, printEval());
545
546     // Quirks-mode rules.
547     String quirksRules = String(quirksUserAgentStyleSheet, sizeof(quirksUserAgentStyleSheet)) + RenderTheme::defaultTheme()->extraQuirksStyleSheet();
548     CSSStyleSheet* quirksSheet = parseUASheet(quirksRules);
549     defaultQuirksStyle->addRulesFromSheet(quirksSheet, screenEval());
550 }
551
552 static void loadSimpleDefaultStyle()
553 {
554     ASSERT(!defaultStyle);
555     ASSERT(!simpleDefaultStyleSheet);
556     
557     defaultStyle = new CSSRuleSet;
558     defaultPrintStyle = new CSSRuleSet;
559     defaultQuirksStyle = new CSSRuleSet;
560
561     simpleDefaultStyleSheet = parseUASheet(simpleUserAgentStyleSheet, strlen(simpleUserAgentStyleSheet));
562     defaultStyle->addRulesFromSheet(simpleDefaultStyleSheet, screenEval());
563     
564     // No need to initialize quirks sheet yet as there are no quirk rules for elements allowed in simple default style.
565 }
566     
567 static void loadViewSourceStyle()
568 {
569     ASSERT(!defaultViewSourceStyle);
570     defaultViewSourceStyle = new CSSRuleSet;
571     defaultViewSourceStyle->addRulesFromSheet(parseUASheet(sourceUserAgentStyleSheet, sizeof(sourceUserAgentStyleSheet)), screenEval());
572 }
573
574 void CSSStyleSelector::addMatchedDeclaration(CSSMutableStyleDeclaration* decl)
575 {
576     if (!decl->hasVariableDependentValue()) {
577         m_matchedDecls.append(decl);
578         return;
579     }
580
581     // See if we have already resolved the variables in this declaration.
582     CSSMutableStyleDeclaration* resolvedDecl = m_resolvedVariablesDeclarations.get(decl).get();
583     if (resolvedDecl) {
584         m_matchedDecls.append(resolvedDecl);
585         return;
586     }
587
588     // If this declaration has any variables in it, then we need to make a cloned
589     // declaration with as many variables resolved as possible for this style selector's media.
590     RefPtr<CSSMutableStyleDeclaration> newDecl = CSSMutableStyleDeclaration::create(decl->parentRule());
591     m_matchedDecls.append(newDecl.get());
592     m_resolvedVariablesDeclarations.set(decl, newDecl);
593
594     HashSet<String> usedBlockVariables;
595     resolveVariablesForDeclaration(decl, newDecl.get(), usedBlockVariables);
596 }
597
598 void CSSStyleSelector::resolveVariablesForDeclaration(CSSMutableStyleDeclaration* decl, CSSMutableStyleDeclaration* newDecl, HashSet<String>& usedBlockVariables)
599 {
600     // Now iterate over the properties in the original declaration.  As we resolve variables we'll end up
601     // mutating the new declaration (possibly expanding shorthands).  The new declaration has no m_node
602     // though, so it can't mistakenly call setChanged on anything.
603     CSSMutableStyleDeclaration::const_iterator end = decl->end();
604     for (CSSMutableStyleDeclaration::const_iterator it = decl->begin(); it != end; ++it) {
605         const CSSProperty& current = *it;
606         if (!current.value()->isVariableDependentValue()) {
607             // We can just add the parsed property directly.
608             newDecl->addParsedProperty(current);
609             continue;
610         }
611         CSSValueList* valueList = static_cast<CSSVariableDependentValue*>(current.value())->valueList();
612         if (!valueList)
613             continue;
614         CSSParserValueList resolvedValueList;
615         unsigned s = valueList->length();
616         bool fullyResolved = true;
617         for (unsigned i = 0; i < s; ++i) {
618             CSSValue* val = valueList->item(i);
619             CSSPrimitiveValue* primitiveValue = val->isPrimitiveValue() ? static_cast<CSSPrimitiveValue*>(val) : 0;
620             if (primitiveValue && primitiveValue->isVariable()) {
621                 CSSVariablesRule* rule = m_variablesMap.get(primitiveValue->getStringValue());
622                 if (!rule || !rule->variables()) {
623                     fullyResolved = false;
624                     break;
625                 }
626                 
627                 if (current.id() == CSSPropertyWebkitVariableDeclarationBlock && s == 1) {
628                     fullyResolved = false;
629                     if (!usedBlockVariables.contains(primitiveValue->getStringValue())) {
630                         CSSMutableStyleDeclaration* declBlock = rule->variables()->getParsedVariableDeclarationBlock(primitiveValue->getStringValue());
631                         if (declBlock) {
632                             usedBlockVariables.add(primitiveValue->getStringValue());
633                             resolveVariablesForDeclaration(declBlock, newDecl, usedBlockVariables);
634                         }
635                     }
636                 }
637
638                 CSSValueList* resolvedVariable = rule->variables()->getParsedVariable(primitiveValue->getStringValue());
639                 if (!resolvedVariable) {
640                     fullyResolved = false;
641                     break;
642                 }
643                 unsigned valueSize = resolvedVariable->length();
644                 for (unsigned j = 0; j < valueSize; ++j)
645                     resolvedValueList.addValue(resolvedVariable->item(j)->parserValue());
646             } else
647                 resolvedValueList.addValue(val->parserValue());
648         }
649         
650         if (!fullyResolved)
651             continue;
652
653         // We now have a fully resolved new value list.  We want the parser to use this value list
654         // and parse our new declaration.
655         CSSParser(m_checker.m_strictParsing).parsePropertyWithResolvedVariables(current.id(), current.isImportant(), newDecl, &resolvedValueList);
656     }
657 }
658
659 void CSSStyleSelector::matchRules(CSSRuleSet* rules, int& firstRuleIndex, int& lastRuleIndex)
660 {
661     m_matchedRules.clear();
662
663     if (!rules || !m_element)
664         return;
665     
666     // We need to collect the rules for id, class, tag, and everything else into a buffer and
667     // then sort the buffer.
668     if (m_element->hasID())
669         matchRulesForList(rules->getIDRules(m_element->getIDAttribute().impl()), firstRuleIndex, lastRuleIndex);
670     if (m_element->hasClass()) {
671         ASSERT(m_styledElement);
672         const SpaceSplitString& classNames = m_styledElement->classNames();
673         size_t size = classNames.size();
674         for (size_t i = 0; i < size; ++i)
675             matchRulesForList(rules->getClassRules(classNames[i].impl()), firstRuleIndex, lastRuleIndex);
676     }
677     matchRulesForList(rules->getTagRules(m_element->localName().impl()), firstRuleIndex, lastRuleIndex);
678     matchRulesForList(rules->getUniversalRules(), firstRuleIndex, lastRuleIndex);
679     
680     // If we didn't match any rules, we're done.
681     if (m_matchedRules.isEmpty())
682         return;
683     
684     // Sort the set of matched rules.
685     sortMatchedRules(0, m_matchedRules.size());
686     
687     // Now transfer the set of matched rules over to our list of decls.
688     if (!m_checker.m_collectRulesOnly) {
689         for (unsigned i = 0; i < m_matchedRules.size(); i++)
690             addMatchedDeclaration(m_matchedRules[i]->rule()->declaration());
691     } else {
692         for (unsigned i = 0; i < m_matchedRules.size(); i++) {
693             if (!m_ruleList)
694                 m_ruleList = CSSRuleList::create();
695             m_ruleList->append(m_matchedRules[i]->rule());
696         }
697     }
698 }
699
700 void CSSStyleSelector::matchRulesForList(CSSRuleDataList* rules, int& firstRuleIndex, int& lastRuleIndex)
701 {
702     if (!rules)
703         return;
704
705     for (CSSRuleData* d = rules->first(); d; d = d->next()) {
706         CSSStyleRule* rule = d->rule();
707         if (checkSelector(d->selector())) {
708             // If the rule has no properties to apply, then ignore it.
709             CSSMutableStyleDeclaration* decl = rule->declaration();
710             if (!decl || !decl->length())
711                 continue;
712             
713             // If we're matching normal rules, set a pseudo bit if 
714             // we really just matched a pseudo-element.
715             if (m_dynamicPseudo != NOPSEUDO && m_checker.m_pseudoStyle == NOPSEUDO) {
716                 if (m_checker.m_collectRulesOnly)
717                     continue;
718                 if (m_dynamicPseudo < FIRST_INTERNAL_PSEUDOID)
719                     m_style->setHasPseudoStyle(m_dynamicPseudo);
720             } else {
721                 // Update our first/last rule indices in the matched rules array.
722                 lastRuleIndex = m_matchedDecls.size() + m_matchedRules.size();
723                 if (firstRuleIndex == -1)
724                     firstRuleIndex = lastRuleIndex;
725
726                 // Add this rule to our list of matched rules.
727                 addMatchedRule(d);
728             }
729         }
730     }
731 }
732
733 static bool operator >(CSSRuleData& r1, CSSRuleData& r2)
734 {
735     int spec1 = r1.selector()->specificity();
736     int spec2 = r2.selector()->specificity();
737     return (spec1 == spec2) ? r1.position() > r2.position() : spec1 > spec2; 
738 }
739     
740 static bool operator <=(CSSRuleData& r1, CSSRuleData& r2)
741 {
742     return !(r1 > r2);
743 }
744
745 void CSSStyleSelector::sortMatchedRules(unsigned start, unsigned end)
746 {
747     if (start >= end || (end - start == 1))
748         return; // Sanity check.
749
750     if (end - start <= 6) {
751         // Apply a bubble sort for smaller lists.
752         for (unsigned i = end - 1; i > start; i--) {
753             bool sorted = true;
754             for (unsigned j = start; j < i; j++) {
755                 CSSRuleData* elt = m_matchedRules[j];
756                 CSSRuleData* elt2 = m_matchedRules[j + 1];
757                 if (*elt > *elt2) {
758                     sorted = false;
759                     m_matchedRules[j] = elt2;
760                     m_matchedRules[j + 1] = elt;
761                 }
762             }
763             if (sorted)
764                 return;
765         }
766         return;
767     }
768
769     // Perform a merge sort for larger lists.
770     unsigned mid = (start + end) / 2;
771     sortMatchedRules(start, mid);
772     sortMatchedRules(mid, end);
773     
774     CSSRuleData* elt = m_matchedRules[mid - 1];
775     CSSRuleData* elt2 = m_matchedRules[mid];
776     
777     // Handle the fast common case (of equal specificity).  The list may already
778     // be completely sorted.
779     if (*elt <= *elt2)
780         return;
781     
782     // We have to merge sort.  Ensure our merge buffer is big enough to hold
783     // all the items.
784     Vector<CSSRuleData*> rulesMergeBuffer;
785     rulesMergeBuffer.reserveInitialCapacity(end - start); 
786
787     unsigned i1 = start;
788     unsigned i2 = mid;
789     
790     elt = m_matchedRules[i1];
791     elt2 = m_matchedRules[i2];
792     
793     while (i1 < mid || i2 < end) {
794         if (i1 < mid && (i2 == end || *elt <= *elt2)) {
795             rulesMergeBuffer.append(elt);
796             if (++i1 < mid)
797                 elt = m_matchedRules[i1];
798         } else {
799             rulesMergeBuffer.append(elt2);
800             if (++i2 < end)
801                 elt2 = m_matchedRules[i2];
802         }
803     }
804     
805     for (unsigned i = start; i < end; i++)
806         m_matchedRules[i] = rulesMergeBuffer[i - start];
807 }
808
809 inline EInsideLink CSSStyleSelector::SelectorChecker::determineLinkState(Element* element) const
810 {
811     if (!element || !element->isLink())
812         return NotInsideLink;
813     return determineLinkStateSlowCase(element);
814 }
815     
816 inline void CSSStyleSelector::initElement(Element* e)
817 {
818     if (m_element != e) {
819         m_element = e;
820         m_styledElement = m_element && m_element->isStyledElement() ? static_cast<StyledElement*>(m_element) : 0;
821         m_elementLinkState = m_checker.determineLinkState(m_element);
822     }
823 }
824
825 inline void CSSStyleSelector::initForStyleResolve(Element* e, RenderStyle* parentStyle, PseudoId pseudoID)
826 {
827     m_checker.m_pseudoStyle = pseudoID;
828
829     m_parentNode = e ? e->parentNode() : 0;
830
831 #if ENABLE(SVG)
832     if (!m_parentNode && e && e->isSVGElement() && e->isShadowNode())
833         m_parentNode = e->shadowParentNode();
834 #endif
835
836     if (parentStyle)
837         m_parentStyle = parentStyle;
838     else
839         m_parentStyle = m_parentNode ? m_parentNode->renderStyle() : 0;
840
841     Node* docElement = e ? e->document()->documentElement() : 0;
842     RenderStyle* docStyle = m_checker.m_document->renderStyle();
843     m_rootElementStyle = docElement && e != docElement ? docElement->renderStyle() : docStyle;
844
845     m_style = 0;
846
847     m_matchedDecls.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     return page->group().isLinkVisited(hash) ? InsideVisitedLink : InsideUnvisitedLink;
932 }
933
934 bool CSSStyleSelector::SelectorChecker::checkSelector(CSSSelector* sel, Element* element) const
935 {
936     PseudoId dynamicPseudo = NOPSEUDO;
937     return checkSelector(sel, element, 0, dynamicPseudo, false, false) == SelectorMatches;
938 }
939
940 #ifdef STYLE_SHARING_STATS
941 static int fraction = 0;
942 static int total = 0;
943 #endif
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->mappedAttributes()->mapsEquivalent(m_styledElement->mappedAttributes());
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);
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);
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);
1097     }
1098 }
1099
1100 PassRefPtr<RenderStyle> CSSStyleSelector::styleForDocument(Document* document)
1101 {
1102     RefPtr<RenderStyle> documentStyle = RenderStyle::create();
1103     documentStyle->setDisplay(BLOCK);
1104     documentStyle->setVisuallyOrdered(document->visuallyOrdered());
1105     documentStyle->setZoom(document->frame()->pageZoomFactor());
1106     
1107     FontDescription fontDescription;
1108     fontDescription.setUsePrinterFont(document->printing());
1109     if (Settings* settings = document->settings()) {
1110         fontDescription.setRenderingMode(settings->fontRenderingMode());
1111         if (document->printing() && !settings->shouldPrintBackgrounds())
1112             documentStyle->setForceBackgroundsToWhite(true);
1113         const AtomicString& stdfont = settings->standardFontFamily();
1114         if (!stdfont.isEmpty()) {
1115             fontDescription.firstFamily().setFamily(stdfont);
1116             fontDescription.firstFamily().appendFamily(0);
1117         }
1118         fontDescription.setKeywordSize(CSSValueMedium - CSSValueXxSmall + 1);
1119         int size = CSSStyleSelector::fontSizeForKeyword(document, CSSValueMedium, false);
1120         fontDescription.setSpecifiedSize(size);
1121         bool useSVGZoomRules = document->isSVGDocument();
1122         fontDescription.setComputedSize(CSSStyleSelector::getComputedSizeFromSpecifiedSize(document, documentStyle.get(), fontDescription.isAbsoluteSize(), size, useSVGZoomRules));
1123     }
1124
1125     documentStyle->setFontDescription(fontDescription);
1126     documentStyle->font().update(0);
1127     if (document->inCompatMode())
1128         documentStyle->setHtmlHacks(true); // enable html specific rendering tricks
1129         
1130     return documentStyle.release();
1131 }
1132
1133 // If resolveForRootDefault is true, style based on user agent style sheet only. This is used in media queries, where
1134 // relative units are interpreted according to document root element style, styled only with UA stylesheet
1135
1136 PassRefPtr<RenderStyle> CSSStyleSelector::styleForElement(Element* e, RenderStyle* defaultParent, bool allowSharing, bool resolveForRootDefault, bool matchVisitedPseudoClass)
1137 {
1138     // Once an element has a renderer, we don't try to destroy it, since otherwise the renderer
1139     // will vanish if a style recalc happens during loading.
1140     if (allowSharing && !e->document()->haveStylesheetsLoaded() && !e->renderer()) {
1141         if (!s_styleNotYetAvailable) {
1142             s_styleNotYetAvailable = RenderStyle::create().releaseRef();
1143             s_styleNotYetAvailable->ref();
1144             s_styleNotYetAvailable->setDisplay(NONE);
1145             s_styleNotYetAvailable->font().update(m_fontSelector);
1146         }
1147         s_styleNotYetAvailable->ref();
1148         e->document()->setHasNodesWithPlaceholderStyle();
1149         return s_styleNotYetAvailable;
1150     }
1151
1152     initElement(e);
1153     if (allowSharing) {
1154         RenderStyle* sharedStyle = locateSharedStyle();
1155         if (sharedStyle)
1156             return sharedStyle;
1157     }
1158     initForStyleResolve(e, defaultParent);
1159
1160     // Compute our style allowing :visited to match first.
1161     RefPtr<RenderStyle> visitedStyle;
1162     if (!matchVisitedPseudoClass && m_parentStyle && (m_parentStyle->insideLink() || e->isLink()) && e->document()->usesLinkRules()) {
1163         // Fetch our parent style.
1164         RenderStyle* parentStyle = m_parentStyle;
1165         if (!e->isLink()) {
1166             // Use the parent's visited style if one exists.
1167             RenderStyle* parentVisitedStyle = m_parentStyle->getCachedPseudoStyle(VISITED_LINK);
1168             if (parentVisitedStyle)
1169                 parentStyle = parentVisitedStyle;
1170         }
1171         visitedStyle = styleForElement(e, parentStyle, false, false, true);
1172         if (visitedStyle) {
1173             if (m_elementLinkState == InsideUnvisitedLink)
1174                 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.
1175             else
1176                 visitedStyle->setStyleType(VISITED_LINK);
1177         }
1178         initForStyleResolve(e, defaultParent);
1179     }
1180
1181     m_checker.m_matchVisitedPseudoClass = matchVisitedPseudoClass;
1182
1183     m_style = RenderStyle::create();
1184
1185     if (m_parentStyle)
1186         m_style->inheritFrom(m_parentStyle);
1187     else
1188         m_parentStyle = style();
1189
1190     if (e->isLink()) {
1191         m_style->setIsLink(true);
1192         m_style->setInsideLink(m_elementLinkState);
1193     }
1194     
1195     if (simpleDefaultStyleSheet && !elementCanUseSimpleDefaultStyle(e))
1196         loadFullDefaultStyle();
1197
1198 #if ENABLE(SVG)
1199     static bool loadedSVGUserAgentSheet;
1200     if (e->isSVGElement() && !loadedSVGUserAgentSheet) {
1201         // SVG rules.
1202         loadedSVGUserAgentSheet = true;
1203         CSSStyleSheet* svgSheet = parseUASheet(svgUserAgentStyleSheet, sizeof(svgUserAgentStyleSheet));
1204         defaultStyle->addRulesFromSheet(svgSheet, screenEval());
1205         defaultPrintStyle->addRulesFromSheet(svgSheet, printEval());
1206     }
1207 #endif
1208
1209 #if ENABLE(MATHML)
1210     static bool loadedMathMLUserAgentSheet;
1211     if (e->isMathMLElement() && !loadedMathMLUserAgentSheet) {
1212         // MathML rules.
1213         loadedMathMLUserAgentSheet = true;
1214         CSSStyleSheet* mathMLSheet = parseUASheet(mathmlUserAgentStyleSheet, sizeof(mathmlUserAgentStyleSheet));
1215         defaultStyle->addRulesFromSheet(mathMLSheet, screenEval());
1216         defaultPrintStyle->addRulesFromSheet(mathMLSheet, printEval());
1217     }
1218 #endif
1219
1220 #if ENABLE(WML)
1221     static bool loadedWMLUserAgentSheet;
1222     if (e->isWMLElement() && !loadedWMLUserAgentSheet) {
1223         // WML rules.
1224         loadedWMLUserAgentSheet = true;
1225         CSSStyleSheet* wmlSheet = parseUASheet(wmlUserAgentStyleSheet, sizeof(wmlUserAgentStyleSheet));
1226         defaultStyle->addRulesFromSheet(wmlSheet, screenEval());
1227         defaultPrintStyle->addRulesFromSheet(wmlSheet, printEval());
1228     }
1229 #endif
1230
1231 #if ENABLE(VIDEO)
1232     static bool loadedMediaStyleSheet;
1233     if (!loadedMediaStyleSheet && (e->hasTagName(videoTag) || e->hasTagName(audioTag))) {
1234         loadedMediaStyleSheet = true;
1235         String mediaRules = String(mediaControlsUserAgentStyleSheet, sizeof(mediaControlsUserAgentStyleSheet)) + RenderTheme::defaultTheme()->extraMediaControlsStyleSheet();
1236         CSSStyleSheet* mediaControlsSheet = parseUASheet(mediaRules);
1237         defaultStyle->addRulesFromSheet(mediaControlsSheet, screenEval());
1238         defaultPrintStyle->addRulesFromSheet(mediaControlsSheet, printEval());
1239     }
1240 #endif
1241
1242     int firstUARule = -1, lastUARule = -1;
1243     int firstUserRule = -1, lastUserRule = -1;
1244     int firstAuthorRule = -1, lastAuthorRule = -1;
1245     matchUARules(firstUARule, lastUARule);
1246
1247     if (!resolveForRootDefault) {
1248         // 4. Now we check user sheet rules.
1249         if (m_matchAuthorAndUserStyles)
1250             matchRules(m_userStyle, firstUserRule, lastUserRule);
1251
1252         // 5. Now check author rules, beginning first with presentational attributes
1253         // mapped from HTML.
1254         if (m_styledElement) {
1255             // Ask if the HTML element has mapped attributes.
1256             if (m_styledElement->hasMappedAttributes()) {
1257                 // Walk our attribute list and add in each decl.
1258                 const NamedMappedAttrMap* map = m_styledElement->mappedAttributes();
1259                 for (unsigned i = 0; i < map->length(); i++) {
1260                     Attribute* attr = map->attributeItem(i);
1261                     if (attr->isMappedAttribute() && attr->decl()) {
1262                         lastAuthorRule = m_matchedDecls.size();
1263                         if (firstAuthorRule == -1)
1264                             firstAuthorRule = lastAuthorRule;
1265                         addMatchedDeclaration(attr->decl());
1266                     }
1267                 }
1268             }
1269
1270             // Now we check additional mapped declarations.
1271             // Tables and table cells share an additional mapped rule that must be applied
1272             // after all attributes, since their mapped style depends on the values of multiple attributes.
1273             if (m_styledElement->canHaveAdditionalAttributeStyleDecls()) {
1274                 m_additionalAttributeStyleDecls.clear();
1275                 m_styledElement->additionalAttributeStyleDecls(m_additionalAttributeStyleDecls);
1276                 if (!m_additionalAttributeStyleDecls.isEmpty()) {
1277                     unsigned additionalDeclsSize = m_additionalAttributeStyleDecls.size();
1278                     if (firstAuthorRule == -1)
1279                         firstAuthorRule = m_matchedDecls.size();
1280                     lastAuthorRule = m_matchedDecls.size() + additionalDeclsSize - 1;
1281                     for (unsigned i = 0; i < additionalDeclsSize; i++)
1282                         addMatchedDeclaration(m_additionalAttributeStyleDecls[i]);
1283                 }
1284             }
1285         }
1286     
1287         // 6. Check the rules in author sheets next.
1288         if (m_matchAuthorAndUserStyles)
1289             matchRules(m_authorStyle, firstAuthorRule, lastAuthorRule);
1290
1291         // 7. Now check our inline style attribute.
1292         if (m_matchAuthorAndUserStyles && m_styledElement) {
1293             CSSMutableStyleDeclaration* inlineDecl = m_styledElement->inlineStyleDecl();
1294             if (inlineDecl) {
1295                 lastAuthorRule = m_matchedDecls.size();
1296                 if (firstAuthorRule == -1)
1297                     firstAuthorRule = lastAuthorRule;
1298                 addMatchedDeclaration(inlineDecl);
1299             }
1300         }
1301     }
1302
1303     // Reset the value back before applying properties, so that -webkit-link knows what color to use.
1304     m_checker.m_matchVisitedPseudoClass = matchVisitedPseudoClass;
1305     
1306     // Now we have all of the matched rules in the appropriate order.  Walk the rules and apply
1307     // high-priority properties first, i.e., those properties that other properties depend on.
1308     // The order is (1) high-priority not important, (2) high-priority important, (3) normal not important
1309     // and (4) normal important.
1310     m_lineHeightValue = 0;
1311     applyDeclarations<true>(false, 0, m_matchedDecls.size() - 1);
1312     if (!resolveForRootDefault) {
1313         applyDeclarations<true>(true, firstAuthorRule, lastAuthorRule);
1314         applyDeclarations<true>(true, firstUserRule, lastUserRule);
1315     }
1316     applyDeclarations<true>(true, firstUARule, lastUARule);
1317     
1318     // If our font got dirtied, go ahead and update it now.
1319     if (m_fontDirty)
1320         updateFont();
1321
1322     // Line-height is set when we are sure we decided on the font-size
1323     if (m_lineHeightValue)
1324         applyProperty(CSSPropertyLineHeight, m_lineHeightValue);
1325
1326     // Now do the normal priority UA properties.
1327     applyDeclarations<false>(false, firstUARule, lastUARule);
1328     
1329     // Cache our border and background so that we can examine them later.
1330     cacheBorderAndBackground();
1331     
1332     // Now do the author and user normal priority properties and all the !important properties.
1333     if (!resolveForRootDefault) {
1334         applyDeclarations<false>(false, lastUARule + 1, m_matchedDecls.size() - 1);
1335         applyDeclarations<false>(true, firstAuthorRule, lastAuthorRule);
1336         applyDeclarations<false>(true, firstUserRule, lastUserRule);
1337     }
1338     applyDeclarations<false>(true, firstUARule, lastUARule);
1339     
1340     // If our font got dirtied by one of the non-essential font props, 
1341     // go ahead and update it a second time.
1342     if (m_fontDirty)
1343         updateFont();
1344     
1345     // Clean up our style object's display and text decorations (among other fixups).
1346     adjustRenderStyle(style(), e);
1347
1348     // If we have first-letter pseudo style, do not share this style
1349     if (m_style->hasPseudoStyle(FIRST_LETTER))
1350         m_style->setUnique();
1351
1352     if (visitedStyle) {
1353         // Copy any pseudo bits that the visited style has to the primary style so that
1354         // pseudo element styles will continue to work for pseudo elements inside :visited
1355         // links.
1356         for (unsigned pseudo = FIRST_PUBLIC_PSEUDOID; pseudo < FIRST_INTERNAL_PSEUDOID; ++pseudo) {
1357             if (visitedStyle->hasPseudoStyle(static_cast<PseudoId>(pseudo)))
1358                 m_style->setHasPseudoStyle(static_cast<PseudoId>(pseudo));
1359         }
1360         
1361         // Add the visited style off the main style.
1362         m_style->addCachedPseudoStyle(visitedStyle.release());
1363     }
1364
1365     if (!matchVisitedPseudoClass)
1366         initElement(0); // Clear out for the next resolve.
1367
1368     // Now return the style.
1369     return m_style.release();
1370 }
1371
1372 void CSSStyleSelector::keyframeStylesForAnimation(Element* e, const RenderStyle* elementStyle, KeyframeList& list)
1373 {
1374     list.clear();
1375     
1376     // Get the keyframesRule for this name
1377     if (!e || list.animationName().isEmpty())
1378         return;
1379
1380     m_keyframesRuleMap.checkConsistency();
1381    
1382     if (!m_keyframesRuleMap.contains(list.animationName().impl()))
1383         return;
1384         
1385     const WebKitCSSKeyframesRule* rule = m_keyframesRuleMap.find(list.animationName().impl()).get()->second.get();
1386     
1387     // Construct and populate the style for each keyframe
1388     for (unsigned i = 0; i < rule->length(); ++i) {
1389         // Apply the declaration to the style. This is a simplified version of the logic in styleForElement
1390         initElement(e);
1391         initForStyleResolve(e);
1392         
1393         const WebKitCSSKeyframeRule* kf = rule->item(i);
1394         addMatchedDeclaration(kf->style());
1395
1396         ASSERT(!m_style);
1397
1398         // Create the style
1399         m_style = RenderStyle::clone(elementStyle);
1400         
1401         m_lineHeightValue = 0;
1402         
1403         // We don't need to bother with !important. Since there is only ever one
1404         // decl, there's nothing to override. So just add the first properties.
1405         applyDeclarations<true>(false, 0, m_matchedDecls.size() - 1);
1406         
1407         // If our font got dirtied, go ahead and update it now.
1408         if (m_fontDirty)
1409             updateFont();
1410
1411         // Line-height is set when we are sure we decided on the font-size
1412         if (m_lineHeightValue)
1413             applyProperty(CSSPropertyLineHeight, m_lineHeightValue);
1414         
1415         // Now do rest of the properties.
1416         applyDeclarations<false>(false, 0, m_matchedDecls.size() - 1);
1417         
1418         // If our font got dirtied by one of the non-essential font props, 
1419         // go ahead and update it a second time.
1420         if (m_fontDirty)
1421             updateFont();
1422
1423         // Add all the animating properties to the list
1424         CSSMutableStyleDeclaration::const_iterator end = kf->style()->end();
1425         for (CSSMutableStyleDeclaration::const_iterator it = kf->style()->begin(); it != end; ++it) {
1426             int property = (*it).id();
1427             // Timing-function within keyframes is special, because it is not animated; it just
1428             // describes the timing function between this keyframe and the next.
1429             if (property != CSSPropertyWebkitAnimationTimingFunction)
1430                 list.addProperty(property);
1431         }
1432         
1433         // Add this keyframe style to all the indicated key times
1434         Vector<float> keys;
1435         kf->getKeys(keys);
1436         for (size_t keyIndex = 0; keyIndex < keys.size(); ++keyIndex) {
1437             float key = keys[keyIndex];
1438             list.insert(key, m_style);
1439         }
1440         m_style = 0;
1441     }
1442     
1443     // Make sure there is a 0% and a 100% keyframe
1444     float first = -1;
1445     float last = -1;
1446     if (list.size() >= 2) {
1447         first = list.beginKeyframes()->key();
1448         last = (list.endKeyframes()-1)->key();
1449     }
1450     if (first != 0 || last != 1)
1451         list.clear();
1452 }
1453
1454 PassRefPtr<RenderStyle> CSSStyleSelector::pseudoStyleForElement(PseudoId pseudo, Element* e, RenderStyle* parentStyle, bool matchVisitedPseudoClass)
1455 {
1456     if (!e)
1457         return 0;
1458
1459     initElement(e);
1460
1461     // Compute our :visited style first, so that we know whether or not we'll need to create a normal style just to hang it
1462     // off of.
1463     RefPtr<RenderStyle> visitedStyle;
1464     if (!matchVisitedPseudoClass && parentStyle && parentStyle->insideLink()) {
1465         // Fetch our parent style with :visited in effect.
1466         RenderStyle* parentVisitedStyle = parentStyle->getCachedPseudoStyle(VISITED_LINK);
1467         visitedStyle = pseudoStyleForElement(pseudo, e, parentVisitedStyle ? parentVisitedStyle : parentStyle, true);
1468         if (visitedStyle) {
1469             if (m_elementLinkState == InsideUnvisitedLink)
1470                 visitedStyle = 0;  // We made the style to avoid timing attacks. Just throw it away now that we did that.
1471             else
1472                 visitedStyle->setStyleType(VISITED_LINK);
1473         }
1474     }
1475
1476     initForStyleResolve(e, parentStyle, pseudo);
1477     m_style = parentStyle;
1478     
1479     m_checker.m_matchVisitedPseudoClass = matchVisitedPseudoClass;
1480
1481     // Since we don't use pseudo-elements in any of our quirk/print user agent rules, don't waste time walking
1482     // those rules.
1483     
1484     // Check UA, user and author rules.
1485     int firstUARule = -1, lastUARule = -1, firstUserRule = -1, lastUserRule = -1, firstAuthorRule = -1, lastAuthorRule = -1;
1486     matchUARules(firstUARule, lastUARule);
1487
1488     if (m_matchAuthorAndUserStyles) {
1489         matchRules(m_userStyle, firstUserRule, lastUserRule);
1490         matchRules(m_authorStyle, firstAuthorRule, lastAuthorRule);
1491     }
1492
1493     if (m_matchedDecls.isEmpty() && !visitedStyle)
1494         return 0;
1495
1496     m_style = RenderStyle::create();
1497     if (parentStyle)
1498         m_style->inheritFrom(parentStyle);
1499
1500     m_style->setStyleType(pseudo);
1501     
1502     m_lineHeightValue = 0;
1503     
1504     // Reset the value back before applying properties, so that -webkit-link knows what color to use.
1505     m_checker.m_matchVisitedPseudoClass = matchVisitedPseudoClass;
1506
1507     // High-priority properties.
1508     applyDeclarations<true>(false, 0, m_matchedDecls.size() - 1);
1509     applyDeclarations<true>(true, firstAuthorRule, lastAuthorRule);
1510     applyDeclarations<true>(true, firstUserRule, lastUserRule);
1511     applyDeclarations<true>(true, firstUARule, lastUARule);
1512     
1513     // If our font got dirtied, go ahead and update it now.
1514     if (m_fontDirty)
1515         updateFont();
1516
1517     // Line-height is set when we are sure we decided on the font-size
1518     if (m_lineHeightValue)
1519         applyProperty(CSSPropertyLineHeight, m_lineHeightValue);
1520     
1521     // Now do the normal priority properties.
1522     applyDeclarations<false>(false, firstUARule, lastUARule);
1523     
1524     // Cache our border and background so that we can examine them later.
1525     cacheBorderAndBackground();
1526     
1527     applyDeclarations<false>(false, lastUARule + 1, m_matchedDecls.size() - 1);
1528     applyDeclarations<false>(true, firstAuthorRule, lastAuthorRule);
1529     applyDeclarations<false>(true, firstUserRule, lastUserRule);
1530     applyDeclarations<false>(true, firstUARule, lastUARule);
1531     
1532     // If our font got dirtied by one of the non-essential font props, 
1533     // go ahead and update it a second time.
1534     if (m_fontDirty)
1535         updateFont();
1536
1537     // Clean up our style object's display and text decorations (among other fixups).
1538     adjustRenderStyle(style(), 0);
1539
1540     // Hang our visited style off m_style.
1541     if (visitedStyle)
1542         m_style->addCachedPseudoStyle(visitedStyle.release());
1543         
1544     // Now return the style.
1545     return m_style.release();
1546 }
1547
1548 #if ENABLE(DATAGRID)
1549
1550 PassRefPtr<RenderStyle> CSSStyleSelector::pseudoStyleForDataGridColumn(DataGridColumn*, RenderStyle*)
1551 {
1552     // FIXME: Implement
1553     return 0;
1554 }
1555
1556 PassRefPtr<RenderStyle> CSSStyleSelector::pseudoStyleForDataGridColumnHeader(DataGridColumn*, RenderStyle*)
1557 {
1558     // FIXME: Implement
1559     return 0;
1560 }
1561
1562 #endif
1563
1564 static void addIntrinsicMargins(RenderStyle* style)
1565 {
1566     // Intrinsic margin value.
1567     const int intrinsicMargin = 2 * style->effectiveZoom();
1568     
1569     // FIXME: Using width/height alone and not also dealing with min-width/max-width is flawed.
1570     // FIXME: Using "quirk" to decide the margin wasn't set is kind of lame.
1571     if (style->width().isIntrinsicOrAuto()) {
1572         if (style->marginLeft().quirk())
1573             style->setMarginLeft(Length(intrinsicMargin, Fixed));
1574         if (style->marginRight().quirk())
1575             style->setMarginRight(Length(intrinsicMargin, Fixed));
1576     }
1577
1578     if (style->height().isAuto()) {
1579         if (style->marginTop().quirk())
1580             style->setMarginTop(Length(intrinsicMargin, Fixed));
1581         if (style->marginBottom().quirk())
1582             style->setMarginBottom(Length(intrinsicMargin, Fixed));
1583     }
1584 }
1585
1586 void CSSStyleSelector::adjustRenderStyle(RenderStyle* style, Element *e)
1587 {
1588     // Cache our original display.
1589     style->setOriginalDisplay(style->display());
1590
1591     if (style->display() != NONE) {
1592         // If we have a <td> that specifies a float property, in quirks mode we just drop the float
1593         // property.
1594         // Sites also commonly use display:inline/block on <td>s and <table>s.  In quirks mode we force
1595         // these tags to retain their display types.
1596         if (!m_checker.m_strictParsing && e) {
1597             if (e->hasTagName(tdTag)) {
1598                 style->setDisplay(TABLE_CELL);
1599                 style->setFloating(FNONE);
1600             }
1601             else if (e->hasTagName(tableTag))
1602                 style->setDisplay(style->isDisplayInlineType() ? INLINE_TABLE : TABLE);
1603         }
1604
1605         if (e && (e->hasTagName(tdTag) || e->hasTagName(thTag))) {
1606             if (style->whiteSpace() == KHTML_NOWRAP) {
1607                 // Figure out if we are really nowrapping or if we should just
1608                 // use normal instead.  If the width of the cell is fixed, then
1609                 // we don't actually use NOWRAP.
1610                 if (style->width().isFixed())
1611                     style->setWhiteSpace(NORMAL);
1612                 else
1613                     style->setWhiteSpace(NOWRAP);
1614             }
1615         }
1616
1617         // Tables never support the -webkit-* values for text-align and will reset back to the default.
1618         if (e && e->hasTagName(tableTag) && (style->textAlign() == WEBKIT_LEFT || style->textAlign() == WEBKIT_CENTER || style->textAlign() == WEBKIT_RIGHT))
1619             style->setTextAlign(TAAUTO);
1620
1621         // Frames and framesets never honor position:relative or position:absolute.  This is necessary to
1622         // fix a crash where a site tries to position these objects.  They also never honor display.
1623         if (e && (e->hasTagName(frameTag) || e->hasTagName(framesetTag))) {
1624             style->setPosition(StaticPosition);
1625             style->setDisplay(BLOCK);
1626         }
1627
1628         // Table headers with a text-align of auto will change the text-align to center.
1629         if (e && e->hasTagName(thTag) && style->textAlign() == TAAUTO)
1630             style->setTextAlign(CENTER);
1631
1632         if (e && e->hasTagName(legendTag))
1633             style->setDisplay(BLOCK);
1634
1635         // Mutate the display to BLOCK or TABLE for certain cases, e.g., if someone attempts to
1636         // position or float an inline, compact, or run-in.  Cache the original display, since it
1637         // may be needed for positioned elements that have to compute their static normal flow
1638         // positions.  We also force inline-level roots to be block-level.
1639         if (style->display() != BLOCK && style->display() != TABLE && style->display() != BOX &&
1640             (style->position() == AbsolutePosition || style->position() == FixedPosition || style->floating() != FNONE ||
1641              (e && e->document()->documentElement() == e))) {
1642             if (style->display() == INLINE_TABLE)
1643                 style->setDisplay(TABLE);
1644             else if (style->display() == INLINE_BOX)
1645                 style->setDisplay(BOX);
1646             else if (style->display() == LIST_ITEM) {
1647                 // It is a WinIE bug that floated list items lose their bullets, so we'll emulate the quirk,
1648                 // but only in quirks mode.
1649                 if (!m_checker.m_strictParsing && style->floating() != FNONE)
1650                     style->setDisplay(BLOCK);
1651             }
1652             else
1653                 style->setDisplay(BLOCK);
1654         }
1655         
1656         // After performing the display mutation, check table rows.  We do not honor position:relative on
1657         // table rows or cells.  This has been established in CSS2.1 (and caused a crash in containingBlock()
1658         // on some sites).
1659         if ((style->display() == TABLE_HEADER_GROUP || style->display() == TABLE_ROW_GROUP ||
1660              style->display() == TABLE_FOOTER_GROUP || style->display() == TABLE_ROW || style->display() == TABLE_CELL) &&
1661              style->position() == RelativePosition)
1662             style->setPosition(StaticPosition);
1663     }
1664
1665     // Make sure our z-index value is only applied if the object is positioned.
1666     if (style->position() == StaticPosition)
1667         style->setHasAutoZIndex();
1668
1669     // Auto z-index becomes 0 for the root element and transparent objects.  This prevents
1670     // cases where objects that should be blended as a single unit end up with a non-transparent
1671     // object wedged in between them.  Auto z-index also becomes 0 for objects that specify transforms/masks/reflections.
1672     if (style->hasAutoZIndex() && ((e && e->document()->documentElement() == e) || style->opacity() < 1.0f || 
1673         style->hasTransformRelatedProperty() || style->hasMask() || style->boxReflect()))
1674         style->setZIndex(0);
1675     
1676     // Button, legend, input, select and textarea all consider width values of 'auto' to be 'intrinsic'.
1677     // This will be important when we use block flows for all form controls.
1678     if (e && (e->hasTagName(legendTag) || e->hasTagName(buttonTag) || e->hasTagName(inputTag) ||
1679               e->hasTagName(selectTag) || e->hasTagName(textareaTag) || e->hasTagName(datagridTag)
1680 #if ENABLE(WML)
1681               || e->hasTagName(WMLNames::insertedLegendTag)
1682               || e->hasTagName(WMLNames::inputTag)
1683 #endif
1684        )) {
1685         if (style->width().isAuto())
1686             style->setWidth(Length(Intrinsic));
1687
1688         // Textarea considers overflow visible as auto.
1689         if (e && e->hasTagName(textareaTag)) {
1690             style->setOverflowX(style->overflowX() == OVISIBLE ? OAUTO : style->overflowX());
1691             style->setOverflowY(style->overflowY() == OVISIBLE ? OAUTO : style->overflowY());
1692         }
1693     }
1694
1695     // Finally update our text decorations in effect, but don't allow text-decoration to percolate through
1696     // tables, inline blocks, inline tables, or run-ins.
1697     if (style->display() == TABLE || style->display() == INLINE_TABLE || style->display() == RUN_IN
1698         || style->display() == INLINE_BLOCK || style->display() == INLINE_BOX)
1699         style->setTextDecorationsInEffect(style->textDecoration());
1700     else
1701         style->addToTextDecorationsInEffect(style->textDecoration());
1702     
1703     // If either overflow value is not visible, change to auto.
1704     if (style->overflowX() == OMARQUEE && style->overflowY() != OMARQUEE)
1705         style->setOverflowY(OMARQUEE);
1706     else if (style->overflowY() == OMARQUEE && style->overflowX() != OMARQUEE)
1707         style->setOverflowX(OMARQUEE);
1708     else if (style->overflowX() == OVISIBLE && style->overflowY() != OVISIBLE)
1709         style->setOverflowX(OAUTO);
1710     else if (style->overflowY() == OVISIBLE && style->overflowX() != OVISIBLE)
1711         style->setOverflowY(OAUTO);
1712
1713     // Table rows, sections and the table itself will support overflow:hidden and will ignore scroll/auto.
1714     // FIXME: Eventually table sections will support auto and scroll.
1715     if (style->display() == TABLE || style->display() == INLINE_TABLE ||
1716         style->display() == TABLE_ROW_GROUP || style->display() == TABLE_ROW) {
1717         if (style->overflowX() != OVISIBLE && style->overflowX() != OHIDDEN) 
1718             style->setOverflowX(OVISIBLE);
1719         if (style->overflowY() != OVISIBLE && style->overflowY() != OHIDDEN) 
1720             style->setOverflowY(OVISIBLE);
1721     }
1722
1723     // Menulists should have visible overflow
1724     if (style->appearance() == MenulistPart) {
1725         style->setOverflowX(OVISIBLE);
1726         style->setOverflowY(OVISIBLE);
1727     }
1728
1729     // Cull out any useless layers and also repeat patterns into additional layers.
1730     style->adjustBackgroundLayers();
1731     style->adjustMaskLayers();
1732
1733     // Do the same for animations and transitions.
1734     style->adjustAnimations();
1735     style->adjustTransitions();
1736
1737     // Important: Intrinsic margins get added to controls before the theme has adjusted the style, since the theme will
1738     // alter fonts and heights/widths.
1739     if (e && e->isFormControlElement() && style->fontSize() >= 11) {
1740         // Don't apply intrinsic margins to image buttons.  The designer knows how big the images are,
1741         // so we have to treat all image buttons as though they were explicitly sized.
1742         if (!e->hasTagName(inputTag) || static_cast<HTMLInputElement*>(e)->inputType() != HTMLInputElement::IMAGE)
1743             addIntrinsicMargins(style);
1744     }
1745
1746     // Let the theme also have a crack at adjusting the style.
1747     if (style->hasAppearance())
1748         RenderTheme::defaultTheme()->adjustStyle(this, style, e, m_hasUAAppearance, m_borderData, m_backgroundData, m_backgroundColor);
1749
1750 #if ENABLE(SVG)
1751     if (e && e->isSVGElement()) {
1752         // Spec: http://www.w3.org/TR/SVG/masking.html#OverflowProperty
1753         if (style->overflowY() == OSCROLL)
1754             style->setOverflowY(OHIDDEN);
1755         else if (style->overflowY() == OAUTO)
1756             style->setOverflowY(OVISIBLE);
1757
1758         if (style->overflowX() == OSCROLL)
1759             style->setOverflowX(OHIDDEN);
1760         else if (style->overflowX() == OAUTO)
1761             style->setOverflowX(OVISIBLE);
1762
1763         // Only the root <svg> element in an SVG document fragment tree honors css position
1764         if (!(e->hasTagName(SVGNames::svgTag) && e->parentNode() && !e->parentNode()->isSVGElement()))
1765             style->setPosition(RenderStyle::initialPosition());
1766     }
1767 #endif
1768 }
1769
1770 void CSSStyleSelector::updateFont()
1771 {
1772     checkForTextSizeAdjust();
1773     checkForGenericFamilyChange(style(), m_parentStyle);
1774     checkForZoomChange(style(), m_parentStyle);
1775     m_style->font().update(m_fontSelector);
1776     m_fontDirty = false;
1777 }
1778
1779 void CSSStyleSelector::cacheBorderAndBackground()
1780 {
1781     m_hasUAAppearance = m_style->hasAppearance();
1782     if (m_hasUAAppearance) {
1783         m_borderData = m_style->border();
1784         m_backgroundData = *m_style->backgroundLayers();
1785         m_backgroundColor = m_style->backgroundColor();
1786     }
1787 }
1788
1789 PassRefPtr<CSSRuleList> CSSStyleSelector::styleRulesForElement(Element* e, bool authorOnly)
1790 {
1791     return pseudoStyleRulesForElement(e, NOPSEUDO, authorOnly);
1792 }
1793
1794 PassRefPtr<CSSRuleList> CSSStyleSelector::pseudoStyleRulesForElement(Element* e, PseudoId pseudoId, bool authorOnly)
1795 {
1796     if (!e || !e->document()->haveStylesheetsLoaded())
1797         return 0;
1798
1799     m_checker.m_collectRulesOnly = true;
1800
1801     initElement(e);
1802     initForStyleResolve(e, 0, pseudoId);
1803
1804     if (!authorOnly) {
1805         int firstUARule = -1, lastUARule = -1;
1806         // First we match rules from the user agent sheet.
1807         matchUARules(firstUARule, lastUARule);
1808
1809         // Now we check user sheet rules.
1810         if (m_matchAuthorAndUserStyles) {
1811             int firstUserRule = -1, lastUserRule = -1;
1812             matchRules(m_userStyle, firstUserRule, lastUserRule);
1813         }
1814     }
1815
1816     if (m_matchAuthorAndUserStyles) {
1817         // Check the rules in author sheets.
1818         int firstAuthorRule = -1, lastAuthorRule = -1;
1819         matchRules(m_authorStyle, firstAuthorRule, lastAuthorRule);
1820     }
1821
1822     m_checker.m_collectRulesOnly = false;
1823     
1824     return m_ruleList.release();
1825 }
1826
1827 bool CSSStyleSelector::checkSelector(CSSSelector* sel)
1828 {
1829     m_dynamicPseudo = NOPSEUDO;
1830
1831     // Check the selector
1832     SelectorMatch match = m_checker.checkSelector(sel, m_element, &m_selectorAttrs, m_dynamicPseudo, false, false, style(), m_parentStyle);
1833     if (match != SelectorMatches)
1834         return false;
1835
1836     if (m_checker.m_pseudoStyle != NOPSEUDO && m_checker.m_pseudoStyle != m_dynamicPseudo)
1837         return false;
1838
1839     return true;
1840 }
1841
1842 // Recursive check of selectors and combinators
1843 // It can return 3 different values:
1844 // * SelectorMatches         - the selector matches the element e
1845 // * SelectorFailsLocally    - the selector fails for the element e
1846 // * SelectorFailsCompletely - the selector fails for e and any sibling or ancestor of e
1847 CSSStyleSelector::SelectorMatch CSSStyleSelector::SelectorChecker::checkSelector(CSSSelector* sel, Element* e, HashSet<AtomicStringImpl*>* selectorAttrs, PseudoId& dynamicPseudo, bool isSubSelector, bool encounteredLink, RenderStyle* elementStyle, RenderStyle* elementParentStyle) const
1848 {
1849 #if ENABLE(SVG)
1850     // Spec: CSS2 selectors cannot be applied to the (conceptually) cloned DOM tree
1851     // because its contents are not part of the formal document structure.
1852     if (e->isSVGElement() && e->isShadowNode())
1853         return SelectorFailsCompletely;
1854 #endif
1855
1856     // first selector has to match
1857     if (!checkOneSelector(sel, e, selectorAttrs, dynamicPseudo, isSubSelector, elementStyle, elementParentStyle))
1858         return SelectorFailsLocally;
1859
1860     // The rest of the selectors has to match
1861     CSSSelector::Relation relation = sel->relation();
1862
1863     // Prepare next sel
1864     sel = sel->tagHistory();
1865     if (!sel)
1866         return SelectorMatches;
1867
1868     if (relation != CSSSelector::SubSelector)
1869         // Bail-out if this selector is irrelevant for the pseudoStyle
1870         if (m_pseudoStyle != NOPSEUDO && m_pseudoStyle != dynamicPseudo)
1871             return SelectorFailsCompletely;
1872
1873     // Check for nested links.
1874     if (m_matchVisitedPseudoClass && !isSubSelector) {
1875         RenderStyle* currentStyle = elementStyle ? elementStyle : e->renderStyle();
1876         if (currentStyle && currentStyle->insideLink() && e->isLink()) {
1877             if (encounteredLink)
1878                 m_matchVisitedPseudoClass = false; // This link is not relevant to the style being resolved, so disable matching.
1879             else
1880                 encounteredLink = true;
1881         }
1882     }
1883
1884     switch (relation) {
1885         case CSSSelector::Descendant:
1886             while (true) {
1887                 Node* n = e->parentNode();
1888                 if (!n || !n->isElementNode())
1889                     return SelectorFailsCompletely;
1890                 e = static_cast<Element*>(n);
1891                 SelectorMatch match = checkSelector(sel, e, selectorAttrs, dynamicPseudo, false, encounteredLink);
1892                 if (match != SelectorFailsLocally)
1893                     return match;
1894             }
1895             break;
1896         case CSSSelector::Child:
1897         {
1898             Node* n = e->parentNode();
1899             if (!n || !n->isElementNode())
1900                 return SelectorFailsCompletely;
1901             e = static_cast<Element*>(n);
1902             return checkSelector(sel, e, selectorAttrs, dynamicPseudo, false, encounteredLink);
1903         }
1904         case CSSSelector::DirectAdjacent:
1905         {
1906             if (!m_collectRulesOnly && e->parentNode() && e->parentNode()->isElementNode()) {
1907                 RenderStyle* parentStyle = elementStyle ? elementParentStyle : e->parentNode()->renderStyle();
1908                 if (parentStyle)
1909                     parentStyle->setChildrenAffectedByDirectAdjacentRules();
1910             }
1911             Node* n = e->previousSibling();
1912             while (n && !n->isElementNode())
1913                 n = n->previousSibling();
1914             if (!n)
1915                 return SelectorFailsLocally;
1916             e = static_cast<Element*>(n);
1917             m_matchVisitedPseudoClass = false;
1918             return checkSelector(sel, e, selectorAttrs, dynamicPseudo, false, encounteredLink); 
1919         }
1920         case CSSSelector::IndirectAdjacent:
1921             if (!m_collectRulesOnly && e->parentNode() && e->parentNode()->isElementNode()) {
1922                 RenderStyle* parentStyle = elementStyle ? elementParentStyle : e->parentNode()->renderStyle();
1923                 if (parentStyle)
1924                     parentStyle->setChildrenAffectedByForwardPositionalRules();
1925             }
1926             while (true) {
1927                 Node* n = e->previousSibling();
1928                 while (n && !n->isElementNode())
1929                     n = n->previousSibling();
1930                 if (!n)
1931                     return SelectorFailsLocally;
1932                 e = static_cast<Element*>(n);
1933                 m_matchVisitedPseudoClass = false;
1934                 SelectorMatch match = checkSelector(sel, e, selectorAttrs, dynamicPseudo, false, encounteredLink);
1935                 if (match != SelectorFailsLocally)
1936                     return match;
1937             };
1938             break;
1939         case CSSSelector::SubSelector:
1940             // a selector is invalid if something follows a pseudo-element
1941             // We make an exception for scrollbar pseudo elements and allow a set of pseudo classes (but nothing else)
1942             // to follow the pseudo elements.
1943             if ((elementStyle || m_collectRulesOnly) && dynamicPseudo != NOPSEUDO && dynamicPseudo != SELECTION &&
1944                 !((RenderScrollbar::scrollbarForStyleResolve() || dynamicPseudo == SCROLLBAR_CORNER || dynamicPseudo == RESIZER) && sel->m_match == CSSSelector::PseudoClass))
1945                 return SelectorFailsCompletely;
1946             return checkSelector(sel, e, selectorAttrs, dynamicPseudo, true, encounteredLink, elementStyle, elementParentStyle);
1947     }
1948
1949     return SelectorFailsCompletely;
1950 }
1951
1952 static void addLocalNameToSet(HashSet<AtomicStringImpl*>* set, const QualifiedName& qName)
1953 {
1954     set->add(qName.localName().impl());
1955 }
1956
1957 static HashSet<AtomicStringImpl*>* createHtmlCaseInsensitiveAttributesSet()
1958 {
1959     // This is the list of attributes in HTML 4.01 with values marked as "[CI]" or case-insensitive
1960     // Mozilla treats all other values as case-sensitive, thus so do we.
1961     HashSet<AtomicStringImpl*>* attrSet = new HashSet<AtomicStringImpl*>;
1962
1963     addLocalNameToSet(attrSet, accept_charsetAttr);
1964     addLocalNameToSet(attrSet, acceptAttr);
1965     addLocalNameToSet(attrSet, alignAttr);
1966     addLocalNameToSet(attrSet, alinkAttr);
1967     addLocalNameToSet(attrSet, axisAttr);
1968     addLocalNameToSet(attrSet, bgcolorAttr);
1969     addLocalNameToSet(attrSet, charsetAttr);
1970     addLocalNameToSet(attrSet, checkedAttr);
1971     addLocalNameToSet(attrSet, clearAttr);
1972     addLocalNameToSet(attrSet, codetypeAttr);
1973     addLocalNameToSet(attrSet, colorAttr);
1974     addLocalNameToSet(attrSet, compactAttr);
1975     addLocalNameToSet(attrSet, declareAttr);
1976     addLocalNameToSet(attrSet, deferAttr);
1977     addLocalNameToSet(attrSet, dirAttr);
1978     addLocalNameToSet(attrSet, disabledAttr);
1979     addLocalNameToSet(attrSet, enctypeAttr);
1980     addLocalNameToSet(attrSet, faceAttr);
1981     addLocalNameToSet(attrSet, frameAttr);
1982     addLocalNameToSet(attrSet, hreflangAttr);
1983     addLocalNameToSet(attrSet, http_equivAttr);
1984     addLocalNameToSet(attrSet, langAttr);
1985     addLocalNameToSet(attrSet, languageAttr);
1986     addLocalNameToSet(attrSet, linkAttr);
1987     addLocalNameToSet(attrSet, mediaAttr);
1988     addLocalNameToSet(attrSet, methodAttr);
1989     addLocalNameToSet(attrSet, multipleAttr);
1990     addLocalNameToSet(attrSet, nohrefAttr);
1991     addLocalNameToSet(attrSet, noresizeAttr);
1992     addLocalNameToSet(attrSet, noshadeAttr);
1993     addLocalNameToSet(attrSet, nowrapAttr);
1994     addLocalNameToSet(attrSet, readonlyAttr);
1995     addLocalNameToSet(attrSet, relAttr);
1996     addLocalNameToSet(attrSet, revAttr);
1997     addLocalNameToSet(attrSet, rulesAttr);
1998     addLocalNameToSet(attrSet, scopeAttr);
1999     addLocalNameToSet(attrSet, scrollingAttr);
2000     addLocalNameToSet(attrSet, selectedAttr);
2001     addLocalNameToSet(attrSet, shapeAttr);
2002     addLocalNameToSet(attrSet, targetAttr);
2003     addLocalNameToSet(attrSet, textAttr);
2004     addLocalNameToSet(attrSet, typeAttr);
2005     addLocalNameToSet(attrSet, valignAttr);
2006     addLocalNameToSet(attrSet, valuetypeAttr);
2007     addLocalNameToSet(attrSet, vlinkAttr);
2008
2009     return attrSet;
2010 }
2011
2012 static bool htmlAttributeHasCaseInsensitiveValue(const QualifiedName& attr)
2013 {
2014     static HashSet<AtomicStringImpl*>* htmlCaseInsensitiveAttributesSet = createHtmlCaseInsensitiveAttributesSet();
2015     bool isPossibleHTMLAttr = !attr.hasPrefix() && (attr.namespaceURI() == nullAtom);
2016     return isPossibleHTMLAttr && htmlCaseInsensitiveAttributesSet->contains(attr.localName().impl());
2017 }
2018
2019 bool CSSStyleSelector::SelectorChecker::checkOneSelector(CSSSelector* sel, Element* e, HashSet<AtomicStringImpl*>* selectorAttrs, PseudoId& dynamicPseudo, bool isSubSelector, RenderStyle* elementStyle, RenderStyle* elementParentStyle) const
2020 {
2021     if (!e)
2022         return false;
2023
2024     if (sel->hasTag()) {
2025         const AtomicString& selLocalName = sel->m_tag.localName();
2026         if (selLocalName != starAtom && selLocalName != e->localName())
2027             return false;
2028         const AtomicString& selNS = sel->m_tag.namespaceURI();
2029         if (selNS != starAtom && selNS != e->namespaceURI())
2030             return false;
2031     }
2032
2033     if (sel->hasAttribute()) {
2034         if (sel->m_match == CSSSelector::Class)
2035             return e->hasClass() && static_cast<StyledElement*>(e)->classNames().contains(sel->m_value);
2036
2037         if (sel->m_match == CSSSelector::Id)
2038             return e->hasID() && e->getIDAttribute() == sel->m_value;
2039         
2040         const QualifiedName& attr = sel->attribute();
2041
2042         // FIXME: Handle the case were elementStyle is 0.
2043         if (elementStyle && (!e->isStyledElement() || (!static_cast<StyledElement*>(e)->isMappedAttribute(attr) && attr != typeAttr && attr != readonlyAttr))) {
2044             elementStyle->setAffectedByAttributeSelectors(); // Special-case the "type" and "readonly" attributes so input form controls can share style.
2045             if (selectorAttrs)
2046                 selectorAttrs->add(attr.localName().impl());
2047         }
2048
2049         const AtomicString& value = e->getAttribute(attr);
2050         if (value.isNull())
2051             return false; // attribute is not set
2052
2053         bool caseSensitive = !m_documentIsHTML || !htmlAttributeHasCaseInsensitiveValue(attr);
2054
2055         switch (sel->m_match) {
2056         case CSSSelector::Exact:
2057             if (caseSensitive ? sel->m_value != value : !equalIgnoringCase(sel->m_value, value))
2058                 return false;
2059             break;
2060         case CSSSelector::List:
2061         {
2062             // Ignore empty selectors or selectors containing spaces
2063             if (sel->m_value.contains(' ') || sel->m_value.isEmpty())
2064                 return false;
2065
2066             int startSearchAt = 0;
2067             while (true) {
2068                 int foundPos = value.find(sel->m_value, startSearchAt, caseSensitive);
2069                 if (foundPos == -1)
2070                     return false;
2071                 if (foundPos == 0 || value[foundPos-1] == ' ') {
2072                     unsigned endStr = foundPos + sel->m_value.length();
2073                     if (endStr == value.length() || value[endStr] == ' ')
2074                         break; // We found a match.
2075                 }
2076                 
2077                 // No match.  Keep looking.
2078                 startSearchAt = foundPos + 1;
2079             }
2080             break;
2081         }
2082         case CSSSelector::Contain:
2083             if (!value.contains(sel->m_value, caseSensitive) || sel->m_value.isEmpty())
2084                 return false;
2085             break;
2086         case CSSSelector::Begin:
2087             if (!value.startsWith(sel->m_value, caseSensitive) || sel->m_value.isEmpty())
2088                 return false;
2089             break;
2090         case CSSSelector::End:
2091             if (!value.endsWith(sel->m_value, caseSensitive) || sel->m_value.isEmpty())
2092                 return false;
2093             break;
2094         case CSSSelector::Hyphen:
2095             if (value.length() < sel->m_value.length())
2096                 return false;
2097             if (!value.startsWith(sel->m_value, caseSensitive))
2098                 return false;
2099             // It they start the same, check for exact match or following '-':
2100             if (value.length() != sel->m_value.length() && value[sel->m_value.length()] != '-')
2101                 return false;
2102             break;
2103         case CSSSelector::PseudoClass:
2104         case CSSSelector::PseudoElement:
2105         default:
2106             break;
2107         }
2108     }
2109     
2110     if (sel->m_match == CSSSelector::PseudoClass) {
2111         // Handle :not up front.
2112         if (sel->pseudoType() == CSSSelector::PseudoNot) {
2113             // check the simple selector
2114             for (CSSSelector* subSel = sel->simpleSelector(); subSel; subSel = subSel->tagHistory()) {
2115                 // :not cannot nest. I don't really know why this is a
2116                 // restriction in CSS3, but it is, so let's honor it.
2117                 // the parser enforces that this never occurs
2118                 ASSERT(!subSel->simpleSelector());
2119
2120                 if (!checkOneSelector(subSel, e, selectorAttrs, dynamicPseudo, true, elementStyle, elementParentStyle))
2121                     return true;
2122             }
2123         } else if (dynamicPseudo != NOPSEUDO && (RenderScrollbar::scrollbarForStyleResolve() || dynamicPseudo == SCROLLBAR_CORNER || dynamicPseudo == RESIZER)) {
2124             // CSS scrollbars match a specific subset of pseudo classes, and they have specialized rules for each
2125             // (since there are no elements involved).
2126             return checkScrollbarPseudoClass(sel, dynamicPseudo);
2127         } else if (dynamicPseudo == SELECTION) {
2128             if (sel->pseudoType() == CSSSelector::PseudoWindowInactive)
2129                 return !m_document->page()->focusController()->isActive();
2130         }
2131         
2132         // Normal element pseudo class checking.
2133         switch (sel->pseudoType()) {
2134             // Pseudo classes:
2135             case CSSSelector::PseudoNot:
2136                 break; // Already handled up above.
2137             case CSSSelector::PseudoEmpty: {
2138                 bool result = true;
2139                 for (Node* n = e->firstChild(); n; n = n->nextSibling()) {
2140                     if (n->isElementNode()) {
2141                         result = false;
2142                         break;
2143                     } else if (n->isTextNode()) {
2144                         Text* textNode = static_cast<Text*>(n);
2145                         if (!textNode->data().isEmpty()) {
2146                             result = false;
2147                             break;
2148                         }
2149                     }
2150                 }
2151                 if (!m_collectRulesOnly) {
2152                     if (elementStyle)
2153                         elementStyle->setEmptyState(result);
2154                     else if (e->renderStyle() && (e->document()->usesSiblingRules() || e->renderStyle()->unique()))
2155                         e->renderStyle()->setEmptyState(result);
2156                 }
2157                 return result;
2158             }
2159             case CSSSelector::PseudoFirstChild: {
2160                 // first-child matches the first child that is an element
2161                 if (e->parentNode() && e->parentNode()->isElementNode()) {
2162                     bool result = false;
2163                     Node* n = e->previousSibling();
2164                     while (n && !n->isElementNode())
2165                         n = n->previousSibling();
2166                     if (!n)
2167                         result = true;
2168                     if (!m_collectRulesOnly) {
2169                         RenderStyle* childStyle = elementStyle ? elementStyle : e->renderStyle();
2170                         RenderStyle* parentStyle = elementStyle ? elementParentStyle : e->parentNode()->renderStyle();
2171                         if (parentStyle)
2172                             parentStyle->setChildrenAffectedByFirstChildRules();
2173                         if (result && childStyle)
2174                             childStyle->setFirstChildState();
2175                     }
2176                     return result;
2177                 }
2178                 break;
2179             }
2180             case CSSSelector::PseudoFirstOfType: {
2181                 // first-of-type matches the first element of its type
2182                 if (e->parentNode() && e->parentNode()->isElementNode()) {
2183                     bool result = false;
2184                     const QualifiedName& type = e->tagQName();
2185                     Node* n = e->previousSibling();
2186                     while (n) {
2187                         if (n->isElementNode() && static_cast<Element*>(n)->hasTagName(type))
2188                             break;
2189                         n = n->previousSibling();
2190                     }
2191                     if (!n)
2192                         result = true;
2193                     if (!m_collectRulesOnly) {
2194                         RenderStyle* parentStyle = elementStyle ? elementParentStyle : e->parentNode()->renderStyle();
2195                         if (parentStyle)
2196                             parentStyle->setChildrenAffectedByForwardPositionalRules();
2197                     }
2198                     return result;
2199                 }
2200                 break;
2201             }
2202             case CSSSelector::PseudoLastChild: {
2203                 // last-child matches the last child that is an element
2204                 if (Element* parentElement = e->parentElement()) {
2205                     bool result = false;
2206                     if (parentElement->isFinishedParsingChildren()) {
2207                         Node* n = e->nextSibling();
2208                         while (n && !n->isElementNode())
2209                             n = n->nextSibling();
2210                         if (!n)
2211                             result = true;
2212                     }
2213                     if (!m_collectRulesOnly) {
2214                         RenderStyle* childStyle = elementStyle ? elementStyle : e->renderStyle();
2215                         RenderStyle* parentStyle = elementStyle ? elementParentStyle : parentElement->renderStyle();
2216                         if (parentStyle)
2217                             parentStyle->setChildrenAffectedByLastChildRules();
2218                         if (result && childStyle)
2219                             childStyle->setLastChildState();
2220                     }
2221                     return result;
2222                 }
2223                 break;
2224             }
2225             case CSSSelector::PseudoLastOfType: {
2226                 // last-of-type matches the last element of its type
2227                 if (Element* parentElement = e->parentElement()) {
2228                     if (!m_collectRulesOnly) {
2229                         RenderStyle* parentStyle = elementStyle ? elementParentStyle : parentElement->renderStyle();
2230                         if (parentStyle)
2231                             parentStyle->setChildrenAffectedByBackwardPositionalRules();
2232                     }
2233                     if (!parentElement->isFinishedParsingChildren())
2234                         return false;
2235                     bool result = false;
2236                     const QualifiedName& type = e->tagQName();
2237                     Node* n = e->nextSibling();
2238                     while (n) {
2239                         if (n->isElementNode() && static_cast<Element*>(n)->hasTagName(type))
2240                             break;
2241                         n = n->nextSibling();
2242                     }
2243                     if (!n)
2244                         result = true;
2245                     return result;
2246                 }
2247                 break;
2248             }
2249             case CSSSelector::PseudoOnlyChild: {
2250                 if (Element* parentElement = e->parentElement()) {
2251                     bool firstChild = false;
2252                     bool lastChild = false;
2253                     
2254                     Node* n = e->previousSibling();
2255                     while (n && !n->isElementNode())
2256                         n = n->previousSibling();
2257                     if (!n)
2258                         firstChild = true;
2259                     if (firstChild && parentElement->isFinishedParsingChildren()) {
2260                         n = e->nextSibling();
2261                         while (n && !n->isElementNode())
2262                             n = n->nextSibling();
2263                         if (!n)
2264                             lastChild = true;
2265                     }
2266                     if (!m_collectRulesOnly) {
2267                         RenderStyle* childStyle = elementStyle ? elementStyle : e->renderStyle();
2268                         RenderStyle* parentStyle = elementStyle ? elementParentStyle : parentElement->renderStyle();
2269                         if (parentStyle) {
2270                             parentStyle->setChildrenAffectedByFirstChildRules();
2271                             parentStyle->setChildrenAffectedByLastChildRules();
2272                         }
2273                         if (firstChild && childStyle)
2274                             childStyle->setFirstChildState();
2275                         if (lastChild && childStyle)
2276                             childStyle->setLastChildState();
2277                     }
2278                     return firstChild && lastChild;
2279                 }
2280                 break;
2281             }
2282             case CSSSelector::PseudoOnlyOfType: {
2283                 // FIXME: This selector is very slow.
2284                 if (Element* parentElement = e->parentElement()) {
2285                     if (!m_collectRulesOnly) {
2286                         RenderStyle* parentStyle = elementStyle ? elementParentStyle : parentElement->renderStyle();
2287                         if (parentStyle) {
2288                             parentStyle->setChildrenAffectedByForwardPositionalRules();
2289                             parentStyle->setChildrenAffectedByBackwardPositionalRules();
2290                         }
2291                     }
2292                     if (!parentElement->isFinishedParsingChildren())
2293                         return false;
2294                     bool firstChild = false;
2295                     bool lastChild = false;
2296                     const QualifiedName& type = e->tagQName();
2297                     Node* n = e->previousSibling();
2298                     while (n) {
2299                         if (n->isElementNode() && static_cast<Element*>(n)->hasTagName(type))
2300                             break;
2301                         n = n->previousSibling();
2302                     }
2303                     if (!n)
2304                         firstChild = true;
2305                     if (firstChild) {
2306                         n = e->nextSibling();
2307                         while (n) {
2308                             if (n->isElementNode() && static_cast<Element*>(n)->hasTagName(type))
2309                                 break;
2310                             n = n->nextSibling();
2311                         }
2312                         if (!n)
2313                             lastChild = true;
2314                     }
2315                     return firstChild && lastChild;
2316                 }
2317                 break;
2318             }
2319             case CSSSelector::PseudoNthChild: {
2320                 if (!sel->parseNth())
2321                     break;
2322                 if (Element* parentElement = e->parentElement()) {
2323                     int count = 1;
2324                     Node* n = e->previousSibling();
2325                     while (n) {
2326                         if (n->isElementNode()) {
2327                             RenderStyle* s = n->renderStyle();
2328                             unsigned index = s ? s->childIndex() : 0;
2329                             if (index) {
2330                                 count += index;
2331                                 break;
2332                             }
2333                             count++;
2334                         }
2335                         n = n->previousSibling();
2336                     }
2337                     
2338                     if (!m_collectRulesOnly) {
2339                         RenderStyle* childStyle = elementStyle ? elementStyle : e->renderStyle();
2340                         RenderStyle* parentStyle = elementStyle ? elementParentStyle : parentElement->renderStyle();
2341                         if (childStyle)
2342                             childStyle->setChildIndex(count);
2343                         if (parentStyle)
2344                             parentStyle->setChildrenAffectedByForwardPositionalRules();
2345                     }
2346                     
2347                     if (sel->matchNth(count))
2348                         return true;
2349                 }
2350                 break;
2351             }
2352             case CSSSelector::PseudoNthOfType: {
2353                 if (!sel->parseNth())
2354                     break;
2355                 if (Element* parentElement = e->parentElement()) {
2356                     int count = 1;
2357                     const QualifiedName& type = e->tagQName();
2358                     Node* n = e->previousSibling();
2359                     while (n) {
2360                         if (n->isElementNode() && static_cast<Element*>(n)->hasTagName(type))
2361                             count++;
2362                         n = n->previousSibling();
2363                     }
2364                     
2365                     if (!m_collectRulesOnly) {
2366                         RenderStyle* parentStyle = elementStyle ? elementParentStyle : parentElement->renderStyle();
2367                         if (parentStyle)
2368                             parentStyle->setChildrenAffectedByForwardPositionalRules();
2369                     }
2370
2371                     if (sel->matchNth(count))
2372                         return true;
2373                 }
2374                 break;
2375             }
2376             case CSSSelector::PseudoNthLastChild: {
2377                 if (!sel->parseNth())
2378                     break;
2379                 if (Element* parentElement = e->parentElement()) {
2380                     if (!m_collectRulesOnly) {
2381                         RenderStyle* parentStyle = elementStyle ? elementParentStyle : parentElement->renderStyle();
2382                         if (parentStyle)
2383                             parentStyle->setChildrenAffectedByBackwardPositionalRules();
2384                     }
2385                     if (!parentElement->isFinishedParsingChildren())
2386                         return false;
2387                     int count = 1;
2388                     Node* n = e->nextSibling();
2389                     while (n) {
2390                         if (n->isElementNode())
2391                             count++;
2392                         n = n->nextSibling();
2393                     }
2394                     if (sel->matchNth(count))
2395                         return true;
2396                 }
2397                 break;
2398             }
2399             case CSSSelector::PseudoNthLastOfType: {
2400                 if (!sel->parseNth())
2401                     break;
2402                 if (Element* parentElement = e->parentElement()) {
2403                     if (!m_collectRulesOnly) {
2404                         RenderStyle* parentStyle = elementStyle ? elementParentStyle : parentElement->renderStyle();
2405                         if (parentStyle)
2406                             parentStyle->setChildrenAffectedByBackwardPositionalRules();
2407                     }
2408                     if (!parentElement->isFinishedParsingChildren())
2409                         return false;
2410                     int count = 1;
2411                     const QualifiedName& type = e->tagQName();
2412                     Node* n = e->nextSibling();
2413                     while (n) {
2414                         if (n->isElementNode() && static_cast<Element*>(n)->hasTagName(type))
2415                             count++;
2416                         n = n->nextSibling();
2417                     }
2418                     if (sel->matchNth(count))
2419                         return true;
2420                 }
2421                 break;
2422             }
2423             case CSSSelector::PseudoTarget:
2424                 if (e == e->document()->cssTarget())
2425                     return true;
2426                 break;
2427             case CSSSelector::PseudoAnyLink:
2428                 if (e && e->isLink())
2429                     return true;
2430                 break;
2431             case CSSSelector::PseudoAutofill: {
2432                 if (!e || !e->isFormControlElement())
2433                     break;
2434                 if (InputElement* inputElement = toInputElement(e))
2435                     return inputElement->isAutofilled();
2436                 break;
2437             }
2438             case CSSSelector::PseudoLink:
2439                 if (e && e->isLink())
2440                     return !m_matchVisitedPseudoClass;
2441                 break;
2442             case CSSSelector::PseudoVisited:
2443                 if (e && e->isLink())
2444                     return m_matchVisitedPseudoClass;
2445                 break;
2446             case CSSSelector::PseudoDrag: {
2447                 if (elementStyle)
2448                     elementStyle->setAffectedByDragRules(true);
2449                 else if (e->renderStyle())
2450                     e->renderStyle()->setAffectedByDragRules(true);
2451                 if (e->renderer() && e->renderer()->isDragging())
2452                     return true;
2453                 break;
2454             }
2455             case CSSSelector::PseudoFocus:
2456                 if (e && e->focused() && e->document()->frame()->selection()->isFocusedAndActive())
2457                     return true;
2458                 break;
2459             case CSSSelector::PseudoHover: {
2460                 // If we're in quirks mode, then hover should never match anchors with no
2461                 // href and *:hover should not match anything.  This is important for sites like wsj.com.
2462                 if (m_strictParsing || isSubSelector || (sel->hasTag() && !e->hasTagName(aTag)) || e->isLink()) {
2463                     if (elementStyle)
2464                         elementStyle->setAffectedByHoverRules(true);
2465                     else if (e->renderStyle())
2466                         e->renderStyle()->setAffectedByHoverRules(true);
2467                     if (e->hovered())
2468                         return true;
2469                 }
2470                 break;
2471             }
2472             case CSSSelector::PseudoActive:
2473                 // If we're in quirks mode, then :active should never match anchors with no
2474                 // href and *:active should not match anything. 
2475                 if (m_strictParsing || isSubSelector || (sel->hasTag() && !e->hasTagName(aTag)) || e->isLink()) {
2476                     if (elementStyle)
2477                         elementStyle->setAffectedByActiveRules(true);
2478                     else if (e->renderStyle())
2479                         e->renderStyle()->setAffectedByActiveRules(true);
2480                     if (e->active())
2481                         return true;
2482                 }
2483                 break;
2484             case CSSSelector::PseudoEnabled:
2485                 if (e && e->isFormControlElement())
2486                     return e->isEnabledFormControl();
2487                 break;
2488             case CSSSelector::PseudoFullPageMedia:
2489                 return e && e->document() && e->document()->isMediaDocument();
2490                 break;
2491             case CSSSelector::PseudoDefault:
2492                 return e && e->isDefaultButtonForForm();
2493             case CSSSelector::PseudoDisabled:
2494                 if (e && e->isFormControlElement())
2495                     return !e->isEnabledFormControl();
2496                 break;
2497             case CSSSelector::PseudoReadOnly: {
2498                 if (!e || !e->isFormControlElement())
2499                     return false;
2500                 return e->isTextFormControl() && e->isReadOnlyFormControl();
2501             }
2502             case CSSSelector::PseudoReadWrite: {
2503                 if (!e || !e->isFormControlElement())
2504                     return false;
2505                 return e->isTextFormControl() && !e->isReadOnlyFormControl();
2506             }
2507             case CSSSelector::PseudoOptional:
2508                 return e && e->isOptionalFormControl();
2509             case CSSSelector::PseudoRequired:
2510                 return e && e->isRequiredFormControl();
2511             case CSSSelector::PseudoValid: {
2512                 if (!e)
2513                     return false;
2514                 e->document()->setContainsValidityStyleRules();
2515                 return e->willValidate() && e->isValidFormControlElement();
2516             } case CSSSelector::PseudoInvalid: {
2517                 if (!e)
2518                     return false;
2519                 e->document()->setContainsValidityStyleRules();
2520                 return e->willValidate() && !e->isValidFormControlElement();
2521             } case CSSSelector::PseudoChecked: {
2522                 if (!e || !e->isFormControlElement())
2523                     break;
2524                 // Even though WinIE allows checked and indeterminate to co-exist, the CSS selector spec says that
2525                 // you can't be both checked and indeterminate.  We will behave like WinIE behind the scenes and just
2526                 // obey the CSS spec here in the test for matching the pseudo.
2527                 InputElement* inputElement = toInputElement(e);
2528                 if (inputElement && inputElement->isChecked() && !inputElement->isIndeterminate())
2529                     return true;
2530                 break;
2531             }
2532             case CSSSelector::PseudoIndeterminate: {
2533                 if (!e || !e->isFormControlElement())
2534                     break;
2535                 InputElement* inputElement = toInputElement(e);
2536                 if (inputElement && inputElement->isIndeterminate())
2537                     return true;
2538                 break;
2539             }
2540             case CSSSelector::PseudoRoot:
2541                 if (e == e->document()->documentElement())
2542                     return true;
2543                 break;
2544             case CSSSelector::PseudoLang: {
2545                 Node* n = e;
2546                 AtomicString value;
2547                 // The language property is inherited, so we iterate over the parents
2548                 // to find the first language.
2549                 while (n && value.isEmpty()) {
2550                     if (n->isElementNode()) {
2551                         // Spec: xml:lang takes precedence -- http://www.w3.org/TR/xhtml1/#C_7
2552                         value = static_cast<Element*>(n)->fastGetAttribute(XMLNames::langAttr);
2553                         if (value.isEmpty())
2554                             value = static_cast<Element*>(n)->fastGetAttribute(langAttr);
2555                     } else if (n->isDocumentNode())
2556                         // checking the MIME content-language
2557                         value = static_cast<Document*>(n)->contentLanguage();
2558
2559                     n = n->parent();
2560                 }
2561                 const AtomicString& argument = sel->argument();
2562                 if (value.isEmpty() || !value.startsWith(argument, false))
2563                     break;
2564                 if (value.length() != argument.length() && value[argument.length()] != '-')
2565                     break;
2566                 return true;
2567             }
2568             case CSSSelector::PseudoUnknown:
2569             case CSSSelector::PseudoNotParsed:
2570             default:
2571                 ASSERT_NOT_REACHED();
2572                 break;
2573         }
2574         return false;
2575     }
2576     if (sel->m_match == CSSSelector::PseudoElement) {
2577         if (!elementStyle && !m_collectRulesOnly)
2578             return false;
2579
2580         PseudoId pseudoId = CSSSelector::pseudoId(sel->pseudoType());
2581         if (pseudoId == FIRST_LETTER) {
2582             if (Document* document = e->document())
2583                 document->setUsesFirstLetterRules(true);
2584         }
2585         if (pseudoId != NOPSEUDO) {
2586             dynamicPseudo = pseudoId;
2587             return true;
2588         }
2589         ASSERT_NOT_REACHED();
2590         return false;
2591     }
2592     // ### add the rest of the checks...
2593     return true;
2594 }
2595
2596 bool CSSStyleSelector::SelectorChecker::checkScrollbarPseudoClass(CSSSelector* sel, PseudoId&) const
2597 {
2598     RenderScrollbar* scrollbar = RenderScrollbar::scrollbarForStyleResolve();
2599     ScrollbarPart part = RenderScrollbar::partForStyleResolve();
2600
2601     // FIXME: This is a temporary hack for resizers and scrollbar corners.  Eventually :window-inactive should become a real
2602     // pseudo class and just apply to everything.
2603     if (sel->pseudoType() == CSSSelector::PseudoWindowInactive)
2604         return !m_document->page()->focusController()->isActive();
2605     
2606     if (!scrollbar)
2607         return false;
2608         
2609     ASSERT(sel->m_match == CSSSelector::PseudoClass);
2610     switch (sel->pseudoType()) {
2611         case CSSSelector::PseudoEnabled:
2612             return scrollbar->enabled();
2613         case CSSSelector::PseudoDisabled:
2614             return !scrollbar->enabled();
2615         case CSSSelector::PseudoHover: {
2616             ScrollbarPart hoveredPart = scrollbar->hoveredPart();
2617             if (part == ScrollbarBGPart)
2618                 return hoveredPart != NoPart;
2619             if (part == TrackBGPart)
2620                 return hoveredPart == BackTrackPart || hoveredPart == ForwardTrackPart || hoveredPart == ThumbPart;
2621             return part == hoveredPart;
2622         }
2623         case CSSSelector::PseudoActive: {
2624             ScrollbarPart pressedPart = scrollbar->pressedPart();
2625             if (part == ScrollbarBGPart)
2626                 return pressedPart != NoPart;
2627             if (part == TrackBGPart)
2628                 return pressedPart == BackTrackPart || pressedPart == ForwardTrackPart || pressedPart == ThumbPart;
2629             return part == pressedPart;
2630         }
2631         case CSSSelector::PseudoHorizontal:
2632             return scrollbar->orientation() == HorizontalScrollbar;
2633         case CSSSelector::PseudoVertical:
2634             return scrollbar->orientation() == VerticalScrollbar;
2635         case CSSSelector::PseudoDecrement:
2636             return part == BackButtonStartPart || part == BackButtonEndPart || part == BackTrackPart;
2637         case CSSSelector::PseudoIncrement:
2638             return part == ForwardButtonStartPart || part == ForwardButtonEndPart || part == ForwardTrackPart;
2639         case CSSSelector::PseudoStart:
2640             return part == BackButtonStartPart || part == ForwardButtonStartPart || part == BackTrackPart;
2641         case CSSSelector::PseudoEnd:
2642             return part == BackButtonEndPart || part == ForwardButtonEndPart || part == ForwardTrackPart;
2643         case CSSSelector::PseudoDoubleButton: {
2644             ScrollbarButtonsPlacement buttonsPlacement = scrollbar->theme()->buttonsPlacement();
2645             if (part == BackButtonStartPart || part == ForwardButtonStartPart || part == BackTrackPart)
2646                 return buttonsPlacement == ScrollbarButtonsDoubleStart || buttonsPlacement == ScrollbarButtonsDoubleBoth;
2647             if (part == BackButtonEndPart || part == ForwardButtonEndPart || part == ForwardTrackPart)
2648                 return buttonsPlacement == ScrollbarButtonsDoubleEnd || buttonsPlacement == ScrollbarButtonsDoubleBoth;
2649             return false;
2650         } 
2651         case CSSSelector::PseudoSingleButton: {
2652             ScrollbarButtonsPlacement buttonsPlacement = scrollbar->theme()->buttonsPlacement();
2653             if (part == BackButtonStartPart || part == ForwardButtonEndPart || part == BackTrackPart || part == ForwardTrackPart)
2654                 return buttonsPlacement == ScrollbarButtonsSingle;
2655             return false;
2656         }
2657         case CSSSelector::PseudoNoButton: {
2658             ScrollbarButtonsPlacement buttonsPlacement = scrollbar->theme()->buttonsPlacement();
2659             if (part == BackTrackPart)
2660                 return buttonsPlacement == ScrollbarButtonsNone || buttonsPlacement == ScrollbarButtonsDoubleEnd;
2661             if (part == ForwardTrackPart)
2662                 return buttonsPlacement == ScrollbarButtonsNone || buttonsPlacement == ScrollbarButtonsDoubleStart;
2663             return false;
2664         }
2665         case CSSSelector::PseudoCornerPresent:
2666             return scrollbar->client()->scrollbarCornerPresent();
2667         default:
2668             return false;
2669     }
2670 }
2671
2672 void CSSStyleSelector::addVariables(CSSVariablesRule* variables)
2673 {
2674     CSSVariablesDeclaration* decl = variables->variables();
2675     if (!decl)
2676         return;
2677     unsigned size = decl->length();
2678     for (unsigned i = 0; i < size; ++i) {
2679         String name = decl->item(i);
2680         m_variablesMap.set(name, variables);
2681     }
2682 }
2683
2684 CSSValue* CSSStyleSelector::resolveVariableDependentValue(CSSVariableDependentValue*)
2685 {
2686     return 0;
2687 }
2688
2689 // -----------------------------------------------------------------
2690
2691 CSSRuleSet::CSSRuleSet()
2692 {
2693     m_universalRules = 0;
2694     m_pageRules = 0;
2695     m_ruleCount = 0;
2696     m_pageRuleCount = 0;
2697 }
2698
2699 CSSRuleSet::~CSSRuleSet()
2700
2701     deleteAllValues(m_idRules);
2702     deleteAllValues(m_classRules);
2703     deleteAllValues(m_tagRules);
2704
2705     delete m_universalRules; 
2706     delete m_pageRules;
2707 }
2708
2709
2710 void CSSRuleSet::addToRuleSet(AtomicStringImpl* key, AtomRuleMap& map,
2711                               CSSStyleRule* rule, CSSSelector* sel)
2712 {
2713     if (!key) return;
2714     CSSRuleDataList* rules = map.get(key);
2715     if (!rules) {
2716         rules = new CSSRuleDataList(m_ruleCount++, rule, sel);
2717         map.set(key, rules);
2718     } else
2719         rules->append(m_ruleCount++, rule, sel);
2720 }
2721
2722 void CSSRuleSet::addRule(CSSStyleRule* rule, CSSSelector* sel)
2723 {
2724     if (sel->m_match == CSSSelector::Id) {
2725         addToRuleSet(sel->m_value.impl(), m_idRules, rule, sel);
2726         return;
2727     }
2728     if (sel->m_match == CSSSelector::Class) {
2729         addToRuleSet(sel->m_value.impl(), m_classRules, rule, sel);
2730         return;
2731     }
2732      
2733     const AtomicString& localName = sel->m_tag.localName();
2734     if (localName != starAtom) {
2735         addToRuleSet(localName.impl(), m_tagRules, rule, sel);
2736         return;
2737     }
2738     
2739     // Just put it in the universal rule set.
2740     if (!m_universalRules)
2741         m_universalRules = new CSSRuleDataList(m_ruleCount++, rule, sel);
2742     else
2743         m_universalRules->append(m_ruleCount++, rule, sel);
2744 }
2745
2746 void CSSRuleSet::addPageRule(CSSStyleRule* rule, CSSSelector* sel)
2747 {
2748     if (!m_pageRules)
2749         m_pageRules = new CSSRuleDataList(m_pageRuleCount++, rule, sel);
2750     else
2751         m_pageRules->append(m_pageRuleCount++, rule, sel);
2752 }
2753
2754 void CSSRuleSet::addRulesFromSheet(CSSStyleSheet* sheet, const MediaQueryEvaluator& medium, CSSStyleSelector* styleSelector)
2755 {
2756     if (!sheet)
2757         return;
2758
2759     // No media implies "all", but if a media list exists it must
2760     // contain our current medium
2761     if (sheet->media() && !medium.eval(sheet->media(), styleSelector))
2762         return; // the style sheet doesn't apply
2763
2764     int len = sheet->length();
2765
2766     for (int i = 0; i < len; i++) {
2767         StyleBase* item = sheet->item(i);
2768         if (item->isStyleRule()) {
2769             if (item->isPageRule()) {
2770                 CSSPageRule* pageRule = static_cast<CSSPageRule*>(item);
2771                 addPageRule(pageRule, pageRule->selectorList().first());
2772             } else {
2773                 CSSStyleRule* rule = static_cast<CSSStyleRule*>(item);
2774                 for (CSSSelector* s = rule->selectorList().first(); s; s = CSSSelectorList::next(s))
2775                     addRule(rule, s);
2776             }
2777         }
2778         else if (item->isImportRule()) {
2779             CSSImportRule* import = static_cast<CSSImportRule*>(item);
2780             if (!import->media() || medium.eval(import->media(), styleSelector))
2781                 addRulesFromSheet(import->styleSheet(), medium, styleSelector);
2782         }
2783         else if (item->isMediaRule()) {
2784             CSSMediaRule* r = static_cast<CSSMediaRule*>(item);
2785             CSSRuleList* rules = r->cssRules();
2786
2787             if ((!r->media() || medium.eval(r->media(), styleSelector)) && rules) {
2788                 // Traverse child elements of the @media rule.
2789                 for (unsigned j = 0; j < rules->length(); j++) {
2790                     CSSRule *childItem = rules->item(j);
2791                     if (childItem->isStyleRule()) {
2792                         // It is a StyleRule, so append it to our list
2793                         CSSStyleRule* rule = static_cast<CSSStyleRule*>(childItem);
2794                         for (CSSSelector* s = rule->selectorList().first(); s; s = CSSSelectorList::next(s))
2795                             addRule(rule, s);
2796                     } else if (childItem->isFontFaceRule() && styleSelector) {
2797                         // Add this font face to our set.
2798                         const CSSFontFaceRule* fontFaceRule = static_cast<CSSFontFaceRule*>(childItem);
2799                         styleSelector->fontSelector()->addFontFaceRule(fontFaceRule);
2800                     } else if (childItem->isKeyframesRule() && styleSelector) {
2801                         // Add this keyframe rule to our set.
2802                         styleSelector->addKeyframeStyle(static_cast<WebKitCSSKeyframesRule*>(childItem));
2803                     }
2804                 }   // for rules
2805             }   // if rules
2806         } else if (item->isFontFaceRule() && styleSelector) {
2807             // Add this font face to our set.
2808             const CSSFontFaceRule* fontFaceRule = static_cast<CSSFontFaceRule*>(item);
2809             styleSelector->fontSelector()->addFontFaceRule(fontFaceRule);
2810         } else if (item->isVariablesRule()) {
2811             // Evaluate the media query and make sure it matches.
2812             CSSVariablesRule* variables = static_cast<CSSVariablesRule*>(item);
2813             if (!variables->media() || medium.eval(variables->media(), styleSelector))
2814                 styleSelector->addVariables(variables);
2815         } else if (item->isKeyframesRule())
2816             styleSelector->addKeyframeStyle(static_cast<WebKitCSSKeyframesRule*>(item));
2817     }
2818 }
2819
2820 // -------------------------------------------------------------------------------------
2821 // this is mostly boring stuff on how to apply a certain rule to the renderstyle...
2822
2823 static Length convertToLength(CSSPrimitiveValue* primitiveValue, RenderStyle* style, RenderStyle* rootStyle, double multiplier = 1, bool *ok = 0)
2824 {
2825     // This function is tolerant of a null style value. The only place style is used is in
2826     // length measurements, like 'ems' and 'px'. And in those cases style is only used
2827     // when the units are EMS or EXS. So we will just fail in those cases.
2828     Length l;
2829     if (!primitiveValue) {
2830         if (ok)
2831             *ok = false;
2832     } else {
2833         int type = primitiveValue->primitiveType();
2834         
2835         if (!style && (type == CSSPrimitiveValue::CSS_EMS || type == CSSPrimitiveValue::CSS_EXS || type == CSSPrimitiveValue::CSS_REMS)) {
2836             if (ok)
2837                 *ok = false;
2838         } else if (CSSPrimitiveValue::isUnitTypeLength(type))
2839             l = Length(primitiveValue->computeLengthIntForLength(style, rootStyle, multiplier), Fixed);
2840         else if (type == CSSPrimitiveValue::CSS_PERCENTAGE)
2841             l = Length(primitiveValue->getDoubleValue(), Percent);
2842         else if (type == CSSPrimitiveValue::CSS_NUMBER)
2843             l = Length(primitiveValue->getDoubleValue() * 100.0, Percent);
2844         else if (ok)
2845             *ok = false;
2846     }
2847     return l;
2848 }
2849
2850 template <bool applyFirst>
2851 void CSSStyleSelector::applyDeclarations(bool isImportant, int startIndex, int endIndex)
2852 {
2853     if (startIndex == -1)
2854         return;
2855
2856     for (int i = startIndex; i <= endIndex; i++) {
2857         CSSMutableStyleDeclaration* decl = m_matchedDecls[i];
2858         CSSMutableStyleDeclaration::const_iterator end = decl->end();
2859         for (CSSMutableStyleDeclaration::const_iterator it = decl->begin(); it != end; ++it) {
2860             const CSSProperty& current = *it;
2861             if (isImportant == current.isImportant()) {
2862                 int property = current.id();
2863
2864                 if (applyFirst) {
2865                     COMPILE_ASSERT(firstCSSProperty == CSSPropertyColor, CSS_color_is_first_property);
2866                     COMPILE_ASSERT(CSSPropertyZoom == CSSPropertyColor + 10, CSS_zoom_is_end_of_first_prop_range);
2867                     COMPILE_ASSERT(CSSPropertyLineHeight == CSSPropertyZoom + 1, CSS_line_height_is_after_zoom);
2868
2869                     // give special priority to font-xxx, color properties, etc
2870                     if (property <= CSSPropertyLineHeight) {
2871                         // we apply line-height later
2872                         if (property == CSSPropertyLineHeight)
2873                             m_lineHeightValue = current.value(); 
2874                         else 
2875                             applyProperty(current.id(), current.value());
2876                     }
2877                 } else {
2878                     if (property > CSSPropertyLineHeight)
2879                         applyProperty(current.id(), current.value());
2880                 }
2881             }
2882         }
2883     }
2884 }
2885
2886 static void applyCounterList(RenderStyle* style, CSSValueList* list, bool isReset)
2887 {
2888     CounterDirectiveMap& map = style->accessCounterDirectives();
2889     typedef CounterDirectiveMap::iterator Iterator;
2890
2891     Iterator end = map.end();
2892     for (Iterator it = map.begin(); it != end; ++it)
2893         if (isReset)
2894             it->second.m_reset = false;
2895         else
2896             it->second.m_increment = false;
2897
2898     int length = list ? list->length() : 0;
2899     for (int i = 0; i < length; ++i) {
2900         Pair* pair = static_cast<CSSPrimitiveValue*>(list->itemWithoutBoundsCheck(i))->getPairValue();
2901         AtomicString identifier = static_cast<CSSPrimitiveValue*>(pair->first())->getStringValue();
2902         // FIXME: What about overflow?
2903         int value = static_cast<CSSPrimitiveValue*>(pair->second())->getIntValue();
2904         CounterDirectives& directives = map.add(identifier.impl(), CounterDirectives()).first->second;
2905         if (isReset) {
2906             directives.m_reset = true;
2907             directives.m_resetValue = value;
2908         } else {
2909             if (directives.m_increment)
2910                 directives.m_incrementValue += value;
2911             else {
2912                 directives.m_increment = true;
2913                 directives.m_incrementValue = value;
2914             }
2915         }
2916     }
2917 }
2918
2919 void CSSStyleSelector::applyPropertyToStyle(int id, CSSValue *value, RenderStyle* style)
2920 {
2921     initElement(0);
2922     initForStyleResolve(0, style);
2923     m_style = style;
2924     applyProperty(id, value);
2925 }
2926
2927 inline bool isValidVisitedLinkProperty(int id)
2928 {
2929     switch(static_cast<CSSPropertyID>(id)) {
2930         case CSSPropertyBackgroundColor:
2931         case CSSPropertyBorderLeftColor:
2932         case CSSPropertyBorderRightColor:
2933         case CSSPropertyBorderTopColor:
2934         case CSSPropertyBorderBottomColor:
2935         case CSSPropertyColor:
2936         case CSSPropertyOutlineColor:
2937         case CSSPropertyWebkitColumnRuleColor:
2938         case CSSPropertyWebkitTextFillColor:
2939         case CSSPropertyWebkitTextStrokeColor:
2940         // Also allow shorthands so that inherit/initial still work.
2941         case CSSPropertyBackground:
2942         case CSSPropertyBorderLeft:
2943         case CSSPropertyBorderRight:
2944         case CSSPropertyBorderTop:
2945         case CSSPropertyBorderBottom:
2946         case CSSPropertyOutline:
2947         case CSSPropertyWebkitColumnRule:
2948 #if ENABLE(SVG)
2949         case CSSPropertyFill:
2950         case CSSPropertyStroke:
2951 #endif
2952             return true;
2953         default:
2954             break;
2955     }
2956
2957     return false;
2958 }
2959
2960 void CSSStyleSelector::applyProperty(int id, CSSValue *value)
2961 {
2962     CSSPrimitiveValue* primitiveValue = 0;
2963     if (value->isPrimitiveValue())
2964         primitiveValue = static_cast<CSSPrimitiveValue*>(value);
2965
2966     float zoomFactor = m_style->effectiveZoom();
2967
2968     // SVG handles zooming in a different way compared to CSS. The whole document is scaled instead
2969     // of each individual length value in the render style / tree. CSSPrimitiveValue::computeLength*()
2970     // multiplies each resolved length with the zoom multiplier - so for SVG we need to disable that.
2971     // Though all CSS values that can be applied to outermost <svg> elements (width/height/border/padding...)
2972     // need to respect the scaling. RenderBox (the parent class of RenderSVGRoot) grabs values like
2973     // width/height/border/padding/... from the RenderStyle -> for SVG these values would never scale,
2974     // if we'd pass a 1.0 zoom factor everyhwere. So we only pass a zoom factor of 1.0 for specific
2975     // properties that are NOT allowed to scale within a zoomed SVG document (letter/word-spacing/font-size).
2976     bool useSVGZoomRules = m_element && m_element->isSVGElement();
2977
2978     Length l;
2979     bool apply = false;
2980
2981     unsigned short valueType = value->cssValueType();
2982
2983     bool isInherit = m_parentNode && valueType == CSSValue::CSS_INHERIT;
2984     bool isInitial = valueType == CSSValue::CSS_INITIAL || (!m_parentNode && valueType == CSSValue::CSS_INHERIT);
2985     
2986     // These properties are used to set the correct margins/padding on RTL lists.
2987     if (id == CSSPropertyWebkitMarginStart)
2988         id = m_style->direction() == LTR ? CSSPropertyMarginLeft : CSSPropertyMarginRight;
2989     else if (id == CSSPropertyWebkitPaddingStart)
2990         id = m_style->direction() == LTR ? CSSPropertyPaddingLeft : CSSPropertyPaddingRight;
2991
2992     if (m_checker.m_matchVisitedPseudoClass && !isValidVisitedLinkProperty(id)) {
2993         // Limit the properties that can be applied to only the ones honored by :visited.
2994         return;
2995     }
2996     
2997     // What follows is a list that maps the CSS properties into their corresponding front-end
2998     // RenderStyle values.  Shorthands (e.g. border, background) occur in this list as well and
2999     // are only hit when mapping "inherit" or "initial" into front-end values.
3000     switch (static_cast<CSSPropertyID>(id)) {
3001 // ident only properties
3002     case CSSPropertyBackgroundAttachment:
3003         HANDLE_BACKGROUND_VALUE(attachment, Attachment, value)
3004         return;
3005     case CSSPropertyBackgroundClip:
3006     case CSSPropertyWebkitBackgroundClip:
3007         HANDLE_BACKGROUND_VALUE(clip, Clip, value)
3008         return;
3009     case CSSPropertyWebkitBackgroundComposite:
3010         HANDLE_BACKGROUND_VALUE(composite, Composite, value)
3011         return;
3012     case CSSPropertyBackgroundOrigin:
3013     case CSSPropertyWebkitBackgroundOrigin:
3014         HANDLE_BACKGROUND_VALUE(origin, Origin, value)
3015         return;
3016     case CSSPropertyBackgroundSize:
3017     case CSSPropertyWebkitBackgroundSize:
3018         HANDLE_BACKGROUND_VALUE(size, Size, value)
3019         return;
3020     case CSSPropertyWebkitMaskAttachment:
3021         HANDLE_MASK_VALUE(attachment, Attachment, value)
3022         return;
3023     case CSSPropertyWebkitMaskClip:
3024         HANDLE_MASK_VALUE(clip, Clip, value)
3025         return;
3026     case CSSPropertyWebkitMaskComposite:
3027         HANDLE_MASK_VALUE(composite, Composite, value)
3028         return;
3029     case CSSPropertyWebkitMaskOrigin:
3030         HANDLE_MASK_VALUE(origin, Origin, value)
3031         return;
3032     case CSSPropertyWebkitMaskSize:
3033         HANDLE_MASK_VALUE(size, Size, value)
3034         return;
3035     case CSSPropertyBorderCollapse:
3036         HANDLE_INHERIT_AND_INITIAL(borderCollapse, BorderCollapse)
3037         if (!primitiveValue)
3038             return;
3039         switch (primitiveValue->getIdent()) {
3040             case CSSValueCollapse:
3041                 m_style->setBorderCollapse(true);
3042                 break;
3043             case CSSValueSeparate:
3044                 m_style->setBorderCollapse(false);
3045                 break;
3046             default:
3047                 return;
3048         }
3049         return;
3050     case CSSPropertyBorderTopStyle:
3051         HANDLE_INHERIT_AND_INITIAL_AND_PRIMITIVE_WITH_VALUE(borderTopStyle, BorderTopStyle, BorderStyle)
3052         return;
3053     case CSSPropertyBorderRightStyle:
3054         HANDLE_INHERIT_AND_INITIAL_AND_PRIMITIVE_WITH_VALUE(borderRightStyle, BorderRightStyle, BorderStyle)
3055         return;
3056     case CSSPropertyBorderBottomStyle:
3057         HANDLE_INHERIT_AND_INITIAL_AND_PRIMITIVE_WITH_VALUE(borderBottomStyle, BorderBottomStyle, BorderStyle)
3058         return;
3059     case CSSPropertyBorderLeftStyle:
3060         HANDLE_INHERIT_AND_INITIAL_AND_PRIMITIVE_WITH_VALUE(borderLeftStyle, BorderLeftStyle, BorderStyle)
3061         return;
3062     case CSSPropertyOutlineStyle:
3063         HANDLE_INHERIT_AND_INITIAL_WITH_VALUE(outlineStyle, OutlineStyle, BorderStyle)
3064         if (primitiveValue) {
3065             if (primitiveValue->getIdent() == CSSValueAuto)
3066                 m_style->setOutlineStyle(DOTTED, true);
3067             else
3068                 m_style->setOutlineStyle(*primitiveValue);
3069         }
3070         return;
3071     case CSSPropertyCaptionSide:
3072         HANDLE_INHERIT_AND_INITIAL_AND_PRIMITIVE(captionSide, CaptionSide)
3073         return;
3074     case CSSPropertyClear:
3075         HANDLE_INHERIT_AND_INITIAL_AND_PRIMITIVE(clear, Clear)
3076         return;
3077     case CSSPropertyDirection:
3078         HANDLE_INHERIT_AND_INITIAL_AND_PRIMITIVE(direction, Direction)
3079         return;
3080     case CSSPropertyDisplay:
3081         HANDLE_INHERIT_AND_INITIAL_AND_PRIMITIVE(display, Display)
3082 #if ENABLE(WCSS)
3083         if (primitiveValue) {
3084             if (primitiveValue->getIdent() == CSSValueWapMarquee) {
3085                 // Initialize WAP Marquee style
3086                 m_style->setOverflowX(OMARQUEE);
3087                 m_style->setOverflowY(OMARQUEE);
3088                 m_style->setWhiteSpace(NOWRAP);
3089                 m_style->setMarqueeDirection(MLEFT);
3090                 m_style->setMarqueeSpeed(85); // Normal speed
3091                 m_style->setMarqueeLoopCount(1);
3092                 m_style->setMarqueeBehavior(MSCROLL);
3093
3094                 if (m_parentStyle)
3095                     m_style->setDisplay(m_parentStyle->display());
3096                 else
3097                     m_style->setDisplay(*primitiveValue);
3098             } else
3099                 m_style->setDisplay(*primitiveValue);
3100         }
3101 #endif
3102         return;
3103     case CSSPropertyEmptyCells:
3104         HANDLE_INHERIT_AND_INITIAL_AND_PRIMITIVE(emptyCells, EmptyCells)
3105         return;
3106     case CSSPropertyFloat:
3107         HANDLE_INHERIT_AND_INITIAL_AND_PRIMITIVE(floating, Floating)
3108         return;
3109     case CSSPropertyFontStyle:
3110     {
3111         FontDescription fontDescription = m_style->fontDescription();
3112         if (isInherit)
3113             fontDescription.setItalic(m_parentStyle->fontDescription().italic());
3114         else if (isInitial)
3115             fontDescription.setItalic(false);
3116         else {
3117             if (!primitiveValue)
3118                 return;
3119             switch (primitiveValue->getIdent()) {
3120                 case CSSValueOblique:
3121                 // FIXME: oblique is the same as italic for the moment...
3122                 case CSSValueItalic:
3123                     fontDescription.setItalic(true);
3124                     break;
3125                 case CSSValueNormal:
3126                     fontDescription.setItalic(false);
3127                     break;
3128                 default:
3129                     return;
3130             }
3131         }
3132         if (m_style->setFontDescription(fontDescription))
3133             m_fontDirty = true;
3134         return;
3135     }
3136
3137     case CSSPropertyFontVariant:
3138     {
3139         FontDescription fontDescription = m_style->fontDescription();
3140         if (isInherit) 
3141             fontDescription.setSmallCaps(m_parentStyle->fontDescription().smallCaps());
3142         else if (isInitial)
3143             fontDescription.setSmallCaps(false);
3144         else {
3145             if (!primitiveValue)
3146                 return;
3147             int id = primitiveValue->getIdent();
3148             if (id == CSSValueNormal)
3149                 fontDescription.setSmallCaps(false);
3150             else if (id == CSSValueSmallCaps)
3151                 fontDescription.setSmallCaps(true);
3152             else
3153                 return;
3154         }
3155         if (m_style->setFontDescription(fontDescription))
3156             m_fontDirty = true;
3157         return;
3158     }
3159
3160     case CSSPropertyFontWeight:
3161     {
3162         FontDescription fontDescription = m_style->fontDescription();
3163         if (isInherit)
3164             fontDescription.setWeight(m_parentStyle->fontDescription().weight());
3165         else if (isInitial)
3166             fontDescription.setWeight(FontWeightNormal);
3167         else {
3168             if (!primitiveValue)
3169                 return;
3170             if (primitiveValue->getIdent()) {
3171                 switch (primitiveValue->getIdent()) {
3172                     case CSSValueBolder:
3173                         fontDescription.setWeight(fontDescription.bolderWeight());
3174                         break;
3175                     case CSSValueLighter:
3176                         fontDescription.setWeight(fontDescription.lighterWeight());
3177                         break;
3178                     case CSSValueBold:
3179                     case CSSValue700:
3180                         fontDescription.setWeight(FontWeightBold);
3181                         break;
3182                     case CSSValueNormal:
3183                     case CSSValue400:
3184                         fontDescription.setWeight(FontWeightNormal);
3185                         break;
3186                     case CSSValue900:
3187                         fontDescription.setWeight(FontWeight900);
3188                         break;
3189                     case CSSValue800:
3190                         fontDescription.setWeight(FontWeight800);
3191                         break;
3192                     case CSSValue600:
3193                         fontDescription.setWeight(FontWeight600);
3194                         break;
3195                     case CSSValue500:
3196                         fontDescription.setWeight(FontWeight500);
3197                         break;
3198                     case CSSValue300:
3199                         fontDescription.setWeight(FontWeight300);
3200                         break;
3201                     case CSSValue200:
3202                         fontDescription.setWeight(FontWeight200);
3203                         break;
3204                     case CSSValue100:
3205                         fontDescription.setWeight(FontWeight100);
3206                         break;
3207                     default:
3208                         return;
3209                 }
3210             } else
3211                 ASSERT_NOT_REACHED();
3212         }
3213         if (m_style->setFontDescription(fontDescription))
3214             m_fontDirty = true;
3215         return;
3216     }
3217         
3218     case CSSPropertyListStylePosition:
3219         HANDLE_INHERIT_AND_INITIAL_AND_PRIMITIVE(listStylePosition, ListStylePosition)
3220         return;
3221     case CSSPropertyListStyleType:
3222         HANDLE_INHERIT_AND_INITIAL_AND_PRIMITIVE(listStyleType, ListStyleType)
3223         return;
3224     case CSSPropertyOverflow:
3225     {
3226         if (isInherit) {
3227             m_style->setOverflowX(m_parentStyle->overflowX());
3228             m_style->setOverflowY(m_parentStyle->overflowY());
3229             return;
3230         }
3231         
3232         if (isInitial) {
3233             m_style->setOverflowX(RenderStyle::initialOverflowX());
3234             m_style->setOverflowY(RenderStyle::initialOverflowY());
3235             return;
3236         }
3237             
3238         EOverflow o = *primitiveValue;
3239
3240         m_style->setOverflowX(o);
3241         m_style->setOverflowY(o);
3242         return;
3243     }
3244
3245     case CSSPropertyOverflowX:
3246         HANDLE_INHERIT_AND_INITIAL_AND_PRIMITIVE(overflowX, OverflowX)
3247         return;
3248     case CSSPropertyOverflowY:
3249         HANDLE_INHERIT_AND_INITIAL_AND_PRIMITIVE(overflowY, OverflowY)
3250         return;
3251     case CSSPropertyPageBreakBefore:
3252         HANDLE_INHERIT_AND_INITIAL_AND_PRIMITIVE_WITH_VALUE(pageBreakBefore, PageBreakBefore, PageBreak)
3253         return;
3254     case CSSPropertyPageBreakAfter:
3255         HANDLE_INHERIT_AND_INITIAL_AND_PRIMITIVE_WITH_VALUE(pageBreakAfter, PageBreakAfter, PageBreak)
3256         return;
3257     case CSSPropertyPageBreakInside: {
3258         HANDLE_INHERIT_AND_INITIAL_WITH_VALUE(pageBreakInside, PageBreakInside, PageBreak)
3259         if (!primitiveValue)
3260             return;
3261         EPageBreak pageBreak = *primitiveValue;
3262         if (pageBreak != PBALWAYS)
3263             m_style->setPageBreakInside(pageBreak);
3264         return;
3265     }
3266         
3267     case CSSPropertyPosition:
3268         HANDLE_INHERIT_AND_INITIAL_AND_PRIMITIVE(position, Position)
3269         return;
3270     case CSSPropertyTableLayout: {
3271         HANDLE_INHERIT_AND_INITIAL(tableLayout, TableLayout)
3272
3273         ETableLayout l = *primitiveValue;
3274         if (l == TAUTO)
3275             l = RenderStyle::initialTableLayout();
3276
3277         m_style->setTableLayout(l);
3278         return;
3279     }
3280         
3281     case CSSPropertyUnicodeBidi: 
3282         HANDLE_INHERIT_AND_INITIAL_AND_PRIMITIVE(unicodeBidi, UnicodeBidi)
3283         return;
3284     case CSSPropertyTextTransform: 
3285         HANDLE_INHERIT_AND_INITIAL_AND_PRIMITIVE(textTransform, TextTransform)
3286         return;
3287     case CSSPropertyVisibility:
3288         HANDLE_INHERIT_AND_INITIAL_AND_PRIMITIVE(visibility, Visibility)
3289         return;
3290     case CSSPropertyWhiteSpace:
3291         HANDLE_INHERIT_AND_INITIAL_AND_PRIMITIVE(whiteSpace, WhiteSpace)
3292         return;
3293
3294     case CSSPropertyBackgroundPosition:
3295         HANDLE_BACKGROUND_INHERIT_AND_INITIAL(xPosition, XPosition);
3296         HANDLE_BACKGROUND_INHERIT_AND_INITIAL(yPosition, YPosition);
3297         return;
3298     case CSSPropertyBackgroundPositionX: {
3299         HANDLE_BACKGROUND_VALUE(xPosition, XPosition, value)
3300         return;
3301     }
3302     case CSSPropertyBackgroundPositionY: {
3303         HANDLE_BACKGROUND_VALUE(yPosition, YPosition, value)
3304         return;
3305     }
3306     case CSSPropertyWebkitMaskPosition:
3307         HANDLE_MASK_INHERIT_AND_INITIAL(xPosition, XPosition);
3308         HANDLE_MASK_INHERIT_AND_INITIAL(yPosition, YPosition);
3309         return;
3310     case CSSPropertyWebkitMaskPositionX: {
3311         HANDLE_MASK_VALUE(xPosition, XPosition, value)
3312         return;
3313     }
3314     case CSSPropertyWebkitMaskPositionY: {
3315         HANDLE_MASK_VALUE(yPosition, YPosition, value)
3316         return;
3317     }
3318     case CSSPropertyBackgroundRepeat:
3319         HANDLE_BACKGROUND_INHERIT_AND_INITIAL(repeatX, RepeatX);
3320         HANDLE_BACKGROUND_INHERIT_AND_INITIAL(repeatY, RepeatY);
3321         return;
3322     case CSSPropertyBackgroundRepeatX:
3323         HANDLE_BACKGROUND_VALUE(repeatX, RepeatX, value)
3324         return;
3325     case CSSPropertyBackgroundRepeatY:
3326         HANDLE_BACKGROUND_VALUE(repeatY, RepeatY, value)
3327         return;
3328     case CSSPropertyWebkitMaskRepeat:
3329         HANDLE_MASK_INHERIT_AND_INITIAL(repeatX, RepeatX);
3330         HANDLE_MASK_INHERIT_AND_INITIAL(repeatY, RepeatY);
3331         return;
3332     case CSSPropertyWebkitMaskRepeatX:
3333         HANDLE_MASK_VALUE(repeatX, RepeatX, value)
3334         return;
3335     case CSSPropertyWebkitMaskRepeatY:
3336         HANDLE_MASK_VALUE(repeatY, RepeatY, value)
3337         return;
3338     case CSSPropertyBorderSpacing: {
3339         if (isInherit) {
3340             m_style->setHorizontalBorderSpacing(m_parentStyle->horizontalBorderSpacing());
3341             m_style->setVerticalBorderSpacing(m_parentStyle->verticalBorderSpacing());
3342         }
3343         else if (isInitial) {
3344             m_style->setHorizontalBorderSpacing(0);
3345             m_style->setVerticalBorderSpacing(0);
3346         }
3347         return;
3348     }
3349     case CSSPropertyWebkitBorderHorizontalSpacing: {
3350         HANDLE_INHERIT_AND_INITIAL(horizontalBorderSpacing, HorizontalBorderSpacing)
3351         if (!primitiveValue)
3352             return;
3353         short spacing = primitiveValue->computeLengthShort(style(), m_rootElementStyle, zoomFactor);
3354         m_style->setHorizontalBorderSpacing(spacing);
3355         return;
3356     }
3357     case CSSPropertyWebkitBorderVerticalSpacing: {
3358         HANDLE_INHERIT_AND_INITIAL(verticalBorderSpacing, VerticalBorderSpacing)
3359         if (!primitiveValue)
3360             return;
3361         short spacing = primitiveValue->computeLengthShort(style(), m_rootElementStyle, zoomFactor);
3362         m_style->setVerticalBorderSpacing(spacing);
3363         return;
3364     }
3365     case CSSPropertyCursor:
3366         if (isInherit) {
3367             m_style->setCursor(m_parentStyle->cursor());
3368             m_style->setCursorList(m_parentStyle->cursors());
3369             return;
3370         }
3371         m_style->clearCursorList();
3372         if (isInitial) {
3373             m_style->setCursor(RenderStyle::initialCursor());
3374             return;
3375         }
3376         if (value->isValueList()) {
3377             CSSValueList* list = static_cast<CSSValueList*>(value);
3378             int len = list->length();
3379             m_style->setCursor(CURSOR_AUTO);
3380             for (int i = 0; i < len; i++) {
3381                 CSSValue* item = list->itemWithoutBoundsCheck(i);
3382                 if (!item->isPrimitiveValue())
3383                     continue;
3384                 primitiveValue = static_cast<CSSPrimitiveValue*>(item);
3385                 int type = primitiveValue->primitiveType();
3386                 if (type == CSSPrimitiveValue::CSS_URI) {
3387                     CSSCursorImageValue* image = static_cast<CSSCursorImageValue*>(primitiveValue);
3388                     if (image->updateIfSVGCursorIsUsed(m_element)) // Elements with SVG cursors are not allowed to share style.
3389                         m_style->setUnique();
3390                     // FIXME: Temporary clumsiness to pass off a CachedImage to an API that will eventually convert to using
3391                     // StyleImage.
3392                     RefPtr<StyleCachedImage> styleCachedImage(image->cachedImage(m_element->document()->docLoader()));
3393                     if (styleCachedImage)
3394                         m_style->addCursor(styleCachedImage->cachedImage(), image->hotspot());
3395                 } else if (type == CSSPrimitiveValue::CSS_IDENT)
3396                     m_style->setCursor(*primitiveValue);
3397             }
3398         } else if (primitiveValue) {
3399             int type = primitiveValue->primitiveType();
3400             if (type == CSSPrimitiveValue::CSS_IDENT && m_style->cursor() != ECursor(*primitiveValue))
3401                 m_style->setCursor(*primitiveValue);
3402         }
3403         return;
3404 // colors || inherit
3405     case CSSPropertyColor:
3406         // If the 'currentColor' keyword is set on the 'color' property itself,
3407         // it is treated as 'color:inherit' at parse time
3408         if (primitiveValue && primitiveValue->getIdent() == CSSValueCurrentcolor)
3409             isInherit = true;
3410     case CSSPropertyBackgroundColor:
3411     case CSSPropertyBorderTopColor:
3412     case CSSPropertyBorderRightColor:
3413     case CSSPropertyBorderBottomColor:
3414     case CSSPropertyBorderLeftColor:
3415     case CSSPropertyOutlineColor:
3416     case CSSPropertyWebkitColumnRuleColor:
3417     case CSSPropertyWebkitTextStrokeColor:
3418     case CSSPropertyWebkitTextFillColor: {
3419         Color col;
3420         if (isInherit) {
3421             HANDLE_INHERIT_COND(CSSPropertyBackgroundColor, backgroundColor, BackgroundColor)
3422             HANDLE_INHERIT_COND_WITH_BACKUP(CSSPropertyBorderTopColor, borderTopColor, color, BorderTopColor)
3423             HANDLE_INHERIT_COND_WITH_BACKUP(CSSPropertyBorderBottomColor, borderBottomColor, color, BorderBottomColor)
3424             HANDLE_INHERIT_COND_WITH_BACKUP(CSSPropertyBorderRightColor, borderRightColor, color, BorderRightColor)
3425             HANDLE_INHERIT_COND_WITH_BACKUP(CSSPropertyBorderLeftColor, borderLeftColor, color, BorderLeftColor)
3426             HANDLE_INHERIT_COND(CSSPropertyColor, color, Color)
3427             HANDLE_INHERIT_COND_WITH_BACKUP(CSSPropertyOutlineColor, outlineColor, color, OutlineColor)
3428             HANDLE_INHERIT_COND_WITH_BACKUP(CSSPropertyWebkitColumnRuleColor, columnRuleColor, color, ColumnRuleColor)
3429             HANDLE_INHERIT_COND_WITH_BACKUP(CSSPropertyWebkitTextStrokeColor, textStrokeColor, color, TextStrokeColor)
3430             HANDLE_INHERIT_COND_WITH_BACKUP(CSSPropertyWebkitTextFillColor, textFillColor, color, TextFillColor)
3431             return;
3432         }
3433         if (isInitial) {
3434             // The border/outline colors will just map to the invalid color |col| above.  This will have the
3435             // effect of forcing the use of the currentColor when it comes time to draw the borders (and of
3436             // not painting the background since the color won't be valid).
3437             if (id == CSSPropertyColor)
3438                 col = RenderStyle::initialColor();
3439         } else {
3440             if (!primitiveValue)
3441                 return;
3442             col = getColorFromPrimitiveValue(primitiveValue);
3443         }
3444
3445         switch (id) {
3446         case CSSPropertyBackgroundColor:
3447             m_style->setBackgroundColor(col);
3448             break;
3449         case CSSPropertyBorderTopColor:
3450             m_style->setBorderTopColor(col);
3451             break;
3452         case CSSPropertyBorderRightColor:
3453             m_style->setBorderRightColor(col);
3454             break;
3455         case CSSPropertyBorderBottomColor:
3456             m_style->setBorderBottomColor(col);
3457             break;
3458         case CSSPropertyBorderLeftColor:
3459             m_style->setBorderLeftColor(col);
3460             break;
3461         case CSSPropertyColor:
3462             m_style->setColor(col);
3463             break;
3464         case CSSPropertyOutlineColor:
3465             m_style->setOutlineColor(col);
3466             break;
3467         case CSSPropertyWebkitColumnRuleColor:
3468             m_style->setColumnRuleColor(col);
3469             break;
3470         case CSSPropertyWebkitTextStrokeColor:
3471             m_style->setTextStrokeColor(col);
3472             break;
3473         case CSSPropertyWebkitTextFillColor:
3474             m_style->setTextFillColor(col);
3475             break;
3476         }
3477         
3478         return;
3479     }
3480     
3481 // uri || inherit
3482     case CSSPropertyBackgroundImage:
3483         HANDLE_BACKGROUND_VALUE(image, Image, value)
3484         return;
3485     case CSSPropertyWebkitMaskImage:
3486         HANDLE_MASK_VALUE(image, Image, value)
3487         return;
3488     case CSSPropertyListStyleImage:
3489     {
3490         HANDLE_INHERIT_AND_INITIAL(listStyleImage, ListStyleImage)
3491         m_style->setListStyleImage(styleImage(value));
3492         return;
3493     }
3494
3495 // length
3496     case CSSPropertyBorderTopWidth:
3497     case CSSPropertyBorderRightWidth:
3498     case CSSPropertyBorderBottomWidth:
3499     case CSSPropertyBorderLeftWidth:
3500     case CSSPropertyOutlineWidth:
3501     case CSSPropertyWebkitColumnRuleWidth:
3502     {
3503         if (isInherit) {
3504             HANDLE_INHERIT_COND(CSSPropertyBorderTopWidth, borderTopWidth, BorderTopWidth)
3505             HANDLE_INHERIT_COND(CSSPropertyBorderRightWidth, borderRightWidth, BorderRightWidth)
3506             HANDLE_INHERIT_COND(CSSPropertyBorderBottomWidth, borderBottomWidth, BorderBottomWidth)
3507             HANDLE_INHERIT_COND(CSSPropertyBorderLeftWidth, borderLeftWidth, BorderLeftWidth)
3508             HANDLE_INHERIT_COND(CSSPropertyOutlineWidth, outlineWidth, OutlineWidth)
3509             HANDLE_INHERIT_COND(CSSPropertyWebkitColumnRuleWidth, columnRuleWidth, ColumnRuleWidth)
3510             return;
3511         }
3512         else if (isInitial) {
3513             HANDLE_INITIAL_COND_WITH_VALUE(CSSPropertyBorderTopWidth, BorderTopWidth, BorderWidth)
3514             HANDLE_INITIAL_COND_WITH_VALUE(CSSPropertyBorderRightWidth, BorderRightWidth, BorderWidth)
3515             HANDLE_INITIAL_COND_WITH_VALUE(CSSPropertyBorderBottomWidth, BorderBottomWidth, BorderWidth)
3516             HANDLE_INITIAL_COND_WITH_VALUE(CSSPropertyBorderLeftWidth, BorderLeftWidth, BorderWidth)
3517             HANDLE_INITIAL_COND_WITH_VALUE(CSSPropertyOutlineWidth, OutlineWidth, BorderWidth)
3518             HANDLE_INITIAL_COND_WITH_VALUE(CSSPropertyWebkitColumnRuleWidth, ColumnRuleWidth, BorderWidth)
3519             return;
3520         }
3521
3522         if (!primitiveValue)
3523             return;
3524         short width = 3;
3525         switch (primitiveValue->getIdent()) {
3526         case CSSValueThin:
3527             width = 1;
3528             break;
3529         case CSSValueMedium:
3530             width = 3;
3531             break;
3532         case CSSValueThick:
3533             width = 5;
3534             break;
3535         case CSSValueInvalid:
3536             width = primitiveValue->computeLengthShort(style(), m_rootElementStyle, zoomFactor);
3537             break;
3538         default:
3539             return;
3540         }
3541
3542         if (width < 0) return;
3543         switch (id) {
3544         case CSSPropertyBorderTopWidth:
3545             m_style->setBorderTopWidth(width);
3546             break;
3547         case CSSPropertyBorderRightWidth:
3548             m_style->setBorderRightWidth(width);
3549             break;
3550         case CSSPropertyBorderBottomWidth:
3551             m_style->setBorderBottomWidth(width);
3552             break;
3553         case CSSPropertyBorderLeftWidth:
3554             m_style->setBorderLeftWidth(width);
3555             break;
3556         case CSSPropertyOutlineWidth:
3557             m_style->setOutlineWidth(width);
3558             break;
3559         case CSSPropertyWebkitColumnRuleWidth:
3560             m_style->setColumnRuleWidth(width);
3561             break;
3562         default:
3563             return;
3564         }
3565         return;
3566     }
3567
3568     case CSSPropertyWebkitFontSmoothing: {
3569         FontDescription fontDescription = m_style->fontDescription();
3570         if (isInherit) 
3571             fontDescription.setFontSmoothing(m_parentStyle->fontDescription().fontSmoothing());
3572         else if (isInitial)
3573             fontDescription.setFontSmoothing(AutoSmoothing);
3574         else {
3575             if (!primitiveValue)
3576                 return;
3577             int id = primitiveValue->getIdent();
3578             FontSmoothingMode smoothing;
3579             switch (id) {
3580                 case CSSValueAuto:
3581                     smoothing = AutoSmoothing;
3582                     break;
3583                 case CSSValueNone:
3584                     smoothing = NoSmoothing;
3585                     break;
3586                 case CSSValueAntialiased:
3587                     smoothing = Antialiased;
3588                     break;
3589                 case CSSValueSubpixelAntialiased:
3590                     smoothing = SubpixelAntialiased;
3591                     break;
3592                 default:
3593                     ASSERT_NOT_REACHED();
3594                     smoothing = AutoSmoothing;
3595             }
3596             fontDescription.setFontSmoothing(smoothing);
3597         }
3598         if (m_style->setFontDescription(fontDescription))
3599             m_fontDirty = true;
3600         return;
3601     }
3602
3603     case CSSPropertyLetterSpacing:
3604     case CSSPropertyWordSpacing:
3605     {
3606         
3607         if (isInherit) {
3608             HANDLE_INHERIT_COND(CSSPropertyLetterSpacing, letterSpacing, LetterSpacing)
3609             HANDLE_INHERIT_COND(CSSPropertyWordSpacing, wordSpacing, WordSpacing)
3610             return;
3611         }
3612         else if (isInitial) {
3613             HANDLE_INITIAL_COND_WITH_VALUE(CSSPropertyLetterSpacing, LetterSpacing, LetterWordSpacing)
3614             HANDLE_INITIAL_COND_WITH_VALUE(CSSPropertyWordSpacing, WordSpacing, LetterWordSpacing)
3615             return;
3616         }
3617         
3618         int width = 0;
3619         if (primitiveValue && primitiveValue->getIdent() == CSSValueNormal) {
3620             width = 0;
3621         } else {
3622             if (!primitiveValue)
3623                 return;
3624             width = primitiveValue->computeLengthInt(style(), m_rootElementStyle, useSVGZoomRules ? 1.0f : zoomFactor);
3625         }
3626         switch (id) {
3627         case CSSPropertyLetterSpacing:
3628             m_style->setLetterSpacing(width);
3629             break;
3630         case CSSPropertyWordSpacing:
3631             m_style->setWordSpacing(width);
3632             break;
3633             // ### needs the definitions in renderstyle
3634         default: break;
3635         }
3636         return;
3637     }
3638
3639     case CSSPropertyWordBreak:
3640         HANDLE_INHERIT_AND_INITIAL_AND_PRIMITIVE(wordBreak, WordBreak)
3641         return;
3642     case CSSPropertyWordWrap:
3643         HANDLE_INHERIT_AND_INITIAL_AND_PRIMITIVE(wordWrap, WordWrap)
3644         return;
3645     case CSSPropertyWebkitNbspMode:
3646         HANDLE_INHERIT_AND_INITIAL_AND_PRIMITIVE(nbspMode, NBSPMode)
3647         return;
3648     case CSSPropertyWebkitLineBreak:
3649         HANDLE_INHERIT_AND_INITIAL_AND_PRIMITIVE(khtmlLineBreak, KHTMLLineBreak)
3650         return;
3651     case CSSPropertyWebkitMatchNearestMailBlockquoteColor:
3652         HANDLE_INHERIT_AND_INITIAL_AND_PRIMITIVE(matchNearestMailBlockquoteColor, MatchNearestMailBlockquoteColor)
3653         return;
3654
3655     case CSSPropertyResize:
3656     {
3657         HANDLE_INHERIT_AND_INITIAL(resize, Resize)
3658
3659         if (!primitiveValue->getIdent())
3660             return;
3661
3662         EResize r = RESIZE_NONE;
3663         if (primitiveValue->getIdent() == CSSValueAuto) {
3664             if (Settings* settings = m_checker.m_document->settings())
3665                 r = settings->textAreasAreResizable() ? RESIZE_BOTH : RESIZE_NONE;
3666         } else
3667             r = *primitiveValue;
3668             
3669         m_style->setResize(r);
3670         return;
3671     }
3672     
3673     // length, percent
3674     case CSSPropertyMaxWidth:
3675         // +none +inherit
3676         if (primitiveValue && primitiveValue->getIdent() == CSSValueNone)
3677             apply = true;
3678     case CSSPropertyTop:
3679     case CSSPropertyLeft:
3680     case CSSPropertyRight:
3681     case CSSPropertyBottom:
3682     case CSSPropertyWidth:
3683     case CSSPropertyMinWidth:
3684     case CSSPropertyMarginTop:
3685     case CSSPropertyMarginRight:
3686     case CSSPropertyMarginBottom:
3687     case CSSPropertyMarginLeft:
3688         // +inherit +auto
3689         if (id == CSSPropertyWidth || id == CSSPropertyMinWidth || id == CSSPropertyMaxWidth) {
3690             if (primitiveValue && primitiveValue->getIdent() == CSSValueIntrinsic) {
3691                 l = Length(Intrinsic);
3692                 apply = true;
3693             }
3694             else if (primitiveValue && primitiveValue->getIdent() == CSSValueMinIntrinsic) {
3695                 l = Length(MinIntrinsic);
3696                 apply = true;
3697             }
3698         }
3699         if (id != CSSPropertyMaxWidth && primitiveValue && primitiveValue->getIdent() == CSSValueAuto)
3700             apply = true;
3701     case CSSPropertyPaddingTop:
3702     case CSSPropertyPaddingRight:
3703     case CSSPropertyPaddingBottom:
3704     case CSSPropertyPaddingLeft:
3705     case CSSPropertyTextIndent:
3706         // +inherit
3707     {
3708         if (isInherit) {
3709             HANDLE_INHERIT_COND(CSSPropertyMaxWidth, maxWidth, MaxWidth)
3710             HANDLE_INHERIT_COND(CSSPropertyBottom, bottom, Bottom)
3711             HANDLE_INHERIT_COND(CSSPropertyTop, top, Top)
3712             HANDLE_INHERIT_COND(CSSPropertyLeft, left, Left)
3713             HANDLE_INHERIT_COND(CSSPropertyRight, right, Right)
3714             HANDLE_INHERIT_COND(CSSPropertyWidth, width, Width)
3715             HANDLE_INHERIT_COND(CSSPropertyMinWidth, minWidth, MinWidth)
3716             HANDLE_INHERIT_COND(CSSPropertyPaddingTop, paddingTop, PaddingTop)
3717             HANDLE_INHERIT_COND(CSSPropertyPaddingRight, paddingRight, PaddingRight)
3718             HANDLE_INHERIT_COND(CSSPropertyPaddingBottom, paddingBottom, PaddingBottom)
3719             HANDLE_INHERIT_COND(CSSPropertyPaddingLeft, paddingLeft, PaddingLeft)
3720             HANDLE_INHERIT_COND(CSSPropertyMarginTop, marginTop, MarginTop)
3721             HANDLE_INHERIT_COND(CSSPropertyMarginRight, marginRight, MarginRight)
3722             HANDLE_INHERIT_COND(CSSPropertyMarginBottom, marginBottom, MarginBottom)
3723             HANDLE_INHERIT_COND(CSSPropertyMarginLeft, marginLeft, MarginLeft)
3724             HANDLE_INHERIT_COND(CSSPropertyTextIndent, textIndent, TextIndent)
3725             return;
3726         }
3727         else if (isInitial) {
3728             HANDLE_INITIAL_COND_WITH_VALUE(CSSPropertyMaxWidth, MaxWidth, MaxSize)
3729             HANDLE_INITIAL_COND_WITH_VALUE(CSSPropertyBottom, Bottom, Offset)
3730             HANDLE_INITIAL_COND_WITH_VALUE(CSSPropertyTop, Top, Offset)
3731             HANDLE_INITIAL_COND_WITH_VALUE(CSSPropertyLeft, Left, Offset)
3732             HANDLE_INITIAL_COND_WITH_VALUE(CSSPropertyRight, Right, Offset)
3733             HANDLE_INITIAL_COND_WITH_VALUE(CSSPropertyWidth, Width, Size)
3734             HANDLE_INITIAL_COND_WITH_VALUE(CSSPropertyMinWidth, MinWidth, MinSize)
3735             HANDLE_INITIAL_COND_WITH_VALUE(CSSPropertyPaddingTop, PaddingTop, Padding)
3736             HANDLE_INITIAL_COND_WITH_VALUE(CSSPropertyPaddingRight, PaddingRight, Padding)
3737             HANDLE_INITIAL_COND_WITH_VALUE(CSSPropertyPaddingBottom, PaddingBottom, Padding)
3738             HANDLE_INITIAL_COND_WITH_VALUE(CSSPropertyPaddingLeft, PaddingLeft, Padding)
3739             HANDLE_INITIAL_COND_WITH_VALUE(CSSPropertyMarginTop, MarginTop, Margin)
3740             HANDLE_INITIAL_COND_WITH_VALUE(CSSPropertyMarginRight, MarginRight, Margin)
3741             HANDLE_INITIAL_COND_WITH_VALUE(CSSPropertyMarginBottom, MarginBottom, Margin)
3742             HANDLE_INITIAL_COND_WITH_VALUE(CSSPropertyMarginLeft, MarginLeft, Margin)
3743             HANDLE_INITIAL_COND(CSSPropertyTextIndent, TextIndent)
3744             return;
3745         } 
3746
3747         if (primitiveValue && !apply) {
3748             int type = primitiveValue->primitiveType();
3749             if (CSSPrimitiveValue::isUnitTypeLength(type))
3750                 // Handle our quirky margin units if we have them.
3751                 l = Length(primitiveValue->computeLengthIntForLength(style(), m_rootElementStyle, zoomFactor), Fixed, 
3752                            primitiveValue->isQuirkValue());
3753             else if (type == CSSPrimitiveValue::CSS_PERCENTAGE)
3754                 l = Length(primitiveValue->getDoubleValue(), Percent);
3755             else
3756                 return;
3757             if (id == CSSPropertyPaddingLeft || id == CSSPropertyPaddingRight ||
3758                 id == CSSPropertyPaddingTop || id == CSSPropertyPaddingBottom)
3759                 // Padding can't be negative
3760                 apply = !((l.isFixed() || l.isPercent()) && l.calcValue(100) < 0);
3761             else
3762                 apply = true;
3763         }
3764         if (!apply) return;
3765         switch (id) {
3766             case CSSPropertyMaxWidth:
3767                 m_style->setMaxWidth(l);
3768                 break;
3769             case CSSPropertyBottom:
3770                 m_style->setBottom(l);
3771                 break;
3772             case CSSPropertyTop:
3773                 m_style->setTop(l);
3774                 break;
3775             case CSSPropertyLeft:
3776                 m_style->setLeft(l);
3777                 break;
3778             case CSSPropertyRight:
3779                 m_style->setRight(l);
3780 &n