2 * Copyright (C) 1999 Lars Knoll (knoll@kde.org)
3 * Copyright (C) 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011 Apple Inc. All rights reserved.
5 * This library is free software; you can redistribute it and/or
6 * modify it under the terms of the GNU Library General Public
7 * License as published by the Free Software Foundation; either
8 * version 2 of the License, or (at your option) any later version.
10 * This library is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 * Library General Public License for more details.
15 * You should have received a copy of the GNU Library General Public License
16 * along with this library; see the file COPYING.LIB. If not, write to
17 * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
18 * Boston, MA 02110-1301, USA.
22 #ifndef StyleResolver_h
23 #define StyleResolver_h
26 #include "CSSToStyleMap.h"
27 #include "CSSValueList.h"
29 #include "MediaQueryExp.h"
30 #include "RenderStyle.h"
31 #include "SelectorChecker.h"
32 #include <wtf/HashMap.h>
33 #include <wtf/HashSet.h>
34 #include <wtf/RefPtr.h>
35 #include <wtf/Vector.h>
36 #include <wtf/text/AtomicStringHash.h>
37 #include <wtf/text/StringHash.h>
41 enum ESmartMinimumForFontSize { DoNotUseSmartMinimumForFontSize, UseSmartMinimumForFontFize };
43 class CSSFontSelector;
45 class CSSPrimitiveValue;
49 class CSSFontFaceRule;
50 class CSSImageGeneratorValue;
51 class CSSImageSetValue;
58 class CustomFilterOperation;
59 class CustomFilterParameter;
67 class MediaQueryEvaluator;
68 class MemoryObjectInfo;
74 class StaticCSSRuleList;
78 class StylePendingImage;
79 class StylePropertySet;
81 class StyleRuleKeyframes;
83 class StyleRuleRegion;
86 class StyleSheetContents;
89 class WebKitCSSFilterValue;
90 class WebKitCSSShaderValue;
91 class WebKitCSSSVGDocumentValue;
93 #if ENABLE(CSS_SHADERS)
94 typedef Vector<RefPtr<CustomFilterParameter> > CustomFilterParameterList;
97 class MediaQueryResult {
98 WTF_MAKE_NONCOPYABLE(MediaQueryResult); WTF_MAKE_FAST_ALLOCATED;
100 MediaQueryResult(const MediaQueryExp& expr, bool result)
106 MediaQueryExp m_expression;
110 enum StyleSharingBehavior {
112 DisallowStyleSharing,
115 // MatchOnlyUserAgentRules is used in media queries, where relative units
116 // are interpreted according to the document root element style, and styled only
117 // from the User Agent Stylesheet rules.
119 enum RuleMatchingBehavior {
121 MatchAllRulesExcludingSMIL,
122 MatchOnlyUserAgentRules,
125 // This class selects a RenderStyle for a given element based on a collection of stylesheets.
126 class StyleResolver {
127 WTF_MAKE_NONCOPYABLE(StyleResolver); WTF_MAKE_FAST_ALLOCATED;
129 StyleResolver(Document*, bool matchAuthorAndUserStyles);
132 // Using these during tree walk will allow style selector to optimize child and descendant selector lookups.
133 void pushParentElement(Element*);
134 void popParentElement(Element*);
135 void pushParentShadowRoot(const ShadowRoot*);
136 void popParentShadowRoot(const ShadowRoot*);
138 PassRefPtr<RenderStyle> styleForElement(Element*, RenderStyle* parentStyle = 0, StyleSharingBehavior = AllowStyleSharing,
139 RuleMatchingBehavior = MatchAllRules, RenderRegion* regionForStyling = 0);
141 void keyframeStylesForAnimation(Element*, const RenderStyle*, KeyframeList&);
143 PassRefPtr<RenderStyle> pseudoStyleForElement(PseudoId, Element*, RenderStyle* parentStyle = 0);
145 PassRefPtr<RenderStyle> styleForPage(int pageIndex);
147 static PassRefPtr<RenderStyle> styleForDocument(Document*, CSSFontSelector* = 0);
149 RenderStyle* style() const { return m_style.get(); }
150 RenderStyle* parentStyle() const { return m_parentStyle; }
151 RenderStyle* rootElementStyle() const { return m_rootElementStyle; }
152 Element* element() const { return m_element; }
153 Document* document() const { return m_checker.document(); }
154 const FontDescription& fontDescription() { return style()->fontDescription(); }
155 const FontDescription& parentFontDescription() { return parentStyle()->fontDescription(); }
156 void setFontDescription(const FontDescription& fontDescription) { m_fontDirty |= style()->setFontDescription(fontDescription); }
157 void setZoom(float f) { m_fontDirty |= style()->setZoom(f); }
158 void setEffectiveZoom(float f) { m_fontDirty |= style()->setEffectiveZoom(f); }
159 void setTextSizeAdjust(bool b) { m_fontDirty |= style()->setTextSizeAdjust(b); }
160 bool hasParentNode() const { return m_parentNode; }
162 void appendAuthorStylesheets(unsigned firstNew, const Vector<RefPtr<StyleSheet> >&);
164 // Find the ids or classes the selectors on a stylesheet are scoped to. The selectors only apply to elements in subtrees where the root element matches the scope.
165 static bool determineStylesheetSelectorScopes(StyleSheetContents*, HashSet<AtomicStringImpl*>& idScopes, HashSet<AtomicStringImpl*>& classScopes);
168 void initForStyleResolve(Element*, RenderStyle* parentStyle = 0, PseudoId = NOPSEUDO);
169 void initElement(Element*);
170 void collectFeatures();
171 RenderStyle* locateSharedStyle();
172 bool matchesRuleSet(RuleSet*);
173 Node* locateCousinList(Element* parent, unsigned& visitedNodeCount) const;
174 StyledElement* findSiblingForStyleSharing(Node*, unsigned& count) const;
175 bool canShareStyleWithElement(StyledElement*) const;
177 PassRefPtr<RenderStyle> styleForKeyframe(const RenderStyle*, const StyleKeyframe*, KeyframeValue&);
179 #if ENABLE(STYLE_SCOPED)
180 void pushScope(const ContainerNode* scope, const ContainerNode* scopeParent);
181 void popScope(const ContainerNode* scope);
183 void pushScope(const ContainerNode*, const ContainerNode*) { }
184 void popScope(const ContainerNode*) { }
188 // These methods will give back the set of rules that matched for a given element (or a pseudo-element).
190 UAAndUserCSSRules = 1 << 1,
191 AuthorCSSRules = 1 << 2,
192 EmptyCSSRules = 1 << 3,
193 CrossOriginCSSRules = 1 << 4,
194 AllButEmptyCSSRules = UAAndUserCSSRules | AuthorCSSRules | CrossOriginCSSRules,
195 AllCSSRules = AllButEmptyCSSRules | EmptyCSSRules,
197 PassRefPtr<CSSRuleList> styleRulesForElement(Element*, unsigned rulesToInclude = AllButEmptyCSSRules);
198 PassRefPtr<CSSRuleList> pseudoStyleRulesForElement(Element*, PseudoId, unsigned rulesToInclude = AllButEmptyCSSRules);
200 // Given a CSS keyword in the range (xx-small to -webkit-xxx-large), this function will return
201 // the correct font size scaled relative to the user's default (medium).
202 static float fontSizeForKeyword(Document*, int keyword, bool shouldUseFixedDefaultSize);
204 // Given a font size in pixel, this function will return legacy font size between 1 and 7.
205 static int legacyFontSize(Document*, int pixelFontSize, bool shouldUseFixedDefaultSize);
208 void setStyle(PassRefPtr<RenderStyle> s) { m_style = s; } // Used by the document when setting up its root style.
210 void applyPropertyToStyle(CSSPropertyID, CSSValue*, RenderStyle*);
212 void applyPropertyToCurrentStyle(CSSPropertyID, CSSValue*);
215 void initializeFontStyle(Settings*);
217 static float getComputedSizeFromSpecifiedSize(Document*, float zoomFactor, bool isAbsoluteSize, float specifiedSize, ESmartMinimumForFontSize = UseSmartMinimumForFontFize);
219 void setFontSize(FontDescription&, float size);
222 static float getComputedSizeFromSpecifiedSize(Document*, RenderStyle*, bool isAbsoluteSize, float specifiedSize, bool useSVGZoomRules);
225 bool useSVGZoomRules();
227 static bool colorFromPrimitiveValueIsDerivedFromElement(CSSPrimitiveValue*);
228 Color colorFromPrimitiveValue(CSSPrimitiveValue*, bool forVisitedLink = false) const;
230 bool hasSelectorForAttribute(const AtomicString&) const;
232 CSSFontSelector* fontSelector() const { return m_fontSelector.get(); }
234 void addViewportDependentMediaQueryResult(const MediaQueryExp*, bool result);
236 bool affectedByViewportChange() const;
238 void allVisitedStateChanged() { m_checker.allVisitedStateChanged(); }
239 void visitedStateChanged(LinkHash visitedHash) { m_checker.visitedStateChanged(visitedHash); }
241 void addKeyframeStyle(PassRefPtr<StyleRuleKeyframes>);
243 bool checkRegionStyle(Element* regionElement);
245 bool usesSiblingRules() const { return !m_features.siblingRules.isEmpty(); }
246 bool usesFirstLineRules() const { return m_features.usesFirstLineRules; }
247 bool usesBeforeAfterRules() const { return m_features.usesBeforeAfterRules; }
248 bool usesLinkRules() const { return m_features.usesLinkRules; }
250 static bool createTransformOperations(CSSValue* inValue, RenderStyle* inStyle, RenderStyle* rootStyle, TransformOperations& outOperations);
252 void invalidateMatchedPropertiesCache();
254 // WARNING. This will construct CSSOM wrappers for all style rules and cache then in a map for significant memory cost.
255 // It is here to support inspector. Don't use for any regular engine functions.
256 CSSStyleRule* ensureFullCSSOMWrapperForInspector(StyleRule*);
258 #if ENABLE(CSS_FILTERS)
259 bool createFilterOperations(CSSValue* inValue, RenderStyle* inStyle, RenderStyle* rootStyle, FilterOperations& outOperations);
260 #if ENABLE(CSS_SHADERS)
261 StyleShader* styleShader(CSSValue*);
262 StyleShader* cachedOrPendingStyleShaderFromValue(WebKitCSSShaderValue*);
263 bool parseCustomFilterParameterList(CSSValue*, CustomFilterParameterList&);
264 PassRefPtr<CustomFilterParameter> parseCustomFilterNumberParamter(const String& name, CSSValueList*);
265 PassRefPtr<CustomFilterOperation> createCustomFilterOperation(WebKitCSSFilterValue*);
266 void loadPendingShaders();
269 void loadPendingSVGDocuments();
271 #endif // ENABLE(CSS_FILTERS)
273 void loadPendingResources();
276 RuleFeature(StyleRule* rule, CSSSelector* selector, bool hasDocumentSecurityOrigin)
279 , hasDocumentSecurityOrigin(hasDocumentSecurityOrigin)
283 CSSSelector* selector;
284 bool hasDocumentSecurityOrigin;
289 void add(const StyleResolver::Features&);
291 void reportMemoryUsage(MemoryObjectInfo*) const;
292 HashSet<AtomicStringImpl*> idsInRules;
293 HashSet<AtomicStringImpl*> attrsInRules;
294 Vector<RuleFeature> siblingRules;
295 Vector<RuleFeature> uncommonAttributeRules;
296 bool usesFirstLineRules;
297 bool usesBeforeAfterRules;
302 // This function fixes up the default font size if it detects that the current generic font family has changed. -dwh
303 void checkForGenericFamilyChange(RenderStyle*, RenderStyle* parentStyle);
304 void checkForZoomChange(RenderStyle*, RenderStyle* parentStyle);
305 void checkForTextSizeAdjust();
307 void adjustRenderStyle(RenderStyle* styleToAdjust, RenderStyle* parentStyle, Element*);
309 void addMatchedRule(const RuleData* rule) { m_matchedRules.append(rule); }
312 MatchRanges() : firstUARule(-1), lastUARule(-1), firstAuthorRule(-1), lastAuthorRule(-1), firstUserRule(-1), lastUserRule(-1) { }
321 struct MatchedProperties {
322 MatchedProperties() : possiblyPaddedMember(0) { }
324 RefPtr<StylePropertySet> properties;
327 unsigned linkMatchType : 2;
328 unsigned isInRegionRule : 1;
330 // Used to make sure all memory is zero-initialized since we compute the hash over the bytes of this object.
331 void* possiblyPaddedMember;
336 MatchResult() : isCacheable(true) { }
337 Vector<MatchedProperties, 64> matchedProperties;
338 Vector<StyleRule*, 64> matchedRules;
343 struct MatchOptions {
344 MatchOptions(bool includeEmptyRules, const ContainerNode* scope = 0) : scope(scope), includeEmptyRules(includeEmptyRules) { }
345 const ContainerNode* scope;
346 bool includeEmptyRules;
349 static void addMatchedProperties(MatchResult&, const StylePropertySet* properties, StyleRule* = 0, unsigned linkMatchType = SelectorChecker::MatchAll, bool inRegionRule = false);
350 void addElementStyleProperties(MatchResult&, const StylePropertySet*, bool isCacheable = true);
352 void matchAllRules(MatchResult&, bool includeSMILProperties);
353 void matchUARules(MatchResult&);
354 void matchUARules(MatchResult&, RuleSet*);
355 void matchAuthorRules(MatchResult&, bool includeEmptyRules);
356 void matchUserRules(MatchResult&, bool includeEmptyRules);
357 void matchScopedAuthorRules(MatchResult&, bool includeEmptyRules);
358 void collectMatchingRules(RuleSet*, int& firstRuleIndex, int& lastRuleIndex, const MatchOptions&);
359 void collectMatchingRulesForRegion(RuleSet*, int& firstRuleIndex, int& lastRuleIndex, const MatchOptions&);
360 void collectMatchingRulesForList(const Vector<RuleData>*, int& firstRuleIndex, int& lastRuleIndex, const MatchOptions&);
361 bool fastRejectSelector(const RuleData&) const;
362 void sortMatchedRules();
363 void sortAndTransferMatchedRules(MatchResult&);
365 bool checkSelector(const RuleData&, const ContainerNode* scope = 0);
366 bool checkRegionSelector(CSSSelector* regionSelector, Element* regionElement);
367 void applyMatchedProperties(const MatchResult&, const Element*);
368 enum StyleApplicationPass {
369 #if ENABLE(CSS_VARIABLES)
372 HighPriorityProperties,
373 LowPriorityProperties
375 template <StyleApplicationPass pass>
376 void applyMatchedProperties(const MatchResult&, bool important, int startIndex, int endIndex, bool inheritedOnly);
377 template <StyleApplicationPass pass>
378 void applyProperties(const StylePropertySet* properties, StyleRule*, bool isImportant, bool inheritedOnly, bool filterRegionProperties);
379 #if ENABLE(CSS_VARIABLES)
380 void resolveVariables(CSSPropertyID, CSSValue*, Vector<std::pair<CSSPropertyID, String> >& knownExpressions);
382 static bool isValidRegionStyleProperty(CSSPropertyID);
384 void matchPageRules(MatchResult&, RuleSet*, bool isLeftPage, bool isFirstPage, const String& pageName);
385 void matchPageRulesForList(Vector<StyleRulePage*>& matchedRules, const Vector<StyleRulePage*>&, bool isLeftPage, bool isFirstPage, const String& pageName);
386 Settings* documentSettings() { return m_checker.document()->settings(); }
388 bool isLeftPage(int pageIndex) const;
389 bool isRightPage(int pageIndex) const { return !isLeftPage(pageIndex); }
390 bool isFirstPage(int pageIndex) const;
391 String pageName(int pageIndex) const;
393 OwnPtr<RuleSet> m_authorStyle;
394 OwnPtr<RuleSet> m_userStyle;
397 OwnPtr<RuleSet> m_siblingRuleSet;
398 OwnPtr<RuleSet> m_uncommonAttributeRuleSet;
400 bool m_hasUAAppearance;
401 BorderData m_borderData;
402 FillLayer m_backgroundData;
403 Color m_backgroundColor;
405 typedef HashMap<AtomicStringImpl*, RefPtr<StyleRuleKeyframes> > KeyframesRuleMap;
406 KeyframesRuleMap m_keyframesRuleMap;
409 static RenderStyle* styleNotYetAvailable() { return s_styleNotYetAvailable; }
411 PassRefPtr<StyleImage> styleImage(CSSPropertyID, CSSValue*);
412 PassRefPtr<StyleImage> cachedOrPendingFromValue(CSSPropertyID, CSSImageValue*);
413 PassRefPtr<StyleImage> generatedOrPendingFromValue(CSSPropertyID, CSSImageGeneratorValue*);
414 #if ENABLE(CSS_IMAGE_SET)
415 PassRefPtr<StyleImage> setOrPendingFromValue(CSSPropertyID, CSSImageSetValue*);
418 bool applyPropertyToRegularStyle() const { return m_applyPropertyToRegularStyle; }
419 bool applyPropertyToVisitedLinkStyle() const { return m_applyPropertyToVisitedLinkStyle; }
421 static Length convertToIntLength(CSSPrimitiveValue*, RenderStyle*, RenderStyle* rootStyle, double multiplier = 1);
422 static Length convertToFloatLength(CSSPrimitiveValue*, RenderStyle*, RenderStyle* rootStyle, double multiplier = 1);
424 CSSToStyleMap* styleMap() { return &m_styleMap; }
426 void reportMemoryUsage(MemoryObjectInfo*) const;
429 static RenderStyle* s_styleNotYetAvailable;
431 void addStylesheetsFromSeamlessParents();
432 void addAuthorRulesAndCollectUserRulesFromSheets(const Vector<RefPtr<CSSStyleSheet> >*, RuleSet& userStyle);
434 void cacheBorderAndBackground();
437 bool canShareStyleWithControl(StyledElement*) const;
439 void applyProperty(CSSPropertyID, CSSValue*);
442 void applySVGProperty(CSSPropertyID, CSSValue*);
445 PassRefPtr<StyleImage> loadPendingImage(StylePendingImage*);
446 void loadPendingImages();
448 static unsigned computeMatchedPropertiesHash(const MatchedProperties*, unsigned size);
449 struct MatchedPropertiesCacheItem {
450 Vector<MatchedProperties> matchedProperties;
452 RefPtr<RenderStyle> renderStyle;
453 RefPtr<RenderStyle> parentRenderStyle;
455 const MatchedPropertiesCacheItem* findFromMatchedPropertiesCache(unsigned hash, const MatchResult&);
456 void addToMatchedPropertiesCache(const RenderStyle*, const RenderStyle* parentStyle, unsigned hash, const MatchResult&);
458 // Every N additions to the matched declaration cache trigger a sweep where entries holding
459 // the last reference to a style declaration are garbage collected.
460 void sweepMatchedPropertiesCache();
462 unsigned m_matchedPropertiesCacheAdditionsSinceLastSweep;
464 typedef HashMap<unsigned, MatchedPropertiesCacheItem> MatchedPropertiesCache;
465 MatchedPropertiesCache m_matchedPropertiesCache;
467 // A buffer used to hold the set of matched rules for an element, and a temporary buffer used for
469 Vector<const RuleData*, 32> m_matchedRules;
471 RefPtr<StaticCSSRuleList> m_ruleList;
473 HashSet<CSSPropertyID> m_pendingImageProperties;
475 OwnPtr<MediaQueryEvaluator> m_medium;
476 RefPtr<RenderStyle> m_rootDefaultStyle;
478 PseudoId m_dynamicPseudo;
480 SelectorChecker m_checker;
482 RefPtr<RenderStyle> m_style;
483 RenderStyle* m_parentStyle;
484 RenderStyle* m_rootElementStyle;
486 StyledElement* m_styledElement;
487 RenderRegion* m_regionForStyling;
488 EInsideLink m_elementLinkState;
489 ContainerNode* m_parentNode;
490 CSSValue* m_lineHeightValue;
492 bool m_matchAuthorAndUserStyles;
493 bool m_sameOriginOnly;
495 RefPtr<CSSFontSelector> m_fontSelector;
496 Vector<OwnPtr<MediaQueryResult> > m_viewportDependentMediaQueryResults;
498 bool m_applyPropertyToRegularStyle;
499 bool m_applyPropertyToVisitedLinkStyle;
500 const StyleBuilder& m_styleBuilder;
502 HashMap<StyleRule*, RefPtr<CSSStyleRule> > m_styleRuleToCSSOMWrapperMap;
503 HashSet<RefPtr<CSSStyleSheet> > m_styleSheetCSSOMWrapperSet;
505 #if ENABLE(CSS_SHADERS)
506 bool m_hasPendingShaders;
509 #if ENABLE(CSS_FILTERS) && ENABLE(SVG)
510 HashMap<FilterOperation*, WebKitCSSSVGDocumentValue*> m_pendingSVGDocuments;
513 #if ENABLE(STYLE_SCOPED)
514 const ContainerNode* determineScope(const CSSStyleSheet*);
516 typedef HashMap<const ContainerNode*, OwnPtr<RuleSet> > ScopedRuleSetMap;
518 RuleSet* ruleSetForScope(const ContainerNode*) const;
520 void setupScopeStack(const ContainerNode*);
521 bool scopeStackIsConsistent(const ContainerNode* parent) const { return parent && parent == m_scopeStackParent; }
523 ScopedRuleSetMap m_scopedAuthorStyles;
525 struct ScopeStackFrame {
526 ScopeStackFrame() : m_scope(0), m_authorStyleBoundsIndex(0), m_ruleSet(0) { }
527 ScopeStackFrame(const ContainerNode* scope, int authorStyleBoundsIndex, RuleSet* ruleSet) : m_scope(scope), m_authorStyleBoundsIndex(authorStyleBoundsIndex), m_ruleSet(ruleSet) { }
528 const ContainerNode* m_scope;
529 int m_authorStyleBoundsIndex;
532 // Vector (used as stack) that keeps track of scoping elements (i.e., elements with a <style scoped> child)
533 // encountered during tree iteration for style resolution.
534 Vector<ScopeStackFrame> m_scopeStack;
535 // Element last seen as parent element when updating m_scopingElementStack.
536 // This is used to decide whether m_scopingElementStack is consistent, separately from SelectorChecker::m_parentStack.
537 const ContainerNode* m_scopeStackParent;
538 int m_scopeStackParentBoundsIndex;
541 CSSToStyleMap m_styleMap;
543 friend class StyleBuilder;
544 friend bool operator==(const MatchedProperties&, const MatchedProperties&);
545 friend bool operator!=(const MatchedProperties&, const MatchedProperties&);
546 friend bool operator==(const MatchRanges&, const MatchRanges&);
547 friend bool operator!=(const MatchRanges&, const MatchRanges&);
550 } // namespace WebCore
552 #endif // StyleResolver_h