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