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