2 * Copyright (C) 1999 Lars Knoll (knoll@kde.org)
3 * (C) 2004-2005 Allan Sandfeld Jensen (kde@carewolf.com)
4 * Copyright (C) 2006, 2007 Nicholas Shanks (webkit@nickshanks.com)
5 * Copyright (C) 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012 Apple Inc. All rights reserved.
6 * Copyright (C) 2007 Alexey Proskuryakov <ap@webkit.org>
7 * Copyright (C) 2007, 2008 Eric Seidel <eric@webkit.org>
8 * Copyright (C) 2008, 2009 Torch Mobile Inc. All rights reserved. (http://www.torchmobile.com/)
9 * Copyright (c) 2011, Code Aurora Forum. All rights reserved.
10 * Copyright (C) Research In Motion Limited 2011. All rights reserved.
12 * This library is free software; you can redistribute it and/or
13 * modify it under the terms of the GNU Library General Public
14 * License as published by the Free Software Foundation; either
15 * version 2 of the License, or (at your option) any later version.
17 * This library is distributed in the hope that it will be useful,
18 * but WITHOUT ANY WARRANTY; without even the implied warranty of
19 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
20 * Library General Public License for more details.
22 * You should have received a copy of the GNU Library General Public License
23 * along with this library; see the file COPYING.LIB. If not, write to
24 * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
25 * Boston, MA 02110-1301, USA.
29 #include "CSSStyleSelector.h"
31 #include "Attribute.h"
32 #include "CachedImage.h"
33 #include "ContentData.h"
35 #include "CounterContent.h"
36 #include "CSSBorderImage.h"
37 #include "CSSCursorImageValue.h"
38 #include "CSSFontFaceRule.h"
39 #include "CSSFontSelector.h"
40 #include "CSSImportRule.h"
41 #include "CSSLineBoxContainValue.h"
42 #include "CSSMediaRule.h"
43 #include "CSSPageRule.h"
44 #include "CSSParser.h"
45 #include "CSSPrimitiveValueMappings.h"
46 #include "CSSPropertyNames.h"
47 #include "CSSReflectValue.h"
48 #include "CSSRuleList.h"
49 #include "CSSSelector.h"
50 #include "CSSSelectorList.h"
51 #include "CSSStyleApplyProperty.h"
52 #include "CSSStyleRule.h"
53 #include "CSSStyleSheet.h"
54 #include "CSSTimingFunctionValue.h"
55 #include "CSSValueList.h"
56 #include "CursorList.h"
57 #include "FontFamilyValue.h"
58 #include "FontFeatureValue.h"
59 #include "FontValue.h"
61 #include "FrameSelection.h"
62 #include "FrameView.h"
63 #include "HTMLDocument.h"
64 #include "HTMLElement.h"
65 #include "HTMLInputElement.h"
66 #include "HTMLNames.h"
67 #include "HTMLProgressElement.h"
68 #include "HTMLStyleElement.h"
69 #include "HTMLTextAreaElement.h"
70 #include "InspectorInstrumentation.h"
71 #include "KeyframeList.h"
73 #include "LocaleToScriptMapping.h"
74 #include "Matrix3DTransformOperation.h"
75 #include "MatrixTransformOperation.h"
76 #include "MediaList.h"
77 #include "MediaQueryEvaluator.h"
78 #include "NodeRenderStyle.h"
80 #include "PageGroup.h"
82 #include "PerspectiveTransformOperation.h"
83 #include "QuotesData.h"
85 #include "RenderRegion.h"
86 #include "RenderScrollbar.h"
87 #include "RenderScrollbarTheme.h"
88 #include "RenderStyleConstants.h"
89 #include "RenderTheme.h"
90 #include "RotateTransformOperation.h"
91 #include "ScaleTransformOperation.h"
92 #include "SecurityOrigin.h"
94 #include "ShadowData.h"
95 #include "ShadowValue.h"
96 #include "SkewTransformOperation.h"
97 #include "StyleCachedImage.h"
98 #include "StylePendingImage.h"
99 #include "StyleGeneratedImage.h"
100 #include "StyleSheetList.h"
102 #include "TransformationMatrix.h"
103 #include "TranslateTransformOperation.h"
104 #include "UserAgentStyleSheets.h"
105 #include "WebKitCSSKeyframeRule.h"
106 #include "WebKitCSSKeyframesRule.h"
107 #include "WebKitCSSRegionRule.h"
108 #include "WebKitCSSTransformValue.h"
109 #include "WebKitFontFamilyNames.h"
110 #include "XMLNames.h"
111 #include <wtf/StdLibExtras.h>
112 #include <wtf/Vector.h>
114 #if ENABLE(CSS_FILTERS)
115 #include "FilterOperation.h"
116 #include "WebKitCSSFilterValue.h"
119 #if ENABLE(DASHBOARD_SUPPORT)
120 #include "DashboardRegion.h"
124 #include "SVGNames.h"
127 #if ENABLE(CSS_SHADERS)
128 #include "CustomFilterNumberParameter.h"
129 #include "CustomFilterOperation.h"
130 #include "CustomFilterParameter.h"
131 #include "StyleCachedShader.h"
132 #include "StyleCustomFilterProgram.h"
133 #include "StylePendingShader.h"
134 #include "StyleShader.h"
135 #include "WebKitCSSShaderValue.h"
142 using namespace HTMLNames;
144 #define HANDLE_INHERIT(prop, Prop) \
146 m_style->set##Prop(m_parentStyle->prop()); \
150 #define HANDLE_INHERIT_AND_INITIAL(prop, Prop) \
151 HANDLE_INHERIT(prop, Prop) \
153 m_style->set##Prop(RenderStyle::initial##Prop()); \
157 #define HANDLE_INHERIT_AND_INITIAL_WITH_VALUE(prop, Prop, Value) \
158 HANDLE_INHERIT(prop, Prop) \
160 m_style->set##Prop(RenderStyle::initial##Value());\
164 #define HANDLE_INHERIT_AND_INITIAL_AND_PRIMITIVE(prop, Prop) \
165 HANDLE_INHERIT_AND_INITIAL(prop, Prop) \
166 if (primitiveValue) \
167 m_style->set##Prop(*primitiveValue);
169 #define HANDLE_INHERIT_AND_INITIAL_AND_PRIMITIVE_WITH_VALUE(prop, Prop, Value) \
170 HANDLE_INHERIT_AND_INITIAL_WITH_VALUE(prop, Prop, Value) \
171 if (primitiveValue) \
172 m_style->set##Prop(*primitiveValue);
176 RuleData(CSSStyleRule*, CSSSelector*, unsigned position);
178 unsigned position() const { return m_position; }
179 CSSStyleRule* rule() const { return m_rule; }
180 CSSSelector* selector() const { return m_selector; }
182 bool hasFastCheckableSelector() const { return m_hasFastCheckableSelector; }
183 bool hasMultipartSelector() const { return m_hasMultipartSelector; }
184 bool hasRightmostSelectorMatchingHTMLBasedOnRuleHash() const { return m_hasRightmostSelectorMatchingHTMLBasedOnRuleHash; }
185 bool containsUncommonAttributeSelector() const { return m_containsUncommonAttributeSelector; }
186 unsigned specificity() const { return m_specificity; }
187 unsigned linkMatchType() const { return m_linkMatchType; }
189 // Try to balance between memory usage (there can be lots of RuleData objects) and good filtering performance.
190 static const unsigned maximumIdentifierCount = 4;
191 const unsigned* descendantSelectorIdentifierHashes() const { return m_descendantSelectorIdentifierHashes; }
194 CSSStyleRule* m_rule;
195 CSSSelector* m_selector;
196 unsigned m_specificity;
197 // This number was picked fairly arbitrarily. We can probably lower it if we need to.
198 // Some simple testing showed <100,000 RuleData's on large sites.
199 unsigned m_position : 26;
200 unsigned m_hasFastCheckableSelector : 1;
201 unsigned m_hasMultipartSelector : 1;
202 unsigned m_hasRightmostSelectorMatchingHTMLBasedOnRuleHash : 1;
203 unsigned m_containsUncommonAttributeSelector : 1;
204 unsigned m_linkMatchType : 2; // SelectorChecker::LinkMatchMask
205 // Use plain array instead of a Vector to minimize memory overhead.
206 unsigned m_descendantSelectorIdentifierHashes[maximumIdentifierCount];
209 struct SameSizeAsRuleData {
217 COMPILE_ASSERT(sizeof(RuleData) == sizeof(SameSizeAsRuleData), RuleData_should_stay_small);
220 WTF_MAKE_NONCOPYABLE(RuleSet);
224 typedef HashMap<AtomicStringImpl*, OwnPtr<Vector<RuleData> > > AtomRuleMap;
226 void addRulesFromSheet(CSSStyleSheet*, const MediaQueryEvaluator&, CSSStyleSelector* = 0, const Element* = 0);
228 void addStyleRule(CSSStyleRule*);
229 void addRule(CSSStyleRule*, CSSSelector*);
230 void addPageRule(CSSPageRule*);
231 void addToRuleSet(AtomicStringImpl* key, AtomRuleMap&, const RuleData&);
232 void addRegionRule(WebKitCSSRegionRule*);
234 void disableAutoShrinkToFit() { m_autoShrinkToFitEnabled = false; }
236 const CSSStyleSelector::Features& features() const { return m_features; }
238 const Vector<RuleData>* idRules(AtomicStringImpl* key) const { return m_idRules.get(key); }
239 const Vector<RuleData>* classRules(AtomicStringImpl* key) const { return m_classRules.get(key); }
240 const Vector<RuleData>* tagRules(AtomicStringImpl* key) const { return m_tagRules.get(key); }
241 const Vector<RuleData>* shadowPseudoElementRules(AtomicStringImpl* key) const { return m_shadowPseudoElementRules.get(key); }
242 const Vector<RuleData>* linkPseudoClassRules() const { return &m_linkPseudoClassRules; }
243 const Vector<RuleData>* focusPseudoClassRules() const { return &m_focusPseudoClassRules; }
244 const Vector<RuleData>* universalRules() const { return &m_universalRules; }
245 const Vector<RuleData>* pageRules() const { return &m_pageRules; }
248 AtomRuleMap m_idRules;
249 AtomRuleMap m_classRules;
250 AtomRuleMap m_tagRules;
251 AtomRuleMap m_shadowPseudoElementRules;
252 Vector<RuleData> m_linkPseudoClassRules;
253 Vector<RuleData> m_focusPseudoClassRules;
254 Vector<RuleData> m_universalRules;
255 Vector<RuleData> m_pageRules;
256 unsigned m_ruleCount;
257 bool m_autoShrinkToFitEnabled;
258 CSSStyleSelector::Features m_features;
260 struct RuleSetSelectorPair {
261 RuleSetSelectorPair(CSSSelector* selector, RuleSet* ruleSet) : selector(selector), ruleSet(adoptPtr(ruleSet)) { }
262 RuleSetSelectorPair(const RuleSetSelectorPair& rs) : selector(rs.selector), ruleSet(const_cast<RuleSetSelectorPair*>(&rs)->ruleSet.release()) { }
263 CSSSelector* selector;
264 OwnPtr<RuleSet> ruleSet;
267 Vector<RuleSetSelectorPair> m_regionSelectorsAndRuleSets;
270 static RuleSet* defaultStyle;
271 static RuleSet* defaultQuirksStyle;
272 static RuleSet* defaultPrintStyle;
273 static RuleSet* defaultViewSourceStyle;
274 static CSSStyleSheet* simpleDefaultStyleSheet;
276 RenderStyle* CSSStyleSelector::s_styleNotYetAvailable;
278 static void loadFullDefaultStyle();
279 static void loadSimpleDefaultStyle();
280 // FIXME: It would be nice to use some mechanism that guarantees this is in sync with the real UA stylesheet.
281 static const char* simpleUserAgentStyleSheet = "html,body,div{display:block}head{display:none}body{margin:8px}div:focus,span:focus{outline:auto 5px -webkit-focus-ring-color}a:-webkit-any-link{color:-webkit-link;text-decoration:underline}a:-webkit-any-link:active{color:-webkit-activelink}";
283 static inline bool elementCanUseSimpleDefaultStyle(Element* e)
285 return e->hasTagName(htmlTag) || e->hasTagName(headTag) || e->hasTagName(bodyTag) || e->hasTagName(divTag) || e->hasTagName(spanTag) || e->hasTagName(brTag) || e->hasTagName(aTag);
288 static const MediaQueryEvaluator& screenEval()
290 DEFINE_STATIC_LOCAL(const MediaQueryEvaluator, staticScreenEval, ("screen"));
291 return staticScreenEval;
294 static const MediaQueryEvaluator& printEval()
296 DEFINE_STATIC_LOCAL(const MediaQueryEvaluator, staticPrintEval, ("print"));
297 return staticPrintEval;
300 static StylePropertySet* leftToRightDeclaration()
302 DEFINE_STATIC_LOCAL(RefPtr<StylePropertySet>, leftToRightDecl, (StylePropertySet::create()));
303 if (leftToRightDecl->isEmpty())
304 leftToRightDecl->setProperty(CSSPropertyDirection, CSSValueLtr);
305 return leftToRightDecl.get();
308 static StylePropertySet* rightToLeftDeclaration()
310 DEFINE_STATIC_LOCAL(RefPtr<StylePropertySet>, rightToLeftDecl, (StylePropertySet::create()));
311 if (rightToLeftDecl->isEmpty())
312 rightToLeftDecl->setProperty(CSSPropertyDirection, CSSValueRtl);
313 return rightToLeftDecl.get();
316 CSSStyleSelector::CSSStyleSelector(Document* document, StyleSheetList* styleSheets, CSSStyleSheet* mappedElementSheet,
317 CSSStyleSheet* pageUserSheet, const Vector<RefPtr<CSSStyleSheet> >* pageGroupUserSheets, const Vector<RefPtr<CSSStyleSheet> >* documentUserSheets,
318 bool strictParsing, bool matchAuthorAndUserStyles)
319 : m_hasUAAppearance(false)
320 , m_backgroundData(BackgroundFillLayer)
321 , m_matchedDeclarationCacheAdditionsSinceLastSweep(0)
322 , m_checker(document, strictParsing)
324 , m_rootElementStyle(0)
327 , m_regionForStyling(0)
328 , m_elementLinkState(NotInsideLink)
330 , m_lineHeightValue(0)
332 , m_matchAuthorAndUserStyles(matchAuthorAndUserStyles)
333 , m_sameOriginOnly(false)
334 , m_fontSelector(CSSFontSelector::create(document))
335 , m_applyPropertyToRegularStyle(true)
336 , m_applyPropertyToVisitedLinkStyle(false)
337 , m_applyProperty(CSSStyleApplyProperty::sharedCSSStyleApplyProperty())
338 #if ENABLE(CSS_SHADERS)
339 , m_hasPendingShaders(false)
341 #if ENABLE(STYLE_SCOPED)
342 , m_scopingElementStackParent(0)
345 Element* root = document->documentElement();
348 if (!root || elementCanUseSimpleDefaultStyle(root))
349 loadSimpleDefaultStyle();
351 loadFullDefaultStyle();
355 // construct document root element default style. this is needed
356 // to evaluate media queries that contain relative constraints, like "screen and (max-width: 10em)"
357 // This is here instead of constructor, because when constructor is run,
358 // document doesn't have documentElement
359 // NOTE: this assumes that element that gets passed to styleForElement -call
360 // is always from the document that owns the style selector
361 FrameView* view = document->view();
363 m_medium = adoptPtr(new MediaQueryEvaluator(view->mediaType()));
365 m_medium = adoptPtr(new MediaQueryEvaluator("all"));
368 m_rootDefaultStyle = styleForElement(root, 0, false, true); // don't ref, because the RenderStyle is allocated from global heap
370 if (m_rootDefaultStyle && view)
371 m_medium = adoptPtr(new MediaQueryEvaluator(view->mediaType(), view->frame(), m_rootDefaultStyle.get()));
373 m_authorStyle = adoptPtr(new RuleSet);
374 // Adding rules from multiple sheets, shrink at the end.
375 // Adding global rules from multiple sheets, shrink at the end.
376 // Note that there usually is only 1 sheet for scoped rules, so auto-shrink-to-fit is fine.
377 m_authorStyle->disableAutoShrinkToFit();
379 // FIXME: This sucks! The user sheet is reparsed every time!
380 OwnPtr<RuleSet> tempUserStyle = adoptPtr(new RuleSet);
382 tempUserStyle->addRulesFromSheet(pageUserSheet, *m_medium, this);
383 if (pageGroupUserSheets) {
384 unsigned length = pageGroupUserSheets->size();
385 for (unsigned i = 0; i < length; i++) {
386 if (pageGroupUserSheets->at(i)->isUserStyleSheet())
387 tempUserStyle->addRulesFromSheet(pageGroupUserSheets->at(i).get(), *m_medium, this);
389 m_authorStyle->addRulesFromSheet(pageGroupUserSheets->at(i).get(), *m_medium, this);
392 if (documentUserSheets) {
393 unsigned length = documentUserSheets->size();
394 for (unsigned i = 0; i < length; i++) {
395 if (documentUserSheets->at(i)->isUserStyleSheet())
396 tempUserStyle->addRulesFromSheet(documentUserSheets->at(i).get(), *m_medium, this);
398 m_authorStyle->addRulesFromSheet(documentUserSheets->at(i).get(), *m_medium, this);
402 if (tempUserStyle->m_ruleCount > 0 || tempUserStyle->m_pageRules.size() > 0)
403 m_userStyle = tempUserStyle.release();
405 // Add rules from elements like SVG's <font-face>
406 if (mappedElementSheet) {
407 // FIXME: see if style scopes can/should be added here.
408 m_authorStyle->addRulesFromSheet(mappedElementSheet, *m_medium, this);
411 // add stylesheets from document
412 appendAuthorStylesheets(0, styleSheets->vector());
415 static PassOwnPtr<RuleSet> makeRuleSet(const Vector<CSSStyleSelector::RuleSelectorPair>& rules)
417 size_t size = rules.size();
420 OwnPtr<RuleSet> ruleSet = adoptPtr(new RuleSet);
421 for (size_t i = 0; i < size; ++i)
422 ruleSet->addRule(rules[i].rule, rules[i].selector);
423 return ruleSet.release();
426 void CSSStyleSelector::collectFeatures()
429 // Collect all ids and rules using sibling selectors (:first-child and similar)
430 // in the current set of stylesheets. Style sharing code uses this information to reject
431 // sharing candidates.
432 m_features.add(defaultStyle->features());
433 m_features.add(m_authorStyle->features());
434 #if ENABLE(STYLE_SCOPED)
435 for (ScopedRuleSetMap::iterator it = m_scopedAuthorStyles.begin(); it != m_scopedAuthorStyles.end(); ++it)
436 m_features.add(it->second->features());
439 m_features.add(m_userStyle->features());
441 m_siblingRuleSet = makeRuleSet(m_features.siblingRules);
442 m_uncommonAttributeRuleSet = makeRuleSet(m_features.uncommonAttributeRules);
445 #if ENABLE(STYLE_SCOPED)
446 Element* CSSStyleSelector::determineScopingElement(const CSSStyleSheet* sheet)
450 Node* ownerNode = sheet->findStyleSheetOwnerNode();
451 if (!ownerNode || !ownerNode->isHTMLElement() || !ownerNode->hasTagName(HTMLNames::styleTag))
454 HTMLStyleElement* styleElement = static_cast<HTMLStyleElement*>(ownerNode);
455 if (!styleElement->scoped())
458 return styleElement->parentElement();
461 inline RuleSet* CSSStyleSelector::scopedRuleSetForElement(const Element* element) const
463 if (!element->hasScopedHTMLStyleChild())
465 ScopedRuleSetMap::const_iterator it = m_scopedAuthorStyles.find(element);
466 return it != m_scopedAuthorStyles.end() ? it->second.get() : 0;
470 void CSSStyleSelector::appendAuthorStylesheets(unsigned firstNew, const Vector<RefPtr<StyleSheet> >& stylesheets)
472 // This handles sheets added to the end of the stylesheet list only. In other cases the style resolver
473 // needs to be reconstructed. To handle insertions too the rule order numbers would need to be updated.
474 unsigned size = stylesheets.size();
475 for (unsigned i = firstNew; i < size; ++i) {
476 if (!stylesheets[i]->isCSSStyleSheet() || stylesheets[i]->disabled())
478 CSSStyleSheet* cssSheet = static_cast<CSSStyleSheet*>(stylesheets[i].get());
479 #if ENABLE(STYLE_SCOPED)
480 const Element* scope = determineScopingElement(cssSheet);
482 pair<ScopedRuleSetMap::iterator, bool> addResult = m_scopedAuthorStyles.add(scope, nullptr);
483 if (addResult.second)
484 addResult.first->second = adoptPtr(new RuleSet());
485 addResult.first->second->addRulesFromSheet(cssSheet, *m_medium, this, scope);
489 m_authorStyle->addRulesFromSheet(cssSheet, *m_medium, this);
491 m_authorStyle->shrinkToFit();
494 if (document()->renderer() && document()->renderer()->style())
495 document()->renderer()->style()->font().update(fontSelector());
498 #if ENABLE(STYLE_SCOPED)
499 void CSSStyleSelector::setupScopingElementStack(const Element* parent)
501 // The scoping element stack shouldn't be used if <style scoped> isn't used anywhere.
502 ASSERT(!m_scopedAuthorStyles.isEmpty());
504 m_scopingElementStack.shrink(0);
505 for (; parent; parent = parent->parentOrHostElement()) {
506 RuleSet* ruleSet = scopedRuleSetForElement(parent);
508 m_scopingElementStack.append(ScopeStackFrame(parent, ruleSet));
510 m_scopingElementStack.reverse();
511 m_scopingElementStackParent = parent;
515 void CSSStyleSelector::pushParent(Element* parent)
517 const Element* parentsParent = parent->parentOrHostElement();
518 // We are not always invoked consistently. For example, script execution can cause us to enter
519 // style recalc in the middle of tree building. We may also be invoked from somewhere within the tree.
520 // Reset the stack in this case, or if we see a new root element.
521 // Otherwise just push the new parent.
522 if (!parentsParent || m_checker.parentStackIsEmpty())
523 m_checker.setupParentStack(parent);
525 m_checker.pushParent(parent);
527 #if ENABLE(STYLE_SCOPED)
528 // Shortcut: Don't bother with the scoping element stack if <style scoped> isn't used anywhere.
529 if (m_scopedAuthorStyles.isEmpty()) {
530 ASSERT(!m_scopingElementStackParent);
531 ASSERT(m_scopingElementStack.isEmpty());
534 // In some wacky cases during style resolve we may get invoked for random elements.
535 // Recreate the whole scoping element stack in such cases.
536 if (!scopingElementStackIsConsistent(parentsParent)) {
537 setupScopingElementStack(parent);
540 // Otherwise just push the parent onto the stack.
541 RuleSet* ruleSet = scopedRuleSetForElement(parent);
543 m_scopingElementStack.append(ScopeStackFrame(parent, ruleSet));
544 m_scopingElementStackParent = parent;
548 void CSSStyleSelector::popParent(Element* parent)
550 // Note that we may get invoked for some random elements in some wacky cases during style resolve.
551 // Pause maintaining the stack in this case.
552 if (m_checker.parentStackIsConsistent(parent))
553 m_checker.popParent();
554 #if ENABLE(STYLE_SCOPED)
555 // Only bother to update the scoping element stack if it is consistent.
556 if (scopingElementStackIsConsistent(parent)) {
557 m_scopingElementStack.removeLast();
558 m_scopingElementStackParent = parent->parentOrHostElement();
563 // This is a simplified style setting function for keyframe styles
564 void CSSStyleSelector::addKeyframeStyle(PassRefPtr<WebKitCSSKeyframesRule> rule)
566 AtomicString s(rule->name());
567 m_keyframesRuleMap.set(s.impl(), rule);
570 CSSStyleSelector::~CSSStyleSelector()
572 m_fontSelector->clearDocument();
575 void CSSStyleSelector::sweepMatchedDeclarationCache()
577 // Look for cache entries containing a style declaration with a single ref and remove them.
578 // This may happen when an element attribute mutation causes it to swap out its Attribute::decl()
579 // for another CSSMappedAttributeDeclaration, potentially leaving this cache with the last ref.
580 Vector<unsigned, 16> toRemove;
581 MatchedStyleDeclarationCache::iterator it = m_matchedStyleDeclarationCache.begin();
582 MatchedStyleDeclarationCache::iterator end = m_matchedStyleDeclarationCache.end();
583 for (; it != end; ++it) {
584 Vector<MatchedStyleDeclaration>& matchedStyleDeclarations = it->second.matchedStyleDeclarations;
585 for (size_t i = 0; i < matchedStyleDeclarations.size(); ++i) {
586 if (matchedStyleDeclarations[i].styleDeclaration->hasOneRef()) {
587 toRemove.append(it->first);
592 for (size_t i = 0; i < toRemove.size(); ++i)
593 m_matchedStyleDeclarationCache.remove(toRemove[i]);
596 CSSStyleSelector::Features::Features()
597 : usesFirstLineRules(false)
598 , usesBeforeAfterRules(false)
599 , usesLinkRules(false)
603 CSSStyleSelector::Features::~Features()
607 void CSSStyleSelector::Features::add(const CSSStyleSelector::Features& other)
609 HashSet<AtomicStringImpl*>::iterator end = other.idsInRules.end();
610 for (HashSet<AtomicStringImpl*>::iterator it = other.idsInRules.begin(); it != end; ++it)
612 end = other.attrsInRules.end();
613 for (HashSet<AtomicStringImpl*>::iterator it = other.attrsInRules.begin(); it != end; ++it)
614 attrsInRules.add(*it);
615 siblingRules.append(other.siblingRules);
616 uncommonAttributeRules.append(other.uncommonAttributeRules);
617 usesFirstLineRules = usesFirstLineRules || other.usesFirstLineRules;
618 usesBeforeAfterRules = usesBeforeAfterRules || other.usesBeforeAfterRules;
619 usesLinkRules = usesLinkRules || other.usesLinkRules;
622 void CSSStyleSelector::Features::clear()
625 attrsInRules.clear();
626 siblingRules.clear();
627 uncommonAttributeRules.clear();
628 usesFirstLineRules = false;
629 usesBeforeAfterRules = false;
630 usesLinkRules = false;
633 static CSSStyleSheet* parseUASheet(const String& str)
635 CSSStyleSheet* sheet = CSSStyleSheet::create().leakRef(); // leak the sheet on purpose
636 sheet->parseString(str);
640 static CSSStyleSheet* parseUASheet(const char* characters, unsigned size)
642 return parseUASheet(String(characters, size));
645 static void loadFullDefaultStyle()
647 if (simpleDefaultStyleSheet) {
648 ASSERT(defaultStyle);
649 ASSERT(defaultPrintStyle == defaultStyle);
651 simpleDefaultStyleSheet->deref();
652 defaultStyle = new RuleSet;
653 defaultPrintStyle = new RuleSet;
654 simpleDefaultStyleSheet = 0;
656 ASSERT(!defaultStyle);
657 defaultStyle = new RuleSet;
658 defaultPrintStyle = new RuleSet;
659 defaultQuirksStyle = new RuleSet;
662 // Strict-mode rules.
663 String defaultRules = String(htmlUserAgentStyleSheet, sizeof(htmlUserAgentStyleSheet)) + RenderTheme::defaultTheme()->extraDefaultStyleSheet();
664 CSSStyleSheet* defaultSheet = parseUASheet(defaultRules);
665 defaultStyle->addRulesFromSheet(defaultSheet, screenEval());
666 defaultPrintStyle->addRulesFromSheet(defaultSheet, printEval());
668 // Quirks-mode rules.
669 String quirksRules = String(quirksUserAgentStyleSheet, sizeof(quirksUserAgentStyleSheet)) + RenderTheme::defaultTheme()->extraQuirksStyleSheet();
670 CSSStyleSheet* quirksSheet = parseUASheet(quirksRules);
671 defaultQuirksStyle->addRulesFromSheet(quirksSheet, screenEval());
674 static void loadSimpleDefaultStyle()
676 ASSERT(!defaultStyle);
677 ASSERT(!simpleDefaultStyleSheet);
679 defaultStyle = new RuleSet;
680 // There are no media-specific rules in the simple default style.
681 defaultPrintStyle = defaultStyle;
682 defaultQuirksStyle = new RuleSet;
684 simpleDefaultStyleSheet = parseUASheet(simpleUserAgentStyleSheet, strlen(simpleUserAgentStyleSheet));
685 defaultStyle->addRulesFromSheet(simpleDefaultStyleSheet, screenEval());
687 // No need to initialize quirks sheet yet as there are no quirk rules for elements allowed in simple default style.
690 static void loadViewSourceStyle()
692 ASSERT(!defaultViewSourceStyle);
693 defaultViewSourceStyle = new RuleSet;
694 defaultViewSourceStyle->addRulesFromSheet(parseUASheet(sourceUserAgentStyleSheet, sizeof(sourceUserAgentStyleSheet)), screenEval());
697 static void ensureDefaultStyleSheetsForElement(Element* element)
699 if (simpleDefaultStyleSheet && !elementCanUseSimpleDefaultStyle(element))
700 loadFullDefaultStyle();
703 static bool loadedSVGUserAgentSheet;
704 if (element->isSVGElement() && !loadedSVGUserAgentSheet) {
706 loadedSVGUserAgentSheet = true;
707 CSSStyleSheet* svgSheet = parseUASheet(svgUserAgentStyleSheet, sizeof(svgUserAgentStyleSheet));
708 defaultStyle->addRulesFromSheet(svgSheet, screenEval());
709 defaultPrintStyle->addRulesFromSheet(svgSheet, printEval());
713 static bool loadedMathMLUserAgentSheet;
715 if (element->isMathMLElement() && !loadedMathMLUserAgentSheet) {
717 loadedMathMLUserAgentSheet = true;
718 CSSStyleSheet* mathMLSheet = parseUASheet(mathmlUserAgentStyleSheet, sizeof(mathmlUserAgentStyleSheet));
719 defaultStyle->addRulesFromSheet(mathMLSheet, screenEval());
720 defaultPrintStyle->addRulesFromSheet(mathMLSheet, printEval());
725 static bool loadedMediaStyleSheet;
726 if (!loadedMediaStyleSheet && (element->hasTagName(videoTag) || element->hasTagName(audioTag))) {
727 loadedMediaStyleSheet = true;
728 String mediaRules = String(mediaControlsUserAgentStyleSheet, sizeof(mediaControlsUserAgentStyleSheet)) + RenderTheme::themeForPage(element->document()->page())->extraMediaControlsStyleSheet();
729 CSSStyleSheet* mediaControlsSheet = parseUASheet(mediaRules);
730 defaultStyle->addRulesFromSheet(mediaControlsSheet, screenEval());
731 defaultPrintStyle->addRulesFromSheet(mediaControlsSheet, printEval());
735 #if ENABLE(FULLSCREEN_API)
736 static bool loadedFullScreenStyleSheet;
737 if (!loadedFullScreenStyleSheet && element->document()->webkitIsFullScreen()) {
738 loadedFullScreenStyleSheet = true;
739 String fullscreenRules = String(fullscreenUserAgentStyleSheet, sizeof(fullscreenUserAgentStyleSheet)) + RenderTheme::defaultTheme()->extraFullScreenStyleSheet();
740 CSSStyleSheet* fullscreenSheet = parseUASheet(fullscreenRules);
741 defaultStyle->addRulesFromSheet(fullscreenSheet, screenEval());
742 defaultQuirksStyle->addRulesFromSheet(fullscreenSheet, screenEval());
746 ASSERT(defaultStyle->features().idsInRules.isEmpty());
747 ASSERT_UNUSED(loadedMathMLUserAgentSheet, loadedMathMLUserAgentSheet || defaultStyle->features().siblingRules.isEmpty());
750 void CSSStyleSelector::addMatchedDeclaration(StylePropertySet* styleDeclaration, unsigned linkMatchType)
752 m_matchedDecls.grow(m_matchedDecls.size() + 1);
753 MatchedStyleDeclaration& newDeclaration = m_matchedDecls.last();
754 newDeclaration.styleDeclaration = styleDeclaration;
755 newDeclaration.linkMatchType = linkMatchType;
758 void CSSStyleSelector::collectMatchingRules(RuleSet* rules, int& firstRuleIndex, int& lastRuleIndex, bool includeEmptyRules)
763 // We need to collect the rules for id, class, tag, and everything else into a buffer and
764 // then sort the buffer.
765 if (m_element->hasID())
766 collectMatchingRulesForList(rules->idRules(m_element->idForStyleResolution().impl()), firstRuleIndex, lastRuleIndex, includeEmptyRules);
767 if (m_element->hasClass()) {
768 ASSERT(m_styledElement);
769 const SpaceSplitString& classNames = m_styledElement->classNames();
770 size_t size = classNames.size();
771 for (size_t i = 0; i < size; ++i)
772 collectMatchingRulesForList(rules->classRules(classNames[i].impl()), firstRuleIndex, lastRuleIndex, includeEmptyRules);
774 const AtomicString& pseudoId = m_element->shadowPseudoId();
775 if (!pseudoId.isEmpty()) {
776 ASSERT(m_styledElement);
777 collectMatchingRulesForList(rules->shadowPseudoElementRules(pseudoId.impl()), firstRuleIndex, lastRuleIndex, includeEmptyRules);
779 if (m_element->isLink())
780 collectMatchingRulesForList(rules->linkPseudoClassRules(), firstRuleIndex, lastRuleIndex, includeEmptyRules);
781 if (m_checker.matchesFocusPseudoClass(m_element))
782 collectMatchingRulesForList(rules->focusPseudoClassRules(), firstRuleIndex, lastRuleIndex, includeEmptyRules);
783 collectMatchingRulesForList(rules->tagRules(m_element->localName().impl()), firstRuleIndex, lastRuleIndex, includeEmptyRules);
784 collectMatchingRulesForList(rules->universalRules(), firstRuleIndex, lastRuleIndex, includeEmptyRules);
787 void CSSStyleSelector::collectMatchingRulesForRegion(RuleSet* rules, int& firstRuleIndex, int& lastRuleIndex, bool includeEmptyRules)
789 if (!m_regionForStyling)
792 unsigned size = rules->m_regionSelectorsAndRuleSets.size();
793 for (unsigned i = 0; i < size; ++i) {
794 CSSSelector* regionSelector = rules->m_regionSelectorsAndRuleSets.at(i).selector;
795 if (checkRegionSelector(regionSelector, static_cast<Element*>(m_regionForStyling->node()))) {
796 RuleSet* regionRules = rules->m_regionSelectorsAndRuleSets.at(i).ruleSet.get();
798 collectMatchingRules(regionRules, firstRuleIndex, lastRuleIndex, includeEmptyRules);
803 void CSSStyleSelector::sortAndTransferMatchedRules()
805 if (m_matchedRules.isEmpty())
810 if (m_checker.isCollectingRulesOnly()) {
812 m_ruleList = CSSRuleList::create();
813 for (unsigned i = 0; i < m_matchedRules.size(); ++i)
814 m_ruleList->append(m_matchedRules[i]->rule());
818 // Now transfer the set of matched rules over to our list of declarations.
819 // FIXME: This sucks, the inspector should get the style from the visited style itself.
820 bool swapVisitedUnvisited = InspectorInstrumentation::forcePseudoState(m_element, CSSSelector::PseudoVisited);
821 for (unsigned i = 0; i < m_matchedRules.size(); i++) {
822 if (m_style && m_matchedRules[i]->containsUncommonAttributeSelector())
823 m_style->setAffectedByUncommonAttributeSelectors();
824 unsigned linkMatchType = m_matchedRules[i]->linkMatchType();
825 if (swapVisitedUnvisited && linkMatchType && linkMatchType != SelectorChecker::MatchAll)
826 linkMatchType = (linkMatchType == SelectorChecker::MatchVisited) ? SelectorChecker::MatchLink : SelectorChecker::MatchVisited;
827 addMatchedDeclaration(m_matchedRules[i]->rule()->declaration(), linkMatchType);
831 void CSSStyleSelector::matchScopedAuthorRules(int& firstRuleIndex, int& lastRuleIndex, bool includeEmptyRules)
833 #if ENABLE(STYLE_SCOPED)
834 if (m_scopedAuthorStyles.isEmpty())
837 // Match scoped author rules by traversing the scoped element stack (rebuild it if it got inconsistent).
838 const Element* parent = m_element->parentOrHostElement();
839 if (!scopingElementStackIsConsistent(parent))
840 setupScopingElementStack(parent);
841 for (size_t i = m_scopingElementStack.size(); i; --i) {
842 collectMatchingRules(m_scopingElementStack[i - 1].m_ruleSet, firstRuleIndex, lastRuleIndex, includeEmptyRules);
843 collectMatchingRulesForRegion(m_scopingElementStack[i - 1].m_ruleSet, firstRuleIndex, lastRuleIndex, includeEmptyRules);
845 // Also include the current element.
846 RuleSet* ruleSet = scopedRuleSetForElement(m_element);
848 collectMatchingRules(ruleSet, firstRuleIndex, lastRuleIndex, includeEmptyRules);
849 collectMatchingRulesForRegion(ruleSet, firstRuleIndex, lastRuleIndex, includeEmptyRules);
852 UNUSED_PARAM(firstRuleIndex);
853 UNUSED_PARAM(lastRuleIndex);
854 UNUSED_PARAM(includeEmptyRules);
858 void CSSStyleSelector::matchAuthorRules(int& firstRuleIndex, int& lastRuleIndex, bool includeEmptyRules)
860 m_matchedRules.clear();
865 // Match global author rules.
866 collectMatchingRules(m_authorStyle.get(), firstRuleIndex, lastRuleIndex, includeEmptyRules);
867 collectMatchingRulesForRegion(m_authorStyle.get(), firstRuleIndex, lastRuleIndex, includeEmptyRules);
869 matchScopedAuthorRules(firstRuleIndex, lastRuleIndex, includeEmptyRules);
871 sortAndTransferMatchedRules();
874 void CSSStyleSelector::matchRules(RuleSet* rules, int& firstRuleIndex, int& lastRuleIndex, bool includeEmptyRules)
876 m_matchedRules.clear();
878 if (!rules || !m_element)
881 collectMatchingRules(rules, firstRuleIndex, lastRuleIndex, includeEmptyRules);
882 collectMatchingRulesForRegion(rules, firstRuleIndex, lastRuleIndex, includeEmptyRules);
884 sortAndTransferMatchedRules();
887 class MatchingUARulesScope {
889 MatchingUARulesScope();
890 ~MatchingUARulesScope();
892 static bool isMatchingUARules();
895 static bool m_matchingUARules;
898 MatchingUARulesScope::MatchingUARulesScope()
900 ASSERT(!m_matchingUARules);
901 m_matchingUARules = true;
904 MatchingUARulesScope::~MatchingUARulesScope()
906 m_matchingUARules = false;
909 inline bool MatchingUARulesScope::isMatchingUARules()
911 return m_matchingUARules;
914 bool MatchingUARulesScope::m_matchingUARules = false;
916 inline static bool matchesInTreeScope(TreeScope* treeScope, bool ruleReachesIntoShadowDOM)
918 return MatchingUARulesScope::isMatchingUARules() || treeScope->applyAuthorSheets() || ruleReachesIntoShadowDOM;
921 void CSSStyleSelector::collectMatchingRulesForList(const Vector<RuleData>* rules, int& firstRuleIndex, int& lastRuleIndex, bool includeEmptyRules)
925 // In some cases we may end up looking up style for random elements in the middle of a recursive tree resolve.
926 // Ancestor identifier filter won't be up-to-date in that case and we can't use the fast path.
927 bool canUseFastReject = m_checker.parentStackIsConsistent(m_parentNode);
929 unsigned size = rules->size();
930 for (unsigned i = 0; i < size; ++i) {
931 const RuleData& ruleData = rules->at(i);
932 if (canUseFastReject && m_checker.fastRejectSelector<RuleData::maximumIdentifierCount>(ruleData.descendantSelectorIdentifierHashes()))
935 CSSStyleRule* rule = ruleData.rule();
936 InspectorInstrumentationCookie cookie = InspectorInstrumentation::willMatchRule(document(), rule);
937 if (checkSelector(ruleData)) {
938 if (!matchesInTreeScope(m_element->treeScope(), m_checker.hasUnknownPseudoElements())) {
939 InspectorInstrumentation::didMatchRule(cookie, false);
942 // If the rule has no properties to apply, then ignore it in the non-debug mode.
943 StylePropertySet* decl = rule->declaration();
944 if (!decl || (decl->isEmpty() && !includeEmptyRules)) {
945 InspectorInstrumentation::didMatchRule(cookie, false);
948 if (m_sameOriginOnly && !m_checker.document()->securityOrigin()->canRequest(rule->baseURL())) {
949 InspectorInstrumentation::didMatchRule(cookie, false);
952 // If we're matching normal rules, set a pseudo bit if
953 // we really just matched a pseudo-element.
954 if (m_dynamicPseudo != NOPSEUDO && m_checker.pseudoStyle() == NOPSEUDO) {
955 if (m_checker.isCollectingRulesOnly()) {
956 InspectorInstrumentation::didMatchRule(cookie, false);
959 if (m_dynamicPseudo < FIRST_INTERNAL_PSEUDOID)
960 m_style->setHasPseudoStyle(m_dynamicPseudo);
962 // Update our first/last rule indices in the matched rules array.
963 lastRuleIndex = m_matchedDecls.size() + m_matchedRules.size();
964 if (firstRuleIndex == -1)
965 firstRuleIndex = lastRuleIndex;
967 // Add this rule to our list of matched rules.
968 addMatchedRule(&ruleData);
969 InspectorInstrumentation::didMatchRule(cookie, true);
973 InspectorInstrumentation::didMatchRule(cookie, false);
977 static inline bool compareRules(const RuleData* r1, const RuleData* r2)
979 unsigned specificity1 = r1->specificity();
980 unsigned specificity2 = r2->specificity();
981 return (specificity1 == specificity2) ? r1->position() < r2->position() : specificity1 < specificity2;
984 void CSSStyleSelector::sortMatchedRules()
986 std::sort(m_matchedRules.begin(), m_matchedRules.end(), compareRules);
989 void CSSStyleSelector::matchAllRules(MatchResult& result)
991 matchUARules(result);
993 // Now we check user sheet rules.
994 if (m_matchAuthorAndUserStyles)
995 matchRules(m_userStyle.get(), result.ranges.firstUserRule, result.ranges.lastUserRule, false);
997 // Now check author rules, beginning first with presentational attributes mapped from HTML.
998 if (m_styledElement) {
999 if (StylePropertySet* attributeStyle = m_styledElement->attributeStyle()) {
1000 if (!attributeStyle->isEmpty()) {
1001 result.ranges.lastAuthorRule = m_matchedRules.size();
1002 if (result.ranges.firstAuthorRule == -1)
1003 result.ranges.firstAuthorRule = result.ranges.lastAuthorRule;
1004 addMatchedDeclaration(attributeStyle);
1005 result.isCacheable = false;
1009 // Now we check additional mapped declarations.
1010 // Tables and table cells share an additional mapped rule that must be applied
1011 // after all attributes, since their mapped style depends on the values of multiple attributes.
1012 if (RefPtr<StylePropertySet> additionalStyle = m_styledElement->additionalAttributeStyle()) {
1013 if (result.ranges.firstAuthorRule == -1)
1014 result.ranges.firstAuthorRule = m_matchedDecls.size();
1015 result.ranges.lastAuthorRule = m_matchedDecls.size();
1016 addMatchedDeclaration(additionalStyle.get());
1017 result.isCacheable = false;
1020 if (m_styledElement->isHTMLElement()) {
1022 TextDirection textDirection = toHTMLElement(m_styledElement)->directionalityIfhasDirAutoAttribute(isAuto);
1024 addMatchedDeclaration(textDirection == LTR ? leftToRightDeclaration() : rightToLeftDeclaration());
1028 // Check the rules in author sheets next.
1029 if (m_matchAuthorAndUserStyles)
1030 matchAuthorRules(result.ranges.firstAuthorRule, result.ranges.lastAuthorRule, false);
1032 // Now check our inline style attribute.
1033 if (m_matchAuthorAndUserStyles && m_styledElement) {
1034 StylePropertySet* inlineDecl = m_styledElement->inlineStyleDecl();
1036 result.ranges.lastAuthorRule = m_matchedDecls.size();
1037 if (result.ranges.firstAuthorRule == -1)
1038 result.ranges.firstAuthorRule = result.ranges.lastAuthorRule;
1039 addMatchedDeclaration(inlineDecl);
1040 result.isCacheable = false;
1045 inline void CSSStyleSelector::initElement(Element* e)
1047 if (m_element != e) {
1049 m_styledElement = m_element && m_element->isStyledElement() ? static_cast<StyledElement*>(m_element) : 0;
1050 m_elementLinkState = m_checker.determineLinkState(m_element);
1051 if (e && e == e->document()->documentElement()) {
1052 e->document()->setDirectionSetOnDocumentElement(false);
1053 e->document()->setWritingModeSetOnDocumentElement(false);
1058 inline void CSSStyleSelector::initForStyleResolve(Element* e, RenderStyle* parentStyle, PseudoId pseudoID)
1060 m_checker.setPseudoStyle(pseudoID);
1062 m_parentNode = e ? e->parentNodeForRenderingAndStyle() : 0;
1065 m_parentStyle = parentStyle;
1067 m_parentStyle = m_parentNode ? m_parentNode->renderStyle() : 0;
1069 Node* docElement = e ? e->document()->documentElement() : 0;
1070 RenderStyle* docStyle = m_checker.document()->renderStyle();
1071 m_rootElementStyle = docElement && e != docElement ? docElement->renderStyle() : docStyle;
1075 m_matchedDecls.clear();
1077 m_pendingImageProperties.clear();
1081 m_fontDirty = false;
1084 static const unsigned cStyleSearchThreshold = 10;
1085 static const unsigned cStyleSearchLevelThreshold = 10;
1087 Node* CSSStyleSelector::locateCousinList(Element* parent, unsigned& visitedNodeCount) const
1089 if (visitedNodeCount >= cStyleSearchThreshold * cStyleSearchLevelThreshold)
1091 if (!parent || !parent->isStyledElement())
1093 #if ENABLE(STYLE_SCOPED)
1094 if (parent->hasScopedHTMLStyleChild())
1097 StyledElement* p = static_cast<StyledElement*>(parent);
1098 if (p->inlineStyleDecl())
1100 if (p->hasID() && m_features.idsInRules.contains(p->idForStyleResolution().impl()))
1103 RenderStyle* parentStyle = p->renderStyle();
1104 unsigned subcount = 0;
1105 Node* thisCousin = p;
1106 Node* currentNode = p->previousSibling();
1108 // Reserve the tries for this level. This effectively makes sure that the algorithm
1109 // will never go deeper than cStyleSearchLevelThreshold levels into recursion.
1110 visitedNodeCount += cStyleSearchThreshold;
1111 while (thisCousin) {
1112 while (currentNode) {
1114 if (currentNode->renderStyle() == parentStyle && currentNode->lastChild()) {
1115 // Adjust for unused reserved tries.
1116 visitedNodeCount -= cStyleSearchThreshold - subcount;
1117 return currentNode->lastChild();
1119 if (subcount >= cStyleSearchThreshold)
1121 currentNode = currentNode->previousSibling();
1123 currentNode = locateCousinList(thisCousin->parentElement(), visitedNodeCount);
1124 thisCousin = currentNode;
1130 bool CSSStyleSelector::matchesRuleSet(RuleSet* ruleSet)
1132 int firstSiblingRule = -1, lastSiblingRule = -1;
1133 matchRules(ruleSet, firstSiblingRule, lastSiblingRule, false);
1134 if (m_matchedDecls.isEmpty())
1136 m_matchedDecls.clear();
1140 bool CSSStyleSelector::canShareStyleWithControl(StyledElement* element) const
1142 #if ENABLE(PROGRESS_TAG)
1143 if (element->hasTagName(progressTag)) {
1144 if (!m_element->hasTagName(progressTag))
1147 HTMLProgressElement* thisProgressElement = static_cast<HTMLProgressElement*>(element);
1148 HTMLProgressElement* otherProgressElement = static_cast<HTMLProgressElement*>(m_element);
1149 if (thisProgressElement->isDeterminate() != otherProgressElement->isDeterminate())
1156 HTMLInputElement* thisInputElement = element->toInputElement();
1157 HTMLInputElement* otherInputElement = m_element->toInputElement();
1159 if (!thisInputElement || !otherInputElement)
1162 if (thisInputElement->isAutofilled() != otherInputElement->isAutofilled())
1164 if (thisInputElement->shouldAppearChecked() != otherInputElement->shouldAppearChecked())
1166 if (thisInputElement->isIndeterminate() != otherInputElement->isIndeterminate())
1168 if (thisInputElement->required() != otherInputElement->required())
1171 if (element->isEnabledFormControl() != m_element->isEnabledFormControl())
1174 if (element->isDefaultButtonForForm() != m_element->isDefaultButtonForForm())
1177 if (!m_element->document()->containsValidityStyleRules())
1180 bool willValidate = element->willValidate();
1182 if (willValidate != m_element->willValidate())
1185 if (willValidate && (element->isValidFormControlElement() != m_element->isValidFormControlElement()))
1188 if (element->isInRange() != m_element->isInRange())
1191 if (element->isOutOfRange() != m_element->isOutOfRange())
1197 bool CSSStyleSelector::canShareStyleWithElement(StyledElement* element) const
1199 RenderStyle* style = element->renderStyle();
1203 if (style->unique())
1205 if (element->tagQName() != m_element->tagQName())
1207 if (element->hasClass() != m_element->hasClass())
1209 if (element->inlineStyleDecl())
1211 if (!!element->attributeStyle() != !!m_styledElement->attributeStyle())
1213 if (element->isLink() != m_element->isLink())
1215 if (style->affectedByUncommonAttributeSelectors())
1217 if (element->hovered() != m_element->hovered())
1219 if (element->active() != m_element->active())
1221 if (element->focused() != m_element->focused())
1223 if (element->shadowPseudoId() != m_element->shadowPseudoId())
1225 if (element == element->document()->cssTarget())
1227 if (m_element == m_element->document()->cssTarget())
1229 if (element->getAttribute(typeAttr) != m_element->getAttribute(typeAttr))
1231 if (element->fastGetAttribute(XMLNames::langAttr) != m_element->fastGetAttribute(XMLNames::langAttr))
1233 if (element->fastGetAttribute(langAttr) != m_element->fastGetAttribute(langAttr))
1235 if (element->fastGetAttribute(readonlyAttr) != m_element->fastGetAttribute(readonlyAttr))
1237 if (element->fastGetAttribute(cellpaddingAttr) != m_element->fastGetAttribute(cellpaddingAttr))
1240 if (element->hasID() && m_features.idsInRules.contains(element->idForStyleResolution().impl()))
1243 #if ENABLE(STYLE_SCOPED)
1244 if (element->hasScopedHTMLStyleChild())
1248 bool isControl = element->isFormControlElement();
1250 if (isControl != m_element->isFormControlElement())
1253 if (isControl && !canShareStyleWithControl(element))
1256 if (style->transitions() || style->animations())
1259 #if USE(ACCELERATED_COMPOSITING)
1260 // Turn off style sharing for elements that can gain layers for reasons outside of the style system.
1261 // See comments in RenderObject::setStyle().
1262 if (element->hasTagName(iframeTag) || element->hasTagName(frameTag) || element->hasTagName(embedTag) || element->hasTagName(objectTag) || element->hasTagName(appletTag)
1263 #if ENABLE(PLUGIN_PROXY_FOR_VIDEO)
1264 // With proxying, the media elements are backed by a RenderEmbeddedObject.
1265 || element->hasTagName(videoTag) || element->hasTagName(audioTag)
1271 if (equalIgnoringCase(element->fastGetAttribute(dirAttr), "auto") || equalIgnoringCase(m_element->fastGetAttribute(dirAttr), "auto"))
1274 if (element->hasClass() && m_element->getAttribute(classAttr) != element->getAttribute(classAttr))
1277 if (element->attributeStyle() && !element->attributeMap()->mapsEquivalent(m_styledElement->attributeMap()))
1280 if (element->isLink() && m_elementLinkState != style->insideLink())
1286 inline StyledElement* CSSStyleSelector::findSiblingForStyleSharing(Node* node, unsigned& count) const
1288 for (; node; node = node->previousSibling()) {
1289 if (!node->isStyledElement())
1291 if (canShareStyleWithElement(static_cast<StyledElement*>(node)))
1293 if (count++ == cStyleSearchThreshold)
1296 return static_cast<StyledElement*>(node);
1299 static inline bool parentStylePreventsSharing(const RenderStyle* parentStyle)
1301 return parentStyle->childrenAffectedByPositionalRules()
1302 || parentStyle->childrenAffectedByFirstChildRules()
1303 || parentStyle->childrenAffectedByLastChildRules()
1304 || parentStyle->childrenAffectedByDirectAdjacentRules();
1307 RenderStyle* CSSStyleSelector::locateSharedStyle()
1309 if (!m_styledElement || !m_parentStyle)
1311 // If the element has inline style it is probably unique.
1312 if (m_styledElement->inlineStyleDecl())
1314 // Ids stop style sharing if they show up in the stylesheets.
1315 if (m_styledElement->hasID() && m_features.idsInRules.contains(m_styledElement->idForStyleResolution().impl()))
1317 if (parentStylePreventsSharing(m_parentStyle))
1319 #if ENABLE(STYLE_SCOPED)
1320 if (m_styledElement->hasScopedHTMLStyleChild())
1324 // Check previous siblings and their cousins.
1326 unsigned visitedNodeCount = 0;
1327 StyledElement* shareElement = 0;
1328 Node* cousinList = m_styledElement->previousSibling();
1329 while (cousinList) {
1330 shareElement = findSiblingForStyleSharing(cousinList, count);
1333 cousinList = locateCousinList(cousinList->parentElement(), visitedNodeCount);
1336 // If we have exhausted all our budget or our cousins.
1340 // Can't share if sibling rules apply. This is checked at the end as it should rarely fail.
1341 if (matchesRuleSet(m_siblingRuleSet.get()))
1343 // Can't share if attribute rules apply.
1344 if (matchesRuleSet(m_uncommonAttributeRuleSet.get()))
1346 // Tracking child index requires unique style for each node. This may get set by the sibling rule match above.
1347 if (parentStylePreventsSharing(m_parentStyle))
1349 return shareElement->renderStyle();
1352 void CSSStyleSelector::matchUARules(MatchResult& result)
1354 MatchingUARulesScope scope;
1356 // First we match rules from the user agent sheet.
1357 if (simpleDefaultStyleSheet)
1358 result.isCacheable = false;
1359 RuleSet* userAgentStyleSheet = m_medium->mediaTypeMatchSpecific("print")
1360 ? defaultPrintStyle : defaultStyle;
1361 matchRules(userAgentStyleSheet, result.ranges.firstUARule, result.ranges.lastUARule, false);
1363 // In quirks mode, we match rules from the quirks user agent sheet.
1364 if (!m_checker.strictParsing())
1365 matchRules(defaultQuirksStyle, result.ranges.firstUARule, result.ranges.lastUARule, false);
1367 // If document uses view source styles (in view source mode or in xml viewer mode), then we match rules from the view source style sheet.
1368 if (m_checker.document()->isViewSource()) {
1369 if (!defaultViewSourceStyle)
1370 loadViewSourceStyle();
1371 matchRules(defaultViewSourceStyle, result.ranges.firstUARule, result.ranges.lastUARule, false);
1375 PassRefPtr<RenderStyle> CSSStyleSelector::styleForDocument(Document* document, CSSFontSelector* fontSelector)
1377 Frame* frame = document->frame();
1379 RefPtr<RenderStyle> documentStyle = RenderStyle::create();
1380 documentStyle->setDisplay(BLOCK);
1381 documentStyle->setRTLOrdering(document->visuallyOrdered() ? VisualOrder : LogicalOrder);
1382 documentStyle->setZoom(frame ? frame->pageZoomFactor() : 1);
1383 documentStyle->setPageScaleTransform(frame ? frame->frameScaleFactor() : 1);
1384 documentStyle->setUserModify(document->inDesignMode() ? READ_WRITE : READ_ONLY);
1385 documentStyle->setLocale(document->contentLanguage());
1387 Element* docElement = document->documentElement();
1388 RenderObject* docElementRenderer = docElement ? docElement->renderer() : 0;
1389 if (docElementRenderer) {
1390 // Use the direction and writing-mode of the body to set the
1391 // viewport's direction and writing-mode unless the property is set on the document element.
1392 // If there is no body, then use the document element.
1393 RenderObject* bodyRenderer = document->body() ? document->body()->renderer() : 0;
1394 if (bodyRenderer && !document->writingModeSetOnDocumentElement())
1395 documentStyle->setWritingMode(bodyRenderer->style()->writingMode());
1397 documentStyle->setWritingMode(docElementRenderer->style()->writingMode());
1398 if (bodyRenderer && !document->directionSetOnDocumentElement())
1399 documentStyle->setDirection(bodyRenderer->style()->direction());
1401 documentStyle->setDirection(docElementRenderer->style()->direction());
1405 if (Page* page = frame->page()) {
1406 const Page::Pagination& pagination = page->pagination();
1407 if (pagination.mode != Page::Pagination::Unpaginated) {
1408 documentStyle->setColumnAxis(pagination.mode == Page::Pagination::HorizontallyPaginated ? HorizontalColumnAxis : VerticalColumnAxis);
1409 documentStyle->setColumnGap(pagination.gap);
1414 FontDescription fontDescription;
1415 fontDescription.setUsePrinterFont(document->printing());
1416 fontDescription.setScript(localeToScriptCodeForFontSelection(documentStyle->locale()));
1417 if (Settings* settings = document->settings()) {
1418 fontDescription.setRenderingMode(settings->fontRenderingMode());
1419 const AtomicString& standardFont = settings->standardFontFamily(fontDescription.script());
1420 if (!standardFont.isEmpty()) {
1421 fontDescription.setGenericFamily(FontDescription::StandardFamily);
1422 fontDescription.firstFamily().setFamily(standardFont);
1423 fontDescription.firstFamily().appendFamily(0);
1425 fontDescription.setKeywordSize(CSSValueMedium - CSSValueXxSmall + 1);
1426 int size = CSSStyleSelector::fontSizeForKeyword(document, CSSValueMedium, false);
1427 fontDescription.setSpecifiedSize(size);
1428 bool useSVGZoomRules = document->isSVGDocument();
1429 fontDescription.setComputedSize(CSSStyleSelector::getComputedSizeFromSpecifiedSize(document, documentStyle.get(), fontDescription.isAbsoluteSize(), size, useSVGZoomRules));
1432 documentStyle->setFontDescription(fontDescription);
1433 documentStyle->font().update(fontSelector);
1435 return documentStyle.release();
1438 static inline bool isAtShadowBoundary(Element* element)
1442 ContainerNode* parentNode = element->parentNode();
1443 return parentNode && parentNode->isShadowRoot();
1446 // If resolveForRootDefault is true, style based on user agent style sheet only. This is used in media queries, where
1447 // relative units are interpreted according to document root element style, styled only with UA stylesheet
1449 PassRefPtr<RenderStyle> CSSStyleSelector::styleForElement(Element* element, RenderStyle* defaultParent, bool allowSharing, bool resolveForRootDefault, RenderRegion* regionForStyling)
1451 // Once an element has a renderer, we don't try to destroy it, since otherwise the renderer
1452 // will vanish if a style recalc happens during loading.
1453 if (allowSharing && !element->document()->haveStylesheetsLoaded() && !element->renderer()) {
1454 if (!s_styleNotYetAvailable) {
1455 s_styleNotYetAvailable = RenderStyle::create().leakRef();
1456 s_styleNotYetAvailable->setDisplay(NONE);
1457 s_styleNotYetAvailable->font().update(m_fontSelector);
1459 element->document()->setHasNodesWithPlaceholderStyle();
1460 return s_styleNotYetAvailable;
1463 initElement(element);
1464 initForStyleResolve(element, defaultParent);
1465 m_regionForStyling = regionForStyling;
1467 RenderStyle* sharedStyle = locateSharedStyle();
1472 m_style = RenderStyle::create();
1475 m_style->inheritFrom(m_parentStyle);
1477 m_parentStyle = style();
1478 // Make sure our fonts are initialized if we don't inherit them from our parent style.
1479 m_style->font().update(0);
1482 // Even if surrounding content is user-editable, shadow DOM should act as a single unit, and not necessarily be editable
1483 if (isAtShadowBoundary(element))
1484 m_style->setUserModify(RenderStyle::initialUserModify());
1486 if (element->isLink()) {
1487 m_style->setIsLink(true);
1488 m_style->setInsideLink(m_elementLinkState);
1491 ensureDefaultStyleSheetsForElement(element);
1493 MatchResult matchResult;
1494 if (resolveForRootDefault)
1495 matchUARules(matchResult);
1497 matchAllRules(matchResult);
1499 applyMatchedDeclarations(matchResult);
1501 // Clean up our style object's display and text decorations (among other fixups).
1502 adjustRenderStyle(style(), m_parentStyle, element);
1504 initElement(0); // Clear out for the next resolve.
1506 // Now return the style.
1507 return m_style.release();
1510 PassRefPtr<RenderStyle> CSSStyleSelector::styleForKeyframe(const RenderStyle* elementStyle, const WebKitCSSKeyframeRule* keyframeRule, KeyframeValue& keyframe)
1512 if (keyframeRule->declaration())
1513 addMatchedDeclaration(keyframeRule->declaration());
1518 m_style = RenderStyle::clone(elementStyle);
1520 m_lineHeightValue = 0;
1522 // We don't need to bother with !important. Since there is only ever one
1523 // decl, there's nothing to override. So just add the first properties.
1524 bool inheritedOnly = false;
1525 if (keyframeRule->style())
1526 applyDeclarations<true>(false, 0, m_matchedDecls.size() - 1, inheritedOnly);
1528 // If our font got dirtied, go ahead and update it now.
1531 // Line-height is set when we are sure we decided on the font-size
1532 if (m_lineHeightValue)
1533 applyProperty(CSSPropertyLineHeight, m_lineHeightValue);
1535 // Now do rest of the properties.
1536 if (keyframeRule->style())
1537 applyDeclarations<false>(false, 0, m_matchedDecls.size() - 1, inheritedOnly);
1539 // If our font got dirtied by one of the non-essential font props,
1540 // go ahead and update it a second time.
1543 // Start loading images referenced by this style.
1544 loadPendingImages();
1546 #if ENABLE(CSS_SHADERS)
1547 // Start loading the shaders referenced by this style.
1548 loadPendingShaders();
1551 // Add all the animating properties to the keyframe.
1552 if (StylePropertySet* styleDeclaration = keyframeRule->declaration()) {
1553 unsigned propertyCount = styleDeclaration->propertyCount();
1554 for (unsigned i = 0; i < propertyCount; ++i) {
1555 int property = styleDeclaration->propertyAt(i).id();
1556 // Timing-function within keyframes is special, because it is not animated; it just
1557 // describes the timing function between this keyframe and the next.
1558 if (property != CSSPropertyWebkitAnimationTimingFunction)
1559 keyframe.addProperty(property);
1563 return m_style.release();
1566 void CSSStyleSelector::keyframeStylesForAnimation(Element* e, const RenderStyle* elementStyle, KeyframeList& list)
1570 // Get the keyframesRule for this name
1571 if (!e || list.animationName().isEmpty())
1574 m_keyframesRuleMap.checkConsistency();
1576 KeyframesRuleMap::iterator it = m_keyframesRuleMap.find(list.animationName().impl());
1577 if (it == m_keyframesRuleMap.end())
1580 const WebKitCSSKeyframesRule* rule = it->second.get();
1582 // Construct and populate the style for each keyframe
1583 for (unsigned i = 0; i < rule->length(); ++i) {
1584 // Apply the declaration to the style. This is a simplified version of the logic in styleForElement
1586 initForStyleResolve(e);
1588 const WebKitCSSKeyframeRule* keyframeRule = rule->item(i);
1590 KeyframeValue keyframe(0, 0);
1591 keyframe.setStyle(styleForKeyframe(elementStyle, keyframeRule, keyframe));
1593 // Add this keyframe style to all the indicated key times
1595 keyframeRule->getKeys(keys);
1596 for (size_t keyIndex = 0; keyIndex < keys.size(); ++keyIndex) {
1597 keyframe.setKey(keys[keyIndex]);
1598 list.insert(keyframe);
1602 // If the 0% keyframe is missing, create it (but only if there is at least one other keyframe)
1603 int initialListSize = list.size();
1604 if (initialListSize > 0 && list[0].key() != 0) {
1605 RefPtr<WebKitCSSKeyframeRule> keyframeRule = WebKitCSSKeyframeRule::create();
1606 keyframeRule->setKeyText("0%");
1607 KeyframeValue keyframe(0, 0);
1608 keyframe.setStyle(styleForKeyframe(elementStyle, keyframeRule.get(), keyframe));
1609 list.insert(keyframe);
1612 // If the 100% keyframe is missing, create it (but only if there is at least one other keyframe)
1613 if (initialListSize > 0 && (list[list.size() - 1].key() != 1)) {
1614 RefPtr<WebKitCSSKeyframeRule> keyframeRule = WebKitCSSKeyframeRule::create();
1615 keyframeRule->setKeyText("100%");
1616 KeyframeValue keyframe(1, 0);
1617 keyframe.setStyle(styleForKeyframe(elementStyle, keyframeRule.get(), keyframe));
1618 list.insert(keyframe);
1622 PassRefPtr<RenderStyle> CSSStyleSelector::pseudoStyleForElement(PseudoId pseudo, Element* e, RenderStyle* parentStyle)
1629 initForStyleResolve(e, parentStyle, pseudo);
1630 m_style = RenderStyle::create();
1633 m_style->inheritFrom(m_parentStyle);
1635 // Since we don't use pseudo-elements in any of our quirk/print user agent rules, don't waste time walking
1638 // Check UA, user and author rules.
1639 MatchResult matchResult;
1640 matchUARules(matchResult);
1642 if (m_matchAuthorAndUserStyles) {
1643 matchRules(m_userStyle.get(), matchResult.ranges.firstUserRule, matchResult.ranges.lastUserRule, false);
1644 matchAuthorRules(matchResult.ranges.firstAuthorRule, matchResult.ranges.lastAuthorRule, false);
1647 if (m_matchedDecls.isEmpty())
1650 m_style->setStyleType(pseudo);
1652 applyMatchedDeclarations(matchResult);
1654 // Clean up our style object's display and text decorations (among other fixups).
1655 adjustRenderStyle(style(), parentStyle, 0);
1657 // Start loading images referenced by this style.
1658 loadPendingImages();
1660 #if ENABLE(CSS_SHADERS)
1661 // Start loading the shaders referenced by this style.
1662 loadPendingShaders();
1665 // Now return the style.
1666 return m_style.release();
1669 PassRefPtr<RenderStyle> CSSStyleSelector::styleForPage(int pageIndex)
1671 initForStyleResolve(m_checker.document()->documentElement()); // m_rootElementStyle will be set to the document style.
1673 m_style = RenderStyle::create();
1674 m_style->inheritFrom(m_rootElementStyle);
1676 const bool isLeft = isLeftPage(pageIndex);
1677 const bool isFirst = isFirstPage(pageIndex);
1678 const String page = pageName(pageIndex);
1679 matchPageRules(defaultPrintStyle, isLeft, isFirst, page);
1680 matchPageRules(m_userStyle.get(), isLeft, isFirst, page);
1681 // Only consider the global author RuleSet for @page rules, as per the HTML5 spec.
1682 matchPageRules(m_authorStyle.get(), isLeft, isFirst, page);
1683 m_lineHeightValue = 0;
1684 bool inheritedOnly = false;
1685 applyDeclarations<true>(false, 0, m_matchedDecls.size() - 1, inheritedOnly);
1687 // If our font got dirtied, go ahead and update it now.
1690 // Line-height is set when we are sure we decided on the font-size.
1691 if (m_lineHeightValue)
1692 applyProperty(CSSPropertyLineHeight, m_lineHeightValue);
1694 applyDeclarations<false>(false, 0, m_matchedDecls.size() - 1, inheritedOnly);
1696 // Start loading images referenced by this style.
1697 loadPendingImages();
1699 #if ENABLE(CSS_SHADERS)
1700 // Start loading the shaders referenced by this style.
1701 loadPendingShaders();
1704 // Now return the style.
1705 return m_style.release();
1708 static void addIntrinsicMargins(RenderStyle* style)
1710 // Intrinsic margin value.
1711 const int intrinsicMargin = 2 * style->effectiveZoom();
1713 // FIXME: Using width/height alone and not also dealing with min-width/max-width is flawed.
1714 // FIXME: Using "quirk" to decide the margin wasn't set is kind of lame.
1715 if (style->width().isIntrinsicOrAuto()) {
1716 if (style->marginLeft().quirk())
1717 style->setMarginLeft(Length(intrinsicMargin, Fixed));
1718 if (style->marginRight().quirk())
1719 style->setMarginRight(Length(intrinsicMargin, Fixed));
1722 if (style->height().isAuto()) {
1723 if (style->marginTop().quirk())
1724 style->setMarginTop(Length(intrinsicMargin, Fixed));
1725 if (style->marginBottom().quirk())
1726 style->setMarginBottom(Length(intrinsicMargin, Fixed));
1730 static EDisplay equivalentBlockDisplay(EDisplay display, bool isFloating, bool strictParsing)
1737 #if ENABLE(CSS_GRID_LAYOUT)
1743 // It is a WinIE bug that floated list items lose their bullets, so we'll emulate the quirk, but only in quirks mode.
1744 if (!strictParsing && isFloating)
1751 case INLINE_FLEXBOX:
1753 #if ENABLE(CSS_GRID_LAYOUT)
1762 case TABLE_ROW_GROUP:
1763 case TABLE_HEADER_GROUP:
1764 case TABLE_FOOTER_GROUP:
1766 case TABLE_COLUMN_GROUP:
1772 ASSERT_NOT_REACHED();
1775 ASSERT_NOT_REACHED();
1779 void CSSStyleSelector::adjustRenderStyle(RenderStyle* style, RenderStyle* parentStyle, Element *e)
1781 // Cache our original display.
1782 style->setOriginalDisplay(style->display());
1784 if (style->display() != NONE) {
1785 // If we have a <td> that specifies a float property, in quirks mode we just drop the float
1787 // Sites also commonly use display:inline/block on <td>s and <table>s. In quirks mode we force
1788 // these tags to retain their display types.
1789 if (!m_checker.strictParsing() && e) {
1790 if (e->hasTagName(tdTag)) {
1791 style->setDisplay(TABLE_CELL);
1792 style->setFloating(NoFloat);
1794 else if (e->hasTagName(tableTag))
1795 style->setDisplay(style->isDisplayInlineType() ? INLINE_TABLE : TABLE);
1798 if (e && (e->hasTagName(tdTag) || e->hasTagName(thTag))) {
1799 if (style->whiteSpace() == KHTML_NOWRAP) {
1800 // Figure out if we are really nowrapping or if we should just
1801 // use normal instead. If the width of the cell is fixed, then
1802 // we don't actually use NOWRAP.
1803 if (style->width().isFixed())
1804 style->setWhiteSpace(NORMAL);
1806 style->setWhiteSpace(NOWRAP);
1810 // Tables never support the -webkit-* values for text-align and will reset back to the default.
1811 if (e && e->hasTagName(tableTag) && (style->textAlign() == WEBKIT_LEFT || style->textAlign() == WEBKIT_CENTER || style->textAlign() == WEBKIT_RIGHT))
1812 style->setTextAlign(TAAUTO);
1814 // Frames and framesets never honor position:relative or position:absolute. This is necessary to
1815 // fix a crash where a site tries to position these objects. They also never honor display.
1816 if (e && (e->hasTagName(frameTag) || e->hasTagName(framesetTag))) {
1817 style->setPosition(StaticPosition);
1818 style->setDisplay(BLOCK);
1821 // Table headers with a text-align of auto will change the text-align to center.
1822 if (e && e->hasTagName(thTag) && style->textAlign() == TAAUTO)
1823 style->setTextAlign(CENTER);
1825 if (e && e->hasTagName(legendTag))
1826 style->setDisplay(BLOCK);
1828 // Absolute/fixed positioned elements, floating elements and the document element need block-like outside display.
1829 if (style->position() == AbsolutePosition || style->position() == FixedPosition || style->isFloating() || (e && e->document()->documentElement() == e))
1830 style->setDisplay(equivalentBlockDisplay(style->display(), style->isFloating(), m_checker.strictParsing()));
1832 // FIXME: Don't support this mutation for pseudo styles like first-letter or first-line, since it's not completely
1833 // clear how that should work.
1834 if (style->display() == INLINE && style->styleType() == NOPSEUDO && parentStyle && style->writingMode() != parentStyle->writingMode())
1835 style->setDisplay(INLINE_BLOCK);
1837 // After performing the display mutation, check table rows. We do not honor position:relative on
1838 // table rows or cells. This has been established in CSS2.1 (and caused a crash in containingBlock()
1840 if ((style->display() == TABLE_HEADER_GROUP || style->display() == TABLE_ROW_GROUP
1841 || style->display() == TABLE_FOOTER_GROUP || style->display() == TABLE_ROW) &&
1842 style->position() == RelativePosition)
1843 style->setPosition(StaticPosition);
1845 // writing-mode does not apply to table row groups, table column groups, table rows, and table columns.
1846 // FIXME: Table cells should be allowed to be perpendicular or flipped with respect to the table, though.
1847 if (style->display() == TABLE_COLUMN || style->display() == TABLE_COLUMN_GROUP || style->display() == TABLE_FOOTER_GROUP
1848 || style->display() == TABLE_HEADER_GROUP || style->display() == TABLE_ROW || style->display() == TABLE_ROW_GROUP
1849 || style->display() == TABLE_CELL)
1850 style->setWritingMode(parentStyle->writingMode());
1852 // FIXME: Since we don't support block-flow on flexible boxes yet, disallow setting
1853 // of block-flow to anything other than TopToBottomWritingMode.
1854 // https://bugs.webkit.org/show_bug.cgi?id=46418 - Flexible box support.
1855 if (style->writingMode() != TopToBottomWritingMode && (style->display() == BOX || style->display() == INLINE_BOX))
1856 style->setWritingMode(TopToBottomWritingMode);
1859 // Make sure our z-index value is only applied if the object is positioned.
1860 if (style->position() == StaticPosition)
1861 style->setHasAutoZIndex();
1863 // Auto z-index becomes 0 for the root element and transparent objects. This prevents
1864 // cases where objects that should be blended as a single unit end up with a non-transparent
1865 // object wedged in between them. Auto z-index also becomes 0 for objects that specify transforms/masks/reflections.
1866 if (style->hasAutoZIndex() && ((e && e->document()->documentElement() == e) || style->opacity() < 1.0f
1867 || style->hasTransformRelatedProperty() || style->hasMask() || style->boxReflect() || style->hasFilter()))
1868 style->setZIndex(0);
1870 // Textarea considers overflow visible as auto.
1871 if (e && e->hasTagName(textareaTag)) {
1872 style->setOverflowX(style->overflowX() == OVISIBLE ? OAUTO : style->overflowX());
1873 style->setOverflowY(style->overflowY() == OVISIBLE ? OAUTO : style->overflowY());
1876 // Finally update our text decorations in effect, but don't allow text-decoration to percolate through
1877 // tables, inline blocks, inline tables, run-ins, or shadow DOM.
1878 if (style->display() == TABLE || style->display() == INLINE_TABLE || style->display() == RUN_IN
1879 || style->display() == INLINE_BLOCK || style->display() == INLINE_BOX || isAtShadowBoundary(e))
1880 style->setTextDecorationsInEffect(style->textDecoration());
1882 style->addToTextDecorationsInEffect(style->textDecoration());
1884 // If either overflow value is not visible, change to auto.
1885 if (style->overflowX() == OMARQUEE && style->overflowY() != OMARQUEE)
1886 style->setOverflowY(OMARQUEE);
1887 else if (style->overflowY() == OMARQUEE && style->overflowX() != OMARQUEE)
1888 style->setOverflowX(OMARQUEE);
1889 else if (style->overflowX() == OVISIBLE && style->overflowY() != OVISIBLE)
1890 style->setOverflowX(OAUTO);
1891 else if (style->overflowY() == OVISIBLE && style->overflowX() != OVISIBLE)
1892 style->setOverflowY(OAUTO);
1894 // Table rows, sections and the table itself will support overflow:hidden and will ignore scroll/auto.
1895 // FIXME: Eventually table sections will support auto and scroll.
1896 if (style->display() == TABLE || style->display() == INLINE_TABLE ||
1897 style->display() == TABLE_ROW_GROUP || style->display() == TABLE_ROW) {
1898 if (style->overflowX() != OVISIBLE && style->overflowX() != OHIDDEN)
1899 style->setOverflowX(OVISIBLE);
1900 if (style->overflowY() != OVISIBLE && style->overflowY() != OHIDDEN)
1901 style->setOverflowY(OVISIBLE);
1904 // Menulists should have visible overflow
1905 if (style->appearance() == MenulistPart) {
1906 style->setOverflowX(OVISIBLE);
1907 style->setOverflowY(OVISIBLE);
1910 // Cull out any useless layers and also repeat patterns into additional layers.
1911 style->adjustBackgroundLayers();
1912 style->adjustMaskLayers();
1914 // Do the same for animations and transitions.
1915 style->adjustAnimations();
1916 style->adjustTransitions();
1918 // Important: Intrinsic margins get added to controls before the theme has adjusted the style, since the theme will
1919 // alter fonts and heights/widths.
1920 if (e && e->isFormControlElement() && style->fontSize() >= 11) {
1921 // Don't apply intrinsic margins to image buttons. The designer knows how big the images are,
1922 // so we have to treat all image buttons as though they were explicitly sized.
1923 if (!e->hasTagName(inputTag) || !static_cast<HTMLInputElement*>(e)->isImageButton())
1924 addIntrinsicMargins(style);
1927 // Let the theme also have a crack at adjusting the style.
1928 if (style->hasAppearance())
1929 RenderTheme::defaultTheme()->adjustStyle(this, style, e, m_hasUAAppearance, m_borderData, m_backgroundData, m_backgroundColor);
1931 // If we have first-letter pseudo style, do not share this style.
1932 if (style->hasPseudoStyle(FIRST_LETTER))
1936 if (e && e->isSVGElement()) {
1937 // Spec: http://www.w3.org/TR/SVG/masking.html#OverflowProperty
1938 if (style->overflowY() == OSCROLL)
1939 style->setOverflowY(OHIDDEN);
1940 else if (style->overflowY() == OAUTO)
1941 style->setOverflowY(OVISIBLE);
1943 if (style->overflowX() == OSCROLL)
1944 style->setOverflowX(OHIDDEN);
1945 else if (style->overflowX() == OAUTO)
1946 style->setOverflowX(OVISIBLE);
1948 // Only the root <svg> element in an SVG document fragment tree honors css position
1949 if (!(e->hasTagName(SVGNames::svgTag) && e->parentNode() && !e->parentNode()->isSVGElement()))
1950 style->setPosition(RenderStyle::initialPosition());
1955 bool CSSStyleSelector::checkRegionStyle(Element* regionElement)
1957 // FIXME (BUG 72472): We don't add @-webkit-region rules of scoped style sheets for the moment,
1958 // so all region rules are global by default. Verify whether that can stand or needs changing.
1960 unsigned rulesSize = m_authorStyle->m_regionSelectorsAndRuleSets.size();
1961 for (unsigned i = 0; i < rulesSize; ++i) {
1962 ASSERT(m_authorStyle->m_regionSelectorsAndRuleSets.at(i).ruleSet.get());
1963 if (checkRegionSelector(m_authorStyle->m_regionSelectorsAndRuleSets.at(i).selector, regionElement))
1968 rulesSize = m_userStyle->m_regionSelectorsAndRuleSets.size();
1969 for (unsigned i = 0; i < rulesSize; ++i) {
1970 ASSERT(m_userStyle->m_regionSelectorsAndRuleSets.at(i).ruleSet.get());
1971 if (checkRegionSelector(m_userStyle->m_regionSelectorsAndRuleSets.at(i).selector, regionElement))
1979 void CSSStyleSelector::updateFont()
1984 checkForTextSizeAdjust();
1985 checkForGenericFamilyChange(style(), m_parentStyle);
1986 checkForZoomChange(style(), m_parentStyle);
1987 m_style->font().update(m_fontSelector);
1988 m_fontDirty = false;
1991 void CSSStyleSelector::cacheBorderAndBackground()
1993 m_hasUAAppearance = m_style->hasAppearance();
1994 if (m_hasUAAppearance) {
1995 m_borderData = m_style->border();
1996 m_backgroundData = *m_style->backgroundLayers();
1997 m_backgroundColor = m_style->backgroundColor();
2001 PassRefPtr<CSSRuleList> CSSStyleSelector::styleRulesForElement(Element* e, unsigned rulesToInclude)
2003 return pseudoStyleRulesForElement(e, NOPSEUDO, rulesToInclude);
2006 PassRefPtr<CSSRuleList> CSSStyleSelector::pseudoStyleRulesForElement(Element* e, PseudoId pseudoId, unsigned rulesToInclude)
2008 if (!e || !e->document()->haveStylesheetsLoaded())
2011 m_checker.setCollectingRulesOnly(true);
2014 initForStyleResolve(e, 0, pseudoId);
2017 if (rulesToInclude & UAAndUserCSSRules) {
2018 // First we match rules from the user agent sheet.
2019 matchUARules(dummy);
2021 // Now we check user sheet rules.
2022 if (m_matchAuthorAndUserStyles)
2023 matchRules(m_userStyle.get(), dummy.ranges.firstUserRule, dummy.ranges.lastUserRule, rulesToInclude & EmptyCSSRules);
2026 if (m_matchAuthorAndUserStyles && (rulesToInclude & AuthorCSSRules)) {
2027 m_sameOriginOnly = !(rulesToInclude & CrossOriginCSSRules);
2029 // Check the rules in author sheets.
2030 matchAuthorRules(dummy.ranges.firstAuthorRule, dummy.ranges.lastAuthorRule, rulesToInclude & EmptyCSSRules);
2032 m_sameOriginOnly = false;
2035 m_checker.setCollectingRulesOnly(false);
2037 return m_ruleList.release();
2040 inline bool CSSStyleSelector::checkSelector(const RuleData& ruleData)
2042 m_dynamicPseudo = NOPSEUDO;
2043 m_checker.clearHasUnknownPseudoElements();
2045 // Let the slow path handle SVG as it has some additional rules regarding shadow trees.
2046 if (ruleData.hasFastCheckableSelector() && !m_element->isSVGElement()) {
2047 // We know this selector does not include any pseudo elements.
2048 if (m_checker.pseudoStyle() != NOPSEUDO)
2050 // We know a sufficiently simple single part selector matches simply because we found it from the rule hash.
2051 // This is limited to HTML only so we don't need to check the namespace.
2052 if (ruleData.hasRightmostSelectorMatchingHTMLBasedOnRuleHash() && m_element->isHTMLElement()) {
2053 if (!ruleData.hasMultipartSelector())
2055 } else if (!SelectorChecker::tagMatches(m_element, ruleData.selector()))
2057 if (!SelectorChecker::fastCheckRightmostAttributeSelector(m_element, ruleData.selector()))
2059 return m_checker.fastCheckSelector(ruleData.selector(), m_element);
2063 SelectorChecker::SelectorMatch match = m_checker.checkSelector(ruleData.selector(), m_element, m_dynamicPseudo, false, SelectorChecker::VisitedMatchEnabled, style(), m_parentNode ? m_parentNode->renderStyle() : 0);
2064 if (match != SelectorChecker::SelectorMatches)
2066 if (m_checker.pseudoStyle() != NOPSEUDO && m_checker.pseudoStyle() != m_dynamicPseudo)
2071 bool CSSStyleSelector::checkRegionSelector(CSSSelector* regionSelector, Element* regionElement)
2073 if (!regionSelector || !regionElement)
2076 m_checker.clearHasUnknownPseudoElements();
2077 m_checker.setPseudoStyle(NOPSEUDO);
2079 for (CSSSelector* s = regionSelector; s; s = CSSSelectorList::next(s))
2080 if (m_checker.checkSelector(s, regionElement))
2086 bool CSSStyleSelector::determineStylesheetSelectorScopes(CSSStyleSheet* stylesheet, HashSet<AtomicStringImpl*>& idScopes, HashSet<AtomicStringImpl*>& classScopes)
2088 ASSERT(!stylesheet->isLoading());
2090 size_t size = stylesheet->length();
2091 for (size_t i = 0; i < size; i++) {
2092 CSSRule* rule = stylesheet->item(i);
2093 if (rule->isStyleRule()) {
2094 CSSStyleRule* styleRule = static_cast<CSSStyleRule*>(rule);
2095 if (!SelectorChecker::determineSelectorScopes(styleRule->selectorList(), idScopes, classScopes))
2099 if (rule->isImportRule()) {
2100 CSSImportRule* importRule = static_cast<CSSImportRule*>(rule);
2101 if (importRule->styleSheet()) {
2102 if (!determineStylesheetSelectorScopes(importRule->styleSheet(), idScopes, classScopes))
2107 // FIXME: Media rules and maybe some others could be allowed.
2113 // -----------------------------------------------------------------
2115 static inline bool isSelectorMatchingHTMLBasedOnRuleHash(const CSSSelector* selector)
2117 const AtomicString& selectorNamespace = selector->tag().namespaceURI();
2118 if (selectorNamespace != starAtom && selectorNamespace != xhtmlNamespaceURI)
2120 if (selector->m_match == CSSSelector::None)
2122 if (selector->tag() != starAtom)
2124 if (SelectorChecker::isCommonPseudoClassSelector(selector))
2126 return selector->m_match == CSSSelector::Id || selector->m_match == CSSSelector::Class;
2129 static inline bool selectorListContainsUncommonAttributeSelector(const CSSSelector* selector)
2131 CSSSelectorList* selectorList = selector->selectorList();
2134 for (CSSSelector* subSelector = selectorList->first(); subSelector; subSelector = CSSSelectorList::next(subSelector)) {
2135 if (subSelector->isAttributeSelector())
2141 static inline bool isCommonAttributeSelectorAttribute(const QualifiedName& attribute)
2143 // These are explicitly tested for equality in canShareStyleWithElement.
2144 return attribute == typeAttr || attribute == readonlyAttr;
2147 static inline bool containsUncommonAttributeSelector(const CSSSelector* selector)
2150 // Allow certain common attributes (used in the default style) in the selectors that match the current element.
2151 if (selector->isAttributeSelector() && !isCommonAttributeSelectorAttribute(selector->attribute()))
2153 if (selectorListContainsUncommonAttributeSelector(selector))
2155 if (selector->relation() != CSSSelector::SubSelector)
2157 selector = selector->tagHistory();
2160 for (selector = selector->tagHistory(); selector; selector = selector->tagHistory()) {
2161 if (selector->isAttributeSelector())
2163 if (selectorListContainsUncommonAttributeSelector(selector))
2169 RuleData::RuleData(CSSStyleRule* rule, CSSSelector* selector, unsigned position)
2171 , m_selector(selector)
2172 , m_specificity(selector->specificity())
2173 , m_position(position)
2174 , m_hasFastCheckableSelector(SelectorChecker::isFastCheckableSelector(selector))
2175 , m_hasMultipartSelector(!!selector->tagHistory())
2176 , m_hasRightmostSelectorMatchingHTMLBasedOnRuleHash(isSelectorMatchingHTMLBasedOnRuleHash(selector))
2177 , m_containsUncommonAttributeSelector(WebCore::containsUncommonAttributeSelector(selector))
2178 , m_linkMatchType(SelectorChecker::determineLinkMatchType(selector))
2180 SelectorChecker::collectIdentifierHashes(m_selector, m_descendantSelectorIdentifierHashes, maximumIdentifierCount);
2185 , m_autoShrinkToFitEnabled(true)
2189 static inline void collectFeaturesFromSelector(CSSStyleSelector::Features& features, const CSSSelector* selector)
2191 if (selector->m_match == CSSSelector::Id)
2192 features.idsInRules.add(selector->value().impl());
2193 if (selector->isAttributeSelector())
2194 features.attrsInRules.add(selector->attribute().localName().impl());
2195 switch (selector->pseudoType()) {
2196 case CSSSelector::PseudoFirstLine:
2197 features.usesFirstLineRules = true;
2199 case CSSSelector::PseudoBefore:
2200 case CSSSelector::PseudoAfter:
2201 features.usesBeforeAfterRules = true;
2203 case CSSSelector::PseudoLink:
2204 case CSSSelector::PseudoVisited:
2205 features.usesLinkRules = true;
2212 static void collectFeaturesFromRuleData(CSSStyleSelector::Features& features, const RuleData& ruleData)
2214 bool foundSiblingSelector = false;
2215 for (CSSSelector* selector = ruleData.selector(); selector; selector = selector->tagHistory()) {
2216 collectFeaturesFromSelector(features, selector);
2218 if (CSSSelectorList* selectorList = selector->selectorList()) {
2219 for (CSSSelector* subSelector = selectorList->first(); subSelector; subSelector = CSSSelectorList::next(subSelector)) {
2220 if (!foundSiblingSelector && selector->isSiblingSelector())
2221 foundSiblingSelector = true;
2222 collectFeaturesFromSelector(features, subSelector);
2224 } else if (!foundSiblingSelector && selector->isSiblingSelector())
2225 foundSiblingSelector = true;
2227 if (foundSiblingSelector)
2228 features.siblingRules.append(CSSStyleSelector::RuleSelectorPair(ruleData.rule(), ruleData.selector()));
2229 if (ruleData.containsUncommonAttributeSelector())
2230 features.uncommonAttributeRules.append(CSSStyleSelector::RuleSelectorPair(ruleData.rule(), ruleData.selector()));
2233 void RuleSet::addToRuleSet(AtomicStringImpl* key, AtomRuleMap& map, const RuleData& ruleData)
2237 OwnPtr<Vector<RuleData> >& rules = map.add(key, nullptr).first->second;
2239 rules = adoptPtr(new Vector<RuleData>);
2240 rules->append(ruleData);
2243 void RuleSet::addRule(CSSStyleRule* rule, CSSSelector* selector)
2245 RuleData ruleData(rule, selector, m_ruleCount++);
2246 collectFeaturesFromRuleData(m_features, ruleData);
2248 if (selector->m_match == CSSSelector::Id) {
2249 addToRuleSet(selector->value().impl(), m_idRules, ruleData);
2252 if (selector->m_match == CSSSelector::Class) {
2253 addToRuleSet(selector->value().impl(), m_classRules, ruleData);
2256 if (selector->isUnknownPseudoElement()) {
2257 addToRuleSet(selector->value().impl(), m_shadowPseudoElementRules, ruleData);
2260 if (SelectorChecker::isCommonPseudoClassSelector(selector)) {
2261 switch (selector->pseudoType()) {
2262 case CSSSelector::PseudoLink:
2263 case CSSSelector::PseudoVisited:
2264 case CSSSelector::PseudoAnyLink:
2265 m_linkPseudoClassRules.append(ruleData);
2267 case CSSSelector::PseudoFocus:
2268 m_focusPseudoClassRules.append(ruleData);
2271 ASSERT_NOT_REACHED();
2275 const AtomicString& localName = selector->tag().localName();
2276 if (localName != starAtom) {
2277 addToRuleSet(localName.impl(), m_tagRules, ruleData);
2280 m_universalRules.append(ruleData);
2283 void RuleSet::addPageRule(CSSPageRule* rule)
2285 m_pageRules.append(RuleData(rule, rule->selectorList().first(), m_pageRules.size()));
2288 void RuleSet::addRegionRule(WebKitCSSRegionRule* rule)
2290 RuleSet* regionRuleSet = new RuleSet;
2291 // The region rule set should take into account the position inside the parent rule set.
2292 // Otherwise, the rules inside region block might be incorrectly positioned before other similar rules from
2293 // the stylesheet that contains the region block.
2294 regionRuleSet->m_ruleCount = m_ruleCount;
2296 // Collect the region rules into a rule set
2297 CSSRuleList* regionStylingRules = rule->cssRules();
2298 unsigned rulesSize = regionStylingRules->length();
2299 for (unsigned i = 0; i < rulesSize; ++i) {
2300 CSSRule* regionStylingRule = regionStylingRules->item(i);
2301 if (regionStylingRule->isStyleRule())
2302 regionRuleSet->addStyleRule(static_cast<CSSStyleRule*>(regionStylingRule));
2305 m_regionSelectorsAndRuleSets.append(RuleSetSelectorPair(rule->selectorList().first(), regionRuleSet));
2308 void RuleSet::addRulesFromSheet(CSSStyleSheet* sheet, const MediaQueryEvaluator& medium, CSSStyleSelector* styleSelector, const Element* scope)
2312 // No media implies "all", but if a media list exists it must
2313 // contain our current medium
2314 if (sheet->media() && !medium.eval(sheet->media(), styleSelector))
2315 return; // the style sheet doesn't apply
2317 int len = sheet->length();
2319 for (int i = 0; i < len; i++) {
2320 CSSRule* rule = sheet->item(i);
2321 if (rule->isStyleRule())
2322 addStyleRule(static_cast<CSSStyleRule*>(rule));
2323 else if (rule->isPageRule())
2324 addPageRule(static_cast<CSSPageRule*>(rule));
2325 else if (rule->isImportRule()) {
2326 CSSImportRule* import = static_cast<CSSImportRule*>(rule);
2327 if (import->styleSheet() && (!import->media() || medium.eval(import->media(), styleSelector)))
2328 addRulesFromSheet(import->styleSheet(), medium, styleSelector, scope);
2330 else if (rule->isMediaRule()) {
2331 CSSMediaRule* r = static_cast<CSSMediaRule*>(rule);
2332 CSSRuleList* rules = r->cssRules();
2334 if ((!r->media() || medium.eval(r->media(), styleSelector)) && rules) {
2335 // Traverse child elements of the @media rule.
2336 for (unsigned j = 0; j < rules->length(); j++) {
2337 CSSRule *childItem = rules->item(j);
2338 if (childItem->isStyleRule())
2339 addStyleRule(static_cast<CSSStyleRule*>(childItem));
2340 else if (childItem->isPageRule())
2341 addPageRule(static_cast<CSSPageRule*>(childItem));
2342 else if (childItem->isFontFaceRule() && styleSelector) {
2343 // Add this font face to our set.
2344 // FIXME(BUG 72461): We don't add @font-face rules of scoped style sheets for the moment.
2347 const CSSFontFaceRule* fontFaceRule = static_cast<CSSFontFaceRule*>(childItem);
2348 styleSelector->fontSelector()->addFontFaceRule(fontFaceRule);
2349 styleSelector->invalidateMatchedDeclarationCache();
2350 } else if (childItem->isKeyframesRule() && styleSelector) {
2351 // Add this keyframe rule to our set.
2352 // FIXME(BUG 72462): We don't add @keyframe rules of scoped style sheets for the moment.
2355 styleSelector->addKeyframeStyle(static_cast<WebKitCSSKeyframesRule*>(childItem));
2359 } else if (rule->isFontFaceRule() && styleSelector) {
2360 // Add this font face to our set.
2361 // FIXME(BUG 72461): We don't add @font-face rules of scoped style sheets for the moment.
2364 const CSSFontFaceRule* fontFaceRule = static_cast<CSSFontFaceRule*>(rule);
2365 styleSelector->fontSelector()->addFontFaceRule(fontFaceRule);
2366 styleSelector->invalidateMatchedDeclarationCache();
2367 } else if (rule->isKeyframesRule()) {
2368 // FIXME (BUG 72462): We don't add @keyframe rules of scoped style sheets for the moment.
2371 styleSelector->addKeyframeStyle(static_cast<WebKitCSSKeyframesRule*>(rule));
2372 } else if (rule->isRegionRule() && styleSelector) {
2373 // FIXME (BUG 72472): We don't add @-webkit-region rules of scoped style sheets for the moment.
2376 addRegionRule(static_cast<WebKitCSSRegionRule*>(rule));
2379 if (m_autoShrinkToFitEnabled)
2383 void RuleSet::addStyleRule(CSSStyleRule* rule)
2385 for (CSSSelector* s = rule->selectorList().first(); s; s = CSSSelectorList::next(s))
2389 static inline void shrinkMapVectorsToFit(RuleSet::AtomRuleMap& map)
2391 RuleSet::AtomRuleMap::iterator end = map.end();
2392 for (RuleSet::AtomRuleMap::iterator it = map.begin(); it != end; ++it)
2393 it->second->shrinkToFit();
2396 void RuleSet::shrinkToFit()
2398 shrinkMapVectorsToFit(m_idRules);
2399 shrinkMapVectorsToFit(m_classRules);
2400 shrinkMapVectorsToFit(m_tagRules);
2401 shrinkMapVectorsToFit(m_shadowPseudoElementRules);
2402 m_linkPseudoClassRules.shrinkToFit();
2403 m_focusPseudoClassRules.shrinkToFit();
2404 m_universalRules.shrinkToFit();
2405 m_pageRules.shrinkToFit();
2408 // -------------------------------------------------------------------------------------
2409 // this is mostly boring stuff on how to apply a certain rule to the renderstyle...
2411 static Length convertToLength(CSSPrimitiveValue* primitiveValue, RenderStyle* style, RenderStyle* rootStyle, bool toFloat, double multiplier = 1, bool *ok = 0)
2413 // This function is tolerant of a null style value. The only place style is used is in
2414 // length measurements, like 'ems' and 'px'. And in those cases style is only used
2415 // when the units are EMS or EXS. So we will just fail in those cases.
2417 if (!primitiveValue) {
2421 if (!style && primitiveValue->isFontRelativeLength()) {
2424 } else if (primitiveValue->isLength()) {
2426 l = Length(primitiveValue->computeLength<double>(style, rootStyle, multiplier), Fixed);
2428 l = primitiveValue->computeLength<Length>(style, rootStyle, multiplier);
2429 } else if (primitiveValue->isPercentage())
2430 l = Length(primitiveValue->getDoubleValue(), Percent);
2431 else if (primitiveValue->isNumber())
2432 l = Length(primitiveValue->getDoubleValue() * 100.0, Percent);
2439 static Length convertToIntLength(CSSPrimitiveValue* primitiveValue, RenderStyle* style, RenderStyle* rootStyle, double multiplier = 1, bool *ok = 0)
2441 return convertToLength(primitiveValue, style, rootStyle, false, multiplier, ok);
2444 static Length convertToFloatLength(CSSPrimitiveValue* primitiveValue, RenderStyle* style, RenderStyle* rootStyle, double multiplier = 1, bool *ok = 0)
2446 return convertToLength(primitiveValue, style, rootStyle, true, multiplier, ok);
2449 static inline bool isInsideRegionRule(StylePropertySet* styleDeclaration)
2451 ASSERT(styleDeclaration);
2453 CSSRule* parentRule = styleDeclaration->parentRuleInternal();
2454 while (parentRule) {
2455 if (parentRule->isRegionRule())
2457 parentRule = parentRule->parentRule();
2462 template <bool applyFirst>
2463 void CSSStyleSelector::applyDeclaration(StylePropertySet* styleDeclaration, bool isImportant, bool inheritedOnly)
2465 InspectorInstrumentationCookie cookie = InspectorInstrumentation::willProcessRule(document(), styleDeclaration->parentRuleInternal());
2466 bool styleDeclarationInsideRegionRule = m_regionForStyling ? isInsideRegionRule(styleDeclaration) : false;
2468 unsigned propertyCount = styleDeclaration->propertyCount();
2469 for (unsigned i = 0; i < propertyCount; ++i) {
2470 const CSSProperty& current = styleDeclaration->propertyAt(i);
2471 if (isImportant != current.isImportant())
2473 if (inheritedOnly && !current.isInherited()) {
2474 // If the property value is explicitly inherited, we need to apply further non-inherited properties
2475 // as they might override the value inherited here. For this reason we don't allow declarations with
2476 // explicitly inherited properties to be cached.
2477 ASSERT(!current.value()->isInheritedValue());
2480 int property = current.id();
2482 // Filter the properties that can be applied using region styling.
2483 if (styleDeclarationInsideRegionRule && !CSSStyleSelector::isValidRegionStyleProperty(property))
2487 COMPILE_ASSERT(firstCSSProperty == CSSPropertyColor, CSS_color_is_first_property);
2488 COMPILE_ASSERT(CSSPropertyZoom == CSSPropertyColor + 18, CSS_zoom_is_end_of_first_prop_range);
2489 COMPILE_ASSERT(CSSPropertyLineHeight == CSSPropertyZoom + 1, CSS_line_height_is_after_zoom);
2490 // give special priority to font-xxx, color properties, etc
2491 if (property > CSSPropertyLineHeight)
2493 // we apply line-height later
2494 if (property == CSSPropertyLineHeight) {
2495 m_lineHeightValue = current.value();
2498 applyProperty(current.id(), current.value());
2501 if (property > CSSPropertyLineHeight)
2502 applyProperty(current.id(), current.value());
2504 InspectorInstrumentation::didProcessRule(cookie);
2507 template <bool applyFirst>
2508 void CSSStyleSelector::applyDeclarations(bool isImportant, int startIndex, int endIndex, bool inheritedOnly)
2510 if (startIndex == -1)
2513 if (m_style->insideLink() != NotInsideLink) {
2514 for (int i = startIndex; i <= endIndex; ++i) {
2515 StylePropertySet* styleDeclaration = m_matchedDecls[i].styleDeclaration.get();
2516 unsigned linkMatchType = m_matchedDecls[i].linkMatchType;
2517 // FIXME: It would be nicer to pass these as arguments but that requires changes in many places.
2518 m_applyPropertyToRegularStyle = linkMatchType & SelectorChecker::MatchLink;
2519 m_applyPropertyToVisitedLinkStyle = linkMatchType & SelectorChecker::MatchVisited;
2521 applyDeclaration<applyFirst>(styleDeclaration, isImportant, inheritedOnly);
2523 m_applyPropertyToRegularStyle = true;
2524 m_applyPropertyToVisitedLinkStyle = false;
2527 for (int i = startIndex; i <= endIndex; ++i)
2528 applyDeclaration<applyFirst>(m_matchedDecls[i].styleDeclaration.get(), isImportant, inheritedOnly);
2531 unsigned CSSStyleSelector::computeDeclarationHash(MatchedStyleDeclaration* declarations, unsigned size)
2533 return StringHasher::hashMemory(declarations, sizeof(MatchedStyleDeclaration) * size);
2536 bool operator==(const CSSStyleSelector::MatchRanges& a, const CSSStyleSelector::MatchRanges& b)
2538 return a.firstUARule == b.firstUARule
2539 && a.lastUARule == b.lastUARule
2540 && a.firstAuthorRule == b.firstAuthorRule
2541 && a.lastAuthorRule == b.lastAuthorRule
2542 && a.firstUserRule == b.firstUserRule
2543 && a.lastUserRule == b.lastUserRule;
2546 bool operator!=(const CSSStyleSelector::MatchRanges& a, const CSSStyleSelector::MatchRanges& b)
2551 bool operator==(const CSSStyleSelector::MatchedStyleDeclaration& a, const CSSStyleSelector::MatchedStyleDeclaration& b)
2553 return a.styleDeclaration == b.styleDeclaration && a.linkMatchType == b.linkMatchType;
2556 bool operator!=(const CSSStyleSelector::MatchedStyleDeclaration& a, const CSSStyleSelector::MatchedStyleDeclaration& b)
2561 const CSSStyleSelector::MatchedStyleDeclarationCacheItem* CSSStyleSelector::findFromMatchedDeclarationCache(unsigned hash, const MatchResult& matchResult)
2565 MatchedStyleDeclarationCache::iterator it = m_matchedStyleDeclarationCache.find(hash);
2566 if (it == m_matchedStyleDeclarationCache.end())
2568 MatchedStyleDeclarationCacheItem& cacheItem = it->second;
2570 size_t size = m_matchedDecls.size();
2571 if (size != cacheItem.matchedStyleDeclarations.size())
2573 for (size_t i = 0; i < size; ++i) {
2574 if (m_matchedDecls[i] != cacheItem.matchedStyleDeclarations[i])
2577 if (cacheItem.ranges != matchResult.ranges)
2582 void CSSStyleSelector::addToMatchedDeclarationCache(const RenderStyle* style, const RenderStyle* parentStyle, unsigned hash, const MatchResult& matchResult)
2584 static unsigned matchedDeclarationCacheAdditionsBetweenSweeps = 100;
2585 if (++m_matchedDeclarationCacheAdditionsSinceLastSweep >= matchedDeclarationCacheAdditionsBetweenSweeps) {
2586 sweepMatchedDeclarationCache();
2587 m_matchedDeclarationCacheAdditionsSinceLastSweep = 0;
2591 MatchedStyleDeclarationCacheItem cacheItem;
2592 cacheItem.matchedStyleDeclarations.append(m_matchedDecls);
2593 cacheItem.ranges = matchResult.ranges;
2594 // Note that we don't cache the original RenderStyle instance. It may be further modified.
2595 // The RenderStyle in the cache is really just a holder for the substructures and never used as-is.
2596 cacheItem.renderStyle = RenderStyle::clone(style);
2597 cacheItem.parentRenderStyle = RenderStyle::clone(parentStyle);
2598 m_matchedStyleDeclarationCache.add(hash, cacheItem);
2601 void CSSStyleSelector::invalidateMatchedDeclarationCache()
2603 m_matchedStyleDeclarationCache.clear();
2606 static bool isCacheableInMatchedDeclarationCache(const RenderStyle* style, const RenderStyle* parentStyle)
2608 if (style->unique() || (style->styleType() != NOPSEUDO && parentStyle->unique()))
2610 if (style->hasAppearance())
2612 if (style->zoom() != RenderStyle::initialZoom())
2614 // The cache assumes static knowledge about which properties are inherited.
2615 if (parentStyle->hasExplicitlyInheritedProperties())
2620 void CSSStyleSelector::applyMatchedDeclarations(const MatchResult& matchResult)
2622 unsigned cacheHash = matchResult.isCacheable ? computeDeclarationHash(m_matchedDecls.data(), m_matchedDecls.size()) : 0;
2623 bool applyInheritedOnly = false;
2624 const MatchedStyleDeclarationCacheItem* cacheItem = 0;
2625 if (cacheHash && (cacheItem = findFromMatchedDeclarationCache(cacheHash, matchResult))) {
2626 // We can build up the style by copying non-inherited properties from an earlier style object built using the same exact
2627 // style declarations. We then only need to apply the inherited properties, if any, as their values can depend on the
2628 // element context. This is fast and saves memory by reusing the style data structures.
2629 m_style->copyNonInheritedFrom(cacheItem->renderStyle.get());
2630 if (m_parentStyle->inheritedDataShared(cacheItem->parentRenderStyle.get())) {
2631 EInsideLink linkStatus = m_style->insideLink();
2632 // If the cache item parent style has identical inherited properties to the current parent style then the
2633 // resulting style will be identical too. We copy the inherited properties over from the cache and are done.
2634 m_style->inheritFrom(cacheItem->renderStyle.get());
2635 // Unfortunately the link status is treated like an inherited property. We need to explicitly restore it.
2636 m_style->setInsideLink(linkStatus);
2639 applyInheritedOnly = true;
2641 // Now we have all of the matched rules in the appropriate order. Walk the rules and apply
2642 // high-priority properties first, i.e., those properties that other properties depend on.
2643 // The order is (1) high-priority not important, (2) high-priority important, (3) normal not important
2644 // and (4) normal important.
2645 m_lineHeightValue = 0;
2646 applyDeclarations<true>(false, 0, m_matchedDecls.size() - 1, applyInheritedOnly);
2647 applyDeclarations<true>(true, matchResult.ranges.firstAuthorRule, matchResult.ranges.lastAuthorRule, applyInheritedOnly);
2648 applyDeclarations<true>(true, matchResult.ranges.firstUserRule, matchResult.ranges.lastUserRule, applyInheritedOnly);
2649 applyDeclarations<true>(true, matchResult.ranges.firstUARule, matchResult.ranges.lastUARule, applyInheritedOnly);
2651 if (cacheItem && cacheItem->renderStyle->effectiveZoom() != m_style->effectiveZoom()) {
2653 applyInheritedOnly = false;
2656 // If our font got dirtied, go ahead and update it now.
2659 // Line-height is set when we are sure we decided on the font-size.
2660 if (m_lineHeightValue)
2661 applyProperty(CSSPropertyLineHeight, m_lineHeightValue);
2663 // Many properties depend on the font. If it changes we just apply all properties.
2664 if (cacheItem && cacheItem->renderStyle->fontDescription() != m_style->fontDescription())
2665 applyInheritedOnly = false;
2667 // Now do the normal priority UA properties.
2668 applyDeclarations<false>(false, matchResult.ranges.firstUARule, matchResult.ranges.lastUARule, applyInheritedOnly);
2670 // Cache our border and background so that we can examine them later.
2671 cacheBorderAndBackground();
2673 // Now do the author and user normal priority properties and all the !important properties.
2674 applyDeclarations<false>(false, matchResult.ranges.lastUARule + 1, m_matchedDecls.size() - 1, applyInheritedOnly);
2675 applyDeclarations<false>(true, matchResult.ranges.firstAuthorRule, matchResult.ranges.lastAuthorRule, applyInheritedOnly);
2676 applyDeclarations<false>(true, matchResult.ranges.firstUserRule, matchResult.ranges.lastUserRule, applyInheritedOnly);
2677 applyDeclarations<false>(true, matchResult.ranges.firstUARule, matchResult.ranges.lastUARule, applyInheritedOnly);
2679 loadPendingImages();
2681 #if ENABLE(CSS_SHADERS)
2682 loadPendingShaders();
2685 ASSERT(!m_fontDirty);
2687 if (cacheItem || !cacheHash)
2689 if (!isCacheableInMatchedDeclarationCache(m_style.get(), m_parentStyle))
2691 addToMatchedDeclarationCache(m_style.get(), m_parentStyle, cacheHash, matchResult);
2694 void CSSStyleSelector::matchPageRules(RuleSet* rules, bool isLeftPage, bool isFirstPage, const String& pageName)
2696 m_matchedRules.clear();
2701 matchPageRulesForList(rules->pageRules(), isLeftPage, isFirstPage, pageName);
2703 // If we didn't match any rules, we're done.
2704 if (m_matchedRules.isEmpty())
2707 // Sort the set of matched rules.
2710 // Now transfer the set of matched rules over to our list of decls.
2711 for (unsigned i = 0; i < m_matchedRules.size(); i++)
2712 addMatchedDeclaration(m_matchedRules[i]->rule()->declaration());
2715 void CSSStyleSelector::matchPageRulesForList(const Vector<RuleData>* rules, bool isLeftPage, bool isFirstPage, const String& pageName)
2720 unsigned size = rules->size();
2721 for (unsigned i = 0; i < size; ++i) {
2722 const RuleData& ruleData = rules->at(i);
2723 CSSStyleRule* rule = ruleData.rule();
2724 const AtomicString& selectorLocalName = ruleData.selector()->tag().localName();
2725 if (selectorLocalName != starAtom && selectorLocalName != pageName)
2727 CSSSelector::PseudoType pseudoType = ruleData.selector()->pseudoType();
2728 if ((pseudoType == CSSSelector::PseudoLeftPage && !isLeftPage)
2729 || (pseudoType == CSSSelector::PseudoRightPage && isLeftPage)
2730 || (pseudoType == CSSSelector::PseudoFirstPage && !isFirstPage))
2733 // If the rule has no properties to apply, then ignore it.
2734 StylePropertySet* decl = rule->declaration();
2735 if (!decl || decl->isEmpty())
2738 // Add this rule to our list of matched rules.
2739 addMatchedRule(&ruleData);
2743 bool CSSStyleSelector::isLeftPage(int pageIndex) const
2745 bool isFirstPageLeft = false;
2746 if (!m_rootElementStyle->isLeftToRightDirection())
2747 isFirstPageLeft = true;
2749 return (pageIndex + (isFirstPageLeft ? 1 : 0)) % 2;
2752 bool CSSStyleSelector::isFirstPage(int pageIndex) const
2754 // FIXME: In case of forced left/right page, page at index 1 (not 0) can be the first page.
2755 return (!pageIndex);
2758 String CSSStyleSelector::pageName(int /* pageIndex */) const
2760 // FIXME: Implement page index to page name mapping.
2764 void CSSStyleSelector::applyPropertyToStyle(int id, CSSValue* value, RenderStyle* style)
2767 initForStyleResolve(0, style);
2769 applyPropertyToCurrentStyle(id, value);
2772 void CSSStyleSelector::applyPropertyToCurrentStyle(int id, CSSValue* value)
2775 applyProperty(id, value);
2778 inline bool isValidVisitedLinkProperty(int id)
2780 switch(static_cast<CSSPropertyID>(id)) {
2781 case CSSPropertyBackgroundColor:
2782 case CSSPropertyBorderLeftColor:
2783 case CSSPropertyBorderRightColor:
2784 case CSSPropertyBorderTopColor:
2785 case CSSPropertyBorderBottomColor:
2786 case CSSPropertyColor:
2787 case CSSPropertyOutlineColor:
2788 case CSSPropertyWebkitColumnRuleColor:
2789 case CSSPropertyWebkitTextEmphasisColor:
2790 case CSSPropertyWebkitTextFillColor:
2791 case CSSPropertyWebkitTextStrokeColor:
2792 // Also allow shorthands so that inherit/initial still work.
2793 case CSSPropertyBackground:
2794 case CSSPropertyBorderLeft:
2795 case CSSPropertyBorderRight:
2796 case CSSPropertyBorderTop:
2797 case CSSPropertyBorderBottom:
2798 case CSSPropertyOutline:
2799 case CSSPropertyWebkitColumnRule:
2801 case CSSPropertyFill:
2802 case CSSPropertyStroke:
2812 // http://dev.w3.org/csswg/css3-regions/#the-at-region-style-rule
2813 // FIXME: add incremental support for other region styling properties.
2814 inline bool CSSStyleSelector::isValidRegionStyleProperty(int id)
2816 switch (static_cast<CSSPropertyID>(id)) {
2817 case CSSPropertyBackgroundColor:
2826 // SVG handles zooming in a different way compared to CSS. The whole document is scaled instead
2827 // of each individual length value in the render style / tree. CSSPrimitiveValue::computeLength*()
2828 // multiplies each resolved length with the zoom multiplier - so for SVG we need to disable that.
2829 // Though all CSS values that can be applied to outermost <svg> elements (width/height/border/padding...)
2830 // need to respect the scaling. RenderBox (the parent class of RenderSVGRoot) grabs values like
2831 // width/height/border/padding/... from the RenderStyle -> for SVG these values would never scale,
2832 // if we'd pass a 1.0 zoom factor everyhwere. So we only pass a zoom factor of 1.0 for specific
2833 // properties that are NOT allowed to scale within a zoomed SVG document (letter/word-spacing/font-size).
2834 bool CSSStyleSelector::useSVGZoomRules()
2836 return m_element && m_element->isSVGElement();
2839 #if ENABLE(CSS_GRID_LAYOUT)
2841 static bool createGridTrackBreadth(CSSPrimitiveValue* primitiveValue, CSSStyleSelector* selector, Length& length)
2843 if (primitiveValue->getIdent() == CSSValueAuto) {
2848 if (primitiveValue->isLength()) {
2849 length = primitiveValue->computeLength<Length>(selector->style(), selector->rootElementStyle(), selector->style()->effectiveZoom());
2850 length.setQuirk(primitiveValue->isQuirkValue());
2854 if (primitiveValue->isPercentage()) {
2855 length = Length(primitiveValue->getDoubleValue(), Percent);
2862 static bool createGridTrackList(CSSValue* value, Vector<Length>& lengths, CSSStyleSelector* selector)
2865 if (value->isPrimitiveValue()) {
2866 CSSPrimitiveValue* primitiveValue = static_cast<CSSPrimitiveValue*>(value);
2867 if (primitiveValue->getIdent() == CSSValueNone) {
2868 lengths.append(Length(Undefined));
2874 if (value->isValueList()) {
2875 for (CSSValueListIterator i = value; i.hasMore(); i.advance()) {
2876 CSSValue* currValue = i.value();
2877 if (!currValue->isPrimitiveValue())
2881 if (!createGridTrackBreadth(static_cast<CSSPrimitiveValue*>(currValue), selector, length))
2884 lengths.append(length);
2893 void CSSStyleSelector::applyProperty(int id, CSSValue *value)
2895 bool isInherit = m_parentNode && value->isInheritedValue();
2896 bool isInitial = value->isInitialValue() || (!m_parentNode && value->isInheritedValue());
2898 ASSERT(!isInherit || !isInitial); // isInherit -> !isInitial && isInitial -> !isInherit
2900 if (!applyPropertyToRegularStyle() && (!applyPropertyToVisitedLinkStyle() || !isValidVisitedLinkProperty(id))) {
2901 // Limit the properties that can be applied to only the ones honored by :visited.
2905 CSSPropertyID property = static_cast<CSSPropertyID>(id);
2907 if (isInherit && m_parentStyle && !m_parentStyle->hasExplicitlyInheritedProperties() && !CSSProperty::isInheritedProperty(property))
2908 m_parentStyle->setHasExplicitlyInheritedProperties();
2910 // check lookup table for implementations and use when available
2911 const PropertyHandler& handler = m_applyProperty.propertyHandler(property);
2912 if (handler.isValid()) {
2914 handler.applyInheritValue(this);
2916 handler.applyInitialValue(this);
2918 handler.applyValue(this, value);
2922 CSSPrimitiveValue* primitiveValue = value->isPrimitiveValue() ? static_cast<CSSPrimitiveValue*>(value) : 0;
2924 float zoomFactor = m_style->effectiveZoom();
2926 // What follows is a list that maps the CSS properties into their corresponding front-end
2927 // RenderStyle values. Shorthands (e.g. border, background) occur in this list as well and
2928 // are only hit when mapping "inherit" or "initial" into front-end values.
2930 // ident only properties
2931 case CSSPropertyBorderCollapse:
2932 HANDLE_INHERIT_AND_INITIAL_AND_PRIMITIVE(borderCollapse, BorderCollapse)
2934 case CSSPropertyCaptionSide:
2935 HANDLE_INHERIT_AND_INITIAL_AND_PRIMITIVE(captionSide, CaptionSide)
2937 case CSSPropertyClear:
2938 HANDLE_INHERIT_AND_INITIAL_AND_PRIMITIVE(clear, Clear)
2940 case CSSPropertyEmptyCells:
2941 HANDLE_INHERIT_AND_INITIAL_AND_PRIMITIVE(emptyCells, EmptyCells)
2943 case CSSPropertyFloat:
2944 HANDLE_INHERIT_AND_INITIAL_AND_PRIMITIVE(floating, Floating)
2946 case CSSPropertyPageBreakBefore:
2947 HANDLE_INHERIT_AND_INITIAL_AND_PRIMITIVE_WITH_VALUE(pageBreakBefore, PageBreakBefore, PageBreak)
2949 case CSSPropertyPageBreakAfter:
2950 HANDLE_INHERIT_AND_INITIAL_AND_PRIMITIVE_WITH_VALUE(pageBreakAfter, PageBreakAfter, PageBreak)
2952 case CSSPropertyPageBreakInside:
2953 HANDLE_INHERIT_AND_INITIAL_AND_PRIMITIVE_WITH_VALUE(pageBreakInside, PageBreakInside, PageBreak)
2955 case CSSPropertyPosition:
2956 HANDLE_INHERIT_AND_INITIAL_AND_PRIMITIVE(position, Position)
2958 case CSSPropertyTableLayout:
2959 HANDLE_INHERIT_AND_INITIAL_AND_PRIMITIVE(tableLayout, TableLayout)
2961 case CSSPropertyUnicodeBidi:
2962 HANDLE_INHERIT_AND_INITIAL_AND_PRIMITIVE(unicodeBidi, UnicodeBidi)
2964 case CSSPropertyTextTransform:
2965 HANDLE_INHERIT_AND_INITIAL_AND_PRIMITIVE(textTransform, TextTransform)
2967 case CSSPropertyVisibility:
2968 HANDLE_INHERIT_AND_INITIAL_AND_PRIMITIVE(visibility, Visibility)
2970 case CSSPropertyWhiteSpace:
2971 HANDLE_INHERIT_AND_INITIAL_AND_PRIMITIVE(whiteSpace, WhiteSpace)
2974 case CSSPropertyWordBreak:
2975 HANDLE_INHERIT_AND_INITIAL_AND_PRIMITIVE(wordBreak, WordBreak)
2977 case CSSPropertyWordWrap:
2978 HANDLE_INHERIT_AND_INITIAL_AND_PRIMITIVE(wordWrap, WordWrap)
2980 case CSSPropertyWebkitNbspMode:
2981 HANDLE_INHERIT_AND_INITIAL_AND_PRIMITIVE(nbspMode, NBSPMode)
2983 case CSSPropertyWebkitLineBreak:
2984 HANDLE_INHERIT_AND_INITIAL_AND_PRIMITIVE(khtmlLineBreak, KHTMLLineBreak)
2986 case CSSPropertyWebkitMatchNearestMailBlockquoteColor:
2987 HANDLE_INHERIT_AND_INITIAL_AND_PRIMITIVE(matchNearestMailBlockquoteColor, MatchNearestMailBlockquoteColor)
2989 case CSSPropertyWidows:
2990 HANDLE_INHERIT_AND_INITIAL_AND_PRIMITIVE(widows, Widows)
2992 case CSSPropertyOrphans:
2993 HANDLE_INHERIT_AND_INITIAL_AND_PRIMITIVE(orphans, Orphans)
2997 case CSSPropertyContent:
2998 // list of string, uri, counter, attr, i
3000 // FIXME: In CSS3, it will be possible to inherit content. In CSS2 it is not. This
3001 // note is a reminder that eventually "inherit" needs to be supported.
3004 m_style->clearContent();
3008 if (!value->isValueList())
3011 bool didSet = false;
3012 for (CSSValueListIterator i = value; i.hasMore(); i.advance()) {
3013 CSSValue* item = i.value();
3014 if (item->isImageGeneratorValue()) {
3015 m_style->setContent(StyleGeneratedImage::create(static_cast<CSSImageGeneratorValue*>(item)), didSet);
3019 if (!item->isPrimitiveValue())
3022 CSSPrimitiveValue* contentValue = static_cast<CSSPrimitiveValue*>(item);
3024 if (contentValue->isString()) {
3025 m_style->setContent(contentValue->getStringValue().impl(), didSet);
3027 } else if (contentValue->isAttr()) {
3028 // FIXME: Can a namespace be specified for an attr(foo)?
3029 if (m_style->styleType() == NOPSEUDO)
3030 m_style->setUnique();
3032 m_parentStyle->setUnique();
3033 QualifiedName attr(nullAtom, contentValue->getStringValue().impl(), nullAtom);
3034 const AtomicString& value = m_element->getAttribute(attr);
3035 m_style->setContent(value.isNull() ? emptyAtom : value.impl(), didSet);
3037 // register the fact that the attribute value affects the style
3038 m_features.attrsInRules.add(attr.localName().impl());
3039 } else if (contentValue->isURI()) {
3040 if (!contentValue->isImageValue())
3042 m_style->setContent(cachedOrPendingFromValue(CSSPropertyContent, static_cast<CSSImageValue*>(contentValue)), didSet);
3044 } else if (contentValue->isCounter()) {
3045 Counter* counterValue = contentValue->getCounterValue();
3046 EListStyleType listStyleType = NoneListStyle;
3047 int listStyleIdent = counterValue->listStyleIdent();
3048 if (listStyleIdent != CSSValueNone)
3049 listStyleType = static_cast<EListStyleType>(listStyleIdent - CSSValueDisc);
3050 OwnPtr<CounterContent> counter = adoptPtr(new CounterContent(counterValue->identifier(), listStyleType, counterValue->separator()));
3051 m_style->setContent(counter.release(), didSet);
3054 switch (contentValue->getIdent()) {
3055 case CSSValueOpenQuote:
3056 m_style->setContent(OPEN_QUOTE, didSet);
3059 case CSSValueCloseQuote:
3060 m_style->setContent(CLOSE_QUOTE, didSet);
3063 case CSSValueNoOpenQuote:
3064 m_style->setContent(NO_OPEN_QUOTE, didSet);
3067 case CSSValueNoCloseQuote:
3068 m_style->setContent(NO_CLOSE_QUOTE, didSet);
3072 // normal and none do not have any effect.
3078 m_style->clearContent();
3081 case CSSPropertyQuotes:
3084 m_style->setQuotes(m_parentStyle->quotes());
3088 m_style->setQuotes(0);
3091 if (value->isValueList()) {
3092 CSSValueList* list = static_cast<CSSValueList*>(value);
3093 QuotesData* data = QuotesData::create(list->length());
3095 return; // Out of memory
3096 String* quotes = data->data();
3097 for (CSSValueListIterator i = list; i.hasMore(); i.advance()) {
3098 CSSValue* item = i.value();
3099 ASSERT(item->isPrimitiveValue());
3100 primitiveValue = static_cast<CSSPrimitiveValue*>(item);
3101 ASSERT(primitiveValue->isString());
3102 quotes[i.index()] = primitiveValue->getStringValue();
3104 m_style->setQuotes(adoptRef(data));
3105 } else if (primitiveValue) {
3106 ASSERT(primitiveValue->isIdent());
3107 if (primitiveValue->getIdent() == CSSValueNone)
3108 m_style->setQuotes(adoptRef(QuotesData::create(0)));
3111 case CSSPropertyFontFamily: {
3112 // list of strings and ids
3114 FontDescription parentFontDescription = m_parentStyle->fontDescription();
3115 FontDescription fontDescription = m_style->fontDescription();
3116 fontDescription.setGenericFamily(parentFontDescription.genericFamily());
3117 fontDescription.setFamily(parentFontDescription.firstFamily());
3118 fontDescription.setIsSpecifiedFont(parentFontDescription.isSpecifiedFont());
3119 setFontDescription(fontDescription);
3121 } else if (isInitial) {
3122 FontDescription initialDesc = FontDescription();
3123 FontDescription fontDescription = m_style->fontDescription();
3124 // We need to adjust the size to account for the generic family change from monospace
3125 // to non-monospace.
3126 if (fontDescription.keywordSize() && fontDescription.useFixedDefaultSize())
3127 setFontSize(fontDescription, fontSizeForKeyword(m_checker.document(), CSSValueXxSmall + fontDescription.keywordSize() - 1, false));
3128 fontDescription.setGenericFamily(initialDesc.genericFamily());
3129 if (!initialDesc.firstFamily().familyIsEmpty())
3130 fontDescription.setFamily(initialDesc.firstFamily());
3131 setFontDescription(fontDescription);
3135 if (!value->isValueList())
3137 FontDescription fontDescription = m_style->fontDescription();
3138 FontFamily& firstFamily = fontDescription.firstFamily();
3139 FontFamily* currFamily = 0;
3141 // Before mapping in a new font-family property, we should reset the generic family.
3142 bool oldFamilyUsedFixedDefaultSize = fontDescription.useFixedDefaultSize();
3143 fontDescription.setGenericFamily(FontDescription::NoFamily);
3145 for (CSSValueListIterator i = value; i.hasMore(); i.advance()) {
3146 CSSValue* item = i.value();
3147 if (!item->isPrimitiveValue())
3149 CSSPrimitiveValue* contentValue = static_cast<CSSPrimitiveValue*>(item);
3151 Settings* settings = m_checker.document()->settings();
3152 if (contentValue->isString()) {
3153 if (contentValue->isFontFamilyValue())
3154 face = static_cast<FontFamilyValue*>(contentValue)->familyName();
3155 } else if (settings) {
3156 switch (contentValue->getIdent()) {
3157 case CSSValueWebkitBody:
3158 face = settings->standardFontFamily();
3162 fontDescription.setGenericFamily(FontDescription::SerifFamily);
3164 case CSSValueSansSerif:
3165 face = sansSerifFamily;
3166 fontDescription.setGenericFamily(FontDescription::SansSerifFamily);
3168 case CSSValueCursive:
3169 face = cursiveFamily;
3170 fontDescription.setGenericFamily(FontDescription::CursiveFamily);
3172 case CSSValueFantasy:
3173 face = fantasyFamily;
3174 fontDescription.setGenericFamily(FontDescription::FantasyFamily);
3176 case CSSValueMonospace:
3177 face = monospaceFamily;
3178 fontDescription.setGenericFamily(FontDescription::MonospaceFamily);
3180 case CSSValueWebkitPictograph:
3181 face = pictographFamily;
3182 fontDescription.setGenericFamily(FontDescription::PictographFamily);
3187 if (!face.isEmpty()) {
3189 // Filling in the first family.
3190 firstFamily.setFamily(face);
3191 firstFamily.appendFamily(0); // Remove any inherited family-fallback list.
3192 currFamily = &firstFamily;
3193 fontDescription.setIsSpecifiedFont(fontDescription.genericFamily() == FontDescription::NoFamily);
3195 RefPtr<SharedFontFamily> newFamily = SharedFontFamily::create();
3196 newFamily->setFamily(face);
3197 currFamily->appendFamily(newFamily);
3198 currFamily = newFamily.get();
3203 // We can't call useFixedDefaultSize() until all new font families have been added
3204 // If currFamily is non-zero then we set at least one family on this description.
3206 if (fontDescription.keywordSize() && fontDescription.useFixedDefaultSize() != oldFamilyUsedFixedDefaultSize)
3207 setFontSize(fontDescription, fontSizeForKeyword(m_checker.document(), CSSValueXxSmall + fontDescription.keywordSize() - 1, !oldFamilyUsedFixedDefaultSize));
3209 setFontDescription(fontDescription);
3213 // shorthand properties
3214 case CSSPropertyBackground:
3216 m_style->clearBackgroundLayers();
3217 m_style->setBackgroundColor(Color());
3219 else if (isInherit) {
3220 m_style->inheritBackgroundLayers(*m_parentStyle->backgroundLayers());
3221 m_style->setBackgroundColor(m_parentStyle->backgroundColor());
3224 case CSSPropertyWebkitMask:
3226 m_style->clearMaskLayers();
3228 m_style->inheritMaskLayers(*m_parentStyle->maskLayers());
3230 case CSSPropertyFont:
3232 FontDescription fontDescription = m_parentStyle->fontDescription();
3233 m_style->setLineHeight(m_parentStyle->lineHeight());
3234 m_lineHeightValue = 0;
3235 setFontDescription(fontDescription);
3236 } else if (isInitial) {
3237 Settings* settings = m_checker.document()->settings();
3238 ASSERT(settings); // If we're doing style resolution, this document should always be in a frame and thus have settings
3241 FontDescription fontDescription;
3242 fontDescription.setGenericFamily(FontDescription::StandardFamily);
3243 fontDescription.setRenderingMode(settings->fontRenderingMode());
3244 fontDescription.setUsePrinterFont(m_checker.document()->printing());
3245 const AtomicString& standardFontFamily = m_checker.document()->settings()->standardFontFamily();
3246 if (!standardFontFamily.isEmpty()) {
3247 fontDescription.firstFamily().setFamily(standardFontFamily);
3248 fontDescription.firstFamily().appendFamily(0);
3250 fontDescription.setKeywordSize(CSSValueMedium - CSSValueXxSmall + 1);
3251 setFontSize(fontDescription, fontSizeForKeyword(m_checker.document(), CSSValueMedium, false));
3252 m_style->setLineHeight(RenderStyle::initialLineHeight());
3253 m_lineHeightValue = 0;
3254 setFontDescription(fontDescription);
3255 } else if (primitiveValue) {
3256 m_style->setLineHeight(RenderStyle::initialLineHeight());
3257 m_lineHeightValue = 0;
3259 FontDescription fontDescription;
3260 RenderTheme::defaultTheme()->systemFont(primitiveValue->getIdent(), fontDescription);
3262 // Double-check and see if the theme did anything. If not, don't bother updating the font.
3263 if (fontDescription.isAbsoluteSize()) {
3264 // Make sure the rendering mode and printer font settings are updated.
3265 Settings* settings = m_checker.document()->settings();
3266 ASSERT(settings); // If we're doing style resolution, this document should always be in a frame and thus have settings
3269 fontDescription.setRenderingMode(settings->fontRenderingMode());
3270 fontDescription.setUsePrinterFont(m_checker.document()->printing());
3272 // Handle the zoom factor.
3273 fontDescription.setComputedSize(getComputedSizeFromSpecifiedSize(m_checker.document(), m_style.get(), fontDescription.isAbsoluteSize(), fontDescription.specifiedSize(), useSVGZoomRules()));
3274 setFontDescription(fontDescription);
3276 } else if (value->isFontValue()) {
3277 FontValue *font = static_cast<FontValue*>(value);
3278 if (!font->style || !font->variant || !font->weight ||
3279 !font->size || !font->lineHeight || !font->family)
3281 applyProperty(CSSPropertyFontStyle, font->style.get());
3282 applyProperty(CSSPropertyFontVariant, font->variant.get());
3283 applyProperty(CSSPropertyFontWeight, font->weight.get());
3284 // The previous properties can dirty our font but they don't try to read the font's
3285 // properties back, which is safe. However if font-size is using the 'ex' unit, it will
3286 // need query the dirtied font's x-height to get the computed size. To be safe in this
3287 // case, let's just update the font now.
3289 applyProperty(CSSPropertyFontSize, font->size.get());
3291 m_lineHeightValue = font->lineHeight.get();
3293 applyProperty(CSSPropertyFontFamily, font->family.get());
3298 case CSSPropertyWebkitAppearance:
3299 HANDLE_INHERIT_AND_INITIAL_AND_PRIMITIVE(appearance, Appearance)
3301 case CSSPropertyImageRendering:
3302 HANDLE_INHERIT_AND_INITIAL_AND_PRIMITIVE(imageRendering, ImageRendering);
3304 case CSSPropertyTextShadow:
3305 case CSSPropertyBoxShadow:
3306 case CSSPropertyWebkitBoxShadow: {
3308 if (id == CSSPropertyTextShadow)
3309 return m_style->setTextShadow(m_parentStyle->textShadow() ? adoptPtr(new ShadowData(*m_parentStyle->textShadow())) : nullptr);
3310 return m_style->setBoxShadow(m_parentStyle->boxShadow() ? adoptPtr(new ShadowData(*m_parentStyle->boxShadow())) : nullptr);
3312 if (isInitial || primitiveValue) // initial | none
3313 return id == CSSPropertyTextShadow ? m_style->setTextShadow(nullptr) : m_style->setBoxShadow(nullptr);
3315 if (!value->isValueList())
3318 for (CSSValueListIterator i = value; i.hasMore(); i.advance()) {
3319 CSSValue* currValue = i.value();
3320 if (!currValue->isShadowValue())
3322 ShadowValue* item = static_cast<ShadowValue*>(currValue);
3323 int x = item->x->computeLength<int>(style(), m_rootElementStyle, zoomFactor);
3324 int y = item->y->computeLength<int>(style(), m_rootElementStyle, zoomFactor);
3325 int blur = item->blur ? item->blur->computeLength<int>(style(), m_rootElementStyle, zoomFactor) : 0;
3326 int spread = item->spread ? item->spread->computeLength<int>(style(), m_rootElementStyle, zoomFactor) : 0;
3327 ShadowStyle shadowStyle = item->style && item->style->getIdent() == CSSValueInset ? Inset : Normal;
3330 color = colorFromPrimitiveValue(item->color.get());
3331 OwnPtr<ShadowData> shadowData = adoptPtr(new ShadowData(x, y, blur, spread, shadowStyle, id == CSSPropertyWebkitBoxShadow, color.isValid() ? color : Color::transparent));
3332 if (id == CSSPropertyTextShadow)
3333 m_style->setTextShadow(shadowData.release(), i.index()); // add to the list if this is not the first entry
3335 m_style->setBoxShadow(shadowData.release(), i.index()); // add to the list if this is not the first entry
3339 case CSSPropertyWebkitBoxReflect: {
3340 HANDLE_INHERIT_AND_INITIAL(boxReflect, BoxReflect)
3341 if (primitiveValue) {
3342 m_style->setBoxReflect(RenderStyle::initialBoxReflect());