Upstream version 5.34.92.0
[platform/framework/web/crosswalk.git] / src / third_party / WebKit / Source / core / css / RuleSet.cpp
1 /*
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.
12  *
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.
17  *
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.
22  *
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.
27  */
28
29 #include "config.h"
30 #include "core/css/RuleSet.h"
31
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"
44
45 namespace WebCore {
46
47 using namespace HTMLNames;
48
49 // -----------------------------------------------------------------
50
51 static inline bool isSelectorMatchingHTMLBasedOnRuleHash(const CSSSelector* selector)
52 {
53     ASSERT(selector);
54     if (selector->m_match == CSSSelector::Tag) {
55         const AtomicString& selectorNamespace = selector->tagQName().namespaceURI();
56         if (selectorNamespace != starAtom && selectorNamespace != xhtmlNamespaceURI)
57             return false;
58         if (selector->relation() == CSSSelector::SubSelector)
59             return isSelectorMatchingHTMLBasedOnRuleHash(selector->tagHistory());
60         return true;
61     }
62     if (SelectorChecker::isCommonPseudoClassSelector(selector))
63         return true;
64     return selector->m_match == CSSSelector::Id || selector->m_match == CSSSelector::Class;
65 }
66
67 static inline bool selectorListContainsUncommonAttributeSelector(const CSSSelector* selector)
68 {
69     const CSSSelectorList* selectorList = selector->selectorList();
70     if (!selectorList)
71         return false;
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())
75                 return true;
76         }
77     }
78     return false;
79 }
80
81 static inline bool isCommonAttributeSelectorAttribute(const QualifiedName& attribute)
82 {
83     // These are explicitly tested for equality in canShareStyleWithElement.
84     return attribute == typeAttr || attribute == readonlyAttr;
85 }
86
87 static inline bool containsUncommonAttributeSelector(const CSSSelector* selector)
88 {
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()))
92             return true;
93         if (selectorListContainsUncommonAttributeSelector(selector))
94             return true;
95         if (selector->relation() != CSSSelector::SubSelector) {
96             selector = selector->tagHistory();
97             break;
98         }
99     }
100
101     for (; selector; selector = selector->tagHistory()) {
102         if (selector->isAttributeSelector())
103             return true;
104         if (selectorListContainsUncommonAttributeSelector(selector))
105             return true;
106     }
107     return false;
108 }
109
110 static inline PropertyWhitelistType determinePropertyWhitelistType(const AddRuleFlags addRuleFlags, const CSSSelector* selector)
111 {
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;
117     }
118     return PropertyWhitelistNone;
119 }
120
121 namespace {
122
123 // FIXME: Should we move this class to WTF?
124 template<typename T>
125 class TerminatedArrayBuilder {
126 public:
127     explicit TerminatedArrayBuilder(PassOwnPtr<T> array)
128         : m_array(array)
129         , m_count(0)
130         , m_capacity(0)
131     {
132         if (!m_array)
133             return;
134         for (T* item = m_array.get(); !item->isLastInArray(); ++item)
135             ++m_count;
136         ++m_count; // To count the last item itself.
137         m_capacity = m_count;
138     }
139
140     void grow(size_t count)
141     {
142         ASSERT(count);
143         if (!m_array) {
144             ASSERT(!m_count);
145             ASSERT(!m_capacity);
146             m_capacity = count;
147             m_array = adoptPtr(static_cast<T*>(fastMalloc(m_capacity * sizeof(T))));
148             return;
149         }
150         m_capacity += count;
151         m_array = adoptPtr(static_cast<T*>(fastRealloc(m_array.leakPtr(), m_capacity * sizeof(T))));
152         m_array.get()[m_count - 1].setLastInArray(false);
153     }
154
155     void append(const T& item)
156     {
157         RELEASE_ASSERT(m_count < m_capacity);
158         ASSERT(!item.isLastInArray());
159         m_array.get()[m_count++] = item;
160     }
161
162     PassOwnPtr<T> release()
163     {
164         RELEASE_ASSERT(m_count == m_capacity);
165         if (m_array)
166             m_array.get()[m_count - 1].setLastInArray(true);
167         assertValid();
168         return m_array.release();
169     }
170
171 private:
172 #ifndef NDEBUG
173     void assertValid()
174     {
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);
178         }
179     }
180 #else
181     void assertValid() { }
182 #endif
183
184     OwnPtr<T> m_array;
185     size_t m_count;
186     size_t m_capacity;
187 };
188
189 }
190
191 RuleData::RuleData(StyleRule* rule, unsigned selectorIndex, unsigned position, AddRuleFlags addRuleFlags)
192     : m_rule(rule)
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()))
204 {
205     ASSERT(m_position == position);
206     ASSERT(m_selectorIndex == selectorIndex);
207     SelectorFilter::collectIdentifierHashes(selector(), m_descendantSelectorIdentifierHashes, maximumIdentifierCount);
208 }
209
210 void RuleSet::addToRuleSet(StringImpl* key, PendingRuleMap& map, const RuleData& ruleData)
211 {
212     if (!key)
213         return;
214     OwnPtr<LinkedStack<RuleData> >& rules = map.add(key, nullptr).iterator->value;
215     if (!rules)
216         rules = adoptPtr(new LinkedStack<RuleData>);
217     rules->push(ruleData);
218 }
219
220 bool RuleSet::findBestRuleSetAndAdd(const CSSSelector* component, RuleData& ruleData)
221 {
222     if (component->m_match == CSSSelector::Id) {
223         addToRuleSet(component->value().impl(), ensurePendingRules()->idRules, ruleData);
224         return true;
225     }
226     if (component->m_match == CSSSelector::Class) {
227         addToRuleSet(component->value().impl(), ensurePendingRules()->classRules, ruleData);
228         return true;
229     }
230     if (component->isCustomPseudoElement()) {
231         addToRuleSet(component->value().impl(), ensurePendingRules()->shadowPseudoElementRules, ruleData);
232         return true;
233     }
234     if (component->pseudoType() == CSSSelector::PseudoCue) {
235         m_cuePseudoRules.append(ruleData);
236         return true;
237     }
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);
244             return true;
245         case CSSSelector::PseudoFocus:
246             m_focusPseudoClassRules.append(ruleData);
247             return true;
248         default:
249             ASSERT_NOT_REACHED();
250             return true;
251         }
252     }
253
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))
260                 return true;
261
262             addToRuleSet(component->tagQName().localName().impl(), ensurePendingRules()->tagRules, ruleData);
263             return true;
264         }
265     }
266     return false;
267 }
268
269 void RuleSet::addRule(StyleRule* rule, unsigned selectorIndex, AddRuleFlags addRuleFlags)
270 {
271     RuleData ruleData(rule, selectorIndex, m_ruleCount++, addRuleFlags);
272     m_features.collectFeaturesFromRuleData(ruleData);
273
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);
277     }
278 }
279
280 void RuleSet::addPageRule(StyleRulePage* rule)
281 {
282     ensurePendingRules(); // So that m_pageRules.shrinkToFit() gets called.
283     m_pageRules.append(rule);
284 }
285
286 void RuleSet::addViewportRule(StyleRuleViewport* rule)
287 {
288     ensurePendingRules(); // So that m_viewportRules.shrinkToFit() gets called.
289     m_viewportRules.append(rule);
290 }
291
292 void RuleSet::addFontFaceRule(StyleRuleFontFace* rule)
293 {
294     ensurePendingRules(); // So that m_fontFaceRules.shrinkToFit() gets called.
295     m_fontFaceRules.append(rule);
296 }
297
298 void RuleSet::addKeyframesRule(StyleRuleKeyframes* rule)
299 {
300     ensurePendingRules(); // So that m_keyframesRules.shrinkToFit() gets called.
301     m_keyframesRules.append(rule);
302 }
303
304 void RuleSet::addRegionRule(StyleRuleRegion* regionRule, bool hasDocumentSecurityOrigin)
305 {
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;
312
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);
322     }
323     // Update the "global" rule count so that proper order is maintained
324     m_ruleCount = regionRuleSet->m_ruleCount;
325
326     m_regionSelectorsAndRuleSets.append(RuleSetSelectorPair(regionRule->selectorList().first(), regionRuleSet.release()));
327 }
328
329 void RuleSet::addChildRules(const Vector<RefPtr<StyleRuleBase> >& rules, const MediaQueryEvaluator& medium, AddRuleFlags addRuleFlags)
330 {
331     for (unsigned i = 0; i < rules.size(); ++i) {
332         StyleRuleBase* rule = rules[i].get();
333
334         if (rule->isStyleRule()) {
335             StyleRule* styleRule = toStyleRule(rule);
336
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));
343                 } else {
344                     addRule(styleRule, selectorIndex, addRuleFlags);
345                 }
346             }
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);
363         }
364     }
365 }
366
367 void RuleSet::addRulesFromSheet(StyleSheetContents* sheet, const MediaQueryEvaluator& medium, AddRuleFlags addRuleFlags)
368 {
369     ASSERT(sheet);
370
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);
377     }
378
379     addChildRules(sheet->childRules(), medium, addRuleFlags);
380 }
381
382 void RuleSet::addStyleRule(StyleRule* rule, AddRuleFlags addRuleFlags)
383 {
384     for (size_t selectorIndex = 0; selectorIndex != kNotFound; selectorIndex = rule->selectorList().indexOfNextSelectorAfter(selectorIndex))
385         addRule(rule, selectorIndex, addRuleFlags);
386 }
387
388 void RuleSet::compactPendingRules(PendingRuleMap& pendingMap, CompactRuleMap& compactMap)
389 {
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;
394
395         TerminatedArrayBuilder<RuleData> builder(compactRules->value.release());
396         builder.grow(pendingRules->size());
397         while (!pendingRules->isEmpty()) {
398             builder.append(pendingRules->peek());
399             pendingRules->pop();
400         }
401
402         compactRules->value = builder.release();
403     }
404 }
405
406 void RuleSet::compactRules()
407 {
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();
424 }
425
426 } // namespace WebCore