2 * Copyright (C) 1999 Lars Knoll (knoll@kde.org)
3 * (C) 1999 Antti Koivisto (koivisto@kde.org)
4 * (C) 2001 Peter Kelly (pmk@post.com)
5 * (C) 2001 Dirk Mueller (mueller@kde.org)
6 * Copyright (C) 2004, 2005, 2006, 2008, 2010 Apple Inc. All rights reserved.
8 * This library is free software; you can redistribute it and/or
9 * modify it under the terms of the GNU Library General Public
10 * License as published by the Free Software Foundation; either
11 * version 2 of the License, or (at your option) any later version.
13 * This library is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
16 * Library General Public License for more details.
18 * You should have received a copy of the GNU Library General Public License
19 * along with this library; see the file COPYING.LIB. If not, write to
20 * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
21 * Boston, MA 02110-1301, USA.
25 #include "StyledElement.h"
27 #include "Attribute.h"
28 #include "CSSImageValue.h"
29 #include "CSSParser.h"
30 #include "CSSPropertyNames.h"
31 #include "CSSStyleSheet.h"
32 #include "CSSValueKeywords.h"
33 #include "CSSValuePool.h"
35 #include "ClassList.h"
36 #include "ContentSecurityPolicy.h"
37 #include "DOMTokenList.h"
39 #include "HTMLNames.h"
40 #include "HTMLParserIdioms.h"
41 #include "PropertySetCSSStyleDeclaration.h"
42 #include "ScriptableDocumentParser.h"
43 #include "StylePropertySet.h"
44 #include "StyleResolver.h"
45 #include <wtf/HashFunctions.h>
46 #include <wtf/text/TextPosition.h>
52 COMPILE_ASSERT(sizeof(StyledElement) == sizeof(Element), styledelement_should_remain_same_size_as_element);
54 using namespace HTMLNames;
56 struct PresentationAttributeCacheKey {
57 PresentationAttributeCacheKey() : tagName(0) { }
58 AtomicStringImpl* tagName;
59 // Only the values need refcounting.
60 Vector<pair<AtomicStringImpl*, AtomicString>, 3> attributesAndValues;
63 struct PresentationAttributeCacheEntry {
64 WTF_MAKE_FAST_ALLOCATED;
66 PresentationAttributeCacheKey key;
67 RefPtr<StylePropertySet> value;
70 typedef HashMap<unsigned, OwnPtr<PresentationAttributeCacheEntry>, AlreadyHashed> PresentationAttributeCache;
72 static bool operator!=(const PresentationAttributeCacheKey& a, const PresentationAttributeCacheKey& b)
74 if (a.tagName != b.tagName)
76 return a.attributesAndValues != b.attributesAndValues;
79 static PresentationAttributeCache& presentationAttributeCache()
81 DEFINE_STATIC_LOCAL(PresentationAttributeCache, cache, ());
85 class PresentationAttributeCacheCleaner {
86 WTF_MAKE_NONCOPYABLE(PresentationAttributeCacheCleaner); WTF_MAKE_FAST_ALLOCATED;
88 PresentationAttributeCacheCleaner()
89 : m_cleanTimer(this, &PresentationAttributeCacheCleaner::cleanCache)
93 void didHitPresentationAttributeCache()
95 if (presentationAttributeCache().size() < minimumPresentationAttributeCacheSizeForCleaning)
100 if (!m_cleanTimer.isActive())
101 m_cleanTimer.startOneShot(presentationAttributeCacheCleanTimeInSeconds);
105 static const unsigned presentationAttributeCacheCleanTimeInSeconds = 60;
106 static const int minimumPresentationAttributeCacheSizeForCleaning = 100;
107 static const unsigned minimumPresentationAttributeCacheHitCountPerMinute = (100 * presentationAttributeCacheCleanTimeInSeconds) / 60;
109 void cleanCache(Timer<PresentationAttributeCacheCleaner>* timer)
111 ASSERT_UNUSED(timer, timer == &m_cleanTimer);
112 unsigned hitCount = m_hitCount;
114 if (hitCount > minimumPresentationAttributeCacheHitCountPerMinute)
116 presentationAttributeCache().clear();
120 Timer<PresentationAttributeCacheCleaner> m_cleanTimer;
123 static PresentationAttributeCacheCleaner& presentationAttributeCacheCleaner()
125 DEFINE_STATIC_LOCAL(PresentationAttributeCacheCleaner, cleaner, ());
129 void StyledElement::updateStyleAttribute() const
131 ASSERT(attributeData());
132 ASSERT(attributeData()->m_styleAttributeIsDirty);
133 attributeData()->m_styleAttributeIsDirty = false;
134 if (const StylePropertySet* inlineStyle = this->inlineStyle())
135 const_cast<StyledElement*>(this)->setSynchronizedLazyAttribute(styleAttr, inlineStyle->asText());
138 StyledElement::~StyledElement()
140 if (PropertySetCSSStyleDeclaration* cssomWrapper = inlineStyleCSSOMWrapper())
141 cssomWrapper->clearParentElement();
144 CSSStyleDeclaration* StyledElement::style()
146 return ensureMutableInlineStyle()->ensureInlineCSSStyleDeclaration(this);
149 StylePropertySet* StyledElement::ensureMutableInlineStyle()
151 RefPtr<StylePropertySet>& inlineStyle = mutableAttributeData()->m_inlineStyle;
153 inlineStyle = StylePropertySet::create(strictToCSSParserMode(isHTMLElement() && !document()->inQuirksMode()));
154 else if (!inlineStyle->isMutable())
155 inlineStyle = inlineStyle->copy();
156 return inlineStyle.get();
159 void StyledElement::attributeChanged(const QualifiedName& name, const AtomicString& newValue)
161 if (name == styleAttr)
162 styleAttributeChanged(newValue);
163 else if (isPresentationAttribute(name)) {
164 attributeData()->m_presentationAttributeStyleIsDirty = true;
165 setNeedsStyleRecalc(InlineStyleChange);
168 Element::attributeChanged(name, newValue);
171 PropertySetCSSStyleDeclaration* StyledElement::inlineStyleCSSOMWrapper()
173 if (!inlineStyle() || !inlineStyle()->hasCSSOMWrapper())
175 PropertySetCSSStyleDeclaration* cssomWrapper = mutableAttributeData()->m_inlineStyle->cssStyleDeclaration();
176 ASSERT(cssomWrapper && cssomWrapper->parentElement() == this);
180 inline void StyledElement::setInlineStyleFromString(const AtomicString& newStyleString)
182 RefPtr<StylePropertySet>& inlineStyle = attributeData()->m_inlineStyle;
184 // Avoid redundant work if we're using shared attribute data with already parsed inline style.
185 if (inlineStyle && !attributeData()->isMutable())
188 // We reconstruct the property set instead of mutating if there is no CSSOM wrapper.
189 // This makes wrapperless property sets immutable and so cacheable.
190 if (inlineStyle && !inlineStyle->isMutable())
194 inlineStyle = CSSParser::parseInlineStyleDeclaration(newStyleString, this);
196 inlineStyle->parseDeclaration(newStyleString, document()->elementSheet()->contents());
199 void StyledElement::styleAttributeChanged(const AtomicString& newStyleString)
201 WTF::OrdinalNumber startLineNumber = WTF::OrdinalNumber::beforeFirst();
202 if (document() && document()->scriptableDocumentParser() && !document()->isInDocumentWrite())
203 startLineNumber = document()->scriptableDocumentParser()->lineNumber();
205 if (newStyleString.isNull()) {
206 if (PropertySetCSSStyleDeclaration* cssomWrapper = inlineStyleCSSOMWrapper())
207 cssomWrapper->clearParentElement();
208 mutableAttributeData()->m_inlineStyle.clear();
209 } else if (document()->contentSecurityPolicy()->allowInlineStyle(document()->url(), startLineNumber))
210 setInlineStyleFromString(newStyleString);
212 attributeData()->m_styleAttributeIsDirty = false;
214 setNeedsStyleRecalc(InlineStyleChange);
215 InspectorInstrumentation::didInvalidateStyleAttr(document(), this);
218 void StyledElement::inlineStyleChanged()
220 setNeedsStyleRecalc(InlineStyleChange);
221 ASSERT(attributeData());
222 attributeData()->m_styleAttributeIsDirty = true;
223 InspectorInstrumentation::didInvalidateStyleAttr(document(), this);
226 bool StyledElement::setInlineStyleProperty(CSSPropertyID propertyID, int identifier, bool important)
228 ensureMutableInlineStyle()->setProperty(propertyID, cssValuePool().createIdentifierValue(identifier), important);
229 inlineStyleChanged();
233 bool StyledElement::setInlineStyleProperty(CSSPropertyID propertyID, double value, CSSPrimitiveValue::UnitTypes unit, bool important)
235 ensureMutableInlineStyle()->setProperty(propertyID, cssValuePool().createValue(value, unit), important);
236 inlineStyleChanged();
240 bool StyledElement::setInlineStyleProperty(CSSPropertyID propertyID, const String& value, bool important)
242 bool changes = ensureMutableInlineStyle()->setProperty(propertyID, value, important, document()->elementSheet()->contents());
244 inlineStyleChanged();
248 bool StyledElement::removeInlineStyleProperty(CSSPropertyID propertyID)
252 bool changes = ensureMutableInlineStyle()->removeProperty(propertyID);
254 inlineStyleChanged();
258 void StyledElement::removeAllInlineStyleProperties()
260 if (!inlineStyle() || inlineStyle()->isEmpty())
262 ensureMutableInlineStyle()->clear();
263 inlineStyleChanged();
266 void StyledElement::addSubresourceAttributeURLs(ListHashSet<KURL>& urls) const
268 if (const StylePropertySet* inlineStyle = attributeData() ? attributeData()->inlineStyle() : 0)
269 inlineStyle->addSubresourceStyleURLs(urls, document()->elementSheet()->contents());
272 static inline bool attributeNameSort(const pair<AtomicStringImpl*, AtomicString>& p1, const pair<AtomicStringImpl*, AtomicString>& p2)
274 // Sort based on the attribute name pointers. It doesn't matter what the order is as long as it is always the same.
275 return p1.first < p2.first;
278 void StyledElement::makePresentationAttributeCacheKey(PresentationAttributeCacheKey& result) const
280 // FIXME: Enable for SVG.
281 if (namespaceURI() != xhtmlNamespaceURI)
283 // Interpretation of the size attributes on <input> depends on the type attribute.
284 if (hasTagName(inputTag))
286 unsigned size = attributeCount();
287 for (unsigned i = 0; i < size; ++i) {
288 const Attribute* attribute = attributeItem(i);
289 if (!isPresentationAttribute(attribute->name()))
291 if (!attribute->namespaceURI().isNull())
293 // FIXME: Background URL may depend on the base URL and can't be shared. Disallow caching.
294 if (attribute->name() == backgroundAttr)
296 result.attributesAndValues.append(make_pair(attribute->localName().impl(), attribute->value()));
298 if (result.attributesAndValues.isEmpty())
300 // Attribute order doesn't matter. Sort for easy equality comparison.
301 std::sort(result.attributesAndValues.begin(), result.attributesAndValues.end(), attributeNameSort);
302 // The cache key is non-null when the tagName is set.
303 result.tagName = localName().impl();
306 static unsigned computePresentationAttributeCacheHash(const PresentationAttributeCacheKey& key)
310 ASSERT(key.attributesAndValues.size());
311 unsigned attributeHash = StringHasher::hashMemory(key.attributesAndValues.data(), key.attributesAndValues.size() * sizeof(key.attributesAndValues[0]));
312 return WTF::pairIntHash(key.tagName->existingHash(), attributeHash);
315 void StyledElement::rebuildPresentationAttributeStyle()
317 PresentationAttributeCacheKey cacheKey;
318 makePresentationAttributeCacheKey(cacheKey);
320 unsigned cacheHash = computePresentationAttributeCacheHash(cacheKey);
322 PresentationAttributeCache::iterator cacheIterator;
324 cacheIterator = presentationAttributeCache().add(cacheHash, nullptr).iterator;
325 if (cacheIterator->value && cacheIterator->value->key != cacheKey)
328 cacheIterator = presentationAttributeCache().end();
330 RefPtr<StylePropertySet> style;
331 if (cacheHash && cacheIterator->value) {
332 style = cacheIterator->value->value;
333 presentationAttributeCacheCleaner().didHitPresentationAttributeCache();
335 style = StylePropertySet::create(isSVGElement() ? SVGAttributeMode : CSSQuirksMode);
336 unsigned size = attributeCount();
337 for (unsigned i = 0; i < size; ++i) {
338 const Attribute* attribute = attributeItem(i);
339 collectStyleForPresentationAttribute(*attribute, style.get());
343 // ImmutableElementAttributeData doesn't store presentation attribute style, so make sure we have a MutableElementAttributeData.
344 ElementAttributeData* attributeData = mutableAttributeData();
346 attributeData->m_presentationAttributeStyleIsDirty = false;
347 attributeData->setPresentationAttributeStyle(style->isEmpty() ? 0 : style);
349 if (!cacheHash || cacheIterator->value)
352 OwnPtr<PresentationAttributeCacheEntry> newEntry = adoptPtr(new PresentationAttributeCacheEntry);
353 newEntry->key = cacheKey;
354 newEntry->value = style.release();
356 static const int presentationAttributeCacheMaximumSize = 4096;
357 if (presentationAttributeCache().size() > presentationAttributeCacheMaximumSize) {
358 // Start building from scratch if the cache ever gets big.
359 presentationAttributeCache().clear();
360 presentationAttributeCache().set(cacheHash, newEntry.release());
362 cacheIterator->value = newEntry.release();
365 void StyledElement::addPropertyToPresentationAttributeStyle(StylePropertySet* style, CSSPropertyID propertyID, int identifier)
367 style->setProperty(propertyID, cssValuePool().createIdentifierValue(identifier));
370 void StyledElement::addPropertyToPresentationAttributeStyle(StylePropertySet* style, CSSPropertyID propertyID, double value, CSSPrimitiveValue::UnitTypes unit)
372 style->setProperty(propertyID, cssValuePool().createValue(value, unit));
375 void StyledElement::addPropertyToPresentationAttributeStyle(StylePropertySet* style, CSSPropertyID propertyID, const String& value)
377 style->setProperty(propertyID, value, false, document()->elementSheet()->contents());