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