blob: 5f2ae80d6bac7bdfa77a6dba0bb15ce6ad16eb21 [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 "CSSValueKeywords.h"
Ben Murdoch7757ec22013-07-23 11:17:36 +010030#include "RuntimeEnabledFeatures.h"
Torne (Richard Coles)93ac45c2013-05-29 14:40:20 +010031#include "SVGNames.h"
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +010032#include "XMLNames.h"
Torne (Richard Coles)09380292014-02-21 12:17:33 +000033#include "bindings/v8/Dictionary.h"
Ben Murdochdf957042013-08-06 11:01:27 +010034#include "bindings/v8/ExceptionState.h"
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +010035#include "core/accessibility/AXObjectCache.h"
Ben Murdoch83750172013-07-24 10:36:59 +010036#include "core/animation/DocumentTimeline.h"
Torne (Richard Coles)c0e19a62013-08-30 15:15:11 +010037#include "core/animation/css/CSSAnimations.h"
Ben Murdoch591b9582013-07-10 11:41:44 +010038#include "core/css/CSSStyleSheet.h"
39#include "core/css/CSSValuePool.h"
40#include "core/css/PropertySetCSSStyleDeclaration.h"
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +010041#include "core/css/StylePropertySet.h"
Torne (Richard Coles)09380292014-02-21 12:17:33 +000042#include "core/css/parser/BisonCSSParser.h"
Torne (Richard Coles)81a51572013-05-13 16:52:28 +010043#include "core/css/resolver/StyleResolver.h"
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +010044#include "core/dom/Attr.h"
Torne (Richard Coles)1e202182013-10-18 15:46:42 +010045#include "core/dom/CSSSelectorWatch.h"
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +010046#include "core/dom/ClientRect.h"
47#include "core/dom/ClientRectList.h"
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +010048#include "core/dom/DatasetDOMStringMap.h"
Torne (Richard Coles)09380292014-02-21 12:17:33 +000049#include "core/dom/ElementDataCache.h"
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +010050#include "core/dom/ElementRareData.h"
Torne (Richard Coles)09380292014-02-21 12:17:33 +000051#include "core/dom/ElementTraversal.h"
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +010052#include "core/dom/ExceptionCode.h"
Torne (Richard Coles)f5e4ad52013-08-05 13:57:57 +010053#include "core/dom/FullscreenElementStack.h"
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +010054#include "core/dom/MutationObserverInterestGroup.h"
55#include "core/dom/MutationRecord.h"
56#include "core/dom/NamedNodeMap.h"
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +010057#include "core/dom/NodeRenderStyle.h"
Torne (Richard Coles)8abfc582013-09-12 12:10:38 +010058#include "core/dom/PostAttachCallbacks.h"
Torne (Richard Coles)bfe35902013-10-22 16:41:51 +010059#include "core/dom/PresentationAttributeStyle.h"
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +010060#include "core/dom/PseudoElement.h"
Torne (Richard Coles)09380292014-02-21 12:17:33 +000061#include "core/dom/RenderTreeBuilder.h"
Ben Murdoch591b9582013-07-10 11:41:44 +010062#include "core/dom/ScriptableDocumentParser.h"
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +010063#include "core/dom/SelectorQuery.h"
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +010064#include "core/dom/Text.h"
Torne (Richard Coles)1e202182013-10-18 15:46:42 +010065#include "core/dom/custom/CustomElement.h"
66#include "core/dom/custom/CustomElementRegistrationContext.h"
Torne (Richard Coles)e5249552013-05-15 11:35:13 +010067#include "core/dom/shadow/InsertionPoint.h"
68#include "core/dom/shadow/ShadowRoot.h"
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +010069#include "core/editing/FrameSelection.h"
70#include "core/editing/TextIterator.h"
71#include "core/editing/htmlediting.h"
Torne (Richard Coles)19cde672013-11-06 12:28:04 +000072#include "core/editing/markup.h"
Torne (Richard Coles)1e202182013-10-18 15:46:42 +010073#include "core/events/EventDispatcher.h"
74#include "core/events/FocusEvent.h"
Torne (Richard Coles)bfe35902013-10-22 16:41:51 +010075#include "core/frame/ContentSecurityPolicy.h"
76#include "core/frame/Frame.h"
77#include "core/frame/FrameView.h"
Torne (Richard Coles)09380292014-02-21 12:17:33 +000078#include "core/frame/UseCounter.h"
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +010079#include "core/html/ClassList.h"
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +010080#include "core/html/HTMLCollection.h"
81#include "core/html/HTMLDocument.h"
82#include "core/html/HTMLElement.h"
83#include "core/html/HTMLFormControlsCollection.h"
84#include "core/html/HTMLFrameOwnerElement.h"
85#include "core/html/HTMLLabelElement.h"
86#include "core/html/HTMLOptionsCollection.h"
87#include "core/html/HTMLTableRowsCollection.h"
Torne (Richard Coles)19cde672013-11-06 12:28:04 +000088#include "core/html/HTMLTemplateElement.h"
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +010089#include "core/html/parser/HTMLParserIdioms.h"
Torne (Richard Coles)51b29062013-11-28 11:56:03 +000090#include "core/inspector/InspectorInstrumentation.h"
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +010091#include "core/page/FocusController.h"
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +010092#include "core/page/Page.h"
93#include "core/page/PointerLockController.h"
Torne (Richard Coles)09380292014-02-21 12:17:33 +000094#include "core/rendering/RenderLayer.h"
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +010095#include "core/rendering/RenderView.h"
96#include "core/rendering/RenderWidget.h"
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +010097#include "core/svg/SVGDocumentExtensions.h"
98#include "core/svg/SVGElement.h"
Torne (Richard Coles)09380292014-02-21 12:17:33 +000099#include "platform/scroll/ScrollableArea.h"
Torne (Richard Coles)93ac45c2013-05-29 14:40:20 +0100100#include "wtf/BitVector.h"
Ben Murdoch591b9582013-07-10 11:41:44 +0100101#include "wtf/HashFunctions.h"
Torne (Richard Coles)93ac45c2013-05-29 14:40:20 +0100102#include "wtf/text/CString.h"
Torne (Richard Coles)09380292014-02-21 12:17:33 +0000103#include "wtf/text/StringBuilder.h"
Ben Murdoch591b9582013-07-10 11:41:44 +0100104#include "wtf/text/TextPosition.h"
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100105
106namespace WebCore {
107
108using namespace HTMLNames;
109using namespace XMLNames;
110
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100111class StyleResolverParentPusher {
112public:
Torne (Richard Coles)51b29062013-11-28 11:56:03 +0000113 explicit StyleResolverParentPusher(Element& parent)
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100114 : m_parent(parent)
115 , m_pushedStyleResolver(0)
116 {
117 }
118 void push()
119 {
120 if (m_pushedStyleResolver)
121 return;
Torne (Richard Coles)a854de02013-12-18 16:25:25 +0000122 m_pushedStyleResolver = &m_parent.document().ensureStyleResolver();
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)51b29062013-11-28 11:56:03 +0000133 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:
Torne (Richard Coles)51b29062013-11-28 11:56:03 +0000141 Element& m_parent;
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100142 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
Torne (Richard Coles)bfe35902013-10-22 16:41:51 +0100162static AttrNodeList& ensureAttrNodeListForElement(Element* element)
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100163{
164 if (element->hasSyntheticAttrChildNodes()) {
165 ASSERT(attrNodeListMap().contains(element));
Torne (Richard Coles)bfe35902013-10-22 16:41:51 +0100166 return *attrNodeListMap().get(element);
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100167 }
168 ASSERT(!attrNodeListMap().contains(element));
169 element->setHasSyntheticAttrChildNodes(true);
170 AttrNodeListMap::AddResult result = attrNodeListMap().add(element, adoptPtr(new AttrNodeList));
Torne (Richard Coles)09380292014-02-21 12:17:33 +0000171 return *result.storedValue->value;
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100172}
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
Torne (Richard Coles)51b29062013-11-28 11:56:03 +0000182static Attr* findAttrNodeInList(const AttrNodeList& attrNodeList, const QualifiedName& name)
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100183{
Torne (Richard Coles)51b29062013-11-28 11:56:03 +0000184 AttrNodeList::const_iterator end = attrNodeList.end();
185 for (AttrNodeList::const_iterator it = attrNodeList.begin(); it != end; ++it) {
186 if ((*it)->qualifiedName() == name)
187 return it->get();
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100188 }
189 return 0;
190}
191
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100192PassRefPtr<Element> Element::create(const QualifiedName& tagName, Document* document)
193{
194 return adoptRef(new Element(tagName, document, CreateElement));
195}
196
197Element::~Element()
198{
Torne (Richard Coles)09380292014-02-21 12:17:33 +0000199 ASSERT(needsAttach());
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100200
Torne (Richard Coles)09380292014-02-21 12:17:33 +0000201 if (hasRareData())
202 elementRareData()->clearShadow();
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100203
Ben Murdoch83750172013-07-24 10:36:59 +0100204 if (isCustomElement())
205 CustomElement::wasDestroyed(this);
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100206
207 if (hasSyntheticAttrChildNodes())
208 detachAllAttrNodesFromElement();
209
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100210 if (hasPendingResources()) {
Torne (Richard Coles)8abfc582013-09-12 12:10:38 +0100211 document().accessSVGExtensions()->removeElementFromPendingResources(this);
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100212 ASSERT(!hasPendingResources());
213 }
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100214}
215
216inline ElementRareData* Element::elementRareData() const
217{
218 ASSERT(hasRareData());
219 return static_cast<ElementRareData*>(rareData());
220}
221
Torne (Richard Coles)bfe35902013-10-22 16:41:51 +0100222inline ElementRareData& Element::ensureElementRareData()
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100223{
Torne (Richard Coles)bfe35902013-10-22 16:41:51 +0100224 return static_cast<ElementRareData&>(ensureRareData());
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100225}
226
227void Element::clearTabIndexExplicitlyIfNeeded()
228{
229 if (hasRareData())
230 elementRareData()->clearTabIndexExplicitly();
231}
232
233void Element::setTabIndexExplicitly(short tabIndex)
234{
Torne (Richard Coles)bfe35902013-10-22 16:41:51 +0100235 ensureElementRareData().setTabIndexExplicitly(tabIndex);
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100236}
237
238bool Element::supportsFocus() const
239{
240 return hasRareData() && elementRareData()->tabIndexSetExplicitly();
241}
242
243short Element::tabIndex() const
244{
245 return hasRareData() ? elementRareData()->tabIndex() : 0;
246}
247
Torne (Richard Coles)521d96e2013-06-19 11:58:24 +0100248bool Element::rendererIsFocusable() const
249{
250 // Elements in canvas fallback content are not rendered, but they are allowed to be
251 // focusable as long as their canvas is displayed and visible.
252 if (isInCanvasSubtree()) {
253 const Element* e = this;
254 while (e && !e->hasLocalName(canvasTag))
255 e = e->parentElement();
256 ASSERT(e);
257 return e->renderer() && e->renderer()->style()->visibility() == VISIBLE;
258 }
259
260 // FIXME: These asserts should be in Node::isFocusable, but there are some
Ben Murdoche69819b2013-07-17 14:56:49 +0100261 // callsites like Document::setFocusedElement that would currently fail on
Torne (Richard Coles)521d96e2013-06-19 11:58:24 +0100262 // them. See crbug.com/251163
Torne (Richard Coles)09380292014-02-21 12:17:33 +0000263 if (!renderer()) {
Torne (Richard Coles)521d96e2013-06-19 11:58:24 +0100264 // We can't just use needsStyleRecalc() because if the node is in a
265 // display:none tree it might say it needs style recalc but the whole
266 // document is actually up to date.
Torne (Richard Coles)8abfc582013-09-12 12:10:38 +0100267 ASSERT(!document().childNeedsStyleRecalc());
Torne (Richard Coles)521d96e2013-06-19 11:58:24 +0100268 }
269
270 // FIXME: Even if we are not visible, we might have a child that is visible.
271 // Hyatt wants to fix that some day with a "has visible content" flag or the like.
272 if (!renderer() || renderer()->style()->visibility() != VISIBLE)
273 return false;
274
275 return true;
276}
277
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100278PassRefPtr<Node> Element::cloneNode(bool deep)
279{
280 return deep ? cloneElementWithChildren() : cloneElementWithoutChildren();
281}
282
283PassRefPtr<Element> Element::cloneElementWithChildren()
284{
285 RefPtr<Element> clone = cloneElementWithoutChildren();
286 cloneChildNodes(clone.get());
287 return clone.release();
288}
289
290PassRefPtr<Element> Element::cloneElementWithoutChildren()
291{
292 RefPtr<Element> clone = cloneElementWithoutAttributesAndChildren();
293 // This will catch HTML elements in the wrong namespace that are not correctly copied.
294 // This is a sanity check as HTML overloads some of the DOM methods.
295 ASSERT(isHTMLElement() == clone->isHTMLElement());
296
297 clone->cloneDataFromElement(*this);
298 return clone.release();
299}
300
301PassRefPtr<Element> Element::cloneElementWithoutAttributesAndChildren()
302{
Torne (Richard Coles)8abfc582013-09-12 12:10:38 +0100303 return document().createElement(tagQName(), false);
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100304}
305
306PassRefPtr<Attr> Element::detachAttribute(size_t index)
307{
308 ASSERT(elementData());
Torne (Richard Coles)e5249552013-05-15 11:35:13 +0100309 const Attribute* attribute = elementData()->attributeItem(index);
310 RefPtr<Attr> attrNode = attrIfExists(attribute->name());
311 if (attrNode)
312 detachAttrNodeAtIndex(attrNode.get(), index);
313 else {
314 attrNode = Attr::create(document(), attribute->name(), attribute->value());
315 removeAttributeInternal(index, NotInSynchronizationOfLazyAttribute);
316 }
317 return attrNode.release();
318}
319
320void Element::detachAttrNodeAtIndex(Attr* attr, size_t index)
321{
322 ASSERT(attr);
323 ASSERT(elementData());
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100324
325 const Attribute* attribute = elementData()->attributeItem(index);
326 ASSERT(attribute);
Torne (Richard Coles)e5249552013-05-15 11:35:13 +0100327 ASSERT(attribute->name() == attr->qualifiedName());
328 detachAttrNodeFromElementWithValue(attr, attribute->value());
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100329 removeAttributeInternal(index, NotInSynchronizationOfLazyAttribute);
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100330}
331
332void Element::removeAttribute(const QualifiedName& name)
333{
334 if (!elementData())
335 return;
336
337 size_t index = elementData()->getAttributeItemIndex(name);
Torne (Richard Coles)06f816c2013-09-26 13:25:12 +0100338 if (index == kNotFound)
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100339 return;
340
341 removeAttributeInternal(index, NotInSynchronizationOfLazyAttribute);
342}
343
344void Element::setBooleanAttribute(const QualifiedName& name, bool value)
345{
346 if (value)
347 setAttribute(name, emptyAtom);
348 else
349 removeAttribute(name);
350}
351
352NamedNodeMap* Element::attributes() const
353{
Torne (Richard Coles)bfe35902013-10-22 16:41:51 +0100354 ElementRareData& rareData = const_cast<Element*>(this)->ensureElementRareData();
355 if (NamedNodeMap* attributeMap = rareData.attributeMap())
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100356 return attributeMap;
357
Torne (Richard Coles)bfe35902013-10-22 16:41:51 +0100358 rareData.setAttributeMap(NamedNodeMap::create(const_cast<Element*>(this)));
359 return rareData.attributeMap();
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100360}
361
Ben Murdoch83750172013-07-24 10:36:59 +0100362ActiveAnimations* Element::activeAnimations() const
Torne (Richard Coles)81a51572013-05-13 16:52:28 +0100363{
Torne (Richard Coles)51b29062013-11-28 11:56:03 +0000364 if (hasRareData())
Ben Murdoch83750172013-07-24 10:36:59 +0100365 return elementRareData()->activeAnimations();
366 return 0;
Torne (Richard Coles)81a51572013-05-13 16:52:28 +0100367}
368
Ben Murdoch83750172013-07-24 10:36:59 +0100369ActiveAnimations* Element::ensureActiveAnimations()
Torne (Richard Coles)81a51572013-05-13 16:52:28 +0100370{
Torne (Richard Coles)bfe35902013-10-22 16:41:51 +0100371 ElementRareData& rareData = ensureElementRareData();
372 if (!rareData.activeAnimations())
373 rareData.setActiveAnimations(adoptPtr(new ActiveAnimations()));
374 return rareData.activeAnimations();
Torne (Richard Coles)81a51572013-05-13 16:52:28 +0100375}
376
377bool Element::hasActiveAnimations() const
378{
Ben Murdoch83750172013-07-24 10:36:59 +0100379 if (!hasRareData())
380 return false;
381
382 ActiveAnimations* activeAnimations = elementRareData()->activeAnimations();
383 return activeAnimations && !activeAnimations->isEmpty();
Torne (Richard Coles)81a51572013-05-13 16:52:28 +0100384}
385
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100386Node::NodeType Element::nodeType() const
387{
388 return ELEMENT_NODE;
389}
390
391bool Element::hasAttribute(const QualifiedName& name) const
392{
393 return hasAttributeNS(name.namespaceURI(), name.localName());
394}
395
396void Element::synchronizeAllAttributes() const
397{
398 if (!elementData())
399 return;
Torne (Richard Coles)09380292014-02-21 12:17:33 +0000400 // NOTE: anyAttributeMatches in SelectorChecker.cpp
401 // currently assumes that all lazy attributes have a null namespace.
402 // If that ever changes we'll need to fix that code.
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100403 if (elementData()->m_styleAttributeIsDirty) {
404 ASSERT(isStyledElement());
Ben Murdoch591b9582013-07-10 11:41:44 +0100405 synchronizeStyleAttributeInternal();
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100406 }
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100407 if (elementData()->m_animatedSVGAttributesAreDirty) {
408 ASSERT(isSVGElement());
409 toSVGElement(this)->synchronizeAnimatedSVGAttribute(anyQName());
410 }
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100411}
412
413inline void Element::synchronizeAttribute(const QualifiedName& name) const
414{
415 if (!elementData())
416 return;
417 if (UNLIKELY(name == styleAttr && elementData()->m_styleAttributeIsDirty)) {
418 ASSERT(isStyledElement());
Ben Murdoch591b9582013-07-10 11:41:44 +0100419 synchronizeStyleAttributeInternal();
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100420 return;
421 }
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100422 if (UNLIKELY(elementData()->m_animatedSVGAttributesAreDirty)) {
423 ASSERT(isSVGElement());
Torne (Richard Coles)09380292014-02-21 12:17:33 +0000424 // See comment in the AtomicString version of synchronizeAttribute()
425 // also.
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100426 toSVGElement(this)->synchronizeAnimatedSVGAttribute(name);
427 }
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100428}
429
Torne (Richard Coles)a854de02013-12-18 16:25:25 +0000430void Element::synchronizeAttribute(const AtomicString& localName) const
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100431{
432 // This version of synchronizeAttribute() is streamlined for the case where you don't have a full QualifiedName,
433 // e.g when called from DOM API.
434 if (!elementData())
435 return;
Torne (Richard Coles)bfe35902013-10-22 16:41:51 +0100436 if (elementData()->m_styleAttributeIsDirty && equalPossiblyIgnoringCase(localName, styleAttr.localName(), shouldIgnoreAttributeCase())) {
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100437 ASSERT(isStyledElement());
Ben Murdoch591b9582013-07-10 11:41:44 +0100438 synchronizeStyleAttributeInternal();
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100439 return;
440 }
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100441 if (elementData()->m_animatedSVGAttributesAreDirty) {
442 // We're not passing a namespace argument on purpose. SVGNames::*Attr are defined w/o namespaces as well.
Torne (Richard Coles)09380292014-02-21 12:17:33 +0000443
444 // FIXME: this code is called regardless of whether name is an
445 // animated SVG Attribute. It would seem we should only call this method
446 // if SVGElement::isAnimatableAttribute is true, but the list of
447 // animatable attributes in isAnimatableAttribute does not suffice to
448 // pass all layout tests. Also, m_animatedSVGAttributesAreDirty stays
449 // dirty unless synchronizeAnimatedSVGAttribute is called with
450 // anyQName(). This means that even if Element::synchronizeAttribute()
451 // is called on all attributes, m_animatedSVGAttributesAreDirty remains
452 // true.
453 toSVGElement(this)->synchronizeAnimatedSVGAttribute(QualifiedName(nullAtom, localName, nullAtom));
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100454 }
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100455}
456
457const AtomicString& Element::getAttribute(const QualifiedName& name) const
458{
459 if (!elementData())
460 return nullAtom;
461 synchronizeAttribute(name);
462 if (const Attribute* attribute = getAttributeItem(name))
463 return attribute->value();
464 return nullAtom;
465}
466
Ben Murdoch591b9582013-07-10 11:41:44 +0100467void Element::scrollIntoView(bool alignToTop)
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100468{
Torne (Richard Coles)8abfc582013-09-12 12:10:38 +0100469 document().updateLayoutIgnorePendingStylesheets();
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100470
471 if (!renderer())
472 return;
473
474 LayoutRect bounds = boundingBox();
475 // Align to the top / bottom and to the closest edge.
476 if (alignToTop)
477 renderer()->scrollRectToVisible(bounds, ScrollAlignment::alignToEdgeIfNeeded, ScrollAlignment::alignTopAlways);
478 else
479 renderer()->scrollRectToVisible(bounds, ScrollAlignment::alignToEdgeIfNeeded, ScrollAlignment::alignBottomAlways);
480}
481
482void Element::scrollIntoViewIfNeeded(bool centerIfNeeded)
483{
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 if (centerIfNeeded)
491 renderer()->scrollRectToVisible(bounds, ScrollAlignment::alignCenterIfNeeded, ScrollAlignment::alignCenterIfNeeded);
492 else
493 renderer()->scrollRectToVisible(bounds, ScrollAlignment::alignToEdgeIfNeeded, ScrollAlignment::alignToEdgeIfNeeded);
494}
495
496void Element::scrollByUnits(int units, ScrollGranularity granularity)
497{
Torne (Richard Coles)8abfc582013-09-12 12:10:38 +0100498 document().updateLayoutIgnorePendingStylesheets();
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100499
500 if (!renderer())
501 return;
502
503 if (!renderer()->hasOverflowClip())
504 return;
505
506 ScrollDirection direction = ScrollDown;
507 if (units < 0) {
508 direction = ScrollUp;
509 units = -units;
510 }
Torne (Richard Coles)a854de02013-12-18 16:25:25 +0000511 toRenderBox(renderer())->scroll(direction, granularity, units);
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100512}
513
514void Element::scrollByLines(int lines)
515{
516 scrollByUnits(lines, ScrollByLine);
517}
518
519void Element::scrollByPages(int pages)
520{
521 scrollByUnits(pages, ScrollByPage);
522}
523
Torne (Richard Coles)51b29062013-11-28 11:56:03 +0000524static float localZoomForRenderer(RenderObject& renderer)
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100525{
526 // FIXME: This does the wrong thing if two opposing zooms are in effect and canceled each
527 // other out, but the alternative is that we'd have to crawl up the whole render tree every
528 // time (or store an additional bit in the RenderStyle to indicate that a zoom was specified).
529 float zoomFactor = 1;
Torne (Richard Coles)51b29062013-11-28 11:56:03 +0000530 if (renderer.style()->effectiveZoom() != 1) {
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100531 // Need to find the nearest enclosing RenderObject that set up
532 // a differing zoom, and then we divide our result by it to eliminate the zoom.
Torne (Richard Coles)51b29062013-11-28 11:56:03 +0000533 RenderObject* prev = &renderer;
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100534 for (RenderObject* curr = prev->parent(); curr; curr = curr->parent()) {
535 if (curr->style()->effectiveZoom() != prev->style()->effectiveZoom()) {
536 zoomFactor = prev->style()->zoom();
537 break;
538 }
539 prev = curr;
540 }
541 if (prev->isRenderView())
542 zoomFactor = prev->style()->zoom();
543 }
544 return zoomFactor;
545}
546
Torne (Richard Coles)51b29062013-11-28 11:56:03 +0000547static int adjustForLocalZoom(LayoutUnit value, RenderObject& renderer)
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100548{
549 float zoomFactor = localZoomForRenderer(renderer);
550 if (zoomFactor == 1)
551 return value;
552 return lroundf(value / zoomFactor);
553}
554
555int Element::offsetLeft()
556{
Torne (Richard Coles)8abfc582013-09-12 12:10:38 +0100557 document().partialUpdateLayoutIgnorePendingStylesheets(this);
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100558 if (RenderBoxModelObject* renderer = renderBoxModelObject())
Torne (Richard Coles)51b29062013-11-28 11:56:03 +0000559 return adjustForLocalZoom(renderer->pixelSnappedOffsetLeft(), *renderer);
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100560 return 0;
561}
562
563int Element::offsetTop()
564{
Torne (Richard Coles)8abfc582013-09-12 12:10:38 +0100565 document().partialUpdateLayoutIgnorePendingStylesheets(this);
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100566 if (RenderBoxModelObject* renderer = renderBoxModelObject())
Torne (Richard Coles)51b29062013-11-28 11:56:03 +0000567 return adjustForLocalZoom(renderer->pixelSnappedOffsetTop(), *renderer);
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100568 return 0;
569}
570
571int Element::offsetWidth()
572{
Torne (Richard Coles)8abfc582013-09-12 12:10:38 +0100573 document().updateStyleForNodeIfNeeded(this);
Ben Murdoch591b9582013-07-10 11:41:44 +0100574
575 if (RenderBox* renderer = renderBox()) {
Torne (Richard Coles)1e202182013-10-18 15:46:42 +0100576 if (renderer->canDetermineWidthWithoutLayout())
Torne (Richard Coles)51b29062013-11-28 11:56:03 +0000577 return adjustLayoutUnitForAbsoluteZoom(renderer->fixedOffsetWidth(), *renderer).round();
Ben Murdoch591b9582013-07-10 11:41:44 +0100578 }
579
Torne (Richard Coles)8abfc582013-09-12 12:10:38 +0100580 document().partialUpdateLayoutIgnorePendingStylesheets(this);
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100581 if (RenderBoxModelObject* renderer = renderBoxModelObject())
Torne (Richard Coles)51b29062013-11-28 11:56:03 +0000582 return adjustLayoutUnitForAbsoluteZoom(renderer->pixelSnappedOffsetWidth(), *renderer).round();
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100583 return 0;
584}
585
586int Element::offsetHeight()
587{
Torne (Richard Coles)8abfc582013-09-12 12:10:38 +0100588 document().partialUpdateLayoutIgnorePendingStylesheets(this);
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100589 if (RenderBoxModelObject* renderer = renderBoxModelObject())
Torne (Richard Coles)51b29062013-11-28 11:56:03 +0000590 return adjustLayoutUnitForAbsoluteZoom(renderer->pixelSnappedOffsetHeight(), *renderer).round();
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100591 return 0;
592}
593
Torne (Richard Coles)09380292014-02-21 12:17:33 +0000594Element* Element::offsetParentForBindings()
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100595{
596 Element* element = offsetParent();
597 if (!element || !element->isInShadowTree())
598 return element;
Torne (Richard Coles)521d96e2013-06-19 11:58:24 +0100599 return element->containingShadowRoot()->shouldExposeToBindings() ? element : 0;
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100600}
601
602Element* Element::offsetParent()
603{
Torne (Richard Coles)8abfc582013-09-12 12:10:38 +0100604 document().updateLayoutIgnorePendingStylesheets();
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100605 if (RenderObject* renderer = this->renderer())
606 return renderer->offsetParent();
607 return 0;
608}
609
610int Element::clientLeft()
611{
Torne (Richard Coles)8abfc582013-09-12 12:10:38 +0100612 document().updateLayoutIgnorePendingStylesheets();
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100613
614 if (RenderBox* renderer = renderBox())
615 return adjustForAbsoluteZoom(roundToInt(renderer->clientLeft()), renderer);
616 return 0;
617}
618
619int Element::clientTop()
620{
Torne (Richard Coles)8abfc582013-09-12 12:10:38 +0100621 document().updateLayoutIgnorePendingStylesheets();
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100622
623 if (RenderBox* renderer = renderBox())
624 return adjustForAbsoluteZoom(roundToInt(renderer->clientTop()), renderer);
625 return 0;
626}
627
628int Element::clientWidth()
629{
Torne (Richard Coles)8abfc582013-09-12 12:10:38 +0100630 document().updateLayoutIgnorePendingStylesheets();
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100631
632 // When in strict mode, clientWidth for the document element should return the width of the containing frame.
633 // 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 +0100634 bool inQuirksMode = document().inQuirksMode();
635 if ((!inQuirksMode && document().documentElement() == this)
636 || (inQuirksMode && isHTMLElement() && document().body() == this)) {
637 if (FrameView* view = document().view()) {
638 if (RenderView* renderView = document().renderView())
Torne (Richard Coles)bfe35902013-10-22 16:41:51 +0100639 return adjustForAbsoluteZoom(view->layoutSize().width(), renderView);
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100640 }
641 }
Ben Murdoch591b9582013-07-10 11:41:44 +0100642
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100643 if (RenderBox* renderer = renderBox())
Torne (Richard Coles)51b29062013-11-28 11:56:03 +0000644 return adjustLayoutUnitForAbsoluteZoom(renderer->pixelSnappedClientWidth(), *renderer).round();
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100645 return 0;
646}
647
648int Element::clientHeight()
649{
Torne (Richard Coles)8abfc582013-09-12 12:10:38 +0100650 document().updateLayoutIgnorePendingStylesheets();
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100651
652 // When in strict mode, clientHeight for the document element should return the height of the containing frame.
653 // 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 +0100654 bool inQuirksMode = document().inQuirksMode();
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100655
Torne (Richard Coles)8abfc582013-09-12 12:10:38 +0100656 if ((!inQuirksMode && document().documentElement() == this)
657 || (inQuirksMode && isHTMLElement() && document().body() == this)) {
658 if (FrameView* view = document().view()) {
659 if (RenderView* renderView = document().renderView())
Torne (Richard Coles)bfe35902013-10-22 16:41:51 +0100660 return adjustForAbsoluteZoom(view->layoutSize().height(), renderView);
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100661 }
662 }
Ben Murdoch591b9582013-07-10 11:41:44 +0100663
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100664 if (RenderBox* renderer = renderBox())
Torne (Richard Coles)51b29062013-11-28 11:56:03 +0000665 return adjustLayoutUnitForAbsoluteZoom(renderer->pixelSnappedClientHeight(), *renderer).round();
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100666 return 0;
667}
668
669int Element::scrollLeft()
670{
Torne (Richard Coles)8abfc582013-09-12 12:10:38 +0100671 document().updateLayoutIgnorePendingStylesheets();
Torne (Richard Coles)1e202182013-10-18 15:46:42 +0100672
Torne (Richard Coles)51b29062013-11-28 11:56:03 +0000673 if (document().documentElement() != this) {
674 if (RenderBox* rend = renderBox())
675 return adjustForAbsoluteZoom(rend->scrollLeft(), rend);
676 return 0;
677 }
678
679 if (RuntimeEnabledFeatures::scrollTopLeftInteropEnabled()) {
Torne (Richard Coles)1e202182013-10-18 15:46:42 +0100680 if (document().inQuirksMode())
681 return 0;
682
683 if (FrameView* view = document().view()) {
684 if (RenderView* renderView = document().renderView())
685 return adjustForAbsoluteZoom(view->scrollX(), renderView);
686 }
687 }
688
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100689 return 0;
690}
691
692int Element::scrollTop()
693{
Torne (Richard Coles)8abfc582013-09-12 12:10:38 +0100694 document().updateLayoutIgnorePendingStylesheets();
Torne (Richard Coles)1e202182013-10-18 15:46:42 +0100695
Torne (Richard Coles)51b29062013-11-28 11:56:03 +0000696 if (document().documentElement() != this) {
697 if (RenderBox* rend = renderBox())
698 return adjustForAbsoluteZoom(rend->scrollTop(), rend);
699 return 0;
700 }
701
702 if (RuntimeEnabledFeatures::scrollTopLeftInteropEnabled()) {
Torne (Richard Coles)1e202182013-10-18 15:46:42 +0100703 if (document().inQuirksMode())
704 return 0;
705
706 if (FrameView* view = document().view()) {
707 if (RenderView* renderView = document().renderView())
708 return adjustForAbsoluteZoom(view->scrollY(), renderView);
709 }
710 }
711
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100712 return 0;
713}
714
715void Element::setScrollLeft(int newLeft)
716{
Torne (Richard Coles)8abfc582013-09-12 12:10:38 +0100717 document().updateLayoutIgnorePendingStylesheets();
Torne (Richard Coles)1e202182013-10-18 15:46:42 +0100718
Torne (Richard Coles)51b29062013-11-28 11:56:03 +0000719 if (document().documentElement() != this) {
720 if (RenderBox* rend = renderBox())
721 rend->setScrollLeft(static_cast<int>(newLeft * rend->style()->effectiveZoom()));
722 return;
723 }
724
725 if (RuntimeEnabledFeatures::scrollTopLeftInteropEnabled()) {
Torne (Richard Coles)1e202182013-10-18 15:46:42 +0100726 if (document().inQuirksMode())
727 return;
728
729 Frame* frame = document().frame();
730 if (!frame)
731 return;
732 FrameView* view = frame->view();
733 if (!view)
734 return;
735
Torne (Richard Coles)1e202182013-10-18 15:46:42 +0100736 view->setScrollPosition(IntPoint(static_cast<int>(newLeft * frame->pageZoomFactor()), view->scrollY()));
737 }
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100738}
739
Torne (Richard Coles)09380292014-02-21 12:17:33 +0000740void Element::setScrollLeft(const Dictionary& scrollOptionsHorizontal, ExceptionState& exceptionState)
741{
742 String scrollBehaviorString;
743 ScrollBehavior scrollBehavior = ScrollBehaviorAuto;
744 if (scrollOptionsHorizontal.get("behavior", scrollBehaviorString)) {
745 if (!ScrollableArea::scrollBehaviorFromString(scrollBehaviorString, scrollBehavior)) {
746 exceptionState.throwTypeError("The ScrollBehavior provided is invalid.");
747 return;
748 }
749 }
750
751 int position;
752 if (!scrollOptionsHorizontal.get("x", position)) {
753 exceptionState.throwTypeError("ScrollOptionsHorizontal must include an 'x' member.");
754 return;
755 }
756
757 // FIXME: Use scrollBehavior to decide whether to scroll smoothly or instantly.
758 setScrollLeft(position);
759}
760
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100761void Element::setScrollTop(int newTop)
762{
Torne (Richard Coles)8abfc582013-09-12 12:10:38 +0100763 document().updateLayoutIgnorePendingStylesheets();
Torne (Richard Coles)1e202182013-10-18 15:46:42 +0100764
Torne (Richard Coles)51b29062013-11-28 11:56:03 +0000765 if (document().documentElement() != this) {
766 if (RenderBox* rend = renderBox())
767 rend->setScrollTop(static_cast<int>(newTop * rend->style()->effectiveZoom()));
768 return;
769 }
770
771 if (RuntimeEnabledFeatures::scrollTopLeftInteropEnabled()) {
Torne (Richard Coles)1e202182013-10-18 15:46:42 +0100772 if (document().inQuirksMode())
773 return;
774
775 Frame* frame = document().frame();
776 if (!frame)
777 return;
778 FrameView* view = frame->view();
779 if (!view)
780 return;
781
Torne (Richard Coles)1e202182013-10-18 15:46:42 +0100782 view->setScrollPosition(IntPoint(view->scrollX(), static_cast<int>(newTop * frame->pageZoomFactor())));
783 }
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100784}
785
Torne (Richard Coles)09380292014-02-21 12:17:33 +0000786void Element::setScrollTop(const Dictionary& scrollOptionsVertical, ExceptionState& exceptionState)
787{
788 String scrollBehaviorString;
789 ScrollBehavior scrollBehavior = ScrollBehaviorAuto;
790 if (scrollOptionsVertical.get("behavior", scrollBehaviorString)) {
791 if (!ScrollableArea::scrollBehaviorFromString(scrollBehaviorString, scrollBehavior)) {
792 exceptionState.throwTypeError("The ScrollBehavior provided is invalid.");
793 return;
794 }
795 }
796
797 int position;
798 if (!scrollOptionsVertical.get("y", position)) {
799 exceptionState.throwTypeError("ScrollOptionsVertical must include a 'y' member.");
800 return;
801 }
802
803 // FIXME: Use scrollBehavior to decide whether to scroll smoothly or instantly.
804 setScrollTop(position);
805}
806
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100807int Element::scrollWidth()
808{
Torne (Richard Coles)8abfc582013-09-12 12:10:38 +0100809 document().updateLayoutIgnorePendingStylesheets();
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100810 if (RenderBox* rend = renderBox())
811 return adjustForAbsoluteZoom(rend->scrollWidth(), rend);
812 return 0;
813}
814
815int Element::scrollHeight()
816{
Torne (Richard Coles)8abfc582013-09-12 12:10:38 +0100817 document().updateLayoutIgnorePendingStylesheets();
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100818 if (RenderBox* rend = renderBox())
819 return adjustForAbsoluteZoom(rend->scrollHeight(), rend);
820 return 0;
821}
822
823IntRect Element::boundsInRootViewSpace()
824{
Torne (Richard Coles)8abfc582013-09-12 12:10:38 +0100825 document().updateLayoutIgnorePendingStylesheets();
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100826
Torne (Richard Coles)8abfc582013-09-12 12:10:38 +0100827 FrameView* view = document().view();
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100828 if (!view)
829 return IntRect();
830
831 Vector<FloatQuad> quads;
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100832 if (isSVGElement() && renderer()) {
833 // Get the bounding rectangle from the SVG model.
834 SVGElement* svgElement = toSVGElement(this);
835 FloatRect localRect;
836 if (svgElement->getBoundingBox(localRect))
837 quads.append(renderer()->localToAbsoluteQuad(localRect));
Torne (Richard Coles)93ac45c2013-05-29 14:40:20 +0100838 } else {
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100839 // Get the bounding rectangle from the box model.
840 if (renderBoxModelObject())
841 renderBoxModelObject()->absoluteQuads(quads);
842 }
843
844 if (quads.isEmpty())
845 return IntRect();
846
847 IntRect result = quads[0].enclosingBoundingBox();
848 for (size_t i = 1; i < quads.size(); ++i)
849 result.unite(quads[i].enclosingBoundingBox());
850
851 result = view->contentsToRootView(result);
852 return result;
853}
854
855PassRefPtr<ClientRectList> Element::getClientRects()
856{
Torne (Richard Coles)8abfc582013-09-12 12:10:38 +0100857 document().updateLayoutIgnorePendingStylesheets();
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100858
859 RenderBoxModelObject* renderBoxModelObject = this->renderBoxModelObject();
860 if (!renderBoxModelObject)
861 return ClientRectList::create();
862
863 // FIXME: Handle SVG elements.
864 // FIXME: Handle table/inline-table with a caption.
865
866 Vector<FloatQuad> quads;
867 renderBoxModelObject->absoluteQuads(quads);
Torne (Richard Coles)51b29062013-11-28 11:56:03 +0000868 document().adjustFloatQuadsForScrollAndAbsoluteZoom(quads, *renderBoxModelObject);
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100869 return ClientRectList::create(quads);
870}
871
872PassRefPtr<ClientRect> Element::getBoundingClientRect()
873{
Torne (Richard Coles)8abfc582013-09-12 12:10:38 +0100874 document().updateLayoutIgnorePendingStylesheets();
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100875
876 Vector<FloatQuad> quads;
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100877 if (isSVGElement() && renderer() && !renderer()->isSVGRoot()) {
878 // Get the bounding rectangle from the SVG model.
879 SVGElement* svgElement = toSVGElement(this);
880 FloatRect localRect;
881 if (svgElement->getBoundingBox(localRect))
882 quads.append(renderer()->localToAbsoluteQuad(localRect));
Torne (Richard Coles)93ac45c2013-05-29 14:40:20 +0100883 } else {
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100884 // Get the bounding rectangle from the box model.
885 if (renderBoxModelObject())
886 renderBoxModelObject()->absoluteQuads(quads);
887 }
888
889 if (quads.isEmpty())
890 return ClientRect::create();
891
892 FloatRect result = quads[0].boundingBox();
893 for (size_t i = 1; i < quads.size(); ++i)
894 result.unite(quads[i].boundingBox());
895
Torne (Richard Coles)51b29062013-11-28 11:56:03 +0000896 ASSERT(renderer());
897 document().adjustFloatRectForScrollAndAbsoluteZoom(result, *renderer());
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100898 return ClientRect::create(result);
899}
Ben Murdoch591b9582013-07-10 11:41:44 +0100900
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100901IntRect Element::screenRect() const
902{
903 if (!renderer())
904 return IntRect();
905 // FIXME: this should probably respect transforms
Torne (Richard Coles)8abfc582013-09-12 12:10:38 +0100906 return document().view()->contentsToScreen(renderer()->absoluteBoundingBoxRectIgnoringTransforms());
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100907}
908
909const AtomicString& Element::getAttribute(const AtomicString& localName) const
910{
911 if (!elementData())
912 return nullAtom;
913 synchronizeAttribute(localName);
Torne (Richard Coles)bfe35902013-10-22 16:41:51 +0100914 if (const Attribute* attribute = elementData()->getAttributeItem(localName, shouldIgnoreAttributeCase()))
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100915 return attribute->value();
916 return nullAtom;
917}
918
919const AtomicString& Element::getAttributeNS(const AtomicString& namespaceURI, const AtomicString& localName) const
920{
921 return getAttribute(QualifiedName(nullAtom, localName, namespaceURI));
922}
923
Torne (Richard Coles)51b29062013-11-28 11:56:03 +0000924void Element::setAttribute(const AtomicString& localName, const AtomicString& value, ExceptionState& exceptionState)
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100925{
926 if (!Document::isValidName(localName)) {
Torne (Richard Coles)09380292014-02-21 12:17:33 +0000927 exceptionState.throwDOMException(InvalidCharacterError, "'" + localName + "' is not a valid attribute name.");
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100928 return;
929 }
930
931 synchronizeAttribute(localName);
Torne (Richard Coles)bfe35902013-10-22 16:41:51 +0100932 const AtomicString& caseAdjustedLocalName = shouldIgnoreAttributeCase() ? localName.lower() : localName;
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100933
Torne (Richard Coles)06f816c2013-09-26 13:25:12 +0100934 size_t index = elementData() ? elementData()->getAttributeItemIndex(caseAdjustedLocalName, false) : kNotFound;
935 const QualifiedName& qName = index != kNotFound ? attributeItem(index)->name() : QualifiedName(nullAtom, caseAdjustedLocalName, nullAtom);
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100936 setAttributeInternal(index, qName, value, NotInSynchronizationOfLazyAttribute);
937}
938
939void Element::setAttribute(const QualifiedName& name, const AtomicString& value)
940{
941 synchronizeAttribute(name);
Torne (Richard Coles)06f816c2013-09-26 13:25:12 +0100942 size_t index = elementData() ? elementData()->getAttributeItemIndex(name) : kNotFound;
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100943 setAttributeInternal(index, name, value, NotInSynchronizationOfLazyAttribute);
944}
945
946void Element::setSynchronizedLazyAttribute(const QualifiedName& name, const AtomicString& value)
947{
Torne (Richard Coles)06f816c2013-09-26 13:25:12 +0100948 size_t index = elementData() ? elementData()->getAttributeItemIndex(name) : kNotFound;
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100949 setAttributeInternal(index, name, value, InSynchronizationOfLazyAttribute);
950}
951
Torne (Richard Coles)51b29062013-11-28 11:56:03 +0000952ALWAYS_INLINE void Element::setAttributeInternal(size_t index, const QualifiedName& name, const AtomicString& newValue, SynchronizationOfLazyAttribute inSynchronizationOfLazyAttribute)
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100953{
954 if (newValue.isNull()) {
Torne (Richard Coles)06f816c2013-09-26 13:25:12 +0100955 if (index != kNotFound)
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100956 removeAttributeInternal(index, inSynchronizationOfLazyAttribute);
957 return;
958 }
959
Torne (Richard Coles)06f816c2013-09-26 13:25:12 +0100960 if (index == kNotFound) {
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100961 addAttributeInternal(name, newValue, inSynchronizationOfLazyAttribute);
962 return;
963 }
964
Torne (Richard Coles)51b29062013-11-28 11:56:03 +0000965 const Attribute* existingAttribute = attributeItem(index);
966 QualifiedName existingAttributeName = existingAttribute->name();
Torne (Richard Coles)8abfc582013-09-12 12:10:38 +0100967
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100968 if (!inSynchronizationOfLazyAttribute)
Torne (Richard Coles)51b29062013-11-28 11:56:03 +0000969 willModifyAttribute(existingAttributeName, existingAttribute->value(), newValue);
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100970
Torne (Richard Coles)51b29062013-11-28 11:56:03 +0000971 if (newValue != existingAttribute->value()) {
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100972 // If there is an Attr node hooked to this attribute, the Attr::setValue() call below
973 // will write into the ElementData.
974 // FIXME: Refactor this so it makes some sense.
Torne (Richard Coles)8abfc582013-09-12 12:10:38 +0100975 if (RefPtr<Attr> attrNode = inSynchronizationOfLazyAttribute ? 0 : attrIfExists(existingAttributeName))
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100976 attrNode->setValue(newValue);
977 else
978 ensureUniqueElementData()->attributeItem(index)->setValue(newValue);
979 }
980
981 if (!inSynchronizationOfLazyAttribute)
Torne (Richard Coles)8abfc582013-09-12 12:10:38 +0100982 didModifyAttribute(existingAttributeName, newValue);
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100983}
984
985static inline AtomicString makeIdForStyleResolution(const AtomicString& value, bool inQuirksMode)
986{
987 if (inQuirksMode)
988 return value.lower();
989 return value;
990}
991
Ben Murdoch7757ec22013-07-23 11:17:36 +0100992static bool checkNeedsStyleInvalidationForIdChange(const AtomicString& oldId, const AtomicString& newId, const RuleFeatureSet& features)
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100993{
994 ASSERT(newId != oldId);
Ben Murdoch7757ec22013-07-23 11:17:36 +0100995 if (!oldId.isEmpty() && features.hasSelectorForId(oldId))
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100996 return true;
Ben Murdoch7757ec22013-07-23 11:17:36 +0100997 if (!newId.isEmpty() && features.hasSelectorForId(newId))
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100998 return true;
999 return false;
1000}
1001
Ben Murdoch591b9582013-07-10 11:41:44 +01001002void Element::attributeChanged(const QualifiedName& name, const AtomicString& newValue, AttributeModificationReason reason)
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001003{
Torne (Richard Coles)19cde672013-11-06 12:28:04 +00001004 if (ElementShadow* parentElementShadow = shadowWhereNodeCanBeDistributed(*this)) {
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001005 if (shouldInvalidateDistributionWhenAttributeChanged(parentElementShadow, name, newValue))
Torne (Richard Coles)f5e4ad52013-08-05 13:57:57 +01001006 parentElementShadow->setNeedsDistributionRecalc();
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001007 }
1008
1009 parseAttribute(name, newValue);
1010
Torne (Richard Coles)8abfc582013-09-12 12:10:38 +01001011 document().incDOMTreeVersion();
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001012
Torne (Richard Coles)a854de02013-12-18 16:25:25 +00001013 StyleResolver* styleResolver = document().styleResolver();
Torne (Richard Coles)f79f16f2013-10-31 11:16:44 +00001014 bool testShouldInvalidateStyle = inActiveDocument() && styleResolver && styleChangeType() < SubtreeStyleChange;
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001015 bool shouldInvalidateStyle = false;
1016
Ben Murdoch591b9582013-07-10 11:41:44 +01001017 if (isStyledElement() && name == styleAttr) {
1018 styleAttributeChanged(newValue, reason);
1019 } else if (isStyledElement() && isPresentationAttribute(name)) {
1020 elementData()->m_presentationAttributeStyleIsDirty = true;
Ben Murdoche69819b2013-07-17 14:56:49 +01001021 setNeedsStyleRecalc(LocalStyleChange);
Ben Murdoch591b9582013-07-10 11:41:44 +01001022 }
1023
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001024 if (isIdAttributeName(name)) {
1025 AtomicString oldId = elementData()->idForStyleResolution();
Torne (Richard Coles)8abfc582013-09-12 12:10:38 +01001026 AtomicString newId = makeIdForStyleResolution(newValue, document().inQuirksMode());
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001027 if (newId != oldId) {
1028 elementData()->setIdForStyleResolution(newId);
Torne (Richard Coles)51b29062013-11-28 11:56:03 +00001029 shouldInvalidateStyle = testShouldInvalidateStyle && checkNeedsStyleInvalidationForIdChange(oldId, newId, styleResolver->ensureRuleFeatureSet());
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001030 }
Ben Murdoch591b9582013-07-10 11:41:44 +01001031 } else if (name == classAttr) {
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001032 classAttributeChanged(newValue);
Ben Murdoch591b9582013-07-10 11:41:44 +01001033 } else if (name == HTMLNames::nameAttr) {
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001034 setHasName(!newValue.isNull());
Ben Murdoch591b9582013-07-10 11:41:44 +01001035 }
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001036
1037 invalidateNodeListCachesInAncestors(&name, this);
1038
1039 // If there is currently no StyleResolver, we can't be sure that this attribute change won't affect style.
1040 shouldInvalidateStyle |= !styleResolver;
1041
1042 if (shouldInvalidateStyle)
Torne (Richard Coles)09380292014-02-21 12:17:33 +00001043 setNeedsStyleRecalc(SubtreeStyleChange);
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001044
Torne (Richard Coles)8abfc582013-09-12 12:10:38 +01001045 if (AXObjectCache* cache = document().existingAXObjectCache())
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001046 cache->handleAttributeChanged(name, this);
1047}
1048
1049inline void Element::attributeChangedFromParserOrByCloning(const QualifiedName& name, const AtomicString& newValue, AttributeModificationReason reason)
1050{
Ben Murdoche69819b2013-07-17 14:56:49 +01001051 if (name == isAttr)
Torne (Richard Coles)51b29062013-11-28 11:56:03 +00001052 CustomElementRegistrationContext::setTypeExtension(this, newValue);
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001053 attributeChanged(name, newValue, reason);
1054}
1055
1056template <typename CharacterType>
1057static inline bool classStringHasClassName(const CharacterType* characters, unsigned length)
1058{
1059 ASSERT(length > 0);
1060
1061 unsigned i = 0;
1062 do {
Torne (Richard Coles)06f816c2013-09-26 13:25:12 +01001063 if (isNotHTMLSpace<CharacterType>(characters[i]))
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001064 break;
1065 ++i;
1066 } while (i < length);
1067
1068 return i < length;
1069}
1070
1071static inline bool classStringHasClassName(const AtomicString& newClassString)
1072{
1073 unsigned length = newClassString.length();
1074
1075 if (!length)
1076 return false;
1077
1078 if (newClassString.is8Bit())
1079 return classStringHasClassName(newClassString.characters8(), length);
1080 return classStringHasClassName(newClassString.characters16(), length);
1081}
1082
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001083void Element::classAttributeChanged(const AtomicString& newClassString)
1084{
Torne (Richard Coles)a854de02013-12-18 16:25:25 +00001085 StyleResolver* styleResolver = document().styleResolver();
Torne (Richard Coles)f79f16f2013-10-31 11:16:44 +00001086 bool testShouldInvalidateStyle = inActiveDocument() && styleResolver && styleChangeType() < SubtreeStyleChange;
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001087
1088 if (classStringHasClassName(newClassString)) {
Torne (Richard Coles)8abfc582013-09-12 12:10:38 +01001089 const bool shouldFoldCase = document().inQuirksMode();
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001090 const SpaceSplitString oldClasses = elementData()->classNames();
1091 elementData()->setClass(newClassString, shouldFoldCase);
1092 const SpaceSplitString& newClasses = elementData()->classNames();
Torne (Richard Coles)09380292014-02-21 12:17:33 +00001093 if (testShouldInvalidateStyle)
1094 styleResolver->ensureRuleFeatureSet().scheduleStyleInvalidationForClassChange(oldClasses, newClasses, this);
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001095 } else {
1096 const SpaceSplitString& oldClasses = elementData()->classNames();
Torne (Richard Coles)09380292014-02-21 12:17:33 +00001097 if (testShouldInvalidateStyle)
1098 styleResolver->ensureRuleFeatureSet().scheduleStyleInvalidationForClassChange(oldClasses, this);
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001099 elementData()->clearClass();
1100 }
1101
1102 if (hasRareData())
1103 elementRareData()->clearClassListValueForQuirksMode();
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001104}
1105
1106bool Element::shouldInvalidateDistributionWhenAttributeChanged(ElementShadow* elementShadow, const QualifiedName& name, const AtomicString& newValue)
1107{
1108 ASSERT(elementShadow);
Torne (Richard Coles)e1f1df52013-08-23 16:39:30 +01001109 const SelectRuleFeatureSet& featureSet = elementShadow->ensureSelectFeatureSet();
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001110
1111 if (isIdAttributeName(name)) {
1112 AtomicString oldId = elementData()->idForStyleResolution();
Torne (Richard Coles)8abfc582013-09-12 12:10:38 +01001113 AtomicString newId = makeIdForStyleResolution(newValue, document().inQuirksMode());
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001114 if (newId != oldId) {
1115 if (!oldId.isEmpty() && featureSet.hasSelectorForId(oldId))
1116 return true;
1117 if (!newId.isEmpty() && featureSet.hasSelectorForId(newId))
1118 return true;
1119 }
1120 }
1121
1122 if (name == HTMLNames::classAttr) {
1123 const AtomicString& newClassString = newValue;
1124 if (classStringHasClassName(newClassString)) {
Torne (Richard Coles)8abfc582013-09-12 12:10:38 +01001125 const bool shouldFoldCase = document().inQuirksMode();
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001126 const SpaceSplitString& oldClasses = elementData()->classNames();
1127 const SpaceSplitString newClasses(newClassString, shouldFoldCase);
Torne (Richard Coles)09380292014-02-21 12:17:33 +00001128 if (featureSet.checkSelectorsForClassChange(oldClasses, newClasses))
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001129 return true;
1130 } else {
1131 const SpaceSplitString& oldClasses = elementData()->classNames();
Torne (Richard Coles)09380292014-02-21 12:17:33 +00001132 if (featureSet.checkSelectorsForClassChange(oldClasses))
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001133 return true;
1134 }
1135 }
1136
1137 return featureSet.hasSelectorForAttribute(name.localName());
1138}
1139
1140// Returns true is the given attribute is an event handler.
1141// We consider an event handler any attribute that begins with "on".
1142// It is a simple solution that has the advantage of not requiring any
1143// code or configuration change if a new event handler is defined.
1144
1145static inline bool isEventHandlerAttribute(const Attribute& attribute)
1146{
1147 return attribute.name().namespaceURI().isNull() && attribute.name().localName().startsWith("on");
1148}
1149
1150bool Element::isJavaScriptURLAttribute(const Attribute& attribute) const
1151{
1152 return isURLAttribute(attribute) && protocolIsJavaScript(stripLeadingAndTrailingHTMLSpaces(attribute.value()));
1153}
1154
1155void Element::stripScriptingAttributes(Vector<Attribute>& attributeVector) const
1156{
1157 size_t destination = 0;
1158 for (size_t source = 0; source < attributeVector.size(); ++source) {
1159 if (isEventHandlerAttribute(attributeVector[source])
1160 || isJavaScriptURLAttribute(attributeVector[source])
1161 || isHTMLContentAttribute(attributeVector[source]))
1162 continue;
1163
1164 if (source != destination)
1165 attributeVector[destination] = attributeVector[source];
1166
1167 ++destination;
1168 }
1169 attributeVector.shrink(destination);
1170}
1171
1172void Element::parserSetAttributes(const Vector<Attribute>& attributeVector)
1173{
1174 ASSERT(!inDocument());
1175 ASSERT(!parentNode());
1176 ASSERT(!m_elementData);
1177
1178 if (attributeVector.isEmpty())
1179 return;
1180
Torne (Richard Coles)09380292014-02-21 12:17:33 +00001181 if (document().elementDataCache())
1182 m_elementData = document().elementDataCache()->cachedShareableElementDataWithAttributes(attributeVector);
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001183 else
1184 m_elementData = ShareableElementData::createWithAttributes(attributeVector);
1185
1186 // Use attributeVector instead of m_elementData because attributeChanged might modify m_elementData.
1187 for (unsigned i = 0; i < attributeVector.size(); ++i)
1188 attributeChangedFromParserOrByCloning(attributeVector[i].name(), attributeVector[i].value(), ModifiedDirectly);
1189}
1190
1191bool Element::hasAttributes() const
1192{
1193 synchronizeAllAttributes();
1194 return elementData() && elementData()->length();
1195}
1196
1197bool Element::hasEquivalentAttributes(const Element* other) const
1198{
1199 synchronizeAllAttributes();
1200 other->synchronizeAllAttributes();
1201 if (elementData() == other->elementData())
1202 return true;
1203 if (elementData())
1204 return elementData()->isEquivalent(other->elementData());
1205 if (other->elementData())
1206 return other->elementData()->isEquivalent(elementData());
1207 return true;
1208}
1209
1210String Element::nodeName() const
1211{
1212 return m_tagName.toString();
1213}
1214
Torne (Richard Coles)51b29062013-11-28 11:56:03 +00001215void Element::setPrefix(const AtomicString& prefix, ExceptionState& exceptionState)
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001216{
Torne (Richard Coles)09380292014-02-21 12:17:33 +00001217 UseCounter::count(document(), UseCounter::ElementSetPrefix);
1218
1219 if (!prefix.isEmpty() && !Document::isValidName(prefix)) {
1220 exceptionState.throwDOMException(InvalidCharacterError, "The prefix '" + prefix + "' is not a valid name.");
1221 return;
1222 }
1223
1224 // FIXME: Raise NamespaceError if prefix is malformed per the Namespaces in XML specification.
1225
1226 const AtomicString& nodeNamespaceURI = namespaceURI();
1227 if (nodeNamespaceURI.isEmpty() && !prefix.isEmpty()) {
1228 exceptionState.throwDOMException(NamespaceError, "No namespace is set, so a namespace prefix may not be set.");
1229 return;
1230 }
1231
1232 if (prefix == xmlAtom && nodeNamespaceURI != XMLNames::xmlNamespaceURI) {
1233 exceptionState.throwDOMException(NamespaceError, "The prefix '" + xmlAtom + "' may not be set on namespace '" + nodeNamespaceURI + "'.");
1234 return;
1235 }
1236
Torne (Richard Coles)51b29062013-11-28 11:56:03 +00001237 if (exceptionState.hadException())
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001238 return;
1239
1240 m_tagName.setPrefix(prefix.isEmpty() ? AtomicString() : prefix);
1241}
1242
Torne (Richard Coles)09380292014-02-21 12:17:33 +00001243const AtomicString& Element::locateNamespacePrefix(const AtomicString& namespaceToLocate) const
1244{
1245 if (!prefix().isNull() && namespaceURI() == namespaceToLocate)
1246 return prefix();
1247
1248 if (hasAttributes()) {
1249 for (unsigned i = 0; i < attributeCount(); i++) {
1250 const Attribute* attr = attributeItem(i);
1251
1252 if (attr->prefix() == xmlnsAtom && attr->value() == namespaceToLocate)
1253 return attr->localName();
1254 }
1255 }
1256
1257 if (Element* parent = parentElement())
1258 return parent->locateNamespacePrefix(namespaceToLocate);
1259
1260 return nullAtom;
1261}
1262
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001263KURL Element::baseURI() const
1264{
Torne (Richard Coles)09380292014-02-21 12:17:33 +00001265 const AtomicString& baseAttribute = fastGetAttribute(baseAttr);
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001266 KURL base(KURL(), baseAttribute);
1267 if (!base.protocol().isEmpty())
1268 return base;
1269
1270 ContainerNode* parent = parentNode();
1271 if (!parent)
1272 return base;
1273
1274 const KURL& parentBase = parent->baseURI();
1275 if (parentBase.isNull())
1276 return base;
1277
1278 return KURL(parentBase, baseAttribute);
1279}
1280
Torne (Richard Coles)8abfc582013-09-12 12:10:38 +01001281const AtomicString Element::imageSourceURL() const
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001282{
1283 return getAttribute(srcAttr);
1284}
1285
Torne (Richard Coles)8abfc582013-09-12 12:10:38 +01001286bool Element::rendererIsNeeded(const RenderStyle& style)
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001287{
Torne (Richard Coles)8abfc582013-09-12 12:10:38 +01001288 return style.display() != NONE;
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001289}
1290
Ben Murdoch591b9582013-07-10 11:41:44 +01001291RenderObject* Element::createRenderer(RenderStyle* style)
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001292{
1293 return RenderObject::createObject(this, style);
1294}
1295
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001296Node::InsertionNotificationRequest Element::insertedInto(ContainerNode* insertionPoint)
1297{
1298 // need to do superclass processing first so inDocument() is true
1299 // by the time we reach updateId
1300 ContainerNode::insertedInto(insertionPoint);
1301
1302 if (containsFullScreenElement() && parentElement() && !parentElement()->containsFullScreenElement())
1303 setContainsFullScreenElementOnAncestorsCrossingFrameBoundaries(true);
1304
Torne (Richard Coles)19cde672013-11-06 12:28:04 +00001305 ASSERT(!hasRareData() || !elementRareData()->hasPseudoElements());
Torne (Richard Coles)e1f1df52013-08-23 16:39:30 +01001306
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001307 if (!insertionPoint->isInTreeScope())
1308 return InsertionDone;
1309
1310 if (hasRareData())
1311 elementRareData()->clearClassListValueForQuirksMode();
1312
Torne (Richard Coles)f5e4ad52013-08-05 13:57:57 +01001313 if (isUpgradedCustomElement() && inDocument())
1314 CustomElement::didEnterDocument(this, document());
1315
Torne (Richard Coles)8abfc582013-09-12 12:10:38 +01001316 TreeScope& scope = insertionPoint->treeScope();
Torne (Richard Coles)1e202182013-10-18 15:46:42 +01001317 if (scope != treeScope())
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001318 return InsertionDone;
1319
1320 const AtomicString& idValue = getIdAttribute();
Ben Murdoch00d3faa2013-08-14 11:52:03 +01001321 if (!idValue.isNull())
1322 updateId(scope, nullAtom, idValue);
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001323
1324 const AtomicString& nameValue = getNameAttribute();
Ben Murdoch00d3faa2013-08-14 11:52:03 +01001325 if (!nameValue.isNull())
1326 updateName(nullAtom, nameValue);
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001327
1328 if (hasTagName(labelTag)) {
Torne (Richard Coles)8abfc582013-09-12 12:10:38 +01001329 if (scope.shouldCacheLabelsByForAttribute())
Ben Murdoch00d3faa2013-08-14 11:52:03 +01001330 updateLabel(scope, nullAtom, fastGetAttribute(forAttr));
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001331 }
1332
Ben Murdoch3c9e4ae2013-08-12 14:20:44 +01001333 if (parentElement() && parentElement()->isInCanvasSubtree())
1334 setIsInCanvasSubtree(true);
1335
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001336 return InsertionDone;
1337}
1338
1339void Element::removedFrom(ContainerNode* insertionPoint)
1340{
Torne (Richard Coles)f5e4ad52013-08-05 13:57:57 +01001341 bool wasInDocument = insertionPoint->inDocument();
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001342
Torne (Richard Coles)19cde672013-11-06 12:28:04 +00001343 ASSERT(!hasRareData() || !elementRareData()->hasPseudoElements());
Ben Murdoche69819b2013-07-17 14:56:49 +01001344
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001345 if (containsFullScreenElement())
1346 setContainsFullScreenElementOnAncestorsCrossingFrameBoundaries(false);
1347
Torne (Richard Coles)8abfc582013-09-12 12:10:38 +01001348 if (document().page())
1349 document().page()->pointerLockController().elementRemoved(this);
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001350
1351 setSavedLayerScrollOffset(IntSize());
1352
Torne (Richard Coles)1e202182013-10-18 15:46:42 +01001353 if (insertionPoint->isInTreeScope() && treeScope() == document()) {
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001354 const AtomicString& idValue = getIdAttribute();
Ben Murdoch00d3faa2013-08-14 11:52:03 +01001355 if (!idValue.isNull())
1356 updateId(insertionPoint->treeScope(), idValue, nullAtom);
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001357
1358 const AtomicString& nameValue = getNameAttribute();
Ben Murdoch00d3faa2013-08-14 11:52:03 +01001359 if (!nameValue.isNull())
1360 updateName(nameValue, nullAtom);
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001361
1362 if (hasTagName(labelTag)) {
Torne (Richard Coles)8abfc582013-09-12 12:10:38 +01001363 TreeScope& treeScope = insertionPoint->treeScope();
1364 if (treeScope.shouldCacheLabelsByForAttribute())
Ben Murdoch00d3faa2013-08-14 11:52:03 +01001365 updateLabel(treeScope, fastGetAttribute(forAttr), nullAtom);
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001366 }
1367 }
1368
1369 ContainerNode::removedFrom(insertionPoint);
Ben Murdoche69819b2013-07-17 14:56:49 +01001370 if (wasInDocument) {
1371 if (hasPendingResources())
Torne (Richard Coles)8abfc582013-09-12 12:10:38 +01001372 document().accessSVGExtensions()->removeElementFromPendingResources(this);
Ben Murdoche69819b2013-07-17 14:56:49 +01001373
Ben Murdoch83750172013-07-24 10:36:59 +01001374 if (isUpgradedCustomElement())
Ben Murdochfff88842013-07-30 15:20:09 +01001375 CustomElement::didLeaveDocument(this, insertionPoint->document());
Ben Murdoche69819b2013-07-17 14:56:49 +01001376 }
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001377
Torne (Richard Coles)19cde672013-11-06 12:28:04 +00001378 document().removeFromTopLayer(this);
1379
Ben Murdoch3c9e4ae2013-08-12 14:20:44 +01001380 if (hasRareData())
1381 elementRareData()->setIsInCanvasSubtree(false);
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001382}
1383
Torne (Richard Coles)521d96e2013-06-19 11:58:24 +01001384void Element::attach(const AttachContext& context)
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001385{
Torne (Richard Coles)8abfc582013-09-12 12:10:38 +01001386 ASSERT(document().inStyleRecalc());
1387
Torne (Richard Coles)51b29062013-11-28 11:56:03 +00001388 StyleResolverParentPusher parentPusher(*this);
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001389
Torne (Richard Coles)51b29062013-11-28 11:56:03 +00001390 // We've already been through detach when doing an attach, but we might
Torne (Richard Coles)e1f1df52013-08-23 16:39:30 +01001391 // need to clear any state that's been added since then.
Torne (Richard Coles)1e202182013-10-18 15:46:42 +01001392 if (hasRareData() && styleChangeType() == NeedsReattachStyleChange) {
Torne (Richard Coles)e1f1df52013-08-23 16:39:30 +01001393 ElementRareData* data = elementRareData();
1394 data->clearComputedStyle();
1395 data->resetDynamicRestyleObservations();
Torne (Richard Coles)51b29062013-11-28 11:56:03 +00001396 // Only clear the style state if we're not going to reuse the style from recalcStyle.
Torne (Richard Coles)e1f1df52013-08-23 16:39:30 +01001397 if (!context.resolvedStyle)
1398 data->resetStyleState();
1399 }
1400
Torne (Richard Coles)09380292014-02-21 12:17:33 +00001401 RenderTreeBuilder(this, context.resolvedStyle).createRendererForElementIfNeeded();
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001402
Torne (Richard Coles)51b29062013-11-28 11:56:03 +00001403 addCallbackSelectors();
Torne (Richard Coles)1e202182013-10-18 15:46:42 +01001404
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001405 createPseudoElementIfNeeded(BEFORE);
1406
1407 // When a shadow root exists, it does the work of attaching the children.
1408 if (ElementShadow* shadow = this->shadow()) {
1409 parentPusher.push();
Ben Murdoch591b9582013-07-10 11:41:44 +01001410 shadow->attach(context);
Torne (Richard Coles)51b29062013-11-28 11:56:03 +00001411 } else if (firstChild()) {
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001412 parentPusher.push();
Torne (Richard Coles)51b29062013-11-28 11:56:03 +00001413 }
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001414
Torne (Richard Coles)521d96e2013-06-19 11:58:24 +01001415 ContainerNode::attach(context);
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001416
1417 createPseudoElementIfNeeded(AFTER);
Ben Murdoche69819b2013-07-17 14:56:49 +01001418 createPseudoElementIfNeeded(BACKDROP);
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001419
Ben Murdoch591b9582013-07-10 11:41:44 +01001420 if (hasRareData()) {
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001421 ElementRareData* data = elementRareData();
1422 if (data->needsFocusAppearanceUpdateSoonAfterAttach()) {
Torne (Richard Coles)8abfc582013-09-12 12:10:38 +01001423 if (isFocusable() && document().focusedElement() == this)
1424 document().updateFocusAppearanceSoon(false /* don't restore selection */);
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001425 data->setNeedsFocusAppearanceUpdateSoonAfterAttach(false);
1426 }
Torne (Richard Coles)09380292014-02-21 12:17:33 +00001427 if (!renderer()) {
1428 if (ActiveAnimations* activeAnimations = data->activeAnimations()) {
1429 activeAnimations->cssAnimations().cancel();
1430 activeAnimations->setAnimationStyleChange(false);
1431 }
1432 }
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001433 }
Ben Murdoch591b9582013-07-10 11:41:44 +01001434
Torne (Richard Coles)8abfc582013-09-12 12:10:38 +01001435 InspectorInstrumentation::didRecalculateStyleForElement(this);
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001436}
1437
Torne (Richard Coles)521d96e2013-06-19 11:58:24 +01001438void Element::detach(const AttachContext& context)
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001439{
Torne (Richard Coles)1e202182013-10-18 15:46:42 +01001440 RenderWidget::UpdateSuspendScope suspendWidgetHierarchyUpdates;
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001441 cancelFocusAppearanceUpdate();
Torne (Richard Coles)51b29062013-11-28 11:56:03 +00001442 removeCallbackSelectors();
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001443 if (hasRareData()) {
1444 ElementRareData* data = elementRareData();
Torne (Richard Coles)09380292014-02-21 12:17:33 +00001445 data->clearPseudoElements();
Torne (Richard Coles)f5e4ad52013-08-05 13:57:57 +01001446
Torne (Richard Coles)51b29062013-11-28 11:56:03 +00001447 // attach() will perform the below steps for us when inside recalcStyle.
1448 if (!document().inStyleRecalc()) {
Ben Murdoch3c9e4ae2013-08-12 14:20:44 +01001449 data->resetStyleState();
Torne (Richard Coles)51b29062013-11-28 11:56:03 +00001450 data->clearComputedStyle();
1451 data->resetDynamicRestyleObservations();
1452 }
Ben Murdoch3c9e4ae2013-08-12 14:20:44 +01001453
Torne (Richard Coles)09380292014-02-21 12:17:33 +00001454 if (ActiveAnimations* activeAnimations = data->activeAnimations()) {
1455 if (context.performingReattach) {
1456 // FIXME: We call detach from withing style recalc, so compositingState is not up to date.
1457 // https://code.google.com/p/chromium/issues/detail?id=339847
1458 DisableCompositingQueryAsserts disabler;
1459
1460 // FIXME: restart compositor animations rather than pull back to the main thread
1461 activeAnimations->cancelAnimationOnCompositor();
1462 } else {
1463 activeAnimations->cssAnimations().cancel();
1464 activeAnimations->setAnimationStyleChange(false);
Torne (Richard Coles)51b29062013-11-28 11:56:03 +00001465 }
Torne (Richard Coles)f5e4ad52013-08-05 13:57:57 +01001466 }
Torne (Richard Coles)09380292014-02-21 12:17:33 +00001467
1468 if (ElementShadow* shadow = data->shadow())
1469 shadow->detach(context);
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001470 }
Torne (Richard Coles)521d96e2013-06-19 11:58:24 +01001471 ContainerNode::detach(context);
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001472}
1473
1474bool Element::pseudoStyleCacheIsInvalid(const RenderStyle* currentStyle, RenderStyle* newStyle)
1475{
1476 ASSERT(currentStyle == renderStyle());
1477 ASSERT(renderer());
1478
1479 if (!currentStyle)
1480 return false;
1481
1482 const PseudoStyleCache* pseudoStyleCache = currentStyle->cachedPseudoStyles();
1483 if (!pseudoStyleCache)
1484 return false;
1485
1486 size_t cacheSize = pseudoStyleCache->size();
1487 for (size_t i = 0; i < cacheSize; ++i) {
1488 RefPtr<RenderStyle> newPseudoStyle;
1489 PseudoId pseudoId = pseudoStyleCache->at(i)->styleType();
1490 if (pseudoId == FIRST_LINE || pseudoId == FIRST_LINE_INHERITED)
1491 newPseudoStyle = renderer()->uncachedFirstLineStyle(newStyle);
1492 else
1493 newPseudoStyle = renderer()->getUncachedPseudoStyle(PseudoStyleRequest(pseudoId), newStyle, newStyle);
1494 if (!newPseudoStyle)
1495 return true;
1496 if (*newPseudoStyle != *pseudoStyleCache->at(i)) {
1497 if (pseudoId < FIRST_INTERNAL_PSEUDOID)
1498 newStyle->setHasPseudoStyle(pseudoId);
1499 newStyle->addCachedPseudoStyle(newPseudoStyle);
1500 if (pseudoId == FIRST_LINE || pseudoId == FIRST_LINE_INHERITED) {
1501 // FIXME: We should do an actual diff to determine whether a repaint vs. layout
Torne (Richard Coles)51b29062013-11-28 11:56:03 +00001502 // is needed, but for now just assume a layout will be required. The diff code
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001503 // in RenderObject::setStyle would need to be factored out so that it could be reused.
1504 renderer()->setNeedsLayoutAndPrefWidthsRecalc();
1505 }
1506 return true;
1507 }
1508 }
1509 return false;
1510}
1511
Torne (Richard Coles)521d96e2013-06-19 11:58:24 +01001512PassRefPtr<RenderStyle> Element::styleForRenderer()
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001513{
Torne (Richard Coles)a854de02013-12-18 16:25:25 +00001514 ASSERT(document().inStyleRecalc());
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001515
Torne (Richard Coles)a854de02013-12-18 16:25:25 +00001516 RefPtr<RenderStyle> style;
1517
1518 // FIXME: Instead of clearing updates that may have been added from calls to styleForElement
1519 // outside recalcStyle, we should just never set them if we're not inside recalcStyle.
1520 if (ActiveAnimations* activeAnimations = this->activeAnimations())
1521 activeAnimations->cssAnimations().setPendingUpdate(nullptr);
1522
1523 if (hasCustomStyleCallbacks())
1524 style = customStyleForRenderer();
1525 if (!style)
1526 style = originalStyleForRenderer();
1527
1528 // styleForElement() might add active animations so we need to get it again.
1529 if (ActiveAnimations* activeAnimations = this->activeAnimations())
1530 activeAnimations->cssAnimations().maybeApplyPendingUpdate(this);
1531
1532 ASSERT(style);
1533 return style.release();
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001534}
1535
Torne (Richard Coles)521d96e2013-06-19 11:58:24 +01001536PassRefPtr<RenderStyle> Element::originalStyleForRenderer()
Torne (Richard Coles)5267f702013-06-11 10:57:24 +01001537{
Torne (Richard Coles)a854de02013-12-18 16:25:25 +00001538 ASSERT(document().inStyleRecalc());
1539 return document().ensureStyleResolver().styleForElement(this);
Torne (Richard Coles)5267f702013-06-11 10:57:24 +01001540}
1541
Torne (Richard Coles)51b29062013-11-28 11:56:03 +00001542void Element::recalcStyle(StyleRecalcChange change, Text* nextTextSibling)
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001543{
Torne (Richard Coles)8abfc582013-09-12 12:10:38 +01001544 ASSERT(document().inStyleRecalc());
Torne (Richard Coles)51b29062013-11-28 11:56:03 +00001545 ASSERT(!parentOrShadowHostNode()->needsStyleRecalc());
Torne (Richard Coles)93ac45c2013-05-29 14:40:20 +01001546
Torne (Richard Coles)bfe35902013-10-22 16:41:51 +01001547 if (hasCustomStyleCallbacks())
1548 willRecalcStyle(change);
1549
Torne (Richard Coles)51b29062013-11-28 11:56:03 +00001550 if (change >= Inherit || needsStyleRecalc()) {
1551 if (hasRareData()) {
1552 ElementRareData* data = elementRareData();
1553 data->resetStyleState();
1554 data->clearComputedStyle();
Torne (Richard Coles)a854de02013-12-18 16:25:25 +00001555
1556 if (change >= Inherit) {
1557 if (ActiveAnimations* activeAnimations = data->activeAnimations())
1558 activeAnimations->setAnimationStyleChange(false);
1559 }
Torne (Richard Coles)51b29062013-11-28 11:56:03 +00001560 }
1561 if (parentRenderStyle())
1562 change = recalcOwnStyle(change);
1563 clearNeedsStyleRecalc();
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001564 }
Ben Murdoch3c9e4ae2013-08-12 14:20:44 +01001565
Torne (Richard Coles)c0e19a62013-08-30 15:15:11 +01001566 // If we reattached we don't need to recalc the style of our descendants anymore.
Torne (Richard Coles)09380292014-02-21 12:17:33 +00001567 if ((change >= UpdatePseudoElements && change < Reattach) || childNeedsStyleRecalc()) {
Torne (Richard Coles)c0e19a62013-08-30 15:15:11 +01001568 recalcChildStyle(change);
Torne (Richard Coles)09380292014-02-21 12:17:33 +00001569 clearChildNeedsStyleRecalc();
1570 }
Ben Murdoch591b9582013-07-10 11:41:44 +01001571
Torne (Richard Coles)bfe35902013-10-22 16:41:51 +01001572 if (hasCustomStyleCallbacks())
1573 didRecalcStyle(change);
1574
Torne (Richard Coles)51b29062013-11-28 11:56:03 +00001575 if (change == Reattach)
1576 reattachWhitespaceSiblings(nextTextSibling);
Torne (Richard Coles)1e202182013-10-18 15:46:42 +01001577}
1578
Torne (Richard Coles)8abfc582013-09-12 12:10:38 +01001579StyleRecalcChange Element::recalcOwnStyle(StyleRecalcChange change)
Torne (Richard Coles)c0e19a62013-08-30 15:15:11 +01001580{
Torne (Richard Coles)8abfc582013-09-12 12:10:38 +01001581 ASSERT(document().inStyleRecalc());
Torne (Richard Coles)51b29062013-11-28 11:56:03 +00001582 ASSERT(!parentOrShadowHostNode()->needsStyleRecalc());
1583 ASSERT(change >= Inherit || needsStyleRecalc());
1584 ASSERT(parentRenderStyle());
Torne (Richard Coles)c0e19a62013-08-30 15:15:11 +01001585
Torne (Richard Coles)c0e19a62013-08-30 15:15:11 +01001586 RefPtr<RenderStyle> oldStyle = renderStyle();
Torne (Richard Coles)a854de02013-12-18 16:25:25 +00001587 RefPtr<RenderStyle> newStyle = styleForRenderer();
Torne (Richard Coles)8abfc582013-09-12 12:10:38 +01001588 StyleRecalcChange localChange = RenderStyle::compare(oldStyle.get(), newStyle.get());
Torne (Richard Coles)c0e19a62013-08-30 15:15:11 +01001589
Torne (Richard Coles)51b29062013-11-28 11:56:03 +00001590 ASSERT(newStyle);
1591
Torne (Richard Coles)c0e19a62013-08-30 15:15:11 +01001592 if (localChange == Reattach) {
1593 AttachContext reattachContext;
1594 reattachContext.resolvedStyle = newStyle.get();
1595 reattach(reattachContext);
1596 return Reattach;
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001597 }
Torne (Richard Coles)c0e19a62013-08-30 15:15:11 +01001598
Torne (Richard Coles)51b29062013-11-28 11:56:03 +00001599 ASSERT(oldStyle);
1600
Torne (Richard Coles)c0e19a62013-08-30 15:15:11 +01001601 InspectorInstrumentation::didRecalculateStyleForElement(this);
1602
Torne (Richard Coles)51b29062013-11-28 11:56:03 +00001603 if (localChange != NoChange)
Torne (Richard Coles)1e202182013-10-18 15:46:42 +01001604 updateCallbackSelectors(oldStyle.get(), newStyle.get());
1605
Torne (Richard Coles)c0e19a62013-08-30 15:15:11 +01001606 if (RenderObject* renderer = this->renderer()) {
Torne (Richard Coles)51b29062013-11-28 11:56:03 +00001607 if (localChange != NoChange || pseudoStyleCacheIsInvalid(oldStyle.get(), newStyle.get()) || shouldNotifyRendererWithIdenticalStyles()) {
Torne (Richard Coles)09380292014-02-21 12:17:33 +00001608 renderer->setStyle(newStyle.get());
Torne (Richard Coles)f79f16f2013-10-31 11:16:44 +00001609 } else {
Torne (Richard Coles)c0e19a62013-08-30 15:15:11 +01001610 // Although no change occurred, we use the new style so that the cousin style sharing code won't get
1611 // fooled into believing this style is the same.
Torne (Richard Coles)f79f16f2013-10-31 11:16:44 +00001612 // FIXME: We may be able to remove this hack, see discussion in
1613 // https://codereview.chromium.org/30453002/
Torne (Richard Coles)c0e19a62013-08-30 15:15:11 +01001614 renderer->setStyleInternal(newStyle.get());
1615 }
1616 }
1617
Torne (Richard Coles)c0e19a62013-08-30 15:15:11 +01001618 if (styleChangeType() >= SubtreeStyleChange)
1619 return Force;
1620
Torne (Richard Coles)09380292014-02-21 12:17:33 +00001621 if (change > Inherit || localChange > Inherit)
1622 return max(localChange, change);
1623
1624 if (localChange < Inherit && (oldStyle->hasPseudoElementStyle() || newStyle->hasPseudoElementStyle()))
1625 return UpdatePseudoElements;
1626
1627 return localChange;
Torne (Richard Coles)c0e19a62013-08-30 15:15:11 +01001628}
1629
Torne (Richard Coles)8abfc582013-09-12 12:10:38 +01001630void Element::recalcChildStyle(StyleRecalcChange change)
Torne (Richard Coles)c0e19a62013-08-30 15:15:11 +01001631{
Torne (Richard Coles)8abfc582013-09-12 12:10:38 +01001632 ASSERT(document().inStyleRecalc());
Torne (Richard Coles)09380292014-02-21 12:17:33 +00001633 ASSERT(change >= UpdatePseudoElements || childNeedsStyleRecalc());
Torne (Richard Coles)51b29062013-11-28 11:56:03 +00001634 ASSERT(!needsStyleRecalc());
Torne (Richard Coles)c0e19a62013-08-30 15:15:11 +01001635
Torne (Richard Coles)51b29062013-11-28 11:56:03 +00001636 StyleResolverParentPusher parentPusher(*this);
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001637
Torne (Richard Coles)09380292014-02-21 12:17:33 +00001638 if (change > UpdatePseudoElements || childNeedsStyleRecalc()) {
1639 for (ShadowRoot* root = youngestShadowRoot(); root; root = root->olderShadowRoot()) {
1640 if (root->shouldCallRecalcStyle(change)) {
1641 parentPusher.push();
1642 root->recalcStyle(change);
1643 }
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001644 }
1645 }
1646
Torne (Richard Coles)09380292014-02-21 12:17:33 +00001647 updatePseudoElement(BEFORE, change);
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001648
Torne (Richard Coles)51b29062013-11-28 11:56:03 +00001649 if (change < Force && hasRareData() && childNeedsStyleRecalc())
1650 checkForChildrenAdjacentRuleChanges();
Torne (Richard Coles)f79f16f2013-10-31 11:16:44 +00001651
Torne (Richard Coles)09380292014-02-21 12:17:33 +00001652 if (change > UpdatePseudoElements || childNeedsStyleRecalc()) {
1653 // This loop is deliberately backwards because we use insertBefore in the rendering tree, and want to avoid
1654 // a potentially n^2 loop to find the insertion point while resolving style. Having us start from the last
1655 // child and work our way back means in the common case, we'll find the insertion point in O(1) time.
1656 // See crbug.com/288225
1657 StyleResolver& styleResolver = document().ensureStyleResolver();
1658 Text* lastTextNode = 0;
1659 for (Node* child = lastChild(); child; child = child->previousSibling()) {
1660 if (child->isTextNode()) {
1661 toText(child)->recalcTextStyle(change, lastTextNode);
1662 lastTextNode = toText(child);
1663 } else if (child->isElementNode()) {
1664 Element* element = toElement(child);
1665 if (element->shouldCallRecalcStyle(change)) {
1666 parentPusher.push();
1667 element->recalcStyle(change, lastTextNode);
1668 } else if (element->supportsStyleSharing()) {
1669 styleResolver.addToStyleSharingList(*element);
1670 }
1671 if (element->renderer())
1672 lastTextNode = 0;
Ben Murdoche69819b2013-07-17 14:56:49 +01001673 }
Ben Murdoch591b9582013-07-10 11:41:44 +01001674 }
Torne (Richard Coles)5267f702013-06-11 10:57:24 +01001675 }
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001676
Torne (Richard Coles)09380292014-02-21 12:17:33 +00001677 updatePseudoElement(AFTER, change);
1678 updatePseudoElement(BACKDROP, change);
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001679}
1680
Torne (Richard Coles)51b29062013-11-28 11:56:03 +00001681void Element::checkForChildrenAdjacentRuleChanges()
1682{
1683 bool hasDirectAdjacentRules = childrenAffectedByDirectAdjacentRules();
1684 bool hasIndirectAdjacentRules = childrenAffectedByForwardPositionalRules();
1685
1686 if (!hasDirectAdjacentRules && !hasIndirectAdjacentRules)
1687 return;
1688
1689 unsigned forceCheckOfNextElementCount = 0;
1690 bool forceCheckOfAnyElementSibling = false;
1691
1692 for (Node* child = firstChild(); child; child = child->nextSibling()) {
1693 if (!child->isElementNode())
1694 continue;
1695 Element* element = toElement(child);
1696 bool childRulesChanged = element->needsStyleRecalc() && element->styleChangeType() >= SubtreeStyleChange;
1697
1698 if (forceCheckOfNextElementCount || forceCheckOfAnyElementSibling)
Torne (Richard Coles)09380292014-02-21 12:17:33 +00001699 element->setNeedsStyleRecalc(SubtreeStyleChange);
Torne (Richard Coles)51b29062013-11-28 11:56:03 +00001700
1701 if (forceCheckOfNextElementCount)
1702 forceCheckOfNextElementCount--;
1703
1704 if (childRulesChanged && hasDirectAdjacentRules)
1705 forceCheckOfNextElementCount = document().styleEngine()->maxDirectAdjacentSelectors();
1706
1707 forceCheckOfAnyElementSibling = forceCheckOfAnyElementSibling || (childRulesChanged && hasIndirectAdjacentRules);
1708 }
1709}
1710
1711void Element::updateCallbackSelectors(RenderStyle* oldStyle, RenderStyle* newStyle)
1712{
1713 Vector<String> emptyVector;
1714 const Vector<String>& oldCallbackSelectors = oldStyle ? oldStyle->callbackSelectors() : emptyVector;
1715 const Vector<String>& newCallbackSelectors = newStyle ? newStyle->callbackSelectors() : emptyVector;
1716 if (oldCallbackSelectors.isEmpty() && newCallbackSelectors.isEmpty())
1717 return;
1718 if (oldCallbackSelectors != newCallbackSelectors)
1719 CSSSelectorWatch::from(document()).updateSelectorMatches(oldCallbackSelectors, newCallbackSelectors);
1720}
1721
1722void Element::addCallbackSelectors()
1723{
1724 updateCallbackSelectors(0, renderStyle());
1725}
1726
1727void Element::removeCallbackSelectors()
1728{
1729 updateCallbackSelectors(renderStyle(), 0);
1730}
1731
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001732ElementShadow* Element::shadow() const
1733{
1734 return hasRareData() ? elementRareData()->shadow() : 0;
1735}
1736
Torne (Richard Coles)bfe35902013-10-22 16:41:51 +01001737ElementShadow& Element::ensureShadow()
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001738{
Torne (Richard Coles)bfe35902013-10-22 16:41:51 +01001739 return ensureElementRareData().ensureShadow();
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001740}
1741
1742void Element::didAffectSelector(AffectedSelectorMask mask)
1743{
Torne (Richard Coles)09380292014-02-21 12:17:33 +00001744 setNeedsStyleRecalc(SubtreeStyleChange);
Torne (Richard Coles)19cde672013-11-06 12:28:04 +00001745 if (ElementShadow* elementShadow = shadowWhereNodeCanBeDistributed(*this))
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001746 elementShadow->didAffectSelector(mask);
1747}
1748
Torne (Richard Coles)a854de02013-12-18 16:25:25 +00001749void Element::setAnimationStyleChange(bool animationStyleChange)
1750{
1751 if (ActiveAnimations* activeAnimations = elementRareData()->activeAnimations())
1752 activeAnimations->setAnimationStyleChange(animationStyleChange);
1753}
1754
1755void Element::setNeedsAnimationStyleRecalc()
1756{
1757 if (styleChangeType() != NoStyleChange)
1758 return;
1759
Torne (Richard Coles)09380292014-02-21 12:17:33 +00001760 setNeedsStyleRecalc(LocalStyleChange);
Torne (Richard Coles)a854de02013-12-18 16:25:25 +00001761 setAnimationStyleChange(true);
1762}
1763
Torne (Richard Coles)51b29062013-11-28 11:56:03 +00001764PassRefPtr<ShadowRoot> Element::createShadowRoot(ExceptionState& exceptionState)
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001765{
1766 if (alwaysCreateUserAgentShadowRoot())
1767 ensureUserAgentShadowRoot();
1768
Torne (Richard Coles)09380292014-02-21 12:17:33 +00001769 // Some elements make assumptions about what kind of renderers they allow
1770 // as children so we can't allow author shadows on them for now. An override
1771 // flag is provided for testing how author shadows interact on these elements.
1772 if (!areAuthorShadowsAllowed() && !RuntimeEnabledFeatures::authorShadowDOMForAnyElementEnabled()) {
1773 exceptionState.throwDOMException(HierarchyRequestError, "Author-created shadow roots are disabled for this element.");
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001774 return 0;
1775 }
Torne (Richard Coles)09380292014-02-21 12:17:33 +00001776
Torne (Richard Coles)51b29062013-11-28 11:56:03 +00001777 return PassRefPtr<ShadowRoot>(ensureShadow().addShadowRoot(*this, ShadowRoot::AuthorShadowRoot));
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001778}
1779
1780ShadowRoot* Element::shadowRoot() const
1781{
1782 ElementShadow* elementShadow = shadow();
1783 if (!elementShadow)
1784 return 0;
1785 ShadowRoot* shadowRoot = elementShadow->youngestShadowRoot();
1786 if (shadowRoot->type() == ShadowRoot::AuthorShadowRoot)
1787 return shadowRoot;
1788 return 0;
1789}
1790
Torne (Richard Coles)8abfc582013-09-12 12:10:38 +01001791void Element::didAddShadowRoot(ShadowRoot&)
1792{
1793}
1794
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001795ShadowRoot* Element::userAgentShadowRoot() const
1796{
1797 if (ElementShadow* elementShadow = shadow()) {
1798 if (ShadowRoot* shadowRoot = elementShadow->oldestShadowRoot()) {
1799 ASSERT(shadowRoot->type() == ShadowRoot::UserAgentShadowRoot);
1800 return shadowRoot;
1801 }
1802 }
1803
1804 return 0;
1805}
1806
Torne (Richard Coles)51b29062013-11-28 11:56:03 +00001807ShadowRoot& Element::ensureUserAgentShadowRoot()
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001808{
1809 if (ShadowRoot* shadowRoot = userAgentShadowRoot())
Torne (Richard Coles)51b29062013-11-28 11:56:03 +00001810 return *shadowRoot;
1811 ShadowRoot& shadowRoot = ensureShadow().addShadowRoot(*this, ShadowRoot::UserAgentShadowRoot);
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001812 didAddUserAgentShadowRoot(shadowRoot);
1813 return shadowRoot;
1814}
1815
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001816bool Element::childTypeAllowed(NodeType type) const
1817{
1818 switch (type) {
1819 case ELEMENT_NODE:
1820 case TEXT_NODE:
1821 case COMMENT_NODE:
1822 case PROCESSING_INSTRUCTION_NODE:
1823 case CDATA_SECTION_NODE:
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001824 return true;
1825 default:
1826 break;
1827 }
1828 return false;
1829}
1830
Torne (Richard Coles)51b29062013-11-28 11:56:03 +00001831void Element::checkForEmptyStyleChange(RenderStyle* style)
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001832{
Torne (Richard Coles)51b29062013-11-28 11:56:03 +00001833 if (!style && !styleAffectedByEmpty())
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001834 return;
1835
Torne (Richard Coles)51b29062013-11-28 11:56:03 +00001836 if (!style || (styleAffectedByEmpty() && (!style->emptyState() || hasChildNodes())))
Torne (Richard Coles)09380292014-02-21 12:17:33 +00001837 setNeedsStyleRecalc(SubtreeStyleChange);
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001838}
1839
Torne (Richard Coles)51b29062013-11-28 11:56:03 +00001840void Element::checkForSiblingStyleChanges(bool finishedParsingCallback, Node* beforeChange, Node* afterChange, int childCountDelta)
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001841{
Torne (Richard Coles)51b29062013-11-28 11:56:03 +00001842 if (!inActiveDocument() || document().hasPendingForcedStyleRecalc() || styleChangeType() >= SubtreeStyleChange)
Ben Murdoch83750172013-07-24 10:36:59 +01001843 return;
1844
Torne (Richard Coles)51b29062013-11-28 11:56:03 +00001845 RenderStyle* style = renderStyle();
Ben Murdoch591b9582013-07-10 11:41:44 +01001846
Torne (Richard Coles)51b29062013-11-28 11:56:03 +00001847 // :empty selector.
1848 checkForEmptyStyleChange(style);
1849
1850 if (!style || (needsStyleRecalc() && childrenAffectedByPositionalRules()))
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001851 return;
1852
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001853 // Forward positional selectors include the ~ selector, nth-child, nth-of-type, first-of-type and only-of-type.
1854 // Backward positional selectors include nth-last-child, nth-last-of-type, last-of-type and only-of-type.
1855 // We have to invalidate everything following the insertion point in the forward case, and everything before the insertion point in the
1856 // backward case.
1857 // |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.
1858 // 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 +01001859 // here. recalcStyle will then force a walk of the children when it sees that this has happened.
Torne (Richard Coles)51b29062013-11-28 11:56:03 +00001860 if ((childrenAffectedByForwardPositionalRules() && afterChange) || (childrenAffectedByBackwardPositionalRules() && beforeChange)) {
Torne (Richard Coles)09380292014-02-21 12:17:33 +00001861 setNeedsStyleRecalc(SubtreeStyleChange);
Ben Murdoch83750172013-07-24 10:36:59 +01001862 return;
1863 }
1864
1865 // :first-child. In the parser callback case, we don't have to check anything, since we were right the first time.
1866 // In the DOM case, we only need to do something if |afterChange| is not 0.
1867 // |afterChange| is 0 in the parser case, so it works out that we'll skip this block.
Torne (Richard Coles)51b29062013-11-28 11:56:03 +00001868 if (childrenAffectedByFirstChildRules() && afterChange) {
Ben Murdoch83750172013-07-24 10:36:59 +01001869 // Find our new first child.
Torne (Richard Coles)09380292014-02-21 12:17:33 +00001870 Element* newFirstChild = ElementTraversal::firstWithin(*this);
Ben Murdoch83750172013-07-24 10:36:59 +01001871 RenderStyle* newFirstChildStyle = newFirstChild ? newFirstChild->renderStyle() : 0;
1872
1873 // Find the first element node following |afterChange|
Torne (Richard Coles)09380292014-02-21 12:17:33 +00001874 Node* firstElementAfterInsertion = afterChange->isElementNode() ? afterChange : ElementTraversal::nextSibling(*afterChange);
Ben Murdoch83750172013-07-24 10:36:59 +01001875 RenderStyle* firstElementAfterInsertionStyle = firstElementAfterInsertion ? firstElementAfterInsertion->renderStyle() : 0;
1876
1877 // This is the insert/append case.
1878 if (newFirstChild != firstElementAfterInsertion && firstElementAfterInsertionStyle && firstElementAfterInsertionStyle->firstChildState())
Torne (Richard Coles)09380292014-02-21 12:17:33 +00001879 firstElementAfterInsertion->setNeedsStyleRecalc(SubtreeStyleChange);
Ben Murdoch83750172013-07-24 10:36:59 +01001880
1881 // We also have to handle node removal.
1882 if (childCountDelta < 0 && newFirstChild == firstElementAfterInsertion && newFirstChild && (!newFirstChildStyle || !newFirstChildStyle->firstChildState()))
Torne (Richard Coles)09380292014-02-21 12:17:33 +00001883 newFirstChild->setNeedsStyleRecalc(SubtreeStyleChange);
Ben Murdoch83750172013-07-24 10:36:59 +01001884 }
1885
1886 // :last-child. In the parser callback case, we don't have to check anything, since we were right the first time.
1887 // In the DOM case, we only need to do something if |afterChange| is not 0.
Torne (Richard Coles)51b29062013-11-28 11:56:03 +00001888 if (childrenAffectedByLastChildRules() && beforeChange) {
Ben Murdoch83750172013-07-24 10:36:59 +01001889 // Find our new last child.
Torne (Richard Coles)09380292014-02-21 12:17:33 +00001890 Node* newLastChild = ElementTraversal::lastWithin(*this);
Ben Murdoch83750172013-07-24 10:36:59 +01001891 RenderStyle* newLastChildStyle = newLastChild ? newLastChild->renderStyle() : 0;
1892
1893 // Find the last element node going backwards from |beforeChange|
Torne (Richard Coles)09380292014-02-21 12:17:33 +00001894 Node* lastElementBeforeInsertion = beforeChange->isElementNode() ? beforeChange : ElementTraversal::previousSibling(*beforeChange);
Ben Murdoch83750172013-07-24 10:36:59 +01001895 RenderStyle* lastElementBeforeInsertionStyle = lastElementBeforeInsertion ? lastElementBeforeInsertion->renderStyle() : 0;
1896
1897 if (newLastChild != lastElementBeforeInsertion && lastElementBeforeInsertionStyle && lastElementBeforeInsertionStyle->lastChildState())
Torne (Richard Coles)09380292014-02-21 12:17:33 +00001898 lastElementBeforeInsertion->setNeedsStyleRecalc(SubtreeStyleChange);
Ben Murdoch83750172013-07-24 10:36:59 +01001899
1900 // 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
1901 // to match now.
1902 if ((childCountDelta < 0 || finishedParsingCallback) && newLastChild == lastElementBeforeInsertion && newLastChild && (!newLastChildStyle || !newLastChildStyle->lastChildState()))
Torne (Richard Coles)09380292014-02-21 12:17:33 +00001903 newLastChild->setNeedsStyleRecalc(SubtreeStyleChange);
Ben Murdoch83750172013-07-24 10:36:59 +01001904 }
1905
1906 // The + selector. We need to invalidate the first element following the insertion point. It is the only possible element
1907 // that could be affected by this DOM change.
Torne (Richard Coles)51b29062013-11-28 11:56:03 +00001908 if (childrenAffectedByDirectAdjacentRules() && afterChange) {
Torne (Richard Coles)09380292014-02-21 12:17:33 +00001909 if (Node* firstElementAfterInsertion = afterChange->isElementNode() ? afterChange : ElementTraversal::nextSibling(*afterChange))
1910 firstElementAfterInsertion->setNeedsStyleRecalc(SubtreeStyleChange);
Ben Murdoch83750172013-07-24 10:36:59 +01001911 }
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001912}
1913
1914void Element::childrenChanged(bool changedByParser, Node* beforeChange, Node* afterChange, int childCountDelta)
1915{
1916 ContainerNode::childrenChanged(changedByParser, beforeChange, afterChange, childCountDelta);
1917 if (changedByParser)
Torne (Richard Coles)51b29062013-11-28 11:56:03 +00001918 checkForEmptyStyleChange(renderStyle());
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001919 else
Torne (Richard Coles)51b29062013-11-28 11:56:03 +00001920 checkForSiblingStyleChanges(false, beforeChange, afterChange, childCountDelta);
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001921
Ben Murdoch83750172013-07-24 10:36:59 +01001922 if (ElementShadow* shadow = this->shadow())
Torne (Richard Coles)f5e4ad52013-08-05 13:57:57 +01001923 shadow->setNeedsDistributionRecalc();
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001924}
1925
1926void Element::removeAllEventListeners()
1927{
1928 ContainerNode::removeAllEventListeners();
1929 if (ElementShadow* shadow = this->shadow())
1930 shadow->removeAllEventListeners();
1931}
1932
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001933void Element::finishParsingChildren()
1934{
Torne (Richard Coles)09380292014-02-21 12:17:33 +00001935 setIsFinishedParsingChildren(true);
Torne (Richard Coles)51b29062013-11-28 11:56:03 +00001936 checkForSiblingStyleChanges(this, lastChild(), 0, 0);
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001937}
1938
1939#ifndef NDEBUG
1940void Element::formatForDebugger(char* buffer, unsigned length) const
1941{
1942 StringBuilder result;
1943 String s;
1944
1945 result.append(nodeName());
1946
1947 s = getIdAttribute();
1948 if (s.length() > 0) {
1949 if (result.length() > 0)
1950 result.appendLiteral("; ");
1951 result.appendLiteral("id=");
1952 result.append(s);
1953 }
1954
1955 s = getAttribute(classAttr);
1956 if (s.length() > 0) {
1957 if (result.length() > 0)
1958 result.appendLiteral("; ");
1959 result.appendLiteral("class=");
1960 result.append(s);
1961 }
1962
1963 strncpy(buffer, result.toString().utf8().data(), length - 1);
1964}
1965#endif
1966
1967const Vector<RefPtr<Attr> >& Element::attrNodeList()
1968{
1969 ASSERT(hasSyntheticAttrChildNodes());
1970 return *attrNodeListForElement(this);
1971}
1972
Torne (Richard Coles)51b29062013-11-28 11:56:03 +00001973PassRefPtr<Attr> Element::setAttributeNode(Attr* attrNode, ExceptionState& exceptionState)
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001974{
1975 if (!attrNode) {
Torne (Richard Coles)09380292014-02-21 12:17:33 +00001976 exceptionState.throwDOMException(TypeMismatchError, "The node provided is invalid.");
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001977 return 0;
1978 }
1979
1980 RefPtr<Attr> oldAttrNode = attrIfExists(attrNode->qualifiedName());
1981 if (oldAttrNode.get() == attrNode)
1982 return attrNode; // This Attr is already attached to the element.
1983
Ben Murdoche69819b2013-07-17 14:56:49 +01001984 // 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 +01001985 // The DOM user must explicitly clone Attr nodes to re-use them in other elements.
1986 if (attrNode->ownerElement()) {
Torne (Richard Coles)09380292014-02-21 12:17:33 +00001987 exceptionState.throwDOMException(InUseAttributeError, "The node provided is an attribute node that is already an attribute of another Element; attribute nodes must be explicitly cloned.");
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001988 return 0;
1989 }
1990
1991 synchronizeAllAttributes();
1992 UniqueElementData* elementData = ensureUniqueElementData();
1993
Torne (Richard Coles)bfe35902013-10-22 16:41:51 +01001994 size_t index = elementData->getAttributeItemIndex(attrNode->qualifiedName(), shouldIgnoreAttributeCase());
Torne (Richard Coles)06f816c2013-09-26 13:25:12 +01001995 if (index != kNotFound) {
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001996 if (oldAttrNode)
1997 detachAttrNodeFromElementWithValue(oldAttrNode.get(), elementData->attributeItem(index)->value());
1998 else
1999 oldAttrNode = Attr::create(document(), attrNode->qualifiedName(), elementData->attributeItem(index)->value());
2000 }
2001
2002 setAttributeInternal(index, attrNode->qualifiedName(), attrNode->value(), NotInSynchronizationOfLazyAttribute);
2003
2004 attrNode->attachToElement(this);
Torne (Richard Coles)f79f16f2013-10-31 11:16:44 +00002005 treeScope().adoptIfNeeded(*attrNode);
Torne (Richard Coles)bfe35902013-10-22 16:41:51 +01002006 ensureAttrNodeListForElement(this).append(attrNode);
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002007
2008 return oldAttrNode.release();
2009}
2010
Torne (Richard Coles)51b29062013-11-28 11:56:03 +00002011PassRefPtr<Attr> Element::removeAttributeNode(Attr* attr, ExceptionState& exceptionState)
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002012{
2013 if (!attr) {
Torne (Richard Coles)09380292014-02-21 12:17:33 +00002014 exceptionState.throwDOMException(TypeMismatchError, "The node provided is invalid.");
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002015 return 0;
2016 }
2017 if (attr->ownerElement() != this) {
Torne (Richard Coles)09380292014-02-21 12:17:33 +00002018 exceptionState.throwDOMException(NotFoundError, "The node provided is owned by another element.");
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002019 return 0;
2020 }
2021
Torne (Richard Coles)1e202182013-10-18 15:46:42 +01002022 ASSERT(document() == attr->document());
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002023
2024 synchronizeAttribute(attr->qualifiedName());
2025
Torne (Richard Coles)e5249552013-05-15 11:35:13 +01002026 size_t index = elementData()->getAttrIndex(attr);
Torne (Richard Coles)06f816c2013-09-26 13:25:12 +01002027 if (index == kNotFound) {
Torne (Richard Coles)09380292014-02-21 12:17:33 +00002028 exceptionState.throwDOMException(NotFoundError, "The attribute was not found on this element.");
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002029 return 0;
2030 }
2031
Torne (Richard Coles)e5249552013-05-15 11:35:13 +01002032 RefPtr<Attr> guard(attr);
2033 detachAttrNodeAtIndex(attr, index);
2034 return guard.release();
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002035}
2036
Torne (Richard Coles)51b29062013-11-28 11:56:03 +00002037bool Element::parseAttributeName(QualifiedName& out, const AtomicString& namespaceURI, const AtomicString& qualifiedName, ExceptionState& exceptionState)
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002038{
Torne (Richard Coles)a854de02013-12-18 16:25:25 +00002039 AtomicString prefix, localName;
Torne (Richard Coles)51b29062013-11-28 11:56:03 +00002040 if (!Document::parseQualifiedName(qualifiedName, prefix, localName, exceptionState))
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002041 return false;
Torne (Richard Coles)51b29062013-11-28 11:56:03 +00002042 ASSERT(!exceptionState.hadException());
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002043
2044 QualifiedName qName(prefix, localName, namespaceURI);
2045
2046 if (!Document::hasValidNamespaceForAttributes(qName)) {
Torne (Richard Coles)09380292014-02-21 12:17:33 +00002047 exceptionState.throwDOMException(NamespaceError, "'" + namespaceURI + "' is an invalid namespace for attributes.");
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002048 return false;
2049 }
2050
2051 out = qName;
2052 return true;
2053}
2054
Torne (Richard Coles)51b29062013-11-28 11:56:03 +00002055void Element::setAttributeNS(const AtomicString& namespaceURI, const AtomicString& qualifiedName, const AtomicString& value, ExceptionState& exceptionState)
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002056{
2057 QualifiedName parsedName = anyName;
Torne (Richard Coles)51b29062013-11-28 11:56:03 +00002058 if (!parseAttributeName(parsedName, namespaceURI, qualifiedName, exceptionState))
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002059 return;
2060 setAttribute(parsedName, value);
2061}
2062
2063void Element::removeAttributeInternal(size_t index, SynchronizationOfLazyAttribute inSynchronizationOfLazyAttribute)
2064{
2065 ASSERT_WITH_SECURITY_IMPLICATION(index < attributeCount());
2066
2067 UniqueElementData* elementData = ensureUniqueElementData();
2068
2069 QualifiedName name = elementData->attributeItem(index)->name();
2070 AtomicString valueBeingRemoved = elementData->attributeItem(index)->value();
2071
2072 if (!inSynchronizationOfLazyAttribute) {
2073 if (!valueBeingRemoved.isNull())
2074 willModifyAttribute(name, valueBeingRemoved, nullAtom);
2075 }
2076
2077 if (RefPtr<Attr> attrNode = attrIfExists(name))
2078 detachAttrNodeFromElementWithValue(attrNode.get(), elementData->attributeItem(index)->value());
2079
2080 elementData->removeAttribute(index);
2081
2082 if (!inSynchronizationOfLazyAttribute)
2083 didRemoveAttribute(name);
2084}
2085
2086void Element::addAttributeInternal(const QualifiedName& name, const AtomicString& value, SynchronizationOfLazyAttribute inSynchronizationOfLazyAttribute)
2087{
2088 if (!inSynchronizationOfLazyAttribute)
2089 willModifyAttribute(name, nullAtom, value);
2090 ensureUniqueElementData()->addAttribute(name, value);
2091 if (!inSynchronizationOfLazyAttribute)
2092 didAddAttribute(name, value);
2093}
2094
2095void Element::removeAttribute(const AtomicString& name)
2096{
2097 if (!elementData())
2098 return;
2099
Torne (Richard Coles)bfe35902013-10-22 16:41:51 +01002100 AtomicString localName = shouldIgnoreAttributeCase() ? name.lower() : name;
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002101 size_t index = elementData()->getAttributeItemIndex(localName, false);
Torne (Richard Coles)06f816c2013-09-26 13:25:12 +01002102 if (index == kNotFound) {
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002103 if (UNLIKELY(localName == styleAttr) && elementData()->m_styleAttributeIsDirty && isStyledElement())
Ben Murdoch591b9582013-07-10 11:41:44 +01002104 removeAllInlineStyleProperties();
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002105 return;
2106 }
2107
2108 removeAttributeInternal(index, NotInSynchronizationOfLazyAttribute);
2109}
2110
2111void Element::removeAttributeNS(const AtomicString& namespaceURI, const AtomicString& localName)
2112{
2113 removeAttribute(QualifiedName(nullAtom, localName, namespaceURI));
2114}
2115
2116PassRefPtr<Attr> Element::getAttributeNode(const AtomicString& localName)
2117{
2118 if (!elementData())
2119 return 0;
2120 synchronizeAttribute(localName);
Torne (Richard Coles)bfe35902013-10-22 16:41:51 +01002121 const Attribute* attribute = elementData()->getAttributeItem(localName, shouldIgnoreAttributeCase());
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002122 if (!attribute)
2123 return 0;
2124 return ensureAttr(attribute->name());
2125}
2126
2127PassRefPtr<Attr> Element::getAttributeNodeNS(const AtomicString& namespaceURI, const AtomicString& localName)
2128{
2129 if (!elementData())
2130 return 0;
2131 QualifiedName qName(nullAtom, localName, namespaceURI);
2132 synchronizeAttribute(qName);
2133 const Attribute* attribute = elementData()->getAttributeItem(qName);
2134 if (!attribute)
2135 return 0;
2136 return ensureAttr(attribute->name());
2137}
2138
2139bool Element::hasAttribute(const AtomicString& localName) const
2140{
2141 if (!elementData())
2142 return false;
2143 synchronizeAttribute(localName);
Torne (Richard Coles)bfe35902013-10-22 16:41:51 +01002144 return elementData()->getAttributeItem(shouldIgnoreAttributeCase() ? localName.lower() : localName, false);
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002145}
2146
2147bool Element::hasAttributeNS(const AtomicString& namespaceURI, const AtomicString& localName) const
2148{
2149 if (!elementData())
2150 return false;
2151 QualifiedName qName(nullAtom, localName, namespaceURI);
2152 synchronizeAttribute(qName);
2153 return elementData()->getAttributeItem(qName);
2154}
2155
Torne (Richard Coles)09380292014-02-21 12:17:33 +00002156void Element::focus(bool restorePreviousSelection, FocusType type)
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002157{
2158 if (!inDocument())
2159 return;
2160
Torne (Richard Coles)8abfc582013-09-12 12:10:38 +01002161 Document& doc = document();
2162 if (doc.focusedElement() == this)
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002163 return;
2164
2165 // If the stylesheets have already been loaded we can reliably check isFocusable.
2166 // If not, we continue and set the focused node on the focus controller below so
Ben Murdoch591b9582013-07-10 11:41:44 +01002167 // that it can be updated soon after attach.
Torne (Richard Coles)8abfc582013-09-12 12:10:38 +01002168 if (doc.haveStylesheetsLoaded()) {
2169 doc.updateLayoutIgnorePendingStylesheets();
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002170 if (!isFocusable())
2171 return;
2172 }
2173
2174 if (!supportsFocus())
2175 return;
2176
2177 RefPtr<Node> protect;
Torne (Richard Coles)8abfc582013-09-12 12:10:38 +01002178 if (Page* page = doc.page()) {
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002179 // Focus and change event handlers can cause us to lose our last ref.
2180 // If a focus event handler changes the focus to a different node it
2181 // does not make sense to continue and update appearence.
2182 protect = this;
Torne (Richard Coles)09380292014-02-21 12:17:33 +00002183 if (!page->focusController().setFocusedElement(this, doc.frame(), type))
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002184 return;
2185 }
2186
2187 // Setting the focused node above might have invalidated the layout due to scripts.
Torne (Richard Coles)8abfc582013-09-12 12:10:38 +01002188 doc.updateLayoutIgnorePendingStylesheets();
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002189
2190 if (!isFocusable()) {
Torne (Richard Coles)bfe35902013-10-22 16:41:51 +01002191 ensureElementRareData().setNeedsFocusAppearanceUpdateSoonAfterAttach(true);
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002192 return;
2193 }
Ben Murdoch591b9582013-07-10 11:41:44 +01002194
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002195 cancelFocusAppearanceUpdate();
2196 updateFocusAppearance(restorePreviousSelection);
2197}
2198
2199void Element::updateFocusAppearance(bool /*restorePreviousSelection*/)
2200{
2201 if (isRootEditableElement()) {
Torne (Richard Coles)8abfc582013-09-12 12:10:38 +01002202 Frame* frame = document().frame();
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002203 if (!frame)
2204 return;
Ben Murdoch591b9582013-07-10 11:41:44 +01002205
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002206 // 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 +01002207 if (this == frame->selection().rootEditableElement())
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002208 return;
2209
2210 // FIXME: We should restore the previous selection if there is one.
2211 VisibleSelection newSelection = VisibleSelection(firstPositionInOrBeforeNode(this), DOWNSTREAM);
Torne (Richard Coles)1e202182013-10-18 15:46:42 +01002212 frame->selection().setSelection(newSelection);
2213 frame->selection().revealSelection();
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002214 } else if (renderer() && !renderer()->isWidget())
2215 renderer()->scrollRectToVisible(boundingBox());
2216}
2217
2218void Element::blur()
2219{
2220 cancelFocusAppearanceUpdate();
Torne (Richard Coles)8abfc582013-09-12 12:10:38 +01002221 if (treeScope().adjustedFocusedElement() == this) {
2222 Document& doc = document();
2223 if (doc.page())
2224 doc.page()->focusController().setFocusedElement(0, doc.frame());
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002225 else
Torne (Richard Coles)8abfc582013-09-12 12:10:38 +01002226 doc.setFocusedElement(0);
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002227 }
2228}
2229
Ben Murdochdf957042013-08-06 11:01:27 +01002230bool Element::isFocusable() const
2231{
2232 return inDocument() && supportsFocus() && !isInert() && rendererIsFocusable();
2233}
2234
Torne (Richard Coles)f5e4ad52013-08-05 13:57:57 +01002235bool Element::isKeyboardFocusable() const
2236{
2237 return isFocusable() && tabIndex() >= 0;
2238}
2239
2240bool Element::isMouseFocusable() const
2241{
2242 return isFocusable();
2243}
2244
Torne (Richard Coles)09380292014-02-21 12:17:33 +00002245void Element::dispatchFocusEvent(Element* oldFocusedElement, FocusType)
Ben Murdoch02772c62013-07-26 10:21:05 +01002246{
Torne (Richard Coles)bfe35902013-10-22 16:41:51 +01002247 RefPtr<FocusEvent> event = FocusEvent::create(EventTypeNames::focus, false, false, document().domWindow(), 0, oldFocusedElement);
Ben Murdoch02772c62013-07-26 10:21:05 +01002248 EventDispatcher::dispatchEvent(this, FocusEventDispatchMediator::create(event.release()));
2249}
2250
2251void Element::dispatchBlurEvent(Element* newFocusedElement)
2252{
Torne (Richard Coles)bfe35902013-10-22 16:41:51 +01002253 RefPtr<FocusEvent> event = FocusEvent::create(EventTypeNames::blur, false, false, document().domWindow(), 0, newFocusedElement);
Ben Murdoch02772c62013-07-26 10:21:05 +01002254 EventDispatcher::dispatchEvent(this, BlurEventDispatchMediator::create(event.release()));
2255}
2256
2257void Element::dispatchFocusInEvent(const AtomicString& eventType, Element* oldFocusedElement)
2258{
2259 ASSERT(!NoEventDispatchAssertion::isEventDispatchForbidden());
Torne (Richard Coles)1e202182013-10-18 15:46:42 +01002260 ASSERT(eventType == EventTypeNames::focusin || eventType == EventTypeNames::DOMFocusIn);
Torne (Richard Coles)bfe35902013-10-22 16:41:51 +01002261 dispatchScopedEventDispatchMediator(FocusInEventDispatchMediator::create(FocusEvent::create(eventType, true, false, document().domWindow(), 0, oldFocusedElement)));
Ben Murdoch02772c62013-07-26 10:21:05 +01002262}
2263
2264void Element::dispatchFocusOutEvent(const AtomicString& eventType, Element* newFocusedElement)
2265{
2266 ASSERT(!NoEventDispatchAssertion::isEventDispatchForbidden());
Torne (Richard Coles)1e202182013-10-18 15:46:42 +01002267 ASSERT(eventType == EventTypeNames::focusout || eventType == EventTypeNames::DOMFocusOut);
Torne (Richard Coles)bfe35902013-10-22 16:41:51 +01002268 dispatchScopedEventDispatchMediator(FocusOutEventDispatchMediator::create(FocusEvent::create(eventType, true, false, document().domWindow(), 0, newFocusedElement)));
Ben Murdoch02772c62013-07-26 10:21:05 +01002269}
2270
Torne (Richard Coles)19cde672013-11-06 12:28:04 +00002271String Element::innerHTML() const
2272{
2273 return createMarkup(this, ChildrenOnly);
2274}
2275
2276String Element::outerHTML() const
2277{
2278 return createMarkup(this);
2279}
2280
Torne (Richard Coles)51b29062013-11-28 11:56:03 +00002281void Element::setInnerHTML(const String& html, ExceptionState& exceptionState)
Torne (Richard Coles)19cde672013-11-06 12:28:04 +00002282{
Torne (Richard Coles)51b29062013-11-28 11:56:03 +00002283 if (RefPtr<DocumentFragment> fragment = createFragmentForInnerOuterHTML(html, this, AllowScriptingContent, "innerHTML", exceptionState)) {
Torne (Richard Coles)19cde672013-11-06 12:28:04 +00002284 ContainerNode* container = this;
2285 if (hasTagName(templateTag))
2286 container = toHTMLTemplateElement(this)->content();
Torne (Richard Coles)51b29062013-11-28 11:56:03 +00002287 replaceChildrenWithFragment(container, fragment.release(), exceptionState);
Torne (Richard Coles)19cde672013-11-06 12:28:04 +00002288 }
2289}
2290
Torne (Richard Coles)51b29062013-11-28 11:56:03 +00002291void Element::setOuterHTML(const String& html, ExceptionState& exceptionState)
Torne (Richard Coles)19cde672013-11-06 12:28:04 +00002292{
2293 Node* p = parentNode();
Torne (Richard Coles)09380292014-02-21 12:17:33 +00002294 if (!p) {
2295 exceptionState.throwDOMException(NoModificationAllowedError, "This element has no parent node.");
Torne (Richard Coles)19cde672013-11-06 12:28:04 +00002296 return;
2297 }
Torne (Richard Coles)09380292014-02-21 12:17:33 +00002298 if (!p->isElementNode()) {
2299 exceptionState.throwDOMException(NoModificationAllowedError, "This element's parent is of type '" + p->nodeName() + "', which is not an element node.");
2300 return;
2301 }
2302
Torne (Richard Coles)19cde672013-11-06 12:28:04 +00002303 RefPtr<Element> parent = toElement(p);
2304 RefPtr<Node> prev = previousSibling();
2305 RefPtr<Node> next = nextSibling();
2306
Torne (Richard Coles)51b29062013-11-28 11:56:03 +00002307 RefPtr<DocumentFragment> fragment = createFragmentForInnerOuterHTML(html, parent.get(), AllowScriptingContent, "outerHTML", exceptionState);
2308 if (exceptionState.hadException())
Torne (Richard Coles)19cde672013-11-06 12:28:04 +00002309 return;
2310
Torne (Richard Coles)51b29062013-11-28 11:56:03 +00002311 parent->replaceChild(fragment.release(), this, exceptionState);
Torne (Richard Coles)19cde672013-11-06 12:28:04 +00002312 RefPtr<Node> node = next ? next->previousSibling() : 0;
Torne (Richard Coles)51b29062013-11-28 11:56:03 +00002313 if (!exceptionState.hadException() && node && node->isTextNode())
2314 mergeWithNextTextNode(node.release(), exceptionState);
Torne (Richard Coles)19cde672013-11-06 12:28:04 +00002315
Torne (Richard Coles)51b29062013-11-28 11:56:03 +00002316 if (!exceptionState.hadException() && prev && prev->isTextNode())
2317 mergeWithNextTextNode(prev.release(), exceptionState);
Torne (Richard Coles)19cde672013-11-06 12:28:04 +00002318}
2319
Torne (Richard Coles)a854de02013-12-18 16:25:25 +00002320Node* Element::insertAdjacent(const String& where, Node* newChild, ExceptionState& exceptionState)
2321{
2322 if (equalIgnoringCase(where, "beforeBegin")) {
2323 if (ContainerNode* parent = this->parentNode()) {
2324 parent->insertBefore(newChild, this, exceptionState);
2325 if (!exceptionState.hadException())
2326 return newChild;
2327 }
2328 return 0;
2329 }
2330
2331 if (equalIgnoringCase(where, "afterBegin")) {
2332 insertBefore(newChild, firstChild(), exceptionState);
2333 return exceptionState.hadException() ? 0 : newChild;
2334 }
2335
2336 if (equalIgnoringCase(where, "beforeEnd")) {
2337 appendChild(newChild, exceptionState);
2338 return exceptionState.hadException() ? 0 : newChild;
2339 }
2340
2341 if (equalIgnoringCase(where, "afterEnd")) {
2342 if (ContainerNode* parent = this->parentNode()) {
2343 parent->insertBefore(newChild, nextSibling(), exceptionState);
2344 if (!exceptionState.hadException())
2345 return newChild;
2346 }
2347 return 0;
2348 }
2349
2350 exceptionState.throwDOMException(SyntaxError, "The value provided ('" + where + "') is not one of 'beforeBegin', 'afterBegin', 'beforeEnd', or 'afterEnd'.");
2351 return 0;
2352}
2353
2354// Step 1 of http://domparsing.spec.whatwg.org/#insertadjacenthtml()
2355static Element* contextElementForInsertion(const String& where, Element* element, ExceptionState& exceptionState)
2356{
2357 if (equalIgnoringCase(where, "beforeBegin") || equalIgnoringCase(where, "afterEnd")) {
2358 ContainerNode* parent = element->parentNode();
2359 if (!parent || !parent->isElementNode()) {
2360 exceptionState.throwDOMException(NoModificationAllowedError, "The element has no parent.");
2361 return 0;
2362 }
2363 return toElement(parent);
2364 }
2365 if (equalIgnoringCase(where, "afterBegin") || equalIgnoringCase(where, "beforeEnd"))
2366 return element;
2367 exceptionState.throwDOMException(SyntaxError, "The value provided ('" + where + "') is not one of 'beforeBegin', 'afterBegin', 'beforeEnd', or 'afterEnd'.");
2368 return 0;
2369}
2370
Torne (Richard Coles)09380292014-02-21 12:17:33 +00002371Element* Element::insertAdjacentElement(const String& where, Element* newChild, ExceptionState& exceptionState)
2372{
2373 if (!newChild) {
2374 // IE throws COM Exception E_INVALIDARG; this is the best DOM exception alternative.
2375 exceptionState.throwTypeError("The node provided is null.");
2376 return 0;
2377 }
2378
2379 Node* returnValue = insertAdjacent(where, newChild, exceptionState);
2380 return toElement(returnValue);
2381}
2382
2383void Element::insertAdjacentText(const String& where, const String& text, ExceptionState& exceptionState)
2384{
2385 RefPtr<Text> textNode = document().createTextNode(text);
2386 insertAdjacent(where, textNode.get(), exceptionState);
2387}
2388
Torne (Richard Coles)a854de02013-12-18 16:25:25 +00002389void Element::insertAdjacentHTML(const String& where, const String& markup, ExceptionState& exceptionState)
2390{
2391 RefPtr<Element> contextElement = contextElementForInsertion(where, this, exceptionState);
2392 if (!contextElement)
2393 return;
2394
2395 RefPtr<DocumentFragment> fragment = createFragmentForInnerOuterHTML(markup, contextElement.get(), AllowScriptingContent, "insertAdjacentHTML", exceptionState);
2396 if (!fragment)
2397 return;
2398 insertAdjacent(where, fragment.get(), exceptionState);
2399}
2400
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002401String Element::innerText()
2402{
2403 // We need to update layout, since plainText uses line boxes in the render tree.
Torne (Richard Coles)8abfc582013-09-12 12:10:38 +01002404 document().updateLayoutIgnorePendingStylesheets();
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002405
2406 if (!renderer())
2407 return textContent(true);
2408
2409 return plainText(rangeOfContents(const_cast<Element*>(this)).get());
2410}
2411
2412String Element::outerText()
2413{
2414 // Getting outerText is the same as getting innerText, only
2415 // setting is different. You would think this should get the plain
2416 // text for the outer range, but this is wrong, <br> for instance
2417 // would return different values for inner and outer text by such
2418 // a rule, but it doesn't in WinIE, and we want to match that.
2419 return innerText();
2420}
2421
Ben Murdoch591b9582013-07-10 11:41:44 +01002422String Element::textFromChildren()
2423{
2424 Text* firstTextNode = 0;
2425 bool foundMultipleTextNodes = false;
2426 unsigned totalLength = 0;
2427
2428 for (Node* child = firstChild(); child; child = child->nextSibling()) {
2429 if (!child->isTextNode())
2430 continue;
2431 Text* text = toText(child);
2432 if (!firstTextNode)
2433 firstTextNode = text;
2434 else
2435 foundMultipleTextNodes = true;
2436 unsigned length = text->data().length();
2437 if (length > std::numeric_limits<unsigned>::max() - totalLength)
2438 return emptyString();
2439 totalLength += length;
2440 }
2441
2442 if (!firstTextNode)
2443 return emptyString();
2444
2445 if (firstTextNode && !foundMultipleTextNodes) {
2446 firstTextNode->atomize();
2447 return firstTextNode->data();
2448 }
2449
2450 StringBuilder content;
2451 content.reserveCapacity(totalLength);
2452 for (Node* child = firstTextNode; child; child = child->nextSibling()) {
2453 if (!child->isTextNode())
2454 continue;
2455 content.append(toText(child)->data());
2456 }
2457
2458 ASSERT(content.length() == totalLength);
2459 return content.toString();
2460}
2461
Torne (Richard Coles)09380292014-02-21 12:17:33 +00002462const AtomicString& Element::shadowPseudoId() const
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002463{
Torne (Richard Coles)09380292014-02-21 12:17:33 +00002464 if (ShadowRoot* root = containingShadowRoot()) {
2465 if (root->type() == ShadowRoot::UserAgentShadowRoot)
2466 return fastGetAttribute(pseudoAttr);
2467 }
2468 return nullAtom;
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002469}
2470
Torne (Richard Coles)09380292014-02-21 12:17:33 +00002471void Element::setShadowPseudoId(const AtomicString& id)
Torne (Richard Coles)f5e4ad52013-08-05 13:57:57 +01002472{
Torne (Richard Coles)09380292014-02-21 12:17:33 +00002473 ASSERT(CSSSelector::parsePseudoType(id) == CSSSelector::PseudoWebKitCustomElement || CSSSelector::parsePseudoType(id) == CSSSelector::PseudoUserAgentCustomElement);
2474 setAttribute(pseudoAttr, id);
Torne (Richard Coles)f5e4ad52013-08-05 13:57:57 +01002475}
2476
Torne (Richard Coles)51b29062013-11-28 11:56:03 +00002477bool Element::isInDescendantTreeOf(const Element* shadowHost) const
Torne (Richard Coles)f5e4ad52013-08-05 13:57:57 +01002478{
Torne (Richard Coles)51b29062013-11-28 11:56:03 +00002479 ASSERT(shadowHost);
2480 ASSERT(isShadowHost(shadowHost));
2481
2482 const ShadowRoot* shadowRoot = containingShadowRoot();
2483 while (shadowRoot) {
2484 const Element* ancestorShadowHost = shadowRoot->shadowHost();
2485 if (ancestorShadowHost == shadowHost)
2486 return true;
2487 shadowRoot = ancestorShadowHost->containingShadowRoot();
2488 }
2489 return false;
Torne (Richard Coles)f5e4ad52013-08-05 13:57:57 +01002490}
2491
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002492LayoutSize Element::minimumSizeForResizing() const
2493{
2494 return hasRareData() ? elementRareData()->minimumSizeForResizing() : defaultMinimumSizeForResizing();
2495}
2496
2497void Element::setMinimumSizeForResizing(const LayoutSize& size)
2498{
2499 if (!hasRareData() && size == defaultMinimumSizeForResizing())
2500 return;
Torne (Richard Coles)bfe35902013-10-22 16:41:51 +01002501 ensureElementRareData().setMinimumSizeForResizing(size);
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002502}
2503
2504RenderStyle* Element::computedStyle(PseudoId pseudoElementSpecifier)
2505{
2506 if (PseudoElement* element = pseudoElement(pseudoElementSpecifier))
2507 return element->computedStyle();
2508
2509 // FIXME: Find and use the renderer from the pseudo element instead of the actual element so that the 'length'
2510 // properties, which are only known by the renderer because it did the layout, will be correct and so that the
2511 // values returned for the ":selection" pseudo-element will be correct.
2512 if (RenderStyle* usedStyle = renderStyle()) {
2513 if (pseudoElementSpecifier) {
2514 RenderStyle* cachedPseudoStyle = usedStyle->getCachedPseudoStyle(pseudoElementSpecifier);
2515 return cachedPseudoStyle ? cachedPseudoStyle : usedStyle;
2516 } else
2517 return usedStyle;
2518 }
2519
Torne (Richard Coles)f79f16f2013-10-31 11:16:44 +00002520 if (!inActiveDocument())
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002521 // FIXME: Try to do better than this. Ensure that styleForElement() works for elements that are not in the
2522 // document tree and figure out when to destroy the computed style for such elements.
2523 return 0;
2524
Torne (Richard Coles)bfe35902013-10-22 16:41:51 +01002525 ElementRareData& rareData = ensureElementRareData();
2526 if (!rareData.computedStyle())
2527 rareData.setComputedStyle(document().styleForElementIgnoringPendingStylesheets(this));
2528 return pseudoElementSpecifier ? rareData.computedStyle()->getCachedPseudoStyle(pseudoElementSpecifier) : rareData.computedStyle();
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002529}
2530
2531void Element::setStyleAffectedByEmpty()
2532{
Torne (Richard Coles)bfe35902013-10-22 16:41:51 +01002533 ensureElementRareData().setStyleAffectedByEmpty(true);
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002534}
2535
Torne (Richard Coles)51b29062013-11-28 11:56:03 +00002536void Element::setChildrenAffectedByFocus()
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002537{
Torne (Richard Coles)51b29062013-11-28 11:56:03 +00002538 ensureElementRareData().setChildrenAffectedByFocus(true);
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002539}
2540
Torne (Richard Coles)51b29062013-11-28 11:56:03 +00002541void Element::setChildrenAffectedByHover()
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002542{
Torne (Richard Coles)51b29062013-11-28 11:56:03 +00002543 ensureElementRareData().setChildrenAffectedByHover(true);
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002544}
2545
Torne (Richard Coles)51b29062013-11-28 11:56:03 +00002546void Element::setChildrenAffectedByActive()
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002547{
Torne (Richard Coles)51b29062013-11-28 11:56:03 +00002548 ensureElementRareData().setChildrenAffectedByActive(true);
2549}
2550
2551void Element::setChildrenAffectedByDrag()
2552{
2553 ensureElementRareData().setChildrenAffectedByDrag(true);
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002554}
2555
2556void Element::setChildrenAffectedByFirstChildRules()
2557{
Torne (Richard Coles)bfe35902013-10-22 16:41:51 +01002558 ensureElementRareData().setChildrenAffectedByFirstChildRules(true);
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002559}
2560
2561void Element::setChildrenAffectedByLastChildRules()
2562{
Torne (Richard Coles)bfe35902013-10-22 16:41:51 +01002563 ensureElementRareData().setChildrenAffectedByLastChildRules(true);
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002564}
2565
2566void Element::setChildrenAffectedByDirectAdjacentRules()
2567{
Torne (Richard Coles)bfe35902013-10-22 16:41:51 +01002568 ensureElementRareData().setChildrenAffectedByDirectAdjacentRules(true);
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002569}
2570
2571void Element::setChildrenAffectedByForwardPositionalRules()
2572{
Torne (Richard Coles)bfe35902013-10-22 16:41:51 +01002573 ensureElementRareData().setChildrenAffectedByForwardPositionalRules(true);
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002574}
2575
2576void Element::setChildrenAffectedByBackwardPositionalRules()
2577{
Torne (Richard Coles)bfe35902013-10-22 16:41:51 +01002578 ensureElementRareData().setChildrenAffectedByBackwardPositionalRules(true);
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002579}
2580
2581void Element::setChildIndex(unsigned index)
2582{
Torne (Richard Coles)bfe35902013-10-22 16:41:51 +01002583 ElementRareData& rareData = ensureElementRareData();
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002584 if (RenderStyle* style = renderStyle())
2585 style->setUnique();
Torne (Richard Coles)bfe35902013-10-22 16:41:51 +01002586 rareData.setChildIndex(index);
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002587}
2588
Torne (Richard Coles)bfe35902013-10-22 16:41:51 +01002589bool Element::childrenSupportStyleSharing() const
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002590{
2591 if (!hasRareData())
Torne (Richard Coles)bfe35902013-10-22 16:41:51 +01002592 return true;
Torne (Richard Coles)51b29062013-11-28 11:56:03 +00002593 return !rareDataChildrenAffectedByFocus()
2594 && !rareDataChildrenAffectedByHover()
Torne (Richard Coles)bfe35902013-10-22 16:41:51 +01002595 && !rareDataChildrenAffectedByActive()
2596 && !rareDataChildrenAffectedByDrag()
2597 && !rareDataChildrenAffectedByFirstChildRules()
2598 && !rareDataChildrenAffectedByLastChildRules()
2599 && !rareDataChildrenAffectedByDirectAdjacentRules()
2600 && !rareDataChildrenAffectedByForwardPositionalRules()
2601 && !rareDataChildrenAffectedByBackwardPositionalRules();
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002602}
2603
2604bool Element::rareDataStyleAffectedByEmpty() const
2605{
2606 ASSERT(hasRareData());
2607 return elementRareData()->styleAffectedByEmpty();
2608}
2609
Torne (Richard Coles)51b29062013-11-28 11:56:03 +00002610bool Element::rareDataChildrenAffectedByFocus() const
2611{
2612 ASSERT(hasRareData());
2613 return elementRareData()->childrenAffectedByFocus();
2614}
2615
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002616bool Element::rareDataChildrenAffectedByHover() const
2617{
2618 ASSERT(hasRareData());
2619 return elementRareData()->childrenAffectedByHover();
2620}
2621
2622bool Element::rareDataChildrenAffectedByActive() const
2623{
2624 ASSERT(hasRareData());
2625 return elementRareData()->childrenAffectedByActive();
2626}
2627
2628bool Element::rareDataChildrenAffectedByDrag() const
2629{
2630 ASSERT(hasRareData());
2631 return elementRareData()->childrenAffectedByDrag();
2632}
2633
2634bool Element::rareDataChildrenAffectedByFirstChildRules() const
2635{
2636 ASSERT(hasRareData());
2637 return elementRareData()->childrenAffectedByFirstChildRules();
2638}
2639
2640bool Element::rareDataChildrenAffectedByLastChildRules() const
2641{
2642 ASSERT(hasRareData());
2643 return elementRareData()->childrenAffectedByLastChildRules();
2644}
2645
2646bool Element::rareDataChildrenAffectedByDirectAdjacentRules() const
2647{
2648 ASSERT(hasRareData());
2649 return elementRareData()->childrenAffectedByDirectAdjacentRules();
2650}
2651
2652bool Element::rareDataChildrenAffectedByForwardPositionalRules() const
2653{
2654 ASSERT(hasRareData());
2655 return elementRareData()->childrenAffectedByForwardPositionalRules();
2656}
2657
2658bool Element::rareDataChildrenAffectedByBackwardPositionalRules() const
2659{
2660 ASSERT(hasRareData());
2661 return elementRareData()->childrenAffectedByBackwardPositionalRules();
2662}
2663
2664unsigned Element::rareDataChildIndex() const
2665{
2666 ASSERT(hasRareData());
2667 return elementRareData()->childIndex();
2668}
2669
2670void Element::setIsInCanvasSubtree(bool isInCanvasSubtree)
2671{
Torne (Richard Coles)bfe35902013-10-22 16:41:51 +01002672 ensureElementRareData().setIsInCanvasSubtree(isInCanvasSubtree);
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002673}
2674
2675bool Element::isInCanvasSubtree() const
2676{
2677 return hasRareData() && elementRareData()->isInCanvasSubtree();
2678}
2679
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002680AtomicString Element::computeInheritedLanguage() const
2681{
2682 const Node* n = this;
2683 AtomicString value;
2684 // The language property is inherited, so we iterate over the parents to find the first language.
2685 do {
2686 if (n->isElementNode()) {
2687 if (const ElementData* elementData = toElement(n)->elementData()) {
2688 // Spec: xml:lang takes precedence -- http://www.w3.org/TR/xhtml1/#C_7
2689 if (const Attribute* attribute = elementData->getAttributeItem(XMLNames::langAttr))
2690 value = attribute->value();
2691 else if (const Attribute* attribute = elementData->getAttributeItem(HTMLNames::langAttr))
2692 value = attribute->value();
2693 }
2694 } else if (n->isDocumentNode()) {
2695 // checking the MIME content-language
2696 value = toDocument(n)->contentLanguage();
2697 }
2698
2699 n = n->parentNode();
2700 } while (n && value.isNull());
2701
2702 return value;
2703}
2704
2705Locale& Element::locale() const
2706{
Torne (Richard Coles)8abfc582013-09-12 12:10:38 +01002707 return document().getCachedLocale(computeInheritedLanguage());
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002708}
2709
2710void Element::cancelFocusAppearanceUpdate()
2711{
2712 if (hasRareData())
2713 elementRareData()->setNeedsFocusAppearanceUpdateSoonAfterAttach(false);
Torne (Richard Coles)8abfc582013-09-12 12:10:38 +01002714 if (document().focusedElement() == this)
2715 document().cancelFocusAppearanceUpdate();
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002716}
2717
2718void Element::normalizeAttributes()
2719{
2720 if (!hasAttributes())
2721 return;
2722 for (unsigned i = 0; i < attributeCount(); ++i) {
2723 if (RefPtr<Attr> attr = attrIfExists(attributeItem(i)->name()))
2724 attr->normalize();
2725 }
2726}
2727
Torne (Richard Coles)8abfc582013-09-12 12:10:38 +01002728void Element::updatePseudoElement(PseudoId pseudoId, StyleRecalcChange change)
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002729{
Torne (Richard Coles)09380292014-02-21 12:17:33 +00002730 ASSERT(!needsStyleRecalc());
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002731 PseudoElement* element = pseudoElement(pseudoId);
Torne (Richard Coles)09380292014-02-21 12:17:33 +00002732 if (element && (change == UpdatePseudoElements || element->shouldCallRecalcStyle(change))) {
2733
Torne (Richard Coles)51b29062013-11-28 11:56:03 +00002734 // Need to clear the cached style if the PseudoElement wants a recalc so it
2735 // computes a new style.
2736 if (element->needsStyleRecalc())
2737 renderer()->style()->removeCachedPseudoStyle(pseudoId);
2738
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002739 // PseudoElement styles hang off their parent element's style so if we needed
2740 // a style recalc we should Force one on the pseudo.
Torne (Richard Coles)51b29062013-11-28 11:56:03 +00002741 // FIXME: We should figure out the right text sibling to pass.
Torne (Richard Coles)09380292014-02-21 12:17:33 +00002742 element->recalcStyle(change == UpdatePseudoElements ? Force : change);
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002743
2744 // Wait until our parent is not displayed or pseudoElementRendererIsNeeded
2745 // is false, otherwise we could continously create and destroy PseudoElements
2746 // when RenderObject::isChildAllowed on our parent returns false for the
2747 // PseudoElement's renderer for each style recalc.
2748 if (!renderer() || !pseudoElementRendererIsNeeded(renderer()->getCachedPseudoStyle(pseudoId)))
Torne (Richard Coles)521d96e2013-06-19 11:58:24 +01002749 elementRareData()->setPseudoElement(pseudoId, 0);
Torne (Richard Coles)09380292014-02-21 12:17:33 +00002750 } else if (change >= UpdatePseudoElements) {
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002751 createPseudoElementIfNeeded(pseudoId);
Torne (Richard Coles)09380292014-02-21 12:17:33 +00002752 }
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002753}
2754
2755void Element::createPseudoElementIfNeeded(PseudoId pseudoId)
2756{
Torne (Richard Coles)09380292014-02-21 12:17:33 +00002757 if (isPseudoElement())
2758 return;
Torne (Richard Coles)9bbd2f52013-09-19 22:37:05 +01002759
Torne (Richard Coles)09380292014-02-21 12:17:33 +00002760 RefPtr<PseudoElement> element = document().ensureStyleResolver().createPseudoElementIfNeeded(*this, pseudoId);
2761 if (!element)
2762 return;
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002763
Ben Murdoche69819b2013-07-17 14:56:49 +01002764 if (pseudoId == BACKDROP)
Torne (Richard Coles)8abfc582013-09-12 12:10:38 +01002765 document().addToTopLayer(element.get(), this);
Torne (Richard Coles)19cde672013-11-06 12:28:04 +00002766 element->insertedInto(this);
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002767 element->attach();
Ben Murdoche69819b2013-07-17 14:56:49 +01002768
Torne (Richard Coles)19cde672013-11-06 12:28:04 +00002769 InspectorInstrumentation::pseudoElementCreated(element.get());
2770
Torne (Richard Coles)bfe35902013-10-22 16:41:51 +01002771 ensureElementRareData().setPseudoElement(pseudoId, element.release());
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002772}
2773
2774PseudoElement* Element::pseudoElement(PseudoId pseudoId) const
2775{
2776 return hasRareData() ? elementRareData()->pseudoElement(pseudoId) : 0;
2777}
2778
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002779RenderObject* Element::pseudoElementRenderer(PseudoId pseudoId) const
2780{
2781 if (PseudoElement* element = pseudoElement(pseudoId))
2782 return element->renderer();
2783 return 0;
2784}
2785
Torne (Richard Coles)09380292014-02-21 12:17:33 +00002786bool Element::matches(const String& selectors, ExceptionState& exceptionState)
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002787{
Torne (Richard Coles)09380292014-02-21 12:17:33 +00002788 SelectorQuery* selectorQuery = document().selectorQueryCache().add(AtomicString(selectors), document(), exceptionState);
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002789 if (!selectorQuery)
2790 return false;
Torne (Richard Coles)19cde672013-11-06 12:28:04 +00002791 return selectorQuery->matches(*this);
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002792}
2793
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002794DOMTokenList* Element::classList()
2795{
Torne (Richard Coles)bfe35902013-10-22 16:41:51 +01002796 ElementRareData& rareData = ensureElementRareData();
2797 if (!rareData.classList())
2798 rareData.setClassList(ClassList::create(this));
2799 return rareData.classList();
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002800}
2801
2802DOMStringMap* Element::dataset()
2803{
Torne (Richard Coles)bfe35902013-10-22 16:41:51 +01002804 ElementRareData& rareData = ensureElementRareData();
2805 if (!rareData.dataset())
2806 rareData.setDataset(DatasetDOMStringMap::create(this));
2807 return rareData.dataset();
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002808}
2809
2810KURL Element::getURLAttribute(const QualifiedName& name) const
2811{
2812#if !ASSERT_DISABLED
2813 if (elementData()) {
2814 if (const Attribute* attribute = getAttributeItem(name))
2815 ASSERT(isURLAttribute(*attribute));
2816 }
2817#endif
Torne (Richard Coles)8abfc582013-09-12 12:10:38 +01002818 return document().completeURL(stripLeadingAndTrailingHTMLSpaces(getAttribute(name)));
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002819}
2820
2821KURL Element::getNonEmptyURLAttribute(const QualifiedName& name) const
2822{
2823#if !ASSERT_DISABLED
2824 if (elementData()) {
2825 if (const Attribute* attribute = getAttributeItem(name))
2826 ASSERT(isURLAttribute(*attribute));
2827 }
2828#endif
2829 String value = stripLeadingAndTrailingHTMLSpaces(getAttribute(name));
2830 if (value.isEmpty())
2831 return KURL();
Torne (Richard Coles)8abfc582013-09-12 12:10:38 +01002832 return document().completeURL(value);
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002833}
2834
2835int Element::getIntegralAttribute(const QualifiedName& attributeName) const
2836{
2837 return getAttribute(attributeName).string().toInt();
2838}
2839
2840void Element::setIntegralAttribute(const QualifiedName& attributeName, int value)
2841{
Torne (Richard Coles)51b29062013-11-28 11:56:03 +00002842 setAttribute(attributeName, AtomicString::number(value));
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002843}
2844
2845unsigned Element::getUnsignedIntegralAttribute(const QualifiedName& attributeName) const
2846{
2847 return getAttribute(attributeName).string().toUInt();
2848}
2849
2850void Element::setUnsignedIntegralAttribute(const QualifiedName& attributeName, unsigned value)
2851{
Torne (Richard Coles)09380292014-02-21 12:17:33 +00002852 // Range restrictions are enforced for unsigned IDL attributes that
2853 // reflect content attributes,
2854 // http://www.whatwg.org/specs/web-apps/current-work/multipage/common-dom-interfaces.html#reflecting-content-attributes-in-idl-attributes
2855 if (value > 0x7fffffffu)
2856 value = 0;
Torne (Richard Coles)51b29062013-11-28 11:56:03 +00002857 setAttribute(attributeName, AtomicString::number(value));
2858}
2859
2860double Element::getFloatingPointAttribute(const QualifiedName& attributeName, double fallbackValue) const
2861{
2862 return parseToDoubleForNumberType(getAttribute(attributeName), fallbackValue);
2863}
2864
2865void Element::setFloatingPointAttribute(const QualifiedName& attributeName, double value)
2866{
2867 setAttribute(attributeName, AtomicString::number(value));
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002868}
2869
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002870void Element::webkitRequestFullscreen()
2871{
Torne (Richard Coles)8abfc582013-09-12 12:10:38 +01002872 FullscreenElementStack::from(&document())->requestFullScreenForElement(this, ALLOW_KEYBOARD_INPUT, FullscreenElementStack::EnforceIFrameAllowFullScreenRequirement);
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002873}
2874
2875void Element::webkitRequestFullScreen(unsigned short flags)
2876{
Torne (Richard Coles)8abfc582013-09-12 12:10:38 +01002877 FullscreenElementStack::from(&document())->requestFullScreenForElement(this, (flags | LEGACY_MOZILLA_REQUEST), FullscreenElementStack::EnforceIFrameAllowFullScreenRequirement);
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002878}
2879
2880bool Element::containsFullScreenElement() const
2881{
2882 return hasRareData() && elementRareData()->containsFullScreenElement();
2883}
2884
2885void Element::setContainsFullScreenElement(bool flag)
2886{
Torne (Richard Coles)bfe35902013-10-22 16:41:51 +01002887 ensureElementRareData().setContainsFullScreenElement(flag);
Ben Murdoche69819b2013-07-17 14:56:49 +01002888 setNeedsStyleRecalc(SubtreeStyleChange);
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002889}
2890
2891static Element* parentCrossingFrameBoundaries(Element* element)
2892{
2893 ASSERT(element);
Torne (Richard Coles)8abfc582013-09-12 12:10:38 +01002894 return element->parentElement() ? element->parentElement() : element->document().ownerElement();
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002895}
2896
2897void Element::setContainsFullScreenElementOnAncestorsCrossingFrameBoundaries(bool flag)
2898{
2899 Element* element = this;
2900 while ((element = parentCrossingFrameBoundaries(element)))
2901 element->setContainsFullScreenElement(flag);
2902}
2903
2904bool Element::isInTopLayer() const
2905{
2906 return hasRareData() && elementRareData()->isInTopLayer();
2907}
2908
2909void Element::setIsInTopLayer(bool inTopLayer)
2910{
2911 if (isInTopLayer() == inTopLayer)
2912 return;
Torne (Richard Coles)bfe35902013-10-22 16:41:51 +01002913 ensureElementRareData().setIsInTopLayer(inTopLayer);
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002914
2915 // We must ensure a reattach occurs so the renderer is inserted in the correct sibling order under RenderView according to its
2916 // top layer position, or in its usual place if not in the top layer.
Torne (Richard Coles)93ac45c2013-05-29 14:40:20 +01002917 lazyReattachIfAttached();
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002918}
2919
2920void Element::webkitRequestPointerLock()
2921{
Torne (Richard Coles)8abfc582013-09-12 12:10:38 +01002922 if (document().page())
2923 document().page()->pointerLockController().requestPointerLock(this);
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002924}
2925
2926SpellcheckAttributeState Element::spellcheckAttributeState() const
2927{
Torne (Richard Coles)09380292014-02-21 12:17:33 +00002928 const AtomicString& value = fastGetAttribute(spellcheckAttr);
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002929 if (value == nullAtom)
2930 return SpellcheckAttributeDefault;
2931 if (equalIgnoringCase(value, "true") || equalIgnoringCase(value, ""))
2932 return SpellcheckAttributeTrue;
2933 if (equalIgnoringCase(value, "false"))
2934 return SpellcheckAttributeFalse;
2935
2936 return SpellcheckAttributeDefault;
2937}
2938
2939bool Element::isSpellCheckingEnabled() const
2940{
2941 for (const Element* element = this; element; element = element->parentOrShadowHostElement()) {
2942 switch (element->spellcheckAttributeState()) {
2943 case SpellcheckAttributeTrue:
2944 return true;
2945 case SpellcheckAttributeFalse:
2946 return false;
2947 case SpellcheckAttributeDefault:
2948 break;
2949 }
2950 }
2951
2952 return true;
2953}
2954
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002955#ifndef NDEBUG
2956bool Element::fastAttributeLookupAllowed(const QualifiedName& name) const
2957{
2958 if (name == HTMLNames::styleAttr)
2959 return false;
2960
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002961 if (isSVGElement())
Torne (Richard Coles)09380292014-02-21 12:17:33 +00002962 return !toSVGElement(this)->isAnimatableAttribute(name);
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002963
2964 return true;
2965}
2966#endif
2967
2968#ifdef DUMP_NODE_STATISTICS
2969bool Element::hasNamedNodeMap() const
2970{
2971 return hasRareData() && elementRareData()->attributeMap();
2972}
2973#endif
2974
Ben Murdoch00d3faa2013-08-14 11:52:03 +01002975inline void Element::updateName(const AtomicString& oldName, const AtomicString& newName)
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002976{
Ben Murdoch00d3faa2013-08-14 11:52:03 +01002977 if (!inDocument() || isInShadowTree())
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002978 return;
2979
2980 if (oldName == newName)
2981 return;
2982
Ben Murdochdf957042013-08-06 11:01:27 +01002983 if (shouldRegisterAsNamedItem())
2984 updateNamedItemRegistration(oldName, newName);
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002985}
2986
Ben Murdoch00d3faa2013-08-14 11:52:03 +01002987inline void Element::updateId(const AtomicString& oldId, const AtomicString& newId)
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002988{
2989 if (!isInTreeScope())
2990 return;
2991
2992 if (oldId == newId)
2993 return;
2994
Ben Murdoch00d3faa2013-08-14 11:52:03 +01002995 updateId(treeScope(), oldId, newId);
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002996}
2997
Torne (Richard Coles)8abfc582013-09-12 12:10:38 +01002998inline void Element::updateId(TreeScope& scope, const AtomicString& oldId, const AtomicString& newId)
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002999{
3000 ASSERT(isInTreeScope());
3001 ASSERT(oldId != newId);
3002
3003 if (!oldId.isEmpty())
Torne (Richard Coles)8abfc582013-09-12 12:10:38 +01003004 scope.removeElementById(oldId, this);
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01003005 if (!newId.isEmpty())
Torne (Richard Coles)8abfc582013-09-12 12:10:38 +01003006 scope.addElementById(newId, this);
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01003007
Ben Murdochdf957042013-08-06 11:01:27 +01003008 if (shouldRegisterAsExtraNamedItem())
3009 updateExtraNamedItemRegistration(oldId, newId);
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01003010}
3011
Torne (Richard Coles)8abfc582013-09-12 12:10:38 +01003012void Element::updateLabel(TreeScope& scope, const AtomicString& oldForAttributeValue, const AtomicString& newForAttributeValue)
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01003013{
3014 ASSERT(hasTagName(labelTag));
3015
3016 if (!inDocument())
3017 return;
3018
3019 if (oldForAttributeValue == newForAttributeValue)
3020 return;
3021
3022 if (!oldForAttributeValue.isEmpty())
Torne (Richard Coles)8abfc582013-09-12 12:10:38 +01003023 scope.removeLabel(oldForAttributeValue, toHTMLLabelElement(this));
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01003024 if (!newForAttributeValue.isEmpty())
Torne (Richard Coles)8abfc582013-09-12 12:10:38 +01003025 scope.addLabel(newForAttributeValue, toHTMLLabelElement(this));
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01003026}
3027
Ben Murdoch7757ec22013-07-23 11:17:36 +01003028static bool hasSelectorForAttribute(Document* document, const AtomicString& localName)
3029{
Torne (Richard Coles)a854de02013-12-18 16:25:25 +00003030 return document->ensureStyleResolver().ensureRuleFeatureSet().hasSelectorForAttribute(localName);
Ben Murdoch7757ec22013-07-23 11:17:36 +01003031}
3032
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01003033void Element::willModifyAttribute(const QualifiedName& name, const AtomicString& oldValue, const AtomicString& newValue)
3034{
3035 if (isIdAttributeName(name))
3036 updateId(oldValue, newValue);
3037 else if (name == HTMLNames::nameAttr)
3038 updateName(oldValue, newValue);
3039 else if (name == HTMLNames::forAttr && hasTagName(labelTag)) {
Torne (Richard Coles)8abfc582013-09-12 12:10:38 +01003040 TreeScope& scope = treeScope();
3041 if (scope.shouldCacheLabelsByForAttribute())
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01003042 updateLabel(scope, oldValue, newValue);
3043 }
3044
3045 if (oldValue != newValue) {
Torne (Richard Coles)f79f16f2013-10-31 11:16:44 +00003046 if (inActiveDocument() && hasSelectorForAttribute(&document(), name.localName()))
Torne (Richard Coles)09380292014-02-21 12:17:33 +00003047 setNeedsStyleRecalc(SubtreeStyleChange);
Ben Murdoche69819b2013-07-17 14:56:49 +01003048
3049 if (isUpgradedCustomElement())
Ben Murdoch83750172013-07-24 10:36:59 +01003050 CustomElement::attributeDidChange(this, name.localName(), oldValue, newValue);
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01003051 }
3052
Torne (Richard Coles)f79f16f2013-10-31 11:16:44 +00003053 if (OwnPtr<MutationObserverInterestGroup> recipients = MutationObserverInterestGroup::createForAttributesMutation(*this, name))
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01003054 recipients->enqueueMutationRecord(MutationRecord::createAttributes(this, name, oldValue));
3055
Torne (Richard Coles)bfe35902013-10-22 16:41:51 +01003056 InspectorInstrumentation::willModifyDOMAttr(this, oldValue, newValue);
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01003057}
3058
3059void Element::didAddAttribute(const QualifiedName& name, const AtomicString& value)
3060{
3061 attributeChanged(name, value);
Torne (Richard Coles)bfe35902013-10-22 16:41:51 +01003062 InspectorInstrumentation::didModifyDOMAttr(this, name.localName(), value);
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01003063 dispatchSubtreeModifiedEvent();
3064}
3065
3066void Element::didModifyAttribute(const QualifiedName& name, const AtomicString& value)
3067{
3068 attributeChanged(name, value);
Torne (Richard Coles)bfe35902013-10-22 16:41:51 +01003069 InspectorInstrumentation::didModifyDOMAttr(this, name.localName(), value);
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01003070 // Do not dispatch a DOMSubtreeModified event here; see bug 81141.
3071}
3072
3073void Element::didRemoveAttribute(const QualifiedName& name)
3074{
3075 attributeChanged(name, nullAtom);
Torne (Richard Coles)bfe35902013-10-22 16:41:51 +01003076 InspectorInstrumentation::didRemoveDOMAttr(this, name.localName());
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01003077 dispatchSubtreeModifiedEvent();
3078}
3079
Torne (Richard Coles)1e202182013-10-18 15:46:42 +01003080void Element::didMoveToNewDocument(Document& oldDocument)
Ben Murdoche69819b2013-07-17 14:56:49 +01003081{
3082 Node::didMoveToNewDocument(oldDocument);
3083
3084 // If the documents differ by quirks mode then they differ by case sensitivity
3085 // for class and id names so we need to go through the attribute change logic
3086 // to pick up the new casing in the ElementData.
Torne (Richard Coles)1e202182013-10-18 15:46:42 +01003087 if (oldDocument.inQuirksMode() != document().inQuirksMode()) {
Ben Murdoche69819b2013-07-17 14:56:49 +01003088 if (hasID())
3089 setIdAttribute(getIdAttribute());
3090 if (hasClass())
3091 setAttribute(HTMLNames::classAttr, getClassAttribute());
3092 }
3093}
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01003094
Ben Murdochdf957042013-08-06 11:01:27 +01003095void Element::updateNamedItemRegistration(const AtomicString& oldName, const AtomicString& newName)
3096{
Torne (Richard Coles)8abfc582013-09-12 12:10:38 +01003097 if (!document().isHTMLDocument())
Ben Murdoch00d3faa2013-08-14 11:52:03 +01003098 return;
Ben Murdochdf957042013-08-06 11:01:27 +01003099
3100 if (!oldName.isEmpty())
Torne (Richard Coles)8abfc582013-09-12 12:10:38 +01003101 toHTMLDocument(document()).removeNamedItem(oldName);
Ben Murdochdf957042013-08-06 11:01:27 +01003102
3103 if (!newName.isEmpty())
Torne (Richard Coles)8abfc582013-09-12 12:10:38 +01003104 toHTMLDocument(document()).addNamedItem(newName);
Ben Murdochdf957042013-08-06 11:01:27 +01003105}
3106
3107void Element::updateExtraNamedItemRegistration(const AtomicString& oldId, const AtomicString& newId)
3108{
Torne (Richard Coles)8abfc582013-09-12 12:10:38 +01003109 if (!document().isHTMLDocument())
Ben Murdoch00d3faa2013-08-14 11:52:03 +01003110 return;
Ben Murdochdf957042013-08-06 11:01:27 +01003111
3112 if (!oldId.isEmpty())
Torne (Richard Coles)8abfc582013-09-12 12:10:38 +01003113 toHTMLDocument(document()).removeExtraNamedItem(oldId);
Ben Murdochdf957042013-08-06 11:01:27 +01003114
3115 if (!newId.isEmpty())
Torne (Richard Coles)8abfc582013-09-12 12:10:38 +01003116 toHTMLDocument(document()).addExtraNamedItem(newId);
Ben Murdochdf957042013-08-06 11:01:27 +01003117}
3118
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01003119PassRefPtr<HTMLCollection> Element::ensureCachedHTMLCollection(CollectionType type)
3120{
3121 if (HTMLCollection* collection = cachedHTMLCollection(type))
3122 return collection;
3123
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01003124 if (type == TableRows) {
3125 ASSERT(hasTagName(tableTag));
Torne (Richard Coles)09380292014-02-21 12:17:33 +00003126 return ensureRareData().ensureNodeLists().addCache<HTMLTableRowsCollection>(this, type);
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01003127 } else if (type == SelectOptions) {
3128 ASSERT(hasTagName(selectTag));
Torne (Richard Coles)09380292014-02-21 12:17:33 +00003129 return ensureRareData().ensureNodeLists().addCache<HTMLOptionsCollection>(this, type);
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01003130 } else if (type == FormControls) {
3131 ASSERT(hasTagName(formTag) || hasTagName(fieldsetTag));
Torne (Richard Coles)09380292014-02-21 12:17:33 +00003132 return ensureRareData().ensureNodeLists().addCache<HTMLFormControlsCollection>(this, type);
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01003133 }
Torne (Richard Coles)09380292014-02-21 12:17:33 +00003134 return ensureRareData().ensureNodeLists().addCache<HTMLCollection>(this, type);
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01003135}
3136
Ben Murdoch591b9582013-07-10 11:41:44 +01003137static void scheduleLayerUpdateCallback(Node* node)
Torne (Richard Coles)93ac45c2013-05-29 14:40:20 +01003138{
Ben Murdoche69819b2013-07-17 14:56:49 +01003139 // Notify the renderer even is the styles are identical since it may need to
3140 // create or destroy a RenderLayer.
3141 node->setNeedsStyleRecalc(LocalStyleChange, StyleChangeFromRenderer);
Torne (Richard Coles)93ac45c2013-05-29 14:40:20 +01003142}
3143
Ben Murdoch591b9582013-07-10 11:41:44 +01003144void Element::scheduleLayerUpdate()
Torne (Richard Coles)93ac45c2013-05-29 14:40:20 +01003145{
Torne (Richard Coles)8abfc582013-09-12 12:10:38 +01003146 if (document().inStyleRecalc())
3147 PostAttachCallbacks::queueCallback(scheduleLayerUpdateCallback, this);
Torne (Richard Coles)93ac45c2013-05-29 14:40:20 +01003148 else
Ben Murdoche69819b2013-07-17 14:56:49 +01003149 scheduleLayerUpdateCallback(this);
Torne (Richard Coles)93ac45c2013-05-29 14:40:20 +01003150}
3151
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01003152HTMLCollection* Element::cachedHTMLCollection(CollectionType type)
3153{
Torne (Richard Coles)09380292014-02-21 12:17:33 +00003154 return hasRareData() && rareData()->nodeLists() ? rareData()->nodeLists()->cached<HTMLCollection>(type) : 0;
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01003155}
3156
3157IntSize Element::savedLayerScrollOffset() const
3158{
3159 return hasRareData() ? elementRareData()->savedLayerScrollOffset() : IntSize();
3160}
3161
3162void Element::setSavedLayerScrollOffset(const IntSize& size)
3163{
3164 if (size.isZero() && !hasRareData())
3165 return;
Torne (Richard Coles)bfe35902013-10-22 16:41:51 +01003166 ensureElementRareData().setSavedLayerScrollOffset(size);
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01003167}
3168
3169PassRefPtr<Attr> Element::attrIfExists(const QualifiedName& name)
3170{
3171 if (AttrNodeList* attrNodeList = attrNodeListForElement(this))
Torne (Richard Coles)bfe35902013-10-22 16:41:51 +01003172 return findAttrNodeInList(*attrNodeList, name);
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01003173 return 0;
3174}
3175
3176PassRefPtr<Attr> Element::ensureAttr(const QualifiedName& name)
3177{
Torne (Richard Coles)bfe35902013-10-22 16:41:51 +01003178 AttrNodeList& attrNodeList = ensureAttrNodeListForElement(this);
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01003179 RefPtr<Attr> attrNode = findAttrNodeInList(attrNodeList, name);
3180 if (!attrNode) {
Torne (Richard Coles)8abfc582013-09-12 12:10:38 +01003181 attrNode = Attr::create(*this, name);
Torne (Richard Coles)f79f16f2013-10-31 11:16:44 +00003182 treeScope().adoptIfNeeded(*attrNode);
Torne (Richard Coles)bfe35902013-10-22 16:41:51 +01003183 attrNodeList.append(attrNode);
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01003184 }
3185 return attrNode.release();
3186}
3187
3188void Element::detachAttrNodeFromElementWithValue(Attr* attrNode, const AtomicString& value)
3189{
3190 ASSERT(hasSyntheticAttrChildNodes());
3191 attrNode->detachFromElementWithValue(value);
3192
3193 AttrNodeList* attrNodeList = attrNodeListForElement(this);
3194 for (unsigned i = 0; i < attrNodeList->size(); ++i) {
3195 if (attrNodeList->at(i)->qualifiedName() == attrNode->qualifiedName()) {
3196 attrNodeList->remove(i);
3197 if (attrNodeList->isEmpty())
3198 removeAttrNodeListForElement(this);
3199 return;
3200 }
3201 }
3202 ASSERT_NOT_REACHED();
3203}
3204
3205void Element::detachAllAttrNodesFromElement()
3206{
3207 AttrNodeList* attrNodeList = attrNodeListForElement(this);
3208 ASSERT(attrNodeList);
3209
3210 for (unsigned i = 0; i < attributeCount(); ++i) {
3211 const Attribute* attribute = attributeItem(i);
Torne (Richard Coles)bfe35902013-10-22 16:41:51 +01003212 if (RefPtr<Attr> attrNode = findAttrNodeInList(*attrNodeList, attribute->name()))
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01003213 attrNode->detachFromElementWithValue(attribute->value());
3214 }
3215
3216 removeAttrNodeListForElement(this);
3217}
3218
Torne (Richard Coles)8abfc582013-09-12 12:10:38 +01003219void Element::willRecalcStyle(StyleRecalcChange)
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01003220{
3221 ASSERT(hasCustomStyleCallbacks());
3222}
3223
Torne (Richard Coles)8abfc582013-09-12 12:10:38 +01003224void Element::didRecalcStyle(StyleRecalcChange)
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01003225{
3226 ASSERT(hasCustomStyleCallbacks());
3227}
3228
3229
3230PassRefPtr<RenderStyle> Element::customStyleForRenderer()
3231{
3232 ASSERT(hasCustomStyleCallbacks());
3233 return 0;
3234}
3235
3236void Element::cloneAttributesFromElement(const Element& other)
3237{
3238 if (hasSyntheticAttrChildNodes())
3239 detachAllAttrNodesFromElement();
3240
3241 other.synchronizeAllAttributes();
3242 if (!other.m_elementData) {
3243 m_elementData.clear();
3244 return;
3245 }
3246
3247 const AtomicString& oldID = getIdAttribute();
3248 const AtomicString& newID = other.getIdAttribute();
3249
3250 if (!oldID.isNull() || !newID.isNull())
3251 updateId(oldID, newID);
3252
3253 const AtomicString& oldName = getNameAttribute();
3254 const AtomicString& newName = other.getNameAttribute();
3255
3256 if (!oldName.isNull() || !newName.isNull())
3257 updateName(oldName, newName);
3258
Ben Murdoche69819b2013-07-17 14:56:49 +01003259 // Quirks mode makes class and id not case sensitive. We can't share the ElementData
3260 // if the idForStyleResolution and the className need different casing.
3261 bool ownerDocumentsHaveDifferentCaseSensitivity = false;
3262 if (other.hasClass() || other.hasID())
Torne (Richard Coles)8abfc582013-09-12 12:10:38 +01003263 ownerDocumentsHaveDifferentCaseSensitivity = other.document().inQuirksMode() != document().inQuirksMode();
Ben Murdoche69819b2013-07-17 14:56:49 +01003264
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01003265 // If 'other' has a mutable ElementData, convert it to an immutable one so we can share it between both elements.
Torne (Richard Coles)09380292014-02-21 12:17:33 +00003266 // We can only do this if there are no presentation attributes and sharing the data won't result in different case sensitivity of class or id.
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01003267 if (other.m_elementData->isUnique()
Ben Murdoche69819b2013-07-17 14:56:49 +01003268 && !ownerDocumentsHaveDifferentCaseSensitivity
Torne (Richard Coles)09380292014-02-21 12:17:33 +00003269 && !other.m_elementData->presentationAttributeStyle())
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01003270 const_cast<Element&>(other).m_elementData = static_cast<const UniqueElementData*>(other.m_elementData.get())->makeShareableCopy();
3271
Ben Murdoche69819b2013-07-17 14:56:49 +01003272 if (!other.m_elementData->isUnique() && !ownerDocumentsHaveDifferentCaseSensitivity)
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01003273 m_elementData = other.m_elementData;
3274 else
3275 m_elementData = other.m_elementData->makeUniqueCopy();
3276
3277 for (unsigned i = 0; i < m_elementData->length(); ++i) {
3278 const Attribute* attribute = const_cast<const ElementData*>(m_elementData.get())->attributeItem(i);
3279 attributeChangedFromParserOrByCloning(attribute->name(), attribute->value(), ModifiedByCloning);
3280 }
3281}
3282
3283void Element::cloneDataFromElement(const Element& other)
3284{
3285 cloneAttributesFromElement(other);
3286 copyNonAttributePropertiesFromElement(other);
3287}
3288
3289void Element::createUniqueElementData()
3290{
3291 if (!m_elementData)
3292 m_elementData = UniqueElementData::create();
3293 else {
3294 ASSERT(!m_elementData->isUnique());
3295 m_elementData = static_cast<ShareableElementData*>(m_elementData.get())->makeUniqueCopy();
3296 }
3297}
3298
Ben Murdoch1fad5ca2013-08-07 11:05:11 +01003299InputMethodContext* Element::inputMethodContext()
Torne (Richard Coles)81a51572013-05-13 16:52:28 +01003300{
Torne (Richard Coles)bfe35902013-10-22 16:41:51 +01003301 return ensureElementRareData().ensureInputMethodContext(toHTMLElement(this));
Torne (Richard Coles)81a51572013-05-13 16:52:28 +01003302}
3303
Torne (Richard Coles)19cde672013-11-06 12:28:04 +00003304bool Element::hasInputMethodContext() const
3305{
3306 return hasRareData() && elementRareData()->hasInputMethodContext();
3307}
3308
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01003309bool Element::hasPendingResources() const
3310{
3311 return hasRareData() && elementRareData()->hasPendingResources();
3312}
3313
3314void Element::setHasPendingResources()
3315{
Torne (Richard Coles)bfe35902013-10-22 16:41:51 +01003316 ensureElementRareData().setHasPendingResources(true);
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01003317}
3318
3319void Element::clearHasPendingResources()
3320{
Torne (Richard Coles)bfe35902013-10-22 16:41:51 +01003321 ensureElementRareData().setHasPendingResources(false);
Ben Murdoch591b9582013-07-10 11:41:44 +01003322}
3323
3324void Element::synchronizeStyleAttributeInternal() const
3325{
3326 ASSERT(isStyledElement());
3327 ASSERT(elementData());
3328 ASSERT(elementData()->m_styleAttributeIsDirty);
3329 elementData()->m_styleAttributeIsDirty = false;
Torne (Richard Coles)09380292014-02-21 12:17:33 +00003330 const StylePropertySet* inlineStyle = this->inlineStyle();
3331 const_cast<Element*>(this)->setSynchronizedLazyAttribute(styleAttr,
3332 inlineStyle ? AtomicString(inlineStyle->asText()) : nullAtom);
Ben Murdoch591b9582013-07-10 11:41:44 +01003333}
3334
3335CSSStyleDeclaration* Element::style()
3336{
3337 if (!isStyledElement())
3338 return 0;
Torne (Richard Coles)09380292014-02-21 12:17:33 +00003339 return ensureElementRareData().ensureInlineCSSStyleDeclaration(this);
Ben Murdoch591b9582013-07-10 11:41:44 +01003340}
3341
3342MutableStylePropertySet* Element::ensureMutableInlineStyle()
3343{
3344 ASSERT(isStyledElement());
3345 RefPtr<StylePropertySet>& inlineStyle = ensureUniqueElementData()->m_inlineStyle;
Torne (Richard Coles)f79f16f2013-10-31 11:16:44 +00003346 if (!inlineStyle) {
3347 CSSParserMode mode = (!isHTMLElement() || document().inQuirksMode()) ? HTMLQuirksMode : HTMLStandardMode;
3348 inlineStyle = MutableStylePropertySet::create(mode);
Torne (Richard Coles)51b29062013-11-28 11:56:03 +00003349 } else if (!inlineStyle->isMutable()) {
Ben Murdoch591b9582013-07-10 11:41:44 +01003350 inlineStyle = inlineStyle->mutableCopy();
Torne (Richard Coles)51b29062013-11-28 11:56:03 +00003351 }
3352 return toMutableStylePropertySet(inlineStyle);
Ben Murdoch591b9582013-07-10 11:41:44 +01003353}
3354
Torne (Richard Coles)09380292014-02-21 12:17:33 +00003355void Element::clearMutableInlineStyleIfEmpty()
Ben Murdoch591b9582013-07-10 11:41:44 +01003356{
Torne (Richard Coles)09380292014-02-21 12:17:33 +00003357 if (ensureMutableInlineStyle()->isEmpty()) {
3358 ensureUniqueElementData()->m_inlineStyle.clear();
3359 }
Ben Murdoch591b9582013-07-10 11:41:44 +01003360}
3361
3362inline void Element::setInlineStyleFromString(const AtomicString& newStyleString)
3363{
3364 ASSERT(isStyledElement());
3365 RefPtr<StylePropertySet>& inlineStyle = elementData()->m_inlineStyle;
3366
3367 // Avoid redundant work if we're using shared attribute data with already parsed inline style.
3368 if (inlineStyle && !elementData()->isUnique())
3369 return;
3370
3371 // We reconstruct the property set instead of mutating if there is no CSSOM wrapper.
3372 // This makes wrapperless property sets immutable and so cacheable.
3373 if (inlineStyle && !inlineStyle->isMutable())
3374 inlineStyle.clear();
3375
3376 if (!inlineStyle) {
Torne (Richard Coles)09380292014-02-21 12:17:33 +00003377 inlineStyle = BisonCSSParser::parseInlineStyleDeclaration(newStyleString, this);
Ben Murdoch591b9582013-07-10 11:41:44 +01003378 } else {
3379 ASSERT(inlineStyle->isMutable());
Torne (Richard Coles)8abfc582013-09-12 12:10:38 +01003380 static_pointer_cast<MutableStylePropertySet>(inlineStyle)->parseDeclaration(newStyleString, document().elementSheet()->contents());
Ben Murdoch591b9582013-07-10 11:41:44 +01003381 }
3382}
3383
3384void Element::styleAttributeChanged(const AtomicString& newStyleString, AttributeModificationReason modificationReason)
3385{
3386 ASSERT(isStyledElement());
3387 WTF::OrdinalNumber startLineNumber = WTF::OrdinalNumber::beforeFirst();
Torne (Richard Coles)8abfc582013-09-12 12:10:38 +01003388 if (document().scriptableDocumentParser() && !document().isInDocumentWrite())
3389 startLineNumber = document().scriptableDocumentParser()->lineNumber();
Ben Murdoch591b9582013-07-10 11:41:44 +01003390
3391 if (newStyleString.isNull()) {
Ben Murdoch591b9582013-07-10 11:41:44 +01003392 ensureUniqueElementData()->m_inlineStyle.clear();
Torne (Richard Coles)8abfc582013-09-12 12:10:38 +01003393 } else if (modificationReason == ModifiedByCloning || document().contentSecurityPolicy()->allowInlineStyle(document().url(), startLineNumber)) {
Ben Murdoch591b9582013-07-10 11:41:44 +01003394 setInlineStyleFromString(newStyleString);
3395 }
3396
3397 elementData()->m_styleAttributeIsDirty = false;
3398
Ben Murdoche69819b2013-07-17 14:56:49 +01003399 setNeedsStyleRecalc(LocalStyleChange);
Torne (Richard Coles)bfe35902013-10-22 16:41:51 +01003400 InspectorInstrumentation::didInvalidateStyleAttr(this);
Ben Murdoch591b9582013-07-10 11:41:44 +01003401}
3402
3403void Element::inlineStyleChanged()
3404{
3405 ASSERT(isStyledElement());
Ben Murdoche69819b2013-07-17 14:56:49 +01003406 setNeedsStyleRecalc(LocalStyleChange);
Ben Murdoch591b9582013-07-10 11:41:44 +01003407 ASSERT(elementData());
3408 elementData()->m_styleAttributeIsDirty = true;
Torne (Richard Coles)bfe35902013-10-22 16:41:51 +01003409 InspectorInstrumentation::didInvalidateStyleAttr(this);
Ben Murdoch591b9582013-07-10 11:41:44 +01003410}
3411
3412bool Element::setInlineStyleProperty(CSSPropertyID propertyID, CSSValueID identifier, bool important)
3413{
3414 ASSERT(isStyledElement());
3415 ensureMutableInlineStyle()->setProperty(propertyID, cssValuePool().createIdentifierValue(identifier), important);
3416 inlineStyleChanged();
3417 return true;
3418}
3419
3420bool Element::setInlineStyleProperty(CSSPropertyID propertyID, CSSPropertyID identifier, bool important)
3421{
3422 ASSERT(isStyledElement());
3423 ensureMutableInlineStyle()->setProperty(propertyID, cssValuePool().createIdentifierValue(identifier), important);
3424 inlineStyleChanged();
3425 return true;
3426}
3427
3428bool Element::setInlineStyleProperty(CSSPropertyID propertyID, double value, CSSPrimitiveValue::UnitTypes unit, bool important)
3429{
3430 ASSERT(isStyledElement());
3431 ensureMutableInlineStyle()->setProperty(propertyID, cssValuePool().createValue(value, unit), important);
3432 inlineStyleChanged();
3433 return true;
3434}
3435
3436bool Element::setInlineStyleProperty(CSSPropertyID propertyID, const String& value, bool important)
3437{
3438 ASSERT(isStyledElement());
Torne (Richard Coles)8abfc582013-09-12 12:10:38 +01003439 bool changes = ensureMutableInlineStyle()->setProperty(propertyID, value, important, document().elementSheet()->contents());
Ben Murdoch591b9582013-07-10 11:41:44 +01003440 if (changes)
3441 inlineStyleChanged();
3442 return changes;
3443}
3444
3445bool Element::removeInlineStyleProperty(CSSPropertyID propertyID)
3446{
3447 ASSERT(isStyledElement());
3448 if (!inlineStyle())
3449 return false;
3450 bool changes = ensureMutableInlineStyle()->removeProperty(propertyID);
3451 if (changes)
3452 inlineStyleChanged();
3453 return changes;
3454}
3455
3456void Element::removeAllInlineStyleProperties()
3457{
3458 ASSERT(isStyledElement());
Torne (Richard Coles)09380292014-02-21 12:17:33 +00003459 if (!inlineStyle())
Ben Murdoch591b9582013-07-10 11:41:44 +01003460 return;
3461 ensureMutableInlineStyle()->clear();
3462 inlineStyleChanged();
3463}
3464
Torne (Richard Coles)bfe35902013-10-22 16:41:51 +01003465void Element::updatePresentationAttributeStyle()
Ben Murdoch591b9582013-07-10 11:41:44 +01003466{
Ben Murdoch591b9582013-07-10 11:41:44 +01003467 // ShareableElementData doesn't store presentation attribute style, so make sure we have a UniqueElementData.
3468 UniqueElementData* elementData = ensureUniqueElementData();
Ben Murdoch591b9582013-07-10 11:41:44 +01003469 elementData->m_presentationAttributeStyleIsDirty = false;
Torne (Richard Coles)bfe35902013-10-22 16:41:51 +01003470 elementData->m_presentationAttributeStyle = computePresentationAttributeStyle(*this);
Ben Murdoch591b9582013-07-10 11:41:44 +01003471}
3472
3473void Element::addPropertyToPresentationAttributeStyle(MutableStylePropertySet* style, CSSPropertyID propertyID, CSSValueID identifier)
3474{
3475 ASSERT(isStyledElement());
3476 style->setProperty(propertyID, cssValuePool().createIdentifierValue(identifier));
3477}
3478
3479void Element::addPropertyToPresentationAttributeStyle(MutableStylePropertySet* style, CSSPropertyID propertyID, double value, CSSPrimitiveValue::UnitTypes unit)
3480{
3481 ASSERT(isStyledElement());
3482 style->setProperty(propertyID, cssValuePool().createValue(value, unit));
3483}
3484
3485void Element::addPropertyToPresentationAttributeStyle(MutableStylePropertySet* style, CSSPropertyID propertyID, const String& value)
3486{
3487 ASSERT(isStyledElement());
Torne (Richard Coles)1e202182013-10-18 15:46:42 +01003488 style->setProperty(propertyID, value, false);
Ben Murdoch591b9582013-07-10 11:41:44 +01003489}
3490
Torne (Richard Coles)bfe35902013-10-22 16:41:51 +01003491bool Element::supportsStyleSharing() const
3492{
Torne (Richard Coles)09380292014-02-21 12:17:33 +00003493 if (!isStyledElement() || !parentOrShadowHostElement())
Torne (Richard Coles)bfe35902013-10-22 16:41:51 +01003494 return false;
3495 // If the element has inline style it is probably unique.
3496 if (inlineStyle())
3497 return false;
3498 if (isSVGElement() && toSVGElement(this)->animatedSMILStyleProperties())
3499 return false;
3500 // Ids stop style sharing if they show up in the stylesheets.
Torne (Richard Coles)a854de02013-12-18 16:25:25 +00003501 if (hasID() && document().ensureStyleResolver().hasRulesForId(idForStyleResolution()))
Torne (Richard Coles)bfe35902013-10-22 16:41:51 +01003502 return false;
3503 // Active and hovered elements always make a chain towards the document node
3504 // and no siblings or cousins will have the same state.
3505 if (hovered())
3506 return false;
3507 if (active())
3508 return false;
3509 if (focused())
3510 return false;
Torne (Richard Coles)09380292014-02-21 12:17:33 +00003511 if (!parentOrShadowHostElement()->childrenSupportStyleSharing())
Torne (Richard Coles)bfe35902013-10-22 16:41:51 +01003512 return false;
3513 if (hasScopedHTMLStyleChild())
3514 return false;
3515 if (this == document().cssTarget())
3516 return false;
3517 if (isHTMLElement() && toHTMLElement(this)->hasDirectionAuto())
3518 return false;
3519 if (hasActiveAnimations())
3520 return false;
Torne (Richard Coles)bfe35902013-10-22 16:41:51 +01003521 // Turn off style sharing for elements that can gain layers for reasons outside of the style system.
3522 // See comments in RenderObject::setStyle().
3523 // FIXME: Why does gaining a layer from outside the style system require disabling sharing?
3524 if (hasTagName(iframeTag)
3525 || hasTagName(frameTag)
3526 || hasTagName(embedTag)
3527 || hasTagName(objectTag)
3528 || hasTagName(appletTag)
3529 || hasTagName(canvasTag))
3530 return false;
3531 // FIXME: We should share style for option and optgroup whenever possible.
3532 // Before doing so, we need to resolve issues in HTMLSelectElement::recalcListItems
3533 // and RenderMenuList::setText. See also https://bugs.webkit.org/show_bug.cgi?id=88405
3534 if (hasTagName(optionTag) || hasTagName(optgroupTag))
3535 return false;
3536 if (FullscreenElementStack::isActiveFullScreenElement(this))
3537 return false;
3538 return true;
3539}
3540
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01003541} // namespace WebCore