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 "HTMLProgressElement.h"
69 #include "HTMLStyleElement.h"
70 #include "HTMLTextAreaElement.h"
71 #include "InspectorInstrumentation.h"
72 #include "KeyframeList.h"
74 #include "LocaleToScriptMapping.h"
75 #include "Matrix3DTransformOperation.h"
76 #include "MatrixTransformOperation.h"
77 #include "MediaList.h"
78 #include "MediaQueryEvaluator.h"
79 #include "NodeRenderStyle.h"
81 #include "PageGroup.h"
83 #include "PerspectiveTransformOperation.h"
84 #include "QuotesData.h"
86 #include "RenderRegion.h"
87 #include "RenderScrollbar.h"
88 #include "RenderScrollbarTheme.h"
89 #include "RenderStyleConstants.h"
90 #include "RenderTheme.h"
91 #include "RotateTransformOperation.h"
92 #include "RuntimeEnabledFeatures.h"
93 #include "ScaleTransformOperation.h"
94 #include "SecurityOrigin.h"
96 #include "ShadowData.h"
97 #include "ShadowRoot.h"
98 #include "ShadowValue.h"
99 #include "SkewTransformOperation.h"
100 #include "StyleCachedImage.h"
101 #include "StylePendingImage.h"
102 #include "StyleRule.h"
103 #include "StyleGeneratedImage.h"
104 #include "StyleSheetList.h"
106 #include "TransformationMatrix.h"
107 #include "TranslateTransformOperation.h"
108 #include "UserAgentStyleSheets.h"
109 #include "WebKitCSSKeyframeRule.h"
110 #include "WebKitCSSKeyframesRule.h"
111 #include "WebKitCSSRegionRule.h"
112 #include "WebKitCSSTransformValue.h"
113 #include "WebKitFontFamilyNames.h"
114 #include "XMLNames.h"
115 #include <wtf/StdLibExtras.h>
116 #include <wtf/Vector.h>
118 #if ENABLE(CSS_FILTERS)
119 #include "FilterOperation.h"
120 #include "WebKitCSSFilterValue.h"
123 #if ENABLE(DASHBOARD_SUPPORT)
124 #include "DashboardRegion.h"
128 #include "SVGElement.h"
129 #include "SVGNames.h"
132 #if ENABLE(CSS_SHADERS)
133 #include "CustomFilterNumberParameter.h"
134 #include "CustomFilterOperation.h"
135 #include "CustomFilterParameter.h"
136 #include "StyleCachedShader.h"
137 #include "StyleCustomFilterProgram.h"
138 #include "StylePendingShader.h"
139 #include "StyleShader.h"
140 #include "WebKitCSSShaderValue.h"
147 using namespace HTMLNames;
149 #define HANDLE_INHERIT(prop, Prop) \
151 m_style->set##Prop(m_parentStyle->prop()); \
155 #define HANDLE_INHERIT_AND_INITIAL(prop, Prop) \
156 HANDLE_INHERIT(prop, Prop) \
158 m_style->set##Prop(RenderStyle::initial##Prop()); \
162 #define HANDLE_INHERIT_AND_INITIAL_WITH_VALUE(prop, Prop, Value) \
163 HANDLE_INHERIT(prop, Prop) \
165 m_style->set##Prop(RenderStyle::initial##Value());\
169 #define HANDLE_INHERIT_AND_INITIAL_AND_PRIMITIVE(prop, Prop) \
170 HANDLE_INHERIT_AND_INITIAL(prop, Prop) \
171 if (primitiveValue) \
172 m_style->set##Prop(*primitiveValue);
176 RuleData(StyleRule*, CSSSelector*, unsigned position, bool canUseFastCheckSelector, bool inRegionRule);
178 unsigned position() const { return m_position; }
179 StyleRule* rule() const { return m_rule; }
180 CSSSelector* selector() const { return m_selector; }
182 bool hasFastCheckableSelector() const { return m_hasFastCheckableSelector; }
183 bool hasMultipartSelector() const { return m_hasMultipartSelector; }
184 bool hasRightmostSelectorMatchingHTMLBasedOnRuleHash() const { return m_hasRightmostSelectorMatchingHTMLBasedOnRuleHash; }
185 bool containsUncommonAttributeSelector() const { return m_containsUncommonAttributeSelector; }
186 unsigned specificity() const { return m_specificity; }
187 unsigned linkMatchType() const { return m_linkMatchType; }
188 bool isInRegionRule() const { return m_isInRegionRule; }
190 // Try to balance between memory usage (there can be lots of RuleData objects) and good filtering performance.
191 static const unsigned maximumIdentifierCount = 4;
192 const unsigned* descendantSelectorIdentifierHashes() const { return m_descendantSelectorIdentifierHashes; }
196 CSSSelector* m_selector;
197 unsigned m_specificity;
198 // This number was picked fairly arbitrarily. We can probably lower it if we need to.
199 // Some simple testing showed <100,000 RuleData's on large sites.
200 unsigned m_position : 25;
201 unsigned m_hasFastCheckableSelector : 1;
202 unsigned m_hasMultipartSelector : 1;
203 unsigned m_hasRightmostSelectorMatchingHTMLBasedOnRuleHash : 1;
204 unsigned m_containsUncommonAttributeSelector : 1;
205 unsigned m_linkMatchType : 2; // SelectorChecker::LinkMatchMask
206 unsigned m_isInRegionRule : 1;
207 // Use plain array instead of a Vector to minimize memory overhead.
208 unsigned m_descendantSelectorIdentifierHashes[maximumIdentifierCount];
211 struct SameSizeAsRuleData {
219 COMPILE_ASSERT(sizeof(RuleData) == sizeof(SameSizeAsRuleData), RuleData_should_stay_small);
222 WTF_MAKE_NONCOPYABLE(RuleSet);
226 typedef HashMap<AtomicStringImpl*, OwnPtr<Vector<RuleData> > > AtomRuleMap;
228 void addRulesFromSheet(CSSStyleSheet*, const MediaQueryEvaluator&, CSSStyleSelector* = 0, const ContainerNode* = 0);
230 void addStyleRule(StyleRule*, bool canUseFastCheckSelector = true, bool isInRegionRule = false);
231 void addRule(StyleRule*, CSSSelector*, bool canUseFastCheckSelector = true, bool isInRegionRule = false);
232 void addPageRule(CSSPageRule*);
233 void addToRuleSet(AtomicStringImpl* key, AtomRuleMap&, const RuleData&);
234 void addRegionRule(WebKitCSSRegionRule*);
236 void disableAutoShrinkToFit() { m_autoShrinkToFitEnabled = false; }
238 const CSSStyleSelector::Features& features() const { return m_features; }
240 const Vector<RuleData>* idRules(AtomicStringImpl* key) const { return m_idRules.get(key); }
241 const Vector<RuleData>* classRules(AtomicStringImpl* key) const { return m_classRules.get(key); }
242 const Vector<RuleData>* tagRules(AtomicStringImpl* key) const { return m_tagRules.get(key); }
243 const Vector<RuleData>* shadowPseudoElementRules(AtomicStringImpl* key) const { return m_shadowPseudoElementRules.get(key); }
244 const Vector<RuleData>* linkPseudoClassRules() const { return &m_linkPseudoClassRules; }
245 const Vector<RuleData>* focusPseudoClassRules() const { return &m_focusPseudoClassRules; }
246 const Vector<RuleData>* universalRules() const { return &m_universalRules; }
247 const Vector<CSSPageRule*>& pageRules() const { return m_pageRules; }
250 AtomRuleMap m_idRules;
251 AtomRuleMap m_classRules;
252 AtomRuleMap m_tagRules;
253 AtomRuleMap m_shadowPseudoElementRules;
254 Vector<RuleData> m_linkPseudoClassRules;
255 Vector<RuleData> m_focusPseudoClassRules;
256 Vector<RuleData> m_universalRules;
257 Vector<CSSPageRule*> m_pageRules;
258 unsigned m_ruleCount;
259 bool m_autoShrinkToFitEnabled;
260 CSSStyleSelector::Features m_features;
262 struct RuleSetSelectorPair {
263 RuleSetSelectorPair(CSSSelector* selector, RuleSet* ruleSet) : selector(selector), ruleSet(adoptPtr(ruleSet)) { }
264 RuleSetSelectorPair(const RuleSetSelectorPair& rs) : selector(rs.selector), ruleSet(const_cast<RuleSetSelectorPair*>(&rs)->ruleSet.release()) { }
265 CSSSelector* selector;
266 OwnPtr<RuleSet> ruleSet;
269 Vector<RuleSetSelectorPair> m_regionSelectorsAndRuleSets;
272 static RuleSet* defaultStyle;
273 static RuleSet* defaultQuirksStyle;
274 static RuleSet* defaultPrintStyle;
275 static RuleSet* defaultViewSourceStyle;
276 static CSSStyleSheet* simpleDefaultStyleSheet;
278 RenderStyle* CSSStyleSelector::s_styleNotYetAvailable;
280 static void loadFullDefaultStyle();
281 static void loadSimpleDefaultStyle();
282 // FIXME: It would be nice to use some mechanism that guarantees this is in sync with the real UA stylesheet.
283 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}";
285 static inline bool elementCanUseSimpleDefaultStyle(Element* e)
287 return e->hasTagName(htmlTag) || e->hasTagName(headTag) || e->hasTagName(bodyTag) || e->hasTagName(divTag) || e->hasTagName(spanTag) || e->hasTagName(brTag) || e->hasTagName(aTag);
290 static const MediaQueryEvaluator& screenEval()
292 DEFINE_STATIC_LOCAL(const MediaQueryEvaluator, staticScreenEval, ("screen"));
293 return staticScreenEval;
296 static const MediaQueryEvaluator& printEval()
298 DEFINE_STATIC_LOCAL(const MediaQueryEvaluator, staticPrintEval, ("print"));
299 return staticPrintEval;
302 static StylePropertySet* leftToRightDeclaration()
304 DEFINE_STATIC_LOCAL(RefPtr<StylePropertySet>, leftToRightDecl, (StylePropertySet::create()));
305 if (leftToRightDecl->isEmpty())
306 leftToRightDecl->setProperty(CSSPropertyDirection, CSSValueLtr);
307 return leftToRightDecl.get();
310 static StylePropertySet* rightToLeftDeclaration()
312 DEFINE_STATIC_LOCAL(RefPtr<StylePropertySet>, rightToLeftDecl, (StylePropertySet::create()));
313 if (rightToLeftDecl->isEmpty())
314 rightToLeftDecl->setProperty(CSSPropertyDirection, CSSValueRtl);
315 return rightToLeftDecl.get();
318 CSSStyleSelector::CSSStyleSelector(Document* document, StyleSheetList* styleSheets, CSSStyleSheet* mappedElementSheet,
319 CSSStyleSheet* pageUserSheet, const Vector<RefPtr<CSSStyleSheet> >* pageGroupUserSheets, const Vector<RefPtr<CSSStyleSheet> >* documentUserSheets,
320 bool strictParsing, bool matchAuthorAndUserStyles)
321 : m_hasUAAppearance(false)
322 , m_backgroundData(BackgroundFillLayer)
323 , m_matchedPropertiesCacheAdditionsSinceLastSweep(0)
324 , m_checker(document, strictParsing)
326 , m_rootElementStyle(0)
329 , m_regionForStyling(0)
330 , m_elementLinkState(NotInsideLink)
332 , m_lineHeightValue(0)
334 , m_matchAuthorAndUserStyles(matchAuthorAndUserStyles)
335 , m_sameOriginOnly(false)
336 , m_fontSelector(CSSFontSelector::create(document))
337 , m_applyPropertyToRegularStyle(true)
338 , m_applyPropertyToVisitedLinkStyle(false)
339 , m_applyProperty(CSSStyleApplyProperty::sharedCSSStyleApplyProperty())
340 #if ENABLE(CSS_SHADERS)
341 , m_hasPendingShaders(false)
343 #if ENABLE(STYLE_SCOPED)
344 , m_scopeStackParent(0)
347 Element* root = document->documentElement();
350 if (!root || elementCanUseSimpleDefaultStyle(root))
351 loadSimpleDefaultStyle();
353 loadFullDefaultStyle();
357 // construct document root element default style. this is needed
358 // to evaluate media queries that contain relative constraints, like "screen and (max-width: 10em)"
359 // This is here instead of constructor, because when constructor is run,
360 // document doesn't have documentElement
361 // NOTE: this assumes that element that gets passed to styleForElement -call
362 // is always from the document that owns the style selector
363 FrameView* view = document->view();
365 m_medium = adoptPtr(new MediaQueryEvaluator(view->mediaType()));
367 m_medium = adoptPtr(new MediaQueryEvaluator("all"));
370 m_rootDefaultStyle = styleForElement(root, 0, false, true); // don't ref, because the RenderStyle is allocated from global heap
372 if (m_rootDefaultStyle && view)
373 m_medium = adoptPtr(new MediaQueryEvaluator(view->mediaType(), view->frame(), m_rootDefaultStyle.get()));
375 m_authorStyle = adoptPtr(new RuleSet);
376 // Adding rules from multiple sheets, shrink at the end.
377 // Adding global rules from multiple sheets, shrink at the end.
378 // Note that there usually is only 1 sheet for scoped rules, so auto-shrink-to-fit is fine.
379 m_authorStyle->disableAutoShrinkToFit();
381 // FIXME: This sucks! The user sheet is reparsed every time!
382 OwnPtr<RuleSet> tempUserStyle = adoptPtr(new RuleSet);
384 tempUserStyle->addRulesFromSheet(pageUserSheet, *m_medium, this);
385 if (pageGroupUserSheets) {
386 unsigned length = pageGroupUserSheets->size();
387 for (unsigned i = 0; i < length; i++) {
388 if (pageGroupUserSheets->at(i)->isUserStyleSheet())
389 tempUserStyle->addRulesFromSheet(pageGroupUserSheets->at(i).get(), *m_medium, this);
391 m_authorStyle->addRulesFromSheet(pageGroupUserSheets->at(i).get(), *m_medium, this);
394 if (documentUserSheets) {
395 unsigned length = documentUserSheets->size();
396 for (unsigned i = 0; i < length; i++) {
397 if (documentUserSheets->at(i)->isUserStyleSheet())
398 tempUserStyle->addRulesFromSheet(documentUserSheets->at(i).get(), *m_medium, this);
400 m_authorStyle->addRulesFromSheet(documentUserSheets->at(i).get(), *m_medium, this);
404 if (tempUserStyle->m_ruleCount > 0 || tempUserStyle->m_pageRules.size() > 0)
405 m_userStyle = tempUserStyle.release();
407 // Add rules from elements like SVG's <font-face>
408 if (mappedElementSheet) {
409 // FIXME: see if style scopes can/should be added here.
410 m_authorStyle->addRulesFromSheet(mappedElementSheet, *m_medium, this);
413 // add stylesheets from document
414 appendAuthorStylesheets(0, styleSheets->vector());
417 static PassOwnPtr<RuleSet> makeRuleSet(const Vector<CSSStyleSelector::RuleSelectorPair>& rules)
419 size_t size = rules.size();
422 OwnPtr<RuleSet> ruleSet = adoptPtr(new RuleSet);
423 for (size_t i = 0; i < size; ++i)
424 ruleSet->addRule(rules[i].rule, rules[i].selector);
425 return ruleSet.release();
428 void CSSStyleSelector::collectFeatures()
431 // Collect all ids and rules using sibling selectors (:first-child and similar)
432 // in the current set of stylesheets. Style sharing code uses this information to reject
433 // sharing candidates.
434 m_features.add(defaultStyle->features());
435 m_features.add(m_authorStyle->features());
436 #if ENABLE(STYLE_SCOPED)
437 for (ScopedRuleSetMap::iterator it = m_scopedAuthorStyles.begin(); it != m_scopedAuthorStyles.end(); ++it)
438 m_features.add(it->second->features());
441 m_features.add(m_userStyle->features());
443 m_siblingRuleSet = makeRuleSet(m_features.siblingRules);
444 m_uncommonAttributeRuleSet = makeRuleSet(m_features.uncommonAttributeRules);
447 #if ENABLE(STYLE_SCOPED)
448 const ContainerNode* CSSStyleSelector::determineScope(const CSSStyleSheet* sheet)
452 if (!RuntimeEnabledFeatures::styleScopedEnabled())
455 Node* ownerNode = sheet->findStyleSheetOwnerNode();
456 if (!ownerNode || !ownerNode->isHTMLElement() || !ownerNode->hasTagName(HTMLNames::styleTag))
459 HTMLStyleElement* styleElement = static_cast<HTMLStyleElement*>(ownerNode);
460 if (!styleElement->scoped())
463 ContainerNode* parent = styleElement->parentNode();
467 return (parent->isElementNode() || parent->isShadowRoot()) ? parent : 0;
470 inline RuleSet* CSSStyleSelector::ruleSetForScope(const ContainerNode* scope) const
472 if (!scope->hasScopedHTMLStyleChild())
474 ScopedRuleSetMap::const_iterator it = m_scopedAuthorStyles.find(scope);
475 return it != m_scopedAuthorStyles.end() ? it->second.get() : 0;
479 void CSSStyleSelector::appendAuthorStylesheets(unsigned firstNew, const Vector<RefPtr<StyleSheet> >& stylesheets)
481 // This handles sheets added to the end of the stylesheet list only. In other cases the style resolver
482 // needs to be reconstructed. To handle insertions too the rule order numbers would need to be updated.
483 unsigned size = stylesheets.size();
484 for (unsigned i = firstNew; i < size; ++i) {
485 if (!stylesheets[i]->isCSSStyleSheet() || stylesheets[i]->disabled())
487 CSSStyleSheet* cssSheet = static_cast<CSSStyleSheet*>(stylesheets[i].get());
488 #if ENABLE(STYLE_SCOPED)
489 const ContainerNode* scope = determineScope(cssSheet);
491 pair<ScopedRuleSetMap::iterator, bool> addResult = m_scopedAuthorStyles.add(scope, nullptr);
492 if (addResult.second)
493 addResult.first->second = adoptPtr(new RuleSet());
494 addResult.first->second->addRulesFromSheet(cssSheet, *m_medium, this, scope);
498 m_authorStyle->addRulesFromSheet(cssSheet, *m_medium, this);
500 m_authorStyle->shrinkToFit();
503 if (document()->renderer() && document()->renderer()->style())
504 document()->renderer()->style()->font().update(fontSelector());
507 #if ENABLE(STYLE_SCOPED)
508 void CSSStyleSelector::setupScopeStack(const ContainerNode* parent)
510 // The scoping element stack shouldn't be used if <style scoped> isn't used anywhere.
511 ASSERT(!m_scopedAuthorStyles.isEmpty());
513 m_scopeStack.shrink(0);
514 for (; parent; parent = parent->parentOrHostNode()) {
515 RuleSet* ruleSet = ruleSetForScope(parent);
517 m_scopeStack.append(ScopeStackFrame(parent, ruleSet));
519 m_scopeStack.reverse();
520 m_scopeStackParent = parent;
523 void CSSStyleSelector::pushScope(const ContainerNode* scope, const ContainerNode* scopeParent)
525 // Shortcut: Don't bother with the scoping element stack if <style scoped> isn't used anywhere.
526 if (m_scopedAuthorStyles.isEmpty()) {
527 ASSERT(!m_scopeStackParent);
528 ASSERT(m_scopeStack.isEmpty());
531 // In some wacky cases during style resolve we may get invoked for random elements.
532 // Recreate the whole scoping element stack in such cases.
533 if (!scopeStackIsConsistent(scopeParent)) {
534 setupScopeStack(scope);
537 // Otherwise just push the parent onto the stack.
538 RuleSet* ruleSet = ruleSetForScope(scope);
540 m_scopeStack.append(ScopeStackFrame(scope, ruleSet));
541 m_scopeStackParent = scope;
544 void CSSStyleSelector::popScope(const ContainerNode* scope)
546 // Only bother to update the scoping element stack if it is consistent.
547 if (scopeStackIsConsistent(scope)) {
548 m_scopeStack.removeLast();
549 m_scopeStackParent = scope->parentOrHostNode();
554 void CSSStyleSelector::pushParentElement(Element* parent)
556 const ContainerNode* parentsParent = parent->parentOrHostElement();
558 // We are not always invoked consistently. For example, script execution can cause us to enter
559 // style recalc in the middle of tree building. We may also be invoked from somewhere within the tree.
560 // Reset the stack in this case, or if we see a new root element.
561 // Otherwise just push the new parent.
562 if (!parentsParent || m_checker.parentStackIsEmpty())
563 m_checker.setupParentStack(parent);
565 m_checker.pushParent(parent);
567 // Note: We mustn't skip ShadowRoot nodes for the scope stack.
568 pushScope(parent, parent->parentOrHostNode());
571 void CSSStyleSelector::popParentElement(Element* parent)
573 // Note that we may get invoked for some random elements in some wacky cases during style resolve.
574 // Pause maintaining the stack in this case.
575 if (m_checker.parentStackIsConsistent(parent))
576 m_checker.popParent();
580 void CSSStyleSelector::pushParentShadowRoot(const ShadowRoot* shadowRoot)
582 ASSERT(shadowRoot->host());
583 pushScope(shadowRoot, shadowRoot->host());
586 void CSSStyleSelector::popParentShadowRoot(const ShadowRoot* shadowRoot)
588 ASSERT(shadowRoot->host());
589 popScope(shadowRoot);
592 // This is a simplified style setting function for keyframe styles
593 void CSSStyleSelector::addKeyframeStyle(PassRefPtr<WebKitCSSKeyframesRule> rule)
595 AtomicString s(rule->name());
596 m_keyframesRuleMap.set(s.impl(), rule);
599 CSSStyleSelector::~CSSStyleSelector()
601 m_fontSelector->clearDocument();
604 void CSSStyleSelector::sweepMatchedPropertiesCache()
606 // Look for cache entries containing a style declaration with a single ref and remove them.
607 // This may happen when an element attribute mutation causes it to swap out its Attribute::decl()
608 // for another CSSMappedAttributeDeclaration, potentially leaving this cache with the last ref.
609 Vector<unsigned, 16> toRemove;
610 MatchedPropertiesCache::iterator it = m_matchedPropertiesCache.begin();
611 MatchedPropertiesCache::iterator end = m_matchedPropertiesCache.end();
612 for (; it != end; ++it) {
613 Vector<MatchedProperties>& matchedProperties = it->second.matchedProperties;
614 for (size_t i = 0; i < matchedProperties.size(); ++i) {
615 if (matchedProperties[i].properties->hasOneRef()) {
616 toRemove.append(it->first);
621 for (size_t i = 0; i < toRemove.size(); ++i)
622 m_matchedPropertiesCache.remove(toRemove[i]);
625 CSSStyleSelector::Features::Features()
626 : usesFirstLineRules(false)
627 , usesBeforeAfterRules(false)
628 , usesLinkRules(false)
632 CSSStyleSelector::Features::~Features()
636 void CSSStyleSelector::Features::add(const CSSStyleSelector::Features& other)
638 HashSet<AtomicStringImpl*>::iterator end = other.idsInRules.end();
639 for (HashSet<AtomicStringImpl*>::iterator it = other.idsInRules.begin(); it != end; ++it)
641 end = other.attrsInRules.end();
642 for (HashSet<AtomicStringImpl*>::iterator it = other.attrsInRules.begin(); it != end; ++it)
643 attrsInRules.add(*it);
644 siblingRules.append(other.siblingRules);
645 uncommonAttributeRules.append(other.uncommonAttributeRules);
646 usesFirstLineRules = usesFirstLineRules || other.usesFirstLineRules;
647 usesBeforeAfterRules = usesBeforeAfterRules || other.usesBeforeAfterRules;
648 usesLinkRules = usesLinkRules || other.usesLinkRules;
651 void CSSStyleSelector::Features::clear()
654 attrsInRules.clear();
655 siblingRules.clear();
656 uncommonAttributeRules.clear();
657 usesFirstLineRules = false;
658 usesBeforeAfterRules = false;
659 usesLinkRules = false;
662 static CSSStyleSheet* parseUASheet(const String& str)
664 CSSStyleSheet* sheet = CSSStyleSheet::create().leakRef(); // leak the sheet on purpose
665 sheet->parseString(str);
669 static CSSStyleSheet* parseUASheet(const char* characters, unsigned size)
671 return parseUASheet(String(characters, size));
674 static void loadFullDefaultStyle()
676 if (simpleDefaultStyleSheet) {
677 ASSERT(defaultStyle);
678 ASSERT(defaultPrintStyle == defaultStyle);
680 simpleDefaultStyleSheet->deref();
681 defaultStyle = new RuleSet;
682 defaultPrintStyle = new RuleSet;
683 simpleDefaultStyleSheet = 0;
685 ASSERT(!defaultStyle);
686 defaultStyle = new RuleSet;
687 defaultPrintStyle = new RuleSet;
688 defaultQuirksStyle = new RuleSet;
691 // Strict-mode rules.
692 String defaultRules = String(htmlUserAgentStyleSheet, sizeof(htmlUserAgentStyleSheet)) + RenderTheme::defaultTheme()->extraDefaultStyleSheet();
693 CSSStyleSheet* defaultSheet = parseUASheet(defaultRules);
694 defaultStyle->addRulesFromSheet(defaultSheet, screenEval());
695 defaultPrintStyle->addRulesFromSheet(defaultSheet, printEval());
697 // Quirks-mode rules.
698 String quirksRules = String(quirksUserAgentStyleSheet, sizeof(quirksUserAgentStyleSheet)) + RenderTheme::defaultTheme()->extraQuirksStyleSheet();
699 CSSStyleSheet* quirksSheet = parseUASheet(quirksRules);
700 defaultQuirksStyle->addRulesFromSheet(quirksSheet, screenEval());
703 static void loadSimpleDefaultStyle()
705 ASSERT(!defaultStyle);
706 ASSERT(!simpleDefaultStyleSheet);
708 defaultStyle = new RuleSet;
709 // There are no media-specific rules in the simple default style.
710 defaultPrintStyle = defaultStyle;
711 defaultQuirksStyle = new RuleSet;
713 simpleDefaultStyleSheet = parseUASheet(simpleUserAgentStyleSheet, strlen(simpleUserAgentStyleSheet));
714 defaultStyle->addRulesFromSheet(simpleDefaultStyleSheet, screenEval());
716 // No need to initialize quirks sheet yet as there are no quirk rules for elements allowed in simple default style.
719 static void loadViewSourceStyle()
721 ASSERT(!defaultViewSourceStyle);
722 defaultViewSourceStyle = new RuleSet;
723 defaultViewSourceStyle->addRulesFromSheet(parseUASheet(sourceUserAgentStyleSheet, sizeof(sourceUserAgentStyleSheet)), screenEval());
726 static void ensureDefaultStyleSheetsForElement(Element* element)
728 if (simpleDefaultStyleSheet && !elementCanUseSimpleDefaultStyle(element))
729 loadFullDefaultStyle();
732 static bool loadedSVGUserAgentSheet;
733 if (element->isSVGElement() && !loadedSVGUserAgentSheet) {
735 loadedSVGUserAgentSheet = true;
736 CSSStyleSheet* svgSheet = parseUASheet(svgUserAgentStyleSheet, sizeof(svgUserAgentStyleSheet));
737 defaultStyle->addRulesFromSheet(svgSheet, screenEval());
738 defaultPrintStyle->addRulesFromSheet(svgSheet, printEval());
742 static bool loadedMathMLUserAgentSheet;
744 if (element->isMathMLElement() && !loadedMathMLUserAgentSheet) {
746 loadedMathMLUserAgentSheet = true;
747 CSSStyleSheet* mathMLSheet = parseUASheet(mathmlUserAgentStyleSheet, sizeof(mathmlUserAgentStyleSheet));
748 defaultStyle->addRulesFromSheet(mathMLSheet, screenEval());
749 defaultPrintStyle->addRulesFromSheet(mathMLSheet, printEval());
754 static bool loadedMediaStyleSheet;
755 if (!loadedMediaStyleSheet && (element->hasTagName(videoTag) || element->hasTagName(audioTag))) {
756 loadedMediaStyleSheet = true;
757 String mediaRules = String(mediaControlsUserAgentStyleSheet, sizeof(mediaControlsUserAgentStyleSheet)) + RenderTheme::themeForPage(element->document()->page())->extraMediaControlsStyleSheet();
758 CSSStyleSheet* mediaControlsSheet = parseUASheet(mediaRules);
759 defaultStyle->addRulesFromSheet(mediaControlsSheet, screenEval());
760 defaultPrintStyle->addRulesFromSheet(mediaControlsSheet, printEval());
764 #if ENABLE(FULLSCREEN_API)
765 static bool loadedFullScreenStyleSheet;
766 if (!loadedFullScreenStyleSheet && element->document()->webkitIsFullScreen()) {
767 loadedFullScreenStyleSheet = true;
768 String fullscreenRules = String(fullscreenUserAgentStyleSheet, sizeof(fullscreenUserAgentStyleSheet)) + RenderTheme::defaultTheme()->extraFullScreenStyleSheet();
769 CSSStyleSheet* fullscreenSheet = parseUASheet(fullscreenRules);
770 defaultStyle->addRulesFromSheet(fullscreenSheet, screenEval());
771 defaultQuirksStyle->addRulesFromSheet(fullscreenSheet, screenEval());
775 ASSERT(defaultStyle->features().idsInRules.isEmpty());
776 ASSERT_UNUSED(loadedMathMLUserAgentSheet, loadedMathMLUserAgentSheet || defaultStyle->features().siblingRules.isEmpty());
779 void CSSStyleSelector::addMatchedProperties(MatchResult& matchResult, StylePropertySet* properties, StyleRule* rule, unsigned linkMatchType, bool inRegionRule)
781 matchResult.matchedProperties.grow(matchResult.matchedProperties.size() + 1);
782 MatchedProperties& newProperties = matchResult.matchedProperties.last();
783 newProperties.properties = properties;
784 newProperties.linkMatchType = linkMatchType;
785 newProperties.isInRegionRule = inRegionRule;
786 matchResult.matchedRules.append(rule);
789 inline void CSSStyleSelector::addElementStyleProperties(MatchResult& result, StylePropertySet* propertySet, bool isCacheable)
793 result.ranges.lastAuthorRule = result.matchedProperties.size();
794 if (result.ranges.firstAuthorRule == -1)
795 result.ranges.firstAuthorRule = result.ranges.lastAuthorRule;
796 addMatchedProperties(result, propertySet);
798 result.isCacheable = false;
801 void CSSStyleSelector::collectMatchingRules(RuleSet* rules, int& firstRuleIndex, int& lastRuleIndex, const MatchOptions& options)
806 // We need to collect the rules for id, class, tag, and everything else into a buffer and
807 // then sort the buffer.
808 if (m_element->hasID())
809 collectMatchingRulesForList(rules->idRules(m_element->idForStyleResolution().impl()), firstRuleIndex, lastRuleIndex, options);
810 if (m_element->hasClass()) {
811 ASSERT(m_styledElement);
812 const SpaceSplitString& classNames = m_styledElement->classNames();
813 size_t size = classNames.size();
814 for (size_t i = 0; i < size; ++i)
815 collectMatchingRulesForList(rules->classRules(classNames[i].impl()), firstRuleIndex, lastRuleIndex, options);
817 const AtomicString& pseudoId = m_element->shadowPseudoId();
818 if (!pseudoId.isEmpty()) {
819 ASSERT(m_styledElement);
820 collectMatchingRulesForList(rules->shadowPseudoElementRules(pseudoId.impl()), firstRuleIndex, lastRuleIndex, options);
822 if (m_element->isLink())
823 collectMatchingRulesForList(rules->linkPseudoClassRules(), firstRuleIndex, lastRuleIndex, options);
824 if (m_checker.matchesFocusPseudoClass(m_element))
825 collectMatchingRulesForList(rules->focusPseudoClassRules(), firstRuleIndex, lastRuleIndex, options);
826 collectMatchingRulesForList(rules->tagRules(m_element->localName().impl()), firstRuleIndex, lastRuleIndex, options);
827 collectMatchingRulesForList(rules->universalRules(), firstRuleIndex, lastRuleIndex, options);
830 void CSSStyleSelector::collectMatchingRulesForRegion(RuleSet* rules, int& firstRuleIndex, int& lastRuleIndex, const MatchOptions& options)
832 if (!m_regionForStyling)
835 unsigned size = rules->m_regionSelectorsAndRuleSets.size();
836 for (unsigned i = 0; i < size; ++i) {
837 CSSSelector* regionSelector = rules->m_regionSelectorsAndRuleSets.at(i).selector;
838 if (checkRegionSelector(regionSelector, static_cast<Element*>(m_regionForStyling->node()))) {
839 RuleSet* regionRules = rules->m_regionSelectorsAndRuleSets.at(i).ruleSet.get();
841 collectMatchingRules(regionRules, firstRuleIndex, lastRuleIndex, options);
846 void CSSStyleSelector::sortAndTransferMatchedRules(MatchResult& result)
848 if (m_matchedRules.isEmpty())
853 if (m_checker.isCollectingRulesOnly()) {
855 m_ruleList = CSSRuleList::create();
856 for (unsigned i = 0; i < m_matchedRules.size(); ++i)
857 m_ruleList->append(m_matchedRules[i]->rule()->ensureCSSStyleRule());
861 // Now transfer the set of matched rules over to our list of declarations.
862 // FIXME: This sucks, the inspector should get the style from the visited style itself.
863 bool swapVisitedUnvisited = InspectorInstrumentation::forcePseudoState(m_element, CSSSelector::PseudoVisited);
864 for (unsigned i = 0; i < m_matchedRules.size(); i++) {
865 if (m_style && m_matchedRules[i]->containsUncommonAttributeSelector())
866 m_style->setAffectedByUncommonAttributeSelectors();
867 unsigned linkMatchType = m_matchedRules[i]->linkMatchType();
868 if (swapVisitedUnvisited && linkMatchType && linkMatchType != SelectorChecker::MatchAll)
869 linkMatchType = (linkMatchType == SelectorChecker::MatchVisited) ? SelectorChecker::MatchLink : SelectorChecker::MatchVisited;
870 addMatchedProperties(result, m_matchedRules[i]->rule()->properties(), m_matchedRules[i]->rule(), linkMatchType, m_matchedRules[i]->isInRegionRule());
874 void CSSStyleSelector::matchScopedAuthorRules(MatchResult& result, bool includeEmptyRules)
876 #if ENABLE(STYLE_SCOPED)
877 if (m_scopedAuthorStyles.isEmpty())
880 MatchOptions options(includeEmptyRules);
882 // Match scoped author rules by traversing the scoped element stack (rebuild it if it got inconsistent).
883 const ContainerNode* parent = m_element->parentOrHostNode();
884 if (!scopeStackIsConsistent(parent))
885 setupScopeStack(parent);
886 for (size_t i = m_scopeStack.size(); i; --i) {
887 const ScopeStackFrame& frame = m_scopeStack[i - 1];
888 options.scope = frame.m_scope;
889 collectMatchingRules(frame.m_ruleSet, result.ranges.firstAuthorRule, result.ranges.lastAuthorRule, options);
890 collectMatchingRulesForRegion(frame.m_ruleSet, result.ranges.firstAuthorRule, result.ranges.lastAuthorRule, options);
892 // Also include the current element.
893 RuleSet* ruleSet = ruleSetForScope(m_element);
895 options.scope = m_element;
896 collectMatchingRules(ruleSet, result.ranges.firstAuthorRule, result.ranges.lastAuthorRule, options);
897 collectMatchingRulesForRegion(ruleSet, result.ranges.firstAuthorRule, result.ranges.lastAuthorRule, options);
900 UNUSED_PARAM(result);
901 UNUSED_PARAM(includeEmptyRules);
905 void CSSStyleSelector::matchAuthorRules(MatchResult& result, bool includeEmptyRules)
907 m_matchedRules.clear();
908 result.ranges.lastAuthorRule = result.matchedProperties.size() - 1;
913 // Match global author rules.
914 MatchOptions options(includeEmptyRules);
915 collectMatchingRules(m_authorStyle.get(), result.ranges.firstAuthorRule, result.ranges.lastAuthorRule, options);
916 collectMatchingRulesForRegion(m_authorStyle.get(), result.ranges.firstAuthorRule, result.ranges.lastAuthorRule, options);
918 matchScopedAuthorRules(result, includeEmptyRules);
920 sortAndTransferMatchedRules(result);
923 void CSSStyleSelector::matchUserRules(MatchResult& result, bool includeEmptyRules)
928 m_matchedRules.clear();
930 result.ranges.lastUserRule = result.matchedProperties.size() - 1;
931 collectMatchingRules(m_userStyle.get(), result.ranges.firstUserRule, result.ranges.lastUserRule, includeEmptyRules);
932 collectMatchingRulesForRegion(m_userStyle.get(), result.ranges.firstUserRule, result.ranges.lastUserRule, includeEmptyRules);
934 sortAndTransferMatchedRules(result);
937 void CSSStyleSelector::matchUARules(MatchResult& result, RuleSet* rules)
939 m_matchedRules.clear();
941 result.ranges.lastUARule = result.matchedProperties.size() - 1;
942 collectMatchingRules(rules, result.ranges.firstUARule, result.ranges.lastUARule, false);
944 sortAndTransferMatchedRules(result);
947 class MatchingUARulesScope {
949 MatchingUARulesScope();
950 ~MatchingUARulesScope();
952 static bool isMatchingUARules();
955 static bool m_matchingUARules;
958 MatchingUARulesScope::MatchingUARulesScope()
960 ASSERT(!m_matchingUARules);
961 m_matchingUARules = true;
964 MatchingUARulesScope::~MatchingUARulesScope()
966 m_matchingUARules = false;
969 inline bool MatchingUARulesScope::isMatchingUARules()
971 return m_matchingUARules;
974 bool MatchingUARulesScope::m_matchingUARules = false;
976 void CSSStyleSelector::collectMatchingRulesForList(const Vector<RuleData>* rules, int& firstRuleIndex, int& lastRuleIndex, const MatchOptions& options)
980 // In some cases we may end up looking up style for random elements in the middle of a recursive tree resolve.
981 // Ancestor identifier filter won't be up-to-date in that case and we can't use the fast path.
982 bool canUseFastReject = m_checker.parentStackIsConsistent(m_parentNode);
984 unsigned size = rules->size();
985 for (unsigned i = 0; i < size; ++i) {
986 const RuleData& ruleData = rules->at(i);
987 if (canUseFastReject && m_checker.fastRejectSelector<RuleData::maximumIdentifierCount>(ruleData.descendantSelectorIdentifierHashes()))
990 StyleRule* rule = ruleData.rule();
991 InspectorInstrumentationCookie cookie = InspectorInstrumentation::willMatchRule(document(), rule);
992 #if ENABLE(STYLE_SCOPED)
993 if (checkSelector(ruleData, options.scope)) {
995 if (checkSelector(ruleData)) {
997 // Check whether the rule is applicable in the current tree scope. Criteria for this:
999 // b) the tree scope allows author rules
1000 // c) the rules comes from a scoped style sheet within the same tree scope
1001 // d) the rule contains shadow-ID pseudo elements
1002 TreeScope* treeScope = m_element->treeScope();
1003 if (!MatchingUARulesScope::isMatchingUARules()
1004 && !treeScope->applyAuthorSheets()
1005 #if ENABLE(STYLE_SCOPED)
1006 && (!options.scope || options.scope->treeScope() != treeScope)
1008 && !m_checker.hasUnknownPseudoElements()) {
1010 InspectorInstrumentation::didMatchRule(cookie, false);
1013 // If the rule has no properties to apply, then ignore it in the non-debug mode.
1014 StylePropertySet* properties = rule->properties();
1015 if (!properties || (properties->isEmpty() && !options.includeEmptyRules)) {
1016 InspectorInstrumentation::didMatchRule(cookie, false);
1019 // FIXME: Exposing getMatchedCSSRules as a web facing API is forcing us to have a way to get the base URL per-rule.
1020 if (m_sameOriginOnly && !m_checker.document()->securityOrigin()->canRequest(rule->ensureCSSStyleRule()->baseURL())) {
1021 InspectorInstrumentation::didMatchRule(cookie, false);
1024 // If we're matching normal rules, set a pseudo bit if
1025 // we really just matched a pseudo-element.
1026 if (m_dynamicPseudo != NOPSEUDO && m_checker.pseudoStyle() == NOPSEUDO) {
1027 if (m_checker.isCollectingRulesOnly()) {
1028 InspectorInstrumentation::didMatchRule(cookie, false);
1031 if (m_dynamicPseudo < FIRST_INTERNAL_PSEUDOID)
1032 m_style->setHasPseudoStyle(m_dynamicPseudo);
1034 // Update our first/last rule indices in the matched rules array.
1036 if (firstRuleIndex == -1)
1037 firstRuleIndex = lastRuleIndex;
1039 // Add this rule to our list of matched rules.
1040 addMatchedRule(&ruleData);
1041 InspectorInstrumentation::didMatchRule(cookie, true);
1045 InspectorInstrumentation::didMatchRule(cookie, false);
1049 static inline bool compareRules(const RuleData* r1, const RuleData* r2)
1051 unsigned specificity1 = r1->specificity();
1052 unsigned specificity2 = r2->specificity();
1053 return (specificity1 == specificity2) ? r1->position() < r2->position() : specificity1 < specificity2;
1056 void CSSStyleSelector::sortMatchedRules()
1058 std::sort(m_matchedRules.begin(), m_matchedRules.end(), compareRules);
1061 void CSSStyleSelector::matchAllRules(MatchResult& result)
1063 matchUARules(result);
1065 // Now we check user sheet rules.
1066 if (m_matchAuthorAndUserStyles)
1067 matchUserRules(result, false);
1069 // Now check author rules, beginning first with presentational attributes mapped from HTML.
1070 if (m_styledElement) {
1071 addElementStyleProperties(result, m_styledElement->attributeStyle());
1073 // Now we check additional mapped declarations.
1074 // Tables and table cells share an additional mapped rule that must be applied
1075 // after all attributes, since their mapped style depends on the values of multiple attributes.
1076 addElementStyleProperties(result, m_styledElement->additionalAttributeStyle());
1078 if (m_styledElement->isHTMLElement()) {
1080 TextDirection textDirection = toHTMLElement(m_styledElement)->directionalityIfhasDirAutoAttribute(isAuto);
1082 addMatchedProperties(result, textDirection == LTR ? leftToRightDeclaration() : rightToLeftDeclaration());
1086 // Check the rules in author sheets next.
1087 if (m_matchAuthorAndUserStyles)
1088 matchAuthorRules(result, false);
1090 // Now check our inline style attribute.
1091 if (m_matchAuthorAndUserStyles && m_styledElement)
1092 addElementStyleProperties(result, m_styledElement->inlineStyleDecl(), false /* isCacheable */);
1095 // Now check SMIL animation override style.
1096 if (m_matchAuthorAndUserStyles && m_styledElement && m_styledElement->isSVGElement())
1097 addElementStyleProperties(result, static_cast<SVGElement*>(m_styledElement)->animatedSMILStyleProperties(), false /* isCacheable */);
1101 inline void CSSStyleSelector::initElement(Element* e)
1103 if (m_element != e) {
1105 m_styledElement = m_element && m_element->isStyledElement() ? static_cast<StyledElement*>(m_element) : 0;
1106 m_elementLinkState = m_checker.determineLinkState(m_element);
1107 if (e && e == e->document()->documentElement()) {
1108 e->document()->setDirectionSetOnDocumentElement(false);
1109 e->document()->setWritingModeSetOnDocumentElement(false);
1114 inline void CSSStyleSelector::initForStyleResolve(Element* e, RenderStyle* parentStyle, PseudoId pseudoID)
1116 m_checker.setPseudoStyle(pseudoID);
1118 m_parentNode = e ? e->parentNodeForRenderingAndStyle() : 0;
1121 m_parentStyle = parentStyle;
1123 m_parentStyle = m_parentNode ? m_parentNode->renderStyle() : 0;
1125 Node* docElement = e ? e->document()->documentElement() : 0;
1126 RenderStyle* docStyle = m_checker.document()->renderStyle();
1127 m_rootElementStyle = docElement && e != docElement ? docElement->renderStyle() : docStyle;
1131 m_pendingImageProperties.clear();
1135 m_fontDirty = false;
1138 static const unsigned cStyleSearchThreshold = 10;
1139 static const unsigned cStyleSearchLevelThreshold = 10;
1141 Node* CSSStyleSelector::locateCousinList(Element* parent, unsigned& visitedNodeCount) const
1143 if (visitedNodeCount >= cStyleSearchThreshold * cStyleSearchLevelThreshold)
1145 if (!parent || !parent->isStyledElement())
1147 #if ENABLE(STYLE_SCOPED)
1148 if (parent->hasScopedHTMLStyleChild())
1151 StyledElement* p = static_cast<StyledElement*>(parent);
1152 if (p->inlineStyleDecl())
1155 if (p->isSVGElement() && static_cast<SVGElement*>(p)->animatedSMILStyleProperties())
1158 if (p->hasID() && m_features.idsInRules.contains(p->idForStyleResolution().impl()))
1161 RenderStyle* parentStyle = p->renderStyle();
1162 unsigned subcount = 0;
1163 Node* thisCousin = p;
1164 Node* currentNode = p->previousSibling();
1166 // Reserve the tries for this level. This effectively makes sure that the algorithm
1167 // will never go deeper than cStyleSearchLevelThreshold levels into recursion.
1168 visitedNodeCount += cStyleSearchThreshold;
1169 while (thisCousin) {
1170 while (currentNode) {
1172 if (currentNode->renderStyle() == parentStyle && currentNode->lastChild()) {
1173 // Adjust for unused reserved tries.
1174 visitedNodeCount -= cStyleSearchThreshold - subcount;
1175 return currentNode->lastChild();
1177 if (subcount >= cStyleSearchThreshold)
1179 currentNode = currentNode->previousSibling();
1181 currentNode = locateCousinList(thisCousin->parentElement(), visitedNodeCount);
1182 thisCousin = currentNode;
1188 bool CSSStyleSelector::matchesRuleSet(RuleSet* ruleSet)
1192 m_matchedRules.clear();
1194 int firstRuleIndex = -1, lastRuleIndex = -1;
1195 collectMatchingRules(ruleSet, firstRuleIndex, lastRuleIndex, false);
1197 if (m_matchedRules.isEmpty())
1199 m_matchedRules.clear();
1203 bool CSSStyleSelector::canShareStyleWithControl(StyledElement* element) const
1205 #if ENABLE(PROGRESS_TAG)
1206 if (element->hasTagName(progressTag)) {
1207 if (!m_element->hasTagName(progressTag))
1210 HTMLProgressElement* thisProgressElement = static_cast<HTMLProgressElement*>(element);
1211 HTMLProgressElement* otherProgressElement = static_cast<HTMLProgressElement*>(m_element);
1212 if (thisProgressElement->isDeterminate() != otherProgressElement->isDeterminate())
1219 HTMLInputElement* thisInputElement = element->toInputElement();
1220 HTMLInputElement* otherInputElement = m_element->toInputElement();
1222 if (!thisInputElement || !otherInputElement)
1225 if (thisInputElement->isAutofilled() != otherInputElement->isAutofilled())
1227 if (thisInputElement->shouldAppearChecked() != otherInputElement->shouldAppearChecked())
1229 if (thisInputElement->isIndeterminate() != otherInputElement->isIndeterminate())
1231 if (thisInputElement->required() != otherInputElement->required())
1234 if (element->isEnabledFormControl() != m_element->isEnabledFormControl())
1237 if (element->isDefaultButtonForForm() != m_element->isDefaultButtonForForm())
1240 if (m_element->document()->containsValidityStyleRules()) {
1241 bool willValidate = element->willValidate();
1243 if (willValidate != m_element->willValidate())
1246 if (willValidate && (element->isValidFormControlElement() != m_element->isValidFormControlElement()))
1249 if (element->isInRange() != m_element->isInRange())
1252 if (element->isOutOfRange() != m_element->isOutOfRange())
1259 // This function makes some assumptions that only make sense for attribute styles (we only compare CSSProperty::id() and CSSProperty::value().)
1260 static inline bool attributeStylesEqual(StylePropertySet* a, StylePropertySet* b)
1264 if (a->propertyCount() != b->propertyCount())
1266 unsigned propertyCount = a->propertyCount();
1267 for (unsigned i = 0; i < propertyCount; ++i) {
1268 const CSSProperty& aProperty = a->propertyAt(i);
1270 for (j = 0; j < propertyCount; ++j) {
1271 const CSSProperty& bProperty = b->propertyAt(j);
1272 if (aProperty.id() != bProperty.id())
1274 // We could get a few more hits by comparing cssText() here, but that gets expensive quickly.
1275 if (aProperty.value() != bProperty.value())
1279 if (j == propertyCount)
1285 bool CSSStyleSelector::canShareStyleWithElement(StyledElement* element) const
1287 RenderStyle* style = element->renderStyle();
1291 if (style->unique())
1293 if (element->tagQName() != m_element->tagQName())
1295 if (element->hasClass() != m_element->hasClass())
1297 if (element->inlineStyleDecl())
1300 if (element->isSVGElement() && static_cast<SVGElement*>(element)->animatedSMILStyleProperties())
1303 if (!!element->attributeStyle() != !!m_styledElement->attributeStyle())
1305 StylePropertySet* additionalAttributeStyleA = element->additionalAttributeStyle();
1306 StylePropertySet* additionalAttributeStyleB = m_styledElement->additionalAttributeStyle();
1307 if (!additionalAttributeStyleA != !additionalAttributeStyleB)
1309 if (element->isLink() != m_element->isLink())
1311 if (style->affectedByUncommonAttributeSelectors())
1313 if (element->hovered() != m_element->hovered())
1315 if (element->active() != m_element->active())
1317 if (element->focused() != m_element->focused())
1319 if (element->shadowPseudoId() != m_element->shadowPseudoId())
1321 if (element == element->document()->cssTarget())
1323 if (m_element == m_element->document()->cssTarget())
1325 if (element->getAttribute(typeAttr) != m_element->getAttribute(typeAttr))
1327 if (element->fastGetAttribute(XMLNames::langAttr) != m_element->fastGetAttribute(XMLNames::langAttr))
1329 if (element->fastGetAttribute(langAttr) != m_element->fastGetAttribute(langAttr))
1331 if (element->fastGetAttribute(readonlyAttr) != m_element->fastGetAttribute(readonlyAttr))
1333 if (element->fastGetAttribute(cellpaddingAttr) != m_element->fastGetAttribute(cellpaddingAttr))
1336 if (element->hasID() && m_features.idsInRules.contains(element->idForStyleResolution().impl()))
1339 #if ENABLE(STYLE_SCOPED)
1340 if (element->hasScopedHTMLStyleChild())
1344 bool isControl = element->isFormControlElement();
1346 if (isControl != m_element->isFormControlElement())
1349 if (isControl && !canShareStyleWithControl(element))
1352 if (style->transitions() || style->animations())
1355 #if USE(ACCELERATED_COMPOSITING)
1356 // Turn off style sharing for elements that can gain layers for reasons outside of the style system.
1357 // See comments in RenderObject::setStyle().
1358 if (element->hasTagName(iframeTag) || element->hasTagName(frameTag) || element->hasTagName(embedTag) || element->hasTagName(objectTag) || element->hasTagName(appletTag)
1359 #if ENABLE(PLUGIN_PROXY_FOR_VIDEO)
1360 // With proxying, the media elements are backed by a RenderEmbeddedObject.
1361 || element->hasTagName(videoTag) || element->hasTagName(audioTag)
1367 if (equalIgnoringCase(element->fastGetAttribute(dirAttr), "auto") || equalIgnoringCase(m_element->fastGetAttribute(dirAttr), "auto"))
1370 if (element->hasClass() && m_element->getAttribute(classAttr) != element->getAttribute(classAttr))
1373 if (element->attributeStyle() && !attributeStylesEqual(element->attributeStyle(), m_styledElement->attributeStyle()))
1376 if (additionalAttributeStyleA && !attributeStylesEqual(additionalAttributeStyleA, additionalAttributeStyleB))
1379 if (element->isLink() && m_elementLinkState != style->insideLink())
1385 inline StyledElement* CSSStyleSelector::findSiblingForStyleSharing(Node* node, unsigned& count) const
1387 for (; node; node = node->previousSibling()) {
1388 if (!node->isStyledElement())
1390 if (canShareStyleWithElement(static_cast<StyledElement*>(node)))
1392 if (count++ == cStyleSearchThreshold)
1395 return static_cast<StyledElement*>(node);
1398 static inline bool parentStylePreventsSharing(const RenderStyle* parentStyle)
1400 return parentStyle->childrenAffectedByPositionalRules()
1401 || parentStyle->childrenAffectedByFirstChildRules()
1402 || parentStyle->childrenAffectedByLastChildRules()
1403 || parentStyle->childrenAffectedByDirectAdjacentRules();
1406 RenderStyle* CSSStyleSelector::locateSharedStyle()
1408 if (!m_styledElement || !m_parentStyle)
1410 // If the element has inline style it is probably unique.
1411 if (m_styledElement->inlineStyleDecl())
1414 if (m_styledElement->isSVGElement() && static_cast<SVGElement*>(m_styledElement)->animatedSMILStyleProperties())
1417 // Ids stop style sharing if they show up in the stylesheets.
1418 if (m_styledElement->hasID() && m_features.idsInRules.contains(m_styledElement->idForStyleResolution().impl()))
1420 if (parentStylePreventsSharing(m_parentStyle))
1422 #if ENABLE(STYLE_SCOPED)
1423 if (m_styledElement->hasScopedHTMLStyleChild())
1427 // Check previous siblings and their cousins.
1429 unsigned visitedNodeCount = 0;
1430 StyledElement* shareElement = 0;
1431 Node* cousinList = m_styledElement->previousSibling();
1432 while (cousinList) {
1433 shareElement = findSiblingForStyleSharing(cousinList, count);
1436 cousinList = locateCousinList(cousinList->parentElement(), visitedNodeCount);
1439 // If we have exhausted all our budget or our cousins.
1443 // Can't share if sibling rules apply. This is checked at the end as it should rarely fail.
1444 if (matchesRuleSet(m_siblingRuleSet.get()))
1446 // Can't share if attribute rules apply.
1447 if (matchesRuleSet(m_uncommonAttributeRuleSet.get()))
1449 // Tracking child index requires unique style for each node. This may get set by the sibling rule match above.
1450 if (parentStylePreventsSharing(m_parentStyle))
1452 return shareElement->renderStyle();
1455 void CSSStyleSelector::matchUARules(MatchResult& result)
1457 MatchingUARulesScope scope;
1459 // First we match rules from the user agent sheet.
1460 if (simpleDefaultStyleSheet)
1461 result.isCacheable = false;
1462 RuleSet* userAgentStyleSheet = m_medium->mediaTypeMatchSpecific("print")
1463 ? defaultPrintStyle : defaultStyle;
1464 matchUARules(result, userAgentStyleSheet);
1466 // In quirks mode, we match rules from the quirks user agent sheet.
1467 if (!m_checker.strictParsing())
1468 matchUARules(result, defaultQuirksStyle);
1470 // 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.
1471 if (m_checker.document()->isViewSource()) {
1472 if (!defaultViewSourceStyle)
1473 loadViewSourceStyle();
1474 matchUARules(result, defaultViewSourceStyle);
1478 PassRefPtr<RenderStyle> CSSStyleSelector::styleForDocument(Document* document, CSSFontSelector* fontSelector)
1480 Frame* frame = document->frame();
1482 RefPtr<RenderStyle> documentStyle = RenderStyle::create();
1483 documentStyle->setDisplay(BLOCK);
1484 documentStyle->setRTLOrdering(document->visuallyOrdered() ? VisualOrder : LogicalOrder);
1485 documentStyle->setZoom(frame && !document->printing() ? frame->pageZoomFactor() : 1);
1486 documentStyle->setPageScaleTransform(frame ? frame->frameScaleFactor() : 1);
1487 documentStyle->setUserModify(document->inDesignMode() ? READ_WRITE : READ_ONLY);
1488 documentStyle->setLocale(document->contentLanguage());
1490 Element* docElement = document->documentElement();
1491 RenderObject* docElementRenderer = docElement ? docElement->renderer() : 0;
1492 if (docElementRenderer) {
1493 // Use the direction and writing-mode of the body to set the
1494 // viewport's direction and writing-mode unless the property is set on the document element.
1495 // If there is no body, then use the document element.
1496 RenderObject* bodyRenderer = document->body() ? document->body()->renderer() : 0;
1497 if (bodyRenderer && !document->writingModeSetOnDocumentElement())
1498 documentStyle->setWritingMode(bodyRenderer->style()->writingMode());
1500 documentStyle->setWritingMode(docElementRenderer->style()->writingMode());
1501 if (bodyRenderer && !document->directionSetOnDocumentElement())
1502 documentStyle->setDirection(bodyRenderer->style()->direction());
1504 documentStyle->setDirection(docElementRenderer->style()->direction());
1508 if (Page* page = frame->page()) {
1509 const Page::Pagination& pagination = page->pagination();
1510 if (pagination.mode != Page::Pagination::Unpaginated) {
1511 documentStyle->setColumnAxis(pagination.mode == Page::Pagination::HorizontallyPaginated ? HorizontalColumnAxis : VerticalColumnAxis);
1512 documentStyle->setColumnGap(pagination.gap);
1517 FontDescription fontDescription;
1518 fontDescription.setUsePrinterFont(document->printing());
1519 fontDescription.setScript(localeToScriptCodeForFontSelection(documentStyle->locale()));
1520 if (Settings* settings = document->settings()) {
1521 fontDescription.setRenderingMode(settings->fontRenderingMode());
1522 const AtomicString& standardFont = settings->standardFontFamily(fontDescription.script());
1523 if (!standardFont.isEmpty()) {
1524 fontDescription.setGenericFamily(FontDescription::StandardFamily);
1525 fontDescription.firstFamily().setFamily(standardFont);
1526 fontDescription.firstFamily().appendFamily(0);
1528 fontDescription.setKeywordSize(CSSValueMedium - CSSValueXxSmall + 1);
1529 int size = CSSStyleSelector::fontSizeForKeyword(document, CSSValueMedium, false);
1530 fontDescription.setSpecifiedSize(size);
1531 bool useSVGZoomRules = document->isSVGDocument();
1532 fontDescription.setComputedSize(CSSStyleSelector::getComputedSizeFromSpecifiedSize(document, documentStyle.get(), fontDescription.isAbsoluteSize(), size, useSVGZoomRules));
1535 documentStyle->setFontDescription(fontDescription);
1536 documentStyle->font().update(fontSelector);
1538 return documentStyle.release();
1541 static inline bool isAtShadowBoundary(Element* element)
1545 ContainerNode* parentNode = element->parentNode();
1546 return parentNode && parentNode->isShadowRoot();
1549 // If resolveForRootDefault is true, style based on user agent style sheet only. This is used in media queries, where
1550 // relative units are interpreted according to document root element style, styled only with UA stylesheet
1552 PassRefPtr<RenderStyle> CSSStyleSelector::styleForElement(Element* element, RenderStyle* defaultParent, bool allowSharing, bool resolveForRootDefault, RenderRegion* regionForStyling)
1554 // Once an element has a renderer, we don't try to destroy it, since otherwise the renderer
1555 // will vanish if a style recalc happens during loading.
1556 if (allowSharing && !element->document()->haveStylesheetsLoaded() && !element->renderer()) {
1557 if (!s_styleNotYetAvailable) {
1558 s_styleNotYetAvailable = RenderStyle::create().leakRef();
1559 s_styleNotYetAvailable->setDisplay(NONE);
1560 s_styleNotYetAvailable->font().update(m_fontSelector);
1562 element->document()->setHasNodesWithPlaceholderStyle();
1563 return s_styleNotYetAvailable;
1566 initElement(element);
1567 initForStyleResolve(element, defaultParent);
1568 m_regionForStyling = regionForStyling;
1570 RenderStyle* sharedStyle = locateSharedStyle();
1575 m_style = RenderStyle::create();
1578 m_style->inheritFrom(m_parentStyle);
1580 m_parentStyle = style();
1581 // Make sure our fonts are initialized if we don't inherit them from our parent style.
1582 m_style->font().update(0);
1585 // Even if surrounding content is user-editable, shadow DOM should act as a single unit, and not necessarily be editable
1586 if (isAtShadowBoundary(element))
1587 m_style->setUserModify(RenderStyle::initialUserModify());
1589 if (element->isLink()) {
1590 m_style->setIsLink(true);
1591 m_style->setInsideLink(m_elementLinkState);
1594 ensureDefaultStyleSheetsForElement(element);
1596 MatchResult matchResult;
1597 if (resolveForRootDefault)
1598 matchUARules(matchResult);
1600 matchAllRules(matchResult);
1602 applyMatchedProperties(matchResult);
1604 // Clean up our style object's display and text decorations (among other fixups).
1605 adjustRenderStyle(style(), m_parentStyle, element);
1607 initElement(0); // Clear out for the next resolve.
1609 // Now return the style.
1610 return m_style.release();
1613 PassRefPtr<RenderStyle> CSSStyleSelector::styleForKeyframe(const RenderStyle* elementStyle, const WebKitCSSKeyframeRule* keyframeRule, KeyframeValue& keyframe)
1616 if (keyframeRule->declaration())
1617 addMatchedProperties(result, keyframeRule->declaration());
1622 m_style = RenderStyle::clone(elementStyle);
1624 m_lineHeightValue = 0;
1626 // We don't need to bother with !important. Since there is only ever one
1627 // decl, there's nothing to override. So just add the first properties.
1628 bool inheritedOnly = false;
1629 if (keyframeRule->style())
1630 applyMatchedProperties<true>(result, false, 0, result.matchedProperties.size() - 1, inheritedOnly);
1632 // If our font got dirtied, go ahead and update it now.
1635 // Line-height is set when we are sure we decided on the font-size
1636 if (m_lineHeightValue)
1637 applyProperty(CSSPropertyLineHeight, m_lineHeightValue);
1639 // Now do rest of the properties.
1640 if (keyframeRule->style())
1641 applyMatchedProperties<false>(result, false, 0, result.matchedProperties.size() - 1, inheritedOnly);
1643 // If our font got dirtied by one of the non-essential font props,
1644 // go ahead and update it a second time.
1647 // Start loading images referenced by this style.
1648 loadPendingImages();
1650 #if ENABLE(CSS_SHADERS)
1651 // Start loading the shaders referenced by this style.
1652 loadPendingShaders();
1655 // Add all the animating properties to the keyframe.
1656 if (StylePropertySet* styleDeclaration = keyframeRule->declaration()) {
1657 unsigned propertyCount = styleDeclaration->propertyCount();
1658 for (unsigned i = 0; i < propertyCount; ++i) {
1659 int property = styleDeclaration->propertyAt(i).id();
1660 // Timing-function within keyframes is special, because it is not animated; it just
1661 // describes the timing function between this keyframe and the next.
1662 if (property != CSSPropertyWebkitAnimationTimingFunction)
1663 keyframe.addProperty(property);
1667 return m_style.release();
1670 void CSSStyleSelector::keyframeStylesForAnimation(Element* e, const RenderStyle* elementStyle, KeyframeList& list)
1674 // Get the keyframesRule for this name
1675 if (!e || list.animationName().isEmpty())
1678 m_keyframesRuleMap.checkConsistency();
1680 KeyframesRuleMap::iterator it = m_keyframesRuleMap.find(list.animationName().impl());
1681 if (it == m_keyframesRuleMap.end())
1684 const WebKitCSSKeyframesRule* rule = it->second.get();
1686 // Construct and populate the style for each keyframe
1687 for (unsigned i = 0; i < rule->length(); ++i) {
1688 // Apply the declaration to the style. This is a simplified version of the logic in styleForElement
1690 initForStyleResolve(e);
1692 const WebKitCSSKeyframeRule* keyframeRule = rule->item(i);
1694 KeyframeValue keyframe(0, 0);
1695 keyframe.setStyle(styleForKeyframe(elementStyle, keyframeRule, keyframe));
1697 // Add this keyframe style to all the indicated key times
1699 keyframeRule->getKeys(keys);
1700 for (size_t keyIndex = 0; keyIndex < keys.size(); ++keyIndex) {
1701 keyframe.setKey(keys[keyIndex]);
1702 list.insert(keyframe);
1706 // If the 0% keyframe is missing, create it (but only if there is at least one other keyframe)
1707 int initialListSize = list.size();
1708 if (initialListSize > 0 && list[0].key() != 0) {
1709 RefPtr<WebKitCSSKeyframeRule> keyframeRule = WebKitCSSKeyframeRule::create();
1710 keyframeRule->setKeyText("0%");
1711 KeyframeValue keyframe(0, 0);
1712 keyframe.setStyle(styleForKeyframe(elementStyle, keyframeRule.get(), keyframe));
1713 list.insert(keyframe);
1716 // If the 100% keyframe is missing, create it (but only if there is at least one other keyframe)
1717 if (initialListSize > 0 && (list[list.size() - 1].key() != 1)) {
1718 RefPtr<WebKitCSSKeyframeRule> keyframeRule = WebKitCSSKeyframeRule::create();
1719 keyframeRule->setKeyText("100%");
1720 KeyframeValue keyframe(1, 0);
1721 keyframe.setStyle(styleForKeyframe(elementStyle, keyframeRule.get(), keyframe));
1722 list.insert(keyframe);
1726 PassRefPtr<RenderStyle> CSSStyleSelector::pseudoStyleForElement(PseudoId pseudo, Element* e, RenderStyle* parentStyle)
1733 initForStyleResolve(e, parentStyle, pseudo);
1734 m_style = RenderStyle::create();
1737 m_style->inheritFrom(m_parentStyle);
1739 // Since we don't use pseudo-elements in any of our quirk/print user agent rules, don't waste time walking
1742 // Check UA, user and author rules.
1743 MatchResult matchResult;
1744 matchUARules(matchResult);
1746 if (m_matchAuthorAndUserStyles) {
1747 matchUserRules(matchResult, false);
1748 matchAuthorRules(matchResult, false);
1751 if (matchResult.matchedProperties.isEmpty())
1754 m_style->setStyleType(pseudo);
1756 applyMatchedProperties(matchResult);
1758 // Clean up our style object's display and text decorations (among other fixups).
1759 adjustRenderStyle(style(), parentStyle, 0);
1761 // Start loading images referenced by this style.
1762 loadPendingImages();
1764 #if ENABLE(CSS_SHADERS)
1765 // Start loading the shaders referenced by this style.
1766 loadPendingShaders();
1769 // Now return the style.
1770 return m_style.release();
1773 PassRefPtr<RenderStyle> CSSStyleSelector::styleForPage(int pageIndex)
1775 initForStyleResolve(m_checker.document()->documentElement()); // m_rootElementStyle will be set to the document style.
1777 m_style = RenderStyle::create();
1778 m_style->inheritFrom(m_rootElementStyle);
1780 const bool isLeft = isLeftPage(pageIndex);
1781 const bool isFirst = isFirstPage(pageIndex);
1782 const String page = pageName(pageIndex);
1785 matchPageRules(result, defaultPrintStyle, isLeft, isFirst, page);
1786 matchPageRules(result, m_userStyle.get(), isLeft, isFirst, page);
1787 // Only consider the global author RuleSet for @page rules, as per the HTML5 spec.
1788 matchPageRules(result, m_authorStyle.get(), isLeft, isFirst, page);
1789 m_lineHeightValue = 0;
1790 bool inheritedOnly = false;
1791 applyMatchedProperties<true>(result, false, 0, result.matchedProperties.size() - 1, inheritedOnly);
1793 // If our font got dirtied, go ahead and update it now.
1796 // Line-height is set when we are sure we decided on the font-size.
1797 if (m_lineHeightValue)
1798 applyProperty(CSSPropertyLineHeight, m_lineHeightValue);
1800 applyMatchedProperties<false>(result, false, 0, result.matchedProperties.size() - 1, inheritedOnly);
1802 // Start loading images referenced by this style.
1803 loadPendingImages();
1805 #if ENABLE(CSS_SHADERS)
1806 // Start loading the shaders referenced by this style.
1807 loadPendingShaders();
1810 // Now return the style.
1811 return m_style.release();
1814 static void addIntrinsicMargins(RenderStyle* style)
1816 // Intrinsic margin value.
1817 const int intrinsicMargin = 2 * style->effectiveZoom();
1819 // FIXME: Using width/height alone and not also dealing with min-width/max-width is flawed.
1820 // FIXME: Using "quirk" to decide the margin wasn't set is kind of lame.
1821 if (style->width().isIntrinsicOrAuto()) {
1822 if (style->marginLeft().quirk())
1823 style->setMarginLeft(Length(intrinsicMargin, Fixed));
1824 if (style->marginRight().quirk())
1825 style->setMarginRight(Length(intrinsicMargin, Fixed));
1828 if (style->height().isAuto()) {
1829 if (style->marginTop().quirk())
1830 style->setMarginTop(Length(intrinsicMargin, Fixed));
1831 if (style->marginBottom().quirk())
1832 style->setMarginBottom(Length(intrinsicMargin, Fixed));
1836 static EDisplay equivalentBlockDisplay(EDisplay display, bool isFloating, bool strictParsing)
1843 #if ENABLE(CSS_GRID_LAYOUT)
1849 // It is a WinIE bug that floated list items lose their bullets, so we'll emulate the quirk, but only in quirks mode.
1850 if (!strictParsing && isFloating)
1857 case INLINE_FLEXBOX:
1859 #if ENABLE(CSS_GRID_LAYOUT)
1868 case TABLE_ROW_GROUP:
1869 case TABLE_HEADER_GROUP:
1870 case TABLE_FOOTER_GROUP:
1872 case TABLE_COLUMN_GROUP:
1878 ASSERT_NOT_REACHED();
1881 ASSERT_NOT_REACHED();
1885 void CSSStyleSelector::adjustRenderStyle(RenderStyle* style, RenderStyle* parentStyle, Element *e)
1887 // Cache our original display.
1888 style->setOriginalDisplay(style->display());
1890 if (style->display() != NONE) {
1891 // If we have a <td> that specifies a float property, in quirks mode we just drop the float
1893 // Sites also commonly use display:inline/block on <td>s and <table>s. In quirks mode we force
1894 // these tags to retain their display types.
1895 if (!m_checker.strictParsing() && e) {
1896 if (e->hasTagName(tdTag)) {
1897 style->setDisplay(TABLE_CELL);
1898 style->setFloating(NoFloat);
1900 else if (e->hasTagName(tableTag))
1901 style->setDisplay(style->isDisplayInlineType() ? INLINE_TABLE : TABLE);
1904 if (e && (e->hasTagName(tdTag) || e->hasTagName(thTag))) {
1905 if (style->whiteSpace() == KHTML_NOWRAP) {
1906 // Figure out if we are really nowrapping or if we should just
1907 // use normal instead. If the width of the cell is fixed, then
1908 // we don't actually use NOWRAP.
1909 if (style->width().isFixed())
1910 style->setWhiteSpace(NORMAL);
1912 style->setWhiteSpace(NOWRAP);
1916 // Tables never support the -webkit-* values for text-align and will reset back to the default.
1917 if (e && e->hasTagName(tableTag) && (style->textAlign() == WEBKIT_LEFT || style->textAlign() == WEBKIT_CENTER || style->textAlign() == WEBKIT_RIGHT))
1918 style->setTextAlign(TAAUTO);
1920 // Frames and framesets never honor position:relative or position:absolute. This is necessary to
1921 // fix a crash where a site tries to position these objects. They also never honor display.
1922 if (e && (e->hasTagName(frameTag) || e->hasTagName(framesetTag))) {
1923 style->setPosition(StaticPosition);
1924 style->setDisplay(BLOCK);
1927 // Table headers with a text-align of auto will change the text-align to center.
1928 if (e && e->hasTagName(thTag) && style->textAlign() == TAAUTO)
1929 style->setTextAlign(CENTER);
1931 if (e && e->hasTagName(legendTag))
1932 style->setDisplay(BLOCK);
1934 // Absolute/fixed positioned elements, floating elements and the document element need block-like outside display.
1935 if (style->position() == AbsolutePosition || style->position() == FixedPosition || style->isFloating() || (e && e->document()->documentElement() == e))
1936 style->setDisplay(equivalentBlockDisplay(style->display(), style->isFloating(), m_checker.strictParsing()));
1938 // FIXME: Don't support this mutation for pseudo styles like first-letter or first-line, since it's not completely
1939 // clear how that should work.
1940 if (style->display() == INLINE && style->styleType() == NOPSEUDO && parentStyle && style->writingMode() != parentStyle->writingMode())
1941 style->setDisplay(INLINE_BLOCK);
1943 // After performing the display mutation, check table rows. We do not honor position:relative on
1944 // table rows or cells. This has been established in CSS2.1 (and caused a crash in containingBlock()
1946 if ((style->display() == TABLE_HEADER_GROUP || style->display() == TABLE_ROW_GROUP
1947 || style->display() == TABLE_FOOTER_GROUP || style->display() == TABLE_ROW) &&
1948 style->position() == RelativePosition)
1949 style->setPosition(StaticPosition);
1951 // writing-mode does not apply to table row groups, table column groups, table rows, and table columns.
1952 // FIXME: Table cells should be allowed to be perpendicular or flipped with respect to the table, though.
1953 if (style->display() == TABLE_COLUMN || style->display() == TABLE_COLUMN_GROUP || style->display() == TABLE_FOOTER_GROUP
1954 || style->display() == TABLE_HEADER_GROUP || style->display() == TABLE_ROW || style->display() == TABLE_ROW_GROUP
1955 || style->display() == TABLE_CELL)
1956 style->setWritingMode(parentStyle->writingMode());
1958 // FIXME: Since we don't support block-flow on flexible boxes yet, disallow setting
1959 // of block-flow to anything other than TopToBottomWritingMode.
1960 // https://bugs.webkit.org/show_bug.cgi?id=46418 - Flexible box support.
1961 if (style->writingMode() != TopToBottomWritingMode && (style->display() == BOX || style->display() == INLINE_BOX))
1962 style->setWritingMode(TopToBottomWritingMode);
1965 // Make sure our z-index value is only applied if the object is positioned.
1966 if (style->position() == StaticPosition)
1967 style->setHasAutoZIndex();
1969 // Auto z-index becomes 0 for the root element and transparent objects. This prevents
1970 // cases where objects that should be blended as a single unit end up with a non-transparent
1971 // object wedged in between them. Auto z-index also becomes 0 for objects that specify transforms/masks/reflections.
1972 if (style->hasAutoZIndex() && ((e && e->document()->documentElement() == e) || style->opacity() < 1.0f
1973 || style->hasTransformRelatedProperty() || style->hasMask() || style->boxReflect() || style->hasFilter()
1974 #if ENABLE(OVERFLOW_SCROLLING)
1975 // Touch overflow scrolling creates a stacking context.
1976 || style->useTouchOverflowScrolling()
1979 style->setZIndex(0);
1981 // Textarea considers overflow visible as auto.
1982 if (e && e->hasTagName(textareaTag)) {
1983 style->setOverflowX(style->overflowX() == OVISIBLE ? OAUTO : style->overflowX());
1984 style->setOverflowY(style->overflowY() == OVISIBLE ? OAUTO : style->overflowY());
1987 // Finally update our text decorations in effect, but don't allow text-decoration to percolate through
1988 // tables, inline blocks, inline tables, run-ins, or shadow DOM.
1989 if (style->display() == TABLE || style->display() == INLINE_TABLE || style->display() == RUN_IN
1990 || style->display() == INLINE_BLOCK || style->display() == INLINE_BOX || isAtShadowBoundary(e))
1991 style->setTextDecorationsInEffect(style->textDecoration());
1993 style->addToTextDecorationsInEffect(style->textDecoration());
1995 // If either overflow value is not visible, change to auto.
1996 if (style->overflowX() == OMARQUEE && style->overflowY() != OMARQUEE)
1997 style->setOverflowY(OMARQUEE);
1998 else if (style->overflowY() == OMARQUEE && style->overflowX() != OMARQUEE)
1999 style->setOverflowX(OMARQUEE);
2000 else if (style->overflowX() == OVISIBLE && style->overflowY() != OVISIBLE)
2001 style->setOverflowX(OAUTO);
2002 else if (style->overflowY() == OVISIBLE && style->overflowX() != OVISIBLE)
2003 style->setOverflowY(OAUTO);
2005 // Table rows, sections and the table itself will support overflow:hidden and will ignore scroll/auto.
2006 // FIXME: Eventually table sections will support auto and scroll.
2007 if (style->display() == TABLE || style->display() == INLINE_TABLE ||
2008 style->display() == TABLE_ROW_GROUP || style->display() == TABLE_ROW) {
2009 if (style->overflowX() != OVISIBLE && style->overflowX() != OHIDDEN)
2010 style->setOverflowX(OVISIBLE);
2011 if (style->overflowY() != OVISIBLE && style->overflowY() != OHIDDEN)
2012 style->setOverflowY(OVISIBLE);
2015 // Menulists should have visible overflow
2016 if (style->appearance() == MenulistPart) {
2017 style->setOverflowX(OVISIBLE);
2018 style->setOverflowY(OVISIBLE);
2021 // Cull out any useless layers and also repeat patterns into additional layers.
2022 style->adjustBackgroundLayers();
2023 style->adjustMaskLayers();
2025 // Do the same for animations and transitions.
2026 style->adjustAnimations();
2027 style->adjustTransitions();
2029 // Important: Intrinsic margins get added to controls before the theme has adjusted the style, since the theme will
2030 // alter fonts and heights/widths.
2031 if (e && e->isFormControlElement() && style->fontSize() >= 11) {
2032 // Don't apply intrinsic margins to image buttons. The designer knows how big the images are,
2033 // so we have to treat all image buttons as though they were explicitly sized.
2034 if (!e->hasTagName(inputTag) || !static_cast<HTMLInputElement*>(e)->isImageButton())
2035 addIntrinsicMargins(style);
2038 // Let the theme also have a crack at adjusting the style.
2039 if (style->hasAppearance())
2040 RenderTheme::defaultTheme()->adjustStyle(this, style, e, m_hasUAAppearance, m_borderData, m_backgroundData, m_backgroundColor);
2042 // If we have first-letter pseudo style, do not share this style.
2043 if (style->hasPseudoStyle(FIRST_LETTER))
2047 if (e && e->isSVGElement()) {
2048 // Spec: http://www.w3.org/TR/SVG/masking.html#OverflowProperty
2049 if (style->overflowY() == OSCROLL)
2050 style->setOverflowY(OHIDDEN);
2051 else if (style->overflowY() == OAUTO)
2052 style->setOverflowY(OVISIBLE);
2054 if (style->overflowX() == OSCROLL)
2055 style->setOverflowX(OHIDDEN);
2056 else if (style->overflowX() == OAUTO)
2057 style->setOverflowX(OVISIBLE);
2059 // Only the root <svg> element in an SVG document fragment tree honors css position
2060 if (!(e->hasTagName(SVGNames::svgTag) && e->parentNode() && !e->parentNode()->isSVGElement()))
2061 style->setPosition(RenderStyle::initialPosition());
2066 bool CSSStyleSelector::checkRegionStyle(Element* regionElement)
2068 // FIXME (BUG 72472): We don't add @-webkit-region rules of scoped style sheets for the moment,
2069 // so all region rules are global by default. Verify whether that can stand or needs changing.
2071 unsigned rulesSize = m_authorStyle->m_regionSelectorsAndRuleSets.size();
2072 for (unsigned i = 0; i < rulesSize; ++i) {
2073 ASSERT(m_authorStyle->m_regionSelectorsAndRuleSets.at(i).ruleSet.get());
2074 if (checkRegionSelector(m_authorStyle->m_regionSelectorsAndRuleSets.at(i).selector, regionElement))
2079 rulesSize = m_userStyle->m_regionSelectorsAndRuleSets.size();
2080 for (unsigned i = 0; i < rulesSize; ++i) {
2081 ASSERT(m_userStyle->m_regionSelectorsAndRuleSets.at(i).ruleSet.get());
2082 if (checkRegionSelector(m_userStyle->m_regionSelectorsAndRuleSets.at(i).selector, regionElement))
2090 void CSSStyleSelector::updateFont()
2095 checkForTextSizeAdjust();
2096 checkForGenericFamilyChange(style(), m_parentStyle);
2097 checkForZoomChange(style(), m_parentStyle);
2098 m_style->font().update(m_fontSelector);
2099 m_fontDirty = false;
2102 void CSSStyleSelector::cacheBorderAndBackground()
2104 m_hasUAAppearance = m_style->hasAppearance();
2105 if (m_hasUAAppearance) {
2106 m_borderData = m_style->border();
2107 m_backgroundData = *m_style->backgroundLayers();
2108 m_backgroundColor = m_style->backgroundColor();
2112 PassRefPtr<CSSRuleList> CSSStyleSelector::styleRulesForElement(Element* e, unsigned rulesToInclude)
2114 return pseudoStyleRulesForElement(e, NOPSEUDO, rulesToInclude);
2117 PassRefPtr<CSSRuleList> CSSStyleSelector::pseudoStyleRulesForElement(Element* e, PseudoId pseudoId, unsigned rulesToInclude)
2119 if (!e || !e->document()->haveStylesheetsLoaded())
2122 m_checker.setCollectingRulesOnly(true);
2125 initForStyleResolve(e, 0, pseudoId);
2128 if (rulesToInclude & UAAndUserCSSRules) {
2129 // First we match rules from the user agent sheet.
2130 matchUARules(dummy);
2132 // Now we check user sheet rules.
2133 if (m_matchAuthorAndUserStyles)
2134 matchUserRules(dummy, rulesToInclude & EmptyCSSRules);
2137 if (m_matchAuthorAndUserStyles && (rulesToInclude & AuthorCSSRules)) {
2138 m_sameOriginOnly = !(rulesToInclude & CrossOriginCSSRules);
2140 // Check the rules in author sheets.
2141 matchAuthorRules(dummy, rulesToInclude & EmptyCSSRules);
2143 m_sameOriginOnly = false;
2146 m_checker.setCollectingRulesOnly(false);
2148 return m_ruleList.release();
2151 inline bool CSSStyleSelector::checkSelector(const RuleData& ruleData, const ContainerNode* scope)
2153 m_dynamicPseudo = NOPSEUDO;
2154 m_checker.clearHasUnknownPseudoElements();
2156 if (ruleData.hasFastCheckableSelector()) {
2157 // We know this selector does not include any pseudo elements.
2158 if (m_checker.pseudoStyle() != NOPSEUDO)
2160 // We know a sufficiently simple single part selector matches simply because we found it from the rule hash.
2161 // This is limited to HTML only so we don't need to check the namespace.
2162 if (ruleData.hasRightmostSelectorMatchingHTMLBasedOnRuleHash() && m_element->isHTMLElement()) {
2163 if (!ruleData.hasMultipartSelector())
2165 } else if (!SelectorChecker::tagMatches(m_element, ruleData.selector()))
2167 if (!SelectorChecker::fastCheckRightmostAttributeSelector(m_element, ruleData.selector()))
2169 return m_checker.fastCheckSelector(ruleData.selector(), m_element);
2173 SelectorChecker::SelectorCheckingContext context(ruleData.selector(), m_element, SelectorChecker::VisitedMatchEnabled);
2174 context.elementStyle = style();
2175 context.elementParentStyle = m_parentNode ? m_parentNode->renderStyle() : 0;
2176 context.scope = scope;
2177 SelectorChecker::SelectorMatch match = m_checker.checkSelector(context, m_dynamicPseudo);
2178 if (match != SelectorChecker::SelectorMatches)
2180 if (m_checker.pseudoStyle() != NOPSEUDO && m_checker.pseudoStyle() != m_dynamicPseudo)
2185 bool CSSStyleSelector::checkRegionSelector(CSSSelector* regionSelector, Element* regionElement)
2187 if (!regionSelector || !regionElement)
2190 m_checker.clearHasUnknownPseudoElements();
2191 m_checker.setPseudoStyle(NOPSEUDO);
2193 for (CSSSelector* s = regionSelector; s; s = CSSSelectorList::next(s))
2194 if (m_checker.checkSelector(s, regionElement))
2200 bool CSSStyleSelector::determineStylesheetSelectorScopes(CSSStyleSheet* stylesheet, HashSet<AtomicStringImpl*>& idScopes, HashSet<AtomicStringImpl*>& classScopes)
2202 ASSERT(!stylesheet->isLoading());
2204 size_t size = stylesheet->length();
2205 for (size_t i = 0; i < size; i++) {
2206 CSSRule* rule = stylesheet->item(i);
2207 if (rule->isStyleRule()) {
2208 StyleRule* styleRule = static_cast<CSSStyleRule*>(rule)->styleRule();
2209 if (!SelectorChecker::determineSelectorScopes(styleRule->selectorList(), idScopes, classScopes))
2213 if (rule->isImportRule()) {
2214 CSSImportRule* importRule = static_cast<CSSImportRule*>(rule);
2215 if (importRule->styleSheet()) {
2216 if (!determineStylesheetSelectorScopes(importRule->styleSheet(), idScopes, classScopes))
2221 // FIXME: Media rules and maybe some others could be allowed.
2227 // -----------------------------------------------------------------
2229 static inline bool isSelectorMatchingHTMLBasedOnRuleHash(const CSSSelector* selector)
2231 const AtomicString& selectorNamespace = selector->tag().namespaceURI();
2232 if (selectorNamespace != starAtom && selectorNamespace != xhtmlNamespaceURI)
2234 if (selector->m_match == CSSSelector::None)
2236 if (selector->tag() != starAtom)
2238 if (SelectorChecker::isCommonPseudoClassSelector(selector))
2240 return selector->m_match == CSSSelector::Id || selector->m_match == CSSSelector::Class;
2243 static inline bool selectorListContainsUncommonAttributeSelector(const CSSSelector* selector)
2245 CSSSelectorList* selectorList = selector->selectorList();
2248 for (CSSSelector* subSelector = selectorList->first(); subSelector; subSelector = CSSSelectorList::next(subSelector)) {
2249 if (subSelector->isAttributeSelector())
2255 static inline bool isCommonAttributeSelectorAttribute(const QualifiedName& attribute)
2257 // These are explicitly tested for equality in canShareStyleWithElement.
2258 return attribute == typeAttr || attribute == readonlyAttr;
2261 static inline bool containsUncommonAttributeSelector(const CSSSelector* selector)
2264 // Allow certain common attributes (used in the default style) in the selectors that match the current element.
2265 if (selector->isAttributeSelector() && !isCommonAttributeSelectorAttribute(selector->attribute()))
2267 if (selectorListContainsUncommonAttributeSelector(selector))
2269 if (selector->relation() != CSSSelector::SubSelector)
2271 selector = selector->tagHistory();
2274 for (selector = selector->tagHistory(); selector; selector = selector->tagHistory()) {
2275 if (selector->isAttributeSelector())
2277 if (selectorListContainsUncommonAttributeSelector(selector))
2283 RuleData::RuleData(StyleRule* rule, CSSSelector* selector, unsigned position, bool canUseFastCheckSelector, bool inRegionRule)
2285 , m_selector(selector)
2286 , m_specificity(selector->specificity())
2287 , m_position(position)
2288 , m_hasFastCheckableSelector(canUseFastCheckSelector && SelectorChecker::isFastCheckableSelector(selector))
2289 , m_hasMultipartSelector(!!selector->tagHistory())
2290 , m_hasRightmostSelectorMatchingHTMLBasedOnRuleHash(isSelectorMatchingHTMLBasedOnRuleHash(selector))
2291 , m_containsUncommonAttributeSelector(WebCore::containsUncommonAttributeSelector(selector))
2292 , m_linkMatchType(SelectorChecker::determineLinkMatchType(selector))
2293 , m_isInRegionRule(inRegionRule)
2295 SelectorChecker::collectIdentifierHashes(m_selector, m_descendantSelectorIdentifierHashes, maximumIdentifierCount);
2300 , m_autoShrinkToFitEnabled(true)
2304 static inline void collectFeaturesFromSelector(CSSStyleSelector::Features& features, const CSSSelector* selector)
2306 if (selector->m_match == CSSSelector::Id)
2307 features.idsInRules.add(selector->value().impl());
2308 if (selector->isAttributeSelector())
2309 features.attrsInRules.add(selector->attribute().localName().impl());
2310 switch (selector->pseudoType()) {
2311 case CSSSelector::PseudoFirstLine:
2312 features.usesFirstLineRules = true;
2314 case CSSSelector::PseudoBefore:
2315 case CSSSelector::PseudoAfter:
2316 features.usesBeforeAfterRules = true;
2318 case CSSSelector::PseudoLink:
2319 case CSSSelector::PseudoVisited:
2320 features.usesLinkRules = true;
2327 static void collectFeaturesFromRuleData(CSSStyleSelector::Features& features, const RuleData& ruleData)
2329 bool foundSiblingSelector = false;
2330 for (CSSSelector* selector = ruleData.selector(); selector; selector = selector->tagHistory()) {
2331 collectFeaturesFromSelector(features, selector);
2333 if (CSSSelectorList* selectorList = selector->selectorList()) {
2334 for (CSSSelector* subSelector = selectorList->first(); subSelector; subSelector = CSSSelectorList::next(subSelector)) {
2335 if (!foundSiblingSelector && selector->isSiblingSelector())
2336 foundSiblingSelector = true;
2337 collectFeaturesFromSelector(features, subSelector);
2339 } else if (!foundSiblingSelector && selector->isSiblingSelector())
2340 foundSiblingSelector = true;
2342 if (foundSiblingSelector)
2343 features.siblingRules.append(CSSStyleSelector::RuleSelectorPair(ruleData.rule(), ruleData.selector()));
2344 if (ruleData.containsUncommonAttributeSelector())
2345 features.uncommonAttributeRules.append(CSSStyleSelector::RuleSelectorPair(ruleData.rule(), ruleData.selector()));
2348 void RuleSet::addToRuleSet(AtomicStringImpl* key, AtomRuleMap& map, const RuleData& ruleData)
2352 OwnPtr<Vector<RuleData> >& rules = map.add(key, nullptr).first->second;
2354 rules = adoptPtr(new Vector<RuleData>);
2355 rules->append(ruleData);
2358 void RuleSet::addRule(StyleRule* rule, CSSSelector* selector, bool canUseFastCheckSelector, bool inRegionRule)
2360 RuleData ruleData(rule, selector, m_ruleCount++, canUseFastCheckSelector, inRegionRule);
2361 collectFeaturesFromRuleData(m_features, ruleData);
2363 if (selector->m_match == CSSSelector::Id) {
2364 addToRuleSet(selector->value().impl(), m_idRules, ruleData);
2367 if (selector->m_match == CSSSelector::Class) {
2368 addToRuleSet(selector->value().impl(), m_classRules, ruleData);
2371 if (selector->isUnknownPseudoElement()) {
2372 addToRuleSet(selector->value().impl(), m_shadowPseudoElementRules, ruleData);
2375 if (SelectorChecker::isCommonPseudoClassSelector(selector)) {
2376 switch (selector->pseudoType()) {
2377 case CSSSelector::PseudoLink:
2378 case CSSSelector::PseudoVisited:
2379 case CSSSelector::PseudoAnyLink:
2380 m_linkPseudoClassRules.append(ruleData);
2382 case CSSSelector::PseudoFocus:
2383 m_focusPseudoClassRules.append(ruleData);
2386 ASSERT_NOT_REACHED();
2390 const AtomicString& localName = selector->tag().localName();
2391 if (localName != starAtom) {
2392 addToRuleSet(localName.impl(), m_tagRules, ruleData);
2395 m_universalRules.append(ruleData);
2398 void RuleSet::addPageRule(CSSPageRule* rule)
2400 m_pageRules.append(rule);
2403 void RuleSet::addRegionRule(WebKitCSSRegionRule* rule)
2405 RuleSet* regionRuleSet = new RuleSet;
2406 // The region rule set should take into account the position inside the parent rule set.
2407 // Otherwise, the rules inside region block might be incorrectly positioned before other similar rules from
2408 // the stylesheet that contains the region block.
2409 regionRuleSet->m_ruleCount = m_ruleCount;
2411 // Collect the region rules into a rule set
2412 CSSRuleList* regionStylingRules = rule->cssRules();
2413 unsigned rulesSize = regionStylingRules->length();
2414 for (unsigned i = 0; i < rulesSize; ++i) {
2415 CSSRule* regionStylingRule = regionStylingRules->item(i);
2416 if (regionStylingRule->isStyleRule())
2417 regionRuleSet->addStyleRule(static_cast<CSSStyleRule*>(regionStylingRule)->styleRule(), true, true);
2420 m_regionSelectorsAndRuleSets.append(RuleSetSelectorPair(rule->selectorList().first(), regionRuleSet));
2423 void RuleSet::addRulesFromSheet(CSSStyleSheet* sheet, const MediaQueryEvaluator& medium, CSSStyleSelector* styleSelector, const ContainerNode* scope)
2427 // No media implies "all", but if a media list exists it must
2428 // contain our current medium
2429 if (sheet->media() && !medium.eval(sheet->media(), styleSelector))
2430 return; // the style sheet doesn't apply
2432 int len = sheet->length();
2434 for (int i = 0; i < len; i++) {
2435 CSSRule* rule = sheet->item(i);
2436 if (rule->isStyleRule())
2437 addStyleRule(static_cast<CSSStyleRule*>(rule)->styleRule(), !scope);
2438 else if (rule->isPageRule())
2439 addPageRule(static_cast<CSSPageRule*>(rule));
2440 else if (rule->isImportRule()) {
2441 CSSImportRule* import = static_cast<CSSImportRule*>(rule);
2442 if (import->styleSheet() && (!import->media() || medium.eval(import->media(), styleSelector)))
2443 addRulesFromSheet(import->styleSheet(), medium, styleSelector, scope);
2445 else if (rule->isMediaRule()) {
2446 CSSMediaRule* r = static_cast<CSSMediaRule*>(rule);
2447 CSSRuleList* rules = r->cssRules();
2449 if ((!r->media() || medium.eval(r->media(), styleSelector)) && rules) {
2450 // Traverse child elements of the @media rule.
2451 for (unsigned j = 0; j < rules->length(); j++) {
2452 CSSRule *childItem = rules->item(j);
2453 if (childItem->isStyleRule())
2454 addStyleRule(static_cast<CSSStyleRule*>(childItem)->styleRule(), !scope);
2455 else if (childItem->isPageRule())
2456 addPageRule(static_cast<CSSPageRule*>(childItem));
2457 else if (childItem->isFontFaceRule() && styleSelector) {
2458 // Add this font face to our set.
2459 // FIXME(BUG 72461): We don't add @font-face rules of scoped style sheets for the moment.
2462 const CSSFontFaceRule* fontFaceRule = static_cast<CSSFontFaceRule*>(childItem);
2463 styleSelector->fontSelector()->addFontFaceRule(fontFaceRule);
2464 styleSelector->invalidateMatchedPropertiesCache();
2465 } else if (childItem->isKeyframesRule() && styleSelector) {
2466 // Add this keyframe rule to our set.
2467 // FIXME(BUG 72462): We don't add @keyframe rules of scoped style sheets for the moment.
2470 styleSelector->addKeyframeStyle(static_cast<WebKitCSSKeyframesRule*>(childItem));
2474 } else if (rule->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*>(rule);
2480 styleSelector->fontSelector()->addFontFaceRule(fontFaceRule);
2481 styleSelector->invalidateMatchedPropertiesCache();
2482 } else if (rule->isKeyframesRule()) {
2483 // FIXME (BUG 72462): We don't add @keyframe rules of scoped style sheets for the moment.
2486 styleSelector->addKeyframeStyle(static_cast<WebKitCSSKeyframesRule*>(rule));
2487 } else if (rule->isRegionRule() && styleSelector) {
2488 // FIXME (BUG 72472): We don't add @-webkit-region rules of scoped style sheets for the moment.
2491 addRegionRule(static_cast<WebKitCSSRegionRule*>(rule));
2494 if (m_autoShrinkToFitEnabled)
2498 void RuleSet::addStyleRule(StyleRule* rule, bool canUseFastCheckSelector, bool isInRegionRule)
2500 for (CSSSelector* s = rule->selectorList().first(); s; s = CSSSelectorList::next(s))
2501 addRule(rule, s, canUseFastCheckSelector, isInRegionRule);
2504 static inline void shrinkMapVectorsToFit(RuleSet::AtomRuleMap& map)
2506 RuleSet::AtomRuleMap::iterator end = map.end();
2507 for (RuleSet::AtomRuleMap::iterator it = map.begin(); it != end; ++it)
2508 it->second->shrinkToFit();
2511 void RuleSet::shrinkToFit()
2513 shrinkMapVectorsToFit(m_idRules);
2514 shrinkMapVectorsToFit(m_classRules);
2515 shrinkMapVectorsToFit(m_tagRules);
2516 shrinkMapVectorsToFit(m_shadowPseudoElementRules);
2517 m_linkPseudoClassRules.shrinkToFit();
2518 m_focusPseudoClassRules.shrinkToFit();
2519 m_universalRules.shrinkToFit();
2520 m_pageRules.shrinkToFit();
2523 // -------------------------------------------------------------------------------------
2524 // this is mostly boring stuff on how to apply a certain rule to the renderstyle...
2526 static Length convertToLength(CSSPrimitiveValue* primitiveValue, RenderStyle* style, RenderStyle* rootStyle, bool toFloat, double multiplier = 1)
2528 // This function is tolerant of a null style value. The only place style is used is in
2529 // length measurements, like 'ems' and 'px'. And in those cases style is only used
2530 // when the units are EMS or EXS. So we will just fail in those cases.
2532 if (!primitiveValue) {
2533 l = Length(Undefined);
2535 if (!style && primitiveValue->isFontRelativeLength()) {
2536 l = Length(Undefined);
2537 } else if (primitiveValue->isLength()) {
2539 l = Length(primitiveValue->computeLength<double>(style, rootStyle, multiplier), Fixed);
2541 l = primitiveValue->computeLength<Length>(style, rootStyle, multiplier);
2542 } else if (primitiveValue->isPercentage())
2543 l = Length(primitiveValue->getDoubleValue(), Percent);
2544 else if (primitiveValue->isNumber())
2545 l = Length(primitiveValue->getDoubleValue() * 100.0, Percent);
2547 l = Length(Undefined);
2552 Length CSSStyleSelector::convertToIntLength(CSSPrimitiveValue* primitiveValue, RenderStyle* style, RenderStyle* rootStyle, double multiplier)
2554 return convertToLength(primitiveValue, style, rootStyle, false, multiplier);
2557 Length CSSStyleSelector::convertToFloatLength(CSSPrimitiveValue* primitiveValue, RenderStyle* style, RenderStyle* rootStyle, double multiplier)
2559 return convertToLength(primitiveValue, style, rootStyle, true, multiplier);
2562 template <bool applyFirst>
2563 void CSSStyleSelector::applyProperties(const StylePropertySet* properties, StyleRule* rule, bool isImportant, bool inheritedOnly, bool filterRegionProperties)
2565 ASSERT(!filterRegionProperties || m_regionForStyling);
2566 InspectorInstrumentationCookie cookie = InspectorInstrumentation::willProcessRule(document(), rule);
2568 unsigned propertyCount = properties->propertyCount();
2569 for (unsigned i = 0; i < propertyCount; ++i) {
2570 const CSSProperty& current = properties->propertyAt(i);
2571 if (isImportant != current.isImportant())
2573 if (inheritedOnly && !current.isInherited()) {
2574 // If the property value is explicitly inherited, we need to apply further non-inherited properties
2575 // as they might override the value inherited here. For this reason we don't allow declarations with
2576 // explicitly inherited properties to be cached.
2577 ASSERT(!current.value()->isInheritedValue());
2580 int property = current.id();
2582 if (filterRegionProperties && !CSSStyleSelector::isValidRegionStyleProperty(property))
2586 COMPILE_ASSERT(firstCSSProperty == CSSPropertyColor, CSS_color_is_first_property);
2587 COMPILE_ASSERT(CSSPropertyZoom == CSSPropertyColor + 18, CSS_zoom_is_end_of_first_prop_range);
2588 COMPILE_ASSERT(CSSPropertyLineHeight == CSSPropertyZoom + 1, CSS_line_height_is_after_zoom);
2589 // give special priority to font-xxx, color properties, etc
2590 if (property > CSSPropertyLineHeight)
2592 // we apply line-height later
2593 if (property == CSSPropertyLineHeight) {
2594 m_lineHeightValue = current.value();
2597 applyProperty(current.id(), current.value());
2600 if (property > CSSPropertyLineHeight)
2601 applyProperty(current.id(), current.value());
2603 InspectorInstrumentation::didProcessRule(cookie);
2606 template <bool applyFirst>
2607 void CSSStyleSelector::applyMatchedProperties(const MatchResult& matchResult, bool isImportant, int startIndex, int endIndex, bool inheritedOnly)
2609 if (startIndex == -1)
2612 if (m_style->insideLink() != NotInsideLink) {
2613 for (int i = startIndex; i <= endIndex; ++i) {
2614 const MatchedProperties& matchedProperties = matchResult.matchedProperties[i];
2615 unsigned linkMatchType = matchedProperties.linkMatchType;
2616 // FIXME: It would be nicer to pass these as arguments but that requires changes in many places.
2617 m_applyPropertyToRegularStyle = linkMatchType & SelectorChecker::MatchLink;
2618 m_applyPropertyToVisitedLinkStyle = linkMatchType & SelectorChecker::MatchVisited;
2620 applyProperties<applyFirst>(matchedProperties.properties.get(), matchResult.matchedRules[i], isImportant, inheritedOnly, matchedProperties.isInRegionRule);
2622 m_applyPropertyToRegularStyle = true;
2623 m_applyPropertyToVisitedLinkStyle = false;
2626 for (int i = startIndex; i <= endIndex; ++i) {
2627 const MatchedProperties& matchedProperties = matchResult.matchedProperties[i];
2628 applyProperties<applyFirst>(matchedProperties.properties.get(), matchResult.matchedRules[i], isImportant, inheritedOnly, matchedProperties.isInRegionRule);
2632 unsigned CSSStyleSelector::computeMatchedPropertiesHash(const MatchedProperties* properties, unsigned size)
2635 return StringHasher::hashMemory(properties, sizeof(MatchedProperties) * size);
2638 bool operator==(const CSSStyleSelector::MatchRanges& a, const CSSStyleSelector::MatchRanges& b)
2640 return a.firstUARule == b.firstUARule
2641 && a.lastUARule == b.lastUARule
2642 && a.firstAuthorRule == b.firstAuthorRule
2643 && a.lastAuthorRule == b.lastAuthorRule
2644 && a.firstUserRule == b.firstUserRule
2645 && a.lastUserRule == b.lastUserRule;
2648 bool operator!=(const CSSStyleSelector::MatchRanges& a, const CSSStyleSelector::MatchRanges& b)
2653 bool operator==(const CSSStyleSelector::MatchedProperties& a, const CSSStyleSelector::MatchedProperties& b)
2655 return a.properties == b.properties && a.linkMatchType == b.linkMatchType;
2658 bool operator!=(const CSSStyleSelector::MatchedProperties& a, const CSSStyleSelector::MatchedProperties& b)
2663 const CSSStyleSelector::MatchedPropertiesCacheItem* CSSStyleSelector::findFromMatchedPropertiesCache(unsigned hash, const MatchResult& matchResult)
2667 MatchedPropertiesCache::iterator it = m_matchedPropertiesCache.find(hash);
2668 if (it == m_matchedPropertiesCache.end())
2670 MatchedPropertiesCacheItem& cacheItem = it->second;
2672 size_t size = matchResult.matchedProperties.size();
2673 if (size != cacheItem.matchedProperties.size())
2675 for (size_t i = 0; i < size; ++i) {
2676 if (matchResult.matchedProperties[i] != cacheItem.matchedProperties[i])
2679 if (cacheItem.ranges != matchResult.ranges)
2684 void CSSStyleSelector::addToMatchedPropertiesCache(const RenderStyle* style, const RenderStyle* parentStyle, unsigned hash, const MatchResult& matchResult)
2686 static unsigned matchedDeclarationCacheAdditionsBetweenSweeps = 100;
2687 if (++m_matchedPropertiesCacheAdditionsSinceLastSweep >= matchedDeclarationCacheAdditionsBetweenSweeps) {
2688 sweepMatchedPropertiesCache();
2689 m_matchedPropertiesCacheAdditionsSinceLastSweep = 0;
2693 MatchedPropertiesCacheItem cacheItem;
2694 cacheItem.matchedProperties.append(matchResult.matchedProperties);
2695 cacheItem.ranges = matchResult.ranges;
2696 // Note that we don't cache the original RenderStyle instance. It may be further modified.
2697 // The RenderStyle in the cache is really just a holder for the substructures and never used as-is.
2698 cacheItem.renderStyle = RenderStyle::clone(style);
2699 cacheItem.parentRenderStyle = RenderStyle::clone(parentStyle);
2700 m_matchedPropertiesCache.add(hash, cacheItem);
2703 void CSSStyleSelector::invalidateMatchedPropertiesCache()
2705 m_matchedPropertiesCache.clear();
2708 static bool isCacheableInMatchedPropertiesCache(const RenderStyle* style, const RenderStyle* parentStyle)
2710 if (style->unique() || (style->styleType() != NOPSEUDO && parentStyle->unique()))
2712 if (style->hasAppearance())
2714 if (style->zoom() != RenderStyle::initialZoom())
2716 // The cache assumes static knowledge about which properties are inherited.
2717 if (parentStyle->hasExplicitlyInheritedProperties())
2722 void CSSStyleSelector::applyMatchedProperties(const MatchResult& matchResult)
2724 unsigned cacheHash = matchResult.isCacheable ? computeMatchedPropertiesHash(matchResult.matchedProperties.data(), matchResult.matchedProperties.size()) : 0;
2725 bool applyInheritedOnly = false;
2726 const MatchedPropertiesCacheItem* cacheItem = 0;
2727 if (cacheHash && (cacheItem = findFromMatchedPropertiesCache(cacheHash, matchResult))) {
2728 // We can build up the style by copying non-inherited properties from an earlier style object built using the same exact
2729 // style declarations. We then only need to apply the inherited properties, if any, as their values can depend on the
2730 // element context. This is fast and saves memory by reusing the style data structures.
2731 m_style->copyNonInheritedFrom(cacheItem->renderStyle.get());
2732 if (m_parentStyle->inheritedDataShared(cacheItem->parentRenderStyle.get())) {
2733 EInsideLink linkStatus = m_style->insideLink();
2734 // If the cache item parent style has identical inherited properties to the current parent style then the
2735 // resulting style will be identical too. We copy the inherited properties over from the cache and are done.
2736 m_style->inheritFrom(cacheItem->renderStyle.get());
2737 // Unfortunately the link status is treated like an inherited property. We need to explicitly restore it.
2738 m_style->setInsideLink(linkStatus);
2741 applyInheritedOnly = true;
2743 // Now we have all of the matched rules in the appropriate order. Walk the rules and apply
2744 // high-priority properties first, i.e., those properties that other properties depend on.
2745 // The order is (1) high-priority not important, (2) high-priority important, (3) normal not important
2746 // and (4) normal important.
2747 m_lineHeightValue = 0;
2748 applyMatchedProperties<true>(matchResult, false, 0, matchResult.matchedProperties.size() - 1, applyInheritedOnly);
2749 applyMatchedProperties<true>(matchResult, true, matchResult.ranges.firstAuthorRule, matchResult.ranges.lastAuthorRule, applyInheritedOnly);
2750 applyMatchedProperties<true>(matchResult, true, matchResult.ranges.firstUserRule, matchResult.ranges.lastUserRule, applyInheritedOnly);
2751 applyMatchedProperties<true>(matchResult, true, matchResult.ranges.firstUARule, matchResult.ranges.lastUARule, applyInheritedOnly);
2753 if (cacheItem && cacheItem->renderStyle->effectiveZoom() != m_style->effectiveZoom()) {
2755 applyInheritedOnly = false;
2758 // If our font got dirtied, go ahead and update it now.
2761 // Line-height is set when we are sure we decided on the font-size.
2762 if (m_lineHeightValue)
2763 applyProperty(CSSPropertyLineHeight, m_lineHeightValue);
2765 // Many properties depend on the font. If it changes we just apply all properties.
2766 if (cacheItem && cacheItem->renderStyle->fontDescription() != m_style->fontDescription())
2767 applyInheritedOnly = false;
2769 // Now do the normal priority UA properties.
2770 applyMatchedProperties<false>(matchResult, false, matchResult.ranges.firstUARule, matchResult.ranges.lastUARule, applyInheritedOnly);
2772 // Cache our border and background so that we can examine them later.
2773 cacheBorderAndBackground();
2775 // Now do the author and user normal priority properties and all the !important properties.
2776 applyMatchedProperties<false>(matchResult, false, matchResult.ranges.lastUARule + 1, matchResult.matchedProperties.size() - 1, applyInheritedOnly);
2777 applyMatchedProperties<false>(matchResult, true, matchResult.ranges.firstAuthorRule, matchResult.ranges.lastAuthorRule, applyInheritedOnly);
2778 applyMatchedProperties<false>(matchResult, true, matchResult.ranges.firstUserRule, matchResult.ranges.lastUserRule, applyInheritedOnly);
2779 applyMatchedProperties<false>(matchResult, true, matchResult.ranges.firstUARule, matchResult.ranges.lastUARule, applyInheritedOnly);
2781 loadPendingImages();
2783 #if ENABLE(CSS_SHADERS)
2784 loadPendingShaders();
2787 ASSERT(!m_fontDirty);
2789 if (cacheItem || !cacheHash)
2791 if (!isCacheableInMatchedPropertiesCache(m_style.get(), m_parentStyle))
2793 addToMatchedPropertiesCache(m_style.get(), m_parentStyle, cacheHash, matchResult);
2796 static inline bool comparePageRules(const CSSPageRule* r1, const CSSPageRule* r2)
2798 return r1->selector()->specificity() < r2->selector()->specificity();
2801 void CSSStyleSelector::matchPageRules(MatchResult& result, RuleSet* rules, bool isLeftPage, bool isFirstPage, const String& pageName)
2806 Vector<CSSPageRule*> matchedPageRules;
2807 matchPageRulesForList(matchedPageRules, rules->pageRules(), isLeftPage, isFirstPage, pageName);
2808 if (matchedPageRules.isEmpty())
2811 std::stable_sort(matchedPageRules.begin(), matchedPageRules.end(), comparePageRules);
2813 for (unsigned i = 0; i < matchedPageRules.size(); i++)
2814 addMatchedProperties(result, matchedPageRules[i]->properties());
2817 void CSSStyleSelector::matchPageRulesForList(Vector<CSSPageRule*>& matchedRules, const Vector<CSSPageRule*>& rules, bool isLeftPage, bool isFirstPage, const String& pageName)
2819 unsigned size = rules.size();
2820 for (unsigned i = 0; i < size; ++i) {
2821 CSSPageRule* rule = rules[i];
2822 const AtomicString& selectorLocalName = rule->selector()->tag().localName();
2823 if (selectorLocalName != starAtom && selectorLocalName != pageName)
2825 CSSSelector::PseudoType pseudoType = rule->selector()->pseudoType();
2826 if ((pseudoType == CSSSelector::PseudoLeftPage && !isLeftPage)
2827 || (pseudoType == CSSSelector::PseudoRightPage && isLeftPage)
2828 || (pseudoType == CSSSelector::PseudoFirstPage && !isFirstPage))
2831 // If the rule has no properties to apply, then ignore it.
2832 StylePropertySet* properties = rule->properties();
2833 if (!properties || properties->isEmpty())
2836 // Add this rule to our list of matched rules.
2837 matchedRules.append(rule);
2841 bool CSSStyleSelector::isLeftPage(int pageIndex) const
2843 bool isFirstPageLeft = false;
2844 if (!m_rootElementStyle->isLeftToRightDirection())
2845 isFirstPageLeft = true;
2847 return (pageIndex + (isFirstPageLeft ? 1 : 0)) % 2;
2850 bool CSSStyleSelector::isFirstPage(int pageIndex) const
2852 // FIXME: In case of forced left/right page, page at index 1 (not 0) can be the first page.
2853 return (!pageIndex);
2856 String CSSStyleSelector::pageName(int /* pageIndex */) const
2858 // FIXME: Implement page index to page name mapping.
2862 void CSSStyleSelector::applyPropertyToStyle(int id, CSSValue* value, RenderStyle* style)
2865 initForStyleResolve(0, style);
2867 applyPropertyToCurrentStyle(id, value);
2870 void CSSStyleSelector::applyPropertyToCurrentStyle(int id, CSSValue* value)
2873 applyProperty(id, value);
2876 inline bool isValidVisitedLinkProperty(int id)
2878 switch(static_cast<CSSPropertyID>(id)) {
2879 case CSSPropertyBackgroundColor:
2880 case CSSPropertyBorderLeftColor:
2881 case CSSPropertyBorderRightColor:
2882 case CSSPropertyBorderTopColor:
2883 case CSSPropertyBorderBottomColor:
2884 case CSSPropertyColor:
2885 case CSSPropertyOutlineColor:
2886 case CSSPropertyWebkitColumnRuleColor:
2887 case CSSPropertyWebkitTextEmphasisColor:
2888 case CSSPropertyWebkitTextFillColor:
2889 case CSSPropertyWebkitTextStrokeColor:
2890 // Also allow shorthands so that inherit/initial still work.
2891 case CSSPropertyBackground:
2892 case CSSPropertyBorderLeft:
2893 case CSSPropertyBorderRight:
2894 case CSSPropertyBorderTop:
2895 case CSSPropertyBorderBottom:
2896 case CSSPropertyOutline:
2897 case CSSPropertyWebkitColumnRule:
2899 case CSSPropertyFill:
2900 case CSSPropertyStroke:
2910 // http://dev.w3.org/csswg/css3-regions/#the-at-region-style-rule
2911 // FIXME: add incremental support for other region styling properties.
2912 inline bool CSSStyleSelector::isValidRegionStyleProperty(int id)
2914 switch (static_cast<CSSPropertyID>(id)) {
2915 case CSSPropertyBackgroundColor:
2924 // SVG handles zooming in a different way compared to CSS. The whole document is scaled instead
2925 // of each individual length value in the render style / tree. CSSPrimitiveValue::computeLength*()
2926 // multiplies each resolved length with the zoom multiplier - so for SVG we need to disable that.
2927 // Though all CSS values that can be applied to outermost <svg> elements (width/height/border/padding...)
2928 // need to respect the scaling. RenderBox (the parent class of RenderSVGRoot) grabs values like
2929 // width/height/border/padding/... from the RenderStyle -> for SVG these values would never scale,
2930 // if we'd pass a 1.0 zoom factor everyhwere. So we only pass a zoom factor of 1.0 for specific
2931 // properties that are NOT allowed to scale within a zoomed SVG document (letter/word-spacing/font-size).
2932 bool CSSStyleSelector::useSVGZoomRules()
2934 return m_element && m_element->isSVGElement();
2937 #if ENABLE(CSS_GRID_LAYOUT)
2939 static bool createGridTrackBreadth(CSSPrimitiveValue* primitiveValue, CSSStyleSelector* selector, Length& length)
2941 if (primitiveValue->getIdent() == CSSValueAuto) {
2946 if (primitiveValue->isLength()) {
2947 length = primitiveValue->computeLength<Length>(selector->style(), selector->rootElementStyle(), selector->style()->effectiveZoom());
2948 length.setQuirk(primitiveValue->isQuirkValue());
2952 if (primitiveValue->isPercentage()) {
2953 length = Length(primitiveValue->getDoubleValue(), Percent);
2960 static bool createGridTrackList(CSSValue* value, Vector<Length>& lengths, CSSStyleSelector* selector)
2963 if (value->isPrimitiveValue()) {
2964 CSSPrimitiveValue* primitiveValue = static_cast<CSSPrimitiveValue*>(value);
2965 if (primitiveValue->getIdent() == CSSValueNone) {
2966 lengths.append(Length(Undefined));
2972 if (value->isValueList()) {
2973 for (CSSValueListIterator i = value; i.hasMore(); i.advance()) {
2974 CSSValue* currValue = i.value();
2975 if (!currValue->isPrimitiveValue())
2979 if (!createGridTrackBreadth(static_cast<CSSPrimitiveValue*>(currValue), selector, length))
2982 lengths.append(length);
2991 static bool createGridPosition(CSSValue* value, Length& position)
2993 // For now, we only accept: <integer> | 'auto'
2994 if (!value->isPrimitiveValue())
2997 CSSPrimitiveValue* primitiveValue = static_cast<CSSPrimitiveValue*>(value);
2998 if (primitiveValue->getIdent() == CSSValueAuto)
3001 ASSERT(primitiveValue->isNumber());
3002 position.setValue(primitiveValue->getIntValue());
3007 void CSSStyleSelector::applyProperty(int id, CSSValue *value)
3009 bool isInherit = m_parentNode && value->isInheritedValue();
3010 bool isInitial = value->isInitialValue() || (!m_parentNode && value->isInheritedValue());
3012 ASSERT(!isInherit || !isInitial); // isInherit -> !isInitial && isInitial -> !isInherit
3014 if (!applyPropertyToRegularStyle() && (!applyPropertyToVisitedLinkStyle() || !isValidVisitedLinkProperty(id))) {
3015 // Limit the properties that can be applied to only the ones honored by :visited.
3019 CSSPropertyID property = static_cast<CSSPropertyID>(id);
3021 if (isInherit && m_parentStyle && !m_parentStyle->hasExplicitlyInheritedProperties() && !CSSProperty::isInheritedProperty(property))
3022 m_parentStyle->setHasExplicitlyInheritedProperties();
3024 // check lookup table for implementations and use when available
3025 const PropertyHandler& handler = m_applyProperty.propertyHandler(property);
3026 if (handler.isValid()) {
3028 handler.applyInheritValue(this);
3030 handler.applyInitialValue(this);
3032 handler.applyValue(this, value);
3036 CSSPrimitiveValue* primitiveValue = value->isPrimitiveValue() ? static_cast<CSSPrimitiveValue*>(value) : 0;
3038 float zoomFactor = m_style->effectiveZoom();
3040 // What follows is a list that maps the CSS properties into their corresponding front-end
3041 // RenderStyle values. Shorthands (e.g. border, background) occur in this list as well and
3042 // are only hit when mapping "inherit" or "initial" into front-end values.
3045 case CSSPropertyContent:
3046 // list of string, uri, counter, attr, i
3048 // FIXME: In CSS3, it will be possible to inherit content. In CSS2 it is not. This
3049 // note is a reminder that eventually "inherit" needs to be supported.
3052 m_style->clearContent();
3056 if (!value->isValueList())
3059 bool didSet = false;
3060 for (CSSValueListIterator i = value; i.hasMore(); i.advance()) {
3061 CSSValue* item = i.value();
3062 if (item->isImageGeneratorValue()) {
3063 m_style->setContent(StyleGeneratedImage::create(static_cast<CSSImageGeneratorValue*>(item)), didSet);
3067 if (!item->isPrimitiveValue())
3070 CSSPrimitiveValue* contentValue = static_cast<CSSPrimitiveValue*>(item);
3072 if (contentValue->isString()) {
3073 m_style->setContent(contentValue->getStringValue().impl(), didSet);
3075 } else if (contentValue->isAttr()) {
3076 // FIXME: Can a namespace be specified for an attr(foo)?
3077 if (m_style->styleType() == NOPSEUDO)
3078 m_style->setUnique();
3080 m_parentStyle->setUnique();
3081 QualifiedName attr(nullAtom, contentValue->getStringValue().impl(), nullAtom);
3082 const AtomicString& value = m_element->getAttribute(attr);
3083 m_style->setContent(value.isNull() ? emptyAtom : value.impl(), didSet);
3085 // register the fact that the attribute value affects the style
3086 m_features.attrsInRules.add(attr.localName().impl());
3087 } else if (contentValue->isURI()) {
3088 if (!contentValue->isImageValue())
3090 m_style->setContent(cachedOrPendingFromValue(CSSPropertyContent, static_cast<CSSImageValue*>(contentValue)), didSet);
3092 } else if (contentValue->isCounter()) {
3093 Counter* counterValue = contentValue->getCounterValue();
3094 EListStyleType listStyleType = NoneListStyle;
3095 int listStyleIdent = counterValue->listStyleIdent();
3096 if (listStyleIdent != CSSValueNone)
3097 listStyleType = static_cast<EListStyleType>(listStyleIdent - CSSValueDisc);
3098 OwnPtr<CounterContent> counter = adoptPtr(new CounterContent(counterValue->identifier(), listStyleType, counterValue->separator()));
3099 m_style->setContent(counter.release(), didSet);
3102 switch (contentValue->getIdent()) {
3103 case CSSValueOpenQuote:
3104 m_style->setContent(OPEN_QUOTE, didSet);
3107 case CSSValueCloseQuote:
3108 m_style->setContent(CLOSE_QUOTE, didSet);
3111 case CSSValueNoOpenQuote:
3112 m_style->setContent(NO_OPEN_QUOTE, didSet);
3115 case CSSValueNoCloseQuote:
3116 m_style->setContent(NO_CLOSE_QUOTE, didSet);
3120 // normal and none do not have any effect.
3126 m_style->clearContent();
3129 case CSSPropertyQuotes:
3132 m_style->setQuotes(m_parentStyle->quotes());
3136 m_style->setQuotes(0);
3139 if (value->isValueList()) {
3140 CSSValueList* list = static_cast<CSSValueList*>(value);
3141 QuotesData* data = QuotesData::create(list->length());
3143 return; // Out of memory
3144 String* quotes = data->data();
3145 for (CSSValueListIterator i = list; i.hasMore(); i.advance()) {
3146 CSSValue* item = i.value();
3147 ASSERT(item->isPrimitiveValue());
3148 primitiveValue = static_cast<CSSPrimitiveValue*>(item);
3149 ASSERT(primitiveValue->isString());
3150 quotes[i.index()] = primitiveValue->getStringValue();
3152 m_style->setQuotes(adoptRef(data));
3153 } else if (primitiveValue) {
3154 ASSERT(primitiveValue->isIdent());
3155 if (primitiveValue->getIdent() == CSSValueNone)
3156 m_style->setQuotes(adoptRef(QuotesData::create(0)));
3159 case CSSPropertyFontFamily: {
3160 // list of strings and ids
3162 FontDescription parentFontDescription = m_parentStyle->fontDescription();
3163 FontDescription fontDescription = m_style->fontDescription();
3164 fontDescription.setGenericFamily(parentFontDescription.genericFamily());
3165 fontDescription.setFamily(parentFontDescription.firstFamily());
3166 fontDescription.setIsSpecifiedFont(parentFontDescription.isSpecifiedFont());
3167 setFontDescription(fontDescription);
3169 } else if (isInitial) {
3170 FontDescription initialDesc = FontDescription();
3171 FontDescription fontDescription = m_style->fontDescription();
3172 // We need to adjust the size to account for the generic family change from monospace
3173 // to non-monospace.
3174 if (fontDescription.keywordSize() && fontDescription.useFixedDefaultSize())
3175 setFontSize(fontDescription, fontSizeForKeyword(m_checker.document(), CSSValueXxSmall + fontDescription.keywordSize() - 1, false));
3176 fontDescription.setGenericFamily(initialDesc.genericFamily());
3177 if (!initialDesc.firstFamily().familyIsEmpty())
3178 fontDescription.setFamily(initialDesc.firstFamily());
3179 setFontDescription(fontDescription);
3183 if (!value->isValueList())
3185 FontDescription fontDescription = m_style->fontDescription();
3186 FontFamily& firstFamily = fontDescription.firstFamily();
3187 FontFamily* currFamily = 0;
3189 // Before mapping in a new font-family property, we should reset the generic family.
3190 bool oldFamilyUsedFixedDefaultSize = fontDescription.useFixedDefaultSize();
3191 fontDescription.setGenericFamily(FontDescription::NoFamily);
3193 for (CSSValueListIterator i = value; i.hasMore(); i.advance()) {
3194 CSSValue* item = i.value();
3195 if (!item->isPrimitiveValue())
3197 CSSPrimitiveValue* contentValue = static_cast<CSSPrimitiveValue*>(item);
3199 Settings* settings = m_checker.document()->settings();
3200 if (contentValue->isString())
3201 face = contentValue->getStringValue();
3202 else if (settings) {
3203 switch (contentValue->getIdent()) {
3204 case CSSValueWebkitBody:
3205 face = settings->standardFontFamily();
3209 fontDescription.setGenericFamily(FontDescription::SerifFamily);
3211 case CSSValueSansSerif:
3212 face = sansSerifFamily;
3213 fontDescription.setGenericFamily(FontDescription::SansSerifFamily);
3215 case CSSValueCursive:
3216 face = cursiveFamily;
3217 fontDescription.setGenericFamily(FontDescription::CursiveFamily);
3219 case CSSValueFantasy:
3220 face = fantasyFamily;
3221 fontDescription.setGenericFamily(FontDescription::FantasyFamily);
3223 case CSSValueMonospace:
3224 face = monospaceFamily;
3225 fontDescription.setGenericFamily(FontDescription::MonospaceFamily);
3227 case CSSValueWebkitPictograph:
3228 face = pictographFamily;
3229 fontDescription.setGenericFamily(FontDescription::PictographFamily);
3234 if (!face.isEmpty()) {
3236 // Filling in the first family.
3237 firstFamily.setFamily(face);
3238 firstFamily.appendFamily(0); // Remove any inherited family-fallback list.
3239 currFamily = &firstFamily;
3240 fontDescription.setIsSpecifiedFont(fontDescription.genericFamily() == FontDescription::NoFamily);
3242 RefPtr<SharedFontFamily> newFamily = SharedFontFamily::create();
3243 newFamily->setFamily(face);
3244 currFamily->appendFamily(newFamily);
3245 currFamily = newFamily.get();
3250 // We can't call useFixedDefaultSize() until all new font families have been added
3251 // If currFamily is non-zero then we set at least one family on this description.
3253 if (fontDescription.keywordSize() && fontDescription.useFixedDefaultSize() != oldFamilyUsedFixedDefaultSize)
3254 setFontSize(fontDescription, fontSizeForKeyword(m_checker.document(), CSSValueXxSmall + fontDescription.keywordSize() - 1, !oldFamilyUsedFixedDefaultSize));
3256 setFontDescription(fontDescription);
3260 // shorthand properties
3261 case CSSPropertyBackground:
3263 m_style->clearBackgroundLayers();
3264 m_style->setBackgroundColor(Color());
3266 else if (isInherit) {
3267 m_style->inheritBackgroundLayers(*m_parentStyle->backgroundLayers());
3268 m_style->setBackgroundColor(m_parentStyle->backgroundColor());
3271 case CSSPropertyWebkitMask:
3273 m_style->clearMaskLayers();
3275 m_style->inheritMaskLayers(*m_parentStyle->maskLayers());
3277 case CSSPropertyFont:
3279 FontDescription fontDescription = m_parentStyle->fontDescription();
3280 m_style->setLineHeight(m_parentStyle->lineHeight());
3281 m_lineHeightValue = 0;
3282 setFontDescription(fontDescription);
3283 } else if (isInitial) {
3284 Settings* settings = m_checker.document()->settings();
3285 ASSERT(settings); // If we're doing style resolution, this document should always be in a frame and thus have settings
3288 FontDescription fontDescription;
3289 fontDescription.setGenericFamily(FontDescription::StandardFamily);
3290 fontDescription.setRenderingMode(settings->fontRenderingMode());
3291 fontDescription.setUsePrinterFont(m_checker.document()->printing());
3292 const AtomicString& standardFontFamily = m_checker.document()->settings()->standardFontFamily();
3293 if (!standardFontFamily.isEmpty()) {
3294 fontDescription.firstFamily().setFamily(standardFontFamily);
3295 fontDescription.firstFamily().appendFamily(0);
3297 fontDescription.setKeywordSize(CSSValueMedium - CSSValueXxSmall + 1);
3298 setFontSize(fontDescription, fontSizeForKeyword(m_checker.document(), CSSValueMedium, false));
3299 m_style->setLineHeight(RenderStyle::initialLineHeight());
3300 m_lineHeightValue = 0;
3301 setFontDescription(fontDescription);
3302 } else if (primitiveValue) {
3303 m_style->setLineHeight(RenderStyle::initialLineHeight());
3304 m_lineHeightValue = 0;
3306 FontDescription fontDescription;
3307 RenderTheme::defaultTheme()->systemFont(primitiveValue->getIdent(), fontDescription);
3309 // Double-check and see if the theme did anything. If not, don't bother updating the font.
3310 if (fontDescription.isAbsoluteSize()) {
3311 // Make sure the rendering mode and printer font settings are updated.
3312 Settings* settings = m_checker.document()->settings();
3313 ASSERT(settings); // If we're doing style resolution, this document should always be in a frame and thus have settings
3316 fontDescription.setRenderingMode(settings->fontRenderingMode());
3317 fontDescription.setUsePrinterFont(m_checker.document()->printing());
3319 // Handle the zoom factor.
3320 fontDescription.setComputedSize(getComputedSizeFromSpecifiedSize(m_checker.document(), m_style.get(), fontDescription.isAbsoluteSize(), fontDescription.specifiedSize(), useSVGZoomRules()));
3321 setFontDescription(fontDescription);
3323 } else if (value->isFontValue()) {
3324 FontValue *font = static_cast<FontValue*>(value);
3325 if (!font->style || !font->variant || !font->weight ||
3326 !font->size || !font->lineHeight || !font->family)
3328 applyProperty(CSSPropertyFontStyle, font->style.get());
3329 applyProperty(CSSPropertyFontVariant, font->variant.get());
3330 applyProperty(CSSPropertyFontWeight, font->weight.get());
3331 // The previous properties can dirty our font but they don't try to read the font's
3332 // properties back, which is safe. However if font-size is using the 'ex' unit, it will
3333 // need query the dirtied font's x-height to get the computed size. To be safe in this
3334 // case, let's just update the font now.
3336 applyProperty(CSSPropertyFontSize, font->size.get());
3338 m_lineHeightValue = font->lineHeight.get();
3340 applyProperty(CSSPropertyFontFamily, font->family.get());
3345 case CSSPropertyTextShadow:
3346 case CSSPropertyBoxShadow:
3347 case CSSPropertyWebkitBoxShadow: {
3349 if (id == CSSPropertyTextShadow)
3350 return m_style->setTextShadow(m_parentStyle->textShadow() ? adoptPtr(new ShadowData(*m_parentStyle->textShadow())) : nullptr);
3351 return m_style->setBoxShadow(m_parentStyle->boxShadow() ? adoptPtr(new ShadowData(*m_parentStyle->boxShadow())) : nullptr);