blob: 957777497c6c19d4bd10710848d78aaed4a75573 [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)
Torne (Richard Coles)e1f1df52013-08-23 16:39:30 +0100956 CustomElementRegistrationContext::setTypeExtension(this, newValue, reason == ModifiedDirectly ? CustomElementRegistrationContext::CreatedByParser : CustomElementRegistrationContext::NotCreatedByParser);
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);
Torne (Richard Coles)e1f1df52013-08-23 16:39:30 +01001056 const SelectRuleFeatureSet& featureSet = elementShadow->ensureSelectFeatureSet();
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001057
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 +01001209Node::InsertionNotificationRequest Element::insertedInto(ContainerNode* insertionPoint)
1210{
1211 // need to do superclass processing first so inDocument() is true
1212 // by the time we reach updateId
1213 ContainerNode::insertedInto(insertionPoint);
1214
1215 if (containsFullScreenElement() && parentElement() && !parentElement()->containsFullScreenElement())
1216 setContainsFullScreenElementOnAncestorsCrossingFrameBoundaries(true);
1217
1218 if (Element* before = pseudoElement(BEFORE))
1219 before->insertedInto(insertionPoint);
1220
1221 if (Element* after = pseudoElement(AFTER))
1222 after->insertedInto(insertionPoint);
1223
Torne (Richard Coles)e1f1df52013-08-23 16:39:30 +01001224 if (Element* backdrop = pseudoElement(BACKDROP))
1225 backdrop->insertedInto(insertionPoint);
1226
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001227 if (!insertionPoint->isInTreeScope())
1228 return InsertionDone;
1229
1230 if (hasRareData())
1231 elementRareData()->clearClassListValueForQuirksMode();
1232
Torne (Richard Coles)f5e4ad52013-08-05 13:57:57 +01001233 if (isUpgradedCustomElement() && inDocument())
1234 CustomElement::didEnterDocument(this, document());
1235
Ben Murdoch00d3faa2013-08-14 11:52:03 +01001236 TreeScope* scope = insertionPoint->treeScope();
1237 if (scope != treeScope())
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001238 return InsertionDone;
1239
1240 const AtomicString& idValue = getIdAttribute();
Ben Murdoch00d3faa2013-08-14 11:52:03 +01001241 if (!idValue.isNull())
1242 updateId(scope, nullAtom, idValue);
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001243
1244 const AtomicString& nameValue = getNameAttribute();
Ben Murdoch00d3faa2013-08-14 11:52:03 +01001245 if (!nameValue.isNull())
1246 updateName(nullAtom, nameValue);
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001247
1248 if (hasTagName(labelTag)) {
Ben Murdoch00d3faa2013-08-14 11:52:03 +01001249 if (scope->shouldCacheLabelsByForAttribute())
1250 updateLabel(scope, nullAtom, fastGetAttribute(forAttr));
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001251 }
1252
Ben Murdoch3c9e4ae2013-08-12 14:20:44 +01001253 if (parentElement() && parentElement()->isInCanvasSubtree())
1254 setIsInCanvasSubtree(true);
1255
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001256 return InsertionDone;
1257}
1258
1259void Element::removedFrom(ContainerNode* insertionPoint)
1260{
Torne (Richard Coles)f5e4ad52013-08-05 13:57:57 +01001261 bool wasInDocument = insertionPoint->inDocument();
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001262
1263 if (Element* before = pseudoElement(BEFORE))
1264 before->removedFrom(insertionPoint);
1265
1266 if (Element* after = pseudoElement(AFTER))
1267 after->removedFrom(insertionPoint);
1268
Ben Murdoche69819b2013-07-17 14:56:49 +01001269 if (Element* backdrop = pseudoElement(BACKDROP))
1270 backdrop->removedFrom(insertionPoint);
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001271 document()->removeFromTopLayer(this);
Ben Murdoche69819b2013-07-17 14:56:49 +01001272
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001273 if (containsFullScreenElement())
1274 setContainsFullScreenElementOnAncestorsCrossingFrameBoundaries(false);
1275
1276 if (document()->page())
Torne (Richard Coles)e1f1df52013-08-23 16:39:30 +01001277 document()->page()->pointerLockController().elementRemoved(this);
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001278
1279 setSavedLayerScrollOffset(IntSize());
1280
1281 if (insertionPoint->isInTreeScope() && treeScope() == document()) {
1282 const AtomicString& idValue = getIdAttribute();
Ben Murdoch00d3faa2013-08-14 11:52:03 +01001283 if (!idValue.isNull())
1284 updateId(insertionPoint->treeScope(), idValue, nullAtom);
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001285
1286 const AtomicString& nameValue = getNameAttribute();
Ben Murdoch00d3faa2013-08-14 11:52:03 +01001287 if (!nameValue.isNull())
1288 updateName(nameValue, nullAtom);
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001289
1290 if (hasTagName(labelTag)) {
Ben Murdoch00d3faa2013-08-14 11:52:03 +01001291 TreeScope* treeScope = insertionPoint->treeScope();
1292 if (treeScope->shouldCacheLabelsByForAttribute())
1293 updateLabel(treeScope, fastGetAttribute(forAttr), nullAtom);
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001294 }
1295 }
1296
1297 ContainerNode::removedFrom(insertionPoint);
Ben Murdoche69819b2013-07-17 14:56:49 +01001298 if (wasInDocument) {
1299 if (hasPendingResources())
1300 document()->accessSVGExtensions()->removeElementFromPendingResources(this);
1301
Ben Murdoch83750172013-07-24 10:36:59 +01001302 if (isUpgradedCustomElement())
Ben Murdochfff88842013-07-30 15:20:09 +01001303 CustomElement::didLeaveDocument(this, insertionPoint->document());
Ben Murdoche69819b2013-07-17 14:56:49 +01001304 }
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001305
Ben Murdoch3c9e4ae2013-08-12 14:20:44 +01001306 if (hasRareData())
1307 elementRareData()->setIsInCanvasSubtree(false);
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001308}
1309
Torne (Richard Coles)521d96e2013-06-19 11:58:24 +01001310void Element::attach(const AttachContext& context)
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001311{
1312 PostAttachCallbackDisabler callbackDisabler(this);
1313 StyleResolverParentPusher parentPusher(this);
1314 WidgetHierarchyUpdatesSuspensionScope suspendWidgetHierarchyUpdates;
1315
Torne (Richard Coles)e1f1df52013-08-23 16:39:30 +01001316 // We've already been through detach when doing a lazyAttach, but we might
1317 // need to clear any state that's been added since then.
1318 if (hasRareData() && styleChangeType() == LazyAttachStyleChange) {
1319 ElementRareData* data = elementRareData();
1320 data->clearComputedStyle();
1321 data->resetDynamicRestyleObservations();
1322 if (!context.resolvedStyle)
1323 data->resetStyleState();
1324 }
1325
Ben Murdoch3c9e4ae2013-08-12 14:20:44 +01001326 NodeRenderingContext(this, context.resolvedStyle).createRendererForElementIfNeeded();
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001327
1328 createPseudoElementIfNeeded(BEFORE);
1329
1330 // When a shadow root exists, it does the work of attaching the children.
1331 if (ElementShadow* shadow = this->shadow()) {
1332 parentPusher.push();
Ben Murdoch591b9582013-07-10 11:41:44 +01001333 shadow->attach(context);
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001334 } else if (firstChild())
1335 parentPusher.push();
1336
Torne (Richard Coles)521d96e2013-06-19 11:58:24 +01001337 ContainerNode::attach(context);
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001338
1339 createPseudoElementIfNeeded(AFTER);
Ben Murdoche69819b2013-07-17 14:56:49 +01001340 createPseudoElementIfNeeded(BACKDROP);
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001341
Ben Murdoch591b9582013-07-10 11:41:44 +01001342 if (hasRareData()) {
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001343 ElementRareData* data = elementRareData();
1344 if (data->needsFocusAppearanceUpdateSoonAfterAttach()) {
Ben Murdoch7757ec22013-07-23 11:17:36 +01001345 if (isFocusable() && document()->focusedElement() == this)
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001346 document()->updateFocusAppearanceSoon(false /* don't restore selection */);
1347 data->setNeedsFocusAppearanceUpdateSoonAfterAttach(false);
1348 }
1349 }
Ben Murdoch591b9582013-07-10 11:41:44 +01001350
1351 // FIXME: It doesn't appear safe to call didRecalculateStyleForElement when
1352 // not in a Document::recalcStyle. Since we're hopefully going to always
1353 // lazyAttach in the future that problem should go away.
1354 if (document()->inStyleRecalc())
1355 InspectorInstrumentation::didRecalculateStyleForElement(this);
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001356}
1357
1358void Element::unregisterNamedFlowContentNode()
1359{
1360 if (RuntimeEnabledFeatures::cssRegionsEnabled() && inNamedFlow() && document()->renderView())
1361 document()->renderView()->flowThreadController()->unregisterNamedFlowContentNode(this);
1362}
1363
Torne (Richard Coles)521d96e2013-06-19 11:58:24 +01001364void Element::detach(const AttachContext& context)
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001365{
1366 WidgetHierarchyUpdatesSuspensionScope suspendWidgetHierarchyUpdates;
1367 unregisterNamedFlowContentNode();
1368 cancelFocusAppearanceUpdate();
1369 if (hasRareData()) {
1370 ElementRareData* data = elementRareData();
1371 data->setPseudoElement(BEFORE, 0);
1372 data->setPseudoElement(AFTER, 0);
Ben Murdoche69819b2013-07-17 14:56:49 +01001373 data->setPseudoElement(BACKDROP, 0);
Ben Murdoch3c9e4ae2013-08-12 14:20:44 +01001374 data->clearComputedStyle();
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001375 data->resetDynamicRestyleObservations();
Ben Murdoch591b9582013-07-10 11:41:44 +01001376 data->setIsInsideRegion(false);
Torne (Richard Coles)f5e4ad52013-08-05 13:57:57 +01001377
Ben Murdoch3c9e4ae2013-08-12 14:20:44 +01001378 // Only clear the style state if we're not going to reuse the style from recalcStyle.
1379 if (!context.resolvedStyle)
1380 data->resetStyleState();
1381
Torne (Richard Coles)f5e4ad52013-08-05 13:57:57 +01001382 if (RuntimeEnabledFeatures::webAnimationsCSSEnabled() && !context.performingReattach) {
1383 if (ActiveAnimations* activeAnimations = data->activeAnimations())
1384 activeAnimations->cssAnimations()->cancel();
1385 }
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001386 }
Ben Murdoch591b9582013-07-10 11:41:44 +01001387 if (ElementShadow* shadow = this->shadow())
1388 shadow->detach(context);
Torne (Richard Coles)521d96e2013-06-19 11:58:24 +01001389 ContainerNode::detach(context);
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001390}
1391
1392bool Element::pseudoStyleCacheIsInvalid(const RenderStyle* currentStyle, RenderStyle* newStyle)
1393{
1394 ASSERT(currentStyle == renderStyle());
1395 ASSERT(renderer());
1396
1397 if (!currentStyle)
1398 return false;
1399
1400 const PseudoStyleCache* pseudoStyleCache = currentStyle->cachedPseudoStyles();
1401 if (!pseudoStyleCache)
1402 return false;
1403
1404 size_t cacheSize = pseudoStyleCache->size();
1405 for (size_t i = 0; i < cacheSize; ++i) {
1406 RefPtr<RenderStyle> newPseudoStyle;
1407 PseudoId pseudoId = pseudoStyleCache->at(i)->styleType();
1408 if (pseudoId == FIRST_LINE || pseudoId == FIRST_LINE_INHERITED)
1409 newPseudoStyle = renderer()->uncachedFirstLineStyle(newStyle);
1410 else
1411 newPseudoStyle = renderer()->getUncachedPseudoStyle(PseudoStyleRequest(pseudoId), newStyle, newStyle);
1412 if (!newPseudoStyle)
1413 return true;
1414 if (*newPseudoStyle != *pseudoStyleCache->at(i)) {
1415 if (pseudoId < FIRST_INTERNAL_PSEUDOID)
1416 newStyle->setHasPseudoStyle(pseudoId);
1417 newStyle->addCachedPseudoStyle(newPseudoStyle);
1418 if (pseudoId == FIRST_LINE || pseudoId == FIRST_LINE_INHERITED) {
1419 // FIXME: We should do an actual diff to determine whether a repaint vs. layout
1420 // is needed, but for now just assume a layout will be required. The diff code
1421 // in RenderObject::setStyle would need to be factored out so that it could be reused.
1422 renderer()->setNeedsLayoutAndPrefWidthsRecalc();
1423 }
1424 return true;
1425 }
1426 }
1427 return false;
1428}
1429
Torne (Richard Coles)521d96e2013-06-19 11:58:24 +01001430PassRefPtr<RenderStyle> Element::styleForRenderer()
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001431{
1432 if (hasCustomStyleCallbacks()) {
1433 if (RefPtr<RenderStyle> style = customStyleForRenderer())
1434 return style.release();
1435 }
1436
Torne (Richard Coles)521d96e2013-06-19 11:58:24 +01001437 return originalStyleForRenderer();
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001438}
1439
Torne (Richard Coles)521d96e2013-06-19 11:58:24 +01001440PassRefPtr<RenderStyle> Element::originalStyleForRenderer()
Torne (Richard Coles)5267f702013-06-11 10:57:24 +01001441{
Torne (Richard Coles)521d96e2013-06-19 11:58:24 +01001442 return document()->styleResolver()->styleForElement(this);
Torne (Richard Coles)5267f702013-06-11 10:57:24 +01001443}
1444
Ben Murdoche69819b2013-07-17 14:56:49 +01001445bool Element::recalcStyle(StyleChange change)
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001446{
Torne (Richard Coles)93ac45c2013-05-29 14:40:20 +01001447 ASSERT(document()->inStyleRecalc());
1448
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001449 if (hasCustomStyleCallbacks())
1450 willRecalcStyle(change);
1451
1452 // Ref currentStyle in case it would otherwise be deleted when setting the new style in the renderer.
Ben Murdoch83750172013-07-24 10:36:59 +01001453 RefPtr<RenderStyle> currentStyle = renderStyle();
1454 bool hasParentStyle = static_cast<bool>(parentRenderStyle());
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001455 bool hasDirectAdjacentRules = childrenAffectedByDirectAdjacentRules();
1456 bool hasIndirectAdjacentRules = childrenAffectedByForwardPositionalRules();
1457
Ben Murdoch3c9e4ae2013-08-12 14:20:44 +01001458 if (hasRareData() && (change > NoChange || needsStyleRecalc())) {
1459 ElementRareData* data = elementRareData();
1460 data->resetStyleState();
1461 data->clearComputedStyle();
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001462 }
Ben Murdoch3c9e4ae2013-08-12 14:20:44 +01001463
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001464 if (hasParentStyle && (change >= Inherit || needsStyleRecalc())) {
1465 StyleChange localChange = Detach;
1466 RefPtr<RenderStyle> newStyle;
1467 if (currentStyle) {
Torne (Richard Coles)521d96e2013-06-19 11:58:24 +01001468 newStyle = styleForRenderer();
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001469 localChange = Node::diff(currentStyle.get(), newStyle.get(), document());
Torne (Richard Coles)521d96e2013-06-19 11:58:24 +01001470 } else if (attached() && isActiveInsertionPoint(this)) {
1471 // Active InsertionPoints will never have renderers so there's no reason to
1472 // reattach them repeatedly once they're already attached.
1473 localChange = change;
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001474 }
1475 if (localChange == Detach) {
Torne (Richard Coles)521d96e2013-06-19 11:58:24 +01001476 AttachContext reattachContext;
1477 reattachContext.resolvedStyle = newStyle.get();
1478 reattach(reattachContext);
1479
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001480 if (hasCustomStyleCallbacks())
1481 didRecalcStyle(change);
Ben Murdoche69819b2013-07-17 14:56:49 +01001482 return true;
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001483 }
1484
Ben Murdoch591b9582013-07-10 11:41:44 +01001485 InspectorInstrumentation::didRecalculateStyleForElement(this);
1486
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001487 if (RenderObject* renderer = this->renderer()) {
Torne (Richard Coles)f5e4ad52013-08-05 13:57:57 +01001488 if (localChange != NoChange || pseudoStyleCacheIsInvalid(currentStyle.get(), newStyle.get()) || (change == Force && renderer->requiresForcedStyleRecalcPropagation()) || shouldNotifyRendererWithIdenticalStyles()) {
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001489 renderer->setAnimatableStyle(newStyle.get());
Torne (Richard Coles)f5e4ad52013-08-05 13:57:57 +01001490 } else if (needsStyleRecalc()) {
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001491 // Although no change occurred, we use the new style so that the cousin style sharing code won't get
1492 // fooled into believing this style is the same.
1493 renderer->setStyleInternal(newStyle.get());
1494 }
1495 }
1496
1497 // 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
1498 // 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).
1499 if (document()->styleSheetCollection()->usesRemUnits() && document()->documentElement() == this && localChange != NoChange && currentStyle && newStyle && currentStyle->fontSize() != newStyle->fontSize()) {
1500 // Cached RenderStyles may depend on the re units.
1501 document()->styleResolver()->invalidateMatchedPropertiesCache();
1502 change = Force;
1503 }
1504
Ben Murdochdf957042013-08-06 11:01:27 +01001505 if (styleChangeType() >= SubtreeStyleChange)
Torne (Richard Coles)e5249552013-05-15 11:35:13 +01001506 change = Force;
1507 else if (change != Force)
1508 change = localChange;
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001509 }
1510 StyleResolverParentPusher parentPusher(this);
1511
Torne (Richard Coles)f5e4ad52013-08-05 13:57:57 +01001512 for (ShadowRoot* root = youngestShadowRoot(); root; root = root->olderShadowRoot()) {
1513 if (shouldRecalcStyle(change, root)) {
1514 parentPusher.push();
1515 root->recalcStyle(change);
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001516 }
1517 }
1518
1519 if (shouldRecalcStyle(change, this))
1520 updatePseudoElement(BEFORE, change);
1521
1522 // FIXME: This check is good enough for :hover + foo, but it is not good enough for :hover + foo + bar.
1523 // For now we will just worry about the common case, since it's a lot trickier to get the second case right
1524 // without doing way too much re-resolution.
1525 bool forceCheckOfNextElementSibling = false;
1526 bool forceCheckOfAnyElementSibling = false;
Ben Murdoche69819b2013-07-17 14:56:49 +01001527 bool forceReattachOfAnyWhitespaceSibling = false;
1528 for (Node* child = firstChild(); child; child = child->nextSibling()) {
1529 bool didReattach = false;
1530
1531 if (child->renderer())
1532 forceReattachOfAnyWhitespaceSibling = false;
1533
1534 if (child->isTextNode()) {
1535 if (forceReattachOfAnyWhitespaceSibling && toText(child)->containsOnlyWhitespace())
1536 child->reattach();
1537 else
1538 didReattach = toText(child)->recalcTextStyle(change);
1539 } else if (child->isElementNode()) {
1540 Element* element = toElement(child);
1541
Torne (Richard Coles)e1f1df52013-08-23 16:39:30 +01001542 bool childRulesChanged = element->needsStyleRecalc() && element->styleChangeType() >= SubtreeStyleChange;
1543
Ben Murdoche69819b2013-07-17 14:56:49 +01001544 if (forceCheckOfNextElementSibling || forceCheckOfAnyElementSibling)
1545 element->setNeedsStyleRecalc();
1546
Ben Murdoche69819b2013-07-17 14:56:49 +01001547 forceCheckOfNextElementSibling = childRulesChanged && hasDirectAdjacentRules;
1548 forceCheckOfAnyElementSibling = forceCheckOfAnyElementSibling || (childRulesChanged && hasIndirectAdjacentRules);
1549
1550 if (shouldRecalcStyle(change, element)) {
1551 parentPusher.push();
1552 didReattach = element->recalcStyle(change);
1553 }
Ben Murdoch591b9582013-07-10 11:41:44 +01001554 }
Ben Murdoche69819b2013-07-17 14:56:49 +01001555
1556 forceReattachOfAnyWhitespaceSibling = didReattach || forceReattachOfAnyWhitespaceSibling;
Torne (Richard Coles)5267f702013-06-11 10:57:24 +01001557 }
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001558
Torne (Richard Coles)e1f1df52013-08-23 16:39:30 +01001559 if (shouldRecalcStyle(change, this)) {
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001560 updatePseudoElement(AFTER, change);
Torne (Richard Coles)e1f1df52013-08-23 16:39:30 +01001561 updatePseudoElement(BACKDROP, change);
1562 }
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001563
1564 clearNeedsStyleRecalc();
1565 clearChildNeedsStyleRecalc();
Ben Murdoch591b9582013-07-10 11:41:44 +01001566
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001567 if (hasCustomStyleCallbacks())
1568 didRecalcStyle(change);
Ben Murdoche69819b2013-07-17 14:56:49 +01001569 return false;
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001570}
1571
1572ElementShadow* Element::shadow() const
1573{
1574 return hasRareData() ? elementRareData()->shadow() : 0;
1575}
1576
1577ElementShadow* Element::ensureShadow()
1578{
1579 return ensureElementRareData()->ensureShadow();
1580}
1581
1582void Element::didAffectSelector(AffectedSelectorMask mask)
1583{
1584 setNeedsStyleRecalc();
1585 if (ElementShadow* elementShadow = shadowOfParentForDistribution(this))
1586 elementShadow->didAffectSelector(mask);
1587}
1588
Ben Murdochdf957042013-08-06 11:01:27 +01001589PassRefPtr<ShadowRoot> Element::createShadowRoot(ExceptionState& es)
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001590{
1591 if (alwaysCreateUserAgentShadowRoot())
1592 ensureUserAgentShadowRoot();
1593
1594 if (RuntimeEnabledFeatures::authorShadowDOMForAnyElementEnabled())
1595 return ensureShadow()->addShadowRoot(this, ShadowRoot::AuthorShadowRoot);
1596
1597 // Since some elements recreates shadow root dynamically, multiple shadow
1598 // subtrees won't work well in that element. Until they are fixed, we disable
1599 // adding author shadow root for them.
1600 if (!areAuthorShadowsAllowed()) {
Ben Murdochdf957042013-08-06 11:01:27 +01001601 es.throwDOMException(HierarchyRequestError);
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001602 return 0;
1603 }
1604 return ensureShadow()->addShadowRoot(this, ShadowRoot::AuthorShadowRoot);
1605}
1606
1607ShadowRoot* Element::shadowRoot() const
1608{
1609 ElementShadow* elementShadow = shadow();
1610 if (!elementShadow)
1611 return 0;
1612 ShadowRoot* shadowRoot = elementShadow->youngestShadowRoot();
1613 if (shadowRoot->type() == ShadowRoot::AuthorShadowRoot)
1614 return shadowRoot;
1615 return 0;
1616}
1617
1618ShadowRoot* Element::userAgentShadowRoot() const
1619{
1620 if (ElementShadow* elementShadow = shadow()) {
1621 if (ShadowRoot* shadowRoot = elementShadow->oldestShadowRoot()) {
1622 ASSERT(shadowRoot->type() == ShadowRoot::UserAgentShadowRoot);
1623 return shadowRoot;
1624 }
1625 }
1626
1627 return 0;
1628}
1629
1630ShadowRoot* Element::ensureUserAgentShadowRoot()
1631{
1632 if (ShadowRoot* shadowRoot = userAgentShadowRoot())
1633 return shadowRoot;
1634 ShadowRoot* shadowRoot = ensureShadow()->addShadowRoot(this, ShadowRoot::UserAgentShadowRoot);
1635 didAddUserAgentShadowRoot(shadowRoot);
1636 return shadowRoot;
1637}
1638
Ben Murdoch1fad5ca2013-08-07 11:05:11 +01001639bool Element::supportsShadowElementForUserAgentShadow() const
1640{
1641 return true;
1642}
1643
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001644bool Element::childTypeAllowed(NodeType type) const
1645{
1646 switch (type) {
1647 case ELEMENT_NODE:
1648 case TEXT_NODE:
1649 case COMMENT_NODE:
1650 case PROCESSING_INSTRUCTION_NODE:
1651 case CDATA_SECTION_NODE:
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001652 return true;
1653 default:
1654 break;
1655 }
1656 return false;
1657}
1658
Ben Murdoch83750172013-07-24 10:36:59 +01001659static void inline checkForEmptyStyleChange(Element* element, RenderStyle* style)
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001660{
1661 if (!style && !element->styleAffectedByEmpty())
1662 return;
1663
1664 if (!style || (element->styleAffectedByEmpty() && (!style->emptyState() || element->hasChildNodes())))
1665 element->setNeedsStyleRecalc();
1666}
1667
1668static void checkForSiblingStyleChanges(Element* e, RenderStyle* style, bool finishedParsingCallback,
1669 Node* beforeChange, Node* afterChange, int childCountDelta)
1670{
Ben Murdochdf957042013-08-06 11:01:27 +01001671 if (!e->attached() || e->document()->hasPendingForcedStyleRecalc() || e->styleChangeType() >= SubtreeStyleChange)
Ben Murdoch83750172013-07-24 10:36:59 +01001672 return;
1673
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001674 // :empty selector.
1675 checkForEmptyStyleChange(e, style);
Ben Murdoch591b9582013-07-10 11:41:44 +01001676
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001677 if (!style || (e->needsStyleRecalc() && e->childrenAffectedByPositionalRules()))
1678 return;
1679
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001680 // Forward positional selectors include the ~ selector, nth-child, nth-of-type, first-of-type and only-of-type.
1681 // Backward positional selectors include nth-last-child, nth-last-of-type, last-of-type and only-of-type.
1682 // We have to invalidate everything following the insertion point in the forward case, and everything before the insertion point in the
1683 // backward case.
1684 // |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.
1685 // 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 +01001686 // here. recalcStyle will then force a walk of the children when it sees that this has happened.
1687 if ((e->childrenAffectedByForwardPositionalRules() && afterChange) || (e->childrenAffectedByBackwardPositionalRules() && beforeChange)) {
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001688 e->setNeedsStyleRecalc();
Ben Murdoch83750172013-07-24 10:36:59 +01001689 return;
1690 }
1691
1692 // :first-child. In the parser callback case, we don't have to check anything, since we were right the first time.
1693 // In the DOM case, we only need to do something if |afterChange| is not 0.
1694 // |afterChange| is 0 in the parser case, so it works out that we'll skip this block.
1695 if (e->childrenAffectedByFirstChildRules() && afterChange) {
1696 // Find our new first child.
1697 Node* newFirstChild = e->firstElementChild();
1698 RenderStyle* newFirstChildStyle = newFirstChild ? newFirstChild->renderStyle() : 0;
1699
1700 // Find the first element node following |afterChange|
1701 Node* firstElementAfterInsertion = afterChange->isElementNode() ? afterChange : afterChange->nextElementSibling();
1702 RenderStyle* firstElementAfterInsertionStyle = firstElementAfterInsertion ? firstElementAfterInsertion->renderStyle() : 0;
1703
1704 // This is the insert/append case.
1705 if (newFirstChild != firstElementAfterInsertion && firstElementAfterInsertionStyle && firstElementAfterInsertionStyle->firstChildState())
1706 firstElementAfterInsertion->setNeedsStyleRecalc();
1707
1708 // We also have to handle node removal.
1709 if (childCountDelta < 0 && newFirstChild == firstElementAfterInsertion && newFirstChild && (!newFirstChildStyle || !newFirstChildStyle->firstChildState()))
1710 newFirstChild->setNeedsStyleRecalc();
1711 }
1712
1713 // :last-child. In the parser callback case, we don't have to check anything, since we were right the first time.
1714 // In the DOM case, we only need to do something if |afterChange| is not 0.
1715 if (e->childrenAffectedByLastChildRules() && beforeChange) {
1716 // Find our new last child.
1717 Node* newLastChild = e->lastElementChild();
1718 RenderStyle* newLastChildStyle = newLastChild ? newLastChild->renderStyle() : 0;
1719
1720 // Find the last element node going backwards from |beforeChange|
1721 Node* lastElementBeforeInsertion = beforeChange->isElementNode() ? beforeChange : beforeChange->previousElementSibling();
1722 RenderStyle* lastElementBeforeInsertionStyle = lastElementBeforeInsertion ? lastElementBeforeInsertion->renderStyle() : 0;
1723
1724 if (newLastChild != lastElementBeforeInsertion && lastElementBeforeInsertionStyle && lastElementBeforeInsertionStyle->lastChildState())
1725 lastElementBeforeInsertion->setNeedsStyleRecalc();
1726
1727 // 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
1728 // to match now.
1729 if ((childCountDelta < 0 || finishedParsingCallback) && newLastChild == lastElementBeforeInsertion && newLastChild && (!newLastChildStyle || !newLastChildStyle->lastChildState()))
1730 newLastChild->setNeedsStyleRecalc();
1731 }
1732
1733 // The + selector. We need to invalidate the first element following the insertion point. It is the only possible element
1734 // that could be affected by this DOM change.
1735 if (e->childrenAffectedByDirectAdjacentRules() && afterChange) {
1736 if (Node* firstElementAfterInsertion = afterChange->nextElementSibling())
1737 firstElementAfterInsertion->setNeedsStyleRecalc();
1738 }
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001739}
1740
1741void Element::childrenChanged(bool changedByParser, Node* beforeChange, Node* afterChange, int childCountDelta)
1742{
1743 ContainerNode::childrenChanged(changedByParser, beforeChange, afterChange, childCountDelta);
1744 if (changedByParser)
1745 checkForEmptyStyleChange(this, renderStyle());
1746 else
1747 checkForSiblingStyleChanges(this, renderStyle(), false, beforeChange, afterChange, childCountDelta);
1748
Ben Murdoch83750172013-07-24 10:36:59 +01001749 if (ElementShadow* shadow = this->shadow())
Torne (Richard Coles)f5e4ad52013-08-05 13:57:57 +01001750 shadow->setNeedsDistributionRecalc();
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001751}
1752
1753void Element::removeAllEventListeners()
1754{
1755 ContainerNode::removeAllEventListeners();
1756 if (ElementShadow* shadow = this->shadow())
1757 shadow->removeAllEventListeners();
1758}
1759
1760void Element::beginParsingChildren()
1761{
1762 clearIsParsingChildrenFinished();
1763 StyleResolver* styleResolver = document()->styleResolverIfExists();
1764 if (styleResolver && attached())
1765 styleResolver->pushParentElement(this);
1766}
1767
1768void Element::finishParsingChildren()
1769{
1770 ContainerNode::finishParsingChildren();
1771 setIsParsingChildrenFinished();
1772 checkForSiblingStyleChanges(this, renderStyle(), true, lastChild(), 0, 0);
1773 if (StyleResolver* styleResolver = document()->styleResolverIfExists())
1774 styleResolver->popParentElement(this);
Torne (Richard Coles)e1f1df52013-08-23 16:39:30 +01001775 if (isCustomElement())
1776 CustomElement::didFinishParsingChildren(this);
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001777}
1778
1779#ifndef NDEBUG
1780void Element::formatForDebugger(char* buffer, unsigned length) const
1781{
1782 StringBuilder result;
1783 String s;
1784
1785 result.append(nodeName());
1786
1787 s = getIdAttribute();
1788 if (s.length() > 0) {
1789 if (result.length() > 0)
1790 result.appendLiteral("; ");
1791 result.appendLiteral("id=");
1792 result.append(s);
1793 }
1794
1795 s = getAttribute(classAttr);
1796 if (s.length() > 0) {
1797 if (result.length() > 0)
1798 result.appendLiteral("; ");
1799 result.appendLiteral("class=");
1800 result.append(s);
1801 }
1802
1803 strncpy(buffer, result.toString().utf8().data(), length - 1);
1804}
1805#endif
1806
1807const Vector<RefPtr<Attr> >& Element::attrNodeList()
1808{
1809 ASSERT(hasSyntheticAttrChildNodes());
1810 return *attrNodeListForElement(this);
1811}
1812
Ben Murdochdf957042013-08-06 11:01:27 +01001813PassRefPtr<Attr> Element::setAttributeNode(Attr* attrNode, ExceptionState& es)
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001814{
1815 if (!attrNode) {
Ben Murdochdf957042013-08-06 11:01:27 +01001816 es.throwDOMException(TypeMismatchError);
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001817 return 0;
1818 }
1819
1820 RefPtr<Attr> oldAttrNode = attrIfExists(attrNode->qualifiedName());
1821 if (oldAttrNode.get() == attrNode)
1822 return attrNode; // This Attr is already attached to the element.
1823
Ben Murdoche69819b2013-07-17 14:56:49 +01001824 // 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 +01001825 // The DOM user must explicitly clone Attr nodes to re-use them in other elements.
1826 if (attrNode->ownerElement()) {
Ben Murdochdf957042013-08-06 11:01:27 +01001827 es.throwDOMException(InUseAttributeError);
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001828 return 0;
1829 }
1830
1831 synchronizeAllAttributes();
1832 UniqueElementData* elementData = ensureUniqueElementData();
1833
Torne (Richard Coles)e1f1df52013-08-23 16:39:30 +01001834 size_t index = elementData->getAttributeItemIndex(attrNode->qualifiedName(), shouldIgnoreAttributeCase(this));
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001835 if (index != notFound) {
1836 if (oldAttrNode)
1837 detachAttrNodeFromElementWithValue(oldAttrNode.get(), elementData->attributeItem(index)->value());
1838 else
1839 oldAttrNode = Attr::create(document(), attrNode->qualifiedName(), elementData->attributeItem(index)->value());
1840 }
1841
1842 setAttributeInternal(index, attrNode->qualifiedName(), attrNode->value(), NotInSynchronizationOfLazyAttribute);
1843
1844 attrNode->attachToElement(this);
Ben Murdoch591b9582013-07-10 11:41:44 +01001845 treeScope()->adoptIfNeeded(attrNode);
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001846 ensureAttrNodeListForElement(this)->append(attrNode);
1847
1848 return oldAttrNode.release();
1849}
1850
Ben Murdochdf957042013-08-06 11:01:27 +01001851PassRefPtr<Attr> Element::setAttributeNodeNS(Attr* attr, ExceptionState& es)
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001852{
Ben Murdochdf957042013-08-06 11:01:27 +01001853 return setAttributeNode(attr, es);
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001854}
1855
Ben Murdochdf957042013-08-06 11:01:27 +01001856PassRefPtr<Attr> Element::removeAttributeNode(Attr* attr, ExceptionState& es)
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001857{
1858 if (!attr) {
Ben Murdochdf957042013-08-06 11:01:27 +01001859 es.throwDOMException(TypeMismatchError);
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001860 return 0;
1861 }
1862 if (attr->ownerElement() != this) {
Ben Murdochdf957042013-08-06 11:01:27 +01001863 es.throwDOMException(NotFoundError);
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001864 return 0;
1865 }
1866
1867 ASSERT(document() == attr->document());
1868
1869 synchronizeAttribute(attr->qualifiedName());
1870
Torne (Richard Coles)e5249552013-05-15 11:35:13 +01001871 size_t index = elementData()->getAttrIndex(attr);
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001872 if (index == notFound) {
Ben Murdochdf957042013-08-06 11:01:27 +01001873 es.throwDOMException(NotFoundError);
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001874 return 0;
1875 }
1876
Torne (Richard Coles)e5249552013-05-15 11:35:13 +01001877 RefPtr<Attr> guard(attr);
1878 detachAttrNodeAtIndex(attr, index);
1879 return guard.release();
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001880}
1881
Ben Murdochdf957042013-08-06 11:01:27 +01001882bool Element::parseAttributeName(QualifiedName& out, const AtomicString& namespaceURI, const AtomicString& qualifiedName, ExceptionState& es)
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001883{
1884 String prefix, localName;
Ben Murdochdf957042013-08-06 11:01:27 +01001885 if (!Document::parseQualifiedName(qualifiedName, prefix, localName, es))
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001886 return false;
Ben Murdochdf957042013-08-06 11:01:27 +01001887 ASSERT(!es.hadException());
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001888
1889 QualifiedName qName(prefix, localName, namespaceURI);
1890
1891 if (!Document::hasValidNamespaceForAttributes(qName)) {
Ben Murdochdf957042013-08-06 11:01:27 +01001892 es.throwDOMException(NamespaceError);
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001893 return false;
1894 }
1895
1896 out = qName;
1897 return true;
1898}
1899
Ben Murdochdf957042013-08-06 11:01:27 +01001900void Element::setAttributeNS(const AtomicString& namespaceURI, const AtomicString& qualifiedName, const AtomicString& value, ExceptionState& es)
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001901{
1902 QualifiedName parsedName = anyName;
Ben Murdochdf957042013-08-06 11:01:27 +01001903 if (!parseAttributeName(parsedName, namespaceURI, qualifiedName, es))
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001904 return;
1905 setAttribute(parsedName, value);
1906}
1907
1908void Element::removeAttributeInternal(size_t index, SynchronizationOfLazyAttribute inSynchronizationOfLazyAttribute)
1909{
1910 ASSERT_WITH_SECURITY_IMPLICATION(index < attributeCount());
1911
1912 UniqueElementData* elementData = ensureUniqueElementData();
1913
1914 QualifiedName name = elementData->attributeItem(index)->name();
1915 AtomicString valueBeingRemoved = elementData->attributeItem(index)->value();
1916
1917 if (!inSynchronizationOfLazyAttribute) {
1918 if (!valueBeingRemoved.isNull())
1919 willModifyAttribute(name, valueBeingRemoved, nullAtom);
1920 }
1921
1922 if (RefPtr<Attr> attrNode = attrIfExists(name))
1923 detachAttrNodeFromElementWithValue(attrNode.get(), elementData->attributeItem(index)->value());
1924
1925 elementData->removeAttribute(index);
1926
1927 if (!inSynchronizationOfLazyAttribute)
1928 didRemoveAttribute(name);
1929}
1930
1931void Element::addAttributeInternal(const QualifiedName& name, const AtomicString& value, SynchronizationOfLazyAttribute inSynchronizationOfLazyAttribute)
1932{
1933 if (!inSynchronizationOfLazyAttribute)
1934 willModifyAttribute(name, nullAtom, value);
1935 ensureUniqueElementData()->addAttribute(name, value);
1936 if (!inSynchronizationOfLazyAttribute)
1937 didAddAttribute(name, value);
1938}
1939
1940void Element::removeAttribute(const AtomicString& name)
1941{
1942 if (!elementData())
1943 return;
1944
1945 AtomicString localName = shouldIgnoreAttributeCase(this) ? name.lower() : name;
1946 size_t index = elementData()->getAttributeItemIndex(localName, false);
1947 if (index == notFound) {
1948 if (UNLIKELY(localName == styleAttr) && elementData()->m_styleAttributeIsDirty && isStyledElement())
Ben Murdoch591b9582013-07-10 11:41:44 +01001949 removeAllInlineStyleProperties();
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001950 return;
1951 }
1952
1953 removeAttributeInternal(index, NotInSynchronizationOfLazyAttribute);
1954}
1955
1956void Element::removeAttributeNS(const AtomicString& namespaceURI, const AtomicString& localName)
1957{
1958 removeAttribute(QualifiedName(nullAtom, localName, namespaceURI));
1959}
1960
1961PassRefPtr<Attr> Element::getAttributeNode(const AtomicString& localName)
1962{
1963 if (!elementData())
1964 return 0;
1965 synchronizeAttribute(localName);
1966 const Attribute* attribute = elementData()->getAttributeItem(localName, shouldIgnoreAttributeCase(this));
1967 if (!attribute)
1968 return 0;
1969 return ensureAttr(attribute->name());
1970}
1971
1972PassRefPtr<Attr> Element::getAttributeNodeNS(const AtomicString& namespaceURI, const AtomicString& localName)
1973{
1974 if (!elementData())
1975 return 0;
1976 QualifiedName qName(nullAtom, localName, namespaceURI);
1977 synchronizeAttribute(qName);
1978 const Attribute* attribute = elementData()->getAttributeItem(qName);
1979 if (!attribute)
1980 return 0;
1981 return ensureAttr(attribute->name());
1982}
1983
1984bool Element::hasAttribute(const AtomicString& localName) const
1985{
1986 if (!elementData())
1987 return false;
1988 synchronizeAttribute(localName);
1989 return elementData()->getAttributeItem(shouldIgnoreAttributeCase(this) ? localName.lower() : localName, false);
1990}
1991
1992bool Element::hasAttributeNS(const AtomicString& namespaceURI, const AtomicString& localName) const
1993{
1994 if (!elementData())
1995 return false;
1996 QualifiedName qName(nullAtom, localName, namespaceURI);
1997 synchronizeAttribute(qName);
1998 return elementData()->getAttributeItem(qName);
1999}
2000
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002001void Element::focus(bool restorePreviousSelection, FocusDirection direction)
2002{
2003 if (!inDocument())
2004 return;
2005
2006 Document* doc = document();
Ben Murdoch7757ec22013-07-23 11:17:36 +01002007 if (doc->focusedElement() == this)
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002008 return;
2009
2010 // If the stylesheets have already been loaded we can reliably check isFocusable.
2011 // If not, we continue and set the focused node on the focus controller below so
Ben Murdoch591b9582013-07-10 11:41:44 +01002012 // that it can be updated soon after attach.
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002013 if (doc->haveStylesheetsLoaded()) {
2014 doc->updateLayoutIgnorePendingStylesheets();
2015 if (!isFocusable())
2016 return;
2017 }
2018
2019 if (!supportsFocus())
2020 return;
2021
2022 RefPtr<Node> protect;
2023 if (Page* page = doc->page()) {
2024 // Focus and change event handlers can cause us to lose our last ref.
2025 // If a focus event handler changes the focus to a different node it
2026 // does not make sense to continue and update appearence.
2027 protect = this;
Ben Murdoch3c9e4ae2013-08-12 14:20:44 +01002028 if (!page->focusController().setFocusedElement(this, doc->frame(), direction))
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002029 return;
2030 }
2031
2032 // Setting the focused node above might have invalidated the layout due to scripts.
2033 doc->updateLayoutIgnorePendingStylesheets();
2034
2035 if (!isFocusable()) {
2036 ensureElementRareData()->setNeedsFocusAppearanceUpdateSoonAfterAttach(true);
2037 return;
2038 }
Ben Murdoch591b9582013-07-10 11:41:44 +01002039
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002040 cancelFocusAppearanceUpdate();
2041 updateFocusAppearance(restorePreviousSelection);
2042}
2043
2044void Element::updateFocusAppearance(bool /*restorePreviousSelection*/)
2045{
2046 if (isRootEditableElement()) {
2047 Frame* frame = document()->frame();
2048 if (!frame)
2049 return;
Ben Murdoch591b9582013-07-10 11:41:44 +01002050
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002051 // When focusing an editable element in an iframe, don't reset the selection if it already contains a selection.
2052 if (this == frame->selection()->rootEditableElement())
2053 return;
2054
2055 // FIXME: We should restore the previous selection if there is one.
2056 VisibleSelection newSelection = VisibleSelection(firstPositionInOrBeforeNode(this), DOWNSTREAM);
Ben Murdoch591b9582013-07-10 11:41:44 +01002057
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002058 if (frame->selection()->shouldChangeSelection(newSelection)) {
2059 frame->selection()->setSelection(newSelection);
2060 frame->selection()->revealSelection();
2061 }
2062 } else if (renderer() && !renderer()->isWidget())
2063 renderer()->scrollRectToVisible(boundingBox());
2064}
2065
2066void Element::blur()
2067{
2068 cancelFocusAppearanceUpdate();
Ben Murdoche69819b2013-07-17 14:56:49 +01002069 if (treeScope()->adjustedFocusedElement() == this) {
2070 Document* doc = document();
Ben Murdoch3c9e4ae2013-08-12 14:20:44 +01002071 if (doc->page())
2072 doc->page()->focusController().setFocusedElement(0, doc->frame());
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002073 else
Ben Murdoche69819b2013-07-17 14:56:49 +01002074 doc->setFocusedElement(0);
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002075 }
2076}
2077
Ben Murdochdf957042013-08-06 11:01:27 +01002078bool Element::isFocusable() const
2079{
2080 return inDocument() && supportsFocus() && !isInert() && rendererIsFocusable();
2081}
2082
Torne (Richard Coles)f5e4ad52013-08-05 13:57:57 +01002083bool Element::isKeyboardFocusable() const
2084{
2085 return isFocusable() && tabIndex() >= 0;
2086}
2087
2088bool Element::isMouseFocusable() const
2089{
2090 return isFocusable();
2091}
2092
Ben Murdoch02772c62013-07-26 10:21:05 +01002093void Element::dispatchFocusEvent(Element* oldFocusedElement, FocusDirection)
2094{
2095 RefPtr<FocusEvent> event = FocusEvent::create(eventNames().focusEvent, false, false, document()->defaultView(), 0, oldFocusedElement);
2096 EventDispatcher::dispatchEvent(this, FocusEventDispatchMediator::create(event.release()));
2097}
2098
2099void Element::dispatchBlurEvent(Element* newFocusedElement)
2100{
2101 RefPtr<FocusEvent> event = FocusEvent::create(eventNames().blurEvent, false, false, document()->defaultView(), 0, newFocusedElement);
2102 EventDispatcher::dispatchEvent(this, BlurEventDispatchMediator::create(event.release()));
2103}
2104
2105void Element::dispatchFocusInEvent(const AtomicString& eventType, Element* oldFocusedElement)
2106{
2107 ASSERT(!NoEventDispatchAssertion::isEventDispatchForbidden());
2108 ASSERT(eventType == eventNames().focusinEvent || eventType == eventNames().DOMFocusInEvent);
2109 dispatchScopedEventDispatchMediator(FocusInEventDispatchMediator::create(FocusEvent::create(eventType, true, false, document()->defaultView(), 0, oldFocusedElement)));
2110}
2111
2112void Element::dispatchFocusOutEvent(const AtomicString& eventType, Element* newFocusedElement)
2113{
2114 ASSERT(!NoEventDispatchAssertion::isEventDispatchForbidden());
2115 ASSERT(eventType == eventNames().focusoutEvent || eventType == eventNames().DOMFocusOutEvent);
2116 dispatchScopedEventDispatchMediator(FocusOutEventDispatchMediator::create(FocusEvent::create(eventType, true, false, document()->defaultView(), 0, newFocusedElement)));
2117}
2118
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002119String Element::innerText()
2120{
2121 // We need to update layout, since plainText uses line boxes in the render tree.
2122 document()->updateLayoutIgnorePendingStylesheets();
2123
2124 if (!renderer())
2125 return textContent(true);
2126
2127 return plainText(rangeOfContents(const_cast<Element*>(this)).get());
2128}
2129
2130String Element::outerText()
2131{
2132 // Getting outerText is the same as getting innerText, only
2133 // setting is different. You would think this should get the plain
2134 // text for the outer range, but this is wrong, <br> for instance
2135 // would return different values for inner and outer text by such
2136 // a rule, but it doesn't in WinIE, and we want to match that.
2137 return innerText();
2138}
2139
Ben Murdoch591b9582013-07-10 11:41:44 +01002140String Element::textFromChildren()
2141{
2142 Text* firstTextNode = 0;
2143 bool foundMultipleTextNodes = false;
2144 unsigned totalLength = 0;
2145
2146 for (Node* child = firstChild(); child; child = child->nextSibling()) {
2147 if (!child->isTextNode())
2148 continue;
2149 Text* text = toText(child);
2150 if (!firstTextNode)
2151 firstTextNode = text;
2152 else
2153 foundMultipleTextNodes = true;
2154 unsigned length = text->data().length();
2155 if (length > std::numeric_limits<unsigned>::max() - totalLength)
2156 return emptyString();
2157 totalLength += length;
2158 }
2159
2160 if (!firstTextNode)
2161 return emptyString();
2162
2163 if (firstTextNode && !foundMultipleTextNodes) {
2164 firstTextNode->atomize();
2165 return firstTextNode->data();
2166 }
2167
2168 StringBuilder content;
2169 content.reserveCapacity(totalLength);
2170 for (Node* child = firstTextNode; child; child = child->nextSibling()) {
2171 if (!child->isTextNode())
2172 continue;
2173 content.append(toText(child)->data());
2174 }
2175
2176 ASSERT(content.length() == totalLength);
2177 return content.toString();
2178}
2179
Ben Murdoch3c9e4ae2013-08-12 14:20:44 +01002180// pseudo is used via shadowPseudoId.
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002181const AtomicString& Element::pseudo() const
2182{
2183 return getAttribute(pseudoAttr);
2184}
2185
Torne (Richard Coles)f5e4ad52013-08-05 13:57:57 +01002186const AtomicString& Element::part() const
2187{
2188 return getAttribute(partAttr);
2189}
2190
2191void Element::setPart(const AtomicString& value)
2192{
2193 setAttribute(partAttr, value);
2194}
2195
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002196LayoutSize Element::minimumSizeForResizing() const
2197{
2198 return hasRareData() ? elementRareData()->minimumSizeForResizing() : defaultMinimumSizeForResizing();
2199}
2200
2201void Element::setMinimumSizeForResizing(const LayoutSize& size)
2202{
2203 if (!hasRareData() && size == defaultMinimumSizeForResizing())
2204 return;
2205 ensureElementRareData()->setMinimumSizeForResizing(size);
2206}
2207
2208RenderStyle* Element::computedStyle(PseudoId pseudoElementSpecifier)
2209{
2210 if (PseudoElement* element = pseudoElement(pseudoElementSpecifier))
2211 return element->computedStyle();
2212
2213 // FIXME: Find and use the renderer from the pseudo element instead of the actual element so that the 'length'
2214 // properties, which are only known by the renderer because it did the layout, will be correct and so that the
2215 // values returned for the ":selection" pseudo-element will be correct.
2216 if (RenderStyle* usedStyle = renderStyle()) {
2217 if (pseudoElementSpecifier) {
2218 RenderStyle* cachedPseudoStyle = usedStyle->getCachedPseudoStyle(pseudoElementSpecifier);
2219 return cachedPseudoStyle ? cachedPseudoStyle : usedStyle;
2220 } else
2221 return usedStyle;
2222 }
2223
2224 if (!attached())
2225 // FIXME: Try to do better than this. Ensure that styleForElement() works for elements that are not in the
2226 // document tree and figure out when to destroy the computed style for such elements.
2227 return 0;
2228
2229 ElementRareData* data = ensureElementRareData();
2230 if (!data->computedStyle())
2231 data->setComputedStyle(document()->styleForElementIgnoringPendingStylesheets(this));
2232 return pseudoElementSpecifier ? data->computedStyle()->getCachedPseudoStyle(pseudoElementSpecifier) : data->computedStyle();
2233}
2234
2235void Element::setStyleAffectedByEmpty()
2236{
2237 ensureElementRareData()->setStyleAffectedByEmpty(true);
2238}
2239
2240void Element::setChildrenAffectedByHover(bool value)
2241{
2242 if (value || hasRareData())
2243 ensureElementRareData()->setChildrenAffectedByHover(value);
2244}
2245
2246void Element::setChildrenAffectedByActive(bool value)
2247{
2248 if (value || hasRareData())
2249 ensureElementRareData()->setChildrenAffectedByActive(value);
2250}
2251
2252void Element::setChildrenAffectedByDrag(bool value)
2253{
2254 if (value || hasRareData())
2255 ensureElementRareData()->setChildrenAffectedByDrag(value);
2256}
2257
2258void Element::setChildrenAffectedByFirstChildRules()
2259{
2260 ensureElementRareData()->setChildrenAffectedByFirstChildRules(true);
2261}
2262
2263void Element::setChildrenAffectedByLastChildRules()
2264{
2265 ensureElementRareData()->setChildrenAffectedByLastChildRules(true);
2266}
2267
2268void Element::setChildrenAffectedByDirectAdjacentRules()
2269{
2270 ensureElementRareData()->setChildrenAffectedByDirectAdjacentRules(true);
2271}
2272
2273void Element::setChildrenAffectedByForwardPositionalRules()
2274{
2275 ensureElementRareData()->setChildrenAffectedByForwardPositionalRules(true);
2276}
2277
2278void Element::setChildrenAffectedByBackwardPositionalRules()
2279{
2280 ensureElementRareData()->setChildrenAffectedByBackwardPositionalRules(true);
2281}
2282
2283void Element::setChildIndex(unsigned index)
2284{
2285 ElementRareData* rareData = ensureElementRareData();
2286 if (RenderStyle* style = renderStyle())
2287 style->setUnique();
2288 rareData->setChildIndex(index);
2289}
2290
2291bool Element::hasFlagsSetDuringStylingOfChildren() const
2292{
2293 if (!hasRareData())
2294 return false;
2295 return rareDataChildrenAffectedByHover()
2296 || rareDataChildrenAffectedByActive()
2297 || rareDataChildrenAffectedByDrag()
2298 || rareDataChildrenAffectedByFirstChildRules()
2299 || rareDataChildrenAffectedByLastChildRules()
2300 || rareDataChildrenAffectedByDirectAdjacentRules()
2301 || rareDataChildrenAffectedByForwardPositionalRules()
2302 || rareDataChildrenAffectedByBackwardPositionalRules();
2303}
2304
2305bool Element::rareDataStyleAffectedByEmpty() const
2306{
2307 ASSERT(hasRareData());
2308 return elementRareData()->styleAffectedByEmpty();
2309}
2310
2311bool Element::rareDataChildrenAffectedByHover() const
2312{
2313 ASSERT(hasRareData());
2314 return elementRareData()->childrenAffectedByHover();
2315}
2316
2317bool Element::rareDataChildrenAffectedByActive() const
2318{
2319 ASSERT(hasRareData());
2320 return elementRareData()->childrenAffectedByActive();
2321}
2322
2323bool Element::rareDataChildrenAffectedByDrag() const
2324{
2325 ASSERT(hasRareData());
2326 return elementRareData()->childrenAffectedByDrag();
2327}
2328
2329bool Element::rareDataChildrenAffectedByFirstChildRules() const
2330{
2331 ASSERT(hasRareData());
2332 return elementRareData()->childrenAffectedByFirstChildRules();
2333}
2334
2335bool Element::rareDataChildrenAffectedByLastChildRules() const
2336{
2337 ASSERT(hasRareData());
2338 return elementRareData()->childrenAffectedByLastChildRules();
2339}
2340
2341bool Element::rareDataChildrenAffectedByDirectAdjacentRules() const
2342{
2343 ASSERT(hasRareData());
2344 return elementRareData()->childrenAffectedByDirectAdjacentRules();
2345}
2346
2347bool Element::rareDataChildrenAffectedByForwardPositionalRules() const
2348{
2349 ASSERT(hasRareData());
2350 return elementRareData()->childrenAffectedByForwardPositionalRules();
2351}
2352
2353bool Element::rareDataChildrenAffectedByBackwardPositionalRules() const
2354{
2355 ASSERT(hasRareData());
2356 return elementRareData()->childrenAffectedByBackwardPositionalRules();
2357}
2358
2359unsigned Element::rareDataChildIndex() const
2360{
2361 ASSERT(hasRareData());
2362 return elementRareData()->childIndex();
2363}
2364
2365void Element::setIsInCanvasSubtree(bool isInCanvasSubtree)
2366{
2367 ensureElementRareData()->setIsInCanvasSubtree(isInCanvasSubtree);
2368}
2369
2370bool Element::isInCanvasSubtree() const
2371{
2372 return hasRareData() && elementRareData()->isInCanvasSubtree();
2373}
2374
Ben Murdoch591b9582013-07-10 11:41:44 +01002375void Element::setIsInsideRegion(bool value)
2376{
2377 if (value == isInsideRegion())
2378 return;
2379
2380 ensureElementRareData()->setIsInsideRegion(value);
2381}
2382
2383bool Element::isInsideRegion() const
2384{
2385 return hasRareData() ? elementRareData()->isInsideRegion() : false;
2386}
2387
2388void Element::setRegionOversetState(RegionOversetState state)
2389{
2390 ensureElementRareData()->setRegionOversetState(state);
2391}
2392
2393RegionOversetState Element::regionOversetState() const
2394{
2395 return hasRareData() ? elementRareData()->regionOversetState() : RegionUndefined;
2396}
2397
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002398AtomicString Element::computeInheritedLanguage() const
2399{
2400 const Node* n = this;
2401 AtomicString value;
2402 // The language property is inherited, so we iterate over the parents to find the first language.
2403 do {
2404 if (n->isElementNode()) {
2405 if (const ElementData* elementData = toElement(n)->elementData()) {
2406 // Spec: xml:lang takes precedence -- http://www.w3.org/TR/xhtml1/#C_7
2407 if (const Attribute* attribute = elementData->getAttributeItem(XMLNames::langAttr))
2408 value = attribute->value();
2409 else if (const Attribute* attribute = elementData->getAttributeItem(HTMLNames::langAttr))
2410 value = attribute->value();
2411 }
2412 } else if (n->isDocumentNode()) {
2413 // checking the MIME content-language
2414 value = toDocument(n)->contentLanguage();
2415 }
2416
2417 n = n->parentNode();
2418 } while (n && value.isNull());
2419
2420 return value;
2421}
2422
2423Locale& Element::locale() const
2424{
2425 return document()->getCachedLocale(computeInheritedLanguage());
2426}
2427
2428void Element::cancelFocusAppearanceUpdate()
2429{
2430 if (hasRareData())
2431 elementRareData()->setNeedsFocusAppearanceUpdateSoonAfterAttach(false);
Ben Murdoch7757ec22013-07-23 11:17:36 +01002432 if (document()->focusedElement() == this)
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002433 document()->cancelFocusAppearanceUpdate();
2434}
2435
2436void Element::normalizeAttributes()
2437{
2438 if (!hasAttributes())
2439 return;
2440 for (unsigned i = 0; i < attributeCount(); ++i) {
2441 if (RefPtr<Attr> attr = attrIfExists(attributeItem(i)->name()))
2442 attr->normalize();
2443 }
2444}
2445
2446void Element::updatePseudoElement(PseudoId pseudoId, StyleChange change)
2447{
2448 PseudoElement* element = pseudoElement(pseudoId);
2449 if (element && (needsStyleRecalc() || shouldRecalcStyle(change, element))) {
2450 // PseudoElement styles hang off their parent element's style so if we needed
2451 // a style recalc we should Force one on the pseudo.
2452 element->recalcStyle(needsStyleRecalc() ? Force : change);
2453
2454 // Wait until our parent is not displayed or pseudoElementRendererIsNeeded
2455 // is false, otherwise we could continously create and destroy PseudoElements
2456 // when RenderObject::isChildAllowed on our parent returns false for the
2457 // PseudoElement's renderer for each style recalc.
2458 if (!renderer() || !pseudoElementRendererIsNeeded(renderer()->getCachedPseudoStyle(pseudoId)))
Torne (Richard Coles)521d96e2013-06-19 11:58:24 +01002459 elementRareData()->setPseudoElement(pseudoId, 0);
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002460 } else if (change >= Inherit || needsStyleRecalc())
2461 createPseudoElementIfNeeded(pseudoId);
2462}
2463
2464void Element::createPseudoElementIfNeeded(PseudoId pseudoId)
2465{
Ben Murdoche69819b2013-07-17 14:56:49 +01002466 if ((pseudoId == BEFORE || pseudoId == AFTER) && !document()->styleSheetCollection()->usesBeforeAfterRules())
2467 return;
2468
2469 if (pseudoId == BACKDROP && !isInTopLayer())
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002470 return;
2471
2472 if (!renderer() || !pseudoElementRendererIsNeeded(renderer()->getCachedPseudoStyle(pseudoId)))
2473 return;
2474
2475 if (!renderer()->canHaveGeneratedChildren())
2476 return;
2477
2478 ASSERT(!isPseudoElement());
2479 RefPtr<PseudoElement> element = PseudoElement::create(this, pseudoId);
Ben Murdoche69819b2013-07-17 14:56:49 +01002480 if (pseudoId == BACKDROP)
2481 document()->addToTopLayer(element.get(), this);
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002482 element->attach();
Ben Murdoche69819b2013-07-17 14:56:49 +01002483
Torne (Richard Coles)521d96e2013-06-19 11:58:24 +01002484 ensureElementRareData()->setPseudoElement(pseudoId, element.release());
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002485}
2486
2487PseudoElement* Element::pseudoElement(PseudoId pseudoId) const
2488{
2489 return hasRareData() ? elementRareData()->pseudoElement(pseudoId) : 0;
2490}
2491
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002492RenderObject* Element::pseudoElementRenderer(PseudoId pseudoId) const
2493{
2494 if (PseudoElement* element = pseudoElement(pseudoId))
2495 return element->renderer();
2496 return 0;
2497}
2498
Ben Murdochdf957042013-08-06 11:01:27 +01002499bool Element::webkitMatchesSelector(const String& selector, ExceptionState& es)
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002500{
2501 if (selector.isEmpty()) {
Ben Murdochdf957042013-08-06 11:01:27 +01002502 es.throwDOMException(SyntaxError);
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002503 return false;
2504 }
2505
Ben Murdochdf957042013-08-06 11:01:27 +01002506 SelectorQuery* selectorQuery = document()->selectorQueryCache()->add(selector, document(), es);
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002507 if (!selectorQuery)
2508 return false;
2509 return selectorQuery->matches(this);
2510}
2511
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002512DOMTokenList* Element::classList()
2513{
2514 ElementRareData* data = ensureElementRareData();
2515 if (!data->classList())
2516 data->setClassList(ClassList::create(this));
2517 return data->classList();
2518}
2519
2520DOMStringMap* Element::dataset()
2521{
2522 ElementRareData* data = ensureElementRareData();
2523 if (!data->dataset())
2524 data->setDataset(DatasetDOMStringMap::create(this));
2525 return data->dataset();
2526}
2527
2528KURL Element::getURLAttribute(const QualifiedName& name) const
2529{
2530#if !ASSERT_DISABLED
2531 if (elementData()) {
2532 if (const Attribute* attribute = getAttributeItem(name))
2533 ASSERT(isURLAttribute(*attribute));
2534 }
2535#endif
2536 return document()->completeURL(stripLeadingAndTrailingHTMLSpaces(getAttribute(name)));
2537}
2538
2539KURL Element::getNonEmptyURLAttribute(const QualifiedName& name) const
2540{
2541#if !ASSERT_DISABLED
2542 if (elementData()) {
2543 if (const Attribute* attribute = getAttributeItem(name))
2544 ASSERT(isURLAttribute(*attribute));
2545 }
2546#endif
2547 String value = stripLeadingAndTrailingHTMLSpaces(getAttribute(name));
2548 if (value.isEmpty())
2549 return KURL();
2550 return document()->completeURL(value);
2551}
2552
2553int Element::getIntegralAttribute(const QualifiedName& attributeName) const
2554{
2555 return getAttribute(attributeName).string().toInt();
2556}
2557
2558void Element::setIntegralAttribute(const QualifiedName& attributeName, int value)
2559{
2560 // FIXME: Need an AtomicString version of String::number.
2561 setAttribute(attributeName, String::number(value));
2562}
2563
2564unsigned Element::getUnsignedIntegralAttribute(const QualifiedName& attributeName) const
2565{
2566 return getAttribute(attributeName).string().toUInt();
2567}
2568
2569void Element::setUnsignedIntegralAttribute(const QualifiedName& attributeName, unsigned value)
2570{
2571 // FIXME: Need an AtomicString version of String::number.
2572 setAttribute(attributeName, String::number(value));
2573}
2574
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002575bool Element::childShouldCreateRenderer(const NodeRenderingContext& childContext) const
2576{
2577 // Only create renderers for SVG elements whose parents are SVG elements, or for proper <svg xmlns="svgNS"> subdocuments.
2578 if (childContext.node()->isSVGElement())
2579 return childContext.node()->hasTagName(SVGNames::svgTag) || isSVGElement();
2580
2581 return ContainerNode::childShouldCreateRenderer(childContext);
2582}
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002583
2584void Element::webkitRequestFullscreen()
2585{
Torne (Richard Coles)f5e4ad52013-08-05 13:57:57 +01002586 FullscreenElementStack::from(document())->requestFullScreenForElement(this, ALLOW_KEYBOARD_INPUT, FullscreenElementStack::EnforceIFrameAllowFullScreenRequirement);
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002587}
2588
2589void Element::webkitRequestFullScreen(unsigned short flags)
2590{
Torne (Richard Coles)f5e4ad52013-08-05 13:57:57 +01002591 FullscreenElementStack::from(document())->requestFullScreenForElement(this, (flags | LEGACY_MOZILLA_REQUEST), FullscreenElementStack::EnforceIFrameAllowFullScreenRequirement);
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002592}
2593
2594bool Element::containsFullScreenElement() const
2595{
2596 return hasRareData() && elementRareData()->containsFullScreenElement();
2597}
2598
2599void Element::setContainsFullScreenElement(bool flag)
2600{
2601 ensureElementRareData()->setContainsFullScreenElement(flag);
Ben Murdoche69819b2013-07-17 14:56:49 +01002602 setNeedsStyleRecalc(SubtreeStyleChange);
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002603}
2604
2605static Element* parentCrossingFrameBoundaries(Element* element)
2606{
2607 ASSERT(element);
2608 return element->parentElement() ? element->parentElement() : element->document()->ownerElement();
2609}
2610
2611void Element::setContainsFullScreenElementOnAncestorsCrossingFrameBoundaries(bool flag)
2612{
2613 Element* element = this;
2614 while ((element = parentCrossingFrameBoundaries(element)))
2615 element->setContainsFullScreenElement(flag);
2616}
2617
2618bool Element::isInTopLayer() const
2619{
2620 return hasRareData() && elementRareData()->isInTopLayer();
2621}
2622
2623void Element::setIsInTopLayer(bool inTopLayer)
2624{
2625 if (isInTopLayer() == inTopLayer)
2626 return;
2627 ensureElementRareData()->setIsInTopLayer(inTopLayer);
2628
2629 // We must ensure a reattach occurs so the renderer is inserted in the correct sibling order under RenderView according to its
2630 // top layer position, or in its usual place if not in the top layer.
Torne (Richard Coles)93ac45c2013-05-29 14:40:20 +01002631 lazyReattachIfAttached();
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002632}
2633
2634void Element::webkitRequestPointerLock()
2635{
2636 if (document()->page())
Torne (Richard Coles)e1f1df52013-08-23 16:39:30 +01002637 document()->page()->pointerLockController().requestPointerLock(this);
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002638}
2639
2640SpellcheckAttributeState Element::spellcheckAttributeState() const
2641{
2642 const AtomicString& value = getAttribute(HTMLNames::spellcheckAttr);
2643 if (value == nullAtom)
2644 return SpellcheckAttributeDefault;
2645 if (equalIgnoringCase(value, "true") || equalIgnoringCase(value, ""))
2646 return SpellcheckAttributeTrue;
2647 if (equalIgnoringCase(value, "false"))
2648 return SpellcheckAttributeFalse;
2649
2650 return SpellcheckAttributeDefault;
2651}
2652
2653bool Element::isSpellCheckingEnabled() const
2654{
2655 for (const Element* element = this; element; element = element->parentOrShadowHostElement()) {
2656 switch (element->spellcheckAttributeState()) {
2657 case SpellcheckAttributeTrue:
2658 return true;
2659 case SpellcheckAttributeFalse:
2660 return false;
2661 case SpellcheckAttributeDefault:
2662 break;
2663 }
2664 }
2665
2666 return true;
2667}
2668
2669RenderRegion* Element::renderRegion() const
2670{
2671 if (renderer() && renderer()->isRenderRegion())
2672 return toRenderRegion(renderer());
2673
2674 return 0;
2675}
2676
Ben Murdoch591b9582013-07-10 11:41:44 +01002677bool Element::shouldMoveToFlowThread(RenderStyle* styleToUse) const
2678{
2679 ASSERT(styleToUse);
2680
Torne (Richard Coles)f5e4ad52013-08-05 13:57:57 +01002681 if (FullscreenElementStack::isActiveFullScreenElement(this))
Ben Murdoch591b9582013-07-10 11:41:44 +01002682 return false;
2683
2684 if (isInShadowTree())
2685 return false;
2686
2687 if (styleToUse->flowThread().isEmpty())
2688 return false;
2689
2690 return !isRegisteredWithNamedFlow();
2691}
2692
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002693const AtomicString& Element::webkitRegionOverset() const
2694{
2695 document()->updateLayoutIgnorePendingStylesheets();
2696
2697 DEFINE_STATIC_LOCAL(AtomicString, undefinedState, ("undefined", AtomicString::ConstructFromLiteral));
2698 if (!RuntimeEnabledFeatures::cssRegionsEnabled() || !renderRegion())
2699 return undefinedState;
2700
Ben Murdoch591b9582013-07-10 11:41:44 +01002701 switch (renderRegion()->regionOversetState()) {
2702 case RegionFit: {
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002703 DEFINE_STATIC_LOCAL(AtomicString, fitState, ("fit", AtomicString::ConstructFromLiteral));
2704 return fitState;
2705 }
Ben Murdoch591b9582013-07-10 11:41:44 +01002706 case RegionEmpty: {
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002707 DEFINE_STATIC_LOCAL(AtomicString, emptyState, ("empty", AtomicString::ConstructFromLiteral));
2708 return emptyState;
2709 }
Ben Murdoch591b9582013-07-10 11:41:44 +01002710 case RegionOverset: {
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002711 DEFINE_STATIC_LOCAL(AtomicString, overflowState, ("overset", AtomicString::ConstructFromLiteral));
2712 return overflowState;
2713 }
Ben Murdoch591b9582013-07-10 11:41:44 +01002714 case RegionUndefined:
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002715 return undefinedState;
2716 }
2717
2718 ASSERT_NOT_REACHED();
2719 return undefinedState;
2720}
2721
2722Vector<RefPtr<Range> > Element::webkitGetRegionFlowRanges() const
2723{
2724 document()->updateLayoutIgnorePendingStylesheets();
2725
2726 Vector<RefPtr<Range> > rangeObjects;
2727 if (RuntimeEnabledFeatures::cssRegionsEnabled() && renderer() && renderer()->isRenderRegion()) {
2728 RenderRegion* region = toRenderRegion(renderer());
2729 if (region->isValid())
2730 region->getRanges(rangeObjects);
2731 }
2732
2733 return rangeObjects;
2734}
2735
2736#ifndef NDEBUG
2737bool Element::fastAttributeLookupAllowed(const QualifiedName& name) const
2738{
2739 if (name == HTMLNames::styleAttr)
2740 return false;
2741
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002742 if (isSVGElement())
2743 return !static_cast<const SVGElement*>(this)->isAnimatableAttribute(name);
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002744
2745 return true;
2746}
2747#endif
2748
2749#ifdef DUMP_NODE_STATISTICS
2750bool Element::hasNamedNodeMap() const
2751{
2752 return hasRareData() && elementRareData()->attributeMap();
2753}
2754#endif
2755
Ben Murdoch00d3faa2013-08-14 11:52:03 +01002756inline void Element::updateName(const AtomicString& oldName, const AtomicString& newName)
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002757{
Ben Murdoch00d3faa2013-08-14 11:52:03 +01002758 if (!inDocument() || isInShadowTree())
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002759 return;
2760
2761 if (oldName == newName)
2762 return;
2763
Ben Murdochdf957042013-08-06 11:01:27 +01002764 if (shouldRegisterAsNamedItem())
2765 updateNamedItemRegistration(oldName, newName);
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002766}
2767
Ben Murdoch00d3faa2013-08-14 11:52:03 +01002768inline void Element::updateId(const AtomicString& oldId, const AtomicString& newId)
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002769{
2770 if (!isInTreeScope())
2771 return;
2772
2773 if (oldId == newId)
2774 return;
2775
Ben Murdoch00d3faa2013-08-14 11:52:03 +01002776 updateId(treeScope(), oldId, newId);
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002777}
2778
Ben Murdoch00d3faa2013-08-14 11:52:03 +01002779inline void Element::updateId(TreeScope* scope, const AtomicString& oldId, const AtomicString& newId)
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002780{
2781 ASSERT(isInTreeScope());
2782 ASSERT(oldId != newId);
2783
2784 if (!oldId.isEmpty())
2785 scope->removeElementById(oldId, this);
2786 if (!newId.isEmpty())
2787 scope->addElementById(newId, this);
2788
Ben Murdochdf957042013-08-06 11:01:27 +01002789 if (shouldRegisterAsExtraNamedItem())
2790 updateExtraNamedItemRegistration(oldId, newId);
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002791}
2792
2793void Element::updateLabel(TreeScope* scope, const AtomicString& oldForAttributeValue, const AtomicString& newForAttributeValue)
2794{
2795 ASSERT(hasTagName(labelTag));
2796
2797 if (!inDocument())
2798 return;
2799
2800 if (oldForAttributeValue == newForAttributeValue)
2801 return;
2802
2803 if (!oldForAttributeValue.isEmpty())
Ben Murdoche69819b2013-07-17 14:56:49 +01002804 scope->removeLabel(oldForAttributeValue, toHTMLLabelElement(this));
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002805 if (!newForAttributeValue.isEmpty())
Ben Murdoche69819b2013-07-17 14:56:49 +01002806 scope->addLabel(newForAttributeValue, toHTMLLabelElement(this));
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002807}
2808
Ben Murdoch7757ec22013-07-23 11:17:36 +01002809static bool hasSelectorForAttribute(Document* document, const AtomicString& localName)
2810{
2811 return document->styleResolver() && document->styleResolver()->ruleFeatureSet().hasSelectorForAttribute(localName);
2812}
2813
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002814void Element::willModifyAttribute(const QualifiedName& name, const AtomicString& oldValue, const AtomicString& newValue)
2815{
2816 if (isIdAttributeName(name))
2817 updateId(oldValue, newValue);
2818 else if (name == HTMLNames::nameAttr)
2819 updateName(oldValue, newValue);
2820 else if (name == HTMLNames::forAttr && hasTagName(labelTag)) {
2821 TreeScope* scope = treeScope();
2822 if (scope->shouldCacheLabelsByForAttribute())
2823 updateLabel(scope, oldValue, newValue);
2824 }
2825
2826 if (oldValue != newValue) {
Ben Murdoch7757ec22013-07-23 11:17:36 +01002827 if (attached() && hasSelectorForAttribute(document(), name.localName()))
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002828 setNeedsStyleRecalc();
Ben Murdoche69819b2013-07-17 14:56:49 +01002829
2830 if (isUpgradedCustomElement())
Ben Murdoch83750172013-07-24 10:36:59 +01002831 CustomElement::attributeDidChange(this, name.localName(), oldValue, newValue);
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002832 }
2833
2834 if (OwnPtr<MutationObserverInterestGroup> recipients = MutationObserverInterestGroup::createForAttributesMutation(this, name))
2835 recipients->enqueueMutationRecord(MutationRecord::createAttributes(this, name, oldValue));
2836
2837 InspectorInstrumentation::willModifyDOMAttr(document(), this, oldValue, newValue);
2838}
2839
2840void Element::didAddAttribute(const QualifiedName& name, const AtomicString& value)
2841{
2842 attributeChanged(name, value);
2843 InspectorInstrumentation::didModifyDOMAttr(document(), this, name.localName(), value);
2844 dispatchSubtreeModifiedEvent();
2845}
2846
2847void Element::didModifyAttribute(const QualifiedName& name, const AtomicString& value)
2848{
2849 attributeChanged(name, value);
2850 InspectorInstrumentation::didModifyDOMAttr(document(), this, name.localName(), value);
2851 // Do not dispatch a DOMSubtreeModified event here; see bug 81141.
2852}
2853
2854void Element::didRemoveAttribute(const QualifiedName& name)
2855{
2856 attributeChanged(name, nullAtom);
2857 InspectorInstrumentation::didRemoveDOMAttr(document(), this, name.localName());
2858 dispatchSubtreeModifiedEvent();
2859}
2860
Ben Murdoche69819b2013-07-17 14:56:49 +01002861void Element::didMoveToNewDocument(Document* oldDocument)
2862{
2863 Node::didMoveToNewDocument(oldDocument);
2864
2865 // If the documents differ by quirks mode then they differ by case sensitivity
2866 // for class and id names so we need to go through the attribute change logic
2867 // to pick up the new casing in the ElementData.
2868 if (oldDocument->inQuirksMode() != document()->inQuirksMode()) {
2869 if (hasID())
2870 setIdAttribute(getIdAttribute());
2871 if (hasClass())
2872 setAttribute(HTMLNames::classAttr, getClassAttribute());
2873 }
2874}
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002875
Ben Murdochdf957042013-08-06 11:01:27 +01002876void Element::updateNamedItemRegistration(const AtomicString& oldName, const AtomicString& newName)
2877{
Ben Murdoch00d3faa2013-08-14 11:52:03 +01002878 if (!document()->isHTMLDocument())
2879 return;
Ben Murdochdf957042013-08-06 11:01:27 +01002880
2881 if (!oldName.isEmpty())
2882 toHTMLDocument(document())->removeNamedItem(oldName);
2883
2884 if (!newName.isEmpty())
2885 toHTMLDocument(document())->addNamedItem(newName);
2886}
2887
2888void Element::updateExtraNamedItemRegistration(const AtomicString& oldId, const AtomicString& newId)
2889{
Ben Murdoch00d3faa2013-08-14 11:52:03 +01002890 if (!document()->isHTMLDocument())
2891 return;
Ben Murdochdf957042013-08-06 11:01:27 +01002892
2893 if (!oldId.isEmpty())
2894 toHTMLDocument(document())->removeExtraNamedItem(oldId);
2895
2896 if (!newId.isEmpty())
2897 toHTMLDocument(document())->addExtraNamedItem(newId);
2898}
2899
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002900PassRefPtr<HTMLCollection> Element::ensureCachedHTMLCollection(CollectionType type)
2901{
2902 if (HTMLCollection* collection = cachedHTMLCollection(type))
2903 return collection;
2904
2905 RefPtr<HTMLCollection> collection;
2906 if (type == TableRows) {
2907 ASSERT(hasTagName(tableTag));
2908 return ensureRareData()->ensureNodeLists()->addCacheWithAtomicName<HTMLTableRowsCollection>(this, type);
2909 } else if (type == SelectOptions) {
2910 ASSERT(hasTagName(selectTag));
2911 return ensureRareData()->ensureNodeLists()->addCacheWithAtomicName<HTMLOptionsCollection>(this, type);
2912 } else if (type == FormControls) {
2913 ASSERT(hasTagName(formTag) || hasTagName(fieldsetTag));
2914 return ensureRareData()->ensureNodeLists()->addCacheWithAtomicName<HTMLFormControlsCollection>(this, type);
2915 }
2916 return ensureRareData()->ensureNodeLists()->addCacheWithAtomicName<HTMLCollection>(this, type);
2917}
2918
Ben Murdoch591b9582013-07-10 11:41:44 +01002919static void scheduleLayerUpdateCallback(Node* node)
Torne (Richard Coles)93ac45c2013-05-29 14:40:20 +01002920{
Ben Murdoche69819b2013-07-17 14:56:49 +01002921 // Notify the renderer even is the styles are identical since it may need to
2922 // create or destroy a RenderLayer.
2923 node->setNeedsStyleRecalc(LocalStyleChange, StyleChangeFromRenderer);
Torne (Richard Coles)93ac45c2013-05-29 14:40:20 +01002924}
2925
Ben Murdoch591b9582013-07-10 11:41:44 +01002926void Element::scheduleLayerUpdate()
Torne (Richard Coles)93ac45c2013-05-29 14:40:20 +01002927{
2928 if (postAttachCallbacksAreSuspended())
Ben Murdoch591b9582013-07-10 11:41:44 +01002929 queuePostAttachCallback(scheduleLayerUpdateCallback, this);
Torne (Richard Coles)93ac45c2013-05-29 14:40:20 +01002930 else
Ben Murdoche69819b2013-07-17 14:56:49 +01002931 scheduleLayerUpdateCallback(this);
Torne (Richard Coles)93ac45c2013-05-29 14:40:20 +01002932}
2933
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002934HTMLCollection* Element::cachedHTMLCollection(CollectionType type)
2935{
2936 return hasRareData() && rareData()->nodeLists() ? rareData()->nodeLists()->cacheWithAtomicName<HTMLCollection>(type) : 0;
2937}
2938
2939IntSize Element::savedLayerScrollOffset() const
2940{
2941 return hasRareData() ? elementRareData()->savedLayerScrollOffset() : IntSize();
2942}
2943
2944void Element::setSavedLayerScrollOffset(const IntSize& size)
2945{
2946 if (size.isZero() && !hasRareData())
2947 return;
2948 ensureElementRareData()->setSavedLayerScrollOffset(size);
2949}
2950
2951PassRefPtr<Attr> Element::attrIfExists(const QualifiedName& name)
2952{
2953 if (AttrNodeList* attrNodeList = attrNodeListForElement(this))
2954 return findAttrNodeInList(attrNodeList, name);
2955 return 0;
2956}
2957
2958PassRefPtr<Attr> Element::ensureAttr(const QualifiedName& name)
2959{
2960 AttrNodeList* attrNodeList = ensureAttrNodeListForElement(this);
2961 RefPtr<Attr> attrNode = findAttrNodeInList(attrNodeList, name);
2962 if (!attrNode) {
2963 attrNode = Attr::create(this, name);
2964 treeScope()->adoptIfNeeded(attrNode.get());
2965 attrNodeList->append(attrNode);
2966 }
2967 return attrNode.release();
2968}
2969
2970void Element::detachAttrNodeFromElementWithValue(Attr* attrNode, const AtomicString& value)
2971{
2972 ASSERT(hasSyntheticAttrChildNodes());
2973 attrNode->detachFromElementWithValue(value);
2974
2975 AttrNodeList* attrNodeList = attrNodeListForElement(this);
2976 for (unsigned i = 0; i < attrNodeList->size(); ++i) {
2977 if (attrNodeList->at(i)->qualifiedName() == attrNode->qualifiedName()) {
2978 attrNodeList->remove(i);
2979 if (attrNodeList->isEmpty())
2980 removeAttrNodeListForElement(this);
2981 return;
2982 }
2983 }
2984 ASSERT_NOT_REACHED();
2985}
2986
2987void Element::detachAllAttrNodesFromElement()
2988{
2989 AttrNodeList* attrNodeList = attrNodeListForElement(this);
2990 ASSERT(attrNodeList);
2991
2992 for (unsigned i = 0; i < attributeCount(); ++i) {
2993 const Attribute* attribute = attributeItem(i);
2994 if (RefPtr<Attr> attrNode = findAttrNodeInList(attrNodeList, attribute->name()))
2995 attrNode->detachFromElementWithValue(attribute->value());
2996 }
2997
2998 removeAttrNodeListForElement(this);
2999}
3000
3001void Element::willRecalcStyle(StyleChange)
3002{
3003 ASSERT(hasCustomStyleCallbacks());
3004}
3005
3006void Element::didRecalcStyle(StyleChange)
3007{
3008 ASSERT(hasCustomStyleCallbacks());
3009}
3010
3011
3012PassRefPtr<RenderStyle> Element::customStyleForRenderer()
3013{
3014 ASSERT(hasCustomStyleCallbacks());
3015 return 0;
3016}
3017
3018void Element::cloneAttributesFromElement(const Element& other)
3019{
3020 if (hasSyntheticAttrChildNodes())
3021 detachAllAttrNodesFromElement();
3022
3023 other.synchronizeAllAttributes();
3024 if (!other.m_elementData) {
3025 m_elementData.clear();
3026 return;
3027 }
3028
3029 const AtomicString& oldID = getIdAttribute();
3030 const AtomicString& newID = other.getIdAttribute();
3031
3032 if (!oldID.isNull() || !newID.isNull())
3033 updateId(oldID, newID);
3034
3035 const AtomicString& oldName = getNameAttribute();
3036 const AtomicString& newName = other.getNameAttribute();
3037
3038 if (!oldName.isNull() || !newName.isNull())
3039 updateName(oldName, newName);
3040
Ben Murdoche69819b2013-07-17 14:56:49 +01003041 // Quirks mode makes class and id not case sensitive. We can't share the ElementData
3042 // if the idForStyleResolution and the className need different casing.
3043 bool ownerDocumentsHaveDifferentCaseSensitivity = false;
3044 if (other.hasClass() || other.hasID())
3045 ownerDocumentsHaveDifferentCaseSensitivity = other.document()->inQuirksMode() != document()->inQuirksMode();
3046
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01003047 // 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 +01003048 // We can only do this if there is no CSSOM wrapper for other's inline style, and there are no presentation attributes,
3049 // and sharing the data won't result in different case sensitivity of class or id.
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01003050 if (other.m_elementData->isUnique()
Ben Murdoche69819b2013-07-17 14:56:49 +01003051 && !ownerDocumentsHaveDifferentCaseSensitivity
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01003052 && !other.m_elementData->presentationAttributeStyle()
3053 && (!other.m_elementData->inlineStyle() || !other.m_elementData->inlineStyle()->hasCSSOMWrapper()))
3054 const_cast<Element&>(other).m_elementData = static_cast<const UniqueElementData*>(other.m_elementData.get())->makeShareableCopy();
3055
Ben Murdoche69819b2013-07-17 14:56:49 +01003056 if (!other.m_elementData->isUnique() && !ownerDocumentsHaveDifferentCaseSensitivity)
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01003057 m_elementData = other.m_elementData;
3058 else
3059 m_elementData = other.m_elementData->makeUniqueCopy();
3060
3061 for (unsigned i = 0; i < m_elementData->length(); ++i) {
3062 const Attribute* attribute = const_cast<const ElementData*>(m_elementData.get())->attributeItem(i);
3063 attributeChangedFromParserOrByCloning(attribute->name(), attribute->value(), ModifiedByCloning);
3064 }
3065}
3066
3067void Element::cloneDataFromElement(const Element& other)
3068{
3069 cloneAttributesFromElement(other);
3070 copyNonAttributePropertiesFromElement(other);
3071}
3072
3073void Element::createUniqueElementData()
3074{
3075 if (!m_elementData)
3076 m_elementData = UniqueElementData::create();
3077 else {
3078 ASSERT(!m_elementData->isUnique());
3079 m_elementData = static_cast<ShareableElementData*>(m_elementData.get())->makeUniqueCopy();
3080 }
3081}
3082
Ben Murdoch1fad5ca2013-08-07 11:05:11 +01003083InputMethodContext* Element::inputMethodContext()
Torne (Richard Coles)81a51572013-05-13 16:52:28 +01003084{
3085 return ensureElementRareData()->ensureInputMethodContext(toHTMLElement(this));
3086}
3087
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01003088bool Element::hasPendingResources() const
3089{
3090 return hasRareData() && elementRareData()->hasPendingResources();
3091}
3092
3093void Element::setHasPendingResources()
3094{
3095 ensureElementRareData()->setHasPendingResources(true);
3096}
3097
3098void Element::clearHasPendingResources()
3099{
3100 ensureElementRareData()->setHasPendingResources(false);
3101}
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01003102
Ben Murdoch591b9582013-07-10 11:41:44 +01003103struct PresentationAttributeCacheKey {
3104 PresentationAttributeCacheKey() : tagName(0) { }
Ben Murdoch83750172013-07-24 10:36:59 +01003105 StringImpl* tagName;
Ben Murdoch591b9582013-07-10 11:41:44 +01003106 // Only the values need refcounting.
Ben Murdoch83750172013-07-24 10:36:59 +01003107 Vector<pair<StringImpl*, AtomicString>, 3> attributesAndValues;
Ben Murdoch591b9582013-07-10 11:41:44 +01003108};
3109
3110struct PresentationAttributeCacheEntry {
3111 WTF_MAKE_FAST_ALLOCATED;
3112public:
3113 PresentationAttributeCacheKey key;
3114 RefPtr<StylePropertySet> value;
3115};
3116
3117typedef HashMap<unsigned, OwnPtr<PresentationAttributeCacheEntry>, AlreadyHashed> PresentationAttributeCache;
3118
3119static bool operator!=(const PresentationAttributeCacheKey& a, const PresentationAttributeCacheKey& b)
3120{
3121 if (a.tagName != b.tagName)
3122 return true;
3123 return a.attributesAndValues != b.attributesAndValues;
3124}
3125
3126static PresentationAttributeCache& presentationAttributeCache()
3127{
3128 DEFINE_STATIC_LOCAL(PresentationAttributeCache, cache, ());
3129 return cache;
3130}
3131
3132class PresentationAttributeCacheCleaner {
3133 WTF_MAKE_NONCOPYABLE(PresentationAttributeCacheCleaner); WTF_MAKE_FAST_ALLOCATED;
3134public:
3135 PresentationAttributeCacheCleaner()
3136 : m_hitCount(0)
3137 , m_cleanTimer(this, &PresentationAttributeCacheCleaner::cleanCache)
3138 {
3139 }
3140
3141 void didHitPresentationAttributeCache()
3142 {
3143 if (presentationAttributeCache().size() < minimumPresentationAttributeCacheSizeForCleaning)
3144 return;
3145
3146 m_hitCount++;
3147
3148 if (!m_cleanTimer.isActive())
3149 m_cleanTimer.startOneShot(presentationAttributeCacheCleanTimeInSeconds);
3150 }
3151
3152private:
3153 static const unsigned presentationAttributeCacheCleanTimeInSeconds = 60;
3154 static const int minimumPresentationAttributeCacheSizeForCleaning = 100;
3155 static const unsigned minimumPresentationAttributeCacheHitCountPerMinute = (100 * presentationAttributeCacheCleanTimeInSeconds) / 60;
3156
3157 void cleanCache(Timer<PresentationAttributeCacheCleaner>* timer)
3158 {
3159 ASSERT_UNUSED(timer, timer == &m_cleanTimer);
3160 unsigned hitCount = m_hitCount;
3161 m_hitCount = 0;
3162 if (hitCount > minimumPresentationAttributeCacheHitCountPerMinute)
3163 return;
3164 presentationAttributeCache().clear();
3165 }
3166
3167 unsigned m_hitCount;
3168 Timer<PresentationAttributeCacheCleaner> m_cleanTimer;
3169};
3170
3171static PresentationAttributeCacheCleaner& presentationAttributeCacheCleaner()
3172{
3173 DEFINE_STATIC_LOCAL(PresentationAttributeCacheCleaner, cleaner, ());
3174 return cleaner;
3175}
3176
3177void Element::synchronizeStyleAttributeInternal() const
3178{
3179 ASSERT(isStyledElement());
3180 ASSERT(elementData());
3181 ASSERT(elementData()->m_styleAttributeIsDirty);
3182 elementData()->m_styleAttributeIsDirty = false;
3183 if (const StylePropertySet* inlineStyle = this->inlineStyle())
3184 const_cast<Element*>(this)->setSynchronizedLazyAttribute(styleAttr, inlineStyle->asText());
3185}
3186
3187CSSStyleDeclaration* Element::style()
3188{
3189 if (!isStyledElement())
3190 return 0;
3191 return ensureMutableInlineStyle()->ensureInlineCSSStyleDeclaration(this);
3192}
3193
3194MutableStylePropertySet* Element::ensureMutableInlineStyle()
3195{
3196 ASSERT(isStyledElement());
3197 RefPtr<StylePropertySet>& inlineStyle = ensureUniqueElementData()->m_inlineStyle;
3198 if (!inlineStyle)
3199 inlineStyle = MutableStylePropertySet::create(strictToCSSParserMode(isHTMLElement() && !document()->inQuirksMode()));
3200 else if (!inlineStyle->isMutable())
3201 inlineStyle = inlineStyle->mutableCopy();
3202 ASSERT(inlineStyle->isMutable());
3203 return static_cast<MutableStylePropertySet*>(inlineStyle.get());
3204}
3205
3206PropertySetCSSStyleDeclaration* Element::inlineStyleCSSOMWrapper()
3207{
3208 if (!inlineStyle() || !inlineStyle()->hasCSSOMWrapper())
3209 return 0;
3210 PropertySetCSSStyleDeclaration* cssomWrapper = ensureMutableInlineStyle()->cssStyleDeclaration();
3211 ASSERT(cssomWrapper && cssomWrapper->parentElement() == this);
3212 return cssomWrapper;
3213}
3214
3215inline void Element::setInlineStyleFromString(const AtomicString& newStyleString)
3216{
3217 ASSERT(isStyledElement());
3218 RefPtr<StylePropertySet>& inlineStyle = elementData()->m_inlineStyle;
3219
3220 // Avoid redundant work if we're using shared attribute data with already parsed inline style.
3221 if (inlineStyle && !elementData()->isUnique())
3222 return;
3223
3224 // We reconstruct the property set instead of mutating if there is no CSSOM wrapper.
3225 // This makes wrapperless property sets immutable and so cacheable.
3226 if (inlineStyle && !inlineStyle->isMutable())
3227 inlineStyle.clear();
3228
3229 if (!inlineStyle) {
3230 inlineStyle = CSSParser::parseInlineStyleDeclaration(newStyleString, this);
3231 } else {
3232 ASSERT(inlineStyle->isMutable());
3233 static_pointer_cast<MutableStylePropertySet>(inlineStyle)->parseDeclaration(newStyleString, document()->elementSheet()->contents());
3234 }
3235}
3236
3237void Element::styleAttributeChanged(const AtomicString& newStyleString, AttributeModificationReason modificationReason)
3238{
3239 ASSERT(isStyledElement());
3240 WTF::OrdinalNumber startLineNumber = WTF::OrdinalNumber::beforeFirst();
3241 if (document() && document()->scriptableDocumentParser() && !document()->isInDocumentWrite())
3242 startLineNumber = document()->scriptableDocumentParser()->lineNumber();
3243
3244 if (newStyleString.isNull()) {
3245 if (PropertySetCSSStyleDeclaration* cssomWrapper = inlineStyleCSSOMWrapper())
3246 cssomWrapper->clearParentElement();
3247 ensureUniqueElementData()->m_inlineStyle.clear();
3248 } else if (modificationReason == ModifiedByCloning || document()->contentSecurityPolicy()->allowInlineStyle(document()->url(), startLineNumber)) {
3249 setInlineStyleFromString(newStyleString);
3250 }
3251
3252 elementData()->m_styleAttributeIsDirty = false;
3253
Ben Murdoche69819b2013-07-17 14:56:49 +01003254 setNeedsStyleRecalc(LocalStyleChange);
Ben Murdoch591b9582013-07-10 11:41:44 +01003255 InspectorInstrumentation::didInvalidateStyleAttr(document(), this);
3256}
3257
3258void Element::inlineStyleChanged()
3259{
3260 ASSERT(isStyledElement());
Ben Murdoche69819b2013-07-17 14:56:49 +01003261 setNeedsStyleRecalc(LocalStyleChange);
Ben Murdoch591b9582013-07-10 11:41:44 +01003262 ASSERT(elementData());
3263 elementData()->m_styleAttributeIsDirty = true;
3264 InspectorInstrumentation::didInvalidateStyleAttr(document(), this);
3265}
3266
3267bool Element::setInlineStyleProperty(CSSPropertyID propertyID, CSSValueID identifier, bool important)
3268{
3269 ASSERT(isStyledElement());
3270 ensureMutableInlineStyle()->setProperty(propertyID, cssValuePool().createIdentifierValue(identifier), important);
3271 inlineStyleChanged();
3272 return true;
3273}
3274
3275bool Element::setInlineStyleProperty(CSSPropertyID propertyID, CSSPropertyID identifier, bool important)
3276{
3277 ASSERT(isStyledElement());
3278 ensureMutableInlineStyle()->setProperty(propertyID, cssValuePool().createIdentifierValue(identifier), important);
3279 inlineStyleChanged();
3280 return true;
3281}
3282
3283bool Element::setInlineStyleProperty(CSSPropertyID propertyID, double value, CSSPrimitiveValue::UnitTypes unit, bool important)
3284{
3285 ASSERT(isStyledElement());
3286 ensureMutableInlineStyle()->setProperty(propertyID, cssValuePool().createValue(value, unit), important);
3287 inlineStyleChanged();
3288 return true;
3289}
3290
3291bool Element::setInlineStyleProperty(CSSPropertyID propertyID, const String& value, bool important)
3292{
3293 ASSERT(isStyledElement());
3294 bool changes = ensureMutableInlineStyle()->setProperty(propertyID, value, important, document()->elementSheet()->contents());
3295 if (changes)
3296 inlineStyleChanged();
3297 return changes;
3298}
3299
3300bool Element::removeInlineStyleProperty(CSSPropertyID propertyID)
3301{
3302 ASSERT(isStyledElement());
3303 if (!inlineStyle())
3304 return false;
3305 bool changes = ensureMutableInlineStyle()->removeProperty(propertyID);
3306 if (changes)
3307 inlineStyleChanged();
3308 return changes;
3309}
3310
3311void Element::removeAllInlineStyleProperties()
3312{
3313 ASSERT(isStyledElement());
3314 if (!inlineStyle() || inlineStyle()->isEmpty())
3315 return;
3316 ensureMutableInlineStyle()->clear();
3317 inlineStyleChanged();
3318}
3319
3320void Element::addSubresourceAttributeURLs(ListHashSet<KURL>& urls) const
3321{
3322 ASSERT(isStyledElement());
3323 if (const StylePropertySet* inlineStyle = elementData() ? elementData()->inlineStyle() : 0)
3324 inlineStyle->addSubresourceStyleURLs(urls, document()->elementSheet()->contents());
3325}
3326
Ben Murdoch83750172013-07-24 10:36:59 +01003327static inline bool attributeNameSort(const pair<StringImpl*, AtomicString>& p1, const pair<StringImpl*, AtomicString>& p2)
Ben Murdoch591b9582013-07-10 11:41:44 +01003328{
3329 // Sort based on the attribute name pointers. It doesn't matter what the order is as long as it is always the same.
3330 return p1.first < p2.first;
3331}
3332
3333void Element::makePresentationAttributeCacheKey(PresentationAttributeCacheKey& result) const
3334{
3335 ASSERT(isStyledElement());
3336 // FIXME: Enable for SVG.
3337 if (namespaceURI() != xhtmlNamespaceURI)
3338 return;
3339 // Interpretation of the size attributes on <input> depends on the type attribute.
3340 if (hasTagName(inputTag))
3341 return;
3342 unsigned size = attributeCount();
3343 for (unsigned i = 0; i < size; ++i) {
3344 const Attribute* attribute = attributeItem(i);
3345 if (!isPresentationAttribute(attribute->name()))
3346 continue;
3347 if (!attribute->namespaceURI().isNull())
3348 return;
3349 // FIXME: Background URL may depend on the base URL and can't be shared. Disallow caching.
3350 if (attribute->name() == backgroundAttr)
3351 return;
3352 result.attributesAndValues.append(std::make_pair(attribute->localName().impl(), attribute->value()));
3353 }
3354 if (result.attributesAndValues.isEmpty())
3355 return;
3356 // Attribute order doesn't matter. Sort for easy equality comparison.
3357 std::sort(result.attributesAndValues.begin(), result.attributesAndValues.end(), attributeNameSort);
3358 // The cache key is non-null when the tagName is set.
3359 result.tagName = localName().impl();
3360}
3361
3362static unsigned computePresentationAttributeCacheHash(const PresentationAttributeCacheKey& key)
3363{
3364 if (!key.tagName)
3365 return 0;
3366 ASSERT(key.attributesAndValues.size());
3367 unsigned attributeHash = StringHasher::hashMemory(key.attributesAndValues.data(), key.attributesAndValues.size() * sizeof(key.attributesAndValues[0]));
3368 return WTF::pairIntHash(key.tagName->existingHash(), attributeHash);
3369}
3370
3371void Element::rebuildPresentationAttributeStyle()
3372{
3373 ASSERT(isStyledElement());
3374 PresentationAttributeCacheKey cacheKey;
3375 makePresentationAttributeCacheKey(cacheKey);
3376
3377 unsigned cacheHash = computePresentationAttributeCacheHash(cacheKey);
3378
3379 PresentationAttributeCache::iterator cacheIterator;
3380 if (cacheHash) {
3381 cacheIterator = presentationAttributeCache().add(cacheHash, nullptr).iterator;
3382 if (cacheIterator->value && cacheIterator->value->key != cacheKey)
3383 cacheHash = 0;
3384 } else {
3385 cacheIterator = presentationAttributeCache().end();
3386 }
3387
3388 RefPtr<StylePropertySet> style;
3389 if (cacheHash && cacheIterator->value) {
3390 style = cacheIterator->value->value;
3391 presentationAttributeCacheCleaner().didHitPresentationAttributeCache();
3392 } else {
3393 style = MutableStylePropertySet::create(isSVGElement() ? SVGAttributeMode : CSSQuirksMode);
3394 unsigned size = attributeCount();
3395 for (unsigned i = 0; i < size; ++i) {
3396 const Attribute* attribute = attributeItem(i);
3397 collectStyleForPresentationAttribute(attribute->name(), attribute->value(), static_cast<MutableStylePropertySet*>(style.get()));
3398 }
3399 }
3400
3401 // ShareableElementData doesn't store presentation attribute style, so make sure we have a UniqueElementData.
3402 UniqueElementData* elementData = ensureUniqueElementData();
3403
3404 elementData->m_presentationAttributeStyleIsDirty = false;
3405 elementData->m_presentationAttributeStyle = style->isEmpty() ? 0 : style;
3406
3407 if (!cacheHash || cacheIterator->value)
3408 return;
3409
3410 OwnPtr<PresentationAttributeCacheEntry> newEntry = adoptPtr(new PresentationAttributeCacheEntry);
3411 newEntry->key = cacheKey;
3412 newEntry->value = style.release();
3413
3414 static const int presentationAttributeCacheMaximumSize = 4096;
3415 if (presentationAttributeCache().size() > presentationAttributeCacheMaximumSize) {
3416 // Start building from scratch if the cache ever gets big.
3417 presentationAttributeCache().clear();
3418 presentationAttributeCache().set(cacheHash, newEntry.release());
3419 } else {
3420 cacheIterator->value = newEntry.release();
3421 }
3422}
3423
3424void Element::addPropertyToPresentationAttributeStyle(MutableStylePropertySet* style, CSSPropertyID propertyID, CSSValueID identifier)
3425{
3426 ASSERT(isStyledElement());
3427 style->setProperty(propertyID, cssValuePool().createIdentifierValue(identifier));
3428}
3429
3430void Element::addPropertyToPresentationAttributeStyle(MutableStylePropertySet* style, CSSPropertyID propertyID, double value, CSSPrimitiveValue::UnitTypes unit)
3431{
3432 ASSERT(isStyledElement());
3433 style->setProperty(propertyID, cssValuePool().createValue(value, unit));
3434}
3435
3436void Element::addPropertyToPresentationAttributeStyle(MutableStylePropertySet* style, CSSPropertyID propertyID, const String& value)
3437{
3438 ASSERT(isStyledElement());
3439 style->setProperty(propertyID, value, false, document()->elementSheet()->contents());
3440}
3441
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01003442void ElementData::deref()
3443{
3444 if (!derefBase())
3445 return;
3446
3447 if (m_isUnique)
3448 delete static_cast<UniqueElementData*>(this);
3449 else
3450 delete static_cast<ShareableElementData*>(this);
3451}
3452
3453ElementData::ElementData()
3454 : m_isUnique(true)
3455 , m_arraySize(0)
3456 , m_presentationAttributeStyleIsDirty(false)
3457 , m_styleAttributeIsDirty(false)
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01003458 , m_animatedSVGAttributesAreDirty(false)
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01003459{
3460}
3461
3462ElementData::ElementData(unsigned arraySize)
3463 : m_isUnique(false)
3464 , m_arraySize(arraySize)
3465 , m_presentationAttributeStyleIsDirty(false)
3466 , m_styleAttributeIsDirty(false)
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01003467 , m_animatedSVGAttributesAreDirty(false)
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01003468{
3469}
3470
3471struct SameSizeAsElementData : public RefCounted<SameSizeAsElementData> {
3472 unsigned bitfield;
3473 void* refPtrs[3];
3474};
3475
3476COMPILE_ASSERT(sizeof(ElementData) == sizeof(SameSizeAsElementData), element_attribute_data_should_stay_small);
3477
3478static size_t sizeForShareableElementDataWithAttributeCount(unsigned count)
3479{
3480 return sizeof(ShareableElementData) + sizeof(Attribute) * count;
3481}
3482
3483PassRefPtr<ShareableElementData> ShareableElementData::createWithAttributes(const Vector<Attribute>& attributes)
3484{
3485 void* slot = WTF::fastMalloc(sizeForShareableElementDataWithAttributeCount(attributes.size()));
3486 return adoptRef(new (slot) ShareableElementData(attributes));
3487}
3488
3489PassRefPtr<UniqueElementData> UniqueElementData::create()
3490{
3491 return adoptRef(new UniqueElementData);
3492}
3493
3494ShareableElementData::ShareableElementData(const Vector<Attribute>& attributes)
3495 : ElementData(attributes.size())
3496{
3497 for (unsigned i = 0; i < m_arraySize; ++i)
3498 new (&m_attributeArray[i]) Attribute(attributes[i]);
3499}
3500
3501ShareableElementData::~ShareableElementData()
3502{
3503 for (unsigned i = 0; i < m_arraySize; ++i)
3504 m_attributeArray[i].~Attribute();
3505}
3506
3507ShareableElementData::ShareableElementData(const UniqueElementData& other)
3508 : ElementData(other, false)
3509{
3510 ASSERT(!other.m_presentationAttributeStyle);
3511
3512 if (other.m_inlineStyle) {
3513 ASSERT(!other.m_inlineStyle->hasCSSOMWrapper());
3514 m_inlineStyle = other.m_inlineStyle->immutableCopyIfNeeded();
3515 }
3516
3517 for (unsigned i = 0; i < m_arraySize; ++i)
3518 new (&m_attributeArray[i]) Attribute(other.m_attributeVector.at(i));
3519}
3520
3521ElementData::ElementData(const ElementData& other, bool isUnique)
3522 : m_isUnique(isUnique)
3523 , m_arraySize(isUnique ? 0 : other.length())
3524 , m_presentationAttributeStyleIsDirty(other.m_presentationAttributeStyleIsDirty)
3525 , m_styleAttributeIsDirty(other.m_styleAttributeIsDirty)
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01003526 , m_animatedSVGAttributesAreDirty(other.m_animatedSVGAttributesAreDirty)
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01003527 , m_classNames(other.m_classNames)
3528 , m_idForStyleResolution(other.m_idForStyleResolution)
3529{
3530 // NOTE: The inline style is copied by the subclass copy constructor since we don't know what to do with it here.
3531}
3532
3533UniqueElementData::UniqueElementData()
3534{
3535}
3536
3537UniqueElementData::UniqueElementData(const UniqueElementData& other)
3538 : ElementData(other, true)
3539 , m_presentationAttributeStyle(other.m_presentationAttributeStyle)
3540 , m_attributeVector(other.m_attributeVector)
3541{
Torne (Richard Coles)93ac45c2013-05-29 14:40:20 +01003542 m_inlineStyle = other.m_inlineStyle ? other.m_inlineStyle->mutableCopy() : 0;
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01003543}
3544
3545UniqueElementData::UniqueElementData(const ShareableElementData& other)
3546 : ElementData(other, true)
3547{
3548 // An ShareableElementData should never have a mutable inline StylePropertySet attached.
3549 ASSERT(!other.m_inlineStyle || !other.m_inlineStyle->isMutable());
3550 m_inlineStyle = other.m_inlineStyle;
3551
3552 m_attributeVector.reserveCapacity(other.length());
3553 for (unsigned i = 0; i < other.length(); ++i)
3554 m_attributeVector.uncheckedAppend(other.m_attributeArray[i]);
3555}
3556
3557PassRefPtr<UniqueElementData> ElementData::makeUniqueCopy() const
3558{
3559 if (isUnique())
3560 return adoptRef(new UniqueElementData(static_cast<const UniqueElementData&>(*this)));
3561 return adoptRef(new UniqueElementData(static_cast<const ShareableElementData&>(*this)));
3562}
3563
3564PassRefPtr<ShareableElementData> UniqueElementData::makeShareableCopy() const
3565{
3566 void* slot = WTF::fastMalloc(sizeForShareableElementDataWithAttributeCount(m_attributeVector.size()));
3567 return adoptRef(new (slot) ShareableElementData(*this));
3568}
3569
3570void UniqueElementData::addAttribute(const QualifiedName& attributeName, const AtomicString& value)
3571{
3572 m_attributeVector.append(Attribute(attributeName, value));
3573}
3574
3575void UniqueElementData::removeAttribute(size_t index)
3576{
3577 ASSERT_WITH_SECURITY_IMPLICATION(index < length());
3578 m_attributeVector.remove(index);
3579}
3580
3581bool ElementData::isEquivalent(const ElementData* other) const
3582{
3583 if (!other)
3584 return isEmpty();
3585
3586 unsigned len = length();
3587 if (len != other->length())
3588 return false;
3589
3590 for (unsigned i = 0; i < len; i++) {
3591 const Attribute* attribute = attributeItem(i);
3592 const Attribute* otherAttr = other->getAttributeItem(attribute->name());
3593 if (!otherAttr || attribute->value() != otherAttr->value())
3594 return false;
3595 }
3596
3597 return true;
3598}
3599
Torne (Richard Coles)e5249552013-05-15 11:35:13 +01003600size_t ElementData::getAttrIndex(Attr* attr) const
3601{
3602 // This relies on the fact that Attr's QualifiedName == the Attribute's name.
3603 for (unsigned i = 0; i < length(); ++i) {
3604 if (attributeItem(i)->name() == attr->qualifiedName())
3605 return i;
3606 }
3607 return notFound;
3608}
3609
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01003610size_t ElementData::getAttributeItemIndexSlowCase(const AtomicString& name, bool shouldIgnoreAttributeCase) const
3611{
3612 // Continue to checking case-insensitively and/or full namespaced names if necessary:
3613 for (unsigned i = 0; i < length(); ++i) {
3614 const Attribute* attribute = attributeItem(i);
3615 if (!attribute->name().hasPrefix()) {
3616 if (shouldIgnoreAttributeCase && equalIgnoringCase(name, attribute->localName()))
3617 return i;
3618 } else {
3619 // FIXME: Would be faster to do this comparison without calling toString, which
3620 // generates a temporary string by concatenation. But this branch is only reached
3621 // if the attribute name has a prefix, which is rare in HTML.
3622 if (equalPossiblyIgnoringCase(name, attribute->name().toString(), shouldIgnoreAttributeCase))
3623 return i;
3624 }
3625 }
3626 return notFound;
3627}
3628
3629Attribute* UniqueElementData::getAttributeItem(const QualifiedName& name)
3630{
3631 for (unsigned i = 0; i < length(); ++i) {
3632 if (m_attributeVector.at(i).name().matches(name))
3633 return &m_attributeVector.at(i);
3634 }
3635 return 0;
3636}
3637
3638Attribute* UniqueElementData::attributeItem(unsigned index)
3639{
3640 ASSERT_WITH_SECURITY_IMPLICATION(index < length());
3641 return &m_attributeVector.at(index);
3642}
3643
3644} // namespace WebCore