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 CSSStyleSelector_h
23 #define CSSStyleSelector_h
26 #include "CSSValueList.h"
28 #include "MediaQueryExp.h"
29 #include "RenderStyle.h"
30 #include "SelectorChecker.h"
31 #include <wtf/HashMap.h>
32 #include <wtf/HashSet.h>
33 #include <wtf/RefPtr.h>
34 #include <wtf/Vector.h>
35 #include <wtf/text/StringHash.h>
39 enum ESmartMinimumForFontSize { DoNotUseSmartMinimumForFontSize, UseSmartMinimumForFontFize };
41 class CSSFontSelector;
43 class CSSPrimitiveValue;
47 class CSSFontFaceRule;
48 class CSSImageGeneratorValue;
49 class CSSImageSetValue;
52 class CSSStyleApplyProperty;
57 class CustomFilterOperation;
58 class CustomFilterParameter;
66 class MediaQueryEvaluator;
72 class StaticCSSRuleList;
75 class StylePendingImage;
76 class StylePropertySet;
78 class StyleRuleKeyframes;
80 class StyleRuleRegion;
85 class WebKitCSSFilterValue;
86 class WebKitCSSShaderValue;
88 #if ENABLE(CSS_SHADERS)
89 typedef Vector<RefPtr<CustomFilterParameter> > CustomFilterParameterList;
92 class MediaQueryResult {
93 WTF_MAKE_NONCOPYABLE(MediaQueryResult); WTF_MAKE_FAST_ALLOCATED;
95 MediaQueryResult(const MediaQueryExp& expr, bool result)
101 MediaQueryExp m_expression;
105 enum StyleSharingBehavior {
107 DisallowStyleSharing,
110 // MatchOnlyUserAgentRules is used in media queries, where relative units
111 // are interpreted according to the document root element style, and styled only
112 // from the User Agent Stylesheet rules.
114 enum RuleMatchingBehavior {
116 MatchOnlyUserAgentRules,
119 // This class selects a RenderStyle for a given element based on a collection of stylesheets.
120 class CSSStyleSelector {
121 WTF_MAKE_NONCOPYABLE(CSSStyleSelector); WTF_MAKE_FAST_ALLOCATED;
123 CSSStyleSelector(Document*, bool matchAuthorAndUserStyles);
126 // Using these during tree walk will allow style selector to optimize child and descendant selector lookups.
127 void pushParentElement(Element*);
128 void popParentElement(Element*);
129 void pushParentShadowRoot(const ShadowRoot*);
130 void popParentShadowRoot(const ShadowRoot*);
132 PassRefPtr<RenderStyle> styleForElement(Element*, RenderStyle* parentStyle = 0, StyleSharingBehavior = AllowStyleSharing,
133 RuleMatchingBehavior = MatchAllRules, RenderRegion* regionForStyling = 0);
135 void keyframeStylesForAnimation(Element*, const RenderStyle*, KeyframeList&);
137 PassRefPtr<RenderStyle> pseudoStyleForElement(PseudoId, Element*, RenderStyle* parentStyle = 0);
139 PassRefPtr<RenderStyle> styleForPage(int pageIndex);
141 static PassRefPtr<RenderStyle> styleForDocument(Document*, CSSFontSelector* = 0);
143 RenderStyle* style() const { return m_style.get(); }
144 RenderStyle* parentStyle() const { return m_parentStyle; }
145 RenderStyle* rootElementStyle() const { return m_rootElementStyle; }
146 Element* element() const { return m_element; }
147 Document* document() const { return m_checker.document(); }
148 FontDescription fontDescription() { return style()->fontDescription(); }
149 FontDescription parentFontDescription() {return parentStyle()->fontDescription(); }
150 void setFontDescription(FontDescription fontDescription) { m_fontDirty |= style()->setFontDescription(fontDescription); }
151 void setZoom(float f) { m_fontDirty |= style()->setZoom(f); }
152 void setEffectiveZoom(float f) { m_fontDirty |= style()->setEffectiveZoom(f); }
153 void setTextSizeAdjust(bool b) { m_fontDirty |= style()->setTextSizeAdjust(b); }
154 bool hasParentNode() const { return m_parentNode; }
156 void appendAuthorStylesheets(unsigned firstNew, const Vector<RefPtr<StyleSheet> >&);
158 // 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.
159 static bool determineStylesheetSelectorScopes(CSSStyleSheet*, HashSet<AtomicStringImpl*>& idScopes, HashSet<AtomicStringImpl*>& classScopes);
162 void initForStyleResolve(Element*, RenderStyle* parentStyle = 0, PseudoId = NOPSEUDO);
163 void initElement(Element*);
164 void collectFeatures();
165 RenderStyle* locateSharedStyle();
166 bool matchesRuleSet(RuleSet*);
167 Node* locateCousinList(Element* parent, unsigned& visitedNodeCount) const;
168 StyledElement* findSiblingForStyleSharing(Node*, unsigned& count) const;
169 bool canShareStyleWithElement(StyledElement*) const;
171 PassRefPtr<RenderStyle> styleForKeyframe(const RenderStyle*, const StyleKeyframe*, KeyframeValue&);
173 #if ENABLE(STYLE_SCOPED)
174 void pushScope(const ContainerNode* scope, const ContainerNode* scopeParent);
175 void popScope(const ContainerNode* scope);
177 void pushScope(const ContainerNode*, const ContainerNode*) { }
178 void popScope(const ContainerNode*) { }
182 // These methods will give back the set of rules that matched for a given element (or a pseudo-element).
184 UAAndUserCSSRules = 1 << 1,
185 AuthorCSSRules = 1 << 2,
186 EmptyCSSRules = 1 << 3,
187 CrossOriginCSSRules = 1 << 4,
188 AllButEmptyCSSRules = UAAndUserCSSRules | AuthorCSSRules | CrossOriginCSSRules,
189 AllCSSRules = AllButEmptyCSSRules | EmptyCSSRules,
191 PassRefPtr<CSSRuleList> styleRulesForElement(Element*, unsigned rulesToInclude = AllButEmptyCSSRules);
192 PassRefPtr<CSSRuleList> pseudoStyleRulesForElement(Element*, PseudoId, unsigned rulesToInclude = AllButEmptyCSSRules);
194 // Given a CSS keyword in the range (xx-small to -webkit-xxx-large), this function will return
195 // the correct font size scaled relative to the user's default (medium).
196 static float fontSizeForKeyword(Document*, int keyword, bool shouldUseFixedDefaultSize);
198 // Given a font size in pixel, this function will return legacy font size between 1 and 7.
199 static int legacyFontSize(Document*, int pixelFontSize, bool shouldUseFixedDefaultSize);
202 void setStyle(PassRefPtr<RenderStyle> s) { m_style = s; } // Used by the document when setting up its root style.
204 void applyPropertyToStyle(int id, CSSValue*, RenderStyle*);
206 void applyPropertyToCurrentStyle(int id, CSSValue*);
210 static float getComputedSizeFromSpecifiedSize(Document*, float zoomFactor, bool isAbsoluteSize, float specifiedSize, ESmartMinimumForFontSize = UseSmartMinimumForFontFize);
212 void setFontSize(FontDescription&, float size);
215 static float getComputedSizeFromSpecifiedSize(Document*, RenderStyle*, bool isAbsoluteSize, float specifiedSize, bool useSVGZoomRules);
218 bool useSVGZoomRules();
220 Color colorFromPrimitiveValue(CSSPrimitiveValue*, bool forVisitedLink = false) const;
222 bool hasSelectorForAttribute(const AtomicString&) const;
224 CSSFontSelector* fontSelector() const { return m_fontSelector.get(); }
226 void addViewportDependentMediaQueryResult(const MediaQueryExp*, bool result);
228 bool affectedByViewportChange() const;
230 void allVisitedStateChanged() { m_checker.allVisitedStateChanged(); }
231 void visitedStateChanged(LinkHash visitedHash) { m_checker.visitedStateChanged(visitedHash); }
233 void addKeyframeStyle(PassRefPtr<StyleRuleKeyframes>);
235 bool checkRegionStyle(Element* regionElement);
237 bool usesSiblingRules() const { return !m_features.siblingRules.isEmpty(); }
238 bool usesFirstLineRules() const { return m_features.usesFirstLineRules; }
239 bool usesBeforeAfterRules() const { return m_features.usesBeforeAfterRules; }
240 bool usesLinkRules() const { return m_features.usesLinkRules; }
242 static bool createTransformOperations(CSSValue* inValue, RenderStyle* inStyle, RenderStyle* rootStyle, TransformOperations& outOperations);
244 void invalidateMatchedPropertiesCache();
246 // WARNING. This will construct CSSOM wrappers for all style rules and cache then in a map for significant memory cost.
247 // It is here to support inspector. Don't use for any regular engine functions.
248 CSSStyleRule* ensureFullCSSOMWrapperForInspector(StyleRule*);
250 #if ENABLE(CSS_FILTERS)
251 bool createFilterOperations(CSSValue* inValue, RenderStyle* inStyle, RenderStyle* rootStyle, FilterOperations& outOperations);
252 #if ENABLE(CSS_SHADERS)
253 StyleShader* styleShader(CSSValue*);
254 StyleShader* cachedOrPendingStyleShaderFromValue(WebKitCSSShaderValue*);
255 bool parseCustomFilterParameterList(CSSValue*, CustomFilterParameterList&);
256 PassRefPtr<CustomFilterParameter> parseCustomFilterNumberParamter(const String& name, CSSValueList*);
257 PassRefPtr<CustomFilterOperation> createCustomFilterOperation(WebKitCSSFilterValue*);
258 void loadPendingShaders();
260 #endif // ENABLE(CSS_FILTERS)
263 RuleFeature(StyleRule* rule, CSSSelector* selector, bool hasDocumentSecurityOrigin)
266 , hasDocumentSecurityOrigin(hasDocumentSecurityOrigin)
270 CSSSelector* selector;
271 bool hasDocumentSecurityOrigin;
276 void add(const CSSStyleSelector::Features&);
278 HashSet<AtomicStringImpl*> idsInRules;
279 HashSet<AtomicStringImpl*> attrsInRules;
280 Vector<RuleFeature> siblingRules;
281 Vector<RuleFeature> uncommonAttributeRules;
282 bool usesFirstLineRules;
283 bool usesBeforeAfterRules;
288 // This function fixes up the default font size if it detects that the current generic font family has changed. -dwh
289 void checkForGenericFamilyChange(RenderStyle*, RenderStyle* parentStyle);
290 void checkForZoomChange(RenderStyle*, RenderStyle* parentStyle);
291 void checkForTextSizeAdjust();
293 void adjustRenderStyle(RenderStyle* styleToAdjust, RenderStyle* parentStyle, Element*);
295 void addMatchedRule(const RuleData* rule) { m_matchedRules.append(rule); }
298 MatchRanges() : firstUARule(-1), lastUARule(-1), firstAuthorRule(-1), lastAuthorRule(-1), firstUserRule(-1), lastUserRule(-1) { }
307 struct MatchedProperties {
308 MatchedProperties() : possiblyPaddedMember(0) { }
310 RefPtr<StylePropertySet> properties;
313 unsigned linkMatchType : 2;
314 unsigned isInRegionRule : 1;
316 // Used to make sure all memory is zero-initialized since we compute the hash over the bytes of this object.
317 void* possiblyPaddedMember;
322 MatchResult() : isCacheable(true) { }
323 Vector<MatchedProperties, 64> matchedProperties;
324 Vector<StyleRule*, 64> matchedRules;
329 struct MatchOptions {
330 MatchOptions(bool includeEmptyRules, const ContainerNode* scope = 0) : scope(scope), includeEmptyRules(includeEmptyRules) { }
331 const ContainerNode* scope;
332 bool includeEmptyRules;
335 static void addMatchedProperties(MatchResult&, StylePropertySet* properties, StyleRule* = 0, unsigned linkMatchType = SelectorChecker::MatchAll, bool inRegionRule = false);
336 void addElementStyleProperties(MatchResult&, StylePropertySet*, bool isCacheable = true);
338 void matchAllRules(MatchResult&);
339 void matchUARules(MatchResult&);
340 void matchUARules(MatchResult&, RuleSet*);
341 void matchAuthorRules(MatchResult&, bool includeEmptyRules);
342 void matchUserRules(MatchResult&, bool includeEmptyRules);
343 void matchScopedAuthorRules(MatchResult&, bool includeEmptyRules);
344 void collectMatchingRules(RuleSet*, int& firstRuleIndex, int& lastRuleIndex, const MatchOptions&);
345 void collectMatchingRulesForRegion(RuleSet*, int& firstRuleIndex, int& lastRuleIndex, const MatchOptions&);
346 void collectMatchingRulesForList(const Vector<RuleData>*, int& firstRuleIndex, int& lastRuleIndex, const MatchOptions&);
347 bool fastRejectSelector(const RuleData&) const;
348 void sortMatchedRules();
349 void sortAndTransferMatchedRules(MatchResult&);
351 bool checkSelector(const RuleData&, const ContainerNode* scope = 0);
352 bool checkRegionSelector(CSSSelector* regionSelector, Element* regionElement);
353 void applyMatchedProperties(const MatchResult&);
354 template <bool firstPass>
355 void applyMatchedProperties(const MatchResult&, bool important, int startIndex, int endIndex, bool inheritedOnly);
356 template <bool firstPass>
357 void applyProperties(const StylePropertySet* properties, StyleRule*, bool isImportant, bool inheritedOnly, bool filterRegionProperties);
359 static bool isValidRegionStyleProperty(int id);
361 void matchPageRules(MatchResult&, RuleSet*, bool isLeftPage, bool isFirstPage, const String& pageName);
362 void matchPageRulesForList(Vector<StyleRulePage*>& matchedRules, const Vector<StyleRulePage*>&, bool isLeftPage, bool isFirstPage, const String& pageName);
363 bool isLeftPage(int pageIndex) const;
364 bool isRightPage(int pageIndex) const { return !isLeftPage(pageIndex); }
365 bool isFirstPage(int pageIndex) const;
366 String pageName(int pageIndex) const;
368 OwnPtr<RuleSet> m_authorStyle;
369 OwnPtr<RuleSet> m_userStyle;
372 OwnPtr<RuleSet> m_siblingRuleSet;
373 OwnPtr<RuleSet> m_uncommonAttributeRuleSet;
375 bool m_hasUAAppearance;
376 BorderData m_borderData;
377 FillLayer m_backgroundData;
378 Color m_backgroundColor;
380 typedef HashMap<AtomicStringImpl*, RefPtr<StyleRuleKeyframes> > KeyframesRuleMap;
381 KeyframesRuleMap m_keyframesRuleMap;
384 static RenderStyle* styleNotYetAvailable() { return s_styleNotYetAvailable; }
386 PassRefPtr<StyleImage> styleImage(CSSPropertyID, CSSValue*);
387 PassRefPtr<StyleImage> cachedOrPendingFromValue(CSSPropertyID, CSSImageValue*);
388 PassRefPtr<StyleImage> generatedOrPendingFromValue(CSSPropertyID, CSSImageGeneratorValue*);
389 #if ENABLE(CSS_IMAGE_SET)
390 PassRefPtr<StyleImage> setOrPendingFromValue(CSSPropertyID, CSSImageSetValue*);
393 bool applyPropertyToRegularStyle() const { return m_applyPropertyToRegularStyle; }
394 bool applyPropertyToVisitedLinkStyle() const { return m_applyPropertyToVisitedLinkStyle; }
396 static Length convertToIntLength(CSSPrimitiveValue*, RenderStyle*, RenderStyle* rootStyle, double multiplier = 1);
397 static Length convertToFloatLength(CSSPrimitiveValue*, RenderStyle*, RenderStyle* rootStyle, double multiplier = 1);
400 static RenderStyle* s_styleNotYetAvailable;
402 void cacheBorderAndBackground();
404 void mapFillAttachment(CSSPropertyID, FillLayer*, CSSValue*);
405 void mapFillClip(CSSPropertyID, FillLayer*, CSSValue*);
406 void mapFillComposite(CSSPropertyID, FillLayer*, CSSValue*);
407 void mapFillOrigin(CSSPropertyID, FillLayer*, CSSValue*);
408 void mapFillImage(CSSPropertyID, FillLayer*, CSSValue*);
409 void mapFillRepeatX(CSSPropertyID, FillLayer*, CSSValue*);
410 void mapFillRepeatY(CSSPropertyID, FillLayer*, CSSValue*);
411 void mapFillSize(CSSPropertyID, FillLayer*, CSSValue*);
412 void mapFillXPosition(CSSPropertyID, FillLayer*, CSSValue*);
413 void mapFillYPosition(CSSPropertyID, FillLayer*, CSSValue*);
415 void mapAnimationDelay(Animation*, CSSValue*);
416 void mapAnimationDirection(Animation*, CSSValue*);
417 void mapAnimationDuration(Animation*, CSSValue*);
418 void mapAnimationFillMode(Animation*, CSSValue*);
419 void mapAnimationIterationCount(Animation*, CSSValue*);
420 void mapAnimationName(Animation*, CSSValue*);
421 void mapAnimationPlayState(Animation*, CSSValue*);
422 void mapAnimationProperty(Animation*, CSSValue*);
423 void mapAnimationTimingFunction(Animation*, CSSValue*);
426 void mapNinePieceImage(CSSPropertyID, CSSValue*, NinePieceImage&);
427 void mapNinePieceImageSlice(CSSValue*, NinePieceImage&);
428 LengthBox mapNinePieceImageQuad(CSSValue*);
429 void mapNinePieceImageRepeat(CSSValue*, NinePieceImage&);
431 bool canShareStyleWithControl(StyledElement*) const;
433 void applyProperty(int id, CSSValue*);
436 void applySVGProperty(int id, CSSValue*);
439 PassRefPtr<StyleImage> loadPendingImage(StylePendingImage*);
440 void loadPendingImages();
442 static unsigned computeMatchedPropertiesHash(const MatchedProperties*, unsigned size);
443 struct MatchedPropertiesCacheItem {
444 Vector<MatchedProperties> matchedProperties;
446 RefPtr<RenderStyle> renderStyle;
447 RefPtr<RenderStyle> parentRenderStyle;
449 const MatchedPropertiesCacheItem* findFromMatchedPropertiesCache(unsigned hash, const MatchResult&);
450 void addToMatchedPropertiesCache(const RenderStyle*, const RenderStyle* parentStyle, unsigned hash, const MatchResult&);
452 // Every N additions to the matched declaration cache trigger a sweep where entries holding
453 // the last reference to a style declaration are garbage collected.
454 void sweepMatchedPropertiesCache();
456 unsigned m_matchedPropertiesCacheAdditionsSinceLastSweep;
458 typedef HashMap<unsigned, MatchedPropertiesCacheItem> MatchedPropertiesCache;
459 MatchedPropertiesCache m_matchedPropertiesCache;
461 // A buffer used to hold the set of matched rules for an element, and a temporary buffer used for
463 Vector<const RuleData*, 32> m_matchedRules;
465 RefPtr<StaticCSSRuleList> m_ruleList;
467 HashSet<int> m_pendingImageProperties; // Hash of CSSPropertyIDs
469 OwnPtr<MediaQueryEvaluator> m_medium;
470 RefPtr<RenderStyle> m_rootDefaultStyle;
472 PseudoId m_dynamicPseudo;
474 SelectorChecker m_checker;
476 RefPtr<RenderStyle> m_style;
477 RenderStyle* m_parentStyle;
478 RenderStyle* m_rootElementStyle;
480 StyledElement* m_styledElement;
481 RenderRegion* m_regionForStyling;
482 EInsideLink m_elementLinkState;
483 ContainerNode* m_parentNode;
484 CSSValue* m_lineHeightValue;
486 bool m_matchAuthorAndUserStyles;
487 bool m_sameOriginOnly;
489 RefPtr<CSSFontSelector> m_fontSelector;
490 Vector<OwnPtr<MediaQueryResult> > m_viewportDependentMediaQueryResults;
492 bool m_applyPropertyToRegularStyle;
493 bool m_applyPropertyToVisitedLinkStyle;
494 const CSSStyleApplyProperty& m_applyProperty;
496 HashMap<StyleRule*, RefPtr<CSSStyleRule> > m_styleRuleToCSSOMWrapperMap;
498 #if ENABLE(CSS_SHADERS)
499 bool m_hasPendingShaders;
502 #if ENABLE(STYLE_SCOPED)
503 static const ContainerNode* determineScope(const CSSStyleSheet*);
505 typedef HashMap<const ContainerNode*, OwnPtr<RuleSet> > ScopedRuleSetMap;
507 RuleSet* ruleSetForScope(const ContainerNode*) const;
509 void setupScopeStack(const ContainerNode*);
510 bool scopeStackIsConsistent(const ContainerNode* parent) const { return parent && parent == m_scopeStackParent; }
512 ScopedRuleSetMap m_scopedAuthorStyles;
514 struct ScopeStackFrame {
515 ScopeStackFrame() : m_scope(0), m_ruleSet(0) { }
516 ScopeStackFrame(const ContainerNode* scope, RuleSet* ruleSet) : m_scope(scope), m_ruleSet(ruleSet) { }
517 const ContainerNode* m_scope;
520 // Vector (used as stack) that keeps track of scoping elements (i.e., elements with a <style scoped> child)
521 // encountered during tree iteration for style resolution.
522 Vector<ScopeStackFrame> m_scopeStack;
523 // Element last seen as parent element when updating m_scopingElementStack.
524 // This is used to decide whether m_scopingElementStack is consistent, separately from SelectorChecker::m_parentStack.
525 const ContainerNode* m_scopeStackParent;
528 friend class CSSStyleApplyProperty;
529 friend bool operator==(const MatchedProperties&, const MatchedProperties&);
530 friend bool operator!=(const MatchedProperties&, const MatchedProperties&);
531 friend bool operator==(const MatchRanges&, const MatchRanges&);
532 friend bool operator!=(const MatchRanges&, const MatchRanges&);
535 } // namespace WebCore
537 #endif // CSSStyleSelector_h