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::synchronizeStyleAttributeInternal() const
131 ASSERT(elementData());
132 ASSERT(elementData()->m_styleAttributeIsDirty);
133 elementData()->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 MutableStylePropertySet* StyledElement::ensureMutableInlineStyle()
151 RefPtr<StylePropertySet>& inlineStyle = ensureUniqueElementData()->m_inlineStyle;
153 inlineStyle = MutableStylePropertySet::create(strictToCSSParserMode(isHTMLElement() && !document()->inQuirksMode()));
154 else if (!inlineStyle->isMutable())
155 inlineStyle = inlineStyle->mutableCopy();
156 ASSERT(inlineStyle->isMutable());
157 return static_cast<MutableStylePropertySet*>(inlineStyle.get());
160 void StyledElement::attributeChanged(const QualifiedName& name, const AtomicString& newValue, AttributeModificationReason reason)
162 if (name == styleAttr)
163 styleAttributeChanged(newValue, reason);
164 else if (isPresentationAttribute(name)) {
165 elementData()->m_presentationAttributeStyleIsDirty = true;
166 setNeedsStyleRecalc(InlineStyleChange);
169 Element::attributeChanged(name, newValue, reason);
172 PropertySetCSSStyleDeclaration* StyledElement::inlineStyleCSSOMWrapper()
174 if (!inlineStyle() || !inlineStyle()->hasCSSOMWrapper())
176 PropertySetCSSStyleDeclaration* cssomWrapper = ensureMutableInlineStyle()->cssStyleDeclaration();
177 ASSERT(cssomWrapper && cssomWrapper->parentElement() == this);
181 inline void StyledElement::setInlineStyleFromString(const AtomicString& newStyleString)
183 RefPtr<StylePropertySet>& inlineStyle = elementData()->m_inlineStyle;
185 // Avoid redundant work if we're using shared attribute data with already parsed inline style.
186 if (inlineStyle && !elementData()->isUnique())
189 // We reconstruct the property set instead of mutating if there is no CSSOM wrapper.
190 // This makes wrapperless property sets immutable and so cacheable.
191 if (inlineStyle && !inlineStyle->isMutable())
195 inlineStyle = CSSParser::parseInlineStyleDeclaration(newStyleString, this);
197 ASSERT(inlineStyle->isMutable());
198 static_pointer_cast<MutableStylePropertySet>(inlineStyle)->parseDeclaration(newStyleString, document()->elementSheet()->contents());
202 void StyledElement::styleAttributeChanged(const AtomicString& newStyleString, AttributeModificationReason reason)
204 WTF::OrdinalNumber startLineNumber = WTF::OrdinalNumber::beforeFirst();
205 if (document() && document()->scriptableDocumentParser() && !document()->isInDocumentWrite())
206 startLineNumber = document()->scriptableDocumentParser()->lineNumber();
208 if (newStyleString.isNull()) {
209 if (PropertySetCSSStyleDeclaration* cssomWrapper = inlineStyleCSSOMWrapper())
210 cssomWrapper->clearParentElement();
211 ensureUniqueElementData()->m_inlineStyle.clear();
212 } else if (reason == ModifiedByCloning || document()->contentSecurityPolicy()->allowInlineStyle(document()->url(), startLineNumber))
213 setInlineStyleFromString(newStyleString);
215 elementData()->m_styleAttributeIsDirty = false;
217 setNeedsStyleRecalc(InlineStyleChange);
218 InspectorInstrumentation::didInvalidateStyleAttr(document(), this);
221 void StyledElement::inlineStyleChanged()
223 setNeedsStyleRecalc(InlineStyleChange);
224 ASSERT(elementData());
225 elementData()->m_styleAttributeIsDirty = true;
226 InspectorInstrumentation::didInvalidateStyleAttr(document(), this);
229 bool StyledElement::setInlineStyleProperty(CSSPropertyID propertyID, int identifier, bool important)
231 ensureMutableInlineStyle()->setProperty(propertyID, cssValuePool().createIdentifierValue(identifier), important);
232 inlineStyleChanged();
236 bool StyledElement::setInlineStyleProperty(CSSPropertyID propertyID, double value, CSSPrimitiveValue::UnitTypes unit, bool important)
238 ensureMutableInlineStyle()->setProperty(propertyID, cssValuePool().createValue(value, unit), important);
239 inlineStyleChanged();
243 bool StyledElement::setInlineStyleProperty(CSSPropertyID propertyID, const String& value, bool important)
245 bool changes = ensureMutableInlineStyle()->setProperty(propertyID, value, important, document()->elementSheet()->contents());
247 inlineStyleChanged();
251 bool StyledElement::removeInlineStyleProperty(CSSPropertyID propertyID)
255 bool changes = ensureMutableInlineStyle()->removeProperty(propertyID);
257 inlineStyleChanged();
261 void StyledElement::removeAllInlineStyleProperties()
263 if (!inlineStyle() || inlineStyle()->isEmpty())
265 ensureMutableInlineStyle()->clear();
266 inlineStyleChanged();
269 void StyledElement::addSubresourceAttributeURLs(ListHashSet<KURL>& urls) const
271 if (const StylePropertySet* inlineStyle = elementData() ? elementData()->inlineStyle() : 0)
272 inlineStyle->addSubresourceStyleURLs(urls, document()->elementSheet()->contents());
275 static inline bool attributeNameSort(const pair<AtomicStringImpl*, AtomicString>& p1, const pair<AtomicStringImpl*, AtomicString>& p2)
277 // Sort based on the attribute name pointers. It doesn't matter what the order is as long as it is always the same.
278 return p1.first < p2.first;
281 void StyledElement::makePresentationAttributeCacheKey(PresentationAttributeCacheKey& result) const
283 // FIXME: Enable for SVG.
284 if (namespaceURI() != xhtmlNamespaceURI)
286 // Interpretation of the size attributes on <input> depends on the type attribute.
287 if (hasTagName(inputTag))
289 unsigned size = attributeCount();
290 for (unsigned i = 0; i < size; ++i) {
291 const Attribute* attribute = attributeItem(i);
292 if (!isPresentationAttribute(attribute->name()))
294 if (!attribute->namespaceURI().isNull())
296 // FIXME: Background URL may depend on the base URL and can't be shared. Disallow caching.
297 if (attribute->name() == backgroundAttr)
299 result.attributesAndValues.append(make_pair(attribute->localName().impl(), attribute->value()));
301 if (result.attributesAndValues.isEmpty())
303 // Attribute order doesn't matter. Sort for easy equality comparison.
304 std::sort(result.attributesAndValues.begin(), result.attributesAndValues.end(), attributeNameSort);
305 // The cache key is non-null when the tagName is set.
306 result.tagName = localName().impl();
309 static unsigned computePresentationAttributeCacheHash(const PresentationAttributeCacheKey& key)
313 ASSERT(key.attributesAndValues.size());
314 unsigned attributeHash = StringHasher::hashMemory(key.attributesAndValues.data(), key.attributesAndValues.size() * sizeof(key.attributesAndValues[0]));
315 return WTF::pairIntHash(key.tagName->existingHash(), attributeHash);
318 void StyledElement::rebuildPresentationAttributeStyle()
320 PresentationAttributeCacheKey cacheKey;
321 makePresentationAttributeCacheKey(cacheKey);
323 unsigned cacheHash = computePresentationAttributeCacheHash(cacheKey);
325 PresentationAttributeCache::iterator cacheIterator;
327 cacheIterator = presentationAttributeCache().add(cacheHash, nullptr).iterator;
328 if (cacheIterator->value && cacheIterator->value->key != cacheKey)
331 cacheIterator = presentationAttributeCache().end();
333 RefPtr<StylePropertySet> style;
334 if (cacheHash && cacheIterator->value) {
335 style = cacheIterator->value->value;
336 presentationAttributeCacheCleaner().didHitPresentationAttributeCache();
338 style = MutableStylePropertySet::create(isSVGElement() ? SVGAttributeMode : CSSQuirksMode);
339 unsigned size = attributeCount();
340 for (unsigned i = 0; i < size; ++i) {
341 const Attribute* attribute = attributeItem(i);
342 collectStyleForPresentationAttribute(attribute->name(), attribute->value(), static_cast<MutableStylePropertySet*>(style.get()));
346 // ShareableElementData doesn't store presentation attribute style, so make sure we have a UniqueElementData.
347 UniqueElementData* elementData = ensureUniqueElementData();
349 elementData->m_presentationAttributeStyleIsDirty = false;
350 elementData->m_presentationAttributeStyle = style->isEmpty() ? 0 : style;
352 if (!cacheHash || cacheIterator->value)
355 OwnPtr<PresentationAttributeCacheEntry> newEntry = adoptPtr(new PresentationAttributeCacheEntry);
356 newEntry->key = cacheKey;
357 newEntry->value = style.release();
359 static const int presentationAttributeCacheMaximumSize = 4096;
360 if (presentationAttributeCache().size() > presentationAttributeCacheMaximumSize) {
361 // Start building from scratch if the cache ever gets big.
362 presentationAttributeCache().clear();
363 presentationAttributeCache().set(cacheHash, newEntry.release());
365 cacheIterator->value = newEntry.release();
368 void StyledElement::addPropertyToPresentationAttributeStyle(MutableStylePropertySet* style, CSSPropertyID propertyID, int identifier)
370 style->setProperty(propertyID, cssValuePool().createIdentifierValue(identifier));
373 void StyledElement::addPropertyToPresentationAttributeStyle(MutableStylePropertySet* style, CSSPropertyID propertyID, double value, CSSPrimitiveValue::UnitTypes unit)
375 style->setProperty(propertyID, cssValuePool().createValue(value, unit));
378 void StyledElement::addPropertyToPresentationAttributeStyle(MutableStylePropertySet* style, CSSPropertyID propertyID, const String& value)
380 style->setProperty(propertyID, value, false, document()->elementSheet()->contents());