e53514f21d91c1eeaa831151209182c0bd910616
[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 #if ENABLE(SVG)
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 #if ENABLE(SVG)
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 #if ENABLE(SVG)
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 #if ENABLE(SVG)
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 #if ENABLE(SVG)
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 #if ENABLE(SVG)
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::PseudoTarget:
1456                 if (e == e->document()->getCSSTarget())
1457                     return true;
1458                 break;
1459             case CSSSelector::PseudoAnyLink:
1460                 if (pseudoState == PseudoUnknown)
1461                     checkPseudoState(e, false);
1462                 if (pseudoState == PseudoAnyLink || pseudoState == PseudoLink || pseudoState == PseudoVisited)
1463                     return true;
1464                 break;
1465             case CSSSelector::PseudoAutofill:
1466                 if (e && e->hasTagName(inputTag))
1467                     return static_cast<HTMLInputElement*>(e)->autofilled();
1468                 break;
1469             case CSSSelector::PseudoLink:
1470                 if (pseudoState == PseudoUnknown || pseudoState == PseudoAnyLink)
1471                     checkPseudoState(e);
1472                 if (pseudoState == PseudoLink)
1473                     return true;
1474                 break;
1475             case CSSSelector::PseudoVisited:
1476                 if (pseudoState == PseudoUnknown || pseudoState == PseudoAnyLink)
1477                     checkPseudoState(e);
1478                 if (pseudoState == PseudoVisited)
1479                     return true;
1480                 break;
1481             case CSSSelector::PseudoHover: {
1482                 // If we're in quirks mode, then hover should never match anchors with no
1483                 // href and *:hover should not match anything.  This is important for sites like wsj.com.
1484                 if (strictParsing || isSubSelector || sel->relation() == CSSSelector::SubSelector || (sel->hasTag() && !e->hasTagName(aTag)) || e->isLink()) {
1485                     if (element == e && style)
1486                         style->setAffectedByHoverRules(true);
1487                     if (element != e && e->renderStyle())
1488                         e->renderStyle()->setAffectedByHoverRules(true);
1489                     if (e->hovered())
1490                         return true;
1491                 }
1492                 break;
1493             }
1494             case CSSSelector::PseudoDrag: {
1495                 if (element == e && style)
1496                     style->setAffectedByDragRules(true);
1497                     if (element != e && e->renderStyle())
1498                         e->renderStyle()->setAffectedByDragRules(true);
1499                     if (e->renderer() && e->renderer()->isDragging())
1500                         return true;
1501                 break;
1502             }
1503             case CSSSelector::PseudoFocus:
1504                 if (e && e->focused() && e->document()->frame()->isActive())
1505                     return true;
1506                 break;
1507             case CSSSelector::PseudoActive:
1508                 // If we're in quirks mode, then :active should never match anchors with no
1509                 // href and *:active should not match anything. 
1510                 if (strictParsing || isSubSelector || sel->relation() == CSSSelector::SubSelector || (sel->hasTag() && !e->hasTagName(aTag)) || e->isLink()) {
1511                     if (element == e && style)
1512                         style->setAffectedByActiveRules(true);
1513                     else if (e->renderStyle())
1514                         e->renderStyle()->setAffectedByActiveRules(true);
1515                     if (e->active())
1516                         return true;
1517                 }
1518                 break;
1519             case CSSSelector::PseudoEnabled:
1520                 if (e && e->isControl())
1521                     // The UI spec states that you can't match :enabled unless you are an object that can
1522                     // "receive focus and be activated."  We will limit matching of this pseudo-class to elements
1523                     // that are controls.
1524                     return e->isEnabled();                    
1525                 break;
1526             case CSSSelector::PseudoDisabled:
1527                 if (e && e->isControl())
1528                     // The UI spec states that you can't match :enabled unless you are an object that can
1529                     // "receive focus and be activated."  We will limit matching of this pseudo-class to elements
1530                     // that are controls.
1531                     return !e->isEnabled();                    
1532                 break;
1533             case CSSSelector::PseudoChecked:
1534                 // Even though WinIE allows checked and indeterminate to co-exist, the CSS selector spec says that
1535                 // you can't be both checked and indeterminate.  We will behave like WinIE behind the scenes and just
1536                 // obey the CSS spec here in the test for matching the pseudo.
1537                 if (e && e->isChecked() && !e->isIndeterminate())
1538                     return true;
1539                 break;
1540             case CSSSelector::PseudoIndeterminate:
1541                 if (e && e->isIndeterminate())
1542                     return true;
1543                 break;
1544             case CSSSelector::PseudoRoot:
1545                 if (e == e->document()->documentElement())
1546                     return true;
1547                 break;
1548             case CSSSelector::PseudoLang: {
1549                 const AtomicString& value = e->getAttribute(langAttr);
1550                 if (value.isEmpty() || !value.startsWith(sel->m_argument, false))
1551                     break;
1552                 if (value.length() != sel->m_argument.length() && value[sel->m_argument.length()] != '-')
1553                     break;
1554                 return true;
1555             }
1556             case CSSSelector::PseudoNot: {
1557                 // check the simple selector
1558                 for (CSSSelector* subSel = sel->m_simpleSelector; subSel; subSel = subSel->m_tagHistory) {
1559                     // :not cannot nest. I don't really know why this is a
1560                     // restriction in CSS3, but it is, so let's honour it.
1561                     if (subSel->m_simpleSelector)
1562                         break;
1563                     if (!checkOneSelector(subSel, e))
1564                         return true;
1565                 }
1566                 break;
1567             }
1568             case CSSSelector::PseudoUnknown:
1569                 ASSERT_NOT_REACHED();
1570                 break;
1571             
1572             // Pseudo-elements:
1573             case CSSSelector::PseudoFirstLine:
1574                 if (subject) {
1575                     dynamicPseudo = RenderStyle::FIRST_LINE;
1576                     return true;
1577                 }
1578                 break;
1579             case CSSSelector::PseudoFirstLetter:
1580                 if (subject) {
1581                     dynamicPseudo = RenderStyle::FIRST_LETTER;
1582                     return true;
1583                 }
1584                 break;
1585             case CSSSelector::PseudoSelection:
1586                 dynamicPseudo = RenderStyle::SELECTION;
1587                 return true;
1588             case CSSSelector::PseudoBefore:
1589                 dynamicPseudo = RenderStyle::BEFORE;
1590                 return true;
1591             case CSSSelector::PseudoAfter:
1592                 dynamicPseudo = RenderStyle::AFTER;
1593                 return true;
1594             case CSSSelector::PseudoFileUploadButton:
1595                 dynamicPseudo = RenderStyle::FILE_UPLOAD_BUTTON;
1596                 return true;
1597             case CSSSelector::PseudoSliderThumb:
1598                 dynamicPseudo = RenderStyle::SLIDER_THUMB;
1599                 return true; 
1600             case CSSSelector::PseudoSearchCancelButton:
1601                 dynamicPseudo = RenderStyle::SEARCH_CANCEL_BUTTON;
1602                 return true; 
1603             case CSSSelector::PseudoSearchDecoration:
1604                 dynamicPseudo = RenderStyle::SEARCH_DECORATION;
1605                 return true;
1606             case CSSSelector::PseudoSearchResultsDecoration:
1607                 dynamicPseudo = RenderStyle::SEARCH_RESULTS_DECORATION;
1608                 return true;
1609             case CSSSelector::PseudoSearchResultsButton:
1610                 dynamicPseudo = RenderStyle::SEARCH_RESULTS_BUTTON;
1611                 return true;
1612             case CSSSelector::PseudoNotParsed:
1613                 ASSERT(false);
1614                 break;
1615         }
1616         return false;
1617     }
1618     // ### add the rest of the checks...
1619     return true;
1620 }
1621
1622 // -----------------------------------------------------------------
1623
1624 CSSRuleSet::CSSRuleSet()
1625 {
1626     m_universalRules = 0;
1627     m_ruleCount = 0;
1628 }
1629
1630 CSSRuleSet::~CSSRuleSet()
1631
1632     deleteAllValues(m_idRules);
1633     deleteAllValues(m_classRules);
1634     deleteAllValues(m_tagRules);
1635
1636     delete m_universalRules; 
1637 }
1638
1639
1640 void CSSRuleSet::addToRuleSet(AtomicStringImpl* key, AtomRuleMap& map,
1641                               CSSStyleRule* rule, CSSSelector* sel)
1642 {
1643     if (!key) return;
1644     CSSRuleDataList* rules = map.get(key);
1645     if (!rules) {
1646         rules = new CSSRuleDataList(m_ruleCount++, rule, sel);
1647         map.set(key, rules);
1648     } else
1649         rules->append(m_ruleCount++, rule, sel);
1650 }
1651
1652 void CSSRuleSet::addRule(CSSStyleRule* rule, CSSSelector* sel)
1653 {
1654     if (sel->m_match == CSSSelector::Id) {
1655         addToRuleSet(sel->m_value.impl(), m_idRules, rule, sel);
1656         return;
1657     }
1658     if (sel->m_match == CSSSelector::Class) {
1659         addToRuleSet(sel->m_value.impl(), m_classRules, rule, sel);
1660         return;
1661     }
1662      
1663     const AtomicString& localName = sel->m_tag.localName();
1664     if (localName != starAtom) {
1665         addToRuleSet(localName.impl(), m_tagRules, rule, sel);
1666         return;
1667     }
1668     
1669     // Just put it in the universal rule set.
1670     if (!m_universalRules)
1671         m_universalRules = new CSSRuleDataList(m_ruleCount++, rule, sel);
1672     else
1673         m_universalRules->append(m_ruleCount++, rule, sel);
1674 }
1675
1676 void CSSRuleSet::addRulesFromSheet(CSSStyleSheet* sheet,  MediaQueryEvaluator* medium)
1677 {
1678     if (!sheet || !sheet->isCSSStyleSheet())
1679         return;
1680
1681     // No media implies "all", but if a media list exists it must
1682     // contain our current medium
1683     if (sheet->media() && !medium->eval(sheet->media()))
1684         return; // the style sheet doesn't apply
1685
1686     int len = sheet->length();
1687
1688     for (int i = 0; i < len; i++) {
1689         StyleBase* item = sheet->item(i);
1690         if (item->isStyleRule()) {
1691             CSSStyleRule* rule = static_cast<CSSStyleRule*>(item);
1692             for (CSSSelector* s = rule->selector(); s; s = s->next())
1693                 addRule(rule, s);
1694         }
1695         else if(item->isImportRule()) {
1696             CSSImportRule* import = static_cast<CSSImportRule*>(item);
1697             if (!import->media() || medium->eval(import->media()))
1698                 addRulesFromSheet(import->styleSheet(), medium);
1699         }
1700         else if(item->isMediaRule()) {
1701             CSSMediaRule* r = static_cast<CSSMediaRule*>(item);
1702             CSSRuleList* rules = r->cssRules();
1703
1704             if ((!r->media() || medium->eval(r->media())) && rules) {
1705                 // Traverse child elements of the @media rule.
1706                 for (unsigned j = 0; j < rules->length(); j++) {
1707                     CSSRule *childItem = rules->item(j);
1708                     if (childItem->isStyleRule()) {
1709                         // It is a StyleRule, so append it to our list
1710                         CSSStyleRule* rule = static_cast<CSSStyleRule*>(childItem);
1711                         for (CSSSelector* s = rule->selector(); s; s = s->next())
1712                             addRule(rule, s);
1713                         
1714                     }
1715                 }   // for rules
1716             }   // if rules
1717         }
1718     }
1719 }
1720
1721 // -------------------------------------------------------------------------------------
1722 // this is mostly boring stuff on how to apply a certain rule to the renderstyle...
1723
1724 static Length convertToLength(CSSPrimitiveValue *primitiveValue, RenderStyle *style, bool *ok = 0)
1725 {
1726     Length l;
1727     if (!primitiveValue) {
1728         if (ok)
1729             *ok = false;
1730     } else {
1731         int type = primitiveValue->primitiveType();
1732         if(type > CSSPrimitiveValue::CSS_PERCENTAGE && type < CSSPrimitiveValue::CSS_DEG)
1733             l = Length(primitiveValue->computeLengthIntForLength(style), Fixed);
1734         else if(type == CSSPrimitiveValue::CSS_PERCENTAGE)
1735             l = Length(primitiveValue->getFloatValue(), Percent);
1736         else if(type == CSSPrimitiveValue::CSS_NUMBER)
1737             l = Length(primitiveValue->getFloatValue() * 100.0, Percent);
1738         else if (ok)
1739             *ok = false;
1740     }
1741     return l;
1742 }
1743
1744 void CSSStyleSelector::applyDeclarations(bool applyFirst, bool isImportant,
1745                                          int startIndex, int endIndex)
1746 {
1747     if (startIndex == -1) return;
1748     for (int i = startIndex; i <= endIndex; i++) {
1749         CSSMutableStyleDeclaration* decl = m_matchedDecls[i];
1750         DeprecatedValueListConstIterator<CSSProperty> end;
1751         for (DeprecatedValueListConstIterator<CSSProperty> it = decl->valuesIterator(); it != end; ++it) {
1752             const CSSProperty& current = *it;
1753             // give special priority to font-xxx, color properties
1754             if (isImportant == current.isImportant()) {
1755                 bool first;
1756                 switch(current.id()) {
1757                     case CSS_PROP_COLOR:
1758                     case CSS_PROP_DIRECTION:
1759                     case CSS_PROP_DISPLAY:
1760                     case CSS_PROP_FONT:
1761                     case CSS_PROP_FONT_SIZE:
1762                     case CSS_PROP_FONT_STYLE:
1763                     case CSS_PROP_FONT_FAMILY:
1764                     case CSS_PROP_FONT_WEIGHT:
1765                     case CSS_PROP__WEBKIT_TEXT_SIZE_ADJUST:
1766                     case CSS_PROP_FONT_VARIANT:
1767                         // these have to be applied first, because other properties use the computed
1768                         // values of these porperties.
1769                         first = true;
1770                         break;
1771                     default:
1772                         first = false;
1773                         break;
1774                 }
1775                 
1776                 if (first == applyFirst)
1777                     applyProperty(current.id(), current.value());
1778             }
1779         }
1780     }
1781 }
1782
1783 static void applyCounterList(RenderStyle* style, CSSValueList* list, bool isReset)
1784 {
1785     CounterDirectiveMap& map = style->accessCounterDirectives();
1786     typedef CounterDirectiveMap::iterator Iterator;
1787
1788     Iterator end = map.end();
1789     for (Iterator it = map.begin(); it != end; ++it)
1790         if (isReset)
1791             it->second.m_reset = false;
1792         else
1793             it->second.m_increment = false;
1794
1795     int length = list ? list->length() : 0;
1796     for (int i = 0; i < length; ++i) {
1797         Pair* pair = static_cast<CSSPrimitiveValue*>(list->item(i))->getPairValue();
1798         AtomicString identifier = static_cast<CSSPrimitiveValue*>(pair->first())->getStringValue();
1799         // FIXME: What about overflow?
1800         int value = static_cast<int>(static_cast<CSSPrimitiveValue*>(pair->second())->getFloatValue());
1801         CounterDirectives& directives = map.add(identifier.impl(), CounterDirectives()).first->second;
1802         if (isReset) {
1803             directives.m_reset = true;
1804             directives.m_resetValue = value;
1805         } else {
1806             if (directives.m_increment)
1807                 directives.m_incrementValue += value;
1808             else {
1809                 directives.m_increment = true;
1810                 directives.m_incrementValue = value;
1811             }
1812         }
1813     }
1814 }
1815
1816 void CSSStyleSelector::applyProperty(int id, CSSValue *value)
1817 {
1818     CSSPrimitiveValue *primitiveValue = 0;
1819     if(value->isPrimitiveValue()) primitiveValue = static_cast<CSSPrimitiveValue*>(value);
1820
1821     Length l;
1822     bool apply = false;
1823
1824     unsigned short valueType = value->cssValueType();
1825
1826     bool isInherit = parentNode && valueType == CSSValue::CSS_INHERIT;
1827     bool isInitial = valueType == CSSValue::CSS_INITIAL || (!parentNode && valueType == CSSValue::CSS_INHERIT);
1828
1829     // These properties are used to set the correct margins/padding on RTL lists.
1830     if (id == CSS_PROP__WEBKIT_MARGIN_START)
1831         id = style->direction() == LTR ? CSS_PROP_MARGIN_LEFT : CSS_PROP_MARGIN_RIGHT;
1832     else if (id == CSS_PROP__WEBKIT_PADDING_START)
1833         id = style->direction() == LTR ? CSS_PROP_PADDING_LEFT : CSS_PROP_PADDING_RIGHT;
1834
1835     // What follows is a list that maps the CSS properties into their corresponding front-end
1836     // RenderStyle values.  Shorthands (e.g. border, background) occur in this list as well and
1837     // are only hit when mapping "inherit" or "initial" into front-end values.
1838     switch (static_cast<CSSPropertyID>(id))
1839     {
1840 // ident only properties
1841     case CSS_PROP_BACKGROUND_ATTACHMENT:
1842         HANDLE_BACKGROUND_VALUE(backgroundAttachment, BackgroundAttachment, value)
1843         return;
1844     case CSS_PROP__WEBKIT_BACKGROUND_CLIP:
1845         HANDLE_BACKGROUND_VALUE(backgroundClip, BackgroundClip, value)
1846         return;
1847     case CSS_PROP__WEBKIT_BACKGROUND_COMPOSITE:
1848         HANDLE_BACKGROUND_VALUE(backgroundComposite, BackgroundComposite, value)
1849         return;
1850     case CSS_PROP__WEBKIT_BACKGROUND_ORIGIN:
1851         HANDLE_BACKGROUND_VALUE(backgroundOrigin, BackgroundOrigin, value)
1852         return;
1853     case CSS_PROP_BACKGROUND_REPEAT:
1854         HANDLE_BACKGROUND_VALUE(backgroundRepeat, BackgroundRepeat, value)
1855         return;
1856     case CSS_PROP__WEBKIT_BACKGROUND_SIZE:
1857         HANDLE_BACKGROUND_VALUE(backgroundSize, BackgroundSize, value)
1858         return;
1859     case CSS_PROP_BORDER_COLLAPSE:
1860         HANDLE_INHERIT_AND_INITIAL(borderCollapse, BorderCollapse)
1861         if(!primitiveValue) return;
1862         switch(primitiveValue->getIdent())
1863         {
1864         case CSS_VAL_COLLAPSE:
1865             style->setBorderCollapse(true);
1866             break;
1867         case CSS_VAL_SEPARATE:
1868             style->setBorderCollapse(false);
1869             break;
1870         default:
1871             return;
1872         }
1873         return;
1874         
1875     case CSS_PROP_BORDER_TOP_STYLE:
1876         HANDLE_INHERIT_AND_INITIAL_WITH_VALUE(borderTopStyle, BorderTopStyle, BorderStyle)
1877         if (!primitiveValue) return;
1878         style->setBorderTopStyle((EBorderStyle)(primitiveValue->getIdent() - CSS_VAL_NONE));
1879         return;
1880     case CSS_PROP_BORDER_RIGHT_STYLE:
1881         HANDLE_INHERIT_AND_INITIAL_WITH_VALUE(borderRightStyle, BorderRightStyle, BorderStyle)
1882         if (!primitiveValue) return;
1883         style->setBorderRightStyle((EBorderStyle)(primitiveValue->getIdent() - CSS_VAL_NONE));
1884         return;
1885     case CSS_PROP_BORDER_BOTTOM_STYLE:
1886         HANDLE_INHERIT_AND_INITIAL_WITH_VALUE(borderBottomStyle, BorderBottomStyle, BorderStyle)
1887         if (!primitiveValue) return;
1888         style->setBorderBottomStyle((EBorderStyle)(primitiveValue->getIdent() - CSS_VAL_NONE));
1889         return;
1890     case CSS_PROP_BORDER_LEFT_STYLE:
1891         HANDLE_INHERIT_AND_INITIAL_WITH_VALUE(borderLeftStyle, BorderLeftStyle, BorderStyle)
1892         if (!primitiveValue) return;
1893         style->setBorderLeftStyle((EBorderStyle)(primitiveValue->getIdent() - CSS_VAL_NONE));
1894         return;
1895     case CSS_PROP_OUTLINE_STYLE:
1896         HANDLE_INHERIT_AND_INITIAL_WITH_VALUE(outlineStyle, OutlineStyle, BorderStyle)
1897         if (!primitiveValue) return;
1898         if (primitiveValue->getIdent() == CSS_VAL_AUTO)
1899             style->setOutlineStyle(DOTTED, true);
1900         else
1901             style->setOutlineStyle((EBorderStyle)(primitiveValue->getIdent() - CSS_VAL_NONE));
1902         return;
1903     case CSS_PROP_CAPTION_SIDE:
1904     {
1905         HANDLE_INHERIT_AND_INITIAL(captionSide, CaptionSide)
1906         if(!primitiveValue) return;
1907         ECaptionSide c = RenderStyle::initialCaptionSide();
1908         switch(primitiveValue->getIdent())
1909         {
1910         case CSS_VAL_LEFT:
1911             c = CAPLEFT; break;
1912         case CSS_VAL_RIGHT:
1913             c = CAPRIGHT; break;
1914         case CSS_VAL_TOP:
1915             c = CAPTOP; break;
1916         case CSS_VAL_BOTTOM:
1917             c = CAPBOTTOM; break;
1918         default:
1919             return;
1920         }
1921         style->setCaptionSide(c);
1922         return;
1923     }
1924     case CSS_PROP_CLEAR:
1925     {
1926         HANDLE_INHERIT_AND_INITIAL(clear, Clear)
1927         if(!primitiveValue) return;
1928         EClear c;
1929         switch(primitiveValue->getIdent())
1930         {
1931         case CSS_VAL_NONE:
1932             c = CNONE; break;
1933         case CSS_VAL_LEFT:
1934             c = CLEFT; break;
1935         case CSS_VAL_RIGHT:
1936             c = CRIGHT; break;
1937         case CSS_VAL_BOTH:
1938             c = CBOTH; break;
1939         default:
1940             return;
1941         }
1942         style->setClear(c);
1943         return;
1944     }
1945     case CSS_PROP_DIRECTION:
1946     {
1947         HANDLE_INHERIT_AND_INITIAL(direction, Direction)
1948         if(!primitiveValue) break;
1949         style->setDirection(primitiveValue->getIdent() == CSS_VAL_LTR ? LTR : RTL);
1950         return;
1951     }
1952     case CSS_PROP_DISPLAY:
1953     {
1954         HANDLE_INHERIT_AND_INITIAL(display, Display)
1955         if(!primitiveValue) break;
1956         int id = primitiveValue->getIdent();
1957         EDisplay d;
1958         if (id == CSS_VAL_NONE)
1959             d = NONE;
1960         else
1961             d = EDisplay(primitiveValue->getIdent() - CSS_VAL_INLINE);
1962
1963         style->setDisplay(d);
1964         return;
1965     }
1966
1967     case CSS_PROP_EMPTY_CELLS:
1968     {
1969         HANDLE_INHERIT_AND_INITIAL(emptyCells, EmptyCells)
1970         if (!primitiveValue) break;
1971         int id = primitiveValue->getIdent();
1972         if (id == CSS_VAL_SHOW)
1973             style->setEmptyCells(SHOW);
1974         else if (id == CSS_VAL_HIDE)
1975             style->setEmptyCells(HIDE);
1976         return;
1977     }
1978     case CSS_PROP_FLOAT:
1979     {
1980         HANDLE_INHERIT_AND_INITIAL(floating, Floating)
1981         if(!primitiveValue) return;
1982         EFloat f;
1983         switch(primitiveValue->getIdent())
1984         {
1985         case CSS_VAL_LEFT:
1986             f = FLEFT; break;
1987         case CSS_VAL_RIGHT:
1988             f = FRIGHT; break;
1989         case CSS_VAL_NONE:
1990         case CSS_VAL_CENTER:  //Non standart CSS-Value
1991             f = FNONE; break;
1992         default:
1993             return;
1994         }
1995         
1996         style->setFloating(f);
1997         return;
1998     }
1999
2000     case CSS_PROP_FONT_STYLE:
2001     {
2002         FontDescription fontDescription = style->fontDescription();
2003         if (isInherit)
2004             fontDescription.setItalic(parentStyle->fontDescription().italic());
2005         else if (isInitial)
2006             fontDescription.setItalic(false);
2007         else {
2008             if (!primitiveValue) return;
2009             switch (primitiveValue->getIdent()) {
2010                 case CSS_VAL_OBLIQUE:
2011                 // FIXME: oblique is the same as italic for the moment...
2012                 case CSS_VAL_ITALIC:
2013                     fontDescription.setItalic(true);
2014                     break;
2015                 case CSS_VAL_NORMAL:
2016                     fontDescription.setItalic(false);
2017                     break;
2018                 default:
2019                     return;
2020             }
2021         }
2022         if (style->setFontDescription(fontDescription))
2023             fontDirty = true;
2024         return;
2025     }
2026
2027     case CSS_PROP_FONT_VARIANT:
2028     {
2029         FontDescription fontDescription = style->fontDescription();
2030         if (isInherit) 
2031             fontDescription.setSmallCaps(parentStyle->fontDescription().smallCaps());
2032         else if (isInitial)
2033             fontDescription.setSmallCaps(false);
2034         else {
2035             if (!primitiveValue) return;
2036             int id = primitiveValue->getIdent();
2037             if (id == CSS_VAL_NORMAL)
2038                 fontDescription.setSmallCaps(false);
2039             else if (id == CSS_VAL_SMALL_CAPS)
2040                 fontDescription.setSmallCaps(true);
2041             else
2042                 return;
2043         }
2044         if (style->setFontDescription(fontDescription))
2045             fontDirty = true;
2046         return;        
2047     }
2048
2049     case CSS_PROP_FONT_WEIGHT:
2050     {
2051         FontDescription fontDescription = style->fontDescription();
2052         if (isInherit)
2053             fontDescription.setWeight(parentStyle->fontDescription().weight());
2054         else if (isInitial)
2055             fontDescription.setWeight(cNormalWeight);
2056         else {
2057             if (!primitiveValue) return;
2058             if (primitiveValue->getIdent()) {
2059                 switch (primitiveValue->getIdent()) {
2060                     // FIXME: We aren't genuinely supporting specific weight values.
2061                     case CSS_VAL_BOLD:
2062                     case CSS_VAL_BOLDER:
2063                     case CSS_VAL_600:
2064                     case CSS_VAL_700:
2065                     case CSS_VAL_800:
2066                     case CSS_VAL_900:
2067                         fontDescription.setWeight(cBoldWeight);
2068                         break;
2069                     case CSS_VAL_NORMAL:
2070                     case CSS_VAL_LIGHTER:
2071                     case CSS_VAL_100:
2072                     case CSS_VAL_200:
2073                     case CSS_VAL_300:
2074                     case CSS_VAL_400:
2075                     case CSS_VAL_500:
2076                         fontDescription.setWeight(cNormalWeight);
2077                         break;
2078                     default:
2079                         return;
2080                 }
2081             }
2082             else
2083             {
2084                 // ### fix parsing of 100-900 values in parser, apply them here
2085             }
2086         }
2087         if (style->setFontDescription(fontDescription))
2088             fontDirty = true;
2089         return;
2090     }
2091         
2092     case CSS_PROP_LIST_STYLE_POSITION:
2093     {
2094         HANDLE_INHERIT_AND_INITIAL(listStylePosition, ListStylePosition)
2095         if (!primitiveValue) return;
2096         if (primitiveValue->getIdent())
2097             style->setListStylePosition((EListStylePosition) (primitiveValue->getIdent() - CSS_VAL_OUTSIDE));
2098         return;
2099     }
2100
2101     case CSS_PROP_LIST_STYLE_TYPE:
2102     {
2103         HANDLE_INHERIT_AND_INITIAL(listStyleType, ListStyleType)
2104         if (!primitiveValue) return;
2105         if (primitiveValue->getIdent())
2106         {
2107             EListStyleType t;
2108             int id = primitiveValue->getIdent();
2109             if (id == CSS_VAL_NONE) { // important!!
2110               t = LNONE;
2111             } else {
2112               t = EListStyleType(id - CSS_VAL_DISC);
2113             }
2114             style->setListStyleType(t);
2115         }
2116         return;
2117     }
2118
2119     case CSS_PROP_OVERFLOW:
2120     {
2121         if (isInherit) {
2122             style->setOverflowX(parentStyle->overflowX());
2123             style->setOverflowY(parentStyle->overflowY());
2124             return;
2125         }
2126         
2127         if (isInitial) {
2128             style->setOverflowX(RenderStyle::initialOverflowX());
2129             style->setOverflowY(RenderStyle::initialOverflowY());
2130             return;
2131         }
2132             
2133         EOverflow o;
2134         switch(primitiveValue->getIdent()) {
2135             case CSS_VAL_VISIBLE:
2136                 o = OVISIBLE; break;
2137             case CSS_VAL_HIDDEN:
2138                 o = OHIDDEN; break;
2139             case CSS_VAL_SCROLL:
2140                 o = OSCROLL; break;
2141             case CSS_VAL_AUTO:
2142                 o = OAUTO; break;
2143             case CSS_VAL__WEBKIT_MARQUEE:
2144                 o = OMARQUEE; break;
2145             case CSS_VAL_OVERLAY:
2146                 o = OOVERLAY; break;
2147             default:
2148                 return;
2149         }
2150         style->setOverflowX(o);
2151         style->setOverflowY(o);
2152         return;
2153     }
2154
2155     case CSS_PROP_OVERFLOW_X:
2156     {
2157         HANDLE_INHERIT_AND_INITIAL(overflowX, OverflowX)
2158         EOverflow o;
2159         switch(primitiveValue->getIdent())
2160         {
2161         case CSS_VAL_VISIBLE:
2162             o = OVISIBLE; break;
2163         case CSS_VAL_HIDDEN:
2164             o = OHIDDEN; break;
2165         case CSS_VAL_SCROLL:
2166             o = OSCROLL; break;
2167         case CSS_VAL_AUTO:
2168             o = OAUTO; break;
2169         case CSS_VAL__WEBKIT_MARQUEE:
2170             o = OMARQUEE; break;
2171         case CSS_VAL_OVERLAY:
2172             o = OOVERLAY; break;
2173         default:
2174             return;
2175         }
2176         style->setOverflowX(o);
2177         return;
2178     }
2179
2180     case CSS_PROP_OVERFLOW_Y:
2181     {
2182         HANDLE_INHERIT_AND_INITIAL(overflowY, OverflowY)
2183         EOverflow o;
2184         switch(primitiveValue->getIdent())
2185         {
2186         case CSS_VAL_VISIBLE:
2187             o = OVISIBLE; break;
2188         case CSS_VAL_HIDDEN:
2189             o = OHIDDEN; break;
2190         case CSS_VAL_SCROLL:
2191             o = OSCROLL; break;
2192         case CSS_VAL_AUTO:
2193             o = OAUTO; break;
2194         case CSS_VAL__WEBKIT_MARQUEE:
2195             o = OMARQUEE; break;
2196         case CSS_VAL_OVERLAY:
2197             o = OOVERLAY; break;
2198         default:
2199             return;
2200         }
2201         style->setOverflowY(o);
2202         return;
2203     }
2204
2205     case CSS_PROP_PAGE_BREAK_BEFORE:
2206     {
2207         HANDLE_INHERIT_AND_INITIAL_WITH_VALUE(pageBreakBefore, PageBreakBefore, PageBreak)
2208         if (!primitiveValue) return;
2209         switch (primitiveValue->getIdent()) {
2210             case CSS_VAL_AUTO:
2211                 style->setPageBreakBefore(PBAUTO);
2212                 break;
2213             case CSS_VAL_LEFT:
2214             case CSS_VAL_RIGHT:
2215             case CSS_VAL_ALWAYS:
2216                 style->setPageBreakBefore(PBALWAYS); // CSS2.1: "Conforming user agents may map left/right to always."
2217                 break;
2218             case CSS_VAL_AVOID:
2219                 style->setPageBreakBefore(PBAVOID);
2220                 break;
2221         }
2222         return;
2223     }
2224
2225     case CSS_PROP_PAGE_BREAK_AFTER:
2226     {
2227         HANDLE_INHERIT_AND_INITIAL_WITH_VALUE(pageBreakAfter, PageBreakAfter, PageBreak)
2228         if (!primitiveValue) return;
2229         switch (primitiveValue->getIdent()) {
2230             case CSS_VAL_AUTO:
2231                 style->setPageBreakAfter(PBAUTO);
2232                 break;
2233             case CSS_VAL_LEFT:
2234             case CSS_VAL_RIGHT:
2235             case CSS_VAL_ALWAYS:
2236                 style->setPageBreakAfter(PBALWAYS); // CSS2.1: "Conforming user agents may map left/right to always."
2237                 break;
2238             case CSS_VAL_AVOID:
2239                 style->setPageBreakAfter(PBAVOID);
2240                 break;
2241         }
2242         return;
2243     }
2244
2245     case CSS_PROP_PAGE_BREAK_INSIDE: {
2246         HANDLE_INHERIT_AND_INITIAL_WITH_VALUE(pageBreakInside, PageBreakInside, PageBreak)
2247         if (!primitiveValue) return;
2248         if (primitiveValue->getIdent() == CSS_VAL_AUTO)
2249             style->setPageBreakInside(PBAUTO);
2250         else if (primitiveValue->getIdent() == CSS_VAL_AVOID)
2251             style->setPageBreakInside(PBAVOID);
2252         return;
2253     }
2254         
2255     case CSS_PROP_POSITION:
2256     {
2257         HANDLE_INHERIT_AND_INITIAL(position, Position)
2258         if(!primitiveValue) return;
2259         EPosition p;
2260         switch(primitiveValue->getIdent())
2261         {
2262         case CSS_VAL_STATIC:
2263             p = StaticPosition;
2264             break;
2265         case CSS_VAL_RELATIVE:
2266             p = RelativePosition;
2267             break;
2268         case CSS_VAL_ABSOLUTE:
2269             p = AbsolutePosition;
2270             break;
2271         case CSS_VAL_FIXED:
2272             p = FixedPosition;
2273             break;
2274         default:
2275             return;
2276         }
2277         style->setPosition(p);
2278         return;
2279     }
2280
2281     case CSS_PROP_TABLE_LAYOUT: {
2282         HANDLE_INHERIT_AND_INITIAL(tableLayout, TableLayout)
2283
2284         if (!primitiveValue->getIdent())
2285             return;
2286
2287         ETableLayout l = RenderStyle::initialTableLayout();
2288         switch(primitiveValue->getIdent()) {
2289             case CSS_VAL_FIXED:
2290                 l = TFIXED;
2291                 // fall through
2292             case CSS_VAL_AUTO:
2293                 style->setTableLayout(l);
2294             default:
2295                 break;
2296         }
2297         return;
2298     }
2299         
2300     case CSS_PROP_UNICODE_BIDI: {
2301         HANDLE_INHERIT_AND_INITIAL(unicodeBidi, UnicodeBidi)
2302         switch (primitiveValue->getIdent()) {
2303             case CSS_VAL_NORMAL:
2304                 style->setUnicodeBidi(UBNormal); 
2305                 break;
2306             case CSS_VAL_EMBED:
2307                 style->setUnicodeBidi(Embed); 
2308                 break;
2309             case CSS_VAL_BIDI_OVERRIDE:
2310                 style->setUnicodeBidi(Override);
2311                 break;
2312             default:
2313                 return;
2314         }
2315         return;
2316     }
2317     case CSS_PROP_TEXT_TRANSFORM: {
2318         HANDLE_INHERIT_AND_INITIAL(textTransform, TextTransform)
2319         
2320         if(!primitiveValue->getIdent()) return;
2321
2322         ETextTransform tt;
2323         switch(primitiveValue->getIdent()) {
2324         case CSS_VAL_CAPITALIZE:  tt = CAPITALIZE;  break;
2325         case CSS_VAL_UPPERCASE:   tt = UPPERCASE;   break;
2326         case CSS_VAL_LOWERCASE:   tt = LOWERCASE;   break;
2327         case CSS_VAL_NONE:
2328         default:                  tt = TTNONE;      break;
2329         }
2330         style->setTextTransform(tt);
2331         return;
2332         }
2333
2334     case CSS_PROP_VISIBILITY:
2335     {
2336         HANDLE_INHERIT_AND_INITIAL(visibility, Visibility)
2337
2338         switch(primitiveValue->getIdent()) {
2339         case CSS_VAL_HIDDEN:
2340             style->setVisibility(HIDDEN);
2341             break;
2342         case CSS_VAL_VISIBLE:
2343             style->setVisibility(VISIBLE);
2344             break;
2345         case CSS_VAL_COLLAPSE:
2346             style->setVisibility(COLLAPSE);
2347         default:
2348             break;
2349         }
2350         return;
2351     }
2352     case CSS_PROP_WHITE_SPACE:
2353         HANDLE_INHERIT_AND_INITIAL(whiteSpace, WhiteSpace)
2354
2355         if(!primitiveValue->getIdent()) return;
2356
2357         EWhiteSpace s;
2358         switch(primitiveValue->getIdent()) {
2359         case CSS_VAL__WEBKIT_NOWRAP:
2360             s = KHTML_NOWRAP;
2361             break;
2362         case CSS_VAL_NOWRAP:
2363             s = NOWRAP;
2364             break;
2365         case CSS_VAL_PRE:
2366             s = PRE;
2367             break;
2368         case CSS_VAL_PRE_WRAP:
2369             s = PRE_WRAP;
2370             break;
2371         case CSS_VAL_PRE_LINE:
2372             s = PRE_LINE;
2373             break;
2374         case CSS_VAL_NORMAL:
2375         default:
2376             s = NORMAL;
2377             break;
2378         }
2379         style->setWhiteSpace(s);
2380         return;
2381
2382     case CSS_PROP_BACKGROUND_POSITION:
2383         HANDLE_BACKGROUND_INHERIT_AND_INITIAL(backgroundXPosition, BackgroundXPosition);
2384         HANDLE_BACKGROUND_INHERIT_AND_INITIAL(backgroundYPosition, BackgroundYPosition);
2385         return;
2386     case CSS_PROP_BACKGROUND_POSITION_X: {
2387         HANDLE_BACKGROUND_VALUE(backgroundXPosition, BackgroundXPosition, value)
2388         return;
2389     }
2390     case CSS_PROP_BACKGROUND_POSITION_Y: {
2391         HANDLE_BACKGROUND_VALUE(backgroundYPosition, BackgroundYPosition, value)
2392         return;
2393     }
2394     case CSS_PROP_BORDER_SPACING: {
2395         if (isInherit) {
2396             style->setHorizontalBorderSpacing(parentStyle->horizontalBorderSpacing());
2397             style->setVerticalBorderSpacing(parentStyle->verticalBorderSpacing());
2398         }
2399         else if (isInitial) {
2400             style->setHorizontalBorderSpacing(0);
2401             style->setVerticalBorderSpacing(0);
2402         }
2403         return;
2404     }
2405     case CSS_PROP__WEBKIT_BORDER_HORIZONTAL_SPACING: {
2406         HANDLE_INHERIT_AND_INITIAL(horizontalBorderSpacing, HorizontalBorderSpacing)
2407         if (!primitiveValue) return;
2408         short spacing =  primitiveValue->computeLengthShort(style);
2409         style->setHorizontalBorderSpacing(spacing);
2410         return;
2411     }
2412     case CSS_PROP__WEBKIT_BORDER_VERTICAL_SPACING: {
2413         HANDLE_INHERIT_AND_INITIAL(verticalBorderSpacing, VerticalBorderSpacing)
2414         if (!primitiveValue) return;
2415         short spacing =  primitiveValue->computeLengthShort(style);
2416         style->setVerticalBorderSpacing(spacing);
2417         return;
2418     }
2419     case CSS_PROP_CURSOR:
2420         if (isInherit) {
2421             style->setCursor(parentStyle->cursor());
2422             style->setCursorList(parentStyle->cursors());
2423             return;
2424         }
2425         style->clearCursorList();
2426         if (isInitial) {
2427             style->setCursor(RenderStyle::initialCursor());
2428             return;
2429         }
2430         if (value->isValueList()) {
2431             CSSValueList* list = static_cast<CSSValueList*>(value);
2432             int len = list->length();
2433             style->setCursor(CURSOR_AUTO);
2434             for (int i = 0; i < len; i++) {
2435                 CSSValue* item = list->item(i);
2436                 if (!item->isPrimitiveValue())
2437                     continue;
2438                 primitiveValue = static_cast<CSSPrimitiveValue*>(item);
2439                 int type = primitiveValue->primitiveType();
2440                 if (type == CSSPrimitiveValue::CSS_URI) {
2441 #if ENABLE(SVG)
2442                     if (primitiveValue->getStringValue().find("#") == 0)
2443                         style->addSVGCursor(primitiveValue->getStringValue().substring(1));
2444                     else
2445 #endif
2446                     {
2447                         CSSCursorImageValue* image = static_cast<CSSCursorImageValue*>(primitiveValue);
2448                         style->addCursor(image->image(element->document()->docLoader()), image->hotspot());
2449                     }
2450                 } else if (type == CSSPrimitiveValue::CSS_IDENT) {
2451                     int ident = primitiveValue->getIdent();
2452                     if (ident == CSS_VAL_COPY)
2453                         style->setCursor(CURSOR_COPY);
2454                     else if (ident == CSS_VAL_NONE)
2455                         style->setCursor(CURSOR_NONE);
2456                     else
2457                         style->setCursor((ECursor)(ident - CSS_VAL_AUTO));
2458                 }
2459             }
2460         } else if (primitiveValue) {
2461             int type = primitiveValue->primitiveType();
2462             if (type == CSSPrimitiveValue::CSS_IDENT) {
2463                 int ident = primitiveValue->getIdent();
2464                 if (ident == CSS_VAL_COPY)
2465                     style->setCursor(CURSOR_COPY);
2466                 else if (ident == CSS_VAL_NONE)
2467                     style->setCursor(CURSOR_NONE);
2468                 else
2469                     style->setCursor((ECursor)(ident - CSS_VAL_AUTO));
2470             }
2471         }
2472         return;
2473 // colors || inherit
2474     case CSS_PROP_BACKGROUND_COLOR:
2475     case CSS_PROP_BORDER_TOP_COLOR:
2476     case CSS_PROP_BORDER_RIGHT_COLOR:
2477     case CSS_PROP_BORDER_BOTTOM_COLOR:
2478     case CSS_PROP_BORDER_LEFT_COLOR:
2479     case CSS_PROP_COLOR:
2480     case CSS_PROP_OUTLINE_COLOR:
2481     case CSS_PROP__WEBKIT_COLUMN_RULE_COLOR:
2482     case CSS_PROP__WEBKIT_TEXT_STROKE_COLOR:
2483     case CSS_PROP__WEBKIT_TEXT_FILL_COLOR: {
2484         Color col;
2485         if (isInherit) {
2486             HANDLE_INHERIT_COND(CSS_PROP_BACKGROUND_COLOR, backgroundColor, BackgroundColor)
2487             HANDLE_INHERIT_COND(CSS_PROP_BORDER_TOP_COLOR, borderTopColor, BorderTopColor)
2488             HANDLE_INHERIT_COND(CSS_PROP_BORDER_BOTTOM_COLOR, borderBottomColor, BorderBottomColor)
2489             HANDLE_INHERIT_COND(CSS_PROP_BORDER_RIGHT_COLOR, borderRightColor, BorderRightColor)
2490             HANDLE_INHERIT_COND(CSS_PROP_BORDER_LEFT_COLOR, borderLeftColor, BorderLeftColor)
2491             HANDLE_INHERIT_COND(CSS_PROP_COLOR, color, Color)
2492             HANDLE_INHERIT_COND(CSS_PROP_OUTLINE_COLOR, outlineColor, OutlineColor)
2493             HANDLE_INHERIT_COND(CSS_PROP__WEBKIT_COLUMN_RULE_COLOR, columnRuleColor, ColumnRuleColor)
2494             HANDLE_INHERIT_COND(CSS_PROP__WEBKIT_TEXT_STROKE_COLOR, textStrokeColor, TextStrokeColor)
2495             HANDLE_INHERIT_COND(CSS_PROP__WEBKIT_TEXT_FILL_COLOR, textFillColor, TextFillColor)
2496             return;
2497         }
2498         if (isInitial) {
2499             // The border/outline colors will just map to the invalid color |col| above.  This will have the
2500             // effect of forcing the use of the currentColor when it comes time to draw the borders (and of
2501             // not painting the background since the color won't be valid).
2502             if (id == CSS_PROP_COLOR)
2503                 col = RenderStyle::initialColor();
2504         } else {
2505             if (!primitiveValue)
2506                 return;
2507             col = getColorFromPrimitiveValue(primitiveValue);
2508         }
2509
2510         switch(id) {
2511         case CSS_PROP_BACKGROUND_COLOR:
2512             style->setBackgroundColor(col); break;
2513         case CSS_PROP_BORDER_TOP_COLOR:
2514             style->setBorderTopColor(col); break;
2515         case CSS_PROP_BORDER_RIGHT_COLOR:
2516             style->setBorderRightColor(col); break;
2517         case CSS_PROP_BORDER_BOTTOM_COLOR:
2518             style->setBorderBottomColor(col); break;
2519         case CSS_PROP_BORDER_LEFT_COLOR:
2520             style->setBorderLeftColor(col); break;
2521         case CSS_PROP_COLOR:
2522             style->setColor(col); break;
2523         case CSS_PROP_OUTLINE_COLOR:
2524             style->setOutlineColor(col); break;
2525         case CSS_PROP__WEBKIT_COLUMN_RULE_COLOR:
2526             style->setColumnRuleColor(col);
2527             break;
2528         case CSS_PROP__WEBKIT_TEXT_STROKE_COLOR:
2529             style->setTextStrokeColor(col);
2530             break;
2531         case CSS_PROP__WEBKIT_TEXT_FILL_COLOR:
2532             style->setTextFillColor(col);
2533             break;
2534         }
2535         
2536         return;
2537     }
2538     
2539 // uri || inherit
2540     case CSS_PROP_BACKGROUND_IMAGE:
2541         HANDLE_BACKGROUND_VALUE(backgroundImage, BackgroundImage, value)
2542         return;
2543     case CSS_PROP_LIST_STYLE_IMAGE:
2544     {
2545         HANDLE_INHERIT_AND_INITIAL(listStyleImage, ListStyleImage)
2546         if (!primitiveValue)
2547             return;
2548         style->setListStyleImage(static_cast<CSSImageValue*>(primitiveValue)->image(element->document()->docLoader()));
2549         return;
2550     }
2551
2552 // length
2553     case CSS_PROP_BORDER_TOP_WIDTH:
2554     case CSS_PROP_BORDER_RIGHT_WIDTH:
2555     case CSS_PROP_BORDER_BOTTOM_WIDTH:
2556     case CSS_PROP_BORDER_LEFT_WIDTH:
2557     case CSS_PROP_OUTLINE_WIDTH:
2558     case CSS_PROP__WEBKIT_COLUMN_RULE_WIDTH:
2559     {
2560         if (isInherit) {
2561             HANDLE_INHERIT_COND(CSS_PROP_BORDER_TOP_WIDTH, borderTopWidth, BorderTopWidth)
2562             HANDLE_INHERIT_COND(CSS_PROP_BORDER_RIGHT_WIDTH, borderRightWidth, BorderRightWidth)
2563             HANDLE_INHERIT_COND(CSS_PROP_BORDER_BOTTOM_WIDTH, borderBottomWidth, BorderBottomWidth)
2564             HANDLE_INHERIT_COND(CSS_PROP_BORDER_LEFT_WIDTH, borderLeftWidth, BorderLeftWidth)
2565             HANDLE_INHERIT_COND(CSS_PROP_OUTLINE_WIDTH, outlineWidth, OutlineWidth)
2566             HANDLE_INHERIT_COND(CSS_PROP__WEBKIT_COLUMN_RULE_WIDTH, columnRuleWidth, ColumnRuleWidth)
2567             return;
2568         }
2569         else if (isInitial) {
2570             HANDLE_INITIAL_COND_WITH_VALUE(CSS_PROP_BORDER_TOP_WIDTH, BorderTopWidth, BorderWidth)
2571             HANDLE_INITIAL_COND_WITH_VALUE(CSS_PROP_BORDER_RIGHT_WIDTH, BorderRightWidth, BorderWidth)
2572             HANDLE_INITIAL_COND_WITH_VALUE(CSS_PROP_BORDER_BOTTOM_WIDTH, BorderBottomWidth, BorderWidth)
2573             HANDLE_INITIAL_COND_WITH_VALUE(CSS_PROP_BORDER_LEFT_WIDTH, BorderLeftWidth, BorderWidth)
2574             HANDLE_INITIAL_COND_WITH_VALUE(CSS_PROP_OUTLINE_WIDTH, OutlineWidth, BorderWidth)
2575             HANDLE_INITIAL_COND_WITH_VALUE(CSS_PROP__WEBKIT_COLUMN_RULE_WIDTH, ColumnRuleWidth, BorderWidth)
2576             return;
2577         }
2578
2579         if(!primitiveValue) return;
2580         short width = 3;
2581         switch(primitiveValue->getIdent())
2582         {
2583         case CSS_VAL_THIN:
2584             width = 1;
2585             break;
2586         case CSS_VAL_MEDIUM:
2587             width = 3;
2588             break;
2589         case CSS_VAL_THICK:
2590             width = 5;
2591             break;
2592         case CSS_VAL_INVALID:
2593             width = primitiveValue->computeLengthShort(style);
2594             break;
2595         default:
2596             return;
2597         }
2598
2599         if(width < 0) return;
2600         switch(id)
2601         {
2602         case CSS_PROP_BORDER_TOP_WIDTH:
2603             style->setBorderTopWidth(width);
2604             break;
2605         case CSS_PROP_BORDER_RIGHT_WIDTH:
2606             style->setBorderRightWidth(width);
2607             break;
2608         case CSS_PROP_BORDER_BOTTOM_WIDTH:
2609             style->setBorderBottomWidth(width);
2610             break;
2611         case CSS_PROP_BORDER_LEFT_WIDTH:
2612             style->setBorderLeftWidth(width);
2613             break;
2614         case CSS_PROP_OUTLINE_WIDTH:
2615             style->setOutlineWidth(width);
2616             break;
2617         case CSS_PROP__WEBKIT_COLUMN_RULE_WIDTH:
2618             style->setColumnRuleWidth(width);
2619             break;
2620         default:
2621             return;
2622         }
2623         return;
2624     }
2625
2626     case CSS_PROP_LETTER_SPACING:
2627     case CSS_PROP_WORD_SPACING:
2628     {
2629         
2630         if (isInherit) {
2631             HANDLE_INHERIT_COND(CSS_PROP_LETTER_SPACING, letterSpacing, LetterSpacing)
2632             HANDLE_INHERIT_COND(CSS_PROP_WORD_SPACING, wordSpacing, WordSpacing)
2633             return;
2634         }
2635         else if (isInitial) {
2636             HANDLE_INITIAL_COND_WITH_VALUE(CSS_PROP_LETTER_SPACING, LetterSpacing, LetterWordSpacing)
2637             HANDLE_INITIAL_COND_WITH_VALUE(CSS_PROP_WORD_SPACING, WordSpacing, LetterWordSpacing)
2638             return;
2639         }
2640         
2641         int width = 0;
2642         if (primitiveValue && primitiveValue->getIdent() == CSS_VAL_NORMAL){
2643             width = 0;
2644         } else {
2645             if(!primitiveValue) return;
2646             width = primitiveValue->computeLengthInt(style);
2647         }
2648         switch(id)
2649         {
2650         case CSS_PROP_LETTER_SPACING:
2651             style->setLetterSpacing(width);
2652             break;
2653         case CSS_PROP_WORD_SPACING:
2654             style->setWordSpacing(width);
2655             break;
2656             // ### needs the definitions in renderstyle
2657         default: break;
2658         }
2659         return;
2660     }
2661
2662     case CSS_PROP_WORD_WRAP:
2663     {
2664         HANDLE_INHERIT_AND_INITIAL(wordWrap, WordWrap)
2665
2666         if(!primitiveValue->getIdent()) return;
2667
2668         EWordWrap s;
2669         switch(primitiveValue->getIdent()) {
2670         case CSS_VAL_BREAK_WORD:
2671             s = BREAK_WORD;
2672             break;
2673         case CSS_VAL_NORMAL:
2674         default:
2675             s = WBNORMAL;
2676             break;
2677         }
2678         style->setWordWrap(s);
2679         return;
2680     }
2681
2682     case CSS_PROP__WEBKIT_NBSP_MODE:
2683     {
2684         HANDLE_INHERIT_AND_INITIAL(nbspMode, NBSPMode)
2685
2686         if (!primitiveValue->getIdent()) return;
2687
2688         ENBSPMode m;
2689         switch(primitiveValue->getIdent()) {
2690         case CSS_VAL_SPACE:
2691             m = SPACE;
2692             break;
2693         case CSS_VAL_NORMAL:
2694         default:
2695             m = NBNORMAL;
2696             break;
2697         }
2698         style->setNBSPMode(m);
2699         return;
2700     }
2701
2702     case CSS_PROP__WEBKIT_LINE_BREAK:
2703     {
2704         HANDLE_INHERIT_AND_INITIAL(khtmlLineBreak, KHTMLLineBreak)
2705
2706         if (!primitiveValue->getIdent()) return;
2707
2708         EKHTMLLineBreak b;
2709         switch(primitiveValue->getIdent()) {
2710         case CSS_VAL_AFTER_WHITE_SPACE:
2711             b = AFTER_WHITE_SPACE;
2712             break;
2713         case CSS_VAL_NORMAL:
2714         default:
2715             b = LBNORMAL;
2716             break;
2717         }
2718         style->setKHTMLLineBreak(b);
2719         return;
2720     }
2721
2722     case CSS_PROP__WEBKIT_MATCH_NEAREST_MAIL_BLOCKQUOTE_COLOR:
2723     {
2724         HANDLE_INHERIT_AND_INITIAL(matchNearestMailBlockquoteColor, MatchNearestMailBlockquoteColor)
2725
2726         if (!primitiveValue->getIdent()) return;
2727
2728         EMatchNearestMailBlockquoteColor c;
2729         switch(primitiveValue->getIdent()) {
2730         case CSS_VAL_NORMAL:
2731             c = BCNORMAL;
2732             break;
2733         case CSS_VAL_MATCH:
2734         default:
2735             c = MATCH;
2736             break;
2737         }
2738         style->setMatchNearestMailBlockquoteColor(c);
2739         return;
2740     }
2741
2742     case CSS_PROP_RESIZE:
2743     {
2744         HANDLE_INHERIT_AND_INITIAL(resize, Resize)
2745
2746         if (!primitiveValue->getIdent()) return;
2747
2748         EResize r;
2749         switch(primitiveValue->getIdent()) {
2750         case CSS_VAL_BOTH:
2751             r = RESIZE_BOTH;
2752             break;
2753         case CSS_VAL_HORIZONTAL:
2754             r = RESIZE_HORIZONTAL;
2755             break;
2756         case CSS_VAL_VERTICAL:
2757             r = RESIZE_VERTICAL;
2758             break;
2759         case CSS_VAL_AUTO:
2760             r = settings->textAreasAreResizable() ? RESIZE_BOTH : RESIZE_NONE;
2761             break;
2762         case CSS_VAL_NONE:
2763         default:
2764             r = RESIZE_NONE;
2765             break;
2766         }
2767         style->setResize(r);
2768         return;
2769     }
2770     
2771     // length, percent
2772     case CSS_PROP_MAX_WIDTH:
2773         // +none +inherit
2774         if(primitiveValue && primitiveValue->getIdent() == CSS_VAL_NONE)
2775             apply = true;
2776     case CSS_PROP_TOP:
2777     case CSS_PROP_LEFT:
2778     case CSS_PROP_RIGHT:
2779     case CSS_PROP_BOTTOM:
2780     case CSS_PROP_WIDTH:
2781     case CSS_PROP_MIN_WIDTH:
2782     case CSS_PROP_MARGIN_TOP:
2783     case CSS_PROP_MARGIN_RIGHT:
2784     case CSS_PROP_MARGIN_BOTTOM:
2785     case CSS_PROP_MARGIN_LEFT:
2786         // +inherit +auto
2787         if (id == CSS_PROP_WIDTH || id == CSS_PROP_MIN_WIDTH || id == CSS_PROP_MAX_WIDTH) {
2788             if (primitiveValue && primitiveValue->getIdent() == CSS_VAL_INTRINSIC) {
2789                 l = Length(Intrinsic);
2790                 apply = true;
2791             }
2792             else if (primitiveValue && primitiveValue->getIdent() == CSS_VAL_MIN_INTRINSIC) {
2793                 l = Length(MinIntrinsic);
2794                 apply = true;
2795             }
2796         }
2797         if (id != CSS_PROP_MAX_WIDTH && primitiveValue && primitiveValue->getIdent() == CSS_VAL_AUTO)
2798             apply = true;
2799     case CSS_PROP_PADDING_TOP:
2800     case CSS_PROP_PADDING_RIGHT:
2801     case CSS_PROP_PADDING_BOTTOM:
2802     case CSS_PROP_PADDING_LEFT:
2803     case CSS_PROP_TEXT_INDENT:
2804         // +inherit
2805     {
2806         if (isInherit) {
2807             HANDLE_INHERIT_COND(CSS_PROP_MAX_WIDTH, maxWidth, MaxWidth)
2808             HANDLE_INHERIT_COND(CSS_PROP_BOTTOM, bottom, Bottom)
2809             HANDLE_INHERIT_COND(CSS_PROP_TOP, top, Top)
2810             HANDLE_INHERIT_COND(CSS_PROP_LEFT, left, Left)
2811             HANDLE_INHERIT_COND(CSS_PROP_RIGHT, right, Right)
2812             HANDLE_INHERIT_COND(CSS_PROP_WIDTH, width, Width)
2813             HANDLE_INHERIT_COND(CSS_PROP_MIN_WIDTH, minWidth, MinWidth)
2814             HANDLE_INHERIT_COND(CSS_PROP_PADDING_TOP, paddingTop, PaddingTop)
2815             HANDLE_INHERIT_COND(CSS_PROP_PADDING_RIGHT, paddingRight, PaddingRight)
2816             HANDLE_INHERIT_COND(CSS_PROP_PADDING_BOTTOM, paddingBottom, PaddingBottom)
2817             HANDLE_INHERIT_COND(CSS_PROP_PADDING_LEFT, paddingLeft, PaddingLeft)
2818             HANDLE_INHERIT_COND(CSS_PROP_MARGIN_TOP, marginTop, MarginTop)
2819             HANDLE_INHERIT_COND(CSS_PROP_MARGIN_RIGHT, marginRight, MarginRight)
2820             HANDLE_INHERIT_COND(CSS_PROP_MARGIN_BOTTOM, marginBottom, MarginBottom)
2821             HANDLE_INHERIT_COND(CSS_PROP_MARGIN_LEFT, marginLeft, MarginLeft)
2822             HANDLE_INHERIT_COND(CSS_PROP_TEXT_INDENT, textIndent, TextIndent)
2823             return;
2824         }
2825         else if (isInitial) {
2826             HANDLE_INITIAL_COND_WITH_VALUE(CSS_PROP_MAX_WIDTH, MaxWidth, MaxSize)
2827             HANDLE_INITIAL_COND_WITH_VALUE(CSS_PROP_BOTTOM, Bottom, Offset)
2828             HANDLE_INITIAL_COND_WITH_VALUE(CSS_PROP_TOP, Top, Offset)
2829             HANDLE_INITIAL_COND_WITH_VALUE(CSS_PROP_LEFT, Left, Offset)
2830             HANDLE_INITIAL_COND_WITH_VALUE(CSS_PROP_RIGHT, Right, Offset)
2831             HANDLE_INITIAL_COND_WITH_VALUE(CSS_PROP_WIDTH, Width, Size)
2832             HANDLE_INITIAL_COND_WITH_VALUE(CSS_PROP_MIN_WIDTH, MinWidth, MinSize)
2833             HANDLE_INITIAL_COND_WITH_VALUE(CSS_PROP_PADDING_TOP, PaddingTop, Padding)
2834             HANDLE_INITIAL_COND_WITH_VALUE(CSS_PROP_PADDING_RIGHT, PaddingRight, Padding)
2835             HANDLE_INITIAL_COND_WITH_VALUE(CSS_PROP_PADDING_BOTTOM, PaddingBottom, Padding)
2836             HANDLE_INITIAL_COND_WITH_VALUE(CSS_PROP_PADDING_LEFT, PaddingLeft, Padding)
2837             HANDLE_INITIAL_COND_WITH_VALUE(CSS_PROP_MARGIN_TOP, MarginTop, Margin)
2838             HANDLE_INITIAL_COND_WITH_VALUE(CSS_PROP_MARGIN_RIGHT, MarginRight, Margin)
2839             HANDLE_INITIAL_COND_WITH_VALUE(CSS_PROP_MARGIN_BOTTOM, MarginBottom, Margin)
2840             HANDLE_INITIAL_COND_WITH_VALUE(CSS_PROP_MARGIN_LEFT, MarginLeft, Margin)
2841             HANDLE_INITIAL_COND(CSS_PROP_TEXT_INDENT, TextIndent)
2842             return;
2843         } 
2844
2845         if (primitiveValue && !apply) {
2846             int type = primitiveValue->primitiveType();
2847             if(type > CSSPrimitiveValue::CSS_PERCENTAGE && type < CSSPrimitiveValue::CSS_DEG)
2848                 // Handle our quirky margin units if we have them.
2849                 l = Length(primitiveValue->computeLengthIntForLength(style), Fixed, 
2850                            primitiveValue->isQuirkValue());
2851             else if(type == CSSPrimitiveValue::CSS_PERCENTAGE)
2852                 l = Length(primitiveValue->getFloatValue(), Percent);
2853             else
2854                 return;
2855             if (id == CSS_PROP_PADDING_LEFT || id == CSS_PROP_PADDING_RIGHT ||
2856                 id == CSS_PROP_PADDING_TOP || id == CSS_PROP_PADDING_BOTTOM)
2857                 // Padding can't be negative
2858                 apply = !((l.isFixed() || l.isPercent()) && l.calcValue(100) < 0);
2859             else
2860                 apply = true;
2861         }
2862         if(!apply) return;
2863         switch(id)
2864             {
2865             case CSS_PROP_MAX_WIDTH:
2866                 style->setMaxWidth(l); break;
2867             case CSS_PROP_BOTTOM:
2868                 style->setBottom(l); break;
2869             case CSS_PROP_TOP:
2870                 style->setTop(l); break;
2871             case CSS_PROP_LEFT:
2872                 style->setLeft(l); break;
2873             case CSS_PROP_RIGHT:
2874                 style->setRight(l); break;
2875             case CSS_PROP_WIDTH:
2876                 style->setWidth(l); break;
2877             case CSS_PROP_MIN_WIDTH:
2878                 style->setMinWidth(l); break;
2879             case CSS_PROP_PADDING_TOP:
2880                 style->setPaddingTop(l); break;
2881             case CSS_PROP_PADDING_RIGHT:
2882                 style->setPaddingRight(l); break;
2883             case CSS_PROP_PADDING_BOTTOM:
2884                 style->setPaddingBottom(l); break;
2885             case CSS_PROP_PADDING_LEFT:
2886                 style->setPaddingLeft(l); break;
2887             case CSS_PROP_MARGIN_TOP:
2888                 style->setMarginTop(l); break;
2889             case CSS_PROP_MARGIN_RIGHT:
2890                 style->setMarginRight(l); break;
2891             case CSS_PROP_MARGIN_BOTTOM:
2892                 style->setMarginBottom(l); break;
2893             case CSS_PROP_MARGIN_LEFT:
2894                 style->setMarginLeft(l); break;
2895             case CSS_PROP_TEXT_INDENT:
2896                 style->setTextIndent(l); break;
2897             default: break;
2898             }
2899         return;
2900     }
2901
2902     case CSS_PROP_MAX_HEIGHT:
2903         if (primitiveValue && primitiveValue->getIdent() == CSS_VAL_NONE) {
2904             l = Length(undefinedLength, Fixed);
2905             apply = true;
2906         }
2907     case CSS_PROP_HEIGHT:
2908     case CSS_PROP_MIN_HEIGHT:
2909         if (primitiveValue && primitiveValue->getIdent() == CSS_VAL_INTRINSIC) {
2910             l = Length(Intrinsic);
2911             apply = true;
2912         } else if (primitiveValue && primitiveValue->getIdent() == CSS_VAL_MIN_INTRINSIC) {
2913             l = Length(MinIntrinsic);
2914             apply = true;
2915         } else if (id != CSS_PROP_MAX_HEIGHT && primitiveValue && primitiveValue->getIdent() == CSS_VAL_AUTO)
2916             apply = true;
2917         if (isInherit) {
2918             HANDLE_INHERIT_COND(CSS_PROP_MAX_HEIGHT, maxHeight, MaxHeight)
2919             HANDLE_INHERIT_COND(CSS_PROP_HEIGHT, height, Height)
2920             HANDLE_INHERIT_COND(CSS_PROP_MIN_HEIGHT, minHeight, MinHeight)
2921             return;
2922         }
2923         if (isInitial) {
2924             HANDLE_INITIAL_COND_WITH_VALUE(CSS_PROP_MAX_HEIGHT, MaxHeight, MaxSize)
2925             HANDLE_INITIAL_COND_WITH_VALUE(CSS_PROP_HEIGHT, Height, Size)
2926             HANDLE_INITIAL_COND_WITH_VALUE(CSS_PROP_MIN_HEIGHT, MinHeight, MinSize)
2927             return;
2928         }
2929
2930         if (primitiveValue && !apply) {
2931             unsigned short type = primitiveValue->primitiveType();
2932             if (type > CSSPrimitiveValue::CSS_PERCENTAGE && type < CSSPrimitiveValue::CSS_DEG)
2933                 l = Length(primitiveValue->computeLengthIntForLength(style), Fixed);
2934             else if (type == CSSPrimitiveValue::CSS_PERCENTAGE)
2935                 l = Length(primitiveValue->getFloatValue(), Percent);
2936             else
2937                 return;
2938             apply = true;
2939         }
2940         if (apply)
2941             switch (id) {
2942                 case CSS_PROP_MAX_HEIGHT:
2943                     style->setMaxHeight(l);
2944                     break;
2945                 case CSS_PROP_HEIGHT:
2946                     style->setHeight(l);
2947                     break;
2948                 case CSS_PROP_MIN_HEIGHT:
2949                     style->setMinHeight(l);
2950                     break;
2951             }
2952         return;
2953
2954     case CSS_PROP_VERTICAL_ALIGN:
2955         HANDLE_INHERIT_AND_INITIAL(verticalAlign, VerticalAlign)
2956         if (!primitiveValue) return;
2957         if (primitiveValue->getIdent()) {
2958           EVerticalAlign align;
2959
2960           switch(primitiveValue->getIdent())
2961             {
2962                 case CSS_VAL_TOP:
2963                     align = TOP; break;
2964                 case CSS_VAL_BOTTOM:
2965                     align = BOTTOM; break;
2966                 case CSS_VAL_MIDDLE:
2967                     align = MIDDLE; break;
2968                 case CSS_VAL_BASELINE:
2969                     align = BASELINE; break;
2970                 case CSS_VAL_TEXT_BOTTOM:
2971                     align = TEXT_BOTTOM; break;
2972                 case CSS_VAL_TEXT_TOP:
2973                     align = TEXT_TOP; break;
2974                 case CSS_VAL_SUB:
2975                     align = SUB; break;
2976                 case CSS_VAL_SUPER:
2977                     align = SUPER; break;
2978                 case CSS_VAL__WEBKIT_BASELINE_MIDDLE:
2979                     align = BASELINE_MIDDLE; break;
2980                 default:
2981                     return;
2982             }
2983           style->setVerticalAlign(align);
2984           return;
2985         } else {
2986           int type = primitiveValue->primitiveType();
2987           Length l;
2988           if(type > CSSPrimitiveValue::CSS_PERCENTAGE && type < CSSPrimitiveValue::CSS_DEG)
2989             l = Length(primitiveValue->computeLengthIntForLength(style), Fixed);
2990           else if(type == CSSPrimitiveValue::CSS_PERCENTAGE)
2991             l = Length(primitiveValue->getFloatValue(), Percent);
2992
2993           style->setVerticalAlign(LENGTH);
2994           style->setVerticalAlignLength(l);
2995         }
2996         return;
2997
2998     case CSS_PROP_FONT_SIZE:
2999     {
3000         FontDescription fontDescription = style->fontDescription();
3001         fontDescription.setKeywordSize(0);
3002         bool familyIsFixed = fontDescription.genericFamily() == FontDescription::MonospaceFamily;
3003         float oldSize = 0;
3004         float size = 0;
3005         
3006         bool parentIsAbsoluteSize = false;
3007         if (parentNode) {
3008             oldSize = parentStyle->fontDescription().specifiedSize();
3009             parentIsAbsoluteSize = parentStyle->fontDescription().isAbsoluteSize();
3010         }
3011
3012         if (isInherit) {
3013             size = oldSize;
3014             if (parentNode)
3015                 fontDescription.setKeywordSize(parentStyle->fontDescription().keywordSize());
3016         } else if (isInitial) {
3017             size = fontSizeForKeyword(CSS_VAL_MEDIUM, style->htmlHacks(), familyIsFixed);
3018             fontDescription.setKeywordSize(CSS_VAL_MEDIUM - CSS_VAL_XX_SMALL + 1);
3019         } else if (primitiveValue->getIdent()) {
3020             // Keywords are being used.
3021             switch (primitiveValue->getIdent()) {
3022                 case CSS_VAL_XX_SMALL:
3023                 case CSS_VAL_X_SMALL:
3024                 case CSS_VAL_SMALL:
3025                 case CSS_VAL_MEDIUM:
3026                 case CSS_VAL_LARGE:
3027                 case CSS_VAL_X_LARGE:
3028                 case CSS_VAL_XX_LARGE:
3029                 case CSS_VAL__WEBKIT_XXX_LARGE:
3030                     size = fontSizeForKeyword(primitiveValue->getIdent(), style->htmlHacks(), familyIsFixed);
3031                     fontDescription.setKeywordSize(primitiveValue->getIdent() - CSS_VAL_XX_SMALL + 1);
3032                     break;
3033                 case CSS_VAL_LARGER:
3034                     size = largerFontSize(oldSize, style->htmlHacks());
3035                     break;
3036                 case CSS_VAL_SMALLER:
3037                     size = smallerFontSize(oldSize, style->htmlHacks());
3038                     break;
3039                 default:
3040                     return;
3041             }
3042
3043             fontDescription.setIsAbsoluteSize(parentIsAbsoluteSize && 
3044                                               (primitiveValue->getIdent() == CSS_VAL_LARGER ||
3045                                                primitiveValue->getIdent() == CSS_VAL_SMALLER));
3046         } else {
3047             int type = primitiveValue->primitiveType();
3048             fontDescription.setIsAbsoluteSize(parentIsAbsoluteSize ||
3049                                               (type != CSSPrimitiveValue::CSS_PERCENTAGE &&
3050                                                type != CSSPrimitiveValue::CSS_EMS && 
3051                                                type != CSSPrimitiveValue::CSS_EXS));
3052             if (type > CSSPrimitiveValue::CSS_PERCENTAGE && type < CSSPrimitiveValue::CSS_DEG)
3053                 size = primitiveValue->computeLengthFloat(parentStyle, false);
3054             else if(type == CSSPrimitiveValue::CSS_PERCENTAGE)
3055                 size = (primitiveValue->getFloatValue() * oldSize) / 100;
3056             else
3057                 return;
3058         }
3059
3060         if (size < 0)
3061             return;
3062
3063         setFontSize(fontDescription, size);
3064         if (style->setFontDescription(fontDescription))
3065             fontDirty = true;
3066         return;
3067     }
3068
3069     case CSS_PROP_Z_INDEX: {
3070         if (isInherit) {
3071             if (parentStyle->hasAutoZIndex())
3072                 style->setHasAutoZIndex();
3073             else
3074                 style->setZIndex(parentStyle->zIndex());
3075             return;
3076         } else if (isInitial || primitiveValue->getIdent() == CSS_VAL_AUTO) {
3077             style->setHasAutoZIndex();
3078             return;
3079         }
3080         style->setZIndex((int)primitiveValue->getFloatValue());
3081         return;
3082     }
3083     case CSS_PROP_WIDOWS:
3084     {
3085         HANDLE_INHERIT_AND_INITIAL(widows, Widows)
3086         if (!primitiveValue || primitiveValue->primitiveType() != CSSPrimitiveValue::CSS_NUMBER)
3087             return;
3088         style->setWidows((int)primitiveValue->getFloatValue());
3089         return;
3090     }
3091         
3092     case CSS_PROP_ORPHANS:
3093     {
3094         HANDLE_INHERIT_AND_INITIAL(orphans, Orphans)
3095         if (!primitiveValue || primitiveValue->primitiveType() != CSSPrimitiveValue::CSS_NUMBER)
3096             return;
3097         style->setOrphans((int)primitiveValue->getFloatValue());
3098         return;
3099     }        
3100
3101 // length, percent, number
3102     case CSS_PROP_LINE_HEIGHT:
3103     {
3104         HANDLE_INHERIT_AND_INITIAL(lineHeight, LineHeight)
3105         if(!primitiveValue) return;
3106         Length lineHeight;
3107         int type = primitiveValue->primitiveType();
3108         if (primitiveValue->getIdent() == CSS_VAL_NORMAL)
3109             lineHeight = Length(-100.0, Percent);
3110         else if (type > CSSPrimitiveValue::CSS_PERCENTAGE && type < CSSPrimitiveValue::CSS_DEG) {
3111             double multiplier = 1.0;
3112             // Scale for the font zoom factor only for types other than "em" and "ex", since those are
3113             // already based on the font size.
3114             if (type != CSSPrimitiveValue::CSS_EMS && type != CSSPrimitiveValue::CSS_EXS && view && view->frame()) {
3115                 multiplier = view->frame()->zoomFactor() / 100.0;
3116             }
3117             lineHeight = Length(primitiveValue->computeLengthIntForLength(style, multiplier), Fixed);
3118         } else if (type == CSSPrimitiveValue::CSS_PERCENTAGE)
3119             lineHeight = Length((style->fontSize() * int(primitiveValue->getFloatValue())) / 100, Fixed);
3120         else if (type == CSSPrimitiveValue::CSS_NUMBER)
3121             lineHeight = Length(primitiveValue->getFloatValue() * 100.0, Percent);
3122         else
3123             return;
3124         style->setLineHeight(lineHeight);
3125         return;
3126     }
3127
3128 // string
3129     case CSS_PROP_TEXT_ALIGN:
3130     {
3131         HANDLE_INHERIT_AND_INITIAL(textAlign, TextAlign)
3132         if (!primitiveValue) return;
3133         if (primitiveValue->getIdent())
3134             style->setTextAlign((ETextAlign) (primitiveValue->getIdent() - CSS_VAL__WEBKIT_AUTO));
3135         return;
3136     }
3137
3138 // rect
3139     case CSS_PROP_CLIP:
3140     {
3141         Length top;
3142         Length right;
3143         Length bottom;
3144         Length left;
3145         bool hasClip = true;
3146         if (isInherit) {
3147             if (parentStyle->hasClip()) {
3148                 top = parentStyle->clipTop();
3149                 right = parentStyle->clipRight();
3150                 bottom = parentStyle->clipBottom();
3151                 left = parentStyle->clipLeft();
3152             }
3153             else {
3154                 hasClip = false;
3155                 top = right = bottom = left = Length();
3156             }
3157         } else if (isInitial) {
3158             hasClip = false;
3159             top = right = bottom = left = Length();
3160         } else if (!primitiveValue) {
3161             return;
3162         } else if (primitiveValue->primitiveType() == CSSPrimitiveValue::CSS_RECT) {
3163             RectImpl* rect = primitiveValue->getRectValue();
3164             if (!rect)
3165                 return;
3166             top = convertToLength(rect->top(), style);
3167             right = convertToLength(rect->right(), style);
3168             bottom = convertToLength(rect->bottom(), style);
3169             left = convertToLength(rect->left(), style);
3170
3171         } else if (primitiveValue->getIdent() != CSS_VAL_AUTO) {
3172             return;
3173         }
3174         style->setClip(top, right, bottom, left);
3175         style->setHasClip(hasClip);
3176     
3177         // rect, ident
3178         return;
3179     }
3180
3181 // lists
3182     case CSS_PROP_CONTENT:
3183         // list of string, uri, counter, attr, i
3184     {
3185         // FIXME: In CSS3, it will be possible to inherit content.  In CSS2 it is not.  This
3186         // note is a reminder that eventually "inherit" needs to be supported.
3187
3188         if (isInitial) {
3189             style->clearContent();
3190             return;
3191         }
3192         
3193         if (!value->isValueList())
3194             return;
3195
3196         CSSValueList* list = static_cast<CSSValueList*>(value);
3197         int len = list->length();
3198
3199         bool didSet = false;
3200         for (int i = 0; i < len; i++) {
3201             CSSValue* item = list->item(i);
3202             if (!item->isPrimitiveValue())
3203                 continue;
3204             
3205             CSSPrimitiveValue* val = static_cast<CSSPrimitiveValue*>(item);
3206             switch (val->primitiveType()) {
3207                 case CSSPrimitiveValue::CSS_STRING:
3208                     style->setContent(val->getStringValue().impl(), didSet);
3209                     didSet = true;
3210                     break;
3211                 case CSSPrimitiveValue::CSS_ATTR: {
3212                     // FIXME: Can a namespace be specified for an attr(foo)?
3213                     if (style->styleType() == RenderStyle::NOPSEUDO)
3214                         style->setUnique();
3215                     else
3216                         parentStyle->setUnique();
3217                     QualifiedName attr(nullAtom, val->getStringValue().impl(), nullAtom);
3218                     style->setContent(element->getAttribute(attr).impl(), didSet);
3219                     didSet = true;
3220                     // register the fact that the attribute value affects the style
3221                     m_selectorAttrs.add(attr.localName().impl());
3222                     break;
3223                 }
3224                 case CSSPrimitiveValue::CSS_URI: {
3225                     CSSImageValue *image = static_cast<CSSImageValue*>(val);
3226                     style->setContent(image->image(element->document()->docLoader()), didSet);
3227                     didSet = true;
3228                     break;
3229                 }
3230                 case CSSPrimitiveValue::CSS_COUNTER: {
3231                     Counter* counterValue = val->getCounterValue();
3232                     CounterContent* counter = new CounterContent(counterValue->identifier(),
3233                         (EListStyleType)counterValue->listStyleNumber(), counterValue->separator());
3234                     style->setContent(counter, didSet);
3235                     didSet = true;
3236                 }
3237             }
3238         }
3239         if (!didSet)
3240             style->clearContent();
3241         return;
3242     }
3243
3244     case CSS_PROP_COUNTER_INCREMENT:
3245         applyCounterList(style, value->isValueList() ? static_cast<CSSValueList*>(value) : 0, false);
3246         return;
3247     case CSS_PROP_COUNTER_RESET:
3248         applyCounterList(style, value->isValueList() ? static_cast<CSSValueList*>(value) : 0, true);
3249         return;
3250
3251     case CSS_PROP_FONT_FAMILY: {
3252         // list of strings and ids
3253         if (isInherit) {
3254             FontDescription parentFontDescription = parentStyle->fontDescription();
3255             FontDescription fontDescription = style->fontDescription();
3256             fontDescription.setGenericFamily(parentFontDescription.genericFamily());
3257             fontDescription.setFamily(parentFontDescription.firstFamily());
3258             if (style->setFontDescription(fontDescription))
3259                 fontDirty = true;
3260             return;
3261         }
3262         else if (isInitial) {
3263             FontDescription initialDesc = FontDescription();
3264             FontDescription fontDescription = style->fontDescription();
3265             // We need to adjust the size to account for the generic family change from monospace
3266             // to non-monospace.
3267             if (fontDescription.keywordSize() && fontDescription.genericFamily() == FontDescription::MonospaceFamily)
3268                 setFontSize(fontDescription, fontSizeForKeyword(CSS_VAL_XX_SMALL + fontDescription.keywordSize() - 1, style->htmlHacks(), false));
3269             fontDescription.setGenericFamily(initialDesc.genericFamily());
3270             fontDescription.setFamily(initialDesc.firstFamily());
3271             if (style->setFontDescription(fontDescription))
3272                 fontDirty = true;
3273             return;
3274         }
3275         
3276         if (!value->isValueList()) return;
3277         FontDescription fontDescription = style->fontDescription();
3278         CSSValueList *list = static_cast<CSSValueList*>(value);
3279         int len = list->length();
3280         FontFamily& firstFamily = fontDescription.firstFamily();
3281         FontFamily *currFamily = 0;
3282         
3283         // Before mapping in a new font-family property, we should reset the generic family.
3284         bool oldFamilyIsMonospace = fontDescription.genericFamily() == FontDescription::MonospaceFamily;
3285         fontDescription.setGenericFamily(FontDescription::NoFamily);
3286
3287         for(int i = 0; i < len; i++) {
3288             CSSValue *item = list->item(i);
3289             if(!item->isPrimitiveValue()) continue;
3290             CSSPrimitiveValue *val = static_cast<CSSPrimitiveValue*>(item);
3291             AtomicString face;
3292             if(val->primitiveType() == CSSPrimitiveValue::CSS_STRING)
3293                 face = static_cast<FontFamilyValue*>(val)->fontName();
3294             else if (val->primitiveType() == CSSPrimitiveValue::CSS_IDENT) {
3295                 switch (val->getIdent()) {
3296                     case CSS_VAL__WEBKIT_BODY:
3297                         face = settings->standardFontFamily();
3298                         break;
3299                     case CSS_VAL_SERIF:
3300                         face = settings->serifFontFamily();
3301                         fontDescription.setGenericFamily(FontDescription::SerifFamily);
3302                         break;
3303                     case CSS_VAL_SANS_SERIF:
3304                         face = settings->sansSerifFontFamily();
3305                         fontDescription.setGenericFamily(FontDescription::SansSerifFamily);
3306                         break;
3307                     case CSS_VAL_CURSIVE: