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