Home | History | Annotate | Download | only in css
      1 /*
      2  * Copyright (C) 1999 Lars Knoll (knoll (at) kde.org)
      3  *           (C) 2004-2005 Allan Sandfeld Jensen (kde (at) carewolf.com)
      4  * Copyright (C) 2006, 2007 Nicholas Shanks (webkit (at) 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 (at) webkit.org>
      7  * Copyright (C) 2007, 2008 Eric Seidel <eric (at) 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 static void collectFeaturesFromRuleData(RuleFeatureSet& features, const RuleData& ruleData)
    211 {
    212     bool foundSiblingSelector = false;
    213     unsigned maxDirectAdjacentSelectors = 0;
    214     for (const CSSSelector* selector = ruleData.selector(); selector; selector = selector->tagHistory()) {
    215         features.collectFeaturesFromSelector(selector);
    216 
    217         if (const CSSSelectorList* selectorList = selector->selectorList()) {
    218             for (const CSSSelector* subSelector = selectorList->first(); subSelector; subSelector = CSSSelectorList::next(subSelector)) {
    219                 // FIXME: Shouldn't this be checking subSelector->isSiblingSelector()?
    220                 if (!foundSiblingSelector && selector->isSiblingSelector())
    221                     foundSiblingSelector = true;
    222                 if (subSelector->isDirectAdjacentSelector())
    223                     maxDirectAdjacentSelectors++;
    224                 features.collectFeaturesFromSelector(subSelector);
    225             }
    226         } else {
    227             if (!foundSiblingSelector && selector->isSiblingSelector())
    228                 foundSiblingSelector = true;
    229             if (selector->isDirectAdjacentSelector())
    230                 maxDirectAdjacentSelectors++;
    231         }
    232     }
    233     features.setMaxDirectAdjacentSelectors(maxDirectAdjacentSelectors);
    234     if (foundSiblingSelector)
    235         features.siblingRules.append(RuleFeature(ruleData.rule(), ruleData.selectorIndex(), ruleData.hasDocumentSecurityOrigin()));
    236     if (ruleData.containsUncommonAttributeSelector())
    237         features.uncommonAttributeRules.append(RuleFeature(ruleData.rule(), ruleData.selectorIndex(), ruleData.hasDocumentSecurityOrigin()));
    238 }
    239 
    240 void RuleSet::addToRuleSet(StringImpl* key, PendingRuleMap& map, const RuleData& ruleData)
    241 {
    242     if (!key)
    243         return;
    244     OwnPtr<LinkedStack<RuleData> >& rules = map.add(key, nullptr).iterator->value;
    245     if (!rules)
    246         rules = adoptPtr(new LinkedStack<RuleData>);
    247     rules->push(ruleData);
    248 }
    249 
    250 bool RuleSet::findBestRuleSetAndAdd(const CSSSelector* component, RuleData& ruleData)
    251 {
    252     if (component->m_match == CSSSelector::Id) {
    253         addToRuleSet(component->value().impl(), ensurePendingRules()->idRules, ruleData);
    254         return true;
    255     }
    256     if (component->m_match == CSSSelector::Class) {
    257         addToRuleSet(component->value().impl(), ensurePendingRules()->classRules, ruleData);
    258         return true;
    259     }
    260     if (component->isCustomPseudoElement()) {
    261         addToRuleSet(component->value().impl(), ensurePendingRules()->shadowPseudoElementRules, ruleData);
    262         return true;
    263     }
    264     if (component->pseudoType() == CSSSelector::PseudoCue) {
    265         m_cuePseudoRules.append(ruleData);
    266         return true;
    267     }
    268     if (SelectorChecker::isCommonPseudoClassSelector(component)) {
    269         switch (component->pseudoType()) {
    270         case CSSSelector::PseudoLink:
    271         case CSSSelector::PseudoVisited:
    272         case CSSSelector::PseudoAnyLink:
    273             m_linkPseudoClassRules.append(ruleData);
    274             return true;
    275         case CSSSelector::PseudoFocus:
    276             m_focusPseudoClassRules.append(ruleData);
    277             return true;
    278         default:
    279             ASSERT_NOT_REACHED();
    280             return true;
    281         }
    282     }
    283 
    284     if (component->m_match == CSSSelector::Tag) {
    285         if (component->tagQName().localName() != starAtom) {
    286             // If this is part of a subselector chain, recurse ahead to find a narrower set (ID/class.)
    287             if (component->relation() == CSSSelector::SubSelector
    288                 && (component->tagHistory()->m_match == CSSSelector::Class || component->tagHistory()->m_match == CSSSelector::Id || SelectorChecker::isCommonPseudoClassSelector(component->tagHistory()))
    289                 && findBestRuleSetAndAdd(component->tagHistory(), ruleData))
    290                 return true;
    291 
    292             addToRuleSet(component->tagQName().localName().impl(), ensurePendingRules()->tagRules, ruleData);
    293             return true;
    294         }
    295     }
    296     return false;
    297 }
    298 
    299 void RuleSet::addRule(StyleRule* rule, unsigned selectorIndex, AddRuleFlags addRuleFlags)
    300 {
    301     RuleData ruleData(rule, selectorIndex, m_ruleCount++, addRuleFlags);
    302     collectFeaturesFromRuleData(m_features, ruleData);
    303 
    304     if (!findBestRuleSetAndAdd(ruleData.selector(), ruleData)) {
    305         // If we didn't find a specialized map to stick it in, file under universal rules.
    306         m_universalRules.append(ruleData);
    307     }
    308 }
    309 
    310 void RuleSet::addPageRule(StyleRulePage* rule)
    311 {
    312     ensurePendingRules(); // So that m_pageRules.shrinkToFit() gets called.
    313     m_pageRules.append(rule);
    314 }
    315 
    316 void RuleSet::addViewportRule(StyleRuleViewport* rule)
    317 {
    318     ensurePendingRules(); // So that m_viewportRules.shrinkToFit() gets called.
    319     m_viewportRules.append(rule);
    320 }
    321 
    322 void RuleSet::addFontFaceRule(StyleRuleFontFace* rule)
    323 {
    324     ensurePendingRules(); // So that m_fontFaceRules.shrinkToFit() gets called.
    325     m_fontFaceRules.append(rule);
    326 }
    327 
    328 void RuleSet::addKeyframesRule(StyleRuleKeyframes* rule)
    329 {
    330     ensurePendingRules(); // So that m_keyframesRules.shrinkToFit() gets called.
    331     m_keyframesRules.append(rule);
    332 }
    333 
    334 void RuleSet::addRegionRule(StyleRuleRegion* regionRule, bool hasDocumentSecurityOrigin)
    335 {
    336     ensurePendingRules(); // So that m_regionSelectorsAndRuleSets.shrinkToFit() gets called.
    337     OwnPtr<RuleSet> regionRuleSet = RuleSet::create();
    338     // The region rule set should take into account the position inside the parent rule set.
    339     // Otherwise, the rules inside region block might be incorrectly positioned before other similar rules from
    340     // the stylesheet that contains the region block.
    341     regionRuleSet->m_ruleCount = m_ruleCount;
    342 
    343     // Collect the region rules into a rule set
    344     // FIXME: Should this add other types of rules? (i.e. use addChildRules() directly?)
    345     const Vector<RefPtr<StyleRuleBase> >& childRules = regionRule->childRules();
    346     AddRuleFlags addRuleFlags = hasDocumentSecurityOrigin ? RuleHasDocumentSecurityOrigin : RuleHasNoSpecialState;
    347     addRuleFlags = static_cast<AddRuleFlags>(addRuleFlags | RuleIsInRegionRule | RuleCanUseFastCheckSelector);
    348     for (unsigned i = 0; i < childRules.size(); ++i) {
    349         StyleRuleBase* regionStylingRule = childRules[i].get();
    350         if (regionStylingRule->isStyleRule())
    351             regionRuleSet->addStyleRule(toStyleRule(regionStylingRule), addRuleFlags);
    352     }
    353     // Update the "global" rule count so that proper order is maintained
    354     m_ruleCount = regionRuleSet->m_ruleCount;
    355 
    356     m_regionSelectorsAndRuleSets.append(RuleSetSelectorPair(regionRule->selectorList().first(), regionRuleSet.release()));
    357 }
    358 
    359 void RuleSet::addChildRules(const Vector<RefPtr<StyleRuleBase> >& rules, const MediaQueryEvaluator& medium, AddRuleFlags addRuleFlags)
    360 {
    361     for (unsigned i = 0; i < rules.size(); ++i) {
    362         StyleRuleBase* rule = rules[i].get();
    363 
    364         if (rule->isStyleRule()) {
    365             StyleRule* styleRule = toStyleRule(rule);
    366 
    367             const CSSSelectorList& selectorList = styleRule->selectorList();
    368             for (size_t selectorIndex = 0; selectorIndex != kNotFound; selectorIndex = selectorList.indexOfNextSelectorAfter(selectorIndex)) {
    369                 if (selectorList.hasCombinatorCrossingTreeBoundaryAt(selectorIndex)) {
    370                     m_treeBoundaryCrossingRules.append(MinimalRuleData(styleRule, selectorIndex, addRuleFlags));
    371                 } else if (selectorList.hasShadowDistributedAt(selectorIndex)) {
    372                     m_shadowDistributedRules.append(MinimalRuleData(styleRule, selectorIndex, addRuleFlags));
    373                 } else {
    374                     addRule(styleRule, selectorIndex, addRuleFlags);
    375                 }
    376             }
    377         } else if (rule->isPageRule()) {
    378             addPageRule(toStyleRulePage(rule));
    379         } else if (rule->isMediaRule()) {
    380             StyleRuleMedia* mediaRule = toStyleRuleMedia(rule);
    381             if ((!mediaRule->mediaQueries() || medium.eval(mediaRule->mediaQueries(), &m_viewportDependentMediaQueryResults)))
    382                 addChildRules(mediaRule->childRules(), medium, addRuleFlags);
    383         } else if (rule->isFontFaceRule()) {
    384             addFontFaceRule(toStyleRuleFontFace(rule));
    385         } else if (rule->isKeyframesRule()) {
    386             addKeyframesRule(toStyleRuleKeyframes(rule));
    387         } else if (rule->isRegionRule()) {
    388             addRegionRule(toStyleRuleRegion(rule), addRuleFlags & RuleHasDocumentSecurityOrigin);
    389         } else if (rule->isViewportRule()) {
    390             addViewportRule(toStyleRuleViewport(rule));
    391         } else if (rule->isSupportsRule() && toStyleRuleSupports(rule)->conditionIsSupported()) {
    392             addChildRules(toStyleRuleSupports(rule)->childRules(), medium, addRuleFlags);
    393         }
    394     }
    395 }
    396 
    397 void RuleSet::addRulesFromSheet(StyleSheetContents* sheet, const MediaQueryEvaluator& medium, AddRuleFlags addRuleFlags)
    398 {
    399     ASSERT(sheet);
    400 
    401     addRuleFlags = static_cast<AddRuleFlags>(addRuleFlags | RuleCanUseFastCheckSelector);
    402     const Vector<RefPtr<StyleRuleImport> >& importRules = sheet->importRules();
    403     for (unsigned i = 0; i < importRules.size(); ++i) {
    404         StyleRuleImport* importRule = importRules[i].get();
    405         if (importRule->styleSheet() && (!importRule->mediaQueries() || medium.eval(importRule->mediaQueries(), &m_viewportDependentMediaQueryResults)))
    406             addRulesFromSheet(importRule->styleSheet(), medium, addRuleFlags);
    407     }
    408 
    409     addChildRules(sheet->childRules(), medium, addRuleFlags);
    410 }
    411 
    412 void RuleSet::addStyleRule(StyleRule* rule, AddRuleFlags addRuleFlags)
    413 {
    414     for (size_t selectorIndex = 0; selectorIndex != kNotFound; selectorIndex = rule->selectorList().indexOfNextSelectorAfter(selectorIndex))
    415         addRule(rule, selectorIndex, addRuleFlags);
    416 }
    417 
    418 void RuleSet::compactPendingRules(PendingRuleMap& pendingMap, CompactRuleMap& compactMap)
    419 {
    420     PendingRuleMap::iterator end = pendingMap.end();
    421     for (PendingRuleMap::iterator it = pendingMap.begin(); it != end; ++it) {
    422         OwnPtr<LinkedStack<RuleData> > pendingRules = it->value.release();
    423         CompactRuleMap::iterator compactRules = compactMap.add(it->key, nullptr).iterator;
    424 
    425         TerminatedArrayBuilder<RuleData> builder(compactRules->value.release());
    426         builder.grow(pendingRules->size());
    427         while (!pendingRules->isEmpty()) {
    428             builder.append(pendingRules->peek());
    429             pendingRules->pop();
    430         }
    431 
    432         compactRules->value = builder.release();
    433     }
    434 }
    435 
    436 void RuleSet::compactRules()
    437 {
    438     ASSERT(m_pendingRules);
    439     OwnPtr<PendingRuleMaps> pendingRules = m_pendingRules.release();
    440     compactPendingRules(pendingRules->idRules, m_idRules);
    441     compactPendingRules(pendingRules->classRules, m_classRules);
    442     compactPendingRules(pendingRules->tagRules, m_tagRules);
    443     compactPendingRules(pendingRules->shadowPseudoElementRules, m_shadowPseudoElementRules);
    444     m_linkPseudoClassRules.shrinkToFit();
    445     m_cuePseudoRules.shrinkToFit();
    446     m_focusPseudoClassRules.shrinkToFit();
    447     m_universalRules.shrinkToFit();
    448     m_pageRules.shrinkToFit();
    449     m_viewportRules.shrinkToFit();
    450     m_fontFaceRules.shrinkToFit();
    451     m_keyframesRules.shrinkToFit();
    452     m_treeBoundaryCrossingRules.shrinkToFit();
    453     m_shadowDistributedRules.shrinkToFit();
    454 }
    455 
    456 } // namespace WebCore
    457