blob: ab2f94dce76f95422924a1d7662939e90a65c61a [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
Ben Murdoch591b9582013-07-10 11:41:44 +010029#include "CSSPropertyNames.h"
30#include "CSSValueKeywords.h"
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +010031#include "HTMLNames.h"
Torne (Richard Coles)93ac45c2013-05-29 14:40:20 +010032#include "SVGNames.h"
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +010033#include "XMLNames.h"
34#include "core/accessibility/AXObjectCache.h"
Ben Murdoch591b9582013-07-10 11:41:44 +010035#include "core/css/CSSParser.h"
36#include "core/css/CSSStyleSheet.h"
37#include "core/css/CSSValuePool.h"
38#include "core/css/PropertySetCSSStyleDeclaration.h"
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +010039#include "core/css/StylePropertySet.h"
Torne (Richard Coles)81a51572013-05-13 16:52:28 +010040#include "core/css/resolver/StyleResolver.h"
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +010041#include "core/dom/Attr.h"
Ben Murdoch591b9582013-07-10 11:41:44 +010042#include "core/dom/Attribute.h"
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +010043#include "core/dom/ClientRect.h"
44#include "core/dom/ClientRectList.h"
45#include "core/dom/CustomElementRegistry.h"
46#include "core/dom/DatasetDOMStringMap.h"
47#include "core/dom/Document.h"
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +010048#include "core/dom/DocumentSharedObjectPool.h"
49#include "core/dom/ElementRareData.h"
50#include "core/dom/ExceptionCode.h"
Torne (Richard Coles)521d96e2013-06-19 11:58:24 +010051#include "core/dom/FullscreenController.h"
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +010052#include "core/dom/MutationObserverInterestGroup.h"
53#include "core/dom/MutationRecord.h"
54#include "core/dom/NamedNodeMap.h"
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +010055#include "core/dom/NodeRenderStyle.h"
56#include "core/dom/NodeRenderingContext.h"
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +010057#include "core/dom/PseudoElement.h"
Ben Murdoch591b9582013-07-10 11:41:44 +010058#include "core/dom/ScriptableDocumentParser.h"
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +010059#include "core/dom/SelectorQuery.h"
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +010060#include "core/dom/Text.h"
61#include "core/dom/WebCoreMemoryInstrumentation.h"
Torne (Richard Coles)e5249552013-05-15 11:35:13 +010062#include "core/dom/shadow/InsertionPoint.h"
63#include "core/dom/shadow/ShadowRoot.h"
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +010064#include "core/editing/FrameSelection.h"
65#include "core/editing/TextIterator.h"
66#include "core/editing/htmlediting.h"
67#include "core/html/ClassList.h"
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +010068#include "core/html/HTMLCollection.h"
69#include "core/html/HTMLDocument.h"
70#include "core/html/HTMLElement.h"
71#include "core/html/HTMLFormControlsCollection.h"
72#include "core/html/HTMLFrameOwnerElement.h"
73#include "core/html/HTMLLabelElement.h"
74#include "core/html/HTMLOptionsCollection.h"
75#include "core/html/HTMLTableRowsCollection.h"
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +010076#include "core/html/parser/HTMLParserIdioms.h"
Ben Murdoch591b9582013-07-10 11:41:44 +010077#include "core/page/ContentSecurityPolicy.h"
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +010078#include "core/page/FocusController.h"
79#include "core/page/Frame.h"
80#include "core/page/FrameView.h"
81#include "core/page/Page.h"
82#include "core/page/PointerLockController.h"
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +010083#include "core/rendering/FlowThreadController.h"
84#include "core/rendering/RenderRegion.h"
85#include "core/rendering/RenderView.h"
86#include "core/rendering/RenderWidget.h"
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +010087#include "core/svg/SVGDocumentExtensions.h"
88#include "core/svg/SVGElement.h"
Torne (Richard Coles)93ac45c2013-05-29 14:40:20 +010089#include "wtf/BitVector.h"
Ben Murdoch591b9582013-07-10 11:41:44 +010090#include "wtf/HashFunctions.h"
Torne (Richard Coles)93ac45c2013-05-29 14:40:20 +010091#include "wtf/MemoryInstrumentationVector.h"
92#include "wtf/text/CString.h"
Ben Murdoch591b9582013-07-10 11:41:44 +010093#include "wtf/text/TextPosition.h"
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +010094
95namespace WebCore {
96
97using namespace HTMLNames;
98using namespace XMLNames;
99
100static inline bool shouldIgnoreAttributeCase(const Element* e)
101{
102 return e && e->document()->isHTMLDocument() && e->isHTMLElement();
103}
Ben Murdoch591b9582013-07-10 11:41:44 +0100104
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100105class StyleResolverParentPusher {
106public:
107 StyleResolverParentPusher(Element* parent)
108 : m_parent(parent)
109 , m_pushedStyleResolver(0)
110 {
111 }
112 void push()
113 {
114 if (m_pushedStyleResolver)
115 return;
116 m_pushedStyleResolver = m_parent->document()->styleResolver();
117 m_pushedStyleResolver->pushParentElement(m_parent);
118 }
119 ~StyleResolverParentPusher()
120 {
121
122 if (!m_pushedStyleResolver)
123 return;
124
125 // This tells us that our pushed style selector is in a bad state,
126 // so we should just bail out in that scenario.
127 ASSERT(m_pushedStyleResolver == m_parent->document()->styleResolver());
128 if (m_pushedStyleResolver != m_parent->document()->styleResolver())
129 return;
130
131 m_pushedStyleResolver->popParentElement(m_parent);
132 }
133
134private:
135 Element* m_parent;
136 StyleResolver* m_pushedStyleResolver;
137};
138
139typedef Vector<RefPtr<Attr> > AttrNodeList;
140typedef HashMap<Element*, OwnPtr<AttrNodeList> > AttrNodeListMap;
141
142static AttrNodeListMap& attrNodeListMap()
143{
144 DEFINE_STATIC_LOCAL(AttrNodeListMap, map, ());
145 return map;
146}
147
148static AttrNodeList* attrNodeListForElement(Element* element)
149{
150 if (!element->hasSyntheticAttrChildNodes())
151 return 0;
152 ASSERT(attrNodeListMap().contains(element));
153 return attrNodeListMap().get(element);
154}
155
156static AttrNodeList* ensureAttrNodeListForElement(Element* element)
157{
158 if (element->hasSyntheticAttrChildNodes()) {
159 ASSERT(attrNodeListMap().contains(element));
160 return attrNodeListMap().get(element);
161 }
162 ASSERT(!attrNodeListMap().contains(element));
163 element->setHasSyntheticAttrChildNodes(true);
164 AttrNodeListMap::AddResult result = attrNodeListMap().add(element, adoptPtr(new AttrNodeList));
165 return result.iterator->value.get();
166}
167
168static void removeAttrNodeListForElement(Element* element)
169{
170 ASSERT(element->hasSyntheticAttrChildNodes());
171 ASSERT(attrNodeListMap().contains(element));
172 attrNodeListMap().remove(element);
173 element->setHasSyntheticAttrChildNodes(false);
174}
175
176static Attr* findAttrNodeInList(AttrNodeList* attrNodeList, const QualifiedName& name)
177{
178 for (unsigned i = 0; i < attrNodeList->size(); ++i) {
179 if (attrNodeList->at(i)->qualifiedName() == name)
180 return attrNodeList->at(i).get();
181 }
182 return 0;
183}
184
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100185PassRefPtr<Element> Element::create(const QualifiedName& tagName, Document* document)
186{
187 return adoptRef(new Element(tagName, document, CreateElement));
188}
189
190Element::~Element()
191{
192#ifndef NDEBUG
193 if (document() && document()->renderer()) {
194 // When the document is not destroyed, an element that was part of a named flow
195 // content nodes should have been removed from the content nodes collection
196 // and the inNamedFlow flag reset.
197 ASSERT(!inNamedFlow());
198 }
199#endif
200
Ben Murdoch591b9582013-07-10 11:41:44 +0100201 if (PropertySetCSSStyleDeclaration* cssomWrapper = inlineStyleCSSOMWrapper())
202 cssomWrapper->clearParentElement();
203
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100204 if (hasRareData()) {
205 ElementRareData* data = elementRareData();
206 data->setPseudoElement(BEFORE, 0);
207 data->setPseudoElement(AFTER, 0);
208 data->clearShadow();
209 }
210
211 if (isCustomElement() && document() && document()->registry()) {
212 document()->registry()->customElementWasDestroyed(this);
213 }
214
215 if (hasSyntheticAttrChildNodes())
216 detachAllAttrNodesFromElement();
217
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100218 if (hasPendingResources()) {
219 document()->accessSVGExtensions()->removeElementFromPendingResources(this);
220 ASSERT(!hasPendingResources());
221 }
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100222}
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
Torne (Richard Coles)521d96e2013-06-19 11:58:24 +0100256bool Element::rendererIsFocusable() const
257{
258 // Elements in canvas fallback content are not rendered, but they are allowed to be
259 // focusable as long as their canvas is displayed and visible.
260 if (isInCanvasSubtree()) {
261 const Element* e = this;
262 while (e && !e->hasLocalName(canvasTag))
263 e = e->parentElement();
264 ASSERT(e);
265 return e->renderer() && e->renderer()->style()->visibility() == VISIBLE;
266 }
267
268 // FIXME: These asserts should be in Node::isFocusable, but there are some
269 // callsites like Document::setFocusedNode that would currently fail on
270 // them. See crbug.com/251163
271 if (renderer()) {
272 ASSERT(!renderer()->needsLayout());
273 } else {
274 // We can't just use needsStyleRecalc() because if the node is in a
275 // display:none tree it might say it needs style recalc but the whole
276 // document is actually up to date.
277 ASSERT(!document()->childNeedsStyleRecalc());
278 }
279
280 // FIXME: Even if we are not visible, we might have a child that is visible.
281 // Hyatt wants to fix that some day with a "has visible content" flag or the like.
282 if (!renderer() || renderer()->style()->visibility() != VISIBLE)
283 return false;
284
285 return true;
286}
287
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100288DEFINE_VIRTUAL_ATTRIBUTE_EVENT_LISTENER(Element, blur);
289DEFINE_VIRTUAL_ATTRIBUTE_EVENT_LISTENER(Element, error);
290DEFINE_VIRTUAL_ATTRIBUTE_EVENT_LISTENER(Element, focus);
291DEFINE_VIRTUAL_ATTRIBUTE_EVENT_LISTENER(Element, load);
292
293PassRefPtr<Node> Element::cloneNode(bool deep)
294{
295 return deep ? cloneElementWithChildren() : cloneElementWithoutChildren();
296}
297
298PassRefPtr<Element> Element::cloneElementWithChildren()
299{
300 RefPtr<Element> clone = cloneElementWithoutChildren();
301 cloneChildNodes(clone.get());
302 return clone.release();
303}
304
305PassRefPtr<Element> Element::cloneElementWithoutChildren()
306{
307 RefPtr<Element> clone = cloneElementWithoutAttributesAndChildren();
308 // This will catch HTML elements in the wrong namespace that are not correctly copied.
309 // This is a sanity check as HTML overloads some of the DOM methods.
310 ASSERT(isHTMLElement() == clone->isHTMLElement());
311
312 clone->cloneDataFromElement(*this);
313 return clone.release();
314}
315
316PassRefPtr<Element> Element::cloneElementWithoutAttributesAndChildren()
317{
318 return document()->createElement(tagQName(), false);
319}
320
321PassRefPtr<Attr> Element::detachAttribute(size_t index)
322{
323 ASSERT(elementData());
Torne (Richard Coles)e5249552013-05-15 11:35:13 +0100324 const Attribute* attribute = elementData()->attributeItem(index);
325 RefPtr<Attr> attrNode = attrIfExists(attribute->name());
326 if (attrNode)
327 detachAttrNodeAtIndex(attrNode.get(), index);
328 else {
329 attrNode = Attr::create(document(), attribute->name(), attribute->value());
330 removeAttributeInternal(index, NotInSynchronizationOfLazyAttribute);
331 }
332 return attrNode.release();
333}
334
335void Element::detachAttrNodeAtIndex(Attr* attr, size_t index)
336{
337 ASSERT(attr);
338 ASSERT(elementData());
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100339
340 const Attribute* attribute = elementData()->attributeItem(index);
341 ASSERT(attribute);
Torne (Richard Coles)e5249552013-05-15 11:35:13 +0100342 ASSERT(attribute->name() == attr->qualifiedName());
343 detachAttrNodeFromElementWithValue(attr, attribute->value());
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100344 removeAttributeInternal(index, NotInSynchronizationOfLazyAttribute);
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100345}
346
347void Element::removeAttribute(const QualifiedName& name)
348{
349 if (!elementData())
350 return;
351
352 size_t index = elementData()->getAttributeItemIndex(name);
353 if (index == notFound)
354 return;
355
356 removeAttributeInternal(index, NotInSynchronizationOfLazyAttribute);
357}
358
359void Element::setBooleanAttribute(const QualifiedName& name, bool value)
360{
361 if (value)
362 setAttribute(name, emptyAtom);
363 else
364 removeAttribute(name);
365}
366
367NamedNodeMap* Element::attributes() const
368{
369 ElementRareData* rareData = const_cast<Element*>(this)->ensureElementRareData();
370 if (NamedNodeMap* attributeMap = rareData->attributeMap())
371 return attributeMap;
372
373 rareData->setAttributeMap(NamedNodeMap::create(const_cast<Element*>(this)));
374 return rareData->attributeMap();
375}
376
Torne (Richard Coles)81a51572013-05-13 16:52:28 +0100377void Element::addActiveAnimation(Animation* animation)
378{
379 ElementRareData* rareData = ensureElementRareData();
380 if (!rareData->activeAnimations())
381 rareData->setActiveAnimations(adoptPtr(new Vector<Animation*>));
382 rareData->activeAnimations()->append(animation);
383}
384
385void Element::removeActiveAnimation(Animation* animation)
386{
387 ElementRareData* rareData = elementRareData();
388 ASSERT(rareData);
389 size_t position = rareData->activeAnimations()->find(animation);
390 ASSERT(position != notFound);
391 rareData->activeAnimations()->remove(position);
392}
393
394bool Element::hasActiveAnimations() const
395{
396 return hasRareData() && elementRareData()->activeAnimations()
397 && elementRareData()->activeAnimations()->size();
398}
399
400Vector<Animation*>* Element::activeAnimations() const
401{
402 if (!elementRareData())
403 return 0;
404 return elementRareData()->activeAnimations();
405}
406
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100407Node::NodeType Element::nodeType() const
408{
409 return ELEMENT_NODE;
410}
411
412bool Element::hasAttribute(const QualifiedName& name) const
413{
414 return hasAttributeNS(name.namespaceURI(), name.localName());
415}
416
417void Element::synchronizeAllAttributes() const
418{
419 if (!elementData())
420 return;
421 if (elementData()->m_styleAttributeIsDirty) {
422 ASSERT(isStyledElement());
Ben Murdoch591b9582013-07-10 11:41:44 +0100423 synchronizeStyleAttributeInternal();
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100424 }
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100425 if (elementData()->m_animatedSVGAttributesAreDirty) {
426 ASSERT(isSVGElement());
427 toSVGElement(this)->synchronizeAnimatedSVGAttribute(anyQName());
428 }
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100429}
430
431inline void Element::synchronizeAttribute(const QualifiedName& name) const
432{
433 if (!elementData())
434 return;
435 if (UNLIKELY(name == styleAttr && elementData()->m_styleAttributeIsDirty)) {
436 ASSERT(isStyledElement());
Ben Murdoch591b9582013-07-10 11:41:44 +0100437 synchronizeStyleAttributeInternal();
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100438 return;
439 }
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100440 if (UNLIKELY(elementData()->m_animatedSVGAttributesAreDirty)) {
441 ASSERT(isSVGElement());
442 toSVGElement(this)->synchronizeAnimatedSVGAttribute(name);
443 }
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100444}
445
446inline void Element::synchronizeAttribute(const AtomicString& localName) const
447{
448 // This version of synchronizeAttribute() is streamlined for the case where you don't have a full QualifiedName,
449 // e.g when called from DOM API.
450 if (!elementData())
451 return;
452 if (elementData()->m_styleAttributeIsDirty && equalPossiblyIgnoringCase(localName, styleAttr.localName(), shouldIgnoreAttributeCase(this))) {
453 ASSERT(isStyledElement());
Ben Murdoch591b9582013-07-10 11:41:44 +0100454 synchronizeStyleAttributeInternal();
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100455 return;
456 }
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100457 if (elementData()->m_animatedSVGAttributesAreDirty) {
458 // We're not passing a namespace argument on purpose. SVGNames::*Attr are defined w/o namespaces as well.
459 ASSERT(isSVGElement());
460 static_cast<const SVGElement*>(this)->synchronizeAnimatedSVGAttribute(QualifiedName(nullAtom, localName, nullAtom));
461 }
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100462}
463
464const AtomicString& Element::getAttribute(const QualifiedName& name) const
465{
466 if (!elementData())
467 return nullAtom;
468 synchronizeAttribute(name);
469 if (const Attribute* attribute = getAttributeItem(name))
470 return attribute->value();
471 return nullAtom;
472}
473
Ben Murdoch591b9582013-07-10 11:41:44 +0100474void Element::scrollIntoView(bool alignToTop)
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100475{
476 document()->updateLayoutIgnorePendingStylesheets();
477
478 if (!renderer())
479 return;
480
481 LayoutRect bounds = boundingBox();
482 // Align to the top / bottom and to the closest edge.
483 if (alignToTop)
484 renderer()->scrollRectToVisible(bounds, ScrollAlignment::alignToEdgeIfNeeded, ScrollAlignment::alignTopAlways);
485 else
486 renderer()->scrollRectToVisible(bounds, ScrollAlignment::alignToEdgeIfNeeded, ScrollAlignment::alignBottomAlways);
487}
488
489void Element::scrollIntoViewIfNeeded(bool centerIfNeeded)
490{
491 document()->updateLayoutIgnorePendingStylesheets();
492
493 if (!renderer())
494 return;
495
496 LayoutRect bounds = boundingBox();
497 if (centerIfNeeded)
498 renderer()->scrollRectToVisible(bounds, ScrollAlignment::alignCenterIfNeeded, ScrollAlignment::alignCenterIfNeeded);
499 else
500 renderer()->scrollRectToVisible(bounds, ScrollAlignment::alignToEdgeIfNeeded, ScrollAlignment::alignToEdgeIfNeeded);
501}
502
503void Element::scrollByUnits(int units, ScrollGranularity granularity)
504{
505 document()->updateLayoutIgnorePendingStylesheets();
506
507 if (!renderer())
508 return;
509
510 if (!renderer()->hasOverflowClip())
511 return;
512
513 ScrollDirection direction = ScrollDown;
514 if (units < 0) {
515 direction = ScrollUp;
516 units = -units;
517 }
518 Node* stopNode = this;
519 toRenderBox(renderer())->scroll(direction, granularity, units, &stopNode);
520}
521
522void Element::scrollByLines(int lines)
523{
524 scrollByUnits(lines, ScrollByLine);
525}
526
527void Element::scrollByPages(int pages)
528{
529 scrollByUnits(pages, ScrollByPage);
530}
531
532static float localZoomForRenderer(RenderObject* renderer)
533{
534 // FIXME: This does the wrong thing if two opposing zooms are in effect and canceled each
535 // other out, but the alternative is that we'd have to crawl up the whole render tree every
536 // time (or store an additional bit in the RenderStyle to indicate that a zoom was specified).
537 float zoomFactor = 1;
538 if (renderer->style()->effectiveZoom() != 1) {
539 // Need to find the nearest enclosing RenderObject that set up
540 // a differing zoom, and then we divide our result by it to eliminate the zoom.
541 RenderObject* prev = renderer;
542 for (RenderObject* curr = prev->parent(); curr; curr = curr->parent()) {
543 if (curr->style()->effectiveZoom() != prev->style()->effectiveZoom()) {
544 zoomFactor = prev->style()->zoom();
545 break;
546 }
547 prev = curr;
548 }
549 if (prev->isRenderView())
550 zoomFactor = prev->style()->zoom();
551 }
552 return zoomFactor;
553}
554
555static int adjustForLocalZoom(LayoutUnit value, RenderObject* renderer)
556{
557 float zoomFactor = localZoomForRenderer(renderer);
558 if (zoomFactor == 1)
559 return value;
560 return lroundf(value / zoomFactor);
561}
562
563int Element::offsetLeft()
564{
565 document()->updateLayoutIgnorePendingStylesheets();
566 if (RenderBoxModelObject* renderer = renderBoxModelObject())
567 return adjustForLocalZoom(renderer->pixelSnappedOffsetLeft(), renderer);
568 return 0;
569}
570
571int Element::offsetTop()
572{
573 document()->updateLayoutIgnorePendingStylesheets();
574 if (RenderBoxModelObject* renderer = renderBoxModelObject())
575 return adjustForLocalZoom(renderer->pixelSnappedOffsetTop(), renderer);
576 return 0;
577}
578
579int Element::offsetWidth()
580{
Ben Murdoch591b9582013-07-10 11:41:44 +0100581 document()->updateStyleForNodeIfNeeded(this);
582
583 if (RenderBox* renderer = renderBox()) {
584 if (!renderer->requiresLayoutToDetermineWidth())
585 return adjustLayoutUnitForAbsoluteZoom(renderer->fixedOffsetWidth(), renderer).round();
586 }
587
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100588 document()->updateLayoutIgnorePendingStylesheets();
589 if (RenderBoxModelObject* renderer = renderBoxModelObject())
590 return adjustLayoutUnitForAbsoluteZoom(renderer->pixelSnappedOffsetWidth(), renderer).round();
591 return 0;
592}
593
594int Element::offsetHeight()
595{
596 document()->updateLayoutIgnorePendingStylesheets();
597 if (RenderBoxModelObject* renderer = renderBoxModelObject())
598 return adjustLayoutUnitForAbsoluteZoom(renderer->pixelSnappedOffsetHeight(), renderer).round();
599 return 0;
600}
601
602Element* Element::bindingsOffsetParent()
603{
604 Element* element = offsetParent();
605 if (!element || !element->isInShadowTree())
606 return element;
Torne (Richard Coles)521d96e2013-06-19 11:58:24 +0100607 return element->containingShadowRoot()->shouldExposeToBindings() ? element : 0;
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100608}
609
610Element* Element::offsetParent()
611{
612 document()->updateLayoutIgnorePendingStylesheets();
613 if (RenderObject* renderer = this->renderer())
614 return renderer->offsetParent();
615 return 0;
616}
617
618int Element::clientLeft()
619{
620 document()->updateLayoutIgnorePendingStylesheets();
621
622 if (RenderBox* renderer = renderBox())
623 return adjustForAbsoluteZoom(roundToInt(renderer->clientLeft()), renderer);
624 return 0;
625}
626
627int Element::clientTop()
628{
629 document()->updateLayoutIgnorePendingStylesheets();
630
631 if (RenderBox* renderer = renderBox())
632 return adjustForAbsoluteZoom(roundToInt(renderer->clientTop()), renderer);
633 return 0;
634}
635
636int Element::clientWidth()
637{
638 document()->updateLayoutIgnorePendingStylesheets();
639
640 // When in strict mode, clientWidth for the document element should return the width of the containing frame.
641 // When in quirks mode, clientWidth for the body element should return the width of the containing frame.
642 bool inQuirksMode = document()->inQuirksMode();
643 if ((!inQuirksMode && document()->documentElement() == this) ||
644 (inQuirksMode && isHTMLElement() && document()->body() == this)) {
645 if (FrameView* view = document()->view()) {
646 if (RenderView* renderView = document()->renderView())
647 return adjustForAbsoluteZoom(view->layoutWidth(), renderView);
648 }
649 }
Ben Murdoch591b9582013-07-10 11:41:44 +0100650
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100651 if (RenderBox* renderer = renderBox())
652 return adjustLayoutUnitForAbsoluteZoom(renderer->pixelSnappedClientWidth(), renderer).round();
653 return 0;
654}
655
656int Element::clientHeight()
657{
658 document()->updateLayoutIgnorePendingStylesheets();
659
660 // When in strict mode, clientHeight for the document element should return the height of the containing frame.
661 // When in quirks mode, clientHeight for the body element should return the height of the containing frame.
Ben Murdoch591b9582013-07-10 11:41:44 +0100662 bool inQuirksMode = document()->inQuirksMode();
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100663
664 if ((!inQuirksMode && document()->documentElement() == this) ||
665 (inQuirksMode && isHTMLElement() && document()->body() == this)) {
666 if (FrameView* view = document()->view()) {
667 if (RenderView* renderView = document()->renderView())
668 return adjustForAbsoluteZoom(view->layoutHeight(), renderView);
669 }
670 }
Ben Murdoch591b9582013-07-10 11:41:44 +0100671
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100672 if (RenderBox* renderer = renderBox())
673 return adjustLayoutUnitForAbsoluteZoom(renderer->pixelSnappedClientHeight(), renderer).round();
674 return 0;
675}
676
677int Element::scrollLeft()
678{
679 document()->updateLayoutIgnorePendingStylesheets();
680 if (RenderBox* rend = renderBox())
681 return adjustForAbsoluteZoom(rend->scrollLeft(), rend);
682 return 0;
683}
684
685int Element::scrollTop()
686{
687 document()->updateLayoutIgnorePendingStylesheets();
688 if (RenderBox* rend = renderBox())
689 return adjustForAbsoluteZoom(rend->scrollTop(), rend);
690 return 0;
691}
692
693void Element::setScrollLeft(int newLeft)
694{
695 document()->updateLayoutIgnorePendingStylesheets();
696 if (RenderBox* rend = renderBox())
697 rend->setScrollLeft(static_cast<int>(newLeft * rend->style()->effectiveZoom()));
698}
699
700void Element::setScrollTop(int newTop)
701{
702 document()->updateLayoutIgnorePendingStylesheets();
703 if (RenderBox* rend = renderBox())
704 rend->setScrollTop(static_cast<int>(newTop * rend->style()->effectiveZoom()));
705}
706
707int Element::scrollWidth()
708{
709 document()->updateLayoutIgnorePendingStylesheets();
710 if (RenderBox* rend = renderBox())
711 return adjustForAbsoluteZoom(rend->scrollWidth(), rend);
712 return 0;
713}
714
715int Element::scrollHeight()
716{
717 document()->updateLayoutIgnorePendingStylesheets();
718 if (RenderBox* rend = renderBox())
719 return adjustForAbsoluteZoom(rend->scrollHeight(), rend);
720 return 0;
721}
722
723IntRect Element::boundsInRootViewSpace()
724{
725 document()->updateLayoutIgnorePendingStylesheets();
726
727 FrameView* view = document()->view();
728 if (!view)
729 return IntRect();
730
731 Vector<FloatQuad> quads;
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100732 if (isSVGElement() && renderer()) {
733 // Get the bounding rectangle from the SVG model.
734 SVGElement* svgElement = toSVGElement(this);
735 FloatRect localRect;
736 if (svgElement->getBoundingBox(localRect))
737 quads.append(renderer()->localToAbsoluteQuad(localRect));
Torne (Richard Coles)93ac45c2013-05-29 14:40:20 +0100738 } else {
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100739 // Get the bounding rectangle from the box model.
740 if (renderBoxModelObject())
741 renderBoxModelObject()->absoluteQuads(quads);
742 }
743
744 if (quads.isEmpty())
745 return IntRect();
746
747 IntRect result = quads[0].enclosingBoundingBox();
748 for (size_t i = 1; i < quads.size(); ++i)
749 result.unite(quads[i].enclosingBoundingBox());
750
751 result = view->contentsToRootView(result);
752 return result;
753}
754
755PassRefPtr<ClientRectList> Element::getClientRects()
756{
757 document()->updateLayoutIgnorePendingStylesheets();
758
759 RenderBoxModelObject* renderBoxModelObject = this->renderBoxModelObject();
760 if (!renderBoxModelObject)
761 return ClientRectList::create();
762
763 // FIXME: Handle SVG elements.
764 // FIXME: Handle table/inline-table with a caption.
765
766 Vector<FloatQuad> quads;
767 renderBoxModelObject->absoluteQuads(quads);
768 document()->adjustFloatQuadsForScrollAndAbsoluteZoom(quads, renderBoxModelObject);
769 return ClientRectList::create(quads);
770}
771
772PassRefPtr<ClientRect> Element::getBoundingClientRect()
773{
774 document()->updateLayoutIgnorePendingStylesheets();
775
776 Vector<FloatQuad> quads;
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100777 if (isSVGElement() && renderer() && !renderer()->isSVGRoot()) {
778 // Get the bounding rectangle from the SVG model.
779 SVGElement* svgElement = toSVGElement(this);
780 FloatRect localRect;
781 if (svgElement->getBoundingBox(localRect))
782 quads.append(renderer()->localToAbsoluteQuad(localRect));
Torne (Richard Coles)93ac45c2013-05-29 14:40:20 +0100783 } else {
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100784 // Get the bounding rectangle from the box model.
785 if (renderBoxModelObject())
786 renderBoxModelObject()->absoluteQuads(quads);
787 }
788
789 if (quads.isEmpty())
790 return ClientRect::create();
791
792 FloatRect result = quads[0].boundingBox();
793 for (size_t i = 1; i < quads.size(); ++i)
794 result.unite(quads[i].boundingBox());
795
796 document()->adjustFloatRectForScrollAndAbsoluteZoom(result, renderer());
797 return ClientRect::create(result);
798}
Ben Murdoch591b9582013-07-10 11:41:44 +0100799
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100800IntRect Element::screenRect() const
801{
802 if (!renderer())
803 return IntRect();
804 // FIXME: this should probably respect transforms
805 return document()->view()->contentsToScreen(renderer()->absoluteBoundingBoxRectIgnoringTransforms());
806}
807
808const AtomicString& Element::getAttribute(const AtomicString& localName) const
809{
810 if (!elementData())
811 return nullAtom;
812 synchronizeAttribute(localName);
813 if (const Attribute* attribute = elementData()->getAttributeItem(localName, shouldIgnoreAttributeCase(this)))
814 return attribute->value();
815 return nullAtom;
816}
817
818const AtomicString& Element::getAttributeNS(const AtomicString& namespaceURI, const AtomicString& localName) const
819{
820 return getAttribute(QualifiedName(nullAtom, localName, namespaceURI));
821}
822
823void Element::setAttribute(const AtomicString& localName, const AtomicString& value, ExceptionCode& ec)
824{
825 if (!Document::isValidName(localName)) {
826 ec = INVALID_CHARACTER_ERR;
827 return;
828 }
829
830 synchronizeAttribute(localName);
831 const AtomicString& caseAdjustedLocalName = shouldIgnoreAttributeCase(this) ? localName.lower() : localName;
832
833 size_t index = elementData() ? elementData()->getAttributeItemIndex(caseAdjustedLocalName, false) : notFound;
834 const QualifiedName& qName = index != notFound ? attributeItem(index)->name() : QualifiedName(nullAtom, caseAdjustedLocalName, nullAtom);
835 setAttributeInternal(index, qName, value, NotInSynchronizationOfLazyAttribute);
836}
837
838void Element::setAttribute(const QualifiedName& name, const AtomicString& value)
839{
840 synchronizeAttribute(name);
841 size_t index = elementData() ? elementData()->getAttributeItemIndex(name) : notFound;
842 setAttributeInternal(index, name, value, NotInSynchronizationOfLazyAttribute);
843}
844
845void Element::setSynchronizedLazyAttribute(const QualifiedName& name, const AtomicString& value)
846{
847 size_t index = elementData() ? elementData()->getAttributeItemIndex(name) : notFound;
848 setAttributeInternal(index, name, value, InSynchronizationOfLazyAttribute);
849}
850
851inline void Element::setAttributeInternal(size_t index, const QualifiedName& name, const AtomicString& newValue, SynchronizationOfLazyAttribute inSynchronizationOfLazyAttribute)
852{
853 if (newValue.isNull()) {
854 if (index != notFound)
855 removeAttributeInternal(index, inSynchronizationOfLazyAttribute);
856 return;
857 }
858
859 if (index == notFound) {
860 addAttributeInternal(name, newValue, inSynchronizationOfLazyAttribute);
861 return;
862 }
863
864 if (!inSynchronizationOfLazyAttribute)
865 willModifyAttribute(name, attributeItem(index)->value(), newValue);
866
867 if (newValue != attributeItem(index)->value()) {
868 // If there is an Attr node hooked to this attribute, the Attr::setValue() call below
869 // will write into the ElementData.
870 // FIXME: Refactor this so it makes some sense.
871 if (RefPtr<Attr> attrNode = inSynchronizationOfLazyAttribute ? 0 : attrIfExists(name))
872 attrNode->setValue(newValue);
873 else
874 ensureUniqueElementData()->attributeItem(index)->setValue(newValue);
875 }
876
877 if (!inSynchronizationOfLazyAttribute)
878 didModifyAttribute(name, newValue);
879}
880
881static inline AtomicString makeIdForStyleResolution(const AtomicString& value, bool inQuirksMode)
882{
883 if (inQuirksMode)
884 return value.lower();
885 return value;
886}
887
888static bool checkNeedsStyleInvalidationForIdChange(const AtomicString& oldId, const AtomicString& newId, StyleResolver* styleResolver)
889{
890 ASSERT(newId != oldId);
891 if (!oldId.isEmpty() && styleResolver->hasSelectorForId(oldId))
892 return true;
893 if (!newId.isEmpty() && styleResolver->hasSelectorForId(newId))
894 return true;
895 return false;
896}
897
Ben Murdoch591b9582013-07-10 11:41:44 +0100898void Element::attributeChanged(const QualifiedName& name, const AtomicString& newValue, AttributeModificationReason reason)
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100899{
900 if (ElementShadow* parentElementShadow = shadowOfParentForDistribution(this)) {
901 if (shouldInvalidateDistributionWhenAttributeChanged(parentElementShadow, name, newValue))
902 parentElementShadow->invalidateDistribution();
903 }
904
905 parseAttribute(name, newValue);
906
907 document()->incDOMTreeVersion();
908
909 StyleResolver* styleResolver = document()->styleResolverIfExists();
910 bool testShouldInvalidateStyle = attached() && styleResolver && styleChangeType() < FullStyleChange;
911 bool shouldInvalidateStyle = false;
912
Ben Murdoch591b9582013-07-10 11:41:44 +0100913 if (isStyledElement() && name == styleAttr) {
914 styleAttributeChanged(newValue, reason);
915 } else if (isStyledElement() && isPresentationAttribute(name)) {
916 elementData()->m_presentationAttributeStyleIsDirty = true;
917 setNeedsStyleRecalc(InlineStyleChange);
918 }
919
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100920 if (isIdAttributeName(name)) {
921 AtomicString oldId = elementData()->idForStyleResolution();
922 AtomicString newId = makeIdForStyleResolution(newValue, document()->inQuirksMode());
923 if (newId != oldId) {
924 elementData()->setIdForStyleResolution(newId);
925 shouldInvalidateStyle = testShouldInvalidateStyle && checkNeedsStyleInvalidationForIdChange(oldId, newId, styleResolver);
926 }
Ben Murdoch591b9582013-07-10 11:41:44 +0100927 } else if (name == classAttr) {
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100928 classAttributeChanged(newValue);
Ben Murdoch591b9582013-07-10 11:41:44 +0100929 } else if (name == HTMLNames::nameAttr) {
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100930 setHasName(!newValue.isNull());
Ben Murdoch591b9582013-07-10 11:41:44 +0100931 } else if (name == HTMLNames::pseudoAttr) {
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100932 shouldInvalidateStyle |= testShouldInvalidateStyle && isInShadowTree();
Ben Murdoch591b9582013-07-10 11:41:44 +0100933 }
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100934
935 invalidateNodeListCachesInAncestors(&name, this);
936
937 // If there is currently no StyleResolver, we can't be sure that this attribute change won't affect style.
938 shouldInvalidateStyle |= !styleResolver;
939
940 if (shouldInvalidateStyle)
941 setNeedsStyleRecalc();
942
943 if (AXObjectCache* cache = document()->existingAXObjectCache())
944 cache->handleAttributeChanged(name, this);
945}
946
947inline void Element::attributeChangedFromParserOrByCloning(const QualifiedName& name, const AtomicString& newValue, AttributeModificationReason reason)
948{
949 if (RuntimeEnabledFeatures::customDOMElementsEnabled() && name == isAttr) {
950 document()->ensureCustomElementRegistry()->didGiveTypeExtension(this, newValue);
951 }
952 attributeChanged(name, newValue, reason);
953}
954
955template <typename CharacterType>
956static inline bool classStringHasClassName(const CharacterType* characters, unsigned length)
957{
958 ASSERT(length > 0);
959
960 unsigned i = 0;
961 do {
962 if (isNotHTMLSpace(characters[i]))
963 break;
964 ++i;
965 } while (i < length);
966
967 return i < length;
968}
969
970static inline bool classStringHasClassName(const AtomicString& newClassString)
971{
972 unsigned length = newClassString.length();
973
974 if (!length)
975 return false;
976
977 if (newClassString.is8Bit())
978 return classStringHasClassName(newClassString.characters8(), length);
979 return classStringHasClassName(newClassString.characters16(), length);
980}
981
982template<typename Checker>
983static bool checkSelectorForClassChange(const SpaceSplitString& changedClasses, const Checker& checker)
984{
985 unsigned changedSize = changedClasses.size();
986 for (unsigned i = 0; i < changedSize; ++i) {
987 if (checker.hasSelectorForClass(changedClasses[i]))
988 return true;
989 }
990 return false;
991}
992
993template<typename Checker>
994static bool checkSelectorForClassChange(const SpaceSplitString& oldClasses, const SpaceSplitString& newClasses, const Checker& checker)
995{
996 unsigned oldSize = oldClasses.size();
997 if (!oldSize)
998 return checkSelectorForClassChange(newClasses, checker);
999 BitVector remainingClassBits;
1000 remainingClassBits.ensureSize(oldSize);
1001 // Class vectors tend to be very short. This is faster than using a hash table.
1002 unsigned newSize = newClasses.size();
1003 for (unsigned i = 0; i < newSize; ++i) {
1004 for (unsigned j = 0; j < oldSize; ++j) {
1005 if (newClasses[i] == oldClasses[j]) {
1006 remainingClassBits.quickSet(j);
1007 continue;
1008 }
1009 }
1010 if (checker.hasSelectorForClass(newClasses[i]))
1011 return true;
1012 }
1013 for (unsigned i = 0; i < oldSize; ++i) {
1014 // If the bit is not set the the corresponding class has been removed.
1015 if (remainingClassBits.quickGet(i))
1016 continue;
1017 if (checker.hasSelectorForClass(oldClasses[i]))
1018 return true;
1019 }
1020 return false;
1021}
1022
1023void Element::classAttributeChanged(const AtomicString& newClassString)
1024{
1025 StyleResolver* styleResolver = document()->styleResolverIfExists();
1026 bool testShouldInvalidateStyle = attached() && styleResolver && styleChangeType() < FullStyleChange;
1027 bool shouldInvalidateStyle = false;
1028
1029 if (classStringHasClassName(newClassString)) {
1030 const bool shouldFoldCase = document()->inQuirksMode();
1031 const SpaceSplitString oldClasses = elementData()->classNames();
1032 elementData()->setClass(newClassString, shouldFoldCase);
1033 const SpaceSplitString& newClasses = elementData()->classNames();
1034 shouldInvalidateStyle = testShouldInvalidateStyle && checkSelectorForClassChange(oldClasses, newClasses, *styleResolver);
1035 } else {
1036 const SpaceSplitString& oldClasses = elementData()->classNames();
1037 shouldInvalidateStyle = testShouldInvalidateStyle && checkSelectorForClassChange(oldClasses, *styleResolver);
1038 elementData()->clearClass();
1039 }
1040
1041 if (hasRareData())
1042 elementRareData()->clearClassListValueForQuirksMode();
1043
1044 if (shouldInvalidateStyle)
1045 setNeedsStyleRecalc();
1046}
1047
1048bool Element::shouldInvalidateDistributionWhenAttributeChanged(ElementShadow* elementShadow, const QualifiedName& name, const AtomicString& newValue)
1049{
1050 ASSERT(elementShadow);
1051 const SelectRuleFeatureSet& featureSet = elementShadow->distributor().ensureSelectFeatureSet(elementShadow);
1052
1053 if (isIdAttributeName(name)) {
1054 AtomicString oldId = elementData()->idForStyleResolution();
1055 AtomicString newId = makeIdForStyleResolution(newValue, document()->inQuirksMode());
1056 if (newId != oldId) {
1057 if (!oldId.isEmpty() && featureSet.hasSelectorForId(oldId))
1058 return true;
1059 if (!newId.isEmpty() && featureSet.hasSelectorForId(newId))
1060 return true;
1061 }
1062 }
1063
1064 if (name == HTMLNames::classAttr) {
1065 const AtomicString& newClassString = newValue;
1066 if (classStringHasClassName(newClassString)) {
1067 const bool shouldFoldCase = document()->inQuirksMode();
1068 const SpaceSplitString& oldClasses = elementData()->classNames();
1069 const SpaceSplitString newClasses(newClassString, shouldFoldCase);
1070 if (checkSelectorForClassChange(oldClasses, newClasses, featureSet))
1071 return true;
1072 } else {
1073 const SpaceSplitString& oldClasses = elementData()->classNames();
1074 if (checkSelectorForClassChange(oldClasses, featureSet))
1075 return true;
1076 }
1077 }
1078
1079 return featureSet.hasSelectorForAttribute(name.localName());
1080}
1081
1082// Returns true is the given attribute is an event handler.
1083// We consider an event handler any attribute that begins with "on".
1084// It is a simple solution that has the advantage of not requiring any
1085// code or configuration change if a new event handler is defined.
1086
1087static inline bool isEventHandlerAttribute(const Attribute& attribute)
1088{
1089 return attribute.name().namespaceURI().isNull() && attribute.name().localName().startsWith("on");
1090}
1091
1092bool Element::isJavaScriptURLAttribute(const Attribute& attribute) const
1093{
1094 return isURLAttribute(attribute) && protocolIsJavaScript(stripLeadingAndTrailingHTMLSpaces(attribute.value()));
1095}
1096
1097void Element::stripScriptingAttributes(Vector<Attribute>& attributeVector) const
1098{
1099 size_t destination = 0;
1100 for (size_t source = 0; source < attributeVector.size(); ++source) {
1101 if (isEventHandlerAttribute(attributeVector[source])
1102 || isJavaScriptURLAttribute(attributeVector[source])
1103 || isHTMLContentAttribute(attributeVector[source]))
1104 continue;
1105
1106 if (source != destination)
1107 attributeVector[destination] = attributeVector[source];
1108
1109 ++destination;
1110 }
1111 attributeVector.shrink(destination);
1112}
1113
1114void Element::parserSetAttributes(const Vector<Attribute>& attributeVector)
1115{
1116 ASSERT(!inDocument());
1117 ASSERT(!parentNode());
1118 ASSERT(!m_elementData);
1119
1120 if (attributeVector.isEmpty())
1121 return;
1122
1123 if (document() && document()->sharedObjectPool())
1124 m_elementData = document()->sharedObjectPool()->cachedShareableElementDataWithAttributes(attributeVector);
1125 else
1126 m_elementData = ShareableElementData::createWithAttributes(attributeVector);
1127
1128 // Use attributeVector instead of m_elementData because attributeChanged might modify m_elementData.
1129 for (unsigned i = 0; i < attributeVector.size(); ++i)
1130 attributeChangedFromParserOrByCloning(attributeVector[i].name(), attributeVector[i].value(), ModifiedDirectly);
1131}
1132
1133bool Element::hasAttributes() const
1134{
1135 synchronizeAllAttributes();
1136 return elementData() && elementData()->length();
1137}
1138
1139bool Element::hasEquivalentAttributes(const Element* other) const
1140{
1141 synchronizeAllAttributes();
1142 other->synchronizeAllAttributes();
1143 if (elementData() == other->elementData())
1144 return true;
1145 if (elementData())
1146 return elementData()->isEquivalent(other->elementData());
1147 if (other->elementData())
1148 return other->elementData()->isEquivalent(elementData());
1149 return true;
1150}
1151
1152String Element::nodeName() const
1153{
1154 return m_tagName.toString();
1155}
1156
1157String Element::nodeNamePreservingCase() const
1158{
1159 return m_tagName.toString();
1160}
1161
1162void Element::setPrefix(const AtomicString& prefix, ExceptionCode& ec)
1163{
1164 ec = 0;
1165 checkSetPrefix(prefix, ec);
1166 if (ec)
1167 return;
1168
1169 m_tagName.setPrefix(prefix.isEmpty() ? AtomicString() : prefix);
1170}
1171
1172KURL Element::baseURI() const
1173{
1174 const AtomicString& baseAttribute = getAttribute(baseAttr);
1175 KURL base(KURL(), baseAttribute);
1176 if (!base.protocol().isEmpty())
1177 return base;
1178
1179 ContainerNode* parent = parentNode();
1180 if (!parent)
1181 return base;
1182
1183 const KURL& parentBase = parent->baseURI();
1184 if (parentBase.isNull())
1185 return base;
1186
1187 return KURL(parentBase, baseAttribute);
1188}
1189
1190const AtomicString& Element::imageSourceURL() const
1191{
1192 return getAttribute(srcAttr);
1193}
1194
1195bool Element::rendererIsNeeded(const NodeRenderingContext& context)
1196{
1197 return context.style()->display() != NONE;
1198}
1199
Ben Murdoch591b9582013-07-10 11:41:44 +01001200RenderObject* Element::createRenderer(RenderStyle* style)
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001201{
1202 return RenderObject::createObject(this, style);
1203}
1204
1205#if ENABLE(INPUT_MULTIPLE_FIELDS_UI)
Torne (Richard Coles)5267f702013-06-11 10:57:24 +01001206bool Element::isDateTimeEditElement() const
1207{
1208 return false;
1209}
1210
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001211bool Element::isDateTimeFieldElement() const
1212{
1213 return false;
1214}
Torne (Richard Coles)5267f702013-06-11 10:57:24 +01001215
1216bool Element::isPickerIndicatorElement() const
1217{
1218 return false;
1219}
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001220#endif
1221
Torne (Richard Coles)5267f702013-06-11 10:57:24 +01001222bool Element::isClearButtonElement() const
1223{
1224 return false;
1225}
1226
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001227bool Element::wasChangedSinceLastFormControlChangeEvent() const
1228{
1229 return false;
1230}
1231
1232void Element::setChangedSinceLastFormControlChangeEvent(bool)
1233{
1234}
1235
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001236bool Element::isInert() const
1237{
Torne (Richard Coles)93ac45c2013-05-29 14:40:20 +01001238 const Element* dialog = document()->activeModalDialog();
Ben Murdoch591b9582013-07-10 11:41:44 +01001239 if (dialog && !containsIncludingShadowDOM(dialog) && !dialog->containsIncludingShadowDOM(this))
1240 return true;
1241 return document()->ownerElement() && document()->ownerElement()->isInert();
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001242}
1243
1244Node::InsertionNotificationRequest Element::insertedInto(ContainerNode* insertionPoint)
1245{
1246 // need to do superclass processing first so inDocument() is true
1247 // by the time we reach updateId
1248 ContainerNode::insertedInto(insertionPoint);
1249
1250 if (containsFullScreenElement() && parentElement() && !parentElement()->containsFullScreenElement())
1251 setContainsFullScreenElementOnAncestorsCrossingFrameBoundaries(true);
1252
1253 if (Element* before = pseudoElement(BEFORE))
1254 before->insertedInto(insertionPoint);
1255
1256 if (Element* after = pseudoElement(AFTER))
1257 after->insertedInto(insertionPoint);
1258
1259 if (!insertionPoint->isInTreeScope())
1260 return InsertionDone;
1261
1262 if (hasRareData())
1263 elementRareData()->clearClassListValueForQuirksMode();
1264
1265 TreeScope* scope = insertionPoint->treeScope();
1266 if (scope != treeScope())
1267 return InsertionDone;
1268
1269 const AtomicString& idValue = getIdAttribute();
1270 if (!idValue.isNull())
1271 updateId(scope, nullAtom, idValue);
1272
1273 const AtomicString& nameValue = getNameAttribute();
1274 if (!nameValue.isNull())
1275 updateName(nullAtom, nameValue);
1276
1277 if (hasTagName(labelTag)) {
1278 if (scope->shouldCacheLabelsByForAttribute())
1279 updateLabel(scope, nullAtom, fastGetAttribute(forAttr));
1280 }
1281
1282 return InsertionDone;
1283}
1284
1285void Element::removedFrom(ContainerNode* insertionPoint)
1286{
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001287 bool wasInDocument = insertionPoint->document();
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001288
1289 if (Element* before = pseudoElement(BEFORE))
1290 before->removedFrom(insertionPoint);
1291
1292 if (Element* after = pseudoElement(AFTER))
1293 after->removedFrom(insertionPoint);
1294
1295 document()->removeFromTopLayer(this);
1296 if (containsFullScreenElement())
1297 setContainsFullScreenElementOnAncestorsCrossingFrameBoundaries(false);
1298
1299 if (document()->page())
1300 document()->page()->pointerLockController()->elementRemoved(this);
1301
1302 setSavedLayerScrollOffset(IntSize());
1303
1304 if (insertionPoint->isInTreeScope() && treeScope() == document()) {
1305 const AtomicString& idValue = getIdAttribute();
1306 if (!idValue.isNull())
1307 updateId(insertionPoint->treeScope(), idValue, nullAtom);
1308
1309 const AtomicString& nameValue = getNameAttribute();
1310 if (!nameValue.isNull())
1311 updateName(nameValue, nullAtom);
1312
1313 if (hasTagName(labelTag)) {
1314 TreeScope* treeScope = insertionPoint->treeScope();
1315 if (treeScope->shouldCacheLabelsByForAttribute())
1316 updateLabel(treeScope, fastGetAttribute(forAttr), nullAtom);
1317 }
1318 }
1319
1320 ContainerNode::removedFrom(insertionPoint);
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001321 if (wasInDocument && hasPendingResources())
1322 document()->accessSVGExtensions()->removeElementFromPendingResources(this);
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001323}
1324
Torne (Richard Coles)521d96e2013-06-19 11:58:24 +01001325void Element::createRendererIfNeeded(const AttachContext& context)
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001326{
Torne (Richard Coles)521d96e2013-06-19 11:58:24 +01001327 NodeRenderingContext(this, context).createRendererForElementIfNeeded();
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001328}
1329
Torne (Richard Coles)521d96e2013-06-19 11:58:24 +01001330void Element::attach(const AttachContext& context)
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001331{
1332 PostAttachCallbackDisabler callbackDisabler(this);
1333 StyleResolverParentPusher parentPusher(this);
1334 WidgetHierarchyUpdatesSuspensionScope suspendWidgetHierarchyUpdates;
1335
Torne (Richard Coles)521d96e2013-06-19 11:58:24 +01001336 createRendererIfNeeded(context);
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001337
1338 if (parentElement() && parentElement()->isInCanvasSubtree())
1339 setIsInCanvasSubtree(true);
1340
1341 createPseudoElementIfNeeded(BEFORE);
1342
1343 // When a shadow root exists, it does the work of attaching the children.
1344 if (ElementShadow* shadow = this->shadow()) {
1345 parentPusher.push();
Ben Murdoch591b9582013-07-10 11:41:44 +01001346 shadow->attach(context);
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001347 } else if (firstChild())
1348 parentPusher.push();
1349
Torne (Richard Coles)521d96e2013-06-19 11:58:24 +01001350 ContainerNode::attach(context);
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001351
1352 createPseudoElementIfNeeded(AFTER);
1353
Ben Murdoch591b9582013-07-10 11:41:44 +01001354 if (hasRareData()) {
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001355 ElementRareData* data = elementRareData();
1356 if (data->needsFocusAppearanceUpdateSoonAfterAttach()) {
1357 if (isFocusable() && document()->focusedNode() == this)
1358 document()->updateFocusAppearanceSoon(false /* don't restore selection */);
1359 data->setNeedsFocusAppearanceUpdateSoonAfterAttach(false);
1360 }
1361 }
Ben Murdoch591b9582013-07-10 11:41:44 +01001362
1363 // FIXME: It doesn't appear safe to call didRecalculateStyleForElement when
1364 // not in a Document::recalcStyle. Since we're hopefully going to always
1365 // lazyAttach in the future that problem should go away.
1366 if (document()->inStyleRecalc())
1367 InspectorInstrumentation::didRecalculateStyleForElement(this);
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001368}
1369
1370void Element::unregisterNamedFlowContentNode()
1371{
1372 if (RuntimeEnabledFeatures::cssRegionsEnabled() && inNamedFlow() && document()->renderView())
1373 document()->renderView()->flowThreadController()->unregisterNamedFlowContentNode(this);
1374}
1375
Torne (Richard Coles)521d96e2013-06-19 11:58:24 +01001376void Element::detach(const AttachContext& context)
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001377{
1378 WidgetHierarchyUpdatesSuspensionScope suspendWidgetHierarchyUpdates;
1379 unregisterNamedFlowContentNode();
1380 cancelFocusAppearanceUpdate();
1381 if (hasRareData()) {
1382 ElementRareData* data = elementRareData();
1383 data->setPseudoElement(BEFORE, 0);
1384 data->setPseudoElement(AFTER, 0);
1385 data->setIsInCanvasSubtree(false);
1386 data->resetComputedStyle();
1387 data->resetDynamicRestyleObservations();
Ben Murdoch591b9582013-07-10 11:41:44 +01001388 data->setIsInsideRegion(false);
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001389 }
Ben Murdoch591b9582013-07-10 11:41:44 +01001390 if (ElementShadow* shadow = this->shadow())
1391 shadow->detach(context);
Torne (Richard Coles)521d96e2013-06-19 11:58:24 +01001392 ContainerNode::detach(context);
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001393}
1394
1395bool Element::pseudoStyleCacheIsInvalid(const RenderStyle* currentStyle, RenderStyle* newStyle)
1396{
1397 ASSERT(currentStyle == renderStyle());
1398 ASSERT(renderer());
1399
1400 if (!currentStyle)
1401 return false;
1402
1403 const PseudoStyleCache* pseudoStyleCache = currentStyle->cachedPseudoStyles();
1404 if (!pseudoStyleCache)
1405 return false;
1406
1407 size_t cacheSize = pseudoStyleCache->size();
1408 for (size_t i = 0; i < cacheSize; ++i) {
1409 RefPtr<RenderStyle> newPseudoStyle;
1410 PseudoId pseudoId = pseudoStyleCache->at(i)->styleType();
1411 if (pseudoId == FIRST_LINE || pseudoId == FIRST_LINE_INHERITED)
1412 newPseudoStyle = renderer()->uncachedFirstLineStyle(newStyle);
1413 else
1414 newPseudoStyle = renderer()->getUncachedPseudoStyle(PseudoStyleRequest(pseudoId), newStyle, newStyle);
1415 if (!newPseudoStyle)
1416 return true;
1417 if (*newPseudoStyle != *pseudoStyleCache->at(i)) {
1418 if (pseudoId < FIRST_INTERNAL_PSEUDOID)
1419 newStyle->setHasPseudoStyle(pseudoId);
1420 newStyle->addCachedPseudoStyle(newPseudoStyle);
1421 if (pseudoId == FIRST_LINE || pseudoId == FIRST_LINE_INHERITED) {
1422 // FIXME: We should do an actual diff to determine whether a repaint vs. layout
1423 // is needed, but for now just assume a layout will be required. The diff code
1424 // in RenderObject::setStyle would need to be factored out so that it could be reused.
1425 renderer()->setNeedsLayoutAndPrefWidthsRecalc();
1426 }
1427 return true;
1428 }
1429 }
1430 return false;
1431}
1432
Torne (Richard Coles)521d96e2013-06-19 11:58:24 +01001433PassRefPtr<RenderStyle> Element::styleForRenderer()
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001434{
1435 if (hasCustomStyleCallbacks()) {
1436 if (RefPtr<RenderStyle> style = customStyleForRenderer())
1437 return style.release();
1438 }
1439
Torne (Richard Coles)521d96e2013-06-19 11:58:24 +01001440 return originalStyleForRenderer();
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001441}
1442
Torne (Richard Coles)521d96e2013-06-19 11:58:24 +01001443PassRefPtr<RenderStyle> Element::originalStyleForRenderer()
Torne (Richard Coles)5267f702013-06-11 10:57:24 +01001444{
Torne (Richard Coles)521d96e2013-06-19 11:58:24 +01001445 return document()->styleResolver()->styleForElement(this);
Torne (Richard Coles)5267f702013-06-11 10:57:24 +01001446}
1447
Torne (Richard Coles)521d96e2013-06-19 11:58:24 +01001448void Element::recalcStyle(StyleChange change)
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001449{
Torne (Richard Coles)93ac45c2013-05-29 14:40:20 +01001450 ASSERT(document()->inStyleRecalc());
1451
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001452 if (hasCustomStyleCallbacks())
1453 willRecalcStyle(change);
1454
1455 // Ref currentStyle in case it would otherwise be deleted when setting the new style in the renderer.
1456 RefPtr<RenderStyle> currentStyle(renderStyle());
1457 bool hasParentStyle = parentNodeForRenderingAndStyle() ? static_cast<bool>(parentNodeForRenderingAndStyle()->renderStyle()) : false;
1458 bool hasDirectAdjacentRules = childrenAffectedByDirectAdjacentRules();
1459 bool hasIndirectAdjacentRules = childrenAffectedByForwardPositionalRules();
1460
1461 if ((change > NoChange || needsStyleRecalc())) {
1462 if (hasRareData())
1463 elementRareData()->resetComputedStyle();
1464 }
1465 if (hasParentStyle && (change >= Inherit || needsStyleRecalc())) {
1466 StyleChange localChange = Detach;
1467 RefPtr<RenderStyle> newStyle;
1468 if (currentStyle) {
1469 // FIXME: This still recalcs style twice when changing display types, but saves
1470 // us from recalcing twice when going from none -> anything else which is more
1471 // common, especially during lazy attach.
Torne (Richard Coles)521d96e2013-06-19 11:58:24 +01001472 newStyle = styleForRenderer();
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001473 localChange = Node::diff(currentStyle.get(), newStyle.get(), document());
Torne (Richard Coles)521d96e2013-06-19 11:58:24 +01001474 } else if (attached() && isActiveInsertionPoint(this)) {
1475 // Active InsertionPoints will never have renderers so there's no reason to
1476 // reattach them repeatedly once they're already attached.
1477 localChange = change;
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001478 }
1479 if (localChange == Detach) {
Torne (Richard Coles)521d96e2013-06-19 11:58:24 +01001480 AttachContext reattachContext;
1481 reattachContext.resolvedStyle = newStyle.get();
1482 reattach(reattachContext);
1483
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001484 // attach recalculates the style for all children. No need to do it twice.
1485 clearNeedsStyleRecalc();
1486 clearChildNeedsStyleRecalc();
1487
1488 if (hasCustomStyleCallbacks())
1489 didRecalcStyle(change);
1490 return;
1491 }
1492
Ben Murdoch591b9582013-07-10 11:41:44 +01001493 InspectorInstrumentation::didRecalculateStyleForElement(this);
1494
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001495 if (RenderObject* renderer = this->renderer()) {
Ben Murdoch591b9582013-07-10 11:41:44 +01001496 if (localChange != NoChange || pseudoStyleCacheIsInvalid(currentStyle.get(), newStyle.get()) || (change == Force && renderer->requiresForcedStyleRecalcPropagation()) || needsLayerUpdate())
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001497 renderer->setAnimatableStyle(newStyle.get());
1498 else if (needsStyleRecalc()) {
1499 // Although no change occurred, we use the new style so that the cousin style sharing code won't get
1500 // fooled into believing this style is the same.
1501 renderer->setStyleInternal(newStyle.get());
1502 }
1503 }
1504
1505 // 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
1506 // 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).
1507 if (document()->styleSheetCollection()->usesRemUnits() && document()->documentElement() == this && localChange != NoChange && currentStyle && newStyle && currentStyle->fontSize() != newStyle->fontSize()) {
1508 // Cached RenderStyles may depend on the re units.
1509 document()->styleResolver()->invalidateMatchedPropertiesCache();
1510 change = Force;
1511 }
1512
Torne (Richard Coles)e5249552013-05-15 11:35:13 +01001513 if (styleChangeType() == FullStyleChange)
1514 change = Force;
1515 else if (change != Force)
1516 change = localChange;
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001517 }
1518 StyleResolverParentPusher parentPusher(this);
1519
1520 // FIXME: This does not care about sibling combinators. Will be necessary in XBL2 world.
1521 if (ElementShadow* shadow = this->shadow()) {
1522 if (shouldRecalcStyle(change, shadow)) {
1523 parentPusher.push();
1524 shadow->recalcStyle(change);
1525 }
1526 }
1527
1528 if (shouldRecalcStyle(change, this))
1529 updatePseudoElement(BEFORE, change);
1530
1531 // FIXME: This check is good enough for :hover + foo, but it is not good enough for :hover + foo + bar.
1532 // For now we will just worry about the common case, since it's a lot trickier to get the second case right
1533 // without doing way too much re-resolution.
1534 bool forceCheckOfNextElementSibling = false;
1535 bool forceCheckOfAnyElementSibling = false;
1536 for (Node *n = firstChild(); n; n = n->nextSibling()) {
1537 if (n->isTextNode()) {
1538 toText(n)->recalcTextStyle(change);
1539 continue;
Ben Murdoch591b9582013-07-10 11:41:44 +01001540 }
1541 if (!n->isElementNode())
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001542 continue;
1543 Element* element = toElement(n);
1544 bool childRulesChanged = element->needsStyleRecalc() && element->styleChangeType() == FullStyleChange;
1545 if ((forceCheckOfNextElementSibling || forceCheckOfAnyElementSibling))
1546 element->setNeedsStyleRecalc();
Torne (Richard Coles)5267f702013-06-11 10:57:24 +01001547 if (shouldRecalcStyle(change, element)) {
1548 parentPusher.push();
Torne (Richard Coles)521d96e2013-06-19 11:58:24 +01001549 element->recalcStyle(change);
Torne (Richard Coles)5267f702013-06-11 10:57:24 +01001550 }
Torne (Richard Coles)521d96e2013-06-19 11:58:24 +01001551 forceCheckOfNextElementSibling = childRulesChanged && hasDirectAdjacentRules;
1552 forceCheckOfAnyElementSibling = forceCheckOfAnyElementSibling || (childRulesChanged && hasIndirectAdjacentRules);
Torne (Richard Coles)5267f702013-06-11 10:57:24 +01001553 }
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001554
1555 if (shouldRecalcStyle(change, this))
1556 updatePseudoElement(AFTER, change);
1557
1558 clearNeedsStyleRecalc();
1559 clearChildNeedsStyleRecalc();
Ben Murdoch591b9582013-07-10 11:41:44 +01001560
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001561 if (hasCustomStyleCallbacks())
1562 didRecalcStyle(change);
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001563}
1564
1565ElementShadow* Element::shadow() const
1566{
1567 return hasRareData() ? elementRareData()->shadow() : 0;
1568}
1569
1570ElementShadow* Element::ensureShadow()
1571{
1572 return ensureElementRareData()->ensureShadow();
1573}
1574
1575void Element::didAffectSelector(AffectedSelectorMask mask)
1576{
1577 setNeedsStyleRecalc();
1578 if (ElementShadow* elementShadow = shadowOfParentForDistribution(this))
1579 elementShadow->didAffectSelector(mask);
1580}
1581
1582PassRefPtr<ShadowRoot> Element::createShadowRoot(ExceptionCode& ec)
1583{
1584 if (alwaysCreateUserAgentShadowRoot())
1585 ensureUserAgentShadowRoot();
1586
1587 if (RuntimeEnabledFeatures::authorShadowDOMForAnyElementEnabled())
1588 return ensureShadow()->addShadowRoot(this, ShadowRoot::AuthorShadowRoot);
1589
1590 // Since some elements recreates shadow root dynamically, multiple shadow
1591 // subtrees won't work well in that element. Until they are fixed, we disable
1592 // adding author shadow root for them.
1593 if (!areAuthorShadowsAllowed()) {
1594 ec = HIERARCHY_REQUEST_ERR;
1595 return 0;
1596 }
1597 return ensureShadow()->addShadowRoot(this, ShadowRoot::AuthorShadowRoot);
1598}
1599
1600ShadowRoot* Element::shadowRoot() const
1601{
1602 ElementShadow* elementShadow = shadow();
1603 if (!elementShadow)
1604 return 0;
1605 ShadowRoot* shadowRoot = elementShadow->youngestShadowRoot();
1606 if (shadowRoot->type() == ShadowRoot::AuthorShadowRoot)
1607 return shadowRoot;
1608 return 0;
1609}
1610
1611ShadowRoot* Element::userAgentShadowRoot() const
1612{
1613 if (ElementShadow* elementShadow = shadow()) {
1614 if (ShadowRoot* shadowRoot = elementShadow->oldestShadowRoot()) {
1615 ASSERT(shadowRoot->type() == ShadowRoot::UserAgentShadowRoot);
1616 return shadowRoot;
1617 }
1618 }
1619
1620 return 0;
1621}
1622
1623ShadowRoot* Element::ensureUserAgentShadowRoot()
1624{
1625 if (ShadowRoot* shadowRoot = userAgentShadowRoot())
1626 return shadowRoot;
1627 ShadowRoot* shadowRoot = ensureShadow()->addShadowRoot(this, ShadowRoot::UserAgentShadowRoot);
1628 didAddUserAgentShadowRoot(shadowRoot);
1629 return shadowRoot;
1630}
1631
1632const AtomicString& Element::shadowPseudoId() const
1633{
1634 return pseudo();
1635}
1636
1637bool Element::childTypeAllowed(NodeType type) const
1638{
1639 switch (type) {
1640 case ELEMENT_NODE:
1641 case TEXT_NODE:
1642 case COMMENT_NODE:
1643 case PROCESSING_INSTRUCTION_NODE:
1644 case CDATA_SECTION_NODE:
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001645 return true;
1646 default:
1647 break;
1648 }
1649 return false;
1650}
1651
1652static void checkForEmptyStyleChange(Element* element, RenderStyle* style)
1653{
1654 if (!style && !element->styleAffectedByEmpty())
1655 return;
1656
1657 if (!style || (element->styleAffectedByEmpty() && (!style->emptyState() || element->hasChildNodes())))
1658 element->setNeedsStyleRecalc();
1659}
1660
1661static void checkForSiblingStyleChanges(Element* e, RenderStyle* style, bool finishedParsingCallback,
1662 Node* beforeChange, Node* afterChange, int childCountDelta)
1663{
1664 // :empty selector.
1665 checkForEmptyStyleChange(e, style);
Ben Murdoch591b9582013-07-10 11:41:44 +01001666
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001667 if (!style || (e->needsStyleRecalc() && e->childrenAffectedByPositionalRules()))
1668 return;
1669
1670 // :first-child. In the parser callback case, we don't have to check anything, since we were right the first time.
1671 // In the DOM case, we only need to do something if |afterChange| is not 0.
1672 // |afterChange| is 0 in the parser case, so it works out that we'll skip this block.
1673 if (e->childrenAffectedByFirstChildRules() && afterChange) {
1674 // Find our new first child.
1675 Node* newFirstChild = 0;
1676 for (newFirstChild = e->firstChild(); newFirstChild && !newFirstChild->isElementNode(); newFirstChild = newFirstChild->nextSibling()) {};
Ben Murdoch591b9582013-07-10 11:41:44 +01001677
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001678 // Find the first element node following |afterChange|
1679 Node* firstElementAfterInsertion = 0;
1680 for (firstElementAfterInsertion = afterChange;
1681 firstElementAfterInsertion && !firstElementAfterInsertion->isElementNode();
1682 firstElementAfterInsertion = firstElementAfterInsertion->nextSibling()) {};
Ben Murdoch591b9582013-07-10 11:41:44 +01001683
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001684 // This is the insert/append case.
1685 if (newFirstChild != firstElementAfterInsertion && firstElementAfterInsertion && firstElementAfterInsertion->attached() &&
1686 firstElementAfterInsertion->renderStyle() && firstElementAfterInsertion->renderStyle()->firstChildState())
1687 firstElementAfterInsertion->setNeedsStyleRecalc();
Ben Murdoch591b9582013-07-10 11:41:44 +01001688
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001689 // We also have to handle node removal.
1690 if (childCountDelta < 0 && newFirstChild == firstElementAfterInsertion && newFirstChild && (!newFirstChild->renderStyle() || !newFirstChild->renderStyle()->firstChildState()))
1691 newFirstChild->setNeedsStyleRecalc();
1692 }
1693
1694 // :last-child. In the parser callback case, we don't have to check anything, since we were right the first time.
1695 // In the DOM case, we only need to do something if |afterChange| is not 0.
1696 if (e->childrenAffectedByLastChildRules() && beforeChange) {
1697 // Find our new last child.
1698 Node* newLastChild = 0;
1699 for (newLastChild = e->lastChild(); newLastChild && !newLastChild->isElementNode(); newLastChild = newLastChild->previousSibling()) {};
Ben Murdoch591b9582013-07-10 11:41:44 +01001700
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001701 // Find the last element node going backwards from |beforeChange|
1702 Node* lastElementBeforeInsertion = 0;
1703 for (lastElementBeforeInsertion = beforeChange;
1704 lastElementBeforeInsertion && !lastElementBeforeInsertion->isElementNode();
1705 lastElementBeforeInsertion = lastElementBeforeInsertion->previousSibling()) {};
Ben Murdoch591b9582013-07-10 11:41:44 +01001706
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001707 if (newLastChild != lastElementBeforeInsertion && lastElementBeforeInsertion && lastElementBeforeInsertion->attached() &&
1708 lastElementBeforeInsertion->renderStyle() && lastElementBeforeInsertion->renderStyle()->lastChildState())
1709 lastElementBeforeInsertion->setNeedsStyleRecalc();
Ben Murdoch591b9582013-07-10 11:41:44 +01001710
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001711 // 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
1712 // to match now.
1713 if ((childCountDelta < 0 || finishedParsingCallback) && newLastChild == lastElementBeforeInsertion && newLastChild && (!newLastChild->renderStyle() || !newLastChild->renderStyle()->lastChildState()))
1714 newLastChild->setNeedsStyleRecalc();
1715 }
1716
1717 // The + selector. We need to invalidate the first element following the insertion point. It is the only possible element
1718 // that could be affected by this DOM change.
1719 if (e->childrenAffectedByDirectAdjacentRules() && afterChange) {
1720 Node* firstElementAfterInsertion = 0;
1721 for (firstElementAfterInsertion = afterChange;
1722 firstElementAfterInsertion && !firstElementAfterInsertion->isElementNode();
1723 firstElementAfterInsertion = firstElementAfterInsertion->nextSibling()) {};
1724 if (firstElementAfterInsertion && firstElementAfterInsertion->attached())
1725 firstElementAfterInsertion->setNeedsStyleRecalc();
1726 }
1727
1728 // Forward positional selectors include the ~ selector, nth-child, nth-of-type, first-of-type and only-of-type.
1729 // Backward positional selectors include nth-last-child, nth-last-of-type, last-of-type and only-of-type.
1730 // We have to invalidate everything following the insertion point in the forward case, and everything before the insertion point in the
1731 // backward case.
1732 // |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.
1733 // 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
1734 // here. recalcStyle will then force a walk of the children when it sees that this has happened.
1735 if ((e->childrenAffectedByForwardPositionalRules() && afterChange)
1736 || (e->childrenAffectedByBackwardPositionalRules() && beforeChange))
1737 e->setNeedsStyleRecalc();
1738}
1739
1740void Element::childrenChanged(bool changedByParser, Node* beforeChange, Node* afterChange, int childCountDelta)
1741{
1742 ContainerNode::childrenChanged(changedByParser, beforeChange, afterChange, childCountDelta);
1743 if (changedByParser)
1744 checkForEmptyStyleChange(this, renderStyle());
1745 else
1746 checkForSiblingStyleChanges(this, renderStyle(), false, beforeChange, afterChange, childCountDelta);
1747
1748 if (ElementShadow * shadow = this->shadow())
1749 shadow->invalidateDistribution();
1750}
1751
1752void Element::removeAllEventListeners()
1753{
1754 ContainerNode::removeAllEventListeners();
1755 if (ElementShadow* shadow = this->shadow())
1756 shadow->removeAllEventListeners();
1757}
1758
1759void Element::beginParsingChildren()
1760{
1761 clearIsParsingChildrenFinished();
1762 StyleResolver* styleResolver = document()->styleResolverIfExists();
1763 if (styleResolver && attached())
1764 styleResolver->pushParentElement(this);
1765}
1766
1767void Element::finishParsingChildren()
1768{
1769 ContainerNode::finishParsingChildren();
1770 setIsParsingChildrenFinished();
1771 checkForSiblingStyleChanges(this, renderStyle(), true, lastChild(), 0, 0);
1772 if (StyleResolver* styleResolver = document()->styleResolverIfExists())
1773 styleResolver->popParentElement(this);
1774}
1775
1776#ifndef NDEBUG
1777void Element::formatForDebugger(char* buffer, unsigned length) const
1778{
1779 StringBuilder result;
1780 String s;
1781
1782 result.append(nodeName());
1783
1784 s = getIdAttribute();
1785 if (s.length() > 0) {
1786 if (result.length() > 0)
1787 result.appendLiteral("; ");
1788 result.appendLiteral("id=");
1789 result.append(s);
1790 }
1791
1792 s = getAttribute(classAttr);
1793 if (s.length() > 0) {
1794 if (result.length() > 0)
1795 result.appendLiteral("; ");
1796 result.appendLiteral("class=");
1797 result.append(s);
1798 }
1799
1800 strncpy(buffer, result.toString().utf8().data(), length - 1);
1801}
1802#endif
1803
1804const Vector<RefPtr<Attr> >& Element::attrNodeList()
1805{
1806 ASSERT(hasSyntheticAttrChildNodes());
1807 return *attrNodeListForElement(this);
1808}
1809
1810PassRefPtr<Attr> Element::setAttributeNode(Attr* attrNode, ExceptionCode& ec)
1811{
1812 if (!attrNode) {
1813 ec = TYPE_MISMATCH_ERR;
1814 return 0;
1815 }
1816
1817 RefPtr<Attr> oldAttrNode = attrIfExists(attrNode->qualifiedName());
1818 if (oldAttrNode.get() == attrNode)
1819 return attrNode; // This Attr is already attached to the element.
1820
1821 // INUSE_ATTRIBUTE_ERR: Raised if node is an Attr that is already an attribute of another Element object.
1822 // The DOM user must explicitly clone Attr nodes to re-use them in other elements.
1823 if (attrNode->ownerElement()) {
1824 ec = INUSE_ATTRIBUTE_ERR;
1825 return 0;
1826 }
1827
1828 synchronizeAllAttributes();
1829 UniqueElementData* elementData = ensureUniqueElementData();
1830
1831 size_t index = elementData->getAttributeItemIndex(attrNode->qualifiedName());
1832 if (index != notFound) {
1833 if (oldAttrNode)
1834 detachAttrNodeFromElementWithValue(oldAttrNode.get(), elementData->attributeItem(index)->value());
1835 else
1836 oldAttrNode = Attr::create(document(), attrNode->qualifiedName(), elementData->attributeItem(index)->value());
1837 }
1838
1839 setAttributeInternal(index, attrNode->qualifiedName(), attrNode->value(), NotInSynchronizationOfLazyAttribute);
1840
1841 attrNode->attachToElement(this);
Ben Murdoch591b9582013-07-10 11:41:44 +01001842 treeScope()->adoptIfNeeded(attrNode);
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001843 ensureAttrNodeListForElement(this)->append(attrNode);
1844
1845 return oldAttrNode.release();
1846}
1847
1848PassRefPtr<Attr> Element::setAttributeNodeNS(Attr* attr, ExceptionCode& ec)
1849{
1850 return setAttributeNode(attr, ec);
1851}
1852
1853PassRefPtr<Attr> Element::removeAttributeNode(Attr* attr, ExceptionCode& ec)
1854{
1855 if (!attr) {
1856 ec = TYPE_MISMATCH_ERR;
1857 return 0;
1858 }
1859 if (attr->ownerElement() != this) {
1860 ec = NOT_FOUND_ERR;
1861 return 0;
1862 }
1863
1864 ASSERT(document() == attr->document());
1865
1866 synchronizeAttribute(attr->qualifiedName());
1867
Torne (Richard Coles)e5249552013-05-15 11:35:13 +01001868 size_t index = elementData()->getAttrIndex(attr);
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001869 if (index == notFound) {
1870 ec = NOT_FOUND_ERR;
1871 return 0;
1872 }
1873
Torne (Richard Coles)e5249552013-05-15 11:35:13 +01001874 RefPtr<Attr> guard(attr);
1875 detachAttrNodeAtIndex(attr, index);
1876 return guard.release();
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001877}
1878
1879bool Element::parseAttributeName(QualifiedName& out, const AtomicString& namespaceURI, const AtomicString& qualifiedName, ExceptionCode& ec)
1880{
1881 String prefix, localName;
1882 if (!Document::parseQualifiedName(qualifiedName, prefix, localName, ec))
1883 return false;
1884 ASSERT(!ec);
1885
1886 QualifiedName qName(prefix, localName, namespaceURI);
1887
1888 if (!Document::hasValidNamespaceForAttributes(qName)) {
1889 ec = NAMESPACE_ERR;
1890 return false;
1891 }
1892
1893 out = qName;
1894 return true;
1895}
1896
1897void Element::setAttributeNS(const AtomicString& namespaceURI, const AtomicString& qualifiedName, const AtomicString& value, ExceptionCode& ec)
1898{
1899 QualifiedName parsedName = anyName;
1900 if (!parseAttributeName(parsedName, namespaceURI, qualifiedName, ec))
1901 return;
1902 setAttribute(parsedName, value);
1903}
1904
1905void Element::removeAttributeInternal(size_t index, SynchronizationOfLazyAttribute inSynchronizationOfLazyAttribute)
1906{
1907 ASSERT_WITH_SECURITY_IMPLICATION(index < attributeCount());
1908
1909 UniqueElementData* elementData = ensureUniqueElementData();
1910
1911 QualifiedName name = elementData->attributeItem(index)->name();
1912 AtomicString valueBeingRemoved = elementData->attributeItem(index)->value();
1913
1914 if (!inSynchronizationOfLazyAttribute) {
1915 if (!valueBeingRemoved.isNull())
1916 willModifyAttribute(name, valueBeingRemoved, nullAtom);
1917 }
1918
1919 if (RefPtr<Attr> attrNode = attrIfExists(name))
1920 detachAttrNodeFromElementWithValue(attrNode.get(), elementData->attributeItem(index)->value());
1921
1922 elementData->removeAttribute(index);
1923
1924 if (!inSynchronizationOfLazyAttribute)
1925 didRemoveAttribute(name);
1926}
1927
1928void Element::addAttributeInternal(const QualifiedName& name, const AtomicString& value, SynchronizationOfLazyAttribute inSynchronizationOfLazyAttribute)
1929{
1930 if (!inSynchronizationOfLazyAttribute)
1931 willModifyAttribute(name, nullAtom, value);
1932 ensureUniqueElementData()->addAttribute(name, value);
1933 if (!inSynchronizationOfLazyAttribute)
1934 didAddAttribute(name, value);
1935}
1936
1937void Element::removeAttribute(const AtomicString& name)
1938{
1939 if (!elementData())
1940 return;
1941
1942 AtomicString localName = shouldIgnoreAttributeCase(this) ? name.lower() : name;
1943 size_t index = elementData()->getAttributeItemIndex(localName, false);
1944 if (index == notFound) {
1945 if (UNLIKELY(localName == styleAttr) && elementData()->m_styleAttributeIsDirty && isStyledElement())
Ben Murdoch591b9582013-07-10 11:41:44 +01001946 removeAllInlineStyleProperties();
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001947 return;
1948 }
1949
1950 removeAttributeInternal(index, NotInSynchronizationOfLazyAttribute);
1951}
1952
1953void Element::removeAttributeNS(const AtomicString& namespaceURI, const AtomicString& localName)
1954{
1955 removeAttribute(QualifiedName(nullAtom, localName, namespaceURI));
1956}
1957
1958PassRefPtr<Attr> Element::getAttributeNode(const AtomicString& localName)
1959{
1960 if (!elementData())
1961 return 0;
1962 synchronizeAttribute(localName);
1963 const Attribute* attribute = elementData()->getAttributeItem(localName, shouldIgnoreAttributeCase(this));
1964 if (!attribute)
1965 return 0;
1966 return ensureAttr(attribute->name());
1967}
1968
1969PassRefPtr<Attr> Element::getAttributeNodeNS(const AtomicString& namespaceURI, const AtomicString& localName)
1970{
1971 if (!elementData())
1972 return 0;
1973 QualifiedName qName(nullAtom, localName, namespaceURI);
1974 synchronizeAttribute(qName);
1975 const Attribute* attribute = elementData()->getAttributeItem(qName);
1976 if (!attribute)
1977 return 0;
1978 return ensureAttr(attribute->name());
1979}
1980
1981bool Element::hasAttribute(const AtomicString& localName) const
1982{
1983 if (!elementData())
1984 return false;
1985 synchronizeAttribute(localName);
1986 return elementData()->getAttributeItem(shouldIgnoreAttributeCase(this) ? localName.lower() : localName, false);
1987}
1988
1989bool Element::hasAttributeNS(const AtomicString& namespaceURI, const AtomicString& localName) const
1990{
1991 if (!elementData())
1992 return false;
1993 QualifiedName qName(nullAtom, localName, namespaceURI);
1994 synchronizeAttribute(qName);
1995 return elementData()->getAttributeItem(qName);
1996}
1997
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001998void Element::focus(bool restorePreviousSelection, FocusDirection direction)
1999{
2000 if (!inDocument())
2001 return;
2002
2003 Document* doc = document();
2004 if (doc->focusedNode() == this)
2005 return;
2006
2007 // If the stylesheets have already been loaded we can reliably check isFocusable.
2008 // If not, we continue and set the focused node on the focus controller below so
Ben Murdoch591b9582013-07-10 11:41:44 +01002009 // that it can be updated soon after attach.
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002010 if (doc->haveStylesheetsLoaded()) {
2011 doc->updateLayoutIgnorePendingStylesheets();
2012 if (!isFocusable())
2013 return;
2014 }
2015
2016 if (!supportsFocus())
2017 return;
2018
2019 RefPtr<Node> protect;
2020 if (Page* page = doc->page()) {
2021 // Focus and change event handlers can cause us to lose our last ref.
2022 // If a focus event handler changes the focus to a different node it
2023 // does not make sense to continue and update appearence.
2024 protect = this;
2025 if (!page->focusController()->setFocusedNode(this, doc->frame(), direction))
2026 return;
2027 }
2028
2029 // Setting the focused node above might have invalidated the layout due to scripts.
2030 doc->updateLayoutIgnorePendingStylesheets();
2031
2032 if (!isFocusable()) {
2033 ensureElementRareData()->setNeedsFocusAppearanceUpdateSoonAfterAttach(true);
2034 return;
2035 }
Ben Murdoch591b9582013-07-10 11:41:44 +01002036
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002037 cancelFocusAppearanceUpdate();
2038 updateFocusAppearance(restorePreviousSelection);
2039}
2040
2041void Element::updateFocusAppearance(bool /*restorePreviousSelection*/)
2042{
2043 if (isRootEditableElement()) {
2044 Frame* frame = document()->frame();
2045 if (!frame)
2046 return;
Ben Murdoch591b9582013-07-10 11:41:44 +01002047
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002048 // When focusing an editable element in an iframe, don't reset the selection if it already contains a selection.
2049 if (this == frame->selection()->rootEditableElement())
2050 return;
2051
2052 // FIXME: We should restore the previous selection if there is one.
2053 VisibleSelection newSelection = VisibleSelection(firstPositionInOrBeforeNode(this), DOWNSTREAM);
Ben Murdoch591b9582013-07-10 11:41:44 +01002054
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002055 if (frame->selection()->shouldChangeSelection(newSelection)) {
2056 frame->selection()->setSelection(newSelection);
2057 frame->selection()->revealSelection();
2058 }
2059 } else if (renderer() && !renderer()->isWidget())
2060 renderer()->scrollRectToVisible(boundingBox());
2061}
2062
2063void Element::blur()
2064{
2065 cancelFocusAppearanceUpdate();
2066 Document* doc = document();
2067 if (treeScope()->focusedNode() == this) {
2068 if (doc->frame())
2069 doc->frame()->page()->focusController()->setFocusedNode(0, doc->frame());
2070 else
2071 doc->setFocusedNode(0);
2072 }
2073}
2074
2075String Element::innerText()
2076{
2077 // We need to update layout, since plainText uses line boxes in the render tree.
2078 document()->updateLayoutIgnorePendingStylesheets();
2079
2080 if (!renderer())
2081 return textContent(true);
2082
2083 return plainText(rangeOfContents(const_cast<Element*>(this)).get());
2084}
2085
2086String Element::outerText()
2087{
2088 // Getting outerText is the same as getting innerText, only
2089 // setting is different. You would think this should get the plain
2090 // text for the outer range, but this is wrong, <br> for instance
2091 // would return different values for inner and outer text by such
2092 // a rule, but it doesn't in WinIE, and we want to match that.
2093 return innerText();
2094}
2095
Ben Murdoch591b9582013-07-10 11:41:44 +01002096String Element::textFromChildren()
2097{
2098 Text* firstTextNode = 0;
2099 bool foundMultipleTextNodes = false;
2100 unsigned totalLength = 0;
2101
2102 for (Node* child = firstChild(); child; child = child->nextSibling()) {
2103 if (!child->isTextNode())
2104 continue;
2105 Text* text = toText(child);
2106 if (!firstTextNode)
2107 firstTextNode = text;
2108 else
2109 foundMultipleTextNodes = true;
2110 unsigned length = text->data().length();
2111 if (length > std::numeric_limits<unsigned>::max() - totalLength)
2112 return emptyString();
2113 totalLength += length;
2114 }
2115
2116 if (!firstTextNode)
2117 return emptyString();
2118
2119 if (firstTextNode && !foundMultipleTextNodes) {
2120 firstTextNode->atomize();
2121 return firstTextNode->data();
2122 }
2123
2124 StringBuilder content;
2125 content.reserveCapacity(totalLength);
2126 for (Node* child = firstTextNode; child; child = child->nextSibling()) {
2127 if (!child->isTextNode())
2128 continue;
2129 content.append(toText(child)->data());
2130 }
2131
2132 ASSERT(content.length() == totalLength);
2133 return content.toString();
2134}
2135
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002136String Element::title() const
2137{
2138 return String();
2139}
2140
2141const AtomicString& Element::pseudo() const
2142{
2143 return getAttribute(pseudoAttr);
2144}
2145
2146void Element::setPseudo(const AtomicString& value)
2147{
2148 setAttribute(pseudoAttr, value);
2149}
2150
2151LayoutSize Element::minimumSizeForResizing() const
2152{
2153 return hasRareData() ? elementRareData()->minimumSizeForResizing() : defaultMinimumSizeForResizing();
2154}
2155
2156void Element::setMinimumSizeForResizing(const LayoutSize& size)
2157{
2158 if (!hasRareData() && size == defaultMinimumSizeForResizing())
2159 return;
2160 ensureElementRareData()->setMinimumSizeForResizing(size);
2161}
2162
2163RenderStyle* Element::computedStyle(PseudoId pseudoElementSpecifier)
2164{
2165 if (PseudoElement* element = pseudoElement(pseudoElementSpecifier))
2166 return element->computedStyle();
2167
2168 // FIXME: Find and use the renderer from the pseudo element instead of the actual element so that the 'length'
2169 // properties, which are only known by the renderer because it did the layout, will be correct and so that the
2170 // values returned for the ":selection" pseudo-element will be correct.
2171 if (RenderStyle* usedStyle = renderStyle()) {
2172 if (pseudoElementSpecifier) {
2173 RenderStyle* cachedPseudoStyle = usedStyle->getCachedPseudoStyle(pseudoElementSpecifier);
2174 return cachedPseudoStyle ? cachedPseudoStyle : usedStyle;
2175 } else
2176 return usedStyle;
2177 }
2178
2179 if (!attached())
2180 // FIXME: Try to do better than this. Ensure that styleForElement() works for elements that are not in the
2181 // document tree and figure out when to destroy the computed style for such elements.
2182 return 0;
2183
2184 ElementRareData* data = ensureElementRareData();
2185 if (!data->computedStyle())
2186 data->setComputedStyle(document()->styleForElementIgnoringPendingStylesheets(this));
2187 return pseudoElementSpecifier ? data->computedStyle()->getCachedPseudoStyle(pseudoElementSpecifier) : data->computedStyle();
2188}
2189
2190void Element::setStyleAffectedByEmpty()
2191{
2192 ensureElementRareData()->setStyleAffectedByEmpty(true);
2193}
2194
2195void Element::setChildrenAffectedByHover(bool value)
2196{
2197 if (value || hasRareData())
2198 ensureElementRareData()->setChildrenAffectedByHover(value);
2199}
2200
2201void Element::setChildrenAffectedByActive(bool value)
2202{
2203 if (value || hasRareData())
2204 ensureElementRareData()->setChildrenAffectedByActive(value);
2205}
2206
2207void Element::setChildrenAffectedByDrag(bool value)
2208{
2209 if (value || hasRareData())
2210 ensureElementRareData()->setChildrenAffectedByDrag(value);
2211}
2212
2213void Element::setChildrenAffectedByFirstChildRules()
2214{
2215 ensureElementRareData()->setChildrenAffectedByFirstChildRules(true);
2216}
2217
2218void Element::setChildrenAffectedByLastChildRules()
2219{
2220 ensureElementRareData()->setChildrenAffectedByLastChildRules(true);
2221}
2222
2223void Element::setChildrenAffectedByDirectAdjacentRules()
2224{
2225 ensureElementRareData()->setChildrenAffectedByDirectAdjacentRules(true);
2226}
2227
2228void Element::setChildrenAffectedByForwardPositionalRules()
2229{
2230 ensureElementRareData()->setChildrenAffectedByForwardPositionalRules(true);
2231}
2232
2233void Element::setChildrenAffectedByBackwardPositionalRules()
2234{
2235 ensureElementRareData()->setChildrenAffectedByBackwardPositionalRules(true);
2236}
2237
2238void Element::setChildIndex(unsigned index)
2239{
2240 ElementRareData* rareData = ensureElementRareData();
2241 if (RenderStyle* style = renderStyle())
2242 style->setUnique();
2243 rareData->setChildIndex(index);
2244}
2245
2246bool Element::hasFlagsSetDuringStylingOfChildren() const
2247{
2248 if (!hasRareData())
2249 return false;
2250 return rareDataChildrenAffectedByHover()
2251 || rareDataChildrenAffectedByActive()
2252 || rareDataChildrenAffectedByDrag()
2253 || rareDataChildrenAffectedByFirstChildRules()
2254 || rareDataChildrenAffectedByLastChildRules()
2255 || rareDataChildrenAffectedByDirectAdjacentRules()
2256 || rareDataChildrenAffectedByForwardPositionalRules()
2257 || rareDataChildrenAffectedByBackwardPositionalRules();
2258}
2259
2260bool Element::rareDataStyleAffectedByEmpty() const
2261{
2262 ASSERT(hasRareData());
2263 return elementRareData()->styleAffectedByEmpty();
2264}
2265
2266bool Element::rareDataChildrenAffectedByHover() const
2267{
2268 ASSERT(hasRareData());
2269 return elementRareData()->childrenAffectedByHover();
2270}
2271
2272bool Element::rareDataChildrenAffectedByActive() const
2273{
2274 ASSERT(hasRareData());
2275 return elementRareData()->childrenAffectedByActive();
2276}
2277
2278bool Element::rareDataChildrenAffectedByDrag() const
2279{
2280 ASSERT(hasRareData());
2281 return elementRareData()->childrenAffectedByDrag();
2282}
2283
2284bool Element::rareDataChildrenAffectedByFirstChildRules() const
2285{
2286 ASSERT(hasRareData());
2287 return elementRareData()->childrenAffectedByFirstChildRules();
2288}
2289
2290bool Element::rareDataChildrenAffectedByLastChildRules() const
2291{
2292 ASSERT(hasRareData());
2293 return elementRareData()->childrenAffectedByLastChildRules();
2294}
2295
2296bool Element::rareDataChildrenAffectedByDirectAdjacentRules() const
2297{
2298 ASSERT(hasRareData());
2299 return elementRareData()->childrenAffectedByDirectAdjacentRules();
2300}
2301
2302bool Element::rareDataChildrenAffectedByForwardPositionalRules() const
2303{
2304 ASSERT(hasRareData());
2305 return elementRareData()->childrenAffectedByForwardPositionalRules();
2306}
2307
2308bool Element::rareDataChildrenAffectedByBackwardPositionalRules() const
2309{
2310 ASSERT(hasRareData());
2311 return elementRareData()->childrenAffectedByBackwardPositionalRules();
2312}
2313
2314unsigned Element::rareDataChildIndex() const
2315{
2316 ASSERT(hasRareData());
2317 return elementRareData()->childIndex();
2318}
2319
2320void Element::setIsInCanvasSubtree(bool isInCanvasSubtree)
2321{
2322 ensureElementRareData()->setIsInCanvasSubtree(isInCanvasSubtree);
2323}
2324
2325bool Element::isInCanvasSubtree() const
2326{
2327 return hasRareData() && elementRareData()->isInCanvasSubtree();
2328}
2329
2330bool Element::isUnresolvedCustomElement()
2331{
2332 return isCustomElement() && document()->registry()->isUnresolved(this);
2333}
2334
Ben Murdoch591b9582013-07-10 11:41:44 +01002335void Element::setIsInsideRegion(bool value)
2336{
2337 if (value == isInsideRegion())
2338 return;
2339
2340 ensureElementRareData()->setIsInsideRegion(value);
2341}
2342
2343bool Element::isInsideRegion() const
2344{
2345 return hasRareData() ? elementRareData()->isInsideRegion() : false;
2346}
2347
2348void Element::setRegionOversetState(RegionOversetState state)
2349{
2350 ensureElementRareData()->setRegionOversetState(state);
2351}
2352
2353RegionOversetState Element::regionOversetState() const
2354{
2355 return hasRareData() ? elementRareData()->regionOversetState() : RegionUndefined;
2356}
2357
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002358AtomicString Element::computeInheritedLanguage() const
2359{
2360 const Node* n = this;
2361 AtomicString value;
2362 // The language property is inherited, so we iterate over the parents to find the first language.
2363 do {
2364 if (n->isElementNode()) {
2365 if (const ElementData* elementData = toElement(n)->elementData()) {
2366 // Spec: xml:lang takes precedence -- http://www.w3.org/TR/xhtml1/#C_7
2367 if (const Attribute* attribute = elementData->getAttributeItem(XMLNames::langAttr))
2368 value = attribute->value();
2369 else if (const Attribute* attribute = elementData->getAttributeItem(HTMLNames::langAttr))
2370 value = attribute->value();
2371 }
2372 } else if (n->isDocumentNode()) {
2373 // checking the MIME content-language
2374 value = toDocument(n)->contentLanguage();
2375 }
2376
2377 n = n->parentNode();
2378 } while (n && value.isNull());
2379
2380 return value;
2381}
2382
2383Locale& Element::locale() const
2384{
2385 return document()->getCachedLocale(computeInheritedLanguage());
2386}
2387
2388void Element::cancelFocusAppearanceUpdate()
2389{
2390 if (hasRareData())
2391 elementRareData()->setNeedsFocusAppearanceUpdateSoonAfterAttach(false);
2392 if (document()->focusedNode() == this)
2393 document()->cancelFocusAppearanceUpdate();
2394}
2395
2396void Element::normalizeAttributes()
2397{
2398 if (!hasAttributes())
2399 return;
2400 for (unsigned i = 0; i < attributeCount(); ++i) {
2401 if (RefPtr<Attr> attr = attrIfExists(attributeItem(i)->name()))
2402 attr->normalize();
2403 }
2404}
2405
2406void Element::updatePseudoElement(PseudoId pseudoId, StyleChange change)
2407{
2408 PseudoElement* element = pseudoElement(pseudoId);
2409 if (element && (needsStyleRecalc() || shouldRecalcStyle(change, element))) {
2410 // PseudoElement styles hang off their parent element's style so if we needed
2411 // a style recalc we should Force one on the pseudo.
2412 element->recalcStyle(needsStyleRecalc() ? Force : change);
2413
2414 // Wait until our parent is not displayed or pseudoElementRendererIsNeeded
2415 // is false, otherwise we could continously create and destroy PseudoElements
2416 // when RenderObject::isChildAllowed on our parent returns false for the
2417 // PseudoElement's renderer for each style recalc.
2418 if (!renderer() || !pseudoElementRendererIsNeeded(renderer()->getCachedPseudoStyle(pseudoId)))
Torne (Richard Coles)521d96e2013-06-19 11:58:24 +01002419 elementRareData()->setPseudoElement(pseudoId, 0);
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002420 } else if (change >= Inherit || needsStyleRecalc())
2421 createPseudoElementIfNeeded(pseudoId);
2422}
2423
2424void Element::createPseudoElementIfNeeded(PseudoId pseudoId)
2425{
2426 if (!document()->styleSheetCollection()->usesBeforeAfterRules())
2427 return;
2428
2429 if (!renderer() || !pseudoElementRendererIsNeeded(renderer()->getCachedPseudoStyle(pseudoId)))
2430 return;
2431
2432 if (!renderer()->canHaveGeneratedChildren())
2433 return;
2434
2435 ASSERT(!isPseudoElement());
2436 RefPtr<PseudoElement> element = PseudoElement::create(this, pseudoId);
2437 element->attach();
Torne (Richard Coles)521d96e2013-06-19 11:58:24 +01002438 ensureElementRareData()->setPseudoElement(pseudoId, element.release());
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002439}
2440
2441PseudoElement* Element::pseudoElement(PseudoId pseudoId) const
2442{
2443 return hasRareData() ? elementRareData()->pseudoElement(pseudoId) : 0;
2444}
2445
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002446RenderObject* Element::pseudoElementRenderer(PseudoId pseudoId) const
2447{
2448 if (PseudoElement* element = pseudoElement(pseudoId))
2449 return element->renderer();
2450 return 0;
2451}
2452
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002453bool Element::matchesReadOnlyPseudoClass() const
2454{
2455 return false;
2456}
2457
2458bool Element::matchesReadWritePseudoClass() const
2459{
2460 return false;
2461}
2462
2463bool Element::webkitMatchesSelector(const String& selector, ExceptionCode& ec)
2464{
2465 if (selector.isEmpty()) {
2466 ec = SYNTAX_ERR;
2467 return false;
2468 }
2469
2470 SelectorQuery* selectorQuery = document()->selectorQueryCache()->add(selector, document(), ec);
2471 if (!selectorQuery)
2472 return false;
2473 return selectorQuery->matches(this);
2474}
2475
2476bool Element::shouldAppearIndeterminate() const
2477{
2478 return false;
2479}
2480
2481DOMTokenList* Element::classList()
2482{
2483 ElementRareData* data = ensureElementRareData();
2484 if (!data->classList())
2485 data->setClassList(ClassList::create(this));
2486 return data->classList();
2487}
2488
2489DOMStringMap* Element::dataset()
2490{
2491 ElementRareData* data = ensureElementRareData();
2492 if (!data->dataset())
2493 data->setDataset(DatasetDOMStringMap::create(this));
2494 return data->dataset();
2495}
2496
2497KURL Element::getURLAttribute(const QualifiedName& name) const
2498{
2499#if !ASSERT_DISABLED
2500 if (elementData()) {
2501 if (const Attribute* attribute = getAttributeItem(name))
2502 ASSERT(isURLAttribute(*attribute));
2503 }
2504#endif
2505 return document()->completeURL(stripLeadingAndTrailingHTMLSpaces(getAttribute(name)));
2506}
2507
2508KURL Element::getNonEmptyURLAttribute(const QualifiedName& name) const
2509{
2510#if !ASSERT_DISABLED
2511 if (elementData()) {
2512 if (const Attribute* attribute = getAttributeItem(name))
2513 ASSERT(isURLAttribute(*attribute));
2514 }
2515#endif
2516 String value = stripLeadingAndTrailingHTMLSpaces(getAttribute(name));
2517 if (value.isEmpty())
2518 return KURL();
2519 return document()->completeURL(value);
2520}
2521
2522int Element::getIntegralAttribute(const QualifiedName& attributeName) const
2523{
2524 return getAttribute(attributeName).string().toInt();
2525}
2526
2527void Element::setIntegralAttribute(const QualifiedName& attributeName, int value)
2528{
2529 // FIXME: Need an AtomicString version of String::number.
2530 setAttribute(attributeName, String::number(value));
2531}
2532
2533unsigned Element::getUnsignedIntegralAttribute(const QualifiedName& attributeName) const
2534{
2535 return getAttribute(attributeName).string().toUInt();
2536}
2537
2538void Element::setUnsignedIntegralAttribute(const QualifiedName& attributeName, unsigned value)
2539{
2540 // FIXME: Need an AtomicString version of String::number.
2541 setAttribute(attributeName, String::number(value));
2542}
2543
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002544bool Element::childShouldCreateRenderer(const NodeRenderingContext& childContext) const
2545{
2546 // Only create renderers for SVG elements whose parents are SVG elements, or for proper <svg xmlns="svgNS"> subdocuments.
2547 if (childContext.node()->isSVGElement())
2548 return childContext.node()->hasTagName(SVGNames::svgTag) || isSVGElement();
2549
2550 return ContainerNode::childShouldCreateRenderer(childContext);
2551}
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002552
2553void Element::webkitRequestFullscreen()
2554{
Torne (Richard Coles)521d96e2013-06-19 11:58:24 +01002555 FullscreenController::from(document())->requestFullScreenForElement(this, ALLOW_KEYBOARD_INPUT, FullscreenController::EnforceIFrameAllowFullScreenRequirement);
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002556}
2557
2558void Element::webkitRequestFullScreen(unsigned short flags)
2559{
Torne (Richard Coles)521d96e2013-06-19 11:58:24 +01002560 FullscreenController::from(document())->requestFullScreenForElement(this, (flags | LEGACY_MOZILLA_REQUEST), FullscreenController::EnforceIFrameAllowFullScreenRequirement);
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002561}
2562
2563bool Element::containsFullScreenElement() const
2564{
2565 return hasRareData() && elementRareData()->containsFullScreenElement();
2566}
2567
2568void Element::setContainsFullScreenElement(bool flag)
2569{
2570 ensureElementRareData()->setContainsFullScreenElement(flag);
2571 setNeedsStyleRecalc(SyntheticStyleChange);
2572}
2573
2574static Element* parentCrossingFrameBoundaries(Element* element)
2575{
2576 ASSERT(element);
2577 return element->parentElement() ? element->parentElement() : element->document()->ownerElement();
2578}
2579
2580void Element::setContainsFullScreenElementOnAncestorsCrossingFrameBoundaries(bool flag)
2581{
2582 Element* element = this;
2583 while ((element = parentCrossingFrameBoundaries(element)))
2584 element->setContainsFullScreenElement(flag);
2585}
2586
2587bool Element::isInTopLayer() const
2588{
2589 return hasRareData() && elementRareData()->isInTopLayer();
2590}
2591
2592void Element::setIsInTopLayer(bool inTopLayer)
2593{
2594 if (isInTopLayer() == inTopLayer)
2595 return;
2596 ensureElementRareData()->setIsInTopLayer(inTopLayer);
2597
2598 // We must ensure a reattach occurs so the renderer is inserted in the correct sibling order under RenderView according to its
2599 // top layer position, or in its usual place if not in the top layer.
Torne (Richard Coles)93ac45c2013-05-29 14:40:20 +01002600 lazyReattachIfAttached();
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002601}
2602
2603void Element::webkitRequestPointerLock()
2604{
2605 if (document()->page())
2606 document()->page()->pointerLockController()->requestPointerLock(this);
2607}
2608
2609SpellcheckAttributeState Element::spellcheckAttributeState() const
2610{
2611 const AtomicString& value = getAttribute(HTMLNames::spellcheckAttr);
2612 if (value == nullAtom)
2613 return SpellcheckAttributeDefault;
2614 if (equalIgnoringCase(value, "true") || equalIgnoringCase(value, ""))
2615 return SpellcheckAttributeTrue;
2616 if (equalIgnoringCase(value, "false"))
2617 return SpellcheckAttributeFalse;
2618
2619 return SpellcheckAttributeDefault;
2620}
2621
2622bool Element::isSpellCheckingEnabled() const
2623{
2624 for (const Element* element = this; element; element = element->parentOrShadowHostElement()) {
2625 switch (element->spellcheckAttributeState()) {
2626 case SpellcheckAttributeTrue:
2627 return true;
2628 case SpellcheckAttributeFalse:
2629 return false;
2630 case SpellcheckAttributeDefault:
2631 break;
2632 }
2633 }
2634
2635 return true;
2636}
2637
2638RenderRegion* Element::renderRegion() const
2639{
2640 if (renderer() && renderer()->isRenderRegion())
2641 return toRenderRegion(renderer());
2642
2643 return 0;
2644}
2645
Ben Murdoch591b9582013-07-10 11:41:44 +01002646bool Element::shouldMoveToFlowThread(RenderStyle* styleToUse) const
2647{
2648 ASSERT(styleToUse);
2649
2650 if (FullscreenController::isActiveFullScreenElement(this))
2651 return false;
2652
2653 if (isInShadowTree())
2654 return false;
2655
2656 if (styleToUse->flowThread().isEmpty())
2657 return false;
2658
2659 return !isRegisteredWithNamedFlow();
2660}
2661
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002662const AtomicString& Element::webkitRegionOverset() const
2663{
2664 document()->updateLayoutIgnorePendingStylesheets();
2665
2666 DEFINE_STATIC_LOCAL(AtomicString, undefinedState, ("undefined", AtomicString::ConstructFromLiteral));
2667 if (!RuntimeEnabledFeatures::cssRegionsEnabled() || !renderRegion())
2668 return undefinedState;
2669
Ben Murdoch591b9582013-07-10 11:41:44 +01002670 switch (renderRegion()->regionOversetState()) {
2671 case RegionFit: {
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002672 DEFINE_STATIC_LOCAL(AtomicString, fitState, ("fit", AtomicString::ConstructFromLiteral));
2673 return fitState;
2674 }
Ben Murdoch591b9582013-07-10 11:41:44 +01002675 case RegionEmpty: {
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002676 DEFINE_STATIC_LOCAL(AtomicString, emptyState, ("empty", AtomicString::ConstructFromLiteral));
2677 return emptyState;
2678 }
Ben Murdoch591b9582013-07-10 11:41:44 +01002679 case RegionOverset: {
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002680 DEFINE_STATIC_LOCAL(AtomicString, overflowState, ("overset", AtomicString::ConstructFromLiteral));
2681 return overflowState;
2682 }
Ben Murdoch591b9582013-07-10 11:41:44 +01002683 case RegionUndefined:
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002684 return undefinedState;
2685 }
2686
2687 ASSERT_NOT_REACHED();
2688 return undefinedState;
2689}
2690
2691Vector<RefPtr<Range> > Element::webkitGetRegionFlowRanges() const
2692{
2693 document()->updateLayoutIgnorePendingStylesheets();
2694
2695 Vector<RefPtr<Range> > rangeObjects;
2696 if (RuntimeEnabledFeatures::cssRegionsEnabled() && renderer() && renderer()->isRenderRegion()) {
2697 RenderRegion* region = toRenderRegion(renderer());
2698 if (region->isValid())
2699 region->getRanges(rangeObjects);
2700 }
2701
2702 return rangeObjects;
2703}
2704
2705#ifndef NDEBUG
2706bool Element::fastAttributeLookupAllowed(const QualifiedName& name) const
2707{
2708 if (name == HTMLNames::styleAttr)
2709 return false;
2710
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002711 if (isSVGElement())
2712 return !static_cast<const SVGElement*>(this)->isAnimatableAttribute(name);
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002713
2714 return true;
2715}
2716#endif
2717
2718#ifdef DUMP_NODE_STATISTICS
2719bool Element::hasNamedNodeMap() const
2720{
2721 return hasRareData() && elementRareData()->attributeMap();
2722}
2723#endif
2724
2725inline void Element::updateName(const AtomicString& oldName, const AtomicString& newName)
2726{
2727 if (!inDocument() || isInShadowTree())
2728 return;
2729
2730 if (oldName == newName)
2731 return;
2732
2733 if (shouldRegisterAsNamedItem())
2734 updateNamedItemRegistration(oldName, newName);
2735}
2736
2737inline void Element::updateId(const AtomicString& oldId, const AtomicString& newId)
2738{
2739 if (!isInTreeScope())
2740 return;
2741
2742 if (oldId == newId)
2743 return;
2744
2745 updateId(treeScope(), oldId, newId);
2746}
2747
2748inline void Element::updateId(TreeScope* scope, const AtomicString& oldId, const AtomicString& newId)
2749{
2750 ASSERT(isInTreeScope());
2751 ASSERT(oldId != newId);
2752
2753 if (!oldId.isEmpty())
2754 scope->removeElementById(oldId, this);
2755 if (!newId.isEmpty())
2756 scope->addElementById(newId, this);
2757
2758 if (shouldRegisterAsExtraNamedItem())
2759 updateExtraNamedItemRegistration(oldId, newId);
2760}
2761
2762void Element::updateLabel(TreeScope* scope, const AtomicString& oldForAttributeValue, const AtomicString& newForAttributeValue)
2763{
2764 ASSERT(hasTagName(labelTag));
2765
2766 if (!inDocument())
2767 return;
2768
2769 if (oldForAttributeValue == newForAttributeValue)
2770 return;
2771
2772 if (!oldForAttributeValue.isEmpty())
2773 scope->removeLabel(oldForAttributeValue, static_cast<HTMLLabelElement*>(this));
2774 if (!newForAttributeValue.isEmpty())
2775 scope->addLabel(newForAttributeValue, static_cast<HTMLLabelElement*>(this));
2776}
2777
2778void Element::willModifyAttribute(const QualifiedName& name, const AtomicString& oldValue, const AtomicString& newValue)
2779{
2780 if (isIdAttributeName(name))
2781 updateId(oldValue, newValue);
2782 else if (name == HTMLNames::nameAttr)
2783 updateName(oldValue, newValue);
2784 else if (name == HTMLNames::forAttr && hasTagName(labelTag)) {
2785 TreeScope* scope = treeScope();
2786 if (scope->shouldCacheLabelsByForAttribute())
2787 updateLabel(scope, oldValue, newValue);
2788 }
2789
2790 if (oldValue != newValue) {
2791 if (attached() && document()->styleResolver() && document()->styleResolver()->hasSelectorForAttribute(name.localName()))
2792 setNeedsStyleRecalc();
2793 }
2794
2795 if (OwnPtr<MutationObserverInterestGroup> recipients = MutationObserverInterestGroup::createForAttributesMutation(this, name))
2796 recipients->enqueueMutationRecord(MutationRecord::createAttributes(this, name, oldValue));
2797
2798 InspectorInstrumentation::willModifyDOMAttr(document(), this, oldValue, newValue);
2799}
2800
2801void Element::didAddAttribute(const QualifiedName& name, const AtomicString& value)
2802{
2803 attributeChanged(name, value);
2804 InspectorInstrumentation::didModifyDOMAttr(document(), this, name.localName(), value);
2805 dispatchSubtreeModifiedEvent();
2806}
2807
2808void Element::didModifyAttribute(const QualifiedName& name, const AtomicString& value)
2809{
2810 attributeChanged(name, value);
2811 InspectorInstrumentation::didModifyDOMAttr(document(), this, name.localName(), value);
2812 // Do not dispatch a DOMSubtreeModified event here; see bug 81141.
2813}
2814
2815void Element::didRemoveAttribute(const QualifiedName& name)
2816{
2817 attributeChanged(name, nullAtom);
2818 InspectorInstrumentation::didRemoveDOMAttr(document(), this, name.localName());
2819 dispatchSubtreeModifiedEvent();
2820}
2821
2822
2823void Element::updateNamedItemRegistration(const AtomicString& oldName, const AtomicString& newName)
2824{
2825 if (!document()->isHTMLDocument())
2826 return;
2827
2828 if (!oldName.isEmpty())
2829 toHTMLDocument(document())->removeNamedItem(oldName);
2830
2831 if (!newName.isEmpty())
2832 toHTMLDocument(document())->addNamedItem(newName);
2833}
2834
2835void Element::updateExtraNamedItemRegistration(const AtomicString& oldId, const AtomicString& newId)
2836{
2837 if (!document()->isHTMLDocument())
2838 return;
2839
2840 if (!oldId.isEmpty())
2841 toHTMLDocument(document())->removeExtraNamedItem(oldId);
2842
2843 if (!newId.isEmpty())
2844 toHTMLDocument(document())->addExtraNamedItem(newId);
2845}
2846
2847PassRefPtr<HTMLCollection> Element::ensureCachedHTMLCollection(CollectionType type)
2848{
2849 if (HTMLCollection* collection = cachedHTMLCollection(type))
2850 return collection;
2851
2852 RefPtr<HTMLCollection> collection;
2853 if (type == TableRows) {
2854 ASSERT(hasTagName(tableTag));
2855 return ensureRareData()->ensureNodeLists()->addCacheWithAtomicName<HTMLTableRowsCollection>(this, type);
2856 } else if (type == SelectOptions) {
2857 ASSERT(hasTagName(selectTag));
2858 return ensureRareData()->ensureNodeLists()->addCacheWithAtomicName<HTMLOptionsCollection>(this, type);
2859 } else if (type == FormControls) {
2860 ASSERT(hasTagName(formTag) || hasTagName(fieldsetTag));
2861 return ensureRareData()->ensureNodeLists()->addCacheWithAtomicName<HTMLFormControlsCollection>(this, type);
2862 }
2863 return ensureRareData()->ensureNodeLists()->addCacheWithAtomicName<HTMLCollection>(this, type);
2864}
2865
Ben Murdoch591b9582013-07-10 11:41:44 +01002866static void scheduleLayerUpdateCallback(Node* node)
Torne (Richard Coles)93ac45c2013-05-29 14:40:20 +01002867{
Ben Murdoch591b9582013-07-10 11:41:44 +01002868 node->setNeedsLayerUpdate();
Torne (Richard Coles)93ac45c2013-05-29 14:40:20 +01002869}
2870
Ben Murdoch591b9582013-07-10 11:41:44 +01002871void Element::scheduleLayerUpdate()
Torne (Richard Coles)93ac45c2013-05-29 14:40:20 +01002872{
2873 if (postAttachCallbacksAreSuspended())
Ben Murdoch591b9582013-07-10 11:41:44 +01002874 queuePostAttachCallback(scheduleLayerUpdateCallback, this);
Torne (Richard Coles)93ac45c2013-05-29 14:40:20 +01002875 else
Ben Murdoch591b9582013-07-10 11:41:44 +01002876 setNeedsLayerUpdate();
Torne (Richard Coles)93ac45c2013-05-29 14:40:20 +01002877}
2878
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002879HTMLCollection* Element::cachedHTMLCollection(CollectionType type)
2880{
2881 return hasRareData() && rareData()->nodeLists() ? rareData()->nodeLists()->cacheWithAtomicName<HTMLCollection>(type) : 0;
2882}
2883
2884IntSize Element::savedLayerScrollOffset() const
2885{
2886 return hasRareData() ? elementRareData()->savedLayerScrollOffset() : IntSize();
2887}
2888
2889void Element::setSavedLayerScrollOffset(const IntSize& size)
2890{
2891 if (size.isZero() && !hasRareData())
2892 return;
2893 ensureElementRareData()->setSavedLayerScrollOffset(size);
2894}
2895
2896PassRefPtr<Attr> Element::attrIfExists(const QualifiedName& name)
2897{
2898 if (AttrNodeList* attrNodeList = attrNodeListForElement(this))
2899 return findAttrNodeInList(attrNodeList, name);
2900 return 0;
2901}
2902
2903PassRefPtr<Attr> Element::ensureAttr(const QualifiedName& name)
2904{
2905 AttrNodeList* attrNodeList = ensureAttrNodeListForElement(this);
2906 RefPtr<Attr> attrNode = findAttrNodeInList(attrNodeList, name);
2907 if (!attrNode) {
2908 attrNode = Attr::create(this, name);
2909 treeScope()->adoptIfNeeded(attrNode.get());
2910 attrNodeList->append(attrNode);
2911 }
2912 return attrNode.release();
2913}
2914
2915void Element::detachAttrNodeFromElementWithValue(Attr* attrNode, const AtomicString& value)
2916{
2917 ASSERT(hasSyntheticAttrChildNodes());
2918 attrNode->detachFromElementWithValue(value);
2919
2920 AttrNodeList* attrNodeList = attrNodeListForElement(this);
2921 for (unsigned i = 0; i < attrNodeList->size(); ++i) {
2922 if (attrNodeList->at(i)->qualifiedName() == attrNode->qualifiedName()) {
2923 attrNodeList->remove(i);
2924 if (attrNodeList->isEmpty())
2925 removeAttrNodeListForElement(this);
2926 return;
2927 }
2928 }
2929 ASSERT_NOT_REACHED();
2930}
2931
2932void Element::detachAllAttrNodesFromElement()
2933{
2934 AttrNodeList* attrNodeList = attrNodeListForElement(this);
2935 ASSERT(attrNodeList);
2936
2937 for (unsigned i = 0; i < attributeCount(); ++i) {
2938 const Attribute* attribute = attributeItem(i);
2939 if (RefPtr<Attr> attrNode = findAttrNodeInList(attrNodeList, attribute->name()))
2940 attrNode->detachFromElementWithValue(attribute->value());
2941 }
2942
2943 removeAttrNodeListForElement(this);
2944}
2945
2946void Element::willRecalcStyle(StyleChange)
2947{
2948 ASSERT(hasCustomStyleCallbacks());
2949}
2950
2951void Element::didRecalcStyle(StyleChange)
2952{
2953 ASSERT(hasCustomStyleCallbacks());
2954}
2955
2956
2957PassRefPtr<RenderStyle> Element::customStyleForRenderer()
2958{
2959 ASSERT(hasCustomStyleCallbacks());
2960 return 0;
2961}
2962
2963void Element::cloneAttributesFromElement(const Element& other)
2964{
2965 if (hasSyntheticAttrChildNodes())
2966 detachAllAttrNodesFromElement();
2967
2968 other.synchronizeAllAttributes();
2969 if (!other.m_elementData) {
2970 m_elementData.clear();
2971 return;
2972 }
2973
2974 const AtomicString& oldID = getIdAttribute();
2975 const AtomicString& newID = other.getIdAttribute();
2976
2977 if (!oldID.isNull() || !newID.isNull())
2978 updateId(oldID, newID);
2979
2980 const AtomicString& oldName = getNameAttribute();
2981 const AtomicString& newName = other.getNameAttribute();
2982
2983 if (!oldName.isNull() || !newName.isNull())
2984 updateName(oldName, newName);
2985
2986 // If 'other' has a mutable ElementData, convert it to an immutable one so we can share it between both elements.
2987 // We can only do this if there is no CSSOM wrapper for other's inline style, and there are no presentation attributes.
2988 if (other.m_elementData->isUnique()
2989 && !other.m_elementData->presentationAttributeStyle()
2990 && (!other.m_elementData->inlineStyle() || !other.m_elementData->inlineStyle()->hasCSSOMWrapper()))
2991 const_cast<Element&>(other).m_elementData = static_cast<const UniqueElementData*>(other.m_elementData.get())->makeShareableCopy();
2992
2993 if (!other.m_elementData->isUnique())
2994 m_elementData = other.m_elementData;
2995 else
2996 m_elementData = other.m_elementData->makeUniqueCopy();
2997
2998 for (unsigned i = 0; i < m_elementData->length(); ++i) {
2999 const Attribute* attribute = const_cast<const ElementData*>(m_elementData.get())->attributeItem(i);
3000 attributeChangedFromParserOrByCloning(attribute->name(), attribute->value(), ModifiedByCloning);
3001 }
3002}
3003
3004void Element::cloneDataFromElement(const Element& other)
3005{
3006 cloneAttributesFromElement(other);
3007 copyNonAttributePropertiesFromElement(other);
3008}
3009
3010void Element::createUniqueElementData()
3011{
3012 if (!m_elementData)
3013 m_elementData = UniqueElementData::create();
3014 else {
3015 ASSERT(!m_elementData->isUnique());
3016 m_elementData = static_cast<ShareableElementData*>(m_elementData.get())->makeUniqueCopy();
3017 }
3018}
3019
3020void Element::reportMemoryUsage(MemoryObjectInfo* memoryObjectInfo) const
3021{
3022 MemoryClassInfo info(memoryObjectInfo, this, WebCoreMemoryTypes::DOM);
3023 ContainerNode::reportMemoryUsage(memoryObjectInfo);
3024 info.addMember(m_tagName, "tagName");
3025 info.addMember(m_elementData, "elementData");
3026}
3027
Torne (Richard Coles)81a51572013-05-13 16:52:28 +01003028InputMethodContext* Element::getInputContext()
3029{
3030 return ensureElementRareData()->ensureInputMethodContext(toHTMLElement(this));
3031}
3032
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01003033bool Element::hasPendingResources() const
3034{
3035 return hasRareData() && elementRareData()->hasPendingResources();
3036}
3037
3038void Element::setHasPendingResources()
3039{
3040 ensureElementRareData()->setHasPendingResources(true);
3041}
3042
3043void Element::clearHasPendingResources()
3044{
3045 ensureElementRareData()->setHasPendingResources(false);
3046}
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01003047
Ben Murdoch591b9582013-07-10 11:41:44 +01003048struct PresentationAttributeCacheKey {
3049 PresentationAttributeCacheKey() : tagName(0) { }
3050 AtomicStringImpl* tagName;
3051 // Only the values need refcounting.
3052 Vector<pair<AtomicStringImpl*, AtomicString>, 3> attributesAndValues;
3053};
3054
3055struct PresentationAttributeCacheEntry {
3056 WTF_MAKE_FAST_ALLOCATED;
3057public:
3058 PresentationAttributeCacheKey key;
3059 RefPtr<StylePropertySet> value;
3060};
3061
3062typedef HashMap<unsigned, OwnPtr<PresentationAttributeCacheEntry>, AlreadyHashed> PresentationAttributeCache;
3063
3064static bool operator!=(const PresentationAttributeCacheKey& a, const PresentationAttributeCacheKey& b)
3065{
3066 if (a.tagName != b.tagName)
3067 return true;
3068 return a.attributesAndValues != b.attributesAndValues;
3069}
3070
3071static PresentationAttributeCache& presentationAttributeCache()
3072{
3073 DEFINE_STATIC_LOCAL(PresentationAttributeCache, cache, ());
3074 return cache;
3075}
3076
3077class PresentationAttributeCacheCleaner {
3078 WTF_MAKE_NONCOPYABLE(PresentationAttributeCacheCleaner); WTF_MAKE_FAST_ALLOCATED;
3079public:
3080 PresentationAttributeCacheCleaner()
3081 : m_hitCount(0)
3082 , m_cleanTimer(this, &PresentationAttributeCacheCleaner::cleanCache)
3083 {
3084 }
3085
3086 void didHitPresentationAttributeCache()
3087 {
3088 if (presentationAttributeCache().size() < minimumPresentationAttributeCacheSizeForCleaning)
3089 return;
3090
3091 m_hitCount++;
3092
3093 if (!m_cleanTimer.isActive())
3094 m_cleanTimer.startOneShot(presentationAttributeCacheCleanTimeInSeconds);
3095 }
3096
3097private:
3098 static const unsigned presentationAttributeCacheCleanTimeInSeconds = 60;
3099 static const int minimumPresentationAttributeCacheSizeForCleaning = 100;
3100 static const unsigned minimumPresentationAttributeCacheHitCountPerMinute = (100 * presentationAttributeCacheCleanTimeInSeconds) / 60;
3101
3102 void cleanCache(Timer<PresentationAttributeCacheCleaner>* timer)
3103 {
3104 ASSERT_UNUSED(timer, timer == &m_cleanTimer);
3105 unsigned hitCount = m_hitCount;
3106 m_hitCount = 0;
3107 if (hitCount > minimumPresentationAttributeCacheHitCountPerMinute)
3108 return;
3109 presentationAttributeCache().clear();
3110 }
3111
3112 unsigned m_hitCount;
3113 Timer<PresentationAttributeCacheCleaner> m_cleanTimer;
3114};
3115
3116static PresentationAttributeCacheCleaner& presentationAttributeCacheCleaner()
3117{
3118 DEFINE_STATIC_LOCAL(PresentationAttributeCacheCleaner, cleaner, ());
3119 return cleaner;
3120}
3121
3122void Element::synchronizeStyleAttributeInternal() const
3123{
3124 ASSERT(isStyledElement());
3125 ASSERT(elementData());
3126 ASSERT(elementData()->m_styleAttributeIsDirty);
3127 elementData()->m_styleAttributeIsDirty = false;
3128 if (const StylePropertySet* inlineStyle = this->inlineStyle())
3129 const_cast<Element*>(this)->setSynchronizedLazyAttribute(styleAttr, inlineStyle->asText());
3130}
3131
3132CSSStyleDeclaration* Element::style()
3133{
3134 if (!isStyledElement())
3135 return 0;
3136 return ensureMutableInlineStyle()->ensureInlineCSSStyleDeclaration(this);
3137}
3138
3139MutableStylePropertySet* Element::ensureMutableInlineStyle()
3140{
3141 ASSERT(isStyledElement());
3142 RefPtr<StylePropertySet>& inlineStyle = ensureUniqueElementData()->m_inlineStyle;
3143 if (!inlineStyle)
3144 inlineStyle = MutableStylePropertySet::create(strictToCSSParserMode(isHTMLElement() && !document()->inQuirksMode()));
3145 else if (!inlineStyle->isMutable())
3146 inlineStyle = inlineStyle->mutableCopy();
3147 ASSERT(inlineStyle->isMutable());
3148 return static_cast<MutableStylePropertySet*>(inlineStyle.get());
3149}
3150
3151PropertySetCSSStyleDeclaration* Element::inlineStyleCSSOMWrapper()
3152{
3153 if (!inlineStyle() || !inlineStyle()->hasCSSOMWrapper())
3154 return 0;
3155 PropertySetCSSStyleDeclaration* cssomWrapper = ensureMutableInlineStyle()->cssStyleDeclaration();
3156 ASSERT(cssomWrapper && cssomWrapper->parentElement() == this);
3157 return cssomWrapper;
3158}
3159
3160inline void Element::setInlineStyleFromString(const AtomicString& newStyleString)
3161{
3162 ASSERT(isStyledElement());
3163 RefPtr<StylePropertySet>& inlineStyle = elementData()->m_inlineStyle;
3164
3165 // Avoid redundant work if we're using shared attribute data with already parsed inline style.
3166 if (inlineStyle && !elementData()->isUnique())
3167 return;
3168
3169 // We reconstruct the property set instead of mutating if there is no CSSOM wrapper.
3170 // This makes wrapperless property sets immutable and so cacheable.
3171 if (inlineStyle && !inlineStyle->isMutable())
3172 inlineStyle.clear();
3173
3174 if (!inlineStyle) {
3175 inlineStyle = CSSParser::parseInlineStyleDeclaration(newStyleString, this);
3176 } else {
3177 ASSERT(inlineStyle->isMutable());
3178 static_pointer_cast<MutableStylePropertySet>(inlineStyle)->parseDeclaration(newStyleString, document()->elementSheet()->contents());
3179 }
3180}
3181
3182void Element::styleAttributeChanged(const AtomicString& newStyleString, AttributeModificationReason modificationReason)
3183{
3184 ASSERT(isStyledElement());
3185 WTF::OrdinalNumber startLineNumber = WTF::OrdinalNumber::beforeFirst();
3186 if (document() && document()->scriptableDocumentParser() && !document()->isInDocumentWrite())
3187 startLineNumber = document()->scriptableDocumentParser()->lineNumber();
3188
3189 if (newStyleString.isNull()) {
3190 if (PropertySetCSSStyleDeclaration* cssomWrapper = inlineStyleCSSOMWrapper())
3191 cssomWrapper->clearParentElement();
3192 ensureUniqueElementData()->m_inlineStyle.clear();
3193 } else if (modificationReason == ModifiedByCloning || document()->contentSecurityPolicy()->allowInlineStyle(document()->url(), startLineNumber)) {
3194 setInlineStyleFromString(newStyleString);
3195 }
3196
3197 elementData()->m_styleAttributeIsDirty = false;
3198
3199 setNeedsStyleRecalc(InlineStyleChange);
3200 InspectorInstrumentation::didInvalidateStyleAttr(document(), this);
3201}
3202
3203void Element::inlineStyleChanged()
3204{
3205 ASSERT(isStyledElement());
3206 setNeedsStyleRecalc(InlineStyleChange);
3207 ASSERT(elementData());
3208 elementData()->m_styleAttributeIsDirty = true;
3209 InspectorInstrumentation::didInvalidateStyleAttr(document(), this);
3210}
3211
3212bool Element::setInlineStyleProperty(CSSPropertyID propertyID, CSSValueID identifier, bool important)
3213{
3214 ASSERT(isStyledElement());
3215 ensureMutableInlineStyle()->setProperty(propertyID, cssValuePool().createIdentifierValue(identifier), important);
3216 inlineStyleChanged();
3217 return true;
3218}
3219
3220bool Element::setInlineStyleProperty(CSSPropertyID propertyID, CSSPropertyID identifier, bool important)
3221{
3222 ASSERT(isStyledElement());
3223 ensureMutableInlineStyle()->setProperty(propertyID, cssValuePool().createIdentifierValue(identifier), important);
3224 inlineStyleChanged();
3225 return true;
3226}
3227
3228bool Element::setInlineStyleProperty(CSSPropertyID propertyID, double value, CSSPrimitiveValue::UnitTypes unit, bool important)
3229{
3230 ASSERT(isStyledElement());
3231 ensureMutableInlineStyle()->setProperty(propertyID, cssValuePool().createValue(value, unit), important);
3232 inlineStyleChanged();
3233 return true;
3234}
3235
3236bool Element::setInlineStyleProperty(CSSPropertyID propertyID, const String& value, bool important)
3237{
3238 ASSERT(isStyledElement());
3239 bool changes = ensureMutableInlineStyle()->setProperty(propertyID, value, important, document()->elementSheet()->contents());
3240 if (changes)
3241 inlineStyleChanged();
3242 return changes;
3243}
3244
3245bool Element::removeInlineStyleProperty(CSSPropertyID propertyID)
3246{
3247 ASSERT(isStyledElement());
3248 if (!inlineStyle())
3249 return false;
3250 bool changes = ensureMutableInlineStyle()->removeProperty(propertyID);
3251 if (changes)
3252 inlineStyleChanged();
3253 return changes;
3254}
3255
3256void Element::removeAllInlineStyleProperties()
3257{
3258 ASSERT(isStyledElement());
3259 if (!inlineStyle() || inlineStyle()->isEmpty())
3260 return;
3261 ensureMutableInlineStyle()->clear();
3262 inlineStyleChanged();
3263}
3264
3265void Element::addSubresourceAttributeURLs(ListHashSet<KURL>& urls) const
3266{
3267 ASSERT(isStyledElement());
3268 if (const StylePropertySet* inlineStyle = elementData() ? elementData()->inlineStyle() : 0)
3269 inlineStyle->addSubresourceStyleURLs(urls, document()->elementSheet()->contents());
3270}
3271
3272static inline bool attributeNameSort(const pair<AtomicStringImpl*, AtomicString>& p1, const pair<AtomicStringImpl*, AtomicString>& p2)
3273{
3274 // Sort based on the attribute name pointers. It doesn't matter what the order is as long as it is always the same.
3275 return p1.first < p2.first;
3276}
3277
3278void Element::makePresentationAttributeCacheKey(PresentationAttributeCacheKey& result) const
3279{
3280 ASSERT(isStyledElement());
3281 // FIXME: Enable for SVG.
3282 if (namespaceURI() != xhtmlNamespaceURI)
3283 return;
3284 // Interpretation of the size attributes on <input> depends on the type attribute.
3285 if (hasTagName(inputTag))
3286 return;
3287 unsigned size = attributeCount();
3288 for (unsigned i = 0; i < size; ++i) {
3289 const Attribute* attribute = attributeItem(i);
3290 if (!isPresentationAttribute(attribute->name()))
3291 continue;
3292 if (!attribute->namespaceURI().isNull())
3293 return;
3294 // FIXME: Background URL may depend on the base URL and can't be shared. Disallow caching.
3295 if (attribute->name() == backgroundAttr)
3296 return;
3297 result.attributesAndValues.append(std::make_pair(attribute->localName().impl(), attribute->value()));
3298 }
3299 if (result.attributesAndValues.isEmpty())
3300 return;
3301 // Attribute order doesn't matter. Sort for easy equality comparison.
3302 std::sort(result.attributesAndValues.begin(), result.attributesAndValues.end(), attributeNameSort);
3303 // The cache key is non-null when the tagName is set.
3304 result.tagName = localName().impl();
3305}
3306
3307static unsigned computePresentationAttributeCacheHash(const PresentationAttributeCacheKey& key)
3308{
3309 if (!key.tagName)
3310 return 0;
3311 ASSERT(key.attributesAndValues.size());
3312 unsigned attributeHash = StringHasher::hashMemory(key.attributesAndValues.data(), key.attributesAndValues.size() * sizeof(key.attributesAndValues[0]));
3313 return WTF::pairIntHash(key.tagName->existingHash(), attributeHash);
3314}
3315
3316void Element::rebuildPresentationAttributeStyle()
3317{
3318 ASSERT(isStyledElement());
3319 PresentationAttributeCacheKey cacheKey;
3320 makePresentationAttributeCacheKey(cacheKey);
3321
3322 unsigned cacheHash = computePresentationAttributeCacheHash(cacheKey);
3323
3324 PresentationAttributeCache::iterator cacheIterator;
3325 if (cacheHash) {
3326 cacheIterator = presentationAttributeCache().add(cacheHash, nullptr).iterator;
3327 if (cacheIterator->value && cacheIterator->value->key != cacheKey)
3328 cacheHash = 0;
3329 } else {
3330 cacheIterator = presentationAttributeCache().end();
3331 }
3332
3333 RefPtr<StylePropertySet> style;
3334 if (cacheHash && cacheIterator->value) {
3335 style = cacheIterator->value->value;
3336 presentationAttributeCacheCleaner().didHitPresentationAttributeCache();
3337 } else {
3338 style = MutableStylePropertySet::create(isSVGElement() ? SVGAttributeMode : CSSQuirksMode);
3339 unsigned size = attributeCount();
3340 for (unsigned i = 0; i < size; ++i) {
3341 const Attribute* attribute = attributeItem(i);
3342 collectStyleForPresentationAttribute(attribute->name(), attribute->value(), static_cast<MutableStylePropertySet*>(style.get()));
3343 }
3344 }
3345
3346 // ShareableElementData doesn't store presentation attribute style, so make sure we have a UniqueElementData.
3347 UniqueElementData* elementData = ensureUniqueElementData();
3348
3349 elementData->m_presentationAttributeStyleIsDirty = false;
3350 elementData->m_presentationAttributeStyle = style->isEmpty() ? 0 : style;
3351
3352 if (!cacheHash || cacheIterator->value)
3353 return;
3354
3355 OwnPtr<PresentationAttributeCacheEntry> newEntry = adoptPtr(new PresentationAttributeCacheEntry);
3356 newEntry->key = cacheKey;
3357 newEntry->value = style.release();
3358
3359 static const int presentationAttributeCacheMaximumSize = 4096;
3360 if (presentationAttributeCache().size() > presentationAttributeCacheMaximumSize) {
3361 // Start building from scratch if the cache ever gets big.
3362 presentationAttributeCache().clear();
3363 presentationAttributeCache().set(cacheHash, newEntry.release());
3364 } else {
3365 cacheIterator->value = newEntry.release();
3366 }
3367}
3368
3369void Element::addPropertyToPresentationAttributeStyle(MutableStylePropertySet* style, CSSPropertyID propertyID, CSSValueID identifier)
3370{
3371 ASSERT(isStyledElement());
3372 style->setProperty(propertyID, cssValuePool().createIdentifierValue(identifier));
3373}
3374
3375void Element::addPropertyToPresentationAttributeStyle(MutableStylePropertySet* style, CSSPropertyID propertyID, double value, CSSPrimitiveValue::UnitTypes unit)
3376{
3377 ASSERT(isStyledElement());
3378 style->setProperty(propertyID, cssValuePool().createValue(value, unit));
3379}
3380
3381void Element::addPropertyToPresentationAttributeStyle(MutableStylePropertySet* style, CSSPropertyID propertyID, const String& value)
3382{
3383 ASSERT(isStyledElement());
3384 style->setProperty(propertyID, value, false, document()->elementSheet()->contents());
3385}
3386
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01003387void ElementData::deref()
3388{
3389 if (!derefBase())
3390 return;
3391
3392 if (m_isUnique)
3393 delete static_cast<UniqueElementData*>(this);
3394 else
3395 delete static_cast<ShareableElementData*>(this);
3396}
3397
3398ElementData::ElementData()
3399 : m_isUnique(true)
3400 , m_arraySize(0)
3401 , m_presentationAttributeStyleIsDirty(false)
3402 , m_styleAttributeIsDirty(false)
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01003403 , m_animatedSVGAttributesAreDirty(false)
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01003404{
3405}
3406
3407ElementData::ElementData(unsigned arraySize)
3408 : m_isUnique(false)
3409 , m_arraySize(arraySize)
3410 , m_presentationAttributeStyleIsDirty(false)
3411 , m_styleAttributeIsDirty(false)
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01003412 , m_animatedSVGAttributesAreDirty(false)
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01003413{
3414}
3415
3416struct SameSizeAsElementData : public RefCounted<SameSizeAsElementData> {
3417 unsigned bitfield;
3418 void* refPtrs[3];
3419};
3420
3421COMPILE_ASSERT(sizeof(ElementData) == sizeof(SameSizeAsElementData), element_attribute_data_should_stay_small);
3422
3423static size_t sizeForShareableElementDataWithAttributeCount(unsigned count)
3424{
3425 return sizeof(ShareableElementData) + sizeof(Attribute) * count;
3426}
3427
3428PassRefPtr<ShareableElementData> ShareableElementData::createWithAttributes(const Vector<Attribute>& attributes)
3429{
3430 void* slot = WTF::fastMalloc(sizeForShareableElementDataWithAttributeCount(attributes.size()));
3431 return adoptRef(new (slot) ShareableElementData(attributes));
3432}
3433
3434PassRefPtr<UniqueElementData> UniqueElementData::create()
3435{
3436 return adoptRef(new UniqueElementData);
3437}
3438
3439ShareableElementData::ShareableElementData(const Vector<Attribute>& attributes)
3440 : ElementData(attributes.size())
3441{
3442 for (unsigned i = 0; i < m_arraySize; ++i)
3443 new (&m_attributeArray[i]) Attribute(attributes[i]);
3444}
3445
3446ShareableElementData::~ShareableElementData()
3447{
3448 for (unsigned i = 0; i < m_arraySize; ++i)
3449 m_attributeArray[i].~Attribute();
3450}
3451
3452ShareableElementData::ShareableElementData(const UniqueElementData& other)
3453 : ElementData(other, false)
3454{
3455 ASSERT(!other.m_presentationAttributeStyle);
3456
3457 if (other.m_inlineStyle) {
3458 ASSERT(!other.m_inlineStyle->hasCSSOMWrapper());
3459 m_inlineStyle = other.m_inlineStyle->immutableCopyIfNeeded();
3460 }
3461
3462 for (unsigned i = 0; i < m_arraySize; ++i)
3463 new (&m_attributeArray[i]) Attribute(other.m_attributeVector.at(i));
3464}
3465
3466ElementData::ElementData(const ElementData& other, bool isUnique)
3467 : m_isUnique(isUnique)
3468 , m_arraySize(isUnique ? 0 : other.length())
3469 , m_presentationAttributeStyleIsDirty(other.m_presentationAttributeStyleIsDirty)
3470 , m_styleAttributeIsDirty(other.m_styleAttributeIsDirty)
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01003471 , m_animatedSVGAttributesAreDirty(other.m_animatedSVGAttributesAreDirty)
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01003472 , m_classNames(other.m_classNames)
3473 , m_idForStyleResolution(other.m_idForStyleResolution)
3474{
3475 // NOTE: The inline style is copied by the subclass copy constructor since we don't know what to do with it here.
3476}
3477
3478UniqueElementData::UniqueElementData()
3479{
3480}
3481
3482UniqueElementData::UniqueElementData(const UniqueElementData& other)
3483 : ElementData(other, true)
3484 , m_presentationAttributeStyle(other.m_presentationAttributeStyle)
3485 , m_attributeVector(other.m_attributeVector)
3486{
Torne (Richard Coles)93ac45c2013-05-29 14:40:20 +01003487 m_inlineStyle = other.m_inlineStyle ? other.m_inlineStyle->mutableCopy() : 0;
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01003488}
3489
3490UniqueElementData::UniqueElementData(const ShareableElementData& other)
3491 : ElementData(other, true)
3492{
3493 // An ShareableElementData should never have a mutable inline StylePropertySet attached.
3494 ASSERT(!other.m_inlineStyle || !other.m_inlineStyle->isMutable());
3495 m_inlineStyle = other.m_inlineStyle;
3496
3497 m_attributeVector.reserveCapacity(other.length());
3498 for (unsigned i = 0; i < other.length(); ++i)
3499 m_attributeVector.uncheckedAppend(other.m_attributeArray[i]);
3500}
3501
3502PassRefPtr<UniqueElementData> ElementData::makeUniqueCopy() const
3503{
3504 if (isUnique())
3505 return adoptRef(new UniqueElementData(static_cast<const UniqueElementData&>(*this)));
3506 return adoptRef(new UniqueElementData(static_cast<const ShareableElementData&>(*this)));
3507}
3508
3509PassRefPtr<ShareableElementData> UniqueElementData::makeShareableCopy() const
3510{
3511 void* slot = WTF::fastMalloc(sizeForShareableElementDataWithAttributeCount(m_attributeVector.size()));
3512 return adoptRef(new (slot) ShareableElementData(*this));
3513}
3514
3515void UniqueElementData::addAttribute(const QualifiedName& attributeName, const AtomicString& value)
3516{
3517 m_attributeVector.append(Attribute(attributeName, value));
3518}
3519
3520void UniqueElementData::removeAttribute(size_t index)
3521{
3522 ASSERT_WITH_SECURITY_IMPLICATION(index < length());
3523 m_attributeVector.remove(index);
3524}
3525
3526bool ElementData::isEquivalent(const ElementData* other) const
3527{
3528 if (!other)
3529 return isEmpty();
3530
3531 unsigned len = length();
3532 if (len != other->length())
3533 return false;
3534
3535 for (unsigned i = 0; i < len; i++) {
3536 const Attribute* attribute = attributeItem(i);
3537 const Attribute* otherAttr = other->getAttributeItem(attribute->name());
3538 if (!otherAttr || attribute->value() != otherAttr->value())
3539 return false;
3540 }
3541
3542 return true;
3543}
3544
3545void ElementData::reportMemoryUsage(MemoryObjectInfo* memoryObjectInfo) const
3546{
3547 size_t actualSize = m_isUnique ? sizeof(ElementData) : sizeForShareableElementDataWithAttributeCount(m_arraySize);
3548 MemoryClassInfo info(memoryObjectInfo, this, WebCoreMemoryTypes::DOM, actualSize);
3549 info.addMember(m_inlineStyle, "inlineStyle");
3550 info.addMember(m_classNames, "classNames");
3551 info.addMember(m_idForStyleResolution, "idForStyleResolution");
3552 if (m_isUnique) {
3553 const UniqueElementData* uniqueThis = static_cast<const UniqueElementData*>(this);
3554 info.addMember(uniqueThis->m_presentationAttributeStyle, "presentationAttributeStyle");
3555 info.addMember(uniqueThis->m_attributeVector, "attributeVector");
3556 }
3557 for (unsigned i = 0, len = length(); i < len; i++)
3558 info.addMember(*attributeItem(i), "*attributeItem");
3559}
3560
Torne (Richard Coles)e5249552013-05-15 11:35:13 +01003561size_t ElementData::getAttrIndex(Attr* attr) const
3562{
3563 // This relies on the fact that Attr's QualifiedName == the Attribute's name.
3564 for (unsigned i = 0; i < length(); ++i) {
3565 if (attributeItem(i)->name() == attr->qualifiedName())
3566 return i;
3567 }
3568 return notFound;
3569}
3570
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01003571size_t ElementData::getAttributeItemIndexSlowCase(const AtomicString& name, bool shouldIgnoreAttributeCase) const
3572{
3573 // Continue to checking case-insensitively and/or full namespaced names if necessary:
3574 for (unsigned i = 0; i < length(); ++i) {
3575 const Attribute* attribute = attributeItem(i);
3576 if (!attribute->name().hasPrefix()) {
3577 if (shouldIgnoreAttributeCase && equalIgnoringCase(name, attribute->localName()))
3578 return i;
3579 } else {
3580 // FIXME: Would be faster to do this comparison without calling toString, which
3581 // generates a temporary string by concatenation. But this branch is only reached
3582 // if the attribute name has a prefix, which is rare in HTML.
3583 if (equalPossiblyIgnoringCase(name, attribute->name().toString(), shouldIgnoreAttributeCase))
3584 return i;
3585 }
3586 }
3587 return notFound;
3588}
3589
3590Attribute* UniqueElementData::getAttributeItem(const QualifiedName& name)
3591{
3592 for (unsigned i = 0; i < length(); ++i) {
3593 if (m_attributeVector.at(i).name().matches(name))
3594 return &m_attributeVector.at(i);
3595 }
3596 return 0;
3597}
3598
3599Attribute* UniqueElementData::attributeItem(unsigned index)
3600{
3601 ASSERT_WITH_SECURITY_IMPLICATION(index < length());
3602 return &m_attributeVector.at(index);
3603}
3604
3605} // namespace WebCore