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