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/Settings.h"
80 #include "core/frame/UseCounter.h"
81 #include "core/frame/csp/ContentSecurityPolicy.h"
82 #include "core/html/ClassList.h"
83 #include "core/html/HTMLCollection.h"
84 #include "core/html/HTMLDocument.h"
85 #include "core/html/HTMLElement.h"
86 #include "core/html/HTMLFormControlsCollection.h"
87 #include "core/html/HTMLFrameElementBase.h"
88 #include "core/html/HTMLFrameOwnerElement.h"
89 #include "core/html/HTMLLabelElement.h"
90 #include "core/html/HTMLOptionsCollection.h"
91 #include "core/html/HTMLTableRowsCollection.h"
92 #include "core/html/HTMLTemplateElement.h"
93 #include "core/html/parser/HTMLParserIdioms.h"
94 #include "core/inspector/InspectorInstrumentation.h"
95 #include "core/page/FocusController.h"
96 #include "core/page/Page.h"
97 #include "core/page/PointerLockController.h"
98 #include "core/rendering/RenderLayer.h"
99 #include "core/rendering/RenderView.h"
100 #include "core/rendering/compositing/RenderLayerCompositor.h"
101 #include "core/svg/SVGDocumentExtensions.h"
102 #include "core/svg/SVGElement.h"
103 #include "platform/scroll/ScrollableArea.h"
104 #include "wtf/BitVector.h"
105 #include "wtf/HashFunctions.h"
106 #include "wtf/text/CString.h"
107 #include "wtf/text/StringBuilder.h"
108 #include "wtf/text/TextPosition.h"
112 using namespace HTMLNames;
113 using namespace XMLNames;
115 typedef Vector<RefPtr<Attr> > AttrNodeList;
116 typedef HashMap<Element*, OwnPtr<AttrNodeList> > AttrNodeListMap;
118 static AttrNodeListMap& attrNodeListMap()
120 DEFINE_STATIC_LOCAL(AttrNodeListMap, map, ());
124 static AttrNodeList* attrNodeListForElement(Element* element)
126 if (!element->hasSyntheticAttrChildNodes())
128 ASSERT(attrNodeListMap().contains(element));
129 return attrNodeListMap().get(element);
132 static AttrNodeList& ensureAttrNodeListForElement(Element* element)
134 if (element->hasSyntheticAttrChildNodes()) {
135 ASSERT(attrNodeListMap().contains(element));
136 return *attrNodeListMap().get(element);
138 ASSERT(!attrNodeListMap().contains(element));
139 element->setHasSyntheticAttrChildNodes(true);
140 AttrNodeListMap::AddResult result = attrNodeListMap().add(element, adoptPtr(new AttrNodeList));
141 return *result.storedValue->value;
144 static void removeAttrNodeListForElement(Element* element)
146 ASSERT(element->hasSyntheticAttrChildNodes());
147 ASSERT(attrNodeListMap().contains(element));
148 attrNodeListMap().remove(element);
149 element->setHasSyntheticAttrChildNodes(false);
152 static Attr* findAttrNodeInList(const AttrNodeList& attrNodeList, const QualifiedName& name)
154 AttrNodeList::const_iterator end = attrNodeList.end();
155 for (AttrNodeList::const_iterator it = attrNodeList.begin(); it != end; ++it) {
156 if ((*it)->qualifiedName() == name)
162 PassRefPtr<Element> Element::create(const QualifiedName& tagName, Document* document)
164 return adoptRef(new Element(tagName, document, CreateElement));
169 ASSERT(needsAttach());
173 elementRareData()->clearShadow();
176 if (isCustomElement())
177 CustomElement::wasDestroyed(this);
179 if (hasSyntheticAttrChildNodes())
180 detachAllAttrNodesFromElement();
183 // With Oilpan, either the Element has been removed from the Document
184 // or the Document is dead as well. If the Element has been removed from
185 // the Document the element has already been removed from the pending
186 // resources. If the document is also dead, there is no need to remove
187 // the element from the pending resources.
188 if (hasPendingResources()) {
189 document().accessSVGExtensions().removeElementFromPendingResources(this);
190 ASSERT(!hasPendingResources());
195 inline ElementRareData* Element::elementRareData() const
197 ASSERT(hasRareData());
198 return static_cast<ElementRareData*>(rareData());
201 inline ElementRareData& Element::ensureElementRareData()
203 return static_cast<ElementRareData&>(ensureRareData());
206 bool Element::hasElementFlagInternal(ElementFlags mask) const
208 return elementRareData()->hasElementFlag(mask);
211 void Element::setElementFlag(ElementFlags mask, bool value)
213 if (!hasRareData() && !value)
215 ensureElementRareData().setElementFlag(mask, value);
218 void Element::clearElementFlag(ElementFlags mask)
222 elementRareData()->clearElementFlag(mask);
225 void Element::clearTabIndexExplicitlyIfNeeded()
228 elementRareData()->clearTabIndexExplicitly();
231 void Element::setTabIndexExplicitly(short tabIndex)
233 ensureElementRareData().setTabIndexExplicitly(tabIndex);
236 void Element::setTabIndex(int value)
238 setIntegralAttribute(tabindexAttr, value);
241 short Element::tabIndex() const
243 return hasRareData() ? elementRareData()->tabIndex() : 0;
246 bool Element::rendererIsFocusable() const
248 // Elements in canvas fallback content are not rendered, but they are allowed to be
249 // focusable as long as their canvas is displayed and visible.
250 if (isInCanvasSubtree()) {
251 const Element* e = this;
252 while (e && !e->hasLocalName(canvasTag))
253 e = e->parentElement();
255 return e->renderer() && e->renderer()->style()->visibility() == VISIBLE;
258 // FIXME: These asserts should be in Node::isFocusable, but there are some
259 // callsites like Document::setFocusedElement that would currently fail on
260 // them. See crbug.com/251163
262 // We can't just use needsStyleRecalc() because if the node is in a
263 // display:none tree it might say it needs style recalc but the whole
264 // document is actually up to date.
265 ASSERT(!document().childNeedsStyleRecalc());
268 // FIXME: Even if we are not visible, we might have a child that is visible.
269 // Hyatt wants to fix that some day with a "has visible content" flag or the like.
270 if (!renderer() || renderer()->style()->visibility() != VISIBLE)
276 PassRefPtr<Node> Element::cloneNode(bool deep)
278 return deep ? cloneElementWithChildren() : cloneElementWithoutChildren();
281 PassRefPtr<Element> Element::cloneElementWithChildren()
283 RefPtr<Element> clone = cloneElementWithoutChildren();
284 cloneChildNodes(clone.get());
285 return clone.release();
288 PassRefPtr<Element> Element::cloneElementWithoutChildren()
290 RefPtr<Element> clone = cloneElementWithoutAttributesAndChildren();
291 // This will catch HTML elements in the wrong namespace that are not correctly copied.
292 // This is a sanity check as HTML overloads some of the DOM methods.
293 ASSERT(isHTMLElement() == clone->isHTMLElement());
295 clone->cloneDataFromElement(*this);
296 return clone.release();
299 PassRefPtr<Element> Element::cloneElementWithoutAttributesAndChildren()
301 return document().createElement(tagQName(), false);
304 PassRefPtr<Attr> Element::detachAttribute(size_t index)
306 ASSERT(elementData());
307 const Attribute& attribute = elementData()->attributeItem(index);
308 RefPtr<Attr> attrNode = attrIfExists(attribute.name());
310 detachAttrNodeAtIndex(attrNode.get(), index);
312 attrNode = Attr::create(document(), attribute.name(), attribute.value());
313 removeAttributeInternal(index, NotInSynchronizationOfLazyAttribute);
315 return attrNode.release();
318 void Element::detachAttrNodeAtIndex(Attr* attr, size_t index)
321 ASSERT(elementData());
323 const Attribute& attribute = elementData()->attributeItem(index);
324 ASSERT(attribute.name() == attr->qualifiedName());
325 detachAttrNodeFromElementWithValue(attr, attribute.value());
326 removeAttributeInternal(index, NotInSynchronizationOfLazyAttribute);
329 void Element::removeAttribute(const QualifiedName& name)
334 size_t index = elementData()->getAttributeItemIndex(name);
335 if (index == kNotFound)
338 removeAttributeInternal(index, NotInSynchronizationOfLazyAttribute);
341 void Element::setBooleanAttribute(const QualifiedName& name, bool value)
344 setAttribute(name, emptyAtom);
346 removeAttribute(name);
349 NamedNodeMap* Element::attributes() const
351 ElementRareData& rareData = const_cast<Element*>(this)->ensureElementRareData();
352 if (NamedNodeMap* attributeMap = rareData.attributeMap())
355 rareData.setAttributeMap(NamedNodeMap::create(const_cast<Element*>(this)));
356 return rareData.attributeMap();
359 ActiveAnimations* Element::activeAnimations() const
362 return elementRareData()->activeAnimations();
366 ActiveAnimations& Element::ensureActiveAnimations()
368 ElementRareData& rareData = ensureElementRareData();
369 if (!rareData.activeAnimations())
370 rareData.setActiveAnimations(adoptPtrWillBeNoop(new ActiveAnimations()));
371 return *rareData.activeAnimations();
374 bool Element::hasActiveAnimations() const
379 ActiveAnimations* activeAnimations = elementRareData()->activeAnimations();
380 return activeAnimations && !activeAnimations->isEmpty();
383 Node::NodeType Element::nodeType() const
388 bool Element::hasAttribute(const QualifiedName& name) const
390 return hasAttributeNS(name.namespaceURI(), name.localName());
393 void Element::synchronizeAllAttributes() const
397 // NOTE: anyAttributeMatches in SelectorChecker.cpp
398 // currently assumes that all lazy attributes have a null namespace.
399 // If that ever changes we'll need to fix that code.
400 if (elementData()->m_styleAttributeIsDirty) {
401 ASSERT(isStyledElement());
402 synchronizeStyleAttributeInternal();
404 if (elementData()->m_animatedSVGAttributesAreDirty) {
405 ASSERT(isSVGElement());
406 toSVGElement(this)->synchronizeAnimatedSVGAttribute(anyQName());
410 inline void Element::synchronizeAttribute(const QualifiedName& name) const
414 if (UNLIKELY(name == styleAttr && elementData()->m_styleAttributeIsDirty)) {
415 ASSERT(isStyledElement());
416 synchronizeStyleAttributeInternal();
419 if (UNLIKELY(elementData()->m_animatedSVGAttributesAreDirty)) {
420 ASSERT(isSVGElement());
421 // See comment in the AtomicString version of synchronizeAttribute()
423 toSVGElement(this)->synchronizeAnimatedSVGAttribute(name);
427 void Element::synchronizeAttribute(const AtomicString& localName) const
429 // This version of synchronizeAttribute() is streamlined for the case where you don't have a full QualifiedName,
430 // e.g when called from DOM API.
433 if (elementData()->m_styleAttributeIsDirty && equalPossiblyIgnoringCase(localName, styleAttr.localName(), shouldIgnoreAttributeCase())) {
434 ASSERT(isStyledElement());
435 synchronizeStyleAttributeInternal();
438 if (elementData()->m_animatedSVGAttributesAreDirty) {
439 // We're not passing a namespace argument on purpose. SVGNames::*Attr are defined w/o namespaces as well.
441 // FIXME: this code is called regardless of whether name is an
442 // animated SVG Attribute. It would seem we should only call this method
443 // if SVGElement::isAnimatableAttribute is true, but the list of
444 // animatable attributes in isAnimatableAttribute does not suffice to
445 // pass all layout tests. Also, m_animatedSVGAttributesAreDirty stays
446 // dirty unless synchronizeAnimatedSVGAttribute is called with
447 // anyQName(). This means that even if Element::synchronizeAttribute()
448 // is called on all attributes, m_animatedSVGAttributesAreDirty remains
450 toSVGElement(this)->synchronizeAnimatedSVGAttribute(QualifiedName(nullAtom, localName, nullAtom));
454 const AtomicString& Element::getAttribute(const QualifiedName& name) const
458 synchronizeAttribute(name);
459 if (const Attribute* attribute = getAttributeItem(name))
460 return attribute->value();
464 void Element::scrollIntoView(bool alignToTop)
466 document().updateLayoutIgnorePendingStylesheets();
471 LayoutRect bounds = boundingBox();
472 // Align to the top / bottom and to the closest edge.
474 renderer()->scrollRectToVisible(bounds, ScrollAlignment::alignToEdgeIfNeeded, ScrollAlignment::alignTopAlways);
476 renderer()->scrollRectToVisible(bounds, ScrollAlignment::alignToEdgeIfNeeded, ScrollAlignment::alignBottomAlways);
479 void Element::scrollIntoViewIfNeeded(bool centerIfNeeded)
481 document().updateLayoutIgnorePendingStylesheets();
486 LayoutRect bounds = boundingBox();
488 renderer()->scrollRectToVisible(bounds, ScrollAlignment::alignCenterIfNeeded, ScrollAlignment::alignCenterIfNeeded);
490 renderer()->scrollRectToVisible(bounds, ScrollAlignment::alignToEdgeIfNeeded, ScrollAlignment::alignToEdgeIfNeeded);
493 void Element::scrollByUnits(int units, ScrollGranularity granularity)
495 document().updateLayoutIgnorePendingStylesheets();
500 if (!renderer()->hasOverflowClip())
503 ScrollDirection direction = ScrollDown;
505 direction = ScrollUp;
508 toRenderBox(renderer())->scroll(direction, granularity, units);
511 void Element::scrollByLines(int lines)
513 scrollByUnits(lines, ScrollByLine);
516 void Element::scrollByPages(int pages)
518 scrollByUnits(pages, ScrollByPage);
521 static float localZoomForRenderer(RenderObject& renderer)
523 // FIXME: This does the wrong thing if two opposing zooms are in effect and canceled each
524 // other out, but the alternative is that we'd have to crawl up the whole render tree every
525 // time (or store an additional bit in the RenderStyle to indicate that a zoom was specified).
526 float zoomFactor = 1;
527 if (renderer.style()->effectiveZoom() != 1) {
528 // Need to find the nearest enclosing RenderObject that set up
529 // a differing zoom, and then we divide our result by it to eliminate the zoom.
530 RenderObject* prev = &renderer;
531 for (RenderObject* curr = prev->parent(); curr; curr = curr->parent()) {
532 if (curr->style()->effectiveZoom() != prev->style()->effectiveZoom()) {
533 zoomFactor = prev->style()->zoom();
538 if (prev->isRenderView())
539 zoomFactor = prev->style()->zoom();
544 static double adjustForLocalZoom(LayoutUnit value, RenderObject& renderer)
546 float zoomFactor = localZoomForRenderer(renderer);
548 return value.toDouble();
549 return value.toDouble() / zoomFactor;
552 double Element::offsetLeft()
554 document().updateLayoutIgnorePendingStylesheets();
555 if (RenderBoxModelObject* renderer = renderBoxModelObject())
556 return adjustForLocalZoom(renderer->offsetLeft(), *renderer);
560 double Element::offsetTop()
562 document().updateLayoutIgnorePendingStylesheets();
563 if (RenderBoxModelObject* renderer = renderBoxModelObject())
564 return adjustForLocalZoom(renderer->offsetTop(), *renderer);
568 double Element::offsetWidth()
570 document().updateLayoutIgnorePendingStylesheets();
571 if (RenderBoxModelObject* renderer = renderBoxModelObject())
572 return adjustLayoutUnitForAbsoluteZoom(renderer->offsetWidth(), *renderer).toFloat();
576 double Element::offsetHeight()
578 document().updateLayoutIgnorePendingStylesheets();
579 if (RenderBoxModelObject* renderer = renderBoxModelObject())
580 return adjustLayoutUnitForAbsoluteZoom(renderer->offsetHeight(), *renderer).toFloat();
584 Element* Element::offsetParentForBindings()
586 Element* element = offsetParent();
587 if (!element || !element->isInShadowTree())
589 return element->containingShadowRoot()->shouldExposeToBindings() ? element : 0;
592 Element* Element::offsetParent()
594 document().updateLayoutIgnorePendingStylesheets();
595 if (RenderObject* renderer = this->renderer())
596 return renderer->offsetParent();
600 double Element::clientLeft()
602 document().updateLayoutIgnorePendingStylesheets();
604 if (RenderBox* renderer = renderBox())
605 return adjustForAbsoluteZoom(renderer->clientLeft(), renderer);
609 double Element::clientTop()
611 document().updateLayoutIgnorePendingStylesheets();
613 if (RenderBox* renderer = renderBox())
614 return adjustForAbsoluteZoom(renderer->clientTop(), renderer);
618 double Element::clientWidth()
620 document().updateLayoutIgnorePendingStylesheets();
622 // When in strict mode, clientWidth for the document element should return the width of the containing frame.
623 // When in quirks mode, clientWidth for the body element should return the width of the containing frame.
624 bool inQuirksMode = document().inQuirksMode();
625 if ((!inQuirksMode && document().documentElement() == this)
626 || (inQuirksMode && isHTMLElement() && document().body() == this)) {
627 if (FrameView* view = document().view()) {
628 if (RenderView* renderView = document().renderView())
629 return adjustForAbsoluteZoom(view->layoutSize().width(), renderView);
633 if (RenderBox* renderer = renderBox())
634 return adjustLayoutUnitForAbsoluteZoom(renderer->clientWidth(), *renderer).toFloat();
638 double Element::clientHeight()
640 document().updateLayoutIgnorePendingStylesheets();
642 // When in strict mode, clientHeight for the document element should return the height of the containing frame.
643 // When in quirks mode, clientHeight for the body element should return the height of the containing frame.
644 bool inQuirksMode = document().inQuirksMode();
646 if ((!inQuirksMode && document().documentElement() == this)
647 || (inQuirksMode && isHTMLElement() && document().body() == this)) {
648 if (FrameView* view = document().view()) {
649 if (RenderView* renderView = document().renderView())
650 return adjustForAbsoluteZoom(view->layoutSize().height(), renderView);
654 if (RenderBox* renderer = renderBox())
655 return adjustLayoutUnitForAbsoluteZoom(renderer->clientHeight(), *renderer).toFloat();
659 double Element::scrollLeft()
661 document().updateLayoutIgnorePendingStylesheets();
663 if (document().documentElement() != this) {
664 if (RenderBox* rend = renderBox())
665 return adjustForAbsoluteZoom(rend->scrollLeft(), rend);
669 if (RuntimeEnabledFeatures::scrollTopLeftInteropEnabled()) {
670 if (document().inQuirksMode())
673 if (FrameView* view = document().view()) {
674 if (RenderView* renderView = document().renderView())
675 return adjustForAbsoluteZoom(view->scrollX(), renderView);
682 double Element::scrollTop()
684 document().updateLayoutIgnorePendingStylesheets();
686 if (document().documentElement() != this) {
687 if (RenderBox* rend = renderBox())
688 return adjustForAbsoluteZoom(rend->scrollTop(), rend);
692 if (RuntimeEnabledFeatures::scrollTopLeftInteropEnabled()) {
693 if (document().inQuirksMode())
696 if (FrameView* view = document().view()) {
697 if (RenderView* renderView = document().renderView())
698 return adjustForAbsoluteZoom(view->scrollY(), renderView);
705 void Element::setScrollLeft(double newLeft)
707 document().updateLayoutIgnorePendingStylesheets();
709 if (document().documentElement() != this) {
710 if (RenderBox* rend = renderBox())
711 rend->setScrollLeft(roundf(newLeft * rend->style()->effectiveZoom()));
715 if (RuntimeEnabledFeatures::scrollTopLeftInteropEnabled()) {
716 if (document().inQuirksMode())
719 LocalFrame* frame = document().frame();
722 FrameView* view = frame->view();
726 view->setScrollPosition(IntPoint(roundf(newLeft * frame->pageZoomFactor()), view->scrollY()));
730 void Element::setScrollLeft(const Dictionary& scrollOptionsHorizontal, ExceptionState& exceptionState)
732 String scrollBehaviorString;
733 ScrollBehavior scrollBehavior = ScrollBehaviorAuto;
734 if (scrollOptionsHorizontal.get("behavior", scrollBehaviorString)) {
735 if (!ScrollableArea::scrollBehaviorFromString(scrollBehaviorString, scrollBehavior)) {
736 exceptionState.throwTypeError("The ScrollBehavior provided is invalid.");
742 if (!scrollOptionsHorizontal.get("x", position)) {
743 exceptionState.throwTypeError("ScrollOptionsHorizontal must include an 'x' member.");
747 // FIXME: Use scrollBehavior to decide whether to scroll smoothly or instantly.
748 setScrollLeft(position);
751 void Element::setScrollTop(double newTop)
753 document().updateLayoutIgnorePendingStylesheets();
755 if (document().documentElement() != this) {
756 if (RenderBox* rend = renderBox())
757 rend->setScrollTop(roundf(newTop * rend->style()->effectiveZoom()));
761 if (RuntimeEnabledFeatures::scrollTopLeftInteropEnabled()) {
762 if (document().inQuirksMode())
765 LocalFrame* frame = document().frame();
768 FrameView* view = frame->view();
772 view->setScrollPosition(IntPoint(view->scrollX(), roundf(newTop * frame->pageZoomFactor())));
776 void Element::setScrollTop(const Dictionary& scrollOptionsVertical, ExceptionState& exceptionState)
778 String scrollBehaviorString;
779 ScrollBehavior scrollBehavior = ScrollBehaviorAuto;
780 if (scrollOptionsVertical.get("behavior", scrollBehaviorString)) {
781 if (!ScrollableArea::scrollBehaviorFromString(scrollBehaviorString, scrollBehavior)) {
782 exceptionState.throwTypeError("The ScrollBehavior provided is invalid.");
788 if (!scrollOptionsVertical.get("y", position)) {
789 exceptionState.throwTypeError("ScrollOptionsVertical must include a 'y' member.");
793 // FIXME: Use scrollBehavior to decide whether to scroll smoothly or instantly.
794 setScrollTop(position);
797 double Element::scrollWidth()
799 document().updateLayoutIgnorePendingStylesheets();
800 if (RenderBox* rend = renderBox())
801 return adjustForAbsoluteZoom(rend->scrollWidth(), rend);
805 double Element::scrollHeight()
807 document().updateLayoutIgnorePendingStylesheets();
808 if (RenderBox* rend = renderBox())
809 return adjustForAbsoluteZoom(rend->scrollHeight(), rend);
813 IntRect Element::boundsInRootViewSpace()
815 document().updateLayoutIgnorePendingStylesheets();
817 FrameView* view = document().view();
821 Vector<FloatQuad> quads;
822 if (isSVGElement() && renderer()) {
823 // Get the bounding rectangle from the SVG model.
824 SVGElement* svgElement = toSVGElement(this);
826 if (svgElement->getBoundingBox(localRect))
827 quads.append(renderer()->localToAbsoluteQuad(localRect));
829 // Get the bounding rectangle from the box model.
830 if (renderBoxModelObject())
831 renderBoxModelObject()->absoluteQuads(quads);
837 IntRect result = quads[0].enclosingBoundingBox();
838 for (size_t i = 1; i < quads.size(); ++i)
839 result.unite(quads[i].enclosingBoundingBox());
841 result = view->contentsToRootView(result);
845 PassRefPtrWillBeRawPtr<ClientRectList> Element::getClientRects()
847 document().updateLayoutIgnorePendingStylesheets();
849 RenderBoxModelObject* renderBoxModelObject = this->renderBoxModelObject();
850 if (!renderBoxModelObject)
851 return ClientRectList::create();
853 // FIXME: Handle SVG elements.
854 // FIXME: Handle table/inline-table with a caption.
856 Vector<FloatQuad> quads;
857 renderBoxModelObject->absoluteQuads(quads);
858 document().adjustFloatQuadsForScrollAndAbsoluteZoom(quads, *renderBoxModelObject);
859 return ClientRectList::create(quads);
862 PassRefPtrWillBeRawPtr<ClientRect> Element::getBoundingClientRect()
864 document().updateLayoutIgnorePendingStylesheets();
866 Vector<FloatQuad> quads;
867 if (isSVGElement() && renderer() && !renderer()->isSVGRoot()) {
868 // Get the bounding rectangle from the SVG model.
869 SVGElement* svgElement = toSVGElement(this);
871 if (svgElement->getBoundingBox(localRect))
872 quads.append(renderer()->localToAbsoluteQuad(localRect));
874 // Get the bounding rectangle from the box model.
875 if (renderBoxModelObject())
876 renderBoxModelObject()->absoluteQuads(quads);
880 return ClientRect::create();
882 FloatRect result = quads[0].boundingBox();
883 for (size_t i = 1; i < quads.size(); ++i)
884 result.unite(quads[i].boundingBox());
887 document().adjustFloatRectForScrollAndAbsoluteZoom(result, *renderer());
888 return ClientRect::create(result);
891 IntRect Element::screenRect() const
895 // FIXME: this should probably respect transforms
896 return document().view()->contentsToScreen(renderer()->absoluteBoundingBoxRectIgnoringTransforms());
899 const AtomicString& Element::getAttribute(const AtomicString& localName) const
903 synchronizeAttribute(localName);
904 if (const Attribute* attribute = elementData()->getAttributeItem(localName, shouldIgnoreAttributeCase()))
905 return attribute->value();
909 const AtomicString& Element::getAttributeNS(const AtomicString& namespaceURI, const AtomicString& localName) const
911 return getAttribute(QualifiedName(nullAtom, localName, namespaceURI));
914 void Element::setAttribute(const AtomicString& localName, const AtomicString& value, ExceptionState& exceptionState)
916 if (!Document::isValidName(localName)) {
917 exceptionState.throwDOMException(InvalidCharacterError, "'" + localName + "' is not a valid attribute name.");
921 synchronizeAttribute(localName);
922 const AtomicString& caseAdjustedLocalName = shouldIgnoreAttributeCase() ? localName.lower() : localName;
924 size_t index = elementData() ? elementData()->getAttributeItemIndex(caseAdjustedLocalName, false) : kNotFound;
925 const QualifiedName& qName = index != kNotFound ? attributeItem(index).name() : QualifiedName(nullAtom, caseAdjustedLocalName, nullAtom);
926 setAttributeInternal(index, qName, value, NotInSynchronizationOfLazyAttribute);
929 void Element::setAttribute(const QualifiedName& name, const AtomicString& value)
931 synchronizeAttribute(name);
932 size_t index = elementData() ? elementData()->getAttributeItemIndex(name) : kNotFound;
933 setAttributeInternal(index, name, value, NotInSynchronizationOfLazyAttribute);
936 void Element::setSynchronizedLazyAttribute(const QualifiedName& name, const AtomicString& value)
938 size_t index = elementData() ? elementData()->getAttributeItemIndex(name) : kNotFound;
939 setAttributeInternal(index, name, value, InSynchronizationOfLazyAttribute);
942 ALWAYS_INLINE void Element::setAttributeInternal(size_t index, const QualifiedName& name, const AtomicString& newValue, SynchronizationOfLazyAttribute inSynchronizationOfLazyAttribute)
944 if (newValue.isNull()) {
945 if (index != kNotFound)
946 removeAttributeInternal(index, inSynchronizationOfLazyAttribute);
950 if (index == kNotFound) {
951 addAttributeInternal(name, newValue, inSynchronizationOfLazyAttribute);
955 const Attribute& existingAttribute = attributeItem(index);
956 QualifiedName existingAttributeName = existingAttribute.name();
958 if (!inSynchronizationOfLazyAttribute)
959 willModifyAttribute(existingAttributeName, existingAttribute.value(), newValue);
961 if (newValue != existingAttribute.value()) {
962 // If there is an Attr node hooked to this attribute, the Attr::setValue() call below
963 // will write into the ElementData.
964 // FIXME: Refactor this so it makes some sense.
965 if (RefPtr<Attr> attrNode = inSynchronizationOfLazyAttribute ? nullptr : attrIfExists(existingAttributeName))
966 attrNode->setValue(newValue);
968 ensureUniqueElementData().attributeItem(index).setValue(newValue);
971 if (!inSynchronizationOfLazyAttribute)
972 didModifyAttribute(existingAttributeName, newValue);
975 static inline AtomicString makeIdForStyleResolution(const AtomicString& value, bool inQuirksMode)
978 return value.lower();
982 void Element::attributeChanged(const QualifiedName& name, const AtomicString& newValue, AttributeModificationReason reason)
984 if (ElementShadow* parentElementShadow = shadowWhereNodeCanBeDistributed(*this)) {
985 if (shouldInvalidateDistributionWhenAttributeChanged(parentElementShadow, name, newValue))
986 parentElementShadow->setNeedsDistributionRecalc();
989 parseAttribute(name, newValue);
991 document().incDOMTreeVersion();
993 StyleResolver* styleResolver = document().styleResolver();
994 bool testShouldInvalidateStyle = inActiveDocument() && styleResolver && styleChangeType() < SubtreeStyleChange;
996 if (isStyledElement() && name == styleAttr) {
997 styleAttributeChanged(newValue, reason);
998 } else if (isStyledElement() && isPresentationAttribute(name)) {
999 elementData()->m_presentationAttributeStyleIsDirty = true;
1000 setNeedsStyleRecalc(LocalStyleChange);
1003 if (isIdAttributeName(name)) {
1004 AtomicString oldId = elementData()->idForStyleResolution();
1005 AtomicString newId = makeIdForStyleResolution(newValue, document().inQuirksMode());
1006 if (newId != oldId) {
1007 elementData()->setIdForStyleResolution(newId);
1008 if (testShouldInvalidateStyle)
1009 styleResolver->ensureUpdatedRuleFeatureSet().scheduleStyleInvalidationForIdChange(oldId, newId, *this);
1011 } else if (name == classAttr) {
1012 classAttributeChanged(newValue);
1013 } else if (name == HTMLNames::nameAttr) {
1014 setHasName(!newValue.isNull());
1017 invalidateNodeListCachesInAncestors(&name, this);
1019 // If there is currently no StyleResolver, we can't be sure that this attribute change won't affect style.
1021 setNeedsStyleRecalc(SubtreeStyleChange);
1023 if (AXObjectCache* cache = document().existingAXObjectCache())
1024 cache->handleAttributeChanged(name, this);
1027 bool Element::hasLegalLinkAttribute(const QualifiedName&) const
1032 const QualifiedName& Element::subResourceAttributeName() const
1037 inline void Element::attributeChangedFromParserOrByCloning(const QualifiedName& name, const AtomicString& newValue, AttributeModificationReason reason)
1040 CustomElementRegistrationContext::setTypeExtension(this, newValue);
1041 attributeChanged(name, newValue, reason);
1044 template <typename CharacterType>
1045 static inline bool classStringHasClassName(const CharacterType* characters, unsigned length)
1051 if (isNotHTMLSpace<CharacterType>(characters[i]))
1054 } while (i < length);
1059 static inline bool classStringHasClassName(const AtomicString& newClassString)
1061 unsigned length = newClassString.length();
1066 if (newClassString.is8Bit())
1067 return classStringHasClassName(newClassString.characters8(), length);
1068 return classStringHasClassName(newClassString.characters16(), length);
1071 void Element::classAttributeChanged(const AtomicString& newClassString)
1073 StyleResolver* styleResolver = document().styleResolver();
1074 bool testShouldInvalidateStyle = inActiveDocument() && styleResolver && styleChangeType() < SubtreeStyleChange;
1076 ASSERT(elementData());
1077 if (classStringHasClassName(newClassString)) {
1078 const bool shouldFoldCase = document().inQuirksMode();
1079 const SpaceSplitString oldClasses = elementData()->classNames();
1080 elementData()->setClass(newClassString, shouldFoldCase);
1081 const SpaceSplitString& newClasses = elementData()->classNames();
1082 if (testShouldInvalidateStyle)
1083 styleResolver->ensureUpdatedRuleFeatureSet().scheduleStyleInvalidationForClassChange(oldClasses, newClasses, *this);
1085 const SpaceSplitString& oldClasses = elementData()->classNames();
1086 if (testShouldInvalidateStyle)
1087 styleResolver->ensureUpdatedRuleFeatureSet().scheduleStyleInvalidationForClassChange(oldClasses, *this);
1088 elementData()->clearClass();
1092 elementRareData()->clearClassListValueForQuirksMode();
1095 bool Element::shouldInvalidateDistributionWhenAttributeChanged(ElementShadow* elementShadow, const QualifiedName& name, const AtomicString& newValue)
1097 ASSERT(elementShadow);
1098 const SelectRuleFeatureSet& featureSet = elementShadow->ensureSelectFeatureSet();
1100 if (isIdAttributeName(name)) {
1101 AtomicString oldId = elementData()->idForStyleResolution();
1102 AtomicString newId = makeIdForStyleResolution(newValue, document().inQuirksMode());
1103 if (newId != oldId) {
1104 if (!oldId.isEmpty() && featureSet.hasSelectorForId(oldId))
1106 if (!newId.isEmpty() && featureSet.hasSelectorForId(newId))
1111 if (name == HTMLNames::classAttr) {
1112 const AtomicString& newClassString = newValue;
1113 if (classStringHasClassName(newClassString)) {
1114 const bool shouldFoldCase = document().inQuirksMode();
1115 const SpaceSplitString& oldClasses = elementData()->classNames();
1116 const SpaceSplitString newClasses(newClassString, shouldFoldCase);
1117 if (featureSet.checkSelectorsForClassChange(oldClasses, newClasses))
1120 const SpaceSplitString& oldClasses = elementData()->classNames();
1121 if (featureSet.checkSelectorsForClassChange(oldClasses))
1126 return featureSet.hasSelectorForAttribute(name.localName());
1129 // Returns true is the given attribute is an event handler.
1130 // We consider an event handler any attribute that begins with "on".
1131 // It is a simple solution that has the advantage of not requiring any
1132 // code or configuration change if a new event handler is defined.
1134 static inline bool isEventHandlerAttribute(const Attribute& attribute)
1136 return attribute.name().namespaceURI().isNull() && attribute.name().localName().startsWith("on");
1139 bool Element::isJavaScriptURLAttribute(const Attribute& attribute) const
1141 return isURLAttribute(attribute) && protocolIsJavaScript(stripLeadingAndTrailingHTMLSpaces(attribute.value()));
1144 void Element::stripScriptingAttributes(Vector<Attribute>& attributeVector) const
1146 size_t destination = 0;
1147 for (size_t source = 0; source < attributeVector.size(); ++source) {
1148 if (isEventHandlerAttribute(attributeVector[source])
1149 || isJavaScriptURLAttribute(attributeVector[source])
1150 || isHTMLContentAttribute(attributeVector[source]))
1153 if (source != destination)
1154 attributeVector[destination] = attributeVector[source];
1158 attributeVector.shrink(destination);
1161 void Element::parserSetAttributes(const Vector<Attribute>& attributeVector)
1163 ASSERT(!inDocument());
1164 ASSERT(!parentNode());
1165 ASSERT(!m_elementData);
1167 if (attributeVector.isEmpty())
1170 if (document().elementDataCache())
1171 m_elementData = document().elementDataCache()->cachedShareableElementDataWithAttributes(attributeVector);
1173 m_elementData = ShareableElementData::createWithAttributes(attributeVector);
1175 // Use attributeVector instead of m_elementData because attributeChanged might modify m_elementData.
1176 for (unsigned i = 0; i < attributeVector.size(); ++i)
1177 attributeChangedFromParserOrByCloning(attributeVector[i].name(), attributeVector[i].value(), ModifiedDirectly);
1180 bool Element::hasAttributes() const
1182 synchronizeAllAttributes();
1183 return elementData() && elementData()->length();
1186 bool Element::hasEquivalentAttributes(const Element* other) const
1188 synchronizeAllAttributes();
1189 other->synchronizeAllAttributes();
1190 if (elementData() == other->elementData())
1193 return elementData()->isEquivalent(other->elementData());
1194 if (other->elementData())
1195 return other->elementData()->isEquivalent(elementData());
1199 String Element::nodeName() const
1201 return m_tagName.toString();
1204 void Element::setPrefix(const AtomicString& prefix, ExceptionState& exceptionState)
1206 UseCounter::count(document(), UseCounter::ElementSetPrefix);
1208 if (!prefix.isEmpty() && !Document::isValidName(prefix)) {
1209 exceptionState.throwDOMException(InvalidCharacterError, "The prefix '" + prefix + "' is not a valid name.");
1213 // FIXME: Raise NamespaceError if prefix is malformed per the Namespaces in XML specification.
1215 const AtomicString& nodeNamespaceURI = namespaceURI();
1216 if (nodeNamespaceURI.isEmpty() && !prefix.isEmpty()) {
1217 exceptionState.throwDOMException(NamespaceError, "No namespace is set, so a namespace prefix may not be set.");
1221 if (prefix == xmlAtom && nodeNamespaceURI != XMLNames::xmlNamespaceURI) {
1222 exceptionState.throwDOMException(NamespaceError, "The prefix '" + xmlAtom + "' may not be set on namespace '" + nodeNamespaceURI + "'.");
1226 if (exceptionState.hadException())
1229 m_tagName.setPrefix(prefix.isEmpty() ? AtomicString() : prefix);
1232 const AtomicString& Element::locateNamespacePrefix(const AtomicString& namespaceToLocate) const
1234 if (!prefix().isNull() && namespaceURI() == namespaceToLocate)
1237 if (hasAttributes()) {
1238 unsigned attributeCount = this->attributeCount();
1239 for (unsigned i = 0; i < attributeCount; ++i) {
1240 const Attribute& attr = attributeItem(i);
1242 if (attr.prefix() == xmlnsAtom && attr.value() == namespaceToLocate)
1243 return attr.localName();
1247 if (Element* parent = parentElement())
1248 return parent->locateNamespacePrefix(namespaceToLocate);
1253 KURL Element::baseURI() const
1255 const AtomicString& baseAttribute = fastGetAttribute(baseAttr);
1256 KURL base(KURL(), baseAttribute);
1257 if (!base.protocol().isEmpty())
1260 ContainerNode* parent = parentNode();
1264 const KURL& parentBase = parent->baseURI();
1265 if (parentBase.isNull())
1268 return KURL(parentBase, baseAttribute);
1271 const AtomicString Element::imageSourceURL() const
1273 return getAttribute(srcAttr);
1276 bool Element::rendererIsNeeded(const RenderStyle& style)
1278 return style.display() != NONE;
1281 RenderObject* Element::createRenderer(RenderStyle* style)
1283 return RenderObject::createObject(this, style);
1286 Node::InsertionNotificationRequest Element::insertedInto(ContainerNode* insertionPoint)
1288 // need to do superclass processing first so inDocument() is true
1289 // by the time we reach updateId
1290 ContainerNode::insertedInto(insertionPoint);
1292 if (containsFullScreenElement() && parentElement() && !parentElement()->containsFullScreenElement())
1293 setContainsFullScreenElementOnAncestorsCrossingFrameBoundaries(true);
1295 ASSERT(!hasRareData() || !elementRareData()->hasPseudoElements());
1297 if (!insertionPoint->isInTreeScope())
1298 return InsertionDone;
1301 elementRareData()->clearClassListValueForQuirksMode();
1303 if (isUpgradedCustomElement() && inDocument())
1304 CustomElement::didEnterDocument(this, document());
1306 TreeScope& scope = insertionPoint->treeScope();
1307 if (scope != treeScope())
1308 return InsertionDone;
1310 const AtomicString& idValue = getIdAttribute();
1311 if (!idValue.isNull())
1312 updateId(scope, nullAtom, idValue);
1314 const AtomicString& nameValue = getNameAttribute();
1315 if (!nameValue.isNull())
1316 updateName(nullAtom, nameValue);
1318 if (isHTMLLabelElement(*this)) {
1319 if (scope.shouldCacheLabelsByForAttribute())
1320 updateLabel(scope, nullAtom, fastGetAttribute(forAttr));
1323 if (parentElement() && parentElement()->isInCanvasSubtree())
1324 setIsInCanvasSubtree(true);
1326 return InsertionDone;
1329 void Element::removedFrom(ContainerNode* insertionPoint)
1331 bool wasInDocument = insertionPoint->inDocument();
1333 ASSERT(!hasRareData() || !elementRareData()->hasPseudoElements());
1335 if (containsFullScreenElement())
1336 setContainsFullScreenElementOnAncestorsCrossingFrameBoundaries(false);
1338 if (document().page())
1339 document().page()->pointerLockController().elementRemoved(this);
1341 setSavedLayerScrollOffset(IntSize());
1343 if (insertionPoint->isInTreeScope() && treeScope() == document()) {
1344 const AtomicString& idValue = getIdAttribute();
1345 if (!idValue.isNull())
1346 updateId(insertionPoint->treeScope(), idValue, nullAtom);
1348 const AtomicString& nameValue = getNameAttribute();
1349 if (!nameValue.isNull())
1350 updateName(nameValue, nullAtom);
1352 if (isHTMLLabelElement(*this)) {
1353 TreeScope& treeScope = insertionPoint->treeScope();
1354 if (treeScope.shouldCacheLabelsByForAttribute())
1355 updateLabel(treeScope, fastGetAttribute(forAttr), nullAtom);
1359 ContainerNode::removedFrom(insertionPoint);
1360 if (wasInDocument) {
1361 if (hasPendingResources())
1362 document().accessSVGExtensions().removeElementFromPendingResources(this);
1364 if (isUpgradedCustomElement())
1365 CustomElement::didLeaveDocument(this, insertionPoint->document());
1368 document().removeFromTopLayer(this);
1370 clearElementFlag(IsInCanvasSubtree);
1373 void Element::attach(const AttachContext& context)
1375 ASSERT(document().inStyleRecalc());
1377 // We've already been through detach when doing an attach, but we might
1378 // need to clear any state that's been added since then.
1379 if (hasRareData() && styleChangeType() == NeedsReattachStyleChange) {
1380 ElementRareData* data = elementRareData();
1381 data->clearComputedStyle();
1382 data->clearRestyleFlags();
1383 // Only clear the style state if we're not going to reuse the style from recalcStyle.
1384 if (!context.resolvedStyle)
1385 data->resetStyleState();
1388 RenderTreeBuilder(this, context.resolvedStyle).createRendererForElementIfNeeded();
1390 addCallbackSelectors();
1392 StyleResolverParentScope parentScope(*this);
1394 createPseudoElementIfNeeded(BEFORE);
1396 // When a shadow root exists, it does the work of attaching the children.
1397 if (ElementShadow* shadow = this->shadow())
1398 shadow->attach(context);
1400 ContainerNode::attach(context);
1402 createPseudoElementIfNeeded(AFTER);
1403 createPseudoElementIfNeeded(BACKDROP);
1405 if (hasRareData() && !renderer()) {
1406 if (ActiveAnimations* activeAnimations = elementRareData()->activeAnimations()) {
1407 activeAnimations->cssAnimations().cancel();
1408 activeAnimations->setAnimationStyleChange(false);
1413 void Element::detach(const AttachContext& context)
1415 HTMLFrameOwnerElement::UpdateSuspendScope suspendWidgetHierarchyUpdates;
1416 cancelFocusAppearanceUpdate();
1417 removeCallbackSelectors();
1418 if (needsLayerUpdate())
1419 document().unscheduleLayerUpdate(*this);
1420 if (hasRareData()) {
1421 ElementRareData* data = elementRareData();
1422 data->clearPseudoElements();
1424 // attach() will perform the below steps for us when inside recalcStyle.
1425 if (!document().inStyleRecalc()) {
1426 data->resetStyleState();
1427 data->clearComputedStyle();
1428 data->clearRestyleFlags();
1431 if (ActiveAnimations* activeAnimations = data->activeAnimations()) {
1432 if (context.performingReattach) {
1433 // FIXME: We call detach from within style recalc, so compositingState is not up to date.
1434 // https://code.google.com/p/chromium/issues/detail?id=339847
1435 DisableCompositingQueryAsserts disabler;
1437 // FIXME: restart compositor animations rather than pull back to the main thread
1438 activeAnimations->cancelAnimationOnCompositor();
1440 activeAnimations->cssAnimations().cancel();
1441 activeAnimations->setAnimationStyleChange(false);
1445 if (ElementShadow* shadow = data->shadow())
1446 shadow->detach(context);
1448 ContainerNode::detach(context);
1451 bool Element::pseudoStyleCacheIsInvalid(const RenderStyle* currentStyle, RenderStyle* newStyle)
1453 ASSERT(currentStyle == renderStyle());
1459 const PseudoStyleCache* pseudoStyleCache = currentStyle->cachedPseudoStyles();
1460 if (!pseudoStyleCache)
1463 size_t cacheSize = pseudoStyleCache->size();
1464 for (size_t i = 0; i < cacheSize; ++i) {
1465 RefPtr<RenderStyle> newPseudoStyle;
1466 PseudoId pseudoId = pseudoStyleCache->at(i)->styleType();
1467 if (pseudoId == FIRST_LINE || pseudoId == FIRST_LINE_INHERITED)
1468 newPseudoStyle = renderer()->uncachedFirstLineStyle(newStyle);
1470 newPseudoStyle = renderer()->getUncachedPseudoStyle(PseudoStyleRequest(pseudoId), newStyle, newStyle);
1471 if (!newPseudoStyle)
1473 if (*newPseudoStyle != *pseudoStyleCache->at(i)) {
1474 if (pseudoId < FIRST_INTERNAL_PSEUDOID)
1475 newStyle->setHasPseudoStyle(pseudoId);
1476 newStyle->addCachedPseudoStyle(newPseudoStyle);
1477 if (pseudoId == FIRST_LINE || pseudoId == FIRST_LINE_INHERITED) {
1478 // FIXME: We should do an actual diff to determine whether a repaint vs. layout
1479 // is needed, but for now just assume a layout will be required. The diff code
1480 // in RenderObject::setStyle would need to be factored out so that it could be reused.
1481 renderer()->setNeedsLayoutAndPrefWidthsRecalc();
1489 PassRefPtr<RenderStyle> Element::styleForRenderer()
1491 ASSERT(document().inStyleRecalc());
1493 RefPtr<RenderStyle> style;
1495 // FIXME: Instead of clearing updates that may have been added from calls to styleForElement
1496 // outside recalcStyle, we should just never set them if we're not inside recalcStyle.
1497 if (ActiveAnimations* activeAnimations = this->activeAnimations())
1498 activeAnimations->cssAnimations().setPendingUpdate(nullptr);
1500 if (hasCustomStyleCallbacks())
1501 style = customStyleForRenderer();
1503 style = originalStyleForRenderer();
1506 // styleForElement() might add active animations so we need to get it again.
1507 if (ActiveAnimations* activeAnimations = this->activeAnimations()) {
1508 activeAnimations->cssAnimations().maybeApplyPendingUpdate(this);
1509 activeAnimations->updateAnimationFlags(*style);
1512 document().didRecalculateStyleForElement();
1513 return style.release();
1516 PassRefPtr<RenderStyle> Element::originalStyleForRenderer()
1518 ASSERT(document().inStyleRecalc());
1519 return document().ensureStyleResolver().styleForElement(this);
1522 void Element::recalcStyle(StyleRecalcChange change, Text* nextTextSibling)
1524 ASSERT(document().inStyleRecalc());
1525 ASSERT(!parentOrShadowHostNode()->needsStyleRecalc());
1527 if (hasCustomStyleCallbacks())
1528 willRecalcStyle(change);
1530 if (change >= Inherit || needsStyleRecalc()) {
1531 if (hasRareData()) {
1532 ElementRareData* data = elementRareData();
1533 data->resetStyleState();
1534 data->clearComputedStyle();
1536 if (change >= Inherit) {
1537 if (ActiveAnimations* activeAnimations = data->activeAnimations())
1538 activeAnimations->setAnimationStyleChange(false);
1541 if (parentRenderStyle())
1542 change = recalcOwnStyle(change);
1543 clearNeedsStyleRecalc();
1546 // If we reattached we don't need to recalc the style of our descendants anymore.
1547 if ((change >= UpdatePseudoElements && change < Reattach) || childNeedsStyleRecalc()) {
1548 recalcChildStyle(change);
1549 clearChildNeedsStyleRecalc();
1552 if (hasCustomStyleCallbacks())
1553 didRecalcStyle(change);
1555 if (change == Reattach)
1556 reattachWhitespaceSiblings(nextTextSibling);
1559 StyleRecalcChange Element::recalcOwnStyle(StyleRecalcChange change)
1561 ASSERT(document().inStyleRecalc());
1562 ASSERT(!parentOrShadowHostNode()->needsStyleRecalc());
1563 ASSERT(change >= Inherit || needsStyleRecalc());
1564 ASSERT(parentRenderStyle());
1566 RefPtr<RenderStyle> oldStyle = renderStyle();
1567 RefPtr<RenderStyle> newStyle = styleForRenderer();
1568 StyleRecalcChange localChange = RenderStyle::stylePropagationDiff(oldStyle.get(), newStyle.get());
1572 if (localChange == Reattach) {
1573 AttachContext reattachContext;
1574 reattachContext.resolvedStyle = newStyle.get();
1575 bool rendererWillChange = needsAttach() || renderer();
1576 reattach(reattachContext);
1577 if (rendererWillChange || renderer())
1579 return ReattachNoRenderer;
1584 if (localChange != NoChange)
1585 updateCallbackSelectors(oldStyle.get(), newStyle.get());
1587 if (RenderObject* renderer = this->renderer()) {
1588 if (localChange != NoChange || pseudoStyleCacheIsInvalid(oldStyle.get(), newStyle.get()) || needsLayerUpdate()) {
1589 renderer->setStyle(newStyle.get());
1591 // Although no change occurred, we use the new style so that the cousin style sharing code won't get
1592 // fooled into believing this style is the same.
1593 // FIXME: We may be able to remove this hack, see discussion in
1594 // https://codereview.chromium.org/30453002/
1595 renderer->setStyleInternal(newStyle.get());
1599 if (styleChangeType() >= SubtreeStyleChange)
1602 if (change > Inherit || localChange > Inherit)
1603 return max(localChange, change);
1605 if (localChange < Inherit && (oldStyle->hasPseudoElementStyle() || newStyle->hasPseudoElementStyle()))
1606 return UpdatePseudoElements;
1611 void Element::recalcChildStyle(StyleRecalcChange change)
1613 ASSERT(document().inStyleRecalc());
1614 ASSERT(change >= UpdatePseudoElements || childNeedsStyleRecalc());
1615 ASSERT(!needsStyleRecalc());
1617 StyleResolverParentScope parentScope(*this);
1619 updatePseudoElement(BEFORE, change);
1621 if (change > UpdatePseudoElements || childNeedsStyleRecalc()) {
1622 for (ShadowRoot* root = youngestShadowRoot(); root; root = root->olderShadowRoot()) {
1623 if (root->shouldCallRecalcStyle(change))
1624 root->recalcStyle(change);
1628 if (change < Force && hasRareData() && childNeedsStyleRecalc())
1629 checkForChildrenAdjacentRuleChanges();
1631 if (change > UpdatePseudoElements || childNeedsStyleRecalc()) {
1632 // This loop is deliberately backwards because we use insertBefore in the rendering tree, and want to avoid
1633 // a potentially n^2 loop to find the insertion point while resolving style. Having us start from the last
1634 // child and work our way back means in the common case, we'll find the insertion point in O(1) time.
1635 // See crbug.com/288225
1636 StyleResolver& styleResolver = document().ensureStyleResolver();
1637 Text* lastTextNode = 0;
1638 for (Node* child = lastChild(); child; child = child->previousSibling()) {
1639 if (child->isTextNode()) {
1640 toText(child)->recalcTextStyle(change, lastTextNode);
1641 lastTextNode = toText(child);
1642 } else if (child->isElementNode()) {
1643 Element* element = toElement(child);
1644 if (element->shouldCallRecalcStyle(change))
1645 element->recalcStyle(change, lastTextNode);
1646 else if (element->supportsStyleSharing())
1647 styleResolver.addToStyleSharingList(*element);
1648 if (element->renderer())
1654 updatePseudoElement(AFTER, change);
1655 updatePseudoElement(BACKDROP, change);
1658 void Element::updateCallbackSelectors(RenderStyle* oldStyle, RenderStyle* newStyle)
1660 Vector<String> emptyVector;
1661 const Vector<String>& oldCallbackSelectors = oldStyle ? oldStyle->callbackSelectors() : emptyVector;
1662 const Vector<String>& newCallbackSelectors = newStyle ? newStyle->callbackSelectors() : emptyVector;
1663 if (oldCallbackSelectors.isEmpty() && newCallbackSelectors.isEmpty())
1665 if (oldCallbackSelectors != newCallbackSelectors)
1666 CSSSelectorWatch::from(document()).updateSelectorMatches(oldCallbackSelectors, newCallbackSelectors);
1669 void Element::addCallbackSelectors()
1671 updateCallbackSelectors(0, renderStyle());
1674 void Element::removeCallbackSelectors()
1676 updateCallbackSelectors(renderStyle(), 0);
1679 ElementShadow* Element::shadow() const
1681 return hasRareData() ? elementRareData()->shadow() : 0;
1684 ElementShadow& Element::ensureShadow()
1686 return ensureElementRareData().ensureShadow();
1689 void Element::didAffectSelector(AffectedSelectorMask mask)
1691 setNeedsStyleRecalc(SubtreeStyleChange);
1692 if (ElementShadow* elementShadow = shadowWhereNodeCanBeDistributed(*this))
1693 elementShadow->didAffectSelector(mask);
1696 void Element::setAnimationStyleChange(bool animationStyleChange)
1698 if (animationStyleChange && document().inStyleRecalc())
1700 if (ActiveAnimations* activeAnimations = elementRareData()->activeAnimations())
1701 activeAnimations->setAnimationStyleChange(animationStyleChange);
1704 void Element::setNeedsAnimationStyleRecalc()
1706 if (styleChangeType() != NoStyleChange)
1709 setNeedsStyleRecalc(LocalStyleChange);
1710 setAnimationStyleChange(true);
1713 void Element::setNeedsCompositingUpdate()
1715 if (!document().isActive())
1717 RenderBoxModelObject* renderer = renderBoxModelObject();
1720 if (!renderer->hasLayer())
1722 renderer->layer()->setNeedsToUpdateAncestorDependentProperties();
1723 document().renderView()->compositor()->setNeedsCompositingUpdate(CompositingUpdateAfterCompositingInputChange);
1726 void Element::setCustomElementDefinition(PassRefPtr<CustomElementDefinition> definition)
1728 if (!hasRareData() && !definition)
1730 ASSERT(!customElementDefinition());
1731 ensureElementRareData().setCustomElementDefinition(definition);
1734 CustomElementDefinition* Element::customElementDefinition() const
1737 return elementRareData()->customElementDefinition();
1741 PassRefPtr<ShadowRoot> Element::createShadowRoot(ExceptionState& exceptionState)
1743 if (alwaysCreateUserAgentShadowRoot())
1744 ensureUserAgentShadowRoot();
1746 // Some elements make assumptions about what kind of renderers they allow
1747 // as children so we can't allow author shadows on them for now. An override
1748 // flag is provided for testing how author shadows interact on these elements.
1749 if (!areAuthorShadowsAllowed() && !RuntimeEnabledFeatures::authorShadowDOMForAnyElementEnabled()) {
1750 exceptionState.throwDOMException(HierarchyRequestError, "Author-created shadow roots are disabled for this element.");
1754 return PassRefPtr<ShadowRoot>(ensureShadow().addShadowRoot(*this, ShadowRoot::AuthorShadowRoot));
1757 ShadowRoot* Element::shadowRoot() const
1759 ElementShadow* elementShadow = shadow();
1762 ShadowRoot* shadowRoot = elementShadow->youngestShadowRoot();
1763 if (shadowRoot->type() == ShadowRoot::AuthorShadowRoot)
1768 ShadowRoot* Element::userAgentShadowRoot() const
1770 if (ElementShadow* elementShadow = shadow()) {
1771 if (ShadowRoot* shadowRoot = elementShadow->oldestShadowRoot()) {
1772 ASSERT(shadowRoot->type() == ShadowRoot::UserAgentShadowRoot);
1780 ShadowRoot& Element::ensureUserAgentShadowRoot()
1782 if (ShadowRoot* shadowRoot = userAgentShadowRoot())
1784 ShadowRoot& shadowRoot = ensureShadow().addShadowRoot(*this, ShadowRoot::UserAgentShadowRoot);
1785 didAddUserAgentShadowRoot(shadowRoot);
1789 bool Element::childTypeAllowed(NodeType type) const
1795 case PROCESSING_INSTRUCTION_NODE:
1796 case CDATA_SECTION_NODE:
1804 void Element::checkForEmptyStyleChange()
1806 RenderStyle* style = renderStyle();
1808 if (!style && !styleAffectedByEmpty())
1811 if (!style || (styleAffectedByEmpty() && (!style->emptyState() || hasChildren())))
1812 setNeedsStyleRecalc(SubtreeStyleChange);
1815 void Element::childrenChanged(bool changedByParser, Node* beforeChange, Node* afterChange, int childCountDelta)
1817 ContainerNode::childrenChanged(changedByParser, beforeChange, afterChange, childCountDelta);
1819 checkForEmptyStyleChange();
1820 if (!changedByParser)
1821 checkForSiblingStyleChanges(false, beforeChange, afterChange, childCountDelta);
1823 if (ElementShadow* shadow = this->shadow())
1824 shadow->setNeedsDistributionRecalc();
1827 void Element::finishParsingChildren()
1829 setIsFinishedParsingChildren(true);
1830 checkForEmptyStyleChange();
1831 checkForSiblingStyleChanges(true, lastChild(), 0, 0);
1835 void Element::formatForDebugger(char* buffer, unsigned length) const
1837 StringBuilder result;
1840 result.append(nodeName());
1842 s = getIdAttribute();
1843 if (s.length() > 0) {
1844 if (result.length() > 0)
1845 result.appendLiteral("; ");
1846 result.appendLiteral("id=");
1850 s = getAttribute(classAttr);
1851 if (s.length() > 0) {
1852 if (result.length() > 0)
1853 result.appendLiteral("; ");
1854 result.appendLiteral("class=");
1858 strncpy(buffer, result.toString().utf8().data(), length - 1);
1862 const Vector<RefPtr<Attr> >& Element::attrNodeList()
1864 ASSERT(hasSyntheticAttrChildNodes());
1865 return *attrNodeListForElement(this);
1868 PassRefPtr<Attr> Element::setAttributeNode(Attr* attrNode, ExceptionState& exceptionState)
1871 exceptionState.throwDOMException(TypeMismatchError, ExceptionMessages::argumentNullOrIncorrectType(1, "Attr"));
1875 RefPtr<Attr> oldAttrNode = attrIfExists(attrNode->qualifiedName());
1876 if (oldAttrNode.get() == attrNode)
1877 return attrNode; // This Attr is already attached to the element.
1879 // InUseAttributeError: Raised if node is an Attr that is already an attribute of another Element object.
1880 // The DOM user must explicitly clone Attr nodes to re-use them in other elements.
1881 if (attrNode->ownerElement()) {
1882 exceptionState.throwDOMException(InUseAttributeError, "The node provided is an attribute node that is already an attribute of another Element; attribute nodes must be explicitly cloned.");
1886 synchronizeAllAttributes();
1887 UniqueElementData& elementData = ensureUniqueElementData();
1889 size_t index = elementData.getAttributeItemIndex(attrNode->qualifiedName(), shouldIgnoreAttributeCase());
1890 if (index != kNotFound) {
1892 detachAttrNodeFromElementWithValue(oldAttrNode.get(), elementData.attributeItem(index).value());
1894 oldAttrNode = Attr::create(document(), attrNode->qualifiedName(), elementData.attributeItem(index).value());
1897 setAttributeInternal(index, attrNode->qualifiedName(), attrNode->value(), NotInSynchronizationOfLazyAttribute);
1899 attrNode->attachToElement(this);
1900 treeScope().adoptIfNeeded(*attrNode);
1901 ensureAttrNodeListForElement(this).append(attrNode);
1903 return oldAttrNode.release();
1906 PassRefPtr<Attr> Element::setAttributeNodeNS(Attr* attr, ExceptionState& exceptionState)
1908 return setAttributeNode(attr, exceptionState);
1911 PassRefPtr<Attr> Element::removeAttributeNode(Attr* attr, ExceptionState& exceptionState)
1914 exceptionState.throwDOMException(TypeMismatchError, ExceptionMessages::argumentNullOrIncorrectType(1, "Attr"));
1917 if (attr->ownerElement() != this) {
1918 exceptionState.throwDOMException(NotFoundError, "The node provided is owned by another element.");
1922 ASSERT(document() == attr->document());
1924 synchronizeAttribute(attr->qualifiedName());
1926 size_t index = elementData()->getAttrIndex(attr);
1927 if (index == kNotFound) {
1928 exceptionState.throwDOMException(NotFoundError, "The attribute was not found on this element.");
1932 RefPtr<Attr> guard(attr);
1933 detachAttrNodeAtIndex(attr, index);
1934 return guard.release();
1937 void Element::parseAttribute(const QualifiedName& name, const AtomicString& value)
1939 if (name == tabindexAttr) {
1941 if (value.isEmpty()) {
1942 clearTabIndexExplicitlyIfNeeded();
1943 if (treeScope().adjustedFocusedElement() == this) {
1944 // We might want to call blur(), but it's dangerous to dispatch
1946 document().setNeedsFocusedElementCheck();
1948 } else if (parseHTMLInteger(value, tabindex)) {
1949 // Clamp tabindex to the range of 'short' to match Firefox's behavior.
1950 setTabIndexExplicitly(max(static_cast<int>(std::numeric_limits<short>::min()), std::min(tabindex, static_cast<int>(std::numeric_limits<short>::max()))));
1955 bool Element::parseAttributeName(QualifiedName& out, const AtomicString& namespaceURI, const AtomicString& qualifiedName, ExceptionState& exceptionState)
1957 AtomicString prefix, localName;
1958 if (!Document::parseQualifiedName(qualifiedName, prefix, localName, exceptionState))
1960 ASSERT(!exceptionState.hadException());
1962 QualifiedName qName(prefix, localName, namespaceURI);
1964 if (!Document::hasValidNamespaceForAttributes(qName)) {
1965 exceptionState.throwDOMException(NamespaceError, "'" + namespaceURI + "' is an invalid namespace for attributes.");
1973 void Element::setAttributeNS(const AtomicString& namespaceURI, const AtomicString& qualifiedName, const AtomicString& value, ExceptionState& exceptionState)
1975 QualifiedName parsedName = anyName;
1976 if (!parseAttributeName(parsedName, namespaceURI, qualifiedName, exceptionState))
1978 setAttribute(parsedName, value);
1981 void Element::removeAttributeInternal(size_t index, SynchronizationOfLazyAttribute inSynchronizationOfLazyAttribute)
1983 ASSERT_WITH_SECURITY_IMPLICATION(index < attributeCount());
1985 UniqueElementData& elementData = ensureUniqueElementData();
1987 QualifiedName name = elementData.attributeItem(index).name();
1988 AtomicString valueBeingRemoved = elementData.attributeItem(index).value();
1990 if (!inSynchronizationOfLazyAttribute) {
1991 if (!valueBeingRemoved.isNull())
1992 willModifyAttribute(name, valueBeingRemoved, nullAtom);
1995 if (RefPtr<Attr> attrNode = attrIfExists(name))
1996 detachAttrNodeFromElementWithValue(attrNode.get(), elementData.attributeItem(index).value());
1998 elementData.removeAttribute(index);
2000 if (!inSynchronizationOfLazyAttribute)
2001 didRemoveAttribute(name);
2004 void Element::addAttributeInternal(const QualifiedName& name, const AtomicString& value, SynchronizationOfLazyAttribute inSynchronizationOfLazyAttribute)
2006 if (!inSynchronizationOfLazyAttribute)
2007 willModifyAttribute(name, nullAtom, value);
2008 ensureUniqueElementData().addAttribute(name, value);
2009 if (!inSynchronizationOfLazyAttribute)
2010 didAddAttribute(name, value);
2013 void Element::removeAttribute(const AtomicString& name)
2018 AtomicString localName = shouldIgnoreAttributeCase() ? name.lower() : name;
2019 size_t index = elementData()->getAttributeItemIndex(localName, false);
2020 if (index == kNotFound) {
2021 if (UNLIKELY(localName == styleAttr) && elementData()->m_styleAttributeIsDirty && isStyledElement())
2022 removeAllInlineStyleProperties();
2026 removeAttributeInternal(index, NotInSynchronizationOfLazyAttribute);
2029 void Element::removeAttributeNS(const AtomicString& namespaceURI, const AtomicString& localName)
2031 removeAttribute(QualifiedName(nullAtom, localName, namespaceURI));
2034 PassRefPtr<Attr> Element::getAttributeNode(const AtomicString& localName)
2038 synchronizeAttribute(localName);
2039 const Attribute* attribute = elementData()->getAttributeItem(localName, shouldIgnoreAttributeCase());
2042 return ensureAttr(attribute->name());
2045 PassRefPtr<Attr> Element::getAttributeNodeNS(const AtomicString& namespaceURI, const AtomicString& localName)
2049 QualifiedName qName(nullAtom, localName, namespaceURI);
2050 synchronizeAttribute(qName);
2051 const Attribute* attribute = elementData()->getAttributeItem(qName);
2054 return ensureAttr(attribute->name());
2057 bool Element::hasAttribute(const AtomicString& localName) const
2061 synchronizeAttribute(localName);
2062 return elementData()->getAttributeItem(shouldIgnoreAttributeCase() ? localName.lower() : localName, false);
2065 bool Element::hasAttributeNS(const AtomicString& namespaceURI, const AtomicString& localName) const
2069 QualifiedName qName(nullAtom, localName, namespaceURI);
2070 synchronizeAttribute(qName);
2071 return elementData()->getAttributeItem(qName);
2074 void Element::focus(bool restorePreviousSelection, FocusType type)
2079 if (document().focusedElement() == this)
2082 if (!document().isActive())
2085 document().updateLayoutIgnorePendingStylesheets();
2089 RefPtr<Node> protect(this);
2090 if (!document().page()->focusController().setFocusedElement(this, document().frame(), type))
2093 // Setting the focused node above might have invalidated the layout due to scripts.
2094 document().updateLayoutIgnorePendingStylesheets();
2098 cancelFocusAppearanceUpdate();
2099 updateFocusAppearance(restorePreviousSelection);
2102 void Element::updateFocusAppearance(bool /*restorePreviousSelection*/)
2104 if (isRootEditableElement()) {
2105 // Taking the ownership since setSelection() may release the last reference to |frame|.
2106 RefPtr<LocalFrame> frame(document().frame());
2110 // When focusing an editable element in an iframe, don't reset the selection if it already contains a selection.
2111 if (this == frame->selection().rootEditableElement())
2114 // FIXME: We should restore the previous selection if there is one.
2115 VisibleSelection newSelection = VisibleSelection(firstPositionInOrBeforeNode(this), DOWNSTREAM);
2116 frame->selection().setSelection(newSelection);
2117 frame->selection().revealSelection();
2118 } else if (renderer() && !renderer()->isWidget())
2119 renderer()->scrollRectToVisible(boundingBox());
2122 void Element::blur()
2124 cancelFocusAppearanceUpdate();
2125 if (treeScope().adjustedFocusedElement() == this) {
2126 Document& doc = document();
2128 doc.page()->focusController().setFocusedElement(0, doc.frame());
2130 doc.setFocusedElement(nullptr);
2134 bool Element::supportsFocus() const
2136 // FIXME: supportsFocus() can be called when layout is not up to date.
2137 // Logic that deals with the renderer should be moved to rendererIsFocusable().
2138 // But supportsFocus must return true when the element is editable, or else
2139 // it won't be focusable. Furthermore, supportsFocus cannot just return true
2140 // always or else tabIndex() will change for all HTML elements.
2141 return hasElementFlag(TabIndexWasSetExplicitly) || (rendererIsEditable() && parentNode() && !parentNode()->rendererIsEditable())
2142 || supportsSpatialNavigationFocus();
2145 bool Element::supportsSpatialNavigationFocus() const
2147 // This function checks whether the element satisfies the extended criteria
2148 // for the element to be focusable, introduced by spatial navigation feature,
2149 // i.e. checks if click or keyboard event handler is specified.
2150 // This is the way to make it possible to navigate to (focus) elements
2151 // which web designer meant for being active (made them respond to click events).
2153 if (!document().settings() || !document().settings()->spatialNavigationEnabled())
2155 return hasEventListeners(EventTypeNames::click)
2156 || hasEventListeners(EventTypeNames::keydown)
2157 || hasEventListeners(EventTypeNames::keypress)
2158 || hasEventListeners(EventTypeNames::keyup);
2161 bool Element::isFocusable() const
2163 return inDocument() && supportsFocus() && !isInert() && rendererIsFocusable();
2166 bool Element::isKeyboardFocusable() const
2168 return isFocusable() && tabIndex() >= 0;
2171 bool Element::isMouseFocusable() const
2173 return isFocusable();
2176 void Element::dispatchFocusEvent(Element* oldFocusedElement, FocusType)
2178 RefPtrWillBeRawPtr<FocusEvent> event = FocusEvent::create(EventTypeNames::focus, false, false, document().domWindow(), 0, oldFocusedElement);
2179 EventDispatcher::dispatchEvent(this, FocusEventDispatchMediator::create(event.release()));
2182 void Element::dispatchBlurEvent(Element* newFocusedElement)
2184 RefPtrWillBeRawPtr<FocusEvent> event = FocusEvent::create(EventTypeNames::blur, false, false, document().domWindow(), 0, newFocusedElement);
2185 EventDispatcher::dispatchEvent(this, BlurEventDispatchMediator::create(event.release()));
2188 void Element::dispatchFocusInEvent(const AtomicString& eventType, Element* oldFocusedElement)
2190 ASSERT(!NoEventDispatchAssertion::isEventDispatchForbidden());
2191 ASSERT(eventType == EventTypeNames::focusin || eventType == EventTypeNames::DOMFocusIn);
2192 dispatchScopedEventDispatchMediator(FocusInEventDispatchMediator::create(FocusEvent::create(eventType, true, false, document().domWindow(), 0, oldFocusedElement)));
2195 void Element::dispatchFocusOutEvent(const AtomicString& eventType, Element* newFocusedElement)
2197 ASSERT(!NoEventDispatchAssertion::isEventDispatchForbidden());
2198 ASSERT(eventType == EventTypeNames::focusout || eventType == EventTypeNames::DOMFocusOut);
2199 dispatchScopedEventDispatchMediator(FocusOutEventDispatchMediator::create(FocusEvent::create(eventType, true, false, document().domWindow(), 0, newFocusedElement)));
2202 String Element::innerHTML() const
2204 return createMarkup(this, ChildrenOnly);
2207 String Element::outerHTML() const
2209 return createMarkup(this);
2212 void Element::setInnerHTML(const String& html, ExceptionState& exceptionState)
2214 if (RefPtr<DocumentFragment> fragment = createFragmentForInnerOuterHTML(html, this, AllowScriptingContent, "innerHTML", exceptionState)) {
2215 ContainerNode* container = this;
2216 if (isHTMLTemplateElement(*this))
2217 container = toHTMLTemplateElement(this)->content();
2218 replaceChildrenWithFragment(container, fragment.release(), exceptionState);
2222 void Element::setOuterHTML(const String& html, ExceptionState& exceptionState)
2224 Node* p = parentNode();
2226 exceptionState.throwDOMException(NoModificationAllowedError, "This element has no parent node.");
2229 if (!p->isElementNode()) {
2230 exceptionState.throwDOMException(NoModificationAllowedError, "This element's parent is of type '" + p->nodeName() + "', which is not an element node.");
2234 RefPtr<Element> parent = toElement(p);
2235 RefPtr<Node> prev = previousSibling();
2236 RefPtr<Node> next = nextSibling();
2238 RefPtr<DocumentFragment> fragment = createFragmentForInnerOuterHTML(html, parent.get(), AllowScriptingContent, "outerHTML", exceptionState);
2239 if (exceptionState.hadException())
2242 parent->replaceChild(fragment.release(), this, exceptionState);
2243 RefPtr<Node> node = next ? next->previousSibling() : 0;
2244 if (!exceptionState.hadException() && node && node->isTextNode())
2245 mergeWithNextTextNode(node.release(), exceptionState);
2247 if (!exceptionState.hadException() && prev && prev->isTextNode())
2248 mergeWithNextTextNode(prev.release(), exceptionState);
2251 Node* Element::insertAdjacent(const String& where, Node* newChild, ExceptionState& exceptionState)
2253 if (equalIgnoringCase(where, "beforeBegin")) {
2254 if (ContainerNode* parent = this->parentNode()) {
2255 parent->insertBefore(newChild, this, exceptionState);
2256 if (!exceptionState.hadException())
2262 if (equalIgnoringCase(where, "afterBegin")) {
2263 insertBefore(newChild, firstChild(), exceptionState);
2264 return exceptionState.hadException() ? 0 : newChild;
2267 if (equalIgnoringCase(where, "beforeEnd")) {
2268 appendChild(newChild, exceptionState);
2269 return exceptionState.hadException() ? 0 : newChild;
2272 if (equalIgnoringCase(where, "afterEnd")) {
2273 if (ContainerNode* parent = this->parentNode()) {
2274 parent->insertBefore(newChild, nextSibling(), exceptionState);
2275 if (!exceptionState.hadException())
2281 exceptionState.throwDOMException(SyntaxError, "The value provided ('" + where + "') is not one of 'beforeBegin', 'afterBegin', 'beforeEnd', or 'afterEnd'.");
2285 // Step 1 of http://domparsing.spec.whatwg.org/#insertadjacenthtml()
2286 static Element* contextElementForInsertion(const String& where, Element* element, ExceptionState& exceptionState)
2288 if (equalIgnoringCase(where, "beforeBegin") || equalIgnoringCase(where, "afterEnd")) {
2289 ContainerNode* parent = element->parentNode();
2290 if (!parent || !parent->isElementNode()) {
2291 exceptionState.throwDOMException(NoModificationAllowedError, "The element has no parent.");
2294 return toElement(parent);
2296 if (equalIgnoringCase(where, "afterBegin") || equalIgnoringCase(where, "beforeEnd"))
2298 exceptionState.throwDOMException(SyntaxError, "The value provided ('" + where + "') is not one of 'beforeBegin', 'afterBegin', 'beforeEnd', or 'afterEnd'.");
2302 Element* Element::insertAdjacentElement(const String& where, Element* newChild, ExceptionState& exceptionState)
2305 // IE throws COM Exception E_INVALIDARG; this is the best DOM exception alternative.
2306 exceptionState.throwTypeError("The node provided is null.");
2310 Node* returnValue = insertAdjacent(where, newChild, exceptionState);
2311 return toElement(returnValue);
2314 void Element::insertAdjacentText(const String& where, const String& text, ExceptionState& exceptionState)
2316 RefPtr<Text> textNode = document().createTextNode(text);
2317 insertAdjacent(where, textNode.get(), exceptionState);
2320 void Element::insertAdjacentHTML(const String& where, const String& markup, ExceptionState& exceptionState)
2322 RefPtr<Element> contextElement = contextElementForInsertion(where, this, exceptionState);
2323 if (!contextElement)
2326 RefPtr<DocumentFragment> fragment = createFragmentForInnerOuterHTML(markup, contextElement.get(), AllowScriptingContent, "insertAdjacentHTML", exceptionState);
2329 insertAdjacent(where, fragment.get(), exceptionState);
2332 String Element::innerText()
2334 // We need to update layout, since plainText uses line boxes in the render tree.
2335 document().updateLayoutIgnorePendingStylesheets();
2338 return textContent(true);
2340 return plainText(rangeOfContents(const_cast<Element*>(this)).get());
2343 String Element::outerText()
2345 // Getting outerText is the same as getting innerText, only
2346 // setting is different. You would think this should get the plain
2347 // text for the outer range, but this is wrong, <br> for instance
2348 // would return different values for inner and outer text by such
2349 // a rule, but it doesn't in WinIE, and we want to match that.
2353 String Element::textFromChildren()
2355 Text* firstTextNode = 0;
2356 bool foundMultipleTextNodes = false;
2357 unsigned totalLength = 0;
2359 for (Node* child = firstChild(); child; child = child->nextSibling()) {
2360 if (!child->isTextNode())
2362 Text* text = toText(child);
2364 firstTextNode = text;
2366 foundMultipleTextNodes = true;
2367 unsigned length = text->data().length();
2368 if (length > std::numeric_limits<unsigned>::max() - totalLength)
2369 return emptyString();
2370 totalLength += length;
2374 return emptyString();
2376 if (firstTextNode && !foundMultipleTextNodes) {
2377 firstTextNode->atomize();
2378 return firstTextNode->data();
2381 StringBuilder content;
2382 content.reserveCapacity(totalLength);
2383 for (Node* child = firstTextNode; child; child = child->nextSibling()) {
2384 if (!child->isTextNode())
2386 content.append(toText(child)->data());
2389 ASSERT(content.length() == totalLength);
2390 return content.toString();
2393 const AtomicString& Element::shadowPseudoId() const
2395 if (ShadowRoot* root = containingShadowRoot()) {
2396 if (root->type() == ShadowRoot::UserAgentShadowRoot)
2397 return fastGetAttribute(pseudoAttr);
2402 void Element::setShadowPseudoId(const AtomicString& id)
2404 ASSERT(CSSSelector::parsePseudoType(id) == CSSSelector::PseudoWebKitCustomElement || CSSSelector::parsePseudoType(id) == CSSSelector::PseudoUserAgentCustomElement);
2405 setAttribute(pseudoAttr, id);
2408 bool Element::isInDescendantTreeOf(const Element* shadowHost) const
2411 ASSERT(isShadowHost(shadowHost));
2413 const ShadowRoot* shadowRoot = containingShadowRoot();
2414 while (shadowRoot) {
2415 const Element* ancestorShadowHost = shadowRoot->shadowHost();
2416 if (ancestorShadowHost == shadowHost)
2418 shadowRoot = ancestorShadowHost->containingShadowRoot();
2423 RenderStyle* Element::computedStyle(PseudoId pseudoElementSpecifier)
2425 if (PseudoElement* element = pseudoElement(pseudoElementSpecifier))
2426 return element->computedStyle();
2428 // FIXME: Find and use the renderer from the pseudo element instead of the actual element so that the 'length'
2429 // properties, which are only known by the renderer because it did the layout, will be correct and so that the
2430 // values returned for the ":selection" pseudo-element will be correct.
2431 if (RenderStyle* usedStyle = renderStyle()) {
2432 if (pseudoElementSpecifier) {
2433 RenderStyle* cachedPseudoStyle = usedStyle->getCachedPseudoStyle(pseudoElementSpecifier);
2434 return cachedPseudoStyle ? cachedPseudoStyle : usedStyle;
2439 if (!inActiveDocument())
2440 // FIXME: Try to do better than this. Ensure that styleForElement() works for elements that are not in the
2441 // document tree and figure out when to destroy the computed style for such elements.
2444 ElementRareData& rareData = ensureElementRareData();
2445 if (!rareData.computedStyle())
2446 rareData.setComputedStyle(document().styleForElementIgnoringPendingStylesheets(this));
2447 return pseudoElementSpecifier ? rareData.computedStyle()->getCachedPseudoStyle(pseudoElementSpecifier) : rareData.computedStyle();
2450 AtomicString Element::computeInheritedLanguage() const
2452 const Node* n = this;
2454 // The language property is inherited, so we iterate over the parents to find the first language.
2456 if (n->isElementNode()) {
2457 if (const ElementData* elementData = toElement(n)->elementData()) {
2458 // Spec: xml:lang takes precedence -- http://www.w3.org/TR/xhtml1/#C_7
2459 if (const Attribute* attribute = elementData->getAttributeItem(XMLNames::langAttr))
2460 value = attribute->value();
2461 else if (const Attribute* attribute = elementData->getAttributeItem(HTMLNames::langAttr))
2462 value = attribute->value();
2464 } else if (n->isDocumentNode()) {
2465 // checking the MIME content-language
2466 value = toDocument(n)->contentLanguage();
2469 n = n->parentNode();
2470 } while (n && value.isNull());
2475 Locale& Element::locale() const
2477 return document().getCachedLocale(computeInheritedLanguage());
2480 void Element::cancelFocusAppearanceUpdate()
2482 if (document().focusedElement() == this)
2483 document().cancelFocusAppearanceUpdate();
2486 void Element::normalizeAttributes()
2488 if (!hasAttributes())
2490 // attributeCount() cannot be cached before the loop because the attributes
2491 // list is altered while iterating.
2492 for (unsigned i = 0; i < attributeCount(); ++i) {
2493 if (RefPtr<Attr> attr = attrIfExists(attributeItem(i).name()))
2498 void Element::updatePseudoElement(PseudoId pseudoId, StyleRecalcChange change)
2500 ASSERT(!needsStyleRecalc());
2501 PseudoElement* element = pseudoElement(pseudoId);
2502 if (element && (change == UpdatePseudoElements || element->shouldCallRecalcStyle(change))) {
2504 // Need to clear the cached style if the PseudoElement wants a recalc so it
2505 // computes a new style.
2506 if (element->needsStyleRecalc())
2507 renderer()->style()->removeCachedPseudoStyle(pseudoId);
2509 // PseudoElement styles hang off their parent element's style so if we needed
2510 // a style recalc we should Force one on the pseudo.
2511 // FIXME: We should figure out the right text sibling to pass.
2512 element->recalcStyle(change == UpdatePseudoElements ? Force : change);
2514 // Wait until our parent is not displayed or pseudoElementRendererIsNeeded
2515 // is false, otherwise we could continously create and destroy PseudoElements
2516 // when RenderObject::isChildAllowed on our parent returns false for the
2517 // PseudoElement's renderer for each style recalc.
2518 if (!renderer() || !pseudoElementRendererIsNeeded(renderer()->getCachedPseudoStyle(pseudoId)))
2519 elementRareData()->setPseudoElement(pseudoId, nullptr);
2520 } else if (change >= UpdatePseudoElements) {
2521 createPseudoElementIfNeeded(pseudoId);
2525 void Element::createPseudoElementIfNeeded(PseudoId pseudoId)
2527 if (isPseudoElement())
2530 // Document::ensureStyleResolver is not inlined and shows up on profiles, avoid it here.
2531 StyleEngine* engine = document().styleEngine();
2532 RefPtr<PseudoElement> element = engine->ensureResolver().createPseudoElementIfNeeded(*this, pseudoId);
2536 if (pseudoId == BACKDROP)
2537 document().addToTopLayer(element.get(), this);
2538 element->insertedInto(this);
2541 InspectorInstrumentation::pseudoElementCreated(element.get());
2543 ensureElementRareData().setPseudoElement(pseudoId, element.release());
2546 PseudoElement* Element::pseudoElement(PseudoId pseudoId) const
2548 return hasRareData() ? elementRareData()->pseudoElement(pseudoId) : 0;
2551 RenderObject* Element::pseudoElementRenderer(PseudoId pseudoId) const
2553 if (PseudoElement* element = pseudoElement(pseudoId))
2554 return element->renderer();
2558 bool Element::matches(const String& selectors, ExceptionState& exceptionState)
2560 SelectorQuery* selectorQuery = document().selectorQueryCache().add(AtomicString(selectors), document(), exceptionState);
2563 return selectorQuery->matches(*this);
2566 DOMTokenList& Element::classList()
2568 ElementRareData& rareData = ensureElementRareData();
2569 if (!rareData.classList())
2570 rareData.setClassList(ClassList::create(this));
2571 return *rareData.classList();
2574 DOMStringMap& Element::dataset()
2576 ElementRareData& rareData = ensureElementRareData();
2577 if (!rareData.dataset())
2578 rareData.setDataset(DatasetDOMStringMap::create(this));
2579 return *rareData.dataset();
2582 KURL Element::getURLAttribute(const QualifiedName& name) const
2584 #if !ASSERT_DISABLED
2585 if (elementData()) {
2586 if (const Attribute* attribute = getAttributeItem(name))
2587 ASSERT(isURLAttribute(*attribute));
2590 return document().completeURL(stripLeadingAndTrailingHTMLSpaces(getAttribute(name)));
2593 KURL Element::getNonEmptyURLAttribute(const QualifiedName& name) const
2595 #if !ASSERT_DISABLED
2596 if (elementData()) {
2597 if (const Attribute* attribute = getAttributeItem(name))
2598 ASSERT(isURLAttribute(*attribute));
2601 String value = stripLeadingAndTrailingHTMLSpaces(getAttribute(name));
2602 if (value.isEmpty())
2604 return document().completeURL(value);
2607 int Element::getIntegralAttribute(const QualifiedName& attributeName) const
2609 return getAttribute(attributeName).string().toInt();
2612 void Element::setIntegralAttribute(const QualifiedName& attributeName, int value)
2614 setAttribute(attributeName, AtomicString::number(value));
2617 unsigned Element::getUnsignedIntegralAttribute(const QualifiedName& attributeName) const
2619 return getAttribute(attributeName).string().toUInt();
2622 void Element::setUnsignedIntegralAttribute(const QualifiedName& attributeName, unsigned value)
2624 // Range restrictions are enforced for unsigned IDL attributes that
2625 // reflect content attributes,
2626 // http://www.whatwg.org/specs/web-apps/current-work/multipage/common-dom-interfaces.html#reflecting-content-attributes-in-idl-attributes
2627 if (value > 0x7fffffffu)
2629 setAttribute(attributeName, AtomicString::number(value));
2632 double Element::getFloatingPointAttribute(const QualifiedName& attributeName, double fallbackValue) const
2634 return parseToDoubleForNumberType(getAttribute(attributeName), fallbackValue);
2637 void Element::setFloatingPointAttribute(const QualifiedName& attributeName, double value)
2639 setAttribute(attributeName, AtomicString::number(value));
2642 void Element::webkitRequestFullscreen()
2644 FullscreenElementStack::from(document()).requestFullScreenForElement(this, ALLOW_KEYBOARD_INPUT, FullscreenElementStack::EnforceIFrameAllowFullScreenRequirement);
2647 void Element::webkitRequestFullScreen(unsigned short flags)
2649 FullscreenElementStack::from(document()).requestFullScreenForElement(this, (flags | LEGACY_MOZILLA_REQUEST), FullscreenElementStack::EnforceIFrameAllowFullScreenRequirement);
2652 void Element::setContainsFullScreenElement(bool flag)
2654 setElementFlag(ContainsFullScreenElement, flag);
2655 setNeedsStyleRecalc(SubtreeStyleChange);
2658 static Element* parentCrossingFrameBoundaries(Element* element)
2661 return element->parentElement() ? element->parentElement() : element->document().ownerElement();
2664 void Element::setContainsFullScreenElementOnAncestorsCrossingFrameBoundaries(bool flag)
2666 Element* element = this;
2667 while ((element = parentCrossingFrameBoundaries(element)))
2668 element->setContainsFullScreenElement(flag);
2671 void Element::setIsInTopLayer(bool inTopLayer)
2673 if (isInTopLayer() == inTopLayer)
2675 setElementFlag(IsInTopLayer, inTopLayer);
2677 // We must ensure a reattach occurs so the renderer is inserted in the correct sibling order under RenderView according to its
2678 // top layer position, or in its usual place if not in the top layer.
2679 lazyReattachIfAttached();
2682 void Element::webkitRequestPointerLock()
2684 if (document().page())
2685 document().page()->pointerLockController().requestPointerLock(this);
2688 SpellcheckAttributeState Element::spellcheckAttributeState() const
2690 const AtomicString& value = fastGetAttribute(spellcheckAttr);
2691 if (value == nullAtom)
2692 return SpellcheckAttributeDefault;
2693 if (equalIgnoringCase(value, "true") || equalIgnoringCase(value, ""))
2694 return SpellcheckAttributeTrue;
2695 if (equalIgnoringCase(value, "false"))
2696 return SpellcheckAttributeFalse;
2698 return SpellcheckAttributeDefault;
2701 bool Element::isSpellCheckingEnabled() const
2703 for (const Element* element = this; element; element = element->parentOrShadowHostElement()) {
2704 switch (element->spellcheckAttributeState()) {
2705 case SpellcheckAttributeTrue:
2707 case SpellcheckAttributeFalse:
2709 case SpellcheckAttributeDefault:
2718 bool Element::fastAttributeLookupAllowed(const QualifiedName& name) const
2720 if (name == HTMLNames::styleAttr)
2724 return !toSVGElement(this)->isAnimatableAttribute(name);
2730 #ifdef DUMP_NODE_STATISTICS
2731 bool Element::hasNamedNodeMap() const
2733 return hasRareData() && elementRareData()->attributeMap();
2737 inline void Element::updateName(const AtomicString& oldName, const AtomicString& newName)
2739 if (!inDocument() || isInShadowTree())
2742 if (oldName == newName)
2745 if (shouldRegisterAsNamedItem())
2746 updateNamedItemRegistration(oldName, newName);
2749 inline void Element::updateId(const AtomicString& oldId, const AtomicString& newId)
2751 if (!isInTreeScope())
2757 updateId(treeScope(), oldId, newId);
2760 inline void Element::updateId(TreeScope& scope, const AtomicString& oldId, const AtomicString& newId)
2762 ASSERT(isInTreeScope());
2763 ASSERT(oldId != newId);
2765 if (!oldId.isEmpty())
2766 scope.removeElementById(oldId, this);
2767 if (!newId.isEmpty())
2768 scope.addElementById(newId, this);
2770 if (shouldRegisterAsExtraNamedItem())
2771 updateExtraNamedItemRegistration(oldId, newId);
2774 void Element::updateLabel(TreeScope& scope, const AtomicString& oldForAttributeValue, const AtomicString& newForAttributeValue)
2776 ASSERT(isHTMLLabelElement(this));
2781 if (oldForAttributeValue == newForAttributeValue)
2784 if (!oldForAttributeValue.isEmpty())
2785 scope.removeLabel(oldForAttributeValue, toHTMLLabelElement(this));
2786 if (!newForAttributeValue.isEmpty())
2787 scope.addLabel(newForAttributeValue, toHTMLLabelElement(this));
2790 void Element::willModifyAttribute(const QualifiedName& name, const AtomicString& oldValue, const AtomicString& newValue)
2792 if (isIdAttributeName(name)) {
2793 updateId(oldValue, newValue);
2794 } else if (name == HTMLNames::nameAttr) {
2795 updateName(oldValue, newValue);
2796 } else if (name == HTMLNames::forAttr && isHTMLLabelElement(*this)) {
2797 TreeScope& scope = treeScope();
2798 if (scope.shouldCacheLabelsByForAttribute())
2799 updateLabel(scope, oldValue, newValue);
2802 if (oldValue != newValue) {
2803 if (inActiveDocument() && document().styleResolver() && styleChangeType() < SubtreeStyleChange)
2804 document().ensureStyleResolver().ensureUpdatedRuleFeatureSet().scheduleStyleInvalidationForAttributeChange(name, *this);
2806 if (isUpgradedCustomElement())
2807 CustomElement::attributeDidChange(this, name.localName(), oldValue, newValue);
2810 if (OwnPtrWillBeRawPtr<MutationObserverInterestGroup> recipients = MutationObserverInterestGroup::createForAttributesMutation(*this, name))
2811 recipients->enqueueMutationRecord(MutationRecord::createAttributes(this, name, oldValue));
2813 InspectorInstrumentation::willModifyDOMAttr(this, oldValue, newValue);
2816 void Element::didAddAttribute(const QualifiedName& name, const AtomicString& value)
2818 attributeChanged(name, value);
2819 InspectorInstrumentation::didModifyDOMAttr(this, name.localName(), value);
2820 dispatchSubtreeModifiedEvent();
2823 void Element::didModifyAttribute(const QualifiedName& name, const AtomicString& value)
2825 attributeChanged(name, value);
2826 InspectorInstrumentation::didModifyDOMAttr(this, name.localName(), value);
2827 // Do not dispatch a DOMSubtreeModified event here; see bug 81141.
2830 void Element::didRemoveAttribute(const QualifiedName& name)
2832 attributeChanged(name, nullAtom);
2833 InspectorInstrumentation::didRemoveDOMAttr(this, name.localName());
2834 dispatchSubtreeModifiedEvent();
2837 static bool needsURLResolutionForInlineStyle(const Element& element, const Document& oldDocument, const Document& newDocument)
2839 if (oldDocument == newDocument)
2841 if (oldDocument.baseURL() == newDocument.baseURL())
2843 const StylePropertySet* style = element.inlineStyle();
2846 for (unsigned i = 0; i < style->propertyCount(); ++i) {
2847 // FIXME: Should handle all URL-based properties: CSSImageSetValue, CSSCursorImageValue, etc.
2848 if (style->propertyAt(i).value()->isImageValue())
2854 static void reResolveURLsInInlineStyle(const Document& document, MutableStylePropertySet& style)
2856 for (unsigned i = 0; i < style.propertyCount(); ++i) {
2857 StylePropertySet::PropertyReference property = style.propertyAt(i);
2858 // FIXME: Should handle all URL-based properties: CSSImageSetValue, CSSCursorImageValue, etc.
2859 if (property.value()->isImageValue())
2860 toCSSImageValue(property.value())->reResolveURL(document);
2864 void Element::didMoveToNewDocument(Document& oldDocument)
2866 Node::didMoveToNewDocument(oldDocument);
2868 // If the documents differ by quirks mode then they differ by case sensitivity
2869 // for class and id names so we need to go through the attribute change logic
2870 // to pick up the new casing in the ElementData.
2871 if (oldDocument.inQuirksMode() != document().inQuirksMode()) {
2873 setIdAttribute(getIdAttribute());
2875 setAttribute(HTMLNames::classAttr, getClassAttribute());
2878 if (needsURLResolutionForInlineStyle(*this, oldDocument, document()))
2879 reResolveURLsInInlineStyle(document(), ensureMutableInlineStyle());
2882 void Element::updateNamedItemRegistration(const AtomicString& oldName, const AtomicString& newName)
2884 if (!document().isHTMLDocument())
2887 if (!oldName.isEmpty())
2888 toHTMLDocument(document()).removeNamedItem(oldName);
2890 if (!newName.isEmpty())
2891 toHTMLDocument(document()).addNamedItem(newName);
2894 void Element::updateExtraNamedItemRegistration(const AtomicString& oldId, const AtomicString& newId)
2896 if (!document().isHTMLDocument())
2899 if (!oldId.isEmpty())
2900 toHTMLDocument(document()).removeExtraNamedItem(oldId);
2902 if (!newId.isEmpty())
2903 toHTMLDocument(document()).addExtraNamedItem(newId);
2906 PassRefPtr<HTMLCollection> Element::ensureCachedHTMLCollection(CollectionType type)
2908 if (HTMLCollection* collection = cachedHTMLCollection(type))
2911 if (type == TableRows) {
2912 ASSERT(isHTMLTableElement(this));
2913 return ensureRareData().ensureNodeLists().addCache<HTMLTableRowsCollection>(*this, type);
2914 } else if (type == SelectOptions) {
2915 ASSERT(isHTMLSelectElement(this));
2916 return ensureRareData().ensureNodeLists().addCache<HTMLOptionsCollection>(*this, type);
2917 } else if (type == FormControls) {
2918 ASSERT(isHTMLFormElement(this) || isHTMLFieldSetElement(this));
2919 return ensureRareData().ensureNodeLists().addCache<HTMLFormControlsCollection>(*this, type);
2921 return ensureRareData().ensureNodeLists().addCache<HTMLCollection>(*this, type);
2924 void Element::scheduleLayerUpdate()
2926 document().scheduleLayerUpdate(*this);
2929 HTMLCollection* Element::cachedHTMLCollection(CollectionType type)
2931 return hasRareData() && rareData()->nodeLists() ? rareData()->nodeLists()->cached<HTMLCollection>(type) : 0;
2934 IntSize Element::savedLayerScrollOffset() const
2936 return hasRareData() ? elementRareData()->savedLayerScrollOffset() : IntSize();
2939 void Element::setSavedLayerScrollOffset(const IntSize& size)
2941 if (size.isZero() && !hasRareData())
2943 ensureElementRareData().setSavedLayerScrollOffset(size);
2946 PassRefPtr<Attr> Element::attrIfExists(const QualifiedName& name)
2948 if (AttrNodeList* attrNodeList = attrNodeListForElement(this))
2949 return findAttrNodeInList(*attrNodeList, name);
2953 PassRefPtr<Attr> Element::ensureAttr(const QualifiedName& name)
2955 AttrNodeList& attrNodeList = ensureAttrNodeListForElement(this);
2956 RefPtr<Attr> attrNode = findAttrNodeInList(attrNodeList, name);
2958 attrNode = Attr::create(*this, name);
2959 treeScope().adoptIfNeeded(*attrNode);
2960 attrNodeList.append(attrNode);
2962 return attrNode.release();
2965 void Element::detachAttrNodeFromElementWithValue(Attr* attrNode, const AtomicString& value)
2967 ASSERT(hasSyntheticAttrChildNodes());
2968 attrNode->detachFromElementWithValue(value);
2970 AttrNodeList* attrNodeList = attrNodeListForElement(this);
2971 for (unsigned i = 0; i < attrNodeList->size(); ++i) {
2972 if (attrNodeList->at(i)->qualifiedName() == attrNode->qualifiedName()) {
2973 attrNodeList->remove(i);
2974 if (attrNodeList->isEmpty())
2975 removeAttrNodeListForElement(this);
2979 ASSERT_NOT_REACHED();
2982 void Element::detachAllAttrNodesFromElement()
2984 AttrNodeList* attrNodeList = attrNodeListForElement(this);
2985 ASSERT(attrNodeList);
2987 unsigned attributeCount = this->attributeCount();
2988 for (unsigned i = 0; i < attributeCount; ++i) {
2989 const Attribute& attribute = attributeItem(i);
2990 if (RefPtr<Attr> attrNode = findAttrNodeInList(*attrNodeList, attribute.name()))
2991 attrNode->detachFromElementWithValue(attribute.value());
2994 removeAttrNodeListForElement(this);
2997 void Element::willRecalcStyle(StyleRecalcChange)
2999 ASSERT(hasCustomStyleCallbacks());
3002 void Element::didRecalcStyle(StyleRecalcChange)
3004 ASSERT(hasCustomStyleCallbacks());
3008 PassRefPtr<RenderStyle> Element::customStyleForRenderer()
3010 ASSERT(hasCustomStyleCallbacks());
3014 void Element::cloneAttributesFromElement(const Element& other)
3016 if (hasSyntheticAttrChildNodes())
3017 detachAllAttrNodesFromElement();
3019 other.synchronizeAllAttributes();
3020 if (!other.m_elementData) {
3021 m_elementData.clear();
3025 const AtomicString& oldID = getIdAttribute();
3026 const AtomicString& newID = other.getIdAttribute();
3028 if (!oldID.isNull() || !newID.isNull())
3029 updateId(oldID, newID);
3031 const AtomicString& oldName = getNameAttribute();
3032 const AtomicString& newName = other.getNameAttribute();
3034 if (!oldName.isNull() || !newName.isNull())
3035 updateName(oldName, newName);
3037 // Quirks mode makes class and id not case sensitive. We can't share the ElementData
3038 // if the idForStyleResolution and the className need different casing.
3039 bool ownerDocumentsHaveDifferentCaseSensitivity = false;
3040 if (other.hasClass() || other.hasID())
3041 ownerDocumentsHaveDifferentCaseSensitivity = other.document().inQuirksMode() != document().inQuirksMode();
3043 // If 'other' has a mutable ElementData, convert it to an immutable one so we can share it between both elements.
3044 // We can only do this if there are no presentation attributes and sharing the data won't result in different case sensitivity of class or id.
3045 if (other.m_elementData->isUnique()
3046 && !ownerDocumentsHaveDifferentCaseSensitivity
3047 && !other.m_elementData->presentationAttributeStyle())
3048 const_cast<Element&>(other).m_elementData = static_cast<const UniqueElementData*>(other.m_elementData.get())->makeShareableCopy();
3050 if (!other.m_elementData->isUnique() && !ownerDocumentsHaveDifferentCaseSensitivity && !needsURLResolutionForInlineStyle(other, other.document(), document()))
3051 m_elementData = other.m_elementData;
3053 m_elementData = other.m_elementData->makeUniqueCopy();
3055 unsigned length = m_elementData->length();
3056 for (unsigned i = 0; i < length; ++i) {
3057 const Attribute& attribute = m_elementData->attributeItem(i);
3058 attributeChangedFromParserOrByCloning(attribute.name(), attribute.value(), ModifiedByCloning);
3062 void Element::cloneDataFromElement(const Element& other)
3064 cloneAttributesFromElement(other);
3065 copyNonAttributePropertiesFromElement(other);
3068 void Element::createUniqueElementData()
3071 m_elementData = UniqueElementData::create();
3073 ASSERT(!m_elementData->isUnique());
3074 m_elementData = static_cast<ShareableElementData*>(m_elementData.get())->makeUniqueCopy();
3078 InputMethodContext& Element::inputMethodContext()
3080 return ensureElementRareData().ensureInputMethodContext(toHTMLElement(this));
3083 bool Element::hasInputMethodContext() const
3085 return hasRareData() && elementRareData()->hasInputMethodContext();
3088 void Element::synchronizeStyleAttributeInternal() const
3090 ASSERT(isStyledElement());
3091 ASSERT(elementData());
3092 ASSERT(elementData()->m_styleAttributeIsDirty);
3093 elementData()->m_styleAttributeIsDirty = false;
3094 const StylePropertySet* inlineStyle = this->inlineStyle();
3095 const_cast<Element*>(this)->setSynchronizedLazyAttribute(styleAttr,
3096 inlineStyle ? AtomicString(inlineStyle->asText()) : nullAtom);
3099 CSSStyleDeclaration* Element::style()
3101 if (!isStyledElement())
3103 return &ensureElementRareData().ensureInlineCSSStyleDeclaration(this);
3106 MutableStylePropertySet& Element::ensureMutableInlineStyle()
3108 ASSERT(isStyledElement());
3109 RefPtr<StylePropertySet>& inlineStyle = ensureUniqueElementData().m_inlineStyle;
3111 CSSParserMode mode = (!isHTMLElement() || document().inQuirksMode()) ? HTMLQuirksMode : HTMLStandardMode;
3112 inlineStyle = MutableStylePropertySet::create(mode);
3113 } else if (!inlineStyle->isMutable()) {
3114 inlineStyle = inlineStyle->mutableCopy();
3116 return *toMutableStylePropertySet(inlineStyle);
3119 void Element::clearMutableInlineStyleIfEmpty()
3121 if (ensureMutableInlineStyle().isEmpty()) {
3122 ensureUniqueElementData().m_inlineStyle.clear();
3126 inline void Element::setInlineStyleFromString(const AtomicString& newStyleString)
3128 ASSERT(isStyledElement());
3129 RefPtr<StylePropertySet>& inlineStyle = elementData()->m_inlineStyle;
3131 // Avoid redundant work if we're using shared attribute data with already parsed inline style.
3132 if (inlineStyle && !elementData()->isUnique())
3135 // We reconstruct the property set instead of mutating if there is no CSSOM wrapper.
3136 // This makes wrapperless property sets immutable and so cacheable.
3137 if (inlineStyle && !inlineStyle->isMutable())
3138 inlineStyle.clear();
3141 inlineStyle = BisonCSSParser::parseInlineStyleDeclaration(newStyleString, this);
3143 ASSERT(inlineStyle->isMutable());
3144 static_pointer_cast<MutableStylePropertySet>(inlineStyle)->parseDeclaration(newStyleString, document().elementSheet().contents());
3148 void Element::styleAttributeChanged(const AtomicString& newStyleString, AttributeModificationReason modificationReason)
3150 ASSERT(isStyledElement());
3151 WTF::OrdinalNumber startLineNumber = WTF::OrdinalNumber::beforeFirst();
3152 if (document().scriptableDocumentParser() && !document().isInDocumentWrite())
3153 startLineNumber = document().scriptableDocumentParser()->lineNumber();
3155 if (newStyleString.isNull()) {
3156 ensureUniqueElementData().m_inlineStyle.clear();
3157 } else if (modificationReason == ModifiedByCloning || document().contentSecurityPolicy()->allowInlineStyle(document().url(), startLineNumber)) {
3158 setInlineStyleFromString(newStyleString);
3161 elementData()->m_styleAttributeIsDirty = false;
3163 setNeedsStyleRecalc(LocalStyleChange);
3164 InspectorInstrumentation::didInvalidateStyleAttr(this);
3167 void Element::inlineStyleChanged()
3169 ASSERT(isStyledElement());
3170 setNeedsStyleRecalc(LocalStyleChange);
3171 ASSERT(elementData());
3172 elementData()->m_styleAttributeIsDirty = true;
3173 InspectorInstrumentation::didInvalidateStyleAttr(this);
3176 bool Element::setInlineStyleProperty(CSSPropertyID propertyID, CSSValueID identifier, bool important)
3178 ASSERT(isStyledElement());
3179 ensureMutableInlineStyle().setProperty(propertyID, cssValuePool().createIdentifierValue(identifier), important);
3180 inlineStyleChanged();
3184 bool Element::setInlineStyleProperty(CSSPropertyID propertyID, CSSPropertyID identifier, bool important)
3186 ASSERT(isStyledElement());
3187 ensureMutableInlineStyle().setProperty(propertyID, cssValuePool().createIdentifierValue(identifier), important);
3188 inlineStyleChanged();
3192 bool Element::setInlineStyleProperty(CSSPropertyID propertyID, double value, CSSPrimitiveValue::UnitTypes unit, bool important)
3194 ASSERT(isStyledElement());
3195 ensureMutableInlineStyle().setProperty(propertyID, cssValuePool().createValue(value, unit), important);
3196 inlineStyleChanged();
3200 bool Element::setInlineStyleProperty(CSSPropertyID propertyID, const String& value, bool important)
3202 ASSERT(isStyledElement());
3203 bool changes = ensureMutableInlineStyle().setProperty(propertyID, value, important, document().elementSheet().contents());
3205 inlineStyleChanged();
3209 bool Element::removeInlineStyleProperty(CSSPropertyID propertyID)
3211 ASSERT(isStyledElement());
3214 bool changes = ensureMutableInlineStyle().removeProperty(propertyID);
3216 inlineStyleChanged();
3220 void Element::removeAllInlineStyleProperties()
3222 ASSERT(isStyledElement());
3225 ensureMutableInlineStyle().clear();
3226 inlineStyleChanged();
3229 void Element::updatePresentationAttributeStyle()
3231 synchronizeAllAttributes();
3232 // ShareableElementData doesn't store presentation attribute style, so make sure we have a UniqueElementData.
3233 UniqueElementData& elementData = ensureUniqueElementData();
3234 elementData.m_presentationAttributeStyleIsDirty = false;
3235 elementData.m_presentationAttributeStyle = computePresentationAttributeStyle(*this);
3238 void Element::addPropertyToPresentationAttributeStyle(MutableStylePropertySet* style, CSSPropertyID propertyID, CSSValueID identifier)
3240 ASSERT(isStyledElement());
3241 style->setProperty(propertyID, cssValuePool().createIdentifierValue(identifier));
3244 void Element::addPropertyToPresentationAttributeStyle(MutableStylePropertySet* style, CSSPropertyID propertyID, double value, CSSPrimitiveValue::UnitTypes unit)
3246 ASSERT(isStyledElement());
3247 style->setProperty(propertyID, cssValuePool().createValue(value, unit));
3250 void Element::addPropertyToPresentationAttributeStyle(MutableStylePropertySet* style, CSSPropertyID propertyID, const String& value)
3252 ASSERT(isStyledElement());
3253 style->setProperty(propertyID, value, false);
3256 bool Element::supportsStyleSharing() const
3258 if (!isStyledElement() || !parentOrShadowHostElement())
3260 // If the element has inline style it is probably unique.
3263 if (isSVGElement() && toSVGElement(this)->animatedSMILStyleProperties())
3265 // Ids stop style sharing if they show up in the stylesheets.
3266 if (hasID() && document().ensureStyleResolver().hasRulesForId(idForStyleResolution()))
3268 // :active and :hover elements always make a chain towards the document node
3269 // and no siblings or cousins will have the same state. There's also only one
3270 // :focus element per scope so we don't need to attempt to share.
3271 if (isUserActionElement())
3273 if (!parentOrShadowHostElement()->childrenSupportStyleSharing())
3275 if (hasScopedHTMLStyleChild())
3277 if (this == document().cssTarget())
3279 if (isHTMLElement() && toHTMLElement(this)->hasDirectionAuto())
3281 if (hasActiveAnimations())
3283 // Turn off style sharing for elements that can gain layers for reasons outside of the style system.
3284 // See comments in RenderObject::setStyle().
3285 // FIXME: Why does gaining a layer from outside the style system require disabling sharing?
3286 if (isHTMLFrameElementBase(*this)
3287 || isHTMLEmbedElement(*this)
3288 || isHTMLObjectElement(*this)
3289 || isHTMLAppletElement(*this)
3290 || isHTMLCanvasElement(*this))
3292 if (FullscreenElementStack::isActiveFullScreenElement(this))
3297 void Element::trace(Visitor* visitor)
3300 visitor->trace(elementRareData());
3302 ContainerNode::trace(visitor);
3305 } // namespace WebCore