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