blob: 02518c5bcfad6a3e0e43c5279e4d700cd817c74a [file] [log] [blame]
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001/*
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 * (C) 2007 David Smith (catfish.man@gmail.com)
7 * Copyright (C) 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2012, 2013 Apple Inc. All rights reserved.
8 * (C) 2007 Eric Seidel (eric@webkit.org)
9 *
10 * This library is free software; you can redistribute it and/or
11 * modify it under the terms of the GNU Library General Public
12 * License as published by the Free Software Foundation; either
13 * version 2 of the License, or (at your option) any later version.
14 *
15 * This library is distributed in the hope that it will be useful,
16 * but WITHOUT ANY WARRANTY; without even the implied warranty of
17 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
18 * Library General Public License for more details.
19 *
20 * You should have received a copy of the GNU Library General Public License
21 * along with this library; see the file COPYING.LIB. If not, write to
22 * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
23 * Boston, MA 02110-1301, USA.
24 */
25
26#include "config.h"
27#include "core/dom/Element.h"
28
Ben Murdoch591b9582013-07-10 11:41:44 +010029#include "CSSPropertyNames.h"
30#include "CSSValueKeywords.h"
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +010031#include "HTMLNames.h"
Ben Murdoch7757ec22013-07-23 11:17:36 +010032#include "RuntimeEnabledFeatures.h"
Torne (Richard Coles)93ac45c2013-05-29 14:40:20 +010033#include "SVGNames.h"
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +010034#include "XMLNames.h"
Ben Murdochdf957042013-08-06 11:01:27 +010035#include "bindings/v8/ExceptionState.h"
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +010036#include "core/accessibility/AXObjectCache.h"
Ben Murdoch83750172013-07-24 10:36:59 +010037#include "core/animation/DocumentTimeline.h"
Torne (Richard Coles)c0e19a62013-08-30 15:15:11 +010038#include "core/animation/css/CSSAnimations.h"
Ben Murdoch591b9582013-07-10 11:41:44 +010039#include "core/css/CSSParser.h"
40#include "core/css/CSSStyleSheet.h"
41#include "core/css/CSSValuePool.h"
42#include "core/css/PropertySetCSSStyleDeclaration.h"
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +010043#include "core/css/StylePropertySet.h"
Torne (Richard Coles)81a51572013-05-13 16:52:28 +010044#include "core/css/resolver/StyleResolver.h"
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +010045#include "core/dom/Attr.h"
Ben Murdoch591b9582013-07-10 11:41:44 +010046#include "core/dom/Attribute.h"
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +010047#include "core/dom/ClientRect.h"
48#include "core/dom/ClientRectList.h"
Ben Murdoch83750172013-07-24 10:36:59 +010049#include "core/dom/CustomElement.h"
Ben Murdoche69819b2013-07-17 14:56:49 +010050#include "core/dom/CustomElementRegistrationContext.h"
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +010051#include "core/dom/DatasetDOMStringMap.h"
52#include "core/dom/Document.h"
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +010053#include "core/dom/DocumentSharedObjectPool.h"
54#include "core/dom/ElementRareData.h"
Ben Murdoch02772c62013-07-26 10:21:05 +010055#include "core/dom/EventDispatcher.h"
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +010056#include "core/dom/ExceptionCode.h"
Ben Murdoch02772c62013-07-26 10:21:05 +010057#include "core/dom/FocusEvent.h"
Torne (Richard Coles)f5e4ad52013-08-05 13:57:57 +010058#include "core/dom/FullscreenElementStack.h"
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +010059#include "core/dom/MutationObserverInterestGroup.h"
60#include "core/dom/MutationRecord.h"
61#include "core/dom/NamedNodeMap.h"
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +010062#include "core/dom/NodeRenderStyle.h"
63#include "core/dom/NodeRenderingContext.h"
Torne (Richard Coles)8abfc582013-09-12 12:10:38 +010064#include "core/dom/PostAttachCallbacks.h"
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +010065#include "core/dom/PseudoElement.h"
Ben Murdoch591b9582013-07-10 11:41:44 +010066#include "core/dom/ScriptableDocumentParser.h"
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +010067#include "core/dom/SelectorQuery.h"
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +010068#include "core/dom/Text.h"
Torne (Richard Coles)e5249552013-05-15 11:35:13 +010069#include "core/dom/shadow/InsertionPoint.h"
70#include "core/dom/shadow/ShadowRoot.h"
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +010071#include "core/editing/FrameSelection.h"
72#include "core/editing/TextIterator.h"
73#include "core/editing/htmlediting.h"
74#include "core/html/ClassList.h"
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +010075#include "core/html/HTMLCollection.h"
76#include "core/html/HTMLDocument.h"
77#include "core/html/HTMLElement.h"
78#include "core/html/HTMLFormControlsCollection.h"
79#include "core/html/HTMLFrameOwnerElement.h"
80#include "core/html/HTMLLabelElement.h"
81#include "core/html/HTMLOptionsCollection.h"
82#include "core/html/HTMLTableRowsCollection.h"
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +010083#include "core/html/parser/HTMLParserIdioms.h"
Ben Murdoch591b9582013-07-10 11:41:44 +010084#include "core/page/ContentSecurityPolicy.h"
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +010085#include "core/page/FocusController.h"
86#include "core/page/Frame.h"
87#include "core/page/FrameView.h"
88#include "core/page/Page.h"
89#include "core/page/PointerLockController.h"
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +010090#include "core/rendering/FlowThreadController.h"
91#include "core/rendering/RenderRegion.h"
92#include "core/rendering/RenderView.h"
93#include "core/rendering/RenderWidget.h"
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +010094#include "core/svg/SVGDocumentExtensions.h"
95#include "core/svg/SVGElement.h"
Torne (Richard Coles)93ac45c2013-05-29 14:40:20 +010096#include "wtf/BitVector.h"
Ben Murdoch591b9582013-07-10 11:41:44 +010097#include "wtf/HashFunctions.h"
Torne (Richard Coles)93ac45c2013-05-29 14:40:20 +010098#include "wtf/text/CString.h"
Ben Murdoch591b9582013-07-10 11:41:44 +010099#include "wtf/text/TextPosition.h"
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100100
101namespace WebCore {
102
103using namespace HTMLNames;
104using namespace XMLNames;
105
106static inline bool shouldIgnoreAttributeCase(const Element* e)
107{
Torne (Richard Coles)8abfc582013-09-12 12:10:38 +0100108 return e && e->document().isHTMLDocument() && e->isHTMLElement();
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100109}
Ben Murdoch591b9582013-07-10 11:41:44 +0100110
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100111class StyleResolverParentPusher {
112public:
113 StyleResolverParentPusher(Element* parent)
114 : m_parent(parent)
115 , m_pushedStyleResolver(0)
116 {
117 }
118 void push()
119 {
120 if (m_pushedStyleResolver)
121 return;
Torne (Richard Coles)8abfc582013-09-12 12:10:38 +0100122 m_pushedStyleResolver = m_parent->document().styleResolver();
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100123 m_pushedStyleResolver->pushParentElement(m_parent);
124 }
125 ~StyleResolverParentPusher()
126 {
127
128 if (!m_pushedStyleResolver)
129 return;
130
131 // This tells us that our pushed style selector is in a bad state,
132 // so we should just bail out in that scenario.
Torne (Richard Coles)8abfc582013-09-12 12:10:38 +0100133 ASSERT(m_pushedStyleResolver == m_parent->document().styleResolver());
134 if (m_pushedStyleResolver != m_parent->document().styleResolver())
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100135 return;
136
137 m_pushedStyleResolver->popParentElement(m_parent);
138 }
139
140private:
141 Element* m_parent;
142 StyleResolver* m_pushedStyleResolver;
143};
144
145typedef Vector<RefPtr<Attr> > AttrNodeList;
146typedef HashMap<Element*, OwnPtr<AttrNodeList> > AttrNodeListMap;
147
148static AttrNodeListMap& attrNodeListMap()
149{
150 DEFINE_STATIC_LOCAL(AttrNodeListMap, map, ());
151 return map;
152}
153
154static AttrNodeList* attrNodeListForElement(Element* element)
155{
156 if (!element->hasSyntheticAttrChildNodes())
157 return 0;
158 ASSERT(attrNodeListMap().contains(element));
159 return attrNodeListMap().get(element);
160}
161
162static AttrNodeList* ensureAttrNodeListForElement(Element* element)
163{
164 if (element->hasSyntheticAttrChildNodes()) {
165 ASSERT(attrNodeListMap().contains(element));
166 return attrNodeListMap().get(element);
167 }
168 ASSERT(!attrNodeListMap().contains(element));
169 element->setHasSyntheticAttrChildNodes(true);
170 AttrNodeListMap::AddResult result = attrNodeListMap().add(element, adoptPtr(new AttrNodeList));
171 return result.iterator->value.get();
172}
173
174static void removeAttrNodeListForElement(Element* element)
175{
176 ASSERT(element->hasSyntheticAttrChildNodes());
177 ASSERT(attrNodeListMap().contains(element));
178 attrNodeListMap().remove(element);
179 element->setHasSyntheticAttrChildNodes(false);
180}
181
182static Attr* findAttrNodeInList(AttrNodeList* attrNodeList, const QualifiedName& name)
183{
184 for (unsigned i = 0; i < attrNodeList->size(); ++i) {
185 if (attrNodeList->at(i)->qualifiedName() == name)
186 return attrNodeList->at(i).get();
187 }
188 return 0;
189}
190
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100191PassRefPtr<Element> Element::create(const QualifiedName& tagName, Document* document)
192{
193 return adoptRef(new Element(tagName, document, CreateElement));
194}
195
196Element::~Element()
197{
198#ifndef NDEBUG
Torne (Richard Coles)8abfc582013-09-12 12:10:38 +0100199 if (document().renderer()) {
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100200 // When the document is not destroyed, an element that was part of a named flow
201 // content nodes should have been removed from the content nodes collection
202 // and the inNamedFlow flag reset.
203 ASSERT(!inNamedFlow());
204 }
205#endif
206
Ben Murdoch591b9582013-07-10 11:41:44 +0100207 if (PropertySetCSSStyleDeclaration* cssomWrapper = inlineStyleCSSOMWrapper())
208 cssomWrapper->clearParentElement();
209
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100210 if (hasRareData()) {
211 ElementRareData* data = elementRareData();
212 data->setPseudoElement(BEFORE, 0);
213 data->setPseudoElement(AFTER, 0);
Ben Murdoche69819b2013-07-17 14:56:49 +0100214 data->setPseudoElement(BACKDROP, 0);
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100215 data->clearShadow();
Torne (Richard Coles)f5e4ad52013-08-05 13:57:57 +0100216
217 if (RuntimeEnabledFeatures::webAnimationsCSSEnabled()) {
218 if (ActiveAnimations* activeAnimations = data->activeAnimations())
219 activeAnimations->cssAnimations()->cancel();
220 }
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100221 }
222
Ben Murdoch83750172013-07-24 10:36:59 +0100223 if (isCustomElement())
224 CustomElement::wasDestroyed(this);
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100225
226 if (hasSyntheticAttrChildNodes())
227 detachAllAttrNodesFromElement();
228
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100229 if (hasPendingResources()) {
Torne (Richard Coles)8abfc582013-09-12 12:10:38 +0100230 document().accessSVGExtensions()->removeElementFromPendingResources(this);
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100231 ASSERT(!hasPendingResources());
232 }
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100233}
234
235inline ElementRareData* Element::elementRareData() const
236{
237 ASSERT(hasRareData());
238 return static_cast<ElementRareData*>(rareData());
239}
240
241inline ElementRareData* Element::ensureElementRareData()
242{
243 return static_cast<ElementRareData*>(ensureRareData());
244}
245
246void Element::clearTabIndexExplicitlyIfNeeded()
247{
248 if (hasRareData())
249 elementRareData()->clearTabIndexExplicitly();
250}
251
252void Element::setTabIndexExplicitly(short tabIndex)
253{
254 ensureElementRareData()->setTabIndexExplicitly(tabIndex);
255}
256
257bool Element::supportsFocus() const
258{
259 return hasRareData() && elementRareData()->tabIndexSetExplicitly();
260}
261
262short Element::tabIndex() const
263{
264 return hasRareData() ? elementRareData()->tabIndex() : 0;
265}
266
Torne (Richard Coles)521d96e2013-06-19 11:58:24 +0100267bool Element::rendererIsFocusable() const
268{
269 // Elements in canvas fallback content are not rendered, but they are allowed to be
270 // focusable as long as their canvas is displayed and visible.
271 if (isInCanvasSubtree()) {
272 const Element* e = this;
273 while (e && !e->hasLocalName(canvasTag))
274 e = e->parentElement();
275 ASSERT(e);
276 return e->renderer() && e->renderer()->style()->visibility() == VISIBLE;
277 }
278
279 // FIXME: These asserts should be in Node::isFocusable, but there are some
Ben Murdoche69819b2013-07-17 14:56:49 +0100280 // callsites like Document::setFocusedElement that would currently fail on
Torne (Richard Coles)521d96e2013-06-19 11:58:24 +0100281 // them. See crbug.com/251163
282 if (renderer()) {
283 ASSERT(!renderer()->needsLayout());
284 } else {
285 // We can't just use needsStyleRecalc() because if the node is in a
286 // display:none tree it might say it needs style recalc but the whole
287 // document is actually up to date.
Torne (Richard Coles)8abfc582013-09-12 12:10:38 +0100288 ASSERT(!document().childNeedsStyleRecalc());
Torne (Richard Coles)521d96e2013-06-19 11:58:24 +0100289 }
290
291 // FIXME: Even if we are not visible, we might have a child that is visible.
292 // Hyatt wants to fix that some day with a "has visible content" flag or the like.
293 if (!renderer() || renderer()->style()->visibility() != VISIBLE)
294 return false;
295
296 return true;
297}
298
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100299DEFINE_VIRTUAL_ATTRIBUTE_EVENT_LISTENER(Element, blur);
300DEFINE_VIRTUAL_ATTRIBUTE_EVENT_LISTENER(Element, error);
301DEFINE_VIRTUAL_ATTRIBUTE_EVENT_LISTENER(Element, focus);
302DEFINE_VIRTUAL_ATTRIBUTE_EVENT_LISTENER(Element, load);
303
304PassRefPtr<Node> Element::cloneNode(bool deep)
305{
306 return deep ? cloneElementWithChildren() : cloneElementWithoutChildren();
307}
308
309PassRefPtr<Element> Element::cloneElementWithChildren()
310{
311 RefPtr<Element> clone = cloneElementWithoutChildren();
312 cloneChildNodes(clone.get());
313 return clone.release();
314}
315
316PassRefPtr<Element> Element::cloneElementWithoutChildren()
317{
318 RefPtr<Element> clone = cloneElementWithoutAttributesAndChildren();
319 // This will catch HTML elements in the wrong namespace that are not correctly copied.
320 // This is a sanity check as HTML overloads some of the DOM methods.
321 ASSERT(isHTMLElement() == clone->isHTMLElement());
322
323 clone->cloneDataFromElement(*this);
324 return clone.release();
325}
326
327PassRefPtr<Element> Element::cloneElementWithoutAttributesAndChildren()
328{
Torne (Richard Coles)8abfc582013-09-12 12:10:38 +0100329 return document().createElement(tagQName(), false);
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100330}
331
332PassRefPtr<Attr> Element::detachAttribute(size_t index)
333{
334 ASSERT(elementData());
Torne (Richard Coles)e5249552013-05-15 11:35:13 +0100335 const Attribute* attribute = elementData()->attributeItem(index);
336 RefPtr<Attr> attrNode = attrIfExists(attribute->name());
337 if (attrNode)
338 detachAttrNodeAtIndex(attrNode.get(), index);
339 else {
340 attrNode = Attr::create(document(), attribute->name(), attribute->value());
341 removeAttributeInternal(index, NotInSynchronizationOfLazyAttribute);
342 }
343 return attrNode.release();
344}
345
346void Element::detachAttrNodeAtIndex(Attr* attr, size_t index)
347{
348 ASSERT(attr);
349 ASSERT(elementData());
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100350
351 const Attribute* attribute = elementData()->attributeItem(index);
352 ASSERT(attribute);
Torne (Richard Coles)e5249552013-05-15 11:35:13 +0100353 ASSERT(attribute->name() == attr->qualifiedName());
354 detachAttrNodeFromElementWithValue(attr, attribute->value());
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100355 removeAttributeInternal(index, NotInSynchronizationOfLazyAttribute);
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100356}
357
358void Element::removeAttribute(const QualifiedName& name)
359{
360 if (!elementData())
361 return;
362
363 size_t index = elementData()->getAttributeItemIndex(name);
364 if (index == notFound)
365 return;
366
367 removeAttributeInternal(index, NotInSynchronizationOfLazyAttribute);
368}
369
370void Element::setBooleanAttribute(const QualifiedName& name, bool value)
371{
372 if (value)
373 setAttribute(name, emptyAtom);
374 else
375 removeAttribute(name);
376}
377
378NamedNodeMap* Element::attributes() const
379{
380 ElementRareData* rareData = const_cast<Element*>(this)->ensureElementRareData();
381 if (NamedNodeMap* attributeMap = rareData->attributeMap())
382 return attributeMap;
383
384 rareData->setAttributeMap(NamedNodeMap::create(const_cast<Element*>(this)));
385 return rareData->attributeMap();
386}
387
Ben Murdoch83750172013-07-24 10:36:59 +0100388ActiveAnimations* Element::activeAnimations() const
Torne (Richard Coles)81a51572013-05-13 16:52:28 +0100389{
Ben Murdoch83750172013-07-24 10:36:59 +0100390 if (hasActiveAnimations())
391 return elementRareData()->activeAnimations();
392 return 0;
Torne (Richard Coles)81a51572013-05-13 16:52:28 +0100393}
394
Ben Murdoch83750172013-07-24 10:36:59 +0100395ActiveAnimations* Element::ensureActiveAnimations()
Torne (Richard Coles)81a51572013-05-13 16:52:28 +0100396{
Ben Murdoch83750172013-07-24 10:36:59 +0100397 ElementRareData* rareData = ensureElementRareData();
398 if (!elementRareData()->activeAnimations())
399 rareData->setActiveAnimations(adoptPtr(new ActiveAnimations()));
400 return rareData->activeAnimations();
Torne (Richard Coles)81a51572013-05-13 16:52:28 +0100401}
402
403bool Element::hasActiveAnimations() const
404{
Ben Murdoch83750172013-07-24 10:36:59 +0100405 if (!RuntimeEnabledFeatures::webAnimationsEnabled())
406 return false;
Torne (Richard Coles)81a51572013-05-13 16:52:28 +0100407
Ben Murdoch83750172013-07-24 10:36:59 +0100408 if (!hasRareData())
409 return false;
410
411 ActiveAnimations* activeAnimations = elementRareData()->activeAnimations();
412 return activeAnimations && !activeAnimations->isEmpty();
Torne (Richard Coles)81a51572013-05-13 16:52:28 +0100413}
414
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100415Node::NodeType Element::nodeType() const
416{
417 return ELEMENT_NODE;
418}
419
420bool Element::hasAttribute(const QualifiedName& name) const
421{
422 return hasAttributeNS(name.namespaceURI(), name.localName());
423}
424
425void Element::synchronizeAllAttributes() const
426{
427 if (!elementData())
428 return;
429 if (elementData()->m_styleAttributeIsDirty) {
430 ASSERT(isStyledElement());
Ben Murdoch591b9582013-07-10 11:41:44 +0100431 synchronizeStyleAttributeInternal();
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100432 }
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100433 if (elementData()->m_animatedSVGAttributesAreDirty) {
434 ASSERT(isSVGElement());
435 toSVGElement(this)->synchronizeAnimatedSVGAttribute(anyQName());
436 }
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100437}
438
439inline void Element::synchronizeAttribute(const QualifiedName& name) const
440{
441 if (!elementData())
442 return;
443 if (UNLIKELY(name == styleAttr && elementData()->m_styleAttributeIsDirty)) {
444 ASSERT(isStyledElement());
Ben Murdoch591b9582013-07-10 11:41:44 +0100445 synchronizeStyleAttributeInternal();
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100446 return;
447 }
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100448 if (UNLIKELY(elementData()->m_animatedSVGAttributesAreDirty)) {
449 ASSERT(isSVGElement());
450 toSVGElement(this)->synchronizeAnimatedSVGAttribute(name);
451 }
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100452}
453
454inline void Element::synchronizeAttribute(const AtomicString& localName) const
455{
456 // This version of synchronizeAttribute() is streamlined for the case where you don't have a full QualifiedName,
457 // e.g when called from DOM API.
458 if (!elementData())
459 return;
460 if (elementData()->m_styleAttributeIsDirty && equalPossiblyIgnoringCase(localName, styleAttr.localName(), shouldIgnoreAttributeCase(this))) {
461 ASSERT(isStyledElement());
Ben Murdoch591b9582013-07-10 11:41:44 +0100462 synchronizeStyleAttributeInternal();
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100463 return;
464 }
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100465 if (elementData()->m_animatedSVGAttributesAreDirty) {
466 // We're not passing a namespace argument on purpose. SVGNames::*Attr are defined w/o namespaces as well.
467 ASSERT(isSVGElement());
468 static_cast<const SVGElement*>(this)->synchronizeAnimatedSVGAttribute(QualifiedName(nullAtom, localName, nullAtom));
469 }
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100470}
471
472const AtomicString& Element::getAttribute(const QualifiedName& name) const
473{
474 if (!elementData())
475 return nullAtom;
476 synchronizeAttribute(name);
477 if (const Attribute* attribute = getAttributeItem(name))
478 return attribute->value();
479 return nullAtom;
480}
481
Ben Murdoch591b9582013-07-10 11:41:44 +0100482void Element::scrollIntoView(bool alignToTop)
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100483{
Torne (Richard Coles)8abfc582013-09-12 12:10:38 +0100484 document().updateLayoutIgnorePendingStylesheets();
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100485
486 if (!renderer())
487 return;
488
489 LayoutRect bounds = boundingBox();
490 // Align to the top / bottom and to the closest edge.
491 if (alignToTop)
492 renderer()->scrollRectToVisible(bounds, ScrollAlignment::alignToEdgeIfNeeded, ScrollAlignment::alignTopAlways);
493 else
494 renderer()->scrollRectToVisible(bounds, ScrollAlignment::alignToEdgeIfNeeded, ScrollAlignment::alignBottomAlways);
495}
496
497void Element::scrollIntoViewIfNeeded(bool centerIfNeeded)
498{
Torne (Richard Coles)8abfc582013-09-12 12:10:38 +0100499 document().updateLayoutIgnorePendingStylesheets();
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100500
501 if (!renderer())
502 return;
503
504 LayoutRect bounds = boundingBox();
505 if (centerIfNeeded)
506 renderer()->scrollRectToVisible(bounds, ScrollAlignment::alignCenterIfNeeded, ScrollAlignment::alignCenterIfNeeded);
507 else
508 renderer()->scrollRectToVisible(bounds, ScrollAlignment::alignToEdgeIfNeeded, ScrollAlignment::alignToEdgeIfNeeded);
509}
510
511void Element::scrollByUnits(int units, ScrollGranularity granularity)
512{
Torne (Richard Coles)8abfc582013-09-12 12:10:38 +0100513 document().updateLayoutIgnorePendingStylesheets();
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100514
515 if (!renderer())
516 return;
517
518 if (!renderer()->hasOverflowClip())
519 return;
520
521 ScrollDirection direction = ScrollDown;
522 if (units < 0) {
523 direction = ScrollUp;
524 units = -units;
525 }
526 Node* stopNode = this;
527 toRenderBox(renderer())->scroll(direction, granularity, units, &stopNode);
528}
529
530void Element::scrollByLines(int lines)
531{
532 scrollByUnits(lines, ScrollByLine);
533}
534
535void Element::scrollByPages(int pages)
536{
537 scrollByUnits(pages, ScrollByPage);
538}
539
540static float localZoomForRenderer(RenderObject* renderer)
541{
542 // FIXME: This does the wrong thing if two opposing zooms are in effect and canceled each
543 // other out, but the alternative is that we'd have to crawl up the whole render tree every
544 // time (or store an additional bit in the RenderStyle to indicate that a zoom was specified).
545 float zoomFactor = 1;
546 if (renderer->style()->effectiveZoom() != 1) {
547 // Need to find the nearest enclosing RenderObject that set up
548 // a differing zoom, and then we divide our result by it to eliminate the zoom.
549 RenderObject* prev = renderer;
550 for (RenderObject* curr = prev->parent(); curr; curr = curr->parent()) {
551 if (curr->style()->effectiveZoom() != prev->style()->effectiveZoom()) {
552 zoomFactor = prev->style()->zoom();
553 break;
554 }
555 prev = curr;
556 }
557 if (prev->isRenderView())
558 zoomFactor = prev->style()->zoom();
559 }
560 return zoomFactor;
561}
562
563static int adjustForLocalZoom(LayoutUnit value, RenderObject* renderer)
564{
565 float zoomFactor = localZoomForRenderer(renderer);
566 if (zoomFactor == 1)
567 return value;
568 return lroundf(value / zoomFactor);
569}
570
571int Element::offsetLeft()
572{
Torne (Richard Coles)8abfc582013-09-12 12:10:38 +0100573 document().partialUpdateLayoutIgnorePendingStylesheets(this);
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100574 if (RenderBoxModelObject* renderer = renderBoxModelObject())
575 return adjustForLocalZoom(renderer->pixelSnappedOffsetLeft(), renderer);
576 return 0;
577}
578
579int Element::offsetTop()
580{
Torne (Richard Coles)8abfc582013-09-12 12:10:38 +0100581 document().partialUpdateLayoutIgnorePendingStylesheets(this);
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100582 if (RenderBoxModelObject* renderer = renderBoxModelObject())
583 return adjustForLocalZoom(renderer->pixelSnappedOffsetTop(), renderer);
584 return 0;
585}
586
587int Element::offsetWidth()
588{
Torne (Richard Coles)8abfc582013-09-12 12:10:38 +0100589 document().updateStyleForNodeIfNeeded(this);
Ben Murdoch591b9582013-07-10 11:41:44 +0100590
591 if (RenderBox* renderer = renderBox()) {
592 if (!renderer->requiresLayoutToDetermineWidth())
593 return adjustLayoutUnitForAbsoluteZoom(renderer->fixedOffsetWidth(), renderer).round();
594 }
595
Torne (Richard Coles)8abfc582013-09-12 12:10:38 +0100596 document().partialUpdateLayoutIgnorePendingStylesheets(this);
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100597 if (RenderBoxModelObject* renderer = renderBoxModelObject())
598 return adjustLayoutUnitForAbsoluteZoom(renderer->pixelSnappedOffsetWidth(), renderer).round();
599 return 0;
600}
601
602int Element::offsetHeight()
603{
Torne (Richard Coles)8abfc582013-09-12 12:10:38 +0100604 document().partialUpdateLayoutIgnorePendingStylesheets(this);
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100605 if (RenderBoxModelObject* renderer = renderBoxModelObject())
606 return adjustLayoutUnitForAbsoluteZoom(renderer->pixelSnappedOffsetHeight(), renderer).round();
607 return 0;
608}
609
610Element* Element::bindingsOffsetParent()
611{
612 Element* element = offsetParent();
613 if (!element || !element->isInShadowTree())
614 return element;
Torne (Richard Coles)521d96e2013-06-19 11:58:24 +0100615 return element->containingShadowRoot()->shouldExposeToBindings() ? element : 0;
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100616}
617
618Element* Element::offsetParent()
619{
Torne (Richard Coles)8abfc582013-09-12 12:10:38 +0100620 document().updateLayoutIgnorePendingStylesheets();
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100621 if (RenderObject* renderer = this->renderer())
622 return renderer->offsetParent();
623 return 0;
624}
625
626int Element::clientLeft()
627{
Torne (Richard Coles)8abfc582013-09-12 12:10:38 +0100628 document().updateLayoutIgnorePendingStylesheets();
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100629
630 if (RenderBox* renderer = renderBox())
631 return adjustForAbsoluteZoom(roundToInt(renderer->clientLeft()), renderer);
632 return 0;
633}
634
635int Element::clientTop()
636{
Torne (Richard Coles)8abfc582013-09-12 12:10:38 +0100637 document().updateLayoutIgnorePendingStylesheets();
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100638
639 if (RenderBox* renderer = renderBox())
640 return adjustForAbsoluteZoom(roundToInt(renderer->clientTop()), renderer);
641 return 0;
642}
643
644int Element::clientWidth()
645{
Torne (Richard Coles)8abfc582013-09-12 12:10:38 +0100646 document().updateLayoutIgnorePendingStylesheets();
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100647
648 // When in strict mode, clientWidth for the document element should return the width of the containing frame.
649 // When in quirks mode, clientWidth for the body element should return the width of the containing frame.
Torne (Richard Coles)8abfc582013-09-12 12:10:38 +0100650 bool inQuirksMode = document().inQuirksMode();
651 if ((!inQuirksMode && document().documentElement() == this)
652 || (inQuirksMode && isHTMLElement() && document().body() == this)) {
653 if (FrameView* view = document().view()) {
654 if (RenderView* renderView = document().renderView())
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100655 return adjustForAbsoluteZoom(view->layoutWidth(), renderView);
656 }
657 }
Ben Murdoch591b9582013-07-10 11:41:44 +0100658
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100659 if (RenderBox* renderer = renderBox())
660 return adjustLayoutUnitForAbsoluteZoom(renderer->pixelSnappedClientWidth(), renderer).round();
661 return 0;
662}
663
664int Element::clientHeight()
665{
Torne (Richard Coles)8abfc582013-09-12 12:10:38 +0100666 document().updateLayoutIgnorePendingStylesheets();
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100667
668 // When in strict mode, clientHeight for the document element should return the height of the containing frame.
669 // When in quirks mode, clientHeight for the body element should return the height of the containing frame.
Torne (Richard Coles)8abfc582013-09-12 12:10:38 +0100670 bool inQuirksMode = document().inQuirksMode();
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100671
Torne (Richard Coles)8abfc582013-09-12 12:10:38 +0100672 if ((!inQuirksMode && document().documentElement() == this)
673 || (inQuirksMode && isHTMLElement() && document().body() == this)) {
674 if (FrameView* view = document().view()) {
675 if (RenderView* renderView = document().renderView())
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100676 return adjustForAbsoluteZoom(view->layoutHeight(), renderView);
677 }
678 }
Ben Murdoch591b9582013-07-10 11:41:44 +0100679
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100680 if (RenderBox* renderer = renderBox())
681 return adjustLayoutUnitForAbsoluteZoom(renderer->pixelSnappedClientHeight(), renderer).round();
682 return 0;
683}
684
685int Element::scrollLeft()
686{
Torne (Richard Coles)8abfc582013-09-12 12:10:38 +0100687 document().updateLayoutIgnorePendingStylesheets();
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100688 if (RenderBox* rend = renderBox())
689 return adjustForAbsoluteZoom(rend->scrollLeft(), rend);
690 return 0;
691}
692
693int Element::scrollTop()
694{
Torne (Richard Coles)8abfc582013-09-12 12:10:38 +0100695 document().updateLayoutIgnorePendingStylesheets();
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100696 if (RenderBox* rend = renderBox())
697 return adjustForAbsoluteZoom(rend->scrollTop(), rend);
698 return 0;
699}
700
701void Element::setScrollLeft(int newLeft)
702{
Torne (Richard Coles)8abfc582013-09-12 12:10:38 +0100703 document().updateLayoutIgnorePendingStylesheets();
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100704 if (RenderBox* rend = renderBox())
705 rend->setScrollLeft(static_cast<int>(newLeft * rend->style()->effectiveZoom()));
706}
707
708void Element::setScrollTop(int newTop)
709{
Torne (Richard Coles)8abfc582013-09-12 12:10:38 +0100710 document().updateLayoutIgnorePendingStylesheets();
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100711 if (RenderBox* rend = renderBox())
712 rend->setScrollTop(static_cast<int>(newTop * rend->style()->effectiveZoom()));
713}
714
715int Element::scrollWidth()
716{
Torne (Richard Coles)8abfc582013-09-12 12:10:38 +0100717 document().updateLayoutIgnorePendingStylesheets();
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100718 if (RenderBox* rend = renderBox())
719 return adjustForAbsoluteZoom(rend->scrollWidth(), rend);
720 return 0;
721}
722
723int Element::scrollHeight()
724{
Torne (Richard Coles)8abfc582013-09-12 12:10:38 +0100725 document().updateLayoutIgnorePendingStylesheets();
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100726 if (RenderBox* rend = renderBox())
727 return adjustForAbsoluteZoom(rend->scrollHeight(), rend);
728 return 0;
729}
730
731IntRect Element::boundsInRootViewSpace()
732{
Torne (Richard Coles)8abfc582013-09-12 12:10:38 +0100733 document().updateLayoutIgnorePendingStylesheets();
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100734
Torne (Richard Coles)8abfc582013-09-12 12:10:38 +0100735 FrameView* view = document().view();
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100736 if (!view)
737 return IntRect();
738
739 Vector<FloatQuad> quads;
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100740 if (isSVGElement() && renderer()) {
741 // Get the bounding rectangle from the SVG model.
742 SVGElement* svgElement = toSVGElement(this);
743 FloatRect localRect;
744 if (svgElement->getBoundingBox(localRect))
745 quads.append(renderer()->localToAbsoluteQuad(localRect));
Torne (Richard Coles)93ac45c2013-05-29 14:40:20 +0100746 } else {
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100747 // Get the bounding rectangle from the box model.
748 if (renderBoxModelObject())
749 renderBoxModelObject()->absoluteQuads(quads);
750 }
751
752 if (quads.isEmpty())
753 return IntRect();
754
755 IntRect result = quads[0].enclosingBoundingBox();
756 for (size_t i = 1; i < quads.size(); ++i)
757 result.unite(quads[i].enclosingBoundingBox());
758
759 result = view->contentsToRootView(result);
760 return result;
761}
762
763PassRefPtr<ClientRectList> Element::getClientRects()
764{
Torne (Richard Coles)8abfc582013-09-12 12:10:38 +0100765 document().updateLayoutIgnorePendingStylesheets();
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100766
767 RenderBoxModelObject* renderBoxModelObject = this->renderBoxModelObject();
768 if (!renderBoxModelObject)
769 return ClientRectList::create();
770
771 // FIXME: Handle SVG elements.
772 // FIXME: Handle table/inline-table with a caption.
773
774 Vector<FloatQuad> quads;
775 renderBoxModelObject->absoluteQuads(quads);
Torne (Richard Coles)8abfc582013-09-12 12:10:38 +0100776 document().adjustFloatQuadsForScrollAndAbsoluteZoom(quads, renderBoxModelObject);
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100777 return ClientRectList::create(quads);
778}
779
780PassRefPtr<ClientRect> Element::getBoundingClientRect()
781{
Torne (Richard Coles)8abfc582013-09-12 12:10:38 +0100782 document().updateLayoutIgnorePendingStylesheets();
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100783
784 Vector<FloatQuad> quads;
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100785 if (isSVGElement() && renderer() && !renderer()->isSVGRoot()) {
786 // Get the bounding rectangle from the SVG model.
787 SVGElement* svgElement = toSVGElement(this);
788 FloatRect localRect;
789 if (svgElement->getBoundingBox(localRect))
790 quads.append(renderer()->localToAbsoluteQuad(localRect));
Torne (Richard Coles)93ac45c2013-05-29 14:40:20 +0100791 } else {
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100792 // Get the bounding rectangle from the box model.
793 if (renderBoxModelObject())
794 renderBoxModelObject()->absoluteQuads(quads);
795 }
796
797 if (quads.isEmpty())
798 return ClientRect::create();
799
800 FloatRect result = quads[0].boundingBox();
801 for (size_t i = 1; i < quads.size(); ++i)
802 result.unite(quads[i].boundingBox());
803
Torne (Richard Coles)8abfc582013-09-12 12:10:38 +0100804 document().adjustFloatRectForScrollAndAbsoluteZoom(result, renderer());
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100805 return ClientRect::create(result);
806}
Ben Murdoch591b9582013-07-10 11:41:44 +0100807
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100808IntRect Element::screenRect() const
809{
810 if (!renderer())
811 return IntRect();
812 // FIXME: this should probably respect transforms
Torne (Richard Coles)8abfc582013-09-12 12:10:38 +0100813 return document().view()->contentsToScreen(renderer()->absoluteBoundingBoxRectIgnoringTransforms());
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100814}
815
816const AtomicString& Element::getAttribute(const AtomicString& localName) const
817{
818 if (!elementData())
819 return nullAtom;
820 synchronizeAttribute(localName);
821 if (const Attribute* attribute = elementData()->getAttributeItem(localName, shouldIgnoreAttributeCase(this)))
822 return attribute->value();
823 return nullAtom;
824}
825
826const AtomicString& Element::getAttributeNS(const AtomicString& namespaceURI, const AtomicString& localName) const
827{
828 return getAttribute(QualifiedName(nullAtom, localName, namespaceURI));
829}
830
Ben Murdochdf957042013-08-06 11:01:27 +0100831void Element::setAttribute(const AtomicString& localName, const AtomicString& value, ExceptionState& es)
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100832{
833 if (!Document::isValidName(localName)) {
Ben Murdochdf957042013-08-06 11:01:27 +0100834 es.throwDOMException(InvalidCharacterError);
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100835 return;
836 }
837
838 synchronizeAttribute(localName);
839 const AtomicString& caseAdjustedLocalName = shouldIgnoreAttributeCase(this) ? localName.lower() : localName;
840
841 size_t index = elementData() ? elementData()->getAttributeItemIndex(caseAdjustedLocalName, false) : notFound;
842 const QualifiedName& qName = index != notFound ? attributeItem(index)->name() : QualifiedName(nullAtom, caseAdjustedLocalName, nullAtom);
843 setAttributeInternal(index, qName, value, NotInSynchronizationOfLazyAttribute);
844}
845
846void Element::setAttribute(const QualifiedName& name, const AtomicString& value)
847{
848 synchronizeAttribute(name);
849 size_t index = elementData() ? elementData()->getAttributeItemIndex(name) : notFound;
850 setAttributeInternal(index, name, value, NotInSynchronizationOfLazyAttribute);
851}
852
853void Element::setSynchronizedLazyAttribute(const QualifiedName& name, const AtomicString& value)
854{
855 size_t index = elementData() ? elementData()->getAttributeItemIndex(name) : notFound;
856 setAttributeInternal(index, name, value, InSynchronizationOfLazyAttribute);
857}
858
859inline void Element::setAttributeInternal(size_t index, const QualifiedName& name, const AtomicString& newValue, SynchronizationOfLazyAttribute inSynchronizationOfLazyAttribute)
860{
861 if (newValue.isNull()) {
862 if (index != notFound)
863 removeAttributeInternal(index, inSynchronizationOfLazyAttribute);
864 return;
865 }
866
867 if (index == notFound) {
868 addAttributeInternal(name, newValue, inSynchronizationOfLazyAttribute);
869 return;
870 }
871
Torne (Richard Coles)8abfc582013-09-12 12:10:38 +0100872 QualifiedName existingAttributeName = attributeItem(index)->name();
873
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100874 if (!inSynchronizationOfLazyAttribute)
Torne (Richard Coles)8abfc582013-09-12 12:10:38 +0100875 willModifyAttribute(existingAttributeName, attributeItem(index)->value(), newValue);
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100876
877 if (newValue != attributeItem(index)->value()) {
878 // If there is an Attr node hooked to this attribute, the Attr::setValue() call below
879 // will write into the ElementData.
880 // FIXME: Refactor this so it makes some sense.
Torne (Richard Coles)8abfc582013-09-12 12:10:38 +0100881 if (RefPtr<Attr> attrNode = inSynchronizationOfLazyAttribute ? 0 : attrIfExists(existingAttributeName))
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100882 attrNode->setValue(newValue);
883 else
884 ensureUniqueElementData()->attributeItem(index)->setValue(newValue);
885 }
886
887 if (!inSynchronizationOfLazyAttribute)
Torne (Richard Coles)8abfc582013-09-12 12:10:38 +0100888 didModifyAttribute(existingAttributeName, newValue);
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100889}
890
891static inline AtomicString makeIdForStyleResolution(const AtomicString& value, bool inQuirksMode)
892{
893 if (inQuirksMode)
894 return value.lower();
895 return value;
896}
897
Ben Murdoch7757ec22013-07-23 11:17:36 +0100898static bool checkNeedsStyleInvalidationForIdChange(const AtomicString& oldId, const AtomicString& newId, const RuleFeatureSet& features)
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100899{
900 ASSERT(newId != oldId);
Ben Murdoch7757ec22013-07-23 11:17:36 +0100901 if (!oldId.isEmpty() && features.hasSelectorForId(oldId))
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100902 return true;
Ben Murdoch7757ec22013-07-23 11:17:36 +0100903 if (!newId.isEmpty() && features.hasSelectorForId(newId))
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100904 return true;
905 return false;
906}
907
Ben Murdoch591b9582013-07-10 11:41:44 +0100908void Element::attributeChanged(const QualifiedName& name, const AtomicString& newValue, AttributeModificationReason reason)
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100909{
910 if (ElementShadow* parentElementShadow = shadowOfParentForDistribution(this)) {
911 if (shouldInvalidateDistributionWhenAttributeChanged(parentElementShadow, name, newValue))
Torne (Richard Coles)f5e4ad52013-08-05 13:57:57 +0100912 parentElementShadow->setNeedsDistributionRecalc();
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100913 }
914
915 parseAttribute(name, newValue);
916
Torne (Richard Coles)8abfc582013-09-12 12:10:38 +0100917 document().incDOMTreeVersion();
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100918
Torne (Richard Coles)8abfc582013-09-12 12:10:38 +0100919 StyleResolver* styleResolver = document().styleResolverIfExists();
Ben Murdoche69819b2013-07-17 14:56:49 +0100920 bool testShouldInvalidateStyle = attached() && styleResolver && styleChangeType() < SubtreeStyleChange;
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100921 bool shouldInvalidateStyle = false;
922
Ben Murdoch591b9582013-07-10 11:41:44 +0100923 if (isStyledElement() && name == styleAttr) {
924 styleAttributeChanged(newValue, reason);
925 } else if (isStyledElement() && isPresentationAttribute(name)) {
926 elementData()->m_presentationAttributeStyleIsDirty = true;
Ben Murdoche69819b2013-07-17 14:56:49 +0100927 setNeedsStyleRecalc(LocalStyleChange);
Ben Murdoch591b9582013-07-10 11:41:44 +0100928 }
929
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100930 if (isIdAttributeName(name)) {
931 AtomicString oldId = elementData()->idForStyleResolution();
Torne (Richard Coles)8abfc582013-09-12 12:10:38 +0100932 AtomicString newId = makeIdForStyleResolution(newValue, document().inQuirksMode());
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100933 if (newId != oldId) {
934 elementData()->setIdForStyleResolution(newId);
Ben Murdoch7757ec22013-07-23 11:17:36 +0100935 shouldInvalidateStyle = testShouldInvalidateStyle && checkNeedsStyleInvalidationForIdChange(oldId, newId, styleResolver->ruleFeatureSet());
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100936 }
Ben Murdoch591b9582013-07-10 11:41:44 +0100937 } else if (name == classAttr) {
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100938 classAttributeChanged(newValue);
Ben Murdoch591b9582013-07-10 11:41:44 +0100939 } else if (name == HTMLNames::nameAttr) {
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100940 setHasName(!newValue.isNull());
Ben Murdoch591b9582013-07-10 11:41:44 +0100941 } else if (name == HTMLNames::pseudoAttr) {
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100942 shouldInvalidateStyle |= testShouldInvalidateStyle && isInShadowTree();
Ben Murdoch591b9582013-07-10 11:41:44 +0100943 }
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100944
945 invalidateNodeListCachesInAncestors(&name, this);
946
947 // If there is currently no StyleResolver, we can't be sure that this attribute change won't affect style.
948 shouldInvalidateStyle |= !styleResolver;
949
950 if (shouldInvalidateStyle)
951 setNeedsStyleRecalc();
952
Torne (Richard Coles)8abfc582013-09-12 12:10:38 +0100953 if (AXObjectCache* cache = document().existingAXObjectCache())
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100954 cache->handleAttributeChanged(name, this);
955}
956
957inline void Element::attributeChangedFromParserOrByCloning(const QualifiedName& name, const AtomicString& newValue, AttributeModificationReason reason)
958{
Ben Murdoche69819b2013-07-17 14:56:49 +0100959 if (name == isAttr)
Torne (Richard Coles)e1f1df52013-08-23 16:39:30 +0100960 CustomElementRegistrationContext::setTypeExtension(this, newValue, reason == ModifiedDirectly ? CustomElementRegistrationContext::CreatedByParser : CustomElementRegistrationContext::NotCreatedByParser);
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100961 attributeChanged(name, newValue, reason);
962}
963
964template <typename CharacterType>
965static inline bool classStringHasClassName(const CharacterType* characters, unsigned length)
966{
967 ASSERT(length > 0);
968
969 unsigned i = 0;
970 do {
971 if (isNotHTMLSpace(characters[i]))
972 break;
973 ++i;
974 } while (i < length);
975
976 return i < length;
977}
978
979static inline bool classStringHasClassName(const AtomicString& newClassString)
980{
981 unsigned length = newClassString.length();
982
983 if (!length)
984 return false;
985
986 if (newClassString.is8Bit())
987 return classStringHasClassName(newClassString.characters8(), length);
988 return classStringHasClassName(newClassString.characters16(), length);
989}
990
991template<typename Checker>
992static bool checkSelectorForClassChange(const SpaceSplitString& changedClasses, const Checker& checker)
993{
994 unsigned changedSize = changedClasses.size();
995 for (unsigned i = 0; i < changedSize; ++i) {
996 if (checker.hasSelectorForClass(changedClasses[i]))
997 return true;
998 }
999 return false;
1000}
1001
1002template<typename Checker>
1003static bool checkSelectorForClassChange(const SpaceSplitString& oldClasses, const SpaceSplitString& newClasses, const Checker& checker)
1004{
1005 unsigned oldSize = oldClasses.size();
1006 if (!oldSize)
1007 return checkSelectorForClassChange(newClasses, checker);
1008 BitVector remainingClassBits;
1009 remainingClassBits.ensureSize(oldSize);
1010 // Class vectors tend to be very short. This is faster than using a hash table.
1011 unsigned newSize = newClasses.size();
1012 for (unsigned i = 0; i < newSize; ++i) {
1013 for (unsigned j = 0; j < oldSize; ++j) {
1014 if (newClasses[i] == oldClasses[j]) {
1015 remainingClassBits.quickSet(j);
1016 continue;
1017 }
1018 }
1019 if (checker.hasSelectorForClass(newClasses[i]))
1020 return true;
1021 }
1022 for (unsigned i = 0; i < oldSize; ++i) {
1023 // If the bit is not set the the corresponding class has been removed.
1024 if (remainingClassBits.quickGet(i))
1025 continue;
1026 if (checker.hasSelectorForClass(oldClasses[i]))
1027 return true;
1028 }
1029 return false;
1030}
1031
1032void Element::classAttributeChanged(const AtomicString& newClassString)
1033{
Torne (Richard Coles)8abfc582013-09-12 12:10:38 +01001034 StyleResolver* styleResolver = document().styleResolverIfExists();
Ben Murdoche69819b2013-07-17 14:56:49 +01001035 bool testShouldInvalidateStyle = attached() && styleResolver && styleChangeType() < SubtreeStyleChange;
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001036 bool shouldInvalidateStyle = false;
1037
1038 if (classStringHasClassName(newClassString)) {
Torne (Richard Coles)8abfc582013-09-12 12:10:38 +01001039 const bool shouldFoldCase = document().inQuirksMode();
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001040 const SpaceSplitString oldClasses = elementData()->classNames();
1041 elementData()->setClass(newClassString, shouldFoldCase);
1042 const SpaceSplitString& newClasses = elementData()->classNames();
Ben Murdoch7757ec22013-07-23 11:17:36 +01001043 shouldInvalidateStyle = testShouldInvalidateStyle && checkSelectorForClassChange(oldClasses, newClasses, styleResolver->ruleFeatureSet());
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001044 } else {
1045 const SpaceSplitString& oldClasses = elementData()->classNames();
Ben Murdoch7757ec22013-07-23 11:17:36 +01001046 shouldInvalidateStyle = testShouldInvalidateStyle && checkSelectorForClassChange(oldClasses, styleResolver->ruleFeatureSet());
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001047 elementData()->clearClass();
1048 }
1049
1050 if (hasRareData())
1051 elementRareData()->clearClassListValueForQuirksMode();
1052
1053 if (shouldInvalidateStyle)
1054 setNeedsStyleRecalc();
1055}
1056
1057bool Element::shouldInvalidateDistributionWhenAttributeChanged(ElementShadow* elementShadow, const QualifiedName& name, const AtomicString& newValue)
1058{
1059 ASSERT(elementShadow);
Torne (Richard Coles)e1f1df52013-08-23 16:39:30 +01001060 const SelectRuleFeatureSet& featureSet = elementShadow->ensureSelectFeatureSet();
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001061
1062 if (isIdAttributeName(name)) {
1063 AtomicString oldId = elementData()->idForStyleResolution();
Torne (Richard Coles)8abfc582013-09-12 12:10:38 +01001064 AtomicString newId = makeIdForStyleResolution(newValue, document().inQuirksMode());
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001065 if (newId != oldId) {
1066 if (!oldId.isEmpty() && featureSet.hasSelectorForId(oldId))
1067 return true;
1068 if (!newId.isEmpty() && featureSet.hasSelectorForId(newId))
1069 return true;
1070 }
1071 }
1072
1073 if (name == HTMLNames::classAttr) {
1074 const AtomicString& newClassString = newValue;
1075 if (classStringHasClassName(newClassString)) {
Torne (Richard Coles)8abfc582013-09-12 12:10:38 +01001076 const bool shouldFoldCase = document().inQuirksMode();
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001077 const SpaceSplitString& oldClasses = elementData()->classNames();
1078 const SpaceSplitString newClasses(newClassString, shouldFoldCase);
1079 if (checkSelectorForClassChange(oldClasses, newClasses, featureSet))
1080 return true;
1081 } else {
1082 const SpaceSplitString& oldClasses = elementData()->classNames();
1083 if (checkSelectorForClassChange(oldClasses, featureSet))
1084 return true;
1085 }
1086 }
1087
1088 return featureSet.hasSelectorForAttribute(name.localName());
1089}
1090
1091// Returns true is the given attribute is an event handler.
1092// We consider an event handler any attribute that begins with "on".
1093// It is a simple solution that has the advantage of not requiring any
1094// code or configuration change if a new event handler is defined.
1095
1096static inline bool isEventHandlerAttribute(const Attribute& attribute)
1097{
1098 return attribute.name().namespaceURI().isNull() && attribute.name().localName().startsWith("on");
1099}
1100
1101bool Element::isJavaScriptURLAttribute(const Attribute& attribute) const
1102{
1103 return isURLAttribute(attribute) && protocolIsJavaScript(stripLeadingAndTrailingHTMLSpaces(attribute.value()));
1104}
1105
1106void Element::stripScriptingAttributes(Vector<Attribute>& attributeVector) const
1107{
1108 size_t destination = 0;
1109 for (size_t source = 0; source < attributeVector.size(); ++source) {
1110 if (isEventHandlerAttribute(attributeVector[source])
1111 || isJavaScriptURLAttribute(attributeVector[source])
1112 || isHTMLContentAttribute(attributeVector[source]))
1113 continue;
1114
1115 if (source != destination)
1116 attributeVector[destination] = attributeVector[source];
1117
1118 ++destination;
1119 }
1120 attributeVector.shrink(destination);
1121}
1122
1123void Element::parserSetAttributes(const Vector<Attribute>& attributeVector)
1124{
1125 ASSERT(!inDocument());
1126 ASSERT(!parentNode());
1127 ASSERT(!m_elementData);
1128
1129 if (attributeVector.isEmpty())
1130 return;
1131
Torne (Richard Coles)8abfc582013-09-12 12:10:38 +01001132 if (document().sharedObjectPool())
1133 m_elementData = document().sharedObjectPool()->cachedShareableElementDataWithAttributes(attributeVector);
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001134 else
1135 m_elementData = ShareableElementData::createWithAttributes(attributeVector);
1136
1137 // Use attributeVector instead of m_elementData because attributeChanged might modify m_elementData.
1138 for (unsigned i = 0; i < attributeVector.size(); ++i)
1139 attributeChangedFromParserOrByCloning(attributeVector[i].name(), attributeVector[i].value(), ModifiedDirectly);
1140}
1141
1142bool Element::hasAttributes() const
1143{
1144 synchronizeAllAttributes();
1145 return elementData() && elementData()->length();
1146}
1147
1148bool Element::hasEquivalentAttributes(const Element* other) const
1149{
1150 synchronizeAllAttributes();
1151 other->synchronizeAllAttributes();
1152 if (elementData() == other->elementData())
1153 return true;
1154 if (elementData())
1155 return elementData()->isEquivalent(other->elementData());
1156 if (other->elementData())
1157 return other->elementData()->isEquivalent(elementData());
1158 return true;
1159}
1160
1161String Element::nodeName() const
1162{
1163 return m_tagName.toString();
1164}
1165
1166String Element::nodeNamePreservingCase() const
1167{
1168 return m_tagName.toString();
1169}
1170
Ben Murdochdf957042013-08-06 11:01:27 +01001171void Element::setPrefix(const AtomicString& prefix, ExceptionState& es)
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001172{
Ben Murdochdf957042013-08-06 11:01:27 +01001173 checkSetPrefix(prefix, es);
1174 if (es.hadException())
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001175 return;
1176
1177 m_tagName.setPrefix(prefix.isEmpty() ? AtomicString() : prefix);
1178}
1179
1180KURL Element::baseURI() const
1181{
1182 const AtomicString& baseAttribute = getAttribute(baseAttr);
1183 KURL base(KURL(), baseAttribute);
1184 if (!base.protocol().isEmpty())
1185 return base;
1186
1187 ContainerNode* parent = parentNode();
1188 if (!parent)
1189 return base;
1190
1191 const KURL& parentBase = parent->baseURI();
1192 if (parentBase.isNull())
1193 return base;
1194
1195 return KURL(parentBase, baseAttribute);
1196}
1197
Torne (Richard Coles)8abfc582013-09-12 12:10:38 +01001198const AtomicString Element::imageSourceURL() const
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001199{
1200 return getAttribute(srcAttr);
1201}
1202
Torne (Richard Coles)8abfc582013-09-12 12:10:38 +01001203bool Element::rendererIsNeeded(const RenderStyle& style)
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001204{
Torne (Richard Coles)8abfc582013-09-12 12:10:38 +01001205 return style.display() != NONE;
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001206}
1207
Ben Murdoch591b9582013-07-10 11:41:44 +01001208RenderObject* Element::createRenderer(RenderStyle* style)
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001209{
1210 return RenderObject::createObject(this, style);
1211}
1212
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001213Node::InsertionNotificationRequest Element::insertedInto(ContainerNode* insertionPoint)
1214{
1215 // need to do superclass processing first so inDocument() is true
1216 // by the time we reach updateId
1217 ContainerNode::insertedInto(insertionPoint);
1218
1219 if (containsFullScreenElement() && parentElement() && !parentElement()->containsFullScreenElement())
1220 setContainsFullScreenElementOnAncestorsCrossingFrameBoundaries(true);
1221
1222 if (Element* before = pseudoElement(BEFORE))
1223 before->insertedInto(insertionPoint);
1224
1225 if (Element* after = pseudoElement(AFTER))
1226 after->insertedInto(insertionPoint);
1227
Torne (Richard Coles)e1f1df52013-08-23 16:39:30 +01001228 if (Element* backdrop = pseudoElement(BACKDROP))
1229 backdrop->insertedInto(insertionPoint);
1230
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001231 if (!insertionPoint->isInTreeScope())
1232 return InsertionDone;
1233
1234 if (hasRareData())
1235 elementRareData()->clearClassListValueForQuirksMode();
1236
Torne (Richard Coles)f5e4ad52013-08-05 13:57:57 +01001237 if (isUpgradedCustomElement() && inDocument())
1238 CustomElement::didEnterDocument(this, document());
1239
Torne (Richard Coles)8abfc582013-09-12 12:10:38 +01001240 TreeScope& scope = insertionPoint->treeScope();
1241 if (&scope != &treeScope())
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001242 return InsertionDone;
1243
1244 const AtomicString& idValue = getIdAttribute();
Ben Murdoch00d3faa2013-08-14 11:52:03 +01001245 if (!idValue.isNull())
1246 updateId(scope, nullAtom, idValue);
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001247
1248 const AtomicString& nameValue = getNameAttribute();
Ben Murdoch00d3faa2013-08-14 11:52:03 +01001249 if (!nameValue.isNull())
1250 updateName(nullAtom, nameValue);
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001251
1252 if (hasTagName(labelTag)) {
Torne (Richard Coles)8abfc582013-09-12 12:10:38 +01001253 if (scope.shouldCacheLabelsByForAttribute())
Ben Murdoch00d3faa2013-08-14 11:52:03 +01001254 updateLabel(scope, nullAtom, fastGetAttribute(forAttr));
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001255 }
1256
Ben Murdoch3c9e4ae2013-08-12 14:20:44 +01001257 if (parentElement() && parentElement()->isInCanvasSubtree())
1258 setIsInCanvasSubtree(true);
1259
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001260 return InsertionDone;
1261}
1262
1263void Element::removedFrom(ContainerNode* insertionPoint)
1264{
Torne (Richard Coles)f5e4ad52013-08-05 13:57:57 +01001265 bool wasInDocument = insertionPoint->inDocument();
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001266
1267 if (Element* before = pseudoElement(BEFORE))
1268 before->removedFrom(insertionPoint);
1269
1270 if (Element* after = pseudoElement(AFTER))
1271 after->removedFrom(insertionPoint);
1272
Ben Murdoche69819b2013-07-17 14:56:49 +01001273 if (Element* backdrop = pseudoElement(BACKDROP))
1274 backdrop->removedFrom(insertionPoint);
Torne (Richard Coles)8abfc582013-09-12 12:10:38 +01001275 document().removeFromTopLayer(this);
Ben Murdoche69819b2013-07-17 14:56:49 +01001276
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001277 if (containsFullScreenElement())
1278 setContainsFullScreenElementOnAncestorsCrossingFrameBoundaries(false);
1279
Torne (Richard Coles)8abfc582013-09-12 12:10:38 +01001280 if (document().page())
1281 document().page()->pointerLockController().elementRemoved(this);
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001282
1283 setSavedLayerScrollOffset(IntSize());
1284
Torne (Richard Coles)8abfc582013-09-12 12:10:38 +01001285 if (insertionPoint->isInTreeScope() && &treeScope() == &document()) {
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001286 const AtomicString& idValue = getIdAttribute();
Ben Murdoch00d3faa2013-08-14 11:52:03 +01001287 if (!idValue.isNull())
1288 updateId(insertionPoint->treeScope(), idValue, nullAtom);
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001289
1290 const AtomicString& nameValue = getNameAttribute();
Ben Murdoch00d3faa2013-08-14 11:52:03 +01001291 if (!nameValue.isNull())
1292 updateName(nameValue, nullAtom);
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001293
1294 if (hasTagName(labelTag)) {
Torne (Richard Coles)8abfc582013-09-12 12:10:38 +01001295 TreeScope& treeScope = insertionPoint->treeScope();
1296 if (treeScope.shouldCacheLabelsByForAttribute())
Ben Murdoch00d3faa2013-08-14 11:52:03 +01001297 updateLabel(treeScope, fastGetAttribute(forAttr), nullAtom);
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001298 }
1299 }
1300
1301 ContainerNode::removedFrom(insertionPoint);
Ben Murdoche69819b2013-07-17 14:56:49 +01001302 if (wasInDocument) {
1303 if (hasPendingResources())
Torne (Richard Coles)8abfc582013-09-12 12:10:38 +01001304 document().accessSVGExtensions()->removeElementFromPendingResources(this);
Ben Murdoche69819b2013-07-17 14:56:49 +01001305
Ben Murdoch83750172013-07-24 10:36:59 +01001306 if (isUpgradedCustomElement())
Ben Murdochfff88842013-07-30 15:20:09 +01001307 CustomElement::didLeaveDocument(this, insertionPoint->document());
Ben Murdoche69819b2013-07-17 14:56:49 +01001308 }
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001309
Ben Murdoch3c9e4ae2013-08-12 14:20:44 +01001310 if (hasRareData())
1311 elementRareData()->setIsInCanvasSubtree(false);
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001312}
1313
Torne (Richard Coles)521d96e2013-06-19 11:58:24 +01001314void Element::attach(const AttachContext& context)
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001315{
Torne (Richard Coles)8abfc582013-09-12 12:10:38 +01001316 ASSERT(document().inStyleRecalc());
1317
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001318 StyleResolverParentPusher parentPusher(this);
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001319
Torne (Richard Coles)e1f1df52013-08-23 16:39:30 +01001320 // We've already been through detach when doing a lazyAttach, but we might
1321 // need to clear any state that's been added since then.
1322 if (hasRareData() && styleChangeType() == LazyAttachStyleChange) {
1323 ElementRareData* data = elementRareData();
1324 data->clearComputedStyle();
1325 data->resetDynamicRestyleObservations();
1326 if (!context.resolvedStyle)
1327 data->resetStyleState();
1328 }
1329
Ben Murdoch3c9e4ae2013-08-12 14:20:44 +01001330 NodeRenderingContext(this, context.resolvedStyle).createRendererForElementIfNeeded();
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001331
1332 createPseudoElementIfNeeded(BEFORE);
1333
1334 // When a shadow root exists, it does the work of attaching the children.
1335 if (ElementShadow* shadow = this->shadow()) {
1336 parentPusher.push();
Ben Murdoch591b9582013-07-10 11:41:44 +01001337 shadow->attach(context);
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001338 } else if (firstChild())
1339 parentPusher.push();
1340
Torne (Richard Coles)521d96e2013-06-19 11:58:24 +01001341 ContainerNode::attach(context);
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001342
1343 createPseudoElementIfNeeded(AFTER);
Ben Murdoche69819b2013-07-17 14:56:49 +01001344 createPseudoElementIfNeeded(BACKDROP);
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001345
Ben Murdoch591b9582013-07-10 11:41:44 +01001346 if (hasRareData()) {
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001347 ElementRareData* data = elementRareData();
1348 if (data->needsFocusAppearanceUpdateSoonAfterAttach()) {
Torne (Richard Coles)8abfc582013-09-12 12:10:38 +01001349 if (isFocusable() && document().focusedElement() == this)
1350 document().updateFocusAppearanceSoon(false /* don't restore selection */);
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001351 data->setNeedsFocusAppearanceUpdateSoonAfterAttach(false);
1352 }
1353 }
Ben Murdoch591b9582013-07-10 11:41:44 +01001354
Torne (Richard Coles)8abfc582013-09-12 12:10:38 +01001355 InspectorInstrumentation::didRecalculateStyleForElement(this);
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001356}
1357
1358void Element::unregisterNamedFlowContentNode()
1359{
Torne (Richard Coles)8abfc582013-09-12 12:10:38 +01001360 if (RuntimeEnabledFeatures::cssRegionsEnabled() && inNamedFlow() && document().renderView())
1361 document().renderView()->flowThreadController()->unregisterNamedFlowContentNode(this);
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001362}
1363
Torne (Richard Coles)521d96e2013-06-19 11:58:24 +01001364void Element::detach(const AttachContext& context)
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001365{
1366 WidgetHierarchyUpdatesSuspensionScope suspendWidgetHierarchyUpdates;
1367 unregisterNamedFlowContentNode();
1368 cancelFocusAppearanceUpdate();
1369 if (hasRareData()) {
1370 ElementRareData* data = elementRareData();
1371 data->setPseudoElement(BEFORE, 0);
1372 data->setPseudoElement(AFTER, 0);
Ben Murdoche69819b2013-07-17 14:56:49 +01001373 data->setPseudoElement(BACKDROP, 0);
Ben Murdoch3c9e4ae2013-08-12 14:20:44 +01001374 data->clearComputedStyle();
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001375 data->resetDynamicRestyleObservations();
Ben Murdoch591b9582013-07-10 11:41:44 +01001376 data->setIsInsideRegion(false);
Torne (Richard Coles)f5e4ad52013-08-05 13:57:57 +01001377
Ben Murdoch3c9e4ae2013-08-12 14:20:44 +01001378 // Only clear the style state if we're not going to reuse the style from recalcStyle.
1379 if (!context.resolvedStyle)
1380 data->resetStyleState();
1381
Torne (Richard Coles)f5e4ad52013-08-05 13:57:57 +01001382 if (RuntimeEnabledFeatures::webAnimationsCSSEnabled() && !context.performingReattach) {
1383 if (ActiveAnimations* activeAnimations = data->activeAnimations())
1384 activeAnimations->cssAnimations()->cancel();
1385 }
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001386 }
Ben Murdoch591b9582013-07-10 11:41:44 +01001387 if (ElementShadow* shadow = this->shadow())
1388 shadow->detach(context);
Torne (Richard Coles)521d96e2013-06-19 11:58:24 +01001389 ContainerNode::detach(context);
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001390}
1391
1392bool Element::pseudoStyleCacheIsInvalid(const RenderStyle* currentStyle, RenderStyle* newStyle)
1393{
1394 ASSERT(currentStyle == renderStyle());
1395 ASSERT(renderer());
1396
1397 if (!currentStyle)
1398 return false;
1399
1400 const PseudoStyleCache* pseudoStyleCache = currentStyle->cachedPseudoStyles();
1401 if (!pseudoStyleCache)
1402 return false;
1403
1404 size_t cacheSize = pseudoStyleCache->size();
1405 for (size_t i = 0; i < cacheSize; ++i) {
1406 RefPtr<RenderStyle> newPseudoStyle;
1407 PseudoId pseudoId = pseudoStyleCache->at(i)->styleType();
1408 if (pseudoId == FIRST_LINE || pseudoId == FIRST_LINE_INHERITED)
1409 newPseudoStyle = renderer()->uncachedFirstLineStyle(newStyle);
1410 else
1411 newPseudoStyle = renderer()->getUncachedPseudoStyle(PseudoStyleRequest(pseudoId), newStyle, newStyle);
1412 if (!newPseudoStyle)
1413 return true;
1414 if (*newPseudoStyle != *pseudoStyleCache->at(i)) {
1415 if (pseudoId < FIRST_INTERNAL_PSEUDOID)
1416 newStyle->setHasPseudoStyle(pseudoId);
1417 newStyle->addCachedPseudoStyle(newPseudoStyle);
1418 if (pseudoId == FIRST_LINE || pseudoId == FIRST_LINE_INHERITED) {
1419 // FIXME: We should do an actual diff to determine whether a repaint vs. layout
1420 // is needed, but for now just assume a layout will be required. The diff code
1421 // in RenderObject::setStyle would need to be factored out so that it could be reused.
1422 renderer()->setNeedsLayoutAndPrefWidthsRecalc();
1423 }
1424 return true;
1425 }
1426 }
1427 return false;
1428}
1429
Torne (Richard Coles)521d96e2013-06-19 11:58:24 +01001430PassRefPtr<RenderStyle> Element::styleForRenderer()
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001431{
1432 if (hasCustomStyleCallbacks()) {
1433 if (RefPtr<RenderStyle> style = customStyleForRenderer())
1434 return style.release();
1435 }
1436
Torne (Richard Coles)521d96e2013-06-19 11:58:24 +01001437 return originalStyleForRenderer();
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001438}
1439
Torne (Richard Coles)521d96e2013-06-19 11:58:24 +01001440PassRefPtr<RenderStyle> Element::originalStyleForRenderer()
Torne (Richard Coles)5267f702013-06-11 10:57:24 +01001441{
Torne (Richard Coles)8abfc582013-09-12 12:10:38 +01001442 return document().styleResolver()->styleForElement(this);
Torne (Richard Coles)5267f702013-06-11 10:57:24 +01001443}
1444
Torne (Richard Coles)8abfc582013-09-12 12:10:38 +01001445bool Element::recalcStyle(StyleRecalcChange change)
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001446{
Torne (Richard Coles)8abfc582013-09-12 12:10:38 +01001447 ASSERT(document().inStyleRecalc());
Torne (Richard Coles)93ac45c2013-05-29 14:40:20 +01001448
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001449 if (hasCustomStyleCallbacks())
1450 willRecalcStyle(change);
1451
Ben Murdoch3c9e4ae2013-08-12 14:20:44 +01001452 if (hasRareData() && (change > NoChange || needsStyleRecalc())) {
1453 ElementRareData* data = elementRareData();
1454 data->resetStyleState();
1455 data->clearComputedStyle();
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001456 }
Ben Murdoch3c9e4ae2013-08-12 14:20:44 +01001457
Torne (Richard Coles)c0e19a62013-08-30 15:15:11 +01001458 // Active InsertionPoints have no renderers so they never need to go through a recalc.
1459 if ((change >= Inherit || needsStyleRecalc()) && parentRenderStyle() && !isActiveInsertionPoint(this))
1460 change = recalcOwnStyle(change);
Torne (Richard Coles)521d96e2013-06-19 11:58:24 +01001461
Torne (Richard Coles)c0e19a62013-08-30 15:15:11 +01001462 // If we reattached we don't need to recalc the style of our descendants anymore.
1463 if (change < Reattach)
1464 recalcChildStyle(change);
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001465
Torne (Richard Coles)c0e19a62013-08-30 15:15:11 +01001466 clearNeedsStyleRecalc();
1467 clearChildNeedsStyleRecalc();
Ben Murdoch591b9582013-07-10 11:41:44 +01001468
Torne (Richard Coles)c0e19a62013-08-30 15:15:11 +01001469 if (hasCustomStyleCallbacks())
1470 didRecalcStyle(change);
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001471
Torne (Richard Coles)c0e19a62013-08-30 15:15:11 +01001472 return change == Reattach;
1473}
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001474
Torne (Richard Coles)8abfc582013-09-12 12:10:38 +01001475StyleRecalcChange Element::recalcOwnStyle(StyleRecalcChange change)
Torne (Richard Coles)c0e19a62013-08-30 15:15:11 +01001476{
Torne (Richard Coles)8abfc582013-09-12 12:10:38 +01001477 ASSERT(document().inStyleRecalc());
Torne (Richard Coles)c0e19a62013-08-30 15:15:11 +01001478
1479 CSSAnimationUpdateScope cssAnimationUpdateScope(this);
1480 RefPtr<RenderStyle> oldStyle = renderStyle();
1481 RefPtr<RenderStyle> newStyle = styleForRenderer();
Torne (Richard Coles)8abfc582013-09-12 12:10:38 +01001482 StyleRecalcChange localChange = RenderStyle::compare(oldStyle.get(), newStyle.get());
Torne (Richard Coles)c0e19a62013-08-30 15:15:11 +01001483
1484 if (localChange == Reattach) {
1485 AttachContext reattachContext;
1486 reattachContext.resolvedStyle = newStyle.get();
1487 reattach(reattachContext);
1488 return Reattach;
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001489 }
Torne (Richard Coles)c0e19a62013-08-30 15:15:11 +01001490
1491 InspectorInstrumentation::didRecalculateStyleForElement(this);
1492
1493 if (RenderObject* renderer = this->renderer()) {
1494 if (localChange != NoChange || pseudoStyleCacheIsInvalid(oldStyle.get(), newStyle.get()) || (change == Force && renderer->requiresForcedStyleRecalcPropagation()) || shouldNotifyRendererWithIdenticalStyles()) {
1495 renderer->setAnimatableStyle(newStyle.get());
1496 } else if (needsStyleRecalc()) {
1497 // Although no change occurred, we use the new style so that the cousin style sharing code won't get
1498 // fooled into believing this style is the same.
1499 renderer->setStyleInternal(newStyle.get());
1500 }
1501 }
1502
1503 // If "rem" units are used anywhere in the document, and if the document element's font size changes, then go ahead and force font updating
1504 // all the way down the tree. This is simpler than having to maintain a cache of objects (and such font size changes should be rare anyway).
Torne (Richard Coles)8abfc582013-09-12 12:10:38 +01001505 if (document().styleSheetCollections()->usesRemUnits() && document().documentElement() == this && oldStyle && newStyle && oldStyle->fontSize() != newStyle->fontSize()) {
Torne (Richard Coles)c0e19a62013-08-30 15:15:11 +01001506 // Cached RenderStyles may depend on the re units.
Torne (Richard Coles)8abfc582013-09-12 12:10:38 +01001507 document().styleResolver()->invalidateMatchedPropertiesCache();
Torne (Richard Coles)c0e19a62013-08-30 15:15:11 +01001508 return Force;
1509 }
1510
1511 if (styleChangeType() >= SubtreeStyleChange)
1512 return Force;
1513
1514 return max(localChange, change);
1515}
1516
Torne (Richard Coles)8abfc582013-09-12 12:10:38 +01001517void Element::recalcChildStyle(StyleRecalcChange change)
Torne (Richard Coles)c0e19a62013-08-30 15:15:11 +01001518{
Torne (Richard Coles)8abfc582013-09-12 12:10:38 +01001519 ASSERT(document().inStyleRecalc());
Torne (Richard Coles)c0e19a62013-08-30 15:15:11 +01001520
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001521 StyleResolverParentPusher parentPusher(this);
1522
Torne (Richard Coles)f5e4ad52013-08-05 13:57:57 +01001523 for (ShadowRoot* root = youngestShadowRoot(); root; root = root->olderShadowRoot()) {
1524 if (shouldRecalcStyle(change, root)) {
1525 parentPusher.push();
1526 root->recalcStyle(change);
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001527 }
1528 }
1529
1530 if (shouldRecalcStyle(change, this))
1531 updatePseudoElement(BEFORE, change);
1532
1533 // FIXME: This check is good enough for :hover + foo, but it is not good enough for :hover + foo + bar.
1534 // For now we will just worry about the common case, since it's a lot trickier to get the second case right
1535 // without doing way too much re-resolution.
Torne (Richard Coles)c0e19a62013-08-30 15:15:11 +01001536 bool hasDirectAdjacentRules = childrenAffectedByDirectAdjacentRules();
1537 bool hasIndirectAdjacentRules = childrenAffectedByForwardPositionalRules();
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001538 bool forceCheckOfNextElementSibling = false;
1539 bool forceCheckOfAnyElementSibling = false;
Ben Murdoche69819b2013-07-17 14:56:49 +01001540 bool forceReattachOfAnyWhitespaceSibling = false;
1541 for (Node* child = firstChild(); child; child = child->nextSibling()) {
1542 bool didReattach = false;
1543
1544 if (child->renderer())
1545 forceReattachOfAnyWhitespaceSibling = false;
1546
1547 if (child->isTextNode()) {
1548 if (forceReattachOfAnyWhitespaceSibling && toText(child)->containsOnlyWhitespace())
1549 child->reattach();
1550 else
1551 didReattach = toText(child)->recalcTextStyle(change);
1552 } else if (child->isElementNode()) {
1553 Element* element = toElement(child);
1554
Torne (Richard Coles)e1f1df52013-08-23 16:39:30 +01001555 bool childRulesChanged = element->needsStyleRecalc() && element->styleChangeType() >= SubtreeStyleChange;
1556
Ben Murdoche69819b2013-07-17 14:56:49 +01001557 if (forceCheckOfNextElementSibling || forceCheckOfAnyElementSibling)
1558 element->setNeedsStyleRecalc();
1559
Ben Murdoche69819b2013-07-17 14:56:49 +01001560 forceCheckOfNextElementSibling = childRulesChanged && hasDirectAdjacentRules;
1561 forceCheckOfAnyElementSibling = forceCheckOfAnyElementSibling || (childRulesChanged && hasIndirectAdjacentRules);
1562
1563 if (shouldRecalcStyle(change, element)) {
1564 parentPusher.push();
1565 didReattach = element->recalcStyle(change);
Torne (Richard Coles)8abfc582013-09-12 12:10:38 +01001566 } else if (document().styleResolver()->supportsStyleSharing(element)) {
1567 document().styleResolver()->addToStyleSharingList(element);
Ben Murdoche69819b2013-07-17 14:56:49 +01001568 }
Ben Murdoch591b9582013-07-10 11:41:44 +01001569 }
Ben Murdoche69819b2013-07-17 14:56:49 +01001570
1571 forceReattachOfAnyWhitespaceSibling = didReattach || forceReattachOfAnyWhitespaceSibling;
Torne (Richard Coles)5267f702013-06-11 10:57:24 +01001572 }
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001573
Torne (Richard Coles)e1f1df52013-08-23 16:39:30 +01001574 if (shouldRecalcStyle(change, this)) {
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001575 updatePseudoElement(AFTER, change);
Torne (Richard Coles)e1f1df52013-08-23 16:39:30 +01001576 updatePseudoElement(BACKDROP, change);
1577 }
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001578}
1579
1580ElementShadow* Element::shadow() const
1581{
1582 return hasRareData() ? elementRareData()->shadow() : 0;
1583}
1584
1585ElementShadow* Element::ensureShadow()
1586{
1587 return ensureElementRareData()->ensureShadow();
1588}
1589
1590void Element::didAffectSelector(AffectedSelectorMask mask)
1591{
1592 setNeedsStyleRecalc();
1593 if (ElementShadow* elementShadow = shadowOfParentForDistribution(this))
1594 elementShadow->didAffectSelector(mask);
1595}
1596
Ben Murdochdf957042013-08-06 11:01:27 +01001597PassRefPtr<ShadowRoot> Element::createShadowRoot(ExceptionState& es)
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001598{
1599 if (alwaysCreateUserAgentShadowRoot())
1600 ensureUserAgentShadowRoot();
1601
1602 if (RuntimeEnabledFeatures::authorShadowDOMForAnyElementEnabled())
1603 return ensureShadow()->addShadowRoot(this, ShadowRoot::AuthorShadowRoot);
1604
1605 // Since some elements recreates shadow root dynamically, multiple shadow
1606 // subtrees won't work well in that element. Until they are fixed, we disable
1607 // adding author shadow root for them.
1608 if (!areAuthorShadowsAllowed()) {
Ben Murdochdf957042013-08-06 11:01:27 +01001609 es.throwDOMException(HierarchyRequestError);
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001610 return 0;
1611 }
1612 return ensureShadow()->addShadowRoot(this, ShadowRoot::AuthorShadowRoot);
1613}
1614
1615ShadowRoot* Element::shadowRoot() const
1616{
1617 ElementShadow* elementShadow = shadow();
1618 if (!elementShadow)
1619 return 0;
1620 ShadowRoot* shadowRoot = elementShadow->youngestShadowRoot();
1621 if (shadowRoot->type() == ShadowRoot::AuthorShadowRoot)
1622 return shadowRoot;
1623 return 0;
1624}
1625
Torne (Richard Coles)8abfc582013-09-12 12:10:38 +01001626void Element::didAddShadowRoot(ShadowRoot&)
1627{
1628}
1629
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001630ShadowRoot* Element::userAgentShadowRoot() const
1631{
1632 if (ElementShadow* elementShadow = shadow()) {
1633 if (ShadowRoot* shadowRoot = elementShadow->oldestShadowRoot()) {
1634 ASSERT(shadowRoot->type() == ShadowRoot::UserAgentShadowRoot);
1635 return shadowRoot;
1636 }
1637 }
1638
1639 return 0;
1640}
1641
1642ShadowRoot* Element::ensureUserAgentShadowRoot()
1643{
1644 if (ShadowRoot* shadowRoot = userAgentShadowRoot())
1645 return shadowRoot;
1646 ShadowRoot* shadowRoot = ensureShadow()->addShadowRoot(this, ShadowRoot::UserAgentShadowRoot);
1647 didAddUserAgentShadowRoot(shadowRoot);
1648 return shadowRoot;
1649}
1650
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001651bool Element::childTypeAllowed(NodeType type) const
1652{
1653 switch (type) {
1654 case ELEMENT_NODE:
1655 case TEXT_NODE:
1656 case COMMENT_NODE:
1657 case PROCESSING_INSTRUCTION_NODE:
1658 case CDATA_SECTION_NODE:
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001659 return true;
1660 default:
1661 break;
1662 }
1663 return false;
1664}
1665
Ben Murdoch83750172013-07-24 10:36:59 +01001666static void inline checkForEmptyStyleChange(Element* element, RenderStyle* style)
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001667{
1668 if (!style && !element->styleAffectedByEmpty())
1669 return;
1670
1671 if (!style || (element->styleAffectedByEmpty() && (!style->emptyState() || element->hasChildNodes())))
1672 element->setNeedsStyleRecalc();
1673}
1674
1675static void checkForSiblingStyleChanges(Element* e, RenderStyle* style, bool finishedParsingCallback,
1676 Node* beforeChange, Node* afterChange, int childCountDelta)
1677{
Torne (Richard Coles)8abfc582013-09-12 12:10:38 +01001678 if (!e->attached() || e->document().hasPendingForcedStyleRecalc() || e->styleChangeType() >= SubtreeStyleChange)
Ben Murdoch83750172013-07-24 10:36:59 +01001679 return;
1680
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001681 // :empty selector.
1682 checkForEmptyStyleChange(e, style);
Ben Murdoch591b9582013-07-10 11:41:44 +01001683
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001684 if (!style || (e->needsStyleRecalc() && e->childrenAffectedByPositionalRules()))
1685 return;
1686
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001687 // Forward positional selectors include the ~ selector, nth-child, nth-of-type, first-of-type and only-of-type.
1688 // Backward positional selectors include nth-last-child, nth-last-of-type, last-of-type and only-of-type.
1689 // We have to invalidate everything following the insertion point in the forward case, and everything before the insertion point in the
1690 // backward case.
1691 // |afterChange| is 0 in the parser callback case, so we won't do any work for the forward case if we don't have to.
1692 // For performance reasons we just mark the parent node as changed, since we don't want to make childrenChanged O(n^2) by crawling all our kids
Ben Murdoch83750172013-07-24 10:36:59 +01001693 // here. recalcStyle will then force a walk of the children when it sees that this has happened.
1694 if ((e->childrenAffectedByForwardPositionalRules() && afterChange) || (e->childrenAffectedByBackwardPositionalRules() && beforeChange)) {
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001695 e->setNeedsStyleRecalc();
Ben Murdoch83750172013-07-24 10:36:59 +01001696 return;
1697 }
1698
1699 // :first-child. In the parser callback case, we don't have to check anything, since we were right the first time.
1700 // In the DOM case, we only need to do something if |afterChange| is not 0.
1701 // |afterChange| is 0 in the parser case, so it works out that we'll skip this block.
1702 if (e->childrenAffectedByFirstChildRules() && afterChange) {
1703 // Find our new first child.
1704 Node* newFirstChild = e->firstElementChild();
1705 RenderStyle* newFirstChildStyle = newFirstChild ? newFirstChild->renderStyle() : 0;
1706
1707 // Find the first element node following |afterChange|
1708 Node* firstElementAfterInsertion = afterChange->isElementNode() ? afterChange : afterChange->nextElementSibling();
1709 RenderStyle* firstElementAfterInsertionStyle = firstElementAfterInsertion ? firstElementAfterInsertion->renderStyle() : 0;
1710
1711 // This is the insert/append case.
1712 if (newFirstChild != firstElementAfterInsertion && firstElementAfterInsertionStyle && firstElementAfterInsertionStyle->firstChildState())
1713 firstElementAfterInsertion->setNeedsStyleRecalc();
1714
1715 // We also have to handle node removal.
1716 if (childCountDelta < 0 && newFirstChild == firstElementAfterInsertion && newFirstChild && (!newFirstChildStyle || !newFirstChildStyle->firstChildState()))
1717 newFirstChild->setNeedsStyleRecalc();
1718 }
1719
1720 // :last-child. In the parser callback case, we don't have to check anything, since we were right the first time.
1721 // In the DOM case, we only need to do something if |afterChange| is not 0.
1722 if (e->childrenAffectedByLastChildRules() && beforeChange) {
1723 // Find our new last child.
1724 Node* newLastChild = e->lastElementChild();
1725 RenderStyle* newLastChildStyle = newLastChild ? newLastChild->renderStyle() : 0;
1726
1727 // Find the last element node going backwards from |beforeChange|
1728 Node* lastElementBeforeInsertion = beforeChange->isElementNode() ? beforeChange : beforeChange->previousElementSibling();
1729 RenderStyle* lastElementBeforeInsertionStyle = lastElementBeforeInsertion ? lastElementBeforeInsertion->renderStyle() : 0;
1730
1731 if (newLastChild != lastElementBeforeInsertion && lastElementBeforeInsertionStyle && lastElementBeforeInsertionStyle->lastChildState())
1732 lastElementBeforeInsertion->setNeedsStyleRecalc();
1733
1734 // We also have to handle node removal. The parser callback case is similar to node removal as well in that we need to change the last child
1735 // to match now.
1736 if ((childCountDelta < 0 || finishedParsingCallback) && newLastChild == lastElementBeforeInsertion && newLastChild && (!newLastChildStyle || !newLastChildStyle->lastChildState()))
1737 newLastChild->setNeedsStyleRecalc();
1738 }
1739
1740 // The + selector. We need to invalidate the first element following the insertion point. It is the only possible element
1741 // that could be affected by this DOM change.
1742 if (e->childrenAffectedByDirectAdjacentRules() && afterChange) {
1743 if (Node* firstElementAfterInsertion = afterChange->nextElementSibling())
1744 firstElementAfterInsertion->setNeedsStyleRecalc();
1745 }
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001746}
1747
1748void Element::childrenChanged(bool changedByParser, Node* beforeChange, Node* afterChange, int childCountDelta)
1749{
1750 ContainerNode::childrenChanged(changedByParser, beforeChange, afterChange, childCountDelta);
1751 if (changedByParser)
1752 checkForEmptyStyleChange(this, renderStyle());
1753 else
1754 checkForSiblingStyleChanges(this, renderStyle(), false, beforeChange, afterChange, childCountDelta);
1755
Ben Murdoch83750172013-07-24 10:36:59 +01001756 if (ElementShadow* shadow = this->shadow())
Torne (Richard Coles)f5e4ad52013-08-05 13:57:57 +01001757 shadow->setNeedsDistributionRecalc();
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001758}
1759
1760void Element::removeAllEventListeners()
1761{
1762 ContainerNode::removeAllEventListeners();
1763 if (ElementShadow* shadow = this->shadow())
1764 shadow->removeAllEventListeners();
1765}
1766
1767void Element::beginParsingChildren()
1768{
1769 clearIsParsingChildrenFinished();
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001770}
1771
1772void Element::finishParsingChildren()
1773{
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001774 setIsParsingChildrenFinished();
1775 checkForSiblingStyleChanges(this, renderStyle(), true, lastChild(), 0, 0);
Torne (Richard Coles)e1f1df52013-08-23 16:39:30 +01001776 if (isCustomElement())
1777 CustomElement::didFinishParsingChildren(this);
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001778}
1779
1780#ifndef NDEBUG
1781void Element::formatForDebugger(char* buffer, unsigned length) const
1782{
1783 StringBuilder result;
1784 String s;
1785
1786 result.append(nodeName());
1787
1788 s = getIdAttribute();
1789 if (s.length() > 0) {
1790 if (result.length() > 0)
1791 result.appendLiteral("; ");
1792 result.appendLiteral("id=");
1793 result.append(s);
1794 }
1795
1796 s = getAttribute(classAttr);
1797 if (s.length() > 0) {
1798 if (result.length() > 0)
1799 result.appendLiteral("; ");
1800 result.appendLiteral("class=");
1801 result.append(s);
1802 }
1803
1804 strncpy(buffer, result.toString().utf8().data(), length - 1);
1805}
1806#endif
1807
1808const Vector<RefPtr<Attr> >& Element::attrNodeList()
1809{
1810 ASSERT(hasSyntheticAttrChildNodes());
1811 return *attrNodeListForElement(this);
1812}
1813
Ben Murdochdf957042013-08-06 11:01:27 +01001814PassRefPtr<Attr> Element::setAttributeNode(Attr* attrNode, ExceptionState& es)
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001815{
1816 if (!attrNode) {
Ben Murdochdf957042013-08-06 11:01:27 +01001817 es.throwDOMException(TypeMismatchError);
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001818 return 0;
1819 }
1820
1821 RefPtr<Attr> oldAttrNode = attrIfExists(attrNode->qualifiedName());
1822 if (oldAttrNode.get() == attrNode)
1823 return attrNode; // This Attr is already attached to the element.
1824
Ben Murdoche69819b2013-07-17 14:56:49 +01001825 // InUseAttributeError: Raised if node is an Attr that is already an attribute of another Element object.
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001826 // The DOM user must explicitly clone Attr nodes to re-use them in other elements.
1827 if (attrNode->ownerElement()) {
Ben Murdochdf957042013-08-06 11:01:27 +01001828 es.throwDOMException(InUseAttributeError);
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001829 return 0;
1830 }
1831
1832 synchronizeAllAttributes();
1833 UniqueElementData* elementData = ensureUniqueElementData();
1834
Torne (Richard Coles)e1f1df52013-08-23 16:39:30 +01001835 size_t index = elementData->getAttributeItemIndex(attrNode->qualifiedName(), shouldIgnoreAttributeCase(this));
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001836 if (index != notFound) {
1837 if (oldAttrNode)
1838 detachAttrNodeFromElementWithValue(oldAttrNode.get(), elementData->attributeItem(index)->value());
1839 else
1840 oldAttrNode = Attr::create(document(), attrNode->qualifiedName(), elementData->attributeItem(index)->value());
1841 }
1842
1843 setAttributeInternal(index, attrNode->qualifiedName(), attrNode->value(), NotInSynchronizationOfLazyAttribute);
1844
1845 attrNode->attachToElement(this);
Torne (Richard Coles)8abfc582013-09-12 12:10:38 +01001846 treeScope().adoptIfNeeded(attrNode);
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001847 ensureAttrNodeListForElement(this)->append(attrNode);
1848
1849 return oldAttrNode.release();
1850}
1851
Ben Murdochdf957042013-08-06 11:01:27 +01001852PassRefPtr<Attr> Element::setAttributeNodeNS(Attr* attr, ExceptionState& es)
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001853{
Ben Murdochdf957042013-08-06 11:01:27 +01001854 return setAttributeNode(attr, es);
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001855}
1856
Ben Murdochdf957042013-08-06 11:01:27 +01001857PassRefPtr<Attr> Element::removeAttributeNode(Attr* attr, ExceptionState& es)
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001858{
1859 if (!attr) {
Ben Murdochdf957042013-08-06 11:01:27 +01001860 es.throwDOMException(TypeMismatchError);
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001861 return 0;
1862 }
1863 if (attr->ownerElement() != this) {
Ben Murdochdf957042013-08-06 11:01:27 +01001864 es.throwDOMException(NotFoundError);
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001865 return 0;
1866 }
1867
Torne (Richard Coles)8abfc582013-09-12 12:10:38 +01001868 ASSERT(&document() == &attr->document());
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001869
1870 synchronizeAttribute(attr->qualifiedName());
1871
Torne (Richard Coles)e5249552013-05-15 11:35:13 +01001872 size_t index = elementData()->getAttrIndex(attr);
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001873 if (index == notFound) {
Ben Murdochdf957042013-08-06 11:01:27 +01001874 es.throwDOMException(NotFoundError);
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001875 return 0;
1876 }
1877
Torne (Richard Coles)e5249552013-05-15 11:35:13 +01001878 RefPtr<Attr> guard(attr);
1879 detachAttrNodeAtIndex(attr, index);
1880 return guard.release();
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001881}
1882
Ben Murdochdf957042013-08-06 11:01:27 +01001883bool Element::parseAttributeName(QualifiedName& out, const AtomicString& namespaceURI, const AtomicString& qualifiedName, ExceptionState& es)
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001884{
1885 String prefix, localName;
Ben Murdochdf957042013-08-06 11:01:27 +01001886 if (!Document::parseQualifiedName(qualifiedName, prefix, localName, es))
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001887 return false;
Ben Murdochdf957042013-08-06 11:01:27 +01001888 ASSERT(!es.hadException());
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001889
1890 QualifiedName qName(prefix, localName, namespaceURI);
1891
1892 if (!Document::hasValidNamespaceForAttributes(qName)) {
Ben Murdochdf957042013-08-06 11:01:27 +01001893 es.throwDOMException(NamespaceError);
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001894 return false;
1895 }
1896
1897 out = qName;
1898 return true;
1899}
1900
Ben Murdochdf957042013-08-06 11:01:27 +01001901void Element::setAttributeNS(const AtomicString& namespaceURI, const AtomicString& qualifiedName, const AtomicString& value, ExceptionState& es)
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001902{
1903 QualifiedName parsedName = anyName;
Ben Murdochdf957042013-08-06 11:01:27 +01001904 if (!parseAttributeName(parsedName, namespaceURI, qualifiedName, es))
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001905 return;
1906 setAttribute(parsedName, value);
1907}
1908
1909void Element::removeAttributeInternal(size_t index, SynchronizationOfLazyAttribute inSynchronizationOfLazyAttribute)
1910{
1911 ASSERT_WITH_SECURITY_IMPLICATION(index < attributeCount());
1912
1913 UniqueElementData* elementData = ensureUniqueElementData();
1914
1915 QualifiedName name = elementData->attributeItem(index)->name();
1916 AtomicString valueBeingRemoved = elementData->attributeItem(index)->value();
1917
1918 if (!inSynchronizationOfLazyAttribute) {
1919 if (!valueBeingRemoved.isNull())
1920 willModifyAttribute(name, valueBeingRemoved, nullAtom);
1921 }
1922
1923 if (RefPtr<Attr> attrNode = attrIfExists(name))
1924 detachAttrNodeFromElementWithValue(attrNode.get(), elementData->attributeItem(index)->value());
1925
1926 elementData->removeAttribute(index);
1927
1928 if (!inSynchronizationOfLazyAttribute)
1929 didRemoveAttribute(name);
1930}
1931
1932void Element::addAttributeInternal(const QualifiedName& name, const AtomicString& value, SynchronizationOfLazyAttribute inSynchronizationOfLazyAttribute)
1933{
1934 if (!inSynchronizationOfLazyAttribute)
1935 willModifyAttribute(name, nullAtom, value);
1936 ensureUniqueElementData()->addAttribute(name, value);
1937 if (!inSynchronizationOfLazyAttribute)
1938 didAddAttribute(name, value);
1939}
1940
1941void Element::removeAttribute(const AtomicString& name)
1942{
1943 if (!elementData())
1944 return;
1945
1946 AtomicString localName = shouldIgnoreAttributeCase(this) ? name.lower() : name;
1947 size_t index = elementData()->getAttributeItemIndex(localName, false);
1948 if (index == notFound) {
1949 if (UNLIKELY(localName == styleAttr) && elementData()->m_styleAttributeIsDirty && isStyledElement())
Ben Murdoch591b9582013-07-10 11:41:44 +01001950 removeAllInlineStyleProperties();
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001951 return;
1952 }
1953
1954 removeAttributeInternal(index, NotInSynchronizationOfLazyAttribute);
1955}
1956
1957void Element::removeAttributeNS(const AtomicString& namespaceURI, const AtomicString& localName)
1958{
1959 removeAttribute(QualifiedName(nullAtom, localName, namespaceURI));
1960}
1961
1962PassRefPtr<Attr> Element::getAttributeNode(const AtomicString& localName)
1963{
1964 if (!elementData())
1965 return 0;
1966 synchronizeAttribute(localName);
1967 const Attribute* attribute = elementData()->getAttributeItem(localName, shouldIgnoreAttributeCase(this));
1968 if (!attribute)
1969 return 0;
1970 return ensureAttr(attribute->name());
1971}
1972
1973PassRefPtr<Attr> Element::getAttributeNodeNS(const AtomicString& namespaceURI, const AtomicString& localName)
1974{
1975 if (!elementData())
1976 return 0;
1977 QualifiedName qName(nullAtom, localName, namespaceURI);
1978 synchronizeAttribute(qName);
1979 const Attribute* attribute = elementData()->getAttributeItem(qName);
1980 if (!attribute)
1981 return 0;
1982 return ensureAttr(attribute->name());
1983}
1984
1985bool Element::hasAttribute(const AtomicString& localName) const
1986{
1987 if (!elementData())
1988 return false;
1989 synchronizeAttribute(localName);
1990 return elementData()->getAttributeItem(shouldIgnoreAttributeCase(this) ? localName.lower() : localName, false);
1991}
1992
1993bool Element::hasAttributeNS(const AtomicString& namespaceURI, const AtomicString& localName) const
1994{
1995 if (!elementData())
1996 return false;
1997 QualifiedName qName(nullAtom, localName, namespaceURI);
1998 synchronizeAttribute(qName);
1999 return elementData()->getAttributeItem(qName);
2000}
2001
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002002void Element::focus(bool restorePreviousSelection, FocusDirection direction)
2003{
2004 if (!inDocument())
2005 return;
2006
Torne (Richard Coles)8abfc582013-09-12 12:10:38 +01002007 Document& doc = document();
2008 if (doc.focusedElement() == this)
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002009 return;
2010
2011 // If the stylesheets have already been loaded we can reliably check isFocusable.
2012 // If not, we continue and set the focused node on the focus controller below so
Ben Murdoch591b9582013-07-10 11:41:44 +01002013 // that it can be updated soon after attach.
Torne (Richard Coles)8abfc582013-09-12 12:10:38 +01002014 if (doc.haveStylesheetsLoaded()) {
2015 doc.updateLayoutIgnorePendingStylesheets();
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002016 if (!isFocusable())
2017 return;
2018 }
2019
2020 if (!supportsFocus())
2021 return;
2022
2023 RefPtr<Node> protect;
Torne (Richard Coles)8abfc582013-09-12 12:10:38 +01002024 if (Page* page = doc.page()) {
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002025 // Focus and change event handlers can cause us to lose our last ref.
2026 // If a focus event handler changes the focus to a different node it
2027 // does not make sense to continue and update appearence.
2028 protect = this;
Torne (Richard Coles)8abfc582013-09-12 12:10:38 +01002029 if (!page->focusController().setFocusedElement(this, doc.frame(), direction))
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002030 return;
2031 }
2032
2033 // Setting the focused node above might have invalidated the layout due to scripts.
Torne (Richard Coles)8abfc582013-09-12 12:10:38 +01002034 doc.updateLayoutIgnorePendingStylesheets();
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002035
2036 if (!isFocusable()) {
2037 ensureElementRareData()->setNeedsFocusAppearanceUpdateSoonAfterAttach(true);
2038 return;
2039 }
Ben Murdoch591b9582013-07-10 11:41:44 +01002040
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002041 cancelFocusAppearanceUpdate();
2042 updateFocusAppearance(restorePreviousSelection);
2043}
2044
2045void Element::updateFocusAppearance(bool /*restorePreviousSelection*/)
2046{
2047 if (isRootEditableElement()) {
Torne (Richard Coles)8abfc582013-09-12 12:10:38 +01002048 Frame* frame = document().frame();
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002049 if (!frame)
2050 return;
Ben Murdoch591b9582013-07-10 11:41:44 +01002051
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002052 // When focusing an editable element in an iframe, don't reset the selection if it already contains a selection.
Torne (Richard Coles)8abfc582013-09-12 12:10:38 +01002053 if (this == frame->selection().rootEditableElement())
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002054 return;
2055
2056 // FIXME: We should restore the previous selection if there is one.
2057 VisibleSelection newSelection = VisibleSelection(firstPositionInOrBeforeNode(this), DOWNSTREAM);
Ben Murdoch591b9582013-07-10 11:41:44 +01002058
Torne (Richard Coles)8abfc582013-09-12 12:10:38 +01002059 if (frame->selection().shouldChangeSelection(newSelection)) {
2060 frame->selection().setSelection(newSelection);
2061 frame->selection().revealSelection();
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002062 }
2063 } else if (renderer() && !renderer()->isWidget())
2064 renderer()->scrollRectToVisible(boundingBox());
2065}
2066
2067void Element::blur()
2068{
2069 cancelFocusAppearanceUpdate();
Torne (Richard Coles)8abfc582013-09-12 12:10:38 +01002070 if (treeScope().adjustedFocusedElement() == this) {
2071 Document& doc = document();
2072 if (doc.page())
2073 doc.page()->focusController().setFocusedElement(0, doc.frame());
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002074 else
Torne (Richard Coles)8abfc582013-09-12 12:10:38 +01002075 doc.setFocusedElement(0);
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002076 }
2077}
2078
Ben Murdochdf957042013-08-06 11:01:27 +01002079bool Element::isFocusable() const
2080{
2081 return inDocument() && supportsFocus() && !isInert() && rendererIsFocusable();
2082}
2083
Torne (Richard Coles)f5e4ad52013-08-05 13:57:57 +01002084bool Element::isKeyboardFocusable() const
2085{
2086 return isFocusable() && tabIndex() >= 0;
2087}
2088
2089bool Element::isMouseFocusable() const
2090{
2091 return isFocusable();
2092}
2093
Ben Murdoch02772c62013-07-26 10:21:05 +01002094void Element::dispatchFocusEvent(Element* oldFocusedElement, FocusDirection)
2095{
Torne (Richard Coles)8abfc582013-09-12 12:10:38 +01002096 RefPtr<FocusEvent> event = FocusEvent::create(eventNames().focusEvent, false, false, document().defaultView(), 0, oldFocusedElement);
Ben Murdoch02772c62013-07-26 10:21:05 +01002097 EventDispatcher::dispatchEvent(this, FocusEventDispatchMediator::create(event.release()));
2098}
2099
2100void Element::dispatchBlurEvent(Element* newFocusedElement)
2101{
Torne (Richard Coles)8abfc582013-09-12 12:10:38 +01002102 RefPtr<FocusEvent> event = FocusEvent::create(eventNames().blurEvent, false, false, document().defaultView(), 0, newFocusedElement);
Ben Murdoch02772c62013-07-26 10:21:05 +01002103 EventDispatcher::dispatchEvent(this, BlurEventDispatchMediator::create(event.release()));
2104}
2105
2106void Element::dispatchFocusInEvent(const AtomicString& eventType, Element* oldFocusedElement)
2107{
2108 ASSERT(!NoEventDispatchAssertion::isEventDispatchForbidden());
2109 ASSERT(eventType == eventNames().focusinEvent || eventType == eventNames().DOMFocusInEvent);
Torne (Richard Coles)8abfc582013-09-12 12:10:38 +01002110 dispatchScopedEventDispatchMediator(FocusInEventDispatchMediator::create(FocusEvent::create(eventType, true, false, document().defaultView(), 0, oldFocusedElement)));
Ben Murdoch02772c62013-07-26 10:21:05 +01002111}
2112
2113void Element::dispatchFocusOutEvent(const AtomicString& eventType, Element* newFocusedElement)
2114{
2115 ASSERT(!NoEventDispatchAssertion::isEventDispatchForbidden());
2116 ASSERT(eventType == eventNames().focusoutEvent || eventType == eventNames().DOMFocusOutEvent);
Torne (Richard Coles)8abfc582013-09-12 12:10:38 +01002117 dispatchScopedEventDispatchMediator(FocusOutEventDispatchMediator::create(FocusEvent::create(eventType, true, false, document().defaultView(), 0, newFocusedElement)));
Ben Murdoch02772c62013-07-26 10:21:05 +01002118}
2119
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002120String Element::innerText()
2121{
2122 // We need to update layout, since plainText uses line boxes in the render tree.
Torne (Richard Coles)8abfc582013-09-12 12:10:38 +01002123 document().updateLayoutIgnorePendingStylesheets();
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002124
2125 if (!renderer())
2126 return textContent(true);
2127
2128 return plainText(rangeOfContents(const_cast<Element*>(this)).get());
2129}
2130
2131String Element::outerText()
2132{
2133 // Getting outerText is the same as getting innerText, only
2134 // setting is different. You would think this should get the plain
2135 // text for the outer range, but this is wrong, <br> for instance
2136 // would return different values for inner and outer text by such
2137 // a rule, but it doesn't in WinIE, and we want to match that.
2138 return innerText();
2139}
2140
Ben Murdoch591b9582013-07-10 11:41:44 +01002141String Element::textFromChildren()
2142{
2143 Text* firstTextNode = 0;
2144 bool foundMultipleTextNodes = false;
2145 unsigned totalLength = 0;
2146
2147 for (Node* child = firstChild(); child; child = child->nextSibling()) {
2148 if (!child->isTextNode())
2149 continue;
2150 Text* text = toText(child);
2151 if (!firstTextNode)
2152 firstTextNode = text;
2153 else
2154 foundMultipleTextNodes = true;
2155 unsigned length = text->data().length();
2156 if (length > std::numeric_limits<unsigned>::max() - totalLength)
2157 return emptyString();
2158 totalLength += length;
2159 }
2160
2161 if (!firstTextNode)
2162 return emptyString();
2163
2164 if (firstTextNode && !foundMultipleTextNodes) {
2165 firstTextNode->atomize();
2166 return firstTextNode->data();
2167 }
2168
2169 StringBuilder content;
2170 content.reserveCapacity(totalLength);
2171 for (Node* child = firstTextNode; child; child = child->nextSibling()) {
2172 if (!child->isTextNode())
2173 continue;
2174 content.append(toText(child)->data());
2175 }
2176
2177 ASSERT(content.length() == totalLength);
2178 return content.toString();
2179}
2180
Ben Murdoch3c9e4ae2013-08-12 14:20:44 +01002181// pseudo is used via shadowPseudoId.
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002182const AtomicString& Element::pseudo() const
2183{
2184 return getAttribute(pseudoAttr);
2185}
2186
Torne (Richard Coles)f5e4ad52013-08-05 13:57:57 +01002187const AtomicString& Element::part() const
2188{
2189 return getAttribute(partAttr);
2190}
2191
2192void Element::setPart(const AtomicString& value)
2193{
2194 setAttribute(partAttr, value);
2195}
2196
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002197LayoutSize Element::minimumSizeForResizing() const
2198{
2199 return hasRareData() ? elementRareData()->minimumSizeForResizing() : defaultMinimumSizeForResizing();
2200}
2201
2202void Element::setMinimumSizeForResizing(const LayoutSize& size)
2203{
2204 if (!hasRareData() && size == defaultMinimumSizeForResizing())
2205 return;
2206 ensureElementRareData()->setMinimumSizeForResizing(size);
2207}
2208
2209RenderStyle* Element::computedStyle(PseudoId pseudoElementSpecifier)
2210{
2211 if (PseudoElement* element = pseudoElement(pseudoElementSpecifier))
2212 return element->computedStyle();
2213
2214 // FIXME: Find and use the renderer from the pseudo element instead of the actual element so that the 'length'
2215 // properties, which are only known by the renderer because it did the layout, will be correct and so that the
2216 // values returned for the ":selection" pseudo-element will be correct.
2217 if (RenderStyle* usedStyle = renderStyle()) {
2218 if (pseudoElementSpecifier) {
2219 RenderStyle* cachedPseudoStyle = usedStyle->getCachedPseudoStyle(pseudoElementSpecifier);
2220 return cachedPseudoStyle ? cachedPseudoStyle : usedStyle;
2221 } else
2222 return usedStyle;
2223 }
2224
2225 if (!attached())
2226 // FIXME: Try to do better than this. Ensure that styleForElement() works for elements that are not in the
2227 // document tree and figure out when to destroy the computed style for such elements.
2228 return 0;
2229
2230 ElementRareData* data = ensureElementRareData();
2231 if (!data->computedStyle())
Torne (Richard Coles)8abfc582013-09-12 12:10:38 +01002232 data->setComputedStyle(document().styleForElementIgnoringPendingStylesheets(this));
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002233 return pseudoElementSpecifier ? data->computedStyle()->getCachedPseudoStyle(pseudoElementSpecifier) : data->computedStyle();
2234}
2235
2236void Element::setStyleAffectedByEmpty()
2237{
2238 ensureElementRareData()->setStyleAffectedByEmpty(true);
2239}
2240
2241void Element::setChildrenAffectedByHover(bool value)
2242{
2243 if (value || hasRareData())
2244 ensureElementRareData()->setChildrenAffectedByHover(value);
2245}
2246
2247void Element::setChildrenAffectedByActive(bool value)
2248{
2249 if (value || hasRareData())
2250 ensureElementRareData()->setChildrenAffectedByActive(value);
2251}
2252
2253void Element::setChildrenAffectedByDrag(bool value)
2254{
2255 if (value || hasRareData())
2256 ensureElementRareData()->setChildrenAffectedByDrag(value);
2257}
2258
2259void Element::setChildrenAffectedByFirstChildRules()
2260{
2261 ensureElementRareData()->setChildrenAffectedByFirstChildRules(true);
2262}
2263
2264void Element::setChildrenAffectedByLastChildRules()
2265{
2266 ensureElementRareData()->setChildrenAffectedByLastChildRules(true);
2267}
2268
2269void Element::setChildrenAffectedByDirectAdjacentRules()
2270{
2271 ensureElementRareData()->setChildrenAffectedByDirectAdjacentRules(true);
2272}
2273
2274void Element::setChildrenAffectedByForwardPositionalRules()
2275{
2276 ensureElementRareData()->setChildrenAffectedByForwardPositionalRules(true);
2277}
2278
2279void Element::setChildrenAffectedByBackwardPositionalRules()
2280{
2281 ensureElementRareData()->setChildrenAffectedByBackwardPositionalRules(true);
2282}
2283
2284void Element::setChildIndex(unsigned index)
2285{
2286 ElementRareData* rareData = ensureElementRareData();
2287 if (RenderStyle* style = renderStyle())
2288 style->setUnique();
2289 rareData->setChildIndex(index);
2290}
2291
2292bool Element::hasFlagsSetDuringStylingOfChildren() const
2293{
2294 if (!hasRareData())
2295 return false;
2296 return rareDataChildrenAffectedByHover()
2297 || rareDataChildrenAffectedByActive()
2298 || rareDataChildrenAffectedByDrag()
2299 || rareDataChildrenAffectedByFirstChildRules()
2300 || rareDataChildrenAffectedByLastChildRules()
2301 || rareDataChildrenAffectedByDirectAdjacentRules()
2302 || rareDataChildrenAffectedByForwardPositionalRules()
2303 || rareDataChildrenAffectedByBackwardPositionalRules();
2304}
2305
2306bool Element::rareDataStyleAffectedByEmpty() const
2307{
2308 ASSERT(hasRareData());
2309 return elementRareData()->styleAffectedByEmpty();
2310}
2311
2312bool Element::rareDataChildrenAffectedByHover() const
2313{
2314 ASSERT(hasRareData());
2315 return elementRareData()->childrenAffectedByHover();
2316}
2317
2318bool Element::rareDataChildrenAffectedByActive() const
2319{
2320 ASSERT(hasRareData());
2321 return elementRareData()->childrenAffectedByActive();
2322}
2323
2324bool Element::rareDataChildrenAffectedByDrag() const
2325{
2326 ASSERT(hasRareData());
2327 return elementRareData()->childrenAffectedByDrag();
2328}
2329
2330bool Element::rareDataChildrenAffectedByFirstChildRules() const
2331{
2332 ASSERT(hasRareData());
2333 return elementRareData()->childrenAffectedByFirstChildRules();
2334}
2335
2336bool Element::rareDataChildrenAffectedByLastChildRules() const
2337{
2338 ASSERT(hasRareData());
2339 return elementRareData()->childrenAffectedByLastChildRules();
2340}
2341
2342bool Element::rareDataChildrenAffectedByDirectAdjacentRules() const
2343{
2344 ASSERT(hasRareData());
2345 return elementRareData()->childrenAffectedByDirectAdjacentRules();
2346}
2347
2348bool Element::rareDataChildrenAffectedByForwardPositionalRules() const
2349{
2350 ASSERT(hasRareData());
2351 return elementRareData()->childrenAffectedByForwardPositionalRules();
2352}
2353
2354bool Element::rareDataChildrenAffectedByBackwardPositionalRules() const
2355{
2356 ASSERT(hasRareData());
2357 return elementRareData()->childrenAffectedByBackwardPositionalRules();
2358}
2359
2360unsigned Element::rareDataChildIndex() const
2361{
2362 ASSERT(hasRareData());
2363 return elementRareData()->childIndex();
2364}
2365
2366void Element::setIsInCanvasSubtree(bool isInCanvasSubtree)
2367{
2368 ensureElementRareData()->setIsInCanvasSubtree(isInCanvasSubtree);
2369}
2370
2371bool Element::isInCanvasSubtree() const
2372{
2373 return hasRareData() && elementRareData()->isInCanvasSubtree();
2374}
2375
Ben Murdoch591b9582013-07-10 11:41:44 +01002376void Element::setIsInsideRegion(bool value)
2377{
2378 if (value == isInsideRegion())
2379 return;
2380
2381 ensureElementRareData()->setIsInsideRegion(value);
2382}
2383
2384bool Element::isInsideRegion() const
2385{
2386 return hasRareData() ? elementRareData()->isInsideRegion() : false;
2387}
2388
2389void Element::setRegionOversetState(RegionOversetState state)
2390{
2391 ensureElementRareData()->setRegionOversetState(state);
2392}
2393
2394RegionOversetState Element::regionOversetState() const
2395{
2396 return hasRareData() ? elementRareData()->regionOversetState() : RegionUndefined;
2397}
2398
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002399AtomicString Element::computeInheritedLanguage() const
2400{
2401 const Node* n = this;
2402 AtomicString value;
2403 // The language property is inherited, so we iterate over the parents to find the first language.
2404 do {
2405 if (n->isElementNode()) {
2406 if (const ElementData* elementData = toElement(n)->elementData()) {
2407 // Spec: xml:lang takes precedence -- http://www.w3.org/TR/xhtml1/#C_7
2408 if (const Attribute* attribute = elementData->getAttributeItem(XMLNames::langAttr))
2409 value = attribute->value();
2410 else if (const Attribute* attribute = elementData->getAttributeItem(HTMLNames::langAttr))
2411 value = attribute->value();
2412 }
2413 } else if (n->isDocumentNode()) {
2414 // checking the MIME content-language
2415 value = toDocument(n)->contentLanguage();
2416 }
2417
2418 n = n->parentNode();
2419 } while (n && value.isNull());
2420
2421 return value;
2422}
2423
2424Locale& Element::locale() const
2425{
Torne (Richard Coles)8abfc582013-09-12 12:10:38 +01002426 return document().getCachedLocale(computeInheritedLanguage());
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002427}
2428
2429void Element::cancelFocusAppearanceUpdate()
2430{
2431 if (hasRareData())
2432 elementRareData()->setNeedsFocusAppearanceUpdateSoonAfterAttach(false);
Torne (Richard Coles)8abfc582013-09-12 12:10:38 +01002433 if (document().focusedElement() == this)
2434 document().cancelFocusAppearanceUpdate();
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002435}
2436
2437void Element::normalizeAttributes()
2438{
2439 if (!hasAttributes())
2440 return;
2441 for (unsigned i = 0; i < attributeCount(); ++i) {
2442 if (RefPtr<Attr> attr = attrIfExists(attributeItem(i)->name()))
2443 attr->normalize();
2444 }
2445}
2446
Torne (Richard Coles)8abfc582013-09-12 12:10:38 +01002447void Element::updatePseudoElement(PseudoId pseudoId, StyleRecalcChange change)
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002448{
2449 PseudoElement* element = pseudoElement(pseudoId);
2450 if (element && (needsStyleRecalc() || shouldRecalcStyle(change, element))) {
2451 // PseudoElement styles hang off their parent element's style so if we needed
2452 // a style recalc we should Force one on the pseudo.
2453 element->recalcStyle(needsStyleRecalc() ? Force : change);
2454
2455 // Wait until our parent is not displayed or pseudoElementRendererIsNeeded
2456 // is false, otherwise we could continously create and destroy PseudoElements
2457 // when RenderObject::isChildAllowed on our parent returns false for the
2458 // PseudoElement's renderer for each style recalc.
2459 if (!renderer() || !pseudoElementRendererIsNeeded(renderer()->getCachedPseudoStyle(pseudoId)))
Torne (Richard Coles)521d96e2013-06-19 11:58:24 +01002460 elementRareData()->setPseudoElement(pseudoId, 0);
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002461 } else if (change >= Inherit || needsStyleRecalc())
2462 createPseudoElementIfNeeded(pseudoId);
2463}
2464
2465void Element::createPseudoElementIfNeeded(PseudoId pseudoId)
2466{
Ben Murdoche69819b2013-07-17 14:56:49 +01002467 if (pseudoId == BACKDROP && !isInTopLayer())
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002468 return;
2469
2470 if (!renderer() || !pseudoElementRendererIsNeeded(renderer()->getCachedPseudoStyle(pseudoId)))
2471 return;
2472
2473 if (!renderer()->canHaveGeneratedChildren())
2474 return;
2475
2476 ASSERT(!isPseudoElement());
2477 RefPtr<PseudoElement> element = PseudoElement::create(this, pseudoId);
Ben Murdoche69819b2013-07-17 14:56:49 +01002478 if (pseudoId == BACKDROP)
Torne (Richard Coles)8abfc582013-09-12 12:10:38 +01002479 document().addToTopLayer(element.get(), this);
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002480 element->attach();
Ben Murdoche69819b2013-07-17 14:56:49 +01002481
Torne (Richard Coles)521d96e2013-06-19 11:58:24 +01002482 ensureElementRareData()->setPseudoElement(pseudoId, element.release());
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002483}
2484
2485PseudoElement* Element::pseudoElement(PseudoId pseudoId) const
2486{
2487 return hasRareData() ? elementRareData()->pseudoElement(pseudoId) : 0;
2488}
2489
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002490RenderObject* Element::pseudoElementRenderer(PseudoId pseudoId) const
2491{
2492 if (PseudoElement* element = pseudoElement(pseudoId))
2493 return element->renderer();
2494 return 0;
2495}
2496
Ben Murdochdf957042013-08-06 11:01:27 +01002497bool Element::webkitMatchesSelector(const String& selector, ExceptionState& es)
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002498{
2499 if (selector.isEmpty()) {
Ben Murdochdf957042013-08-06 11:01:27 +01002500 es.throwDOMException(SyntaxError);
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002501 return false;
2502 }
2503
Torne (Richard Coles)8abfc582013-09-12 12:10:38 +01002504 SelectorQuery* selectorQuery = document().selectorQueryCache()->add(selector, document(), es);
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002505 if (!selectorQuery)
2506 return false;
2507 return selectorQuery->matches(this);
2508}
2509
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002510DOMTokenList* Element::classList()
2511{
2512 ElementRareData* data = ensureElementRareData();
2513 if (!data->classList())
2514 data->setClassList(ClassList::create(this));
2515 return data->classList();
2516}
2517
2518DOMStringMap* Element::dataset()
2519{
2520 ElementRareData* data = ensureElementRareData();
2521 if (!data->dataset())
2522 data->setDataset(DatasetDOMStringMap::create(this));
2523 return data->dataset();
2524}
2525
2526KURL Element::getURLAttribute(const QualifiedName& name) const
2527{
2528#if !ASSERT_DISABLED
2529 if (elementData()) {
2530 if (const Attribute* attribute = getAttributeItem(name))
2531 ASSERT(isURLAttribute(*attribute));
2532 }
2533#endif
Torne (Richard Coles)8abfc582013-09-12 12:10:38 +01002534 return document().completeURL(stripLeadingAndTrailingHTMLSpaces(getAttribute(name)));
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002535}
2536
2537KURL Element::getNonEmptyURLAttribute(const QualifiedName& name) const
2538{
2539#if !ASSERT_DISABLED
2540 if (elementData()) {
2541 if (const Attribute* attribute = getAttributeItem(name))
2542 ASSERT(isURLAttribute(*attribute));
2543 }
2544#endif
2545 String value = stripLeadingAndTrailingHTMLSpaces(getAttribute(name));
2546 if (value.isEmpty())
2547 return KURL();
Torne (Richard Coles)8abfc582013-09-12 12:10:38 +01002548 return document().completeURL(value);
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002549}
2550
2551int Element::getIntegralAttribute(const QualifiedName& attributeName) const
2552{
2553 return getAttribute(attributeName).string().toInt();
2554}
2555
2556void Element::setIntegralAttribute(const QualifiedName& attributeName, int value)
2557{
2558 // FIXME: Need an AtomicString version of String::number.
2559 setAttribute(attributeName, String::number(value));
2560}
2561
2562unsigned Element::getUnsignedIntegralAttribute(const QualifiedName& attributeName) const
2563{
2564 return getAttribute(attributeName).string().toUInt();
2565}
2566
2567void Element::setUnsignedIntegralAttribute(const QualifiedName& attributeName, unsigned value)
2568{
2569 // FIXME: Need an AtomicString version of String::number.
2570 setAttribute(attributeName, String::number(value));
2571}
2572
Torne (Richard Coles)8abfc582013-09-12 12:10:38 +01002573bool Element::childShouldCreateRenderer(const Node& child) const
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002574{
2575 // Only create renderers for SVG elements whose parents are SVG elements, or for proper <svg xmlns="svgNS"> subdocuments.
Torne (Richard Coles)8abfc582013-09-12 12:10:38 +01002576 if (child.isSVGElement())
2577 return child.hasTagName(SVGNames::svgTag) || isSVGElement();
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002578
Torne (Richard Coles)8abfc582013-09-12 12:10:38 +01002579 return ContainerNode::childShouldCreateRenderer(child);
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002580}
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002581
2582void Element::webkitRequestFullscreen()
2583{
Torne (Richard Coles)8abfc582013-09-12 12:10:38 +01002584 FullscreenElementStack::from(&document())->requestFullScreenForElement(this, ALLOW_KEYBOARD_INPUT, FullscreenElementStack::EnforceIFrameAllowFullScreenRequirement);
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002585}
2586
2587void Element::webkitRequestFullScreen(unsigned short flags)
2588{
Torne (Richard Coles)8abfc582013-09-12 12:10:38 +01002589 FullscreenElementStack::from(&document())->requestFullScreenForElement(this, (flags | LEGACY_MOZILLA_REQUEST), FullscreenElementStack::EnforceIFrameAllowFullScreenRequirement);
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002590}
2591
2592bool Element::containsFullScreenElement() const
2593{
2594 return hasRareData() && elementRareData()->containsFullScreenElement();
2595}
2596
2597void Element::setContainsFullScreenElement(bool flag)
2598{
2599 ensureElementRareData()->setContainsFullScreenElement(flag);
Ben Murdoche69819b2013-07-17 14:56:49 +01002600 setNeedsStyleRecalc(SubtreeStyleChange);
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002601}
2602
2603static Element* parentCrossingFrameBoundaries(Element* element)
2604{
2605 ASSERT(element);
Torne (Richard Coles)8abfc582013-09-12 12:10:38 +01002606 return element->parentElement() ? element->parentElement() : element->document().ownerElement();
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002607}
2608
2609void Element::setContainsFullScreenElementOnAncestorsCrossingFrameBoundaries(bool flag)
2610{
2611 Element* element = this;
2612 while ((element = parentCrossingFrameBoundaries(element)))
2613 element->setContainsFullScreenElement(flag);
2614}
2615
2616bool Element::isInTopLayer() const
2617{
2618 return hasRareData() && elementRareData()->isInTopLayer();
2619}
2620
2621void Element::setIsInTopLayer(bool inTopLayer)
2622{
2623 if (isInTopLayer() == inTopLayer)
2624 return;
2625 ensureElementRareData()->setIsInTopLayer(inTopLayer);
2626
2627 // We must ensure a reattach occurs so the renderer is inserted in the correct sibling order under RenderView according to its
2628 // top layer position, or in its usual place if not in the top layer.
Torne (Richard Coles)93ac45c2013-05-29 14:40:20 +01002629 lazyReattachIfAttached();
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002630}
2631
2632void Element::webkitRequestPointerLock()
2633{
Torne (Richard Coles)8abfc582013-09-12 12:10:38 +01002634 if (document().page())
2635 document().page()->pointerLockController().requestPointerLock(this);
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002636}
2637
2638SpellcheckAttributeState Element::spellcheckAttributeState() const
2639{
2640 const AtomicString& value = getAttribute(HTMLNames::spellcheckAttr);
2641 if (value == nullAtom)
2642 return SpellcheckAttributeDefault;
2643 if (equalIgnoringCase(value, "true") || equalIgnoringCase(value, ""))
2644 return SpellcheckAttributeTrue;
2645 if (equalIgnoringCase(value, "false"))
2646 return SpellcheckAttributeFalse;
2647
2648 return SpellcheckAttributeDefault;
2649}
2650
2651bool Element::isSpellCheckingEnabled() const
2652{
2653 for (const Element* element = this; element; element = element->parentOrShadowHostElement()) {
2654 switch (element->spellcheckAttributeState()) {
2655 case SpellcheckAttributeTrue:
2656 return true;
2657 case SpellcheckAttributeFalse:
2658 return false;
2659 case SpellcheckAttributeDefault:
2660 break;
2661 }
2662 }
2663
2664 return true;
2665}
2666
2667RenderRegion* Element::renderRegion() const
2668{
2669 if (renderer() && renderer()->isRenderRegion())
2670 return toRenderRegion(renderer());
2671
2672 return 0;
2673}
2674
Ben Murdoch591b9582013-07-10 11:41:44 +01002675bool Element::shouldMoveToFlowThread(RenderStyle* styleToUse) const
2676{
2677 ASSERT(styleToUse);
2678
Torne (Richard Coles)f5e4ad52013-08-05 13:57:57 +01002679 if (FullscreenElementStack::isActiveFullScreenElement(this))
Ben Murdoch591b9582013-07-10 11:41:44 +01002680 return false;
2681
2682 if (isInShadowTree())
2683 return false;
2684
2685 if (styleToUse->flowThread().isEmpty())
2686 return false;
2687
2688 return !isRegisteredWithNamedFlow();
2689}
2690
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002691const AtomicString& Element::webkitRegionOverset() const
2692{
Torne (Richard Coles)8abfc582013-09-12 12:10:38 +01002693 document().updateLayoutIgnorePendingStylesheets();
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002694
2695 DEFINE_STATIC_LOCAL(AtomicString, undefinedState, ("undefined", AtomicString::ConstructFromLiteral));
2696 if (!RuntimeEnabledFeatures::cssRegionsEnabled() || !renderRegion())
2697 return undefinedState;
2698
Ben Murdoch591b9582013-07-10 11:41:44 +01002699 switch (renderRegion()->regionOversetState()) {
2700 case RegionFit: {
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002701 DEFINE_STATIC_LOCAL(AtomicString, fitState, ("fit", AtomicString::ConstructFromLiteral));
2702 return fitState;
2703 }
Ben Murdoch591b9582013-07-10 11:41:44 +01002704 case RegionEmpty: {
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002705 DEFINE_STATIC_LOCAL(AtomicString, emptyState, ("empty", AtomicString::ConstructFromLiteral));
2706 return emptyState;
2707 }
Ben Murdoch591b9582013-07-10 11:41:44 +01002708 case RegionOverset: {
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002709 DEFINE_STATIC_LOCAL(AtomicString, overflowState, ("overset", AtomicString::ConstructFromLiteral));
2710 return overflowState;
2711 }
Ben Murdoch591b9582013-07-10 11:41:44 +01002712 case RegionUndefined:
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002713 return undefinedState;
2714 }
2715
2716 ASSERT_NOT_REACHED();
2717 return undefinedState;
2718}
2719
2720Vector<RefPtr<Range> > Element::webkitGetRegionFlowRanges() const
2721{
Torne (Richard Coles)8abfc582013-09-12 12:10:38 +01002722 document().updateLayoutIgnorePendingStylesheets();
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002723
2724 Vector<RefPtr<Range> > rangeObjects;
2725 if (RuntimeEnabledFeatures::cssRegionsEnabled() && renderer() && renderer()->isRenderRegion()) {
2726 RenderRegion* region = toRenderRegion(renderer());
2727 if (region->isValid())
2728 region->getRanges(rangeObjects);
2729 }
2730
2731 return rangeObjects;
2732}
2733
2734#ifndef NDEBUG
2735bool Element::fastAttributeLookupAllowed(const QualifiedName& name) const
2736{
2737 if (name == HTMLNames::styleAttr)
2738 return false;
2739
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002740 if (isSVGElement())
2741 return !static_cast<const SVGElement*>(this)->isAnimatableAttribute(name);
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002742
2743 return true;
2744}
2745#endif
2746
2747#ifdef DUMP_NODE_STATISTICS
2748bool Element::hasNamedNodeMap() const
2749{
2750 return hasRareData() && elementRareData()->attributeMap();
2751}
2752#endif
2753
Ben Murdoch00d3faa2013-08-14 11:52:03 +01002754inline void Element::updateName(const AtomicString& oldName, const AtomicString& newName)
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002755{
Ben Murdoch00d3faa2013-08-14 11:52:03 +01002756 if (!inDocument() || isInShadowTree())
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002757 return;
2758
2759 if (oldName == newName)
2760 return;
2761
Ben Murdochdf957042013-08-06 11:01:27 +01002762 if (shouldRegisterAsNamedItem())
2763 updateNamedItemRegistration(oldName, newName);
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002764}
2765
Ben Murdoch00d3faa2013-08-14 11:52:03 +01002766inline void Element::updateId(const AtomicString& oldId, const AtomicString& newId)
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002767{
2768 if (!isInTreeScope())
2769 return;
2770
2771 if (oldId == newId)
2772 return;
2773
Ben Murdoch00d3faa2013-08-14 11:52:03 +01002774 updateId(treeScope(), oldId, newId);
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002775}
2776
Torne (Richard Coles)8abfc582013-09-12 12:10:38 +01002777inline void Element::updateId(TreeScope& scope, const AtomicString& oldId, const AtomicString& newId)
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002778{
2779 ASSERT(isInTreeScope());
2780 ASSERT(oldId != newId);
2781
2782 if (!oldId.isEmpty())
Torne (Richard Coles)8abfc582013-09-12 12:10:38 +01002783 scope.removeElementById(oldId, this);
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002784 if (!newId.isEmpty())
Torne (Richard Coles)8abfc582013-09-12 12:10:38 +01002785 scope.addElementById(newId, this);
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002786
Ben Murdochdf957042013-08-06 11:01:27 +01002787 if (shouldRegisterAsExtraNamedItem())
2788 updateExtraNamedItemRegistration(oldId, newId);
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002789}
2790
Torne (Richard Coles)8abfc582013-09-12 12:10:38 +01002791void Element::updateLabel(TreeScope& scope, const AtomicString& oldForAttributeValue, const AtomicString& newForAttributeValue)
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002792{
2793 ASSERT(hasTagName(labelTag));
2794
2795 if (!inDocument())
2796 return;
2797
2798 if (oldForAttributeValue == newForAttributeValue)
2799 return;
2800
2801 if (!oldForAttributeValue.isEmpty())
Torne (Richard Coles)8abfc582013-09-12 12:10:38 +01002802 scope.removeLabel(oldForAttributeValue, toHTMLLabelElement(this));
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002803 if (!newForAttributeValue.isEmpty())
Torne (Richard Coles)8abfc582013-09-12 12:10:38 +01002804 scope.addLabel(newForAttributeValue, toHTMLLabelElement(this));
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002805}
2806
Ben Murdoch7757ec22013-07-23 11:17:36 +01002807static bool hasSelectorForAttribute(Document* document, const AtomicString& localName)
2808{
2809 return document->styleResolver() && document->styleResolver()->ruleFeatureSet().hasSelectorForAttribute(localName);
2810}
2811
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002812void Element::willModifyAttribute(const QualifiedName& name, const AtomicString& oldValue, const AtomicString& newValue)
2813{
2814 if (isIdAttributeName(name))
2815 updateId(oldValue, newValue);
2816 else if (name == HTMLNames::nameAttr)
2817 updateName(oldValue, newValue);
2818 else if (name == HTMLNames::forAttr && hasTagName(labelTag)) {
Torne (Richard Coles)8abfc582013-09-12 12:10:38 +01002819 TreeScope& scope = treeScope();
2820 if (scope.shouldCacheLabelsByForAttribute())
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002821 updateLabel(scope, oldValue, newValue);
2822 }
2823
2824 if (oldValue != newValue) {
Torne (Richard Coles)8abfc582013-09-12 12:10:38 +01002825 if (attached() && hasSelectorForAttribute(&document(), name.localName()))
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002826 setNeedsStyleRecalc();
Ben Murdoche69819b2013-07-17 14:56:49 +01002827
2828 if (isUpgradedCustomElement())
Ben Murdoch83750172013-07-24 10:36:59 +01002829 CustomElement::attributeDidChange(this, name.localName(), oldValue, newValue);
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002830 }
2831
2832 if (OwnPtr<MutationObserverInterestGroup> recipients = MutationObserverInterestGroup::createForAttributesMutation(this, name))
2833 recipients->enqueueMutationRecord(MutationRecord::createAttributes(this, name, oldValue));
2834
Torne (Richard Coles)8abfc582013-09-12 12:10:38 +01002835 InspectorInstrumentation::willModifyDOMAttr(&document(), this, oldValue, newValue);
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002836}
2837
2838void Element::didAddAttribute(const QualifiedName& name, const AtomicString& value)
2839{
2840 attributeChanged(name, value);
Torne (Richard Coles)8abfc582013-09-12 12:10:38 +01002841 InspectorInstrumentation::didModifyDOMAttr(&document(), this, name.localName(), value);
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002842 dispatchSubtreeModifiedEvent();
2843}
2844
2845void Element::didModifyAttribute(const QualifiedName& name, const AtomicString& value)
2846{
2847 attributeChanged(name, value);
Torne (Richard Coles)8abfc582013-09-12 12:10:38 +01002848 InspectorInstrumentation::didModifyDOMAttr(&document(), this, name.localName(), value);
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002849 // Do not dispatch a DOMSubtreeModified event here; see bug 81141.
2850}
2851
2852void Element::didRemoveAttribute(const QualifiedName& name)
2853{
2854 attributeChanged(name, nullAtom);
Torne (Richard Coles)8abfc582013-09-12 12:10:38 +01002855 InspectorInstrumentation::didRemoveDOMAttr(&document(), this, name.localName());
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002856 dispatchSubtreeModifiedEvent();
2857}
2858
Ben Murdoche69819b2013-07-17 14:56:49 +01002859void Element::didMoveToNewDocument(Document* oldDocument)
2860{
2861 Node::didMoveToNewDocument(oldDocument);
2862
2863 // If the documents differ by quirks mode then they differ by case sensitivity
2864 // for class and id names so we need to go through the attribute change logic
2865 // to pick up the new casing in the ElementData.
Torne (Richard Coles)8abfc582013-09-12 12:10:38 +01002866 if (oldDocument->inQuirksMode() != document().inQuirksMode()) {
Ben Murdoche69819b2013-07-17 14:56:49 +01002867 if (hasID())
2868 setIdAttribute(getIdAttribute());
2869 if (hasClass())
2870 setAttribute(HTMLNames::classAttr, getClassAttribute());
2871 }
2872}
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002873
Ben Murdochdf957042013-08-06 11:01:27 +01002874void Element::updateNamedItemRegistration(const AtomicString& oldName, const AtomicString& newName)
2875{
Torne (Richard Coles)8abfc582013-09-12 12:10:38 +01002876 if (!document().isHTMLDocument())
Ben Murdoch00d3faa2013-08-14 11:52:03 +01002877 return;
Ben Murdochdf957042013-08-06 11:01:27 +01002878
2879 if (!oldName.isEmpty())
Torne (Richard Coles)8abfc582013-09-12 12:10:38 +01002880 toHTMLDocument(document()).removeNamedItem(oldName);
Ben Murdochdf957042013-08-06 11:01:27 +01002881
2882 if (!newName.isEmpty())
Torne (Richard Coles)8abfc582013-09-12 12:10:38 +01002883 toHTMLDocument(document()).addNamedItem(newName);
Ben Murdochdf957042013-08-06 11:01:27 +01002884}
2885
2886void Element::updateExtraNamedItemRegistration(const AtomicString& oldId, const AtomicString& newId)
2887{
Torne (Richard Coles)8abfc582013-09-12 12:10:38 +01002888 if (!document().isHTMLDocument())
Ben Murdoch00d3faa2013-08-14 11:52:03 +01002889 return;
Ben Murdochdf957042013-08-06 11:01:27 +01002890
2891 if (!oldId.isEmpty())
Torne (Richard Coles)8abfc582013-09-12 12:10:38 +01002892 toHTMLDocument(document()).removeExtraNamedItem(oldId);
Ben Murdochdf957042013-08-06 11:01:27 +01002893
2894 if (!newId.isEmpty())
Torne (Richard Coles)8abfc582013-09-12 12:10:38 +01002895 toHTMLDocument(document()).addExtraNamedItem(newId);
Ben Murdochdf957042013-08-06 11:01:27 +01002896}
2897
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002898PassRefPtr<HTMLCollection> Element::ensureCachedHTMLCollection(CollectionType type)
2899{
2900 if (HTMLCollection* collection = cachedHTMLCollection(type))
2901 return collection;
2902
2903 RefPtr<HTMLCollection> collection;
2904 if (type == TableRows) {
2905 ASSERT(hasTagName(tableTag));
2906 return ensureRareData()->ensureNodeLists()->addCacheWithAtomicName<HTMLTableRowsCollection>(this, type);
2907 } else if (type == SelectOptions) {
2908 ASSERT(hasTagName(selectTag));
2909 return ensureRareData()->ensureNodeLists()->addCacheWithAtomicName<HTMLOptionsCollection>(this, type);
2910 } else if (type == FormControls) {
2911 ASSERT(hasTagName(formTag) || hasTagName(fieldsetTag));
2912 return ensureRareData()->ensureNodeLists()->addCacheWithAtomicName<HTMLFormControlsCollection>(this, type);
2913 }
2914 return ensureRareData()->ensureNodeLists()->addCacheWithAtomicName<HTMLCollection>(this, type);
2915}
2916
Ben Murdoch591b9582013-07-10 11:41:44 +01002917static void scheduleLayerUpdateCallback(Node* node)
Torne (Richard Coles)93ac45c2013-05-29 14:40:20 +01002918{
Ben Murdoche69819b2013-07-17 14:56:49 +01002919 // Notify the renderer even is the styles are identical since it may need to
2920 // create or destroy a RenderLayer.
2921 node->setNeedsStyleRecalc(LocalStyleChange, StyleChangeFromRenderer);
Torne (Richard Coles)93ac45c2013-05-29 14:40:20 +01002922}
2923
Ben Murdoch591b9582013-07-10 11:41:44 +01002924void Element::scheduleLayerUpdate()
Torne (Richard Coles)93ac45c2013-05-29 14:40:20 +01002925{
Torne (Richard Coles)8abfc582013-09-12 12:10:38 +01002926 if (document().inStyleRecalc())
2927 PostAttachCallbacks::queueCallback(scheduleLayerUpdateCallback, this);
Torne (Richard Coles)93ac45c2013-05-29 14:40:20 +01002928 else
Ben Murdoche69819b2013-07-17 14:56:49 +01002929 scheduleLayerUpdateCallback(this);
Torne (Richard Coles)93ac45c2013-05-29 14:40:20 +01002930}
2931
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002932HTMLCollection* Element::cachedHTMLCollection(CollectionType type)
2933{
2934 return hasRareData() && rareData()->nodeLists() ? rareData()->nodeLists()->cacheWithAtomicName<HTMLCollection>(type) : 0;
2935}
2936
2937IntSize Element::savedLayerScrollOffset() const
2938{
2939 return hasRareData() ? elementRareData()->savedLayerScrollOffset() : IntSize();
2940}
2941
2942void Element::setSavedLayerScrollOffset(const IntSize& size)
2943{
2944 if (size.isZero() && !hasRareData())
2945 return;
2946 ensureElementRareData()->setSavedLayerScrollOffset(size);
2947}
2948
2949PassRefPtr<Attr> Element::attrIfExists(const QualifiedName& name)
2950{
2951 if (AttrNodeList* attrNodeList = attrNodeListForElement(this))
2952 return findAttrNodeInList(attrNodeList, name);
2953 return 0;
2954}
2955
2956PassRefPtr<Attr> Element::ensureAttr(const QualifiedName& name)
2957{
2958 AttrNodeList* attrNodeList = ensureAttrNodeListForElement(this);
2959 RefPtr<Attr> attrNode = findAttrNodeInList(attrNodeList, name);
2960 if (!attrNode) {
Torne (Richard Coles)8abfc582013-09-12 12:10:38 +01002961 attrNode = Attr::create(*this, name);
2962 treeScope().adoptIfNeeded(attrNode.get());
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002963 attrNodeList->append(attrNode);
2964 }
2965 return attrNode.release();
2966}
2967
2968void Element::detachAttrNodeFromElementWithValue(Attr* attrNode, const AtomicString& value)
2969{
2970 ASSERT(hasSyntheticAttrChildNodes());
2971 attrNode->detachFromElementWithValue(value);
2972
2973 AttrNodeList* attrNodeList = attrNodeListForElement(this);
2974 for (unsigned i = 0; i < attrNodeList->size(); ++i) {
2975 if (attrNodeList->at(i)->qualifiedName() == attrNode->qualifiedName()) {
2976 attrNodeList->remove(i);
2977 if (attrNodeList->isEmpty())
2978 removeAttrNodeListForElement(this);
2979 return;
2980 }
2981 }
2982 ASSERT_NOT_REACHED();
2983}
2984
2985void Element::detachAllAttrNodesFromElement()
2986{
2987 AttrNodeList* attrNodeList = attrNodeListForElement(this);
2988 ASSERT(attrNodeList);
2989
2990 for (unsigned i = 0; i < attributeCount(); ++i) {
2991 const Attribute* attribute = attributeItem(i);
2992 if (RefPtr<Attr> attrNode = findAttrNodeInList(attrNodeList, attribute->name()))
2993 attrNode->detachFromElementWithValue(attribute->value());
2994 }
2995
2996 removeAttrNodeListForElement(this);
2997}
2998
Torne (Richard Coles)8abfc582013-09-12 12:10:38 +01002999void Element::willRecalcStyle(StyleRecalcChange)
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01003000{
3001 ASSERT(hasCustomStyleCallbacks());
3002}
3003
Torne (Richard Coles)8abfc582013-09-12 12:10:38 +01003004void Element::didRecalcStyle(StyleRecalcChange)
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01003005{
3006 ASSERT(hasCustomStyleCallbacks());
3007}
3008
3009
3010PassRefPtr<RenderStyle> Element::customStyleForRenderer()
3011{
3012 ASSERT(hasCustomStyleCallbacks());
3013 return 0;
3014}
3015
3016void Element::cloneAttributesFromElement(const Element& other)
3017{
3018 if (hasSyntheticAttrChildNodes())
3019 detachAllAttrNodesFromElement();
3020
3021 other.synchronizeAllAttributes();
3022 if (!other.m_elementData) {
3023 m_elementData.clear();
3024 return;
3025 }
3026
3027 const AtomicString& oldID = getIdAttribute();
3028 const AtomicString& newID = other.getIdAttribute();
3029
3030 if (!oldID.isNull() || !newID.isNull())
3031 updateId(oldID, newID);
3032
3033 const AtomicString& oldName = getNameAttribute();
3034 const AtomicString& newName = other.getNameAttribute();
3035
3036 if (!oldName.isNull() || !newName.isNull())
3037 updateName(oldName, newName);
3038
Ben Murdoche69819b2013-07-17 14:56:49 +01003039 // Quirks mode makes class and id not case sensitive. We can't share the ElementData
3040 // if the idForStyleResolution and the className need different casing.
3041 bool ownerDocumentsHaveDifferentCaseSensitivity = false;
3042 if (other.hasClass() || other.hasID())
Torne (Richard Coles)8abfc582013-09-12 12:10:38 +01003043 ownerDocumentsHaveDifferentCaseSensitivity = other.document().inQuirksMode() != document().inQuirksMode();
Ben Murdoche69819b2013-07-17 14:56:49 +01003044
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01003045 // If 'other' has a mutable ElementData, convert it to an immutable one so we can share it between both elements.
Ben Murdoche69819b2013-07-17 14:56:49 +01003046 // We can only do this if there is no CSSOM wrapper for other's inline style, and there are no presentation attributes,
3047 // and sharing the data won't result in different case sensitivity of class or id.
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01003048 if (other.m_elementData->isUnique()
Ben Murdoche69819b2013-07-17 14:56:49 +01003049 && !ownerDocumentsHaveDifferentCaseSensitivity
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01003050 && !other.m_elementData->presentationAttributeStyle()
3051 && (!other.m_elementData->inlineStyle() || !other.m_elementData->inlineStyle()->hasCSSOMWrapper()))
3052 const_cast<Element&>(other).m_elementData = static_cast<const UniqueElementData*>(other.m_elementData.get())->makeShareableCopy();
3053
Ben Murdoche69819b2013-07-17 14:56:49 +01003054 if (!other.m_elementData->isUnique() && !ownerDocumentsHaveDifferentCaseSensitivity)
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01003055 m_elementData = other.m_elementData;
3056 else
3057 m_elementData = other.m_elementData->makeUniqueCopy();
3058
3059 for (unsigned i = 0; i < m_elementData->length(); ++i) {
3060 const Attribute* attribute = const_cast<const ElementData*>(m_elementData.get())->attributeItem(i);
3061 attributeChangedFromParserOrByCloning(attribute->name(), attribute->value(), ModifiedByCloning);
3062 }
3063}
3064
3065void Element::cloneDataFromElement(const Element& other)
3066{
3067 cloneAttributesFromElement(other);
3068 copyNonAttributePropertiesFromElement(other);
3069}
3070
3071void Element::createUniqueElementData()
3072{
3073 if (!m_elementData)
3074 m_elementData = UniqueElementData::create();
3075 else {
3076 ASSERT(!m_elementData->isUnique());
3077 m_elementData = static_cast<ShareableElementData*>(m_elementData.get())->makeUniqueCopy();
3078 }
3079}
3080
Ben Murdoch1fad5ca2013-08-07 11:05:11 +01003081InputMethodContext* Element::inputMethodContext()
Torne (Richard Coles)81a51572013-05-13 16:52:28 +01003082{
3083 return ensureElementRareData()->ensureInputMethodContext(toHTMLElement(this));
3084}
3085
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01003086bool Element::hasPendingResources() const
3087{
3088 return hasRareData() && elementRareData()->hasPendingResources();
3089}
3090
3091void Element::setHasPendingResources()
3092{
3093 ensureElementRareData()->setHasPendingResources(true);
3094}
3095
3096void Element::clearHasPendingResources()
3097{
3098 ensureElementRareData()->setHasPendingResources(false);
3099}
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01003100
Ben Murdoch591b9582013-07-10 11:41:44 +01003101struct PresentationAttributeCacheKey {
3102 PresentationAttributeCacheKey() : tagName(0) { }
Ben Murdoch83750172013-07-24 10:36:59 +01003103 StringImpl* tagName;
Ben Murdoch591b9582013-07-10 11:41:44 +01003104 // Only the values need refcounting.
Ben Murdoch83750172013-07-24 10:36:59 +01003105 Vector<pair<StringImpl*, AtomicString>, 3> attributesAndValues;
Ben Murdoch591b9582013-07-10 11:41:44 +01003106};
3107
3108struct PresentationAttributeCacheEntry {
3109 WTF_MAKE_FAST_ALLOCATED;
3110public:
3111 PresentationAttributeCacheKey key;
3112 RefPtr<StylePropertySet> value;
3113};
3114
3115typedef HashMap<unsigned, OwnPtr<PresentationAttributeCacheEntry>, AlreadyHashed> PresentationAttributeCache;
3116
3117static bool operator!=(const PresentationAttributeCacheKey& a, const PresentationAttributeCacheKey& b)
3118{
3119 if (a.tagName != b.tagName)
3120 return true;
3121 return a.attributesAndValues != b.attributesAndValues;
3122}
3123
3124static PresentationAttributeCache& presentationAttributeCache()
3125{
3126 DEFINE_STATIC_LOCAL(PresentationAttributeCache, cache, ());
3127 return cache;
3128}
3129
3130class PresentationAttributeCacheCleaner {
3131 WTF_MAKE_NONCOPYABLE(PresentationAttributeCacheCleaner); WTF_MAKE_FAST_ALLOCATED;
3132public:
3133 PresentationAttributeCacheCleaner()
3134 : m_hitCount(0)
3135 , m_cleanTimer(this, &PresentationAttributeCacheCleaner::cleanCache)
3136 {
3137 }
3138
3139 void didHitPresentationAttributeCache()
3140 {
3141 if (presentationAttributeCache().size() < minimumPresentationAttributeCacheSizeForCleaning)
3142 return;
3143
3144 m_hitCount++;
3145
3146 if (!m_cleanTimer.isActive())
3147 m_cleanTimer.startOneShot(presentationAttributeCacheCleanTimeInSeconds);
3148 }
3149
3150private:
3151 static const unsigned presentationAttributeCacheCleanTimeInSeconds = 60;
3152 static const int minimumPresentationAttributeCacheSizeForCleaning = 100;
3153 static const unsigned minimumPresentationAttributeCacheHitCountPerMinute = (100 * presentationAttributeCacheCleanTimeInSeconds) / 60;
3154
3155 void cleanCache(Timer<PresentationAttributeCacheCleaner>* timer)
3156 {
3157 ASSERT_UNUSED(timer, timer == &m_cleanTimer);
3158 unsigned hitCount = m_hitCount;
3159 m_hitCount = 0;
3160 if (hitCount > minimumPresentationAttributeCacheHitCountPerMinute)
3161 return;
3162 presentationAttributeCache().clear();
3163 }
3164
3165 unsigned m_hitCount;
3166 Timer<PresentationAttributeCacheCleaner> m_cleanTimer;
3167};
3168
3169static PresentationAttributeCacheCleaner& presentationAttributeCacheCleaner()
3170{
3171 DEFINE_STATIC_LOCAL(PresentationAttributeCacheCleaner, cleaner, ());
3172 return cleaner;
3173}
3174
3175void Element::synchronizeStyleAttributeInternal() const
3176{
3177 ASSERT(isStyledElement());
3178 ASSERT(elementData());
3179 ASSERT(elementData()->m_styleAttributeIsDirty);
3180 elementData()->m_styleAttributeIsDirty = false;
3181 if (const StylePropertySet* inlineStyle = this->inlineStyle())
3182 const_cast<Element*>(this)->setSynchronizedLazyAttribute(styleAttr, inlineStyle->asText());
3183}
3184
3185CSSStyleDeclaration* Element::style()
3186{
3187 if (!isStyledElement())
3188 return 0;
3189 return ensureMutableInlineStyle()->ensureInlineCSSStyleDeclaration(this);
3190}
3191
3192MutableStylePropertySet* Element::ensureMutableInlineStyle()
3193{
3194 ASSERT(isStyledElement());
3195 RefPtr<StylePropertySet>& inlineStyle = ensureUniqueElementData()->m_inlineStyle;
3196 if (!inlineStyle)
Torne (Richard Coles)8abfc582013-09-12 12:10:38 +01003197 inlineStyle = MutableStylePropertySet::create(strictToCSSParserMode(isHTMLElement() && !document().inQuirksMode()));
Ben Murdoch591b9582013-07-10 11:41:44 +01003198 else if (!inlineStyle->isMutable())
3199 inlineStyle = inlineStyle->mutableCopy();
3200 ASSERT(inlineStyle->isMutable());
3201 return static_cast<MutableStylePropertySet*>(inlineStyle.get());
3202}
3203
3204PropertySetCSSStyleDeclaration* Element::inlineStyleCSSOMWrapper()
3205{
3206 if (!inlineStyle() || !inlineStyle()->hasCSSOMWrapper())
3207 return 0;
3208 PropertySetCSSStyleDeclaration* cssomWrapper = ensureMutableInlineStyle()->cssStyleDeclaration();
3209 ASSERT(cssomWrapper && cssomWrapper->parentElement() == this);
3210 return cssomWrapper;
3211}
3212
3213inline void Element::setInlineStyleFromString(const AtomicString& newStyleString)
3214{
3215 ASSERT(isStyledElement());
3216 RefPtr<StylePropertySet>& inlineStyle = elementData()->m_inlineStyle;
3217
3218 // Avoid redundant work if we're using shared attribute data with already parsed inline style.
3219 if (inlineStyle && !elementData()->isUnique())
3220 return;
3221
3222 // We reconstruct the property set instead of mutating if there is no CSSOM wrapper.
3223 // This makes wrapperless property sets immutable and so cacheable.
3224 if (inlineStyle && !inlineStyle->isMutable())
3225 inlineStyle.clear();
3226
3227 if (!inlineStyle) {
3228 inlineStyle = CSSParser::parseInlineStyleDeclaration(newStyleString, this);
3229 } else {
3230 ASSERT(inlineStyle->isMutable());
Torne (Richard Coles)8abfc582013-09-12 12:10:38 +01003231 static_pointer_cast<MutableStylePropertySet>(inlineStyle)->parseDeclaration(newStyleString, document().elementSheet()->contents());
Ben Murdoch591b9582013-07-10 11:41:44 +01003232 }
3233}
3234
3235void Element::styleAttributeChanged(const AtomicString& newStyleString, AttributeModificationReason modificationReason)
3236{
3237 ASSERT(isStyledElement());
3238 WTF::OrdinalNumber startLineNumber = WTF::OrdinalNumber::beforeFirst();
Torne (Richard Coles)8abfc582013-09-12 12:10:38 +01003239 if (document().scriptableDocumentParser() && !document().isInDocumentWrite())
3240 startLineNumber = document().scriptableDocumentParser()->lineNumber();
Ben Murdoch591b9582013-07-10 11:41:44 +01003241
3242 if (newStyleString.isNull()) {
3243 if (PropertySetCSSStyleDeclaration* cssomWrapper = inlineStyleCSSOMWrapper())
3244 cssomWrapper->clearParentElement();
3245 ensureUniqueElementData()->m_inlineStyle.clear();
Torne (Richard Coles)8abfc582013-09-12 12:10:38 +01003246 } else if (modificationReason == ModifiedByCloning || document().contentSecurityPolicy()->allowInlineStyle(document().url(), startLineNumber)) {
Ben Murdoch591b9582013-07-10 11:41:44 +01003247 setInlineStyleFromString(newStyleString);
3248 }
3249
3250 elementData()->m_styleAttributeIsDirty = false;
3251
Ben Murdoche69819b2013-07-17 14:56:49 +01003252 setNeedsStyleRecalc(LocalStyleChange);
Torne (Richard Coles)8abfc582013-09-12 12:10:38 +01003253 InspectorInstrumentation::didInvalidateStyleAttr(&document(), this);
Ben Murdoch591b9582013-07-10 11:41:44 +01003254}
3255
3256void Element::inlineStyleChanged()
3257{
3258 ASSERT(isStyledElement());
Ben Murdoche69819b2013-07-17 14:56:49 +01003259 setNeedsStyleRecalc(LocalStyleChange);
Ben Murdoch591b9582013-07-10 11:41:44 +01003260 ASSERT(elementData());
3261 elementData()->m_styleAttributeIsDirty = true;
Torne (Richard Coles)8abfc582013-09-12 12:10:38 +01003262 InspectorInstrumentation::didInvalidateStyleAttr(&document(), this);
Ben Murdoch591b9582013-07-10 11:41:44 +01003263}
3264
3265bool Element::setInlineStyleProperty(CSSPropertyID propertyID, CSSValueID identifier, bool important)
3266{
3267 ASSERT(isStyledElement());
3268 ensureMutableInlineStyle()->setProperty(propertyID, cssValuePool().createIdentifierValue(identifier), important);
3269 inlineStyleChanged();
3270 return true;
3271}
3272
3273bool Element::setInlineStyleProperty(CSSPropertyID propertyID, CSSPropertyID identifier, bool important)
3274{
3275 ASSERT(isStyledElement());
3276 ensureMutableInlineStyle()->setProperty(propertyID, cssValuePool().createIdentifierValue(identifier), important);
3277 inlineStyleChanged();
3278 return true;
3279}
3280
3281bool Element::setInlineStyleProperty(CSSPropertyID propertyID, double value, CSSPrimitiveValue::UnitTypes unit, bool important)
3282{
3283 ASSERT(isStyledElement());
3284 ensureMutableInlineStyle()->setProperty(propertyID, cssValuePool().createValue(value, unit), important);
3285 inlineStyleChanged();
3286 return true;
3287}
3288
3289bool Element::setInlineStyleProperty(CSSPropertyID propertyID, const String& value, bool important)
3290{
3291 ASSERT(isStyledElement());
Torne (Richard Coles)8abfc582013-09-12 12:10:38 +01003292 bool changes = ensureMutableInlineStyle()->setProperty(propertyID, value, important, document().elementSheet()->contents());
Ben Murdoch591b9582013-07-10 11:41:44 +01003293 if (changes)
3294 inlineStyleChanged();
3295 return changes;
3296}
3297
3298bool Element::removeInlineStyleProperty(CSSPropertyID propertyID)
3299{
3300 ASSERT(isStyledElement());
3301 if (!inlineStyle())
3302 return false;
3303 bool changes = ensureMutableInlineStyle()->removeProperty(propertyID);
3304 if (changes)
3305 inlineStyleChanged();
3306 return changes;
3307}
3308
3309void Element::removeAllInlineStyleProperties()
3310{
3311 ASSERT(isStyledElement());
3312 if (!inlineStyle() || inlineStyle()->isEmpty())
3313 return;
3314 ensureMutableInlineStyle()->clear();
3315 inlineStyleChanged();
3316}
3317
3318void Element::addSubresourceAttributeURLs(ListHashSet<KURL>& urls) const
3319{
3320 ASSERT(isStyledElement());
3321 if (const StylePropertySet* inlineStyle = elementData() ? elementData()->inlineStyle() : 0)
Torne (Richard Coles)8abfc582013-09-12 12:10:38 +01003322 inlineStyle->addSubresourceStyleURLs(urls, document().elementSheet()->contents());
Ben Murdoch591b9582013-07-10 11:41:44 +01003323}
3324
Ben Murdoch83750172013-07-24 10:36:59 +01003325static inline bool attributeNameSort(const pair<StringImpl*, AtomicString>& p1, const pair<StringImpl*, AtomicString>& p2)
Ben Murdoch591b9582013-07-10 11:41:44 +01003326{
3327 // Sort based on the attribute name pointers. It doesn't matter what the order is as long as it is always the same.
3328 return p1.first < p2.first;
3329}
3330
3331void Element::makePresentationAttributeCacheKey(PresentationAttributeCacheKey& result) const
3332{
3333 ASSERT(isStyledElement());
3334 // FIXME: Enable for SVG.
3335 if (namespaceURI() != xhtmlNamespaceURI)
3336 return;
3337 // Interpretation of the size attributes on <input> depends on the type attribute.
3338 if (hasTagName(inputTag))
3339 return;
3340 unsigned size = attributeCount();
3341 for (unsigned i = 0; i < size; ++i) {
3342 const Attribute* attribute = attributeItem(i);
3343 if (!isPresentationAttribute(attribute->name()))
3344 continue;
3345 if (!attribute->namespaceURI().isNull())
3346 return;
3347 // FIXME: Background URL may depend on the base URL and can't be shared. Disallow caching.
3348 if (attribute->name() == backgroundAttr)
3349 return;
3350 result.attributesAndValues.append(std::make_pair(attribute->localName().impl(), attribute->value()));
3351 }
3352 if (result.attributesAndValues.isEmpty())
3353 return;
3354 // Attribute order doesn't matter. Sort for easy equality comparison.
3355 std::sort(result.attributesAndValues.begin(), result.attributesAndValues.end(), attributeNameSort);
3356 // The cache key is non-null when the tagName is set.
3357 result.tagName = localName().impl();
3358}
3359
3360static unsigned computePresentationAttributeCacheHash(const PresentationAttributeCacheKey& key)
3361{
3362 if (!key.tagName)
3363 return 0;
3364 ASSERT(key.attributesAndValues.size());
3365 unsigned attributeHash = StringHasher::hashMemory(key.attributesAndValues.data(), key.attributesAndValues.size() * sizeof(key.attributesAndValues[0]));
3366 return WTF::pairIntHash(key.tagName->existingHash(), attributeHash);
3367}
3368
3369void Element::rebuildPresentationAttributeStyle()
3370{
3371 ASSERT(isStyledElement());
3372 PresentationAttributeCacheKey cacheKey;
3373 makePresentationAttributeCacheKey(cacheKey);
3374
3375 unsigned cacheHash = computePresentationAttributeCacheHash(cacheKey);
3376
3377 PresentationAttributeCache::iterator cacheIterator;
3378 if (cacheHash) {
3379 cacheIterator = presentationAttributeCache().add(cacheHash, nullptr).iterator;
3380 if (cacheIterator->value && cacheIterator->value->key != cacheKey)
3381 cacheHash = 0;
3382 } else {
3383 cacheIterator = presentationAttributeCache().end();
3384 }
3385
3386 RefPtr<StylePropertySet> style;
3387 if (cacheHash && cacheIterator->value) {
3388 style = cacheIterator->value->value;
3389 presentationAttributeCacheCleaner().didHitPresentationAttributeCache();
3390 } else {
3391 style = MutableStylePropertySet::create(isSVGElement() ? SVGAttributeMode : CSSQuirksMode);
3392 unsigned size = attributeCount();
3393 for (unsigned i = 0; i < size; ++i) {
3394 const Attribute* attribute = attributeItem(i);
3395 collectStyleForPresentationAttribute(attribute->name(), attribute->value(), static_cast<MutableStylePropertySet*>(style.get()));
3396 }
3397 }
3398
3399 // ShareableElementData doesn't store presentation attribute style, so make sure we have a UniqueElementData.
3400 UniqueElementData* elementData = ensureUniqueElementData();
3401
3402 elementData->m_presentationAttributeStyleIsDirty = false;
3403 elementData->m_presentationAttributeStyle = style->isEmpty() ? 0 : style;
3404
3405 if (!cacheHash || cacheIterator->value)
3406 return;
3407
3408 OwnPtr<PresentationAttributeCacheEntry> newEntry = adoptPtr(new PresentationAttributeCacheEntry);
3409 newEntry->key = cacheKey;
3410 newEntry->value = style.release();
3411
3412 static const int presentationAttributeCacheMaximumSize = 4096;
3413 if (presentationAttributeCache().size() > presentationAttributeCacheMaximumSize) {
3414 // Start building from scratch if the cache ever gets big.
3415 presentationAttributeCache().clear();
3416 presentationAttributeCache().set(cacheHash, newEntry.release());
3417 } else {
3418 cacheIterator->value = newEntry.release();
3419 }
3420}
3421
3422void Element::addPropertyToPresentationAttributeStyle(MutableStylePropertySet* style, CSSPropertyID propertyID, CSSValueID identifier)
3423{
3424 ASSERT(isStyledElement());
3425 style->setProperty(propertyID, cssValuePool().createIdentifierValue(identifier));
3426}
3427
3428void Element::addPropertyToPresentationAttributeStyle(MutableStylePropertySet* style, CSSPropertyID propertyID, double value, CSSPrimitiveValue::UnitTypes unit)
3429{
3430 ASSERT(isStyledElement());
3431 style->setProperty(propertyID, cssValuePool().createValue(value, unit));
3432}
3433
3434void Element::addPropertyToPresentationAttributeStyle(MutableStylePropertySet* style, CSSPropertyID propertyID, const String& value)
3435{
3436 ASSERT(isStyledElement());
Torne (Richard Coles)8abfc582013-09-12 12:10:38 +01003437 style->setProperty(propertyID, value, false, document().elementSheet()->contents());
Ben Murdoch591b9582013-07-10 11:41:44 +01003438}
3439
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01003440void ElementData::deref()
3441{
3442 if (!derefBase())
3443 return;
3444
3445 if (m_isUnique)
3446 delete static_cast<UniqueElementData*>(this);
3447 else
3448 delete static_cast<ShareableElementData*>(this);
3449}
3450
3451ElementData::ElementData()
3452 : m_isUnique(true)
3453 , m_arraySize(0)
3454 , m_presentationAttributeStyleIsDirty(false)
3455 , m_styleAttributeIsDirty(false)
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01003456 , m_animatedSVGAttributesAreDirty(false)
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01003457{
3458}
3459
3460ElementData::ElementData(unsigned arraySize)
3461 : m_isUnique(false)
3462 , m_arraySize(arraySize)
3463 , m_presentationAttributeStyleIsDirty(false)
3464 , m_styleAttributeIsDirty(false)
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01003465 , m_animatedSVGAttributesAreDirty(false)
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01003466{
3467}
3468
3469struct SameSizeAsElementData : public RefCounted<SameSizeAsElementData> {
3470 unsigned bitfield;
3471 void* refPtrs[3];
3472};
3473
3474COMPILE_ASSERT(sizeof(ElementData) == sizeof(SameSizeAsElementData), element_attribute_data_should_stay_small);
3475
3476static size_t sizeForShareableElementDataWithAttributeCount(unsigned count)
3477{
3478 return sizeof(ShareableElementData) + sizeof(Attribute) * count;
3479}
3480
3481PassRefPtr<ShareableElementData> ShareableElementData::createWithAttributes(const Vector<Attribute>& attributes)
3482{
3483 void* slot = WTF::fastMalloc(sizeForShareableElementDataWithAttributeCount(attributes.size()));
3484 return adoptRef(new (slot) ShareableElementData(attributes));
3485}
3486
3487PassRefPtr<UniqueElementData> UniqueElementData::create()
3488{
3489 return adoptRef(new UniqueElementData);
3490}
3491
3492ShareableElementData::ShareableElementData(const Vector<Attribute>& attributes)
3493 : ElementData(attributes.size())
3494{
3495 for (unsigned i = 0; i < m_arraySize; ++i)
3496 new (&m_attributeArray[i]) Attribute(attributes[i]);
3497}
3498
3499ShareableElementData::~ShareableElementData()
3500{
3501 for (unsigned i = 0; i < m_arraySize; ++i)
3502 m_attributeArray[i].~Attribute();
3503}
3504
3505ShareableElementData::ShareableElementData(const UniqueElementData& other)
3506 : ElementData(other, false)
3507{
3508 ASSERT(!other.m_presentationAttributeStyle);
3509
3510 if (other.m_inlineStyle) {
3511 ASSERT(!other.m_inlineStyle->hasCSSOMWrapper());
3512 m_inlineStyle = other.m_inlineStyle->immutableCopyIfNeeded();
3513 }
3514
3515 for (unsigned i = 0; i < m_arraySize; ++i)
3516 new (&m_attributeArray[i]) Attribute(other.m_attributeVector.at(i));
3517}
3518
3519ElementData::ElementData(const ElementData& other, bool isUnique)
3520 : m_isUnique(isUnique)
3521 , m_arraySize(isUnique ? 0 : other.length())
3522 , m_presentationAttributeStyleIsDirty(other.m_presentationAttributeStyleIsDirty)
3523 , m_styleAttributeIsDirty(other.m_styleAttributeIsDirty)
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01003524 , m_animatedSVGAttributesAreDirty(other.m_animatedSVGAttributesAreDirty)
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01003525 , m_classNames(other.m_classNames)
3526 , m_idForStyleResolution(other.m_idForStyleResolution)
3527{
3528 // NOTE: The inline style is copied by the subclass copy constructor since we don't know what to do with it here.
3529}
3530
3531UniqueElementData::UniqueElementData()
3532{
3533}
3534
3535UniqueElementData::UniqueElementData(const UniqueElementData& other)
3536 : ElementData(other, true)
3537 , m_presentationAttributeStyle(other.m_presentationAttributeStyle)
3538 , m_attributeVector(other.m_attributeVector)
3539{
Torne (Richard Coles)93ac45c2013-05-29 14:40:20 +01003540 m_inlineStyle = other.m_inlineStyle ? other.m_inlineStyle->mutableCopy() : 0;
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01003541}
3542
3543UniqueElementData::UniqueElementData(const ShareableElementData& other)
3544 : ElementData(other, true)
3545{
3546 // An ShareableElementData should never have a mutable inline StylePropertySet attached.
3547 ASSERT(!other.m_inlineStyle || !other.m_inlineStyle->isMutable());
3548 m_inlineStyle = other.m_inlineStyle;
3549
3550 m_attributeVector.reserveCapacity(other.length());
3551 for (unsigned i = 0; i < other.length(); ++i)
3552 m_attributeVector.uncheckedAppend(other.m_attributeArray[i]);
3553}
3554
3555PassRefPtr<UniqueElementData> ElementData::makeUniqueCopy() const
3556{
3557 if (isUnique())
3558 return adoptRef(new UniqueElementData(static_cast<const UniqueElementData&>(*this)));
3559 return adoptRef(new UniqueElementData(static_cast<const ShareableElementData&>(*this)));
3560}
3561
3562PassRefPtr<ShareableElementData> UniqueElementData::makeShareableCopy() const
3563{
3564 void* slot = WTF::fastMalloc(sizeForShareableElementDataWithAttributeCount(m_attributeVector.size()));
3565 return adoptRef(new (slot) ShareableElementData(*this));
3566}
3567
3568void UniqueElementData::addAttribute(const QualifiedName& attributeName, const AtomicString& value)
3569{
3570 m_attributeVector.append(Attribute(attributeName, value));
3571}
3572
3573void UniqueElementData::removeAttribute(size_t index)
3574{
3575 ASSERT_WITH_SECURITY_IMPLICATION(index < length());
3576 m_attributeVector.remove(index);
3577}
3578
3579bool ElementData::isEquivalent(const ElementData* other) const
3580{
3581 if (!other)
3582 return isEmpty();
3583
3584 unsigned len = length();
3585 if (len != other->length())
3586 return false;
3587
3588 for (unsigned i = 0; i < len; i++) {
3589 const Attribute* attribute = attributeItem(i);
3590 const Attribute* otherAttr = other->getAttributeItem(attribute->name());
3591 if (!otherAttr || attribute->value() != otherAttr->value())
3592 return false;
3593 }
3594
3595 return true;
3596}
3597
Torne (Richard Coles)e5249552013-05-15 11:35:13 +01003598size_t ElementData::getAttrIndex(Attr* attr) const
3599{
3600 // This relies on the fact that Attr's QualifiedName == the Attribute's name.
3601 for (unsigned i = 0; i < length(); ++i) {
3602 if (attributeItem(i)->name() == attr->qualifiedName())
3603 return i;
3604 }
3605 return notFound;
3606}
3607
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01003608size_t ElementData::getAttributeItemIndexSlowCase(const AtomicString& name, bool shouldIgnoreAttributeCase) const
3609{
3610 // Continue to checking case-insensitively and/or full namespaced names if necessary:
3611 for (unsigned i = 0; i < length(); ++i) {
3612 const Attribute* attribute = attributeItem(i);
3613 if (!attribute->name().hasPrefix()) {
3614 if (shouldIgnoreAttributeCase && equalIgnoringCase(name, attribute->localName()))
3615 return i;
3616 } else {
3617 // FIXME: Would be faster to do this comparison without calling toString, which
3618 // generates a temporary string by concatenation. But this branch is only reached
3619 // if the attribute name has a prefix, which is rare in HTML.
3620 if (equalPossiblyIgnoringCase(name, attribute->name().toString(), shouldIgnoreAttributeCase))
3621 return i;
3622 }
3623 }
3624 return notFound;
3625}
3626
3627Attribute* UniqueElementData::getAttributeItem(const QualifiedName& name)
3628{
3629 for (unsigned i = 0; i < length(); ++i) {
3630 if (m_attributeVector.at(i).name().matches(name))
3631 return &m_attributeVector.at(i);
3632 }
3633 return 0;
3634}
3635
3636Attribute* UniqueElementData::attributeItem(unsigned index)
3637{
3638 ASSERT_WITH_SECURITY_IMPLICATION(index < length());
3639 return &m_attributeVector.at(index);
3640}
3641
3642} // namespace WebCore