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