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 "core/css/RuleSet.h"
32 #include "HTMLNames.h"
33 #include "RuntimeEnabledFeatures.h"
34 #include "core/css/CSSFontSelector.h"
35 #include "core/css/CSSSelector.h"
36 #include "core/css/CSSSelectorList.h"
37 #include "core/css/SelectorChecker.h"
38 #include "core/css/SelectorCheckerFastPath.h"
39 #include "core/css/SelectorFilter.h"
40 #include "core/css/StyleRuleImport.h"
41 #include "core/css/StyleSheetContents.h"
42 #include "core/html/track/TextTrackCue.h"
43 #include "platform/weborigin/SecurityOrigin.h"
47 using namespace HTMLNames;
49 // -----------------------------------------------------------------
51 static inline bool isSelectorMatchingHTMLBasedOnRuleHash(const CSSSelector* selector)
54 if (selector->m_match == CSSSelector::Tag) {
55 const AtomicString& selectorNamespace = selector->tagQName().namespaceURI();
56 if (selectorNamespace != starAtom && selectorNamespace != xhtmlNamespaceURI)
58 if (selector->relation() == CSSSelector::SubSelector)
59 return isSelectorMatchingHTMLBasedOnRuleHash(selector->tagHistory());
62 if (SelectorChecker::isCommonPseudoClassSelector(selector))
64 return selector->m_match == CSSSelector::Id || selector->m_match == CSSSelector::Class;
67 static inline bool selectorListContainsUncommonAttributeSelector(const CSSSelector* selector)
69 const CSSSelectorList* selectorList = selector->selectorList();
72 for (const CSSSelector* selector = selectorList->first(); selector; selector = CSSSelectorList::next(selector)) {
73 for (const CSSSelector* component = selector; component; component = component->tagHistory()) {
74 if (component->isAttributeSelector())
81 static inline bool isCommonAttributeSelectorAttribute(const QualifiedName& attribute)
83 // These are explicitly tested for equality in canShareStyleWithElement.
84 return attribute == typeAttr || attribute == readonlyAttr;
87 static inline bool containsUncommonAttributeSelector(const CSSSelector* selector)
89 for (; selector; selector = selector->tagHistory()) {
90 // Allow certain common attributes (used in the default style) in the selectors that match the current element.
91 if (selector->isAttributeSelector() && !isCommonAttributeSelectorAttribute(selector->attribute()))
93 if (selectorListContainsUncommonAttributeSelector(selector))
95 if (selector->relation() != CSSSelector::SubSelector) {
96 selector = selector->tagHistory();
101 for (; selector; selector = selector->tagHistory()) {
102 if (selector->isAttributeSelector())
104 if (selectorListContainsUncommonAttributeSelector(selector))
110 static inline PropertyWhitelistType determinePropertyWhitelistType(const AddRuleFlags addRuleFlags, const CSSSelector* selector)
112 if (addRuleFlags & RuleIsInRegionRule)
113 return PropertyWhitelistRegion;
114 for (const CSSSelector* component = selector; component; component = component->tagHistory()) {
115 if (component->pseudoType() == CSSSelector::PseudoCue || (component->m_match == CSSSelector::PseudoElement && component->value() == TextTrackCue::cueShadowPseudoId()))
116 return PropertyWhitelistCue;
118 return PropertyWhitelistNone;
123 // FIXME: Should we move this class to WTF?
125 class TerminatedArrayBuilder {
127 explicit TerminatedArrayBuilder(PassOwnPtr<T> array)
134 for (T* item = m_array.get(); !item->isLastInArray(); ++item)
136 ++m_count; // To count the last item itself.
137 m_capacity = m_count;
140 void grow(size_t count)
147 m_array = adoptPtr(static_cast<T*>(fastMalloc(m_capacity * sizeof(T))));
151 m_array = adoptPtr(static_cast<T*>(fastRealloc(m_array.leakPtr(), m_capacity * sizeof(T))));
152 m_array.get()[m_count - 1].setLastInArray(false);
155 void append(const T& item)
157 RELEASE_ASSERT(m_count < m_capacity);
158 ASSERT(!item.isLastInArray());
159 m_array.get()[m_count++] = item;
162 PassOwnPtr<T> release()
164 RELEASE_ASSERT(m_count == m_capacity);
166 m_array.get()[m_count - 1].setLastInArray(true);
168 return m_array.release();
175 for (size_t i = 0; i < m_count; ++i) {
176 bool isLastInArray = (i + 1 == m_count);
177 ASSERT(m_array.get()[i].isLastInArray() == isLastInArray);
181 void assertValid() { }
191 RuleData::RuleData(StyleRule* rule, unsigned selectorIndex, unsigned position, AddRuleFlags addRuleFlags)
193 , m_selectorIndex(selectorIndex)
194 , m_isLastInArray(false)
195 , m_position(position)
196 , m_hasFastCheckableSelector((addRuleFlags & RuleCanUseFastCheckSelector) && SelectorCheckerFastPath::canUse(selector()))
197 , m_specificity(selector()->specificity())
198 , m_hasMultipartSelector(!!selector()->tagHistory())
199 , m_hasRightmostSelectorMatchingHTMLBasedOnRuleHash(isSelectorMatchingHTMLBasedOnRuleHash(selector()))
200 , m_containsUncommonAttributeSelector(WebCore::containsUncommonAttributeSelector(selector()))
201 , m_linkMatchType(SelectorChecker::determineLinkMatchType(selector()))
202 , m_hasDocumentSecurityOrigin(addRuleFlags & RuleHasDocumentSecurityOrigin)
203 , m_propertyWhitelistType(determinePropertyWhitelistType(addRuleFlags, selector()))
205 ASSERT(m_position == position);
206 ASSERT(m_selectorIndex == selectorIndex);
207 SelectorFilter::collectIdentifierHashes(selector(), m_descendantSelectorIdentifierHashes, maximumIdentifierCount);
210 void RuleSet::addToRuleSet(StringImpl* key, PendingRuleMap& map, const RuleData& ruleData)
214 OwnPtr<LinkedStack<RuleData> >& rules = map.add(key, nullptr).iterator->value;
216 rules = adoptPtr(new LinkedStack<RuleData>);
217 rules->push(ruleData);
220 bool RuleSet::findBestRuleSetAndAdd(const CSSSelector* component, RuleData& ruleData)
222 if (component->m_match == CSSSelector::Id) {
223 addToRuleSet(component->value().impl(), ensurePendingRules()->idRules, ruleData);
226 if (component->m_match == CSSSelector::Class) {
227 addToRuleSet(component->value().impl(), ensurePendingRules()->classRules, ruleData);
230 if (component->isCustomPseudoElement()) {
231 addToRuleSet(component->value().impl(), ensurePendingRules()->shadowPseudoElementRules, ruleData);
234 if (component->pseudoType() == CSSSelector::PseudoCue) {
235 m_cuePseudoRules.append(ruleData);
238 if (SelectorChecker::isCommonPseudoClassSelector(component)) {
239 switch (component->pseudoType()) {
240 case CSSSelector::PseudoLink:
241 case CSSSelector::PseudoVisited:
242 case CSSSelector::PseudoAnyLink:
243 m_linkPseudoClassRules.append(ruleData);
245 case CSSSelector::PseudoFocus:
246 m_focusPseudoClassRules.append(ruleData);
249 ASSERT_NOT_REACHED();
254 if (component->m_match == CSSSelector::Tag) {
255 if (component->tagQName().localName() != starAtom) {
256 // If this is part of a subselector chain, recurse ahead to find a narrower set (ID/class.)
257 if (component->relation() == CSSSelector::SubSelector
258 && (component->tagHistory()->m_match == CSSSelector::Class || component->tagHistory()->m_match == CSSSelector::Id || SelectorChecker::isCommonPseudoClassSelector(component->tagHistory()))
259 && findBestRuleSetAndAdd(component->tagHistory(), ruleData))
262 addToRuleSet(component->tagQName().localName().impl(), ensurePendingRules()->tagRules, ruleData);
269 void RuleSet::addRule(StyleRule* rule, unsigned selectorIndex, AddRuleFlags addRuleFlags)
271 RuleData ruleData(rule, selectorIndex, m_ruleCount++, addRuleFlags);
272 m_features.collectFeaturesFromRuleData(ruleData);
274 if (!findBestRuleSetAndAdd(ruleData.selector(), ruleData)) {
275 // If we didn't find a specialized map to stick it in, file under universal rules.
276 m_universalRules.append(ruleData);
280 void RuleSet::addPageRule(StyleRulePage* rule)
282 ensurePendingRules(); // So that m_pageRules.shrinkToFit() gets called.
283 m_pageRules.append(rule);
286 void RuleSet::addViewportRule(StyleRuleViewport* rule)
288 ensurePendingRules(); // So that m_viewportRules.shrinkToFit() gets called.
289 m_viewportRules.append(rule);
292 void RuleSet::addFontFaceRule(StyleRuleFontFace* rule)
294 ensurePendingRules(); // So that m_fontFaceRules.shrinkToFit() gets called.
295 m_fontFaceRules.append(rule);
298 void RuleSet::addKeyframesRule(StyleRuleKeyframes* rule)
300 ensurePendingRules(); // So that m_keyframesRules.shrinkToFit() gets called.
301 m_keyframesRules.append(rule);
304 void RuleSet::addRegionRule(StyleRuleRegion* regionRule, bool hasDocumentSecurityOrigin)
306 ensurePendingRules(); // So that m_regionSelectorsAndRuleSets.shrinkToFit() gets called.
307 OwnPtr<RuleSet> regionRuleSet = RuleSet::create();
308 // The region rule set should take into account the position inside the parent rule set.
309 // Otherwise, the rules inside region block might be incorrectly positioned before other similar rules from
310 // the stylesheet that contains the region block.
311 regionRuleSet->m_ruleCount = m_ruleCount;
313 // Collect the region rules into a rule set
314 // FIXME: Should this add other types of rules? (i.e. use addChildRules() directly?)
315 const Vector<RefPtr<StyleRuleBase> >& childRules = regionRule->childRules();
316 AddRuleFlags addRuleFlags = hasDocumentSecurityOrigin ? RuleHasDocumentSecurityOrigin : RuleHasNoSpecialState;
317 addRuleFlags = static_cast<AddRuleFlags>(addRuleFlags | RuleIsInRegionRule | RuleCanUseFastCheckSelector);
318 for (unsigned i = 0; i < childRules.size(); ++i) {
319 StyleRuleBase* regionStylingRule = childRules[i].get();
320 if (regionStylingRule->isStyleRule())
321 regionRuleSet->addStyleRule(toStyleRule(regionStylingRule), addRuleFlags);
323 // Update the "global" rule count so that proper order is maintained
324 m_ruleCount = regionRuleSet->m_ruleCount;
326 m_regionSelectorsAndRuleSets.append(RuleSetSelectorPair(regionRule->selectorList().first(), regionRuleSet.release()));
329 void RuleSet::addChildRules(const Vector<RefPtr<StyleRuleBase> >& rules, const MediaQueryEvaluator& medium, AddRuleFlags addRuleFlags)
331 for (unsigned i = 0; i < rules.size(); ++i) {
332 StyleRuleBase* rule = rules[i].get();
334 if (rule->isStyleRule()) {
335 StyleRule* styleRule = toStyleRule(rule);
337 const CSSSelectorList& selectorList = styleRule->selectorList();
338 for (size_t selectorIndex = 0; selectorIndex != kNotFound; selectorIndex = selectorList.indexOfNextSelectorAfter(selectorIndex)) {
339 if (selectorList.hasCombinatorCrossingTreeBoundaryAt(selectorIndex)) {
340 m_treeBoundaryCrossingRules.append(MinimalRuleData(styleRule, selectorIndex, addRuleFlags));
341 } else if (selectorList.hasShadowDistributedAt(selectorIndex)) {
342 m_shadowDistributedRules.append(MinimalRuleData(styleRule, selectorIndex, addRuleFlags));
344 addRule(styleRule, selectorIndex, addRuleFlags);
347 } else if (rule->isPageRule()) {
348 addPageRule(toStyleRulePage(rule));
349 } else if (rule->isMediaRule()) {
350 StyleRuleMedia* mediaRule = toStyleRuleMedia(rule);
351 if ((!mediaRule->mediaQueries() || medium.eval(mediaRule->mediaQueries(), &m_viewportDependentMediaQueryResults)))
352 addChildRules(mediaRule->childRules(), medium, addRuleFlags);
353 } else if (rule->isFontFaceRule()) {
354 addFontFaceRule(toStyleRuleFontFace(rule));
355 } else if (rule->isKeyframesRule()) {
356 addKeyframesRule(toStyleRuleKeyframes(rule));
357 } else if (rule->isRegionRule()) {
358 addRegionRule(toStyleRuleRegion(rule), addRuleFlags & RuleHasDocumentSecurityOrigin);
359 } else if (rule->isViewportRule()) {
360 addViewportRule(toStyleRuleViewport(rule));
361 } else if (rule->isSupportsRule() && toStyleRuleSupports(rule)->conditionIsSupported()) {
362 addChildRules(toStyleRuleSupports(rule)->childRules(), medium, addRuleFlags);
367 void RuleSet::addRulesFromSheet(StyleSheetContents* sheet, const MediaQueryEvaluator& medium, AddRuleFlags addRuleFlags)
371 addRuleFlags = static_cast<AddRuleFlags>(addRuleFlags | RuleCanUseFastCheckSelector);
372 const Vector<RefPtr<StyleRuleImport> >& importRules = sheet->importRules();
373 for (unsigned i = 0; i < importRules.size(); ++i) {
374 StyleRuleImport* importRule = importRules[i].get();
375 if (importRule->styleSheet() && (!importRule->mediaQueries() || medium.eval(importRule->mediaQueries(), &m_viewportDependentMediaQueryResults)))
376 addRulesFromSheet(importRule->styleSheet(), medium, addRuleFlags);
379 addChildRules(sheet->childRules(), medium, addRuleFlags);
382 void RuleSet::addStyleRule(StyleRule* rule, AddRuleFlags addRuleFlags)
384 for (size_t selectorIndex = 0; selectorIndex != kNotFound; selectorIndex = rule->selectorList().indexOfNextSelectorAfter(selectorIndex))
385 addRule(rule, selectorIndex, addRuleFlags);
388 void RuleSet::compactPendingRules(PendingRuleMap& pendingMap, CompactRuleMap& compactMap)
390 PendingRuleMap::iterator end = pendingMap.end();
391 for (PendingRuleMap::iterator it = pendingMap.begin(); it != end; ++it) {
392 OwnPtr<LinkedStack<RuleData> > pendingRules = it->value.release();
393 CompactRuleMap::iterator compactRules = compactMap.add(it->key, nullptr).iterator;
395 TerminatedArrayBuilder<RuleData> builder(compactRules->value.release());
396 builder.grow(pendingRules->size());
397 while (!pendingRules->isEmpty()) {
398 builder.append(pendingRules->peek());
402 compactRules->value = builder.release();
406 void RuleSet::compactRules()
408 ASSERT(m_pendingRules);
409 OwnPtr<PendingRuleMaps> pendingRules = m_pendingRules.release();
410 compactPendingRules(pendingRules->idRules, m_idRules);
411 compactPendingRules(pendingRules->classRules, m_classRules);
412 compactPendingRules(pendingRules->tagRules, m_tagRules);
413 compactPendingRules(pendingRules->shadowPseudoElementRules, m_shadowPseudoElementRules);
414 m_linkPseudoClassRules.shrinkToFit();
415 m_cuePseudoRules.shrinkToFit();
416 m_focusPseudoClassRules.shrinkToFit();
417 m_universalRules.shrinkToFit();
418 m_pageRules.shrinkToFit();
419 m_viewportRules.shrinkToFit();
420 m_fontFaceRules.shrinkToFit();
421 m_keyframesRules.shrinkToFit();
422 m_treeBoundaryCrossingRules.shrinkToFit();
423 m_shadowDistributedRules.shrinkToFit();
426 } // namespace WebCore