64469ad4900fb16b26868af97a5a91f3cc88a598
[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_FONT_STRETCH:
1825                     case CSS_PROP_FONT_VARIANT:
1826                     case CSS_PROP__WEBKIT_TEXT_SIZE_ADJUST:
1827                         // these have to be applied first, because other properties use the computed
1828                         // values of these porperties.
1829                         first = true;
1830                         break;
1831                     default:
1832                         first = false;
1833                         break;
1834                 }
1835                 
1836                 if (first == applyFirst)
1837                     applyProperty(current.id(), current.value());
1838             }
1839         }
1840     }
1841 }
1842
1843 static void applyCounterList(RenderStyle* style, CSSValueList* list, bool isReset)
1844 {
1845     CounterDirectiveMap& map = style->accessCounterDirectives();
1846     typedef CounterDirectiveMap::iterator Iterator;
1847
1848     Iterator end = map.end();
1849     for (Iterator it = map.begin(); it != end; ++it)
1850         if (isReset)
1851             it->second.m_reset = false;
1852         else
1853             it->second.m_increment = false;
1854
1855     int length = list ? list->length() : 0;
1856     for (int i = 0; i < length; ++i) {
1857         Pair* pair = static_cast<CSSPrimitiveValue*>(list->item(i))->getPairValue();
1858         AtomicString identifier = static_cast<CSSPrimitiveValue*>(pair->first())->getStringValue();
1859         // FIXME: What about overflow?
1860         int value = static_cast<int>(static_cast<CSSPrimitiveValue*>(pair->second())->getFloatValue());
1861         CounterDirectives& directives = map.add(identifier.impl(), CounterDirectives()).first->second;
1862         if (isReset) {
1863             directives.m_reset = true;
1864             directives.m_resetValue = value;
1865         } else {
1866             if (directives.m_increment)
1867                 directives.m_incrementValue += value;
1868             else {
1869                 directives.m_increment = true;
1870                 directives.m_incrementValue = value;
1871             }
1872         }
1873     }
1874 }
1875
1876 void CSSStyleSelector::applyProperty(int id, CSSValue *value)
1877 {
1878     CSSPrimitiveValue *primitiveValue = 0;
1879     if(value->isPrimitiveValue()) primitiveValue = static_cast<CSSPrimitiveValue*>(value);
1880
1881     Length l;
1882     bool apply = false;
1883
1884     unsigned short valueType = value->cssValueType();
1885
1886     bool isInherit = parentNode && valueType == CSSValue::CSS_INHERIT;
1887     bool isInitial = valueType == CSSValue::CSS_INITIAL || (!parentNode && valueType == CSSValue::CSS_INHERIT);
1888
1889     // These properties are used to set the correct margins/padding on RTL lists.
1890     if (id == CSS_PROP__WEBKIT_MARGIN_START)
1891         id = style->direction() == LTR ? CSS_PROP_MARGIN_LEFT : CSS_PROP_MARGIN_RIGHT;
1892     else if (id == CSS_PROP__WEBKIT_PADDING_START)
1893         id = style->direction() == LTR ? CSS_PROP_PADDING_LEFT : CSS_PROP_PADDING_RIGHT;
1894
1895     // What follows is a list that maps the CSS properties into their corresponding front-end
1896     // RenderStyle values.  Shorthands (e.g. border, background) occur in this list as well and
1897     // are only hit when mapping "inherit" or "initial" into front-end values.
1898     switch (static_cast<CSSPropertyID>(id))
1899     {
1900 // ident only properties
1901     case CSS_PROP_BACKGROUND_ATTACHMENT:
1902         HANDLE_BACKGROUND_VALUE(backgroundAttachment, BackgroundAttachment, value)
1903         return;
1904     case CSS_PROP__WEBKIT_BACKGROUND_CLIP:
1905         HANDLE_BACKGROUND_VALUE(backgroundClip, BackgroundClip, value)
1906         return;
1907     case CSS_PROP__WEBKIT_BACKGROUND_COMPOSITE:
1908         HANDLE_BACKGROUND_VALUE(backgroundComposite, BackgroundComposite, value)
1909         return;
1910     case CSS_PROP__WEBKIT_BACKGROUND_ORIGIN:
1911         HANDLE_BACKGROUND_VALUE(backgroundOrigin, BackgroundOrigin, value)
1912         return;
1913     case CSS_PROP_BACKGROUND_REPEAT:
1914         HANDLE_BACKGROUND_VALUE(backgroundRepeat, BackgroundRepeat, value)
1915         return;
1916     case CSS_PROP__WEBKIT_BACKGROUND_SIZE:
1917         HANDLE_BACKGROUND_VALUE(backgroundSize, BackgroundSize, value)
1918         return;
1919     case CSS_PROP_BORDER_COLLAPSE:
1920         HANDLE_INHERIT_AND_INITIAL(borderCollapse, BorderCollapse)
1921         if(!primitiveValue) return;
1922         switch(primitiveValue->getIdent())
1923         {
1924         case CSS_VAL_COLLAPSE:
1925             style->setBorderCollapse(true);
1926             break;
1927         case CSS_VAL_SEPARATE:
1928             style->setBorderCollapse(false);
1929             break;
1930         default:
1931             return;
1932         }
1933         return;
1934         
1935     case CSS_PROP_BORDER_TOP_STYLE:
1936         HANDLE_INHERIT_AND_INITIAL_WITH_VALUE(borderTopStyle, BorderTopStyle, BorderStyle)
1937         if (!primitiveValue) return;
1938         style->setBorderTopStyle((EBorderStyle)(primitiveValue->getIdent() - CSS_VAL_NONE));
1939         return;
1940     case CSS_PROP_BORDER_RIGHT_STYLE:
1941         HANDLE_INHERIT_AND_INITIAL_WITH_VALUE(borderRightStyle, BorderRightStyle, BorderStyle)
1942         if (!primitiveValue) return;
1943         style->setBorderRightStyle((EBorderStyle)(primitiveValue->getIdent() - CSS_VAL_NONE));
1944         return;
1945     case CSS_PROP_BORDER_BOTTOM_STYLE:
1946         HANDLE_INHERIT_AND_INITIAL_WITH_VALUE(borderBottomStyle, BorderBottomStyle, BorderStyle)
1947         if (!primitiveValue) return;
1948         style->setBorderBottomStyle((EBorderStyle)(primitiveValue->getIdent() - CSS_VAL_NONE));
1949         return;
1950     case CSS_PROP_BORDER_LEFT_STYLE:
1951         HANDLE_INHERIT_AND_INITIAL_WITH_VALUE(borderLeftStyle, BorderLeftStyle, BorderStyle)
1952         if (!primitiveValue) return;
1953         style->setBorderLeftStyle((EBorderStyle)(primitiveValue->getIdent() - CSS_VAL_NONE));
1954         return;
1955     case CSS_PROP_OUTLINE_STYLE:
1956         HANDLE_INHERIT_AND_INITIAL_WITH_VALUE(outlineStyle, OutlineStyle, BorderStyle)
1957         if (!primitiveValue) return;
1958         if (primitiveValue->getIdent() == CSS_VAL_AUTO)
1959             style->setOutlineStyle(DOTTED, true);
1960         else
1961             style->setOutlineStyle((EBorderStyle)(primitiveValue->getIdent() - CSS_VAL_NONE));
1962         return;
1963     case CSS_PROP_CAPTION_SIDE:
1964     {
1965         HANDLE_INHERIT_AND_INITIAL(captionSide, CaptionSide)
1966         if(!primitiveValue) return;
1967         ECaptionSide c = RenderStyle::initialCaptionSide();
1968         switch(primitiveValue->getIdent())
1969         {
1970         case CSS_VAL_LEFT:
1971             c = CAPLEFT; break;
1972         case CSS_VAL_RIGHT:
1973             c = CAPRIGHT; break;
1974         case CSS_VAL_TOP:
1975             c = CAPTOP; break;
1976         case CSS_VAL_BOTTOM:
1977             c = CAPBOTTOM; break;
1978         default:
1979             return;
1980         }
1981         style->setCaptionSide(c);
1982         return;
1983     }
1984     case CSS_PROP_CLEAR:
1985     {
1986         HANDLE_INHERIT_AND_INITIAL(clear, Clear)
1987         if(!primitiveValue) return;
1988         EClear c;
1989         switch(primitiveValue->getIdent())
1990         {
1991         case CSS_VAL_NONE:
1992             c = CNONE; break;
1993         case CSS_VAL_LEFT:
1994             c = CLEFT; break;
1995         case CSS_VAL_RIGHT:
1996             c = CRIGHT; break;
1997         case CSS_VAL_BOTH:
1998             c = CBOTH; break;
1999         default:
2000             return;
2001         }
2002         style->setClear(c);
2003         return;
2004     }
2005     case CSS_PROP_DIRECTION:
2006     {
2007         HANDLE_INHERIT_AND_INITIAL(direction, Direction)
2008         if(!primitiveValue) break;
2009         style->setDirection(primitiveValue->getIdent() == CSS_VAL_LTR ? LTR : RTL);
2010         return;
2011     }
2012     case CSS_PROP_DISPLAY:
2013     {
2014         HANDLE_INHERIT_AND_INITIAL(display, Display)
2015         if(!primitiveValue) break;
2016         int id = primitiveValue->getIdent();
2017         EDisplay d;
2018         if (id == CSS_VAL_NONE)
2019             d = NONE;
2020         else
2021             d = EDisplay(primitiveValue->getIdent() - CSS_VAL_INLINE);
2022
2023         style->setDisplay(d);
2024         return;
2025     }
2026
2027     case CSS_PROP_EMPTY_CELLS:
2028     {
2029         HANDLE_INHERIT_AND_INITIAL(emptyCells, EmptyCells)
2030         if (!primitiveValue) break;
2031         int id = primitiveValue->getIdent();
2032         if (id == CSS_VAL_SHOW)
2033             style->setEmptyCells(SHOW);
2034         else if (id == CSS_VAL_HIDE)
2035             style->setEmptyCells(HIDE);
2036         return;
2037     }
2038     case CSS_PROP_FLOAT:
2039     {
2040         HANDLE_INHERIT_AND_INITIAL(floating, Floating)
2041         if(!primitiveValue) return;
2042         EFloat f;
2043         switch(primitiveValue->getIdent())
2044         {
2045         case CSS_VAL_LEFT:
2046             f = FLEFT; break;
2047         case CSS_VAL_RIGHT:
2048             f = FRIGHT; break;
2049         case CSS_VAL_NONE:
2050         case CSS_VAL_CENTER:  //Non standart CSS-Value
2051             f = FNONE; break;
2052         default:
2053             return;
2054         }
2055         
2056         style->setFloating(f);
2057         return;
2058     }
2059
2060     case CSS_PROP_FONT_STYLE:
2061     {
2062         FontDescription fontDescription = style->fontDescription();
2063         if (isInherit)
2064             fontDescription.setItalic(parentStyle->fontDescription().italic());
2065         else if (isInitial)
2066             fontDescription.setItalic(false);
2067         else {
2068             if (!primitiveValue) return;
2069             switch (primitiveValue->getIdent()) {
2070                 case CSS_VAL_OBLIQUE:
2071                 // FIXME: oblique is the same as italic for the moment...
2072                 case CSS_VAL_ITALIC:
2073                     fontDescription.setItalic(true);
2074                     break;
2075                 case CSS_VAL_NORMAL:
2076                     fontDescription.setItalic(false);
2077                     break;
2078                 default:
2079                     return;
2080             }
2081         }
2082         if (style->setFontDescription(fontDescription))
2083             fontDirty = true;
2084         return;
2085     }
2086
2087     case CSS_PROP_FONT_VARIANT:
2088     {
2089         FontDescription fontDescription = style->fontDescription();
2090         if (isInherit) 
2091             fontDescription.setSmallCaps(parentStyle->fontDescription().smallCaps());
2092         else if (isInitial)
2093             fontDescription.setSmallCaps(false);
2094         else {
2095             if (!primitiveValue) return;
2096             int id = primitiveValue->getIdent();
2097             if (id == CSS_VAL_NORMAL)
2098                 fontDescription.setSmallCaps(false);
2099             else if (id == CSS_VAL_SMALL_CAPS)
2100                 fontDescription.setSmallCaps(true);
2101             else
2102                 return;
2103         }
2104         if (style->setFontDescription(fontDescription))
2105             fontDirty = true;
2106         return;        
2107     }
2108
2109     case CSS_PROP_FONT_WEIGHT:
2110     {
2111         FontDescription fontDescription = style->fontDescription();
2112         if (isInherit)
2113             fontDescription.setWeight(parentStyle->fontDescription().weight());
2114         else if (isInitial)
2115             fontDescription.setWeight(cNormalWeight);
2116         else {
2117             if (!primitiveValue) return;
2118             if (primitiveValue->getIdent()) {
2119                 switch (primitiveValue->getIdent()) {
2120                     // FIXME: We aren't genuinely supporting specific weight values.
2121                     case CSS_VAL_BOLD:
2122                     case CSS_VAL_BOLDER:
2123                     case CSS_VAL_600:
2124                     case CSS_VAL_700:
2125                     case CSS_VAL_800:
2126                     case CSS_VAL_900:
2127                         fontDescription.setWeight(cBoldWeight);
2128                         break;
2129                     case CSS_VAL_NORMAL:
2130                     case CSS_VAL_LIGHTER:
2131                     case CSS_VAL_100:
2132                     case CSS_VAL_200:
2133                     case CSS_VAL_300:
2134                     case CSS_VAL_400:
2135                     case CSS_VAL_500:
2136                         fontDescription.setWeight(cNormalWeight);
2137                         break;
2138                     default:
2139                         return;
2140                 }
2141             }
2142             else
2143             {
2144                 // ### fix parsing of 100-900 values in parser, apply them here
2145             }
2146         }
2147         if (style->setFontDescription(fontDescription))
2148             fontDirty = true;
2149         return;
2150     }
2151         
2152     case CSS_PROP_FONT_STRETCH: {
2153         FontDescription fontDescription = style->fontDescription();
2154         if (isInherit)
2155             fontDescription.setStretch(parentStyle->fontDescription().stretch());
2156         else if (isInitial)
2157             fontDescription.setStretch(FontStretchNormal);
2158         else {
2159             if (!primitiveValue || !primitiveValue->getIdent())
2160                 return;
2161             switch (primitiveValue->getIdent()) {
2162                 case CSS_VAL_WIDER:
2163                     fontDescription.setStretch(fontDescription.widerStretch());
2164                     break;
2165                 case CSS_VAL_NARROWER:
2166                     fontDescription.setStretch(fontDescription.narrowerStretch());
2167                     break;
2168                 case CSS_VAL_NORMAL:
2169                     fontDescription.setStretch(FontStretchNormal);
2170                     break;
2171                 case CSS_VAL_SEMI_EXPANDED:
2172                 case CSS_VAL_EXPANDED:
2173                 case CSS_VAL_EXTRA_EXPANDED:
2174                 case CSS_VAL_ULTRA_EXPANDED:
2175                     fontDescription.setStretch(FontStretchExpanded);
2176                     break;
2177                 case CSS_VAL_ULTRA_CONDENSED:
2178                 case CSS_VAL_EXTRA_CONDENSED:
2179                 case CSS_VAL_CONDENSED:
2180                 case CSS_VAL_SEMI_CONDENSED:
2181                     fontDescription.setStretch(FontStretchCondensed);
2182                     break;
2183                 default:
2184                     return;
2185             }
2186         }
2187         if (style->setFontDescription(fontDescription))
2188             fontDirty = true;
2189         return;
2190     }
2191     
2192     case CSS_PROP_LIST_STYLE_POSITION:
2193     {
2194         HANDLE_INHERIT_AND_INITIAL(listStylePosition, ListStylePosition)
2195         if (!primitiveValue) return;
2196         if (primitiveValue->getIdent())
2197             style->setListStylePosition((EListStylePosition) (primitiveValue->getIdent() - CSS_VAL_OUTSIDE));
2198         return;
2199     }
2200
2201     case CSS_PROP_LIST_STYLE_TYPE:
2202     {
2203         HANDLE_INHERIT_AND_INITIAL(listStyleType, ListStyleType)
2204         if (!primitiveValue) return;
2205         if (primitiveValue->getIdent())
2206         {
2207             EListStyleType t;
2208             int id = primitiveValue->getIdent();
2209             if (id == CSS_VAL_NONE) { // important!!
2210               t = LNONE;
2211             } else {
2212               t = EListStyleType(id - CSS_VAL_DISC);
2213             }
2214             style->setListStyleType(t);
2215         }
2216         return;
2217     }
2218
2219     case CSS_PROP_OVERFLOW:
2220     {
2221         if (isInherit) {
2222             style->setOverflowX(parentStyle->overflowX());
2223             style->setOverflowY(parentStyle->overflowY());
2224             return;
2225         }
2226         
2227         if (isInitial) {
2228             style->setOverflowX(RenderStyle::initialOverflowX());
2229             style->setOverflowY(RenderStyle::initialOverflowY());
2230             return;
2231         }
2232             
2233         EOverflow o;
2234         switch(primitiveValue->getIdent()) {
2235             case CSS_VAL_VISIBLE:
2236                 o = OVISIBLE; break;
2237             case CSS_VAL_HIDDEN:
2238                 o = OHIDDEN; break;
2239             case CSS_VAL_SCROLL:
2240                 o = OSCROLL; break;
2241             case CSS_VAL_AUTO:
2242                 o = OAUTO; break;
2243             case CSS_VAL__WEBKIT_MARQUEE:
2244                 o = OMARQUEE; break;
2245             case CSS_VAL_OVERLAY:
2246                 o = OOVERLAY; break;
2247             default:
2248                 return;
2249         }
2250         style->setOverflowX(o);
2251         style->setOverflowY(o);
2252         return;
2253     }
2254
2255     case CSS_PROP_OVERFLOW_X:
2256     {
2257         HANDLE_INHERIT_AND_INITIAL(overflowX, OverflowX)
2258         EOverflow o;
2259         switch(primitiveValue->getIdent())
2260         {
2261         case CSS_VAL_VISIBLE:
2262             o = OVISIBLE; break;
2263         case CSS_VAL_HIDDEN:
2264             o = OHIDDEN; break;
2265         case CSS_VAL_SCROLL:
2266             o = OSCROLL; break;
2267         case CSS_VAL_AUTO:
2268             o = OAUTO; break;
2269         case CSS_VAL__WEBKIT_MARQUEE:
2270             o = OMARQUEE; break;
2271         case CSS_VAL_OVERLAY:
2272             o = OOVERLAY; break;
2273         default:
2274             return;
2275         }
2276         style->setOverflowX(o);
2277         return;
2278     }
2279
2280     case CSS_PROP_OVERFLOW_Y:
2281     {
2282         HANDLE_INHERIT_AND_INITIAL(overflowY, OverflowY)
2283         EOverflow o;
2284         switch(primitiveValue->getIdent())
2285         {
2286         case CSS_VAL_VISIBLE:
2287             o = OVISIBLE; break;
2288         case CSS_VAL_HIDDEN:
2289             o = OHIDDEN; break;
2290         case CSS_VAL_SCROLL:
2291             o = OSCROLL; break;
2292         case CSS_VAL_AUTO:
2293             o = OAUTO; break;
2294         case CSS_VAL__WEBKIT_MARQUEE:
2295             o = OMARQUEE; break;
2296         case CSS_VAL_OVERLAY:
2297             o = OOVERLAY; break;
2298         default:
2299             return;
2300         }
2301         style->setOverflowY(o);
2302         return;
2303     }
2304
2305     case CSS_PROP_PAGE_BREAK_BEFORE:
2306     {
2307         HANDLE_INHERIT_AND_INITIAL_WITH_VALUE(pageBreakBefore, PageBreakBefore, PageBreak)
2308         if (!primitiveValue) return;
2309         switch (primitiveValue->getIdent()) {
2310             case CSS_VAL_AUTO:
2311                 style->setPageBreakBefore(PBAUTO);
2312                 break;
2313             case CSS_VAL_LEFT:
2314             case CSS_VAL_RIGHT:
2315             case CSS_VAL_ALWAYS:
2316                 style->setPageBreakBefore(PBALWAYS); // CSS2.1: "Conforming user agents may map left/right to always."
2317                 break;
2318             case CSS_VAL_AVOID:
2319                 style->setPageBreakBefore(PBAVOID);
2320                 break;
2321         }
2322         return;
2323     }
2324
2325     case CSS_PROP_PAGE_BREAK_AFTER:
2326     {
2327         HANDLE_INHERIT_AND_INITIAL_WITH_VALUE(pageBreakAfter, PageBreakAfter, PageBreak)
2328         if (!primitiveValue) return;
2329         switch (primitiveValue->getIdent()) {
2330             case CSS_VAL_AUTO:
2331                 style->setPageBreakAfter(PBAUTO);
2332                 break;
2333             case CSS_VAL_LEFT:
2334             case CSS_VAL_RIGHT:
2335             case CSS_VAL_ALWAYS:
2336                 style->setPageBreakAfter(PBALWAYS); // CSS2.1: "Conforming user agents may map left/right to always."
2337                 break;
2338             case CSS_VAL_AVOID:
2339                 style->setPageBreakAfter(PBAVOID);
2340                 break;
2341         }
2342         return;
2343     }
2344
2345     case CSS_PROP_PAGE_BREAK_INSIDE: {
2346         HANDLE_INHERIT_AND_INITIAL_WITH_VALUE(pageBreakInside, PageBreakInside, PageBreak)
2347         if (!primitiveValue) return;
2348         if (primitiveValue->getIdent() == CSS_VAL_AUTO)
2349             style->setPageBreakInside(PBAUTO);
2350         else if (primitiveValue->getIdent() == CSS_VAL_AVOID)
2351             style->setPageBreakInside(PBAVOID);
2352         return;
2353     }
2354         
2355     case CSS_PROP_POSITION:
2356     {
2357         HANDLE_INHERIT_AND_INITIAL(position, Position)
2358         if(!primitiveValue) return;
2359         EPosition p;
2360         switch(primitiveValue->getIdent())
2361         {
2362         case CSS_VAL_STATIC:
2363             p = StaticPosition;
2364             break;
2365         case CSS_VAL_RELATIVE:
2366             p = RelativePosition;
2367             break;
2368         case CSS_VAL_ABSOLUTE:
2369             p = AbsolutePosition;
2370             break;
2371         case CSS_VAL_FIXED:
2372             p = FixedPosition;
2373             break;
2374         default:
2375             return;
2376         }
2377         style->setPosition(p);
2378         return;
2379     }
2380
2381     case CSS_PROP_TABLE_LAYOUT: {
2382         HANDLE_INHERIT_AND_INITIAL(tableLayout, TableLayout)
2383
2384         if (!primitiveValue->getIdent())
2385             return;
2386
2387         ETableLayout l = RenderStyle::initialTableLayout();
2388         switch(primitiveValue->getIdent()) {
2389             case CSS_VAL_FIXED:
2390                 l = TFIXED;
2391                 // fall through
2392             case CSS_VAL_AUTO:
2393                 style->setTableLayout(l);
2394             default:
2395                 break;
2396         }
2397         return;
2398     }
2399         
2400     case CSS_PROP_UNICODE_BIDI: {
2401         HANDLE_INHERIT_AND_INITIAL(unicodeBidi, UnicodeBidi)
2402         switch (primitiveValue->getIdent()) {
2403             case CSS_VAL_NORMAL:
2404                 style->setUnicodeBidi(UBNormal); 
2405                 break;
2406             case CSS_VAL_EMBED:
2407                 style->setUnicodeBidi(Embed); 
2408                 break;
2409             case CSS_VAL_BIDI_OVERRIDE:
2410                 style->setUnicodeBidi(Override);
2411                 break;
2412             default:
2413                 return;
2414         }
2415         return;
2416     }
2417     case CSS_PROP_TEXT_TRANSFORM: {
2418         HANDLE_INHERIT_AND_INITIAL(textTransform, TextTransform)
2419         
2420         if(!primitiveValue->getIdent()) return;
2421
2422         ETextTransform tt;
2423         switch(primitiveValue->getIdent()) {
2424         case CSS_VAL_CAPITALIZE:  tt = CAPITALIZE;  break;
2425         case CSS_VAL_UPPERCASE:   tt = UPPERCASE;   break;
2426         case CSS_VAL_LOWERCASE:   tt = LOWERCASE;   break;
2427         case CSS_VAL_NONE:
2428         default:                  tt = TTNONE;      break;
2429         }
2430         style->setTextTransform(tt);
2431         return;
2432         }
2433
2434     case CSS_PROP_VISIBILITY:
2435     {
2436         HANDLE_INHERIT_AND_INITIAL(visibility, Visibility)
2437
2438         switch(primitiveValue->getIdent()) {
2439         case CSS_VAL_HIDDEN:
2440             style->setVisibility(HIDDEN);
2441             break;
2442         case CSS_VAL_VISIBLE:
2443             style->setVisibility(VISIBLE);
2444             break;
2445         case CSS_VAL_COLLAPSE:
2446             style->setVisibility(COLLAPSE);
2447         default:
2448             break;
2449         }
2450         return;
2451     }
2452     case CSS_PROP_WHITE_SPACE:
2453         HANDLE_INHERIT_AND_INITIAL(whiteSpace, WhiteSpace)
2454
2455         if(!primitiveValue->getIdent()) return;
2456
2457         EWhiteSpace s;
2458         switch(primitiveValue->getIdent()) {
2459         case CSS_VAL__WEBKIT_NOWRAP:
2460             s = KHTML_NOWRAP;
2461             break;
2462         case CSS_VAL_NOWRAP:
2463             s = NOWRAP;
2464             break;
2465         case CSS_VAL_PRE:
2466             s = PRE;
2467             break;
2468         case CSS_VAL_PRE_WRAP:
2469             s = PRE_WRAP;
2470             break;
2471         case CSS_VAL_PRE_LINE:
2472             s = PRE_LINE;
2473             break;
2474         case CSS_VAL_NORMAL:
2475         default:
2476             s = NORMAL;
2477             break;
2478         }
2479         style->setWhiteSpace(s);
2480         return;
2481
2482     case CSS_PROP_BACKGROUND_POSITION:
2483         HANDLE_BACKGROUND_INHERIT_AND_INITIAL(backgroundXPosition, BackgroundXPosition);
2484         HANDLE_BACKGROUND_INHERIT_AND_INITIAL(backgroundYPosition, BackgroundYPosition);
2485         return;
2486     case CSS_PROP_BACKGROUND_POSITION_X: {
2487         HANDLE_BACKGROUND_VALUE(backgroundXPosition, BackgroundXPosition, value)
2488         return;
2489     }
2490     case CSS_PROP_BACKGROUND_POSITION_Y: {
2491         HANDLE_BACKGROUND_VALUE(backgroundYPosition, BackgroundYPosition, value)
2492         return;
2493     }
2494     case CSS_PROP_BORDER_SPACING: {
2495         if (isInherit) {
2496             style->setHorizontalBorderSpacing(parentStyle->horizontalBorderSpacing());
2497             style->setVerticalBorderSpacing(parentStyle->verticalBorderSpacing());
2498         }
2499         else if (isInitial) {
2500             style->setHorizontalBorderSpacing(0);
2501             style->setVerticalBorderSpacing(0);
2502         }
2503         return;
2504     }
2505     case CSS_PROP__WEBKIT_BORDER_HORIZONTAL_SPACING: {
2506         HANDLE_INHERIT_AND_INITIAL(horizontalBorderSpacing, HorizontalBorderSpacing)
2507         if (!primitiveValue) return;
2508         short spacing =  primitiveValue->computeLengthShort(style);
2509         style->setHorizontalBorderSpacing(spacing);
2510         return;
2511     }
2512     case CSS_PROP__WEBKIT_BORDER_VERTICAL_SPACING: {
2513         HANDLE_INHERIT_AND_INITIAL(verticalBorderSpacing, VerticalBorderSpacing)
2514         if (!primitiveValue) return;
2515         short spacing =  primitiveValue->computeLengthShort(style);
2516         style->setVerticalBorderSpacing(spacing);
2517         return;
2518     }
2519     case CSS_PROP_CURSOR:
2520         if (isInherit) {
2521             style->setCursor(parentStyle->cursor());
2522             style->setCursorList(parentStyle->cursors());
2523             return;
2524         }
2525         style->clearCursorList();
2526         if (isInitial) {
2527             style->setCursor(RenderStyle::initialCursor());
2528             return;
2529         }
2530         if (value->isValueList()) {
2531             CSSValueList* list = static_cast<CSSValueList*>(value);
2532             int len = list->length();
2533             style->setCursor(CURSOR_AUTO);
2534             for (int i = 0; i < len; i++) {
2535                 CSSValue* item = list->item(i);
2536                 if (!item->isPrimitiveValue())
2537                     continue;
2538                 primitiveValue = static_cast<CSSPrimitiveValue*>(item);
2539                 int type = primitiveValue->primitiveType();
2540                 if (type == CSSPrimitiveValue::CSS_URI) {
2541 #ifdef SVG_SUPPORT
2542                     if (primitiveValue->getStringValue().find("#") == 0)
2543                         style->addSVGCursor(primitiveValue->getStringValue().substring(1));
2544                     else
2545 #endif
2546                     {
2547                         CSSCursorImageValue* image = static_cast<CSSCursorImageValue*>(primitiveValue);
2548                         style->addCursor(image->image(element->document()->docLoader()), image->hotspot());
2549                     }
2550                 } else if (type == CSSPrimitiveValue::CSS_IDENT) {
2551                     int ident = primitiveValue->getIdent();
2552                     if (ident == CSS_VAL_COPY)
2553                         style->setCursor(CURSOR_COPY);
2554                     else if (ident == CSS_VAL_NONE)
2555                         style->setCursor(CURSOR_NONE);
2556                     else
2557                         style->setCursor((ECursor)(ident - CSS_VAL_AUTO));
2558                 }
2559             }
2560         } else if (primitiveValue) {
2561             int type = primitiveValue->primitiveType();
2562             if (type == CSSPrimitiveValue::CSS_IDENT) {
2563                 int ident = primitiveValue->getIdent();
2564                 if (ident == CSS_VAL_COPY)
2565                     style->setCursor(CURSOR_COPY);
2566                 else if (ident == CSS_VAL_NONE)
2567                     style->setCursor(CURSOR_NONE);
2568                 else
2569                     style->setCursor((ECursor)(ident - CSS_VAL_AUTO));
2570             }
2571         }
2572         return;
2573 // colors || inherit
2574     case CSS_PROP_BACKGROUND_COLOR:
2575     case CSS_PROP_BORDER_TOP_COLOR:
2576     case CSS_PROP_BORDER_RIGHT_COLOR:
2577     case CSS_PROP_BORDER_BOTTOM_COLOR:
2578     case CSS_PROP_BORDER_LEFT_COLOR:
2579     case CSS_PROP_COLOR:
2580     case CSS_PROP_OUTLINE_COLOR:
2581     case CSS_PROP__WEBKIT_COLUMN_RULE_COLOR:
2582     case CSS_PROP__WEBKIT_TEXT_STROKE_COLOR:
2583     case CSS_PROP__WEBKIT_TEXT_FILL_COLOR: {
2584         Color col;
2585         if (isInherit) {
2586             HANDLE_INHERIT_COND(CSS_PROP_BACKGROUND_COLOR, backgroundColor, BackgroundColor)
2587             HANDLE_INHERIT_COND(CSS_PROP_BORDER_TOP_COLOR, borderTopColor, BorderTopColor)
2588             HANDLE_INHERIT_COND(CSS_PROP_BORDER_BOTTOM_COLOR, borderBottomColor, BorderBottomColor)
2589             HANDLE_INHERIT_COND(CSS_PROP_BORDER_RIGHT_COLOR, borderRightColor, BorderRightColor)
2590             HANDLE_INHERIT_COND(CSS_PROP_BORDER_LEFT_COLOR, borderLeftColor, BorderLeftColor)
2591             HANDLE_INHERIT_COND(CSS_PROP_COLOR, color, Color)
2592             HANDLE_INHERIT_COND(CSS_PROP_OUTLINE_COLOR, outlineColor, OutlineColor)
2593             HANDLE_INHERIT_COND(CSS_PROP__WEBKIT_COLUMN_RULE_COLOR, columnRuleColor, ColumnRuleColor)
2594             HANDLE_INHERIT_COND(CSS_PROP__WEBKIT_TEXT_STROKE_COLOR, textStrokeColor, TextStrokeColor)
2595             HANDLE_INHERIT_COND(CSS_PROP__WEBKIT_TEXT_FILL_COLOR, textFillColor, TextFillColor)
2596             return;
2597         }
2598         if (isInitial) {
2599             // The border/outline colors will just map to the invalid color |col| above.  This will have the
2600             // effect of forcing the use of the currentColor when it comes time to draw the borders (and of
2601             // not painting the background since the color won't be valid).
2602             if (id == CSS_PROP_COLOR)
2603                 col = RenderStyle::initialColor();
2604         } else {
2605             if (!primitiveValue)
2606                 return;
2607             col = getColorFromPrimitiveValue(primitiveValue);
2608         }
2609
2610         switch(id) {
2611         case CSS_PROP_BACKGROUND_COLOR:
2612             style->setBackgroundColor(col); break;
2613         case CSS_PROP_BORDER_TOP_COLOR:
2614             style->setBorderTopColor(col); break;
2615         case CSS_PROP_BORDER_RIGHT_COLOR:
2616             style->setBorderRightColor(col); break;
2617         case CSS_PROP_BORDER_BOTTOM_COLOR:
2618             style->setBorderBottomColor(col); break;
2619         case CSS_PROP_BORDER_LEFT_COLOR:
2620             style->setBorderLeftColor(col); break;
2621         case CSS_PROP_COLOR:
2622             style->setColor(col); break;
2623         case CSS_PROP_OUTLINE_COLOR:
2624             style->setOutlineColor(col); break;
2625         case CSS_PROP__WEBKIT_COLUMN_RULE_COLOR:
2626             style->setColumnRuleColor(col);
2627             break;
2628         case CSS_PROP__WEBKIT_TEXT_STROKE_COLOR:
2629             style->setTextStrokeColor(col);
2630             break;
2631         case CSS_PROP__WEBKIT_TEXT_FILL_COLOR:
2632             style->setTextFillColor(col);
2633             break;
2634         }
2635         
2636         return;
2637     }
2638     
2639 // uri || inherit
2640     case CSS_PROP_BACKGROUND_IMAGE:
2641         HANDLE_BACKGROUND_VALUE(backgroundImage, BackgroundImage, value)
2642         return;
2643     case CSS_PROP_LIST_STYLE_IMAGE:
2644     {
2645         HANDLE_INHERIT_AND_INITIAL(listStyleImage, ListStyleImage)
2646         if (!primitiveValue)
2647             return;
2648         style->setListStyleImage(static_cast<CSSImageValue*>(primitiveValue)->image(element->document()->docLoader()));
2649         return;
2650     }
2651
2652 // length
2653     case CSS_PROP_BORDER_TOP_WIDTH:
2654     case CSS_PROP_BORDER_RIGHT_WIDTH:
2655     case CSS_PROP_BORDER_BOTTOM_WIDTH:
2656     case CSS_PROP_BORDER_LEFT_WIDTH:
2657     case CSS_PROP_OUTLINE_WIDTH:
2658     case CSS_PROP__WEBKIT_COLUMN_RULE_WIDTH:
2659     {
2660         if (isInherit) {
2661             HANDLE_INHERIT_COND(CSS_PROP_BORDER_TOP_WIDTH, borderTopWidth, BorderTopWidth)
2662             HANDLE_INHERIT_COND(CSS_PROP_BORDER_RIGHT_WIDTH, borderRightWidth, BorderRightWidth)
2663             HANDLE_INHERIT_COND(CSS_PROP_BORDER_BOTTOM_WIDTH, borderBottomWidth, BorderBottomWidth)
2664             HANDLE_INHERIT_COND(CSS_PROP_BORDER_LEFT_WIDTH, borderLeftWidth, BorderLeftWidth)
2665             HANDLE_INHERIT_COND(CSS_PROP_OUTLINE_WIDTH, outlineWidth, OutlineWidth)
2666             HANDLE_INHERIT_COND(CSS_PROP__WEBKIT_COLUMN_RULE_WIDTH, columnRuleWidth, ColumnRuleWidth)
2667             return;
2668         }
2669         else if (isInitial) {
2670             HANDLE_INITIAL_COND_WITH_VALUE(CSS_PROP_BORDER_TOP_WIDTH, BorderTopWidth, BorderWidth)
2671             HANDLE_INITIAL_COND_WITH_VALUE(CSS_PROP_BORDER_RIGHT_WIDTH, BorderRightWidth, BorderWidth)
2672             HANDLE_INITIAL_COND_WITH_VALUE(CSS_PROP_BORDER_BOTTOM_WIDTH, BorderBottomWidth, BorderWidth)
2673             HANDLE_INITIAL_COND_WITH_VALUE(CSS_PROP_BORDER_LEFT_WIDTH, BorderLeftWidth, BorderWidth)
2674             HANDLE_INITIAL_COND_WITH_VALUE(CSS_PROP_OUTLINE_WIDTH, OutlineWidth, BorderWidth)
2675             HANDLE_INITIAL_COND_WITH_VALUE(CSS_PROP__WEBKIT_COLUMN_RULE_WIDTH, ColumnRuleWidth, BorderWidth)
2676             return;
2677         }
2678
2679         if(!primitiveValue) return;
2680         short width = 3;
2681         switch(primitiveValue->getIdent())
2682         {
2683         case CSS_VAL_THIN:
2684             width = 1;
2685             break;
2686         case CSS_VAL_MEDIUM:
2687             width = 3;
2688             break;
2689         case CSS_VAL_THICK:
2690             width = 5;
2691             break;
2692         case CSS_VAL_INVALID:
2693             width = primitiveValue->computeLengthShort(style);
2694             break;
2695         default:
2696             return;
2697         }
2698
2699         if(width < 0) return;
2700         switch(id)
2701         {
2702         case CSS_PROP_BORDER_TOP_WIDTH:
2703             style->setBorderTopWidth(width);
2704             break;
2705         case CSS_PROP_BORDER_RIGHT_WIDTH:
2706             style->setBorderRightWidth(width);
2707             break;
2708         case CSS_PROP_BORDER_BOTTOM_WIDTH:
2709             style->setBorderBottomWidth(width);
2710             break;
2711         case CSS_PROP_BORDER_LEFT_WIDTH:
2712             style->setBorderLeftWidth(width);
2713             break;
2714         case CSS_PROP_OUTLINE_WIDTH:
2715             style->setOutlineWidth(width);
2716             break;
2717         case CSS_PROP__WEBKIT_COLUMN_RULE_WIDTH:
2718             style->setColumnRuleWidth(width);
2719             break;
2720         default:
2721             return;
2722         }
2723         return;
2724     }
2725
2726     case CSS_PROP_LETTER_SPACING:
2727     case CSS_PROP_WORD_SPACING:
2728     {
2729         
2730         if (isInherit) {
2731             HANDLE_INHERIT_COND(CSS_PROP_LETTER_SPACING, letterSpacing, LetterSpacing)
2732             HANDLE_INHERIT_COND(CSS_PROP_WORD_SPACING, wordSpacing, WordSpacing)
2733             return;
2734         }
2735         else if (isInitial) {
2736             HANDLE_INITIAL_COND_WITH_VALUE(CSS_PROP_LETTER_SPACING, LetterSpacing, LetterWordSpacing)
2737             HANDLE_INITIAL_COND_WITH_VALUE(CSS_PROP_WORD_SPACING, WordSpacing, LetterWordSpacing)
2738             return;
2739         }
2740         
2741         int width = 0;
2742         if (primitiveValue && primitiveValue->getIdent() == CSS_VAL_NORMAL){
2743             width = 0;
2744         } else {
2745             if(!primitiveValue) return;
2746             width = primitiveValue->computeLengthInt(style);
2747         }
2748         switch(id)
2749         {
2750         case CSS_PROP_LETTER_SPACING:
2751             style->setLetterSpacing(width);
2752             break;
2753         case CSS_PROP_WORD_SPACING:
2754             style->setWordSpacing(width);
2755             break;
2756             // ### needs the definitions in renderstyle
2757         default: break;
2758         }
2759         return;
2760     }
2761
2762     case CSS_PROP_WORD_WRAP:
2763     {
2764         HANDLE_INHERIT_AND_INITIAL(wordWrap, WordWrap)
2765
2766         if(!primitiveValue->getIdent()) return;
2767
2768         EWordWrap s;
2769         switch(primitiveValue->getIdent()) {
2770         case CSS_VAL_BREAK_WORD:
2771             s = BREAK_WORD;
2772             break;
2773         case CSS_VAL_NORMAL:
2774         default:
2775             s = WBNORMAL;
2776             break;
2777         }
2778         style->setWordWrap(s);
2779         return;
2780     }
2781
2782     case CSS_PROP__WEBKIT_NBSP_MODE:
2783     {
2784         HANDLE_INHERIT_AND_INITIAL(nbspMode, NBSPMode)
2785
2786         if (!primitiveValue->getIdent()) return;
2787
2788         ENBSPMode m;
2789         switch(primitiveValue->getIdent()) {
2790         case CSS_VAL_SPACE:
2791             m = SPACE;
2792             break;
2793         case CSS_VAL_NORMAL:
2794         default:
2795             m = NBNORMAL;
2796             break;
2797         }
2798         style->setNBSPMode(m);
2799         return;
2800     }
2801
2802     case CSS_PROP__WEBKIT_LINE_BREAK:
2803     {
2804         HANDLE_INHERIT_AND_INITIAL(khtmlLineBreak, KHTMLLineBreak)
2805
2806         if (!primitiveValue->getIdent()) return;
2807
2808         EKHTMLLineBreak b;
2809         switch(primitiveValue->getIdent()) {
2810         case CSS_VAL_AFTER_WHITE_SPACE:
2811             b = AFTER_WHITE_SPACE;
2812             break;
2813         case CSS_VAL_NORMAL:
2814         default:
2815             b = LBNORMAL;
2816             break;
2817         }
2818         style->setKHTMLLineBreak(b);
2819         return;
2820     }
2821
2822     case CSS_PROP__WEBKIT_MATCH_NEAREST_MAIL_BLOCKQUOTE_COLOR:
2823     {
2824         HANDLE_INHERIT_AND_INITIAL(matchNearestMailBlockquoteColor, MatchNearestMailBlockquoteColor)
2825
2826         if (!primitiveValue->getIdent()) return;
2827
2828         EMatchNearestMailBlockquoteColor c;
2829         switch(primitiveValue->getIdent()) {
2830         case CSS_VAL_NORMAL:
2831             c = BCNORMAL;
2832             break;
2833         case CSS_VAL_MATCH:
2834         default:
2835             c = MATCH;
2836             break;
2837         }
2838         style->setMatchNearestMailBlockquoteColor(c);
2839         return;
2840     }
2841
2842     case CSS_PROP_RESIZE:
2843     {
2844         HANDLE_INHERIT_AND_INITIAL(resize, Resize)
2845
2846         if (!primitiveValue->getIdent()) return;
2847
2848         EResize r;
2849         switch(primitiveValue->getIdent()) {
2850         case CSS_VAL_BOTH:
2851             r = RESIZE_BOTH;
2852             break;
2853         case CSS_VAL_HORIZONTAL:
2854             r = RESIZE_HORIZONTAL;
2855             break;
2856         case CSS_VAL_VERTICAL:
2857             r = RESIZE_VERTICAL;
2858             break;
2859         case CSS_VAL_AUTO:
2860             r = settings->textAreasAreResizable() ? RESIZE_BOTH : RESIZE_NONE;
2861             break;
2862         case CSS_VAL_NONE:
2863         default:
2864             r = RESIZE_NONE;
2865             break;
2866         }
2867         style->setResize(r);
2868         return;
2869     }
2870     
2871     // length, percent
2872     case CSS_PROP_MAX_WIDTH:
2873         // +none +inherit
2874         if(primitiveValue && primitiveValue->getIdent() == CSS_VAL_NONE)
2875             apply = true;
2876     case CSS_PROP_TOP:
2877     case CSS_PROP_LEFT:
2878     case CSS_PROP_RIGHT:
2879     case CSS_PROP_BOTTOM:
2880     case CSS_PROP_WIDTH:
2881     case CSS_PROP_MIN_WIDTH:
2882     case CSS_PROP_MARGIN_TOP:
2883     case CSS_PROP_MARGIN_RIGHT:
2884     case CSS_PROP_MARGIN_BOTTOM:
2885     case CSS_PROP_MARGIN_LEFT:
2886         // +inherit +auto
2887         if (id == CSS_PROP_WIDTH || id == CSS_PROP_MIN_WIDTH || id == CSS_PROP_MAX_WIDTH) {
2888             if (primitiveValue && primitiveValue->getIdent() == CSS_VAL_INTRINSIC) {
2889                 l = Length(Intrinsic);
2890                 apply = true;
2891             }
2892             else if (primitiveValue && primitiveValue->getIdent() == CSS_VAL_MIN_INTRINSIC) {
2893                 l = Length(MinIntrinsic);
2894                 apply = true;
2895             }
2896         }
2897         if (id != CSS_PROP_MAX_WIDTH && primitiveValue && primitiveValue->getIdent() == CSS_VAL_AUTO)
2898             apply = true;
2899     case CSS_PROP_PADDING_TOP:
2900     case CSS_PROP_PADDING_RIGHT:
2901     case CSS_PROP_PADDING_BOTTOM:
2902     case CSS_PROP_PADDING_LEFT:
2903     case CSS_PROP_TEXT_INDENT:
2904         // +inherit
2905     {
2906         if (isInherit) {
2907             HANDLE_INHERIT_COND(CSS_PROP_MAX_WIDTH, maxWidth, MaxWidth)
2908             HANDLE_INHERIT_COND(CSS_PROP_BOTTOM, bottom, Bottom)
2909             HANDLE_INHERIT_COND(CSS_PROP_TOP, top, Top)
2910             HANDLE_INHERIT_COND(CSS_PROP_LEFT, left, Left)
2911             HANDLE_INHERIT_COND(CSS_PROP_RIGHT, right, Right)
2912             HANDLE_INHERIT_COND(CSS_PROP_WIDTH, width, Width)
2913             HANDLE_INHERIT_COND(CSS_PROP_MIN_WIDTH, minWidth, MinWidth)
2914             HANDLE_INHERIT_COND(CSS_PROP_PADDING_TOP, paddingTop, PaddingTop)
2915             HANDLE_INHERIT_COND(CSS_PROP_PADDING_RIGHT, paddingRight, PaddingRight)
2916             HANDLE_INHERIT_COND(CSS_PROP_PADDING_BOTTOM, paddingBottom, PaddingBottom)
2917             HANDLE_INHERIT_COND(CSS_PROP_PADDING_LEFT, paddingLeft, PaddingLeft)
2918             HANDLE_INHERIT_COND(CSS_PROP_MARGIN_TOP, marginTop, MarginTop)
2919             HANDLE_INHERIT_COND(CSS_PROP_MARGIN_RIGHT, marginRight, MarginRight)
2920             HANDLE_INHERIT_COND(CSS_PROP_MARGIN_BOTTOM, marginBottom, MarginBottom)
2921             HANDLE_INHERIT_COND(CSS_PROP_MARGIN_LEFT, marginLeft, MarginLeft)
2922             HANDLE_INHERIT_COND(CSS_PROP_TEXT_INDENT, textIndent, TextIndent)
2923             return;
2924         }
2925         else if (isInitial) {
2926             HANDLE_INITIAL_COND_WITH_VALUE(CSS_PROP_MAX_WIDTH, MaxWidth, MaxSize)
2927             HANDLE_INITIAL_COND_WITH_VALUE(CSS_PROP_BOTTOM, Bottom, Offset)
2928             HANDLE_INITIAL_COND_WITH_VALUE(CSS_PROP_TOP, Top, Offset)
2929             HANDLE_INITIAL_COND_WITH_VALUE(CSS_PROP_LEFT, Left, Offset)
2930             HANDLE_INITIAL_COND_WITH_VALUE(CSS_PROP_RIGHT, Right, Offset)
2931             HANDLE_INITIAL_COND_WITH_VALUE(CSS_PROP_WIDTH, Width, Size)
2932             HANDLE_INITIAL_COND_WITH_VALUE(CSS_PROP_MIN_WIDTH, MinWidth, MinSize)
2933             HANDLE_INITIAL_COND_WITH_VALUE(CSS_PROP_PADDING_TOP, PaddingTop, Padding)
2934             HANDLE_INITIAL_COND_WITH_VALUE(CSS_PROP_PADDING_RIGHT, PaddingRight, Padding)
2935             HANDLE_INITIAL_COND_WITH_VALUE(CSS_PROP_PADDING_BOTTOM, PaddingBottom, Padding)
2936             HANDLE_INITIAL_COND_WITH_VALUE(CSS_PROP_PADDING_LEFT, PaddingLeft, Padding)
2937             HANDLE_INITIAL_COND_WITH_VALUE(CSS_PROP_MARGIN_TOP, MarginTop, Margin)
2938             HANDLE_INITIAL_COND_WITH_VALUE(CSS_PROP_MARGIN_RIGHT, MarginRight, Margin)
2939             HANDLE_INITIAL_COND_WITH_VALUE(CSS_PROP_MARGIN_BOTTOM, MarginBottom, Margin)
2940             HANDLE_INITIAL_COND_WITH_VALUE(CSS_PROP_MARGIN_LEFT, MarginLeft, Margin)
2941             HANDLE_INITIAL_COND(CSS_PROP_TEXT_INDENT, TextIndent)
2942             return;
2943         } 
2944
2945         if (primitiveValue && !apply) {
2946             int type = primitiveValue->primitiveType();
2947             if(type > CSSPrimitiveValue::CSS_PERCENTAGE && type < CSSPrimitiveValue::CSS_DEG)
2948                 // Handle our quirky margin units if we have them.
2949                 l = Length(primitiveValue->computeLengthIntForLength(style), Fixed, 
2950                            primitiveValue->isQuirkValue());
2951             else if(type == CSSPrimitiveValue::CSS_PERCENTAGE)
2952                 l = Length(primitiveValue->getFloatValue(), Percent);
2953             else
2954                 return;
2955             if (id == CSS_PROP_PADDING_LEFT || id == CSS_PROP_PADDING_RIGHT ||
2956                 id == CSS_PROP_PADDING_TOP || id == CSS_PROP_PADDING_BOTTOM)
2957                 // Padding can't be negative
2958                 apply = !((l.isFixed() || l.isPercent()) && l.calcValue(100) < 0);
2959             else
2960                 apply = true;
2961         }
2962         if(!apply) return;
2963         switch(id)
2964             {
2965             case CSS_PROP_MAX_WIDTH:
2966                 style->setMaxWidth(l); break;
2967             case CSS_PROP_BOTTOM:
2968                 style->setBottom(l); break;
2969             case CSS_PROP_TOP:
2970                 style->setTop(l); break;
2971             case CSS_PROP_LEFT:
2972                 style->setLeft(l); break;
2973             case CSS_PROP_RIGHT:
2974                 style->setRight(l); break;
2975             case CSS_PROP_WIDTH:
2976                 style->setWidth(l); break;
2977             case CSS_PROP_MIN_WIDTH:
2978                 style->setMinWidth(l); break;
2979             case CSS_PROP_PADDING_TOP:
2980                 style->setPaddingTop(l); break;
2981             case CSS_PROP_PADDING_RIGHT:
2982                 style->setPaddingRight(l); break;
2983             case CSS_PROP_PADDING_BOTTOM:
2984                 style->setPaddingBottom(l); break;
2985             case CSS_PROP_PADDING_LEFT:
2986                 style->setPaddingLeft(l); break;
2987             case CSS_PROP_MARGIN_TOP:
2988                 style->setMarginTop(l); break;
2989             case CSS_PROP_MARGIN_RIGHT:
2990                 style->setMarginRight(l); break;
2991             case CSS_PROP_MARGIN_BOTTOM:
2992                 style->setMarginBottom(l); break;
2993             case CSS_PROP_MARGIN_LEFT:
2994                 style->setMarginLeft(l); break;
2995             case CSS_PROP_TEXT_INDENT:
2996                 style->setTextIndent(l); break;
2997             default: break;
2998             }
2999         return;
3000     }
3001
3002     case CSS_PROP_MAX_HEIGHT:
3003         if (primitiveValue && primitiveValue->getIdent() == CSS_VAL_NONE) {
3004             l = Length(undefinedLength, Fixed);
3005             apply = true;
3006         }
3007     case CSS_PROP_HEIGHT:
3008     case CSS_PROP_MIN_HEIGHT:
3009         if (primitiveValue && primitiveValue->getIdent() == CSS_VAL_INTRINSIC) {
3010             l = Length(Intrinsic);
3011             apply = true;
3012         } else if (primitiveValue && primitiveValue->getIdent() == CSS_VAL_MIN_INTRINSIC) {
3013             l = Length(MinIntrinsic);
3014             apply = true;
3015         } else if (id != CSS_PROP_MAX_HEIGHT && primitiveValue && primitiveValue->getIdent() == CSS_VAL_AUTO)
3016             apply = true;
3017         if (isInherit) {
3018             HANDLE_INHERIT_COND(CSS_PROP_MAX_HEIGHT, maxHeight, MaxHeight)
3019             HANDLE_INHERIT_COND(CSS_PROP_HEIGHT, height, Height)
3020             HANDLE_INHERIT_COND(CSS_PROP_MIN_HEIGHT, minHeight, MinHeight)
3021             return;
3022         }
3023         if (isInitial) {
3024             HANDLE_INITIAL_COND_WITH_VALUE(CSS_PROP_MAX_HEIGHT, MaxHeight, MaxSize)
3025             HANDLE_INITIAL_COND_WITH_VALUE(CSS_PROP_HEIGHT, Height, Size)
3026             HANDLE_INITIAL_COND_WITH_VALUE(CSS_PROP_MIN_HEIGHT, MinHeight, MinSize)
3027             return;
3028         }
3029
3030         if (primitiveValue && !apply) {
3031             unsigned short type = primitiveValue->primitiveType();
3032             if (type > CSSPrimitiveValue::CSS_PERCENTAGE && type < CSSPrimitiveValue::CSS_DEG)
3033                 l = Length(primitiveValue->computeLengthIntForLength(style), Fixed);
3034             else if (type == CSSPrimitiveValue::CSS_PERCENTAGE)
3035                 l = Length(primitiveValue->getFloatValue(), Percent);
3036             else
3037                 return;
3038             apply = true;
3039         }
3040         if (apply)
3041             switch (id) {
3042                 case CSS_PROP_MAX_HEIGHT:
3043                     style->setMaxHeight(l);
3044                     break;
3045                 case CSS_PROP_HEIGHT:
3046                     style->setHeight(l);
3047                     break;
3048                 case CSS_PROP_MIN_HEIGHT:
3049                     style->setMinHeight(l);
3050                     break;
3051             }
3052         return;
3053
3054     case CSS_PROP_VERTICAL_ALIGN:
3055         HANDLE_INHERIT_AND_INITIAL(verticalAlign, VerticalAlign)
3056         if (!primitiveValue) return;
3057         if (primitiveValue->getIdent()) {
3058           EVerticalAlign align;
3059
3060           switch(primitiveValue->getIdent())
3061             {
3062                 case CSS_VAL_TOP:
3063                     align = TOP; break;
3064                 case CSS_VAL_BOTTOM:
3065                     align = BOTTOM; break;
3066                 case CSS_VAL_MIDDLE:
3067                     align = MIDDLE; break;
3068                 case CSS_VAL_BASELINE:
3069                     align = BASELINE; break;
3070                 case CSS_VAL_TEXT_BOTTOM:
3071                     align = TEXT_BOTTOM; break;
3072                 case CSS_VAL_TEXT_TOP:
3073                     align = TEXT_TOP; break;
3074                 case CSS_VAL_SUB:
3075                     align = SUB; break;
3076                 case CSS_VAL_SUPER:
3077                     align = SUPER; break;
3078                 case CSS_VAL__WEBKIT_BASELINE_MIDDLE:
3079                     align = BASELINE_MIDDLE; break;
3080                 default:
3081                     return;
3082             }
3083           style->setVerticalAlign(align);
3084           return;
3085         } else {
3086           int type = primitiveValue->primitiveType();
3087           Length l;
3088           if(type > CSSPrimitiveValue::CSS_PERCENTAGE && type < CSSPrimitiveValue::CSS_DEG)
3089             l = Length(primitiveValue->computeLengthIntForLength(style), Fixed);
3090           else if(type == CSSPrimitiveValue::CSS_PERCENTAGE)
3091             l = Length(primitiveValue->getFloatValue(), Percent);
3092
3093           style->setVerticalAlign(LENGTH);
3094           style->setVerticalAlignLength(l);
3095         }
3096         return;
3097
3098     case CSS_PROP_FONT_SIZE:
3099     {
3100         FontDescription fontDescription = style->fontDescription();
3101         fontDescription.setKeywordSize(0);
3102         bool familyIsFixed = fontDescription.genericFamily() == FontDescription::MonospaceFamily;
3103         float oldSize = 0;
3104         float size = 0;
3105         
3106         bool parentIsAbsoluteSize = false;
3107         if (parentNode) {
3108             oldSize = parentStyle->fontDescription().specifiedSize();
3109             parentIsAbsoluteSize = parentStyle->fontDescription().isAbsoluteSize();
3110         }
3111
3112         if (isInherit) {
3113             size = oldSize;
3114             if (parentNode)
3115                 fontDescription.setKeywordSize(parentStyle->fontDescription().keywordSize());
3116         } else if (isInitial) {
3117             size = fontSizeForKeyword(CSS_VAL_MEDIUM, style->htmlHacks(), familyIsFixed);
3118             fontDescription.setKeywordSize(CSS_VAL_MEDIUM - CSS_VAL_XX_SMALL + 1);
3119         } else if (primitiveValue->getIdent()) {
3120             // Keywords are being used.
3121             switch (primitiveValue->getIdent()) {
3122                 case CSS_VAL_XX_SMALL:
3123                 case CSS_VAL_X_SMALL:
3124                 case CSS_VAL_SMALL:
3125                 case CSS_VAL_MEDIUM:
3126                 case CSS_VAL_LARGE:
3127                 case CSS_VAL_X_LARGE:
3128                 case CSS_VAL_XX_LARGE:
3129                 case CSS_VAL__WEBKIT_XXX_LARGE:
3130                     size = fontSizeForKeyword(primitiveValue->getIdent(), style->htmlHacks(), familyIsFixed);
3131                     fontDescription.setKeywordSize(primitiveValue->getIdent() - CSS_VAL_XX_SMALL + 1);
3132                     break;
3133                 case CSS_VAL_LARGER:
3134                     size = largerFontSize(oldSize, style->htmlHacks());
3135                     break;
3136                 case CSS_VAL_SMALLER:
3137                     size = smallerFontSize(oldSize, style->htmlHacks());
3138                     break;
3139                 default:
3140                     return;
3141             }
3142
3143             fontDescription.setIsAbsoluteSize(parentIsAbsoluteSize && 
3144                                               (primitiveValue->getIdent() == CSS_VAL_LARGER ||
3145                                                primitiveValue->getIdent() == CSS_VAL_SMALLER));
3146         } else {
3147             int type = primitiveValue->primitiveType();
3148             fontDescription.setIsAbsoluteSize(parentIsAbsoluteSize ||
3149                                               (type != CSSPrimitiveValue::CSS_PERCENTAGE &&
3150                                                type != CSSPrimitiveValue::CSS_EMS && 
3151                                                type != CSSPrimitiveValue::CSS_EXS));
3152             if (type > CSSPrimitiveValue::CSS_PERCENTAGE && type < CSSPrimitiveValue::CSS_DEG)
3153                 size = primitiveValue->computeLengthFloat(parentStyle, false);
3154             else if(type == CSSPrimitiveValue::CSS_PERCENTAGE)
3155                 size = (primitiveValue->getFloatValue() * oldSize) / 100;
3156             else
3157                 return;
3158         }
3159
3160         if (size < 0)
3161             return;
3162
3163         setFontSize(fontDescription, size);
3164         if (style->setFontDescription(fontDescription))
3165             fontDirty = true;
3166         return;
3167     }
3168
3169     case CSS_PROP_Z_INDEX: {
3170         if (isInherit) {
3171             if (parentStyle->hasAutoZIndex())
3172                 style->setHasAutoZIndex();
3173             else
3174                 style->setZIndex(parentStyle->zIndex());
3175             return;
3176         } else if (isInitial || primitiveValue->getIdent() == CSS_VAL_AUTO) {
3177             style->setHasAutoZIndex();
3178             return;
3179         }
3180         style->setZIndex((int)primitiveValue->getFloatValue());
3181         return;
3182     }
3183     case CSS_PROP_WIDOWS:
3184     {
3185         HANDLE_INHERIT_AND_INITIAL(widows, Widows)
3186         if (!primitiveValue || primitiveValue->primitiveType() != CSSPrimitiveValue::CSS_NUMBER)
3187             return;
3188         style->setWidows((int)primitiveValue->getFloatValue());
3189         return;
3190     }
3191         
3192     case CSS_PROP_ORPHANS:
3193     {
3194         HANDLE_INHERIT_AND_INITIAL(orphans, Orphans)
3195         if (!primitiveValue || primitiveValue->primitiveType() != CSSPrimitiveValue::CSS_NUMBER)
3196             return;
3197         style->setOrphans((int)primitiveValue->getFloatValue());
3198         return;
3199     }        
3200
3201 // length, percent, number
3202     case CSS_PROP_LINE_HEIGHT:
3203     {
3204         HANDLE_INHERIT_AND_INITIAL(lineHeight, LineHeight)
3205         if(!primitiveValue) return;
3206         Length lineHeight;
3207         int type = primitiveValue->primitiveType();
3208         if (primitiveValue->getIdent() == CSS_VAL_NORMAL)
3209             lineHeight = Length(-100.0, Percent);
3210         else if (type > CSSPrimitiveValue::CSS_PERCENTAGE && type < CSSPrimitiveValue::CSS_DEG) {
3211             double multiplier = 1.0;
3212             // Scale for the font zoom factor only for types other than "em" and "ex", since those are
3213             // already based on the font size.
3214             if (type != CSSPrimitiveValue::CSS_EMS && type != CSSPrimitiveValue::CSS_EXS && view && view->frame()) {
3215                 multiplier = view->frame()->zoomFactor() / 100.0;
3216             }
3217             lineHeight = Length(primitiveValue->computeLengthIntForLength(style, multiplier), Fixed);
3218         } else if (type == CSSPrimitiveValue::CSS_PERCENTAGE)
3219             lineHeight = Length((style->fontSize() * int(primitiveValue->getFloatValue())) / 100, Fixed);
3220         else if (type == CSSPrimitiveValue::CSS_NUMBER)
3221             lineHeight = Length(primitiveValue->getFloatValue() * 100.0, Percent);
3222         else
3223             return;
3224         style->setLineHeight(lineHeight);
3225         return;
3226     }
3227
3228 // string
3229     case CSS_PROP_TEXT_ALIGN:
3230     {
3231         HANDLE_INHERIT_AND_INITIAL(textAlign, TextAlign)
3232         if (!primitiveValue) return;
3233         if (primitiveValue->getIdent())
3234             style->setTextAlign((ETextAlign) (primitiveValue->getIdent() - CSS_VAL__WEBKIT_AUTO));
3235         return;
3236     }
3237
3238 // rect
3239     case CSS_PROP_CLIP:
3240     {
3241         Length top;
3242         Length right;
3243         Length bottom;
3244         Length left;
3245         bool hasClip = true;
3246         if (isInherit) {
3247             if (parentStyle->hasClip()) {
3248                 top = parentStyle->clipTop();
3249                 right = parentStyle->clipRight();
3250                 bottom = parentStyle->clipBottom();
3251                 left = parentStyle->clipLeft();
3252             }
3253             else {
3254                 hasClip = false;
3255                 top = right = bottom = left = Length();
3256             }
3257         } else if (isInitial) {
3258             hasClip = false;
3259             top = right = bottom = left = Length();
3260         } else if (!primitiveValue) {
3261             return;
3262         } else if (primitiveValue->primitiveType() == CSSPrimitiveValue::CSS_RECT) {
3263             RectImpl* rect = primitiveValue->getRectValue();
3264             if (!rect)
3265                 return;
3266             top = convertToLength(rect->top(), style);
3267             right = convertToLength(rect->right(), style);
3268             bottom = convertToLength(rect->bottom(), style);
3269             left = convertToLength(rect->left(), style);
3270
3271         } else if (primitiveValue->getIdent() != CSS_VAL_AUTO) {
3272             return;
3273         }
3274         style->setClip(top, right, bottom, left);
3275         style->setHasClip(hasClip);
3276     
3277         // rect, ident
3278         return;
3279     }
3280
3281 // lists
3282     case CSS_PROP_CONTENT:
3283         // list of string, uri, counter, attr, i
3284     {
3285         // FIXME: In CSS3, it will be possible to inherit content.  In CSS2 it is not.  This
3286         // note is a reminder that eventually "inherit" needs to be supported.
3287
3288         if (isInitial) {
3289             style->clearContent();
3290             return;
3291         }
3292         
3293         if (!value->isValueList())
3294             return;
3295
3296         CSSValueList* list = static_cast<CSSValueList*>(value);
3297         int len = list->length();
3298
3299         bool didSet = false;
3300         for (int i = 0; i < len; i++) {
3301             CSSValue* item = list->item(i);
3302             if (!item->isPrimitiveValue())
3303                 continue;
3304             
3305             CSSPrimitiveValue* val = static_cast<CSSPrimitiveValue*>(item);
3306             switch (val->primitiveType()) {
3307                 case CSSPrimitiveValue::CSS_STRING:
3308                     style->setContent(val->getStringValue().impl(), didSet);
3309                     didSet = true;
3310                     break;
3311                 case CSSPrimitiveValue::CSS_ATTR: {
3312                     // FIXME: Can a namespace be specified for an attr(foo)?
3313                     if (style->styleType() == RenderStyle::NOPSEUDO)
3314                         style->setUnique();
3315                     else
3316                         parentStyle->setUnique();
3317                     QualifiedName attr(nullAtom, val->getStringValue().impl(), nullAtom);
3318                     style->setContent(element->getAttribute(attr).impl(), didSet);
3319                     didSet = true;
3320                     // register the fact that the attribute value affects the style
3321                     m_selectorAttrs.add(attr.localName().impl());
3322                     break;
3323                 }
3324                 case CSSPrimitiveValue::CSS_URI: {
3325                     CSSImageValue *image = static_cast<CSSImageValue*>(val);
3326                     style->setContent(image->image(element->document()->docLoader()), didSet);
3327                     didSet = true;
3328                     break;
3329                 }
3330                 case CSSPrimitiveValue::CSS_COUNTER: {
3331                     Counter* counterValue = val->getCounterValue();
3332                     CounterContent* counter = new CounterContent(counterValue->identifier(),
3333                         (EListStyleType)counterValue->listStyleNumber(), counterValue->separator());
3334                     style->setContent(counter, didSet);
3335                     didSet = true;
3336                 }
3337             }
3338         }
3339         if (!didSet)
3340             style->clearContent();
3341         return;
3342     }
3343
3344     case CSS_PROP_COUNTER_INCREMENT:
3345         applyCounterList(style, value->isValueList() ? static_cast<CSSValueList*>(value) : 0, false);
3346         return;
3347     case CSS_PROP_COUNTER_RESET:
3348         applyCounterList(style, value->isValueList() ? static_cast<CSSValueList*>(value) : 0, true);
3349         return;
3350
3351     case CSS_PROP_FONT_FAMILY: {
3352         // list of strings and ids
3353         if (isInherit) {
3354             FontDescription parentFontDescription = parentStyle->fontDescription();
3355             FontDescription fontDescription = style->fontDescription();
3356             fontDescription.setGenericFamily(parentFontDescription.genericFamily());
3357             fontDescription.setFamily(parentFontDescription.firstFamily());
3358             if (style->setFontDescription(fontDescription))
3359                 fontDirty = true;
3360             return;
3361         }
3362         else if (isInitial) {
3363             FontDescription initialDesc = FontDescription();
3364             FontDescription fontDescription = style->fontDescription();
3365             // We need to adjust the size to account for the generic family change from monospace
3366             // to non-monospace.
3367             if (fontDescription.keywordSize() && fontDescription.genericFamily() == FontDescription::MonospaceFamily)
3368                 setFontSize(fontDescription, fontSizeForKeyword(CSS_VAL_XX_SMALL + fontDescription.keywordSize() - 1, style->htmlHacks(), false));
3369             fontDescription.setGenericFamily(initialDesc.genericFamily());
3370             fontDescription.setFamily(initialDesc.firstFamily());
3371             if (style->setFontDescription(fontDescription))
3372                 fontDirty = true;
3373             return;
3374         }
3375         
3376         if (!value->isValueList()) return;
3377         FontDescription fontDescription = style->fontDescription();
3378         CSSValueList *list = static_cast<CSSValueList*>(value);
3379         int len = list->length();
3380         FontFamily& firstFamily = fontDescription.firstFamily();
3381         FontFamily *currFamily = 0;
3382         
3383         // Before mapping in a new font-family property, we should reset the generic family.
3384         bool oldFamilyIsMonospace = fontDescription.genericFamily() == FontDescription::MonospaceFamily;
3385         fontDescription.setGenericFamily(FontDescription::NoFamily);
3386
3387         for(int i = 0; i < len; i++) {
3388             CSSValue *item = list->item(i);
3389             if(!item->isPrimitiveValue()) continue;
3390             CSSPrimitiveValue *val = static_cast<CSSPrimitiveValue*>(item);
3391             AtomicString face;
3392             if(val->primitiveType() == CSSPrimitiveValue::CSS_STRING)
3393                 face = static_cast<FontFamilyValue*>(val)->fontName();
3394             else if (val->primitiveType() == CSSPrimitiveValue::CSS_IDENT) {
3395                 switch (val->getIdent()) {
3396                     case CSS_VAL__WEBKIT_BODY:
3397                         face = settings->standardFontFamily();
3398                         break;
3399                     case CSS_VAL_SERIF:
3400                         face = settings->serifFontFamily();
3401                         fontDescription.setGenericFamily(FontDescription::SerifFamily);
3402                         break;
3403                     case CSS_VAL_SANS_SERIF:
3404                         face = settings->sansSerifFontFamily();
3405                         fontDescription.setGenericFamily(FontDescription::SansSerifFamily);
3406                         break;
3407                     case CSS_VAL_CURSIVE:
3408                         face = settings->cursiveFontFamily();
3409                         fontDescription.setGenericFamily(FontDescription::CursiveFamily);
3410                         break;
3411                     case CSS_VAL_FANTASY:
3412                         face = settings->fantasyFontFamily();
3413                         fontDescription.setGenericFamily(FontDescription::FantasyFamily);
3414                         break;
3415                     case CSS_VAL_MONOSPACE:
3416                         face = settings->fixedFontFamily();
3417                         fontDescription.setGenericFamily(FontDescription::MonospaceFamily);
3418                         break;
3419                 }
3420             }
3421     
3422             if (!face.isEmpty()) {
3423                 if (!currFamily) {
3424                     // Filling in the first family.
3425                     firstFamily.setFamily(face);
3426                     currFamily = &firstFamily;
3427                 }
3428                 else {
3429                     FontFamily *newFamily = new FontFamily;
3430                     newFamily->setFamily(face);
3431                     currFamily->appendFamily(newFamily);
3432                     currFamily = newFamily;
3433                 }
3434     
3435                 if (fontDescription.keywordSize() && (fontDescription.genericFamily() == FontDescription::MonospaceFamily) != oldFamilyIsMonospace)
3436                     setFontSize(fontDescription, fontSizeForKeyword(CSS_VAL_XX_SMALL + fontDescription.keywordSize() - 1, style->htmlHacks(), !oldFamilyIsMonospace));
3437             
3438                 if (style->setFontDescription(fontDescription))
3439                     fontDirty = true;
3440             }
3441         }
3442       return;
3443     }
3444     case CSS_PROP_TEXT_DECORATION: {
3445         // list of ident
3446         HANDLE_INHERIT_AND_INITIAL(textDecoration, TextDecoration)
3447         int t = RenderStyle::initialTextDecoration();
3448         if(primitiveValue && primitiveValue->getIdent() == CSS_VAL_NONE) {
3449             // do nothing
3450         } else {
3451             if(!value->isValueList()) return;
3452             CSSValueList *list = static_cast<CSSValueList*>(value);
3453             int len = list->length();
3454             for(int i = 0; i < len; i++)
3455             {
3456                 CSSValue *item = list->item(i);
3457                 if(!item->isPrimitiveValue()) continue;
3458                 primitiveValue = static_cast<CSSPrimitiveValue*>(item);
3459                 switch(primitiveValue->getIdent())
3460                 {
3461                     case CSS_VAL_NONE:
3462                         t = TDNONE; break;
3463                     case CSS_VAL_UNDERLINE:
3464                         t |= UNDERLINE; break;
3465                     case CSS_VAL_OVERLINE:
3466                         t |= OVERLINE; break;
3467                     case CSS_VAL_LINE_THROUGH:
3468                         t |= LINE_THROUGH; break;
3469                     case CSS_VAL_BLINK:
3470                         t |= BLINK; break;
3471                     default:
3472                         return;
3473                 }
3474             }
3475         }
3476
3477         style->setTextDecoration(t);
3478         return;
3479     }
3480
3481 // shorthand properties
3482     case CSS_PROP_BACKGROUND:
3483         if (isInitial) {
3484             style->clearBackgroundLayers();
3485             style->setBackgroundColor(Color());
3486             return;
3487         }
3488         else if (isInherit) {
3489             style->inheritBackgroundLayers(*parentStyle->backgroundLayers());
3490             style->setBackgroundColor(parentStyle->backgroundColor());
3491         }
3492         return;
3493     case CSS_PROP_BORDER:
3494     case CSS_PROP_BORDER_STYLE:
3495     case CSS_PROP_BORDER_WIDTH:
3496     case CSS_PROP_BORDER_COLOR:
3497         if (id == CSS_PROP_BORDER || id == CSS_PROP_BORDER_COLOR)
3498         {
3499             if (isInherit) {
3500                 style->setBorderTopColor(parentStyle->borderTopColor());
3501                 style->setBorderBottomColor(parentStyle->borderBottomColor());
3502                 style->setBorderLeftColor(parentStyle->borderLeftColor());
3503                 style->setBorderRightColor(parentStyle->borderRightColor());
3504             }
3505             else if (isInitial) {
3506                 style->setBorderTopColor(Color()); // Reset to invalid color so currentColor is used instead.
3507                 style->setBorderBottomColor(Color());
3508                 style->setBorderLeftColor(Color());
3509                 style->setBorderRightColor(Color());
3510             }
3511         }
3512         if (id == CSS_PROP_BORDER || id == CSS_PROP_BORDER_STYLE)
3513         {
3514             if (isInherit) {
3515                 style->setBorderTopStyle(parentStyle->borderTopStyle());
3516                 style->setBorderBottomStyle(parentStyle->borderBottomStyle());
3517                 style->setBorderLeftStyle(parentStyle->borderLeftStyle());
3518                 style->setBorderRightStyle(parentStyle->borderRightStyle());
3519             }
3520             else if (isInitial) {
3521                 style->setBorderTopStyle(RenderStyle::initialBorderStyle());
3522                 style->setBorderBottomStyle(RenderStyle::initialBorderStyle());
3523                 style->setBorderLeftStyle(RenderStyle::initialBorderStyle());
3524                 style->setBorderRightStyle(RenderStyle::initialBorderStyle());
3525             }
3526         }
3527         if (id == CSS_PROP_BORDER || id == CSS_PROP_BORDER_WIDTH)
3528         {
3529             if (isInherit) {
3530                 style->setBorderTopWidth(parentStyle->borderTopWidth());
3531                 style->setBorderBottomWidth(parentStyle->borderBottomWidth());
3532                 style->setBorderLeftWidth(parentStyle->borderLeftWidth());
3533                 style->setBorderRightWidth(parentStyle->borderRightWidth());
3534             }
3535             else if (isInitial) {
3536                 style->setBorderTopWidth(RenderStyle::initialBorderWidth());
3537                 style->setBorderBottomWidth(RenderStyle::initialBorderWidth());
3538                 style->setBorderLeftWidth(RenderStyle::initialBorderWidth());
3539                 style->setBorderRightWidth(RenderStyle::initialBorderWidth());
3540             }
3541         }
3542         return;
3543     case CSS_PROP_BORDER_TOP:
3544         if (isInherit) {
3545             style->setBorderTopColor(parentStyle->borderTopColor());
3546             style->setBorderTopStyle(parentStyle->borderTopStyle());
3547             style->setBorderTopWidth(parentStyle->borderTopWidth());
3548         }
3549         else if (isInitial)
3550             style->resetBorderTop();
3551         return;
3552     case CSS_PROP_BORDER_RIGHT:
3553         if (isInherit) {
3554             style->setBorderRightColor(parentStyle->borderRightColor());
3555             style->setBorderRightStyle(parentStyle->borderRightStyle());
3556             style->setBorderRightWidth(parentStyle->borderRightWidth());
3557         }
3558         else if (isInitial)
3559             style->resetBorderRight();
3560         return;
3561     case CSS_PROP_BORDER_BOTTOM:
3562         if (isInherit) {
3563             style->setBorderBottomColor(parentStyle->borderBottomColor());
3564             style->setBorderBottomStyle(parentStyle->borderBottomStyle());
3565             style->setBorderBottomWidth(parentStyle->borderBottomWidth());
3566         }
3567         else if (isInitial)
3568             style->resetBorderBottom();
3569         return;
3570     case CSS_PROP_BORDER_LEFT:
3571         if (isInherit) {
3572             style->setBorderLeftColor(parentStyle->borderLeftColor());
3573             style->setBorderLeftStyle(parentStyle->borderLeftStyle());
3574             style->setBorderLeftWidth(parentStyle->borderLeftWidth());
3575         }
3576         else if (isInitial)
3577             style->resetBorderLeft();
3578         return;
3579     case CSS_PROP_MARGIN:
3580         if (isInherit) {
3581             style->setMarginTop(parentStyle->marginTop());
3582             style->setMarginBottom(parentStyle->marginBottom());
3583             style->setMarginLeft(parentStyle->marginLeft());
3584             style->setMarginRight(parentStyle->marginRight());
3585         }
3586         else if (isInitial)
3587             style->resetMargin();
3588         return;
3589     case CSS_PROP_PADDING:
3590         if (isInherit) {
3591             style->setPaddingTop(parentStyle->paddingTop());
3592             style->setPaddingBottom(parentStyle->paddingBottom());
3593             style->setPaddingLeft(parentStyle->paddingLeft());
3594             style->setPaddingRight(parentStyle->paddingRight());
3595         }
3596         else if (isInitial)
3597             style->resetPadding();
3598         return;
3599     case CSS_PROP_FONT:
3600         if (isInherit) {
3601             FontDescription fontDescription = parentStyle->fontDescription();
3602             style->setLineHeight(parentStyle->lineHeight());
3603             if (style->setFontDescription(fontDescription))
3604                 fontDirty = true;
3605         } else if (isInitial) {
3606             FontDescription fontDescription;
3607             fontDescription.setGenericFamily(FontDescription::StandardFamily);
3608             style->setLineHeight(RenderStyle::initialLineHeight());
3609             if (style->setFontDescription(fontDescription))
3610                 fontDirty = true;
3611         } else if (primitiveValue) {
3612             style->setLineHeight(RenderStyle::initialLineHeight());
3613             FontDescription fontDescription;
3614             theme()->systemFont(primitiveValue->getIdent(), fontDescription);
3615             // Double-check and see if the theme did anything.  If not, don't bother updating the font.
3616             if (fontDescription.isAbsoluteSize()) {
3617                 // Handle the zoom factor.
3618                 fontDescription.setComputedSize(getComputedSizeFromSpecifiedSize(fontDescription.isAbsoluteSize(), fontDescription.specifiedSize()));
3619                 if (style->setFontDescription(fontDescription))
3620                     fontDirty = true;
3621             }
3622         } else if (value->isFontValue()) {
3623             FontValue *font = static_cast<FontValue*>(value);
3624             if (!font->style || !font->variant || !font->weight ||
3625                  !font->size || !font->lineHeight || !font->family)
3626                 return;
3627             applyProperty(CSS_PROP_FONT_STYLE, font->style.get());
3628             applyProperty(CSS_PROP_FONT_VARIANT, font->variant.get());
3629             applyProperty(CSS_PROP_FONT_WEIGHT, font->weight.get());
3630             applyProperty(CSS_PROP_FONT_SIZE, font->size.get());
3631
3632             // Line-height can depend on font().pixelSize(), so we have to update the font
3633             // before we evaluate line-height, e.g., font: 1em/1em.  FIXME: Still not
3634             // good enough: style="font:1em/1em; font-size:36px" should have a line-height of 36px.
3635             if (fontDirty)
3636                 CSSStyleSelector::style->font().update();
3637             
3638             applyProperty(CSS_PROP_LINE_HEIGHT, font->lineHeight.get());
3639             applyProperty(CSS_PROP_FONT_FAMILY, font->family.get());
3640         }
3641         return;
3642         
3643     case CSS_PROP_LIST_STYLE:
3644         if (isInherit) {
3645             style->setListStyleType(parentStyle->listStyleType());
3646             style->setListStyleImage(parentStyle->listStyleImage());
3647             style->setListStylePosition(parentStyle->listStylePosition());
3648         }
3649         else if (isInitial) {
3650             style->setListStyleType(RenderStyle::initialListStyleType());
3651             style->setListStyleImage(RenderStyle::initialListStyleImage());
3652             style->setListStylePosition(RenderStyle::initialListStylePosition());
3653         }
3654         return;
3655     case CSS_PROP_OUTLINE:
3656         if (isInherit) {
3657             style->setOutlineWidth(parentStyle->outlineWidth());
3658             style->setOutlineColor(parentStyle->outlineColor());
3659             style->setOutlineStyle(parentStyle->outlineStyle());
3660         }
3661         else if (isInitial)
3662             style->resetOutline();
3663         return;
3664
3665     // CSS3 Properties
3666     case CSS_PROP__WEBKIT_APPEARANCE: {
3667         HANDLE_INHERIT_AND_INITIAL(appearance, Appearance)
3668         if (!primitiveValue) break;
3669         int id = primitiveValue->getIdent();
3670         EAppearance appearance;
3671         if (id == CSS_VAL_NONE)
3672             appearance = NoAppearance;
3673         else
3674             appearance = EAppearance(id - CSS_VAL_CHECKBOX + 1);
3675         style->setAppearance(appearance);
3676         return;
3677     }
3678     case CSS_PROP__WEBKIT_BINDING: {
3679 #ifdef XBL_SUPPORT
3680         if (isInitial || (primitiveValue && primitiveValue->getIdent() == CSS_VAL_NONE)) {
3681             style->deleteBindingURIs();
3682             return;
3683         }
3684         else if (isInherit) {
3685             if (parentStyle->bindingURIs())
3686                 style->inheritBindingURIs(parentStyle->bindingURIs());
3687             else
3688                 style->deleteBindingURIs();
3689             return;
3690         }
3691
3692         if (!value->isValueList()) return;
3693         CSSValueList* list = static_cast<CSSValueList*>(value);
3694         bool firstBinding = true;
3695         for (unsigned int i = 0; i < list->length(); i++) {
3696             CSSValue *item = list->item(i);
3697             CSSPrimitiveValue *val = static_cast<CSSPrimitiveValue*>(item);
3698             if (val->primitiveType() == CSSPrimitiveValue::CSS_URI) {
3699                 if (firstBinding) {
3700                     firstBinding = false;
3701                     style->deleteBindingURIs();
3702                 }
3703                 style->addBindingURI(val->getStringValue());
3704             }
3705         }
3706 #endif
3707         return;
3708     }
3709
3710     case CSS_PROP__WEBKIT_BORDER_IMAGE: {
3711         HANDLE_INHERIT_AND_INITIAL(borderImage, BorderImage)
3712         BorderImage image;
3713         if (primitiveValue) {
3714             if (primitiveValue->getIdent() == CSS_VAL_NONE)
3715                 style->setBorderImage(image);
3716         } else {
3717             // Retrieve the border image value.
3718             CSSBorderImageValue* borderImage = static_cast<CSSBorderImageValue*>(value);
3719             
3720             // Set the image (this kicks off the load).
3721             image.m_image = borderImage->m_image->image(element->document()->docLoader());
3722             
3723             // Set up a length box to represent our image slices.
3724             LengthBox& l = image.m_slices;
3725             RectImpl* r = borderImage->m_imageSliceRect.get();
3726             if (r->top()->primitiveType() == CSSPrimitiveValue::CSS_PERCENTAGE)
3727                 l.top = Length(r->top()->getFloatValue(), Percent);
3728             else
3729                 l.top = Length((int)r->top()->getFloatValue(CSSPrimitiveValue::CSS_NUMBER), Fixed);
3730             if (r->bottom()->primitiveType() == CSSPrimitiveValue::CSS_PERCENTAGE)
3731                 l.bottom = Length(r->bottom()->getFloatValue(), Percent);
3732             else
3733                 l.bottom = Length((int)r->bottom()->getFloatValue(CSSPrimitiveValue::CSS_NUMBER), Fixed);
3734             if (r->left()->primitiveType() == CSSPrimitiveValue::CSS_PERCENTAGE)
3735                 l.left = Length(r->left()->getFloatValue(), Percent);
3736             else
3737                 l.left = Length((int)r->left()->getFloatValue(CSSPrimitiveValue::CSS_NUMBER), Fixed);
3738             if (r->right()->primitiveType() == CSSPrimitiveValue::CSS_PERCENTAGE)
3739                 l.right = Length(r->right()->getFloatValue(), Percent);
3740             else
3741                 l.right = Length((int)r->right()->getFloatValue(CSSPrimitiveValue::CSS_NUMBER), Fixed);
3742             
3743             // Set the appropriate rules for stretch/round/repeat of the slices
3744             switch (borderImage->m_horizontalSizeRule) {
3745                 case CSS_VAL_STRETCH:
3746                     image.m_horizontalRule = BI_STRETCH;
3747                     break;
3748                 case CSS_VAL_ROUND:
3749                     image.m_horizontalRule = BI_ROUND;
3750                     break;
3751                 default: // CSS_VAL_REPEAT
3752                     image.m_horizontalRule = BI_REPEAT;
3753                     break;
3754             }
3755
3756             switch (borderImage->m_verticalSizeRule) {
3757                 case CSS_VAL_STRETCH:
3758                     image.m_verticalRule = BI_STRETCH;
3759                     break;
3760                 case CSS_VAL_ROUND:
3761                     image.m_verticalRule = BI_ROUND;
3762                     break;
3763                 default: // CSS_VAL_REPEAT
3764                     image.m_verticalRule = BI_REPEAT;
3765                     break;
3766             }
3767
3768             style->setBorderImage(image);
3769         }
3770         return;
3771     }
3772
3773     case CSS_PROP__WEBKIT_BORDER_RADIUS:
3774         if (isInherit) {
3775             style->setBorderTopLeftRadius(parentStyle->borderTopLeftRadius());
3776             style->setBorderTopRightRadius(parentStyle->borderTopRightRadius());
3777             style->setBorderBottomLeftRadius(parentStyle->borderBottomLeftRadius());
3778             style->setBorderBottomRightRadius(parentStyle->borderBottomRightRadius());
3779             return;
3780         }
3781         if (isInitial) {
3782             style->resetBorderRadius();
3783             return;
3784         }
3785         // Fall through
3786     case CSS_PROP__WEBKIT_BORDER_TOP_LEFT_RADIUS:
3787     case CSS_PROP__WEBKIT_BORDER_TOP_RIGHT_RADIUS:
3788     case CSS_PROP__WEBKIT_BORDER_BOTTOM_LEFT_RADIUS:
3789     case CSS_PROP__WEBKIT_BORDER_BOTTOM_RIGHT_RADIUS: {
3790         if (isInherit) {
3791             HANDLE_INHERIT_COND(CSS_PROP__WEBKIT_BORDER_TOP_LEFT_RADIUS, borderTopLeftRadius, BorderTopLeftRadius)
3792             HANDLE_INHERIT_COND(CSS_PROP__WEBKIT_BORDER_TOP_RIGHT_RADIUS, borderTopRightRadius, BorderTopRightRadius)
3793             HANDLE_INHERIT_COND(CSS_PROP__WEBKIT_BORDER_BOTTOM_LEFT_RADIUS, borderBottomLeftRadius, BorderBottomLeftRadius)
3794             HANDLE_INHERIT_COND(CSS_PROP__WEBKIT_BORDER_BOTTOM_RIGHT_RADIUS, borderBottomRightRadius, BorderBottomRightRadius)
3795             return;
3796         }
3797         
3798  &n