blob: 1c0ca09910247206a7fc9f91065c1d604bb83024 [file] [log] [blame]
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001/*
2 * Copyright (C) 1999 Lars Knoll (knoll@kde.org)
3 * (C) 1999 Antti Koivisto (koivisto@kde.org)
4 * (C) 2001 Peter Kelly (pmk@post.com)
5 * (C) 2001 Dirk Mueller (mueller@kde.org)
6 * (C) 2007 David Smith (catfish.man@gmail.com)
7 * Copyright (C) 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2012, 2013 Apple Inc. All rights reserved.
8 * (C) 2007 Eric Seidel (eric@webkit.org)
9 *
10 * This library is free software; you can redistribute it and/or
11 * modify it under the terms of the GNU Library General Public
12 * License as published by the Free Software Foundation; either
13 * version 2 of the License, or (at your option) any later version.
14 *
15 * This library is distributed in the hope that it will be useful,
16 * but WITHOUT ANY WARRANTY; without even the implied warranty of
17 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
18 * Library General Public License for more details.
19 *
20 * You should have received a copy of the GNU Library General Public License
21 * along with this library; see the file COPYING.LIB. If not, write to
22 * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
23 * Boston, MA 02110-1301, USA.
24 */
25
26#include "config.h"
27#include "core/dom/Element.h"
28
Ben Murdoch591b9582013-07-10 11:41:44 +010029#include "CSSPropertyNames.h"
30#include "CSSValueKeywords.h"
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +010031#include "HTMLNames.h"
Ben Murdoch7757ec22013-07-23 11:17:36 +010032#include "RuntimeEnabledFeatures.h"
Torne (Richard Coles)93ac45c2013-05-29 14:40:20 +010033#include "SVGNames.h"
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +010034#include "XMLNames.h"
Ben Murdochdf957042013-08-06 11:01:27 +010035#include "bindings/v8/ExceptionState.h"
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +010036#include "core/accessibility/AXObjectCache.h"
Ben Murdoch83750172013-07-24 10:36:59 +010037#include "core/animation/DocumentTimeline.h"
Ben Murdoch591b9582013-07-10 11:41:44 +010038#include "core/css/CSSParser.h"
39#include "core/css/CSSStyleSheet.h"
40#include "core/css/CSSValuePool.h"
41#include "core/css/PropertySetCSSStyleDeclaration.h"
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +010042#include "core/css/StylePropertySet.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"
Ben Murdoch591b9582013-07-10 11:41:44 +010045#include "core/dom/Attribute.h"
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +010046#include "core/dom/ClientRect.h"
47#include "core/dom/ClientRectList.h"
Ben Murdoch83750172013-07-24 10:36:59 +010048#include "core/dom/CustomElement.h"
Ben Murdoche69819b2013-07-17 14:56:49 +010049#include "core/dom/CustomElementRegistrationContext.h"
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +010050#include "core/dom/DatasetDOMStringMap.h"
51#include "core/dom/Document.h"
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +010052#include "core/dom/DocumentSharedObjectPool.h"
53#include "core/dom/ElementRareData.h"
Ben Murdoch02772c62013-07-26 10:21:05 +010054#include "core/dom/EventDispatcher.h"
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +010055#include "core/dom/ExceptionCode.h"
Ben Murdoch02772c62013-07-26 10:21:05 +010056#include "core/dom/FocusEvent.h"
Torne (Richard Coles)f5e4ad52013-08-05 13:57:57 +010057#include "core/dom/FullscreenElementStack.h"
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +010058#include "core/dom/MutationObserverInterestGroup.h"
59#include "core/dom/MutationRecord.h"
60#include "core/dom/NamedNodeMap.h"
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +010061#include "core/dom/NodeRenderStyle.h"
62#include "core/dom/NodeRenderingContext.h"
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +010063#include "core/dom/PseudoElement.h"
Ben Murdoch591b9582013-07-10 11:41:44 +010064#include "core/dom/ScriptableDocumentParser.h"
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +010065#include "core/dom/SelectorQuery.h"
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +010066#include "core/dom/Text.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"
72#include "core/html/ClassList.h"
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +010073#include "core/html/HTMLCollection.h"
74#include "core/html/HTMLDocument.h"
75#include "core/html/HTMLElement.h"
76#include "core/html/HTMLFormControlsCollection.h"
77#include "core/html/HTMLFrameOwnerElement.h"
78#include "core/html/HTMLLabelElement.h"
79#include "core/html/HTMLOptionsCollection.h"
80#include "core/html/HTMLTableRowsCollection.h"
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +010081#include "core/html/parser/HTMLParserIdioms.h"
Ben Murdoch591b9582013-07-10 11:41:44 +010082#include "core/page/ContentSecurityPolicy.h"
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +010083#include "core/page/FocusController.h"
84#include "core/page/Frame.h"
85#include "core/page/FrameView.h"
86#include "core/page/Page.h"
87#include "core/page/PointerLockController.h"
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +010088#include "core/rendering/FlowThreadController.h"
89#include "core/rendering/RenderRegion.h"
90#include "core/rendering/RenderView.h"
91#include "core/rendering/RenderWidget.h"
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +010092#include "core/svg/SVGDocumentExtensions.h"
93#include "core/svg/SVGElement.h"
Torne (Richard Coles)93ac45c2013-05-29 14:40:20 +010094#include "wtf/BitVector.h"
Ben Murdoch591b9582013-07-10 11:41:44 +010095#include "wtf/HashFunctions.h"
Torne (Richard Coles)93ac45c2013-05-29 14:40:20 +010096#include "wtf/text/CString.h"
Ben Murdoch591b9582013-07-10 11:41:44 +010097#include "wtf/text/TextPosition.h"
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +010098
99namespace WebCore {
100
101using namespace HTMLNames;
102using namespace XMLNames;
103
104static inline bool shouldIgnoreAttributeCase(const Element* e)
105{
106 return e && e->document()->isHTMLDocument() && e->isHTMLElement();
107}
Ben Murdoch591b9582013-07-10 11:41:44 +0100108
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100109class StyleResolverParentPusher {
110public:
111 StyleResolverParentPusher(Element* parent)
112 : m_parent(parent)
113 , m_pushedStyleResolver(0)
114 {
115 }
116 void push()
117 {
118 if (m_pushedStyleResolver)
119 return;
120 m_pushedStyleResolver = m_parent->document()->styleResolver();
121 m_pushedStyleResolver->pushParentElement(m_parent);
122 }
123 ~StyleResolverParentPusher()
124 {
125
126 if (!m_pushedStyleResolver)
127 return;
128
129 // This tells us that our pushed style selector is in a bad state,
130 // so we should just bail out in that scenario.
131 ASSERT(m_pushedStyleResolver == m_parent->document()->styleResolver());
132 if (m_pushedStyleResolver != m_parent->document()->styleResolver())
133 return;
134
135 m_pushedStyleResolver->popParentElement(m_parent);
136 }
137
138private:
139 Element* m_parent;
140 StyleResolver* m_pushedStyleResolver;
141};
142
143typedef Vector<RefPtr<Attr> > AttrNodeList;
144typedef HashMap<Element*, OwnPtr<AttrNodeList> > AttrNodeListMap;
145
146static AttrNodeListMap& attrNodeListMap()
147{
148 DEFINE_STATIC_LOCAL(AttrNodeListMap, map, ());
149 return map;
150}
151
152static AttrNodeList* attrNodeListForElement(Element* element)
153{
154 if (!element->hasSyntheticAttrChildNodes())
155 return 0;
156 ASSERT(attrNodeListMap().contains(element));
157 return attrNodeListMap().get(element);
158}
159
160static AttrNodeList* ensureAttrNodeListForElement(Element* element)
161{
162 if (element->hasSyntheticAttrChildNodes()) {
163 ASSERT(attrNodeListMap().contains(element));
164 return attrNodeListMap().get(element);
165 }
166 ASSERT(!attrNodeListMap().contains(element));
167 element->setHasSyntheticAttrChildNodes(true);
168 AttrNodeListMap::AddResult result = attrNodeListMap().add(element, adoptPtr(new AttrNodeList));
169 return result.iterator->value.get();
170}
171
172static void removeAttrNodeListForElement(Element* element)
173{
174 ASSERT(element->hasSyntheticAttrChildNodes());
175 ASSERT(attrNodeListMap().contains(element));
176 attrNodeListMap().remove(element);
177 element->setHasSyntheticAttrChildNodes(false);
178}
179
180static Attr* findAttrNodeInList(AttrNodeList* attrNodeList, const QualifiedName& name)
181{
182 for (unsigned i = 0; i < attrNodeList->size(); ++i) {
183 if (attrNodeList->at(i)->qualifiedName() == name)
184 return attrNodeList->at(i).get();
185 }
186 return 0;
187}
188
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100189PassRefPtr<Element> Element::create(const QualifiedName& tagName, Document* document)
190{
191 return adoptRef(new Element(tagName, document, CreateElement));
192}
193
194Element::~Element()
195{
196#ifndef NDEBUG
197 if (document() && document()->renderer()) {
198 // When the document is not destroyed, an element that was part of a named flow
199 // content nodes should have been removed from the content nodes collection
200 // and the inNamedFlow flag reset.
201 ASSERT(!inNamedFlow());
202 }
203#endif
204
Ben Murdoch591b9582013-07-10 11:41:44 +0100205 if (PropertySetCSSStyleDeclaration* cssomWrapper = inlineStyleCSSOMWrapper())
206 cssomWrapper->clearParentElement();
207
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100208 if (hasRareData()) {
209 ElementRareData* data = elementRareData();
210 data->setPseudoElement(BEFORE, 0);
211 data->setPseudoElement(AFTER, 0);
Ben Murdoche69819b2013-07-17 14:56:49 +0100212 data->setPseudoElement(BACKDROP, 0);
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100213 data->clearShadow();
Torne (Richard Coles)f5e4ad52013-08-05 13:57:57 +0100214
215 if (RuntimeEnabledFeatures::webAnimationsCSSEnabled()) {
216 if (ActiveAnimations* activeAnimations = data->activeAnimations())
217 activeAnimations->cssAnimations()->cancel();
218 }
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100219 }
220
Ben Murdoch83750172013-07-24 10:36:59 +0100221 if (isCustomElement())
222 CustomElement::wasDestroyed(this);
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100223
224 if (hasSyntheticAttrChildNodes())
225 detachAllAttrNodesFromElement();
226
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100227 if (hasPendingResources()) {
228 document()->accessSVGExtensions()->removeElementFromPendingResources(this);
229 ASSERT(!hasPendingResources());
230 }
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100231}
232
233inline ElementRareData* Element::elementRareData() const
234{
235 ASSERT(hasRareData());
236 return static_cast<ElementRareData*>(rareData());
237}
238
239inline ElementRareData* Element::ensureElementRareData()
240{
241 return static_cast<ElementRareData*>(ensureRareData());
242}
243
244void Element::clearTabIndexExplicitlyIfNeeded()
245{
246 if (hasRareData())
247 elementRareData()->clearTabIndexExplicitly();
248}
249
250void Element::setTabIndexExplicitly(short tabIndex)
251{
252 ensureElementRareData()->setTabIndexExplicitly(tabIndex);
253}
254
255bool Element::supportsFocus() const
256{
257 return hasRareData() && elementRareData()->tabIndexSetExplicitly();
258}
259
260short Element::tabIndex() const
261{
262 return hasRareData() ? elementRareData()->tabIndex() : 0;
263}
264
Torne (Richard Coles)521d96e2013-06-19 11:58:24 +0100265bool Element::rendererIsFocusable() const
266{
267 // Elements in canvas fallback content are not rendered, but they are allowed to be
268 // focusable as long as their canvas is displayed and visible.
269 if (isInCanvasSubtree()) {
270 const Element* e = this;
271 while (e && !e->hasLocalName(canvasTag))
272 e = e->parentElement();
273 ASSERT(e);
274 return e->renderer() && e->renderer()->style()->visibility() == VISIBLE;
275 }
276
277 // FIXME: These asserts should be in Node::isFocusable, but there are some
Ben Murdoche69819b2013-07-17 14:56:49 +0100278 // callsites like Document::setFocusedElement that would currently fail on
Torne (Richard Coles)521d96e2013-06-19 11:58:24 +0100279 // them. See crbug.com/251163
280 if (renderer()) {
281 ASSERT(!renderer()->needsLayout());
282 } else {
283 // We can't just use needsStyleRecalc() because if the node is in a
284 // display:none tree it might say it needs style recalc but the whole
285 // document is actually up to date.
286 ASSERT(!document()->childNeedsStyleRecalc());
287 }
288
289 // FIXME: Even if we are not visible, we might have a child that is visible.
290 // Hyatt wants to fix that some day with a "has visible content" flag or the like.
291 if (!renderer() || renderer()->style()->visibility() != VISIBLE)
292 return false;
293
294 return true;
295}
296
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100297DEFINE_VIRTUAL_ATTRIBUTE_EVENT_LISTENER(Element, blur);
298DEFINE_VIRTUAL_ATTRIBUTE_EVENT_LISTENER(Element, error);
299DEFINE_VIRTUAL_ATTRIBUTE_EVENT_LISTENER(Element, focus);
300DEFINE_VIRTUAL_ATTRIBUTE_EVENT_LISTENER(Element, load);
301
302PassRefPtr<Node> Element::cloneNode(bool deep)
303{
304 return deep ? cloneElementWithChildren() : cloneElementWithoutChildren();
305}
306
307PassRefPtr<Element> Element::cloneElementWithChildren()
308{
309 RefPtr<Element> clone = cloneElementWithoutChildren();
310 cloneChildNodes(clone.get());
311 return clone.release();
312}
313
314PassRefPtr<Element> Element::cloneElementWithoutChildren()
315{
316 RefPtr<Element> clone = cloneElementWithoutAttributesAndChildren();
317 // This will catch HTML elements in the wrong namespace that are not correctly copied.
318 // This is a sanity check as HTML overloads some of the DOM methods.
319 ASSERT(isHTMLElement() == clone->isHTMLElement());
320
321 clone->cloneDataFromElement(*this);
322 return clone.release();
323}
324
325PassRefPtr<Element> Element::cloneElementWithoutAttributesAndChildren()
326{
327 return document()->createElement(tagQName(), false);
328}
329
330PassRefPtr<Attr> Element::detachAttribute(size_t index)
331{
332 ASSERT(elementData());
Torne (Richard Coles)e5249552013-05-15 11:35:13 +0100333 const Attribute* attribute = elementData()->attributeItem(index);
334 RefPtr<Attr> attrNode = attrIfExists(attribute->name());
335 if (attrNode)
336 detachAttrNodeAtIndex(attrNode.get(), index);
337 else {
338 attrNode = Attr::create(document(), attribute->name(), attribute->value());
339 removeAttributeInternal(index, NotInSynchronizationOfLazyAttribute);
340 }
341 return attrNode.release();
342}
343
344void Element::detachAttrNodeAtIndex(Attr* attr, size_t index)
345{
346 ASSERT(attr);
347 ASSERT(elementData());
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100348
349 const Attribute* attribute = elementData()->attributeItem(index);
350 ASSERT(attribute);
Torne (Richard Coles)e5249552013-05-15 11:35:13 +0100351 ASSERT(attribute->name() == attr->qualifiedName());
352 detachAttrNodeFromElementWithValue(attr, attribute->value());
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100353 removeAttributeInternal(index, NotInSynchronizationOfLazyAttribute);
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100354}
355
356void Element::removeAttribute(const QualifiedName& name)
357{
358 if (!elementData())
359 return;
360
361 size_t index = elementData()->getAttributeItemIndex(name);
362 if (index == notFound)
363 return;
364
365 removeAttributeInternal(index, NotInSynchronizationOfLazyAttribute);
366}
367
368void Element::setBooleanAttribute(const QualifiedName& name, bool value)
369{
370 if (value)
371 setAttribute(name, emptyAtom);
372 else
373 removeAttribute(name);
374}
375
376NamedNodeMap* Element::attributes() const
377{
378 ElementRareData* rareData = const_cast<Element*>(this)->ensureElementRareData();
379 if (NamedNodeMap* attributeMap = rareData->attributeMap())
380 return attributeMap;
381
382 rareData->setAttributeMap(NamedNodeMap::create(const_cast<Element*>(this)));
383 return rareData->attributeMap();
384}
385
Ben Murdoch83750172013-07-24 10:36:59 +0100386ActiveAnimations* Element::activeAnimations() const
Torne (Richard Coles)81a51572013-05-13 16:52:28 +0100387{
Ben Murdoch83750172013-07-24 10:36:59 +0100388 if (hasActiveAnimations())
389 return elementRareData()->activeAnimations();
390 return 0;
Torne (Richard Coles)81a51572013-05-13 16:52:28 +0100391}
392
Ben Murdoch83750172013-07-24 10:36:59 +0100393ActiveAnimations* Element::ensureActiveAnimations()
Torne (Richard Coles)81a51572013-05-13 16:52:28 +0100394{
Ben Murdoch83750172013-07-24 10:36:59 +0100395 ElementRareData* rareData = ensureElementRareData();
396 if (!elementRareData()->activeAnimations())
397 rareData->setActiveAnimations(adoptPtr(new ActiveAnimations()));
398 return rareData->activeAnimations();
Torne (Richard Coles)81a51572013-05-13 16:52:28 +0100399}
400
401bool Element::hasActiveAnimations() const
402{
Ben Murdoch83750172013-07-24 10:36:59 +0100403 if (!RuntimeEnabledFeatures::webAnimationsEnabled())
404 return false;
Torne (Richard Coles)81a51572013-05-13 16:52:28 +0100405
Ben Murdoch83750172013-07-24 10:36:59 +0100406 if (!hasRareData())
407 return false;
408
409 ActiveAnimations* activeAnimations = elementRareData()->activeAnimations();
410 return activeAnimations && !activeAnimations->isEmpty();
Torne (Richard Coles)81a51572013-05-13 16:52:28 +0100411}
412
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100413Node::NodeType Element::nodeType() const
414{
415 return ELEMENT_NODE;
416}
417
418bool Element::hasAttribute(const QualifiedName& name) const
419{
420 return hasAttributeNS(name.namespaceURI(), name.localName());
421}
422
423void Element::synchronizeAllAttributes() const
424{
425 if (!elementData())
426 return;
427 if (elementData()->m_styleAttributeIsDirty) {
428 ASSERT(isStyledElement());
Ben Murdoch591b9582013-07-10 11:41:44 +0100429 synchronizeStyleAttributeInternal();
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100430 }
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100431 if (elementData()->m_animatedSVGAttributesAreDirty) {
432 ASSERT(isSVGElement());
433 toSVGElement(this)->synchronizeAnimatedSVGAttribute(anyQName());
434 }
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100435}
436
437inline void Element::synchronizeAttribute(const QualifiedName& name) const
438{
439 if (!elementData())
440 return;
441 if (UNLIKELY(name == styleAttr && elementData()->m_styleAttributeIsDirty)) {
442 ASSERT(isStyledElement());
Ben Murdoch591b9582013-07-10 11:41:44 +0100443 synchronizeStyleAttributeInternal();
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100444 return;
445 }
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100446 if (UNLIKELY(elementData()->m_animatedSVGAttributesAreDirty)) {
447 ASSERT(isSVGElement());
448 toSVGElement(this)->synchronizeAnimatedSVGAttribute(name);
449 }
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100450}
451
452inline void Element::synchronizeAttribute(const AtomicString& localName) const
453{
454 // This version of synchronizeAttribute() is streamlined for the case where you don't have a full QualifiedName,
455 // e.g when called from DOM API.
456 if (!elementData())
457 return;
458 if (elementData()->m_styleAttributeIsDirty && equalPossiblyIgnoringCase(localName, styleAttr.localName(), shouldIgnoreAttributeCase(this))) {
459 ASSERT(isStyledElement());
Ben Murdoch591b9582013-07-10 11:41:44 +0100460 synchronizeStyleAttributeInternal();
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100461 return;
462 }
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100463 if (elementData()->m_animatedSVGAttributesAreDirty) {
464 // We're not passing a namespace argument on purpose. SVGNames::*Attr are defined w/o namespaces as well.
465 ASSERT(isSVGElement());
466 static_cast<const SVGElement*>(this)->synchronizeAnimatedSVGAttribute(QualifiedName(nullAtom, localName, nullAtom));
467 }
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100468}
469
470const AtomicString& Element::getAttribute(const QualifiedName& name) const
471{
472 if (!elementData())
473 return nullAtom;
474 synchronizeAttribute(name);
475 if (const Attribute* attribute = getAttributeItem(name))
476 return attribute->value();
477 return nullAtom;
478}
479
Ben Murdoch591b9582013-07-10 11:41:44 +0100480void Element::scrollIntoView(bool alignToTop)
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100481{
482 document()->updateLayoutIgnorePendingStylesheets();
483
484 if (!renderer())
485 return;
486
487 LayoutRect bounds = boundingBox();
488 // Align to the top / bottom and to the closest edge.
489 if (alignToTop)
490 renderer()->scrollRectToVisible(bounds, ScrollAlignment::alignToEdgeIfNeeded, ScrollAlignment::alignTopAlways);
491 else
492 renderer()->scrollRectToVisible(bounds, ScrollAlignment::alignToEdgeIfNeeded, ScrollAlignment::alignBottomAlways);
493}
494
495void Element::scrollIntoViewIfNeeded(bool centerIfNeeded)
496{
497 document()->updateLayoutIgnorePendingStylesheets();
498
499 if (!renderer())
500 return;
501
502 LayoutRect bounds = boundingBox();
503 if (centerIfNeeded)
504 renderer()->scrollRectToVisible(bounds, ScrollAlignment::alignCenterIfNeeded, ScrollAlignment::alignCenterIfNeeded);
505 else
506 renderer()->scrollRectToVisible(bounds, ScrollAlignment::alignToEdgeIfNeeded, ScrollAlignment::alignToEdgeIfNeeded);
507}
508
509void Element::scrollByUnits(int units, ScrollGranularity granularity)
510{
511 document()->updateLayoutIgnorePendingStylesheets();
512
513 if (!renderer())
514 return;
515
516 if (!renderer()->hasOverflowClip())
517 return;
518
519 ScrollDirection direction = ScrollDown;
520 if (units < 0) {
521 direction = ScrollUp;
522 units = -units;
523 }
524 Node* stopNode = this;
525 toRenderBox(renderer())->scroll(direction, granularity, units, &stopNode);
526}
527
528void Element::scrollByLines(int lines)
529{
530 scrollByUnits(lines, ScrollByLine);
531}
532
533void Element::scrollByPages(int pages)
534{
535 scrollByUnits(pages, ScrollByPage);
536}
537
538static float localZoomForRenderer(RenderObject* renderer)
539{
540 // FIXME: This does the wrong thing if two opposing zooms are in effect and canceled each
541 // other out, but the alternative is that we'd have to crawl up the whole render tree every
542 // time (or store an additional bit in the RenderStyle to indicate that a zoom was specified).
543 float zoomFactor = 1;
544 if (renderer->style()->effectiveZoom() != 1) {
545 // Need to find the nearest enclosing RenderObject that set up
546 // a differing zoom, and then we divide our result by it to eliminate the zoom.
547 RenderObject* prev = renderer;
548 for (RenderObject* curr = prev->parent(); curr; curr = curr->parent()) {
549 if (curr->style()->effectiveZoom() != prev->style()->effectiveZoom()) {
550 zoomFactor = prev->style()->zoom();
551 break;
552 }
553 prev = curr;
554 }
555 if (prev->isRenderView())
556 zoomFactor = prev->style()->zoom();
557 }
558 return zoomFactor;
559}
560
561static int adjustForLocalZoom(LayoutUnit value, RenderObject* renderer)
562{
563 float zoomFactor = localZoomForRenderer(renderer);
564 if (zoomFactor == 1)
565 return value;
566 return lroundf(value / zoomFactor);
567}
568
569int Element::offsetLeft()
570{
571 document()->updateLayoutIgnorePendingStylesheets();
572 if (RenderBoxModelObject* renderer = renderBoxModelObject())
573 return adjustForLocalZoom(renderer->pixelSnappedOffsetLeft(), renderer);
574 return 0;
575}
576
577int Element::offsetTop()
578{
579 document()->updateLayoutIgnorePendingStylesheets();
580 if (RenderBoxModelObject* renderer = renderBoxModelObject())
581 return adjustForLocalZoom(renderer->pixelSnappedOffsetTop(), renderer);
582 return 0;
583}
584
585int Element::offsetWidth()
586{
Ben Murdoch591b9582013-07-10 11:41:44 +0100587 document()->updateStyleForNodeIfNeeded(this);
588
589 if (RenderBox* renderer = renderBox()) {
590 if (!renderer->requiresLayoutToDetermineWidth())
591 return adjustLayoutUnitForAbsoluteZoom(renderer->fixedOffsetWidth(), renderer).round();
592 }
593
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100594 document()->updateLayoutIgnorePendingStylesheets();
595 if (RenderBoxModelObject* renderer = renderBoxModelObject())
596 return adjustLayoutUnitForAbsoluteZoom(renderer->pixelSnappedOffsetWidth(), renderer).round();
597 return 0;
598}
599
600int Element::offsetHeight()
601{
602 document()->updateLayoutIgnorePendingStylesheets();
603 if (RenderBoxModelObject* renderer = renderBoxModelObject())
604 return adjustLayoutUnitForAbsoluteZoom(renderer->pixelSnappedOffsetHeight(), renderer).round();
605 return 0;
606}
607
608Element* Element::bindingsOffsetParent()
609{
610 Element* element = offsetParent();
611 if (!element || !element->isInShadowTree())
612 return element;
Torne (Richard Coles)521d96e2013-06-19 11:58:24 +0100613 return element->containingShadowRoot()->shouldExposeToBindings() ? element : 0;
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100614}
615
616Element* Element::offsetParent()
617{
618 document()->updateLayoutIgnorePendingStylesheets();
619 if (RenderObject* renderer = this->renderer())
620 return renderer->offsetParent();
621 return 0;
622}
623
624int Element::clientLeft()
625{
626 document()->updateLayoutIgnorePendingStylesheets();
627
628 if (RenderBox* renderer = renderBox())
629 return adjustForAbsoluteZoom(roundToInt(renderer->clientLeft()), renderer);
630 return 0;
631}
632
633int Element::clientTop()
634{
635 document()->updateLayoutIgnorePendingStylesheets();
636
637 if (RenderBox* renderer = renderBox())
638 return adjustForAbsoluteZoom(roundToInt(renderer->clientTop()), renderer);
639 return 0;
640}
641
642int Element::clientWidth()
643{
644 document()->updateLayoutIgnorePendingStylesheets();
645
646 // When in strict mode, clientWidth for the document element should return the width of the containing frame.
647 // When in quirks mode, clientWidth for the body element should return the width of the containing frame.
648 bool inQuirksMode = document()->inQuirksMode();
649 if ((!inQuirksMode && document()->documentElement() == this) ||
650 (inQuirksMode && isHTMLElement() && document()->body() == this)) {
651 if (FrameView* view = document()->view()) {
652 if (RenderView* renderView = document()->renderView())
653 return adjustForAbsoluteZoom(view->layoutWidth(), renderView);
654 }
655 }
Ben Murdoch591b9582013-07-10 11:41:44 +0100656
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100657 if (RenderBox* renderer = renderBox())
658 return adjustLayoutUnitForAbsoluteZoom(renderer->pixelSnappedClientWidth(), renderer).round();
659 return 0;
660}
661
662int Element::clientHeight()
663{
664 document()->updateLayoutIgnorePendingStylesheets();
665
666 // When in strict mode, clientHeight for the document element should return the height of the containing frame.
667 // When in quirks mode, clientHeight for the body element should return the height of the containing frame.
Ben Murdoch591b9582013-07-10 11:41:44 +0100668 bool inQuirksMode = document()->inQuirksMode();
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100669
670 if ((!inQuirksMode && document()->documentElement() == this) ||
671 (inQuirksMode && isHTMLElement() && document()->body() == this)) {
672 if (FrameView* view = document()->view()) {
673 if (RenderView* renderView = document()->renderView())
674 return adjustForAbsoluteZoom(view->layoutHeight(), renderView);
675 }
676 }
Ben Murdoch591b9582013-07-10 11:41:44 +0100677
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100678 if (RenderBox* renderer = renderBox())
679 return adjustLayoutUnitForAbsoluteZoom(renderer->pixelSnappedClientHeight(), renderer).round();
680 return 0;
681}
682
683int Element::scrollLeft()
684{
685 document()->updateLayoutIgnorePendingStylesheets();
686 if (RenderBox* rend = renderBox())
687 return adjustForAbsoluteZoom(rend->scrollLeft(), rend);
688 return 0;
689}
690
691int Element::scrollTop()
692{
693 document()->updateLayoutIgnorePendingStylesheets();
694 if (RenderBox* rend = renderBox())
695 return adjustForAbsoluteZoom(rend->scrollTop(), rend);
696 return 0;
697}
698
699void Element::setScrollLeft(int newLeft)
700{
701 document()->updateLayoutIgnorePendingStylesheets();
702 if (RenderBox* rend = renderBox())
703 rend->setScrollLeft(static_cast<int>(newLeft * rend->style()->effectiveZoom()));
704}
705
706void Element::setScrollTop(int newTop)
707{
708 document()->updateLayoutIgnorePendingStylesheets();
709 if (RenderBox* rend = renderBox())
710 rend->setScrollTop(static_cast<int>(newTop * rend->style()->effectiveZoom()));
711}
712
713int Element::scrollWidth()
714{
715 document()->updateLayoutIgnorePendingStylesheets();
716 if (RenderBox* rend = renderBox())
717 return adjustForAbsoluteZoom(rend->scrollWidth(), rend);
718 return 0;
719}
720
721int Element::scrollHeight()
722{
723 document()->updateLayoutIgnorePendingStylesheets();
724 if (RenderBox* rend = renderBox())
725 return adjustForAbsoluteZoom(rend->scrollHeight(), rend);
726 return 0;
727}
728
729IntRect Element::boundsInRootViewSpace()
730{
731 document()->updateLayoutIgnorePendingStylesheets();
732
733 FrameView* view = document()->view();
734 if (!view)
735 return IntRect();
736
737 Vector<FloatQuad> quads;
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100738 if (isSVGElement() && renderer()) {
739 // Get the bounding rectangle from the SVG model.
740 SVGElement* svgElement = toSVGElement(this);
741 FloatRect localRect;
742 if (svgElement->getBoundingBox(localRect))
743 quads.append(renderer()->localToAbsoluteQuad(localRect));
Torne (Richard Coles)93ac45c2013-05-29 14:40:20 +0100744 } else {
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100745 // Get the bounding rectangle from the box model.
746 if (renderBoxModelObject())
747 renderBoxModelObject()->absoluteQuads(quads);
748 }
749
750 if (quads.isEmpty())
751 return IntRect();
752
753 IntRect result = quads[0].enclosingBoundingBox();
754 for (size_t i = 1; i < quads.size(); ++i)
755 result.unite(quads[i].enclosingBoundingBox());
756
757 result = view->contentsToRootView(result);
758 return result;
759}
760
761PassRefPtr<ClientRectList> Element::getClientRects()
762{
763 document()->updateLayoutIgnorePendingStylesheets();
764
765 RenderBoxModelObject* renderBoxModelObject = this->renderBoxModelObject();
766 if (!renderBoxModelObject)
767 return ClientRectList::create();
768
769 // FIXME: Handle SVG elements.
770 // FIXME: Handle table/inline-table with a caption.
771
772 Vector<FloatQuad> quads;
773 renderBoxModelObject->absoluteQuads(quads);
774 document()->adjustFloatQuadsForScrollAndAbsoluteZoom(quads, renderBoxModelObject);
775 return ClientRectList::create(quads);
776}
777
778PassRefPtr<ClientRect> Element::getBoundingClientRect()
779{
780 document()->updateLayoutIgnorePendingStylesheets();
781
782 Vector<FloatQuad> quads;
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100783 if (isSVGElement() && renderer() && !renderer()->isSVGRoot()) {
784 // Get the bounding rectangle from the SVG model.
785 SVGElement* svgElement = toSVGElement(this);
786 FloatRect localRect;
787 if (svgElement->getBoundingBox(localRect))
788 quads.append(renderer()->localToAbsoluteQuad(localRect));
Torne (Richard Coles)93ac45c2013-05-29 14:40:20 +0100789 } else {
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100790 // Get the bounding rectangle from the box model.
791 if (renderBoxModelObject())
792 renderBoxModelObject()->absoluteQuads(quads);
793 }
794
795 if (quads.isEmpty())
796 return ClientRect::create();
797
798 FloatRect result = quads[0].boundingBox();
799 for (size_t i = 1; i < quads.size(); ++i)
800 result.unite(quads[i].boundingBox());
801
802 document()->adjustFloatRectForScrollAndAbsoluteZoom(result, renderer());
803 return ClientRect::create(result);
804}
Ben Murdoch591b9582013-07-10 11:41:44 +0100805
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100806IntRect Element::screenRect() const
807{
808 if (!renderer())
809 return IntRect();
810 // FIXME: this should probably respect transforms
811 return document()->view()->contentsToScreen(renderer()->absoluteBoundingBoxRectIgnoringTransforms());
812}
813
814const AtomicString& Element::getAttribute(const AtomicString& localName) const
815{
816 if (!elementData())
817 return nullAtom;
818 synchronizeAttribute(localName);
819 if (const Attribute* attribute = elementData()->getAttributeItem(localName, shouldIgnoreAttributeCase(this)))
820 return attribute->value();
821 return nullAtom;
822}
823
824const AtomicString& Element::getAttributeNS(const AtomicString& namespaceURI, const AtomicString& localName) const
825{
826 return getAttribute(QualifiedName(nullAtom, localName, namespaceURI));
827}
828
Ben Murdochdf957042013-08-06 11:01:27 +0100829void Element::setAttribute(const AtomicString& localName, const AtomicString& value, ExceptionState& es)
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100830{
831 if (!Document::isValidName(localName)) {
Ben Murdochdf957042013-08-06 11:01:27 +0100832 es.throwDOMException(InvalidCharacterError);
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100833 return;
834 }
835
836 synchronizeAttribute(localName);
837 const AtomicString& caseAdjustedLocalName = shouldIgnoreAttributeCase(this) ? localName.lower() : localName;
838
839 size_t index = elementData() ? elementData()->getAttributeItemIndex(caseAdjustedLocalName, false) : notFound;
840 const QualifiedName& qName = index != notFound ? attributeItem(index)->name() : QualifiedName(nullAtom, caseAdjustedLocalName, nullAtom);
841 setAttributeInternal(index, qName, value, NotInSynchronizationOfLazyAttribute);
842}
843
844void Element::setAttribute(const QualifiedName& name, const AtomicString& value)
845{
846 synchronizeAttribute(name);
847 size_t index = elementData() ? elementData()->getAttributeItemIndex(name) : notFound;
848 setAttributeInternal(index, name, value, NotInSynchronizationOfLazyAttribute);
849}
850
851void Element::setSynchronizedLazyAttribute(const QualifiedName& name, const AtomicString& value)
852{
853 size_t index = elementData() ? elementData()->getAttributeItemIndex(name) : notFound;
854 setAttributeInternal(index, name, value, InSynchronizationOfLazyAttribute);
855}
856
857inline void Element::setAttributeInternal(size_t index, const QualifiedName& name, const AtomicString& newValue, SynchronizationOfLazyAttribute inSynchronizationOfLazyAttribute)
858{
859 if (newValue.isNull()) {
860 if (index != notFound)
861 removeAttributeInternal(index, inSynchronizationOfLazyAttribute);
862 return;
863 }
864
865 if (index == notFound) {
866 addAttributeInternal(name, newValue, inSynchronizationOfLazyAttribute);
867 return;
868 }
869
870 if (!inSynchronizationOfLazyAttribute)
871 willModifyAttribute(name, attributeItem(index)->value(), newValue);
872
873 if (newValue != attributeItem(index)->value()) {
874 // If there is an Attr node hooked to this attribute, the Attr::setValue() call below
875 // will write into the ElementData.
876 // FIXME: Refactor this so it makes some sense.
877 if (RefPtr<Attr> attrNode = inSynchronizationOfLazyAttribute ? 0 : attrIfExists(name))
878 attrNode->setValue(newValue);
879 else
880 ensureUniqueElementData()->attributeItem(index)->setValue(newValue);
881 }
882
883 if (!inSynchronizationOfLazyAttribute)
884 didModifyAttribute(name, newValue);
885}
886
887static inline AtomicString makeIdForStyleResolution(const AtomicString& value, bool inQuirksMode)
888{
889 if (inQuirksMode)
890 return value.lower();
891 return value;
892}
893
Ben Murdoch7757ec22013-07-23 11:17:36 +0100894static bool checkNeedsStyleInvalidationForIdChange(const AtomicString& oldId, const AtomicString& newId, const RuleFeatureSet& features)
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100895{
896 ASSERT(newId != oldId);
Ben Murdoch7757ec22013-07-23 11:17:36 +0100897 if (!oldId.isEmpty() && features.hasSelectorForId(oldId))
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100898 return true;
Ben Murdoch7757ec22013-07-23 11:17:36 +0100899 if (!newId.isEmpty() && features.hasSelectorForId(newId))
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100900 return true;
901 return false;
902}
903
Ben Murdoch591b9582013-07-10 11:41:44 +0100904void Element::attributeChanged(const QualifiedName& name, const AtomicString& newValue, AttributeModificationReason reason)
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100905{
906 if (ElementShadow* parentElementShadow = shadowOfParentForDistribution(this)) {
907 if (shouldInvalidateDistributionWhenAttributeChanged(parentElementShadow, name, newValue))
Torne (Richard Coles)f5e4ad52013-08-05 13:57:57 +0100908 parentElementShadow->setNeedsDistributionRecalc();
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100909 }
910
911 parseAttribute(name, newValue);
912
913 document()->incDOMTreeVersion();
914
915 StyleResolver* styleResolver = document()->styleResolverIfExists();
Ben Murdoche69819b2013-07-17 14:56:49 +0100916 bool testShouldInvalidateStyle = attached() && styleResolver && styleChangeType() < SubtreeStyleChange;
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100917 bool shouldInvalidateStyle = false;
918
Ben Murdoch591b9582013-07-10 11:41:44 +0100919 if (isStyledElement() && name == styleAttr) {
920 styleAttributeChanged(newValue, reason);
921 } else if (isStyledElement() && isPresentationAttribute(name)) {
922 elementData()->m_presentationAttributeStyleIsDirty = true;
Ben Murdoche69819b2013-07-17 14:56:49 +0100923 setNeedsStyleRecalc(LocalStyleChange);
Ben Murdoch591b9582013-07-10 11:41:44 +0100924 }
925
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100926 if (isIdAttributeName(name)) {
927 AtomicString oldId = elementData()->idForStyleResolution();
928 AtomicString newId = makeIdForStyleResolution(newValue, document()->inQuirksMode());
929 if (newId != oldId) {
930 elementData()->setIdForStyleResolution(newId);
Ben Murdoch7757ec22013-07-23 11:17:36 +0100931 shouldInvalidateStyle = testShouldInvalidateStyle && checkNeedsStyleInvalidationForIdChange(oldId, newId, styleResolver->ruleFeatureSet());
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100932 }
Ben Murdoch591b9582013-07-10 11:41:44 +0100933 } else if (name == classAttr) {
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100934 classAttributeChanged(newValue);
Ben Murdoch591b9582013-07-10 11:41:44 +0100935 } else if (name == HTMLNames::nameAttr) {
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100936 setHasName(!newValue.isNull());
Ben Murdoch591b9582013-07-10 11:41:44 +0100937 } else if (name == HTMLNames::pseudoAttr) {
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100938 shouldInvalidateStyle |= testShouldInvalidateStyle && isInShadowTree();
Ben Murdoch591b9582013-07-10 11:41:44 +0100939 }
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100940
941 invalidateNodeListCachesInAncestors(&name, this);
942
943 // If there is currently no StyleResolver, we can't be sure that this attribute change won't affect style.
944 shouldInvalidateStyle |= !styleResolver;
945
946 if (shouldInvalidateStyle)
947 setNeedsStyleRecalc();
948
949 if (AXObjectCache* cache = document()->existingAXObjectCache())
950 cache->handleAttributeChanged(name, this);
951}
952
953inline void Element::attributeChangedFromParserOrByCloning(const QualifiedName& name, const AtomicString& newValue, AttributeModificationReason reason)
954{
Ben Murdoche69819b2013-07-17 14:56:49 +0100955 if (name == isAttr)
Ben Murdoch0019e4e2013-07-18 11:57:54 +0100956 CustomElementRegistrationContext::setTypeExtension(this, newValue);
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100957 attributeChanged(name, newValue, reason);
958}
959
960template <typename CharacterType>
961static inline bool classStringHasClassName(const CharacterType* characters, unsigned length)
962{
963 ASSERT(length > 0);
964
965 unsigned i = 0;
966 do {
967 if (isNotHTMLSpace(characters[i]))
968 break;
969 ++i;
970 } while (i < length);
971
972 return i < length;
973}
974
975static inline bool classStringHasClassName(const AtomicString& newClassString)
976{
977 unsigned length = newClassString.length();
978
979 if (!length)
980 return false;
981
982 if (newClassString.is8Bit())
983 return classStringHasClassName(newClassString.characters8(), length);
984 return classStringHasClassName(newClassString.characters16(), length);
985}
986
987template<typename Checker>
988static bool checkSelectorForClassChange(const SpaceSplitString& changedClasses, const Checker& checker)
989{
990 unsigned changedSize = changedClasses.size();
991 for (unsigned i = 0; i < changedSize; ++i) {
992 if (checker.hasSelectorForClass(changedClasses[i]))
993 return true;
994 }
995 return false;
996}
997
998template<typename Checker>
999static bool checkSelectorForClassChange(const SpaceSplitString& oldClasses, const SpaceSplitString& newClasses, const Checker& checker)
1000{
1001 unsigned oldSize = oldClasses.size();
1002 if (!oldSize)
1003 return checkSelectorForClassChange(newClasses, checker);
1004 BitVector remainingClassBits;
1005 remainingClassBits.ensureSize(oldSize);
1006 // Class vectors tend to be very short. This is faster than using a hash table.
1007 unsigned newSize = newClasses.size();
1008 for (unsigned i = 0; i < newSize; ++i) {
1009 for (unsigned j = 0; j < oldSize; ++j) {
1010 if (newClasses[i] == oldClasses[j]) {
1011 remainingClassBits.quickSet(j);
1012 continue;
1013 }
1014 }
1015 if (checker.hasSelectorForClass(newClasses[i]))
1016 return true;
1017 }
1018 for (unsigned i = 0; i < oldSize; ++i) {
1019 // If the bit is not set the the corresponding class has been removed.
1020 if (remainingClassBits.quickGet(i))
1021 continue;
1022 if (checker.hasSelectorForClass(oldClasses[i]))
1023 return true;
1024 }
1025 return false;
1026}
1027
1028void Element::classAttributeChanged(const AtomicString& newClassString)
1029{
1030 StyleResolver* styleResolver = document()->styleResolverIfExists();
Ben Murdoche69819b2013-07-17 14:56:49 +01001031 bool testShouldInvalidateStyle = attached() && styleResolver && styleChangeType() < SubtreeStyleChange;
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001032 bool shouldInvalidateStyle = false;
1033
1034 if (classStringHasClassName(newClassString)) {
1035 const bool shouldFoldCase = document()->inQuirksMode();
1036 const SpaceSplitString oldClasses = elementData()->classNames();
1037 elementData()->setClass(newClassString, shouldFoldCase);
1038 const SpaceSplitString& newClasses = elementData()->classNames();
Ben Murdoch7757ec22013-07-23 11:17:36 +01001039 shouldInvalidateStyle = testShouldInvalidateStyle && checkSelectorForClassChange(oldClasses, newClasses, styleResolver->ruleFeatureSet());
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001040 } else {
1041 const SpaceSplitString& oldClasses = elementData()->classNames();
Ben Murdoch7757ec22013-07-23 11:17:36 +01001042 shouldInvalidateStyle = testShouldInvalidateStyle && checkSelectorForClassChange(oldClasses, styleResolver->ruleFeatureSet());
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001043 elementData()->clearClass();
1044 }
1045
1046 if (hasRareData())
1047 elementRareData()->clearClassListValueForQuirksMode();
1048
1049 if (shouldInvalidateStyle)
1050 setNeedsStyleRecalc();
1051}
1052
1053bool Element::shouldInvalidateDistributionWhenAttributeChanged(ElementShadow* elementShadow, const QualifiedName& name, const AtomicString& newValue)
1054{
1055 ASSERT(elementShadow);
1056 const SelectRuleFeatureSet& featureSet = elementShadow->distributor().ensureSelectFeatureSet(elementShadow);
1057
1058 if (isIdAttributeName(name)) {
1059 AtomicString oldId = elementData()->idForStyleResolution();
1060 AtomicString newId = makeIdForStyleResolution(newValue, document()->inQuirksMode());
1061 if (newId != oldId) {
1062 if (!oldId.isEmpty() && featureSet.hasSelectorForId(oldId))
1063 return true;
1064 if (!newId.isEmpty() && featureSet.hasSelectorForId(newId))
1065 return true;
1066 }
1067 }
1068
1069 if (name == HTMLNames::classAttr) {
1070 const AtomicString& newClassString = newValue;
1071 if (classStringHasClassName(newClassString)) {
1072 const bool shouldFoldCase = document()->inQuirksMode();
1073 const SpaceSplitString& oldClasses = elementData()->classNames();
1074 const SpaceSplitString newClasses(newClassString, shouldFoldCase);
1075 if (checkSelectorForClassChange(oldClasses, newClasses, featureSet))
1076 return true;
1077 } else {
1078 const SpaceSplitString& oldClasses = elementData()->classNames();
1079 if (checkSelectorForClassChange(oldClasses, featureSet))
1080 return true;
1081 }
1082 }
1083
1084 return featureSet.hasSelectorForAttribute(name.localName());
1085}
1086
1087// Returns true is the given attribute is an event handler.
1088// We consider an event handler any attribute that begins with "on".
1089// It is a simple solution that has the advantage of not requiring any
1090// code or configuration change if a new event handler is defined.
1091
1092static inline bool isEventHandlerAttribute(const Attribute& attribute)
1093{
1094 return attribute.name().namespaceURI().isNull() && attribute.name().localName().startsWith("on");
1095}
1096
1097bool Element::isJavaScriptURLAttribute(const Attribute& attribute) const
1098{
1099 return isURLAttribute(attribute) && protocolIsJavaScript(stripLeadingAndTrailingHTMLSpaces(attribute.value()));
1100}
1101
1102void Element::stripScriptingAttributes(Vector<Attribute>& attributeVector) const
1103{
1104 size_t destination = 0;
1105 for (size_t source = 0; source < attributeVector.size(); ++source) {
1106 if (isEventHandlerAttribute(attributeVector[source])
1107 || isJavaScriptURLAttribute(attributeVector[source])
1108 || isHTMLContentAttribute(attributeVector[source]))
1109 continue;
1110
1111 if (source != destination)
1112 attributeVector[destination] = attributeVector[source];
1113
1114 ++destination;
1115 }
1116 attributeVector.shrink(destination);
1117}
1118
1119void Element::parserSetAttributes(const Vector<Attribute>& attributeVector)
1120{
1121 ASSERT(!inDocument());
1122 ASSERT(!parentNode());
1123 ASSERT(!m_elementData);
1124
1125 if (attributeVector.isEmpty())
1126 return;
1127
1128 if (document() && document()->sharedObjectPool())
1129 m_elementData = document()->sharedObjectPool()->cachedShareableElementDataWithAttributes(attributeVector);
1130 else
1131 m_elementData = ShareableElementData::createWithAttributes(attributeVector);
1132
1133 // Use attributeVector instead of m_elementData because attributeChanged might modify m_elementData.
1134 for (unsigned i = 0; i < attributeVector.size(); ++i)
1135 attributeChangedFromParserOrByCloning(attributeVector[i].name(), attributeVector[i].value(), ModifiedDirectly);
1136}
1137
1138bool Element::hasAttributes() const
1139{
1140 synchronizeAllAttributes();
1141 return elementData() && elementData()->length();
1142}
1143
1144bool Element::hasEquivalentAttributes(const Element* other) const
1145{
1146 synchronizeAllAttributes();
1147 other->synchronizeAllAttributes();
1148 if (elementData() == other->elementData())
1149 return true;
1150 if (elementData())
1151 return elementData()->isEquivalent(other->elementData());
1152 if (other->elementData())
1153 return other->elementData()->isEquivalent(elementData());
1154 return true;
1155}
1156
1157String Element::nodeName() const
1158{
1159 return m_tagName.toString();
1160}
1161
1162String Element::nodeNamePreservingCase() const
1163{
1164 return m_tagName.toString();
1165}
1166
Ben Murdochdf957042013-08-06 11:01:27 +01001167void Element::setPrefix(const AtomicString& prefix, ExceptionState& es)
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001168{
Ben Murdochdf957042013-08-06 11:01:27 +01001169 checkSetPrefix(prefix, es);
1170 if (es.hadException())
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001171 return;
1172
1173 m_tagName.setPrefix(prefix.isEmpty() ? AtomicString() : prefix);
1174}
1175
1176KURL Element::baseURI() const
1177{
1178 const AtomicString& baseAttribute = getAttribute(baseAttr);
1179 KURL base(KURL(), baseAttribute);
1180 if (!base.protocol().isEmpty())
1181 return base;
1182
1183 ContainerNode* parent = parentNode();
1184 if (!parent)
1185 return base;
1186
1187 const KURL& parentBase = parent->baseURI();
1188 if (parentBase.isNull())
1189 return base;
1190
1191 return KURL(parentBase, baseAttribute);
1192}
1193
1194const AtomicString& Element::imageSourceURL() const
1195{
1196 return getAttribute(srcAttr);
1197}
1198
1199bool Element::rendererIsNeeded(const NodeRenderingContext& context)
1200{
1201 return context.style()->display() != NONE;
1202}
1203
Ben Murdoch591b9582013-07-10 11:41:44 +01001204RenderObject* Element::createRenderer(RenderStyle* style)
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001205{
1206 return RenderObject::createObject(this, style);
1207}
1208
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001209bool Element::isInert() const
1210{
Torne (Richard Coles)93ac45c2013-05-29 14:40:20 +01001211 const Element* dialog = document()->activeModalDialog();
Ben Murdoch591b9582013-07-10 11:41:44 +01001212 if (dialog && !containsIncludingShadowDOM(dialog) && !dialog->containsIncludingShadowDOM(this))
1213 return true;
1214 return document()->ownerElement() && document()->ownerElement()->isInert();
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001215}
1216
1217Node::InsertionNotificationRequest Element::insertedInto(ContainerNode* insertionPoint)
1218{
1219 // need to do superclass processing first so inDocument() is true
1220 // by the time we reach updateId
1221 ContainerNode::insertedInto(insertionPoint);
1222
1223 if (containsFullScreenElement() && parentElement() && !parentElement()->containsFullScreenElement())
1224 setContainsFullScreenElementOnAncestorsCrossingFrameBoundaries(true);
1225
1226 if (Element* before = pseudoElement(BEFORE))
1227 before->insertedInto(insertionPoint);
1228
1229 if (Element* after = pseudoElement(AFTER))
1230 after->insertedInto(insertionPoint);
1231
1232 if (!insertionPoint->isInTreeScope())
1233 return InsertionDone;
1234
1235 if (hasRareData())
1236 elementRareData()->clearClassListValueForQuirksMode();
1237
Torne (Richard Coles)f5e4ad52013-08-05 13:57:57 +01001238 if (isUpgradedCustomElement() && inDocument())
1239 CustomElement::didEnterDocument(this, document());
1240
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001241 TreeScope* scope = insertionPoint->treeScope();
1242 if (scope != treeScope())
1243 return InsertionDone;
1244
1245 const AtomicString& idValue = getIdAttribute();
1246 if (!idValue.isNull())
1247 updateId(scope, nullAtom, idValue);
1248
1249 const AtomicString& nameValue = getNameAttribute();
1250 if (!nameValue.isNull())
Ben Murdochdf957042013-08-06 11:01:27 +01001251 updateName(nullAtom, nameValue);
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001252
1253 if (hasTagName(labelTag)) {
1254 if (scope->shouldCacheLabelsByForAttribute())
1255 updateLabel(scope, nullAtom, fastGetAttribute(forAttr));
1256 }
1257
1258 return InsertionDone;
1259}
1260
1261void Element::removedFrom(ContainerNode* insertionPoint)
1262{
Torne (Richard Coles)f5e4ad52013-08-05 13:57:57 +01001263 bool wasInDocument = insertionPoint->inDocument();
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001264
1265 if (Element* before = pseudoElement(BEFORE))
1266 before->removedFrom(insertionPoint);
1267
1268 if (Element* after = pseudoElement(AFTER))
1269 after->removedFrom(insertionPoint);
1270
Ben Murdoche69819b2013-07-17 14:56:49 +01001271 if (Element* backdrop = pseudoElement(BACKDROP))
1272 backdrop->removedFrom(insertionPoint);
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001273 document()->removeFromTopLayer(this);
Ben Murdoche69819b2013-07-17 14:56:49 +01001274
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001275 if (containsFullScreenElement())
1276 setContainsFullScreenElementOnAncestorsCrossingFrameBoundaries(false);
1277
1278 if (document()->page())
1279 document()->page()->pointerLockController()->elementRemoved(this);
1280
1281 setSavedLayerScrollOffset(IntSize());
1282
1283 if (insertionPoint->isInTreeScope() && treeScope() == document()) {
1284 const AtomicString& idValue = getIdAttribute();
1285 if (!idValue.isNull())
1286 updateId(insertionPoint->treeScope(), idValue, nullAtom);
1287
1288 const AtomicString& nameValue = getNameAttribute();
1289 if (!nameValue.isNull())
Ben Murdochdf957042013-08-06 11:01:27 +01001290 updateName(nameValue, nullAtom);
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001291
1292 if (hasTagName(labelTag)) {
1293 TreeScope* treeScope = insertionPoint->treeScope();
1294 if (treeScope->shouldCacheLabelsByForAttribute())
1295 updateLabel(treeScope, fastGetAttribute(forAttr), nullAtom);
1296 }
1297 }
1298
1299 ContainerNode::removedFrom(insertionPoint);
Ben Murdoche69819b2013-07-17 14:56:49 +01001300 if (wasInDocument) {
1301 if (hasPendingResources())
1302 document()->accessSVGExtensions()->removeElementFromPendingResources(this);
1303
Ben Murdoch83750172013-07-24 10:36:59 +01001304 if (isUpgradedCustomElement())
Ben Murdochfff88842013-07-30 15:20:09 +01001305 CustomElement::didLeaveDocument(this, insertionPoint->document());
Ben Murdoche69819b2013-07-17 14:56:49 +01001306 }
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001307}
1308
Torne (Richard Coles)521d96e2013-06-19 11:58:24 +01001309void Element::createRendererIfNeeded(const AttachContext& context)
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001310{
Ben Murdoch83750172013-07-24 10:36:59 +01001311 NodeRenderingContext(this, context.resolvedStyle).createRendererForElementIfNeeded();
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001312}
1313
Torne (Richard Coles)521d96e2013-06-19 11:58:24 +01001314void Element::attach(const AttachContext& context)
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001315{
1316 PostAttachCallbackDisabler callbackDisabler(this);
1317 StyleResolverParentPusher parentPusher(this);
1318 WidgetHierarchyUpdatesSuspensionScope suspendWidgetHierarchyUpdates;
1319
Torne (Richard Coles)521d96e2013-06-19 11:58:24 +01001320 createRendererIfNeeded(context);
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001321
1322 if (parentElement() && parentElement()->isInCanvasSubtree())
1323 setIsInCanvasSubtree(true);
1324
1325 createPseudoElementIfNeeded(BEFORE);
1326
1327 // When a shadow root exists, it does the work of attaching the children.
1328 if (ElementShadow* shadow = this->shadow()) {
1329 parentPusher.push();
Ben Murdoch591b9582013-07-10 11:41:44 +01001330 shadow->attach(context);
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001331 } else if (firstChild())
1332 parentPusher.push();
1333
Torne (Richard Coles)521d96e2013-06-19 11:58:24 +01001334 ContainerNode::attach(context);
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001335
1336 createPseudoElementIfNeeded(AFTER);
Ben Murdoche69819b2013-07-17 14:56:49 +01001337 createPseudoElementIfNeeded(BACKDROP);
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001338
Ben Murdoch591b9582013-07-10 11:41:44 +01001339 if (hasRareData()) {
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001340 ElementRareData* data = elementRareData();
1341 if (data->needsFocusAppearanceUpdateSoonAfterAttach()) {
Ben Murdoch7757ec22013-07-23 11:17:36 +01001342 if (isFocusable() && document()->focusedElement() == this)
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001343 document()->updateFocusAppearanceSoon(false /* don't restore selection */);
1344 data->setNeedsFocusAppearanceUpdateSoonAfterAttach(false);
1345 }
1346 }
Ben Murdoch591b9582013-07-10 11:41:44 +01001347
1348 // FIXME: It doesn't appear safe to call didRecalculateStyleForElement when
1349 // not in a Document::recalcStyle. Since we're hopefully going to always
1350 // lazyAttach in the future that problem should go away.
1351 if (document()->inStyleRecalc())
1352 InspectorInstrumentation::didRecalculateStyleForElement(this);
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001353}
1354
1355void Element::unregisterNamedFlowContentNode()
1356{
1357 if (RuntimeEnabledFeatures::cssRegionsEnabled() && inNamedFlow() && document()->renderView())
1358 document()->renderView()->flowThreadController()->unregisterNamedFlowContentNode(this);
1359}
1360
Torne (Richard Coles)521d96e2013-06-19 11:58:24 +01001361void Element::detach(const AttachContext& context)
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001362{
1363 WidgetHierarchyUpdatesSuspensionScope suspendWidgetHierarchyUpdates;
1364 unregisterNamedFlowContentNode();
1365 cancelFocusAppearanceUpdate();
1366 if (hasRareData()) {
1367 ElementRareData* data = elementRareData();
1368 data->setPseudoElement(BEFORE, 0);
1369 data->setPseudoElement(AFTER, 0);
Ben Murdoche69819b2013-07-17 14:56:49 +01001370 data->setPseudoElement(BACKDROP, 0);
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001371 data->setIsInCanvasSubtree(false);
1372 data->resetComputedStyle();
1373 data->resetDynamicRestyleObservations();
Ben Murdoch591b9582013-07-10 11:41:44 +01001374 data->setIsInsideRegion(false);
Torne (Richard Coles)f5e4ad52013-08-05 13:57:57 +01001375
1376 if (RuntimeEnabledFeatures::webAnimationsCSSEnabled() && !context.performingReattach) {
1377 if (ActiveAnimations* activeAnimations = data->activeAnimations())
1378 activeAnimations->cssAnimations()->cancel();
1379 }
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001380 }
Ben Murdoch591b9582013-07-10 11:41:44 +01001381 if (ElementShadow* shadow = this->shadow())
1382 shadow->detach(context);
Torne (Richard Coles)521d96e2013-06-19 11:58:24 +01001383 ContainerNode::detach(context);
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001384}
1385
1386bool Element::pseudoStyleCacheIsInvalid(const RenderStyle* currentStyle, RenderStyle* newStyle)
1387{
1388 ASSERT(currentStyle == renderStyle());
1389 ASSERT(renderer());
1390
1391 if (!currentStyle)
1392 return false;
1393
1394 const PseudoStyleCache* pseudoStyleCache = currentStyle->cachedPseudoStyles();
1395 if (!pseudoStyleCache)
1396 return false;
1397
1398 size_t cacheSize = pseudoStyleCache->size();
1399 for (size_t i = 0; i < cacheSize; ++i) {
1400 RefPtr<RenderStyle> newPseudoStyle;
1401 PseudoId pseudoId = pseudoStyleCache->at(i)->styleType();
1402 if (pseudoId == FIRST_LINE || pseudoId == FIRST_LINE_INHERITED)
1403 newPseudoStyle = renderer()->uncachedFirstLineStyle(newStyle);
1404 else
1405 newPseudoStyle = renderer()->getUncachedPseudoStyle(PseudoStyleRequest(pseudoId), newStyle, newStyle);
1406 if (!newPseudoStyle)
1407 return true;
1408 if (*newPseudoStyle != *pseudoStyleCache->at(i)) {
1409 if (pseudoId < FIRST_INTERNAL_PSEUDOID)
1410 newStyle->setHasPseudoStyle(pseudoId);
1411 newStyle->addCachedPseudoStyle(newPseudoStyle);
1412 if (pseudoId == FIRST_LINE || pseudoId == FIRST_LINE_INHERITED) {
1413 // FIXME: We should do an actual diff to determine whether a repaint vs. layout
1414 // is needed, but for now just assume a layout will be required. The diff code
1415 // in RenderObject::setStyle would need to be factored out so that it could be reused.
1416 renderer()->setNeedsLayoutAndPrefWidthsRecalc();
1417 }
1418 return true;
1419 }
1420 }
1421 return false;
1422}
1423
Torne (Richard Coles)521d96e2013-06-19 11:58:24 +01001424PassRefPtr<RenderStyle> Element::styleForRenderer()
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001425{
1426 if (hasCustomStyleCallbacks()) {
1427 if (RefPtr<RenderStyle> style = customStyleForRenderer())
1428 return style.release();
1429 }
1430
Torne (Richard Coles)521d96e2013-06-19 11:58:24 +01001431 return originalStyleForRenderer();
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001432}
1433
Torne (Richard Coles)521d96e2013-06-19 11:58:24 +01001434PassRefPtr<RenderStyle> Element::originalStyleForRenderer()
Torne (Richard Coles)5267f702013-06-11 10:57:24 +01001435{
Torne (Richard Coles)521d96e2013-06-19 11:58:24 +01001436 return document()->styleResolver()->styleForElement(this);
Torne (Richard Coles)5267f702013-06-11 10:57:24 +01001437}
1438
Ben Murdoche69819b2013-07-17 14:56:49 +01001439bool Element::recalcStyle(StyleChange change)
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001440{
Torne (Richard Coles)93ac45c2013-05-29 14:40:20 +01001441 ASSERT(document()->inStyleRecalc());
1442
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001443 if (hasCustomStyleCallbacks())
1444 willRecalcStyle(change);
1445
1446 // Ref currentStyle in case it would otherwise be deleted when setting the new style in the renderer.
Ben Murdoch83750172013-07-24 10:36:59 +01001447 RefPtr<RenderStyle> currentStyle = renderStyle();
1448 bool hasParentStyle = static_cast<bool>(parentRenderStyle());
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001449 bool hasDirectAdjacentRules = childrenAffectedByDirectAdjacentRules();
1450 bool hasIndirectAdjacentRules = childrenAffectedByForwardPositionalRules();
1451
Ben Murdoch83750172013-07-24 10:36:59 +01001452 if (change > NoChange || needsStyleRecalc()) {
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001453 if (hasRareData())
1454 elementRareData()->resetComputedStyle();
1455 }
1456 if (hasParentStyle && (change >= Inherit || needsStyleRecalc())) {
1457 StyleChange localChange = Detach;
1458 RefPtr<RenderStyle> newStyle;
1459 if (currentStyle) {
1460 // FIXME: This still recalcs style twice when changing display types, but saves
1461 // us from recalcing twice when going from none -> anything else which is more
1462 // common, especially during lazy attach.
Torne (Richard Coles)521d96e2013-06-19 11:58:24 +01001463 newStyle = styleForRenderer();
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001464 localChange = Node::diff(currentStyle.get(), newStyle.get(), document());
Torne (Richard Coles)521d96e2013-06-19 11:58:24 +01001465 } else if (attached() && isActiveInsertionPoint(this)) {
1466 // Active InsertionPoints will never have renderers so there's no reason to
1467 // reattach them repeatedly once they're already attached.
1468 localChange = change;
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001469 }
1470 if (localChange == Detach) {
Torne (Richard Coles)521d96e2013-06-19 11:58:24 +01001471 AttachContext reattachContext;
1472 reattachContext.resolvedStyle = newStyle.get();
1473 reattach(reattachContext);
1474
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001475 // attach recalculates the style for all children. No need to do it twice.
1476 clearNeedsStyleRecalc();
1477 clearChildNeedsStyleRecalc();
1478
1479 if (hasCustomStyleCallbacks())
1480 didRecalcStyle(change);
Ben Murdoche69819b2013-07-17 14:56:49 +01001481 return true;
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001482 }
1483
Ben Murdoch591b9582013-07-10 11:41:44 +01001484 InspectorInstrumentation::didRecalculateStyleForElement(this);
1485
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001486 if (RenderObject* renderer = this->renderer()) {
Torne (Richard Coles)f5e4ad52013-08-05 13:57:57 +01001487 if (localChange != NoChange || pseudoStyleCacheIsInvalid(currentStyle.get(), newStyle.get()) || (change == Force && renderer->requiresForcedStyleRecalcPropagation()) || shouldNotifyRendererWithIdenticalStyles()) {
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001488 renderer->setAnimatableStyle(newStyle.get());
Torne (Richard Coles)f5e4ad52013-08-05 13:57:57 +01001489 } else if (needsStyleRecalc()) {
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001490 // Although no change occurred, we use the new style so that the cousin style sharing code won't get
1491 // fooled into believing this style is the same.
1492 renderer->setStyleInternal(newStyle.get());
1493 }
1494 }
1495
1496 // If "rem" units are used anywhere in the document, and if the document element's font size changes, then go ahead and force font updating
1497 // all the way down the tree. This is simpler than having to maintain a cache of objects (and such font size changes should be rare anyway).
1498 if (document()->styleSheetCollection()->usesRemUnits() && document()->documentElement() == this && localChange != NoChange && currentStyle && newStyle && currentStyle->fontSize() != newStyle->fontSize()) {
1499 // Cached RenderStyles may depend on the re units.
1500 document()->styleResolver()->invalidateMatchedPropertiesCache();
1501 change = Force;
1502 }
1503
Ben Murdochdf957042013-08-06 11:01:27 +01001504 if (styleChangeType() >= SubtreeStyleChange)
Torne (Richard Coles)e5249552013-05-15 11:35:13 +01001505 change = Force;
1506 else if (change != Force)
1507 change = localChange;
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001508 }
1509 StyleResolverParentPusher parentPusher(this);
1510
Torne (Richard Coles)f5e4ad52013-08-05 13:57:57 +01001511 for (ShadowRoot* root = youngestShadowRoot(); root; root = root->olderShadowRoot()) {
1512 if (shouldRecalcStyle(change, root)) {
1513 parentPusher.push();
1514 root->recalcStyle(change);
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001515 }
1516 }
1517
1518 if (shouldRecalcStyle(change, this))
1519 updatePseudoElement(BEFORE, change);
1520
1521 // FIXME: This check is good enough for :hover + foo, but it is not good enough for :hover + foo + bar.
1522 // For now we will just worry about the common case, since it's a lot trickier to get the second case right
1523 // without doing way too much re-resolution.
1524 bool forceCheckOfNextElementSibling = false;
1525 bool forceCheckOfAnyElementSibling = false;
Ben Murdoche69819b2013-07-17 14:56:49 +01001526 bool forceReattachOfAnyWhitespaceSibling = false;
1527 for (Node* child = firstChild(); child; child = child->nextSibling()) {
1528 bool didReattach = false;
1529
1530 if (child->renderer())
1531 forceReattachOfAnyWhitespaceSibling = false;
1532
1533 if (child->isTextNode()) {
1534 if (forceReattachOfAnyWhitespaceSibling && toText(child)->containsOnlyWhitespace())
1535 child->reattach();
1536 else
1537 didReattach = toText(child)->recalcTextStyle(change);
1538 } else if (child->isElementNode()) {
1539 Element* element = toElement(child);
1540
1541 if (forceCheckOfNextElementSibling || forceCheckOfAnyElementSibling)
1542 element->setNeedsStyleRecalc();
1543
Ben Murdochdf957042013-08-06 11:01:27 +01001544 bool childRulesChanged = element->needsStyleRecalc() && element->styleChangeType() >= SubtreeStyleChange;
Ben Murdoche69819b2013-07-17 14:56:49 +01001545 forceCheckOfNextElementSibling = childRulesChanged && hasDirectAdjacentRules;
1546 forceCheckOfAnyElementSibling = forceCheckOfAnyElementSibling || (childRulesChanged && hasIndirectAdjacentRules);
1547
1548 if (shouldRecalcStyle(change, element)) {
1549 parentPusher.push();
1550 didReattach = element->recalcStyle(change);
1551 }
Ben Murdoch591b9582013-07-10 11:41:44 +01001552 }
Ben Murdoche69819b2013-07-17 14:56:49 +01001553
1554 forceReattachOfAnyWhitespaceSibling = didReattach || forceReattachOfAnyWhitespaceSibling;
Torne (Richard Coles)5267f702013-06-11 10:57:24 +01001555 }
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001556
1557 if (shouldRecalcStyle(change, this))
1558 updatePseudoElement(AFTER, change);
1559
1560 clearNeedsStyleRecalc();
1561 clearChildNeedsStyleRecalc();
Ben Murdoch591b9582013-07-10 11:41:44 +01001562
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001563 if (hasCustomStyleCallbacks())
1564 didRecalcStyle(change);
Ben Murdoche69819b2013-07-17 14:56:49 +01001565 return false;
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001566}
1567
1568ElementShadow* Element::shadow() const
1569{
1570 return hasRareData() ? elementRareData()->shadow() : 0;
1571}
1572
1573ElementShadow* Element::ensureShadow()
1574{
1575 return ensureElementRareData()->ensureShadow();
1576}
1577
1578void Element::didAffectSelector(AffectedSelectorMask mask)
1579{
1580 setNeedsStyleRecalc();
1581 if (ElementShadow* elementShadow = shadowOfParentForDistribution(this))
1582 elementShadow->didAffectSelector(mask);
1583}
1584
Ben Murdochdf957042013-08-06 11:01:27 +01001585PassRefPtr<ShadowRoot> Element::createShadowRoot(ExceptionState& es)
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001586{
1587 if (alwaysCreateUserAgentShadowRoot())
1588 ensureUserAgentShadowRoot();
1589
1590 if (RuntimeEnabledFeatures::authorShadowDOMForAnyElementEnabled())
1591 return ensureShadow()->addShadowRoot(this, ShadowRoot::AuthorShadowRoot);
1592
1593 // Since some elements recreates shadow root dynamically, multiple shadow
1594 // subtrees won't work well in that element. Until they are fixed, we disable
1595 // adding author shadow root for them.
1596 if (!areAuthorShadowsAllowed()) {
Ben Murdochdf957042013-08-06 11:01:27 +01001597 es.throwDOMException(HierarchyRequestError);
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001598 return 0;
1599 }
1600 return ensureShadow()->addShadowRoot(this, ShadowRoot::AuthorShadowRoot);
1601}
1602
1603ShadowRoot* Element::shadowRoot() const
1604{
1605 ElementShadow* elementShadow = shadow();
1606 if (!elementShadow)
1607 return 0;
1608 ShadowRoot* shadowRoot = elementShadow->youngestShadowRoot();
1609 if (shadowRoot->type() == ShadowRoot::AuthorShadowRoot)
1610 return shadowRoot;
1611 return 0;
1612}
1613
1614ShadowRoot* Element::userAgentShadowRoot() const
1615{
1616 if (ElementShadow* elementShadow = shadow()) {
1617 if (ShadowRoot* shadowRoot = elementShadow->oldestShadowRoot()) {
1618 ASSERT(shadowRoot->type() == ShadowRoot::UserAgentShadowRoot);
1619 return shadowRoot;
1620 }
1621 }
1622
1623 return 0;
1624}
1625
1626ShadowRoot* Element::ensureUserAgentShadowRoot()
1627{
1628 if (ShadowRoot* shadowRoot = userAgentShadowRoot())
1629 return shadowRoot;
1630 ShadowRoot* shadowRoot = ensureShadow()->addShadowRoot(this, ShadowRoot::UserAgentShadowRoot);
1631 didAddUserAgentShadowRoot(shadowRoot);
1632 return shadowRoot;
1633}
1634
Ben Murdoch1fad5ca2013-08-07 11:05:11 +01001635bool Element::supportsShadowElementForUserAgentShadow() const
1636{
1637 return true;
1638}
1639
Torne (Richard Coles)f5e4ad52013-08-05 13:57:57 +01001640// FIXME: After replacing all internal shadowPseudoId with shadowPartId, remove this method.
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001641const AtomicString& Element::shadowPseudoId() const
1642{
1643 return pseudo();
1644}
1645
Torne (Richard Coles)f5e4ad52013-08-05 13:57:57 +01001646const AtomicString& Element::shadowPartId() const
1647{
1648 return part();
1649}
1650
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001651bool Element::childTypeAllowed(NodeType type) const
1652{
1653 switch (type) {
1654 case ELEMENT_NODE:
1655 case TEXT_NODE:
1656 case COMMENT_NODE:
1657 case PROCESSING_INSTRUCTION_NODE:
1658 case CDATA_SECTION_NODE:
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001659 return true;
1660 default:
1661 break;
1662 }
1663 return false;
1664}
1665
Ben Murdoch83750172013-07-24 10:36:59 +01001666static void inline checkForEmptyStyleChange(Element* element, RenderStyle* style)
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001667{
1668 if (!style && !element->styleAffectedByEmpty())
1669 return;
1670
1671 if (!style || (element->styleAffectedByEmpty() && (!style->emptyState() || element->hasChildNodes())))
1672 element->setNeedsStyleRecalc();
1673}
1674
1675static void checkForSiblingStyleChanges(Element* e, RenderStyle* style, bool finishedParsingCallback,
1676 Node* beforeChange, Node* afterChange, int childCountDelta)
1677{
Ben Murdochdf957042013-08-06 11:01:27 +01001678 if (!e->attached() || e->document()->hasPendingForcedStyleRecalc() || e->styleChangeType() >= SubtreeStyleChange)
Ben Murdoch83750172013-07-24 10:36:59 +01001679 return;
1680
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001681 // :empty selector.
1682 checkForEmptyStyleChange(e, style);
Ben Murdoch591b9582013-07-10 11:41:44 +01001683
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001684 if (!style || (e->needsStyleRecalc() && e->childrenAffectedByPositionalRules()))
1685 return;
1686
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001687 // Forward positional selectors include the ~ selector, nth-child, nth-of-type, first-of-type and only-of-type.
1688 // Backward positional selectors include nth-last-child, nth-last-of-type, last-of-type and only-of-type.
1689 // We have to invalidate everything following the insertion point in the forward case, and everything before the insertion point in the
1690 // backward case.
1691 // |afterChange| is 0 in the parser callback case, so we won't do any work for the forward case if we don't have to.
1692 // For performance reasons we just mark the parent node as changed, since we don't want to make childrenChanged O(n^2) by crawling all our kids
Ben Murdoch83750172013-07-24 10:36:59 +01001693 // here. recalcStyle will then force a walk of the children when it sees that this has happened.
1694 if ((e->childrenAffectedByForwardPositionalRules() && afterChange) || (e->childrenAffectedByBackwardPositionalRules() && beforeChange)) {
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001695 e->setNeedsStyleRecalc();
Ben Murdoch83750172013-07-24 10:36:59 +01001696 return;
1697 }
1698
1699 // :first-child. In the parser callback case, we don't have to check anything, since we were right the first time.
1700 // In the DOM case, we only need to do something if |afterChange| is not 0.
1701 // |afterChange| is 0 in the parser case, so it works out that we'll skip this block.
1702 if (e->childrenAffectedByFirstChildRules() && afterChange) {
1703 // Find our new first child.
1704 Node* newFirstChild = e->firstElementChild();
1705 RenderStyle* newFirstChildStyle = newFirstChild ? newFirstChild->renderStyle() : 0;
1706
1707 // Find the first element node following |afterChange|
1708 Node* firstElementAfterInsertion = afterChange->isElementNode() ? afterChange : afterChange->nextElementSibling();
1709 RenderStyle* firstElementAfterInsertionStyle = firstElementAfterInsertion ? firstElementAfterInsertion->renderStyle() : 0;
1710
1711 // This is the insert/append case.
1712 if (newFirstChild != firstElementAfterInsertion && firstElementAfterInsertionStyle && firstElementAfterInsertionStyle->firstChildState())
1713 firstElementAfterInsertion->setNeedsStyleRecalc();
1714
1715 // We also have to handle node removal.
1716 if (childCountDelta < 0 && newFirstChild == firstElementAfterInsertion && newFirstChild && (!newFirstChildStyle || !newFirstChildStyle->firstChildState()))
1717 newFirstChild->setNeedsStyleRecalc();
1718 }
1719
1720 // :last-child. In the parser callback case, we don't have to check anything, since we were right the first time.
1721 // In the DOM case, we only need to do something if |afterChange| is not 0.
1722 if (e->childrenAffectedByLastChildRules() && beforeChange) {
1723 // Find our new last child.
1724 Node* newLastChild = e->lastElementChild();
1725 RenderStyle* newLastChildStyle = newLastChild ? newLastChild->renderStyle() : 0;
1726
1727 // Find the last element node going backwards from |beforeChange|
1728 Node* lastElementBeforeInsertion = beforeChange->isElementNode() ? beforeChange : beforeChange->previousElementSibling();
1729 RenderStyle* lastElementBeforeInsertionStyle = lastElementBeforeInsertion ? lastElementBeforeInsertion->renderStyle() : 0;
1730
1731 if (newLastChild != lastElementBeforeInsertion && lastElementBeforeInsertionStyle && lastElementBeforeInsertionStyle->lastChildState())
1732 lastElementBeforeInsertion->setNeedsStyleRecalc();
1733
1734 // We also have to handle node removal. The parser callback case is similar to node removal as well in that we need to change the last child
1735 // to match now.
1736 if ((childCountDelta < 0 || finishedParsingCallback) && newLastChild == lastElementBeforeInsertion && newLastChild && (!newLastChildStyle || !newLastChildStyle->lastChildState()))
1737 newLastChild->setNeedsStyleRecalc();
1738 }
1739
1740 // The + selector. We need to invalidate the first element following the insertion point. It is the only possible element
1741 // that could be affected by this DOM change.
1742 if (e->childrenAffectedByDirectAdjacentRules() && afterChange) {
1743 if (Node* firstElementAfterInsertion = afterChange->nextElementSibling())
1744 firstElementAfterInsertion->setNeedsStyleRecalc();
1745 }
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001746}
1747
1748void Element::childrenChanged(bool changedByParser, Node* beforeChange, Node* afterChange, int childCountDelta)
1749{
1750 ContainerNode::childrenChanged(changedByParser, beforeChange, afterChange, childCountDelta);
1751 if (changedByParser)
1752 checkForEmptyStyleChange(this, renderStyle());
1753 else
1754 checkForSiblingStyleChanges(this, renderStyle(), false, beforeChange, afterChange, childCountDelta);
1755
Ben Murdoch83750172013-07-24 10:36:59 +01001756 if (ElementShadow* shadow = this->shadow())
Torne (Richard Coles)f5e4ad52013-08-05 13:57:57 +01001757 shadow->setNeedsDistributionRecalc();
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001758}
1759
1760void Element::removeAllEventListeners()
1761{
1762 ContainerNode::removeAllEventListeners();
1763 if (ElementShadow* shadow = this->shadow())
1764 shadow->removeAllEventListeners();
1765}
1766
1767void Element::beginParsingChildren()
1768{
1769 clearIsParsingChildrenFinished();
1770 StyleResolver* styleResolver = document()->styleResolverIfExists();
1771 if (styleResolver && attached())
1772 styleResolver->pushParentElement(this);
1773}
1774
1775void Element::finishParsingChildren()
1776{
1777 ContainerNode::finishParsingChildren();
1778 setIsParsingChildrenFinished();
1779 checkForSiblingStyleChanges(this, renderStyle(), true, lastChild(), 0, 0);
1780 if (StyleResolver* styleResolver = document()->styleResolverIfExists())
1781 styleResolver->popParentElement(this);
1782}
1783
1784#ifndef NDEBUG
1785void Element::formatForDebugger(char* buffer, unsigned length) const
1786{
1787 StringBuilder result;
1788 String s;
1789
1790 result.append(nodeName());
1791
1792 s = getIdAttribute();
1793 if (s.length() > 0) {
1794 if (result.length() > 0)
1795 result.appendLiteral("; ");
1796 result.appendLiteral("id=");
1797 result.append(s);
1798 }
1799
1800 s = getAttribute(classAttr);
1801 if (s.length() > 0) {
1802 if (result.length() > 0)
1803 result.appendLiteral("; ");
1804 result.appendLiteral("class=");
1805 result.append(s);
1806 }
1807
1808 strncpy(buffer, result.toString().utf8().data(), length - 1);
1809}
1810#endif
1811
1812const Vector<RefPtr<Attr> >& Element::attrNodeList()
1813{
1814 ASSERT(hasSyntheticAttrChildNodes());
1815 return *attrNodeListForElement(this);
1816}
1817
Ben Murdochdf957042013-08-06 11:01:27 +01001818PassRefPtr<Attr> Element::setAttributeNode(Attr* attrNode, ExceptionState& es)
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001819{
1820 if (!attrNode) {
Ben Murdochdf957042013-08-06 11:01:27 +01001821 es.throwDOMException(TypeMismatchError);
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001822 return 0;
1823 }
1824
1825 RefPtr<Attr> oldAttrNode = attrIfExists(attrNode->qualifiedName());
1826 if (oldAttrNode.get() == attrNode)
1827 return attrNode; // This Attr is already attached to the element.
1828
Ben Murdoche69819b2013-07-17 14:56:49 +01001829 // 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 +01001830 // The DOM user must explicitly clone Attr nodes to re-use them in other elements.
1831 if (attrNode->ownerElement()) {
Ben Murdochdf957042013-08-06 11:01:27 +01001832 es.throwDOMException(InUseAttributeError);
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001833 return 0;
1834 }
1835
1836 synchronizeAllAttributes();
1837 UniqueElementData* elementData = ensureUniqueElementData();
1838
1839 size_t index = elementData->getAttributeItemIndex(attrNode->qualifiedName());
1840 if (index != notFound) {
1841 if (oldAttrNode)
1842 detachAttrNodeFromElementWithValue(oldAttrNode.get(), elementData->attributeItem(index)->value());
1843 else
1844 oldAttrNode = Attr::create(document(), attrNode->qualifiedName(), elementData->attributeItem(index)->value());
1845 }
1846
1847 setAttributeInternal(index, attrNode->qualifiedName(), attrNode->value(), NotInSynchronizationOfLazyAttribute);
1848
1849 attrNode->attachToElement(this);
Ben Murdoch591b9582013-07-10 11:41:44 +01001850 treeScope()->adoptIfNeeded(attrNode);
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001851 ensureAttrNodeListForElement(this)->append(attrNode);
1852
1853 return oldAttrNode.release();
1854}
1855
Ben Murdochdf957042013-08-06 11:01:27 +01001856PassRefPtr<Attr> Element::setAttributeNodeNS(Attr* attr, ExceptionState& es)
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001857{
Ben Murdochdf957042013-08-06 11:01:27 +01001858 return setAttributeNode(attr, es);
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001859}
1860
Ben Murdochdf957042013-08-06 11:01:27 +01001861PassRefPtr<Attr> Element::removeAttributeNode(Attr* attr, ExceptionState& es)
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001862{
1863 if (!attr) {
Ben Murdochdf957042013-08-06 11:01:27 +01001864 es.throwDOMException(TypeMismatchError);
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001865 return 0;
1866 }
1867 if (attr->ownerElement() != this) {
Ben Murdochdf957042013-08-06 11:01:27 +01001868 es.throwDOMException(NotFoundError);
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001869 return 0;
1870 }
1871
1872 ASSERT(document() == attr->document());
1873
1874 synchronizeAttribute(attr->qualifiedName());
1875
Torne (Richard Coles)e5249552013-05-15 11:35:13 +01001876 size_t index = elementData()->getAttrIndex(attr);
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001877 if (index == notFound) {
Ben Murdochdf957042013-08-06 11:01:27 +01001878 es.throwDOMException(NotFoundError);
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001879 return 0;
1880 }
1881
Torne (Richard Coles)e5249552013-05-15 11:35:13 +01001882 RefPtr<Attr> guard(attr);
1883 detachAttrNodeAtIndex(attr, index);
1884 return guard.release();
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001885}
1886
Ben Murdochdf957042013-08-06 11:01:27 +01001887bool Element::parseAttributeName(QualifiedName& out, const AtomicString& namespaceURI, const AtomicString& qualifiedName, ExceptionState& es)
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001888{
1889 String prefix, localName;
Ben Murdochdf957042013-08-06 11:01:27 +01001890 if (!Document::parseQualifiedName(qualifiedName, prefix, localName, es))
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001891 return false;
Ben Murdochdf957042013-08-06 11:01:27 +01001892 ASSERT(!es.hadException());
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001893
1894 QualifiedName qName(prefix, localName, namespaceURI);
1895
1896 if (!Document::hasValidNamespaceForAttributes(qName)) {
Ben Murdochdf957042013-08-06 11:01:27 +01001897 es.throwDOMException(NamespaceError);
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001898 return false;
1899 }
1900
1901 out = qName;
1902 return true;
1903}
1904
Ben Murdochdf957042013-08-06 11:01:27 +01001905void Element::setAttributeNS(const AtomicString& namespaceURI, const AtomicString& qualifiedName, const AtomicString& value, ExceptionState& es)
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001906{
1907 QualifiedName parsedName = anyName;
Ben Murdochdf957042013-08-06 11:01:27 +01001908 if (!parseAttributeName(parsedName, namespaceURI, qualifiedName, es))
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001909 return;
1910 setAttribute(parsedName, value);
1911}
1912
1913void Element::removeAttributeInternal(size_t index, SynchronizationOfLazyAttribute inSynchronizationOfLazyAttribute)
1914{
1915 ASSERT_WITH_SECURITY_IMPLICATION(index < attributeCount());
1916
1917 UniqueElementData* elementData = ensureUniqueElementData();
1918
1919 QualifiedName name = elementData->attributeItem(index)->name();
1920 AtomicString valueBeingRemoved = elementData->attributeItem(index)->value();
1921
1922 if (!inSynchronizationOfLazyAttribute) {
1923 if (!valueBeingRemoved.isNull())
1924 willModifyAttribute(name, valueBeingRemoved, nullAtom);
1925 }
1926
1927 if (RefPtr<Attr> attrNode = attrIfExists(name))
1928 detachAttrNodeFromElementWithValue(attrNode.get(), elementData->attributeItem(index)->value());
1929
1930 elementData->removeAttribute(index);
1931
1932 if (!inSynchronizationOfLazyAttribute)
1933 didRemoveAttribute(name);
1934}
1935
1936void Element::addAttributeInternal(const QualifiedName& name, const AtomicString& value, SynchronizationOfLazyAttribute inSynchronizationOfLazyAttribute)
1937{
1938 if (!inSynchronizationOfLazyAttribute)
1939 willModifyAttribute(name, nullAtom, value);
1940 ensureUniqueElementData()->addAttribute(name, value);
1941 if (!inSynchronizationOfLazyAttribute)
1942 didAddAttribute(name, value);
1943}
1944
1945void Element::removeAttribute(const AtomicString& name)
1946{
1947 if (!elementData())
1948 return;
1949
1950 AtomicString localName = shouldIgnoreAttributeCase(this) ? name.lower() : name;
1951 size_t index = elementData()->getAttributeItemIndex(localName, false);
1952 if (index == notFound) {
1953 if (UNLIKELY(localName == styleAttr) && elementData()->m_styleAttributeIsDirty && isStyledElement())
Ben Murdoch591b9582013-07-10 11:41:44 +01001954 removeAllInlineStyleProperties();
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001955 return;
1956 }
1957
1958 removeAttributeInternal(index, NotInSynchronizationOfLazyAttribute);
1959}
1960
1961void Element::removeAttributeNS(const AtomicString& namespaceURI, const AtomicString& localName)
1962{
1963 removeAttribute(QualifiedName(nullAtom, localName, namespaceURI));
1964}
1965
1966PassRefPtr<Attr> Element::getAttributeNode(const AtomicString& localName)
1967{
1968 if (!elementData())
1969 return 0;
1970 synchronizeAttribute(localName);
1971 const Attribute* attribute = elementData()->getAttributeItem(localName, shouldIgnoreAttributeCase(this));
1972 if (!attribute)
1973 return 0;
1974 return ensureAttr(attribute->name());
1975}
1976
1977PassRefPtr<Attr> Element::getAttributeNodeNS(const AtomicString& namespaceURI, const AtomicString& localName)
1978{
1979 if (!elementData())
1980 return 0;
1981 QualifiedName qName(nullAtom, localName, namespaceURI);
1982 synchronizeAttribute(qName);
1983 const Attribute* attribute = elementData()->getAttributeItem(qName);
1984 if (!attribute)
1985 return 0;
1986 return ensureAttr(attribute->name());
1987}
1988
1989bool Element::hasAttribute(const AtomicString& localName) const
1990{
1991 if (!elementData())
1992 return false;
1993 synchronizeAttribute(localName);
1994 return elementData()->getAttributeItem(shouldIgnoreAttributeCase(this) ? localName.lower() : localName, false);
1995}
1996
1997bool Element::hasAttributeNS(const AtomicString& namespaceURI, const AtomicString& localName) const
1998{
1999 if (!elementData())
2000 return false;
2001 QualifiedName qName(nullAtom, localName, namespaceURI);
2002 synchronizeAttribute(qName);
2003 return elementData()->getAttributeItem(qName);
2004}
2005
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002006void Element::focus(bool restorePreviousSelection, FocusDirection direction)
2007{
2008 if (!inDocument())
2009 return;
2010
2011 Document* doc = document();
Ben Murdoch7757ec22013-07-23 11:17:36 +01002012 if (doc->focusedElement() == this)
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002013 return;
2014
2015 // If the stylesheets have already been loaded we can reliably check isFocusable.
2016 // If not, we continue and set the focused node on the focus controller below so
Ben Murdoch591b9582013-07-10 11:41:44 +01002017 // that it can be updated soon after attach.
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002018 if (doc->haveStylesheetsLoaded()) {
2019 doc->updateLayoutIgnorePendingStylesheets();
2020 if (!isFocusable())
2021 return;
2022 }
2023
2024 if (!supportsFocus())
2025 return;
2026
2027 RefPtr<Node> protect;
2028 if (Page* page = doc->page()) {
2029 // Focus and change event handlers can cause us to lose our last ref.
2030 // If a focus event handler changes the focus to a different node it
2031 // does not make sense to continue and update appearence.
2032 protect = this;
Ben Murdoche69819b2013-07-17 14:56:49 +01002033 if (!page->focusController()->setFocusedElement(this, doc->frame(), direction))
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002034 return;
2035 }
2036
2037 // Setting the focused node above might have invalidated the layout due to scripts.
2038 doc->updateLayoutIgnorePendingStylesheets();
2039
2040 if (!isFocusable()) {
2041 ensureElementRareData()->setNeedsFocusAppearanceUpdateSoonAfterAttach(true);
2042 return;
2043 }
Ben Murdoch591b9582013-07-10 11:41:44 +01002044
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002045 cancelFocusAppearanceUpdate();
2046 updateFocusAppearance(restorePreviousSelection);
2047}
2048
2049void Element::updateFocusAppearance(bool /*restorePreviousSelection*/)
2050{
2051 if (isRootEditableElement()) {
2052 Frame* frame = document()->frame();
2053 if (!frame)
2054 return;
Ben Murdoch591b9582013-07-10 11:41:44 +01002055
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002056 // When focusing an editable element in an iframe, don't reset the selection if it already contains a selection.
2057 if (this == frame->selection()->rootEditableElement())
2058 return;
2059
2060 // FIXME: We should restore the previous selection if there is one.
2061 VisibleSelection newSelection = VisibleSelection(firstPositionInOrBeforeNode(this), DOWNSTREAM);
Ben Murdoch591b9582013-07-10 11:41:44 +01002062
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002063 if (frame->selection()->shouldChangeSelection(newSelection)) {
2064 frame->selection()->setSelection(newSelection);
2065 frame->selection()->revealSelection();
2066 }
2067 } else if (renderer() && !renderer()->isWidget())
2068 renderer()->scrollRectToVisible(boundingBox());
2069}
2070
2071void Element::blur()
2072{
2073 cancelFocusAppearanceUpdate();
Ben Murdoche69819b2013-07-17 14:56:49 +01002074 if (treeScope()->adjustedFocusedElement() == this) {
2075 Document* doc = document();
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002076 if (doc->frame())
Ben Murdoche69819b2013-07-17 14:56:49 +01002077 doc->frame()->page()->focusController()->setFocusedElement(0, doc->frame());
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002078 else
Ben Murdoche69819b2013-07-17 14:56:49 +01002079 doc->setFocusedElement(0);
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002080 }
2081}
2082
Ben Murdochdf957042013-08-06 11:01:27 +01002083bool Element::isFocusable() const
2084{
2085 return inDocument() && supportsFocus() && !isInert() && rendererIsFocusable();
2086}
2087
Torne (Richard Coles)f5e4ad52013-08-05 13:57:57 +01002088bool Element::isKeyboardFocusable() const
2089{
2090 return isFocusable() && tabIndex() >= 0;
2091}
2092
2093bool Element::isMouseFocusable() const
2094{
2095 return isFocusable();
2096}
2097
Ben Murdoch02772c62013-07-26 10:21:05 +01002098void Element::dispatchFocusEvent(Element* oldFocusedElement, FocusDirection)
2099{
2100 RefPtr<FocusEvent> event = FocusEvent::create(eventNames().focusEvent, false, false, document()->defaultView(), 0, oldFocusedElement);
2101 EventDispatcher::dispatchEvent(this, FocusEventDispatchMediator::create(event.release()));
2102}
2103
2104void Element::dispatchBlurEvent(Element* newFocusedElement)
2105{
2106 RefPtr<FocusEvent> event = FocusEvent::create(eventNames().blurEvent, false, false, document()->defaultView(), 0, newFocusedElement);
2107 EventDispatcher::dispatchEvent(this, BlurEventDispatchMediator::create(event.release()));
2108}
2109
2110void Element::dispatchFocusInEvent(const AtomicString& eventType, Element* oldFocusedElement)
2111{
2112 ASSERT(!NoEventDispatchAssertion::isEventDispatchForbidden());
2113 ASSERT(eventType == eventNames().focusinEvent || eventType == eventNames().DOMFocusInEvent);
2114 dispatchScopedEventDispatchMediator(FocusInEventDispatchMediator::create(FocusEvent::create(eventType, true, false, document()->defaultView(), 0, oldFocusedElement)));
2115}
2116
2117void Element::dispatchFocusOutEvent(const AtomicString& eventType, Element* newFocusedElement)
2118{
2119 ASSERT(!NoEventDispatchAssertion::isEventDispatchForbidden());
2120 ASSERT(eventType == eventNames().focusoutEvent || eventType == eventNames().DOMFocusOutEvent);
2121 dispatchScopedEventDispatchMediator(FocusOutEventDispatchMediator::create(FocusEvent::create(eventType, true, false, document()->defaultView(), 0, newFocusedElement)));
2122}
2123
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002124String Element::innerText()
2125{
2126 // We need to update layout, since plainText uses line boxes in the render tree.
2127 document()->updateLayoutIgnorePendingStylesheets();
2128
2129 if (!renderer())
2130 return textContent(true);
2131
2132 return plainText(rangeOfContents(const_cast<Element*>(this)).get());
2133}
2134
2135String Element::outerText()
2136{
2137 // Getting outerText is the same as getting innerText, only
2138 // setting is different. You would think this should get the plain
2139 // text for the outer range, but this is wrong, <br> for instance
2140 // would return different values for inner and outer text by such
2141 // a rule, but it doesn't in WinIE, and we want to match that.
2142 return innerText();
2143}
2144
Ben Murdoch591b9582013-07-10 11:41:44 +01002145String Element::textFromChildren()
2146{
2147 Text* firstTextNode = 0;
2148 bool foundMultipleTextNodes = false;
2149 unsigned totalLength = 0;
2150
2151 for (Node* child = firstChild(); child; child = child->nextSibling()) {
2152 if (!child->isTextNode())
2153 continue;
2154 Text* text = toText(child);
2155 if (!firstTextNode)
2156 firstTextNode = text;
2157 else
2158 foundMultipleTextNodes = true;
2159 unsigned length = text->data().length();
2160 if (length > std::numeric_limits<unsigned>::max() - totalLength)
2161 return emptyString();
2162 totalLength += length;
2163 }
2164
2165 if (!firstTextNode)
2166 return emptyString();
2167
2168 if (firstTextNode && !foundMultipleTextNodes) {
2169 firstTextNode->atomize();
2170 return firstTextNode->data();
2171 }
2172
2173 StringBuilder content;
2174 content.reserveCapacity(totalLength);
2175 for (Node* child = firstTextNode; child; child = child->nextSibling()) {
2176 if (!child->isTextNode())
2177 continue;
2178 content.append(toText(child)->data());
2179 }
2180
2181 ASSERT(content.length() == totalLength);
2182 return content.toString();
2183}
2184
Torne (Richard Coles)f5e4ad52013-08-05 13:57:57 +01002185// FIXME: pseudo should be deprecated after all pseudo is replaced with ::part.
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002186const AtomicString& Element::pseudo() const
2187{
2188 return getAttribute(pseudoAttr);
2189}
2190
2191void Element::setPseudo(const AtomicString& value)
2192{
2193 setAttribute(pseudoAttr, value);
2194}
2195
Torne (Richard Coles)f5e4ad52013-08-05 13:57:57 +01002196const AtomicString& Element::part() const
2197{
2198 return getAttribute(partAttr);
2199}
2200
2201void Element::setPart(const AtomicString& value)
2202{
2203 setAttribute(partAttr, value);
2204}
2205
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002206LayoutSize Element::minimumSizeForResizing() const
2207{
2208 return hasRareData() ? elementRareData()->minimumSizeForResizing() : defaultMinimumSizeForResizing();
2209}
2210
2211void Element::setMinimumSizeForResizing(const LayoutSize& size)
2212{
2213 if (!hasRareData() && size == defaultMinimumSizeForResizing())
2214 return;
2215 ensureElementRareData()->setMinimumSizeForResizing(size);
2216}
2217
2218RenderStyle* Element::computedStyle(PseudoId pseudoElementSpecifier)
2219{
2220 if (PseudoElement* element = pseudoElement(pseudoElementSpecifier))
2221 return element->computedStyle();
2222
2223 // FIXME: Find and use the renderer from the pseudo element instead of the actual element so that the 'length'
2224 // properties, which are only known by the renderer because it did the layout, will be correct and so that the
2225 // values returned for the ":selection" pseudo-element will be correct.
2226 if (RenderStyle* usedStyle = renderStyle()) {
2227 if (pseudoElementSpecifier) {
2228 RenderStyle* cachedPseudoStyle = usedStyle->getCachedPseudoStyle(pseudoElementSpecifier);
2229 return cachedPseudoStyle ? cachedPseudoStyle : usedStyle;
2230 } else
2231 return usedStyle;
2232 }
2233
2234 if (!attached())
2235 // FIXME: Try to do better than this. Ensure that styleForElement() works for elements that are not in the
2236 // document tree and figure out when to destroy the computed style for such elements.
2237 return 0;
2238
2239 ElementRareData* data = ensureElementRareData();
2240 if (!data->computedStyle())
2241 data->setComputedStyle(document()->styleForElementIgnoringPendingStylesheets(this));
2242 return pseudoElementSpecifier ? data->computedStyle()->getCachedPseudoStyle(pseudoElementSpecifier) : data->computedStyle();
2243}
2244
2245void Element::setStyleAffectedByEmpty()
2246{
2247 ensureElementRareData()->setStyleAffectedByEmpty(true);
2248}
2249
2250void Element::setChildrenAffectedByHover(bool value)
2251{
2252 if (value || hasRareData())
2253 ensureElementRareData()->setChildrenAffectedByHover(value);
2254}
2255
2256void Element::setChildrenAffectedByActive(bool value)
2257{
2258 if (value || hasRareData())
2259 ensureElementRareData()->setChildrenAffectedByActive(value);
2260}
2261
2262void Element::setChildrenAffectedByDrag(bool value)
2263{
2264 if (value || hasRareData())
2265 ensureElementRareData()->setChildrenAffectedByDrag(value);
2266}
2267
2268void Element::setChildrenAffectedByFirstChildRules()
2269{
2270 ensureElementRareData()->setChildrenAffectedByFirstChildRules(true);
2271}
2272
2273void Element::setChildrenAffectedByLastChildRules()
2274{
2275 ensureElementRareData()->setChildrenAffectedByLastChildRules(true);
2276}
2277
2278void Element::setChildrenAffectedByDirectAdjacentRules()
2279{
2280 ensureElementRareData()->setChildrenAffectedByDirectAdjacentRules(true);
2281}
2282
2283void Element::setChildrenAffectedByForwardPositionalRules()
2284{
2285 ensureElementRareData()->setChildrenAffectedByForwardPositionalRules(true);
2286}
2287
2288void Element::setChildrenAffectedByBackwardPositionalRules()
2289{
2290 ensureElementRareData()->setChildrenAffectedByBackwardPositionalRules(true);
2291}
2292
2293void Element::setChildIndex(unsigned index)
2294{
2295 ElementRareData* rareData = ensureElementRareData();
2296 if (RenderStyle* style = renderStyle())
2297 style->setUnique();
2298 rareData->setChildIndex(index);
2299}
2300
2301bool Element::hasFlagsSetDuringStylingOfChildren() const
2302{
2303 if (!hasRareData())
2304 return false;
2305 return rareDataChildrenAffectedByHover()
2306 || rareDataChildrenAffectedByActive()
2307 || rareDataChildrenAffectedByDrag()
2308 || rareDataChildrenAffectedByFirstChildRules()
2309 || rareDataChildrenAffectedByLastChildRules()
2310 || rareDataChildrenAffectedByDirectAdjacentRules()
2311 || rareDataChildrenAffectedByForwardPositionalRules()
2312 || rareDataChildrenAffectedByBackwardPositionalRules();
2313}
2314
2315bool Element::rareDataStyleAffectedByEmpty() const
2316{
2317 ASSERT(hasRareData());
2318 return elementRareData()->styleAffectedByEmpty();
2319}
2320
2321bool Element::rareDataChildrenAffectedByHover() const
2322{
2323 ASSERT(hasRareData());
2324 return elementRareData()->childrenAffectedByHover();
2325}
2326
2327bool Element::rareDataChildrenAffectedByActive() const
2328{
2329 ASSERT(hasRareData());
2330 return elementRareData()->childrenAffectedByActive();
2331}
2332
2333bool Element::rareDataChildrenAffectedByDrag() const
2334{
2335 ASSERT(hasRareData());
2336 return elementRareData()->childrenAffectedByDrag();
2337}
2338
2339bool Element::rareDataChildrenAffectedByFirstChildRules() const
2340{
2341 ASSERT(hasRareData());
2342 return elementRareData()->childrenAffectedByFirstChildRules();
2343}
2344
2345bool Element::rareDataChildrenAffectedByLastChildRules() const
2346{
2347 ASSERT(hasRareData());
2348 return elementRareData()->childrenAffectedByLastChildRules();
2349}
2350
2351bool Element::rareDataChildrenAffectedByDirectAdjacentRules() const
2352{
2353 ASSERT(hasRareData());
2354 return elementRareData()->childrenAffectedByDirectAdjacentRules();
2355}
2356
2357bool Element::rareDataChildrenAffectedByForwardPositionalRules() const
2358{
2359 ASSERT(hasRareData());
2360 return elementRareData()->childrenAffectedByForwardPositionalRules();
2361}
2362
2363bool Element::rareDataChildrenAffectedByBackwardPositionalRules() const
2364{
2365 ASSERT(hasRareData());
2366 return elementRareData()->childrenAffectedByBackwardPositionalRules();
2367}
2368
2369unsigned Element::rareDataChildIndex() const
2370{
2371 ASSERT(hasRareData());
2372 return elementRareData()->childIndex();
2373}
2374
2375void Element::setIsInCanvasSubtree(bool isInCanvasSubtree)
2376{
2377 ensureElementRareData()->setIsInCanvasSubtree(isInCanvasSubtree);
2378}
2379
2380bool Element::isInCanvasSubtree() const
2381{
2382 return hasRareData() && elementRareData()->isInCanvasSubtree();
2383}
2384
Ben Murdoch591b9582013-07-10 11:41:44 +01002385void Element::setIsInsideRegion(bool value)
2386{
2387 if (value == isInsideRegion())
2388 return;
2389
2390 ensureElementRareData()->setIsInsideRegion(value);
2391}
2392
2393bool Element::isInsideRegion() const
2394{
2395 return hasRareData() ? elementRareData()->isInsideRegion() : false;
2396}
2397
2398void Element::setRegionOversetState(RegionOversetState state)
2399{
2400 ensureElementRareData()->setRegionOversetState(state);
2401}
2402
2403RegionOversetState Element::regionOversetState() const
2404{
2405 return hasRareData() ? elementRareData()->regionOversetState() : RegionUndefined;
2406}
2407
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002408AtomicString Element::computeInheritedLanguage() const
2409{
2410 const Node* n = this;
2411 AtomicString value;
2412 // The language property is inherited, so we iterate over the parents to find the first language.
2413 do {
2414 if (n->isElementNode()) {
2415 if (const ElementData* elementData = toElement(n)->elementData()) {
2416 // Spec: xml:lang takes precedence -- http://www.w3.org/TR/xhtml1/#C_7
2417 if (const Attribute* attribute = elementData->getAttributeItem(XMLNames::langAttr))
2418 value = attribute->value();
2419 else if (const Attribute* attribute = elementData->getAttributeItem(HTMLNames::langAttr))
2420 value = attribute->value();
2421 }
2422 } else if (n->isDocumentNode()) {
2423 // checking the MIME content-language
2424 value = toDocument(n)->contentLanguage();
2425 }
2426
2427 n = n->parentNode();
2428 } while (n && value.isNull());
2429
2430 return value;
2431}
2432
2433Locale& Element::locale() const
2434{
2435 return document()->getCachedLocale(computeInheritedLanguage());
2436}
2437
2438void Element::cancelFocusAppearanceUpdate()
2439{
2440 if (hasRareData())
2441 elementRareData()->setNeedsFocusAppearanceUpdateSoonAfterAttach(false);
Ben Murdoch7757ec22013-07-23 11:17:36 +01002442 if (document()->focusedElement() == this)
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002443 document()->cancelFocusAppearanceUpdate();
2444}
2445
2446void Element::normalizeAttributes()
2447{
2448 if (!hasAttributes())
2449 return;
2450 for (unsigned i = 0; i < attributeCount(); ++i) {
2451 if (RefPtr<Attr> attr = attrIfExists(attributeItem(i)->name()))
2452 attr->normalize();
2453 }
2454}
2455
2456void Element::updatePseudoElement(PseudoId pseudoId, StyleChange change)
2457{
2458 PseudoElement* element = pseudoElement(pseudoId);
2459 if (element && (needsStyleRecalc() || shouldRecalcStyle(change, element))) {
2460 // PseudoElement styles hang off their parent element's style so if we needed
2461 // a style recalc we should Force one on the pseudo.
2462 element->recalcStyle(needsStyleRecalc() ? Force : change);
2463
2464 // Wait until our parent is not displayed or pseudoElementRendererIsNeeded
2465 // is false, otherwise we could continously create and destroy PseudoElements
2466 // when RenderObject::isChildAllowed on our parent returns false for the
2467 // PseudoElement's renderer for each style recalc.
2468 if (!renderer() || !pseudoElementRendererIsNeeded(renderer()->getCachedPseudoStyle(pseudoId)))
Torne (Richard Coles)521d96e2013-06-19 11:58:24 +01002469 elementRareData()->setPseudoElement(pseudoId, 0);
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002470 } else if (change >= Inherit || needsStyleRecalc())
2471 createPseudoElementIfNeeded(pseudoId);
2472}
2473
2474void Element::createPseudoElementIfNeeded(PseudoId pseudoId)
2475{
Ben Murdoche69819b2013-07-17 14:56:49 +01002476 if ((pseudoId == BEFORE || pseudoId == AFTER) && !document()->styleSheetCollection()->usesBeforeAfterRules())
2477 return;
2478
2479 if (pseudoId == BACKDROP && !isInTopLayer())
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002480 return;
2481
2482 if (!renderer() || !pseudoElementRendererIsNeeded(renderer()->getCachedPseudoStyle(pseudoId)))
2483 return;
2484
2485 if (!renderer()->canHaveGeneratedChildren())
2486 return;
2487
2488 ASSERT(!isPseudoElement());
2489 RefPtr<PseudoElement> element = PseudoElement::create(this, pseudoId);
Ben Murdoche69819b2013-07-17 14:56:49 +01002490 if (pseudoId == BACKDROP)
2491 document()->addToTopLayer(element.get(), this);
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002492 element->attach();
Ben Murdoche69819b2013-07-17 14:56:49 +01002493
Torne (Richard Coles)521d96e2013-06-19 11:58:24 +01002494 ensureElementRareData()->setPseudoElement(pseudoId, element.release());
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002495}
2496
2497PseudoElement* Element::pseudoElement(PseudoId pseudoId) const
2498{
2499 return hasRareData() ? elementRareData()->pseudoElement(pseudoId) : 0;
2500}
2501
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002502RenderObject* Element::pseudoElementRenderer(PseudoId pseudoId) const
2503{
2504 if (PseudoElement* element = pseudoElement(pseudoId))
2505 return element->renderer();
2506 return 0;
2507}
2508
Ben Murdochdf957042013-08-06 11:01:27 +01002509bool Element::webkitMatchesSelector(const String& selector, ExceptionState& es)
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002510{
2511 if (selector.isEmpty()) {
Ben Murdochdf957042013-08-06 11:01:27 +01002512 es.throwDOMException(SyntaxError);
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002513 return false;
2514 }
2515
Ben Murdochdf957042013-08-06 11:01:27 +01002516 SelectorQuery* selectorQuery = document()->selectorQueryCache()->add(selector, document(), es);
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002517 if (!selectorQuery)
2518 return false;
2519 return selectorQuery->matches(this);
2520}
2521
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002522DOMTokenList* Element::classList()
2523{
2524 ElementRareData* data = ensureElementRareData();
2525 if (!data->classList())
2526 data->setClassList(ClassList::create(this));
2527 return data->classList();
2528}
2529
2530DOMStringMap* Element::dataset()
2531{
2532 ElementRareData* data = ensureElementRareData();
2533 if (!data->dataset())
2534 data->setDataset(DatasetDOMStringMap::create(this));
2535 return data->dataset();
2536}
2537
2538KURL Element::getURLAttribute(const QualifiedName& name) const
2539{
2540#if !ASSERT_DISABLED
2541 if (elementData()) {
2542 if (const Attribute* attribute = getAttributeItem(name))
2543 ASSERT(isURLAttribute(*attribute));
2544 }
2545#endif
2546 return document()->completeURL(stripLeadingAndTrailingHTMLSpaces(getAttribute(name)));
2547}
2548
2549KURL Element::getNonEmptyURLAttribute(const QualifiedName& name) const
2550{
2551#if !ASSERT_DISABLED
2552 if (elementData()) {
2553 if (const Attribute* attribute = getAttributeItem(name))
2554 ASSERT(isURLAttribute(*attribute));
2555 }
2556#endif
2557 String value = stripLeadingAndTrailingHTMLSpaces(getAttribute(name));
2558 if (value.isEmpty())
2559 return KURL();
2560 return document()->completeURL(value);
2561}
2562
2563int Element::getIntegralAttribute(const QualifiedName& attributeName) const
2564{
2565 return getAttribute(attributeName).string().toInt();
2566}
2567
2568void Element::setIntegralAttribute(const QualifiedName& attributeName, int value)
2569{
2570 // FIXME: Need an AtomicString version of String::number.
2571 setAttribute(attributeName, String::number(value));
2572}
2573
2574unsigned Element::getUnsignedIntegralAttribute(const QualifiedName& attributeName) const
2575{
2576 return getAttribute(attributeName).string().toUInt();
2577}
2578
2579void Element::setUnsignedIntegralAttribute(const QualifiedName& attributeName, unsigned value)
2580{
2581 // FIXME: Need an AtomicString version of String::number.
2582 setAttribute(attributeName, String::number(value));
2583}
2584
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002585bool Element::childShouldCreateRenderer(const NodeRenderingContext& childContext) const
2586{
2587 // Only create renderers for SVG elements whose parents are SVG elements, or for proper <svg xmlns="svgNS"> subdocuments.
2588 if (childContext.node()->isSVGElement())
2589 return childContext.node()->hasTagName(SVGNames::svgTag) || isSVGElement();
2590
2591 return ContainerNode::childShouldCreateRenderer(childContext);
2592}
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002593
2594void Element::webkitRequestFullscreen()
2595{
Torne (Richard Coles)f5e4ad52013-08-05 13:57:57 +01002596 FullscreenElementStack::from(document())->requestFullScreenForElement(this, ALLOW_KEYBOARD_INPUT, FullscreenElementStack::EnforceIFrameAllowFullScreenRequirement);
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002597}
2598
2599void Element::webkitRequestFullScreen(unsigned short flags)
2600{
Torne (Richard Coles)f5e4ad52013-08-05 13:57:57 +01002601 FullscreenElementStack::from(document())->requestFullScreenForElement(this, (flags | LEGACY_MOZILLA_REQUEST), FullscreenElementStack::EnforceIFrameAllowFullScreenRequirement);
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002602}
2603
2604bool Element::containsFullScreenElement() const
2605{
2606 return hasRareData() && elementRareData()->containsFullScreenElement();
2607}
2608
2609void Element::setContainsFullScreenElement(bool flag)
2610{
2611 ensureElementRareData()->setContainsFullScreenElement(flag);
Ben Murdoche69819b2013-07-17 14:56:49 +01002612 setNeedsStyleRecalc(SubtreeStyleChange);
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002613}
2614
2615static Element* parentCrossingFrameBoundaries(Element* element)
2616{
2617 ASSERT(element);
2618 return element->parentElement() ? element->parentElement() : element->document()->ownerElement();
2619}
2620
2621void Element::setContainsFullScreenElementOnAncestorsCrossingFrameBoundaries(bool flag)
2622{
2623 Element* element = this;
2624 while ((element = parentCrossingFrameBoundaries(element)))
2625 element->setContainsFullScreenElement(flag);
2626}
2627
2628bool Element::isInTopLayer() const
2629{
2630 return hasRareData() && elementRareData()->isInTopLayer();
2631}
2632
2633void Element::setIsInTopLayer(bool inTopLayer)
2634{
2635 if (isInTopLayer() == inTopLayer)
2636 return;
2637 ensureElementRareData()->setIsInTopLayer(inTopLayer);
2638
2639 // We must ensure a reattach occurs so the renderer is inserted in the correct sibling order under RenderView according to its
2640 // top layer position, or in its usual place if not in the top layer.
Torne (Richard Coles)93ac45c2013-05-29 14:40:20 +01002641 lazyReattachIfAttached();
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002642}
2643
2644void Element::webkitRequestPointerLock()
2645{
2646 if (document()->page())
2647 document()->page()->pointerLockController()->requestPointerLock(this);
2648}
2649
2650SpellcheckAttributeState Element::spellcheckAttributeState() const
2651{
2652 const AtomicString& value = getAttribute(HTMLNames::spellcheckAttr);
2653 if (value == nullAtom)
2654 return SpellcheckAttributeDefault;
2655 if (equalIgnoringCase(value, "true") || equalIgnoringCase(value, ""))
2656 return SpellcheckAttributeTrue;
2657 if (equalIgnoringCase(value, "false"))
2658 return SpellcheckAttributeFalse;
2659
2660 return SpellcheckAttributeDefault;
2661}
2662
2663bool Element::isSpellCheckingEnabled() const
2664{
2665 for (const Element* element = this; element; element = element->parentOrShadowHostElement()) {
2666 switch (element->spellcheckAttributeState()) {
2667 case SpellcheckAttributeTrue:
2668 return true;
2669 case SpellcheckAttributeFalse:
2670 return false;
2671 case SpellcheckAttributeDefault:
2672 break;
2673 }
2674 }
2675
2676 return true;
2677}
2678
2679RenderRegion* Element::renderRegion() const
2680{
2681 if (renderer() && renderer()->isRenderRegion())
2682 return toRenderRegion(renderer());
2683
2684 return 0;
2685}
2686
Ben Murdoch591b9582013-07-10 11:41:44 +01002687bool Element::shouldMoveToFlowThread(RenderStyle* styleToUse) const
2688{
2689 ASSERT(styleToUse);
2690
Torne (Richard Coles)f5e4ad52013-08-05 13:57:57 +01002691 if (FullscreenElementStack::isActiveFullScreenElement(this))
Ben Murdoch591b9582013-07-10 11:41:44 +01002692 return false;
2693
2694 if (isInShadowTree())
2695 return false;
2696
2697 if (styleToUse->flowThread().isEmpty())
2698 return false;
2699
2700 return !isRegisteredWithNamedFlow();
2701}
2702
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002703const AtomicString& Element::webkitRegionOverset() const
2704{
2705 document()->updateLayoutIgnorePendingStylesheets();
2706
2707 DEFINE_STATIC_LOCAL(AtomicString, undefinedState, ("undefined", AtomicString::ConstructFromLiteral));
2708 if (!RuntimeEnabledFeatures::cssRegionsEnabled() || !renderRegion())
2709 return undefinedState;
2710
Ben Murdoch591b9582013-07-10 11:41:44 +01002711 switch (renderRegion()->regionOversetState()) {
2712 case RegionFit: {
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002713 DEFINE_STATIC_LOCAL(AtomicString, fitState, ("fit", AtomicString::ConstructFromLiteral));
2714 return fitState;
2715 }
Ben Murdoch591b9582013-07-10 11:41:44 +01002716 case RegionEmpty: {
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002717 DEFINE_STATIC_LOCAL(AtomicString, emptyState, ("empty", AtomicString::ConstructFromLiteral));
2718 return emptyState;
2719 }
Ben Murdoch591b9582013-07-10 11:41:44 +01002720 case RegionOverset: {
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002721 DEFINE_STATIC_LOCAL(AtomicString, overflowState, ("overset", AtomicString::ConstructFromLiteral));
2722 return overflowState;
2723 }
Ben Murdoch591b9582013-07-10 11:41:44 +01002724 case RegionUndefined:
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002725 return undefinedState;
2726 }
2727
2728 ASSERT_NOT_REACHED();
2729 return undefinedState;
2730}
2731
2732Vector<RefPtr<Range> > Element::webkitGetRegionFlowRanges() const
2733{
2734 document()->updateLayoutIgnorePendingStylesheets();
2735
2736 Vector<RefPtr<Range> > rangeObjects;
2737 if (RuntimeEnabledFeatures::cssRegionsEnabled() && renderer() && renderer()->isRenderRegion()) {
2738 RenderRegion* region = toRenderRegion(renderer());
2739 if (region->isValid())
2740 region->getRanges(rangeObjects);
2741 }
2742
2743 return rangeObjects;
2744}
2745
2746#ifndef NDEBUG
2747bool Element::fastAttributeLookupAllowed(const QualifiedName& name) const
2748{
2749 if (name == HTMLNames::styleAttr)
2750 return false;
2751
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002752 if (isSVGElement())
2753 return !static_cast<const SVGElement*>(this)->isAnimatableAttribute(name);
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002754
2755 return true;
2756}
2757#endif
2758
2759#ifdef DUMP_NODE_STATISTICS
2760bool Element::hasNamedNodeMap() const
2761{
2762 return hasRareData() && elementRareData()->attributeMap();
2763}
2764#endif
2765
2766inline void Element::updateName(const AtomicString& oldName, const AtomicString& newName)
2767{
Ben Murdochdf957042013-08-06 11:01:27 +01002768 if (!inDocument() || isInShadowTree())
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002769 return;
2770
2771 if (oldName == newName)
2772 return;
2773
Ben Murdochdf957042013-08-06 11:01:27 +01002774 if (shouldRegisterAsNamedItem())
2775 updateNamedItemRegistration(oldName, newName);
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002776}
2777
Ben Murdochdf957042013-08-06 11:01:27 +01002778inline void Element::updateId(const AtomicString& oldId, const AtomicString& newId)
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002779{
2780 if (!isInTreeScope())
2781 return;
2782
2783 if (oldId == newId)
2784 return;
2785
2786 updateId(treeScope(), oldId, newId);
2787}
2788
2789inline void Element::updateId(TreeScope* scope, const AtomicString& oldId, const AtomicString& newId)
2790{
2791 ASSERT(isInTreeScope());
2792 ASSERT(oldId != newId);
2793
2794 if (!oldId.isEmpty())
2795 scope->removeElementById(oldId, this);
2796 if (!newId.isEmpty())
2797 scope->addElementById(newId, this);
2798
Ben Murdochdf957042013-08-06 11:01:27 +01002799 if (shouldRegisterAsExtraNamedItem())
2800 updateExtraNamedItemRegistration(oldId, newId);
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002801}
2802
2803void Element::updateLabel(TreeScope* scope, const AtomicString& oldForAttributeValue, const AtomicString& newForAttributeValue)
2804{
2805 ASSERT(hasTagName(labelTag));
2806
2807 if (!inDocument())
2808 return;
2809
2810 if (oldForAttributeValue == newForAttributeValue)
2811 return;
2812
2813 if (!oldForAttributeValue.isEmpty())
Ben Murdoche69819b2013-07-17 14:56:49 +01002814 scope->removeLabel(oldForAttributeValue, toHTMLLabelElement(this));
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002815 if (!newForAttributeValue.isEmpty())
Ben Murdoche69819b2013-07-17 14:56:49 +01002816 scope->addLabel(newForAttributeValue, toHTMLLabelElement(this));
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002817}
2818
Ben Murdoch7757ec22013-07-23 11:17:36 +01002819static bool hasSelectorForAttribute(Document* document, const AtomicString& localName)
2820{
2821 return document->styleResolver() && document->styleResolver()->ruleFeatureSet().hasSelectorForAttribute(localName);
2822}
2823
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002824void Element::willModifyAttribute(const QualifiedName& name, const AtomicString& oldValue, const AtomicString& newValue)
2825{
2826 if (isIdAttributeName(name))
2827 updateId(oldValue, newValue);
2828 else if (name == HTMLNames::nameAttr)
2829 updateName(oldValue, newValue);
2830 else if (name == HTMLNames::forAttr && hasTagName(labelTag)) {
2831 TreeScope* scope = treeScope();
2832 if (scope->shouldCacheLabelsByForAttribute())
2833 updateLabel(scope, oldValue, newValue);
2834 }
2835
2836 if (oldValue != newValue) {
Ben Murdoch7757ec22013-07-23 11:17:36 +01002837 if (attached() && hasSelectorForAttribute(document(), name.localName()))
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002838 setNeedsStyleRecalc();
Ben Murdoche69819b2013-07-17 14:56:49 +01002839
2840 if (isUpgradedCustomElement())
Ben Murdoch83750172013-07-24 10:36:59 +01002841 CustomElement::attributeDidChange(this, name.localName(), oldValue, newValue);
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002842 }
2843
2844 if (OwnPtr<MutationObserverInterestGroup> recipients = MutationObserverInterestGroup::createForAttributesMutation(this, name))
2845 recipients->enqueueMutationRecord(MutationRecord::createAttributes(this, name, oldValue));
2846
2847 InspectorInstrumentation::willModifyDOMAttr(document(), this, oldValue, newValue);
2848}
2849
2850void Element::didAddAttribute(const QualifiedName& name, const AtomicString& value)
2851{
2852 attributeChanged(name, value);
2853 InspectorInstrumentation::didModifyDOMAttr(document(), this, name.localName(), value);
2854 dispatchSubtreeModifiedEvent();
2855}
2856
2857void Element::didModifyAttribute(const QualifiedName& name, const AtomicString& value)
2858{
2859 attributeChanged(name, value);
2860 InspectorInstrumentation::didModifyDOMAttr(document(), this, name.localName(), value);
2861 // Do not dispatch a DOMSubtreeModified event here; see bug 81141.
2862}
2863
2864void Element::didRemoveAttribute(const QualifiedName& name)
2865{
2866 attributeChanged(name, nullAtom);
2867 InspectorInstrumentation::didRemoveDOMAttr(document(), this, name.localName());
2868 dispatchSubtreeModifiedEvent();
2869}
2870
Ben Murdoche69819b2013-07-17 14:56:49 +01002871void Element::didMoveToNewDocument(Document* oldDocument)
2872{
2873 Node::didMoveToNewDocument(oldDocument);
2874
2875 // If the documents differ by quirks mode then they differ by case sensitivity
2876 // for class and id names so we need to go through the attribute change logic
2877 // to pick up the new casing in the ElementData.
2878 if (oldDocument->inQuirksMode() != document()->inQuirksMode()) {
2879 if (hasID())
2880 setIdAttribute(getIdAttribute());
2881 if (hasClass())
2882 setAttribute(HTMLNames::classAttr, getClassAttribute());
2883 }
2884}
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002885
Ben Murdochdf957042013-08-06 11:01:27 +01002886void Element::updateNamedItemRegistration(const AtomicString& oldName, const AtomicString& newName)
2887{
2888 if (!document()->isHTMLDocument())
2889 return;
2890
2891 if (!oldName.isEmpty())
2892 toHTMLDocument(document())->removeNamedItem(oldName);
2893
2894 if (!newName.isEmpty())
2895 toHTMLDocument(document())->addNamedItem(newName);
2896}
2897
2898void Element::updateExtraNamedItemRegistration(const AtomicString& oldId, const AtomicString& newId)
2899{
2900 if (!document()->isHTMLDocument())
2901 return;
2902
2903 if (!oldId.isEmpty())
2904 toHTMLDocument(document())->removeExtraNamedItem(oldId);
2905
2906 if (!newId.isEmpty())
2907 toHTMLDocument(document())->addExtraNamedItem(newId);
2908}
2909
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002910PassRefPtr<HTMLCollection> Element::ensureCachedHTMLCollection(CollectionType type)
2911{
2912 if (HTMLCollection* collection = cachedHTMLCollection(type))
2913 return collection;
2914
2915 RefPtr<HTMLCollection> collection;
2916 if (type == TableRows) {
2917 ASSERT(hasTagName(tableTag));
2918 return ensureRareData()->ensureNodeLists()->addCacheWithAtomicName<HTMLTableRowsCollection>(this, type);
2919 } else if (type == SelectOptions) {
2920 ASSERT(hasTagName(selectTag));
2921 return ensureRareData()->ensureNodeLists()->addCacheWithAtomicName<HTMLOptionsCollection>(this, type);
2922 } else if (type == FormControls) {
2923 ASSERT(hasTagName(formTag) || hasTagName(fieldsetTag));
2924 return ensureRareData()->ensureNodeLists()->addCacheWithAtomicName<HTMLFormControlsCollection>(this, type);
2925 }
2926 return ensureRareData()->ensureNodeLists()->addCacheWithAtomicName<HTMLCollection>(this, type);
2927}
2928
Ben Murdoch591b9582013-07-10 11:41:44 +01002929static void scheduleLayerUpdateCallback(Node* node)
Torne (Richard Coles)93ac45c2013-05-29 14:40:20 +01002930{
Ben Murdoche69819b2013-07-17 14:56:49 +01002931 // Notify the renderer even is the styles are identical since it may need to
2932 // create or destroy a RenderLayer.
2933 node->setNeedsStyleRecalc(LocalStyleChange, StyleChangeFromRenderer);
Torne (Richard Coles)93ac45c2013-05-29 14:40:20 +01002934}
2935
Ben Murdoch591b9582013-07-10 11:41:44 +01002936void Element::scheduleLayerUpdate()
Torne (Richard Coles)93ac45c2013-05-29 14:40:20 +01002937{
2938 if (postAttachCallbacksAreSuspended())
Ben Murdoch591b9582013-07-10 11:41:44 +01002939 queuePostAttachCallback(scheduleLayerUpdateCallback, this);
Torne (Richard Coles)93ac45c2013-05-29 14:40:20 +01002940 else
Ben Murdoche69819b2013-07-17 14:56:49 +01002941 scheduleLayerUpdateCallback(this);
Torne (Richard Coles)93ac45c2013-05-29 14:40:20 +01002942}
2943
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002944HTMLCollection* Element::cachedHTMLCollection(CollectionType type)
2945{
2946 return hasRareData() && rareData()->nodeLists() ? rareData()->nodeLists()->cacheWithAtomicName<HTMLCollection>(type) : 0;
2947}
2948
2949IntSize Element::savedLayerScrollOffset() const
2950{
2951 return hasRareData() ? elementRareData()->savedLayerScrollOffset() : IntSize();
2952}
2953
2954void Element::setSavedLayerScrollOffset(const IntSize& size)
2955{
2956 if (size.isZero() && !hasRareData())
2957 return;
2958 ensureElementRareData()->setSavedLayerScrollOffset(size);
2959}
2960
2961PassRefPtr<Attr> Element::attrIfExists(const QualifiedName& name)
2962{
2963 if (AttrNodeList* attrNodeList = attrNodeListForElement(this))
2964 return findAttrNodeInList(attrNodeList, name);
2965 return 0;
2966}
2967
2968PassRefPtr<Attr> Element::ensureAttr(const QualifiedName& name)
2969{
2970 AttrNodeList* attrNodeList = ensureAttrNodeListForElement(this);
2971 RefPtr<Attr> attrNode = findAttrNodeInList(attrNodeList, name);
2972 if (!attrNode) {
2973 attrNode = Attr::create(this, name);
2974 treeScope()->adoptIfNeeded(attrNode.get());
2975 attrNodeList->append(attrNode);
2976 }
2977 return attrNode.release();
2978}
2979
2980void Element::detachAttrNodeFromElementWithValue(Attr* attrNode, const AtomicString& value)
2981{
2982 ASSERT(hasSyntheticAttrChildNodes());
2983 attrNode->detachFromElementWithValue(value);
2984
2985 AttrNodeList* attrNodeList = attrNodeListForElement(this);
2986 for (unsigned i = 0; i < attrNodeList->size(); ++i) {
2987 if (attrNodeList->at(i)->qualifiedName() == attrNode->qualifiedName()) {
2988 attrNodeList->remove(i);
2989 if (attrNodeList->isEmpty())
2990 removeAttrNodeListForElement(this);
2991 return;
2992 }
2993 }
2994 ASSERT_NOT_REACHED();
2995}
2996
2997void Element::detachAllAttrNodesFromElement()
2998{
2999 AttrNodeList* attrNodeList = attrNodeListForElement(this);
3000 ASSERT(attrNodeList);
3001
3002 for (unsigned i = 0; i < attributeCount(); ++i) {
3003 const Attribute* attribute = attributeItem(i);
3004 if (RefPtr<Attr> attrNode = findAttrNodeInList(attrNodeList, attribute->name()))
3005 attrNode->detachFromElementWithValue(attribute->value());
3006 }
3007
3008 removeAttrNodeListForElement(this);
3009}
3010
3011void Element::willRecalcStyle(StyleChange)
3012{
3013 ASSERT(hasCustomStyleCallbacks());
3014}
3015
3016void Element::didRecalcStyle(StyleChange)
3017{
3018 ASSERT(hasCustomStyleCallbacks());
3019}
3020
3021
3022PassRefPtr<RenderStyle> Element::customStyleForRenderer()
3023{
3024 ASSERT(hasCustomStyleCallbacks());
3025 return 0;
3026}
3027
3028void Element::cloneAttributesFromElement(const Element& other)
3029{
3030 if (hasSyntheticAttrChildNodes())
3031 detachAllAttrNodesFromElement();
3032
3033 other.synchronizeAllAttributes();
3034 if (!other.m_elementData) {
3035 m_elementData.clear();
3036 return;
3037 }
3038
3039 const AtomicString& oldID = getIdAttribute();
3040 const AtomicString& newID = other.getIdAttribute();
3041
3042 if (!oldID.isNull() || !newID.isNull())
3043 updateId(oldID, newID);
3044
3045 const AtomicString& oldName = getNameAttribute();
3046 const AtomicString& newName = other.getNameAttribute();
3047
3048 if (!oldName.isNull() || !newName.isNull())
3049 updateName(oldName, newName);
3050
Ben Murdoche69819b2013-07-17 14:56:49 +01003051 // Quirks mode makes class and id not case sensitive. We can't share the ElementData
3052 // if the idForStyleResolution and the className need different casing.
3053 bool ownerDocumentsHaveDifferentCaseSensitivity = false;
3054 if (other.hasClass() || other.hasID())
3055 ownerDocumentsHaveDifferentCaseSensitivity = other.document()->inQuirksMode() != document()->inQuirksMode();
3056
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01003057 // If 'other' has a mutable ElementData, convert it to an immutable one so we can share it between both elements.
Ben Murdoche69819b2013-07-17 14:56:49 +01003058 // We can only do this if there is no CSSOM wrapper for other's inline style, and there are no presentation attributes,
3059 // and sharing the data won't result in different case sensitivity of class or id.
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01003060 if (other.m_elementData->isUnique()
Ben Murdoche69819b2013-07-17 14:56:49 +01003061 && !ownerDocumentsHaveDifferentCaseSensitivity
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01003062 && !other.m_elementData->presentationAttributeStyle()
3063 && (!other.m_elementData->inlineStyle() || !other.m_elementData->inlineStyle()->hasCSSOMWrapper()))
3064 const_cast<Element&>(other).m_elementData = static_cast<const UniqueElementData*>(other.m_elementData.get())->makeShareableCopy();
3065
Ben Murdoche69819b2013-07-17 14:56:49 +01003066 if (!other.m_elementData->isUnique() && !ownerDocumentsHaveDifferentCaseSensitivity)
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01003067 m_elementData = other.m_elementData;
3068 else
3069 m_elementData = other.m_elementData->makeUniqueCopy();
3070
3071 for (unsigned i = 0; i < m_elementData->length(); ++i) {
3072 const Attribute* attribute = const_cast<const ElementData*>(m_elementData.get())->attributeItem(i);
3073 attributeChangedFromParserOrByCloning(attribute->name(), attribute->value(), ModifiedByCloning);
3074 }
3075}
3076
3077void Element::cloneDataFromElement(const Element& other)
3078{
3079 cloneAttributesFromElement(other);
3080 copyNonAttributePropertiesFromElement(other);
3081}
3082
3083void Element::createUniqueElementData()
3084{
3085 if (!m_elementData)
3086 m_elementData = UniqueElementData::create();
3087 else {
3088 ASSERT(!m_elementData->isUnique());
3089 m_elementData = static_cast<ShareableElementData*>(m_elementData.get())->makeUniqueCopy();
3090 }
3091}
3092
Ben Murdoch1fad5ca2013-08-07 11:05:11 +01003093InputMethodContext* Element::inputMethodContext()
Torne (Richard Coles)81a51572013-05-13 16:52:28 +01003094{
3095 return ensureElementRareData()->ensureInputMethodContext(toHTMLElement(this));
3096}
3097
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01003098bool Element::hasPendingResources() const
3099{
3100 return hasRareData() && elementRareData()->hasPendingResources();
3101}
3102
3103void Element::setHasPendingResources()
3104{
3105 ensureElementRareData()->setHasPendingResources(true);
3106}
3107
3108void Element::clearHasPendingResources()
3109{
3110 ensureElementRareData()->setHasPendingResources(false);
3111}
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01003112
Ben Murdoch591b9582013-07-10 11:41:44 +01003113struct PresentationAttributeCacheKey {
3114 PresentationAttributeCacheKey() : tagName(0) { }
Ben Murdoch83750172013-07-24 10:36:59 +01003115 StringImpl* tagName;
Ben Murdoch591b9582013-07-10 11:41:44 +01003116 // Only the values need refcounting.
Ben Murdoch83750172013-07-24 10:36:59 +01003117 Vector<pair<StringImpl*, AtomicString>, 3> attributesAndValues;
Ben Murdoch591b9582013-07-10 11:41:44 +01003118};
3119
3120struct PresentationAttributeCacheEntry {
3121 WTF_MAKE_FAST_ALLOCATED;
3122public:
3123 PresentationAttributeCacheKey key;
3124 RefPtr<StylePropertySet> value;
3125};
3126
3127typedef HashMap<unsigned, OwnPtr<PresentationAttributeCacheEntry>, AlreadyHashed> PresentationAttributeCache;
3128
3129static bool operator!=(const PresentationAttributeCacheKey& a, const PresentationAttributeCacheKey& b)
3130{
3131 if (a.tagName != b.tagName)
3132 return true;
3133 return a.attributesAndValues != b.attributesAndValues;
3134}
3135
3136static PresentationAttributeCache& presentationAttributeCache()
3137{
3138 DEFINE_STATIC_LOCAL(PresentationAttributeCache, cache, ());
3139 return cache;
3140}
3141
3142class PresentationAttributeCacheCleaner {
3143 WTF_MAKE_NONCOPYABLE(PresentationAttributeCacheCleaner); WTF_MAKE_FAST_ALLOCATED;
3144public:
3145 PresentationAttributeCacheCleaner()
3146 : m_hitCount(0)
3147 , m_cleanTimer(this, &PresentationAttributeCacheCleaner::cleanCache)
3148 {
3149 }
3150
3151 void didHitPresentationAttributeCache()
3152 {
3153 if (presentationAttributeCache().size() < minimumPresentationAttributeCacheSizeForCleaning)
3154 return;
3155
3156 m_hitCount++;
3157
3158 if (!m_cleanTimer.isActive())
3159 m_cleanTimer.startOneShot(presentationAttributeCacheCleanTimeInSeconds);
3160 }
3161
3162private:
3163 static const unsigned presentationAttributeCacheCleanTimeInSeconds = 60;
3164 static const int minimumPresentationAttributeCacheSizeForCleaning = 100;
3165 static const unsigned minimumPresentationAttributeCacheHitCountPerMinute = (100 * presentationAttributeCacheCleanTimeInSeconds) / 60;
3166
3167 void cleanCache(Timer<PresentationAttributeCacheCleaner>* timer)
3168 {
3169 ASSERT_UNUSED(timer, timer == &m_cleanTimer);
3170 unsigned hitCount = m_hitCount;
3171 m_hitCount = 0;
3172 if (hitCount > minimumPresentationAttributeCacheHitCountPerMinute)
3173 return;
3174 presentationAttributeCache().clear();
3175 }
3176
3177 unsigned m_hitCount;
3178 Timer<PresentationAttributeCacheCleaner> m_cleanTimer;
3179};
3180
3181static PresentationAttributeCacheCleaner& presentationAttributeCacheCleaner()
3182{
3183 DEFINE_STATIC_LOCAL(PresentationAttributeCacheCleaner, cleaner, ());
3184 return cleaner;
3185}
3186
3187void Element::synchronizeStyleAttributeInternal() const
3188{
3189 ASSERT(isStyledElement());
3190 ASSERT(elementData());
3191 ASSERT(elementData()->m_styleAttributeIsDirty);
3192 elementData()->m_styleAttributeIsDirty = false;
3193 if (const StylePropertySet* inlineStyle = this->inlineStyle())
3194 const_cast<Element*>(this)->setSynchronizedLazyAttribute(styleAttr, inlineStyle->asText());
3195}
3196
3197CSSStyleDeclaration* Element::style()
3198{
3199 if (!isStyledElement())
3200 return 0;
3201 return ensureMutableInlineStyle()->ensureInlineCSSStyleDeclaration(this);
3202}
3203
3204MutableStylePropertySet* Element::ensureMutableInlineStyle()
3205{
3206 ASSERT(isStyledElement());
3207 RefPtr<StylePropertySet>& inlineStyle = ensureUniqueElementData()->m_inlineStyle;
3208 if (!inlineStyle)
3209 inlineStyle = MutableStylePropertySet::create(strictToCSSParserMode(isHTMLElement() && !document()->inQuirksMode()));
3210 else if (!inlineStyle->isMutable())
3211 inlineStyle = inlineStyle->mutableCopy();
3212 ASSERT(inlineStyle->isMutable());
3213 return static_cast<MutableStylePropertySet*>(inlineStyle.get());
3214}
3215
3216PropertySetCSSStyleDeclaration* Element::inlineStyleCSSOMWrapper()
3217{
3218 if (!inlineStyle() || !inlineStyle()->hasCSSOMWrapper())
3219 return 0;
3220 PropertySetCSSStyleDeclaration* cssomWrapper = ensureMutableInlineStyle()->cssStyleDeclaration();
3221 ASSERT(cssomWrapper && cssomWrapper->parentElement() == this);
3222 return cssomWrapper;
3223}
3224
3225inline void Element::setInlineStyleFromString(const AtomicString& newStyleString)
3226{
3227 ASSERT(isStyledElement());
3228 RefPtr<StylePropertySet>& inlineStyle = elementData()->m_inlineStyle;
3229
3230 // Avoid redundant work if we're using shared attribute data with already parsed inline style.
3231 if (inlineStyle && !elementData()->isUnique())
3232 return;
3233
3234 // We reconstruct the property set instead of mutating if there is no CSSOM wrapper.
3235 // This makes wrapperless property sets immutable and so cacheable.
3236 if (inlineStyle && !inlineStyle->isMutable())
3237 inlineStyle.clear();
3238
3239 if (!inlineStyle) {
3240 inlineStyle = CSSParser::parseInlineStyleDeclaration(newStyleString, this);
3241 } else {
3242 ASSERT(inlineStyle->isMutable());
3243 static_pointer_cast<MutableStylePropertySet>(inlineStyle)->parseDeclaration(newStyleString, document()->elementSheet()->contents());
3244 }
3245}
3246
3247void Element::styleAttributeChanged(const AtomicString& newStyleString, AttributeModificationReason modificationReason)
3248{
3249 ASSERT(isStyledElement());
3250 WTF::OrdinalNumber startLineNumber = WTF::OrdinalNumber::beforeFirst();
3251 if (document() && document()->scriptableDocumentParser() && !document()->isInDocumentWrite())
3252 startLineNumber = document()->scriptableDocumentParser()->lineNumber();
3253
3254 if (newStyleString.isNull()) {
3255 if (PropertySetCSSStyleDeclaration* cssomWrapper = inlineStyleCSSOMWrapper())
3256 cssomWrapper->clearParentElement();
3257 ensureUniqueElementData()->m_inlineStyle.clear();
3258 } else if (modificationReason == ModifiedByCloning || document()->contentSecurityPolicy()->allowInlineStyle(document()->url(), startLineNumber)) {
3259 setInlineStyleFromString(newStyleString);
3260 }
3261
3262 elementData()->m_styleAttributeIsDirty = false;
3263
Ben Murdoche69819b2013-07-17 14:56:49 +01003264 setNeedsStyleRecalc(LocalStyleChange);
Ben Murdoch591b9582013-07-10 11:41:44 +01003265 InspectorInstrumentation::didInvalidateStyleAttr(document(), this);
3266}
3267
3268void Element::inlineStyleChanged()
3269{
3270 ASSERT(isStyledElement());
Ben Murdoche69819b2013-07-17 14:56:49 +01003271 setNeedsStyleRecalc(LocalStyleChange);
Ben Murdoch591b9582013-07-10 11:41:44 +01003272 ASSERT(elementData());
3273 elementData()->m_styleAttributeIsDirty = true;
3274 InspectorInstrumentation::didInvalidateStyleAttr(document(), this);
3275}
3276
3277bool Element::setInlineStyleProperty(CSSPropertyID propertyID, CSSValueID identifier, bool important)
3278{
3279 ASSERT(isStyledElement());
3280 ensureMutableInlineStyle()->setProperty(propertyID, cssValuePool().createIdentifierValue(identifier), important);
3281 inlineStyleChanged();
3282 return true;
3283}
3284
3285bool Element::setInlineStyleProperty(CSSPropertyID propertyID, CSSPropertyID identifier, bool important)
3286{
3287 ASSERT(isStyledElement());
3288 ensureMutableInlineStyle()->setProperty(propertyID, cssValuePool().createIdentifierValue(identifier), important);
3289 inlineStyleChanged();
3290 return true;
3291}
3292
3293bool Element::setInlineStyleProperty(CSSPropertyID propertyID, double value, CSSPrimitiveValue::UnitTypes unit, bool important)
3294{
3295 ASSERT(isStyledElement());
3296 ensureMutableInlineStyle()->setProperty(propertyID, cssValuePool().createValue(value, unit), important);
3297 inlineStyleChanged();
3298 return true;
3299}
3300
3301bool Element::setInlineStyleProperty(CSSPropertyID propertyID, const String& value, bool important)
3302{
3303 ASSERT(isStyledElement());
3304 bool changes = ensureMutableInlineStyle()->setProperty(propertyID, value, important, document()->elementSheet()->contents());
3305 if (changes)
3306 inlineStyleChanged();
3307 return changes;
3308}
3309
3310bool Element::removeInlineStyleProperty(CSSPropertyID propertyID)
3311{
3312 ASSERT(isStyledElement());
3313 if (!inlineStyle())
3314 return false;
3315 bool changes = ensureMutableInlineStyle()->removeProperty(propertyID);
3316 if (changes)
3317 inlineStyleChanged();
3318 return changes;
3319}
3320
3321void Element::removeAllInlineStyleProperties()
3322{
3323 ASSERT(isStyledElement());
3324 if (!inlineStyle() || inlineStyle()->isEmpty())
3325 return;
3326 ensureMutableInlineStyle()->clear();
3327 inlineStyleChanged();
3328}
3329
3330void Element::addSubresourceAttributeURLs(ListHashSet<KURL>& urls) const
3331{
3332 ASSERT(isStyledElement());
3333 if (const StylePropertySet* inlineStyle = elementData() ? elementData()->inlineStyle() : 0)
3334 inlineStyle->addSubresourceStyleURLs(urls, document()->elementSheet()->contents());
3335}
3336
Ben Murdoch83750172013-07-24 10:36:59 +01003337static inline bool attributeNameSort(const pair<StringImpl*, AtomicString>& p1, const pair<StringImpl*, AtomicString>& p2)
Ben Murdoch591b9582013-07-10 11:41:44 +01003338{
3339 // Sort based on the attribute name pointers. It doesn't matter what the order is as long as it is always the same.
3340 return p1.first < p2.first;
3341}
3342
3343void Element::makePresentationAttributeCacheKey(PresentationAttributeCacheKey& result) const
3344{
3345 ASSERT(isStyledElement());
3346 // FIXME: Enable for SVG.
3347 if (namespaceURI() != xhtmlNamespaceURI)
3348 return;
3349 // Interpretation of the size attributes on <input> depends on the type attribute.
3350 if (hasTagName(inputTag))
3351 return;
3352 unsigned size = attributeCount();
3353 for (unsigned i = 0; i < size; ++i) {
3354 const Attribute* attribute = attributeItem(i);
3355 if (!isPresentationAttribute(attribute->name()))
3356 continue;
3357 if (!attribute->namespaceURI().isNull())
3358 return;
3359 // FIXME: Background URL may depend on the base URL and can't be shared. Disallow caching.
3360 if (attribute->name() == backgroundAttr)
3361 return;
3362 result.attributesAndValues.append(std::make_pair(attribute->localName().impl(), attribute->value()));
3363 }
3364 if (result.attributesAndValues.isEmpty())
3365 return;
3366 // Attribute order doesn't matter. Sort for easy equality comparison.
3367 std::sort(result.attributesAndValues.begin(), result.attributesAndValues.end(), attributeNameSort);
3368 // The cache key is non-null when the tagName is set.
3369 result.tagName = localName().impl();
3370}
3371
3372static unsigned computePresentationAttributeCacheHash(const PresentationAttributeCacheKey& key)
3373{
3374 if (!key.tagName)
3375 return 0;
3376 ASSERT(key.attributesAndValues.size());
3377 unsigned attributeHash = StringHasher::hashMemory(key.attributesAndValues.data(), key.attributesAndValues.size() * sizeof(key.attributesAndValues[0]));
3378 return WTF::pairIntHash(key.tagName->existingHash(), attributeHash);
3379}
3380
3381void Element::rebuildPresentationAttributeStyle()
3382{
3383 ASSERT(isStyledElement());
3384 PresentationAttributeCacheKey cacheKey;
3385 makePresentationAttributeCacheKey(cacheKey);
3386
3387 unsigned cacheHash = computePresentationAttributeCacheHash(cacheKey);
3388
3389 PresentationAttributeCache::iterator cacheIterator;
3390 if (cacheHash) {
3391 cacheIterator = presentationAttributeCache().add(cacheHash, nullptr).iterator;
3392 if (cacheIterator->value && cacheIterator->value->key != cacheKey)
3393 cacheHash = 0;
3394 } else {
3395 cacheIterator = presentationAttributeCache().end();
3396 }
3397
3398 RefPtr<StylePropertySet> style;
3399 if (cacheHash && cacheIterator->value) {
3400 style = cacheIterator->value->value;
3401 presentationAttributeCacheCleaner().didHitPresentationAttributeCache();
3402 } else {
3403 style = MutableStylePropertySet::create(isSVGElement() ? SVGAttributeMode : CSSQuirksMode);
3404 unsigned size = attributeCount();
3405 for (unsigned i = 0; i < size; ++i) {
3406 const Attribute* attribute = attributeItem(i);
3407 collectStyleForPresentationAttribute(attribute->name(), attribute->value(), static_cast<MutableStylePropertySet*>(style.get()));
3408 }
3409 }
3410
3411 // ShareableElementData doesn't store presentation attribute style, so make sure we have a UniqueElementData.
3412 UniqueElementData* elementData = ensureUniqueElementData();
3413
3414 elementData->m_presentationAttributeStyleIsDirty = false;
3415 elementData->m_presentationAttributeStyle = style->isEmpty() ? 0 : style;
3416
3417 if (!cacheHash || cacheIterator->value)
3418 return;
3419
3420 OwnPtr<PresentationAttributeCacheEntry> newEntry = adoptPtr(new PresentationAttributeCacheEntry);
3421 newEntry->key = cacheKey;
3422 newEntry->value = style.release();
3423
3424 static const int presentationAttributeCacheMaximumSize = 4096;
3425 if (presentationAttributeCache().size() > presentationAttributeCacheMaximumSize) {
3426 // Start building from scratch if the cache ever gets big.
3427 presentationAttributeCache().clear();
3428 presentationAttributeCache().set(cacheHash, newEntry.release());
3429 } else {
3430 cacheIterator->value = newEntry.release();
3431 }
3432}
3433
3434void Element::addPropertyToPresentationAttributeStyle(MutableStylePropertySet* style, CSSPropertyID propertyID, CSSValueID identifier)
3435{
3436 ASSERT(isStyledElement());
3437 style->setProperty(propertyID, cssValuePool().createIdentifierValue(identifier));
3438}
3439
3440void Element::addPropertyToPresentationAttributeStyle(MutableStylePropertySet* style, CSSPropertyID propertyID, double value, CSSPrimitiveValue::UnitTypes unit)
3441{
3442 ASSERT(isStyledElement());
3443 style->setProperty(propertyID, cssValuePool().createValue(value, unit));
3444}
3445
3446void Element::addPropertyToPresentationAttributeStyle(MutableStylePropertySet* style, CSSPropertyID propertyID, const String& value)
3447{
3448 ASSERT(isStyledElement());
3449 style->setProperty(propertyID, value, false, document()->elementSheet()->contents());
3450}
3451
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01003452void ElementData::deref()
3453{
3454 if (!derefBase())
3455 return;
3456
3457 if (m_isUnique)
3458 delete static_cast<UniqueElementData*>(this);
3459 else
3460 delete static_cast<ShareableElementData*>(this);
3461}
3462
3463ElementData::ElementData()
3464 : m_isUnique(true)
3465 , m_arraySize(0)
3466 , m_presentationAttributeStyleIsDirty(false)
3467 , m_styleAttributeIsDirty(false)
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01003468 , m_animatedSVGAttributesAreDirty(false)
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01003469{
3470}
3471
3472ElementData::ElementData(unsigned arraySize)
3473 : m_isUnique(false)
3474 , m_arraySize(arraySize)
3475 , m_presentationAttributeStyleIsDirty(false)
3476 , m_styleAttributeIsDirty(false)
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01003477 , m_animatedSVGAttributesAreDirty(false)
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01003478{
3479}
3480
3481struct SameSizeAsElementData : public RefCounted<SameSizeAsElementData> {
3482 unsigned bitfield;
3483 void* refPtrs[3];
3484};
3485
3486COMPILE_ASSERT(sizeof(ElementData) == sizeof(SameSizeAsElementData), element_attribute_data_should_stay_small);
3487
3488static size_t sizeForShareableElementDataWithAttributeCount(unsigned count)
3489{
3490 return sizeof(ShareableElementData) + sizeof(Attribute) * count;
3491}
3492
3493PassRefPtr<ShareableElementData> ShareableElementData::createWithAttributes(const Vector<Attribute>& attributes)
3494{
3495 void* slot = WTF::fastMalloc(sizeForShareableElementDataWithAttributeCount(attributes.size()));
3496 return adoptRef(new (slot) ShareableElementData(attributes));
3497}
3498
3499PassRefPtr<UniqueElementData> UniqueElementData::create()
3500{
3501 return adoptRef(new UniqueElementData);
3502}
3503
3504ShareableElementData::ShareableElementData(const Vector<Attribute>& attributes)
3505 : ElementData(attributes.size())
3506{
3507 for (unsigned i = 0; i < m_arraySize; ++i)
3508 new (&m_attributeArray[i]) Attribute(attributes[i]);
3509}
3510
3511ShareableElementData::~ShareableElementData()
3512{
3513 for (unsigned i = 0; i < m_arraySize; ++i)
3514 m_attributeArray[i].~Attribute();
3515}
3516
3517ShareableElementData::ShareableElementData(const UniqueElementData& other)
3518 : ElementData(other, false)
3519{
3520 ASSERT(!other.m_presentationAttributeStyle);
3521
3522 if (other.m_inlineStyle) {
3523 ASSERT(!other.m_inlineStyle->hasCSSOMWrapper());
3524 m_inlineStyle = other.m_inlineStyle->immutableCopyIfNeeded();
3525 }
3526
3527 for (unsigned i = 0; i < m_arraySize; ++i)
3528 new (&m_attributeArray[i]) Attribute(other.m_attributeVector.at(i));
3529}
3530
3531ElementData::ElementData(const ElementData& other, bool isUnique)
3532 : m_isUnique(isUnique)
3533 , m_arraySize(isUnique ? 0 : other.length())
3534 , m_presentationAttributeStyleIsDirty(other.m_presentationAttributeStyleIsDirty)
3535 , m_styleAttributeIsDirty(other.m_styleAttributeIsDirty)
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01003536 , m_animatedSVGAttributesAreDirty(other.m_animatedSVGAttributesAreDirty)
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01003537 , m_classNames(other.m_classNames)
3538 , m_idForStyleResolution(other.m_idForStyleResolution)
3539{
3540 // NOTE: The inline style is copied by the subclass copy constructor since we don't know what to do with it here.
3541}
3542
3543UniqueElementData::UniqueElementData()
3544{
3545}
3546
3547UniqueElementData::UniqueElementData(const UniqueElementData& other)
3548 : ElementData(other, true)
3549 , m_presentationAttributeStyle(other.m_presentationAttributeStyle)
3550 , m_attributeVector(other.m_attributeVector)
3551{
Torne (Richard Coles)93ac45c2013-05-29 14:40:20 +01003552 m_inlineStyle = other.m_inlineStyle ? other.m_inlineStyle->mutableCopy() : 0;
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01003553}
3554
3555UniqueElementData::UniqueElementData(const ShareableElementData& other)
3556 : ElementData(other, true)
3557{
3558 // An ShareableElementData should never have a mutable inline StylePropertySet attached.
3559 ASSERT(!other.m_inlineStyle || !other.m_inlineStyle->isMutable());
3560 m_inlineStyle = other.m_inlineStyle;
3561
3562 m_attributeVector.reserveCapacity(other.length());
3563 for (unsigned i = 0; i < other.length(); ++i)
3564 m_attributeVector.uncheckedAppend(other.m_attributeArray[i]);
3565}
3566
3567PassRefPtr<UniqueElementData> ElementData::makeUniqueCopy() const
3568{
3569 if (isUnique())
3570 return adoptRef(new UniqueElementData(static_cast<const UniqueElementData&>(*this)));
3571 return adoptRef(new UniqueElementData(static_cast<const ShareableElementData&>(*this)));
3572}
3573
3574PassRefPtr<ShareableElementData> UniqueElementData::makeShareableCopy() const
3575{
3576 void* slot = WTF::fastMalloc(sizeForShareableElementDataWithAttributeCount(m_attributeVector.size()));
3577 return adoptRef(new (slot) ShareableElementData(*this));
3578}
3579
3580void UniqueElementData::addAttribute(const QualifiedName& attributeName, const AtomicString& value)
3581{
3582 m_attributeVector.append(Attribute(attributeName, value));
3583}
3584
3585void UniqueElementData::removeAttribute(size_t index)
3586{
3587 ASSERT_WITH_SECURITY_IMPLICATION(index < length());
3588 m_attributeVector.remove(index);
3589}
3590
3591bool ElementData::isEquivalent(const ElementData* other) const
3592{
3593 if (!other)
3594 return isEmpty();
3595
3596 unsigned len = length();
3597 if (len != other->length())
3598 return false;
3599
3600 for (unsigned i = 0; i < len; i++) {
3601 const Attribute* attribute = attributeItem(i);
3602 const Attribute* otherAttr = other->getAttributeItem(attribute->name());
3603 if (!otherAttr || attribute->value() != otherAttr->value())
3604 return false;
3605 }
3606
3607 return true;
3608}
3609
Torne (Richard Coles)e5249552013-05-15 11:35:13 +01003610size_t ElementData::getAttrIndex(Attr* attr) const
3611{
3612 // This relies on the fact that Attr's QualifiedName == the Attribute's name.
3613 for (unsigned i = 0; i < length(); ++i) {
3614 if (attributeItem(i)->name() == attr->qualifiedName())
3615 return i;
3616 }
3617 return notFound;
3618}
3619
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01003620size_t ElementData::getAttributeItemIndexSlowCase(const AtomicString& name, bool shouldIgnoreAttributeCase) const
3621{
3622 // Continue to checking case-insensitively and/or full namespaced names if necessary:
3623 for (unsigned i = 0; i < length(); ++i) {
3624 const Attribute* attribute = attributeItem(i);
3625 if (!attribute->name().hasPrefix()) {
3626 if (shouldIgnoreAttributeCase && equalIgnoringCase(name, attribute->localName()))
3627 return i;
3628 } else {
3629 // FIXME: Would be faster to do this comparison without calling toString, which
3630 // generates a temporary string by concatenation. But this branch is only reached
3631 // if the attribute name has a prefix, which is rare in HTML.
3632 if (equalPossiblyIgnoringCase(name, attribute->name().toString(), shouldIgnoreAttributeCase))
3633 return i;
3634 }
3635 }
3636 return notFound;
3637}
3638
3639Attribute* UniqueElementData::getAttributeItem(const QualifiedName& name)
3640{
3641 for (unsigned i = 0; i < length(); ++i) {
3642 if (m_attributeVector.at(i).name().matches(name))
3643 return &m_attributeVector.at(i);
3644 }
3645 return 0;
3646}
3647
3648Attribute* UniqueElementData::attributeItem(unsigned index)
3649{
3650 ASSERT_WITH_SECURITY_IMPLICATION(index < length());
3651 return &m_attributeVector.at(index);
3652}
3653
3654} // namespace WebCore