Upstream version 7.36.149.0
[platform/framework/web/crosswalk.git] / src / third_party / WebKit / Source / core / dom / Element.cpp
1 /*
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
29 #include "CSSValueKeywords.h"
30 #include "RuntimeEnabledFeatures.h"
31 #include "SVGNames.h"
32 #include "XMLNames.h"
33 #include "bindings/v8/Dictionary.h"
34 #include "bindings/v8/ExceptionMessages.h"
35 #include "bindings/v8/ExceptionState.h"
36 #include "core/accessibility/AXObjectCache.h"
37 #include "core/animation/DocumentTimeline.h"
38 #include "core/animation/css/CSSAnimations.h"
39 #include "core/css/CSSImageValue.h"
40 #include "core/css/CSSStyleSheet.h"
41 #include "core/css/CSSValuePool.h"
42 #include "core/css/PropertySetCSSStyleDeclaration.h"
43 #include "core/css/StylePropertySet.h"
44 #include "core/css/parser/BisonCSSParser.h"
45 #include "core/css/resolver/StyleResolver.h"
46 #include "core/css/resolver/StyleResolverParentScope.h"
47 #include "core/dom/Attr.h"
48 #include "core/dom/CSSSelectorWatch.h"
49 #include "core/dom/ClientRect.h"
50 #include "core/dom/ClientRectList.h"
51 #include "core/dom/DatasetDOMStringMap.h"
52 #include "core/dom/ElementDataCache.h"
53 #include "core/dom/ElementRareData.h"
54 #include "core/dom/ElementTraversal.h"
55 #include "core/dom/ExceptionCode.h"
56 #include "core/dom/FullscreenElementStack.h"
57 #include "core/dom/MutationObserverInterestGroup.h"
58 #include "core/dom/MutationRecord.h"
59 #include "core/dom/NamedNodeMap.h"
60 #include "core/dom/NodeRenderStyle.h"
61 #include "core/dom/PresentationAttributeStyle.h"
62 #include "core/dom/PseudoElement.h"
63 #include "core/dom/RenderTreeBuilder.h"
64 #include "core/dom/ScriptableDocumentParser.h"
65 #include "core/dom/SelectorQuery.h"
66 #include "core/dom/Text.h"
67 #include "core/dom/custom/CustomElement.h"
68 #include "core/dom/custom/CustomElementRegistrationContext.h"
69 #include "core/dom/shadow/InsertionPoint.h"
70 #include "core/dom/shadow/ShadowRoot.h"
71 #include "core/editing/FrameSelection.h"
72 #include "core/editing/TextIterator.h"
73 #include "core/editing/htmlediting.h"
74 #include "core/editing/markup.h"
75 #include "core/events/EventDispatcher.h"
76 #include "core/events/FocusEvent.h"
77 #include "core/frame/FrameView.h"
78 #include "core/frame/LocalFrame.h"
79 #include "core/frame/Settings.h"
80 #include "core/frame/UseCounter.h"
81 #include "core/frame/csp/ContentSecurityPolicy.h"
82 #include "core/html/ClassList.h"
83 #include "core/html/HTMLCollection.h"
84 #include "core/html/HTMLDocument.h"
85 #include "core/html/HTMLElement.h"
86 #include "core/html/HTMLFormControlsCollection.h"
87 #include "core/html/HTMLFrameElementBase.h"
88 #include "core/html/HTMLFrameOwnerElement.h"
89 #include "core/html/HTMLLabelElement.h"
90 #include "core/html/HTMLOptionsCollection.h"
91 #include "core/html/HTMLTableRowsCollection.h"
92 #include "core/html/HTMLTemplateElement.h"
93 #include "core/html/parser/HTMLParserIdioms.h"
94 #include "core/inspector/InspectorInstrumentation.h"
95 #include "core/page/FocusController.h"
96 #include "core/page/Page.h"
97 #include "core/page/PointerLockController.h"
98 #include "core/rendering/RenderLayer.h"
99 #include "core/rendering/RenderView.h"
100 #include "core/rendering/compositing/RenderLayerCompositor.h"
101 #include "core/svg/SVGDocumentExtensions.h"
102 #include "core/svg/SVGElement.h"
103 #include "platform/scroll/ScrollableArea.h"
104 #include "wtf/BitVector.h"
105 #include "wtf/HashFunctions.h"
106 #include "wtf/text/CString.h"
107 #include "wtf/text/StringBuilder.h"
108 #include "wtf/text/TextPosition.h"
109
110 namespace WebCore {
111
112 using namespace HTMLNames;
113 using namespace XMLNames;
114
115 typedef Vector<RefPtr<Attr> > AttrNodeList;
116 typedef HashMap<Element*, OwnPtr<AttrNodeList> > AttrNodeListMap;
117
118 static AttrNodeListMap& attrNodeListMap()
119 {
120     DEFINE_STATIC_LOCAL(AttrNodeListMap, map, ());
121     return map;
122 }
123
124 static AttrNodeList* attrNodeListForElement(Element* element)
125 {
126     if (!element->hasSyntheticAttrChildNodes())
127         return 0;
128     ASSERT(attrNodeListMap().contains(element));
129     return attrNodeListMap().get(element);
130 }
131
132 static AttrNodeList& ensureAttrNodeListForElement(Element* element)
133 {
134     if (element->hasSyntheticAttrChildNodes()) {
135         ASSERT(attrNodeListMap().contains(element));
136         return *attrNodeListMap().get(element);
137     }
138     ASSERT(!attrNodeListMap().contains(element));
139     element->setHasSyntheticAttrChildNodes(true);
140     AttrNodeListMap::AddResult result = attrNodeListMap().add(element, adoptPtr(new AttrNodeList));
141     return *result.storedValue->value;
142 }
143
144 static void removeAttrNodeListForElement(Element* element)
145 {
146     ASSERT(element->hasSyntheticAttrChildNodes());
147     ASSERT(attrNodeListMap().contains(element));
148     attrNodeListMap().remove(element);
149     element->setHasSyntheticAttrChildNodes(false);
150 }
151
152 static Attr* findAttrNodeInList(const AttrNodeList& attrNodeList, const QualifiedName& name)
153 {
154     AttrNodeList::const_iterator end = attrNodeList.end();
155     for (AttrNodeList::const_iterator it = attrNodeList.begin(); it != end; ++it) {
156         if ((*it)->qualifiedName() == name)
157             return it->get();
158     }
159     return 0;
160 }
161
162 PassRefPtr<Element> Element::create(const QualifiedName& tagName, Document* document)
163 {
164     return adoptRef(new Element(tagName, document, CreateElement));
165 }
166
167 Element::~Element()
168 {
169     ASSERT(needsAttach());
170
171 #if !ENABLE(OILPAN)
172     if (hasRareData())
173         elementRareData()->clearShadow();
174 #endif
175
176     if (isCustomElement())
177         CustomElement::wasDestroyed(this);
178
179     if (hasSyntheticAttrChildNodes())
180         detachAllAttrNodesFromElement();
181
182 #if !ENABLE(OILPAN)
183     // With Oilpan, either the Element has been removed from the Document
184     // or the Document is dead as well. If the Element has been removed from
185     // the Document the element has already been removed from the pending
186     // resources. If the document is also dead, there is no need to remove
187     // the element from the pending resources.
188     if (hasPendingResources()) {
189         document().accessSVGExtensions().removeElementFromPendingResources(this);
190         ASSERT(!hasPendingResources());
191     }
192 #endif
193 }
194
195 inline ElementRareData* Element::elementRareData() const
196 {
197     ASSERT(hasRareData());
198     return static_cast<ElementRareData*>(rareData());
199 }
200
201 inline ElementRareData& Element::ensureElementRareData()
202 {
203     return static_cast<ElementRareData&>(ensureRareData());
204 }
205
206 bool Element::hasElementFlagInternal(ElementFlags mask) const
207 {
208     return elementRareData()->hasElementFlag(mask);
209 }
210
211 void Element::setElementFlag(ElementFlags mask, bool value)
212 {
213     if (!hasRareData() && !value)
214         return;
215     ensureElementRareData().setElementFlag(mask, value);
216 }
217
218 void Element::clearElementFlag(ElementFlags mask)
219 {
220     if (!hasRareData())
221         return;
222     elementRareData()->clearElementFlag(mask);
223 }
224
225 void Element::clearTabIndexExplicitlyIfNeeded()
226 {
227     if (hasRareData())
228         elementRareData()->clearTabIndexExplicitly();
229 }
230
231 void Element::setTabIndexExplicitly(short tabIndex)
232 {
233     ensureElementRareData().setTabIndexExplicitly(tabIndex);
234 }
235
236 void Element::setTabIndex(int value)
237 {
238     setIntegralAttribute(tabindexAttr, value);
239 }
240
241 short Element::tabIndex() const
242 {
243     return hasRareData() ? elementRareData()->tabIndex() : 0;
244 }
245
246 bool Element::rendererIsFocusable() const
247 {
248     // Elements in canvas fallback content are not rendered, but they are allowed to be
249     // focusable as long as their canvas is displayed and visible.
250     if (isInCanvasSubtree()) {
251         const Element* e = this;
252         while (e && !e->hasLocalName(canvasTag))
253             e = e->parentElement();
254         ASSERT(e);
255         return e->renderer() && e->renderer()->style()->visibility() == VISIBLE;
256     }
257
258     // FIXME: These asserts should be in Node::isFocusable, but there are some
259     // callsites like Document::setFocusedElement that would currently fail on
260     // them. See crbug.com/251163
261     if (!renderer()) {
262         // We can't just use needsStyleRecalc() because if the node is in a
263         // display:none tree it might say it needs style recalc but the whole
264         // document is actually up to date.
265         ASSERT(!document().childNeedsStyleRecalc());
266     }
267
268     // FIXME: Even if we are not visible, we might have a child that is visible.
269     // Hyatt wants to fix that some day with a "has visible content" flag or the like.
270     if (!renderer() || renderer()->style()->visibility() != VISIBLE)
271         return false;
272
273     return true;
274 }
275
276 PassRefPtr<Node> Element::cloneNode(bool deep)
277 {
278     return deep ? cloneElementWithChildren() : cloneElementWithoutChildren();
279 }
280
281 PassRefPtr<Element> Element::cloneElementWithChildren()
282 {
283     RefPtr<Element> clone = cloneElementWithoutChildren();
284     cloneChildNodes(clone.get());
285     return clone.release();
286 }
287
288 PassRefPtr<Element> Element::cloneElementWithoutChildren()
289 {
290     RefPtr<Element> clone = cloneElementWithoutAttributesAndChildren();
291     // This will catch HTML elements in the wrong namespace that are not correctly copied.
292     // This is a sanity check as HTML overloads some of the DOM methods.
293     ASSERT(isHTMLElement() == clone->isHTMLElement());
294
295     clone->cloneDataFromElement(*this);
296     return clone.release();
297 }
298
299 PassRefPtr<Element> Element::cloneElementWithoutAttributesAndChildren()
300 {
301     return document().createElement(tagQName(), false);
302 }
303
304 PassRefPtr<Attr> Element::detachAttribute(size_t index)
305 {
306     ASSERT(elementData());
307     const Attribute& attribute = elementData()->attributeItem(index);
308     RefPtr<Attr> attrNode = attrIfExists(attribute.name());
309     if (attrNode)
310         detachAttrNodeAtIndex(attrNode.get(), index);
311     else {
312         attrNode = Attr::create(document(), attribute.name(), attribute.value());
313         removeAttributeInternal(index, NotInSynchronizationOfLazyAttribute);
314     }
315     return attrNode.release();
316 }
317
318 void Element::detachAttrNodeAtIndex(Attr* attr, size_t index)
319 {
320     ASSERT(attr);
321     ASSERT(elementData());
322
323     const Attribute& attribute = elementData()->attributeItem(index);
324     ASSERT(attribute.name() == attr->qualifiedName());
325     detachAttrNodeFromElementWithValue(attr, attribute.value());
326     removeAttributeInternal(index, NotInSynchronizationOfLazyAttribute);
327 }
328
329 void Element::removeAttribute(const QualifiedName& name)
330 {
331     if (!elementData())
332         return;
333
334     size_t index = elementData()->getAttributeItemIndex(name);
335     if (index == kNotFound)
336         return;
337
338     removeAttributeInternal(index, NotInSynchronizationOfLazyAttribute);
339 }
340
341 void Element::setBooleanAttribute(const QualifiedName& name, bool value)
342 {
343     if (value)
344         setAttribute(name, emptyAtom);
345     else
346         removeAttribute(name);
347 }
348
349 NamedNodeMap* Element::attributes() const
350 {
351     ElementRareData& rareData = const_cast<Element*>(this)->ensureElementRareData();
352     if (NamedNodeMap* attributeMap = rareData.attributeMap())
353         return attributeMap;
354
355     rareData.setAttributeMap(NamedNodeMap::create(const_cast<Element*>(this)));
356     return rareData.attributeMap();
357 }
358
359 ActiveAnimations* Element::activeAnimations() const
360 {
361     if (hasRareData())
362         return elementRareData()->activeAnimations();
363     return 0;
364 }
365
366 ActiveAnimations& Element::ensureActiveAnimations()
367 {
368     ElementRareData& rareData = ensureElementRareData();
369     if (!rareData.activeAnimations())
370         rareData.setActiveAnimations(adoptPtrWillBeNoop(new ActiveAnimations()));
371     return *rareData.activeAnimations();
372 }
373
374 bool Element::hasActiveAnimations() const
375 {
376     if (!hasRareData())
377         return false;
378
379     ActiveAnimations* activeAnimations = elementRareData()->activeAnimations();
380     return activeAnimations && !activeAnimations->isEmpty();
381 }
382
383 Node::NodeType Element::nodeType() const
384 {
385     return ELEMENT_NODE;
386 }
387
388 bool Element::hasAttribute(const QualifiedName& name) const
389 {
390     return hasAttributeNS(name.namespaceURI(), name.localName());
391 }
392
393 void Element::synchronizeAllAttributes() const
394 {
395     if (!elementData())
396         return;
397     // NOTE: anyAttributeMatches in SelectorChecker.cpp
398     // currently assumes that all lazy attributes have a null namespace.
399     // If that ever changes we'll need to fix that code.
400     if (elementData()->m_styleAttributeIsDirty) {
401         ASSERT(isStyledElement());
402         synchronizeStyleAttributeInternal();
403     }
404     if (elementData()->m_animatedSVGAttributesAreDirty) {
405         ASSERT(isSVGElement());
406         toSVGElement(this)->synchronizeAnimatedSVGAttribute(anyQName());
407     }
408 }
409
410 inline void Element::synchronizeAttribute(const QualifiedName& name) const
411 {
412     if (!elementData())
413         return;
414     if (UNLIKELY(name == styleAttr && elementData()->m_styleAttributeIsDirty)) {
415         ASSERT(isStyledElement());
416         synchronizeStyleAttributeInternal();
417         return;
418     }
419     if (UNLIKELY(elementData()->m_animatedSVGAttributesAreDirty)) {
420         ASSERT(isSVGElement());
421         // See comment in the AtomicString version of synchronizeAttribute()
422         // also.
423         toSVGElement(this)->synchronizeAnimatedSVGAttribute(name);
424     }
425 }
426
427 void Element::synchronizeAttribute(const AtomicString& localName) const
428 {
429     // This version of synchronizeAttribute() is streamlined for the case where you don't have a full QualifiedName,
430     // e.g when called from DOM API.
431     if (!elementData())
432         return;
433     if (elementData()->m_styleAttributeIsDirty && equalPossiblyIgnoringCase(localName, styleAttr.localName(), shouldIgnoreAttributeCase())) {
434         ASSERT(isStyledElement());
435         synchronizeStyleAttributeInternal();
436         return;
437     }
438     if (elementData()->m_animatedSVGAttributesAreDirty) {
439         // We're not passing a namespace argument on purpose. SVGNames::*Attr are defined w/o namespaces as well.
440
441         // FIXME: this code is called regardless of whether name is an
442         // animated SVG Attribute. It would seem we should only call this method
443         // if SVGElement::isAnimatableAttribute is true, but the list of
444         // animatable attributes in isAnimatableAttribute does not suffice to
445         // pass all layout tests. Also, m_animatedSVGAttributesAreDirty stays
446         // dirty unless synchronizeAnimatedSVGAttribute is called with
447         // anyQName(). This means that even if Element::synchronizeAttribute()
448         // is called on all attributes, m_animatedSVGAttributesAreDirty remains
449         // true.
450         toSVGElement(this)->synchronizeAnimatedSVGAttribute(QualifiedName(nullAtom, localName, nullAtom));
451     }
452 }
453
454 const AtomicString& Element::getAttribute(const QualifiedName& name) const
455 {
456     if (!elementData())
457         return nullAtom;
458     synchronizeAttribute(name);
459     if (const Attribute* attribute = getAttributeItem(name))
460         return attribute->value();
461     return nullAtom;
462 }
463
464 void Element::scrollIntoView(bool alignToTop)
465 {
466     document().updateLayoutIgnorePendingStylesheets();
467
468     if (!renderer())
469         return;
470
471     LayoutRect bounds = boundingBox();
472     // Align to the top / bottom and to the closest edge.
473     if (alignToTop)
474         renderer()->scrollRectToVisible(bounds, ScrollAlignment::alignToEdgeIfNeeded, ScrollAlignment::alignTopAlways);
475     else
476         renderer()->scrollRectToVisible(bounds, ScrollAlignment::alignToEdgeIfNeeded, ScrollAlignment::alignBottomAlways);
477 }
478
479 void Element::scrollIntoViewIfNeeded(bool centerIfNeeded)
480 {
481     document().updateLayoutIgnorePendingStylesheets();
482
483     if (!renderer())
484         return;
485
486     LayoutRect bounds = boundingBox();
487     if (centerIfNeeded)
488         renderer()->scrollRectToVisible(bounds, ScrollAlignment::alignCenterIfNeeded, ScrollAlignment::alignCenterIfNeeded);
489     else
490         renderer()->scrollRectToVisible(bounds, ScrollAlignment::alignToEdgeIfNeeded, ScrollAlignment::alignToEdgeIfNeeded);
491 }
492
493 void Element::scrollByUnits(int units, ScrollGranularity granularity)
494 {
495     document().updateLayoutIgnorePendingStylesheets();
496
497     if (!renderer())
498         return;
499
500     if (!renderer()->hasOverflowClip())
501         return;
502
503     ScrollDirection direction = ScrollDown;
504     if (units < 0) {
505         direction = ScrollUp;
506         units = -units;
507     }
508     toRenderBox(renderer())->scroll(direction, granularity, units);
509 }
510
511 void Element::scrollByLines(int lines)
512 {
513     scrollByUnits(lines, ScrollByLine);
514 }
515
516 void Element::scrollByPages(int pages)
517 {
518     scrollByUnits(pages, ScrollByPage);
519 }
520
521 static float localZoomForRenderer(RenderObject& renderer)
522 {
523     // FIXME: This does the wrong thing if two opposing zooms are in effect and canceled each
524     // other out, but the alternative is that we'd have to crawl up the whole render tree every
525     // time (or store an additional bit in the RenderStyle to indicate that a zoom was specified).
526     float zoomFactor = 1;
527     if (renderer.style()->effectiveZoom() != 1) {
528         // Need to find the nearest enclosing RenderObject that set up
529         // a differing zoom, and then we divide our result by it to eliminate the zoom.
530         RenderObject* prev = &renderer;
531         for (RenderObject* curr = prev->parent(); curr; curr = curr->parent()) {
532             if (curr->style()->effectiveZoom() != prev->style()->effectiveZoom()) {
533                 zoomFactor = prev->style()->zoom();
534                 break;
535             }
536             prev = curr;
537         }
538         if (prev->isRenderView())
539             zoomFactor = prev->style()->zoom();
540     }
541     return zoomFactor;
542 }
543
544 static double adjustForLocalZoom(LayoutUnit value, RenderObject& renderer)
545 {
546     float zoomFactor = localZoomForRenderer(renderer);
547     if (zoomFactor == 1)
548         return value.toDouble();
549     return value.toDouble() / zoomFactor;
550 }
551
552 double Element::offsetLeft()
553 {
554     document().updateLayoutIgnorePendingStylesheets();
555     if (RenderBoxModelObject* renderer = renderBoxModelObject())
556         return adjustForLocalZoom(renderer->offsetLeft(), *renderer);
557     return 0;
558 }
559
560 double Element::offsetTop()
561 {
562     document().updateLayoutIgnorePendingStylesheets();
563     if (RenderBoxModelObject* renderer = renderBoxModelObject())
564         return adjustForLocalZoom(renderer->offsetTop(), *renderer);
565     return 0;
566 }
567
568 double Element::offsetWidth()
569 {
570     document().updateLayoutIgnorePendingStylesheets();
571     if (RenderBoxModelObject* renderer = renderBoxModelObject())
572         return adjustLayoutUnitForAbsoluteZoom(renderer->offsetWidth(), *renderer).toFloat();
573     return 0;
574 }
575
576 double Element::offsetHeight()
577 {
578     document().updateLayoutIgnorePendingStylesheets();
579     if (RenderBoxModelObject* renderer = renderBoxModelObject())
580         return adjustLayoutUnitForAbsoluteZoom(renderer->offsetHeight(), *renderer).toFloat();
581     return 0;
582 }
583
584 Element* Element::offsetParentForBindings()
585 {
586     Element* element = offsetParent();
587     if (!element || !element->isInShadowTree())
588         return element;
589     return element->containingShadowRoot()->shouldExposeToBindings() ? element : 0;
590 }
591
592 Element* Element::offsetParent()
593 {
594     document().updateLayoutIgnorePendingStylesheets();
595     if (RenderObject* renderer = this->renderer())
596         return renderer->offsetParent();
597     return 0;
598 }
599
600 double Element::clientLeft()
601 {
602     document().updateLayoutIgnorePendingStylesheets();
603
604     if (RenderBox* renderer = renderBox())
605         return adjustForAbsoluteZoom(renderer->clientLeft(), renderer);
606     return 0;
607 }
608
609 double Element::clientTop()
610 {
611     document().updateLayoutIgnorePendingStylesheets();
612
613     if (RenderBox* renderer = renderBox())
614         return adjustForAbsoluteZoom(renderer->clientTop(), renderer);
615     return 0;
616 }
617
618 double Element::clientWidth()
619 {
620     document().updateLayoutIgnorePendingStylesheets();
621
622     // When in strict mode, clientWidth for the document element should return the width of the containing frame.
623     // When in quirks mode, clientWidth for the body element should return the width of the containing frame.
624     bool inQuirksMode = document().inQuirksMode();
625     if ((!inQuirksMode && document().documentElement() == this)
626         || (inQuirksMode && isHTMLElement() && document().body() == this)) {
627         if (FrameView* view = document().view()) {
628             if (RenderView* renderView = document().renderView())
629                 return adjustForAbsoluteZoom(view->layoutSize().width(), renderView);
630         }
631     }
632
633     if (RenderBox* renderer = renderBox())
634         return adjustLayoutUnitForAbsoluteZoom(renderer->clientWidth(), *renderer).toFloat();
635     return 0;
636 }
637
638 double Element::clientHeight()
639 {
640     document().updateLayoutIgnorePendingStylesheets();
641
642     // When in strict mode, clientHeight for the document element should return the height of the containing frame.
643     // When in quirks mode, clientHeight for the body element should return the height of the containing frame.
644     bool inQuirksMode = document().inQuirksMode();
645
646     if ((!inQuirksMode && document().documentElement() == this)
647         || (inQuirksMode && isHTMLElement() && document().body() == this)) {
648         if (FrameView* view = document().view()) {
649             if (RenderView* renderView = document().renderView())
650                 return adjustForAbsoluteZoom(view->layoutSize().height(), renderView);
651         }
652     }
653
654     if (RenderBox* renderer = renderBox())
655         return adjustLayoutUnitForAbsoluteZoom(renderer->clientHeight(), *renderer).toFloat();
656     return 0;
657 }
658
659 double Element::scrollLeft()
660 {
661     document().updateLayoutIgnorePendingStylesheets();
662
663     if (document().documentElement() != this) {
664         if (RenderBox* rend = renderBox())
665             return adjustForAbsoluteZoom(rend->scrollLeft(), rend);
666         return 0;
667     }
668
669     if (RuntimeEnabledFeatures::scrollTopLeftInteropEnabled()) {
670         if (document().inQuirksMode())
671             return 0;
672
673         if (FrameView* view = document().view()) {
674             if (RenderView* renderView = document().renderView())
675                 return adjustForAbsoluteZoom(view->scrollX(), renderView);
676         }
677     }
678
679     return 0;
680 }
681
682 double Element::scrollTop()
683 {
684     document().updateLayoutIgnorePendingStylesheets();
685
686     if (document().documentElement() != this) {
687         if (RenderBox* rend = renderBox())
688             return adjustForAbsoluteZoom(rend->scrollTop(), rend);
689         return 0;
690     }
691
692     if (RuntimeEnabledFeatures::scrollTopLeftInteropEnabled()) {
693         if (document().inQuirksMode())
694             return 0;
695
696         if (FrameView* view = document().view()) {
697             if (RenderView* renderView = document().renderView())
698                 return adjustForAbsoluteZoom(view->scrollY(), renderView);
699         }
700     }
701
702     return 0;
703 }
704
705 void Element::setScrollLeft(double newLeft)
706 {
707     document().updateLayoutIgnorePendingStylesheets();
708
709     if (document().documentElement() != this) {
710         if (RenderBox* rend = renderBox())
711             rend->setScrollLeft(roundf(newLeft * rend->style()->effectiveZoom()));
712         return;
713     }
714
715     if (RuntimeEnabledFeatures::scrollTopLeftInteropEnabled()) {
716         if (document().inQuirksMode())
717             return;
718
719         LocalFrame* frame = document().frame();
720         if (!frame)
721             return;
722         FrameView* view = frame->view();
723         if (!view)
724             return;
725
726         view->setScrollPosition(IntPoint(roundf(newLeft * frame->pageZoomFactor()), view->scrollY()));
727     }
728 }
729
730 void Element::setScrollLeft(const Dictionary& scrollOptionsHorizontal, ExceptionState& exceptionState)
731 {
732     String scrollBehaviorString;
733     ScrollBehavior scrollBehavior = ScrollBehaviorAuto;
734     if (scrollOptionsHorizontal.get("behavior", scrollBehaviorString)) {
735         if (!ScrollableArea::scrollBehaviorFromString(scrollBehaviorString, scrollBehavior)) {
736             exceptionState.throwTypeError("The ScrollBehavior provided is invalid.");
737             return;
738         }
739     }
740
741     int position;
742     if (!scrollOptionsHorizontal.get("x", position)) {
743         exceptionState.throwTypeError("ScrollOptionsHorizontal must include an 'x' member.");
744         return;
745     }
746
747     // FIXME: Use scrollBehavior to decide whether to scroll smoothly or instantly.
748     setScrollLeft(position);
749 }
750
751 void Element::setScrollTop(double newTop)
752 {
753     document().updateLayoutIgnorePendingStylesheets();
754
755     if (document().documentElement() != this) {
756         if (RenderBox* rend = renderBox())
757             rend->setScrollTop(roundf(newTop * rend->style()->effectiveZoom()));
758         return;
759     }
760
761     if (RuntimeEnabledFeatures::scrollTopLeftInteropEnabled()) {
762         if (document().inQuirksMode())
763             return;
764
765         LocalFrame* frame = document().frame();
766         if (!frame)
767             return;
768         FrameView* view = frame->view();
769         if (!view)
770             return;
771
772         view->setScrollPosition(IntPoint(view->scrollX(), roundf(newTop * frame->pageZoomFactor())));
773     }
774 }
775
776 void Element::setScrollTop(const Dictionary& scrollOptionsVertical, ExceptionState& exceptionState)
777 {
778     String scrollBehaviorString;
779     ScrollBehavior scrollBehavior = ScrollBehaviorAuto;
780     if (scrollOptionsVertical.get("behavior", scrollBehaviorString)) {
781         if (!ScrollableArea::scrollBehaviorFromString(scrollBehaviorString, scrollBehavior)) {
782             exceptionState.throwTypeError("The ScrollBehavior provided is invalid.");
783             return;
784         }
785     }
786
787     int position;
788     if (!scrollOptionsVertical.get("y", position)) {
789         exceptionState.throwTypeError("ScrollOptionsVertical must include a 'y' member.");
790         return;
791     }
792
793     // FIXME: Use scrollBehavior to decide whether to scroll smoothly or instantly.
794     setScrollTop(position);
795 }
796
797 double Element::scrollWidth()
798 {
799     document().updateLayoutIgnorePendingStylesheets();
800     if (RenderBox* rend = renderBox())
801         return adjustForAbsoluteZoom(rend->scrollWidth(), rend);
802     return 0;
803 }
804
805 double Element::scrollHeight()
806 {
807     document().updateLayoutIgnorePendingStylesheets();
808     if (RenderBox* rend = renderBox())
809         return adjustForAbsoluteZoom(rend->scrollHeight(), rend);
810     return 0;
811 }
812
813 IntRect Element::boundsInRootViewSpace()
814 {
815     document().updateLayoutIgnorePendingStylesheets();
816
817     FrameView* view = document().view();
818     if (!view)
819         return IntRect();
820
821     Vector<FloatQuad> quads;
822     if (isSVGElement() && renderer()) {
823         // Get the bounding rectangle from the SVG model.
824         SVGElement* svgElement = toSVGElement(this);
825         FloatRect localRect;
826         if (svgElement->getBoundingBox(localRect))
827             quads.append(renderer()->localToAbsoluteQuad(localRect));
828     } else {
829         // Get the bounding rectangle from the box model.
830         if (renderBoxModelObject())
831             renderBoxModelObject()->absoluteQuads(quads);
832     }
833
834     if (quads.isEmpty())
835         return IntRect();
836
837     IntRect result = quads[0].enclosingBoundingBox();
838     for (size_t i = 1; i < quads.size(); ++i)
839         result.unite(quads[i].enclosingBoundingBox());
840
841     result = view->contentsToRootView(result);
842     return result;
843 }
844
845 PassRefPtrWillBeRawPtr<ClientRectList> Element::getClientRects()
846 {
847     document().updateLayoutIgnorePendingStylesheets();
848
849     RenderBoxModelObject* renderBoxModelObject = this->renderBoxModelObject();
850     if (!renderBoxModelObject)
851         return ClientRectList::create();
852
853     // FIXME: Handle SVG elements.
854     // FIXME: Handle table/inline-table with a caption.
855
856     Vector<FloatQuad> quads;
857     renderBoxModelObject->absoluteQuads(quads);
858     document().adjustFloatQuadsForScrollAndAbsoluteZoom(quads, *renderBoxModelObject);
859     return ClientRectList::create(quads);
860 }
861
862 PassRefPtrWillBeRawPtr<ClientRect> Element::getBoundingClientRect()
863 {
864     document().updateLayoutIgnorePendingStylesheets();
865
866     Vector<FloatQuad> quads;
867     if (isSVGElement() && renderer() && !renderer()->isSVGRoot()) {
868         // Get the bounding rectangle from the SVG model.
869         SVGElement* svgElement = toSVGElement(this);
870         FloatRect localRect;
871         if (svgElement->getBoundingBox(localRect))
872             quads.append(renderer()->localToAbsoluteQuad(localRect));
873     } else {
874         // Get the bounding rectangle from the box model.
875         if (renderBoxModelObject())
876             renderBoxModelObject()->absoluteQuads(quads);
877     }
878
879     if (quads.isEmpty())
880         return ClientRect::create();
881
882     FloatRect result = quads[0].boundingBox();
883     for (size_t i = 1; i < quads.size(); ++i)
884         result.unite(quads[i].boundingBox());
885
886     ASSERT(renderer());
887     document().adjustFloatRectForScrollAndAbsoluteZoom(result, *renderer());
888     return ClientRect::create(result);
889 }
890
891 IntRect Element::screenRect() const
892 {
893     if (!renderer())
894         return IntRect();
895     // FIXME: this should probably respect transforms
896     return document().view()->contentsToScreen(renderer()->absoluteBoundingBoxRectIgnoringTransforms());
897 }
898
899 const AtomicString& Element::getAttribute(const AtomicString& localName) const
900 {
901     if (!elementData())
902         return nullAtom;
903     synchronizeAttribute(localName);
904     if (const Attribute* attribute = elementData()->getAttributeItem(localName, shouldIgnoreAttributeCase()))
905         return attribute->value();
906     return nullAtom;
907 }
908
909 const AtomicString& Element::getAttributeNS(const AtomicString& namespaceURI, const AtomicString& localName) const
910 {
911     return getAttribute(QualifiedName(nullAtom, localName, namespaceURI));
912 }
913
914 void Element::setAttribute(const AtomicString& localName, const AtomicString& value, ExceptionState& exceptionState)
915 {
916     if (!Document::isValidName(localName)) {
917         exceptionState.throwDOMException(InvalidCharacterError, "'" + localName + "' is not a valid attribute name.");
918         return;
919     }
920
921     synchronizeAttribute(localName);
922     const AtomicString& caseAdjustedLocalName = shouldIgnoreAttributeCase() ? localName.lower() : localName;
923
924     size_t index = elementData() ? elementData()->getAttributeItemIndex(caseAdjustedLocalName, false) : kNotFound;
925     const QualifiedName& qName = index != kNotFound ? attributeItem(index).name() : QualifiedName(nullAtom, caseAdjustedLocalName, nullAtom);
926     setAttributeInternal(index, qName, value, NotInSynchronizationOfLazyAttribute);
927 }
928
929 void Element::setAttribute(const QualifiedName& name, const AtomicString& value)
930 {
931     synchronizeAttribute(name);
932     size_t index = elementData() ? elementData()->getAttributeItemIndex(name) : kNotFound;
933     setAttributeInternal(index, name, value, NotInSynchronizationOfLazyAttribute);
934 }
935
936 void Element::setSynchronizedLazyAttribute(const QualifiedName& name, const AtomicString& value)
937 {
938     size_t index = elementData() ? elementData()->getAttributeItemIndex(name) : kNotFound;
939     setAttributeInternal(index, name, value, InSynchronizationOfLazyAttribute);
940 }
941
942 ALWAYS_INLINE void Element::setAttributeInternal(size_t index, const QualifiedName& name, const AtomicString& newValue, SynchronizationOfLazyAttribute inSynchronizationOfLazyAttribute)
943 {
944     if (newValue.isNull()) {
945         if (index != kNotFound)
946             removeAttributeInternal(index, inSynchronizationOfLazyAttribute);
947         return;
948     }
949
950     if (index == kNotFound) {
951         addAttributeInternal(name, newValue, inSynchronizationOfLazyAttribute);
952         return;
953     }
954
955     const Attribute& existingAttribute = attributeItem(index);
956     QualifiedName existingAttributeName = existingAttribute.name();
957
958     if (!inSynchronizationOfLazyAttribute)
959         willModifyAttribute(existingAttributeName, existingAttribute.value(), newValue);
960
961     if (newValue != existingAttribute.value()) {
962         // If there is an Attr node hooked to this attribute, the Attr::setValue() call below
963         // will write into the ElementData.
964         // FIXME: Refactor this so it makes some sense.
965         if (RefPtr<Attr> attrNode = inSynchronizationOfLazyAttribute ? nullptr : attrIfExists(existingAttributeName))
966             attrNode->setValue(newValue);
967         else
968             ensureUniqueElementData().attributeItem(index).setValue(newValue);
969     }
970
971     if (!inSynchronizationOfLazyAttribute)
972         didModifyAttribute(existingAttributeName, newValue);
973 }
974
975 static inline AtomicString makeIdForStyleResolution(const AtomicString& value, bool inQuirksMode)
976 {
977     if (inQuirksMode)
978         return value.lower();
979     return value;
980 }
981
982 void Element::attributeChanged(const QualifiedName& name, const AtomicString& newValue, AttributeModificationReason reason)
983 {
984     if (ElementShadow* parentElementShadow = shadowWhereNodeCanBeDistributed(*this)) {
985         if (shouldInvalidateDistributionWhenAttributeChanged(parentElementShadow, name, newValue))
986             parentElementShadow->setNeedsDistributionRecalc();
987     }
988
989     parseAttribute(name, newValue);
990
991     document().incDOMTreeVersion();
992
993     StyleResolver* styleResolver = document().styleResolver();
994     bool testShouldInvalidateStyle = inActiveDocument() && styleResolver && styleChangeType() < SubtreeStyleChange;
995
996     if (isStyledElement() && name == styleAttr) {
997         styleAttributeChanged(newValue, reason);
998     } else if (isStyledElement() && isPresentationAttribute(name)) {
999         elementData()->m_presentationAttributeStyleIsDirty = true;
1000         setNeedsStyleRecalc(LocalStyleChange);
1001     }
1002
1003     if (isIdAttributeName(name)) {
1004         AtomicString oldId = elementData()->idForStyleResolution();
1005         AtomicString newId = makeIdForStyleResolution(newValue, document().inQuirksMode());
1006         if (newId != oldId) {
1007             elementData()->setIdForStyleResolution(newId);
1008             if (testShouldInvalidateStyle)
1009                 styleResolver->ensureUpdatedRuleFeatureSet().scheduleStyleInvalidationForIdChange(oldId, newId, *this);
1010         }
1011     } else if (name == classAttr) {
1012         classAttributeChanged(newValue);
1013     } else if (name == HTMLNames::nameAttr) {
1014         setHasName(!newValue.isNull());
1015     }
1016
1017     invalidateNodeListCachesInAncestors(&name, this);
1018
1019     // If there is currently no StyleResolver, we can't be sure that this attribute change won't affect style.
1020     if (!styleResolver)
1021         setNeedsStyleRecalc(SubtreeStyleChange);
1022
1023     if (AXObjectCache* cache = document().existingAXObjectCache())
1024         cache->handleAttributeChanged(name, this);
1025 }
1026
1027 bool Element::hasLegalLinkAttribute(const QualifiedName&) const
1028 {
1029     return false;
1030 }
1031
1032 const QualifiedName& Element::subResourceAttributeName() const
1033 {
1034     return nullQName();
1035 }
1036
1037 inline void Element::attributeChangedFromParserOrByCloning(const QualifiedName& name, const AtomicString& newValue, AttributeModificationReason reason)
1038 {
1039     if (name == isAttr)
1040         CustomElementRegistrationContext::setTypeExtension(this, newValue);
1041     attributeChanged(name, newValue, reason);
1042 }
1043
1044 template <typename CharacterType>
1045 static inline bool classStringHasClassName(const CharacterType* characters, unsigned length)
1046 {
1047     ASSERT(length > 0);
1048
1049     unsigned i = 0;
1050     do {
1051         if (isNotHTMLSpace<CharacterType>(characters[i]))
1052             break;
1053         ++i;
1054     } while (i < length);
1055
1056     return i < length;
1057 }
1058
1059 static inline bool classStringHasClassName(const AtomicString& newClassString)
1060 {
1061     unsigned length = newClassString.length();
1062
1063     if (!length)
1064         return false;
1065
1066     if (newClassString.is8Bit())
1067         return classStringHasClassName(newClassString.characters8(), length);
1068     return classStringHasClassName(newClassString.characters16(), length);
1069 }
1070
1071 void Element::classAttributeChanged(const AtomicString& newClassString)
1072 {
1073     StyleResolver* styleResolver = document().styleResolver();
1074     bool testShouldInvalidateStyle = inActiveDocument() && styleResolver && styleChangeType() < SubtreeStyleChange;
1075
1076     ASSERT(elementData());
1077     if (classStringHasClassName(newClassString)) {
1078         const bool shouldFoldCase = document().inQuirksMode();
1079         const SpaceSplitString oldClasses = elementData()->classNames();
1080         elementData()->setClass(newClassString, shouldFoldCase);
1081         const SpaceSplitString& newClasses = elementData()->classNames();
1082         if (testShouldInvalidateStyle)
1083             styleResolver->ensureUpdatedRuleFeatureSet().scheduleStyleInvalidationForClassChange(oldClasses, newClasses, *this);
1084     } else {
1085         const SpaceSplitString& oldClasses = elementData()->classNames();
1086         if (testShouldInvalidateStyle)
1087             styleResolver->ensureUpdatedRuleFeatureSet().scheduleStyleInvalidationForClassChange(oldClasses, *this);
1088         elementData()->clearClass();
1089     }
1090
1091     if (hasRareData())
1092         elementRareData()->clearClassListValueForQuirksMode();
1093 }
1094
1095 bool Element::shouldInvalidateDistributionWhenAttributeChanged(ElementShadow* elementShadow, const QualifiedName& name, const AtomicString& newValue)
1096 {
1097     ASSERT(elementShadow);
1098     const SelectRuleFeatureSet& featureSet = elementShadow->ensureSelectFeatureSet();
1099
1100     if (isIdAttributeName(name)) {
1101         AtomicString oldId = elementData()->idForStyleResolution();
1102         AtomicString newId = makeIdForStyleResolution(newValue, document().inQuirksMode());
1103         if (newId != oldId) {
1104             if (!oldId.isEmpty() && featureSet.hasSelectorForId(oldId))
1105                 return true;
1106             if (!newId.isEmpty() && featureSet.hasSelectorForId(newId))
1107                 return true;
1108         }
1109     }
1110
1111     if (name == HTMLNames::classAttr) {
1112         const AtomicString& newClassString = newValue;
1113         if (classStringHasClassName(newClassString)) {
1114             const bool shouldFoldCase = document().inQuirksMode();
1115             const SpaceSplitString& oldClasses = elementData()->classNames();
1116             const SpaceSplitString newClasses(newClassString, shouldFoldCase);
1117             if (featureSet.checkSelectorsForClassChange(oldClasses, newClasses))
1118                 return true;
1119         } else {
1120             const SpaceSplitString& oldClasses = elementData()->classNames();
1121             if (featureSet.checkSelectorsForClassChange(oldClasses))
1122                 return true;
1123         }
1124     }
1125
1126     return featureSet.hasSelectorForAttribute(name.localName());
1127 }
1128
1129 // Returns true is the given attribute is an event handler.
1130 // We consider an event handler any attribute that begins with "on".
1131 // It is a simple solution that has the advantage of not requiring any
1132 // code or configuration change if a new event handler is defined.
1133
1134 static inline bool isEventHandlerAttribute(const Attribute& attribute)
1135 {
1136     return attribute.name().namespaceURI().isNull() && attribute.name().localName().startsWith("on");
1137 }
1138
1139 bool Element::isJavaScriptURLAttribute(const Attribute& attribute) const
1140 {
1141     return isURLAttribute(attribute) && protocolIsJavaScript(stripLeadingAndTrailingHTMLSpaces(attribute.value()));
1142 }
1143
1144 void Element::stripScriptingAttributes(Vector<Attribute>& attributeVector) const
1145 {
1146     size_t destination = 0;
1147     for (size_t source = 0; source < attributeVector.size(); ++source) {
1148         if (isEventHandlerAttribute(attributeVector[source])
1149             || isJavaScriptURLAttribute(attributeVector[source])
1150             || isHTMLContentAttribute(attributeVector[source]))
1151             continue;
1152
1153         if (source != destination)
1154             attributeVector[destination] = attributeVector[source];
1155
1156         ++destination;
1157     }
1158     attributeVector.shrink(destination);
1159 }
1160
1161 void Element::parserSetAttributes(const Vector<Attribute>& attributeVector)
1162 {
1163     ASSERT(!inDocument());
1164     ASSERT(!parentNode());
1165     ASSERT(!m_elementData);
1166
1167     if (attributeVector.isEmpty())
1168         return;
1169
1170     if (document().elementDataCache())
1171         m_elementData = document().elementDataCache()->cachedShareableElementDataWithAttributes(attributeVector);
1172     else
1173         m_elementData = ShareableElementData::createWithAttributes(attributeVector);
1174
1175     // Use attributeVector instead of m_elementData because attributeChanged might modify m_elementData.
1176     for (unsigned i = 0; i < attributeVector.size(); ++i)
1177         attributeChangedFromParserOrByCloning(attributeVector[i].name(), attributeVector[i].value(), ModifiedDirectly);
1178 }
1179
1180 bool Element::hasAttributes() const
1181 {
1182     synchronizeAllAttributes();
1183     return elementData() && elementData()->length();
1184 }
1185
1186 bool Element::hasEquivalentAttributes(const Element* other) const
1187 {
1188     synchronizeAllAttributes();
1189     other->synchronizeAllAttributes();
1190     if (elementData() == other->elementData())
1191         return true;
1192     if (elementData())
1193         return elementData()->isEquivalent(other->elementData());
1194     if (other->elementData())
1195         return other->elementData()->isEquivalent(elementData());
1196     return true;
1197 }
1198
1199 String Element::nodeName() const
1200 {
1201     return m_tagName.toString();
1202 }
1203
1204 void Element::setPrefix(const AtomicString& prefix, ExceptionState& exceptionState)
1205 {
1206     UseCounter::count(document(), UseCounter::ElementSetPrefix);
1207
1208     if (!prefix.isEmpty() && !Document::isValidName(prefix)) {
1209         exceptionState.throwDOMException(InvalidCharacterError, "The prefix '" + prefix + "' is not a valid name.");
1210         return;
1211     }
1212
1213     // FIXME: Raise NamespaceError if prefix is malformed per the Namespaces in XML specification.
1214
1215     const AtomicString& nodeNamespaceURI = namespaceURI();
1216     if (nodeNamespaceURI.isEmpty() && !prefix.isEmpty()) {
1217         exceptionState.throwDOMException(NamespaceError, "No namespace is set, so a namespace prefix may not be set.");
1218         return;
1219     }
1220
1221     if (prefix == xmlAtom && nodeNamespaceURI != XMLNames::xmlNamespaceURI) {
1222         exceptionState.throwDOMException(NamespaceError, "The prefix '" + xmlAtom + "' may not be set on namespace '" + nodeNamespaceURI + "'.");
1223         return;
1224     }
1225
1226     if (exceptionState.hadException())
1227         return;
1228
1229     m_tagName.setPrefix(prefix.isEmpty() ? AtomicString() : prefix);
1230 }
1231
1232 const AtomicString& Element::locateNamespacePrefix(const AtomicString& namespaceToLocate) const
1233 {
1234     if (!prefix().isNull() && namespaceURI() == namespaceToLocate)
1235         return prefix();
1236
1237     if (hasAttributes()) {
1238         unsigned attributeCount = this->attributeCount();
1239         for (unsigned i = 0; i < attributeCount; ++i) {
1240             const Attribute& attr = attributeItem(i);
1241
1242             if (attr.prefix() == xmlnsAtom && attr.value() == namespaceToLocate)
1243                 return attr.localName();
1244         }
1245     }
1246
1247     if (Element* parent = parentElement())
1248         return parent->locateNamespacePrefix(namespaceToLocate);
1249
1250     return nullAtom;
1251 }
1252
1253 KURL Element::baseURI() const
1254 {
1255     const AtomicString& baseAttribute = fastGetAttribute(baseAttr);
1256     KURL base(KURL(), baseAttribute);
1257     if (!base.protocol().isEmpty())
1258         return base;
1259
1260     ContainerNode* parent = parentNode();
1261     if (!parent)
1262         return base;
1263
1264     const KURL& parentBase = parent->baseURI();
1265     if (parentBase.isNull())
1266         return base;
1267
1268     return KURL(parentBase, baseAttribute);
1269 }
1270
1271 const AtomicString Element::imageSourceURL() const
1272 {
1273     return getAttribute(srcAttr);
1274 }
1275
1276 bool Element::rendererIsNeeded(const RenderStyle& style)
1277 {
1278     return style.display() != NONE;
1279 }
1280
1281 RenderObject* Element::createRenderer(RenderStyle* style)
1282 {
1283     return RenderObject::createObject(this, style);
1284 }
1285
1286 Node::InsertionNotificationRequest Element::insertedInto(ContainerNode* insertionPoint)
1287 {
1288     // need to do superclass processing first so inDocument() is true
1289     // by the time we reach updateId
1290     ContainerNode::insertedInto(insertionPoint);
1291
1292     if (containsFullScreenElement() && parentElement() && !parentElement()->containsFullScreenElement())
1293         setContainsFullScreenElementOnAncestorsCrossingFrameBoundaries(true);
1294
1295     ASSERT(!hasRareData() || !elementRareData()->hasPseudoElements());
1296
1297     if (!insertionPoint->isInTreeScope())
1298         return InsertionDone;
1299
1300     if (hasRareData())
1301         elementRareData()->clearClassListValueForQuirksMode();
1302
1303     if (isUpgradedCustomElement() && inDocument())
1304         CustomElement::didEnterDocument(this, document());
1305
1306     TreeScope& scope = insertionPoint->treeScope();
1307     if (scope != treeScope())
1308         return InsertionDone;
1309
1310     const AtomicString& idValue = getIdAttribute();
1311     if (!idValue.isNull())
1312         updateId(scope, nullAtom, idValue);
1313
1314     const AtomicString& nameValue = getNameAttribute();
1315     if (!nameValue.isNull())
1316         updateName(nullAtom, nameValue);
1317
1318     if (isHTMLLabelElement(*this)) {
1319         if (scope.shouldCacheLabelsByForAttribute())
1320             updateLabel(scope, nullAtom, fastGetAttribute(forAttr));
1321     }
1322
1323     if (parentElement() && parentElement()->isInCanvasSubtree())
1324         setIsInCanvasSubtree(true);
1325
1326     return InsertionDone;
1327 }
1328
1329 void Element::removedFrom(ContainerNode* insertionPoint)
1330 {
1331     bool wasInDocument = insertionPoint->inDocument();
1332
1333     ASSERT(!hasRareData() || !elementRareData()->hasPseudoElements());
1334
1335     if (containsFullScreenElement())
1336         setContainsFullScreenElementOnAncestorsCrossingFrameBoundaries(false);
1337
1338     if (document().page())
1339         document().page()->pointerLockController().elementRemoved(this);
1340
1341     setSavedLayerScrollOffset(IntSize());
1342
1343     if (insertionPoint->isInTreeScope() && treeScope() == document()) {
1344         const AtomicString& idValue = getIdAttribute();
1345         if (!idValue.isNull())
1346             updateId(insertionPoint->treeScope(), idValue, nullAtom);
1347
1348         const AtomicString& nameValue = getNameAttribute();
1349         if (!nameValue.isNull())
1350             updateName(nameValue, nullAtom);
1351
1352         if (isHTMLLabelElement(*this)) {
1353             TreeScope& treeScope = insertionPoint->treeScope();
1354             if (treeScope.shouldCacheLabelsByForAttribute())
1355                 updateLabel(treeScope, fastGetAttribute(forAttr), nullAtom);
1356         }
1357     }
1358
1359     ContainerNode::removedFrom(insertionPoint);
1360     if (wasInDocument) {
1361         if (hasPendingResources())
1362             document().accessSVGExtensions().removeElementFromPendingResources(this);
1363
1364         if (isUpgradedCustomElement())
1365             CustomElement::didLeaveDocument(this, insertionPoint->document());
1366     }
1367
1368     document().removeFromTopLayer(this);
1369
1370     clearElementFlag(IsInCanvasSubtree);
1371 }
1372
1373 void Element::attach(const AttachContext& context)
1374 {
1375     ASSERT(document().inStyleRecalc());
1376
1377     // We've already been through detach when doing an attach, but we might
1378     // need to clear any state that's been added since then.
1379     if (hasRareData() && styleChangeType() == NeedsReattachStyleChange) {
1380         ElementRareData* data = elementRareData();
1381         data->clearComputedStyle();
1382         data->clearRestyleFlags();
1383         // Only clear the style state if we're not going to reuse the style from recalcStyle.
1384         if (!context.resolvedStyle)
1385             data->resetStyleState();
1386     }
1387
1388     RenderTreeBuilder(this, context.resolvedStyle).createRendererForElementIfNeeded();
1389
1390     addCallbackSelectors();
1391
1392     StyleResolverParentScope parentScope(*this);
1393
1394     createPseudoElementIfNeeded(BEFORE);
1395
1396     // When a shadow root exists, it does the work of attaching the children.
1397     if (ElementShadow* shadow = this->shadow())
1398         shadow->attach(context);
1399
1400     ContainerNode::attach(context);
1401
1402     createPseudoElementIfNeeded(AFTER);
1403     createPseudoElementIfNeeded(BACKDROP);
1404
1405     if (hasRareData() && !renderer()) {
1406         if (ActiveAnimations* activeAnimations = elementRareData()->activeAnimations()) {
1407             activeAnimations->cssAnimations().cancel();
1408             activeAnimations->setAnimationStyleChange(false);
1409         }
1410     }
1411 }
1412
1413 void Element::detach(const AttachContext& context)
1414 {
1415     HTMLFrameOwnerElement::UpdateSuspendScope suspendWidgetHierarchyUpdates;
1416     cancelFocusAppearanceUpdate();
1417     removeCallbackSelectors();
1418     if (needsLayerUpdate())
1419         document().unscheduleLayerUpdate(*this);
1420     if (hasRareData()) {
1421         ElementRareData* data = elementRareData();
1422         data->clearPseudoElements();
1423
1424         // attach() will perform the below steps for us when inside recalcStyle.
1425         if (!document().inStyleRecalc()) {
1426             data->resetStyleState();
1427             data->clearComputedStyle();
1428             data->clearRestyleFlags();
1429         }
1430
1431         if (ActiveAnimations* activeAnimations = data->activeAnimations()) {
1432             if (context.performingReattach) {
1433                 // FIXME: We call detach from within style recalc, so compositingState is not up to date.
1434                 // https://code.google.com/p/chromium/issues/detail?id=339847
1435                 DisableCompositingQueryAsserts disabler;
1436
1437                 // FIXME: restart compositor animations rather than pull back to the main thread
1438                 activeAnimations->cancelAnimationOnCompositor();
1439             } else {
1440                 activeAnimations->cssAnimations().cancel();
1441                 activeAnimations->setAnimationStyleChange(false);
1442             }
1443         }
1444
1445         if (ElementShadow* shadow = data->shadow())
1446             shadow->detach(context);
1447     }
1448     ContainerNode::detach(context);
1449 }
1450
1451 bool Element::pseudoStyleCacheIsInvalid(const RenderStyle* currentStyle, RenderStyle* newStyle)
1452 {
1453     ASSERT(currentStyle == renderStyle());
1454     ASSERT(renderer());
1455
1456     if (!currentStyle)
1457         return false;
1458
1459     const PseudoStyleCache* pseudoStyleCache = currentStyle->cachedPseudoStyles();
1460     if (!pseudoStyleCache)
1461         return false;
1462
1463     size_t cacheSize = pseudoStyleCache->size();
1464     for (size_t i = 0; i < cacheSize; ++i) {
1465         RefPtr<RenderStyle> newPseudoStyle;
1466         PseudoId pseudoId = pseudoStyleCache->at(i)->styleType();
1467         if (pseudoId == FIRST_LINE || pseudoId == FIRST_LINE_INHERITED)
1468             newPseudoStyle = renderer()->uncachedFirstLineStyle(newStyle);
1469         else
1470             newPseudoStyle = renderer()->getUncachedPseudoStyle(PseudoStyleRequest(pseudoId), newStyle, newStyle);
1471         if (!newPseudoStyle)
1472             return true;
1473         if (*newPseudoStyle != *pseudoStyleCache->at(i)) {
1474             if (pseudoId < FIRST_INTERNAL_PSEUDOID)
1475                 newStyle->setHasPseudoStyle(pseudoId);
1476             newStyle->addCachedPseudoStyle(newPseudoStyle);
1477             if (pseudoId == FIRST_LINE || pseudoId == FIRST_LINE_INHERITED) {
1478                 // FIXME: We should do an actual diff to determine whether a repaint vs. layout
1479                 // is needed, but for now just assume a layout will be required. The diff code
1480                 // in RenderObject::setStyle would need to be factored out so that it could be reused.
1481                 renderer()->setNeedsLayoutAndPrefWidthsRecalc();
1482             }
1483             return true;
1484         }
1485     }
1486     return false;
1487 }
1488
1489 PassRefPtr<RenderStyle> Element::styleForRenderer()
1490 {
1491     ASSERT(document().inStyleRecalc());
1492
1493     RefPtr<RenderStyle> style;
1494
1495     // FIXME: Instead of clearing updates that may have been added from calls to styleForElement
1496     // outside recalcStyle, we should just never set them if we're not inside recalcStyle.
1497     if (ActiveAnimations* activeAnimations = this->activeAnimations())
1498         activeAnimations->cssAnimations().setPendingUpdate(nullptr);
1499
1500     if (hasCustomStyleCallbacks())
1501         style = customStyleForRenderer();
1502     if (!style)
1503         style = originalStyleForRenderer();
1504     ASSERT(style);
1505
1506     // styleForElement() might add active animations so we need to get it again.
1507     if (ActiveAnimations* activeAnimations = this->activeAnimations()) {
1508         activeAnimations->cssAnimations().maybeApplyPendingUpdate(this);
1509         activeAnimations->updateAnimationFlags(*style);
1510     }
1511
1512     document().didRecalculateStyleForElement();
1513     return style.release();
1514 }
1515
1516 PassRefPtr<RenderStyle> Element::originalStyleForRenderer()
1517 {
1518     ASSERT(document().inStyleRecalc());
1519     return document().ensureStyleResolver().styleForElement(this);
1520 }
1521
1522 void Element::recalcStyle(StyleRecalcChange change, Text* nextTextSibling)
1523 {
1524     ASSERT(document().inStyleRecalc());
1525     ASSERT(!parentOrShadowHostNode()->needsStyleRecalc());
1526
1527     if (hasCustomStyleCallbacks())
1528         willRecalcStyle(change);
1529
1530     if (change >= Inherit || needsStyleRecalc()) {
1531         if (hasRareData()) {
1532             ElementRareData* data = elementRareData();
1533             data->resetStyleState();
1534             data->clearComputedStyle();
1535
1536             if (change >= Inherit) {
1537                 if (ActiveAnimations* activeAnimations = data->activeAnimations())
1538                     activeAnimations->setAnimationStyleChange(false);
1539             }
1540         }
1541         if (parentRenderStyle())
1542             change = recalcOwnStyle(change);
1543         clearNeedsStyleRecalc();
1544     }
1545
1546     // If we reattached we don't need to recalc the style of our descendants anymore.
1547     if ((change >= UpdatePseudoElements && change < Reattach) || childNeedsStyleRecalc()) {
1548         recalcChildStyle(change);
1549         clearChildNeedsStyleRecalc();
1550     }
1551
1552     if (hasCustomStyleCallbacks())
1553         didRecalcStyle(change);
1554
1555     if (change == Reattach)
1556         reattachWhitespaceSiblings(nextTextSibling);
1557 }
1558
1559 StyleRecalcChange Element::recalcOwnStyle(StyleRecalcChange change)
1560 {
1561     ASSERT(document().inStyleRecalc());
1562     ASSERT(!parentOrShadowHostNode()->needsStyleRecalc());
1563     ASSERT(change >= Inherit || needsStyleRecalc());
1564     ASSERT(parentRenderStyle());
1565
1566     RefPtr<RenderStyle> oldStyle = renderStyle();
1567     RefPtr<RenderStyle> newStyle = styleForRenderer();
1568     StyleRecalcChange localChange = RenderStyle::stylePropagationDiff(oldStyle.get(), newStyle.get());
1569
1570     ASSERT(newStyle);
1571
1572     if (localChange == Reattach) {
1573         AttachContext reattachContext;
1574         reattachContext.resolvedStyle = newStyle.get();
1575         bool rendererWillChange = needsAttach() || renderer();
1576         reattach(reattachContext);
1577         if (rendererWillChange || renderer())
1578             return Reattach;
1579         return ReattachNoRenderer;
1580     }
1581
1582     ASSERT(oldStyle);
1583
1584     if (localChange != NoChange)
1585         updateCallbackSelectors(oldStyle.get(), newStyle.get());
1586
1587     if (RenderObject* renderer = this->renderer()) {
1588         if (localChange != NoChange || pseudoStyleCacheIsInvalid(oldStyle.get(), newStyle.get()) || needsLayerUpdate()) {
1589             renderer->setStyle(newStyle.get());
1590         } else {
1591             // Although no change occurred, we use the new style so that the cousin style sharing code won't get
1592             // fooled into believing this style is the same.
1593             // FIXME: We may be able to remove this hack, see discussion in
1594             // https://codereview.chromium.org/30453002/
1595             renderer->setStyleInternal(newStyle.get());
1596         }
1597     }
1598
1599     if (styleChangeType() >= SubtreeStyleChange)
1600         return Force;
1601
1602     if (change > Inherit || localChange > Inherit)
1603         return max(localChange, change);
1604
1605     if (localChange < Inherit && (oldStyle->hasPseudoElementStyle() || newStyle->hasPseudoElementStyle()))
1606         return UpdatePseudoElements;
1607
1608     return localChange;
1609 }
1610
1611 void Element::recalcChildStyle(StyleRecalcChange change)
1612 {
1613     ASSERT(document().inStyleRecalc());
1614     ASSERT(change >= UpdatePseudoElements || childNeedsStyleRecalc());
1615     ASSERT(!needsStyleRecalc());
1616
1617     StyleResolverParentScope parentScope(*this);
1618
1619     updatePseudoElement(BEFORE, change);
1620
1621     if (change > UpdatePseudoElements || childNeedsStyleRecalc()) {
1622         for (ShadowRoot* root = youngestShadowRoot(); root; root = root->olderShadowRoot()) {
1623             if (root->shouldCallRecalcStyle(change))
1624                 root->recalcStyle(change);
1625         }
1626     }
1627
1628     if (change < Force && hasRareData() && childNeedsStyleRecalc())
1629         checkForChildrenAdjacentRuleChanges();
1630
1631     if (change > UpdatePseudoElements || childNeedsStyleRecalc()) {
1632         // This loop is deliberately backwards because we use insertBefore in the rendering tree, and want to avoid
1633         // a potentially n^2 loop to find the insertion point while resolving style. Having us start from the last
1634         // child and work our way back means in the common case, we'll find the insertion point in O(1) time.
1635         // See crbug.com/288225
1636         StyleResolver& styleResolver = document().ensureStyleResolver();
1637         Text* lastTextNode = 0;
1638         for (Node* child = lastChild(); child; child = child->previousSibling()) {
1639             if (child->isTextNode()) {
1640                 toText(child)->recalcTextStyle(change, lastTextNode);
1641                 lastTextNode = toText(child);
1642             } else if (child->isElementNode()) {
1643                 Element* element = toElement(child);
1644                 if (element->shouldCallRecalcStyle(change))
1645                     element->recalcStyle(change, lastTextNode);
1646                 else if (element->supportsStyleSharing())
1647                     styleResolver.addToStyleSharingList(*element);
1648                 if (element->renderer())
1649                     lastTextNode = 0;
1650             }
1651         }
1652     }
1653
1654     updatePseudoElement(AFTER, change);
1655     updatePseudoElement(BACKDROP, change);
1656 }
1657
1658 void Element::updateCallbackSelectors(RenderStyle* oldStyle, RenderStyle* newStyle)
1659 {
1660     Vector<String> emptyVector;
1661     const Vector<String>& oldCallbackSelectors = oldStyle ? oldStyle->callbackSelectors() : emptyVector;
1662     const Vector<String>& newCallbackSelectors = newStyle ? newStyle->callbackSelectors() : emptyVector;
1663     if (oldCallbackSelectors.isEmpty() && newCallbackSelectors.isEmpty())
1664         return;
1665     if (oldCallbackSelectors != newCallbackSelectors)
1666         CSSSelectorWatch::from(document()).updateSelectorMatches(oldCallbackSelectors, newCallbackSelectors);
1667 }
1668
1669 void Element::addCallbackSelectors()
1670 {
1671     updateCallbackSelectors(0, renderStyle());
1672 }
1673
1674 void Element::removeCallbackSelectors()
1675 {
1676     updateCallbackSelectors(renderStyle(), 0);
1677 }
1678
1679 ElementShadow* Element::shadow() const
1680 {
1681     return hasRareData() ? elementRareData()->shadow() : 0;
1682 }
1683
1684 ElementShadow& Element::ensureShadow()
1685 {
1686     return ensureElementRareData().ensureShadow();
1687 }
1688
1689 void Element::didAffectSelector(AffectedSelectorMask mask)
1690 {
1691     setNeedsStyleRecalc(SubtreeStyleChange);
1692     if (ElementShadow* elementShadow = shadowWhereNodeCanBeDistributed(*this))
1693         elementShadow->didAffectSelector(mask);
1694 }
1695
1696 void Element::setAnimationStyleChange(bool animationStyleChange)
1697 {
1698     if (animationStyleChange && document().inStyleRecalc())
1699         return;
1700     if (ActiveAnimations* activeAnimations = elementRareData()->activeAnimations())
1701         activeAnimations->setAnimationStyleChange(animationStyleChange);
1702 }
1703
1704 void Element::setNeedsAnimationStyleRecalc()
1705 {
1706     if (styleChangeType() != NoStyleChange)
1707         return;
1708
1709     setNeedsStyleRecalc(LocalStyleChange);
1710     setAnimationStyleChange(true);
1711 }
1712
1713 void Element::setNeedsCompositingUpdate()
1714 {
1715     if (!document().isActive())
1716         return;
1717     RenderBoxModelObject* renderer = renderBoxModelObject();
1718     if (!renderer)
1719         return;
1720     if (!renderer->hasLayer())
1721         return;
1722     renderer->layer()->setNeedsToUpdateAncestorDependentProperties();
1723     document().renderView()->compositor()->setNeedsCompositingUpdate(CompositingUpdateAfterCompositingInputChange);
1724 }
1725
1726 void Element::setCustomElementDefinition(PassRefPtr<CustomElementDefinition> definition)
1727 {
1728     if (!hasRareData() && !definition)
1729         return;
1730     ASSERT(!customElementDefinition());
1731     ensureElementRareData().setCustomElementDefinition(definition);
1732 }
1733
1734 CustomElementDefinition* Element::customElementDefinition() const
1735 {
1736     if (hasRareData())
1737         return elementRareData()->customElementDefinition();
1738     return 0;
1739 }
1740
1741 PassRefPtr<ShadowRoot> Element::createShadowRoot(ExceptionState& exceptionState)
1742 {
1743     if (alwaysCreateUserAgentShadowRoot())
1744         ensureUserAgentShadowRoot();
1745
1746     // Some elements make assumptions about what kind of renderers they allow
1747     // as children so we can't allow author shadows on them for now. An override
1748     // flag is provided for testing how author shadows interact on these elements.
1749     if (!areAuthorShadowsAllowed() && !RuntimeEnabledFeatures::authorShadowDOMForAnyElementEnabled()) {
1750         exceptionState.throwDOMException(HierarchyRequestError, "Author-created shadow roots are disabled for this element.");
1751         return nullptr;
1752     }
1753
1754     return PassRefPtr<ShadowRoot>(ensureShadow().addShadowRoot(*this, ShadowRoot::AuthorShadowRoot));
1755 }
1756
1757 ShadowRoot* Element::shadowRoot() const
1758 {
1759     ElementShadow* elementShadow = shadow();
1760     if (!elementShadow)
1761         return 0;
1762     ShadowRoot* shadowRoot = elementShadow->youngestShadowRoot();
1763     if (shadowRoot->type() == ShadowRoot::AuthorShadowRoot)
1764         return shadowRoot;
1765     return 0;
1766 }
1767
1768 ShadowRoot* Element::userAgentShadowRoot() const
1769 {
1770     if (ElementShadow* elementShadow = shadow()) {
1771         if (ShadowRoot* shadowRoot = elementShadow->oldestShadowRoot()) {
1772             ASSERT(shadowRoot->type() == ShadowRoot::UserAgentShadowRoot);
1773             return shadowRoot;
1774         }
1775     }
1776
1777     return 0;
1778 }
1779
1780 ShadowRoot& Element::ensureUserAgentShadowRoot()
1781 {
1782     if (ShadowRoot* shadowRoot = userAgentShadowRoot())
1783         return *shadowRoot;
1784     ShadowRoot& shadowRoot = ensureShadow().addShadowRoot(*this, ShadowRoot::UserAgentShadowRoot);
1785     didAddUserAgentShadowRoot(shadowRoot);
1786     return shadowRoot;
1787 }
1788
1789 bool Element::childTypeAllowed(NodeType type) const
1790 {
1791     switch (type) {
1792     case ELEMENT_NODE:
1793     case TEXT_NODE:
1794     case COMMENT_NODE:
1795     case PROCESSING_INSTRUCTION_NODE:
1796     case CDATA_SECTION_NODE:
1797         return true;
1798     default:
1799         break;
1800     }
1801     return false;
1802 }
1803
1804 void Element::checkForEmptyStyleChange()
1805 {
1806     RenderStyle* style = renderStyle();
1807
1808     if (!style && !styleAffectedByEmpty())
1809         return;
1810
1811     if (!style || (styleAffectedByEmpty() && (!style->emptyState() || hasChildren())))
1812         setNeedsStyleRecalc(SubtreeStyleChange);
1813 }
1814
1815 void Element::childrenChanged(bool changedByParser, Node* beforeChange, Node* afterChange, int childCountDelta)
1816 {
1817     ContainerNode::childrenChanged(changedByParser, beforeChange, afterChange, childCountDelta);
1818
1819     checkForEmptyStyleChange();
1820     if (!changedByParser)
1821         checkForSiblingStyleChanges(false, beforeChange, afterChange, childCountDelta);
1822
1823     if (ElementShadow* shadow = this->shadow())
1824         shadow->setNeedsDistributionRecalc();
1825 }
1826
1827 void Element::finishParsingChildren()
1828 {
1829     setIsFinishedParsingChildren(true);
1830     checkForEmptyStyleChange();
1831     checkForSiblingStyleChanges(true, lastChild(), 0, 0);
1832 }
1833
1834 #ifndef NDEBUG
1835 void Element::formatForDebugger(char* buffer, unsigned length) const
1836 {
1837     StringBuilder result;
1838     String s;
1839
1840     result.append(nodeName());
1841
1842     s = getIdAttribute();
1843     if (s.length() > 0) {
1844         if (result.length() > 0)
1845             result.appendLiteral("; ");
1846         result.appendLiteral("id=");
1847         result.append(s);
1848     }
1849
1850     s = getAttribute(classAttr);
1851     if (s.length() > 0) {
1852         if (result.length() > 0)
1853             result.appendLiteral("; ");
1854         result.appendLiteral("class=");
1855         result.append(s);
1856     }
1857
1858     strncpy(buffer, result.toString().utf8().data(), length - 1);
1859 }
1860 #endif
1861
1862 const Vector<RefPtr<Attr> >& Element::attrNodeList()
1863 {
1864     ASSERT(hasSyntheticAttrChildNodes());
1865     return *attrNodeListForElement(this);
1866 }
1867
1868 PassRefPtr<Attr> Element::setAttributeNode(Attr* attrNode, ExceptionState& exceptionState)
1869 {
1870     if (!attrNode) {
1871         exceptionState.throwDOMException(TypeMismatchError, ExceptionMessages::argumentNullOrIncorrectType(1, "Attr"));
1872         return nullptr;
1873     }
1874
1875     RefPtr<Attr> oldAttrNode = attrIfExists(attrNode->qualifiedName());
1876     if (oldAttrNode.get() == attrNode)
1877         return attrNode; // This Attr is already attached to the element.
1878
1879     // InUseAttributeError: Raised if node is an Attr that is already an attribute of another Element object.
1880     // The DOM user must explicitly clone Attr nodes to re-use them in other elements.
1881     if (attrNode->ownerElement()) {
1882         exceptionState.throwDOMException(InUseAttributeError, "The node provided is an attribute node that is already an attribute of another Element; attribute nodes must be explicitly cloned.");
1883         return nullptr;
1884     }
1885
1886     synchronizeAllAttributes();
1887     UniqueElementData& elementData = ensureUniqueElementData();
1888
1889     size_t index = elementData.getAttributeItemIndex(attrNode->qualifiedName(), shouldIgnoreAttributeCase());
1890     if (index != kNotFound) {
1891         if (oldAttrNode)
1892             detachAttrNodeFromElementWithValue(oldAttrNode.get(), elementData.attributeItem(index).value());
1893         else
1894             oldAttrNode = Attr::create(document(), attrNode->qualifiedName(), elementData.attributeItem(index).value());
1895     }
1896
1897     setAttributeInternal(index, attrNode->qualifiedName(), attrNode->value(), NotInSynchronizationOfLazyAttribute);
1898
1899     attrNode->attachToElement(this);
1900     treeScope().adoptIfNeeded(*attrNode);
1901     ensureAttrNodeListForElement(this).append(attrNode);
1902
1903     return oldAttrNode.release();
1904 }
1905
1906 PassRefPtr<Attr> Element::setAttributeNodeNS(Attr* attr, ExceptionState& exceptionState)
1907 {
1908     return setAttributeNode(attr, exceptionState);
1909 }
1910
1911 PassRefPtr<Attr> Element::removeAttributeNode(Attr* attr, ExceptionState& exceptionState)
1912 {
1913     if (!attr) {
1914         exceptionState.throwDOMException(TypeMismatchError, ExceptionMessages::argumentNullOrIncorrectType(1, "Attr"));
1915         return nullptr;
1916     }
1917     if (attr->ownerElement() != this) {
1918         exceptionState.throwDOMException(NotFoundError, "The node provided is owned by another element.");
1919         return nullptr;
1920     }
1921
1922     ASSERT(document() == attr->document());
1923
1924     synchronizeAttribute(attr->qualifiedName());
1925
1926     size_t index = elementData()->getAttrIndex(attr);
1927     if (index == kNotFound) {
1928         exceptionState.throwDOMException(NotFoundError, "The attribute was not found on this element.");
1929         return nullptr;
1930     }
1931
1932     RefPtr<Attr> guard(attr);
1933     detachAttrNodeAtIndex(attr, index);
1934     return guard.release();
1935 }
1936
1937 void Element::parseAttribute(const QualifiedName& name, const AtomicString& value)
1938 {
1939     if (name == tabindexAttr) {
1940         int tabindex = 0;
1941         if (value.isEmpty()) {
1942             clearTabIndexExplicitlyIfNeeded();
1943             if (treeScope().adjustedFocusedElement() == this) {
1944                 // We might want to call blur(), but it's dangerous to dispatch
1945                 // events here.
1946                 document().setNeedsFocusedElementCheck();
1947             }
1948         } else if (parseHTMLInteger(value, tabindex)) {
1949             // Clamp tabindex to the range of 'short' to match Firefox's behavior.
1950             setTabIndexExplicitly(max(static_cast<int>(std::numeric_limits<short>::min()), std::min(tabindex, static_cast<int>(std::numeric_limits<short>::max()))));
1951         }
1952     }
1953 }
1954
1955 bool Element::parseAttributeName(QualifiedName& out, const AtomicString& namespaceURI, const AtomicString& qualifiedName, ExceptionState& exceptionState)
1956 {
1957     AtomicString prefix, localName;
1958     if (!Document::parseQualifiedName(qualifiedName, prefix, localName, exceptionState))
1959         return false;
1960     ASSERT(!exceptionState.hadException());
1961
1962     QualifiedName qName(prefix, localName, namespaceURI);
1963
1964     if (!Document::hasValidNamespaceForAttributes(qName)) {
1965         exceptionState.throwDOMException(NamespaceError, "'" + namespaceURI + "' is an invalid namespace for attributes.");
1966         return false;
1967     }
1968
1969     out = qName;
1970     return true;
1971 }
1972
1973 void Element::setAttributeNS(const AtomicString& namespaceURI, const AtomicString& qualifiedName, const AtomicString& value, ExceptionState& exceptionState)
1974 {
1975     QualifiedName parsedName = anyName;
1976     if (!parseAttributeName(parsedName, namespaceURI, qualifiedName, exceptionState))
1977         return;
1978     setAttribute(parsedName, value);
1979 }
1980
1981 void Element::removeAttributeInternal(size_t index, SynchronizationOfLazyAttribute inSynchronizationOfLazyAttribute)
1982 {
1983     ASSERT_WITH_SECURITY_IMPLICATION(index < attributeCount());
1984
1985     UniqueElementData& elementData = ensureUniqueElementData();
1986
1987     QualifiedName name = elementData.attributeItem(index).name();
1988     AtomicString valueBeingRemoved = elementData.attributeItem(index).value();
1989
1990     if (!inSynchronizationOfLazyAttribute) {
1991         if (!valueBeingRemoved.isNull())
1992             willModifyAttribute(name, valueBeingRemoved, nullAtom);
1993     }
1994
1995     if (RefPtr<Attr> attrNode = attrIfExists(name))
1996         detachAttrNodeFromElementWithValue(attrNode.get(), elementData.attributeItem(index).value());
1997
1998     elementData.removeAttribute(index);
1999
2000     if (!inSynchronizationOfLazyAttribute)
2001         didRemoveAttribute(name);
2002 }
2003
2004 void Element::addAttributeInternal(const QualifiedName& name, const AtomicString& value, SynchronizationOfLazyAttribute inSynchronizationOfLazyAttribute)
2005 {
2006     if (!inSynchronizationOfLazyAttribute)
2007         willModifyAttribute(name, nullAtom, value);
2008     ensureUniqueElementData().addAttribute(name, value);
2009     if (!inSynchronizationOfLazyAttribute)
2010         didAddAttribute(name, value);
2011 }
2012
2013 void Element::removeAttribute(const AtomicString& name)
2014 {
2015     if (!elementData())
2016         return;
2017
2018     AtomicString localName = shouldIgnoreAttributeCase() ? name.lower() : name;
2019     size_t index = elementData()->getAttributeItemIndex(localName, false);
2020     if (index == kNotFound) {
2021         if (UNLIKELY(localName == styleAttr) && elementData()->m_styleAttributeIsDirty && isStyledElement())
2022             removeAllInlineStyleProperties();
2023         return;
2024     }
2025
2026     removeAttributeInternal(index, NotInSynchronizationOfLazyAttribute);
2027 }
2028
2029 void Element::removeAttributeNS(const AtomicString& namespaceURI, const AtomicString& localName)
2030 {
2031     removeAttribute(QualifiedName(nullAtom, localName, namespaceURI));
2032 }
2033
2034 PassRefPtr<Attr> Element::getAttributeNode(const AtomicString& localName)
2035 {
2036     if (!elementData())
2037         return nullptr;
2038     synchronizeAttribute(localName);
2039     const Attribute* attribute = elementData()->getAttributeItem(localName, shouldIgnoreAttributeCase());
2040     if (!attribute)
2041         return nullptr;
2042     return ensureAttr(attribute->name());
2043 }
2044
2045 PassRefPtr<Attr> Element::getAttributeNodeNS(const AtomicString& namespaceURI, const AtomicString& localName)
2046 {
2047     if (!elementData())
2048         return nullptr;
2049     QualifiedName qName(nullAtom, localName, namespaceURI);
2050     synchronizeAttribute(qName);
2051     const Attribute* attribute = elementData()->getAttributeItem(qName);
2052     if (!attribute)
2053         return nullptr;
2054     return ensureAttr(attribute->name());
2055 }
2056
2057 bool Element::hasAttribute(const AtomicString& localName) const
2058 {
2059     if (!elementData())
2060         return false;
2061     synchronizeAttribute(localName);
2062     return elementData()->getAttributeItem(shouldIgnoreAttributeCase() ? localName.lower() : localName, false);
2063 }
2064
2065 bool Element::hasAttributeNS(const AtomicString& namespaceURI, const AtomicString& localName) const
2066 {
2067     if (!elementData())
2068         return false;
2069     QualifiedName qName(nullAtom, localName, namespaceURI);
2070     synchronizeAttribute(qName);
2071     return elementData()->getAttributeItem(qName);
2072 }
2073
2074 void Element::focus(bool restorePreviousSelection, FocusType type)
2075 {
2076     if (!inDocument())
2077         return;
2078
2079     if (document().focusedElement() == this)
2080         return;
2081
2082     if (!document().isActive())
2083         return;
2084
2085     document().updateLayoutIgnorePendingStylesheets();
2086     if (!isFocusable())
2087         return;
2088
2089     RefPtr<Node> protect(this);
2090     if (!document().page()->focusController().setFocusedElement(this, document().frame(), type))
2091         return;
2092
2093     // Setting the focused node above might have invalidated the layout due to scripts.
2094     document().updateLayoutIgnorePendingStylesheets();
2095     if (!isFocusable())
2096         return;
2097
2098     cancelFocusAppearanceUpdate();
2099     updateFocusAppearance(restorePreviousSelection);
2100 }
2101
2102 void Element::updateFocusAppearance(bool /*restorePreviousSelection*/)
2103 {
2104     if (isRootEditableElement()) {
2105         // Taking the ownership since setSelection() may release the last reference to |frame|.
2106         RefPtr<LocalFrame> frame(document().frame());
2107         if (!frame)
2108             return;
2109
2110         // When focusing an editable element in an iframe, don't reset the selection if it already contains a selection.
2111         if (this == frame->selection().rootEditableElement())
2112             return;
2113
2114         // FIXME: We should restore the previous selection if there is one.
2115         VisibleSelection newSelection = VisibleSelection(firstPositionInOrBeforeNode(this), DOWNSTREAM);
2116         frame->selection().setSelection(newSelection);
2117         frame->selection().revealSelection();
2118     } else if (renderer() && !renderer()->isWidget())
2119         renderer()->scrollRectToVisible(boundingBox());
2120 }
2121
2122 void Element::blur()
2123 {
2124     cancelFocusAppearanceUpdate();
2125     if (treeScope().adjustedFocusedElement() == this) {
2126         Document& doc = document();
2127         if (doc.page())
2128             doc.page()->focusController().setFocusedElement(0, doc.frame());
2129         else
2130             doc.setFocusedElement(nullptr);
2131     }
2132 }
2133
2134 bool Element::supportsFocus() const
2135 {
2136     // FIXME: supportsFocus() can be called when layout is not up to date.
2137     // Logic that deals with the renderer should be moved to rendererIsFocusable().
2138     // But supportsFocus must return true when the element is editable, or else
2139     // it won't be focusable. Furthermore, supportsFocus cannot just return true
2140     // always or else tabIndex() will change for all HTML elements.
2141     return hasElementFlag(TabIndexWasSetExplicitly) || (rendererIsEditable() && parentNode() && !parentNode()->rendererIsEditable())
2142         || supportsSpatialNavigationFocus();
2143 }
2144
2145 bool Element::supportsSpatialNavigationFocus() const
2146 {
2147     // This function checks whether the element satisfies the extended criteria
2148     // for the element to be focusable, introduced by spatial navigation feature,
2149     // i.e. checks if click or keyboard event handler is specified.
2150     // This is the way to make it possible to navigate to (focus) elements
2151     // which web designer meant for being active (made them respond to click events).
2152
2153     if (!document().settings() || !document().settings()->spatialNavigationEnabled())
2154         return false;
2155     return hasEventListeners(EventTypeNames::click)
2156         || hasEventListeners(EventTypeNames::keydown)
2157         || hasEventListeners(EventTypeNames::keypress)
2158         || hasEventListeners(EventTypeNames::keyup);
2159 }
2160
2161 bool Element::isFocusable() const
2162 {
2163     return inDocument() && supportsFocus() && !isInert() && rendererIsFocusable();
2164 }
2165
2166 bool Element::isKeyboardFocusable() const
2167 {
2168     return isFocusable() && tabIndex() >= 0;
2169 }
2170
2171 bool Element::isMouseFocusable() const
2172 {
2173     return isFocusable();
2174 }
2175
2176 void Element::dispatchFocusEvent(Element* oldFocusedElement, FocusType)
2177 {
2178     RefPtrWillBeRawPtr<FocusEvent> event = FocusEvent::create(EventTypeNames::focus, false, false, document().domWindow(), 0, oldFocusedElement);
2179     EventDispatcher::dispatchEvent(this, FocusEventDispatchMediator::create(event.release()));
2180 }
2181
2182 void Element::dispatchBlurEvent(Element* newFocusedElement)
2183 {
2184     RefPtrWillBeRawPtr<FocusEvent> event = FocusEvent::create(EventTypeNames::blur, false, false, document().domWindow(), 0, newFocusedElement);
2185     EventDispatcher::dispatchEvent(this, BlurEventDispatchMediator::create(event.release()));
2186 }
2187
2188 void Element::dispatchFocusInEvent(const AtomicString& eventType, Element* oldFocusedElement)
2189 {
2190     ASSERT(!NoEventDispatchAssertion::isEventDispatchForbidden());
2191     ASSERT(eventType == EventTypeNames::focusin || eventType == EventTypeNames::DOMFocusIn);
2192     dispatchScopedEventDispatchMediator(FocusInEventDispatchMediator::create(FocusEvent::create(eventType, true, false, document().domWindow(), 0, oldFocusedElement)));
2193 }
2194
2195 void Element::dispatchFocusOutEvent(const AtomicString& eventType, Element* newFocusedElement)
2196 {
2197     ASSERT(!NoEventDispatchAssertion::isEventDispatchForbidden());
2198     ASSERT(eventType == EventTypeNames::focusout || eventType == EventTypeNames::DOMFocusOut);
2199     dispatchScopedEventDispatchMediator(FocusOutEventDispatchMediator::create(FocusEvent::create(eventType, true, false, document().domWindow(), 0, newFocusedElement)));
2200 }
2201
2202 String Element::innerHTML() const
2203 {
2204     return createMarkup(this, ChildrenOnly);
2205 }
2206
2207 String Element::outerHTML() const
2208 {
2209     return createMarkup(this);
2210 }
2211
2212 void Element::setInnerHTML(const String& html, ExceptionState& exceptionState)
2213 {
2214     if (RefPtr<DocumentFragment> fragment = createFragmentForInnerOuterHTML(html, this, AllowScriptingContent, "innerHTML", exceptionState)) {
2215         ContainerNode* container = this;
2216         if (isHTMLTemplateElement(*this))
2217             container = toHTMLTemplateElement(this)->content();
2218         replaceChildrenWithFragment(container, fragment.release(), exceptionState);
2219     }
2220 }
2221
2222 void Element::setOuterHTML(const String& html, ExceptionState& exceptionState)
2223 {
2224     Node* p = parentNode();
2225     if (!p) {
2226         exceptionState.throwDOMException(NoModificationAllowedError, "This element has no parent node.");
2227         return;
2228     }
2229     if (!p->isElementNode()) {
2230         exceptionState.throwDOMException(NoModificationAllowedError, "This element's parent is of type '" + p->nodeName() + "', which is not an element node.");
2231         return;
2232     }
2233
2234     RefPtr<Element> parent = toElement(p);
2235     RefPtr<Node> prev = previousSibling();
2236     RefPtr<Node> next = nextSibling();
2237
2238     RefPtr<DocumentFragment> fragment = createFragmentForInnerOuterHTML(html, parent.get(), AllowScriptingContent, "outerHTML", exceptionState);
2239     if (exceptionState.hadException())
2240         return;
2241
2242     parent->replaceChild(fragment.release(), this, exceptionState);
2243     RefPtr<Node> node = next ? next->previousSibling() : 0;
2244     if (!exceptionState.hadException() && node && node->isTextNode())
2245         mergeWithNextTextNode(node.release(), exceptionState);
2246
2247     if (!exceptionState.hadException() && prev && prev->isTextNode())
2248         mergeWithNextTextNode(prev.release(), exceptionState);
2249 }
2250
2251 Node* Element::insertAdjacent(const String& where, Node* newChild, ExceptionState& exceptionState)
2252 {
2253     if (equalIgnoringCase(where, "beforeBegin")) {
2254         if (ContainerNode* parent = this->parentNode()) {
2255             parent->insertBefore(newChild, this, exceptionState);
2256             if (!exceptionState.hadException())
2257                 return newChild;
2258         }
2259         return 0;
2260     }
2261
2262     if (equalIgnoringCase(where, "afterBegin")) {
2263         insertBefore(newChild, firstChild(), exceptionState);
2264         return exceptionState.hadException() ? 0 : newChild;
2265     }
2266
2267     if (equalIgnoringCase(where, "beforeEnd")) {
2268         appendChild(newChild, exceptionState);
2269         return exceptionState.hadException() ? 0 : newChild;
2270     }
2271
2272     if (equalIgnoringCase(where, "afterEnd")) {
2273         if (ContainerNode* parent = this->parentNode()) {
2274             parent->insertBefore(newChild, nextSibling(), exceptionState);
2275             if (!exceptionState.hadException())
2276                 return newChild;
2277         }
2278         return 0;
2279     }
2280
2281     exceptionState.throwDOMException(SyntaxError, "The value provided ('" + where + "') is not one of 'beforeBegin', 'afterBegin', 'beforeEnd', or 'afterEnd'.");
2282     return 0;
2283 }
2284
2285 // Step 1 of http://domparsing.spec.whatwg.org/#insertadjacenthtml()
2286 static Element* contextElementForInsertion(const String& where, Element* element, ExceptionState& exceptionState)
2287 {
2288     if (equalIgnoringCase(where, "beforeBegin") || equalIgnoringCase(where, "afterEnd")) {
2289         ContainerNode* parent = element->parentNode();
2290         if (!parent || !parent->isElementNode()) {
2291             exceptionState.throwDOMException(NoModificationAllowedError, "The element has no parent.");
2292             return 0;
2293         }
2294         return toElement(parent);
2295     }
2296     if (equalIgnoringCase(where, "afterBegin") || equalIgnoringCase(where, "beforeEnd"))
2297         return element;
2298     exceptionState.throwDOMException(SyntaxError, "The value provided ('" + where + "') is not one of 'beforeBegin', 'afterBegin', 'beforeEnd', or 'afterEnd'.");
2299     return 0;
2300 }
2301
2302 Element* Element::insertAdjacentElement(const String& where, Element* newChild, ExceptionState& exceptionState)
2303 {
2304     if (!newChild) {
2305         // IE throws COM Exception E_INVALIDARG; this is the best DOM exception alternative.
2306         exceptionState.throwTypeError("The node provided is null.");
2307         return 0;
2308     }
2309
2310     Node* returnValue = insertAdjacent(where, newChild, exceptionState);
2311     return toElement(returnValue);
2312 }
2313
2314 void Element::insertAdjacentText(const String& where, const String& text, ExceptionState& exceptionState)
2315 {
2316     RefPtr<Text> textNode = document().createTextNode(text);
2317     insertAdjacent(where, textNode.get(), exceptionState);
2318 }
2319
2320 void Element::insertAdjacentHTML(const String& where, const String& markup, ExceptionState& exceptionState)
2321 {
2322     RefPtr<Element> contextElement = contextElementForInsertion(where, this, exceptionState);
2323     if (!contextElement)
2324         return;
2325
2326     RefPtr<DocumentFragment> fragment = createFragmentForInnerOuterHTML(markup, contextElement.get(), AllowScriptingContent, "insertAdjacentHTML", exceptionState);
2327     if (!fragment)
2328         return;
2329     insertAdjacent(where, fragment.get(), exceptionState);
2330 }
2331
2332 String Element::innerText()
2333 {
2334     // We need to update layout, since plainText uses line boxes in the render tree.
2335     document().updateLayoutIgnorePendingStylesheets();
2336
2337     if (!renderer())
2338         return textContent(true);
2339
2340     return plainText(rangeOfContents(const_cast<Element*>(this)).get());
2341 }
2342
2343 String Element::outerText()
2344 {
2345     // Getting outerText is the same as getting innerText, only
2346     // setting is different. You would think this should get the plain
2347     // text for the outer range, but this is wrong, <br> for instance
2348     // would return different values for inner and outer text by such
2349     // a rule, but it doesn't in WinIE, and we want to match that.
2350     return innerText();
2351 }
2352
2353 String Element::textFromChildren()
2354 {
2355     Text* firstTextNode = 0;
2356     bool foundMultipleTextNodes = false;
2357     unsigned totalLength = 0;
2358
2359     for (Node* child = firstChild(); child; child = child->nextSibling()) {
2360         if (!child->isTextNode())
2361             continue;
2362         Text* text = toText(child);
2363         if (!firstTextNode)
2364             firstTextNode = text;
2365         else
2366             foundMultipleTextNodes = true;
2367         unsigned length = text->data().length();
2368         if (length > std::numeric_limits<unsigned>::max() - totalLength)
2369             return emptyString();
2370         totalLength += length;
2371     }
2372
2373     if (!firstTextNode)
2374         return emptyString();
2375
2376     if (firstTextNode && !foundMultipleTextNodes) {
2377         firstTextNode->atomize();
2378         return firstTextNode->data();
2379     }
2380
2381     StringBuilder content;
2382     content.reserveCapacity(totalLength);
2383     for (Node* child = firstTextNode; child; child = child->nextSibling()) {
2384         if (!child->isTextNode())
2385             continue;
2386         content.append(toText(child)->data());
2387     }
2388
2389     ASSERT(content.length() == totalLength);
2390     return content.toString();
2391 }
2392
2393 const AtomicString& Element::shadowPseudoId() const
2394 {
2395     if (ShadowRoot* root = containingShadowRoot()) {
2396         if (root->type() == ShadowRoot::UserAgentShadowRoot)
2397             return fastGetAttribute(pseudoAttr);
2398     }
2399     return nullAtom;
2400 }
2401
2402 void Element::setShadowPseudoId(const AtomicString& id)
2403 {
2404     ASSERT(CSSSelector::parsePseudoType(id) == CSSSelector::PseudoWebKitCustomElement || CSSSelector::parsePseudoType(id) == CSSSelector::PseudoUserAgentCustomElement);
2405     setAttribute(pseudoAttr, id);
2406 }
2407
2408 bool Element::isInDescendantTreeOf(const Element* shadowHost) const
2409 {
2410     ASSERT(shadowHost);
2411     ASSERT(isShadowHost(shadowHost));
2412
2413     const ShadowRoot* shadowRoot = containingShadowRoot();
2414     while (shadowRoot) {
2415         const Element* ancestorShadowHost = shadowRoot->shadowHost();
2416         if (ancestorShadowHost == shadowHost)
2417             return true;
2418         shadowRoot = ancestorShadowHost->containingShadowRoot();
2419     }
2420     return false;
2421 }
2422
2423 RenderStyle* Element::computedStyle(PseudoId pseudoElementSpecifier)
2424 {
2425     if (PseudoElement* element = pseudoElement(pseudoElementSpecifier))
2426         return element->computedStyle();
2427
2428     // FIXME: Find and use the renderer from the pseudo element instead of the actual element so that the 'length'
2429     // properties, which are only known by the renderer because it did the layout, will be correct and so that the
2430     // values returned for the ":selection" pseudo-element will be correct.
2431     if (RenderStyle* usedStyle = renderStyle()) {
2432         if (pseudoElementSpecifier) {
2433             RenderStyle* cachedPseudoStyle = usedStyle->getCachedPseudoStyle(pseudoElementSpecifier);
2434             return cachedPseudoStyle ? cachedPseudoStyle : usedStyle;
2435          } else
2436             return usedStyle;
2437     }
2438
2439     if (!inActiveDocument())
2440         // FIXME: Try to do better than this. Ensure that styleForElement() works for elements that are not in the
2441         // document tree and figure out when to destroy the computed style for such elements.
2442         return 0;
2443
2444     ElementRareData& rareData = ensureElementRareData();
2445     if (!rareData.computedStyle())
2446         rareData.setComputedStyle(document().styleForElementIgnoringPendingStylesheets(this));
2447     return pseudoElementSpecifier ? rareData.computedStyle()->getCachedPseudoStyle(pseudoElementSpecifier) : rareData.computedStyle();
2448 }
2449
2450 AtomicString Element::computeInheritedLanguage() const
2451 {
2452     const Node* n = this;
2453     AtomicString value;
2454     // The language property is inherited, so we iterate over the parents to find the first language.
2455     do {
2456         if (n->isElementNode()) {
2457             if (const ElementData* elementData = toElement(n)->elementData()) {
2458                 // Spec: xml:lang takes precedence -- http://www.w3.org/TR/xhtml1/#C_7
2459                 if (const Attribute* attribute = elementData->getAttributeItem(XMLNames::langAttr))
2460                     value = attribute->value();
2461                 else if (const Attribute* attribute = elementData->getAttributeItem(HTMLNames::langAttr))
2462                     value = attribute->value();
2463             }
2464         } else if (n->isDocumentNode()) {
2465             // checking the MIME content-language
2466             value = toDocument(n)->contentLanguage();
2467         }
2468
2469         n = n->parentNode();
2470     } while (n && value.isNull());
2471
2472     return value;
2473 }
2474
2475 Locale& Element::locale() const
2476 {
2477     return document().getCachedLocale(computeInheritedLanguage());
2478 }
2479
2480 void Element::cancelFocusAppearanceUpdate()
2481 {
2482     if (document().focusedElement() == this)
2483         document().cancelFocusAppearanceUpdate();
2484 }
2485
2486 void Element::normalizeAttributes()
2487 {
2488     if (!hasAttributes())
2489         return;
2490     // attributeCount() cannot be cached before the loop because the attributes
2491     // list is altered while iterating.
2492     for (unsigned i = 0; i < attributeCount(); ++i) {
2493         if (RefPtr<Attr> attr = attrIfExists(attributeItem(i).name()))
2494             attr->normalize();
2495     }
2496 }
2497
2498 void Element::updatePseudoElement(PseudoId pseudoId, StyleRecalcChange change)
2499 {
2500     ASSERT(!needsStyleRecalc());
2501     PseudoElement* element = pseudoElement(pseudoId);
2502     if (element && (change == UpdatePseudoElements || element->shouldCallRecalcStyle(change))) {
2503
2504         // Need to clear the cached style if the PseudoElement wants a recalc so it
2505         // computes a new style.
2506         if (element->needsStyleRecalc())
2507             renderer()->style()->removeCachedPseudoStyle(pseudoId);
2508
2509         // PseudoElement styles hang off their parent element's style so if we needed
2510         // a style recalc we should Force one on the pseudo.
2511         // FIXME: We should figure out the right text sibling to pass.
2512         element->recalcStyle(change == UpdatePseudoElements ? Force : change);
2513
2514         // Wait until our parent is not displayed or pseudoElementRendererIsNeeded
2515         // is false, otherwise we could continously create and destroy PseudoElements
2516         // when RenderObject::isChildAllowed on our parent returns false for the
2517         // PseudoElement's renderer for each style recalc.
2518         if (!renderer() || !pseudoElementRendererIsNeeded(renderer()->getCachedPseudoStyle(pseudoId)))
2519             elementRareData()->setPseudoElement(pseudoId, nullptr);
2520     } else if (change >= UpdatePseudoElements) {
2521         createPseudoElementIfNeeded(pseudoId);
2522     }
2523 }
2524
2525 void Element::createPseudoElementIfNeeded(PseudoId pseudoId)
2526 {
2527     if (isPseudoElement())
2528         return;
2529
2530     // Document::ensureStyleResolver is not inlined and shows up on profiles, avoid it here.
2531     StyleEngine* engine = document().styleEngine();
2532     RefPtr<PseudoElement> element = engine->ensureResolver().createPseudoElementIfNeeded(*this, pseudoId);
2533     if (!element)
2534         return;
2535
2536     if (pseudoId == BACKDROP)
2537         document().addToTopLayer(element.get(), this);
2538     element->insertedInto(this);
2539     element->attach();
2540
2541     InspectorInstrumentation::pseudoElementCreated(element.get());
2542
2543     ensureElementRareData().setPseudoElement(pseudoId, element.release());
2544 }
2545
2546 PseudoElement* Element::pseudoElement(PseudoId pseudoId) const
2547 {
2548     return hasRareData() ? elementRareData()->pseudoElement(pseudoId) : 0;
2549 }
2550
2551 RenderObject* Element::pseudoElementRenderer(PseudoId pseudoId) const
2552 {
2553     if (PseudoElement* element = pseudoElement(pseudoId))
2554         return element->renderer();
2555     return 0;
2556 }
2557
2558 bool Element::matches(const String& selectors, ExceptionState& exceptionState)
2559 {
2560     SelectorQuery* selectorQuery = document().selectorQueryCache().add(AtomicString(selectors), document(), exceptionState);
2561     if (!selectorQuery)
2562         return false;
2563     return selectorQuery->matches(*this);
2564 }
2565
2566 DOMTokenList& Element::classList()
2567 {
2568     ElementRareData& rareData = ensureElementRareData();
2569     if (!rareData.classList())
2570         rareData.setClassList(ClassList::create(this));
2571     return *rareData.classList();
2572 }
2573
2574 DOMStringMap& Element::dataset()
2575 {
2576     ElementRareData& rareData = ensureElementRareData();
2577     if (!rareData.dataset())
2578         rareData.setDataset(DatasetDOMStringMap::create(this));
2579     return *rareData.dataset();
2580 }
2581
2582 KURL Element::getURLAttribute(const QualifiedName& name) const
2583 {
2584 #if !ASSERT_DISABLED
2585     if (elementData()) {
2586         if (const Attribute* attribute = getAttributeItem(name))
2587             ASSERT(isURLAttribute(*attribute));
2588     }
2589 #endif
2590     return document().completeURL(stripLeadingAndTrailingHTMLSpaces(getAttribute(name)));
2591 }
2592
2593 KURL Element::getNonEmptyURLAttribute(const QualifiedName& name) const
2594 {
2595 #if !ASSERT_DISABLED
2596     if (elementData()) {
2597         if (const Attribute* attribute = getAttributeItem(name))
2598             ASSERT(isURLAttribute(*attribute));
2599     }
2600 #endif
2601     String value = stripLeadingAndTrailingHTMLSpaces(getAttribute(name));
2602     if (value.isEmpty())
2603         return KURL();
2604     return document().completeURL(value);
2605 }
2606
2607 int Element::getIntegralAttribute(const QualifiedName& attributeName) const
2608 {
2609     return getAttribute(attributeName).string().toInt();
2610 }
2611
2612 void Element::setIntegralAttribute(const QualifiedName& attributeName, int value)
2613 {
2614     setAttribute(attributeName, AtomicString::number(value));
2615 }
2616
2617 unsigned Element::getUnsignedIntegralAttribute(const QualifiedName& attributeName) const
2618 {
2619     return getAttribute(attributeName).string().toUInt();
2620 }
2621
2622 void Element::setUnsignedIntegralAttribute(const QualifiedName& attributeName, unsigned value)
2623 {
2624     // Range restrictions are enforced for unsigned IDL attributes that
2625     // reflect content attributes,
2626     //   http://www.whatwg.org/specs/web-apps/current-work/multipage/common-dom-interfaces.html#reflecting-content-attributes-in-idl-attributes
2627     if (value > 0x7fffffffu)
2628         value = 0;
2629     setAttribute(attributeName, AtomicString::number(value));
2630 }
2631
2632 double Element::getFloatingPointAttribute(const QualifiedName& attributeName, double fallbackValue) const
2633 {
2634     return parseToDoubleForNumberType(getAttribute(attributeName), fallbackValue);
2635 }
2636
2637 void Element::setFloatingPointAttribute(const QualifiedName& attributeName, double value)
2638 {
2639     setAttribute(attributeName, AtomicString::number(value));
2640 }
2641
2642 void Element::webkitRequestFullscreen()
2643 {
2644     FullscreenElementStack::from(document()).requestFullScreenForElement(this, ALLOW_KEYBOARD_INPUT, FullscreenElementStack::EnforceIFrameAllowFullScreenRequirement);
2645 }
2646
2647 void Element::webkitRequestFullScreen(unsigned short flags)
2648 {
2649     FullscreenElementStack::from(document()).requestFullScreenForElement(this, (flags | LEGACY_MOZILLA_REQUEST), FullscreenElementStack::EnforceIFrameAllowFullScreenRequirement);
2650 }
2651
2652 void Element::setContainsFullScreenElement(bool flag)
2653 {
2654     setElementFlag(ContainsFullScreenElement, flag);
2655     setNeedsStyleRecalc(SubtreeStyleChange);
2656 }
2657
2658 static Element* parentCrossingFrameBoundaries(Element* element)
2659 {
2660     ASSERT(element);
2661     return element->parentElement() ? element->parentElement() : element->document().ownerElement();
2662 }
2663
2664 void Element::setContainsFullScreenElementOnAncestorsCrossingFrameBoundaries(bool flag)
2665 {
2666     Element* element = this;
2667     while ((element = parentCrossingFrameBoundaries(element)))
2668         element->setContainsFullScreenElement(flag);
2669 }
2670
2671 void Element::setIsInTopLayer(bool inTopLayer)
2672 {
2673     if (isInTopLayer() == inTopLayer)
2674         return;
2675     setElementFlag(IsInTopLayer, inTopLayer);
2676
2677     // We must ensure a reattach occurs so the renderer is inserted in the correct sibling order under RenderView according to its
2678     // top layer position, or in its usual place if not in the top layer.
2679     lazyReattachIfAttached();
2680 }
2681
2682 void Element::webkitRequestPointerLock()
2683 {
2684     if (document().page())
2685         document().page()->pointerLockController().requestPointerLock(this);
2686 }
2687
2688 SpellcheckAttributeState Element::spellcheckAttributeState() const
2689 {
2690     const AtomicString& value = fastGetAttribute(spellcheckAttr);
2691     if (value == nullAtom)
2692         return SpellcheckAttributeDefault;
2693     if (equalIgnoringCase(value, "true") || equalIgnoringCase(value, ""))
2694         return SpellcheckAttributeTrue;
2695     if (equalIgnoringCase(value, "false"))
2696         return SpellcheckAttributeFalse;
2697
2698     return SpellcheckAttributeDefault;
2699 }
2700
2701 bool Element::isSpellCheckingEnabled() const
2702 {
2703     for (const Element* element = this; element; element = element->parentOrShadowHostElement()) {
2704         switch (element->spellcheckAttributeState()) {
2705         case SpellcheckAttributeTrue:
2706             return true;
2707         case SpellcheckAttributeFalse:
2708             return false;
2709         case SpellcheckAttributeDefault:
2710             break;
2711         }
2712     }
2713
2714     return true;
2715 }
2716
2717 #ifndef NDEBUG
2718 bool Element::fastAttributeLookupAllowed(const QualifiedName& name) const
2719 {
2720     if (name == HTMLNames::styleAttr)
2721         return false;
2722
2723     if (isSVGElement())
2724         return !toSVGElement(this)->isAnimatableAttribute(name);
2725
2726     return true;
2727 }
2728 #endif
2729
2730 #ifdef DUMP_NODE_STATISTICS
2731 bool Element::hasNamedNodeMap() const
2732 {
2733     return hasRareData() && elementRareData()->attributeMap();
2734 }
2735 #endif
2736
2737 inline void Element::updateName(const AtomicString& oldName, const AtomicString& newName)
2738 {
2739     if (!inDocument() || isInShadowTree())
2740         return;
2741
2742     if (oldName == newName)
2743         return;
2744
2745     if (shouldRegisterAsNamedItem())
2746         updateNamedItemRegistration(oldName, newName);
2747 }
2748
2749 inline void Element::updateId(const AtomicString& oldId, const AtomicString& newId)
2750 {
2751     if (!isInTreeScope())
2752         return;
2753
2754     if (oldId == newId)
2755         return;
2756
2757     updateId(treeScope(), oldId, newId);
2758 }
2759
2760 inline void Element::updateId(TreeScope& scope, const AtomicString& oldId, const AtomicString& newId)
2761 {
2762     ASSERT(isInTreeScope());
2763     ASSERT(oldId != newId);
2764
2765     if (!oldId.isEmpty())
2766         scope.removeElementById(oldId, this);
2767     if (!newId.isEmpty())
2768         scope.addElementById(newId, this);
2769
2770     if (shouldRegisterAsExtraNamedItem())
2771         updateExtraNamedItemRegistration(oldId, newId);
2772 }
2773
2774 void Element::updateLabel(TreeScope& scope, const AtomicString& oldForAttributeValue, const AtomicString& newForAttributeValue)
2775 {
2776     ASSERT(isHTMLLabelElement(this));
2777
2778     if (!inDocument())
2779         return;
2780
2781     if (oldForAttributeValue == newForAttributeValue)
2782         return;
2783
2784     if (!oldForAttributeValue.isEmpty())
2785         scope.removeLabel(oldForAttributeValue, toHTMLLabelElement(this));
2786     if (!newForAttributeValue.isEmpty())
2787         scope.addLabel(newForAttributeValue, toHTMLLabelElement(this));
2788 }
2789
2790 void Element::willModifyAttribute(const QualifiedName& name, const AtomicString& oldValue, const AtomicString& newValue)
2791 {
2792     if (isIdAttributeName(name)) {
2793         updateId(oldValue, newValue);
2794     } else if (name == HTMLNames::nameAttr) {
2795         updateName(oldValue, newValue);
2796     } else if (name == HTMLNames::forAttr && isHTMLLabelElement(*this)) {
2797         TreeScope& scope = treeScope();
2798         if (scope.shouldCacheLabelsByForAttribute())
2799             updateLabel(scope, oldValue, newValue);
2800     }
2801
2802     if (oldValue != newValue) {
2803         if (inActiveDocument() && document().styleResolver() && styleChangeType() < SubtreeStyleChange)
2804             document().ensureStyleResolver().ensureUpdatedRuleFeatureSet().scheduleStyleInvalidationForAttributeChange(name, *this);
2805
2806         if (isUpgradedCustomElement())
2807             CustomElement::attributeDidChange(this, name.localName(), oldValue, newValue);
2808     }
2809
2810     if (OwnPtrWillBeRawPtr<MutationObserverInterestGroup> recipients = MutationObserverInterestGroup::createForAttributesMutation(*this, name))
2811         recipients->enqueueMutationRecord(MutationRecord::createAttributes(this, name, oldValue));
2812
2813     InspectorInstrumentation::willModifyDOMAttr(this, oldValue, newValue);
2814 }
2815
2816 void Element::didAddAttribute(const QualifiedName& name, const AtomicString& value)
2817 {
2818     attributeChanged(name, value);
2819     InspectorInstrumentation::didModifyDOMAttr(this, name.localName(), value);
2820     dispatchSubtreeModifiedEvent();
2821 }
2822
2823 void Element::didModifyAttribute(const QualifiedName& name, const AtomicString& value)
2824 {
2825     attributeChanged(name, value);
2826     InspectorInstrumentation::didModifyDOMAttr(this, name.localName(), value);
2827     // Do not dispatch a DOMSubtreeModified event here; see bug 81141.
2828 }
2829
2830 void Element::didRemoveAttribute(const QualifiedName& name)
2831 {
2832     attributeChanged(name, nullAtom);
2833     InspectorInstrumentation::didRemoveDOMAttr(this, name.localName());
2834     dispatchSubtreeModifiedEvent();
2835 }
2836
2837 static bool needsURLResolutionForInlineStyle(const Element& element, const Document& oldDocument, const Document& newDocument)
2838 {
2839     if (oldDocument == newDocument)
2840         return false;
2841     if (oldDocument.baseURL() == newDocument.baseURL())
2842         return false;
2843     const StylePropertySet* style = element.inlineStyle();
2844     if (!style)
2845         return false;
2846     for (unsigned i = 0; i < style->propertyCount(); ++i) {
2847         // FIXME: Should handle all URL-based properties: CSSImageSetValue, CSSCursorImageValue, etc.
2848         if (style->propertyAt(i).value()->isImageValue())
2849             return true;
2850     }
2851     return false;
2852 }
2853
2854 static void reResolveURLsInInlineStyle(const Document& document, MutableStylePropertySet& style)
2855 {
2856     for (unsigned i = 0; i < style.propertyCount(); ++i) {
2857         StylePropertySet::PropertyReference property = style.propertyAt(i);
2858         // FIXME: Should handle all URL-based properties: CSSImageSetValue, CSSCursorImageValue, etc.
2859         if (property.value()->isImageValue())
2860             toCSSImageValue(property.value())->reResolveURL(document);
2861     }
2862 }
2863
2864 void Element::didMoveToNewDocument(Document& oldDocument)
2865 {
2866     Node::didMoveToNewDocument(oldDocument);
2867
2868     // If the documents differ by quirks mode then they differ by case sensitivity
2869     // for class and id names so we need to go through the attribute change logic
2870     // to pick up the new casing in the ElementData.
2871     if (oldDocument.inQuirksMode() != document().inQuirksMode()) {
2872         if (hasID())
2873             setIdAttribute(getIdAttribute());
2874         if (hasClass())
2875             setAttribute(HTMLNames::classAttr, getClassAttribute());
2876     }
2877
2878     if (needsURLResolutionForInlineStyle(*this, oldDocument, document()))
2879         reResolveURLsInInlineStyle(document(), ensureMutableInlineStyle());
2880 }
2881
2882 void Element::updateNamedItemRegistration(const AtomicString& oldName, const AtomicString& newName)
2883 {
2884     if (!document().isHTMLDocument())
2885         return;
2886
2887     if (!oldName.isEmpty())
2888         toHTMLDocument(document()).removeNamedItem(oldName);
2889
2890     if (!newName.isEmpty())
2891         toHTMLDocument(document()).addNamedItem(newName);
2892 }
2893
2894 void Element::updateExtraNamedItemRegistration(const AtomicString& oldId, const AtomicString& newId)
2895 {
2896     if (!document().isHTMLDocument())
2897         return;
2898
2899     if (!oldId.isEmpty())
2900         toHTMLDocument(document()).removeExtraNamedItem(oldId);
2901
2902     if (!newId.isEmpty())
2903         toHTMLDocument(document()).addExtraNamedItem(newId);
2904 }
2905
2906 PassRefPtr<HTMLCollection> Element::ensureCachedHTMLCollection(CollectionType type)
2907 {
2908     if (HTMLCollection* collection = cachedHTMLCollection(type))
2909         return collection;
2910
2911     if (type == TableRows) {
2912         ASSERT(isHTMLTableElement(this));
2913         return ensureRareData().ensureNodeLists().addCache<HTMLTableRowsCollection>(*this, type);
2914     } else if (type == SelectOptions) {
2915         ASSERT(isHTMLSelectElement(this));
2916         return ensureRareData().ensureNodeLists().addCache<HTMLOptionsCollection>(*this, type);
2917     } else if (type == FormControls) {
2918         ASSERT(isHTMLFormElement(this) || isHTMLFieldSetElement(this));
2919         return ensureRareData().ensureNodeLists().addCache<HTMLFormControlsCollection>(*this, type);
2920     }
2921     return ensureRareData().ensureNodeLists().addCache<HTMLCollection>(*this, type);
2922 }
2923
2924 void Element::scheduleLayerUpdate()
2925 {
2926     document().scheduleLayerUpdate(*this);
2927 }
2928
2929 HTMLCollection* Element::cachedHTMLCollection(CollectionType type)
2930 {
2931     return hasRareData() && rareData()->nodeLists() ? rareData()->nodeLists()->cached<HTMLCollection>(type) : 0;
2932 }
2933
2934 IntSize Element::savedLayerScrollOffset() const
2935 {
2936     return hasRareData() ? elementRareData()->savedLayerScrollOffset() : IntSize();
2937 }
2938
2939 void Element::setSavedLayerScrollOffset(const IntSize& size)
2940 {
2941     if (size.isZero() && !hasRareData())
2942         return;
2943     ensureElementRareData().setSavedLayerScrollOffset(size);
2944 }
2945
2946 PassRefPtr<Attr> Element::attrIfExists(const QualifiedName& name)
2947 {
2948     if (AttrNodeList* attrNodeList = attrNodeListForElement(this))
2949         return findAttrNodeInList(*attrNodeList, name);
2950     return nullptr;
2951 }
2952
2953 PassRefPtr<Attr> Element::ensureAttr(const QualifiedName& name)
2954 {
2955     AttrNodeList& attrNodeList = ensureAttrNodeListForElement(this);
2956     RefPtr<Attr> attrNode = findAttrNodeInList(attrNodeList, name);
2957     if (!attrNode) {
2958         attrNode = Attr::create(*this, name);
2959         treeScope().adoptIfNeeded(*attrNode);
2960         attrNodeList.append(attrNode);
2961     }
2962     return attrNode.release();
2963 }
2964
2965 void Element::detachAttrNodeFromElementWithValue(Attr* attrNode, const AtomicString& value)
2966 {
2967     ASSERT(hasSyntheticAttrChildNodes());
2968     attrNode->detachFromElementWithValue(value);
2969
2970     AttrNodeList* attrNodeList = attrNodeListForElement(this);
2971     for (unsigned i = 0; i < attrNodeList->size(); ++i) {
2972         if (attrNodeList->at(i)->qualifiedName() == attrNode->qualifiedName()) {
2973             attrNodeList->remove(i);
2974             if (attrNodeList->isEmpty())
2975                 removeAttrNodeListForElement(this);
2976             return;
2977         }
2978     }
2979     ASSERT_NOT_REACHED();
2980 }
2981
2982 void Element::detachAllAttrNodesFromElement()
2983 {
2984     AttrNodeList* attrNodeList = attrNodeListForElement(this);
2985     ASSERT(attrNodeList);
2986
2987     unsigned attributeCount = this->attributeCount();
2988     for (unsigned i = 0; i < attributeCount; ++i) {
2989         const Attribute& attribute = attributeItem(i);
2990         if (RefPtr<Attr> attrNode = findAttrNodeInList(*attrNodeList, attribute.name()))
2991             attrNode->detachFromElementWithValue(attribute.value());
2992     }
2993
2994     removeAttrNodeListForElement(this);
2995 }
2996
2997 void Element::willRecalcStyle(StyleRecalcChange)
2998 {
2999     ASSERT(hasCustomStyleCallbacks());
3000 }
3001
3002 void Element::didRecalcStyle(StyleRecalcChange)
3003 {
3004     ASSERT(hasCustomStyleCallbacks());
3005 }
3006
3007
3008 PassRefPtr<RenderStyle> Element::customStyleForRenderer()
3009 {
3010     ASSERT(hasCustomStyleCallbacks());
3011     return nullptr;
3012 }
3013
3014 void Element::cloneAttributesFromElement(const Element& other)
3015 {
3016     if (hasSyntheticAttrChildNodes())
3017         detachAllAttrNodesFromElement();
3018
3019     other.synchronizeAllAttributes();
3020     if (!other.m_elementData) {
3021         m_elementData.clear();
3022         return;
3023     }
3024
3025     const AtomicString& oldID = getIdAttribute();
3026     const AtomicString& newID = other.getIdAttribute();
3027
3028     if (!oldID.isNull() || !newID.isNull())
3029         updateId(oldID, newID);
3030
3031     const AtomicString& oldName = getNameAttribute();
3032     const AtomicString& newName = other.getNameAttribute();
3033
3034     if (!oldName.isNull() || !newName.isNull())
3035         updateName(oldName, newName);
3036
3037     // Quirks mode makes class and id not case sensitive. We can't share the ElementData
3038     // if the idForStyleResolution and the className need different casing.
3039     bool ownerDocumentsHaveDifferentCaseSensitivity = false;
3040     if (other.hasClass() || other.hasID())
3041         ownerDocumentsHaveDifferentCaseSensitivity = other.document().inQuirksMode() != document().inQuirksMode();
3042
3043     // If 'other' has a mutable ElementData, convert it to an immutable one so we can share it between both elements.
3044     // We can only do this if there are no presentation attributes and sharing the data won't result in different case sensitivity of class or id.
3045     if (other.m_elementData->isUnique()
3046         && !ownerDocumentsHaveDifferentCaseSensitivity
3047         && !other.m_elementData->presentationAttributeStyle())
3048         const_cast<Element&>(other).m_elementData = static_cast<const UniqueElementData*>(other.m_elementData.get())->makeShareableCopy();
3049
3050     if (!other.m_elementData->isUnique() && !ownerDocumentsHaveDifferentCaseSensitivity && !needsURLResolutionForInlineStyle(other, other.document(), document()))
3051         m_elementData = other.m_elementData;
3052     else
3053         m_elementData = other.m_elementData->makeUniqueCopy();
3054
3055     unsigned length = m_elementData->length();
3056     for (unsigned i = 0; i < length; ++i) {
3057         const Attribute& attribute = m_elementData->attributeItem(i);
3058         attributeChangedFromParserOrByCloning(attribute.name(), attribute.value(), ModifiedByCloning);
3059     }
3060 }
3061
3062 void Element::cloneDataFromElement(const Element& other)
3063 {
3064     cloneAttributesFromElement(other);
3065     copyNonAttributePropertiesFromElement(other);
3066 }
3067
3068 void Element::createUniqueElementData()
3069 {
3070     if (!m_elementData)
3071         m_elementData = UniqueElementData::create();
3072     else {
3073         ASSERT(!m_elementData->isUnique());
3074         m_elementData = static_cast<ShareableElementData*>(m_elementData.get())->makeUniqueCopy();
3075     }
3076 }
3077
3078 InputMethodContext& Element::inputMethodContext()
3079 {
3080     return ensureElementRareData().ensureInputMethodContext(toHTMLElement(this));
3081 }
3082
3083 bool Element::hasInputMethodContext() const
3084 {
3085     return hasRareData() && elementRareData()->hasInputMethodContext();
3086 }
3087
3088 void Element::synchronizeStyleAttributeInternal() const
3089 {
3090     ASSERT(isStyledElement());
3091     ASSERT(elementData());
3092     ASSERT(elementData()->m_styleAttributeIsDirty);
3093     elementData()->m_styleAttributeIsDirty = false;
3094     const StylePropertySet* inlineStyle = this->inlineStyle();
3095     const_cast<Element*>(this)->setSynchronizedLazyAttribute(styleAttr,
3096         inlineStyle ? AtomicString(inlineStyle->asText()) : nullAtom);
3097 }
3098
3099 CSSStyleDeclaration* Element::style()
3100 {
3101     if (!isStyledElement())
3102         return 0;
3103     return &ensureElementRareData().ensureInlineCSSStyleDeclaration(this);
3104 }
3105
3106 MutableStylePropertySet& Element::ensureMutableInlineStyle()
3107 {
3108     ASSERT(isStyledElement());
3109     RefPtr<StylePropertySet>& inlineStyle = ensureUniqueElementData().m_inlineStyle;
3110     if (!inlineStyle) {
3111         CSSParserMode mode = (!isHTMLElement() || document().inQuirksMode()) ? HTMLQuirksMode : HTMLStandardMode;
3112         inlineStyle = MutableStylePropertySet::create(mode);
3113     } else if (!inlineStyle->isMutable()) {
3114         inlineStyle = inlineStyle->mutableCopy();
3115     }
3116     return *toMutableStylePropertySet(inlineStyle);
3117 }
3118
3119 void Element::clearMutableInlineStyleIfEmpty()
3120 {
3121     if (ensureMutableInlineStyle().isEmpty()) {
3122         ensureUniqueElementData().m_inlineStyle.clear();
3123     }
3124 }
3125
3126 inline void Element::setInlineStyleFromString(const AtomicString& newStyleString)
3127 {
3128     ASSERT(isStyledElement());
3129     RefPtr<StylePropertySet>& inlineStyle = elementData()->m_inlineStyle;
3130
3131     // Avoid redundant work if we're using shared attribute data with already parsed inline style.
3132     if (inlineStyle && !elementData()->isUnique())
3133         return;
3134
3135     // We reconstruct the property set instead of mutating if there is no CSSOM wrapper.
3136     // This makes wrapperless property sets immutable and so cacheable.
3137     if (inlineStyle && !inlineStyle->isMutable())
3138         inlineStyle.clear();
3139
3140     if (!inlineStyle) {
3141         inlineStyle = BisonCSSParser::parseInlineStyleDeclaration(newStyleString, this);
3142     } else {
3143         ASSERT(inlineStyle->isMutable());
3144         static_pointer_cast<MutableStylePropertySet>(inlineStyle)->parseDeclaration(newStyleString, document().elementSheet().contents());
3145     }
3146 }
3147
3148 void Element::styleAttributeChanged(const AtomicString& newStyleString, AttributeModificationReason modificationReason)
3149 {
3150     ASSERT(isStyledElement());
3151     WTF::OrdinalNumber startLineNumber = WTF::OrdinalNumber::beforeFirst();
3152     if (document().scriptableDocumentParser() && !document().isInDocumentWrite())
3153         startLineNumber = document().scriptableDocumentParser()->lineNumber();
3154
3155     if (newStyleString.isNull()) {
3156         ensureUniqueElementData().m_inlineStyle.clear();
3157     } else if (modificationReason == ModifiedByCloning || document().contentSecurityPolicy()->allowInlineStyle(document().url(), startLineNumber)) {
3158         setInlineStyleFromString(newStyleString);
3159     }
3160
3161     elementData()->m_styleAttributeIsDirty = false;
3162
3163     setNeedsStyleRecalc(LocalStyleChange);
3164     InspectorInstrumentation::didInvalidateStyleAttr(this);
3165 }
3166
3167 void Element::inlineStyleChanged()
3168 {
3169     ASSERT(isStyledElement());
3170     setNeedsStyleRecalc(LocalStyleChange);
3171     ASSERT(elementData());
3172     elementData()->m_styleAttributeIsDirty = true;
3173     InspectorInstrumentation::didInvalidateStyleAttr(this);
3174 }
3175
3176 bool Element::setInlineStyleProperty(CSSPropertyID propertyID, CSSValueID identifier, bool important)
3177 {
3178     ASSERT(isStyledElement());
3179     ensureMutableInlineStyle().setProperty(propertyID, cssValuePool().createIdentifierValue(identifier), important);
3180     inlineStyleChanged();
3181     return true;
3182 }
3183
3184 bool Element::setInlineStyleProperty(CSSPropertyID propertyID, CSSPropertyID identifier, bool important)
3185 {
3186     ASSERT(isStyledElement());
3187     ensureMutableInlineStyle().setProperty(propertyID, cssValuePool().createIdentifierValue(identifier), important);
3188     inlineStyleChanged();
3189     return true;
3190 }
3191
3192 bool Element::setInlineStyleProperty(CSSPropertyID propertyID, double value, CSSPrimitiveValue::UnitTypes unit, bool important)
3193 {
3194     ASSERT(isStyledElement());
3195     ensureMutableInlineStyle().setProperty(propertyID, cssValuePool().createValue(value, unit), important);
3196     inlineStyleChanged();
3197     return true;
3198 }
3199
3200 bool Element::setInlineStyleProperty(CSSPropertyID propertyID, const String& value, bool important)
3201 {
3202     ASSERT(isStyledElement());
3203     bool changes = ensureMutableInlineStyle().setProperty(propertyID, value, important, document().elementSheet().contents());
3204     if (changes)
3205         inlineStyleChanged();
3206     return changes;
3207 }
3208
3209 bool Element::removeInlineStyleProperty(CSSPropertyID propertyID)
3210 {
3211     ASSERT(isStyledElement());
3212     if (!inlineStyle())
3213         return false;
3214     bool changes = ensureMutableInlineStyle().removeProperty(propertyID);
3215     if (changes)
3216         inlineStyleChanged();
3217     return changes;
3218 }
3219
3220 void Element::removeAllInlineStyleProperties()
3221 {
3222     ASSERT(isStyledElement());
3223     if (!inlineStyle())
3224         return;
3225     ensureMutableInlineStyle().clear();
3226     inlineStyleChanged();
3227 }
3228
3229 void Element::updatePresentationAttributeStyle()
3230 {
3231     synchronizeAllAttributes();
3232     // ShareableElementData doesn't store presentation attribute style, so make sure we have a UniqueElementData.
3233     UniqueElementData& elementData = ensureUniqueElementData();
3234     elementData.m_presentationAttributeStyleIsDirty = false;
3235     elementData.m_presentationAttributeStyle = computePresentationAttributeStyle(*this);
3236 }
3237
3238 void Element::addPropertyToPresentationAttributeStyle(MutableStylePropertySet* style, CSSPropertyID propertyID, CSSValueID identifier)
3239 {
3240     ASSERT(isStyledElement());
3241     style->setProperty(propertyID, cssValuePool().createIdentifierValue(identifier));
3242 }
3243
3244 void Element::addPropertyToPresentationAttributeStyle(MutableStylePropertySet* style, CSSPropertyID propertyID, double value, CSSPrimitiveValue::UnitTypes unit)
3245 {
3246     ASSERT(isStyledElement());
3247     style->setProperty(propertyID, cssValuePool().createValue(value, unit));
3248 }
3249
3250 void Element::addPropertyToPresentationAttributeStyle(MutableStylePropertySet* style, CSSPropertyID propertyID, const String& value)
3251 {
3252     ASSERT(isStyledElement());
3253     style->setProperty(propertyID, value, false);
3254 }
3255
3256 bool Element::supportsStyleSharing() const
3257 {
3258     if (!isStyledElement() || !parentOrShadowHostElement())
3259         return false;
3260     // If the element has inline style it is probably unique.
3261     if (inlineStyle())
3262         return false;
3263     if (isSVGElement() && toSVGElement(this)->animatedSMILStyleProperties())
3264         return false;
3265     // Ids stop style sharing if they show up in the stylesheets.
3266     if (hasID() && document().ensureStyleResolver().hasRulesForId(idForStyleResolution()))
3267         return false;
3268     // :active and :hover elements always make a chain towards the document node
3269     // and no siblings or cousins will have the same state. There's also only one
3270     // :focus element per scope so we don't need to attempt to share.
3271     if (isUserActionElement())
3272         return false;
3273     if (!parentOrShadowHostElement()->childrenSupportStyleSharing())
3274         return false;
3275     if (hasScopedHTMLStyleChild())
3276         return false;
3277     if (this == document().cssTarget())
3278         return false;
3279     if (isHTMLElement() && toHTMLElement(this)->hasDirectionAuto())
3280         return false;
3281     if (hasActiveAnimations())
3282         return false;
3283     // Turn off style sharing for elements that can gain layers for reasons outside of the style system.
3284     // See comments in RenderObject::setStyle().
3285     // FIXME: Why does gaining a layer from outside the style system require disabling sharing?
3286     if (isHTMLFrameElementBase(*this)
3287         || isHTMLEmbedElement(*this)
3288         || isHTMLObjectElement(*this)
3289         || isHTMLAppletElement(*this)
3290         || isHTMLCanvasElement(*this))
3291         return false;
3292     if (FullscreenElementStack::isActiveFullScreenElement(this))
3293         return false;
3294     return true;
3295 }
3296
3297 void Element::trace(Visitor* visitor)
3298 {
3299     if (hasRareData())
3300         visitor->trace(elementRareData());
3301
3302     ContainerNode::trace(visitor);
3303 }
3304
3305 } // namespace WebCore