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.
11 * Copyright (C) 2012 Google Inc. All rights reserved.
13 * This library is free software; you can redistribute it and/or
14 * modify it under the terms of the GNU Library General Public
15 * License as published by the Free Software Foundation; either
16 * version 2 of the License, or (at your option) any later version.
18 * This library is distributed in the hope that it will be useful,
19 * but WITHOUT ANY WARRANTY; without even the implied warranty of
20 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
21 * Library General Public License for more details.
23 * You should have received a copy of the GNU Library General Public License
24 * along with this library; see the file COPYING.LIB. If not, write to
25 * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
26 * Boston, MA 02110-1301, USA.
30 #include "StyleResolver.h"
32 #include "Attribute.h"
33 #include "CSSBorderImage.h"
34 #include "CSSCalculationValue.h"
35 #include "CSSCursorImageValue.h"
36 #include "CSSFontFaceRule.h"
37 #include "CSSFontSelector.h"
38 #include "CSSImportRule.h"
39 #include "CSSLineBoxContainValue.h"
40 #include "CSSMediaRule.h"
41 #include "CSSPageRule.h"
42 #include "CSSParser.h"
43 #include "CSSPrimitiveValueMappings.h"
44 #include "CSSPropertyNames.h"
45 #include "CSSReflectValue.h"
46 #include "CSSRuleList.h"
47 #include "CSSSelector.h"
48 #include "CSSSelectorList.h"
49 #include "CSSStyleRule.h"
50 #include "CSSStyleSheet.h"
51 #include "CSSTimingFunctionValue.h"
52 #include "CSSValueList.h"
53 #if ENABLE(CSS_VARIABLES)
54 #include "CSSVariableValue.h"
56 #include "CachedImage.h"
57 #include "CalculationValue.h"
58 #include "ContentData.h"
59 #include "ContextFeatures.h"
61 #include "CounterContent.h"
62 #include "CursorList.h"
63 #include "DocumentStyleSheetCollection.h"
64 #include "FontFeatureValue.h"
65 #include "FontValue.h"
67 #include "FrameSelection.h"
68 #include "FrameView.h"
69 #include "HTMLDocument.h"
70 #include "HTMLIFrameElement.h"
71 #include "HTMLInputElement.h"
72 #include "HTMLNames.h"
73 #include "HTMLOptionElement.h"
74 #include "HTMLProgressElement.h"
75 #include "HTMLStyleElement.h"
76 #include "HTMLTextAreaElement.h"
77 #include "InspectorInstrumentation.h"
78 #include "KeyframeList.h"
80 #include "LocaleToScriptMapping.h"
81 #include "MathMLNames.h"
82 #include "Matrix3DTransformOperation.h"
83 #include "MatrixTransformOperation.h"
84 #include "MediaList.h"
85 #include "MediaQueryEvaluator.h"
86 #include "NodeRenderStyle.h"
87 #include "NodeRenderingContext.h"
89 #include "PageGroup.h"
91 #include "PerspectiveTransformOperation.h"
92 #include "QuotesData.h"
94 #include "RenderRegion.h"
95 #include "RenderScrollbar.h"
96 #include "RenderScrollbarTheme.h"
97 #include "RenderStyleConstants.h"
98 #include "RenderTheme.h"
99 #include "RenderView.h"
100 #include "RotateTransformOperation.h"
101 #include "SVGDocumentExtensions.h"
102 #include "SVGFontFaceElement.h"
103 #include "ScaleTransformOperation.h"
104 #include "SecurityOrigin.h"
105 #include "Settings.h"
106 #include "ShadowData.h"
107 #include "ShadowRoot.h"
108 #include "ShadowValue.h"
109 #include "SkewTransformOperation.h"
110 #include "StyleBuilder.h"
111 #include "StyleCachedImage.h"
112 #include "StyleGeneratedImage.h"
113 #include "StylePendingImage.h"
114 #include "StyleRule.h"
115 #include "StyleRuleImport.h"
116 #include "StyleSheetContents.h"
117 #include "StyleSheetList.h"
119 #include "TransformationMatrix.h"
120 #include "TranslateTransformOperation.h"
121 #include "UserAgentStyleSheets.h"
122 #include "WebCoreMemoryInstrumentation.h"
123 #include "WebKitCSSKeyframeRule.h"
124 #include "WebKitCSSKeyframesRule.h"
125 #include "WebKitCSSRegionRule.h"
126 #include "WebKitCSSTransformValue.h"
127 #include "WebKitFontFamilyNames.h"
128 #include "XMLNames.h"
129 #include <wtf/MemoryInstrumentationHashSet.h>
130 #include <wtf/MemoryInstrumentationVector.h>
131 #include <wtf/StdLibExtras.h>
132 #include <wtf/Vector.h>
134 #if ENABLE(CSS_FILTERS)
135 #include "FilterOperation.h"
136 #include "WebKitCSSFilterValue.h"
139 #if ENABLE(DASHBOARD_SUPPORT) || ENABLE(WIDGET_REGION)
140 #include "DashboardRegion.h"
144 #include "CachedSVGDocument.h"
145 #include "SVGDocument.h"
146 #include "SVGElement.h"
147 #include "SVGNames.h"
148 #include "SVGURIReference.h"
149 #include "WebKitCSSSVGDocumentValue.h"
152 #if ENABLE(CSS_SHADERS)
153 #include "CustomFilterArrayParameter.h"
154 #include "CustomFilterNumberParameter.h"
155 #include "CustomFilterOperation.h"
156 #include "CustomFilterParameter.h"
157 #include "CustomFilterTransformParameter.h"
158 #include "StyleCachedShader.h"
159 #include "StyleCustomFilterProgram.h"
160 #include "StylePendingShader.h"
161 #include "StyleShader.h"
162 #include "WebKitCSSMixFunctionValue.h"
163 #include "WebKitCSSShaderValue.h"
166 #if ENABLE(CSS_IMAGE_SET)
167 #include "CSSImageSetValue.h"
168 #include "StyleCachedImageSet.h"
171 #if PLATFORM(BLACKBERRY)
172 #define FIXED_POSITION_CREATES_STACKING_CONTEXT 1
180 using namespace HTMLNames;
182 #define HANDLE_INHERIT(prop, Prop) \
184 m_style->set##Prop(m_parentStyle->prop()); \
188 #define HANDLE_INHERIT_AND_INITIAL(prop, Prop) \
189 HANDLE_INHERIT(prop, Prop) \
191 m_style->set##Prop(RenderStyle::initial##Prop()); \
195 #define HANDLE_INHERIT_AND_INITIAL_WITH_VALUE(prop, Prop, Value) \
196 HANDLE_INHERIT(prop, Prop) \
198 m_style->set##Prop(RenderStyle::initial##Value());\
202 #define HANDLE_INHERIT_AND_INITIAL_AND_PRIMITIVE(prop, Prop) \
203 HANDLE_INHERIT_AND_INITIAL(prop, Prop) \
204 if (primitiveValue) \
205 m_style->set##Prop(*primitiveValue);
209 RuleData(StyleRule*, unsigned selectorIndex, unsigned position, bool hasDocumentSecurityOrigin, bool canUseFastCheckSelector, bool inRegionRule);
211 unsigned position() const { return m_position; }
212 StyleRule* rule() const { return m_rule; }
213 CSSSelector* selector() const { return m_rule->selectorList().selectorAt(m_selectorIndex); }
214 unsigned selectorIndex() const { return m_selectorIndex; }
216 bool hasFastCheckableSelector() const { return m_hasFastCheckableSelector; }
217 bool hasMultipartSelector() const { return m_hasMultipartSelector; }
218 bool hasRightmostSelectorMatchingHTMLBasedOnRuleHash() const { return m_hasRightmostSelectorMatchingHTMLBasedOnRuleHash; }
219 bool containsUncommonAttributeSelector() const { return m_containsUncommonAttributeSelector; }
220 unsigned specificity() const { return m_specificity; }
221 unsigned linkMatchType() const { return m_linkMatchType; }
222 bool hasDocumentSecurityOrigin() const { return m_hasDocumentSecurityOrigin; }
223 bool isInRegionRule() const { return m_isInRegionRule; }
225 // Try to balance between memory usage (there can be lots of RuleData objects) and good filtering performance.
226 static const unsigned maximumIdentifierCount = 4;
227 const unsigned* descendantSelectorIdentifierHashes() const { return m_descendantSelectorIdentifierHashes; }
229 void reportMemoryUsage(MemoryObjectInfo*) const;
233 unsigned m_selectorIndex : 12;
234 // This number was picked fairly arbitrarily. We can probably lower it if we need to.
235 // Some simple testing showed <100,000 RuleData's on large sites.
236 unsigned m_position : 20;
237 unsigned m_specificity : 24;
238 unsigned m_hasFastCheckableSelector : 1;
239 unsigned m_hasMultipartSelector : 1;
240 unsigned m_hasRightmostSelectorMatchingHTMLBasedOnRuleHash : 1;
241 unsigned m_containsUncommonAttributeSelector : 1;
242 unsigned m_linkMatchType : 2; // SelectorChecker::LinkMatchMask
243 unsigned m_hasDocumentSecurityOrigin : 1;
244 unsigned m_isInRegionRule : 1;
245 // Use plain array instead of a Vector to minimize memory overhead.
246 unsigned m_descendantSelectorIdentifierHashes[maximumIdentifierCount];
249 struct SameSizeAsRuleData {
256 COMPILE_ASSERT(sizeof(RuleData) == sizeof(SameSizeAsRuleData), RuleData_should_stay_small);
259 WTF_MAKE_NONCOPYABLE(RuleSet); WTF_MAKE_FAST_ALLOCATED;
261 static PassOwnPtr<RuleSet> create() { return adoptPtr(new RuleSet); }
263 typedef HashMap<AtomicStringImpl*, OwnPtr<Vector<RuleData> > > AtomRuleMap;
265 void addRulesFromSheet(StyleSheetContents*, const MediaQueryEvaluator&, StyleResolver* = 0, const ContainerNode* = 0);
267 void addStyleRule(StyleRule*, bool hasDocumentSecurityOrigin, bool canUseFastCheckSelector, bool isInRegionRule = false);
268 void addRule(StyleRule*, unsigned selectorIndex, bool hasDocumentSecurityOrigin, bool canUseFastCheckSelector, bool isInRegionRule = false);
269 void addPageRule(StyleRulePage*);
270 void addToRuleSet(AtomicStringImpl* key, AtomRuleMap&, const RuleData&);
271 void addRegionRule(StyleRuleRegion*, bool hasDocumentSecurityOrigin);
273 void disableAutoShrinkToFit() { m_autoShrinkToFitEnabled = false; }
275 const StyleResolver::Features& features() const { return m_features; }
277 const Vector<RuleData>* idRules(AtomicStringImpl* key) const { return m_idRules.get(key); }
278 const Vector<RuleData>* classRules(AtomicStringImpl* key) const { return m_classRules.get(key); }
279 const Vector<RuleData>* tagRules(AtomicStringImpl* key) const { return m_tagRules.get(key); }
280 const Vector<RuleData>* shadowPseudoElementRules(AtomicStringImpl* key) const { return m_shadowPseudoElementRules.get(key); }
281 const Vector<RuleData>* linkPseudoClassRules() const { return &m_linkPseudoClassRules; }
282 const Vector<RuleData>* focusPseudoClassRules() const { return &m_focusPseudoClassRules; }
283 const Vector<RuleData>* universalRules() const { return &m_universalRules; }
284 const Vector<StyleRulePage*>& pageRules() const { return m_pageRules; }
286 void reportMemoryUsage(MemoryObjectInfo*) const;
291 AtomRuleMap m_idRules;
292 AtomRuleMap m_classRules;
293 AtomRuleMap m_tagRules;
294 AtomRuleMap m_shadowPseudoElementRules;
295 Vector<RuleData> m_linkPseudoClassRules;
296 Vector<RuleData> m_focusPseudoClassRules;
297 Vector<RuleData> m_universalRules;
298 Vector<StyleRulePage*> m_pageRules;
299 unsigned m_ruleCount;
300 bool m_autoShrinkToFitEnabled;
301 StyleResolver::Features m_features;
303 struct RuleSetSelectorPair {
304 RuleSetSelectorPair(CSSSelector* selector, PassOwnPtr<RuleSet> ruleSet) : selector(selector), ruleSet(ruleSet) { }
305 RuleSetSelectorPair(const RuleSetSelectorPair& rs) : selector(rs.selector), ruleSet(const_cast<RuleSetSelectorPair*>(&rs)->ruleSet.release()) { }
306 void reportMemoryUsage(MemoryObjectInfo*) const;
308 CSSSelector* selector;
309 OwnPtr<RuleSet> ruleSet;
312 Vector<RuleSetSelectorPair> m_regionSelectorsAndRuleSets;
315 static RuleSet* defaultStyle;
316 static RuleSet* defaultQuirksStyle;
317 static RuleSet* defaultPrintStyle;
318 static RuleSet* defaultViewSourceStyle;
319 static StyleSheetContents* simpleDefaultStyleSheet;
320 static StyleSheetContents* defaultStyleSheet;
321 static StyleSheetContents* quirksStyleSheet;
322 static StyleSheetContents* svgStyleSheet;
323 static StyleSheetContents* mathMLStyleSheet;
324 static StyleSheetContents* mediaControlsStyleSheet;
325 static StyleSheetContents* fullscreenStyleSheet;
327 RenderStyle* StyleResolver::s_styleNotYetAvailable;
329 static void loadFullDefaultStyle();
330 static void loadSimpleDefaultStyle();
331 template <class ListType>
332 static void collectCSSOMWrappers(HashMap<StyleRule*, RefPtr<CSSStyleRule> >&, ListType*);
334 // FIXME: It would be nice to use some mechanism that guarantees this is in sync with the real UA stylesheet.
335 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}";
337 static inline bool elementCanUseSimpleDefaultStyle(Element* e)
339 return e->hasTagName(htmlTag) || e->hasTagName(headTag) || e->hasTagName(bodyTag) || e->hasTagName(divTag) || e->hasTagName(spanTag) || e->hasTagName(brTag) || e->hasTagName(aTag);
342 static const MediaQueryEvaluator& screenEval()
344 DEFINE_STATIC_LOCAL(const MediaQueryEvaluator, staticScreenEval, ("screen"));
345 return staticScreenEval;
348 static const MediaQueryEvaluator& printEval()
350 DEFINE_STATIC_LOCAL(const MediaQueryEvaluator, staticPrintEval, ("print"));
351 return staticPrintEval;
354 static StylePropertySet* leftToRightDeclaration()
356 DEFINE_STATIC_LOCAL(RefPtr<StylePropertySet>, leftToRightDecl, (StylePropertySet::create()));
357 if (leftToRightDecl->isEmpty())
358 leftToRightDecl->setProperty(CSSPropertyDirection, CSSValueLtr);
359 return leftToRightDecl.get();
362 static StylePropertySet* rightToLeftDeclaration()
364 DEFINE_STATIC_LOCAL(RefPtr<StylePropertySet>, rightToLeftDecl, (StylePropertySet::create()));
365 if (rightToLeftDecl->isEmpty())
366 rightToLeftDecl->setProperty(CSSPropertyDirection, CSSValueRtl);
367 return rightToLeftDecl.get();
370 StyleResolver::StyleResolver(Document* document, bool matchAuthorAndUserStyles)
371 : m_hasUAAppearance(false)
372 , m_backgroundData(BackgroundFillLayer)
373 , m_matchedPropertiesCacheAdditionsSinceLastSweep(0)
374 , m_checker(document, !document->inQuirksMode())
376 , m_rootElementStyle(0)
379 , m_regionForStyling(0)
380 , m_elementLinkState(NotInsideLink)
382 , m_lineHeightValue(0)
384 , m_matchAuthorAndUserStyles(matchAuthorAndUserStyles)
385 , m_sameOriginOnly(false)
386 , m_distributedToInsertionPoint(false)
387 , m_hasUnknownPseudoElements(false)
388 , m_fontSelector(CSSFontSelector::create(document))
389 , m_applyPropertyToRegularStyle(true)
390 , m_applyPropertyToVisitedLinkStyle(false)
391 , m_styleBuilder(StyleBuilder::sharedStyleBuilder())
392 #if ENABLE(CSS_SHADERS)
393 , m_hasPendingShaders(false)
395 #if ENABLE(STYLE_SCOPED)
396 , m_scopeStackParent(0)
397 , m_scopeStackParentBoundsIndex(0)
401 Element* root = document->documentElement();
404 if (!root || elementCanUseSimpleDefaultStyle(root))
405 loadSimpleDefaultStyle();
407 loadFullDefaultStyle();
410 // construct document root element default style. this is needed
411 // to evaluate media queries that contain relative constraints, like "screen and (max-width: 10em)"
412 // This is here instead of constructor, because when constructor is run,
413 // document doesn't have documentElement
414 // NOTE: this assumes that element that gets passed to styleForElement -call
415 // is always from the document that owns the style selector
416 FrameView* view = document->view();
418 m_medium = adoptPtr(new MediaQueryEvaluator(view->mediaType()));
420 m_medium = adoptPtr(new MediaQueryEvaluator("all"));
423 m_rootDefaultStyle = styleForElement(root, 0, DisallowStyleSharing, MatchOnlyUserAgentRules);
425 if (m_rootDefaultStyle && view)
426 m_medium = adoptPtr(new MediaQueryEvaluator(view->mediaType(), view->frame(), m_rootDefaultStyle.get()));
428 m_authorStyle = RuleSet::create();
429 // Adding rules from multiple sheets, shrink at the end.
430 // Adding global rules from multiple sheets, shrink at the end.
431 // Note that there usually is only 1 sheet for scoped rules, so auto-shrink-to-fit is fine.
432 m_authorStyle->disableAutoShrinkToFit();
434 DocumentStyleSheetCollection* styleSheetCollection = document->styleSheetCollection();
435 // FIXME: This sucks! The user sheet is reparsed every time!
436 OwnPtr<RuleSet> tempUserStyle = RuleSet::create();
437 if (CSSStyleSheet* pageUserSheet = styleSheetCollection->pageUserSheet())
438 tempUserStyle->addRulesFromSheet(pageUserSheet->contents(), *m_medium, this);
439 addAuthorRulesAndCollectUserRulesFromSheets(styleSheetCollection->pageGroupUserSheets(), *tempUserStyle);
440 addAuthorRulesAndCollectUserRulesFromSheets(styleSheetCollection->documentUserSheets(), *tempUserStyle);
441 if (tempUserStyle->m_ruleCount > 0 || tempUserStyle->m_pageRules.size() > 0)
442 m_userStyle = tempUserStyle.release();
444 #if ENABLE(SVG_FONTS)
445 if (document->svgExtensions()) {
446 const HashSet<SVGFontFaceElement*>& svgFontFaceElements = document->svgExtensions()->svgFontFaceElements();
447 HashSet<SVGFontFaceElement*>::const_iterator end = svgFontFaceElements.end();
448 for (HashSet<SVGFontFaceElement*>::const_iterator it = svgFontFaceElements.begin(); it != end; ++it)
449 fontSelector()->addFontFaceRule((*it)->fontFaceRule());
453 addStylesheetsFromSeamlessParents();
454 appendAuthorStylesheets(0, styleSheetCollection->authorStyleSheets());
457 void StyleResolver::addStylesheetsFromSeamlessParents()
459 // Build a list of stylesheet lists from our ancestors, and walk that
460 // list in reverse order so that the root-most sheets are appended first.
461 Document* childDocument = document();
462 Vector<const Vector<RefPtr<StyleSheet> >* > ancestorSheets;
463 while (HTMLIFrameElement* parentIFrame = childDocument->seamlessParentIFrame()) {
464 Document* parentDocument = parentIFrame->document();
465 ancestorSheets.append(&parentDocument->styleSheetCollection()->authorStyleSheets());
466 childDocument = parentDocument;
468 for (int i = ancestorSheets.size() - 1; i >= 0; i--)
469 appendAuthorStylesheets(0, *ancestorSheets[i]);
472 void StyleResolver::addAuthorRulesAndCollectUserRulesFromSheets(const Vector<RefPtr<CSSStyleSheet> >* userSheets, RuleSet& userStyle)
477 unsigned length = userSheets->size();
478 for (unsigned i = 0; i < length; i++) {
479 StyleSheetContents* sheet = userSheets->at(i)->contents();
480 if (sheet->isUserStyleSheet())
481 userStyle.addRulesFromSheet(sheet, *m_medium, this);
483 m_authorStyle->addRulesFromSheet(sheet, *m_medium, this);
487 static PassOwnPtr<RuleSet> makeRuleSet(const Vector<StyleResolver::RuleFeature>& rules)
489 size_t size = rules.size();
492 OwnPtr<RuleSet> ruleSet = RuleSet::create();
493 for (size_t i = 0; i < size; ++i)
494 ruleSet->addRule(rules[i].rule, rules[i].selectorIndex, rules[i].hasDocumentSecurityOrigin, false);
495 ruleSet->shrinkToFit();
496 return ruleSet.release();
499 void StyleResolver::collectFeatures()
502 // Collect all ids and rules using sibling selectors (:first-child and similar)
503 // in the current set of stylesheets. Style sharing code uses this information to reject
504 // sharing candidates.
505 m_features.add(defaultStyle->features());
506 m_features.add(m_authorStyle->features());
507 #if ENABLE(STYLE_SCOPED)
508 for (ScopedRuleSetMap::iterator it = m_scopedAuthorStyles.begin(); it != m_scopedAuthorStyles.end(); ++it)
509 m_features.add(it->second->features());
512 m_features.add(m_userStyle->features());
514 m_siblingRuleSet = makeRuleSet(m_features.siblingRules);
515 m_uncommonAttributeRuleSet = makeRuleSet(m_features.uncommonAttributeRules);
518 #if ENABLE(STYLE_SCOPED)
519 const ContainerNode* StyleResolver::determineScope(const CSSStyleSheet* sheet)
523 if (!ContextFeatures::styleScopedEnabled(document()))
526 Node* ownerNode = sheet->ownerNode();
527 if (!ownerNode || !ownerNode->isHTMLElement() || !ownerNode->hasTagName(HTMLNames::styleTag))
530 HTMLStyleElement* styleElement = static_cast<HTMLStyleElement*>(ownerNode);
531 if (!styleElement->scoped())
532 return styleElement->isInShadowTree()? styleElement->shadowRoot() : 0;
534 ContainerNode* parent = styleElement->parentNode();
538 return (parent->isElementNode() || parent->isShadowRoot()) ? parent : 0;
541 inline RuleSet* StyleResolver::ruleSetForScope(const ContainerNode* scope) const
543 if (!scope->hasScopedHTMLStyleChild())
545 ScopedRuleSetMap::const_iterator it = m_scopedAuthorStyles.find(scope);
546 return it != m_scopedAuthorStyles.end() ? it->second.get() : 0;
550 void StyleResolver::appendAuthorStylesheets(unsigned firstNew, const Vector<RefPtr<StyleSheet> >& stylesheets)
552 // This handles sheets added to the end of the stylesheet list only. In other cases the style resolver
553 // needs to be reconstructed. To handle insertions too the rule order numbers would need to be updated.
554 unsigned size = stylesheets.size();
555 for (unsigned i = firstNew; i < size; ++i) {
556 if (!stylesheets[i]->isCSSStyleSheet())
558 CSSStyleSheet* cssSheet = static_cast<CSSStyleSheet*>(stylesheets[i].get());
559 if (cssSheet->disabled())
561 if (cssSheet->mediaQueries() && !m_medium->eval(cssSheet->mediaQueries(), this))
563 StyleSheetContents* sheet = cssSheet->contents();
564 #if ENABLE(STYLE_SCOPED)
565 const ContainerNode* scope = determineScope(cssSheet);
567 ScopedRuleSetMap::AddResult addResult = m_scopedAuthorStyles.add(scope, nullptr);
568 if (addResult.isNewEntry)
569 addResult.iterator->second = RuleSet::create();
570 addResult.iterator->second->addRulesFromSheet(sheet, *m_medium, this, scope);
574 m_authorStyle->addRulesFromSheet(sheet, *m_medium, this);
575 if (!m_styleRuleToCSSOMWrapperMap.isEmpty())
576 collectCSSOMWrappers(m_styleRuleToCSSOMWrapperMap, cssSheet);
578 m_authorStyle->shrinkToFit();
581 if (document()->renderer() && document()->renderer()->style())
582 document()->renderer()->style()->font().update(fontSelector());
585 #if ENABLE(STYLE_SCOPED)
586 void StyleResolver::setupScopeStack(const ContainerNode* parent)
588 // The scoping element stack shouldn't be used if <style scoped> isn't used anywhere.
589 ASSERT(!m_scopedAuthorStyles.isEmpty());
591 m_scopeStack.shrink(0);
592 int authorStyleBoundsIndex = 0;
593 for (const ContainerNode* scope = parent; scope; scope = scope->parentOrHostNode()) {
594 RuleSet* ruleSet = ruleSetForScope(scope);
596 m_scopeStack.append(ScopeStackFrame(scope, authorStyleBoundsIndex, ruleSet));
597 if (scope->isShadowRoot() && !toShadowRoot(scope)->applyAuthorStyles())
598 --authorStyleBoundsIndex;
600 m_scopeStack.reverse();
601 m_scopeStackParent = parent;
602 m_scopeStackParentBoundsIndex = 0;
605 void StyleResolver::pushScope(const ContainerNode* scope, const ContainerNode* scopeParent)
607 // Shortcut: Don't bother with the scoping element stack if <style scoped> isn't used anywhere.
608 if (m_scopedAuthorStyles.isEmpty()) {
609 ASSERT(!m_scopeStackParent);
610 ASSERT(m_scopeStack.isEmpty());
613 // In some wacky cases during style resolve we may get invoked for random elements.
614 // Recreate the whole scoping element stack in such cases.
615 if (!scopeStackIsConsistent(scopeParent)) {
616 setupScopeStack(scope);
619 if (scope->isShadowRoot() && !toShadowRoot(scope)->applyAuthorStyles())
620 ++m_scopeStackParentBoundsIndex;
621 // Otherwise just push the parent onto the stack.
622 RuleSet* ruleSet = ruleSetForScope(scope);
624 m_scopeStack.append(ScopeStackFrame(scope, m_scopeStackParentBoundsIndex, ruleSet));
625 m_scopeStackParent = scope;
628 void StyleResolver::popScope(const ContainerNode* scope)
630 // Only bother to update the scoping element stack if it is consistent.
631 if (scopeStackIsConsistent(scope)) {
632 if (!m_scopeStack.isEmpty() && m_scopeStack.last().m_scope == scope)
633 m_scopeStack.removeLast();
634 if (scope->isShadowRoot() && !toShadowRoot(scope)->applyAuthorStyles())
635 --m_scopeStackParentBoundsIndex;
636 m_scopeStackParent = scope->parentOrHostNode();
641 void StyleResolver::pushParentElement(Element* parent)
643 const ContainerNode* parentsParent = parent->parentOrHostElement();
645 // We are not always invoked consistently. For example, script execution can cause us to enter
646 // style recalc in the middle of tree building. We may also be invoked from somewhere within the tree.
647 // Reset the stack in this case, or if we see a new root element.
648 // Otherwise just push the new parent.
649 if (!parentsParent || m_checker.parentStackIsEmpty())
650 m_checker.setupParentStack(parent);
652 m_checker.pushParent(parent);
654 // Note: We mustn't skip ShadowRoot nodes for the scope stack.
655 pushScope(parent, parent->parentOrHostNode());
658 void StyleResolver::popParentElement(Element* parent)
660 // Note that we may get invoked for some random elements in some wacky cases during style resolve.
661 // Pause maintaining the stack in this case.
662 if (m_checker.parentStackIsConsistent(parent))
663 m_checker.popParent();
667 void StyleResolver::pushParentShadowRoot(const ShadowRoot* shadowRoot)
669 ASSERT(shadowRoot->host());
670 pushScope(shadowRoot, shadowRoot->host());
673 void StyleResolver::popParentShadowRoot(const ShadowRoot* shadowRoot)
675 ASSERT(shadowRoot->host());
676 popScope(shadowRoot);
679 // This is a simplified style setting function for keyframe styles
680 void StyleResolver::addKeyframeStyle(PassRefPtr<StyleRuleKeyframes> rule)
682 AtomicString s(rule->name());
683 m_keyframesRuleMap.set(s.impl(), rule);
686 StyleResolver::~StyleResolver()
688 m_fontSelector->clearDocument();
691 void StyleResolver::sweepMatchedPropertiesCache()
693 // Look for cache entries containing a style declaration with a single ref and remove them.
694 // This may happen when an element attribute mutation causes it to swap out its Attribute::decl()
695 // for another CSSMappedAttributeDeclaration, potentially leaving this cache with the last ref.
696 Vector<unsigned, 16> toRemove;
697 MatchedPropertiesCache::iterator it = m_matchedPropertiesCache.begin();
698 MatchedPropertiesCache::iterator end = m_matchedPropertiesCache.end();
699 for (; it != end; ++it) {
700 Vector<MatchedProperties>& matchedProperties = it->second.matchedProperties;
701 for (size_t i = 0; i < matchedProperties.size(); ++i) {
702 if (matchedProperties[i].properties->hasOneRef()) {
703 toRemove.append(it->first);
708 for (size_t i = 0; i < toRemove.size(); ++i)
709 m_matchedPropertiesCache.remove(toRemove[i]);
712 StyleResolver::Features::Features()
713 : usesFirstLineRules(false)
714 , usesBeforeAfterRules(false)
718 StyleResolver::Features::~Features()
722 void StyleResolver::Features::add(const StyleResolver::Features& other)
724 HashSet<AtomicStringImpl*>::iterator end = other.idsInRules.end();
725 for (HashSet<AtomicStringImpl*>::iterator it = other.idsInRules.begin(); it != end; ++it)
727 end = other.attrsInRules.end();
728 for (HashSet<AtomicStringImpl*>::iterator it = other.attrsInRules.begin(); it != end; ++it)
729 attrsInRules.add(*it);
730 siblingRules.append(other.siblingRules);
731 uncommonAttributeRules.append(other.uncommonAttributeRules);
732 usesFirstLineRules = usesFirstLineRules || other.usesFirstLineRules;
733 usesBeforeAfterRules = usesBeforeAfterRules || other.usesBeforeAfterRules;
736 void StyleResolver::Features::clear()
739 attrsInRules.clear();
740 siblingRules.clear();
741 uncommonAttributeRules.clear();
742 usesFirstLineRules = false;
743 usesBeforeAfterRules = false;
746 void StyleResolver::Features::reportMemoryUsage(MemoryObjectInfo* memoryObjectInfo) const
748 MemoryClassInfo info(memoryObjectInfo, this, WebCoreMemoryTypes::CSS);
749 info.addMember(idsInRules);
750 info.addMember(attrsInRules);
751 info.addMember(siblingRules);
752 info.addMember(uncommonAttributeRules);
755 static StyleSheetContents* parseUASheet(const String& str)
757 StyleSheetContents* sheet = StyleSheetContents::create().leakRef(); // leak the sheet on purpose
758 sheet->parseString(str);
762 static StyleSheetContents* parseUASheet(const char* characters, unsigned size)
764 return parseUASheet(String(characters, size));
767 static void loadFullDefaultStyle()
769 if (simpleDefaultStyleSheet) {
770 ASSERT(defaultStyle);
771 ASSERT(defaultPrintStyle == defaultStyle);
773 simpleDefaultStyleSheet->deref();
774 defaultStyle = RuleSet::create().leakPtr();
775 defaultPrintStyle = RuleSet::create().leakPtr();
776 simpleDefaultStyleSheet = 0;
778 ASSERT(!defaultStyle);
779 defaultStyle = RuleSet::create().leakPtr();
780 defaultPrintStyle = RuleSet::create().leakPtr();
781 defaultQuirksStyle = RuleSet::create().leakPtr();
784 // Strict-mode rules.
785 String defaultRules = String(htmlUserAgentStyleSheet, sizeof(htmlUserAgentStyleSheet)) + RenderTheme::defaultTheme()->extraDefaultStyleSheet();
786 defaultStyleSheet = parseUASheet(defaultRules);
787 defaultStyle->addRulesFromSheet(defaultStyleSheet, screenEval());
788 defaultPrintStyle->addRulesFromSheet(defaultStyleSheet, printEval());
790 // Quirks-mode rules.
791 String quirksRules = String(quirksUserAgentStyleSheet, sizeof(quirksUserAgentStyleSheet)) + RenderTheme::defaultTheme()->extraQuirksStyleSheet();
792 quirksStyleSheet = parseUASheet(quirksRules);
793 defaultQuirksStyle->addRulesFromSheet(quirksStyleSheet, screenEval());
796 static void loadSimpleDefaultStyle()
798 ASSERT(!defaultStyle);
799 ASSERT(!simpleDefaultStyleSheet);
801 defaultStyle = RuleSet::create().leakPtr();
802 // There are no media-specific rules in the simple default style.
803 defaultPrintStyle = defaultStyle;
804 defaultQuirksStyle = RuleSet::create().leakPtr();
806 simpleDefaultStyleSheet = parseUASheet(simpleUserAgentStyleSheet, strlen(simpleUserAgentStyleSheet));
807 defaultStyle->addRulesFromSheet(simpleDefaultStyleSheet, screenEval());
809 // No need to initialize quirks sheet yet as there are no quirk rules for elements allowed in simple default style.
812 static void loadViewSourceStyle()
814 ASSERT(!defaultViewSourceStyle);
815 defaultViewSourceStyle = RuleSet::create().leakPtr();
816 defaultViewSourceStyle->addRulesFromSheet(parseUASheet(sourceUserAgentStyleSheet, sizeof(sourceUserAgentStyleSheet)), screenEval());
819 static void ensureDefaultStyleSheetsForElement(Element* element)
821 if (simpleDefaultStyleSheet && !elementCanUseSimpleDefaultStyle(element))
822 loadFullDefaultStyle();
825 if (element->isSVGElement() && !svgStyleSheet) {
827 svgStyleSheet = parseUASheet(svgUserAgentStyleSheet, sizeof(svgUserAgentStyleSheet));
828 defaultStyle->addRulesFromSheet(svgStyleSheet, screenEval());
829 defaultPrintStyle->addRulesFromSheet(svgStyleSheet, printEval());
834 if (element->isMathMLElement() && !mathMLStyleSheet) {
836 mathMLStyleSheet = parseUASheet(mathmlUserAgentStyleSheet, sizeof(mathmlUserAgentStyleSheet));
837 defaultStyle->addRulesFromSheet(mathMLStyleSheet, screenEval());
838 defaultPrintStyle->addRulesFromSheet(mathMLStyleSheet, printEval());
843 if (!mediaControlsStyleSheet && (element->hasTagName(videoTag) || element->hasTagName(audioTag))) {
844 String mediaRules = String(mediaControlsUserAgentStyleSheet, sizeof(mediaControlsUserAgentStyleSheet)) + RenderTheme::themeForPage(element->document()->page())->extraMediaControlsStyleSheet();
845 mediaControlsStyleSheet = parseUASheet(mediaRules);
846 defaultStyle->addRulesFromSheet(mediaControlsStyleSheet, screenEval());
847 defaultPrintStyle->addRulesFromSheet(mediaControlsStyleSheet, printEval());
851 #if ENABLE(FULLSCREEN_API)
852 if (!fullscreenStyleSheet && element->document()->webkitIsFullScreen()) {
853 String fullscreenRules = String(fullscreenUserAgentStyleSheet, sizeof(fullscreenUserAgentStyleSheet)) + RenderTheme::defaultTheme()->extraFullScreenStyleSheet();
854 fullscreenStyleSheet = parseUASheet(fullscreenRules);
855 defaultStyle->addRulesFromSheet(fullscreenStyleSheet, screenEval());
856 defaultQuirksStyle->addRulesFromSheet(fullscreenStyleSheet, screenEval());
860 ASSERT(defaultStyle->features().idsInRules.isEmpty());
861 ASSERT(mathMLStyleSheet || defaultStyle->features().siblingRules.isEmpty());
864 void StyleResolver::addMatchedProperties(MatchResult& matchResult, const StylePropertySet* properties, StyleRule* rule, unsigned linkMatchType, bool inRegionRule)
866 matchResult.matchedProperties.grow(matchResult.matchedProperties.size() + 1);
867 MatchedProperties& newProperties = matchResult.matchedProperties.last();
868 newProperties.properties = const_cast<StylePropertySet*>(properties);
869 newProperties.linkMatchType = linkMatchType;
870 newProperties.isInRegionRule = inRegionRule;
871 matchResult.matchedRules.append(rule);
874 inline void StyleResolver::addElementStyleProperties(MatchResult& result, const StylePropertySet* propertySet, bool isCacheable)
878 result.ranges.lastAuthorRule = result.matchedProperties.size();
879 if (result.ranges.firstAuthorRule == -1)
880 result.ranges.firstAuthorRule = result.ranges.lastAuthorRule;
881 addMatchedProperties(result, propertySet);
883 result.isCacheable = false;
886 void StyleResolver::collectMatchingRules(RuleSet* rules, int& firstRuleIndex, int& lastRuleIndex, const MatchOptions& options)
891 // We need to collect the rules for id, class, tag, and everything else into a buffer and
892 // then sort the buffer.
893 if (m_element->hasID())
894 collectMatchingRulesForList(rules->idRules(m_element->idForStyleResolution().impl()), firstRuleIndex, lastRuleIndex, options);
895 if (m_styledElement && m_styledElement->hasClass()) {
896 for (size_t i = 0; i < m_styledElement->classNames().size(); ++i)
897 collectMatchingRulesForList(rules->classRules(m_styledElement->classNames()[i].impl()), firstRuleIndex, lastRuleIndex, options);
899 const AtomicString& pseudoId = m_element->shadowPseudoId();
900 if (!pseudoId.isEmpty()) {
901 ASSERT(m_styledElement);
902 collectMatchingRulesForList(rules->shadowPseudoElementRules(pseudoId.impl()), firstRuleIndex, lastRuleIndex, options);
904 if (m_element->isLink())
905 collectMatchingRulesForList(rules->linkPseudoClassRules(), firstRuleIndex, lastRuleIndex, options);
906 if (m_checker.matchesFocusPseudoClass(m_element))
907 collectMatchingRulesForList(rules->focusPseudoClassRules(), firstRuleIndex, lastRuleIndex, options);
908 collectMatchingRulesForList(rules->tagRules(m_element->localName().impl()), firstRuleIndex, lastRuleIndex, options);
909 collectMatchingRulesForList(rules->universalRules(), firstRuleIndex, lastRuleIndex, options);
912 void StyleResolver::collectMatchingRulesForRegion(RuleSet* rules, int& firstRuleIndex, int& lastRuleIndex, const MatchOptions& options)
914 if (!m_regionForStyling)
917 unsigned size = rules->m_regionSelectorsAndRuleSets.size();
918 for (unsigned i = 0; i < size; ++i) {
919 CSSSelector* regionSelector = rules->m_regionSelectorsAndRuleSets.at(i).selector;
920 if (checkRegionSelector(regionSelector, static_cast<Element*>(m_regionForStyling->node()))) {
921 RuleSet* regionRules = rules->m_regionSelectorsAndRuleSets.at(i).ruleSet.get();
923 collectMatchingRules(regionRules, firstRuleIndex, lastRuleIndex, options);
928 void StyleResolver::sortAndTransferMatchedRules(MatchResult& result)
930 if (m_matchedRules.isEmpty())
935 if (m_checker.mode() == SelectorChecker::CollectingRules) {
937 m_ruleList = StaticCSSRuleList::create();
938 for (unsigned i = 0; i < m_matchedRules.size(); ++i)
939 m_ruleList->rules().append(m_matchedRules[i]->rule()->createCSSOMWrapper());
943 // Now transfer the set of matched rules over to our list of declarations.
944 // FIXME: This sucks, the inspector should get the style from the visited style itself.
945 bool swapVisitedUnvisited = InspectorInstrumentation::forcePseudoState(m_element, CSSSelector::PseudoVisited);
946 for (unsigned i = 0; i < m_matchedRules.size(); i++) {
947 if (m_style && m_matchedRules[i]->containsUncommonAttributeSelector())
948 m_style->setAffectedByUncommonAttributeSelectors();
949 unsigned linkMatchType = m_matchedRules[i]->linkMatchType();
950 if (swapVisitedUnvisited && linkMatchType && linkMatchType != SelectorChecker::MatchAll)
951 linkMatchType = (linkMatchType == SelectorChecker::MatchVisited) ? SelectorChecker::MatchLink : SelectorChecker::MatchVisited;
952 addMatchedProperties(result, m_matchedRules[i]->rule()->properties(), m_matchedRules[i]->rule(), linkMatchType, m_matchedRules[i]->isInRegionRule());
956 void StyleResolver::matchScopedAuthorRules(MatchResult& result, bool includeEmptyRules)
958 #if ENABLE(STYLE_SCOPED)
959 if (m_scopedAuthorStyles.isEmpty())
962 MatchOptions options(includeEmptyRules);
964 // Match scoped author rules by traversing the scoped element stack (rebuild it if it got inconsistent).
965 if (!scopeStackIsConsistent(m_element))
966 setupScopeStack(m_element);
968 unsigned int firstShadowScopeIndex = 0;
969 if (m_element->treeScope()->applyAuthorStyles()) {
971 for (i = 0; i < m_scopeStack.size() && !m_scopeStack[i].m_scope->isInShadowTree(); ++i) {
972 const ScopeStackFrame& frame = m_scopeStack[i];
973 options.scope = frame.m_scope;
974 collectMatchingRules(frame.m_ruleSet, result.ranges.firstAuthorRule, result.ranges.lastAuthorRule, options);
975 collectMatchingRulesForRegion(frame.m_ruleSet, result.ranges.firstAuthorRule, result.ranges.lastAuthorRule, options);
977 firstShadowScopeIndex = i;
980 if (!m_element->isInShadowTree() || m_scopeStack.isEmpty())
983 unsigned scopedIndex = m_scopeStack.size();
984 int authorStyleBoundsIndex = m_scopeStackParentBoundsIndex;
985 for ( ; scopedIndex > firstShadowScopeIndex; --scopedIndex) {
986 if (authorStyleBoundsIndex != m_scopeStack[scopedIndex - 1].m_authorStyleBoundsIndex)
990 // Ruleset for ancestor nodes should be applied first.
991 for (unsigned i = scopedIndex; i < m_scopeStack.size(); ++i) {
992 const ScopeStackFrame& frame = m_scopeStack[i];
993 options.scope = frame.m_scope;
994 collectMatchingRules(frame.m_ruleSet, result.ranges.firstAuthorRule, result.ranges.lastAuthorRule, options);
995 collectMatchingRulesForRegion(frame.m_ruleSet, result.ranges.firstAuthorRule, result.ranges.lastAuthorRule, options);
998 UNUSED_PARAM(result);
999 UNUSED_PARAM(includeEmptyRules);
1003 void StyleResolver::matchAuthorRules(MatchResult& result, bool includeEmptyRules)
1005 m_matchedRules.clear();
1006 result.ranges.lastAuthorRule = result.matchedProperties.size() - 1;
1011 // Match global author rules.
1012 MatchOptions options(includeEmptyRules);
1013 collectMatchingRules(m_authorStyle.get(), result.ranges.firstAuthorRule, result.ranges.lastAuthorRule, options);
1014 collectMatchingRulesForRegion(m_authorStyle.get(), result.ranges.firstAuthorRule, result.ranges.lastAuthorRule, options);
1016 matchScopedAuthorRules(result, includeEmptyRules);
1018 sortAndTransferMatchedRules(result);
1021 void StyleResolver::matchUserRules(MatchResult& result, bool includeEmptyRules)
1026 m_matchedRules.clear();
1028 result.ranges.lastUserRule = result.matchedProperties.size() - 1;
1029 collectMatchingRules(m_userStyle.get(), result.ranges.firstUserRule, result.ranges.lastUserRule, includeEmptyRules);
1030 collectMatchingRulesForRegion(m_userStyle.get(), result.ranges.firstUserRule, result.ranges.lastUserRule, includeEmptyRules);
1032 sortAndTransferMatchedRules(result);
1035 void StyleResolver::matchUARules(MatchResult& result, RuleSet* rules)
1037 m_matchedRules.clear();
1039 result.ranges.lastUARule = result.matchedProperties.size() - 1;
1040 collectMatchingRules(rules, result.ranges.firstUARule, result.ranges.lastUARule, false);
1042 sortAndTransferMatchedRules(result);
1045 class MatchingUARulesScope {
1047 MatchingUARulesScope();
1048 ~MatchingUARulesScope();
1050 static bool isMatchingUARules();
1053 static bool m_matchingUARules;
1056 MatchingUARulesScope::MatchingUARulesScope()
1058 ASSERT(!m_matchingUARules);
1059 m_matchingUARules = true;
1062 MatchingUARulesScope::~MatchingUARulesScope()
1064 m_matchingUARules = false;
1067 inline bool MatchingUARulesScope::isMatchingUARules()
1069 return m_matchingUARules;
1072 bool MatchingUARulesScope::m_matchingUARules = false;
1074 void StyleResolver::collectMatchingRulesForList(const Vector<RuleData>* rules, int& firstRuleIndex, int& lastRuleIndex, const MatchOptions& options)
1079 TreeScope* treeScope = m_element->treeScope();
1081 // In some cases we may end up looking up style for random elements in the middle of a recursive tree resolve.
1082 // Ancestor identifier filter won't be up-to-date in that case and we can't use the fast path.
1083 bool canUseFastReject = m_checker.parentStackIsConsistent(m_parentNode);
1085 unsigned size = rules->size();
1086 for (unsigned i = 0; i < size; ++i) {
1087 const RuleData& ruleData = rules->at(i);
1088 if (canUseFastReject && m_checker.fastRejectSelector<RuleData::maximumIdentifierCount>(ruleData.descendantSelectorIdentifierHashes()))
1091 StyleRule* rule = ruleData.rule();
1092 InspectorInstrumentationCookie cookie = InspectorInstrumentation::willMatchRule(document(), rule);
1093 #if ENABLE(STYLE_SCOPED)
1094 if (checkSelector(ruleData, options.scope)) {
1096 if (checkSelector(ruleData)) {
1098 // Check whether the rule is applicable in the current tree scope. Criteria for this:
1099 // a) it's a UA rule
1100 // b) the tree scope allows author rules
1101 // c) the rules comes from a scoped style sheet within the same tree scope
1102 // d) the rule contains shadow-ID pseudo elements
1103 if (!MatchingUARulesScope::isMatchingUARules()
1104 && !treeScope->applyAuthorStyles()
1105 #if ENABLE(STYLE_SCOPED)
1106 && (!options.scope || options.scope->treeScope() != treeScope)
1108 && !m_hasUnknownPseudoElements) {
1110 InspectorInstrumentation::didMatchRule(cookie, false);
1113 // If the rule has no properties to apply, then ignore it in the non-debug mode.
1114 const StylePropertySet* properties = rule->properties();
1115 if (!properties || (properties->isEmpty() && !options.includeEmptyRules)) {
1116 InspectorInstrumentation::didMatchRule(cookie, false);
1119 // FIXME: Exposing the non-standard getMatchedCSSRules API to web is the only reason this is needed.
1120 if (m_sameOriginOnly && !ruleData.hasDocumentSecurityOrigin()) {
1121 InspectorInstrumentation::didMatchRule(cookie, false);
1124 // If we're matching normal rules, set a pseudo bit if
1125 // we really just matched a pseudo-element.
1126 if (m_dynamicPseudo != NOPSEUDO && m_pseudoStyle == NOPSEUDO) {
1127 if (m_checker.mode() == SelectorChecker::CollectingRules) {
1128 InspectorInstrumentation::didMatchRule(cookie, false);
1131 if (m_dynamicPseudo < FIRST_INTERNAL_PSEUDOID)
1132 m_style->setHasPseudoStyle(m_dynamicPseudo);
1134 // Update our first/last rule indices in the matched rules array.
1136 if (firstRuleIndex == -1)
1137 firstRuleIndex = lastRuleIndex;
1139 // Add this rule to our list of matched rules.
1140 addMatchedRule(&ruleData);
1141 InspectorInstrumentation::didMatchRule(cookie, true);
1145 InspectorInstrumentation::didMatchRule(cookie, false);
1149 static inline bool compareRules(const RuleData* r1, const RuleData* r2)
1151 unsigned specificity1 = r1->specificity();
1152 unsigned specificity2 = r2->specificity();
1153 return (specificity1 == specificity2) ? r1->position() < r2->position() : specificity1 < specificity2;
1156 void StyleResolver::sortMatchedRules()
1158 std::sort(m_matchedRules.begin(), m_matchedRules.end(), compareRules);
1161 void StyleResolver::matchAllRules(MatchResult& result, bool includeSMILProperties)
1163 matchUARules(result);
1165 // Now we check user sheet rules.
1166 if (m_matchAuthorAndUserStyles)
1167 matchUserRules(result, false);
1169 // Now check author rules, beginning first with presentational attributes mapped from HTML.
1170 if (m_styledElement) {
1171 addElementStyleProperties(result, m_styledElement->attributeStyle());
1173 // Now we check additional mapped declarations.
1174 // Tables and table cells share an additional mapped rule that must be applied
1175 // after all attributes, since their mapped style depends on the values of multiple attributes.
1176 addElementStyleProperties(result, m_styledElement->additionalAttributeStyle());
1178 if (m_styledElement->isHTMLElement()) {
1180 TextDirection textDirection = toHTMLElement(m_styledElement)->directionalityIfhasDirAutoAttribute(isAuto);
1182 addMatchedProperties(result, textDirection == LTR ? leftToRightDeclaration() : rightToLeftDeclaration());
1186 // Check the rules in author sheets next.
1187 if (m_matchAuthorAndUserStyles)
1188 matchAuthorRules(result, false);
1190 // Now check our inline style attribute.
1191 if (m_matchAuthorAndUserStyles && m_styledElement && m_styledElement->inlineStyle()) {
1192 // Inline style is immutable as long as there is no CSSOM wrapper.
1193 // FIXME: Media control shadow trees seem to have problems with caching.
1194 bool isInlineStyleCacheable = !m_styledElement->inlineStyle()->isMutable() && !m_styledElement->isInShadowTree();
1196 addElementStyleProperties(result, m_styledElement->inlineStyle(), isInlineStyleCacheable);
1200 // Now check SMIL animation override style.
1201 if (includeSMILProperties && m_matchAuthorAndUserStyles && m_styledElement && m_styledElement->isSVGElement())
1202 addElementStyleProperties(result, static_cast<SVGElement*>(m_styledElement)->animatedSMILStyleProperties(), false /* isCacheable */);
1204 UNUSED_PARAM(includeSMILProperties);
1208 inline void StyleResolver::initElement(Element* e)
1210 if (m_element != e) {
1212 m_styledElement = m_element && m_element->isStyledElement() ? static_cast<StyledElement*>(m_element) : 0;
1213 m_elementLinkState = m_checker.determineLinkState(m_element);
1214 if (e && e == e->document()->documentElement()) {
1215 e->document()->setDirectionSetOnDocumentElement(false);
1216 e->document()->setWritingModeSetOnDocumentElement(false);
1221 inline void StyleResolver::initForStyleResolve(Element* e, RenderStyle* parentStyle, PseudoId pseudoID)
1223 m_pseudoStyle = pseudoID;
1226 NodeRenderingContext context(e);
1227 m_parentNode = context.parentNodeForRenderingAndStyle();
1228 m_parentStyle = context.resetStyleInheritance()? 0 :
1229 parentStyle ? parentStyle :
1230 m_parentNode ? m_parentNode->renderStyle() : 0;
1231 m_distributedToInsertionPoint = context.insertionPoint();
1234 m_parentStyle = parentStyle;
1235 m_distributedToInsertionPoint = false;
1238 Node* docElement = e ? e->document()->documentElement() : 0;
1239 RenderStyle* docStyle = m_checker.document()->renderStyle();
1240 m_rootElementStyle = docElement && e != docElement ? docElement->renderStyle() : docStyle;
1244 m_pendingImageProperties.clear();
1248 m_fontDirty = false;
1251 static const unsigned cStyleSearchThreshold = 10;
1252 static const unsigned cStyleSearchLevelThreshold = 10;
1254 Node* StyleResolver::locateCousinList(Element* parent, unsigned& visitedNodeCount) const
1256 if (visitedNodeCount >= cStyleSearchThreshold * cStyleSearchLevelThreshold)
1258 if (!parent || !parent->isStyledElement())
1260 #if ENABLE(STYLE_SCOPED)
1261 if (parent->hasScopedHTMLStyleChild())
1264 StyledElement* p = static_cast<StyledElement*>(parent);
1265 if (p->inlineStyle())
1268 if (p->isSVGElement() && static_cast<SVGElement*>(p)->animatedSMILStyleProperties())
1271 if (p->hasID() && m_features.idsInRules.contains(p->idForStyleResolution().impl()))
1274 RenderStyle* parentStyle = p->renderStyle();
1275 unsigned subcount = 0;
1276 Node* thisCousin = p;
1277 Node* currentNode = p->previousSibling();
1279 // Reserve the tries for this level. This effectively makes sure that the algorithm
1280 // will never go deeper than cStyleSearchLevelThreshold levels into recursion.
1281 visitedNodeCount += cStyleSearchThreshold;
1282 while (thisCousin) {
1283 while (currentNode) {
1285 if (currentNode->renderStyle() == parentStyle && currentNode->lastChild()) {
1286 // Adjust for unused reserved tries.
1287 visitedNodeCount -= cStyleSearchThreshold - subcount;
1288 return currentNode->lastChild();
1290 if (subcount >= cStyleSearchThreshold)
1292 currentNode = currentNode->previousSibling();
1294 currentNode = locateCousinList(thisCousin->parentElement(), visitedNodeCount);
1295 thisCousin = currentNode;
1301 bool StyleResolver::matchesRuleSet(RuleSet* ruleSet)
1305 m_matchedRules.clear();
1307 int firstRuleIndex = -1, lastRuleIndex = -1;
1308 collectMatchingRules(ruleSet, firstRuleIndex, lastRuleIndex, false);
1310 if (m_matchedRules.isEmpty())
1312 m_matchedRules.clear();
1316 bool StyleResolver::canShareStyleWithControl(StyledElement* element) const
1318 HTMLInputElement* thisInputElement = element->toInputElement();
1319 HTMLInputElement* otherInputElement = m_element->toInputElement();
1321 if (!thisInputElement || !otherInputElement)
1324 if (thisInputElement->fastGetAttribute(typeAttr) != otherInputElement->fastGetAttribute(typeAttr))
1327 if (thisInputElement->isAutofilled() != otherInputElement->isAutofilled())
1329 if (thisInputElement->shouldAppearChecked() != otherInputElement->shouldAppearChecked())
1331 if (thisInputElement->isIndeterminate() != otherInputElement->isIndeterminate())
1333 if (thisInputElement->required() != otherInputElement->required())
1336 if (element->isEnabledFormControl() != m_element->isEnabledFormControl())
1339 if (element->isDefaultButtonForForm() != m_element->isDefaultButtonForForm())
1342 if (m_element->document()->containsValidityStyleRules()) {
1343 bool willValidate = element->willValidate();
1345 if (willValidate != m_element->willValidate())
1348 if (willValidate && (element->isValidFormControlElement() != m_element->isValidFormControlElement()))
1351 if (element->isInRange() != m_element->isInRange())
1354 if (element->isOutOfRange() != m_element->isOutOfRange())
1361 // This function makes some assumptions that only make sense for attribute styles (we only compare CSSProperty::id() and CSSProperty::value().)
1362 static inline bool attributeStylesEqual(const StylePropertySet* a, const StylePropertySet* b)
1366 if (a->propertyCount() != b->propertyCount())
1368 unsigned propertyCount = a->propertyCount();
1369 for (unsigned i = 0; i < propertyCount; ++i) {
1370 const CSSProperty& aProperty = a->propertyAt(i);
1372 for (j = 0; j < propertyCount; ++j) {
1373 const CSSProperty& bProperty = b->propertyAt(j);
1374 if (aProperty.id() != bProperty.id())
1376 // We could get a few more hits by comparing cssText() here, but that gets expensive quickly.
1377 if (aProperty.value() != bProperty.value())
1381 if (j == propertyCount)
1387 static inline bool elementHasDirectionAuto(Element* element)
1389 // FIXME: This line is surprisingly hot, we may wish to inline hasDirectionAuto into StyleResolver.
1390 return element->isHTMLElement() && toHTMLElement(element)->hasDirectionAuto();
1393 bool StyleResolver::canShareStyleWithElement(StyledElement* element) const
1395 RenderStyle* style = element->renderStyle();
1399 if (style->unique())
1401 if (element->tagQName() != m_element->tagQName())
1403 if (element->hasClass() != m_element->hasClass())
1405 if (element->inlineStyle())
1407 if (element->needsStyleRecalc())
1410 if (element->isSVGElement() && static_cast<SVGElement*>(element)->animatedSMILStyleProperties())
1413 if (!!element->attributeStyle() != !!m_styledElement->attributeStyle())
1415 const StylePropertySet* additionalAttributeStyleA = element->additionalAttributeStyle();
1416 const StylePropertySet* additionalAttributeStyleB = m_styledElement->additionalAttributeStyle();
1417 if (!additionalAttributeStyleA != !additionalAttributeStyleB)
1419 if (element->isLink() != m_element->isLink())
1421 if (style->affectedByUncommonAttributeSelectors())
1423 if (element->hovered() != m_element->hovered())
1425 if (element->active() != m_element->active())
1427 if (element->focused() != m_element->focused())
1429 if (element->shadowPseudoId() != m_element->shadowPseudoId())
1431 if (element == element->document()->cssTarget())
1433 if (m_element == m_element->document()->cssTarget())
1435 if (element->fastGetAttribute(XMLNames::langAttr) != m_element->fastGetAttribute(XMLNames::langAttr))
1437 if (element->fastGetAttribute(langAttr) != m_element->fastGetAttribute(langAttr))
1439 if (element->fastGetAttribute(readonlyAttr) != m_element->fastGetAttribute(readonlyAttr))
1441 if (element->fastGetAttribute(cellpaddingAttr) != m_element->fastGetAttribute(cellpaddingAttr))
1444 if (element->hasID() && m_features.idsInRules.contains(element->idForStyleResolution().impl()))
1447 #if ENABLE(STYLE_SCOPED)
1448 if (element->hasScopedHTMLStyleChild())
1452 #if ENABLE(PROGRESS_ELEMENT)
1453 if (element->hasTagName(progressTag)) {
1454 if (!m_element->hasTagName(progressTag))
1457 HTMLProgressElement* thisProgressElement = static_cast<HTMLProgressElement*>(element);
1458 HTMLProgressElement* otherProgressElement = static_cast<HTMLProgressElement*>(m_element);
1459 if (thisProgressElement->isDeterminate() != otherProgressElement->isDeterminate())
1464 // FIXME: We should share style for option and optgroup whenever possible.
1465 // Before doing so, we need to resolve issues in HTMLSelectElement::recalcListItems
1466 // and RenderMenuList::setText. See also https://bugs.webkit.org/show_bug.cgi?id=88405
1467 if (element->hasTagName(optionTag) || element->hasTagName(optgroupTag))
1470 bool isControl = element->isFormControlElement();
1472 if (isControl != m_element->isFormControlElement())
1475 if (isControl && !canShareStyleWithControl(element))
1478 if (style->transitions() || style->animations())
1481 #if USE(ACCELERATED_COMPOSITING)
1482 // Turn off style sharing for elements that can gain layers for reasons outside of the style system.
1483 // See comments in RenderObject::setStyle().
1484 if (element->hasTagName(iframeTag) || element->hasTagName(frameTag) || element->hasTagName(embedTag) || element->hasTagName(objectTag) || element->hasTagName(appletTag)
1485 #if ENABLE(PLUGIN_PROXY_FOR_VIDEO)
1486 // With proxying, the media elements are backed by a RenderEmbeddedObject.
1487 || element->hasTagName(videoTag) || element->hasTagName(audioTag)
1493 if (elementHasDirectionAuto(element) || elementHasDirectionAuto(m_element))
1496 if (element->hasClass()) {
1498 // SVG elements require a (slow!) getAttribute comparision because "class" is an animatable attribute for SVG.
1499 if (element->isSVGElement()) {
1500 if (element->getAttribute(classAttr) != m_element->getAttribute(classAttr))
1504 if (element->fastGetAttribute(classAttr) != m_element->fastGetAttribute(classAttr))
1508 if (element->attributeStyle() && !attributeStylesEqual(element->attributeStyle(), m_styledElement->attributeStyle()))
1511 if (additionalAttributeStyleA && !attributeStylesEqual(additionalAttributeStyleA, additionalAttributeStyleB))
1514 if (element->isLink() && m_elementLinkState != style->insideLink())
1520 inline StyledElement* StyleResolver::findSiblingForStyleSharing(Node* node, unsigned& count) const
1522 for (; node; node = node->previousSibling()) {
1523 if (!node->isStyledElement())
1525 if (canShareStyleWithElement(static_cast<StyledElement*>(node)))
1527 if (count++ == cStyleSearchThreshold)
1530 return static_cast<StyledElement*>(node);
1533 static inline bool parentStylePreventsSharing(const RenderStyle* parentStyle)
1535 return parentStyle->childrenAffectedByPositionalRules()
1536 || parentStyle->childrenAffectedByFirstChildRules()
1537 || parentStyle->childrenAffectedByLastChildRules()
1538 || parentStyle->childrenAffectedByDirectAdjacentRules();
1541 RenderStyle* StyleResolver::locateSharedStyle()
1543 if (!m_styledElement || !m_parentStyle)
1545 // If the element has inline style it is probably unique.
1546 if (m_styledElement->inlineStyle())
1549 if (m_styledElement->isSVGElement() && static_cast<SVGElement*>(m_styledElement)->animatedSMILStyleProperties())
1552 // Ids stop style sharing if they show up in the stylesheets.
1553 if (m_styledElement->hasID() && m_features.idsInRules.contains(m_styledElement->idForStyleResolution().impl()))
1555 if (parentStylePreventsSharing(m_parentStyle))
1557 #if ENABLE(STYLE_SCOPED)
1558 if (m_styledElement->hasScopedHTMLStyleChild())
1562 // Check previous siblings and their cousins.
1564 unsigned visitedNodeCount = 0;
1565 StyledElement* shareElement = 0;
1566 Node* cousinList = m_styledElement->previousSibling();
1567 while (cousinList) {
1568 shareElement = findSiblingForStyleSharing(cousinList, count);
1571 cousinList = locateCousinList(cousinList->parentElement(), visitedNodeCount);
1574 // If we have exhausted all our budget or our cousins.
1578 // Can't share if sibling rules apply. This is checked at the end as it should rarely fail.
1579 if (matchesRuleSet(m_siblingRuleSet.get()))
1581 // Can't share if attribute rules apply.
1582 if (matchesRuleSet(m_uncommonAttributeRuleSet.get()))
1584 // Tracking child index requires unique style for each node. This may get set by the sibling rule match above.
1585 if (parentStylePreventsSharing(m_parentStyle))
1587 return shareElement->renderStyle();
1590 void StyleResolver::matchUARules(MatchResult& result)
1592 MatchingUARulesScope scope;
1594 // First we match rules from the user agent sheet.
1595 if (simpleDefaultStyleSheet)
1596 result.isCacheable = false;
1597 RuleSet* userAgentStyleSheet = m_medium->mediaTypeMatchSpecific("print")
1598 ? defaultPrintStyle : defaultStyle;
1599 matchUARules(result, userAgentStyleSheet);
1601 // In quirks mode, we match rules from the quirks user agent sheet.
1602 if (!m_checker.strictParsing())
1603 matchUARules(result, defaultQuirksStyle);
1605 // 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.
1606 if (m_checker.document()->isViewSource()) {
1607 if (!defaultViewSourceStyle)
1608 loadViewSourceStyle();
1609 matchUARules(result, defaultViewSourceStyle);
1613 static void setStylesForPaginationMode(Pagination::Mode paginationMode, RenderStyle* style)
1615 if (paginationMode == Pagination::Unpaginated)
1618 switch (paginationMode) {
1619 case Pagination::LeftToRightPaginated:
1620 style->setColumnAxis(HorizontalColumnAxis);
1621 if (style->isHorizontalWritingMode())
1622 style->setColumnProgression(style->isLeftToRightDirection() ? NormalColumnProgression : ReverseColumnProgression);
1624 style->setColumnProgression(style->isFlippedBlocksWritingMode() ? ReverseColumnProgression : NormalColumnProgression);
1626 case Pagination::RightToLeftPaginated:
1627 style->setColumnAxis(HorizontalColumnAxis);
1628 if (style->isHorizontalWritingMode())
1629 style->setColumnProgression(style->isLeftToRightDirection() ? ReverseColumnProgression : NormalColumnProgression);
1631 style->setColumnProgression(style->isFlippedBlocksWritingMode() ? NormalColumnProgression : ReverseColumnProgression);
1633 case Pagination::TopToBottomPaginated:
1634 style->setColumnAxis(VerticalColumnAxis);
1635 if (style->isHorizontalWritingMode())
1636 style->setColumnProgression(style->isFlippedBlocksWritingMode() ? ReverseColumnProgression : NormalColumnProgression);
1638 style->setColumnProgression(style->isLeftToRightDirection() ? NormalColumnProgression : ReverseColumnProgression);
1640 case Pagination::BottomToTopPaginated:
1641 style->setColumnAxis(VerticalColumnAxis);
1642 if (style->isHorizontalWritingMode())
1643 style->setColumnProgression(style->isFlippedBlocksWritingMode() ? NormalColumnProgression : ReverseColumnProgression);
1645 style->setColumnProgression(style->isLeftToRightDirection() ? ReverseColumnProgression : NormalColumnProgression);
1647 case Pagination::Unpaginated:
1648 ASSERT_NOT_REACHED();
1653 PassRefPtr<RenderStyle> StyleResolver::styleForDocument(Document* document, CSSFontSelector* fontSelector)
1655 Frame* frame = document->frame();
1657 // HTML5 states that seamless iframes should replace default CSS values
1658 // with values inherited from the containing iframe element. However,
1659 // some values (such as the case of designMode = "on") still need to
1660 // be set by this "document style".
1661 RefPtr<RenderStyle> documentStyle = RenderStyle::create();
1662 bool seamlessWithParent = document->shouldDisplaySeamlesslyWithParent();
1663 if (seamlessWithParent) {
1664 RenderStyle* iframeStyle = document->seamlessParentIFrame()->renderStyle();
1666 documentStyle->inheritFrom(iframeStyle);
1669 // FIXME: It's not clear which values below we want to override in the seamless case!
1670 documentStyle->setDisplay(BLOCK);
1671 if (!seamlessWithParent) {
1672 documentStyle->setRTLOrdering(document->visuallyOrdered() ? VisualOrder : LogicalOrder);
1673 documentStyle->setZoom(frame && !document->printing() ? frame->pageZoomFactor() : 1);
1674 documentStyle->setPageScaleTransform(frame ? frame->frameScaleFactor() : 1);
1675 documentStyle->setLocale(document->contentLanguage());
1677 // FIXME: This overrides any -webkit-user-modify inherited from the parent iframe.
1678 documentStyle->setUserModify(document->inDesignMode() ? READ_WRITE : READ_ONLY);
1680 Element* docElement = document->documentElement();
1681 RenderObject* docElementRenderer = docElement ? docElement->renderer() : 0;
1682 if (docElementRenderer) {
1683 // Use the direction and writing-mode of the body to set the
1684 // viewport's direction and writing-mode unless the property is set on the document element.
1685 // If there is no body, then use the document element.
1686 RenderObject* bodyRenderer = document->body() ? document->body()->renderer() : 0;
1687 if (bodyRenderer && !document->writingModeSetOnDocumentElement())
1688 documentStyle->setWritingMode(bodyRenderer->style()->writingMode());
1690 documentStyle->setWritingMode(docElementRenderer->style()->writingMode());
1691 if (bodyRenderer && !document->directionSetOnDocumentElement())
1692 documentStyle->setDirection(bodyRenderer->style()->direction());
1694 documentStyle->setDirection(docElementRenderer->style()->direction());
1698 if (FrameView* frameView = frame->view()) {
1699 const Pagination& pagination = frameView->pagination();
1700 if (pagination.mode != Pagination::Unpaginated) {
1701 setStylesForPaginationMode(pagination.mode, documentStyle.get());
1702 documentStyle->setColumnGap(pagination.gap);
1703 if (RenderView* view = document->renderView()) {
1704 if (view->hasColumns())
1705 view->updateColumnInfoFromStyle(documentStyle.get());
1711 // Seamless iframes want to inherit their font from their parent iframe, so early return before setting the font.
1712 if (seamlessWithParent)
1713 return documentStyle.release();
1715 FontDescription fontDescription;
1716 fontDescription.setScript(localeToScriptCodeForFontSelection(documentStyle->locale()));
1717 if (Settings* settings = document->settings()) {
1718 fontDescription.setUsePrinterFont(document->printing() || !settings->screenFontSubstitutionEnabled());
1719 fontDescription.setRenderingMode(settings->fontRenderingMode());
1720 const AtomicString& standardFont = settings->standardFontFamily(fontDescription.script());
1721 if (!standardFont.isEmpty()) {
1722 fontDescription.setGenericFamily(FontDescription::StandardFamily);
1723 fontDescription.firstFamily().setFamily(standardFont);
1724 fontDescription.firstFamily().appendFamily(0);
1726 fontDescription.setKeywordSize(CSSValueMedium - CSSValueXxSmall + 1);
1727 int size = StyleResolver::fontSizeForKeyword(document, CSSValueMedium, false);
1728 fontDescription.setSpecifiedSize(size);
1729 bool useSVGZoomRules = document->isSVGDocument();
1730 fontDescription.setComputedSize(StyleResolver::getComputedSizeFromSpecifiedSize(document, documentStyle.get(), fontDescription.isAbsoluteSize(), size, useSVGZoomRules));
1732 fontDescription.setUsePrinterFont(document->printing());
1734 documentStyle->setFontDescription(fontDescription);
1735 documentStyle->font().update(fontSelector);
1737 return documentStyle.release();
1740 static inline bool isAtShadowBoundary(const Element* element)
1744 ContainerNode* parentNode = element->parentNode();
1745 return parentNode && parentNode->isShadowRoot();
1748 PassRefPtr<RenderStyle> StyleResolver::styleForElement(Element* element, RenderStyle* defaultParent,
1749 StyleSharingBehavior sharingBehavior, RuleMatchingBehavior matchingBehavior, RenderRegion* regionForStyling)
1751 // Once an element has a renderer, we don't try to destroy it, since otherwise the renderer
1752 // will vanish if a style recalc happens during loading.
1753 if (sharingBehavior == AllowStyleSharing && !element->document()->haveStylesheetsLoaded() && !element->renderer()) {
1754 if (!s_styleNotYetAvailable) {
1755 s_styleNotYetAvailable = RenderStyle::create().leakRef();
1756 s_styleNotYetAvailable->setDisplay(NONE);
1757 s_styleNotYetAvailable->font().update(m_fontSelector);
1759 element->document()->setHasNodesWithPlaceholderStyle();
1760 return s_styleNotYetAvailable;
1763 initElement(element);
1764 initForStyleResolve(element, defaultParent);
1765 m_regionForStyling = regionForStyling;
1766 if (sharingBehavior == AllowStyleSharing && !m_distributedToInsertionPoint) {
1767 RenderStyle* sharedStyle = locateSharedStyle();
1772 m_style = RenderStyle::create();
1774 RefPtr<RenderStyle> cloneForParent;
1777 m_style->inheritFrom(m_parentStyle, isAtShadowBoundary(element) ? RenderStyle::AtShadowBoundary : RenderStyle::NotAtShadowBoundary);
1779 // Make sure our fonts are initialized if we don't inherit them from our parent style.
1780 if (Settings* settings = documentSettings()) {
1781 initializeFontStyle(settings);
1782 m_style->font().update(fontSelector());
1784 m_style->font().update(0);
1785 cloneForParent = RenderStyle::clone(style());
1786 m_parentStyle = cloneForParent.get();
1789 if (element->isLink()) {
1790 m_style->setIsLink(true);
1791 m_style->setInsideLink(m_elementLinkState);
1794 ensureDefaultStyleSheetsForElement(element);
1796 MatchResult matchResult;
1797 if (matchingBehavior == MatchOnlyUserAgentRules)
1798 matchUARules(matchResult);
1800 matchAllRules(matchResult, matchingBehavior != MatchAllRulesExcludingSMIL);
1802 applyMatchedProperties(matchResult, element);
1804 // Clean up our style object's display and text decorations (among other fixups).
1805 adjustRenderStyle(style(), m_parentStyle, element);
1807 initElement(0); // Clear out for the next resolve.
1812 // Now return the style.
1813 return m_style.release();
1816 PassRefPtr<RenderStyle> StyleResolver::styleForKeyframe(const RenderStyle* elementStyle, const StyleKeyframe* keyframe, KeyframeValue& keyframeValue)
1819 if (keyframe->properties())
1820 addMatchedProperties(result, keyframe->properties());
1825 m_style = RenderStyle::clone(elementStyle);
1827 m_lineHeightValue = 0;
1829 // We don't need to bother with !important. Since there is only ever one
1830 // decl, there's nothing to override. So just add the first properties.
1831 bool inheritedOnly = false;
1832 if (keyframe->properties())
1833 applyMatchedProperties<HighPriorityProperties>(result, false, 0, result.matchedProperties.size() - 1, inheritedOnly);
1835 // If our font got dirtied, go ahead and update it now.
1838 // Line-height is set when we are sure we decided on the font-size
1839 if (m_lineHeightValue)
1840 applyProperty(CSSPropertyLineHeight, m_lineHeightValue);
1842 // Now do rest of the properties.
1843 if (keyframe->properties())
1844 applyMatchedProperties<LowPriorityProperties>(result, false, 0, result.matchedProperties.size() - 1, inheritedOnly);
1846 // If our font got dirtied by one of the non-essential font props,
1847 // go ahead and update it a second time.
1850 // Start loading resources referenced by this style.
1851 loadPendingResources();
1853 // Add all the animating properties to the keyframe.
1854 if (const StylePropertySet* styleDeclaration = keyframe->properties()) {
1855 unsigned propertyCount = styleDeclaration->propertyCount();
1856 for (unsigned i = 0; i < propertyCount; ++i) {
1857 CSSPropertyID property = styleDeclaration->propertyAt(i).id();
1858 // Timing-function within keyframes is special, because it is not animated; it just
1859 // describes the timing function between this keyframe and the next.
1860 if (property != CSSPropertyWebkitAnimationTimingFunction)
1861 keyframeValue.addProperty(property);
1865 return m_style.release();
1868 void StyleResolver::keyframeStylesForAnimation(Element* e, const RenderStyle* elementStyle, KeyframeList& list)
1872 // Get the keyframesRule for this name
1873 if (!e || list.animationName().isEmpty())
1876 m_keyframesRuleMap.checkConsistency();
1878 KeyframesRuleMap::iterator it = m_keyframesRuleMap.find(list.animationName().impl());
1879 if (it == m_keyframesRuleMap.end())
1882 const StyleRuleKeyframes* keyframesRule = it->second.get();
1884 // Construct and populate the style for each keyframe
1885 const Vector<RefPtr<StyleKeyframe> >& keyframes = keyframesRule->keyframes();
1886 for (unsigned i = 0; i < keyframes.size(); ++i) {
1887 // Apply the declaration to the style. This is a simplified version of the logic in styleForElement
1889 initForStyleResolve(e);
1891 const StyleKeyframe* keyframe = keyframes[i].get();
1893 KeyframeValue keyframeValue(0, 0);
1894 keyframeValue.setStyle(styleForKeyframe(elementStyle, keyframe, keyframeValue));
1896 // Add this keyframe style to all the indicated key times
1898 keyframe->getKeys(keys);
1899 for (size_t keyIndex = 0; keyIndex < keys.size(); ++keyIndex) {
1900 keyframeValue.setKey(keys[keyIndex]);
1901 list.insert(keyframeValue);
1905 // If the 0% keyframe is missing, create it (but only if there is at least one other keyframe)
1906 int initialListSize = list.size();
1907 if (initialListSize > 0 && list[0].key()) {
1908 static StyleKeyframe* zeroPercentKeyframe;
1909 if (!zeroPercentKeyframe) {
1910 zeroPercentKeyframe = StyleKeyframe::create().leakRef();
1911 zeroPercentKeyframe->setKeyText("0%");
1913 KeyframeValue keyframeValue(0, 0);
1914 keyframeValue.setStyle(styleForKeyframe(elementStyle, zeroPercentKeyframe, keyframeValue));
1915 list.insert(keyframeValue);
1918 // If the 100% keyframe is missing, create it (but only if there is at least one other keyframe)
1919 if (initialListSize > 0 && (list[list.size() - 1].key() != 1)) {
1920 static StyleKeyframe* hundredPercentKeyframe;
1921 if (!hundredPercentKeyframe) {
1922 hundredPercentKeyframe = StyleKeyframe::create().leakRef();
1923 hundredPercentKeyframe->setKeyText("100%");
1925 KeyframeValue keyframeValue(1, 0);
1926 keyframeValue.setStyle(styleForKeyframe(elementStyle, hundredPercentKeyframe, keyframeValue));
1927 list.insert(keyframeValue);
1931 PassRefPtr<RenderStyle> StyleResolver::pseudoStyleForElement(PseudoId pseudo, Element* e, RenderStyle* parentStyle)
1933 ASSERT(m_parentStyle);
1939 initForStyleResolve(e, parentStyle, pseudo);
1940 m_style = RenderStyle::create();
1941 m_style->inheritFrom(m_parentStyle);
1943 // Since we don't use pseudo-elements in any of our quirk/print user agent rules, don't waste time walking
1946 // Check UA, user and author rules.
1947 MatchResult matchResult;
1948 matchUARules(matchResult);
1950 if (m_matchAuthorAndUserStyles) {
1951 matchUserRules(matchResult, false);
1952 matchAuthorRules(matchResult, false);
1955 if (matchResult.matchedProperties.isEmpty())
1958 m_style->setStyleType(pseudo);
1960 applyMatchedProperties(matchResult, e);
1962 // Clean up our style object's display and text decorations (among other fixups).
1963 adjustRenderStyle(style(), parentStyle, 0);
1965 // Start loading resources referenced by this style.
1966 loadPendingResources();
1968 // Now return the style.
1969 return m_style.release();
1972 PassRefPtr<RenderStyle> StyleResolver::styleForPage(int pageIndex)
1974 initForStyleResolve(m_checker.document()->documentElement()); // m_rootElementStyle will be set to the document style.
1976 m_style = RenderStyle::create();
1977 m_style->inheritFrom(m_rootElementStyle);
1979 const bool isLeft = isLeftPage(pageIndex);
1980 const bool isFirst = isFirstPage(pageIndex);
1981 const String page = pageName(pageIndex);
1984 matchPageRules(result, defaultPrintStyle, isLeft, isFirst, page);
1985 matchPageRules(result, m_userStyle.get(), isLeft, isFirst, page);
1986 // Only consider the global author RuleSet for @page rules, as per the HTML5 spec.
1987 matchPageRules(result, m_authorStyle.get(), isLeft, isFirst, page);
1988 m_lineHeightValue = 0;
1989 bool inheritedOnly = false;
1990 #if ENABLE(CSS_VARIABLES)
1991 applyMatchedProperties<VariableDefinitions>(result, false, 0, result.matchedProperties.size() - 1, inheritedOnly);
1993 applyMatchedProperties<HighPriorityProperties>(result, false, 0, result.matchedProperties.size() - 1, inheritedOnly);
1995 // If our font got dirtied, go ahead and update it now.
1998 // Line-height is set when we are sure we decided on the font-size.
1999 if (m_lineHeightValue)
2000 applyProperty(CSSPropertyLineHeight, m_lineHeightValue);
2002 applyMatchedProperties<LowPriorityProperties>(result, false, 0, result.matchedProperties.size() - 1, inheritedOnly);
2004 // Start loading resources referenced by this style.
2005 loadPendingResources();
2007 // Now return the style.
2008 return m_style.release();
2011 static void addIntrinsicMargins(RenderStyle* style)
2013 // Intrinsic margin value.
2014 const int intrinsicMargin = 2 * style->effectiveZoom();
2016 // FIXME: Using width/height alone and not also dealing with min-width/max-width is flawed.
2017 // FIXME: Using "quirk" to decide the margin wasn't set is kind of lame.
2018 if (style->width().isIntrinsicOrAuto()) {
2019 if (style->marginLeft().quirk())
2020 style->setMarginLeft(Length(intrinsicMargin, Fixed));
2021 if (style->marginRight().quirk())
2022 style->setMarginRight(Length(intrinsicMargin, Fixed));
2025 if (style->height().isAuto()) {
2026 if (style->marginTop().quirk())
2027 style->setMarginTop(Length(intrinsicMargin, Fixed));
2028 if (style->marginBottom().quirk())
2029 style->setMarginBottom(Length(intrinsicMargin, Fixed));
2033 static EDisplay equivalentBlockDisplay(EDisplay display, bool isFloating, bool strictParsing)
2044 // It is a WinIE bug that floated list items lose their bullets, so we'll emulate the quirk, but only in quirks mode.
2045 if (!strictParsing && isFloating)
2061 case TABLE_ROW_GROUP:
2062 case TABLE_HEADER_GROUP:
2063 case TABLE_FOOTER_GROUP:
2065 case TABLE_COLUMN_GROUP:
2071 ASSERT_NOT_REACHED();
2074 ASSERT_NOT_REACHED();
2078 // CSS requires text-decoration to be reset at each DOM element for tables,
2079 // inline blocks, inline tables, run-ins, shadow DOM crossings, floating elements,
2080 // and absolute or relatively positioned elements.
2081 static bool doesNotInheritTextDecoration(RenderStyle* style, Element* e)
2083 return style->display() == TABLE || style->display() == INLINE_TABLE || style->display() == RUN_IN
2084 || style->display() == INLINE_BLOCK || style->display() == INLINE_BOX || isAtShadowBoundary(e)
2085 || style->isFloating() || style->hasOutOfFlowPosition();
2088 static bool isDisplayFlexibleBox(EDisplay display)
2090 return display == FLEX || display == INLINE_FLEX;
2093 void StyleResolver::adjustRenderStyle(RenderStyle* style, RenderStyle* parentStyle, Element *e)
2095 ASSERT(parentStyle);
2097 // Cache our original display.
2098 style->setOriginalDisplay(style->display());
2100 if (style->display() != NONE) {
2101 // If we have a <td> that specifies a float property, in quirks mode we just drop the float
2103 // Sites also commonly use display:inline/block on <td>s and <table>s. In quirks mode we force
2104 // these tags to retain their display types.
2105 if (!m_checker.strictParsing() && e) {
2106 if (e->hasTagName(tdTag)) {
2107 style->setDisplay(TABLE_CELL);
2108 style->setFloating(NoFloat);
2109 } else if (e->hasTagName(tableTag))
2110 style->setDisplay(style->isDisplayInlineType() ? INLINE_TABLE : TABLE);
2113 if (e && (e->hasTagName(tdTag) || e->hasTagName(thTag))) {
2114 if (style->whiteSpace() == KHTML_NOWRAP) {
2115 // Figure out if we are really nowrapping or if we should just
2116 // use normal instead. If the width of the cell is fixed, then
2117 // we don't actually use NOWRAP.
2118 if (style->width().isFixed())
2119 style->setWhiteSpace(NORMAL);
2121 style->setWhiteSpace(NOWRAP);
2125 // Tables never support the -webkit-* values for text-align and will reset back to the default.
2126 if (e && e->hasTagName(tableTag) && (style->textAlign() == WEBKIT_LEFT || style->textAlign() == WEBKIT_CENTER || style->textAlign() == WEBKIT_RIGHT))
2127 style->setTextAlign(TASTART);
2129 // Frames and framesets never honor position:relative or position:absolute. This is necessary to
2130 // fix a crash where a site tries to position these objects. They also never honor display.
2131 if (e && (e->hasTagName(frameTag) || e->hasTagName(framesetTag))) {
2132 style->setPosition(StaticPosition);
2133 style->setDisplay(BLOCK);
2136 // Ruby text does not support float or position. This might change with evolution of the specification.
2137 if (e && e->hasTagName(rtTag)) {
2138 style->setPosition(StaticPosition);
2139 style->setFloating(NoFloat);
2142 // FIXME: We shouldn't be overriding start/-webkit-auto like this. Do it in html.css instead.
2143 // Table headers with a text-align of -webkit-auto will change the text-align to center.
2144 if (e && e->hasTagName(thTag) && style->textAlign() == TASTART)
2145 style->setTextAlign(CENTER);
2147 if (e && e->hasTagName(legendTag))
2148 style->setDisplay(BLOCK);
2150 // Absolute/fixed positioned elements, floating elements and the document element need block-like outside display.
2151 if (style->hasOutOfFlowPosition() || style->isFloating() || (e && e->document()->documentElement() == e))
2152 style->setDisplay(equivalentBlockDisplay(style->display(), style->isFloating(), m_checker.strictParsing()));
2154 // FIXME: Don't support this mutation for pseudo styles like first-letter or first-line, since it's not completely
2155 // clear how that should work.
2156 if (style->display() == INLINE && style->styleType() == NOPSEUDO && style->writingMode() != parentStyle->writingMode())
2157 style->setDisplay(INLINE_BLOCK);
2159 // After performing the display mutation, check table rows. We do not honor position:relative on
2160 // table rows or cells. This has been established in CSS2.1 (and caused a crash in containingBlock()
2162 if ((style->display() == TABLE_HEADER_GROUP || style->display() == TABLE_ROW_GROUP
2163 || style->display() == TABLE_FOOTER_GROUP || style->display() == TABLE_ROW)
2164 && style->position() == RelativePosition)
2165 style->setPosition(StaticPosition);
2167 // writing-mode does not apply to table row groups, table column groups, table rows, and table columns.
2168 // FIXME: Table cells should be allowed to be perpendicular or flipped with respect to the table, though.
2169 if (style->display() == TABLE_COLUMN || style->display() == TABLE_COLUMN_GROUP || style->display() == TABLE_FOOTER_GROUP
2170 || style->display() == TABLE_HEADER_GROUP || style->display() == TABLE_ROW || style->display() == TABLE_ROW_GROUP
2171 || style->display() == TABLE_CELL)
2172 style->setWritingMode(parentStyle->writingMode());
2174 // FIXME: Since we don't support block-flow on flexible boxes yet, disallow setting
2175 // of block-flow to anything other than TopToBottomWritingMode.
2176 // https://bugs.webkit.org/show_bug.cgi?id=46418 - Flexible box support.
2177 if (style->writingMode() != TopToBottomWritingMode && (style->display() == BOX || style->display() == INLINE_BOX))
2178 style->setWritingMode(TopToBottomWritingMode);
2180 if (isDisplayFlexibleBox(parentStyle->display())) {
2181 style->setFloating(NoFloat);
2182 style->setDisplay(equivalentBlockDisplay(style->display(), style->isFloating(), m_checker.strictParsing()));
2186 // Make sure our z-index value is only applied if the object is positioned.
2187 if (style->position() == StaticPosition && !isDisplayFlexibleBox(parentStyle->display()))
2188 style->setHasAutoZIndex();
2190 // Auto z-index becomes 0 for the root element and transparent objects. This prevents
2191 // cases where objects that should be blended as a single unit end up with a non-transparent
2192 // object wedged in between them. Auto z-index also becomes 0 for objects that specify transforms/masks/reflections.
2193 if (style->hasAutoZIndex() && ((e && e->document()->documentElement() == e)
2194 || style->opacity() < 1.0f
2195 || style->hasTransformRelatedProperty()
2197 || style->clipPath()
2198 || style->boxReflect()
2199 || style->hasFilter()
2200 || style->hasBlendMode()
2201 || style->position() == StickyPosition
2202 #ifdef FIXED_POSITION_CREATES_STACKING_CONTEXT
2203 || style->position() == FixedPosition
2205 || (style->position() == FixedPosition && e && e->document()->page() && e->document()->page()->settings()->fixedPositionCreatesStackingContext())
2207 #if ENABLE(ACCELERATED_OVERFLOW_SCROLLING)
2208 // Touch overflow scrolling creates a stacking context.
2209 || ((style->overflowX() != OHIDDEN || style->overflowY() != OHIDDEN) && style->useTouchOverflowScrolling())
2212 style->setZIndex(0);
2214 // Textarea considers overflow visible as auto.
2215 if (e && e->hasTagName(textareaTag)) {
2216 style->setOverflowX(style->overflowX() == OVISIBLE ? OAUTO : style->overflowX());
2217 style->setOverflowY(style->overflowY() == OVISIBLE ? OAUTO : style->overflowY());
2220 if (doesNotInheritTextDecoration(style, e))
2221 style->setTextDecorationsInEffect(style->textDecoration());
2223 style->addToTextDecorationsInEffect(style->textDecoration());
2225 // If either overflow value is not visible, change to auto.
2226 if (style->overflowX() == OMARQUEE && style->overflowY() != OMARQUEE)
2227 style->setOverflowY(OMARQUEE);
2228 else if (style->overflowY() == OMARQUEE && style->overflowX() != OMARQUEE)
2229 style->setOverflowX(OMARQUEE);
2230 else if (style->overflowX() == OVISIBLE && style->overflowY() != OVISIBLE) {
2231 // FIXME: Once we implement pagination controls, overflow-x should default to hidden
2232 // if overflow-y is set to -webkit-paged-x or -webkit-page-y. For now, we'll let it
2233 // default to auto so we can at least scroll through the pages.
2234 style->setOverflowX(OAUTO);
2235 } else if (style->overflowY() == OVISIBLE && style->overflowX() != OVISIBLE)
2236 style->setOverflowY(OAUTO);
2238 // Call setStylesForPaginationMode() if a pagination mode is set for any non-root elements. If these
2239 // styles are specified on a root element, then they will be incorporated in
2240 // StyleResolver::styleForDocument().
2241 if ((style->overflowY() == OPAGEDX || style->overflowY() == OPAGEDY) && !(e->hasTagName(htmlTag) || e->hasTagName(bodyTag)))
2242 setStylesForPaginationMode(WebCore::paginationModeForRenderStyle(style), style);
2244 // Table rows, sections and the table itself will support overflow:hidden and will ignore scroll/auto.
2245 // FIXME: Eventually table sections will support auto and scroll.
2246 if (style->display() == TABLE || style->display() == INLINE_TABLE
2247 || style->display() == TABLE_ROW_GROUP || style->display() == TABLE_ROW) {
2248 if (style->overflowX() != OVISIBLE && style->overflowX() != OHIDDEN)
2249 style->setOverflowX(OVISIBLE);
2250 if (style->overflowY() != OVISIBLE && style->overflowY() != OHIDDEN)
2251 style->setOverflowY(OVISIBLE);
2254 // Menulists should have visible overflow
2255 if (style->appearance() == MenulistPart) {
2256 style->setOverflowX(OVISIBLE);
2257 style->setOverflowY(OVISIBLE);
2260 // Cull out any useless layers and also repeat patterns into additional layers.
2261 style->adjustBackgroundLayers();
2262 style->adjustMaskLayers();
2264 // Do the same for animations and transitions.
2265 style->adjustAnimations();
2266 style->adjustTransitions();
2268 // Important: Intrinsic margins get added to controls before the theme has adjusted the style, since the theme will
2269 // alter fonts and heights/widths.
2270 if (e && e->isFormControlElement() && style->fontSize() >= 11) {
2271 // Don't apply intrinsic margins to image buttons. The designer knows how big the images are,
2272 // so we have to treat all image buttons as though they were explicitly sized.
2273 if (!e->hasTagName(inputTag) || !static_cast<HTMLInputElement*>(e)->isImageButton())
2274 addIntrinsicMargins(style);
2277 // Let the theme also have a crack at adjusting the style.
2278 if (style->hasAppearance())
2279 RenderTheme::defaultTheme()->adjustStyle(this, style, e, m_hasUAAppearance, m_borderData, m_backgroundData, m_backgroundColor);
2281 // If we have first-letter pseudo style, do not share this style.
2282 if (style->hasPseudoStyle(FIRST_LETTER))
2285 // FIXME: when dropping the -webkit prefix on transform-style, we should also have opacity < 1 cause flattening.
2286 if (style->preserves3D() && (style->overflowX() != OVISIBLE
2287 || style->overflowY() != OVISIBLE
2288 || style->hasFilter()))
2289 style->setTransformStyle3D(TransformStyle3DFlat);
2291 // Seamless iframes behave like blocks. Map their display to inline-block when marked inline.
2292 if (e && e->hasTagName(iframeTag) && style->display() == INLINE && static_cast<HTMLIFrameElement*>(e)->shouldDisplaySeamlessly())
2293 style->setDisplay(INLINE_BLOCK);
2296 if (e && e->isSVGElement()) {
2297 // Spec: http://www.w3.org/TR/SVG/masking.html#OverflowProperty
2298 if (style->overflowY() == OSCROLL)
2299 style->setOverflowY(OHIDDEN);
2300 else if (style->overflowY() == OAUTO)
2301 style->setOverflowY(OVISIBLE);
2303 if (style->overflowX() == OSCROLL)
2304 style->setOverflowX(OHIDDEN);
2305 else if (style->overflowX() == OAUTO)
2306 style->setOverflowX(OVISIBLE);
2308 // Only the root <svg> element in an SVG document fragment tree honors css position
2309 if (!(e->hasTagName(SVGNames::svgTag) && e->parentNode() && !e->parentNode()->isSVGElement()))
2310 style->setPosition(RenderStyle::initialPosition());
2312 // RenderSVGRoot handles zooming for the whole SVG subtree, so foreignObject content should
2313 // not be scaled again.
2314 if (e->hasTagName(SVGNames::foreignObjectTag))
2315 style->setEffectiveZoom(RenderStyle::initialZoom());
2320 bool StyleResolver::checkRegionStyle(Element* regionElement)
2322 // FIXME (BUG 72472): We don't add @-webkit-region rules of scoped style sheets for the moment,
2323 // so all region rules are global by default. Verify whether that can stand or needs changing.
2325 unsigned rulesSize = m_authorStyle->m_regionSelectorsAndRuleSets.size();
2326 for (unsigned i = 0; i < rulesSize; ++i) {
2327 ASSERT(m_authorStyle->m_regionSelectorsAndRuleSets.at(i).ruleSet.get());
2328 if (checkRegionSelector(m_authorStyle->m_regionSelectorsAndRuleSets.at(i).selector, regionElement))
2333 rulesSize = m_userStyle->m_regionSelectorsAndRuleSets.size();
2334 for (unsigned i = 0; i < rulesSize; ++i) {
2335 ASSERT(m_userStyle->m_regionSelectorsAndRuleSets.at(i).ruleSet.get());
2336 if (checkRegionSelector(m_userStyle->m_regionSelectorsAndRuleSets.at(i).selector, regionElement))
2344 void StyleResolver::updateFont()
2349 checkForTextSizeAdjust();
2350 checkForGenericFamilyChange(style(), m_parentStyle);
2351 checkForZoomChange(style(), m_parentStyle);
2352 m_style->font().update(m_fontSelector);
2353 m_fontDirty = false;
2356 void StyleResolver::cacheBorderAndBackground()
2358 m_hasUAAppearance = m_style->hasAppearance();
2359 if (m_hasUAAppearance) {
2360 m_borderData = m_style->border();
2361 m_backgroundData = *m_style->backgroundLayers();
2362 m_backgroundColor = m_style->backgroundColor();
2366 PassRefPtr<CSSRuleList> StyleResolver::styleRulesForElement(Element* e, unsigned rulesToInclude)
2368 return pseudoStyleRulesForElement(e, NOPSEUDO, rulesToInclude);
2371 PassRefPtr<CSSRuleList> StyleResolver::pseudoStyleRulesForElement(Element* e, PseudoId pseudoId, unsigned rulesToInclude)
2373 if (!e || !e->document()->haveStylesheetsLoaded())
2376 m_checker.setMode(SelectorChecker::CollectingRules);
2379 initForStyleResolve(e, 0, pseudoId);
2382 if (rulesToInclude & UAAndUserCSSRules) {
2383 // First we match rules from the user agent sheet.
2384 matchUARules(dummy);
2386 // Now we check user sheet rules.
2387 if (m_matchAuthorAndUserStyles)
2388 matchUserRules(dummy, rulesToInclude & EmptyCSSRules);
2391 if (m_matchAuthorAndUserStyles && (rulesToInclude & AuthorCSSRules)) {
2392 m_sameOriginOnly = !(rulesToInclude & CrossOriginCSSRules);
2394 // Check the rules in author sheets.
2395 matchAuthorRules(dummy, rulesToInclude & EmptyCSSRules);
2397 m_sameOriginOnly = false;
2400 m_checker.setMode(SelectorChecker::ResolvingStyle);
2402 return m_ruleList.release();
2405 inline bool StyleResolver::checkSelector(const RuleData& ruleData, const ContainerNode* scope)
2407 m_dynamicPseudo = NOPSEUDO;
2408 m_hasUnknownPseudoElements = false;
2410 if (ruleData.hasFastCheckableSelector()) {
2411 // We know this selector does not include any pseudo elements.
2412 if (m_pseudoStyle != NOPSEUDO)
2414 // We know a sufficiently simple single part selector matches simply because we found it from the rule hash.
2415 // This is limited to HTML only so we don't need to check the namespace.
2416 if (ruleData.hasRightmostSelectorMatchingHTMLBasedOnRuleHash() && m_element->isHTMLElement()) {
2417 if (!ruleData.hasMultipartSelector())
2419 } else if (!SelectorChecker::tagMatches(m_element, ruleData.selector()))
2421 if (!SelectorChecker::fastCheckRightmostAttributeSelector(m_element, ruleData.selector()))
2423 return m_checker.fastCheckSelector(ruleData.selector(), m_element);
2427 SelectorChecker::SelectorCheckingContext context(ruleData.selector(), m_element, SelectorChecker::VisitedMatchEnabled);
2428 context.elementStyle = style();
2429 context.elementParentStyle = m_parentNode ? m_parentNode->renderStyle() : 0;
2430 context.scope = scope;
2431 context.pseudoStyle = m_pseudoStyle;
2432 SelectorChecker::SelectorMatch match = m_checker.checkSelector(context, m_dynamicPseudo, m_hasUnknownPseudoElements);
2433 if (match != SelectorChecker::SelectorMatches)
2435 if (m_pseudoStyle != NOPSEUDO && m_pseudoStyle != m_dynamicPseudo)
2440 bool StyleResolver::checkRegionSelector(CSSSelector* regionSelector, Element* regionElement)
2442 if (!regionSelector || !regionElement)
2445 m_hasUnknownPseudoElements = false;
2446 m_pseudoStyle = NOPSEUDO;
2448 for (CSSSelector* s = regionSelector; s; s = CSSSelectorList::next(s))
2449 if (m_checker.checkSelector(s, regionElement))
2455 bool StyleResolver::determineStylesheetSelectorScopes(StyleSheetContents* stylesheet, HashSet<AtomicStringImpl*>& idScopes, HashSet<AtomicStringImpl*>& classScopes)
2457 ASSERT(!stylesheet->isLoading());
2459 const Vector<RefPtr<StyleRuleImport> >& importRules = stylesheet->importRules();
2460 for (unsigned i = 0; i < importRules.size(); ++i) {
2461 if (!importRules[i]->styleSheet())
2463 if (!determineStylesheetSelectorScopes(importRules[i]->styleSheet(), idScopes, classScopes))
2467 const Vector<RefPtr<StyleRuleBase> >& rules = stylesheet->childRules();
2468 for (unsigned i = 0; i < rules.size(); i++) {
2469 StyleRuleBase* rule = rules[i].get();
2470 if (rule->isStyleRule()) {
2471 StyleRule* styleRule = static_cast<StyleRule*>(rule);
2472 if (!SelectorChecker::determineSelectorScopes(styleRule->selectorList(), idScopes, classScopes))
2476 // FIXME: Media rules and maybe some others could be allowed.
2482 // -----------------------------------------------------------------
2484 static inline bool isSelectorMatchingHTMLBasedOnRuleHash(const CSSSelector* selector)
2486 const AtomicString& selectorNamespace = selector->tag().namespaceURI();
2487 if (selectorNamespace != starAtom && selectorNamespace != xhtmlNamespaceURI)
2489 if (selector->m_match == CSSSelector::None)
2491 if (selector->tag() != starAtom)
2493 if (SelectorChecker::isCommonPseudoClassSelector(selector))
2495 return selector->m_match == CSSSelector::Id || selector->m_match == CSSSelector::Class;
2498 static inline bool selectorListContainsUncommonAttributeSelector(const CSSSelector* selector)
2500 CSSSelectorList* selectorList = selector->selectorList();
2503 for (CSSSelector* subSelector = selectorList->first(); subSelector; subSelector = CSSSelectorList::next(subSelector)) {
2504 if (subSelector->isAttributeSelector())
2510 static inline bool isCommonAttributeSelectorAttribute(const QualifiedName& attribute)
2512 // These are explicitly tested for equality in canShareStyleWithElement.
2513 return attribute == typeAttr || attribute == readonlyAttr;
2516 static inline bool containsUncommonAttributeSelector(const CSSSelector* selector)
2518 for (; selector; selector = selector->tagHistory()) {
2519 // Allow certain common attributes (used in the default style) in the selectors that match the current element.
2520 if (selector->isAttributeSelector() && !isCommonAttributeSelectorAttribute(selector->attribute()))
2522 if (selectorListContainsUncommonAttributeSelector(selector))
2524 if (selector->relation() != CSSSelector::SubSelector) {
2525 selector = selector->tagHistory();
2530 for (; selector; selector = selector->tagHistory()) {
2531 if (selector->isAttributeSelector())
2533 if (selectorListContainsUncommonAttributeSelector(selector))
2539 RuleData::RuleData(StyleRule* rule, unsigned selectorIndex, unsigned position, bool hasDocumentSecurityOrigin, bool canUseFastCheckSelector, bool inRegionRule)
2541 , m_selectorIndex(selectorIndex)
2542 , m_position(position)
2543 , m_specificity(selector()->specificity())
2544 , m_hasFastCheckableSelector(canUseFastCheckSelector && SelectorChecker::isFastCheckableSelector(selector()))
2545 , m_hasMultipartSelector(!!selector()->tagHistory())
2546 , m_hasRightmostSelectorMatchingHTMLBasedOnRuleHash(isSelectorMatchingHTMLBasedOnRuleHash(selector()))
2547 , m_containsUncommonAttributeSelector(WebCore::containsUncommonAttributeSelector(selector()))
2548 , m_linkMatchType(SelectorChecker::determineLinkMatchType(selector()))
2549 , m_hasDocumentSecurityOrigin(hasDocumentSecurityOrigin)
2550 , m_isInRegionRule(inRegionRule)
2552 ASSERT(m_position == position);
2553 ASSERT(m_selectorIndex == selectorIndex);
2554 SelectorChecker::collectIdentifierHashes(selector(), m_descendantSelectorIdentifierHashes, maximumIdentifierCount);
2557 void RuleData::reportMemoryUsage(MemoryObjectInfo* memoryObjectInfo) const
2559 MemoryClassInfo info(memoryObjectInfo, this, WebCoreMemoryTypes::CSS);
2564 , m_autoShrinkToFitEnabled(true)
2568 static void reportAtomRuleMap(MemoryClassInfo* info, const RuleSet::AtomRuleMap& atomicRuleMap)
2570 info->addHashMap(atomicRuleMap);
2571 for (RuleSet::AtomRuleMap::const_iterator it = atomicRuleMap.begin(); it != atomicRuleMap.end(); ++it)
2572 info->addMember(*it->second);
2575 void RuleSet::reportMemoryUsage(MemoryObjectInfo* memoryObjectInfo) const
2577 MemoryClassInfo info(memoryObjectInfo, this, WebCoreMemoryTypes::CSS);
2578 reportAtomRuleMap(&info, m_idRules);
2579 reportAtomRuleMap(&info, m_classRules);
2580 reportAtomRuleMap(&info, m_tagRules);
2581 reportAtomRuleMap(&info, m_shadowPseudoElementRules);
2582 info.addMember(m_linkPseudoClassRules);
2583 info.addMember(m_focusPseudoClassRules);
2584 info.addMember(m_universalRules);
2585 info.addMember(m_pageRules);
2586 info.addMember(m_regionSelectorsAndRuleSets);
2589 void RuleSet::RuleSetSelectorPair::reportMemoryUsage(MemoryObjectInfo* memoryObjectInfo) const
2591 MemoryClassInfo info(memoryObjectInfo, this, WebCoreMemoryTypes::CSS);
2592 info.addMember(ruleSet);
2595 static inline void collectFeaturesFromSelector(StyleResolver::Features& features, const CSSSelector* selector)
2597 if (selector->m_match == CSSSelector::Id)
2598 features.idsInRules.add(selector->value().impl());
2599 if (selector->isAttributeSelector())
2600 features.attrsInRules.add(selector->attribute().localName().impl());
2601 switch (selector->pseudoType()) {
2602 case CSSSelector::PseudoFirstLine:
2603 features.usesFirstLineRules = true;
2605 case CSSSelector::PseudoBefore:
2606 case CSSSelector::PseudoAfter:
2607 features.usesBeforeAfterRules = true;
2614 static void collectFeaturesFromRuleData(StyleResolver::Features& features, const RuleData& ruleData)
2616 bool foundSiblingSelector = false;
2617 for (CSSSelector* selector = ruleData.selector(); selector; selector = selector->tagHistory()) {
2618 collectFeaturesFromSelector(features, selector);
2620 if (CSSSelectorList* selectorList = selector->selectorList()) {
2621 for (CSSSelector* subSelector = selectorList->first(); subSelector; subSelector = CSSSelectorList::next(subSelector)) {
2622 if (!foundSiblingSelector && selector->isSiblingSelector())
2623 foundSiblingSelector = true;
2624 collectFeaturesFromSelector(features, subSelector);
2626 } else if (!foundSiblingSelector && selector->isSiblingSelector())
2627 foundSiblingSelector = true;
2629 if (foundSiblingSelector)
2630 features.siblingRules.append(StyleResolver::RuleFeature(ruleData.rule(), ruleData.selectorIndex(), ruleData.hasDocumentSecurityOrigin()));
2631 if (ruleData.containsUncommonAttributeSelector())
2632 features.uncommonAttributeRules.append(StyleResolver::RuleFeature(ruleData.rule(), ruleData.selectorIndex(), ruleData.hasDocumentSecurityOrigin()));
2635 void RuleSet::addToRuleSet(AtomicStringImpl* key, AtomRuleMap& map, const RuleData& ruleData)
2639 OwnPtr<Vector<RuleData> >& rules = map.add(key, nullptr).iterator->second;
2641 rules = adoptPtr(new Vector<RuleData>);
2642 rules->append(ruleData);
2645 void RuleSet::addRule(StyleRule* rule, unsigned selectorIndex, bool hasDocumentSecurityOrigin, bool canUseFastCheckSelector, bool inRegionRule)
2647 RuleData ruleData(rule, selectorIndex, m_ruleCount++, hasDocumentSecurityOrigin, canUseFastCheckSelector, inRegionRule);
2648 collectFeaturesFromRuleData(m_features, ruleData);
2650 CSSSelector* selector = ruleData.selector();
2652 if (selector->m_match == CSSSelector::Id) {
2653 addToRuleSet(selector->value().impl(), m_idRules, ruleData);
2656 if (selector->m_match == CSSSelector::Class) {
2657 addToRuleSet(selector->value().impl(), m_classRules, ruleData);
2660 if (selector->isUnknownPseudoElement()) {
2661 addToRuleSet(selector->value().impl(), m_shadowPseudoElementRules, ruleData);
2664 if (SelectorChecker::isCommonPseudoClassSelector(selector)) {
2665 switch (selector->pseudoType()) {
2666 case CSSSelector::PseudoLink:
2667 case CSSSelector::PseudoVisited:
2668 case CSSSelector::PseudoAnyLink:
2669 m_linkPseudoClassRules.append(ruleData);
2671 case CSSSelector::PseudoFocus:
2672 m_focusPseudoClassRules.append(ruleData);
2675 ASSERT_NOT_REACHED();
2679 const AtomicString& localName = selector->tag().localName();
2680 if (localName != starAtom) {
2681 addToRuleSet(localName.impl(), m_tagRules, ruleData);
2684 m_universalRules.append(ruleData);
2687 void RuleSet::addPageRule(StyleRulePage* rule)
2689 m_pageRules.append(rule);
2692 void RuleSet::addRegionRule(StyleRuleRegion* regionRule, bool hasDocumentSecurityOrigin)
2694 OwnPtr<RuleSet> regionRuleSet = RuleSet::create();
2695 // The region rule set should take into account the position inside the parent rule set.
2696 // Otherwise, the rules inside region block might be incorrectly positioned before other similar rules from
2697 // the stylesheet that contains the region block.
2698 regionRuleSet->m_ruleCount = m_ruleCount;
2700 // Collect the region rules into a rule set
2701 const Vector<RefPtr<StyleRuleBase> >& childRules = regionRule->childRules();
2702 for (unsigned i = 0; i < childRules.size(); ++i) {
2703 StyleRuleBase* regionStylingRule = childRules[i].get();
2704 if (regionStylingRule->isStyleRule())
2705 regionRuleSet->addStyleRule(static_cast<StyleRule*>(regionStylingRule), hasDocumentSecurityOrigin, true, true);
2707 // Update the "global" rule count so that proper order is maintained
2708 m_ruleCount = regionRuleSet->m_ruleCount;
2710 m_regionSelectorsAndRuleSets.append(RuleSetSelectorPair(regionRule->selectorList().first(), regionRuleSet.release()));
2713 void RuleSet::addRulesFromSheet(StyleSheetContents* sheet, const MediaQueryEvaluator& medium, StyleResolver* resolver, const ContainerNode* scope)
2717 const Vector<RefPtr<StyleRuleImport> >& importRules = sheet->importRules();
2718 for (unsigned i = 0; i < importRules.size(); ++i) {
2719 StyleRuleImport* importRule = importRules[i].get();
2720 if (importRule->styleSheet() && (!importRule->mediaQueries() || medium.eval(importRule->mediaQueries(), resolver)))
2721 addRulesFromSheet(importRule->styleSheet(), medium, resolver, scope);
2723 bool hasDocumentSecurityOrigin = resolver && resolver->document()->securityOrigin()->canRequest(sheet->baseURL());
2725 const Vector<RefPtr<StyleRuleBase> >& rules = sheet->childRules();
2726 for (unsigned i = 0; i < rules.size(); ++i) {
2727 StyleRuleBase* rule = rules[i].get();
2729 ASSERT(!rule->isImportRule());
2730 if (rule->isStyleRule())
2731 addStyleRule(static_cast<StyleRule*>(rule), hasDocumentSecurityOrigin, !scope);
2732 else if (rule->isPageRule())
2733 addPageRule(static_cast<StyleRulePage*>(rule));
2734 else if (rule->isMediaRule()) {
2735 StyleRuleMedia* mediaRule = static_cast<StyleRuleMedia*>(rule);
2737 if ((!mediaRule->mediaQueries() || medium.eval(mediaRule->mediaQueries(), resolver))) {
2738 // Traverse child elements of the @media rule.
2739 const Vector<RefPtr<StyleRuleBase> >& childRules = mediaRule->childRules();
2740 for (unsigned j = 0; j < childRules.size(); ++j) {
2741 StyleRuleBase* childRule = childRules[j].get();
2742 if (childRule->isStyleRule())
2743 addStyleRule(static_cast<StyleRule*>(childRule), hasDocumentSecurityOrigin, !scope);
2744 else if (childRule->isPageRule())
2745 addPageRule(static_cast<StyleRulePage*>(childRule));
2746 else if (childRule->isFontFaceRule() && resolver) {
2747 // Add this font face to our set.
2748 // FIXME(BUG 72461): We don't add @font-face rules of scoped style sheets for the moment.
2751 const StyleRuleFontFace* fontFaceRule = static_cast<StyleRuleFontFace*>(childRule);
2752 resolver->fontSelector()->addFontFaceRule(fontFaceRule);
2753 resolver->invalidateMatchedPropertiesCache();
2754 } else if (childRule->isKeyframesRule() && resolver) {
2755 // Add this keyframe rule to our set.
2756 // FIXME(BUG 72462): We don't add @keyframe rules of scoped style sheets for the moment.
2759 resolver->addKeyframeStyle(static_cast<StyleRuleKeyframes*>(childRule));
2763 } else if (rule->isFontFaceRule() && resolver) {
2764 // Add this font face to our set.
2765 // FIXME(BUG 72461): We don't add @font-face rules of scoped style sheets for the moment.
2768 const StyleRuleFontFace* fontFaceRule = static_cast<StyleRuleFontFace*>(rule);
2769 resolver->fontSelector()->addFontFaceRule(fontFaceRule);
2770 resolver->invalidateMatchedPropertiesCache();
2771 } else if (rule->isKeyframesRule() && resolver) {
2772 // FIXME (BUG 72462): We don't add @keyframe rules of scoped style sheets for the moment.
2775 resolver->addKeyframeStyle(static_cast<StyleRuleKeyframes*>(rule));
2777 #if ENABLE(CSS_REGIONS)
2778 else if (rule->isRegionRule() && resolver) {
2779 // FIXME (BUG 72472): We don't add @-webkit-region rules of scoped style sheets for the moment.
2782 addRegionRule(static_cast<StyleRuleRegion*>(rule), hasDocumentSecurityOrigin);
2786 if (m_autoShrinkToFitEnabled)
2790 void RuleSet::addStyleRule(StyleRule* rule, bool hasDocumentSecurityOrigin, bool canUseFastCheckSelector, bool isInRegionRule)
2792 for (size_t selectorIndex = 0; selectorIndex != notFound; selectorIndex = rule->selectorList().indexOfNextSelectorAfter(selectorIndex))
2793 addRule(rule, selectorIndex, hasDocumentSecurityOrigin, canUseFastCheckSelector, isInRegionRule);
2796 static inline void shrinkMapVectorsToFit(RuleSet::AtomRuleMap& map)
2798 RuleSet::AtomRuleMap::iterator end = map.end();
2799 for (RuleSet::AtomRuleMap::iterator it = map.begin(); it != end; ++it)
2800 it->second->shrinkToFit();
2803 void RuleSet::shrinkToFit()
2805 shrinkMapVectorsToFit(m_idRules);
2806 shrinkMapVectorsToFit(m_classRules);
2807 shrinkMapVectorsToFit(m_tagRules);
2808 shrinkMapVectorsToFit(m_shadowPseudoElementRules);
2809 m_linkPseudoClassRules.shrinkToFit();
2810 m_focusPseudoClassRules.shrinkToFit();
2811 m_universalRules.shrinkToFit();
2812 m_pageRules.shrinkToFit();
2815 // -------------------------------------------------------------------------------------
2816 // this is mostly boring stuff on how to apply a certain rule to the renderstyle...
2818 Length StyleResolver::convertToIntLength(CSSPrimitiveValue* primitiveValue, RenderStyle* style, RenderStyle* rootStyle, double multiplier)
2820 return primitiveValue ? primitiveValue->convertToLength<FixedIntegerConversion | PercentConversion | FractionConversion | ViewportPercentageConversion>(style, rootStyle, multiplier) : Length(Undefined);
2823 Length StyleResolver::convertToFloatLength(CSSPrimitiveValue* primitiveValue, RenderStyle* style, RenderStyle* rootStyle, double multiplier)
2825 return primitiveValue ? primitiveValue->convertToLength<FixedFloatConversion | PercentConversion | FractionConversion | ViewportPercentageConversion>(style, rootStyle, multiplier) : Length(Undefined);
2828 template <StyleResolver::StyleApplicationPass pass>
2829 void StyleResolver::applyProperties(const StylePropertySet* properties, StyleRule* rule, bool isImportant, bool inheritedOnly, bool filterRegionProperties)
2831 ASSERT(!filterRegionProperties || m_regionForStyling);
2832 InspectorInstrumentationCookie cookie = InspectorInstrumentation::willProcessRule(document(), rule);
2834 unsigned propertyCount = properties->propertyCount();
2835 for (unsigned i = 0; i < propertyCount; ++i) {
2836 const CSSProperty& current = properties->propertyAt(i);
2837 if (isImportant != current.isImportant())
2839 if (inheritedOnly && !current.isInherited()) {
2840 // If the property value is explicitly inherited, we need to apply further non-inherited properties
2841 // as they might override the value inherited here. For this reason we don't allow declarations with
2842 // explicitly inherited properties to be cached.
2843 ASSERT(!current.value()->isInheritedValue());
2846 CSSPropertyID property = current.id();
2848 if (filterRegionProperties && !StyleResolver::isValidRegionStyleProperty(property))
2852 #if ENABLE(CSS_VARIABLES)
2853 case VariableDefinitions:
2854 COMPILE_ASSERT(CSSPropertyVariable < firstCSSProperty, CSS_variable_is_before_first_property);
2855 if (property == CSSPropertyVariable)
2856 applyProperty(current.id(), current.value());
2859 case HighPriorityProperties:
2860 COMPILE_ASSERT(firstCSSProperty == CSSPropertyColor, CSS_color_is_first_property);
2861 COMPILE_ASSERT(CSSPropertyZoom == CSSPropertyColor + 18, CSS_zoom_is_end_of_first_prop_range);
2862 COMPILE_ASSERT(CSSPropertyLineHeight == CSSPropertyZoom + 1, CSS_line_height_is_after_zoom);
2863 #if ENABLE(CSS_VARIABLES)
2864 if (property == CSSPropertyVariable)
2867 // give special priority to font-xxx, color properties, etc
2868 if (property < CSSPropertyLineHeight)
2869 applyProperty(current.id(), current.value());
2870 // we apply line-height later
2871 else if (property == CSSPropertyLineHeight)
2872 m_lineHeightValue = current.value();
2874 case LowPriorityProperties:
2875 if (property > CSSPropertyLineHeight)
2876 applyProperty(current.id(), current.value());
2879 InspectorInstrumentation::didProcessRule(cookie);
2882 template <StyleResolver::StyleApplicationPass pass>
2883 void StyleResolver::applyMatchedProperties(const MatchResult& matchResult, bool isImportant, int startIndex, int endIndex, bool inheritedOnly)
2885 if (startIndex == -1)
2888 if (m_style->insideLink() != NotInsideLink) {
2889 for (int i = startIndex; i <= endIndex; ++i) {
2890 const MatchedProperties& matchedProperties = matchResult.matchedProperties[i];
2891 unsigned linkMatchType = matchedProperties.linkMatchType;
2892 // FIXME: It would be nicer to pass these as arguments but that requires changes in many places.
2893 m_applyPropertyToRegularStyle = linkMatchType & SelectorChecker::MatchLink;
2894 m_applyPropertyToVisitedLinkStyle = linkMatchType & SelectorChecker::MatchVisited;
2896 applyProperties<pass>(matchedProperties.properties.get(), matchResult.matchedRules[i], isImportant, inheritedOnly, matchedProperties.isInRegionRule);
2898 m_applyPropertyToRegularStyle = true;
2899 m_applyPropertyToVisitedLinkStyle = false;
2902 for (int i = startIndex; i <= endIndex; ++i) {
2903 const MatchedProperties& matchedProperties = matchResult.matchedProperties[i];
2904 applyProperties<pass>(matchedProperties.properties.get(), matchResult.matchedRules[i], isImportant, inheritedOnly, matchedProperties.isInRegionRule);
2908 unsigned StyleResolver::computeMatchedPropertiesHash(const MatchedProperties* properties, unsigned size)
2911 return StringHasher::hashMemory(properties, sizeof(MatchedProperties) * size);
2914 bool operator==(const StyleResolver::MatchRanges& a, const StyleResolver::MatchRanges& b)
2916 return a.firstUARule == b.firstUARule
2917 && a.lastUARule == b.lastUARule
2918 && a.firstAuthorRule == b.firstAuthorRule
2919 && a.lastAuthorRule == b.lastAuthorRule
2920 && a.firstUserRule == b.firstUserRule
2921 && a.lastUserRule == b.lastUserRule;
2924 bool operator!=(const StyleResolver::MatchRanges& a, const StyleResolver::MatchRanges& b)
2929 bool operator==(const StyleResolver::MatchedProperties& a, const StyleResolver::MatchedProperties& b)
2931 return a.properties == b.properties && a.linkMatchType == b.linkMatchType;
2934 bool operator!=(const StyleResolver::MatchedProperties& a, const StyleResolver::MatchedProperties& b)
2939 const StyleResolver::MatchedPropertiesCacheItem* StyleResolver::findFromMatchedPropertiesCache(unsigned hash, const MatchResult& matchResult)
2943 MatchedPropertiesCache::iterator it = m_matchedPropertiesCache.find(hash);
2944 if (it == m_matchedPropertiesCache.end())
2946 MatchedPropertiesCacheItem& cacheItem = it->second;
2948 size_t size = matchResult.matchedProperties.size();
2949 if (size != cacheItem.matchedProperties.size())
2951 for (size_t i = 0; i < size; ++i) {
2952 if (matchResult.matchedProperties[i] != cacheItem.matchedProperties[i])
2955 if (cacheItem.ranges != matchResult.ranges)
2960 void StyleResolver::addToMatchedPropertiesCache(const RenderStyle* style, const RenderStyle* parentStyle, unsigned hash, const MatchResult& matchResult)
2962 static unsigned matchedDeclarationCacheAdditionsBetweenSweeps = 100;
2963 if (++m_matchedPropertiesCacheAdditionsSinceLastSweep >= matchedDeclarationCacheAdditionsBetweenSweeps) {
2964 sweepMatchedPropertiesCache();
2965 m_matchedPropertiesCacheAdditionsSinceLastSweep = 0;
2969 MatchedPropertiesCacheItem cacheItem;
2970 cacheItem.matchedProperties.append(matchResult.matchedProperties);
2971 cacheItem.ranges = matchResult.ranges;
2972 // Note that we don't cache the original RenderStyle instance. It may be further modified.
2973 // The RenderStyle in the cache is really just a holder for the substructures and never used as-is.
2974 cacheItem.renderStyle = RenderStyle::clone(style);
2975 cacheItem.parentRenderStyle = RenderStyle::clone(parentStyle);
2976 m_matchedPropertiesCache.add(hash, cacheItem);
2979 void StyleResolver::invalidateMatchedPropertiesCache()
2981 m_matchedPropertiesCache.clear();
2984 static bool isCacheableInMatchedPropertiesCache(const Element* element, const RenderStyle* style, const RenderStyle* parentStyle)
2986 // FIXME: CSSPropertyWebkitWritingMode modifies state when applying to document element. We can't skip the applying by caching.
2987 if (element == element->document()->documentElement() && element->document()->writingModeSetOnDocumentElement())
2989 if (style->unique() || (style->styleType() != NOPSEUDO && parentStyle->unique()))
2991 if (style->hasAppearance())
2993 if (style->zoom() != RenderStyle::initialZoom())
2995 // The cache assumes static knowledge about which properties are inherited.
2996 if (parentStyle->hasExplicitlyInheritedProperties())
3001 void StyleResolver::applyMatchedProperties(const MatchResult& matchResult, const Element* element)
3004 unsigned cacheHash = matchResult.isCacheable ? computeMatchedPropertiesHash(matchResult.matchedProperties.data(), matchResult.matchedProperties.size()) : 0;
3005 bool applyInheritedOnly = false;
3006 const MatchedPropertiesCacheItem* cacheItem = 0;
3007 if (cacheHash && (cacheItem = findFromMatchedPropertiesCache(cacheHash, matchResult))) {
3008 // We can build up the style by copying non-inherited properties from an earlier style object built using the same exact
3009 // style declarations. We then only need to apply the inherited properties, if any, as their values can depend on the
3010 // element context. This is fast and saves memory by reusing the style data structures.
3011 m_style->copyNonInheritedFrom(cacheItem->renderStyle.get());
3012 if (m_parentStyle->inheritedDataShared(cacheItem->parentRenderStyle.get()) && !isAtShadowBoundary(element)) {
3013 EInsideLink linkStatus = m_style->insideLink();
3014 // If the cache item parent style has identical inherited properties to the current parent style then the
3015 // resulting style will be identical too. We copy the inherited properties over from the cache and are done.
3016 m_style->inheritFrom(cacheItem->renderStyle.get());
3018 // Unfortunately the link status is treated like an inherited property. We need to explicitly restore it.
3019 m_style->setInsideLink(linkStatus);
3022 applyInheritedOnly = true;
3025 #if ENABLE(CSS_VARIABLES)
3026 // First apply all variable definitions, as they may be used during application of later properties.
3027 applyMatchedProperties<VariableDefinitions>(matchResult, false, 0, matchResult.matchedProperties.size() - 1, applyInheritedOnly);
3028 applyMatchedProperties<VariableDefinitions>(matchResult, true, matchResult.ranges.firstAuthorRule, matchResult.ranges.lastAuthorRule, applyInheritedOnly);
3029 applyMatchedProperties<VariableDefinitions>(matchResult, true, matchResult.ranges.firstUserRule, matchResult.ranges.lastUserRule, applyInheritedOnly);
3030 applyMatchedProperties<VariableDefinitions>(matchResult, true, matchResult.ranges.firstUARule, matchResult.ranges.lastUARule, applyInheritedOnly);
3033 // Now we have all of the matched rules in the appropriate order. Walk the rules and apply
3034 // high-priority properties first, i.e., those properties that other properties depend on.
3035 // The order is (1) high-priority not important, (2) high-priority important, (3) normal not important
3036 // and (4) normal important.
3037 m_lineHeightValue = 0;
3038 applyMatchedProperties<HighPriorityProperties>(matchResult, false, 0, matchResult.matchedProperties.size() - 1, applyInheritedOnly);
3039 applyMatchedProperties<HighPriorityProperties>(matchResult, true, matchResult.ranges.firstAuthorRule, matchResult.ranges.lastAuthorRule, applyInheritedOnly);
3040 applyMatchedProperties<HighPriorityProperties>(matchResult, true, matchResult.ranges.firstUserRule, matchResult.ranges.lastUserRule, applyInheritedOnly);
3041 applyMatchedProperties<HighPriorityProperties>(matchResult, true, matchResult.ranges.firstUARule, matchResult.ranges.lastUARule, applyInheritedOnly);
3043 if (cacheItem && cacheItem->renderStyle->effectiveZoom() != m_style->effectiveZoom()) {
3045 applyInheritedOnly = false;
3048 // If our font got dirtied, go ahead and update it now.
3051 // Line-height is set when we are sure we decided on the font-size.
3052 if (m_lineHeightValue)
3053 applyProperty(CSSPropertyLineHeight, m_lineHeightValue);
3055 // Many properties depend on the font. If it changes we just apply all properties.
3056 if (cacheItem && cacheItem->renderStyle->fontDescription() != m_style->fontDescription())
3057 applyInheritedOnly = false;
3059 // Now do the normal priority UA properties.
3060 applyMatchedProperties<LowPriorityProperties>(matchResult, false, matchResult.ranges.firstUARule, matchResult.ranges.lastUARule, applyInheritedOnly);
3062 // Cache our border and background so that we can examine them later.
3063 cacheBorderAndBackground();
3065 // Now do the author and user normal priority properties and all the !important properties.
3066 applyMatchedProperties<LowPriorityProperties>(matchResult, false, matchResult.ranges.lastUARule + 1, matchResult.matchedProperties.size() - 1, applyInheritedOnly);
3067 applyMatchedProperties<LowPriorityProperties>(matchResult, true, matchResult.ranges.firstAuthorRule, matchResult.ranges.lastAuthorRule, applyInheritedOnly);
3068 applyMatchedProperties<LowPriorityProperties>(matchResult, true, matchResult.ranges.firstUserRule, matchResult.ranges.lastUserRule, applyInheritedOnly);
3069 applyMatchedProperties<LowPriorityProperties>(matchResult, true, matchResult.ranges.firstUARule, matchResult.ranges.lastUARule, applyInheritedOnly);
3071 // Start loading resources referenced by this style.
3072 loadPendingResources();
3074 ASSERT(!m_fontDirty);
3076 if (cacheItem || !cacheHash)
3078 if (!isCacheableInMatchedPropertiesCache(m_element, m_style.get(), m_parentStyle))
3080 addToMatchedPropertiesCache(m_style.get(), m_parentStyle, cacheHash, matchResult);
3083 static inline bool comparePageRules(const StyleRulePage* r1, const StyleRulePage* r2)
3085 return r1->selector()->specificity() < r2->selector()->specificity();
3088 void StyleResolver::matchPageRules(MatchResult& result, RuleSet* rules, bool isLeftPage, bool isFirstPage, const String& pageName)
3093 Vector<StyleRulePage*> matchedPageRules;
3094 matchPageRulesForList(matchedPageRules, rules->pageRules(), isLeftPage, isFirstPage, pageName);
3095 if (matchedPageRules.isEmpty())
3098 std::stable_sort(matchedPageRules.begin(), matchedPageRules.end(), comparePageRules);
3100 for (unsigned i = 0; i < matchedPageRules.size(); i++)
3101 addMatchedProperties(result, matchedPageRules[i]->properties());
3104 void StyleResolver::matchPageRulesForList(Vector<StyleRulePage*>& matchedRules, const Vector<StyleRulePage*>& rules, bool isLeftPage, bool isFirstPage, const String& pageName)
3106 unsigned size = rules.size();
3107 for (unsigned i = 0; i < size; ++i) {
3108 StyleRulePage* rule = rules[i];
3109 const AtomicString& selectorLocalName = rule->selector()->tag().localName();
3110 if (selectorLocalName != starAtom && selectorLocalName != pageName)
3112 CSSSelector::PseudoType pseudoType = rule->selector()->pseudoType();
3113 if ((pseudoType == CSSSelector::PseudoLeftPage && !isLeftPage)
3114 || (pseudoType == CSSSelector::PseudoRightPage && isLeftPage)
3115 || (pseudoType == CSSSelector::PseudoFirstPage && !isFirstPage))
3118 // If the rule has no properties to apply, then ignore it.
3119 const StylePropertySet* properties = rule->properties();
3120 if (!properties || properties->isEmpty())
3123 // Add this rule to our list of matched rules.
3124 matchedRules.append(rule);
3128 bool StyleResolver::isLeftPage(int pageIndex) const
3130 bool isFirstPageLeft = false;
3131 if (!m_rootElementStyle->isLeftToRightDirection())
3132 isFirstPageLeft = true;
3134 return (pageIndex + (isFirstPageLeft ? 1 : 0)) % 2;
3137 bool StyleResolver::isFirstPage(int pageIndex) const
3139 // FIXME: In case of forced left/right page, page at index 1 (not 0) can be the first page.
3140 return (!pageIndex);
3143 String StyleResolver::pageName(int /* pageIndex */) const
3145 // FIXME: Implement page index to page name mapping.
3149 template <class ListType>
3150 static void collectCSSOMWrappers(HashMap<StyleRule*, RefPtr<CSSStyleRule> >& wrapperMap, ListType* listType)
3154 unsigned size = listType->length();
3155 for (unsigned i = 0; i < size; ++i) {
3156 CSSRule* cssRule = listType->item(i);
3157 if (cssRule->isImportRule())
3158 collectCSSOMWrappers(wrapperMap, static_cast<CSSImportRule*>(cssRule)->styleSheet());
3159 else if (cssRule->isMediaRule())
3160 collectCSSOMWrappers(wrapperMap, static_cast<CSSMediaRule*>(cssRule));
3161 #if ENABLE(CSS_REGIONS)
3162 else if (cssRule->isRegionRule())
3163 collectCSSOMWrappers(wrapperMap, static_cast<WebKitCSSRegionRule*>(cssRule));
3165 else if (cssRule->isStyleRule()) {
3166 CSSStyleRule* cssStyleRule = static_cast<CSSStyleRule*>(cssRule);
3167 wrapperMap.add(cssStyleRule->styleRule(), cssStyleRule);
3172 static void collectCSSOMWrappers(HashMap<StyleRule*, RefPtr<CSSStyleRule> >& wrapperMap, HashSet<RefPtr<CSSStyleSheet> >& sheetWrapperSet, StyleSheetContents* styleSheet)
3176 RefPtr<CSSStyleSheet> styleSheetWrapper = CSSStyleSheet::create(styleSheet);
3177 sheetWrapperSet.add(styleSheetWrapper);
3178 collectCSSOMWrappers(wrapperMap, styleSheetWrapper.get());
3181 static void collectCSSOMWrappers(HashMap<StyleRule*, RefPtr<CSSStyleRule> >& wrapperMap, DocumentStyleSheetCollection* styleSheetCollection)
3183 const Vector<RefPtr<StyleSheet> >& styleSheets = styleSheetCollection->authorStyleSheets();
3184 for (unsigned i = 0; i < styleSheets.size(); ++i) {
3185 StyleSheet* styleSheet = styleSheets[i].get();
3186 if (!styleSheet->isCSSStyleSheet())
3188 collectCSSOMWrappers(wrapperMap, static_cast<CSSStyleSheet*>(styleSheet));
3190 collectCSSOMWrappers(wrapperMap, styleSheetCollection->pageUserSheet());
3192 const Vector<RefPtr<CSSStyleSheet> >* pageGroupUserSheets = styleSheetCollection->pageGroupUserSheets();
3193 if (pageGroupUserSheets) {
3194 for (size_t i = 0, size = pageGroupUserSheets->size(); i < size; ++i)
3195 collectCSSOMWrappers(wrapperMap, pageGroupUserSheets->at(i).get());
3199 const Vector<RefPtr<CSSStyleSheet> >* documentUserSheets = styleSheetCollection->documentUserSheets();
3200 if (documentUserSheets) {
3201 for (size_t i = 0, size = documentUserSheets->size(); i < size; ++i)
3202 collectCSSOMWrappers(wrapperMap, documentUserSheets->at(i).get());
3207 CSSStyleRule* StyleResolver::ensureFullCSSOMWrapperForInspector(StyleRule* rule)
3209 if (m_styleRuleToCSSOMWrapperMap.isEmpty()) {
3210 collectCSSOMWrappers(m_styleRuleToCSSOMWrapperMap, m_styleSheetCSSOMWrapperSet, simpleDefaultStyleSheet);
3211 collectCSSOMWrappers(m_styleRuleToCSSOMWrapperMap, m_styleSheetCSSOMWrapperSet, defaultStyleSheet);
3212 collectCSSOMWrappers(m_styleRuleToCSSOMWrapperMap, m_styleSheetCSSOMWrapperSet, quirksStyleSheet);
3213 collectCSSOMWrappers(m_styleRuleToCSSOMWrapperMap, m_styleSheetCSSOMWrapperSet, svgStyleSheet);
3214 collectCSSOMWrappers(m_styleRuleToCSSOMWrapperMap, m_styleSheetCSSOMWrapperSet, mathMLStyleSheet);
3215 collectCSSOMWrappers(m_styleRuleToCSSOMWrapperMap, m_styleSheetCSSOMWrapperSet, mediaControlsStyleSheet);
3216 collectCSSOMWrappers(m_styleRuleToCSSOMWrapperMap, m_styleSheetCSSOMWrapperSet, fullscreenStyleSheet);
3218 collectCSSOMWrappers(m_styleRuleToCSSOMWrapperMap, document()->styleSheetCollection());
3220 return m_styleRuleToCSSOMWrapperMap.get(rule).get();
3223 void StyleResolver::applyPropertyToStyle(CSSPropertyID id, CSSValue* value, RenderStyle* style)
3226 initForStyleResolve(0, style);
3228 applyPropertyToCurrentStyle(id, value);
3231 void StyleResolver::applyPropertyToCurrentStyle(CSSPropertyID id, CSSValue* value)
3234 applyProperty(id, value);
3237 inline bool isValidVisitedLinkProperty(CSSPropertyID id)
3240 case CSSPropertyBackgroundColor:
3241 case CSSPropertyBorderLeftColor:
3242 case CSSPropertyBorderRightColor:
3243 case CSSPropertyBorderTopColor:
3244 case CSSPropertyBorderBottomColor:
3245 case CSSPropertyColor:
3246 case CSSPropertyOutlineColor:
3247 case CSSPropertyWebkitColumnRuleColor:
3248 case CSSPropertyWebkitTextEmphasisColor:
3249 case CSSPropertyWebkitTextFillColor:
3250 case CSSPropertyWebkitTextStrokeColor:
3251 // Also allow shorthands so that inherit/initial still work.
3252 case CSSPropertyBackground:
3253 case CSSPropertyBorderLeft:
3254 case CSSPropertyBorderRight:
3255 case CSSPropertyBorderTop:
3256 case CSSPropertyBorderBottom:
3257 case CSSPropertyOutline:
3258 case CSSPropertyWebkitColumnRule:
3260 case CSSPropertyFill:
3261 case CSSPropertyStroke:
3271 // http://dev.w3.org/csswg/css3-regions/#the-at-region-style-rule
3272 // FIXME: add incremental support for other region styling properties.
3273 inline bool StyleResolver::isValidRegionStyleProperty(CSSPropertyID id)
3276 case CSSPropertyBackgroundColor:
3277 case CSSPropertyColor:
3286 // SVG handles zooming in a different way compared to CSS. The whole document is scaled instead
3287 // of each individual length value in the render style / tree. CSSPrimitiveValue::computeLength*()
3288 // multiplies each resolved length with the zoom multiplier - so for SVG we need to disable that.
3289 // Though all CSS values that can be applied to outermost <svg> elements (width/height/border/padding...)
3290 // need to respect the scaling. RenderBox (the parent class of RenderSVGRoot) grabs values like
3291 // width/height/border/padding/... from the RenderStyle -> for SVG these values would never scale,
3292 // if we'd pass a 1.0 zoom factor everyhwere. So we only pass a zoom factor of 1.0 for specific
3293 // properties that are NOT allowed to scale within a zoomed SVG document (letter/word-spacing/font-size).
3294 bool StyleResolver::useSVGZoomRules()
3296 return m_element && m_element->isSVGElement();
3299 static bool createGridTrackBreadth(CSSPrimitiveValue* primitiveValue, StyleResolver* selector, Length& length)
3301 Length workingLength = primitiveValue->convertToLength<FixedIntegerConversion | PercentConversion | ViewportPercentageConversion | AutoConversion>(selector->style(), selector->rootElementStyle(), selector->style()->effectiveZoom());
3302 if (workingLength.isUndefined())
3305 if (primitiveValue->isLength())
3306 workingLength.setQuirk(primitiveValue->isQuirkValue());
3308 length = workingLength;
3312 static bool createGridTrackList(CSSValue* value, Vector<Length>& lengths, StyleResolver* selector)
3315 if (value->isPrimitiveValue()) {
3316 CSSPrimitiveValue* primitiveValue = static_cast<CSSPrimitiveValue*>(value);
3317 if (primitiveValue->getIdent() == CSSValueNone) {
3318 lengths.append(Length(Undefined));
3324 if (value->isValueList()) {
3325 for (CSSValueListIterator i = value; i.hasMore(); i.advance()) {
3326 CSSValue* currValue = i.value();
3327 if (!currValue->isPrimitiveValue())
3331 if (!createGridTrackBreadth(static_cast<CSSPrimitiveValue*>(currValue), selector, length))
3334 lengths.append(length);
3343 static bool createGridPosition(CSSValue* value, Length& position)
3345 // For now, we only accept: <integer> | 'auto'
3346 if (!value->isPrimitiveValue())
3349 CSSPrimitiveValue* primitiveValue = static_cast<CSSPrimitiveValue*>(value);
3350 if (primitiveValue->getIdent() == CSSValueAuto)
3353 ASSERT(primitiveValue->isNumber());
3354 position.setValue(primitiveValue->getIntValue());
3358 #if ENABLE(CSS_VARIABLES)
3359 static bool hasVariableReference(CSSValue* value)
3361 if (value->isPrimitiveValue()) {
3362 CSSPrimitiveValue* primitiveValue = static_cast<CSSPrimitiveValue*>(value);
3363 return primitiveValue->hasVariableReference();
3366 if (value->isCalculationValue())
3367 return static_cast<CSSCalcValue*>(value)->hasVariableReference();
3369 for (CSSValueListIterator i = value; i.hasMore(); i.advance()) {
3370 if (hasVariableReference(i.value()))
3377 void StyleResolver::resolveVariables(CSSPropertyID id, CSSValue* value, Vector<std::pair<CSSPropertyID, String> >& knownExpressions)
3379 std::pair<CSSPropertyID, String> expression(id, value->serializeResolvingVariables(*style()->variables()));
3381 if (knownExpressions.contains(expression))
3382 return; // cycle detected.
3384 knownExpressions.append(expression);
3386 // FIXME: It would be faster not to re-parse from strings, but for now CSS property validation lives inside the parser so we do it there.
3387 RefPtr<StylePropertySet> resultSet = StylePropertySet::create();
3388 if (!CSSParser::parseValue(resultSet.get(), id, expression.second, false, document()))
3389 return; // expression failed to parse.
3391 for (unsigned i = 0; i < resultSet->propertyCount(); i++) {
3392 const CSSProperty& property = resultSet->propertyAt(i);
3393 if (property.id() != CSSPropertyVariable && hasVariableReference(property.value()))
3394 resolveVariables(property.id(), property.value(), knownExpressions);
3396 applyProperty(property.id(), property.value());
3401 void StyleResolver::applyProperty(CSSPropertyID id, CSSValue* value)
3403 #if ENABLE(CSS_VARIABLES)
3404 if (id != CSSPropertyVariable && hasVariableReference(value)) {
3405 Vector<std::pair<CSSPropertyID, String> > knownExpressions;
3406 resolveVariables(id, value, knownExpressions);
3411 bool isInherit = m_parentNode && value->isInheritedValue();
3412 bool isInitial = value->isInitialValue() || (!m_parentNode && value->isInheritedValue());
3414 ASSERT(!isInherit || !isInitial); // isInherit -> !isInitial && isInitial -> !isInherit
3416 if (!applyPropertyToRegularStyle() && (!applyPropertyToVisitedLinkStyle() || !isValidVisitedLinkProperty(id))) {
3417 // Limit the properties that can be applied to only the ones honored by :visited.
3421 if (isInherit && m_parentStyle && !m_parentStyle->hasExplicitlyInheritedProperties() && !CSSProperty::isInheritedProperty(id))