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 "FontFeatureValue.h"
64 #include "FontValue.h"
66 #include "FrameSelection.h"
67 #include "FrameView.h"
68 #include "HTMLDocument.h"
69 #include "HTMLIFrameElement.h"
70 #include "HTMLInputElement.h"
71 #include "HTMLNames.h"
72 #include "HTMLOptionElement.h"
73 #include "HTMLProgressElement.h"
74 #include "HTMLStyleElement.h"
75 #include "HTMLTextAreaElement.h"
76 #include "InspectorInstrumentation.h"
77 #include "KeyframeList.h"
79 #include "LocaleToScriptMapping.h"
80 #include "MathMLNames.h"
81 #include "Matrix3DTransformOperation.h"
82 #include "MatrixTransformOperation.h"
83 #include "MediaList.h"
84 #include "MediaQueryEvaluator.h"
85 #include "NodeRenderStyle.h"
86 #include "NodeRenderingContext.h"
88 #include "PageGroup.h"
90 #include "PerspectiveTransformOperation.h"
91 #include "QuotesData.h"
93 #include "RenderRegion.h"
94 #include "RenderScrollbar.h"
95 #include "RenderScrollbarTheme.h"
96 #include "RenderStyleConstants.h"
97 #include "RenderTheme.h"
98 #include "RotateTransformOperation.h"
99 #include "SVGDocumentExtensions.h"
100 #include "SVGFontFaceElement.h"
101 #include "ScaleTransformOperation.h"
102 #include "SecurityOrigin.h"
103 #include "Settings.h"
104 #include "ShadowData.h"
105 #include "ShadowRoot.h"
106 #include "ShadowValue.h"
107 #include "SkewTransformOperation.h"
108 #include "StyleBuilder.h"
109 #include "StyleCachedImage.h"
110 #include "StyleGeneratedImage.h"
111 #include "StylePendingImage.h"
112 #include "StyleRule.h"
113 #include "StyleRuleImport.h"
114 #include "StyleSheetContents.h"
115 #include "StyleSheetList.h"
117 #include "TransformationMatrix.h"
118 #include "TranslateTransformOperation.h"
119 #include "UserAgentStyleSheets.h"
120 #include "WebKitCSSKeyframeRule.h"
121 #include "WebKitCSSKeyframesRule.h"
122 #include "WebKitCSSRegionRule.h"
123 #include "WebKitCSSTransformValue.h"
124 #include "WebKitFontFamilyNames.h"
125 #include "XMLNames.h"
126 #include <wtf/StdLibExtras.h>
127 #include <wtf/Vector.h>
129 #if ENABLE(CSS_FILTERS)
130 #include "FilterOperation.h"
131 #include "WebKitCSSFilterValue.h"
134 #if ENABLE(DASHBOARD_SUPPORT)
135 #include "DashboardRegion.h"
139 #include "CachedSVGDocument.h"
140 #include "SVGDocument.h"
141 #include "SVGElement.h"
142 #include "SVGNames.h"
143 #include "SVGURIReference.h"
144 #include "WebKitCSSSVGDocumentValue.h"
147 #if ENABLE(CSS_SHADERS)
148 #include "CustomFilterNumberParameter.h"
149 #include "CustomFilterOperation.h"
150 #include "CustomFilterParameter.h"
151 #include "StyleCachedShader.h"
152 #include "StyleCustomFilterProgram.h"
153 #include "StylePendingShader.h"
154 #include "StyleShader.h"
155 #include "WebKitCSSShaderValue.h"
158 #if ENABLE(CSS_IMAGE_SET)
159 #include "CSSImageSetValue.h"
160 #include "StyleCachedImageSet.h"
163 #if PLATFORM(BLACKBERRY)
164 #define FIXED_POSITION_CREATES_STACKING_CONTEXT 1
171 using namespace HTMLNames;
173 #define HANDLE_INHERIT(prop, Prop) \
175 m_style->set##Prop(m_parentStyle->prop()); \
179 #define HANDLE_INHERIT_AND_INITIAL(prop, Prop) \
180 HANDLE_INHERIT(prop, Prop) \
182 m_style->set##Prop(RenderStyle::initial##Prop()); \
186 #define HANDLE_INHERIT_AND_INITIAL_WITH_VALUE(prop, Prop, Value) \
187 HANDLE_INHERIT(prop, Prop) \
189 m_style->set##Prop(RenderStyle::initial##Value());\
193 #define HANDLE_INHERIT_AND_INITIAL_AND_PRIMITIVE(prop, Prop) \
194 HANDLE_INHERIT_AND_INITIAL(prop, Prop) \
195 if (primitiveValue) \
196 m_style->set##Prop(*primitiveValue);
200 RuleData(StyleRule*, CSSSelector*, unsigned position, bool hasDocumentSecurityOrigin, bool canUseFastCheckSelector, bool inRegionRule);
202 unsigned position() const { return m_position; }
203 StyleRule* rule() const { return m_rule; }
204 CSSSelector* selector() const { return m_selector; }
206 bool hasFastCheckableSelector() const { return m_hasFastCheckableSelector; }
207 bool hasMultipartSelector() const { return m_hasMultipartSelector; }
208 bool hasRightmostSelectorMatchingHTMLBasedOnRuleHash() const { return m_hasRightmostSelectorMatchingHTMLBasedOnRuleHash; }
209 bool containsUncommonAttributeSelector() const { return m_containsUncommonAttributeSelector; }
210 unsigned specificity() const { return m_specificity; }
211 unsigned linkMatchType() const { return m_linkMatchType; }
212 bool hasDocumentSecurityOrigin() const { return m_hasDocumentSecurityOrigin; }
213 bool isInRegionRule() const { return m_isInRegionRule; }
215 // Try to balance between memory usage (there can be lots of RuleData objects) and good filtering performance.
216 static const unsigned maximumIdentifierCount = 4;
217 const unsigned* descendantSelectorIdentifierHashes() const { return m_descendantSelectorIdentifierHashes; }
221 CSSSelector* m_selector;
222 unsigned m_specificity;
223 // This number was picked fairly arbitrarily. We can probably lower it if we need to.
224 // Some simple testing showed <100,000 RuleData's on large sites.
225 unsigned m_position : 24;
226 unsigned m_hasFastCheckableSelector : 1;
227 unsigned m_hasMultipartSelector : 1;
228 unsigned m_hasRightmostSelectorMatchingHTMLBasedOnRuleHash : 1;
229 unsigned m_containsUncommonAttributeSelector : 1;
230 unsigned m_linkMatchType : 2; // SelectorChecker::LinkMatchMask
231 unsigned m_hasDocumentSecurityOrigin : 1;
232 unsigned m_isInRegionRule : 1;
233 // Use plain array instead of a Vector to minimize memory overhead.
234 unsigned m_descendantSelectorIdentifierHashes[maximumIdentifierCount];
237 struct SameSizeAsRuleData {
245 COMPILE_ASSERT(sizeof(RuleData) == sizeof(SameSizeAsRuleData), RuleData_should_stay_small);
248 WTF_MAKE_NONCOPYABLE(RuleSet);
250 static PassOwnPtr<RuleSet> create() { return adoptPtr(new RuleSet); }
252 typedef HashMap<AtomicStringImpl*, OwnPtr<Vector<RuleData> > > AtomRuleMap;
254 void addRulesFromSheet(StyleSheetContents*, const MediaQueryEvaluator&, StyleResolver* = 0, const ContainerNode* = 0);
256 void addStyleRule(StyleRule*, bool hasDocumentSecurityOrigin, bool canUseFastCheckSelector, bool isInRegionRule = false);
257 void addRule(StyleRule*, CSSSelector*, bool hasDocumentSecurityOrigin, bool canUseFastCheckSelector, bool isInRegionRule = false);
258 void addPageRule(StyleRulePage*);
259 void addToRuleSet(AtomicStringImpl* key, AtomRuleMap&, const RuleData&);
260 void addRegionRule(StyleRuleRegion*, bool hasDocumentSecurityOrigin);
262 void disableAutoShrinkToFit() { m_autoShrinkToFitEnabled = false; }
264 const StyleResolver::Features& features() const { return m_features; }
266 const Vector<RuleData>* idRules(AtomicStringImpl* key) const { return m_idRules.get(key); }
267 const Vector<RuleData>* classRules(AtomicStringImpl* key) const { return m_classRules.get(key); }
268 const Vector<RuleData>* tagRules(AtomicStringImpl* key) const { return m_tagRules.get(key); }
269 const Vector<RuleData>* shadowPseudoElementRules(AtomicStringImpl* key) const { return m_shadowPseudoElementRules.get(key); }
270 const Vector<RuleData>* linkPseudoClassRules() const { return &m_linkPseudoClassRules; }
271 const Vector<RuleData>* focusPseudoClassRules() const { return &m_focusPseudoClassRules; }
272 const Vector<RuleData>* universalRules() const { return &m_universalRules; }
273 const Vector<StyleRulePage*>& pageRules() const { return m_pageRules; }
278 AtomRuleMap m_idRules;
279 AtomRuleMap m_classRules;
280 AtomRuleMap m_tagRules;
281 AtomRuleMap m_shadowPseudoElementRules;
282 Vector<RuleData> m_linkPseudoClassRules;
283 Vector<RuleData> m_focusPseudoClassRules;
284 Vector<RuleData> m_universalRules;
285 Vector<StyleRulePage*> m_pageRules;
286 unsigned m_ruleCount;
287 bool m_autoShrinkToFitEnabled;
288 StyleResolver::Features m_features;
290 struct RuleSetSelectorPair {
291 RuleSetSelectorPair(CSSSelector* selector, PassOwnPtr<RuleSet> ruleSet) : selector(selector), ruleSet(ruleSet) { }
292 RuleSetSelectorPair(const RuleSetSelectorPair& rs) : selector(rs.selector), ruleSet(const_cast<RuleSetSelectorPair*>(&rs)->ruleSet.release()) { }
293 CSSSelector* selector;
294 OwnPtr<RuleSet> ruleSet;
297 Vector<RuleSetSelectorPair> m_regionSelectorsAndRuleSets;
300 static RuleSet* defaultStyle;
301 static RuleSet* defaultQuirksStyle;
302 static RuleSet* defaultPrintStyle;
303 static RuleSet* defaultViewSourceStyle;
304 static StyleSheetContents* simpleDefaultStyleSheet;
305 static StyleSheetContents* defaultStyleSheet;
306 static StyleSheetContents* quirksStyleSheet;
307 static StyleSheetContents* svgStyleSheet;
308 static StyleSheetContents* mathMLStyleSheet;
309 static StyleSheetContents* mediaControlsStyleSheet;
310 static StyleSheetContents* fullscreenStyleSheet;
312 RenderStyle* StyleResolver::s_styleNotYetAvailable;
314 static void loadFullDefaultStyle();
315 static void loadSimpleDefaultStyle();
316 template <class ListType>
317 static void collectCSSOMWrappers(HashMap<StyleRule*, RefPtr<CSSStyleRule> >&, ListType*);
319 // FIXME: It would be nice to use some mechanism that guarantees this is in sync with the real UA stylesheet.
320 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}";
322 static inline bool elementCanUseSimpleDefaultStyle(Element* e)
324 return e->hasTagName(htmlTag) || e->hasTagName(headTag) || e->hasTagName(bodyTag) || e->hasTagName(divTag) || e->hasTagName(spanTag) || e->hasTagName(brTag) || e->hasTagName(aTag);
327 static const MediaQueryEvaluator& screenEval()
329 DEFINE_STATIC_LOCAL(const MediaQueryEvaluator, staticScreenEval, ("screen"));
330 return staticScreenEval;
333 static const MediaQueryEvaluator& printEval()
335 DEFINE_STATIC_LOCAL(const MediaQueryEvaluator, staticPrintEval, ("print"));
336 return staticPrintEval;
339 static StylePropertySet* leftToRightDeclaration()
341 DEFINE_STATIC_LOCAL(RefPtr<StylePropertySet>, leftToRightDecl, (StylePropertySet::create()));
342 if (leftToRightDecl->isEmpty())
343 leftToRightDecl->setProperty(CSSPropertyDirection, CSSValueLtr);
344 return leftToRightDecl.get();
347 static StylePropertySet* rightToLeftDeclaration()
349 DEFINE_STATIC_LOCAL(RefPtr<StylePropertySet>, rightToLeftDecl, (StylePropertySet::create()));
350 if (rightToLeftDecl->isEmpty())
351 rightToLeftDecl->setProperty(CSSPropertyDirection, CSSValueRtl);
352 return rightToLeftDecl.get();
355 StyleResolver::StyleResolver(Document* document, bool matchAuthorAndUserStyles)
356 : m_hasUAAppearance(false)
357 , m_backgroundData(BackgroundFillLayer)
358 , m_matchedPropertiesCacheAdditionsSinceLastSweep(0)
359 , m_checker(document, !document->inQuirksMode())
361 , m_rootElementStyle(0)
364 , m_regionForStyling(0)
365 , m_elementLinkState(NotInsideLink)
367 , m_lineHeightValue(0)
369 , m_matchAuthorAndUserStyles(matchAuthorAndUserStyles)
370 , m_sameOriginOnly(false)
371 , m_fontSelector(CSSFontSelector::create(document))
372 , m_applyPropertyToRegularStyle(true)
373 , m_applyPropertyToVisitedLinkStyle(false)
374 , m_styleBuilder(StyleBuilder::sharedStyleBuilder())
375 #if ENABLE(CSS_SHADERS)
376 , m_hasPendingShaders(false)
378 #if ENABLE(STYLE_SCOPED)
379 , m_scopeStackParent(0)
380 , m_scopeStackParentBoundsIndex(0)
384 Element* root = document->documentElement();
387 if (!root || elementCanUseSimpleDefaultStyle(root))
388 loadSimpleDefaultStyle();
390 loadFullDefaultStyle();
393 // construct document root element default style. this is needed
394 // to evaluate media queries that contain relative constraints, like "screen and (max-width: 10em)"
395 // This is here instead of constructor, because when constructor is run,
396 // document doesn't have documentElement
397 // NOTE: this assumes that element that gets passed to styleForElement -call
398 // is always from the document that owns the style selector
399 FrameView* view = document->view();
401 m_medium = adoptPtr(new MediaQueryEvaluator(view->mediaType()));
403 m_medium = adoptPtr(new MediaQueryEvaluator("all"));
406 m_rootDefaultStyle = styleForElement(root, 0, DisallowStyleSharing, MatchOnlyUserAgentRules);
408 if (m_rootDefaultStyle && view)
409 m_medium = adoptPtr(new MediaQueryEvaluator(view->mediaType(), view->frame(), m_rootDefaultStyle.get()));
411 m_authorStyle = RuleSet::create();
412 // Adding rules from multiple sheets, shrink at the end.
413 // Adding global rules from multiple sheets, shrink at the end.
414 // Note that there usually is only 1 sheet for scoped rules, so auto-shrink-to-fit is fine.
415 m_authorStyle->disableAutoShrinkToFit();
417 // FIXME: This sucks! The user sheet is reparsed every time!
418 OwnPtr<RuleSet> tempUserStyle = RuleSet::create();
419 if (CSSStyleSheet* pageUserSheet = document->pageUserSheet())
420 tempUserStyle->addRulesFromSheet(pageUserSheet->contents(), *m_medium, this);
421 addAuthorRulesAndCollectUserRulesFromSheets(document->pageGroupUserSheets(), *tempUserStyle);
422 addAuthorRulesAndCollectUserRulesFromSheets(document->documentUserSheets(), *tempUserStyle);
423 if (tempUserStyle->m_ruleCount > 0 || tempUserStyle->m_pageRules.size() > 0)
424 m_userStyle = tempUserStyle.release();
426 #if ENABLE(SVG_FONTS)
427 if (document->svgExtensions()) {
428 const HashSet<SVGFontFaceElement*>& svgFontFaceElements = document->svgExtensions()->svgFontFaceElements();
429 HashSet<SVGFontFaceElement*>::const_iterator end = svgFontFaceElements.end();
430 for (HashSet<SVGFontFaceElement*>::const_iterator it = svgFontFaceElements.begin(); it != end; ++it)
431 fontSelector()->addFontFaceRule((*it)->fontFaceRule());
435 addStylesheetsFromSeamlessParents();
436 appendAuthorStylesheets(0, document->styleSheets()->vector());
439 void StyleResolver::addStylesheetsFromSeamlessParents()
441 // Build a list of stylesheet lists from our ancestors, and walk that
442 // list in reverse order so that the root-most sheets are appended first.
443 Document* childDocument = document();
444 Vector<StyleSheetList*> ancestorSheets;
445 while (HTMLIFrameElement* parentIFrame = childDocument->seamlessParentIFrame()) {
446 Document* parentDocument = parentIFrame->document();
447 ancestorSheets.append(parentDocument->styleSheets());
448 childDocument = parentDocument;
450 for (int i = ancestorSheets.size() - 1; i >= 0; i--)
451 appendAuthorStylesheets(0, ancestorSheets.at(i)->vector());
454 void StyleResolver::addAuthorRulesAndCollectUserRulesFromSheets(const Vector<RefPtr<CSSStyleSheet> >* userSheets, RuleSet& userStyle)
459 unsigned length = userSheets->size();
460 for (unsigned i = 0; i < length; i++) {
461 StyleSheetContents* sheet = userSheets->at(i)->contents();
462 if (sheet->isUserStyleSheet())
463 userStyle.addRulesFromSheet(sheet, *m_medium, this);
465 m_authorStyle->addRulesFromSheet(sheet, *m_medium, this);
469 static PassOwnPtr<RuleSet> makeRuleSet(const Vector<StyleResolver::RuleFeature>& rules)
471 size_t size = rules.size();
474 OwnPtr<RuleSet> ruleSet = RuleSet::create();
475 for (size_t i = 0; i < size; ++i)
476 ruleSet->addRule(rules[i].rule, rules[i].selector, rules[i].hasDocumentSecurityOrigin, false);
477 ruleSet->shrinkToFit();
478 return ruleSet.release();
481 void StyleResolver::collectFeatures()
484 // Collect all ids and rules using sibling selectors (:first-child and similar)
485 // in the current set of stylesheets. Style sharing code uses this information to reject
486 // sharing candidates.
487 m_features.add(defaultStyle->features());
488 m_features.add(m_authorStyle->features());
489 #if ENABLE(STYLE_SCOPED)
490 for (ScopedRuleSetMap::iterator it = m_scopedAuthorStyles.begin(); it != m_scopedAuthorStyles.end(); ++it)
491 m_features.add(it->second->features());
494 m_features.add(m_userStyle->features());
496 m_siblingRuleSet = makeRuleSet(m_features.siblingRules);
497 m_uncommonAttributeRuleSet = makeRuleSet(m_features.uncommonAttributeRules);
500 #if ENABLE(STYLE_SCOPED)
501 const ContainerNode* StyleResolver::determineScope(const CSSStyleSheet* sheet)
505 if (!ContextFeatures::styleScopedEnabled(document()))
508 Node* ownerNode = sheet->ownerNode();
509 if (!ownerNode || !ownerNode->isHTMLElement() || !ownerNode->hasTagName(HTMLNames::styleTag))
512 HTMLStyleElement* styleElement = static_cast<HTMLStyleElement*>(ownerNode);
513 if (!styleElement->scoped())
514 return styleElement->isInShadowTree()? styleElement->shadowRoot() : 0;
516 ContainerNode* parent = styleElement->parentNode();
520 return (parent->isElementNode() || parent->isShadowRoot()) ? parent : 0;
523 inline RuleSet* StyleResolver::ruleSetForScope(const ContainerNode* scope) const
525 if (!scope->hasScopedHTMLStyleChild())
527 ScopedRuleSetMap::const_iterator it = m_scopedAuthorStyles.find(scope);
528 return it != m_scopedAuthorStyles.end() ? it->second.get() : 0;
532 void StyleResolver::appendAuthorStylesheets(unsigned firstNew, const Vector<RefPtr<StyleSheet> >& stylesheets)
534 // This handles sheets added to the end of the stylesheet list only. In other cases the style resolver
535 // needs to be reconstructed. To handle insertions too the rule order numbers would need to be updated.
536 unsigned size = stylesheets.size();
537 for (unsigned i = firstNew; i < size; ++i) {
538 if (!stylesheets[i]->isCSSStyleSheet())
540 CSSStyleSheet* cssSheet = static_cast<CSSStyleSheet*>(stylesheets[i].get());
541 if (cssSheet->disabled())
543 if (cssSheet->mediaQueries() && !m_medium->eval(cssSheet->mediaQueries(), this))
545 StyleSheetContents* sheet = cssSheet->contents();
546 #if ENABLE(STYLE_SCOPED)
547 const ContainerNode* scope = determineScope(cssSheet);
549 ScopedRuleSetMap::AddResult addResult = m_scopedAuthorStyles.add(scope, nullptr);
550 if (addResult.isNewEntry)
551 addResult.iterator->second = RuleSet::create();
552 addResult.iterator->second->addRulesFromSheet(sheet, *m_medium, this, scope);
556 m_authorStyle->addRulesFromSheet(sheet, *m_medium, this);
557 if (!m_styleRuleToCSSOMWrapperMap.isEmpty())
558 collectCSSOMWrappers(m_styleRuleToCSSOMWrapperMap, cssSheet);
560 m_authorStyle->shrinkToFit();
563 if (document()->renderer() && document()->renderer()->style())
564 document()->renderer()->style()->font().update(fontSelector());
567 #if ENABLE(STYLE_SCOPED)
568 void StyleResolver::setupScopeStack(const ContainerNode* parent)
570 // The scoping element stack shouldn't be used if <style scoped> isn't used anywhere.
571 ASSERT(!m_scopedAuthorStyles.isEmpty());
573 m_scopeStack.shrink(0);
574 int authorStyleBoundsIndex = 0;
575 for (const ContainerNode* scope = parent; scope; scope = scope->parentOrHostNode()) {
576 RuleSet* ruleSet = ruleSetForScope(scope);
578 m_scopeStack.append(ScopeStackFrame(scope, authorStyleBoundsIndex, ruleSet));
579 if (scope->isShadowRoot() && !toShadowRoot(scope)->applyAuthorStyles())
580 --authorStyleBoundsIndex;
582 m_scopeStack.reverse();
583 m_scopeStackParent = parent;
584 m_scopeStackParentBoundsIndex = 0;
587 void StyleResolver::pushScope(const ContainerNode* scope, const ContainerNode* scopeParent)
589 // Shortcut: Don't bother with the scoping element stack if <style scoped> isn't used anywhere.
590 if (m_scopedAuthorStyles.isEmpty()) {
591 ASSERT(!m_scopeStackParent);
592 ASSERT(m_scopeStack.isEmpty());
595 // In some wacky cases during style resolve we may get invoked for random elements.
596 // Recreate the whole scoping element stack in such cases.
597 if (!scopeStackIsConsistent(scopeParent)) {
598 setupScopeStack(scope);
601 if (scope->isShadowRoot() && !toShadowRoot(scope)->applyAuthorStyles())
602 ++m_scopeStackParentBoundsIndex;
603 // Otherwise just push the parent onto the stack.
604 RuleSet* ruleSet = ruleSetForScope(scope);
606 m_scopeStack.append(ScopeStackFrame(scope, m_scopeStackParentBoundsIndex, ruleSet));
607 m_scopeStackParent = scope;
610 void StyleResolver::popScope(const ContainerNode* scope)
612 // Only bother to update the scoping element stack if it is consistent.
613 if (scopeStackIsConsistent(scope)) {
614 if (!m_scopeStack.isEmpty() && m_scopeStack.last().m_scope == scope)
615 m_scopeStack.removeLast();
616 if (scope->isShadowRoot() && !toShadowRoot(scope)->applyAuthorStyles())
617 --m_scopeStackParentBoundsIndex;
618 m_scopeStackParent = scope->parentOrHostNode();
623 void StyleResolver::pushParentElement(Element* parent)
625 const ContainerNode* parentsParent = parent->parentOrHostElement();
627 // We are not always invoked consistently. For example, script execution can cause us to enter
628 // style recalc in the middle of tree building. We may also be invoked from somewhere within the tree.
629 // Reset the stack in this case, or if we see a new root element.
630 // Otherwise just push the new parent.
631 if (!parentsParent || m_checker.parentStackIsEmpty())
632 m_checker.setupParentStack(parent);
634 m_checker.pushParent(parent);
636 // Note: We mustn't skip ShadowRoot nodes for the scope stack.
637 pushScope(parent, parent->parentOrHostNode());
640 void StyleResolver::popParentElement(Element* parent)
642 // Note that we may get invoked for some random elements in some wacky cases during style resolve.
643 // Pause maintaining the stack in this case.
644 if (m_checker.parentStackIsConsistent(parent))
645 m_checker.popParent();
649 void StyleResolver::pushParentShadowRoot(const ShadowRoot* shadowRoot)
651 ASSERT(shadowRoot->host());
652 pushScope(shadowRoot, shadowRoot->host());
655 void StyleResolver::popParentShadowRoot(const ShadowRoot* shadowRoot)
657 ASSERT(shadowRoot->host());
658 popScope(shadowRoot);
661 // This is a simplified style setting function for keyframe styles
662 void StyleResolver::addKeyframeStyle(PassRefPtr<StyleRuleKeyframes> rule)
664 AtomicString s(rule->name());
665 m_keyframesRuleMap.set(s.impl(), rule);
668 StyleResolver::~StyleResolver()
670 m_fontSelector->clearDocument();
673 void StyleResolver::sweepMatchedPropertiesCache()
675 // Look for cache entries containing a style declaration with a single ref and remove them.
676 // This may happen when an element attribute mutation causes it to swap out its Attribute::decl()
677 // for another CSSMappedAttributeDeclaration, potentially leaving this cache with the last ref.
678 Vector<unsigned, 16> toRemove;
679 MatchedPropertiesCache::iterator it = m_matchedPropertiesCache.begin();
680 MatchedPropertiesCache::iterator end = m_matchedPropertiesCache.end();
681 for (; it != end; ++it) {
682 Vector<MatchedProperties>& matchedProperties = it->second.matchedProperties;
683 for (size_t i = 0; i < matchedProperties.size(); ++i) {
684 if (matchedProperties[i].properties->hasOneRef()) {
685 toRemove.append(it->first);
690 for (size_t i = 0; i < toRemove.size(); ++i)
691 m_matchedPropertiesCache.remove(toRemove[i]);
694 StyleResolver::Features::Features()
695 : usesFirstLineRules(false)
696 , usesBeforeAfterRules(false)
697 , usesLinkRules(false)
701 StyleResolver::Features::~Features()
705 void StyleResolver::Features::add(const StyleResolver::Features& other)
707 HashSet<AtomicStringImpl*>::iterator end = other.idsInRules.end();
708 for (HashSet<AtomicStringImpl*>::iterator it = other.idsInRules.begin(); it != end; ++it)
710 end = other.attrsInRules.end();
711 for (HashSet<AtomicStringImpl*>::iterator it = other.attrsInRules.begin(); it != end; ++it)
712 attrsInRules.add(*it);
713 siblingRules.append(other.siblingRules);
714 uncommonAttributeRules.append(other.uncommonAttributeRules);
715 usesFirstLineRules = usesFirstLineRules || other.usesFirstLineRules;
716 usesBeforeAfterRules = usesBeforeAfterRules || other.usesBeforeAfterRules;
717 usesLinkRules = usesLinkRules || other.usesLinkRules;
720 void StyleResolver::Features::clear()
723 attrsInRules.clear();
724 siblingRules.clear();
725 uncommonAttributeRules.clear();
726 usesFirstLineRules = false;
727 usesBeforeAfterRules = false;
728 usesLinkRules = false;
731 static StyleSheetContents* parseUASheet(const String& str)
733 StyleSheetContents* sheet = StyleSheetContents::create().leakRef(); // leak the sheet on purpose
734 sheet->parseString(str);
738 static StyleSheetContents* parseUASheet(const char* characters, unsigned size)
740 return parseUASheet(String(characters, size));
743 static void loadFullDefaultStyle()
745 if (simpleDefaultStyleSheet) {
746 ASSERT(defaultStyle);
747 ASSERT(defaultPrintStyle == defaultStyle);
749 simpleDefaultStyleSheet->deref();
750 defaultStyle = RuleSet::create().leakPtr();
751 defaultPrintStyle = RuleSet::create().leakPtr();
752 simpleDefaultStyleSheet = 0;
754 ASSERT(!defaultStyle);
755 defaultStyle = RuleSet::create().leakPtr();
756 defaultPrintStyle = RuleSet::create().leakPtr();
757 defaultQuirksStyle = RuleSet::create().leakPtr();
760 // Strict-mode rules.
761 String defaultRules = String(htmlUserAgentStyleSheet, sizeof(htmlUserAgentStyleSheet)) + RenderTheme::defaultTheme()->extraDefaultStyleSheet();
762 defaultStyleSheet = parseUASheet(defaultRules);
763 defaultStyle->addRulesFromSheet(defaultStyleSheet, screenEval());
764 defaultPrintStyle->addRulesFromSheet(defaultStyleSheet, printEval());
766 // Quirks-mode rules.
767 String quirksRules = String(quirksUserAgentStyleSheet, sizeof(quirksUserAgentStyleSheet)) + RenderTheme::defaultTheme()->extraQuirksStyleSheet();
768 quirksStyleSheet = parseUASheet(quirksRules);
769 defaultQuirksStyle->addRulesFromSheet(quirksStyleSheet, screenEval());
772 static void loadSimpleDefaultStyle()
774 ASSERT(!defaultStyle);
775 ASSERT(!simpleDefaultStyleSheet);
777 defaultStyle = RuleSet::create().leakPtr();
778 // There are no media-specific rules in the simple default style.
779 defaultPrintStyle = defaultStyle;
780 defaultQuirksStyle = RuleSet::create().leakPtr();
782 simpleDefaultStyleSheet = parseUASheet(simpleUserAgentStyleSheet, strlen(simpleUserAgentStyleSheet));
783 defaultStyle->addRulesFromSheet(simpleDefaultStyleSheet, screenEval());
785 // No need to initialize quirks sheet yet as there are no quirk rules for elements allowed in simple default style.
788 static void loadViewSourceStyle()
790 ASSERT(!defaultViewSourceStyle);
791 defaultViewSourceStyle = RuleSet::create().leakPtr();
792 defaultViewSourceStyle->addRulesFromSheet(parseUASheet(sourceUserAgentStyleSheet, sizeof(sourceUserAgentStyleSheet)), screenEval());
795 static void ensureDefaultStyleSheetsForElement(Element* element)
797 if (simpleDefaultStyleSheet && !elementCanUseSimpleDefaultStyle(element))
798 loadFullDefaultStyle();
801 if (element->isSVGElement() && !svgStyleSheet) {
803 svgStyleSheet = parseUASheet(svgUserAgentStyleSheet, sizeof(svgUserAgentStyleSheet));
804 defaultStyle->addRulesFromSheet(svgStyleSheet, screenEval());
805 defaultPrintStyle->addRulesFromSheet(svgStyleSheet, printEval());
810 if (element->isMathMLElement() && !mathMLStyleSheet) {
812 mathMLStyleSheet = parseUASheet(mathmlUserAgentStyleSheet, sizeof(mathmlUserAgentStyleSheet));
813 defaultStyle->addRulesFromSheet(mathMLStyleSheet, screenEval());
814 defaultPrintStyle->addRulesFromSheet(mathMLStyleSheet, printEval());
819 if (!mediaControlsStyleSheet && (element->hasTagName(videoTag) || element->hasTagName(audioTag))) {
820 String mediaRules = String(mediaControlsUserAgentStyleSheet, sizeof(mediaControlsUserAgentStyleSheet)) + RenderTheme::themeForPage(element->document()->page())->extraMediaControlsStyleSheet();
821 mediaControlsStyleSheet = parseUASheet(mediaRules);
822 defaultStyle->addRulesFromSheet(mediaControlsStyleSheet, screenEval());
823 defaultPrintStyle->addRulesFromSheet(mediaControlsStyleSheet, printEval());
827 #if ENABLE(FULLSCREEN_API)
828 if (!fullscreenStyleSheet && element->document()->webkitIsFullScreen()) {
829 String fullscreenRules = String(fullscreenUserAgentStyleSheet, sizeof(fullscreenUserAgentStyleSheet)) + RenderTheme::defaultTheme()->extraFullScreenStyleSheet();
830 fullscreenStyleSheet = parseUASheet(fullscreenRules);
831 defaultStyle->addRulesFromSheet(fullscreenStyleSheet, screenEval());
832 defaultQuirksStyle->addRulesFromSheet(fullscreenStyleSheet, screenEval());
836 ASSERT(defaultStyle->features().idsInRules.isEmpty());
837 ASSERT(mathMLStyleSheet || defaultStyle->features().siblingRules.isEmpty());
840 void StyleResolver::addMatchedProperties(MatchResult& matchResult, const StylePropertySet* properties, StyleRule* rule, unsigned linkMatchType, bool inRegionRule)
842 matchResult.matchedProperties.grow(matchResult.matchedProperties.size() + 1);
843 MatchedProperties& newProperties = matchResult.matchedProperties.last();
844 newProperties.properties = const_cast<StylePropertySet*>(properties);
845 newProperties.linkMatchType = linkMatchType;
846 newProperties.isInRegionRule = inRegionRule;
847 matchResult.matchedRules.append(rule);
850 inline void StyleResolver::addElementStyleProperties(MatchResult& result, StylePropertySet* propertySet, bool isCacheable)
854 result.ranges.lastAuthorRule = result.matchedProperties.size();
855 if (result.ranges.firstAuthorRule == -1)
856 result.ranges.firstAuthorRule = result.ranges.lastAuthorRule;
857 addMatchedProperties(result, propertySet);
859 result.isCacheable = false;
862 void StyleResolver::collectMatchingRules(RuleSet* rules, int& firstRuleIndex, int& lastRuleIndex, const MatchOptions& options)
867 // We need to collect the rules for id, class, tag, and everything else into a buffer and
868 // then sort the buffer.
869 if (m_element->hasID())
870 collectMatchingRulesForList(rules->idRules(m_element->idForStyleResolution().impl()), firstRuleIndex, lastRuleIndex, options);
871 if (m_element->hasClass()) {
872 ASSERT(m_styledElement);
873 const SpaceSplitString& classNames = m_styledElement->classNames();
874 size_t size = classNames.size();
875 for (size_t i = 0; i < size; ++i)
876 collectMatchingRulesForList(rules->classRules(classNames[i].impl()), firstRuleIndex, lastRuleIndex, options);
878 const AtomicString& pseudoId = m_element->shadowPseudoId();
879 if (!pseudoId.isEmpty()) {
880 ASSERT(m_styledElement);
881 collectMatchingRulesForList(rules->shadowPseudoElementRules(pseudoId.impl()), firstRuleIndex, lastRuleIndex, options);
883 if (m_element->isLink())
884 collectMatchingRulesForList(rules->linkPseudoClassRules(), firstRuleIndex, lastRuleIndex, options);
885 if (m_checker.matchesFocusPseudoClass(m_element))
886 collectMatchingRulesForList(rules->focusPseudoClassRules(), firstRuleIndex, lastRuleIndex, options);
887 collectMatchingRulesForList(rules->tagRules(m_element->localName().impl()), firstRuleIndex, lastRuleIndex, options);
888 collectMatchingRulesForList(rules->universalRules(), firstRuleIndex, lastRuleIndex, options);
891 void StyleResolver::collectMatchingRulesForRegion(RuleSet* rules, int& firstRuleIndex, int& lastRuleIndex, const MatchOptions& options)
893 if (!m_regionForStyling)
896 unsigned size = rules->m_regionSelectorsAndRuleSets.size();
897 for (unsigned i = 0; i < size; ++i) {
898 CSSSelector* regionSelector = rules->m_regionSelectorsAndRuleSets.at(i).selector;
899 if (checkRegionSelector(regionSelector, static_cast<Element*>(m_regionForStyling->node()))) {
900 RuleSet* regionRules = rules->m_regionSelectorsAndRuleSets.at(i).ruleSet.get();
902 collectMatchingRules(regionRules, firstRuleIndex, lastRuleIndex, options);
907 void StyleResolver::sortAndTransferMatchedRules(MatchResult& result)
909 if (m_matchedRules.isEmpty())
914 if (m_checker.mode() == SelectorChecker::CollectingRules) {
916 m_ruleList = StaticCSSRuleList::create();
917 for (unsigned i = 0; i < m_matchedRules.size(); ++i)
918 m_ruleList->rules().append(m_matchedRules[i]->rule()->createCSSOMWrapper());
922 // Now transfer the set of matched rules over to our list of declarations.
923 // FIXME: This sucks, the inspector should get the style from the visited style itself.
924 bool swapVisitedUnvisited = InspectorInstrumentation::forcePseudoState(m_element, CSSSelector::PseudoVisited);
925 for (unsigned i = 0; i < m_matchedRules.size(); i++) {
926 if (m_style && m_matchedRules[i]->containsUncommonAttributeSelector())
927 m_style->setAffectedByUncommonAttributeSelectors();
928 unsigned linkMatchType = m_matchedRules[i]->linkMatchType();
929 if (swapVisitedUnvisited && linkMatchType && linkMatchType != SelectorChecker::MatchAll)
930 linkMatchType = (linkMatchType == SelectorChecker::MatchVisited) ? SelectorChecker::MatchLink : SelectorChecker::MatchVisited;
931 addMatchedProperties(result, m_matchedRules[i]->rule()->properties(), m_matchedRules[i]->rule(), linkMatchType, m_matchedRules[i]->isInRegionRule());
935 void StyleResolver::matchScopedAuthorRules(MatchResult& result, bool includeEmptyRules)
937 #if ENABLE(STYLE_SCOPED)
938 if (m_scopedAuthorStyles.isEmpty())
941 MatchOptions options(includeEmptyRules);
943 // Match scoped author rules by traversing the scoped element stack (rebuild it if it got inconsistent).
944 if (!scopeStackIsConsistent(m_element))
945 setupScopeStack(m_element);
947 unsigned int firstShadowScopeIndex = 0;
948 if (m_element->treeScope()->applyAuthorStyles()) {
950 for (i = 0; i < m_scopeStack.size() && !m_scopeStack[i].m_scope->isInShadowTree(); ++i) {
951 const ScopeStackFrame& frame = m_scopeStack[i];
952 options.scope = frame.m_scope;
953 collectMatchingRules(frame.m_ruleSet, result.ranges.firstAuthorRule, result.ranges.lastAuthorRule, options);
954 collectMatchingRulesForRegion(frame.m_ruleSet, result.ranges.firstAuthorRule, result.ranges.lastAuthorRule, options);
956 firstShadowScopeIndex = i;
959 if (!m_element->isInShadowTree() || m_scopeStack.isEmpty())
962 unsigned scopedIndex = m_scopeStack.size();
963 int authorStyleBoundsIndex = m_scopeStackParentBoundsIndex;
964 for ( ; scopedIndex > firstShadowScopeIndex; --scopedIndex) {
965 if (authorStyleBoundsIndex != m_scopeStack[scopedIndex - 1].m_authorStyleBoundsIndex)
969 // Ruleset for ancestor nodes should be applied first.
970 for (unsigned i = scopedIndex; i < m_scopeStack.size(); ++i) {
971 const ScopeStackFrame& frame = m_scopeStack[i];
972 options.scope = frame.m_scope;
973 collectMatchingRules(frame.m_ruleSet, result.ranges.firstAuthorRule, result.ranges.lastAuthorRule, options);
974 collectMatchingRulesForRegion(frame.m_ruleSet, result.ranges.firstAuthorRule, result.ranges.lastAuthorRule, options);
977 UNUSED_PARAM(result);
978 UNUSED_PARAM(includeEmptyRules);
982 void StyleResolver::matchAuthorRules(MatchResult& result, bool includeEmptyRules)
984 m_matchedRules.clear();
985 result.ranges.lastAuthorRule = result.matchedProperties.size() - 1;
990 // Match global author rules.
991 MatchOptions options(includeEmptyRules);
992 collectMatchingRules(m_authorStyle.get(), result.ranges.firstAuthorRule, result.ranges.lastAuthorRule, options);
993 collectMatchingRulesForRegion(m_authorStyle.get(), result.ranges.firstAuthorRule, result.ranges.lastAuthorRule, options);
995 matchScopedAuthorRules(result, includeEmptyRules);
997 sortAndTransferMatchedRules(result);
1000 void StyleResolver::matchUserRules(MatchResult& result, bool includeEmptyRules)
1005 m_matchedRules.clear();
1007 result.ranges.lastUserRule = result.matchedProperties.size() - 1;
1008 collectMatchingRules(m_userStyle.get(), result.ranges.firstUserRule, result.ranges.lastUserRule, includeEmptyRules);
1009 collectMatchingRulesForRegion(m_userStyle.get(), result.ranges.firstUserRule, result.ranges.lastUserRule, includeEmptyRules);
1011 sortAndTransferMatchedRules(result);
1014 void StyleResolver::matchUARules(MatchResult& result, RuleSet* rules)
1016 m_matchedRules.clear();
1018 result.ranges.lastUARule = result.matchedProperties.size() - 1;
1019 collectMatchingRules(rules, result.ranges.firstUARule, result.ranges.lastUARule, false);
1021 sortAndTransferMatchedRules(result);
1024 class MatchingUARulesScope {
1026 MatchingUARulesScope();
1027 ~MatchingUARulesScope();
1029 static bool isMatchingUARules();
1032 static bool m_matchingUARules;
1035 MatchingUARulesScope::MatchingUARulesScope()
1037 ASSERT(!m_matchingUARules);
1038 m_matchingUARules = true;
1041 MatchingUARulesScope::~MatchingUARulesScope()
1043 m_matchingUARules = false;
1046 inline bool MatchingUARulesScope::isMatchingUARules()
1048 return m_matchingUARules;
1051 bool MatchingUARulesScope::m_matchingUARules = false;
1053 void StyleResolver::collectMatchingRulesForList(const Vector<RuleData>* rules, int& firstRuleIndex, int& lastRuleIndex, const MatchOptions& options)
1057 // In some cases we may end up looking up style for random elements in the middle of a recursive tree resolve.
1058 // Ancestor identifier filter won't be up-to-date in that case and we can't use the fast path.
1059 bool canUseFastReject = m_checker.parentStackIsConsistent(m_parentNode);
1061 unsigned size = rules->size();
1062 for (unsigned i = 0; i < size; ++i) {
1063 const RuleData& ruleData = rules->at(i);
1064 if (canUseFastReject && m_checker.fastRejectSelector<RuleData::maximumIdentifierCount>(ruleData.descendantSelectorIdentifierHashes()))
1067 StyleRule* rule = ruleData.rule();
1068 InspectorInstrumentationCookie cookie = InspectorInstrumentation::willMatchRule(document(), rule);
1069 #if ENABLE(STYLE_SCOPED)
1070 if (checkSelector(ruleData, options.scope)) {
1072 if (checkSelector(ruleData)) {
1074 // Check whether the rule is applicable in the current tree scope. Criteria for this:
1075 // a) it's a UA rule
1076 // b) the tree scope allows author rules
1077 // c) the rules comes from a scoped style sheet within the same tree scope
1078 // d) the rule contains shadow-ID pseudo elements
1079 TreeScope* treeScope = m_element->treeScope();
1080 if (!MatchingUARulesScope::isMatchingUARules()
1081 && !treeScope->applyAuthorStyles()
1082 #if ENABLE(STYLE_SCOPED)
1083 && (!options.scope || options.scope->treeScope() != treeScope)
1085 && !m_checker.hasUnknownPseudoElements()) {
1087 InspectorInstrumentation::didMatchRule(cookie, false);
1090 // If the rule has no properties to apply, then ignore it in the non-debug mode.
1091 const StylePropertySet* properties = rule->properties();
1092 if (!properties || (properties->isEmpty() && !options.includeEmptyRules)) {
1093 InspectorInstrumentation::didMatchRule(cookie, false);
1096 // FIXME: Exposing the non-standard getMatchedCSSRules API to web is the only reason this is needed.
1097 if (m_sameOriginOnly && !ruleData.hasDocumentSecurityOrigin()) {
1098 InspectorInstrumentation::didMatchRule(cookie, false);
1101 // If we're matching normal rules, set a pseudo bit if
1102 // we really just matched a pseudo-element.
1103 if (m_dynamicPseudo != NOPSEUDO && m_checker.pseudoStyle() == NOPSEUDO) {
1104 if (m_checker.mode() == SelectorChecker::CollectingRules) {
1105 InspectorInstrumentation::didMatchRule(cookie, false);
1108 if (m_dynamicPseudo < FIRST_INTERNAL_PSEUDOID)
1109 m_style->setHasPseudoStyle(m_dynamicPseudo);
1111 // Update our first/last rule indices in the matched rules array.
1113 if (firstRuleIndex == -1)
1114 firstRuleIndex = lastRuleIndex;
1116 // Add this rule to our list of matched rules.
1117 addMatchedRule(&ruleData);
1118 InspectorInstrumentation::didMatchRule(cookie, true);
1122 InspectorInstrumentation::didMatchRule(cookie, false);
1126 static inline bool compareRules(const RuleData* r1, const RuleData* r2)
1128 unsigned specificity1 = r1->specificity();
1129 unsigned specificity2 = r2->specificity();
1130 return (specificity1 == specificity2) ? r1->position() < r2->position() : specificity1 < specificity2;
1133 void StyleResolver::sortMatchedRules()
1135 std::sort(m_matchedRules.begin(), m_matchedRules.end(), compareRules);
1138 void StyleResolver::matchAllRules(MatchResult& result, bool includeSMILProperties)
1140 matchUARules(result);
1142 // Now we check user sheet rules.
1143 if (m_matchAuthorAndUserStyles)
1144 matchUserRules(result, false);
1146 // Now check author rules, beginning first with presentational attributes mapped from HTML.
1147 if (m_styledElement) {
1148 addElementStyleProperties(result, m_styledElement->attributeStyle());
1150 // Now we check additional mapped declarations.
1151 // Tables and table cells share an additional mapped rule that must be applied
1152 // after all attributes, since their mapped style depends on the values of multiple attributes.
1153 addElementStyleProperties(result, m_styledElement->additionalAttributeStyle());
1155 if (m_styledElement->isHTMLElement()) {
1157 TextDirection textDirection = toHTMLElement(m_styledElement)->directionalityIfhasDirAutoAttribute(isAuto);
1159 addMatchedProperties(result, textDirection == LTR ? leftToRightDeclaration() : rightToLeftDeclaration());
1163 // Check the rules in author sheets next.
1164 if (m_matchAuthorAndUserStyles)
1165 matchAuthorRules(result, false);
1167 // Now check our inline style attribute.
1168 if (m_matchAuthorAndUserStyles && m_styledElement && m_styledElement->inlineStyle()) {
1169 // Inline style is immutable as long as there is no CSSOM wrapper.
1170 // FIXME: Media control shadow trees seem to have problems with caching.
1171 bool isInlineStyleCacheable = !m_styledElement->inlineStyle()->isMutable() && !m_styledElement->isInShadowTree();
1173 addElementStyleProperties(result, const_cast<StylePropertySet*>(m_styledElement->inlineStyle()), isInlineStyleCacheable);
1177 // Now check SMIL animation override style.
1178 if (includeSMILProperties && m_matchAuthorAndUserStyles && m_styledElement && m_styledElement->isSVGElement())
1179 addElementStyleProperties(result, static_cast<SVGElement*>(m_styledElement)->animatedSMILStyleProperties(), false /* isCacheable */);
1181 UNUSED_PARAM(includeSMILProperties);
1185 inline void StyleResolver::initElement(Element* e)
1187 if (m_element != e) {
1189 m_styledElement = m_element && m_element->isStyledElement() ? static_cast<StyledElement*>(m_element) : 0;
1190 m_elementLinkState = m_checker.determineLinkState(m_element);
1191 if (e && e == e->document()->documentElement()) {
1192 e->document()->setDirectionSetOnDocumentElement(false);
1193 e->document()->setWritingModeSetOnDocumentElement(false);
1198 inline void StyleResolver::initForStyleResolve(Element* e, RenderStyle* parentStyle, PseudoId pseudoID)
1200 m_checker.setPseudoStyle(pseudoID);
1203 NodeRenderingContext context(e);
1204 m_parentNode = context.parentNodeForRenderingAndStyle();
1205 m_parentStyle = context.resetStyleInheritance()? 0 :
1206 parentStyle ? parentStyle :
1207 m_parentNode ? m_parentNode->renderStyle() : 0;
1210 m_parentStyle = parentStyle;
1213 Node* docElement = e ? e->document()->documentElement() : 0;
1214 RenderStyle* docStyle = m_checker.document()->renderStyle();
1215 m_rootElementStyle = docElement && e != docElement ? docElement->renderStyle() : docStyle;
1219 m_pendingImageProperties.clear();
1223 m_fontDirty = false;
1226 static const unsigned cStyleSearchThreshold = 10;
1227 static const unsigned cStyleSearchLevelThreshold = 10;
1229 Node* StyleResolver::locateCousinList(Element* parent, unsigned& visitedNodeCount) const
1231 if (visitedNodeCount >= cStyleSearchThreshold * cStyleSearchLevelThreshold)
1233 if (!parent || !parent->isStyledElement())
1235 #if ENABLE(STYLE_SCOPED)
1236 if (parent->hasScopedHTMLStyleChild())
1239 StyledElement* p = static_cast<StyledElement*>(parent);
1240 if (p->inlineStyle())
1243 if (p->isSVGElement() && static_cast<SVGElement*>(p)->animatedSMILStyleProperties())
1246 if (p->hasID() && m_features.idsInRules.contains(p->idForStyleResolution().impl()))
1249 RenderStyle* parentStyle = p->renderStyle();
1250 unsigned subcount = 0;
1251 Node* thisCousin = p;
1252 Node* currentNode = p->previousSibling();
1254 // Reserve the tries for this level. This effectively makes sure that the algorithm
1255 // will never go deeper than cStyleSearchLevelThreshold levels into recursion.
1256 visitedNodeCount += cStyleSearchThreshold;
1257 while (thisCousin) {
1258 while (currentNode) {
1260 if (currentNode->renderStyle() == parentStyle && currentNode->lastChild()) {
1261 // Adjust for unused reserved tries.
1262 visitedNodeCount -= cStyleSearchThreshold - subcount;
1263 return currentNode->lastChild();
1265 if (subcount >= cStyleSearchThreshold)
1267 currentNode = currentNode->previousSibling();
1269 currentNode = locateCousinList(thisCousin->parentElement(), visitedNodeCount);
1270 thisCousin = currentNode;
1276 bool StyleResolver::matchesRuleSet(RuleSet* ruleSet)
1280 m_matchedRules.clear();
1282 int firstRuleIndex = -1, lastRuleIndex = -1;
1283 collectMatchingRules(ruleSet, firstRuleIndex, lastRuleIndex, false);
1285 if (m_matchedRules.isEmpty())
1287 m_matchedRules.clear();
1291 bool StyleResolver::canShareStyleWithControl(StyledElement* element) const
1293 HTMLInputElement* thisInputElement = element->toInputElement();
1294 HTMLInputElement* otherInputElement = m_element->toInputElement();
1296 if (!thisInputElement || !otherInputElement)
1299 if (thisInputElement->isAutofilled() != otherInputElement->isAutofilled())
1301 if (thisInputElement->shouldAppearChecked() != otherInputElement->shouldAppearChecked())
1303 if (thisInputElement->isIndeterminate() != otherInputElement->isIndeterminate())
1305 if (thisInputElement->required() != otherInputElement->required())
1308 if (element->isEnabledFormControl() != m_element->isEnabledFormControl())
1311 if (element->isDefaultButtonForForm() != m_element->isDefaultButtonForForm())
1314 if (m_element->document()->containsValidityStyleRules()) {
1315 bool willValidate = element->willValidate();
1317 if (willValidate != m_element->willValidate())
1320 if (willValidate && (element->isValidFormControlElement() != m_element->isValidFormControlElement()))
1323 if (element->isInRange() != m_element->isInRange())
1326 if (element->isOutOfRange() != m_element->isOutOfRange())
1333 // This function makes some assumptions that only make sense for attribute styles (we only compare CSSProperty::id() and CSSProperty::value().)
1334 static inline bool attributeStylesEqual(StylePropertySet* a, StylePropertySet* b)
1338 if (a->propertyCount() != b->propertyCount())
1340 unsigned propertyCount = a->propertyCount();
1341 for (unsigned i = 0; i < propertyCount; ++i) {
1342 const CSSProperty& aProperty = a->propertyAt(i);
1344 for (j = 0; j < propertyCount; ++j) {
1345 const CSSProperty& bProperty = b->propertyAt(j);
1346 if (aProperty.id() != bProperty.id())
1348 // We could get a few more hits by comparing cssText() here, but that gets expensive quickly.
1349 if (aProperty.value() != bProperty.value())
1353 if (j == propertyCount)
1359 inline bool elementHasDirectionAuto(Element* element)
1361 return element->isHTMLElement() && toHTMLElement(element)->hasDirectionAuto();
1364 bool StyleResolver::canShareStyleWithElement(StyledElement* element) const
1366 RenderStyle* style = element->renderStyle();
1370 if (style->unique())
1372 if (element->tagQName() != m_element->tagQName())
1374 if (element->hasClass() != m_element->hasClass())
1376 if (element->inlineStyle())
1379 if (element->isSVGElement() && static_cast<SVGElement*>(element)->animatedSMILStyleProperties())
1382 if (!!element->attributeStyle() != !!m_styledElement->attributeStyle())
1384 StylePropertySet* additionalAttributeStyleA = element->additionalAttributeStyle();
1385 StylePropertySet* additionalAttributeStyleB = m_styledElement->additionalAttributeStyle();
1386 if (!additionalAttributeStyleA != !additionalAttributeStyleB)
1388 if (element->isLink() != m_element->isLink())
1390 if (style->affectedByUncommonAttributeSelectors())
1392 if (element->hovered() != m_element->hovered())
1394 if (element->active() != m_element->active())
1396 if (element->focused() != m_element->focused())
1398 if (element->shadowPseudoId() != m_element->shadowPseudoId())
1400 if (element == element->document()->cssTarget())
1402 if (m_element == m_element->document()->cssTarget())
1404 if (element->getAttribute(typeAttr) != m_element->getAttribute(typeAttr))
1406 if (element->fastGetAttribute(XMLNames::langAttr) != m_element->fastGetAttribute(XMLNames::langAttr))
1408 if (element->fastGetAttribute(langAttr) != m_element->fastGetAttribute(langAttr))
1410 if (element->fastGetAttribute(readonlyAttr) != m_element->fastGetAttribute(readonlyAttr))
1412 if (element->fastGetAttribute(cellpaddingAttr) != m_element->fastGetAttribute(cellpaddingAttr))
1415 if (element->hasID() && m_features.idsInRules.contains(element->idForStyleResolution().impl()))
1418 #if ENABLE(STYLE_SCOPED)
1419 if (element->hasScopedHTMLStyleChild())
1423 #if ENABLE(PROGRESS_TAG)
1424 if (element->hasTagName(progressTag)) {
1425 if (!m_element->hasTagName(progressTag))
1428 HTMLProgressElement* thisProgressElement = static_cast<HTMLProgressElement*>(element);
1429 HTMLProgressElement* otherProgressElement = static_cast<HTMLProgressElement*>(m_element);
1430 if (thisProgressElement->isDeterminate() != otherProgressElement->isDeterminate())
1435 // FIXME: We should share style for option and optgroup whenever possible.
1436 // Before doing so, we need to resolve issues in HTMLSelectElement::recalcListItems
1437 // and RenderMenuList::setText. See also https://bugs.webkit.org/show_bug.cgi?id=88405
1438 if (element->hasTagName(optionTag) || element->hasTagName(optgroupTag))
1441 bool isControl = element->isFormControlElement();
1443 if (isControl != m_element->isFormControlElement())
1446 if (isControl && !canShareStyleWithControl(element))
1449 if (style->transitions() || style->animations())
1452 #if USE(ACCELERATED_COMPOSITING)
1453 // Turn off style sharing for elements that can gain layers for reasons outside of the style system.
1454 // See comments in RenderObject::setStyle().
1455 if (element->hasTagName(iframeTag) || element->hasTagName(frameTag) || element->hasTagName(embedTag) || element->hasTagName(objectTag) || element->hasTagName(appletTag)
1456 #if ENABLE(PLUGIN_PROXY_FOR_VIDEO)
1457 // With proxying, the media elements are backed by a RenderEmbeddedObject.
1458 || element->hasTagName(videoTag) || element->hasTagName(audioTag)
1464 if (elementHasDirectionAuto(element) || elementHasDirectionAuto(m_element))
1467 if (element->hasClass() && m_element->getAttribute(classAttr) != element->getAttribute(classAttr))
1470 if (element->attributeStyle() && !attributeStylesEqual(element->attributeStyle(), m_styledElement->attributeStyle()))
1473 if (additionalAttributeStyleA && !attributeStylesEqual(additionalAttributeStyleA, additionalAttributeStyleB))
1476 if (element->isLink() && m_elementLinkState != style->insideLink())
1482 inline StyledElement* StyleResolver::findSiblingForStyleSharing(Node* node, unsigned& count) const
1484 for (; node; node = node->previousSibling()) {
1485 if (!node->isStyledElement())
1487 if (canShareStyleWithElement(static_cast<StyledElement*>(node)))
1489 if (count++ == cStyleSearchThreshold)
1492 return static_cast<StyledElement*>(node);
1495 static inline bool parentStylePreventsSharing(const RenderStyle* parentStyle)
1497 return parentStyle->childrenAffectedByPositionalRules()
1498 || parentStyle->childrenAffectedByFirstChildRules()
1499 || parentStyle->childrenAffectedByLastChildRules()
1500 || parentStyle->childrenAffectedByDirectAdjacentRules();
1503 RenderStyle* StyleResolver::locateSharedStyle()
1505 if (!m_styledElement || !m_parentStyle)
1507 // If the element has inline style it is probably unique.
1508 if (m_styledElement->inlineStyle())
1511 if (m_styledElement->isSVGElement() && static_cast<SVGElement*>(m_styledElement)->animatedSMILStyleProperties())
1514 // Ids stop style sharing if they show up in the stylesheets.
1515 if (m_styledElement->hasID() && m_features.idsInRules.contains(m_styledElement->idForStyleResolution().impl()))
1517 if (parentStylePreventsSharing(m_parentStyle))
1519 #if ENABLE(STYLE_SCOPED)
1520 if (m_styledElement->hasScopedHTMLStyleChild())
1524 // Check previous siblings and their cousins.
1526 unsigned visitedNodeCount = 0;
1527 StyledElement* shareElement = 0;
1528 Node* cousinList = m_styledElement->previousSibling();
1529 while (cousinList) {
1530 shareElement = findSiblingForStyleSharing(cousinList, count);
1533 cousinList = locateCousinList(cousinList->parentElement(), visitedNodeCount);
1536 // If we have exhausted all our budget or our cousins.
1540 // Can't share if sibling rules apply. This is checked at the end as it should rarely fail.
1541 if (matchesRuleSet(m_siblingRuleSet.get()))
1543 // Can't share if attribute rules apply.
1544 if (matchesRuleSet(m_uncommonAttributeRuleSet.get()))
1546 // Tracking child index requires unique style for each node. This may get set by the sibling rule match above.
1547 if (parentStylePreventsSharing(m_parentStyle))
1549 return shareElement->renderStyle();
1552 void StyleResolver::matchUARules(MatchResult& result)
1554 MatchingUARulesScope scope;
1556 // First we match rules from the user agent sheet.
1557 if (simpleDefaultStyleSheet)
1558 result.isCacheable = false;
1559 RuleSet* userAgentStyleSheet = m_medium->mediaTypeMatchSpecific("print")
1560 ? defaultPrintStyle : defaultStyle;
1561 matchUARules(result, userAgentStyleSheet);
1563 // In quirks mode, we match rules from the quirks user agent sheet.
1564 if (!m_checker.strictParsing())
1565 matchUARules(result, defaultQuirksStyle);
1567 // 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.
1568 if (m_checker.document()->isViewSource()) {
1569 if (!defaultViewSourceStyle)
1570 loadViewSourceStyle();
1571 matchUARules(result, defaultViewSourceStyle);
1575 PassRefPtr<RenderStyle> StyleResolver::styleForDocument(Document* document, CSSFontSelector* fontSelector)
1577 Frame* frame = document->frame();
1579 // HTML5 states that seamless iframes should replace default CSS values
1580 // with values inherited from the containing iframe element. However,
1581 // some values (such as the case of designMode = "on") still need to
1582 // be set by this "document style".
1583 RefPtr<RenderStyle> documentStyle = RenderStyle::create();
1584 bool seamlessWithParent = document->shouldDisplaySeamlesslyWithParent();
1585 if (seamlessWithParent) {
1586 RenderStyle* iframeStyle = document->seamlessParentIFrame()->renderStyle();
1588 documentStyle->inheritFrom(iframeStyle);
1591 // FIXME: It's not clear which values below we want to override in the seamless case!
1592 documentStyle->setDisplay(BLOCK);
1593 if (!seamlessWithParent) {
1594 documentStyle->setRTLOrdering(document->visuallyOrdered() ? VisualOrder : LogicalOrder);
1595 documentStyle->setZoom(frame && !document->printing() ? frame->pageZoomFactor() : 1);
1596 documentStyle->setPageScaleTransform(frame ? frame->frameScaleFactor() : 1);
1597 documentStyle->setLocale(document->contentLanguage());
1599 // FIXME: This overrides any -webkit-user-modify inherited from the parent iframe.
1600 documentStyle->setUserModify(document->inDesignMode() ? READ_WRITE : READ_ONLY);
1602 Element* docElement = document->documentElement();
1603 RenderObject* docElementRenderer = docElement ? docElement->renderer() : 0;
1604 if (docElementRenderer) {
1605 // Use the direction and writing-mode of the body to set the
1606 // viewport's direction and writing-mode unless the property is set on the document element.
1607 // If there is no body, then use the document element.
1608 RenderObject* bodyRenderer = document->body() ? document->body()->renderer() : 0;
1609 if (bodyRenderer && !document->writingModeSetOnDocumentElement())
1610 documentStyle->setWritingMode(bodyRenderer->style()->writingMode());
1612 documentStyle->setWritingMode(docElementRenderer->style()->writingMode());
1613 if (bodyRenderer && !document->directionSetOnDocumentElement())
1614 documentStyle->setDirection(bodyRenderer->style()->direction());
1616 documentStyle->setDirection(docElementRenderer->style()->direction());
1620 if (Page* page = frame->page()) {
1621 const Page::Pagination& pagination = page->pagination();
1622 if (pagination.mode != Page::Pagination::Unpaginated) {
1623 switch (pagination.mode) {
1624 case Page::Pagination::LeftToRightPaginated:
1625 documentStyle->setColumnAxis(HorizontalColumnAxis);
1626 if (documentStyle->isHorizontalWritingMode())
1627 documentStyle->setColumnProgression(documentStyle->isLeftToRightDirection() ? NormalColumnProgression : ReverseColumnProgression);
1629 documentStyle->setColumnProgression(documentStyle->isFlippedBlocksWritingMode() ? ReverseColumnProgression : NormalColumnProgression);
1631 case Page::Pagination::RightToLeftPaginated:
1632 documentStyle->setColumnAxis(HorizontalColumnAxis);
1633 if (documentStyle->isHorizontalWritingMode())
1634 documentStyle->setColumnProgression(documentStyle->isLeftToRightDirection() ? ReverseColumnProgression : NormalColumnProgression);
1636 documentStyle->setColumnProgression(documentStyle->isFlippedBlocksWritingMode() ? NormalColumnProgression : ReverseColumnProgression);
1638 case Page::Pagination::TopToBottomPaginated:
1639 documentStyle->setColumnAxis(VerticalColumnAxis);
1640 if (documentStyle->isHorizontalWritingMode())
1641 documentStyle->setColumnProgression(documentStyle->isFlippedBlocksWritingMode() ? ReverseColumnProgression : NormalColumnProgression);
1643 documentStyle->setColumnProgression(documentStyle->isLeftToRightDirection() ? NormalColumnProgression : ReverseColumnProgression);
1645 case Page::Pagination::BottomToTopPaginated:
1646 documentStyle->setColumnAxis(VerticalColumnAxis);
1647 if (documentStyle->isHorizontalWritingMode())
1648 documentStyle->setColumnProgression(documentStyle->isFlippedBlocksWritingMode() ? NormalColumnProgression : ReverseColumnProgression);
1650 documentStyle->setColumnProgression(documentStyle->isLeftToRightDirection() ? ReverseColumnProgression : NormalColumnProgression);
1652 case Page::Pagination::Unpaginated:
1653 ASSERT_NOT_REACHED();
1657 documentStyle->setColumnGap(pagination.gap);
1662 // Seamless iframes want to inherit their font from their parent iframe, so early return before setting the font.
1663 if (seamlessWithParent)
1664 return documentStyle.release();
1666 FontDescription fontDescription;
1667 fontDescription.setUsePrinterFont(document->printing());
1668 fontDescription.setScript(localeToScriptCodeForFontSelection(documentStyle->locale()));
1669 if (Settings* settings = document->settings()) {
1670 fontDescription.setRenderingMode(settings->fontRenderingMode());
1671 const AtomicString& standardFont = settings->standardFontFamily(fontDescription.script());
1672 if (!standardFont.isEmpty()) {
1673 fontDescription.setGenericFamily(FontDescription::StandardFamily);
1674 fontDescription.firstFamily().setFamily(standardFont);
1675 fontDescription.firstFamily().appendFamily(0);
1677 fontDescription.setKeywordSize(CSSValueMedium - CSSValueXxSmall + 1);
1678 int size = StyleResolver::fontSizeForKeyword(document, CSSValueMedium, false);
1679 fontDescription.setSpecifiedSize(size);
1680 bool useSVGZoomRules = document->isSVGDocument();
1681 fontDescription.setComputedSize(StyleResolver::getComputedSizeFromSpecifiedSize(document, documentStyle.get(), fontDescription.isAbsoluteSize(), size, useSVGZoomRules));
1684 documentStyle->setFontDescription(fontDescription);
1685 documentStyle->font().update(fontSelector);
1687 return documentStyle.release();
1690 static inline bool isAtShadowBoundary(const Element* element)
1694 ContainerNode* parentNode = element->parentNode();
1695 return parentNode && parentNode->isShadowRoot();
1698 PassRefPtr<RenderStyle> StyleResolver::styleForElement(Element* element, RenderStyle* defaultParent,
1699 StyleSharingBehavior sharingBehavior, RuleMatchingBehavior matchingBehavior, RenderRegion* regionForStyling)
1701 // Once an element has a renderer, we don't try to destroy it, since otherwise the renderer
1702 // will vanish if a style recalc happens during loading.
1703 if (sharingBehavior == AllowStyleSharing && !element->document()->haveStylesheetsLoaded() && !element->renderer()) {
1704 if (!s_styleNotYetAvailable) {
1705 s_styleNotYetAvailable = RenderStyle::create().leakRef();
1706 s_styleNotYetAvailable->setDisplay(NONE);
1707 s_styleNotYetAvailable->font().update(m_fontSelector);
1709 element->document()->setHasNodesWithPlaceholderStyle();
1710 return s_styleNotYetAvailable;
1713 initElement(element);
1714 initForStyleResolve(element, defaultParent);
1715 m_regionForStyling = regionForStyling;
1716 if (sharingBehavior == AllowStyleSharing) {
1717 RenderStyle* sharedStyle = locateSharedStyle();
1722 m_style = RenderStyle::create();
1724 RefPtr<RenderStyle> cloneForParent;
1727 m_style->inheritFrom(m_parentStyle, isAtShadowBoundary(element) ? RenderStyle::AtShadowBoundary : RenderStyle::NotAtShadowBoundary);
1729 // Make sure our fonts are initialized if we don't inherit them from our parent style.
1730 if (Settings* settings = documentSettings()) {
1731 initializeFontStyle(settings);
1732 m_style->font().update(fontSelector());
1734 m_style->font().update(0);
1735 cloneForParent = RenderStyle::clone(style());
1736 m_parentStyle = cloneForParent.get();
1739 if (element->isLink()) {
1740 m_style->setIsLink(true);
1741 m_style->setInsideLink(m_elementLinkState);
1744 ensureDefaultStyleSheetsForElement(element);
1746 MatchResult matchResult;
1747 if (matchingBehavior == MatchOnlyUserAgentRules)
1748 matchUARules(matchResult);
1750 matchAllRules(matchResult, matchingBehavior != MatchAllRulesExcludingSMIL);
1752 applyMatchedProperties(matchResult, element);
1754 // Clean up our style object's display and text decorations (among other fixups).
1755 adjustRenderStyle(style(), m_parentStyle, element);
1757 initElement(0); // Clear out for the next resolve.
1762 // Now return the style.
1763 return m_style.release();
1766 PassRefPtr<RenderStyle> StyleResolver::styleForKeyframe(const RenderStyle* elementStyle, const StyleKeyframe* keyframe, KeyframeValue& keyframeValue)
1769 if (keyframe->properties())
1770 addMatchedProperties(result, keyframe->properties());
1775 m_style = RenderStyle::clone(elementStyle);
1777 m_lineHeightValue = 0;
1779 // We don't need to bother with !important. Since there is only ever one
1780 // decl, there's nothing to override. So just add the first properties.
1781 bool inheritedOnly = false;
1782 if (keyframe->properties())
1783 applyMatchedProperties<HighPriorityProperties>(result, false, 0, result.matchedProperties.size() - 1, inheritedOnly);
1785 // If our font got dirtied, go ahead and update it now.
1788 // Line-height is set when we are sure we decided on the font-size
1789 if (m_lineHeightValue)
1790 applyProperty(CSSPropertyLineHeight, m_lineHeightValue);
1792 // Now do rest of the properties.
1793 if (keyframe->properties())
1794 applyMatchedProperties<LowPriorityProperties>(result, false, 0, result.matchedProperties.size() - 1, inheritedOnly);
1796 // If our font got dirtied by one of the non-essential font props,
1797 // go ahead and update it a second time.
1800 // Start loading resources referenced by this style.
1801 loadPendingResources();
1803 // Add all the animating properties to the keyframe.
1804 if (StylePropertySet* styleDeclaration = keyframe->properties()) {
1805 unsigned propertyCount = styleDeclaration->propertyCount();
1806 for (unsigned i = 0; i < propertyCount; ++i) {
1807 CSSPropertyID property = styleDeclaration->propertyAt(i).id();
1808 // Timing-function within keyframes is special, because it is not animated; it just
1809 // describes the timing function between this keyframe and the next.
1810 if (property != CSSPropertyWebkitAnimationTimingFunction)
1811 keyframeValue.addProperty(property);
1815 return m_style.release();
1818 void StyleResolver::keyframeStylesForAnimation(Element* e, const RenderStyle* elementStyle, KeyframeList& list)
1822 // Get the keyframesRule for this name
1823 if (!e || list.animationName().isEmpty())
1826 m_keyframesRuleMap.checkConsistency();
1828 KeyframesRuleMap::iterator it = m_keyframesRuleMap.find(list.animationName().impl());
1829 if (it == m_keyframesRuleMap.end())
1832 const StyleRuleKeyframes* keyframesRule = it->second.get();
1834 // Construct and populate the style for each keyframe
1835 const Vector<RefPtr<StyleKeyframe> >& keyframes = keyframesRule->keyframes();
1836 for (unsigned i = 0; i < keyframes.size(); ++i) {
1837 // Apply the declaration to the style. This is a simplified version of the logic in styleForElement
1839 initForStyleResolve(e);
1841 const StyleKeyframe* keyframe = keyframes[i].get();
1843 KeyframeValue keyframeValue(0, 0);
1844 keyframeValue.setStyle(styleForKeyframe(elementStyle, keyframe, keyframeValue));
1846 // Add this keyframe style to all the indicated key times
1848 keyframe->getKeys(keys);
1849 for (size_t keyIndex = 0; keyIndex < keys.size(); ++keyIndex) {
1850 keyframeValue.setKey(keys[keyIndex]);
1851 list.insert(keyframeValue);
1855 // If the 0% keyframe is missing, create it (but only if there is at least one other keyframe)
1856 int initialListSize = list.size();
1857 if (initialListSize > 0 && list[0].key()) {
1858 static StyleKeyframe* zeroPercentKeyframe;
1859 if (!zeroPercentKeyframe) {
1860 zeroPercentKeyframe = StyleKeyframe::create().leakRef();
1861 zeroPercentKeyframe->setKeyText("0%");
1863 KeyframeValue keyframeValue(0, 0);
1864 keyframeValue.setStyle(styleForKeyframe(elementStyle, zeroPercentKeyframe, keyframeValue));
1865 list.insert(keyframeValue);
1868 // If the 100% keyframe is missing, create it (but only if there is at least one other keyframe)
1869 if (initialListSize > 0 && (list[list.size() - 1].key() != 1)) {
1870 static StyleKeyframe* hundredPercentKeyframe;
1871 if (!hundredPercentKeyframe) {
1872 hundredPercentKeyframe = StyleKeyframe::create().leakRef();
1873 hundredPercentKeyframe->setKeyText("100%");
1875 KeyframeValue keyframeValue(1, 0);
1876 keyframeValue.setStyle(styleForKeyframe(elementStyle, hundredPercentKeyframe, keyframeValue));
1877 list.insert(keyframeValue);
1881 PassRefPtr<RenderStyle> StyleResolver::pseudoStyleForElement(PseudoId pseudo, Element* e, RenderStyle* parentStyle)
1888 initForStyleResolve(e, parentStyle, pseudo);
1889 m_style = RenderStyle::create();
1892 m_style->inheritFrom(m_parentStyle);
1894 // Since we don't use pseudo-elements in any of our quirk/print user agent rules, don't waste time walking
1897 // Check UA, user and author rules.
1898 MatchResult matchResult;
1899 matchUARules(matchResult);
1901 if (m_matchAuthorAndUserStyles) {
1902 matchUserRules(matchResult, false);
1903 matchAuthorRules(matchResult, false);
1906 if (matchResult.matchedProperties.isEmpty())
1909 m_style->setStyleType(pseudo);
1911 applyMatchedProperties(matchResult, e);
1913 // Clean up our style object's display and text decorations (among other fixups).
1914 adjustRenderStyle(style(), parentStyle, 0);
1916 // Start loading resources referenced by this style.
1917 loadPendingResources();
1919 // Now return the style.
1920 return m_style.release();
1923 PassRefPtr<RenderStyle> StyleResolver::styleForPage(int pageIndex)
1925 initForStyleResolve(m_checker.document()->documentElement()); // m_rootElementStyle will be set to the document style.
1927 m_style = RenderStyle::create();
1928 m_style->inheritFrom(m_rootElementStyle);
1930 const bool isLeft = isLeftPage(pageIndex);
1931 const bool isFirst = isFirstPage(pageIndex);
1932 const String page = pageName(pageIndex);
1935 matchPageRules(result, defaultPrintStyle, isLeft, isFirst, page);
1936 matchPageRules(result, m_userStyle.get(), isLeft, isFirst, page);
1937 // Only consider the global author RuleSet for @page rules, as per the HTML5 spec.
1938 matchPageRules(result, m_authorStyle.get(), isLeft, isFirst, page);
1939 m_lineHeightValue = 0;
1940 bool inheritedOnly = false;
1941 #if ENABLE(CSS_VARIABLES)
1942 applyMatchedProperties<VariableDefinitions>(result, false, 0, result.matchedProperties.size() - 1, inheritedOnly);
1944 applyMatchedProperties<HighPriorityProperties>(result, false, 0, result.matchedProperties.size() - 1, inheritedOnly);
1946 // If our font got dirtied, go ahead and update it now.
1949 // Line-height is set when we are sure we decided on the font-size.
1950 if (m_lineHeightValue)
1951 applyProperty(CSSPropertyLineHeight, m_lineHeightValue);
1953 applyMatchedProperties<LowPriorityProperties>(result, false, 0, result.matchedProperties.size() - 1, inheritedOnly);
1955 // Start loading resources referenced by this style.
1956 loadPendingResources();
1958 // Now return the style.
1959 return m_style.release();
1962 static void addIntrinsicMargins(RenderStyle* style)
1964 // Intrinsic margin value.
1965 const int intrinsicMargin = 2 * style->effectiveZoom();
1967 // FIXME: Using width/height alone and not also dealing with min-width/max-width is flawed.
1968 // FIXME: Using "quirk" to decide the margin wasn't set is kind of lame.
1969 if (style->width().isIntrinsicOrAuto()) {
1970 if (style->marginLeft().quirk())
1971 style->setMarginLeft(Length(intrinsicMargin, Fixed));
1972 if (style->marginRight().quirk())
1973 style->setMarginRight(Length(intrinsicMargin, Fixed));
1976 if (style->height().isAuto()) {
1977 if (style->marginTop().quirk())
1978 style->setMarginTop(Length(intrinsicMargin, Fixed));
1979 if (style->marginBottom().quirk())
1980 style->setMarginBottom(Length(intrinsicMargin, Fixed));
1984 static EDisplay equivalentBlockDisplay(EDisplay display, bool isFloating, bool strictParsing)
1990 #if ENABLE(CSS3_FLEXBOX)
1997 // It is a WinIE bug that floated list items lose their bullets, so we'll emulate the quirk, but only in quirks mode.
1998 if (!strictParsing && isFloating)
2005 #if ENABLE(CSS3_FLEXBOX)
2016 case TABLE_ROW_GROUP:
2017 case TABLE_HEADER_GROUP:
2018 case TABLE_FOOTER_GROUP:
2020 case TABLE_COLUMN_GROUP:
2026 ASSERT_NOT_REACHED();
2029 ASSERT_NOT_REACHED();
2033 // CSS requires text-decoration to be reset at each DOM element for tables,
2034 // inline blocks, inline tables, run-ins, shadow DOM crossings, floating elements,
2035 // and absolute or relatively positioned elements.
2036 static bool doesNotInheritTextDecoration(RenderStyle* style, Element* e)
2038 return style->display() == TABLE || style->display() == INLINE_TABLE || style->display() == RUN_IN
2039 || style->display() == INLINE_BLOCK || style->display() == INLINE_BOX || isAtShadowBoundary(e)
2040 || style->isFloating() || style->isOutOfFlowPositioned();
2043 void StyleResolver::adjustRenderStyle(RenderStyle* style, RenderStyle* parentStyle, Element *e)
2045 // Cache our original display.
2046 style->setOriginalDisplay(style->display());
2048 if (style->display() != NONE) {
2049 // If we have a <td> that specifies a float property, in quirks mode we just drop the float
2051 // Sites also commonly use display:inline/block on <td>s and <table>s. In quirks mode we force
2052 // these tags to retain their display types.
2053 if (!m_checker.strictParsing() && e) {
2054 if (e->hasTagName(tdTag)) {
2055 style->setDisplay(TABLE_CELL);
2056 style->setFloating(NoFloat);
2057 } else if (e->hasTagName(tableTag))
2058 style->setDisplay(style->isDisplayInlineType() ? INLINE_TABLE : TABLE);
2061 if (e && (e->hasTagName(tdTag) || e->hasTagName(thTag))) {
2062 if (style->whiteSpace() == KHTML_NOWRAP) {
2063 // Figure out if we are really nowrapping or if we should just
2064 // use normal instead. If the width of the cell is fixed, then
2065 // we don't actually use NOWRAP.
2066 if (style->width().isFixed())
2067 style->setWhiteSpace(NORMAL);
2069 style->setWhiteSpace(NOWRAP);
2073 // Tables never support the -webkit-* values for text-align and will reset back to the default.
2074 if (e && e->hasTagName(tableTag) && (style->textAlign() == WEBKIT_LEFT || style->textAlign() == WEBKIT_CENTER || style->textAlign() == WEBKIT_RIGHT))
2075 style->setTextAlign(TASTART);
2077 // Frames and framesets never honor position:relative or position:absolute. This is necessary to
2078 // fix a crash where a site tries to position these objects. They also never honor display.
2079 if (e && (e->hasTagName(frameTag) || e->hasTagName(framesetTag))) {
2080 style->setPosition(StaticPosition);
2081 style->setDisplay(BLOCK);
2084 // Ruby text does not support float or position. This might change with evolution of the specification.
2085 if (e && e->hasTagName(rtTag)) {
2086 style->setPosition(StaticPosition);
2087 style->setFloating(NoFloat);
2090 // FIXME: We shouldn't be overriding start/-webkit-auto like this. Do it in html.css instead.
2091 // Table headers with a text-align of -webkit-auto will change the text-align to center.
2092 if (e && e->hasTagName(thTag) && style->textAlign() == TASTART)
2093 style->setTextAlign(CENTER);
2095 if (e && e->hasTagName(legendTag))
2096 style->setDisplay(BLOCK);
2098 // Absolute/fixed positioned elements, floating elements and the document element need block-like outside display.
2099 if (style->position() == AbsolutePosition || style->position() == FixedPosition || style->isFloating() || (e && e->document()->documentElement() == e))
2100 style->setDisplay(equivalentBlockDisplay(style->display(), style->isFloating(), m_checker.strictParsing()));
2102 // FIXME: Don't support this mutation for pseudo styles like first-letter or first-line, since it's not completely
2103 // clear how that should work.
2104 if (style->display() == INLINE && style->styleType() == NOPSEUDO && parentStyle && style->writingMode() != parentStyle->writingMode())
2105 style->setDisplay(INLINE_BLOCK);
2107 // After performing the display mutation, check table rows. We do not honor position:relative on
2108 // table rows or cells. This has been established in CSS2.1 (and caused a crash in containingBlock()
2110 if ((style->display() == TABLE_HEADER_GROUP || style->display() == TABLE_ROW_GROUP
2111 || style->display() == TABLE_FOOTER_GROUP || style->display() == TABLE_ROW)
2112 && style->position() == RelativePosition)
2113 style->setPosition(StaticPosition);
2115 // writing-mode does not apply to table row groups, table column groups, table rows, and table columns.
2116 // FIXME: Table cells should be allowed to be perpendicular or flipped with respect to the table, though.
2117 if (style->display() == TABLE_COLUMN || style->display() == TABLE_COLUMN_GROUP || style->display() == TABLE_FOOTER_GROUP
2118 || style->display() == TABLE_HEADER_GROUP || style->display() == TABLE_ROW || style->display() == TABLE_ROW_GROUP
2119 || style->display() == TABLE_CELL)
2120 style->setWritingMode(parentStyle->writingMode());
2122 // FIXME: Since we don't support block-flow on flexible boxes yet, disallow setting
2123 // of block-flow to anything other than TopToBottomWritingMode.
2124 // https://bugs.webkit.org/show_bug.cgi?id=46418 - Flexible box support.
2125 if (style->writingMode() != TopToBottomWritingMode && (style->display() == BOX || style->display() == INLINE_BOX))
2126 style->setWritingMode(TopToBottomWritingMode);
2128 if (e && e->parentNode() && e->parentNode()->renderer() && e->parentNode()->renderer()->isFlexibleBox())
2129 style->setDisplay(equivalentBlockDisplay(style->display(), style->isFloating(), m_checker.strictParsing()));
2132 // Make sure our z-index value is only applied if the object is positioned.
2133 if (style->position() == StaticPosition)
2134 style->setHasAutoZIndex();
2136 // Auto z-index becomes 0 for the root element and transparent objects. This prevents
2137 // cases where objects that should be blended as a single unit end up with a non-transparent
2138 // object wedged in between them. Auto z-index also becomes 0 for objects that specify transforms/masks/reflections.
2139 if (style->hasAutoZIndex() && ((e && e->document()->documentElement() == e) || style->opacity() < 1.0f
2140 || style->hasTransformRelatedProperty() || style->hasMask() || style->boxReflect() || style->hasFilter()
2141 #ifdef FIXED_POSITION_CREATES_STACKING_CONTEXT
2142 || style->position() == FixedPosition
2144 || (style->position() == FixedPosition && e && e->document()->page() && e->document()->page()->settings()->fixedPositionCreatesStackingContext())
2146 #if ENABLE(OVERFLOW_SCROLLING)
2147 // Touch overflow scrolling creates a stacking context.
2148 || ((style->overflowX() != OHIDDEN || style->overflowY() != OHIDDEN) && style->useTouchOverflowScrolling())
2151 style->setZIndex(0);
2153 // Textarea considers overflow visible as auto.
2154 if (e && e->hasTagName(textareaTag)) {
2155 style->setOverflowX(style->overflowX() == OVISIBLE ? OAUTO : style->overflowX());
2156 style->setOverflowY(style->overflowY() == OVISIBLE ? OAUTO : style->overflowY());
2159 if (doesNotInheritTextDecoration(style, e))
2160 style->setTextDecorationsInEffect(style->textDecoration());
2162 style->addToTextDecorationsInEffect(style->textDecoration());
2164 // If either overflow value is not visible, change to auto.
2165 if (style->overflowX() == OMARQUEE && style->overflowY() != OMARQUEE)
2166 style->setOverflowY(OMARQUEE);
2167 else if (style->overflowY() == OMARQUEE && style->overflowX() != OMARQUEE)
2168 style->setOverflowX(OMARQUEE);
2169 else if (style->overflowX() == OVISIBLE && style->overflowY() != OVISIBLE)
2170 style->setOverflowX(OAUTO);
2171 else if (style->overflowY() == OVISIBLE && style->overflowX() != OVISIBLE)
2172 style->setOverflowY(OAUTO);
2174 // Table rows, sections and the table itself will support overflow:hidden and will ignore scroll/auto.
2175 // FIXME: Eventually table sections will support auto and scroll.
2176 if (style->display() == TABLE || style->display() == INLINE_TABLE
2177 || style->display() == TABLE_ROW_GROUP || style->display() == TABLE_ROW) {
2178 if (style->overflowX() != OVISIBLE && style->overflowX() != OHIDDEN)
2179 style->setOverflowX(OVISIBLE);
2180 if (style->overflowY() != OVISIBLE && style->overflowY() != OHIDDEN)
2181 style->setOverflowY(OVISIBLE);
2184 // Menulists should have visible overflow
2185 if (style->appearance() == MenulistPart) {
2186 style->setOverflowX(OVISIBLE);
2187 style->setOverflowY(OVISIBLE);
2190 // Cull out any useless layers and also repeat patterns into additional layers.
2191 style->adjustBackgroundLayers();
2192 style->adjustMaskLayers();
2194 // Do the same for animations and transitions.
2195 style->adjustAnimations();
2196 style->adjustTransitions();
2198 // Important: Intrinsic margins get added to controls before the theme has adjusted the style, since the theme will
2199 // alter fonts and heights/widths.
2200 if (e && e->isFormControlElement() && style->fontSize() >= 11) {
2201 // Don't apply intrinsic margins to image buttons. The designer knows how big the images are,
2202 // so we have to treat all image buttons as though they were explicitly sized.
2203 if (!e->hasTagName(inputTag) || !static_cast<HTMLInputElement*>(e)->isImageButton())
2204 addIntrinsicMargins(style);
2207 // Let the theme also have a crack at adjusting the style.
2208 if (style->hasAppearance())
2209 RenderTheme::defaultTheme()->adjustStyle(this, style, e, m_hasUAAppearance, m_borderData, m_backgroundData, m_backgroundColor);
2211 // If we have first-letter pseudo style, do not share this style.
2212 if (style->hasPseudoStyle(FIRST_LETTER))
2215 // FIXME: when dropping the -webkit prefix on transform-style, we should also have opacity < 1 cause flattening.
2216 if (style->preserves3D() && (style->overflowX() != OVISIBLE
2217 || style->overflowY() != OVISIBLE
2218 || style->hasFilter()))
2219 style->setTransformStyle3D(TransformStyle3DFlat);
2221 // Seamless iframes behave like blocks. Map their display to inline-block when marked inline.
2222 if (e && e->hasTagName(iframeTag) && style->display() == INLINE && static_cast<HTMLIFrameElement*>(e)->shouldDisplaySeamlessly())
2223 style->setDisplay(INLINE_BLOCK);
2226 if (e && e->isSVGElement()) {
2227 // Spec: http://www.w3.org/TR/SVG/masking.html#OverflowProperty
2228 if (style->overflowY() == OSCROLL)
2229 style->setOverflowY(OHIDDEN);
2230 else if (style->overflowY() == OAUTO)
2231 style->setOverflowY(OVISIBLE);
2233 if (style->overflowX() == OSCROLL)
2234 style->setOverflowX(OHIDDEN);
2235 else if (style->overflowX() == OAUTO)
2236 style->setOverflowX(OVISIBLE);
2238 // Only the root <svg> element in an SVG document fragment tree honors css position
2239 if (!(e->hasTagName(SVGNames::svgTag) && e->parentNode() && !e->parentNode()->isSVGElement()))
2240 style->setPosition(RenderStyle::initialPosition());
2242 // RenderSVGRoot handles zooming for the whole SVG subtree, so foreignObject content should
2243 // not be scaled again.
2244 if (e->hasTagName(SVGNames::foreignObjectTag))
2245 style->setEffectiveZoom(RenderStyle::initialZoom());
2250 bool StyleResolver::checkRegionStyle(Element* regionElement)
2252 // FIXME (BUG 72472): We don't add @-webkit-region rules of scoped style sheets for the moment,
2253 // so all region rules are global by default. Verify whether that can stand or needs changing.
2255 unsigned rulesSize = m_authorStyle->m_regionSelectorsAndRuleSets.size();
2256 for (unsigned i = 0; i < rulesSize; ++i) {
2257 ASSERT(m_authorStyle->m_regionSelectorsAndRuleSets.at(i).ruleSet.get());
2258 if (checkRegionSelector(m_authorStyle->m_regionSelectorsAndRuleSets.at(i).selector, regionElement))
2263 rulesSize = m_userStyle->m_regionSelectorsAndRuleSets.size();
2264 for (unsigned i = 0; i < rulesSize; ++i) {
2265 ASSERT(m_userStyle->m_regionSelectorsAndRuleSets.at(i).ruleSet.get());
2266 if (checkRegionSelector(m_userStyle->m_regionSelectorsAndRuleSets.at(i).selector, regionElement))
2274 void StyleResolver::updateFont()
2279 checkForTextSizeAdjust();
2280 checkForGenericFamilyChange(style(), m_parentStyle);
2281 checkForZoomChange(style(), m_parentStyle);
2282 m_style->font().update(m_fontSelector);
2283 m_fontDirty = false;
2286 void StyleResolver::cacheBorderAndBackground()
2288 m_hasUAAppearance = m_style->hasAppearance();
2289 if (m_hasUAAppearance) {
2290 m_borderData = m_style->border();
2291 m_backgroundData = *m_style->backgroundLayers();
2292 m_backgroundColor = m_style->backgroundColor();
2296 PassRefPtr<CSSRuleList> StyleResolver::styleRulesForElement(Element* e, unsigned rulesToInclude)
2298 return pseudoStyleRulesForElement(e, NOPSEUDO, rulesToInclude);
2301 PassRefPtr<CSSRuleList> StyleResolver::pseudoStyleRulesForElement(Element* e, PseudoId pseudoId, unsigned rulesToInclude)
2303 if (!e || !e->document()->haveStylesheetsLoaded())
2306 m_checker.setMode(SelectorChecker::CollectingRules);
2309 initForStyleResolve(e, 0, pseudoId);
2312 if (rulesToInclude & UAAndUserCSSRules) {
2313 // First we match rules from the user agent sheet.
2314 matchUARules(dummy);
2316 // Now we check user sheet rules.
2317 if (m_matchAuthorAndUserStyles)
2318 matchUserRules(dummy, rulesToInclude & EmptyCSSRules);
2321 if (m_matchAuthorAndUserStyles && (rulesToInclude & AuthorCSSRules)) {
2322 m_sameOriginOnly = !(rulesToInclude & CrossOriginCSSRules);
2324 // Check the rules in author sheets.
2325 matchAuthorRules(dummy, rulesToInclude & EmptyCSSRules);
2327 m_sameOriginOnly = false;
2330 m_checker.setMode(SelectorChecker::ResolvingStyle);
2332 return m_ruleList.release();
2335 inline bool StyleResolver::checkSelector(const RuleData& ruleData, const ContainerNode* scope)
2337 m_dynamicPseudo = NOPSEUDO;
2338 m_checker.clearHasUnknownPseudoElements();
2340 if (ruleData.hasFastCheckableSelector()) {
2341 // We know this selector does not include any pseudo elements.
2342 if (m_checker.pseudoStyle() != NOPSEUDO)
2344 // We know a sufficiently simple single part selector matches simply because we found it from the rule hash.
2345 // This is limited to HTML only so we don't need to check the namespace.
2346 if (ruleData.hasRightmostSelectorMatchingHTMLBasedOnRuleHash() && m_element->isHTMLElement()) {
2347 if (!ruleData.hasMultipartSelector())
2349 } else if (!SelectorChecker::tagMatches(m_element, ruleData.selector()))
2351 if (!SelectorChecker::fastCheckRightmostAttributeSelector(m_element, ruleData.selector()))
2353 return m_checker.fastCheckSelector(ruleData.selector(), m_element);
2357 SelectorChecker::SelectorCheckingContext context(ruleData.selector(), m_element, SelectorChecker::VisitedMatchEnabled);
2358 context.elementStyle = style();
2359 context.elementParentStyle = m_parentNode ? m_parentNode->renderStyle() : 0;
2360 context.scope = scope;
2361 SelectorChecker::SelectorMatch match = m_checker.checkSelector(context, m_dynamicPseudo);
2362 if (match != SelectorChecker::SelectorMatches)
2364 if (m_checker.pseudoStyle() != NOPSEUDO && m_checker.pseudoStyle() != m_dynamicPseudo)
2369 bool StyleResolver::checkRegionSelector(CSSSelector* regionSelector, Element* regionElement)
2371 if (!regionSelector || !regionElement)
2374 m_checker.clearHasUnknownPseudoElements();
2375 m_checker.setPseudoStyle(NOPSEUDO);
2377 for (CSSSelector* s = regionSelector; s; s = CSSSelectorList::next(s))
2378 if (m_checker.checkSelector(s, regionElement))
2384 bool StyleResolver::determineStylesheetSelectorScopes(StyleSheetContents* stylesheet, HashSet<AtomicStringImpl*>& idScopes, HashSet<AtomicStringImpl*>& classScopes)
2386 ASSERT(!stylesheet->isLoading());
2388 const Vector<RefPtr<StyleRuleImport> >& importRules = stylesheet->importRules();
2389 for (unsigned i = 0; i < importRules.size(); ++i) {
2390 if (!importRules[i]->styleSheet())
2392 if (!determineStylesheetSelectorScopes(importRules[i]->styleSheet(), idScopes, classScopes))
2396 const Vector<RefPtr<StyleRuleBase> >& rules = stylesheet->childRules();
2397 for (unsigned i = 0; i < rules.size(); i++) {
2398 StyleRuleBase* rule = rules[i].get();
2399 if (rule->isStyleRule()) {
2400 StyleRule* styleRule = static_cast<StyleRule*>(rule);
2401 if (!SelectorChecker::determineSelectorScopes(styleRule->selectorList(), idScopes, classScopes))
2405 // FIXME: Media rules and maybe some others could be allowed.
2411 // -----------------------------------------------------------------
2413 static inline bool isSelectorMatchingHTMLBasedOnRuleHash(const CSSSelector* selector)
2415 const AtomicString& selectorNamespace = selector->tag().namespaceURI();
2416 if (selectorNamespace != starAtom && selectorNamespace != xhtmlNamespaceURI)
2418 if (selector->m_match == CSSSelector::None)
2420 if (selector->tag() != starAtom)
2422 if (SelectorChecker::isCommonPseudoClassSelector(selector))
2424 return selector->m_match == CSSSelector::Id || selector->m_match == CSSSelector::Class;
2427 static inline bool selectorListContainsUncommonAttributeSelector(const CSSSelector* selector)
2429 CSSSelectorList* selectorList = selector->selectorList();
2432 for (CSSSelector* subSelector = selectorList->first(); subSelector; subSelector = CSSSelectorList::next(subSelector)) {
2433 if (subSelector->isAttributeSelector())
2439 static inline bool isCommonAttributeSelectorAttribute(const QualifiedName& attribute)
2441 // These are explicitly tested for equality in canShareStyleWithElement.
2442 return attribute == typeAttr || attribute == readonlyAttr;
2445 static inline bool containsUncommonAttributeSelector(const CSSSelector* selector)
2447 for (; selector; selector = selector->tagHistory()) {
2448 // Allow certain common attributes (used in the default style) in the selectors that match the current element.
2449 if (selector->isAttributeSelector() && !isCommonAttributeSelectorAttribute(selector->attribute()))
2451 if (selectorListContainsUncommonAttributeSelector(selector))
2453 if (selector->relation() != CSSSelector::SubSelector) {
2454 selector = selector->tagHistory();
2459 for (; selector; selector = selector->tagHistory()) {
2460 if (selector->isAttributeSelector())
2462 if (selectorListContainsUncommonAttributeSelector(selector))
2468 RuleData::RuleData(StyleRule* rule, CSSSelector* selector, unsigned position, bool hasDocumentSecurityOrigin, bool canUseFastCheckSelector, bool inRegionRule)
2470 , m_selector(selector)
2471 , m_specificity(selector->specificity())
2472 , m_position(position)
2473 , m_hasFastCheckableSelector(canUseFastCheckSelector && SelectorChecker::isFastCheckableSelector(selector))
2474 , m_hasMultipartSelector(!!selector->tagHistory())
2475 , m_hasRightmostSelectorMatchingHTMLBasedOnRuleHash(isSelectorMatchingHTMLBasedOnRuleHash(selector))
2476 , m_containsUncommonAttributeSelector(WebCore::containsUncommonAttributeSelector(selector))
2477 , m_linkMatchType(SelectorChecker::determineLinkMatchType(selector))
2478 , m_hasDocumentSecurityOrigin(hasDocumentSecurityOrigin)
2479 , m_isInRegionRule(inRegionRule)
2481 SelectorChecker::collectIdentifierHashes(m_selector, m_descendantSelectorIdentifierHashes, maximumIdentifierCount);
2486 , m_autoShrinkToFitEnabled(true)
2490 static inline void collectFeaturesFromSelector(StyleResolver::Features& features, const CSSSelector* selector)
2492 if (selector->m_match == CSSSelector::Id)
2493 features.idsInRules.add(selector->value().impl());
2494 if (selector->isAttributeSelector())
2495 features.attrsInRules.add(selector->attribute().localName().impl());
2496 switch (selector->pseudoType()) {
2497 case CSSSelector::PseudoFirstLine:
2498 features.usesFirstLineRules = true;
2500 case CSSSelector::PseudoBefore:
2501 case CSSSelector::PseudoAfter:
2502 features.usesBeforeAfterRules = true;
2504 case CSSSelector::PseudoLink:
2505 case CSSSelector::PseudoVisited:
2506 features.usesLinkRules = true;
2513 static void collectFeaturesFromRuleData(StyleResolver::Features& features, const RuleData& ruleData)
2515 bool foundSiblingSelector = false;
2516 for (CSSSelector* selector = ruleData.selector(); selector; selector = selector->tagHistory()) {
2517 collectFeaturesFromSelector(features, selector);
2519 if (CSSSelectorList* selectorList = selector->selectorList()) {
2520 for (CSSSelector* subSelector = selectorList->first(); subSelector; subSelector = CSSSelectorList::next(subSelector)) {
2521 if (!foundSiblingSelector && selector->isSiblingSelector())
2522 foundSiblingSelector = true;
2523 collectFeaturesFromSelector(features, subSelector);
2525 } else if (!foundSiblingSelector && selector->isSiblingSelector())
2526 foundSiblingSelector = true;
2528 if (foundSiblingSelector)
2529 features.siblingRules.append(StyleResolver::RuleFeature(ruleData.rule(), ruleData.selector(), ruleData.hasDocumentSecurityOrigin()));
2530 if (ruleData.containsUncommonAttributeSelector())
2531 features.uncommonAttributeRules.append(StyleResolver::RuleFeature(ruleData.rule(), ruleData.selector(), ruleData.hasDocumentSecurityOrigin()));
2534 void RuleSet::addToRuleSet(AtomicStringImpl* key, AtomRuleMap& map, const RuleData& ruleData)
2538 OwnPtr<Vector<RuleData> >& rules = map.add(key, nullptr).iterator->second;
2540 rules = adoptPtr(new Vector<RuleData>);
2541 rules->append(ruleData);
2544 void RuleSet::addRule(StyleRule* rule, CSSSelector* selector, bool hasDocumentSecurityOrigin, bool canUseFastCheckSelector, bool inRegionRule)
2546 RuleData ruleData(rule, selector, m_ruleCount++, hasDocumentSecurityOrigin, canUseFastCheckSelector, inRegionRule);
2547 collectFeaturesFromRuleData(m_features, ruleData);
2549 if (selector->m_match == CSSSelector::Id) {
2550 addToRuleSet(selector->value().impl(), m_idRules, ruleData);
2553 if (selector->m_match == CSSSelector::Class) {
2554 addToRuleSet(selector->value().impl(), m_classRules, ruleData);
2557 if (selector->isUnknownPseudoElement()) {
2558 addToRuleSet(selector->value().impl(), m_shadowPseudoElementRules, ruleData);
2561 if (SelectorChecker::isCommonPseudoClassSelector(selector)) {
2562 switch (selector->pseudoType()) {
2563 case CSSSelector::PseudoLink:
2564 case CSSSelector::PseudoVisited:
2565 case CSSSelector::PseudoAnyLink:
2566 m_linkPseudoClassRules.append(ruleData);
2568 case CSSSelector::PseudoFocus:
2569 m_focusPseudoClassRules.append(ruleData);
2572 ASSERT_NOT_REACHED();
2576 const AtomicString& localName = selector->tag().localName();
2577 if (localName != starAtom) {
2578 addToRuleSet(localName.impl(), m_tagRules, ruleData);
2581 m_universalRules.append(ruleData);
2584 void RuleSet::addPageRule(StyleRulePage* rule)
2586 m_pageRules.append(rule);
2589 void RuleSet::addRegionRule(StyleRuleRegion* regionRule, bool hasDocumentSecurityOrigin)
2591 OwnPtr<RuleSet> regionRuleSet = RuleSet::create();
2592 // The region rule set should take into account the position inside the parent rule set.
2593 // Otherwise, the rules inside region block might be incorrectly positioned before other similar rules from
2594 // the stylesheet that contains the region block.
2595 regionRuleSet->m_ruleCount = m_ruleCount;
2597 // Collect the region rules into a rule set
2598 const Vector<RefPtr<StyleRuleBase> >& childRules = regionRule->childRules();
2599 for (unsigned i = 0; i < childRules.size(); ++i) {
2600 StyleRuleBase* regionStylingRule = childRules[i].get();
2601 if (regionStylingRule->isStyleRule())
2602 regionRuleSet->addStyleRule(static_cast<StyleRule*>(regionStylingRule), hasDocumentSecurityOrigin, true, true);
2604 // Update the "global" rule count so that proper order is maintained
2605 m_ruleCount = regionRuleSet->m_ruleCount;
2607 m_regionSelectorsAndRuleSets.append(RuleSetSelectorPair(regionRule->selectorList().first(), regionRuleSet.release()));
2610 void RuleSet::addRulesFromSheet(StyleSheetContents* sheet, const MediaQueryEvaluator& medium, StyleResolver* styleSelector, const ContainerNode* scope)
2614 const Vector<RefPtr<StyleRuleImport> >& importRules = sheet->importRules();
2615 for (unsigned i = 0; i < importRules.size(); ++i) {
2616 StyleRuleImport* importRule = importRules[i].get();
2617 if (importRule->styleSheet() && (!importRule->mediaQueries() || medium.eval(importRule->mediaQueries(), styleSelector)))
2618 addRulesFromSheet(importRule->styleSheet(), medium, styleSelector, scope);
2620 bool hasDocumentSecurityOrigin = styleSelector && styleSelector->document()->securityOrigin()->canRequest(sheet->baseURL());
2622 const Vector<RefPtr<StyleRuleBase> >& rules = sheet->childRules();
2623 for (unsigned i = 0; i < rules.size(); ++i) {
2624 StyleRuleBase* rule = rules[i].get();
2626 ASSERT(!rule->isImportRule());
2627 if (rule->isStyleRule())
2628 addStyleRule(static_cast<StyleRule*>(rule), hasDocumentSecurityOrigin, !scope);
2629 else if (rule->isPageRule())
2630 addPageRule(static_cast<StyleRulePage*>(rule));
2631 else if (rule->isMediaRule()) {
2632 StyleRuleMedia* mediaRule = static_cast<StyleRuleMedia*>(rule);
2634 if ((!mediaRule->mediaQueries() || medium.eval(mediaRule->mediaQueries(), styleSelector))) {
2635 // Traverse child elements of the @media rule.
2636 const Vector<RefPtr<StyleRuleBase> >& childRules = mediaRule->childRules();
2637 for (unsigned j = 0; j < childRules.size(); ++j) {
2638 StyleRuleBase* childRule = childRules[j].get();
2639 if (childRule->isStyleRule())
2640 addStyleRule(static_cast<StyleRule*>(childRule), hasDocumentSecurityOrigin, !scope);
2641 else if (childRule->isPageRule())
2642 addPageRule(static_cast<StyleRulePage*>(childRule));
2643 else if (childRule->isFontFaceRule() && styleSelector) {
2644 // Add this font face to our set.
2645 // FIXME(BUG 72461): We don't add @font-face rules of scoped style sheets for the moment.
2648 const StyleRuleFontFace* fontFaceRule = static_cast<StyleRuleFontFace*>(childRule);
2649 styleSelector->fontSelector()->addFontFaceRule(fontFaceRule);
2650 styleSelector->invalidateMatchedPropertiesCache();
2651 } else if (childRule->isKeyframesRule() && styleSelector) {
2652 // Add this keyframe rule to our set.
2653 // FIXME(BUG 72462): We don't add @keyframe rules of scoped style sheets for the moment.
2656 styleSelector->addKeyframeStyle(static_cast<StyleRuleKeyframes*>(childRule));
2660 } else if (rule->isFontFaceRule() && styleSelector) {
2661 // Add this font face to our set.
2662 // FIXME(BUG 72461): We don't add @font-face rules of scoped style sheets for the moment.
2665 const StyleRuleFontFace* fontFaceRule = static_cast<StyleRuleFontFace*>(rule);
2666 styleSelector->fontSelector()->addFontFaceRule(fontFaceRule);
2667 styleSelector->invalidateMatchedPropertiesCache();
2668 } else if (rule->isKeyframesRule() && styleSelector) {
2669 // FIXME (BUG 72462): We don't add @keyframe rules of scoped style sheets for the moment.
2672 styleSelector->addKeyframeStyle(static_cast<StyleRuleKeyframes*>(rule));
2674 #if ENABLE(CSS_REGIONS)
2675 else if (rule->isRegionRule() && styleSelector) {
2676 // FIXME (BUG 72472): We don't add @-webkit-region rules of scoped style sheets for the moment.
2679 addRegionRule(static_cast<StyleRuleRegion*>(rule), hasDocumentSecurityOrigin);
2683 if (m_autoShrinkToFitEnabled)
2687 void RuleSet::addStyleRule(StyleRule* rule, bool hasDocumentSecurityOrigin, bool canUseFastCheckSelector, bool isInRegionRule)
2689 for (CSSSelector* s = rule->selectorList().first(); s; s = CSSSelectorList::next(s))
2690 addRule(rule, s, hasDocumentSecurityOrigin, canUseFastCheckSelector, isInRegionRule);
2693 static inline void shrinkMapVectorsToFit(RuleSet::AtomRuleMap& map)
2695 RuleSet::AtomRuleMap::iterator end = map.end();
2696 for (RuleSet::AtomRuleMap::iterator it = map.begin(); it != end; ++it)
2697 it->second->shrinkToFit();
2700 void RuleSet::shrinkToFit()
2702 shrinkMapVectorsToFit(m_idRules);
2703 shrinkMapVectorsToFit(m_classRules);
2704 shrinkMapVectorsToFit(m_tagRules);
2705 shrinkMapVectorsToFit(m_shadowPseudoElementRules);
2706 m_linkPseudoClassRules.shrinkToFit();
2707 m_focusPseudoClassRules.shrinkToFit();
2708 m_universalRules.shrinkToFit();
2709 m_pageRules.shrinkToFit();
2712 // -------------------------------------------------------------------------------------
2713 // this is mostly boring stuff on how to apply a certain rule to the renderstyle...
2715 Length StyleResolver::convertToIntLength(CSSPrimitiveValue* primitiveValue, RenderStyle* style, RenderStyle* rootStyle, double multiplier)
2717 return primitiveValue ? primitiveValue->convertToLength<FixedIntegerConversion | PercentConversion | FractionConversion | ViewportPercentageConversion>(style, rootStyle, multiplier) : Length(Undefined);
2720 Length StyleResolver::convertToFloatLength(CSSPrimitiveValue* primitiveValue, RenderStyle* style, RenderStyle* rootStyle, double multiplier)
2722 return primitiveValue ? primitiveValue->convertToLength<FixedFloatConversion | PercentConversion | FractionConversion | ViewportPercentageConversion>(style, rootStyle, multiplier) : Length(Undefined);
2725 template <StyleResolver::StyleApplicationPass pass>
2726 void StyleResolver::applyProperties(const StylePropertySet* properties, StyleRule* rule, bool isImportant, bool inheritedOnly, bool filterRegionProperties)
2728 ASSERT(!filterRegionProperties || m_regionForStyling);
2729 InspectorInstrumentationCookie cookie = InspectorInstrumentation::willProcessRule(document(), rule);
2731 unsigned propertyCount = properties->propertyCount();
2732 for (unsigned i = 0; i < propertyCount; ++i) {
2733 const CSSProperty& current = properties->propertyAt(i);
2734 if (isImportant != current.isImportant())
2736 if (inheritedOnly && !current.isInherited()) {
2737 // If the property value is explicitly inherited, we need to apply further non-inherited properties
2738 // as they might override the value inherited here. For this reason we don't allow declarations with
2739 // explicitly inherited properties to be cached.
2740 ASSERT(!current.value()->isInheritedValue());
2743 CSSPropertyID property = current.id();
2745 if (filterRegionProperties && !StyleResolver::isValidRegionStyleProperty(property))
2749 #if ENABLE(CSS_VARIABLES)
2750 case VariableDefinitions:
2751 COMPILE_ASSERT(CSSPropertyVariable < firstCSSProperty, CSS_variable_is_before_first_property);
2752 if (property == CSSPropertyVariable)
2753 applyProperty(current.id(), current.value());
2756 case HighPriorityProperties:
2757 COMPILE_ASSERT(firstCSSProperty == CSSPropertyColor, CSS_color_is_first_property);
2758 COMPILE_ASSERT(CSSPropertyZoom == CSSPropertyColor + 18, CSS_zoom_is_end_of_first_prop_range);
2759 COMPILE_ASSERT(CSSPropertyLineHeight == CSSPropertyZoom + 1, CSS_line_height_is_after_zoom);
2760 #if ENABLE(CSS_VARIABLES)
2761 if (property == CSSPropertyVariable)
2764 // give special priority to font-xxx, color properties, etc
2765 if (property < CSSPropertyLineHeight)
2766 applyProperty(current.id(), current.value());
2767 // we apply line-height later
2768 else if (property == CSSPropertyLineHeight)
2769 m_lineHeightValue = current.value();
2771 case LowPriorityProperties:
2772 if (property > CSSPropertyLineHeight)
2773 applyProperty(current.id(), current.value());
2776 InspectorInstrumentation::didProcessRule(cookie);
2779 template <StyleResolver::StyleApplicationPass pass>
2780 void StyleResolver::applyMatchedProperties(const MatchResult& matchResult, bool isImportant, int startIndex, int endIndex, bool inheritedOnly)
2782 if (startIndex == -1)
2785 if (m_style->insideLink() != NotInsideLink) {
2786 for (int i = startIndex; i <= endIndex; ++i) {
2787 const MatchedProperties& matchedProperties = matchResult.matchedProperties[i];
2788 unsigned linkMatchType = matchedProperties.linkMatchType;
2789 // FIXME: It would be nicer to pass these as arguments but that requires changes in many places.
2790 m_applyPropertyToRegularStyle = linkMatchType & SelectorChecker::MatchLink;
2791 m_applyPropertyToVisitedLinkStyle = linkMatchType & SelectorChecker::MatchVisited;
2793 applyProperties<pass>(matchedProperties.properties.get(), matchResult.matchedRules[i], isImportant, inheritedOnly, matchedProperties.isInRegionRule);
2795 m_applyPropertyToRegularStyle = true;
2796 m_applyPropertyToVisitedLinkStyle = false;
2799 for (int i = startIndex; i <= endIndex; ++i) {
2800 const MatchedProperties& matchedProperties = matchResult.matchedProperties[i];
2801 applyProperties<pass>(matchedProperties.properties.get(), matchResult.matchedRules[i], isImportant, inheritedOnly, matchedProperties.isInRegionRule);
2805 unsigned StyleResolver::computeMatchedPropertiesHash(const MatchedProperties* properties, unsigned size)
2808 return StringHasher::hashMemory(properties, sizeof(MatchedProperties) * size);
2811 bool operator==(const StyleResolver::MatchRanges& a, const StyleResolver::MatchRanges& b)
2813 return a.firstUARule == b.firstUARule
2814 && a.lastUARule == b.lastUARule
2815 && a.firstAuthorRule == b.firstAuthorRule
2816 && a.lastAuthorRule == b.lastAuthorRule
2817 && a.firstUserRule == b.firstUserRule
2818 && a.lastUserRule == b.lastUserRule;
2821 bool operator!=(const StyleResolver::MatchRanges& a, const StyleResolver::MatchRanges& b)
2826 bool operator==(const StyleResolver::MatchedProperties& a, const StyleResolver::MatchedProperties& b)
2828 return a.properties == b.properties && a.linkMatchType == b.linkMatchType;
2831 bool operator!=(const StyleResolver::MatchedProperties& a, const StyleResolver::MatchedProperties& b)
2836 const StyleResolver::MatchedPropertiesCacheItem* StyleResolver::findFromMatchedPropertiesCache(unsigned hash, const MatchResult& matchResult)
2840 MatchedPropertiesCache::iterator it = m_matchedPropertiesCache.find(hash);
2841 if (it == m_matchedPropertiesCache.end())
2843 MatchedPropertiesCacheItem& cacheItem = it->second;
2845 size_t size = matchResult.matchedProperties.size();
2846 if (size != cacheItem.matchedProperties.size())
2848 for (size_t i = 0; i < size; ++i) {
2849 if (matchResult.matchedProperties[i] != cacheItem.matchedProperties[i])
2852 if (cacheItem.ranges != matchResult.ranges)
2857 void StyleResolver::addToMatchedPropertiesCache(const RenderStyle* style, const RenderStyle* parentStyle, unsigned hash, const MatchResult& matchResult)
2859 static unsigned matchedDeclarationCacheAdditionsBetweenSweeps = 100;
2860 if (++m_matchedPropertiesCacheAdditionsSinceLastSweep >= matchedDeclarationCacheAdditionsBetweenSweeps) {
2861 sweepMatchedPropertiesCache();
2862 m_matchedPropertiesCacheAdditionsSinceLastSweep = 0;
2866 MatchedPropertiesCacheItem cacheItem;
2867 cacheItem.matchedProperties.append(matchResult.matchedProperties);
2868 cacheItem.ranges = matchResult.ranges;
2869 // Note that we don't cache the original RenderStyle instance. It may be further modified.
2870 // The RenderStyle in the cache is really just a holder for the substructures and never used as-is.
2871 cacheItem.renderStyle = RenderStyle::clone(style);
2872 cacheItem.parentRenderStyle = RenderStyle::clone(parentStyle);
2873 m_matchedPropertiesCache.add(hash, cacheItem);
2876 void StyleResolver::invalidateMatchedPropertiesCache()
2878 m_matchedPropertiesCache.clear();
2881 static bool isCacheableInMatchedPropertiesCache(const Element* element, const RenderStyle* style, const RenderStyle* parentStyle)
2883 // FIXME: CSSPropertyWebkitWritingMode modifies state when applying to document element. We can't skip the applying by caching.
2884 if (element == element->document()->documentElement() && element->document()->writingModeSetOnDocumentElement())
2886 if (style->unique() || (style->styleType() != NOPSEUDO && parentStyle->unique()))
2888 if (style->hasAppearance())
2890 if (style->zoom() != RenderStyle::initialZoom())
2892 // The cache assumes static knowledge about which properties are inherited.
2893 if (parentStyle->hasExplicitlyInheritedProperties())
2898 void StyleResolver::applyMatchedProperties(const MatchResult& matchResult, const Element* element)
2901 unsigned cacheHash = matchResult.isCacheable ? computeMatchedPropertiesHash(matchResult.matchedProperties.data(), matchResult.matchedProperties.size()) : 0;
2902 bool applyInheritedOnly = false;
2903 const MatchedPropertiesCacheItem* cacheItem = 0;
2904 if (cacheHash && (cacheItem = findFromMatchedPropertiesCache(cacheHash, matchResult))) {
2905 // We can build up the style by copying non-inherited properties from an earlier style object built using the same exact
2906 // style declarations. We then only need to apply the inherited properties, if any, as their values can depend on the
2907 // element context. This is fast and saves memory by reusing the style data structures.
2908 m_style->copyNonInheritedFrom(cacheItem->renderStyle.get());
2909 if (m_parentStyle->inheritedDataShared(cacheItem->parentRenderStyle.get()) && !isAtShadowBoundary(element)) {
2910 EInsideLink linkStatus = m_style->insideLink();
2911 // If the cache item parent style has identical inherited properties to the current parent style then the
2912 // resulting style will be identical too. We copy the inherited properties over from the cache and are done.
2913 m_style->inheritFrom(cacheItem->renderStyle.get());
2915 // Unfortunately the link status is treated like an inherited property. We need to explicitly restore it.
2916 m_style->setInsideLink(linkStatus);
2919 applyInheritedOnly = true;
2922 #if ENABLE(CSS_VARIABLES)
2923 // First apply all variable definitions, as they may be used during application of later properties.
2924 applyMatchedProperties<VariableDefinitions>(matchResult, false, 0, matchResult.matchedProperties.size() - 1, applyInheritedOnly);
2925 applyMatchedProperties<VariableDefinitions>(matchResult, true, matchResult.ranges.firstAuthorRule, matchResult.ranges.lastAuthorRule, applyInheritedOnly);
2926 applyMatchedProperties<VariableDefinitions>(matchResult, true, matchResult.ranges.firstUserRule, matchResult.ranges.lastUserRule, applyInheritedOnly);
2927 applyMatchedProperties<VariableDefinitions>(matchResult, true, matchResult.ranges.firstUARule, matchResult.ranges.lastUARule, applyInheritedOnly);
2930 // Now we have all of the matched rules in the appropriate order. Walk the rules and apply
2931 // high-priority properties first, i.e., those properties that other properties depend on.
2932 // The order is (1) high-priority not important, (2) high-priority important, (3) normal not important
2933 // and (4) normal important.
2934 m_lineHeightValue = 0;
2935 applyMatchedProperties<HighPriorityProperties>(matchResult, false, 0, matchResult.matchedProperties.size() - 1, applyInheritedOnly);
2936 applyMatchedProperties<HighPriorityProperties>(matchResult, true, matchResult.ranges.firstAuthorRule, matchResult.ranges.lastAuthorRule, applyInheritedOnly);
2937 applyMatchedProperties<HighPriorityProperties>(matchResult, true, matchResult.ranges.firstUserRule, matchResult.ranges.lastUserRule, applyInheritedOnly);
2938 applyMatchedProperties<HighPriorityProperties>(matchResult, true, matchResult.ranges.firstUARule, matchResult.ranges.lastUARule, applyInheritedOnly);
2940 if (cacheItem && cacheItem->renderStyle->effectiveZoom() != m_style->effectiveZoom()) {
2942 applyInheritedOnly = false;
2945 // If our font got dirtied, go ahead and update it now.
2948 // Line-height is set when we are sure we decided on the font-size.
2949 if (m_lineHeightValue)
2950 applyProperty(CSSPropertyLineHeight, m_lineHeightValue);
2952 // Many properties depend on the font. If it changes we just apply all properties.
2953 if (cacheItem && cacheItem->renderStyle->fontDescription() != m_style->fontDescription())
2954 applyInheritedOnly = false;
2956 // Now do the normal priority UA properties.
2957 applyMatchedProperties<LowPriorityProperties>(matchResult, false, matchResult.ranges.firstUARule, matchResult.ranges.lastUARule, applyInheritedOnly);
2959 // Cache our border and background so that we can examine them later.
2960 cacheBorderAndBackground();
2962 // Now do the author and user normal priority properties and all the !important properties.
2963 applyMatchedProperties<LowPriorityProperties>(matchResult, false, matchResult.ranges.lastUARule + 1, matchResult.matchedProperties.size() - 1, applyInheritedOnly);
2964 applyMatchedProperties<LowPriorityProperties>(matchResult, true, matchResult.ranges.firstAuthorRule, matchResult.ranges.lastAuthorRule, applyInheritedOnly);
2965 applyMatchedProperties<LowPriorityProperties>(matchResult, true, matchResult.ranges.firstUserRule, matchResult.ranges.lastUserRule, applyInheritedOnly);
2966 applyMatchedProperties<LowPriorityProperties>(matchResult, true, matchResult.ranges.firstUARule, matchResult.ranges.lastUARule, applyInheritedOnly);
2968 // Start loading resources referenced by this style.
2969 loadPendingResources();
2971 ASSERT(!m_fontDirty);
2973 if (cacheItem || !cacheHash)
2975 if (!isCacheableInMatchedPropertiesCache(m_element, m_style.get(), m_parentStyle))
2977 addToMatchedPropertiesCache(m_style.get(), m_parentStyle, cacheHash, matchResult);
2980 static inline bool comparePageRules(const StyleRulePage* r1, const StyleRulePage* r2)
2982 return r1->selector()->specificity() < r2->selector()->specificity();
2985 void StyleResolver::matchPageRules(MatchResult& result, RuleSet* rules, bool isLeftPage, bool isFirstPage, const String& pageName)
2990 Vector<StyleRulePage*> matchedPageRules;
2991 matchPageRulesForList(matchedPageRules, rules->pageRules(), isLeftPage, isFirstPage, pageName);
2992 if (matchedPageRules.isEmpty())
2995 std::stable_sort(matchedPageRules.begin(), matchedPageRules.end(), comparePageRules);
2997 for (unsigned i = 0; i < matchedPageRules.size(); i++)
2998 addMatchedProperties(result, matchedPageRules[i]->properties());
3001 void StyleResolver::matchPageRulesForList(Vector<StyleRulePage*>& matchedRules, const Vector<StyleRulePage*>& rules, bool isLeftPage, bool isFirstPage, const String& pageName)
3003 unsigned size = rules.size();
3004 for (unsigned i = 0; i < size; ++i) {
3005 StyleRulePage* rule = rules[i];
3006 const AtomicString& selectorLocalName = rule->selector()->tag().localName();
3007 if (selectorLocalName != starAtom && selectorLocalName != pageName)
3009 CSSSelector::PseudoType pseudoType = rule->selector()->pseudoType();
3010 if ((pseudoType == CSSSelector::PseudoLeftPage && !isLeftPage)
3011 || (pseudoType == CSSSelector::PseudoRightPage && isLeftPage)
3012 || (pseudoType == CSSSelector::PseudoFirstPage && !isFirstPage))
3015 // If the rule has no properties to apply, then ignore it.
3016 const StylePropertySet* properties = rule->properties();
3017 if (!properties || properties->isEmpty())
3020 // Add this rule to our list of matched rules.
3021 matchedRules.append(rule);
3025 bool StyleResolver::isLeftPage(int pageIndex) const
3027 bool isFirstPageLeft = false;
3028 if (!m_rootElementStyle->isLeftToRightDirection())
3029 isFirstPageLeft = true;
3031 return (pageIndex + (isFirstPageLeft ? 1 : 0)) % 2;
3034 bool StyleResolver::isFirstPage(int pageIndex) const
3036 // FIXME: In case of forced left/right page, page at index 1 (not 0) can be the first page.
3037 return (!pageIndex);
3040 String StyleResolver::pageName(int /* pageIndex */) const
3042 // FIXME: Implement page index to page name mapping.
3046 template <class ListType>
3047 static void collectCSSOMWrappers(HashMap<StyleRule*, RefPtr<CSSStyleRule> >& wrapperMap, ListType* listType)
3051 unsigned size = listType->length();
3052 for (unsigned i = 0; i < size; ++i) {
3053 CSSRule* cssRule = listType->item(i);
3054 if (cssRule->isImportRule())
3055 collectCSSOMWrappers(wrapperMap, static_cast<CSSImportRule*>(cssRule)->styleSheet());
3056 else if (cssRule->isMediaRule())
3057 collectCSSOMWrappers(wrapperMap, static_cast<CSSMediaRule*>(cssRule));
3058 #if ENABLE(CSS_REGIONS)
3059 else if (cssRule->isRegionRule())
3060 collectCSSOMWrappers(wrapperMap, static_cast<WebKitCSSRegionRule*>(cssRule));
3062 else if (cssRule->isStyleRule()) {
3063 CSSStyleRule* cssStyleRule = static_cast<CSSStyleRule*>(cssRule);
3064 wrapperMap.add(cssStyleRule->styleRule(), cssStyleRule);
3069 static void collectCSSOMWrappers(HashMap<StyleRule*, RefPtr<CSSStyleRule> >& wrapperMap, HashSet<RefPtr<CSSStyleSheet> >& sheetWrapperSet, StyleSheetContents* styleSheet)
3073 RefPtr<CSSStyleSheet> styleSheetWrapper = CSSStyleSheet::create(styleSheet);
3074 sheetWrapperSet.add(styleSheetWrapper);
3075 collectCSSOMWrappers(wrapperMap, styleSheetWrapper.get());
3078 static void collectCSSOMWrappers(HashMap<StyleRule*, RefPtr<CSSStyleRule> >& wrapperMap, Document* document)
3080 const Vector<RefPtr<StyleSheet> >& styleSheets = document->styleSheets()->vector();
3081 for (unsigned i = 0; i < styleSheets.size(); ++i) {
3082 StyleSheet* styleSheet = styleSheets[i].get();
3083 if (!styleSheet->isCSSStyleSheet())
3085 collectCSSOMWrappers(wrapperMap, static_cast<CSSStyleSheet*>(styleSheet));
3087 collectCSSOMWrappers(wrapperMap, document->pageUserSheet());
3089 const Vector<RefPtr<CSSStyleSheet> >* pageGroupUserSheets = document->pageGroupUserSheets();
3090 if (pageGroupUserSheets) {
3091 for (size_t i = 0, size = pageGroupUserSheets->size(); i < size; ++i)
3092 collectCSSOMWrappers(wrapperMap, pageGroupUserSheets->at(i).get());
3096 const Vector<RefPtr<CSSStyleSheet> >* documentUserSheets = document->documentUserSheets();
3097 if (documentUserSheets) {
3098 for (size_t i = 0, size = documentUserSheets->size(); i < size; ++i)
3099 collectCSSOMWrappers(wrapperMap, documentUserSheets->at(i).get());
3104 CSSStyleRule* StyleResolver::ensureFullCSSOMWrapperForInspector(StyleRule* rule)
3106 if (m_styleRuleToCSSOMWrapperMap.isEmpty()) {
3107 collectCSSOMWrappers(m_styleRuleToCSSOMWrapperMap, m_styleSheetCSSOMWrapperSet, simpleDefaultStyleSheet);
3108 collectCSSOMWrappers(m_styleRuleToCSSOMWrapperMap, m_styleSheetCSSOMWrapperSet, defaultStyleSheet);
3109 collectCSSOMWrappers(m_styleRuleToCSSOMWrapperMap, m_styleSheetCSSOMWrapperSet, quirksStyleSheet);
3110 collectCSSOMWrappers(m_styleRuleToCSSOMWrapperMap, m_styleSheetCSSOMWrapperSet, svgStyleSheet);
3111 collectCSSOMWrappers(m_styleRuleToCSSOMWrapperMap, m_styleSheetCSSOMWrapperSet, mathMLStyleSheet);
3112 collectCSSOMWrappers(m_styleRuleToCSSOMWrapperMap, m_styleSheetCSSOMWrapperSet, mediaControlsStyleSheet);
3113 collectCSSOMWrappers(m_styleRuleToCSSOMWrapperMap, m_styleSheetCSSOMWrapperSet, fullscreenStyleSheet);
3115 collectCSSOMWrappers(m_styleRuleToCSSOMWrapperMap, document());
3117 return m_styleRuleToCSSOMWrapperMap.get(rule).get();
3120 void StyleResolver::applyPropertyToStyle(CSSPropertyID id, CSSValue* value, RenderStyle* style)
3123 initForStyleResolve(0, style);
3125 applyPropertyToCurrentStyle(id, value);
3128 void StyleResolver::applyPropertyToCurrentStyle(CSSPropertyID id, CSSValue* value)
3131 applyProperty(id, value);
3134 inline bool isValidVisitedLinkProperty(CSSPropertyID id)
3137 case CSSPropertyBackgroundColor:
3138 case CSSPropertyBorderLeftColor:
3139 case CSSPropertyBorderRightColor:
3140 case CSSPropertyBorderTopColor:
3141 case CSSPropertyBorderBottomColor:
3142 case CSSPropertyColor:
3143 case CSSPropertyOutlineColor:
3144 case CSSPropertyWebkitColumnRuleColor:
3145 case CSSPropertyWebkitTextEmphasisColor:
3146 case CSSPropertyWebkitTextFillColor:
3147 case CSSPropertyWebkitTextStrokeColor:
3148 // Also allow shorthands so that inherit/initial still work.
3149 case CSSPropertyBackground:
3150 case CSSPropertyBorderLeft:
3151 case CSSPropertyBorderRight:
3152 case CSSPropertyBorderTop:
3153 case CSSPropertyBorderBottom:
3154 case CSSPropertyOutline:
3155 case CSSPropertyWebkitColumnRule:
3157 case CSSPropertyFill:
3158 case CSSPropertyStroke:
3168 // http://dev.w3.org/csswg/css3-regions/#the-at-region-style-rule
3169 // FIXME: add incremental support for other region styling properties.
3170 inline bool StyleResolver::isValidRegionStyleProperty(CSSPropertyID id)
3173 case CSSPropertyBackgroundColor:
3174 case CSSPropertyColor:
3183 // SVG handles zooming in a different way compared to CSS. The whole document is scaled instead
3184 // of each individual length value in the render style / tree. CSSPrimitiveValue::computeLength*()
3185 // multiplies each resolved length with the zoom multiplier - so for SVG we need to disable that.
3186 // Though all CSS values that can be applied to outermost <svg> elements (width/height/border/padding...)
3187 // need to respect the scaling. RenderBox (the parent class of RenderSVGRoot) grabs values like
3188 // width/height/border/padding/... from the RenderStyle -> for SVG these values would never scale,
3189 // if we'd pass a 1.0 zoom factor everyhwere. So we only pass a zoom factor of 1.0 for specific
3190 // properties that are NOT allowed to scale within a zoomed SVG document (letter/word-spacing/font-size).
3191 bool StyleResolver::useSVGZoomRules()
3193 return m_element && m_element->isSVGElement();
3196 static bool createGridTrackBreadth(CSSPrimitiveValue* primitiveValue, StyleResolver* selector, Length& length)
3198 Length workingLength = primitiveValue->convertToLength<FixedIntegerConversion | PercentConversion | ViewportPercentageConversion | AutoConversion>(selector->style(), selector->rootElementStyle(), selector->style()->effectiveZoom());
3199 if (workingLength.isUndefined())
3202 if (primitiveValue->isLength())
3203 workingLength.setQuirk(primitiveValue->isQuirkValue());
3205 length = workingLength;
3209 static bool createGridTrackList(CSSValue* value, Vector<Length>& lengths, StyleResolver* selector)
3212 if (value->isPrimitiveValue()) {
3213 CSSPrimitiveValue* primitiveValue = static_cast<CSSPrimitiveValue*>(value);
3214 if (primitiveValue->getIdent() == CSSValueNone) {
3215 lengths.append(Length(Undefined));
3221 if (value->isValueList()) {
3222 for (CSSValueListIterator i = value; i.hasMore(); i.advance()) {
3223 CSSValue* currValue = i.value();
3224 if (!currValue->isPrimitiveValue())
3228 if (!createGridTrackBreadth(static_cast<CSSPrimitiveValue*>(currValue), selector, length))
3231 lengths.append(length);
3240 static bool createGridPosition(CSSValue* value, Length& position)
3242 // For now, we only accept: <integer> | 'auto'
3243 if (!value->isPrimitiveValue())
3246 CSSPrimitiveValue* primitiveValue = static_cast<CSSPrimitiveValue*>(value);
3247 if (primitiveValue->getIdent() == CSSValueAuto)
3250 ASSERT(primitiveValue->isNumber());
3251 position.setValue(primitiveValue->getIntValue());
3255 #if ENABLE(CSS_VARIABLES)
3256 static bool hasVariableReference(CSSValue* value)
3258 if (value->isPrimitiveValue() && static_cast<CSSPrimitiveValue*>(value)->isVariableName())
3261 for (CSSValueListIterator i = value; i.hasMore(); i.advance()) {
3262 if (hasVariableReference(i.value()))
3269 void StyleResolver::resolveVariables(CSSPropertyID id, CSSValue* value, Vector<std::pair<CSSPropertyID, String> >& knownExpressions)
3271 std::pair<CSSPropertyID, String> expression(id, value->serializeResolvingVariables(*style()->variables()));
3273 if (knownExpressions.contains(expression))
3274 return; // cycle detected.
3276 knownExpressions.append(expression);
3278 // 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.
3279 RefPtr<StylePropertySet> resultSet = StylePropertySet::create();
3280 if (!CSSParser::parseValue(resultSet.get(), id, expression.second, false, document()))
3281 return; // expression failed to parse.
3283 for (unsigned i = 0; i < resultSet->propertyCount(); i++) {
3284 const CSSProperty& property = resultSet->propertyAt(i);
3285 if (property.id() != CSSPropertyVariable && hasVariableReference(property.value()))
3286 resolveVariables(property.id(), property.value(), knownExpressions);
3288 applyProperty(property.id(), property.value());
3293 void StyleResolver::applyProperty(CSSPropertyID id, CSSValue* value)
3295 #if ENABLE(CSS_VARIABLES)
3296 if (id != CSSPropertyVariable && hasVariableReference(value)) {
3297 Vector<std::pair<CSSPropertyID, String> > knownExpressions;
3298 resolveVariables(id, value, knownExpressions);
3303 bool isInherit = m_parentNode && value->isInheritedValue();
3304 bool isInitial = value->isInitialValue() || (!m_parentNode && value->isInheritedValue());
3306 ASSERT(!isInherit || !isInitial); // isInherit -> !isInitial && isInitial -> !isInherit
3308 if (!applyPropertyToRegularStyle() && (!applyPropertyToVisitedLinkStyle() || !isValidVisitedLinkProperty(id))) {
3309 // Limit the properties that can be applied to only the ones honored by :visited.
3313 if (isInherit && m_parentStyle && !m_parentStyle->hasExplicitlyInheritedProperties() && !CSSProperty::isInheritedProperty(id))
3314 m_parentStyle->setHasExplicitlyInheritedProperties();
3316 #if ENABLE(CSS_VARIABLES)
3317 if (id == CSSPropertyVariable) {
3318 ASSERT(value->isVariableValue());
3319 CSSVariableValue* variable = static_cast<CSSVariableValue*>(value);
3320 ASSERT(!variable->name().isEmpty());
3321 ASSERT(!variable->value().isEmpty());
3322 m_style->setVariable(variable->name(), variable->value());
3327 // Check lookup table for implementations and use when available.
3328 const PropertyHandler& handler = m_styleBuilder.propertyHandler(id);
3329 if (handler.isValid()) {
3331 handler.applyInheritValue(this);
3333 handler.applyInitialValue(this);
3335 handler.applyValue(this, value);
3339 CSSPrimitiveValue* primitiveValue = value->isPrimitiveValue() ? static_cast<CSSPrimitiveValue*>(value) : 0;
3341 float zoomFactor = m_style->effectiveZoom();
3343 // What follows is a list that maps the CSS properties into their corresponding front-end
3344 // RenderStyle values. Shorthands (e.g. border, background) occur in this list as well and
3345 // are only hit when mapping "inherit" or "initial" into front-end values.
3348 case CSSPropertyContent:
3349 // list of string, uri, counter, attr, i
3351 // FIXME: In CSS3, it will be possible to inherit content. In CSS2 it is not. This
3352 // note is a reminder that eventually "inherit" needs to be supported.
3355 m_style->clearContent();
3359 if (!value->isValueList())
3362 bool didSet = false;
3363 for (CSSValueListIterator i = value; i.hasMore(); i.advance()) {
3364 CSSValue* item = i.value();
3365 if (item->isImageGeneratorValue()) {
3366 m_style->setContent(StyleGeneratedImage::create(static_cast<CSSImageGeneratorValue*>(item)), didSet);
3368 #if ENABLE(CSS_IMAGE_SET)
3369 } else if (item->isImageSetValue()) {
3370 m_style->setContent(setOrPendingFromValue(CSSPropertyContent, static_cast<CSSImageSetValue*>(item)), didSet);
3375 if (item->isImageValue()) {
3376 m_style->setContent(cachedOrPendingFromValue(CSSPropertyContent, static_cast<CSSImageValue*>(item)), didSet);
3381 if (!item->isPrimitiveValue())
3384 CSSPrimitiveValue* contentValue = static_cast<CSSPrimitiveValue*>(item);
3386 if (contentValue->isString()) {
3387 m_style->setContent(contentValue->getStringValue().impl(), didSet);
3389 } else if (contentValue->isAttr()) {
3390 // FIXME: Can a namespace be specified for an attr(foo)?
3391 if (m_style->styleType() == NOPSEUDO)
3392 m_style->setUnique();
3394 m_parentStyle->setUnique();
3395 QualifiedName attr(nullAtom, contentValue->getStringValue().impl(), nullAtom);
3396 const AtomicString& value = m_element->getAttribute(attr);
3397 m_style->setContent(value.isNull() ? emptyAtom : value.impl(), didSet);
3399 // register the fact that the attribute value affects the style
3400 m_features.attrsInRules.add(attr.localName().impl());
3401 } else if (contentValue->isCounter()) {
3402 Counter* counterValue = contentValue->getCounterValue();
3403 EListStyleType listSty