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)
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.
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.
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.
27 #include "core/dom/Element.h"
29 #include "CSSValueKeywords.h"
30 #include "RuntimeEnabledFeatures.h"
33 #include "bindings/v8/Dictionary.h"
34 #include "bindings/v8/ExceptionMessages.h"
35 #include "bindings/v8/ExceptionState.h"
36 #include "core/accessibility/AXObjectCache.h"
37 #include "core/animation/DocumentTimeline.h"
38 #include "core/animation/css/CSSAnimations.h"
39 #include "core/css/CSSImageValue.h"
40 #include "core/css/CSSStyleSheet.h"
41 #include "core/css/CSSValuePool.h"
42 #include "core/css/PropertySetCSSStyleDeclaration.h"
43 #include "core/css/StylePropertySet.h"
44 #include "core/css/parser/BisonCSSParser.h"
45 #include "core/css/resolver/StyleResolver.h"
46 #include "core/css/resolver/StyleResolverParentScope.h"
47 #include "core/dom/Attr.h"
48 #include "core/dom/CSSSelectorWatch.h"
49 #include "core/dom/ClientRect.h"
50 #include "core/dom/ClientRectList.h"
51 #include "core/dom/DatasetDOMStringMap.h"
52 #include "core/dom/ElementDataCache.h"
53 #include "core/dom/ElementRareData.h"
54 #include "core/dom/ElementTraversal.h"
55 #include "core/dom/ExceptionCode.h"
56 #include "core/dom/FullscreenElementStack.h"
57 #include "core/dom/MutationObserverInterestGroup.h"
58 #include "core/dom/MutationRecord.h"
59 #include "core/dom/NamedNodeMap.h"
60 #include "core/dom/NodeRenderStyle.h"
61 #include "core/dom/PresentationAttributeStyle.h"
62 #include "core/dom/PseudoElement.h"
63 #include "core/dom/RenderTreeBuilder.h"
64 #include "core/dom/ScriptableDocumentParser.h"
65 #include "core/dom/SelectorQuery.h"
66 #include "core/dom/Text.h"
67 #include "core/dom/custom/CustomElement.h"
68 #include "core/dom/custom/CustomElementRegistrationContext.h"
69 #include "core/dom/shadow/InsertionPoint.h"
70 #include "core/dom/shadow/ShadowRoot.h"
71 #include "core/editing/FrameSelection.h"
72 #include "core/editing/TextIterator.h"
73 #include "core/editing/htmlediting.h"
74 #include "core/editing/markup.h"
75 #include "core/events/EventDispatcher.h"
76 #include "core/events/FocusEvent.h"
77 #include "core/frame/FrameView.h"
78 #include "core/frame/LocalFrame.h"
79 #include "core/frame/UseCounter.h"
80 #include "core/frame/csp/ContentSecurityPolicy.h"
81 #include "core/html/ClassList.h"
82 #include "core/html/HTMLCollection.h"
83 #include "core/html/HTMLDocument.h"
84 #include "core/html/HTMLElement.h"
85 #include "core/html/HTMLFormControlsCollection.h"
86 #include "core/html/HTMLFrameElementBase.h"
87 #include "core/html/HTMLFrameOwnerElement.h"
88 #include "core/html/HTMLLabelElement.h"
89 #include "core/html/HTMLOptionsCollection.h"
90 #include "core/html/HTMLTableRowsCollection.h"
91 #include "core/html/HTMLTemplateElement.h"
92 #include "core/html/parser/HTMLParserIdioms.h"
93 #include "core/inspector/InspectorInstrumentation.h"
94 #include "core/page/FocusController.h"
95 #include "core/page/Page.h"
96 #include "core/page/PointerLockController.h"
97 #include "core/rendering/RenderLayer.h"
98 #include "core/rendering/RenderView.h"
99 #include "core/rendering/RenderWidget.h"
100 #include "core/svg/SVGDocumentExtensions.h"
101 #include "core/svg/SVGElement.h"
102 #include "platform/scroll/ScrollableArea.h"
103 #include "wtf/BitVector.h"
104 #include "wtf/HashFunctions.h"
105 #include "wtf/text/CString.h"
106 #include "wtf/text/StringBuilder.h"
107 #include "wtf/text/TextPosition.h"
111 using namespace HTMLNames;
112 using namespace XMLNames;
114 typedef Vector<RefPtr<Attr> > AttrNodeList;
115 typedef HashMap<Element*, OwnPtr<AttrNodeList> > AttrNodeListMap;
117 static AttrNodeListMap& attrNodeListMap()
119 DEFINE_STATIC_LOCAL(AttrNodeListMap, map, ());
123 static AttrNodeList* attrNodeListForElement(Element* element)
125 if (!element->hasSyntheticAttrChildNodes())
127 ASSERT(attrNodeListMap().contains(element));
128 return attrNodeListMap().get(element);
131 static AttrNodeList& ensureAttrNodeListForElement(Element* element)
133 if (element->hasSyntheticAttrChildNodes()) {
134 ASSERT(attrNodeListMap().contains(element));
135 return *attrNodeListMap().get(element);
137 ASSERT(!attrNodeListMap().contains(element));
138 element->setHasSyntheticAttrChildNodes(true);
139 AttrNodeListMap::AddResult result = attrNodeListMap().add(element, adoptPtr(new AttrNodeList));
140 return *result.storedValue->value;
143 static void removeAttrNodeListForElement(Element* element)
145 ASSERT(element->hasSyntheticAttrChildNodes());
146 ASSERT(attrNodeListMap().contains(element));
147 attrNodeListMap().remove(element);
148 element->setHasSyntheticAttrChildNodes(false);
151 static Attr* findAttrNodeInList(const AttrNodeList& attrNodeList, const QualifiedName& name)
153 AttrNodeList::const_iterator end = attrNodeList.end();
154 for (AttrNodeList::const_iterator it = attrNodeList.begin(); it != end; ++it) {
155 if ((*it)->qualifiedName() == name)
161 PassRefPtr<Element> Element::create(const QualifiedName& tagName, Document* document)
163 return adoptRef(new Element(tagName, document, CreateElement));
168 ASSERT(needsAttach());
171 elementRareData()->clearShadow();
173 if (isCustomElement())
174 CustomElement::wasDestroyed(this);
176 if (hasSyntheticAttrChildNodes())
177 detachAllAttrNodesFromElement();
179 if (hasPendingResources()) {
180 document().accessSVGExtensions().removeElementFromPendingResources(this);
181 ASSERT(!hasPendingResources());
185 inline ElementRareData* Element::elementRareData() const
187 ASSERT(hasRareData());
188 return static_cast<ElementRareData*>(rareData());
191 inline ElementRareData& Element::ensureElementRareData()
193 return static_cast<ElementRareData&>(ensureRareData());
196 bool Element::hasElementFlagInternal(ElementFlags mask) const
198 return elementRareData()->hasElementFlag(mask);
201 void Element::setElementFlag(ElementFlags mask, bool value)
203 if (!hasRareData() && !value)
205 ensureElementRareData().setElementFlag(mask, value);
208 void Element::clearElementFlag(ElementFlags mask)
212 elementRareData()->clearElementFlag(mask);
215 void Element::clearTabIndexExplicitlyIfNeeded()
218 elementRareData()->clearTabIndexExplicitly();
221 void Element::setTabIndexExplicitly(short tabIndex)
223 ensureElementRareData().setTabIndexExplicitly(tabIndex);
226 short Element::tabIndex() const
228 return hasRareData() ? elementRareData()->tabIndex() : 0;
231 bool Element::rendererIsFocusable() const
233 // Elements in canvas fallback content are not rendered, but they are allowed to be
234 // focusable as long as their canvas is displayed and visible.
235 if (isInCanvasSubtree()) {
236 const Element* e = this;
237 while (e && !e->hasLocalName(canvasTag))
238 e = e->parentElement();
240 return e->renderer() && e->renderer()->style()->visibility() == VISIBLE;
243 // FIXME: These asserts should be in Node::isFocusable, but there are some
244 // callsites like Document::setFocusedElement that would currently fail on
245 // them. See crbug.com/251163
247 // We can't just use needsStyleRecalc() because if the node is in a
248 // display:none tree it might say it needs style recalc but the whole
249 // document is actually up to date.
250 ASSERT(!document().childNeedsStyleRecalc());
253 // FIXME: Even if we are not visible, we might have a child that is visible.
254 // Hyatt wants to fix that some day with a "has visible content" flag or the like.
255 if (!renderer() || renderer()->style()->visibility() != VISIBLE)
261 PassRefPtr<Node> Element::cloneNode(bool deep)
263 return deep ? cloneElementWithChildren() : cloneElementWithoutChildren();
266 PassRefPtr<Element> Element::cloneElementWithChildren()
268 RefPtr<Element> clone = cloneElementWithoutChildren();
269 cloneChildNodes(clone.get());
270 return clone.release();
273 PassRefPtr<Element> Element::cloneElementWithoutChildren()
275 RefPtr<Element> clone = cloneElementWithoutAttributesAndChildren();
276 // This will catch HTML elements in the wrong namespace that are not correctly copied.
277 // This is a sanity check as HTML overloads some of the DOM methods.
278 ASSERT(isHTMLElement() == clone->isHTMLElement());
280 clone->cloneDataFromElement(*this);
281 return clone.release();
284 PassRefPtr<Element> Element::cloneElementWithoutAttributesAndChildren()
286 return document().createElement(tagQName(), false);
289 PassRefPtr<Attr> Element::detachAttribute(size_t index)
291 ASSERT(elementData());
292 const Attribute& attribute = elementData()->attributeItem(index);
293 RefPtr<Attr> attrNode = attrIfExists(attribute.name());
295 detachAttrNodeAtIndex(attrNode.get(), index);
297 attrNode = Attr::create(document(), attribute.name(), attribute.value());
298 removeAttributeInternal(index, NotInSynchronizationOfLazyAttribute);
300 return attrNode.release();
303 void Element::detachAttrNodeAtIndex(Attr* attr, size_t index)
306 ASSERT(elementData());
308 const Attribute& attribute = elementData()->attributeItem(index);
309 ASSERT(attribute.name() == attr->qualifiedName());
310 detachAttrNodeFromElementWithValue(attr, attribute.value());
311 removeAttributeInternal(index, NotInSynchronizationOfLazyAttribute);
314 void Element::removeAttribute(const QualifiedName& name)
319 size_t index = elementData()->getAttributeItemIndex(name);
320 if (index == kNotFound)
323 removeAttributeInternal(index, NotInSynchronizationOfLazyAttribute);
326 void Element::setBooleanAttribute(const QualifiedName& name, bool value)
329 setAttribute(name, emptyAtom);
331 removeAttribute(name);
334 NamedNodeMap* Element::attributes() const
336 ElementRareData& rareData = const_cast<Element*>(this)->ensureElementRareData();
337 if (NamedNodeMap* attributeMap = rareData.attributeMap())
340 rareData.setAttributeMap(NamedNodeMap::create(const_cast<Element*>(this)));
341 return rareData.attributeMap();
344 ActiveAnimations* Element::activeAnimations() const
347 return elementRareData()->activeAnimations();
351 ActiveAnimations& Element::ensureActiveAnimations()
353 ElementRareData& rareData = ensureElementRareData();
354 if (!rareData.activeAnimations())
355 rareData.setActiveAnimations(adoptPtrWillBeNoop(new ActiveAnimations()));
356 return *rareData.activeAnimations();
359 bool Element::hasActiveAnimations() const
364 ActiveAnimations* activeAnimations = elementRareData()->activeAnimations();
365 return activeAnimations && !activeAnimations->isEmpty();
368 Node::NodeType Element::nodeType() const
373 bool Element::hasAttribute(const QualifiedName& name) const
375 return hasAttributeNS(name.namespaceURI(), name.localName());
378 void Element::synchronizeAllAttributes() const
382 // NOTE: anyAttributeMatches in SelectorChecker.cpp
383 // currently assumes that all lazy attributes have a null namespace.
384 // If that ever changes we'll need to fix that code.
385 if (elementData()->m_styleAttributeIsDirty) {
386 ASSERT(isStyledElement());
387 synchronizeStyleAttributeInternal();
389 if (elementData()->m_animatedSVGAttributesAreDirty) {
390 ASSERT(isSVGElement());
391 toSVGElement(this)->synchronizeAnimatedSVGAttribute(anyQName());
395 inline void Element::synchronizeAttribute(const QualifiedName& name) const
399 if (UNLIKELY(name == styleAttr && elementData()->m_styleAttributeIsDirty)) {
400 ASSERT(isStyledElement());
401 synchronizeStyleAttributeInternal();
404 if (UNLIKELY(elementData()->m_animatedSVGAttributesAreDirty)) {
405 ASSERT(isSVGElement());
406 // See comment in the AtomicString version of synchronizeAttribute()
408 toSVGElement(this)->synchronizeAnimatedSVGAttribute(name);
412 void Element::synchronizeAttribute(const AtomicString& localName) const
414 // This version of synchronizeAttribute() is streamlined for the case where you don't have a full QualifiedName,
415 // e.g when called from DOM API.
418 if (elementData()->m_styleAttributeIsDirty && equalPossiblyIgnoringCase(localName, styleAttr.localName(), shouldIgnoreAttributeCase())) {
419 ASSERT(isStyledElement());
420 synchronizeStyleAttributeInternal();
423 if (elementData()->m_animatedSVGAttributesAreDirty) {
424 // We're not passing a namespace argument on purpose. SVGNames::*Attr are defined w/o namespaces as well.
426 // FIXME: this code is called regardless of whether name is an
427 // animated SVG Attribute. It would seem we should only call this method
428 // if SVGElement::isAnimatableAttribute is true, but the list of
429 // animatable attributes in isAnimatableAttribute does not suffice to
430 // pass all layout tests. Also, m_animatedSVGAttributesAreDirty stays
431 // dirty unless synchronizeAnimatedSVGAttribute is called with
432 // anyQName(). This means that even if Element::synchronizeAttribute()
433 // is called on all attributes, m_animatedSVGAttributesAreDirty remains
435 toSVGElement(this)->synchronizeAnimatedSVGAttribute(QualifiedName(nullAtom, localName, nullAtom));
439 const AtomicString& Element::getAttribute(const QualifiedName& name) const
443 synchronizeAttribute(name);
444 if (const Attribute* attribute = getAttributeItem(name))
445 return attribute->value();
449 void Element::scrollIntoView(bool alignToTop)
451 document().updateLayoutIgnorePendingStylesheets();
456 LayoutRect bounds = boundingBox();
457 // Align to the top / bottom and to the closest edge.
459 renderer()->scrollRectToVisible(bounds, ScrollAlignment::alignToEdgeIfNeeded, ScrollAlignment::alignTopAlways);
461 renderer()->scrollRectToVisible(bounds, ScrollAlignment::alignToEdgeIfNeeded, ScrollAlignment::alignBottomAlways);
464 void Element::scrollIntoViewIfNeeded(bool centerIfNeeded)
466 document().updateLayoutIgnorePendingStylesheets();
471 LayoutRect bounds = boundingBox();
473 renderer()->scrollRectToVisible(bounds, ScrollAlignment::alignCenterIfNeeded, ScrollAlignment::alignCenterIfNeeded);
475 renderer()->scrollRectToVisible(bounds, ScrollAlignment::alignToEdgeIfNeeded, ScrollAlignment::alignToEdgeIfNeeded);
478 void Element::scrollByUnits(int units, ScrollGranularity granularity)
480 document().updateLayoutIgnorePendingStylesheets();
485 if (!renderer()->hasOverflowClip())
488 ScrollDirection direction = ScrollDown;
490 direction = ScrollUp;
493 toRenderBox(renderer())->scroll(direction, granularity, units);
496 void Element::scrollByLines(int lines)
498 scrollByUnits(lines, ScrollByLine);
501 void Element::scrollByPages(int pages)
503 scrollByUnits(pages, ScrollByPage);
506 static float localZoomForRenderer(RenderObject& renderer)
508 // FIXME: This does the wrong thing if two opposing zooms are in effect and canceled each
509 // other out, but the alternative is that we'd have to crawl up the whole render tree every
510 // time (or store an additional bit in the RenderStyle to indicate that a zoom was specified).
511 float zoomFactor = 1;
512 if (renderer.style()->effectiveZoom() != 1) {
513 // Need to find the nearest enclosing RenderObject that set up
514 // a differing zoom, and then we divide our result by it to eliminate the zoom.
515 RenderObject* prev = &renderer;
516 for (RenderObject* curr = prev->parent(); curr; curr = curr->parent()) {
517 if (curr->style()->effectiveZoom() != prev->style()->effectiveZoom()) {
518 zoomFactor = prev->style()->zoom();
523 if (prev->isRenderView())
524 zoomFactor = prev->style()->zoom();
529 static int adjustForLocalZoom(LayoutUnit value, RenderObject& renderer)
531 float zoomFactor = localZoomForRenderer(renderer);
534 return lroundf(value / zoomFactor);
537 int Element::offsetLeft()
539 document().updateLayoutIgnorePendingStylesheets();
540 if (RenderBoxModelObject* renderer = renderBoxModelObject())
541 return adjustForLocalZoom(renderer->pixelSnappedOffsetLeft(), *renderer);
545 int Element::offsetTop()
547 document().updateLayoutIgnorePendingStylesheets();
548 if (RenderBoxModelObject* renderer = renderBoxModelObject())
549 return adjustForLocalZoom(renderer->pixelSnappedOffsetTop(), *renderer);
553 int Element::offsetWidth()
555 document().updateRenderTreeForNodeIfNeeded(this);
557 if (RenderBox* renderer = renderBox()) {
558 if (renderer->canDetermineWidthWithoutLayout())
559 return adjustLayoutUnitForAbsoluteZoom(renderer->fixedOffsetWidth(), *renderer).round();
562 document().updateLayoutIgnorePendingStylesheets();
563 if (RenderBoxModelObject* renderer = renderBoxModelObject())
564 return adjustLayoutUnitForAbsoluteZoom(renderer->pixelSnappedOffsetWidth(), *renderer).round();
568 int Element::offsetHeight()
570 document().updateLayoutIgnorePendingStylesheets();
571 if (RenderBoxModelObject* renderer = renderBoxModelObject())
572 return adjustLayoutUnitForAbsoluteZoom(renderer->pixelSnappedOffsetHeight(), *renderer).round();
576 Element* Element::offsetParentForBindings()
578 Element* element = offsetParent();
579 if (!element || !element->isInShadowTree())
581 return element->containingShadowRoot()->shouldExposeToBindings() ? element : 0;
584 Element* Element::offsetParent()
586 document().updateLayoutIgnorePendingStylesheets();
587 if (RenderObject* renderer = this->renderer())
588 return renderer->offsetParent();
592 int Element::clientLeft()
594 document().updateLayoutIgnorePendingStylesheets();
596 if (RenderBox* renderer = renderBox())
597 return adjustForAbsoluteZoom(roundToInt(renderer->clientLeft()), renderer);
601 int Element::clientTop()
603 document().updateLayoutIgnorePendingStylesheets();
605 if (RenderBox* renderer = renderBox())
606 return adjustForAbsoluteZoom(roundToInt(renderer->clientTop()), renderer);
610 int Element::clientWidth()
612 document().updateLayoutIgnorePendingStylesheets();
614 // When in strict mode, clientWidth for the document element should return the width of the containing frame.
615 // When in quirks mode, clientWidth for the body element should return the width of the containing frame.
616 bool inQuirksMode = document().inQuirksMode();
617 if ((!inQuirksMode && document().documentElement() == this)
618 || (inQuirksMode && isHTMLElement() && document().body() == this)) {
619 if (FrameView* view = document().view()) {
620 if (RenderView* renderView = document().renderView())
621 return adjustForAbsoluteZoom(view->layoutSize().width(), renderView);
625 if (RenderBox* renderer = renderBox())
626 return adjustLayoutUnitForAbsoluteZoom(renderer->pixelSnappedClientWidth(), *renderer).round();
630 int Element::clientHeight()
632 document().updateLayoutIgnorePendingStylesheets();
634 // When in strict mode, clientHeight for the document element should return the height of the containing frame.
635 // When in quirks mode, clientHeight for the body element should return the height of the containing frame.
636 bool inQuirksMode = document().inQuirksMode();
638 if ((!inQuirksMode && document().documentElement() == this)
639 || (inQuirksMode && isHTMLElement() && document().body() == this)) {
640 if (FrameView* view = document().view()) {
641 if (RenderView* renderView = document().renderView())
642 return adjustForAbsoluteZoom(view->layoutSize().height(), renderView);
646 if (RenderBox* renderer = renderBox())
647 return adjustLayoutUnitForAbsoluteZoom(renderer->pixelSnappedClientHeight(), *renderer).round();
651 int Element::scrollLeft()
653 document().updateLayoutIgnorePendingStylesheets();
655 if (document().documentElement() != this) {
656 if (RenderBox* rend = renderBox())
657 return adjustForAbsoluteZoom(rend->scrollLeft(), rend);
661 if (RuntimeEnabledFeatures::scrollTopLeftInteropEnabled()) {
662 if (document().inQuirksMode())
665 if (FrameView* view = document().view()) {
666 if (RenderView* renderView = document().renderView())
667 return adjustForAbsoluteZoom(view->scrollX(), renderView);
674 int Element::scrollTop()
676 document().updateLayoutIgnorePendingStylesheets();
678 if (document().documentElement() != this) {
679 if (RenderBox* rend = renderBox())
680 return adjustForAbsoluteZoom(rend->scrollTop(), rend);
684 if (RuntimeEnabledFeatures::scrollTopLeftInteropEnabled()) {
685 if (document().inQuirksMode())
688 if (FrameView* view = document().view()) {
689 if (RenderView* renderView = document().renderView())
690 return adjustForAbsoluteZoom(view->scrollY(), renderView);
697 void Element::setScrollLeft(int newLeft)
699 document().updateLayoutIgnorePendingStylesheets();
701 if (document().documentElement() != this) {
702 if (RenderBox* rend = renderBox())
703 rend->setScrollLeft(static_cast<int>(newLeft * rend->style()->effectiveZoom()));
707 if (RuntimeEnabledFeatures::scrollTopLeftInteropEnabled()) {
708 if (document().inQuirksMode())
711 LocalFrame* frame = document().frame();
714 FrameView* view = frame->view();
718 view->setScrollPosition(IntPoint(static_cast<int>(newLeft * frame->pageZoomFactor()), view->scrollY()));
722 void Element::setScrollLeft(const Dictionary& scrollOptionsHorizontal, ExceptionState& exceptionState)
724 String scrollBehaviorString;
725 ScrollBehavior scrollBehavior = ScrollBehaviorAuto;
726 if (scrollOptionsHorizontal.get("behavior", scrollBehaviorString)) {
727 if (!ScrollableArea::scrollBehaviorFromString(scrollBehaviorString, scrollBehavior)) {
728 exceptionState.throwTypeError("The ScrollBehavior provided is invalid.");
734 if (!scrollOptionsHorizontal.get("x", position)) {
735 exceptionState.throwTypeError("ScrollOptionsHorizontal must include an 'x' member.");
739 // FIXME: Use scrollBehavior to decide whether to scroll smoothly or instantly.
740 setScrollLeft(position);
743 void Element::setScrollTop(int newTop)
745 document().updateLayoutIgnorePendingStylesheets();
747 if (document().documentElement() != this) {
748 if (RenderBox* rend = renderBox())
749 rend->setScrollTop(static_cast<int>(newTop * rend->style()->effectiveZoom()));
753 if (RuntimeEnabledFeatures::scrollTopLeftInteropEnabled()) {
754 if (document().inQuirksMode())
757 LocalFrame* frame = document().frame();
760 FrameView* view = frame->view();
764 view->setScrollPosition(IntPoint(view->scrollX(), static_cast<int>(newTop * frame->pageZoomFactor())));
768 void Element::setScrollTop(const Dictionary& scrollOptionsVertical, ExceptionState& exceptionState)
770 String scrollBehaviorString;
771 ScrollBehavior scrollBehavior = ScrollBehaviorAuto;
772 if (scrollOptionsVertical.get("behavior", scrollBehaviorString)) {
773 if (!ScrollableArea::scrollBehaviorFromString(scrollBehaviorString, scrollBehavior)) {
774 exceptionState.throwTypeError("The ScrollBehavior provided is invalid.");
780 if (!scrollOptionsVertical.get("y", position)) {
781 exceptionState.throwTypeError("ScrollOptionsVertical must include a 'y' member.");
785 // FIXME: Use scrollBehavior to decide whether to scroll smoothly or instantly.
786 setScrollTop(position);
789 int Element::scrollWidth()
791 document().updateLayoutIgnorePendingStylesheets();
792 if (RenderBox* rend = renderBox())
793 return adjustForAbsoluteZoom(rend->scrollWidth(), rend);
797 int Element::scrollHeight()
799 document().updateLayoutIgnorePendingStylesheets();
800 if (RenderBox* rend = renderBox())
801 return adjustForAbsoluteZoom(rend->scrollHeight(), rend);
805 IntRect Element::boundsInRootViewSpace()
807 document().updateLayoutIgnorePendingStylesheets();
809 FrameView* view = document().view();
813 Vector<FloatQuad> quads;
814 if (isSVGElement() && renderer()) {
815 // Get the bounding rectangle from the SVG model.
816 SVGElement* svgElement = toSVGElement(this);
818 if (svgElement->getBoundingBox(localRect))
819 quads.append(renderer()->localToAbsoluteQuad(localRect));
821 // Get the bounding rectangle from the box model.
822 if (renderBoxModelObject())
823 renderBoxModelObject()->absoluteQuads(quads);
829 IntRect result = quads[0].enclosingBoundingBox();
830 for (size_t i = 1; i < quads.size(); ++i)
831 result.unite(quads[i].enclosingBoundingBox());
833 result = view->contentsToRootView(result);
837 PassRefPtr<ClientRectList> Element::getClientRects()
839 document().updateLayoutIgnorePendingStylesheets();
841 RenderBoxModelObject* renderBoxModelObject = this->renderBoxModelObject();
842 if (!renderBoxModelObject)
843 return ClientRectList::create();
845 // FIXME: Handle SVG elements.
846 // FIXME: Handle table/inline-table with a caption.
848 Vector<FloatQuad> quads;
849 renderBoxModelObject->absoluteQuads(quads);
850 document().adjustFloatQuadsForScrollAndAbsoluteZoom(quads, *renderBoxModelObject);
851 return ClientRectList::create(quads);
854 PassRefPtr<ClientRect> Element::getBoundingClientRect()
856 document().updateLayoutIgnorePendingStylesheets();
858 Vector<FloatQuad> quads;
859 if (isSVGElement() && renderer() && !renderer()->isSVGRoot()) {
860 // Get the bounding rectangle from the SVG model.
861 SVGElement* svgElement = toSVGElement(this);
863 if (svgElement->getBoundingBox(localRect))
864 quads.append(renderer()->localToAbsoluteQuad(localRect));
866 // Get the bounding rectangle from the box model.
867 if (renderBoxModelObject())
868 renderBoxModelObject()->absoluteQuads(quads);
872 return ClientRect::create();
874 FloatRect result = quads[0].boundingBox();
875 for (size_t i = 1; i < quads.size(); ++i)
876 result.unite(quads[i].boundingBox());
879 document().adjustFloatRectForScrollAndAbsoluteZoom(result, *renderer());
880 return ClientRect::create(result);
883 IntRect Element::screenRect() const
887 // FIXME: this should probably respect transforms
888 return document().view()->contentsToScreen(renderer()->absoluteBoundingBoxRectIgnoringTransforms());
891 const AtomicString& Element::getAttribute(const AtomicString& localName) const
895 synchronizeAttribute(localName);
896 if (const Attribute* attribute = elementData()->getAttributeItem(localName, shouldIgnoreAttributeCase()))
897 return attribute->value();
901 const AtomicString& Element::getAttributeNS(const AtomicString& namespaceURI, const AtomicString& localName) const
903 return getAttribute(QualifiedName(nullAtom, localName, namespaceURI));
906 void Element::setAttribute(const AtomicString& localName, const AtomicString& value, ExceptionState& exceptionState)
908 if (!Document::isValidName(localName)) {
909 exceptionState.throwDOMException(InvalidCharacterError, "'" + localName + "' is not a valid attribute name.");
913 synchronizeAttribute(localName);
914 const AtomicString& caseAdjustedLocalName = shouldIgnoreAttributeCase() ? localName.lower() : localName;
916 size_t index = elementData() ? elementData()->getAttributeItemIndex(caseAdjustedLocalName, false) : kNotFound;
917 const QualifiedName& qName = index != kNotFound ? attributeItem(index).name() : QualifiedName(nullAtom, caseAdjustedLocalName, nullAtom);
918 setAttributeInternal(index, qName, value, NotInSynchronizationOfLazyAttribute);
921 void Element::setAttribute(const QualifiedName& name, const AtomicString& value)
923 synchronizeAttribute(name);
924 size_t index = elementData() ? elementData()->getAttributeItemIndex(name) : kNotFound;
925 setAttributeInternal(index, name, value, NotInSynchronizationOfLazyAttribute);
928 void Element::setSynchronizedLazyAttribute(const QualifiedName& name, const AtomicString& value)
930 size_t index = elementData() ? elementData()->getAttributeItemIndex(name) : kNotFound;
931 setAttributeInternal(index, name, value, InSynchronizationOfLazyAttribute);
934 ALWAYS_INLINE void Element::setAttributeInternal(size_t index, const QualifiedName& name, const AtomicString& newValue, SynchronizationOfLazyAttribute inSynchronizationOfLazyAttribute)
936 if (newValue.isNull()) {
937 if (index != kNotFound)
938 removeAttributeInternal(index, inSynchronizationOfLazyAttribute);
942 if (index == kNotFound) {
943 addAttributeInternal(name, newValue, inSynchronizationOfLazyAttribute);
947 const Attribute& existingAttribute = attributeItem(index);
948 QualifiedName existingAttributeName = existingAttribute.name();
950 if (!inSynchronizationOfLazyAttribute)
951 willModifyAttribute(existingAttributeName, existingAttribute.value(), newValue);
953 if (newValue != existingAttribute.value()) {
954 // If there is an Attr node hooked to this attribute, the Attr::setValue() call below
955 // will write into the ElementData.
956 // FIXME: Refactor this so it makes some sense.
957 if (RefPtr<Attr> attrNode = inSynchronizationOfLazyAttribute ? nullptr : attrIfExists(existingAttributeName))
958 attrNode->setValue(newValue);
960 ensureUniqueElementData().attributeItem(index).setValue(newValue);
963 if (!inSynchronizationOfLazyAttribute)
964 didModifyAttribute(existingAttributeName, newValue);
967 static inline AtomicString makeIdForStyleResolution(const AtomicString& value, bool inQuirksMode)
970 return value.lower();
974 static bool checkNeedsStyleInvalidationForIdChange(const AtomicString& oldId, const AtomicString& newId, const RuleFeatureSet& features)
976 ASSERT(newId != oldId);
977 if (!oldId.isEmpty() && features.hasSelectorForId(oldId))
979 if (!newId.isEmpty() && features.hasSelectorForId(newId))
984 void Element::attributeChanged(const QualifiedName& name, const AtomicString& newValue, AttributeModificationReason reason)
986 if (ElementShadow* parentElementShadow = shadowWhereNodeCanBeDistributed(*this)) {
987 if (shouldInvalidateDistributionWhenAttributeChanged(parentElementShadow, name, newValue))
988 parentElementShadow->setNeedsDistributionRecalc();
991 parseAttribute(name, newValue);
993 document().incDOMTreeVersion();
995 StyleResolver* styleResolver = document().styleResolver();
996 bool testShouldInvalidateStyle = inActiveDocument() && styleResolver && styleChangeType() < SubtreeStyleChange;
997 bool shouldInvalidateStyle = false;
999 if (isStyledElement() && name == styleAttr) {
1000 styleAttributeChanged(newValue, reason);
1001 } else if (isStyledElement() && isPresentationAttribute(name)) {
1002 elementData()->m_presentationAttributeStyleIsDirty = true;
1003 setNeedsStyleRecalc(LocalStyleChange);
1006 if (isIdAttributeName(name)) {
1007 AtomicString oldId = elementData()->idForStyleResolution();
1008 AtomicString newId = makeIdForStyleResolution(newValue, document().inQuirksMode());
1009 if (newId != oldId) {
1010 elementData()->setIdForStyleResolution(newId);
1011 shouldInvalidateStyle = testShouldInvalidateStyle && checkNeedsStyleInvalidationForIdChange(oldId, newId, styleResolver->ensureUpdatedRuleFeatureSet());
1013 } else if (name == classAttr) {
1014 classAttributeChanged(newValue);
1015 } else if (name == HTMLNames::nameAttr) {
1016 setHasName(!newValue.isNull());
1019 invalidateNodeListCachesInAncestors(&name, this);
1021 // If there is currently no StyleResolver, we can't be sure that this attribute change won't affect style.
1022 shouldInvalidateStyle |= !styleResolver;
1024 if (shouldInvalidateStyle)
1025 setNeedsStyleRecalc(SubtreeStyleChange);
1027 if (AXObjectCache* cache = document().existingAXObjectCache())
1028 cache->handleAttributeChanged(name, this);
1031 bool Element::hasLegalLinkAttribute(const QualifiedName&) const
1036 const QualifiedName& Element::subResourceAttributeName() const
1041 inline void Element::attributeChangedFromParserOrByCloning(const QualifiedName& name, const AtomicString& newValue, AttributeModificationReason reason)
1044 CustomElementRegistrationContext::setTypeExtension(this, newValue);
1045 attributeChanged(name, newValue, reason);
1048 template <typename CharacterType>
1049 static inline bool classStringHasClassName(const CharacterType* characters, unsigned length)
1055 if (isNotHTMLSpace<CharacterType>(characters[i]))
1058 } while (i < length);
1063 static inline bool classStringHasClassName(const AtomicString& newClassString)
1065 unsigned length = newClassString.length();
1070 if (newClassString.is8Bit())
1071 return classStringHasClassName(newClassString.characters8(), length);
1072 return classStringHasClassName(newClassString.characters16(), length);
1075 void Element::classAttributeChanged(const AtomicString& newClassString)
1077 StyleResolver* styleResolver = document().styleResolver();
1078 bool testShouldInvalidateStyle = inActiveDocument() && styleResolver && styleChangeType() < SubtreeStyleChange;
1080 ASSERT(elementData());
1081 if (classStringHasClassName(newClassString)) {
1082 const bool shouldFoldCase = document().inQuirksMode();
1083 const SpaceSplitString oldClasses = elementData()->classNames();
1084 elementData()->setClass(newClassString, shouldFoldCase);
1085 const SpaceSplitString& newClasses = elementData()->classNames();
1086 if (testShouldInvalidateStyle)
1087 styleResolver->ensureUpdatedRuleFeatureSet().scheduleStyleInvalidationForClassChange(oldClasses, newClasses, this);
1089 const SpaceSplitString& oldClasses = elementData()->classNames();
1090 if (testShouldInvalidateStyle)
1091 styleResolver->ensureUpdatedRuleFeatureSet().scheduleStyleInvalidationForClassChange(oldClasses, this);
1092 elementData()->clearClass();
1096 elementRareData()->clearClassListValueForQuirksMode();
1099 bool Element::shouldInvalidateDistributionWhenAttributeChanged(ElementShadow* elementShadow, const QualifiedName& name, const AtomicString& newValue)
1101 ASSERT(elementShadow);
1102 const SelectRuleFeatureSet& featureSet = elementShadow->ensureSelectFeatureSet();
1104 if (isIdAttributeName(name)) {
1105 AtomicString oldId = elementData()->idForStyleResolution();
1106 AtomicString newId = makeIdForStyleResolution(newValue, document().inQuirksMode());
1107 if (newId != oldId) {
1108 if (!oldId.isEmpty() && featureSet.hasSelectorForId(oldId))
1110 if (!newId.isEmpty() && featureSet.hasSelectorForId(newId))
1115 if (name == HTMLNames::classAttr) {
1116 const AtomicString& newClassString = newValue;
1117 if (classStringHasClassName(newClassString)) {
1118 const bool shouldFoldCase = document().inQuirksMode();
1119 const SpaceSplitString& oldClasses = elementData()->classNames();
1120 const SpaceSplitString newClasses(newClassString, shouldFoldCase);
1121 if (featureSet.checkSelectorsForClassChange(oldClasses, newClasses))
1124 const SpaceSplitString& oldClasses = elementData()->classNames();
1125 if (featureSet.checkSelectorsForClassChange(oldClasses))
1130 return featureSet.hasSelectorForAttribute(name.localName());
1133 // Returns true is the given attribute is an event handler.
1134 // We consider an event handler any attribute that begins with "on".
1135 // It is a simple solution that has the advantage of not requiring any
1136 // code or configuration change if a new event handler is defined.
1138 static inline bool isEventHandlerAttribute(const Attribute& attribute)
1140 return attribute.name().namespaceURI().isNull() && attribute.name().localName().startsWith("on");
1143 bool Element::isJavaScriptURLAttribute(const Attribute& attribute) const
1145 return isURLAttribute(attribute) && protocolIsJavaScript(stripLeadingAndTrailingHTMLSpaces(attribute.value()));
1148 void Element::stripScriptingAttributes(Vector<Attribute>& attributeVector) const
1150 size_t destination = 0;
1151 for (size_t source = 0; source < attributeVector.size(); ++source) {
1152 if (isEventHandlerAttribute(attributeVector[source])
1153 || isJavaScriptURLAttribute(attributeVector[source])
1154 || isHTMLContentAttribute(attributeVector[source]))
1157 if (source != destination)
1158 attributeVector[destination] = attributeVector[source];
1162 attributeVector.shrink(destination);
1165 void Element::parserSetAttributes(const Vector<Attribute>& attributeVector)
1167 ASSERT(!inDocument());
1168 ASSERT(!parentNode());
1169 ASSERT(!m_elementData);
1171 if (attributeVector.isEmpty())
1174 if (document().elementDataCache())
1175 m_elementData = document().elementDataCache()->cachedShareableElementDataWithAttributes(attributeVector);
1177 m_elementData = ShareableElementData::createWithAttributes(attributeVector);
1179 // Use attributeVector instead of m_elementData because attributeChanged might modify m_elementData.
1180 for (unsigned i = 0; i < attributeVector.size(); ++i)
1181 attributeChangedFromParserOrByCloning(attributeVector[i].name(), attributeVector[i].value(), ModifiedDirectly);
1184 bool Element::hasAttributes() const
1186 synchronizeAllAttributes();
1187 return elementData() && elementData()->length();
1190 bool Element::hasEquivalentAttributes(const Element* other) const
1192 synchronizeAllAttributes();
1193 other->synchronizeAllAttributes();
1194 if (elementData() == other->elementData())
1197 return elementData()->isEquivalent(other->elementData());
1198 if (other->elementData())
1199 return other->elementData()->isEquivalent(elementData());
1203 String Element::nodeName() const
1205 return m_tagName.toString();
1208 void Element::setPrefix(const AtomicString& prefix, ExceptionState& exceptionState)
1210 UseCounter::count(document(), UseCounter::ElementSetPrefix);
1212 if (!prefix.isEmpty() && !Document::isValidName(prefix)) {
1213 exceptionState.throwDOMException(InvalidCharacterError, "The prefix '" + prefix + "' is not a valid name.");
1217 // FIXME: Raise NamespaceError if prefix is malformed per the Namespaces in XML specification.
1219 const AtomicString& nodeNamespaceURI = namespaceURI();
1220 if (nodeNamespaceURI.isEmpty() && !prefix.isEmpty()) {
1221 exceptionState.throwDOMException(NamespaceError, "No namespace is set, so a namespace prefix may not be set.");
1225 if (prefix == xmlAtom && nodeNamespaceURI != XMLNames::xmlNamespaceURI) {
1226 exceptionState.throwDOMException(NamespaceError, "The prefix '" + xmlAtom + "' may not be set on namespace '" + nodeNamespaceURI + "'.");
1230 if (exceptionState.hadException())
1233 m_tagName.setPrefix(prefix.isEmpty() ? AtomicString() : prefix);
1236 const AtomicString& Element::locateNamespacePrefix(const AtomicString& namespaceToLocate) const
1238 if (!prefix().isNull() && namespaceURI() == namespaceToLocate)
1241 if (hasAttributes()) {
1242 unsigned attributeCount = this->attributeCount();
1243 for (unsigned i = 0; i < attributeCount; ++i) {
1244 const Attribute& attr = attributeItem(i);
1246 if (attr.prefix() == xmlnsAtom && attr.value() == namespaceToLocate)
1247 return attr.localName();
1251 if (Element* parent = parentElement())
1252 return parent->locateNamespacePrefix(namespaceToLocate);
1257 KURL Element::baseURI() const
1259 const AtomicString& baseAttribute = fastGetAttribute(baseAttr);
1260 KURL base(KURL(), baseAttribute);
1261 if (!base.protocol().isEmpty())
1264 ContainerNode* parent = parentNode();
1268 const KURL& parentBase = parent->baseURI();
1269 if (parentBase.isNull())
1272 return KURL(parentBase, baseAttribute);
1275 const AtomicString Element::imageSourceURL() const
1277 return getAttribute(srcAttr);
1280 bool Element::rendererIsNeeded(const RenderStyle& style)
1282 return style.display() != NONE;
1285 RenderObject* Element::createRenderer(RenderStyle* style)
1287 return RenderObject::createObject(this, style);
1290 Node::InsertionNotificationRequest Element::insertedInto(ContainerNode* insertionPoint)
1292 // need to do superclass processing first so inDocument() is true
1293 // by the time we reach updateId
1294 ContainerNode::insertedInto(insertionPoint);
1296 if (containsFullScreenElement() && parentElement() && !parentElement()->containsFullScreenElement())
1297 setContainsFullScreenElementOnAncestorsCrossingFrameBoundaries(true);
1299 ASSERT(!hasRareData() || !elementRareData()->hasPseudoElements());
1301 if (!insertionPoint->isInTreeScope())
1302 return InsertionDone;
1305 elementRareData()->clearClassListValueForQuirksMode();
1307 if (isUpgradedCustomElement() && inDocument())
1308 CustomElement::didEnterDocument(this, document());
1310 TreeScope& scope = insertionPoint->treeScope();
1311 if (scope != treeScope())
1312 return InsertionDone;
1314 const AtomicString& idValue = getIdAttribute();
1315 if (!idValue.isNull())
1316 updateId(scope, nullAtom, idValue);
1318 const AtomicString& nameValue = getNameAttribute();
1319 if (!nameValue.isNull())
1320 updateName(nullAtom, nameValue);
1322 if (isHTMLLabelElement(*this)) {
1323 if (scope.shouldCacheLabelsByForAttribute())
1324 updateLabel(scope, nullAtom, fastGetAttribute(forAttr));
1327 if (parentElement() && parentElement()->isInCanvasSubtree())
1328 setIsInCanvasSubtree(true);
1330 return InsertionDone;
1333 void Element::removedFrom(ContainerNode* insertionPoint)
1335 bool wasInDocument = insertionPoint->inDocument();
1337 ASSERT(!hasRareData() || !elementRareData()->hasPseudoElements());
1339 if (containsFullScreenElement())
1340 setContainsFullScreenElementOnAncestorsCrossingFrameBoundaries(false);
1342 if (document().page())
1343 document().page()->pointerLockController().elementRemoved(this);
1345 setSavedLayerScrollOffset(IntSize());
1347 if (insertionPoint->isInTreeScope() && treeScope() == document()) {
1348 const AtomicString& idValue = getIdAttribute();
1349 if (!idValue.isNull())
1350 updateId(insertionPoint->treeScope(), idValue, nullAtom);
1352 const AtomicString& nameValue = getNameAttribute();
1353 if (!nameValue.isNull())
1354 updateName(nameValue, nullAtom);
1356 if (isHTMLLabelElement(*this)) {
1357 TreeScope& treeScope = insertionPoint->treeScope();
1358 if (treeScope.shouldCacheLabelsByForAttribute())
1359 updateLabel(treeScope, fastGetAttribute(forAttr), nullAtom);
1363 ContainerNode::removedFrom(insertionPoint);
1364 if (wasInDocument) {
1365 if (hasPendingResources())
1366 document().accessSVGExtensions().removeElementFromPendingResources(this);
1368 if (isUpgradedCustomElement())
1369 CustomElement::didLeaveDocument(this, insertionPoint->document());
1372 document().removeFromTopLayer(this);
1374 clearElementFlag(IsInCanvasSubtree);
1377 void Element::attach(const AttachContext& context)
1379 ASSERT(document().inStyleRecalc());
1381 // We've already been through detach when doing an attach, but we might
1382 // need to clear any state that's been added since then.
1383 if (hasRareData() && styleChangeType() == NeedsReattachStyleChange) {
1384 ElementRareData* data = elementRareData();
1385 data->clearComputedStyle();
1386 data->clearRestyleFlags();
1387 // Only clear the style state if we're not going to reuse the style from recalcStyle.
1388 if (!context.resolvedStyle)
1389 data->resetStyleState();
1392 RenderTreeBuilder(this, context.resolvedStyle).createRendererForElementIfNeeded();
1394 addCallbackSelectors();
1396 StyleResolverParentScope parentScope(*this);
1398 createPseudoElementIfNeeded(BEFORE);
1400 // When a shadow root exists, it does the work of attaching the children.
1401 if (ElementShadow* shadow = this->shadow())
1402 shadow->attach(context);
1404 ContainerNode::attach(context);
1406 createPseudoElementIfNeeded(AFTER);
1407 createPseudoElementIfNeeded(BACKDROP);
1409 if (hasRareData()) {
1410 ElementRareData* data = elementRareData();
1411 if (data->hasElementFlag(NeedsFocusAppearanceUpdateSoonAfterAttach)) {
1412 if (isFocusable() && document().focusedElement() == this)
1413 document().updateFocusAppearanceSoon(false /* don't restore selection */);
1414 data->clearElementFlag(NeedsFocusAppearanceUpdateSoonAfterAttach);
1417 if (ActiveAnimations* activeAnimations = data->activeAnimations()) {
1418 activeAnimations->cssAnimations().cancel();
1419 activeAnimations->setAnimationStyleChange(false);
1424 InspectorInstrumentation::didRecalculateStyleForElement(this);
1427 void Element::detach(const AttachContext& context)
1429 RenderWidget::UpdateSuspendScope suspendWidgetHierarchyUpdates;
1430 cancelFocusAppearanceUpdate();
1431 removeCallbackSelectors();
1432 if (needsLayerUpdate())
1433 document().unscheduleLayerUpdate(*this);
1434 if (hasRareData()) {
1435 ElementRareData* data = elementRareData();
1436 data->clearPseudoElements();
1438 // attach() will perform the below steps for us when inside recalcStyle.
1439 if (!document().inStyleRecalc()) {
1440 data->resetStyleState();
1441 data->clearComputedStyle();
1442 data->clearRestyleFlags();
1445 if (ActiveAnimations* activeAnimations = data->activeAnimations()) {
1446 if (context.performingReattach) {
1447 // FIXME: We call detach from withing style recalc, so compositingState is not up to date.
1448 // https://code.google.com/p/chromium/issues/detail?id=339847
1449 DisableCompositingQueryAsserts disabler;
1451 // FIXME: restart compositor animations rather than pull back to the main thread
1452 activeAnimations->cancelAnimationOnCompositor();
1454 activeAnimations->cssAnimations().cancel();
1455 activeAnimations->setAnimationStyleChange(false);
1459 if (ElementShadow* shadow = data->shadow())
1460 shadow->detach(context);
1462 ContainerNode::detach(context);
1465 bool Element::pseudoStyleCacheIsInvalid(const RenderStyle* currentStyle, RenderStyle* newStyle)
1467 ASSERT(currentStyle == renderStyle());
1473 const PseudoStyleCache* pseudoStyleCache = currentStyle->cachedPseudoStyles();
1474 if (!pseudoStyleCache)
1477 size_t cacheSize = pseudoStyleCache->size();
1478 for (size_t i = 0; i < cacheSize; ++i) {
1479 RefPtr<RenderStyle> newPseudoStyle;
1480 PseudoId pseudoId = pseudoStyleCache->at(i)->styleType();
1481 if (pseudoId == FIRST_LINE || pseudoId == FIRST_LINE_INHERITED)
1482 newPseudoStyle = renderer()->uncachedFirstLineStyle(newStyle);
1484 newPseudoStyle = renderer()->getUncachedPseudoStyle(PseudoStyleRequest(pseudoId), newStyle, newStyle);
1485 if (!newPseudoStyle)
1487 if (*newPseudoStyle != *pseudoStyleCache->at(i)) {
1488 if (pseudoId < FIRST_INTERNAL_PSEUDOID)
1489 newStyle->setHasPseudoStyle(pseudoId);
1490 newStyle->addCachedPseudoStyle(newPseudoStyle);
1491 if (pseudoId == FIRST_LINE || pseudoId == FIRST_LINE_INHERITED) {
1492 // FIXME: We should do an actual diff to determine whether a repaint vs. layout
1493 // is needed, but for now just assume a layout will be required. The diff code
1494 // in RenderObject::setStyle would need to be factored out so that it could be reused.
1495 renderer()->setNeedsLayoutAndPrefWidthsRecalc();
1503 PassRefPtr<RenderStyle> Element::styleForRenderer()
1505 ASSERT(document().inStyleRecalc());
1507 RefPtr<RenderStyle> style;
1509 // FIXME: Instead of clearing updates that may have been added from calls to styleForElement
1510 // outside recalcStyle, we should just never set them if we're not inside recalcStyle.
1511 if (ActiveAnimations* activeAnimations = this->activeAnimations())
1512 activeAnimations->cssAnimations().setPendingUpdate(nullptr);
1514 if (hasCustomStyleCallbacks())
1515 style = customStyleForRenderer();
1517 style = originalStyleForRenderer();
1519 // styleForElement() might add active animations so we need to get it again.
1520 if (ActiveAnimations* activeAnimations = this->activeAnimations())
1521 activeAnimations->cssAnimations().maybeApplyPendingUpdate(this);
1524 return style.release();
1527 PassRefPtr<RenderStyle> Element::originalStyleForRenderer()
1529 ASSERT(document().inStyleRecalc());
1530 return document().ensureStyleResolver().styleForElement(this);
1533 void Element::recalcStyle(StyleRecalcChange change, Text* nextTextSibling)
1535 ASSERT(document().inStyleRecalc());
1536 ASSERT(!parentOrShadowHostNode()->needsStyleRecalc());
1538 if (hasCustomStyleCallbacks())
1539 willRecalcStyle(change);
1541 if (change >= Inherit || needsStyleRecalc()) {
1542 if (hasRareData()) {
1543 ElementRareData* data = elementRareData();
1544 data->resetStyleState();
1545 data->clearComputedStyle();
1547 if (change >= Inherit) {
1548 if (ActiveAnimations* activeAnimations = data->activeAnimations())
1549 activeAnimations->setAnimationStyleChange(false);
1552 if (parentRenderStyle())
1553 change = recalcOwnStyle(change);
1554 clearNeedsStyleRecalc();
1557 // If we reattached we don't need to recalc the style of our descendants anymore.
1558 if ((change >= UpdatePseudoElements && change < Reattach) || childNeedsStyleRecalc()) {
1559 recalcChildStyle(change);
1560 clearChildNeedsStyleRecalc();
1563 if (hasCustomStyleCallbacks())
1564 didRecalcStyle(change);
1566 if (change == Reattach)
1567 reattachWhitespaceSiblings(nextTextSibling);
1570 StyleRecalcChange Element::recalcOwnStyle(StyleRecalcChange change)
1572 ASSERT(document().inStyleRecalc());
1573 ASSERT(!parentOrShadowHostNode()->needsStyleRecalc());
1574 ASSERT(change >= Inherit || needsStyleRecalc());
1575 ASSERT(parentRenderStyle());
1577 RefPtr<RenderStyle> oldStyle = renderStyle();
1578 RefPtr<RenderStyle> newStyle = styleForRenderer();
1579 StyleRecalcChange localChange = RenderStyle::stylePropagationDiff(oldStyle.get(), newStyle.get());
1583 if (localChange == Reattach) {
1584 AttachContext reattachContext;
1585 reattachContext.resolvedStyle = newStyle.get();
1586 bool rendererWillChange = needsAttach() || renderer();
1587 reattach(reattachContext);
1588 if (rendererWillChange || renderer())
1590 return ReattachNoRenderer;
1595 InspectorInstrumentation::didRecalculateStyleForElement(this);
1597 if (localChange != NoChange)
1598 updateCallbackSelectors(oldStyle.get(), newStyle.get());
1600 if (RenderObject* renderer = this->renderer()) {
1601 if (localChange != NoChange || pseudoStyleCacheIsInvalid(oldStyle.get(), newStyle.get()) || needsLayerUpdate()) {
1602 renderer->setStyle(newStyle.get());
1604 // Although no change occurred, we use the new style so that the cousin style sharing code won't get
1605 // fooled into believing this style is the same.
1606 // FIXME: We may be able to remove this hack, see discussion in
1607 // https://codereview.chromium.org/30453002/
1608 renderer->setStyleInternal(newStyle.get());
1612 if (styleChangeType() >= SubtreeStyleChange)
1615 if (change > Inherit || localChange > Inherit)
1616 return max(localChange, change);
1618 if (localChange < Inherit && (oldStyle->hasPseudoElementStyle() || newStyle->hasPseudoElementStyle()))
1619 return UpdatePseudoElements;
1624 void Element::recalcChildStyle(StyleRecalcChange change)
1626 ASSERT(document().inStyleRecalc());
1627 ASSERT(change >= UpdatePseudoElements || childNeedsStyleRecalc());
1628 ASSERT(!needsStyleRecalc());
1630 StyleResolverParentScope parentScope(*this);
1632 updatePseudoElement(BEFORE, change);
1634 if (change > UpdatePseudoElements || childNeedsStyleRecalc()) {
1635 for (ShadowRoot* root = youngestShadowRoot(); root; root = root->olderShadowRoot()) {
1636 if (root->shouldCallRecalcStyle(change))
1637 root->recalcStyle(change);
1641 if (change < Force && hasRareData() && childNeedsStyleRecalc())
1642 checkForChildrenAdjacentRuleChanges();
1644 if (change > UpdatePseudoElements || childNeedsStyleRecalc()) {
1645 // This loop is deliberately backwards because we use insertBefore in the rendering tree, and want to avoid
1646 // a potentially n^2 loop to find the insertion point while resolving style. Having us start from the last
1647 // child and work our way back means in the common case, we'll find the insertion point in O(1) time.
1648 // See crbug.com/288225
1649 StyleResolver& styleResolver = document().ensureStyleResolver();
1650 Text* lastTextNode = 0;
1651 for (Node* child = lastChild(); child; child = child->previousSibling()) {
1652 if (child->isTextNode()) {
1653 toText(child)->recalcTextStyle(change, lastTextNode);
1654 lastTextNode = toText(child);
1655 } else if (child->isElementNode()) {
1656 Element* element = toElement(child);
1657 if (element->shouldCallRecalcStyle(change))
1658 element->recalcStyle(change, lastTextNode);
1659 else if (element->supportsStyleSharing())
1660 styleResolver.addToStyleSharingList(*element);
1661 if (element->renderer())
1667 updatePseudoElement(AFTER, change);
1668 updatePseudoElement(BACKDROP, change);
1671 void Element::updateCallbackSelectors(RenderStyle* oldStyle, RenderStyle* newStyle)
1673 Vector<String> emptyVector;
1674 const Vector<String>& oldCallbackSelectors = oldStyle ? oldStyle->callbackSelectors() : emptyVector;
1675 const Vector<String>& newCallbackSelectors = newStyle ? newStyle->callbackSelectors() : emptyVector;
1676 if (oldCallbackSelectors.isEmpty() && newCallbackSelectors.isEmpty())
1678 if (oldCallbackSelectors != newCallbackSelectors)
1679 CSSSelectorWatch::from(document()).updateSelectorMatches(oldCallbackSelectors, newCallbackSelectors);
1682 void Element::addCallbackSelectors()
1684 updateCallbackSelectors(0, renderStyle());
1687 void Element::removeCallbackSelectors()
1689 updateCallbackSelectors(renderStyle(), 0);
1692 ElementShadow* Element::shadow() const
1694 return hasRareData() ? elementRareData()->shadow() : 0;
1697 ElementShadow& Element::ensureShadow()
1699 return ensureElementRareData().ensureShadow();
1702 void Element::didAffectSelector(AffectedSelectorMask mask)
1704 setNeedsStyleRecalc(SubtreeStyleChange);
1705 if (ElementShadow* elementShadow = shadowWhereNodeCanBeDistributed(*this))
1706 elementShadow->didAffectSelector(mask);
1709 void Element::setAnimationStyleChange(bool animationStyleChange)
1711 if (ActiveAnimations* activeAnimations = elementRareData()->activeAnimations())
1712 activeAnimations->setAnimationStyleChange(animationStyleChange);
1715 void Element::setNeedsAnimationStyleRecalc()
1717 if (styleChangeType() != NoStyleChange)
1720 setNeedsStyleRecalc(LocalStyleChange);
1721 setAnimationStyleChange(true);
1724 void Element::setCustomElementDefinition(PassRefPtr<CustomElementDefinition> definition)
1726 if (!hasRareData() && !definition)
1728 ASSERT(!customElementDefinition());
1729 ensureElementRareData().setCustomElementDefinition(definition);
1732 CustomElementDefinition* Element::customElementDefinition() const
1735 return elementRareData()->customElementDefinition();
1739 PassRefPtr<ShadowRoot> Element::createShadowRoot(ExceptionState& exceptionState)
1741 if (alwaysCreateUserAgentShadowRoot())
1742 ensureUserAgentShadowRoot();
1744 // Some elements make assumptions about what kind of renderers they allow
1745 // as children so we can't allow author shadows on them for now. An override
1746 // flag is provided for testing how author shadows interact on these elements.
1747 if (!areAuthorShadowsAllowed() && !RuntimeEnabledFeatures::authorShadowDOMForAnyElementEnabled()) {
1748 exceptionState.throwDOMException(HierarchyRequestError, "Author-created shadow roots are disabled for this element.");
1752 return PassRefPtr<ShadowRoot>(ensureShadow().addShadowRoot(*this, ShadowRoot::AuthorShadowRoot));
1755 ShadowRoot* Element::shadowRoot() const
1757 ElementShadow* elementShadow = shadow();
1760 ShadowRoot* shadowRoot = elementShadow->youngestShadowRoot();
1761 if (shadowRoot->type() == ShadowRoot::AuthorShadowRoot)
1766 void Element::didAddShadowRoot(ShadowRoot&)
1770 ShadowRoot* Element::userAgentShadowRoot() const
1772 if (ElementShadow* elementShadow = shadow()) {
1773 if (ShadowRoot* shadowRoot = elementShadow->oldestShadowRoot()) {
1774 ASSERT(shadowRoot->type() == ShadowRoot::UserAgentShadowRoot);
1782 ShadowRoot& Element::ensureUserAgentShadowRoot()
1784 if (ShadowRoot* shadowRoot = userAgentShadowRoot())
1786 ShadowRoot& shadowRoot = ensureShadow().addShadowRoot(*this, ShadowRoot::UserAgentShadowRoot);
1787 didAddUserAgentShadowRoot(shadowRoot);
1791 bool Element::childTypeAllowed(NodeType type) const
1797 case PROCESSING_INSTRUCTION_NODE:
1798 case CDATA_SECTION_NODE:
1806 void Element::checkForEmptyStyleChange(RenderStyle* style)
1808 if (!style && !styleAffectedByEmpty())
1811 if (!style || (styleAffectedByEmpty() && (!style->emptyState() || hasChildren())))
1812 setNeedsStyleRecalc(SubtreeStyleChange);
1815 void Element::checkForSiblingStyleChanges(bool finishedParsingCallback, Node* beforeChange, Node* afterChange, int childCountDelta)
1817 if (!inActiveDocument() || document().hasPendingForcedStyleRecalc() || styleChangeType() >= SubtreeStyleChange)
1820 RenderStyle* style = renderStyle();
1823 checkForEmptyStyleChange(style);
1825 if (!style || (needsStyleRecalc() && childrenAffectedByPositionalRules()))
1828 // Forward positional selectors include nth-child, nth-of-type, first-of-type and only-of-type.
1829 // The indirect adjacent selector is the ~ selector.
1830 // Backward positional selectors include nth-last-child, nth-last-of-type, last-of-type and only-of-type.
1831 // We have to invalidate everything following the insertion point in the forward and indirect adjacent case,
1832 // and everything before the insertion point in the backward case.
1833 // |afterChange| is 0 in the parser callback case, so we won't do any work for the forward case if we don't have to.
1834 // For performance reasons we just mark the parent node as changed, since we don't want to make childrenChanged O(n^2) by crawling all our kids
1835 // here. recalcStyle will then force a walk of the children when it sees that this has happened.
1836 if (((childrenAffectedByForwardPositionalRules() || childrenAffectedByIndirectAdjacentRules()) && afterChange)
1837 || (childrenAffectedByBackwardPositionalRules() && beforeChange)) {
1838 setNeedsStyleRecalc(SubtreeStyleChange);
1842 // :first-child. In the parser callback case, we don't have to check anything, since we were right the first time.
1843 // In the DOM case, we only need to do something if |afterChange| is not 0.
1844 // |afterChange| is 0 in the parser case, so it works out that we'll skip this block.
1845 if (childrenAffectedByFirstChildRules() && afterChange) {
1846 // Find our new first child.
1847 Element* newFirstChild = ElementTraversal::firstWithin(*this);
1848 RenderStyle* newFirstChildStyle = newFirstChild ? newFirstChild->renderStyle() : 0;
1850 // Find the first element node following |afterChange|
1851 Node* firstElementAfterInsertion = afterChange->isElementNode() ? afterChange : ElementTraversal::nextSibling(*afterChange);
1852 RenderStyle* firstElementAfterInsertionStyle = firstElementAfterInsertion ? firstElementAfterInsertion->renderStyle() : 0;
1854 // This is the insert/append case.
1855 if (newFirstChild != firstElementAfterInsertion && firstElementAfterInsertionStyle && firstElementAfterInsertionStyle->firstChildState())
1856 firstElementAfterInsertion->setNeedsStyleRecalc(SubtreeStyleChange);
1858 // We also have to handle node removal.
1859 if (childCountDelta < 0 && newFirstChild == firstElementAfterInsertion && newFirstChild && (!newFirstChildStyle || !newFirstChildStyle->firstChildState()))
1860 newFirstChild->setNeedsStyleRecalc(SubtreeStyleChange);
1863 // :last-child. In the parser callback case, we don't have to check anything, since we were right the first time.
1864 // In the DOM case, we only need to do something if |afterChange| is not 0.
1865 if (childrenAffectedByLastChildRules() && beforeChange) {
1866 // Find our new last child.
1867 Node* newLastChild = ElementTraversal::lastWithin(*this);
1868 RenderStyle* newLastChildStyle = newLastChild ? newLastChild->renderStyle() : 0;
1870 // Find the last element node going backwards from |beforeChange|
1871 Node* lastElementBeforeInsertion = beforeChange->isElementNode() ? beforeChange : ElementTraversal::previousSibling(*beforeChange);
1872 RenderStyle* lastElementBeforeInsertionStyle = lastElementBeforeInsertion ? lastElementBeforeInsertion->renderStyle() : 0;
1874 if (newLastChild != lastElementBeforeInsertion && lastElementBeforeInsertionStyle && lastElementBeforeInsertionStyle->lastChildState())
1875 lastElementBeforeInsertion->setNeedsStyleRecalc(SubtreeStyleChange);
1877 // We also have to handle node removal. The parser callback case is similar to node removal as well in that we need to change the last child
1879 if ((childCountDelta < 0 || finishedParsingCallback) && newLastChild == lastElementBeforeInsertion && newLastChild && (!newLastChildStyle || !newLastChildStyle->lastChildState()))
1880 newLastChild->setNeedsStyleRecalc(SubtreeStyleChange);
1883 // The + selector. We need to invalidate the first element following the insertion point. It is the only possible element
1884 // that could be affected by this DOM change.
1885 if (childrenAffectedByDirectAdjacentRules() && afterChange) {
1886 if (Node* firstElementAfterInsertion = afterChange->isElementNode() ? afterChange : ElementTraversal::nextSibling(*afterChange))
1887 firstElementAfterInsertion->setNeedsStyleRecalc(SubtreeStyleChange);
1891 void Element::childrenChanged(bool changedByParser, Node* beforeChange, Node* afterChange, int childCountDelta)
1893 ContainerNode::childrenChanged(changedByParser, beforeChange, afterChange, childCountDelta);
1894 if (changedByParser)
1895 checkForEmptyStyleChange(renderStyle());
1897 checkForSiblingStyleChanges(false, beforeChange, afterChange, childCountDelta);
1899 if (ElementShadow* shadow = this->shadow())
1900 shadow->setNeedsDistributionRecalc();
1903 void Element::removeAllEventListeners()
1905 ContainerNode::removeAllEventListeners();
1906 if (ElementShadow* shadow = this->shadow())
1907 shadow->removeAllEventListeners();
1910 void Element::finishParsingChildren()
1912 setIsFinishedParsingChildren(true);
1913 checkForSiblingStyleChanges(this, lastChild(), 0, 0);
1917 void Element::formatForDebugger(char* buffer, unsigned length) const
1919 StringBuilder result;
1922 result.append(nodeName());
1924 s = getIdAttribute();
1925 if (s.length() > 0) {
1926 if (result.length() > 0)
1927 result.appendLiteral("; ");
1928 result.appendLiteral("id=");
1932 s = getAttribute(classAttr);
1933 if (s.length() > 0) {
1934 if (result.length() > 0)
1935 result.appendLiteral("; ");
1936 result.appendLiteral("class=");
1940 strncpy(buffer, result.toString().utf8().data(), length - 1);
1944 const Vector<RefPtr<Attr> >& Element::attrNodeList()
1946 ASSERT(hasSyntheticAttrChildNodes());
1947 return *attrNodeListForElement(this);
1950 PassRefPtr<Attr> Element::setAttributeNode(Attr* attrNode, ExceptionState& exceptionState)
1953 exceptionState.throwDOMException(TypeMismatchError, ExceptionMessages::argumentNullOrIncorrectType(1, "Attr"));
1957 RefPtr<Attr> oldAttrNode = attrIfExists(attrNode->qualifiedName());
1958 if (oldAttrNode.get() == attrNode)
1959 return attrNode; // This Attr is already attached to the element.
1961 // InUseAttributeError: Raised if node is an Attr that is already an attribute of another Element object.
1962 // The DOM user must explicitly clone Attr nodes to re-use them in other elements.
1963 if (attrNode->ownerElement()) {
1964 exceptionState.throwDOMException(InUseAttributeError, "The node provided is an attribute node that is already an attribute of another Element; attribute nodes must be explicitly cloned.");
1968 synchronizeAllAttributes();
1969 UniqueElementData& elementData = ensureUniqueElementData();
1971 size_t index = elementData.getAttributeItemIndex(attrNode->qualifiedName(), shouldIgnoreAttributeCase());
1972 if (index != kNotFound) {
1974 detachAttrNodeFromElementWithValue(oldAttrNode.get(), elementData.attributeItem(index).value());
1976 oldAttrNode = Attr::create(document(), attrNode->qualifiedName(), elementData.attributeItem(index).value());
1979 setAttributeInternal(index, attrNode->qualifiedName(), attrNode->value(), NotInSynchronizationOfLazyAttribute);
1981 attrNode->attachToElement(this);
1982 treeScope().adoptIfNeeded(*attrNode);
1983 ensureAttrNodeListForElement(this).append(attrNode);
1985 return oldAttrNode.release();
1988 PassRefPtr<Attr> Element::removeAttributeNode(Attr* attr, ExceptionState& exceptionState)
1991 exceptionState.throwDOMException(TypeMismatchError, ExceptionMessages::argumentNullOrIncorrectType(1, "Attr"));
1994 if (attr->ownerElement() != this) {
1995 exceptionState.throwDOMException(NotFoundError, "The node provided is owned by another element.");
1999 ASSERT(document() == attr->document());
2001 synchronizeAttribute(attr->qualifiedName());
2003 size_t index = elementData()->getAttrIndex(attr);
2004 if (index == kNotFound) {
2005 exceptionState.throwDOMException(NotFoundError, "The attribute was not found on this element.");
2009 RefPtr<Attr> guard(attr);
2010 detachAttrNodeAtIndex(attr, index);
2011 return guard.release();
2014 bool Element::parseAttributeName(QualifiedName& out, const AtomicString& namespaceURI, const AtomicString& qualifiedName, ExceptionState& exceptionState)
2016 AtomicString prefix, localName;
2017 if (!Document::parseQualifiedName(qualifiedName, prefix, localName, exceptionState))
2019 ASSERT(!exceptionState.hadException());
2021 QualifiedName qName(prefix, localName, namespaceURI);
2023 if (!Document::hasValidNamespaceForAttributes(qName)) {
2024 exceptionState.throwDOMException(NamespaceError, "'" + namespaceURI + "' is an invalid namespace for attributes.");
2032 void Element::setAttributeNS(const AtomicString& namespaceURI, const AtomicString& qualifiedName, const AtomicString& value, ExceptionState& exceptionState)
2034 QualifiedName parsedName = anyName;
2035 if (!parseAttributeName(parsedName, namespaceURI, qualifiedName, exceptionState))
2037 setAttribute(parsedName, value);
2040 void Element::removeAttributeInternal(size_t index, SynchronizationOfLazyAttribute inSynchronizationOfLazyAttribute)
2042 ASSERT_WITH_SECURITY_IMPLICATION(index < attributeCount());
2044 UniqueElementData& elementData = ensureUniqueElementData();
2046 QualifiedName name = elementData.attributeItem(index).name();
2047 AtomicString valueBeingRemoved = elementData.attributeItem(index).value();
2049 if (!inSynchronizationOfLazyAttribute) {
2050 if (!valueBeingRemoved.isNull())
2051 willModifyAttribute(name, valueBeingRemoved, nullAtom);
2054 if (RefPtr<Attr> attrNode = attrIfExists(name))
2055 detachAttrNodeFromElementWithValue(attrNode.get(), elementData.attributeItem(index).value());
2057 elementData.removeAttribute(index);
2059 if (!inSynchronizationOfLazyAttribute)
2060 didRemoveAttribute(name);
2063 void Element::addAttributeInternal(const QualifiedName& name, const AtomicString& value, SynchronizationOfLazyAttribute inSynchronizationOfLazyAttribute)
2065 if (!inSynchronizationOfLazyAttribute)
2066 willModifyAttribute(name, nullAtom, value);
2067 ensureUniqueElementData().addAttribute(name, value);
2068 if (!inSynchronizationOfLazyAttribute)
2069 didAddAttribute(name, value);
2072 void Element::removeAttribute(const AtomicString& name)
2077 AtomicString localName = shouldIgnoreAttributeCase() ? name.lower() : name;
2078 size_t index = elementData()->getAttributeItemIndex(localName, false);
2079 if (index == kNotFound) {
2080 if (UNLIKELY(localName == styleAttr) && elementData()->m_styleAttributeIsDirty && isStyledElement())
2081 removeAllInlineStyleProperties();
2085 removeAttributeInternal(index, NotInSynchronizationOfLazyAttribute);
2088 void Element::removeAttributeNS(const AtomicString& namespaceURI, const AtomicString& localName)
2090 removeAttribute(QualifiedName(nullAtom, localName, namespaceURI));
2093 PassRefPtr<Attr> Element::getAttributeNode(const AtomicString& localName)
2097 synchronizeAttribute(localName);
2098 const Attribute* attribute = elementData()->getAttributeItem(localName, shouldIgnoreAttributeCase());
2101 return ensureAttr(attribute->name());
2104 PassRefPtr<Attr> Element::getAttributeNodeNS(const AtomicString& namespaceURI, const AtomicString& localName)
2108 QualifiedName qName(nullAtom, localName, namespaceURI);
2109 synchronizeAttribute(qName);
2110 const Attribute* attribute = elementData()->getAttributeItem(qName);
2113 return ensureAttr(attribute->name());
2116 bool Element::hasAttribute(const AtomicString& localName) const
2120 synchronizeAttribute(localName);
2121 return elementData()->getAttributeItem(shouldIgnoreAttributeCase() ? localName.lower() : localName, false);
2124 bool Element::hasAttributeNS(const AtomicString& namespaceURI, const AtomicString& localName) const
2128 QualifiedName qName(nullAtom, localName, namespaceURI);
2129 synchronizeAttribute(qName);
2130 return elementData()->getAttributeItem(qName);
2133 void Element::focus(bool restorePreviousSelection, FocusType type)
2138 Document& doc = document();
2139 if (doc.focusedElement() == this)
2142 // If the stylesheets have already been loaded we can reliably check isFocusable.
2143 // If not, we continue and set the focused node on the focus controller below so
2144 // that it can be updated soon after attach.
2145 if (doc.haveStylesheetsLoaded()) {
2146 doc.updateLayoutIgnorePendingStylesheets();
2151 if (!supportsFocus())
2154 RefPtr<Node> protect;
2155 if (Page* page = doc.page()) {
2156 // Focus and change event handlers can cause us to lose our last ref.
2157 // If a focus event handler changes the focus to a different node it
2158 // does not make sense to continue and update appearence.
2160 if (!page->focusController().setFocusedElement(this, doc.frame(), type))
2164 // Setting the focused node above might have invalidated the layout due to scripts.
2165 doc.updateLayoutIgnorePendingStylesheets();
2167 if (!isFocusable()) {
2168 setElementFlag(NeedsFocusAppearanceUpdateSoonAfterAttach);
2172 cancelFocusAppearanceUpdate();
2173 updateFocusAppearance(restorePreviousSelection);
2176 void Element::updateFocusAppearance(bool /*restorePreviousSelection*/)
2178 if (isRootEditableElement()) {
2179 LocalFrame* frame = document().frame();
2183 // When focusing an editable element in an iframe, don't reset the selection if it already contains a selection.
2184 if (this == frame->selection().rootEditableElement())
2187 // FIXME: We should restore the previous selection if there is one.
2188 VisibleSelection newSelection = VisibleSelection(firstPositionInOrBeforeNode(this), DOWNSTREAM);
2189 frame->selection().setSelection(newSelection);
2190 frame->selection().revealSelection();
2191 } else if (renderer() && !renderer()->isWidget())
2192 renderer()->scrollRectToVisible(boundingBox());
2195 void Element::blur()
2197 cancelFocusAppearanceUpdate();
2198 if (treeScope().adjustedFocusedElement() == this) {
2199 Document& doc = document();
2201 doc.page()->focusController().setFocusedElement(0, doc.frame());
2203 doc.setFocusedElement(nullptr);
2207 bool Element::isFocusable() const
2209 return inDocument() && supportsFocus() && !isInert() && rendererIsFocusable();
2212 bool Element::isKeyboardFocusable() const
2214 return isFocusable() && tabIndex() >= 0;
2217 bool Element::isMouseFocusable() const
2219 return isFocusable();
2222 void Element::dispatchFocusEvent(Element* oldFocusedElement, FocusType)
2224 RefPtr<FocusEvent> event = FocusEvent::create(EventTypeNames::focus, false, false, document().domWindow(), 0, oldFocusedElement);
2225 EventDispatcher::dispatchEvent(this, FocusEventDispatchMediator::create(event.release()));
2228 void Element::dispatchBlurEvent(Element* newFocusedElement)
2230 RefPtr<FocusEvent> event = FocusEvent::create(EventTypeNames::blur, false, false, document().domWindow(), 0, newFocusedElement);
2231 EventDispatcher::dispatchEvent(this, BlurEventDispatchMediator::create(event.release()));
2234 void Element::dispatchFocusInEvent(const AtomicString& eventType, Element* oldFocusedElement)
2236 ASSERT(!NoEventDispatchAssertion::isEventDispatchForbidden());
2237 ASSERT(eventType == EventTypeNames::focusin || eventType == EventTypeNames::DOMFocusIn);
2238 dispatchScopedEventDispatchMediator(FocusInEventDispatchMediator::create(FocusEvent::create(eventType, true, false, document().domWindow(), 0, oldFocusedElement)));
2241 void Element::dispatchFocusOutEvent(const AtomicString& eventType, Element* newFocusedElement)
2243 ASSERT(!NoEventDispatchAssertion::isEventDispatchForbidden());
2244 ASSERT(eventType == EventTypeNames::focusout || eventType == EventTypeNames::DOMFocusOut);
2245 dispatchScopedEventDispatchMediator(FocusOutEventDispatchMediator::create(FocusEvent::create(eventType, true, false, document().domWindow(), 0, newFocusedElement)));
2248 String Element::innerHTML() const
2250 return createMarkup(this, ChildrenOnly);
2253 String Element::outerHTML() const
2255 return createMarkup(this);
2258 void Element::setInnerHTML(const String& html, ExceptionState& exceptionState)
2260 if (RefPtr<DocumentFragment> fragment = createFragmentForInnerOuterHTML(html, this, AllowScriptingContent, "innerHTML", exceptionState)) {
2261 ContainerNode* container = this;
2262 if (isHTMLTemplateElement(*this))
2263 container = toHTMLTemplateElement(this)->content();
2264 replaceChildrenWithFragment(container, fragment.release(), exceptionState);
2268 void Element::setOuterHTML(const String& html, ExceptionState& exceptionState)
2270 Node* p = parentNode();
2272 exceptionState.throwDOMException(NoModificationAllowedError, "This element has no parent node.");
2275 if (!p->isElementNode()) {
2276 exceptionState.throwDOMException(NoModificationAllowedError, "This element's parent is of type '" + p->nodeName() + "', which is not an element node.");
2280 RefPtr<Element> parent = toElement(p);
2281 RefPtr<Node> prev = previousSibling();
2282 RefPtr<Node> next = nextSibling();
2284 RefPtr<DocumentFragment> fragment = createFragmentForInnerOuterHTML(html, parent.get(), AllowScriptingContent, "outerHTML", exceptionState);
2285 if (exceptionState.hadException())
2288 parent->replaceChild(fragment.release(), this, exceptionState);
2289 RefPtr<Node> node = next ? next->previousSibling() : 0;
2290 if (!exceptionState.hadException() && node && node->isTextNode())
2291 mergeWithNextTextNode(node.release(), exceptionState);
2293 if (!exceptionState.hadException() && prev && prev->isTextNode())
2294 mergeWithNextTextNode(prev.release(), exceptionState);
2297 Node* Element::insertAdjacent(const String& where, Node* newChild, ExceptionState& exceptionState)
2299 if (equalIgnoringCase(where, "beforeBegin")) {
2300 if (ContainerNode* parent = this->parentNode()) {
2301 parent->insertBefore(newChild, this, exceptionState);
2302 if (!exceptionState.hadException())
2308 if (equalIgnoringCase(where, "afterBegin")) {
2309 insertBefore(newChild, firstChild(), exceptionState);
2310 return exceptionState.hadException() ? 0 : newChild;
2313 if (equalIgnoringCase(where, "beforeEnd")) {
2314 appendChild(newChild, exceptionState);
2315 return exceptionState.hadException() ? 0 : newChild;
2318 if (equalIgnoringCase(where, "afterEnd")) {
2319 if (ContainerNode* parent = this->parentNode()) {
2320 parent->insertBefore(newChild, nextSibling(), exceptionState);
2321 if (!exceptionState.hadException())
2327 exceptionState.throwDOMException(SyntaxError, "The value provided ('" + where + "') is not one of 'beforeBegin', 'afterBegin', 'beforeEnd', or 'afterEnd'.");
2331 // Step 1 of http://domparsing.spec.whatwg.org/#insertadjacenthtml()
2332 static Element* contextElementForInsertion(const String& where, Element* element, ExceptionState& exceptionState)
2334 if (equalIgnoringCase(where, "beforeBegin") || equalIgnoringCase(where, "afterEnd")) {
2335 ContainerNode* parent = element->parentNode();
2336 if (!parent || !parent->isElementNode()) {
2337 exceptionState.throwDOMException(NoModificationAllowedError, "The element has no parent.");
2340 return toElement(parent);
2342 if (equalIgnoringCase(where, "afterBegin") || equalIgnoringCase(where, "beforeEnd"))
2344 exceptionState.throwDOMException(SyntaxError, "The value provided ('" + where + "') is not one of 'beforeBegin', 'afterBegin', 'beforeEnd', or 'afterEnd'.");
2348 Element* Element::insertAdjacentElement(const String& where, Element* newChild, ExceptionState& exceptionState)
2351 // IE throws COM Exception E_INVALIDARG; this is the best DOM exception alternative.
2352 exceptionState.throwTypeError("The node provided is null.");
2356 Node* returnValue = insertAdjacent(where, newChild, exceptionState);
2357 return toElement(returnValue);
2360 void Element::insertAdjacentText(const String& where, const String& text, ExceptionState& exceptionState)
2362 RefPtr<Text> textNode = document().createTextNode(text);
2363 insertAdjacent(where, textNode.get(), exceptionState);
2366 void Element::insertAdjacentHTML(const String& where, const String& markup, ExceptionState& exceptionState)
2368 RefPtr<Element> contextElement = contextElementForInsertion(where, this, exceptionState);
2369 if (!contextElement)
2372 RefPtr<DocumentFragment> fragment = createFragmentForInnerOuterHTML(markup, contextElement.get(), AllowScriptingContent, "insertAdjacentHTML", exceptionState);
2375 insertAdjacent(where, fragment.get(), exceptionState);
2378 String Element::innerText()
2380 // We need to update layout, since plainText uses line boxes in the render tree.
2381 document().updateLayoutIgnorePendingStylesheets();
2384 return textContent(true);
2386 return plainText(rangeOfContents(const_cast<Element*>(this)).get());
2389 String Element::outerText()
2391 // Getting outerText is the same as getting innerText, only
2392 // setting is different. You would think this should get the plain
2393 // text for the outer range, but this is wrong, <br> for instance
2394 // would return different values for inner and outer text by such
2395 // a rule, but it doesn't in WinIE, and we want to match that.
2399 String Element::textFromChildren()
2401 Text* firstTextNode = 0;
2402 bool foundMultipleTextNodes = false;
2403 unsigned totalLength = 0;
2405 for (Node* child = firstChild(); child; child = child->nextSibling()) {
2406 if (!child->isTextNode())
2408 Text* text = toText(child);
2410 firstTextNode = text;
2412 foundMultipleTextNodes = true;
2413 unsigned length = text->data().length();
2414 if (length > std::numeric_limits<unsigned>::max() - totalLength)
2415 return emptyString();
2416 totalLength += length;
2420 return emptyString();
2422 if (firstTextNode && !foundMultipleTextNodes) {
2423 firstTextNode->atomize();
2424 return firstTextNode->data();
2427 StringBuilder content;
2428 content.reserveCapacity(totalLength);
2429 for (Node* child = firstTextNode; child; child = child->nextSibling()) {
2430 if (!child->isTextNode())
2432 content.append(toText(child)->data());
2435 ASSERT(content.length() == totalLength);
2436 return content.toString();
2439 const AtomicString& Element::shadowPseudoId() const
2441 if (ShadowRoot* root = containingShadowRoot()) {
2442 if (root->type() == ShadowRoot::UserAgentShadowRoot)
2443 return fastGetAttribute(pseudoAttr);
2448 void Element::setShadowPseudoId(const AtomicString& id)
2450 ASSERT(CSSSelector::parsePseudoType(id) == CSSSelector::PseudoWebKitCustomElement || CSSSelector::parsePseudoType(id) == CSSSelector::PseudoUserAgentCustomElement);
2451 setAttribute(pseudoAttr, id);
2454 bool Element::isInDescendantTreeOf(const Element* shadowHost) const
2457 ASSERT(isShadowHost(shadowHost));
2459 const ShadowRoot* shadowRoot = containingShadowRoot();
2460 while (shadowRoot) {
2461 const Element* ancestorShadowHost = shadowRoot->shadowHost();
2462 if (ancestorShadowHost == shadowHost)
2464 shadowRoot = ancestorShadowHost->containingShadowRoot();
2469 LayoutSize Element::minimumSizeForResizing() const
2471 return hasRareData() ? elementRareData()->minimumSizeForResizing() : defaultMinimumSizeForResizing();
2474 void Element::setMinimumSizeForResizing(const LayoutSize& size)
2476 if (!hasRareData() && size == defaultMinimumSizeForResizing())
2478 ensureElementRareData().setMinimumSizeForResizing(size);
2481 RenderStyle* Element::computedStyle(PseudoId pseudoElementSpecifier)
2483 if (PseudoElement* element = pseudoElement(pseudoElementSpecifier))
2484 return element->computedStyle();
2486 // FIXME: Find and use the renderer from the pseudo element instead of the actual element so that the 'length'
2487 // properties, which are only known by the renderer because it did the layout, will be correct and so that the
2488 // values returned for the ":selection" pseudo-element will be correct.
2489 if (RenderStyle* usedStyle = renderStyle()) {
2490 if (pseudoElementSpecifier) {
2491 RenderStyle* cachedPseudoStyle = usedStyle->getCachedPseudoStyle(pseudoElementSpecifier);
2492 return cachedPseudoStyle ? cachedPseudoStyle : usedStyle;
2497 if (!inActiveDocument())
2498 // FIXME: Try to do better than this. Ensure that styleForElement() works for elements that are not in the
2499 // document tree and figure out when to destroy the computed style for such elements.
2502 ElementRareData& rareData = ensureElementRareData();
2503 if (!rareData.computedStyle())
2504 rareData.setComputedStyle(document().styleForElementIgnoringPendingStylesheets(this));
2505 return pseudoElementSpecifier ? rareData.computedStyle()->getCachedPseudoStyle(pseudoElementSpecifier) : rareData.computedStyle();
2508 void Element::setChildIndex(unsigned index)
2510 ElementRareData& rareData = ensureElementRareData();
2511 if (RenderStyle* style = renderStyle())
2513 rareData.setChildIndex(index);
2516 unsigned Element::rareDataChildIndex() const
2518 ASSERT(hasRareData());
2519 return elementRareData()->childIndex();
2522 AtomicString Element::computeInheritedLanguage() const
2524 const Node* n = this;
2526 // The language property is inherited, so we iterate over the parents to find the first language.
2528 if (n->isElementNode()) {
2529 if (const ElementData* elementData = toElement(n)->elementData()) {
2530 // Spec: xml:lang takes precedence -- http://www.w3.org/TR/xhtml1/#C_7
2531 if (const Attribute* attribute = elementData->getAttributeItem(XMLNames::langAttr))
2532 value = attribute->value();
2533 else if (const Attribute* attribute = elementData->getAttributeItem(HTMLNames::langAttr))
2534 value = attribute->value();
2536 } else if (n->isDocumentNode()) {
2537 // checking the MIME content-language
2538 value = toDocument(n)->contentLanguage();
2541 n = n->parentNode();
2542 } while (n && value.isNull());
2547 Locale& Element::locale() const
2549 return document().getCachedLocale(computeInheritedLanguage());
2552 void Element::cancelFocusAppearanceUpdate()
2555 clearElementFlag(NeedsFocusAppearanceUpdateSoonAfterAttach);
2556 if (document().focusedElement() == this)
2557 document().cancelFocusAppearanceUpdate();
2560 void Element::normalizeAttributes()
2562 if (!hasAttributes())
2564 // attributeCount() cannot be cached before the loop because the attributes
2565 // list is altered while iterating.
2566 for (unsigned i = 0; i < attributeCount(); ++i) {
2567 if (RefPtr<Attr> attr = attrIfExists(attributeItem(i).name()))
2572 void Element::updatePseudoElement(PseudoId pseudoId, StyleRecalcChange change)
2574 ASSERT(!needsStyleRecalc());
2575 PseudoElement* element = pseudoElement(pseudoId);
2576 if (element && (change == UpdatePseudoElements || element->shouldCallRecalcStyle(change))) {
2578 // Need to clear the cached style if the PseudoElement wants a recalc so it
2579 // computes a new style.
2580 if (element->needsStyleRecalc())
2581 renderer()->style()->removeCachedPseudoStyle(pseudoId);
2583 // PseudoElement styles hang off their parent element's style so if we needed
2584 // a style recalc we should Force one on the pseudo.
2585 // FIXME: We should figure out the right text sibling to pass.
2586 element->recalcStyle(change == UpdatePseudoElements ? Force : change);
2588 // Wait until our parent is not displayed or pseudoElementRendererIsNeeded
2589 // is false, otherwise we could continously create and destroy PseudoElements
2590 // when RenderObject::isChildAllowed on our parent returns false for the
2591 // PseudoElement's renderer for each style recalc.
2592 if (!renderer() || !pseudoElementRendererIsNeeded(renderer()->getCachedPseudoStyle(pseudoId)))
2593 elementRareData()->setPseudoElement(pseudoId, nullptr);
2594 } else if (change >= UpdatePseudoElements) {
2595 createPseudoElementIfNeeded(pseudoId);
2599 void Element::createPseudoElementIfNeeded(PseudoId pseudoId)
2601 if (isPseudoElement())
2604 RefPtr<PseudoElement> element = document().ensureStyleResolver().createPseudoElementIfNeeded(*this, pseudoId);
2608 if (pseudoId == BACKDROP)
2609 document().addToTopLayer(element.get(), this);
2610 element->insertedInto(this);
2613 InspectorInstrumentation::pseudoElementCreated(element.get());
2615 ensureElementRareData().setPseudoElement(pseudoId, element.release());
2618 PseudoElement* Element::pseudoElement(PseudoId pseudoId) const
2620 return hasRareData() ? elementRareData()->pseudoElement(pseudoId) : 0;
2623 RenderObject* Element::pseudoElementRenderer(PseudoId pseudoId) const
2625 if (PseudoElement* element = pseudoElement(pseudoId))
2626 return element->renderer();
2630 bool Element::matches(const String& selectors, ExceptionState& exceptionState)
2632 SelectorQuery* selectorQuery = document().selectorQueryCache().add(AtomicString(selectors), document(), exceptionState);
2635 return selectorQuery->matches(*this);
2638 DOMTokenList& Element::classList()
2640 ElementRareData& rareData = ensureElementRareData();
2641 if (!rareData.classList())
2642 rareData.setClassList(ClassList::create(this));
2643 return *rareData.classList();
2646 DOMStringMap& Element::dataset()
2648 ElementRareData& rareData = ensureElementRareData();
2649 if (!rareData.dataset())
2650 rareData.setDataset(DatasetDOMStringMap::create(this));
2651 return *rareData.dataset();
2654 KURL Element::getURLAttribute(const QualifiedName& name) const
2656 #if !ASSERT_DISABLED
2657 if (elementData()) {
2658 if (const Attribute* attribute = getAttributeItem(name))
2659 ASSERT(isURLAttribute(*attribute));
2662 return document().completeURL(stripLeadingAndTrailingHTMLSpaces(getAttribute(name)));
2665 KURL Element::getNonEmptyURLAttribute(const QualifiedName& name) const
2667 #if !ASSERT_DISABLED
2668 if (elementData()) {
2669 if (const Attribute* attribute = getAttributeItem(name))
2670 ASSERT(isURLAttribute(*attribute));
2673 String value = stripLeadingAndTrailingHTMLSpaces(getAttribute(name));
2674 if (value.isEmpty())
2676 return document().completeURL(value);
2679 int Element::getIntegralAttribute(const QualifiedName& attributeName) const
2681 return getAttribute(attributeName).string().toInt();
2684 void Element::setIntegralAttribute(const QualifiedName& attributeName, int value)
2686 setAttribute(attributeName, AtomicString::number(value));
2689 unsigned Element::getUnsignedIntegralAttribute(const QualifiedName& attributeName) const
2691 return getAttribute(attributeName).string().toUInt();
2694 void Element::setUnsignedIntegralAttribute(const QualifiedName& attributeName, unsigned value)
2696 // Range restrictions are enforced for unsigned IDL attributes that
2697 // reflect content attributes,
2698 // http://www.whatwg.org/specs/web-apps/current-work/multipage/common-dom-interfaces.html#reflecting-content-attributes-in-idl-attributes
2699 if (value > 0x7fffffffu)
2701 setAttribute(attributeName, AtomicString::number(value));
2704 double Element::getFloatingPointAttribute(const QualifiedName& attributeName, double fallbackValue) const
2706 return parseToDoubleForNumberType(getAttribute(attributeName), fallbackValue);
2709 void Element::setFloatingPointAttribute(const QualifiedName& attributeName, double value)
2711 setAttribute(attributeName, AtomicString::number(value));
2714 void Element::webkitRequestFullscreen()
2716 FullscreenElementStack::from(document()).requestFullScreenForElement(this, ALLOW_KEYBOARD_INPUT, FullscreenElementStack::EnforceIFrameAllowFullScreenRequirement);
2719 void Element::webkitRequestFullScreen(unsigned short flags)
2721 FullscreenElementStack::from(document()).requestFullScreenForElement(this, (flags | LEGACY_MOZILLA_REQUEST), FullscreenElementStack::EnforceIFrameAllowFullScreenRequirement);
2724 void Element::setContainsFullScreenElement(bool flag)
2726 setElementFlag(ContainsFullScreenElement, flag);
2727 setNeedsStyleRecalc(SubtreeStyleChange);
2730 static Element* parentCrossingFrameBoundaries(Element* element)
2733 return element->parentElement() ? element->parentElement() : element->document().ownerElement();
2736 void Element::setContainsFullScreenElementOnAncestorsCrossingFrameBoundaries(bool flag)
2738 Element* element = this;
2739 while ((element = parentCrossingFrameBoundaries(element)))
2740 element->setContainsFullScreenElement(flag);
2743 void Element::setIsInTopLayer(bool inTopLayer)
2745 if (isInTopLayer() == inTopLayer)
2747 setElementFlag(IsInTopLayer, inTopLayer);
2749 // We must ensure a reattach occurs so the renderer is inserted in the correct sibling order under RenderView according to its
2750 // top layer position, or in its usual place if not in the top layer.
2751 lazyReattachIfAttached();
2754 void Element::webkitRequestPointerLock()
2756 if (document().page())
2757 document().page()->pointerLockController().requestPointerLock(this);
2760 SpellcheckAttributeState Element::spellcheckAttributeState() const
2762 const AtomicString& value = fastGetAttribute(spellcheckAttr);
2763 if (value == nullAtom)
2764 return SpellcheckAttributeDefault;
2765 if (equalIgnoringCase(value, "true") || equalIgnoringCase(value, ""))
2766 return SpellcheckAttributeTrue;
2767 if (equalIgnoringCase(value, "false"))
2768 return SpellcheckAttributeFalse;
2770 return SpellcheckAttributeDefault;
2773 bool Element::isSpellCheckingEnabled() const
2775 for (const Element* element = this; element; element = element->parentOrShadowHostElement()) {
2776 switch (element->spellcheckAttributeState()) {
2777 case SpellcheckAttributeTrue:
2779 case SpellcheckAttributeFalse:
2781 case SpellcheckAttributeDefault:
2790 bool Element::fastAttributeLookupAllowed(const QualifiedName& name) const
2792 if (name == HTMLNames::styleAttr)
2796 return !toSVGElement(this)->isAnimatableAttribute(name);
2802 #ifdef DUMP_NODE_STATISTICS
2803 bool Element::hasNamedNodeMap() const
2805 return hasRareData() && elementRareData()->attributeMap();
2809 inline void Element::updateName(const AtomicString& oldName, const AtomicString& newName)
2811 if (!inDocument() || isInShadowTree())
2814 if (oldName == newName)
2817 if (shouldRegisterAsNamedItem())
2818 updateNamedItemRegistration(oldName, newName);
2821 inline void Element::updateId(const AtomicString& oldId, const AtomicString& newId)
2823 if (!isInTreeScope())
2829 updateId(treeScope(), oldId, newId);
2832 inline void Element::updateId(TreeScope& scope, const AtomicString& oldId, const AtomicString& newId)
2834 ASSERT(isInTreeScope());
2835 ASSERT(oldId != newId);
2837 if (!oldId.isEmpty())
2838 scope.removeElementById(oldId, this);
2839 if (!newId.isEmpty())
2840 scope.addElementById(newId, this);
2842 if (shouldRegisterAsExtraNamedItem())
2843 updateExtraNamedItemRegistration(oldId, newId);
2846 void Element::updateLabel(TreeScope& scope, const AtomicString& oldForAttributeValue, const AtomicString& newForAttributeValue)
2848 ASSERT(isHTMLLabelElement(this));
2853 if (oldForAttributeValue == newForAttributeValue)
2856 if (!oldForAttributeValue.isEmpty())
2857 scope.removeLabel(oldForAttributeValue, toHTMLLabelElement(this));
2858 if (!newForAttributeValue.isEmpty())
2859 scope.addLabel(newForAttributeValue, toHTMLLabelElement(this));
2862 void Element::willModifyAttribute(const QualifiedName& name, const AtomicString& oldValue, const AtomicString& newValue)
2864 if (isIdAttributeName(name)) {
2865 updateId(oldValue, newValue);
2866 } else if (name == HTMLNames::nameAttr) {
2867 updateName(oldValue, newValue);
2868 } else if (name == HTMLNames::forAttr && isHTMLLabelElement(*this)) {
2869 TreeScope& scope = treeScope();
2870 if (scope.shouldCacheLabelsByForAttribute())
2871 updateLabel(scope, oldValue, newValue);
2874 if (oldValue != newValue) {
2875 if (inActiveDocument())
2876 document().ensureStyleResolver().ensureUpdatedRuleFeatureSet().scheduleStyleInvalidationForAttributeChange(name, this);
2878 if (isUpgradedCustomElement())
2879 CustomElement::attributeDidChange(this, name.localName(), oldValue, newValue);
2882 if (OwnPtr<MutationObserverInterestGroup> recipients = MutationObserverInterestGroup::createForAttributesMutation(*this, name))
2883 recipients->enqueueMutationRecord(MutationRecord::createAttributes(this, name, oldValue));
2885 InspectorInstrumentation::willModifyDOMAttr(this, oldValue, newValue);
2888 void Element::didAddAttribute(const QualifiedName& name, const AtomicString& value)
2890 attributeChanged(name, value);
2891 InspectorInstrumentation::didModifyDOMAttr(this, name.localName(), value);
2892 dispatchSubtreeModifiedEvent();
2895 void Element::didModifyAttribute(const QualifiedName& name, const AtomicString& value)
2897 attributeChanged(name, value);
2898 InspectorInstrumentation::didModifyDOMAttr(this, name.localName(), value);
2899 // Do not dispatch a DOMSubtreeModified event here; see bug 81141.
2902 void Element::didRemoveAttribute(const QualifiedName& name)
2904 attributeChanged(name, nullAtom);
2905 InspectorInstrumentation::didRemoveDOMAttr(this, name.localName());
2906 dispatchSubtreeModifiedEvent();
2909 static bool needsURLResolutionForInlineStyle(const Element& element, const Document& oldDocument, const Document& newDocument)
2911 if (oldDocument == newDocument)
2913 if (oldDocument.baseURL() == newDocument.baseURL())
2915 const StylePropertySet* style = element.inlineStyle();
2918 for (unsigned i = 0; i < style->propertyCount(); ++i) {
2919 // FIXME: Should handle all URL-based properties: CSSImageSetValue, CSSCursorImageValue, etc.
2920 if (style->propertyAt(i).value()->isImageValue())
2926 static void reResolveURLsInInlineStyle(const Document& document, MutableStylePropertySet& style)
2928 for (unsigned i = 0; i < style.propertyCount(); ++i) {
2929 StylePropertySet::PropertyReference property = style.propertyAt(i);
2930 // FIXME: Should handle all URL-based properties: CSSImageSetValue, CSSCursorImageValue, etc.
2931 if (property.value()->isImageValue())
2932 toCSSImageValue(property.value())->reResolveURL(document);
2936 void Element::didMoveToNewDocument(Document& oldDocument)
2938 Node::didMoveToNewDocument(oldDocument);
2940 // If the documents differ by quirks mode then they differ by case sensitivity
2941 // for class and id names so we need to go through the attribute change logic
2942 // to pick up the new casing in the ElementData.
2943 if (oldDocument.inQuirksMode() != document().inQuirksMode()) {
2945 setIdAttribute(getIdAttribute());
2947 setAttribute(HTMLNames::classAttr, getClassAttribute());
2950 if (needsURLResolutionForInlineStyle(*this, oldDocument, document()))
2951 reResolveURLsInInlineStyle(document(), ensureMutableInlineStyle());
2954 void Element::updateNamedItemRegistration(const AtomicString& oldName, const AtomicString& newName)
2956 if (!document().isHTMLDocument())
2959 if (!oldName.isEmpty())
2960 toHTMLDocument(document()).removeNamedItem(oldName);
2962 if (!newName.isEmpty())
2963 toHTMLDocument(document()).addNamedItem(newName);
2966 void Element::updateExtraNamedItemRegistration(const AtomicString& oldId, const AtomicString& newId)
2968 if (!document().isHTMLDocument())
2971 if (!oldId.isEmpty())
2972 toHTMLDocument(document()).removeExtraNamedItem(oldId);
2974 if (!newId.isEmpty())
2975 toHTMLDocument(document()).addExtraNamedItem(newId);
2978 PassRefPtr<HTMLCollection> Element::ensureCachedHTMLCollection(CollectionType type)
2980 if (HTMLCollection* collection = cachedHTMLCollection(type))
2983 if (type == TableRows) {
2984 ASSERT(isHTMLTableElement(this));
2985 return ensureRareData().ensureNodeLists().addCache<HTMLTableRowsCollection>(*this, type);
2986 } else if (type == SelectOptions) {
2987 ASSERT(isHTMLSelectElement(this));
2988 return ensureRareData().ensureNodeLists().addCache<HTMLOptionsCollection>(*this, type);
2989 } else if (type == FormControls) {
2990 ASSERT(isHTMLFormElement(this) || isHTMLFieldSetElement(this));
2991 return ensureRareData().ensureNodeLists().addCache<HTMLFormControlsCollection>(*this, type);
2993 return ensureRareData().ensureNodeLists().addCache<HTMLCollection>(*this, type);
2996 void Element::scheduleLayerUpdate()
2998 document().scheduleLayerUpdate(*this);
3001 HTMLCollection* Element::cachedHTMLCollection(CollectionType type)
3003 return hasRareData() && rareData()->nodeLists() ? rareData()->nodeLists()->cached<HTMLCollection>(type) : 0;
3006 IntSize Element::savedLayerScrollOffset() const
3008 return hasRareData() ? elementRareData()->savedLayerScrollOffset() : IntSize();
3011 void Element::setSavedLayerScrollOffset(const IntSize& size)
3013 if (size.isZero() && !hasRareData())
3015 ensureElementRareData().setSavedLayerScrollOffset(size);
3018 PassRefPtr<Attr> Element::attrIfExists(const QualifiedName& name)
3020 if (AttrNodeList* attrNodeList = attrNodeListForElement(this))
3021 return findAttrNodeInList(*attrNodeList, name);
3025 PassRefPtr<Attr> Element::ensureAttr(const QualifiedName& name)
3027 AttrNodeList& attrNodeList = ensureAttrNodeListForElement(this);
3028 RefPtr<Attr> attrNode = findAttrNodeInList(attrNodeList, name);
3030 attrNode = Attr::create(*this, name);
3031 treeScope().adoptIfNeeded(*attrNode);
3032 attrNodeList.append(attrNode);
3034 return attrNode.release();
3037 void Element::detachAttrNodeFromElementWithValue(Attr* attrNode, const AtomicString& value)
3039 ASSERT(hasSyntheticAttrChildNodes());
3040 attrNode->detachFromElementWithValue(value);
3042 AttrNodeList* attrNodeList = attrNodeListForElement(this);
3043 for (unsigned i = 0; i < attrNodeList->size(); ++i) {
3044 if (attrNodeList->at(i)->qualifiedName() == attrNode->qualifiedName()) {
3045 attrNodeList->remove(i);
3046 if (attrNodeList->isEmpty())
3047 removeAttrNodeListForElement(this);
3051 ASSERT_NOT_REACHED();
3054 void Element::detachAllAttrNodesFromElement()
3056 AttrNodeList* attrNodeList = attrNodeListForElement(this);
3057 ASSERT(attrNodeList);
3059 unsigned attributeCount = this->attributeCount();
3060 for (unsigned i = 0; i < attributeCount; ++i) {
3061 const Attribute& attribute = attributeItem(i);
3062 if (RefPtr<Attr> attrNode = findAttrNodeInList(*attrNodeList, attribute.name()))
3063 attrNode->detachFromElementWithValue(attribute.value());
3066 removeAttrNodeListForElement(this);
3069 void Element::willRecalcStyle(StyleRecalcChange)
3071 ASSERT(hasCustomStyleCallbacks());
3074 void Element::didRecalcStyle(StyleRecalcChange)
3076 ASSERT(hasCustomStyleCallbacks());
3080 PassRefPtr<RenderStyle> Element::customStyleForRenderer()
3082 ASSERT(hasCustomStyleCallbacks());
3086 void Element::cloneAttributesFromElement(const Element& other)
3088 if (hasSyntheticAttrChildNodes())
3089 detachAllAttrNodesFromElement();
3091 other.synchronizeAllAttributes();
3092 if (!other.m_elementData) {
3093 m_elementData.clear();
3097 const AtomicString& oldID = getIdAttribute();
3098 const AtomicString& newID = other.getIdAttribute();
3100 if (!oldID.isNull() || !newID.isNull())
3101 updateId(oldID, newID);
3103 const AtomicString& oldName = getNameAttribute();
3104 const AtomicString& newName = other.getNameAttribute();
3106 if (!oldName.isNull() || !newName.isNull())
3107 updateName(oldName, newName);
3109 // Quirks mode makes class and id not case sensitive. We can't share the ElementData
3110 // if the idForStyleResolution and the className need different casing.
3111 bool ownerDocumentsHaveDifferentCaseSensitivity = false;
3112 if (other.hasClass() || other.hasID())
3113 ownerDocumentsHaveDifferentCaseSensitivity = other.document().inQuirksMode() != document().inQuirksMode();
3115 // If 'other' has a mutable ElementData, convert it to an immutable one so we can share it between both elements.
3116 // We can only do this if there are no presentation attributes and sharing the data won't result in different case sensitivity of class or id.
3117 if (other.m_elementData->isUnique()
3118 && !ownerDocumentsHaveDifferentCaseSensitivity
3119 && !other.m_elementData->presentationAttributeStyle())
3120 const_cast<Element&>(other).m_elementData = static_cast<const UniqueElementData*>(other.m_elementData.get())->makeShareableCopy();
3122 if (!other.m_elementData->isUnique() && !ownerDocumentsHaveDifferentCaseSensitivity && !needsURLResolutionForInlineStyle(other, other.document(), document()))
3123 m_elementData = other.m_elementData;
3125 m_elementData = other.m_elementData->makeUniqueCopy();
3127 unsigned length = m_elementData->length();
3128 for (unsigned i = 0; i < length; ++i) {
3129 const Attribute& attribute = m_elementData->attributeItem(i);
3130 attributeChangedFromParserOrByCloning(attribute.name(), attribute.value(), ModifiedByCloning);
3134 void Element::cloneDataFromElement(const Element& other)
3136 cloneAttributesFromElement(other);
3137 copyNonAttributePropertiesFromElement(other);
3140 void Element::createUniqueElementData()
3143 m_elementData = UniqueElementData::create();
3145 ASSERT(!m_elementData->isUnique());
3146 m_elementData = static_cast<ShareableElementData*>(m_elementData.get())->makeUniqueCopy();
3150 InputMethodContext& Element::inputMethodContext()
3152 return ensureElementRareData().ensureInputMethodContext(toHTMLElement(this));
3155 bool Element::hasInputMethodContext() const
3157 return hasRareData() && elementRareData()->hasInputMethodContext();
3160 void Element::synchronizeStyleAttributeInternal() const
3162 ASSERT(isStyledElement());
3163 ASSERT(elementData());
3164 ASSERT(elementData()->m_styleAttributeIsDirty);
3165 elementData()->m_styleAttributeIsDirty = false;
3166 const StylePropertySet* inlineStyle = this->inlineStyle();
3167 const_cast<Element*>(this)->setSynchronizedLazyAttribute(styleAttr,
3168 inlineStyle ? AtomicString(inlineStyle->asText()) : nullAtom);
3171 CSSStyleDeclaration* Element::style()
3173 if (!isStyledElement())
3175 return &ensureElementRareData().ensureInlineCSSStyleDeclaration(this);
3178 MutableStylePropertySet& Element::ensureMutableInlineStyle()
3180 ASSERT(isStyledElement());
3181 RefPtr<StylePropertySet>& inlineStyle = ensureUniqueElementData().m_inlineStyle;
3183 CSSParserMode mode = (!isHTMLElement() || document().inQuirksMode()) ? HTMLQuirksMode : HTMLStandardMode;
3184 inlineStyle = MutableStylePropertySet::create(mode);
3185 } else if (!inlineStyle->isMutable()) {
3186 inlineStyle = inlineStyle->mutableCopy();
3188 return *toMutableStylePropertySet(inlineStyle);
3191 void Element::clearMutableInlineStyleIfEmpty()
3193 if (ensureMutableInlineStyle().isEmpty()) {
3194 ensureUniqueElementData().m_inlineStyle.clear();
3198 inline void Element::setInlineStyleFromString(const AtomicString& newStyleString)
3200 ASSERT(isStyledElement());
3201 RefPtr<StylePropertySet>& inlineStyle = elementData()->m_inlineStyle;
3203 // Avoid redundant work if we're using shared attribute data with already parsed inline style.
3204 if (inlineStyle && !elementData()->isUnique())
3207 // We reconstruct the property set instead of mutating if there is no CSSOM wrapper.
3208 // This makes wrapperless property sets immutable and so cacheable.
3209 if (inlineStyle && !inlineStyle->isMutable())
3210 inlineStyle.clear();
3213 inlineStyle = BisonCSSParser::parseInlineStyleDeclaration(newStyleString, this);
3215 ASSERT(inlineStyle->isMutable());
3216 static_pointer_cast<MutableStylePropertySet>(inlineStyle)->parseDeclaration(newStyleString, document().elementSheet().contents());
3220 void Element::styleAttributeChanged(const AtomicString& newStyleString, AttributeModificationReason modificationReason)
3222 ASSERT(isStyledElement());
3223 WTF::OrdinalNumber startLineNumber = WTF::OrdinalNumber::beforeFirst();
3224 if (document().scriptableDocumentParser() && !document().isInDocumentWrite())
3225 startLineNumber = document().scriptableDocumentParser()->lineNumber();
3227 if (newStyleString.isNull()) {
3228 ensureUniqueElementData().m_inlineStyle.clear();
3229 } else if (modificationReason == ModifiedByCloning || document().contentSecurityPolicy()->allowInlineStyle(document().url(), startLineNumber)) {
3230 setInlineStyleFromString(newStyleString);
3233 elementData()->m_styleAttributeIsDirty = false;
3235 setNeedsStyleRecalc(LocalStyleChange);
3236 InspectorInstrumentation::didInvalidateStyleAttr(this);
3239 void Element::inlineStyleChanged()
3241 ASSERT(isStyledElement());
3242 setNeedsStyleRecalc(LocalStyleChange);
3243 ASSERT(elementData());
3244 elementData()->m_styleAttributeIsDirty = true;
3245 InspectorInstrumentation::didInvalidateStyleAttr(this);
3248 bool Element::setInlineStyleProperty(CSSPropertyID propertyID, CSSValueID identifier, bool important)
3250 ASSERT(isStyledElement());
3251 ensureMutableInlineStyle().setProperty(propertyID, cssValuePool().createIdentifierValue(identifier), important);
3252 inlineStyleChanged();
3256 bool Element::setInlineStyleProperty(CSSPropertyID propertyID, CSSPropertyID identifier, bool important)
3258 ASSERT(isStyledElement());
3259 ensureMutableInlineStyle().setProperty(propertyID, cssValuePool().createIdentifierValue(identifier), important);
3260 inlineStyleChanged();
3264 bool Element::setInlineStyleProperty(CSSPropertyID propertyID, double value, CSSPrimitiveValue::UnitTypes unit, bool important)
3266 ASSERT(isStyledElement());
3267 ensureMutableInlineStyle().setProperty(propertyID, cssValuePool().createValue(value, unit), important);
3268 inlineStyleChanged();
3272 bool Element::setInlineStyleProperty(CSSPropertyID propertyID, const String& value, bool important)
3274 ASSERT(isStyledElement());
3275 bool changes = ensureMutableInlineStyle().setProperty(propertyID, value, important, document().elementSheet().contents());
3277 inlineStyleChanged();
3281 bool Element::removeInlineStyleProperty(CSSPropertyID propertyID)
3283 ASSERT(isStyledElement());
3286 bool changes = ensureMutableInlineStyle().removeProperty(propertyID);
3288 inlineStyleChanged();
3292 void Element::removeAllInlineStyleProperties()
3294 ASSERT(isStyledElement());
3297 ensureMutableInlineStyle().clear();
3298 inlineStyleChanged();
3301 void Element::updatePresentationAttributeStyle()
3303 // ShareableElementData doesn't store presentation attribute style, so make sure we have a UniqueElementData.
3304 UniqueElementData& elementData = ensureUniqueElementData();
3305 elementData.m_presentationAttributeStyleIsDirty = false;
3306 elementData.m_presentationAttributeStyle = computePresentationAttributeStyle(*this);
3309 void Element::addPropertyToPresentationAttributeStyle(MutableStylePropertySet* style, CSSPropertyID propertyID, CSSValueID identifier)
3311 ASSERT(isStyledElement());
3312 style->setProperty(propertyID, cssValuePool().createIdentifierValue(identifier));
3315 void Element::addPropertyToPresentationAttributeStyle(MutableStylePropertySet* style, CSSPropertyID propertyID, double value, CSSPrimitiveValue::UnitTypes unit)
3317 ASSERT(isStyledElement());
3318 style->setProperty(propertyID, cssValuePool().createValue(value, unit));
3321 void Element::addPropertyToPresentationAttributeStyle(MutableStylePropertySet* style, CSSPropertyID propertyID, const String& value)
3323 ASSERT(isStyledElement());
3324 style->setProperty(propertyID, value, false);
3327 bool Element::supportsStyleSharing() const
3329 if (!isStyledElement() || !parentOrShadowHostElement())
3331 // If the element has inline style it is probably unique.
3334 if (isSVGElement() && toSVGElement(this)->animatedSMILStyleProperties())
3336 // Ids stop style sharing if they show up in the stylesheets.
3337 if (hasID() && document().ensureStyleResolver().hasRulesForId(idForStyleResolution()))
3339 // Active and hovered elements always make a chain towards the document node
3340 // and no siblings or cousins will have the same state.
3347 if (!parentOrShadowHostElement()->childrenSupportStyleSharing())
3349 if (hasScopedHTMLStyleChild())
3351 if (this == document().cssTarget())
3353 if (isHTMLElement() && toHTMLElement(this)->hasDirectionAuto())
3355 if (hasActiveAnimations())
3357 // Turn off style sharing for elements that can gain layers for reasons outside of the style system.
3358 // See comments in RenderObject::setStyle().
3359 // FIXME: Why does gaining a layer from outside the style system require disabling sharing?
3360 if (isHTMLFrameElementBase(*this)
3361 || isHTMLEmbedElement(*this)
3362 || isHTMLObjectElement(*this)
3363 || isHTMLAppletElement(*this)
3364 || isHTMLCanvasElement(*this))
3366 if (FullscreenElementStack::isActiveFullScreenElement(this))
3371 } // namespace WebCore