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