blob: 0aedfeca43c66160a8b0836989d23c7891ca88c4 [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
Ben Murdoch3c9e4ae2013-08-12 14:20:44 +01001241 if (insertionPoint->treeScope() != treeScope())
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001242 return InsertionDone;
1243
Ben Murdoch3c9e4ae2013-08-12 14:20:44 +01001244 HTMLDocument* newDocument = inDocument() && !isInShadowTree() && document()->isHTMLDocument() ? toHTMLDocument(document()) : 0;
1245
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001246 const AtomicString& idValue = getIdAttribute();
Ben Murdoch3c9e4ae2013-08-12 14:20:44 +01001247 if (!idValue.isNull()) {
1248 updateIdForTreeScope(treeScope(), nullAtom, idValue);
1249 if (newDocument)
1250 updateIdForDocument(newDocument, nullAtom, idValue);
1251 }
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001252
1253 const AtomicString& nameValue = getNameAttribute();
Ben Murdoch3c9e4ae2013-08-12 14:20:44 +01001254 if (!nameValue.isNull()) {
1255 updateNameForTreeScope(treeScope(), nullAtom, nameValue);
1256 if (newDocument)
1257 updateNameForDocument(newDocument, nullAtom, nameValue);
1258 }
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001259
1260 if (hasTagName(labelTag)) {
Ben Murdoch3c9e4ae2013-08-12 14:20:44 +01001261 if (treeScope()->shouldCacheLabelsByForAttribute())
1262 updateLabel(treeScope(), nullAtom, fastGetAttribute(forAttr));
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001263 }
1264
Ben Murdoch3c9e4ae2013-08-12 14:20:44 +01001265 if (parentElement() && parentElement()->isInCanvasSubtree())
1266 setIsInCanvasSubtree(true);
1267
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001268 return InsertionDone;
1269}
1270
1271void Element::removedFrom(ContainerNode* insertionPoint)
1272{
Torne (Richard Coles)f5e4ad52013-08-05 13:57:57 +01001273 bool wasInDocument = insertionPoint->inDocument();
Ben Murdoch3c9e4ae2013-08-12 14:20:44 +01001274 bool wasInShadowTree = isInShadowTree(); // Of course, we might still be in a shadow tree...
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001275
1276 if (Element* before = pseudoElement(BEFORE))
1277 before->removedFrom(insertionPoint);
1278
1279 if (Element* after = pseudoElement(AFTER))
1280 after->removedFrom(insertionPoint);
1281
Ben Murdoche69819b2013-07-17 14:56:49 +01001282 if (Element* backdrop = pseudoElement(BACKDROP))
1283 backdrop->removedFrom(insertionPoint);
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001284 document()->removeFromTopLayer(this);
Ben Murdoche69819b2013-07-17 14:56:49 +01001285
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001286 if (containsFullScreenElement())
1287 setContainsFullScreenElementOnAncestorsCrossingFrameBoundaries(false);
1288
1289 if (document()->page())
1290 document()->page()->pointerLockController()->elementRemoved(this);
1291
1292 setSavedLayerScrollOffset(IntSize());
1293
1294 if (insertionPoint->isInTreeScope() && treeScope() == document()) {
Ben Murdoch3c9e4ae2013-08-12 14:20:44 +01001295 TreeScope* oldScope = insertionPoint->treeScope();
1296 HTMLDocument* oldDocument = wasInDocument && !wasInShadowTree && oldScope->documentScope()->isHTMLDocument() ? toHTMLDocument(oldScope->documentScope()) : 0;
1297
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001298 const AtomicString& idValue = getIdAttribute();
Ben Murdoch3c9e4ae2013-08-12 14:20:44 +01001299 if (!idValue.isNull()) {
1300 updateIdForTreeScope(oldScope, idValue, nullAtom);
1301 if (oldDocument)
1302 updateIdForDocument(oldDocument, idValue, nullAtom);
1303 }
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001304
1305 const AtomicString& nameValue = getNameAttribute();
Ben Murdoch3c9e4ae2013-08-12 14:20:44 +01001306 if (!nameValue.isNull()) {
1307 updateNameForTreeScope(oldScope, nameValue, nullAtom);
1308 if (oldDocument)
1309 updateNameForDocument(oldDocument, nameValue, nullAtom);
1310 }
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001311
1312 if (hasTagName(labelTag)) {
Ben Murdoch3c9e4ae2013-08-12 14:20:44 +01001313 if (oldScope->shouldCacheLabelsByForAttribute())
1314 updateLabel(oldScope, fastGetAttribute(forAttr), nullAtom);
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001315 }
1316 }
1317
1318 ContainerNode::removedFrom(insertionPoint);
Ben Murdoch3c9e4ae2013-08-12 14:20:44 +01001319
Ben Murdoche69819b2013-07-17 14:56:49 +01001320 if (wasInDocument) {
1321 if (hasPendingResources())
1322 document()->accessSVGExtensions()->removeElementFromPendingResources(this);
1323
Ben Murdoch83750172013-07-24 10:36:59 +01001324 if (isUpgradedCustomElement())
Ben Murdochfff88842013-07-30 15:20:09 +01001325 CustomElement::didLeaveDocument(this, insertionPoint->document());
Ben Murdoche69819b2013-07-17 14:56:49 +01001326 }
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001327
Ben Murdoch3c9e4ae2013-08-12 14:20:44 +01001328 if (hasRareData())
1329 elementRareData()->setIsInCanvasSubtree(false);
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001330}
1331
Torne (Richard Coles)521d96e2013-06-19 11:58:24 +01001332void Element::attach(const AttachContext& context)
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001333{
1334 PostAttachCallbackDisabler callbackDisabler(this);
1335 StyleResolverParentPusher parentPusher(this);
1336 WidgetHierarchyUpdatesSuspensionScope suspendWidgetHierarchyUpdates;
1337
Ben Murdoch3c9e4ae2013-08-12 14:20:44 +01001338 NodeRenderingContext(this, context.resolvedStyle).createRendererForElementIfNeeded();
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001339
1340 createPseudoElementIfNeeded(BEFORE);
1341
1342 // When a shadow root exists, it does the work of attaching the children.
1343 if (ElementShadow* shadow = this->shadow()) {
1344 parentPusher.push();
Ben Murdoch591b9582013-07-10 11:41:44 +01001345 shadow->attach(context);
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001346 } else if (firstChild())
1347 parentPusher.push();
1348
Torne (Richard Coles)521d96e2013-06-19 11:58:24 +01001349 ContainerNode::attach(context);
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001350
1351 createPseudoElementIfNeeded(AFTER);
Ben Murdoche69819b2013-07-17 14:56:49 +01001352 createPseudoElementIfNeeded(BACKDROP);
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001353
Ben Murdoch591b9582013-07-10 11:41:44 +01001354 if (hasRareData()) {
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001355 ElementRareData* data = elementRareData();
1356 if (data->needsFocusAppearanceUpdateSoonAfterAttach()) {
Ben Murdoch7757ec22013-07-23 11:17:36 +01001357 if (isFocusable() && document()->focusedElement() == this)
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001358 document()->updateFocusAppearanceSoon(false /* don't restore selection */);
1359 data->setNeedsFocusAppearanceUpdateSoonAfterAttach(false);
1360 }
1361 }
Ben Murdoch591b9582013-07-10 11:41:44 +01001362
1363 // FIXME: It doesn't appear safe to call didRecalculateStyleForElement when
1364 // not in a Document::recalcStyle. Since we're hopefully going to always
1365 // lazyAttach in the future that problem should go away.
1366 if (document()->inStyleRecalc())
1367 InspectorInstrumentation::didRecalculateStyleForElement(this);
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001368}
1369
1370void Element::unregisterNamedFlowContentNode()
1371{
1372 if (RuntimeEnabledFeatures::cssRegionsEnabled() && inNamedFlow() && document()->renderView())
1373 document()->renderView()->flowThreadController()->unregisterNamedFlowContentNode(this);
1374}
1375
Torne (Richard Coles)521d96e2013-06-19 11:58:24 +01001376void Element::detach(const AttachContext& context)
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001377{
1378 WidgetHierarchyUpdatesSuspensionScope suspendWidgetHierarchyUpdates;
1379 unregisterNamedFlowContentNode();
1380 cancelFocusAppearanceUpdate();
1381 if (hasRareData()) {
1382 ElementRareData* data = elementRareData();
1383 data->setPseudoElement(BEFORE, 0);
1384 data->setPseudoElement(AFTER, 0);
Ben Murdoche69819b2013-07-17 14:56:49 +01001385 data->setPseudoElement(BACKDROP, 0);
Ben Murdoch3c9e4ae2013-08-12 14:20:44 +01001386 data->clearComputedStyle();
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001387 data->resetDynamicRestyleObservations();
Ben Murdoch591b9582013-07-10 11:41:44 +01001388 data->setIsInsideRegion(false);
Torne (Richard Coles)f5e4ad52013-08-05 13:57:57 +01001389
Ben Murdoch3c9e4ae2013-08-12 14:20:44 +01001390 // Only clear the style state if we're not going to reuse the style from recalcStyle.
1391 if (!context.resolvedStyle)
1392 data->resetStyleState();
1393
Torne (Richard Coles)f5e4ad52013-08-05 13:57:57 +01001394 if (RuntimeEnabledFeatures::webAnimationsCSSEnabled() && !context.performingReattach) {
1395 if (ActiveAnimations* activeAnimations = data->activeAnimations())
1396 activeAnimations->cssAnimations()->cancel();
1397 }
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001398 }
Ben Murdoch591b9582013-07-10 11:41:44 +01001399 if (ElementShadow* shadow = this->shadow())
1400 shadow->detach(context);
Torne (Richard Coles)521d96e2013-06-19 11:58:24 +01001401 ContainerNode::detach(context);
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001402}
1403
1404bool Element::pseudoStyleCacheIsInvalid(const RenderStyle* currentStyle, RenderStyle* newStyle)
1405{
1406 ASSERT(currentStyle == renderStyle());
1407 ASSERT(renderer());
1408
1409 if (!currentStyle)
1410 return false;
1411
1412 const PseudoStyleCache* pseudoStyleCache = currentStyle->cachedPseudoStyles();
1413 if (!pseudoStyleCache)
1414 return false;
1415
1416 size_t cacheSize = pseudoStyleCache->size();
1417 for (size_t i = 0; i < cacheSize; ++i) {
1418 RefPtr<RenderStyle> newPseudoStyle;
1419 PseudoId pseudoId = pseudoStyleCache->at(i)->styleType();
1420 if (pseudoId == FIRST_LINE || pseudoId == FIRST_LINE_INHERITED)
1421 newPseudoStyle = renderer()->uncachedFirstLineStyle(newStyle);
1422 else
1423 newPseudoStyle = renderer()->getUncachedPseudoStyle(PseudoStyleRequest(pseudoId), newStyle, newStyle);
1424 if (!newPseudoStyle)
1425 return true;
1426 if (*newPseudoStyle != *pseudoStyleCache->at(i)) {
1427 if (pseudoId < FIRST_INTERNAL_PSEUDOID)
1428 newStyle->setHasPseudoStyle(pseudoId);
1429 newStyle->addCachedPseudoStyle(newPseudoStyle);
1430 if (pseudoId == FIRST_LINE || pseudoId == FIRST_LINE_INHERITED) {
1431 // FIXME: We should do an actual diff to determine whether a repaint vs. layout
1432 // is needed, but for now just assume a layout will be required. The diff code
1433 // in RenderObject::setStyle would need to be factored out so that it could be reused.
1434 renderer()->setNeedsLayoutAndPrefWidthsRecalc();
1435 }
1436 return true;
1437 }
1438 }
1439 return false;
1440}
1441
Torne (Richard Coles)521d96e2013-06-19 11:58:24 +01001442PassRefPtr<RenderStyle> Element::styleForRenderer()
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001443{
1444 if (hasCustomStyleCallbacks()) {
1445 if (RefPtr<RenderStyle> style = customStyleForRenderer())
1446 return style.release();
1447 }
1448
Torne (Richard Coles)521d96e2013-06-19 11:58:24 +01001449 return originalStyleForRenderer();
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001450}
1451
Torne (Richard Coles)521d96e2013-06-19 11:58:24 +01001452PassRefPtr<RenderStyle> Element::originalStyleForRenderer()
Torne (Richard Coles)5267f702013-06-11 10:57:24 +01001453{
Torne (Richard Coles)521d96e2013-06-19 11:58:24 +01001454 return document()->styleResolver()->styleForElement(this);
Torne (Richard Coles)5267f702013-06-11 10:57:24 +01001455}
1456
Ben Murdoche69819b2013-07-17 14:56:49 +01001457bool Element::recalcStyle(StyleChange change)
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001458{
Torne (Richard Coles)93ac45c2013-05-29 14:40:20 +01001459 ASSERT(document()->inStyleRecalc());
1460
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001461 if (hasCustomStyleCallbacks())
1462 willRecalcStyle(change);
1463
1464 // Ref currentStyle in case it would otherwise be deleted when setting the new style in the renderer.
Ben Murdoch83750172013-07-24 10:36:59 +01001465 RefPtr<RenderStyle> currentStyle = renderStyle();
1466 bool hasParentStyle = static_cast<bool>(parentRenderStyle());
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001467 bool hasDirectAdjacentRules = childrenAffectedByDirectAdjacentRules();
1468 bool hasIndirectAdjacentRules = childrenAffectedByForwardPositionalRules();
1469
Ben Murdoch3c9e4ae2013-08-12 14:20:44 +01001470 if (hasRareData() && (change > NoChange || needsStyleRecalc())) {
1471 ElementRareData* data = elementRareData();
1472 data->resetStyleState();
1473 data->clearComputedStyle();
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001474 }
Ben Murdoch3c9e4ae2013-08-12 14:20:44 +01001475
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001476 if (hasParentStyle && (change >= Inherit || needsStyleRecalc())) {
1477 StyleChange localChange = Detach;
1478 RefPtr<RenderStyle> newStyle;
1479 if (currentStyle) {
Torne (Richard Coles)521d96e2013-06-19 11:58:24 +01001480 newStyle = styleForRenderer();
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001481 localChange = Node::diff(currentStyle.get(), newStyle.get(), document());
Torne (Richard Coles)521d96e2013-06-19 11:58:24 +01001482 } else if (attached() && isActiveInsertionPoint(this)) {
1483 // Active InsertionPoints will never have renderers so there's no reason to
1484 // reattach them repeatedly once they're already attached.
1485 localChange = change;
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001486 }
1487 if (localChange == Detach) {
Torne (Richard Coles)521d96e2013-06-19 11:58:24 +01001488 AttachContext reattachContext;
1489 reattachContext.resolvedStyle = newStyle.get();
1490 reattach(reattachContext);
1491
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001492 if (hasCustomStyleCallbacks())
1493 didRecalcStyle(change);
Ben Murdoche69819b2013-07-17 14:56:49 +01001494 return true;
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001495 }
1496
Ben Murdoch591b9582013-07-10 11:41:44 +01001497 InspectorInstrumentation::didRecalculateStyleForElement(this);
1498
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001499 if (RenderObject* renderer = this->renderer()) {
Torne (Richard Coles)f5e4ad52013-08-05 13:57:57 +01001500 if (localChange != NoChange || pseudoStyleCacheIsInvalid(currentStyle.get(), newStyle.get()) || (change == Force && renderer->requiresForcedStyleRecalcPropagation()) || shouldNotifyRendererWithIdenticalStyles()) {
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001501 renderer->setAnimatableStyle(newStyle.get());
Torne (Richard Coles)f5e4ad52013-08-05 13:57:57 +01001502 } else if (needsStyleRecalc()) {
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001503 // Although no change occurred, we use the new style so that the cousin style sharing code won't get
1504 // fooled into believing this style is the same.
1505 renderer->setStyleInternal(newStyle.get());
1506 }
1507 }
1508
1509 // 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
1510 // 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).
1511 if (document()->styleSheetCollection()->usesRemUnits() && document()->documentElement() == this && localChange != NoChange && currentStyle && newStyle && currentStyle->fontSize() != newStyle->fontSize()) {
1512 // Cached RenderStyles may depend on the re units.
1513 document()->styleResolver()->invalidateMatchedPropertiesCache();
1514 change = Force;
1515 }
1516
Ben Murdochdf957042013-08-06 11:01:27 +01001517 if (styleChangeType() >= SubtreeStyleChange)
Torne (Richard Coles)e5249552013-05-15 11:35:13 +01001518 change = Force;
1519 else if (change != Force)
1520 change = localChange;
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001521 }
1522 StyleResolverParentPusher parentPusher(this);
1523
Torne (Richard Coles)f5e4ad52013-08-05 13:57:57 +01001524 for (ShadowRoot* root = youngestShadowRoot(); root; root = root->olderShadowRoot()) {
1525 if (shouldRecalcStyle(change, root)) {
1526 parentPusher.push();
1527 root->recalcStyle(change);
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001528 }
1529 }
1530
1531 if (shouldRecalcStyle(change, this))
1532 updatePseudoElement(BEFORE, change);
1533
1534 // FIXME: This check is good enough for :hover + foo, but it is not good enough for :hover + foo + bar.
1535 // For now we will just worry about the common case, since it's a lot trickier to get the second case right
1536 // without doing way too much re-resolution.
1537 bool forceCheckOfNextElementSibling = false;
1538 bool forceCheckOfAnyElementSibling = false;
Ben Murdoche69819b2013-07-17 14:56:49 +01001539 bool forceReattachOfAnyWhitespaceSibling = false;
1540 for (Node* child = firstChild(); child; child = child->nextSibling()) {
1541 bool didReattach = false;
1542
1543 if (child->renderer())
1544 forceReattachOfAnyWhitespaceSibling = false;
1545
1546 if (child->isTextNode()) {
1547 if (forceReattachOfAnyWhitespaceSibling && toText(child)->containsOnlyWhitespace())
1548 child->reattach();
1549 else
1550 didReattach = toText(child)->recalcTextStyle(change);
1551 } else if (child->isElementNode()) {
1552 Element* element = toElement(child);
1553
1554 if (forceCheckOfNextElementSibling || forceCheckOfAnyElementSibling)
1555 element->setNeedsStyleRecalc();
1556
Ben Murdochdf957042013-08-06 11:01:27 +01001557 bool childRulesChanged = element->needsStyleRecalc() && element->styleChangeType() >= SubtreeStyleChange;
Ben Murdoche69819b2013-07-17 14:56:49 +01001558 forceCheckOfNextElementSibling = childRulesChanged && hasDirectAdjacentRules;
1559 forceCheckOfAnyElementSibling = forceCheckOfAnyElementSibling || (childRulesChanged && hasIndirectAdjacentRules);
1560
1561 if (shouldRecalcStyle(change, element)) {
1562 parentPusher.push();
1563 didReattach = element->recalcStyle(change);
1564 }
Ben Murdoch591b9582013-07-10 11:41:44 +01001565 }
Ben Murdoche69819b2013-07-17 14:56:49 +01001566
1567 forceReattachOfAnyWhitespaceSibling = didReattach || forceReattachOfAnyWhitespaceSibling;
Torne (Richard Coles)5267f702013-06-11 10:57:24 +01001568 }
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001569
1570 if (shouldRecalcStyle(change, this))
1571 updatePseudoElement(AFTER, change);
1572
1573 clearNeedsStyleRecalc();
1574 clearChildNeedsStyleRecalc();
Ben Murdoch591b9582013-07-10 11:41:44 +01001575
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001576 if (hasCustomStyleCallbacks())
1577 didRecalcStyle(change);
Ben Murdoche69819b2013-07-17 14:56:49 +01001578 return false;
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001579}
1580
1581ElementShadow* Element::shadow() const
1582{
1583 return hasRareData() ? elementRareData()->shadow() : 0;
1584}
1585
1586ElementShadow* Element::ensureShadow()
1587{
1588 return ensureElementRareData()->ensureShadow();
1589}
1590
1591void Element::didAffectSelector(AffectedSelectorMask mask)
1592{
1593 setNeedsStyleRecalc();
1594 if (ElementShadow* elementShadow = shadowOfParentForDistribution(this))
1595 elementShadow->didAffectSelector(mask);
1596}
1597
Ben Murdochdf957042013-08-06 11:01:27 +01001598PassRefPtr<ShadowRoot> Element::createShadowRoot(ExceptionState& es)
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001599{
1600 if (alwaysCreateUserAgentShadowRoot())
1601 ensureUserAgentShadowRoot();
1602
1603 if (RuntimeEnabledFeatures::authorShadowDOMForAnyElementEnabled())
1604 return ensureShadow()->addShadowRoot(this, ShadowRoot::AuthorShadowRoot);
1605
1606 // Since some elements recreates shadow root dynamically, multiple shadow
1607 // subtrees won't work well in that element. Until they are fixed, we disable
1608 // adding author shadow root for them.
1609 if (!areAuthorShadowsAllowed()) {
Ben Murdochdf957042013-08-06 11:01:27 +01001610 es.throwDOMException(HierarchyRequestError);
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001611 return 0;
1612 }
1613 return ensureShadow()->addShadowRoot(this, ShadowRoot::AuthorShadowRoot);
1614}
1615
1616ShadowRoot* Element::shadowRoot() const
1617{
1618 ElementShadow* elementShadow = shadow();
1619 if (!elementShadow)
1620 return 0;
1621 ShadowRoot* shadowRoot = elementShadow->youngestShadowRoot();
1622 if (shadowRoot->type() == ShadowRoot::AuthorShadowRoot)
1623 return shadowRoot;
1624 return 0;
1625}
1626
1627ShadowRoot* Element::userAgentShadowRoot() const
1628{
1629 if (ElementShadow* elementShadow = shadow()) {
1630 if (ShadowRoot* shadowRoot = elementShadow->oldestShadowRoot()) {
1631 ASSERT(shadowRoot->type() == ShadowRoot::UserAgentShadowRoot);
1632 return shadowRoot;
1633 }
1634 }
1635
1636 return 0;
1637}
1638
1639ShadowRoot* Element::ensureUserAgentShadowRoot()
1640{
1641 if (ShadowRoot* shadowRoot = userAgentShadowRoot())
1642 return shadowRoot;
1643 ShadowRoot* shadowRoot = ensureShadow()->addShadowRoot(this, ShadowRoot::UserAgentShadowRoot);
1644 didAddUserAgentShadowRoot(shadowRoot);
1645 return shadowRoot;
1646}
1647
Ben Murdoch3c9e4ae2013-08-12 14:20:44 +01001648Element* Element::uaShadowElementById(const AtomicString& id) const
1649{
1650 ShadowRoot* shadowRoot = userAgentShadowRoot();
1651 return shadowRoot ? shadowRoot->getElementById(id) : 0;
1652}
1653
Ben Murdoch1fad5ca2013-08-07 11:05:11 +01001654bool Element::supportsShadowElementForUserAgentShadow() const
1655{
1656 return true;
1657}
1658
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001659bool Element::childTypeAllowed(NodeType type) const
1660{
1661 switch (type) {
1662 case ELEMENT_NODE:
1663 case TEXT_NODE:
1664 case COMMENT_NODE:
1665 case PROCESSING_INSTRUCTION_NODE:
1666 case CDATA_SECTION_NODE:
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001667 return true;
1668 default:
1669 break;
1670 }
1671 return false;
1672}
1673
Ben Murdoch83750172013-07-24 10:36:59 +01001674static void inline checkForEmptyStyleChange(Element* element, RenderStyle* style)
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001675{
1676 if (!style && !element->styleAffectedByEmpty())
1677 return;
1678
1679 if (!style || (element->styleAffectedByEmpty() && (!style->emptyState() || element->hasChildNodes())))
1680 element->setNeedsStyleRecalc();
1681}
1682
1683static void checkForSiblingStyleChanges(Element* e, RenderStyle* style, bool finishedParsingCallback,
1684 Node* beforeChange, Node* afterChange, int childCountDelta)
1685{
Ben Murdochdf957042013-08-06 11:01:27 +01001686 if (!e->attached() || e->document()->hasPendingForcedStyleRecalc() || e->styleChangeType() >= SubtreeStyleChange)
Ben Murdoch83750172013-07-24 10:36:59 +01001687 return;
1688
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001689 // :empty selector.
1690 checkForEmptyStyleChange(e, style);
Ben Murdoch591b9582013-07-10 11:41:44 +01001691
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001692 if (!style || (e->needsStyleRecalc() && e->childrenAffectedByPositionalRules()))
1693 return;
1694
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001695 // Forward positional selectors include the ~ selector, nth-child, nth-of-type, first-of-type and only-of-type.
1696 // Backward positional selectors include nth-last-child, nth-last-of-type, last-of-type and only-of-type.
1697 // We have to invalidate everything following the insertion point in the forward case, and everything before the insertion point in the
1698 // backward case.
1699 // |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.
1700 // 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 +01001701 // here. recalcStyle will then force a walk of the children when it sees that this has happened.
1702 if ((e->childrenAffectedByForwardPositionalRules() && afterChange) || (e->childrenAffectedByBackwardPositionalRules() && beforeChange)) {
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001703 e->setNeedsStyleRecalc();
Ben Murdoch83750172013-07-24 10:36:59 +01001704 return;
1705 }
1706
1707 // :first-child. In the parser callback case, we don't have to check anything, since we were right the first time.
1708 // In the DOM case, we only need to do something if |afterChange| is not 0.
1709 // |afterChange| is 0 in the parser case, so it works out that we'll skip this block.
1710 if (e->childrenAffectedByFirstChildRules() && afterChange) {
1711 // Find our new first child.
1712 Node* newFirstChild = e->firstElementChild();
1713 RenderStyle* newFirstChildStyle = newFirstChild ? newFirstChild->renderStyle() : 0;
1714
1715 // Find the first element node following |afterChange|
1716 Node* firstElementAfterInsertion = afterChange->isElementNode() ? afterChange : afterChange->nextElementSibling();
1717 RenderStyle* firstElementAfterInsertionStyle = firstElementAfterInsertion ? firstElementAfterInsertion->renderStyle() : 0;
1718
1719 // This is the insert/append case.
1720 if (newFirstChild != firstElementAfterInsertion && firstElementAfterInsertionStyle && firstElementAfterInsertionStyle->firstChildState())
1721 firstElementAfterInsertion->setNeedsStyleRecalc();
1722
1723 // We also have to handle node removal.
1724 if (childCountDelta < 0 && newFirstChild == firstElementAfterInsertion && newFirstChild && (!newFirstChildStyle || !newFirstChildStyle->firstChildState()))
1725 newFirstChild->setNeedsStyleRecalc();
1726 }
1727
1728 // :last-child. In the parser callback case, we don't have to check anything, since we were right the first time.
1729 // In the DOM case, we only need to do something if |afterChange| is not 0.
1730 if (e->childrenAffectedByLastChildRules() && beforeChange) {
1731 // Find our new last child.
1732 Node* newLastChild = e->lastElementChild();
1733 RenderStyle* newLastChildStyle = newLastChild ? newLastChild->renderStyle() : 0;
1734
1735 // Find the last element node going backwards from |beforeChange|
1736 Node* lastElementBeforeInsertion = beforeChange->isElementNode() ? beforeChange : beforeChange->previousElementSibling();
1737 RenderStyle* lastElementBeforeInsertionStyle = lastElementBeforeInsertion ? lastElementBeforeInsertion->renderStyle() : 0;
1738
1739 if (newLastChild != lastElementBeforeInsertion && lastElementBeforeInsertionStyle && lastElementBeforeInsertionStyle->lastChildState())
1740 lastElementBeforeInsertion->setNeedsStyleRecalc();
1741
1742 // 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
1743 // to match now.
1744 if ((childCountDelta < 0 || finishedParsingCallback) && newLastChild == lastElementBeforeInsertion && newLastChild && (!newLastChildStyle || !newLastChildStyle->lastChildState()))
1745 newLastChild->setNeedsStyleRecalc();
1746 }
1747
1748 // The + selector. We need to invalidate the first element following the insertion point. It is the only possible element
1749 // that could be affected by this DOM change.
1750 if (e->childrenAffectedByDirectAdjacentRules() && afterChange) {
1751 if (Node* firstElementAfterInsertion = afterChange->nextElementSibling())
1752 firstElementAfterInsertion->setNeedsStyleRecalc();
1753 }
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001754}
1755
1756void Element::childrenChanged(bool changedByParser, Node* beforeChange, Node* afterChange, int childCountDelta)
1757{
1758 ContainerNode::childrenChanged(changedByParser, beforeChange, afterChange, childCountDelta);
1759 if (changedByParser)
1760 checkForEmptyStyleChange(this, renderStyle());
1761 else
1762 checkForSiblingStyleChanges(this, renderStyle(), false, beforeChange, afterChange, childCountDelta);
1763
Ben Murdoch83750172013-07-24 10:36:59 +01001764 if (ElementShadow* shadow = this->shadow())
Torne (Richard Coles)f5e4ad52013-08-05 13:57:57 +01001765 shadow->setNeedsDistributionRecalc();
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001766}
1767
1768void Element::removeAllEventListeners()
1769{
1770 ContainerNode::removeAllEventListeners();
1771 if (ElementShadow* shadow = this->shadow())
1772 shadow->removeAllEventListeners();
1773}
1774
1775void Element::beginParsingChildren()
1776{
1777 clearIsParsingChildrenFinished();
1778 StyleResolver* styleResolver = document()->styleResolverIfExists();
1779 if (styleResolver && attached())
1780 styleResolver->pushParentElement(this);
1781}
1782
1783void Element::finishParsingChildren()
1784{
1785 ContainerNode::finishParsingChildren();
1786 setIsParsingChildrenFinished();
1787 checkForSiblingStyleChanges(this, renderStyle(), true, lastChild(), 0, 0);
1788 if (StyleResolver* styleResolver = document()->styleResolverIfExists())
1789 styleResolver->popParentElement(this);
1790}
1791
1792#ifndef NDEBUG
1793void Element::formatForDebugger(char* buffer, unsigned length) const
1794{
1795 StringBuilder result;
1796 String s;
1797
1798 result.append(nodeName());
1799
1800 s = getIdAttribute();
1801 if (s.length() > 0) {
1802 if (result.length() > 0)
1803 result.appendLiteral("; ");
1804 result.appendLiteral("id=");
1805 result.append(s);
1806 }
1807
1808 s = getAttribute(classAttr);
1809 if (s.length() > 0) {
1810 if (result.length() > 0)
1811 result.appendLiteral("; ");
1812 result.appendLiteral("class=");
1813 result.append(s);
1814 }
1815
1816 strncpy(buffer, result.toString().utf8().data(), length - 1);
1817}
1818#endif
1819
1820const Vector<RefPtr<Attr> >& Element::attrNodeList()
1821{
1822 ASSERT(hasSyntheticAttrChildNodes());
1823 return *attrNodeListForElement(this);
1824}
1825
Ben Murdochdf957042013-08-06 11:01:27 +01001826PassRefPtr<Attr> Element::setAttributeNode(Attr* attrNode, ExceptionState& es)
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001827{
1828 if (!attrNode) {
Ben Murdochdf957042013-08-06 11:01:27 +01001829 es.throwDOMException(TypeMismatchError);
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001830 return 0;
1831 }
1832
1833 RefPtr<Attr> oldAttrNode = attrIfExists(attrNode->qualifiedName());
1834 if (oldAttrNode.get() == attrNode)
1835 return attrNode; // This Attr is already attached to the element.
1836
Ben Murdoche69819b2013-07-17 14:56:49 +01001837 // 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 +01001838 // The DOM user must explicitly clone Attr nodes to re-use them in other elements.
1839 if (attrNode->ownerElement()) {
Ben Murdochdf957042013-08-06 11:01:27 +01001840 es.throwDOMException(InUseAttributeError);
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001841 return 0;
1842 }
1843
1844 synchronizeAllAttributes();
1845 UniqueElementData* elementData = ensureUniqueElementData();
1846
1847 size_t index = elementData->getAttributeItemIndex(attrNode->qualifiedName());
1848 if (index != notFound) {
1849 if (oldAttrNode)
1850 detachAttrNodeFromElementWithValue(oldAttrNode.get(), elementData->attributeItem(index)->value());
1851 else
1852 oldAttrNode = Attr::create(document(), attrNode->qualifiedName(), elementData->attributeItem(index)->value());
1853 }
1854
1855 setAttributeInternal(index, attrNode->qualifiedName(), attrNode->value(), NotInSynchronizationOfLazyAttribute);
1856
1857 attrNode->attachToElement(this);
Ben Murdoch591b9582013-07-10 11:41:44 +01001858 treeScope()->adoptIfNeeded(attrNode);
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001859 ensureAttrNodeListForElement(this)->append(attrNode);
1860
1861 return oldAttrNode.release();
1862}
1863
Ben Murdochdf957042013-08-06 11:01:27 +01001864PassRefPtr<Attr> Element::setAttributeNodeNS(Attr* attr, ExceptionState& es)
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001865{
Ben Murdochdf957042013-08-06 11:01:27 +01001866 return setAttributeNode(attr, es);
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001867}
1868
Ben Murdochdf957042013-08-06 11:01:27 +01001869PassRefPtr<Attr> Element::removeAttributeNode(Attr* attr, ExceptionState& es)
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001870{
1871 if (!attr) {
Ben Murdochdf957042013-08-06 11:01:27 +01001872 es.throwDOMException(TypeMismatchError);
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001873 return 0;
1874 }
1875 if (attr->ownerElement() != this) {
Ben Murdochdf957042013-08-06 11:01:27 +01001876 es.throwDOMException(NotFoundError);
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001877 return 0;
1878 }
1879
1880 ASSERT(document() == attr->document());
1881
1882 synchronizeAttribute(attr->qualifiedName());
1883
Torne (Richard Coles)e5249552013-05-15 11:35:13 +01001884 size_t index = elementData()->getAttrIndex(attr);
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001885 if (index == notFound) {
Ben Murdochdf957042013-08-06 11:01:27 +01001886 es.throwDOMException(NotFoundError);
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001887 return 0;
1888 }
1889
Torne (Richard Coles)e5249552013-05-15 11:35:13 +01001890 RefPtr<Attr> guard(attr);
1891 detachAttrNodeAtIndex(attr, index);
1892 return guard.release();
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001893}
1894
Ben Murdochdf957042013-08-06 11:01:27 +01001895bool Element::parseAttributeName(QualifiedName& out, const AtomicString& namespaceURI, const AtomicString& qualifiedName, ExceptionState& es)
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001896{
1897 String prefix, localName;
Ben Murdochdf957042013-08-06 11:01:27 +01001898 if (!Document::parseQualifiedName(qualifiedName, prefix, localName, es))
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001899 return false;
Ben Murdochdf957042013-08-06 11:01:27 +01001900 ASSERT(!es.hadException());
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001901
1902 QualifiedName qName(prefix, localName, namespaceURI);
1903
1904 if (!Document::hasValidNamespaceForAttributes(qName)) {
Ben Murdochdf957042013-08-06 11:01:27 +01001905 es.throwDOMException(NamespaceError);
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001906 return false;
1907 }
1908
1909 out = qName;
1910 return true;
1911}
1912
Ben Murdochdf957042013-08-06 11:01:27 +01001913void Element::setAttributeNS(const AtomicString& namespaceURI, const AtomicString& qualifiedName, const AtomicString& value, ExceptionState& es)
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001914{
1915 QualifiedName parsedName = anyName;
Ben Murdochdf957042013-08-06 11:01:27 +01001916 if (!parseAttributeName(parsedName, namespaceURI, qualifiedName, es))
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001917 return;
1918 setAttribute(parsedName, value);
1919}
1920
1921void Element::removeAttributeInternal(size_t index, SynchronizationOfLazyAttribute inSynchronizationOfLazyAttribute)
1922{
1923 ASSERT_WITH_SECURITY_IMPLICATION(index < attributeCount());
1924
1925 UniqueElementData* elementData = ensureUniqueElementData();
1926
1927 QualifiedName name = elementData->attributeItem(index)->name();
1928 AtomicString valueBeingRemoved = elementData->attributeItem(index)->value();
1929
1930 if (!inSynchronizationOfLazyAttribute) {
1931 if (!valueBeingRemoved.isNull())
1932 willModifyAttribute(name, valueBeingRemoved, nullAtom);
1933 }
1934
1935 if (RefPtr<Attr> attrNode = attrIfExists(name))
1936 detachAttrNodeFromElementWithValue(attrNode.get(), elementData->attributeItem(index)->value());
1937
1938 elementData->removeAttribute(index);
1939
1940 if (!inSynchronizationOfLazyAttribute)
1941 didRemoveAttribute(name);
1942}
1943
1944void Element::addAttributeInternal(const QualifiedName& name, const AtomicString& value, SynchronizationOfLazyAttribute inSynchronizationOfLazyAttribute)
1945{
1946 if (!inSynchronizationOfLazyAttribute)
1947 willModifyAttribute(name, nullAtom, value);
1948 ensureUniqueElementData()->addAttribute(name, value);
1949 if (!inSynchronizationOfLazyAttribute)
1950 didAddAttribute(name, value);
1951}
1952
1953void Element::removeAttribute(const AtomicString& name)
1954{
1955 if (!elementData())
1956 return;
1957
1958 AtomicString localName = shouldIgnoreAttributeCase(this) ? name.lower() : name;
1959 size_t index = elementData()->getAttributeItemIndex(localName, false);
1960 if (index == notFound) {
1961 if (UNLIKELY(localName == styleAttr) && elementData()->m_styleAttributeIsDirty && isStyledElement())
Ben Murdoch591b9582013-07-10 11:41:44 +01001962 removeAllInlineStyleProperties();
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001963 return;
1964 }
1965
1966 removeAttributeInternal(index, NotInSynchronizationOfLazyAttribute);
1967}
1968
1969void Element::removeAttributeNS(const AtomicString& namespaceURI, const AtomicString& localName)
1970{
1971 removeAttribute(QualifiedName(nullAtom, localName, namespaceURI));
1972}
1973
1974PassRefPtr<Attr> Element::getAttributeNode(const AtomicString& localName)
1975{
1976 if (!elementData())
1977 return 0;
1978 synchronizeAttribute(localName);
1979 const Attribute* attribute = elementData()->getAttributeItem(localName, shouldIgnoreAttributeCase(this));
1980 if (!attribute)
1981 return 0;
1982 return ensureAttr(attribute->name());
1983}
1984
1985PassRefPtr<Attr> Element::getAttributeNodeNS(const AtomicString& namespaceURI, const AtomicString& localName)
1986{
1987 if (!elementData())
1988 return 0;
1989 QualifiedName qName(nullAtom, localName, namespaceURI);
1990 synchronizeAttribute(qName);
1991 const Attribute* attribute = elementData()->getAttributeItem(qName);
1992 if (!attribute)
1993 return 0;
1994 return ensureAttr(attribute->name());
1995}
1996
1997bool Element::hasAttribute(const AtomicString& localName) const
1998{
1999 if (!elementData())
2000 return false;
2001 synchronizeAttribute(localName);
2002 return elementData()->getAttributeItem(shouldIgnoreAttributeCase(this) ? localName.lower() : localName, false);
2003}
2004
2005bool Element::hasAttributeNS(const AtomicString& namespaceURI, const AtomicString& localName) const
2006{
2007 if (!elementData())
2008 return false;
2009 QualifiedName qName(nullAtom, localName, namespaceURI);
2010 synchronizeAttribute(qName);
2011 return elementData()->getAttributeItem(qName);
2012}
2013
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002014void Element::focus(bool restorePreviousSelection, FocusDirection direction)
2015{
2016 if (!inDocument())
2017 return;
2018
2019 Document* doc = document();
Ben Murdoch7757ec22013-07-23 11:17:36 +01002020 if (doc->focusedElement() == this)
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002021 return;
2022
2023 // If the stylesheets have already been loaded we can reliably check isFocusable.
2024 // If not, we continue and set the focused node on the focus controller below so
Ben Murdoch591b9582013-07-10 11:41:44 +01002025 // that it can be updated soon after attach.
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002026 if (doc->haveStylesheetsLoaded()) {
2027 doc->updateLayoutIgnorePendingStylesheets();
2028 if (!isFocusable())
2029 return;
2030 }
2031
2032 if (!supportsFocus())
2033 return;
2034
2035 RefPtr<Node> protect;
2036 if (Page* page = doc->page()) {
2037 // Focus and change event handlers can cause us to lose our last ref.
2038 // If a focus event handler changes the focus to a different node it
2039 // does not make sense to continue and update appearence.
2040 protect = this;
Ben Murdoch3c9e4ae2013-08-12 14:20:44 +01002041 if (!page->focusController().setFocusedElement(this, doc->frame(), direction))
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002042 return;
2043 }
2044
2045 // Setting the focused node above might have invalidated the layout due to scripts.
2046 doc->updateLayoutIgnorePendingStylesheets();
2047
2048 if (!isFocusable()) {
2049 ensureElementRareData()->setNeedsFocusAppearanceUpdateSoonAfterAttach(true);
2050 return;
2051 }
Ben Murdoch591b9582013-07-10 11:41:44 +01002052
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002053 cancelFocusAppearanceUpdate();
2054 updateFocusAppearance(restorePreviousSelection);
2055}
2056
2057void Element::updateFocusAppearance(bool /*restorePreviousSelection*/)
2058{
2059 if (isRootEditableElement()) {
2060 Frame* frame = document()->frame();
2061 if (!frame)
2062 return;
Ben Murdoch591b9582013-07-10 11:41:44 +01002063
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002064 // When focusing an editable element in an iframe, don't reset the selection if it already contains a selection.
2065 if (this == frame->selection()->rootEditableElement())
2066 return;
2067
2068 // FIXME: We should restore the previous selection if there is one.
2069 VisibleSelection newSelection = VisibleSelection(firstPositionInOrBeforeNode(this), DOWNSTREAM);
Ben Murdoch591b9582013-07-10 11:41:44 +01002070
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002071 if (frame->selection()->shouldChangeSelection(newSelection)) {
2072 frame->selection()->setSelection(newSelection);
2073 frame->selection()->revealSelection();
2074 }
2075 } else if (renderer() && !renderer()->isWidget())
2076 renderer()->scrollRectToVisible(boundingBox());
2077}
2078
2079void Element::blur()
2080{
2081 cancelFocusAppearanceUpdate();
Ben Murdoche69819b2013-07-17 14:56:49 +01002082 if (treeScope()->adjustedFocusedElement() == this) {
2083 Document* doc = document();
Ben Murdoch3c9e4ae2013-08-12 14:20:44 +01002084 if (doc->page())
2085 doc->page()->focusController().setFocusedElement(0, doc->frame());
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002086 else
Ben Murdoche69819b2013-07-17 14:56:49 +01002087 doc->setFocusedElement(0);
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002088 }
2089}
2090
Ben Murdochdf957042013-08-06 11:01:27 +01002091bool Element::isFocusable() const
2092{
2093 return inDocument() && supportsFocus() && !isInert() && rendererIsFocusable();
2094}
2095
Torne (Richard Coles)f5e4ad52013-08-05 13:57:57 +01002096bool Element::isKeyboardFocusable() const
2097{
2098 return isFocusable() && tabIndex() >= 0;
2099}
2100
2101bool Element::isMouseFocusable() const
2102{
2103 return isFocusable();
2104}
2105
Ben Murdoch02772c62013-07-26 10:21:05 +01002106void Element::dispatchFocusEvent(Element* oldFocusedElement, FocusDirection)
2107{
2108 RefPtr<FocusEvent> event = FocusEvent::create(eventNames().focusEvent, false, false, document()->defaultView(), 0, oldFocusedElement);
2109 EventDispatcher::dispatchEvent(this, FocusEventDispatchMediator::create(event.release()));
2110}
2111
2112void Element::dispatchBlurEvent(Element* newFocusedElement)
2113{
2114 RefPtr<FocusEvent> event = FocusEvent::create(eventNames().blurEvent, false, false, document()->defaultView(), 0, newFocusedElement);
2115 EventDispatcher::dispatchEvent(this, BlurEventDispatchMediator::create(event.release()));
2116}
2117
2118void Element::dispatchFocusInEvent(const AtomicString& eventType, Element* oldFocusedElement)
2119{
2120 ASSERT(!NoEventDispatchAssertion::isEventDispatchForbidden());
2121 ASSERT(eventType == eventNames().focusinEvent || eventType == eventNames().DOMFocusInEvent);
2122 dispatchScopedEventDispatchMediator(FocusInEventDispatchMediator::create(FocusEvent::create(eventType, true, false, document()->defaultView(), 0, oldFocusedElement)));
2123}
2124
2125void Element::dispatchFocusOutEvent(const AtomicString& eventType, Element* newFocusedElement)
2126{
2127 ASSERT(!NoEventDispatchAssertion::isEventDispatchForbidden());
2128 ASSERT(eventType == eventNames().focusoutEvent || eventType == eventNames().DOMFocusOutEvent);
2129 dispatchScopedEventDispatchMediator(FocusOutEventDispatchMediator::create(FocusEvent::create(eventType, true, false, document()->defaultView(), 0, newFocusedElement)));
2130}
2131
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002132String Element::innerText()
2133{
2134 // We need to update layout, since plainText uses line boxes in the render tree.
2135 document()->updateLayoutIgnorePendingStylesheets();
2136
2137 if (!renderer())
2138 return textContent(true);
2139
2140 return plainText(rangeOfContents(const_cast<Element*>(this)).get());
2141}
2142
2143String Element::outerText()
2144{
2145 // Getting outerText is the same as getting innerText, only
2146 // setting is different. You would think this should get the plain
2147 // text for the outer range, but this is wrong, <br> for instance
2148 // would return different values for inner and outer text by such
2149 // a rule, but it doesn't in WinIE, and we want to match that.
2150 return innerText();
2151}
2152
Ben Murdoch591b9582013-07-10 11:41:44 +01002153String Element::textFromChildren()
2154{
2155 Text* firstTextNode = 0;
2156 bool foundMultipleTextNodes = false;
2157 unsigned totalLength = 0;
2158
2159 for (Node* child = firstChild(); child; child = child->nextSibling()) {
2160 if (!child->isTextNode())
2161 continue;
2162 Text* text = toText(child);
2163 if (!firstTextNode)
2164 firstTextNode = text;
2165 else
2166 foundMultipleTextNodes = true;
2167 unsigned length = text->data().length();
2168 if (length > std::numeric_limits<unsigned>::max() - totalLength)
2169 return emptyString();
2170 totalLength += length;
2171 }
2172
2173 if (!firstTextNode)
2174 return emptyString();
2175
2176 if (firstTextNode && !foundMultipleTextNodes) {
2177 firstTextNode->atomize();
2178 return firstTextNode->data();
2179 }
2180
2181 StringBuilder content;
2182 content.reserveCapacity(totalLength);
2183 for (Node* child = firstTextNode; child; child = child->nextSibling()) {
2184 if (!child->isTextNode())
2185 continue;
2186 content.append(toText(child)->data());
2187 }
2188
2189 ASSERT(content.length() == totalLength);
2190 return content.toString();
2191}
2192
Ben Murdoch3c9e4ae2013-08-12 14:20:44 +01002193// pseudo is used via shadowPseudoId.
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002194const AtomicString& Element::pseudo() const
2195{
2196 return getAttribute(pseudoAttr);
2197}
2198
Torne (Richard Coles)f5e4ad52013-08-05 13:57:57 +01002199const AtomicString& Element::part() const
2200{
2201 return getAttribute(partAttr);
2202}
2203
2204void Element::setPart(const AtomicString& value)
2205{
2206 setAttribute(partAttr, value);
2207}
2208
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002209LayoutSize Element::minimumSizeForResizing() const
2210{
2211 return hasRareData() ? elementRareData()->minimumSizeForResizing() : defaultMinimumSizeForResizing();
2212}
2213
2214void Element::setMinimumSizeForResizing(const LayoutSize& size)
2215{
2216 if (!hasRareData() && size == defaultMinimumSizeForResizing())
2217 return;
2218 ensureElementRareData()->setMinimumSizeForResizing(size);
2219}
2220
2221RenderStyle* Element::computedStyle(PseudoId pseudoElementSpecifier)
2222{
2223 if (PseudoElement* element = pseudoElement(pseudoElementSpecifier))
2224 return element->computedStyle();
2225
2226 // FIXME: Find and use the renderer from the pseudo element instead of the actual element so that the 'length'
2227 // properties, which are only known by the renderer because it did the layout, will be correct and so that the
2228 // values returned for the ":selection" pseudo-element will be correct.
2229 if (RenderStyle* usedStyle = renderStyle()) {
2230 if (pseudoElementSpecifier) {
2231 RenderStyle* cachedPseudoStyle = usedStyle->getCachedPseudoStyle(pseudoElementSpecifier);
2232 return cachedPseudoStyle ? cachedPseudoStyle : usedStyle;
2233 } else
2234 return usedStyle;
2235 }
2236
2237 if (!attached())
2238 // FIXME: Try to do better than this. Ensure that styleForElement() works for elements that are not in the
2239 // document tree and figure out when to destroy the computed style for such elements.
2240 return 0;
2241
2242 ElementRareData* data = ensureElementRareData();
2243 if (!data->computedStyle())
2244 data->setComputedStyle(document()->styleForElementIgnoringPendingStylesheets(this));
2245 return pseudoElementSpecifier ? data->computedStyle()->getCachedPseudoStyle(pseudoElementSpecifier) : data->computedStyle();
2246}
2247
2248void Element::setStyleAffectedByEmpty()
2249{
2250 ensureElementRareData()->setStyleAffectedByEmpty(true);
2251}
2252
2253void Element::setChildrenAffectedByHover(bool value)
2254{
2255 if (value || hasRareData())
2256 ensureElementRareData()->setChildrenAffectedByHover(value);
2257}
2258
2259void Element::setChildrenAffectedByActive(bool value)
2260{
2261 if (value || hasRareData())
2262 ensureElementRareData()->setChildrenAffectedByActive(value);
2263}
2264
2265void Element::setChildrenAffectedByDrag(bool value)
2266{
2267 if (value || hasRareData())
2268 ensureElementRareData()->setChildrenAffectedByDrag(value);
2269}
2270
2271void Element::setChildrenAffectedByFirstChildRules()
2272{
2273 ensureElementRareData()->setChildrenAffectedByFirstChildRules(true);
2274}
2275
2276void Element::setChildrenAffectedByLastChildRules()
2277{
2278 ensureElementRareData()->setChildrenAffectedByLastChildRules(true);
2279}
2280
2281void Element::setChildrenAffectedByDirectAdjacentRules()
2282{
2283 ensureElementRareData()->setChildrenAffectedByDirectAdjacentRules(true);
2284}
2285
2286void Element::setChildrenAffectedByForwardPositionalRules()
2287{
2288 ensureElementRareData()->setChildrenAffectedByForwardPositionalRules(true);
2289}
2290
2291void Element::setChildrenAffectedByBackwardPositionalRules()
2292{
2293 ensureElementRareData()->setChildrenAffectedByBackwardPositionalRules(true);
2294}
2295
2296void Element::setChildIndex(unsigned index)
2297{
2298 ElementRareData* rareData = ensureElementRareData();
2299 if (RenderStyle* style = renderStyle())
2300 style->setUnique();
2301 rareData->setChildIndex(index);
2302}
2303
2304bool Element::hasFlagsSetDuringStylingOfChildren() const
2305{
2306 if (!hasRareData())
2307 return false;
2308 return rareDataChildrenAffectedByHover()
2309 || rareDataChildrenAffectedByActive()
2310 || rareDataChildrenAffectedByDrag()
2311 || rareDataChildrenAffectedByFirstChildRules()
2312 || rareDataChildrenAffectedByLastChildRules()
2313 || rareDataChildrenAffectedByDirectAdjacentRules()
2314 || rareDataChildrenAffectedByForwardPositionalRules()
2315 || rareDataChildrenAffectedByBackwardPositionalRules();
2316}
2317
2318bool Element::rareDataStyleAffectedByEmpty() const
2319{
2320 ASSERT(hasRareData());
2321 return elementRareData()->styleAffectedByEmpty();
2322}
2323
2324bool Element::rareDataChildrenAffectedByHover() const
2325{
2326 ASSERT(hasRareData());
2327 return elementRareData()->childrenAffectedByHover();
2328}
2329
2330bool Element::rareDataChildrenAffectedByActive() const
2331{
2332 ASSERT(hasRareData());
2333 return elementRareData()->childrenAffectedByActive();
2334}
2335
2336bool Element::rareDataChildrenAffectedByDrag() const
2337{
2338 ASSERT(hasRareData());
2339 return elementRareData()->childrenAffectedByDrag();
2340}
2341
2342bool Element::rareDataChildrenAffectedByFirstChildRules() const
2343{
2344 ASSERT(hasRareData());
2345 return elementRareData()->childrenAffectedByFirstChildRules();
2346}
2347
2348bool Element::rareDataChildrenAffectedByLastChildRules() const
2349{
2350 ASSERT(hasRareData());
2351 return elementRareData()->childrenAffectedByLastChildRules();
2352}
2353
2354bool Element::rareDataChildrenAffectedByDirectAdjacentRules() const
2355{
2356 ASSERT(hasRareData());
2357 return elementRareData()->childrenAffectedByDirectAdjacentRules();
2358}
2359
2360bool Element::rareDataChildrenAffectedByForwardPositionalRules() const
2361{
2362 ASSERT(hasRareData());
2363 return elementRareData()->childrenAffectedByForwardPositionalRules();
2364}
2365
2366bool Element::rareDataChildrenAffectedByBackwardPositionalRules() const
2367{
2368 ASSERT(hasRareData());
2369 return elementRareData()->childrenAffectedByBackwardPositionalRules();
2370}
2371
2372unsigned Element::rareDataChildIndex() const
2373{
2374 ASSERT(hasRareData());
2375 return elementRareData()->childIndex();
2376}
2377
2378void Element::setIsInCanvasSubtree(bool isInCanvasSubtree)
2379{
2380 ensureElementRareData()->setIsInCanvasSubtree(isInCanvasSubtree);
2381}
2382
2383bool Element::isInCanvasSubtree() const
2384{
2385 return hasRareData() && elementRareData()->isInCanvasSubtree();
2386}
2387
Ben Murdoch591b9582013-07-10 11:41:44 +01002388void Element::setIsInsideRegion(bool value)
2389{
2390 if (value == isInsideRegion())
2391 return;
2392
2393 ensureElementRareData()->setIsInsideRegion(value);
2394}
2395
2396bool Element::isInsideRegion() const
2397{
2398 return hasRareData() ? elementRareData()->isInsideRegion() : false;
2399}
2400
2401void Element::setRegionOversetState(RegionOversetState state)
2402{
2403 ensureElementRareData()->setRegionOversetState(state);
2404}
2405
2406RegionOversetState Element::regionOversetState() const
2407{
2408 return hasRareData() ? elementRareData()->regionOversetState() : RegionUndefined;
2409}
2410
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002411AtomicString Element::computeInheritedLanguage() const
2412{
2413 const Node* n = this;
2414 AtomicString value;
2415 // The language property is inherited, so we iterate over the parents to find the first language.
2416 do {
2417 if (n->isElementNode()) {
2418 if (const ElementData* elementData = toElement(n)->elementData()) {
2419 // Spec: xml:lang takes precedence -- http://www.w3.org/TR/xhtml1/#C_7
2420 if (const Attribute* attribute = elementData->getAttributeItem(XMLNames::langAttr))
2421 value = attribute->value();
2422 else if (const Attribute* attribute = elementData->getAttributeItem(HTMLNames::langAttr))
2423 value = attribute->value();
2424 }
2425 } else if (n->isDocumentNode()) {
2426 // checking the MIME content-language
2427 value = toDocument(n)->contentLanguage();
2428 }
2429
2430 n = n->parentNode();
2431 } while (n && value.isNull());
2432
2433 return value;
2434}
2435
2436Locale& Element::locale() const
2437{
2438 return document()->getCachedLocale(computeInheritedLanguage());
2439}
2440
2441void Element::cancelFocusAppearanceUpdate()
2442{
2443 if (hasRareData())
2444 elementRareData()->setNeedsFocusAppearanceUpdateSoonAfterAttach(false);
Ben Murdoch7757ec22013-07-23 11:17:36 +01002445 if (document()->focusedElement() == this)
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002446 document()->cancelFocusAppearanceUpdate();
2447}
2448
2449void Element::normalizeAttributes()
2450{
2451 if (!hasAttributes())
2452 return;
2453 for (unsigned i = 0; i < attributeCount(); ++i) {
2454 if (RefPtr<Attr> attr = attrIfExists(attributeItem(i)->name()))
2455 attr->normalize();
2456 }
2457}
2458
2459void Element::updatePseudoElement(PseudoId pseudoId, StyleChange change)
2460{
2461 PseudoElement* element = pseudoElement(pseudoId);
2462 if (element && (needsStyleRecalc() || shouldRecalcStyle(change, element))) {
2463 // PseudoElement styles hang off their parent element's style so if we needed
2464 // a style recalc we should Force one on the pseudo.
2465 element->recalcStyle(needsStyleRecalc() ? Force : change);
2466
2467 // Wait until our parent is not displayed or pseudoElementRendererIsNeeded
2468 // is false, otherwise we could continously create and destroy PseudoElements
2469 // when RenderObject::isChildAllowed on our parent returns false for the
2470 // PseudoElement's renderer for each style recalc.
2471 if (!renderer() || !pseudoElementRendererIsNeeded(renderer()->getCachedPseudoStyle(pseudoId)))
Torne (Richard Coles)521d96e2013-06-19 11:58:24 +01002472 elementRareData()->setPseudoElement(pseudoId, 0);
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002473 } else if (change >= Inherit || needsStyleRecalc())
2474 createPseudoElementIfNeeded(pseudoId);
2475}
2476
2477void Element::createPseudoElementIfNeeded(PseudoId pseudoId)
2478{
Ben Murdoche69819b2013-07-17 14:56:49 +01002479 if ((pseudoId == BEFORE || pseudoId == AFTER) && !document()->styleSheetCollection()->usesBeforeAfterRules())
2480 return;
2481
2482 if (pseudoId == BACKDROP && !isInTopLayer())
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002483 return;
2484
2485 if (!renderer() || !pseudoElementRendererIsNeeded(renderer()->getCachedPseudoStyle(pseudoId)))
2486 return;
2487
2488 if (!renderer()->canHaveGeneratedChildren())
2489 return;
2490
2491 ASSERT(!isPseudoElement());
2492 RefPtr<PseudoElement> element = PseudoElement::create(this, pseudoId);
Ben Murdoche69819b2013-07-17 14:56:49 +01002493 if (pseudoId == BACKDROP)
2494 document()->addToTopLayer(element.get(), this);
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002495 element->attach();
Ben Murdoche69819b2013-07-17 14:56:49 +01002496
Torne (Richard Coles)521d96e2013-06-19 11:58:24 +01002497 ensureElementRareData()->setPseudoElement(pseudoId, element.release());
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002498}
2499
2500PseudoElement* Element::pseudoElement(PseudoId pseudoId) const
2501{
2502 return hasRareData() ? elementRareData()->pseudoElement(pseudoId) : 0;
2503}
2504
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002505RenderObject* Element::pseudoElementRenderer(PseudoId pseudoId) const
2506{
2507 if (PseudoElement* element = pseudoElement(pseudoId))
2508 return element->renderer();
2509 return 0;
2510}
2511
Ben Murdochdf957042013-08-06 11:01:27 +01002512bool Element::webkitMatchesSelector(const String& selector, ExceptionState& es)
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002513{
2514 if (selector.isEmpty()) {
Ben Murdochdf957042013-08-06 11:01:27 +01002515 es.throwDOMException(SyntaxError);
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002516 return false;
2517 }
2518
Ben Murdochdf957042013-08-06 11:01:27 +01002519 SelectorQuery* selectorQuery = document()->selectorQueryCache()->add(selector, document(), es);
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002520 if (!selectorQuery)
2521 return false;
2522 return selectorQuery->matches(this);
2523}
2524
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002525DOMTokenList* Element::classList()
2526{
2527 ElementRareData* data = ensureElementRareData();
2528 if (!data->classList())
2529 data->setClassList(ClassList::create(this));
2530 return data->classList();
2531}
2532
2533DOMStringMap* Element::dataset()
2534{
2535 ElementRareData* data = ensureElementRareData();
2536 if (!data->dataset())
2537 data->setDataset(DatasetDOMStringMap::create(this));
2538 return data->dataset();
2539}
2540
2541KURL Element::getURLAttribute(const QualifiedName& name) const
2542{
2543#if !ASSERT_DISABLED
2544 if (elementData()) {
2545 if (const Attribute* attribute = getAttributeItem(name))
2546 ASSERT(isURLAttribute(*attribute));
2547 }
2548#endif
2549 return document()->completeURL(stripLeadingAndTrailingHTMLSpaces(getAttribute(name)));
2550}
2551
2552KURL Element::getNonEmptyURLAttribute(const QualifiedName& name) const
2553{
2554#if !ASSERT_DISABLED
2555 if (elementData()) {
2556 if (const Attribute* attribute = getAttributeItem(name))
2557 ASSERT(isURLAttribute(*attribute));
2558 }
2559#endif
2560 String value = stripLeadingAndTrailingHTMLSpaces(getAttribute(name));
2561 if (value.isEmpty())
2562 return KURL();
2563 return document()->completeURL(value);
2564}
2565
2566int Element::getIntegralAttribute(const QualifiedName& attributeName) const
2567{
2568 return getAttribute(attributeName).string().toInt();
2569}
2570
2571void Element::setIntegralAttribute(const QualifiedName& attributeName, int value)
2572{
2573 // FIXME: Need an AtomicString version of String::number.
2574 setAttribute(attributeName, String::number(value));
2575}
2576
2577unsigned Element::getUnsignedIntegralAttribute(const QualifiedName& attributeName) const
2578{
2579 return getAttribute(attributeName).string().toUInt();
2580}
2581
2582void Element::setUnsignedIntegralAttribute(const QualifiedName& attributeName, unsigned value)
2583{
2584 // FIXME: Need an AtomicString version of String::number.
2585 setAttribute(attributeName, String::number(value));
2586}
2587
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002588bool Element::childShouldCreateRenderer(const NodeRenderingContext& childContext) const
2589{
2590 // Only create renderers for SVG elements whose parents are SVG elements, or for proper <svg xmlns="svgNS"> subdocuments.
2591 if (childContext.node()->isSVGElement())
2592 return childContext.node()->hasTagName(SVGNames::svgTag) || isSVGElement();
2593
2594 return ContainerNode::childShouldCreateRenderer(childContext);
2595}
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002596
2597void Element::webkitRequestFullscreen()
2598{
Torne (Richard Coles)f5e4ad52013-08-05 13:57:57 +01002599 FullscreenElementStack::from(document())->requestFullScreenForElement(this, ALLOW_KEYBOARD_INPUT, FullscreenElementStack::EnforceIFrameAllowFullScreenRequirement);
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002600}
2601
2602void Element::webkitRequestFullScreen(unsigned short flags)
2603{
Torne (Richard Coles)f5e4ad52013-08-05 13:57:57 +01002604 FullscreenElementStack::from(document())->requestFullScreenForElement(this, (flags | LEGACY_MOZILLA_REQUEST), FullscreenElementStack::EnforceIFrameAllowFullScreenRequirement);
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002605}
2606
2607bool Element::containsFullScreenElement() const
2608{
2609 return hasRareData() && elementRareData()->containsFullScreenElement();
2610}
2611
2612void Element::setContainsFullScreenElement(bool flag)
2613{
2614 ensureElementRareData()->setContainsFullScreenElement(flag);
Ben Murdoche69819b2013-07-17 14:56:49 +01002615 setNeedsStyleRecalc(SubtreeStyleChange);
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002616}
2617
2618static Element* parentCrossingFrameBoundaries(Element* element)
2619{
2620 ASSERT(element);
2621 return element->parentElement() ? element->parentElement() : element->document()->ownerElement();
2622}
2623
2624void Element::setContainsFullScreenElementOnAncestorsCrossingFrameBoundaries(bool flag)
2625{
2626 Element* element = this;
2627 while ((element = parentCrossingFrameBoundaries(element)))
2628 element->setContainsFullScreenElement(flag);
2629}
2630
2631bool Element::isInTopLayer() const
2632{
2633 return hasRareData() && elementRareData()->isInTopLayer();
2634}
2635
2636void Element::setIsInTopLayer(bool inTopLayer)
2637{
2638 if (isInTopLayer() == inTopLayer)
2639 return;
2640 ensureElementRareData()->setIsInTopLayer(inTopLayer);
2641
2642 // We must ensure a reattach occurs so the renderer is inserted in the correct sibling order under RenderView according to its
2643 // top layer position, or in its usual place if not in the top layer.
Torne (Richard Coles)93ac45c2013-05-29 14:40:20 +01002644 lazyReattachIfAttached();
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002645}
2646
2647void Element::webkitRequestPointerLock()
2648{
2649 if (document()->page())
2650 document()->page()->pointerLockController()->requestPointerLock(this);
2651}
2652
2653SpellcheckAttributeState Element::spellcheckAttributeState() const
2654{
2655 const AtomicString& value = getAttribute(HTMLNames::spellcheckAttr);
2656 if (value == nullAtom)
2657 return SpellcheckAttributeDefault;
2658 if (equalIgnoringCase(value, "true") || equalIgnoringCase(value, ""))
2659 return SpellcheckAttributeTrue;
2660 if (equalIgnoringCase(value, "false"))
2661 return SpellcheckAttributeFalse;
2662
2663 return SpellcheckAttributeDefault;
2664}
2665
2666bool Element::isSpellCheckingEnabled() const
2667{
2668 for (const Element* element = this; element; element = element->parentOrShadowHostElement()) {
2669 switch (element->spellcheckAttributeState()) {
2670 case SpellcheckAttributeTrue:
2671 return true;
2672 case SpellcheckAttributeFalse:
2673 return false;
2674 case SpellcheckAttributeDefault:
2675 break;
2676 }
2677 }
2678
2679 return true;
2680}
2681
2682RenderRegion* Element::renderRegion() const
2683{
2684 if (renderer() && renderer()->isRenderRegion())
2685 return toRenderRegion(renderer());
2686
2687 return 0;
2688}
2689
Ben Murdoch591b9582013-07-10 11:41:44 +01002690bool Element::shouldMoveToFlowThread(RenderStyle* styleToUse) const
2691{
2692 ASSERT(styleToUse);
2693
Torne (Richard Coles)f5e4ad52013-08-05 13:57:57 +01002694 if (FullscreenElementStack::isActiveFullScreenElement(this))
Ben Murdoch591b9582013-07-10 11:41:44 +01002695 return false;
2696
2697 if (isInShadowTree())
2698 return false;
2699
2700 if (styleToUse->flowThread().isEmpty())
2701 return false;
2702
2703 return !isRegisteredWithNamedFlow();
2704}
2705
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002706const AtomicString& Element::webkitRegionOverset() const
2707{
2708 document()->updateLayoutIgnorePendingStylesheets();
2709
2710 DEFINE_STATIC_LOCAL(AtomicString, undefinedState, ("undefined", AtomicString::ConstructFromLiteral));
2711 if (!RuntimeEnabledFeatures::cssRegionsEnabled() || !renderRegion())
2712 return undefinedState;
2713
Ben Murdoch591b9582013-07-10 11:41:44 +01002714 switch (renderRegion()->regionOversetState()) {
2715 case RegionFit: {
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002716 DEFINE_STATIC_LOCAL(AtomicString, fitState, ("fit", AtomicString::ConstructFromLiteral));
2717 return fitState;
2718 }
Ben Murdoch591b9582013-07-10 11:41:44 +01002719 case RegionEmpty: {
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002720 DEFINE_STATIC_LOCAL(AtomicString, emptyState, ("empty", AtomicString::ConstructFromLiteral));
2721 return emptyState;
2722 }
Ben Murdoch591b9582013-07-10 11:41:44 +01002723 case RegionOverset: {
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002724 DEFINE_STATIC_LOCAL(AtomicString, overflowState, ("overset", AtomicString::ConstructFromLiteral));
2725 return overflowState;
2726 }
Ben Murdoch591b9582013-07-10 11:41:44 +01002727 case RegionUndefined:
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002728 return undefinedState;
2729 }
2730
2731 ASSERT_NOT_REACHED();
2732 return undefinedState;
2733}
2734
2735Vector<RefPtr<Range> > Element::webkitGetRegionFlowRanges() const
2736{
2737 document()->updateLayoutIgnorePendingStylesheets();
2738
2739 Vector<RefPtr<Range> > rangeObjects;
2740 if (RuntimeEnabledFeatures::cssRegionsEnabled() && renderer() && renderer()->isRenderRegion()) {
2741 RenderRegion* region = toRenderRegion(renderer());
2742 if (region->isValid())
2743 region->getRanges(rangeObjects);
2744 }
2745
2746 return rangeObjects;
2747}
2748
2749#ifndef NDEBUG
2750bool Element::fastAttributeLookupAllowed(const QualifiedName& name) const
2751{
2752 if (name == HTMLNames::styleAttr)
2753 return false;
2754
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002755 if (isSVGElement())
2756 return !static_cast<const SVGElement*>(this)->isAnimatableAttribute(name);
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002757
2758 return true;
2759}
2760#endif
2761
2762#ifdef DUMP_NODE_STATISTICS
2763bool Element::hasNamedNodeMap() const
2764{
2765 return hasRareData() && elementRareData()->attributeMap();
2766}
2767#endif
2768
Ben Murdoch3c9e4ae2013-08-12 14:20:44 +01002769void Element::updateName(const AtomicString& oldName, const AtomicString& newName)
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002770{
Ben Murdoch3c9e4ae2013-08-12 14:20:44 +01002771 if (!isInTreeScope())
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002772 return;
2773
2774 if (oldName == newName)
2775 return;
2776
Ben Murdoch3c9e4ae2013-08-12 14:20:44 +01002777 updateNameForTreeScope(treeScope(), oldName, newName);
2778
2779 if (!inDocument() || isInShadowTree())
2780 return;
2781
2782 Document* htmlDocument = document();
2783 if (!htmlDocument->isHTMLDocument())
2784 return;
2785
2786 updateNameForDocument(toHTMLDocument(htmlDocument), oldName, newName);
2787}
2788
2789void Element::updateNameForTreeScope(TreeScope* scope, const AtomicString& oldName, const AtomicString& newName)
2790{
2791 ASSERT(isInTreeScope());
2792 ASSERT(oldName != newName);
2793
2794 if (!oldName.isEmpty())
2795 scope->removeElementByName(oldName, this);
2796 if (!newName.isEmpty())
2797 scope->addElementByName(newName, this);
2798}
2799
2800void Element::updateNameForDocument(HTMLDocument* document, const AtomicString& oldName, const AtomicString& newName)
2801{
2802 ASSERT(inDocument() && !isInShadowTree());
2803 ASSERT(oldName != newName);
2804
Ben Murdochdf957042013-08-06 11:01:27 +01002805 if (shouldRegisterAsNamedItem())
2806 updateNamedItemRegistration(oldName, newName);
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002807}
2808
Ben Murdoch3c9e4ae2013-08-12 14:20:44 +01002809void Element::updateId(const AtomicString& oldId, const AtomicString& newId)
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002810{
2811 if (!isInTreeScope())
2812 return;
2813
2814 if (oldId == newId)
2815 return;
2816
Ben Murdoch3c9e4ae2013-08-12 14:20:44 +01002817 updateIdForTreeScope(treeScope(), oldId, newId);
2818
2819 if (!inDocument() || isInShadowTree())
2820 return;
2821
2822 Document* htmlDocument = document();
2823 if (!htmlDocument->isHTMLDocument())
2824 return;
2825
2826 updateIdForDocument(toHTMLDocument(htmlDocument), oldId, newId);
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002827}
2828
Ben Murdoch3c9e4ae2013-08-12 14:20:44 +01002829void Element::updateIdForTreeScope(TreeScope* scope, const AtomicString& oldId, const AtomicString& newId)
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002830{
2831 ASSERT(isInTreeScope());
2832 ASSERT(oldId != newId);
2833
2834 if (!oldId.isEmpty())
2835 scope->removeElementById(oldId, this);
2836 if (!newId.isEmpty())
2837 scope->addElementById(newId, this);
Ben Murdoch3c9e4ae2013-08-12 14:20:44 +01002838}
2839
2840void Element::updateIdForDocument(HTMLDocument* document, const AtomicString& oldId, const AtomicString& newId)
2841{
2842 ASSERT(inDocument() && !isInShadowTree());
2843 ASSERT(oldId != newId);
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002844
Ben Murdochdf957042013-08-06 11:01:27 +01002845 if (shouldRegisterAsExtraNamedItem())
2846 updateExtraNamedItemRegistration(oldId, newId);
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002847}
2848
2849void Element::updateLabel(TreeScope* scope, const AtomicString& oldForAttributeValue, const AtomicString& newForAttributeValue)
2850{
2851 ASSERT(hasTagName(labelTag));
2852
2853 if (!inDocument())
2854 return;
2855
2856 if (oldForAttributeValue == newForAttributeValue)
2857 return;
2858
2859 if (!oldForAttributeValue.isEmpty())
Ben Murdoche69819b2013-07-17 14:56:49 +01002860 scope->removeLabel(oldForAttributeValue, toHTMLLabelElement(this));
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002861 if (!newForAttributeValue.isEmpty())
Ben Murdoche69819b2013-07-17 14:56:49 +01002862 scope->addLabel(newForAttributeValue, toHTMLLabelElement(this));
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002863}
2864
Ben Murdoch7757ec22013-07-23 11:17:36 +01002865static bool hasSelectorForAttribute(Document* document, const AtomicString& localName)
2866{
2867 return document->styleResolver() && document->styleResolver()->ruleFeatureSet().hasSelectorForAttribute(localName);
2868}
2869
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002870void Element::willModifyAttribute(const QualifiedName& name, const AtomicString& oldValue, const AtomicString& newValue)
2871{
2872 if (isIdAttributeName(name))
2873 updateId(oldValue, newValue);
2874 else if (name == HTMLNames::nameAttr)
2875 updateName(oldValue, newValue);
2876 else if (name == HTMLNames::forAttr && hasTagName(labelTag)) {
2877 TreeScope* scope = treeScope();
2878 if (scope->shouldCacheLabelsByForAttribute())
2879 updateLabel(scope, oldValue, newValue);
2880 }
2881
2882 if (oldValue != newValue) {
Ben Murdoch7757ec22013-07-23 11:17:36 +01002883 if (attached() && hasSelectorForAttribute(document(), name.localName()))
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002884 setNeedsStyleRecalc();
Ben Murdoche69819b2013-07-17 14:56:49 +01002885
2886 if (isUpgradedCustomElement())
Ben Murdoch83750172013-07-24 10:36:59 +01002887 CustomElement::attributeDidChange(this, name.localName(), oldValue, newValue);
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002888 }
2889
2890 if (OwnPtr<MutationObserverInterestGroup> recipients = MutationObserverInterestGroup::createForAttributesMutation(this, name))
2891 recipients->enqueueMutationRecord(MutationRecord::createAttributes(this, name, oldValue));
2892
2893 InspectorInstrumentation::willModifyDOMAttr(document(), this, oldValue, newValue);
2894}
2895
2896void Element::didAddAttribute(const QualifiedName& name, const AtomicString& value)
2897{
2898 attributeChanged(name, value);
2899 InspectorInstrumentation::didModifyDOMAttr(document(), this, name.localName(), value);
2900 dispatchSubtreeModifiedEvent();
2901}
2902
2903void Element::didModifyAttribute(const QualifiedName& name, const AtomicString& value)
2904{
2905 attributeChanged(name, value);
2906 InspectorInstrumentation::didModifyDOMAttr(document(), this, name.localName(), value);
2907 // Do not dispatch a DOMSubtreeModified event here; see bug 81141.
2908}
2909
2910void Element::didRemoveAttribute(const QualifiedName& name)
2911{
2912 attributeChanged(name, nullAtom);
2913 InspectorInstrumentation::didRemoveDOMAttr(document(), this, name.localName());
2914 dispatchSubtreeModifiedEvent();
2915}
2916
Ben Murdoche69819b2013-07-17 14:56:49 +01002917void Element::didMoveToNewDocument(Document* oldDocument)
2918{
2919 Node::didMoveToNewDocument(oldDocument);
2920
2921 // If the documents differ by quirks mode then they differ by case sensitivity
2922 // for class and id names so we need to go through the attribute change logic
2923 // to pick up the new casing in the ElementData.
2924 if (oldDocument->inQuirksMode() != document()->inQuirksMode()) {
2925 if (hasID())
2926 setIdAttribute(getIdAttribute());
2927 if (hasClass())
2928 setAttribute(HTMLNames::classAttr, getClassAttribute());
2929 }
2930}
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002931
Ben Murdochdf957042013-08-06 11:01:27 +01002932void Element::updateNamedItemRegistration(const AtomicString& oldName, const AtomicString& newName)
2933{
Ben Murdoch3c9e4ae2013-08-12 14:20:44 +01002934 ASSERT(document()->isHTMLDocument());
Ben Murdochdf957042013-08-06 11:01:27 +01002935
2936 if (!oldName.isEmpty())
2937 toHTMLDocument(document())->removeNamedItem(oldName);
2938
2939 if (!newName.isEmpty())
2940 toHTMLDocument(document())->addNamedItem(newName);
2941}
2942
2943void Element::updateExtraNamedItemRegistration(const AtomicString& oldId, const AtomicString& newId)
2944{
Ben Murdoch3c9e4ae2013-08-12 14:20:44 +01002945 ASSERT(document()->isHTMLDocument());
Ben Murdochdf957042013-08-06 11:01:27 +01002946
2947 if (!oldId.isEmpty())
2948 toHTMLDocument(document())->removeExtraNamedItem(oldId);
2949
2950 if (!newId.isEmpty())
2951 toHTMLDocument(document())->addExtraNamedItem(newId);
2952}
2953
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002954PassRefPtr<HTMLCollection> Element::ensureCachedHTMLCollection(CollectionType type)
2955{
2956 if (HTMLCollection* collection = cachedHTMLCollection(type))
2957 return collection;
2958
2959 RefPtr<HTMLCollection> collection;
2960 if (type == TableRows) {
2961 ASSERT(hasTagName(tableTag));
2962 return ensureRareData()->ensureNodeLists()->addCacheWithAtomicName<HTMLTableRowsCollection>(this, type);
2963 } else if (type == SelectOptions) {
2964 ASSERT(hasTagName(selectTag));
2965 return ensureRareData()->ensureNodeLists()->addCacheWithAtomicName<HTMLOptionsCollection>(this, type);
2966 } else if (type == FormControls) {
2967 ASSERT(hasTagName(formTag) || hasTagName(fieldsetTag));
2968 return ensureRareData()->ensureNodeLists()->addCacheWithAtomicName<HTMLFormControlsCollection>(this, type);
2969 }
2970 return ensureRareData()->ensureNodeLists()->addCacheWithAtomicName<HTMLCollection>(this, type);
2971}
2972
Ben Murdoch591b9582013-07-10 11:41:44 +01002973static void scheduleLayerUpdateCallback(Node* node)
Torne (Richard Coles)93ac45c2013-05-29 14:40:20 +01002974{
Ben Murdoche69819b2013-07-17 14:56:49 +01002975 // Notify the renderer even is the styles are identical since it may need to
2976 // create or destroy a RenderLayer.
2977 node->setNeedsStyleRecalc(LocalStyleChange, StyleChangeFromRenderer);
Torne (Richard Coles)93ac45c2013-05-29 14:40:20 +01002978}
2979
Ben Murdoch591b9582013-07-10 11:41:44 +01002980void Element::scheduleLayerUpdate()
Torne (Richard Coles)93ac45c2013-05-29 14:40:20 +01002981{
2982 if (postAttachCallbacksAreSuspended())
Ben Murdoch591b9582013-07-10 11:41:44 +01002983 queuePostAttachCallback(scheduleLayerUpdateCallback, this);
Torne (Richard Coles)93ac45c2013-05-29 14:40:20 +01002984 else
Ben Murdoche69819b2013-07-17 14:56:49 +01002985 scheduleLayerUpdateCallback(this);
Torne (Richard Coles)93ac45c2013-05-29 14:40:20 +01002986}
2987
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002988HTMLCollection* Element::cachedHTMLCollection(CollectionType type)
2989{
2990 return hasRareData() && rareData()->nodeLists() ? rareData()->nodeLists()->cacheWithAtomicName<HTMLCollection>(type) : 0;
2991}
2992
2993IntSize Element::savedLayerScrollOffset() const
2994{
2995 return hasRareData() ? elementRareData()->savedLayerScrollOffset() : IntSize();
2996}
2997
2998void Element::setSavedLayerScrollOffset(const IntSize& size)
2999{
3000 if (size.isZero() && !hasRareData())
3001 return;
3002 ensureElementRareData()->setSavedLayerScrollOffset(size);
3003}
3004
3005PassRefPtr<Attr> Element::attrIfExists(const QualifiedName& name)
3006{
3007 if (AttrNodeList* attrNodeList = attrNodeListForElement(this))
3008 return findAttrNodeInList(attrNodeList, name);
3009 return 0;
3010}
3011
3012PassRefPtr<Attr> Element::ensureAttr(const QualifiedName& name)
3013{
3014 AttrNodeList* attrNodeList = ensureAttrNodeListForElement(this);
3015 RefPtr<Attr> attrNode = findAttrNodeInList(attrNodeList, name);
3016 if (!attrNode) {
3017 attrNode = Attr::create(this, name);
3018 treeScope()->adoptIfNeeded(attrNode.get());
3019 attrNodeList->append(attrNode);
3020 }
3021 return attrNode.release();
3022}
3023
3024void Element::detachAttrNodeFromElementWithValue(Attr* attrNode, const AtomicString& value)
3025{
3026 ASSERT(hasSyntheticAttrChildNodes());
3027 attrNode->detachFromElementWithValue(value);
3028
3029 AttrNodeList* attrNodeList = attrNodeListForElement(this);
3030 for (unsigned i = 0; i < attrNodeList->size(); ++i) {
3031 if (attrNodeList->at(i)->qualifiedName() == attrNode->qualifiedName()) {
3032 attrNodeList->remove(i);
3033 if (attrNodeList->isEmpty())
3034 removeAttrNodeListForElement(this);
3035 return;
3036 }
3037 }
3038 ASSERT_NOT_REACHED();
3039}
3040
3041void Element::detachAllAttrNodesFromElement()
3042{
3043 AttrNodeList* attrNodeList = attrNodeListForElement(this);
3044 ASSERT(attrNodeList);
3045
3046 for (unsigned i = 0; i < attributeCount(); ++i) {
3047 const Attribute* attribute = attributeItem(i);
3048 if (RefPtr<Attr> attrNode = findAttrNodeInList(attrNodeList, attribute->name()))
3049 attrNode->detachFromElementWithValue(attribute->value());
3050 }
3051
3052 removeAttrNodeListForElement(this);
3053}
3054
3055void Element::willRecalcStyle(StyleChange)
3056{
3057 ASSERT(hasCustomStyleCallbacks());
3058}
3059
3060void Element::didRecalcStyle(StyleChange)
3061{
3062 ASSERT(hasCustomStyleCallbacks());
3063}
3064
3065
3066PassRefPtr<RenderStyle> Element::customStyleForRenderer()
3067{
3068 ASSERT(hasCustomStyleCallbacks());
3069 return 0;
3070}
3071
3072void Element::cloneAttributesFromElement(const Element& other)
3073{
3074 if (hasSyntheticAttrChildNodes())
3075 detachAllAttrNodesFromElement();
3076
3077 other.synchronizeAllAttributes();
3078 if (!other.m_elementData) {
3079 m_elementData.clear();
3080 return;
3081 }
3082
Ben Murdoch3c9e4ae2013-08-12 14:20:44 +01003083 // We can't update window and document's named item maps since the presence of image and object elements depend on other attributes and children.
3084 // Fortunately, those named item maps are only updated when this element is in the document, which should never be the case.
3085 ASSERT(!inDocument());
3086
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01003087 const AtomicString& oldID = getIdAttribute();
3088 const AtomicString& newID = other.getIdAttribute();
3089
3090 if (!oldID.isNull() || !newID.isNull())
3091 updateId(oldID, newID);
3092
3093 const AtomicString& oldName = getNameAttribute();
3094 const AtomicString& newName = other.getNameAttribute();
3095
3096 if (!oldName.isNull() || !newName.isNull())
3097 updateName(oldName, newName);
3098
Ben Murdoche69819b2013-07-17 14:56:49 +01003099 // Quirks mode makes class and id not case sensitive. We can't share the ElementData
3100 // if the idForStyleResolution and the className need different casing.
3101 bool ownerDocumentsHaveDifferentCaseSensitivity = false;
3102 if (other.hasClass() || other.hasID())
3103 ownerDocumentsHaveDifferentCaseSensitivity = other.document()->inQuirksMode() != document()->inQuirksMode();
3104
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01003105 // 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 +01003106 // We can only do this if there is no CSSOM wrapper for other's inline style, and there are no presentation attributes,
3107 // and sharing the data won't result in different case sensitivity of class or id.
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01003108 if (other.m_elementData->isUnique()
Ben Murdoche69819b2013-07-17 14:56:49 +01003109 && !ownerDocumentsHaveDifferentCaseSensitivity
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01003110 && !other.m_elementData->presentationAttributeStyle()
3111 && (!other.m_elementData->inlineStyle() || !other.m_elementData->inlineStyle()->hasCSSOMWrapper()))
3112 const_cast<Element&>(other).m_elementData = static_cast<const UniqueElementData*>(other.m_elementData.get())->makeShareableCopy();
3113
Ben Murdoche69819b2013-07-17 14:56:49 +01003114 if (!other.m_elementData->isUnique() && !ownerDocumentsHaveDifferentCaseSensitivity)
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01003115 m_elementData = other.m_elementData;
3116 else
3117 m_elementData = other.m_elementData->makeUniqueCopy();
3118
3119 for (unsigned i = 0; i < m_elementData->length(); ++i) {
3120 const Attribute* attribute = const_cast<const ElementData*>(m_elementData.get())->attributeItem(i);
3121 attributeChangedFromParserOrByCloning(attribute->name(), attribute->value(), ModifiedByCloning);
3122 }
3123}
3124
3125void Element::cloneDataFromElement(const Element& other)
3126{
3127 cloneAttributesFromElement(other);
3128 copyNonAttributePropertiesFromElement(other);
3129}
3130
3131void Element::createUniqueElementData()
3132{
3133 if (!m_elementData)
3134 m_elementData = UniqueElementData::create();
3135 else {
3136 ASSERT(!m_elementData->isUnique());
3137 m_elementData = static_cast<ShareableElementData*>(m_elementData.get())->makeUniqueCopy();
3138 }
3139}
3140
Ben Murdoch1fad5ca2013-08-07 11:05:11 +01003141InputMethodContext* Element::inputMethodContext()
Torne (Richard Coles)81a51572013-05-13 16:52:28 +01003142{
3143 return ensureElementRareData()->ensureInputMethodContext(toHTMLElement(this));
3144}
3145
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01003146bool Element::hasPendingResources() const
3147{
3148 return hasRareData() && elementRareData()->hasPendingResources();
3149}
3150
3151void Element::setHasPendingResources()
3152{
3153 ensureElementRareData()->setHasPendingResources(true);
3154}
3155
3156void Element::clearHasPendingResources()
3157{
3158 ensureElementRareData()->setHasPendingResources(false);
3159}
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01003160
Ben Murdoch591b9582013-07-10 11:41:44 +01003161struct PresentationAttributeCacheKey {
3162 PresentationAttributeCacheKey() : tagName(0) { }
Ben Murdoch83750172013-07-24 10:36:59 +01003163 StringImpl* tagName;
Ben Murdoch591b9582013-07-10 11:41:44 +01003164 // Only the values need refcounting.
Ben Murdoch83750172013-07-24 10:36:59 +01003165 Vector<pair<StringImpl*, AtomicString>, 3> attributesAndValues;
Ben Murdoch591b9582013-07-10 11:41:44 +01003166};
3167
3168struct PresentationAttributeCacheEntry {
3169 WTF_MAKE_FAST_ALLOCATED;
3170public:
3171 PresentationAttributeCacheKey key;
3172 RefPtr<StylePropertySet> value;
3173};
3174
3175typedef HashMap<unsigned, OwnPtr<PresentationAttributeCacheEntry>, AlreadyHashed> PresentationAttributeCache;
3176
3177static bool operator!=(const PresentationAttributeCacheKey& a, const PresentationAttributeCacheKey& b)
3178{
3179 if (a.tagName != b.tagName)
3180 return true;
3181 return a.attributesAndValues != b.attributesAndValues;
3182}
3183
3184static PresentationAttributeCache& presentationAttributeCache()
3185{
3186 DEFINE_STATIC_LOCAL(PresentationAttributeCache, cache, ());
3187 return cache;
3188}
3189
3190class PresentationAttributeCacheCleaner {
3191 WTF_MAKE_NONCOPYABLE(PresentationAttributeCacheCleaner); WTF_MAKE_FAST_ALLOCATED;
3192public:
3193 PresentationAttributeCacheCleaner()
3194 : m_hitCount(0)
3195 , m_cleanTimer(this, &PresentationAttributeCacheCleaner::cleanCache)
3196 {
3197 }
3198
3199 void didHitPresentationAttributeCache()
3200 {
3201 if (presentationAttributeCache().size() < minimumPresentationAttributeCacheSizeForCleaning)
3202 return;
3203
3204 m_hitCount++;
3205
3206 if (!m_cleanTimer.isActive())
3207 m_cleanTimer.startOneShot(presentationAttributeCacheCleanTimeInSeconds);
3208 }
3209
3210private:
3211 static const unsigned presentationAttributeCacheCleanTimeInSeconds = 60;
3212 static const int minimumPresentationAttributeCacheSizeForCleaning = 100;
3213 static const unsigned minimumPresentationAttributeCacheHitCountPerMinute = (100 * presentationAttributeCacheCleanTimeInSeconds) / 60;
3214
3215 void cleanCache(Timer<PresentationAttributeCacheCleaner>* timer)
3216 {
3217 ASSERT_UNUSED(timer, timer == &m_cleanTimer);
3218 unsigned hitCount = m_hitCount;
3219 m_hitCount = 0;
3220 if (hitCount > minimumPresentationAttributeCacheHitCountPerMinute)
3221 return;
3222 presentationAttributeCache().clear();
3223 }
3224
3225 unsigned m_hitCount;
3226 Timer<PresentationAttributeCacheCleaner> m_cleanTimer;
3227};
3228
3229static PresentationAttributeCacheCleaner& presentationAttributeCacheCleaner()
3230{
3231 DEFINE_STATIC_LOCAL(PresentationAttributeCacheCleaner, cleaner, ());
3232 return cleaner;
3233}
3234
3235void Element::synchronizeStyleAttributeInternal() const
3236{
3237 ASSERT(isStyledElement());
3238 ASSERT(elementData());
3239 ASSERT(elementData()->m_styleAttributeIsDirty);
3240 elementData()->m_styleAttributeIsDirty = false;
3241 if (const StylePropertySet* inlineStyle = this->inlineStyle())
3242 const_cast<Element*>(this)->setSynchronizedLazyAttribute(styleAttr, inlineStyle->asText());
3243}
3244
3245CSSStyleDeclaration* Element::style()
3246{
3247 if (!isStyledElement())
3248 return 0;
3249 return ensureMutableInlineStyle()->ensureInlineCSSStyleDeclaration(this);
3250}
3251
3252MutableStylePropertySet* Element::ensureMutableInlineStyle()
3253{
3254 ASSERT(isStyledElement());
3255 RefPtr<StylePropertySet>& inlineStyle = ensureUniqueElementData()->m_inlineStyle;
3256 if (!inlineStyle)
3257 inlineStyle = MutableStylePropertySet::create(strictToCSSParserMode(isHTMLElement() && !document()->inQuirksMode()));
3258 else if (!inlineStyle->isMutable())
3259 inlineStyle = inlineStyle->mutableCopy();
3260 ASSERT(inlineStyle->isMutable());
3261 return static_cast<MutableStylePropertySet*>(inlineStyle.get());
3262}
3263
3264PropertySetCSSStyleDeclaration* Element::inlineStyleCSSOMWrapper()
3265{
3266 if (!inlineStyle() || !inlineStyle()->hasCSSOMWrapper())
3267 return 0;
3268 PropertySetCSSStyleDeclaration* cssomWrapper = ensureMutableInlineStyle()->cssStyleDeclaration();
3269 ASSERT(cssomWrapper && cssomWrapper->parentElement() == this);
3270 return cssomWrapper;
3271}
3272
3273inline void Element::setInlineStyleFromString(const AtomicString& newStyleString)
3274{
3275 ASSERT(isStyledElement());
3276 RefPtr<StylePropertySet>& inlineStyle = elementData()->m_inlineStyle;
3277
3278 // Avoid redundant work if we're using shared attribute data with already parsed inline style.
3279 if (inlineStyle && !elementData()->isUnique())
3280 return;
3281
3282 // We reconstruct the property set instead of mutating if there is no CSSOM wrapper.
3283 // This makes wrapperless property sets immutable and so cacheable.
3284 if (inlineStyle && !inlineStyle->isMutable())
3285 inlineStyle.clear();
3286
3287 if (!inlineStyle) {
3288 inlineStyle = CSSParser::parseInlineStyleDeclaration(newStyleString, this);
3289 } else {
3290 ASSERT(inlineStyle->isMutable());
3291 static_pointer_cast<MutableStylePropertySet>(inlineStyle)->parseDeclaration(newStyleString, document()->elementSheet()->contents());
3292 }
3293}
3294
3295void Element::styleAttributeChanged(const AtomicString& newStyleString, AttributeModificationReason modificationReason)
3296{
3297 ASSERT(isStyledElement());
3298 WTF::OrdinalNumber startLineNumber = WTF::OrdinalNumber::beforeFirst();
3299 if (document() && document()->scriptableDocumentParser() && !document()->isInDocumentWrite())
3300 startLineNumber = document()->scriptableDocumentParser()->lineNumber();
3301
3302 if (newStyleString.isNull()) {
3303 if (PropertySetCSSStyleDeclaration* cssomWrapper = inlineStyleCSSOMWrapper())
3304 cssomWrapper->clearParentElement();
3305 ensureUniqueElementData()->m_inlineStyle.clear();
3306 } else if (modificationReason == ModifiedByCloning || document()->contentSecurityPolicy()->allowInlineStyle(document()->url(), startLineNumber)) {
3307 setInlineStyleFromString(newStyleString);
3308 }
3309
3310 elementData()->m_styleAttributeIsDirty = false;
3311
Ben Murdoche69819b2013-07-17 14:56:49 +01003312 setNeedsStyleRecalc(LocalStyleChange);
Ben Murdoch591b9582013-07-10 11:41:44 +01003313 InspectorInstrumentation::didInvalidateStyleAttr(document(), this);
3314}
3315
3316void Element::inlineStyleChanged()
3317{
3318 ASSERT(isStyledElement());
Ben Murdoche69819b2013-07-17 14:56:49 +01003319 setNeedsStyleRecalc(LocalStyleChange);
Ben Murdoch591b9582013-07-10 11:41:44 +01003320 ASSERT(elementData());
3321 elementData()->m_styleAttributeIsDirty = true;
3322 InspectorInstrumentation::didInvalidateStyleAttr(document(), this);
3323}
3324
3325bool Element::setInlineStyleProperty(CSSPropertyID propertyID, CSSValueID identifier, bool important)
3326{
3327 ASSERT(isStyledElement());
3328 ensureMutableInlineStyle()->setProperty(propertyID, cssValuePool().createIdentifierValue(identifier), important);
3329 inlineStyleChanged();
3330 return true;
3331}
3332
3333bool Element::setInlineStyleProperty(CSSPropertyID propertyID, CSSPropertyID identifier, bool important)
3334{
3335 ASSERT(isStyledElement());
3336 ensureMutableInlineStyle()->setProperty(propertyID, cssValuePool().createIdentifierValue(identifier), important);
3337 inlineStyleChanged();
3338 return true;
3339}
3340
3341bool Element::setInlineStyleProperty(CSSPropertyID propertyID, double value, CSSPrimitiveValue::UnitTypes unit, bool important)
3342{
3343 ASSERT(isStyledElement());
3344 ensureMutableInlineStyle()->setProperty(propertyID, cssValuePool().createValue(value, unit), important);
3345 inlineStyleChanged();
3346 return true;
3347}
3348
3349bool Element::setInlineStyleProperty(CSSPropertyID propertyID, const String& value, bool important)
3350{
3351 ASSERT(isStyledElement());
3352 bool changes = ensureMutableInlineStyle()->setProperty(propertyID, value, important, document()->elementSheet()->contents());
3353 if (changes)
3354 inlineStyleChanged();
3355 return changes;
3356}
3357
3358bool Element::removeInlineStyleProperty(CSSPropertyID propertyID)
3359{
3360 ASSERT(isStyledElement());
3361 if (!inlineStyle())
3362 return false;
3363 bool changes = ensureMutableInlineStyle()->removeProperty(propertyID);
3364 if (changes)
3365 inlineStyleChanged();
3366 return changes;
3367}
3368
3369void Element::removeAllInlineStyleProperties()
3370{
3371 ASSERT(isStyledElement());
3372 if (!inlineStyle() || inlineStyle()->isEmpty())
3373 return;
3374 ensureMutableInlineStyle()->clear();
3375 inlineStyleChanged();
3376}
3377
3378void Element::addSubresourceAttributeURLs(ListHashSet<KURL>& urls) const
3379{
3380 ASSERT(isStyledElement());
3381 if (const StylePropertySet* inlineStyle = elementData() ? elementData()->inlineStyle() : 0)
3382 inlineStyle->addSubresourceStyleURLs(urls, document()->elementSheet()->contents());
3383}
3384
Ben Murdoch83750172013-07-24 10:36:59 +01003385static inline bool attributeNameSort(const pair<StringImpl*, AtomicString>& p1, const pair<StringImpl*, AtomicString>& p2)
Ben Murdoch591b9582013-07-10 11:41:44 +01003386{
3387 // Sort based on the attribute name pointers. It doesn't matter what the order is as long as it is always the same.
3388 return p1.first < p2.first;
3389}
3390
3391void Element::makePresentationAttributeCacheKey(PresentationAttributeCacheKey& result) const
3392{
3393 ASSERT(isStyledElement());
3394 // FIXME: Enable for SVG.
3395 if (namespaceURI() != xhtmlNamespaceURI)
3396 return;
3397 // Interpretation of the size attributes on <input> depends on the type attribute.
3398 if (hasTagName(inputTag))
3399 return;
3400 unsigned size = attributeCount();
3401 for (unsigned i = 0; i < size; ++i) {
3402 const Attribute* attribute = attributeItem(i);
3403 if (!isPresentationAttribute(attribute->name()))
3404 continue;
3405 if (!attribute->namespaceURI().isNull())
3406 return;
3407 // FIXME: Background URL may depend on the base URL and can't be shared. Disallow caching.
3408 if (attribute->name() == backgroundAttr)
3409 return;
3410 result.attributesAndValues.append(std::make_pair(attribute->localName().impl(), attribute->value()));
3411 }
3412 if (result.attributesAndValues.isEmpty())
3413 return;
3414 // Attribute order doesn't matter. Sort for easy equality comparison.
3415 std::sort(result.attributesAndValues.begin(), result.attributesAndValues.end(), attributeNameSort);
3416 // The cache key is non-null when the tagName is set.
3417 result.tagName = localName().impl();
3418}
3419
3420static unsigned computePresentationAttributeCacheHash(const PresentationAttributeCacheKey& key)
3421{
3422 if (!key.tagName)
3423 return 0;
3424 ASSERT(key.attributesAndValues.size());
3425 unsigned attributeHash = StringHasher::hashMemory(key.attributesAndValues.data(), key.attributesAndValues.size() * sizeof(key.attributesAndValues[0]));
3426 return WTF::pairIntHash(key.tagName->existingHash(), attributeHash);
3427}
3428
3429void Element::rebuildPresentationAttributeStyle()
3430{
3431 ASSERT(isStyledElement());
3432 PresentationAttributeCacheKey cacheKey;
3433 makePresentationAttributeCacheKey(cacheKey);
3434
3435 unsigned cacheHash = computePresentationAttributeCacheHash(cacheKey);
3436
3437 PresentationAttributeCache::iterator cacheIterator;
3438 if (cacheHash) {
3439 cacheIterator = presentationAttributeCache().add(cacheHash, nullptr).iterator;
3440 if (cacheIterator->value && cacheIterator->value->key != cacheKey)
3441 cacheHash = 0;
3442 } else {
3443 cacheIterator = presentationAttributeCache().end();
3444 }
3445
3446 RefPtr<StylePropertySet> style;
3447 if (cacheHash && cacheIterator->value) {
3448 style = cacheIterator->value->value;
3449 presentationAttributeCacheCleaner().didHitPresentationAttributeCache();
3450 } else {
3451 style = MutableStylePropertySet::create(isSVGElement() ? SVGAttributeMode : CSSQuirksMode);
3452 unsigned size = attributeCount();
3453 for (unsigned i = 0; i < size; ++i) {
3454 const Attribute* attribute = attributeItem(i);
3455 collectStyleForPresentationAttribute(attribute->name(), attribute->value(), static_cast<MutableStylePropertySet*>(style.get()));
3456 }
3457 }
3458
3459 // ShareableElementData doesn't store presentation attribute style, so make sure we have a UniqueElementData.
3460 UniqueElementData* elementData = ensureUniqueElementData();
3461
3462 elementData->m_presentationAttributeStyleIsDirty = false;
3463 elementData->m_presentationAttributeStyle = style->isEmpty() ? 0 : style;
3464
3465 if (!cacheHash || cacheIterator->value)
3466 return;
3467
3468 OwnPtr<PresentationAttributeCacheEntry> newEntry = adoptPtr(new PresentationAttributeCacheEntry);
3469 newEntry->key = cacheKey;
3470 newEntry->value = style.release();
3471
3472 static const int presentationAttributeCacheMaximumSize = 4096;
3473 if (presentationAttributeCache().size() > presentationAttributeCacheMaximumSize) {
3474 // Start building from scratch if the cache ever gets big.
3475 presentationAttributeCache().clear();
3476 presentationAttributeCache().set(cacheHash, newEntry.release());
3477 } else {
3478 cacheIterator->value = newEntry.release();
3479 }
3480}
3481
3482void Element::addPropertyToPresentationAttributeStyle(MutableStylePropertySet* style, CSSPropertyID propertyID, CSSValueID identifier)
3483{
3484 ASSERT(isStyledElement());
3485 style->setProperty(propertyID, cssValuePool().createIdentifierValue(identifier));
3486}
3487
3488void Element::addPropertyToPresentationAttributeStyle(MutableStylePropertySet* style, CSSPropertyID propertyID, double value, CSSPrimitiveValue::UnitTypes unit)
3489{
3490 ASSERT(isStyledElement());
3491 style->setProperty(propertyID, cssValuePool().createValue(value, unit));
3492}
3493
3494void Element::addPropertyToPresentationAttributeStyle(MutableStylePropertySet* style, CSSPropertyID propertyID, const String& value)
3495{
3496 ASSERT(isStyledElement());
3497 style->setProperty(propertyID, value, false, document()->elementSheet()->contents());
3498}
3499
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01003500void ElementData::deref()
3501{
3502 if (!derefBase())
3503 return;
3504
3505 if (m_isUnique)
3506 delete static_cast<UniqueElementData*>(this);
3507 else
3508 delete static_cast<ShareableElementData*>(this);
3509}
3510
3511ElementData::ElementData()
3512 : m_isUnique(true)
3513 , m_arraySize(0)
3514 , m_presentationAttributeStyleIsDirty(false)
3515 , m_styleAttributeIsDirty(false)
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01003516 , m_animatedSVGAttributesAreDirty(false)
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01003517{
3518}
3519
3520ElementData::ElementData(unsigned arraySize)
3521 : m_isUnique(false)
3522 , m_arraySize(arraySize)
3523 , m_presentationAttributeStyleIsDirty(false)
3524 , m_styleAttributeIsDirty(false)
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01003525 , m_animatedSVGAttributesAreDirty(false)
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01003526{
3527}
3528
3529struct SameSizeAsElementData : public RefCounted<SameSizeAsElementData> {
3530 unsigned bitfield;
3531 void* refPtrs[3];
3532};
3533
3534COMPILE_ASSERT(sizeof(ElementData) == sizeof(SameSizeAsElementData), element_attribute_data_should_stay_small);
3535
3536static size_t sizeForShareableElementDataWithAttributeCount(unsigned count)
3537{
3538 return sizeof(ShareableElementData) + sizeof(Attribute) * count;
3539}
3540
3541PassRefPtr<ShareableElementData> ShareableElementData::createWithAttributes(const Vector<Attribute>& attributes)
3542{
3543 void* slot = WTF::fastMalloc(sizeForShareableElementDataWithAttributeCount(attributes.size()));
3544 return adoptRef(new (slot) ShareableElementData(attributes));
3545}
3546
3547PassRefPtr<UniqueElementData> UniqueElementData::create()
3548{
3549 return adoptRef(new UniqueElementData);
3550}
3551
3552ShareableElementData::ShareableElementData(const Vector<Attribute>& attributes)
3553 : ElementData(attributes.size())
3554{
3555 for (unsigned i = 0; i < m_arraySize; ++i)
3556 new (&m_attributeArray[i]) Attribute(attributes[i]);
3557}
3558
3559ShareableElementData::~ShareableElementData()
3560{
3561 for (unsigned i = 0; i < m_arraySize; ++i)
3562 m_attributeArray[i].~Attribute();
3563}
3564
3565ShareableElementData::ShareableElementData(const UniqueElementData& other)
3566 : ElementData(other, false)
3567{
3568 ASSERT(!other.m_presentationAttributeStyle);
3569
3570 if (other.m_inlineStyle) {
3571 ASSERT(!other.m_inlineStyle->hasCSSOMWrapper());
3572 m_inlineStyle = other.m_inlineStyle->immutableCopyIfNeeded();
3573 }
3574
3575 for (unsigned i = 0; i < m_arraySize; ++i)
3576 new (&m_attributeArray[i]) Attribute(other.m_attributeVector.at(i));
3577}
3578
3579ElementData::ElementData(const ElementData& other, bool isUnique)
3580 : m_isUnique(isUnique)
3581 , m_arraySize(isUnique ? 0 : other.length())
3582 , m_presentationAttributeStyleIsDirty(other.m_presentationAttributeStyleIsDirty)
3583 , m_styleAttributeIsDirty(other.m_styleAttributeIsDirty)
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01003584 , m_animatedSVGAttributesAreDirty(other.m_animatedSVGAttributesAreDirty)
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01003585 , m_classNames(other.m_classNames)
3586 , m_idForStyleResolution(other.m_idForStyleResolution)
3587{
3588 // NOTE: The inline style is copied by the subclass copy constructor since we don't know what to do with it here.
3589}
3590
3591UniqueElementData::UniqueElementData()
3592{
3593}
3594
3595UniqueElementData::UniqueElementData(const UniqueElementData& other)
3596 : ElementData(other, true)
3597 , m_presentationAttributeStyle(other.m_presentationAttributeStyle)
3598 , m_attributeVector(other.m_attributeVector)
3599{
Torne (Richard Coles)93ac45c2013-05-29 14:40:20 +01003600 m_inlineStyle = other.m_inlineStyle ? other.m_inlineStyle->mutableCopy() : 0;
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01003601}
3602
3603UniqueElementData::UniqueElementData(const ShareableElementData& other)
3604 : ElementData(other, true)
3605{
3606 // An ShareableElementData should never have a mutable inline StylePropertySet attached.
3607 ASSERT(!other.m_inlineStyle || !other.m_inlineStyle->isMutable());
3608 m_inlineStyle = other.m_inlineStyle;
3609
3610 m_attributeVector.reserveCapacity(other.length());
3611 for (unsigned i = 0; i < other.length(); ++i)
3612 m_attributeVector.uncheckedAppend(other.m_attributeArray[i]);
3613}
3614
3615PassRefPtr<UniqueElementData> ElementData::makeUniqueCopy() const
3616{
3617 if (isUnique())
3618 return adoptRef(new UniqueElementData(static_cast<const UniqueElementData&>(*this)));
3619 return adoptRef(new UniqueElementData(static_cast<const ShareableElementData&>(*this)));
3620}
3621
3622PassRefPtr<ShareableElementData> UniqueElementData::makeShareableCopy() const
3623{
3624 void* slot = WTF::fastMalloc(sizeForShareableElementDataWithAttributeCount(m_attributeVector.size()));
3625 return adoptRef(new (slot) ShareableElementData(*this));
3626}
3627
3628void UniqueElementData::addAttribute(const QualifiedName& attributeName, const AtomicString& value)
3629{
3630 m_attributeVector.append(Attribute(attributeName, value));
3631}
3632
3633void UniqueElementData::removeAttribute(size_t index)
3634{
3635 ASSERT_WITH_SECURITY_IMPLICATION(index < length());
3636 m_attributeVector.remove(index);
3637}
3638
3639bool ElementData::isEquivalent(const ElementData* other) const
3640{
3641 if (!other)
3642 return isEmpty();
3643
3644 unsigned len = length();
3645 if (len != other->length())
3646 return false;
3647
3648 for (unsigned i = 0; i < len; i++) {
3649 const Attribute* attribute = attributeItem(i);
3650 const Attribute* otherAttr = other->getAttributeItem(attribute->name());
3651 if (!otherAttr || attribute->value() != otherAttr->value())
3652 return false;
3653 }
3654
3655 return true;
3656}
3657
Torne (Richard Coles)e5249552013-05-15 11:35:13 +01003658size_t ElementData::getAttrIndex(Attr* attr) const
3659{
3660 // This relies on the fact that Attr's QualifiedName == the Attribute's name.
3661 for (unsigned i = 0; i < length(); ++i) {
3662 if (attributeItem(i)->name() == attr->qualifiedName())
3663 return i;
3664 }
3665 return notFound;
3666}
3667
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01003668size_t ElementData::getAttributeItemIndexSlowCase(const AtomicString& name, bool shouldIgnoreAttributeCase) const
3669{
3670 // Continue to checking case-insensitively and/or full namespaced names if necessary:
3671 for (unsigned i = 0; i < length(); ++i) {
3672 const Attribute* attribute = attributeItem(i);
3673 if (!attribute->name().hasPrefix()) {
3674 if (shouldIgnoreAttributeCase && equalIgnoringCase(name, attribute->localName()))
3675 return i;
3676 } else {
3677 // FIXME: Would be faster to do this comparison without calling toString, which
3678 // generates a temporary string by concatenation. But this branch is only reached
3679 // if the attribute name has a prefix, which is rare in HTML.
3680 if (equalPossiblyIgnoringCase(name, attribute->name().toString(), shouldIgnoreAttributeCase))
3681 return i;
3682 }
3683 }
3684 return notFound;
3685}
3686
3687Attribute* UniqueElementData::getAttributeItem(const QualifiedName& name)
3688{
3689 for (unsigned i = 0; i < length(); ++i) {
3690 if (m_attributeVector.at(i).name().matches(name))
3691 return &m_attributeVector.at(i);
3692 }
3693 return 0;
3694}
3695
3696Attribute* UniqueElementData::attributeItem(unsigned index)
3697{
3698 ASSERT_WITH_SECURITY_IMPLICATION(index < length());
3699 return &m_attributeVector.at(index);
3700}
3701
3702} // namespace WebCore