2 * Copyright (C) 1999 Lars Knoll (knoll@kde.org)
3 * (C) 2004-2005 Allan Sandfeld Jensen (kde@carewolf.com)
4 * Copyright (C) 2006, 2007 Nicholas Shanks (webkit@nickshanks.com)
5 * Copyright (C) 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012 Apple Inc. All rights reserved.
6 * Copyright (C) 2007 Alexey Proskuryakov <ap@webkit.org>
7 * Copyright (C) 2007, 2008 Eric Seidel <eric@webkit.org>
8 * Copyright (C) 2008, 2009 Torch Mobile Inc. All rights reserved. (http://www.torchmobile.com/)
9 * Copyright (c) 2011, Code Aurora Forum. All rights reserved.
10 * Copyright (C) Research In Motion Limited 2011. All rights reserved.
11 * Copyright (C) 2012 Google Inc. All rights reserved.
13 * This library is free software; you can redistribute it and/or
14 * modify it under the terms of the GNU Library General Public
15 * License as published by the Free Software Foundation; either
16 * version 2 of the License, or (at your option) any later version.
18 * This library is distributed in the hope that it will be useful,
19 * but WITHOUT ANY WARRANTY; without even the implied warranty of
20 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
21 * Library General Public License for more details.
23 * You should have received a copy of the GNU Library General Public License
24 * along with this library; see the file COPYING.LIB. If not, write to
25 * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
26 * Boston, MA 02110-1301, USA.
30 #include "StyleResolver.h"
32 #include "Attribute.h"
33 #include "CSSBorderImage.h"
34 #include "CSSCalculationValue.h"
35 #include "CSSCursorImageValue.h"
36 #include "CSSFontFaceRule.h"
37 #include "CSSFontSelector.h"
38 #include "CSSImportRule.h"
39 #include "CSSLineBoxContainValue.h"
40 #include "CSSMediaRule.h"
41 #include "CSSPageRule.h"
42 #include "CSSParser.h"
43 #include "CSSPrimitiveValueMappings.h"
44 #include "CSSPropertyNames.h"
45 #include "CSSReflectValue.h"
46 #include "CSSRuleList.h"
47 #include "CSSSelector.h"
48 #include "CSSSelectorList.h"
49 #include "CSSStyleRule.h"
50 #include "CSSStyleSheet.h"
51 #include "CSSTimingFunctionValue.h"
52 #include "CSSValueList.h"
53 #if ENABLE(CSS_VARIABLES)
54 #include "CSSVariableValue.h"
56 #include "CachedImage.h"
57 #include "CalculationValue.h"
58 #include "ContentData.h"
59 #include "ContextFeatures.h"
61 #include "CounterContent.h"
62 #include "CursorList.h"
63 #include "DocumentStyleSheetCollection.h"
64 #include "ElementShadow.h"
65 #include "FontFeatureValue.h"
66 #include "FontValue.h"
68 #include "FrameSelection.h"
69 #include "FrameView.h"
70 #include "HTMLDocument.h"
71 #include "HTMLIFrameElement.h"
72 #include "HTMLInputElement.h"
73 #include "HTMLNames.h"
74 #include "HTMLOptionElement.h"
75 #include "HTMLProgressElement.h"
76 #include "HTMLStyleElement.h"
77 #include "HTMLTextAreaElement.h"
78 #include "InsertionPoint.h"
79 #include "InspectorInstrumentation.h"
80 #include "KeyframeList.h"
82 #include "LocaleToScriptMapping.h"
83 #include "MathMLNames.h"
84 #include "Matrix3DTransformOperation.h"
85 #include "MatrixTransformOperation.h"
86 #include "MediaList.h"
87 #include "MediaQueryEvaluator.h"
88 #include "NodeRenderStyle.h"
89 #include "NodeRenderingContext.h"
92 #include "PerspectiveTransformOperation.h"
93 #include "QuotesData.h"
95 #include "RenderRegion.h"
96 #include "RenderScrollbar.h"
97 #include "RenderScrollbarTheme.h"
98 #include "RenderStyleConstants.h"
99 #include "RenderTheme.h"
100 #include "RenderView.h"
101 #include "RotateTransformOperation.h"
103 #include "SVGDocumentExtensions.h"
104 #include "SVGFontFaceElement.h"
105 #include "ScaleTransformOperation.h"
106 #include "SecurityOrigin.h"
107 #include "Settings.h"
108 #include "ShadowData.h"
109 #include "ShadowRoot.h"
110 #include "ShadowValue.h"
111 #include "SiblingTraversalStrategies.h"
112 #include "SkewTransformOperation.h"
113 #include "StyleBuilder.h"
114 #include "StyleCachedImage.h"
115 #include "StyleGeneratedImage.h"
116 #include "StylePendingImage.h"
117 #include "StyleRule.h"
118 #include "StyleRuleImport.h"
119 #include "StyleSheetContents.h"
120 #include "StyleSheetList.h"
122 #include "TransformationMatrix.h"
123 #include "TranslateTransformOperation.h"
124 #include "UserAgentStyleSheets.h"
125 #include "ViewportStyleResolver.h"
126 #include "VisitedLinkState.h"
127 #include "WebCoreMemoryInstrumentation.h"
128 #include "WebKitCSSKeyframeRule.h"
129 #include "WebKitCSSKeyframesRule.h"
130 #include "WebKitCSSRegionRule.h"
131 #include "WebKitCSSTransformValue.h"
132 #include "WebKitFontFamilyNames.h"
133 #include "XMLNames.h"
134 #include <wtf/MemoryInstrumentationHashMap.h>
135 #include <wtf/MemoryInstrumentationHashSet.h>
136 #include <wtf/MemoryInstrumentationVector.h>
137 #include <wtf/StdLibExtras.h>
138 #include <wtf/Vector.h>
140 #if ENABLE(CSS_FILTERS)
141 #include "FilterOperation.h"
142 #include "WebKitCSSFilterValue.h"
145 #if ENABLE(DASHBOARD_SUPPORT)
146 #include "DashboardRegion.h"
150 #include "CachedSVGDocument.h"
151 #include "CachedSVGDocumentReference.h"
152 #include "SVGDocument.h"
153 #include "SVGElement.h"
154 #include "SVGNames.h"
155 #include "SVGURIReference.h"
156 #include "WebKitCSSSVGDocumentValue.h"
159 #if ENABLE(CSS_SHADERS)
160 #include "CustomFilterArrayParameter.h"
161 #include "CustomFilterConstants.h"
162 #include "CustomFilterNumberParameter.h"
163 #include "CustomFilterOperation.h"
164 #include "CustomFilterParameter.h"
165 #include "CustomFilterTransformParameter.h"
166 #include "StyleCachedShader.h"
167 #include "StyleCustomFilterProgram.h"
168 #include "StylePendingShader.h"
169 #include "StyleShader.h"
170 #include "WebKitCSSMixFunctionValue.h"
171 #include "WebKitCSSShaderValue.h"
174 #if ENABLE(CSS_IMAGE_SET)
175 #include "CSSImageSetValue.h"
176 #include "StyleCachedImageSet.h"
183 template<> struct SequenceMemoryInstrumentationTraits<const WebCore::RuleData*> {
184 template <typename I> static void reportMemoryUsage(I, I, MemoryClassInfo&) { }
191 using namespace HTMLNames;
193 #define HANDLE_INHERIT(prop, Prop) \
195 m_style->set##Prop(m_parentStyle->prop()); \
199 #define HANDLE_INHERIT_AND_INITIAL(prop, Prop) \
200 HANDLE_INHERIT(prop, Prop) \
202 m_style->set##Prop(RenderStyle::initial##Prop()); \
206 static RuleSet* defaultStyle;
207 static RuleSet* defaultQuirksStyle;
208 static RuleSet* defaultPrintStyle;
209 static RuleSet* defaultViewSourceStyle;
210 static StyleSheetContents* simpleDefaultStyleSheet;
211 static StyleSheetContents* defaultStyleSheet;
212 static StyleSheetContents* quirksStyleSheet;
213 static StyleSheetContents* svgStyleSheet;
214 static StyleSheetContents* mathMLStyleSheet;
215 static StyleSheetContents* mediaControlsStyleSheet;
216 static StyleSheetContents* fullscreenStyleSheet;
218 RenderStyle* StyleResolver::s_styleNotYetAvailable;
220 static void loadFullDefaultStyle();
221 static void loadSimpleDefaultStyle();
222 template <class ListType>
223 static void collectCSSOMWrappers(HashMap<StyleRule*, RefPtr<CSSStyleRule> >&, ListType*);
225 // FIXME: It would be nice to use some mechanism that guarantees this is in sync with the real UA stylesheet.
226 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}";
228 static inline bool elementCanUseSimpleDefaultStyle(Element* e)
230 return e->hasTagName(htmlTag) || e->hasTagName(headTag) || e->hasTagName(bodyTag) || e->hasTagName(divTag) || e->hasTagName(spanTag) || e->hasTagName(brTag) || e->hasTagName(aTag);
233 static const MediaQueryEvaluator& screenEval()
235 DEFINE_STATIC_LOCAL(const MediaQueryEvaluator, staticScreenEval, ("screen"));
236 return staticScreenEval;
239 static const MediaQueryEvaluator& printEval()
241 DEFINE_STATIC_LOCAL(const MediaQueryEvaluator, staticPrintEval, ("print"));
242 return staticPrintEval;
245 static StylePropertySet* leftToRightDeclaration()
247 DEFINE_STATIC_LOCAL(RefPtr<StylePropertySet>, leftToRightDecl, (StylePropertySet::create()));
248 if (leftToRightDecl->isEmpty())
249 leftToRightDecl->setProperty(CSSPropertyDirection, CSSValueLtr);
250 return leftToRightDecl.get();
253 static StylePropertySet* rightToLeftDeclaration()
255 DEFINE_STATIC_LOCAL(RefPtr<StylePropertySet>, rightToLeftDecl, (StylePropertySet::create()));
256 if (rightToLeftDecl->isEmpty())
257 rightToLeftDecl->setProperty(CSSPropertyDirection, CSSValueRtl);
258 return rightToLeftDecl.get();
262 StyleResolver::StyleResolver(Document* document, bool matchAuthorAndUserStyles)
263 : m_hasUAAppearance(false)
264 , m_backgroundData(BackgroundFillLayer)
265 , m_matchedPropertiesCacheAdditionsSinceLastSweep(0)
266 , m_matchedPropertiesCacheSweepTimer(this, &StyleResolver::sweepMatchedPropertiesCache)
267 , m_document(document)
268 , m_selectorChecker(document)
270 , m_rootElementStyle(0)
273 , m_regionForStyling(0)
274 , m_elementLinkState(NotInsideLink)
276 , m_lineHeightValue(0)
278 , m_matchAuthorAndUserStyles(matchAuthorAndUserStyles)
279 , m_sameOriginOnly(false)
280 , m_distributedToInsertionPoint(false)
281 , m_fontSelector(CSSFontSelector::create(document))
282 #if ENABLE(CSS_DEVICE_ADAPTATION)
283 , m_viewportStyleResolver(ViewportStyleResolver::create(document))
285 , m_applyPropertyToRegularStyle(true)
286 , m_applyPropertyToVisitedLinkStyle(false)
287 , m_styleBuilder(StyleBuilder::sharedStyleBuilder())
288 #if ENABLE(CSS_SHADERS)
289 , m_hasPendingShaders(false)
293 Element* root = document->documentElement();
296 if (!root || elementCanUseSimpleDefaultStyle(root))
297 loadSimpleDefaultStyle();
299 loadFullDefaultStyle();
302 // construct document root element default style. this is needed
303 // to evaluate media queries that contain relative constraints, like "screen and (max-width: 10em)"
304 // This is here instead of constructor, because when constructor is run,
305 // document doesn't have documentElement
306 // NOTE: this assumes that element that gets passed to styleForElement -call
307 // is always from the document that owns the style selector
308 FrameView* view = document->view();
310 m_medium = adoptPtr(new MediaQueryEvaluator(view->mediaType()));
312 m_medium = adoptPtr(new MediaQueryEvaluator("all"));
315 m_rootDefaultStyle = styleForElement(root, 0, DisallowStyleSharing, MatchOnlyUserAgentRules);
317 if (m_rootDefaultStyle && view)
318 m_medium = adoptPtr(new MediaQueryEvaluator(view->mediaType(), view->frame(), m_rootDefaultStyle.get()));
322 DocumentStyleSheetCollection* styleSheetCollection = document->styleSheetCollection();
323 OwnPtr<RuleSet> tempUserStyle = RuleSet::create();
324 if (CSSStyleSheet* pageUserSheet = styleSheetCollection->pageUserSheet())
325 tempUserStyle->addRulesFromSheet(pageUserSheet->contents(), *m_medium, this);
326 collectRulesFromUserStyleSheets(styleSheetCollection->injectedUserStyleSheets(), *tempUserStyle);
327 collectRulesFromUserStyleSheets(styleSheetCollection->documentUserStyleSheets(), *tempUserStyle);
328 if (tempUserStyle->m_ruleCount > 0 || tempUserStyle->m_pageRules.size() > 0)
329 m_userStyle = tempUserStyle.release();
331 #if ENABLE(SVG_FONTS)
332 if (document->svgExtensions()) {
333 const HashSet<SVGFontFaceElement*>& svgFontFaceElements = document->svgExtensions()->svgFontFaceElements();
334 HashSet<SVGFontFaceElement*>::const_iterator end = svgFontFaceElements.end();
335 for (HashSet<SVGFontFaceElement*>::const_iterator it = svgFontFaceElements.begin(); it != end; ++it)
336 fontSelector()->addFontFaceRule((*it)->fontFaceRule());
340 appendAuthorStyleSheets(0, styleSheetCollection->activeAuthorStyleSheets());
343 void StyleResolver::collectRulesFromUserStyleSheets(const Vector<RefPtr<CSSStyleSheet> >& userSheets, RuleSet& userStyle)
345 for (unsigned i = 0; i < userSheets.size(); ++i) {
346 ASSERT(userSheets[i]->contents()->isUserStyleSheet());
347 userStyle.addRulesFromSheet(userSheets[i]->contents(), *m_medium, this);
351 static PassOwnPtr<RuleSet> makeRuleSet(const Vector<RuleFeature>& rules)
353 size_t size = rules.size();
356 OwnPtr<RuleSet> ruleSet = RuleSet::create();
357 for (size_t i = 0; i < size; ++i)
358 ruleSet->addRule(rules[i].rule, rules[i].selectorIndex, rules[i].hasDocumentSecurityOrigin ? RuleHasDocumentSecurityOrigin : RuleHasNoSpecialState);
359 ruleSet->shrinkToFit();
360 return ruleSet.release();
363 void StyleResolver::resetAuthorStyle()
365 m_authorStyle = RuleSet::create();
366 m_authorStyle->disableAutoShrinkToFit();
369 void StyleResolver::appendAuthorStyleSheets(unsigned firstNew, const Vector<RefPtr<CSSStyleSheet> >& styleSheets)
371 // This handles sheets added to the end of the stylesheet list only. In other cases the style resolver
372 // needs to be reconstructed. To handle insertions too the rule order numbers would need to be updated.
373 unsigned size = styleSheets.size();
374 for (unsigned i = firstNew; i < size; ++i) {
375 CSSStyleSheet* cssSheet = styleSheets[i].get();
376 ASSERT(!cssSheet->disabled());
377 if (cssSheet->mediaQueries() && !m_medium->eval(cssSheet->mediaQueries(), this))
379 StyleSheetContents* sheet = cssSheet->contents();
380 #if ENABLE(STYLE_SCOPED) || ENABLE(SHADOW_DOM)
381 if (const ContainerNode* scope = StyleScopeResolver::scopeFor(cssSheet)) {
382 ensureScopeResolver()->ensureRuleSetFor(scope)->addRulesFromSheet(sheet, *m_medium, this, scope);
387 m_authorStyle->addRulesFromSheet(sheet, *m_medium, this);
388 if (!m_styleRuleToCSSOMWrapperMap.isEmpty())
389 collectCSSOMWrappers(m_styleRuleToCSSOMWrapperMap, cssSheet);
391 m_authorStyle->shrinkToFit();
394 if (document()->renderer() && document()->renderer()->style())
395 document()->renderer()->style()->font().update(fontSelector());
397 #if ENABLE(CSS_DEVICE_ADAPTATION)
398 viewportStyleResolver()->resolve();
402 void StyleResolver::pushParentElement(Element* parent)
404 const ContainerNode* parentsParent = parent->parentOrHostElement();
406 // We are not always invoked consistently. For example, script execution can cause us to enter
407 // style recalc in the middle of tree building. We may also be invoked from somewhere within the tree.
408 // Reset the stack in this case, or if we see a new root element.
409 // Otherwise just push the new parent.
410 if (!parentsParent || m_selectorFilter.parentStackIsEmpty())
411 m_selectorFilter.setupParentStack(parent);
413 m_selectorFilter.pushParent(parent);
415 // Note: We mustn't skip ShadowRoot nodes for the scope stack.
417 m_scopeResolver->push(parent, parent->parentOrHostNode());
420 void StyleResolver::popParentElement(Element* parent)
422 // Note that we may get invoked for some random elements in some wacky cases during style resolve.
423 // Pause maintaining the stack in this case.
424 if (m_selectorFilter.parentStackIsConsistent(parent))
425 m_selectorFilter.popParent();
427 m_scopeResolver->pop(parent);
430 void StyleResolver::pushParentShadowRoot(const ShadowRoot* shadowRoot)
432 ASSERT(shadowRoot->host());
434 m_scopeResolver->push(shadowRoot, shadowRoot->host());
437 void StyleResolver::popParentShadowRoot(const ShadowRoot* shadowRoot)
439 ASSERT(shadowRoot->host());
441 m_scopeResolver->pop(shadowRoot);
444 // This is a simplified style setting function for keyframe styles
445 void StyleResolver::addKeyframeStyle(PassRefPtr<StyleRuleKeyframes> rule)
447 AtomicString s(rule->name());
448 m_keyframesRuleMap.set(s.impl(), rule);
451 StyleResolver::~StyleResolver()
453 m_fontSelector->clearDocument();
455 #if ENABLE(CSS_DEVICE_ADAPTATION)
456 m_viewportStyleResolver->clearDocument();
460 void StyleResolver::sweepMatchedPropertiesCache(Timer<StyleResolver>*)
462 // Look for cache entries containing a style declaration with a single ref and remove them.
463 // This may happen when an element attribute mutation causes it to generate a new inlineStyle()
464 // or presentationAttributeStyle(), potentially leaving this cache with the last ref on the old one.
465 Vector<unsigned, 16> toRemove;
466 MatchedPropertiesCache::iterator it = m_matchedPropertiesCache.begin();
467 MatchedPropertiesCache::iterator end = m_matchedPropertiesCache.end();
468 for (; it != end; ++it) {
469 Vector<MatchedProperties>& matchedProperties = it->value.matchedProperties;
470 for (size_t i = 0; i < matchedProperties.size(); ++i) {
471 if (matchedProperties[i].properties->hasOneRef()) {
472 toRemove.append(it->key);
477 for (size_t i = 0; i < toRemove.size(); ++i)
478 m_matchedPropertiesCache.remove(toRemove[i]);
480 m_matchedPropertiesCacheAdditionsSinceLastSweep = 0;
483 static StyleSheetContents* parseUASheet(const String& str)
485 StyleSheetContents* sheet = StyleSheetContents::create().leakRef(); // leak the sheet on purpose
486 sheet->parseString(str);
490 static StyleSheetContents* parseUASheet(const char* characters, unsigned size)
492 return parseUASheet(String(characters, size));
495 static void loadFullDefaultStyle()
497 if (simpleDefaultStyleSheet) {
498 ASSERT(defaultStyle);
499 ASSERT(defaultPrintStyle == defaultStyle);
501 simpleDefaultStyleSheet->deref();
502 defaultStyle = RuleSet::create().leakPtr();
503 defaultPrintStyle = RuleSet::create().leakPtr();
504 simpleDefaultStyleSheet = 0;
506 ASSERT(!defaultStyle);
507 defaultStyle = RuleSet::create().leakPtr();
508 defaultPrintStyle = RuleSet::create().leakPtr();
509 defaultQuirksStyle = RuleSet::create().leakPtr();
512 // Strict-mode rules.
513 String defaultRules = String(htmlUserAgentStyleSheet, sizeof(htmlUserAgentStyleSheet)) + RenderTheme::defaultTheme()->extraDefaultStyleSheet();
514 defaultStyleSheet = parseUASheet(defaultRules);
515 defaultStyle->addRulesFromSheet(defaultStyleSheet, screenEval());
516 defaultPrintStyle->addRulesFromSheet(defaultStyleSheet, printEval());
518 // Quirks-mode rules.
519 String quirksRules = String(quirksUserAgentStyleSheet, sizeof(quirksUserAgentStyleSheet)) + RenderTheme::defaultTheme()->extraQuirksStyleSheet();
520 quirksStyleSheet = parseUASheet(quirksRules);
521 defaultQuirksStyle->addRulesFromSheet(quirksStyleSheet, screenEval());
524 static void loadSimpleDefaultStyle()
526 ASSERT(!defaultStyle);
527 ASSERT(!simpleDefaultStyleSheet);
529 defaultStyle = RuleSet::create().leakPtr();
530 // There are no media-specific rules in the simple default style.
531 defaultPrintStyle = defaultStyle;
532 defaultQuirksStyle = RuleSet::create().leakPtr();
534 simpleDefaultStyleSheet = parseUASheet(simpleUserAgentStyleSheet, strlen(simpleUserAgentStyleSheet));
535 defaultStyle->addRulesFromSheet(simpleDefaultStyleSheet, screenEval());
537 // No need to initialize quirks sheet yet as there are no quirk rules for elements allowed in simple default style.
540 static RuleSet* viewSourceStyle()
542 if (!defaultViewSourceStyle) {
543 defaultViewSourceStyle = RuleSet::create().leakPtr();
544 defaultViewSourceStyle->addRulesFromSheet(parseUASheet(sourceUserAgentStyleSheet, sizeof(sourceUserAgentStyleSheet)), screenEval());
546 return defaultViewSourceStyle;
549 static void ensureDefaultStyleSheetsForElement(Element* element)
551 if (simpleDefaultStyleSheet && !elementCanUseSimpleDefaultStyle(element))
552 loadFullDefaultStyle();
555 if (element->isSVGElement() && !svgStyleSheet) {
557 svgStyleSheet = parseUASheet(svgUserAgentStyleSheet, sizeof(svgUserAgentStyleSheet));
558 defaultStyle->addRulesFromSheet(svgStyleSheet, screenEval());
559 defaultPrintStyle->addRulesFromSheet(svgStyleSheet, printEval());
564 if (element->isMathMLElement() && !mathMLStyleSheet) {
566 mathMLStyleSheet = parseUASheet(mathmlUserAgentStyleSheet, sizeof(mathmlUserAgentStyleSheet));
567 defaultStyle->addRulesFromSheet(mathMLStyleSheet, screenEval());
568 defaultPrintStyle->addRulesFromSheet(mathMLStyleSheet, printEval());
573 if (!mediaControlsStyleSheet && (element->hasTagName(videoTag) || element->hasTagName(audioTag))) {
574 String mediaRules = String(mediaControlsUserAgentStyleSheet, sizeof(mediaControlsUserAgentStyleSheet)) + RenderTheme::themeForPage(element->document()->page())->extraMediaControlsStyleSheet();
575 mediaControlsStyleSheet = parseUASheet(mediaRules);
576 defaultStyle->addRulesFromSheet(mediaControlsStyleSheet, screenEval());
577 defaultPrintStyle->addRulesFromSheet(mediaControlsStyleSheet, printEval());
581 #if ENABLE(FULLSCREEN_API)
582 if (!fullscreenStyleSheet && element->document()->webkitIsFullScreen()) {
583 String fullscreenRules = String(fullscreenUserAgentStyleSheet, sizeof(fullscreenUserAgentStyleSheet)) + RenderTheme::defaultTheme()->extraFullScreenStyleSheet();
584 fullscreenStyleSheet = parseUASheet(fullscreenRules);
585 defaultStyle->addRulesFromSheet(fullscreenStyleSheet, screenEval());
586 defaultQuirksStyle->addRulesFromSheet(fullscreenStyleSheet, screenEval());
590 ASSERT(defaultStyle->features().idsInRules.isEmpty());
591 ASSERT(mathMLStyleSheet || defaultStyle->features().siblingRules.isEmpty());
594 void StyleResolver::addMatchedProperties(MatchResult& matchResult, const StylePropertySet* properties, StyleRule* rule, unsigned linkMatchType, bool inRegionRule)
596 matchResult.matchedProperties.grow(matchResult.matchedProperties.size() + 1);
597 MatchedProperties& newProperties = matchResult.matchedProperties.last();
598 newProperties.properties = const_cast<StylePropertySet*>(properties);
599 newProperties.linkMatchType = linkMatchType;
600 newProperties.isInRegionRule = inRegionRule;
601 matchResult.matchedRules.append(rule);
604 inline void StyleResolver::addElementStyleProperties(MatchResult& result, const StylePropertySet* propertySet, bool isCacheable)
608 result.ranges.lastAuthorRule = result.matchedProperties.size();
609 if (result.ranges.firstAuthorRule == -1)
610 result.ranges.firstAuthorRule = result.ranges.lastAuthorRule;
611 addMatchedProperties(result, propertySet);
613 result.isCacheable = false;
616 class MatchingUARulesScope {
618 MatchingUARulesScope();
619 ~MatchingUARulesScope();
621 static bool isMatchingUARules();
624 static bool m_matchingUARules;
627 MatchingUARulesScope::MatchingUARulesScope()
629 ASSERT(!m_matchingUARules);
630 m_matchingUARules = true;
633 MatchingUARulesScope::~MatchingUARulesScope()
635 m_matchingUARules = false;
638 inline bool MatchingUARulesScope::isMatchingUARules()
640 return m_matchingUARules;
643 bool MatchingUARulesScope::m_matchingUARules = false;
645 void StyleResolver::collectMatchingRules(const MatchRequest& matchRequest, int& firstRuleIndex, int& lastRuleIndex)
647 ASSERT(matchRequest.ruleSet);
650 const AtomicString& pseudoId = m_element->shadowPseudoId();
651 if (!pseudoId.isEmpty()) {
652 ASSERT(m_styledElement);
653 collectMatchingRulesForList(matchRequest.ruleSet->shadowPseudoElementRules(pseudoId.impl()), matchRequest, firstRuleIndex, lastRuleIndex);
656 #if ENABLE(VIDEO_TRACK)
657 if (m_element->webVTTNodeType())
658 collectMatchingRulesForList(matchRequest.ruleSet->cuePseudoRules(), matchRequest, firstRuleIndex, lastRuleIndex);
660 // Check whether other types of rules are applicable in the current tree scope. Criteria for this:
662 // b) the tree scope allows author rules
663 // c) the rules comes from a scoped style sheet within the same tree scope
664 TreeScope* treeScope = m_element->treeScope();
665 if (!MatchingUARulesScope::isMatchingUARules()
666 && !treeScope->applyAuthorStyles()
667 && (!matchRequest.scope || matchRequest.scope->treeScope() != treeScope))
670 // We need to collect the rules for id, class, tag, and everything else into a buffer and
671 // then sort the buffer.
672 if (m_element->hasID())
673 collectMatchingRulesForList(matchRequest.ruleSet->idRules(m_element->idForStyleResolution().impl()), matchRequest, firstRuleIndex, lastRuleIndex);
674 if (m_styledElement && m_styledElement->hasClass()) {
675 for (size_t i = 0; i < m_styledElement->classNames().size(); ++i)
676 collectMatchingRulesForList(matchRequest.ruleSet->classRules(m_styledElement->classNames()[i].impl()), matchRequest, firstRuleIndex, lastRuleIndex);
679 if (m_element->isLink())
680 collectMatchingRulesForList(matchRequest.ruleSet->linkPseudoClassRules(), matchRequest, firstRuleIndex, lastRuleIndex);
681 if (m_selectorChecker.matchesFocusPseudoClass(m_element))
682 collectMatchingRulesForList(matchRequest.ruleSet->focusPseudoClassRules(), matchRequest, firstRuleIndex, lastRuleIndex);
683 collectMatchingRulesForList(matchRequest.ruleSet->tagRules(m_element->localName().impl()), matchRequest, firstRuleIndex, lastRuleIndex);
684 collectMatchingRulesForList(matchRequest.ruleSet->universalRules(), matchRequest, firstRuleIndex, lastRuleIndex);
687 void StyleResolver::collectMatchingRulesForRegion(const MatchRequest& matchRequest, int& firstRuleIndex, int& lastRuleIndex)
689 if (!m_regionForStyling)
692 unsigned size = matchRequest.ruleSet->m_regionSelectorsAndRuleSets.size();
693 for (unsigned i = 0; i < size; ++i) {
694 CSSSelector* regionSelector = matchRequest.ruleSet->m_regionSelectorsAndRuleSets.at(i).selector;
695 if (checkRegionSelector(regionSelector, static_cast<Element*>(m_regionForStyling->node()))) {
696 RuleSet* regionRules = matchRequest.ruleSet->m_regionSelectorsAndRuleSets.at(i).ruleSet.get();
698 collectMatchingRules(MatchRequest(regionRules, matchRequest.includeEmptyRules, matchRequest.scope), firstRuleIndex, lastRuleIndex);
703 void StyleResolver::sortAndTransferMatchedRules(MatchResult& result)
705 if (m_matchedRules.isEmpty())
710 if (m_selectorChecker.mode() == SelectorChecker::CollectingRules) {
712 m_ruleList = StaticCSSRuleList::create();
713 for (unsigned i = 0; i < m_matchedRules.size(); ++i)
714 m_ruleList->rules().append(m_matchedRules[i]->rule()->createCSSOMWrapper());
718 // Now transfer the set of matched rules over to our list of declarations.
719 // FIXME: This sucks, the inspector should get the style from the visited style itself.
720 bool swapVisitedUnvisited = InspectorInstrumentation::forcePseudoState(m_element, CSSSelector::PseudoVisited);
721 for (unsigned i = 0; i < m_matchedRules.size(); i++) {
722 if (m_style && m_matchedRules[i]->containsUncommonAttributeSelector())
723 m_style->setUnique();
724 unsigned linkMatchType = m_matchedRules[i]->linkMatchType();
725 if (swapVisitedUnvisited && linkMatchType && linkMatchType != SelectorChecker::MatchAll)
726 linkMatchType = (linkMatchType == SelectorChecker::MatchVisited) ? SelectorChecker::MatchLink : SelectorChecker::MatchVisited;
727 addMatchedProperties(result, m_matchedRules[i]->rule()->properties(), m_matchedRules[i]->rule(), linkMatchType, m_matchedRules[i]->isInRegionRule());
731 void StyleResolver::matchScopedAuthorRules(MatchResult& result, bool includeEmptyRules)
733 #if ENABLE(STYLE_SCOPED) || ENABLE(SHADOW_DOM)
734 if (!m_scopeResolver)
737 // Match scoped author rules by traversing the scoped element stack (rebuild it if it got inconsistent).
738 if (m_scopeResolver->hasScopedStyles() && m_scopeResolver->ensureStackConsistency(m_element)) {
739 bool applyAuthorStyles = m_element->treeScope()->applyAuthorStyles();
740 bool documentScope = true;
741 unsigned scopeSize = m_scopeResolver->stackSize();
742 for (unsigned i = 0; i < scopeSize; ++i) {
743 m_matchedRules.clear();
744 result.ranges.lastAuthorRule = result.matchedProperties.size() - 1;
746 const StyleScopeResolver::StackFrame& frame = m_scopeResolver->stackFrameAt(i);
747 documentScope = documentScope && !frame.m_scope->isInShadowTree();
749 if (!applyAuthorStyles)
752 if (!m_scopeResolver->matchesStyleBounds(frame))
756 MatchRequest matchRequest(frame.m_ruleSet, includeEmptyRules, frame.m_scope);
757 collectMatchingRules(matchRequest, result.ranges.firstAuthorRule, result.ranges.lastAuthorRule);
758 collectMatchingRulesForRegion(matchRequest, result.ranges.firstAuthorRule, result.ranges.lastAuthorRule);
759 sortAndTransferMatchedRules(result);
763 matchHostRules(result, includeEmptyRules);
765 UNUSED_PARAM(result);
766 UNUSED_PARAM(includeEmptyRules);
770 inline bool StyleResolver::styleSharingCandidateMatchesHostRules()
772 #if ENABLE(SHADOW_DOM)
773 return m_scopeResolver && m_scopeResolver->styleSharingCandidateMatchesHostRules(m_element);
779 void StyleResolver::matchHostRules(MatchResult& result, bool includeEmptyRules)
781 #if ENABLE(SHADOW_DOM)
782 ASSERT(m_scopeResolver);
784 m_matchedRules.clear();
785 result.ranges.lastAuthorRule = result.matchedProperties.size() - 1;
787 Vector<RuleSet*> matchedRules;
788 m_scopeResolver->matchHostRules(m_element, matchedRules);
789 if (matchedRules.isEmpty())
792 for (unsigned i = matchedRules.size(); i > 0; --i)
793 collectMatchingRules(MatchRequest(matchedRules.at(i-1), includeEmptyRules, m_element), result.ranges.firstAuthorRule, result.ranges.lastAuthorRule);
794 sortAndTransferMatchedRules(result);
796 UNUSED_PARAM(result);
797 UNUSED_PARAM(includeEmptyRules);
801 void StyleResolver::matchAuthorRules(MatchResult& result, bool includeEmptyRules)
803 m_matchedRules.clear();
804 result.ranges.lastAuthorRule = result.matchedProperties.size() - 1;
809 // Match global author rules.
810 MatchRequest matchRequest(m_authorStyle.get(), includeEmptyRules);
811 collectMatchingRules(matchRequest, result.ranges.firstAuthorRule, result.ranges.lastAuthorRule);
812 collectMatchingRulesForRegion(matchRequest, result.ranges.firstAuthorRule, result.ranges.lastAuthorRule);
813 sortAndTransferMatchedRules(result);
815 matchScopedAuthorRules(result, includeEmptyRules);
818 void StyleResolver::matchUserRules(MatchResult& result, bool includeEmptyRules)
823 m_matchedRules.clear();
825 result.ranges.lastUserRule = result.matchedProperties.size() - 1;
826 MatchRequest matchRequest(m_userStyle.get(), includeEmptyRules);
827 collectMatchingRules(matchRequest, result.ranges.firstUserRule, result.ranges.lastUserRule);
828 collectMatchingRulesForRegion(matchRequest, result.ranges.firstUserRule, result.ranges.lastUserRule);
830 sortAndTransferMatchedRules(result);
833 void StyleResolver::matchUARules(MatchResult& result, RuleSet* rules)
835 m_matchedRules.clear();
837 result.ranges.lastUARule = result.matchedProperties.size() - 1;
838 collectMatchingRules(MatchRequest(rules), result.ranges.firstUARule, result.ranges.lastUARule);
840 sortAndTransferMatchedRules(result);
843 void StyleResolver::collectMatchingRulesForList(const Vector<RuleData>* rules, const MatchRequest& matchRequest, int& firstRuleIndex, int& lastRuleIndex)
848 // In some cases we may end up looking up style for random elements in the middle of a recursive tree resolve.
849 // Ancestor identifier filter won't be up-to-date in that case and we can't use the fast path.
850 bool canUseFastReject = m_selectorFilter.parentStackIsConsistent(m_parentNode);
852 unsigned size = rules->size();
853 for (unsigned i = 0; i < size; ++i) {
854 const RuleData& ruleData = rules->at(i);
855 if (canUseFastReject && m_selectorFilter.fastRejectSelector<RuleData::maximumIdentifierCount>(ruleData.descendantSelectorIdentifierHashes()))
858 StyleRule* rule = ruleData.rule();
859 InspectorInstrumentationCookie cookie = InspectorInstrumentation::willMatchRule(document(), rule, this);
860 if (ruleMatches(ruleData, matchRequest.scope)) {
861 // If the rule has no properties to apply, then ignore it in the non-debug mode.
862 const StylePropertySet* properties = rule->properties();
863 if (!properties || (properties->isEmpty() && !matchRequest.includeEmptyRules)) {
864 InspectorInstrumentation::didMatchRule(cookie, false);
867 // FIXME: Exposing the non-standard getMatchedCSSRules API to web is the only reason this is needed.
868 if (m_sameOriginOnly && !ruleData.hasDocumentSecurityOrigin()) {
869 InspectorInstrumentation::didMatchRule(cookie, false);
872 // If we're matching normal rules, set a pseudo bit if
873 // we really just matched a pseudo-element.
874 if (m_dynamicPseudo != NOPSEUDO && m_pseudoStyle == NOPSEUDO) {
875 if (m_selectorChecker.mode() == SelectorChecker::CollectingRules) {
876 InspectorInstrumentation::didMatchRule(cookie, false);
879 if (m_dynamicPseudo < FIRST_INTERNAL_PSEUDOID)
880 m_style->setHasPseudoStyle(m_dynamicPseudo);
882 // Update our first/last rule indices in the matched rules array.
884 if (firstRuleIndex == -1)
885 firstRuleIndex = lastRuleIndex;
887 // Add this rule to our list of matched rules.
888 addMatchedRule(&ruleData);
889 InspectorInstrumentation::didMatchRule(cookie, true);
893 InspectorInstrumentation::didMatchRule(cookie, false);
897 static inline bool compareRules(const RuleData* r1, const RuleData* r2)
899 unsigned specificity1 = r1->specificity();
900 unsigned specificity2 = r2->specificity();
901 return (specificity1 == specificity2) ? r1->position() < r2->position() : specificity1 < specificity2;
904 void StyleResolver::sortMatchedRules()
906 std::sort(m_matchedRules.begin(), m_matchedRules.end(), compareRules);
909 void StyleResolver::matchAllRules(MatchResult& result, bool includeSMILProperties)
911 matchUARules(result);
913 // Now we check user sheet rules.
914 if (m_matchAuthorAndUserStyles)
915 matchUserRules(result, false);
917 // Now check author rules, beginning first with presentational attributes mapped from HTML.
918 if (m_styledElement) {
919 addElementStyleProperties(result, m_styledElement->presentationAttributeStyle());
921 // Now we check additional mapped declarations.
922 // Tables and table cells share an additional mapped rule that must be applied
923 // after all attributes, since their mapped style depends on the values of multiple attributes.
924 addElementStyleProperties(result, m_styledElement->additionalPresentationAttributeStyle());
926 if (m_styledElement->isHTMLElement()) {
928 TextDirection textDirection = toHTMLElement(m_styledElement)->directionalityIfhasDirAutoAttribute(isAuto);
930 addMatchedProperties(result, textDirection == LTR ? leftToRightDeclaration() : rightToLeftDeclaration());
934 // Check the rules in author sheets next.
935 if (m_matchAuthorAndUserStyles)
936 matchAuthorRules(result, false);
938 // Now check our inline style attribute.
939 if (m_matchAuthorAndUserStyles && m_styledElement && m_styledElement->inlineStyle()) {
940 // Inline style is immutable as long as there is no CSSOM wrapper.
941 // FIXME: Media control shadow trees seem to have problems with caching.
942 bool isInlineStyleCacheable = !m_styledElement->inlineStyle()->isMutable() && !m_styledElement->isInShadowTree();
944 addElementStyleProperties(result, m_styledElement->inlineStyle(), isInlineStyleCacheable);
948 // Now check SMIL animation override style.
949 if (includeSMILProperties && m_matchAuthorAndUserStyles && m_styledElement && m_styledElement->isSVGElement())
950 addElementStyleProperties(result, static_cast<SVGElement*>(m_styledElement)->animatedSMILStyleProperties(), false /* isCacheable */);
952 UNUSED_PARAM(includeSMILProperties);
956 bool StyleResolver::classNamesAffectedByRules(const SpaceSplitString& classNames) const
958 for (unsigned i = 0; i < classNames.size(); ++i) {
959 if (m_features.classesInRules.contains(classNames[i].impl()))
965 inline void StyleResolver::initElement(Element* e)
967 if (m_element != e) {
969 m_styledElement = m_element && m_element->isStyledElement() ? static_cast<StyledElement*>(m_element) : 0;
970 m_elementLinkState = document()->visitedLinkState()->determineLinkState(m_element);
971 if (e && e == e->document()->documentElement()) {
972 e->document()->setDirectionSetOnDocumentElement(false);
973 e->document()->setWritingModeSetOnDocumentElement(false);
978 inline void StyleResolver::initForStyleResolve(Element* e, RenderStyle* parentStyle, PseudoId pseudoID)
980 m_pseudoStyle = pseudoID;
983 NodeRenderingContext context(e);
984 m_parentNode = context.parentNodeForRenderingAndStyle();
985 m_parentStyle = context.resetStyleInheritance() ? 0 :
986 parentStyle ? parentStyle :
987 m_parentNode ? m_parentNode->renderStyle() : 0;
988 m_distributedToInsertionPoint = context.insertionPoint();
991 m_parentStyle = parentStyle;
992 m_distributedToInsertionPoint = false;
995 Node* docElement = e ? e->document()->documentElement() : 0;
996 RenderStyle* docStyle = document()->renderStyle();
997 m_rootElementStyle = docElement && e != docElement ? docElement->renderStyle() : docStyle;
1001 m_pendingImageProperties.clear();
1005 m_fontDirty = false;
1008 static const unsigned cStyleSearchThreshold = 10;
1009 static const unsigned cStyleSearchLevelThreshold = 10;
1011 Node* StyleResolver::locateCousinList(Element* parent, unsigned& visitedNodeCount) const
1013 if (visitedNodeCount >= cStyleSearchThreshold * cStyleSearchLevelThreshold)
1015 if (!parent || !parent->isStyledElement())
1017 if (parent->hasScopedHTMLStyleChild())
1019 StyledElement* p = static_cast<StyledElement*>(parent);
1020 if (p->inlineStyle())
1023 if (p->isSVGElement() && static_cast<SVGElement*>(p)->animatedSMILStyleProperties())
1026 if (p->hasID() && m_features.idsInRules.contains(p->idForStyleResolution().impl()))
1029 RenderStyle* parentStyle = p->renderStyle();
1030 unsigned subcount = 0;
1031 Node* thisCousin = p;
1032 Node* currentNode = p->previousSibling();
1034 // Reserve the tries for this level. This effectively makes sure that the algorithm
1035 // will never go deeper than cStyleSearchLevelThreshold levels into recursion.
1036 visitedNodeCount += cStyleSearchThreshold;
1037 while (thisCousin) {
1038 while (currentNode) {
1040 if (currentNode->renderStyle() == parentStyle && currentNode->lastChild()) {
1041 // Adjust for unused reserved tries.
1042 visitedNodeCount -= cStyleSearchThreshold - subcount;
1043 return currentNode->lastChild();
1045 if (subcount >= cStyleSearchThreshold)
1047 currentNode = currentNode->previousSibling();
1049 currentNode = locateCousinList(thisCousin->parentElement(), visitedNodeCount);
1050 thisCousin = currentNode;
1056 bool StyleResolver::styleSharingCandidateMatchesRuleSet(RuleSet* ruleSet)
1060 m_matchedRules.clear();
1062 int firstRuleIndex = -1, lastRuleIndex = -1;
1063 m_selectorChecker.setMode(SelectorChecker::SharingRules);
1064 collectMatchingRules(MatchRequest(ruleSet), firstRuleIndex, lastRuleIndex);
1065 m_selectorChecker.setMode(SelectorChecker::ResolvingStyle);
1066 if (m_matchedRules.isEmpty())
1068 m_matchedRules.clear();
1072 bool StyleResolver::canShareStyleWithControl(StyledElement* element) const
1074 HTMLInputElement* thisInputElement = element->toInputElement();
1075 HTMLInputElement* otherInputElement = m_element->toInputElement();
1077 if (!thisInputElement || !otherInputElement)
1080 if (thisInputElement->attributeData() != otherInputElement->attributeData()) {
1081 if (thisInputElement->fastGetAttribute(typeAttr) != otherInputElement->fastGetAttribute(typeAttr))
1083 if (thisInputElement->fastGetAttribute(readonlyAttr) != otherInputElement->fastGetAttribute(readonlyAttr))
1087 if (thisInputElement->isAutofilled() != otherInputElement->isAutofilled())
1089 if (thisInputElement->shouldAppearChecked() != otherInputElement->shouldAppearChecked())
1091 if (thisInputElement->isIndeterminate() != otherInputElement->isIndeterminate())
1093 if (thisInputElement->isRequired() != otherInputElement->isRequired())
1096 if (element->isEnabledFormControl() != m_element->isEnabledFormControl())
1099 if (element->isDefaultButtonForForm() != m_element->isDefaultButtonForForm())
1102 if (m_element->document()->containsValidityStyleRules()) {
1103 bool willValidate = element->willValidate();
1105 if (willValidate != m_element->willValidate())
1108 if (willValidate && (element->isValidFormControlElement() != m_element->isValidFormControlElement()))
1111 if (element->isInRange() != m_element->isInRange())
1114 if (element->isOutOfRange() != m_element->isOutOfRange())
1121 static inline bool elementHasDirectionAuto(Element* element)
1123 // FIXME: This line is surprisingly hot, we may wish to inline hasDirectionAuto into StyleResolver.
1124 return element->isHTMLElement() && toHTMLElement(element)->hasDirectionAuto();
1127 bool StyleResolver::sharingCandidateHasIdenticalStyleAffectingAttributes(StyledElement* sharingCandidate) const
1129 if (m_element->attributeData() == sharingCandidate->attributeData())
1131 if (m_element->fastGetAttribute(XMLNames::langAttr) != sharingCandidate->fastGetAttribute(XMLNames::langAttr))
1133 if (m_element->fastGetAttribute(langAttr) != sharingCandidate->fastGetAttribute(langAttr))
1136 if (!m_elementAffectedByClassRules) {
1137 if (sharingCandidate->hasClass() && classNamesAffectedByRules(sharingCandidate->classNames()))
1139 } else if (sharingCandidate->hasClass()) {
1141 // SVG elements require a (slow!) getAttribute comparision because "class" is an animatable attribute for SVG.
1142 if (m_element->isSVGElement()) {
1143 if (m_element->getAttribute(classAttr) != sharingCandidate->getAttribute(classAttr))
1147 if (m_element->classNames() != sharingCandidate->classNames())
1155 if (m_styledElement->presentationAttributeStyle() != sharingCandidate->presentationAttributeStyle())
1158 #if ENABLE(PROGRESS_ELEMENT)
1159 if (m_element->hasTagName(progressTag)) {
1160 if (static_cast<HTMLProgressElement*>(m_element)->isDeterminate() != static_cast<HTMLProgressElement*>(sharingCandidate)->isDeterminate())
1168 bool StyleResolver::canShareStyleWithElement(StyledElement* element) const
1170 RenderStyle* style = element->renderStyle();
1174 if (style->unique())
1176 if (element->tagQName() != m_element->tagQName())
1178 if (element->inlineStyle())
1180 if (element->needsStyleRecalc())
1183 if (element->isSVGElement() && static_cast<SVGElement*>(element)->animatedSMILStyleProperties())
1186 if (element->isLink() != m_element->isLink())
1188 if (element->hovered() != m_element->hovered())
1190 if (element->active() != m_element->active())
1192 if (element->focused() != m_element->focused())
1194 if (element->shadowPseudoId() != m_element->shadowPseudoId())
1196 if (element == element->document()->cssTarget())
1198 if (!sharingCandidateHasIdenticalStyleAffectingAttributes(element))
1200 if (element->additionalPresentationAttributeStyle() != m_styledElement->additionalPresentationAttributeStyle())
1203 if (element->hasID() && m_features.idsInRules.contains(element->idForStyleResolution().impl()))
1205 if (element->hasScopedHTMLStyleChild())
1208 // FIXME: We should share style for option and optgroup whenever possible.
1209 // Before doing so, we need to resolve issues in HTMLSelectElement::recalcListItems
1210 // and RenderMenuList::setText. See also https://bugs.webkit.org/show_bug.cgi?id=88405
1211 if (element->hasTagName(optionTag) || element->hasTagName(optgroupTag))
1214 bool isControl = element->isFormControlElement();
1216 if (isControl != m_element->isFormControlElement())
1219 if (isControl && !canShareStyleWithControl(element))
1222 if (style->transitions() || style->animations())
1225 #if USE(ACCELERATED_COMPOSITING)
1226 // Turn off style sharing for elements that can gain layers for reasons outside of the style system.
1227 // See comments in RenderObject::setStyle().
1228 if (element->hasTagName(iframeTag) || element->hasTagName(frameTag) || element->hasTagName(embedTag) || element->hasTagName(objectTag) || element->hasTagName(appletTag) || element->hasTagName(canvasTag)
1229 #if ENABLE(PLUGIN_PROXY_FOR_VIDEO)
1230 // With proxying, the media elements are backed by a RenderEmbeddedObject.
1231 || element->hasTagName(videoTag) || element->hasTagName(audioTag)
1237 if (elementHasDirectionAuto(element))
1240 if (element->isLink() && m_elementLinkState != style->insideLink())
1243 #if ENABLE(VIDEO_TRACK)
1244 if (element->webVTTNodeType() != m_element->webVTTNodeType())
1248 #if ENABLE(FULLSCREEN_API)
1249 if (element == element->document()->webkitCurrentFullScreenElement() || m_element == m_element->document()->webkitCurrentFullScreenElement())
1255 inline StyledElement* StyleResolver::findSiblingForStyleSharing(Node* node, unsigned& count) const
1257 for (; node; node = node->previousSibling()) {
1258 if (!node->isStyledElement())
1260 if (canShareStyleWithElement(static_cast<StyledElement*>(node)))
1262 if (count++ == cStyleSearchThreshold)
1265 return static_cast<StyledElement*>(node);
1268 static inline bool parentElementPreventsSharing(const Element* parentElement)
1272 return parentElement->childrenAffectedByPositionalRules()
1273 || parentElement->childrenAffectedByFirstChildRules()
1274 || parentElement->childrenAffectedByLastChildRules()
1275 || parentElement->childrenAffectedByDirectAdjacentRules();
1278 RenderStyle* StyleResolver::locateSharedStyle()
1280 if (!m_styledElement || !m_parentStyle)
1282 // If the element has inline style it is probably unique.
1283 if (m_styledElement->inlineStyle())
1286 if (m_styledElement->isSVGElement() && static_cast<SVGElement*>(m_styledElement)->animatedSMILStyleProperties())
1289 // Ids stop style sharing if they show up in the stylesheets.
1290 if (m_styledElement->hasID() && m_features.idsInRules.contains(m_styledElement->idForStyleResolution().impl()))
1292 if (parentElementPreventsSharing(m_element->parentElement()))
1294 if (m_styledElement->hasScopedHTMLStyleChild())
1296 if (m_element == m_element->document()->cssTarget())
1298 if (elementHasDirectionAuto(m_element))
1301 // Cache whether m_element is affected by any known class selectors.
1302 // FIXME: This shouldn't be a member variable. The style sharing code could be factored out of StyleResolver.
1303 m_elementAffectedByClassRules = m_element && m_element->hasClass() && classNamesAffectedByRules(m_element->classNames());
1305 // Check previous siblings and their cousins.
1307 unsigned visitedNodeCount = 0;
1308 StyledElement* shareElement = 0;
1309 Node* cousinList = m_styledElement->previousSibling();
1310 while (cousinList) {
1311 shareElement = findSiblingForStyleSharing(cousinList, count);
1314 cousinList = locateCousinList(cousinList->parentElement(), visitedNodeCount);
1317 // If we have exhausted all our budget or our cousins.
1321 // Can't share if sibling rules apply. This is checked at the end as it should rarely fail.
1322 if (styleSharingCandidateMatchesRuleSet(m_siblingRuleSet.get()))
1324 // Can't share if attribute rules apply.
1325 if (styleSharingCandidateMatchesRuleSet(m_uncommonAttributeRuleSet.get()))
1327 // Can't share if @host @-rules apply.
1328 if (styleSharingCandidateMatchesHostRules())
1330 // Tracking child index requires unique style for each node. This may get set by the sibling rule match above.
1331 if (parentElementPreventsSharing(m_element->parentElement()))
1333 return shareElement->renderStyle();
1336 void StyleResolver::matchUARules(MatchResult& result)
1338 MatchingUARulesScope scope;
1340 // First we match rules from the user agent sheet.
1341 if (simpleDefaultStyleSheet)
1342 result.isCacheable = false;
1343 RuleSet* userAgentStyleSheet = m_medium->mediaTypeMatchSpecific("print")
1344 ? defaultPrintStyle : defaultStyle;
1345 matchUARules(result, userAgentStyleSheet);
1347 // In quirks mode, we match rules from the quirks user agent sheet.
1348 if (!m_selectorChecker.strictParsing())
1349 matchUARules(result, defaultQuirksStyle);
1351 // 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.
1352 if (document()->isViewSource())
1353 matchUARules(result, viewSourceStyle());
1356 static void setStylesForPaginationMode(Pagination::Mode paginationMode, RenderStyle* style)
1358 if (paginationMode == Pagination::Unpaginated)
1361 switch (paginationMode) {
1362 case Pagination::LeftToRightPaginated:
1363 style->setColumnAxis(HorizontalColumnAxis);
1364 if (style->isHorizontalWritingMode())
1365 style->setColumnProgression(style->isLeftToRightDirection() ? NormalColumnProgression : ReverseColumnProgression);
1367 style->setColumnProgression(style->isFlippedBlocksWritingMode() ? ReverseColumnProgression : NormalColumnProgression);
1369 case Pagination::RightToLeftPaginated:
1370 style->setColumnAxis(HorizontalColumnAxis);
1371 if (style->isHorizontalWritingMode())
1372 style->setColumnProgression(style->isLeftToRightDirection() ? ReverseColumnProgression : NormalColumnProgression);
1374 style->setColumnProgression(style->isFlippedBlocksWritingMode() ? NormalColumnProgression : ReverseColumnProgression);
1376 case Pagination::TopToBottomPaginated:
1377 style->setColumnAxis(VerticalColumnAxis);
1378 if (style->isHorizontalWritingMode())
1379 style->setColumnProgression(style->isFlippedBlocksWritingMode() ? ReverseColumnProgression : NormalColumnProgression);
1381 style->setColumnProgression(style->isLeftToRightDirection() ? NormalColumnProgression : ReverseColumnProgression);
1383 case Pagination::BottomToTopPaginated:
1384 style->setColumnAxis(VerticalColumnAxis);
1385 if (style->isHorizontalWritingMode())
1386 style->setColumnProgression(style->isFlippedBlocksWritingMode() ? NormalColumnProgression : ReverseColumnProgression);
1388 style->setColumnProgression(style->isLeftToRightDirection() ? ReverseColumnProgression : NormalColumnProgression);
1390 case Pagination::Unpaginated:
1391 ASSERT_NOT_REACHED();
1396 static void getFontAndGlyphOrientation(const RenderStyle* style, FontOrientation& fontOrientation, NonCJKGlyphOrientation& glyphOrientation)
1398 if (style->isHorizontalWritingMode()) {
1399 fontOrientation = Horizontal;
1400 glyphOrientation = NonCJKGlyphOrientationVerticalRight;
1404 switch (style->textOrientation()) {
1405 case TextOrientationVerticalRight:
1406 fontOrientation = Vertical;
1407 glyphOrientation = NonCJKGlyphOrientationVerticalRight;
1409 case TextOrientationUpright:
1410 fontOrientation = Vertical;
1411 glyphOrientation = NonCJKGlyphOrientationUpright;
1413 case TextOrientationSideways:
1414 if (style->writingMode() == LeftToRightWritingMode) {
1415 // FIXME: This should map to sideways-left, which is not supported yet.
1416 fontOrientation = Vertical;
1417 glyphOrientation = NonCJKGlyphOrientationVerticalRight;
1420 fontOrientation = Horizontal;
1421 glyphOrientation = NonCJKGlyphOrientationVerticalRight;
1423 case TextOrientationSidewaysRight:
1424 fontOrientation = Horizontal;
1425 glyphOrientation = NonCJKGlyphOrientationVerticalRight;
1428 ASSERT_NOT_REACHED();
1429 fontOrientation = Horizontal;
1430 glyphOrientation = NonCJKGlyphOrientationVerticalRight;
1435 PassRefPtr<RenderStyle> StyleResolver::styleForDocument(Document* document, CSSFontSelector* fontSelector)
1437 Frame* frame = document->frame();
1439 // HTML5 states that seamless iframes should replace default CSS values
1440 // with values inherited from the containing iframe element. However,
1441 // some values (such as the case of designMode = "on") still need to
1442 // be set by this "document style".
1443 RefPtr<RenderStyle> documentStyle = RenderStyle::create();
1444 bool seamlessWithParent = document->shouldDisplaySeamlesslyWithParent();
1445 if (seamlessWithParent) {
1446 RenderStyle* iframeStyle = document->seamlessParentIFrame()->renderStyle();
1448 documentStyle->inheritFrom(iframeStyle);
1451 // FIXME: It's not clear which values below we want to override in the seamless case!
1452 documentStyle->setDisplay(BLOCK);
1453 if (!seamlessWithParent) {
1454 documentStyle->setRTLOrdering(document->visuallyOrdered() ? VisualOrder : LogicalOrder);
1455 documentStyle->setZoom(frame && !document->printing() ? frame->pageZoomFactor() : 1);
1456 documentStyle->setPageScaleTransform(frame ? frame->frameScaleFactor() : 1);
1457 documentStyle->setLocale(document->contentLanguage());
1459 // This overrides any -webkit-user-modify inherited from the parent iframe.
1460 documentStyle->setUserModify(document->inDesignMode() ? READ_WRITE : READ_ONLY);
1462 Element* docElement = document->documentElement();
1463 RenderObject* docElementRenderer = docElement ? docElement->renderer() : 0;
1464 if (docElementRenderer) {
1465 // Use the direction and writing-mode of the body to set the
1466 // viewport's direction and writing-mode unless the property is set on the document element.
1467 // If there is no body, then use the document element.
1468 RenderObject* bodyRenderer = document->body() ? document->body()->renderer() : 0;
1469 if (bodyRenderer && !document->writingModeSetOnDocumentElement())
1470 documentStyle->setWritingMode(bodyRenderer->style()->writingMode());
1472 documentStyle->setWritingMode(docElementRenderer->style()->writingMode());
1473 if (bodyRenderer && !document->directionSetOnDocumentElement())
1474 documentStyle->setDirection(bodyRenderer->style()->direction());
1476 documentStyle->setDirection(docElementRenderer->style()->direction());
1480 if (FrameView* frameView = frame->view()) {
1481 const Pagination& pagination = frameView->pagination();
1482 if (pagination.mode != Pagination::Unpaginated) {
1483 setStylesForPaginationMode(pagination.mode, documentStyle.get());
1484 documentStyle->setColumnGap(pagination.gap);
1485 if (RenderView* view = document->renderView()) {
1486 if (view->hasColumns())
1487 view->updateColumnInfoFromStyle(documentStyle.get());
1493 // Seamless iframes want to inherit their font from their parent iframe, so early return before setting the font.
1494 if (seamlessWithParent)
1495 return documentStyle.release();
1497 FontDescription fontDescription;
1498 fontDescription.setScript(localeToScriptCodeForFontSelection(documentStyle->locale()));
1499 if (Settings* settings = document->settings()) {
1500 fontDescription.setUsePrinterFont(document->printing() || !settings->screenFontSubstitutionEnabled());
1501 fontDescription.setRenderingMode(settings->fontRenderingMode());
1502 const AtomicString& standardFont = settings->standardFontFamily(fontDescription.script());
1503 if (!standardFont.isEmpty()) {
1504 fontDescription.setGenericFamily(FontDescription::StandardFamily);
1505 fontDescription.firstFamily().setFamily(standardFont);
1506 fontDescription.firstFamily().appendFamily(0);
1508 fontDescription.setKeywordSize(CSSValueMedium - CSSValueXxSmall + 1);
1509 int size = StyleResolver::fontSizeForKeyword(document, CSSValueMedium, false);
1510 fontDescription.setSpecifiedSize(size);
1511 bool useSVGZoomRules = document->isSVGDocument();
1512 fontDescription.setComputedSize(StyleResolver::getComputedSizeFromSpecifiedSize(document, documentStyle.get(), fontDescription.isAbsoluteSize(), size, useSVGZoomRules));
1514 fontDescription.setUsePrinterFont(document->printing());
1516 FontOrientation fontOrientation;
1517 NonCJKGlyphOrientation glyphOrientation;
1518 getFontAndGlyphOrientation(documentStyle.get(), fontOrientation, glyphOrientation);
1519 fontDescription.setOrientation(fontOrientation);
1520 fontDescription.setNonCJKGlyphOrientation(glyphOrientation);
1522 documentStyle->setFontDescription(fontDescription);
1523 documentStyle->font().update(fontSelector);
1525 return documentStyle.release();
1528 static inline bool isAtShadowBoundary(const Element* element)
1532 ContainerNode* parentNode = element->parentNode();
1533 return parentNode && parentNode->isShadowRoot();
1536 PassRefPtr<RenderStyle> StyleResolver::styleForElement(Element* element, RenderStyle* defaultParent,
1537 StyleSharingBehavior sharingBehavior, RuleMatchingBehavior matchingBehavior, RenderRegion* regionForStyling)
1539 // Once an element has a renderer, we don't try to destroy it, since otherwise the renderer
1540 // will vanish if a style recalc happens during loading.
1541 if (sharingBehavior == AllowStyleSharing && !element->document()->haveStylesheetsLoaded() && !element->renderer()) {
1542 if (!s_styleNotYetAvailable) {
1543 s_styleNotYetAvailable = RenderStyle::create().leakRef();
1544 s_styleNotYetAvailable->setDisplay(NONE);
1545 s_styleNotYetAvailable->font().update(m_fontSelector);
1547 element->document()->setHasNodesWithPlaceholderStyle();
1548 return s_styleNotYetAvailable;
1551 initElement(element);
1552 initForStyleResolve(element, defaultParent);
1553 m_regionForStyling = regionForStyling;
1554 if (sharingBehavior == AllowStyleSharing && !m_distributedToInsertionPoint) {
1555 RenderStyle* sharedStyle = locateSharedStyle();
1560 RefPtr<RenderStyle> cloneForParent;
1562 if (m_parentStyle) {
1563 m_style = RenderStyle::create();
1564 m_style->inheritFrom(m_parentStyle, isAtShadowBoundary(element) ? RenderStyle::AtShadowBoundary : RenderStyle::NotAtShadowBoundary);
1566 m_style = defaultStyleForElement();
1567 cloneForParent = RenderStyle::clone(style());
1568 m_parentStyle = cloneForParent.get();
1570 // contenteditable attribute (implemented by -webkit-user-modify) should
1571 // be propagated from shadow host to distributed node.
1572 if (m_distributedToInsertionPoint) {
1573 if (Element* parent = element->parentElement()) {
1574 if (RenderStyle* styleOfShadowHost = parent->renderStyle())
1575 m_style->setUserModify(styleOfShadowHost->userModify());
1579 if (element->isLink()) {
1580 m_style->setIsLink(true);
1581 m_style->setInsideLink(m_elementLinkState);
1584 ensureDefaultStyleSheetsForElement(element);
1586 MatchResult matchResult;
1587 if (matchingBehavior == MatchOnlyUserAgentRules)
1588 matchUARules(matchResult);
1590 matchAllRules(matchResult, matchingBehavior != MatchAllRulesExcludingSMIL);
1592 applyMatchedProperties(matchResult, element);
1594 // Clean up our style object's display and text decorations (among other fixups).
1595 adjustRenderStyle(style(), m_parentStyle, element);
1597 initElement(0); // Clear out for the next resolve.
1602 document()->didAccessStyleResolver();
1604 // Now return the style.
1605 return m_style.release();
1608 PassRefPtr<RenderStyle> StyleResolver::styleForKeyframe(const RenderStyle* elementStyle, const StyleKeyframe* keyframe, KeyframeValue& keyframeValue)
1611 if (keyframe->properties())
1612 addMatchedProperties(result, keyframe->properties());
1617 m_style = RenderStyle::clone(elementStyle);
1619 m_lineHeightValue = 0;
1621 // We don't need to bother with !important. Since there is only ever one
1622 // decl, there's nothing to override. So just add the first properties.
1623 bool inheritedOnly = false;
1624 if (keyframe->properties())
1625 applyMatchedProperties<HighPriorityProperties>(result, false, 0, result.matchedProperties.size() - 1, inheritedOnly);
1627 // If our font got dirtied, go ahead and update it now.
1630 // Line-height is set when we are sure we decided on the font-size
1631 if (m_lineHeightValue)
1632 applyProperty(CSSPropertyLineHeight, m_lineHeightValue);
1634 // Now do rest of the properties.
1635 if (keyframe->properties())
1636 applyMatchedProperties<LowPriorityProperties>(result, false, 0, result.matchedProperties.size() - 1, inheritedOnly);
1638 // If our font got dirtied by one of the non-essential font props,
1639 // go ahead and update it a second time.
1642 // Start loading resources referenced by this style.
1643 loadPendingResources();
1645 // Add all the animating properties to the keyframe.
1646 if (const StylePropertySet* styleDeclaration = keyframe->properties()) {
1647 unsigned propertyCount = styleDeclaration->propertyCount();
1648 for (unsigned i = 0; i < propertyCount; ++i) {
1649 CSSPropertyID property = styleDeclaration->propertyAt(i).id();
1650 // Timing-function within keyframes is special, because it is not animated; it just
1651 // describes the timing function between this keyframe and the next.
1652 if (property != CSSPropertyWebkitAnimationTimingFunction)
1653 keyframeValue.addProperty(property);
1657 document()->didAccessStyleResolver();
1659 return m_style.release();
1662 void StyleResolver::keyframeStylesForAnimation(Element* e, const RenderStyle* elementStyle, KeyframeList& list)
1666 // Get the keyframesRule for this name
1667 if (!e || list.animationName().isEmpty())
1670 m_keyframesRuleMap.checkConsistency();
1672 KeyframesRuleMap::iterator it = m_keyframesRuleMap.find(list.animationName().impl());
1673 if (it == m_keyframesRuleMap.end())
1676 const StyleRuleKeyframes* keyframesRule = it->value.get();
1678 // Construct and populate the style for each keyframe
1679 const Vector<RefPtr<StyleKeyframe> >& keyframes = keyframesRule->keyframes();
1680 for (unsigned i = 0; i < keyframes.size(); ++i) {
1681 // Apply the declaration to the style. This is a simplified version of the logic in styleForElement
1683 initForStyleResolve(e);
1685 const StyleKeyframe* keyframe = keyframes[i].get();
1687 KeyframeValue keyframeValue(0, 0);
1688 keyframeValue.setStyle(styleForKeyframe(elementStyle, keyframe, keyframeValue));
1690 // Add this keyframe style to all the indicated key times
1692 keyframe->getKeys(keys);
1693 for (size_t keyIndex = 0; keyIndex < keys.size(); ++keyIndex) {
1694 keyframeValue.setKey(keys[keyIndex]);
1695 list.insert(keyframeValue);
1699 // If the 0% keyframe is missing, create it (but only if there is at least one other keyframe)
1700 int initialListSize = list.size();
1701 if (initialListSize > 0 && list[0].key()) {
1702 static StyleKeyframe* zeroPercentKeyframe;
1703 if (!zeroPercentKeyframe) {
1704 zeroPercentKeyframe = StyleKeyframe::create().leakRef();
1705 zeroPercentKeyframe->setKeyText("0%");
1707 KeyframeValue keyframeValue(0, 0);
1708 keyframeValue.setStyle(styleForKeyframe(elementStyle, zeroPercentKeyframe, keyframeValue));
1709 list.insert(keyframeValue);
1712 // If the 100% keyframe is missing, create it (but only if there is at least one other keyframe)
1713 if (initialListSize > 0 && (list[list.size() - 1].key() != 1)) {
1714 static StyleKeyframe* hundredPercentKeyframe;
1715 if (!hundredPercentKeyframe) {
1716 hundredPercentKeyframe = StyleKeyframe::create().leakRef();
1717 hundredPercentKeyframe->setKeyText("100%");
1719 KeyframeValue keyframeValue(1, 0);
1720 keyframeValue.setStyle(styleForKeyframe(elementStyle, hundredPercentKeyframe, keyframeValue));
1721 list.insert(keyframeValue);
1725 PassRefPtr<RenderStyle> StyleResolver::pseudoStyleForElement(PseudoId pseudo, Element* e, RenderStyle* parentStyle)
1727 ASSERT(m_parentStyle);
1733 initForStyleResolve(e, parentStyle, pseudo);
1734 m_style = RenderStyle::create();
1735 m_style->inheritFrom(m_parentStyle);
1737 // Since we don't use pseudo-elements in any of our quirk/print user agent rules, don't waste time walking
1740 // Check UA, user and author rules.
1741 MatchResult matchResult;
1742 matchUARules(matchResult);
1744 if (m_matchAuthorAndUserStyles) {
1745 matchUserRules(matchResult, false);
1746 matchAuthorRules(matchResult, false);
1749 if (matchResult.matchedProperties.isEmpty())
1752 m_style->setStyleType(pseudo);
1754 applyMatchedProperties(matchResult, e);
1756 // Clean up our style object's display and text decorations (among other fixups).
1757 adjustRenderStyle(style(), parentStyle, 0);
1759 // Start loading resources referenced by this style.
1760 loadPendingResources();
1762 document()->didAccessStyleResolver();
1764 // Now return the style.
1765 return m_style.release();
1768 PassRefPtr<RenderStyle> StyleResolver::styleForPage(int pageIndex)
1770 initForStyleResolve(document()->documentElement()); // m_rootElementStyle will be set to the document style.
1772 m_style = RenderStyle::create();
1773 m_style->inheritFrom(m_rootElementStyle);
1775 const bool isLeft = isLeftPage(pageIndex);
1776 const bool isFirst = isFirstPage(pageIndex);
1777 const String page = pageName(pageIndex);
1780 matchPageRules(result, defaultPrintStyle, isLeft, isFirst, page);
1781 matchPageRules(result, m_userStyle.get(), isLeft, isFirst, page);
1782 // Only consider the global author RuleSet for @page rules, as per the HTML5 spec.
1783 matchPageRules(result, m_authorStyle.get(), isLeft, isFirst, page);
1784 m_lineHeightValue = 0;
1785 bool inheritedOnly = false;
1786 #if ENABLE(CSS_VARIABLES)
1787 applyMatchedProperties<VariableDefinitions>(result, false, 0, result.matchedProperties.size() - 1, inheritedOnly);
1789 applyMatchedProperties<HighPriorityProperties>(result, false, 0, result.matchedProperties.size() - 1, inheritedOnly);
1791 // If our font got dirtied, go ahead and update it now.
1794 // Line-height is set when we are sure we decided on the font-size.
1795 if (m_lineHeightValue)
1796 applyProperty(CSSPropertyLineHeight, m_lineHeightValue);
1798 applyMatchedProperties<LowPriorityProperties>(result, false, 0, result.matchedProperties.size() - 1, inheritedOnly);
1800 // Start loading resources referenced by this style.
1801 loadPendingResources();
1803 document()->didAccessStyleResolver();
1805 // Now return the style.
1806 return m_style.release();
1809 PassRefPtr<RenderStyle> StyleResolver::defaultStyleForElement()
1811 m_style = RenderStyle::create();
1812 // Make sure our fonts are initialized if we don't inherit them from our parent style.
1813 if (Settings* settings = documentSettings()) {
1814 initializeFontStyle(settings);
1815 m_style->font().update(fontSelector());
1817 m_style->font().update(0);
1819 return m_style.release();
1822 PassRefPtr<RenderStyle> StyleResolver::styleForText(Text* textNode)
1826 NodeRenderingContext context(textNode);
1827 Node* parentNode = context.parentNodeForRenderingAndStyle();
1828 return context.resetStyleInheritance() || !parentNode ?
1829 defaultStyleForElement() : parentNode->renderStyle();
1832 static void addIntrinsicMargins(RenderStyle* style)
1834 // Intrinsic margin value.
1835 const int intrinsicMargin = 2 * style->effectiveZoom();
1837 // FIXME: Using width/height alone and not also dealing with min-width/max-width is flawed.
1838 // FIXME: Using "quirk" to decide the margin wasn't set is kind of lame.
1839 if (style->width().isIntrinsicOrAuto()) {
1840 if (style->marginLeft().quirk())
1841 style->setMarginLeft(Length(intrinsicMargin, Fixed));
1842 if (style->marginRight().quirk())
1843 style->setMarginRight(Length(intrinsicMargin, Fixed));
1846 if (style->height().isAuto()) {
1847 if (style->marginTop().quirk())
1848 style->setMarginTop(Length(intrinsicMargin, Fixed));
1849 if (style->marginBottom().quirk())
1850 style->setMarginBottom(Length(intrinsicMargin, Fixed));
1854 static EDisplay equivalentBlockDisplay(EDisplay display, bool isFloating, bool strictParsing)
1865 // It is a WinIE bug that floated list items lose their bullets, so we'll emulate the quirk, but only in quirks mode.
1866 if (!strictParsing && isFloating)
1882 case TABLE_ROW_GROUP:
1883 case TABLE_HEADER_GROUP:
1884 case TABLE_FOOTER_GROUP:
1886 case TABLE_COLUMN_GROUP:
1892 ASSERT_NOT_REACHED();
1895 ASSERT_NOT_REACHED();
1899 // CSS requires text-decoration to be reset at each DOM element for tables,
1900 // inline blocks, inline tables, run-ins, shadow DOM crossings, floating elements,
1901 // and absolute or relatively positioned elements.
1902 static bool doesNotInheritTextDecoration(RenderStyle* style, Element* e)
1904 return style->display() == TABLE || style->display() == INLINE_TABLE || style->display() == RUN_IN
1905 || style->display() == INLINE_BLOCK || style->display() == INLINE_BOX || isAtShadowBoundary(e)
1906 || style->isFloating() || style->hasOutOfFlowPosition();
1909 static bool isDisplayFlexibleBox(EDisplay display)
1911 return display == FLEX || display == INLINE_FLEX;
1914 void StyleResolver::adjustRenderStyle(RenderStyle* style, RenderStyle* parentStyle, Element *e)
1916 ASSERT(parentStyle);
1918 // Cache our original display.
1919 style->setOriginalDisplay(style->display());
1921 if (style->display() != NONE) {
1922 // If we have a <td> that specifies a float property, in quirks mode we just drop the float
1924 // Sites also commonly use display:inline/block on <td>s and <table>s. In quirks mode we force
1925 // these tags to retain their display types.
1926 if (!m_selectorChecker.strictParsing() && e) {
1927 if (e->hasTagName(tdTag)) {
1928 style->setDisplay(TABLE_CELL);
1929 style->setFloating(NoFloat);
1930 } else if (e->hasTagName(tableTag))
1931 style->setDisplay(style->isDisplayInlineType() ? INLINE_TABLE : TABLE);
1934 if (e && (e->hasTagName(tdTag) || e->hasTagName(thTag))) {
1935 if (style->whiteSpace() == KHTML_NOWRAP) {
1936 // Figure out if we are really nowrapping or if we should just
1937 // use normal instead. If the width of the cell is fixed, then
1938 // we don't actually use NOWRAP.
1939 if (style->width().isFixed())
1940 style->setWhiteSpace(NORMAL);
1942 style->setWhiteSpace(NOWRAP);
1946 // Tables never support the -webkit-* values for text-align and will reset back to the default.
1947 if (e && e->hasTagName(tableTag) && (style->textAlign() == WEBKIT_LEFT || style->textAlign() == WEBKIT_CENTER || style->textAlign() == WEBKIT_RIGHT))
1948 style->setTextAlign(TASTART);
1950 // Frames and framesets never honor position:relative or position:absolute. This is necessary to
1951 // fix a crash where a site tries to position these objects. They also never honor display.
1952 if (e && (e->hasTagName(frameTag) || e->hasTagName(framesetTag))) {
1953 style->setPosition(StaticPosition);
1954 style->setDisplay(BLOCK);
1957 // Ruby text does not support float or position. This might change with evolution of the specification.
1958 if (e && e->hasTagName(rtTag)) {
1959 style->setPosition(StaticPosition);
1960 style->setFloating(NoFloat);
1963 // FIXME: We shouldn't be overriding start/-webkit-auto like this. Do it in html.css instead.
1964 // Table headers with a text-align of -webkit-auto will change the text-align to center.
1965 if (e && e->hasTagName(thTag) && style->textAlign() == TASTART)
1966 style->setTextAlign(CENTER);
1968 if (e && e->hasTagName(legendTag))
1969 style->setDisplay(BLOCK);
1971 // Absolute/fixed positioned elements, floating elements and the document element need block-like outside display.
1972 if (style->hasOutOfFlowPosition() || style->isFloating() || (e && e->document()->documentElement() == e))
1973 style->setDisplay(equivalentBlockDisplay(style->display(), style->isFloating(), m_selectorChecker.strictParsing()));
1975 // FIXME: Don't support this mutation for pseudo styles like first-letter or first-line, since it's not completely
1976 // clear how that should work.
1977 if (style->display() == INLINE && style->styleType() == NOPSEUDO && style->writingMode() != parentStyle->writingMode())
1978 style->setDisplay(INLINE_BLOCK);
1980 // After performing the display mutation, check table rows. We do not honor position:relative or position:sticky on
1981 // table rows or cells. This has been established for position:relative in CSS2.1 (and caused a crash in containingBlock()
1983 if ((style->display() == TABLE_HEADER_GROUP || style->display() == TABLE_ROW_GROUP
1984 || style->display() == TABLE_FOOTER_GROUP || style->display() == TABLE_ROW)
1985 && style->hasInFlowPosition())
1986 style->setPosition(StaticPosition);
1988 // writing-mode does not apply to table row groups, table column groups, table rows, and table columns.
1989 // FIXME: Table cells should be allowed to be perpendicular or flipped with respect to the table, though.
1990 if (style->display() == TABLE_COLUMN || style->display() == TABLE_COLUMN_GROUP || style->display() == TABLE_FOOTER_GROUP
1991 || style->display() == TABLE_HEADER_GROUP || style->display() == TABLE_ROW || style->display() == TABLE_ROW_GROUP
1992 || style->display() == TABLE_CELL)
1993 style->setWritingMode(parentStyle->writingMode());
1995 // FIXME: Since we don't support block-flow on flexible boxes yet, disallow setting
1996 // of block-flow to anything other than TopToBottomWritingMode.
1997 // https://bugs.webkit.org/show_bug.cgi?id=46418 - Flexible box support.
1998 if (style->writingMode() != TopToBottomWritingMode && (style->display() == BOX || style->display() == INLINE_BOX))
1999 style->setWritingMode(TopToBottomWritingMode);
2001 if (isDisplayFlexibleBox(parentStyle->display())) {
2002 style->setFloating(NoFloat);
2003 style->setDisplay(equivalentBlockDisplay(style->display(), style->isFloating(), m_selectorChecker.strictParsing()));
2007 // Make sure our z-index value is only applied if the object is positioned.
2008 if (style->position() == StaticPosition && !isDisplayFlexibleBox(parentStyle->display()))
2009 style->setHasAutoZIndex();
2011 // Auto z-index becomes 0 for the root element and transparent objects. This prevents
2012 // cases where objects that should be blended as a single unit end up with a non-transparent
2013 // object wedged in between them. Auto z-index also becomes 0 for objects that specify transforms/masks/reflections.
2014 if (style->hasAutoZIndex() && ((e && e->document()->documentElement() == e)
2015 || style->opacity() < 1.0f
2016 || style->hasTransformRelatedProperty()
2018 || style->clipPath()
2019 || style->boxReflect()
2020 || style->hasFilter()
2021 || style->hasBlendMode()
2022 || style->position() == StickyPosition
2023 || (style->position() == FixedPosition && e && e->document()->page() && e->document()->page()->settings()->fixedPositionCreatesStackingContext())
2024 #if ENABLE(ACCELERATED_OVERFLOW_SCROLLING)
2025 // Touch overflow scrolling creates a stacking context.
2026 || ((style->overflowX() != OHIDDEN || style->overflowY() != OHIDDEN) && style->useTouchOverflowScrolling())
2028 #if ENABLE(DIALOG_ELEMENT)
2029 || (e && e->isInTopLayer())
2032 style->setZIndex(0);
2034 // Textarea considers overflow visible as auto.
2035 if (e && e->hasTagName(textareaTag)) {
2036 style->setOverflowX(style->overflowX() == OVISIBLE ? OAUTO : style->overflowX());
2037 style->setOverflowY(style->overflowY() == OVISIBLE ? OAUTO : style->overflowY());
2040 if (doesNotInheritTextDecoration(style, e))
2041 style->setTextDecorationsInEffect(style->textDecoration());
2043 style->addToTextDecorationsInEffect(style->textDecoration());
2045 // If either overflow value is not visible, change to auto.
2046 if (style->overflowX() == OMARQUEE && style->overflowY() != OMARQUEE)
2047 style->setOverflowY(OMARQUEE);
2048 else if (style->overflowY() == OMARQUEE && style->overflowX() != OMARQUEE)
2049 style->setOverflowX(OMARQUEE);
2050 else if (style->overflowX() == OVISIBLE && style->overflowY() != OVISIBLE) {
2051 // FIXME: Once we implement pagination controls, overflow-x should default to hidden
2052 // if overflow-y is set to -webkit-paged-x or -webkit-page-y. For now, we'll let it
2053 // default to auto so we can at least scroll through the pages.
2054 style->setOverflowX(OAUTO);
2055 } else if (style->overflowY() == OVISIBLE && style->overflowX() != OVISIBLE)
2056 style->setOverflowY(OAUTO);
2058 // Call setStylesForPaginationMode() if a pagination mode is set for any non-root elements. If these
2059 // styles are specified on a root element, then they will be incorporated in
2060 // StyleResolver::styleForDocument().
2061 if ((style->overflowY() == OPAGEDX || style->overflowY() == OPAGEDY) && !(e && (e->hasTagName(htmlTag) || e->hasTagName(bodyTag))))
2062 setStylesForPaginationMode(WebCore::paginationModeForRenderStyle(style), style);
2064 // Table rows, sections and the table itself will support overflow:hidden and will ignore scroll/auto.
2065 // FIXME: Eventually table sections will support auto and scroll.
2066 if (style->display() == TABLE || style->display() == INLINE_TABLE
2067 || style->display() == TABLE_ROW_GROUP || style->display() == TABLE_ROW) {
2068 if (style->overflowX() != OVISIBLE && style->overflowX() != OHIDDEN)
2069 style->setOverflowX(OVISIBLE);
2070 if (style->overflowY() != OVISIBLE && style->overflowY() != OHIDDEN)
2071 style->setOverflowY(OVISIBLE);
2074 // Menulists should have visible overflow
2075 if (style->appearance() == MenulistPart) {
2076 style->setOverflowX(OVISIBLE);
2077 style->setOverflowY(OVISIBLE);
2080 // Cull out any useless layers and also repeat patterns into additional layers.
2081 style->adjustBackgroundLayers();
2082 style->adjustMaskLayers();
2084 // Do the same for animations and transitions.
2085 style->adjustAnimations();
2086 style->adjustTransitions();
2088 // Important: Intrinsic margins get added to controls before the theme has adjusted the style, since the theme will
2089 // alter fonts and heights/widths.
2090 if (e && e->isFormControlElement() && style->fontSize() >= 11) {
2091 // Don't apply intrinsic margins to image buttons. The designer knows how big the images are,
2092 // so we have to treat all image buttons as though they were explicitly sized.
2093 if (!e->hasTagName(inputTag) || !static_cast<HTMLInputElement*>(e)->isImageButton())
2094 addIntrinsicMargins(style);
2097 // Let the theme also have a crack at adjusting the style.
2098 if (style->hasAppearance())
2099 RenderTheme::defaultTheme()->adjustStyle(this, style, e, m_hasUAAppearance, m_borderData, m_backgroundData, m_backgroundColor);
2101 // If we have first-letter pseudo style, do not share this style.
2102 if (style->hasPseudoStyle(FIRST_LETTER))
2105 // FIXME: when dropping the -webkit prefix on transform-style, we should also have opacity < 1 cause flattening.
2106 if (style->preserves3D() && (style->overflowX() != OVISIBLE
2107 || style->overflowY() != OVISIBLE
2108 || style->hasFilter()))
2109 style->setTransformStyle3D(TransformStyle3DFlat);
2111 // Seamless iframes behave like blocks. Map their display to inline-block when marked inline.
2112 if (e && e->hasTagName(iframeTag) && style->display() == INLINE && static_cast<HTMLIFrameElement*>(e)->shouldDisplaySeamlessly())
2113 style->setDisplay(INLINE_BLOCK);
2116 if (e && e->isSVGElement()) {
2117 // Spec: http://www.w3.org/TR/SVG/masking.html#OverflowProperty
2118 if (style->overflowY() == OSCROLL)
2119 style->setOverflowY(OHIDDEN);
2120 else if (style->overflowY() == OAUTO)
2121 style->setOverflowY(OVISIBLE);
2123 if (style->overflowX() == OSCROLL)
2124 style->setOverflowX(OHIDDEN);
2125 else if (style->overflowX() == OAUTO)
2126 style->setOverflowX(OVISIBLE);
2128 // Only the root <svg> element in an SVG document fragment tree honors css position
2129 if (!(e->hasTagName(SVGNames::svgTag) && e->parentNode() && !e->parentNode()->isSVGElement()))
2130 style->setPosition(RenderStyle::initialPosition());
2132 // RenderSVGRoot handles zooming for the whole SVG subtree, so foreignObject content should
2133 // not be scaled again.
2134 if (e->hasTagName(SVGNames::foreignObjectTag))
2135 style->setEffectiveZoom(RenderStyle::initialZoom());
2140 bool StyleResolver::checkRegionStyle(Element* regionElement)
2142 // FIXME (BUG 72472): We don't add @-webkit-region rules of scoped style sheets for the moment,
2143 // so all region rules are global by default. Verify whether that can stand or needs changing.
2145 unsigned rulesSize = m_authorStyle->m_regionSelectorsAndRuleSets.size();
2146 for (unsigned i = 0; i < rulesSize; ++i) {
2147 ASSERT(m_authorStyle->m_regionSelectorsAndRuleSets.at(i).ruleSet.get());
2148 if (checkRegionSelector(m_authorStyle->m_regionSelectorsAndRuleSets.at(i).selector, regionElement))
2153 rulesSize = m_userStyle->m_regionSelectorsAndRuleSets.size();
2154 for (unsigned i = 0; i < rulesSize; ++i) {
2155 ASSERT(m_userStyle->m_regionSelectorsAndRuleSets.at(i).ruleSet.get());
2156 if (checkRegionSelector(m_userStyle->m_regionSelectorsAndRuleSets.at(i).selector, regionElement))
2164 static void checkForOrientationChange(RenderStyle* style)
2166 FontOrientation fontOrientation;
2167 NonCJKGlyphOrientation glyphOrientation;
2168 getFontAndGlyphOrientation(style, fontOrientation, glyphOrientation);
2170 const FontDescription& fontDescription = style->fontDescription();
2171 if (fontDescription.orientation() == fontOrientation && fontDescription.nonCJKGlyphOrientation() == glyphOrientation)
2174 FontDescription newFontDescription(fontDescription);
2175 newFontDescription.setNonCJKGlyphOrientation(glyphOrientation);
2176 newFontDescription.setOrientation(fontOrientation);
2177 style->setFontDescription(newFontDescription);
2180 void StyleResolver::updateFont()
2185 checkForTextSizeAdjust();
2186 checkForGenericFamilyChange(style(), m_parentStyle);
2187 checkForZoomChange(style(), m_parentStyle);
2188 checkForOrientationChange(style());
2189 m_style->font().update(m_fontSelector);
2190 m_fontDirty = false;
2193 void StyleResolver::cacheBorderAndBackground()
2195 m_hasUAAppearance = m_style->hasAppearance();
2196 if (m_hasUAAppearance) {
2197 m_borderData = m_style->border();
2198 m_backgroundData = *m_style->backgroundLayers();
2199 m_backgroundColor = m_style->backgroundColor();
2203 PassRefPtr<CSSRuleList> StyleResolver::styleRulesForElement(Element* e, unsigned rulesToInclude)
2205 return pseudoStyleRulesForElement(e, NOPSEUDO, rulesToInclude);
2208 PassRefPtr<CSSRuleList> StyleResolver::pseudoStyleRulesForElement(Element* e, PseudoId pseudoId, unsigned rulesToInclude)
2210 if (!e || !e->document()->haveStylesheetsLoaded())
2213 m_selectorChecker.setMode(SelectorChecker::CollectingRules);
2216 initForStyleResolve(e, 0, pseudoId);
2219 if (rulesToInclude & UAAndUserCSSRules) {
2220 // First we match rules from the user agent sheet.
2221 matchUARules(dummy);
2223 // Now we check user sheet rules.
2224 if (m_matchAuthorAndUserStyles)
2225 matchUserRules(dummy, rulesToInclude & EmptyCSSRules);
2228 if (m_matchAuthorAndUserStyles && (rulesToInclude & AuthorCSSRules)) {
2229 m_sameOriginOnly = !(rulesToInclude & CrossOriginCSSRules);
2231 // Check the rules in author sheets.
2232 matchAuthorRules(dummy, rulesToInclude & EmptyCSSRules);
2234 m_sameOriginOnly = false;
2237 m_selectorChecker.setMode(SelectorChecker::ResolvingStyle);
2239 return m_ruleList.release();
2242 inline bool StyleResolver::ruleMatches(const RuleData& ruleData, const ContainerNode* scope)
2244 m_dynamicPseudo = NOPSEUDO;
2246 if (ruleData.hasFastCheckableSelector()) {
2247 // We know this selector does not include any pseudo elements.
2248 if (m_pseudoStyle != NOPSEUDO)
2250 // We know a sufficiently simple single part selector matches simply because we found it from the rule hash.
2251 // This is limited to HTML only so we don't need to check the namespace.
2252 if (ruleData.hasRightmostSelectorMatchingHTMLBasedOnRuleHash() && m_element->isHTMLElement()) {
2253 if (!ruleData.hasMultipartSelector())
2255 } else if (!SelectorChecker::tagMatches(m_element, ruleData.selector()))
2257 if (!SelectorChecker::fastCheckRightmostAttributeSelector(m_element, ruleData.selector()))
2259 return m_selectorChecker.fastCheck(ruleData.selector(), m_element);
2263 SelectorChecker::SelectorCheckingContext context(ruleData.selector(), m_element, SelectorChecker::VisitedMatchEnabled);
2264 context.elementStyle = style();
2265 context.elementParentStyle = m_parentNode ? m_parentNode->renderStyle() : 0;
2266 context.scope = scope;
2267 context.pseudoStyle = m_pseudoStyle;
2268 SelectorChecker::Match match = m_selectorChecker.match(context, m_dynamicPseudo);
2269 if (match != SelectorChecker::SelectorMatches)
2271 if (m_pseudoStyle != NOPSEUDO && m_pseudoStyle != m_dynamicPseudo)
2276 bool StyleResolver::checkRegionSelector(CSSSelector* regionSelector, Element* regionElement)
2278 if (!regionSelector || !regionElement)
2281 m_pseudoStyle = NOPSEUDO;
2283 for (CSSSelector* s = regionSelector; s; s = CSSSelectorList::next(s))
2284 if (m_selectorChecker.matches(s, regionElement))
2290 // -------------------------------------------------------------------------------------
2291 // this is mostly boring stuff on how to apply a certain rule to the renderstyle...
2293 Length StyleResolver::convertToIntLength(CSSPrimitiveValue* primitiveValue, RenderStyle* style, RenderStyle* rootStyle, double multiplier)
2295 return primitiveValue ? primitiveValue->convertToLength<FixedIntegerConversion | PercentConversion | CalculatedConversion | FractionConversion | ViewportPercentageConversion>(style, rootStyle, multiplier) : Length(Undefined);
2298 Length StyleResolver::convertToFloatLength(CSSPrimitiveValue* primitiveValue, RenderStyle* style, RenderStyle* rootStyle, double multiplier)
2300 return primitiveValue ? primitiveValue->convertToLength<FixedFloatConversion | PercentConversion | CalculatedConversion | FractionConversion | ViewportPercentageConversion>(style, rootStyle, multiplier) : Length(Undefined);
2303 template <StyleResolver::StyleApplicationPass pass>
2304 void StyleResolver::applyProperties(const StylePropertySet* properties, StyleRule* rule, bool isImportant, bool inheritedOnly, bool filterRegionProperties)
2306 ASSERT(!filterRegionProperties || m_regionForStyling);
2307 InspectorInstrumentationCookie cookie = InspectorInstrumentation::willProcessRule(document(), rule, this);
2309 unsigned propertyCount = properties->propertyCount();
2310 for (unsigned i = 0; i < propertyCount; ++i) {
2311 StylePropertySet::PropertyReference current = properties->propertyAt(i);
2312 if (isImportant != current.isImportant())
2314 if (inheritedOnly && !current.isInherited()) {
2315 // If the property value is explicitly inherited, we need to apply further non-inherited properties
2316 // as they might override the value inherited here. For this reason we don't allow declarations with
2317 // explicitly inherited properties to be cached.
2318 ASSERT(!current.value()->isInheritedValue());
2321 CSSPropertyID property = current.id();
2323 if (filterRegionProperties && !StyleResolver::isValidRegionStyleProperty(property))
2327 #if ENABLE(CSS_VARIABLES)
2328 case VariableDefinitions:
2329 COMPILE_ASSERT(CSSPropertyVariable < firstCSSProperty, CSS_variable_is_before_first_property);
2330 if (property == CSSPropertyVariable)
2331 applyProperty(current.id(), current.value());
2334 case HighPriorityProperties:
2335 COMPILE_ASSERT(firstCSSProperty == CSSPropertyColor, CSS_color_is_first_property);
2336 COMPILE_ASSERT(CSSPropertyZoom == CSSPropertyColor + 18, CSS_zoom_is_end_of_first_prop_range);
2337 COMPILE_ASSERT(CSSPropertyLineHeight == CSSPropertyZoom + 1, CSS_line_height_is_after_zoom);
2338 #if ENABLE(CSS_VARIABLES)
2339 if (property == CSSPropertyVariable)
2342 // give special priority to font-xxx, color properties, etc
2343 if (property < CSSPropertyLineHeight)
2344 applyProperty(current.id(), current.value());
2345 // we apply line-height later
2346 else if (property == CSSPropertyLineHeight)
2347 m_lineHeightValue = current.value();
2349 case LowPriorityProperties:
2350 if (property > CSSPropertyLineHeight)
2351 applyProperty(current.id(), current.value());
2354 InspectorInstrumentation::didProcessRule(cookie);
2357 template <StyleResolver::StyleApplicationPass pass>
2358 void StyleResolver::applyMatchedProperties(const MatchResult& matchResult, bool isImportant, int startIndex, int endIndex, bool inheritedOnly)
2360 if (startIndex == -1)
2363 if (m_style->insideLink() != NotInsideLink) {
2364 for (int i = startIndex; i <= endIndex; ++i) {
2365 const MatchedProperties& matchedProperties = matchResult.matchedProperties[i];
2366 unsigned linkMatchType = matchedProperties.linkMatchType;
2367 // FIXME: It would be nicer to pass these as arguments but that requires changes in many places.
2368 m_applyPropertyToRegularStyle = linkMatchType & SelectorChecker::MatchLink;
2369 m_applyPropertyToVisitedLinkStyle = linkMatchType & SelectorChecker::MatchVisited;
2371 applyProperties<pass>(matchedProperties.properties.get(), matchResult.matchedRules[i], isImportant, inheritedOnly, matchedProperties.isInRegionRule);
2373 m_applyPropertyToRegularStyle = true;
2374 m_applyPropertyToVisitedLinkStyle = false;
2377 for (int i = startIndex; i <= endIndex; ++i) {
2378 const MatchedProperties& matchedProperties = matchResult.matchedProperties[i];
2379 applyProperties<pass>(matchedProperties.properties.get(), matchResult.matchedRules[i], isImportant, inheritedOnly, matchedProperties.isInRegionRule);
2383 unsigned StyleResolver::computeMatchedPropertiesHash(const MatchedProperties* properties, unsigned size)
2386 return StringHasher::hashMemory(properties, sizeof(MatchedProperties) * size);
2389 bool operator==(const StyleResolver::MatchRanges& a, const StyleResolver::MatchRanges& b)
2391 return a.firstUARule == b.firstUARule
2392 && a.lastUARule == b.lastUARule
2393 && a.firstAuthorRule == b.firstAuthorRule
2394 && a.lastAuthorRule == b.lastAuthorRule
2395 && a.firstUserRule == b.firstUserRule
2396 && a.lastUserRule == b.lastUserRule;
2399 bool operator!=(const StyleResolver::MatchRanges& a, const StyleResolver::MatchRanges& b)
2404 bool operator==(const StyleResolver::MatchedProperties& a, const StyleResolver::MatchedProperties& b)
2406 return a.properties == b.properties && a.linkMatchType == b.linkMatchType;
2409 bool operator!=(const StyleResolver::MatchedProperties& a, const StyleResolver::MatchedProperties& b)
2414 const StyleResolver::MatchedPropertiesCacheItem* StyleResolver::findFromMatchedPropertiesCache(unsigned hash, const MatchResult& matchResult)
2418 MatchedPropertiesCache::iterator it = m_matchedPropertiesCache.find(hash);
2419 if (it == m_matchedPropertiesCache.end())
2421 MatchedPropertiesCacheItem& cacheItem = it->value;
2423 size_t size = matchResult.matchedProperties.size();
2424 if (size != cacheItem.matchedProperties.size())
2426 for (size_t i = 0; i < size; ++i) {
2427 if (matchResult.matchedProperties[i] != cacheItem.matchedProperties[i])
2430 if (cacheItem.ranges != matchResult.ranges)
2435 void StyleResolver::addToMatchedPropertiesCache(const RenderStyle* style, const RenderStyle* parentStyle, unsigned hash, const MatchResult& matchResult)
2437 static const unsigned matchedDeclarationCacheAdditionsBetweenSweeps = 100;
2438 if (++m_matchedPropertiesCacheAdditionsSinceLastSweep >= matchedDeclarationCacheAdditionsBetweenSweeps) {
2439 static const unsigned matchedDeclarationCacheSweepTimeInSeconds = 60;
2440 m_matchedPropertiesCacheSweepTimer.startOneShot(matchedDeclarationCacheSweepTimeInSeconds);
2444 MatchedPropertiesCacheItem cacheItem;
2445 cacheItem.matchedProperties.append(matchResult.matchedProperties);
2446 cacheItem.ranges = matchResult.ranges;
2447 // Note that we don't cache the original RenderStyle instance. It may be further modified.
2448 // The RenderStyle in the cache is really just a holder for the substructures and never used as-is.
2449 cacheItem.renderStyle = RenderStyle::clone(style);
2450 cacheItem.parentRenderStyle = RenderStyle::clone(parentStyle);
2451 m_matchedPropertiesCache.add(hash, cacheItem);
2454 void StyleResolver::invalidateMatchedPropertiesCache()
2456 m_matchedPropertiesCache.clear();
2459 static bool isCacheableInMatchedPropertiesCache(const Element* element, const RenderStyle* style, const RenderStyle* parentStyle)
2461 // FIXME: CSSPropertyWebkitWritingMode modifies state when applying to document element. We can't skip the applying by caching.
2462 if (element == element->document()->documentElement() && element->document()->writingModeSetOnDocumentElement())
2464 if (style->unique() || (style->styleType() != NOPSEUDO && parentStyle->unique()))
2466 if (style->hasAppearance())
2468 if (style->zoom() != RenderStyle::initialZoom())
2470 if (style->writingMode() != RenderStyle::initialWritingMode())
2472 // The cache assumes static knowledge about which properties are inherited.
2473 if (parentStyle->hasExplicitlyInheritedProperties())
2478 void StyleResolver::applyMatchedProperties(const MatchResult& matchResult, const Element* element)
2481 unsigned cacheHash = matchResult.isCacheable ? computeMatchedPropertiesHash(matchResult.matchedProperties.data(), matchResult.matchedProperties.size()) : 0;
2482 bool applyInheritedOnly = false;
2483 const MatchedPropertiesCacheItem* cacheItem = 0;
2484 if (cacheHash && (cacheItem = findFromMatchedPropertiesCache(cacheHash, matchResult))) {
2485 // We can build up the style by copying non-inherited properties from an earlier style object built using the same exact
2486 // style declarations. We then only need to apply the inherited properties, if any, as their values can depend on the
2487 // element context. This is fast and saves memory by reusing the style data structures.
2488 m_style->copyNonInheritedFrom(cacheItem->renderStyle.get());
2489 if (m_parentStyle->inheritedDataShared(cacheItem->parentRenderStyle.get()) && !isAtShadowBoundary(element)) {
2490 EInsideLink linkStatus = m_style->insideLink();
2491 // If the cache item parent style has identical inherited properties to the current parent style then the
2492 // resulting style will be identical too. We copy the inherited properties over from the cache and are done.
2493 m_style->inheritFrom(cacheItem->renderStyle.get());
2495 // Unfortunately the link status is treated like an inherited property. We need to explicitly restore it.
2496 m_style->setInsideLink(linkStatus);
2499 applyInheritedOnly = true;
2502 #if ENABLE(CSS_VARIABLES)
2503 // First apply all variable definitions, as they may be used during application of later properties.
2504 applyMatchedProperties<VariableDefinitions>(matchResult, false, 0, matchResult.matchedProperties.size() - 1, applyInheritedOnly);
2505 applyMatchedProperties<VariableDefinitions>(matchResult, true, matchResult.ranges.firstAuthorRule, matchResult.ranges.lastAuthorRule, applyInheritedOnly);
2506 applyMatchedProperties<VariableDefinitions>(matchResult, true, matchResult.ranges.firstUserRule, matchResult.ranges.lastUserRule, applyInheritedOnly);
2507 applyMatchedProperties<VariableDefinitions>(matchResult, true, matchResult.ranges.firstUARule, matchResult.ranges.lastUARule, applyInheritedOnly);
2510 // Now we have all of the matched rules in the appropriate order. Walk the rules and apply
2511 // high-priority properties first, i.e., those properties that other properties depend on.
2512 // The order is (1) high-priority not important, (2) high-priority important, (3) normal not important
2513 // and (4) normal important.
2514 m_lineHeightValue = 0;
2515 applyMatchedProperties<HighPriorityProperties>(matchResult, false, 0, matchResult.matchedProperties.size() - 1, applyInheritedOnly);
2516 applyMatchedProperties<HighPriorityProperties>(matchResult, true, matchResult.ranges.firstAuthorRule, matchResult.ranges.lastAuthorRule, applyInheritedOnly);
2517 applyMatchedProperties<HighPriorityProperties>(matchResult, true, matchResult.ranges.firstUserRule, matchResult.ranges.lastUserRule, applyInheritedOnly);
2518 applyMatchedProperties<HighPriorityProperties>(matchResult, true, matchResult.ranges.firstUARule, matchResult.ranges.lastUARule, applyInheritedOnly);
2520 if (cacheItem && cacheItem->renderStyle->effectiveZoom() != m_style->effectiveZoom()) {
2522 applyInheritedOnly = false;
2525 // If our font got dirtied, go ahead and update it now.
2528 // Line-height is set when we are sure we decided on the font-size.
2529 if (m_lineHeightValue)
2530 applyProperty(CSSPropertyLineHeight, m_lineHeightValue);
2532 // Many properties depend on the font. If it changes we just apply all properties.
2533 if (cacheItem && cacheItem->renderStyle->fontDescription() != m_style->fontDescription())
2534 applyInheritedOnly = false;
2536 // Now do the normal priority UA properties.
2537 applyMatchedProperties<LowPriorityProperties>(matchResult, false, matchResult.ranges.firstUARule, matchResult.ranges.lastUARule, applyInheritedOnly);
2539 // Cache our border and background so that we can examine them later.
2540 cacheBorderAndBackground();
2542 // Now do the author and user normal priority properties and all the !important properties.
2543 applyMatchedProperties<LowPriorityProperties>(matchResult, false, matchResult.ranges.lastUARule + 1, matchResult.matchedProperties.size() - 1, applyInheritedOnly);
2544 applyMatchedProperties<LowPriorityProperties>(matchResult, true, matchResult.ranges.firstAuthorRule, matchResult.ranges.lastAuthorRule, applyInheritedOnly);
2545 applyMatchedProperties<LowPriorityProperties>(matchResult, true, matchResult.ranges.firstUserRule, matchResult.ranges.lastUserRule, applyInheritedOnly);
2546 applyMatchedProperties<LowPriorityProperties>(matchResult, true, matchResult.ranges.firstUARule, matchResult.ranges.lastUARule, applyInheritedOnly);
2548 // Start loading resources referenced by this style.
2549 loadPendingResources();
2551 ASSERT(!m_fontDirty);
2553 if (cacheItem || !cacheHash)
2555 if (!isCacheableInMatchedPropertiesCache(m_element, m_style.get(), m_parentStyle))
2557 addToMatchedPropertiesCache(m_style.get(), m_parentStyle, cacheHash, matchResult);
2560 static inline bool comparePageRules(const StyleRulePage* r1, const StyleRulePage* r2)
2562 return r1->selector()->specificity() < r2->selector()->specificity();
2565 void StyleResolver::matchPageRules(MatchResult& result, RuleSet* rules, bool isLeftPage, bool isFirstPage, const String& pageName)
2570 Vector<StyleRulePage*> matchedPageRules;
2571 matchPageRulesForList(matchedPageRules, rules->pageRules(), isLeftPage, isFirstPage, pageName);
2572 if (matchedPageRules.isEmpty())
2575 std::stable_sort(matchedPageRules.begin(), matchedPageRules.end(), comparePageRules);
2577 for (unsigned i = 0; i < matchedPageRules.size(); i++)
2578 addMatchedProperties(result, matchedPageRules[i]->properties());
2581 void StyleResolver::matchPageRulesForList(Vector<StyleRulePage*>& matchedRules, const Vector<StyleRulePage*>& rules, bool isLeftPage, bool isFirstPage, const String& pageName)
2583 unsigned size = rules.size();
2584 for (unsigned i = 0; i < size; ++i) {
2585 StyleRulePage* rule = rules[i];
2586 const AtomicString& selectorLocalName = rule->selector()->tag().localName();
2587 if (selectorLocalName != starAtom && selectorLocalName != pageName)
2589 CSSSelector::PseudoType pseudoType = rule->selector()->pseudoType();
2590 if ((pseudoType == CSSSelector::PseudoLeftPage && !isLeftPage)
2591 || (pseudoType == CSSSelector::PseudoRightPage && isLeftPage)
2592 || (pseudoType == CSSSelector::PseudoFirstPage && !isFirstPage))
2595 // If the rule has no properties to apply, then ignore it.
2596 const StylePropertySet* properties = rule->properties();
2597 if (!properties || properties->isEmpty())
2600 // Add this rule to our list of matched rules.
2601 matchedRules.append(rule);
2605 bool StyleResolver::isLeftPage(int pageIndex) const
2607 bool isFirstPageLeft = false;
2608 if (!m_rootElementStyle->isLeftToRightDirection())
2609 isFirstPageLeft = true;
2611 return (pageIndex + (isFirstPageLeft ? 1 : 0)) % 2;
2614 bool StyleResolver::isFirstPage(int pageIndex) const
2616 // FIXME: In case of forced left/right page, page at index 1 (not 0) can be the first page.
2617 return (!pageIndex);
2620 String StyleResolver::pageName(int /* pageIndex */) const
2622 // FIXME: Implement page index to page name mapping.
2626 template <class ListType>
2627 static void collectCSSOMWrappers(HashMap<StyleRule*, RefPtr<CSSStyleRule> >& wrapperMap, ListType* listType)
2631 unsigned size = listType->length();
2632 for (unsigned i = 0; i < size; ++i) {
2633 CSSRule* cssRule = listType->item(i);
2634 switch (cssRule->type()) {
2635 case CSSRule::IMPORT_RULE:
2636 collectCSSOMWrappers(wrapperMap, static_cast<CSSImportRule*>(cssRule)->styleSheet());
2638 case CSSRule::MEDIA_RULE:
2639 collectCSSOMWrappers(wrapperMap, static_cast<CSSMediaRule*>(cssRule));
2641 #if ENABLE(CSS_REGIONS)
2642 case CSSRule::WEBKIT_REGION_RULE:
2643 collectCSSOMWrappers(wrapperMap, static_cast<WebKitCSSRegionRule*>(cssRule));
2646 case CSSRule::STYLE_RULE:
2647 wrapperMap.add(static_cast<CSSStyleRule*>(cssRule)->styleRule(), static_cast<CSSStyleRule*>(cssRule));
2655 static void collectCSSOMWrappers(HashMap<StyleRule*, RefPtr<CSSStyleRule> >& wrapperMap, HashSet<RefPtr<CSSStyleSheet> >& sheetWrapperSet, StyleSheetContents* styleSheet)
2659 RefPtr<CSSStyleSheet> styleSheetWrapper = CSSStyleSheet::create(styleSheet);
2660 sheetWrapperSet.add(styleSheetWrapper);
2661 collectCSSOMWrappers(wrapperMap, styleSheetWrapper.get());
2664 static void collectCSSOMWrappers(HashMap<StyleRule*, RefPtr<CSSStyleRule> >& wrapperMap, const Vector<RefPtr<CSSStyleSheet> >& sheets)
2666 for (unsigned i = 0; i < sheets.size(); ++i)
2667 collectCSSOMWrappers(wrapperMap, sheets[i].get());
2670 static void collectCSSOMWrappers(HashMap<StyleRule*, RefPtr<CSSStyleRule> >& wrapperMap, DocumentStyleSheetCollection* styleSheetCollection)
2672 collectCSSOMWrappers(wrapperMap, styleSheetCollection->activeAuthorStyleSheets());
2673 collectCSSOMWrappers(wrapperMap, styleSheetCollection->pageUserSheet());
2674 collectCSSOMWrappers(wrapperMap, styleSheetCollection->injectedUserStyleSheets());
2675 collectCSSOMWrappers(wrapperMap, styleSheetCollection->documentUserStyleSheets());
2678 CSSStyleRule* StyleResolver::ensureFullCSSOMWrapperForInspector(StyleRule* rule)
2680 if (m_styleRuleToCSSOMWrapperMap.isEmpty()) {
2681 collectCSSOMWrappers(m_styleRuleToCSSOMWrapperMap, m_styleSheetCSSOMWrapperSet, simpleDefaultStyleSheet);
2682 collectCSSOMWrappers(m_styleRuleToCSSOMWrapperMap, m_styleSheetCSSOMWrapperSet, defaultStyleSheet);
2683 collectCSSOMWrappers(m_styleRuleToCSSOMWrapperMap, m_styleSheetCSSOMWrapperSet, quirksStyleSheet);
2684 collectCSSOMWrappers(m_styleRuleToCSSOMWrapperMap, m_styleSheetCSSOMWrapperSet, svgStyleSheet);
2685 collectCSSOMWrappers(m_styleRuleToCSSOMWrapperMap, m_styleSheetCSSOMWrapperSet, mathMLStyleSheet);
2686 collectCSSOMWrappers(m_styleRuleToCSSOMWrapperMap, m_styleSheetCSSOMWrapperSet, mediaControlsStyleSheet);
2687 collectCSSOMWrappers(m_styleRuleToCSSOMWrapperMap, m_styleSheetCSSOMWrapperSet, fullscreenStyleSheet);
2689 collectCSSOMWrappers(m_styleRuleToCSSOMWrapperMap, document()->styleSheetCollection());
2691 return m_styleRuleToCSSOMWrapperMap.get(rule).get();
2694 void StyleResolver::applyPropertyToStyle(CSSPropertyID id, CSSValue* value, RenderStyle* style)
2697 initForStyleResolve(0, style);
2699 applyPropertyToCurrentStyle(id, value);
2702 void StyleResolver::applyPropertyToCurrentStyle(CSSPropertyID id, CSSValue* value)
2705 applyProperty(id, value);
2708 inline bool isValidVisitedLinkProperty(CSSPropertyID id)
2711 case CSSPropertyBackgroundColor:
2712 case CSSPropertyBorderLeftColor:
2713 case CSSPropertyBorderRightColor:
2714 case CSSPropertyBorderTopColor:
2715 case CSSPropertyBorderBottomColor:
2716 case CSSPropertyColor:
2717 case CSSPropertyOutlineColor:
2718 case CSSPropertyWebkitColumnRuleColor:
2719 case CSSPropertyWebkitTextEmphasisColor:
2720 case CSSPropertyWebkitTextFillColor:
2721 case CSSPropertyWebkitTextStrokeColor:
2722 // Also allow shorthands so that inherit/initial still work.
2723 case CSSPropertyBackground:
2724 case CSSPropertyBorderLeft:
2725 case CSSPropertyBorderRight:
2726 case CSSPropertyBorderTop:
2727 case CSSPropertyBorderBottom:
2728 case CSSPropertyOutline:
2729 case CSSPropertyWebkitColumnRule:
2731 case CSSPropertyFill:
2732 case CSSPropertyStroke:
2742 // http://dev.w3.org/csswg/css3-regions/#the-at-region-style-rule
2743 // FIXME: add incremental support for other region styling properties.
2744 inline bool StyleResolver::isValidRegionStyleProperty(CSSPropertyID id)
2747 case CSSPropertyBackgroundColor:
2748 case CSSPropertyColor:
2757 // SVG handles zooming in a different way compared to CSS. The whole document is scaled instead
2758 // of each individual length value in the render style / tree. CSSPrimitiveValue::computeLength*()
2759 // multiplies each resolved length with the zoom multiplier - so for SVG we need to disable that.
2760 // Though all CSS values that can be applied to outermost <svg> elements (width/height/border/padding...)
2761 // need to respect the scaling. RenderBox (the parent class of RenderSVGRoot) grabs values like
2762 // width/height/border/padding/... from the RenderStyle -> for SVG these values would never scale,
2763 // if we'd pass a 1.0 zoom factor everyhwere. So we only pass a zoom factor of 1.0 for specific
2764 // properties that are NOT allowed to scale within a zoomed SVG document (letter/word-spacing/font-size).
2765 bool StyleResolver::useSVGZoomRules()
2767 return m_element && m_element->isSVGElement();
2770 static bool createGridTrackBreadth(CSSPrimitiveValue* primitiveValue, StyleResolver* selector, Length& workingLength)
2772 if (primitiveValue->getIdent() == CSSValueWebkitMinContent) {
2773 workingLength = Length(MinContent);
2777 if (primitiveValue->getIdent() == CSSValueWebkitMaxContent) {
2778 workingLength = Length(MaxContent);
2782 workingLength = primitiveValue->convertToLength<FixedIntegerConversion | PercentConversion | ViewportPercentageConversion | AutoConversion>(selector->style(), selector->rootElementStyle(), selector->style()->effectiveZoom());
2783 if (workingLength.isUndefined())
2786 if (primitiveValue->isLength())
2787 workingLength.setQuirk(primitiveValue->isQuirkValue());
2792 static bool createGridTrackMinMax(CSSPrimitiveValue* primitiveValue, StyleResolver* selector, GridTrackSize& trackSize)
2794 Pair* minMaxTrackBreadth = primitiveValue->getPairValue();
2795 if (!minMaxTrackBreadth) {
2796 Length workingLength;
2797 if (!createGridTrackBreadth(primitiveValue, selector, workingLength))
2800 trackSize.setLength(workingLength);
2804 Length minTrackBreadth;
2805 Length maxTrackBreadth;
2806 if (!createGridTrackBreadth(minMaxTrackBreadth->first(), selector, minTrackBreadth) || !createGridTrackBreadth(minMaxTrackBreadth->second(), selector, maxTrackBreadth))
2809 trackSize.setMinMax(minTrackBreadth, maxTrackBreadth);
2813 static bool createGridTrackGroup(CSSValue* value, StyleResolver* selector, Vector<GridTrackSize>& trackSizes)
2815 if (!value->isValueList())
2818 for (CSSValueListIterator i = value; i.hasMore(); i.advance()) {
2819 CSSValue* currValue = i.value();
2820 if (!currValue->isPrimitiveValue())
2823 GridTrackSize trackSize;
2824 if (!createGridTrackMinMax(static_cast<CSSPrimitiveValue*>(currValue), selector, trackSize))
2827 trackSizes.append(trackSize);
2832 static bool createGridTrackList(CSSValue* value, Vector<GridTrackSize>& trackSizes, StyleResolver* selector)
2835 if (value->isPrimitiveValue()) {
2836 CSSPrimitiveValue* primitiveValue = static_cast<CSSPrimitiveValue*>(value);
2837 return primitiveValue->getIdent() == CSSValueNone;
2840 return createGridTrackGroup(value, selector, trackSizes);
2844 static bool createGridPosition(CSSValue* value, GridPosition& position)
2846 // For now, we only accept: <integer> | 'auto'
2847 if (!value->isPrimitiveValue())
2850 CSSPrimitiveValue* primitiveValue = static_cast<CSSPrimitiveValue*>(value);
2851 if (primitiveValue->getIdent() == CSSValueAuto)
2854 ASSERT(primitiveValue->isNumber());
2855 position.setIntegerPosition(primitiveValue->getIntValue());
2859 #if ENABLE(CSS_VARIABLES)
2860 static bool hasVariableReference(CSSValue* value)
2862 if (value->isPrimitiveValue()) {
2863 CSSPrimitiveValue* primitiveValue = static_cast<CSSPrimitiveValue*>(value);
2864 return primitiveValue->hasVariableReference();
2867 if (value->isCalculationValue())
2868 return static_cast<CSSCalcValue*>(value)->hasVariableReference();
2870 for (CSSValueListIterator i = value; i.hasMore(); i.advance()) {
2871 if (hasVariableReference(i.value()))
2878 void StyleResolver::resolveVariables(CSSPropertyID id, CSSValue* value, Vector<std::pair<CSSPropertyID, String> >& knownExpressions)
2880 std::pair<CSSPropertyID, String> expression(id, value->serializeResolvingVariables(*style()->variables()));
2882 if (knownExpressions.contains(expression))
2883 return; // cycle detected.
2885 knownExpressions.append(expression);
2887 // FIXME: It would be faster not to re-parse from strings, but for now CSS property validation lives inside the parser so we do it there.
2888 RefPtr<StylePropertySet> resultSet = StylePropertySet::create();
2889 if (!CSSParser::parseValue(resultSet.get(), id, expression.second, false, document()))
2890 return; // expression failed to parse.
2892 for (unsigned i = 0; i < resultSet->propertyCount(); i++) {
2893 StylePropertySet::PropertyReference property = resultSet->propertyAt(i);
2894 if (property.id() != CSSPropertyVariable && hasVariableReference(property.value()))
2895 resolveVariables(property.id(), property.value(), knownExpressions);
2897 applyProperty(property.id(), property.value());
2902 void StyleResolver::applyProperty(CSSPropertyID id, CSSValue* value)
2904 #if ENABLE(CSS_VARIABLES)
2905 if (id != CSSPropertyVariable && hasVariableReference(value)) {
2906 Vector<std::pair<CSSPropertyID, String> > knownExpressions;
2907 resolveVariables(id, value, knownExpressions);
2912 bool isInherit = m_parentNode && value->isInheritedValue();
2913 bool isInitial = value->isInitialValue() || (!m_parentNode && value->isInheritedValue());
2915 ASSERT(!isInherit || !isInitial); // isInherit -> !isInitial && isInitial -> !isInherit
2916 ASSERT(!isInherit || (m_parentNode && m_parentStyle)); // isInherit -> (m_parentNode && m_parentStyle)
2918 if (!applyPropertyToRegularStyle() && (!applyPropertyToVisitedLinkStyle() || !isValidVisitedLinkProperty(id))) {
2919 // Limit the properties that can be applied to only the ones honored by :visited.
2923 if (isInherit && !m_parentStyle->hasExplicitlyInheritedProperties() && !CSSProperty::isInheritedProperty(id))
2924 m_parentStyle->setHasExplicitlyInheritedProperties();
2926 #if ENABLE(CSS_VARIABLES)
2927 if (id == CSSPropertyVariable) {
2928 ASSERT(value->isVariableValue());
2929 CSSVariableValue* variable = static_cast<CSSVariableValue*>(value);
2930 ASSERT(!variable->name().isEmpty());
2931 ASSERT(!variable->value().isEmpty());
2932 m_style->setVariable(variable->name(), variable->value());
2937 // Check lookup table for implementations and use when available.
2938 const PropertyHandler& handler = m_styleBuilder.propertyHandler(id);
2939 if (handler.isValid()) {
2941 handler.applyInheritValue(id, this);
2943 handler.applyInitialValue(id, this);
2945 handler.applyValue(id, this, value);
2949 CSSPrimitiveValue* primitiveValue = value->isPrimitiveValue() ? static_cast<CSSPrimitiveValue*>(value) : 0;
2951 float zoomFactor = m_style->effectiveZoom();
2953 // What follows is a list that maps the CSS properties into their corresponding front-end
2954 // RenderStyle values. Shorthands (e.g. border, background) occur in this list as well and
2955 // are only hit when mapping "inherit" or "initial" into front-end values.
2958 case CSSPropertyContent:
2959 // list of string, uri, counter, attr, i
2961 // FIXME: In CSS3, it will be possible to inherit content. In CSS2 it is not. This
2962 // note is a reminder that eventually "inherit" needs to be supported.
2965 m_style->clearContent();
2969 if (!value->isValueList())
2972 bool didSet = false;
2973 for (CSSValueListIterator i = value; i.hasMore(); i.advance()) {
2974 CSSValue* item = i.value();
2975 if (item->isImageGeneratorValue()) {
2976 if (item->isGradientValue())
2977 m_style->setContent(StyleGeneratedImage::create(static_cast<CSSGradientValue*>(item)->gradientWithStylesResolved(this).get()), didSet);
2979 m_style->setContent(StyleGeneratedImage::create(static_cast<CSSImageGeneratorValue*>(item)), didSet);
2981 #if ENABLE(CSS_IMAGE_SET)
2982 } else if (item->isImageSetValue()) {
2983 m_style->setContent(setOrPendingFromValue(CSSPropertyContent, static_cast<CSSImageSetValue*>(item)), didSet);
2988 if (item->isImageValue()) {
2989 m_style->setContent(cachedOrPendingFromValue(CSSPropertyContent, static_cast<CSSImageValue*>(item)), didSet);
2994 if (!item->isPrimitiveValue())
2997 CSSPrimitiveValue* contentValue = static_cast<CSSPrimitiveValue*>(item);
2999 if (contentValue->isString()) {
3000 m_style->setContent(contentValue->getStringValue().impl(), didSet);
3002 } else if (contentValue->isAttr()) {
3003 // FIXME: Can a namespace be specified for an attr(foo)?
3004 if (m_style->styleType() == NOPSEUDO)
3005 m_style->setUnique();
3007 m_parentStyle->setUnique();
3008 QualifiedName attr(nullAtom, contentValue->getStringValue().impl(), nullAtom);
3009 const AtomicString& value = m_element->getAttribute(attr);
3010 m_style->setContent(value.isNull() ? emptyAtom : value.impl(), didSet);
3012 // register the fact that the attribute value affects the style
3013 m_features.attrsInRules.add(attr.localName().impl());
3014 } else if (contentValue->isCounter()) {
3015 Counter* counterValue = contentValue->getCounterValue();
3016 EListStyleType listStyleType = NoneListStyle;
3017 int listStyleIdent = counterValue->listStyleIdent();
3018 if (listStyleIdent != CSSValueNone)
3019 listStyleType = static_cast<EListStyleType>(listStyleIdent - CSSValueDisc);
3020 OwnPtr<CounterContent> counter = adoptPtr(new CounterContent(counterValue->identifier(), listStyleType, counterValue->separator()));
3021 m_style->setContent(counter.release(), didSet);
3024 switch (contentValue->getIdent()) {
3025 case CSSValueOpenQuote:
3026 m_style->setContent(OPEN_QUOTE, didSet);
3029 case CSSValueCloseQuote:
3030 m_style->setContent(CLOSE_QUOTE, didSet);
3033 case CSSValueNoOpenQuote:
3034 m_style->setContent(NO_OPEN_QUOTE, didSet);
3037 case CSSValueNoCloseQuote:
3038 m_style->setContent(NO_CLOSE_QUOTE, didSet);
3042 // normal and none do not have any effect.
3048 m_style->clearContent();
3051 case CSSPropertyQuotes:
3053 m_style->setQuotes(m_parentStyle->quotes());
3057 m_style->setQuotes(0);
3060 if (value->isValueList()) {
3061 CSSValueList* list = static_cast<CSSValueList*>(value);
3062 RefPtr<QuotesData> quotes = QuotesData::create();
3063 for (size_t i = 0; i < list->length(); i += 2) {
3064 CSSValue* first = list->itemWithoutBoundsCheck(i);
3065 // item() returns null if out of bounds so this is safe.
3066 CSSValue* second = list->item(i + 1);
3069 ASSERT(first->isPrimitiveValue());
3070 ASSERT(second->isPrimitiveValue());
3071 String startQuote = static_cast<CSSPrimitiveValue*>(first)->getStringValue();
3072 String endQuote = static_cast<CSSPrimitiveValue*>(second)->getStringValue();
3073 quotes->addPair(std::make_pair(startQuote, endQuote));
3075 m_style->setQuotes(quotes);
3078 if (primitiveValue) {
3079 if (primitiveValue->getIdent() == CSSValueNone)
3080 m_style->setQuotes(QuotesData::create());
3083 case CSSPropertyFontFamily: {
3084 // list of strings and ids
3086 FontDescription parentFontDescription = m_parentStyle->fontDescription();
3087 FontDescription fontDescription = m_style->fontDescription();
3088 fontDescription.setGenericFamily(parentFontDescription.genericFamily());
3089 fontDescription.setFamily(parentFontDescription.firstFamily());
3090 fontDescription.setIsSpecifiedFont(parentFontDescription.isSpecifiedFont());
3091 setFontDescription(fontDescription);
3096 FontDescription initialDesc = FontDescription();
3097 FontDescription fontDescription = m_style->fontDescription();
3098 // We need to adjust the size to account for the generic family change from monospace
3099 // to non-monospace.
3100 if (fontDescription.keywordSize() && fontDescription.useFixedDefaultSize())
3101 setFontSize(fontDescription, fontSizeForKeyword(document(), CSSValueXxSmall + fontDescription.keywordSize() - 1, false));
3102 fontDescription.setGenericFamily(initialDesc.genericFamily());
3103 if (!initialDesc.firstFamily().familyIsEmpty())
3104 fontDescription.setFamily(initialDesc.firstFamily());
3105 setFontDescription(fontDescription);
3109 if (!value->isValueList())
3111 FontDescription fontDescription = m_style->fontDescription();
3112 FontFamily& firstFamily = fontDescription.firstFamily();
3113 FontFamily* currFamily = 0;
3115 // Before mapping in a new font-family property, we should reset the generic family.
3116 bool oldFamilyUsedFixedDefaultSize = fontDescription.useFixedDefaultSize();
3117 fontDescription.setGenericFamily(FontDescription::NoFamily);
3119 for (CSSValueListIterator i = value; i.hasMore(); i.advance()) {
3120 CSSValue* item = i.value();
3121 if (!item->isPrimitiveValue())
3123 CSSPrimitiveValue* contentValue = static_cast<CSSPrimitiveValue*>(item);
3125 Settings* settings = documentSettings();
3126 if (contentValue->isString())
3127 face = contentValue->getStringValue();
3128 else if (settings) {
3129 switch (contentValue->getIdent()) {
3130 case CSSValueWebkitBody:
3131 face = settings->standardFontFamily();
3135 fontDescription.setGenericFamily(FontDescription::SerifFamily);
3137 case CSSValueSansSerif:
3138 face = sansSerifFamily;
3139 fontDescription.setGenericFamily(FontDescription::SansSerifFamily);
3141 case CSSValueCursive:
3142 face = cursiveFamily;
3143 fontDescription.setGenericFamily(FontDescription::CursiveFamily);
3145 case CSSValueFantasy:
3146 face = fantasyFamily;
3147 fontDescription.setGenericFamily(FontDescription::FantasyFamily);
3149 case CSSValueMonospace:
3150 face = monospaceFamily;
3151 fontDescription.setGenericFamily(FontDescription::MonospaceFamily);
3153 case CSSValueWebkitPictograph:
3154 face = pictographFamily;
3155 fontDescription.setGenericFamily(FontDescription::PictographFamily);
3160 if (!face.isEmpty()) {
3162 // Filling in the first family.
3163 firstFamily.setFamily(face);
3164 firstFamily.appendFamily(0); // Remove any inherited family-fallback list.
3165 currFamily = &firstFamily;
3166 fontDescription.setIsSpecifiedFont(fontDescription.genericFamily() == FontDescription::NoFamily);
3168 RefPtr<SharedFontFamily> newFamily = SharedFontFamily::create();
3169 newFamily->setFamily(face);
3170 currFamily->appendFamily(newFamily);
3171 currFamily = newFamily.get();
3176 // We can't call useFixedDefaultSize() until all new font families have been added
3177 // If currFamily is non-zero then we set at least one family on this description.
3179 if (fontDescription.keywordSize() && fontDescription.useFixedDefaultSize() != oldFamilyUsedFixedDefaultSize)
3180 setFontSize(fontDescription, fontSizeForKeyword(document(), CSSValueXxSmall + fontDescription.keywordSize() - 1, !oldFamilyUsedFixedDefaultSize));
3182 setFontDescription(fontDescription);
3186 // shorthand properties
3187 case CSSPropertyBackground:
3189 m_style->clearBackgroundLayers();
3190 m_style->setBackgroundColor(Color());
3191 } else if (isInherit) {
3192 m_style->inheritBackgroundLayers(*m_parentStyle->backgroundLayers());
3193 m_style->setBackgroundColor(m_parentStyle->backgroundColor());
3196 case CSSPropertyWebkitMask:
3198 m_style->clearMaskLayers();
3200 m_style->inheritMaskLayers(*m_parentStyle->maskLayers());
3202 case CSSPropertyFont:
3204 FontDescription fontDescription = m_parentStyle->fontDescription();
3205 m_style->setLineHeight(m_parentStyle->specifiedLineHeight());
3206 m_lineHeightValue = 0;
3207 setFontDescription(fontDescription);
3208 } else if (isInitial) {
3209 Settings* settings = documentSettings();
3210 ASSERT(settings); // If we're doing style resolution, this document should always be in a frame and thus have settings
3213 initializeFontStyle(settings);
3214 } else if (primitiveValue) {
3215 m_style->setLineHeight(RenderStyle::initialLineHeight());
3216 m_lineHeightValue = 0;
3218 FontDescription fontDescription;
3219 RenderTheme::defaultTheme()->systemFont(primitiveValue->getIdent(), fontDescription);
3221 // Double-check and see if the theme did anything. If not, don't bother updating the font.
3222 if (fontDescription.isAbsoluteSize()) {
3223 // Make sure the rendering mode and printer font settings are updated.
3224 Settings* settings = documentSettings();
3225 ASSERT(settings); // If we're doing style resolution, this document should always be in a frame and thus have settings
3228 fontDescription.setRenderingMode(settings->fontRenderingMode());
3229 fontDescription.setUsePrinterFont(document()->printing() || !settings->screenFontSubstitutionEnabled());
3231 // Handle the zoom factor.
3232 fontDescription.setComputedSize(getComputedSizeFromSpecifiedSize(document(), m_style.get(), fontDescription.isAbsoluteSize(), fontDescription.specifiedSize(), useSVGZoomRules()));
3233 setFontDescription(fontDescription);
3235 } else if (value->isFontValue()) {
3236 FontValue* font = static_cast<FontValue*>(value);
3237 if (!font->style || !font->variant || !font->weight
3238 || !font->size || !font->lineHeight || !font->family)
3240 applyProperty(CSSPropertyFontStyle, font->style.get());
3241 applyProperty(CSSPropertyFontVariant, font->variant.get());
3242 applyProperty(CSSPropertyFontWeight, font->weight.get());
3243 // The previous properties can dirty our font but they don't try to read the font's
3244 // properties back, which is safe. However if font-size is using the 'ex' unit, it will
3245 // need query the dirtied font's x-height to get the computed size. To be safe in this
3246 // case, let's just update the font now.
3248 applyProperty(CSSPropertyFontSize, font->size.get());
3250 m_lineHeightValue = font->lineHeight.get();
3252 applyProperty(CSSPropertyFontFamily, font->family.get());
3257 case CSSPropertyTextShadow:
3258 case CSSPropertyBoxShadow:
3259 case CSSPropertyWebkitBoxShadow: {
3261 if (id == CSSPropertyTextShadow)
3262 return m_style->setTextShadow(m_parentStyle->textShadow() ? adoptPtr(new ShadowData(*m_parentStyle->textShadow())) : nullptr);
3263 return m_style->setBoxShadow(m_parentStyle->boxShadow() ? adoptPtr(new ShadowData(*m_parentStyle->boxShadow())) : nullptr);
3265 if (isInitial || primitiveValue) // initial | none
3266 return id == CSSPropertyTextShadow ? m_style->setTextShadow(nullptr) : m_style->setBoxShadow(nullptr);
3268 if (!value->isValueList())
3271 for (CSSValueListIterator i = value; i.hasMore(); i.advance()) {
3272 CSSValue* currValue = i.value();
3273 if (!currValue->isShadowValue())
3275 ShadowValue* item = static_cast<ShadowValue*>(currValue);
3276 int x = item->x->computeLength<int>(style(), m_rootElementStyle, zoomFactor);
3277 int y = item->y->computeLength<int>(style(), m_rootElementStyle, zoomFactor);
3278 int blur = item->blur ? item->blur->computeLength<int>(style(), m_rootElementStyle, zoomFactor) : 0;
3279 int spread = item->spread ? item->spread->computeLength<int>(style(), m_rootElementStyle, zoomFactor) : 0;
3280 ShadowStyle shadowStyle = item->style && item->style->getIdent() == CSSValueInset ? Inset : Normal;
3283 color = colorFromPrimitiveValue(item->color.get());
3285 color = m_style->color();
3287 OwnPtr<ShadowData> shadowData = adoptPtr(new ShadowData(IntPoint(x, y), blur, spread, shadowStyle, id == CSSPropertyWebkitBoxShadow, color.isValid() ? color : Color::transparent));
3288 if (id == CSSPropertyTextShadow)
3289 m_style->setTextShadow(shadowData.release(), i.index()); // add to the list if this is not the first entry
3291 m_style->setBoxShadow(shadowData.release(), i.index()); // add to the list if this is not the first entry
3295 case CSSPropertyWebkitBoxReflect: {
3296 HANDLE_INHERIT_AND_INITIAL(boxReflect, BoxReflect)
3297 if (primitiveValue) {
3298 m_style->setBoxReflect(RenderStyle::initialBoxReflect());
3302 if (!value->isReflectValue())
3305 CSSReflectValue* reflectValue = static_cast<CSSReflectValue*>(value);
3306 RefPtr<StyleReflection> reflection = StyleReflection::create();
3307 reflection->setDirection(reflectValue->direction());
3308 if (reflectValue->offset())
3309 reflection->setOffset(reflectValue->offset()->convertToLength<FixedIntegerConversion | PercentConversion | CalculatedConversion>(style(), m_rootElementStyle, zoomFactor));
3310 NinePieceImage mask;
3311 mask.setMaskDefaults();
3312 m_styleMap.mapNinePieceImage(id, reflectValue->mask(), mask);
3313 reflection->setMask(mask);
3315 m_style->setBoxReflect(reflection.release());
3318 case CSSPropertySrc: // Only used in @font-face rules.
3320 case CSSPropertyUnicodeRange: // Only used in @font-face rules.
3322 case CSSPropertyWebkitColumnRule:
3324 m_style->setColumnRuleColor(m_parentStyle->columnRuleColor().isValid() ? m_parentStyle->columnRuleColor() : m_parentStyle->color());
3325 m_style->setColumnRuleStyle(m_parentStyle->columnRuleStyle());
3326 m_style->setColumnRuleWidth(m_parentStyle->columnRuleWidth());
3327 } else if (isInitial)
3328 m_style->resetColumnRule();
3330 case CSSPropertyWebkitMarquee:
3333 m_style->setMarqueeDirection(m_parentStyle->marqueeDirection());
3334 m_style->setMarqueeIncrement(m_parentStyle->marqueeIncrement());
3335 m_style->setMarqueeSpeed(m_parentStyle->marqueeSpeed());
3336 m_style->setMarqueeLoopCount(m_parentStyle->marqueeLoopCount());
3337 m_style->setMarqueeBehavior(m_parentStyle->marqueeBehavior());
3339 case CSSPropertyWebkitMarqueeRepetition: {
3340 HANDLE_INHERIT_AND_INITIAL(marqueeLoopCount, MarqueeLoopCount)
3341 if (!primitiveValue)
3343 if (primitiveValue->getIdent() == CSSValueInfinite)
3344 m_style->setMarqueeLoopCount(-1); // -1 means repeat forever.
3345 else if (primitiveValue->isNumber())
3346 m_style->setMarqueeLoopCount(primitiveValue->getIntValue());
3349 case CSSPropertyWebkitMarqueeSpeed: {
3350 HANDLE_INHERIT_AND_INITIAL(marqueeSpeed, MarqueeSpeed)
3351 if (!primitiveValue)
3353 if (int ident = primitiveValue->getIdent()) {
3356 m_style->setMarqueeSpeed(500); // 500 msec.
3358 case CSSValueNormal:
3359 m_style->setMarqueeSpeed(85); // 85msec. The WinIE default.
3362 m_style->setMarqueeSpeed(10); // 10msec. Super fast.
3365 } else if (primitiveValue->isTime())
3366 m_style->setMarqueeSpeed(primitiveValue->computeTime<int, CSSPrimitiveValue::Milliseconds>());
3367 else if (primitiveValue->isNumber()) // For scrollamount support.
3368 m_style->setMarqueeSpeed(primitiveValue->getIntValue());
3371 case CSSPropertyWebkitMarqueeIncrement: {
3372 HANDLE_INHERIT_AND_INITIAL(marqueeIncrement, MarqueeIncrement)
3373 if (!primitiveValue)
3375 if (primitiveValue->getIdent()) {
3376 switch (primitiveValue->getIdent()) {
3378 m_style->setMarqueeIncrement(Length(1, Fixed)); // 1px.