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.
29 #include "AXObjectCache.h"
31 #include "CSSParser.h"
32 #include "CSSSelectorList.h"
33 #include "ClassList.h"
34 #include "ClientRect.h"
35 #include "ClientRectList.h"
36 #include "DOMTokenList.h"
37 #include "DatasetDOMStringMap.h"
39 #include "DocumentFragment.h"
40 #include "DocumentSharedObjectPool.h"
41 #include "ElementRareData.h"
42 #include "ExceptionCode.h"
43 #include "FlowThreadController.h"
44 #include "FocusController.h"
46 #include "FrameView.h"
47 #include "HTMLCollection.h"
48 #include "HTMLDocument.h"
49 #include "HTMLElement.h"
50 #include "HTMLFormControlsCollection.h"
51 #include "HTMLFrameOwnerElement.h"
52 #include "HTMLLabelElement.h"
53 #include "HTMLNames.h"
54 #include "HTMLOptionsCollection.h"
55 #include "HTMLParserIdioms.h"
56 #include "HTMLTableRowsCollection.h"
57 #include "InsertionPoint.h"
58 #include "InspectorInstrumentation.h"
59 #include "MutationObserverInterestGroup.h"
60 #include "MutationRecord.h"
61 #include "NamedNodeMap.h"
63 #include "NodeRenderStyle.h"
64 #include "NodeRenderingContext.h"
65 #include "NodeTraversal.h"
67 #include "PointerLockController.h"
68 #include "PseudoElement.h"
69 #include "RenderRegion.h"
70 #include "RenderView.h"
71 #include "RenderWidget.h"
72 #include "SelectorQuery.h"
74 #include "ShadowRoot.h"
75 #include "StylePropertySet.h"
76 #include "StyleResolver.h"
78 #include "TextIterator.h"
79 #include "VoidCallback.h"
80 #include "WebCoreMemoryInstrumentation.h"
81 #include "XMLNSNames.h"
83 #include "htmlediting.h"
84 #include <wtf/BitVector.h>
85 #include <wtf/MemoryInstrumentationVector.h>
86 #include <wtf/text/CString.h>
89 #include "SVGDocumentExtensions.h"
90 #include "SVGElement.h"
96 using namespace HTMLNames;
97 using namespace XMLNames;
99 static inline bool shouldIgnoreAttributeCase(const Element* e)
101 return e && e->document()->isHTMLDocument() && e->isHTMLElement();
104 class StyleResolverParentPusher {
106 StyleResolverParentPusher(Element* parent)
108 , m_pushedStyleResolver(0)
113 if (m_pushedStyleResolver)
115 m_pushedStyleResolver = m_parent->document()->styleResolver();
116 m_pushedStyleResolver->pushParentElement(m_parent);
118 ~StyleResolverParentPusher()
121 if (!m_pushedStyleResolver)
124 // This tells us that our pushed style selector is in a bad state,
125 // so we should just bail out in that scenario.
126 ASSERT(m_pushedStyleResolver == m_parent->document()->styleResolver());
127 if (m_pushedStyleResolver != m_parent->document()->styleResolver())
130 m_pushedStyleResolver->popParentElement(m_parent);
135 StyleResolver* m_pushedStyleResolver;
138 typedef Vector<RefPtr<Attr> > AttrNodeList;
139 typedef HashMap<Element*, OwnPtr<AttrNodeList> > AttrNodeListMap;
141 static AttrNodeListMap& attrNodeListMap()
143 DEFINE_STATIC_LOCAL(AttrNodeListMap, map, ());
147 static AttrNodeList* attrNodeListForElement(Element* element)
149 if (!element->hasSyntheticAttrChildNodes())
151 ASSERT(attrNodeListMap().contains(element));
152 return attrNodeListMap().get(element);
155 static AttrNodeList* ensureAttrNodeListForElement(Element* element)
157 if (element->hasSyntheticAttrChildNodes()) {
158 ASSERT(attrNodeListMap().contains(element));
159 return attrNodeListMap().get(element);
161 ASSERT(!attrNodeListMap().contains(element));
162 element->setHasSyntheticAttrChildNodes(true);
163 AttrNodeListMap::AddResult result = attrNodeListMap().add(element, adoptPtr(new AttrNodeList));
164 return result.iterator->value.get();
167 static void removeAttrNodeListForElement(Element* element)
169 ASSERT(element->hasSyntheticAttrChildNodes());
170 ASSERT(attrNodeListMap().contains(element));
171 attrNodeListMap().remove(element);
172 element->setHasSyntheticAttrChildNodes(false);
175 static Attr* findAttrNodeInList(AttrNodeList* attrNodeList, const QualifiedName& name)
177 for (unsigned i = 0; i < attrNodeList->size(); ++i) {
178 if (attrNodeList->at(i)->qualifiedName() == name)
179 return attrNodeList->at(i).get();
184 PassRefPtr<Element> Element::create(const QualifiedName& tagName, Document* document)
186 return adoptRef(new Element(tagName, document, CreateElement));
192 if (document() && document()->renderer()) {
193 // When the document is not destroyed, an element that was part of a named flow
194 // content nodes should have been removed from the content nodes collection
195 // and the inNamedFlow flag reset.
196 ASSERT(!inNamedFlow());
201 ElementRareData* data = elementRareData();
202 data->setPseudoElement(BEFORE, 0);
203 data->setPseudoElement(AFTER, 0);
207 if (hasSyntheticAttrChildNodes())
208 detachAllAttrNodesFromElement();
211 if (hasPendingResources()) {
212 document()->accessSVGExtensions()->removeElementFromPendingResources(this);
213 ASSERT(!hasPendingResources());
218 inline ElementRareData* Element::elementRareData() const
220 ASSERT(hasRareData());
221 return static_cast<ElementRareData*>(rareData());
224 inline ElementRareData* Element::ensureElementRareData()
226 return static_cast<ElementRareData*>(ensureRareData());
229 void Element::clearTabIndexExplicitlyIfNeeded()
232 elementRareData()->clearTabIndexExplicitly();
235 void Element::setTabIndexExplicitly(short tabIndex)
237 ensureElementRareData()->setTabIndexExplicitly(tabIndex);
240 bool Element::supportsFocus() const
242 return hasRareData() && elementRareData()->tabIndexSetExplicitly();
245 short Element::tabIndex() const
247 return hasRareData() ? elementRareData()->tabIndex() : 0;
250 DEFINE_VIRTUAL_ATTRIBUTE_EVENT_LISTENER(Element, blur);
251 DEFINE_VIRTUAL_ATTRIBUTE_EVENT_LISTENER(Element, error);
252 DEFINE_VIRTUAL_ATTRIBUTE_EVENT_LISTENER(Element, focus);
253 DEFINE_VIRTUAL_ATTRIBUTE_EVENT_LISTENER(Element, load);
255 PassRefPtr<Node> Element::cloneNode(bool deep)
257 return deep ? cloneElementWithChildren() : cloneElementWithoutChildren();
260 PassRefPtr<Element> Element::cloneElementWithChildren()
262 RefPtr<Element> clone = cloneElementWithoutChildren();
263 cloneChildNodes(clone.get());
264 return clone.release();
267 PassRefPtr<Element> Element::cloneElementWithoutChildren()
269 RefPtr<Element> clone = cloneElementWithoutAttributesAndChildren();
270 // This will catch HTML elements in the wrong namespace that are not correctly copied.
271 // This is a sanity check as HTML overloads some of the DOM methods.
272 ASSERT(isHTMLElement() == clone->isHTMLElement());
274 clone->cloneDataFromElement(*this);
275 return clone.release();
278 PassRefPtr<Element> Element::cloneElementWithoutAttributesAndChildren()
280 return document()->createElement(tagQName(), false);
283 PassRefPtr<Attr> Element::detachAttribute(size_t index)
285 ASSERT(elementData());
287 const Attribute* attribute = elementData()->attributeItem(index);
290 RefPtr<Attr> attrNode = attrIfExists(attribute->name());
292 detachAttrNodeFromElementWithValue(attrNode.get(), attribute->value());
294 attrNode = Attr::create(document(), attribute->name(), attribute->value());
296 removeAttributeInternal(index, NotInSynchronizationOfLazyAttribute);
297 return attrNode.release();
300 void Element::removeAttribute(const QualifiedName& name)
305 size_t index = elementData()->getAttributeItemIndex(name);
306 if (index == notFound)
309 removeAttributeInternal(index, NotInSynchronizationOfLazyAttribute);
312 void Element::setBooleanAttribute(const QualifiedName& name, bool value)
315 setAttribute(name, emptyAtom);
317 removeAttribute(name);
320 NamedNodeMap* Element::attributes() const
322 ElementRareData* rareData = const_cast<Element*>(this)->ensureElementRareData();
323 if (NamedNodeMap* attributeMap = rareData->attributeMap())
326 rareData->setAttributeMap(NamedNodeMap::create(const_cast<Element*>(this)));
327 return rareData->attributeMap();
330 Node::NodeType Element::nodeType() const
335 bool Element::hasAttribute(const QualifiedName& name) const
337 return hasAttributeNS(name.namespaceURI(), name.localName());
340 void Element::synchronizeAllAttributes() const
344 if (elementData()->m_styleAttributeIsDirty) {
345 ASSERT(isStyledElement());
346 static_cast<const StyledElement*>(this)->synchronizeStyleAttributeInternal();
349 if (elementData()->m_animatedSVGAttributesAreDirty) {
350 ASSERT(isSVGElement());
351 toSVGElement(this)->synchronizeAnimatedSVGAttribute(anyQName());
356 inline void Element::synchronizeAttribute(const QualifiedName& name) const
360 if (UNLIKELY(name == styleAttr && elementData()->m_styleAttributeIsDirty)) {
361 ASSERT(isStyledElement());
362 static_cast<const StyledElement*>(this)->synchronizeStyleAttributeInternal();
366 if (UNLIKELY(elementData()->m_animatedSVGAttributesAreDirty)) {
367 ASSERT(isSVGElement());
368 toSVGElement(this)->synchronizeAnimatedSVGAttribute(name);
373 inline void Element::synchronizeAttribute(const AtomicString& localName) const
375 // This version of synchronizeAttribute() is streamlined for the case where you don't have a full QualifiedName,
376 // e.g when called from DOM API.
379 if (elementData()->m_styleAttributeIsDirty && equalPossiblyIgnoringCase(localName, styleAttr.localName(), shouldIgnoreAttributeCase(this))) {
380 ASSERT(isStyledElement());
381 static_cast<const StyledElement*>(this)->synchronizeStyleAttributeInternal();
385 if (elementData()->m_animatedSVGAttributesAreDirty) {
386 // We're not passing a namespace argument on purpose. SVGNames::*Attr are defined w/o namespaces as well.
387 ASSERT(isSVGElement());
388 static_cast<const SVGElement*>(this)->synchronizeAnimatedSVGAttribute(QualifiedName(nullAtom, localName, nullAtom));
393 const AtomicString& Element::getAttribute(const QualifiedName& name) const
397 synchronizeAttribute(name);
398 if (const Attribute* attribute = getAttributeItem(name))
399 return attribute->value();
403 void Element::scrollIntoView(bool alignToTop)
405 document()->updateLayoutIgnorePendingStylesheets();
410 LayoutRect bounds = boundingBox();
411 // Align to the top / bottom and to the closest edge.
413 renderer()->scrollRectToVisible(bounds, ScrollAlignment::alignToEdgeIfNeeded, ScrollAlignment::alignTopAlways);
415 renderer()->scrollRectToVisible(bounds, ScrollAlignment::alignToEdgeIfNeeded, ScrollAlignment::alignBottomAlways);
418 void Element::scrollIntoViewIfNeeded(bool centerIfNeeded)
420 document()->updateLayoutIgnorePendingStylesheets();
425 LayoutRect bounds = boundingBox();
427 renderer()->scrollRectToVisible(bounds, ScrollAlignment::alignCenterIfNeeded, ScrollAlignment::alignCenterIfNeeded);
429 renderer()->scrollRectToVisible(bounds, ScrollAlignment::alignToEdgeIfNeeded, ScrollAlignment::alignToEdgeIfNeeded);
432 void Element::scrollByUnits(int units, ScrollGranularity granularity)
434 document()->updateLayoutIgnorePendingStylesheets();
439 if (!renderer()->hasOverflowClip())
442 ScrollDirection direction = ScrollDown;
444 direction = ScrollUp;
447 Node* stopNode = this;
448 toRenderBox(renderer())->scroll(direction, granularity, units, &stopNode);
451 void Element::scrollByLines(int lines)
453 scrollByUnits(lines, ScrollByLine);
456 void Element::scrollByPages(int pages)
458 scrollByUnits(pages, ScrollByPage);
461 static float localZoomForRenderer(RenderObject* renderer)
463 // FIXME: This does the wrong thing if two opposing zooms are in effect and canceled each
464 // other out, but the alternative is that we'd have to crawl up the whole render tree every
465 // time (or store an additional bit in the RenderStyle to indicate that a zoom was specified).
466 float zoomFactor = 1;
467 if (renderer->style()->effectiveZoom() != 1) {
468 // Need to find the nearest enclosing RenderObject that set up
469 // a differing zoom, and then we divide our result by it to eliminate the zoom.
470 RenderObject* prev = renderer;
471 for (RenderObject* curr = prev->parent(); curr; curr = curr->parent()) {
472 if (curr->style()->effectiveZoom() != prev->style()->effectiveZoom()) {
473 zoomFactor = prev->style()->zoom();
478 if (prev->isRenderView())
479 zoomFactor = prev->style()->zoom();
484 static int adjustForLocalZoom(LayoutUnit value, RenderObject* renderer)
486 float zoomFactor = localZoomForRenderer(renderer);
489 #if ENABLE(SUBPIXEL_LAYOUT)
490 return lroundf(value / zoomFactor);
492 // Needed because computeLengthInt truncates (rather than rounds) when scaling up.
495 return static_cast<int>(value / zoomFactor);
499 int Element::offsetLeft()
501 document()->updateLayoutIgnorePendingStylesheets();
502 if (RenderBoxModelObject* renderer = renderBoxModelObject())
503 return adjustForLocalZoom(renderer->pixelSnappedOffsetLeft(), renderer);
507 int Element::offsetTop()
509 document()->updateLayoutIgnorePendingStylesheets();
510 if (RenderBoxModelObject* renderer = renderBoxModelObject())
511 return adjustForLocalZoom(renderer->pixelSnappedOffsetTop(), renderer);
515 int Element::offsetWidth()
517 document()->updateLayoutIgnorePendingStylesheets();
518 if (RenderBoxModelObject* renderer = renderBoxModelObject())
519 #if ENABLE(SUBPIXEL_LAYOUT)
520 return adjustLayoutUnitForAbsoluteZoom(renderer->pixelSnappedOffsetWidth(), renderer).round();
522 return adjustForAbsoluteZoom(renderer->pixelSnappedOffsetWidth(), renderer);
527 int Element::offsetHeight()
529 document()->updateLayoutIgnorePendingStylesheets();
530 if (RenderBoxModelObject* renderer = renderBoxModelObject())
531 #if ENABLE(SUBPIXEL_LAYOUT)
532 return adjustLayoutUnitForAbsoluteZoom(renderer->pixelSnappedOffsetHeight(), renderer).round();
534 return adjustForAbsoluteZoom(renderer->pixelSnappedOffsetHeight(), renderer);
539 Element* Element::offsetParent()
541 document()->updateLayoutIgnorePendingStylesheets();
542 if (RenderObject* rend = renderer())
543 if (RenderObject* offsetParent = rend->offsetParent())
544 return static_cast<Element*>(offsetParent->node());
548 int Element::clientLeft()
550 document()->updateLayoutIgnorePendingStylesheets();
552 if (RenderBox* renderer = renderBox())
553 return adjustForAbsoluteZoom(roundToInt(renderer->clientLeft()), renderer);
557 int Element::clientTop()
559 document()->updateLayoutIgnorePendingStylesheets();
561 if (RenderBox* renderer = renderBox())
562 return adjustForAbsoluteZoom(roundToInt(renderer->clientTop()), renderer);
566 int Element::clientWidth()
568 document()->updateLayoutIgnorePendingStylesheets();
570 // When in strict mode, clientWidth for the document element should return the width of the containing frame.
571 // When in quirks mode, clientWidth for the body element should return the width of the containing frame.
572 bool inQuirksMode = document()->inQuirksMode();
573 if ((!inQuirksMode && document()->documentElement() == this) ||
574 (inQuirksMode && isHTMLElement() && document()->body() == this)) {
575 if (FrameView* view = document()->view()) {
576 if (RenderView* renderView = document()->renderView())
577 return adjustForAbsoluteZoom(view->layoutWidth(), renderView);
581 if (RenderBox* renderer = renderBox())
582 #if ENABLE(SUBPIXEL_LAYOUT)
583 return adjustLayoutUnitForAbsoluteZoom(renderer->pixelSnappedClientWidth(), renderer).round();
585 return adjustForAbsoluteZoom(renderer->pixelSnappedClientWidth(), renderer);
590 int Element::clientHeight()
592 document()->updateLayoutIgnorePendingStylesheets();
594 // When in strict mode, clientHeight for the document element should return the height of the containing frame.
595 // When in quirks mode, clientHeight for the body element should return the height of the containing frame.
596 bool inQuirksMode = document()->inQuirksMode();
598 if ((!inQuirksMode && document()->documentElement() == this) ||
599 (inQuirksMode && isHTMLElement() && document()->body() == this)) {
600 if (FrameView* view = document()->view()) {
601 if (RenderView* renderView = document()->renderView())
602 return adjustForAbsoluteZoom(view->layoutHeight(), renderView);
606 if (RenderBox* renderer = renderBox())
607 #if ENABLE(SUBPIXEL_LAYOUT)
608 return adjustLayoutUnitForAbsoluteZoom(renderer->pixelSnappedClientHeight(), renderer).round();
610 return adjustForAbsoluteZoom(renderer->pixelSnappedClientHeight(), renderer);
615 int Element::scrollLeft()
617 document()->updateLayoutIgnorePendingStylesheets();
618 if (RenderBox* rend = renderBox())
619 return adjustForAbsoluteZoom(rend->scrollLeft(), rend);
623 int Element::scrollTop()
625 document()->updateLayoutIgnorePendingStylesheets();
626 if (RenderBox* rend = renderBox())
627 return adjustForAbsoluteZoom(rend->scrollTop(), rend);
631 void Element::setScrollLeft(int newLeft)
633 document()->updateLayoutIgnorePendingStylesheets();
634 if (RenderBox* rend = renderBox())
635 rend->setScrollLeft(static_cast<int>(newLeft * rend->style()->effectiveZoom()));
638 void Element::setScrollTop(int newTop)
640 document()->updateLayoutIgnorePendingStylesheets();
641 if (RenderBox* rend = renderBox())
642 rend->setScrollTop(static_cast<int>(newTop * rend->style()->effectiveZoom()));
645 int Element::scrollWidth()
647 document()->updateLayoutIgnorePendingStylesheets();
648 if (RenderBox* rend = renderBox())
649 return adjustForAbsoluteZoom(rend->scrollWidth(), rend);
653 int Element::scrollHeight()
655 document()->updateLayoutIgnorePendingStylesheets();
656 if (RenderBox* rend = renderBox())
657 return adjustForAbsoluteZoom(rend->scrollHeight(), rend);
661 IntRect Element::boundsInRootViewSpace()
663 document()->updateLayoutIgnorePendingStylesheets();
665 FrameView* view = document()->view();
669 Vector<FloatQuad> quads;
671 if (isSVGElement() && renderer()) {
672 // Get the bounding rectangle from the SVG model.
673 SVGElement* svgElement = static_cast<SVGElement*>(this);
675 if (svgElement->getBoundingBox(localRect))
676 quads.append(renderer()->localToAbsoluteQuad(localRect));
680 // Get the bounding rectangle from the box model.
681 if (renderBoxModelObject())
682 renderBoxModelObject()->absoluteQuads(quads);
688 IntRect result = quads[0].enclosingBoundingBox();
689 for (size_t i = 1; i < quads.size(); ++i)
690 result.unite(quads[i].enclosingBoundingBox());
692 result = view->contentsToRootView(result);
696 PassRefPtr<ClientRectList> Element::getClientRects()
698 document()->updateLayoutIgnorePendingStylesheets();
700 RenderBoxModelObject* renderBoxModelObject = this->renderBoxModelObject();
701 if (!renderBoxModelObject)
702 return ClientRectList::create();
704 // FIXME: Handle SVG elements.
705 // FIXME: Handle table/inline-table with a caption.
707 Vector<FloatQuad> quads;
708 renderBoxModelObject->absoluteQuads(quads);
709 document()->adjustFloatQuadsForScrollAndAbsoluteZoomAndFrameScale(quads, renderBoxModelObject);
710 return ClientRectList::create(quads);
713 PassRefPtr<ClientRect> Element::getBoundingClientRect()
715 document()->updateLayoutIgnorePendingStylesheets();
717 Vector<FloatQuad> quads;
719 if (isSVGElement() && renderer() && !renderer()->isSVGRoot()) {
720 // Get the bounding rectangle from the SVG model.
721 SVGElement* svgElement = static_cast<SVGElement*>(this);
723 if (svgElement->getBoundingBox(localRect))
724 quads.append(renderer()->localToAbsoluteQuad(localRect));
728 // Get the bounding rectangle from the box model.
729 if (renderBoxModelObject())
730 renderBoxModelObject()->absoluteQuads(quads);
734 return ClientRect::create();
736 FloatRect result = quads[0].boundingBox();
737 for (size_t i = 1; i < quads.size(); ++i)
738 result.unite(quads[i].boundingBox());
740 document()->adjustFloatRectForScrollAndAbsoluteZoomAndFrameScale(result, renderer());
741 return ClientRect::create(result);
744 IntRect Element::screenRect() const
748 // FIXME: this should probably respect transforms
749 return document()->view()->contentsToScreen(renderer()->absoluteBoundingBoxRectIgnoringTransforms());
752 const AtomicString& Element::getAttribute(const AtomicString& localName) const
756 synchronizeAttribute(localName);
757 if (const Attribute* attribute = elementData()->getAttributeItem(localName, shouldIgnoreAttributeCase(this)))
758 return attribute->value();
762 const AtomicString& Element::getAttributeNS(const AtomicString& namespaceURI, const AtomicString& localName) const
764 return getAttribute(QualifiedName(nullAtom, localName, namespaceURI));
767 void Element::setAttribute(const AtomicString& localName, const AtomicString& value, ExceptionCode& ec)
769 if (!Document::isValidName(localName)) {
770 ec = INVALID_CHARACTER_ERR;
774 synchronizeAttribute(localName);
775 const AtomicString& caseAdjustedLocalName = shouldIgnoreAttributeCase(this) ? localName.lower() : localName;
777 size_t index = elementData() ? elementData()->getAttributeItemIndex(caseAdjustedLocalName, false) : notFound;
778 const QualifiedName& qName = index != notFound ? attributeItem(index)->name() : QualifiedName(nullAtom, caseAdjustedLocalName, nullAtom);
779 setAttributeInternal(index, qName, value, NotInSynchronizationOfLazyAttribute);
782 void Element::setAttribute(const QualifiedName& name, const AtomicString& value)
784 synchronizeAttribute(name);
785 size_t index = elementData() ? elementData()->getAttributeItemIndex(name) : notFound;
786 setAttributeInternal(index, name, value, NotInSynchronizationOfLazyAttribute);
789 void Element::setSynchronizedLazyAttribute(const QualifiedName& name, const AtomicString& value)
791 size_t index = elementData() ? elementData()->getAttributeItemIndex(name) : notFound;
792 setAttributeInternal(index, name, value, InSynchronizationOfLazyAttribute);
795 inline void Element::setAttributeInternal(size_t index, const QualifiedName& name, const AtomicString& newValue, SynchronizationOfLazyAttribute inSynchronizationOfLazyAttribute)
797 if (newValue.isNull()) {
798 if (index != notFound)
799 removeAttributeInternal(index, inSynchronizationOfLazyAttribute);
803 if (index == notFound) {
804 addAttributeInternal(name, newValue, inSynchronizationOfLazyAttribute);
808 if (!inSynchronizationOfLazyAttribute)
809 willModifyAttribute(name, attributeItem(index)->value(), newValue);
811 if (newValue != attributeItem(index)->value()) {
812 ensureUniqueElementData()->attributeItem(index)->setValue(newValue);
814 if (RefPtr<Attr> attrNode = inSynchronizationOfLazyAttribute ? 0 : attrIfExists(name))
815 attrNode->recreateTextChildAfterAttributeValueChanged();
818 if (!inSynchronizationOfLazyAttribute)
819 didModifyAttribute(name, newValue);
822 static inline AtomicString makeIdForStyleResolution(const AtomicString& value, bool inQuirksMode)
825 return value.lower();
829 static bool checkNeedsStyleInvalidationForIdChange(const AtomicString& oldId, const AtomicString& newId, StyleResolver* styleResolver)
831 ASSERT(newId != oldId);
832 if (!oldId.isEmpty() && styleResolver->hasSelectorForId(oldId))
834 if (!newId.isEmpty() && styleResolver->hasSelectorForId(newId))
839 void Element::attributeChanged(const QualifiedName& name, const AtomicString& newValue)
841 if (ElementShadow* parentElementShadow = shadowOfParentForDistribution(this)) {
842 if (shouldInvalidateDistributionWhenAttributeChanged(parentElementShadow, name, newValue))
843 parentElementShadow->invalidateDistribution();
846 parseAttribute(name, newValue);
848 document()->incDOMTreeVersion();
850 StyleResolver* styleResolver = document()->styleResolverIfExists();
851 bool testShouldInvalidateStyle = attached() && styleResolver && styleChangeType() < FullStyleChange;
852 bool shouldInvalidateStyle = false;
854 if (isIdAttributeName(name)) {
855 AtomicString oldId = elementData()->idForStyleResolution();
856 AtomicString newId = makeIdForStyleResolution(newValue, document()->inQuirksMode());
857 if (newId != oldId) {
858 elementData()->setIdForStyleResolution(newId);
859 shouldInvalidateStyle = testShouldInvalidateStyle && checkNeedsStyleInvalidationForIdChange(oldId, newId, styleResolver);
861 } else if (name == classAttr)
862 classAttributeChanged(newValue);
863 else if (name == HTMLNames::nameAttr)
864 setHasName(!newValue.isNull());
865 else if (name == HTMLNames::pseudoAttr)
866 shouldInvalidateStyle |= testShouldInvalidateStyle && isInShadowTree();
868 shouldInvalidateStyle |= testShouldInvalidateStyle && styleResolver->hasSelectorForAttribute(name.localName());
870 invalidateNodeListCachesInAncestors(&name, this);
872 // If there is currently no StyleResolver, we can't be sure that this attribute change won't affect style.
873 shouldInvalidateStyle |= !styleResolver;
875 if (shouldInvalidateStyle)
876 setNeedsStyleRecalc();
878 if (AXObjectCache::accessibilityEnabled())
879 document()->axObjectCache()->handleAttributeChanged(name, this);
882 template <typename CharacterType>
883 static inline bool classStringHasClassName(const CharacterType* characters, unsigned length)
889 if (isNotHTMLSpace(characters[i]))
892 } while (i < length);
897 static inline bool classStringHasClassName(const AtomicString& newClassString)
899 unsigned length = newClassString.length();
904 if (newClassString.is8Bit())
905 return classStringHasClassName(newClassString.characters8(), length);
906 return classStringHasClassName(newClassString.characters16(), length);
909 template<typename Checker>
910 static bool checkSelectorForClassChange(const SpaceSplitString& changedClasses, const Checker& checker)
912 unsigned changedSize = changedClasses.size();
913 for (unsigned i = 0; i < changedSize; ++i) {
914 if (checker.hasSelectorForClass(changedClasses[i]))
920 template<typename Checker>
921 static bool checkSelectorForClassChange(const SpaceSplitString& oldClasses, const SpaceSplitString& newClasses, const Checker& checker)
923 unsigned oldSize = oldClasses.size();
925 return checkSelectorForClassChange(newClasses, checker);
926 BitVector remainingClassBits;
927 remainingClassBits.ensureSize(oldSize);
928 // Class vectors tend to be very short. This is faster than using a hash table.
929 unsigned newSize = newClasses.size();
930 for (unsigned i = 0; i < newSize; ++i) {
931 for (unsigned j = 0; j < oldSize; ++j) {
932 if (newClasses[i] == oldClasses[j]) {
933 remainingClassBits.quickSet(j);
937 if (checker.hasSelectorForClass(newClasses[i]))
940 for (unsigned i = 0; i < oldSize; ++i) {
941 // If the bit is not set the the corresponding class has been removed.
942 if (remainingClassBits.quickGet(i))
944 if (checker.hasSelectorForClass(oldClasses[i]))
950 void Element::classAttributeChanged(const AtomicString& newClassString)
952 StyleResolver* styleResolver = document()->styleResolverIfExists();
953 bool testShouldInvalidateStyle = attached() && styleResolver && styleChangeType() < FullStyleChange;
954 bool shouldInvalidateStyle = false;
956 if (classStringHasClassName(newClassString)) {
957 const bool shouldFoldCase = document()->inQuirksMode();
958 const SpaceSplitString oldClasses = elementData()->classNames();
959 elementData()->setClass(newClassString, shouldFoldCase);
960 const SpaceSplitString& newClasses = elementData()->classNames();
961 shouldInvalidateStyle = testShouldInvalidateStyle && checkSelectorForClassChange(oldClasses, newClasses, *styleResolver);
963 const SpaceSplitString& oldClasses = elementData()->classNames();
964 shouldInvalidateStyle = testShouldInvalidateStyle && checkSelectorForClassChange(oldClasses, *styleResolver);
965 elementData()->clearClass();
969 elementRareData()->clearClassListValueForQuirksMode();
971 if (shouldInvalidateStyle)
972 setNeedsStyleRecalc();
975 bool Element::shouldInvalidateDistributionWhenAttributeChanged(ElementShadow* elementShadow, const QualifiedName& name, const AtomicString& newValue)
977 ASSERT(elementShadow);
978 const SelectRuleFeatureSet& featureSet = elementShadow->distributor().ensureSelectFeatureSet(elementShadow);
980 if (isIdAttributeName(name)) {
981 AtomicString oldId = elementData()->idForStyleResolution();
982 AtomicString newId = makeIdForStyleResolution(newValue, document()->inQuirksMode());
983 if (newId != oldId) {
984 if (!oldId.isEmpty() && featureSet.hasSelectorForId(oldId))
986 if (!newId.isEmpty() && featureSet.hasSelectorForId(newId))
991 if (name == HTMLNames::classAttr) {
992 const AtomicString& newClassString = newValue;
993 if (classStringHasClassName(newClassString)) {
994 const bool shouldFoldCase = document()->inQuirksMode();
995 const SpaceSplitString& oldClasses = elementData()->classNames();
996 const SpaceSplitString newClasses(newClassString, shouldFoldCase);
997 if (checkSelectorForClassChange(oldClasses, newClasses, featureSet))
1000 const SpaceSplitString& oldClasses = elementData()->classNames();
1001 if (checkSelectorForClassChange(oldClasses, featureSet))
1006 return featureSet.hasSelectorForAttribute(name.localName());
1009 // Returns true is the given attribute is an event handler.
1010 // We consider an event handler any attribute that begins with "on".
1011 // It is a simple solution that has the advantage of not requiring any
1012 // code or configuration change if a new event handler is defined.
1014 static bool isEventHandlerAttribute(const QualifiedName& name)
1016 return name.namespaceURI().isNull() && name.localName().startsWith("on");
1019 // FIXME: Share code with Element::isURLAttribute.
1020 static bool isAttributeToRemove(const QualifiedName& name, const AtomicString& value)
1022 return (name.localName() == hrefAttr.localName() || name.localName() == nohrefAttr.localName()
1023 || name == srcAttr || name == actionAttr || name == formactionAttr) && protocolIsJavaScript(stripLeadingAndTrailingHTMLSpaces(value));
1026 void Element::parserSetAttributes(const Vector<Attribute>& attributeVector, FragmentScriptingPermission scriptingPermission)
1028 ASSERT(!inDocument());
1029 ASSERT(!parentNode());
1031 ASSERT(!m_elementData);
1033 if (attributeVector.isEmpty())
1036 Vector<Attribute> filteredAttributes = attributeVector;
1038 // If the element is created as result of a paste or drag-n-drop operation
1039 // we want to remove all the script and event handlers.
1040 if (!scriptingContentIsAllowed(scriptingPermission)) {
1042 while (i < filteredAttributes.size()) {
1043 Attribute& attribute = filteredAttributes[i];
1044 if (isEventHandlerAttribute(attribute.name())) {
1045 filteredAttributes.remove(i);
1049 if (isAttributeToRemove(attribute.name(), attribute.value()))
1050 attribute.setValue(emptyAtom);
1055 if (document() && document()->sharedObjectPool())
1056 m_elementData = document()->sharedObjectPool()->cachedShareableElementDataWithAttributes(filteredAttributes);
1058 m_elementData = ShareableElementData::createWithAttributes(filteredAttributes);
1060 // Iterate over the set of attributes we already have on the stack in case
1061 // attributeChanged mutates m_elementData.
1062 // FIXME: Find a way so we don't have to do this.
1063 for (unsigned i = 0; i < filteredAttributes.size(); ++i)
1064 attributeChanged(filteredAttributes[i].name(), filteredAttributes[i].value());
1067 bool Element::hasAttributes() const
1069 synchronizeAllAttributes();
1070 return elementData() && elementData()->length();
1073 bool Element::hasEquivalentAttributes(const Element* other) const
1075 synchronizeAllAttributes();
1076 other->synchronizeAllAttributes();
1077 if (elementData() == other->elementData())
1080 return elementData()->isEquivalent(other->elementData());
1081 if (other->elementData())
1082 return other->elementData()->isEquivalent(elementData());
1086 String Element::nodeName() const
1088 return m_tagName.toString();
1091 String Element::nodeNamePreservingCase() const
1093 return m_tagName.toString();
1096 void Element::setPrefix(const AtomicString& prefix, ExceptionCode& ec)
1099 checkSetPrefix(prefix, ec);
1103 m_tagName.setPrefix(prefix.isEmpty() ? AtomicString() : prefix);
1106 KURL Element::baseURI() const
1108 const AtomicString& baseAttribute = getAttribute(baseAttr);
1109 KURL base(KURL(), baseAttribute);
1110 if (!base.protocol().isEmpty())
1113 ContainerNode* parent = parentNode();
1117 const KURL& parentBase = parent->baseURI();
1118 if (parentBase.isNull())
1121 return KURL(parentBase, baseAttribute);
1124 const QualifiedName& Element::imageSourceAttributeName() const
1129 bool Element::rendererIsNeeded(const NodeRenderingContext& context)
1131 return context.style()->display() != NONE;
1134 RenderObject* Element::createRenderer(RenderArena*, RenderStyle* style)
1136 return RenderObject::createObject(this, style);
1139 #if ENABLE(INPUT_MULTIPLE_FIELDS_UI)
1140 bool Element::isDateTimeFieldElement() const
1146 bool Element::wasChangedSinceLastFormControlChangeEvent() const
1151 void Element::setChangedSinceLastFormControlChangeEvent(bool)
1155 Node::InsertionNotificationRequest Element::insertedInto(ContainerNode* insertionPoint)
1157 // need to do superclass processing first so inDocument() is true
1158 // by the time we reach updateId
1159 ContainerNode::insertedInto(insertionPoint);
1161 #if ENABLE(FULLSCREEN_API)
1162 if (containsFullScreenElement() && parentElement() && !parentElement()->containsFullScreenElement())
1163 setContainsFullScreenElementOnAncestorsCrossingFrameBoundaries(true);
1166 if (Element* before = pseudoElement(BEFORE))
1167 before->insertedInto(insertionPoint);
1169 if (Element* after = pseudoElement(AFTER))
1170 after->insertedInto(insertionPoint);
1172 if (!insertionPoint->isInTreeScope())
1173 return InsertionDone;
1176 elementRareData()->clearClassListValueForQuirksMode();
1178 TreeScope* scope = insertionPoint->treeScope();
1179 if (scope != treeScope())
1180 return InsertionDone;
1182 const AtomicString& idValue = getIdAttribute();
1183 if (!idValue.isNull())
1184 updateId(scope, nullAtom, idValue);
1186 const AtomicString& nameValue = getNameAttribute();
1187 if (!nameValue.isNull())
1188 updateName(nullAtom, nameValue);
1190 if (hasTagName(labelTag)) {
1191 if (scope->shouldCacheLabelsByForAttribute())
1192 updateLabel(scope, nullAtom, fastGetAttribute(forAttr));
1195 return InsertionDone;
1198 void Element::removedFrom(ContainerNode* insertionPoint)
1201 bool wasInDocument = insertionPoint->document();
1204 if (Element* before = pseudoElement(BEFORE))
1205 before->removedFrom(insertionPoint);
1207 if (Element* after = pseudoElement(AFTER))
1208 after->removedFrom(insertionPoint);
1210 #if ENABLE(DIALOG_ELEMENT)
1211 document()->removeFromTopLayer(this);
1213 #if ENABLE(FULLSCREEN_API)
1214 if (containsFullScreenElement())
1215 setContainsFullScreenElementOnAncestorsCrossingFrameBoundaries(false);
1217 #if ENABLE(POINTER_LOCK)
1218 if (document()->page())
1219 document()->page()->pointerLockController()->elementRemoved(this);
1222 setSavedLayerScrollOffset(IntSize());
1224 if (insertionPoint->isInTreeScope() && treeScope() == document()) {
1225 const AtomicString& idValue = getIdAttribute();
1226 if (!idValue.isNull())
1227 updateId(insertionPoint->treeScope(), idValue, nullAtom);
1229 const AtomicString& nameValue = getNameAttribute();
1230 if (!nameValue.isNull())
1231 updateName(nameValue, nullAtom);
1233 if (hasTagName(labelTag)) {
1234 TreeScope* treeScope = insertionPoint->treeScope();
1235 if (treeScope->shouldCacheLabelsByForAttribute())
1236 updateLabel(treeScope, fastGetAttribute(forAttr), nullAtom);
1240 ContainerNode::removedFrom(insertionPoint);
1242 if (wasInDocument && hasPendingResources())
1243 document()->accessSVGExtensions()->removeElementFromPendingResources(this);
1247 void Element::createRendererIfNeeded()
1249 NodeRenderingContext(this).createRendererForElementIfNeeded();
1252 void Element::attach()
1254 PostAttachCallbackDisabler callbackDisabler(this);
1255 StyleResolverParentPusher parentPusher(this);
1256 WidgetHierarchyUpdatesSuspensionScope suspendWidgetHierarchyUpdates;
1258 createRendererIfNeeded();
1260 if (parentElement() && parentElement()->isInCanvasSubtree())
1261 setIsInCanvasSubtree(true);
1263 updatePseudoElement(BEFORE);
1265 // When a shadow root exists, it does the work of attaching the children.
1266 if (ElementShadow* shadow = this->shadow()) {
1267 parentPusher.push();
1269 } else if (firstChild())
1270 parentPusher.push();
1272 ContainerNode::attach();
1274 updatePseudoElement(AFTER);
1276 if (hasRareData()) {
1277 ElementRareData* data = elementRareData();
1278 if (data->needsFocusAppearanceUpdateSoonAfterAttach()) {
1279 if (isFocusable() && document()->focusedNode() == this)
1280 document()->updateFocusAppearanceSoon(false /* don't restore selection */);
1281 data->setNeedsFocusAppearanceUpdateSoonAfterAttach(false);
1286 void Element::unregisterNamedFlowContentNode()
1288 if (document()->cssRegionsEnabled() && inNamedFlow() && document()->renderView())
1289 document()->renderView()->flowThreadController()->unregisterNamedFlowContentNode(this);
1292 void Element::detach()
1294 WidgetHierarchyUpdatesSuspensionScope suspendWidgetHierarchyUpdates;
1295 unregisterNamedFlowContentNode();
1296 cancelFocusAppearanceUpdate();
1297 if (hasRareData()) {
1298 ElementRareData* data = elementRareData();
1299 data->setPseudoElement(BEFORE, 0);
1300 data->setPseudoElement(AFTER, 0);
1301 data->setIsInCanvasSubtree(false);
1302 data->resetComputedStyle();
1303 data->resetDynamicRestyleObservations();
1306 if (ElementShadow* shadow = this->shadow()) {
1307 detachChildrenIfNeeded();
1310 ContainerNode::detach();
1313 bool Element::pseudoStyleCacheIsInvalid(const RenderStyle* currentStyle, RenderStyle* newStyle)
1315 ASSERT(currentStyle == renderStyle());
1321 const PseudoStyleCache* pseudoStyleCache = currentStyle->cachedPseudoStyles();
1322 if (!pseudoStyleCache)
1325 size_t cacheSize = pseudoStyleCache->size();
1326 for (size_t i = 0; i < cacheSize; ++i) {
1327 RefPtr<RenderStyle> newPseudoStyle;
1328 PseudoId pseudoId = pseudoStyleCache->at(i)->styleType();
1329 if (pseudoId == FIRST_LINE || pseudoId == FIRST_LINE_INHERITED)
1330 newPseudoStyle = renderer()->uncachedFirstLineStyle(newStyle);
1332 newPseudoStyle = renderer()->getUncachedPseudoStyle(PseudoStyleRequest(pseudoId), newStyle, newStyle);
1333 if (!newPseudoStyle)
1335 if (*newPseudoStyle != *pseudoStyleCache->at(i)) {
1336 if (pseudoId < FIRST_INTERNAL_PSEUDOID)
1337 newStyle->setHasPseudoStyle(pseudoId);
1338 newStyle->addCachedPseudoStyle(newPseudoStyle);
1339 if (pseudoId == FIRST_LINE || pseudoId == FIRST_LINE_INHERITED) {
1340 // FIXME: We should do an actual diff to determine whether a repaint vs. layout
1341 // is needed, but for now just assume a layout will be required. The diff code
1342 // in RenderObject::setStyle would need to be factored out so that it could be reused.
1343 renderer()->setNeedsLayoutAndPrefWidthsRecalc();
1351 PassRefPtr<RenderStyle> Element::styleForRenderer()
1353 if (hasCustomStyleCallbacks()) {
1354 if (RefPtr<RenderStyle> style = customStyleForRenderer())
1355 return style.release();
1358 return document()->styleResolver()->styleForElement(this);
1361 void Element::recalcStyle(StyleChange change)
1363 if (hasCustomStyleCallbacks()) {
1364 if (!willRecalcStyle(change))
1368 // Ref currentStyle in case it would otherwise be deleted when setting the new style in the renderer.
1369 RefPtr<RenderStyle> currentStyle(renderStyle());
1370 bool hasParentStyle = parentNodeForRenderingAndStyle() ? static_cast<bool>(parentNodeForRenderingAndStyle()->renderStyle()) : false;
1371 bool hasDirectAdjacentRules = childrenAffectedByDirectAdjacentRules();
1372 bool hasIndirectAdjacentRules = childrenAffectedByForwardPositionalRules();
1374 if ((change > NoChange || needsStyleRecalc())) {
1376 elementRareData()->resetComputedStyle();
1378 if (hasParentStyle && (change >= Inherit || needsStyleRecalc())) {
1379 RefPtr<RenderStyle> newStyle = styleForRenderer();
1380 StyleChange ch = Node::diff(currentStyle.get(), newStyle.get(), document());
1381 if (ch == Detach || !currentStyle) {
1382 // FIXME: The style gets computed twice by calling attach. We could do better if we passed the style along.
1384 // attach recalculates the style for all children. No need to do it twice.
1385 clearNeedsStyleRecalc();
1386 clearChildNeedsStyleRecalc();
1388 if (hasCustomStyleCallbacks())
1389 didRecalcStyle(change);
1393 if (RenderObject* renderer = this->renderer()) {
1394 if (ch != NoChange || pseudoStyleCacheIsInvalid(currentStyle.get(), newStyle.get()) || (change == Force && renderer->requiresForcedStyleRecalcPropagation()) || styleChangeType() == SyntheticStyleChange)
1395 renderer->setAnimatableStyle(newStyle.get());
1396 else if (needsStyleRecalc()) {
1397 // Although no change occurred, we use the new style so that the cousin style sharing code won't get
1398 // fooled into believing this style is the same.
1399 renderer->setStyleInternal(newStyle.get());
1403 // If "rem" units are used anywhere in the document, and if the document element's font size changes, then go ahead and force font updating
1404 // all the way down the tree. This is simpler than having to maintain a cache of objects (and such font size changes should be rare anyway).
1405 if (document()->styleSheetCollection()->usesRemUnits() && document()->documentElement() == this && ch != NoChange && currentStyle && newStyle && currentStyle->fontSize() != newStyle->fontSize()) {
1406 // Cached RenderStyles may depend on the re units.
1407 document()->styleResolver()->invalidateMatchedPropertiesCache();
1411 if (change != Force) {
1412 if (styleChangeType() >= FullStyleChange)
1418 StyleResolverParentPusher parentPusher(this);
1420 // FIXME: This does not care about sibling combinators. Will be necessary in XBL2 world.
1421 if (ElementShadow* shadow = this->shadow()) {
1422 if (change >= Inherit || shadow->childNeedsStyleRecalc() || shadow->needsStyleRecalc()) {
1423 parentPusher.push();
1424 shadow->recalcStyle(change);
1428 updatePseudoElement(BEFORE, change);
1430 // FIXME: This check is good enough for :hover + foo, but it is not good enough for :hover + foo + bar.
1431 // For now we will just worry about the common case, since it's a lot trickier to get the second case right
1432 // without doing way too much re-resolution.
1433 bool forceCheckOfNextElementSibling = false;
1434 bool forceCheckOfAnyElementSibling = false;
1435 for (Node *n = firstChild(); n; n = n->nextSibling()) {
1436 if (n->isTextNode()) {
1437 toText(n)->recalcTextStyle(change);
1440 if (!n->isElementNode())
1442 Element* element = static_cast<Element*>(n);
1443 bool childRulesChanged = element->needsStyleRecalc() && element->styleChangeType() == FullStyleChange;
1444 if ((forceCheckOfNextElementSibling || forceCheckOfAnyElementSibling))
1445 element->setNeedsStyleRecalc();
1446 if (change >= Inherit || element->childNeedsStyleRecalc() || element->needsStyleRecalc()) {
1447 parentPusher.push();
1448 element->recalcStyle(change);
1450 forceCheckOfNextElementSibling = childRulesChanged && hasDirectAdjacentRules;
1451 forceCheckOfAnyElementSibling = forceCheckOfAnyElementSibling || (childRulesChanged && hasIndirectAdjacentRules);
1454 updatePseudoElement(AFTER, change);
1456 clearNeedsStyleRecalc();
1457 clearChildNeedsStyleRecalc();
1459 if (hasCustomStyleCallbacks())
1460 didRecalcStyle(change);
1463 ElementShadow* Element::shadow() const
1465 return hasRareData() ? elementRareData()->shadow() : 0;
1468 ElementShadow* Element::ensureShadow()
1470 return ensureElementRareData()->ensureShadow();
1473 void Element::didAffectSelector(AffectedSelectorMask mask)
1475 setNeedsStyleRecalc();
1476 if (ElementShadow* elementShadow = shadowOfParentForDistribution(this))
1477 elementShadow->didAffectSelector(mask);
1480 PassRefPtr<ShadowRoot> Element::createShadowRoot(ExceptionCode& ec)
1482 if (alwaysCreateUserAgentShadowRoot())
1483 ensureUserAgentShadowRoot();
1485 #if ENABLE(SHADOW_DOM)
1486 if (RuntimeEnabledFeatures::authorShadowDOMForAnyElementEnabled())
1487 return ensureShadow()->addShadowRoot(this, ShadowRoot::AuthorShadowRoot);
1490 // Since some elements recreates shadow root dynamically, multiple shadow
1491 // subtrees won't work well in that element. Until they are fixed, we disable
1492 // adding author shadow root for them.
1493 if (!areAuthorShadowsAllowed()) {
1494 ec = HIERARCHY_REQUEST_ERR;
1497 return ensureShadow()->addShadowRoot(this, ShadowRoot::AuthorShadowRoot);
1500 ShadowRoot* Element::shadowRoot() const
1502 ElementShadow* elementShadow = shadow();
1505 ShadowRoot* shadowRoot = elementShadow->youngestShadowRoot();
1506 if (shadowRoot->type() == ShadowRoot::AuthorShadowRoot)
1511 ShadowRoot* Element::userAgentShadowRoot() const
1513 if (ElementShadow* elementShadow = shadow()) {
1514 if (ShadowRoot* shadowRoot = elementShadow->oldestShadowRoot()) {
1515 ASSERT(shadowRoot->type() == ShadowRoot::UserAgentShadowRoot);
1523 ShadowRoot* Element::ensureUserAgentShadowRoot()
1525 if (ShadowRoot* shadowRoot = userAgentShadowRoot())
1527 ShadowRoot* shadowRoot = ensureShadow()->addShadowRoot(this, ShadowRoot::UserAgentShadowRoot);
1528 didAddUserAgentShadowRoot(shadowRoot);
1532 const AtomicString& Element::shadowPseudoId() const
1537 bool Element::childTypeAllowed(NodeType type) const
1543 case PROCESSING_INSTRUCTION_NODE:
1544 case CDATA_SECTION_NODE:
1545 case ENTITY_REFERENCE_NODE:
1553 static void checkForEmptyStyleChange(Element* element, RenderStyle* style)
1555 if (!style && !element->styleAffectedByEmpty())
1558 if (!style || (element->styleAffectedByEmpty() && (!style->emptyState() || element->hasChildNodes())))
1559 element->setNeedsStyleRecalc();
1562 static void checkForSiblingStyleChanges(Element* e, RenderStyle* style, bool finishedParsingCallback,
1563 Node* beforeChange, Node* afterChange, int childCountDelta)
1566 checkForEmptyStyleChange(e, style);
1568 if (!style || (e->needsStyleRecalc() && e->childrenAffectedByPositionalRules()))
1571 // :first-child. In the parser callback case, we don't have to check anything, since we were right the first time.
1572 // In the DOM case, we only need to do something if |afterChange| is not 0.
1573 // |afterChange| is 0 in the parser case, so it works out that we'll skip this block.
1574 if (e->childrenAffectedByFirstChildRules() && afterChange) {
1575 // Find our new first child.
1576 Node* newFirstChild = 0;
1577 for (newFirstChild = e->firstChild(); newFirstChild && !newFirstChild->isElementNode(); newFirstChild = newFirstChild->nextSibling()) {};
1579 // Find the first element node following |afterChange|
1580 Node* firstElementAfterInsertion = 0;
1581 for (firstElementAfterInsertion = afterChange;
1582 firstElementAfterInsertion && !firstElementAfterInsertion->isElementNode();
1583 firstElementAfterInsertion = firstElementAfterInsertion->nextSibling()) {};
1585 // This is the insert/append case.
1586 if (newFirstChild != firstElementAfterInsertion && firstElementAfterInsertion && firstElementAfterInsertion->attached() &&
1587 firstElementAfterInsertion->renderStyle() && firstElementAfterInsertion->renderStyle()->firstChildState())
1588 firstElementAfterInsertion->setNeedsStyleRecalc();
1590 // We also have to handle node removal.
1591 if (childCountDelta < 0 && newFirstChild == firstElementAfterInsertion && newFirstChild && (!newFirstChild->renderStyle() || !newFirstChild->renderStyle()->firstChildState()))
1592 newFirstChild->setNeedsStyleRecalc();
1595 // :last-child. In the parser callback case, we don't have to check anything, since we were right the first time.
1596 // In the DOM case, we only need to do something if |afterChange| is not 0.
1597 if (e->childrenAffectedByLastChildRules() && beforeChange) {
1598 // Find our new last child.
1599 Node* newLastChild = 0;
1600 for (newLastChild = e->lastChild(); newLastChild && !newLastChild->isElementNode(); newLastChild = newLastChild->previousSibling()) {};
1602 // Find the last element node going backwards from |beforeChange|
1603 Node* lastElementBeforeInsertion = 0;
1604 for (lastElementBeforeInsertion = beforeChange;
1605 lastElementBeforeInsertion && !lastElementBeforeInsertion->isElementNode();
1606 lastElementBeforeInsertion = lastElementBeforeInsertion->previousSibling()) {};
1608 if (newLastChild != lastElementBeforeInsertion && lastElementBeforeInsertion && lastElementBeforeInsertion->attached() &&
1609 lastElementBeforeInsertion->renderStyle() && lastElementBeforeInsertion->renderStyle()->lastChildState())
1610 lastElementBeforeInsertion->setNeedsStyleRecalc();
1612 // 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
1614 if ((childCountDelta < 0 || finishedParsingCallback) && newLastChild == lastElementBeforeInsertion && newLastChild && (!newLastChild->renderStyle() || !newLastChild->renderStyle()->lastChildState()))
1615 newLastChild->setNeedsStyleRecalc();
1618 // The + selector. We need to invalidate the first element following the insertion point. It is the only possible element
1619 // that could be affected by this DOM change.
1620 if (e->childrenAffectedByDirectAdjacentRules() && afterChange) {
1621 Node* firstElementAfterInsertion = 0;
1622 for (firstElementAfterInsertion = afterChange;
1623 firstElementAfterInsertion && !firstElementAfterInsertion->isElementNode();
1624 firstElementAfterInsertion = firstElementAfterInsertion->nextSibling()) {};
1625 if (firstElementAfterInsertion && firstElementAfterInsertion->attached())
1626 firstElementAfterInsertion->setNeedsStyleRecalc();
1629 // Forward positional selectors include the ~ selector, nth-child, nth-of-type, first-of-type and only-of-type.
1630 // Backward positional selectors include nth-last-child, nth-last-of-type, last-of-type and only-of-type.
1631 // We have to invalidate everything following the insertion point in the forward case, and everything before the insertion point in the
1633 // |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.
1634 // 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
1635 // here. recalcStyle will then force a walk of the children when it sees that this has happened.
1636 if ((e->childrenAffectedByForwardPositionalRules() && afterChange)
1637 || (e->childrenAffectedByBackwardPositionalRules() && beforeChange))
1638 e->setNeedsStyleRecalc();
1641 void Element::childrenChanged(bool changedByParser, Node* beforeChange, Node* afterChange, int childCountDelta)
1643 ContainerNode::childrenChanged(changedByParser, beforeChange, afterChange, childCountDelta);
1644 if (changedByParser)
1645 checkForEmptyStyleChange(this, renderStyle());
1647 checkForSiblingStyleChanges(this, renderStyle(), false, beforeChange, afterChange, childCountDelta);
1649 if (ElementShadow * shadow = this->shadow())
1650 shadow->invalidateDistribution();
1653 void Element::beginParsingChildren()
1655 clearIsParsingChildrenFinished();
1656 StyleResolver* styleResolver = document()->styleResolverIfExists();
1657 if (styleResolver && attached())
1658 styleResolver->pushParentElement(this);
1661 void Element::finishParsingChildren()
1663 ContainerNode::finishParsingChildren();
1664 setIsParsingChildrenFinished();
1665 checkForSiblingStyleChanges(this, renderStyle(), true, lastChild(), 0, 0);
1666 if (StyleResolver* styleResolver = document()->styleResolverIfExists())
1667 styleResolver->popParentElement(this);
1671 void Element::formatForDebugger(char* buffer, unsigned length) const
1673 StringBuilder result;
1676 result.append(nodeName());
1678 s = getIdAttribute();
1679 if (s.length() > 0) {
1680 if (result.length() > 0)
1681 result.appendLiteral("; ");
1682 result.appendLiteral("id=");
1686 s = getAttribute(classAttr);
1687 if (s.length() > 0) {
1688 if (result.length() > 0)
1689 result.appendLiteral("; ");
1690 result.appendLiteral("class=");
1694 strncpy(buffer, result.toString().utf8().data(), length - 1);
1698 const Vector<RefPtr<Attr> >& Element::attrNodeList()
1700 ASSERT(hasSyntheticAttrChildNodes());
1701 return *attrNodeListForElement(this);
1704 PassRefPtr<Attr> Element::setAttributeNode(Attr* attrNode, ExceptionCode& ec)
1707 ec = TYPE_MISMATCH_ERR;
1711 RefPtr<Attr> oldAttrNode = attrIfExists(attrNode->qualifiedName());
1712 if (oldAttrNode.get() == attrNode)
1713 return attrNode; // This Attr is already attached to the element.
1715 // INUSE_ATTRIBUTE_ERR: Raised if node is an Attr that is already an attribute of another Element object.
1716 // The DOM user must explicitly clone Attr nodes to re-use them in other elements.
1717 if (attrNode->ownerElement()) {
1718 ec = INUSE_ATTRIBUTE_ERR;
1722 synchronizeAllAttributes();
1723 UniqueElementData* elementData = ensureUniqueElementData();
1725 size_t index = elementData->getAttributeItemIndex(attrNode->qualifiedName());
1726 if (index != notFound) {
1728 detachAttrNodeFromElementWithValue(oldAttrNode.get(), elementData->attributeItem(index)->value());
1730 oldAttrNode = Attr::create(document(), attrNode->qualifiedName(), elementData->attributeItem(index)->value());
1733 setAttributeInternal(index, attrNode->qualifiedName(), attrNode->value(), NotInSynchronizationOfLazyAttribute);
1735 attrNode->attachToElement(this);
1736 ensureAttrNodeListForElement(this)->append(attrNode);
1738 return oldAttrNode.release();
1741 PassRefPtr<Attr> Element::setAttributeNodeNS(Attr* attr, ExceptionCode& ec)
1743 return setAttributeNode(attr, ec);
1746 PassRefPtr<Attr> Element::removeAttributeNode(Attr* attr, ExceptionCode& ec)
1749 ec = TYPE_MISMATCH_ERR;
1752 if (attr->ownerElement() != this) {
1757 ASSERT(document() == attr->document());
1759 synchronizeAttribute(attr->qualifiedName());
1761 size_t index = elementData()->getAttributeItemIndex(attr->qualifiedName());
1762 if (index == notFound) {
1767 return detachAttribute(index);
1770 bool Element::parseAttributeName(QualifiedName& out, const AtomicString& namespaceURI, const AtomicString& qualifiedName, ExceptionCode& ec)
1772 String prefix, localName;
1773 if (!Document::parseQualifiedName(qualifiedName, prefix, localName, ec))
1777 QualifiedName qName(prefix, localName, namespaceURI);
1779 if (!Document::hasValidNamespaceForAttributes(qName)) {
1788 void Element::setAttributeNS(const AtomicString& namespaceURI, const AtomicString& qualifiedName, const AtomicString& value, ExceptionCode& ec)
1790 QualifiedName parsedName = anyName;
1791 if (!parseAttributeName(parsedName, namespaceURI, qualifiedName, ec))
1793 setAttribute(parsedName, value);
1796 void Element::removeAttributeInternal(size_t index, SynchronizationOfLazyAttribute inSynchronizationOfLazyAttribute)
1798 ASSERT_WITH_SECURITY_IMPLICATION(index < attributeCount());
1800 UniqueElementData* elementData = ensureUniqueElementData();
1802 QualifiedName name = elementData->attributeItem(index)->name();
1803 AtomicString valueBeingRemoved = elementData->attributeItem(index)->value();
1805 if (!inSynchronizationOfLazyAttribute) {
1806 if (!valueBeingRemoved.isNull())
1807 willModifyAttribute(name, valueBeingRemoved, nullAtom);
1810 if (RefPtr<Attr> attrNode = attrIfExists(name))
1811 detachAttrNodeFromElementWithValue(attrNode.get(), elementData->attributeItem(index)->value());
1813 elementData->removeAttribute(index);
1815 if (!inSynchronizationOfLazyAttribute)
1816 didRemoveAttribute(name);
1819 void Element::addAttributeInternal(const QualifiedName& name, const AtomicString& value, SynchronizationOfLazyAttribute inSynchronizationOfLazyAttribute)
1821 if (!inSynchronizationOfLazyAttribute)
1822 willModifyAttribute(name, nullAtom, value);
1823 ensureUniqueElementData()->addAttribute(name, value);
1824 if (!inSynchronizationOfLazyAttribute)
1825 didAddAttribute(name, value);
1828 void Element::removeAttribute(const AtomicString& name)
1833 AtomicString localName = shouldIgnoreAttributeCase(this) ? name.lower() : name;
1834 size_t index = elementData()->getAttributeItemIndex(localName, false);
1835 if (index == notFound) {
1836 if (UNLIKELY(localName == styleAttr) && elementData()->m_styleAttributeIsDirty && isStyledElement())
1837 static_cast<StyledElement*>(this)->removeAllInlineStyleProperties();
1841 removeAttributeInternal(index, NotInSynchronizationOfLazyAttribute);
1844 void Element::removeAttributeNS(const AtomicString& namespaceURI, const AtomicString& localName)
1846 removeAttribute(QualifiedName(nullAtom, localName, namespaceURI));
1849 PassRefPtr<Attr> Element::getAttributeNode(const AtomicString& localName)
1853 synchronizeAttribute(localName);
1854 const Attribute* attribute = elementData()->getAttributeItem(localName, shouldIgnoreAttributeCase(this));
1857 return ensureAttr(attribute->name());
1860 PassRefPtr<Attr> Element::getAttributeNodeNS(const AtomicString& namespaceURI, const AtomicString& localName)
1864 QualifiedName qName(nullAtom, localName, namespaceURI);
1865 synchronizeAttribute(qName);
1866 const Attribute* attribute = elementData()->getAttributeItem(qName);
1869 return ensureAttr(attribute->name());
1872 bool Element::hasAttribute(const AtomicString& localName) const
1876 synchronizeAttribute(localName);
1877 return elementData()->getAttributeItem(shouldIgnoreAttributeCase(this) ? localName.lower() : localName, false);
1880 bool Element::hasAttributeNS(const AtomicString& namespaceURI, const AtomicString& localName) const
1884 QualifiedName qName(nullAtom, localName, namespaceURI);
1885 synchronizeAttribute(qName);
1886 return elementData()->getAttributeItem(qName);
1889 CSSStyleDeclaration *Element::style()
1894 void Element::focus(bool restorePreviousSelection, FocusDirection direction)
1899 Document* doc = document();
1900 if (doc->focusedNode() == this)
1903 // If the stylesheets have already been loaded we can reliably check isFocusable.
1904 // If not, we continue and set the focused node on the focus controller below so
1905 // that it can be updated soon after attach.
1906 if (doc->haveStylesheetsLoaded()) {
1907 doc->updateLayoutIgnorePendingStylesheets();
1912 if (!supportsFocus())
1915 RefPtr<Node> protect;
1916 if (Page* page = doc->page()) {
1917 // Focus and change event handlers can cause us to lose our last ref.
1918 // If a focus event handler changes the focus to a different node it
1919 // does not make sense to continue and update appearence.
1921 if (!page->focusController()->setFocusedNode(this, doc->frame(), direction))
1925 // Setting the focused node above might have invalidated the layout due to scripts.
1926 doc->updateLayoutIgnorePendingStylesheets();
1928 if (!isFocusable()) {
1929 ensureElementRareData()->setNeedsFocusAppearanceUpdateSoonAfterAttach(true);
1933 cancelFocusAppearanceUpdate();
1934 updateFocusAppearance(restorePreviousSelection);
1937 void Element::updateFocusAppearance(bool /*restorePreviousSelection*/)
1939 if (isRootEditableElement()) {
1940 Frame* frame = document()->frame();
1944 // When focusing an editable element in an iframe, don't reset the selection if it already contains a selection.
1945 if (this == frame->selection()->rootEditableElement())
1948 // FIXME: We should restore the previous selection if there is one.
1949 VisibleSelection newSelection = VisibleSelection(firstPositionInOrBeforeNode(this), DOWNSTREAM);
1951 if (frame->selection()->shouldChangeSelection(newSelection)) {
1952 frame->selection()->setSelection(newSelection);
1953 frame->selection()->revealSelection();
1955 } else if (renderer() && !renderer()->isWidget())
1956 renderer()->scrollRectToVisible(boundingBox());
1959 void Element::blur()
1961 cancelFocusAppearanceUpdate();
1962 Document* doc = document();
1963 if (treeScope()->focusedNode() == this) {
1965 doc->frame()->page()->focusController()->setFocusedNode(0, doc->frame());
1967 doc->setFocusedNode(0);
1971 String Element::innerText()
1973 // We need to update layout, since plainText uses line boxes in the render tree.
1974 document()->updateLayoutIgnorePendingStylesheets();
1977 return textContent(true);
1979 return plainText(rangeOfContents(const_cast<Element*>(this)).get());
1982 String Element::outerText()
1984 // Getting outerText is the same as getting innerText, only
1985 // setting is different. You would think this should get the plain
1986 // text for the outer range, but this is wrong, <br> for instance
1987 // would return different values for inner and outer text by such
1988 // a rule, but it doesn't in WinIE, and we want to match that.
1992 String Element::title() const
1997 const AtomicString& Element::pseudo() const
1999 return getAttribute(pseudoAttr);
2002 void Element::setPseudo(const AtomicString& value)
2004 setAttribute(pseudoAttr, value);
2007 LayoutSize Element::minimumSizeForResizing() const
2009 return hasRareData() ? elementRareData()->minimumSizeForResizing() : defaultMinimumSizeForResizing();
2012 void Element::setMinimumSizeForResizing(const LayoutSize& size)
2014 if (!hasRareData() && size == defaultMinimumSizeForResizing())
2016 ensureElementRareData()->setMinimumSizeForResizing(size);
2019 RenderStyle* Element::computedStyle(PseudoId pseudoElementSpecifier)
2021 if (PseudoElement* element = pseudoElement(pseudoElementSpecifier))
2022 return element->computedStyle();
2024 // FIXME: Find and use the renderer from the pseudo element instead of the actual element so that the 'length'
2025 // properties, which are only known by the renderer because it did the layout, will be correct and so that the
2026 // values returned for the ":selection" pseudo-element will be correct.
2027 if (RenderStyle* usedStyle = renderStyle()) {
2028 if (pseudoElementSpecifier) {
2029 RenderStyle* cachedPseudoStyle = usedStyle->getCachedPseudoStyle(pseudoElementSpecifier);
2030 return cachedPseudoStyle ? cachedPseudoStyle : usedStyle;
2036 // FIXME: Try to do better than this. Ensure that styleForElement() works for elements that are not in the
2037 // document tree and figure out when to destroy the computed style for such elements.
2040 ElementRareData* data = ensureElementRareData();
2041 if (!data->computedStyle())
2042 data->setComputedStyle(document()->styleForElementIgnoringPendingStylesheets(this));
2043 return pseudoElementSpecifier ? data->computedStyle()->getCachedPseudoStyle(pseudoElementSpecifier) : data->computedStyle();
2046 void Element::setStyleAffectedByEmpty()
2048 ensureElementRareData()->setStyleAffectedByEmpty(true);
2051 void Element::setChildrenAffectedByHover(bool value)
2053 if (value || hasRareData())
2054 ensureElementRareData()->setChildrenAffectedByHover(value);
2057 void Element::setChildrenAffectedByActive(bool value)
2059 if (value || hasRareData())
2060 ensureElementRareData()->setChildrenAffectedByActive(value);
2063 void Element::setChildrenAffectedByDrag(bool value)
2065 if (value || hasRareData())
2066 ensureElementRareData()->setChildrenAffectedByDrag(value);
2069 void Element::setChildrenAffectedByFirstChildRules()
2071 ensureElementRareData()->setChildrenAffectedByFirstChildRules(true);
2074 void Element::setChildrenAffectedByLastChildRules()
2076 ensureElementRareData()->setChildrenAffectedByLastChildRules(true);
2079 void Element::setChildrenAffectedByDirectAdjacentRules()
2081 ensureElementRareData()->setChildrenAffectedByDirectAdjacentRules(true);
2084 void Element::setChildrenAffectedByForwardPositionalRules()
2086 ensureElementRareData()->setChildrenAffectedByForwardPositionalRules(true);
2089 void Element::setChildrenAffectedByBackwardPositionalRules()
2091 ensureElementRareData()->setChildrenAffectedByBackwardPositionalRules(true);
2094 void Element::setChildIndex(unsigned index)
2096 ElementRareData* rareData = ensureElementRareData();
2097 if (RenderStyle* style = renderStyle())
2099 rareData->setChildIndex(index);
2102 bool Element::hasFlagsSetDuringStylingOfChildren() const
2106 return rareDataChildrenAffectedByHover()
2107 || rareDataChildrenAffectedByActive()
2108 || rareDataChildrenAffectedByDrag()
2109 || rareDataChildrenAffectedByFirstChildRules()
2110 || rareDataChildrenAffectedByLastChildRules()
2111 || rareDataChildrenAffectedByDirectAdjacentRules()
2112 || rareDataChildrenAffectedByForwardPositionalRules()
2113 || rareDataChildrenAffectedByBackwardPositionalRules();
2116 bool Element::rareDataStyleAffectedByEmpty() const
2118 ASSERT(hasRareData());
2119 return elementRareData()->styleAffectedByEmpty();
2122 bool Element::rareDataChildrenAffectedByHover() const
2124 ASSERT(hasRareData());
2125 return elementRareData()->childrenAffectedByHover();
2128 bool Element::rareDataChildrenAffectedByActive() const
2130 ASSERT(hasRareData());
2131 return elementRareData()->childrenAffectedByActive();
2134 bool Element::rareDataChildrenAffectedByDrag() const
2136 ASSERT(hasRareData());
2137 return elementRareData()->childrenAffectedByDrag();
2140 bool Element::rareDataChildrenAffectedByFirstChildRules() const
2142 ASSERT(hasRareData());
2143 return elementRareData()->childrenAffectedByFirstChildRules();
2146 bool Element::rareDataChildrenAffectedByLastChildRules() const
2148 ASSERT(hasRareData());
2149 return elementRareData()->childrenAffectedByLastChildRules();
2152 bool Element::rareDataChildrenAffectedByDirectAdjacentRules() const
2154 ASSERT(hasRareData());
2155 return elementRareData()->childrenAffectedByDirectAdjacentRules();
2158 bool Element::rareDataChildrenAffectedByForwardPositionalRules() const
2160 ASSERT(hasRareData());
2161 return elementRareData()->childrenAffectedByForwardPositionalRules();
2164 bool Element::rareDataChildrenAffectedByBackwardPositionalRules() const
2166 ASSERT(hasRareData());
2167 return elementRareData()->childrenAffectedByBackwardPositionalRules();
2170 unsigned Element::rareDataChildIndex() const
2172 ASSERT(hasRareData());
2173 return elementRareData()->childIndex();
2176 void Element::setIsInCanvasSubtree(bool isInCanvasSubtree)
2178 ensureElementRareData()->setIsInCanvasSubtree(isInCanvasSubtree);
2181 bool Element::isInCanvasSubtree() const
2183 return hasRareData() && elementRareData()->isInCanvasSubtree();
2186 AtomicString Element::computeInheritedLanguage() const
2188 const Node* n = this;
2190 // The language property is inherited, so we iterate over the parents to find the first language.
2192 if (n->isElementNode()) {
2193 if (const ElementData* elementData = static_cast<const Element*>(n)->elementData()) {
2194 // Spec: xml:lang takes precedence -- http://www.w3.org/TR/xhtml1/#C_7
2195 if (const Attribute* attribute = elementData->getAttributeItem(XMLNames::langAttr))
2196 value = attribute->value();
2197 else if (const Attribute* attribute = elementData->getAttributeItem(HTMLNames::langAttr))
2198 value = attribute->value();
2200 } else if (n->isDocumentNode()) {
2201 // checking the MIME content-language
2202 value = static_cast<const Document*>(n)->contentLanguage();
2205 n = n->parentNode();
2206 } while (n && value.isNull());
2211 Locale& Element::locale() const
2213 return document()->getCachedLocale(computeInheritedLanguage());
2216 void Element::cancelFocusAppearanceUpdate()
2219 elementRareData()->setNeedsFocusAppearanceUpdateSoonAfterAttach(false);
2220 if (document()->focusedNode() == this)
2221 document()->cancelFocusAppearanceUpdate();
2224 void Element::normalizeAttributes()
2226 if (!hasAttributes())
2228 for (unsigned i = 0; i < attributeCount(); ++i) {
2229 if (RefPtr<Attr> attr = attrIfExists(attributeItem(i)->name()))
2234 void Element::updatePseudoElement(PseudoId pseudoId, StyleChange change)
2236 PseudoElement* existing = pseudoElement(pseudoId);
2238 // PseudoElement styles hang off their parent element's style so if we needed
2239 // a style recalc we should Force one on the pseudo.
2240 existing->recalcStyle(needsStyleRecalc() ? Force : change);
2242 // Wait until our parent is not displayed or pseudoElementRendererIsNeeded
2243 // is false, otherwise we could continously create and destroy PseudoElements
2244 // when RenderObject::isChildAllowed on our parent returns false for the
2245 // PseudoElement's renderer for each style recalc.
2246 if (!renderer() || !pseudoElementRendererIsNeeded(renderer()->getCachedPseudoStyle(pseudoId)))
2247 setPseudoElement(pseudoId, 0);
2248 } else if (RefPtr<PseudoElement> element = createPseudoElementIfNeeded(pseudoId)) {
2250 setPseudoElement(pseudoId, element.release());
2254 PassRefPtr<PseudoElement> Element::createPseudoElementIfNeeded(PseudoId pseudoId)
2256 if (!document()->styleSheetCollection()->usesBeforeAfterRules())
2259 if (!renderer() || !renderer()->canHaveGeneratedChildren())
2262 if (isPseudoElement())
2265 if (!pseudoElementRendererIsNeeded(renderer()->getCachedPseudoStyle(pseudoId)))
2268 return PseudoElement::create(this, pseudoId);
2271 bool Element::hasPseudoElements() const
2273 return hasRareData() && elementRareData()->hasPseudoElements();
2276 PseudoElement* Element::pseudoElement(PseudoId pseudoId) const
2278 return hasRareData() ? elementRareData()->pseudoElement(pseudoId) : 0;
2281 void Element::setPseudoElement(PseudoId pseudoId, PassRefPtr<PseudoElement> element)
2283 ensureElementRareData()->setPseudoElement(pseudoId, element);
2284 resetNeedsShadowTreeWalker();
2287 RenderObject* Element::pseudoElementRenderer(PseudoId pseudoId) const
2289 if (PseudoElement* element = pseudoElement(pseudoId))
2290 return element->renderer();
2294 // ElementTraversal API
2295 Element* Element::firstElementChild() const
2297 return ElementTraversal::firstWithin(this);
2300 Element* Element::lastElementChild() const
2302 Node* n = lastChild();
2303 while (n && !n->isElementNode())
2304 n = n->previousSibling();
2305 return static_cast<Element*>(n);
2308 unsigned Element::childElementCount() const
2311 Node* n = firstChild();
2313 count += n->isElementNode();
2314 n = n->nextSibling();
2319 bool Element::matchesReadOnlyPseudoClass() const
2324 bool Element::matchesReadWritePseudoClass() const
2329 bool Element::webkitMatchesSelector(const String& selector, ExceptionCode& ec)
2331 if (selector.isEmpty()) {
2336 SelectorQuery* selectorQuery = document()->selectorQueryCache()->add(selector, document(), ec);
2339 return selectorQuery->matches(this);
2342 DOMTokenList* Element::classList()
2344 ElementRareData* data = ensureElementRareData();
2345 if (!data->classList())
2346 data->setClassList(ClassList::create(this));
2347 return data->classList();
2350 DOMStringMap* Element::dataset()
2352 ElementRareData* data = ensureElementRareData();
2353 if (!data->dataset())
2354 data->setDataset(DatasetDOMStringMap::create(this));
2355 return data->dataset();
2358 KURL Element::getURLAttribute(const QualifiedName& name) const
2360 #if !ASSERT_DISABLED
2361 if (elementData()) {
2362 if (const Attribute* attribute = getAttributeItem(name))
2363 ASSERT(isURLAttribute(*attribute));
2366 return document()->completeURL(stripLeadingAndTrailingHTMLSpaces(getAttribute(name)));
2369 KURL Element::getNonEmptyURLAttribute(const QualifiedName& name) const
2371 #if !ASSERT_DISABLED
2372 if (elementData()) {
2373 if (const Attribute* attribute = getAttributeItem(name))
2374 ASSERT(isURLAttribute(*attribute));
2377 String value = stripLeadingAndTrailingHTMLSpaces(getAttribute(name));
2378 if (value.isEmpty())
2380 return document()->completeURL(value);
2383 int Element::getIntegralAttribute(const QualifiedName& attributeName) const
2385 return getAttribute(attributeName).string().toInt();
2388 void Element::setIntegralAttribute(const QualifiedName& attributeName, int value)
2390 // FIXME: Need an AtomicString version of String::number.
2391 setAttribute(attributeName, String::number(value));
2394 unsigned Element::getUnsignedIntegralAttribute(const QualifiedName& attributeName) const
2396 return getAttribute(attributeName).string().toUInt();
2399 void Element::setUnsignedIntegralAttribute(const QualifiedName& attributeName, unsigned value)
2401 // FIXME: Need an AtomicString version of String::number.
2402 setAttribute(attributeName, String::number(value));
2406 bool Element::childShouldCreateRenderer(const NodeRenderingContext& childContext) const
2408 // Only create renderers for SVG elements whose parents are SVG elements, or for proper <svg xmlns="svgNS"> subdocuments.
2409 if (childContext.node()->isSVGElement())
2410 return childContext.node()->hasTagName(SVGNames::svgTag) || isSVGElement();
2412 return ContainerNode::childShouldCreateRenderer(childContext);
2416 #if ENABLE(FULLSCREEN_API)
2417 void Element::webkitRequestFullscreen()
2419 document()->requestFullScreenForElement(this, ALLOW_KEYBOARD_INPUT, Document::EnforceIFrameAllowFullScreenRequirement);
2422 void Element::webkitRequestFullScreen(unsigned short flags)
2424 document()->requestFullScreenForElement(this, (flags | LEGACY_MOZILLA_REQUEST), Document::EnforceIFrameAllowFullScreenRequirement);
2427 bool Element::containsFullScreenElement() const
2429 return hasRareData() && elementRareData()->containsFullScreenElement();
2432 void Element::setContainsFullScreenElement(bool flag)
2434 ensureElementRareData()->setContainsFullScreenElement(flag);
2435 setNeedsStyleRecalc(SyntheticStyleChange);
2438 static Element* parentCrossingFrameBoundaries(Element* element)
2441 return element->parentElement() ? element->parentElement() : element->document()->ownerElement();
2444 void Element::setContainsFullScreenElementOnAncestorsCrossingFrameBoundaries(bool flag)
2446 Element* element = this;
2447 while ((element = parentCrossingFrameBoundaries(element)))
2448 element->setContainsFullScreenElement(flag);
2452 #if ENABLE(DIALOG_ELEMENT)
2453 bool Element::isInTopLayer() const
2455 return hasRareData() && elementRareData()->isInTopLayer();
2458 void Element::setIsInTopLayer(bool inTopLayer)
2460 if (isInTopLayer() == inTopLayer)
2462 ensureElementRareData()->setIsInTopLayer(inTopLayer);
2464 // We must ensure a reattach occurs so the renderer is inserted in the correct sibling order under RenderView according to its
2465 // top layer position, or in its usual place if not in the top layer.
2466 reattachIfAttached();
2470 #if ENABLE(POINTER_LOCK)
2471 void Element::webkitRequestPointerLock()
2473 if (document()->page())
2474 document()->page()->pointerLockController()->requestPointerLock(this);
2478 SpellcheckAttributeState Element::spellcheckAttributeState() const
2480 const AtomicString& value = getAttribute(HTMLNames::spellcheckAttr);
2481 if (value == nullAtom)
2482 return SpellcheckAttributeDefault;
2483 if (equalIgnoringCase(value, "true") || equalIgnoringCase(value, ""))
2484 return SpellcheckAttributeTrue;
2485 if (equalIgnoringCase(value, "false"))
2486 return SpellcheckAttributeFalse;
2488 return SpellcheckAttributeDefault;
2491 bool Element::isSpellCheckingEnabled() const
2493 for (const Element* element = this; element; element = element->parentOrShadowHostElement()) {
2494 switch (element->spellcheckAttributeState()) {
2495 case SpellcheckAttributeTrue:
2497 case SpellcheckAttributeFalse:
2499 case SpellcheckAttributeDefault:
2507 RenderRegion* Element::renderRegion() const
2509 if (renderer() && renderer()->isRenderRegion())
2510 return toRenderRegion(renderer());
2515 #if ENABLE(CSS_REGIONS)
2517 const AtomicString& Element::webkitRegionOverset() const
2519 document()->updateLayoutIgnorePendingStylesheets();
2521 DEFINE_STATIC_LOCAL(AtomicString, undefinedState, ("undefined", AtomicString::ConstructFromLiteral));
2522 if (!document()->cssRegionsEnabled() || !renderRegion())
2523 return undefinedState;
2525 switch (renderRegion()->regionState()) {
2526 case RenderRegion::RegionFit: {
2527 DEFINE_STATIC_LOCAL(AtomicString, fitState, ("fit", AtomicString::ConstructFromLiteral));
2530 case RenderRegion::RegionEmpty: {
2531 DEFINE_STATIC_LOCAL(AtomicString, emptyState, ("empty", AtomicString::ConstructFromLiteral));
2534 case RenderRegion::RegionOverset: {
2535 DEFINE_STATIC_LOCAL(AtomicString, overflowState, ("overset", AtomicString::ConstructFromLiteral));
2536 return overflowState;
2538 case RenderRegion::RegionUndefined:
2539 return undefinedState;
2542 ASSERT_NOT_REACHED();
2543 return undefinedState;
2546 Vector<RefPtr<Range> > Element::webkitGetRegionFlowRanges() const
2548 document()->updateLayoutIgnorePendingStylesheets();
2550 Vector<RefPtr<Range> > rangeObjects;
2551 if (document()->cssRegionsEnabled() && renderer() && renderer()->isRenderRegion()) {
2552 RenderRegion* region = toRenderRegion(renderer());
2553 if (region->isValid())
2554 region->getRanges(rangeObjects);
2557 return rangeObjects;
2563 bool Element::fastAttributeLookupAllowed(const QualifiedName& name) const
2565 if (name == HTMLNames::styleAttr)
2570 return !static_cast<const SVGElement*>(this)->isAnimatableAttribute(name);
2577 #ifdef DUMP_NODE_STATISTICS
2578 bool Element::hasNamedNodeMap() const
2580 return hasRareData() && elementRareData()->attributeMap();
2584 inline void Element::updateName(const AtomicString& oldName, const AtomicString& newName)
2586 if (!inDocument() || isInShadowTree())
2589 if (oldName == newName)
2592 if (shouldRegisterAsNamedItem())
2593 updateNamedItemRegistration(oldName, newName);
2596 inline void Element::updateId(const AtomicString& oldId, const AtomicString& newId)
2598 if (!isInTreeScope())
2604 updateId(treeScope(), oldId, newId);
2607 inline void Element::updateId(TreeScope* scope, const AtomicString& oldId, const AtomicString& newId)
2609 ASSERT(isInTreeScope());
2610 ASSERT(oldId != newId);
2612 if (!oldId.isEmpty())
2613 scope->removeElementById(oldId, this);
2614 if (!newId.isEmpty())
2615 scope->addElementById(newId, this);
2617 if (shouldRegisterAsExtraNamedItem())
2618 updateExtraNamedItemRegistration(oldId, newId);
2621 void Element::updateLabel(TreeScope* scope, const AtomicString& oldForAttributeValue, const AtomicString& newForAttributeValue)
2623 ASSERT(hasTagName(labelTag));
2628 if (oldForAttributeValue == newForAttributeValue)
2631 if (!oldForAttributeValue.isEmpty())
2632 scope->removeLabel(oldForAttributeValue, static_cast<HTMLLabelElement*>(this));
2633 if (!newForAttributeValue.isEmpty())
2634 scope->addLabel(newForAttributeValue, static_cast<HTMLLabelElement*>(this));
2637 void Element::willModifyAttribute(const QualifiedName& name, const AtomicString& oldValue, const AtomicString& newValue)
2639 if (isIdAttributeName(name))
2640 updateId(oldValue, newValue);
2641 else if (name == HTMLNames::nameAttr)
2642 updateName(oldValue, newValue);
2643 else if (name == HTMLNames::forAttr && hasTagName(labelTag)) {
2644 TreeScope* scope = treeScope();
2645 if (scope->shouldCacheLabelsByForAttribute())
2646 updateLabel(scope, oldValue, newValue);
2649 if (OwnPtr<MutationObserverInterestGroup> recipients = MutationObserverInterestGroup::createForAttributesMutation(this, name))
2650 recipients->enqueueMutationRecord(MutationRecord::createAttributes(this, name, oldValue));
2652 #if ENABLE(INSPECTOR)
2653 InspectorInstrumentation::willModifyDOMAttr(document(), this, oldValue, newValue);
2657 void Element::didAddAttribute(const QualifiedName& name, const AtomicString& value)
2659 attributeChanged(name, value);
2660 InspectorInstrumentation::didModifyDOMAttr(document(), this, name.localName(), value);
2661 dispatchSubtreeModifiedEvent();
2664 void Element::didModifyAttribute(const QualifiedName& name, const AtomicString& value)
2666 attributeChanged(name, value);
2667 InspectorInstrumentation::didModifyDOMAttr(document(), this, name.localName(), value);
2668 // Do not dispatch a DOMSubtreeModified event here; see bug 81141.
2671 void Element::didRemoveAttribute(const QualifiedName& name)
2673 attributeChanged(name, nullAtom);
2674 InspectorInstrumentation::didRemoveDOMAttr(document(), this, name.localName());
2675 dispatchSubtreeModifiedEvent();
2679 void Element::updateNamedItemRegistration(const AtomicString& oldName, const AtomicString& newName)
2681 if (!document()->isHTMLDocument())
2684 if (!oldName.isEmpty())
2685 static_cast<HTMLDocument*>(document())->removeNamedItem(oldName);
2687 if (!newName.isEmpty())
2688 static_cast<HTMLDocument*>(document())->addNamedItem(newName);
2691 void Element::updateExtraNamedItemRegistration(const AtomicString& oldId, const AtomicString& newId)
2693 if (!document()->isHTMLDocument())
2696 if (!oldId.isEmpty())
2697 static_cast<HTMLDocument*>(document())->removeExtraNamedItem(oldId);
2699 if (!newId.isEmpty())
2700 static_cast<HTMLDocument*>(document())->addExtraNamedItem(newId);
2703 PassRefPtr<HTMLCollection> Element::ensureCachedHTMLCollection(CollectionType type)
2705 if (HTMLCollection* collection = cachedHTMLCollection(type))
2708 RefPtr<HTMLCollection> collection;
2709 if (type == TableRows) {
2710 ASSERT(hasTagName(tableTag));
2711 return ensureRareData()->ensureNodeLists()->addCacheWithAtomicName<HTMLTableRowsCollection>(this, type);
2712 } else if (type == SelectOptions) {
2713 ASSERT(hasTagName(selectTag));
2714 return ensureRareData()->ensureNodeLists()->addCacheWithAtomicName<HTMLOptionsCollection>(this, type);
2715 } else if (type == FormControls) {
2716 ASSERT(hasTagName(formTag) || hasTagName(fieldsetTag));
2717 return ensureRareData()->ensureNodeLists()->addCacheWithAtomicName<HTMLFormControlsCollection>(this, type);
2718 #if ENABLE(MICRODATA)
2719 } else if (type == ItemProperties) {
2720 return ensureRareData()->ensureNodeLists()->addCacheWithAtomicName<HTMLPropertiesCollection>(this, type);
2723 return ensureRareData()->ensureNodeLists()->addCacheWithAtomicName<HTMLCollection>(this, type);
2726 HTMLCollection* Element::cachedHTMLCollection(CollectionType type)
2728 return hasRareData() && rareData()->nodeLists() ? rareData()->nodeLists()->cacheWithAtomicName<HTMLCollection>(type) : 0;
2731 IntSize Element::savedLayerScrollOffset() const
2733 return hasRareData() ? elementRareData()->savedLayerScrollOffset() : IntSize();
2736 void Element::setSavedLayerScrollOffset(const IntSize& size)
2738 if (size.isZero() && !hasRareData())
2740 ensureElementRareData()->setSavedLayerScrollOffset(size);
2743 PassRefPtr<Attr> Element::attrIfExists(const QualifiedName& name)
2745 if (AttrNodeList* attrNodeList = attrNodeListForElement(this))
2746 return findAttrNodeInList(attrNodeList, name);
2750 PassRefPtr<Attr> Element::ensureAttr(const QualifiedName& name)
2752 AttrNodeList* attrNodeList = ensureAttrNodeListForElement(this);
2753 RefPtr<Attr> attrNode = findAttrNodeInList(attrNodeList, name);
2755 attrNode = Attr::create(this, name);
2756 treeScope()->adoptIfNeeded(attrNode.get());
2757 attrNodeList->append(attrNode);
2759 return attrNode.release();
2762 void Element::detachAttrNodeFromElementWithValue(Attr* attrNode, const AtomicString& value)
2764 ASSERT(hasSyntheticAttrChildNodes());
2765 attrNode->detachFromElementWithValue(value);
2767 AttrNodeList* attrNodeList = attrNodeListForElement(this);
2768 for (unsigned i = 0; i < attrNodeList->size(); ++i) {
2769 if (attrNodeList->at(i)->qualifiedName() == attrNode->qualifiedName()) {
2770 attrNodeList->remove(i);
2771 if (attrNodeList->isEmpty())
2772 removeAttrNodeListForElement(this);
2776 ASSERT_NOT_REACHED();
2779 void Element::detachAllAttrNodesFromElement()
2781 AttrNodeList* attrNodeList = attrNodeListForElement(this);
2782 ASSERT(attrNodeList);
2784 for (unsigned i = 0; i < attributeCount(); ++i) {
2785 const Attribute* attribute = attributeItem(i);
2786 if (RefPtr<Attr> attrNode = findAttrNodeInList(attrNodeList, attribute->name()))
2787 attrNode->detachFromElementWithValue(attribute->value());
2790 removeAttrNodeListForElement(this);
2793 bool Element::willRecalcStyle(StyleChange)
2795 ASSERT(hasCustomStyleCallbacks());
2799 void Element::didRecalcStyle(StyleChange)
2801 ASSERT(hasCustomStyleCallbacks());
2805 PassRefPtr<RenderStyle> Element::customStyleForRenderer()
2807 ASSERT(hasCustomStyleCallbacks());
2811 void Element::cloneAttributesFromElement(const Element& other)
2813 if (hasSyntheticAttrChildNodes())
2814 detachAllAttrNodesFromElement();
2816 other.synchronizeAllAttributes();
2817 if (!other.m_elementData) {
2818 m_elementData.clear();
2822 const AtomicString& oldID = getIdAttribute();
2823 const AtomicString& newID = other.getIdAttribute();
2825 if (!oldID.isNull() || !newID.isNull())
2826 updateId(oldID, newID);
2828 const AtomicString& oldName = getNameAttribute();
2829 const AtomicString& newName = other.getNameAttribute();
2831 if (!oldName.isNull() || !newName.isNull())
2832 updateName(oldName, newName);
2834 // If 'other' has a mutable ElementData, convert it to an immutable one so we can share it between both elements.
2835 // We can only do this if there is no CSSOM wrapper for other's inline style, and there are no presentation attributes.
2836 if (other.m_elementData->isUnique()
2837 && !other.m_elementData->presentationAttributeStyle()
2838 && (!other.m_elementData->inlineStyle() || !other.m_elementData->inlineStyle()->hasCSSOMWrapper()))
2839 const_cast<Element&>(other).m_elementData = static_cast<const UniqueElementData*>(other.m_elementData.get())->makeShareableCopy();
2841 if (!other.m_elementData->isUnique())
2842 m_elementData = other.m_elementData;
2844 m_elementData = other.m_elementData->makeUniqueCopy();
2846 for (unsigned i = 0; i < m_elementData->length(); ++i) {
2847 const Attribute* attribute = const_cast<const ElementData*>(m_elementData.get())->attributeItem(i);
2848 attributeChanged(attribute->name(), attribute->value());
2852 void Element::cloneDataFromElement(const Element& other)
2854 cloneAttributesFromElement(other);
2855 copyNonAttributePropertiesFromElement(other);
2858 void Element::createUniqueElementData()
2861 m_elementData = UniqueElementData::create();
2863 ASSERT(!m_elementData->isUnique());
2864 m_elementData = static_cast<ShareableElementData*>(m_elementData.get())->makeUniqueCopy();
2868 void Element::reportMemoryUsage(MemoryObjectInfo* memoryObjectInfo) const
2870 MemoryClassInfo info(memoryObjectInfo, this, WebCoreMemoryTypes::DOM);
2871 ContainerNode::reportMemoryUsage(memoryObjectInfo);
2872 info.addMember(m_tagName, "tagName");
2873 info.addMember(m_elementData, "elementData");
2877 bool Element::hasPendingResources() const
2879 return hasRareData() && elementRareData()->hasPendingResources();
2882 void Element::setHasPendingResources()
2884 ensureElementRareData()->setHasPendingResources(true);
2887 void Element::clearHasPendingResources()
2889 ensureElementRareData()->setHasPendingResources(false);
2893 void ElementData::deref()
2899 delete static_cast<UniqueElementData*>(this);
2901 delete static_cast<ShareableElementData*>(this);
2904 ElementData::ElementData()
2907 , m_presentationAttributeStyleIsDirty(false)
2908 , m_styleAttributeIsDirty(false)
2910 , m_animatedSVGAttributesAreDirty(false)
2915 ElementData::ElementData(unsigned arraySize)
2917 , m_arraySize(arraySize)
2918 , m_presentationAttributeStyleIsDirty(false)
2919 , m_styleAttributeIsDirty(false)
2921 , m_animatedSVGAttributesAreDirty(false)
2926 struct SameSizeAsElementData : public RefCounted<SameSizeAsElementData> {
2931 COMPILE_ASSERT(sizeof(ElementData) == sizeof(SameSizeAsElementData), element_attribute_data_should_stay_small);
2933 static size_t sizeForShareableElementDataWithAttributeCount(unsigned count)
2935 return sizeof(ShareableElementData) + sizeof(Attribute) * count;
2938 PassRefPtr<ShareableElementData> ShareableElementData::createWithAttributes(const Vector<Attribute>& attributes)
2940 void* slot = WTF::fastMalloc(sizeForShareableElementDataWithAttributeCount(attributes.size()));
2941 return adoptRef(new (slot) ShareableElementData(attributes));
2944 PassRefPtr<UniqueElementData> UniqueElementData::create()
2946 return adoptRef(new UniqueElementData);
2949 ShareableElementData::ShareableElementData(const Vector<Attribute>& attributes)
2950 : ElementData(attributes.size())
2952 for (unsigned i = 0; i < m_arraySize; ++i)
2953 new (&m_attributeArray[i]) Attribute(attributes[i]);
2956 ShareableElementData::~ShareableElementData()
2958 for (unsigned i = 0; i < m_arraySize; ++i)
2959 m_attributeArray[i].~Attribute();
2962 ShareableElementData::ShareableElementData(const UniqueElementData& other)
2963 : ElementData(other, false)
2965 ASSERT(!other.m_presentationAttributeStyle);
2967 if (other.m_inlineStyle) {
2968 ASSERT(!other.m_inlineStyle->hasCSSOMWrapper());
2969 m_inlineStyle = other.m_inlineStyle->immutableCopyIfNeeded();
2972 for (unsigned i = 0; i < m_arraySize; ++i)
2973 new (&m_attributeArray[i]) Attribute(other.m_attributeVector.at(i));
2976 ElementData::ElementData(const ElementData& other, bool isUnique)
2977 : m_isUnique(isUnique)
2978 , m_arraySize(isUnique ? 0 : other.length())
2979 , m_presentationAttributeStyleIsDirty(other.m_presentationAttributeStyleIsDirty)
2980 , m_styleAttributeIsDirty(other.m_styleAttributeIsDirty)
2982 , m_animatedSVGAttributesAreDirty(other.m_animatedSVGAttributesAreDirty)
2984 , m_classNames(other.m_classNames)
2985 , m_idForStyleResolution(other.m_idForStyleResolution)
2987 // NOTE: The inline style is copied by the subclass copy constructor since we don't know what to do with it here.
2990 UniqueElementData::UniqueElementData()
2994 UniqueElementData::UniqueElementData(const UniqueElementData& other)
2995 : ElementData(other, true)
2996 , m_presentationAttributeStyle(other.m_presentationAttributeStyle)
2997 , m_attributeVector(other.m_attributeVector)
2999 m_inlineStyle = other.m_inlineStyle ? other.m_inlineStyle->copy() : 0;
3002 UniqueElementData::UniqueElementData(const ShareableElementData& other)
3003 : ElementData(other, true)
3005 // An ShareableElementData should never have a mutable inline StylePropertySet attached.
3006 ASSERT(!other.m_inlineStyle || !other.m_inlineStyle->isMutable());
3007 m_inlineStyle = other.m_inlineStyle;
3009 m_attributeVector.reserveCapacity(other.length());
3010 for (unsigned i = 0; i < other.length(); ++i)
3011 m_attributeVector.uncheckedAppend(other.m_attributeArray[i]);
3014 PassRefPtr<UniqueElementData> ElementData::makeUniqueCopy() const
3017 return adoptRef(new UniqueElementData(static_cast<const UniqueElementData&>(*this)));
3018 return adoptRef(new UniqueElementData(static_cast<const ShareableElementData&>(*this)));
3021 PassRefPtr<ShareableElementData> UniqueElementData::makeShareableCopy() const
3023 void* slot = WTF::fastMalloc(sizeForShareableElementDataWithAttributeCount(m_attributeVector.size()));
3024 return adoptRef(new (slot) ShareableElementData(*this));
3027 void UniqueElementData::addAttribute(const QualifiedName& attributeName, const AtomicString& value)
3029 m_attributeVector.append(Attribute(attributeName, value));
3032 void UniqueElementData::removeAttribute(size_t index)
3034 ASSERT_WITH_SECURITY_IMPLICATION(index < length());
3035 m_attributeVector.remove(index);
3038 bool ElementData::isEquivalent(const ElementData* other) const
3043 unsigned len = length();
3044 if (len != other->length())
3047 for (unsigned i = 0; i < len; i++) {
3048 const Attribute* attribute = attributeItem(i);
3049 const Attribute* otherAttr = other->getAttributeItem(attribute->name());
3050 if (!otherAttr || attribute->value() != otherAttr->value())
3057 void ElementData::reportMemoryUsage(MemoryObjectInfo* memoryObjectInfo) const
3059 size_t actualSize = m_isUnique ? sizeof(ElementData) : sizeForShareableElementDataWithAttributeCount(m_arraySize);
3060 MemoryClassInfo info(memoryObjectInfo, this, WebCoreMemoryTypes::DOM, actualSize);
3061 info.addMember(m_inlineStyle, "inlineStyle");
3062 info.addMember(m_classNames, "classNames");
3063 info.addMember(m_idForStyleResolution, "idForStyleResolution");
3065 const UniqueElementData* uniqueThis = static_cast<const UniqueElementData*>(this);
3066 info.addMember(uniqueThis->m_presentationAttributeStyle, "presentationAttributeStyle");
3067 info.addMember(uniqueThis->m_attributeVector, "attributeVector");
3069 for (unsigned i = 0, len = length(); i < len; i++)
3070 info.addMember(*attributeItem(i), "*attributeItem");
3073 size_t ElementData::getAttributeItemIndexSlowCase(const AtomicString& name, bool shouldIgnoreAttributeCase) const
3075 // Continue to checking case-insensitively and/or full namespaced names if necessary:
3076 for (unsigned i = 0; i < length(); ++i) {
3077 const Attribute* attribute = attributeItem(i);
3078 if (!attribute->name().hasPrefix()) {
3079 if (shouldIgnoreAttributeCase && equalIgnoringCase(name, attribute->localName()))
3082 // FIXME: Would be faster to do this comparison without calling toString, which
3083 // generates a temporary string by concatenation. But this branch is only reached
3084 // if the attribute name has a prefix, which is rare in HTML.
3085 if (equalPossiblyIgnoringCase(name, attribute->name().toString(), shouldIgnoreAttributeCase))
3092 Attribute* UniqueElementData::getAttributeItem(const QualifiedName& name)
3094 for (unsigned i = 0; i < length(); ++i) {
3095 if (m_attributeVector.at(i).name().matches(name))
3096 return &m_attributeVector.at(i);
3101 Attribute* UniqueElementData::attributeItem(unsigned index)
3103 ASSERT_WITH_SECURITY_IMPLICATION(index < length());
3104 return &m_attributeVector.at(index);
3107 } // namespace WebCore