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 "ScaleTransformOperation.h"
95 #include "SecurityOrigin.h"
97 #include "ShadowData.h"
98 #include "ShadowRoot.h"
99 #include "ShadowValue.h"
100 #include "SkewTransformOperation.h"
101 #include "StyleCachedImage.h"
102 #include "StylePendingImage.h"
103 #include "StyleRule.h"
104 #include "StyleGeneratedImage.h"
105 #include "StyleSheetList.h"
107 #include "TransformationMatrix.h"
108 #include "TranslateTransformOperation.h"
109 #include "UserAgentStyleSheets.h"
110 #include "WebKitCSSKeyframeRule.h"
111 #include "WebKitCSSKeyframesRule.h"
112 #include "WebKitCSSRegionRule.h"
113 #include "WebKitCSSTransformValue.h"
114 #include "WebKitFontFamilyNames.h"
115 #include "XMLNames.h"
116 #include <wtf/StdLibExtras.h>
117 #include <wtf/Vector.h>
119 #if ENABLE(CSS_FILTERS)
120 #include "FilterOperation.h"
121 #include "WebKitCSSFilterValue.h"
124 #if ENABLE(DASHBOARD_SUPPORT)
125 #include "DashboardRegion.h"
129 #include "SVGElement.h"
130 #include "SVGNames.h"
133 #if ENABLE(CSS_SHADERS)
134 #include "CustomFilterNumberParameter.h"
135 #include "CustomFilterOperation.h"
136 #include "CustomFilterParameter.h"
137 #include "StyleCachedShader.h"
138 #include "StyleCustomFilterProgram.h"
139 #include "StylePendingShader.h"
140 #include "StyleShader.h"
141 #include "WebKitCSSShaderValue.h"
144 #if ENABLE(CSS_IMAGE_SET)
145 #include "CSSImageSetValue.h"
146 #include "StyleCachedImageSet.h"
153 using namespace HTMLNames;
155 #define HANDLE_INHERIT(prop, Prop) \
157 m_style->set##Prop(m_parentStyle->prop()); \
161 #define HANDLE_INHERIT_AND_INITIAL(prop, Prop) \
162 HANDLE_INHERIT(prop, Prop) \
164 m_style->set##Prop(RenderStyle::initial##Prop()); \
168 #define HANDLE_INHERIT_AND_INITIAL_WITH_VALUE(prop, Prop, Value) \
169 HANDLE_INHERIT(prop, Prop) \
171 m_style->set##Prop(RenderStyle::initial##Value());\
175 #define HANDLE_INHERIT_AND_INITIAL_AND_PRIMITIVE(prop, Prop) \
176 HANDLE_INHERIT_AND_INITIAL(prop, Prop) \
177 if (primitiveValue) \
178 m_style->set##Prop(*primitiveValue);
182 RuleData(StyleRule*, CSSSelector*, unsigned position, bool canUseFastCheckSelector, bool inRegionRule);
184 unsigned position() const { return m_position; }
185 StyleRule* rule() const { return m_rule; }
186 CSSSelector* selector() const { return m_selector; }
188 bool hasFastCheckableSelector() const { return m_hasFastCheckableSelector; }
189 bool hasMultipartSelector() const { return m_hasMultipartSelector; }
190 bool hasRightmostSelectorMatchingHTMLBasedOnRuleHash() const { return m_hasRightmostSelectorMatchingHTMLBasedOnRuleHash; }
191 bool containsUncommonAttributeSelector() const { return m_containsUncommonAttributeSelector; }
192 unsigned specificity() const { return m_specificity; }
193 unsigned linkMatchType() const { return m_linkMatchType; }
194 bool isInRegionRule() const { return m_isInRegionRule; }
196 // Try to balance between memory usage (there can be lots of RuleData objects) and good filtering performance.
197 static const unsigned maximumIdentifierCount = 4;
198 const unsigned* descendantSelectorIdentifierHashes() const { return m_descendantSelectorIdentifierHashes; }
202 CSSSelector* m_selector;
203 unsigned m_specificity;
204 // This number was picked fairly arbitrarily. We can probably lower it if we need to.
205 // Some simple testing showed <100,000 RuleData's on large sites.
206 unsigned m_position : 25;
207 unsigned m_hasFastCheckableSelector : 1;
208 unsigned m_hasMultipartSelector : 1;
209 unsigned m_hasRightmostSelectorMatchingHTMLBasedOnRuleHash : 1;
210 unsigned m_containsUncommonAttributeSelector : 1;
211 unsigned m_linkMatchType : 2; // SelectorChecker::LinkMatchMask
212 unsigned m_isInRegionRule : 1;
213 // Use plain array instead of a Vector to minimize memory overhead.
214 unsigned m_descendantSelectorIdentifierHashes[maximumIdentifierCount];
217 struct SameSizeAsRuleData {
225 COMPILE_ASSERT(sizeof(RuleData) == sizeof(SameSizeAsRuleData), RuleData_should_stay_small);
228 WTF_MAKE_NONCOPYABLE(RuleSet);
232 typedef HashMap<AtomicStringImpl*, OwnPtr<Vector<RuleData> > > AtomRuleMap;
234 void addRulesFromSheet(CSSStyleSheet*, const MediaQueryEvaluator&, CSSStyleSelector* = 0, const ContainerNode* = 0);
236 void addStyleRule(StyleRule*, bool canUseFastCheckSelector = true, bool isInRegionRule = false);
237 void addRule(StyleRule*, CSSSelector*, bool canUseFastCheckSelector = true, bool isInRegionRule = false);
238 void addPageRule(CSSPageRule*);
239 void addToRuleSet(AtomicStringImpl* key, AtomRuleMap&, const RuleData&);
240 void addRegionRule(WebKitCSSRegionRule*);
242 void disableAutoShrinkToFit() { m_autoShrinkToFitEnabled = false; }
244 const CSSStyleSelector::Features& features() const { return m_features; }
246 const Vector<RuleData>* idRules(AtomicStringImpl* key) const { return m_idRules.get(key); }
247 const Vector<RuleData>* classRules(AtomicStringImpl* key) const { return m_classRules.get(key); }
248 const Vector<RuleData>* tagRules(AtomicStringImpl* key) const { return m_tagRules.get(key); }
249 const Vector<RuleData>* shadowPseudoElementRules(AtomicStringImpl* key) const { return m_shadowPseudoElementRules.get(key); }
250 const Vector<RuleData>* linkPseudoClassRules() const { return &m_linkPseudoClassRules; }
251 const Vector<RuleData>* focusPseudoClassRules() const { return &m_focusPseudoClassRules; }
252 const Vector<RuleData>* universalRules() const { return &m_universalRules; }
253 const Vector<CSSPageRule*>& pageRules() const { return m_pageRules; }
256 AtomRuleMap m_idRules;
257 AtomRuleMap m_classRules;
258 AtomRuleMap m_tagRules;
259 AtomRuleMap m_shadowPseudoElementRules;
260 Vector<RuleData> m_linkPseudoClassRules;
261 Vector<RuleData> m_focusPseudoClassRules;
262 Vector<RuleData> m_universalRules;
263 Vector<CSSPageRule*> m_pageRules;
264 unsigned m_ruleCount;
265 bool m_autoShrinkToFitEnabled;
266 CSSStyleSelector::Features m_features;
268 struct RuleSetSelectorPair {
269 RuleSetSelectorPair(CSSSelector* selector, RuleSet* ruleSet) : selector(selector), ruleSet(adoptPtr(ruleSet)) { }
270 RuleSetSelectorPair(const RuleSetSelectorPair& rs) : selector(rs.selector), ruleSet(const_cast<RuleSetSelectorPair*>(&rs)->ruleSet.release()) { }
271 CSSSelector* selector;
272 OwnPtr<RuleSet> ruleSet;
275 Vector<RuleSetSelectorPair> m_regionSelectorsAndRuleSets;
278 static RuleSet* defaultStyle;
279 static RuleSet* defaultQuirksStyle;
280 static RuleSet* defaultPrintStyle;
281 static RuleSet* defaultViewSourceStyle;
282 static CSSStyleSheet* simpleDefaultStyleSheet;
284 RenderStyle* CSSStyleSelector::s_styleNotYetAvailable;
286 static void loadFullDefaultStyle();
287 static void loadSimpleDefaultStyle();
288 // FIXME: It would be nice to use some mechanism that guarantees this is in sync with the real UA stylesheet.
289 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}";
291 static inline bool elementCanUseSimpleDefaultStyle(Element* e)
293 return e->hasTagName(htmlTag) || e->hasTagName(headTag) || e->hasTagName(bodyTag) || e->hasTagName(divTag) || e->hasTagName(spanTag) || e->hasTagName(brTag) || e->hasTagName(aTag);
296 static const MediaQueryEvaluator& screenEval()
298 DEFINE_STATIC_LOCAL(const MediaQueryEvaluator, staticScreenEval, ("screen"));
299 return staticScreenEval;
302 static const MediaQueryEvaluator& printEval()
304 DEFINE_STATIC_LOCAL(const MediaQueryEvaluator, staticPrintEval, ("print"));
305 return staticPrintEval;
308 static StylePropertySet* leftToRightDeclaration()
310 DEFINE_STATIC_LOCAL(RefPtr<StylePropertySet>, leftToRightDecl, (StylePropertySet::create()));
311 if (leftToRightDecl->isEmpty())
312 leftToRightDecl->setProperty(CSSPropertyDirection, CSSValueLtr);
313 return leftToRightDecl.get();
316 static StylePropertySet* rightToLeftDeclaration()
318 DEFINE_STATIC_LOCAL(RefPtr<StylePropertySet>, rightToLeftDecl, (StylePropertySet::create()));
319 if (rightToLeftDecl->isEmpty())
320 rightToLeftDecl->setProperty(CSSPropertyDirection, CSSValueRtl);
321 return rightToLeftDecl.get();
324 CSSStyleSelector::CSSStyleSelector(Document* document, StyleSheetList* styleSheets, CSSStyleSheet* mappedElementSheet,
325 CSSStyleSheet* pageUserSheet, const Vector<RefPtr<CSSStyleSheet> >* pageGroupUserSheets, const Vector<RefPtr<CSSStyleSheet> >* documentUserSheets,
326 bool strictParsing, bool matchAuthorAndUserStyles)
327 : m_hasUAAppearance(false)
328 , m_backgroundData(BackgroundFillLayer)
329 , m_matchedPropertiesCacheAdditionsSinceLastSweep(0)
330 , m_checker(document, strictParsing)
332 , m_rootElementStyle(0)
335 , m_regionForStyling(0)
336 , m_elementLinkState(NotInsideLink)
338 , m_lineHeightValue(0)
340 , m_matchAuthorAndUserStyles(matchAuthorAndUserStyles)
341 , m_sameOriginOnly(false)
342 , m_fontSelector(CSSFontSelector::create(document))
343 , m_applyPropertyToRegularStyle(true)
344 , m_applyPropertyToVisitedLinkStyle(false)
345 , m_applyProperty(CSSStyleApplyProperty::sharedCSSStyleApplyProperty())
346 #if ENABLE(CSS_SHADERS)
347 , m_hasPendingShaders(false)
349 #if ENABLE(STYLE_SCOPED)
350 , m_scopeStackParent(0)
353 Element* root = document->documentElement();
356 if (!root || elementCanUseSimpleDefaultStyle(root))
357 loadSimpleDefaultStyle();
359 loadFullDefaultStyle();
363 // construct document root element default style. this is needed
364 // to evaluate media queries that contain relative constraints, like "screen and (max-width: 10em)"
365 // This is here instead of constructor, because when constructor is run,
366 // document doesn't have documentElement
367 // NOTE: this assumes that element that gets passed to styleForElement -call
368 // is always from the document that owns the style selector
369 FrameView* view = document->view();
371 m_medium = adoptPtr(new MediaQueryEvaluator(view->mediaType()));
373 m_medium = adoptPtr(new MediaQueryEvaluator("all"));
376 m_rootDefaultStyle = styleForElement(root, 0, false, true); // don't ref, because the RenderStyle is allocated from global heap
378 if (m_rootDefaultStyle && view)
379 m_medium = adoptPtr(new MediaQueryEvaluator(view->mediaType(), view->frame(), m_rootDefaultStyle.get()));
381 m_authorStyle = adoptPtr(new RuleSet);
382 // Adding rules from multiple sheets, shrink at the end.
383 // Adding global rules from multiple sheets, shrink at the end.
384 // Note that there usually is only 1 sheet for scoped rules, so auto-shrink-to-fit is fine.
385 m_authorStyle->disableAutoShrinkToFit();
387 // FIXME: This sucks! The user sheet is reparsed every time!
388 OwnPtr<RuleSet> tempUserStyle = adoptPtr(new RuleSet);
390 tempUserStyle->addRulesFromSheet(pageUserSheet, *m_medium, this);
391 if (pageGroupUserSheets) {
392 unsigned length = pageGroupUserSheets->size();
393 for (unsigned i = 0; i < length; i++) {
394 if (pageGroupUserSheets->at(i)->isUserStyleSheet())
395 tempUserStyle->addRulesFromSheet(pageGroupUserSheets->at(i).get(), *m_medium, this);
397 m_authorStyle->addRulesFromSheet(pageGroupUserSheets->at(i).get(), *m_medium, this);
400 if (documentUserSheets) {
401 unsigned length = documentUserSheets->size();
402 for (unsigned i = 0; i < length; i++) {
403 if (documentUserSheets->at(i)->isUserStyleSheet())
404 tempUserStyle->addRulesFromSheet(documentUserSheets->at(i).get(), *m_medium, this);
406 m_authorStyle->addRulesFromSheet(documentUserSheets->at(i).get(), *m_medium, this);
410 if (tempUserStyle->m_ruleCount > 0 || tempUserStyle->m_pageRules.size() > 0)
411 m_userStyle = tempUserStyle.release();
413 // Add rules from elements like SVG's <font-face>
414 if (mappedElementSheet) {
415 // FIXME: see if style scopes can/should be added here.
416 m_authorStyle->addRulesFromSheet(mappedElementSheet, *m_medium, this);
419 // add stylesheets from document
420 appendAuthorStylesheets(0, styleSheets->vector());
423 static PassOwnPtr<RuleSet> makeRuleSet(const Vector<CSSStyleSelector::RuleSelectorPair>& rules)
425 size_t size = rules.size();
428 OwnPtr<RuleSet> ruleSet = adoptPtr(new RuleSet);
429 for (size_t i = 0; i < size; ++i)
430 ruleSet->addRule(rules[i].rule, rules[i].selector);
431 return ruleSet.release();
434 void CSSStyleSelector::collectFeatures()
437 // Collect all ids and rules using sibling selectors (:first-child and similar)
438 // in the current set of stylesheets. Style sharing code uses this information to reject
439 // sharing candidates.
440 m_features.add(defaultStyle->features());
441 m_features.add(m_authorStyle->features());
442 #if ENABLE(STYLE_SCOPED)
443 for (ScopedRuleSetMap::iterator it = m_scopedAuthorStyles.begin(); it != m_scopedAuthorStyles.end(); ++it)
444 m_features.add(it->second->features());
447 m_features.add(m_userStyle->features());
449 m_siblingRuleSet = makeRuleSet(m_features.siblingRules);
450 m_uncommonAttributeRuleSet = makeRuleSet(m_features.uncommonAttributeRules);
453 #if ENABLE(STYLE_SCOPED)
454 const ContainerNode* CSSStyleSelector::determineScope(const CSSStyleSheet* sheet)
458 if (!RuntimeEnabledFeatures::styleScopedEnabled())
461 Node* ownerNode = sheet->findStyleSheetOwnerNode();
462 if (!ownerNode || !ownerNode->isHTMLElement() || !ownerNode->hasTagName(HTMLNames::styleTag))
465 HTMLStyleElement* styleElement = static_cast<HTMLStyleElement*>(ownerNode);
466 if (!styleElement->scoped())
469 ContainerNode* parent = styleElement->parentNode();
473 return (parent->isElementNode() || parent->isShadowRoot()) ? parent : 0;
476 inline RuleSet* CSSStyleSelector::ruleSetForScope(const ContainerNode* scope) const
478 if (!scope->hasScopedHTMLStyleChild())
480 ScopedRuleSetMap::const_iterator it = m_scopedAuthorStyles.find(scope);
481 return it != m_scopedAuthorStyles.end() ? it->second.get() : 0;
485 void CSSStyleSelector::appendAuthorStylesheets(unsigned firstNew, const Vector<RefPtr<StyleSheet> >& stylesheets)
487 // This handles sheets added to the end of the stylesheet list only. In other cases the style resolver
488 // needs to be reconstructed. To handle insertions too the rule order numbers would need to be updated.
489 unsigned size = stylesheets.size();
490 for (unsigned i = firstNew; i < size; ++i) {
491 if (!stylesheets[i]->isCSSStyleSheet() || stylesheets[i]->disabled())
493 CSSStyleSheet* cssSheet = static_cast<CSSStyleSheet*>(stylesheets[i].get());
494 #if ENABLE(STYLE_SCOPED)
495 const ContainerNode* scope = determineScope(cssSheet);
497 pair<ScopedRuleSetMap::iterator, bool> addResult = m_scopedAuthorStyles.add(scope, nullptr);
498 if (addResult.second)
499 addResult.first->second = adoptPtr(new RuleSet());
500 addResult.first->second->addRulesFromSheet(cssSheet, *m_medium, this, scope);
504 m_authorStyle->addRulesFromSheet(cssSheet, *m_medium, this);
506 m_authorStyle->shrinkToFit();
509 if (document()->renderer() && document()->renderer()->style())
510 document()->renderer()->style()->font().update(fontSelector());
513 #if ENABLE(STYLE_SCOPED)
514 void CSSStyleSelector::setupScopeStack(const ContainerNode* parent)
516 // The scoping element stack shouldn't be used if <style scoped> isn't used anywhere.
517 ASSERT(!m_scopedAuthorStyles.isEmpty());
519 m_scopeStack.shrink(0);
520 for (; parent; parent = parent->parentOrHostNode()) {
521 RuleSet* ruleSet = ruleSetForScope(parent);
523 m_scopeStack.append(ScopeStackFrame(parent, ruleSet));
525 m_scopeStack.reverse();
526 m_scopeStackParent = parent;
529 void CSSStyleSelector::pushScope(const ContainerNode* scope, const ContainerNode* scopeParent)
531 // Shortcut: Don't bother with the scoping element stack if <style scoped> isn't used anywhere.
532 if (m_scopedAuthorStyles.isEmpty()) {
533 ASSERT(!m_scopeStackParent);
534 ASSERT(m_scopeStack.isEmpty());
537 // In some wacky cases during style resolve we may get invoked for random elements.
538 // Recreate the whole scoping element stack in such cases.
539 if (!scopeStackIsConsistent(scopeParent)) {
540 setupScopeStack(scope);
543 // Otherwise just push the parent onto the stack.
544 RuleSet* ruleSet = ruleSetForScope(scope);
546 m_scopeStack.append(ScopeStackFrame(scope, ruleSet));
547 m_scopeStackParent = scope;
550 void CSSStyleSelector::popScope(const ContainerNode* scope)
552 // Only bother to update the scoping element stack if it is consistent.
553 if (scopeStackIsConsistent(scope)) {
554 m_scopeStack.removeLast();
555 m_scopeStackParent = scope->parentOrHostNode();
560 void CSSStyleSelector::pushParentElement(Element* parent)
562 const ContainerNode* parentsParent = parent->parentOrHostElement();
564 // We are not always invoked consistently. For example, script execution can cause us to enter
565 // style recalc in the middle of tree building. We may also be invoked from somewhere within the tree.
566 // Reset the stack in this case, or if we see a new root element.
567 // Otherwise just push the new parent.
568 if (!parentsParent || m_checker.parentStackIsEmpty())
569 m_checker.setupParentStack(parent);
571 m_checker.pushParent(parent);
573 // Note: We mustn't skip ShadowRoot nodes for the scope stack.
574 pushScope(parent, parent->parentOrHostNode());
577 void CSSStyleSelector::popParentElement(Element* parent)
579 // Note that we may get invoked for some random elements in some wacky cases during style resolve.
580 // Pause maintaining the stack in this case.
581 if (m_checker.parentStackIsConsistent(parent))
582 m_checker.popParent();
586 void CSSStyleSelector::pushParentShadowRoot(const ShadowRoot* shadowRoot)
588 ASSERT(shadowRoot->host());
589 pushScope(shadowRoot, shadowRoot->host());
592 void CSSStyleSelector::popParentShadowRoot(const ShadowRoot* shadowRoot)
594 ASSERT(shadowRoot->host());
595 popScope(shadowRoot);
598 // This is a simplified style setting function for keyframe styles
599 void CSSStyleSelector::addKeyframeStyle(PassRefPtr<WebKitCSSKeyframesRule> rule)
601 AtomicString s(rule->name());
602 m_keyframesRuleMap.set(s.impl(), rule);
605 CSSStyleSelector::~CSSStyleSelector()
607 m_fontSelector->clearDocument();
610 void CSSStyleSelector::sweepMatchedPropertiesCache()
612 // Look for cache entries containing a style declaration with a single ref and remove them.
613 // This may happen when an element attribute mutation causes it to swap out its Attribute::decl()
614 // for another CSSMappedAttributeDeclaration, potentially leaving this cache with the last ref.
615 Vector<unsigned, 16> toRemove;
616 MatchedPropertiesCache::iterator it = m_matchedPropertiesCache.begin();
617 MatchedPropertiesCache::iterator end = m_matchedPropertiesCache.end();
618 for (; it != end; ++it) {
619 Vector<MatchedProperties>& matchedProperties = it->second.matchedProperties;
620 for (size_t i = 0; i < matchedProperties.size(); ++i) {
621 if (matchedProperties[i].properties->hasOneRef()) {
622 toRemove.append(it->first);
627 for (size_t i = 0; i < toRemove.size(); ++i)
628 m_matchedPropertiesCache.remove(toRemove[i]);
631 CSSStyleSelector::Features::Features()
632 : usesFirstLineRules(false)
633 , usesBeforeAfterRules(false)
634 , usesLinkRules(false)
638 CSSStyleSelector::Features::~Features()
642 void CSSStyleSelector::Features::add(const CSSStyleSelector::Features& other)
644 HashSet<AtomicStringImpl*>::iterator end = other.idsInRules.end();
645 for (HashSet<AtomicStringImpl*>::iterator it = other.idsInRules.begin(); it != end; ++it)
647 end = other.attrsInRules.end();
648 for (HashSet<AtomicStringImpl*>::iterator it = other.attrsInRules.begin(); it != end; ++it)
649 attrsInRules.add(*it);
650 siblingRules.append(other.siblingRules);
651 uncommonAttributeRules.append(other.uncommonAttributeRules);
652 usesFirstLineRules = usesFirstLineRules || other.usesFirstLineRules;
653 usesBeforeAfterRules = usesBeforeAfterRules || other.usesBeforeAfterRules;
654 usesLinkRules = usesLinkRules || other.usesLinkRules;
657 void CSSStyleSelector::Features::clear()
660 attrsInRules.clear();
661 siblingRules.clear();
662 uncommonAttributeRules.clear();
663 usesFirstLineRules = false;
664 usesBeforeAfterRules = false;
665 usesLinkRules = false;
668 static CSSStyleSheet* parseUASheet(const String& str)
670 CSSStyleSheet* sheet = CSSStyleSheet::create().leakRef(); // leak the sheet on purpose
671 sheet->parseString(str);
675 static CSSStyleSheet* parseUASheet(const char* characters, unsigned size)
677 return parseUASheet(String(characters, size));
680 static void loadFullDefaultStyle()
682 if (simpleDefaultStyleSheet) {
683 ASSERT(defaultStyle);
684 ASSERT(defaultPrintStyle == defaultStyle);
686 simpleDefaultStyleSheet->deref();
687 defaultStyle = new RuleSet;
688 defaultPrintStyle = new RuleSet;
689 simpleDefaultStyleSheet = 0;
691 ASSERT(!defaultStyle);
692 defaultStyle = new RuleSet;
693 defaultPrintStyle = new RuleSet;
694 defaultQuirksStyle = new RuleSet;
697 // Strict-mode rules.
698 String defaultRules = String(htmlUserAgentStyleSheet, sizeof(htmlUserAgentStyleSheet)) + RenderTheme::defaultTheme()->extraDefaultStyleSheet();
699 CSSStyleSheet* defaultSheet = parseUASheet(defaultRules);
700 defaultStyle->addRulesFromSheet(defaultSheet, screenEval());
701 defaultPrintStyle->addRulesFromSheet(defaultSheet, printEval());
703 // Quirks-mode rules.
704 String quirksRules = String(quirksUserAgentStyleSheet, sizeof(quirksUserAgentStyleSheet)) + RenderTheme::defaultTheme()->extraQuirksStyleSheet();
705 CSSStyleSheet* quirksSheet = parseUASheet(quirksRules);
706 defaultQuirksStyle->addRulesFromSheet(quirksSheet, screenEval());
709 static void loadSimpleDefaultStyle()
711 ASSERT(!defaultStyle);
712 ASSERT(!simpleDefaultStyleSheet);
714 defaultStyle = new RuleSet;
715 // There are no media-specific rules in the simple default style.
716 defaultPrintStyle = defaultStyle;
717 defaultQuirksStyle = new RuleSet;
719 simpleDefaultStyleSheet = parseUASheet(simpleUserAgentStyleSheet, strlen(simpleUserAgentStyleSheet));
720 defaultStyle->addRulesFromSheet(simpleDefaultStyleSheet, screenEval());
722 // No need to initialize quirks sheet yet as there are no quirk rules for elements allowed in simple default style.
725 static void loadViewSourceStyle()
727 ASSERT(!defaultViewSourceStyle);
728 defaultViewSourceStyle = new RuleSet;
729 defaultViewSourceStyle->addRulesFromSheet(parseUASheet(sourceUserAgentStyleSheet, sizeof(sourceUserAgentStyleSheet)), screenEval());
732 static void ensureDefaultStyleSheetsForElement(Element* element)
734 if (simpleDefaultStyleSheet && !elementCanUseSimpleDefaultStyle(element))
735 loadFullDefaultStyle();
738 static bool loadedSVGUserAgentSheet;
739 if (element->isSVGElement() && !loadedSVGUserAgentSheet) {
741 loadedSVGUserAgentSheet = true;
742 CSSStyleSheet* svgSheet = parseUASheet(svgUserAgentStyleSheet, sizeof(svgUserAgentStyleSheet));
743 defaultStyle->addRulesFromSheet(svgSheet, screenEval());
744 defaultPrintStyle->addRulesFromSheet(svgSheet, printEval());
748 static bool loadedMathMLUserAgentSheet;
750 if (element->isMathMLElement() && !loadedMathMLUserAgentSheet) {
752 loadedMathMLUserAgentSheet = true;
753 CSSStyleSheet* mathMLSheet = parseUASheet(mathmlUserAgentStyleSheet, sizeof(mathmlUserAgentStyleSheet));
754 defaultStyle->addRulesFromSheet(mathMLSheet, screenEval());
755 defaultPrintStyle->addRulesFromSheet(mathMLSheet, printEval());
760 static bool loadedMediaStyleSheet;
761 if (!loadedMediaStyleSheet && (element->hasTagName(videoTag) || element->hasTagName(audioTag))) {
762 loadedMediaStyleSheet = true;
763 String mediaRules = String(mediaControlsUserAgentStyleSheet, sizeof(mediaControlsUserAgentStyleSheet)) + RenderTheme::themeForPage(element->document()->page())->extraMediaControlsStyleSheet();
764 CSSStyleSheet* mediaControlsSheet = parseUASheet(mediaRules);
765 defaultStyle->addRulesFromSheet(mediaControlsSheet, screenEval());
766 defaultPrintStyle->addRulesFromSheet(mediaControlsSheet, printEval());
770 #if ENABLE(FULLSCREEN_API)
771 static bool loadedFullScreenStyleSheet;
772 if (!loadedFullScreenStyleSheet && element->document()->webkitIsFullScreen()) {
773 loadedFullScreenStyleSheet = true;
774 String fullscreenRules = String(fullscreenUserAgentStyleSheet, sizeof(fullscreenUserAgentStyleSheet)) + RenderTheme::defaultTheme()->extraFullScreenStyleSheet();
775 CSSStyleSheet* fullscreenSheet = parseUASheet(fullscreenRules);
776 defaultStyle->addRulesFromSheet(fullscreenSheet, screenEval());
777 defaultQuirksStyle->addRulesFromSheet(fullscreenSheet, screenEval());
781 ASSERT(defaultStyle->features().idsInRules.isEmpty());
782 ASSERT_UNUSED(loadedMathMLUserAgentSheet, loadedMathMLUserAgentSheet || defaultStyle->features().siblingRules.isEmpty());
785 void CSSStyleSelector::addMatchedProperties(MatchResult& matchResult, StylePropertySet* properties, StyleRule* rule, unsigned linkMatchType, bool inRegionRule)
787 matchResult.matchedProperties.grow(matchResult.matchedProperties.size() + 1);
788 MatchedProperties& newProperties = matchResult.matchedProperties.last();
789 newProperties.properties = properties;
790 newProperties.linkMatchType = linkMatchType;
791 newProperties.isInRegionRule = inRegionRule;
792 matchResult.matchedRules.append(rule);
795 inline void CSSStyleSelector::addElementStyleProperties(MatchResult& result, StylePropertySet* propertySet, bool isCacheable)
799 result.ranges.lastAuthorRule = result.matchedProperties.size();
800 if (result.ranges.firstAuthorRule == -1)
801 result.ranges.firstAuthorRule = result.ranges.lastAuthorRule;
802 addMatchedProperties(result, propertySet);
804 result.isCacheable = false;
807 void CSSStyleSelector::collectMatchingRules(RuleSet* rules, int& firstRuleIndex, int& lastRuleIndex, const MatchOptions& options)
812 // We need to collect the rules for id, class, tag, and everything else into a buffer and
813 // then sort the buffer.
814 if (m_element->hasID())
815 collectMatchingRulesForList(rules->idRules(m_element->idForStyleResolution().impl()), firstRuleIndex, lastRuleIndex, options);
816 if (m_element->hasClass()) {
817 ASSERT(m_styledElement);
818 const SpaceSplitString& classNames = m_styledElement->classNames();
819 size_t size = classNames.size();
820 for (size_t i = 0; i < size; ++i)
821 collectMatchingRulesForList(rules->classRules(classNames[i].impl()), firstRuleIndex, lastRuleIndex, options);
823 const AtomicString& pseudoId = m_element->shadowPseudoId();
824 if (!pseudoId.isEmpty()) {
825 ASSERT(m_styledElement);
826 collectMatchingRulesForList(rules->shadowPseudoElementRules(pseudoId.impl()), firstRuleIndex, lastRuleIndex, options);
828 if (m_element->isLink())
829 collectMatchingRulesForList(rules->linkPseudoClassRules(), firstRuleIndex, lastRuleIndex, options);
830 if (m_checker.matchesFocusPseudoClass(m_element))
831 collectMatchingRulesForList(rules->focusPseudoClassRules(), firstRuleIndex, lastRuleIndex, options);
832 collectMatchingRulesForList(rules->tagRules(m_element->localName().impl()), firstRuleIndex, lastRuleIndex, options);
833 collectMatchingRulesForList(rules->universalRules(), firstRuleIndex, lastRuleIndex, options);
836 void CSSStyleSelector::collectMatchingRulesForRegion(RuleSet* rules, int& firstRuleIndex, int& lastRuleIndex, const MatchOptions& options)
838 if (!m_regionForStyling)
841 unsigned size = rules->m_regionSelectorsAndRuleSets.size();
842 for (unsigned i = 0; i < size; ++i) {
843 CSSSelector* regionSelector = rules->m_regionSelectorsAndRuleSets.at(i).selector;
844 if (checkRegionSelector(regionSelector, static_cast<Element*>(m_regionForStyling->node()))) {
845 RuleSet* regionRules = rules->m_regionSelectorsAndRuleSets.at(i).ruleSet.get();
847 collectMatchingRules(regionRules, firstRuleIndex, lastRuleIndex, options);
852 void CSSStyleSelector::sortAndTransferMatchedRules(MatchResult& result)
854 if (m_matchedRules.isEmpty())
859 if (m_checker.isCollectingRulesOnly()) {
861 m_ruleList = CSSRuleList::create();
862 for (unsigned i = 0; i < m_matchedRules.size(); ++i)
863 m_ruleList->append(m_matchedRules[i]->rule()->ensureCSSStyleRule());
867 // Now transfer the set of matched rules over to our list of declarations.
868 // FIXME: This sucks, the inspector should get the style from the visited style itself.
869 bool swapVisitedUnvisited = InspectorInstrumentation::forcePseudoState(m_element, CSSSelector::PseudoVisited);
870 for (unsigned i = 0; i < m_matchedRules.size(); i++) {
871 if (m_style && m_matchedRules[i]->containsUncommonAttributeSelector())
872 m_style->setAffectedByUncommonAttributeSelectors();
873 unsigned linkMatchType = m_matchedRules[i]->linkMatchType();
874 if (swapVisitedUnvisited && linkMatchType && linkMatchType != SelectorChecker::MatchAll)
875 linkMatchType = (linkMatchType == SelectorChecker::MatchVisited) ? SelectorChecker::MatchLink : SelectorChecker::MatchVisited;
876 addMatchedProperties(result, m_matchedRules[i]->rule()->properties(), m_matchedRules[i]->rule(), linkMatchType, m_matchedRules[i]->isInRegionRule());
880 void CSSStyleSelector::matchScopedAuthorRules(MatchResult& result, bool includeEmptyRules)
882 #if ENABLE(STYLE_SCOPED)
883 if (m_scopedAuthorStyles.isEmpty())
886 MatchOptions options(includeEmptyRules);
888 // Match scoped author rules by traversing the scoped element stack (rebuild it if it got inconsistent).
889 const ContainerNode* parent = m_element->parentOrHostNode();
890 if (!scopeStackIsConsistent(parent))
891 setupScopeStack(parent);
892 for (size_t i = m_scopeStack.size(); i; --i) {
893 const ScopeStackFrame& frame = m_scopeStack[i - 1];
894 options.scope = frame.m_scope;
895 collectMatchingRules(frame.m_ruleSet, result.ranges.firstAuthorRule, result.ranges.lastAuthorRule, options);
896 collectMatchingRulesForRegion(frame.m_ruleSet, result.ranges.firstAuthorRule, result.ranges.lastAuthorRule, options);
898 // Also include the current element.
899 RuleSet* ruleSet = ruleSetForScope(m_element);
901 options.scope = m_element;
902 collectMatchingRules(ruleSet, result.ranges.firstAuthorRule, result.ranges.lastAuthorRule, options);
903 collectMatchingRulesForRegion(ruleSet, result.ranges.firstAuthorRule, result.ranges.lastAuthorRule, options);
906 UNUSED_PARAM(result);
907 UNUSED_PARAM(includeEmptyRules);
911 void CSSStyleSelector::matchAuthorRules(MatchResult& result, bool includeEmptyRules)
913 m_matchedRules.clear();
914 result.ranges.lastAuthorRule = result.matchedProperties.size() - 1;
919 // Match global author rules.
920 MatchOptions options(includeEmptyRules);
921 collectMatchingRules(m_authorStyle.get(), result.ranges.firstAuthorRule, result.ranges.lastAuthorRule, options);
922 collectMatchingRulesForRegion(m_authorStyle.get(), result.ranges.firstAuthorRule, result.ranges.lastAuthorRule, options);
924 matchScopedAuthorRules(result, includeEmptyRules);
926 sortAndTransferMatchedRules(result);
929 void CSSStyleSelector::matchUserRules(MatchResult& result, bool includeEmptyRules)
934 m_matchedRules.clear();
936 result.ranges.lastUserRule = result.matchedProperties.size() - 1;
937 collectMatchingRules(m_userStyle.get(), result.ranges.firstUserRule, result.ranges.lastUserRule, includeEmptyRules);
938 collectMatchingRulesForRegion(m_userStyle.get(), result.ranges.firstUserRule, result.ranges.lastUserRule, includeEmptyRules);
940 sortAndTransferMatchedRules(result);
943 void CSSStyleSelector::matchUARules(MatchResult& result, RuleSet* rules)
945 m_matchedRules.clear();
947 result.ranges.lastUARule = result.matchedProperties.size() - 1;
948 collectMatchingRules(rules, result.ranges.firstUARule, result.ranges.lastUARule, false);
950 sortAndTransferMatchedRules(result);
953 class MatchingUARulesScope {
955 MatchingUARulesScope();
956 ~MatchingUARulesScope();
958 static bool isMatchingUARules();
961 static bool m_matchingUARules;
964 MatchingUARulesScope::MatchingUARulesScope()
966 ASSERT(!m_matchingUARules);
967 m_matchingUARules = true;
970 MatchingUARulesScope::~MatchingUARulesScope()
972 m_matchingUARules = false;
975 inline bool MatchingUARulesScope::isMatchingUARules()
977 return m_matchingUARules;
980 bool MatchingUARulesScope::m_matchingUARules = false;
982 void CSSStyleSelector::collectMatchingRulesForList(const Vector<RuleData>* rules, int& firstRuleIndex, int& lastRuleIndex, const MatchOptions& options)
986 // In some cases we may end up looking up style for random elements in the middle of a recursive tree resolve.
987 // Ancestor identifier filter won't be up-to-date in that case and we can't use the fast path.
988 bool canUseFastReject = m_checker.parentStackIsConsistent(m_parentNode);
990 unsigned size = rules->size();
991 for (unsigned i = 0; i < size; ++i) {
992 const RuleData& ruleData = rules->at(i);
993 if (canUseFastReject && m_checker.fastRejectSelector<RuleData::maximumIdentifierCount>(ruleData.descendantSelectorIdentifierHashes()))
996 StyleRule* rule = ruleData.rule();
997 InspectorInstrumentationCookie cookie = InspectorInstrumentation::willMatchRule(document(), rule);
998 #if ENABLE(STYLE_SCOPED)
999 if (checkSelector(ruleData, options.scope)) {
1001 if (checkSelector(ruleData)) {
1003 // Check whether the rule is applicable in the current tree scope. Criteria for this:
1004 // a) it's a UA rule
1005 // b) the tree scope allows author rules
1006 // c) the rules comes from a scoped style sheet within the same tree scope
1007 // d) the rule contains shadow-ID pseudo elements
1008 TreeScope* treeScope = m_element->treeScope();
1009 if (!MatchingUARulesScope::isMatchingUARules()
1010 && !treeScope->applyAuthorSheets()
1011 #if ENABLE(STYLE_SCOPED)
1012 && (!options.scope || options.scope->treeScope() != treeScope)
1014 && !m_checker.hasUnknownPseudoElements()) {
1016 InspectorInstrumentation::didMatchRule(cookie, false);
1019 // If the rule has no properties to apply, then ignore it in the non-debug mode.
1020 StylePropertySet* properties = rule->properties();
1021 if (!properties || (properties->isEmpty() && !options.includeEmptyRules)) {
1022 InspectorInstrumentation::didMatchRule(cookie, false);
1025 // FIXME: Exposing getMatchedCSSRules as a web facing API is forcing us to have a way to get the base URL per-rule.
1026 if (m_sameOriginOnly && !m_checker.document()->securityOrigin()->canRequest(rule->ensureCSSStyleRule()->baseURL())) {
1027 InspectorInstrumentation::didMatchRule(cookie, false);
1030 // If we're matching normal rules, set a pseudo bit if
1031 // we really just matched a pseudo-element.
1032 if (m_dynamicPseudo != NOPSEUDO && m_checker.pseudoStyle() == NOPSEUDO) {
1033 if (m_checker.isCollectingRulesOnly()) {
1034 InspectorInstrumentation::didMatchRule(cookie, false);
1037 if (m_dynamicPseudo < FIRST_INTERNAL_PSEUDOID)
1038 m_style->setHasPseudoStyle(m_dynamicPseudo);
1040 // Update our first/last rule indices in the matched rules array.
1042 if (firstRuleIndex == -1)
1043 firstRuleIndex = lastRuleIndex;
1045 // Add this rule to our list of matched rules.
1046 addMatchedRule(&ruleData);
1047 InspectorInstrumentation::didMatchRule(cookie, true);
1051 InspectorInstrumentation::didMatchRule(cookie, false);
1055 static inline bool compareRules(const RuleData* r1, const RuleData* r2)
1057 unsigned specificity1 = r1->specificity();
1058 unsigned specificity2 = r2->specificity();
1059 return (specificity1 == specificity2) ? r1->position() < r2->position() : specificity1 < specificity2;
1062 void CSSStyleSelector::sortMatchedRules()
1064 std::sort(m_matchedRules.begin(), m_matchedRules.end(), compareRules);
1067 void CSSStyleSelector::matchAllRules(MatchResult& result)
1069 matchUARules(result);
1071 // Now we check user sheet rules.
1072 if (m_matchAuthorAndUserStyles)
1073 matchUserRules(result, false);
1075 // Now check author rules, beginning first with presentational attributes mapped from HTML.
1076 if (m_styledElement) {
1077 addElementStyleProperties(result, m_styledElement->attributeStyle());
1079 // Now we check additional mapped declarations.
1080 // Tables and table cells share an additional mapped rule that must be applied
1081 // after all attributes, since their mapped style depends on the values of multiple attributes.
1082 addElementStyleProperties(result, m_styledElement->additionalAttributeStyle());
1084 if (m_styledElement->isHTMLElement()) {
1086 TextDirection textDirection = toHTMLElement(m_styledElement)->directionalityIfhasDirAutoAttribute(isAuto);
1088 addMatchedProperties(result, textDirection == LTR ? leftToRightDeclaration() : rightToLeftDeclaration());
1092 // Check the rules in author sheets next.
1093 if (m_matchAuthorAndUserStyles)
1094 matchAuthorRules(result, false);
1096 // Now check our inline style attribute.
1097 if (m_matchAuthorAndUserStyles && m_styledElement && m_styledElement->inlineStyle()) {
1098 // Inline style is immutable as long as there is no CSSOM wrapper.
1099 // FIXME: Media control shadow trees seem to have problems with caching.
1100 bool isInlineStyleCacheable = !m_styledElement->inlineStyle()->hasCSSOMWrapper() && !m_styledElement->isInShadowTree();
1102 addElementStyleProperties(result, const_cast<StylePropertySet*>(m_styledElement->inlineStyle()), isInlineStyleCacheable);
1106 // Now check SMIL animation override style.
1107 if (m_matchAuthorAndUserStyles && m_styledElement && m_styledElement->isSVGElement())
1108 addElementStyleProperties(result, static_cast<SVGElement*>(m_styledElement)->animatedSMILStyleProperties(), false /* isCacheable */);
1112 inline void CSSStyleSelector::initElement(Element* e)
1114 if (m_element != e) {
1116 m_styledElement = m_element && m_element->isStyledElement() ? static_cast<StyledElement*>(m_element) : 0;
1117 m_elementLinkState = m_checker.determineLinkState(m_element);
1118 if (e && e == e->document()->documentElement()) {
1119 e->document()->setDirectionSetOnDocumentElement(false);
1120 e->document()->setWritingModeSetOnDocumentElement(false);
1125 inline void CSSStyleSelector::initForStyleResolve(Element* e, RenderStyle* parentStyle, PseudoId pseudoID)
1127 m_checker.setPseudoStyle(pseudoID);
1129 m_parentNode = e ? e->parentNodeForRenderingAndStyle() : 0;
1132 m_parentStyle = parentStyle;
1134 m_parentStyle = m_parentNode ? m_parentNode->renderStyle() : 0;
1136 Node* docElement = e ? e->document()->documentElement() : 0;
1137 RenderStyle* docStyle = m_checker.document()->renderStyle();
1138 m_rootElementStyle = docElement && e != docElement ? docElement->renderStyle() : docStyle;
1142 m_pendingImageProperties.clear();
1146 m_fontDirty = false;
1149 static const unsigned cStyleSearchThreshold = 10;
1150 static const unsigned cStyleSearchLevelThreshold = 10;
1152 Node* CSSStyleSelector::locateCousinList(Element* parent, unsigned& visitedNodeCount) const
1154 if (visitedNodeCount >= cStyleSearchThreshold * cStyleSearchLevelThreshold)
1156 if (!parent || !parent->isStyledElement())
1158 #if ENABLE(STYLE_SCOPED)
1159 if (parent->hasScopedHTMLStyleChild())
1162 StyledElement* p = static_cast<StyledElement*>(parent);
1163 if (p->inlineStyle())
1166 if (p->isSVGElement() && static_cast<SVGElement*>(p)->animatedSMILStyleProperties())
1169 if (p->hasID() && m_features.idsInRules.contains(p->idForStyleResolution().impl()))
1172 RenderStyle* parentStyle = p->renderStyle();
1173 unsigned subcount = 0;
1174 Node* thisCousin = p;
1175 Node* currentNode = p->previousSibling();
1177 // Reserve the tries for this level. This effectively makes sure that the algorithm
1178 // will never go deeper than cStyleSearchLevelThreshold levels into recursion.
1179 visitedNodeCount += cStyleSearchThreshold;
1180 while (thisCousin) {
1181 while (currentNode) {
1183 if (currentNode->renderStyle() == parentStyle && currentNode->lastChild()) {
1184 // Adjust for unused reserved tries.
1185 visitedNodeCount -= cStyleSearchThreshold - subcount;
1186 return currentNode->lastChild();
1188 if (subcount >= cStyleSearchThreshold)
1190 currentNode = currentNode->previousSibling();
1192 currentNode = locateCousinList(thisCousin->parentElement(), visitedNodeCount);
1193 thisCousin = currentNode;
1199 bool CSSStyleSelector::matchesRuleSet(RuleSet* ruleSet)
1203 m_matchedRules.clear();
1205 int firstRuleIndex = -1, lastRuleIndex = -1;
1206 collectMatchingRules(ruleSet, firstRuleIndex, lastRuleIndex, false);
1208 if (m_matchedRules.isEmpty())
1210 m_matchedRules.clear();
1214 bool CSSStyleSelector::canShareStyleWithControl(StyledElement* element) const
1216 HTMLInputElement* thisInputElement = element->toInputElement();
1217 HTMLInputElement* otherInputElement = m_element->toInputElement();
1219 if (!thisInputElement || !otherInputElement)
1222 if (thisInputElement->isAutofilled() != otherInputElement->isAutofilled())
1224 if (thisInputElement->shouldAppearChecked() != otherInputElement->shouldAppearChecked())
1226 if (thisInputElement->isIndeterminate() != otherInputElement->isIndeterminate())
1228 if (thisInputElement->required() != otherInputElement->required())
1231 if (element->isEnabledFormControl() != m_element->isEnabledFormControl())
1234 if (element->isDefaultButtonForForm() != m_element->isDefaultButtonForForm())
1237 if (m_element->document()->containsValidityStyleRules()) {
1238 bool willValidate = element->willValidate();
1240 if (willValidate != m_element->willValidate())
1243 if (willValidate && (element->isValidFormControlElement() != m_element->isValidFormControlElement()))
1246 if (element->isInRange() != m_element->isInRange())
1249 if (element->isOutOfRange() != m_element->isOutOfRange())
1256 // This function makes some assumptions that only make sense for attribute styles (we only compare CSSProperty::id() and CSSProperty::value().)
1257 static inline bool attributeStylesEqual(StylePropertySet* a, StylePropertySet* b)
1261 if (a->propertyCount() != b->propertyCount())
1263 unsigned propertyCount = a->propertyCount();
1264 for (unsigned i = 0; i < propertyCount; ++i) {
1265 const CSSProperty& aProperty = a->propertyAt(i);
1267 for (j = 0; j < propertyCount; ++j) {
1268 const CSSProperty& bProperty = b->propertyAt(j);
1269 if (aProperty.id() != bProperty.id())
1271 // We could get a few more hits by comparing cssText() here, but that gets expensive quickly.
1272 if (aProperty.value() != bProperty.value())
1276 if (j == propertyCount)
1282 inline bool elementHasDirectionAuto(Element* element)
1284 return element->isHTMLElement() && toHTMLElement(element)->hasDirectionAuto();
1287 bool CSSStyleSelector::canShareStyleWithElement(StyledElement* element) const
1289 RenderStyle* style = element->renderStyle();
1293 if (style->unique())
1295 if (element->tagQName() != m_element->tagQName())
1297 if (element->hasClass() != m_element->hasClass())
1299 if (element->inlineStyle())
1302 if (element->isSVGElement() && static_cast<SVGElement*>(element)->animatedSMILStyleProperties())
1305 if (!!element->attributeStyle() != !!m_styledElement->attributeStyle())
1307 StylePropertySet* additionalAttributeStyleA = element->additionalAttributeStyle();
1308 StylePropertySet* additionalAttributeStyleB = m_styledElement->additionalAttributeStyle();
1309 if (!additionalAttributeStyleA != !additionalAttributeStyleB)
1311 if (element->isLink() != m_element->isLink())
1313 if (style->affectedByUncommonAttributeSelectors())
1315 if (element->hovered() != m_element->hovered())
1317 if (element->active() != m_element->active())
1319 if (element->focused() != m_element->focused())
1321 if (element->shadowPseudoId() != m_element->shadowPseudoId())
1323 if (element == element->document()->cssTarget())
1325 if (m_element == m_element->document()->cssTarget())
1327 if (element->getAttribute(typeAttr) != m_element->getAttribute(typeAttr))
1329 if (element->fastGetAttribute(XMLNames::langAttr) != m_element->fastGetAttribute(XMLNames::langAttr))
1331 if (element->fastGetAttribute(langAttr) != m_element->fastGetAttribute(langAttr))
1333 if (element->fastGetAttribute(readonlyAttr) != m_element->fastGetAttribute(readonlyAttr))
1335 if (element->fastGetAttribute(cellpaddingAttr) != m_element->fastGetAttribute(cellpaddingAttr))
1338 if (element->hasID() && m_features.idsInRules.contains(element->idForStyleResolution().impl()))
1341 #if ENABLE(STYLE_SCOPED)
1342 if (element->hasScopedHTMLStyleChild())
1346 #if ENABLE(PROGRESS_TAG)
1347 if (element->hasTagName(progressTag)) {
1348 if (!m_element->hasTagName(progressTag))
1351 HTMLProgressElement* thisProgressElement = static_cast<HTMLProgressElement*>(element);
1352 HTMLProgressElement* otherProgressElement = static_cast<HTMLProgressElement*>(m_element);
1353 if (thisProgressElement->isDeterminate() != otherProgressElement->isDeterminate())
1358 if (element->hasTagName(optionTag))
1361 bool isControl = element->isFormControlElement();
1363 if (isControl != m_element->isFormControlElement())
1366 if (isControl && !canShareStyleWithControl(element))
1369 if (style->transitions() || style->animations())
1372 #if USE(ACCELERATED_COMPOSITING)
1373 // Turn off style sharing for elements that can gain layers for reasons outside of the style system.
1374 // See comments in RenderObject::setStyle().
1375 if (element->hasTagName(iframeTag) || element->hasTagName(frameTag) || element->hasTagName(embedTag) || element->hasTagName(objectTag) || element->hasTagName(appletTag)
1376 #if ENABLE(PLUGIN_PROXY_FOR_VIDEO)
1377 // With proxying, the media elements are backed by a RenderEmbeddedObject.
1378 || element->hasTagName(videoTag) || element->hasTagName(audioTag)
1384 if (elementHasDirectionAuto(element) || elementHasDirectionAuto(m_element))
1387 if (element->hasClass() && m_element->getAttribute(classAttr) != element->getAttribute(classAttr))
1390 if (element->attributeStyle() && !attributeStylesEqual(element->attributeStyle(), m_styledElement->attributeStyle()))
1393 if (additionalAttributeStyleA && !attributeStylesEqual(additionalAttributeStyleA, additionalAttributeStyleB))
1396 if (element->isLink() && m_elementLinkState != style->insideLink())
1402 inline StyledElement* CSSStyleSelector::findSiblingForStyleSharing(Node* node, unsigned& count) const
1404 for (; node; node = node->previousSibling()) {
1405 if (!node->isStyledElement())
1407 if (canShareStyleWithElement(static_cast<StyledElement*>(node)))
1409 if (count++ == cStyleSearchThreshold)
1412 return static_cast<StyledElement*>(node);
1415 static inline bool parentStylePreventsSharing(const RenderStyle* parentStyle)
1417 return parentStyle->childrenAffectedByPositionalRules()
1418 || parentStyle->childrenAffectedByFirstChildRules()
1419 || parentStyle->childrenAffectedByLastChildRules()
1420 || parentStyle->childrenAffectedByDirectAdjacentRules();
1423 RenderStyle* CSSStyleSelector::locateSharedStyle()
1425 if (!m_styledElement || !m_parentStyle)
1427 // If the element has inline style it is probably unique.
1428 if (m_styledElement->inlineStyle())
1431 if (m_styledElement->isSVGElement() && static_cast<SVGElement*>(m_styledElement)->animatedSMILStyleProperties())
1434 // Ids stop style sharing if they show up in the stylesheets.
1435 if (m_styledElement->hasID() && m_features.idsInRules.contains(m_styledElement->idForStyleResolution().impl()))
1437 if (parentStylePreventsSharing(m_parentStyle))
1439 #if ENABLE(STYLE_SCOPED)
1440 if (m_styledElement->hasScopedHTMLStyleChild())
1444 // Check previous siblings and their cousins.
1446 unsigned visitedNodeCount = 0;
1447 StyledElement* shareElement = 0;
1448 Node* cousinList = m_styledElement->previousSibling();
1449 while (cousinList) {
1450 shareElement = findSiblingForStyleSharing(cousinList, count);
1453 cousinList = locateCousinList(cousinList->parentElement(), visitedNodeCount);
1456 // If we have exhausted all our budget or our cousins.
1460 // Can't share if sibling rules apply. This is checked at the end as it should rarely fail.
1461 if (matchesRuleSet(m_siblingRuleSet.get()))
1463 // Can't share if attribute rules apply.
1464 if (matchesRuleSet(m_uncommonAttributeRuleSet.get()))
1466 // Tracking child index requires unique style for each node. This may get set by the sibling rule match above.
1467 if (parentStylePreventsSharing(m_parentStyle))
1469 return shareElement->renderStyle();
1472 void CSSStyleSelector::matchUARules(MatchResult& result)
1474 MatchingUARulesScope scope;
1476 // First we match rules from the user agent sheet.
1477 if (simpleDefaultStyleSheet)
1478 result.isCacheable = false;
1479 RuleSet* userAgentStyleSheet = m_medium->mediaTypeMatchSpecific("print")
1480 ? defaultPrintStyle : defaultStyle;
1481 matchUARules(result, userAgentStyleSheet);
1483 // In quirks mode, we match rules from the quirks user agent sheet.
1484 if (!m_checker.strictParsing())
1485 matchUARules(result, defaultQuirksStyle);
1487 // 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.
1488 if (m_checker.document()->isViewSource()) {
1489 if (!defaultViewSourceStyle)
1490 loadViewSourceStyle();
1491 matchUARules(result, defaultViewSourceStyle);
1495 PassRefPtr<RenderStyle> CSSStyleSelector::styleForDocument(Document* document, CSSFontSelector* fontSelector)
1497 Frame* frame = document->frame();
1499 RefPtr<RenderStyle> documentStyle = RenderStyle::create();
1500 documentStyle->setDisplay(BLOCK);
1501 documentStyle->setRTLOrdering(document->visuallyOrdered() ? VisualOrder : LogicalOrder);
1502 documentStyle->setZoom(frame && !document->printing() ? frame->pageZoomFactor() : 1);
1503 documentStyle->setPageScaleTransform(frame ? frame->frameScaleFactor() : 1);
1504 documentStyle->setUserModify(document->inDesignMode() ? READ_WRITE : READ_ONLY);
1505 documentStyle->setLocale(document->contentLanguage());
1507 Element* docElement = document->documentElement();
1508 RenderObject* docElementRenderer = docElement ? docElement->renderer() : 0;
1509 if (docElementRenderer) {
1510 // Use the direction and writing-mode of the body to set the
1511 // viewport's direction and writing-mode unless the property is set on the document element.
1512 // If there is no body, then use the document element.
1513 RenderObject* bodyRenderer = document->body() ? document->body()->renderer() : 0;
1514 if (bodyRenderer && !document->writingModeSetOnDocumentElement())
1515 documentStyle->setWritingMode(bodyRenderer->style()->writingMode());
1517 documentStyle->setWritingMode(docElementRenderer->style()->writingMode());
1518 if (bodyRenderer && !document->directionSetOnDocumentElement())
1519 documentStyle->setDirection(bodyRenderer->style()->direction());
1521 documentStyle->setDirection(docElementRenderer->style()->direction());
1525 if (Page* page = frame->page()) {
1526 const Page::Pagination& pagination = page->pagination();
1527 if (pagination.mode != Page::Pagination::Unpaginated) {
1528 documentStyle->setColumnAxis(pagination.mode == Page::Pagination::HorizontallyPaginated ? HorizontalColumnAxis : VerticalColumnAxis);
1529 documentStyle->setColumnGap(pagination.gap);
1534 FontDescription fontDescription;
1535 fontDescription.setUsePrinterFont(document->printing());
1536 fontDescription.setScript(localeToScriptCodeForFontSelection(documentStyle->locale()));
1537 if (Settings* settings = document->settings()) {
1538 fontDescription.setRenderingMode(settings->fontRenderingMode());
1539 const AtomicString& standardFont = settings->standardFontFamily(fontDescription.script());
1540 if (!standardFont.isEmpty()) {
1541 fontDescription.setGenericFamily(FontDescription::StandardFamily);
1542 fontDescription.firstFamily().setFamily(standardFont);
1543 fontDescription.firstFamily().appendFamily(0);
1545 fontDescription.setKeywordSize(CSSValueMedium - CSSValueXxSmall + 1);
1546 int size = CSSStyleSelector::fontSizeForKeyword(document, CSSValueMedium, false);
1547 fontDescription.setSpecifiedSize(size);
1548 bool useSVGZoomRules = document->isSVGDocument();
1549 fontDescription.setComputedSize(CSSStyleSelector::getComputedSizeFromSpecifiedSize(document, documentStyle.get(), fontDescription.isAbsoluteSize(), size, useSVGZoomRules));
1552 documentStyle->setFontDescription(fontDescription);
1553 documentStyle->font().update(fontSelector);
1555 return documentStyle.release();
1558 static inline bool isAtShadowBoundary(Element* element)
1562 ContainerNode* parentNode = element->parentNode();
1563 return parentNode && parentNode->isShadowRoot();
1566 // If resolveForRootDefault is true, style based on user agent style sheet only. This is used in media queries, where
1567 // relative units are interpreted according to document root element style, styled only with UA stylesheet
1569 PassRefPtr<RenderStyle> CSSStyleSelector::styleForElement(Element* element, RenderStyle* defaultParent, bool allowSharing, bool resolveForRootDefault, RenderRegion* regionForStyling)
1571 // Once an element has a renderer, we don't try to destroy it, since otherwise the renderer
1572 // will vanish if a style recalc happens during loading.
1573 if (allowSharing && !element->document()->haveStylesheetsLoaded() && !element->renderer()) {
1574 if (!s_styleNotYetAvailable) {
1575 s_styleNotYetAvailable = RenderStyle::create().leakRef();
1576 s_styleNotYetAvailable->setDisplay(NONE);
1577 s_styleNotYetAvailable->font().update(m_fontSelector);
1579 element->document()->setHasNodesWithPlaceholderStyle();
1580 return s_styleNotYetAvailable;
1583 initElement(element);
1584 initForStyleResolve(element, defaultParent);
1585 m_regionForStyling = regionForStyling;
1587 RenderStyle* sharedStyle = locateSharedStyle();
1592 m_style = RenderStyle::create();
1595 m_style->inheritFrom(m_parentStyle);
1597 m_parentStyle = style();
1598 // Make sure our fonts are initialized if we don't inherit them from our parent style.
1599 m_style->font().update(0);
1602 // Even if surrounding content is user-editable, shadow DOM should act as a single unit, and not necessarily be editable
1603 if (isAtShadowBoundary(element))
1604 m_style->setUserModify(RenderStyle::initialUserModify());
1606 if (element->isLink()) {
1607 m_style->setIsLink(true);
1608 m_style->setInsideLink(m_elementLinkState);
1611 ensureDefaultStyleSheetsForElement(element);
1613 MatchResult matchResult;
1614 if (resolveForRootDefault)
1615 matchUARules(matchResult);
1617 matchAllRules(matchResult);
1619 applyMatchedProperties(matchResult);
1621 // Clean up our style object's display and text decorations (among other fixups).
1622 adjustRenderStyle(style(), m_parentStyle, element);
1624 initElement(0); // Clear out for the next resolve.
1626 // Now return the style.
1627 return m_style.release();
1630 PassRefPtr<RenderStyle> CSSStyleSelector::styleForKeyframe(const RenderStyle* elementStyle, const WebKitCSSKeyframeRule* keyframeRule, KeyframeValue& keyframe)
1633 if (keyframeRule->declaration())
1634 addMatchedProperties(result, keyframeRule->declaration());
1639 m_style = RenderStyle::clone(elementStyle);
1641 m_lineHeightValue = 0;
1643 // We don't need to bother with !important. Since there is only ever one
1644 // decl, there's nothing to override. So just add the first properties.
1645 bool inheritedOnly = false;
1646 if (keyframeRule->style())
1647 applyMatchedProperties<true>(result, false, 0, result.matchedProperties.size() - 1, inheritedOnly);
1649 // If our font got dirtied, go ahead and update it now.
1652 // Line-height is set when we are sure we decided on the font-size
1653 if (m_lineHeightValue)
1654 applyProperty(CSSPropertyLineHeight, m_lineHeightValue);
1656 // Now do rest of the properties.
1657 if (keyframeRule->style())
1658 applyMatchedProperties<false>(result, false, 0, result.matchedProperties.size() - 1, inheritedOnly);
1660 // If our font got dirtied by one of the non-essential font props,
1661 // go ahead and update it a second time.
1664 // Start loading images referenced by this style.
1665 loadPendingImages();
1667 #if ENABLE(CSS_SHADERS)
1668 // Start loading the shaders referenced by this style.
1669 loadPendingShaders();
1672 // Add all the animating properties to the keyframe.
1673 if (StylePropertySet* styleDeclaration = keyframeRule->declaration()) {
1674 unsigned propertyCount = styleDeclaration->propertyCount();
1675 for (unsigned i = 0; i < propertyCount; ++i) {
1676 int property = styleDeclaration->propertyAt(i).id();
1677 // Timing-function within keyframes is special, because it is not animated; it just
1678 // describes the timing function between this keyframe and the next.
1679 if (property != CSSPropertyWebkitAnimationTimingFunction)
1680 keyframe.addProperty(property);
1684 return m_style.release();
1687 void CSSStyleSelector::keyframeStylesForAnimation(Element* e, const RenderStyle* elementStyle, KeyframeList& list)
1691 // Get the keyframesRule for this name
1692 if (!e || list.animationName().isEmpty())
1695 m_keyframesRuleMap.checkConsistency();
1697 KeyframesRuleMap::iterator it = m_keyframesRuleMap.find(list.animationName().impl());
1698 if (it == m_keyframesRuleMap.end())
1701 const WebKitCSSKeyframesRule* rule = it->second.get();
1703 // Construct and populate the style for each keyframe
1704 for (unsigned i = 0; i < rule->length(); ++i) {
1705 // Apply the declaration to the style. This is a simplified version of the logic in styleForElement
1707 initForStyleResolve(e);
1709 const WebKitCSSKeyframeRule* keyframeRule = rule->item(i);
1711 KeyframeValue keyframe(0, 0);
1712 keyframe.setStyle(styleForKeyframe(elementStyle, keyframeRule, keyframe));
1714 // Add this keyframe style to all the indicated key times
1716 keyframeRule->getKeys(keys);
1717 for (size_t keyIndex = 0; keyIndex < keys.size(); ++keyIndex) {
1718 keyframe.setKey(keys[keyIndex]);
1719 list.insert(keyframe);
1723 // If the 0% keyframe is missing, create it (but only if there is at least one other keyframe)
1724 int initialListSize = list.size();
1725 if (initialListSize > 0 && list[0].key() != 0) {
1726 RefPtr<WebKitCSSKeyframeRule> keyframeRule = WebKitCSSKeyframeRule::create();
1727 keyframeRule->setKeyText("0%");
1728 KeyframeValue keyframe(0, 0);
1729 keyframe.setStyle(styleForKeyframe(elementStyle, keyframeRule.get(), keyframe));
1730 list.insert(keyframe);
1733 // If the 100% keyframe is missing, create it (but only if there is at least one other keyframe)
1734 if (initialListSize > 0 && (list[list.size() - 1].key() != 1)) {
1735 RefPtr<WebKitCSSKeyframeRule> keyframeRule = WebKitCSSKeyframeRule::create();
1736 keyframeRule->setKeyText("100%");
1737 KeyframeValue keyframe(1, 0);
1738 keyframe.setStyle(styleForKeyframe(elementStyle, keyframeRule.get(), keyframe));
1739 list.insert(keyframe);
1743 PassRefPtr<RenderStyle> CSSStyleSelector::pseudoStyleForElement(PseudoId pseudo, Element* e, RenderStyle* parentStyle)
1750 initForStyleResolve(e, parentStyle, pseudo);
1751 m_style = RenderStyle::create();
1754 m_style->inheritFrom(m_parentStyle);
1756 // Since we don't use pseudo-elements in any of our quirk/print user agent rules, don't waste time walking
1759 // Check UA, user and author rules.
1760 MatchResult matchResult;
1761 matchUARules(matchResult);
1763 if (m_matchAuthorAndUserStyles) {
1764 matchUserRules(matchResult, false);
1765 matchAuthorRules(matchResult, false);
1768 if (matchResult.matchedProperties.isEmpty())
1771 m_style->setStyleType(pseudo);
1773 applyMatchedProperties(matchResult);
1775 // Clean up our style object's display and text decorations (among other fixups).
1776 adjustRenderStyle(style(), parentStyle, 0);
1778 // Start loading images referenced by this style.
1779 loadPendingImages();
1781 #if ENABLE(CSS_SHADERS)
1782 // Start loading the shaders referenced by this style.
1783 loadPendingShaders();
1786 // Now return the style.
1787 return m_style.release();
1790 PassRefPtr<RenderStyle> CSSStyleSelector::styleForPage(int pageIndex)
1792 initForStyleResolve(m_checker.document()->documentElement()); // m_rootElementStyle will be set to the document style.
1794 m_style = RenderStyle::create();
1795 m_style->inheritFrom(m_rootElementStyle);
1797 const bool isLeft = isLeftPage(pageIndex);
1798 const bool isFirst = isFirstPage(pageIndex);
1799 const String page = pageName(pageIndex);
1802 matchPageRules(result, defaultPrintStyle, isLeft, isFirst, page);
1803 matchPageRules(result, m_userStyle.get(), isLeft, isFirst, page);
1804 // Only consider the global author RuleSet for @page rules, as per the HTML5 spec.
1805 matchPageRules(result, m_authorStyle.get(), isLeft, isFirst, page);
1806 m_lineHeightValue = 0;
1807 bool inheritedOnly = false;
1808 applyMatchedProperties<true>(result, false, 0, result.matchedProperties.size() - 1, inheritedOnly);
1810 // If our font got dirtied, go ahead and update it now.
1813 // Line-height is set when we are sure we decided on the font-size.
1814 if (m_lineHeightValue)
1815 applyProperty(CSSPropertyLineHeight, m_lineHeightValue);
1817 applyMatchedProperties<false>(result, false, 0, result.matchedProperties.size() - 1, inheritedOnly);
1819 // Start loading images referenced by this style.
1820 loadPendingImages();
1822 #if ENABLE(CSS_SHADERS)
1823 // Start loading the shaders referenced by this style.
1824 loadPendingShaders();
1827 // Now return the style.
1828 return m_style.release();
1831 static void addIntrinsicMargins(RenderStyle* style)
1833 // Intrinsic margin value.
1834 const int intrinsicMargin = 2 * style->effectiveZoom();
1836 // FIXME: Using width/height alone and not also dealing with min-width/max-width is flawed.
1837 // FIXME: Using "quirk" to decide the margin wasn't set is kind of lame.
1838 if (style->width().isIntrinsicOrAuto()) {
1839 if (style->marginLeft().quirk())
1840 style->setMarginLeft(Length(intrinsicMargin, Fixed));
1841 if (style->marginRight().quirk())
1842 style->setMarginRight(Length(intrinsicMargin, Fixed));
1845 if (style->height().isAuto()) {
1846 if (style->marginTop().quirk())
1847 style->setMarginTop(Length(intrinsicMargin, Fixed));
1848 if (style->marginBottom().quirk())
1849 style->setMarginBottom(Length(intrinsicMargin, Fixed));
1853 static EDisplay equivalentBlockDisplay(EDisplay display, bool isFloating, bool strictParsing)
1860 #if ENABLE(CSS_GRID_LAYOUT)
1866 // It is a WinIE bug that floated list items lose their bullets, so we'll emulate the quirk, but only in quirks mode.
1867 if (!strictParsing && isFloating)
1874 case INLINE_FLEXBOX:
1876 #if ENABLE(CSS_GRID_LAYOUT)
1885 case TABLE_ROW_GROUP:
1886 case TABLE_HEADER_GROUP:
1887 case TABLE_FOOTER_GROUP:
1889 case TABLE_COLUMN_GROUP:
1895 ASSERT_NOT_REACHED();
1898 ASSERT_NOT_REACHED();
1902 void CSSStyleSelector::adjustRenderStyle(RenderStyle* style, RenderStyle* parentStyle, Element *e)
1904 // Cache our original display.
1905 style->setOriginalDisplay(style->display());
1907 if (style->display() != NONE) {
1908 // If we have a <td> that specifies a float property, in quirks mode we just drop the float
1910 // Sites also commonly use display:inline/block on <td>s and <table>s. In quirks mode we force
1911 // these tags to retain their display types.
1912 if (!m_checker.strictParsing() && e) {
1913 if (e->hasTagName(tdTag)) {
1914 style->setDisplay(TABLE_CELL);
1915 style->setFloating(NoFloat);
1917 else if (e->hasTagName(tableTag))
1918 style->setDisplay(style->isDisplayInlineType() ? INLINE_TABLE : TABLE);
1921 if (e && (e->hasTagName(tdTag) || e->hasTagName(thTag))) {
1922 if (style->whiteSpace() == KHTML_NOWRAP) {
1923 // Figure out if we are really nowrapping or if we should just
1924 // use normal instead. If the width of the cell is fixed, then
1925 // we don't actually use NOWRAP.
1926 if (style->width().isFixed())
1927 style->setWhiteSpace(NORMAL);
1929 style->setWhiteSpace(NOWRAP);
1933 // Tables never support the -webkit-* values for text-align and will reset back to the default.
1934 if (e && e->hasTagName(tableTag) && (style->textAlign() == WEBKIT_LEFT || style->textAlign() == WEBKIT_CENTER || style->textAlign() == WEBKIT_RIGHT))
1935 style->setTextAlign(TAAUTO);
1937 // Frames and framesets never honor position:relative or position:absolute. This is necessary to
1938 // fix a crash where a site tries to position these objects. They also never honor display.
1939 if (e && (e->hasTagName(frameTag) || e->hasTagName(framesetTag))) {
1940 style->setPosition(StaticPosition);
1941 style->setDisplay(BLOCK);
1944 // Table headers with a text-align of auto will change the text-align to center.
1945 if (e && e->hasTagName(thTag) && style->textAlign() == TAAUTO)
1946 style->setTextAlign(CENTER);
1948 if (e && e->hasTagName(legendTag))
1949 style->setDisplay(BLOCK);
1951 // Absolute/fixed positioned elements, floating elements and the document element need block-like outside display.
1952 if (style->position() == AbsolutePosition || style->position() == FixedPosition || style->isFloating() || (e && e->document()->documentElement() == e))
1953 style->setDisplay(equivalentBlockDisplay(style->display(), style->isFloating(), m_checker.strictParsing()));
1955 // FIXME: Don't support this mutation for pseudo styles like first-letter or first-line, since it's not completely
1956 // clear how that should work.
1957 if (style->display() == INLINE && style->styleType() == NOPSEUDO && parentStyle && style->writingMode() != parentStyle->writingMode())
1958 style->setDisplay(INLINE_BLOCK);
1960 // After performing the display mutation, check table rows. We do not honor position:relative on
1961 // table rows or cells. This has been established in CSS2.1 (and caused a crash in containingBlock()
1963 if ((style->display() == TABLE_HEADER_GROUP || style->display() == TABLE_ROW_GROUP
1964 || style->display() == TABLE_FOOTER_GROUP || style->display() == TABLE_ROW) &&
1965 style->position() == RelativePosition)
1966 style->setPosition(StaticPosition);
1968 // writing-mode does not apply to table row groups, table column groups, table rows, and table columns.
1969 // FIXME: Table cells should be allowed to be perpendicular or flipped with respect to the table, though.
1970 if (style->display() == TABLE_COLUMN || style->display() == TABLE_COLUMN_GROUP || style->display() == TABLE_FOOTER_GROUP
1971 || style->display() == TABLE_HEADER_GROUP || style->display() == TABLE_ROW || style->display() == TABLE_ROW_GROUP
1972 || style->display() == TABLE_CELL)
1973 style->setWritingMode(parentStyle->writingMode());
1975 // FIXME: Since we don't support block-flow on flexible boxes yet, disallow setting
1976 // of block-flow to anything other than TopToBottomWritingMode.
1977 // https://bugs.webkit.org/show_bug.cgi?id=46418 - Flexible box support.
1978 if (style->writingMode() != TopToBottomWritingMode && (style->display() == BOX || style->display() == INLINE_BOX))
1979 style->setWritingMode(TopToBottomWritingMode);
1982 // Make sure our z-index value is only applied if the object is positioned.
1983 if (style->position() == StaticPosition)
1984 style->setHasAutoZIndex();
1986 // Auto z-index becomes 0 for the root element and transparent objects. This prevents
1987 // cases where objects that should be blended as a single unit end up with a non-transparent
1988 // object wedged in between them. Auto z-index also becomes 0 for objects that specify transforms/masks/reflections.
1989 if (style->hasAutoZIndex() && ((e && e->document()->documentElement() == e) || style->opacity() < 1.0f
1990 || style->hasTransformRelatedProperty() || style->hasMask() || style->boxReflect() || style->hasFilter()
1991 #if ENABLE(OVERFLOW_SCROLLING)
1992 // Touch overflow scrolling creates a stacking context.
1993 || style->useTouchOverflowScrolling()
1996 style->setZIndex(0);
1998 // Textarea considers overflow visible as auto.
1999 if (e && e->hasTagName(textareaTag)) {
2000 style->setOverflowX(style->overflowX() == OVISIBLE ? OAUTO : style->overflowX());
2001 style->setOverflowY(style->overflowY() == OVISIBLE ? OAUTO : style->overflowY());
2004 // Finally update our text decorations in effect, but don't allow text-decoration to percolate through
2005 // tables, inline blocks, inline tables, run-ins, or shadow DOM.
2006 if (style->display() == TABLE || style->display() == INLINE_TABLE || style->display() == RUN_IN
2007 || style->display() == INLINE_BLOCK || style->display() == INLINE_BOX || isAtShadowBoundary(e))
2008 style->setTextDecorationsInEffect(style->textDecoration());
2010 style->addToTextDecorationsInEffect(style->textDecoration());
2012 // If either overflow value is not visible, change to auto.
2013 if (style->overflowX() == OMARQUEE && style->overflowY() != OMARQUEE)
2014 style->setOverflowY(OMARQUEE);
2015 else if (style->overflowY() == OMARQUEE && style->overflowX() != OMARQUEE)
2016 style->setOverflowX(OMARQUEE);
2017 else if (style->overflowX() == OVISIBLE && style->overflowY() != OVISIBLE)
2018 style->setOverflowX(OAUTO);
2019 else if (style->overflowY() == OVISIBLE && style->overflowX() != OVISIBLE)
2020 style->setOverflowY(OAUTO);
2022 // Table rows, sections and the table itself will support overflow:hidden and will ignore scroll/auto.
2023 // FIXME: Eventually table sections will support auto and scroll.
2024 if (style->display() == TABLE || style->display() == INLINE_TABLE ||
2025 style->display() == TABLE_ROW_GROUP || style->display() == TABLE_ROW) {
2026 if (style->overflowX() != OVISIBLE && style->overflowX() != OHIDDEN)
2027 style->setOverflowX(OVISIBLE);
2028 if (style->overflowY() != OVISIBLE && style->overflowY() != OHIDDEN)
2029 style->setOverflowY(OVISIBLE);
2032 // Menulists should have visible overflow
2033 if (style->appearance() == MenulistPart) {
2034 style->setOverflowX(OVISIBLE);
2035 style->setOverflowY(OVISIBLE);
2038 // Cull out any useless layers and also repeat patterns into additional layers.
2039 style->adjustBackgroundLayers();
2040 style->adjustMaskLayers();
2042 // Do the same for animations and transitions.
2043 style->adjustAnimations();
2044 style->adjustTransitions();
2046 // Important: Intrinsic margins get added to controls before the theme has adjusted the style, since the theme will
2047 // alter fonts and heights/widths.
2048 if (e && e->isFormControlElement() && style->fontSize() >= 11) {
2049 // Don't apply intrinsic margins to image buttons. The designer knows how big the images are,
2050 // so we have to treat all image buttons as though they were explicitly sized.
2051 if (!e->hasTagName(inputTag) || !static_cast<HTMLInputElement*>(e)->isImageButton())
2052 addIntrinsicMargins(style);
2055 // Let the theme also have a crack at adjusting the style.
2056 if (style->hasAppearance())
2057 RenderTheme::defaultTheme()->adjustStyle(this, style, e, m_hasUAAppearance, m_borderData, m_backgroundData, m_backgroundColor);
2059 // If we have first-letter pseudo style, do not share this style.
2060 if (style->hasPseudoStyle(FIRST_LETTER))
2064 if (e && e->isSVGElement()) {
2065 // Spec: http://www.w3.org/TR/SVG/masking.html#OverflowProperty
2066 if (style->overflowY() == OSCROLL)
2067 style->setOverflowY(OHIDDEN);
2068 else if (style->overflowY() == OAUTO)
2069 style->setOverflowY(OVISIBLE);
2071 if (style->overflowX() == OSCROLL)
2072 style->setOverflowX(OHIDDEN);
2073 else if (style->overflowX() == OAUTO)
2074 style->setOverflowX(OVISIBLE);
2076 // Only the root <svg> element in an SVG document fragment tree honors css position
2077 if (!(e->hasTagName(SVGNames::svgTag) && e->parentNode() && !e->parentNode()->isSVGElement()))
2078 style->setPosition(RenderStyle::initialPosition());
2083 bool CSSStyleSelector::checkRegionStyle(Element* regionElement)
2085 // FIXME (BUG 72472): We don't add @-webkit-region rules of scoped style sheets for the moment,
2086 // so all region rules are global by default. Verify whether that can stand or needs changing.
2088 unsigned rulesSize = m_authorStyle->m_regionSelectorsAndRuleSets.size();
2089 for (unsigned i = 0; i < rulesSize; ++i) {
2090 ASSERT(m_authorStyle->m_regionSelectorsAndRuleSets.at(i).ruleSet.get());
2091 if (checkRegionSelector(m_authorStyle->m_regionSelectorsAndRuleSets.at(i).selector, regionElement))
2096 rulesSize = m_userStyle->m_regionSelectorsAndRuleSets.size();
2097 for (unsigned i = 0; i < rulesSize; ++i) {
2098 ASSERT(m_userStyle->m_regionSelectorsAndRuleSets.at(i).ruleSet.get());
2099 if (checkRegionSelector(m_userStyle->m_regionSelectorsAndRuleSets.at(i).selector, regionElement))
2107 void CSSStyleSelector::updateFont()
2112 checkForTextSizeAdjust();
2113 checkForGenericFamilyChange(style(), m_parentStyle);
2114 checkForZoomChange(style(), m_parentStyle);
2115 m_style->font().update(m_fontSelector);
2116 m_fontDirty = false;
2119 void CSSStyleSelector::cacheBorderAndBackground()
2121 m_hasUAAppearance = m_style->hasAppearance();
2122 if (m_hasUAAppearance) {
2123 m_borderData = m_style->border();
2124 m_backgroundData = *m_style->backgroundLayers();
2125 m_backgroundColor = m_style->backgroundColor();
2129 PassRefPtr<CSSRuleList> CSSStyleSelector::styleRulesForElement(Element* e, unsigned rulesToInclude)
2131 return pseudoStyleRulesForElement(e, NOPSEUDO, rulesToInclude);
2134 PassRefPtr<CSSRuleList> CSSStyleSelector::pseudoStyleRulesForElement(Element* e, PseudoId pseudoId, unsigned rulesToInclude)
2136 if (!e || !e->document()->haveStylesheetsLoaded())
2139 m_checker.setCollectingRulesOnly(true);
2142 initForStyleResolve(e, 0, pseudoId);
2145 if (rulesToInclude & UAAndUserCSSRules) {
2146 // First we match rules from the user agent sheet.
2147 matchUARules(dummy);
2149 // Now we check user sheet rules.
2150 if (m_matchAuthorAndUserStyles)
2151 matchUserRules(dummy, rulesToInclude & EmptyCSSRules);
2154 if (m_matchAuthorAndUserStyles && (rulesToInclude & AuthorCSSRules)) {
2155 m_sameOriginOnly = !(rulesToInclude & CrossOriginCSSRules);
2157 // Check the rules in author sheets.
2158 matchAuthorRules(dummy, rulesToInclude & EmptyCSSRules);
2160 m_sameOriginOnly = false;
2163 m_checker.setCollectingRulesOnly(false);
2165 return m_ruleList.release();
2168 inline bool CSSStyleSelector::checkSelector(const RuleData& ruleData, const ContainerNode* scope)
2170 m_dynamicPseudo = NOPSEUDO;
2171 m_checker.clearHasUnknownPseudoElements();
2173 if (ruleData.hasFastCheckableSelector()) {
2174 // We know this selector does not include any pseudo elements.
2175 if (m_checker.pseudoStyle() != NOPSEUDO)
2177 // We know a sufficiently simple single part selector matches simply because we found it from the rule hash.
2178 // This is limited to HTML only so we don't need to check the namespace.
2179 if (ruleData.hasRightmostSelectorMatchingHTMLBasedOnRuleHash() && m_element->isHTMLElement()) {
2180 if (!ruleData.hasMultipartSelector())
2182 } else if (!SelectorChecker::tagMatches(m_element, ruleData.selector()))
2184 if (!SelectorChecker::fastCheckRightmostAttributeSelector(m_element, ruleData.selector()))
2186 return m_checker.fastCheckSelector(ruleData.selector(), m_element);
2190 SelectorChecker::SelectorCheckingContext context(ruleData.selector(), m_element, SelectorChecker::VisitedMatchEnabled);
2191 context.elementStyle = style();
2192 context.elementParentStyle = m_parentNode ? m_parentNode->renderStyle() : 0;
2193 context.scope = scope;
2194 SelectorChecker::SelectorMatch match = m_checker.checkSelector(context, m_dynamicPseudo);
2195 if (match != SelectorChecker::SelectorMatches)
2197 if (m_checker.pseudoStyle() != NOPSEUDO && m_checker.pseudoStyle() != m_dynamicPseudo)
2202 bool CSSStyleSelector::checkRegionSelector(CSSSelector* regionSelector, Element* regionElement)
2204 if (!regionSelector || !regionElement)
2207 m_checker.clearHasUnknownPseudoElements();
2208 m_checker.setPseudoStyle(NOPSEUDO);
2210 for (CSSSelector* s = regionSelector; s; s = CSSSelectorList::next(s))
2211 if (m_checker.checkSelector(s, regionElement))
2217 bool CSSStyleSelector::determineStylesheetSelectorScopes(CSSStyleSheet* stylesheet, HashSet<AtomicStringImpl*>& idScopes, HashSet<AtomicStringImpl*>& classScopes)
2219 ASSERT(!stylesheet->isLoading());
2221 size_t size = stylesheet->length();
2222 for (size_t i = 0; i < size; i++) {
2223 CSSRule* rule = stylesheet->item(i);
2224 if (rule->isStyleRule()) {
2225 StyleRule* styleRule = static_cast<CSSStyleRule*>(rule)->styleRule();
2226 if (!SelectorChecker::determineSelectorScopes(styleRule->selectorList(), idScopes, classScopes))
2230 if (rule->isImportRule()) {
2231 CSSImportRule* importRule = static_cast<CSSImportRule*>(rule);
2232 if (importRule->styleSheet()) {
2233 if (!determineStylesheetSelectorScopes(importRule->styleSheet(), idScopes, classScopes))
2238 // FIXME: Media rules and maybe some others could be allowed.
2244 // -----------------------------------------------------------------
2246 static inline bool isSelectorMatchingHTMLBasedOnRuleHash(const CSSSelector* selector)
2248 const AtomicString& selectorNamespace = selector->tag().namespaceURI();
2249 if (selectorNamespace != starAtom && selectorNamespace != xhtmlNamespaceURI)
2251 if (selector->m_match == CSSSelector::None)
2253 if (selector->tag() != starAtom)
2255 if (SelectorChecker::isCommonPseudoClassSelector(selector))
2257 return selector->m_match == CSSSelector::Id || selector->m_match == CSSSelector::Class;
2260 static inline bool selectorListContainsUncommonAttributeSelector(const CSSSelector* selector)
2262 CSSSelectorList* selectorList = selector->selectorList();
2265 for (CSSSelector* subSelector = selectorList->first(); subSelector; subSelector = CSSSelectorList::next(subSelector)) {
2266 if (subSelector->isAttributeSelector())
2272 static inline bool isCommonAttributeSelectorAttribute(const QualifiedName& attribute)
2274 // These are explicitly tested for equality in canShareStyleWithElement.
2275 return attribute == typeAttr || attribute == readonlyAttr;
2278 static inline bool containsUncommonAttributeSelector(const CSSSelector* selector)
2281 // Allow certain common attributes (used in the default style) in the selectors that match the current element.
2282 if (selector->isAttributeSelector() && !isCommonAttributeSelectorAttribute(selector->attribute()))
2284 if (selectorListContainsUncommonAttributeSelector(selector))
2286 if (selector->relation() != CSSSelector::SubSelector)
2288 selector = selector->tagHistory();
2291 for (selector = selector->tagHistory(); selector; selector = selector->tagHistory()) {
2292 if (selector->isAttributeSelector())
2294 if (selectorListContainsUncommonAttributeSelector(selector))
2300 RuleData::RuleData(StyleRule* rule, CSSSelector* selector, unsigned position, bool canUseFastCheckSelector, bool inRegionRule)
2302 , m_selector(selector)
2303 , m_specificity(selector->specificity())
2304 , m_position(position)
2305 , m_hasFastCheckableSelector(canUseFastCheckSelector && SelectorChecker::isFastCheckableSelector(selector))
2306 , m_hasMultipartSelector(!!selector->tagHistory())
2307 , m_hasRightmostSelectorMatchingHTMLBasedOnRuleHash(isSelectorMatchingHTMLBasedOnRuleHash(selector))
2308 , m_containsUncommonAttributeSelector(WebCore::containsUncommonAttributeSelector(selector))
2309 , m_linkMatchType(SelectorChecker::determineLinkMatchType(selector))
2310 , m_isInRegionRule(inRegionRule)
2312 SelectorChecker::collectIdentifierHashes(m_selector, m_descendantSelectorIdentifierHashes, maximumIdentifierCount);
2317 , m_autoShrinkToFitEnabled(true)
2321 static inline void collectFeaturesFromSelector(CSSStyleSelector::Features& features, const CSSSelector* selector)
2323 if (selector->m_match == CSSSelector::Id)
2324 features.idsInRules.add(selector->value().impl());
2325 if (selector->isAttributeSelector())
2326 features.attrsInRules.add(selector->attribute().localName().impl());
2327 switch (selector->pseudoType()) {
2328 case CSSSelector::PseudoFirstLine:
2329 features.usesFirstLineRules = true;
2331 case CSSSelector::PseudoBefore:
2332 case CSSSelector::PseudoAfter:
2333 features.usesBeforeAfterRules = true;
2335 case CSSSelector::PseudoLink:
2336 case CSSSelector::PseudoVisited:
2337 features.usesLinkRules = true;
2344 static void collectFeaturesFromRuleData(CSSStyleSelector::Features& features, const RuleData& ruleData)
2346 bool foundSiblingSelector = false;
2347 for (CSSSelector* selector = ruleData.selector(); selector; selector = selector->tagHistory()) {
2348 collectFeaturesFromSelector(features, selector);
2350 if (CSSSelectorList* selectorList = selector->selectorList()) {
2351 for (CSSSelector* subSelector = selectorList->first(); subSelector; subSelector = CSSSelectorList::next(subSelector)) {
2352 if (!foundSiblingSelector && selector->isSiblingSelector())
2353 foundSiblingSelector = true;
2354 collectFeaturesFromSelector(features, subSelector);
2356 } else if (!foundSiblingSelector && selector->isSiblingSelector())
2357 foundSiblingSelector = true;
2359 if (foundSiblingSelector)
2360 features.siblingRules.append(CSSStyleSelector::RuleSelectorPair(ruleData.rule(), ruleData.selector()));
2361 if (ruleData.containsUncommonAttributeSelector())
2362 features.uncommonAttributeRules.append(CSSStyleSelector::RuleSelectorPair(ruleData.rule(), ruleData.selector()));
2365 void RuleSet::addToRuleSet(AtomicStringImpl* key, AtomRuleMap& map, const RuleData& ruleData)
2369 OwnPtr<Vector<RuleData> >& rules = map.add(key, nullptr).first->second;
2371 rules = adoptPtr(new Vector<RuleData>);
2372 rules->append(ruleData);
2375 void RuleSet::addRule(StyleRule* rule, CSSSelector* selector, bool canUseFastCheckSelector, bool inRegionRule)
2377 RuleData ruleData(rule, selector, m_ruleCount++, canUseFastCheckSelector, inRegionRule);
2378 collectFeaturesFromRuleData(m_features, ruleData);
2380 if (selector->m_match == CSSSelector::Id) {
2381 addToRuleSet(selector->value().impl(), m_idRules, ruleData);
2384 if (selector->m_match == CSSSelector::Class) {
2385 addToRuleSet(selector->value().impl(), m_classRules, ruleData);
2388 if (selector->isUnknownPseudoElement()) {
2389 addToRuleSet(selector->value().impl(), m_shadowPseudoElementRules, ruleData);
2392 if (SelectorChecker::isCommonPseudoClassSelector(selector)) {
2393 switch (selector->pseudoType()) {
2394 case CSSSelector::PseudoLink:
2395 case CSSSelector::PseudoVisited:
2396 case CSSSelector::PseudoAnyLink:
2397 m_linkPseudoClassRules.append(ruleData);
2399 case CSSSelector::PseudoFocus:
2400 m_focusPseudoClassRules.append(ruleData);
2403 ASSERT_NOT_REACHED();
2407 const AtomicString& localName = selector->tag().localName();
2408 if (localName != starAtom) {
2409 addToRuleSet(localName.impl(), m_tagRules, ruleData);
2412 m_universalRules.append(ruleData);
2415 void RuleSet::addPageRule(CSSPageRule* rule)
2417 m_pageRules.append(rule);
2420 void RuleSet::addRegionRule(WebKitCSSRegionRule* rule)
2422 RuleSet* regionRuleSet = new RuleSet;
2423 // The region rule set should take into account the position inside the parent rule set.
2424 // Otherwise, the rules inside region block might be incorrectly positioned before other similar rules from
2425 // the stylesheet that contains the region block.
2426 regionRuleSet->m_ruleCount = m_ruleCount;
2428 // Collect the region rules into a rule set
2429 CSSRuleList* regionStylingRules = rule->cssRules();
2430 unsigned rulesSize = regionStylingRules->length();
2431 for (unsigned i = 0; i < rulesSize; ++i) {
2432 CSSRule* regionStylingRule = regionStylingRules->item(i);
2433 if (regionStylingRule->isStyleRule())
2434 regionRuleSet->addStyleRule(static_cast<CSSStyleRule*>(regionStylingRule)->styleRule(), true, true);
2437 m_regionSelectorsAndRuleSets.append(RuleSetSelectorPair(rule->selectorList().first(), regionRuleSet));
2440 void RuleSet::addRulesFromSheet(CSSStyleSheet* sheet, const MediaQueryEvaluator& medium, CSSStyleSelector* styleSelector, const ContainerNode* scope)
2444 // No media implies "all", but if a media list exists it must
2445 // contain our current medium
2446 if (sheet->media() && !medium.eval(sheet->media(), styleSelector))
2447 return; // the style sheet doesn't apply
2449 int len = sheet->length();
2451 for (int i = 0; i < len; i++) {
2452 CSSRule* rule = sheet->item(i);
2453 if (rule->isStyleRule())
2454 addStyleRule(static_cast<CSSStyleRule*>(rule)->styleRule(), !scope);
2455 else if (rule->isPageRule())
2456 addPageRule(static_cast<CSSPageRule*>(rule));
2457 else if (rule->isImportRule()) {
2458 CSSImportRule* import = static_cast<CSSImportRule*>(rule);
2459 if (import->styleSheet() && (!import->media() || medium.eval(import->media(), styleSelector)))
2460 addRulesFromSheet(import->styleSheet(), medium, styleSelector, scope);
2462 else if (rule->isMediaRule()) {
2463 CSSMediaRule* r = static_cast<CSSMediaRule*>(rule);
2464 CSSRuleList* rules = r->cssRules();
2466 if ((!r->media() || medium.eval(r->media(), styleSelector)) && rules) {
2467 // Traverse child elements of the @media rule.
2468 for (unsigned j = 0; j < rules->length(); j++) {
2469 CSSRule *childItem = rules->item(j);
2470 if (childItem->isStyleRule())
2471 addStyleRule(static_cast<CSSStyleRule*>(childItem)->styleRule(), !scope);
2472 else if (childItem->isPageRule())
2473 addPageRule(static_cast<CSSPageRule*>(childItem));
2474 else if (childItem->isFontFaceRule() && styleSelector) {
2475 // Add this font face to our set.
2476 // FIXME(BUG 72461): We don't add @font-face rules of scoped style sheets for the moment.
2479 const CSSFontFaceRule* fontFaceRule = static_cast<CSSFontFaceRule*>(childItem);
2480 styleSelector->fontSelector()->addFontFaceRule(fontFaceRule);
2481 styleSelector->invalidateMatchedPropertiesCache();
2482 } else if (childItem->isKeyframesRule() && styleSelector) {
2483 // Add this keyframe rule to our set.
2484 // FIXME(BUG 72462): We don't add @keyframe rules of scoped style sheets for the moment.
2487 styleSelector->addKeyframeStyle(static_cast<WebKitCSSKeyframesRule*>(childItem));
2491 } else if (rule->isFontFaceRule() && styleSelector) {
2492 // Add this font face to our set.
2493 // FIXME(BUG 72461): We don't add @font-face rules of scoped style sheets for the moment.
2496 const CSSFontFaceRule* fontFaceRule = static_cast<CSSFontFaceRule*>(rule);
2497 styleSelector->fontSelector()->addFontFaceRule(fontFaceRule);
2498 styleSelector->invalidateMatchedPropertiesCache();
2499 } else if (rule->isKeyframesRule()) {
2500 // FIXME (BUG 72462): We don't add @keyframe rules of scoped style sheets for the moment.
2503 styleSelector->addKeyframeStyle(static_cast<WebKitCSSKeyframesRule*>(rule));
2504 } else if (rule->isRegionRule() && styleSelector) {
2505 // FIXME (BUG 72472): We don't add @-webkit-region rules of scoped style sheets for the moment.
2508 addRegionRule(static_cast<WebKitCSSRegionRule*>(rule));
2511 if (m_autoShrinkToFitEnabled)
2515 void RuleSet::addStyleRule(StyleRule* rule, bool canUseFastCheckSelector, bool isInRegionRule)
2517 for (CSSSelector* s = rule->selectorList().first(); s; s = CSSSelectorList::next(s))
2518 addRule(rule, s, canUseFastCheckSelector, isInRegionRule);
2521 static inline void shrinkMapVectorsToFit(RuleSet::AtomRuleMap& map)
2523 RuleSet::AtomRuleMap::iterator end = map.end();
2524 for (RuleSet::AtomRuleMap::iterator it = map.begin(); it != end; ++it)
2525 it->second->shrinkToFit();
2528 void RuleSet::shrinkToFit()
2530 shrinkMapVectorsToFit(m_idRules);
2531 shrinkMapVectorsToFit(m_classRules);
2532 shrinkMapVectorsToFit(m_tagRules);
2533 shrinkMapVectorsToFit(m_shadowPseudoElementRules);
2534 m_linkPseudoClassRules.shrinkToFit();
2535 m_focusPseudoClassRules.shrinkToFit();
2536 m_universalRules.shrinkToFit();
2537 m_pageRules.shrinkToFit();
2540 // -------------------------------------------------------------------------------------
2541 // this is mostly boring stuff on how to apply a certain rule to the renderstyle...
2543 Length CSSStyleSelector::convertToIntLength(CSSPrimitiveValue* primitiveValue, RenderStyle* style, RenderStyle* rootStyle, double multiplier)
2545 return primitiveValue ? primitiveValue->convertToLength<FixedIntegerConversion | PercentConversion | FractionConversion>(style, rootStyle, multiplier) : Length(Undefined);
2548 Length CSSStyleSelector::convertToFloatLength(CSSPrimitiveValue* primitiveValue, RenderStyle* style, RenderStyle* rootStyle, double multiplier)
2550 return primitiveValue ? primitiveValue->convertToLength<FixedFloatConversion | PercentConversion | FractionConversion>(style, rootStyle, multiplier) : Length(Undefined);
2553 template <bool applyFirst>
2554 void CSSStyleSelector::applyProperties(const StylePropertySet* properties, StyleRule* rule, bool isImportant, bool inheritedOnly, bool filterRegionProperties)
2556 ASSERT(!filterRegionProperties || m_regionForStyling);
2557 InspectorInstrumentationCookie cookie = InspectorInstrumentation::willProcessRule(document(), rule);
2559 unsigned propertyCount = properties->propertyCount();
2560 for (unsigned i = 0; i < propertyCount; ++i) {
2561 const CSSProperty& current = properties->propertyAt(i);
2562 if (isImportant != current.isImportant())
2564 if (inheritedOnly && !current.isInherited()) {
2565 // If the property value is explicitly inherited, we need to apply further non-inherited properties
2566 // as they might override the value inherited here. For this reason we don't allow declarations with
2567 // explicitly inherited properties to be cached.
2568 ASSERT(!current.value()->isInheritedValue());
2571 int property = current.id();
2573 if (filterRegionProperties && !CSSStyleSelector::isValidRegionStyleProperty(property))
2577 COMPILE_ASSERT(firstCSSProperty == CSSPropertyColor, CSS_color_is_first_property);
2578 COMPILE_ASSERT(CSSPropertyZoom == CSSPropertyColor + 18, CSS_zoom_is_end_of_first_prop_range);
2579 COMPILE_ASSERT(CSSPropertyLineHeight == CSSPropertyZoom + 1, CSS_line_height_is_after_zoom);
2580 // give special priority to font-xxx, color properties, etc
2581 if (property > CSSPropertyLineHeight)
2583 // we apply line-height later
2584 if (property == CSSPropertyLineHeight) {
2585 m_lineHeightValue = current.value();
2588 applyProperty(current.id(), current.value());
2591 if (property > CSSPropertyLineHeight)
2592 applyProperty(current.id(), current.value());
2594 InspectorInstrumentation::didProcessRule(cookie);
2597 template <bool applyFirst>
2598 void CSSStyleSelector::applyMatchedProperties(const MatchResult& matchResult, bool isImportant, int startIndex, int endIndex, bool inheritedOnly)
2600 if (startIndex == -1)
2603 if (m_style->insideLink() != NotInsideLink) {
2604 for (int i = startIndex; i <= endIndex; ++i) {
2605 const MatchedProperties& matchedProperties = matchResult.matchedProperties[i];
2606 unsigned linkMatchType = matchedProperties.linkMatchType;
2607 // FIXME: It would be nicer to pass these as arguments but that requires changes in many places.
2608 m_applyPropertyToRegularStyle = linkMatchType & SelectorChecker::MatchLink;
2609 m_applyPropertyToVisitedLinkStyle = linkMatchType & SelectorChecker::MatchVisited;
2611 applyProperties<applyFirst>(matchedProperties.properties.get(), matchResult.matchedRules[i], isImportant, inheritedOnly, matchedProperties.isInRegionRule);
2613 m_applyPropertyToRegularStyle = true;
2614 m_applyPropertyToVisitedLinkStyle = false;
2617 for (int i = startIndex; i <= endIndex; ++i) {
2618 const MatchedProperties& matchedProperties = matchResult.matchedProperties[i];
2619 applyProperties<applyFirst>(matchedProperties.properties.get(), matchResult.matchedRules[i], isImportant, inheritedOnly, matchedProperties.isInRegionRule);
2623 unsigned CSSStyleSelector::computeMatchedPropertiesHash(const MatchedProperties* properties, unsigned size)
2626 return StringHasher::hashMemory(properties, sizeof(MatchedProperties) * size);
2629 bool operator==(const CSSStyleSelector::MatchRanges& a, const CSSStyleSelector::MatchRanges& b)
2631 return a.firstUARule == b.firstUARule
2632 && a.lastUARule == b.lastUARule
2633 && a.firstAuthorRule == b.firstAuthorRule
2634 && a.lastAuthorRule == b.lastAuthorRule
2635 && a.firstUserRule == b.firstUserRule
2636 && a.lastUserRule == b.lastUserRule;
2639 bool operator!=(const CSSStyleSelector::MatchRanges& a, const CSSStyleSelector::MatchRanges& b)
2644 bool operator==(const CSSStyleSelector::MatchedProperties& a, const CSSStyleSelector::MatchedProperties& b)
2646 return a.properties == b.properties && a.linkMatchType == b.linkMatchType;
2649 bool operator!=(const CSSStyleSelector::MatchedProperties& a, const CSSStyleSelector::MatchedProperties& b)
2654 const CSSStyleSelector::MatchedPropertiesCacheItem* CSSStyleSelector::findFromMatchedPropertiesCache(unsigned hash, const MatchResult& matchResult)
2658 MatchedPropertiesCache::iterator it = m_matchedPropertiesCache.find(hash);
2659 if (it == m_matchedPropertiesCache.end())
2661 MatchedPropertiesCacheItem& cacheItem = it->second;
2663 size_t size = matchResult.matchedProperties.size();
2664 if (size != cacheItem.matchedProperties.size())
2666 for (size_t i = 0; i < size; ++i) {
2667 if (matchResult.matchedProperties[i] != cacheItem.matchedProperties[i])
2670 if (cacheItem.ranges != matchResult.ranges)
2675 void CSSStyleSelector::addToMatchedPropertiesCache(const RenderStyle* style, const RenderStyle* parentStyle, unsigned hash, const MatchResult& matchResult)
2677 static unsigned matchedDeclarationCacheAdditionsBetweenSweeps = 100;
2678 if (++m_matchedPropertiesCacheAdditionsSinceLastSweep >= matchedDeclarationCacheAdditionsBetweenSweeps) {
2679 sweepMatchedPropertiesCache();
2680 m_matchedPropertiesCacheAdditionsSinceLastSweep = 0;
2684 MatchedPropertiesCacheItem cacheItem;
2685 cacheItem.matchedProperties.append(matchResult.matchedProperties);
2686 cacheItem.ranges = matchResult.ranges;
2687 // Note that we don't cache the original RenderStyle instance. It may be further modified.
2688 // The RenderStyle in the cache is really just a holder for the substructures and never used as-is.
2689 cacheItem.renderStyle = RenderStyle::clone(style);
2690 cacheItem.parentRenderStyle = RenderStyle::clone(parentStyle);
2691 m_matchedPropertiesCache.add(hash, cacheItem);
2694 void CSSStyleSelector::invalidateMatchedPropertiesCache()
2696 m_matchedPropertiesCache.clear();
2699 static bool isCacheableInMatchedPropertiesCache(const Element* element, const RenderStyle* style, const RenderStyle* parentStyle)
2701 // FIXME: CSSPropertyWebkitWritingMode modifies state when applying to document element. We can't skip the applying by caching.
2702 if (element == element->document()->documentElement() && element->document()->writingModeSetOnDocumentElement())
2704 if (style->unique() || (style->styleType() != NOPSEUDO && parentStyle->unique()))
2706 if (style->hasAppearance())
2708 if (style->zoom() != RenderStyle::initialZoom())
2710 // The cache assumes static knowledge about which properties are inherited.
2711 if (parentStyle->hasExplicitlyInheritedProperties())
2716 void CSSStyleSelector::applyMatchedProperties(const MatchResult& matchResult)
2718 unsigned cacheHash = matchResult.isCacheable ? computeMatchedPropertiesHash(matchResult.matchedProperties.data(), matchResult.matchedProperties.size()) : 0;
2719 bool applyInheritedOnly = false;
2720 const MatchedPropertiesCacheItem* cacheItem = 0;
2721 if (cacheHash && (cacheItem = findFromMatchedPropertiesCache(cacheHash, matchResult))) {
2722 // We can build up the style by copying non-inherited properties from an earlier style object built using the same exact
2723 // style declarations. We then only need to apply the inherited properties, if any, as their values can depend on the
2724 // element context. This is fast and saves memory by reusing the style data structures.
2725 m_style->copyNonInheritedFrom(cacheItem->renderStyle.get());
2726 if (m_parentStyle->inheritedDataShared(cacheItem->parentRenderStyle.get())) {
2727 EInsideLink linkStatus = m_style->insideLink();
2728 // If the cache item parent style has identical inherited properties to the current parent style then the
2729 // resulting style will be identical too. We copy the inherited properties over from the cache and are done.
2730 m_style->inheritFrom(cacheItem->renderStyle.get());
2731 // Unfortunately the link status is treated like an inherited property. We need to explicitly restore it.
2732 m_style->setInsideLink(linkStatus);
2735 applyInheritedOnly = true;
2737 // Now we have all of the matched rules in the appropriate order. Walk the rules and apply
2738 // high-priority properties first, i.e., those properties that other properties depend on.
2739 // The order is (1) high-priority not important, (2) high-priority important, (3) normal not important
2740 // and (4) normal important.
2741 m_lineHeightValue = 0;
2742 applyMatchedProperties<true>(matchResult, false, 0, matchResult.matchedProperties.size() - 1, applyInheritedOnly);
2743 applyMatchedProperties<true>(matchResult, true, matchResult.ranges.firstAuthorRule, matchResult.ranges.lastAuthorRule, applyInheritedOnly);
2744 applyMatchedProperties<true>(matchResult, true, matchResult.ranges.firstUserRule, matchResult.ranges.lastUserRule, applyInheritedOnly);
2745 applyMatchedProperties<true>(matchResult, true, matchResult.ranges.firstUARule, matchResult.ranges.lastUARule, applyInheritedOnly);
2747 if (cacheItem && cacheItem->renderStyle->effectiveZoom() != m_style->effectiveZoom()) {
2749 applyInheritedOnly = false;
2752 // If our font got dirtied, go ahead and update it now.
2755 // Line-height is set when we are sure we decided on the font-size.
2756 if (m_lineHeightValue)
2757 applyProperty(CSSPropertyLineHeight, m_lineHeightValue);
2759 // Many properties depend on the font. If it changes we just apply all properties.
2760 if (cacheItem && cacheItem->renderStyle->fontDescription() != m_style->fontDescription())
2761 applyInheritedOnly = false;
2763 // Now do the normal priority UA properties.
2764 applyMatchedProperties<false>(matchResult, false, matchResult.ranges.firstUARule, matchResult.ranges.lastUARule, applyInheritedOnly);
2766 // Cache our border and background so that we can examine them later.
2767 cacheBorderAndBackground();
2769 // Now do the author and user normal priority properties and all the !important properties.
2770 applyMatchedProperties<false>(matchResult, false, matchResult.ranges.lastUARule + 1, matchResult.matchedProperties.size() - 1, applyInheritedOnly);
2771 applyMatchedProperties<false>(matchResult, true, matchResult.ranges.firstAuthorRule, matchResult.ranges.lastAuthorRule, applyInheritedOnly);
2772 applyMatchedProperties<false>(matchResult, true, matchResult.ranges.firstUserRule, matchResult.ranges.lastUserRule, applyInheritedOnly);
2773 applyMatchedProperties<false>(matchResult, true, matchResult.ranges.firstUARule, matchResult.ranges.lastUARule, applyInheritedOnly);
2775 loadPendingImages();
2777 #if ENABLE(CSS_SHADERS)
2778 loadPendingShaders();
2781 ASSERT(!m_fontDirty);
2783 if (cacheItem || !cacheHash)
2785 if (!isCacheableInMatchedPropertiesCache(m_element, m_style.get(), m_parentStyle))
2787 addToMatchedPropertiesCache(m_style.get(), m_parentStyle, cacheHash, matchResult);
2790 static inline bool comparePageRules(const CSSPageRule* r1, const CSSPageRule* r2)
2792 return r1->selector()->specificity() < r2->selector()->specificity();
2795 void CSSStyleSelector::matchPageRules(MatchResult& result, RuleSet* rules, bool isLeftPage, bool isFirstPage, const String& pageName)
2800 Vector<CSSPageRule*> matchedPageRules;
2801 matchPageRulesForList(matchedPageRules, rules->pageRules(), isLeftPage, isFirstPage, pageName);
2802 if (matchedPageRules.isEmpty())
2805 std::stable_sort(matchedPageRules.begin(), matchedPageRules.end(), comparePageRules);
2807 for (unsigned i = 0; i < matchedPageRules.size(); i++)
2808 addMatchedProperties(result, matchedPageRules[i]->properties());
2811 void CSSStyleSelector::matchPageRulesForList(Vector<CSSPageRule*>& matchedRules, const Vector<CSSPageRule*>& rules, bool isLeftPage, bool isFirstPage, const String& pageName)
2813 unsigned size = rules.size();
2814 for (unsigned i = 0; i < size; ++i) {
2815 CSSPageRule* rule = rules[i];
2816 const AtomicString& selectorLocalName = rule->selector()->tag().localName();
2817 if (selectorLocalName != starAtom && selectorLocalName != pageName)
2819 CSSSelector::PseudoType pseudoType = rule->selector()->pseudoType();
2820 if ((pseudoType == CSSSelector::PseudoLeftPage && !isLeftPage)
2821 || (pseudoType == CSSSelector::PseudoRightPage && isLeftPage)
2822 || (pseudoType == CSSSelector::PseudoFirstPage && !isFirstPage))
2825 // If the rule has no properties to apply, then ignore it.
2826 StylePropertySet* properties = rule->properties();
2827 if (!properties || properties->isEmpty())
2830 // Add this rule to our list of matched rules.
2831 matchedRules.append(rule);
2835 bool CSSStyleSelector::isLeftPage(int pageIndex) const
2837 bool isFirstPageLeft = false;
2838 if (!m_rootElementStyle->isLeftToRightDirection())
2839 isFirstPageLeft = true;
2841 return (pageIndex + (isFirstPageLeft ? 1 : 0)) % 2;
2844 bool CSSStyleSelector::isFirstPage(int pageIndex) const
2846 // FIXME: In case of forced left/right page, page at index 1 (not 0) can be the first page.
2847 return (!pageIndex);
2850 String CSSStyleSelector::pageName(int /* pageIndex */) const
2852 // FIXME: Implement page index to page name mapping.
2856 void CSSStyleSelector::applyPropertyToStyle(int id, CSSValue* value, RenderStyle* style)
2859 initForStyleResolve(0, style);
2861 applyPropertyToCurrentStyle(id, value);
2864 void CSSStyleSelector::applyPropertyToCurrentStyle(int id, CSSValue* value)
2867 applyProperty(id, value);
2870 inline bool isValidVisitedLinkProperty(int id)
2872 switch(static_cast<CSSPropertyID>(id)) {
2873 case CSSPropertyBackgroundColor:
2874 case CSSPropertyBorderLeftColor:
2875 case CSSPropertyBorderRightColor:
2876 case CSSPropertyBorderTopColor:
2877 case CSSPropertyBorderBottomColor:
2878 case CSSPropertyColor:
2879 case CSSPropertyOutlineColor:
2880 case CSSPropertyWebkitColumnRuleColor:
2881 case CSSPropertyWebkitTextEmphasisColor:
2882 case CSSPropertyWebkitTextFillColor:
2883 case CSSPropertyWebkitTextStrokeColor:
2884 // Also allow shorthands so that inherit/initial still work.
2885 case CSSPropertyBackground:
2886 case CSSPropertyBorderLeft:
2887 case CSSPropertyBorderRight:
2888 case CSSPropertyBorderTop:
2889 case CSSPropertyBorderBottom:
2890 case CSSPropertyOutline:
2891 case CSSPropertyWebkitColumnRule:
2893 case CSSPropertyFill:
2894 case CSSPropertyStroke:
2904 // http://dev.w3.org/csswg/css3-regions/#the-at-region-style-rule
2905 // FIXME: add incremental support for other region styling properties.
2906 inline bool CSSStyleSelector::isValidRegionStyleProperty(int id)
2908 switch (static_cast<CSSPropertyID>(id)) {
2909 case CSSPropertyBackgroundColor:
2918 // SVG handles zooming in a different way compared to CSS. The whole document is scaled instead
2919 // of each individual length value in the render style / tree. CSSPrimitiveValue::computeLength*()
2920 // multiplies each resolved length with the zoom multiplier - so for SVG we need to disable that.
2921 // Though all CSS values that can be applied to outermost <svg> elements (width/height/border/padding...)
2922 // need to respect the scaling. RenderBox (the parent class of RenderSVGRoot) grabs values like
2923 // width/height/border/padding/... from the RenderStyle -> for SVG these values would never scale,
2924 // if we'd pass a 1.0 zoom factor everyhwere. So we only pass a zoom factor of 1.0 for specific
2925 // properties that are NOT allowed to scale within a zoomed SVG document (letter/word-spacing/font-size).
2926 bool CSSStyleSelector::useSVGZoomRules()
2928 return m_element && m_element->isSVGElement();
2931 #if ENABLE(CSS_GRID_LAYOUT)
2933 static bool createGridTrackBreadth(CSSPrimitiveValue* primitiveValue, CSSStyleSelector* selector, Length& length)
2935 Length workingLength = primitiveValue->convertToLength<FixedIntegerConversion | PercentConversion | AutoConversion>(selector->style(), selector->rootElementStyle(), selector->style()->effectiveZoom());
2936 if (workingLength.isUndefined())
2939 if (primitiveValue->isLength())
2940 workingLength.setQuirk(primitiveValue->isQuirkValue());
2942 length = workingLength;
2946 static bool createGridTrackList(CSSValue* value, Vector<Length>& lengths, CSSStyleSelector* selector)
2949 if (value->isPrimitiveValue()) {
2950 CSSPrimitiveValue* primitiveValue = static_cast<CSSPrimitiveValue*>(value);
2951 if (primitiveValue->getIdent() == CSSValueNone) {
2952 lengths.append(Length(Undefined));
2958 if (value->isValueList()) {
2959 for (CSSValueListIterator i = value; i.hasMore(); i.advance()) {
2960 CSSValue* currValue = i.value();
2961 if (!currValue->isPrimitiveValue())
2965 if (!createGridTrackBreadth(static_cast<CSSPrimitiveValue*>(currValue), selector, length))
2968 lengths.append(length);
2977 static bool createGridPosition(CSSValue* value, Length& position)
2979 // For now, we only accept: <integer> | 'auto'
2980 if (!value->isPrimitiveValue())
2983 CSSPrimitiveValue* primitiveValue = static_cast<CSSPrimitiveValue*>(value);
2984 if (primitiveValue->getIdent() == CSSValueAuto)
2987 ASSERT(primitiveValue->isNumber());
2988 position.setValue(primitiveValue->getIntValue());
2993 void CSSStyleSelector::applyProperty(int id, CSSValue *value)
2995 bool isInherit = m_parentNode && value->isInheritedValue();
2996 bool isInitial = value->isInitialValue() || (!m_parentNode && value->isInheritedValue());
2998 ASSERT(!isInherit || !isInitial); // isInherit -> !isInitial && isInitial -> !isInherit
3000 if (!applyPropertyToRegularStyle() && (!applyPropertyToVisitedLinkStyle() || !isValidVisitedLinkProperty(id))) {
3001 // Limit the properties that can be applied to only the ones honored by :visited.
3005 CSSPropertyID property = static_cast<CSSPropertyID>(id);
3007 if (isInherit && m_parentStyle && !m_parentStyle->hasExplicitlyInheritedProperties() && !CSSProperty::isInheritedProperty(property))
3008 m_parentStyle->setHasExplicitlyInheritedProperties();
3010 // check lookup table for implementations and use when available
3011 const PropertyHandler& handler = m_applyProperty.propertyHandler(property);
3012 if (handler.isValid()) {
3014 handler.applyInheritValue(this);
3016 handler.applyInitialValue(this);
3018 handler.applyValue(this, value);
3022 CSSPrimitiveValue* primitiveValue = value->isPrimitiveValue() ? static_cast<CSSPrimitiveValue*>(value) : 0;
3024 float zoomFactor = m_style->effectiveZoom();
3026 // What follows is a list that maps the CSS properties into their corresponding front-end
3027 // RenderStyle values. Shorthands (e.g. border, background) occur in this list as well and
3028 // are only hit when mapping "inherit" or "initial" into front-end values.
3031 case CSSPropertyContent:
3032 // list of string, uri, counter, attr, i
3034 // FIXME: In CSS3, it will be possible to inherit content. In CSS2 it is not. This
3035 // note is a reminder that eventually "inherit" needs to be supported.
3038 m_style->clearContent();
3042 if (!value->isValueList())
3045 bool didSet = false;
3046 for (CSSValueListIterator i = value; i.hasMore(); i.advance()) {
3047 CSSValue* item = i.value();
3048 if (item->isImageGeneratorValue()) {
3049 m_style->setContent(StyleGeneratedImage::create(static_cast<CSSImageGeneratorValue*>(item)), didSet);
3051 #if ENABLE(CSS_IMAGE_SET)
3052 } else if (item->isImageSetValue()) {
3053 m_style->setContent(setOrPendingFromValue(CSSPropertyContent, static_cast<CSSImageSetValue*>(item)), didSet);
3058 if (item->isImageValue()) {
3059 m_style->setContent(cachedOrPendingFromValue(CSSPropertyContent, static_cast<CSSImageValue*>(item)), didSet);
3064 if (!item->isPrimitiveValue())
3067 CSSPrimitiveValue* contentValue = static_cast<CSSPrimitiveValue*>(item);
3069 if (contentValue->isString()) {
3070 m_style->setContent(contentValue->getStringValue().impl(), didSet);
3072 } else if (contentValue->isAttr()) {
3073 // FIXME: Can a namespace be specified for an attr(foo)?
3074 if (m_style->styleType() == NOPSEUDO)
3075 m_style->setUnique();
3077 m_parentStyle->setUnique();
3078 QualifiedName attr(nullAtom, contentValue->getStringValue().impl(), nullAtom);
3079 const AtomicString& value = m_element->getAttribute(attr);
3080 m_style->setContent(value.isNull() ? emptyAtom : value.impl(), didSet);
3082 // register the fact that the attribute value affects the style
3083 m_features.attrsInRules.add(attr.localName().impl());
3084 } else if (contentValue->isCounter()) {
3085 Counter* counterValue = contentValue->getCounterValue();
3086 EListStyleType listStyleType = NoneListStyle;
3087 int listStyleIdent = counterValue->listStyleIdent();
3088 if (listStyleIdent != CSSValueNone)
3089 listStyleType = static_cast<EListStyleType>(listStyleIdent - CSSValueDisc);
3090 OwnPtr<CounterContent> counter = adoptPtr(new CounterContent(counterValue->identifier(), listStyleType, counterValue->separator()));
3091 m_style->setContent(counter.release(), didSet);
3094 switch (contentValue->getIdent()) {
3095 case CSSValueOpenQuote:
3096 m_style->setContent(OPEN_QUOTE, didSet);
3099 case CSSValueCloseQuote:
3100 m_style->setContent(CLOSE_QUOTE, didSet);
3103 case CSSValueNoOpenQuote:
3104 m_style->setContent(NO_OPEN_QUOTE, didSet);
3107 case CSSValueNoCloseQuote:
3108 m_style->setContent(NO_CLOSE_QUOTE, didSet);
3112 // normal and none do not have any effect.
3118 m_style->clearContent();
3121 case CSSPropertyQuotes:
3124 m_style->setQuotes(m_parentStyle->quotes());
3128 m_style->setQuotes(0);
3131 if (value->isValueList()) {
3132 CSSValueList* list = static_cast<CSSValueList*>(value);
3133 QuotesData* data = QuotesData::create(list->length());
3135 return; // Out of memory
3136 String* quotes = data->data();
3137 for (CSSValueListIterator i = list; i.hasMore(); i.advance()) {
3138 CSSValue* item = i.value();
3139 ASSERT(item->isPrimitiveValue());
3140 primitiveValue = static_cast<CSSPrimitiveValue*>(item);
3141 ASSERT(primitiveValue->isString());
3142 quotes[i.index()] = primitiveValue->getStringValue();
3144 m_style->setQuotes(adoptRef(data));
3145 } else if (primitiveValue) {
3146 ASSERT(primitiveValue->isIdent());
3147 if (primitiveValue->getIdent() == CSSValueNone)
3148 m_style->setQuotes(adoptRef(QuotesData::create(0)));
3151 case CSSPropertyFontFamily: {
3152 // list of strings and ids
3154 FontDescription parentFontDescription = m_parentStyle->fontDescription();
3155 FontDescription fontDescription = m_style->fontDescription();
3156 fontDescription.setGenericFamily(parentFontDescription.genericFamily());
3157 fontDescription.setFamily(parentFontDescription.firstFamily());
3158 fontDescription.setIsSpecifiedFont(parentFontDescription.isSpecifiedFont());
3159 setFontDescription(fontDescription);
3161 } else if (isInitial) {
3162 FontDescription initialDesc = FontDescription();
3163 FontDescription fontDescription = m_style->fontDescription();
3164 // We need to adjust the size to account for the generic family change from monospace
3165 // to non-monospace.
3166 if (fontDescription.keywordSize() && fontDescription.useFixedDefaultSize())
3167 setFontSize(fontDescription, fontSizeForKeyword(m_checker.document(), CSSValueXxSmall + fontDescription.keywordSize() - 1, false));
3168 fontDescription.setGenericFamily(initialDesc.genericFamily());
3169 if (!initialDesc.firstFamily().familyIsEmpty())
3170 fontDescription.setFamily(initialDesc.firstFamily());
3171 setFontDescription(fontDescription);
3175 if (!value->isValueList())
3177 FontDescription fontDescription = m_style->fontDescription();
3178 FontFamily& firstFamily = fontDescription.firstFamily();
3179 FontFamily* currFamily = 0;
3181 // Before mapping in a new font-family property, we should reset the generic family.
3182 bool oldFamilyUsedFixedDefaultSize = fontDescription.useFixedDefaultSize();
3183 fontDescription.setGenericFamily(FontDescription::NoFamily);
3185 for (CSSValueListIterator i = value; i.hasMore(); i.advance()) {
3186 CSSValue* item = i.value();
3187 if (!item->isPrimitiveValue())
3189 CSSPrimitiveValue* contentValue = static_cast<CSSPrimitiveValue*>(item);
3191 Settings* settings = m_checker.document()->settings();
3192 if (contentValue->isString())
3193 face = contentValue->getStringValue();
3194 else if (settings) {
3195 switch (contentValue->getIdent()) {
3196 case CSSValueWebkitBody:
3197 face = settings->standardFontFamily();
3201 fontDescription.setGenericFamily(FontDescription::SerifFamily);
3203 case CSSValueSansSerif:
3204 face = sansSerifFamily;
3205 fontDescription.setGenericFamily(FontDescription::SansSerifFamily);
3207 case CSSValueCursive:
3208 face = cursiveFamily;
3209 fontDescription.setGenericFamily(FontDescription::CursiveFamily);
3211 case CSSValueFantasy:
3212 face = fantasyFamily;
3213 fontDescription.setGenericFamily(FontDescription::FantasyFamily);
3215 case CSSValueMonospace:
3216 face = monospaceFamily;
3217 fontDescription.setGenericFamily(FontDescription::MonospaceFamily);
3219 case CSSValueWebkitPictograph:
3220 face = pictographFamily;
3221 fontDescription.setGenericFamily(FontDescription::PictographFamily);
3226 if (!face.isEmpty()) {
3228 // Filling in the first family.
3229 firstFamily.setFamily(face);
3230 firstFamily.appendFamily(0); // Remove any inherited family-fallback list.
3231 currFamily = &firstFamily;
3232 fontDescription.setIsSpecifiedFont(fontDescription.genericFamily() == FontDescription::NoFamily);
3234 RefPtr<SharedFontFamily> newFamily = SharedFontFamily::create();
3235 newFamily->setFamily(face);
3236 currFamily->appendFamily(newFamily);
3237 currFamily = newFamily.get();
3242 // We can't call useFixedDefaultSize() until all new font families have been added
3243 // If currFamily is non-zero then we set at least one family on this description.
3245 if (fontDescription.keywordSize() && fontDescription.useFixedDefaultSize() != oldFamilyUsedFixedDefaultSize)
3246 setFontSize(fontDescription, fontSizeForKeyword(m_checker.document(), CSSValueXxSmall + fontDescription.keywordSize() - 1, !oldFamilyUsedFixedDefaultSize));
3248 setFontDescription(fontDescription);
3252 // shorthand properties
3253 case CSSPropertyBackground:
3255 m_style->clearBackgroundLayers();
3256 m_style->setBackgroundColor(Color());
3258 else if (isInherit) {
3259 m_style->inheritBackgroundLayers(*m_parentStyle->backgroundLayers());
3260 m_style->setBackgroundColor(m_parentStyle->backgroundColor());
3263 case CSSPropertyWebkitMask:
3265 m_style->clearMaskLayers();
3267 m_style->inheritMaskLayers(*m_parentStyle->maskLayers());
3269 case CSSPropertyFont:
3271 FontDescription fontDescription = m_parentStyle->fontDescription();
3272 m_style->setLineHeight(m_parentStyle->lineHeight());
3273 m_lineHeightValue = 0;
3274 setFontDescription(fontDescription);
3275 } else if (isInitial) {
3276 Settings* settings = m_checker.document()->settings();
3277 ASSERT(settings); // If we're doing style resolution, this document should always be in a frame and thus have settings
3280 FontDescription fontDescription;
3281 fontDescription.setGenericFamily(FontDescription::StandardFamily);
3282 fontDescription.setRenderingMode(settings->fontRenderingMode());
3283 fontDescription.setUsePrinterFont(m_checker.document()->printing());
3284 const AtomicString& standardFontFamily = m_checker.document()->settings()->standardFontFamily();
3285 if (!standardFontFamily.isEmpty()) {
3286 fontDescription.firstFamily().setFamily(standardFontFamily);
3287 fontDescription.firstFamily().appendFamily(0);
3289 fontDescription.setKeywordSize(CSSValueMedium - CSSValueXxSmall + 1);
3290 setFontSize(fontDescription, fontSizeForKeyword(m_checker.document(), CSSValueMedium, false));
3291 m_style->setLineHeight(RenderStyle::initialLineHeight());
3292 m_lineHeightValue = 0;
3293 setFontDescription(fontDescription);
3294 } else if (primitiveValue) {
3295 m_style->setLineHeight(RenderStyle::initialLineHeight());
3296 m_lineHeightValue = 0;
3298 FontDescription fontDescription;
3299 RenderTheme::defaultTheme()->systemFont(primitiveValue->getIdent(), fontDescription);
3301 // Double-check and see if the theme did anything. If not, don't bother updating the font.
3302 if (fontDescription.isAbsoluteSize()) {
3303 // Make sure the rendering mode and printer font settings are updated.
3304 Settings* settings = m_checker.document()->settings();
3305 ASSERT(settings); // If we're doing style resolution, this document should always be in a frame and thus have settings
3308 fontDescription.setRenderingMode(settings->fontRenderingMode());
3309 fontDescription.setUsePrinterFont(m_checker.document()->printing());
3311 // Handle the zoom factor.
3312 fontDescription.setComputedSize(getComputedSizeFromSpecifiedSize(m_checker.document(), m_style.get(), fontDescription.isAbsoluteSize(), fontDescription.specifiedSize(), useSVGZoomRules()));
3313 setFontDescription(fontDescription);
3315 } else if (value->isFontValue()) {
3316 FontValue *font = static_cast<FontValue*>(value);
3317 if (!font->style || !font->variant || !font->weight ||
3318 !font->size || !font->lineHeight || !font->family)
3320 applyProperty(CSSPropertyFontStyle, font->style.get());
3321 applyProperty(CSSPropertyFontVariant, font->variant.get());
3322 applyProperty(CSSPropertyFontWeight, font->weight.get());
3323 // The previous properties can dirty our font but they don't try to read the font's
3324 // properties back, which is safe. However if font-size is using the 'ex' unit, it will
3325 // need query the dirtied font's x-height to get the computed size. To be safe in this
3326 // case, let's just update the font now.
3328 applyProperty(CSSPropertyFontSize, font->size.get());
3330 m_lineHeightValue = font->lineHeight.get();
3332 applyProperty(CSSPropertyFontFamily, font->family.get());
3337 case CSSPropertyTextShadow:
3338 case CSSPropertyBoxShadow:
3339 case CSSPropertyWebkitBoxShadow: {
3341 if (id == CSSPropertyTextShadow)
3342 return m_style->setTextShadow(m_parentStyle->textShadow() ? adoptPtr(new ShadowData(*m_parentStyle->textShadow())) : nullptr);
3343 return m_style->setBoxShadow(m_parentStyle->boxShadow() ? adoptPtr(new ShadowData(*m_parentStyle->boxShadow())) : nullptr);
3345 if (isInitial || primitiveValue) // initial | none
3346 return id == CSSPropertyTextShadow ? m_style->setTextShadow(nullptr) : m_style->setBoxShadow(nullptr);
3348 if (!value->isValueList())
3351 for (CSSValueListIterator i = value; i.hasMore(); i.advance()) {
3352 CSSValue* currValue = i.value();