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