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()
90 , m_cleanTimer(this, &PresentationAttributeCacheCleaner::cleanCache)
94 void didHitPresentationAttributeCache()
96 if (presentationAttributeCache().size() < minimumPresentationAttributeCacheSizeForCleaning)
101 if (!m_cleanTimer.isActive())
102 m_cleanTimer.startOneShot(presentationAttributeCacheCleanTimeInSeconds);
106 static const unsigned presentationAttributeCacheCleanTimeInSeconds = 60;
107 static const int minimumPresentationAttributeCacheSizeForCleaning = 100;
108 static const unsigned minimumPresentationAttributeCacheHitCountPerMinute = (100 * presentationAttributeCacheCleanTimeInSeconds) / 60;
110 void cleanCache(Timer<PresentationAttributeCacheCleaner>* timer)
112 ASSERT_UNUSED(timer, timer == &m_cleanTimer);
113 unsigned hitCount = m_hitCount;
115 if (hitCount > minimumPresentationAttributeCacheHitCountPerMinute)
117 presentationAttributeCache().clear();
121 Timer<PresentationAttributeCacheCleaner> m_cleanTimer;
124 static PresentationAttributeCacheCleaner& presentationAttributeCacheCleaner()
126 DEFINE_STATIC_LOCAL(PresentationAttributeCacheCleaner, cleaner, ());
130 void StyledElement::synchronizeStyleAttributeInternal() const
132 ASSERT(elementData());
133 ASSERT(elementData()->m_styleAttributeIsDirty);
134 elementData()->m_styleAttributeIsDirty = false;
135 if (const StylePropertySet* inlineStyle = this->inlineStyle())
136 const_cast<StyledElement*>(this)->setSynchronizedLazyAttribute(styleAttr, inlineStyle->asText());
139 StyledElement::~StyledElement()
141 if (PropertySetCSSStyleDeclaration* cssomWrapper = inlineStyleCSSOMWrapper())
142 cssomWrapper->clearParentElement();
145 CSSStyleDeclaration* StyledElement::style()
147 return ensureMutableInlineStyle()->ensureInlineCSSStyleDeclaration(this);
150 MutableStylePropertySet* StyledElement::ensureMutableInlineStyle()
152 RefPtr<StylePropertySet>& inlineStyle = ensureUniqueElementData()->m_inlineStyle;
154 inlineStyle = MutableStylePropertySet::create(strictToCSSParserMode(isHTMLElement() && !document()->inQuirksMode()));
155 else if (!inlineStyle->isMutable())
156 inlineStyle = inlineStyle->mutableCopy();
157 ASSERT(inlineStyle->isMutable());
158 return static_cast<MutableStylePropertySet*>(inlineStyle.get());
161 void StyledElement::attributeChanged(const QualifiedName& name, const AtomicString& newValue, AttributeModificationReason reason)
163 if (name == styleAttr)
164 styleAttributeChanged(newValue, reason);
165 else if (isPresentationAttribute(name)) {
166 elementData()->m_presentationAttributeStyleIsDirty = true;
167 setNeedsStyleRecalc(InlineStyleChange);
170 Element::attributeChanged(name, newValue, reason);
173 PropertySetCSSStyleDeclaration* StyledElement::inlineStyleCSSOMWrapper()
175 if (!inlineStyle() || !inlineStyle()->hasCSSOMWrapper())
177 PropertySetCSSStyleDeclaration* cssomWrapper = ensureMutableInlineStyle()->cssStyleDeclaration();
178 ASSERT(cssomWrapper && cssomWrapper->parentElement() == this);
182 inline void StyledElement::setInlineStyleFromString(const AtomicString& newStyleString)
184 RefPtr<StylePropertySet>& inlineStyle = elementData()->m_inlineStyle;
186 // Avoid redundant work if we're using shared attribute data with already parsed inline style.
187 if (inlineStyle && !elementData()->isUnique())
190 // We reconstruct the property set instead of mutating if there is no CSSOM wrapper.
191 // This makes wrapperless property sets immutable and so cacheable.
192 if (inlineStyle && !inlineStyle->isMutable())
196 inlineStyle = CSSParser::parseInlineStyleDeclaration(newStyleString, this);
198 ASSERT(inlineStyle->isMutable());
199 static_pointer_cast<MutableStylePropertySet>(inlineStyle)->parseDeclaration(newStyleString, document()->elementSheet()->contents());
203 void StyledElement::styleAttributeChanged(const AtomicString& newStyleString, AttributeModificationReason reason)
205 WTF::OrdinalNumber startLineNumber = WTF::OrdinalNumber::beforeFirst();
206 if (document() && document()->scriptableDocumentParser() && !document()->isInDocumentWrite())
207 startLineNumber = document()->scriptableDocumentParser()->lineNumber();
209 if (newStyleString.isNull()) {
210 if (PropertySetCSSStyleDeclaration* cssomWrapper = inlineStyleCSSOMWrapper())
211 cssomWrapper->clearParentElement();
212 ensureUniqueElementData()->m_inlineStyle.clear();
213 } else if (reason == ModifiedByCloning || document()->contentSecurityPolicy()->allowInlineStyle(document()->url(), startLineNumber))
214 setInlineStyleFromString(newStyleString);
216 elementData()->m_styleAttributeIsDirty = false;
218 setNeedsStyleRecalc(InlineStyleChange);
219 InspectorInstrumentation::didInvalidateStyleAttr(document(), this);
222 void StyledElement::inlineStyleChanged()
224 setNeedsStyleRecalc(InlineStyleChange);
225 ASSERT(elementData());
226 elementData()->m_styleAttributeIsDirty = true;
227 InspectorInstrumentation::didInvalidateStyleAttr(document(), this);
230 bool StyledElement::setInlineStyleProperty(CSSPropertyID propertyID, int identifier, bool important)
232 ensureMutableInlineStyle()->setProperty(propertyID, cssValuePool().createIdentifierValue(identifier), important);
233 inlineStyleChanged();
237 bool StyledElement::setInlineStyleProperty(CSSPropertyID propertyID, double value, CSSPrimitiveValue::UnitTypes unit, bool important)
239 ensureMutableInlineStyle()->setProperty(propertyID, cssValuePool().createValue(value, unit), important);
240 inlineStyleChanged();
244 bool StyledElement::setInlineStyleProperty(CSSPropertyID propertyID, const String& value, bool important)
246 bool changes = ensureMutableInlineStyle()->setProperty(propertyID, value, important, document()->elementSheet()->contents());
248 inlineStyleChanged();
252 bool StyledElement::removeInlineStyleProperty(CSSPropertyID propertyID)
256 bool changes = ensureMutableInlineStyle()->removeProperty(propertyID);
258 inlineStyleChanged();
262 void StyledElement::removeAllInlineStyleProperties()
264 if (!inlineStyle() || inlineStyle()->isEmpty())
266 ensureMutableInlineStyle()->clear();
267 inlineStyleChanged();
270 void StyledElement::addSubresourceAttributeURLs(ListHashSet<KURL>& urls) const
272 if (const StylePropertySet* inlineStyle = elementData() ? elementData()->inlineStyle() : 0)
273 inlineStyle->addSubresourceStyleURLs(urls, document()->elementSheet()->contents());
276 static inline bool attributeNameSort(const pair<AtomicStringImpl*, AtomicString>& p1, const pair<AtomicStringImpl*, AtomicString>& p2)
278 // Sort based on the attribute name pointers. It doesn't matter what the order is as long as it is always the same.
279 return p1.first < p2.first;
282 void StyledElement::makePresentationAttributeCacheKey(PresentationAttributeCacheKey& result) const
284 // FIXME: Enable for SVG.
285 if (namespaceURI() != xhtmlNamespaceURI)
287 // Interpretation of the size attributes on <input> depends on the type attribute.
288 if (hasTagName(inputTag))
290 unsigned size = attributeCount();
291 for (unsigned i = 0; i < size; ++i) {
292 const Attribute* attribute = attributeItem(i);
293 if (!isPresentationAttribute(attribute->name()))
295 if (!attribute->namespaceURI().isNull())
297 // FIXME: Background URL may depend on the base URL and can't be shared. Disallow caching.
298 if (attribute->name() == backgroundAttr)
300 result.attributesAndValues.append(make_pair(attribute->localName().impl(), attribute->value()));
302 if (result.attributesAndValues.isEmpty())
304 // Attribute order doesn't matter. Sort for easy equality comparison.
305 std::sort(result.attributesAndValues.begin(), result.attributesAndValues.end(), attributeNameSort);
306 // The cache key is non-null when the tagName is set.
307 result.tagName = localName().impl();
310 static unsigned computePresentationAttributeCacheHash(const PresentationAttributeCacheKey& key)
314 ASSERT(key.attributesAndValues.size());
315 unsigned attributeHash = StringHasher::hashMemory(key.attributesAndValues.data(), key.attributesAndValues.size() * sizeof(key.attributesAndValues[0]));
316 return WTF::pairIntHash(key.tagName->existingHash(), attributeHash);
319 void StyledElement::rebuildPresentationAttributeStyle()
321 PresentationAttributeCacheKey cacheKey;
322 makePresentationAttributeCacheKey(cacheKey);
324 unsigned cacheHash = computePresentationAttributeCacheHash(cacheKey);
326 PresentationAttributeCache::iterator cacheIterator;
328 cacheIterator = presentationAttributeCache().add(cacheHash, nullptr).iterator;
329 if (cacheIterator->value && cacheIterator->value->key != cacheKey)
332 cacheIterator = presentationAttributeCache().end();
334 RefPtr<StylePropertySet> style;
335 if (cacheHash && cacheIterator->value) {
336 style = cacheIterator->value->value;
337 presentationAttributeCacheCleaner().didHitPresentationAttributeCache();
339 style = MutableStylePropertySet::create(isSVGElement() ? SVGAttributeMode : CSSQuirksMode);
340 unsigned size = attributeCount();
341 for (unsigned i = 0; i < size; ++i) {
342 const Attribute* attribute = attributeItem(i);
343 collectStyleForPresentationAttribute(attribute->name(), attribute->value(), static_cast<MutableStylePropertySet*>(style.get()));
347 // ShareableElementData doesn't store presentation attribute style, so make sure we have a UniqueElementData.
348 UniqueElementData* elementData = ensureUniqueElementData();
350 elementData->m_presentationAttributeStyleIsDirty = false;
351 elementData->m_presentationAttributeStyle = style->isEmpty() ? 0 : style;
353 if (!cacheHash || cacheIterator->value)
356 OwnPtr<PresentationAttributeCacheEntry> newEntry = adoptPtr(new PresentationAttributeCacheEntry);
357 newEntry->key = cacheKey;
358 newEntry->value = style.release();
360 static const int presentationAttributeCacheMaximumSize = 4096;
361 if (presentationAttributeCache().size() > presentationAttributeCacheMaximumSize) {
362 // Start building from scratch if the cache ever gets big.
363 presentationAttributeCache().clear();
364 presentationAttributeCache().set(cacheHash, newEntry.release());
366 cacheIterator->value = newEntry.release();
369 void StyledElement::addPropertyToPresentationAttributeStyle(MutableStylePropertySet* style, CSSPropertyID propertyID, int identifier)
371 style->setProperty(propertyID, cssValuePool().createIdentifierValue(identifier));
374 void StyledElement::addPropertyToPresentationAttributeStyle(MutableStylePropertySet* style, CSSPropertyID propertyID, double value, CSSPrimitiveValue::UnitTypes unit)
376 style->setProperty(propertyID, cssValuePool().createValue(value, unit));
379 void StyledElement::addPropertyToPresentationAttributeStyle(MutableStylePropertySet* style, CSSPropertyID propertyID, const String& value)
381 style->setProperty(propertyID, value, false, document()->elementSheet()->contents());