2010-10-19 Hayato Ito <hayato@chromium.org>
[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, 2010 Apple Inc. All rights reserved.
6  * Copyright (C) 2007 Alexey Proskuryakov <ap@webkit.org>
7  * Copyright (C) 2007, 2008 Eric Seidel <eric@webkit.org>
8  * Copyright (C) 2008, 2009 Torch Mobile Inc. All rights reserved. (http://www.torchmobile.com/)
9  *
10  * This library is free software; you can redistribute it and/or
11  * modify it under the terms of the GNU Library General Public
12  * License as published by the Free Software Foundation; either
13  * version 2 of the License, or (at your option) any later version.
14  *
15  * This library is distributed in the hope that it will be useful,
16  * but WITHOUT ANY WARRANTY; without even the implied warranty of
17  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
18  * Library General Public License for more details.
19  *
20  * You should have received a copy of the GNU Library General Public License
21  * along with this library; see the file COPYING.LIB.  If not, write to
22  * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
23  * Boston, MA 02110-1301, USA.
24  */
25
26 #include "config.h"
27 #include "CSSStyleSelector.h"
28
29 #include "Attribute.h"
30 #include "CSSBorderImageValue.h"
31 #include "CSSCursorImageValue.h"
32 #include "CSSFontFaceRule.h"
33 #include "CSSImportRule.h"
34 #include "CSSMediaRule.h"
35 #include "CSSPageRule.h"
36 #include "CSSParser.h"
37 #include "CSSPrimitiveValueMappings.h"
38 #include "CSSPropertyNames.h"
39 #include "CSSReflectValue.h"
40 #include "CSSRuleList.h"
41 #include "CSSSelector.h"
42 #include "CSSSelectorList.h"
43 #include "CSSStyleRule.h"
44 #include "CSSStyleSheet.h"
45 #include "CSSTimingFunctionValue.h"
46 #include "CSSValueList.h"
47 #include "CSSVariableDependentValue.h"
48 #include "CSSVariablesDeclaration.h"
49 #include "CSSVariablesRule.h"
50 #include "CachedImage.h"
51 #include "Counter.h"
52 #include "FocusController.h"
53 #include "FontFamilyValue.h"
54 #include "FontValue.h"
55 #include "Frame.h"
56 #include "FrameView.h"
57 #include "HTMLDocument.h"
58 #include "HTMLElement.h"
59 #include "HTMLInputElement.h"
60 #include "HTMLNames.h"
61 #include "HTMLTextAreaElement.h"
62 #include "KeyframeList.h"
63 #include "LinkHash.h"
64 #include "Matrix3DTransformOperation.h"
65 #include "MatrixTransformOperation.h"
66 #include "MediaList.h"
67 #include "MediaQueryEvaluator.h"
68 #include "NodeRenderStyle.h"
69 #include "Page.h"
70 #include "PageGroup.h"
71 #include "Pair.h"
72 #include "PerspectiveTransformOperation.h"
73 #include "Rect.h"
74 #include "RenderScrollbar.h"
75 #include "RenderScrollbarTheme.h"
76 #include "RenderStyleConstants.h"
77 #include "RenderTheme.h"
78 #include "RotateTransformOperation.h"
79 #include "ScaleTransformOperation.h"
80 #include "SelectionController.h"
81 #include "Settings.h"
82 #include "ShadowValue.h"
83 #include "SkewTransformOperation.h"
84 #include "StyleCachedImage.h"
85 #include "StylePendingImage.h"
86 #include "StyleGeneratedImage.h"
87 #include "StyleSheetList.h"
88 #include "Text.h"
89 #include "TransformationMatrix.h"
90 #include "TranslateTransformOperation.h"
91 #include "UserAgentStyleSheets.h"
92 #include "WebKitCSSKeyframeRule.h"
93 #include "WebKitCSSKeyframesRule.h"
94 #include "WebKitCSSTransformValue.h"
95 #include "XMLNames.h"
96 #include "loader.h"
97 #include <wtf/StdLibExtras.h>
98 #include <wtf/Vector.h>
99
100 #if USE(PLATFORM_STRATEGIES)
101 #include "PlatformStrategies.h"
102 #include "VisitedLinkStrategy.h"
103 #endif
104
105 #if ENABLE(DASHBOARD_SUPPORT)
106 #include "DashboardRegion.h"
107 #endif
108
109 #if ENABLE(SVG)
110 #include "XLinkNames.h"
111 #include "SVGNames.h"
112 #endif
113
114 #if ENABLE(WML)
115 #include "WMLNames.h"
116 #endif
117
118 #if PLATFORM(QT)
119 #include <qwebhistoryinterface.h>
120 #endif
121
122 using namespace std;
123
124 namespace WebCore {
125
126 using namespace HTMLNames;
127
128 #define HANDLE_INHERIT(prop, Prop) \
129 if (isInherit) { \
130     m_style->set##Prop(m_parentStyle->prop()); \
131     return; \
132 }
133
134 #define HANDLE_INHERIT_AND_INITIAL(prop, Prop) \
135 HANDLE_INHERIT(prop, Prop) \
136 if (isInitial) { \
137     m_style->set##Prop(RenderStyle::initial##Prop()); \
138     return; \
139 }
140
141 #define HANDLE_INHERIT_AND_INITIAL_WITH_VALUE(prop, Prop, Value) \
142 HANDLE_INHERIT(prop, Prop) \
143 if (isInitial) { \
144     m_style->set##Prop(RenderStyle::initial##Value());\
145     return;\
146 }
147
148 #define HANDLE_INHERIT_AND_INITIAL_AND_PRIMITIVE(prop, Prop) \
149 HANDLE_INHERIT_AND_INITIAL(prop, Prop) \
150 if (primitiveValue) \
151     m_style->set##Prop(*primitiveValue);
152
153 #define HANDLE_INHERIT_AND_INITIAL_AND_PRIMITIVE_WITH_VALUE(prop, Prop, Value) \
154 HANDLE_INHERIT_AND_INITIAL_WITH_VALUE(prop, Prop, Value) \
155 if (primitiveValue) \
156     m_style->set##Prop(*primitiveValue);
157
158 #define HANDLE_FILL_LAYER_INHERIT_AND_INITIAL(layerType, LayerType, prop, Prop) \
159 if (isInherit) { \
160     FillLayer* currChild = m_style->access##LayerType##Layers(); \
161     FillLayer* prevChild = 0; \
162     const FillLayer* currParent = m_parentStyle->layerType##Layers(); \
163     while (currParent && currParent->is##Prop##Set()) { \
164         if (!currChild) { \
165             /* Need to make a new layer.*/ \
166             currChild = new FillLayer(LayerType##FillLayer); \
167             prevChild->setNext(currChild); \
168         } \
169         currChild->set##Prop(currParent->prop()); \
170         prevChild = currChild; \
171         currChild = prevChild->next(); \
172         currParent = currParent->next(); \
173     } \
174     \
175     while (currChild) { \
176         /* Reset any remaining layers to not have the property set. */ \
177         currChild->clear##Prop(); \
178         currChild = currChild->next(); \
179     } \
180 } else if (isInitial) { \
181     FillLayer* currChild = m_style->access##LayerType##Layers(); \
182     currChild->set##Prop(FillLayer::initialFill##Prop(LayerType##FillLayer)); \
183     for (currChild = currChild->next(); currChild; currChild = currChild->next()) \
184         currChild->clear##Prop(); \
185 }
186
187 #define HANDLE_FILL_LAYER_VALUE(layerType, LayerType, prop, Prop, value) { \
188 HANDLE_FILL_LAYER_INHERIT_AND_INITIAL(layerType, LayerType, prop, Prop) \
189 if (isInherit || isInitial) \
190     return; \
191 FillLayer* currChild = m_style->access##LayerType##Layers(); \
192 FillLayer* prevChild = 0; \
193 if (value->isValueList()) { \
194     /* Walk each value and put it into a layer, creating new layers as needed. */ \
195     CSSValueList* valueList = static_cast<CSSValueList*>(value); \
196     for (unsigned int i = 0; i < valueList->length(); i++) { \
197         if (!currChild) { \
198             /* Need to make a new layer to hold this value */ \
199             currChild = new FillLayer(LayerType##FillLayer); \
200             prevChild->setNext(currChild); \
201         } \
202         mapFill##Prop(property, currChild, valueList->itemWithoutBoundsCheck(i)); \
203         prevChild = currChild; \
204         currChild = currChild->next(); \
205     } \
206 } else { \
207     mapFill##Prop(property, currChild, value); \
208     currChild = currChild->next(); \
209 } \
210 while (currChild) { \
211     /* Reset all remaining layers to not have the property set. */ \
212     currChild->clear##Prop(); \
213     currChild = currChild->next(); \
214 } }
215
216 #define HANDLE_BACKGROUND_INHERIT_AND_INITIAL(prop, Prop) \
217 HANDLE_FILL_LAYER_INHERIT_AND_INITIAL(background, Background, prop, Prop)
218
219 #define HANDLE_BACKGROUND_VALUE(prop, Prop, value) \
220 HANDLE_FILL_LAYER_VALUE(background, Background, prop, Prop, value)
221
222 #define HANDLE_MASK_INHERIT_AND_INITIAL(prop, Prop) \
223 HANDLE_FILL_LAYER_INHERIT_AND_INITIAL(mask, Mask, prop, Prop)
224
225 #define HANDLE_MASK_VALUE(prop, Prop, value) \
226 HANDLE_FILL_LAYER_VALUE(mask, Mask, prop, Prop, value)
227
228 #define HANDLE_ANIMATION_INHERIT_AND_INITIAL(prop, Prop) \
229 if (isInherit) { \
230     AnimationList* list = m_style->accessAnimations(); \
231     const AnimationList* parentList = m_parentStyle->animations(); \
232     size_t i = 0, parentSize = parentList ? parentList->size() : 0; \
233     for ( ; i < parentSize && parentList->animation(i)->is##Prop##Set(); ++i) { \
234         if (list->size() <= i) \
235             list->append(Animation::create()); \
236         list->animation(i)->set##Prop(parentList->animation(i)->prop()); \
237     } \
238     \
239     /* Reset any remaining animations to not have the property set. */ \
240     for ( ; i < list->size(); ++i) \
241         list->animation(i)->clear##Prop(); \
242 } else if (isInitial) { \
243     AnimationList* list = m_style->accessAnimations(); \
244     if (list->isEmpty()) \
245         list->append(Animation::create()); \
246     list->animation(0)->set##Prop(Animation::initialAnimation##Prop()); \
247     for (size_t i = 1; i < list->size(); ++i) \
248         list->animation(0)->clear##Prop(); \
249 }
250
251 #define HANDLE_ANIMATION_VALUE(prop, Prop, value) { \
252 HANDLE_ANIMATION_INHERIT_AND_INITIAL(prop, Prop) \
253 if (isInherit || isInitial) \
254     return; \
255 AnimationList* list = m_style->accessAnimations(); \
256 size_t childIndex = 0; \
257 if (value->isValueList()) { \
258     /* Walk each value and put it into an animation, creating new animations as needed. */ \
259     CSSValueList* valueList = static_cast<CSSValueList*>(value); \
260     for (unsigned int i = 0; i < valueList->length(); i++) { \
261         if (childIndex <= list->size()) \
262             list->append(Animation::create()); \
263         mapAnimation##Prop(list->animation(childIndex), valueList->itemWithoutBoundsCheck(i)); \
264         ++childIndex; \
265     } \
266 } else { \
267     if (list->isEmpty()) \
268         list->append(Animation::create()); \
269     mapAnimation##Prop(list->animation(childIndex), value); \
270     childIndex = 1; \
271 } \
272 for ( ; childIndex < list->size(); ++childIndex) { \
273     /* Reset all remaining animations to not have the property set. */ \
274     list->animation(childIndex)->clear##Prop(); \
275 } \
276 }
277
278 #define HANDLE_TRANSITION_INHERIT_AND_INITIAL(prop, Prop) \
279 if (isInherit) { \
280     AnimationList* list = m_style->accessTransitions(); \
281     const AnimationList* parentList = m_parentStyle->transitions(); \
282     size_t i = 0, parentSize = parentList ? parentList->size() : 0; \
283     for ( ; i < parentSize && parentList->animation(i)->is##Prop##Set(); ++i) { \
284         if (list->size() <= i) \
285             list->append(Animation::create()); \
286         list->animation(i)->set##Prop(parentList->animation(i)->prop()); \
287     } \
288     \
289     /* Reset any remaining transitions to not have the property set. */ \
290     for ( ; i < list->size(); ++i) \
291         list->animation(i)->clear##Prop(); \
292 } else if (isInitial) { \
293     AnimationList* list = m_style->accessTransitions(); \
294     if (list->isEmpty()) \
295         list->append(Animation::create()); \
296     list->animation(0)->set##Prop(Animation::initialAnimation##Prop()); \
297     for (size_t i = 1; i < list->size(); ++i) \
298         list->animation(0)->clear##Prop(); \
299 }
300
301 #define HANDLE_TRANSITION_VALUE(prop, Prop, value) { \
302 HANDLE_TRANSITION_INHERIT_AND_INITIAL(prop, Prop) \
303 if (isInherit || isInitial) \
304     return; \
305 AnimationList* list = m_style->accessTransitions(); \
306 size_t childIndex = 0; \
307 if (value->isValueList()) { \
308     /* Walk each value and put it into a transition, creating new animations as needed. */ \
309     CSSValueList* valueList = static_cast<CSSValueList*>(value); \
310     for (unsigned int i = 0; i < valueList->length(); i++) { \
311         if (childIndex <= list->size()) \
312             list->append(Animation::create()); \
313         mapAnimation##Prop(list->animation(childIndex), valueList->itemWithoutBoundsCheck(i)); \
314         ++childIndex; \
315     } \
316 } else { \
317     if (list->isEmpty()) \
318         list->append(Animation::create()); \
319     mapAnimation##Prop(list->animation(childIndex), value); \
320     childIndex = 1; \
321 } \
322 for ( ; childIndex < list->size(); ++childIndex) { \
323     /* Reset all remaining transitions to not have the property set. */ \
324     list->animation(childIndex)->clear##Prop(); \
325 } \
326 }
327
328 #define HANDLE_INHERIT_COND(propID, prop, Prop) \
329 if (id == propID) { \
330     m_style->set##Prop(m_parentStyle->prop()); \
331     return; \
332 }
333     
334 #define HANDLE_INHERIT_COND_WITH_BACKUP(propID, prop, propAlt, Prop) \
335 if (id == propID) { \
336     if (m_parentStyle->prop().isValid()) \
337         m_style->set##Prop(m_parentStyle->prop()); \
338     else \
339         m_style->set##Prop(m_parentStyle->propAlt()); \
340     return; \
341 }
342
343 #define HANDLE_INITIAL_COND(propID, Prop) \
344 if (id == propID) { \
345     m_style->set##Prop(RenderStyle::initial##Prop()); \
346     return; \
347 }
348
349 #define HANDLE_INITIAL_COND_WITH_VALUE(propID, Prop, Value) \
350 if (id == propID) { \
351     m_style->set##Prop(RenderStyle::initial##Value()); \
352     return; \
353 }
354
355 class CSSRuleSet : public Noncopyable {
356 public:
357     CSSRuleSet();
358     ~CSSRuleSet();
359     
360     typedef HashMap<AtomicStringImpl*, CSSRuleDataList*> AtomRuleMap;
361     
362     void addRulesFromSheet(CSSStyleSheet*, const MediaQueryEvaluator&, CSSStyleSelector* = 0);
363
364     void addStyleRule(StyleBase* item);
365     void addRule(CSSStyleRule* rule, CSSSelector* sel);
366     void addPageRule(CSSStyleRule* rule, CSSSelector* sel);
367     void addToRuleSet(AtomicStringImpl* key, AtomRuleMap& map,
368                       CSSStyleRule* rule, CSSSelector* sel);
369     
370     CSSRuleDataList* getIDRules(AtomicStringImpl* key) { return m_idRules.get(key); }
371     CSSRuleDataList* getClassRules(AtomicStringImpl* key) { return m_classRules.get(key); }
372     CSSRuleDataList* getTagRules(AtomicStringImpl* key) { return m_tagRules.get(key); }
373     CSSRuleDataList* getUniversalRules() { return m_universalRules.get(); }
374     CSSRuleDataList* getPageRules() { return m_pageRules.get(); }
375     
376 public:
377     AtomRuleMap m_idRules;
378     AtomRuleMap m_classRules;
379     AtomRuleMap m_tagRules;
380     OwnPtr<CSSRuleDataList> m_universalRules;
381     OwnPtr<CSSRuleDataList> m_pageRules;
382     unsigned m_ruleCount;
383     unsigned m_pageRuleCount;
384 };
385
386 static CSSRuleSet* defaultStyle;
387 static CSSRuleSet* defaultQuirksStyle;
388 static CSSRuleSet* defaultPrintStyle;
389 static CSSRuleSet* defaultViewSourceStyle;
390 static CSSStyleSheet* simpleDefaultStyleSheet;
391
392 RenderStyle* CSSStyleSelector::s_styleNotYetAvailable;
393
394 static void loadFullDefaultStyle();
395 static void loadSimpleDefaultStyle();
396 // FIXME: It would be nice to use some mechanism that guarantees this is in sync with the real UA stylesheet.
397 static const char* simpleUserAgentStyleSheet = "html,body,div{display:block}body{margin:8px}div:focus,span:focus{outline:auto 5px -webkit-focus-ring-color}a:-webkit-any-link{color:-webkit-link;text-decoration:underline}a:-webkit-any-link:active{color:-webkit-activelink}";
398
399 static bool elementCanUseSimpleDefaultStyle(Element* e)
400 {
401     return e->hasTagName(htmlTag) || e->hasTagName(bodyTag) || e->hasTagName(divTag) || e->hasTagName(spanTag) || e->hasTagName(brTag) || e->hasTagName(aTag);
402 }
403
404 static const MediaQueryEvaluator& screenEval()
405 {
406     DEFINE_STATIC_LOCAL(const MediaQueryEvaluator, staticScreenEval, ("screen"));
407     return staticScreenEval;
408 }
409
410 static const MediaQueryEvaluator& printEval()
411 {
412     DEFINE_STATIC_LOCAL(const MediaQueryEvaluator, staticPrintEval, ("print"));
413     return staticPrintEval;
414 }
415
416 CSSStyleSelector::CSSStyleSelector(Document* document, StyleSheetList* styleSheets, CSSStyleSheet* mappedElementSheet,
417                                    CSSStyleSheet* pageUserSheet, const Vector<RefPtr<CSSStyleSheet> >* pageGroupUserSheets,
418                                    bool strictParsing, bool matchAuthorAndUserStyles)
419     : m_backgroundData(BackgroundFillLayer)
420     , m_checker(document, strictParsing)
421     , m_element(0)
422     , m_styledElement(0)
423     , m_elementLinkState(NotInsideLink)
424     , m_fontSelector(CSSFontSelector::create(document))
425 {
426     m_matchAuthorAndUserStyles = matchAuthorAndUserStyles;
427     
428     Element* root = document->documentElement();
429
430     if (!defaultStyle) {
431         if (!root || elementCanUseSimpleDefaultStyle(root))
432             loadSimpleDefaultStyle();
433         else
434             loadFullDefaultStyle();
435     }
436
437     // construct document root element default style. this is needed
438     // to evaluate media queries that contain relative constraints, like "screen and (max-width: 10em)"
439     // This is here instead of constructor, because when constructor is run,
440     // document doesn't have documentElement
441     // NOTE: this assumes that element that gets passed to styleForElement -call
442     // is always from the document that owns the style selector
443     FrameView* view = document->view();
444     if (view)
445         m_medium = adoptPtr(new MediaQueryEvaluator(view->mediaType()));
446     else
447         m_medium = adoptPtr(new MediaQueryEvaluator("all"));
448
449     if (root)
450         m_rootDefaultStyle = styleForElement(root, 0, false, true); // don't ref, because the RenderStyle is allocated from global heap
451
452     if (m_rootDefaultStyle && view)
453         m_medium = adoptPtr(new MediaQueryEvaluator(view->mediaType(), view->frame(), m_rootDefaultStyle.get()));
454
455     m_authorStyle = adoptPtr(new CSSRuleSet);
456
457     // FIXME: This sucks! The user sheet is reparsed every time!
458     OwnPtr<CSSRuleSet> tempUserStyle = adoptPtr(new CSSRuleSet);
459     if (pageUserSheet)
460         tempUserStyle->addRulesFromSheet(pageUserSheet, *m_medium, this);
461     if (pageGroupUserSheets) {
462         unsigned length = pageGroupUserSheets->size();
463         for (unsigned i = 0; i < length; i++) {
464             if (pageGroupUserSheets->at(i)->isUserStyleSheet())
465                 tempUserStyle->addRulesFromSheet(pageGroupUserSheets->at(i).get(), *m_medium, this);
466             else
467                 m_authorStyle->addRulesFromSheet(pageGroupUserSheets->at(i).get(), *m_medium, this);
468         }
469     }
470
471     if (tempUserStyle->m_ruleCount > 0 || tempUserStyle->m_pageRuleCount > 0)
472         m_userStyle = tempUserStyle.release();
473
474     // Add rules from elements like SVG's <font-face>
475     if (mappedElementSheet)
476         m_authorStyle->addRulesFromSheet(mappedElementSheet, *m_medium, this);
477
478     // add stylesheets from document
479     unsigned length = styleSheets->length();
480     for (unsigned i = 0; i < length; i++) {
481         StyleSheet* sheet = styleSheets->item(i);
482         if (sheet->isCSSStyleSheet() && !sheet->disabled())
483             m_authorStyle->addRulesFromSheet(static_cast<CSSStyleSheet*>(sheet), *m_medium, this);
484     }
485
486     if (document->renderer() && document->renderer()->style())
487         document->renderer()->style()->font().update(fontSelector());
488 }
489
490 // This is a simplified style setting function for keyframe styles
491 void CSSStyleSelector::addKeyframeStyle(PassRefPtr<WebKitCSSKeyframesRule> rule)
492 {
493     AtomicString s(rule->name());
494     m_keyframesRuleMap.add(s.impl(), rule);
495 }
496
497 CSSStyleSelector::~CSSStyleSelector()
498 {
499     m_fontSelector->clearDocument();
500     deleteAllValues(m_viewportDependentMediaQueryResults);
501 }
502
503 static CSSStyleSheet* parseUASheet(const String& str)
504 {
505     CSSStyleSheet* sheet = CSSStyleSheet::create().releaseRef(); // leak the sheet on purpose
506     sheet->parseString(str);
507     return sheet;
508 }
509
510 static CSSStyleSheet* parseUASheet(const char* characters, unsigned size)
511 {
512     return parseUASheet(String(characters, size));
513 }
514
515 static void loadFullDefaultStyle()
516 {
517     if (simpleDefaultStyleSheet) {
518         ASSERT(defaultStyle);
519         delete defaultStyle;
520         simpleDefaultStyleSheet->deref();
521         defaultStyle = new CSSRuleSet;
522         simpleDefaultStyleSheet = 0;
523     } else {
524         ASSERT(!defaultStyle);
525         defaultStyle = new CSSRuleSet;
526         defaultPrintStyle = new CSSRuleSet;
527         defaultQuirksStyle = new CSSRuleSet;
528     }
529
530     // Strict-mode rules.
531     String defaultRules = String(htmlUserAgentStyleSheet, sizeof(htmlUserAgentStyleSheet)) + RenderTheme::defaultTheme()->extraDefaultStyleSheet();
532     CSSStyleSheet* defaultSheet = parseUASheet(defaultRules);
533     defaultStyle->addRulesFromSheet(defaultSheet, screenEval());
534     defaultPrintStyle->addRulesFromSheet(defaultSheet, printEval());
535
536     // Quirks-mode rules.
537     String quirksRules = String(quirksUserAgentStyleSheet, sizeof(quirksUserAgentStyleSheet)) + RenderTheme::defaultTheme()->extraQuirksStyleSheet();
538     CSSStyleSheet* quirksSheet = parseUASheet(quirksRules);
539     defaultQuirksStyle->addRulesFromSheet(quirksSheet, screenEval());
540     
541 #if ENABLE(FULLSCREEN_API)
542     // Full-screen rules.
543     String fullscreenRules = String(fullscreenUserAgentStyleSheet, sizeof(fullscreenUserAgentStyleSheet)) + RenderTheme::defaultTheme()->extraDefaultStyleSheet();
544     CSSStyleSheet* fullscreenSheet = parseUASheet(fullscreenRules);
545     defaultStyle->addRulesFromSheet(fullscreenSheet, screenEval());
546     defaultQuirksStyle->addRulesFromSheet(fullscreenSheet, screenEval());
547 #endif
548 }
549
550 static void loadSimpleDefaultStyle()
551 {
552     ASSERT(!defaultStyle);
553     ASSERT(!simpleDefaultStyleSheet);
554     
555     defaultStyle = new CSSRuleSet;
556     defaultPrintStyle = new CSSRuleSet;
557     defaultQuirksStyle = new CSSRuleSet;
558
559     simpleDefaultStyleSheet = parseUASheet(simpleUserAgentStyleSheet, strlen(simpleUserAgentStyleSheet));
560     defaultStyle->addRulesFromSheet(simpleDefaultStyleSheet, screenEval());
561     
562     // No need to initialize quirks sheet yet as there are no quirk rules for elements allowed in simple default style.
563 }
564     
565 static void loadViewSourceStyle()
566 {
567     ASSERT(!defaultViewSourceStyle);
568     defaultViewSourceStyle = new CSSRuleSet;
569     defaultViewSourceStyle->addRulesFromSheet(parseUASheet(sourceUserAgentStyleSheet, sizeof(sourceUserAgentStyleSheet)), screenEval());
570 }
571
572 void CSSStyleSelector::addMatchedDeclaration(CSSMutableStyleDeclaration* decl)
573 {
574     if (!decl->hasVariableDependentValue()) {
575         m_matchedDecls.append(decl);
576         return;
577     }
578
579     // See if we have already resolved the variables in this declaration.
580     CSSMutableStyleDeclaration* resolvedDecl = m_resolvedVariablesDeclarations.get(decl).get();
581     if (resolvedDecl) {
582         m_matchedDecls.append(resolvedDecl);
583         return;
584     }
585
586     // If this declaration has any variables in it, then we need to make a cloned
587     // declaration with as many variables resolved as possible for this style selector's media.
588     RefPtr<CSSMutableStyleDeclaration> newDecl = CSSMutableStyleDeclaration::create(decl->parentRule());
589     m_matchedDecls.append(newDecl.get());
590     m_resolvedVariablesDeclarations.set(decl, newDecl);
591
592     HashSet<String> usedBlockVariables;
593     resolveVariablesForDeclaration(decl, newDecl.get(), usedBlockVariables);
594 }
595
596 void CSSStyleSelector::resolveVariablesForDeclaration(CSSMutableStyleDeclaration* decl, CSSMutableStyleDeclaration* newDecl, HashSet<String>& usedBlockVariables)
597 {
598     // Now iterate over the properties in the original declaration.  As we resolve variables we'll end up
599     // mutating the new declaration (possibly expanding shorthands).  The new declaration has no m_node
600     // though, so it can't mistakenly call setChanged on anything.
601     CSSMutableStyleDeclaration::const_iterator end = decl->end();
602     for (CSSMutableStyleDeclaration::const_iterator it = decl->begin(); it != end; ++it) {
603         const CSSProperty& current = *it;
604         if (!current.value()->isVariableDependentValue()) {
605             // We can just add the parsed property directly.
606             newDecl->addParsedProperty(current);
607             continue;
608         }
609         CSSValueList* valueList = static_cast<CSSVariableDependentValue*>(current.value())->valueList();
610         if (!valueList)
611             continue;
612         CSSParserValueList resolvedValueList;
613         unsigned s = valueList->length();
614         bool fullyResolved = true;
615         for (unsigned i = 0; i < s; ++i) {
616             CSSValue* val = valueList->item(i);
617             CSSPrimitiveValue* primitiveValue = val->isPrimitiveValue() ? static_cast<CSSPrimitiveValue*>(val) : 0;
618             if (primitiveValue && primitiveValue->isVariable()) {
619                 CSSVariablesRule* rule = m_variablesMap.get(primitiveValue->getStringValue());
620                 if (!rule || !rule->variables()) {
621                     fullyResolved = false;
622                     break;
623                 }
624                 
625                 if (current.id() == CSSPropertyWebkitVariableDeclarationBlock && s == 1) {
626                     fullyResolved = false;
627                     if (!usedBlockVariables.contains(primitiveValue->getStringValue())) {
628                         CSSMutableStyleDeclaration* declBlock = rule->variables()->getParsedVariableDeclarationBlock(primitiveValue->getStringValue());
629                         if (declBlock) {
630                             usedBlockVariables.add(primitiveValue->getStringValue());
631                             resolveVariablesForDeclaration(declBlock, newDecl, usedBlockVariables);
632                         }
633                     }
634                 }
635
636                 CSSValueList* resolvedVariable = rule->variables()->getParsedVariable(primitiveValue->getStringValue());
637                 if (!resolvedVariable) {
638                     fullyResolved = false;
639                     break;
640                 }
641                 unsigned valueSize = resolvedVariable->length();
642                 for (unsigned j = 0; j < valueSize; ++j)
643                     resolvedValueList.addValue(resolvedVariable->item(j)->parserValue());
644             } else
645                 resolvedValueList.addValue(val->parserValue());
646         }
647         
648         if (!fullyResolved)
649             continue;
650
651         // We now have a fully resolved new value list.  We want the parser to use this value list
652         // and parse our new declaration.
653         CSSParser(m_checker.m_strictParsing).parsePropertyWithResolvedVariables(current.id(), current.isImportant(), newDecl, &resolvedValueList);
654     }
655 }
656
657 void CSSStyleSelector::matchRules(CSSRuleSet* rules, int& firstRuleIndex, int& lastRuleIndex, bool includeEmptyRules)
658 {
659     m_matchedRules.clear();
660
661     if (!rules || !m_element)
662         return;
663     
664     // We need to collect the rules for id, class, tag, and everything else into a buffer and
665     // then sort the buffer.
666     if (m_element->hasID())
667         matchRulesForList(rules->getIDRules(m_element->idForStyleResolution().impl()), firstRuleIndex, lastRuleIndex, includeEmptyRules);
668     if (m_element->hasClass()) {
669         ASSERT(m_styledElement);
670         const SpaceSplitString& classNames = m_styledElement->classNames();
671         size_t size = classNames.size();
672         for (size_t i = 0; i < size; ++i)
673             matchRulesForList(rules->getClassRules(classNames[i].impl()), firstRuleIndex, lastRuleIndex, includeEmptyRules);
674     }
675     matchRulesForList(rules->getTagRules(m_element->localName().impl()), firstRuleIndex, lastRuleIndex, includeEmptyRules);
676     matchRulesForList(rules->getUniversalRules(), firstRuleIndex, lastRuleIndex, includeEmptyRules);
677     
678     // If we didn't match any rules, we're done.
679     if (m_matchedRules.isEmpty())
680         return;
681     
682     // Sort the set of matched rules.
683     sortMatchedRules(0, m_matchedRules.size());
684     
685     // Now transfer the set of matched rules over to our list of decls.
686     if (!m_checker.m_collectRulesOnly) {
687         for (unsigned i = 0; i < m_matchedRules.size(); i++)
688             addMatchedDeclaration(m_matchedRules[i]->rule()->declaration());
689     } else {
690         for (unsigned i = 0; i < m_matchedRules.size(); i++) {
691             if (!m_ruleList)
692                 m_ruleList = CSSRuleList::create();
693             m_ruleList->append(m_matchedRules[i]->rule());
694         }
695     }
696 }
697
698 void CSSStyleSelector::matchRulesForList(CSSRuleDataList* rules, int& firstRuleIndex, int& lastRuleIndex, bool includeEmptyRules)
699 {
700     if (!rules)
701         return;
702
703     for (CSSRuleData* d = rules->first(); d; d = d->next()) {
704         CSSStyleRule* rule = d->rule();
705         if (checkSelector(d->selector())) {
706             // If the rule has no properties to apply, then ignore it in the non-debug mode.
707             CSSMutableStyleDeclaration* decl = rule->declaration();
708             if (!decl || (!decl->length() && !includeEmptyRules))
709                 continue;
710             
711             // If we're matching normal rules, set a pseudo bit if 
712             // we really just matched a pseudo-element.
713             if (m_dynamicPseudo != NOPSEUDO && m_checker.m_pseudoStyle == NOPSEUDO) {
714                 if (m_checker.m_collectRulesOnly)
715                     continue;
716                 if (m_dynamicPseudo < FIRST_INTERNAL_PSEUDOID)
717                     m_style->setHasPseudoStyle(m_dynamicPseudo);
718             } else {
719                 // Update our first/last rule indices in the matched rules array.
720                 lastRuleIndex = m_matchedDecls.size() + m_matchedRules.size();
721                 if (firstRuleIndex == -1)
722                     firstRuleIndex = lastRuleIndex;
723
724                 // Add this rule to our list of matched rules.
725                 addMatchedRule(d);
726             }
727         }
728     }
729 }
730
731 static bool operator >(CSSRuleData& r1, CSSRuleData& r2)
732 {
733     int spec1 = r1.selector()->specificity();
734     int spec2 = r2.selector()->specificity();
735     return (spec1 == spec2) ? r1.position() > r2.position() : spec1 > spec2; 
736 }
737     
738 static bool operator <=(CSSRuleData& r1, CSSRuleData& r2)
739 {
740     return !(r1 > r2);
741 }
742
743 void CSSStyleSelector::sortMatchedRules(unsigned start, unsigned end)
744 {
745     if (start >= end || (end - start == 1))
746         return; // Sanity check.
747
748     if (end - start <= 6) {
749         // Apply a bubble sort for smaller lists.
750         for (unsigned i = end - 1; i > start; i--) {
751             bool sorted = true;
752             for (unsigned j = start; j < i; j++) {
753                 CSSRuleData* elt = m_matchedRules[j];
754                 CSSRuleData* elt2 = m_matchedRules[j + 1];
755                 if (*elt > *elt2) {
756                     sorted = false;
757                     m_matchedRules[j] = elt2;
758                     m_matchedRules[j + 1] = elt;
759                 }
760             }
761             if (sorted)
762                 return;
763         }
764         return;
765     }
766
767     // Perform a merge sort for larger lists.
768     unsigned mid = (start + end) / 2;
769     sortMatchedRules(start, mid);
770     sortMatchedRules(mid, end);
771     
772     CSSRuleData* elt = m_matchedRules[mid - 1];
773     CSSRuleData* elt2 = m_matchedRules[mid];
774     
775     // Handle the fast common case (of equal specificity).  The list may already
776     // be completely sorted.
777     if (*elt <= *elt2)
778         return;
779     
780     // We have to merge sort.  Ensure our merge buffer is big enough to hold
781     // all the items.
782     Vector<CSSRuleData*> rulesMergeBuffer;
783     rulesMergeBuffer.reserveInitialCapacity(end - start); 
784
785     unsigned i1 = start;
786     unsigned i2 = mid;
787     
788     elt = m_matchedRules[i1];
789     elt2 = m_matchedRules[i2];
790     
791     while (i1 < mid || i2 < end) {
792         if (i1 < mid && (i2 == end || *elt <= *elt2)) {
793             rulesMergeBuffer.append(elt);
794             if (++i1 < mid)
795                 elt = m_matchedRules[i1];
796         } else {
797             rulesMergeBuffer.append(elt2);
798             if (++i2 < end)
799                 elt2 = m_matchedRules[i2];
800         }
801     }
802     
803     for (unsigned i = start; i < end; i++)
804         m_matchedRules[i] = rulesMergeBuffer[i - start];
805 }
806
807 inline EInsideLink CSSStyleSelector::SelectorChecker::determineLinkState(Element* element) const
808 {
809     if (!element || !element->isLink())
810         return NotInsideLink;
811     return determineLinkStateSlowCase(element);
812 }
813     
814 inline void CSSStyleSelector::initElement(Element* e)
815 {
816     if (m_element != e) {
817         m_element = e;
818         m_styledElement = m_element && m_element->isStyledElement() ? static_cast<StyledElement*>(m_element) : 0;
819         m_elementLinkState = m_checker.determineLinkState(m_element);
820     }
821 }
822
823 inline void CSSStyleSelector::initForStyleResolve(Element* e, RenderStyle* parentStyle, PseudoId pseudoID)
824 {
825     m_checker.m_pseudoStyle = pseudoID;
826
827     m_parentNode = e ? e->parentNode() : 0;
828
829 #if ENABLE(SVG)
830     if (!m_parentNode && e && e->isSVGElement() && e->isShadowNode())
831         m_parentNode = e->shadowParentNode();
832 #endif
833
834     if (parentStyle)
835         m_parentStyle = parentStyle;
836     else
837         m_parentStyle = m_parentNode ? m_parentNode->renderStyle() : 0;
838
839     Node* docElement = e ? e->document()->documentElement() : 0;
840     RenderStyle* docStyle = m_checker.m_document->renderStyle();
841     m_rootElementStyle = docElement && e != docElement ? docElement->renderStyle() : docStyle;
842
843     m_style = 0;
844
845     m_matchedDecls.clear();
846
847     m_pendingImageProperties.clear();
848
849     m_ruleList = 0;
850
851     m_fontDirty = false;
852 }
853
854 static inline const AtomicString* linkAttribute(Node* node)
855 {
856     if (!node->isLink())
857         return 0;
858
859     ASSERT(node->isElementNode());
860     Element* element = static_cast<Element*>(node);
861     if (element->isHTMLElement())
862         return &element->fastGetAttribute(hrefAttr);
863
864 #if ENABLE(WML)
865     if (element->isWMLElement()) {
866         // <anchor> elements don't have href attributes, but we still want to
867         // appear as link, so linkAttribute() has to return a non-null value!
868         if (element->hasTagName(WMLNames::anchorTag))
869             return &emptyAtom;
870
871         return &element->fastGetAttribute(hrefAttr);
872     }
873 #endif
874
875 #if ENABLE(SVG)
876     if (element->isSVGElement())
877         return &element->fastGetAttribute(XLinkNames::hrefAttr);
878 #endif
879
880     return 0;
881 }
882
883 CSSStyleSelector::SelectorChecker::SelectorChecker(Document* document, bool strictParsing)
884     : m_document(document)
885     , m_strictParsing(strictParsing)
886     , m_collectRulesOnly(false)
887     , m_pseudoStyle(NOPSEUDO)
888     , m_documentIsHTML(document->isHTMLDocument())
889     , m_matchVisitedPseudoClass(false)
890 {
891 }
892
893 EInsideLink CSSStyleSelector::SelectorChecker::determineLinkStateSlowCase(Element* element) const
894 {
895     ASSERT(element->isLink());
896     
897     const AtomicString* attr = linkAttribute(element);
898     if (!attr || attr->isNull())
899         return NotInsideLink;
900
901 #if PLATFORM(QT)
902     Vector<UChar, 512> url;
903     visitedURL(m_document->baseURL(), *attr, url);
904     if (url.isEmpty())
905         return InsideUnvisitedLink;
906
907     // If the Qt4.4 interface for the history is used, we will have to fallback
908     // to the old global history.
909     QWebHistoryInterface* iface = QWebHistoryInterface::defaultInterface();
910     if (iface)
911         return iface->historyContains(QString(reinterpret_cast<QChar*>(url.data()), url.size())) ? InsideVisitedLink : InsideUnvisitedLink;
912
913     LinkHash hash = visitedLinkHash(url.data(), url.size());
914     if (!hash)
915         return InsideUnvisitedLink;
916 #else
917     LinkHash hash = visitedLinkHash(m_document->baseURL(), *attr);
918     if (!hash)
919         return InsideUnvisitedLink;
920 #endif
921
922     Frame* frame = m_document->frame();
923     if (!frame)
924         return InsideUnvisitedLink;
925
926     Page* page = frame->page();
927     if (!page)
928         return InsideUnvisitedLink;
929
930     m_linksCheckedForVisitedState.add(hash);
931
932 #if USE(PLATFORM_STRATEGIES)
933     return platformStrategies()->visitedLinkStrategy()->isLinkVisited(page, hash) ? InsideVisitedLink : InsideUnvisitedLink;
934 #else
935     return page->group().isLinkVisited(hash) ? InsideVisitedLink : InsideUnvisitedLink;
936 #endif
937 }
938
939 bool CSSStyleSelector::SelectorChecker::checkSelector(CSSSelector* sel, Element* element) const
940 {
941     PseudoId dynamicPseudo = NOPSEUDO;
942     return checkSelector(sel, element, 0, dynamicPseudo, false, false);
943 }
944
945 static const unsigned cStyleSearchThreshold = 10;
946
947 Node* CSSStyleSelector::locateCousinList(Element* parent, unsigned depth)
948 {
949     if (parent && parent->isStyledElement()) {
950         StyledElement* p = static_cast<StyledElement*>(parent);
951         if (!p->inlineStyleDecl() && !p->hasID()) {
952             Node* r = p->previousSibling();
953             unsigned subcount = 0;
954             RenderStyle* st = p->renderStyle();
955             while (r) {
956                 if (r->renderStyle() == st)
957                     return r->lastChild();
958                 if (subcount++ == cStyleSearchThreshold)
959                     return 0;
960                 r = r->previousSibling();
961             }
962             if (!r && depth < cStyleSearchThreshold)
963                 r = locateCousinList(parent->parentElement(), depth + 1);
964             while (r) {
965                 if (r->renderStyle() == st)
966                     return r->lastChild();
967                 if (subcount++ == cStyleSearchThreshold)
968                     return 0;
969                 r = r->previousSibling();
970             }
971         }
972     }
973     return 0;
974 }
975
976 bool CSSStyleSelector::canShareStyleWithElement(Node* n)
977 {
978     if (n->isStyledElement()) {
979         StyledElement* s = static_cast<StyledElement*>(n);
980         RenderStyle* style = s->renderStyle();
981         if (style && !style->unique() &&
982             (s->tagQName() == m_element->tagQName()) && !s->hasID() &&
983             (s->hasClass() == m_element->hasClass()) && !s->inlineStyleDecl() &&
984             (s->hasMappedAttributes() == m_styledElement->hasMappedAttributes()) &&
985             (s->isLink() == m_element->isLink()) && 
986             !style->affectedByAttributeSelectors() &&
987             (s->hovered() == m_element->hovered()) &&
988             (s->active() == m_element->active()) &&
989             (s->focused() == m_element->focused()) &&
990             (s != s->document()->cssTarget() && m_element != m_element->document()->cssTarget()) &&
991             (s->fastGetAttribute(typeAttr) == m_element->fastGetAttribute(typeAttr)) &&
992             (s->fastGetAttribute(XMLNames::langAttr) == m_element->fastGetAttribute(XMLNames::langAttr)) &&
993             (s->fastGetAttribute(langAttr) == m_element->fastGetAttribute(langAttr)) &&
994             (s->fastGetAttribute(readonlyAttr) == m_element->fastGetAttribute(readonlyAttr)) &&
995             (s->fastGetAttribute(cellpaddingAttr) == m_element->fastGetAttribute(cellpaddingAttr))) {
996             bool isControl = s->isFormControlElement();
997             if (isControl != m_element->isFormControlElement())
998                 return false;
999             if (isControl) {
1000                 InputElement* thisInputElement = toInputElement(s);
1001                 InputElement* otherInputElement = toInputElement(m_element);
1002                 if (thisInputElement && otherInputElement) {
1003                     if ((thisInputElement->isAutofilled() != otherInputElement->isAutofilled()) ||
1004                         (thisInputElement->isChecked() != otherInputElement->isChecked()) ||
1005                         (thisInputElement->isIndeterminate() != otherInputElement->isIndeterminate()))
1006                     return false;
1007                 } else
1008                     return false;
1009
1010                 if (s->isEnabledFormControl() != m_element->isEnabledFormControl())
1011                     return false;
1012
1013                 if (s->isDefaultButtonForForm() != m_element->isDefaultButtonForForm())
1014                     return false;
1015                 
1016                 if (!m_element->document()->containsValidityStyleRules())
1017                     return false;
1018                 
1019                 bool willValidate = s->willValidate();
1020                 if (willValidate != m_element->willValidate())
1021                     return false;
1022                 
1023                 if (willValidate && (s->isValidFormControlElement() != m_element->isValidFormControlElement()))
1024                     return false;
1025             }
1026
1027             if (style->transitions() || style->animations())
1028                 return false;
1029
1030             bool classesMatch = true;
1031             if (s->hasClass()) {
1032                 const AtomicString& class1 = m_element->fastGetAttribute(classAttr);
1033                 const AtomicString& class2 = s->fastGetAttribute(classAttr);
1034                 classesMatch = (class1 == class2);
1035             }
1036             
1037             if (classesMatch) {
1038                 bool mappedAttrsMatch = true;
1039                 if (s->hasMappedAttributes())
1040                     mappedAttrsMatch = s->attributeMap()->mappedMapsEquivalent(m_styledElement->attributeMap());
1041                 if (mappedAttrsMatch) {
1042                     if (s->isLink()) {
1043                         if (m_elementLinkState != style->insideLink())
1044                             return false;
1045                     }
1046                     return true;
1047                 }
1048             }
1049         }
1050     }
1051     return false;
1052 }
1053
1054 ALWAYS_INLINE RenderStyle* CSSStyleSelector::locateSharedStyle()
1055 {
1056     if (m_styledElement && !m_styledElement->inlineStyleDecl() && !m_styledElement->hasID() && !m_styledElement->document()->usesSiblingRules()) {
1057         // Check previous siblings.
1058         unsigned count = 0;
1059         Node* n;
1060         for (n = m_element->previousSibling(); n && !n->isElementNode(); n = n->previousSibling()) { }
1061         while (n) {
1062             if (canShareStyleWithElement(n))
1063                 return n->renderStyle();
1064             if (count++ == cStyleSearchThreshold)
1065                 return 0;
1066             for (n = n->previousSibling(); n && !n->isElementNode(); n = n->previousSibling()) { }
1067         }
1068         if (!n) 
1069             n = locateCousinList(m_element->parentElement());
1070         while (n) {
1071             if (canShareStyleWithElement(n))
1072                 return n->renderStyle();
1073             if (count++ == cStyleSearchThreshold)
1074                 return 0;
1075             for (n = n->previousSibling(); n && !n->isElementNode(); n = n->previousSibling()) { }
1076         }        
1077     }
1078     return 0;
1079 }
1080
1081 void CSSStyleSelector::matchUARules(int& firstUARule, int& lastUARule)
1082 {
1083     // First we match rules from the user agent sheet.
1084     CSSRuleSet* userAgentStyleSheet = m_medium->mediaTypeMatchSpecific("print")
1085         ? defaultPrintStyle : defaultStyle;
1086     matchRules(userAgentStyleSheet, firstUARule, lastUARule, false);
1087
1088     // In quirks mode, we match rules from the quirks user agent sheet.
1089     if (!m_checker.m_strictParsing)
1090         matchRules(defaultQuirksStyle, firstUARule, lastUARule, false);
1091         
1092     // If we're in view source mode, then we match rules from the view source style sheet.
1093     if (m_checker.m_document->frame() && m_checker.m_document->frame()->inViewSourceMode()) {
1094         if (!defaultViewSourceStyle)
1095             loadViewSourceStyle();
1096         matchRules(defaultViewSourceStyle, firstUARule, lastUARule, false);
1097     }
1098 }
1099
1100 PassRefPtr<RenderStyle> CSSStyleSelector::styleForDocument(Document* document)
1101 {
1102     Frame* frame = document->frame();
1103
1104     RefPtr<RenderStyle> documentStyle = RenderStyle::create();
1105     documentStyle->setDisplay(BLOCK);
1106     documentStyle->setVisuallyOrdered(document->visuallyOrdered());
1107     documentStyle->setZoom(frame ? frame->pageZoomFactor() : 1);
1108     
1109     Element* docElement = document->documentElement();
1110     if (docElement && docElement->renderer()) {
1111         // Use the direction and block-flow of the document element to set the
1112         // viewport's direction and block-flow.
1113         documentStyle->setWritingMode(docElement->renderer()->style()->writingMode());
1114         documentStyle->setDirection(docElement->renderer()->style()->direction());
1115     }
1116
1117     FontDescription fontDescription;
1118     fontDescription.setUsePrinterFont(document->printing());
1119     if (Settings* settings = document->settings()) {
1120         fontDescription.setRenderingMode(settings->fontRenderingMode());
1121         if (document->printing() && !settings->shouldPrintBackgrounds())
1122             documentStyle->setForceBackgroundsToWhite(true);
1123         const AtomicString& stdfont = settings->standardFontFamily();
1124         if (!stdfont.isEmpty()) {
1125             fontDescription.firstFamily().setFamily(stdfont);
1126             fontDescription.firstFamily().appendFamily(0);
1127         }
1128         fontDescription.setKeywordSize(CSSValueMedium - CSSValueXxSmall + 1);
1129         int size = CSSStyleSelector::fontSizeForKeyword(document, CSSValueMedium, false);
1130         fontDescription.setSpecifiedSize(size);
1131         bool useSVGZoomRules = document->isSVGDocument();
1132         fontDescription.setComputedSize(CSSStyleSelector::getComputedSizeFromSpecifiedSize(document, documentStyle.get(), fontDescription.isAbsoluteSize(), size, useSVGZoomRules));
1133     }
1134
1135     documentStyle->setFontDescription(fontDescription);
1136     documentStyle->font().update(0);
1137         
1138     return documentStyle.release();
1139 }
1140
1141 // If resolveForRootDefault is true, style based on user agent style sheet only. This is used in media queries, where
1142 // relative units are interpreted according to document root element style, styled only with UA stylesheet
1143
1144 PassRefPtr<RenderStyle> CSSStyleSelector::styleForElement(Element* e, RenderStyle* defaultParent, bool allowSharing, bool resolveForRootDefault, bool matchVisitedPseudoClass)
1145 {
1146     // Once an element has a renderer, we don't try to destroy it, since otherwise the renderer
1147     // will vanish if a style recalc happens during loading.
1148     if (allowSharing && !e->document()->haveStylesheetsLoaded() && !e->renderer()) {
1149         if (!s_styleNotYetAvailable) {
1150             s_styleNotYetAvailable = RenderStyle::create().releaseRef();
1151             s_styleNotYetAvailable->ref();
1152             s_styleNotYetAvailable->setDisplay(NONE);
1153             s_styleNotYetAvailable->font().update(m_fontSelector);
1154         }
1155         s_styleNotYetAvailable->ref();
1156         e->document()->setHasNodesWithPlaceholderStyle();
1157         return s_styleNotYetAvailable;
1158     }
1159
1160     initElement(e);
1161     if (allowSharing) {
1162         RenderStyle* sharedStyle = locateSharedStyle();
1163         if (sharedStyle)
1164             return sharedStyle;
1165     }
1166     initForStyleResolve(e, defaultParent);
1167
1168     // Compute our style allowing :visited to match first.
1169     RefPtr<RenderStyle> visitedStyle;
1170     if (!matchVisitedPseudoClass && m_parentStyle && (m_parentStyle->insideLink() || e->isLink()) && e->document()->usesLinkRules()) {
1171         // Fetch our parent style.
1172         RenderStyle* parentStyle = m_parentStyle;
1173         if (!e->isLink()) {
1174             // Use the parent's visited style if one exists.
1175             RenderStyle* parentVisitedStyle = m_parentStyle->getCachedPseudoStyle(VISITED_LINK);
1176             if (parentVisitedStyle)
1177                 parentStyle = parentVisitedStyle;
1178         }
1179         visitedStyle = styleForElement(e, parentStyle, false, false, true);
1180         if (visitedStyle) {
1181             if (m_elementLinkState == InsideUnvisitedLink)
1182                 visitedStyle = 0;  // We made the style to avoid timing attacks. Just throw it away now that we did that, since we don't need it.
1183             else
1184                 visitedStyle->setStyleType(VISITED_LINK);
1185         }
1186         initForStyleResolve(e, defaultParent);
1187     }
1188
1189     m_checker.m_matchVisitedPseudoClass = matchVisitedPseudoClass;
1190
1191     m_style = RenderStyle::create();
1192
1193     if (m_parentStyle)
1194         m_style->inheritFrom(m_parentStyle);
1195     else
1196         m_parentStyle = style();
1197
1198     if (e->isLink()) {
1199         m_style->setIsLink(true);
1200         m_style->setInsideLink(m_elementLinkState);
1201     }
1202     
1203     if (simpleDefaultStyleSheet && !elementCanUseSimpleDefaultStyle(e))
1204         loadFullDefaultStyle();
1205
1206 #if ENABLE(SVG)
1207     static bool loadedSVGUserAgentSheet;
1208     if (e->isSVGElement() && !loadedSVGUserAgentSheet) {
1209         // SVG rules.
1210         loadedSVGUserAgentSheet = true;
1211         CSSStyleSheet* svgSheet = parseUASheet(svgUserAgentStyleSheet, sizeof(svgUserAgentStyleSheet));
1212         defaultStyle->addRulesFromSheet(svgSheet, screenEval());
1213         defaultPrintStyle->addRulesFromSheet(svgSheet, printEval());
1214     }
1215 #endif
1216
1217 #if ENABLE(MATHML)
1218     static bool loadedMathMLUserAgentSheet;
1219     if (e->isMathMLElement() && !loadedMathMLUserAgentSheet) {
1220         // MathML rules.
1221         loadedMathMLUserAgentSheet = true;
1222         CSSStyleSheet* mathMLSheet = parseUASheet(mathmlUserAgentStyleSheet, sizeof(mathmlUserAgentStyleSheet));
1223         defaultStyle->addRulesFromSheet(mathMLSheet, screenEval());
1224         defaultPrintStyle->addRulesFromSheet(mathMLSheet, printEval());
1225     }
1226 #endif
1227
1228 #if ENABLE(WML)
1229     static bool loadedWMLUserAgentSheet;
1230     if (e->isWMLElement() && !loadedWMLUserAgentSheet) {
1231         // WML rules.
1232         loadedWMLUserAgentSheet = true;
1233         CSSStyleSheet* wmlSheet = parseUASheet(wmlUserAgentStyleSheet, sizeof(wmlUserAgentStyleSheet));
1234         defaultStyle->addRulesFromSheet(wmlSheet, screenEval());
1235         defaultPrintStyle->addRulesFromSheet(wmlSheet, printEval());
1236     }
1237 #endif
1238
1239 #if ENABLE(VIDEO)
1240     static bool loadedMediaStyleSheet;
1241     if (!loadedMediaStyleSheet && (e->hasTagName(videoTag) || e->hasTagName(audioTag))) {
1242         loadedMediaStyleSheet = true;
1243         String mediaRules = String(mediaControlsUserAgentStyleSheet, sizeof(mediaControlsUserAgentStyleSheet)) + RenderTheme::defaultTheme()->extraMediaControlsStyleSheet();
1244         CSSStyleSheet* mediaControlsSheet = parseUASheet(mediaRules);
1245         defaultStyle->addRulesFromSheet(mediaControlsSheet, screenEval());
1246         defaultPrintStyle->addRulesFromSheet(mediaControlsSheet, printEval());
1247     }
1248 #endif
1249
1250     int firstUARule = -1, lastUARule = -1;
1251     int firstUserRule = -1, lastUserRule = -1;
1252     int firstAuthorRule = -1, lastAuthorRule = -1;
1253     matchUARules(firstUARule, lastUARule);
1254
1255     if (!resolveForRootDefault) {
1256         // 4. Now we check user sheet rules.
1257         if (m_matchAuthorAndUserStyles)
1258             matchRules(m_userStyle.get(), firstUserRule, lastUserRule, false);
1259
1260         // 5. Now check author rules, beginning first with presentational attributes
1261         // mapped from HTML.
1262         if (m_styledElement) {
1263             // Ask if the HTML element has mapped attributes.
1264             if (m_styledElement->hasMappedAttributes()) {
1265                 // Walk our attribute list and add in each decl.
1266                 const NamedNodeMap* map = m_styledElement->attributeMap();
1267                 for (unsigned i = 0; i < map->length(); i++) {
1268                     Attribute* attr = map->attributeItem(i);
1269                     if (attr->isMappedAttribute() && attr->decl()) {
1270                         lastAuthorRule = m_matchedDecls.size();
1271                         if (firstAuthorRule == -1)
1272                             firstAuthorRule = lastAuthorRule;
1273                         addMatchedDeclaration(attr->decl());
1274                     }
1275                 }
1276             }
1277
1278             // Now we check additional mapped declarations.
1279             // Tables and table cells share an additional mapped rule that must be applied
1280             // after all attributes, since their mapped style depends on the values of multiple attributes.
1281             if (m_styledElement->canHaveAdditionalAttributeStyleDecls()) {
1282                 m_additionalAttributeStyleDecls.clear();
1283                 m_styledElement->additionalAttributeStyleDecls(m_additionalAttributeStyleDecls);
1284                 if (!m_additionalAttributeStyleDecls.isEmpty()) {
1285                     unsigned additionalDeclsSize = m_additionalAttributeStyleDecls.size();
1286                     if (firstAuthorRule == -1)
1287                         firstAuthorRule = m_matchedDecls.size();
1288                     lastAuthorRule = m_matchedDecls.size() + additionalDeclsSize - 1;
1289                     for (unsigned i = 0; i < additionalDeclsSize; i++)
1290                         addMatchedDeclaration(m_additionalAttributeStyleDecls[i]);
1291                 }
1292             }
1293         }
1294     
1295         // 6. Check the rules in author sheets next.
1296         if (m_matchAuthorAndUserStyles)
1297             matchRules(m_authorStyle.get(), firstAuthorRule, lastAuthorRule, false);
1298
1299         // 7. Now check our inline style attribute.
1300         if (m_matchAuthorAndUserStyles && m_styledElement) {
1301             CSSMutableStyleDeclaration* inlineDecl = m_styledElement->inlineStyleDecl();
1302             if (inlineDecl) {
1303                 lastAuthorRule = m_matchedDecls.size();
1304                 if (firstAuthorRule == -1)
1305                     firstAuthorRule = lastAuthorRule;
1306                 addMatchedDeclaration(inlineDecl);
1307             }
1308         }
1309     }
1310
1311     // Reset the value back before applying properties, so that -webkit-link knows what color to use.
1312     m_checker.m_matchVisitedPseudoClass = matchVisitedPseudoClass;
1313     
1314     // Now we have all of the matched rules in the appropriate order.  Walk the rules and apply
1315     // high-priority properties first, i.e., those properties that other properties depend on.
1316     // The order is (1) high-priority not important, (2) high-priority important, (3) normal not important
1317     // and (4) normal important.
1318     m_lineHeightValue = 0;
1319     applyDeclarations<true>(false, 0, m_matchedDecls.size() - 1);
1320     if (!resolveForRootDefault) {
1321         applyDeclarations<true>(true, firstAuthorRule, lastAuthorRule);
1322         applyDeclarations<true>(true, firstUserRule, lastUserRule);
1323     }
1324     applyDeclarations<true>(true, firstUARule, lastUARule);
1325     
1326     // If our font got dirtied, go ahead and update it now.
1327     if (m_fontDirty)
1328         updateFont();
1329
1330     // Line-height is set when we are sure we decided on the font-size
1331     if (m_lineHeightValue)
1332         applyProperty(CSSPropertyLineHeight, m_lineHeightValue);
1333
1334     // Now do the normal priority UA properties.
1335     applyDeclarations<false>(false, firstUARule, lastUARule);
1336     
1337     // Cache our border and background so that we can examine them later.
1338     cacheBorderAndBackground();
1339     
1340     // Now do the author and user normal priority properties and all the !important properties.
1341     if (!resolveForRootDefault) {
1342         applyDeclarations<false>(false, lastUARule + 1, m_matchedDecls.size() - 1);
1343         applyDeclarations<false>(true, firstAuthorRule, lastAuthorRule);
1344         applyDeclarations<false>(true, firstUserRule, lastUserRule);
1345     }
1346     applyDeclarations<false>(true, firstUARule, lastUARule);
1347
1348     ASSERT(!m_fontDirty);
1349     // If our font got dirtied by one of the non-essential font props, 
1350     // go ahead and update it a second time.
1351     if (m_fontDirty)
1352         updateFont();
1353     
1354     // Clean up our style object's display and text decorations (among other fixups).
1355     adjustRenderStyle(style(), m_parentStyle, e);
1356
1357     // Start loading images referenced by this style.
1358     loadPendingImages();
1359
1360     // If we have first-letter pseudo style, do not share this style
1361     if (m_style->hasPseudoStyle(FIRST_LETTER))
1362         m_style->setUnique();
1363
1364     if (visitedStyle) {
1365         // Copy any pseudo bits that the visited style has to the primary style so that
1366         // pseudo element styles will continue to work for pseudo elements inside :visited
1367         // links.
1368         for (unsigned pseudo = FIRST_PUBLIC_PSEUDOID; pseudo < FIRST_INTERNAL_PSEUDOID; ++pseudo) {
1369             if (visitedStyle->hasPseudoStyle(static_cast<PseudoId>(pseudo)))
1370                 m_style->setHasPseudoStyle(static_cast<PseudoId>(pseudo));
1371         }
1372         
1373         // Add the visited style off the main style.
1374         m_style->addCachedPseudoStyle(visitedStyle.release());
1375     }
1376
1377     if (!matchVisitedPseudoClass)
1378         initElement(0); // Clear out for the next resolve.
1379
1380     // Now return the style.
1381     return m_style.release();
1382 }
1383
1384 PassRefPtr<RenderStyle> CSSStyleSelector::styleForKeyframe(const RenderStyle* elementStyle, const WebKitCSSKeyframeRule* keyframeRule, KeyframeValue& keyframe)
1385 {
1386     if (keyframeRule->style())
1387         addMatchedDeclaration(keyframeRule->style());
1388
1389     ASSERT(!m_style);
1390
1391     // Create the style
1392     m_style = RenderStyle::clone(elementStyle);
1393
1394     m_lineHeightValue = 0;
1395
1396     // We don't need to bother with !important. Since there is only ever one
1397     // decl, there's nothing to override. So just add the first properties.
1398     if (keyframeRule->style())
1399         applyDeclarations<true>(false, 0, m_matchedDecls.size() - 1);
1400
1401     // If our font got dirtied, go ahead and update it now.
1402     if (m_fontDirty)
1403         updateFont();
1404
1405     // Line-height is set when we are sure we decided on the font-size
1406     if (m_lineHeightValue)
1407         applyProperty(CSSPropertyLineHeight, m_lineHeightValue);
1408
1409     // Now do rest of the properties.
1410     if (keyframeRule->style())
1411         applyDeclarations<false>(false, 0, m_matchedDecls.size() - 1);
1412
1413     // If our font got dirtied by one of the non-essential font props,
1414     // go ahead and update it a second time.
1415     if (m_fontDirty)
1416         updateFont();
1417
1418     // Start loading images referenced by this style.
1419     loadPendingImages();
1420
1421     // Add all the animating properties to the keyframe.
1422     if (keyframeRule->style()) {
1423         CSSMutableStyleDeclaration::const_iterator end = keyframeRule->style()->end();
1424         for (CSSMutableStyleDeclaration::const_iterator it = keyframeRule->style()->begin(); it != end; ++it) {
1425             int property = (*it).id();
1426             // Timing-function within keyframes is special, because it is not animated; it just
1427             // describes the timing function between this keyframe and the next.
1428             if (property != CSSPropertyWebkitAnimationTimingFunction)
1429                 keyframe.addProperty(property);
1430         }
1431     }
1432
1433     return m_style.release();
1434 }
1435
1436 void CSSStyleSelector::keyframeStylesForAnimation(Element* e, const RenderStyle* elementStyle, KeyframeList& list)
1437 {
1438     list.clear();
1439     
1440     // Get the keyframesRule for this name
1441     if (!e || list.animationName().isEmpty())
1442         return;
1443
1444     m_keyframesRuleMap.checkConsistency();
1445    
1446     if (!m_keyframesRuleMap.contains(list.animationName().impl()))
1447         return;
1448         
1449     const WebKitCSSKeyframesRule* rule = m_keyframesRuleMap.find(list.animationName().impl()).get()->second.get();
1450     
1451     // Construct and populate the style for each keyframe
1452     for (unsigned i = 0; i < rule->length(); ++i) {
1453         // Apply the declaration to the style. This is a simplified version of the logic in styleForElement
1454         initElement(e);
1455         initForStyleResolve(e);
1456         
1457         const WebKitCSSKeyframeRule* keyframeRule = rule->item(i);
1458
1459         KeyframeValue keyframe(0, 0);
1460         keyframe.setStyle(styleForKeyframe(elementStyle, keyframeRule, keyframe));
1461
1462         // Add this keyframe style to all the indicated key times
1463         Vector<float> keys;
1464         keyframeRule->getKeys(keys);
1465         for (size_t keyIndex = 0; keyIndex < keys.size(); ++keyIndex) {
1466             keyframe.setKey(keys[keyIndex]);
1467             list.insert(keyframe);
1468         }
1469     }
1470     
1471     // If the 0% keyframe is missing, create it (but only if there is at least one other keyframe)
1472     int initialListSize = list.size();
1473     if (initialListSize > 0 && list[0].key() != 0) {
1474         RefPtr<WebKitCSSKeyframeRule> keyframeRule = WebKitCSSKeyframeRule::create();
1475         keyframeRule->setKeyText("0%");
1476         KeyframeValue keyframe(0, 0);
1477         keyframe.setStyle(styleForKeyframe(elementStyle, keyframeRule.get(), keyframe));
1478         list.insert(keyframe);
1479     }
1480
1481     // If the 100% keyframe is missing, create it (but only if there is at least one other keyframe)
1482     if (initialListSize > 0 && (list[list.size() - 1].key() != 1)) {
1483         RefPtr<WebKitCSSKeyframeRule> keyframeRule = WebKitCSSKeyframeRule::create();
1484         keyframeRule->setKeyText("100%");
1485         KeyframeValue keyframe(1, 0);
1486         keyframe.setStyle(styleForKeyframe(elementStyle, keyframeRule.get(), keyframe));
1487         list.insert(keyframe);
1488     }
1489 }
1490
1491 PassRefPtr<RenderStyle> CSSStyleSelector::pseudoStyleForElement(PseudoId pseudo, Element* e, RenderStyle* parentStyle, bool matchVisitedPseudoClass)
1492 {
1493     if (!e)
1494         return 0;
1495
1496     initElement(e);
1497
1498     // Compute our :visited style first, so that we know whether or not we'll need to create a normal style just to hang it
1499     // off of.
1500     RefPtr<RenderStyle> visitedStyle;
1501     if (!matchVisitedPseudoClass && parentStyle && parentStyle->insideLink()) {
1502         // Fetch our parent style with :visited in effect.
1503         RenderStyle* parentVisitedStyle = parentStyle->getCachedPseudoStyle(VISITED_LINK);
1504         visitedStyle = pseudoStyleForElement(pseudo, e, parentVisitedStyle ? parentVisitedStyle : parentStyle, true);
1505         if (visitedStyle) {
1506             if (m_elementLinkState == InsideUnvisitedLink)
1507                 visitedStyle = 0;  // We made the style to avoid timing attacks. Just throw it away now that we did that.
1508             else
1509                 visitedStyle->setStyleType(VISITED_LINK);
1510         }
1511     }
1512
1513     initForStyleResolve(e, parentStyle, pseudo);
1514     m_style = RenderStyle::create();
1515     if (parentStyle)
1516         m_style->inheritFrom(parentStyle);
1517
1518     m_checker.m_matchVisitedPseudoClass = matchVisitedPseudoClass;
1519
1520     // Since we don't use pseudo-elements in any of our quirk/print user agent rules, don't waste time walking
1521     // those rules.
1522     
1523     // Check UA, user and author rules.
1524     int firstUARule = -1, lastUARule = -1, firstUserRule = -1, lastUserRule = -1, firstAuthorRule = -1, lastAuthorRule = -1;
1525     matchUARules(firstUARule, lastUARule);
1526
1527     if (m_matchAuthorAndUserStyles) {
1528         matchRules(m_userStyle.get(), firstUserRule, lastUserRule, false);
1529         matchRules(m_authorStyle.get(), firstAuthorRule, lastAuthorRule, false);
1530     }
1531
1532     if (m_matchedDecls.isEmpty() && !visitedStyle)
1533         return 0;
1534
1535     m_style->setStyleType(pseudo);
1536     
1537     m_lineHeightValue = 0;
1538     
1539     // Reset the value back before applying properties, so that -webkit-link knows what color to use.
1540     m_checker.m_matchVisitedPseudoClass = matchVisitedPseudoClass;
1541
1542     // High-priority properties.
1543     applyDeclarations<true>(false, 0, m_matchedDecls.size() - 1);
1544     applyDeclarations<true>(true, firstAuthorRule, lastAuthorRule);
1545     applyDeclarations<true>(true, firstUserRule, lastUserRule);
1546     applyDeclarations<true>(true, firstUARule, lastUARule);
1547     
1548     // If our font got dirtied, go ahead and update it now.
1549     if (m_fontDirty)
1550         updateFont();
1551
1552     // Line-height is set when we are sure we decided on the font-size
1553     if (m_lineHeightValue)
1554         applyProperty(CSSPropertyLineHeight, m_lineHeightValue);
1555     
1556     // Now do the normal priority properties.
1557     applyDeclarations<false>(false, firstUARule, lastUARule);
1558     
1559     // Cache our border and background so that we can examine them later.
1560     cacheBorderAndBackground();
1561     
1562     applyDeclarations<false>(false, lastUARule + 1, m_matchedDecls.size() - 1);
1563     applyDeclarations<false>(true, firstAuthorRule, lastAuthorRule);
1564     applyDeclarations<false>(true, firstUserRule, lastUserRule);
1565     applyDeclarations<false>(true, firstUARule, lastUARule);
1566     
1567     // If our font got dirtied by one of the non-essential font props, 
1568     // go ahead and update it a second time.
1569     if (m_fontDirty)
1570         updateFont();
1571
1572     // Clean up our style object's display and text decorations (among other fixups).
1573     adjustRenderStyle(style(), parentStyle, 0);
1574
1575     // Start loading images referenced by this style.
1576     loadPendingImages();
1577
1578     // Hang our visited style off m_style.
1579     if (visitedStyle)
1580         m_style->addCachedPseudoStyle(visitedStyle.release());
1581         
1582     // Now return the style.
1583     return m_style.release();
1584 }
1585
1586 PassRefPtr<RenderStyle> CSSStyleSelector::styleForPage(int pageIndex)
1587 {
1588     initForStyleResolve(m_checker.m_document->body());
1589
1590     m_style = RenderStyle::create();
1591     m_style->inheritFrom(m_rootElementStyle);
1592
1593     const bool isLeft = isLeftPage(pageIndex);
1594     const bool isFirst = isFirstPage(pageIndex);
1595     const String page = pageName(pageIndex);
1596     matchPageRules(defaultPrintStyle, isLeft, isFirst, page);
1597     matchPageRules(m_userStyle.get(), isLeft, isFirst, page);
1598     matchPageRules(m_authorStyle.get(), isLeft, isFirst, page);
1599     m_lineHeightValue = 0;
1600     applyDeclarations<true>(false, 0, m_matchedDecls.size() - 1);
1601
1602     // If our font got dirtied, go ahead and update it now.
1603     if (m_fontDirty)
1604         updateFont();
1605
1606     // Line-height is set when we are sure we decided on the font-size
1607     if (m_lineHeightValue)
1608         applyProperty(CSSPropertyLineHeight, m_lineHeightValue);
1609
1610     applyDeclarations<false>(false, 0, m_matchedDecls.size() - 1);
1611
1612     // Start loading images referenced by this style.
1613     loadPendingImages();
1614
1615     // Now return the style.
1616     return m_style.release();
1617 }
1618
1619 #if ENABLE(DATAGRID)
1620
1621 PassRefPtr<RenderStyle> CSSStyleSelector::pseudoStyleForDataGridColumn(DataGridColumn*, RenderStyle*)
1622 {
1623     // FIXME: Implement
1624     return 0;
1625 }
1626
1627 PassRefPtr<RenderStyle> CSSStyleSelector::pseudoStyleForDataGridColumnHeader(DataGridColumn*, RenderStyle*)
1628 {
1629     // FIXME: Implement
1630     return 0;
1631 }
1632
1633 #endif
1634
1635 static void addIntrinsicMargins(RenderStyle* style)
1636 {
1637     // Intrinsic margin value.
1638     const int intrinsicMargin = 2 * style->effectiveZoom();
1639     
1640     // FIXME: Using width/height alone and not also dealing with min-width/max-width is flawed.
1641     // FIXME: Using "quirk" to decide the margin wasn't set is kind of lame.
1642     if (style->width().isIntrinsicOrAuto()) {
1643         if (style->marginLeft().quirk())
1644             style->setMarginLeft(Length(intrinsicMargin, Fixed));
1645         if (style->marginRight().quirk())
1646             style->setMarginRight(Length(intrinsicMargin, Fixed));
1647     }
1648
1649     if (style->height().isAuto()) {
1650         if (style->marginTop().quirk())
1651             style->setMarginTop(Length(intrinsicMargin, Fixed));
1652         if (style->marginBottom().quirk())
1653             style->setMarginBottom(Length(intrinsicMargin, Fixed));
1654     }
1655 }
1656
1657 void CSSStyleSelector::adjustRenderStyle(RenderStyle* style, RenderStyle* parentStyle, Element *e)
1658 {
1659     // Cache our original display.
1660     style->setOriginalDisplay(style->display());
1661
1662     if (style->display() != NONE) {
1663         // If we have a <td> that specifies a float property, in quirks mode we just drop the float
1664         // property.
1665         // Sites also commonly use display:inline/block on <td>s and <table>s.  In quirks mode we force
1666         // these tags to retain their display types.
1667         if (!m_checker.m_strictParsing && e) {
1668             if (e->hasTagName(tdTag)) {
1669                 style->setDisplay(TABLE_CELL);
1670                 style->setFloating(FNONE);
1671             }
1672             else if (e->hasTagName(tableTag))
1673                 style->setDisplay(style->isDisplayInlineType() ? INLINE_TABLE : TABLE);
1674         }
1675
1676         if (e && (e->hasTagName(tdTag) || e->hasTagName(thTag))) {
1677             if (style->whiteSpace() == KHTML_NOWRAP) {
1678                 // Figure out if we are really nowrapping or if we should just
1679                 // use normal instead.  If the width of the cell is fixed, then
1680                 // we don't actually use NOWRAP.
1681                 if (style->width().isFixed())
1682                     style->setWhiteSpace(NORMAL);
1683                 else
1684                     style->setWhiteSpace(NOWRAP);
1685             }
1686         }
1687
1688         // Tables never support the -webkit-* values for text-align and will reset back to the default.
1689         if (e && e->hasTagName(tableTag) && (style->textAlign() == WEBKIT_LEFT || style->textAlign() == WEBKIT_CENTER || style->textAlign() == WEBKIT_RIGHT))
1690             style->setTextAlign(TAAUTO);
1691
1692         // Frames and framesets never honor position:relative or position:absolute.  This is necessary to
1693         // fix a crash where a site tries to position these objects.  They also never honor display.
1694         if (e && (e->hasTagName(frameTag) || e->hasTagName(framesetTag))) {
1695             style->setPosition(StaticPosition);
1696             style->setDisplay(BLOCK);
1697         }
1698
1699         // Table headers with a text-align of auto will change the text-align to center.
1700         if (e && e->hasTagName(thTag) && style->textAlign() == TAAUTO)
1701             style->setTextAlign(CENTER);
1702
1703         if (e && e->hasTagName(legendTag))
1704             style->setDisplay(BLOCK);
1705
1706         // Mutate the display to BLOCK or TABLE for certain cases, e.g., if someone attempts to
1707         // position or float an inline, compact, or run-in.  Cache the original display, since it
1708         // may be needed for positioned elements that have to compute their static normal flow
1709         // positions.  We also force inline-level roots to be block-level.
1710         if (style->display() != BLOCK && style->display() != TABLE && style->display() != BOX &&
1711             (style->position() == AbsolutePosition || style->position() == FixedPosition || style->floating() != FNONE ||
1712              (e && e->document()->documentElement() == e))) {
1713             if (style->display() == INLINE_TABLE)
1714                 style->setDisplay(TABLE);
1715             else if (style->display() == INLINE_BOX)
1716                 style->setDisplay(BOX);
1717             else if (style->display() == LIST_ITEM) {
1718                 // It is a WinIE bug that floated list items lose their bullets, so we'll emulate the quirk,
1719                 // but only in quirks mode.
1720                 if (!m_checker.m_strictParsing && style->floating() != FNONE)
1721                     style->setDisplay(BLOCK);
1722             }
1723             else
1724                 style->setDisplay(BLOCK);
1725         }
1726         
1727         // FIXME: Don't support this mutation for pseudo styles like first-letter or first-line, since it's not completely
1728         // clear how that should work.
1729         if (style->display() == INLINE && style->styleType() == NOPSEUDO && parentStyle && style->writingMode() != parentStyle->writingMode())
1730             style->setDisplay(INLINE_BLOCK);
1731         
1732         // After performing the display mutation, check table rows.  We do not honor position:relative on
1733         // table rows or cells.  This has been established in CSS2.1 (and caused a crash in containingBlock()
1734         // on some sites).
1735         if ((style->display() == TABLE_HEADER_GROUP || style->display() == TABLE_ROW_GROUP ||
1736              style->display() == TABLE_FOOTER_GROUP || style->display() == TABLE_ROW || style->display() == TABLE_CELL) &&
1737              style->position() == RelativePosition)
1738             style->setPosition(StaticPosition);
1739         
1740         // FIXME: Since we don't support block-flow on either tables or flexible boxes yet, disallow setting
1741         // of block-flow to anything other than TopToBottomWritingMode.
1742         // https://bugs.webkit.org/show_bug.cgi?id=46417 - Tables support
1743         // https://bugs.webkit.org/show_bug.cgi?id=46418 - Flexible box support.
1744         if (style->writingMode() != TopToBottomWritingMode && (style->display() == TABLE || style->display() == INLINE_TABLE
1745             || style->display() == TABLE_HEADER_GROUP || style->display() == TABLE_ROW_GROUP
1746             || style->display() == TABLE_FOOTER_GROUP || style->display() == TABLE_ROW || style->display() == TABLE_CELL
1747             || style->display() == BOX || style->display() == INLINE_BOX))
1748             style->setWritingMode(TopToBottomWritingMode);
1749     }
1750
1751     // Make sure our z-index value is only applied if the object is positioned.
1752     if (style->position() == StaticPosition)
1753         style->setHasAutoZIndex();
1754
1755     // Auto z-index becomes 0 for the root element and transparent objects.  This prevents
1756     // cases where objects that should be blended as a single unit end up with a non-transparent
1757     // object wedged in between them.  Auto z-index also becomes 0 for objects that specify transforms/masks/reflections.
1758     if (style->hasAutoZIndex() && ((e && e->document()->documentElement() == e) || style->opacity() < 1.0f || 
1759         style->hasTransformRelatedProperty() || style->hasMask() || style->boxReflect()))
1760         style->setZIndex(0);
1761     
1762 #if ENABLE(WML)
1763     if (e && (e->hasTagName(WMLNames::insertedLegendTag)
1764               || e->hasTagName(WMLNames::inputTag))
1765             && style->width().isAuto())
1766         style->setWidth(Length(Intrinsic));
1767 #endif
1768
1769     // Textarea considers overflow visible as auto.
1770     if (e && e->hasTagName(textareaTag)) {
1771         style->setOverflowX(style->overflowX() == OVISIBLE ? OAUTO : style->overflowX());
1772         style->setOverflowY(style->overflowY() == OVISIBLE ? OAUTO : style->overflowY());
1773     }
1774
1775     // Finally update our text decorations in effect, but don't allow text-decoration to percolate through
1776     // tables, inline blocks, inline tables, or run-ins.
1777     if (style->display() == TABLE || style->display() == INLINE_TABLE || style->display() == RUN_IN
1778         || style->display() == INLINE_BLOCK || style->display() == INLINE_BOX)
1779         style->setTextDecorationsInEffect(style->textDecoration());
1780     else
1781         style->addToTextDecorationsInEffect(style->textDecoration());
1782     
1783     // If either overflow value is not visible, change to auto.
1784     if (style->overflowX() == OMARQUEE && style->overflowY() != OMARQUEE)
1785         style->setOverflowY(OMARQUEE);
1786     else if (style->overflowY() == OMARQUEE && style->overflowX() != OMARQUEE)
1787         style->setOverflowX(OMARQUEE);
1788     else if (style->overflowX() == OVISIBLE && style->overflowY() != OVISIBLE)
1789         style->setOverflowX(OAUTO);
1790     else if (style->overflowY() == OVISIBLE && style->overflowX() != OVISIBLE)
1791         style->setOverflowY(OAUTO);
1792
1793     // Table rows, sections and the table itself will support overflow:hidden and will ignore scroll/auto.
1794     // FIXME: Eventually table sections will support auto and scroll.
1795     if (style->display() == TABLE || style->display() == INLINE_TABLE ||
1796         style->display() == TABLE_ROW_GROUP || style->display() == TABLE_ROW) {
1797         if (style->overflowX() != OVISIBLE && style->overflowX() != OHIDDEN) 
1798             style->setOverflowX(OVISIBLE);
1799         if (style->overflowY() != OVISIBLE && style->overflowY() != OHIDDEN) 
1800             style->setOverflowY(OVISIBLE);
1801     }
1802
1803     // Menulists should have visible overflow
1804     if (style->appearance() == MenulistPart) {
1805         style->setOverflowX(OVISIBLE);
1806         style->setOverflowY(OVISIBLE);
1807     }
1808
1809     // Cull out any useless layers and also repeat patterns into additional layers.
1810     style->adjustBackgroundLayers();
1811     style->adjustMaskLayers();
1812
1813     // Do the same for animations and transitions.
1814     style->adjustAnimations();
1815     style->adjustTransitions();
1816
1817     // Important: Intrinsic margins get added to controls before the theme has adjusted the style, since the theme will
1818     // alter fonts and heights/widths.
1819     if (e && e->isFormControlElement() && style->fontSize() >= 11) {
1820         // Don't apply intrinsic margins to image buttons.  The designer knows how big the images are,
1821         // so we have to treat all image buttons as though they were explicitly sized.
1822         if (!e->hasTagName(inputTag) || !static_cast<HTMLInputElement*>(e)->isImageButton())
1823             addIntrinsicMargins(style);
1824     }
1825
1826     // Let the theme also have a crack at adjusting the style.
1827     if (style->hasAppearance())
1828         RenderTheme::defaultTheme()->adjustStyle(this, style, e, m_hasUAAppearance, m_borderData, m_backgroundData, m_backgroundColor);
1829
1830 #if ENABLE(SVG)
1831     if (e && e->isSVGElement()) {
1832         // Spec: http://www.w3.org/TR/SVG/masking.html#OverflowProperty
1833         if (style->overflowY() == OSCROLL)
1834             style->setOverflowY(OHIDDEN);
1835         else if (style->overflowY() == OAUTO)
1836             style->setOverflowY(OVISIBLE);
1837
1838         if (style->overflowX() == OSCROLL)
1839             style->setOverflowX(OHIDDEN);
1840         else if (style->overflowX() == OAUTO)
1841             style->setOverflowX(OVISIBLE);
1842
1843         // Only the root <svg> element in an SVG document fragment tree honors css position
1844         if (!(e->hasTagName(SVGNames::svgTag) && e->parentNode() && !e->parentNode()->isSVGElement()))
1845             style->setPosition(RenderStyle::initialPosition());
1846     }
1847 #endif
1848 }
1849
1850 void CSSStyleSelector::updateFont()
1851 {
1852     checkForTextSizeAdjust();
1853     checkForGenericFamilyChange(style(), m_parentStyle);
1854     checkForZoomChange(style(), m_parentStyle);
1855     m_style->font().update(m_fontSelector);
1856     m_fontDirty = false;
1857 }
1858
1859 void CSSStyleSelector::cacheBorderAndBackground()
1860 {
1861     m_hasUAAppearance = m_style->hasAppearance();
1862     if (m_hasUAAppearance) {
1863         m_borderData = m_style->border();
1864         m_backgroundData = *m_style->backgroundLayers();
1865         m_backgroundColor = m_style->backgroundColor();
1866     }
1867 }
1868
1869 PassRefPtr<CSSRuleList> CSSStyleSelector::styleRulesForElement(Element* e, bool authorOnly, bool includeEmptyRules)
1870 {
1871     return pseudoStyleRulesForElement(e, NOPSEUDO, authorOnly, includeEmptyRules);
1872 }
1873
1874 PassRefPtr<CSSRuleList> CSSStyleSelector::pseudoStyleRulesForElement(Element* e, PseudoId pseudoId, bool authorOnly, bool includeEmptyRules)
1875 {
1876     if (!e || !e->document()->haveStylesheetsLoaded())
1877         return 0;
1878
1879     m_checker.m_collectRulesOnly = true;
1880
1881     initElement(e);
1882     initForStyleResolve(e, 0, pseudoId);
1883
1884     if (!authorOnly) {
1885         int firstUARule = -1, lastUARule = -1;
1886         // First we match rules from the user agent sheet.
1887         matchUARules(firstUARule, lastUARule);
1888
1889         // Now we check user sheet rules.
1890         if (m_matchAuthorAndUserStyles) {
1891             int firstUserRule = -1, lastUserRule = -1;
1892             matchRules(m_userStyle.get(), firstUserRule, lastUserRule, includeEmptyRules);
1893         }
1894     }
1895
1896     if (m_matchAuthorAndUserStyles) {
1897         // Check the rules in author sheets.
1898         int firstAuthorRule = -1, lastAuthorRule = -1;
1899         matchRules(m_authorStyle.get(), firstAuthorRule, lastAuthorRule, includeEmptyRules);
1900     }
1901
1902     m_checker.m_collectRulesOnly = false;
1903     
1904     return m_ruleList.release();
1905 }
1906
1907 bool CSSStyleSelector::checkSelector(CSSSelector* sel)
1908 {
1909     m_dynamicPseudo = NOPSEUDO;
1910
1911     // Check the selector
1912     if (!m_checker.checkSelector(sel, m_element, &m_selectorAttrs, m_dynamicPseudo, false, false, style(), m_parentNode ? m_parentNode->renderStyle() : 0))
1913         return false;
1914
1915     if (m_checker.m_pseudoStyle != NOPSEUDO && m_checker.m_pseudoStyle != m_dynamicPseudo)
1916         return false;
1917
1918     return true;
1919 }
1920
1921 namespace {
1922
1923 // Internally used from CSSStyleSelector::SelectorChecker::checkSelector.
1924 struct CallState {
1925     enum State {
1926         SeekingDescendant, SeekingIndirectAdjacent,
1927     };
1928
1929     State state;
1930     CSSSelector* selector;
1931     Element* element;
1932     bool isSubSelector;
1933     bool encounteredLink;
1934     RenderStyle* elementStyle;
1935     RenderStyle* elementParentStyle;
1936
1937     CallState(State state, CSSSelector* selector, Element* element, bool isSubSelector, bool encounteredLink, RenderStyle* elementStyle, RenderStyle* elementParentStyle)
1938         : state(state)
1939         , selector(selector)
1940         , element(element)
1941         , isSubSelector(isSubSelector)
1942         , encounteredLink(encounteredLink)
1943         , elementStyle(elementStyle)
1944         , elementParentStyle(elementParentStyle)
1945     {
1946     }
1947 };
1948
1949 class CallStack {
1950 public:
1951     bool isEmpty() const
1952     {
1953         return m_stack.isEmpty();
1954     }
1955
1956     void push(const CallState& state)
1957     {
1958         m_stack.append(state);
1959     }
1960
1961     CallState pop()
1962     {
1963         ASSERT(!isEmpty());
1964         CallState state = m_stack.last();
1965         m_stack.removeLast();
1966         return state;
1967     }
1968
1969 private:
1970     Vector<CallState, 20> m_stack;
1971 };
1972
1973 } // anonymous namespace
1974
1975 // Check selectors and combinators.
1976 bool CSSStyleSelector::SelectorChecker::checkSelector(CSSSelector* selector, Element* element, HashSet<AtomicStringImpl*>* selectorAttrs, PseudoId& dynamicPseudo, bool isSubSelector, bool encounteredLink, RenderStyle* elementStyle, RenderStyle* elementParentStyle) const
1977 {
1978     // We should avoid recursive calls, which might cause stack overflow if the chain of selector is very long.
1979     // Therefore we have to maintain a call stack by ourselves so that we can check selectors iteratively.
1980     CallStack callStack;
1981     while (true) {
1982 #if ENABLE(SVG)
1983         // Spec: CSS2 selectors cannot be applied to the (conceptually) cloned DOM tree
1984         // because its contents are not part of the formal document structure.
1985         if (element->isSVGElement() && element->isShadowNode())
1986             return false;
1987 #endif
1988         // first selector has to match
1989         bool matched = checkOneSelector(selector, element, selectorAttrs, dynamicPseudo, isSubSelector, elementStyle, elementParentStyle);
1990         bool needUnwinding = !matched;
1991
1992         if (matched) {
1993             // The rest of the selectors has to match
1994             CSSSelector::Relation relation = selector->relation();
1995
1996             // Prepare next sel
1997             selector = selector->tagHistory();
1998             if (!selector)
1999                 return true;
2000
2001             if (relation != CSSSelector::SubSelector)
2002                 // Bail-out if this selector is irrelevant for the pseudoStyle
2003                 if (m_pseudoStyle != NOPSEUDO && m_pseudoStyle != dynamicPseudo)
2004                     return false;
2005
2006             // Check for nested links.
2007             if (m_matchVisitedPseudoClass && !isSubSelector) {
2008                 RenderStyle* currentStyle = elementStyle ? elementStyle : element->renderStyle();
2009                 if (currentStyle && currentStyle->insideLink() && element->isLink()) {
2010                     if (encounteredLink)
2011                         m_matchVisitedPseudoClass = false; // This link is not relevant to the style being resolved, so disable matching.
2012                     else
2013                         encounteredLink = true;
2014                 }
2015             }
2016
2017             switch (relation) {
2018             case CSSSelector::Descendant: {
2019                 ContainerNode* node = element->parentNode();
2020                 if (!node || !node->isElementNode())
2021                     return false;
2022                 element = static_cast<Element*>(node);
2023                 callStack.push(CallState(CallState::SeekingDescendant, selector, element, isSubSelector, encounteredLink, elementStyle, elementParentStyle));
2024                 isSubSelector = false;
2025                 elementStyle = 0;
2026                 elementParentStyle = 0;
2027                 break;
2028             }
2029             case CSSSelector::Child: {
2030                 ContainerNode* node = element->parentNode();
2031                 if (!node || !node->isElementNode())
2032                     return false;
2033                 element = static_cast<Element*>(node);
2034                 isSubSelector = false;
2035                 elementStyle = 0;
2036                 elementParentStyle = 0;
2037                 break;
2038             }
2039             case CSSSelector::DirectAdjacent: {
2040                 if (!m_collectRulesOnly && element->parentNode() && element->parentNode()->isElementNode()) {
2041                     RenderStyle* parentStyle = elementStyle ? elementParentStyle : element->parentNode()->renderStyle();
2042                     if (parentStyle)
2043                         parentStyle->setChildrenAffectedByDirectAdjacentRules();
2044                 }
2045                 Node* node = element->previousSibling();
2046                 while (node && !node->isElementNode())
2047                     node = node->previousSibling();
2048                 if (!node) {
2049                     needUnwinding = true;
2050                     break;
2051                 }
2052                 element = static_cast<Element*>(node);
2053                 m_matchVisitedPseudoClass = false;
2054                 isSubSelector = false;
2055                 elementStyle = 0;
2056                 elementParentStyle = 0;
2057                 break;
2058             }
2059             case CSSSelector::IndirectAdjacent: {
2060                 if (!m_collectRulesOnly && element->parentNode() && element->parentNode()->isElementNode()) {
2061                     RenderStyle* parentStyle = elementStyle ? elementParentStyle : element->parentNode()->renderStyle();
2062                     if (parentStyle)
2063                         parentStyle->setChildrenAffectedByForwardPositionalRules();
2064                 }
2065                 Node* node = element->previousSibling();
2066                 while (node && !node->isElementNode())
2067                     node = node->previousSibling();
2068                 if (!node) {
2069                     needUnwinding = true;
2070                     break;
2071                 }
2072                 element = static_cast<Element*>(node);
2073                 m_matchVisitedPseudoClass = false;
2074                 callStack.push(CallState(CallState::SeekingIndirectAdjacent, selector, element, isSubSelector, encounteredLink, elementStyle, elementParentStyle));
2075                 isSubSelector = false;
2076                 elementStyle = 0;
2077                 elementParentStyle = 0;
2078                 break;
2079             }
2080             case CSSSelector::SubSelector:
2081                 // a selector is invalid if something follows a pseudo-element
2082                 // We make an exception for scrollbar pseudo elements and allow a set of pseudo classes (but nothing else)
2083                 // to follow the pseudo elements.
2084                 if ((elementStyle || m_collectRulesOnly) && dynamicPseudo != NOPSEUDO && dynamicPseudo != SELECTION
2085                     && !((RenderScrollbar::scrollbarForStyleResolve() || dynamicPseudo == SCROLLBAR_CORNER || dynamicPseudo == RESIZER) && selector->m_match == CSSSelector::PseudoClass))
2086                     return false;
2087                 isSubSelector = true;
2088                 break;
2089             }
2090         }
2091         if (!needUnwinding)
2092             continue;
2093         while (!callStack.isEmpty()) {
2094             // Unwinds call stack.
2095             CallState callState = callStack.pop();
2096             selector = callState.selector;
2097             element = callState.element;
2098             isSubSelector = callState.isSubSelector;
2099             encounteredLink = callState.encounteredLink;
2100             elementStyle = callState.elementStyle;
2101             elementParentStyle = callState.elementParentStyle;
2102
2103             switch (callState.state) {
2104             case CallState::SeekingDescendant: {
2105                 ContainerNode* node = element->parentNode();
2106                 if (!node || !node->isElementNode())
2107                     return false;
2108                 element = static_cast<Element*>(node);
2109                 callStack.push(CallState(CallState::SeekingDescendant, selector, element, isSubSelector, encounteredLink, elementStyle, elementParentStyle));
2110                 isSubSelector = false;
2111                 elementStyle = 0;
2112                 elementParentStyle = 0;
2113                 break;
2114             }
2115             case CallState::SeekingIndirectAdjacent: {
2116                 Node* node = element->previousSibling();
2117                 while (node && !node->isElementNode())
2118                     node = node->previousSibling();
2119                 if (!node)
2120                     continue; // Continue to next while loop to unwind callStack further.
2121                 element = static_cast<Element*>(node);
2122                 m_matchVisitedPseudoClass = false;
2123                 callStack.push(CallState(CallState::SeekingIndirectAdjacent, selector, element, isSubSelector, encounteredLink, elementStyle, elementParentStyle));
2124                 isSubSelector = false;
2125                 elementStyle = 0;
2126                 elementParentStyle = 0;
2127                 break;
2128             }
2129             }
2130             break;
2131         }
2132         if (callStack.isEmpty())
2133             return false;
2134     }
2135 }
2136
2137 static void addLocalNameToSet(HashSet<AtomicStringImpl*>* set, const QualifiedName& qName)
2138 {
2139     set->add(qName.localName().impl());
2140 }
2141
2142 static HashSet<AtomicStringImpl*>* createHtmlCaseInsensitiveAttributesSet()
2143 {
2144     // This is the list of attributes in HTML 4.01 with values marked as "[CI]" or case-insensitive
2145     // Mozilla treats all other values as case-sensitive, thus so do we.
2146     HashSet<AtomicStringImpl*>* attrSet = new HashSet<AtomicStringImpl*>;
2147
2148     addLocalNameToSet(attrSet, accept_charsetAttr);
2149     addLocalNameToSet(attrSet, acceptAttr);
2150     addLocalNameToSet(attrSet, alignAttr);
2151     addLocalNameToSet(attrSet, alinkAttr);
2152     addLocalNameToSet(attrSet, axisAttr);
2153     addLocalNameToSet(attrSet, bgcolorAttr);
2154     addLocalNameToSet(attrSet, charsetAttr);
2155     addLocalNameToSet(attrSet, checkedAttr);
2156     addLocalNameToSet(attrSet, clearAttr);
2157     addLocalNameToSet(attrSet, codetypeAttr);
2158     addLocalNameToSet(attrSet, colorAttr);
2159     addLocalNameToSet(attrSet, compactAttr);
2160     addLocalNameToSet(attrSet, declareAttr);
2161     addLocalNameToSet(attrSet, deferAttr);
2162     addLocalNameToSet(attrSet, dirAttr);
2163     addLocalNameToSet(attrSet, disabledAttr);
2164     addLocalNameToSet(attrSet, enctypeAttr);
2165     addLocalNameToSet(attrSet, faceAttr);
2166     addLocalNameToSet(attrSet, frameAttr);
2167     addLocalNameToSet(attrSet, hreflangAttr);
2168     addLocalNameToSet(attrSet, http_equivAttr);
2169     addLocalNameToSet(attrSet, langAttr);
2170     addLocalNameToSet(attrSet, languageAttr);
2171     addLocalNameToSet(attrSet, linkAttr);
2172     addLocalNameToSet(attrSet, mediaAttr);
2173     addLocalNameToSet(attrSet, methodAttr);
2174     addLocalNameToSet(attrSet, multipleAttr);
2175     addLocalNameToSet(attrSet, nohrefAttr);
2176     addLocalNameToSet(attrSet, noresizeAttr);
2177     addLocalNameToSet(attrSet, noshadeAttr);
2178     addLocalNameToSet(attrSet, nowrapAttr);
2179     addLocalNameToSet(attrSet, readonlyAttr);
2180     addLocalNameToSet(attrSet, relAttr);
2181     addLocalNameToSet(attrSet, revAttr);
2182     addLocalNameToSet(attrSet, rulesAttr);
2183     addLocalNameToSet(attrSet, scopeAttr);
2184     addLocalNameToSet(attrSet, scrollingAttr);
2185     addLocalNameToSet(attrSet, selectedAttr);
2186     addLocalNameToSet(attrSet, shapeAttr);
2187     addLocalNameToSet(attrSet, targetAttr);
2188     addLocalNameToSet(attrSet, textAttr);
2189     addLocalNameToSet(attrSet, typeAttr);
2190     addLocalNameToSet(attrSet, valignAttr);
2191     addLocalNameToSet(attrSet, valuetypeAttr);
2192     addLocalNameToSet(attrSet, vlinkAttr);
2193
2194     return attrSet;
2195 }
2196
2197 static bool htmlAttributeHasCaseInsensitiveValue(const QualifiedName& attr)
2198 {
2199     static HashSet<AtomicStringImpl*>* htmlCaseInsensitiveAttributesSet = createHtmlCaseInsensitiveAttributesSet();
2200     bool isPossibleHTMLAttr = !attr.hasPrefix() && (attr.namespaceURI() == nullAtom);
2201     return isPossibleHTMLAttr && htmlCaseInsensitiveAttributesSet->contains(attr.localName().impl());
2202 }
2203
2204 bool CSSStyleSelector::SelectorChecker::checkOneSelector(CSSSelector* sel, Element* e, HashSet<AtomicStringImpl*>* selectorAttrs, PseudoId& dynamicPseudo, bool isSubSelector, RenderStyle* elementStyle, RenderStyle* elementParentStyle) const
2205 {
2206     if (!e)
2207         return false;
2208
2209     if (sel->hasTag()) {
2210         const AtomicString& selLocalName = sel->m_tag.localName();
2211         if (selLocalName != starAtom && selLocalName != e->localName())
2212             return false;
2213         const AtomicString& selNS = sel->m_tag.namespaceURI();
2214         if (selNS != starAtom && selNS != e->namespaceURI())
2215             return false;
2216     }
2217
2218     if (sel->hasAttribute()) {
2219         if (sel->m_match == CSSSelector::Class)
2220             return e->hasClass() && static_cast<StyledElement*>(e)->classNames().contains(sel->m_value);
2221
2222         if (sel->m_match == CSSSelector::Id)
2223             return e->hasID() && e->idForStyleResolution() == sel->m_value;
2224         
2225         const QualifiedName& attr = sel->attribute();
2226
2227         // FIXME: Handle the case were elementStyle is 0.
2228         if (elementStyle && (!e->isStyledElement() || (!static_cast<StyledElement*>(e)->isMappedAttribute(attr) && attr != typeAttr && attr != readonlyAttr))) {
2229             elementStyle->setAffectedByAttributeSelectors(); // Special-case the "type" and "readonly" attributes so input form controls can share style.
2230             if (selectorAttrs)
2231                 selectorAttrs->add(attr.localName().impl());
2232         }
2233
2234         const AtomicString& value = e->getAttribute(attr);
2235         if (value.isNull())
2236             return false; // attribute is not set
2237
2238         bool caseSensitive = !m_documentIsHTML || !htmlAttributeHasCaseInsensitiveValue(attr);
2239
2240         switch (sel->m_match) {
2241         case CSSSelector::Exact:
2242             if (caseSensitive ? sel->m_value != value : !equalIgnoringCase(sel->m_value, value))
2243                 return false;
2244             break;
2245         case CSSSelector::List:
2246         {
2247             // Ignore empty selectors or selectors containing spaces
2248             if (sel->m_value.contains(' ') || sel->m_value.isEmpty())
2249                 return false;
2250
2251             unsigned startSearchAt = 0;
2252             while (true) {
2253                 size_t foundPos = value.find(sel->m_value, startSearchAt, caseSensitive);
2254                 if (foundPos == notFound)
2255                     return false;
2256                 if (foundPos == 0 || value[foundPos - 1] == ' ') {
2257                     unsigned endStr = foundPos + sel->m_value.length();
2258                     if (endStr == value.length() || value[endStr] == ' ')
2259                         break; // We found a match.
2260                 }
2261                 
2262                 // No match. Keep looking.
2263                 startSearchAt = foundPos + 1;
2264             }
2265             break;
2266         }
2267         case CSSSelector::Contain:
2268             if (!value.contains(sel->m_value, caseSensitive) || sel->m_value.isEmpty())
2269                 return false;
2270             break;
2271         case CSSSelector::Begin:
2272             if (!value.startsWith(sel->m_value, caseSensitive) || sel->m_value.isEmpty())
2273                 return false;
2274             break;
2275         case CSSSelector::End:
2276             if (!value.endsWith(sel->m_value, caseSensitive) || sel->m_value.isEmpty())
2277                 return false;
2278             break;
2279         case CSSSelector::Hyphen:
2280             if (value.length() < sel->m_value.length())
2281                 return false;
2282             if (!value.startsWith(sel->m_value, caseSensitive))
2283                 return false;
2284             // It they start the same, check for exact match or following '-':
2285             if (value.length() != sel->m_value.length() && value[sel->m_value.length()] != '-')
2286                 return false;
2287             break;
2288         case CSSSelector::PseudoClass:
2289         case CSSSelector::PseudoElement:
2290         default:
2291             break;
2292         }
2293     }
2294     
2295     if (sel->m_match == CSSSelector::PseudoClass) {
2296         // Handle :not up front.
2297         if (sel->pseudoType() == CSSSelector::PseudoNot) {
2298             // check the simple selector
2299             for (CSSSelector* subSel = sel->simpleSelector(); subSel; subSel = subSel->tagHistory()) {
2300                 // :not cannot nest. I don't really know why this is a
2301                 // restriction in CSS3, but it is, so let's honor it.
2302                 // the parser enforces that this never occurs
2303                 ASSERT(!subSel->simpleSelector());
2304
2305                 if (!checkOneSelector(subSel, e, selectorAttrs, dynamicPseudo, true, elementStyle, elementParentStyle))
2306                     return true;
2307             }
2308         } else if (dynamicPseudo != NOPSEUDO && (RenderScrollbar::scrollbarForStyleResolve() || dynamicPseudo == SCROLLBAR_CORNER || dynamicPseudo == RESIZER)) {
2309             // CSS scrollbars match a specific subset of pseudo classes, and they have specialized rules for each
2310             // (since there are no elements involved).
2311             return checkScrollbarPseudoClass(sel, dynamicPseudo);
2312         } else if (dynamicPseudo == SELECTION) {
2313             if (sel->pseudoType() == CSSSelector::PseudoWindowInactive)
2314                 return !m_document->page()->focusController()->isActive();
2315         }
2316         
2317         // Normal element pseudo class checking.
2318         switch (sel->pseudoType()) {
2319             // Pseudo classes:
2320             case CSSSelector::PseudoNot:
2321                 break; // Already handled up above.
2322             case CSSSelector::PseudoEmpty: {
2323                 bool result = true;
2324                 for (Node* n = e->firstChild(); n; n = n->nextSibling()) {
2325                     if (n->isElementNode()) {
2326                         result = false;
2327                         break;
2328                     } else if (n->isTextNode()) {
2329                         Text* textNode = static_cast<Text*>(n);
2330                         if (!textNode->data().isEmpty()) {
2331                             result = false;
2332                             break;
2333                         }
2334                     }
2335                 }
2336                 if (!m_collectRulesOnly) {
2337                     if (elementStyle)
2338                         elementStyle->setEmptyState(result);
2339                     else if (e->renderStyle() && (e->document()->usesSiblingRules() || e->renderStyle()->unique()))
2340                         e->renderStyle()->setEmptyState(result);
2341                 }
2342                 return result;
2343             }
2344             case CSSSelector::PseudoFirstChild: {
2345                 // first-child matches the first child that is an element
2346                 if (e->parentNode() && e->parentNode()->isElementNode()) {
2347                     bool result = false;
2348                     Node* n = e->previousSibling();
2349                     while (n && !n->isElementNode())
2350                         n = n->previousSibling();
2351                     if (!n)
2352                         result = true;
2353                     if (!m_collectRulesOnly) {
2354                         RenderStyle* childStyle = elementStyle ? elementStyle : e->renderStyle();
2355                         RenderStyle* parentStyle = elementStyle ? elementParentStyle : e->parentNode()->renderStyle();
2356                         if (parentStyle)
2357                             parentStyle->setChildrenAffectedByFirstChildRules();
2358                         if (result && childStyle)
2359                             childStyle->setFirstChildState();
2360                     }
2361                     return result;
2362                 }
2363                 break;
2364             }
2365             case CSSSelector::PseudoFirstOfType: {
2366                 // first-of-type matches the first element of its type
2367                 if (e->parentNode() && e->parentNode()->isElementNode()) {
2368                     bool result = false;
2369                     const QualifiedName& type = e->tagQName();
2370                     Node* n = e->previousSibling();
2371                     while (n) {
2372                         if (n->isElementNode() && static_cast<Element*>(n)->hasTagName(type))
2373                             break;
2374                         n = n->previousSibling();
2375                     }
2376                     if (!n)
2377                         result = true;
2378                     if (!m_collectRulesOnly) {
2379                         RenderStyle* parentStyle = elementStyle ? elementParentStyle : e->parentNode()->renderStyle();
2380                         if (parentStyle)
2381                             parentStyle->setChildrenAffectedByForwardPositionalRules();
2382                     }
2383                     return result;
2384                 }
2385                 break;
2386             }
2387             case CSSSelector::PseudoLastChild: {
2388                 // last-child matches the last child that is an element
2389                 if (Element* parentElement = e->parentElement()) {
2390                     bool result = false;
2391                     if (parentElement->isFinishedParsingChildren()) {
2392                         Node* n = e->nextSibling();
2393                         while (n && !n->isElementNode())
2394                             n = n->nextSibling();
2395                         if (!n)
2396                             result = true;
2397                     }
2398                     if (!m_collectRulesOnly) {
2399                         RenderStyle* childStyle = elementStyle ? elementStyle : e->renderStyle();
2400                         RenderStyle* parentStyle = elementStyle ? elementParentStyle : parentElement->renderStyle();
2401                         if (parentStyle)
2402                             parentStyle->setChildrenAffectedByLastChildRules();
2403                         if (result && childStyle)
2404                             childStyle->setLastChildState();
2405                     }
2406                     return result;
2407                 }
2408                 break;
2409             }
2410             case CSSSelector::PseudoLastOfType: {
2411                 // last-of-type matches the last element of its type
2412                 if (Element* parentElement = e->parentElement()) {
2413                     if (!m_collectRulesOnly) {
2414                         RenderStyle* parentStyle = elementStyle ? elementParentStyle : parentElement->renderStyle();
2415                         if (parentStyle)
2416                             parentStyle->setChildrenAffectedByBackwardPositionalRules();
2417                     }
2418                     if (!parentElement->isFinishedParsingChildren())
2419                         return false;
2420                     bool result = false;
2421                     const QualifiedName& type = e->tagQName();
2422                     Node* n = e->nextSibling();
2423                     while (n) {
2424                         if (n->isElementNode() && static_cast<Element*>(n)->hasTagName(type))
2425                             break;
2426                         n = n->nextSibling();
2427                     }
2428                     if (!n)
2429                         result = true;
2430                     return result;
2431                 }
2432                 break;
2433             }
2434             case CSSSelector::PseudoOnlyChild: {
2435                 if (Element* parentElement = e->parentElement()) {
2436                     bool firstChild = false;
2437                     bool lastChild = false;
2438                     
2439                     Node* n = e->previousSibling();
2440                     while (n && !n->isElementNode())
2441                         n = n->previousSibling();
2442                     if (!n)
2443                         firstChild = true;
2444                     if (firstChild && parentElement->isFinishedParsingChildren()) {
2445                         n = e->nextSibling();
2446                         while (n && !n->isElementNode())
2447                             n = n->nextSibling();
2448                         if (!n)
2449                             lastChild = true;
2450                     }
2451                     if (!m_collectRulesOnly) {
2452                         RenderStyle* childStyle = elementStyle ? elementStyle : e->renderStyle();
2453                         RenderStyle* parentStyle = elementStyle ? elementParentStyle : parentElement->renderStyle();
2454                         if (parentStyle) {
2455                             parentStyle->setChildrenAffectedByFirstChildRules();
2456                             parentStyle->setChildrenAffectedByLastChildRules();
2457                         }
2458                         if (firstChild && childStyle)
2459                             childStyle->setFirstChildState();
2460                         if (lastChild && childStyle)
2461                             childStyle->setLastChildState();
2462                     }
2463                     return firstChild && lastChild;
2464                 }
2465                 break;
2466             }
2467             case CSSSelector::PseudoOnlyOfType: {
2468                 // FIXME: This selector is very slow.
2469                 if (Element* parentElement = e->parentElement()) {
2470                     if (!m_collectRulesOnly) {
2471                         RenderStyle* parentStyle = elementStyle ? elementParentStyle : parentElement->renderStyle();
2472                         if (parentStyle) {
2473                             parentStyle->setChildrenAffectedByForwardPositionalRules();
2474                             parentStyle->setChildrenAffectedByBackwardPositionalRules();
2475                         }
2476                     }
2477                     if (!parentElement->isFinishedParsingChildren())
2478                         return false;
2479                     bool firstChild = false;
2480                     bool lastChild = false;
2481                     const QualifiedName& type = e->tagQName();
2482                     Node* n = e->previousSibling();
2483                     while (n) {
2484                         if (n->isElementNode() && static_cast<Element*>(n)->hasTagName(type))
2485                             break;
2486                         n = n->previousSibling();
2487                     }
2488                     if (!n)
2489                         firstChild = true;
2490                     if (firstChild) {
2491                         n = e->nextSibling();
2492                         while (n) {
2493                             if (n->isElementNode() && static_cast<Element*>(n)->hasTagName(type))
2494                                 break;
2495                             n = n->nextSibling();
2496                         }
2497                         if (!n)
2498                             lastChild = true;
2499                     }
2500                     return firstChild && lastChild;
2501                 }
2502                 break;
2503             }
2504             case CSSSelector::PseudoNthChild: {
2505                 if (!sel->parseNth())
2506                     break;
2507                 if (Element* parentElement = e->parentElement()) {
2508                     int count = 1;
2509                     Node* n = e->previousSibling();
2510                     while (n) {
2511                         if (n->isElementNode()) {
2512                             RenderStyle* s = n->renderStyle();
2513                             unsigned index = s ? s->childIndex() : 0;
2514                             if (index) {
2515                                 count += index;
2516                                 break;
2517                             }
2518                             count++;
2519                         }
2520                         n = n->previousSibling();
2521                     }
2522                     
2523                     if (!m_collectRulesOnly) {
2524                         RenderStyle* childStyle = elementStyle ? elementStyle : e->renderStyle();
2525                         RenderStyle* parentStyle = elementStyle ? elementParentStyle : parentElement->renderStyle();
2526                         if (childStyle)
2527                             childStyle->setChildIndex(count);
2528                         if (parentStyle)
2529                             parentStyle->setChildrenAffectedByForwardPositionalRules();
2530                     }
2531                     
2532                     if (sel->matchNth(count))
2533                         return true;
2534                 }
2535                 break;
2536             }
2537             case CSSSelector::PseudoNthOfType: {
2538                 if (!sel->parseNth())
2539                     break;
2540                 if (Element* parentElement = e->parentElement()) {
2541                     int count = 1;
2542                     const QualifiedName& type = e->tagQName();
2543                     Node* n = e->previousSibling();
2544                     while (n) {
2545                         if (n->isElementNode() && static_cast<Element*>(n)->hasTagName(type))
2546                             count++;
2547                         n = n->previousSibling();
2548                     }
2549                     
2550                     if (!m_collectRulesOnly) {
2551                         RenderStyle* parentStyle = elementStyle ? elementParentStyle : parentElement->renderStyle();
2552                         if (parentStyle)
2553                             parentStyle->setChildrenAffectedByForwardPositionalRules();
2554                     }
2555
2556                     if (sel->matchNth(count))
2557                         return true;
2558                 }
2559                 break;
2560             }
2561             case CSSSelector::PseudoNthLastChild: {
2562                 if (!sel->parseNth())
2563                     break;
2564                 if (Element* parentElement = e->parentElement()) {
2565                     if (!m_collectRulesOnly) {
2566                         RenderStyle* parentStyle = elementStyle ? elementParentStyle : parentElement->renderStyle();
2567                         if (parentStyle)
2568                             parentStyle->setChildrenAffectedByBackwardPositionalRules();
2569                     }
2570                     if (!parentElement->isFinishedParsingChildren())
2571                         return false;
2572                     int count = 1;
2573                     Node* n = e->nextSibling();
2574                     while (n) {
2575                         if (n->isElementNode())
2576                             count++;
2577                         n = n->nextSibling();
2578                     }
2579                     if (sel->matchNth(count))
2580                         return true;
2581                 }
2582                 break;
2583             }
2584             case CSSSelector::PseudoNthLastOfType: {
2585                 if (!sel->parseNth())
2586                     break;
2587                 if (Element* parentElement = e->parentElement()) {
2588                     if (!m_collectRulesOnly) {
2589                         RenderStyle* parentStyle = elementStyle ? elementParentStyle : parentElement->renderStyle();
2590                         if (parentStyle)
2591                             parentStyle->setChildrenAffectedByBackwardPositionalRules();
2592                     }
2593                     if (!parentElement->isFinishedParsingChildren())
2594                         return false;
2595                     int count = 1;
2596                     const QualifiedName& type = e->tagQName();
2597                     Node* n = e->nextSibling();
2598                     while (n) {
2599                         if (n->isElementNode() && static_cast<Element*>(n)->hasTagName(type))
2600                             count++;
2601                         n = n->nextSibling();
2602                     }
2603                     if (sel->matchNth(count))
2604                         return true;
2605                 }
2606                 break;
2607             }
2608             case CSSSelector::PseudoTarget:
2609                 if (e == e->document()->cssTarget())
2610                     return true;
2611                 break;
2612             case CSSSelector::PseudoAnyLink:
2613                 if (e && e->isLink())
2614                     return true;
2615                 break;
2616             case CSSSelector::PseudoAutofill: {
2617                 if (!e || !e->isFormControlElement())
2618                     break;
2619                 if (InputElement* inputElement = toInputElement(e))
2620                     return inputElement->isAutofilled();
2621                 break;
2622             }
2623             case CSSSelector::PseudoLink:
2624                 if (e && e->isLink())
2625                     return !m_matchVisitedPseudoClass;
2626                 break;
2627             case CSSSelector::PseudoVisited:
2628                 if (e && e->isLink())
2629                     return m_matchVisitedPseudoClass;
2630                 break;
2631             case CSSSelector::PseudoDrag: {
2632                 if (elementStyle)
2633                     elementStyle->setAffectedByDragRules(true);
2634                 else if (e->renderStyle())
2635                     e->renderStyle()->setAffectedByDragRules(true);
2636                 if (e->renderer() && e->renderer()->isDragging())
2637                     return true;
2638                 break;
2639             }
2640             case CSSSelector::PseudoFocus:
2641                 if (e && e->focused() && e->document()->frame() && e->document()->frame()->selection()->isFocusedAndActive())
2642                     return true;
2643                 break;
2644             case CSSSelector::PseudoHover: {
2645                 // If we're in quirks mode, then hover should never match anchors with no
2646                 // href and *:hover should not match anything.  This is important for sites like wsj.com.
2647                 if (m_strictParsing || isSubSelector || (sel->hasTag() && !e->hasTagName(aTag)) || e->isLink()) {
2648                     if (elementStyle)
2649                         elementStyle->setAffectedByHoverRules(true);
2650                     else if (e->renderStyle())
2651                         e->renderStyle()->setAffectedByHoverRules(true);
2652                     if (e->hovered())
2653                         return true;
2654                 }
2655                 break;
2656             }
2657             case CSSSelector::PseudoActive:
2658                 // If we're in quirks mode, then :active should never match anchors with no
2659                 // href and *:active should not match anything. 
2660                 if (m_strictParsing || isSubSelector || (sel->hasTag() && !e->hasTagName(aTag)) || e->isLink()) {
2661                     if (elementStyle)
2662                         elementStyle->setAffectedByActiveRules(true);
2663                     else if (e->renderStyle())
2664                         e->renderStyle()->setAffectedByActiveRules(true);
2665                     if (e->active())
2666                         return true;
2667                 }
2668                 break;
2669             case CSSSelector::PseudoEnabled:
2670                 if (e && e->isFormControlElement())
2671                     return e->isEnabledFormControl();
2672                 break;
2673             case CSSSelector::PseudoFullPageMedia:
2674                 return e && e->document() && e->document()->isMediaDocument();
2675                 break;
2676             case CSSSelector::PseudoDefault:
2677                 return e && e->isDefaultButtonForForm();
2678             case CSSSelector::PseudoDisabled:
2679                 if (e && e->isFormControlElement())
2680                     return !e->isEnabledFormControl();
2681                 break;
2682             case CSSSelector::PseudoReadOnly: {
2683                 if (!e || !e->isFormControlElement())
2684                     return false;
2685                 return e->isTextFormControl() && e->isReadOnlyFormControl();
2686             }
2687             case CSSSelector::PseudoReadWrite: {
2688                 if (!e || !e->isFormControlElement())
2689                     return false;
2690                 return e->isTextFormControl() && !e->isReadOnlyFormControl();
2691             }
2692             case CSSSelector::PseudoOptional:
2693                 return e && e->isOptionalFormControl();
2694             case CSSSelector::PseudoRequired:
2695                 return e && e->isRequiredFormControl();
2696             case CSSSelector::PseudoValid: {
2697                 if (!e)
2698                     return false;
2699                 e->document()->setContainsValidityStyleRules();
2700                 return e->willValidate() && e->isValidFormControlElement();
2701             } case CSSSelector::PseudoInvalid: {
2702                 if (!e)
2703                     return false;
2704                 e->document()->setContainsValidityStyleRules();
2705                 return (e->willValidate() && !e->isValidFormControlElement()) || e->hasUnacceptableValue();
2706             } case CSSSelector::PseudoChecked: {
2707                 if (!e || !e->isFormControlElement())
2708                     break;
2709                 // Even though WinIE allows checked and indeterminate to co-exist, the CSS selector spec says that
2710                 // you can't be both checked and indeterminate.  We will behave like WinIE behind the scenes and just
2711                 // obey the CSS spec here in the test for matching the pseudo.
2712                 InputElement* inputElement = toInputElement(e);
2713                 if (inputElement && inputElement->isChecked() && !inputElement->isIndeterminate())
2714                     return true;
2715                 break;
2716             }
2717             case CSSSelector::PseudoIndeterminate: {
2718                 if (!e || !e->isFormControlElement())
2719                     break;
2720                 InputElement* inputElement = toInputElement(e);
2721                 if (inputElement && inputElement->isIndeterminate())
2722                     return true;
2723                 break;
2724             }
2725             case CSSSelector::PseudoRoot:
2726                 if (e == e->document()->documentElement())
2727                     return true;
2728                 break;
2729             case CSSSelector::PseudoLang: {
2730                 AtomicString value = e->computeInheritedLanguage();
2731                 const AtomicString& argument = sel->argument();
2732                 if (value.isEmpty() || !value.startsWith(argument, false))
2733                     break;
2734                 if (value.length() != argument.length() && value[argument.length()] != '-')
2735                     break;
2736                 return true;
2737             }
2738 #if ENABLE(FULLSCREEN_API)
2739             case CSSSelector::PseudoFullScreen:
2740                 // While a Document is in the fullscreen state, and the document's current fullscreen 
2741                 // element is an element in the document, the 'full-screen' pseudoclass applies to 
2742                 // that element. Also, an <iframe>, <object> or <embed> element whose child browsing 
2743                 // context's Document is in the fullscreen state has the 'full-screen' pseudoclass applied.
2744                 if (!e->document()->webkitFullScreen())
2745                     return false;
2746                 if (e != e->document()->webkitCurrentFullScreenElement())
2747                     return false;
2748                 return true;
2749             case CSSSelector::PseudoFullScreenDocument:
2750                 // While a Document is in the fullscreen state, the 'full-screen-document' pseudoclass applies 
2751                 // to the root element of that Document.
2752                 if (!e->document()->webkitFullScreen())
2753                     return false;
2754                 if (e != e->document()->documentElement())
2755                     return false;
2756                 return true;
2757 #endif
2758             case CSSSelector::PseudoUnknown:
2759             case CSSSelector::PseudoNotParsed:
2760             default:
2761                 ASSERT_NOT_REACHED();
2762                 break;
2763         }
2764         return false;
2765     }
2766     if (sel->m_match == CSSSelector::PseudoElement) {
2767         if (!elementStyle && !m_collectRulesOnly)
2768             return false;
2769
2770         PseudoId pseudoId = CSSSelector::pseudoId(sel->pseudoType());
2771         if (pseudoId == FIRST_LETTER) {
2772             if (Document* document = e->document())
2773                 document->setUsesFirstLetterRules(true);
2774         }
2775         if (pseudoId != NOPSEUDO) {
2776             dynamicPseudo = pseudoId;
2777             return true;
2778         }
2779         ASSERT_NOT_REACHED();
2780         return false;
2781     }
2782     // ### add the rest of the checks...
2783     return true;
2784 }
2785
2786 bool CSSStyleSelector::SelectorChecker::checkScrollbarPseudoClass(CSSSelector* sel, PseudoId&) const
2787 {
2788     RenderScrollbar* scrollbar = RenderScrollbar::scrollbarForStyleResolve();
2789     ScrollbarPart part = RenderScrollbar::partForStyleResolve();
2790
2791     // FIXME: This is a temporary hack for resizers and scrollbar corners.  Eventually :window-inactive should become a real
2792     // pseudo class and just apply to everything.
2793     if (sel->pseudoType() == CSSSelector::PseudoWindowInactive)
2794         return !m_document->page()->focusController()->isActive();
2795     
2796     if (!scrollbar)
2797         return false;
2798         
2799     ASSERT(sel->m_match == CSSSelector::PseudoClass);
2800     switch (sel->pseudoType()) {
2801         case CSSSelector::PseudoEnabled:
2802             return scrollbar->enabled();
2803         case CSSSelector::PseudoDisabled:
2804             return !scrollbar->enabled();
2805         case CSSSelector::PseudoHover: {
2806             ScrollbarPart hoveredPart = scrollbar->hoveredPart();
2807             if (part == ScrollbarBGPart)
2808                 return hoveredPart != NoPart;
2809             if (part == TrackBGPart)
2810                 return hoveredPart == BackTrackPart || hoveredPart == ForwardTrackPart || hoveredPart == ThumbPart;
2811             return part == hoveredPart;
2812         }
2813         case CSSSelector::PseudoActive: {
2814             ScrollbarPart pressedPart = scrollbar->pressedPart();
2815             if (part == ScrollbarBGPart)
2816                 return pressedPart != NoPart;
2817             if (part == TrackBGPart)
2818                 return pressedPart == BackTrackPart || pressedPart == ForwardTrackPart || pressedPart == ThumbPart;
2819             return part == pressedPart;
2820         }
2821         case CSSSelector::PseudoHorizontal:
2822             return scrollbar->orientation() == HorizontalScrollbar;
2823         case CSSSelector::PseudoVertical:
2824             return scrollbar->orientation() == VerticalScrollbar;
2825         case CSSSelector::PseudoDecrement:
2826             return part == BackButtonStartPart || part == BackButtonEndPart || part == BackTrackPart;
2827         case CSSSelector::PseudoIncrement:
2828             return part == ForwardButtonStartPart || part == ForwardButtonEndPart || part == ForwardTrackPart;
2829         case CSSSelector::PseudoStart:
2830             return part == BackButtonStartPart || part == ForwardButtonStartPart || part == BackTrackPart;
2831         case CSSSelector::PseudoEnd:
2832             return part == BackButtonEndPart || part == ForwardButtonEndPart || part == ForwardTrackPart;
2833         case CSSSelector::PseudoDoubleButton: {
2834             ScrollbarButtonsPlacement buttonsPlacement = scrollbar->theme()->buttonsPlacement();
2835             if (part == BackButtonStartPart || part == ForwardButtonStartPart || part == BackTrackPart)
2836                 return buttonsPlacement == ScrollbarButtonsDoubleStart || buttonsPlacement == ScrollbarButtonsDoubleBoth;
2837             if (part == BackButtonEndPart || part == ForwardButtonEndPart || part == ForwardTrackPart)
2838                 return buttonsPlacement == ScrollbarButtonsDoubleEnd || buttonsPlacement == ScrollbarButtonsDoubleBoth;
2839             return false;
2840         } 
2841         case CSSSelector::PseudoSingleButton: {
2842             ScrollbarButtonsPlacement buttonsPlacement = scrollbar->theme()->buttonsPlacement();
2843             if (part == BackButtonStartPart || part == ForwardButtonEndPart || part == BackTrackPart || part == ForwardTrackPart)
2844                 return buttonsPlacement == ScrollbarButtonsSingle;
2845             return false;
2846         }
2847         case CSSSelector::PseudoNoButton: {
2848             ScrollbarButtonsPlacement buttonsPlacement = scrollbar->theme()->buttonsPlacement();
2849             if (part == BackTrackPart)
2850                 return buttonsPlacement == ScrollbarButtonsNone || buttonsPlacement == ScrollbarButtonsDoubleEnd;
2851             if (part == ForwardTrackPart)
2852                 return buttonsPlacement == ScrollbarButtonsNone || buttonsPlacement == ScrollbarButtonsDoubleStart;
2853             return false;
2854         }
2855         case CSSSelector::PseudoCornerPresent:
2856             return scrollbar->client()->scrollbarCornerPresent();
2857         default:
2858             return false;
2859     }
2860 }
2861
2862 void CSSStyleSelector::addVariables(CSSVariablesRule* variables)
2863 {
2864     CSSVariablesDeclaration* decl = variables->variables();
2865     if (!decl)
2866         return;
2867     unsigned size = decl->length();
2868     for (unsigned i = 0; i < size; ++i) {
2869         String name = decl->item(i);
2870         m_variablesMap.set(name, variables);
2871     }
2872 }
2873
2874 CSSValue* CSSStyleSelector::resolveVariableDependentValue(CSSVariableDependentValue*)
2875 {
2876     return 0;
2877 }
2878
2879 // -----------------------------------------------------------------
2880
2881 CSSRuleSet::CSSRuleSet()
2882     : m_ruleCount(0)
2883     , m_pageRuleCount(0)
2884 {
2885 }
2886
2887 CSSRuleSet::~CSSRuleSet()
2888
2889     deleteAllValues(m_idRules);
2890     deleteAllValues(m_classRules);
2891     deleteAllValues(m_tagRules);
2892 }
2893
2894
2895 void CSSRuleSet::addToRuleSet(AtomicStringImpl* key, AtomRuleMap& map,
2896                               CSSStyleRule* rule, CSSSelector* sel)
2897 {
2898     if (!key) return;
2899     CSSRuleDataList* rules = map.get(key);
2900     if (!rules) {
2901         rules = new CSSRuleDataList(m_ruleCount++, rule, sel);
2902         map.set(key, rules);
2903     } else
2904         rules->append(m_ruleCount++, rule, sel);
2905 }
2906
2907 void CSSRuleSet::addRule(CSSStyleRule* rule, CSSSelector* sel)
2908 {
2909     if (sel->m_match == CSSSelector::Id) {
2910         addToRuleSet(sel->m_value.impl(), m_idRules, rule, sel);
2911         return;
2912     }
2913     if (sel->m_match == CSSSelector::Class) {
2914         addToRuleSet(sel->m_value.impl(), m_classRules, rule, sel);
2915         return;
2916     }
2917      
2918     const AtomicString& localName = sel->m_tag.localName();
2919     if (localName != starAtom) {
2920         addToRuleSet(localName.impl(), m_tagRules, rule, sel);
2921         return;
2922     }
2923     
2924     // Just put it in the universal rule set.
2925     if (!m_universalRules)
2926         m_universalRules = adoptPtr(new CSSRuleDataList(m_ruleCount++, rule, sel));
2927     else
2928         m_universalRules->append(m_ruleCount++, rule, sel);
2929 }
2930
2931 void CSSRuleSet::addPageRule(CSSStyleRule* rule, CSSSelector* sel)
2932 {
2933     if (!m_pageRules)
2934         m_pageRules = adoptPtr(new CSSRuleDataList(m_pageRuleCount++, rule, sel));
2935     else
2936         m_pageRules->append(m_pageRuleCount++, rule, sel);
2937 }
2938
2939 void CSSRuleSet::addRulesFromSheet(CSSStyleSheet* sheet, const MediaQueryEvaluator& medium, CSSStyleSelector* styleSelector)
2940 {
2941     if (!sheet)
2942         return;
2943
2944     // No media implies "all", but if a media list exists it must
2945     // contain our current medium
2946     if (sheet->media() && !medium.eval(sheet->media(), styleSelector))
2947         return; // the style sheet doesn't apply
2948
2949     int len = sheet->length();
2950
2951     for (int i = 0; i < len; i++) {
2952         StyleBase* item = sheet->item(i);
2953         if (item->isStyleRule()) {
2954             addStyleRule(item);
2955         }
2956         else if (item->isImportRule()) {
2957             CSSImportRule* import = static_cast<CSSImportRule*>(item);
2958             if (!import->media() || medium.eval(import->media(), styleSelector))
2959                 addRulesFromSheet(import->styleSheet(), medium, styleSelector);
2960         }
2961         else if (item->isMediaRule()) {
2962             CSSMediaRule* r = static_cast<CSSMediaRule*>(item);
2963             CSSRuleList* rules = r->cssRules();
2964
2965             if ((!r->media() || medium.eval(r->media(), styleSelector)) && rules) {
2966                 // Traverse child elements of the @media rule.
2967                 for (unsigned j = 0; j < rules->length(); j++) {
2968                     CSSRule *childItem = rules->item(j);
2969                     if (childItem->isStyleRule()) {
2970                         // It is a StyleRule, so append it to our list
2971                         addStyleRule(childItem);
2972                     } else if (childItem->isFontFaceRule() && styleSelector) {
2973                         // Add this font face to our set.
2974                         const CSSFontFaceRule* fontFaceRule = static_cast<CSSFontFaceRule*>(childItem);
2975                         styleSelector->fontSelector()->addFontFaceRule(fontFaceRule);
2976                     } else if (childItem->isKeyframesRule() && styleSelector) {
2977                         // Add this keyframe rule to our set.
2978                         styleSelector->addKeyframeStyle(static_cast<WebKitCSSKeyframesRule*>(childItem));
2979                     }
2980                 }   // for rules
2981             }   // if rules
2982         } else if (item->isFontFaceRule() && styleSelector) {
2983             // Add this font face to our set.
2984             const CSSFontFaceRule* fontFaceRule = static_cast<CSSFontFaceRule*>(item);
2985             styleSelector->fontSelector()->addFontFaceRule(fontFaceRule);
2986         } else if (item->isVariablesRule()) {
2987             // Evaluate the media query and make sure it matches.
2988             CSSVariablesRule* variables = static_cast<CSSVariablesRule*>(item);
2989             if (!variables->media() || medium.eval(variables->media(), styleSelector))
2990                 styleSelector->addVariables(variables);
2991         } else if (item->isKeyframesRule())
2992             styleSelector->addKeyframeStyle(static_cast<WebKitCSSKeyframesRule*>(item));
2993     }
2994 }
2995
2996 void CSSRuleSet::addStyleRule(StyleBase* item)
2997 {
2998     if (item->isPageRule()) {
2999         CSSPageRule* pageRule = static_cast<CSSPageRule*>(item);
3000         addPageRule(pageRule, pageRule->selectorList().first());
3001     } else {
3002         CSSStyleRule* rule = static_cast<CSSStyleRule*>(item);
3003         for (CSSSelector* s = rule->selectorList().first(); s; s = CSSSelectorList::next(s))
3004             addRule(rule, s);
3005     }
3006 }
3007
3008 // -------------------------------------------------------------------------------------
3009 // this is mostly boring stuff on how to apply a certain rule to the renderstyle...
3010
3011 static Length convertToLength(CSSPrimitiveValue* primitiveValue, RenderStyle* style, RenderStyle* rootStyle, double multiplier = 1, bool *ok = 0)
3012 {
3013     // This function is tolerant of a null style value. The only place style is used is in
3014     // length measurements, like 'ems' and 'px'. And in those cases style is only used
3015     // when the units are EMS or EXS. So we will just fail in those cases.
3016     Length l;
3017     if (!primitiveValue) {
3018         if (ok)
3019             *ok = false;
3020     } else {
3021         int type = primitiveValue->primitiveType();
3022         
3023         if (!style && (type == CSSPrimitiveValue::CSS_EMS || type == CSSPrimitiveValue::CSS_EXS || type == CSSPrimitiveValue::CSS_REMS)) {
3024             if (ok)
3025                 *ok = false;
3026         } else if (CSSPrimitiveValue::isUnitTypeLength(type))
3027             l = Length(primitiveValue->computeLengthIntForLength(style, rootStyle, multiplier), Fixed);
3028         else if (type == CSSPrimitiveValue::CSS_PERCENTAGE)
3029             l = Length(primitiveValue->getDoubleValue(), Percent);
3030         else if (type == CSSPrimitiveValue::CSS_NUMBER)
3031             l = Length(primitiveValue->getDoubleValue() * 100.0, Percent);
3032         else if (ok)
3033             *ok = false;
3034     }
3035     return l;
3036 }
3037
3038 template <bool applyFirst>
3039 void CSSStyleSelector::applyDeclarations(bool isImportant, int startIndex, int endIndex)
3040 {
3041     if (startIndex == -1)
3042         return;
3043
3044     for (int i = startIndex; i <= endIndex; i++) {
3045         CSSMutableStyleDeclaration* decl = m_matchedDecls[i];
3046         CSSMutableStyleDeclaration::const_iterator end = decl->end();
3047         for (CSSMutableStyleDeclaration::const_iterator it = decl->begin(); it != end; ++it) {
3048             const CSSProperty& current = *it;
3049             if (isImportant == current.isImportant()) {
3050                 int property = current.id();
3051
3052                 if (applyFirst) {
3053                     COMPILE_ASSERT(firstCSSProperty == CSSPropertyColor, CSS_color_is_first_property);
3054                     COMPILE_ASSERT(CSSPropertyZoom == CSSPropertyColor + 13, CSS_zoom_is_end_of_first_prop_range);
3055                     COMPILE_ASSERT(CSSPropertyLineHeight == CSSPropertyZoom + 1, CSS_line_height_is_after_zoom);
3056
3057                     // give special priority to font-xxx, color properties, etc
3058                     if (property <= CSSPropertyLineHeight) {
3059                         // we apply line-height later
3060                         if (property == CSSPropertyLineHeight)
3061                             m_lineHeightValue = current.value(); 
3062                         else 
3063                             applyProperty(current.id(), current.value());
3064                     }
3065                 } else {
3066                     if (property > CSSPropertyLineHeight)
3067                         applyProperty(current.id(), current.value());
3068                 }
3069             }
3070         }
3071     }
3072 }
3073
3074 void CSSStyleSelector::matchPageRules(CSSRuleSet* rules, bool isLeftPage, bool isFirstPage, const String& pageName)
3075 {
3076     m_matchedRules.clear();
3077
3078     if (!rules)
3079         return;
3080
3081     matchPageRulesForList(rules->getPageRules(), isLeftPage, isFirstPage, pageName);
3082
3083     // If we didn't match any rules, we're done.
3084     if (m_matchedRules.isEmpty())
3085         return;
3086
3087     // Sort the set of matched rules.
3088     sortMatchedRules(0, m_matchedRules.size());
3089
3090     // Now transfer the set of matched rules over to our list of decls.
3091     for (unsigned i = 0; i < m_matchedRules.size(); i++)
3092         addMatchedDeclaration(m_matchedRules[i]->rule()->declaration());
3093 }
3094
3095 void CSSStyleSelector::matchPageRulesForList(CSSRuleDataList* rules, bool isLeftPage, bool isFirstPage, const String& pageName)
3096 {
3097     if (!rules)
3098         return;
3099
3100     for (CSSRuleData* d = rules->first(); d; d = d->next()) {
3101         CSSStyleRule* rule = d->rule();
3102         const AtomicString& selectorLocalName = d->selector()->m_tag.localName();
3103         if (selectorLocalName != starAtom && selectorLocalName != pageName)
3104             continue;
3105         CSSSelector::PseudoType pseudoType = d->selector()->pseudoType();
3106         if ((pseudoType == CSSSelector::PseudoLeftPage && !isLeftPage)
3107             || (pseudoType == CSSSelector::PseudoRightPage && isLeftPage)
3108             || (pseudoType == CSSSelector::PseudoFirstPage && !isFirstPage))
3109             continue;
3110
3111         // If the rule has no properties to apply, then ignore it.
3112         CSSMutableStyleDeclaration* decl = rule->declaration();
3113         if (!decl || !decl->length())
3114             continue;
3115
3116         // Add this rule to our list of matched rules.
3117         addMatchedRule(d);
3118     }
3119 }
3120
3121 bool CSSStyleSelector::isLeftPage(int pageIndex) const
3122 {
3123     bool isFirstPageLeft = false;
3124     if (!m_rootElementStyle->isLeftToRightDirection())
3125         isFirstPageLeft = true;
3126
3127     return (pageIndex + (isFirstPageLeft ? 1 : 0)) % 2;
3128 }
3129
3130 bool CSSStyleSelector::isFirstPage(int pageIndex) const
3131 {
3132     // FIXME: In case of forced left/right page, page at index 1 (not 0) can be the first page.
3133     return (!pageIndex);
3134 }
3135
3136 String CSSStyleSelector::pageName(int /* pageIndex */) const
3137 {
3138     // FIXME: Implement page index to page name mapping.
3139     return "";
3140 }
3141
3142 static void applyCounterList(RenderStyle* style, CSSValueList* list, bool isReset)
3143 {
3144     CounterDirectiveMap& map = style->accessCounterDirectives();
3145     typedef CounterDirectiveMap::iterator Iterator;
3146
3147     Iterator end = map.end();
3148     for (Iterator it = map.begin(); it != end; ++it)
3149         if (isReset)
3150             it->second.m_reset = false;
3151         else
3152             it->second.m_increment = false;
3153
3154     int length = list ? list->length() : 0;
3155     for (int i = 0; i < length; ++i) {
3156         Pair* pair = static_cast<CSSPrimitiveValue*>(list->itemWithoutBoundsCheck(i))->getPairValue();
3157         AtomicString identifier = static_cast<CSSPrimitiveValue*>(pair->first())->getStringValue();
3158         // FIXME: What about overflow?
3159         int value = static_cast<CSSPrimitiveValue*>(pair->second())->getIntValue();
3160         CounterDirectives& directives = map.add(identifier.impl(), CounterDirectives()).first->second;
3161         if (isReset) {
3162             directives.m_reset = true;
3163             directives.m_resetValue = value;
3164         } else {
3165             if (directives.m_increment)
3166                 directives.m_incrementValue += value;
3167             else {
3168                 directives.m_increment = true;
3169                 directives.m_incrementValue = value;
3170             }
3171         }
3172     }
3173 }
3174
3175 void CSSStyleSelector::applyPropertyToStyle(int id, CSSValue *value, RenderStyle* style)
3176 {
3177     initElement(0);
3178     initForStyleResolve(0, style);
3179     m_style = style;
3180     applyProperty(id, value);
3181 }
3182
3183 inline bool isValidVisitedLinkProperty(int id)
3184 {
3185     switch(static_cast<CSSPropertyID>(id)) {
3186         case CSSPropertyBackgroundColor:
3187         case CSSPropertyBorderLeftColor:
3188         case CSSPropertyBorderRightColor:
3189         case CSSPropertyBorderTopColor:
3190         case CSSPropertyBorderBottomColor:
3191         case CSSPropertyColor:
3192         case CSSPropertyOutlineColor:
3193         case CSSPropertyWebkitColumnRuleColor:
3194         case CSSPropertyWebkitTextFillColor:
3195         case CSSPropertyWebkitTextStrokeColor:
3196         // Also allow shorthands so that inherit/initial still work.
3197         case CSSPropertyBackground:
3198         case CSSPropertyBorderLeft:
3199         case CSSPropertyBorderRight:
3200         case CSSPropertyBorderTop:
3201         case CSSPropertyBorderBottom:
3202         case CSSPropertyOutline:
3203         case CSSPropertyWebkitColumnRule:
3204 #if ENABLE(SVG)
3205         case CSSPropertyFill:
3206         case CSSPropertyStroke:
3207 #endif
3208             return true;
3209         default:
3210             break;
3211     }
3212
3213     return false;
3214 }
3215
3216 void CSSStyleSelector::applyProperty(int id, CSSValue *value)
3217 {
3218     CSSPrimitiveValue* primitiveValue = 0;
3219     if (value->isPrimitiveValue())
3220         primitiveValue = static_cast<CSSPrimitiveValue*>(value);
3221
3222     float zoomFactor = m_style->effectiveZoom();
3223
3224     // SVG handles zooming in a different way compared to CSS. The whole document is scaled instead
3225     // of each individual length value in the render style / tree. CSSPrimitiveValue::computeLength*()
3226     // multiplies each resolved length with the zoom multiplier - so for SVG we need to disable that.
3227     // Though all CSS values that can be applied to outermost <svg> elements (width/height/border/padding...)
3228     // need to respect the scaling. RenderBox (the parent class of RenderSVGRoot) grabs values like
3229     // width/height/border/padding/... from the RenderStyle -> for SVG these values would never scale,
3230     // if we'd pass a 1.0 zoom factor everyhwere. So we only pass a zoom factor of 1.0 for specific
3231     // properties that are NOT allowed to scale within a zoomed SVG document (letter/word-spacing/font-size).
3232     bool useSVGZoomRules = m_element && m_element->isSVGElement();
3233
3234     Length l;
3235     bool apply = false;
3236
3237     unsigned short valueType = value->cssValueType();
3238
3239     bool isInherit = m_parentNode && valueType == CSSValue::CSS_INHERIT;
3240     bool isInitial = valueType == CSSValue::CSS_INITIAL || (!m_parentNode && valueType == CSSValue::CSS_INHERIT);
3241     
3242     id = CSSProperty::resolveDirectionAwareProperty(id, m_style->direction(), m_style->writingMode());
3243
3244     if (m_checker.m_matchVisitedPseudoClass && !isValidVisitedLinkProperty(id)) {
3245         // Limit the properties that can be applied to only the ones honored by :visited.
3246         return;
3247     }
3248     
3249     // What follows is a list that maps the CSS properties into their corresponding front-end
3250     // RenderStyle values.  Shorthands (e.g. border, background) occur in this list as well and
3251     // are only hit when mapping "inherit" or "initial" into front-end values.
3252     CSSPropertyID property = static_cast<CSSPropertyID>(id);
3253     switch (property) {
3254 // ident only properties
3255     case CSSPropertyBackgroundAttachment:
3256         HANDLE_BACKGROUND_VALUE(attachment, Attachment, value)
3257         return;
3258     case CSSPropertyBackgroundClip:
3259     case CSSPropertyWebkitBackgroundClip:
3260         HANDLE_BACKGROUND_VALUE(clip, Clip, value)
3261         return;
3262     case CSSPropertyWebkitBackgroundComposite:
3263         HANDLE_BACKGROUND_VALUE(composite, Composite, value)
3264         return;
3265     case CSSPropertyBackgroundOrigin:
3266     case CSSPropertyWebkitBackgroundOrigin: