blob: 1ea95155d3a19aa7883d153b17e3c14e86fbdfb3 [file] [log] [blame]
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001/*
2 * Copyright (C) 1999 Lars Knoll (knoll@kde.org)
3 * (C) 1999 Antti Koivisto (koivisto@kde.org)
4 * (C) 2001 Peter Kelly (pmk@post.com)
5 * (C) 2001 Dirk Mueller (mueller@kde.org)
6 * (C) 2007 David Smith (catfish.man@gmail.com)
7 * Copyright (C) 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2012, 2013 Apple Inc. All rights reserved.
8 * (C) 2007 Eric Seidel (eric@webkit.org)
9 *
10 * This library is free software; you can redistribute it and/or
11 * modify it under the terms of the GNU Library General Public
12 * License as published by the Free Software Foundation; either
13 * version 2 of the License, or (at your option) any later version.
14 *
15 * This library is distributed in the hope that it will be useful,
16 * but WITHOUT ANY WARRANTY; without even the implied warranty of
17 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
18 * Library General Public License for more details.
19 *
20 * You should have received a copy of the GNU Library General Public License
21 * along with this library; see the file COPYING.LIB. If not, write to
22 * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
23 * Boston, MA 02110-1301, USA.
24 */
25
26#include "config.h"
27#include "core/dom/Element.h"
28
29#include "HTMLNames.h"
30#include "XMLNSNames.h"
31#include "XMLNames.h"
32#include "core/accessibility/AXObjectCache.h"
33#include "core/css/CSSParser.h"
34#include "core/css/CSSSelectorList.h"
35#include "core/css/StylePropertySet.h"
36#include "core/css/StyleResolver.h"
37#include "core/dom/Attr.h"
38#include "core/dom/ClientRect.h"
39#include "core/dom/ClientRectList.h"
40#include "core/dom/CustomElementRegistry.h"
41#include "core/dom/DatasetDOMStringMap.h"
42#include "core/dom/Document.h"
43#include "core/dom/DocumentFragment.h"
44#include "core/dom/DocumentSharedObjectPool.h"
45#include "core/dom/ElementRareData.h"
46#include "core/dom/ExceptionCode.h"
47#include "core/dom/MutationObserverInterestGroup.h"
48#include "core/dom/MutationRecord.h"
49#include "core/dom/NamedNodeMap.h"
50#include "core/dom/NodeList.h"
51#include "core/dom/NodeRenderStyle.h"
52#include "core/dom/NodeRenderingContext.h"
53#include "core/dom/NodeTraversal.h"
54#include "core/dom/PseudoElement.h"
55#include "core/dom/SelectorQuery.h"
56#include "core/dom/ShadowRoot.h"
57#include "core/dom/Text.h"
58#include "core/dom/WebCoreMemoryInstrumentation.h"
59#include "core/editing/FrameSelection.h"
60#include "core/editing/TextIterator.h"
61#include "core/editing/htmlediting.h"
62#include "core/html/ClassList.h"
63#include "core/html/DOMTokenList.h"
64#include "core/html/HTMLCollection.h"
65#include "core/html/HTMLDocument.h"
66#include "core/html/HTMLElement.h"
67#include "core/html/HTMLFormControlsCollection.h"
68#include "core/html/HTMLFrameOwnerElement.h"
69#include "core/html/HTMLLabelElement.h"
70#include "core/html/HTMLOptionsCollection.h"
71#include "core/html/HTMLTableRowsCollection.h"
72#include "core/html/VoidCallback.h"
73#include "core/html/parser/HTMLParserIdioms.h"
74#include "core/html/shadow/InsertionPoint.h"
75#include "core/inspector/InspectorInstrumentation.h"
76#include "core/page/FocusController.h"
77#include "core/page/Frame.h"
78#include "core/page/FrameView.h"
79#include "core/page/Page.h"
80#include "core/page/PointerLockController.h"
81#include "core/page/Settings.h"
82#include "core/rendering/FlowThreadController.h"
83#include "core/rendering/RenderRegion.h"
84#include "core/rendering/RenderView.h"
85#include "core/rendering/RenderWidget.h"
86#include <wtf/BitVector.h>
87#include <wtf/MemoryInstrumentationVector.h>
88#include <wtf/text/CString.h>
89
90#if ENABLE(SVG)
91#include "SVGNames.h"
92#include "core/svg/SVGDocumentExtensions.h"
93#include "core/svg/SVGElement.h"
94#endif
95
96namespace WebCore {
97
98using namespace HTMLNames;
99using namespace XMLNames;
100
101static inline bool shouldIgnoreAttributeCase(const Element* e)
102{
103 return e && e->document()->isHTMLDocument() && e->isHTMLElement();
104}
105
106class StyleResolverParentPusher {
107public:
108 StyleResolverParentPusher(Element* parent)
109 : m_parent(parent)
110 , m_pushedStyleResolver(0)
111 {
112 }
113 void push()
114 {
115 if (m_pushedStyleResolver)
116 return;
117 m_pushedStyleResolver = m_parent->document()->styleResolver();
118 m_pushedStyleResolver->pushParentElement(m_parent);
119 }
120 ~StyleResolverParentPusher()
121 {
122
123 if (!m_pushedStyleResolver)
124 return;
125
126 // This tells us that our pushed style selector is in a bad state,
127 // so we should just bail out in that scenario.
128 ASSERT(m_pushedStyleResolver == m_parent->document()->styleResolver());
129 if (m_pushedStyleResolver != m_parent->document()->styleResolver())
130 return;
131
132 m_pushedStyleResolver->popParentElement(m_parent);
133 }
134
135private:
136 Element* m_parent;
137 StyleResolver* m_pushedStyleResolver;
138};
139
140typedef Vector<RefPtr<Attr> > AttrNodeList;
141typedef HashMap<Element*, OwnPtr<AttrNodeList> > AttrNodeListMap;
142
143static AttrNodeListMap& attrNodeListMap()
144{
145 DEFINE_STATIC_LOCAL(AttrNodeListMap, map, ());
146 return map;
147}
148
149static AttrNodeList* attrNodeListForElement(Element* element)
150{
151 if (!element->hasSyntheticAttrChildNodes())
152 return 0;
153 ASSERT(attrNodeListMap().contains(element));
154 return attrNodeListMap().get(element);
155}
156
157static AttrNodeList* ensureAttrNodeListForElement(Element* element)
158{
159 if (element->hasSyntheticAttrChildNodes()) {
160 ASSERT(attrNodeListMap().contains(element));
161 return attrNodeListMap().get(element);
162 }
163 ASSERT(!attrNodeListMap().contains(element));
164 element->setHasSyntheticAttrChildNodes(true);
165 AttrNodeListMap::AddResult result = attrNodeListMap().add(element, adoptPtr(new AttrNodeList));
166 return result.iterator->value.get();
167}
168
169static void removeAttrNodeListForElement(Element* element)
170{
171 ASSERT(element->hasSyntheticAttrChildNodes());
172 ASSERT(attrNodeListMap().contains(element));
173 attrNodeListMap().remove(element);
174 element->setHasSyntheticAttrChildNodes(false);
175}
176
177static Attr* findAttrNodeInList(AttrNodeList* attrNodeList, const QualifiedName& name)
178{
179 for (unsigned i = 0; i < attrNodeList->size(); ++i) {
180 if (attrNodeList->at(i)->qualifiedName() == name)
181 return attrNodeList->at(i).get();
182 }
183 return 0;
184}
185
186// Need a template since ElementShadow is not a Node, but has the style recalc methods.
187template<class T>
188static inline bool shouldRecalcStyle(Node::StyleChange change, const T* node)
189{
190 return change >= Node::Inherit || node->childNeedsStyleRecalc() || node->needsStyleRecalc();
191}
192
193PassRefPtr<Element> Element::create(const QualifiedName& tagName, Document* document)
194{
195 return adoptRef(new Element(tagName, document, CreateElement));
196}
197
198Element::~Element()
199{
200#ifndef NDEBUG
201 if (document() && document()->renderer()) {
202 // When the document is not destroyed, an element that was part of a named flow
203 // content nodes should have been removed from the content nodes collection
204 // and the inNamedFlow flag reset.
205 ASSERT(!inNamedFlow());
206 }
207#endif
208
209 if (hasRareData()) {
210 ElementRareData* data = elementRareData();
211 data->setPseudoElement(BEFORE, 0);
212 data->setPseudoElement(AFTER, 0);
213 data->clearShadow();
214 }
215
216 if (isCustomElement() && document() && document()->registry()) {
217 document()->registry()->customElementWasDestroyed(this);
218 }
219
220 if (hasSyntheticAttrChildNodes())
221 detachAllAttrNodesFromElement();
222
223#if ENABLE(SVG)
224 if (hasPendingResources()) {
225 document()->accessSVGExtensions()->removeElementFromPendingResources(this);
226 ASSERT(!hasPendingResources());
227 }
228#endif
229}
230
231inline ElementRareData* Element::elementRareData() const
232{
233 ASSERT(hasRareData());
234 return static_cast<ElementRareData*>(rareData());
235}
236
237inline ElementRareData* Element::ensureElementRareData()
238{
239 return static_cast<ElementRareData*>(ensureRareData());
240}
241
242void Element::clearTabIndexExplicitlyIfNeeded()
243{
244 if (hasRareData())
245 elementRareData()->clearTabIndexExplicitly();
246}
247
248void Element::setTabIndexExplicitly(short tabIndex)
249{
250 ensureElementRareData()->setTabIndexExplicitly(tabIndex);
251}
252
253bool Element::supportsFocus() const
254{
255 return hasRareData() && elementRareData()->tabIndexSetExplicitly();
256}
257
258short Element::tabIndex() const
259{
260 return hasRareData() ? elementRareData()->tabIndex() : 0;
261}
262
263DEFINE_VIRTUAL_ATTRIBUTE_EVENT_LISTENER(Element, blur);
264DEFINE_VIRTUAL_ATTRIBUTE_EVENT_LISTENER(Element, error);
265DEFINE_VIRTUAL_ATTRIBUTE_EVENT_LISTENER(Element, focus);
266DEFINE_VIRTUAL_ATTRIBUTE_EVENT_LISTENER(Element, load);
267
268PassRefPtr<Node> Element::cloneNode(bool deep)
269{
270 return deep ? cloneElementWithChildren() : cloneElementWithoutChildren();
271}
272
273PassRefPtr<Element> Element::cloneElementWithChildren()
274{
275 RefPtr<Element> clone = cloneElementWithoutChildren();
276 cloneChildNodes(clone.get());
277 return clone.release();
278}
279
280PassRefPtr<Element> Element::cloneElementWithoutChildren()
281{
282 RefPtr<Element> clone = cloneElementWithoutAttributesAndChildren();
283 // This will catch HTML elements in the wrong namespace that are not correctly copied.
284 // This is a sanity check as HTML overloads some of the DOM methods.
285 ASSERT(isHTMLElement() == clone->isHTMLElement());
286
287 clone->cloneDataFromElement(*this);
288 return clone.release();
289}
290
291PassRefPtr<Element> Element::cloneElementWithoutAttributesAndChildren()
292{
293 return document()->createElement(tagQName(), false);
294}
295
296PassRefPtr<Attr> Element::detachAttribute(size_t index)
297{
298 ASSERT(elementData());
299
300 const Attribute* attribute = elementData()->attributeItem(index);
301 ASSERT(attribute);
302
303 RefPtr<Attr> attrNode = attrIfExists(attribute->name());
304 if (attrNode)
305 detachAttrNodeFromElementWithValue(attrNode.get(), attribute->value());
306 else
307 attrNode = Attr::create(document(), attribute->name(), attribute->value());
308
309 removeAttributeInternal(index, NotInSynchronizationOfLazyAttribute);
310 return attrNode.release();
311}
312
313void Element::removeAttribute(const QualifiedName& name)
314{
315 if (!elementData())
316 return;
317
318 size_t index = elementData()->getAttributeItemIndex(name);
319 if (index == notFound)
320 return;
321
322 removeAttributeInternal(index, NotInSynchronizationOfLazyAttribute);
323}
324
325void Element::setBooleanAttribute(const QualifiedName& name, bool value)
326{
327 if (value)
328 setAttribute(name, emptyAtom);
329 else
330 removeAttribute(name);
331}
332
333NamedNodeMap* Element::attributes() const
334{
335 ElementRareData* rareData = const_cast<Element*>(this)->ensureElementRareData();
336 if (NamedNodeMap* attributeMap = rareData->attributeMap())
337 return attributeMap;
338
339 rareData->setAttributeMap(NamedNodeMap::create(const_cast<Element*>(this)));
340 return rareData->attributeMap();
341}
342
343Node::NodeType Element::nodeType() const
344{
345 return ELEMENT_NODE;
346}
347
348bool Element::hasAttribute(const QualifiedName& name) const
349{
350 return hasAttributeNS(name.namespaceURI(), name.localName());
351}
352
353void Element::synchronizeAllAttributes() const
354{
355 if (!elementData())
356 return;
357 if (elementData()->m_styleAttributeIsDirty) {
358 ASSERT(isStyledElement());
359 static_cast<const StyledElement*>(this)->synchronizeStyleAttributeInternal();
360 }
361#if ENABLE(SVG)
362 if (elementData()->m_animatedSVGAttributesAreDirty) {
363 ASSERT(isSVGElement());
364 toSVGElement(this)->synchronizeAnimatedSVGAttribute(anyQName());
365 }
366#endif
367}
368
369inline void Element::synchronizeAttribute(const QualifiedName& name) const
370{
371 if (!elementData())
372 return;
373 if (UNLIKELY(name == styleAttr && elementData()->m_styleAttributeIsDirty)) {
374 ASSERT(isStyledElement());
375 static_cast<const StyledElement*>(this)->synchronizeStyleAttributeInternal();
376 return;
377 }
378#if ENABLE(SVG)
379 if (UNLIKELY(elementData()->m_animatedSVGAttributesAreDirty)) {
380 ASSERT(isSVGElement());
381 toSVGElement(this)->synchronizeAnimatedSVGAttribute(name);
382 }
383#endif
384}
385
386inline void Element::synchronizeAttribute(const AtomicString& localName) const
387{
388 // This version of synchronizeAttribute() is streamlined for the case where you don't have a full QualifiedName,
389 // e.g when called from DOM API.
390 if (!elementData())
391 return;
392 if (elementData()->m_styleAttributeIsDirty && equalPossiblyIgnoringCase(localName, styleAttr.localName(), shouldIgnoreAttributeCase(this))) {
393 ASSERT(isStyledElement());
394 static_cast<const StyledElement*>(this)->synchronizeStyleAttributeInternal();
395 return;
396 }
397#if ENABLE(SVG)
398 if (elementData()->m_animatedSVGAttributesAreDirty) {
399 // We're not passing a namespace argument on purpose. SVGNames::*Attr are defined w/o namespaces as well.
400 ASSERT(isSVGElement());
401 static_cast<const SVGElement*>(this)->synchronizeAnimatedSVGAttribute(QualifiedName(nullAtom, localName, nullAtom));
402 }
403#endif
404}
405
406const AtomicString& Element::getAttribute(const QualifiedName& name) const
407{
408 if (!elementData())
409 return nullAtom;
410 synchronizeAttribute(name);
411 if (const Attribute* attribute = getAttributeItem(name))
412 return attribute->value();
413 return nullAtom;
414}
415
416void Element::scrollIntoView(bool alignToTop)
417{
418 document()->updateLayoutIgnorePendingStylesheets();
419
420 if (!renderer())
421 return;
422
423 LayoutRect bounds = boundingBox();
424 // Align to the top / bottom and to the closest edge.
425 if (alignToTop)
426 renderer()->scrollRectToVisible(bounds, ScrollAlignment::alignToEdgeIfNeeded, ScrollAlignment::alignTopAlways);
427 else
428 renderer()->scrollRectToVisible(bounds, ScrollAlignment::alignToEdgeIfNeeded, ScrollAlignment::alignBottomAlways);
429}
430
431void Element::scrollIntoViewIfNeeded(bool centerIfNeeded)
432{
433 document()->updateLayoutIgnorePendingStylesheets();
434
435 if (!renderer())
436 return;
437
438 LayoutRect bounds = boundingBox();
439 if (centerIfNeeded)
440 renderer()->scrollRectToVisible(bounds, ScrollAlignment::alignCenterIfNeeded, ScrollAlignment::alignCenterIfNeeded);
441 else
442 renderer()->scrollRectToVisible(bounds, ScrollAlignment::alignToEdgeIfNeeded, ScrollAlignment::alignToEdgeIfNeeded);
443}
444
445void Element::scrollByUnits(int units, ScrollGranularity granularity)
446{
447 document()->updateLayoutIgnorePendingStylesheets();
448
449 if (!renderer())
450 return;
451
452 if (!renderer()->hasOverflowClip())
453 return;
454
455 ScrollDirection direction = ScrollDown;
456 if (units < 0) {
457 direction = ScrollUp;
458 units = -units;
459 }
460 Node* stopNode = this;
461 toRenderBox(renderer())->scroll(direction, granularity, units, &stopNode);
462}
463
464void Element::scrollByLines(int lines)
465{
466 scrollByUnits(lines, ScrollByLine);
467}
468
469void Element::scrollByPages(int pages)
470{
471 scrollByUnits(pages, ScrollByPage);
472}
473
474static float localZoomForRenderer(RenderObject* renderer)
475{
476 // FIXME: This does the wrong thing if two opposing zooms are in effect and canceled each
477 // other out, but the alternative is that we'd have to crawl up the whole render tree every
478 // time (or store an additional bit in the RenderStyle to indicate that a zoom was specified).
479 float zoomFactor = 1;
480 if (renderer->style()->effectiveZoom() != 1) {
481 // Need to find the nearest enclosing RenderObject that set up
482 // a differing zoom, and then we divide our result by it to eliminate the zoom.
483 RenderObject* prev = renderer;
484 for (RenderObject* curr = prev->parent(); curr; curr = curr->parent()) {
485 if (curr->style()->effectiveZoom() != prev->style()->effectiveZoom()) {
486 zoomFactor = prev->style()->zoom();
487 break;
488 }
489 prev = curr;
490 }
491 if (prev->isRenderView())
492 zoomFactor = prev->style()->zoom();
493 }
494 return zoomFactor;
495}
496
497static int adjustForLocalZoom(LayoutUnit value, RenderObject* renderer)
498{
499 float zoomFactor = localZoomForRenderer(renderer);
500 if (zoomFactor == 1)
501 return value;
502 return lroundf(value / zoomFactor);
503}
504
505int Element::offsetLeft()
506{
507 document()->updateLayoutIgnorePendingStylesheets();
508 if (RenderBoxModelObject* renderer = renderBoxModelObject())
509 return adjustForLocalZoom(renderer->pixelSnappedOffsetLeft(), renderer);
510 return 0;
511}
512
513int Element::offsetTop()
514{
515 document()->updateLayoutIgnorePendingStylesheets();
516 if (RenderBoxModelObject* renderer = renderBoxModelObject())
517 return adjustForLocalZoom(renderer->pixelSnappedOffsetTop(), renderer);
518 return 0;
519}
520
521int Element::offsetWidth()
522{
523 document()->updateLayoutIgnorePendingStylesheets();
524 if (RenderBoxModelObject* renderer = renderBoxModelObject())
525 return adjustLayoutUnitForAbsoluteZoom(renderer->pixelSnappedOffsetWidth(), renderer).round();
526 return 0;
527}
528
529int Element::offsetHeight()
530{
531 document()->updateLayoutIgnorePendingStylesheets();
532 if (RenderBoxModelObject* renderer = renderBoxModelObject())
533 return adjustLayoutUnitForAbsoluteZoom(renderer->pixelSnappedOffsetHeight(), renderer).round();
534 return 0;
535}
536
537Element* Element::bindingsOffsetParent()
538{
539 Element* element = offsetParent();
540 if (!element || !element->isInShadowTree())
541 return element;
542 return element->containingShadowRoot()->type() == ShadowRoot::UserAgentShadowRoot ? 0 : element;
543}
544
545Element* Element::offsetParent()
546{
547 document()->updateLayoutIgnorePendingStylesheets();
548 if (RenderObject* renderer = this->renderer())
549 return renderer->offsetParent();
550 return 0;
551}
552
553int Element::clientLeft()
554{
555 document()->updateLayoutIgnorePendingStylesheets();
556
557 if (RenderBox* renderer = renderBox())
558 return adjustForAbsoluteZoom(roundToInt(renderer->clientLeft()), renderer);
559 return 0;
560}
561
562int Element::clientTop()
563{
564 document()->updateLayoutIgnorePendingStylesheets();
565
566 if (RenderBox* renderer = renderBox())
567 return adjustForAbsoluteZoom(roundToInt(renderer->clientTop()), renderer);
568 return 0;
569}
570
571int Element::clientWidth()
572{
573 document()->updateLayoutIgnorePendingStylesheets();
574
575 // When in strict mode, clientWidth for the document element should return the width of the containing frame.
576 // When in quirks mode, clientWidth for the body element should return the width of the containing frame.
577 bool inQuirksMode = document()->inQuirksMode();
578 if ((!inQuirksMode && document()->documentElement() == this) ||
579 (inQuirksMode && isHTMLElement() && document()->body() == this)) {
580 if (FrameView* view = document()->view()) {
581 if (RenderView* renderView = document()->renderView())
582 return adjustForAbsoluteZoom(view->layoutWidth(), renderView);
583 }
584 }
585
586 if (RenderBox* renderer = renderBox())
587 return adjustLayoutUnitForAbsoluteZoom(renderer->pixelSnappedClientWidth(), renderer).round();
588 return 0;
589}
590
591int Element::clientHeight()
592{
593 document()->updateLayoutIgnorePendingStylesheets();
594
595 // When in strict mode, clientHeight for the document element should return the height of the containing frame.
596 // When in quirks mode, clientHeight for the body element should return the height of the containing frame.
597 bool inQuirksMode = document()->inQuirksMode();
598
599 if ((!inQuirksMode && document()->documentElement() == this) ||
600 (inQuirksMode && isHTMLElement() && document()->body() == this)) {
601 if (FrameView* view = document()->view()) {
602 if (RenderView* renderView = document()->renderView())
603 return adjustForAbsoluteZoom(view->layoutHeight(), renderView);
604 }
605 }
606
607 if (RenderBox* renderer = renderBox())
608 return adjustLayoutUnitForAbsoluteZoom(renderer->pixelSnappedClientHeight(), renderer).round();
609 return 0;
610}
611
612int Element::scrollLeft()
613{
614 document()->updateLayoutIgnorePendingStylesheets();
615 if (RenderBox* rend = renderBox())
616 return adjustForAbsoluteZoom(rend->scrollLeft(), rend);
617 return 0;
618}
619
620int Element::scrollTop()
621{
622 document()->updateLayoutIgnorePendingStylesheets();
623 if (RenderBox* rend = renderBox())
624 return adjustForAbsoluteZoom(rend->scrollTop(), rend);
625 return 0;
626}
627
628void Element::setScrollLeft(int newLeft)
629{
630 document()->updateLayoutIgnorePendingStylesheets();
631 if (RenderBox* rend = renderBox())
632 rend->setScrollLeft(static_cast<int>(newLeft * rend->style()->effectiveZoom()));
633}
634
635void Element::setScrollTop(int newTop)
636{
637 document()->updateLayoutIgnorePendingStylesheets();
638 if (RenderBox* rend = renderBox())
639 rend->setScrollTop(static_cast<int>(newTop * rend->style()->effectiveZoom()));
640}
641
642int Element::scrollWidth()
643{
644 document()->updateLayoutIgnorePendingStylesheets();
645 if (RenderBox* rend = renderBox())
646 return adjustForAbsoluteZoom(rend->scrollWidth(), rend);
647 return 0;
648}
649
650int Element::scrollHeight()
651{
652 document()->updateLayoutIgnorePendingStylesheets();
653 if (RenderBox* rend = renderBox())
654 return adjustForAbsoluteZoom(rend->scrollHeight(), rend);
655 return 0;
656}
657
658IntRect Element::boundsInRootViewSpace()
659{
660 document()->updateLayoutIgnorePendingStylesheets();
661
662 FrameView* view = document()->view();
663 if (!view)
664 return IntRect();
665
666 Vector<FloatQuad> quads;
667#if ENABLE(SVG)
668 if (isSVGElement() && renderer()) {
669 // Get the bounding rectangle from the SVG model.
670 SVGElement* svgElement = toSVGElement(this);
671 FloatRect localRect;
672 if (svgElement->getBoundingBox(localRect))
673 quads.append(renderer()->localToAbsoluteQuad(localRect));
674 } else
675#endif
676 {
677 // Get the bounding rectangle from the box model.
678 if (renderBoxModelObject())
679 renderBoxModelObject()->absoluteQuads(quads);
680 }
681
682 if (quads.isEmpty())
683 return IntRect();
684
685 IntRect result = quads[0].enclosingBoundingBox();
686 for (size_t i = 1; i < quads.size(); ++i)
687 result.unite(quads[i].enclosingBoundingBox());
688
689 result = view->contentsToRootView(result);
690 return result;
691}
692
693PassRefPtr<ClientRectList> Element::getClientRects()
694{
695 document()->updateLayoutIgnorePendingStylesheets();
696
697 RenderBoxModelObject* renderBoxModelObject = this->renderBoxModelObject();
698 if (!renderBoxModelObject)
699 return ClientRectList::create();
700
701 // FIXME: Handle SVG elements.
702 // FIXME: Handle table/inline-table with a caption.
703
704 Vector<FloatQuad> quads;
705 renderBoxModelObject->absoluteQuads(quads);
706 document()->adjustFloatQuadsForScrollAndAbsoluteZoom(quads, renderBoxModelObject);
707 return ClientRectList::create(quads);
708}
709
710PassRefPtr<ClientRect> Element::getBoundingClientRect()
711{
712 document()->updateLayoutIgnorePendingStylesheets();
713
714 Vector<FloatQuad> quads;
715#if ENABLE(SVG)
716 if (isSVGElement() && renderer() && !renderer()->isSVGRoot()) {
717 // Get the bounding rectangle from the SVG model.
718 SVGElement* svgElement = toSVGElement(this);
719 FloatRect localRect;
720 if (svgElement->getBoundingBox(localRect))
721 quads.append(renderer()->localToAbsoluteQuad(localRect));
722 } else
723#endif
724 {
725 // Get the bounding rectangle from the box model.
726 if (renderBoxModelObject())
727 renderBoxModelObject()->absoluteQuads(quads);
728 }
729
730 if (quads.isEmpty())
731 return ClientRect::create();
732
733 FloatRect result = quads[0].boundingBox();
734 for (size_t i = 1; i < quads.size(); ++i)
735 result.unite(quads[i].boundingBox());
736
737 document()->adjustFloatRectForScrollAndAbsoluteZoom(result, renderer());
738 return ClientRect::create(result);
739}
740
741IntRect Element::screenRect() const
742{
743 if (!renderer())
744 return IntRect();
745 // FIXME: this should probably respect transforms
746 return document()->view()->contentsToScreen(renderer()->absoluteBoundingBoxRectIgnoringTransforms());
747}
748
749const AtomicString& Element::getAttribute(const AtomicString& localName) const
750{
751 if (!elementData())
752 return nullAtom;
753 synchronizeAttribute(localName);
754 if (const Attribute* attribute = elementData()->getAttributeItem(localName, shouldIgnoreAttributeCase(this)))
755 return attribute->value();
756 return nullAtom;
757}
758
759const AtomicString& Element::getAttributeNS(const AtomicString& namespaceURI, const AtomicString& localName) const
760{
761 return getAttribute(QualifiedName(nullAtom, localName, namespaceURI));
762}
763
764void Element::setAttribute(const AtomicString& localName, const AtomicString& value, ExceptionCode& ec)
765{
766 if (!Document::isValidName(localName)) {
767 ec = INVALID_CHARACTER_ERR;
768 return;
769 }
770
771 synchronizeAttribute(localName);
772 const AtomicString& caseAdjustedLocalName = shouldIgnoreAttributeCase(this) ? localName.lower() : localName;
773
774 size_t index = elementData() ? elementData()->getAttributeItemIndex(caseAdjustedLocalName, false) : notFound;
775 const QualifiedName& qName = index != notFound ? attributeItem(index)->name() : QualifiedName(nullAtom, caseAdjustedLocalName, nullAtom);
776 setAttributeInternal(index, qName, value, NotInSynchronizationOfLazyAttribute);
777}
778
779void Element::setAttribute(const QualifiedName& name, const AtomicString& value)
780{
781 synchronizeAttribute(name);
782 size_t index = elementData() ? elementData()->getAttributeItemIndex(name) : notFound;
783 setAttributeInternal(index, name, value, NotInSynchronizationOfLazyAttribute);
784}
785
786void Element::setSynchronizedLazyAttribute(const QualifiedName& name, const AtomicString& value)
787{
788 size_t index = elementData() ? elementData()->getAttributeItemIndex(name) : notFound;
789 setAttributeInternal(index, name, value, InSynchronizationOfLazyAttribute);
790}
791
792inline void Element::setAttributeInternal(size_t index, const QualifiedName& name, const AtomicString& newValue, SynchronizationOfLazyAttribute inSynchronizationOfLazyAttribute)
793{
794 if (newValue.isNull()) {
795 if (index != notFound)
796 removeAttributeInternal(index, inSynchronizationOfLazyAttribute);
797 return;
798 }
799
800 if (index == notFound) {
801 addAttributeInternal(name, newValue, inSynchronizationOfLazyAttribute);
802 return;
803 }
804
805 if (!inSynchronizationOfLazyAttribute)
806 willModifyAttribute(name, attributeItem(index)->value(), newValue);
807
808 if (newValue != attributeItem(index)->value()) {
809 // If there is an Attr node hooked to this attribute, the Attr::setValue() call below
810 // will write into the ElementData.
811 // FIXME: Refactor this so it makes some sense.
812 if (RefPtr<Attr> attrNode = inSynchronizationOfLazyAttribute ? 0 : attrIfExists(name))
813 attrNode->setValue(newValue);
814 else
815 ensureUniqueElementData()->attributeItem(index)->setValue(newValue);
816 }
817
818 if (!inSynchronizationOfLazyAttribute)
819 didModifyAttribute(name, newValue);
820}
821
822static inline AtomicString makeIdForStyleResolution(const AtomicString& value, bool inQuirksMode)
823{
824 if (inQuirksMode)
825 return value.lower();
826 return value;
827}
828
829static bool checkNeedsStyleInvalidationForIdChange(const AtomicString& oldId, const AtomicString& newId, StyleResolver* styleResolver)
830{
831 ASSERT(newId != oldId);
832 if (!oldId.isEmpty() && styleResolver->hasSelectorForId(oldId))
833 return true;
834 if (!newId.isEmpty() && styleResolver->hasSelectorForId(newId))
835 return true;
836 return false;
837}
838
839void Element::attributeChanged(const QualifiedName& name, const AtomicString& newValue, AttributeModificationReason)
840{
841 if (ElementShadow* parentElementShadow = shadowOfParentForDistribution(this)) {
842 if (shouldInvalidateDistributionWhenAttributeChanged(parentElementShadow, name, newValue))
843 parentElementShadow->invalidateDistribution();
844 }
845
846 parseAttribute(name, newValue);
847
848 document()->incDOMTreeVersion();
849
850 StyleResolver* styleResolver = document()->styleResolverIfExists();
851 bool testShouldInvalidateStyle = attached() && styleResolver && styleChangeType() < FullStyleChange;
852 bool shouldInvalidateStyle = false;
853
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);
860 }
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();
867
868 invalidateNodeListCachesInAncestors(&name, this);
869
870 // If there is currently no StyleResolver, we can't be sure that this attribute change won't affect style.
871 shouldInvalidateStyle |= !styleResolver;
872
873 if (shouldInvalidateStyle)
874 setNeedsStyleRecalc();
875
876 if (AXObjectCache* cache = document()->existingAXObjectCache())
877 cache->handleAttributeChanged(name, this);
878}
879
880inline void Element::attributeChangedFromParserOrByCloning(const QualifiedName& name, const AtomicString& newValue, AttributeModificationReason reason)
881{
882 if (RuntimeEnabledFeatures::customDOMElementsEnabled() && name == isAttr) {
883 document()->ensureCustomElementRegistry()->didGiveTypeExtension(this, newValue);
884 }
885 attributeChanged(name, newValue, reason);
886}
887
888template <typename CharacterType>
889static inline bool classStringHasClassName(const CharacterType* characters, unsigned length)
890{
891 ASSERT(length > 0);
892
893 unsigned i = 0;
894 do {
895 if (isNotHTMLSpace(characters[i]))
896 break;
897 ++i;
898 } while (i < length);
899
900 return i < length;
901}
902
903static inline bool classStringHasClassName(const AtomicString& newClassString)
904{
905 unsigned length = newClassString.length();
906
907 if (!length)
908 return false;
909
910 if (newClassString.is8Bit())
911 return classStringHasClassName(newClassString.characters8(), length);
912 return classStringHasClassName(newClassString.characters16(), length);
913}
914
915template<typename Checker>
916static bool checkSelectorForClassChange(const SpaceSplitString& changedClasses, const Checker& checker)
917{
918 unsigned changedSize = changedClasses.size();
919 for (unsigned i = 0; i < changedSize; ++i) {
920 if (checker.hasSelectorForClass(changedClasses[i]))
921 return true;
922 }
923 return false;
924}
925
926template<typename Checker>
927static bool checkSelectorForClassChange(const SpaceSplitString& oldClasses, const SpaceSplitString& newClasses, const Checker& checker)
928{
929 unsigned oldSize = oldClasses.size();
930 if (!oldSize)
931 return checkSelectorForClassChange(newClasses, checker);
932 BitVector remainingClassBits;
933 remainingClassBits.ensureSize(oldSize);
934 // Class vectors tend to be very short. This is faster than using a hash table.
935 unsigned newSize = newClasses.size();
936 for (unsigned i = 0; i < newSize; ++i) {
937 for (unsigned j = 0; j < oldSize; ++j) {
938 if (newClasses[i] == oldClasses[j]) {
939 remainingClassBits.quickSet(j);
940 continue;
941 }
942 }
943 if (checker.hasSelectorForClass(newClasses[i]))
944 return true;
945 }
946 for (unsigned i = 0; i < oldSize; ++i) {
947 // If the bit is not set the the corresponding class has been removed.
948 if (remainingClassBits.quickGet(i))
949 continue;
950 if (checker.hasSelectorForClass(oldClasses[i]))
951 return true;
952 }
953 return false;
954}
955
956void Element::classAttributeChanged(const AtomicString& newClassString)
957{
958 StyleResolver* styleResolver = document()->styleResolverIfExists();
959 bool testShouldInvalidateStyle = attached() && styleResolver && styleChangeType() < FullStyleChange;
960 bool shouldInvalidateStyle = false;
961
962 if (classStringHasClassName(newClassString)) {
963 const bool shouldFoldCase = document()->inQuirksMode();
964 const SpaceSplitString oldClasses = elementData()->classNames();
965 elementData()->setClass(newClassString, shouldFoldCase);
966 const SpaceSplitString& newClasses = elementData()->classNames();
967 shouldInvalidateStyle = testShouldInvalidateStyle && checkSelectorForClassChange(oldClasses, newClasses, *styleResolver);
968 } else {
969 const SpaceSplitString& oldClasses = elementData()->classNames();
970 shouldInvalidateStyle = testShouldInvalidateStyle && checkSelectorForClassChange(oldClasses, *styleResolver);
971 elementData()->clearClass();
972 }
973
974 if (hasRareData())
975 elementRareData()->clearClassListValueForQuirksMode();
976
977 if (shouldInvalidateStyle)
978 setNeedsStyleRecalc();
979}
980
981bool Element::shouldInvalidateDistributionWhenAttributeChanged(ElementShadow* elementShadow, const QualifiedName& name, const AtomicString& newValue)
982{
983 ASSERT(elementShadow);
984 const SelectRuleFeatureSet& featureSet = elementShadow->distributor().ensureSelectFeatureSet(elementShadow);
985
986 if (isIdAttributeName(name)) {
987 AtomicString oldId = elementData()->idForStyleResolution();
988 AtomicString newId = makeIdForStyleResolution(newValue, document()->inQuirksMode());
989 if (newId != oldId) {
990 if (!oldId.isEmpty() && featureSet.hasSelectorForId(oldId))
991 return true;
992 if (!newId.isEmpty() && featureSet.hasSelectorForId(newId))
993 return true;
994 }
995 }
996
997 if (name == HTMLNames::classAttr) {
998 const AtomicString& newClassString = newValue;
999 if (classStringHasClassName(newClassString)) {
1000 const bool shouldFoldCase = document()->inQuirksMode();
1001 const SpaceSplitString& oldClasses = elementData()->classNames();
1002 const SpaceSplitString newClasses(newClassString, shouldFoldCase);
1003 if (checkSelectorForClassChange(oldClasses, newClasses, featureSet))
1004 return true;
1005 } else {
1006 const SpaceSplitString& oldClasses = elementData()->classNames();
1007 if (checkSelectorForClassChange(oldClasses, featureSet))
1008 return true;
1009 }
1010 }
1011
1012 return featureSet.hasSelectorForAttribute(name.localName());
1013}
1014
1015// Returns true is the given attribute is an event handler.
1016// We consider an event handler any attribute that begins with "on".
1017// It is a simple solution that has the advantage of not requiring any
1018// code or configuration change if a new event handler is defined.
1019
1020static inline bool isEventHandlerAttribute(const Attribute& attribute)
1021{
1022 return attribute.name().namespaceURI().isNull() && attribute.name().localName().startsWith("on");
1023}
1024
1025bool Element::isJavaScriptURLAttribute(const Attribute& attribute) const
1026{
1027 return isURLAttribute(attribute) && protocolIsJavaScript(stripLeadingAndTrailingHTMLSpaces(attribute.value()));
1028}
1029
1030void Element::stripScriptingAttributes(Vector<Attribute>& attributeVector) const
1031{
1032 size_t destination = 0;
1033 for (size_t source = 0; source < attributeVector.size(); ++source) {
1034 if (isEventHandlerAttribute(attributeVector[source])
1035 || isJavaScriptURLAttribute(attributeVector[source])
1036 || isHTMLContentAttribute(attributeVector[source]))
1037 continue;
1038
1039 if (source != destination)
1040 attributeVector[destination] = attributeVector[source];
1041
1042 ++destination;
1043 }
1044 attributeVector.shrink(destination);
1045}
1046
1047void Element::parserSetAttributes(const Vector<Attribute>& attributeVector)
1048{
1049 ASSERT(!inDocument());
1050 ASSERT(!parentNode());
1051 ASSERT(!m_elementData);
1052
1053 if (attributeVector.isEmpty())
1054 return;
1055
1056 if (document() && document()->sharedObjectPool())
1057 m_elementData = document()->sharedObjectPool()->cachedShareableElementDataWithAttributes(attributeVector);
1058 else
1059 m_elementData = ShareableElementData::createWithAttributes(attributeVector);
1060
1061 // Use attributeVector instead of m_elementData because attributeChanged might modify m_elementData.
1062 for (unsigned i = 0; i < attributeVector.size(); ++i)
1063 attributeChangedFromParserOrByCloning(attributeVector[i].name(), attributeVector[i].value(), ModifiedDirectly);
1064}
1065
1066bool Element::hasAttributes() const
1067{
1068 synchronizeAllAttributes();
1069 return elementData() && elementData()->length();
1070}
1071
1072bool Element::hasEquivalentAttributes(const Element* other) const
1073{
1074 synchronizeAllAttributes();
1075 other->synchronizeAllAttributes();
1076 if (elementData() == other->elementData())
1077 return true;
1078 if (elementData())
1079 return elementData()->isEquivalent(other->elementData());
1080 if (other->elementData())
1081 return other->elementData()->isEquivalent(elementData());
1082 return true;
1083}
1084
1085String Element::nodeName() const
1086{
1087 return m_tagName.toString();
1088}
1089
1090String Element::nodeNamePreservingCase() const
1091{
1092 return m_tagName.toString();
1093}
1094
1095void Element::setPrefix(const AtomicString& prefix, ExceptionCode& ec)
1096{
1097 ec = 0;
1098 checkSetPrefix(prefix, ec);
1099 if (ec)
1100 return;
1101
1102 m_tagName.setPrefix(prefix.isEmpty() ? AtomicString() : prefix);
1103}
1104
1105KURL Element::baseURI() const
1106{
1107 const AtomicString& baseAttribute = getAttribute(baseAttr);
1108 KURL base(KURL(), baseAttribute);
1109 if (!base.protocol().isEmpty())
1110 return base;
1111
1112 ContainerNode* parent = parentNode();
1113 if (!parent)
1114 return base;
1115
1116 const KURL& parentBase = parent->baseURI();
1117 if (parentBase.isNull())
1118 return base;
1119
1120 return KURL(parentBase, baseAttribute);
1121}
1122
1123const AtomicString& Element::imageSourceURL() const
1124{
1125 return getAttribute(srcAttr);
1126}
1127
1128bool Element::rendererIsNeeded(const NodeRenderingContext& context)
1129{
1130 return context.style()->display() != NONE;
1131}
1132
1133RenderObject* Element::createRenderer(RenderArena*, RenderStyle* style)
1134{
1135 return RenderObject::createObject(this, style);
1136}
1137
1138#if ENABLE(INPUT_MULTIPLE_FIELDS_UI)
1139bool Element::isDateTimeFieldElement() const
1140{
1141 return false;
1142}
1143#endif
1144
1145bool Element::wasChangedSinceLastFormControlChangeEvent() const
1146{
1147 return false;
1148}
1149
1150void Element::setChangedSinceLastFormControlChangeEvent(bool)
1151{
1152}
1153
1154bool Element::isDisabledFormControl() const
1155{
1156 // FIXME: disabled and inert are separate concepts in the spec, but now we treat them as the same.
1157 // For example, an inert, non-disabled form control should not be grayed out.
1158 if (isInert())
1159 return true;
1160 return false;
1161}
1162
1163bool Element::isInert() const
1164{
1165 Element* dialog = document()->activeModalDialog();
1166 return dialog && !containsIncludingShadowDOM(dialog) && !dialog->containsIncludingShadowDOM(this);
1167}
1168
1169Node::InsertionNotificationRequest Element::insertedInto(ContainerNode* insertionPoint)
1170{
1171 // need to do superclass processing first so inDocument() is true
1172 // by the time we reach updateId
1173 ContainerNode::insertedInto(insertionPoint);
1174
1175 if (containsFullScreenElement() && parentElement() && !parentElement()->containsFullScreenElement())
1176 setContainsFullScreenElementOnAncestorsCrossingFrameBoundaries(true);
1177
1178 if (Element* before = pseudoElement(BEFORE))
1179 before->insertedInto(insertionPoint);
1180
1181 if (Element* after = pseudoElement(AFTER))
1182 after->insertedInto(insertionPoint);
1183
1184 if (!insertionPoint->isInTreeScope())
1185 return InsertionDone;
1186
1187 if (hasRareData())
1188 elementRareData()->clearClassListValueForQuirksMode();
1189
1190 TreeScope* scope = insertionPoint->treeScope();
1191 if (scope != treeScope())
1192 return InsertionDone;
1193
1194 const AtomicString& idValue = getIdAttribute();
1195 if (!idValue.isNull())
1196 updateId(scope, nullAtom, idValue);
1197
1198 const AtomicString& nameValue = getNameAttribute();
1199 if (!nameValue.isNull())
1200 updateName(nullAtom, nameValue);
1201
1202 if (hasTagName(labelTag)) {
1203 if (scope->shouldCacheLabelsByForAttribute())
1204 updateLabel(scope, nullAtom, fastGetAttribute(forAttr));
1205 }
1206
1207 return InsertionDone;
1208}
1209
1210void Element::removedFrom(ContainerNode* insertionPoint)
1211{
1212#if ENABLE(SVG)
1213 bool wasInDocument = insertionPoint->document();
1214#endif
1215
1216 if (Element* before = pseudoElement(BEFORE))
1217 before->removedFrom(insertionPoint);
1218
1219 if (Element* after = pseudoElement(AFTER))
1220 after->removedFrom(insertionPoint);
1221
1222 document()->removeFromTopLayer(this);
1223 if (containsFullScreenElement())
1224 setContainsFullScreenElementOnAncestorsCrossingFrameBoundaries(false);
1225
1226 if (document()->page())
1227 document()->page()->pointerLockController()->elementRemoved(this);
1228
1229 setSavedLayerScrollOffset(IntSize());
1230
1231 if (insertionPoint->isInTreeScope() && treeScope() == document()) {
1232 const AtomicString& idValue = getIdAttribute();
1233 if (!idValue.isNull())
1234 updateId(insertionPoint->treeScope(), idValue, nullAtom);
1235
1236 const AtomicString& nameValue = getNameAttribute();
1237 if (!nameValue.isNull())
1238 updateName(nameValue, nullAtom);
1239
1240 if (hasTagName(labelTag)) {
1241 TreeScope* treeScope = insertionPoint->treeScope();
1242 if (treeScope->shouldCacheLabelsByForAttribute())
1243 updateLabel(treeScope, fastGetAttribute(forAttr), nullAtom);
1244 }
1245 }
1246
1247 ContainerNode::removedFrom(insertionPoint);
1248#if ENABLE(SVG)
1249 if (wasInDocument && hasPendingResources())
1250 document()->accessSVGExtensions()->removeElementFromPendingResources(this);
1251#endif
1252}
1253
1254void Element::createRendererIfNeeded()
1255{
1256 NodeRenderingContext(this).createRendererForElementIfNeeded();
1257}
1258
1259void Element::attach()
1260{
1261 PostAttachCallbackDisabler callbackDisabler(this);
1262 StyleResolverParentPusher parentPusher(this);
1263 WidgetHierarchyUpdatesSuspensionScope suspendWidgetHierarchyUpdates;
1264
1265 createRendererIfNeeded();
1266
1267 if (parentElement() && parentElement()->isInCanvasSubtree())
1268 setIsInCanvasSubtree(true);
1269
1270 createPseudoElementIfNeeded(BEFORE);
1271
1272 // When a shadow root exists, it does the work of attaching the children.
1273 if (ElementShadow* shadow = this->shadow()) {
1274 parentPusher.push();
1275 shadow->attach();
1276 } else if (firstChild())
1277 parentPusher.push();
1278
1279 ContainerNode::attach();
1280
1281 createPseudoElementIfNeeded(AFTER);
1282
1283 if (hasRareData()) {
1284 ElementRareData* data = elementRareData();
1285 if (data->needsFocusAppearanceUpdateSoonAfterAttach()) {
1286 if (isFocusable() && document()->focusedNode() == this)
1287 document()->updateFocusAppearanceSoon(false /* don't restore selection */);
1288 data->setNeedsFocusAppearanceUpdateSoonAfterAttach(false);
1289 }
1290 }
1291}
1292
1293void Element::unregisterNamedFlowContentNode()
1294{
1295 if (RuntimeEnabledFeatures::cssRegionsEnabled() && inNamedFlow() && document()->renderView())
1296 document()->renderView()->flowThreadController()->unregisterNamedFlowContentNode(this);
1297}
1298
1299void Element::detach()
1300{
1301 WidgetHierarchyUpdatesSuspensionScope suspendWidgetHierarchyUpdates;
1302 unregisterNamedFlowContentNode();
1303 cancelFocusAppearanceUpdate();
1304 if (hasRareData()) {
1305 ElementRareData* data = elementRareData();
1306 data->setPseudoElement(BEFORE, 0);
1307 data->setPseudoElement(AFTER, 0);
1308 data->setIsInCanvasSubtree(false);
1309 data->resetComputedStyle();
1310 data->resetDynamicRestyleObservations();
1311 }
1312
1313 if (ElementShadow* shadow = this->shadow()) {
1314 detachChildrenIfNeeded();
1315 shadow->detach();
1316 }
1317 ContainerNode::detach();
1318}
1319
1320bool Element::pseudoStyleCacheIsInvalid(const RenderStyle* currentStyle, RenderStyle* newStyle)
1321{
1322 ASSERT(currentStyle == renderStyle());
1323 ASSERT(renderer());
1324
1325 if (!currentStyle)
1326 return false;
1327
1328 const PseudoStyleCache* pseudoStyleCache = currentStyle->cachedPseudoStyles();
1329 if (!pseudoStyleCache)
1330 return false;
1331
1332 size_t cacheSize = pseudoStyleCache->size();
1333 for (size_t i = 0; i < cacheSize; ++i) {
1334 RefPtr<RenderStyle> newPseudoStyle;
1335 PseudoId pseudoId = pseudoStyleCache->at(i)->styleType();
1336 if (pseudoId == FIRST_LINE || pseudoId == FIRST_LINE_INHERITED)
1337 newPseudoStyle = renderer()->uncachedFirstLineStyle(newStyle);
1338 else
1339 newPseudoStyle = renderer()->getUncachedPseudoStyle(PseudoStyleRequest(pseudoId), newStyle, newStyle);
1340 if (!newPseudoStyle)
1341 return true;
1342 if (*newPseudoStyle != *pseudoStyleCache->at(i)) {
1343 if (pseudoId < FIRST_INTERNAL_PSEUDOID)
1344 newStyle->setHasPseudoStyle(pseudoId);
1345 newStyle->addCachedPseudoStyle(newPseudoStyle);
1346 if (pseudoId == FIRST_LINE || pseudoId == FIRST_LINE_INHERITED) {
1347 // FIXME: We should do an actual diff to determine whether a repaint vs. layout
1348 // is needed, but for now just assume a layout will be required. The diff code
1349 // in RenderObject::setStyle would need to be factored out so that it could be reused.
1350 renderer()->setNeedsLayoutAndPrefWidthsRecalc();
1351 }
1352 return true;
1353 }
1354 }
1355 return false;
1356}
1357
1358PassRefPtr<RenderStyle> Element::styleForRenderer()
1359{
1360 if (hasCustomStyleCallbacks()) {
1361 if (RefPtr<RenderStyle> style = customStyleForRenderer())
1362 return style.release();
1363 }
1364
1365 return document()->styleResolver()->styleForElement(this);
1366}
1367
1368void Element::recalcStyle(StyleChange change)
1369{
1370 if (hasCustomStyleCallbacks())
1371 willRecalcStyle(change);
1372
1373 // Ref currentStyle in case it would otherwise be deleted when setting the new style in the renderer.
1374 RefPtr<RenderStyle> currentStyle(renderStyle());
1375 bool hasParentStyle = parentNodeForRenderingAndStyle() ? static_cast<bool>(parentNodeForRenderingAndStyle()->renderStyle()) : false;
1376 bool hasDirectAdjacentRules = childrenAffectedByDirectAdjacentRules();
1377 bool hasIndirectAdjacentRules = childrenAffectedByForwardPositionalRules();
1378
1379 if ((change > NoChange || needsStyleRecalc())) {
1380 if (hasRareData())
1381 elementRareData()->resetComputedStyle();
1382 }
1383 if (hasParentStyle && (change >= Inherit || needsStyleRecalc())) {
1384 StyleChange localChange = Detach;
1385 RefPtr<RenderStyle> newStyle;
1386 if (currentStyle) {
1387 // FIXME: This still recalcs style twice when changing display types, but saves
1388 // us from recalcing twice when going from none -> anything else which is more
1389 // common, especially during lazy attach.
1390 newStyle = styleForRenderer();
1391 localChange = Node::diff(currentStyle.get(), newStyle.get(), document());
1392 }
1393 if (localChange == Detach) {
1394 // FIXME: The style gets computed twice by calling attach. We could do better if we passed the style along.
1395 reattach();
1396 // attach recalculates the style for all children. No need to do it twice.
1397 clearNeedsStyleRecalc();
1398 clearChildNeedsStyleRecalc();
1399
1400 if (hasCustomStyleCallbacks())
1401 didRecalcStyle(change);
1402 return;
1403 }
1404
1405 if (RenderObject* renderer = this->renderer()) {
1406 if (localChange != NoChange || pseudoStyleCacheIsInvalid(currentStyle.get(), newStyle.get()) || (change == Force && renderer->requiresForcedStyleRecalcPropagation()) || styleChangeType() == SyntheticStyleChange)
1407 renderer->setAnimatableStyle(newStyle.get());
1408 else if (needsStyleRecalc()) {
1409 // Although no change occurred, we use the new style so that the cousin style sharing code won't get
1410 // fooled into believing this style is the same.
1411 renderer->setStyleInternal(newStyle.get());
1412 }
1413 }
1414
1415 // 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
1416 // 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).
1417 if (document()->styleSheetCollection()->usesRemUnits() && document()->documentElement() == this && localChange != NoChange && currentStyle && newStyle && currentStyle->fontSize() != newStyle->fontSize()) {
1418 // Cached RenderStyles may depend on the re units.
1419 document()->styleResolver()->invalidateMatchedPropertiesCache();
1420 change = Force;
1421 }
1422
1423 if (change != Force) {
1424 if (styleChangeType() >= FullStyleChange)
1425 change = Force;
1426 else
1427 change = localChange;
1428 }
1429 }
1430 StyleResolverParentPusher parentPusher(this);
1431
1432 // FIXME: This does not care about sibling combinators. Will be necessary in XBL2 world.
1433 if (ElementShadow* shadow = this->shadow()) {
1434 if (shouldRecalcStyle(change, shadow)) {
1435 parentPusher.push();
1436 shadow->recalcStyle(change);
1437 }
1438 }
1439
1440 if (shouldRecalcStyle(change, this))
1441 updatePseudoElement(BEFORE, change);
1442
1443 // FIXME: This check is good enough for :hover + foo, but it is not good enough for :hover + foo + bar.
1444 // For now we will just worry about the common case, since it's a lot trickier to get the second case right
1445 // without doing way too much re-resolution.
1446 bool forceCheckOfNextElementSibling = false;
1447 bool forceCheckOfAnyElementSibling = false;
1448 for (Node *n = firstChild(); n; n = n->nextSibling()) {
1449 if (n->isTextNode()) {
1450 toText(n)->recalcTextStyle(change);
1451 continue;
1452 }
1453 if (!n->isElementNode())
1454 continue;
1455 Element* element = toElement(n);
1456 bool childRulesChanged = element->needsStyleRecalc() && element->styleChangeType() == FullStyleChange;
1457 if ((forceCheckOfNextElementSibling || forceCheckOfAnyElementSibling))
1458 element->setNeedsStyleRecalc();
1459 if (shouldRecalcStyle(change, element)) {
1460 parentPusher.push();
1461 element->recalcStyle(change);
1462 }
1463 forceCheckOfNextElementSibling = childRulesChanged && hasDirectAdjacentRules;
1464 forceCheckOfAnyElementSibling = forceCheckOfAnyElementSibling || (childRulesChanged && hasIndirectAdjacentRules);
1465 }
1466
1467 if (shouldRecalcStyle(change, this))
1468 updatePseudoElement(AFTER, change);
1469
1470 clearNeedsStyleRecalc();
1471 clearChildNeedsStyleRecalc();
1472
1473 if (hasCustomStyleCallbacks())
1474 didRecalcStyle(change);
1475 InspectorInstrumentation::didRecalculateStyleForElement(this);
1476}
1477
1478ElementShadow* Element::shadow() const
1479{
1480 return hasRareData() ? elementRareData()->shadow() : 0;
1481}
1482
1483ElementShadow* Element::ensureShadow()
1484{
1485 return ensureElementRareData()->ensureShadow();
1486}
1487
1488void Element::didAffectSelector(AffectedSelectorMask mask)
1489{
1490 setNeedsStyleRecalc();
1491 if (ElementShadow* elementShadow = shadowOfParentForDistribution(this))
1492 elementShadow->didAffectSelector(mask);
1493}
1494
1495PassRefPtr<ShadowRoot> Element::createShadowRoot(ExceptionCode& ec)
1496{
1497 if (alwaysCreateUserAgentShadowRoot())
1498 ensureUserAgentShadowRoot();
1499
1500 if (RuntimeEnabledFeatures::authorShadowDOMForAnyElementEnabled())
1501 return ensureShadow()->addShadowRoot(this, ShadowRoot::AuthorShadowRoot);
1502
1503 // Since some elements recreates shadow root dynamically, multiple shadow
1504 // subtrees won't work well in that element. Until they are fixed, we disable
1505 // adding author shadow root for them.
1506 if (!areAuthorShadowsAllowed()) {
1507 ec = HIERARCHY_REQUEST_ERR;
1508 return 0;
1509 }
1510 return ensureShadow()->addShadowRoot(this, ShadowRoot::AuthorShadowRoot);
1511}
1512
1513ShadowRoot* Element::shadowRoot() const
1514{
1515 ElementShadow* elementShadow = shadow();
1516 if (!elementShadow)
1517 return 0;
1518 ShadowRoot* shadowRoot = elementShadow->youngestShadowRoot();
1519 if (shadowRoot->type() == ShadowRoot::AuthorShadowRoot)
1520 return shadowRoot;
1521 return 0;
1522}
1523
1524ShadowRoot* Element::userAgentShadowRoot() const
1525{
1526 if (ElementShadow* elementShadow = shadow()) {
1527 if (ShadowRoot* shadowRoot = elementShadow->oldestShadowRoot()) {
1528 ASSERT(shadowRoot->type() == ShadowRoot::UserAgentShadowRoot);
1529 return shadowRoot;
1530 }
1531 }
1532
1533 return 0;
1534}
1535
1536ShadowRoot* Element::ensureUserAgentShadowRoot()
1537{
1538 if (ShadowRoot* shadowRoot = userAgentShadowRoot())
1539 return shadowRoot;
1540 ShadowRoot* shadowRoot = ensureShadow()->addShadowRoot(this, ShadowRoot::UserAgentShadowRoot);
1541 didAddUserAgentShadowRoot(shadowRoot);
1542 return shadowRoot;
1543}
1544
1545const AtomicString& Element::shadowPseudoId() const
1546{
1547 return pseudo();
1548}
1549
1550bool Element::childTypeAllowed(NodeType type) const
1551{
1552 switch (type) {
1553 case ELEMENT_NODE:
1554 case TEXT_NODE:
1555 case COMMENT_NODE:
1556 case PROCESSING_INSTRUCTION_NODE:
1557 case CDATA_SECTION_NODE:
1558 case ENTITY_REFERENCE_NODE:
1559 return true;
1560 default:
1561 break;
1562 }
1563 return false;
1564}
1565
1566static void checkForEmptyStyleChange(Element* element, RenderStyle* style)
1567{
1568 if (!style && !element->styleAffectedByEmpty())
1569 return;
1570
1571 if (!style || (element->styleAffectedByEmpty() && (!style->emptyState() || element->hasChildNodes())))
1572 element->setNeedsStyleRecalc();
1573}
1574
1575static void checkForSiblingStyleChanges(Element* e, RenderStyle* style, bool finishedParsingCallback,
1576 Node* beforeChange, Node* afterChange, int childCountDelta)
1577{
1578 // :empty selector.
1579 checkForEmptyStyleChange(e, style);
1580
1581 if (!style || (e->needsStyleRecalc() && e->childrenAffectedByPositionalRules()))
1582 return;
1583
1584 // :first-child. In the parser callback case, we don't have to check anything, since we were right the first time.
1585 // In the DOM case, we only need to do something if |afterChange| is not 0.
1586 // |afterChange| is 0 in the parser case, so it works out that we'll skip this block.
1587 if (e->childrenAffectedByFirstChildRules() && afterChange) {
1588 // Find our new first child.
1589 Node* newFirstChild = 0;
1590 for (newFirstChild = e->firstChild(); newFirstChild && !newFirstChild->isElementNode(); newFirstChild = newFirstChild->nextSibling()) {};
1591
1592 // Find the first element node following |afterChange|
1593 Node* firstElementAfterInsertion = 0;
1594 for (firstElementAfterInsertion = afterChange;
1595 firstElementAfterInsertion && !firstElementAfterInsertion->isElementNode();
1596 firstElementAfterInsertion = firstElementAfterInsertion->nextSibling()) {};
1597
1598 // This is the insert/append case.
1599 if (newFirstChild != firstElementAfterInsertion && firstElementAfterInsertion && firstElementAfterInsertion->attached() &&
1600 firstElementAfterInsertion->renderStyle() && firstElementAfterInsertion->renderStyle()->firstChildState())
1601 firstElementAfterInsertion->setNeedsStyleRecalc();
1602
1603 // We also have to handle node removal.
1604 if (childCountDelta < 0 && newFirstChild == firstElementAfterInsertion && newFirstChild && (!newFirstChild->renderStyle() || !newFirstChild->renderStyle()->firstChildState()))
1605 newFirstChild->setNeedsStyleRecalc();
1606 }
1607
1608 // :last-child. In the parser callback case, we don't have to check anything, since we were right the first time.
1609 // In the DOM case, we only need to do something if |afterChange| is not 0.
1610 if (e->childrenAffectedByLastChildRules() && beforeChange) {
1611 // Find our new last child.
1612 Node* newLastChild = 0;
1613 for (newLastChild = e->lastChild(); newLastChild && !newLastChild->isElementNode(); newLastChild = newLastChild->previousSibling()) {};
1614
1615 // Find the last element node going backwards from |beforeChange|
1616 Node* lastElementBeforeInsertion = 0;
1617 for (lastElementBeforeInsertion = beforeChange;
1618 lastElementBeforeInsertion && !lastElementBeforeInsertion->isElementNode();
1619 lastElementBeforeInsertion = lastElementBeforeInsertion->previousSibling()) {};
1620
1621 if (newLastChild != lastElementBeforeInsertion && lastElementBeforeInsertion && lastElementBeforeInsertion->attached() &&
1622 lastElementBeforeInsertion->renderStyle() && lastElementBeforeInsertion->renderStyle()->lastChildState())
1623 lastElementBeforeInsertion->setNeedsStyleRecalc();
1624
1625 // 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
1626 // to match now.
1627 if ((childCountDelta < 0 || finishedParsingCallback) && newLastChild == lastElementBeforeInsertion && newLastChild && (!newLastChild->renderStyle() || !newLastChild->renderStyle()->lastChildState()))
1628 newLastChild->setNeedsStyleRecalc();
1629 }
1630
1631 // The + selector. We need to invalidate the first element following the insertion point. It is the only possible element
1632 // that could be affected by this DOM change.
1633 if (e->childrenAffectedByDirectAdjacentRules() && afterChange) {
1634 Node* firstElementAfterInsertion = 0;
1635 for (firstElementAfterInsertion = afterChange;
1636 firstElementAfterInsertion && !firstElementAfterInsertion->isElementNode();
1637 firstElementAfterInsertion = firstElementAfterInsertion->nextSibling()) {};
1638 if (firstElementAfterInsertion && firstElementAfterInsertion->attached())
1639 firstElementAfterInsertion->setNeedsStyleRecalc();
1640 }
1641
1642 // Forward positional selectors include the ~ selector, nth-child, nth-of-type, first-of-type and only-of-type.
1643 // Backward positional selectors include nth-last-child, nth-last-of-type, last-of-type and only-of-type.
1644 // We have to invalidate everything following the insertion point in the forward case, and everything before the insertion point in the
1645 // backward case.
1646 // |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.
1647 // 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
1648 // here. recalcStyle will then force a walk of the children when it sees that this has happened.
1649 if ((e->childrenAffectedByForwardPositionalRules() && afterChange)
1650 || (e->childrenAffectedByBackwardPositionalRules() && beforeChange))
1651 e->setNeedsStyleRecalc();
1652}
1653
1654void Element::childrenChanged(bool changedByParser, Node* beforeChange, Node* afterChange, int childCountDelta)
1655{
1656 ContainerNode::childrenChanged(changedByParser, beforeChange, afterChange, childCountDelta);
1657 if (changedByParser)
1658 checkForEmptyStyleChange(this, renderStyle());
1659 else
1660 checkForSiblingStyleChanges(this, renderStyle(), false, beforeChange, afterChange, childCountDelta);
1661
1662 if (ElementShadow * shadow = this->shadow())
1663 shadow->invalidateDistribution();
1664}
1665
1666void Element::removeAllEventListeners()
1667{
1668 ContainerNode::removeAllEventListeners();
1669 if (ElementShadow* shadow = this->shadow())
1670 shadow->removeAllEventListeners();
1671}
1672
1673void Element::beginParsingChildren()
1674{
1675 clearIsParsingChildrenFinished();
1676 StyleResolver* styleResolver = document()->styleResolverIfExists();
1677 if (styleResolver && attached())
1678 styleResolver->pushParentElement(this);
1679}
1680
1681void Element::finishParsingChildren()
1682{
1683 ContainerNode::finishParsingChildren();
1684 setIsParsingChildrenFinished();
1685 checkForSiblingStyleChanges(this, renderStyle(), true, lastChild(), 0, 0);
1686 if (StyleResolver* styleResolver = document()->styleResolverIfExists())
1687 styleResolver->popParentElement(this);
1688}
1689
1690#ifndef NDEBUG
1691void Element::formatForDebugger(char* buffer, unsigned length) const
1692{
1693 StringBuilder result;
1694 String s;
1695
1696 result.append(nodeName());
1697
1698 s = getIdAttribute();
1699 if (s.length() > 0) {
1700 if (result.length() > 0)
1701 result.appendLiteral("; ");
1702 result.appendLiteral("id=");
1703 result.append(s);
1704 }
1705
1706 s = getAttribute(classAttr);
1707 if (s.length() > 0) {
1708 if (result.length() > 0)
1709 result.appendLiteral("; ");
1710 result.appendLiteral("class=");
1711 result.append(s);
1712 }
1713
1714 strncpy(buffer, result.toString().utf8().data(), length - 1);
1715}
1716#endif
1717
1718const Vector<RefPtr<Attr> >& Element::attrNodeList()
1719{
1720 ASSERT(hasSyntheticAttrChildNodes());
1721 return *attrNodeListForElement(this);
1722}
1723
1724PassRefPtr<Attr> Element::setAttributeNode(Attr* attrNode, ExceptionCode& ec)
1725{
1726 if (!attrNode) {
1727 ec = TYPE_MISMATCH_ERR;
1728 return 0;
1729 }
1730
1731 RefPtr<Attr> oldAttrNode = attrIfExists(attrNode->qualifiedName());
1732 if (oldAttrNode.get() == attrNode)
1733 return attrNode; // This Attr is already attached to the element.
1734
1735 // INUSE_ATTRIBUTE_ERR: Raised if node is an Attr that is already an attribute of another Element object.
1736 // The DOM user must explicitly clone Attr nodes to re-use them in other elements.
1737 if (attrNode->ownerElement()) {
1738 ec = INUSE_ATTRIBUTE_ERR;
1739 return 0;
1740 }
1741
1742 synchronizeAllAttributes();
1743 UniqueElementData* elementData = ensureUniqueElementData();
1744
1745 size_t index = elementData->getAttributeItemIndex(attrNode->qualifiedName());
1746 if (index != notFound) {
1747 if (oldAttrNode)
1748 detachAttrNodeFromElementWithValue(oldAttrNode.get(), elementData->attributeItem(index)->value());
1749 else
1750 oldAttrNode = Attr::create(document(), attrNode->qualifiedName(), elementData->attributeItem(index)->value());
1751 }
1752
1753 setAttributeInternal(index, attrNode->qualifiedName(), attrNode->value(), NotInSynchronizationOfLazyAttribute);
1754
1755 attrNode->attachToElement(this);
1756 ensureAttrNodeListForElement(this)->append(attrNode);
1757
1758 return oldAttrNode.release();
1759}
1760
1761PassRefPtr<Attr> Element::setAttributeNodeNS(Attr* attr, ExceptionCode& ec)
1762{
1763 return setAttributeNode(attr, ec);
1764}
1765
1766PassRefPtr<Attr> Element::removeAttributeNode(Attr* attr, ExceptionCode& ec)
1767{
1768 if (!attr) {
1769 ec = TYPE_MISMATCH_ERR;
1770 return 0;
1771 }
1772 if (attr->ownerElement() != this) {
1773 ec = NOT_FOUND_ERR;
1774 return 0;
1775 }
1776
1777 ASSERT(document() == attr->document());
1778
1779 synchronizeAttribute(attr->qualifiedName());
1780
1781 size_t index = elementData()->getAttributeItemIndex(attr->qualifiedName());
1782 if (index == notFound) {
1783 ec = NOT_FOUND_ERR;
1784 return 0;
1785 }
1786
1787 return detachAttribute(index);
1788}
1789
1790bool Element::parseAttributeName(QualifiedName& out, const AtomicString& namespaceURI, const AtomicString& qualifiedName, ExceptionCode& ec)
1791{
1792 String prefix, localName;
1793 if (!Document::parseQualifiedName(qualifiedName, prefix, localName, ec))
1794 return false;
1795 ASSERT(!ec);
1796
1797 QualifiedName qName(prefix, localName, namespaceURI);
1798
1799 if (!Document::hasValidNamespaceForAttributes(qName)) {
1800 ec = NAMESPACE_ERR;
1801 return false;
1802 }
1803
1804 out = qName;
1805 return true;
1806}
1807
1808void Element::setAttributeNS(const AtomicString& namespaceURI, const AtomicString& qualifiedName, const AtomicString& value, ExceptionCode& ec)
1809{
1810 QualifiedName parsedName = anyName;
1811 if (!parseAttributeName(parsedName, namespaceURI, qualifiedName, ec))
1812 return;
1813 setAttribute(parsedName, value);
1814}
1815
1816void Element::removeAttributeInternal(size_t index, SynchronizationOfLazyAttribute inSynchronizationOfLazyAttribute)
1817{
1818 ASSERT_WITH_SECURITY_IMPLICATION(index < attributeCount());
1819
1820 UniqueElementData* elementData = ensureUniqueElementData();
1821
1822 QualifiedName name = elementData->attributeItem(index)->name();
1823 AtomicString valueBeingRemoved = elementData->attributeItem(index)->value();
1824
1825 if (!inSynchronizationOfLazyAttribute) {
1826 if (!valueBeingRemoved.isNull())
1827 willModifyAttribute(name, valueBeingRemoved, nullAtom);
1828 }
1829
1830 if (RefPtr<Attr> attrNode = attrIfExists(name))
1831 detachAttrNodeFromElementWithValue(attrNode.get(), elementData->attributeItem(index)->value());
1832
1833 elementData->removeAttribute(index);
1834
1835 if (!inSynchronizationOfLazyAttribute)
1836 didRemoveAttribute(name);
1837}
1838
1839void Element::addAttributeInternal(const QualifiedName& name, const AtomicString& value, SynchronizationOfLazyAttribute inSynchronizationOfLazyAttribute)
1840{
1841 if (!inSynchronizationOfLazyAttribute)
1842 willModifyAttribute(name, nullAtom, value);
1843 ensureUniqueElementData()->addAttribute(name, value);
1844 if (!inSynchronizationOfLazyAttribute)
1845 didAddAttribute(name, value);
1846}
1847
1848void Element::removeAttribute(const AtomicString& name)
1849{
1850 if (!elementData())
1851 return;
1852
1853 AtomicString localName = shouldIgnoreAttributeCase(this) ? name.lower() : name;
1854 size_t index = elementData()->getAttributeItemIndex(localName, false);
1855 if (index == notFound) {
1856 if (UNLIKELY(localName == styleAttr) && elementData()->m_styleAttributeIsDirty && isStyledElement())
1857 static_cast<StyledElement*>(this)->removeAllInlineStyleProperties();
1858 return;
1859 }
1860
1861 removeAttributeInternal(index, NotInSynchronizationOfLazyAttribute);
1862}
1863
1864void Element::removeAttributeNS(const AtomicString& namespaceURI, const AtomicString& localName)
1865{
1866 removeAttribute(QualifiedName(nullAtom, localName, namespaceURI));
1867}
1868
1869PassRefPtr<Attr> Element::getAttributeNode(const AtomicString& localName)
1870{
1871 if (!elementData())
1872 return 0;
1873 synchronizeAttribute(localName);
1874 const Attribute* attribute = elementData()->getAttributeItem(localName, shouldIgnoreAttributeCase(this));
1875 if (!attribute)
1876 return 0;
1877 return ensureAttr(attribute->name());
1878}
1879
1880PassRefPtr<Attr> Element::getAttributeNodeNS(const AtomicString& namespaceURI, const AtomicString& localName)
1881{
1882 if (!elementData())
1883 return 0;
1884 QualifiedName qName(nullAtom, localName, namespaceURI);
1885 synchronizeAttribute(qName);
1886 const Attribute* attribute = elementData()->getAttributeItem(qName);
1887 if (!attribute)
1888 return 0;
1889 return ensureAttr(attribute->name());
1890}
1891
1892bool Element::hasAttribute(const AtomicString& localName) const
1893{
1894 if (!elementData())
1895 return false;
1896 synchronizeAttribute(localName);
1897 return elementData()->getAttributeItem(shouldIgnoreAttributeCase(this) ? localName.lower() : localName, false);
1898}
1899
1900bool Element::hasAttributeNS(const AtomicString& namespaceURI, const AtomicString& localName) const
1901{
1902 if (!elementData())
1903 return false;
1904 QualifiedName qName(nullAtom, localName, namespaceURI);
1905 synchronizeAttribute(qName);
1906 return elementData()->getAttributeItem(qName);
1907}
1908
1909CSSStyleDeclaration *Element::style()
1910{
1911 return 0;
1912}
1913
1914void Element::focus(bool restorePreviousSelection, FocusDirection direction)
1915{
1916 if (!inDocument())
1917 return;
1918
1919 Document* doc = document();
1920 if (doc->focusedNode() == this)
1921 return;
1922
1923 // If the stylesheets have already been loaded we can reliably check isFocusable.
1924 // If not, we continue and set the focused node on the focus controller below so
1925 // that it can be updated soon after attach.
1926 if (doc->haveStylesheetsLoaded()) {
1927 doc->updateLayoutIgnorePendingStylesheets();
1928 if (!isFocusable())
1929 return;
1930 }
1931
1932 if (!supportsFocus())
1933 return;
1934
1935 RefPtr<Node> protect;
1936 if (Page* page = doc->page()) {
1937 // Focus and change event handlers can cause us to lose our last ref.
1938 // If a focus event handler changes the focus to a different node it
1939 // does not make sense to continue and update appearence.
1940 protect = this;
1941 if (!page->focusController()->setFocusedNode(this, doc->frame(), direction))
1942 return;
1943 }
1944
1945 // Setting the focused node above might have invalidated the layout due to scripts.
1946 doc->updateLayoutIgnorePendingStylesheets();
1947
1948 if (!isFocusable()) {
1949 ensureElementRareData()->setNeedsFocusAppearanceUpdateSoonAfterAttach(true);
1950 return;
1951 }
1952
1953 cancelFocusAppearanceUpdate();
1954 updateFocusAppearance(restorePreviousSelection);
1955}
1956
1957void Element::updateFocusAppearance(bool /*restorePreviousSelection*/)
1958{
1959 if (isRootEditableElement()) {
1960 Frame* frame = document()->frame();
1961 if (!frame)
1962 return;
1963
1964 // When focusing an editable element in an iframe, don't reset the selection if it already contains a selection.
1965 if (this == frame->selection()->rootEditableElement())
1966 return;
1967
1968 // FIXME: We should restore the previous selection if there is one.
1969 VisibleSelection newSelection = VisibleSelection(firstPositionInOrBeforeNode(this), DOWNSTREAM);
1970
1971 if (frame->selection()->shouldChangeSelection(newSelection)) {
1972 frame->selection()->setSelection(newSelection);
1973 frame->selection()->revealSelection();
1974 }
1975 } else if (renderer() && !renderer()->isWidget())
1976 renderer()->scrollRectToVisible(boundingBox());
1977}
1978
1979void Element::blur()
1980{
1981 cancelFocusAppearanceUpdate();
1982 Document* doc = document();
1983 if (treeScope()->focusedNode() == this) {
1984 if (doc->frame())
1985 doc->frame()->page()->focusController()->setFocusedNode(0, doc->frame());
1986 else
1987 doc->setFocusedNode(0);
1988 }
1989}
1990
1991String Element::innerText()
1992{
1993 // We need to update layout, since plainText uses line boxes in the render tree.
1994 document()->updateLayoutIgnorePendingStylesheets();
1995
1996 if (!renderer())
1997 return textContent(true);
1998
1999 return plainText(rangeOfContents(const_cast<Element*>(this)).get());
2000}
2001
2002String Element::outerText()
2003{
2004 // Getting outerText is the same as getting innerText, only
2005 // setting is different. You would think this should get the plain
2006 // text for the outer range, but this is wrong, <br> for instance
2007 // would return different values for inner and outer text by such
2008 // a rule, but it doesn't in WinIE, and we want to match that.
2009 return innerText();
2010}
2011
2012String Element::title() const
2013{
2014 return String();
2015}
2016
2017const AtomicString& Element::pseudo() const
2018{
2019 return getAttribute(pseudoAttr);
2020}
2021
2022void Element::setPseudo(const AtomicString& value)
2023{
2024 setAttribute(pseudoAttr, value);
2025}
2026
2027LayoutSize Element::minimumSizeForResizing() const
2028{
2029 return hasRareData() ? elementRareData()->minimumSizeForResizing() : defaultMinimumSizeForResizing();
2030}
2031
2032void Element::setMinimumSizeForResizing(const LayoutSize& size)
2033{
2034 if (!hasRareData() && size == defaultMinimumSizeForResizing())
2035 return;
2036 ensureElementRareData()->setMinimumSizeForResizing(size);
2037}
2038
2039RenderStyle* Element::computedStyle(PseudoId pseudoElementSpecifier)
2040{
2041 if (PseudoElement* element = pseudoElement(pseudoElementSpecifier))
2042 return element->computedStyle();
2043
2044 // FIXME: Find and use the renderer from the pseudo element instead of the actual element so that the 'length'
2045 // properties, which are only known by the renderer because it did the layout, will be correct and so that the
2046 // values returned for the ":selection" pseudo-element will be correct.
2047 if (RenderStyle* usedStyle = renderStyle()) {
2048 if (pseudoElementSpecifier) {
2049 RenderStyle* cachedPseudoStyle = usedStyle->getCachedPseudoStyle(pseudoElementSpecifier);
2050 return cachedPseudoStyle ? cachedPseudoStyle : usedStyle;
2051 } else
2052 return usedStyle;
2053 }
2054
2055 if (!attached())
2056 // FIXME: Try to do better than this. Ensure that styleForElement() works for elements that are not in the
2057 // document tree and figure out when to destroy the computed style for such elements.
2058 return 0;
2059
2060 ElementRareData* data = ensureElementRareData();
2061 if (!data->computedStyle())
2062 data->setComputedStyle(document()->styleForElementIgnoringPendingStylesheets(this));
2063 return pseudoElementSpecifier ? data->computedStyle()->getCachedPseudoStyle(pseudoElementSpecifier) : data->computedStyle();
2064}
2065
2066void Element::setStyleAffectedByEmpty()
2067{
2068 ensureElementRareData()->setStyleAffectedByEmpty(true);
2069}
2070
2071void Element::setChildrenAffectedByHover(bool value)
2072{
2073 if (value || hasRareData())
2074 ensureElementRareData()->setChildrenAffectedByHover(value);
2075}
2076
2077void Element::setChildrenAffectedByActive(bool value)
2078{
2079 if (value || hasRareData())
2080 ensureElementRareData()->setChildrenAffectedByActive(value);
2081}
2082
2083void Element::setChildrenAffectedByDrag(bool value)
2084{
2085 if (value || hasRareData())
2086 ensureElementRareData()->setChildrenAffectedByDrag(value);
2087}
2088
2089void Element::setChildrenAffectedByFirstChildRules()
2090{
2091 ensureElementRareData()->setChildrenAffectedByFirstChildRules(true);
2092}
2093
2094void Element::setChildrenAffectedByLastChildRules()
2095{
2096 ensureElementRareData()->setChildrenAffectedByLastChildRules(true);
2097}
2098
2099void Element::setChildrenAffectedByDirectAdjacentRules()
2100{
2101 ensureElementRareData()->setChildrenAffectedByDirectAdjacentRules(true);
2102}
2103
2104void Element::setChildrenAffectedByForwardPositionalRules()
2105{
2106 ensureElementRareData()->setChildrenAffectedByForwardPositionalRules(true);
2107}
2108
2109void Element::setChildrenAffectedByBackwardPositionalRules()
2110{
2111 ensureElementRareData()->setChildrenAffectedByBackwardPositionalRules(true);
2112}
2113
2114void Element::setChildIndex(unsigned index)
2115{
2116 ElementRareData* rareData = ensureElementRareData();
2117 if (RenderStyle* style = renderStyle())
2118 style->setUnique();
2119 rareData->setChildIndex(index);
2120}
2121
2122bool Element::hasFlagsSetDuringStylingOfChildren() const
2123{
2124 if (!hasRareData())
2125 return false;
2126 return rareDataChildrenAffectedByHover()
2127 || rareDataChildrenAffectedByActive()
2128 || rareDataChildrenAffectedByDrag()
2129 || rareDataChildrenAffectedByFirstChildRules()
2130 || rareDataChildrenAffectedByLastChildRules()
2131 || rareDataChildrenAffectedByDirectAdjacentRules()
2132 || rareDataChildrenAffectedByForwardPositionalRules()
2133 || rareDataChildrenAffectedByBackwardPositionalRules();
2134}
2135
2136bool Element::rareDataStyleAffectedByEmpty() const
2137{
2138 ASSERT(hasRareData());
2139 return elementRareData()->styleAffectedByEmpty();
2140}
2141
2142bool Element::rareDataChildrenAffectedByHover() const
2143{
2144 ASSERT(hasRareData());
2145 return elementRareData()->childrenAffectedByHover();
2146}
2147
2148bool Element::rareDataChildrenAffectedByActive() const
2149{
2150 ASSERT(hasRareData());
2151 return elementRareData()->childrenAffectedByActive();
2152}
2153
2154bool Element::rareDataChildrenAffectedByDrag() const
2155{
2156 ASSERT(hasRareData());
2157 return elementRareData()->childrenAffectedByDrag();
2158}
2159
2160bool Element::rareDataChildrenAffectedByFirstChildRules() const
2161{
2162 ASSERT(hasRareData());
2163 return elementRareData()->childrenAffectedByFirstChildRules();
2164}
2165
2166bool Element::rareDataChildrenAffectedByLastChildRules() const
2167{
2168 ASSERT(hasRareData());
2169 return elementRareData()->childrenAffectedByLastChildRules();
2170}
2171
2172bool Element::rareDataChildrenAffectedByDirectAdjacentRules() const
2173{
2174 ASSERT(hasRareData());
2175 return elementRareData()->childrenAffectedByDirectAdjacentRules();
2176}
2177
2178bool Element::rareDataChildrenAffectedByForwardPositionalRules() const
2179{
2180 ASSERT(hasRareData());
2181 return elementRareData()->childrenAffectedByForwardPositionalRules();
2182}
2183
2184bool Element::rareDataChildrenAffectedByBackwardPositionalRules() const
2185{
2186 ASSERT(hasRareData());
2187 return elementRareData()->childrenAffectedByBackwardPositionalRules();
2188}
2189
2190unsigned Element::rareDataChildIndex() const
2191{
2192 ASSERT(hasRareData());
2193 return elementRareData()->childIndex();
2194}
2195
2196void Element::setIsInCanvasSubtree(bool isInCanvasSubtree)
2197{
2198 ensureElementRareData()->setIsInCanvasSubtree(isInCanvasSubtree);
2199}
2200
2201bool Element::isInCanvasSubtree() const
2202{
2203 return hasRareData() && elementRareData()->isInCanvasSubtree();
2204}
2205
2206bool Element::isUnresolvedCustomElement()
2207{
2208 return isCustomElement() && document()->registry()->isUnresolved(this);
2209}
2210
2211AtomicString Element::computeInheritedLanguage() const
2212{
2213 const Node* n = this;
2214 AtomicString value;
2215 // The language property is inherited, so we iterate over the parents to find the first language.
2216 do {
2217 if (n->isElementNode()) {
2218 if (const ElementData* elementData = toElement(n)->elementData()) {
2219 // Spec: xml:lang takes precedence -- http://www.w3.org/TR/xhtml1/#C_7
2220 if (const Attribute* attribute = elementData->getAttributeItem(XMLNames::langAttr))
2221 value = attribute->value();
2222 else if (const Attribute* attribute = elementData->getAttributeItem(HTMLNames::langAttr))
2223 value = attribute->value();
2224 }
2225 } else if (n->isDocumentNode()) {
2226 // checking the MIME content-language
2227 value = toDocument(n)->contentLanguage();
2228 }
2229
2230 n = n->parentNode();
2231 } while (n && value.isNull());
2232
2233 return value;
2234}
2235
2236Locale& Element::locale() const
2237{
2238 return document()->getCachedLocale(computeInheritedLanguage());
2239}
2240
2241void Element::cancelFocusAppearanceUpdate()
2242{
2243 if (hasRareData())
2244 elementRareData()->setNeedsFocusAppearanceUpdateSoonAfterAttach(false);
2245 if (document()->focusedNode() == this)
2246 document()->cancelFocusAppearanceUpdate();
2247}
2248
2249void Element::normalizeAttributes()
2250{
2251 if (!hasAttributes())
2252 return;
2253 for (unsigned i = 0; i < attributeCount(); ++i) {
2254 if (RefPtr<Attr> attr = attrIfExists(attributeItem(i)->name()))
2255 attr->normalize();
2256 }
2257}
2258
2259void Element::updatePseudoElement(PseudoId pseudoId, StyleChange change)
2260{
2261 PseudoElement* element = pseudoElement(pseudoId);
2262 if (element && (needsStyleRecalc() || shouldRecalcStyle(change, element))) {
2263 // PseudoElement styles hang off their parent element's style so if we needed
2264 // a style recalc we should Force one on the pseudo.
2265 element->recalcStyle(needsStyleRecalc() ? Force : change);
2266
2267 // Wait until our parent is not displayed or pseudoElementRendererIsNeeded
2268 // is false, otherwise we could continously create and destroy PseudoElements
2269 // when RenderObject::isChildAllowed on our parent returns false for the
2270 // PseudoElement's renderer for each style recalc.
2271 if (!renderer() || !pseudoElementRendererIsNeeded(renderer()->getCachedPseudoStyle(pseudoId)))
2272 setPseudoElement(pseudoId, 0);
2273 } else if (change >= Inherit || needsStyleRecalc())
2274 createPseudoElementIfNeeded(pseudoId);
2275}
2276
2277void Element::createPseudoElementIfNeeded(PseudoId pseudoId)
2278{
2279 if (!document()->styleSheetCollection()->usesBeforeAfterRules())
2280 return;
2281
2282 if (!renderer() || !pseudoElementRendererIsNeeded(renderer()->getCachedPseudoStyle(pseudoId)))
2283 return;
2284
2285 if (!renderer()->canHaveGeneratedChildren())
2286 return;
2287
2288 ASSERT(!isPseudoElement());
2289 RefPtr<PseudoElement> element = PseudoElement::create(this, pseudoId);
2290 element->attach();
2291 setPseudoElement(pseudoId, element.release());
2292}
2293
2294bool Element::hasPseudoElements() const
2295{
2296 return hasRareData() && elementRareData()->hasPseudoElements();
2297}
2298
2299PseudoElement* Element::pseudoElement(PseudoId pseudoId) const
2300{
2301 return hasRareData() ? elementRareData()->pseudoElement(pseudoId) : 0;
2302}
2303
2304void Element::setPseudoElement(PseudoId pseudoId, PassRefPtr<PseudoElement> element)
2305{
2306 ensureElementRareData()->setPseudoElement(pseudoId, element);
2307 resetNeedsShadowTreeWalker();
2308}
2309
2310RenderObject* Element::pseudoElementRenderer(PseudoId pseudoId) const
2311{
2312 if (PseudoElement* element = pseudoElement(pseudoId))
2313 return element->renderer();
2314 return 0;
2315}
2316
2317// ElementTraversal API
2318Element* Element::firstElementChild() const
2319{
2320 return ElementTraversal::firstWithin(this);
2321}
2322
2323Element* Element::lastElementChild() const
2324{
2325 Node* n = lastChild();
2326 while (n && !n->isElementNode())
2327 n = n->previousSibling();
2328 return toElement(n);
2329}
2330
2331unsigned Element::childElementCount() const
2332{
2333 unsigned count = 0;
2334 Node* n = firstChild();
2335 while (n) {
2336 count += n->isElementNode();
2337 n = n->nextSibling();
2338 }
2339 return count;
2340}
2341
2342bool Element::matchesReadOnlyPseudoClass() const
2343{
2344 return false;
2345}
2346
2347bool Element::matchesReadWritePseudoClass() const
2348{
2349 return false;
2350}
2351
2352bool Element::webkitMatchesSelector(const String& selector, ExceptionCode& ec)
2353{
2354 if (selector.isEmpty()) {
2355 ec = SYNTAX_ERR;
2356 return false;
2357 }
2358
2359 SelectorQuery* selectorQuery = document()->selectorQueryCache()->add(selector, document(), ec);
2360 if (!selectorQuery)
2361 return false;
2362 return selectorQuery->matches(this);
2363}
2364
2365bool Element::shouldAppearIndeterminate() const
2366{
2367 return false;
2368}
2369
2370DOMTokenList* Element::classList()
2371{
2372 ElementRareData* data = ensureElementRareData();
2373 if (!data->classList())
2374 data->setClassList(ClassList::create(this));
2375 return data->classList();
2376}
2377
2378DOMStringMap* Element::dataset()
2379{
2380 ElementRareData* data = ensureElementRareData();
2381 if (!data->dataset())
2382 data->setDataset(DatasetDOMStringMap::create(this));
2383 return data->dataset();
2384}
2385
2386KURL Element::getURLAttribute(const QualifiedName& name) const
2387{
2388#if !ASSERT_DISABLED
2389 if (elementData()) {
2390 if (const Attribute* attribute = getAttributeItem(name))
2391 ASSERT(isURLAttribute(*attribute));
2392 }
2393#endif
2394 return document()->completeURL(stripLeadingAndTrailingHTMLSpaces(getAttribute(name)));
2395}
2396
2397KURL Element::getNonEmptyURLAttribute(const QualifiedName& name) const
2398{
2399#if !ASSERT_DISABLED
2400 if (elementData()) {
2401 if (const Attribute* attribute = getAttributeItem(name))
2402 ASSERT(isURLAttribute(*attribute));
2403 }
2404#endif
2405 String value = stripLeadingAndTrailingHTMLSpaces(getAttribute(name));
2406 if (value.isEmpty())
2407 return KURL();
2408 return document()->completeURL(value);
2409}
2410
2411int Element::getIntegralAttribute(const QualifiedName& attributeName) const
2412{
2413 return getAttribute(attributeName).string().toInt();
2414}
2415
2416void Element::setIntegralAttribute(const QualifiedName& attributeName, int value)
2417{
2418 // FIXME: Need an AtomicString version of String::number.
2419 setAttribute(attributeName, String::number(value));
2420}
2421
2422unsigned Element::getUnsignedIntegralAttribute(const QualifiedName& attributeName) const
2423{
2424 return getAttribute(attributeName).string().toUInt();
2425}
2426
2427void Element::setUnsignedIntegralAttribute(const QualifiedName& attributeName, unsigned value)
2428{
2429 // FIXME: Need an AtomicString version of String::number.
2430 setAttribute(attributeName, String::number(value));
2431}
2432
2433#if ENABLE(SVG)
2434bool Element::childShouldCreateRenderer(const NodeRenderingContext& childContext) const
2435{
2436 // Only create renderers for SVG elements whose parents are SVG elements, or for proper <svg xmlns="svgNS"> subdocuments.
2437 if (childContext.node()->isSVGElement())
2438 return childContext.node()->hasTagName(SVGNames::svgTag) || isSVGElement();
2439
2440 return ContainerNode::childShouldCreateRenderer(childContext);
2441}
2442#endif
2443
2444void Element::webkitRequestFullscreen()
2445{
2446 document()->requestFullScreenForElement(this, ALLOW_KEYBOARD_INPUT, Document::EnforceIFrameAllowFullScreenRequirement);
2447}
2448
2449void Element::webkitRequestFullScreen(unsigned short flags)
2450{
2451 document()->requestFullScreenForElement(this, (flags | LEGACY_MOZILLA_REQUEST), Document::EnforceIFrameAllowFullScreenRequirement);
2452}
2453
2454bool Element::containsFullScreenElement() const
2455{
2456 return hasRareData() && elementRareData()->containsFullScreenElement();
2457}
2458
2459void Element::setContainsFullScreenElement(bool flag)
2460{
2461 ensureElementRareData()->setContainsFullScreenElement(flag);
2462 setNeedsStyleRecalc(SyntheticStyleChange);
2463}
2464
2465static Element* parentCrossingFrameBoundaries(Element* element)
2466{
2467 ASSERT(element);
2468 return element->parentElement() ? element->parentElement() : element->document()->ownerElement();
2469}
2470
2471void Element::setContainsFullScreenElementOnAncestorsCrossingFrameBoundaries(bool flag)
2472{
2473 Element* element = this;
2474 while ((element = parentCrossingFrameBoundaries(element)))
2475 element->setContainsFullScreenElement(flag);
2476}
2477
2478bool Element::isInTopLayer() const
2479{
2480 return hasRareData() && elementRareData()->isInTopLayer();
2481}
2482
2483void Element::setIsInTopLayer(bool inTopLayer)
2484{
2485 if (isInTopLayer() == inTopLayer)
2486 return;
2487 ensureElementRareData()->setIsInTopLayer(inTopLayer);
2488
2489 // We must ensure a reattach occurs so the renderer is inserted in the correct sibling order under RenderView according to its
2490 // top layer position, or in its usual place if not in the top layer.
2491 reattachIfAttached();
2492}
2493
2494void Element::webkitRequestPointerLock()
2495{
2496 if (document()->page())
2497 document()->page()->pointerLockController()->requestPointerLock(this);
2498}
2499
2500SpellcheckAttributeState Element::spellcheckAttributeState() const
2501{
2502 const AtomicString& value = getAttribute(HTMLNames::spellcheckAttr);
2503 if (value == nullAtom)
2504 return SpellcheckAttributeDefault;
2505 if (equalIgnoringCase(value, "true") || equalIgnoringCase(value, ""))
2506 return SpellcheckAttributeTrue;
2507 if (equalIgnoringCase(value, "false"))
2508 return SpellcheckAttributeFalse;
2509
2510 return SpellcheckAttributeDefault;
2511}
2512
2513bool Element::isSpellCheckingEnabled() const
2514{
2515 for (const Element* element = this; element; element = element->parentOrShadowHostElement()) {
2516 switch (element->spellcheckAttributeState()) {
2517 case SpellcheckAttributeTrue:
2518 return true;
2519 case SpellcheckAttributeFalse:
2520 return false;
2521 case SpellcheckAttributeDefault:
2522 break;
2523 }
2524 }
2525
2526 return true;
2527}
2528
2529RenderRegion* Element::renderRegion() const
2530{
2531 if (renderer() && renderer()->isRenderRegion())
2532 return toRenderRegion(renderer());
2533
2534 return 0;
2535}
2536
2537const AtomicString& Element::webkitRegionOverset() const
2538{
2539 document()->updateLayoutIgnorePendingStylesheets();
2540
2541 DEFINE_STATIC_LOCAL(AtomicString, undefinedState, ("undefined", AtomicString::ConstructFromLiteral));
2542 if (!RuntimeEnabledFeatures::cssRegionsEnabled() || !renderRegion())
2543 return undefinedState;
2544
2545 switch (renderRegion()->regionState()) {
2546 case RenderRegion::RegionFit: {
2547 DEFINE_STATIC_LOCAL(AtomicString, fitState, ("fit", AtomicString::ConstructFromLiteral));
2548 return fitState;
2549 }
2550 case RenderRegion::RegionEmpty: {
2551 DEFINE_STATIC_LOCAL(AtomicString, emptyState, ("empty", AtomicString::ConstructFromLiteral));
2552 return emptyState;
2553 }
2554 case RenderRegion::RegionOverset: {
2555 DEFINE_STATIC_LOCAL(AtomicString, overflowState, ("overset", AtomicString::ConstructFromLiteral));
2556 return overflowState;
2557 }
2558 case RenderRegion::RegionUndefined:
2559 return undefinedState;
2560 }
2561
2562 ASSERT_NOT_REACHED();
2563 return undefinedState;
2564}
2565
2566Vector<RefPtr<Range> > Element::webkitGetRegionFlowRanges() const
2567{
2568 document()->updateLayoutIgnorePendingStylesheets();
2569
2570 Vector<RefPtr<Range> > rangeObjects;
2571 if (RuntimeEnabledFeatures::cssRegionsEnabled() && renderer() && renderer()->isRenderRegion()) {
2572 RenderRegion* region = toRenderRegion(renderer());
2573 if (region->isValid())
2574 region->getRanges(rangeObjects);
2575 }
2576
2577 return rangeObjects;
2578}
2579
2580#ifndef NDEBUG
2581bool Element::fastAttributeLookupAllowed(const QualifiedName& name) const
2582{
2583 if (name == HTMLNames::styleAttr)
2584 return false;
2585
2586#if ENABLE(SVG)
2587 if (isSVGElement())
2588 return !static_cast<const SVGElement*>(this)->isAnimatableAttribute(name);
2589#endif
2590
2591 return true;
2592}
2593#endif
2594
2595#ifdef DUMP_NODE_STATISTICS
2596bool Element::hasNamedNodeMap() const
2597{
2598 return hasRareData() && elementRareData()->attributeMap();
2599}
2600#endif
2601
2602inline void Element::updateName(const AtomicString& oldName, const AtomicString& newName)
2603{
2604 if (!inDocument() || isInShadowTree())
2605 return;
2606
2607 if (oldName == newName)
2608 return;
2609
2610 if (shouldRegisterAsNamedItem())
2611 updateNamedItemRegistration(oldName, newName);
2612}
2613
2614inline void Element::updateId(const AtomicString& oldId, const AtomicString& newId)
2615{
2616 if (!isInTreeScope())
2617 return;
2618
2619 if (oldId == newId)
2620 return;
2621
2622 updateId(treeScope(), oldId, newId);
2623}
2624
2625inline void Element::updateId(TreeScope* scope, const AtomicString& oldId, const AtomicString& newId)
2626{
2627 ASSERT(isInTreeScope());
2628 ASSERT(oldId != newId);
2629
2630 if (!oldId.isEmpty())
2631 scope->removeElementById(oldId, this);
2632 if (!newId.isEmpty())
2633 scope->addElementById(newId, this);
2634
2635 if (shouldRegisterAsExtraNamedItem())
2636 updateExtraNamedItemRegistration(oldId, newId);
2637}
2638
2639void Element::updateLabel(TreeScope* scope, const AtomicString& oldForAttributeValue, const AtomicString& newForAttributeValue)
2640{
2641 ASSERT(hasTagName(labelTag));
2642
2643 if (!inDocument())
2644 return;
2645
2646 if (oldForAttributeValue == newForAttributeValue)
2647 return;
2648
2649 if (!oldForAttributeValue.isEmpty())
2650 scope->removeLabel(oldForAttributeValue, static_cast<HTMLLabelElement*>(this));
2651 if (!newForAttributeValue.isEmpty())
2652 scope->addLabel(newForAttributeValue, static_cast<HTMLLabelElement*>(this));
2653}
2654
2655void Element::willModifyAttribute(const QualifiedName& name, const AtomicString& oldValue, const AtomicString& newValue)
2656{
2657 if (isIdAttributeName(name))
2658 updateId(oldValue, newValue);
2659 else if (name == HTMLNames::nameAttr)
2660 updateName(oldValue, newValue);
2661 else if (name == HTMLNames::forAttr && hasTagName(labelTag)) {
2662 TreeScope* scope = treeScope();
2663 if (scope->shouldCacheLabelsByForAttribute())
2664 updateLabel(scope, oldValue, newValue);
2665 }
2666
2667 if (oldValue != newValue) {
2668 if (attached() && document()->styleResolver() && document()->styleResolver()->hasSelectorForAttribute(name.localName()))
2669 setNeedsStyleRecalc();
2670 }
2671
2672 if (OwnPtr<MutationObserverInterestGroup> recipients = MutationObserverInterestGroup::createForAttributesMutation(this, name))
2673 recipients->enqueueMutationRecord(MutationRecord::createAttributes(this, name, oldValue));
2674
2675 InspectorInstrumentation::willModifyDOMAttr(document(), this, oldValue, newValue);
2676}
2677
2678void Element::didAddAttribute(const QualifiedName& name, const AtomicString& value)
2679{
2680 attributeChanged(name, value);
2681 InspectorInstrumentation::didModifyDOMAttr(document(), this, name.localName(), value);
2682 dispatchSubtreeModifiedEvent();
2683}
2684
2685void Element::didModifyAttribute(const QualifiedName& name, const AtomicString& value)
2686{
2687 attributeChanged(name, value);
2688 InspectorInstrumentation::didModifyDOMAttr(document(), this, name.localName(), value);
2689 // Do not dispatch a DOMSubtreeModified event here; see bug 81141.
2690}
2691
2692void Element::didRemoveAttribute(const QualifiedName& name)
2693{
2694 attributeChanged(name, nullAtom);
2695 InspectorInstrumentation::didRemoveDOMAttr(document(), this, name.localName());
2696 dispatchSubtreeModifiedEvent();
2697}
2698
2699
2700void Element::updateNamedItemRegistration(const AtomicString& oldName, const AtomicString& newName)
2701{
2702 if (!document()->isHTMLDocument())
2703 return;
2704
2705 if (!oldName.isEmpty())
2706 toHTMLDocument(document())->removeNamedItem(oldName);
2707
2708 if (!newName.isEmpty())
2709 toHTMLDocument(document())->addNamedItem(newName);
2710}
2711
2712void Element::updateExtraNamedItemRegistration(const AtomicString& oldId, const AtomicString& newId)
2713{
2714 if (!document()->isHTMLDocument())
2715 return;
2716
2717 if (!oldId.isEmpty())
2718 toHTMLDocument(document())->removeExtraNamedItem(oldId);
2719
2720 if (!newId.isEmpty())
2721 toHTMLDocument(document())->addExtraNamedItem(newId);
2722}
2723
2724PassRefPtr<HTMLCollection> Element::ensureCachedHTMLCollection(CollectionType type)
2725{
2726 if (HTMLCollection* collection = cachedHTMLCollection(type))
2727 return collection;
2728
2729 RefPtr<HTMLCollection> collection;
2730 if (type == TableRows) {
2731 ASSERT(hasTagName(tableTag));
2732 return ensureRareData()->ensureNodeLists()->addCacheWithAtomicName<HTMLTableRowsCollection>(this, type);
2733 } else if (type == SelectOptions) {
2734 ASSERT(hasTagName(selectTag));
2735 return ensureRareData()->ensureNodeLists()->addCacheWithAtomicName<HTMLOptionsCollection>(this, type);
2736 } else if (type == FormControls) {
2737 ASSERT(hasTagName(formTag) || hasTagName(fieldsetTag));
2738 return ensureRareData()->ensureNodeLists()->addCacheWithAtomicName<HTMLFormControlsCollection>(this, type);
2739 }
2740 return ensureRareData()->ensureNodeLists()->addCacheWithAtomicName<HTMLCollection>(this, type);
2741}
2742
2743HTMLCollection* Element::cachedHTMLCollection(CollectionType type)
2744{
2745 return hasRareData() && rareData()->nodeLists() ? rareData()->nodeLists()->cacheWithAtomicName<HTMLCollection>(type) : 0;
2746}
2747
2748IntSize Element::savedLayerScrollOffset() const
2749{
2750 return hasRareData() ? elementRareData()->savedLayerScrollOffset() : IntSize();
2751}
2752
2753void Element::setSavedLayerScrollOffset(const IntSize& size)
2754{
2755 if (size.isZero() && !hasRareData())
2756 return;
2757 ensureElementRareData()->setSavedLayerScrollOffset(size);
2758}
2759
2760PassRefPtr<Attr> Element::attrIfExists(const QualifiedName& name)
2761{
2762 if (AttrNodeList* attrNodeList = attrNodeListForElement(this))
2763 return findAttrNodeInList(attrNodeList, name);
2764 return 0;
2765}
2766
2767PassRefPtr<Attr> Element::ensureAttr(const QualifiedName& name)
2768{
2769 AttrNodeList* attrNodeList = ensureAttrNodeListForElement(this);
2770 RefPtr<Attr> attrNode = findAttrNodeInList(attrNodeList, name);
2771 if (!attrNode) {
2772 attrNode = Attr::create(this, name);
2773 treeScope()->adoptIfNeeded(attrNode.get());
2774 attrNodeList->append(attrNode);
2775 }
2776 return attrNode.release();
2777}
2778
2779void Element::detachAttrNodeFromElementWithValue(Attr* attrNode, const AtomicString& value)
2780{
2781 ASSERT(hasSyntheticAttrChildNodes());
2782 attrNode->detachFromElementWithValue(value);
2783
2784 AttrNodeList* attrNodeList = attrNodeListForElement(this);
2785 for (unsigned i = 0; i < attrNodeList->size(); ++i) {
2786 if (attrNodeList->at(i)->qualifiedName() == attrNode->qualifiedName()) {
2787 attrNodeList->remove(i);
2788 if (attrNodeList->isEmpty())
2789 removeAttrNodeListForElement(this);
2790 return;
2791 }
2792 }
2793 ASSERT_NOT_REACHED();
2794}
2795
2796void Element::detachAllAttrNodesFromElement()
2797{
2798 AttrNodeList* attrNodeList = attrNodeListForElement(this);
2799 ASSERT(attrNodeList);
2800
2801 for (unsigned i = 0; i < attributeCount(); ++i) {
2802 const Attribute* attribute = attributeItem(i);
2803 if (RefPtr<Attr> attrNode = findAttrNodeInList(attrNodeList, attribute->name()))
2804 attrNode->detachFromElementWithValue(attribute->value());
2805 }
2806
2807 removeAttrNodeListForElement(this);
2808}
2809
2810void Element::willRecalcStyle(StyleChange)
2811{
2812 ASSERT(hasCustomStyleCallbacks());
2813}
2814
2815void Element::didRecalcStyle(StyleChange)
2816{
2817 ASSERT(hasCustomStyleCallbacks());
2818}
2819
2820
2821PassRefPtr<RenderStyle> Element::customStyleForRenderer()
2822{
2823 ASSERT(hasCustomStyleCallbacks());
2824 return 0;
2825}
2826
2827void Element::cloneAttributesFromElement(const Element& other)
2828{
2829 if (hasSyntheticAttrChildNodes())
2830 detachAllAttrNodesFromElement();
2831
2832 other.synchronizeAllAttributes();
2833 if (!other.m_elementData) {
2834 m_elementData.clear();
2835 return;
2836 }
2837
2838 const AtomicString& oldID = getIdAttribute();
2839 const AtomicString& newID = other.getIdAttribute();
2840
2841 if (!oldID.isNull() || !newID.isNull())
2842 updateId(oldID, newID);
2843
2844 const AtomicString& oldName = getNameAttribute();
2845 const AtomicString& newName = other.getNameAttribute();
2846
2847 if (!oldName.isNull() || !newName.isNull())
2848 updateName(oldName, newName);
2849
2850 // If 'other' has a mutable ElementData, convert it to an immutable one so we can share it between both elements.
2851 // We can only do this if there is no CSSOM wrapper for other's inline style, and there are no presentation attributes.
2852 if (other.m_elementData->isUnique()
2853 && !other.m_elementData->presentationAttributeStyle()
2854 && (!other.m_elementData->inlineStyle() || !other.m_elementData->inlineStyle()->hasCSSOMWrapper()))
2855 const_cast<Element&>(other).m_elementData = static_cast<const UniqueElementData*>(other.m_elementData.get())->makeShareableCopy();
2856
2857 if (!other.m_elementData->isUnique())
2858 m_elementData = other.m_elementData;
2859 else
2860 m_elementData = other.m_elementData->makeUniqueCopy();
2861
2862 for (unsigned i = 0; i < m_elementData->length(); ++i) {
2863 const Attribute* attribute = const_cast<const ElementData*>(m_elementData.get())->attributeItem(i);
2864 attributeChangedFromParserOrByCloning(attribute->name(), attribute->value(), ModifiedByCloning);
2865 }
2866}
2867
2868void Element::cloneDataFromElement(const Element& other)
2869{
2870 cloneAttributesFromElement(other);
2871 copyNonAttributePropertiesFromElement(other);
2872}
2873
2874void Element::createUniqueElementData()
2875{
2876 if (!m_elementData)
2877 m_elementData = UniqueElementData::create();
2878 else {
2879 ASSERT(!m_elementData->isUnique());
2880 m_elementData = static_cast<ShareableElementData*>(m_elementData.get())->makeUniqueCopy();
2881 }
2882}
2883
2884void Element::reportMemoryUsage(MemoryObjectInfo* memoryObjectInfo) const
2885{
2886 MemoryClassInfo info(memoryObjectInfo, this, WebCoreMemoryTypes::DOM);
2887 ContainerNode::reportMemoryUsage(memoryObjectInfo);
2888 info.addMember(m_tagName, "tagName");
2889 info.addMember(m_elementData, "elementData");
2890}
2891
2892#if ENABLE(SVG)
2893bool Element::hasPendingResources() const
2894{
2895 return hasRareData() && elementRareData()->hasPendingResources();
2896}
2897
2898void Element::setHasPendingResources()
2899{
2900 ensureElementRareData()->setHasPendingResources(true);
2901}
2902
2903void Element::clearHasPendingResources()
2904{
2905 ensureElementRareData()->setHasPendingResources(false);
2906}
2907#endif
2908
2909void ElementData::deref()
2910{
2911 if (!derefBase())
2912 return;
2913
2914 if (m_isUnique)
2915 delete static_cast<UniqueElementData*>(this);
2916 else
2917 delete static_cast<ShareableElementData*>(this);
2918}
2919
2920ElementData::ElementData()
2921 : m_isUnique(true)
2922 , m_arraySize(0)
2923 , m_presentationAttributeStyleIsDirty(false)
2924 , m_styleAttributeIsDirty(false)
2925#if ENABLE(SVG)
2926 , m_animatedSVGAttributesAreDirty(false)
2927#endif
2928{
2929}
2930
2931ElementData::ElementData(unsigned arraySize)
2932 : m_isUnique(false)
2933 , m_arraySize(arraySize)
2934 , m_presentationAttributeStyleIsDirty(false)
2935 , m_styleAttributeIsDirty(false)
2936#if ENABLE(SVG)
2937 , m_animatedSVGAttributesAreDirty(false)
2938#endif
2939{
2940}
2941
2942struct SameSizeAsElementData : public RefCounted<SameSizeAsElementData> {
2943 unsigned bitfield;
2944 void* refPtrs[3];
2945};
2946
2947COMPILE_ASSERT(sizeof(ElementData) == sizeof(SameSizeAsElementData), element_attribute_data_should_stay_small);
2948
2949static size_t sizeForShareableElementDataWithAttributeCount(unsigned count)
2950{
2951 return sizeof(ShareableElementData) + sizeof(Attribute) * count;
2952}
2953
2954PassRefPtr<ShareableElementData> ShareableElementData::createWithAttributes(const Vector<Attribute>& attributes)
2955{
2956 void* slot = WTF::fastMalloc(sizeForShareableElementDataWithAttributeCount(attributes.size()));
2957 return adoptRef(new (slot) ShareableElementData(attributes));
2958}
2959
2960PassRefPtr<UniqueElementData> UniqueElementData::create()
2961{
2962 return adoptRef(new UniqueElementData);
2963}
2964
2965ShareableElementData::ShareableElementData(const Vector<Attribute>& attributes)
2966 : ElementData(attributes.size())
2967{
2968 for (unsigned i = 0; i < m_arraySize; ++i)
2969 new (&m_attributeArray[i]) Attribute(attributes[i]);
2970}
2971
2972ShareableElementData::~ShareableElementData()
2973{
2974 for (unsigned i = 0; i < m_arraySize; ++i)
2975 m_attributeArray[i].~Attribute();
2976}
2977
2978ShareableElementData::ShareableElementData(const UniqueElementData& other)
2979 : ElementData(other, false)
2980{
2981 ASSERT(!other.m_presentationAttributeStyle);
2982
2983 if (other.m_inlineStyle) {
2984 ASSERT(!other.m_inlineStyle->hasCSSOMWrapper());
2985 m_inlineStyle = other.m_inlineStyle->immutableCopyIfNeeded();
2986 }
2987
2988 for (unsigned i = 0; i < m_arraySize; ++i)
2989 new (&m_attributeArray[i]) Attribute(other.m_attributeVector.at(i));
2990}
2991
2992ElementData::ElementData(const ElementData& other, bool isUnique)
2993 : m_isUnique(isUnique)
2994 , m_arraySize(isUnique ? 0 : other.length())
2995 , m_presentationAttributeStyleIsDirty(other.m_presentationAttributeStyleIsDirty)
2996 , m_styleAttributeIsDirty(other.m_styleAttributeIsDirty)
2997#if ENABLE(SVG)
2998 , m_animatedSVGAttributesAreDirty(other.m_animatedSVGAttributesAreDirty)
2999#endif
3000 , m_classNames(other.m_classNames)
3001 , m_idForStyleResolution(other.m_idForStyleResolution)
3002{
3003 // NOTE: The inline style is copied by the subclass copy constructor since we don't know what to do with it here.
3004}
3005
3006UniqueElementData::UniqueElementData()
3007{
3008}
3009
3010UniqueElementData::UniqueElementData(const UniqueElementData& other)
3011 : ElementData(other, true)
3012 , m_presentationAttributeStyle(other.m_presentationAttributeStyle)
3013 , m_attributeVector(other.m_attributeVector)
3014{
3015 m_inlineStyle = other.m_inlineStyle ? other.m_inlineStyle->copy() : 0;
3016}
3017
3018UniqueElementData::UniqueElementData(const ShareableElementData& other)
3019 : ElementData(other, true)
3020{
3021 // An ShareableElementData should never have a mutable inline StylePropertySet attached.
3022 ASSERT(!other.m_inlineStyle || !other.m_inlineStyle->isMutable());
3023 m_inlineStyle = other.m_inlineStyle;
3024
3025 m_attributeVector.reserveCapacity(other.length());
3026 for (unsigned i = 0; i < other.length(); ++i)
3027 m_attributeVector.uncheckedAppend(other.m_attributeArray[i]);
3028}
3029
3030PassRefPtr<UniqueElementData> ElementData::makeUniqueCopy() const
3031{
3032 if (isUnique())
3033 return adoptRef(new UniqueElementData(static_cast<const UniqueElementData&>(*this)));
3034 return adoptRef(new UniqueElementData(static_cast<const ShareableElementData&>(*this)));
3035}
3036
3037PassRefPtr<ShareableElementData> UniqueElementData::makeShareableCopy() const
3038{
3039 void* slot = WTF::fastMalloc(sizeForShareableElementDataWithAttributeCount(m_attributeVector.size()));
3040 return adoptRef(new (slot) ShareableElementData(*this));
3041}
3042
3043void UniqueElementData::addAttribute(const QualifiedName& attributeName, const AtomicString& value)
3044{
3045 m_attributeVector.append(Attribute(attributeName, value));
3046}
3047
3048void UniqueElementData::removeAttribute(size_t index)
3049{
3050 ASSERT_WITH_SECURITY_IMPLICATION(index < length());
3051 m_attributeVector.remove(index);
3052}
3053
3054bool ElementData::isEquivalent(const ElementData* other) const
3055{
3056 if (!other)
3057 return isEmpty();
3058
3059 unsigned len = length();
3060 if (len != other->length())
3061 return false;
3062
3063 for (unsigned i = 0; i < len; i++) {
3064 const Attribute* attribute = attributeItem(i);
3065 const Attribute* otherAttr = other->getAttributeItem(attribute->name());
3066 if (!otherAttr || attribute->value() != otherAttr->value())
3067 return false;
3068 }
3069
3070 return true;
3071}
3072
3073void ElementData::reportMemoryUsage(MemoryObjectInfo* memoryObjectInfo) const
3074{
3075 size_t actualSize = m_isUnique ? sizeof(ElementData) : sizeForShareableElementDataWithAttributeCount(m_arraySize);
3076 MemoryClassInfo info(memoryObjectInfo, this, WebCoreMemoryTypes::DOM, actualSize);
3077 info.addMember(m_inlineStyle, "inlineStyle");
3078 info.addMember(m_classNames, "classNames");
3079 info.addMember(m_idForStyleResolution, "idForStyleResolution");
3080 if (m_isUnique) {
3081 const UniqueElementData* uniqueThis = static_cast<const UniqueElementData*>(this);
3082 info.addMember(uniqueThis->m_presentationAttributeStyle, "presentationAttributeStyle");
3083 info.addMember(uniqueThis->m_attributeVector, "attributeVector");
3084 }
3085 for (unsigned i = 0, len = length(); i < len; i++)
3086 info.addMember(*attributeItem(i), "*attributeItem");
3087}
3088
3089size_t ElementData::getAttributeItemIndexSlowCase(const AtomicString& name, bool shouldIgnoreAttributeCase) const
3090{
3091 // Continue to checking case-insensitively and/or full namespaced names if necessary:
3092 for (unsigned i = 0; i < length(); ++i) {
3093 const Attribute* attribute = attributeItem(i);
3094 if (!attribute->name().hasPrefix()) {
3095 if (shouldIgnoreAttributeCase && equalIgnoringCase(name, attribute->localName()))
3096 return i;
3097 } else {
3098 // FIXME: Would be faster to do this comparison without calling toString, which
3099 // generates a temporary string by concatenation. But this branch is only reached
3100 // if the attribute name has a prefix, which is rare in HTML.
3101 if (equalPossiblyIgnoringCase(name, attribute->name().toString(), shouldIgnoreAttributeCase))
3102 return i;
3103 }
3104 }
3105 return notFound;
3106}
3107
3108Attribute* UniqueElementData::getAttributeItem(const QualifiedName& name)
3109{
3110 for (unsigned i = 0; i < length(); ++i) {
3111 if (m_attributeVector.at(i).name().matches(name))
3112 return &m_attributeVector.at(i);
3113 }
3114 return 0;
3115}
3116
3117Attribute* UniqueElementData::attributeItem(unsigned index)
3118{
3119 ASSERT_WITH_SECURITY_IMPLICATION(index < length());
3120 return &m_attributeVector.at(index);
3121}
3122
3123} // namespace WebCore