2 * Copyright (C) 1999 Lars Knoll (knoll@kde.org)
3 * (C) 2004-2005 Allan Sandfeld Jensen (kde@carewolf.com)
4 * Copyright (C) 2006, 2007 Nicholas Shanks (webkit@nickshanks.com)
5 * Copyright (C) 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012 Apple Inc. All rights reserved.
6 * Copyright (C) 2007 Alexey Proskuryakov <ap@webkit.org>
7 * Copyright (C) 2007, 2008 Eric Seidel <eric@webkit.org>
8 * Copyright (C) 2008, 2009 Torch Mobile Inc. All rights reserved. (http://www.torchmobile.com/)
9 * Copyright (c) 2011, Code Aurora Forum. All rights reserved.
10 * Copyright (C) Research In Motion Limited 2011. All rights reserved.
12 * This library is free software; you can redistribute it and/or
13 * modify it under the terms of the GNU Library General Public
14 * License as published by the Free Software Foundation; either
15 * version 2 of the License, or (at your option) any later version.
17 * This library is distributed in the hope that it will be useful,
18 * but WITHOUT ANY WARRANTY; without even the implied warranty of
19 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
20 * Library General Public License for more details.
22 * You should have received a copy of the GNU Library General Public License
23 * along with this library; see the file COPYING.LIB. If not, write to
24 * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
25 * Boston, MA 02110-1301, USA.
29 #include "CSSStyleSelector.h"
31 #include "Attribute.h"
32 #include "CachedImage.h"
33 #include "CalculationValue.h"
34 #include "ContentData.h"
36 #include "CounterContent.h"
37 #include "CSSBorderImage.h"
38 #include "CSSCalculationValue.h"
39 #include "CSSCursorImageValue.h"
40 #include "CSSFontFaceRule.h"
41 #include "CSSFontSelector.h"
42 #include "CSSImportRule.h"
43 #include "CSSLineBoxContainValue.h"
44 #include "CSSMediaRule.h"
45 #include "CSSPageRule.h"
46 #include "CSSParser.h"
47 #include "CSSPrimitiveValueMappings.h"
48 #include "CSSPropertyNames.h"
49 #include "CSSReflectValue.h"
50 #include "CSSRuleList.h"
51 #include "CSSSelector.h"
52 #include "CSSSelectorList.h"
53 #include "CSSStyleApplyProperty.h"
54 #include "CSSStyleRule.h"
55 #include "CSSStyleSheet.h"
56 #include "CSSTimingFunctionValue.h"
57 #include "CSSValueList.h"
58 #include "CursorList.h"
59 #include "FontFeatureValue.h"
60 #include "FontValue.h"
62 #include "FrameSelection.h"
63 #include "FrameView.h"
64 #include "HTMLDocument.h"
65 #include "HTMLElement.h"
66 #include "HTMLInputElement.h"
67 #include "HTMLNames.h"
68 #include "HTMLOptionElement.h"
69 #include "HTMLProgressElement.h"
70 #include "HTMLStyleElement.h"
71 #include "HTMLTextAreaElement.h"
72 #include "InspectorInstrumentation.h"
73 #include "KeyframeList.h"
75 #include "LocaleToScriptMapping.h"
76 #include "Matrix3DTransformOperation.h"
77 #include "MatrixTransformOperation.h"
78 #include "MediaList.h"
79 #include "MediaQueryEvaluator.h"
80 #include "NodeRenderStyle.h"
82 #include "PageGroup.h"
84 #include "PerspectiveTransformOperation.h"
85 #include "QuotesData.h"
87 #include "RenderRegion.h"
88 #include "RenderScrollbar.h"
89 #include "RenderScrollbarTheme.h"
90 #include "RenderStyleConstants.h"
91 #include "RenderTheme.h"
92 #include "RotateTransformOperation.h"
93 #include "RuntimeEnabledFeatures.h"
94 #include "SVGDocumentExtensions.h"
95 #include "SVGFontFaceElement.h"
96 #include "ScaleTransformOperation.h"
97 #include "SecurityOrigin.h"
99 #include "ShadowData.h"
100 #include "ShadowRoot.h"
101 #include "ShadowValue.h"
102 #include "SkewTransformOperation.h"
103 #include "StyleCachedImage.h"
104 #include "StylePendingImage.h"
105 #include "StyleRule.h"
106 #include "StyleGeneratedImage.h"
107 #include "StyleSheetList.h"
109 #include "TransformationMatrix.h"
110 #include "TranslateTransformOperation.h"
111 #include "UserAgentStyleSheets.h"
112 #include "WebKitCSSKeyframeRule.h"
113 #include "WebKitCSSKeyframesRule.h"
114 #include "WebKitCSSRegionRule.h"
115 #include "WebKitCSSTransformValue.h"
116 #include "WebKitFontFamilyNames.h"
117 #include "XMLNames.h"
118 #include <wtf/StdLibExtras.h>
119 #include <wtf/Vector.h>
121 #if ENABLE(CSS_FILTERS)
122 #include "FilterOperation.h"
123 #include "WebKitCSSFilterValue.h"
126 #if ENABLE(DASHBOARD_SUPPORT)
127 #include "DashboardRegion.h"
131 #include "SVGElement.h"
132 #include "SVGNames.h"
135 #if ENABLE(CSS_SHADERS)
136 #include "CustomFilterNumberParameter.h"
137 #include "CustomFilterOperation.h"
138 #include "CustomFilterParameter.h"
139 #include "StyleCachedShader.h"
140 #include "StyleCustomFilterProgram.h"
141 #include "StylePendingShader.h"
142 #include "StyleShader.h"
143 #include "WebKitCSSShaderValue.h"
146 #if ENABLE(CSS_IMAGE_SET)
147 #include "CSSImageSetValue.h"
148 #include "StyleCachedImageSet.h"
155 using namespace HTMLNames;
157 #define HANDLE_INHERIT(prop, Prop) \
159 m_style->set##Prop(m_parentStyle->prop()); \
163 #define HANDLE_INHERIT_AND_INITIAL(prop, Prop) \
164 HANDLE_INHERIT(prop, Prop) \
166 m_style->set##Prop(RenderStyle::initial##Prop()); \
170 #define HANDLE_INHERIT_AND_INITIAL_WITH_VALUE(prop, Prop, Value) \
171 HANDLE_INHERIT(prop, Prop) \
173 m_style->set##Prop(RenderStyle::initial##Value());\
177 #define HANDLE_INHERIT_AND_INITIAL_AND_PRIMITIVE(prop, Prop) \
178 HANDLE_INHERIT_AND_INITIAL(prop, Prop) \
179 if (primitiveValue) \
180 m_style->set##Prop(*primitiveValue);
184 RuleData(StyleRule*, CSSSelector*, unsigned position, bool hasDocumentSecurityOrigin, bool canUseFastCheckSelector, bool inRegionRule);
186 unsigned position() const { return m_position; }
187 StyleRule* rule() const { return m_rule; }
188 CSSSelector* selector() const { return m_selector; }
190 bool hasFastCheckableSelector() const { return m_hasFastCheckableSelector; }
191 bool hasMultipartSelector() const { return m_hasMultipartSelector; }
192 bool hasRightmostSelectorMatchingHTMLBasedOnRuleHash() const { return m_hasRightmostSelectorMatchingHTMLBasedOnRuleHash; }
193 bool containsUncommonAttributeSelector() const { return m_containsUncommonAttributeSelector; }
194 unsigned specificity() const { return m_specificity; }
195 unsigned linkMatchType() const { return m_linkMatchType; }
196 bool hasDocumentSecurityOrigin() const { return m_hasDocumentSecurityOrigin; }
197 bool isInRegionRule() const { return m_isInRegionRule; }
199 // Try to balance between memory usage (there can be lots of RuleData objects) and good filtering performance.
200 static const unsigned maximumIdentifierCount = 4;
201 const unsigned* descendantSelectorIdentifierHashes() const { return m_descendantSelectorIdentifierHashes; }
205 CSSSelector* m_selector;
206 unsigned m_specificity;
207 // This number was picked fairly arbitrarily. We can probably lower it if we need to.
208 // Some simple testing showed <100,000 RuleData's on large sites.
209 unsigned m_position : 24;
210 unsigned m_hasFastCheckableSelector : 1;
211 unsigned m_hasMultipartSelector : 1;
212 unsigned m_hasRightmostSelectorMatchingHTMLBasedOnRuleHash : 1;
213 unsigned m_containsUncommonAttributeSelector : 1;
214 unsigned m_linkMatchType : 2; // SelectorChecker::LinkMatchMask
215 unsigned m_hasDocumentSecurityOrigin : 1;
216 unsigned m_isInRegionRule : 1;
217 // Use plain array instead of a Vector to minimize memory overhead.
218 unsigned m_descendantSelectorIdentifierHashes[maximumIdentifierCount];
221 struct SameSizeAsRuleData {
229 COMPILE_ASSERT(sizeof(RuleData) == sizeof(SameSizeAsRuleData), RuleData_should_stay_small);
232 WTF_MAKE_NONCOPYABLE(RuleSet);
234 static PassOwnPtr<RuleSet> create() { return adoptPtr(new RuleSet); }
236 typedef HashMap<AtomicStringImpl*, OwnPtr<Vector<RuleData> > > AtomRuleMap;
238 void addRulesFromSheet(CSSStyleSheet*, const MediaQueryEvaluator&, CSSStyleSelector* = 0, const ContainerNode* = 0);
240 void addStyleRule(StyleRule*, bool hasDocumentSecurityOrigin, bool canUseFastCheckSelector, bool isInRegionRule = false);
241 void addRule(StyleRule*, CSSSelector*, bool hasDocumentSecurityOrigin, bool canUseFastCheckSelector, bool isInRegionRule = false);
242 void addPageRule(StyleRulePage*);
243 void addToRuleSet(AtomicStringImpl* key, AtomRuleMap&, const RuleData&);
244 void addRegionRule(StyleRuleRegion*, bool hasDocumentSecurityOrigin);
246 void disableAutoShrinkToFit() { m_autoShrinkToFitEnabled = false; }
248 const CSSStyleSelector::Features& features() const { return m_features; }
250 const Vector<RuleData>* idRules(AtomicStringImpl* key) const { return m_idRules.get(key); }
251 const Vector<RuleData>* classRules(AtomicStringImpl* key) const { return m_classRules.get(key); }
252 const Vector<RuleData>* tagRules(AtomicStringImpl* key) const { return m_tagRules.get(key); }
253 const Vector<RuleData>* shadowPseudoElementRules(AtomicStringImpl* key) const { return m_shadowPseudoElementRules.get(key); }
254 const Vector<RuleData>* linkPseudoClassRules() const { return &m_linkPseudoClassRules; }
255 const Vector<RuleData>* focusPseudoClassRules() const { return &m_focusPseudoClassRules; }
256 const Vector<RuleData>* universalRules() const { return &m_universalRules; }
257 const Vector<StyleRulePage*>& pageRules() const { return m_pageRules; }
262 AtomRuleMap m_idRules;
263 AtomRuleMap m_classRules;
264 AtomRuleMap m_tagRules;
265 AtomRuleMap m_shadowPseudoElementRules;
266 Vector<RuleData> m_linkPseudoClassRules;
267 Vector<RuleData> m_focusPseudoClassRules;
268 Vector<RuleData> m_universalRules;
269 Vector<StyleRulePage*> m_pageRules;
270 unsigned m_ruleCount;
271 bool m_autoShrinkToFitEnabled;
272 CSSStyleSelector::Features m_features;
274 struct RuleSetSelectorPair {
275 RuleSetSelectorPair(CSSSelector* selector, PassOwnPtr<RuleSet> ruleSet) : selector(selector), ruleSet(ruleSet) { }
276 RuleSetSelectorPair(const RuleSetSelectorPair& rs) : selector(rs.selector), ruleSet(const_cast<RuleSetSelectorPair*>(&rs)->ruleSet.release()) { }
277 CSSSelector* selector;
278 OwnPtr<RuleSet> ruleSet;
281 Vector<RuleSetSelectorPair> m_regionSelectorsAndRuleSets;
284 static RuleSet* defaultStyle;
285 static RuleSet* defaultQuirksStyle;
286 static RuleSet* defaultPrintStyle;
287 static RuleSet* defaultViewSourceStyle;
288 static CSSStyleSheet* simpleDefaultStyleSheet;
289 static CSSStyleSheet* defaultStyleSheet;
290 static CSSStyleSheet* quirksStyleSheet;
291 static CSSStyleSheet* svgStyleSheet;
292 static CSSStyleSheet* mathMLStyleSheet;
293 static CSSStyleSheet* mediaControlsStyleSheet;
294 static CSSStyleSheet* fullscreenStyleSheet;
296 RenderStyle* CSSStyleSelector::s_styleNotYetAvailable;
298 static void loadFullDefaultStyle();
299 static void loadSimpleDefaultStyle();
300 template <class ListType>
301 static void collectCSSOMWrappers(HashMap<StyleRule*, RefPtr<CSSStyleRule> >&, ListType*);
303 // FIXME: It would be nice to use some mechanism that guarantees this is in sync with the real UA stylesheet.
304 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}";
306 static inline bool elementCanUseSimpleDefaultStyle(Element* e)
308 return e->hasTagName(htmlTag) || e->hasTagName(headTag) || e->hasTagName(bodyTag) || e->hasTagName(divTag) || e->hasTagName(spanTag) || e->hasTagName(brTag) || e->hasTagName(aTag);
311 static const MediaQueryEvaluator& screenEval()
313 DEFINE_STATIC_LOCAL(const MediaQueryEvaluator, staticScreenEval, ("screen"));
314 return staticScreenEval;
317 static const MediaQueryEvaluator& printEval()
319 DEFINE_STATIC_LOCAL(const MediaQueryEvaluator, staticPrintEval, ("print"));
320 return staticPrintEval;
323 static StylePropertySet* leftToRightDeclaration()
325 DEFINE_STATIC_LOCAL(RefPtr<StylePropertySet>, leftToRightDecl, (StylePropertySet::create()));
326 if (leftToRightDecl->isEmpty())
327 leftToRightDecl->setProperty(CSSPropertyDirection, CSSValueLtr);
328 return leftToRightDecl.get();
331 static StylePropertySet* rightToLeftDeclaration()
333 DEFINE_STATIC_LOCAL(RefPtr<StylePropertySet>, rightToLeftDecl, (StylePropertySet::create()));
334 if (rightToLeftDecl->isEmpty())
335 rightToLeftDecl->setProperty(CSSPropertyDirection, CSSValueRtl);
336 return rightToLeftDecl.get();
339 CSSStyleSelector::CSSStyleSelector(Document* document, bool matchAuthorAndUserStyles)
340 : m_hasUAAppearance(false)
341 , m_backgroundData(BackgroundFillLayer)
342 , m_matchedPropertiesCacheAdditionsSinceLastSweep(0)
343 , m_checker(document, !document->inQuirksMode())
345 , m_rootElementStyle(0)
348 , m_regionForStyling(0)
349 , m_elementLinkState(NotInsideLink)
351 , m_lineHeightValue(0)
353 , m_matchAuthorAndUserStyles(matchAuthorAndUserStyles)
354 , m_sameOriginOnly(false)
355 , m_fontSelector(CSSFontSelector::create(document))
356 , m_applyPropertyToRegularStyle(true)
357 , m_applyPropertyToVisitedLinkStyle(false)
358 , m_applyProperty(CSSStyleApplyProperty::sharedCSSStyleApplyProperty())
359 #if ENABLE(CSS_SHADERS)
360 , m_hasPendingShaders(false)
362 #if ENABLE(STYLE_SCOPED)
363 , m_scopeStackParent(0)
366 Element* root = document->documentElement();
369 if (!root || elementCanUseSimpleDefaultStyle(root))
370 loadSimpleDefaultStyle();
372 loadFullDefaultStyle();
376 // construct document root element default style. this is needed
377 // to evaluate media queries that contain relative constraints, like "screen and (max-width: 10em)"
378 // This is here instead of constructor, because when constructor is run,
379 // document doesn't have documentElement
380 // NOTE: this assumes that element that gets passed to styleForElement -call
381 // is always from the document that owns the style selector
382 FrameView* view = document->view();
384 m_medium = adoptPtr(new MediaQueryEvaluator(view->mediaType()));
386 m_medium = adoptPtr(new MediaQueryEvaluator("all"));
389 m_rootDefaultStyle = styleForElement(root, 0, DisallowStyleSharing, MatchOnlyUserAgentRules);
391 if (m_rootDefaultStyle && view)
392 m_medium = adoptPtr(new MediaQueryEvaluator(view->mediaType(), view->frame(), m_rootDefaultStyle.get()));
394 m_authorStyle = RuleSet::create();
395 // Adding rules from multiple sheets, shrink at the end.
396 // Adding global rules from multiple sheets, shrink at the end.
397 // Note that there usually is only 1 sheet for scoped rules, so auto-shrink-to-fit is fine.
398 m_authorStyle->disableAutoShrinkToFit();
400 // FIXME: This sucks! The user sheet is reparsed every time!
401 OwnPtr<RuleSet> tempUserStyle = RuleSet::create();
402 if (CSSStyleSheet* pageUserSheet = document->pageUserSheet())
403 tempUserStyle->addRulesFromSheet(pageUserSheet, *m_medium, this);
404 if (const Vector<RefPtr<CSSStyleSheet> >* pageGroupUserSheets = document->pageGroupUserSheets()) {
405 unsigned length = pageGroupUserSheets->size();
406 for (unsigned i = 0; i < length; i++) {
407 if (pageGroupUserSheets->at(i)->isUserStyleSheet())
408 tempUserStyle->addRulesFromSheet(pageGroupUserSheets->at(i).get(), *m_medium, this);
410 m_authorStyle->addRulesFromSheet(pageGroupUserSheets->at(i).get(), *m_medium, this);
413 if (const Vector<RefPtr<CSSStyleSheet> >* documentUserSheets = document->documentUserSheets()) {
414 unsigned length = documentUserSheets->size();
415 for (unsigned i = 0; i < length; i++) {
416 if (documentUserSheets->at(i)->isUserStyleSheet())
417 tempUserStyle->addRulesFromSheet(documentUserSheets->at(i).get(), *m_medium, this);
419 m_authorStyle->addRulesFromSheet(documentUserSheets->at(i).get(), *m_medium, this);
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 appendAuthorStylesheets(0, document->styleSheets()->vector());
438 static PassOwnPtr<RuleSet> makeRuleSet(const Vector<CSSStyleSelector::RuleFeature>& rules)
440 size_t size = rules.size();
443 OwnPtr<RuleSet> ruleSet = RuleSet::create();
444 for (size_t i = 0; i < size; ++i)
445 ruleSet->addRule(rules[i].rule, rules[i].selector, rules[i].hasDocumentSecurityOrigin, false);
446 return ruleSet.release();
449 void CSSStyleSelector::collectFeatures()
452 // Collect all ids and rules using sibling selectors (:first-child and similar)
453 // in the current set of stylesheets. Style sharing code uses this information to reject
454 // sharing candidates.
455 m_features.add(defaultStyle->features());
456 m_features.add(m_authorStyle->features());
457 #if ENABLE(STYLE_SCOPED)
458 for (ScopedRuleSetMap::iterator it = m_scopedAuthorStyles.begin(); it != m_scopedAuthorStyles.end(); ++it)
459 m_features.add(it->second->features());
462 m_features.add(m_userStyle->features());
464 m_siblingRuleSet = makeRuleSet(m_features.siblingRules);
465 m_uncommonAttributeRuleSet = makeRuleSet(m_features.uncommonAttributeRules);
468 #if ENABLE(STYLE_SCOPED)
469 const ContainerNode* CSSStyleSelector::determineScope(const CSSStyleSheet* sheet)
473 if (!RuntimeEnabledFeatures::styleScopedEnabled())
476 Node* ownerNode = sheet->findStyleSheetOwnerNode();
477 if (!ownerNode || !ownerNode->isHTMLElement() || !ownerNode->hasTagName(HTMLNames::styleTag))
480 HTMLStyleElement* styleElement = static_cast<HTMLStyleElement*>(ownerNode);
481 if (!styleElement->scoped())
484 ContainerNode* parent = styleElement->parentNode();
488 return (parent->isElementNode() || parent->isShadowRoot()) ? parent : 0;
491 inline RuleSet* CSSStyleSelector::ruleSetForScope(const ContainerNode* scope) const
493 if (!scope->hasScopedHTMLStyleChild())
495 ScopedRuleSetMap::const_iterator it = m_scopedAuthorStyles.find(scope);
496 return it != m_scopedAuthorStyles.end() ? it->second.get() : 0;
500 void CSSStyleSelector::appendAuthorStylesheets(unsigned firstNew, const Vector<RefPtr<StyleSheet> >& stylesheets)
502 // This handles sheets added to the end of the stylesheet list only. In other cases the style resolver
503 // needs to be reconstructed. To handle insertions too the rule order numbers would need to be updated.
504 unsigned size = stylesheets.size();
505 for (unsigned i = firstNew; i < size; ++i) {
506 if (!stylesheets[i]->isCSSStyleSheet() || stylesheets[i]->disabled())
508 CSSStyleSheet* cssSheet = static_cast<CSSStyleSheet*>(stylesheets[i].get());
509 #if ENABLE(STYLE_SCOPED)
510 const ContainerNode* scope = determineScope(cssSheet);
512 ScopedRuleSetMap::AddResult addResult = m_scopedAuthorStyles.add(scope, nullptr);
513 if (addResult.isNewEntry)
514 addResult.iterator->second = RuleSet::create();
515 addResult.iterator->second->addRulesFromSheet(cssSheet, *m_medium, this, scope);
519 m_authorStyle->addRulesFromSheet(cssSheet, *m_medium, this);
520 if (!m_styleRuleToCSSOMWrapperMap.isEmpty())
521 collectCSSOMWrappers(m_styleRuleToCSSOMWrapperMap, cssSheet);
523 m_authorStyle->shrinkToFit();
526 if (document()->renderer() && document()->renderer()->style())
527 document()->renderer()->style()->font().update(fontSelector());
530 #if ENABLE(STYLE_SCOPED)
531 void CSSStyleSelector::setupScopeStack(const ContainerNode* parent)
533 // The scoping element stack shouldn't be used if <style scoped> isn't used anywhere.
534 ASSERT(!m_scopedAuthorStyles.isEmpty());
536 m_scopeStack.shrink(0);
537 for (; parent; parent = parent->parentOrHostNode()) {
538 RuleSet* ruleSet = ruleSetForScope(parent);
540 m_scopeStack.append(ScopeStackFrame(parent, ruleSet));
542 m_scopeStack.reverse();
543 m_scopeStackParent = parent;
546 void CSSStyleSelector::pushScope(const ContainerNode* scope, const ContainerNode* scopeParent)
548 // Shortcut: Don't bother with the scoping element stack if <style scoped> isn't used anywhere.
549 if (m_scopedAuthorStyles.isEmpty()) {
550 ASSERT(!m_scopeStackParent);
551 ASSERT(m_scopeStack.isEmpty());
554 // In some wacky cases during style resolve we may get invoked for random elements.
555 // Recreate the whole scoping element stack in such cases.
556 if (!scopeStackIsConsistent(scopeParent)) {
557 setupScopeStack(scope);
560 // Otherwise just push the parent onto the stack.
561 RuleSet* ruleSet = ruleSetForScope(scope);
563 m_scopeStack.append(ScopeStackFrame(scope, ruleSet));
564 m_scopeStackParent = scope;
567 void CSSStyleSelector::popScope(const ContainerNode* scope)
569 // Only bother to update the scoping element stack if it is consistent.
570 if (scopeStackIsConsistent(scope)) {
571 m_scopeStack.removeLast();
572 m_scopeStackParent = scope->parentOrHostNode();
577 void CSSStyleSelector::pushParentElement(Element* parent)
579 const ContainerNode* parentsParent = parent->parentOrHostElement();
581 // We are not always invoked consistently. For example, script execution can cause us to enter
582 // style recalc in the middle of tree building. We may also be invoked from somewhere within the tree.
583 // Reset the stack in this case, or if we see a new root element.
584 // Otherwise just push the new parent.
585 if (!parentsParent || m_checker.parentStackIsEmpty())
586 m_checker.setupParentStack(parent);
588 m_checker.pushParent(parent);
590 // Note: We mustn't skip ShadowRoot nodes for the scope stack.
591 pushScope(parent, parent->parentOrHostNode());
594 void CSSStyleSelector::popParentElement(Element* parent)
596 // Note that we may get invoked for some random elements in some wacky cases during style resolve.
597 // Pause maintaining the stack in this case.
598 if (m_checker.parentStackIsConsistent(parent))
599 m_checker.popParent();
603 void CSSStyleSelector::pushParentShadowRoot(const ShadowRoot* shadowRoot)
605 ASSERT(shadowRoot->host());
606 pushScope(shadowRoot, shadowRoot->host());
609 void CSSStyleSelector::popParentShadowRoot(const ShadowRoot* shadowRoot)
611 ASSERT(shadowRoot->host());
612 popScope(shadowRoot);
615 // This is a simplified style setting function for keyframe styles
616 void CSSStyleSelector::addKeyframeStyle(PassRefPtr<StyleRuleKeyframes> rule)
618 AtomicString s(rule->name());
619 m_keyframesRuleMap.set(s.impl(), rule);
622 CSSStyleSelector::~CSSStyleSelector()
624 m_fontSelector->clearDocument();
627 void CSSStyleSelector::sweepMatchedPropertiesCache()
629 // Look for cache entries containing a style declaration with a single ref and remove them.
630 // This may happen when an element attribute mutation causes it to swap out its Attribute::decl()
631 // for another CSSMappedAttributeDeclaration, potentially leaving this cache with the last ref.
632 Vector<unsigned, 16> toRemove;
633 MatchedPropertiesCache::iterator it = m_matchedPropertiesCache.begin();
634 MatchedPropertiesCache::iterator end = m_matchedPropertiesCache.end();
635 for (; it != end; ++it) {
636 Vector<MatchedProperties>& matchedProperties = it->second.matchedProperties;
637 for (size_t i = 0; i < matchedProperties.size(); ++i) {
638 if (matchedProperties[i].properties->hasOneRef()) {
639 toRemove.append(it->first);
644 for (size_t i = 0; i < toRemove.size(); ++i)
645 m_matchedPropertiesCache.remove(toRemove[i]);
648 CSSStyleSelector::Features::Features()
649 : usesFirstLineRules(false)
650 , usesBeforeAfterRules(false)
651 , usesLinkRules(false)
655 CSSStyleSelector::Features::~Features()
659 void CSSStyleSelector::Features::add(const CSSStyleSelector::Features& other)
661 HashSet<AtomicStringImpl*>::iterator end = other.idsInRules.end();
662 for (HashSet<AtomicStringImpl*>::iterator it = other.idsInRules.begin(); it != end; ++it)
664 end = other.attrsInRules.end();
665 for (HashSet<AtomicStringImpl*>::iterator it = other.attrsInRules.begin(); it != end; ++it)
666 attrsInRules.add(*it);
667 siblingRules.append(other.siblingRules);
668 uncommonAttributeRules.append(other.uncommonAttributeRules);
669 usesFirstLineRules = usesFirstLineRules || other.usesFirstLineRules;
670 usesBeforeAfterRules = usesBeforeAfterRules || other.usesBeforeAfterRules;
671 usesLinkRules = usesLinkRules || other.usesLinkRules;
674 void CSSStyleSelector::Features::clear()
677 attrsInRules.clear();
678 siblingRules.clear();
679 uncommonAttributeRules.clear();
680 usesFirstLineRules = false;
681 usesBeforeAfterRules = false;
682 usesLinkRules = false;
685 static CSSStyleSheet* parseUASheet(const String& str)
687 CSSStyleSheet* sheet = CSSStyleSheet::create().leakRef(); // leak the sheet on purpose
688 sheet->parseString(str);
692 static CSSStyleSheet* parseUASheet(const char* characters, unsigned size)
694 return parseUASheet(String(characters, size));
697 static void loadFullDefaultStyle()
699 if (simpleDefaultStyleSheet) {
700 ASSERT(defaultStyle);
701 ASSERT(defaultPrintStyle == defaultStyle);
703 simpleDefaultStyleSheet->deref();
704 defaultStyle = RuleSet::create().leakPtr();
705 defaultPrintStyle = RuleSet::create().leakPtr();
706 simpleDefaultStyleSheet = 0;
708 ASSERT(!defaultStyle);
709 defaultStyle = RuleSet::create().leakPtr();
710 defaultPrintStyle = RuleSet::create().leakPtr();
711 defaultQuirksStyle = RuleSet::create().leakPtr();
714 // Strict-mode rules.
715 String defaultRules = String(htmlUserAgentStyleSheet, sizeof(htmlUserAgentStyleSheet)) + RenderTheme::defaultTheme()->extraDefaultStyleSheet();
716 defaultStyleSheet = parseUASheet(defaultRules);
717 defaultStyle->addRulesFromSheet(defaultStyleSheet, screenEval());
718 defaultPrintStyle->addRulesFromSheet(defaultStyleSheet, printEval());
720 // Quirks-mode rules.
721 String quirksRules = String(quirksUserAgentStyleSheet, sizeof(quirksUserAgentStyleSheet)) + RenderTheme::defaultTheme()->extraQuirksStyleSheet();
722 quirksStyleSheet = parseUASheet(quirksRules);
723 defaultQuirksStyle->addRulesFromSheet(quirksStyleSheet, screenEval());
726 static void loadSimpleDefaultStyle()
728 ASSERT(!defaultStyle);
729 ASSERT(!simpleDefaultStyleSheet);
731 defaultStyle = RuleSet::create().leakPtr();
732 // There are no media-specific rules in the simple default style.
733 defaultPrintStyle = defaultStyle;
734 defaultQuirksStyle = RuleSet::create().leakPtr();
736 simpleDefaultStyleSheet = parseUASheet(simpleUserAgentStyleSheet, strlen(simpleUserAgentStyleSheet));
737 defaultStyle->addRulesFromSheet(simpleDefaultStyleSheet, screenEval());
739 // No need to initialize quirks sheet yet as there are no quirk rules for elements allowed in simple default style.
742 static void loadViewSourceStyle()
744 ASSERT(!defaultViewSourceStyle);
745 defaultViewSourceStyle = RuleSet::create().leakPtr();
746 defaultViewSourceStyle->addRulesFromSheet(parseUASheet(sourceUserAgentStyleSheet, sizeof(sourceUserAgentStyleSheet)), screenEval());
749 static void ensureDefaultStyleSheetsForElement(Element* element)
751 if (simpleDefaultStyleSheet && !elementCanUseSimpleDefaultStyle(element))
752 loadFullDefaultStyle();
755 if (element->isSVGElement() && !svgStyleSheet) {
757 svgStyleSheet = parseUASheet(svgUserAgentStyleSheet, sizeof(svgUserAgentStyleSheet));
758 defaultStyle->addRulesFromSheet(svgStyleSheet, screenEval());
759 defaultPrintStyle->addRulesFromSheet(svgStyleSheet, printEval());
764 if (element->isMathMLElement() && !mathMLStyleSheet) {
766 mathMLStyleSheet = parseUASheet(mathmlUserAgentStyleSheet, sizeof(mathmlUserAgentStyleSheet));
767 defaultStyle->addRulesFromSheet(mathMLStyleSheet, screenEval());
768 defaultPrintStyle->addRulesFromSheet(mathMLStyleSheet, printEval());
773 if (!mediaControlsStyleSheet && (element->hasTagName(videoTag) || element->hasTagName(audioTag))) {
774 String mediaRules = String(mediaControlsUserAgentStyleSheet, sizeof(mediaControlsUserAgentStyleSheet)) + RenderTheme::themeForPage(element->document()->page())->extraMediaControlsStyleSheet();
775 mediaControlsStyleSheet = parseUASheet(mediaRules);
776 defaultStyle->addRulesFromSheet(mediaControlsStyleSheet, screenEval());
777 defaultPrintStyle->addRulesFromSheet(mediaControlsStyleSheet, printEval());
781 #if ENABLE(FULLSCREEN_API)
782 if (!fullscreenStyleSheet && element->document()->webkitIsFullScreen()) {
783 String fullscreenRules = String(fullscreenUserAgentStyleSheet, sizeof(fullscreenUserAgentStyleSheet)) + RenderTheme::defaultTheme()->extraFullScreenStyleSheet();
784 fullscreenStyleSheet = parseUASheet(fullscreenRules);
785 defaultStyle->addRulesFromSheet(fullscreenStyleSheet, screenEval());
786 defaultQuirksStyle->addRulesFromSheet(fullscreenStyleSheet, screenEval());
790 ASSERT(defaultStyle->features().idsInRules.isEmpty());
791 ASSERT(mathMLStyleSheet || defaultStyle->features().siblingRules.isEmpty());
794 void CSSStyleSelector::addMatchedProperties(MatchResult& matchResult, StylePropertySet* properties, StyleRule* rule, unsigned linkMatchType, bool inRegionRule)
796 matchResult.matchedProperties.grow(matchResult.matchedProperties.size() + 1);
797 MatchedProperties& newProperties = matchResult.matchedProperties.last();
798 newProperties.properties = properties;
799 newProperties.linkMatchType = linkMatchType;
800 newProperties.isInRegionRule = inRegionRule;
801 matchResult.matchedRules.append(rule);
804 inline void CSSStyleSelector::addElementStyleProperties(MatchResult& result, StylePropertySet* propertySet, bool isCacheable)
808 result.ranges.lastAuthorRule = result.matchedProperties.size();
809 if (result.ranges.firstAuthorRule == -1)
810 result.ranges.firstAuthorRule = result.ranges.lastAuthorRule;
811 addMatchedProperties(result, propertySet);
813 result.isCacheable = false;
816 void CSSStyleSelector::collectMatchingRules(RuleSet* rules, int& firstRuleIndex, int& lastRuleIndex, const MatchOptions& options)
821 // We need to collect the rules for id, class, tag, and everything else into a buffer and
822 // then sort the buffer.
823 if (m_element->hasID())
824 collectMatchingRulesForList(rules->idRules(m_element->idForStyleResolution().impl()), firstRuleIndex, lastRuleIndex, options);
825 if (m_element->hasClass()) {
826 ASSERT(m_styledElement);
827 const SpaceSplitString& classNames = m_styledElement->classNames();
828 size_t size = classNames.size();
829 for (size_t i = 0; i < size; ++i)
830 collectMatchingRulesForList(rules->classRules(classNames[i].impl()), firstRuleIndex, lastRuleIndex, options);
832 const AtomicString& pseudoId = m_element->shadowPseudoId();
833 if (!pseudoId.isEmpty()) {
834 ASSERT(m_styledElement);
835 collectMatchingRulesForList(rules->shadowPseudoElementRules(pseudoId.impl()), firstRuleIndex, lastRuleIndex, options);
837 if (m_element->isLink())
838 collectMatchingRulesForList(rules->linkPseudoClassRules(), firstRuleIndex, lastRuleIndex, options);
839 if (m_checker.matchesFocusPseudoClass(m_element))
840 collectMatchingRulesForList(rules->focusPseudoClassRules(), firstRuleIndex, lastRuleIndex, options);
841 collectMatchingRulesForList(rules->tagRules(m_element->localName().impl()), firstRuleIndex, lastRuleIndex, options);
842 collectMatchingRulesForList(rules->universalRules(), firstRuleIndex, lastRuleIndex, options);
845 void CSSStyleSelector::collectMatchingRulesForRegion(RuleSet* rules, int& firstRuleIndex, int& lastRuleIndex, const MatchOptions& options)
847 if (!m_regionForStyling)
850 unsigned size = rules->m_regionSelectorsAndRuleSets.size();
851 for (unsigned i = 0; i < size; ++i) {
852 CSSSelector* regionSelector = rules->m_regionSelectorsAndRuleSets.at(i).selector;
853 if (checkRegionSelector(regionSelector, static_cast<Element*>(m_regionForStyling->node()))) {
854 RuleSet* regionRules = rules->m_regionSelectorsAndRuleSets.at(i).ruleSet.get();
856 collectMatchingRules(regionRules, firstRuleIndex, lastRuleIndex, options);
861 void CSSStyleSelector::sortAndTransferMatchedRules(MatchResult& result)
863 if (m_matchedRules.isEmpty())
868 if (m_checker.isCollectingRulesOnly()) {
870 m_ruleList = StaticCSSRuleList::create();
871 for (unsigned i = 0; i < m_matchedRules.size(); ++i)
872 m_ruleList->rules().append(m_matchedRules[i]->rule()->createCSSOMWrapper());
876 // Now transfer the set of matched rules over to our list of declarations.
877 // FIXME: This sucks, the inspector should get the style from the visited style itself.
878 bool swapVisitedUnvisited = InspectorInstrumentation::forcePseudoState(m_element, CSSSelector::PseudoVisited);
879 for (unsigned i = 0; i < m_matchedRules.size(); i++) {
880 if (m_style && m_matchedRules[i]->containsUncommonAttributeSelector())
881 m_style->setAffectedByUncommonAttributeSelectors();
882 unsigned linkMatchType = m_matchedRules[i]->linkMatchType();
883 if (swapVisitedUnvisited && linkMatchType && linkMatchType != SelectorChecker::MatchAll)
884 linkMatchType = (linkMatchType == SelectorChecker::MatchVisited) ? SelectorChecker::MatchLink : SelectorChecker::MatchVisited;
885 addMatchedProperties(result, m_matchedRules[i]->rule()->properties(), m_matchedRules[i]->rule(), linkMatchType, m_matchedRules[i]->isInRegionRule());
889 void CSSStyleSelector::matchScopedAuthorRules(MatchResult& result, bool includeEmptyRules)
891 #if ENABLE(STYLE_SCOPED)
892 if (m_scopedAuthorStyles.isEmpty())
895 MatchOptions options(includeEmptyRules);
897 // Match scoped author rules by traversing the scoped element stack (rebuild it if it got inconsistent).
898 const ContainerNode* parent = m_element->parentOrHostNode();
899 if (!scopeStackIsConsistent(parent))
900 setupScopeStack(parent);
901 for (size_t i = m_scopeStack.size(); i; --i) {
902 const ScopeStackFrame& frame = m_scopeStack[i - 1];
903 options.scope = frame.m_scope;
904 collectMatchingRules(frame.m_ruleSet, result.ranges.firstAuthorRule, result.ranges.lastAuthorRule, options);
905 collectMatchingRulesForRegion(frame.m_ruleSet, result.ranges.firstAuthorRule, result.ranges.lastAuthorRule, options);
907 // Also include the current element.
908 RuleSet* ruleSet = ruleSetForScope(m_element);
910 options.scope = m_element;
911 collectMatchingRules(ruleSet, result.ranges.firstAuthorRule, result.ranges.lastAuthorRule, options);
912 collectMatchingRulesForRegion(ruleSet, result.ranges.firstAuthorRule, result.ranges.lastAuthorRule, options);
915 UNUSED_PARAM(result);
916 UNUSED_PARAM(includeEmptyRules);
920 void CSSStyleSelector::matchAuthorRules(MatchResult& result, bool includeEmptyRules)
922 m_matchedRules.clear();
923 result.ranges.lastAuthorRule = result.matchedProperties.size() - 1;
928 // Match global author rules.
929 MatchOptions options(includeEmptyRules);
930 collectMatchingRules(m_authorStyle.get(), result.ranges.firstAuthorRule, result.ranges.lastAuthorRule, options);
931 collectMatchingRulesForRegion(m_authorStyle.get(), result.ranges.firstAuthorRule, result.ranges.lastAuthorRule, options);
933 matchScopedAuthorRules(result, includeEmptyRules);
935 sortAndTransferMatchedRules(result);
938 void CSSStyleSelector::matchUserRules(MatchResult& result, bool includeEmptyRules)
943 m_matchedRules.clear();
945 result.ranges.lastUserRule = result.matchedProperties.size() - 1;
946 collectMatchingRules(m_userStyle.get(), result.ranges.firstUserRule, result.ranges.lastUserRule, includeEmptyRules);
947 collectMatchingRulesForRegion(m_userStyle.get(), result.ranges.firstUserRule, result.ranges.lastUserRule, includeEmptyRules);
949 sortAndTransferMatchedRules(result);
952 void CSSStyleSelector::matchUARules(MatchResult& result, RuleSet* rules)
954 m_matchedRules.clear();
956 result.ranges.lastUARule = result.matchedProperties.size() - 1;
957 collectMatchingRules(rules, result.ranges.firstUARule, result.ranges.lastUARule, false);
959 sortAndTransferMatchedRules(result);
962 class MatchingUARulesScope {
964 MatchingUARulesScope();
965 ~MatchingUARulesScope();
967 static bool isMatchingUARules();
970 static bool m_matchingUARules;
973 MatchingUARulesScope::MatchingUARulesScope()
975 ASSERT(!m_matchingUARules);
976 m_matchingUARules = true;
979 MatchingUARulesScope::~MatchingUARulesScope()
981 m_matchingUARules = false;
984 inline bool MatchingUARulesScope::isMatchingUARules()
986 return m_matchingUARules;
989 bool MatchingUARulesScope::m_matchingUARules = false;
991 void CSSStyleSelector::collectMatchingRulesForList(const Vector<RuleData>* rules, int& firstRuleIndex, int& lastRuleIndex, const MatchOptions& options)
995 // In some cases we may end up looking up style for random elements in the middle of a recursive tree resolve.
996 // Ancestor identifier filter won't be up-to-date in that case and we can't use the fast path.
997 bool canUseFastReject = m_checker.parentStackIsConsistent(m_parentNode);
999 unsigned size = rules->size();
1000 for (unsigned i = 0; i < size; ++i) {
1001 const RuleData& ruleData = rules->at(i);
1002 if (canUseFastReject && m_checker.fastRejectSelector<RuleData::maximumIdentifierCount>(ruleData.descendantSelectorIdentifierHashes()))
1005 StyleRule* rule = ruleData.rule();
1006 InspectorInstrumentationCookie cookie = InspectorInstrumentation::willMatchRule(document(), rule);
1007 #if ENABLE(STYLE_SCOPED)
1008 if (checkSelector(ruleData, options.scope)) {
1010 if (checkSelector(ruleData)) {
1012 // Check whether the rule is applicable in the current tree scope. Criteria for this:
1013 // a) it's a UA rule
1014 // b) the tree scope allows author rules
1015 // c) the rules comes from a scoped style sheet within the same tree scope
1016 // d) the rule contains shadow-ID pseudo elements
1017 TreeScope* treeScope = m_element->treeScope();
1018 if (!MatchingUARulesScope::isMatchingUARules()
1019 && !treeScope->applyAuthorSheets()
1020 #if ENABLE(STYLE_SCOPED)
1021 && (!options.scope || options.scope->treeScope() != treeScope)
1023 && !m_checker.hasUnknownPseudoElements()) {
1025 InspectorInstrumentation::didMatchRule(cookie, false);
1028 // If the rule has no properties to apply, then ignore it in the non-debug mode.
1029 StylePropertySet* properties = rule->properties();
1030 if (!properties || (properties->isEmpty() && !options.includeEmptyRules)) {
1031 InspectorInstrumentation::didMatchRule(cookie, false);
1034 // FIXME: Exposing the non-standard getMatchedCSSRules API to web is the only reason this is needed.
1035 if (m_sameOriginOnly && !ruleData.hasDocumentSecurityOrigin()) {
1036 InspectorInstrumentation::didMatchRule(cookie, false);
1039 // If we're matching normal rules, set a pseudo bit if
1040 // we really just matched a pseudo-element.
1041 if (m_dynamicPseudo != NOPSEUDO && m_checker.pseudoStyle() == NOPSEUDO) {
1042 if (m_checker.isCollectingRulesOnly()) {
1043 InspectorInstrumentation::didMatchRule(cookie, false);
1046 if (m_dynamicPseudo < FIRST_INTERNAL_PSEUDOID)
1047 m_style->setHasPseudoStyle(m_dynamicPseudo);
1049 // Update our first/last rule indices in the matched rules array.
1051 if (firstRuleIndex == -1)
1052 firstRuleIndex = lastRuleIndex;
1054 // Add this rule to our list of matched rules.
1055 addMatchedRule(&ruleData);
1056 InspectorInstrumentation::didMatchRule(cookie, true);
1060 InspectorInstrumentation::didMatchRule(cookie, false);
1064 static inline bool compareRules(const RuleData* r1, const RuleData* r2)
1066 unsigned specificity1 = r1->specificity();
1067 unsigned specificity2 = r2->specificity();
1068 return (specificity1 == specificity2) ? r1->position() < r2->position() : specificity1 < specificity2;
1071 void CSSStyleSelector::sortMatchedRules()
1073 std::sort(m_matchedRules.begin(), m_matchedRules.end(), compareRules);
1076 void CSSStyleSelector::matchAllRules(MatchResult& result)
1078 matchUARules(result);
1080 // Now we check user sheet rules.
1081 if (m_matchAuthorAndUserStyles)
1082 matchUserRules(result, false);
1084 // Now check author rules, beginning first with presentational attributes mapped from HTML.
1085 if (m_styledElement) {
1086 addElementStyleProperties(result, m_styledElement->attributeStyle());
1088 // Now we check additional mapped declarations.
1089 // Tables and table cells share an additional mapped rule that must be applied
1090 // after all attributes, since their mapped style depends on the values of multiple attributes.
1091 addElementStyleProperties(result, m_styledElement->additionalAttributeStyle());
1093 if (m_styledElement->isHTMLElement()) {
1095 TextDirection textDirection = toHTMLElement(m_styledElement)->directionalityIfhasDirAutoAttribute(isAuto);
1097 addMatchedProperties(result, textDirection == LTR ? leftToRightDeclaration() : rightToLeftDeclaration());
1101 // Check the rules in author sheets next.
1102 if (m_matchAuthorAndUserStyles)
1103 matchAuthorRules(result, false);
1105 // Now check our inline style attribute.
1106 if (m_matchAuthorAndUserStyles && m_styledElement && m_styledElement->inlineStyle()) {
1107 // Inline style is immutable as long as there is no CSSOM wrapper.
1108 // FIXME: Media control shadow trees seem to have problems with caching.
1109 bool isInlineStyleCacheable = !m_styledElement->inlineStyle()->isMutable() && !m_styledElement->isInShadowTree();
1111 addElementStyleProperties(result, const_cast<StylePropertySet*>(m_styledElement->inlineStyle()), isInlineStyleCacheable);
1115 // Now check SMIL animation override style.
1116 if (m_matchAuthorAndUserStyles && m_styledElement && m_styledElement->isSVGElement())
1117 addElementStyleProperties(result, static_cast<SVGElement*>(m_styledElement)->animatedSMILStyleProperties(), false /* isCacheable */);
1121 inline void CSSStyleSelector::initElement(Element* e)
1123 if (m_element != e) {
1125 m_styledElement = m_element && m_element->isStyledElement() ? static_cast<StyledElement*>(m_element) : 0;
1126 m_elementLinkState = m_checker.determineLinkState(m_element);
1127 if (e && e == e->document()->documentElement()) {
1128 e->document()->setDirectionSetOnDocumentElement(false);
1129 e->document()->setWritingModeSetOnDocumentElement(false);
1134 inline void CSSStyleSelector::initForStyleResolve(Element* e, RenderStyle* parentStyle, PseudoId pseudoID)
1136 m_checker.setPseudoStyle(pseudoID);
1138 m_parentNode = e ? e->parentNodeForRenderingAndStyle() : 0;
1141 m_parentStyle = parentStyle;
1143 m_parentStyle = m_parentNode ? m_parentNode->renderStyle() : 0;
1145 Node* docElement = e ? e->document()->documentElement() : 0;
1146 RenderStyle* docStyle = m_checker.document()->renderStyle();
1147 m_rootElementStyle = docElement && e != docElement ? docElement->renderStyle() : docStyle;
1151 m_pendingImageProperties.clear();
1155 m_fontDirty = false;
1158 static const unsigned cStyleSearchThreshold = 10;
1159 static const unsigned cStyleSearchLevelThreshold = 10;
1161 Node* CSSStyleSelector::locateCousinList(Element* parent, unsigned& visitedNodeCount) const
1163 if (visitedNodeCount >= cStyleSearchThreshold * cStyleSearchLevelThreshold)
1165 if (!parent || !parent->isStyledElement())
1167 #if ENABLE(STYLE_SCOPED)
1168 if (parent->hasScopedHTMLStyleChild())
1171 StyledElement* p = static_cast<StyledElement*>(parent);
1172 if (p->inlineStyle())
1175 if (p->isSVGElement() && static_cast<SVGElement*>(p)->animatedSMILStyleProperties())
1178 if (p->hasID() && m_features.idsInRules.contains(p->idForStyleResolution().impl()))
1181 RenderStyle* parentStyle = p->renderStyle();
1182 unsigned subcount = 0;
1183 Node* thisCousin = p;
1184 Node* currentNode = p->previousSibling();
1186 // Reserve the tries for this level. This effectively makes sure that the algorithm
1187 // will never go deeper than cStyleSearchLevelThreshold levels into recursion.
1188 visitedNodeCount += cStyleSearchThreshold;
1189 while (thisCousin) {
1190 while (currentNode) {
1192 if (currentNode->renderStyle() == parentStyle && currentNode->lastChild()) {
1193 // Adjust for unused reserved tries.
1194 visitedNodeCount -= cStyleSearchThreshold - subcount;
1195 return currentNode->lastChild();
1197 if (subcount >= cStyleSearchThreshold)
1199 currentNode = currentNode->previousSibling();
1201 currentNode = locateCousinList(thisCousin->parentElement(), visitedNodeCount);
1202 thisCousin = currentNode;
1208 bool CSSStyleSelector::matchesRuleSet(RuleSet* ruleSet)
1212 m_matchedRules.clear();
1214 int firstRuleIndex = -1, lastRuleIndex = -1;
1215 collectMatchingRules(ruleSet, firstRuleIndex, lastRuleIndex, false);
1217 if (m_matchedRules.isEmpty())
1219 m_matchedRules.clear();
1223 bool CSSStyleSelector::canShareStyleWithControl(StyledElement* element) const
1225 HTMLInputElement* thisInputElement = element->toInputElement();
1226 HTMLInputElement* otherInputElement = m_element->toInputElement();
1228 if (!thisInputElement || !otherInputElement)
1231 if (thisInputElement->isAutofilled() != otherInputElement->isAutofilled())
1233 if (thisInputElement->shouldAppearChecked() != otherInputElement->shouldAppearChecked())
1235 if (thisInputElement->isIndeterminate() != otherInputElement->isIndeterminate())
1237 if (thisInputElement->required() != otherInputElement->required())
1240 if (element->isEnabledFormControl() != m_element->isEnabledFormControl())
1243 if (element->isDefaultButtonForForm() != m_element->isDefaultButtonForForm())
1246 if (m_element->document()->containsValidityStyleRules()) {
1247 bool willValidate = element->willValidate();
1249 if (willValidate != m_element->willValidate())
1252 if (willValidate && (element->isValidFormControlElement() != m_element->isValidFormControlElement()))
1255 if (element->isInRange() != m_element->isInRange())
1258 if (element->isOutOfRange() != m_element->isOutOfRange())
1265 // This function makes some assumptions that only make sense for attribute styles (we only compare CSSProperty::id() and CSSProperty::value().)
1266 static inline bool attributeStylesEqual(StylePropertySet* a, StylePropertySet* b)
1270 if (a->propertyCount() != b->propertyCount())
1272 unsigned propertyCount = a->propertyCount();
1273 for (unsigned i = 0; i < propertyCount; ++i) {
1274 const CSSProperty& aProperty = a->propertyAt(i);
1276 for (j = 0; j < propertyCount; ++j) {
1277 const CSSProperty& bProperty = b->propertyAt(j);
1278 if (aProperty.id() != bProperty.id())
1280 // We could get a few more hits by comparing cssText() here, but that gets expensive quickly.
1281 if (aProperty.value() != bProperty.value())
1285 if (j == propertyCount)
1291 inline bool elementHasDirectionAuto(Element* element)
1293 return element->isHTMLElement() && toHTMLElement(element)->hasDirectionAuto();
1296 bool CSSStyleSelector::canShareStyleWithElement(StyledElement* element) const
1298 RenderStyle* style = element->renderStyle();
1302 if (style->unique())
1304 if (element->tagQName() != m_element->tagQName())
1306 if (element->hasClass() != m_element->hasClass())
1308 if (element->inlineStyle())
1311 if (element->isSVGElement() && static_cast<SVGElement*>(element)->animatedSMILStyleProperties())
1314 if (!!element->attributeStyle() != !!m_styledElement->attributeStyle())
1316 StylePropertySet* additionalAttributeStyleA = element->additionalAttributeStyle();
1317 StylePropertySet* additionalAttributeStyleB = m_styledElement->additionalAttributeStyle();
1318 if (!additionalAttributeStyleA != !additionalAttributeStyleB)
1320 if (element->isLink() != m_element->isLink())
1322 if (style->affectedByUncommonAttributeSelectors())
1324 if (element->hovered() != m_element->hovered())
1326 if (element->active() != m_element->active())
1328 if (element->focused() != m_element->focused())
1330 if (element->shadowPseudoId() != m_element->shadowPseudoId())
1332 if (element == element->document()->cssTarget())
1334 if (m_element == m_element->document()->cssTarget())
1336 if (element->getAttribute(typeAttr) != m_element->getAttribute(typeAttr))
1338 if (element->fastGetAttribute(XMLNames::langAttr) != m_element->fastGetAttribute(XMLNames::langAttr))
1340 if (element->fastGetAttribute(langAttr) != m_element->fastGetAttribute(langAttr))
1342 if (element->fastGetAttribute(readonlyAttr) != m_element->fastGetAttribute(readonlyAttr))
1344 if (element->fastGetAttribute(cellpaddingAttr) != m_element->fastGetAttribute(cellpaddingAttr))
1347 if (element->hasID() && m_features.idsInRules.contains(element->idForStyleResolution().impl()))
1350 #if ENABLE(STYLE_SCOPED)
1351 if (element->hasScopedHTMLStyleChild())
1355 #if ENABLE(PROGRESS_TAG)
1356 if (element->hasTagName(progressTag)) {
1357 if (!m_element->hasTagName(progressTag))
1360 HTMLProgressElement* thisProgressElement = static_cast<HTMLProgressElement*>(element);
1361 HTMLProgressElement* otherProgressElement = static_cast<HTMLProgressElement*>(m_element);
1362 if (thisProgressElement->isDeterminate() != otherProgressElement->isDeterminate())
1367 if (element->hasTagName(optionTag))
1370 bool isControl = element->isFormControlElement();
1372 if (isControl != m_element->isFormControlElement())
1375 if (isControl && !canShareStyleWithControl(element))
1378 if (style->transitions() || style->animations())
1381 #if USE(ACCELERATED_COMPOSITING)
1382 // Turn off style sharing for elements that can gain layers for reasons outside of the style system.
1383 // See comments in RenderObject::setStyle().
1384 if (element->hasTagName(iframeTag) || element->hasTagName(frameTag) || element->hasTagName(embedTag) || element->hasTagName(objectTag) || element->hasTagName(appletTag)
1385 #if ENABLE(PLUGIN_PROXY_FOR_VIDEO)
1386 // With proxying, the media elements are backed by a RenderEmbeddedObject.
1387 || element->hasTagName(videoTag) || element->hasTagName(audioTag)
1393 if (elementHasDirectionAuto(element) || elementHasDirectionAuto(m_element))
1396 if (element->hasClass() && m_element->getAttribute(classAttr) != element->getAttribute(classAttr))
1399 if (element->attributeStyle() && !attributeStylesEqual(element->attributeStyle(), m_styledElement->attributeStyle()))
1402 if (additionalAttributeStyleA && !attributeStylesEqual(additionalAttributeStyleA, additionalAttributeStyleB))
1405 if (element->isLink() && m_elementLinkState != style->insideLink())
1411 inline StyledElement* CSSStyleSelector::findSiblingForStyleSharing(Node* node, unsigned& count) const
1413 for (; node; node = node->previousSibling()) {
1414 if (!node->isStyledElement())
1416 if (canShareStyleWithElement(static_cast<StyledElement*>(node)))
1418 if (count++ == cStyleSearchThreshold)
1421 return static_cast<StyledElement*>(node);
1424 static inline bool parentStylePreventsSharing(const RenderStyle* parentStyle)
1426 return parentStyle->childrenAffectedByPositionalRules()
1427 || parentStyle->childrenAffectedByFirstChildRules()
1428 || parentStyle->childrenAffectedByLastChildRules()
1429 || parentStyle->childrenAffectedByDirectAdjacentRules();
1432 RenderStyle* CSSStyleSelector::locateSharedStyle()
1434 if (!m_styledElement || !m_parentStyle)
1436 // If the element has inline style it is probably unique.
1437 if (m_styledElement->inlineStyle())
1440 if (m_styledElement->isSVGElement() && static_cast<SVGElement*>(m_styledElement)->animatedSMILStyleProperties())
1443 // Ids stop style sharing if they show up in the stylesheets.
1444 if (m_styledElement->hasID() && m_features.idsInRules.contains(m_styledElement->idForStyleResolution().impl()))
1446 if (parentStylePreventsSharing(m_parentStyle))
1448 #if ENABLE(STYLE_SCOPED)
1449 if (m_styledElement->hasScopedHTMLStyleChild())
1453 // Check previous siblings and their cousins.
1455 unsigned visitedNodeCount = 0;
1456 StyledElement* shareElement = 0;
1457 Node* cousinList = m_styledElement->previousSibling();
1458 while (cousinList) {
1459 shareElement = findSiblingForStyleSharing(cousinList, count);
1462 cousinList = locateCousinList(cousinList->parentElement(), visitedNodeCount);
1465 // If we have exhausted all our budget or our cousins.
1469 // Can't share if sibling rules apply. This is checked at the end as it should rarely fail.
1470 if (matchesRuleSet(m_siblingRuleSet.get()))
1472 // Can't share if attribute rules apply.
1473 if (matchesRuleSet(m_uncommonAttributeRuleSet.get()))
1475 // Tracking child index requires unique style for each node. This may get set by the sibling rule match above.
1476 if (parentStylePreventsSharing(m_parentStyle))
1478 return shareElement->renderStyle();
1481 void CSSStyleSelector::matchUARules(MatchResult& result)
1483 MatchingUARulesScope scope;
1485 // First we match rules from the user agent sheet.
1486 if (simpleDefaultStyleSheet)
1487 result.isCacheable = false;
1488 RuleSet* userAgentStyleSheet = m_medium->mediaTypeMatchSpecific("print")
1489 ? defaultPrintStyle : defaultStyle;
1490 matchUARules(result, userAgentStyleSheet);
1492 // In quirks mode, we match rules from the quirks user agent sheet.
1493 if (!m_checker.strictParsing())
1494 matchUARules(result, defaultQuirksStyle);
1496 // 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.
1497 if (m_checker.document()->isViewSource()) {
1498 if (!defaultViewSourceStyle)
1499 loadViewSourceStyle();
1500 matchUARules(result, defaultViewSourceStyle);
1504 PassRefPtr<RenderStyle> CSSStyleSelector::styleForDocument(Document* document, CSSFontSelector* fontSelector)
1506 Frame* frame = document->frame();
1508 RefPtr<RenderStyle> documentStyle = RenderStyle::create();
1509 documentStyle->setDisplay(BLOCK);
1510 documentStyle->setRTLOrdering(document->visuallyOrdered() ? VisualOrder : LogicalOrder);
1511 documentStyle->setZoom(frame && !document->printing() ? frame->pageZoomFactor() : 1);
1512 documentStyle->setPageScaleTransform(frame ? frame->frameScaleFactor() : 1);
1513 documentStyle->setUserModify(document->inDesignMode() ? READ_WRITE : READ_ONLY);
1514 documentStyle->setLocale(document->contentLanguage());
1516 Element* docElement = document->documentElement();
1517 RenderObject* docElementRenderer = docElement ? docElement->renderer() : 0;
1518 if (docElementRenderer) {
1519 // Use the direction and writing-mode of the body to set the
1520 // viewport's direction and writing-mode unless the property is set on the document element.
1521 // If there is no body, then use the document element.
1522 RenderObject* bodyRenderer = document->body() ? document->body()->renderer() : 0;
1523 if (bodyRenderer && !document->writingModeSetOnDocumentElement())
1524 documentStyle->setWritingMode(bodyRenderer->style()->writingMode());
1526 documentStyle->setWritingMode(docElementRenderer->style()->writingMode());
1527 if (bodyRenderer && !document->directionSetOnDocumentElement())
1528 documentStyle->setDirection(bodyRenderer->style()->direction());
1530 documentStyle->setDirection(docElementRenderer->style()->direction());
1534 if (Page* page = frame->page()) {
1535 const Page::Pagination& pagination = page->pagination();
1536 if (pagination.mode != Page::Pagination::Unpaginated) {
1537 documentStyle->setColumnAxis(pagination.mode == Page::Pagination::HorizontallyPaginated ? HorizontalColumnAxis : VerticalColumnAxis);
1538 documentStyle->setColumnGap(pagination.gap);
1543 FontDescription fontDescription;
1544 fontDescription.setUsePrinterFont(document->printing());
1545 fontDescription.setScript(localeToScriptCodeForFontSelection(documentStyle->locale()));
1546 if (Settings* settings = document->settings()) {
1547 fontDescription.setRenderingMode(settings->fontRenderingMode());
1548 const AtomicString& standardFont = settings->standardFontFamily(fontDescription.script());
1549 if (!standardFont.isEmpty()) {
1550 fontDescription.setGenericFamily(FontDescription::StandardFamily);
1551 fontDescription.firstFamily().setFamily(standardFont);
1552 fontDescription.firstFamily().appendFamily(0);
1554 fontDescription.setKeywordSize(CSSValueMedium - CSSValueXxSmall + 1);
1555 int size = CSSStyleSelector::fontSizeForKeyword(document, CSSValueMedium, false);
1556 fontDescription.setSpecifiedSize(size);
1557 bool useSVGZoomRules = document->isSVGDocument();
1558 fontDescription.setComputedSize(CSSStyleSelector::getComputedSizeFromSpecifiedSize(document, documentStyle.get(), fontDescription.isAbsoluteSize(), size, useSVGZoomRules));
1561 documentStyle->setFontDescription(fontDescription);
1562 documentStyle->font().update(fontSelector);
1564 return documentStyle.release();
1567 static inline bool isAtShadowBoundary(Element* element)
1571 ContainerNode* parentNode = element->parentNode();
1572 return parentNode && parentNode->isShadowRoot();
1575 PassRefPtr<RenderStyle> CSSStyleSelector::styleForElement(Element* element, RenderStyle* defaultParent,
1576 StyleSharingBehavior sharingBehavior, RuleMatchingBehavior matchingBehavior, RenderRegion* regionForStyling)
1578 // Once an element has a renderer, we don't try to destroy it, since otherwise the renderer
1579 // will vanish if a style recalc happens during loading.
1580 if (sharingBehavior == AllowStyleSharing && !element->document()->haveStylesheetsLoaded() && !element->renderer()) {
1581 if (!s_styleNotYetAvailable) {
1582 s_styleNotYetAvailable = RenderStyle::create().leakRef();
1583 s_styleNotYetAvailable->setDisplay(NONE);
1584 s_styleNotYetAvailable->font().update(m_fontSelector);
1586 element->document()->setHasNodesWithPlaceholderStyle();
1587 return s_styleNotYetAvailable;
1590 initElement(element);
1591 initForStyleResolve(element, defaultParent);
1592 m_regionForStyling = regionForStyling;
1593 if (sharingBehavior == AllowStyleSharing) {
1594 RenderStyle* sharedStyle = locateSharedStyle();
1599 m_style = RenderStyle::create();
1602 m_style->inheritFrom(m_parentStyle);
1604 m_parentStyle = style();
1605 // Make sure our fonts are initialized if we don't inherit them from our parent style.
1606 m_style->font().update(0);
1609 // Even if surrounding content is user-editable, shadow DOM should act as a single unit, and not necessarily be editable
1610 if (isAtShadowBoundary(element))
1611 m_style->setUserModify(RenderStyle::initialUserModify());
1613 if (element->isLink()) {
1614 m_style->setIsLink(true);
1615 m_style->setInsideLink(m_elementLinkState);
1618 ensureDefaultStyleSheetsForElement(element);
1620 MatchResult matchResult;
1621 if (matchingBehavior == MatchOnlyUserAgentRules)
1622 matchUARules(matchResult);
1624 matchAllRules(matchResult);
1626 applyMatchedProperties(matchResult);
1628 // Clean up our style object's display and text decorations (among other fixups).
1629 adjustRenderStyle(style(), m_parentStyle, element);
1631 initElement(0); // Clear out for the next resolve.
1633 // Now return the style.
1634 return m_style.release();
1637 PassRefPtr<RenderStyle> CSSStyleSelector::styleForKeyframe(const RenderStyle* elementStyle, const StyleKeyframe* keyframe, KeyframeValue& keyframeValue)
1640 if (keyframe->properties())
1641 addMatchedProperties(result, keyframe->properties());
1646 m_style = RenderStyle::clone(elementStyle);
1648 m_lineHeightValue = 0;
1650 // We don't need to bother with !important. Since there is only ever one
1651 // decl, there's nothing to override. So just add the first properties.
1652 bool inheritedOnly = false;
1653 if (keyframe->properties())
1654 applyMatchedProperties<true>(result, false, 0, result.matchedProperties.size() - 1, inheritedOnly);
1656 // If our font got dirtied, go ahead and update it now.
1659 // Line-height is set when we are sure we decided on the font-size
1660 if (m_lineHeightValue)
1661 applyProperty(CSSPropertyLineHeight, m_lineHeightValue);
1663 // Now do rest of the properties.
1664 if (keyframe->properties())
1665 applyMatchedProperties<false>(result, false, 0, result.matchedProperties.size() - 1, inheritedOnly);
1667 // If our font got dirtied by one of the non-essential font props,
1668 // go ahead and update it a second time.
1671 // Start loading images referenced by this style.
1672 loadPendingImages();
1674 #if ENABLE(CSS_SHADERS)
1675 // Start loading the shaders referenced by this style.
1676 loadPendingShaders();
1679 // Add all the animating properties to the keyframe.
1680 if (StylePropertySet* styleDeclaration = keyframe->properties()) {
1681 unsigned propertyCount = styleDeclaration->propertyCount();
1682 for (unsigned i = 0; i < propertyCount; ++i) {
1683 int property = styleDeclaration->propertyAt(i).id();
1684 // Timing-function within keyframes is special, because it is not animated; it just
1685 // describes the timing function between this keyframe and the next.
1686 if (property != CSSPropertyWebkitAnimationTimingFunction)
1687 keyframeValue.addProperty(property);
1691 return m_style.release();
1694 void CSSStyleSelector::keyframeStylesForAnimation(Element* e, const RenderStyle* elementStyle, KeyframeList& list)
1698 // Get the keyframesRule for this name
1699 if (!e || list.animationName().isEmpty())
1702 m_keyframesRuleMap.checkConsistency();
1704 KeyframesRuleMap::iterator it = m_keyframesRuleMap.find(list.animationName().impl());
1705 if (it == m_keyframesRuleMap.end())
1708 const StyleRuleKeyframes* keyframesRule = it->second.get();
1710 // Construct and populate the style for each keyframe
1711 const Vector<RefPtr<StyleKeyframe> >& keyframes = keyframesRule->keyframes();
1712 for (unsigned i = 0; i < keyframes.size(); ++i) {
1713 // Apply the declaration to the style. This is a simplified version of the logic in styleForElement
1715 initForStyleResolve(e);
1717 const StyleKeyframe* keyframe = keyframes[i].get();
1719 KeyframeValue keyframeValue(0, 0);
1720 keyframeValue.setStyle(styleForKeyframe(elementStyle, keyframe, keyframeValue));
1722 // Add this keyframe style to all the indicated key times
1724 keyframe->getKeys(keys);
1725 for (size_t keyIndex = 0; keyIndex < keys.size(); ++keyIndex) {
1726 keyframeValue.setKey(keys[keyIndex]);
1727 list.insert(keyframeValue);
1731 // If the 0% keyframe is missing, create it (but only if there is at least one other keyframe)
1732 int initialListSize = list.size();
1733 if (initialListSize > 0 && list[0].key() != 0) {
1734 static StyleKeyframe* zeroPercentKeyframe;
1735 if (!zeroPercentKeyframe) {
1736 zeroPercentKeyframe = StyleKeyframe::create().leakRef();
1737 zeroPercentKeyframe->setKeyText("0%");
1739 KeyframeValue keyframeValue(0, 0);
1740 keyframeValue.setStyle(styleForKeyframe(elementStyle, zeroPercentKeyframe, keyframeValue));
1741 list.insert(keyframeValue);
1744 // If the 100% keyframe is missing, create it (but only if there is at least one other keyframe)
1745 if (initialListSize > 0 && (list[list.size() - 1].key() != 1)) {
1746 static StyleKeyframe* hundredPercentKeyframe;
1747 if (!hundredPercentKeyframe) {
1748 hundredPercentKeyframe = StyleKeyframe::create().leakRef();
1749 hundredPercentKeyframe->setKeyText("100%");
1751 KeyframeValue keyframeValue(1, 0);
1752 keyframeValue.setStyle(styleForKeyframe(elementStyle, hundredPercentKeyframe, keyframeValue));
1753 list.insert(keyframeValue);
1757 PassRefPtr<RenderStyle> CSSStyleSelector::pseudoStyleForElement(PseudoId pseudo, Element* e, RenderStyle* parentStyle)
1764 initForStyleResolve(e, parentStyle, pseudo);
1765 m_style = RenderStyle::create();
1768 m_style->inheritFrom(m_parentStyle);
1770 // Since we don't use pseudo-elements in any of our quirk/print user agent rules, don't waste time walking
1773 // Check UA, user and author rules.
1774 MatchResult matchResult;
1775 matchUARules(matchResult);
1777 if (m_matchAuthorAndUserStyles) {
1778 matchUserRules(matchResult, false);
1779 matchAuthorRules(matchResult, false);
1782 if (matchResult.matchedProperties.isEmpty())
1785 m_style->setStyleType(pseudo);
1787 applyMatchedProperties(matchResult);
1789 // Clean up our style object's display and text decorations (among other fixups).
1790 adjustRenderStyle(style(), parentStyle, 0);
1792 // Start loading images referenced by this style.
1793 loadPendingImages();
1795 #if ENABLE(CSS_SHADERS)
1796 // Start loading the shaders referenced by this style.
1797 loadPendingShaders();
1800 // Now return the style.
1801 return m_style.release();
1804 PassRefPtr<RenderStyle> CSSStyleSelector::styleForPage(int pageIndex)
1806 initForStyleResolve(m_checker.document()->documentElement()); // m_rootElementStyle will be set to the document style.
1808 m_style = RenderStyle::create();
1809 m_style->inheritFrom(m_rootElementStyle);
1811 const bool isLeft = isLeftPage(pageIndex);
1812 const bool isFirst = isFirstPage(pageIndex);
1813 const String page = pageName(pageIndex);
1816 matchPageRules(result, defaultPrintStyle, isLeft, isFirst, page);
1817 matchPageRules(result, m_userStyle.get(), isLeft, isFirst, page);
1818 // Only consider the global author RuleSet for @page rules, as per the HTML5 spec.
1819 matchPageRules(result, m_authorStyle.get(), isLeft, isFirst, page);
1820 m_lineHeightValue = 0;
1821 bool inheritedOnly = false;
1822 applyMatchedProperties<true>(result, false, 0, result.matchedProperties.size() - 1, inheritedOnly);
1824 // If our font got dirtied, go ahead and update it now.
1827 // Line-height is set when we are sure we decided on the font-size.
1828 if (m_lineHeightValue)
1829 applyProperty(CSSPropertyLineHeight, m_lineHeightValue);
1831 applyMatchedProperties<false>(result, false, 0, result.matchedProperties.size() - 1, inheritedOnly);
1833 // Start loading images referenced by this style.
1834 loadPendingImages();
1836 #if ENABLE(CSS_SHADERS)
1837 // Start loading the shaders referenced by this style.
1838 loadPendingShaders();
1841 // Now return the style.
1842 return m_style.release();
1845 static void addIntrinsicMargins(RenderStyle* style)
1847 // Intrinsic margin value.
1848 const int intrinsicMargin = 2 * style->effectiveZoom();
1850 // FIXME: Using width/height alone and not also dealing with min-width/max-width is flawed.
1851 // FIXME: Using "quirk" to decide the margin wasn't set is kind of lame.
1852 if (style->width().isIntrinsicOrAuto()) {
1853 if (style->marginLeft().quirk())
1854 style->setMarginLeft(Length(intrinsicMargin, Fixed));
1855 if (style->marginRight().quirk())
1856 style->setMarginRight(Length(intrinsicMargin, Fixed));
1859 if (style->height().isAuto()) {
1860 if (style->marginTop().quirk())
1861 style->setMarginTop(Length(intrinsicMargin, Fixed));
1862 if (style->marginBottom().quirk())
1863 style->setMarginBottom(Length(intrinsicMargin, Fixed));
1867 static EDisplay equivalentBlockDisplay(EDisplay display, bool isFloating, bool strictParsing)
1874 #if ENABLE(CSS_GRID_LAYOUT)
1880 // It is a WinIE bug that floated list items lose their bullets, so we'll emulate the quirk, but only in quirks mode.
1881 if (!strictParsing && isFloating)
1888 case INLINE_FLEXBOX:
1890 #if ENABLE(CSS_GRID_LAYOUT)
1899 case TABLE_ROW_GROUP:
1900 case TABLE_HEADER_GROUP:
1901 case TABLE_FOOTER_GROUP:
1903 case TABLE_COLUMN_GROUP:
1909 ASSERT_NOT_REACHED();
1912 ASSERT_NOT_REACHED();
1916 void CSSStyleSelector::adjustRenderStyle(RenderStyle* style, RenderStyle* parentStyle, Element *e)
1918 // Cache our original display.
1919 style->setOriginalDisplay(style->display());
1921 if (style->display() != NONE) {
1922 // If we have a <td> that specifies a float property, in quirks mode we just drop the float
1924 // Sites also commonly use display:inline/block on <td>s and <table>s. In quirks mode we force
1925 // these tags to retain their display types.
1926 if (!m_checker.strictParsing() && e) {
1927 if (e->hasTagName(tdTag)) {
1928 style->setDisplay(TABLE_CELL);
1929 style->setFloating(NoFloat);
1931 else if (e->hasTagName(tableTag))
1932 style->setDisplay(style->isDisplayInlineType() ? INLINE_TABLE : TABLE);
1935 if (e && (e->hasTagName(tdTag) || e->hasTagName(thTag))) {
1936 if (style->whiteSpace() == KHTML_NOWRAP) {
1937 // Figure out if we are really nowrapping or if we should just
1938 // use normal instead. If the width of the cell is fixed, then
1939 // we don't actually use NOWRAP.
1940 if (style->width().isFixed())
1941 style->setWhiteSpace(NORMAL);
1943 style->setWhiteSpace(NOWRAP);
1947 // Tables never support the -webkit-* values for text-align and will reset back to the default.
1948 if (e && e->hasTagName(tableTag) && (style->textAlign() == WEBKIT_LEFT || style->textAlign() == WEBKIT_CENTER || style->textAlign() == WEBKIT_RIGHT))
1949 style->setTextAlign(TAAUTO);
1951 // Frames and framesets never honor position:relative or position:absolute. This is necessary to
1952 // fix a crash where a site tries to position these objects. They also never honor display.
1953 if (e && (e->hasTagName(frameTag) || e->hasTagName(framesetTag))) {
1954 style->setPosition(StaticPosition);
1955 style->setDisplay(BLOCK);
1958 // Table headers with a text-align of auto will change the text-align to center.
1959 if (e && e->hasTagName(thTag) && style->textAlign() == TAAUTO)
1960 style->setTextAlign(CENTER);
1962 if (e && e->hasTagName(legendTag))
1963 style->setDisplay(BLOCK);
1965 // Absolute/fixed positioned elements, floating elements and the document element need block-like outside display.
1966 if (style->position() == AbsolutePosition || style->position() == FixedPosition || style->isFloating() || (e && e->document()->documentElement() == e))
1967 style->setDisplay(equivalentBlockDisplay(style->display(), style->isFloating(), m_checker.strictParsing()));
1969 // FIXME: Don't support this mutation for pseudo styles like first-letter or first-line, since it's not completely
1970 // clear how that should work.
1971 if (style->display() == INLINE && style->styleType() == NOPSEUDO && parentStyle && style->writingMode() != parentStyle->writingMode())
1972 style->setDisplay(INLINE_BLOCK);
1974 // After performing the display mutation, check table rows. We do not honor position:relative on
1975 // table rows or cells. This has been established in CSS2.1 (and caused a crash in containingBlock()
1977 if ((style->display() == TABLE_HEADER_GROUP || style->display() == TABLE_ROW_GROUP
1978 || style->display() == TABLE_FOOTER_GROUP || style->display() == TABLE_ROW) &&
1979 style->position() == RelativePosition)
1980 style->setPosition(StaticPosition);
1982 // writing-mode does not apply to table row groups, table column groups, table rows, and table columns.
1983 // FIXME: Table cells should be allowed to be perpendicular or flipped with respect to the table, though.
1984 if (style->display() == TABLE_COLUMN || style->display() == TABLE_COLUMN_GROUP || style->display() == TABLE_FOOTER_GROUP
1985 || style->display() == TABLE_HEADER_GROUP || style->display() == TABLE_ROW || style->display() == TABLE_ROW_GROUP
1986 || style->display() == TABLE_CELL)
1987 style->setWritingMode(parentStyle->writingMode());
1989 // FIXME: Since we don't support block-flow on flexible boxes yet, disallow setting
1990 // of block-flow to anything other than TopToBottomWritingMode.
1991 // https://bugs.webkit.org/show_bug.cgi?id=46418 - Flexible box support.
1992 if (style->writingMode() != TopToBottomWritingMode && (style->display() == BOX || style->display() == INLINE_BOX))
1993 style->setWritingMode(TopToBottomWritingMode);
1996 // Make sure our z-index value is only applied if the object is positioned.
1997 if (style->position() == StaticPosition)
1998 style->setHasAutoZIndex();
2000 // Auto z-index becomes 0 for the root element and transparent objects. This prevents
2001 // cases where objects that should be blended as a single unit end up with a non-transparent
2002 // object wedged in between them. Auto z-index also becomes 0 for objects that specify transforms/masks/reflections.
2003 if (style->hasAutoZIndex() && ((e && e->document()->documentElement() == e) || style->opacity() < 1.0f
2004 || style->hasTransformRelatedProperty() || style->hasMask() || style->boxReflect() || style->hasFilter()
2005 #if ENABLE(OVERFLOW_SCROLLING)
2006 // Touch overflow scrolling creates a stacking context.
2007 || style->useTouchOverflowScrolling()
2010 style->setZIndex(0);
2012 // Textarea considers overflow visible as auto.
2013 if (e && e->hasTagName(textareaTag)) {
2014 style->setOverflowX(style->overflowX() == OVISIBLE ? OAUTO : style->overflowX());
2015 style->setOverflowY(style->overflowY() == OVISIBLE ? OAUTO : style->overflowY());
2018 // Finally update our text decorations in effect, but don't allow text-decoration to percolate through
2019 // tables, inline blocks, inline tables, run-ins, or shadow DOM.
2020 if (style->display() == TABLE || style->display() == INLINE_TABLE || style->display() == RUN_IN
2021 || style->display() == INLINE_BLOCK || style->display() == INLINE_BOX || isAtShadowBoundary(e))
2022 style->setTextDecorationsInEffect(style->textDecoration());
2024 style->addToTextDecorationsInEffect(style->textDecoration());
2026 // If either overflow value is not visible, change to auto.
2027 if (style->overflowX() == OMARQUEE && style->overflowY() != OMARQUEE)
2028 style->setOverflowY(OMARQUEE);
2029 else if (style->overflowY() == OMARQUEE && style->overflowX() != OMARQUEE)
2030 style->setOverflowX(OMARQUEE);
2031 else if (style->overflowX() == OVISIBLE && style->overflowY() != OVISIBLE)
2032 style->setOverflowX(OAUTO);
2033 else if (style->overflowY() == OVISIBLE && style->overflowX() != OVISIBLE)
2034 style->setOverflowY(OAUTO);
2036 // Table rows, sections and the table itself will support overflow:hidden and will ignore scroll/auto.
2037 // FIXME: Eventually table sections will support auto and scroll.
2038 if (style->display() == TABLE || style->display() == INLINE_TABLE ||
2039 style->display() == TABLE_ROW_GROUP || style->display() == TABLE_ROW) {
2040 if (style->overflowX() != OVISIBLE && style->overflowX() != OHIDDEN)
2041 style->setOverflowX(OVISIBLE);
2042 if (style->overflowY() != OVISIBLE && style->overflowY() != OHIDDEN)
2043 style->setOverflowY(OVISIBLE);
2046 // Menulists should have visible overflow
2047 if (style->appearance() == MenulistPart) {
2048 style->setOverflowX(OVISIBLE);
2049 style->setOverflowY(OVISIBLE);
2052 // Cull out any useless layers and also repeat patterns into additional layers.
2053 style->adjustBackgroundLayers();
2054 style->adjustMaskLayers();
2056 // Do the same for animations and transitions.
2057 style->adjustAnimations();
2058 style->adjustTransitions();
2060 // Important: Intrinsic margins get added to controls before the theme has adjusted the style, since the theme will
2061 // alter fonts and heights/widths.
2062 if (e && e->isFormControlElement() && style->fontSize() >= 11) {
2063 // Don't apply intrinsic margins to image buttons. The designer knows how big the images are,
2064 // so we have to treat all image buttons as though they were explicitly sized.
2065 if (!e->hasTagName(inputTag) || !static_cast<HTMLInputElement*>(e)->isImageButton())
2066 addIntrinsicMargins(style);
2069 // Let the theme also have a crack at adjusting the style.
2070 if (style->hasAppearance())
2071 RenderTheme::defaultTheme()->adjustStyle(this, style, e, m_hasUAAppearance, m_borderData, m_backgroundData, m_backgroundColor);
2073 // If we have first-letter pseudo style, do not share this style.
2074 if (style->hasPseudoStyle(FIRST_LETTER))
2078 if (e && e->isSVGElement()) {
2079 // Spec: http://www.w3.org/TR/SVG/masking.html#OverflowProperty
2080 if (style->overflowY() == OSCROLL)
2081 style->setOverflowY(OHIDDEN);
2082 else if (style->overflowY() == OAUTO)
2083 style->setOverflowY(OVISIBLE);
2085 if (style->overflowX() == OSCROLL)
2086 style->setOverflowX(OHIDDEN);
2087 else if (style->overflowX() == OAUTO)
2088 style->setOverflowX(OVISIBLE);
2090 // Only the root <svg> element in an SVG document fragment tree honors css position
2091 if (!(e->hasTagName(SVGNames::svgTag) && e->parentNode() && !e->parentNode()->isSVGElement()))
2092 style->setPosition(RenderStyle::initialPosition());
2094 // RenderSVGRoot handles zooming for the whole SVG subtree, so foreignObject content should
2095 // not be scaled again.
2096 if (e->hasTagName(SVGNames::foreignObjectTag))
2097 style->setEffectiveZoom(RenderStyle::initialZoom());
2102 bool CSSStyleSelector::checkRegionStyle(Element* regionElement)
2104 // FIXME (BUG 72472): We don't add @-webkit-region rules of scoped style sheets for the moment,
2105 // so all region rules are global by default. Verify whether that can stand or needs changing.
2107 unsigned rulesSize = m_authorStyle->m_regionSelectorsAndRuleSets.size();
2108 for (unsigned i = 0; i < rulesSize; ++i) {
2109 ASSERT(m_authorStyle->m_regionSelectorsAndRuleSets.at(i).ruleSet.get());
2110 if (checkRegionSelector(m_authorStyle->m_regionSelectorsAndRuleSets.at(i).selector, regionElement))
2115 rulesSize = m_userStyle->m_regionSelectorsAndRuleSets.size();
2116 for (unsigned i = 0; i < rulesSize; ++i) {
2117 ASSERT(m_userStyle->m_regionSelectorsAndRuleSets.at(i).ruleSet.get());
2118 if (checkRegionSelector(m_userStyle->m_regionSelectorsAndRuleSets.at(i).selector, regionElement))
2126 void CSSStyleSelector::updateFont()
2131 checkForTextSizeAdjust();
2132 checkForGenericFamilyChange(style(), m_parentStyle);
2133 checkForZoomChange(style(), m_parentStyle);
2134 m_style->font().update(m_fontSelector);
2135 m_fontDirty = false;
2138 void CSSStyleSelector::cacheBorderAndBackground()
2140 m_hasUAAppearance = m_style->hasAppearance();
2141 if (m_hasUAAppearance) {
2142 m_borderData = m_style->border();
2143 m_backgroundData = *m_style->backgroundLayers();
2144 m_backgroundColor = m_style->backgroundColor();
2148 PassRefPtr<CSSRuleList> CSSStyleSelector::styleRulesForElement(Element* e, unsigned rulesToInclude)
2150 return pseudoStyleRulesForElement(e, NOPSEUDO, rulesToInclude);
2153 PassRefPtr<CSSRuleList> CSSStyleSelector::pseudoStyleRulesForElement(Element* e, PseudoId pseudoId, unsigned rulesToInclude)
2155 if (!e || !e->document()->haveStylesheetsLoaded())
2158 m_checker.setCollectingRulesOnly(true);
2161 initForStyleResolve(e, 0, pseudoId);
2164 if (rulesToInclude & UAAndUserCSSRules) {
2165 // First we match rules from the user agent sheet.
2166 matchUARules(dummy);
2168 // Now we check user sheet rules.
2169 if (m_matchAuthorAndUserStyles)
2170 matchUserRules(dummy, rulesToInclude & EmptyCSSRules);
2173 if (m_matchAuthorAndUserStyles && (rulesToInclude & AuthorCSSRules)) {
2174 m_sameOriginOnly = !(rulesToInclude & CrossOriginCSSRules);
2176 // Check the rules in author sheets.
2177 matchAuthorRules(dummy, rulesToInclude & EmptyCSSRules);
2179 m_sameOriginOnly = false;
2182 m_checker.setCollectingRulesOnly(false);
2184 return m_ruleList.release();
2187 inline bool CSSStyleSelector::checkSelector(const RuleData& ruleData, const ContainerNode* scope)
2189 m_dynamicPseudo = NOPSEUDO;
2190 m_checker.clearHasUnknownPseudoElements();
2192 if (ruleData.hasFastCheckableSelector()) {
2193 // We know this selector does not include any pseudo elements.
2194 if (m_checker.pseudoStyle() != NOPSEUDO)
2196 // We know a sufficiently simple single part selector matches simply because we found it from the rule hash.
2197 // This is limited to HTML only so we don't need to check the namespace.
2198 if (ruleData.hasRightmostSelectorMatchingHTMLBasedOnRuleHash() && m_element->isHTMLElement()) {
2199 if (!ruleData.hasMultipartSelector())
2201 } else if (!SelectorChecker::tagMatches(m_element, ruleData.selector()))
2203 if (!SelectorChecker::fastCheckRightmostAttributeSelector(m_element, ruleData.selector()))
2205 return m_checker.fastCheckSelector(ruleData.selector(), m_element);
2209 SelectorChecker::SelectorCheckingContext context(ruleData.selector(), m_element, SelectorChecker::VisitedMatchEnabled);
2210 context.elementStyle = style();
2211 context.elementParentStyle = m_parentNode ? m_parentNode->renderStyle() : 0;
2212 context.scope = scope;
2213 SelectorChecker::SelectorMatch match = m_checker.checkSelector(context, m_dynamicPseudo);
2214 if (match != SelectorChecker::SelectorMatches)
2216 if (m_checker.pseudoStyle() != NOPSEUDO && m_checker.pseudoStyle() != m_dynamicPseudo)
2221 bool CSSStyleSelector::checkRegionSelector(CSSSelector* regionSelector, Element* regionElement)
2223 if (!regionSelector || !regionElement)
2226 m_checker.clearHasUnknownPseudoElements();
2227 m_checker.setPseudoStyle(NOPSEUDO);
2229 for (CSSSelector* s = regionSelector; s; s = CSSSelectorList::next(s))
2230 if (m_checker.checkSelector(s, regionElement))
2236 bool CSSStyleSelector::determineStylesheetSelectorScopes(CSSStyleSheet* stylesheet, HashSet<AtomicStringImpl*>& idScopes, HashSet<AtomicStringImpl*>& classScopes)
2238 ASSERT(!stylesheet->isLoading());
2240 const Vector<RefPtr<StyleRuleImport> >& importRules = stylesheet->importRules();
2241 for (unsigned i = 0; i < importRules.size(); ++i) {
2242 if (!importRules[i]->styleSheet())
2244 if (!determineStylesheetSelectorScopes(importRules[i]->styleSheet(), idScopes, classScopes))
2248 const Vector<RefPtr<StyleRuleBase> >& rules = stylesheet->childRules();
2249 for (unsigned i = 0; i < rules.size(); i++) {
2250 StyleRuleBase* rule = rules[i].get();
2251 if (rule->isStyleRule()) {
2252 StyleRule* styleRule = static_cast<StyleRule*>(rule);
2253 if (!SelectorChecker::determineSelectorScopes(styleRule->selectorList(), idScopes, classScopes))
2257 // FIXME: Media rules and maybe some others could be allowed.
2263 // -----------------------------------------------------------------
2265 static inline bool isSelectorMatchingHTMLBasedOnRuleHash(const CSSSelector* selector)
2267 const AtomicString& selectorNamespace = selector->tag().namespaceURI();
2268 if (selectorNamespace != starAtom && selectorNamespace != xhtmlNamespaceURI)
2270 if (selector->m_match == CSSSelector::None)
2272 if (selector->tag() != starAtom)
2274 if (SelectorChecker::isCommonPseudoClassSelector(selector))
2276 return selector->m_match == CSSSelector::Id || selector->m_match == CSSSelector::Class;
2279 static inline bool selectorListContainsUncommonAttributeSelector(const CSSSelector* selector)
2281 CSSSelectorList* selectorList = selector->selectorList();
2284 for (CSSSelector* subSelector = selectorList->first(); subSelector; subSelector = CSSSelectorList::next(subSelector)) {
2285 if (subSelector->isAttributeSelector())
2291 static inline bool isCommonAttributeSelectorAttribute(const QualifiedName& attribute)
2293 // These are explicitly tested for equality in canShareStyleWithElement.
2294 return attribute == typeAttr || attribute == readonlyAttr;
2297 static inline bool containsUncommonAttributeSelector(const CSSSelector* selector)
2300 // Allow certain common attributes (used in the default style) in the selectors that match the current element.
2301 if (selector->isAttributeSelector() && !isCommonAttributeSelectorAttribute(selector->attribute()))
2303 if (selectorListContainsUncommonAttributeSelector(selector))
2305 if (selector->relation() != CSSSelector::SubSelector)
2307 selector = selector->tagHistory();
2310 for (selector = selector->tagHistory(); selector; selector = selector->tagHistory()) {
2311 if (selector->isAttributeSelector())
2313 if (selectorListContainsUncommonAttributeSelector(selector))
2319 RuleData::RuleData(StyleRule* rule, CSSSelector* selector, unsigned position, bool hasDocumentSecurityOrigin, bool canUseFastCheckSelector, bool inRegionRule)
2321 , m_selector(selector)
2322 , m_specificity(selector->specificity())
2323 , m_position(position)
2324 , m_hasFastCheckableSelector(canUseFastCheckSelector && SelectorChecker::isFastCheckableSelector(selector))
2325 , m_hasMultipartSelector(!!selector->tagHistory())
2326 , m_hasRightmostSelectorMatchingHTMLBasedOnRuleHash(isSelectorMatchingHTMLBasedOnRuleHash(selector))
2327 , m_containsUncommonAttributeSelector(WebCore::containsUncommonAttributeSelector(selector))
2328 , m_linkMatchType(SelectorChecker::determineLinkMatchType(selector))
2329 , m_hasDocumentSecurityOrigin(hasDocumentSecurityOrigin)
2330 , m_isInRegionRule(inRegionRule)
2332 SelectorChecker::collectIdentifierHashes(m_selector, m_descendantSelectorIdentifierHashes, maximumIdentifierCount);
2337 , m_autoShrinkToFitEnabled(true)
2341 static inline void collectFeaturesFromSelector(CSSStyleSelector::Features& features, const CSSSelector* selector)
2343 if (selector->m_match == CSSSelector::Id)
2344 features.idsInRules.add(selector->value().impl());
2345 if (selector->isAttributeSelector())
2346 features.attrsInRules.add(selector->attribute().localName().impl());
2347 switch (selector->pseudoType()) {
2348 case CSSSelector::PseudoFirstLine:
2349 features.usesFirstLineRules = true;
2351 case CSSSelector::PseudoBefore:
2352 case CSSSelector::PseudoAfter:
2353 features.usesBeforeAfterRules = true;
2355 case CSSSelector::PseudoLink:
2356 case CSSSelector::PseudoVisited:
2357 features.usesLinkRules = true;
2364 static void collectFeaturesFromRuleData(CSSStyleSelector::Features& features, const RuleData& ruleData)
2366 bool foundSiblingSelector = false;
2367 for (CSSSelector* selector = ruleData.selector(); selector; selector = selector->tagHistory()) {
2368 collectFeaturesFromSelector(features, selector);
2370 if (CSSSelectorList* selectorList = selector->selectorList()) {
2371 for (CSSSelector* subSelector = selectorList->first(); subSelector; subSelector = CSSSelectorList::next(subSelector)) {
2372 if (!foundSiblingSelector && selector->isSiblingSelector())
2373 foundSiblingSelector = true;
2374 collectFeaturesFromSelector(features, subSelector);
2376 } else if (!foundSiblingSelector && selector->isSiblingSelector())
2377 foundSiblingSelector = true;
2379 if (foundSiblingSelector)
2380 features.siblingRules.append(CSSStyleSelector::RuleFeature(ruleData.rule(), ruleData.selector(), ruleData.hasDocumentSecurityOrigin()));
2381 if (ruleData.containsUncommonAttributeSelector())
2382 features.uncommonAttributeRules.append(CSSStyleSelector::RuleFeature(ruleData.rule(), ruleData.selector(), ruleData.hasDocumentSecurityOrigin()));
2385 void RuleSet::addToRuleSet(AtomicStringImpl* key, AtomRuleMap& map, const RuleData& ruleData)
2389 OwnPtr<Vector<RuleData> >& rules = map.add(key, nullptr).iterator->second;
2391 rules = adoptPtr(new Vector<RuleData>);
2392 rules->append(ruleData);
2395 void RuleSet::addRule(StyleRule* rule, CSSSelector* selector, bool hasDocumentSecurityOrigin, bool canUseFastCheckSelector, bool inRegionRule)
2397 RuleData ruleData(rule, selector, m_ruleCount++, hasDocumentSecurityOrigin, canUseFastCheckSelector, inRegionRule);
2398 collectFeaturesFromRuleData(m_features, ruleData);
2400 if (selector->m_match == CSSSelector::Id) {
2401 addToRuleSet(selector->value().impl(), m_idRules, ruleData);
2404 if (selector->m_match == CSSSelector::Class) {
2405 addToRuleSet(selector->value().impl(), m_classRules, ruleData);
2408 if (selector->isUnknownPseudoElement()) {
2409 addToRuleSet(selector->value().impl(), m_shadowPseudoElementRules, ruleData);
2412 if (SelectorChecker::isCommonPseudoClassSelector(selector)) {
2413 switch (selector->pseudoType()) {
2414 case CSSSelector::PseudoLink:
2415 case CSSSelector::PseudoVisited:
2416 case CSSSelector::PseudoAnyLink:
2417 m_linkPseudoClassRules.append(ruleData);
2419 case CSSSelector::PseudoFocus:
2420 m_focusPseudoClassRules.append(ruleData);
2423 ASSERT_NOT_REACHED();
2427 const AtomicString& localName = selector->tag().localName();
2428 if (localName != starAtom) {
2429 addToRuleSet(localName.impl(), m_tagRules, ruleData);
2432 m_universalRules.append(ruleData);
2435 void RuleSet::addPageRule(StyleRulePage* rule)
2437 m_pageRules.append(rule);
2440 void RuleSet::addRegionRule(StyleRuleRegion* regionRule, bool hasDocumentSecurityOrigin)
2442 OwnPtr<RuleSet> regionRuleSet = RuleSet::create();
2443 // The region rule set should take into account the position inside the parent rule set.
2444 // Otherwise, the rules inside region block might be incorrectly positioned before other similar rules from
2445 // the stylesheet that contains the region block.
2446 regionRuleSet->m_ruleCount = m_ruleCount;
2448 // Collect the region rules into a rule set
2449 const Vector<RefPtr<StyleRuleBase> >& childRules = regionRule->childRules();
2450 for (unsigned i = 0; i < childRules.size(); ++i) {
2451 StyleRuleBase* regionStylingRule = childRules[i].get();
2452 if (regionStylingRule->isStyleRule())
2453 regionRuleSet->addStyleRule(static_cast<StyleRule*>(regionStylingRule), hasDocumentSecurityOrigin, true, true);
2455 // Update the "global" rule count so that proper order is maintained
2456 m_ruleCount = regionRuleSet->m_ruleCount;
2458 m_regionSelectorsAndRuleSets.append(RuleSetSelectorPair(regionRule->selectorList().first(), regionRuleSet.release()));
2461 void RuleSet::addRulesFromSheet(CSSStyleSheet* sheet, const MediaQueryEvaluator& medium, CSSStyleSelector* styleSelector, const ContainerNode* scope)
2465 // No media implies "all", but if a media list exists it must
2466 // contain our current medium
2467 if (sheet->mediaQueries() && !medium.eval(sheet->mediaQueries(), styleSelector))
2468 return; // the style sheet doesn't apply
2470 const Vector<RefPtr<StyleRuleImport> >& importRules = sheet->importRules();
2471 for (unsigned i = 0; i < importRules.size(); ++i) {
2472 StyleRuleImport* importRule = importRules[i].get();
2473 if (importRule->styleSheet() && (!importRule->mediaQueries() || medium.eval(importRule->mediaQueries(), styleSelector)))
2474 addRulesFromSheet(importRule->styleSheet(), medium, styleSelector, scope);
2476 bool hasDocumentSecurityOrigin = styleSelector && styleSelector->document()->securityOrigin()->canRequest(sheet->baseURL());
2478 const Vector<RefPtr<StyleRuleBase> >& rules = sheet->childRules();
2479 for (unsigned i = 0; i < rules.size(); ++i) {
2480 StyleRuleBase* rule = rules[i].get();
2482 ASSERT(!rule->isImportRule());
2483 if (rule->isStyleRule())
2484 addStyleRule(static_cast<StyleRule*>(rule), hasDocumentSecurityOrigin, !scope);
2485 else if (rule->isPageRule())
2486 addPageRule(static_cast<StyleRulePage*>(rule));
2487 else if (rule->isMediaRule()) {
2488 StyleRuleMedia* mediaRule = static_cast<StyleRuleMedia*>(rule);
2490 if ((!mediaRule->mediaQueries() || medium.eval(mediaRule->mediaQueries(), styleSelector))) {
2491 // Traverse child elements of the @media rule.
2492 const Vector<RefPtr<StyleRuleBase> >& childRules = mediaRule->childRules();
2493 for (unsigned j = 0; j < childRules.size(); ++j) {
2494 StyleRuleBase* childRule = childRules[j].get();
2495 if (childRule->isStyleRule())
2496 addStyleRule(static_cast<StyleRule*>(childRule), hasDocumentSecurityOrigin, !scope);
2497 else if (childRule->isPageRule())
2498 addPageRule(static_cast<StyleRulePage*>(childRule));
2499 else if (childRule->isFontFaceRule() && styleSelector) {
2500 // Add this font face to our set.
2501 // FIXME(BUG 72461): We don't add @font-face rules of scoped style sheets for the moment.
2504 const StyleRuleFontFace* fontFaceRule = static_cast<StyleRuleFontFace*>(childRule);
2505 styleSelector->fontSelector()->addFontFaceRule(fontFaceRule);
2506 styleSelector->invalidateMatchedPropertiesCache();
2507 } else if (childRule->isKeyframesRule() && styleSelector) {
2508 // Add this keyframe rule to our set.
2509 // FIXME(BUG 72462): We don't add @keyframe rules of scoped style sheets for the moment.
2512 styleSelector->addKeyframeStyle(static_cast<StyleRuleKeyframes*>(childRule));
2516 } else if (rule->isFontFaceRule() && styleSelector) {
2517 // Add this font face to our set.
2518 // FIXME(BUG 72461): We don't add @font-face rules of scoped style sheets for the moment.
2521 const StyleRuleFontFace* fontFaceRule = static_cast<StyleRuleFontFace*>(rule);
2522 styleSelector->fontSelector()->addFontFaceRule(fontFaceRule);
2523 styleSelector->invalidateMatchedPropertiesCache();
2524 } else if (rule->isKeyframesRule()) {
2525 // FIXME (BUG 72462): We don't add @keyframe rules of scoped style sheets for the moment.
2528 styleSelector->addKeyframeStyle(static_cast<StyleRuleKeyframes*>(rule));
2529 } else if (rule->isRegionRule() && styleSelector) {
2530 // FIXME (BUG 72472): We don't add @-webkit-region rules of scoped style sheets for the moment.
2533 addRegionRule(static_cast<StyleRuleRegion*>(rule), hasDocumentSecurityOrigin);
2536 if (m_autoShrinkToFitEnabled)
2540 void RuleSet::addStyleRule(StyleRule* rule, bool hasDocumentSecurityOrigin, bool canUseFastCheckSelector, bool isInRegionRule)
2542 for (CSSSelector* s = rule->selectorList().first(); s; s = CSSSelectorList::next(s))
2543 addRule(rule, s, hasDocumentSecurityOrigin, canUseFastCheckSelector, isInRegionRule);
2546 static inline void shrinkMapVectorsToFit(RuleSet::AtomRuleMap& map)
2548 RuleSet::AtomRuleMap::iterator end = map.end();
2549 for (RuleSet::AtomRuleMap::iterator it = map.begin(); it != end; ++it)
2550 it->second->shrinkToFit();
2553 void RuleSet::shrinkToFit()
2555 shrinkMapVectorsToFit(m_idRules);
2556 shrinkMapVectorsToFit(m_classRules);
2557 shrinkMapVectorsToFit(m_tagRules);
2558 shrinkMapVectorsToFit(m_shadowPseudoElementRules);
2559 m_linkPseudoClassRules.shrinkToFit();
2560 m_focusPseudoClassRules.shrinkToFit();
2561 m_universalRules.shrinkToFit();
2562 m_pageRules.shrinkToFit();
2565 // -------------------------------------------------------------------------------------
2566 // this is mostly boring stuff on how to apply a certain rule to the renderstyle...
2568 Length CSSStyleSelector::convertToIntLength(CSSPrimitiveValue* primitiveValue, RenderStyle* style, RenderStyle* rootStyle, double multiplier)
2570 return primitiveValue ? primitiveValue->convertToLength<FixedIntegerConversion | PercentConversion | FractionConversion | ViewportPercentageConversion>(style, rootStyle, multiplier) : Length(Undefined);
2573 Length CSSStyleSelector::convertToFloatLength(CSSPrimitiveValue* primitiveValue, RenderStyle* style, RenderStyle* rootStyle, double multiplier)
2575 return primitiveValue ? primitiveValue->convertToLength<FixedFloatConversion | PercentConversion | FractionConversion | ViewportPercentageConversion>(style, rootStyle, multiplier) : Length(Undefined);
2578 template <bool applyFirst>
2579 void CSSStyleSelector::applyProperties(const StylePropertySet* properties, StyleRule* rule, bool isImportant, bool inheritedOnly, bool filterRegionProperties)
2581 ASSERT(!filterRegionProperties || m_regionForStyling);
2582 InspectorInstrumentationCookie cookie = InspectorInstrumentation::willProcessRule(document(), rule);
2584 unsigned propertyCount = properties->propertyCount();
2585 for (unsigned i = 0; i < propertyCount; ++i) {
2586 const CSSProperty& current = properties->propertyAt(i);
2587 if (isImportant != current.isImportant())
2589 if (inheritedOnly && !current.isInherited()) {
2590 // If the property value is explicitly inherited, we need to apply further non-inherited properties
2591 // as they might override the value inherited here. For this reason we don't allow declarations with
2592 // explicitly inherited properties to be cached.
2593 ASSERT(!current.value()->isInheritedValue());
2596 int property = current.id();
2598 if (filterRegionProperties && !CSSStyleSelector::isValidRegionStyleProperty(property))
2602 COMPILE_ASSERT(firstCSSProperty == CSSPropertyColor, CSS_color_is_first_property);
2603 COMPILE_ASSERT(CSSPropertyZoom == CSSPropertyColor + 18, CSS_zoom_is_end_of_first_prop_range);
2604 COMPILE_ASSERT(CSSPropertyLineHeight == CSSPropertyZoom + 1, CSS_line_height_is_after_zoom);
2605 // give special priority to font-xxx, color properties, etc
2606 if (property > CSSPropertyLineHeight)
2608 // we apply line-height later
2609 if (property == CSSPropertyLineHeight) {
2610 m_lineHeightValue = current.value();
2613 applyProperty(current.id(), current.value());
2616 if (property > CSSPropertyLineHeight)
2617 applyProperty(current.id(), current.value());
2619 InspectorInstrumentation::didProcessRule(cookie);
2622 template <bool applyFirst>
2623 void CSSStyleSelector::applyMatchedProperties(const MatchResult& matchResult, bool isImportant, int startIndex, int endIndex, bool inheritedOnly)
2625 if (startIndex == -1)
2628 if (m_style->insideLink() != NotInsideLink) {
2629 for (int i = startIndex; i <= endIndex; ++i) {
2630 const MatchedProperties& matchedProperties = matchResult.matchedProperties[i];
2631 unsigned linkMatchType = matchedProperties.linkMatchType;
2632 // FIXME: It would be nicer to pass these as arguments but that requires changes in many places.
2633 m_applyPropertyToRegularStyle = linkMatchType & SelectorChecker::MatchLink;
2634 m_applyPropertyToVisitedLinkStyle = linkMatchType & SelectorChecker::MatchVisited;
2636 applyProperties<applyFirst>(matchedProperties.properties.get(), matchResult.matchedRules[i], isImportant, inheritedOnly, matchedProperties.isInRegionRule);
2638 m_applyPropertyToRegularStyle = true;
2639 m_applyPropertyToVisitedLinkStyle = false;
2642 for (int i = startIndex; i <= endIndex; ++i) {
2643 const MatchedProperties& matchedProperties = matchResult.matchedProperties[i];
2644 applyProperties<applyFirst>(matchedProperties.properties.get(), matchResult.matchedRules[i], isImportant, inheritedOnly, matchedProperties.isInRegionRule);
2648 unsigned CSSStyleSelector::computeMatchedPropertiesHash(const MatchedProperties* properties, unsigned size)
2651 return StringHasher::hashMemory(properties, sizeof(MatchedProperties) * size);
2654 bool operator==(const CSSStyleSelector::MatchRanges& a, const CSSStyleSelector::MatchRanges& b)
2656 return a.firstUARule == b.firstUARule
2657 && a.lastUARule == b.lastUARule
2658 && a.firstAuthorRule == b.firstAuthorRule
2659 && a.lastAuthorRule == b.lastAuthorRule
2660 && a.firstUserRule == b.firstUserRule
2661 && a.lastUserRule == b.lastUserRule;
2664 bool operator!=(const CSSStyleSelector::MatchRanges& a, const CSSStyleSelector::MatchRanges& b)
2669 bool operator==(const CSSStyleSelector::MatchedProperties& a, const CSSStyleSelector::MatchedProperties& b)
2671 return a.properties == b.properties && a.linkMatchType == b.linkMatchType;
2674 bool operator!=(const CSSStyleSelector::MatchedProperties& a, const CSSStyleSelector::MatchedProperties& b)
2679 const CSSStyleSelector::MatchedPropertiesCacheItem* CSSStyleSelector::findFromMatchedPropertiesCache(unsigned hash, const MatchResult& matchResult)
2683 MatchedPropertiesCache::iterator it = m_matchedPropertiesCache.find(hash);
2684 if (it == m_matchedPropertiesCache.end())
2686 MatchedPropertiesCacheItem& cacheItem = it->second;
2688 size_t size = matchResult.matchedProperties.size();
2689 if (size != cacheItem.matchedProperties.size())
2691 for (size_t i = 0; i < size; ++i) {
2692 if (matchResult.matchedProperties[i] != cacheItem.matchedProperties[i])
2695 if (cacheItem.ranges != matchResult.ranges)
2700 void CSSStyleSelector::addToMatchedPropertiesCache(const RenderStyle* style, const RenderStyle* parentStyle, unsigned hash, const MatchResult& matchResult)
2702 static unsigned matchedDeclarationCacheAdditionsBetweenSweeps = 100;
2703 if (++m_matchedPropertiesCacheAdditionsSinceLastSweep >= matchedDeclarationCacheAdditionsBetweenSweeps) {
2704 sweepMatchedPropertiesCache();
2705 m_matchedPropertiesCacheAdditionsSinceLastSweep = 0;
2709 MatchedPropertiesCacheItem cacheItem;
2710 cacheItem.matchedProperties.append(matchResult.matchedProperties);
2711 cacheItem.ranges = matchResult.ranges;
2712 // Note that we don't cache the original RenderStyle instance. It may be further modified.
2713 // The RenderStyle in the cache is really just a holder for the substructures and never used as-is.
2714 cacheItem.renderStyle = RenderStyle::clone(style);
2715 cacheItem.parentRenderStyle = RenderStyle::clone(parentStyle);
2716 m_matchedPropertiesCache.add(hash, cacheItem);
2719 void CSSStyleSelector::invalidateMatchedPropertiesCache()
2721 m_matchedPropertiesCache.clear();
2724 static bool isCacheableInMatchedPropertiesCache(const Element* element, const RenderStyle* style, const RenderStyle* parentStyle)
2726 // FIXME: CSSPropertyWebkitWritingMode modifies state when applying to document element. We can't skip the applying by caching.
2727 if (element == element->document()->documentElement() && element->document()->writingModeSetOnDocumentElement())
2729 if (style->unique() || (style->styleType() != NOPSEUDO && parentStyle->unique()))
2731 if (style->hasAppearance())
2733 if (style->zoom() != RenderStyle::initialZoom())
2735 // The cache assumes static knowledge about which properties are inherited.
2736 if (parentStyle->hasExplicitlyInheritedProperties())
2741 void CSSStyleSelector::applyMatchedProperties(const MatchResult& matchResult)
2743 unsigned cacheHash = matchResult.isCacheable ? computeMatchedPropertiesHash(matchResult.matchedProperties.data(), matchResult.matchedProperties.size()) : 0;
2744 bool applyInheritedOnly = false;
2745 const MatchedPropertiesCacheItem* cacheItem = 0;
2746 if (cacheHash && (cacheItem = findFromMatchedPropertiesCache(cacheHash, matchResult))) {
2747 // We can build up the style by copying non-inherited properties from an earlier style object built using the same exact
2748 // style declarations. We then only need to apply the inherited properties, if any, as their values can depend on the
2749 // element context. This is fast and saves memory by reusing the style data structures.
2750 m_style->copyNonInheritedFrom(cacheItem->renderStyle.get());
2751 if (m_parentStyle->inheritedDataShared(cacheItem->parentRenderStyle.get())) {
2752 EInsideLink linkStatus = m_style->insideLink();
2753 // If the cache item parent style has identical inherited properties to the current parent style then the
2754 // resulting style will be identical too. We copy the inherited properties over from the cache and are done.
2755 m_style->inheritFrom(cacheItem->renderStyle.get());
2756 // Unfortunately the link status is treated like an inherited property. We need to explicitly restore it.
2757 m_style->setInsideLink(linkStatus);
2760 applyInheritedOnly = true;
2762 // Now we have all of the matched rules in the appropriate order. Walk the rules and apply
2763 // high-priority properties first, i.e., those properties that other properties depend on.
2764 // The order is (1) high-priority not important, (2) high-priority important, (3) normal not important
2765 // and (4) normal important.
2766 m_lineHeightValue = 0;
2767 applyMatchedProperties<true>(matchResult, false, 0, matchResult.matchedProperties.size() - 1, applyInheritedOnly);
2768 applyMatchedProperties<true>(matchResult, true, matchResult.ranges.firstAuthorRule, matchResult.ranges.lastAuthorRule, applyInheritedOnly);
2769 applyMatchedProperties<true>(matchResult, true, matchResult.ranges.firstUserRule, matchResult.ranges.lastUserRule, applyInheritedOnly);
2770 applyMatchedProperties<true>(matchResult, true, matchResult.ranges.firstUARule, matchResult.ranges.lastUARule, applyInheritedOnly);
2772 if (cacheItem && cacheItem->renderStyle->effectiveZoom() != m_style->effectiveZoom()) {
2774 applyInheritedOnly = false;
2777 // If our font got dirtied, go ahead and update it now.
2780 // Line-height is set when we are sure we decided on the font-size.
2781 if (m_lineHeightValue)
2782 applyProperty(CSSPropertyLineHeight, m_lineHeightValue);
2784 // Many properties depend on the font. If it changes we just apply all properties.
2785 if (cacheItem && cacheItem->renderStyle->fontDescription() != m_style->fontDescription())
2786 applyInheritedOnly = false;
2788 // Now do the normal priority UA properties.
2789 applyMatchedProperties<false>(matchResult, false, matchResult.ranges.firstUARule, matchResult.ranges.lastUARule, applyInheritedOnly);
2791 // Cache our border and background so that we can examine them later.
2792 cacheBorderAndBackground();
2794 // Now do the author and user normal priority properties and all the !important properties.
2795 applyMatchedProperties<false>(matchResult, false, matchResult.ranges.lastUARule + 1, matchResult.matchedProperties.size() - 1, applyInheritedOnly);
2796 applyMatchedProperties<false>(matchResult, true, matchResult.ranges.firstAuthorRule, matchResult.ranges.lastAuthorRule, applyInheritedOnly);
2797 applyMatchedProperties<false>(matchResult, true, matchResult.ranges.firstUserRule, matchResult.ranges.lastUserRule, applyInheritedOnly);
2798 applyMatchedProperties<false>(matchResult, true, matchResult.ranges.firstUARule, matchResult.ranges.lastUARule, applyInheritedOnly);
2800 loadPendingImages();
2802 #if ENABLE(CSS_SHADERS)
2803 loadPendingShaders();
2806 ASSERT(!m_fontDirty);
2808 if (cacheItem || !cacheHash)
2810 if (!isCacheableInMatchedPropertiesCache(m_element, m_style.get(), m_parentStyle))
2812 addToMatchedPropertiesCache(m_style.get(), m_parentStyle, cacheHash, matchResult);
2815 static inline bool comparePageRules(const StyleRulePage* r1, const StyleRulePage* r2)
2817 return r1->selector()->specificity() < r2->selector()->specificity();
2820 void CSSStyleSelector::matchPageRules(MatchResult& result, RuleSet* rules, bool isLeftPage, bool isFirstPage, const String& pageName)
2825 Vector<StyleRulePage*> matchedPageRules;
2826 matchPageRulesForList(matchedPageRules, rules->pageRules(), isLeftPage, isFirstPage, pageName);
2827 if (matchedPageRules.isEmpty())
2830 std::stable_sort(matchedPageRules.begin(), matchedPageRules.end(), comparePageRules);
2832 for (unsigned i = 0; i < matchedPageRules.size(); i++)
2833 addMatchedProperties(result, matchedPageRules[i]->properties());
2836 void CSSStyleSelector::matchPageRulesForList(Vector<StyleRulePage*>& matchedRules, const Vector<StyleRulePage*>& rules, bool isLeftPage, bool isFirstPage, const String& pageName)
2838 unsigned size = rules.size();
2839 for (unsigned i = 0; i < size; ++i) {
2840 StyleRulePage* rule = rules[i];
2841 const AtomicString& selectorLocalName = rule->selector()->tag().localName();
2842 if (selectorLocalName != starAtom && selectorLocalName != pageName)
2844 CSSSelector::PseudoType pseudoType = rule->selector()->pseudoType();
2845 if ((pseudoType == CSSSelector::PseudoLeftPage && !isLeftPage)
2846 || (pseudoType == CSSSelector::PseudoRightPage && isLeftPage)
2847 || (pseudoType == CSSSelector::PseudoFirstPage && !isFirstPage))
2850 // If the rule has no properties to apply, then ignore it.
2851 StylePropertySet* properties = rule->properties();
2852 if (!properties || properties->isEmpty())
2855 // Add this rule to our list of matched rules.
2856 matchedRules.append(rule);
2860 bool CSSStyleSelector::isLeftPage(int pageIndex) const
2862 bool isFirstPageLeft = false;
2863 if (!m_rootElementStyle->isLeftToRightDirection())
2864 isFirstPageLeft = true;
2866 return (pageIndex + (isFirstPageLeft ? 1 : 0)) % 2;
2869 bool CSSStyleSelector::isFirstPage(int pageIndex) const
2871 // FIXME: In case of forced left/right page, page at index 1 (not 0) can be the first page.
2872 return (!pageIndex);
2875 String CSSStyleSelector::pageName(int /* pageIndex */) const
2877 // FIXME: Implement page index to page name mapping.
2881 template <class ListType>
2882 static void collectCSSOMWrappers(HashMap<StyleRule*, RefPtr<CSSStyleRule> >& wrapperMap, ListType* listType)
2886 unsigned size = listType->length();
2887 for (unsigned i = 0; i < size; ++i) {
2888 CSSRule* cssRule = listType->item(i);
2889 if (cssRule->isImportRule())
2890 collectCSSOMWrappers(wrapperMap, static_cast<CSSImportRule*>(cssRule)->styleSheet());
2891 else if (cssRule->isMediaRule())
2892 collectCSSOMWrappers(wrapperMap, static_cast<CSSMediaRule*>(cssRule));
2893 else if (cssRule->isRegionRule())
2894 collectCSSOMWrappers(wrapperMap, static_cast<WebKitCSSRegionRule*>(cssRule));
2895 else if (cssRule->isStyleRule()) {
2896 CSSStyleRule* cssStyleRule = static_cast<CSSStyleRule*>(cssRule);
2897 wrapperMap.add(cssStyleRule->styleRule(), cssStyleRule);
2902 static void collectCSSOMWrappers(HashMap<StyleRule*, RefPtr<CSSStyleRule> >& wrapperMap, Document* document)
2904 const Vector<RefPtr<StyleSheet> >& styleSheets = document->styleSheets()->vector();
2905 for (unsigned i = 0; i < styleSheets.size(); ++i) {
2906 StyleSheet* styleSheet = styleSheets[i].get();
2907 if (!styleSheet->isCSSStyleSheet())
2909 collectCSSOMWrappers(wrapperMap, static_cast<CSSStyleSheet*>(styleSheet));
2911 collectCSSOMWrappers(wrapperMap, document->pageUserSheet());
2914 CSSStyleRule* CSSStyleSelector::ensureFullCSSOMWrapperForInspector(StyleRule* rule)
2916 if (m_styleRuleToCSSOMWrapperMap.isEmpty()) {
2917 collectCSSOMWrappers(m_styleRuleToCSSOMWrapperMap, simpleDefaultStyleSheet);
2918 collectCSSOMWrappers(m_styleRuleToCSSOMWrapperMap, defaultStyleSheet);
2919 collectCSSOMWrappers(m_styleRuleToCSSOMWrapperMap, quirksStyleSheet);
2920 collectCSSOMWrappers(m_styleRuleToCSSOMWrapperMap, svgStyleSheet);
2921 collectCSSOMWrappers(m_styleRuleToCSSOMWrapperMap, mathMLStyleSheet);
2922 collectCSSOMWrappers(m_styleRuleToCSSOMWrapperMap, mediaControlsStyleSheet);
2923 collectCSSOMWrappers(m_styleRuleToCSSOMWrapperMap, fullscreenStyleSheet);
2925 collectCSSOMWrappers(m_styleRuleToCSSOMWrapperMap, document());
2927 return m_styleRuleToCSSOMWrapperMap.get(rule).get();
2930 void CSSStyleSelector::applyPropertyToStyle(int id, CSSValue* value, RenderStyle* style)
2933 initForStyleResolve(0, style);
2935 applyPropertyToCurrentStyle(id, value);
2938 void CSSStyleSelector::applyPropertyToCurrentStyle(int id, CSSValue* value)
2941 applyProperty(id, value);
2944 inline bool isValidVisitedLinkProperty(int id)
2946 switch(static_cast<CSSPropertyID>(id)) {
2947 case CSSPropertyBackgroundColor:
2948 case CSSPropertyBorderLeftColor:
2949 case CSSPropertyBorderRightColor:
2950 case CSSPropertyBorderTopColor:
2951 case CSSPropertyBorderBottomColor:
2952 case CSSPropertyColor:
2953 case CSSPropertyOutlineColor:
2954 case CSSPropertyWebkitColumnRuleColor:
2955 case CSSPropertyWebkitTextEmphasisColor:
2956 case CSSPropertyWebkitTextFillColor:
2957 case CSSPropertyWebkitTextStrokeColor:
2958 // Also allow shorthands so that inherit/initial still work.
2959 case CSSPropertyBackground:
2960 case CSSPropertyBorderLeft:
2961 case CSSPropertyBorderRight:
2962 case CSSPropertyBorderTop:
2963 case CSSPropertyBorderBottom:
2964 case CSSPropertyOutline:
2965 case CSSPropertyWebkitColumnRule:
2967 case CSSPropertyFill:
2968 case CSSPropertyStroke:
2978 // http://dev.w3.org/csswg/css3-regions/#the-at-region-style-rule
2979 // FIXME: add incremental support for other region styling properties.
2980 inline bool CSSStyleSelector::isValidRegionStyleProperty(int id)
2982 switch (static_cast<CSSPropertyID>(id)) {
2983 case CSSPropertyBackgroundColor:
2992 // SVG handles zooming in a different way compared to CSS. The whole document is scaled instead
2993 // of each individual length value in the render style / tree. CSSPrimitiveValue::computeLength*()
2994 // multiplies each resolved length with the zoom multiplier - so for SVG we need to disable that.
2995 // Though all CSS values that can be applied to outermost <svg> elements (width/height/border/padding...)
2996 // need to respect the scaling. RenderBox (the parent class of RenderSVGRoot) grabs values like
2997 // width/height/border/padding/... from the RenderStyle -> for SVG these values would never scale,
2998 // if we'd pass a 1.0 zoom factor everyhwere. So we only pass a zoom factor of 1.0 for specific
2999 // properties that are NOT allowed to scale within a zoomed SVG document (letter/word-spacing/font-size).
3000 bool CSSStyleSelector::useSVGZoomRules()
3002 return m_element && m_element->isSVGElement();
3005 #if ENABLE(CSS_GRID_LAYOUT)
3007 static bool createGridTrackBreadth(CSSPrimitiveValue* primitiveValue, CSSStyleSelector* selector, Length& length)
3009 Length workingLength = primitiveValue->convertToLength<FixedIntegerConversion | PercentConversion | ViewportPercentageConversion | AutoConversion>(selector->style(), selector->rootElementStyle(), selector->style()->effectiveZoom());
3010 if (workingLength.isUndefined())
3013 if (primitiveValue->isLength())
3014 workingLength.setQuirk(primitiveValue->isQuirkValue());
3016 length = workingLength;
3020 static bool createGridTrackList(CSSValue* value, Vector<Length>& lengths, CSSStyleSelector* selector)
3023 if (value->isPrimitiveValue()) {
3024 CSSPrimitiveValue* primitiveValue = static_cast<CSSPrimitiveValue*>(value);
3025 if (primitiveValue->getIdent() == CSSValueNone) {
3026 lengths.append(Length(Undefined));
3032 if (value->isValueList()) {
3033 for (CSSValueListIterator i = value; i.hasMore(); i.advance()) {
3034 CSSValue* currValue = i.value();
3035 if (!currValue->isPrimitiveValue())
3039 if (!createGridTrackBreadth(static_cast<CSSPrimitiveValue*>(currValue), selector, length))
3042 lengths.append(length);
3051 static bool createGridPosition(CSSValue* value, Length& position)
3053 // For now, we only accept: <integer> | 'auto'
3054 if (!value->isPrimitiveValue())
3057 CSSPrimitiveValue* primitiveValue = static_cast<CSSPrimitiveValue*>(value);
3058 if (primitiveValue->getIdent() == CSSValueAuto)
3061 ASSERT(primitiveValue->isNumber());
3062 position.setValue(primitiveValue->getIntValue());
3067 void CSSStyleSelector::applyProperty(int id, CSSValue *value)
3069 bool isInherit = m_parentNode && value->isInheritedValue();
3070 bool isInitial = value->isInitialValue() || (!m_parentNode && value->isInheritedValue());
3072 ASSERT(!isInherit || !isInitial); // isInherit -> !isInitial && isInitial -> !isInherit
3074 if (!applyPropertyToRegularStyle() && (!applyPropertyToVisitedLinkStyle() || !isValidVisitedLinkProperty(id))) {
3075 // Limit the properties that can be applied to only the ones honored by :visited.
3079 CSSPropertyID property = static_cast<CSSPropertyID>(id);
3081 if (isInherit && m_parentStyle && !m_parentStyle->hasExplicitlyInheritedProperties() && !CSSProperty::isInheritedProperty(property))
3082 m_parentStyle->setHasExplicitlyInheritedProperties();
3084 // check lookup table for implementations and use when available
3085 const PropertyHandler& handler = m_applyProperty.propertyHandler(property);
3086 if (handler.isValid()) {
3088 handler.applyInheritValue(this);
3090 handler.applyInitialValue(this);
3092 handler.applyValue(this, value);
3096 CSSPrimitiveValue* primitiveValue = value->isPrimitiveValue() ? static_cast<CSSPrimitiveValue*>(value) : 0;
3098 float zoomFactor = m_style->effectiveZoom();
3100 // What follows is a list that maps the CSS properties into their corresponding front-end
3101 // RenderStyle values. Shorthands (e.g. border, background) occur in this list as well and
3102 // are only hit when mapping "inherit" or "initial" into front-end values.
3105 case CSSPropertyContent:
3106 // list of string, uri, counter, attr, i
3108 // FIXME: In CSS3, it will be possible to inherit content. In CSS2 it is not. This
3109 // note is a reminder that eventually "inherit" needs to be supported.
3112 m_style->clearContent();
3116 if (!value->isValueList())
3119 bool didSet = false;
3120 for (CSSValueListIterator i = value; i.hasMore(); i.advance()) {
3121 CSSValue* item = i.value();
3122 if (item->isImageGeneratorValue()) {
3123 m_style->setContent(StyleGeneratedImage::create(static_cast<CSSImageGeneratorValue*>(item)), didSet);
3125 #if ENABLE(CSS_IMAGE_SET)
3126 } else if (item->isImageSetValue()) {
3127 m_style->setContent(setOrPendingFromValue(CSSPropertyContent, static_cast<CSSImageSetValue*>(item)), didSet);
3132 if (item->isImageValue()) {
3133 m_style->setContent(cachedOrPendingFromValue(CSSPropertyContent, static_cast<CSSImageValue*>(item)), didSet);
3138 if (!item->isPrimitiveValue())
3141 CSSPrimitiveValue* contentValue = static_cast<CSSPrimitiveValue*>(item);
3143 if (contentValue->isString()) {
3144 m_style->setContent(contentValue->getStringValue().impl(), didSet);
3146 } else if (contentValue->isAttr()) {
3147 // FIXME: Can a namespace be specified for an attr(foo)?
3148 if (m_style->styleType() == NOPSEUDO)
3149 m_style->setUnique();
3151 m_parentStyle->setUnique();
3152 QualifiedName attr(nullAtom, contentValue->getStringValue().impl(), nullAtom);
3153 const AtomicString& value = m_element->getAttribute(attr);
3154 m_style->setContent(value.isNull() ? emptyAtom : value.impl(), didSet);
3156 // register the fact that the attribute value affects the style
3157 m_features.attrsInRules.add(attr.localName().impl());
3158 } else if (contentValue->isCounter()) {
3159 Counter* counterValue = contentValue->getCounterValue();
3160 EListStyleType listStyleType = NoneListStyle;
3161 int listStyleIdent = counterValue->listStyleIdent();
3162 if (listStyleIdent != CSSValueNone)
3163 listStyleType = static_cast<EListStyleType>(listStyleIdent - CSSValueDisc);
3164 OwnPtr<CounterContent> counter = adoptPtr(new CounterContent(counterValue->identifier(), listStyleType, counterValue->separator()));
3165 m_style->setContent(counter.release(), didSet);
3168 switch (contentValue->getIdent()) {
3169 case CSSValueOpenQuote:
3170 m_style->setContent(OPEN_QUOTE, didSet);
3173 case CSSValueCloseQuote:
3174 m_style->setContent(CLOSE_QUOTE, didSet);
3177 case CSSValueNoOpenQuote:
3178 m_style->setContent(NO_OPEN_QUOTE, didSet);
3181 case CSSValueNoCloseQuote:
3182 m_style->setContent(NO_CLOSE_QUOTE, didSet);
3186 // normal and none do not have any effect.
3192 m_style->clearContent();
3195 case CSSPropertyQuotes:
3198 m_style->setQuotes(m_parentStyle->quotes());
3202 m_style->setQuotes(0);
3205 if (value->isValueList()) {
3206 CSSValueList* list = static_cast<CSSValueList*>(value);
3207 QuotesData* data = QuotesData::create(list->length());
3209 return; // Out of memory
3210 String* quotes = data->data();
3211 for (CSSValueListIterator i = list; i.hasMore(); i.advance()) {
3212 CSSValue* item = i.value();
3213 ASSERT(item->isPrimitiveValue());
3214 primitiveValue = static_cast<CSSPrimitiveValue*>(item);
3215 ASSERT(primitiveValue->isString());
3216 quotes[i.index()] = primitiveValue->getStringValue();
3218 m_style->setQuotes(adoptRef(data));
3219 } else if (primitiveValue) {
3220 ASSERT(primitiveValue->isIdent());
3221 if (primitiveValue->getIdent() == CSSValueNone)
3222 m_style->setQuotes(adoptRef(QuotesData::create(0)));
3225 case CSSPropertyFontFamily: {
3226 // list of strings and ids
3228 FontDescription parentFontDescription = m_parentStyle->fontDescription();
3229 FontDescription fontDescription = m_style->fontDescription();
3230 fontDescription.setGenericFamily(parentFontDescription.genericFamily());
3231 fontDescription.setFamily(parentFontDescription.firstFamily());
3232 fontDescription.setIsSpecifiedFont(parentFontDescription.isSpecifiedFont());
3233 setFontDescription(fontDescription);
3235 } else if (isInitial) {
3236 FontDescription initialDesc = FontDescription();
3237 FontDescription fontDescription = m_style->fontDescription();
3238 // We need to adjust the size to account for the generic family change from monospace
3239 // to non-monospace.
3240 if (fontDescription.keywordSize() && fontDescription.useFixedDefaultSize())
3241 setFontSize(fontDescription, fontSizeForKeyword(m_checker.document(), CSSValueXxSmall + fontDescription.keywordSize() - 1, false));
3242 fontDescription.setGenericFamily(initialDesc.genericFamily());
3243 if (!initialDesc.firstFamily().familyIsEmpty())
3244 fontDescription.setFamily(initialDesc.firstFamily());
3245 setFontDescription(fontDescription);
3249 if (!value->isValueList())
3251 FontDescription fontDescription = m_style->fontDescription();
3252 FontFamily& firstFamily = fontDescription.firstFamily();
3253 FontFamily* currFamily = 0;
3255 // Before mapping in a new font-family property, we should reset the generic family.
3256 bool oldFamilyUsedFixedDefaultSize = fontDescription.useFixedDefaultSize();
3257 fontDescription.setGenericFamily(FontDescription::NoFamily);
3259 for (CSSValueListIterator i = value; i.hasMore(); i.advance()) {
3260 CSSValue* item = i.value();
3261 if (!item->isPrimitiveValue())
3263 CSSPrimitiveValue* contentValue = static_cast<CSSPrimitiveValue*>(item);
3265 Settings* settings = m_checker.document()->settings();
3266 if (contentValue->isString())
3267 face = contentValue->getStringValue();
3268 else if (settings) {
3269 switch (contentValue->getIdent()) {
3270 case CSSValueWebkitBody:
3271 face = settings->standardFontFamily();
3275 fontDescription.setGenericFamily(FontDescription::SerifFamily);
3277 case CSSValueSansSerif:
3278 face = sansSerifFamily;
3279 fontDescription.setGenericFamily(FontDescription::SansSerifFamily);
3281 case CSSValueCursive:
3282 face = cursiveFamily;
3283 fontDescription.setGenericFamily(FontDescription::CursiveFamily);
3285 case CSSValueFantasy:
3286 face = fantasyFamily;
3287 fontDescription.setGenericFamily(FontDescription::FantasyFamily);
3289 case CSSValueMonospace:
3290 face = monospaceFamily;
3291 fontDescription.setGenericFamily(FontDescription::MonospaceFamily);
3293 case CSSValueWebkitPictograph:
3294 face = pictographFamily;
3295 fontDescription.setGenericFamily(FontDescription::PictographFamily);
3300 if (!face.isEmpty()) {
3302 // Filling in the first family.
3303 firstFamily.setFamily(face);
3304 firstFamily.appendFamily(0); // Remove any inherited family-fallback list.
3305 currFamily = &firstFamily;
3306 fontDescription.setIsSpecifiedFont(fontDescription.genericFamily() == FontDescription::NoFamily);
3308 RefPtr<SharedFontFamily> newFamily = SharedFontFamily::create();
3309 newFamily->setFamily(face);
3310 currFamily->appendFamily(newFamily);
3311 currFamily = newFamily.get();
3316 // We can't call useFixedDefaultSize() until all new font families have been added
3317 // If currFamily is non-zero then we set at least one family on this description.
3319 if (fontDescription.keywordSize() && fontDescription.useFixedDefaultSize() != oldFamilyUsedFixedDefaultSize)
3320 setFontSize(fontDescription, fontSizeForKeyword(m_checker.document(), CSSValueXxSmall + fontDescription.keywordSize() - 1, !oldFamilyUsedFixedDefaultSize));
3322 setFontDescription(fontDescription);
3326 // shorthand properties
3327 case CSSPropertyBackground:
3329 m_style->clearBackgroundLayers();
3330 m_style->setBackgroundColor(Color());
3332 else if (isInherit) {
3333 m_style->inheritBackgroundLayers(*m_parentStyle->backgroundLayers());
3334 m_style->setBackgroundColor(m_parentStyle->backgroundColor());
3337 case CSSPropertyWebkitMask:
3339 m_style->clearMaskLayers();
3341 m_style->inheritMaskLayers(*m_parentStyle->maskLayers());
3343 case CSSPropertyFont:
3345 FontDescription fontDescription = m_parentStyle->fontDescription();
3346 m_style->setLineHeight(m_parentStyle->lineHeight());
3347 m_lineHeightValue = 0;
3348 setFontDescription(fontDescription);
3349 } else if (isInitial) {
3350 Settings* settings = m_checker.document()->settings();
3351 ASSERT(settings); // If we're doing style resolution, this document should always be in a frame and thus have settings
3354 FontDescription fontDescription;
3355 fontDescription.setGenericFamily(FontDescription::StandardFamily);
3356 fontDescription.setRenderingMode(settings->fontRenderingMode());
3357 fontDescription.setUsePrinterFont(m_checker.document()->printing());
3358 const AtomicString& standardFontFamily = m_checker.document()->settings()->standardFontFamily();