Reviewed by Adele Peterson.
[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  *           (C) 2006 Nicholas Shanks (webkit@nickshanks.com)
5  * Copyright (C) 2005, 2006, 2007, 2008 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  *
9  * This library is free software; you can redistribute it and/or
10  * modify it under the terms of the GNU Library General Public
11  * License as published by the Free Software Foundation; either
12  * version 2 of the License, or (at your option) any later version.
13  *
14  * This library is distributed in the hope that it will be useful,
15  * but WITHOUT ANY WARRANTY; without even the implied warranty of
16  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
17  * Library General Public License for more details.
18  *
19  * You should have received a copy of the GNU Library General Public License
20  * along with this library; see the file COPYING.LIB.  If not, write to
21  * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
22  * Boston, MA 02110-1301, USA.
23  */
24
25 #include "config.h"
26 #include "CSSStyleSelector.h"
27
28 #include "CSSBorderImageValue.h"
29 #include "CSSCursorImageValue.h"
30 #include "CSSFontFace.h"
31 #include "CSSFontFaceRule.h"
32 #include "CSSFontFaceSource.h"
33 #include "CSSImageValue.h"
34 #include "CSSImportRule.h"
35 #include "CSSMediaRule.h"
36 #include "CSSPrimitiveValueMappings.h"
37 #include "CSSProperty.h"
38 #include "CSSPropertyNames.h"
39 #include "CSSRuleList.h"
40 #include "CSSSelector.h"
41 #include "CSSStyleRule.h"
42 #include "CSSStyleSheet.h"
43 #include "CSSTimingFunctionValue.h"
44 #include "CSSValueList.h"
45 #include "CachedImage.h"
46 #include "Counter.h"
47 #include "DashboardRegion.h"
48 #include "FontFamilyValue.h"
49 #include "FontValue.h"
50 #include "Frame.h"
51 #include "FrameView.h"
52 #include "GlobalHistory.h"
53 #include "HTMLDocument.h"
54 #include "HTMLElement.h"
55 #include "HTMLInputElement.h"
56 #include "HTMLNames.h"
57 #include "MediaList.h"
58 #include "MediaQueryEvaluator.h"
59 #include "Pair.h"
60 #include "Rect.h"
61 #include "RenderTheme.h"
62 #include "SelectionController.h"
63 #include "Settings.h"
64 #include "ShadowValue.h"
65 #include "StyleSheetList.h"
66 #include "Text.h"
67 #include "UserAgentStyleSheets.h"
68 #include "XMLNames.h"
69 #include "loader.h"
70 #include <wtf/Vector.h>
71
72 #if ENABLE(SVG)
73 #include "XLinkNames.h"
74 #include "SVGNames.h"
75 #endif
76
77 using namespace std;
78
79 namespace WebCore {
80
81 using namespace HTMLNames;
82
83 // #define STYLE_SHARING_STATS 1
84
85 #define HANDLE_INHERIT(prop, Prop) \
86 if (isInherit) { \
87     m_style->set##Prop(m_parentStyle->prop()); \
88     return; \
89 }
90
91 #define HANDLE_INHERIT_AND_INITIAL(prop, Prop) \
92 HANDLE_INHERIT(prop, Prop) \
93 if (isInitial) { \
94     m_style->set##Prop(RenderStyle::initial##Prop()); \
95     return; \
96 }
97
98 #define HANDLE_INHERIT_AND_INITIAL_WITH_VALUE(prop, Prop, Value) \
99 HANDLE_INHERIT(prop, Prop) \
100 if (isInitial) { \
101     m_style->set##Prop(RenderStyle::initial##Value());\
102     return;\
103 }
104
105 #define HANDLE_MULTILAYER_INHERIT_AND_INITIAL(layerType, LayerType, prop, Prop) \
106 if (isInherit) { \
107     LayerType* currChild = m_style->access##LayerType##s(); \
108     LayerType* prevChild = 0; \
109     const LayerType* currParent = m_parentStyle->layerType##s(); \
110     while (currParent && currParent->is##Prop##Set()) { \
111         if (!currChild) { \
112             /* Need to make a new layer.*/ \
113             currChild = new LayerType(); \
114             prevChild->setNext(currChild); \
115         } \
116         currChild->set##Prop(currParent->prop()); \
117         prevChild = currChild; \
118         currChild = prevChild->next(); \
119         currParent = currParent->next(); \
120     } \
121     \
122     while (currChild) { \
123         /* Reset any remaining layers to not have the property set. */ \
124         currChild->clear##Prop(); \
125         currChild = currChild->next(); \
126     } \
127 } else if (isInitial) { \
128     LayerType* currChild = m_style->access##LayerType##s(); \
129     currChild->set##Prop(RenderStyle::initial##Prop()); \
130     for (currChild = currChild->next(); currChild; currChild = currChild->next()) \
131         currChild->clear##Prop(); \
132 }
133
134 #define HANDLE_MULTILAYER_VALUE(layerType, LayerType, prop, Prop, value) { \
135 HANDLE_MULTILAYER_INHERIT_AND_INITIAL(layerType, LayerType, prop, Prop) \
136 if (isInherit || isInitial) \
137     return; \
138 LayerType* currChild = m_style->access##LayerType##s(); \
139 LayerType* prevChild = 0; \
140 if (value->isValueList()) { \
141     /* Walk each value and put it into a layer, creating new layers as needed. */ \
142     CSSValueList* valueList = static_cast<CSSValueList*>(value); \
143     for (unsigned int i = 0; i < valueList->length(); i++) { \
144         if (!currChild) { \
145             /* Need to make a new layer to hold this value */ \
146             currChild = new LayerType(); \
147             prevChild->setNext(currChild); \
148         } \
149         map##Prop(currChild, valueList->item(i)); \
150         prevChild = currChild; \
151         currChild = currChild->next(); \
152     } \
153 } else { \
154     map##Prop(currChild, value); \
155     currChild = currChild->next(); \
156 } \
157 while (currChild) { \
158     /* Reset all remaining layers to not have the property set. */ \
159     currChild->clear##Prop(); \
160     currChild = currChild->next(); \
161 } }
162
163 #define HANDLE_BACKGROUND_INHERIT_AND_INITIAL(prop, Prop) \
164 HANDLE_MULTILAYER_INHERIT_AND_INITIAL(backgroundLayer, BackgroundLayer, prop, Prop)
165
166 #define HANDLE_BACKGROUND_VALUE(prop, Prop, value) \
167 HANDLE_MULTILAYER_VALUE(backgroundLayer, BackgroundLayer, prop, Prop, value)
168
169 #define HANDLE_TRANSITION_VALUE(prop, Prop, value) \
170 HANDLE_MULTILAYER_VALUE(transition, Transition, prop, Prop, value)
171
172 #define HANDLE_INHERIT_COND(propID, prop, Prop) \
173 if (id == propID) { \
174     m_style->set##Prop(m_parentStyle->prop()); \
175     return; \
176 }
177
178 #define HANDLE_INITIAL_COND(propID, Prop) \
179 if (id == propID) { \
180     m_style->set##Prop(RenderStyle::initial##Prop()); \
181     return; \
182 }
183
184 #define HANDLE_INITIAL_COND_WITH_VALUE(propID, Prop, Value) \
185 if (id == propID) { \
186     m_style->set##Prop(RenderStyle::initial##Value()); \
187     return; \
188 }
189
190 class CSSRuleSet
191 {
192 public:
193     CSSRuleSet();
194     ~CSSRuleSet();
195     
196     typedef HashMap<AtomicStringImpl*, CSSRuleDataList*> AtomRuleMap;
197     
198     void addRulesFromSheet(CSSStyleSheet*, const MediaQueryEvaluator&, CSSStyleSelector* = 0);
199     
200     void addRule(CSSStyleRule* rule, CSSSelector* sel);
201     void addToRuleSet(AtomicStringImpl* key, AtomRuleMap& map,
202                       CSSStyleRule* rule, CSSSelector* sel);
203     
204     CSSRuleDataList* getIDRules(AtomicStringImpl* key) { return m_idRules.get(key); }
205     CSSRuleDataList* getClassRules(AtomicStringImpl* key) { return m_classRules.get(key); }
206     CSSRuleDataList* getTagRules(AtomicStringImpl* key) { return m_tagRules.get(key); }
207     CSSRuleDataList* getUniversalRules() { return m_universalRules; }
208     
209 public:
210     AtomRuleMap m_idRules;
211     AtomRuleMap m_classRules;
212     AtomRuleMap m_tagRules;
213     CSSRuleDataList* m_universalRules;
214     unsigned m_ruleCount;
215 };
216
217 CSSRuleSet* CSSStyleSelector::m_defaultStyle = 0;
218 CSSRuleSet* CSSStyleSelector::m_defaultQuirksStyle = 0;
219 CSSRuleSet* CSSStyleSelector::m_defaultPrintStyle = 0;
220 CSSRuleSet* CSSStyleSelector::m_defaultViewSourceStyle = 0;
221
222 CSSStyleSheet* CSSStyleSelector::m_defaultSheet = 0;
223 RenderStyle* CSSStyleSelector::m_styleNotYetAvailable = 0;
224 CSSStyleSheet* CSSStyleSelector::m_quirksSheet = 0;
225 CSSStyleSheet* CSSStyleSelector::m_viewSourceSheet = 0;
226
227 #if ENABLE(SVG)
228 CSSStyleSheet *CSSStyleSelector::m_svgSheet = 0;
229 #endif
230
231 static CSSStyleSelector::EncodedURL* currentEncodedURL = 0;
232 static PseudoState pseudoState;
233
234 static const MediaQueryEvaluator& screenEval()
235 {
236     static const MediaQueryEvaluator staticScreenEval("screen");
237     return staticScreenEval;
238 }
239
240 static const MediaQueryEvaluator& printEval()
241 {
242     static const MediaQueryEvaluator staticPrintEval("print");
243     return staticPrintEval;
244 }
245
246 CSSStyleSelector::CSSStyleSelector(Document* doc, const String& userStyleSheet, StyleSheetList *styleSheets, CSSStyleSheet* mappedElementSheet, bool _strictParsing, bool matchAuthorAndUserStyles)
247 {
248     init();
249     
250     m_document = doc;
251     m_fontSelector = new CSSFontSelector(doc);
252
253     m_matchAuthorAndUserStyles = matchAuthorAndUserStyles;
254
255     strictParsing = _strictParsing;
256     if (!m_defaultStyle)
257         loadDefaultStyle();
258
259     m_userStyle = 0;
260
261     // construct document root element default style. this is needed
262     // to evaluate media queries that contain relative constraints, like "screen and (max-width: 10em)"
263     // This is here instead of constructor, because when constructor is run,
264     // document doesn't have documentElement
265     // NOTE: this assumes that element that gets passed to styleForElement -call
266     // is always from the document that owns the style selector
267     FrameView* view = m_document->view();
268     if (view)
269         m_medium = new MediaQueryEvaluator(view->mediaType());
270     else
271         m_medium = new MediaQueryEvaluator("all");
272
273     Element* root = doc->documentElement();
274
275     if (root)
276         m_rootDefaultStyle = styleForElement(root, 0, false, true); // dont ref, because the RenderStyle is allocated from global heap
277
278     if (m_rootDefaultStyle && view) {
279         delete m_medium;
280         m_medium = new MediaQueryEvaluator(view->mediaType(), view->frame(), m_rootDefaultStyle);
281     }
282
283     // FIXME: This sucks! The user sheet is reparsed every time!
284     if (!userStyleSheet.isEmpty()) {
285         m_userSheet = new CSSStyleSheet(doc);
286         m_userSheet->parseString(userStyleSheet, strictParsing);
287
288         m_userStyle = new CSSRuleSet();
289         m_userStyle->addRulesFromSheet(m_userSheet.get(), *m_medium, this);
290     }
291
292     // add stylesheets from document
293     m_authorStyle = new CSSRuleSet();
294     
295     // Add rules from elments like SVG's <font-face>
296     if (mappedElementSheet)
297         m_authorStyle->addRulesFromSheet(mappedElementSheet, *m_medium, this);
298
299     DeprecatedPtrListIterator<StyleSheet> it(styleSheets->styleSheets);
300     for (; it.current(); ++it)
301         if (it.current()->isCSSStyleSheet() && !it.current()->disabled())
302             m_authorStyle->addRulesFromSheet(static_cast<CSSStyleSheet*>(it.current()), *m_medium, this);
303 }
304
305 void CSSStyleSelector::init()
306 {
307     m_element = 0;
308     m_matchedDecls.clear();
309     m_ruleList = 0;
310     m_collectRulesOnly = false;
311     m_rootDefaultStyle = 0;
312     m_medium = 0;
313 }
314
315 void CSSStyleSelector::setEncodedURL(const KURL& url)
316 {
317     KURL u = url;
318
319     u.setQuery(String());
320     u.setRef(String());
321     m_encodedURL.file = u.string();
322     int pos = m_encodedURL.file.reverseFind('/');
323     m_encodedURL.path = m_encodedURL.file;
324     if (pos > 0) {
325         m_encodedURL.path.truncate(pos);
326         m_encodedURL.path.append('/');
327     }
328     u.setPath(String());
329     m_encodedURL.prefix = u.string();
330 }
331
332 CSSStyleSelector::~CSSStyleSelector()
333 {
334     delete m_medium;
335     ::delete m_rootDefaultStyle;
336
337     delete m_authorStyle;
338     delete m_userStyle;
339 }
340
341 static CSSStyleSheet* parseUASheet(const char* characters, unsigned size)
342 {
343     CSSStyleSheet* const parent = 0;
344     CSSStyleSheet* sheet = new CSSStyleSheet(parent);
345     sheet->ref(); // leak the sheet on purpose since it will be stored in a global variable
346     sheet->parseString(String(characters, size));
347     return sheet;
348 }
349
350 template<typename T> CSSStyleSheet* parseUASheet(const T& array)
351 {
352     return parseUASheet(array, sizeof(array));
353 }
354
355 void CSSStyleSelector::loadDefaultStyle()
356 {
357     if (m_defaultStyle)
358         return;
359
360     m_defaultStyle = new CSSRuleSet;
361     m_defaultPrintStyle = new CSSRuleSet;
362     m_defaultQuirksStyle = new CSSRuleSet;
363     m_defaultViewSourceStyle = new CSSRuleSet;
364
365     // Strict-mode rules.
366     m_defaultSheet = parseUASheet(html4UserAgentStyleSheet);
367     m_defaultStyle->addRulesFromSheet(m_defaultSheet, screenEval());
368     m_defaultPrintStyle->addRulesFromSheet(m_defaultSheet, printEval());
369
370     // Quirks-mode rules.
371     m_quirksSheet = parseUASheet(quirksUserAgentStyleSheet);
372     m_defaultQuirksStyle->addRulesFromSheet(m_quirksSheet, screenEval());
373     
374     // View source rules.
375     m_viewSourceSheet = parseUASheet(sourceUserAgentStyleSheet);
376     m_defaultViewSourceStyle->addRulesFromSheet(m_viewSourceSheet, screenEval());
377 }
378
379 void CSSStyleSelector::matchRules(CSSRuleSet* rules, int& firstRuleIndex, int& lastRuleIndex)
380 {
381     m_matchedRules.clear();
382
383     if (!rules || !m_element)
384         return;
385     
386     // We need to collect the rules for id, class, tag, and everything else into a buffer and
387     // then sort the buffer.
388     if (m_element->hasID())
389         matchRulesForList(rules->getIDRules(m_element->getIDAttribute().impl()), firstRuleIndex, lastRuleIndex);
390     if (m_element->hasClass()) {
391         const ClassNames& classNames = *m_element->getClassNames();
392         size_t classNamesSize = classNames.size();
393         for (size_t i = 0; i < classNamesSize; ++i)
394             matchRulesForList(rules->getClassRules(classNames[i].impl()), firstRuleIndex, lastRuleIndex);
395     }
396     matchRulesForList(rules->getTagRules(m_element->localName().impl()), firstRuleIndex, lastRuleIndex);
397     matchRulesForList(rules->getUniversalRules(), firstRuleIndex, lastRuleIndex);
398     
399     // If we didn't match any rules, we're done.
400     if (m_matchedRules.isEmpty())
401         return;
402     
403     // Sort the set of matched rules.
404     sortMatchedRules(0, m_matchedRules.size());
405     
406     // Now transfer the set of matched rules over to our list of decls.
407     if (!m_collectRulesOnly) {
408         for (unsigned i = 0; i < m_matchedRules.size(); i++)
409             addMatchedDeclaration(m_matchedRules[i]->rule()->declaration());
410     } else {
411         for (unsigned i = 0; i < m_matchedRules.size(); i++) {
412             if (!m_ruleList)
413                 m_ruleList = new CSSRuleList();
414             m_ruleList->append(m_matchedRules[i]->rule());
415         }
416     }
417 }
418
419 void CSSStyleSelector::matchRulesForList(CSSRuleDataList* rules, int& firstRuleIndex, int& lastRuleIndex)
420 {
421     if (!rules)
422         return;
423
424     for (CSSRuleData* d = rules->first(); d; d = d->next()) {
425         CSSStyleRule* rule = d->rule();
426         const AtomicString& localName = m_element->localName();
427         const AtomicString& selectorLocalName = d->selector()->m_tag.localName();
428         if ((localName == selectorLocalName || selectorLocalName == starAtom) && checkSelector(d->selector())) {
429             // If the rule has no properties to apply, then ignore it.
430             CSSMutableStyleDeclaration* decl = rule->declaration();
431             if (!decl || !decl->length())
432                 continue;
433             
434             // If we're matching normal rules, set a pseudo bit if 
435             // we really just matched a pseudo-element.
436             if (dynamicPseudo != RenderStyle::NOPSEUDO && m_pseudoStyle == RenderStyle::NOPSEUDO) {
437                 if (m_collectRulesOnly)
438                     return;
439                 if (dynamicPseudo < RenderStyle::FIRST_INTERNAL_PSEUDOID)
440                     m_style->setHasPseudoStyle(dynamicPseudo);
441             } else {
442                 // Update our first/last rule indices in the matched rules array.
443                 lastRuleIndex = m_matchedDecls.size() + m_matchedRules.size();
444                 if (firstRuleIndex == -1)
445                     firstRuleIndex = lastRuleIndex;
446
447                 // Add this rule to our list of matched rules.
448                 addMatchedRule(d);
449             }
450         }
451     }
452 }
453
454 bool operator >(CSSRuleData& r1, CSSRuleData& r2)
455 {
456     int spec1 = r1.selector()->specificity();
457     int spec2 = r2.selector()->specificity();
458     return (spec1 == spec2) ? r1.position() > r2.position() : spec1 > spec2; 
459 }
460 bool operator <=(CSSRuleData& r1, CSSRuleData& r2)
461 {
462     return !(r1 > r2);
463 }
464
465 void CSSStyleSelector::sortMatchedRules(unsigned start, unsigned end)
466 {
467     if (start >= end || (end - start == 1))
468         return; // Sanity check.
469
470     if (end - start <= 6) {
471         // Apply a bubble sort for smaller lists.
472         for (unsigned i = end - 1; i > start; i--) {
473             bool sorted = true;
474             for (unsigned j = start; j < i; j++) {
475                 CSSRuleData* elt = m_matchedRules[j];
476                 CSSRuleData* elt2 = m_matchedRules[j + 1];
477                 if (*elt > *elt2) {
478                     sorted = false;
479                     m_matchedRules[j] = elt2;
480                     m_matchedRules[j + 1] = elt;
481                 }
482             }
483             if (sorted)
484                 return;
485         }
486         return;
487     }
488
489     // Peform a merge sort for larger lists.
490     unsigned mid = (start + end) / 2;
491     sortMatchedRules(start, mid);
492     sortMatchedRules(mid, end);
493     
494     CSSRuleData* elt = m_matchedRules[mid - 1];
495     CSSRuleData* elt2 = m_matchedRules[mid];
496     
497     // Handle the fast common case (of equal specificity).  The list may already
498     // be completely sorted.
499     if (*elt <= *elt2)
500         return;
501     
502     // We have to merge sort.  Ensure our merge buffer is big enough to hold
503     // all the items.
504     Vector<CSSRuleData*> rulesMergeBuffer;
505     rulesMergeBuffer.reserveCapacity(end - start); 
506
507     unsigned i1 = start;
508     unsigned i2 = mid;
509     
510     elt = m_matchedRules[i1];
511     elt2 = m_matchedRules[i2];
512     
513     while (i1 < mid || i2 < end) {
514         if (i1 < mid && (i2 == end || *elt <= *elt2)) {
515             rulesMergeBuffer.append(elt);
516             if (++i1 < mid)
517                 elt = m_matchedRules[i1];
518         } else {
519             rulesMergeBuffer.append(elt2);
520             if (++i2 < end)
521                 elt2 = m_matchedRules[i2];
522         }
523     }
524     
525     for (unsigned i = start; i < end; i++)
526         m_matchedRules[i] = rulesMergeBuffer[i - start];
527 }
528
529 void CSSStyleSelector::initElementAndPseudoState(Element* e)
530 {
531     m_element = e;
532     if (m_element && m_element->isStyledElement())
533         m_styledElement = static_cast<StyledElement*>(m_element);
534     else
535         m_styledElement = 0;
536     currentEncodedURL = &m_encodedURL;
537     pseudoState = PseudoUnknown;
538 }
539
540 void CSSStyleSelector::initForStyleResolve(Element* e, RenderStyle* defaultParent)
541 {
542     // set some variables we will need
543     m_pseudoStyle = RenderStyle::NOPSEUDO;
544
545     m_parentNode = e->parentNode();
546
547 #if ENABLE(SVG)
548     if (!m_parentNode && e->isSVGElement() && e->isShadowNode())
549         m_parentNode = e->shadowParentNode();
550 #endif
551
552     if (defaultParent)
553         m_parentStyle = defaultParent;
554     else
555         m_parentStyle = m_parentNode ? m_parentNode->renderStyle() : 0;
556     m_isXMLDoc = !m_element->document()->isHTMLDocument();
557
558     m_style = 0;
559     
560     m_matchedDecls.clear();
561
562     m_ruleList = 0;
563
564     m_fontDirty = false;
565 }
566
567 static inline int findSlashDotDotSlash(const UChar* characters, size_t length)
568 {
569     unsigned loopLimit = length < 4 ? 0 : length - 3;
570     for (unsigned i = 0; i < loopLimit; ++i) {
571         if (characters[i] == '/' && characters[i + 1] == '.' && characters[i + 2] == '.' && characters[i + 3] == '/')
572             return i;
573     }
574     return -1;
575 }
576
577 static inline int findSlashSlash(const UChar* characters, size_t length, int position)
578 {
579     unsigned loopLimit = length < 2 ? 0 : length - 1;
580     for (unsigned i = position; i < loopLimit; ++i) {
581         if (characters[i] == '/' && characters[i + 1] == '/')
582             return i;
583     }
584     return -1;
585 }
586
587 static inline int findSlashDotSlash(const UChar* characters, size_t length)
588 {
589     unsigned loopLimit = length < 3 ? 0 : length - 2;
590     for (unsigned i = 0; i < loopLimit; ++i) {
591         if (characters[i] == '/' && characters[i + 1] == '.' && characters[i + 2] == '/')
592             return i;
593     }
594     return -1;
595 }
596
597 static inline bool containsColonSlashSlash(const UChar* characters, unsigned length)
598 {
599     unsigned loopLimit = length < 3 ? 0 : length - 2;
600     for (unsigned i = 0; i < loopLimit; ++i)
601         if (characters[i] == ':' && characters[i + 1] == '/' && characters[i + 2] == '/')
602             return true;
603     return false;
604 }
605
606 static void cleanPath(Vector<UChar, 512>& path)
607 {
608     int pos;
609     while ((pos = findSlashDotDotSlash(path.data(), path.size())) != -1) {
610         int prev = reverseFind(path.data(), path.size(), '/', pos - 1);
611         // don't remove the host, i.e. http://foo.org/../foo.html
612         if (prev < 0 || (prev > 3 && path[prev - 2] == ':' && path[prev - 1] == '/'))
613             path.remove(pos, 3);
614         else
615             path.remove(prev, pos - prev + 3);
616     }
617
618     // Don't remove "//" from an anchor identifier. -rjw
619     // Set refPos to -2 to mean "I haven't looked for the anchor yet".
620     // We don't want to waste a function call on the search for the the anchor
621     // in the vast majority of cases where there is no "//" in the path.
622     pos = 0;
623     int refPos = -2;
624     while ((pos = findSlashSlash(path.data(), path.size(), pos)) != -1) {
625         if (refPos == -2)
626             refPos = find(path.data(), path.size(), '#');
627         if (refPos > 0 && pos >= refPos)
628             break;
629
630         if (pos == 0 || path[pos - 1] != ':')
631             path.remove(pos);
632         else
633             pos += 2;
634     }
635
636     // FIXME: We don't want to remove "/./" from an anchor identifier either.
637     while ((pos = findSlashDotSlash(path.data(), path.size())) != -1)
638         path.remove(pos, 2);
639 }
640
641 static void checkPseudoState(Element *e, bool checkVisited = true)
642 {
643     if (!e->isLink()) {
644         pseudoState = PseudoNone;
645         return;
646     }
647
648     const AtomicString* attr;
649     if (e->isHTMLElement())
650         attr = &e->getAttribute(hrefAttr);
651 #if ENABLE(SVG)
652     else if (e->isSVGElement())
653         attr = &e->getAttribute(XLinkNames::hrefAttr);
654 #endif
655     else {
656         pseudoState = PseudoNone;
657         return;
658     }
659
660     if (attr->isNull()) {
661         pseudoState = PseudoNone;
662         return;
663     }
664
665     if (!checkVisited) {
666         pseudoState = PseudoAnyLink;
667         return;
668     }
669
670     const UChar* characters = attr->characters();
671     unsigned length = attr->length();
672
673     if (containsColonSlashSlash(characters, length)) {
674         // FIXME: Strange to not clean the path just beacause it has "://" in it.
675         pseudoState = historyContains(characters, length) ? PseudoVisited : PseudoLink;
676         return;
677     }
678
679     Vector<UChar, 512> buffer;
680     if (length && characters[0] == '/') {
681         buffer.append(currentEncodedURL->prefix.characters(), currentEncodedURL->prefix.length());
682     } else if (length && characters[0] == '#') {
683         buffer.append(currentEncodedURL->file.characters(), currentEncodedURL->file.length());
684     } else {
685         buffer.append(currentEncodedURL->path.characters(), currentEncodedURL->path.length());
686     }
687     buffer.append(characters, length);
688     cleanPath(buffer);
689     pseudoState = historyContains(buffer.data(), buffer.size()) ? PseudoVisited : PseudoLink;
690 }
691
692 // a helper function for parsing nth-arguments
693 static bool parseNth(const String& nth, int &a, int &b)
694 {
695     if (nth.isEmpty())
696         return false;
697     a = 0;
698     b = 0;
699     if (nth == "odd") {
700         a = 2;
701         b = 1;
702     } else if (nth == "even") {
703         a = 2;
704         b = 0;
705     } else {
706         int n = nth.find('n');
707         if (n != -1) {
708             if (nth[0] == '-') {
709                 if (n == 1)
710                     a = -1; // -n == -1n
711                 else
712                     a = nth.substring(0, n).toInt();
713             } else if (!n)
714                 a = 1; // n == 1n
715             else
716                 a = nth.substring(0, n).toInt();
717
718             int p = nth.find('+', n);
719             if (p != -1)
720                 b = nth.substring(p + 1, nth.length() - p - 1).toInt();
721             else {
722                 p = nth.find('-', n);
723                 b = -nth.substring(p + 1, nth.length() - p - 1).toInt();
724             }
725         } else
726             b = nth.toInt();
727     }
728     return true;
729 }
730
731 // a helper function for checking nth-arguments
732 static bool matchNth(int count, int a, int b)
733 {
734     if (!a)
735         return count == b;
736     else if (a > 0) {
737         if (count < b)
738             return false;
739         return (count - b) % a == 0;
740     } else {
741         if (count > b)
742             return false;
743         return (b - count) % (-a) == 0;
744     }
745 }
746
747
748 #ifdef STYLE_SHARING_STATS
749 static int fraction = 0;
750 static int total = 0;
751 #endif
752
753 static const unsigned cStyleSearchThreshold = 10;
754
755 Node* CSSStyleSelector::locateCousinList(Element* parent, unsigned depth)
756 {
757     if (parent && parent->isStyledElement()) {
758         StyledElement* p = static_cast<StyledElement*>(parent);
759         if (!p->inlineStyleDecl() && !p->hasID()) {
760             Node* r = p->previousSibling();
761             unsigned subcount = 0;
762             RenderStyle* st = p->renderStyle();
763             while (r) {
764                 if (r->renderStyle() == st)
765                     return r->lastChild();
766                 if (subcount++ == cStyleSearchThreshold)
767                     return 0;
768                 r = r->previousSibling();
769             }
770             if (!r && depth < cStyleSearchThreshold)
771                 r = locateCousinList(static_cast<Element*>(parent->parentNode()), depth + 1);
772             while (r) {
773                 if (r->renderStyle() == st)
774                     return r->lastChild();
775                 if (subcount++ == cStyleSearchThreshold)
776                     return 0;
777                 r = r->previousSibling();
778             }
779         }
780     }
781     return 0;
782 }
783
784 bool CSSStyleSelector::canShareStyleWithElement(Node* n)
785 {
786     if (n->isStyledElement()) {
787         StyledElement* s = static_cast<StyledElement*>(n);
788         RenderStyle* style = s->renderStyle();
789         if (style && !style->unique() &&
790             (s->tagQName() == m_element->tagQName()) && !s->hasID() &&
791             (s->hasClass() == m_element->hasClass()) && !s->inlineStyleDecl() &&
792             (s->hasMappedAttributes() == m_styledElement->hasMappedAttributes()) &&
793             (s->isLink() == m_element->isLink()) && 
794             !style->affectedByAttributeSelectors() &&
795             (s->hovered() == m_element->hovered()) &&
796             (s->active() == m_element->active()) &&
797             (s->focused() == m_element->focused()) &&
798             (s != s->document()->getCSSTarget() && m_element != m_element->document()->getCSSTarget()) &&
799             (s->getAttribute(typeAttr) == m_element->getAttribute(typeAttr)) &&
800             (s->getAttribute(XMLNames::langAttr) == m_element->getAttribute(XMLNames::langAttr)) &&
801             (s->getAttribute(langAttr) == m_element->getAttribute(langAttr)) &&
802             (s->getAttribute(readonlyAttr) == m_element->getAttribute(readonlyAttr)) &&
803             (s->getAttribute(cellpaddingAttr) == m_element->getAttribute(cellpaddingAttr))) {
804             bool isControl = s->isControl();
805             if (isControl != m_element->isControl())
806                 return false;
807             if (isControl && (s->isEnabled() != m_element->isEnabled()) ||
808                              (s->isIndeterminate() != m_element->isIndeterminate()) ||
809                              (s->isChecked() != m_element->isChecked()))
810                 return false;
811             
812             if (style->transitions())
813                 return false;
814
815             bool classesMatch = true;
816             if (s->hasClass()) {
817                 const AtomicString& class1 = m_element->getAttribute(classAttr);
818                 const AtomicString& class2 = s->getAttribute(classAttr);
819                 classesMatch = (class1 == class2);
820             }
821             
822             if (classesMatch) {
823                 bool mappedAttrsMatch = true;
824                 if (s->hasMappedAttributes())
825                     mappedAttrsMatch = s->mappedAttributes()->mapsEquivalent(m_styledElement->mappedAttributes());
826                 if (mappedAttrsMatch) {
827                     bool linksMatch = true;
828                     if (s->isLink()) {
829                         // We need to check to see if the visited state matches.
830                         Color linkColor = m_element->document()->linkColor();
831                         Color visitedColor = m_element->document()->visitedLinkColor();
832                         if (pseudoState == PseudoUnknown)
833                             checkPseudoState(m_element, style->pseudoState() != PseudoAnyLink || linkColor != visitedColor);
834                         linksMatch = (pseudoState == style->pseudoState());
835                     }
836                     
837                     if (linksMatch)
838                         return true;
839                 }
840             }
841         }
842     }
843     return false;
844 }
845
846 RenderStyle* CSSStyleSelector::locateSharedStyle()
847 {
848     if (m_styledElement && !m_styledElement->inlineStyleDecl() && !m_styledElement->hasID() && !m_styledElement->document()->usesSiblingRules()) {
849         // Check previous siblings.
850         unsigned count = 0;
851         Node* n;
852         for (n = m_element->previousSibling(); n && !n->isElementNode(); n = n->previousSibling()) { }
853         while (n) {
854             if (canShareStyleWithElement(n))
855                 return n->renderStyle();
856             if (count++ == cStyleSearchThreshold)
857                 return 0;
858             for (n = n->previousSibling(); n && !n->isElementNode(); n = n->previousSibling()) { }
859         }
860         if (!n) 
861             n = locateCousinList(static_cast<Element*>(m_element->parentNode()));
862         while (n) {
863             if (canShareStyleWithElement(n))
864                 return n->renderStyle();
865             if (count++ == cStyleSearchThreshold)
866                 return 0;
867             for (n = n->previousSibling(); n && !n->isElementNode(); n = n->previousSibling()) { }
868         }        
869     }
870     return 0;
871 }
872
873 void CSSStyleSelector::matchUARules(int& firstUARule, int& lastUARule)
874 {
875     // First we match rules from the user agent sheet.
876     CSSRuleSet* userAgentStyleSheet = m_medium->mediaTypeMatchSpecific("print")
877         ? m_defaultPrintStyle : m_defaultStyle;
878     matchRules(userAgentStyleSheet, firstUARule, lastUARule);
879
880     // In quirks mode, we match rules from the quirks user agent sheet.
881     if (!strictParsing)
882         matchRules(m_defaultQuirksStyle, firstUARule, lastUARule);
883         
884     // If we're in view source mode, then we match rules from the view source style sheet.
885     if (m_document->frame() && m_document->frame()->inViewSourceMode())
886         matchRules(m_defaultViewSourceStyle, firstUARule, lastUARule);
887 }
888
889 // If resolveForRootDefault is true, style based on user agent style sheet only. This is used in media queries, where
890 // relative units are interpreted according to document root element style, styled only with UA stylesheet
891
892 RenderStyle* CSSStyleSelector::styleForElement(Element* e, RenderStyle* defaultParent, bool allowSharing, bool resolveForRootDefault)
893 {
894     // Once an element has a renderer, we don't try to destroy it, since otherwise the renderer
895     // will vanish if a style recalc happens during loading.
896     if (allowSharing && !e->document()->haveStylesheetsLoaded() && !e->renderer()) {
897         if (!m_styleNotYetAvailable) {
898             m_styleNotYetAvailable = ::new RenderStyle;
899             m_styleNotYetAvailable->ref();
900             m_styleNotYetAvailable->setDisplay(NONE);
901             m_styleNotYetAvailable->font().update(m_fontSelector);
902         }
903         m_styleNotYetAvailable->ref();
904         e->document()->setHasNodesWithPlaceholderStyle();
905         return m_styleNotYetAvailable;
906     }
907     
908     initElementAndPseudoState(e);
909     if (allowSharing) {
910         m_style = locateSharedStyle();
911 #ifdef STYLE_SHARING_STATS
912         fraction += m_style != 0;
913         total++;
914         printf("Sharing %d out of %d\n", fraction, total);
915 #endif
916         if (m_style) {
917             m_style->ref();
918             return m_style;
919         }
920     }
921     initForStyleResolve(e, defaultParent);
922
923     if (resolveForRootDefault) {
924         m_style = ::new RenderStyle();
925         // don't ref, because we want to delete this, but we cannot unref it
926     } else {
927         m_style = new (e->document()->renderArena()) RenderStyle();
928         m_style->ref();
929     }
930     if (m_parentStyle)
931         m_style->inheritFrom(m_parentStyle);
932     else
933         m_parentStyle = m_style;
934
935 #if ENABLE(SVG)
936     if (e->isSVGElement() && !m_svgSheet) {
937         // SVG rules.
938         m_svgSheet = parseUASheet(svgUserAgentStyleSheet);
939         m_defaultStyle->addRulesFromSheet(m_svgSheet, screenEval());
940         m_defaultPrintStyle->addRulesFromSheet(m_svgSheet, printEval());
941     }
942 #endif
943
944     int firstUARule = -1, lastUARule = -1;
945     int firstUserRule = -1, lastUserRule = -1;
946     int firstAuthorRule = -1, lastAuthorRule = -1;
947     matchUARules(firstUARule, lastUARule);
948
949     if (!resolveForRootDefault) {
950         // 4. Now we check user sheet rules.
951         if (m_matchAuthorAndUserStyles)
952             matchRules(m_userStyle, firstUserRule, lastUserRule);
953
954         // 5. Now check author rules, beginning first with presentational attributes
955         // mapped from HTML.
956         if (m_styledElement) {
957             // Ask if the HTML element has mapped attributes.
958             if (m_styledElement->hasMappedAttributes()) {
959                 // Walk our attribute list and add in each decl.
960                 const NamedMappedAttrMap* map = m_styledElement->mappedAttributes();
961                 for (unsigned i = 0; i < map->length(); i++) {
962                     MappedAttribute* attr = map->attributeItem(i);
963                     if (attr->decl()) {
964                         lastAuthorRule = m_matchedDecls.size();
965                         if (firstAuthorRule == -1)
966                             firstAuthorRule = lastAuthorRule;
967                         addMatchedDeclaration(attr->decl());
968                     }
969                 }
970             }
971
972             // Now we check additional mapped declarations.
973             // Tables and table cells share an additional mapped rule that must be applied
974             // after all attributes, since their mapped style depends on the values of multiple attributes.
975             if (m_styledElement->canHaveAdditionalAttributeStyleDecls()) {
976                 m_additionalAttributeStyleDecls.clear();
977                 m_styledElement->additionalAttributeStyleDecls(m_additionalAttributeStyleDecls);
978                 if (!m_additionalAttributeStyleDecls.isEmpty()) {
979                     unsigned additionalDeclsSize = m_additionalAttributeStyleDecls.size();
980                     if (firstAuthorRule == -1)
981                         firstAuthorRule = m_matchedDecls.size();
982                     lastAuthorRule = m_matchedDecls.size() + additionalDeclsSize - 1;
983                     for (unsigned i = 0; i < additionalDeclsSize; i++)
984                         addMatchedDeclaration(m_additionalAttributeStyleDecls[i]);
985                 }
986             }
987         }
988     
989         // 6. Check the rules in author sheets next.
990         if (m_matchAuthorAndUserStyles)
991             matchRules(m_authorStyle, firstAuthorRule, lastAuthorRule);
992
993         // 7. Now check our inline style attribute.
994         if (m_matchAuthorAndUserStyles && m_styledElement) {
995             CSSMutableStyleDeclaration* inlineDecl = m_styledElement->inlineStyleDecl();
996             if (inlineDecl) {
997                 lastAuthorRule = m_matchedDecls.size();
998                 if (firstAuthorRule == -1)
999                     firstAuthorRule = lastAuthorRule;
1000                 addMatchedDeclaration(inlineDecl);
1001             }
1002         }
1003     }
1004
1005     // Now we have all of the matched rules in the appropriate order.  Walk the rules and apply
1006     // high-priority properties first, i.e., those properties that other properties depend on.
1007     // The order is (1) high-priority not important, (2) high-priority important, (3) normal not important
1008     // and (4) normal important.
1009     m_lineHeightValue = 0;
1010     applyDeclarations(true, false, 0, m_matchedDecls.size() - 1);
1011     if (!resolveForRootDefault) {
1012         applyDeclarations(true, true, firstAuthorRule, lastAuthorRule);
1013         applyDeclarations(true, true, firstUserRule, lastUserRule);
1014     }
1015     applyDeclarations(true, true, firstUARule, lastUARule);
1016     
1017     // If our font got dirtied, go ahead and update it now.
1018     if (m_fontDirty)
1019         updateFont();
1020
1021     // Line-height is set when we are sure we decided on the font-size
1022     if (m_lineHeightValue)
1023         applyProperty(CSS_PROP_LINE_HEIGHT, m_lineHeightValue);
1024
1025     // Now do the normal priority UA properties.
1026     applyDeclarations(false, false, firstUARule, lastUARule);
1027     
1028     // Cache our border and background so that we can examine them later.
1029     cacheBorderAndBackground();
1030     
1031     // Now do the author and user normal priority properties and all the !important properties.
1032     if (!resolveForRootDefault) {
1033         applyDeclarations(false, false, lastUARule + 1, m_matchedDecls.size() - 1);
1034         applyDeclarations(false, true, firstAuthorRule, lastAuthorRule);
1035         applyDeclarations(false, true, firstUserRule, lastUserRule);
1036     }
1037     applyDeclarations(false, true, firstUARule, lastUARule);
1038     
1039     // If our font got dirtied by one of the non-essential font props, 
1040     // go ahead and update it a second time.
1041     if (m_fontDirty)
1042         updateFont();
1043     
1044     // Clean up our style object's display and text decorations (among other fixups).
1045     adjustRenderStyle(m_style, e);
1046
1047     // If we are a link, cache the determined pseudo-state.
1048     if (e->isLink())
1049         m_style->setPseudoState(pseudoState);
1050
1051     // If we have first-letter pseudo style, do not share this style
1052     if (m_style->hasPseudoStyle(RenderStyle::FIRST_LETTER))
1053         m_style->setUnique();
1054
1055     // Now return the style.
1056     return m_style;
1057 }
1058
1059 RenderStyle* CSSStyleSelector::pseudoStyleForElement(RenderStyle::PseudoId pseudo, Element* e, RenderStyle* parentStyle)
1060 {
1061     if (!e)
1062         return 0;
1063
1064     initElementAndPseudoState(e);
1065     initForStyleResolve(e, parentStyle);
1066     m_pseudoStyle = pseudo;
1067     
1068     // Since we don't use pseudo-elements in any of our quirk/print user agent rules, don't waste time walking
1069     // those rules.
1070     
1071     // Check UA, user and author rules.
1072     int firstUARule = -1, lastUARule = -1, firstUserRule = -1, lastUserRule = -1, firstAuthorRule = -1, lastAuthorRule = -1;
1073     matchUARules(firstUARule, lastUARule);
1074
1075     if (m_matchAuthorAndUserStyles) {
1076         matchRules(m_userStyle, firstUserRule, lastUserRule);
1077         matchRules(m_authorStyle, firstAuthorRule, lastAuthorRule);
1078     }
1079
1080     if (m_matchedDecls.isEmpty())
1081         return 0;
1082     
1083     m_style = new (e->document()->renderArena()) RenderStyle();
1084     m_style->ref();
1085     if (parentStyle)
1086         m_style->inheritFrom(parentStyle);
1087     else
1088         parentStyle = m_style;
1089     m_style->noninherited_flags._styleType = m_pseudoStyle;
1090     
1091     m_lineHeightValue = 0;
1092     // High-priority properties.
1093     applyDeclarations(true, false, 0, m_matchedDecls.size() - 1);
1094     applyDeclarations(true, true, firstAuthorRule, lastAuthorRule);
1095     applyDeclarations(true, true, firstUserRule, lastUserRule);
1096     applyDeclarations(true, true, firstUARule, lastUARule);
1097     
1098     // If our font got dirtied, go ahead and update it now.
1099     if (m_fontDirty)
1100         updateFont();
1101
1102     // Line-height is set when we are sure we decided on the font-size
1103     if (m_lineHeightValue)
1104         applyProperty(CSS_PROP_LINE_HEIGHT, m_lineHeightValue);
1105     
1106     // Now do the normal priority properties.
1107     applyDeclarations(false, false, firstUARule, lastUARule);
1108     
1109     // Cache our border and background so that we can examine them later.
1110     cacheBorderAndBackground();
1111     
1112     applyDeclarations(false, false, lastUARule + 1, m_matchedDecls.size() - 1);
1113     applyDeclarations(false, true, firstAuthorRule, lastAuthorRule);
1114     applyDeclarations(false, true, firstUserRule, lastUserRule);
1115     applyDeclarations(false, true, firstUARule, lastUARule);
1116     
1117     // If our font got dirtied by one of the non-essential font props, 
1118     // go ahead and update it a second time.
1119     if (m_fontDirty)
1120         updateFont();
1121     // Clean up our style object's display and text decorations (among other fixups).
1122     adjustRenderStyle(m_style, 0);
1123
1124     // Now return the style.
1125     return m_style;
1126 }
1127
1128 static void addIntrinsicMargins(RenderStyle* style)
1129 {
1130     // Intrinsic margin value.
1131     const int intrinsicMargin = 2;
1132     
1133     // FIXME: Using width/height alone and not also dealing with min-width/max-width is flawed.
1134     // FIXME: Using "quirk" to decide the margin wasn't set is kind of lame.
1135     if (style->width().isIntrinsicOrAuto()) {
1136         if (style->marginLeft().quirk())
1137             style->setMarginLeft(Length(intrinsicMargin, Fixed));
1138         if (style->marginRight().quirk())
1139             style->setMarginRight(Length(intrinsicMargin, Fixed));
1140     }
1141
1142     if (style->height().isAuto()) {
1143         if (style->marginTop().quirk())
1144             style->setMarginTop(Length(intrinsicMargin, Fixed));
1145         if (style->marginBottom().quirk())
1146             style->setMarginBottom(Length(intrinsicMargin, Fixed));
1147     }
1148 }
1149
1150 void CSSStyleSelector::adjustRenderStyle(RenderStyle* style, Element *e)
1151 {
1152     // Cache our original display.
1153     style->setOriginalDisplay(style->display());
1154
1155     if (style->display() != NONE) {
1156         // If we have a <td> that specifies a float property, in quirks mode we just drop the float
1157         // property.
1158         // Sites also commonly use display:inline/block on <td>s and <table>s.  In quirks mode we force
1159         // these tags to retain their display types.
1160         if (!strictParsing && e) {
1161             if (e->hasTagName(tdTag)) {
1162                 style->setDisplay(TABLE_CELL);
1163                 style->setFloating(FNONE);
1164             }
1165             else if (e->hasTagName(tableTag))
1166                 style->setDisplay(style->isDisplayInlineType() ? INLINE_TABLE : TABLE);
1167         }
1168
1169         // Tables never support the -webkit-* values for text-align and will reset back to the default.
1170         if (e && e->hasTagName(tableTag) && (style->textAlign() == WEBKIT_LEFT || style->textAlign() == WEBKIT_CENTER || style->textAlign() == WEBKIT_RIGHT))
1171             style->setTextAlign(TAAUTO);
1172
1173         // Frames and framesets never honor position:relative or position:absolute.  This is necessary to
1174         // fix a crash where a site tries to position these objects.  They also never honor display.
1175         if (e && (e->hasTagName(frameTag) || e->hasTagName(framesetTag))) {
1176             style->setPosition(StaticPosition);
1177             style->setDisplay(BLOCK);
1178         }
1179
1180         // Table headers with a text-align of auto will change the text-align to center.
1181         if (e && e->hasTagName(thTag) && style->textAlign() == TAAUTO)
1182             style->setTextAlign(CENTER);
1183         
1184         // Mutate the display to BLOCK or TABLE for certain cases, e.g., if someone attempts to
1185         // position or float an inline, compact, or run-in.  Cache the original display, since it
1186         // may be needed for positioned elements that have to compute their static normal flow
1187         // positions.  We also force inline-level roots to be block-level.
1188         if (style->display() != BLOCK && style->display() != TABLE && style->display() != BOX &&
1189             (style->position() == AbsolutePosition || style->position() == FixedPosition || style->floating() != FNONE ||
1190              (e && e->document()->documentElement() == e))) {
1191             if (style->display() == INLINE_TABLE)
1192                 style->setDisplay(TABLE);
1193             else if (style->display() == INLINE_BOX)
1194                 style->setDisplay(BOX);
1195             else if (style->display() == LIST_ITEM) {
1196                 // It is a WinIE bug that floated list items lose their bullets, so we'll emulate the quirk,
1197                 // but only in quirks mode.
1198                 if (!strictParsing && style->floating() != FNONE)
1199                     style->setDisplay(BLOCK);
1200             }
1201             else
1202                 style->setDisplay(BLOCK);
1203         }
1204         
1205         // After performing the display mutation, check table rows.  We do not honor position:relative on
1206         // table rows or cells.  This has been established in CSS2.1 (and caused a crash in containingBlock()
1207         // on some sites).
1208         if ((style->display() == TABLE_HEADER_GROUP || style->display() == TABLE_ROW_GROUP ||
1209              style->display() == TABLE_FOOTER_GROUP || style->display() == TABLE_ROW || style->display() == TABLE_CELL) &&
1210              style->position() == RelativePosition)
1211             style->setPosition(StaticPosition);
1212     }
1213
1214     // Make sure our z-index value is only applied if the object is positioned,
1215     // relatively positioned, transparent, or has a transform.
1216     if (style->position() == StaticPosition && style->opacity() == 1.0f && !style->hasTransform())
1217         style->setHasAutoZIndex();
1218
1219     // Auto z-index becomes 0 for the root element and transparent objects.  This prevents
1220     // cases where objects that should be blended as a single unit end up with a non-transparent
1221     // object wedged in between them.  Auto z-index also becomes 0 for objects that specify transforms.
1222     if (style->hasAutoZIndex() && ((e && e->document()->documentElement() == e) || style->opacity() < 1.0f || style->hasTransform()))
1223         style->setZIndex(0);
1224     
1225     // Button, legend, input, select and textarea all consider width values of 'auto' to be 'intrinsic'.
1226     // This will be important when we use block flows for all form controls.
1227     if (e && (e->hasTagName(legendTag) || e->hasTagName(buttonTag) || e->hasTagName(inputTag) ||
1228               e->hasTagName(selectTag) || e->hasTagName(textareaTag))) {
1229         if (style->width().isAuto())
1230             style->setWidth(Length(Intrinsic));
1231     }
1232
1233     // Finally update our text decorations in effect, but don't allow text-decoration to percolate through
1234     // tables, inline blocks, inline tables, or run-ins.
1235     if (style->display() == TABLE || style->display() == INLINE_TABLE || style->display() == RUN_IN
1236         || style->display() == INLINE_BLOCK || style->display() == INLINE_BOX)
1237         style->setTextDecorationsInEffect(style->textDecoration());
1238     else
1239         style->addToTextDecorationsInEffect(style->textDecoration());
1240     
1241     // If either overflow value is not visible, change to auto.
1242     if (style->overflowX() == OMARQUEE && style->overflowY() != OMARQUEE)
1243         style->setOverflowY(OMARQUEE);
1244     else if (style->overflowY() == OMARQUEE && style->overflowX() != OMARQUEE)
1245         style->setOverflowX(OMARQUEE);
1246     else if (style->overflowX() == OVISIBLE && style->overflowY() != OVISIBLE)
1247         style->setOverflowX(OAUTO);
1248     else if (style->overflowY() == OVISIBLE && style->overflowX() != OVISIBLE)
1249         style->setOverflowY(OAUTO);
1250
1251     // Table rows, sections and the table itself will support overflow:hidden and will ignore scroll/auto.
1252     // FIXME: Eventually table sections will support auto and scroll.
1253     if (style->display() == TABLE || style->display() == INLINE_TABLE ||
1254         style->display() == TABLE_ROW_GROUP || style->display() == TABLE_ROW) {
1255         if (style->overflowX() != OVISIBLE && style->overflowX() != OHIDDEN) 
1256             style->setOverflowX(OVISIBLE);
1257         if (style->overflowY() != OVISIBLE && style->overflowY() != OHIDDEN) 
1258             style->setOverflowY(OVISIBLE);
1259     }
1260
1261     // Cull out any useless layers and also repeat patterns into additional layers.
1262     style->adjustBackgroundLayers();
1263
1264     // Do the same for transitions.
1265     style->adjustTransitions();
1266
1267     // Important: Intrinsic margins get added to controls before the theme has adjusted the style, since the theme will
1268     // alter fonts and heights/widths.
1269     if (e && e->isControl() && style->fontSize() >= 11) {
1270         // Don't apply intrinsic margins to image buttons.  The designer knows how big the images are,
1271         // so we have to treat all image buttons as though they were explicitly sized.
1272         if (!e->hasTagName(inputTag) || static_cast<HTMLInputElement*>(e)->inputType() != HTMLInputElement::IMAGE)
1273             addIntrinsicMargins(style);
1274     }
1275
1276     // Let the theme also have a crack at adjusting the style.
1277     if (style->hasAppearance())
1278         theme()->adjustStyle(this, style, e, m_hasUAAppearance, m_borderData, m_backgroundData, m_backgroundColor);
1279
1280 #if ENABLE(SVG)
1281     if (e && e->isSVGElement()) {
1282         // Spec: http://www.w3.org/TR/SVG/masking.html#OverflowProperty
1283         if (style->overflowY() == OSCROLL)
1284             style->setOverflowY(OHIDDEN);
1285         else if (style->overflowY() == OAUTO)
1286             style->setOverflowY(OVISIBLE);
1287
1288         if (style->overflowX() == OSCROLL)
1289             style->setOverflowX(OHIDDEN);
1290         else if (style->overflowX() == OAUTO)
1291             style->setOverflowX(OVISIBLE);
1292
1293         // Only the root <svg> element in an SVG document fragment tree honors css position
1294         if (!(e->hasTagName(SVGNames::svgTag) && e->parentNode() && !e->parentNode()->isSVGElement()))
1295             style->setPosition(RenderStyle::initialPosition());
1296     }
1297 #endif
1298 }
1299
1300 void CSSStyleSelector::updateFont()
1301 {
1302     checkForTextSizeAdjust();
1303     checkForGenericFamilyChange(m_style, m_parentStyle);
1304     m_style->font().update(m_fontSelector);
1305     m_fontDirty = false;
1306 }
1307
1308 void CSSStyleSelector::cacheBorderAndBackground()
1309 {
1310     m_hasUAAppearance = m_style->hasAppearance();
1311     if (m_hasUAAppearance) {
1312         m_borderData = m_style->border();
1313         m_backgroundData = *m_style->backgroundLayers();
1314         m_backgroundColor = m_style->backgroundColor();
1315     }
1316 }
1317
1318 RefPtr<CSSRuleList> CSSStyleSelector::styleRulesForElement(Element* e, bool authorOnly)
1319 {
1320     if (!e || !e->document()->haveStylesheetsLoaded())
1321         return 0;
1322
1323     m_collectRulesOnly = true;
1324     
1325     initElementAndPseudoState(e);
1326     initForStyleResolve(e, 0);
1327     
1328     if (!authorOnly) {
1329         int firstUARule = -1, lastUARule = -1;
1330         // First we match rules from the user agent sheet.
1331         matchUARules(firstUARule, lastUARule);
1332
1333         // Now we check user sheet rules.
1334         if (m_matchAuthorAndUserStyles) {
1335             int firstUserRule = -1, lastUserRule = -1;
1336             matchRules(m_userStyle, firstUserRule, lastUserRule);
1337         }
1338     }
1339
1340     if (m_matchAuthorAndUserStyles) {
1341         // Check the rules in author sheets.
1342         int firstAuthorRule = -1, lastAuthorRule = -1;
1343         matchRules(m_authorStyle, firstAuthorRule, lastAuthorRule);
1344     }
1345
1346     m_collectRulesOnly = false;
1347     
1348     return m_ruleList;
1349 }
1350
1351 RefPtr<CSSRuleList> CSSStyleSelector::pseudoStyleRulesForElement(Element* e, StringImpl* pseudoStyle, bool authorOnly)
1352 {
1353     // FIXME: Implement this.
1354     return 0;
1355 }
1356
1357 bool CSSStyleSelector::checkSelector(CSSSelector* sel)
1358 {
1359     dynamicPseudo = RenderStyle::NOPSEUDO;
1360
1361     // Check the selector
1362     SelectorMatch match = checkSelector(sel, m_element, true, false);
1363     if (match != SelectorMatches)
1364         return false;
1365
1366     if (m_pseudoStyle != RenderStyle::NOPSEUDO && m_pseudoStyle != dynamicPseudo)
1367         return false;
1368
1369     return true;
1370 }
1371
1372 // Recursive check of selectors and combinators
1373 // It can return 3 different values:
1374 // * SelectorMatches         - the selector matches the element e
1375 // * SelectorFailsLocally    - the selector fails for the element e
1376 // * SelectorFailsCompletely - the selector fails for e and any sibling or ancestor of e
1377 CSSStyleSelector::SelectorMatch CSSStyleSelector::checkSelector(CSSSelector* sel, Element* e, bool isAncestor, bool isSubSelector)
1378 {
1379 #if ENABLE(SVG)
1380     // Spec: CSS2 selectors cannot be applied to the (conceptually) cloned DOM tree
1381     // because its contents are not part of the formal document structure.
1382     if (e->isSVGElement() && e->isShadowNode())
1383         return SelectorFailsCompletely;
1384 #endif
1385
1386     // first selector has to match
1387     if (!checkOneSelector(sel, e, isAncestor, isSubSelector))
1388         return SelectorFailsLocally;
1389
1390     // The rest of the selectors has to match
1391     CSSSelector::Relation relation = sel->relation();
1392
1393     // Prepare next sel
1394     sel = sel->m_tagHistory;
1395     if (!sel)
1396         return SelectorMatches;
1397
1398     if (relation != CSSSelector::SubSelector)
1399         // Bail-out if this selector is irrelevant for the pseudoStyle
1400         if (m_pseudoStyle != RenderStyle::NOPSEUDO && m_pseudoStyle != dynamicPseudo)
1401             return SelectorFailsCompletely;
1402
1403     switch (relation) {
1404         case CSSSelector::Descendant:
1405             while (true) {
1406                 Node* n = e->parentNode();
1407                 if (!n || !n->isElementNode())
1408                     return SelectorFailsCompletely;
1409                 e = static_cast<Element*>(n);
1410                 SelectorMatch match = checkSelector(sel, e, true, false);
1411                 if (match != SelectorFailsLocally)
1412                     return match;
1413             }
1414             break;
1415         case CSSSelector::Child:
1416         {
1417             Node* n = e->parentNode();
1418             if (!n || !n->isElementNode())
1419                 return SelectorFailsCompletely;
1420             e = static_cast<Element*>(n);
1421             return checkSelector(sel, e, true, false);
1422         }
1423         case CSSSelector::DirectAdjacent:
1424         {
1425             if (!m_collectRulesOnly && e->parentNode() && e->parentNode()->isElementNode()) {
1426                 RenderStyle* parentStyle = (m_element == e) ? m_parentStyle : e->parentNode()->renderStyle();
1427                 if (parentStyle)
1428                     parentStyle->setChildrenAffectedByDirectAdjacentRules();
1429             }
1430             Node* n = e->previousSibling();
1431             while (n && !n->isElementNode())
1432                 n = n->previousSibling();
1433             if (!n)
1434                 return SelectorFailsLocally;
1435             e = static_cast<Element*>(n);
1436             return checkSelector(sel, e, false, false); 
1437         }
1438         case CSSSelector::IndirectAdjacent:
1439             if (!m_collectRulesOnly && e->parentNode() && e->parentNode()->isElementNode()) {
1440                 RenderStyle* parentStyle = (m_element == e) ? m_parentStyle : e->parentNode()->renderStyle();
1441                 if (parentStyle)
1442                     parentStyle->setChildrenAffectedByForwardPositionalRules();
1443             }
1444             while (true) {
1445                 Node* n = e->previousSibling();
1446                 while (n && !n->isElementNode())
1447                     n = n->previousSibling();
1448                 if (!n)
1449                     return SelectorFailsLocally;
1450                 e = static_cast<Element*>(n);
1451                 SelectorMatch match = checkSelector(sel, e, false, false);
1452                 if (match != SelectorFailsLocally)
1453                     return match;
1454             };
1455             break;
1456         case CSSSelector::SubSelector:
1457             // a selector is invalid if something follows a pseudo-element
1458             if (e == m_element && dynamicPseudo != RenderStyle::NOPSEUDO)
1459                 return SelectorFailsCompletely;
1460             return checkSelector(sel, e, isAncestor, true);
1461     }
1462
1463     return SelectorFailsCompletely;
1464 }
1465
1466 static void addLocalNameToSet(HashSet<AtomicStringImpl*>* set, const QualifiedName& qName)
1467 {
1468     set->add(qName.localName().impl());
1469 }
1470
1471 static HashSet<AtomicStringImpl*>* createHtmlCaseInsensitiveAttributesSet()
1472 {
1473     // This is the list of attributes in HTML 4.01 with values marked as "[CI]" or case-insensitive
1474     // Mozilla treats all other values as case-sensitive, thus so do we.
1475     HashSet<AtomicStringImpl*>* attrSet = new HashSet<AtomicStringImpl*>;
1476
1477     addLocalNameToSet(attrSet, accept_charsetAttr);
1478     addLocalNameToSet(attrSet, acceptAttr);
1479     addLocalNameToSet(attrSet, alignAttr);
1480     addLocalNameToSet(attrSet, alinkAttr);
1481     addLocalNameToSet(attrSet, axisAttr);
1482     addLocalNameToSet(attrSet, bgcolorAttr);
1483     addLocalNameToSet(attrSet, charsetAttr);
1484     addLocalNameToSet(attrSet, checkedAttr);
1485     addLocalNameToSet(attrSet, clearAttr);
1486     addLocalNameToSet(attrSet, codetypeAttr);
1487     addLocalNameToSet(attrSet, colorAttr);
1488     addLocalNameToSet(attrSet, compactAttr);
1489     addLocalNameToSet(attrSet, declareAttr);
1490     addLocalNameToSet(attrSet, deferAttr);
1491     addLocalNameToSet(attrSet, dirAttr);
1492     addLocalNameToSet(attrSet, disabledAttr);
1493     addLocalNameToSet(attrSet, enctypeAttr);
1494     addLocalNameToSet(attrSet, faceAttr);
1495     addLocalNameToSet(attrSet, frameAttr);
1496     addLocalNameToSet(attrSet, hreflangAttr);
1497     addLocalNameToSet(attrSet, http_equivAttr);
1498     addLocalNameToSet(attrSet, langAttr);
1499     addLocalNameToSet(attrSet, languageAttr);
1500     addLocalNameToSet(attrSet, linkAttr);
1501     addLocalNameToSet(attrSet, mediaAttr);
1502     addLocalNameToSet(attrSet, methodAttr);
1503     addLocalNameToSet(attrSet, multipleAttr);
1504     addLocalNameToSet(attrSet, nohrefAttr);
1505     addLocalNameToSet(attrSet, noresizeAttr);
1506     addLocalNameToSet(attrSet, noshadeAttr);
1507     addLocalNameToSet(attrSet, nowrapAttr);
1508     addLocalNameToSet(attrSet, readonlyAttr);
1509     addLocalNameToSet(attrSet, relAttr);
1510     addLocalNameToSet(attrSet, revAttr);
1511     addLocalNameToSet(attrSet, rulesAttr);
1512     addLocalNameToSet(attrSet, scopeAttr);
1513     addLocalNameToSet(attrSet, scrollingAttr);
1514     addLocalNameToSet(attrSet, selectedAttr);
1515     addLocalNameToSet(attrSet, shapeAttr);
1516     addLocalNameToSet(attrSet, targetAttr);
1517     addLocalNameToSet(attrSet, textAttr);
1518     addLocalNameToSet(attrSet, typeAttr);
1519     addLocalNameToSet(attrSet, valignAttr);
1520     addLocalNameToSet(attrSet, valuetypeAttr);
1521     addLocalNameToSet(attrSet, vlinkAttr);
1522
1523     return attrSet;
1524 }
1525
1526 static bool htmlAttributeHasCaseInsensitiveValue(const QualifiedName& attr)
1527 {
1528     static HashSet<AtomicStringImpl*>* htmlCaseInsensitiveAttributesSet = createHtmlCaseInsensitiveAttributesSet();
1529     bool isPossibleHTMLAttr = !attr.hasPrefix() && (attr.namespaceURI() == nullAtom);
1530     return isPossibleHTMLAttr && htmlCaseInsensitiveAttributesSet->contains(attr.localName().impl());
1531 }
1532
1533 bool CSSStyleSelector::checkOneSelector(CSSSelector* sel, Element* e, bool isAncestor, bool isSubSelector)
1534 {
1535     if (!e)
1536         return false;
1537
1538     if (sel->hasTag()) {
1539         const AtomicString& localName = e->localName();
1540         const AtomicString& ns = e->namespaceURI();
1541         const AtomicString& selLocalName = sel->m_tag.localName();
1542         const AtomicString& selNS = sel->m_tag.namespaceURI();
1543     
1544         if ((selLocalName != starAtom && localName != selLocalName) ||
1545             (selNS != starAtom && ns != selNS))
1546             return false;
1547     }
1548
1549     if (sel->hasAttribute()) {
1550         if (sel->m_match == CSSSelector::Class) {
1551             if (!e->hasClass())
1552                 return false;
1553             return e->getClassNames()->contains(sel->m_value);
1554         } else if (sel->m_match == CSSSelector::Id)
1555             return e->hasID() && e->getIDAttribute() == sel->m_value;
1556         else if (m_style && (e != m_element || !m_styledElement || (!m_styledElement->isMappedAttribute(sel->m_attr) && sel->m_attr != typeAttr && sel->m_attr != readonlyAttr))) {
1557             m_style->setAffectedByAttributeSelectors(); // Special-case the "type" and "readonly" attributes so input form controls can share style.
1558             m_selectorAttrs.add(sel->m_attr.localName().impl());
1559         }
1560
1561         const AtomicString& value = e->getAttribute(sel->m_attr);
1562         if (value.isNull())
1563             return false; // attribute is not set
1564
1565         bool caseSensitive = m_isXMLDoc || !htmlAttributeHasCaseInsensitiveValue(sel->m_attr);
1566
1567         switch (sel->m_match) {
1568         case CSSSelector::Exact:
1569             if (caseSensitive ? sel->m_value != value : !equalIgnoringCase(sel->m_value, value))
1570                 return false;
1571             break;
1572         case CSSSelector::List:
1573         {
1574             // The selector's value can't contain a space, or it's totally bogus.
1575             if (sel->m_value.contains(' '))
1576                 return false;
1577
1578             int startSearchAt = 0;
1579             while (true) {
1580                 int foundPos = value.find(sel->m_value, startSearchAt, caseSensitive);
1581                 if (foundPos == -1)
1582                     return false;
1583                 if (foundPos == 0 || value[foundPos-1] == ' ') {
1584                     unsigned endStr = foundPos + sel->m_value.length();
1585                     if (endStr == value.length() || value[endStr] == ' ')
1586                         break; // We found a match.
1587                 }
1588                 
1589                 // No match.  Keep looking.
1590                 startSearchAt = foundPos + 1;
1591             }
1592             break;
1593         }
1594         case CSSSelector::Contain:
1595             if (!value.contains(sel->m_value, caseSensitive))
1596                 return false;
1597             break;
1598         case CSSSelector::Begin:
1599             if (!value.startsWith(sel->m_value, caseSensitive))
1600                 return false;
1601             break;
1602         case CSSSelector::End:
1603             if (!value.endsWith(sel->m_value, caseSensitive))
1604                 return false;
1605             break;
1606         case CSSSelector::Hyphen:
1607             if (value.length() < sel->m_value.length())
1608                 return false;
1609             if (!value.startsWith(sel->m_value, caseSensitive))
1610                 return false;
1611             // It they start the same, check for exact match or following '-':
1612             if (value.length() != sel->m_value.length() && value[sel->m_value.length()] != '-')
1613                 return false;
1614             break;
1615         case CSSSelector::PseudoClass:
1616         case CSSSelector::PseudoElement:
1617         default:
1618             break;
1619         }
1620     }
1621     if (sel->m_match == CSSSelector::PseudoClass) {
1622         switch (sel->pseudoType()) {
1623             // Pseudo classes:
1624             case CSSSelector::PseudoEmpty: {
1625                 bool result = true;
1626                 for (Node* n = e->firstChild(); n; n = n->nextSibling()) {
1627                     if (n->isElementNode()) {
1628                         result = false;
1629                         break;
1630                     } else if (n->isTextNode()) {
1631                         Text* textNode = static_cast<Text*>(n);
1632                         if (!textNode->data().isEmpty()) {
1633                             result = false;
1634                             break;
1635                         }
1636                     }
1637                 }
1638                 if (!m_collectRulesOnly) {
1639                     if (m_element == e && m_style)
1640                         m_style->setEmptyState(result);
1641                     else if (e->renderStyle() && (e->document()->usesSiblingRules() || e->renderStyle()->unique()))
1642                         e->renderStyle()->setEmptyState(result);
1643                 }
1644                 return result;
1645             }
1646             case CSSSelector::PseudoFirstChild: {
1647                 // first-child matches the first child that is an element
1648                 if (e->parentNode() && e->parentNode()->isElementNode()) {
1649                     bool result = false;
1650                     Node* n = e->previousSibling();
1651                     while (n && !n->isElementNode())
1652                         n = n->previousSibling();
1653                     if (!n)
1654                         result = true;
1655                     if (!m_collectRulesOnly) {
1656                         RenderStyle* childStyle = (m_element == e) ? m_style : e->renderStyle();
1657                         RenderStyle* parentStyle = (m_element == e) ? m_parentStyle : e->parentNode()->renderStyle();
1658                         if (parentStyle)
1659                             parentStyle->setChildrenAffectedByFirstChildRules();
1660                         if (result && childStyle)
1661                             childStyle->setFirstChildState();
1662                     }
1663                     return result;
1664                 }
1665                 break;
1666             }
1667             case CSSSelector::PseudoFirstOfType: {
1668                 // first-of-type matches the first element of its type
1669                 if (e->parentNode() && e->parentNode()->isElementNode()) {
1670                     bool result = false;
1671                     const QualifiedName& type = e->tagQName();
1672                     Node* n = e->previousSibling();
1673                     while (n) {
1674                         if (n->isElementNode() && static_cast<Element*>(n)->hasTagName(type))
1675                             break;
1676                         n = n->previousSibling();
1677                     }
1678                     if (!n)
1679                         result = true;
1680                     if (!m_collectRulesOnly) {
1681                         RenderStyle* parentStyle = (m_element == e) ? m_parentStyle : e->parentNode()->renderStyle();
1682                         if (parentStyle)
1683                             parentStyle->setChildrenAffectedByForwardPositionalRules();
1684                     }
1685                     return result;
1686                 }
1687                 break;
1688             }
1689             case CSSSelector::PseudoLastChild: {
1690                 // last-child matches the last child that is an element
1691                 if (e->parentNode() && e->parentNode()->isElementNode()) {
1692                     Element* parentNode = static_cast<Element*>(e->parentNode());
1693                     bool result = false;
1694                     if (parentNode->isFinishedParsingChildren()) {
1695                         Node* n = e->nextSibling();
1696                         while (n && !n->isElementNode())
1697                             n = n->nextSibling();
1698                         if (!n)
1699                             result = true;
1700                     }
1701                     if (!m_collectRulesOnly) {
1702                         RenderStyle* childStyle = (m_element == e) ? m_style : e->renderStyle();
1703                         RenderStyle* parentStyle = (m_element == e) ? m_parentStyle : parentNode->renderStyle();
1704                         if (parentStyle)
1705                             parentStyle->setChildrenAffectedByLastChildRules();
1706                         if (result && childStyle)
1707                             childStyle->setLastChildState();
1708                     }
1709                     return result;
1710                 }
1711                 break;
1712             }
1713             case CSSSelector::PseudoLastOfType: {
1714                 // last-of-type matches the last element of its type
1715                 if (e->parentNode() && e->parentNode()->isElementNode()) {
1716                     Element* parentNode = static_cast<Element*>(e->parentNode());
1717                     if (!m_collectRulesOnly) {
1718                         RenderStyle* parentStyle = (m_element == e) ? m_parentStyle : parentNode->renderStyle();
1719                         if (parentStyle)
1720                             parentStyle->setChildrenAffectedByBackwardPositionalRules();
1721                     }
1722                     if (!parentNode->isFinishedParsingChildren())
1723                         return false;
1724                     bool result = false;
1725                     const QualifiedName& type = e->tagQName();
1726                     Node* n = e->nextSibling();
1727                     while (n) {
1728                         if (n->isElementNode() && static_cast<Element*>(n)->hasTagName(type))
1729                             break;
1730                         n = n->nextSibling();
1731                     }
1732                     if (!n)
1733                         result = true;
1734                     return result;
1735                 }
1736                 break;
1737             }
1738             case CSSSelector::PseudoOnlyChild: {
1739                 if (e->parentNode() && e->parentNode()->isElementNode()) {
1740                     Element* parentNode = static_cast<Element*>(e->parentNode());
1741                     bool firstChild = false;
1742                     bool lastChild = false;
1743                     
1744                     Node* n = e->previousSibling();
1745                     while (n && !n->isElementNode())
1746                         n = n->previousSibling();
1747                     if (!n)
1748                         firstChild = true;
1749                     if (firstChild && parentNode->isFinishedParsingChildren()) {
1750                         n = e->nextSibling();
1751                         while (n && !n->isElementNode())
1752                             n = n->nextSibling();
1753                         if (!n)
1754                             lastChild = true;
1755                     }
1756                     if (!m_collectRulesOnly) {
1757                         RenderStyle* childStyle = (m_element == e) ? m_style : e->renderStyle();
1758                         RenderStyle* parentStyle = (m_element == e) ? m_parentStyle : parentNode->renderStyle();
1759                         if (parentStyle) {
1760                             parentStyle->setChildrenAffectedByFirstChildRules();
1761                             parentStyle->setChildrenAffectedByLastChildRules();
1762                         }
1763                         if (firstChild && childStyle)
1764                             childStyle->setFirstChildState();
1765                         if (lastChild && childStyle)
1766                             childStyle->setLastChildState();
1767                     }
1768                     return firstChild && lastChild;
1769                 }
1770                 break;
1771             }
1772             case CSSSelector::PseudoOnlyOfType: {
1773                 // FIXME: This selector is very slow.
1774                 if (e->parentNode() && e->parentNode()->isElementNode()) {
1775                     Element* parentNode = static_cast<Element*>(e->parentNode());
1776                     if (!m_collectRulesOnly) {
1777                         RenderStyle* parentStyle = (m_element == e) ? m_parentStyle : parentNode->renderStyle();
1778                         if (parentStyle) {
1779                             parentStyle->setChildrenAffectedByForwardPositionalRules();
1780                             parentStyle->setChildrenAffectedByBackwardPositionalRules();
1781                         }
1782                     }
1783                     if (!parentNode->isFinishedParsingChildren())
1784                         return false;
1785                     bool firstChild = false;
1786                     bool lastChild = false;
1787                     const QualifiedName& type = e->tagQName();
1788                     Node* n = e->previousSibling();
1789                     while (n) {
1790                         if (n->isElementNode() && static_cast<Element*>(n)->hasTagName(type))
1791                             break;
1792                         n = n->previousSibling();
1793                     }
1794                     if (!n)
1795                         firstChild = true;
1796                     if (firstChild) {
1797                         n = e->nextSibling();
1798                         while (n) {
1799                             if (n->isElementNode() && static_cast<Element*>(n)->hasTagName(type))
1800                                 break;
1801                             n = n->nextSibling();
1802                         }
1803                         if (!n)
1804                             lastChild = true;
1805                     }
1806                     return firstChild && lastChild;
1807                 }
1808                 break;
1809             }
1810             case CSSSelector::PseudoNthChild: {
1811                 int a, b;
1812                 // calculate a and b every time we run through checkOneSelector
1813                 // this should probably be saved after we calculate it once, but currently
1814                 // would require increasing the size of CSSSelector
1815                 if (!parseNth(sel->m_argument, a, b))
1816                     break;
1817                 if (e->parentNode() && e->parentNode()->isElementNode()) {
1818                     int count = 1;
1819                     Node* n = e->previousSibling();
1820                     while (n) {
1821                         if (n->isElementNode()) {
1822                             RenderStyle* s = n->renderStyle();
1823                             unsigned index = s ? s->childIndex() : 0;
1824                             if (index) {
1825                                 count += index;
1826                                 break;
1827                             }
1828                             count++;
1829                         }
1830                         n = n->previousSibling();
1831                     }
1832                     
1833                     if (!m_collectRulesOnly) {
1834                         RenderStyle* childStyle = (m_element == e) ? m_style : e->renderStyle();
1835                         RenderStyle* parentStyle = (m_element == e) ? m_parentStyle : e->parentNode()->renderStyle();
1836                         if (childStyle)
1837                             childStyle->setChildIndex(count);
1838                         if (parentStyle)
1839                             parentStyle->setChildrenAffectedByForwardPositionalRules();
1840                     }
1841                     
1842                     if (matchNth(count, a, b))
1843                         return true;
1844                 }
1845                 break;
1846             }
1847             case CSSSelector::PseudoNthOfType: {
1848                 // FIXME: This selector is very slow.
1849                 int a, b;
1850                 // calculate a and b every time we run through checkOneSelector (see above)
1851                 if (!parseNth(sel->m_argument, a, b))
1852                     break;
1853                 if (e->parentNode() && e->parentNode()->isElementNode()) {
1854                     int count = 1;
1855                     const QualifiedName& type = e->tagQName();
1856                     Node* n = e->previousSibling();
1857                     while (n) {
1858                         if (n->isElementNode() && static_cast<Element*>(n)->hasTagName(type))
1859                             count++;
1860                         n = n->previousSibling();
1861                     }
1862                     
1863                     if (!m_collectRulesOnly) {
1864                         RenderStyle* parentStyle = (m_element == e) ? m_parentStyle : e->parentNode()->renderStyle();
1865                         if (parentStyle)
1866                             parentStyle->setChildrenAffectedByForwardPositionalRules();
1867                     }
1868
1869                     if (matchNth(count, a, b))
1870                         return true;
1871                 }
1872                 break;
1873             }
1874             case CSSSelector::PseudoNthLastChild: {
1875                 int a, b;
1876                 // calculate a and b every time we run through checkOneSelector
1877                 // this should probably be saved after we calculate it once, but currently
1878                 // would require increasing the size of CSSSelector
1879                 if (!parseNth(sel->m_argument, a, b))
1880                     break;
1881                 if (e->parentNode() && e->parentNode()->isElementNode()) {
1882                     Element* parentNode = static_cast<Element*>(e->parentNode());
1883                     if (!m_collectRulesOnly) {
1884                         RenderStyle* parentStyle = (m_element == e) ? m_parentStyle : parentNode->renderStyle();
1885                         if (parentStyle)
1886                             parentStyle->setChildrenAffectedByBackwardPositionalRules();
1887                     }
1888                     if (!parentNode->isFinishedParsingChildren())
1889                         return false;
1890                     int count = 1;
1891                     Node* n = e->nextSibling();
1892                     while (n) {
1893                         if (n->isElementNode())
1894                             count++;
1895                         n = n->nextSibling();
1896                     }
1897                     if (matchNth(count, a, b))
1898                         return true;
1899                 }
1900                 break;
1901             }
1902             case CSSSelector::PseudoNthLastOfType: {
1903                 // FIXME: This selector is very slow.
1904                 int a, b;
1905                 // calculate a and b every time we run through checkOneSelector (see above)
1906                 if (!parseNth(sel->m_argument, a, b))
1907                     break;
1908                 if (e->parentNode() && e->parentNode()->isElementNode()) {
1909                     Element* parentNode = static_cast<Element*>(e->parentNode());
1910                     if (!m_collectRulesOnly) {
1911                         RenderStyle* parentStyle = (m_element == e) ? m_parentStyle : parentNode->renderStyle();
1912                         if (parentStyle)
1913                             parentStyle->setChildrenAffectedByBackwardPositionalRules();
1914                     }
1915                     if (!parentNode->isFinishedParsingChildren())
1916                         return false;
1917                     int count = 1;
1918                     const QualifiedName& type = e->tagQName();
1919                     Node* n = e->nextSibling();
1920                     while (n) {
1921                         if (n->isElementNode() && static_cast<Element*>(n)->hasTagName(type))
1922                             count++;
1923                         n = n->nextSibling();
1924                     }
1925                     if (matchNth(count, a, b))
1926                         return true;
1927                 }
1928                 break;
1929             }
1930             case CSSSelector::PseudoTarget:
1931                 if (e == e->document()->getCSSTarget())
1932                     return true;
1933                 break;
1934             case CSSSelector::PseudoAnyLink:
1935                 if (pseudoState == PseudoUnknown)
1936                     checkPseudoState(e, false);
1937                 if (pseudoState == PseudoAnyLink || pseudoState == PseudoLink || pseudoState == PseudoVisited)
1938                     return true;
1939                 break;
1940             case CSSSelector::PseudoAutofill:
1941                 if (e && e->hasTagName(inputTag))
1942                     return static_cast<HTMLInputElement*>(e)->autofilled();
1943                 break;
1944             case CSSSelector::PseudoLink:
1945                 if (pseudoState == PseudoUnknown || pseudoState == PseudoAnyLink)
1946                     checkPseudoState(e);
1947                 if (pseudoState == PseudoLink)
1948                     return true;
1949                 break;
1950             case CSSSelector::PseudoVisited:
1951                 if (pseudoState == PseudoUnknown || pseudoState == PseudoAnyLink)
1952                     checkPseudoState(e);
1953                 if (pseudoState == PseudoVisited)
1954                     return true;
1955                 break;
1956             case CSSSelector::PseudoDrag: {
1957                 if (m_element == e && m_style)
1958                     m_style->setAffectedByDragRules(true);
1959                     if (m_element != e && e->renderStyle())
1960                         e->renderStyle()->setAffectedByDragRules(true);
1961                     if (e->renderer() && e->renderer()->isDragging())
1962                         return true;
1963                 break;
1964             }
1965             case CSSSelector::PseudoFocus:
1966                 if (e && e->focused() && e->document()->frame()->selectionController()->isFocusedAndActive())
1967                     return true;
1968                 break;
1969             case CSSSelector::PseudoHover: {
1970                 // If we're in quirks mode, then hover should never match anchors with no
1971                 // href and *:hover should not match anything.  This is important for sites like wsj.com.
1972                 if (strictParsing || isSubSelector || (sel->hasTag() && !e->hasTagName(aTag)) || e->isLink()) {
1973                     if (m_element == e && m_style)
1974                         m_style->setAffectedByHoverRules(true);
1975                     if (m_element != e && e->renderStyle())
1976                         e->renderStyle()->setAffectedByHoverRules(true);
1977                     if (e->hovered())
1978                         return true;
1979                 }
1980                 break;
1981             }
1982             case CSSSelector::PseudoActive:
1983                 // If we're in quirks mode, then :active should never match anchors with no
1984                 // href and *:active should not match anything. 
1985                 if (strictParsing || isSubSelector || (sel->hasTag() && !e->hasTagName(aTag)) || e->isLink()) {
1986                     if (m_element == e && m_style)
1987                         m_style->setAffectedByActiveRules(true);
1988                     else if (e->renderStyle())
1989                         e->renderStyle()->setAffectedByActiveRules(true);
1990                     if (e->active())
1991                         return true;
1992                 }
1993                 break;
1994             case CSSSelector::PseudoEnabled:
1995                 if (e && e->isControl() && !e->isInputTypeHidden())
1996                     // The UI spec states that you can't match :enabled unless you are an object that can
1997                     // "receive focus and be activated."  We will limit matching of this pseudo-class to elements
1998                     // that are non-"hidden" controls.
1999                     return e->isEnabled();                    
2000                 break;
2001             case CSSSelector::PseudoDisabled:
2002                 if (e && e->isControl() && !e->isInputTypeHidden())
2003                     // The UI spec states that you can't match :enabled unless you are an object that can
2004                     // "receive focus and be activated."  We will limit matching of this pseudo-class to elements
2005                     // that are non-"hidden" controls.
2006                     return !e->isEnabled();                    
2007                 break;
2008             case CSSSelector::PseudoChecked:
2009                 // Even though WinIE allows checked and indeterminate to co-exist, the CSS selector spec says that
2010                 // you can't be both checked and indeterminate.  We will behave like WinIE behind the scenes and just
2011                 // obey the CSS spec here in the test for matching the pseudo.
2012                 if (e && e->isChecked() && !e->isIndeterminate())
2013                     return true;
2014                 break;
2015             case CSSSelector::PseudoIndeterminate:
2016                 if (e && e->isIndeterminate())
2017                     return true;
2018                 break;
2019             case CSSSelector::PseudoRoot:
2020                 if (e == e->document()->documentElement())
2021                     return true;
2022                 break;
2023             case CSSSelector::PseudoLang: {
2024                 Node* n = e;
2025                 AtomicString value;
2026                 // The language property is inherited, so we iterate over the parents
2027                 // to find the first language.
2028                 while (n && value.isEmpty()) {
2029                     if (n->isElementNode()) {
2030                         // Spec: xml:lang takes precedence -- http://www.w3.org/TR/xhtml1/#C_7
2031                         value = static_cast<Element*>(n)->getAttribute(XMLNames::langAttr);
2032                         if (value.isEmpty())
2033                             value = static_cast<Element*>(n)->getAttribute(langAttr);
2034                     } else if (n->isDocumentNode())
2035                         // checking the MIME content-language
2036                         value = static_cast<Document*>(n)->contentLanguage();
2037
2038                     n = n->parent();
2039                 }
2040                 if (value.isEmpty() || !value.startsWith(sel->m_argument, false))
2041                     break;
2042                 if (value.length() != sel->m_argument.length() && value[sel->m_argument.length()] != '-')
2043                     break;
2044                 return true;
2045             }
2046             case CSSSelector::PseudoNot: {
2047                 // check the simple selector
2048                 for (CSSSelector* subSel = sel->m_simpleSelector; subSel; subSel = subSel->m_tagHistory) {
2049                     // :not cannot nest. I don't really know why this is a
2050                     // restriction in CSS3, but it is, so let's honour it.
2051                     if (subSel->m_simpleSelector)
2052                         break;
2053                     if (!checkOneSelector(subSel, e, isAncestor, true))
2054                         return true;
2055                 }
2056                 break;
2057             }
2058             case CSSSelector::PseudoUnknown:
2059             case CSSSelector::PseudoNotParsed:
2060             default:
2061                 ASSERT_NOT_REACHED();
2062                 break;
2063         }
2064         return false;
2065     }
2066     if (sel->m_match == CSSSelector::PseudoElement) {
2067         if (e != m_element) return false;
2068
2069         switch (sel->pseudoType()) {
2070             // Pseudo-elements:
2071             case CSSSelector::PseudoFirstLine:
2072                 dynamicPseudo = RenderStyle::FIRST_LINE;
2073                 return true;
2074             case CSSSelector::PseudoFirstLetter:
2075                 dynamicPseudo = RenderStyle::FIRST_LETTER;
2076                 if (Document* doc = e->document())
2077                     doc->setUsesFirstLetterRules(true);
2078                 return true;
2079             case CSSSelector::PseudoSelection:
2080                 dynamicPseudo = RenderStyle::SELECTION;
2081                 return true;
2082             case CSSSelector::PseudoBefore:
2083                 dynamicPseudo = RenderStyle::BEFORE;
2084                 return true;
2085             case CSSSelector::PseudoAfter:
2086                 dynamicPseudo = RenderStyle::AFTER;
2087                 return true;
2088             case CSSSelector::PseudoFileUploadButton:
2089                 dynamicPseudo = RenderStyle::FILE_UPLOAD_BUTTON;
2090                 return true;
2091             case CSSSelector::PseudoSliderThumb:
2092                 dynamicPseudo = RenderStyle::SLIDER_THUMB;
2093                 return true; 
2094             case CSSSelector::PseudoSearchCancelButton:
2095                 dynamicPseudo = RenderStyle::SEARCH_CANCEL_BUTTON;
2096                 return true; 
2097             case CSSSelector::PseudoSearchDecoration:
2098                 dynamicPseudo = RenderStyle::SEARCH_DECORATION;
2099                 return true;
2100             case CSSSelector::PseudoSearchResultsDecoration:
2101                 dynamicPseudo = RenderStyle::SEARCH_RESULTS_DECORATION;
2102                 return true;
2103             case CSSSelector::PseudoSearchResultsButton:
2104                 dynamicPseudo = RenderStyle::SEARCH_RESULTS_BUTTON;
2105                 return true;
2106             case CSSSelector::PseudoMediaControlsPanel:
2107                 dynamicPseudo = RenderStyle::MEDIA_CONTROLS_PANEL;
2108                 return true;
2109             case CSSSelector::PseudoMediaControlsMuteButton:
2110                 dynamicPseudo = RenderStyle::MEDIA_CONTROLS_MUTE_BUTTON;
2111                 return true;
2112             case CSSSelector::PseudoMediaControlsPlayButton:
2113                 dynamicPseudo = RenderStyle::MEDIA_CONTROLS_PLAY_BUTTON;
2114                 return true;
2115             case CSSSelector::PseudoMediaControlsTimeDisplay:
2116                 dynamicPseudo = RenderStyle::MEDIA_CONTROLS_TIME_DISPLAY;
2117                 return true;
2118             case CSSSelector::PseudoMediaControlsTimeline:
2119                 dynamicPseudo = RenderStyle::MEDIA_CONTROLS_TIMELINE;
2120                 return true;
2121             case CSSSelector::PseudoMediaControlsSeekBackButton:
2122                 dynamicPseudo = RenderStyle::MEDIA_CONTROLS_SEEK_BACK_BUTTON;
2123                 return true;
2124             case CSSSelector::PseudoMediaControlsSeekForwardButton:
2125                 dynamicPseudo = RenderStyle::MEDIA_CONTROLS_SEEK_FORWARD_BUTTON;
2126                 return true;
2127             case CSSSelector::PseudoMediaControlsFullscreenButton:
2128                 dynamicPseudo = RenderStyle::MEDIA_CONTROLS_FULLSCREEN_BUTTON;
2129                 return true;
2130             case CSSSelector::PseudoUnknown:
2131             case CSSSelector::PseudoNotParsed:
2132             default:
2133                 ASSERT_NOT_REACHED();
2134                 break;
2135         }
2136         return false;
2137     }
2138     // ### add the rest of the checks...
2139     return true;
2140 }
2141
2142 // -----------------------------------------------------------------
2143
2144 CSSRuleSet::CSSRuleSet()
2145 {
2146     m_universalRules = 0;
2147     m_ruleCount = 0;
2148 }
2149
2150 CSSRuleSet::~CSSRuleSet()
2151
2152     deleteAllValues(m_idRules);
2153     deleteAllValues(m_classRules);
2154     deleteAllValues(m_tagRules);
2155
2156     delete m_universalRules; 
2157 }
2158
2159
2160 void CSSRuleSet::addToRuleSet(AtomicStringImpl* key, AtomRuleMap& map,
2161                               CSSStyleRule* rule, CSSSelector* sel)
2162 {
2163     if (!key) return;
2164     CSSRuleDataList* rules = map.get(key);
2165     if (!rules) {
2166         rules = new CSSRuleDataList(m_ruleCount++, rule, sel);
2167         map.set(key, rules);
2168     } else
2169         rules->append(m_ruleCount++, rule, sel);
2170 }
2171
2172 void CSSRuleSet::addRule(CSSStyleRule* rule, CSSSelector* sel)
2173 {
2174     if (sel->m_match == CSSSelector::Id) {
2175         addToRuleSet(sel->m_value.impl(), m_idRules, rule, sel);
2176         return;
2177     }
2178     if (sel->m_match == CSSSelector::Class) {
2179         addToRuleSet(sel->m_value.impl(), m_classRules, rule, sel);
2180         return;
2181     }
2182      
2183     const AtomicString& localName = sel->m_tag.localName();
2184     if (localName != starAtom) {
2185         addToRuleSet(localName.impl(), m_tagRules, rule, sel);
2186         return;
2187     }
2188     
2189     // Just put it in the universal rule set.
2190     if (!m_universalRules)
2191         m_universalRules = new CSSRuleDataList(m_ruleCount++, rule, sel);
2192     else
2193         m_universalRules->append(m_ruleCount++, rule, sel);
2194 }
2195
2196 void CSSRuleSet::addRulesFromSheet(CSSStyleSheet* sheet, const MediaQueryEvaluator& medium, CSSStyleSelector* styleSelector)
2197 {
2198     if (!sheet || !sheet->isCSSStyleSheet())
2199         return;
2200
2201     // No media implies "all", but if a media list exists it must
2202     // contain our current medium
2203     if (sheet->media() && !medium.eval(sheet->media(), styleSelector))
2204         return; // the style sheet doesn't apply
2205
2206     int len = sheet->length();
2207
2208     for (int i = 0; i < len; i++) {
2209         StyleBase* item = sheet->item(i);
2210         if (item->isStyleRule()) {
2211             CSSStyleRule* rule = static_cast<CSSStyleRule*>(item);
2212             for (CSSSelector* s = rule->selector(); s; s = s->next())
2213                 addRule(rule, s);
2214         }
2215         else if (item->isImportRule()) {
2216             CSSImportRule* import = static_cast<CSSImportRule*>(item);
2217             if (!import->media() || medium.eval(import->media(), styleSelector))
2218                 addRulesFromSheet(import->styleSheet(), medium, styleSelector);
2219         }
2220         else if (item->isMediaRule()) {
2221             CSSMediaRule* r = static_cast<CSSMediaRule*>(item);
2222             CSSRuleList* rules = r->cssRules();
2223
2224             if ((!r->media() || medium.eval(r->media(), styleSelector)) && rules) {
2225                 // Traverse child elements of the @media rule.
2226                 for (unsigned j = 0; j < rules->length(); j++) {
2227                     CSSRule *childItem = rules->item(j);
2228                     if (childItem->isStyleRule()) {
2229                         // It is a StyleRule, so append it to our list
2230                         CSSStyleRule* rule = static_cast<CSSStyleRule*>(childItem);
2231                         for (CSSSelector* s = rule->selector(); s; s = s->next())
2232                             addRule(rule, s);
2233                     } else if (item->isFontFaceRule() && styleSelector) {
2234                         // Add this font face to our set.
2235                         const CSSFontFaceRule* fontFaceRule = static_cast<CSSFontFaceRule*>(item);
2236                         styleSelector->fontSelector()->addFontFaceRule(fontFaceRule);
2237                     }
2238                 }   // for rules
2239             }   // if rules
2240         } else if (item->isFontFaceRule() && styleSelector) {
2241             // Add this font face to our set.
2242             const CSSFontFaceRule* fontFaceRule = static_cast<CSSFontFaceRule*>(item);
2243             styleSelector->fontSelector()->addFontFaceRule(fontFaceRule);
2244         }
2245     }
2246 }
2247
2248 // -------------------------------------------------------------------------------------
2249 // this is mostly boring stuff on how to apply a certain rule to the renderstyle...
2250
2251 static Length convertToLength(CSSPrimitiveValue *primitiveValue, RenderStyle *style, bool *ok = 0)
2252 {
2253     Length l;
2254     if (!primitiveValue) {
2255         if (ok)
2256             *ok = false;
2257     } else {
2258         int type = primitiveValue->primitiveType();
2259         if (type > CSSPrimitiveValue::CSS_PERCENTAGE && type < CSSPrimitiveValue::CSS_DEG)
2260             l = Length(primitiveValue->computeLengthIntForLength(style), Fixed);
2261         else if (type == CSSPrimitiveValue::CSS_PERCENTAGE)
2262             l = Length(primitiveValue->getDoubleValue(), Percent);
2263         else if (type == CSSPrimitiveValue::CSS_NUMBER)
2264             l = Length(primitiveValue->getDoubleValue() * 100.0, Percent);
2265         else if (ok)
2266             *ok = false;
2267     }
2268     return l;
2269 }
2270
2271 void CSSStyleSelector::applyDeclarations(bool applyFirst, bool isImportant,
2272                                          int startIndex, int endIndex)
2273 {
2274     if (startIndex == -1) return;
2275     for (int i = startIndex; i <= endIndex; i++) {
2276         CSSMutableStyleDeclaration* decl = m_matchedDecls[i];
2277         DeprecatedValueListConstIterator<CSSProperty> end;
2278         for (DeprecatedValueListConstIterator<CSSProperty> it = decl->valuesIterator(); it != end; ++it) {
2279             const CSSProperty& current = *it;
2280             // give special priority to font-xxx, color properties
2281             if (isImportant == current.isImportant()) {
2282                 bool first;
2283                 switch (current.id()) {
2284                     case CSS_PROP_LINE_HEIGHT:
2285                         m_lineHeightValue = current.value();
2286                         first = !applyFirst; // we apply line-height later
2287                         break;
2288                     case CSS_PROP_COLOR:
2289                     case CSS_PROP_DIRECTION:
2290                     case CSS_PROP_DISPLAY:
2291                     case CSS_PROP_FONT:
2292                     case CSS_PROP_FONT_SIZE:
2293                     case CSS_PROP_FONT_STYLE:
2294                     case CSS_PROP_FONT_FAMILY:
2295                     case CSS_PROP_FONT_WEIGHT:
2296                     case CSS_PROP__WEBKIT_TEXT_SIZE_ADJUST:
2297                     case CSS_PROP_FONT_VARIANT:
2298                         // these have to be applied first, because other properties use the computed
2299                         // values of these porperties.
2300                         first = true;
2301                         break;
2302                     default:
2303                         first = false;
2304                         break;
2305                 }
2306                 if (first == applyFirst)
2307                     applyProperty(current.id(), current.value());
2308             }
2309         }
2310     }
2311 }
2312
2313 static void applyCounterList(RenderStyle* style, CSSValueList* list, bool isReset)
2314 {
2315     CounterDirectiveMap& map = style->accessCounterDirectives();
2316     typedef CounterDirectiveMap::iterator Iterator;
2317
2318     Iterator end = map.end();
2319     for (Iterator it = map.begin(); it != end; ++it)
2320         if (isReset)
2321             it->second.m_reset = false;
2322         else
2323             it->second.m_increment = false;
2324
2325     int length = list ? list->length() : 0;
2326     for (int i = 0; i < length; ++i) {
2327         Pair* pair = static_cast<CSSPrimitiveValue*>(list->item(i))->getPairValue();
2328         AtomicString identifier = static_cast<CSSPrimitiveValue*>(pair->first())->getStringValue();
2329         // FIXME: What about overflow?
2330         int value = static_cast<CSSPrimitiveValue*>(pair->second())->getIntValue();
2331         CounterDirectives& directives = map.add(identifier.impl(), CounterDirectives()).first->second;
2332         if (isReset) {
2333             directives.m_reset = true;
2334             directives.m_resetValue = value;
2335         } else {
2336             if (directives.m_increment)
2337                 directives.m_incrementValue += value;
2338             else {
2339                 directives.m_increment = true;
2340                 directives.m_incrementValue = value;
2341             }
2342         }
2343     }
2344 }
2345
2346 void CSSStyleSelector::applyProperty(int id, CSSValue *value)
2347 {
2348     CSSPrimitiveValue* primitiveValue = 0;
2349     if (value->isPrimitiveValue())
2350         primitiveValue = static_cast<CSSPrimitiveValue*>(value);
2351
2352     Length l;
2353     bool apply = false;
2354
2355     unsigned short valueType = value->cssValueType();
2356
2357     bool isInherit = m_parentNode && valueType == CSSValue::CSS_INHERIT;
2358     bool isInitial = valueType == CSSValue::CSS_INITIAL || (!m_parentNode && valueType == CSSValue::CSS_INHERIT);
2359
2360     // These properties are used to set the correct margins/padding on RTL lists.
2361     if (id == CSS_PROP__WEBKIT_MARGIN_START)
2362         id = m_style->direction() == LTR ? CSS_PROP_MARGIN_LEFT : CSS_PROP_MARGIN_RIGHT;
2363     else if (id == CSS_PROP__WEBKIT_PADDING_START)
2364         id = m_style->direction() == LTR ? CSS_PROP_PADDING_LEFT : CSS_PROP_PADDING_RIGHT;
2365
2366     // What follows is a list that maps the CSS properties into their corresponding front-end
2367     // RenderStyle values.  Shorthands (e.g. border, background) occur in this list as well and
2368     // are only hit when mapping "inherit" or "initial" into front-end values.
2369     switch (static_cast<CSSPropertyID>(id)) {
2370 // ident only properties
2371     case CSS_PROP_BACKGROUND_ATTACHMENT:
2372         HANDLE_BACKGROUND_VALUE(backgroundAttachment, BackgroundAttachment, value)
2373         return;
2374     case CSS_PROP__WEBKIT_BACKGROUND_CLIP:
2375         HANDLE_BACKGROUND_VALUE(backgroundClip, BackgroundClip, value)
2376         return;
2377     case CSS_PROP__WEBKIT_BACKGROUND_COMPOSITE:
2378         HANDLE_BACKGROUND_VALUE(backgroundComposite, BackgroundComposite, value)
2379         return;
2380     case CSS_PROP__WEBKIT_BACKGROUND_ORIGIN:
2381         HANDLE_BACKGROUND_VALUE(backgroundOrigin, BackgroundOrigin, value)
2382         return;
2383     case CSS_PROP_BACKGROUND_REPEAT:
2384         HANDLE_BACKGROUND_VALUE(backgroundRepeat, BackgroundRepeat, value)
2385         return;
2386     case CSS_PROP__WEBKIT_BACKGROUND_SIZE:
2387         HANDLE_BACKGROUND_VALUE(backgroundSize, BackgroundSize, value)
2388         return;
2389     case CSS_PROP_BORDER_COLLAPSE:
2390         HANDLE_INHERIT_AND_INITIAL(borderCollapse, BorderCollapse)
2391         if (!primitiveValue)
2392             return;
2393         switch (primitiveValue->getIdent()) {
2394             case CSS_VAL_COLLAPSE:
2395                 m_style->setBorderCollapse(true);
2396                 break;
2397             case CSS_VAL_SEPARATE:
2398                 m_style->setBorderCollapse(false);
2399                 break;
2400             default:
2401                 return;
2402         }
2403         return;
2404         
2405     case CSS_PROP_BORDER_TOP_STYLE:
2406         HANDLE_INHERIT_AND_INITIAL_WITH_VALUE(borderTopStyle, BorderTopStyle, BorderStyle)
2407         if (primitiveValue)
2408             m_style->setBorderTopStyle(*primitiveValue);
2409         return;
2410     case CSS_PROP_BORDER_RIGHT_STYLE:
2411         HANDLE_INHERIT_AND_INITIAL_WITH_VALUE(borderRightStyle, BorderRightStyle, BorderStyle)
2412         if (primitiveValue)
2413             m_style->setBorderRightStyle(*primitiveValue);
2414         return;
2415     case CSS_PROP_BORDER_BOTTOM_STYLE:
2416         HANDLE_INHERIT_AND_INITIAL_WITH_VALUE(borderBottomStyle, BorderBottomStyle, BorderStyle)
2417         if (primitiveValue)
2418             m_style->setBorderBottomStyle(*primitiveValue);
2419         return;
2420     case CSS_PROP_BORDER_LEFT_STYLE:
2421         HANDLE_INHERIT_AND_INITIAL_WITH_VALUE(borderLeftStyle, BorderLeftStyle, BorderStyle)
2422         if (primitiveValue)
2423             m_style->setBorderLeftStyle(*primitiveValue);
2424         return;
2425     case CSS_PROP_OUTLINE_STYLE:
2426         HANDLE_INHERIT_AND_INITIAL_WITH_VALUE(outlineStyle, OutlineStyle, BorderStyle)
2427         if (primitiveValue) {
2428             if (primitiveValue->getIdent() == CSS_VAL_AUTO)
2429                 m_style->setOutlineStyle(DOTTED, true);
2430             else
2431                 m_style->setOutlineStyle(*primitiveValue);
2432         }
2433         return;
2434     case CSS_PROP_CAPTION_SIDE:
2435     {
2436         HANDLE_INHERIT_AND_INITIAL(captionSide, CaptionSide)
2437         if (primitiveValue)
2438             m_style->setCaptionSide(*primitiveValue);
2439         return;
2440     }
2441     case CSS_PROP_CLEAR:
2442     {
2443         HANDLE_INHERIT_AND_INITIAL(clear, Clear)
2444         if (primitiveValue)
2445             m_style->setClear(*primitiveValue);
2446         return;
2447     }
2448     case CSS_PROP_DIRECTION:
2449     {
2450         HANDLE_INHERIT_AND_INITIAL(direction, Direction)
2451         if (primitiveValue)
2452             m_style->setDirection(*primitiveValue);
2453         return;
2454     }
2455     case CSS_PROP_DISPLAY:
2456     {
2457         HANDLE_INHERIT_AND_INITIAL(display, Display)
2458         if (primitiveValue)
2459             m_style->setDisplay(*primitiveValue);
2460         return;
2461     }
2462
2463     case CSS_PROP_EMPTY_CELLS:
2464     {
2465         HANDLE_INHERIT_AND_INITIAL(emptyCells, EmptyCells)
2466         if (primitiveValue)
2467             m_style->setEmptyCells(*primitiveValue);
2468         return;
2469     }
2470     case CSS_PROP_FLOAT:
2471     {
2472         HANDLE_INHERIT_AND_INITIAL(floating, Floating)
2473         if (primitiveValue)
2474             m_style->setFloating(*primitiveValue);
2475         return;
2476     }
2477
2478     case CSS_PROP_FONT_STYLE:
2479     {
2480         FontDescription fontDescription = m_style->fontDescription();
2481         if (isInherit)
2482             fontDescription.setItalic(m_parentStyle->fontDescription().italic());
2483         else if (isInitial)
2484             fontDescription.setItalic(false);
2485         else {
2486             if (!primitiveValue)
2487                 return;
2488             switch (primitiveValue->getIdent()) {
2489                 case CSS_VAL_OBLIQUE:
2490                 // FIXME: oblique is the same as italic for the moment...
2491                 case CSS_VAL_ITALIC:
2492                     fontDescription.setItalic(true);
2493                     break;
2494                 case CSS_VAL_NORMAL:
2495                     fontDescription.setItalic(false);
2496                     break;
2497                 default:
2498                     return;
2499             }
2500         }
2501         if (m_style->setFontDescription(fontDescription))
2502             m_fontDirty = true;
2503         return;
2504     }
2505
2506     case CSS_PROP_FONT_VARIANT:
2507     {
2508         FontDescription fontDescription = m_style->fontDescription();
2509         if (isInherit) 
2510             fontDescription.setSmallCaps(m_parentStyle->fontDescription().smallCaps());
2511         else if (isInitial)
2512             fontDescription.setSmallCaps(false);
2513         else {
2514             if (!primitiveValue)
2515                 return;
2516             int id = primitiveValue->getIdent();
2517             if (id == CSS_VAL_NORMAL)
2518                 fontDescription.setSmallCaps(false);
2519             else if (id == CSS_VAL_SMALL_CAPS)
2520                 fontDescription.setSmallCaps(true);
2521             else
2522                 return;
2523         }
2524         if (m_style->setFontDescription(fontDescription))
2525             m_fontDirty = true;
2526         return;        
2527     }
2528
2529     case CSS_PROP_FONT_WEIGHT:
2530     {
2531         FontDescription fontDescription = m_style->fontDescription();
2532         if (isInherit)
2533             fontDescription.setWeight(m_parentStyle->fontDescription().weight());
2534         else if (isInitial)
2535             fontDescription.setWeight(cNormalWeight);
2536         else {
2537             if (!primitiveValue)
2538                 return;
2539             if (primitiveValue->getIdent()) {
2540                 switch (primitiveValue->getIdent()) {
2541                     // FIXME: We aren't genuinely supporting specific weight values.
2542                     case CSS_VAL_BOLD:
2543                     case CSS_VAL_BOLDER:
2544                     case CSS_VAL_600:
2545                     case CSS_VAL_700:
2546                     case CSS_VAL_800:
2547                     case CSS_VAL_900:
2548                         fontDescription.setWeight(cBoldWeight);
2549                         break;
2550                     case CSS_VAL_NORMAL:
2551                     case CSS_VAL_LIGHTER:
2552                     case CSS_VAL_100:
2553                     case CSS_VAL_200:
2554                     case CSS_VAL_300:
2555                     case CSS_VAL_400:
2556                     case CSS_VAL_500:
2557                         fontDescription.setWeight(cNormalWeight);
2558                         break;
2559                     default:
2560                         return;
2561                 }
2562             }
2563             else
2564             {
2565                 // ### fix parsing of 100-900 values in parser, apply them here
2566             }
2567         }
2568         if (m_style->setFontDescription(fontDescription))
2569             m_fontDirty = true;
2570         return;
2571     }
2572         
2573     case CSS_PROP_LIST_STYLE_POSITION:
2574     {
2575         HANDLE_INHERIT_AND_INITIAL(listStylePosition, ListStylePosition)
2576         if (primitiveValue)
2577             m_style->setListStylePosition(*primitiveValue);
2578         return;
2579     }
2580
2581     case CSS_PROP_LIST_STYLE_TYPE:
2582     {
2583         HANDLE_INHERIT_AND_INITIAL(listStyleType, ListStyleType)
2584         if (primitiveValue)
2585             m_style->setListStyleType(*primitiveValue);
2586         return;
2587     }
2588
2589     case CSS_PROP_OVERFLOW:
2590     {
2591         if (isInherit) {
2592             m_style->setOverflowX(m_parentStyle->overflowX());
2593             m_style->setOverflowY(m_parentStyle->overflowY());
2594             return;
2595         }
2596         
2597         if (isInitial) {
2598             m_style->setOverflowX(RenderStyle::initialOverflowX());
2599             m_style->setOverflowY(RenderStyle::initialOverflowY());
2600             return;
2601         }
2602             
2603         EOverflow o = *primitiveValue;
2604
2605         m_style->setOverflowX(o);
2606         m_style->setOverflowY(o);
2607         return;
2608     }
2609
2610     case CSS_PROP_OVERFLOW_X:
2611     {
2612         HANDLE_INHERIT_AND_INITIAL(overflowX, OverflowX)
2613         m_style->setOverflowX(*primitiveValue);
2614         return;
2615     }
2616
2617     case CSS_PROP_OVERFLOW_Y:
2618     {
2619         HANDLE_INHERIT_AND_INITIAL(overflowY, OverflowY)
2620         m_style->setOverflowY(*primitiveValue);
2621         return;
2622     }
2623
2624     case CSS_PROP_PAGE_BREAK_BEFORE:
2625     {
2626         HANDLE_INHERIT_AND_INITIAL_WITH_VALUE(pageBreakBefore, PageBreakBefore, PageBreak)
2627         if (primitiveValue)
2628             m_style->setPageBreakBefore(*primitiveValue);
2629         return;
2630     }
2631
2632     case CSS_PROP_PAGE_BREAK_AFTER:
2633     {
2634         HANDLE_INHERIT_AND_INITIAL_WITH_VALUE(pageBreakAfter, PageBreakAfter, PageBreak)
2635         if (primitiveValue)
2636             m_style->setPageBreakAfter(*primitiveValue);
2637         return;
2638     }
2639
2640     case CSS_PROP_PAGE_BREAK_INSIDE: {
2641         HANDLE_INHERIT_AND_INITIAL_WITH_VALUE(pageBreakInside, PageBreakInside, PageBreak)
2642         if (!primitiveValue)
2643             return;
2644         EPageBreak pageBreak = *primitiveValue;
2645         if (pageBreak != PBALWAYS)
2646             m_style->setPageBreakInside(pageBreak);
2647         return;
2648     }
2649         
2650     case CSS_PROP_POSITION:
2651     {
2652         HANDLE_INHERIT_AND_INITIAL(position, Position)
2653         if (primitiveValue)
2654             m_style->setPosition(*primitiveValue);
2655         return;
2656     }
2657
2658     case CSS_PROP_TABLE_LAYOUT: {
2659         HANDLE_INHERIT_AND_INITIAL(tableLayout, TableLayout)
2660
2661         ETableLayout l = *primitiveValue;
2662         if (l == TAUTO)
2663             l = RenderStyle::initialTableLayout();
2664
2665         m_style->setTableLayout(l);
2666         return;
2667     }
2668         
2669     case CSS_PROP_UNICODE_BIDI: {
2670         HANDLE_INHERIT_AND_INITIAL(unicodeBidi, UnicodeBidi)
2671         m_style->setUnicodeBidi(*primitiveValue);
2672         return;
2673     }
2674     case CSS_PROP_TEXT_TRANSFORM: {
2675         HANDLE_INHERIT_AND_INITIAL(textTransform, TextTransform)
2676         m_style->setTextTransform(*primitiveValue);
2677         return;
2678     }
2679
2680     case CSS_PROP_VISIBILITY:
2681     {
2682         HANDLE_INHERIT_AND_INITIAL(visibility, Visibility)
2683         m_style->setVisibility(*primitiveValue);
2684         return;
2685     }
2686     case CSS_PROP_WHITE_SPACE:
2687         HANDLE_INHERIT_AND_INITIAL(whiteSpace, WhiteSpace)
2688         m_style->setWhiteSpace(*primitiveValue);
2689         return;
2690
2691     case CSS_PROP_BACKGROUND_POSITION:
2692         HANDLE_BACKGROUND_INHERIT_AND_INITIAL(backgroundXPosition, BackgroundXPosition);
2693         HANDLE_BACKGROUND_INHERIT_AND_INITIAL(backgroundYPosition, BackgroundYPosition);
2694         return;
2695     case CSS_PROP_BACKGROUND_POSITION_X: {
2696         HANDLE_BACKGROUND_VALUE(backgroundXPosition, BackgroundXPosition, value)
2697         return;
2698     }
2699     case CSS_PROP_BACKGROUND_POSITION_Y: {
2700         HANDLE_BACKGROUND_VALUE(backgroundYPosition, BackgroundYPosition, value)
2701         return;
2702     }
2703     case CSS_PROP_BORDER_SPACING: {
2704         if (isInherit) {
2705             m_style->setHorizontalBorderSpacing(m_parentStyle->horizontalBorderSpacing());
2706             m_style->setVerticalBorderSpacing(m_parentStyle->verticalBorderSpacing());
2707         }
2708         else if (isInitial) {
2709             m_style->setHorizontalBorderSpacing(0);
2710             m_style->setVerticalBorderSpacing(0);
2711         }
2712         return;
2713     }
2714     case CSS_PROP__WEBKIT_BORDER_HORIZONTAL_SPACING: {
2715         HANDLE_INHERIT_AND_INITIAL(horizontalBorderSpacing, HorizontalBorderSpacing)
2716         if (!primitiveValue)
2717             return;
2718         short spacing =  primitiveValue->computeLengthShort(m_style);
2719         m_style->setHorizontalBorderSpacing(spacing);
2720         return;
2721     }
2722     case CSS_PROP__WEBKIT_BORDER_VERTICAL_SPACING: {
2723         HANDLE_INHERIT_AND_INITIAL(verticalBorderSpacing, VerticalBorderSpacing)
2724         if (!primitiveValue)
2725             return;
2726         short spacing =  primitiveValue->computeLengthShort(m_style);
2727         m_style->setVerticalBorderSpacing(spacing);
2728         return;
2729     }
2730     case CSS_PROP_CURSOR:
2731         if (isInherit) {
2732             m_style->setCursor(m_parentStyle->cursor());
2733             m_style->setCursorList(m_parentStyle->cursors());
2734             return;
2735         }
2736         m_style->clearCursorList();
2737         if (isInitial) {
2738             m_style->setCursor(RenderStyle::initialCursor());
2739             return;
2740         }
2741         if (value->isValueList()) {
2742             CSSValueList* list = static_cast<CSSValueList*>(value);
2743             int len = list->length();
2744             m_style->setCursor(CURSOR_AUTO);
2745             for (int i = 0; i < len; i++) {
2746                 CSSValue* item = list->item(i);
2747                 if (!item->isPrimitiveValue())
2748                     continue;
2749                 primitiveValue = static_cast<CSSPrimitiveValue*>(item);
2750                 int type = primitiveValue->primitiveType();
2751                 if (type == CSSPrimitiveValue::CSS_URI) {
2752                     CSSCursorImageValue* image = static_cast<CSSCursorImageValue*>(primitiveValue);
2753                     if (image->updateIfSVGCursorIsUsed(m_element)) // Elements with SVG cursors are not allowed to share style.
2754                         m_style->setUnique();
2755                     m_style->addCursor(image->image(m_element->document()->docLoader()), image->hotspot());
2756                 } else if (type == CSSPrimitiveValue::CSS_IDENT)
2757                     m_style->setCursor(*primitiveValue);
2758             }
2759         } else if (primitiveValue) {
2760             int type = primitiveValue->primitiveType();
2761             if (type == CSSPrimitiveValue::CSS_IDENT)
2762                 m_style->setCursor(*primitiveValue);
2763         }
2764         return;
2765 // colors || inherit
2766     case CSS_PROP_BACKGROUND_COLOR:
2767     case CSS_PROP_BORDER_TOP_COLOR:
2768     case CSS_PROP_BORDER_RIGHT_COLOR:
2769     case CSS_PROP_BORDER_BOTTOM_COLOR:
2770     case CSS_PROP_BORDER_LEFT_COLOR:
2771     case CSS_PROP_COLOR:
2772     case CSS_PROP_OUTLINE_COLOR:
2773     case CSS_PROP__WEBKIT_COLUMN_RULE_COLOR:
2774     case CSS_PROP__WEBKIT_TEXT_STROKE_COLOR:
2775     case CSS_PROP__WEBKIT_TEXT_FILL_COLOR: {
2776         Color col;
2777         if (isInherit) {
2778             HANDLE_INHERIT_COND(CSS_PROP_BACKGROUND_COLOR, backgroundColor, BackgroundColor)
2779             HANDLE_INHERIT_COND(CSS_PROP_BORDER_TOP_COLOR, borderTopColor, BorderTopColor)
2780             HANDLE_INHERIT_COND(CSS_PROP_BORDER_BOTTOM_COLOR, borderBottomColor, BorderBottomColor)
2781             HANDLE_INHERIT_COND(CSS_PROP_BORDER_RIGHT_COLOR, borderRightColor, BorderRightColor)
2782             HANDLE_INHERIT_COND(CSS_PROP_BORDER_LEFT_COLOR, borderLeftColor, BorderLeftColor)
2783             HANDLE_INHERIT_COND(CSS_PROP_COLOR, color, Color)
2784             HANDLE_INHERIT_COND(CSS_PROP_OUTLINE_COLOR, outlineColor, OutlineColor)
2785             HANDLE_INHERIT_COND(CSS_PROP__WEBKIT_COLUMN_RULE_COLOR, columnRuleColor, ColumnRuleColor)
2786             HANDLE_INHERIT_COND(CSS_PROP__WEBKIT_TEXT_STROKE_COLOR, textStrokeColor, TextStrokeColor)
2787             HANDLE_INHERIT_COND(CSS_PROP__WEBKIT_TEXT_FILL_COLOR, textFillColor, TextFillColor)
2788             return;
2789         }
2790         if (isInitial) {
2791             // The border/outline colors will just map to the invalid color |col| above.  This will have the
2792             // effect of forcing the use of the currentColor when it comes time to draw the borders (and of
2793             // not painting the background since the color won't be valid).
2794             if (id == CSS_PROP_COLOR)
2795                 col = RenderStyle::initialColor();
2796         } else {
2797             if (!primitiveValue)
2798                 return;
2799             col = getColorFromPrimitiveValue(primitiveValue);
2800         }
2801
2802         switch (id) {
2803         case CSS_PROP_BACKGROUND_COLOR:
2804             m_style->setBackgroundColor(col);
2805             break;
2806         case CSS_PROP_BORDER_TOP_COLOR:
2807             m_style->setBorderTopColor(col);
2808             break;
2809         case CSS_PROP_BORDER_RIGHT_COLOR:
2810             m_style->setBorderRightColor(col);
2811             break;
2812         case CSS_PROP_BORDER_BOTTOM_COLOR:
2813             m_style->setBorderBottomColor(col);
2814             break;
2815         case CSS_PROP_BORDER_LEFT_COLOR:
2816             m_style->setBorderLeftColor(col);
2817             break;
2818         case CSS_PROP_COLOR:
2819             m_style->setColor(col);
2820             break;
2821         case CSS_PROP_OUTLINE_COLOR:
2822             m_style->setOutlineColor(col);
2823             break;
2824         case CSS_PROP__WEBKIT_COLUMN_RULE_COLOR:
2825             m_style->setColumnRuleColor(col);
2826             break;
2827         case CSS_PROP__WEBKIT_TEXT_STROKE_COLOR:
2828             m_style->setTextStrokeColor(col);
2829             break;
2830         case CSS_PROP__WEBKIT_TEXT_FILL_COLOR:
2831             m_style->setTextFillColor(col);
2832             break;
2833         }
2834         
2835         return;
2836     }
2837     
2838 // uri || inherit
2839     case CSS_PROP_BACKGROUND_IMAGE:
2840         HANDLE_BACKGROUND_VALUE(backgroundImage, BackgroundImage, value)
2841         return;
2842     case CSS_PROP_LIST_STYLE_IMAGE:
2843     {
2844         HANDLE_INHERIT_AND_INITIAL(listStyleImage, ListStyleImage)
2845         if (!primitiveValue)
2846             return;
2847         m_style->setListStyleImage(static_cast<CSSImageValue*>(primitiveValue)->image(m_element->document()->docLoader()));
2848         return;
2849     }
2850
2851 // length
2852     case CSS_PROP_BORDER_TOP_WIDTH:
2853     case CSS_PROP_BORDER_RIGHT_WIDTH:
2854     case CSS_PROP_BORDER_BOTTOM_WIDTH:
2855     case CSS_PROP_BORDER_LEFT_WIDTH:
2856     case CSS_PROP_OUTLINE_WIDTH:
2857     case CSS_PROP__WEBKIT_COLUMN_RULE_WIDTH:
2858     {
2859         if (isInherit) {
2860             HANDLE_INHERIT_COND(CSS_PROP_BORDER_TOP_WIDTH, borderTopWidth, BorderTopWidth)
2861             HANDLE_INHERIT_COND(CSS_PROP_BORDER_RIGHT_WIDTH, borderRightWidth, BorderRightWidth)
2862             HANDLE_INHERIT_COND(CSS_PROP_BORDER_BOTTOM_WIDTH, borderBottomWidth, BorderBottomWidth)
2863             HANDLE_INHERIT_COND(CSS_PROP_BORDER_LEFT_WIDTH, borderLeftWidth, BorderLeftWidth)
2864             HANDLE_INHERIT_COND(CSS_PROP_OUTLINE_WIDTH, outlineWidth, OutlineWidth)
2865             HANDLE_INHERIT_COND(CSS_PROP__WEBKIT_COLUMN_RULE_WIDTH, columnRuleWidth, ColumnRuleWidth)
2866             return;
2867         }
2868         else if (isInitial) {
2869             HANDLE_INITIAL_COND_WITH_VALUE(CSS_PROP_BORDER_TOP_WIDTH, BorderTopWidth, BorderWidth)
2870             HANDLE_INITIAL_COND_WITH_VALUE(CSS_PROP_BORDER_RIGHT_WIDTH, BorderRightWidth, BorderWidth)
2871             HANDLE_INITIAL_COND_WITH_VALUE(CSS_PROP_BORDER_BOTTOM_WIDTH, BorderBottomWidth, BorderWidth)
2872             HANDLE_INITIAL_COND_WITH_VALUE(CSS_PROP_BORDER_LEFT_WIDTH, BorderLeftWidth, BorderWidth)
2873             HANDLE_INITIAL_COND_WITH_VALUE(CSS_PROP_OUTLINE_WIDTH, OutlineWidth, BorderWidth)
2874             HANDLE_INITIAL_COND_WITH_VALUE(CSS_PROP__WEBKIT_COLUMN_RULE_WIDTH, ColumnRuleWidth, BorderWidth)
2875             return;
2876         }
2877
2878         if (!primitiveValue)
2879             return;
2880         short width = 3;
2881         switch (primitiveValue->getIdent()) {
2882         case CSS_VAL_THIN:
2883             width = 1;
2884             break;
2885         case CSS_VAL_MEDIUM:
2886             width = 3;
2887             break;
2888         case CSS_VAL_THICK:
2889             width = 5;
2890             break;
2891         case CSS_VAL_INVALID:
2892             width = primitiveValue->computeLengthShort(m_style);
2893             break;
2894         default:
2895             return;
2896         }
2897
2898         if (width < 0) return;
2899         switch (id) {
2900         case CSS_PROP_BORDER_TOP_WIDTH:
2901             m_style->setBorderTopWidth(width);
2902             break;
2903         case CSS_PROP_BORDER_RIGHT_WIDTH:
2904             m_style->setBorderRightWidth(width);
2905             break;
2906         case CSS_PROP_BORDER_BOTTOM_WIDTH:
2907             m_style->setBorderBottomWidth(width);
2908             break;
2909         case CSS_PROP_BORDER_LEFT_WIDTH:
2910             m_style->setBorderLeftWidth(width);
2911             break;
2912         case CSS_PROP_OUTLINE_WIDTH:
2913             m_style->setOutlineWidth(width);
2914             break;
2915         case CSS_PROP__WEBKIT_COLUMN_RULE_WIDTH:
2916             m_style->setColumnRuleWidth(width);
2917             break;
2918         default:
2919             return;
2920         }
2921         return;
2922     }
2923
2924     case CSS_PROP_LETTER_SPACING:
2925     case CSS_PROP_WORD_SPACING:
2926     {
2927         
2928         if (isInherit) {
2929             HANDLE_INHERIT_COND(CSS_PROP_LETTER_SPACING, letterSpacing, LetterSpacing)
2930             HANDLE_INHERIT_COND(CSS_PROP_WORD_SPACING, wordSpacing, WordSpacing)
2931             return;
2932         }
2933         else if (isInitial) {
2934             HANDLE_INITIAL_COND_WITH_VALUE(CSS_PROP_LETTER_SPACING, LetterSpacing, LetterWordSpacing)
2935             HANDLE_INITIAL_COND_WITH_VALUE(CSS_PROP_WORD_SPACING, WordSpacing, LetterWordSpacing)
2936             return;
2937         }
2938         
2939         int width = 0;
2940         if (primitiveValue && primitiveValue->getIdent() == CSS_VAL_NORMAL){
2941             width = 0;
2942         } else {
2943             if (!primitiveValue)
2944                 return;
2945             width = primitiveValue->computeLengthInt(m_style);
2946         }
2947         switch (id) {
2948         case CSS_PROP_LETTER_SPACING:
2949             m_style->setLetterSpacing(width);
2950             break;
2951         case CSS_PROP_WORD_SPACING:
2952             m_style->setWordSpacing(width);
2953             break;
2954             // ### needs the definitions in renderstyle
2955         default: break;
2956         }
2957         return;
2958     }
2959
2960     case CSS_PROP_WORD_BREAK: {
2961         HANDLE_INHERIT_AND_INITIAL(wordBreak, WordBreak)
2962         m_style->setWordBreak(*primitiveValue);
2963         return;
2964     }
2965
2966     case CSS_PROP_WORD_WRAP: {
2967         HANDLE_INHERIT_AND_INITIAL(wordWrap, WordWrap)
2968         m_style->setWordWrap(*primitiveValue);
2969         return;
2970     }
2971
2972     case CSS_PROP__WEBKIT_NBSP_MODE:
2973     {
2974         HANDLE_INHERIT_AND_INITIAL(nbspMode, NBSPMode)
2975         m_style->setNBSPMode(*primitiveValue);
2976         return;
2977     }
2978
2979     case CSS_PROP__WEBKIT_LINE_BREAK:
2980     {
2981         HANDLE_INHERIT_AND_INITIAL(khtmlLineBreak, KHTMLLineBreak)
2982         m_style->setKHTMLLineBreak(*primitiveValue);
2983         return;
2984     }
2985
2986     case CSS_PROP__WEBKIT_MATCH_NEAREST_MAIL_BLOCKQUOTE_COLOR:
2987     {
2988         HANDLE_INHERIT_AND_INITIAL(matchNearestMailBlockquoteColor, MatchNearestMailBlockquoteColor)
2989         m_style->setMatchNearestMailBlockquoteColor(*primitiveValue);
2990         return;
2991     }
2992
2993     case CSS_PROP_RESIZE:
2994     {
2995         HANDLE_INHERIT_AND_INITIAL(resize, Resize)
2996
2997         if (!primitiveValue->getIdent())
2998             return;
2999
3000         EResize r = RESIZE_NONE;
3001         if (primitiveValue->getIdent() == CSS_VAL_AUTO) {
3002             if (Settings* settings = m_document->settings())
3003                 r = settings->textAreasAreResizable() ? RESIZE_BOTH : RESIZE_NONE;
3004         } else
3005             r = *primitiveValue;
3006             
3007         m_style->setResize(r);
3008         return;
3009     }
3010     
3011     // length, percent
3012     case CSS_PROP_MAX_WIDTH:
3013         // +none +inherit
3014         if (primitiveValue && primitiveValue->getIdent() == CSS_VAL_NONE)
3015             apply = true;
3016     case CSS_PROP_TOP:
3017     case CSS_PROP_LEFT:
3018     case CSS_PROP_RIGHT:
3019     case CSS_PROP_BOTTOM:
3020     case CSS_PROP_WIDTH:
3021     case CSS_PROP_MIN_WIDTH:
3022     case CSS_PROP_MARGIN_TOP:
3023     case CSS_PROP_MARGIN_RIGHT:
3024     case CSS_PROP_MARGIN_BOTTOM:
3025     case CSS_PROP_MARGIN_LEFT:
3026         // +inherit +auto
3027         if (id == CSS_PROP_WIDTH || id == CSS_PROP_MIN_WIDTH || id == CSS_PROP_MAX_WIDTH) {
3028             if (primitiveValue && primitiveValue->getIdent() == CSS_VAL_INTRINSIC) {
3029                 l = Length(Intrinsic);
3030                 apply = true;
3031             }
3032             else if (primitiveValue && primitiveValue->getIdent() == CSS_VAL_MIN_INTRINSIC) {
3033                 l = Length(MinIntrinsic);
3034                 apply = true;
3035             }
3036         }
3037         if (id != CSS_PROP_MAX_WIDTH && primitiveValue && primitiveValue->getIdent() == CSS_VAL_AUTO)
3038             apply = true;
3039     case CSS_PROP_PADDING_TOP:
3040     case CSS_PROP_PADDING_RIGHT:
3041     case CSS_PROP_PADDING_BOTTOM:
3042     case CSS_PROP_PADDING_LEFT:
3043     case CSS_PROP_TEXT_INDENT:
3044         // +inherit
3045     {
3046         if (isInherit) {
3047             HANDLE_INHERIT_COND(CSS_PROP_MAX_WIDTH, maxWidth, MaxWidth)
3048             HANDLE_INHERIT_COND(CSS_PROP_BOTTOM, bottom, Bottom)
3049             HANDLE_INHERIT_COND(CSS_PROP_TOP, top, Top)
3050             HANDLE_INHERIT_COND(CSS_PROP_LEFT, left, Left)
3051             HANDLE_INHERIT_COND(CSS_PROP_RIGHT, right, Right)
3052             HANDLE_INHERIT_COND(CSS_PROP_WIDTH, width, Width)
3053             HANDLE_INHERIT_COND(CSS_PROP_MIN_WIDTH, minWidth, MinWidth)
3054             HANDLE_INHERIT_COND(CSS_PROP_PADDING_TOP, paddingTop, PaddingTop)
3055             HANDLE_INHERIT_COND(CSS_PROP_PADDING_RIGHT, paddingRight, PaddingRight)
3056             HANDLE_INHERIT_COND(CSS_PROP_PADDING_BOTTOM, paddingBottom, PaddingBottom)
3057             HANDLE_INHERIT_COND(CSS_PROP_PADDING_LEFT, paddingLeft, PaddingLeft)
3058             HANDLE_INHERIT_COND(CSS_PROP_MARGIN_TOP, marginTop, MarginTop)
3059             HANDLE_INHERIT_COND(CSS_PROP_MARGIN_RIGHT, marginRight, MarginRight)
3060             HANDLE_INHERIT_COND(CSS_PROP_MARGIN_BOTTOM, marginBottom, MarginBottom)
3061             HANDLE_INHERIT_COND(CSS_PROP_MARGIN_LEFT, marginLeft, MarginLeft)
3062             HANDLE_INHERIT_COND(CSS_PROP_TEXT_INDENT, textIndent, TextIndent)
3063             return;
3064         }
3065         else if (isInitial) {
3066             HANDLE_INITIAL_COND_WITH_VALUE(CSS_PROP_MAX_WIDTH, MaxWidth, MaxSize)
3067             HANDLE_INITIAL_COND_WITH_VALUE(CSS_PROP_BOTTOM, Bottom, Offset)
3068             HANDLE_INITIAL_COND_WITH_VALUE(CSS_PROP_TOP, Top, Offset)
3069             HANDLE_INITIAL_COND_WITH_VALUE(CSS_PROP_LEFT, Left, Offset)
3070             HANDLE_INITIAL_COND_WITH_VALUE(CSS_PROP_RIGHT, Right, Offset)
3071             HANDLE_INITIAL_COND_WITH_VALUE(CSS_PROP_WIDTH, Width, Size)
3072             HANDLE_INITIAL_COND_WITH_VALUE(CSS_PROP_MIN_WIDTH, MinWidth, MinSize)
3073             HANDLE_INITIAL_COND_WITH_VALUE(CSS_PROP_PADDING_TOP, PaddingTop, Padding)
3074             HANDLE_INITIAL_COND_WITH_VALUE(CSS_PROP_PADDING_RIGHT, PaddingRight, Padding)
3075             HANDLE_INITIAL_COND_WITH_VALUE(CSS_PROP_PADDING_BOTTOM, PaddingBottom, Padding)
3076             HANDLE_INITIAL_COND_WITH_VALUE(CSS_PROP_PADDING_LEFT, PaddingLeft, Padding)
3077             HANDLE_INITIAL_COND_WITH_VALUE(CSS_PROP_MARGIN_TOP, MarginTop, Margin)
3078             HANDLE_INITIAL_COND_WITH_VALUE(CSS_PROP_MARGIN_RIGHT, MarginRight, Margin)
3079             HANDLE_INITIAL_COND_WITH_VALUE(CSS_PROP_MARGIN_BOTTOM, MarginBottom, Margin)
3080             HANDLE_INITIAL_COND_WITH_VALUE(CSS_PROP_MARGIN_LEFT, MarginLeft, Margin)
3081             HANDLE_INITIAL_COND(CSS_PROP_TEXT_INDENT, TextIndent)
3082             return;
3083         } 
3084
3085         if (primitiveValue && !apply) {
3086             int type = primitiveValue->primitiveType();
3087             if (type > CSSPrimitiveValue::CSS_PERCENTAGE && type < CSSPrimitiveValue::CSS_DEG)
3088                 // Handle our quirky margin units if we have them.
3089                 l = Length(primitiveValue->computeLengthIntForLength(m_style), Fixed, 
3090                            primitiveValue->isQuirkValue());
3091             else if (type == CSSPrimitiveValue::CSS_PERCENTAGE)
3092                 l = Length(primitiveValue->getDoubleValue(), Percent);
3093             else
3094                 return;
3095             if (id == CSS_PROP_PADDING_LEFT || id == CSS_PROP_PADDING_RIGHT ||
3096                 id == CSS_PROP_PADDING_TOP || id == CSS_PROP_PADDING_BOTTOM)
3097                 // Padding can't be negative
3098                 apply = !((l.isFixed() || l.isPercent()) && l.calcValue(100) < 0);
3099             else
3100                 apply = true;
3101         }
3102         if (!apply) return;
3103         switch (id) {
3104             case CSS_PROP_MAX_WIDTH:
3105                 m_style->setMaxWidth(l);
3106                 break;
3107             case CSS_PROP_BOTTOM:
3108                 m_style->setBottom(l);
3109                 break;
3110             case CSS_PROP_TOP:
3111                 m_style->setTop(l);
3112                 break;
3113             case CSS_PROP_LEFT:
3114                 m_style->setLeft(l);
3115                 break;
3116             case CSS_PROP_RIGHT:
3117                 m_style->setRight(l);
3118                 break;
3119             case CSS_PROP_WIDTH:
3120                 m_style->setWidth(l);
3121                 break;
3122             case CSS_PROP_MIN_WIDTH:
3123                 m_style->setMinWidth(l);
3124                 break;
3125             case CSS_PROP_PADDING_TOP:
3126                 m_style->setPaddingTop(l);
3127                 break;
3128             case CSS_PROP_PADDING_RIGHT:
3129                 m_style->setPaddingRight(l);
3130                 break;
3131             case CSS_PROP_PADDING_BOTTOM:
3132                 m_style->setPaddingBottom(l);
3133                 break;
3134             case CSS_PROP_PADDING_LEFT:
3135                 m_style->setPaddingLeft(l);
3136                 break;
3137             case CSS_PROP_MARGIN_TOP:
3138                 m_style->setMarginTop(l);
3139                 break;
3140             case CSS_PROP_MARGIN_RIGHT:
3141                 m_style->setMarginRight(l);
3142                 break;
3143             case CSS_PROP_MARGIN_BOTTOM:
3144                 m_style->setMarginBottom(l);
3145                 break;
3146             case CSS_PROP_MARGIN_LEFT:
3147                 m_style->setMarginLeft(l);
3148                 break;
3149             case CSS_PROP_TEXT_INDENT:
3150                 m_style->setTextIndent(l);
3151                 break;
3152             default:
3153                 break;
3154             }
3155         return;
3156     }
3157
3158     case CSS_PROP_MAX_HEIGHT:
3159         if (primitiveValue && primitiveValue->getIdent() == CSS_VAL_NONE) {
3160             l = Length(undefinedLength, Fixed);
3161             apply = true;
3162         }
3163     case CSS_PROP_HEIGHT:
3164     case CSS_PROP_MIN_HEIGHT:
3165         if (primitiveValue && primitiveValue->getIdent() == CSS_VAL_INTRINSIC) {
3166             l = Length(Intrinsic);
3167             apply = true;
3168         } else if (primitiveValue && primitiveValue->getIdent() == CSS_VAL_MIN_INTRINSIC) {
3169             l = Length(MinIntrinsic);
3170             apply = true;
3171         } else if (id != CSS_PROP_MAX_HEIGHT && primitiveValue && primitiveValue->getIdent() == CSS_VAL_AUTO)
3172             apply = true;
3173         if (isInherit) {
3174             HANDLE_INHERIT_COND(CSS_PROP_MAX_HEIGHT, maxHeight, MaxHeight)
3175             HANDLE_INHERIT_COND(CSS_PROP_HEIGHT, height, Height)
3176             HANDLE_INHERIT_COND(CSS_PROP_MIN_HEIGHT, minHeight, MinHeight)
3177             return;
3178         }
3179         if (isInitial) {
3180             HANDLE_INITIAL_COND_WITH_VALUE(CSS_PROP_MAX_HEIGHT, MaxHeight, MaxSize)
3181             HANDLE_INITIAL_COND_WITH_VALUE(CSS_PROP_HEIGHT, Height, Size)
3182             HANDLE_INITIAL_COND_WITH_VALUE(CSS_PROP_MIN_HEIGHT, MinHeight, MinSize)
3183             return;
3184         }
3185
3186         if (primitiveValue && !apply) {
3187             unsigned short type = primitiveValue->primitiveType();
3188             if (type > CSSPrimitiveValue::CSS_PERCENTAGE && type < CSSPrimitiveValue::CSS_DEG)
3189                 l = Length(primitiveValue->computeLengthIntForLength(m_style), Fixed);
3190             else if (type == CSSPrimitiveValue::CSS_PERCENTAGE)
3191                 l = Length(primitiveValue->getDoubleValue(), Percent);
3192             else
3193                 return;
3194             apply = true;
3195         }
3196         if (apply)
3197             switch (id) {
3198                 case CSS_PROP_MAX_HEIGHT:
3199                     m_style->setMaxHeight(l);
3200                     break;
3201                 case CSS_PROP_HEIGHT:
3202                     m_style->setHeight(l);
3203                     break;
3204                 case CSS_PROP_MIN_HEIGHT:
3205                     m_style->setMinHeight(l);
3206                     break;
3207             }
3208         return;
3209
3210     case CSS_PROP_VERTICAL_ALIGN:
3211         HANDLE_INHERIT_AND_INITIAL(verticalAlign, VerticalAlign)
3212         if (!primitiveValue)
3213             return;
3214         if (primitiveValue->getIdent()) {
3215           EVerticalAlign align;
3216
3217           switch (primitiveValue->getIdent()) {
3218                 case CSS_VAL_TOP:
3219                     align = TOP; break;
3220                 case CSS_VAL_BOTTOM:
3221                     align = BOTTOM; break;
3222                 case CSS_VAL_MIDDLE:
3223                     align = MIDDLE; break;
3224                 case CSS_VAL_BASELINE:
3225                     align = BASELINE; break;
3226                 case CSS_VAL_TEXT_BOTTOM:
3227                     align = TEXT_BOTTOM; break;
3228                 case CSS_VAL_TEXT_TOP:
3229                     align = TEXT_TOP; break;
3230                 case CSS_VAL_SUB:
3231                     align = SUB; break;
3232                 case CSS_VAL_SUPER:
3233                     align = SUPER; break;
3234                 case CSS_VAL__WEBKIT_BASELINE_MIDDLE:
3235                     align = BASELINE_MIDDLE; break;
3236                 default:
3237                     return;
3238             }
3239           m_style->setVerticalAlign(align);
3240           return;
3241         } else {
3242           int type = primitiveValue->primitiveType();
3243           Length l;
3244           if (type > CSSPrimitiveValue::CSS_PERCENTAGE && type < CSSPrimitiveValue::CSS_DEG)
3245             l = Length(primitiveValue->computeLengthIntForLength(m_style), Fixed);
3246           else if (type == CSSPrimitiveValue::CSS_PERCENTAGE)
3247             l = Length(primitiveValue->getDoubleValue(), Percent);
3248