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