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/ExceptionState.h"
35 #include "core/accessibility/AXObjectCache.h"
36 #include "core/animation/DocumentTimeline.h"
37 #include "core/animation/css/CSSAnimations.h"
38 #include "core/css/CSSStyleSheet.h"
39 #include "core/css/CSSValuePool.h"
40 #include "core/css/PropertySetCSSStyleDeclaration.h"
41 #include "core/css/StylePropertySet.h"
42 #include "core/css/parser/BisonCSSParser.h"
43 #include "core/css/resolver/StyleResolver.h"
44 #include "core/dom/Attr.h"
45 #include "core/dom/CSSSelectorWatch.h"
46 #include "core/dom/ClientRect.h"
47 #include "core/dom/ClientRectList.h"
48 #include "core/dom/DatasetDOMStringMap.h"
49 #include "core/dom/ElementDataCache.h"
50 #include "core/dom/ElementRareData.h"
51 #include "core/dom/ElementTraversal.h"
52 #include "core/dom/ExceptionCode.h"
53 #include "core/dom/FullscreenElementStack.h"
54 #include "core/dom/MutationObserverInterestGroup.h"
55 #include "core/dom/MutationRecord.h"
56 #include "core/dom/NamedNodeMap.h"
57 #include "core/dom/NodeRenderStyle.h"
58 #include "core/dom/PostAttachCallbacks.h"
59 #include "core/dom/PresentationAttributeStyle.h"
60 #include "core/dom/PseudoElement.h"
61 #include "core/dom/RenderTreeBuilder.h"
62 #include "core/dom/ScriptableDocumentParser.h"
63 #include "core/dom/SelectorQuery.h"
64 #include "core/dom/Text.h"
65 #include "core/dom/custom/CustomElement.h"
66 #include "core/dom/custom/CustomElementRegistrationContext.h"
67 #include "core/dom/shadow/InsertionPoint.h"
68 #include "core/dom/shadow/ShadowRoot.h"
69 #include "core/editing/FrameSelection.h"
70 #include "core/editing/TextIterator.h"
71 #include "core/editing/htmlediting.h"
72 #include "core/editing/markup.h"
73 #include "core/events/EventDispatcher.h"
74 #include "core/events/FocusEvent.h"
75 #include "core/frame/ContentSecurityPolicy.h"
76 #include "core/frame/Frame.h"
77 #include "core/frame/FrameView.h"
78 #include "core/frame/UseCounter.h"
79 #include "core/html/ClassList.h"
80 #include "core/html/HTMLCollection.h"
81 #include "core/html/HTMLDocument.h"
82 #include "core/html/HTMLElement.h"
83 #include "core/html/HTMLFormControlsCollection.h"
84 #include "core/html/HTMLFrameOwnerElement.h"
85 #include "core/html/HTMLLabelElement.h"
86 #include "core/html/HTMLOptionsCollection.h"
87 #include "core/html/HTMLTableRowsCollection.h"
88 #include "core/html/HTMLTemplateElement.h"
89 #include "core/html/parser/HTMLParserIdioms.h"
90 #include "core/inspector/InspectorInstrumentation.h"
91 #include "core/page/FocusController.h"
92 #include "core/page/Page.h"
93 #include "core/page/PointerLockController.h"
94 #include "core/rendering/RenderLayer.h"
95 #include "core/rendering/RenderView.h"
96 #include "core/rendering/RenderWidget.h"
97 #include "core/svg/SVGDocumentExtensions.h"
98 #include "core/svg/SVGElement.h"
99 #include "platform/scroll/ScrollableArea.h"
100 #include "wtf/BitVector.h"
101 #include "wtf/HashFunctions.h"
102 #include "wtf/text/CString.h"
103 #include "wtf/text/StringBuilder.h"
104 #include "wtf/text/TextPosition.h"
108 using namespace HTMLNames;
109 using namespace XMLNames;
111 class StyleResolverParentPusher {
113 explicit StyleResolverParentPusher(Element& parent)
115 , m_pushedStyleResolver(0)
120 if (m_pushedStyleResolver)
122 m_pushedStyleResolver = &m_parent.document().ensureStyleResolver();
123 m_pushedStyleResolver->pushParentElement(m_parent);
125 ~StyleResolverParentPusher()
128 if (!m_pushedStyleResolver)
131 // This tells us that our pushed style selector is in a bad state,
132 // so we should just bail out in that scenario.
133 ASSERT(m_pushedStyleResolver == m_parent.document().styleResolver());
134 if (m_pushedStyleResolver != m_parent.document().styleResolver())
137 m_pushedStyleResolver->popParentElement(m_parent);
142 StyleResolver* m_pushedStyleResolver;
145 typedef Vector<RefPtr<Attr> > AttrNodeList;
146 typedef HashMap<Element*, OwnPtr<AttrNodeList> > AttrNodeListMap;
148 static AttrNodeListMap& attrNodeListMap()
150 DEFINE_STATIC_LOCAL(AttrNodeListMap, map, ());
154 static AttrNodeList* attrNodeListForElement(Element* element)
156 if (!element->hasSyntheticAttrChildNodes())
158 ASSERT(attrNodeListMap().contains(element));
159 return attrNodeListMap().get(element);
162 static AttrNodeList& ensureAttrNodeListForElement(Element* element)
164 if (element->hasSyntheticAttrChildNodes()) {
165 ASSERT(attrNodeListMap().contains(element));
166 return *attrNodeListMap().get(element);
168 ASSERT(!attrNodeListMap().contains(element));
169 element->setHasSyntheticAttrChildNodes(true);
170 AttrNodeListMap::AddResult result = attrNodeListMap().add(element, adoptPtr(new AttrNodeList));
171 return *result.storedValue->value;
174 static void removeAttrNodeListForElement(Element* element)
176 ASSERT(element->hasSyntheticAttrChildNodes());
177 ASSERT(attrNodeListMap().contains(element));
178 attrNodeListMap().remove(element);
179 element->setHasSyntheticAttrChildNodes(false);
182 static Attr* findAttrNodeInList(const AttrNodeList& attrNodeList, const QualifiedName& name)
184 AttrNodeList::const_iterator end = attrNodeList.end();
185 for (AttrNodeList::const_iterator it = attrNodeList.begin(); it != end; ++it) {
186 if ((*it)->qualifiedName() == name)
192 PassRefPtr<Element> Element::create(const QualifiedName& tagName, Document* document)
194 return adoptRef(new Element(tagName, document, CreateElement));
199 ASSERT(needsAttach());
202 elementRareData()->clearShadow();
204 if (isCustomElement())
205 CustomElement::wasDestroyed(this);
207 if (hasSyntheticAttrChildNodes())
208 detachAllAttrNodesFromElement();
210 if (hasPendingResources()) {
211 document().accessSVGExtensions()->removeElementFromPendingResources(this);
212 ASSERT(!hasPendingResources());
216 inline ElementRareData* Element::elementRareData() const
218 ASSERT(hasRareData());
219 return static_cast<ElementRareData*>(rareData());
222 inline ElementRareData& Element::ensureElementRareData()
224 return static_cast<ElementRareData&>(ensureRareData());
227 void Element::clearTabIndexExplicitlyIfNeeded()
230 elementRareData()->clearTabIndexExplicitly();
233 void Element::setTabIndexExplicitly(short tabIndex)
235 ensureElementRareData().setTabIndexExplicitly(tabIndex);
238 bool Element::supportsFocus() const
240 return hasRareData() && elementRareData()->tabIndexSetExplicitly();
243 short Element::tabIndex() const
245 return hasRareData() ? elementRareData()->tabIndex() : 0;
248 bool Element::rendererIsFocusable() const
250 // Elements in canvas fallback content are not rendered, but they are allowed to be
251 // focusable as long as their canvas is displayed and visible.
252 if (isInCanvasSubtree()) {
253 const Element* e = this;
254 while (e && !e->hasLocalName(canvasTag))
255 e = e->parentElement();
257 return e->renderer() && e->renderer()->style()->visibility() == VISIBLE;
260 // FIXME: These asserts should be in Node::isFocusable, but there are some
261 // callsites like Document::setFocusedElement that would currently fail on
262 // them. See crbug.com/251163
264 // We can't just use needsStyleRecalc() because if the node is in a
265 // display:none tree it might say it needs style recalc but the whole
266 // document is actually up to date.
267 ASSERT(!document().childNeedsStyleRecalc());
270 // FIXME: Even if we are not visible, we might have a child that is visible.
271 // Hyatt wants to fix that some day with a "has visible content" flag or the like.
272 if (!renderer() || renderer()->style()->visibility() != VISIBLE)
278 PassRefPtr<Node> Element::cloneNode(bool deep)
280 return deep ? cloneElementWithChildren() : cloneElementWithoutChildren();
283 PassRefPtr<Element> Element::cloneElementWithChildren()
285 RefPtr<Element> clone = cloneElementWithoutChildren();
286 cloneChildNodes(clone.get());
287 return clone.release();
290 PassRefPtr<Element> Element::cloneElementWithoutChildren()
292 RefPtr<Element> clone = cloneElementWithoutAttributesAndChildren();
293 // This will catch HTML elements in the wrong namespace that are not correctly copied.
294 // This is a sanity check as HTML overloads some of the DOM methods.
295 ASSERT(isHTMLElement() == clone->isHTMLElement());
297 clone->cloneDataFromElement(*this);
298 return clone.release();
301 PassRefPtr<Element> Element::cloneElementWithoutAttributesAndChildren()
303 return document().createElement(tagQName(), false);
306 PassRefPtr<Attr> Element::detachAttribute(size_t index)
308 ASSERT(elementData());
309 const Attribute* attribute = elementData()->attributeItem(index);
310 RefPtr<Attr> attrNode = attrIfExists(attribute->name());
312 detachAttrNodeAtIndex(attrNode.get(), index);
314 attrNode = Attr::create(document(), attribute->name(), attribute->value());
315 removeAttributeInternal(index, NotInSynchronizationOfLazyAttribute);
317 return attrNode.release();
320 void Element::detachAttrNodeAtIndex(Attr* attr, size_t index)
323 ASSERT(elementData());
325 const Attribute* attribute = elementData()->attributeItem(index);
327 ASSERT(attribute->name() == attr->qualifiedName());
328 detachAttrNodeFromElementWithValue(attr, attribute->value());
329 removeAttributeInternal(index, NotInSynchronizationOfLazyAttribute);
332 void Element::removeAttribute(const QualifiedName& name)
337 size_t index = elementData()->getAttributeItemIndex(name);
338 if (index == kNotFound)
341 removeAttributeInternal(index, NotInSynchronizationOfLazyAttribute);
344 void Element::setBooleanAttribute(const QualifiedName& name, bool value)
347 setAttribute(name, emptyAtom);
349 removeAttribute(name);
352 NamedNodeMap* Element::attributes() const
354 ElementRareData& rareData = const_cast<Element*>(this)->ensureElementRareData();
355 if (NamedNodeMap* attributeMap = rareData.attributeMap())
358 rareData.setAttributeMap(NamedNodeMap::create(const_cast<Element*>(this)));
359 return rareData.attributeMap();
362 ActiveAnimations* Element::activeAnimations() const
365 return elementRareData()->activeAnimations();
369 ActiveAnimations* Element::ensureActiveAnimations()
371 ElementRareData& rareData = ensureElementRareData();
372 if (!rareData.activeAnimations())
373 rareData.setActiveAnimations(adoptPtr(new ActiveAnimations()));
374 return rareData.activeAnimations();
377 bool Element::hasActiveAnimations() const
382 ActiveAnimations* activeAnimations = elementRareData()->activeAnimations();
383 return activeAnimations && !activeAnimations->isEmpty();
386 Node::NodeType Element::nodeType() const
391 bool Element::hasAttribute(const QualifiedName& name) const
393 return hasAttributeNS(name.namespaceURI(), name.localName());
396 void Element::synchronizeAllAttributes() const
400 // NOTE: anyAttributeMatches in SelectorChecker.cpp
401 // currently assumes that all lazy attributes have a null namespace.
402 // If that ever changes we'll need to fix that code.
403 if (elementData()->m_styleAttributeIsDirty) {
404 ASSERT(isStyledElement());
405 synchronizeStyleAttributeInternal();
407 if (elementData()->m_animatedSVGAttributesAreDirty) {
408 ASSERT(isSVGElement());
409 toSVGElement(this)->synchronizeAnimatedSVGAttribute(anyQName());
413 inline void Element::synchronizeAttribute(const QualifiedName& name) const
417 if (UNLIKELY(name == styleAttr && elementData()->m_styleAttributeIsDirty)) {
418 ASSERT(isStyledElement());
419 synchronizeStyleAttributeInternal();
422 if (UNLIKELY(elementData()->m_animatedSVGAttributesAreDirty)) {
423 ASSERT(isSVGElement());
424 // See comment in the AtomicString version of synchronizeAttribute()
426 toSVGElement(this)->synchronizeAnimatedSVGAttribute(name);
430 void Element::synchronizeAttribute(const AtomicString& localName) const
432 // This version of synchronizeAttribute() is streamlined for the case where you don't have a full QualifiedName,
433 // e.g when called from DOM API.
436 if (elementData()->m_styleAttributeIsDirty && equalPossiblyIgnoringCase(localName, styleAttr.localName(), shouldIgnoreAttributeCase())) {
437 ASSERT(isStyledElement());
438 synchronizeStyleAttributeInternal();
441 if (elementData()->m_animatedSVGAttributesAreDirty) {
442 // We're not passing a namespace argument on purpose. SVGNames::*Attr are defined w/o namespaces as well.
444 // FIXME: this code is called regardless of whether name is an
445 // animated SVG Attribute. It would seem we should only call this method
446 // if SVGElement::isAnimatableAttribute is true, but the list of
447 // animatable attributes in isAnimatableAttribute does not suffice to
448 // pass all layout tests. Also, m_animatedSVGAttributesAreDirty stays
449 // dirty unless synchronizeAnimatedSVGAttribute is called with
450 // anyQName(). This means that even if Element::synchronizeAttribute()
451 // is called on all attributes, m_animatedSVGAttributesAreDirty remains
453 toSVGElement(this)->synchronizeAnimatedSVGAttribute(QualifiedName(nullAtom, localName, nullAtom));
457 const AtomicString& Element::getAttribute(const QualifiedName& name) const
461 synchronizeAttribute(name);
462 if (const Attribute* attribute = getAttributeItem(name))
463 return attribute->value();
467 void Element::scrollIntoView(bool alignToTop)
469 document().updateLayoutIgnorePendingStylesheets();
474 LayoutRect bounds = boundingBox();
475 // Align to the top / bottom and to the closest edge.
477 renderer()->scrollRectToVisible(bounds, ScrollAlignment::alignToEdgeIfNeeded, ScrollAlignment::alignTopAlways);
479 renderer()->scrollRectToVisible(bounds, ScrollAlignment::alignToEdgeIfNeeded, ScrollAlignment::alignBottomAlways);
482 void Element::scrollIntoViewIfNeeded(bool centerIfNeeded)
484 document().updateLayoutIgnorePendingStylesheets();
489 LayoutRect bounds = boundingBox();
491 renderer()->scrollRectToVisible(bounds, ScrollAlignment::alignCenterIfNeeded, ScrollAlignment::alignCenterIfNeeded);
493 renderer()->scrollRectToVisible(bounds, ScrollAlignment::alignToEdgeIfNeeded, ScrollAlignment::alignToEdgeIfNeeded);
496 void Element::scrollByUnits(int units, ScrollGranularity granularity)
498 document().updateLayoutIgnorePendingStylesheets();
503 if (!renderer()->hasOverflowClip())
506 ScrollDirection direction = ScrollDown;
508 direction = ScrollUp;
511 toRenderBox(renderer())->scroll(direction, granularity, units);
514 void Element::scrollByLines(int lines)
516 scrollByUnits(lines, ScrollByLine);
519 void Element::scrollByPages(int pages)
521 scrollByUnits(pages, ScrollByPage);
524 static float localZoomForRenderer(RenderObject& renderer)
526 // FIXME: This does the wrong thing if two opposing zooms are in effect and canceled each
527 // other out, but the alternative is that we'd have to crawl up the whole render tree every
528 // time (or store an additional bit in the RenderStyle to indicate that a zoom was specified).
529 float zoomFactor = 1;
530 if (renderer.style()->effectiveZoom() != 1) {
531 // Need to find the nearest enclosing RenderObject that set up
532 // a differing zoom, and then we divide our result by it to eliminate the zoom.
533 RenderObject* prev = &renderer;
534 for (RenderObject* curr = prev->parent(); curr; curr = curr->parent()) {
535 if (curr->style()->effectiveZoom() != prev->style()->effectiveZoom()) {
536 zoomFactor = prev->style()->zoom();
541 if (prev->isRenderView())
542 zoomFactor = prev->style()->zoom();
547 static int adjustForLocalZoom(LayoutUnit value, RenderObject& renderer)
549 float zoomFactor = localZoomForRenderer(renderer);
552 return lroundf(value / zoomFactor);
555 int Element::offsetLeft()
557 document().partialUpdateLayoutIgnorePendingStylesheets(this);
558 if (RenderBoxModelObject* renderer = renderBoxModelObject())
559 return adjustForLocalZoom(renderer->pixelSnappedOffsetLeft(), *renderer);
563 int Element::offsetTop()
565 document().partialUpdateLayoutIgnorePendingStylesheets(this);
566 if (RenderBoxModelObject* renderer = renderBoxModelObject())
567 return adjustForLocalZoom(renderer->pixelSnappedOffsetTop(), *renderer);
571 int Element::offsetWidth()
573 document().updateStyleForNodeIfNeeded(this);
575 if (RenderBox* renderer = renderBox()) {
576 if (renderer->canDetermineWidthWithoutLayout())
577 return adjustLayoutUnitForAbsoluteZoom(renderer->fixedOffsetWidth(), *renderer).round();
580 document().partialUpdateLayoutIgnorePendingStylesheets(this);
581 if (RenderBoxModelObject* renderer = renderBoxModelObject())
582 return adjustLayoutUnitForAbsoluteZoom(renderer->pixelSnappedOffsetWidth(), *renderer).round();
586 int Element::offsetHeight()
588 document().partialUpdateLayoutIgnorePendingStylesheets(this);
589 if (RenderBoxModelObject* renderer = renderBoxModelObject())
590 return adjustLayoutUnitForAbsoluteZoom(renderer->pixelSnappedOffsetHeight(), *renderer).round();
594 Element* Element::offsetParentForBindings()
596 Element* element = offsetParent();
597 if (!element || !element->isInShadowTree())
599 return element->containingShadowRoot()->shouldExposeToBindings() ? element : 0;
602 Element* Element::offsetParent()
604 document().updateLayoutIgnorePendingStylesheets();
605 if (RenderObject* renderer = this->renderer())
606 return renderer->offsetParent();
610 int Element::clientLeft()
612 document().updateLayoutIgnorePendingStylesheets();
614 if (RenderBox* renderer = renderBox())
615 return adjustForAbsoluteZoom(roundToInt(renderer->clientLeft()), renderer);
619 int Element::clientTop()
621 document().updateLayoutIgnorePendingStylesheets();
623 if (RenderBox* renderer = renderBox())
624 return adjustForAbsoluteZoom(roundToInt(renderer->clientTop()), renderer);
628 int Element::clientWidth()
630 document().updateLayoutIgnorePendingStylesheets();
632 // When in strict mode, clientWidth for the document element should return the width of the containing frame.
633 // When in quirks mode, clientWidth for the body element should return the width of the containing frame.
634 bool inQuirksMode = document().inQuirksMode();
635 if ((!inQuirksMode && document().documentElement() == this)
636 || (inQuirksMode && isHTMLElement() && document().body() == this)) {
637 if (FrameView* view = document().view()) {
638 if (RenderView* renderView = document().renderView())
639 return adjustForAbsoluteZoom(view->layoutSize().width(), renderView);
643 if (RenderBox* renderer = renderBox())
644 return adjustLayoutUnitForAbsoluteZoom(renderer->pixelSnappedClientWidth(), *renderer).round();
648 int Element::clientHeight()
650 document().updateLayoutIgnorePendingStylesheets();
652 // When in strict mode, clientHeight for the document element should return the height of the containing frame.
653 // When in quirks mode, clientHeight for the body element should return the height of the containing frame.
654 bool inQuirksMode = document().inQuirksMode();
656 if ((!inQuirksMode && document().documentElement() == this)
657 || (inQuirksMode && isHTMLElement() && document().body() == this)) {
658 if (FrameView* view = document().view()) {
659 if (RenderView* renderView = document().renderView())
660 return adjustForAbsoluteZoom(view->layoutSize().height(), renderView);
664 if (RenderBox* renderer = renderBox())
665 return adjustLayoutUnitForAbsoluteZoom(renderer->pixelSnappedClientHeight(), *renderer).round();
669 int Element::scrollLeft()
671 document().updateLayoutIgnorePendingStylesheets();
673 if (document().documentElement() != this) {
674 if (RenderBox* rend = renderBox())
675 return adjustForAbsoluteZoom(rend->scrollLeft(), rend);
679 if (RuntimeEnabledFeatures::scrollTopLeftInteropEnabled()) {
680 if (document().inQuirksMode())
683 if (FrameView* view = document().view()) {
684 if (RenderView* renderView = document().renderView())
685 return adjustForAbsoluteZoom(view->scrollX(), renderView);
692 int Element::scrollTop()
694 document().updateLayoutIgnorePendingStylesheets();
696 if (document().documentElement() != this) {
697 if (RenderBox* rend = renderBox())
698 return adjustForAbsoluteZoom(rend->scrollTop(), rend);
702 if (RuntimeEnabledFeatures::scrollTopLeftInteropEnabled()) {
703 if (document().inQuirksMode())
706 if (FrameView* view = document().view()) {
707 if (RenderView* renderView = document().renderView())
708 return adjustForAbsoluteZoom(view->scrollY(), renderView);
715 void Element::setScrollLeft(int newLeft)
717 document().updateLayoutIgnorePendingStylesheets();
719 if (document().documentElement() != this) {
720 if (RenderBox* rend = renderBox())
721 rend->setScrollLeft(static_cast<int>(newLeft * rend->style()->effectiveZoom()));
725 if (RuntimeEnabledFeatures::scrollTopLeftInteropEnabled()) {
726 if (document().inQuirksMode())
729 Frame* frame = document().frame();
732 FrameView* view = frame->view();
736 view->setScrollPosition(IntPoint(static_cast<int>(newLeft * frame->pageZoomFactor()), view->scrollY()));
740 void Element::setScrollLeft(const Dictionary& scrollOptionsHorizontal, ExceptionState& exceptionState)
742 String scrollBehaviorString;
743 ScrollBehavior scrollBehavior = ScrollBehaviorAuto;
744 if (scrollOptionsHorizontal.get("behavior", scrollBehaviorString)) {
745 if (!ScrollableArea::scrollBehaviorFromString(scrollBehaviorString, scrollBehavior)) {
746 exceptionState.throwTypeError("The ScrollBehavior provided is invalid.");
752 if (!scrollOptionsHorizontal.get("x", position)) {
753 exceptionState.throwTypeError("ScrollOptionsHorizontal must include an 'x' member.");
757 // FIXME: Use scrollBehavior to decide whether to scroll smoothly or instantly.
758 setScrollLeft(position);
761 void Element::setScrollTop(int newTop)
763 document().updateLayoutIgnorePendingStylesheets();
765 if (document().documentElement() != this) {
766 if (RenderBox* rend = renderBox())
767 rend->setScrollTop(static_cast<int>(newTop * rend->style()->effectiveZoom()));
771 if (RuntimeEnabledFeatures::scrollTopLeftInteropEnabled()) {
772 if (document().inQuirksMode())
775 Frame* frame = document().frame();
778 FrameView* view = frame->view();
782 view->setScrollPosition(IntPoint(view->scrollX(), static_cast<int>(newTop * frame->pageZoomFactor())));
786 void Element::setScrollTop(const Dictionary& scrollOptionsVertical, ExceptionState& exceptionState)
788 String scrollBehaviorString;
789 ScrollBehavior scrollBehavior = ScrollBehaviorAuto;
790 if (scrollOptionsVertical.get("behavior", scrollBehaviorString)) {
791 if (!ScrollableArea::scrollBehaviorFromString(scrollBehaviorString, scrollBehavior)) {
792 exceptionState.throwTypeError("The ScrollBehavior provided is invalid.");
798 if (!scrollOptionsVertical.get("y", position)) {
799 exceptionState.throwTypeError("ScrollOptionsVertical must include a 'y' member.");
803 // FIXME: Use scrollBehavior to decide whether to scroll smoothly or instantly.
804 setScrollTop(position);
807 int Element::scrollWidth()
809 document().updateLayoutIgnorePendingStylesheets();
810 if (RenderBox* rend = renderBox())
811 return adjustForAbsoluteZoom(rend->scrollWidth(), rend);
815 int Element::scrollHeight()
817 document().updateLayoutIgnorePendingStylesheets();
818 if (RenderBox* rend = renderBox())
819 return adjustForAbsoluteZoom(rend->scrollHeight(), rend);
823 IntRect Element::boundsInRootViewSpace()
825 document().updateLayoutIgnorePendingStylesheets();
827 FrameView* view = document().view();
831 Vector<FloatQuad> quads;
832 if (isSVGElement() && renderer()) {
833 // Get the bounding rectangle from the SVG model.
834 SVGElement* svgElement = toSVGElement(this);
836 if (svgElement->getBoundingBox(localRect))
837 quads.append(renderer()->localToAbsoluteQuad(localRect));
839 // Get the bounding rectangle from the box model.
840 if (renderBoxModelObject())
841 renderBoxModelObject()->absoluteQuads(quads);
847 IntRect result = quads[0].enclosingBoundingBox();
848 for (size_t i = 1; i < quads.size(); ++i)
849 result.unite(quads[i].enclosingBoundingBox());
851 result = view->contentsToRootView(result);
855 PassRefPtr<ClientRectList> Element::getClientRects()
857 document().updateLayoutIgnorePendingStylesheets();
859 RenderBoxModelObject* renderBoxModelObject = this->renderBoxModelObject();
860 if (!renderBoxModelObject)
861 return ClientRectList::create();
863 // FIXME: Handle SVG elements.
864 // FIXME: Handle table/inline-table with a caption.
866 Vector<FloatQuad> quads;
867 renderBoxModelObject->absoluteQuads(quads);
868 document().adjustFloatQuadsForScrollAndAbsoluteZoom(quads, *renderBoxModelObject);
869 return ClientRectList::create(quads);
872 PassRefPtr<ClientRect> Element::getBoundingClientRect()
874 document().updateLayoutIgnorePendingStylesheets();
876 Vector<FloatQuad> quads;
877 if (isSVGElement() && renderer() && !renderer()->isSVGRoot()) {
878 // Get the bounding rectangle from the SVG model.
879 SVGElement* svgElement = toSVGElement(this);
881 if (svgElement->getBoundingBox(localRect))
882 quads.append(renderer()->localToAbsoluteQuad(localRect));
884 // Get the bounding rectangle from the box model.
885 if (renderBoxModelObject())
886 renderBoxModelObject()->absoluteQuads(quads);
890 return ClientRect::create();
892 FloatRect result = quads[0].boundingBox();
893 for (size_t i = 1; i < quads.size(); ++i)
894 result.unite(quads[i].boundingBox());
897 document().adjustFloatRectForScrollAndAbsoluteZoom(result, *renderer());
898 return ClientRect::create(result);
901 IntRect Element::screenRect() const
905 // FIXME: this should probably respect transforms
906 return document().view()->contentsToScreen(renderer()->absoluteBoundingBoxRectIgnoringTransforms());
909 const AtomicString& Element::getAttribute(const AtomicString& localName) const
913 synchronizeAttribute(localName);
914 if (const Attribute* attribute = elementData()->getAttributeItem(localName, shouldIgnoreAttributeCase()))
915 return attribute->value();
919 const AtomicString& Element::getAttributeNS(const AtomicString& namespaceURI, const AtomicString& localName) const
921 return getAttribute(QualifiedName(nullAtom, localName, namespaceURI));
924 void Element::setAttribute(const AtomicString& localName, const AtomicString& value, ExceptionState& exceptionState)
926 if (!Document::isValidName(localName)) {
927 exceptionState.throwDOMException(InvalidCharacterError, "'" + localName + "' is not a valid attribute name.");
931 synchronizeAttribute(localName);
932 const AtomicString& caseAdjustedLocalName = shouldIgnoreAttributeCase() ? localName.lower() : localName;
934 size_t index = elementData() ? elementData()->getAttributeItemIndex(caseAdjustedLocalName, false) : kNotFound;
935 const QualifiedName& qName = index != kNotFound ? attributeItem(index)->name() : QualifiedName(nullAtom, caseAdjustedLocalName, nullAtom);
936 setAttributeInternal(index, qName, value, NotInSynchronizationOfLazyAttribute);
939 void Element::setAttribute(const QualifiedName& name, const AtomicString& value)
941 synchronizeAttribute(name);
942 size_t index = elementData() ? elementData()->getAttributeItemIndex(name) : kNotFound;
943 setAttributeInternal(index, name, value, NotInSynchronizationOfLazyAttribute);
946 void Element::setSynchronizedLazyAttribute(const QualifiedName& name, const AtomicString& value)
948 size_t index = elementData() ? elementData()->getAttributeItemIndex(name) : kNotFound;
949 setAttributeInternal(index, name, value, InSynchronizationOfLazyAttribute);
952 ALWAYS_INLINE void Element::setAttributeInternal(size_t index, const QualifiedName& name, const AtomicString& newValue, SynchronizationOfLazyAttribute inSynchronizationOfLazyAttribute)
954 if (newValue.isNull()) {
955 if (index != kNotFound)
956 removeAttributeInternal(index, inSynchronizationOfLazyAttribute);
960 if (index == kNotFound) {
961 addAttributeInternal(name, newValue, inSynchronizationOfLazyAttribute);
965 const Attribute* existingAttribute = attributeItem(index);
966 QualifiedName existingAttributeName = existingAttribute->name();
968 if (!inSynchronizationOfLazyAttribute)
969 willModifyAttribute(existingAttributeName, existingAttribute->value(), newValue);
971 if (newValue != existingAttribute->value()) {
972 // If there is an Attr node hooked to this attribute, the Attr::setValue() call below
973 // will write into the ElementData.
974 // FIXME: Refactor this so it makes some sense.
975 if (RefPtr<Attr> attrNode = inSynchronizationOfLazyAttribute ? 0 : attrIfExists(existingAttributeName))
976 attrNode->setValue(newValue);
978 ensureUniqueElementData()->attributeItem(index)->setValue(newValue);
981 if (!inSynchronizationOfLazyAttribute)
982 didModifyAttribute(existingAttributeName, newValue);
985 static inline AtomicString makeIdForStyleResolution(const AtomicString& value, bool inQuirksMode)
988 return value.lower();
992 static bool checkNeedsStyleInvalidationForIdChange(const AtomicString& oldId, const AtomicString& newId, const RuleFeatureSet& features)
994 ASSERT(newId != oldId);
995 if (!oldId.isEmpty() && features.hasSelectorForId(oldId))
997 if (!newId.isEmpty() && features.hasSelectorForId(newId))
1002 void Element::attributeChanged(const QualifiedName& name, const AtomicString& newValue, AttributeModificationReason reason)
1004 if (ElementShadow* parentElementShadow = shadowWhereNodeCanBeDistributed(*this)) {
1005 if (shouldInvalidateDistributionWhenAttributeChanged(parentElementShadow, name, newValue))
1006 parentElementShadow->setNeedsDistributionRecalc();
1009 parseAttribute(name, newValue);
1011 document().incDOMTreeVersion();
1013 StyleResolver* styleResolver = document().styleResolver();
1014 bool testShouldInvalidateStyle = inActiveDocument() && styleResolver && styleChangeType() < SubtreeStyleChange;
1015 bool shouldInvalidateStyle = false;
1017 if (isStyledElement() && name == styleAttr) {
1018 styleAttributeChanged(newValue, reason);
1019 } else if (isStyledElement() && isPresentationAttribute(name)) {
1020 elementData()->m_presentationAttributeStyleIsDirty = true;
1021 setNeedsStyleRecalc(LocalStyleChange);
1024 if (isIdAttributeName(name)) {
1025 AtomicString oldId = elementData()->idForStyleResolution();
1026 AtomicString newId = makeIdForStyleResolution(newValue, document().inQuirksMode());
1027 if (newId != oldId) {
1028 elementData()->setIdForStyleResolution(newId);
1029 shouldInvalidateStyle = testShouldInvalidateStyle && checkNeedsStyleInvalidationForIdChange(oldId, newId, styleResolver->ensureRuleFeatureSet());
1031 } else if (name == classAttr) {
1032 classAttributeChanged(newValue);
1033 } else if (name == HTMLNames::nameAttr) {
1034 setHasName(!newValue.isNull());
1037 invalidateNodeListCachesInAncestors(&name, this);
1039 // If there is currently no StyleResolver, we can't be sure that this attribute change won't affect style.
1040 shouldInvalidateStyle |= !styleResolver;
1042 if (shouldInvalidateStyle)
1043 setNeedsStyleRecalc(SubtreeStyleChange);
1045 if (AXObjectCache* cache = document().existingAXObjectCache())
1046 cache->handleAttributeChanged(name, this);
1049 inline void Element::attributeChangedFromParserOrByCloning(const QualifiedName& name, const AtomicString& newValue, AttributeModificationReason reason)
1052 CustomElementRegistrationContext::setTypeExtension(this, newValue);
1053 attributeChanged(name, newValue, reason);
1056 template <typename CharacterType>
1057 static inline bool classStringHasClassName(const CharacterType* characters, unsigned length)
1063 if (isNotHTMLSpace<CharacterType>(characters[i]))
1066 } while (i < length);
1071 static inline bool classStringHasClassName(const AtomicString& newClassString)
1073 unsigned length = newClassString.length();
1078 if (newClassString.is8Bit())
1079 return classStringHasClassName(newClassString.characters8(), length);
1080 return classStringHasClassName(newClassString.characters16(), length);
1083 void Element::classAttributeChanged(const AtomicString& newClassString)
1085 StyleResolver* styleResolver = document().styleResolver();
1086 bool testShouldInvalidateStyle = inActiveDocument() && styleResolver && styleChangeType() < SubtreeStyleChange;
1088 ASSERT(elementData());
1089 if (classStringHasClassName(newClassString)) {
1090 const bool shouldFoldCase = document().inQuirksMode();
1091 const SpaceSplitString oldClasses = elementData()->classNames();
1092 elementData()->setClass(newClassString, shouldFoldCase);
1093 const SpaceSplitString& newClasses = elementData()->classNames();
1094 if (testShouldInvalidateStyle)
1095 styleResolver->ensureRuleFeatureSet().scheduleStyleInvalidationForClassChange(oldClasses, newClasses, this);
1097 const SpaceSplitString& oldClasses = elementData()->classNames();
1098 if (testShouldInvalidateStyle)
1099 styleResolver->ensureRuleFeatureSet().scheduleStyleInvalidationForClassChange(oldClasses, this);
1100 elementData()->clearClass();
1104 elementRareData()->clearClassListValueForQuirksMode();
1107 bool Element::shouldInvalidateDistributionWhenAttributeChanged(ElementShadow* elementShadow, const QualifiedName& name, const AtomicString& newValue)
1109 ASSERT(elementShadow);
1110 const SelectRuleFeatureSet& featureSet = elementShadow->ensureSelectFeatureSet();
1112 if (isIdAttributeName(name)) {
1113 AtomicString oldId = elementData()->idForStyleResolution();
1114 AtomicString newId = makeIdForStyleResolution(newValue, document().inQuirksMode());
1115 if (newId != oldId) {
1116 if (!oldId.isEmpty() && featureSet.hasSelectorForId(oldId))
1118 if (!newId.isEmpty() && featureSet.hasSelectorForId(newId))
1123 if (name == HTMLNames::classAttr) {
1124 const AtomicString& newClassString = newValue;
1125 if (classStringHasClassName(newClassString)) {
1126 const bool shouldFoldCase = document().inQuirksMode();
1127 const SpaceSplitString& oldClasses = elementData()->classNames();
1128 const SpaceSplitString newClasses(newClassString, shouldFoldCase);
1129 if (featureSet.checkSelectorsForClassChange(oldClasses, newClasses))
1132 const SpaceSplitString& oldClasses = elementData()->classNames();
1133 if (featureSet.checkSelectorsForClassChange(oldClasses))
1138 return featureSet.hasSelectorForAttribute(name.localName());
1141 // Returns true is the given attribute is an event handler.
1142 // We consider an event handler any attribute that begins with "on".
1143 // It is a simple solution that has the advantage of not requiring any
1144 // code or configuration change if a new event handler is defined.
1146 static inline bool isEventHandlerAttribute(const Attribute& attribute)
1148 return attribute.name().namespaceURI().isNull() && attribute.name().localName().startsWith("on");
1151 bool Element::isJavaScriptURLAttribute(const Attribute& attribute) const
1153 return isURLAttribute(attribute) && protocolIsJavaScript(stripLeadingAndTrailingHTMLSpaces(attribute.value()));
1156 void Element::stripScriptingAttributes(Vector<Attribute>& attributeVector) const
1158 size_t destination = 0;
1159 for (size_t source = 0; source < attributeVector.size(); ++source) {
1160 if (isEventHandlerAttribute(attributeVector[source])
1161 || isJavaScriptURLAttribute(attributeVector[source])
1162 || isHTMLContentAttribute(attributeVector[source]))
1165 if (source != destination)
1166 attributeVector[destination] = attributeVector[source];
1170 attributeVector.shrink(destination);
1173 void Element::parserSetAttributes(const Vector<Attribute>& attributeVector)
1175 ASSERT(!inDocument());
1176 ASSERT(!parentNode());
1177 ASSERT(!m_elementData);
1179 if (attributeVector.isEmpty())
1182 if (document().elementDataCache())
1183 m_elementData = document().elementDataCache()->cachedShareableElementDataWithAttributes(attributeVector);
1185 m_elementData = ShareableElementData::createWithAttributes(attributeVector);
1187 // Use attributeVector instead of m_elementData because attributeChanged might modify m_elementData.
1188 for (unsigned i = 0; i < attributeVector.size(); ++i)
1189 attributeChangedFromParserOrByCloning(attributeVector[i].name(), attributeVector[i].value(), ModifiedDirectly);
1192 bool Element::hasAttributes() const
1194 synchronizeAllAttributes();
1195 return elementData() && elementData()->length();
1198 bool Element::hasEquivalentAttributes(const Element* other) const
1200 synchronizeAllAttributes();
1201 other->synchronizeAllAttributes();
1202 if (elementData() == other->elementData())
1205 return elementData()->isEquivalent(other->elementData());
1206 if (other->elementData())
1207 return other->elementData()->isEquivalent(elementData());
1211 String Element::nodeName() const
1213 return m_tagName.toString();
1216 void Element::setPrefix(const AtomicString& prefix, ExceptionState& exceptionState)
1218 UseCounter::count(document(), UseCounter::ElementSetPrefix);
1220 if (!prefix.isEmpty() && !Document::isValidName(prefix)) {
1221 exceptionState.throwDOMException(InvalidCharacterError, "The prefix '" + prefix + "' is not a valid name.");
1225 // FIXME: Raise NamespaceError if prefix is malformed per the Namespaces in XML specification.
1227 const AtomicString& nodeNamespaceURI = namespaceURI();
1228 if (nodeNamespaceURI.isEmpty() && !prefix.isEmpty()) {
1229 exceptionState.throwDOMException(NamespaceError, "No namespace is set, so a namespace prefix may not be set.");
1233 if (prefix == xmlAtom && nodeNamespaceURI != XMLNames::xmlNamespaceURI) {
1234 exceptionState.throwDOMException(NamespaceError, "The prefix '" + xmlAtom + "' may not be set on namespace '" + nodeNamespaceURI + "'.");
1238 if (exceptionState.hadException())
1241 m_tagName.setPrefix(prefix.isEmpty() ? AtomicString() : prefix);
1244 const AtomicString& Element::locateNamespacePrefix(const AtomicString& namespaceToLocate) const
1246 if (!prefix().isNull() && namespaceURI() == namespaceToLocate)
1249 if (hasAttributes()) {
1250 for (unsigned i = 0; i < attributeCount(); i++) {
1251 const Attribute* attr = attributeItem(i);
1253 if (attr->prefix() == xmlnsAtom && attr->value() == namespaceToLocate)
1254 return attr->localName();
1258 if (Element* parent = parentElement())
1259 return parent->locateNamespacePrefix(namespaceToLocate);
1264 KURL Element::baseURI() const
1266 const AtomicString& baseAttribute = fastGetAttribute(baseAttr);
1267 KURL base(KURL(), baseAttribute);
1268 if (!base.protocol().isEmpty())
1271 ContainerNode* parent = parentNode();
1275 const KURL& parentBase = parent->baseURI();
1276 if (parentBase.isNull())
1279 return KURL(parentBase, baseAttribute);
1282 const AtomicString Element::imageSourceURL() const
1284 return getAttribute(srcAttr);
1287 bool Element::rendererIsNeeded(const RenderStyle& style)
1289 return style.display() != NONE;
1292 RenderObject* Element::createRenderer(RenderStyle* style)
1294 return RenderObject::createObject(this, style);
1297 Node::InsertionNotificationRequest Element::insertedInto(ContainerNode* insertionPoint)
1299 // need to do superclass processing first so inDocument() is true
1300 // by the time we reach updateId
1301 ContainerNode::insertedInto(insertionPoint);
1303 if (containsFullScreenElement() && parentElement() && !parentElement()->containsFullScreenElement())
1304 setContainsFullScreenElementOnAncestorsCrossingFrameBoundaries(true);
1306 ASSERT(!hasRareData() || !elementRareData()->hasPseudoElements());
1308 if (!insertionPoint->isInTreeScope())
1309 return InsertionDone;
1312 elementRareData()->clearClassListValueForQuirksMode();
1314 if (isUpgradedCustomElement() && inDocument())
1315 CustomElement::didEnterDocument(this, document());
1317 TreeScope& scope = insertionPoint->treeScope();
1318 if (scope != treeScope())
1319 return InsertionDone;
1321 const AtomicString& idValue = getIdAttribute();
1322 if (!idValue.isNull())
1323 updateId(scope, nullAtom, idValue);
1325 const AtomicString& nameValue = getNameAttribute();
1326 if (!nameValue.isNull())
1327 updateName(nullAtom, nameValue);
1329 if (hasTagName(labelTag)) {
1330 if (scope.shouldCacheLabelsByForAttribute())
1331 updateLabel(scope, nullAtom, fastGetAttribute(forAttr));
1334 if (parentElement() && parentElement()->isInCanvasSubtree())
1335 setIsInCanvasSubtree(true);
1337 return InsertionDone;
1340 void Element::removedFrom(ContainerNode* insertionPoint)
1342 bool wasInDocument = insertionPoint->inDocument();
1344 ASSERT(!hasRareData() || !elementRareData()->hasPseudoElements());
1346 if (containsFullScreenElement())
1347 setContainsFullScreenElementOnAncestorsCrossingFrameBoundaries(false);
1349 if (document().page())
1350 document().page()->pointerLockController().elementRemoved(this);
1352 setSavedLayerScrollOffset(IntSize());
1354 if (insertionPoint->isInTreeScope() && treeScope() == document()) {
1355 const AtomicString& idValue = getIdAttribute();
1356 if (!idValue.isNull())
1357 updateId(insertionPoint->treeScope(), idValue, nullAtom);
1359 const AtomicString& nameValue = getNameAttribute();
1360 if (!nameValue.isNull())
1361 updateName(nameValue, nullAtom);
1363 if (hasTagName(labelTag)) {
1364 TreeScope& treeScope = insertionPoint->treeScope();
1365 if (treeScope.shouldCacheLabelsByForAttribute())
1366 updateLabel(treeScope, fastGetAttribute(forAttr), nullAtom);
1370 ContainerNode::removedFrom(insertionPoint);
1371 if (wasInDocument) {
1372 if (hasPendingResources())
1373 document().accessSVGExtensions()->removeElementFromPendingResources(this);
1375 if (isUpgradedCustomElement())
1376 CustomElement::didLeaveDocument(this, insertionPoint->document());
1379 document().removeFromTopLayer(this);
1382 elementRareData()->setIsInCanvasSubtree(false);
1385 void Element::attach(const AttachContext& context)
1387 ASSERT(document().inStyleRecalc());
1389 StyleResolverParentPusher parentPusher(*this);
1391 // We've already been through detach when doing an attach, but we might
1392 // need to clear any state that's been added since then.
1393 if (hasRareData() && styleChangeType() == NeedsReattachStyleChange) {
1394 ElementRareData* data = elementRareData();
1395 data->clearComputedStyle();
1396 data->resetDynamicRestyleObservations();
1397 // Only clear the style state if we're not going to reuse the style from recalcStyle.
1398 if (!context.resolvedStyle)
1399 data->resetStyleState();
1402 RenderTreeBuilder(this, context.resolvedStyle).createRendererForElementIfNeeded();
1404 addCallbackSelectors();
1406 createPseudoElementIfNeeded(BEFORE);
1408 // When a shadow root exists, it does the work of attaching the children.
1409 if (ElementShadow* shadow = this->shadow()) {
1410 parentPusher.push();
1411 shadow->attach(context);
1412 } else if (firstChild()) {
1413 parentPusher.push();
1416 ContainerNode::attach(context);
1418 createPseudoElementIfNeeded(AFTER);
1419 createPseudoElementIfNeeded(BACKDROP);
1421 if (hasRareData()) {
1422 ElementRareData* data = elementRareData();
1423 if (data->needsFocusAppearanceUpdateSoonAfterAttach()) {
1424 if (isFocusable() && document().focusedElement() == this)
1425 document().updateFocusAppearanceSoon(false /* don't restore selection */);
1426 data->setNeedsFocusAppearanceUpdateSoonAfterAttach(false);
1429 if (ActiveAnimations* activeAnimations = data->activeAnimations()) {
1430 activeAnimations->cssAnimations().cancel();
1431 activeAnimations->setAnimationStyleChange(false);
1436 InspectorInstrumentation::didRecalculateStyleForElement(this);
1439 void Element::detach(const AttachContext& context)
1441 RenderWidget::UpdateSuspendScope suspendWidgetHierarchyUpdates;
1442 cancelFocusAppearanceUpdate();
1443 removeCallbackSelectors();
1444 if (hasRareData()) {
1445 ElementRareData* data = elementRareData();
1446 data->clearPseudoElements();
1448 // attach() will perform the below steps for us when inside recalcStyle.
1449 if (!document().inStyleRecalc()) {
1450 data->resetStyleState();
1451 data->clearComputedStyle();
1452 data->resetDynamicRestyleObservations();
1455 if (ActiveAnimations* activeAnimations = data->activeAnimations()) {
1456 if (context.performingReattach) {
1457 // FIXME: We call detach from withing style recalc, so compositingState is not up to date.
1458 // https://code.google.com/p/chromium/issues/detail?id=339847
1459 DisableCompositingQueryAsserts disabler;
1461 // FIXME: restart compositor animations rather than pull back to the main thread
1462 activeAnimations->cancelAnimationOnCompositor();
1464 activeAnimations->cssAnimations().cancel();
1465 activeAnimations->setAnimationStyleChange(false);
1469 if (ElementShadow* shadow = data->shadow())
1470 shadow->detach(context);
1472 ContainerNode::detach(context);
1475 bool Element::pseudoStyleCacheIsInvalid(const RenderStyle* currentStyle, RenderStyle* newStyle)
1477 ASSERT(currentStyle == renderStyle());
1483 const PseudoStyleCache* pseudoStyleCache = currentStyle->cachedPseudoStyles();
1484 if (!pseudoStyleCache)
1487 size_t cacheSize = pseudoStyleCache->size();
1488 for (size_t i = 0; i < cacheSize; ++i) {
1489 RefPtr<RenderStyle> newPseudoStyle;
1490 PseudoId pseudoId = pseudoStyleCache->at(i)->styleType();
1491 if (pseudoId == FIRST_LINE || pseudoId == FIRST_LINE_INHERITED)
1492 newPseudoStyle = renderer()->uncachedFirstLineStyle(newStyle);
1494 newPseudoStyle = renderer()->getUncachedPseudoStyle(PseudoStyleRequest(pseudoId), newStyle, newStyle);
1495 if (!newPseudoStyle)
1497 if (*newPseudoStyle != *pseudoStyleCache->at(i)) {
1498 if (pseudoId < FIRST_INTERNAL_PSEUDOID)
1499 newStyle->setHasPseudoStyle(pseudoId);
1500 newStyle->addCachedPseudoStyle(newPseudoStyle);
1501 if (pseudoId == FIRST_LINE || pseudoId == FIRST_LINE_INHERITED) {
1502 // FIXME: We should do an actual diff to determine whether a repaint vs. layout
1503 // is needed, but for now just assume a layout will be required. The diff code
1504 // in RenderObject::setStyle would need to be factored out so that it could be reused.
1505 renderer()->setNeedsLayoutAndPrefWidthsRecalc();
1513 PassRefPtr<RenderStyle> Element::styleForRenderer()
1515 ASSERT(document().inStyleRecalc());
1517 RefPtr<RenderStyle> style;
1519 // FIXME: Instead of clearing updates that may have been added from calls to styleForElement
1520 // outside recalcStyle, we should just never set them if we're not inside recalcStyle.
1521 if (ActiveAnimations* activeAnimations = this->activeAnimations())
1522 activeAnimations->cssAnimations().setPendingUpdate(nullptr);
1524 if (hasCustomStyleCallbacks())
1525 style = customStyleForRenderer();
1527 style = originalStyleForRenderer();
1529 // styleForElement() might add active animations so we need to get it again.
1530 if (ActiveAnimations* activeAnimations = this->activeAnimations())
1531 activeAnimations->cssAnimations().maybeApplyPendingUpdate(this);
1534 return style.release();
1537 PassRefPtr<RenderStyle> Element::originalStyleForRenderer()
1539 ASSERT(document().inStyleRecalc());
1540 return document().ensureStyleResolver().styleForElement(this);
1543 void Element::recalcStyle(StyleRecalcChange change, Text* nextTextSibling)
1545 ASSERT(document().inStyleRecalc());
1546 ASSERT(!parentOrShadowHostNode()->needsStyleRecalc());
1548 if (hasCustomStyleCallbacks())
1549 willRecalcStyle(change);
1551 if (change >= Inherit || needsStyleRecalc()) {
1552 if (hasRareData()) {
1553 ElementRareData* data = elementRareData();
1554 data->resetStyleState();
1555 data->clearComputedStyle();
1557 if (change >= Inherit) {
1558 if (ActiveAnimations* activeAnimations = data->activeAnimations())
1559 activeAnimations->setAnimationStyleChange(false);
1562 if (parentRenderStyle())
1563 change = recalcOwnStyle(change);
1564 clearNeedsStyleRecalc();
1567 // If we reattached we don't need to recalc the style of our descendants anymore.
1568 if ((change >= UpdatePseudoElements && change < Reattach) || childNeedsStyleRecalc()) {
1569 recalcChildStyle(change);
1570 clearChildNeedsStyleRecalc();
1573 if (hasCustomStyleCallbacks())
1574 didRecalcStyle(change);
1576 if (change == Reattach)
1577 reattachWhitespaceSiblings(nextTextSibling);
1580 StyleRecalcChange Element::recalcOwnStyle(StyleRecalcChange change)
1582 ASSERT(document().inStyleRecalc());
1583 ASSERT(!parentOrShadowHostNode()->needsStyleRecalc());
1584 ASSERT(change >= Inherit || needsStyleRecalc());
1585 ASSERT(parentRenderStyle());
1587 RefPtr<RenderStyle> oldStyle = renderStyle();
1588 RefPtr<RenderStyle> newStyle = styleForRenderer();
1589 StyleRecalcChange localChange = RenderStyle::compare(oldStyle.get(), newStyle.get());
1593 if (localChange == Reattach) {
1594 AttachContext reattachContext;
1595 reattachContext.resolvedStyle = newStyle.get();
1596 reattach(reattachContext);
1602 InspectorInstrumentation::didRecalculateStyleForElement(this);
1604 if (localChange != NoChange)
1605 updateCallbackSelectors(oldStyle.get(), newStyle.get());
1607 if (RenderObject* renderer = this->renderer()) {
1608 if (localChange != NoChange || pseudoStyleCacheIsInvalid(oldStyle.get(), newStyle.get()) || shouldNotifyRendererWithIdenticalStyles()) {
1609 renderer->setStyle(newStyle.get());
1611 // Although no change occurred, we use the new style so that the cousin style sharing code won't get
1612 // fooled into believing this style is the same.
1613 // FIXME: We may be able to remove this hack, see discussion in
1614 // https://codereview.chromium.org/30453002/
1615 renderer->setStyleInternal(newStyle.get());
1619 if (styleChangeType() >= SubtreeStyleChange)
1622 if (change > Inherit || localChange > Inherit)
1623 return max(localChange, change);
1625 if (localChange < Inherit && (oldStyle->hasPseudoElementStyle() || newStyle->hasPseudoElementStyle()))
1626 return UpdatePseudoElements;
1631 void Element::recalcChildStyle(StyleRecalcChange change)
1633 ASSERT(document().inStyleRecalc());
1634 ASSERT(change >= UpdatePseudoElements || childNeedsStyleRecalc());
1635 ASSERT(!needsStyleRecalc());
1637 StyleResolverParentPusher parentPusher(*this);
1639 if (change > UpdatePseudoElements || childNeedsStyleRecalc()) {
1640 for (ShadowRoot* root = youngestShadowRoot(); root; root = root->olderShadowRoot()) {
1641 if (root->shouldCallRecalcStyle(change)) {
1642 parentPusher.push();
1643 root->recalcStyle(change);
1648 updatePseudoElement(BEFORE, change);
1650 if (change < Force && hasRareData() && childNeedsStyleRecalc())
1651 checkForChildrenAdjacentRuleChanges();
1653 if (change > UpdatePseudoElements || childNeedsStyleRecalc()) {
1654 // This loop is deliberately backwards because we use insertBefore in the rendering tree, and want to avoid
1655 // a potentially n^2 loop to find the insertion point while resolving style. Having us start from the last
1656 // child and work our way back means in the common case, we'll find the insertion point in O(1) time.
1657 // See crbug.com/288225
1658 StyleResolver& styleResolver = document().ensureStyleResolver();
1659 Text* lastTextNode = 0;
1660 for (Node* child = lastChild(); child; child = child->previousSibling()) {
1661 if (child->isTextNode()) {
1662 toText(child)->recalcTextStyle(change, lastTextNode);
1663 lastTextNode = toText(child);
1664 } else if (child->isElementNode()) {
1665 Element* element = toElement(child);
1666 if (element->shouldCallRecalcStyle(change)) {
1667 parentPusher.push();
1668 element->recalcStyle(change, lastTextNode);
1669 } else if (element->supportsStyleSharing()) {
1670 styleResolver.addToStyleSharingList(*element);
1672 if (element->renderer())
1678 updatePseudoElement(AFTER, change);
1679 updatePseudoElement(BACKDROP, change);
1682 void Element::checkForChildrenAdjacentRuleChanges()
1684 bool hasDirectAdjacentRules = childrenAffectedByDirectAdjacentRules();
1685 bool hasIndirectAdjacentRules = childrenAffectedByForwardPositionalRules();
1687 if (!hasDirectAdjacentRules && !hasIndirectAdjacentRules)
1690 unsigned forceCheckOfNextElementCount = 0;
1691 bool forceCheckOfAnyElementSibling = false;
1693 for (Node* child = firstChild(); child; child = child->nextSibling()) {
1694 if (!child->isElementNode())
1696 Element* element = toElement(child);
1697 bool childRulesChanged = element->needsStyleRecalc() && element->styleChangeType() >= SubtreeStyleChange;
1699 if (forceCheckOfNextElementCount || forceCheckOfAnyElementSibling)
1700 element->setNeedsStyleRecalc(SubtreeStyleChange);
1702 if (forceCheckOfNextElementCount)
1703 forceCheckOfNextElementCount--;
1705 if (childRulesChanged && hasDirectAdjacentRules)
1706 forceCheckOfNextElementCount = document().styleEngine()->maxDirectAdjacentSelectors();
1708 forceCheckOfAnyElementSibling = forceCheckOfAnyElementSibling || (childRulesChanged && hasIndirectAdjacentRules);
1712 void Element::updateCallbackSelectors(RenderStyle* oldStyle, RenderStyle* newStyle)
1714 Vector<String> emptyVector;
1715 const Vector<String>& oldCallbackSelectors = oldStyle ? oldStyle->callbackSelectors() : emptyVector;
1716 const Vector<String>& newCallbackSelectors = newStyle ? newStyle->callbackSelectors() : emptyVector;
1717 if (oldCallbackSelectors.isEmpty() && newCallbackSelectors.isEmpty())
1719 if (oldCallbackSelectors != newCallbackSelectors)
1720 CSSSelectorWatch::from(document()).updateSelectorMatches(oldCallbackSelectors, newCallbackSelectors);
1723 void Element::addCallbackSelectors()
1725 updateCallbackSelectors(0, renderStyle());
1728 void Element::removeCallbackSelectors()
1730 updateCallbackSelectors(renderStyle(), 0);
1733 ElementShadow* Element::shadow() const
1735 return hasRareData() ? elementRareData()->shadow() : 0;
1738 ElementShadow& Element::ensureShadow()
1740 return ensureElementRareData().ensureShadow();
1743 void Element::didAffectSelector(AffectedSelectorMask mask)
1745 setNeedsStyleRecalc(SubtreeStyleChange);
1746 if (ElementShadow* elementShadow = shadowWhereNodeCanBeDistributed(*this))
1747 elementShadow->didAffectSelector(mask);
1750 void Element::setAnimationStyleChange(bool animationStyleChange)
1752 if (ActiveAnimations* activeAnimations = elementRareData()->activeAnimations())
1753 activeAnimations->setAnimationStyleChange(animationStyleChange);
1756 void Element::setNeedsAnimationStyleRecalc()
1758 if (styleChangeType() != NoStyleChange)
1761 setNeedsStyleRecalc(LocalStyleChange);
1762 setAnimationStyleChange(true);
1765 PassRefPtr<ShadowRoot> Element::createShadowRoot(ExceptionState& exceptionState)
1767 if (alwaysCreateUserAgentShadowRoot())
1768 ensureUserAgentShadowRoot();
1770 // Some elements make assumptions about what kind of renderers they allow
1771 // as children so we can't allow author shadows on them for now. An override
1772 // flag is provided for testing how author shadows interact on these elements.
1773 if (!areAuthorShadowsAllowed() && !RuntimeEnabledFeatures::authorShadowDOMForAnyElementEnabled()) {
1774 exceptionState.throwDOMException(HierarchyRequestError, "Author-created shadow roots are disabled for this element.");
1778 return PassRefPtr<ShadowRoot>(ensureShadow().addShadowRoot(*this, ShadowRoot::AuthorShadowRoot));
1781 ShadowRoot* Element::shadowRoot() const
1783 ElementShadow* elementShadow = shadow();
1786 ShadowRoot* shadowRoot = elementShadow->youngestShadowRoot();
1787 if (shadowRoot->type() == ShadowRoot::AuthorShadowRoot)
1792 void Element::didAddShadowRoot(ShadowRoot&)
1796 ShadowRoot* Element::userAgentShadowRoot() const
1798 if (ElementShadow* elementShadow = shadow()) {
1799 if (ShadowRoot* shadowRoot = elementShadow->oldestShadowRoot()) {
1800 ASSERT(shadowRoot->type() == ShadowRoot::UserAgentShadowRoot);
1808 ShadowRoot& Element::ensureUserAgentShadowRoot()
1810 if (ShadowRoot* shadowRoot = userAgentShadowRoot())
1812 ShadowRoot& shadowRoot = ensureShadow().addShadowRoot(*this, ShadowRoot::UserAgentShadowRoot);
1813 didAddUserAgentShadowRoot(shadowRoot);
1817 bool Element::childTypeAllowed(NodeType type) const
1823 case PROCESSING_INSTRUCTION_NODE:
1824 case CDATA_SECTION_NODE:
1832 void Element::checkForEmptyStyleChange(RenderStyle* style)
1834 if (!style && !styleAffectedByEmpty())
1837 if (!style || (styleAffectedByEmpty() && (!style->emptyState() || hasChildNodes())))
1838 setNeedsStyleRecalc(SubtreeStyleChange);
1841 void Element::checkForSiblingStyleChanges(bool finishedParsingCallback, Node* beforeChange, Node* afterChange, int childCountDelta)
1843 if (!inActiveDocument() || document().hasPendingForcedStyleRecalc() || styleChangeType() >= SubtreeStyleChange)
1846 RenderStyle* style = renderStyle();
1849 checkForEmptyStyleChange(style);
1851 if (!style || (needsStyleRecalc() && childrenAffectedByPositionalRules()))
1854 // Forward positional selectors include the ~ selector, nth-child, nth-of-type, first-of-type and only-of-type.
1855 // Backward positional selectors include nth-last-child, nth-last-of-type, last-of-type and only-of-type.
1856 // We have to invalidate everything following the insertion point in the forward case, and everything before the insertion point in the
1858 // |afterChange| is 0 in the parser callback case, so we won't do any work for the forward case if we don't have to.
1859 // For performance reasons we just mark the parent node as changed, since we don't want to make childrenChanged O(n^2) by crawling all our kids
1860 // here. recalcStyle will then force a walk of the children when it sees that this has happened.
1861 if ((childrenAffectedByForwardPositionalRules() && afterChange) || (childrenAffectedByBackwardPositionalRules() && beforeChange)) {
1862 setNeedsStyleRecalc(SubtreeStyleChange);
1866 // :first-child. In the parser callback case, we don't have to check anything, since we were right the first time.
1867 // In the DOM case, we only need to do something if |afterChange| is not 0.
1868 // |afterChange| is 0 in the parser case, so it works out that we'll skip this block.
1869 if (childrenAffectedByFirstChildRules() && afterChange) {
1870 // Find our new first child.
1871 Element* newFirstChild = ElementTraversal::firstWithin(*this);
1872 RenderStyle* newFirstChildStyle = newFirstChild ? newFirstChild->renderStyle() : 0;
1874 // Find the first element node following |afterChange|
1875 Node* firstElementAfterInsertion = afterChange->isElementNode() ? afterChange : ElementTraversal::nextSibling(*afterChange);
1876 RenderStyle* firstElementAfterInsertionStyle = firstElementAfterInsertion ? firstElementAfterInsertion->renderStyle() : 0;
1878 // This is the insert/append case.
1879 if (newFirstChild != firstElementAfterInsertion && firstElementAfterInsertionStyle && firstElementAfterInsertionStyle->firstChildState())
1880 firstElementAfterInsertion->setNeedsStyleRecalc(SubtreeStyleChange);
1882 // We also have to handle node removal.
1883 if (childCountDelta < 0 && newFirstChild == firstElementAfterInsertion && newFirstChild && (!newFirstChildStyle || !newFirstChildStyle->firstChildState()))
1884 newFirstChild->setNeedsStyleRecalc(SubtreeStyleChange);
1887 // :last-child. In the parser callback case, we don't have to check anything, since we were right the first time.
1888 // In the DOM case, we only need to do something if |afterChange| is not 0.
1889 if (childrenAffectedByLastChildRules() && beforeChange) {
1890 // Find our new last child.
1891 Node* newLastChild = ElementTraversal::lastWithin(*this);
1892 RenderStyle* newLastChildStyle = newLastChild ? newLastChild->renderStyle() : 0;
1894 // Find the last element node going backwards from |beforeChange|
1895 Node* lastElementBeforeInsertion = beforeChange->isElementNode() ? beforeChange : ElementTraversal::previousSibling(*beforeChange);
1896 RenderStyle* lastElementBeforeInsertionStyle = lastElementBeforeInsertion ? lastElementBeforeInsertion->renderStyle() : 0;
1898 if (newLastChild != lastElementBeforeInsertion && lastElementBeforeInsertionStyle && lastElementBeforeInsertionStyle->lastChildState())
1899 lastElementBeforeInsertion->setNeedsStyleRecalc(SubtreeStyleChange);
1901 // We also have to handle node removal. The parser callback case is similar to node removal as well in that we need to change the last child
1903 if ((childCountDelta < 0 || finishedParsingCallback) && newLastChild == lastElementBeforeInsertion && newLastChild && (!newLastChildStyle || !newLastChildStyle->lastChildState()))
1904 newLastChild->setNeedsStyleRecalc(SubtreeStyleChange);
1907 // The + selector. We need to invalidate the first element following the insertion point. It is the only possible element
1908 // that could be affected by this DOM change.
1909 if (childrenAffectedByDirectAdjacentRules() && afterChange) {
1910 if (Node* firstElementAfterInsertion = afterChange->isElementNode() ? afterChange : ElementTraversal::nextSibling(*afterChange))
1911 firstElementAfterInsertion->setNeedsStyleRecalc(SubtreeStyleChange);
1915 void Element::childrenChanged(bool changedByParser, Node* beforeChange, Node* afterChange, int childCountDelta)
1917 ContainerNode::childrenChanged(changedByParser, beforeChange, afterChange, childCountDelta);
1918 if (changedByParser)
1919 checkForEmptyStyleChange(renderStyle());
1921 checkForSiblingStyleChanges(false, beforeChange, afterChange, childCountDelta);
1923 if (ElementShadow* shadow = this->shadow())
1924 shadow->setNeedsDistributionRecalc();
1927 void Element::removeAllEventListeners()
1929 ContainerNode::removeAllEventListeners();
1930 if (ElementShadow* shadow = this->shadow())
1931 shadow->removeAllEventListeners();
1934 void Element::finishParsingChildren()
1936 setIsFinishedParsingChildren(true);
1937 checkForSiblingStyleChanges(this, lastChild(), 0, 0);
1941 void Element::formatForDebugger(char* buffer, unsigned length) const
1943 StringBuilder result;
1946 result.append(nodeName());
1948 s = getIdAttribute();
1949 if (s.length() > 0) {
1950 if (result.length() > 0)
1951 result.appendLiteral("; ");
1952 result.appendLiteral("id=");
1956 s = getAttribute(classAttr);
1957 if (s.length() > 0) {
1958 if (result.length() > 0)
1959 result.appendLiteral("; ");
1960 result.appendLiteral("class=");
1964 strncpy(buffer, result.toString().utf8().data(), length - 1);
1968 const Vector<RefPtr<Attr> >& Element::attrNodeList()
1970 ASSERT(hasSyntheticAttrChildNodes());
1971 return *attrNodeListForElement(this);
1974 PassRefPtr<Attr> Element::setAttributeNode(Attr* attrNode, ExceptionState& exceptionState)
1977 exceptionState.throwDOMException(TypeMismatchError, "The node provided is invalid.");
1981 RefPtr<Attr> oldAttrNode = attrIfExists(attrNode->qualifiedName());
1982 if (oldAttrNode.get() == attrNode)
1983 return attrNode; // This Attr is already attached to the element.
1985 // InUseAttributeError: Raised if node is an Attr that is already an attribute of another Element object.
1986 // The DOM user must explicitly clone Attr nodes to re-use them in other elements.
1987 if (attrNode->ownerElement()) {
1988 exceptionState.throwDOMException(InUseAttributeError, "The node provided is an attribute node that is already an attribute of another Element; attribute nodes must be explicitly cloned.");
1992 synchronizeAllAttributes();
1993 UniqueElementData* elementData = ensureUniqueElementData();
1995 size_t index = elementData->getAttributeItemIndex(attrNode->qualifiedName(), shouldIgnoreAttributeCase());
1996 if (index != kNotFound) {
1998 detachAttrNodeFromElementWithValue(oldAttrNode.get(), elementData->attributeItem(index)->value());
2000 oldAttrNode = Attr::create(document(), attrNode->qualifiedName(), elementData->attributeItem(index)->value());
2003 setAttributeInternal(index, attrNode->qualifiedName(), attrNode->value(), NotInSynchronizationOfLazyAttribute);
2005 attrNode->attachToElement(this);
2006 treeScope().adoptIfNeeded(*attrNode);
2007 ensureAttrNodeListForElement(this).append(attrNode);
2009 return oldAttrNode.release();
2012 PassRefPtr<Attr> Element::removeAttributeNode(Attr* attr, ExceptionState& exceptionState)
2015 exceptionState.throwDOMException(TypeMismatchError, "The node provided is invalid.");
2018 if (attr->ownerElement() != this) {
2019 exceptionState.throwDOMException(NotFoundError, "The node provided is owned by another element.");
2023 ASSERT(document() == attr->document());
2025 synchronizeAttribute(attr->qualifiedName());
2027 size_t index = elementData()->getAttrIndex(attr);
2028 if (index == kNotFound) {
2029 exceptionState.throwDOMException(NotFoundError, "The attribute was not found on this element.");
2033 RefPtr<Attr> guard(attr);
2034 detachAttrNodeAtIndex(attr, index);
2035 return guard.release();
2038 bool Element::parseAttributeName(QualifiedName& out, const AtomicString& namespaceURI, const AtomicString& qualifiedName, ExceptionState& exceptionState)
2040 AtomicString prefix, localName;
2041 if (!Document::parseQualifiedName(qualifiedName, prefix, localName, exceptionState))
2043 ASSERT(!exceptionState.hadException());
2045 QualifiedName qName(prefix, localName, namespaceURI);
2047 if (!Document::hasValidNamespaceForAttributes(qName)) {
2048 exceptionState.throwDOMException(NamespaceError, "'" + namespaceURI + "' is an invalid namespace for attributes.");
2056 void Element::setAttributeNS(const AtomicString& namespaceURI, const AtomicString& qualifiedName, const AtomicString& value, ExceptionState& exceptionState)
2058 QualifiedName parsedName = anyName;
2059 if (!parseAttributeName(parsedName, namespaceURI, qualifiedName, exceptionState))
2061 setAttribute(parsedName, value);
2064 void Element::removeAttributeInternal(size_t index, SynchronizationOfLazyAttribute inSynchronizationOfLazyAttribute)
2066 ASSERT_WITH_SECURITY_IMPLICATION(index < attributeCount());
2068 UniqueElementData* elementData = ensureUniqueElementData();
2070 QualifiedName name = elementData->attributeItem(index)->name();
2071 AtomicString valueBeingRemoved = elementData->attributeItem(index)->value();
2073 if (!inSynchronizationOfLazyAttribute) {
2074 if (!valueBeingRemoved.isNull())
2075 willModifyAttribute(name, valueBeingRemoved, nullAtom);
2078 if (RefPtr<Attr> attrNode = attrIfExists(name))
2079 detachAttrNodeFromElementWithValue(attrNode.get(), elementData->attributeItem(index)->value());
2081 elementData->removeAttribute(index);
2083 if (!inSynchronizationOfLazyAttribute)
2084 didRemoveAttribute(name);
2087 void Element::addAttributeInternal(const QualifiedName& name, const AtomicString& value, SynchronizationOfLazyAttribute inSynchronizationOfLazyAttribute)
2089 if (!inSynchronizationOfLazyAttribute)
2090 willModifyAttribute(name, nullAtom, value);
2091 ensureUniqueElementData()->addAttribute(name, value);
2092 if (!inSynchronizationOfLazyAttribute)
2093 didAddAttribute(name, value);
2096 void Element::removeAttribute(const AtomicString& name)
2101 AtomicString localName = shouldIgnoreAttributeCase() ? name.lower() : name;
2102 size_t index = elementData()->getAttributeItemIndex(localName, false);
2103 if (index == kNotFound) {
2104 if (UNLIKELY(localName == styleAttr) && elementData()->m_styleAttributeIsDirty && isStyledElement())
2105 removeAllInlineStyleProperties();
2109 removeAttributeInternal(index, NotInSynchronizationOfLazyAttribute);
2112 void Element::removeAttributeNS(const AtomicString& namespaceURI, const AtomicString& localName)
2114 removeAttribute(QualifiedName(nullAtom, localName, namespaceURI));
2117 PassRefPtr<Attr> Element::getAttributeNode(const AtomicString& localName)
2121 synchronizeAttribute(localName);
2122 const Attribute* attribute = elementData()->getAttributeItem(localName, shouldIgnoreAttributeCase());
2125 return ensureAttr(attribute->name());
2128 PassRefPtr<Attr> Element::getAttributeNodeNS(const AtomicString& namespaceURI, const AtomicString& localName)
2132 QualifiedName qName(nullAtom, localName, namespaceURI);
2133 synchronizeAttribute(qName);
2134 const Attribute* attribute = elementData()->getAttributeItem(qName);
2137 return ensureAttr(attribute->name());
2140 bool Element::hasAttribute(const AtomicString& localName) const
2144 synchronizeAttribute(localName);
2145 return elementData()->getAttributeItem(shouldIgnoreAttributeCase() ? localName.lower() : localName, false);
2148 bool Element::hasAttributeNS(const AtomicString& namespaceURI, const AtomicString& localName) const
2152 QualifiedName qName(nullAtom, localName, namespaceURI);
2153 synchronizeAttribute(qName);
2154 return elementData()->getAttributeItem(qName);
2157 void Element::focus(bool restorePreviousSelection, FocusType type)
2162 Document& doc = document();
2163 if (doc.focusedElement() == this)
2166 // If the stylesheets have already been loaded we can reliably check isFocusable.
2167 // If not, we continue and set the focused node on the focus controller below so
2168 // that it can be updated soon after attach.
2169 if (doc.haveStylesheetsLoaded()) {
2170 doc.updateLayoutIgnorePendingStylesheets();
2175 if (!supportsFocus())
2178 RefPtr<Node> protect;
2179 if (Page* page = doc.page()) {
2180 // Focus and change event handlers can cause us to lose our last ref.
2181 // If a focus event handler changes the focus to a different node it
2182 // does not make sense to continue and update appearence.
2184 if (!page->focusController().setFocusedElement(this, doc.frame(), type))
2188 // Setting the focused node above might have invalidated the layout due to scripts.
2189 doc.updateLayoutIgnorePendingStylesheets();
2191 if (!isFocusable()) {
2192 ensureElementRareData().setNeedsFocusAppearanceUpdateSoonAfterAttach(true);
2196 cancelFocusAppearanceUpdate();
2197 updateFocusAppearance(restorePreviousSelection);
2200 void Element::updateFocusAppearance(bool /*restorePreviousSelection*/)
2202 if (isRootEditableElement()) {
2203 Frame* frame = document().frame();
2207 // When focusing an editable element in an iframe, don't reset the selection if it already contains a selection.
2208 if (this == frame->selection().rootEditableElement())
2211 // FIXME: We should restore the previous selection if there is one.
2212 VisibleSelection newSelection = VisibleSelection(firstPositionInOrBeforeNode(this), DOWNSTREAM);
2213 frame->selection().setSelection(newSelection);
2214 frame->selection().revealSelection();
2215 } else if (renderer() && !renderer()->isWidget())
2216 renderer()->scrollRectToVisible(boundingBox());
2219 void Element::blur()
2221 cancelFocusAppearanceUpdate();
2222 if (treeScope().adjustedFocusedElement() == this) {
2223 Document& doc = document();
2225 doc.page()->focusController().setFocusedElement(0, doc.frame());
2227 doc.setFocusedElement(0);
2231 bool Element::isFocusable() const
2233 return inDocument() && supportsFocus() && !isInert() && rendererIsFocusable();
2236 bool Element::isKeyboardFocusable() const
2238 return isFocusable() && tabIndex() >= 0;
2241 bool Element::isMouseFocusable() const
2243 return isFocusable();
2246 void Element::dispatchFocusEvent(Element* oldFocusedElement, FocusType)
2248 RefPtr<FocusEvent> event = FocusEvent::create(EventTypeNames::focus, false, false, document().domWindow(), 0, oldFocusedElement);
2249 EventDispatcher::dispatchEvent(this, FocusEventDispatchMediator::create(event.release()));
2252 void Element::dispatchBlurEvent(Element* newFocusedElement)
2254 RefPtr<FocusEvent> event = FocusEvent::create(EventTypeNames::blur, false, false, document().domWindow(), 0, newFocusedElement);
2255 EventDispatcher::dispatchEvent(this, BlurEventDispatchMediator::create(event.release()));
2258 void Element::dispatchFocusInEvent(const AtomicString& eventType, Element* oldFocusedElement)
2260 ASSERT(!NoEventDispatchAssertion::isEventDispatchForbidden());
2261 ASSERT(eventType == EventTypeNames::focusin || eventType == EventTypeNames::DOMFocusIn);
2262 dispatchScopedEventDispatchMediator(FocusInEventDispatchMediator::create(FocusEvent::create(eventType, true, false, document().domWindow(), 0, oldFocusedElement)));
2265 void Element::dispatchFocusOutEvent(const AtomicString& eventType, Element* newFocusedElement)
2267 ASSERT(!NoEventDispatchAssertion::isEventDispatchForbidden());
2268 ASSERT(eventType == EventTypeNames::focusout || eventType == EventTypeNames::DOMFocusOut);
2269 dispatchScopedEventDispatchMediator(FocusOutEventDispatchMediator::create(FocusEvent::create(eventType, true, false, document().domWindow(), 0, newFocusedElement)));
2272 String Element::innerHTML() const
2274 return createMarkup(this, ChildrenOnly);
2277 String Element::outerHTML() const
2279 return createMarkup(this);
2282 void Element::setInnerHTML(const String& html, ExceptionState& exceptionState)
2284 if (RefPtr<DocumentFragment> fragment = createFragmentForInnerOuterHTML(html, this, AllowScriptingContent, "innerHTML", exceptionState)) {
2285 ContainerNode* container = this;
2286 if (hasTagName(templateTag))
2287 container = toHTMLTemplateElement(this)->content();
2288 replaceChildrenWithFragment(container, fragment.release(), exceptionState);
2292 void Element::setOuterHTML(const String& html, ExceptionState& exceptionState)
2294 Node* p = parentNode();
2296 exceptionState.throwDOMException(NoModificationAllowedError, "This element has no parent node.");
2299 if (!p->isElementNode()) {
2300 exceptionState.throwDOMException(NoModificationAllowedError, "This element's parent is of type '" + p->nodeName() + "', which is not an element node.");
2304 RefPtr<Element> parent = toElement(p);
2305 RefPtr<Node> prev = previousSibling();
2306 RefPtr<Node> next = nextSibling();
2308 RefPtr<DocumentFragment> fragment = createFragmentForInnerOuterHTML(html, parent.get(), AllowScriptingContent, "outerHTML", exceptionState);
2309 if (exceptionState.hadException())
2312 parent->replaceChild(fragment.release(), this, exceptionState);
2313 RefPtr<Node> node = next ? next->previousSibling() : 0;
2314 if (!exceptionState.hadException() && node && node->isTextNode())
2315 mergeWithNextTextNode(node.release(), exceptionState);
2317 if (!exceptionState.hadException() && prev && prev->isTextNode())
2318 mergeWithNextTextNode(prev.release(), exceptionState);
2321 Node* Element::insertAdjacent(const String& where, Node* newChild, ExceptionState& exceptionState)
2323 if (equalIgnoringCase(where, "beforeBegin")) {
2324 if (ContainerNode* parent = this->parentNode()) {
2325 parent->insertBefore(newChild, this, exceptionState);
2326 if (!exceptionState.hadException())
2332 if (equalIgnoringCase(where, "afterBegin")) {
2333 insertBefore(newChild, firstChild(), exceptionState);
2334 return exceptionState.hadException() ? 0 : newChild;
2337 if (equalIgnoringCase(where, "beforeEnd")) {
2338 appendChild(newChild, exceptionState);
2339 return exceptionState.hadException() ? 0 : newChild;
2342 if (equalIgnoringCase(where, "afterEnd")) {
2343 if (ContainerNode* parent = this->parentNode()) {
2344 parent->insertBefore(newChild, nextSibling(), exceptionState);
2345 if (!exceptionState.hadException())
2351 exceptionState.throwDOMException(SyntaxError, "The value provided ('" + where + "') is not one of 'beforeBegin', 'afterBegin', 'beforeEnd', or 'afterEnd'.");
2355 // Step 1 of http://domparsing.spec.whatwg.org/#insertadjacenthtml()
2356 static Element* contextElementForInsertion(const String& where, Element* element, ExceptionState& exceptionState)
2358 if (equalIgnoringCase(where, "beforeBegin") || equalIgnoringCase(where, "afterEnd")) {
2359 ContainerNode* parent = element->parentNode();
2360 if (!parent || !parent->isElementNode()) {
2361 exceptionState.throwDOMException(NoModificationAllowedError, "The element has no parent.");
2364 return toElement(parent);
2366 if (equalIgnoringCase(where, "afterBegin") || equalIgnoringCase(where, "beforeEnd"))
2368 exceptionState.throwDOMException(SyntaxError, "The value provided ('" + where + "') is not one of 'beforeBegin', 'afterBegin', 'beforeEnd', or 'afterEnd'.");
2372 Element* Element::insertAdjacentElement(const String& where, Element* newChild, ExceptionState& exceptionState)
2375 // IE throws COM Exception E_INVALIDARG; this is the best DOM exception alternative.
2376 exceptionState.throwTypeError("The node provided is null.");
2380 Node* returnValue = insertAdjacent(where, newChild, exceptionState);
2381 return toElement(returnValue);
2384 void Element::insertAdjacentText(const String& where, const String& text, ExceptionState& exceptionState)
2386 RefPtr<Text> textNode = document().createTextNode(text);
2387 insertAdjacent(where, textNode.get(), exceptionState);
2390 void Element::insertAdjacentHTML(const String& where, const String& markup, ExceptionState& exceptionState)
2392 RefPtr<Element> contextElement = contextElementForInsertion(where, this, exceptionState);
2393 if (!contextElement)
2396 RefPtr<DocumentFragment> fragment = createFragmentForInnerOuterHTML(markup, contextElement.get(), AllowScriptingContent, "insertAdjacentHTML", exceptionState);
2399 insertAdjacent(where, fragment.get(), exceptionState);
2402 String Element::innerText()
2404 // We need to update layout, since plainText uses line boxes in the render tree.
2405 document().updateLayoutIgnorePendingStylesheets();
2408 return textContent(true);
2410 return plainText(rangeOfContents(const_cast<Element*>(this)).get());
2413 String Element::outerText()
2415 // Getting outerText is the same as getting innerText, only
2416 // setting is different. You would think this should get the plain
2417 // text for the outer range, but this is wrong, <br> for instance
2418 // would return different values for inner and outer text by such
2419 // a rule, but it doesn't in WinIE, and we want to match that.
2423 String Element::textFromChildren()
2425 Text* firstTextNode = 0;
2426 bool foundMultipleTextNodes = false;
2427 unsigned totalLength = 0;
2429 for (Node* child = firstChild(); child; child = child->nextSibling()) {
2430 if (!child->isTextNode())
2432 Text* text = toText(child);
2434 firstTextNode = text;
2436 foundMultipleTextNodes = true;
2437 unsigned length = text->data().length();
2438 if (length > std::numeric_limits<unsigned>::max() - totalLength)
2439 return emptyString();
2440 totalLength += length;
2444 return emptyString();
2446 if (firstTextNode && !foundMultipleTextNodes) {
2447 firstTextNode->atomize();
2448 return firstTextNode->data();
2451 StringBuilder content;
2452 content.reserveCapacity(totalLength);
2453 for (Node* child = firstTextNode; child; child = child->nextSibling()) {
2454 if (!child->isTextNode())
2456 content.append(toText(child)->data());
2459 ASSERT(content.length() == totalLength);
2460 return content.toString();
2463 const AtomicString& Element::shadowPseudoId() const
2465 if (ShadowRoot* root = containingShadowRoot()) {
2466 if (root->type() == ShadowRoot::UserAgentShadowRoot)
2467 return fastGetAttribute(pseudoAttr);
2472 void Element::setShadowPseudoId(const AtomicString& id)
2474 ASSERT(CSSSelector::parsePseudoType(id) == CSSSelector::PseudoWebKitCustomElement || CSSSelector::parsePseudoType(id) == CSSSelector::PseudoUserAgentCustomElement);
2475 setAttribute(pseudoAttr, id);
2478 bool Element::isInDescendantTreeOf(const Element* shadowHost) const
2481 ASSERT(isShadowHost(shadowHost));
2483 const ShadowRoot* shadowRoot = containingShadowRoot();
2484 while (shadowRoot) {
2485 const Element* ancestorShadowHost = shadowRoot->shadowHost();
2486 if (ancestorShadowHost == shadowHost)
2488 shadowRoot = ancestorShadowHost->containingShadowRoot();
2493 LayoutSize Element::minimumSizeForResizing() const
2495 return hasRareData() ? elementRareData()->minimumSizeForResizing() : defaultMinimumSizeForResizing();
2498 void Element::setMinimumSizeForResizing(const LayoutSize& size)
2500 if (!hasRareData() && size == defaultMinimumSizeForResizing())
2502 ensureElementRareData().setMinimumSizeForResizing(size);
2505 RenderStyle* Element::computedStyle(PseudoId pseudoElementSpecifier)
2507 if (PseudoElement* element = pseudoElement(pseudoElementSpecifier))
2508 return element->computedStyle();
2510 // FIXME: Find and use the renderer from the pseudo element instead of the actual element so that the 'length'
2511 // properties, which are only known by the renderer because it did the layout, will be correct and so that the
2512 // values returned for the ":selection" pseudo-element will be correct.
2513 if (RenderStyle* usedStyle = renderStyle()) {
2514 if (pseudoElementSpecifier) {
2515 RenderStyle* cachedPseudoStyle = usedStyle->getCachedPseudoStyle(pseudoElementSpecifier);
2516 return cachedPseudoStyle ? cachedPseudoStyle : usedStyle;
2521 if (!inActiveDocument())
2522 // FIXME: Try to do better than this. Ensure that styleForElement() works for elements that are not in the
2523 // document tree and figure out when to destroy the computed style for such elements.
2526 ElementRareData& rareData = ensureElementRareData();
2527 if (!rareData.computedStyle())
2528 rareData.setComputedStyle(document().styleForElementIgnoringPendingStylesheets(this));
2529 return pseudoElementSpecifier ? rareData.computedStyle()->getCachedPseudoStyle(pseudoElementSpecifier) : rareData.computedStyle();
2532 void Element::setStyleAffectedByEmpty()
2534 ensureElementRareData().setStyleAffectedByEmpty(true);
2537 void Element::setChildrenAffectedByFocus()
2539 ensureElementRareData().setChildrenAffectedByFocus(true);
2542 void Element::setChildrenAffectedByHover()
2544 ensureElementRareData().setChildrenAffectedByHover(true);
2547 void Element::setChildrenAffectedByActive()
2549 ensureElementRareData().setChildrenAffectedByActive(true);
2552 void Element::setChildrenAffectedByDrag()
2554 ensureElementRareData().setChildrenAffectedByDrag(true);
2557 void Element::setChildrenAffectedByFirstChildRules()
2559 ensureElementRareData().setChildrenAffectedByFirstChildRules(true);
2562 void Element::setChildrenAffectedByLastChildRules()
2564 ensureElementRareData().setChildrenAffectedByLastChildRules(true);
2567 void Element::setChildrenAffectedByDirectAdjacentRules()
2569 ensureElementRareData().setChildrenAffectedByDirectAdjacentRules(true);
2572 void Element::setChildrenAffectedByForwardPositionalRules()
2574 ensureElementRareData().setChildrenAffectedByForwardPositionalRules(true);
2577 void Element::setChildrenAffectedByBackwardPositionalRules()
2579 ensureElementRareData().setChildrenAffectedByBackwardPositionalRules(true);
2582 void Element::setChildIndex(unsigned index)
2584 ElementRareData& rareData = ensureElementRareData();
2585 if (RenderStyle* style = renderStyle())
2587 rareData.setChildIndex(index);
2590 bool Element::childrenSupportStyleSharing() const
2594 return !rareDataChildrenAffectedByFocus()
2595 && !rareDataChildrenAffectedByHover()
2596 && !rareDataChildrenAffectedByActive()
2597 && !rareDataChildrenAffectedByDrag()
2598 && !rareDataChildrenAffectedByFirstChildRules()
2599 && !rareDataChildrenAffectedByLastChildRules()
2600 && !rareDataChildrenAffectedByDirectAdjacentRules()
2601 && !rareDataChildrenAffectedByForwardPositionalRules()
2602 && !rareDataChildrenAffectedByBackwardPositionalRules();
2605 bool Element::rareDataStyleAffectedByEmpty() const
2607 ASSERT(hasRareData());
2608 return elementRareData()->styleAffectedByEmpty();
2611 bool Element::rareDataChildrenAffectedByFocus() const
2613 ASSERT(hasRareData());
2614 return elementRareData()->childrenAffectedByFocus();
2617 bool Element::rareDataChildrenAffectedByHover() const
2619 ASSERT(hasRareData());
2620 return elementRareData()->childrenAffectedByHover();
2623 bool Element::rareDataChildrenAffectedByActive() const
2625 ASSERT(hasRareData());
2626 return elementRareData()->childrenAffectedByActive();
2629 bool Element::rareDataChildrenAffectedByDrag() const
2631 ASSERT(hasRareData());
2632 return elementRareData()->childrenAffectedByDrag();
2635 bool Element::rareDataChildrenAffectedByFirstChildRules() const
2637 ASSERT(hasRareData());
2638 return elementRareData()->childrenAffectedByFirstChildRules();
2641 bool Element::rareDataChildrenAffectedByLastChildRules() const
2643 ASSERT(hasRareData());
2644 return elementRareData()->childrenAffectedByLastChildRules();
2647 bool Element::rareDataChildrenAffectedByDirectAdjacentRules() const
2649 ASSERT(hasRareData());
2650 return elementRareData()->childrenAffectedByDirectAdjacentRules();
2653 bool Element::rareDataChildrenAffectedByForwardPositionalRules() const
2655 ASSERT(hasRareData());
2656 return elementRareData()->childrenAffectedByForwardPositionalRules();
2659 bool Element::rareDataChildrenAffectedByBackwardPositionalRules() const
2661 ASSERT(hasRareData());
2662 return elementRareData()->childrenAffectedByBackwardPositionalRules();
2665 unsigned Element::rareDataChildIndex() const
2667 ASSERT(hasRareData());
2668 return elementRareData()->childIndex();
2671 void Element::setIsInCanvasSubtree(bool isInCanvasSubtree)
2673 ensureElementRareData().setIsInCanvasSubtree(isInCanvasSubtree);
2676 bool Element::isInCanvasSubtree() const
2678 return hasRareData() && elementRareData()->isInCanvasSubtree();
2681 AtomicString Element::computeInheritedLanguage() const
2683 const Node* n = this;
2685 // The language property is inherited, so we iterate over the parents to find the first language.
2687 if (n->isElementNode()) {
2688 if (const ElementData* elementData = toElement(n)->elementData()) {
2689 // Spec: xml:lang takes precedence -- http://www.w3.org/TR/xhtml1/#C_7
2690 if (const Attribute* attribute = elementData->getAttributeItem(XMLNames::langAttr))
2691 value = attribute->value();
2692 else if (const Attribute* attribute = elementData->getAttributeItem(HTMLNames::langAttr))
2693 value = attribute->value();
2695 } else if (n->isDocumentNode()) {
2696 // checking the MIME content-language
2697 value = toDocument(n)->contentLanguage();
2700 n = n->parentNode();
2701 } while (n && value.isNull());
2706 Locale& Element::locale() const
2708 return document().getCachedLocale(computeInheritedLanguage());
2711 void Element::cancelFocusAppearanceUpdate()
2714 elementRareData()->setNeedsFocusAppearanceUpdateSoonAfterAttach(false);
2715 if (document().focusedElement() == this)
2716 document().cancelFocusAppearanceUpdate();
2719 void Element::normalizeAttributes()
2721 if (!hasAttributes())
2723 for (unsigned i = 0; i < attributeCount(); ++i) {
2724 if (RefPtr<Attr> attr = attrIfExists(attributeItem(i)->name()))
2729 void Element::updatePseudoElement(PseudoId pseudoId, StyleRecalcChange change)
2731 ASSERT(!needsStyleRecalc());
2732 PseudoElement* element = pseudoElement(pseudoId);
2733 if (element && (change == UpdatePseudoElements || element->shouldCallRecalcStyle(change))) {
2735 // Need to clear the cached style if the PseudoElement wants a recalc so it
2736 // computes a new style.
2737 if (element->needsStyleRecalc())
2738 renderer()->style()->removeCachedPseudoStyle(pseudoId);
2740 // PseudoElement styles hang off their parent element's style so if we needed
2741 // a style recalc we should Force one on the pseudo.
2742 // FIXME: We should figure out the right text sibling to pass.
2743 element->recalcStyle(change == UpdatePseudoElements ? Force : change);
2745 // Wait until our parent is not displayed or pseudoElementRendererIsNeeded
2746 // is false, otherwise we could continously create and destroy PseudoElements
2747 // when RenderObject::isChildAllowed on our parent returns false for the
2748 // PseudoElement's renderer for each style recalc.
2749 if (!renderer() || !pseudoElementRendererIsNeeded(renderer()->getCachedPseudoStyle(pseudoId)))
2750 elementRareData()->setPseudoElement(pseudoId, 0);
2751 } else if (change >= UpdatePseudoElements) {
2752 createPseudoElementIfNeeded(pseudoId);
2756 void Element::createPseudoElementIfNeeded(PseudoId pseudoId)
2758 if (isPseudoElement())
2761 RefPtr<PseudoElement> element = document().ensureStyleResolver().createPseudoElementIfNeeded(*this, pseudoId);
2765 if (pseudoId == BACKDROP)
2766 document().addToTopLayer(element.get(), this);
2767 element->insertedInto(this);
2770 InspectorInstrumentation::pseudoElementCreated(element.get());
2772 ensureElementRareData().setPseudoElement(pseudoId, element.release());
2775 PseudoElement* Element::pseudoElement(PseudoId pseudoId) const
2777 return hasRareData() ? elementRareData()->pseudoElement(pseudoId) : 0;
2780 RenderObject* Element::pseudoElementRenderer(PseudoId pseudoId) const
2782 if (PseudoElement* element = pseudoElement(pseudoId))
2783 return element->renderer();
2787 bool Element::matches(const String& selectors, ExceptionState& exceptionState)
2789 SelectorQuery* selectorQuery = document().selectorQueryCache().add(AtomicString(selectors), document(), exceptionState);
2792 return selectorQuery->matches(*this);
2795 DOMTokenList* Element::classList()
2797 ElementRareData& rareData = ensureElementRareData();
2798 if (!rareData.classList())
2799 rareData.setClassList(ClassList::create(this));
2800 return rareData.classList();
2803 DOMStringMap* Element::dataset()
2805 ElementRareData& rareData = ensureElementRareData();
2806 if (!rareData.dataset())
2807 rareData.setDataset(DatasetDOMStringMap::create(this));
2808 return rareData.dataset();
2811 KURL Element::getURLAttribute(const QualifiedName& name) const
2813 #if !ASSERT_DISABLED
2814 if (elementData()) {
2815 if (const Attribute* attribute = getAttributeItem(name))
2816 ASSERT(isURLAttribute(*attribute));
2819 return document().completeURL(stripLeadingAndTrailingHTMLSpaces(getAttribute(name)));
2822 KURL Element::getNonEmptyURLAttribute(const QualifiedName& name) const
2824 #if !ASSERT_DISABLED
2825 if (elementData()) {
2826 if (const Attribute* attribute = getAttributeItem(name))
2827 ASSERT(isURLAttribute(*attribute));
2830 String value = stripLeadingAndTrailingHTMLSpaces(getAttribute(name));
2831 if (value.isEmpty())
2833 return document().completeURL(value);
2836 int Element::getIntegralAttribute(const QualifiedName& attributeName) const
2838 return getAttribute(attributeName).string().toInt();
2841 void Element::setIntegralAttribute(const QualifiedName& attributeName, int value)
2843 setAttribute(attributeName, AtomicString::number(value));
2846 unsigned Element::getUnsignedIntegralAttribute(const QualifiedName& attributeName) const
2848 return getAttribute(attributeName).string().toUInt();
2851 void Element::setUnsignedIntegralAttribute(const QualifiedName& attributeName, unsigned value)
2853 // Range restrictions are enforced for unsigned IDL attributes that
2854 // reflect content attributes,
2855 // http://www.whatwg.org/specs/web-apps/current-work/multipage/common-dom-interfaces.html#reflecting-content-attributes-in-idl-attributes
2856 if (value > 0x7fffffffu)
2858 setAttribute(attributeName, AtomicString::number(value));
2861 double Element::getFloatingPointAttribute(const QualifiedName& attributeName, double fallbackValue) const
2863 return parseToDoubleForNumberType(getAttribute(attributeName), fallbackValue);
2866 void Element::setFloatingPointAttribute(const QualifiedName& attributeName, double value)
2868 setAttribute(attributeName, AtomicString::number(value));
2871 void Element::webkitRequestFullscreen()
2873 FullscreenElementStack::from(&document())->requestFullScreenForElement(this, ALLOW_KEYBOARD_INPUT, FullscreenElementStack::EnforceIFrameAllowFullScreenRequirement);
2876 void Element::webkitRequestFullScreen(unsigned short flags)
2878 FullscreenElementStack::from(&document())->requestFullScreenForElement(this, (flags | LEGACY_MOZILLA_REQUEST), FullscreenElementStack::EnforceIFrameAllowFullScreenRequirement);
2881 bool Element::containsFullScreenElement() const
2883 return hasRareData() && elementRareData()->containsFullScreenElement();
2886 void Element::setContainsFullScreenElement(bool flag)
2888 ensureElementRareData().setContainsFullScreenElement(flag);
2889 setNeedsStyleRecalc(SubtreeStyleChange);
2892 static Element* parentCrossingFrameBoundaries(Element* element)
2895 return element->parentElement() ? element->parentElement() : element->document().ownerElement();
2898 void Element::setContainsFullScreenElementOnAncestorsCrossingFrameBoundaries(bool flag)
2900 Element* element = this;
2901 while ((element = parentCrossingFrameBoundaries(element)))
2902 element->setContainsFullScreenElement(flag);
2905 bool Element::isInTopLayer() const
2907 return hasRareData() && elementRareData()->isInTopLayer();
2910 void Element::setIsInTopLayer(bool inTopLayer)
2912 if (isInTopLayer() == inTopLayer)
2914 ensureElementRareData().setIsInTopLayer(inTopLayer);
2916 // We must ensure a reattach occurs so the renderer is inserted in the correct sibling order under RenderView according to its
2917 // top layer position, or in its usual place if not in the top layer.
2918 lazyReattachIfAttached();
2921 void Element::webkitRequestPointerLock()
2923 if (document().page())
2924 document().page()->pointerLockController().requestPointerLock(this);
2927 SpellcheckAttributeState Element::spellcheckAttributeState() const
2929 const AtomicString& value = fastGetAttribute(spellcheckAttr);
2930 if (value == nullAtom)
2931 return SpellcheckAttributeDefault;
2932 if (equalIgnoringCase(value, "true") || equalIgnoringCase(value, ""))
2933 return SpellcheckAttributeTrue;
2934 if (equalIgnoringCase(value, "false"))
2935 return SpellcheckAttributeFalse;
2937 return SpellcheckAttributeDefault;
2940 bool Element::isSpellCheckingEnabled() const
2942 for (const Element* element = this; element; element = element->parentOrShadowHostElement()) {
2943 switch (element->spellcheckAttributeState()) {
2944 case SpellcheckAttributeTrue:
2946 case SpellcheckAttributeFalse:
2948 case SpellcheckAttributeDefault:
2957 bool Element::fastAttributeLookupAllowed(const QualifiedName& name) const
2959 if (name == HTMLNames::styleAttr)
2963 return !toSVGElement(this)->isAnimatableAttribute(name);
2969 #ifdef DUMP_NODE_STATISTICS
2970 bool Element::hasNamedNodeMap() const
2972 return hasRareData() && elementRareData()->attributeMap();
2976 inline void Element::updateName(const AtomicString& oldName, const AtomicString& newName)
2978 if (!inDocument() || isInShadowTree())
2981 if (oldName == newName)
2984 if (shouldRegisterAsNamedItem())
2985 updateNamedItemRegistration(oldName, newName);
2988 inline void Element::updateId(const AtomicString& oldId, const AtomicString& newId)
2990 if (!isInTreeScope())
2996 updateId(treeScope(), oldId, newId);
2999 inline void Element::updateId(TreeScope& scope, const AtomicString& oldId, const AtomicString& newId)
3001 ASSERT(isInTreeScope());
3002 ASSERT(oldId != newId);
3004 if (!oldId.isEmpty())
3005 scope.removeElementById(oldId, this);
3006 if (!newId.isEmpty())
3007 scope.addElementById(newId, this);
3009 if (shouldRegisterAsExtraNamedItem())
3010 updateExtraNamedItemRegistration(oldId, newId);
3013 void Element::updateLabel(TreeScope& scope, const AtomicString& oldForAttributeValue, const AtomicString& newForAttributeValue)
3015 ASSERT(hasTagName(labelTag));
3020 if (oldForAttributeValue == newForAttributeValue)
3023 if (!oldForAttributeValue.isEmpty())
3024 scope.removeLabel(oldForAttributeValue, toHTMLLabelElement(this));
3025 if (!newForAttributeValue.isEmpty())
3026 scope.addLabel(newForAttributeValue, toHTMLLabelElement(this));
3029 static bool hasSelectorForAttribute(Document* document, const AtomicString& localName)
3031 return document->ensureStyleResolver().ensureRuleFeatureSet().hasSelectorForAttribute(localName);
3034 void Element::willModifyAttribute(const QualifiedName& name, const AtomicString& oldValue, const AtomicString& newValue)
3036 if (isIdAttributeName(name))
3037 updateId(oldValue, newValue);
3038 else if (name == HTMLNames::nameAttr)
3039 updateName(oldValue, newValue);
3040 else if (name == HTMLNames::forAttr && hasTagName(labelTag)) {
3041 TreeScope& scope = treeScope();
3042 if (scope.shouldCacheLabelsByForAttribute())
3043 updateLabel(scope, oldValue, newValue);
3046 if (oldValue != newValue) {
3047 if (inActiveDocument() && hasSelectorForAttribute(&document(), name.localName()))
3048 setNeedsStyleRecalc(SubtreeStyleChange);
3050 if (isUpgradedCustomElement())
3051 CustomElement::attributeDidChange(this, name.localName(), oldValue, newValue);
3054 if (OwnPtr<MutationObserverInterestGroup> recipients = MutationObserverInterestGroup::createForAttributesMutation(*this, name))
3055 recipients->enqueueMutationRecord(MutationRecord::createAttributes(this, name, oldValue));
3057 InspectorInstrumentation::willModifyDOMAttr(this, oldValue, newValue);
3060 void Element::didAddAttribute(const QualifiedName& name, const AtomicString& value)
3062 attributeChanged(name, value);
3063 InspectorInstrumentation::didModifyDOMAttr(this, name.localName(), value);
3064 dispatchSubtreeModifiedEvent();
3067 void Element::didModifyAttribute(const QualifiedName& name, const AtomicString& value)
3069 attributeChanged(name, value);
3070 InspectorInstrumentation::didModifyDOMAttr(this, name.localName(), value);
3071 // Do not dispatch a DOMSubtreeModified event here; see bug 81141.
3074 void Element::didRemoveAttribute(const QualifiedName& name)
3076 attributeChanged(name, nullAtom);
3077 InspectorInstrumentation::didRemoveDOMAttr(this, name.localName());
3078 dispatchSubtreeModifiedEvent();
3081 void Element::didMoveToNewDocument(Document& oldDocument)
3083 Node::didMoveToNewDocument(oldDocument);
3085 // If the documents differ by quirks mode then they differ by case sensitivity
3086 // for class and id names so we need to go through the attribute change logic
3087 // to pick up the new casing in the ElementData.
3088 if (oldDocument.inQuirksMode() != document().inQuirksMode()) {
3090 setIdAttribute(getIdAttribute());
3092 setAttribute(HTMLNames::classAttr, getClassAttribute());
3096 void Element::updateNamedItemRegistration(const AtomicString& oldName, const AtomicString& newName)
3098 if (!document().isHTMLDocument())
3101 if (!oldName.isEmpty())
3102 toHTMLDocument(document()).removeNamedItem(oldName);
3104 if (!newName.isEmpty())
3105 toHTMLDocument(document()).addNamedItem(newName);
3108 void Element::updateExtraNamedItemRegistration(const AtomicString& oldId, const AtomicString& newId)
3110 if (!document().isHTMLDocument())
3113 if (!oldId.isEmpty())
3114 toHTMLDocument(document()).removeExtraNamedItem(oldId);
3116 if (!newId.isEmpty())
3117 toHTMLDocument(document()).addExtraNamedItem(newId);
3120 PassRefPtr<HTMLCollection> Element::ensureCachedHTMLCollection(CollectionType type)
3122 if (HTMLCollection* collection = cachedHTMLCollection(type))
3125 if (type == TableRows) {
3126 ASSERT(hasTagName(tableTag));
3127 return ensureRareData().ensureNodeLists().addCache<HTMLTableRowsCollection>(this, type);
3128 } else if (type == SelectOptions) {
3129 ASSERT(hasTagName(selectTag));
3130 return ensureRareData().ensureNodeLists().addCache<HTMLOptionsCollection>(this, type);
3131 } else if (type == FormControls) {
3132 ASSERT(hasTagName(formTag) || hasTagName(fieldsetTag));
3133 return ensureRareData().ensureNodeLists().addCache<HTMLFormControlsCollection>(this, type);
3135 return ensureRareData().ensureNodeLists().addCache<HTMLCollection>(this, type);
3138 static void scheduleLayerUpdateCallback(Node* node)
3140 // Notify the renderer even is the styles are identical since it may need to
3141 // create or destroy a RenderLayer.
3142 node->setNeedsStyleRecalc(LocalStyleChange, StyleChangeFromRenderer);
3145 void Element::scheduleLayerUpdate()
3147 if (document().inStyleRecalc())
3148 PostAttachCallbacks::queueCallback(scheduleLayerUpdateCallback, this);
3150 scheduleLayerUpdateCallback(this);
3153 HTMLCollection* Element::cachedHTMLCollection(CollectionType type)
3155 return hasRareData() && rareData()->nodeLists() ? rareData()->nodeLists()->cached<HTMLCollection>(type) : 0;
3158 IntSize Element::savedLayerScrollOffset() const
3160 return hasRareData() ? elementRareData()->savedLayerScrollOffset() : IntSize();
3163 void Element::setSavedLayerScrollOffset(const IntSize& size)
3165 if (size.isZero() && !hasRareData())
3167 ensureElementRareData().setSavedLayerScrollOffset(size);
3170 PassRefPtr<Attr> Element::attrIfExists(const QualifiedName& name)
3172 if (AttrNodeList* attrNodeList = attrNodeListForElement(this))
3173 return findAttrNodeInList(*attrNodeList, name);
3177 PassRefPtr<Attr> Element::ensureAttr(const QualifiedName& name)
3179 AttrNodeList& attrNodeList = ensureAttrNodeListForElement(this);
3180 RefPtr<Attr> attrNode = findAttrNodeInList(attrNodeList, name);
3182 attrNode = Attr::create(*this, name);
3183 treeScope().adoptIfNeeded(*attrNode);
3184 attrNodeList.append(attrNode);
3186 return attrNode.release();
3189 void Element::detachAttrNodeFromElementWithValue(Attr* attrNode, const AtomicString& value)
3191 ASSERT(hasSyntheticAttrChildNodes());
3192 attrNode->detachFromElementWithValue(value);
3194 AttrNodeList* attrNodeList = attrNodeListForElement(this);
3195 for (unsigned i = 0; i < attrNodeList->size(); ++i) {
3196 if (attrNodeList->at(i)->qualifiedName() == attrNode->qualifiedName()) {
3197 attrNodeList->remove(i);
3198 if (attrNodeList->isEmpty())
3199 removeAttrNodeListForElement(this);
3203 ASSERT_NOT_REACHED();
3206 void Element::detachAllAttrNodesFromElement()
3208 AttrNodeList* attrNodeList = attrNodeListForElement(this);
3209 ASSERT(attrNodeList);
3211 for (unsigned i = 0; i < attributeCount(); ++i) {
3212 const Attribute* attribute = attributeItem(i);
3213 if (RefPtr<Attr> attrNode = findAttrNodeInList(*attrNodeList, attribute->name()))
3214 attrNode->detachFromElementWithValue(attribute->value());
3217 removeAttrNodeListForElement(this);
3220 void Element::willRecalcStyle(StyleRecalcChange)
3222 ASSERT(hasCustomStyleCallbacks());
3225 void Element::didRecalcStyle(StyleRecalcChange)
3227 ASSERT(hasCustomStyleCallbacks());
3231 PassRefPtr<RenderStyle> Element::customStyleForRenderer()
3233 ASSERT(hasCustomStyleCallbacks());
3237 void Element::cloneAttributesFromElement(const Element& other)
3239 if (hasSyntheticAttrChildNodes())
3240 detachAllAttrNodesFromElement();
3242 other.synchronizeAllAttributes();
3243 if (!other.m_elementData) {
3244 m_elementData.clear();
3248 const AtomicString& oldID = getIdAttribute();
3249 const AtomicString& newID = other.getIdAttribute();
3251 if (!oldID.isNull() || !newID.isNull())
3252 updateId(oldID, newID);
3254 const AtomicString& oldName = getNameAttribute();
3255 const AtomicString& newName = other.getNameAttribute();
3257 if (!oldName.isNull() || !newName.isNull())
3258 updateName(oldName, newName);
3260 // Quirks mode makes class and id not case sensitive. We can't share the ElementData
3261 // if the idForStyleResolution and the className need different casing.
3262 bool ownerDocumentsHaveDifferentCaseSensitivity = false;
3263 if (other.hasClass() || other.hasID())
3264 ownerDocumentsHaveDifferentCaseSensitivity = other.document().inQuirksMode() != document().inQuirksMode();
3266 // If 'other' has a mutable ElementData, convert it to an immutable one so we can share it between both elements.
3267 // We can only do this if there are no presentation attributes and sharing the data won't result in different case sensitivity of class or id.
3268 if (other.m_elementData->isUnique()
3269 && !ownerDocumentsHaveDifferentCaseSensitivity
3270 && !other.m_elementData->presentationAttributeStyle())
3271 const_cast<Element&>(other).m_elementData = static_cast<const UniqueElementData*>(other.m_elementData.get())->makeShareableCopy();
3273 if (!other.m_elementData->isUnique() && !ownerDocumentsHaveDifferentCaseSensitivity)
3274 m_elementData = other.m_elementData;
3276 m_elementData = other.m_elementData->makeUniqueCopy();
3278 for (unsigned i = 0; i < m_elementData->length(); ++i) {
3279 const Attribute* attribute = const_cast<const ElementData*>(m_elementData.get())->attributeItem(i);
3280 attributeChangedFromParserOrByCloning(attribute->name(), attribute->value(), ModifiedByCloning);
3284 void Element::cloneDataFromElement(const Element& other)
3286 cloneAttributesFromElement(other);
3287 copyNonAttributePropertiesFromElement(other);
3290 void Element::createUniqueElementData()
3293 m_elementData = UniqueElementData::create();
3295 ASSERT(!m_elementData->isUnique());
3296 m_elementData = static_cast<ShareableElementData*>(m_elementData.get())->makeUniqueCopy();
3300 InputMethodContext* Element::inputMethodContext()
3302 return ensureElementRareData().ensureInputMethodContext(toHTMLElement(this));
3305 bool Element::hasInputMethodContext() const
3307 return hasRareData() && elementRareData()->hasInputMethodContext();
3310 bool Element::hasPendingResources() const
3312 return hasRareData() && elementRareData()->hasPendingResources();
3315 void Element::setHasPendingResources()
3317 ensureElementRareData().setHasPendingResources(true);
3320 void Element::clearHasPendingResources()
3322 ensureElementRareData().setHasPendingResources(false);
3325 void Element::synchronizeStyleAttributeInternal() const
3327 ASSERT(isStyledElement());
3328 ASSERT(elementData());
3329 ASSERT(elementData()->m_styleAttributeIsDirty);
3330 elementData()->m_styleAttributeIsDirty = false;
3331 const StylePropertySet* inlineStyle = this->inlineStyle();
3332 const_cast<Element*>(this)->setSynchronizedLazyAttribute(styleAttr,
3333 inlineStyle ? AtomicString(inlineStyle->asText()) : nullAtom);
3336 CSSStyleDeclaration* Element::style()
3338 if (!isStyledElement())
3340 return ensureElementRareData().ensureInlineCSSStyleDeclaration(this);
3343 MutableStylePropertySet* Element::ensureMutableInlineStyle()
3345 ASSERT(isStyledElement());
3346 RefPtr<StylePropertySet>& inlineStyle = ensureUniqueElementData()->m_inlineStyle;
3348 CSSParserMode mode = (!isHTMLElement() || document().inQuirksMode()) ? HTMLQuirksMode : HTMLStandardMode;
3349 inlineStyle = MutableStylePropertySet::create(mode);
3350 } else if (!inlineStyle->isMutable()) {
3351 inlineStyle = inlineStyle->mutableCopy();
3353 return toMutableStylePropertySet(inlineStyle);
3356 void Element::clearMutableInlineStyleIfEmpty()
3358 if (ensureMutableInlineStyle()->isEmpty()) {
3359 ensureUniqueElementData()->m_inlineStyle.clear();
3363 inline void Element::setInlineStyleFromString(const AtomicString& newStyleString)
3365 ASSERT(isStyledElement());
3366 RefPtr<StylePropertySet>& inlineStyle = elementData()->m_inlineStyle;
3368 // Avoid redundant work if we're using shared attribute data with already parsed inline style.
3369 if (inlineStyle && !elementData()->isUnique())
3372 // We reconstruct the property set instead of mutating if there is no CSSOM wrapper.
3373 // This makes wrapperless property sets immutable and so cacheable.
3374 if (inlineStyle && !inlineStyle->isMutable())
3375 inlineStyle.clear();
3378 inlineStyle = BisonCSSParser::parseInlineStyleDeclaration(newStyleString, this);
3380 ASSERT(inlineStyle->isMutable());
3381 static_pointer_cast<MutableStylePropertySet>(inlineStyle)->parseDeclaration(newStyleString, document().elementSheet()->contents());
3385 void Element::styleAttributeChanged(const AtomicString& newStyleString, AttributeModificationReason modificationReason)
3387 ASSERT(isStyledElement());
3388 WTF::OrdinalNumber startLineNumber = WTF::OrdinalNumber::beforeFirst();
3389 if (document().scriptableDocumentParser() && !document().isInDocumentWrite())
3390 startLineNumber = document().scriptableDocumentParser()->lineNumber();
3392 if (newStyleString.isNull()) {
3393 ensureUniqueElementData()->m_inlineStyle.clear();
3394 } else if (modificationReason == ModifiedByCloning || document().contentSecurityPolicy()->allowInlineStyle(document().url(), startLineNumber)) {
3395 setInlineStyleFromString(newStyleString);
3398 elementData()->m_styleAttributeIsDirty = false;
3400 setNeedsStyleRecalc(LocalStyleChange);
3401 InspectorInstrumentation::didInvalidateStyleAttr(this);
3404 void Element::inlineStyleChanged()
3406 ASSERT(isStyledElement());
3407 setNeedsStyleRecalc(LocalStyleChange);
3408 ASSERT(elementData());
3409 elementData()->m_styleAttributeIsDirty = true;
3410 InspectorInstrumentation::didInvalidateStyleAttr(this);
3413 bool Element::setInlineStyleProperty(CSSPropertyID propertyID, CSSValueID identifier, bool important)
3415 ASSERT(isStyledElement());
3416 ensureMutableInlineStyle()->setProperty(propertyID, cssValuePool().createIdentifierValue(identifier), important);
3417 inlineStyleChanged();
3421 bool Element::setInlineStyleProperty(CSSPropertyID propertyID, CSSPropertyID identifier, bool important)
3423 ASSERT(isStyledElement());
3424 ensureMutableInlineStyle()->setProperty(propertyID, cssValuePool().createIdentifierValue(identifier), important);
3425 inlineStyleChanged();
3429 bool Element::setInlineStyleProperty(CSSPropertyID propertyID, double value, CSSPrimitiveValue::UnitTypes unit, bool important)
3431 ASSERT(isStyledElement());
3432 ensureMutableInlineStyle()->setProperty(propertyID, cssValuePool().createValue(value, unit), important);
3433 inlineStyleChanged();
3437 bool Element::setInlineStyleProperty(CSSPropertyID propertyID, const String& value, bool important)
3439 ASSERT(isStyledElement());
3440 bool changes = ensureMutableInlineStyle()->setProperty(propertyID, value, important, document().elementSheet()->contents());
3442 inlineStyleChanged();
3446 bool Element::removeInlineStyleProperty(CSSPropertyID propertyID)
3448 ASSERT(isStyledElement());
3451 bool changes = ensureMutableInlineStyle()->removeProperty(propertyID);
3453 inlineStyleChanged();
3457 void Element::removeAllInlineStyleProperties()
3459 ASSERT(isStyledElement());
3462 ensureMutableInlineStyle()->clear();
3463 inlineStyleChanged();
3466 void Element::updatePresentationAttributeStyle()
3468 // ShareableElementData doesn't store presentation attribute style, so make sure we have a UniqueElementData.
3469 UniqueElementData* elementData = ensureUniqueElementData();
3470 elementData->m_presentationAttributeStyleIsDirty = false;
3471 elementData->m_presentationAttributeStyle = computePresentationAttributeStyle(*this);
3474 void Element::addPropertyToPresentationAttributeStyle(MutableStylePropertySet* style, CSSPropertyID propertyID, CSSValueID identifier)
3476 ASSERT(isStyledElement());
3477 style->setProperty(propertyID, cssValuePool().createIdentifierValue(identifier));
3480 void Element::addPropertyToPresentationAttributeStyle(MutableStylePropertySet* style, CSSPropertyID propertyID, double value, CSSPrimitiveValue::UnitTypes unit)
3482 ASSERT(isStyledElement());
3483 style->setProperty(propertyID, cssValuePool().createValue(value, unit));
3486 void Element::addPropertyToPresentationAttributeStyle(MutableStylePropertySet* style, CSSPropertyID propertyID, const String& value)
3488 ASSERT(isStyledElement());
3489 style->setProperty(propertyID, value, false);
3492 bool Element::supportsStyleSharing() const
3494 if (!isStyledElement() || !parentOrShadowHostElement())
3496 // If the element has inline style it is probably unique.
3499 if (isSVGElement() && toSVGElement(this)->animatedSMILStyleProperties())
3501 // Ids stop style sharing if they show up in the stylesheets.
3502 if (hasID() && document().ensureStyleResolver().hasRulesForId(idForStyleResolution()))
3504 // Active and hovered elements always make a chain towards the document node
3505 // and no siblings or cousins will have the same state.
3512 if (!parentOrShadowHostElement()->childrenSupportStyleSharing())
3514 if (hasScopedHTMLStyleChild())
3516 if (this == document().cssTarget())
3518 if (isHTMLElement() && toHTMLElement(this)->hasDirectionAuto())
3520 if (hasActiveAnimations())
3522 // Turn off style sharing for elements that can gain layers for reasons outside of the style system.
3523 // See comments in RenderObject::setStyle().
3524 // FIXME: Why does gaining a layer from outside the style system require disabling sharing?
3525 if (hasTagName(iframeTag)
3526 || hasTagName(frameTag)
3527 || hasTagName(embedTag)
3528 || hasTagName(objectTag)
3529 || hasTagName(appletTag)
3530 || hasTagName(canvasTag))
3532 // FIXME: We should share style for option and optgroup whenever possible.
3533 // Before doing so, we need to resolve issues in HTMLSelectElement::recalcListItems
3534 // and RenderMenuList::setText. See also https://bugs.webkit.org/show_bug.cgi?id=88405
3535 if (hasTagName(optionTag) || hasTagName(optgroupTag))
3537 if (FullscreenElementStack::isActiveFullScreenElement(this))
3542 } // namespace WebCore