blob: ab7a395c42c2543f781360ad34f682294a3091b9 [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"
Ben Murdoche69819b2013-07-17 14:56:49 +010045#include "core/dom/CustomElementRegistrationContext.h"
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +010046#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);
Ben Murdoche69819b2013-07-17 14:56:49 +0100208 data->setPseudoElement(BACKDROP, 0);
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100209 data->clearShadow();
210 }
211
Ben Murdoche69819b2013-07-17 14:56:49 +0100212 if (isCustomElement() && document() && document()->registrationContext())
213 document()->registrationContext()->customElementIsBeingDestroyed(this);
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100214
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
Ben Murdoche69819b2013-07-17 14:56:49 +0100269 // callsites like Document::setFocusedElement that would currently fail on
Torne (Richard Coles)521d96e2013-06-19 11:58:24 +0100270 // 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)) {
Ben Murdoche69819b2013-07-17 14:56:49 +0100826 ec = InvalidCharacterError;
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100827 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();
Ben Murdoche69819b2013-07-17 14:56:49 +0100910 bool testShouldInvalidateStyle = attached() && styleResolver && styleChangeType() < SubtreeStyleChange;
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100911 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;
Ben Murdoche69819b2013-07-17 14:56:49 +0100917 setNeedsStyleRecalc(LocalStyleChange);
Ben Murdoch591b9582013-07-10 11:41:44 +0100918 }
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{
Ben Murdoche69819b2013-07-17 14:56:49 +0100949 if (name == isAttr)
950 document()->registrationContext()->didGiveTypeExtension(this, newValue);
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100951 attributeChanged(name, newValue, reason);
952}
953
954template <typename CharacterType>
955static inline bool classStringHasClassName(const CharacterType* characters, unsigned length)
956{
957 ASSERT(length > 0);
958
959 unsigned i = 0;
960 do {
961 if (isNotHTMLSpace(characters[i]))
962 break;
963 ++i;
964 } while (i < length);
965
966 return i < length;
967}
968
969static inline bool classStringHasClassName(const AtomicString& newClassString)
970{
971 unsigned length = newClassString.length();
972
973 if (!length)
974 return false;
975
976 if (newClassString.is8Bit())
977 return classStringHasClassName(newClassString.characters8(), length);
978 return classStringHasClassName(newClassString.characters16(), length);
979}
980
981template<typename Checker>
982static bool checkSelectorForClassChange(const SpaceSplitString& changedClasses, const Checker& checker)
983{
984 unsigned changedSize = changedClasses.size();
985 for (unsigned i = 0; i < changedSize; ++i) {
986 if (checker.hasSelectorForClass(changedClasses[i]))
987 return true;
988 }
989 return false;
990}
991
992template<typename Checker>
993static bool checkSelectorForClassChange(const SpaceSplitString& oldClasses, const SpaceSplitString& newClasses, const Checker& checker)
994{
995 unsigned oldSize = oldClasses.size();
996 if (!oldSize)
997 return checkSelectorForClassChange(newClasses, checker);
998 BitVector remainingClassBits;
999 remainingClassBits.ensureSize(oldSize);
1000 // Class vectors tend to be very short. This is faster than using a hash table.
1001 unsigned newSize = newClasses.size();
1002 for (unsigned i = 0; i < newSize; ++i) {
1003 for (unsigned j = 0; j < oldSize; ++j) {
1004 if (newClasses[i] == oldClasses[j]) {
1005 remainingClassBits.quickSet(j);
1006 continue;
1007 }
1008 }
1009 if (checker.hasSelectorForClass(newClasses[i]))
1010 return true;
1011 }
1012 for (unsigned i = 0; i < oldSize; ++i) {
1013 // If the bit is not set the the corresponding class has been removed.
1014 if (remainingClassBits.quickGet(i))
1015 continue;
1016 if (checker.hasSelectorForClass(oldClasses[i]))
1017 return true;
1018 }
1019 return false;
1020}
1021
1022void Element::classAttributeChanged(const AtomicString& newClassString)
1023{
1024 StyleResolver* styleResolver = document()->styleResolverIfExists();
Ben Murdoche69819b2013-07-17 14:56:49 +01001025 bool testShouldInvalidateStyle = attached() && styleResolver && styleChangeType() < SubtreeStyleChange;
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001026 bool shouldInvalidateStyle = false;
1027
1028 if (classStringHasClassName(newClassString)) {
1029 const bool shouldFoldCase = document()->inQuirksMode();
1030 const SpaceSplitString oldClasses = elementData()->classNames();
1031 elementData()->setClass(newClassString, shouldFoldCase);
1032 const SpaceSplitString& newClasses = elementData()->classNames();
1033 shouldInvalidateStyle = testShouldInvalidateStyle && checkSelectorForClassChange(oldClasses, newClasses, *styleResolver);
1034 } else {
1035 const SpaceSplitString& oldClasses = elementData()->classNames();
1036 shouldInvalidateStyle = testShouldInvalidateStyle && checkSelectorForClassChange(oldClasses, *styleResolver);
1037 elementData()->clearClass();
1038 }
1039
1040 if (hasRareData())
1041 elementRareData()->clearClassListValueForQuirksMode();
1042
1043 if (shouldInvalidateStyle)
1044 setNeedsStyleRecalc();
1045}
1046
1047bool Element::shouldInvalidateDistributionWhenAttributeChanged(ElementShadow* elementShadow, const QualifiedName& name, const AtomicString& newValue)
1048{
1049 ASSERT(elementShadow);
1050 const SelectRuleFeatureSet& featureSet = elementShadow->distributor().ensureSelectFeatureSet(elementShadow);
1051
1052 if (isIdAttributeName(name)) {
1053 AtomicString oldId = elementData()->idForStyleResolution();
1054 AtomicString newId = makeIdForStyleResolution(newValue, document()->inQuirksMode());
1055 if (newId != oldId) {
1056 if (!oldId.isEmpty() && featureSet.hasSelectorForId(oldId))
1057 return true;
1058 if (!newId.isEmpty() && featureSet.hasSelectorForId(newId))
1059 return true;
1060 }
1061 }
1062
1063 if (name == HTMLNames::classAttr) {
1064 const AtomicString& newClassString = newValue;
1065 if (classStringHasClassName(newClassString)) {
1066 const bool shouldFoldCase = document()->inQuirksMode();
1067 const SpaceSplitString& oldClasses = elementData()->classNames();
1068 const SpaceSplitString newClasses(newClassString, shouldFoldCase);
1069 if (checkSelectorForClassChange(oldClasses, newClasses, featureSet))
1070 return true;
1071 } else {
1072 const SpaceSplitString& oldClasses = elementData()->classNames();
1073 if (checkSelectorForClassChange(oldClasses, featureSet))
1074 return true;
1075 }
1076 }
1077
1078 return featureSet.hasSelectorForAttribute(name.localName());
1079}
1080
1081// Returns true is the given attribute is an event handler.
1082// We consider an event handler any attribute that begins with "on".
1083// It is a simple solution that has the advantage of not requiring any
1084// code or configuration change if a new event handler is defined.
1085
1086static inline bool isEventHandlerAttribute(const Attribute& attribute)
1087{
1088 return attribute.name().namespaceURI().isNull() && attribute.name().localName().startsWith("on");
1089}
1090
1091bool Element::isJavaScriptURLAttribute(const Attribute& attribute) const
1092{
1093 return isURLAttribute(attribute) && protocolIsJavaScript(stripLeadingAndTrailingHTMLSpaces(attribute.value()));
1094}
1095
1096void Element::stripScriptingAttributes(Vector<Attribute>& attributeVector) const
1097{
1098 size_t destination = 0;
1099 for (size_t source = 0; source < attributeVector.size(); ++source) {
1100 if (isEventHandlerAttribute(attributeVector[source])
1101 || isJavaScriptURLAttribute(attributeVector[source])
1102 || isHTMLContentAttribute(attributeVector[source]))
1103 continue;
1104
1105 if (source != destination)
1106 attributeVector[destination] = attributeVector[source];
1107
1108 ++destination;
1109 }
1110 attributeVector.shrink(destination);
1111}
1112
1113void Element::parserSetAttributes(const Vector<Attribute>& attributeVector)
1114{
1115 ASSERT(!inDocument());
1116 ASSERT(!parentNode());
1117 ASSERT(!m_elementData);
1118
1119 if (attributeVector.isEmpty())
1120 return;
1121
1122 if (document() && document()->sharedObjectPool())
1123 m_elementData = document()->sharedObjectPool()->cachedShareableElementDataWithAttributes(attributeVector);
1124 else
1125 m_elementData = ShareableElementData::createWithAttributes(attributeVector);
1126
1127 // Use attributeVector instead of m_elementData because attributeChanged might modify m_elementData.
1128 for (unsigned i = 0; i < attributeVector.size(); ++i)
1129 attributeChangedFromParserOrByCloning(attributeVector[i].name(), attributeVector[i].value(), ModifiedDirectly);
1130}
1131
1132bool Element::hasAttributes() const
1133{
1134 synchronizeAllAttributes();
1135 return elementData() && elementData()->length();
1136}
1137
1138bool Element::hasEquivalentAttributes(const Element* other) const
1139{
1140 synchronizeAllAttributes();
1141 other->synchronizeAllAttributes();
1142 if (elementData() == other->elementData())
1143 return true;
1144 if (elementData())
1145 return elementData()->isEquivalent(other->elementData());
1146 if (other->elementData())
1147 return other->elementData()->isEquivalent(elementData());
1148 return true;
1149}
1150
1151String Element::nodeName() const
1152{
1153 return m_tagName.toString();
1154}
1155
1156String Element::nodeNamePreservingCase() const
1157{
1158 return m_tagName.toString();
1159}
1160
1161void Element::setPrefix(const AtomicString& prefix, ExceptionCode& ec)
1162{
1163 ec = 0;
1164 checkSetPrefix(prefix, ec);
1165 if (ec)
1166 return;
1167
1168 m_tagName.setPrefix(prefix.isEmpty() ? AtomicString() : prefix);
1169}
1170
1171KURL Element::baseURI() const
1172{
1173 const AtomicString& baseAttribute = getAttribute(baseAttr);
1174 KURL base(KURL(), baseAttribute);
1175 if (!base.protocol().isEmpty())
1176 return base;
1177
1178 ContainerNode* parent = parentNode();
1179 if (!parent)
1180 return base;
1181
1182 const KURL& parentBase = parent->baseURI();
1183 if (parentBase.isNull())
1184 return base;
1185
1186 return KURL(parentBase, baseAttribute);
1187}
1188
1189const AtomicString& Element::imageSourceURL() const
1190{
1191 return getAttribute(srcAttr);
1192}
1193
1194bool Element::rendererIsNeeded(const NodeRenderingContext& context)
1195{
1196 return context.style()->display() != NONE;
1197}
1198
Ben Murdoch591b9582013-07-10 11:41:44 +01001199RenderObject* Element::createRenderer(RenderStyle* style)
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001200{
1201 return RenderObject::createObject(this, style);
1202}
1203
1204#if ENABLE(INPUT_MULTIPLE_FIELDS_UI)
Torne (Richard Coles)5267f702013-06-11 10:57:24 +01001205bool Element::isDateTimeEditElement() const
1206{
1207 return false;
1208}
1209
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001210bool Element::isDateTimeFieldElement() const
1211{
1212 return false;
1213}
Torne (Richard Coles)5267f702013-06-11 10:57:24 +01001214
1215bool Element::isPickerIndicatorElement() const
1216{
1217 return false;
1218}
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001219#endif
1220
Torne (Richard Coles)5267f702013-06-11 10:57:24 +01001221bool Element::isClearButtonElement() const
1222{
1223 return false;
1224}
1225
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001226bool Element::wasChangedSinceLastFormControlChangeEvent() const
1227{
1228 return false;
1229}
1230
1231void Element::setChangedSinceLastFormControlChangeEvent(bool)
1232{
1233}
1234
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001235bool Element::isInert() const
1236{
Torne (Richard Coles)93ac45c2013-05-29 14:40:20 +01001237 const Element* dialog = document()->activeModalDialog();
Ben Murdoch591b9582013-07-10 11:41:44 +01001238 if (dialog && !containsIncludingShadowDOM(dialog) && !dialog->containsIncludingShadowDOM(this))
1239 return true;
1240 return document()->ownerElement() && document()->ownerElement()->isInert();
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001241}
1242
1243Node::InsertionNotificationRequest Element::insertedInto(ContainerNode* insertionPoint)
1244{
1245 // need to do superclass processing first so inDocument() is true
1246 // by the time we reach updateId
1247 ContainerNode::insertedInto(insertionPoint);
1248
1249 if (containsFullScreenElement() && parentElement() && !parentElement()->containsFullScreenElement())
1250 setContainsFullScreenElementOnAncestorsCrossingFrameBoundaries(true);
1251
1252 if (Element* before = pseudoElement(BEFORE))
1253 before->insertedInto(insertionPoint);
1254
1255 if (Element* after = pseudoElement(AFTER))
1256 after->insertedInto(insertionPoint);
1257
1258 if (!insertionPoint->isInTreeScope())
1259 return InsertionDone;
1260
1261 if (hasRareData())
1262 elementRareData()->clearClassListValueForQuirksMode();
1263
1264 TreeScope* scope = insertionPoint->treeScope();
1265 if (scope != treeScope())
1266 return InsertionDone;
1267
Ben Murdoche69819b2013-07-17 14:56:49 +01001268 if (isUpgradedCustomElement())
1269 document()->registrationContext()->customElementDidEnterDocument(this);
1270
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001271 const AtomicString& idValue = getIdAttribute();
1272 if (!idValue.isNull())
1273 updateId(scope, nullAtom, idValue);
1274
1275 const AtomicString& nameValue = getNameAttribute();
1276 if (!nameValue.isNull())
1277 updateName(nullAtom, nameValue);
1278
1279 if (hasTagName(labelTag)) {
1280 if (scope->shouldCacheLabelsByForAttribute())
1281 updateLabel(scope, nullAtom, fastGetAttribute(forAttr));
1282 }
1283
1284 return InsertionDone;
1285}
1286
1287void Element::removedFrom(ContainerNode* insertionPoint)
1288{
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001289 bool wasInDocument = insertionPoint->document();
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001290
1291 if (Element* before = pseudoElement(BEFORE))
1292 before->removedFrom(insertionPoint);
1293
1294 if (Element* after = pseudoElement(AFTER))
1295 after->removedFrom(insertionPoint);
1296
Ben Murdoche69819b2013-07-17 14:56:49 +01001297 if (Element* backdrop = pseudoElement(BACKDROP))
1298 backdrop->removedFrom(insertionPoint);
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001299 document()->removeFromTopLayer(this);
Ben Murdoche69819b2013-07-17 14:56:49 +01001300
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001301 if (containsFullScreenElement())
1302 setContainsFullScreenElementOnAncestorsCrossingFrameBoundaries(false);
1303
1304 if (document()->page())
1305 document()->page()->pointerLockController()->elementRemoved(this);
1306
1307 setSavedLayerScrollOffset(IntSize());
1308
1309 if (insertionPoint->isInTreeScope() && treeScope() == document()) {
1310 const AtomicString& idValue = getIdAttribute();
1311 if (!idValue.isNull())
1312 updateId(insertionPoint->treeScope(), idValue, nullAtom);
1313
1314 const AtomicString& nameValue = getNameAttribute();
1315 if (!nameValue.isNull())
1316 updateName(nameValue, nullAtom);
1317
1318 if (hasTagName(labelTag)) {
1319 TreeScope* treeScope = insertionPoint->treeScope();
1320 if (treeScope->shouldCacheLabelsByForAttribute())
1321 updateLabel(treeScope, fastGetAttribute(forAttr), nullAtom);
1322 }
1323 }
1324
1325 ContainerNode::removedFrom(insertionPoint);
Ben Murdoche69819b2013-07-17 14:56:49 +01001326 if (wasInDocument) {
1327 if (hasPendingResources())
1328 document()->accessSVGExtensions()->removeElementFromPendingResources(this);
1329
1330 if (isUpgradedCustomElement() && document()->registrationContext())
1331 document()->registrationContext()->customElementDidLeaveDocument(this);
1332 }
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001333}
1334
Torne (Richard Coles)521d96e2013-06-19 11:58:24 +01001335void Element::createRendererIfNeeded(const AttachContext& context)
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001336{
Torne (Richard Coles)521d96e2013-06-19 11:58:24 +01001337 NodeRenderingContext(this, context).createRendererForElementIfNeeded();
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001338}
1339
Torne (Richard Coles)521d96e2013-06-19 11:58:24 +01001340void Element::attach(const AttachContext& context)
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001341{
1342 PostAttachCallbackDisabler callbackDisabler(this);
1343 StyleResolverParentPusher parentPusher(this);
1344 WidgetHierarchyUpdatesSuspensionScope suspendWidgetHierarchyUpdates;
1345
Torne (Richard Coles)521d96e2013-06-19 11:58:24 +01001346 createRendererIfNeeded(context);
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001347
1348 if (parentElement() && parentElement()->isInCanvasSubtree())
1349 setIsInCanvasSubtree(true);
1350
1351 createPseudoElementIfNeeded(BEFORE);
1352
1353 // When a shadow root exists, it does the work of attaching the children.
1354 if (ElementShadow* shadow = this->shadow()) {
1355 parentPusher.push();
Ben Murdoch591b9582013-07-10 11:41:44 +01001356 shadow->attach(context);
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001357 } else if (firstChild())
1358 parentPusher.push();
1359
Torne (Richard Coles)521d96e2013-06-19 11:58:24 +01001360 ContainerNode::attach(context);
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001361
1362 createPseudoElementIfNeeded(AFTER);
Ben Murdoche69819b2013-07-17 14:56:49 +01001363 createPseudoElementIfNeeded(BACKDROP);
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001364
Ben Murdoch591b9582013-07-10 11:41:44 +01001365 if (hasRareData()) {
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001366 ElementRareData* data = elementRareData();
1367 if (data->needsFocusAppearanceUpdateSoonAfterAttach()) {
1368 if (isFocusable() && document()->focusedNode() == this)
1369 document()->updateFocusAppearanceSoon(false /* don't restore selection */);
1370 data->setNeedsFocusAppearanceUpdateSoonAfterAttach(false);
1371 }
1372 }
Ben Murdoch591b9582013-07-10 11:41:44 +01001373
1374 // FIXME: It doesn't appear safe to call didRecalculateStyleForElement when
1375 // not in a Document::recalcStyle. Since we're hopefully going to always
1376 // lazyAttach in the future that problem should go away.
1377 if (document()->inStyleRecalc())
1378 InspectorInstrumentation::didRecalculateStyleForElement(this);
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001379}
1380
1381void Element::unregisterNamedFlowContentNode()
1382{
1383 if (RuntimeEnabledFeatures::cssRegionsEnabled() && inNamedFlow() && document()->renderView())
1384 document()->renderView()->flowThreadController()->unregisterNamedFlowContentNode(this);
1385}
1386
Torne (Richard Coles)521d96e2013-06-19 11:58:24 +01001387void Element::detach(const AttachContext& context)
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001388{
1389 WidgetHierarchyUpdatesSuspensionScope suspendWidgetHierarchyUpdates;
1390 unregisterNamedFlowContentNode();
1391 cancelFocusAppearanceUpdate();
1392 if (hasRareData()) {
1393 ElementRareData* data = elementRareData();
1394 data->setPseudoElement(BEFORE, 0);
1395 data->setPseudoElement(AFTER, 0);
Ben Murdoche69819b2013-07-17 14:56:49 +01001396 data->setPseudoElement(BACKDROP, 0);
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001397 data->setIsInCanvasSubtree(false);
1398 data->resetComputedStyle();
1399 data->resetDynamicRestyleObservations();
Ben Murdoch591b9582013-07-10 11:41:44 +01001400 data->setIsInsideRegion(false);
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001401 }
Ben Murdoch591b9582013-07-10 11:41:44 +01001402 if (ElementShadow* shadow = this->shadow())
1403 shadow->detach(context);
Torne (Richard Coles)521d96e2013-06-19 11:58:24 +01001404 ContainerNode::detach(context);
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001405}
1406
1407bool Element::pseudoStyleCacheIsInvalid(const RenderStyle* currentStyle, RenderStyle* newStyle)
1408{
1409 ASSERT(currentStyle == renderStyle());
1410 ASSERT(renderer());
1411
1412 if (!currentStyle)
1413 return false;
1414
1415 const PseudoStyleCache* pseudoStyleCache = currentStyle->cachedPseudoStyles();
1416 if (!pseudoStyleCache)
1417 return false;
1418
1419 size_t cacheSize = pseudoStyleCache->size();
1420 for (size_t i = 0; i < cacheSize; ++i) {
1421 RefPtr<RenderStyle> newPseudoStyle;
1422 PseudoId pseudoId = pseudoStyleCache->at(i)->styleType();
1423 if (pseudoId == FIRST_LINE || pseudoId == FIRST_LINE_INHERITED)
1424 newPseudoStyle = renderer()->uncachedFirstLineStyle(newStyle);
1425 else
1426 newPseudoStyle = renderer()->getUncachedPseudoStyle(PseudoStyleRequest(pseudoId), newStyle, newStyle);
1427 if (!newPseudoStyle)
1428 return true;
1429 if (*newPseudoStyle != *pseudoStyleCache->at(i)) {
1430 if (pseudoId < FIRST_INTERNAL_PSEUDOID)
1431 newStyle->setHasPseudoStyle(pseudoId);
1432 newStyle->addCachedPseudoStyle(newPseudoStyle);
1433 if (pseudoId == FIRST_LINE || pseudoId == FIRST_LINE_INHERITED) {
1434 // FIXME: We should do an actual diff to determine whether a repaint vs. layout
1435 // is needed, but for now just assume a layout will be required. The diff code
1436 // in RenderObject::setStyle would need to be factored out so that it could be reused.
1437 renderer()->setNeedsLayoutAndPrefWidthsRecalc();
1438 }
1439 return true;
1440 }
1441 }
1442 return false;
1443}
1444
Torne (Richard Coles)521d96e2013-06-19 11:58:24 +01001445PassRefPtr<RenderStyle> Element::styleForRenderer()
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001446{
1447 if (hasCustomStyleCallbacks()) {
1448 if (RefPtr<RenderStyle> style = customStyleForRenderer())
1449 return style.release();
1450 }
1451
Torne (Richard Coles)521d96e2013-06-19 11:58:24 +01001452 return originalStyleForRenderer();
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001453}
1454
Torne (Richard Coles)521d96e2013-06-19 11:58:24 +01001455PassRefPtr<RenderStyle> Element::originalStyleForRenderer()
Torne (Richard Coles)5267f702013-06-11 10:57:24 +01001456{
Torne (Richard Coles)521d96e2013-06-19 11:58:24 +01001457 return document()->styleResolver()->styleForElement(this);
Torne (Richard Coles)5267f702013-06-11 10:57:24 +01001458}
1459
Ben Murdoche69819b2013-07-17 14:56:49 +01001460bool Element::recalcStyle(StyleChange change)
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001461{
Torne (Richard Coles)93ac45c2013-05-29 14:40:20 +01001462 ASSERT(document()->inStyleRecalc());
1463
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001464 if (hasCustomStyleCallbacks())
1465 willRecalcStyle(change);
1466
1467 // Ref currentStyle in case it would otherwise be deleted when setting the new style in the renderer.
1468 RefPtr<RenderStyle> currentStyle(renderStyle());
1469 bool hasParentStyle = parentNodeForRenderingAndStyle() ? static_cast<bool>(parentNodeForRenderingAndStyle()->renderStyle()) : false;
1470 bool hasDirectAdjacentRules = childrenAffectedByDirectAdjacentRules();
1471 bool hasIndirectAdjacentRules = childrenAffectedByForwardPositionalRules();
1472
1473 if ((change > NoChange || needsStyleRecalc())) {
1474 if (hasRareData())
1475 elementRareData()->resetComputedStyle();
1476 }
1477 if (hasParentStyle && (change >= Inherit || needsStyleRecalc())) {
1478 StyleChange localChange = Detach;
1479 RefPtr<RenderStyle> newStyle;
1480 if (currentStyle) {
1481 // FIXME: This still recalcs style twice when changing display types, but saves
1482 // us from recalcing twice when going from none -> anything else which is more
1483 // common, especially during lazy attach.
Torne (Richard Coles)521d96e2013-06-19 11:58:24 +01001484 newStyle = styleForRenderer();
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001485 localChange = Node::diff(currentStyle.get(), newStyle.get(), document());
Torne (Richard Coles)521d96e2013-06-19 11:58:24 +01001486 } else if (attached() && isActiveInsertionPoint(this)) {
1487 // Active InsertionPoints will never have renderers so there's no reason to
1488 // reattach them repeatedly once they're already attached.
1489 localChange = change;
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001490 }
1491 if (localChange == Detach) {
Torne (Richard Coles)521d96e2013-06-19 11:58:24 +01001492 AttachContext reattachContext;
1493 reattachContext.resolvedStyle = newStyle.get();
1494 reattach(reattachContext);
1495
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001496 // attach recalculates the style for all children. No need to do it twice.
1497 clearNeedsStyleRecalc();
1498 clearChildNeedsStyleRecalc();
1499
1500 if (hasCustomStyleCallbacks())
1501 didRecalcStyle(change);
Ben Murdoche69819b2013-07-17 14:56:49 +01001502 return true;
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001503 }
1504
Ben Murdoch591b9582013-07-10 11:41:44 +01001505 InspectorInstrumentation::didRecalculateStyleForElement(this);
1506
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001507 if (RenderObject* renderer = this->renderer()) {
Ben Murdoche69819b2013-07-17 14:56:49 +01001508 if (localChange != NoChange || pseudoStyleCacheIsInvalid(currentStyle.get(), newStyle.get()) || (change == Force && renderer->requiresForcedStyleRecalcPropagation()) || shouldNotifyRendererWithIdenticalStyles())
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001509 renderer->setAnimatableStyle(newStyle.get());
1510 else if (needsStyleRecalc()) {
1511 // Although no change occurred, we use the new style so that the cousin style sharing code won't get
1512 // fooled into believing this style is the same.
1513 renderer->setStyleInternal(newStyle.get());
1514 }
1515 }
1516
1517 // 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
1518 // 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).
1519 if (document()->styleSheetCollection()->usesRemUnits() && document()->documentElement() == this && localChange != NoChange && currentStyle && newStyle && currentStyle->fontSize() != newStyle->fontSize()) {
1520 // Cached RenderStyles may depend on the re units.
1521 document()->styleResolver()->invalidateMatchedPropertiesCache();
1522 change = Force;
1523 }
1524
Ben Murdoche69819b2013-07-17 14:56:49 +01001525 if (styleChangeType() == SubtreeStyleChange)
Torne (Richard Coles)e5249552013-05-15 11:35:13 +01001526 change = Force;
1527 else if (change != Force)
1528 change = localChange;
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001529 }
1530 StyleResolverParentPusher parentPusher(this);
1531
1532 // FIXME: This does not care about sibling combinators. Will be necessary in XBL2 world.
1533 if (ElementShadow* shadow = this->shadow()) {
1534 if (shouldRecalcStyle(change, shadow)) {
1535 parentPusher.push();
1536 shadow->recalcStyle(change);
1537 }
1538 }
1539
1540 if (shouldRecalcStyle(change, this))
1541 updatePseudoElement(BEFORE, change);
1542
1543 // FIXME: This check is good enough for :hover + foo, but it is not good enough for :hover + foo + bar.
1544 // For now we will just worry about the common case, since it's a lot trickier to get the second case right
1545 // without doing way too much re-resolution.
1546 bool forceCheckOfNextElementSibling = false;
1547 bool forceCheckOfAnyElementSibling = false;
Ben Murdoche69819b2013-07-17 14:56:49 +01001548 bool forceReattachOfAnyWhitespaceSibling = false;
1549 for (Node* child = firstChild(); child; child = child->nextSibling()) {
1550 bool didReattach = false;
1551
1552 if (child->renderer())
1553 forceReattachOfAnyWhitespaceSibling = false;
1554
1555 if (child->isTextNode()) {
1556 if (forceReattachOfAnyWhitespaceSibling && toText(child)->containsOnlyWhitespace())
1557 child->reattach();
1558 else
1559 didReattach = toText(child)->recalcTextStyle(change);
1560 } else if (child->isElementNode()) {
1561 Element* element = toElement(child);
1562
1563 if (forceCheckOfNextElementSibling || forceCheckOfAnyElementSibling)
1564 element->setNeedsStyleRecalc();
1565
1566 bool childRulesChanged = element->needsStyleRecalc() && element->styleChangeType() == SubtreeStyleChange;
1567 forceCheckOfNextElementSibling = childRulesChanged && hasDirectAdjacentRules;
1568 forceCheckOfAnyElementSibling = forceCheckOfAnyElementSibling || (childRulesChanged && hasIndirectAdjacentRules);
1569
1570 if (shouldRecalcStyle(change, element)) {
1571 parentPusher.push();
1572 didReattach = element->recalcStyle(change);
1573 }
Ben Murdoch591b9582013-07-10 11:41:44 +01001574 }
Ben Murdoche69819b2013-07-17 14:56:49 +01001575
1576 forceReattachOfAnyWhitespaceSibling = didReattach || forceReattachOfAnyWhitespaceSibling;
Torne (Richard Coles)5267f702013-06-11 10:57:24 +01001577 }
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001578
1579 if (shouldRecalcStyle(change, this))
1580 updatePseudoElement(AFTER, change);
1581
1582 clearNeedsStyleRecalc();
1583 clearChildNeedsStyleRecalc();
Ben Murdoch591b9582013-07-10 11:41:44 +01001584
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001585 if (hasCustomStyleCallbacks())
1586 didRecalcStyle(change);
Ben Murdoche69819b2013-07-17 14:56:49 +01001587 return false;
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001588}
1589
1590ElementShadow* Element::shadow() const
1591{
1592 return hasRareData() ? elementRareData()->shadow() : 0;
1593}
1594
1595ElementShadow* Element::ensureShadow()
1596{
1597 return ensureElementRareData()->ensureShadow();
1598}
1599
1600void Element::didAffectSelector(AffectedSelectorMask mask)
1601{
1602 setNeedsStyleRecalc();
1603 if (ElementShadow* elementShadow = shadowOfParentForDistribution(this))
1604 elementShadow->didAffectSelector(mask);
1605}
1606
1607PassRefPtr<ShadowRoot> Element::createShadowRoot(ExceptionCode& ec)
1608{
1609 if (alwaysCreateUserAgentShadowRoot())
1610 ensureUserAgentShadowRoot();
1611
1612 if (RuntimeEnabledFeatures::authorShadowDOMForAnyElementEnabled())
1613 return ensureShadow()->addShadowRoot(this, ShadowRoot::AuthorShadowRoot);
1614
1615 // Since some elements recreates shadow root dynamically, multiple shadow
1616 // subtrees won't work well in that element. Until they are fixed, we disable
1617 // adding author shadow root for them.
1618 if (!areAuthorShadowsAllowed()) {
Ben Murdoche69819b2013-07-17 14:56:49 +01001619 ec = HierarchyRequestError;
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001620 return 0;
1621 }
1622 return ensureShadow()->addShadowRoot(this, ShadowRoot::AuthorShadowRoot);
1623}
1624
1625ShadowRoot* Element::shadowRoot() const
1626{
1627 ElementShadow* elementShadow = shadow();
1628 if (!elementShadow)
1629 return 0;
1630 ShadowRoot* shadowRoot = elementShadow->youngestShadowRoot();
1631 if (shadowRoot->type() == ShadowRoot::AuthorShadowRoot)
1632 return shadowRoot;
1633 return 0;
1634}
1635
1636ShadowRoot* Element::userAgentShadowRoot() const
1637{
1638 if (ElementShadow* elementShadow = shadow()) {
1639 if (ShadowRoot* shadowRoot = elementShadow->oldestShadowRoot()) {
1640 ASSERT(shadowRoot->type() == ShadowRoot::UserAgentShadowRoot);
1641 return shadowRoot;
1642 }
1643 }
1644
1645 return 0;
1646}
1647
1648ShadowRoot* Element::ensureUserAgentShadowRoot()
1649{
1650 if (ShadowRoot* shadowRoot = userAgentShadowRoot())
1651 return shadowRoot;
1652 ShadowRoot* shadowRoot = ensureShadow()->addShadowRoot(this, ShadowRoot::UserAgentShadowRoot);
1653 didAddUserAgentShadowRoot(shadowRoot);
1654 return shadowRoot;
1655}
1656
1657const AtomicString& Element::shadowPseudoId() const
1658{
1659 return pseudo();
1660}
1661
1662bool Element::childTypeAllowed(NodeType type) const
1663{
1664 switch (type) {
1665 case ELEMENT_NODE:
1666 case TEXT_NODE:
1667 case COMMENT_NODE:
1668 case PROCESSING_INSTRUCTION_NODE:
1669 case CDATA_SECTION_NODE:
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001670 return true;
1671 default:
1672 break;
1673 }
1674 return false;
1675}
1676
1677static void checkForEmptyStyleChange(Element* element, RenderStyle* style)
1678{
1679 if (!style && !element->styleAffectedByEmpty())
1680 return;
1681
1682 if (!style || (element->styleAffectedByEmpty() && (!style->emptyState() || element->hasChildNodes())))
1683 element->setNeedsStyleRecalc();
1684}
1685
1686static void checkForSiblingStyleChanges(Element* e, RenderStyle* style, bool finishedParsingCallback,
1687 Node* beforeChange, Node* afterChange, int childCountDelta)
1688{
1689 // :empty selector.
1690 checkForEmptyStyleChange(e, style);
Ben Murdoch591b9582013-07-10 11:41:44 +01001691
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001692 if (!style || (e->needsStyleRecalc() && e->childrenAffectedByPositionalRules()))
1693 return;
1694
1695 // :first-child. In the parser callback case, we don't have to check anything, since we were right the first time.
1696 // In the DOM case, we only need to do something if |afterChange| is not 0.
1697 // |afterChange| is 0 in the parser case, so it works out that we'll skip this block.
1698 if (e->childrenAffectedByFirstChildRules() && afterChange) {
1699 // Find our new first child.
1700 Node* newFirstChild = 0;
1701 for (newFirstChild = e->firstChild(); newFirstChild && !newFirstChild->isElementNode(); newFirstChild = newFirstChild->nextSibling()) {};
Ben Murdoch591b9582013-07-10 11:41:44 +01001702
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001703 // Find the first element node following |afterChange|
1704 Node* firstElementAfterInsertion = 0;
1705 for (firstElementAfterInsertion = afterChange;
1706 firstElementAfterInsertion && !firstElementAfterInsertion->isElementNode();
1707 firstElementAfterInsertion = firstElementAfterInsertion->nextSibling()) {};
Ben Murdoch591b9582013-07-10 11:41:44 +01001708
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001709 // This is the insert/append case.
1710 if (newFirstChild != firstElementAfterInsertion && firstElementAfterInsertion && firstElementAfterInsertion->attached() &&
1711 firstElementAfterInsertion->renderStyle() && firstElementAfterInsertion->renderStyle()->firstChildState())
1712 firstElementAfterInsertion->setNeedsStyleRecalc();
Ben Murdoch591b9582013-07-10 11:41:44 +01001713
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001714 // We also have to handle node removal.
1715 if (childCountDelta < 0 && newFirstChild == firstElementAfterInsertion && newFirstChild && (!newFirstChild->renderStyle() || !newFirstChild->renderStyle()->firstChildState()))
1716 newFirstChild->setNeedsStyleRecalc();
1717 }
1718
1719 // :last-child. In the parser callback case, we don't have to check anything, since we were right the first time.
1720 // In the DOM case, we only need to do something if |afterChange| is not 0.
1721 if (e->childrenAffectedByLastChildRules() && beforeChange) {
1722 // Find our new last child.
1723 Node* newLastChild = 0;
1724 for (newLastChild = e->lastChild(); newLastChild && !newLastChild->isElementNode(); newLastChild = newLastChild->previousSibling()) {};
Ben Murdoch591b9582013-07-10 11:41:44 +01001725
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001726 // Find the last element node going backwards from |beforeChange|
1727 Node* lastElementBeforeInsertion = 0;
1728 for (lastElementBeforeInsertion = beforeChange;
1729 lastElementBeforeInsertion && !lastElementBeforeInsertion->isElementNode();
1730 lastElementBeforeInsertion = lastElementBeforeInsertion->previousSibling()) {};
Ben Murdoch591b9582013-07-10 11:41:44 +01001731
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001732 if (newLastChild != lastElementBeforeInsertion && lastElementBeforeInsertion && lastElementBeforeInsertion->attached() &&
1733 lastElementBeforeInsertion->renderStyle() && lastElementBeforeInsertion->renderStyle()->lastChildState())
1734 lastElementBeforeInsertion->setNeedsStyleRecalc();
Ben Murdoch591b9582013-07-10 11:41:44 +01001735
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001736 // 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
1737 // to match now.
1738 if ((childCountDelta < 0 || finishedParsingCallback) && newLastChild == lastElementBeforeInsertion && newLastChild && (!newLastChild->renderStyle() || !newLastChild->renderStyle()->lastChildState()))
1739 newLastChild->setNeedsStyleRecalc();
1740 }
1741
1742 // The + selector. We need to invalidate the first element following the insertion point. It is the only possible element
1743 // that could be affected by this DOM change.
1744 if (e->childrenAffectedByDirectAdjacentRules() && afterChange) {
1745 Node* firstElementAfterInsertion = 0;
1746 for (firstElementAfterInsertion = afterChange;
1747 firstElementAfterInsertion && !firstElementAfterInsertion->isElementNode();
1748 firstElementAfterInsertion = firstElementAfterInsertion->nextSibling()) {};
1749 if (firstElementAfterInsertion && firstElementAfterInsertion->attached())
1750 firstElementAfterInsertion->setNeedsStyleRecalc();
1751 }
1752
1753 // Forward positional selectors include the ~ selector, nth-child, nth-of-type, first-of-type and only-of-type.
1754 // Backward positional selectors include nth-last-child, nth-last-of-type, last-of-type and only-of-type.
1755 // We have to invalidate everything following the insertion point in the forward case, and everything before the insertion point in the
1756 // backward case.
1757 // |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.
1758 // 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
1759 // here. recalcStyle will then force a walk of the children when it sees that this has happened.
1760 if ((e->childrenAffectedByForwardPositionalRules() && afterChange)
1761 || (e->childrenAffectedByBackwardPositionalRules() && beforeChange))
1762 e->setNeedsStyleRecalc();
1763}
1764
1765void Element::childrenChanged(bool changedByParser, Node* beforeChange, Node* afterChange, int childCountDelta)
1766{
1767 ContainerNode::childrenChanged(changedByParser, beforeChange, afterChange, childCountDelta);
1768 if (changedByParser)
1769 checkForEmptyStyleChange(this, renderStyle());
1770 else
1771 checkForSiblingStyleChanges(this, renderStyle(), false, beforeChange, afterChange, childCountDelta);
1772
1773 if (ElementShadow * shadow = this->shadow())
1774 shadow->invalidateDistribution();
1775}
1776
1777void Element::removeAllEventListeners()
1778{
1779 ContainerNode::removeAllEventListeners();
1780 if (ElementShadow* shadow = this->shadow())
1781 shadow->removeAllEventListeners();
1782}
1783
1784void Element::beginParsingChildren()
1785{
1786 clearIsParsingChildrenFinished();
1787 StyleResolver* styleResolver = document()->styleResolverIfExists();
1788 if (styleResolver && attached())
1789 styleResolver->pushParentElement(this);
1790}
1791
1792void Element::finishParsingChildren()
1793{
1794 ContainerNode::finishParsingChildren();
1795 setIsParsingChildrenFinished();
1796 checkForSiblingStyleChanges(this, renderStyle(), true, lastChild(), 0, 0);
1797 if (StyleResolver* styleResolver = document()->styleResolverIfExists())
1798 styleResolver->popParentElement(this);
1799}
1800
1801#ifndef NDEBUG
1802void Element::formatForDebugger(char* buffer, unsigned length) const
1803{
1804 StringBuilder result;
1805 String s;
1806
1807 result.append(nodeName());
1808
1809 s = getIdAttribute();
1810 if (s.length() > 0) {
1811 if (result.length() > 0)
1812 result.appendLiteral("; ");
1813 result.appendLiteral("id=");
1814 result.append(s);
1815 }
1816
1817 s = getAttribute(classAttr);
1818 if (s.length() > 0) {
1819 if (result.length() > 0)
1820 result.appendLiteral("; ");
1821 result.appendLiteral("class=");
1822 result.append(s);
1823 }
1824
1825 strncpy(buffer, result.toString().utf8().data(), length - 1);
1826}
1827#endif
1828
1829const Vector<RefPtr<Attr> >& Element::attrNodeList()
1830{
1831 ASSERT(hasSyntheticAttrChildNodes());
1832 return *attrNodeListForElement(this);
1833}
1834
1835PassRefPtr<Attr> Element::setAttributeNode(Attr* attrNode, ExceptionCode& ec)
1836{
1837 if (!attrNode) {
Ben Murdoche69819b2013-07-17 14:56:49 +01001838 ec = TypeMismatchError;
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001839 return 0;
1840 }
1841
1842 RefPtr<Attr> oldAttrNode = attrIfExists(attrNode->qualifiedName());
1843 if (oldAttrNode.get() == attrNode)
1844 return attrNode; // This Attr is already attached to the element.
1845
Ben Murdoche69819b2013-07-17 14:56:49 +01001846 // InUseAttributeError: Raised if node is an Attr that is already an attribute of another Element object.
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001847 // The DOM user must explicitly clone Attr nodes to re-use them in other elements.
1848 if (attrNode->ownerElement()) {
Ben Murdoche69819b2013-07-17 14:56:49 +01001849 ec = InUseAttributeError;
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001850 return 0;
1851 }
1852
1853 synchronizeAllAttributes();
1854 UniqueElementData* elementData = ensureUniqueElementData();
1855
1856 size_t index = elementData->getAttributeItemIndex(attrNode->qualifiedName());
1857 if (index != notFound) {
1858 if (oldAttrNode)
1859 detachAttrNodeFromElementWithValue(oldAttrNode.get(), elementData->attributeItem(index)->value());
1860 else
1861 oldAttrNode = Attr::create(document(), attrNode->qualifiedName(), elementData->attributeItem(index)->value());
1862 }
1863
1864 setAttributeInternal(index, attrNode->qualifiedName(), attrNode->value(), NotInSynchronizationOfLazyAttribute);
1865
1866 attrNode->attachToElement(this);
Ben Murdoch591b9582013-07-10 11:41:44 +01001867 treeScope()->adoptIfNeeded(attrNode);
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001868 ensureAttrNodeListForElement(this)->append(attrNode);
1869
1870 return oldAttrNode.release();
1871}
1872
1873PassRefPtr<Attr> Element::setAttributeNodeNS(Attr* attr, ExceptionCode& ec)
1874{
1875 return setAttributeNode(attr, ec);
1876}
1877
1878PassRefPtr<Attr> Element::removeAttributeNode(Attr* attr, ExceptionCode& ec)
1879{
1880 if (!attr) {
Ben Murdoche69819b2013-07-17 14:56:49 +01001881 ec = TypeMismatchError;
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001882 return 0;
1883 }
1884 if (attr->ownerElement() != this) {
Ben Murdoche69819b2013-07-17 14:56:49 +01001885 ec = NotFoundError;
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001886 return 0;
1887 }
1888
1889 ASSERT(document() == attr->document());
1890
1891 synchronizeAttribute(attr->qualifiedName());
1892
Torne (Richard Coles)e5249552013-05-15 11:35:13 +01001893 size_t index = elementData()->getAttrIndex(attr);
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001894 if (index == notFound) {
Ben Murdoche69819b2013-07-17 14:56:49 +01001895 ec = NotFoundError;
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001896 return 0;
1897 }
1898
Torne (Richard Coles)e5249552013-05-15 11:35:13 +01001899 RefPtr<Attr> guard(attr);
1900 detachAttrNodeAtIndex(attr, index);
1901 return guard.release();
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001902}
1903
1904bool Element::parseAttributeName(QualifiedName& out, const AtomicString& namespaceURI, const AtomicString& qualifiedName, ExceptionCode& ec)
1905{
1906 String prefix, localName;
1907 if (!Document::parseQualifiedName(qualifiedName, prefix, localName, ec))
1908 return false;
1909 ASSERT(!ec);
1910
1911 QualifiedName qName(prefix, localName, namespaceURI);
1912
1913 if (!Document::hasValidNamespaceForAttributes(qName)) {
Ben Murdoche69819b2013-07-17 14:56:49 +01001914 ec = NamespaceError;
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001915 return false;
1916 }
1917
1918 out = qName;
1919 return true;
1920}
1921
1922void Element::setAttributeNS(const AtomicString& namespaceURI, const AtomicString& qualifiedName, const AtomicString& value, ExceptionCode& ec)
1923{
1924 QualifiedName parsedName = anyName;
1925 if (!parseAttributeName(parsedName, namespaceURI, qualifiedName, ec))
1926 return;
1927 setAttribute(parsedName, value);
1928}
1929
1930void Element::removeAttributeInternal(size_t index, SynchronizationOfLazyAttribute inSynchronizationOfLazyAttribute)
1931{
1932 ASSERT_WITH_SECURITY_IMPLICATION(index < attributeCount());
1933
1934 UniqueElementData* elementData = ensureUniqueElementData();
1935
1936 QualifiedName name = elementData->attributeItem(index)->name();
1937 AtomicString valueBeingRemoved = elementData->attributeItem(index)->value();
1938
1939 if (!inSynchronizationOfLazyAttribute) {
1940 if (!valueBeingRemoved.isNull())
1941 willModifyAttribute(name, valueBeingRemoved, nullAtom);
1942 }
1943
1944 if (RefPtr<Attr> attrNode = attrIfExists(name))
1945 detachAttrNodeFromElementWithValue(attrNode.get(), elementData->attributeItem(index)->value());
1946
1947 elementData->removeAttribute(index);
1948
1949 if (!inSynchronizationOfLazyAttribute)
1950 didRemoveAttribute(name);
1951}
1952
1953void Element::addAttributeInternal(const QualifiedName& name, const AtomicString& value, SynchronizationOfLazyAttribute inSynchronizationOfLazyAttribute)
1954{
1955 if (!inSynchronizationOfLazyAttribute)
1956 willModifyAttribute(name, nullAtom, value);
1957 ensureUniqueElementData()->addAttribute(name, value);
1958 if (!inSynchronizationOfLazyAttribute)
1959 didAddAttribute(name, value);
1960}
1961
1962void Element::removeAttribute(const AtomicString& name)
1963{
1964 if (!elementData())
1965 return;
1966
1967 AtomicString localName = shouldIgnoreAttributeCase(this) ? name.lower() : name;
1968 size_t index = elementData()->getAttributeItemIndex(localName, false);
1969 if (index == notFound) {
1970 if (UNLIKELY(localName == styleAttr) && elementData()->m_styleAttributeIsDirty && isStyledElement())
Ben Murdoch591b9582013-07-10 11:41:44 +01001971 removeAllInlineStyleProperties();
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001972 return;
1973 }
1974
1975 removeAttributeInternal(index, NotInSynchronizationOfLazyAttribute);
1976}
1977
1978void Element::removeAttributeNS(const AtomicString& namespaceURI, const AtomicString& localName)
1979{
1980 removeAttribute(QualifiedName(nullAtom, localName, namespaceURI));
1981}
1982
1983PassRefPtr<Attr> Element::getAttributeNode(const AtomicString& localName)
1984{
1985 if (!elementData())
1986 return 0;
1987 synchronizeAttribute(localName);
1988 const Attribute* attribute = elementData()->getAttributeItem(localName, shouldIgnoreAttributeCase(this));
1989 if (!attribute)
1990 return 0;
1991 return ensureAttr(attribute->name());
1992}
1993
1994PassRefPtr<Attr> Element::getAttributeNodeNS(const AtomicString& namespaceURI, const AtomicString& localName)
1995{
1996 if (!elementData())
1997 return 0;
1998 QualifiedName qName(nullAtom, localName, namespaceURI);
1999 synchronizeAttribute(qName);
2000 const Attribute* attribute = elementData()->getAttributeItem(qName);
2001 if (!attribute)
2002 return 0;
2003 return ensureAttr(attribute->name());
2004}
2005
2006bool Element::hasAttribute(const AtomicString& localName) const
2007{
2008 if (!elementData())
2009 return false;
2010 synchronizeAttribute(localName);
2011 return elementData()->getAttributeItem(shouldIgnoreAttributeCase(this) ? localName.lower() : localName, false);
2012}
2013
2014bool Element::hasAttributeNS(const AtomicString& namespaceURI, const AtomicString& localName) const
2015{
2016 if (!elementData())
2017 return false;
2018 QualifiedName qName(nullAtom, localName, namespaceURI);
2019 synchronizeAttribute(qName);
2020 return elementData()->getAttributeItem(qName);
2021}
2022
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002023void Element::focus(bool restorePreviousSelection, FocusDirection direction)
2024{
2025 if (!inDocument())
2026 return;
2027
2028 Document* doc = document();
2029 if (doc->focusedNode() == this)
2030 return;
2031
2032 // If the stylesheets have already been loaded we can reliably check isFocusable.
2033 // If not, we continue and set the focused node on the focus controller below so
Ben Murdoch591b9582013-07-10 11:41:44 +01002034 // that it can be updated soon after attach.
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002035 if (doc->haveStylesheetsLoaded()) {
2036 doc->updateLayoutIgnorePendingStylesheets();
2037 if (!isFocusable())
2038 return;
2039 }
2040
2041 if (!supportsFocus())
2042 return;
2043
2044 RefPtr<Node> protect;
2045 if (Page* page = doc->page()) {
2046 // Focus and change event handlers can cause us to lose our last ref.
2047 // If a focus event handler changes the focus to a different node it
2048 // does not make sense to continue and update appearence.
2049 protect = this;
Ben Murdoche69819b2013-07-17 14:56:49 +01002050 if (!page->focusController()->setFocusedElement(this, doc->frame(), direction))
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002051 return;
2052 }
2053
2054 // Setting the focused node above might have invalidated the layout due to scripts.
2055 doc->updateLayoutIgnorePendingStylesheets();
2056
2057 if (!isFocusable()) {
2058 ensureElementRareData()->setNeedsFocusAppearanceUpdateSoonAfterAttach(true);
2059 return;
2060 }
Ben Murdoch591b9582013-07-10 11:41:44 +01002061
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002062 cancelFocusAppearanceUpdate();
2063 updateFocusAppearance(restorePreviousSelection);
2064}
2065
2066void Element::updateFocusAppearance(bool /*restorePreviousSelection*/)
2067{
2068 if (isRootEditableElement()) {
2069 Frame* frame = document()->frame();
2070 if (!frame)
2071 return;
Ben Murdoch591b9582013-07-10 11:41:44 +01002072
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002073 // When focusing an editable element in an iframe, don't reset the selection if it already contains a selection.
2074 if (this == frame->selection()->rootEditableElement())
2075 return;
2076
2077 // FIXME: We should restore the previous selection if there is one.
2078 VisibleSelection newSelection = VisibleSelection(firstPositionInOrBeforeNode(this), DOWNSTREAM);
Ben Murdoch591b9582013-07-10 11:41:44 +01002079
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002080 if (frame->selection()->shouldChangeSelection(newSelection)) {
2081 frame->selection()->setSelection(newSelection);
2082 frame->selection()->revealSelection();
2083 }
2084 } else if (renderer() && !renderer()->isWidget())
2085 renderer()->scrollRectToVisible(boundingBox());
2086}
2087
2088void Element::blur()
2089{
2090 cancelFocusAppearanceUpdate();
Ben Murdoche69819b2013-07-17 14:56:49 +01002091 if (treeScope()->adjustedFocusedElement() == this) {
2092 Document* doc = document();
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002093 if (doc->frame())
Ben Murdoche69819b2013-07-17 14:56:49 +01002094 doc->frame()->page()->focusController()->setFocusedElement(0, doc->frame());
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002095 else
Ben Murdoche69819b2013-07-17 14:56:49 +01002096 doc->setFocusedElement(0);
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002097 }
2098}
2099
2100String Element::innerText()
2101{
2102 // We need to update layout, since plainText uses line boxes in the render tree.
2103 document()->updateLayoutIgnorePendingStylesheets();
2104
2105 if (!renderer())
2106 return textContent(true);
2107
2108 return plainText(rangeOfContents(const_cast<Element*>(this)).get());
2109}
2110
2111String Element::outerText()
2112{
2113 // Getting outerText is the same as getting innerText, only
2114 // setting is different. You would think this should get the plain
2115 // text for the outer range, but this is wrong, <br> for instance
2116 // would return different values for inner and outer text by such
2117 // a rule, but it doesn't in WinIE, and we want to match that.
2118 return innerText();
2119}
2120
Ben Murdoch591b9582013-07-10 11:41:44 +01002121String Element::textFromChildren()
2122{
2123 Text* firstTextNode = 0;
2124 bool foundMultipleTextNodes = false;
2125 unsigned totalLength = 0;
2126
2127 for (Node* child = firstChild(); child; child = child->nextSibling()) {
2128 if (!child->isTextNode())
2129 continue;
2130 Text* text = toText(child);
2131 if (!firstTextNode)
2132 firstTextNode = text;
2133 else
2134 foundMultipleTextNodes = true;
2135 unsigned length = text->data().length();
2136 if (length > std::numeric_limits<unsigned>::max() - totalLength)
2137 return emptyString();
2138 totalLength += length;
2139 }
2140
2141 if (!firstTextNode)
2142 return emptyString();
2143
2144 if (firstTextNode && !foundMultipleTextNodes) {
2145 firstTextNode->atomize();
2146 return firstTextNode->data();
2147 }
2148
2149 StringBuilder content;
2150 content.reserveCapacity(totalLength);
2151 for (Node* child = firstTextNode; child; child = child->nextSibling()) {
2152 if (!child->isTextNode())
2153 continue;
2154 content.append(toText(child)->data());
2155 }
2156
2157 ASSERT(content.length() == totalLength);
2158 return content.toString();
2159}
2160
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002161String Element::title() const
2162{
2163 return String();
2164}
2165
2166const AtomicString& Element::pseudo() const
2167{
2168 return getAttribute(pseudoAttr);
2169}
2170
2171void Element::setPseudo(const AtomicString& value)
2172{
2173 setAttribute(pseudoAttr, value);
2174}
2175
2176LayoutSize Element::minimumSizeForResizing() const
2177{
2178 return hasRareData() ? elementRareData()->minimumSizeForResizing() : defaultMinimumSizeForResizing();
2179}
2180
2181void Element::setMinimumSizeForResizing(const LayoutSize& size)
2182{
2183 if (!hasRareData() && size == defaultMinimumSizeForResizing())
2184 return;
2185 ensureElementRareData()->setMinimumSizeForResizing(size);
2186}
2187
2188RenderStyle* Element::computedStyle(PseudoId pseudoElementSpecifier)
2189{
2190 if (PseudoElement* element = pseudoElement(pseudoElementSpecifier))
2191 return element->computedStyle();
2192
2193 // FIXME: Find and use the renderer from the pseudo element instead of the actual element so that the 'length'
2194 // properties, which are only known by the renderer because it did the layout, will be correct and so that the
2195 // values returned for the ":selection" pseudo-element will be correct.
2196 if (RenderStyle* usedStyle = renderStyle()) {
2197 if (pseudoElementSpecifier) {
2198 RenderStyle* cachedPseudoStyle = usedStyle->getCachedPseudoStyle(pseudoElementSpecifier);
2199 return cachedPseudoStyle ? cachedPseudoStyle : usedStyle;
2200 } else
2201 return usedStyle;
2202 }
2203
2204 if (!attached())
2205 // FIXME: Try to do better than this. Ensure that styleForElement() works for elements that are not in the
2206 // document tree and figure out when to destroy the computed style for such elements.
2207 return 0;
2208
2209 ElementRareData* data = ensureElementRareData();
2210 if (!data->computedStyle())
2211 data->setComputedStyle(document()->styleForElementIgnoringPendingStylesheets(this));
2212 return pseudoElementSpecifier ? data->computedStyle()->getCachedPseudoStyle(pseudoElementSpecifier) : data->computedStyle();
2213}
2214
2215void Element::setStyleAffectedByEmpty()
2216{
2217 ensureElementRareData()->setStyleAffectedByEmpty(true);
2218}
2219
2220void Element::setChildrenAffectedByHover(bool value)
2221{
2222 if (value || hasRareData())
2223 ensureElementRareData()->setChildrenAffectedByHover(value);
2224}
2225
2226void Element::setChildrenAffectedByActive(bool value)
2227{
2228 if (value || hasRareData())
2229 ensureElementRareData()->setChildrenAffectedByActive(value);
2230}
2231
2232void Element::setChildrenAffectedByDrag(bool value)
2233{
2234 if (value || hasRareData())
2235 ensureElementRareData()->setChildrenAffectedByDrag(value);
2236}
2237
2238void Element::setChildrenAffectedByFirstChildRules()
2239{
2240 ensureElementRareData()->setChildrenAffectedByFirstChildRules(true);
2241}
2242
2243void Element::setChildrenAffectedByLastChildRules()
2244{
2245 ensureElementRareData()->setChildrenAffectedByLastChildRules(true);
2246}
2247
2248void Element::setChildrenAffectedByDirectAdjacentRules()
2249{
2250 ensureElementRareData()->setChildrenAffectedByDirectAdjacentRules(true);
2251}
2252
2253void Element::setChildrenAffectedByForwardPositionalRules()
2254{
2255 ensureElementRareData()->setChildrenAffectedByForwardPositionalRules(true);
2256}
2257
2258void Element::setChildrenAffectedByBackwardPositionalRules()
2259{
2260 ensureElementRareData()->setChildrenAffectedByBackwardPositionalRules(true);
2261}
2262
2263void Element::setChildIndex(unsigned index)
2264{
2265 ElementRareData* rareData = ensureElementRareData();
2266 if (RenderStyle* style = renderStyle())
2267 style->setUnique();
2268 rareData->setChildIndex(index);
2269}
2270
2271bool Element::hasFlagsSetDuringStylingOfChildren() const
2272{
2273 if (!hasRareData())
2274 return false;
2275 return rareDataChildrenAffectedByHover()
2276 || rareDataChildrenAffectedByActive()
2277 || rareDataChildrenAffectedByDrag()
2278 || rareDataChildrenAffectedByFirstChildRules()
2279 || rareDataChildrenAffectedByLastChildRules()
2280 || rareDataChildrenAffectedByDirectAdjacentRules()
2281 || rareDataChildrenAffectedByForwardPositionalRules()
2282 || rareDataChildrenAffectedByBackwardPositionalRules();
2283}
2284
2285bool Element::rareDataStyleAffectedByEmpty() const
2286{
2287 ASSERT(hasRareData());
2288 return elementRareData()->styleAffectedByEmpty();
2289}
2290
2291bool Element::rareDataChildrenAffectedByHover() const
2292{
2293 ASSERT(hasRareData());
2294 return elementRareData()->childrenAffectedByHover();
2295}
2296
2297bool Element::rareDataChildrenAffectedByActive() const
2298{
2299 ASSERT(hasRareData());
2300 return elementRareData()->childrenAffectedByActive();
2301}
2302
2303bool Element::rareDataChildrenAffectedByDrag() const
2304{
2305 ASSERT(hasRareData());
2306 return elementRareData()->childrenAffectedByDrag();
2307}
2308
2309bool Element::rareDataChildrenAffectedByFirstChildRules() const
2310{
2311 ASSERT(hasRareData());
2312 return elementRareData()->childrenAffectedByFirstChildRules();
2313}
2314
2315bool Element::rareDataChildrenAffectedByLastChildRules() const
2316{
2317 ASSERT(hasRareData());
2318 return elementRareData()->childrenAffectedByLastChildRules();
2319}
2320
2321bool Element::rareDataChildrenAffectedByDirectAdjacentRules() const
2322{
2323 ASSERT(hasRareData());
2324 return elementRareData()->childrenAffectedByDirectAdjacentRules();
2325}
2326
2327bool Element::rareDataChildrenAffectedByForwardPositionalRules() const
2328{
2329 ASSERT(hasRareData());
2330 return elementRareData()->childrenAffectedByForwardPositionalRules();
2331}
2332
2333bool Element::rareDataChildrenAffectedByBackwardPositionalRules() const
2334{
2335 ASSERT(hasRareData());
2336 return elementRareData()->childrenAffectedByBackwardPositionalRules();
2337}
2338
2339unsigned Element::rareDataChildIndex() const
2340{
2341 ASSERT(hasRareData());
2342 return elementRareData()->childIndex();
2343}
2344
2345void Element::setIsInCanvasSubtree(bool isInCanvasSubtree)
2346{
2347 ensureElementRareData()->setIsInCanvasSubtree(isInCanvasSubtree);
2348}
2349
2350bool Element::isInCanvasSubtree() const
2351{
2352 return hasRareData() && elementRareData()->isInCanvasSubtree();
2353}
2354
Ben Murdoch591b9582013-07-10 11:41:44 +01002355void Element::setIsInsideRegion(bool value)
2356{
2357 if (value == isInsideRegion())
2358 return;
2359
2360 ensureElementRareData()->setIsInsideRegion(value);
2361}
2362
2363bool Element::isInsideRegion() const
2364{
2365 return hasRareData() ? elementRareData()->isInsideRegion() : false;
2366}
2367
2368void Element::setRegionOversetState(RegionOversetState state)
2369{
2370 ensureElementRareData()->setRegionOversetState(state);
2371}
2372
2373RegionOversetState Element::regionOversetState() const
2374{
2375 return hasRareData() ? elementRareData()->regionOversetState() : RegionUndefined;
2376}
2377
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002378AtomicString Element::computeInheritedLanguage() const
2379{
2380 const Node* n = this;
2381 AtomicString value;
2382 // The language property is inherited, so we iterate over the parents to find the first language.
2383 do {
2384 if (n->isElementNode()) {
2385 if (const ElementData* elementData = toElement(n)->elementData()) {
2386 // Spec: xml:lang takes precedence -- http://www.w3.org/TR/xhtml1/#C_7
2387 if (const Attribute* attribute = elementData->getAttributeItem(XMLNames::langAttr))
2388 value = attribute->value();
2389 else if (const Attribute* attribute = elementData->getAttributeItem(HTMLNames::langAttr))
2390 value = attribute->value();
2391 }
2392 } else if (n->isDocumentNode()) {
2393 // checking the MIME content-language
2394 value = toDocument(n)->contentLanguage();
2395 }
2396
2397 n = n->parentNode();
2398 } while (n && value.isNull());
2399
2400 return value;
2401}
2402
2403Locale& Element::locale() const
2404{
2405 return document()->getCachedLocale(computeInheritedLanguage());
2406}
2407
2408void Element::cancelFocusAppearanceUpdate()
2409{
2410 if (hasRareData())
2411 elementRareData()->setNeedsFocusAppearanceUpdateSoonAfterAttach(false);
2412 if (document()->focusedNode() == this)
2413 document()->cancelFocusAppearanceUpdate();
2414}
2415
2416void Element::normalizeAttributes()
2417{
2418 if (!hasAttributes())
2419 return;
2420 for (unsigned i = 0; i < attributeCount(); ++i) {
2421 if (RefPtr<Attr> attr = attrIfExists(attributeItem(i)->name()))
2422 attr->normalize();
2423 }
2424}
2425
2426void Element::updatePseudoElement(PseudoId pseudoId, StyleChange change)
2427{
2428 PseudoElement* element = pseudoElement(pseudoId);
2429 if (element && (needsStyleRecalc() || shouldRecalcStyle(change, element))) {
2430 // PseudoElement styles hang off their parent element's style so if we needed
2431 // a style recalc we should Force one on the pseudo.
2432 element->recalcStyle(needsStyleRecalc() ? Force : change);
2433
2434 // Wait until our parent is not displayed or pseudoElementRendererIsNeeded
2435 // is false, otherwise we could continously create and destroy PseudoElements
2436 // when RenderObject::isChildAllowed on our parent returns false for the
2437 // PseudoElement's renderer for each style recalc.
2438 if (!renderer() || !pseudoElementRendererIsNeeded(renderer()->getCachedPseudoStyle(pseudoId)))
Torne (Richard Coles)521d96e2013-06-19 11:58:24 +01002439 elementRareData()->setPseudoElement(pseudoId, 0);
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002440 } else if (change >= Inherit || needsStyleRecalc())
2441 createPseudoElementIfNeeded(pseudoId);
2442}
2443
2444void Element::createPseudoElementIfNeeded(PseudoId pseudoId)
2445{
Ben Murdoche69819b2013-07-17 14:56:49 +01002446 if ((pseudoId == BEFORE || pseudoId == AFTER) && !document()->styleSheetCollection()->usesBeforeAfterRules())
2447 return;
2448
2449 if (pseudoId == BACKDROP && !isInTopLayer())
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002450 return;
2451
2452 if (!renderer() || !pseudoElementRendererIsNeeded(renderer()->getCachedPseudoStyle(pseudoId)))
2453 return;
2454
2455 if (!renderer()->canHaveGeneratedChildren())
2456 return;
2457
2458 ASSERT(!isPseudoElement());
2459 RefPtr<PseudoElement> element = PseudoElement::create(this, pseudoId);
Ben Murdoche69819b2013-07-17 14:56:49 +01002460 if (pseudoId == BACKDROP)
2461 document()->addToTopLayer(element.get(), this);
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002462 element->attach();
Ben Murdoche69819b2013-07-17 14:56:49 +01002463
Torne (Richard Coles)521d96e2013-06-19 11:58:24 +01002464 ensureElementRareData()->setPseudoElement(pseudoId, element.release());
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002465}
2466
2467PseudoElement* Element::pseudoElement(PseudoId pseudoId) const
2468{
2469 return hasRareData() ? elementRareData()->pseudoElement(pseudoId) : 0;
2470}
2471
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002472RenderObject* Element::pseudoElementRenderer(PseudoId pseudoId) const
2473{
2474 if (PseudoElement* element = pseudoElement(pseudoId))
2475 return element->renderer();
2476 return 0;
2477}
2478
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002479bool Element::matchesReadOnlyPseudoClass() const
2480{
2481 return false;
2482}
2483
2484bool Element::matchesReadWritePseudoClass() const
2485{
2486 return false;
2487}
2488
2489bool Element::webkitMatchesSelector(const String& selector, ExceptionCode& ec)
2490{
2491 if (selector.isEmpty()) {
Ben Murdoche69819b2013-07-17 14:56:49 +01002492 ec = SyntaxError;
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002493 return false;
2494 }
2495
2496 SelectorQuery* selectorQuery = document()->selectorQueryCache()->add(selector, document(), ec);
2497 if (!selectorQuery)
2498 return false;
2499 return selectorQuery->matches(this);
2500}
2501
2502bool Element::shouldAppearIndeterminate() const
2503{
2504 return false;
2505}
2506
2507DOMTokenList* Element::classList()
2508{
2509 ElementRareData* data = ensureElementRareData();
2510 if (!data->classList())
2511 data->setClassList(ClassList::create(this));
2512 return data->classList();
2513}
2514
2515DOMStringMap* Element::dataset()
2516{
2517 ElementRareData* data = ensureElementRareData();
2518 if (!data->dataset())
2519 data->setDataset(DatasetDOMStringMap::create(this));
2520 return data->dataset();
2521}
2522
2523KURL Element::getURLAttribute(const QualifiedName& name) const
2524{
2525#if !ASSERT_DISABLED
2526 if (elementData()) {
2527 if (const Attribute* attribute = getAttributeItem(name))
2528 ASSERT(isURLAttribute(*attribute));
2529 }
2530#endif
2531 return document()->completeURL(stripLeadingAndTrailingHTMLSpaces(getAttribute(name)));
2532}
2533
2534KURL Element::getNonEmptyURLAttribute(const QualifiedName& name) const
2535{
2536#if !ASSERT_DISABLED
2537 if (elementData()) {
2538 if (const Attribute* attribute = getAttributeItem(name))
2539 ASSERT(isURLAttribute(*attribute));
2540 }
2541#endif
2542 String value = stripLeadingAndTrailingHTMLSpaces(getAttribute(name));
2543 if (value.isEmpty())
2544 return KURL();
2545 return document()->completeURL(value);
2546}
2547
2548int Element::getIntegralAttribute(const QualifiedName& attributeName) const
2549{
2550 return getAttribute(attributeName).string().toInt();
2551}
2552
2553void Element::setIntegralAttribute(const QualifiedName& attributeName, int value)
2554{
2555 // FIXME: Need an AtomicString version of String::number.
2556 setAttribute(attributeName, String::number(value));
2557}
2558
2559unsigned Element::getUnsignedIntegralAttribute(const QualifiedName& attributeName) const
2560{
2561 return getAttribute(attributeName).string().toUInt();
2562}
2563
2564void Element::setUnsignedIntegralAttribute(const QualifiedName& attributeName, unsigned value)
2565{
2566 // FIXME: Need an AtomicString version of String::number.
2567 setAttribute(attributeName, String::number(value));
2568}
2569
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002570bool Element::childShouldCreateRenderer(const NodeRenderingContext& childContext) const
2571{
2572 // Only create renderers for SVG elements whose parents are SVG elements, or for proper <svg xmlns="svgNS"> subdocuments.
2573 if (childContext.node()->isSVGElement())
2574 return childContext.node()->hasTagName(SVGNames::svgTag) || isSVGElement();
2575
2576 return ContainerNode::childShouldCreateRenderer(childContext);
2577}
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002578
2579void Element::webkitRequestFullscreen()
2580{
Torne (Richard Coles)521d96e2013-06-19 11:58:24 +01002581 FullscreenController::from(document())->requestFullScreenForElement(this, ALLOW_KEYBOARD_INPUT, FullscreenController::EnforceIFrameAllowFullScreenRequirement);
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002582}
2583
2584void Element::webkitRequestFullScreen(unsigned short flags)
2585{
Torne (Richard Coles)521d96e2013-06-19 11:58:24 +01002586 FullscreenController::from(document())->requestFullScreenForElement(this, (flags | LEGACY_MOZILLA_REQUEST), FullscreenController::EnforceIFrameAllowFullScreenRequirement);
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002587}
2588
2589bool Element::containsFullScreenElement() const
2590{
2591 return hasRareData() && elementRareData()->containsFullScreenElement();
2592}
2593
2594void Element::setContainsFullScreenElement(bool flag)
2595{
2596 ensureElementRareData()->setContainsFullScreenElement(flag);
Ben Murdoche69819b2013-07-17 14:56:49 +01002597 setNeedsStyleRecalc(SubtreeStyleChange);
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002598}
2599
2600static Element* parentCrossingFrameBoundaries(Element* element)
2601{
2602 ASSERT(element);
2603 return element->parentElement() ? element->parentElement() : element->document()->ownerElement();
2604}
2605
2606void Element::setContainsFullScreenElementOnAncestorsCrossingFrameBoundaries(bool flag)
2607{
2608 Element* element = this;
2609 while ((element = parentCrossingFrameBoundaries(element)))
2610 element->setContainsFullScreenElement(flag);
2611}
2612
2613bool Element::isInTopLayer() const
2614{
2615 return hasRareData() && elementRareData()->isInTopLayer();
2616}
2617
2618void Element::setIsInTopLayer(bool inTopLayer)
2619{
2620 if (isInTopLayer() == inTopLayer)
2621 return;
2622 ensureElementRareData()->setIsInTopLayer(inTopLayer);
2623
2624 // We must ensure a reattach occurs so the renderer is inserted in the correct sibling order under RenderView according to its
2625 // top layer position, or in its usual place if not in the top layer.
Torne (Richard Coles)93ac45c2013-05-29 14:40:20 +01002626 lazyReattachIfAttached();
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002627}
2628
2629void Element::webkitRequestPointerLock()
2630{
2631 if (document()->page())
2632 document()->page()->pointerLockController()->requestPointerLock(this);
2633}
2634
2635SpellcheckAttributeState Element::spellcheckAttributeState() const
2636{
2637 const AtomicString& value = getAttribute(HTMLNames::spellcheckAttr);
2638 if (value == nullAtom)
2639 return SpellcheckAttributeDefault;
2640 if (equalIgnoringCase(value, "true") || equalIgnoringCase(value, ""))
2641 return SpellcheckAttributeTrue;
2642 if (equalIgnoringCase(value, "false"))
2643 return SpellcheckAttributeFalse;
2644
2645 return SpellcheckAttributeDefault;
2646}
2647
2648bool Element::isSpellCheckingEnabled() const
2649{
2650 for (const Element* element = this; element; element = element->parentOrShadowHostElement()) {
2651 switch (element->spellcheckAttributeState()) {
2652 case SpellcheckAttributeTrue:
2653 return true;
2654 case SpellcheckAttributeFalse:
2655 return false;
2656 case SpellcheckAttributeDefault:
2657 break;
2658 }
2659 }
2660
2661 return true;
2662}
2663
2664RenderRegion* Element::renderRegion() const
2665{
2666 if (renderer() && renderer()->isRenderRegion())
2667 return toRenderRegion(renderer());
2668
2669 return 0;
2670}
2671
Ben Murdoch591b9582013-07-10 11:41:44 +01002672bool Element::shouldMoveToFlowThread(RenderStyle* styleToUse) const
2673{
2674 ASSERT(styleToUse);
2675
2676 if (FullscreenController::isActiveFullScreenElement(this))
2677 return false;
2678
2679 if (isInShadowTree())
2680 return false;
2681
2682 if (styleToUse->flowThread().isEmpty())
2683 return false;
2684
2685 return !isRegisteredWithNamedFlow();
2686}
2687
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002688const AtomicString& Element::webkitRegionOverset() const
2689{
2690 document()->updateLayoutIgnorePendingStylesheets();
2691
2692 DEFINE_STATIC_LOCAL(AtomicString, undefinedState, ("undefined", AtomicString::ConstructFromLiteral));
2693 if (!RuntimeEnabledFeatures::cssRegionsEnabled() || !renderRegion())
2694 return undefinedState;
2695
Ben Murdoch591b9582013-07-10 11:41:44 +01002696 switch (renderRegion()->regionOversetState()) {
2697 case RegionFit: {
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002698 DEFINE_STATIC_LOCAL(AtomicString, fitState, ("fit", AtomicString::ConstructFromLiteral));
2699 return fitState;
2700 }
Ben Murdoch591b9582013-07-10 11:41:44 +01002701 case RegionEmpty: {
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002702 DEFINE_STATIC_LOCAL(AtomicString, emptyState, ("empty", AtomicString::ConstructFromLiteral));
2703 return emptyState;
2704 }
Ben Murdoch591b9582013-07-10 11:41:44 +01002705 case RegionOverset: {
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002706 DEFINE_STATIC_LOCAL(AtomicString, overflowState, ("overset", AtomicString::ConstructFromLiteral));
2707 return overflowState;
2708 }
Ben Murdoch591b9582013-07-10 11:41:44 +01002709 case RegionUndefined:
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002710 return undefinedState;
2711 }
2712
2713 ASSERT_NOT_REACHED();
2714 return undefinedState;
2715}
2716
2717Vector<RefPtr<Range> > Element::webkitGetRegionFlowRanges() const
2718{
2719 document()->updateLayoutIgnorePendingStylesheets();
2720
2721 Vector<RefPtr<Range> > rangeObjects;
2722 if (RuntimeEnabledFeatures::cssRegionsEnabled() && renderer() && renderer()->isRenderRegion()) {
2723 RenderRegion* region = toRenderRegion(renderer());
2724 if (region->isValid())
2725 region->getRanges(rangeObjects);
2726 }
2727
2728 return rangeObjects;
2729}
2730
2731#ifndef NDEBUG
2732bool Element::fastAttributeLookupAllowed(const QualifiedName& name) const
2733{
2734 if (name == HTMLNames::styleAttr)
2735 return false;
2736
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002737 if (isSVGElement())
2738 return !static_cast<const SVGElement*>(this)->isAnimatableAttribute(name);
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002739
2740 return true;
2741}
2742#endif
2743
2744#ifdef DUMP_NODE_STATISTICS
2745bool Element::hasNamedNodeMap() const
2746{
2747 return hasRareData() && elementRareData()->attributeMap();
2748}
2749#endif
2750
2751inline void Element::updateName(const AtomicString& oldName, const AtomicString& newName)
2752{
2753 if (!inDocument() || isInShadowTree())
2754 return;
2755
2756 if (oldName == newName)
2757 return;
2758
2759 if (shouldRegisterAsNamedItem())
2760 updateNamedItemRegistration(oldName, newName);
2761}
2762
2763inline void Element::updateId(const AtomicString& oldId, const AtomicString& newId)
2764{
2765 if (!isInTreeScope())
2766 return;
2767
2768 if (oldId == newId)
2769 return;
2770
2771 updateId(treeScope(), oldId, newId);
2772}
2773
2774inline void Element::updateId(TreeScope* scope, const AtomicString& oldId, const AtomicString& newId)
2775{
2776 ASSERT(isInTreeScope());
2777 ASSERT(oldId != newId);
2778
2779 if (!oldId.isEmpty())
2780 scope->removeElementById(oldId, this);
2781 if (!newId.isEmpty())
2782 scope->addElementById(newId, this);
2783
2784 if (shouldRegisterAsExtraNamedItem())
2785 updateExtraNamedItemRegistration(oldId, newId);
2786}
2787
2788void Element::updateLabel(TreeScope* scope, const AtomicString& oldForAttributeValue, const AtomicString& newForAttributeValue)
2789{
2790 ASSERT(hasTagName(labelTag));
2791
2792 if (!inDocument())
2793 return;
2794
2795 if (oldForAttributeValue == newForAttributeValue)
2796 return;
2797
2798 if (!oldForAttributeValue.isEmpty())
Ben Murdoche69819b2013-07-17 14:56:49 +01002799 scope->removeLabel(oldForAttributeValue, toHTMLLabelElement(this));
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002800 if (!newForAttributeValue.isEmpty())
Ben Murdoche69819b2013-07-17 14:56:49 +01002801 scope->addLabel(newForAttributeValue, toHTMLLabelElement(this));
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002802}
2803
2804void Element::willModifyAttribute(const QualifiedName& name, const AtomicString& oldValue, const AtomicString& newValue)
2805{
2806 if (isIdAttributeName(name))
2807 updateId(oldValue, newValue);
2808 else if (name == HTMLNames::nameAttr)
2809 updateName(oldValue, newValue);
2810 else if (name == HTMLNames::forAttr && hasTagName(labelTag)) {
2811 TreeScope* scope = treeScope();
2812 if (scope->shouldCacheLabelsByForAttribute())
2813 updateLabel(scope, oldValue, newValue);
2814 }
2815
2816 if (oldValue != newValue) {
2817 if (attached() && document()->styleResolver() && document()->styleResolver()->hasSelectorForAttribute(name.localName()))
2818 setNeedsStyleRecalc();
Ben Murdoche69819b2013-07-17 14:56:49 +01002819
2820 if (isUpgradedCustomElement())
2821 document()->registrationContext()->customElementAttributeDidChange(this, name.localName(), oldValue, newValue);
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002822 }
2823
2824 if (OwnPtr<MutationObserverInterestGroup> recipients = MutationObserverInterestGroup::createForAttributesMutation(this, name))
2825 recipients->enqueueMutationRecord(MutationRecord::createAttributes(this, name, oldValue));
2826
2827 InspectorInstrumentation::willModifyDOMAttr(document(), this, oldValue, newValue);
2828}
2829
2830void Element::didAddAttribute(const QualifiedName& name, const AtomicString& value)
2831{
2832 attributeChanged(name, value);
2833 InspectorInstrumentation::didModifyDOMAttr(document(), this, name.localName(), value);
2834 dispatchSubtreeModifiedEvent();
2835}
2836
2837void Element::didModifyAttribute(const QualifiedName& name, const AtomicString& value)
2838{
2839 attributeChanged(name, value);
2840 InspectorInstrumentation::didModifyDOMAttr(document(), this, name.localName(), value);
2841 // Do not dispatch a DOMSubtreeModified event here; see bug 81141.
2842}
2843
2844void Element::didRemoveAttribute(const QualifiedName& name)
2845{
2846 attributeChanged(name, nullAtom);
2847 InspectorInstrumentation::didRemoveDOMAttr(document(), this, name.localName());
2848 dispatchSubtreeModifiedEvent();
2849}
2850
Ben Murdoche69819b2013-07-17 14:56:49 +01002851void Element::didMoveToNewDocument(Document* oldDocument)
2852{
2853 Node::didMoveToNewDocument(oldDocument);
2854
2855 // If the documents differ by quirks mode then they differ by case sensitivity
2856 // for class and id names so we need to go through the attribute change logic
2857 // to pick up the new casing in the ElementData.
2858 if (oldDocument->inQuirksMode() != document()->inQuirksMode()) {
2859 if (hasID())
2860 setIdAttribute(getIdAttribute());
2861 if (hasClass())
2862 setAttribute(HTMLNames::classAttr, getClassAttribute());
2863 }
2864}
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002865
2866void Element::updateNamedItemRegistration(const AtomicString& oldName, const AtomicString& newName)
2867{
2868 if (!document()->isHTMLDocument())
2869 return;
2870
2871 if (!oldName.isEmpty())
2872 toHTMLDocument(document())->removeNamedItem(oldName);
2873
2874 if (!newName.isEmpty())
2875 toHTMLDocument(document())->addNamedItem(newName);
2876}
2877
2878void Element::updateExtraNamedItemRegistration(const AtomicString& oldId, const AtomicString& newId)
2879{
2880 if (!document()->isHTMLDocument())
2881 return;
2882
2883 if (!oldId.isEmpty())
2884 toHTMLDocument(document())->removeExtraNamedItem(oldId);
2885
2886 if (!newId.isEmpty())
2887 toHTMLDocument(document())->addExtraNamedItem(newId);
2888}
2889
2890PassRefPtr<HTMLCollection> Element::ensureCachedHTMLCollection(CollectionType type)
2891{
2892 if (HTMLCollection* collection = cachedHTMLCollection(type))
2893 return collection;
2894
2895 RefPtr<HTMLCollection> collection;
2896 if (type == TableRows) {
2897 ASSERT(hasTagName(tableTag));
2898 return ensureRareData()->ensureNodeLists()->addCacheWithAtomicName<HTMLTableRowsCollection>(this, type);
2899 } else if (type == SelectOptions) {
2900 ASSERT(hasTagName(selectTag));
2901 return ensureRareData()->ensureNodeLists()->addCacheWithAtomicName<HTMLOptionsCollection>(this, type);
2902 } else if (type == FormControls) {
2903 ASSERT(hasTagName(formTag) || hasTagName(fieldsetTag));
2904 return ensureRareData()->ensureNodeLists()->addCacheWithAtomicName<HTMLFormControlsCollection>(this, type);
2905 }
2906 return ensureRareData()->ensureNodeLists()->addCacheWithAtomicName<HTMLCollection>(this, type);
2907}
2908
Ben Murdoch591b9582013-07-10 11:41:44 +01002909static void scheduleLayerUpdateCallback(Node* node)
Torne (Richard Coles)93ac45c2013-05-29 14:40:20 +01002910{
Ben Murdoche69819b2013-07-17 14:56:49 +01002911 // Notify the renderer even is the styles are identical since it may need to
2912 // create or destroy a RenderLayer.
2913 node->setNeedsStyleRecalc(LocalStyleChange, StyleChangeFromRenderer);
Torne (Richard Coles)93ac45c2013-05-29 14:40:20 +01002914}
2915
Ben Murdoch591b9582013-07-10 11:41:44 +01002916void Element::scheduleLayerUpdate()
Torne (Richard Coles)93ac45c2013-05-29 14:40:20 +01002917{
2918 if (postAttachCallbacksAreSuspended())
Ben Murdoch591b9582013-07-10 11:41:44 +01002919 queuePostAttachCallback(scheduleLayerUpdateCallback, this);
Torne (Richard Coles)93ac45c2013-05-29 14:40:20 +01002920 else
Ben Murdoche69819b2013-07-17 14:56:49 +01002921 scheduleLayerUpdateCallback(this);
Torne (Richard Coles)93ac45c2013-05-29 14:40:20 +01002922}
2923
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002924HTMLCollection* Element::cachedHTMLCollection(CollectionType type)
2925{
2926 return hasRareData() && rareData()->nodeLists() ? rareData()->nodeLists()->cacheWithAtomicName<HTMLCollection>(type) : 0;
2927}
2928
2929IntSize Element::savedLayerScrollOffset() const
2930{
2931 return hasRareData() ? elementRareData()->savedLayerScrollOffset() : IntSize();
2932}
2933
2934void Element::setSavedLayerScrollOffset(const IntSize& size)
2935{
2936 if (size.isZero() && !hasRareData())
2937 return;
2938 ensureElementRareData()->setSavedLayerScrollOffset(size);
2939}
2940
2941PassRefPtr<Attr> Element::attrIfExists(const QualifiedName& name)
2942{
2943 if (AttrNodeList* attrNodeList = attrNodeListForElement(this))
2944 return findAttrNodeInList(attrNodeList, name);
2945 return 0;
2946}
2947
2948PassRefPtr<Attr> Element::ensureAttr(const QualifiedName& name)
2949{
2950 AttrNodeList* attrNodeList = ensureAttrNodeListForElement(this);
2951 RefPtr<Attr> attrNode = findAttrNodeInList(attrNodeList, name);
2952 if (!attrNode) {
2953 attrNode = Attr::create(this, name);
2954 treeScope()->adoptIfNeeded(attrNode.get());
2955 attrNodeList->append(attrNode);
2956 }
2957 return attrNode.release();
2958}
2959
2960void Element::detachAttrNodeFromElementWithValue(Attr* attrNode, const AtomicString& value)
2961{
2962 ASSERT(hasSyntheticAttrChildNodes());
2963 attrNode->detachFromElementWithValue(value);
2964
2965 AttrNodeList* attrNodeList = attrNodeListForElement(this);
2966 for (unsigned i = 0; i < attrNodeList->size(); ++i) {
2967 if (attrNodeList->at(i)->qualifiedName() == attrNode->qualifiedName()) {
2968 attrNodeList->remove(i);
2969 if (attrNodeList->isEmpty())
2970 removeAttrNodeListForElement(this);
2971 return;
2972 }
2973 }
2974 ASSERT_NOT_REACHED();
2975}
2976
2977void Element::detachAllAttrNodesFromElement()
2978{
2979 AttrNodeList* attrNodeList = attrNodeListForElement(this);
2980 ASSERT(attrNodeList);
2981
2982 for (unsigned i = 0; i < attributeCount(); ++i) {
2983 const Attribute* attribute = attributeItem(i);
2984 if (RefPtr<Attr> attrNode = findAttrNodeInList(attrNodeList, attribute->name()))
2985 attrNode->detachFromElementWithValue(attribute->value());
2986 }
2987
2988 removeAttrNodeListForElement(this);
2989}
2990
2991void Element::willRecalcStyle(StyleChange)
2992{
2993 ASSERT(hasCustomStyleCallbacks());
2994}
2995
2996void Element::didRecalcStyle(StyleChange)
2997{
2998 ASSERT(hasCustomStyleCallbacks());
2999}
3000
3001
3002PassRefPtr<RenderStyle> Element::customStyleForRenderer()
3003{
3004 ASSERT(hasCustomStyleCallbacks());
3005 return 0;
3006}
3007
3008void Element::cloneAttributesFromElement(const Element& other)
3009{
3010 if (hasSyntheticAttrChildNodes())
3011 detachAllAttrNodesFromElement();
3012
3013 other.synchronizeAllAttributes();
3014 if (!other.m_elementData) {
3015 m_elementData.clear();
3016 return;
3017 }
3018
3019 const AtomicString& oldID = getIdAttribute();
3020 const AtomicString& newID = other.getIdAttribute();
3021
3022 if (!oldID.isNull() || !newID.isNull())
3023 updateId(oldID, newID);
3024
3025 const AtomicString& oldName = getNameAttribute();
3026 const AtomicString& newName = other.getNameAttribute();
3027
3028 if (!oldName.isNull() || !newName.isNull())
3029 updateName(oldName, newName);
3030
Ben Murdoche69819b2013-07-17 14:56:49 +01003031 // Quirks mode makes class and id not case sensitive. We can't share the ElementData
3032 // if the idForStyleResolution and the className need different casing.
3033 bool ownerDocumentsHaveDifferentCaseSensitivity = false;
3034 if (other.hasClass() || other.hasID())
3035 ownerDocumentsHaveDifferentCaseSensitivity = other.document()->inQuirksMode() != document()->inQuirksMode();
3036
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01003037 // If 'other' has a mutable ElementData, convert it to an immutable one so we can share it between both elements.
Ben Murdoche69819b2013-07-17 14:56:49 +01003038 // We can only do this if there is no CSSOM wrapper for other's inline style, and there are no presentation attributes,
3039 // and sharing the data won't result in different case sensitivity of class or id.
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01003040 if (other.m_elementData->isUnique()
Ben Murdoche69819b2013-07-17 14:56:49 +01003041 && !ownerDocumentsHaveDifferentCaseSensitivity
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01003042 && !other.m_elementData->presentationAttributeStyle()
3043 && (!other.m_elementData->inlineStyle() || !other.m_elementData->inlineStyle()->hasCSSOMWrapper()))
3044 const_cast<Element&>(other).m_elementData = static_cast<const UniqueElementData*>(other.m_elementData.get())->makeShareableCopy();
3045
Ben Murdoche69819b2013-07-17 14:56:49 +01003046 if (!other.m_elementData->isUnique() && !ownerDocumentsHaveDifferentCaseSensitivity)
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01003047 m_elementData = other.m_elementData;
3048 else
3049 m_elementData = other.m_elementData->makeUniqueCopy();
3050
3051 for (unsigned i = 0; i < m_elementData->length(); ++i) {
3052 const Attribute* attribute = const_cast<const ElementData*>(m_elementData.get())->attributeItem(i);
3053 attributeChangedFromParserOrByCloning(attribute->name(), attribute->value(), ModifiedByCloning);
3054 }
3055}
3056
3057void Element::cloneDataFromElement(const Element& other)
3058{
3059 cloneAttributesFromElement(other);
3060 copyNonAttributePropertiesFromElement(other);
3061}
3062
3063void Element::createUniqueElementData()
3064{
3065 if (!m_elementData)
3066 m_elementData = UniqueElementData::create();
3067 else {
3068 ASSERT(!m_elementData->isUnique());
3069 m_elementData = static_cast<ShareableElementData*>(m_elementData.get())->makeUniqueCopy();
3070 }
3071}
3072
3073void Element::reportMemoryUsage(MemoryObjectInfo* memoryObjectInfo) const
3074{
3075 MemoryClassInfo info(memoryObjectInfo, this, WebCoreMemoryTypes::DOM);
3076 ContainerNode::reportMemoryUsage(memoryObjectInfo);
3077 info.addMember(m_tagName, "tagName");
3078 info.addMember(m_elementData, "elementData");
3079}
3080
Torne (Richard Coles)81a51572013-05-13 16:52:28 +01003081InputMethodContext* Element::getInputContext()
3082{
3083 return ensureElementRareData()->ensureInputMethodContext(toHTMLElement(this));
3084}
3085
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01003086bool Element::hasPendingResources() const
3087{
3088 return hasRareData() && elementRareData()->hasPendingResources();
3089}
3090
3091void Element::setHasPendingResources()
3092{
3093 ensureElementRareData()->setHasPendingResources(true);
3094}
3095
3096void Element::clearHasPendingResources()
3097{
3098 ensureElementRareData()->setHasPendingResources(false);
3099}
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01003100
Ben Murdoch591b9582013-07-10 11:41:44 +01003101struct PresentationAttributeCacheKey {
3102 PresentationAttributeCacheKey() : tagName(0) { }
3103 AtomicStringImpl* tagName;
3104 // Only the values need refcounting.
3105 Vector<pair<AtomicStringImpl*, AtomicString>, 3> attributesAndValues;
3106};
3107
3108struct PresentationAttributeCacheEntry {
3109 WTF_MAKE_FAST_ALLOCATED;
3110public:
3111 PresentationAttributeCacheKey key;
3112 RefPtr<StylePropertySet> value;
3113};
3114
3115typedef HashMap<unsigned, OwnPtr<PresentationAttributeCacheEntry>, AlreadyHashed> PresentationAttributeCache;
3116
3117static bool operator!=(const PresentationAttributeCacheKey& a, const PresentationAttributeCacheKey& b)
3118{
3119 if (a.tagName != b.tagName)
3120 return true;
3121 return a.attributesAndValues != b.attributesAndValues;
3122}
3123
3124static PresentationAttributeCache& presentationAttributeCache()
3125{
3126 DEFINE_STATIC_LOCAL(PresentationAttributeCache, cache, ());
3127 return cache;
3128}
3129
3130class PresentationAttributeCacheCleaner {
3131 WTF_MAKE_NONCOPYABLE(PresentationAttributeCacheCleaner); WTF_MAKE_FAST_ALLOCATED;
3132public:
3133 PresentationAttributeCacheCleaner()
3134 : m_hitCount(0)
3135 , m_cleanTimer(this, &PresentationAttributeCacheCleaner::cleanCache)
3136 {
3137 }
3138
3139 void didHitPresentationAttributeCache()
3140 {
3141 if (presentationAttributeCache().size() < minimumPresentationAttributeCacheSizeForCleaning)
3142 return;
3143
3144 m_hitCount++;
3145
3146 if (!m_cleanTimer.isActive())
3147 m_cleanTimer.startOneShot(presentationAttributeCacheCleanTimeInSeconds);
3148 }
3149
3150private:
3151 static const unsigned presentationAttributeCacheCleanTimeInSeconds = 60;
3152 static const int minimumPresentationAttributeCacheSizeForCleaning = 100;
3153 static const unsigned minimumPresentationAttributeCacheHitCountPerMinute = (100 * presentationAttributeCacheCleanTimeInSeconds) / 60;
3154
3155 void cleanCache(Timer<PresentationAttributeCacheCleaner>* timer)
3156 {
3157 ASSERT_UNUSED(timer, timer == &m_cleanTimer);
3158 unsigned hitCount = m_hitCount;
3159 m_hitCount = 0;
3160 if (hitCount > minimumPresentationAttributeCacheHitCountPerMinute)
3161 return;
3162 presentationAttributeCache().clear();
3163 }
3164
3165 unsigned m_hitCount;
3166 Timer<PresentationAttributeCacheCleaner> m_cleanTimer;
3167};
3168
3169static PresentationAttributeCacheCleaner& presentationAttributeCacheCleaner()
3170{
3171 DEFINE_STATIC_LOCAL(PresentationAttributeCacheCleaner, cleaner, ());
3172 return cleaner;
3173}
3174
3175void Element::synchronizeStyleAttributeInternal() const
3176{
3177 ASSERT(isStyledElement());
3178 ASSERT(elementData());
3179 ASSERT(elementData()->m_styleAttributeIsDirty);
3180 elementData()->m_styleAttributeIsDirty = false;
3181 if (const StylePropertySet* inlineStyle = this->inlineStyle())
3182 const_cast<Element*>(this)->setSynchronizedLazyAttribute(styleAttr, inlineStyle->asText());
3183}
3184
3185CSSStyleDeclaration* Element::style()
3186{
3187 if (!isStyledElement())
3188 return 0;
3189 return ensureMutableInlineStyle()->ensureInlineCSSStyleDeclaration(this);
3190}
3191
3192MutableStylePropertySet* Element::ensureMutableInlineStyle()
3193{
3194 ASSERT(isStyledElement());
3195 RefPtr<StylePropertySet>& inlineStyle = ensureUniqueElementData()->m_inlineStyle;
3196 if (!inlineStyle)
3197 inlineStyle = MutableStylePropertySet::create(strictToCSSParserMode(isHTMLElement() && !document()->inQuirksMode()));
3198 else if (!inlineStyle->isMutable())
3199 inlineStyle = inlineStyle->mutableCopy();
3200 ASSERT(inlineStyle->isMutable());
3201 return static_cast<MutableStylePropertySet*>(inlineStyle.get());
3202}
3203
3204PropertySetCSSStyleDeclaration* Element::inlineStyleCSSOMWrapper()
3205{
3206 if (!inlineStyle() || !inlineStyle()->hasCSSOMWrapper())
3207 return 0;
3208 PropertySetCSSStyleDeclaration* cssomWrapper = ensureMutableInlineStyle()->cssStyleDeclaration();
3209 ASSERT(cssomWrapper && cssomWrapper->parentElement() == this);
3210 return cssomWrapper;
3211}
3212
3213inline void Element::setInlineStyleFromString(const AtomicString& newStyleString)
3214{
3215 ASSERT(isStyledElement());
3216 RefPtr<StylePropertySet>& inlineStyle = elementData()->m_inlineStyle;
3217
3218 // Avoid redundant work if we're using shared attribute data with already parsed inline style.
3219 if (inlineStyle && !elementData()->isUnique())
3220 return;
3221
3222 // We reconstruct the property set instead of mutating if there is no CSSOM wrapper.
3223 // This makes wrapperless property sets immutable and so cacheable.
3224 if (inlineStyle && !inlineStyle->isMutable())
3225 inlineStyle.clear();
3226
3227 if (!inlineStyle) {
3228 inlineStyle = CSSParser::parseInlineStyleDeclaration(newStyleString, this);
3229 } else {
3230 ASSERT(inlineStyle->isMutable());
3231 static_pointer_cast<MutableStylePropertySet>(inlineStyle)->parseDeclaration(newStyleString, document()->elementSheet()->contents());
3232 }
3233}
3234
3235void Element::styleAttributeChanged(const AtomicString& newStyleString, AttributeModificationReason modificationReason)
3236{
3237 ASSERT(isStyledElement());
3238 WTF::OrdinalNumber startLineNumber = WTF::OrdinalNumber::beforeFirst();
3239 if (document() && document()->scriptableDocumentParser() && !document()->isInDocumentWrite())
3240 startLineNumber = document()->scriptableDocumentParser()->lineNumber();
3241
3242 if (newStyleString.isNull()) {
3243 if (PropertySetCSSStyleDeclaration* cssomWrapper = inlineStyleCSSOMWrapper())
3244 cssomWrapper->clearParentElement();
3245 ensureUniqueElementData()->m_inlineStyle.clear();
3246 } else if (modificationReason == ModifiedByCloning || document()->contentSecurityPolicy()->allowInlineStyle(document()->url(), startLineNumber)) {
3247 setInlineStyleFromString(newStyleString);
3248 }
3249
3250 elementData()->m_styleAttributeIsDirty = false;
3251
Ben Murdoche69819b2013-07-17 14:56:49 +01003252 setNeedsStyleRecalc(LocalStyleChange);
Ben Murdoch591b9582013-07-10 11:41:44 +01003253 InspectorInstrumentation::didInvalidateStyleAttr(document(), this);
3254}
3255
3256void Element::inlineStyleChanged()
3257{
3258 ASSERT(isStyledElement());
Ben Murdoche69819b2013-07-17 14:56:49 +01003259 setNeedsStyleRecalc(LocalStyleChange);
Ben Murdoch591b9582013-07-10 11:41:44 +01003260 ASSERT(elementData());
3261 elementData()->m_styleAttributeIsDirty = true;
3262 InspectorInstrumentation::didInvalidateStyleAttr(document(), this);
3263}
3264
3265bool Element::setInlineStyleProperty(CSSPropertyID propertyID, CSSValueID identifier, bool important)
3266{
3267 ASSERT(isStyledElement());
3268 ensureMutableInlineStyle()->setProperty(propertyID, cssValuePool().createIdentifierValue(identifier), important);
3269 inlineStyleChanged();
3270 return true;
3271}
3272
3273bool Element::setInlineStyleProperty(CSSPropertyID propertyID, CSSPropertyID identifier, bool important)
3274{
3275 ASSERT(isStyledElement());
3276 ensureMutableInlineStyle()->setProperty(propertyID, cssValuePool().createIdentifierValue(identifier), important);
3277 inlineStyleChanged();
3278 return true;
3279}
3280
3281bool Element::setInlineStyleProperty(CSSPropertyID propertyID, double value, CSSPrimitiveValue::UnitTypes unit, bool important)
3282{
3283 ASSERT(isStyledElement());
3284 ensureMutableInlineStyle()->setProperty(propertyID, cssValuePool().createValue(value, unit), important);
3285 inlineStyleChanged();
3286 return true;
3287}
3288
3289bool Element::setInlineStyleProperty(CSSPropertyID propertyID, const String& value, bool important)
3290{
3291 ASSERT(isStyledElement());
3292 bool changes = ensureMutableInlineStyle()->setProperty(propertyID, value, important, document()->elementSheet()->contents());
3293 if (changes)
3294 inlineStyleChanged();
3295 return changes;
3296}
3297
3298bool Element::removeInlineStyleProperty(CSSPropertyID propertyID)
3299{
3300 ASSERT(isStyledElement());
3301 if (!inlineStyle())
3302 return false;
3303 bool changes = ensureMutableInlineStyle()->removeProperty(propertyID);
3304 if (changes)
3305 inlineStyleChanged();
3306 return changes;
3307}
3308
3309void Element::removeAllInlineStyleProperties()
3310{
3311 ASSERT(isStyledElement());
3312 if (!inlineStyle() || inlineStyle()->isEmpty())
3313 return;
3314 ensureMutableInlineStyle()->clear();
3315 inlineStyleChanged();
3316}
3317
3318void Element::addSubresourceAttributeURLs(ListHashSet<KURL>& urls) const
3319{
3320 ASSERT(isStyledElement());
3321 if (const StylePropertySet* inlineStyle = elementData() ? elementData()->inlineStyle() : 0)
3322 inlineStyle->addSubresourceStyleURLs(urls, document()->elementSheet()->contents());
3323}
3324
3325static inline bool attributeNameSort(const pair<AtomicStringImpl*, AtomicString>& p1, const pair<AtomicStringImpl*, AtomicString>& p2)
3326{
3327 // Sort based on the attribute name pointers. It doesn't matter what the order is as long as it is always the same.
3328 return p1.first < p2.first;
3329}
3330
3331void Element::makePresentationAttributeCacheKey(PresentationAttributeCacheKey& result) const
3332{
3333 ASSERT(isStyledElement());
3334 // FIXME: Enable for SVG.
3335 if (namespaceURI() != xhtmlNamespaceURI)
3336 return;
3337 // Interpretation of the size attributes on <input> depends on the type attribute.
3338 if (hasTagName(inputTag))
3339 return;
3340 unsigned size = attributeCount();
3341 for (unsigned i = 0; i < size; ++i) {
3342 const Attribute* attribute = attributeItem(i);
3343 if (!isPresentationAttribute(attribute->name()))
3344 continue;
3345 if (!attribute->namespaceURI().isNull())
3346 return;
3347 // FIXME: Background URL may depend on the base URL and can't be shared. Disallow caching.
3348 if (attribute->name() == backgroundAttr)
3349 return;
3350 result.attributesAndValues.append(std::make_pair(attribute->localName().impl(), attribute->value()));
3351 }
3352 if (result.attributesAndValues.isEmpty())
3353 return;
3354 // Attribute order doesn't matter. Sort for easy equality comparison.
3355 std::sort(result.attributesAndValues.begin(), result.attributesAndValues.end(), attributeNameSort);
3356 // The cache key is non-null when the tagName is set.
3357 result.tagName = localName().impl();
3358}
3359
3360static unsigned computePresentationAttributeCacheHash(const PresentationAttributeCacheKey& key)
3361{
3362 if (!key.tagName)
3363 return 0;
3364 ASSERT(key.attributesAndValues.size());
3365 unsigned attributeHash = StringHasher::hashMemory(key.attributesAndValues.data(), key.attributesAndValues.size() * sizeof(key.attributesAndValues[0]));
3366 return WTF::pairIntHash(key.tagName->existingHash(), attributeHash);
3367}
3368
3369void Element::rebuildPresentationAttributeStyle()
3370{
3371 ASSERT(isStyledElement());
3372 PresentationAttributeCacheKey cacheKey;
3373 makePresentationAttributeCacheKey(cacheKey);
3374
3375 unsigned cacheHash = computePresentationAttributeCacheHash(cacheKey);
3376
3377 PresentationAttributeCache::iterator cacheIterator;
3378 if (cacheHash) {
3379 cacheIterator = presentationAttributeCache().add(cacheHash, nullptr).iterator;
3380 if (cacheIterator->value && cacheIterator->value->key != cacheKey)
3381 cacheHash = 0;
3382 } else {
3383 cacheIterator = presentationAttributeCache().end();
3384 }
3385
3386 RefPtr<StylePropertySet> style;
3387 if (cacheHash && cacheIterator->value) {
3388 style = cacheIterator->value->value;
3389 presentationAttributeCacheCleaner().didHitPresentationAttributeCache();
3390 } else {
3391 style = MutableStylePropertySet::create(isSVGElement() ? SVGAttributeMode : CSSQuirksMode);
3392 unsigned size = attributeCount();
3393 for (unsigned i = 0; i < size; ++i) {
3394 const Attribute* attribute = attributeItem(i);
3395 collectStyleForPresentationAttribute(attribute->name(), attribute->value(), static_cast<MutableStylePropertySet*>(style.get()));
3396 }
3397 }
3398
3399 // ShareableElementData doesn't store presentation attribute style, so make sure we have a UniqueElementData.
3400 UniqueElementData* elementData = ensureUniqueElementData();
3401
3402 elementData->m_presentationAttributeStyleIsDirty = false;
3403 elementData->m_presentationAttributeStyle = style->isEmpty() ? 0 : style;
3404
3405 if (!cacheHash || cacheIterator->value)
3406 return;
3407
3408 OwnPtr<PresentationAttributeCacheEntry> newEntry = adoptPtr(new PresentationAttributeCacheEntry);
3409 newEntry->key = cacheKey;
3410 newEntry->value = style.release();
3411
3412 static const int presentationAttributeCacheMaximumSize = 4096;
3413 if (presentationAttributeCache().size() > presentationAttributeCacheMaximumSize) {
3414 // Start building from scratch if the cache ever gets big.
3415 presentationAttributeCache().clear();
3416 presentationAttributeCache().set(cacheHash, newEntry.release());
3417 } else {
3418 cacheIterator->value = newEntry.release();
3419 }
3420}
3421
3422void Element::addPropertyToPresentationAttributeStyle(MutableStylePropertySet* style, CSSPropertyID propertyID, CSSValueID identifier)
3423{
3424 ASSERT(isStyledElement());
3425 style->setProperty(propertyID, cssValuePool().createIdentifierValue(identifier));
3426}
3427
3428void Element::addPropertyToPresentationAttributeStyle(MutableStylePropertySet* style, CSSPropertyID propertyID, double value, CSSPrimitiveValue::UnitTypes unit)
3429{
3430 ASSERT(isStyledElement());
3431 style->setProperty(propertyID, cssValuePool().createValue(value, unit));
3432}
3433
3434void Element::addPropertyToPresentationAttributeStyle(MutableStylePropertySet* style, CSSPropertyID propertyID, const String& value)
3435{
3436 ASSERT(isStyledElement());
3437 style->setProperty(propertyID, value, false, document()->elementSheet()->contents());
3438}
3439
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01003440void ElementData::deref()
3441{
3442 if (!derefBase())
3443 return;
3444
3445 if (m_isUnique)
3446 delete static_cast<UniqueElementData*>(this);
3447 else
3448 delete static_cast<ShareableElementData*>(this);
3449}
3450
3451ElementData::ElementData()
3452 : m_isUnique(true)
3453 , m_arraySize(0)
3454 , m_presentationAttributeStyleIsDirty(false)
3455 , m_styleAttributeIsDirty(false)
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01003456 , m_animatedSVGAttributesAreDirty(false)
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01003457{
3458}
3459
3460ElementData::ElementData(unsigned arraySize)
3461 : m_isUnique(false)
3462 , m_arraySize(arraySize)
3463 , m_presentationAttributeStyleIsDirty(false)
3464 , m_styleAttributeIsDirty(false)
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01003465 , m_animatedSVGAttributesAreDirty(false)
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01003466{
3467}
3468
3469struct SameSizeAsElementData : public RefCounted<SameSizeAsElementData> {
3470 unsigned bitfield;
3471 void* refPtrs[3];
3472};
3473
3474COMPILE_ASSERT(sizeof(ElementData) == sizeof(SameSizeAsElementData), element_attribute_data_should_stay_small);
3475
3476static size_t sizeForShareableElementDataWithAttributeCount(unsigned count)
3477{
3478 return sizeof(ShareableElementData) + sizeof(Attribute) * count;
3479}
3480
3481PassRefPtr<ShareableElementData> ShareableElementData::createWithAttributes(const Vector<Attribute>& attributes)
3482{
3483 void* slot = WTF::fastMalloc(sizeForShareableElementDataWithAttributeCount(attributes.size()));
3484 return adoptRef(new (slot) ShareableElementData(attributes));
3485}
3486
3487PassRefPtr<UniqueElementData> UniqueElementData::create()
3488{
3489 return adoptRef(new UniqueElementData);
3490}
3491
3492ShareableElementData::ShareableElementData(const Vector<Attribute>& attributes)
3493 : ElementData(attributes.size())
3494{
3495 for (unsigned i = 0; i < m_arraySize; ++i)
3496 new (&m_attributeArray[i]) Attribute(attributes[i]);
3497}
3498
3499ShareableElementData::~ShareableElementData()
3500{
3501 for (unsigned i = 0; i < m_arraySize; ++i)
3502 m_attributeArray[i].~Attribute();
3503}
3504
3505ShareableElementData::ShareableElementData(const UniqueElementData& other)
3506 : ElementData(other, false)
3507{
3508 ASSERT(!other.m_presentationAttributeStyle);
3509
3510 if (other.m_inlineStyle) {
3511 ASSERT(!other.m_inlineStyle->hasCSSOMWrapper());
3512 m_inlineStyle = other.m_inlineStyle->immutableCopyIfNeeded();
3513 }
3514
3515 for (unsigned i = 0; i < m_arraySize; ++i)
3516 new (&m_attributeArray[i]) Attribute(other.m_attributeVector.at(i));
3517}
3518
3519ElementData::ElementData(const ElementData& other, bool isUnique)
3520 : m_isUnique(isUnique)
3521 , m_arraySize(isUnique ? 0 : other.length())
3522 , m_presentationAttributeStyleIsDirty(other.m_presentationAttributeStyleIsDirty)
3523 , m_styleAttributeIsDirty(other.m_styleAttributeIsDirty)
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01003524 , m_animatedSVGAttributesAreDirty(other.m_animatedSVGAttributesAreDirty)
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01003525 , m_classNames(other.m_classNames)
3526 , m_idForStyleResolution(other.m_idForStyleResolution)
3527{
3528 // NOTE: The inline style is copied by the subclass copy constructor since we don't know what to do with it here.
3529}
3530
3531UniqueElementData::UniqueElementData()
3532{
3533}
3534
3535UniqueElementData::UniqueElementData(const UniqueElementData& other)
3536 : ElementData(other, true)
3537 , m_presentationAttributeStyle(other.m_presentationAttributeStyle)
3538 , m_attributeVector(other.m_attributeVector)
3539{
Torne (Richard Coles)93ac45c2013-05-29 14:40:20 +01003540 m_inlineStyle = other.m_inlineStyle ? other.m_inlineStyle->mutableCopy() : 0;
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01003541}
3542
3543UniqueElementData::UniqueElementData(const ShareableElementData& other)
3544 : ElementData(other, true)
3545{
3546 // An ShareableElementData should never have a mutable inline StylePropertySet attached.
3547 ASSERT(!other.m_inlineStyle || !other.m_inlineStyle->isMutable());
3548 m_inlineStyle = other.m_inlineStyle;
3549
3550 m_attributeVector.reserveCapacity(other.length());
3551 for (unsigned i = 0; i < other.length(); ++i)
3552 m_attributeVector.uncheckedAppend(other.m_attributeArray[i]);
3553}
3554
3555PassRefPtr<UniqueElementData> ElementData::makeUniqueCopy() const
3556{
3557 if (isUnique())
3558 return adoptRef(new UniqueElementData(static_cast<const UniqueElementData&>(*this)));
3559 return adoptRef(new UniqueElementData(static_cast<const ShareableElementData&>(*this)));
3560}
3561
3562PassRefPtr<ShareableElementData> UniqueElementData::makeShareableCopy() const
3563{
3564 void* slot = WTF::fastMalloc(sizeForShareableElementDataWithAttributeCount(m_attributeVector.size()));
3565 return adoptRef(new (slot) ShareableElementData(*this));
3566}
3567
3568void UniqueElementData::addAttribute(const QualifiedName& attributeName, const AtomicString& value)
3569{
3570 m_attributeVector.append(Attribute(attributeName, value));
3571}
3572
3573void UniqueElementData::removeAttribute(size_t index)
3574{
3575 ASSERT_WITH_SECURITY_IMPLICATION(index < length());
3576 m_attributeVector.remove(index);
3577}
3578
3579bool ElementData::isEquivalent(const ElementData* other) const
3580{
3581 if (!other)
3582 return isEmpty();
3583
3584 unsigned len = length();
3585 if (len != other->length())
3586 return false;
3587
3588 for (unsigned i = 0; i < len; i++) {
3589 const Attribute* attribute = attributeItem(i);
3590 const Attribute* otherAttr = other->getAttributeItem(attribute->name());
3591 if (!otherAttr || attribute->value() != otherAttr->value())
3592 return false;
3593 }
3594
3595 return true;
3596}
3597
3598void ElementData::reportMemoryUsage(MemoryObjectInfo* memoryObjectInfo) const
3599{
3600 size_t actualSize = m_isUnique ? sizeof(ElementData) : sizeForShareableElementDataWithAttributeCount(m_arraySize);
3601 MemoryClassInfo info(memoryObjectInfo, this, WebCoreMemoryTypes::DOM, actualSize);
3602 info.addMember(m_inlineStyle, "inlineStyle");
3603 info.addMember(m_classNames, "classNames");
3604 info.addMember(m_idForStyleResolution, "idForStyleResolution");
3605 if (m_isUnique) {
3606 const UniqueElementData* uniqueThis = static_cast<const UniqueElementData*>(this);
3607 info.addMember(uniqueThis->m_presentationAttributeStyle, "presentationAttributeStyle");
3608 info.addMember(uniqueThis->m_attributeVector, "attributeVector");
3609 }
3610 for (unsigned i = 0, len = length(); i < len; i++)
3611 info.addMember(*attributeItem(i), "*attributeItem");
3612}
3613
Torne (Richard Coles)e5249552013-05-15 11:35:13 +01003614size_t ElementData::getAttrIndex(Attr* attr) const
3615{
3616 // This relies on the fact that Attr's QualifiedName == the Attribute's name.
3617 for (unsigned i = 0; i < length(); ++i) {
3618 if (attributeItem(i)->name() == attr->qualifiedName())
3619 return i;
3620 }
3621 return notFound;
3622}
3623
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01003624size_t ElementData::getAttributeItemIndexSlowCase(const AtomicString& name, bool shouldIgnoreAttributeCase) const
3625{
3626 // Continue to checking case-insensitively and/or full namespaced names if necessary:
3627 for (unsigned i = 0; i < length(); ++i) {
3628 const Attribute* attribute = attributeItem(i);
3629 if (!attribute->name().hasPrefix()) {
3630 if (shouldIgnoreAttributeCase && equalIgnoringCase(name, attribute->localName()))
3631 return i;
3632 } else {
3633 // FIXME: Would be faster to do this comparison without calling toString, which
3634 // generates a temporary string by concatenation. But this branch is only reached
3635 // if the attribute name has a prefix, which is rare in HTML.
3636 if (equalPossiblyIgnoringCase(name, attribute->name().toString(), shouldIgnoreAttributeCase))
3637 return i;
3638 }
3639 }
3640 return notFound;
3641}
3642
3643Attribute* UniqueElementData::getAttributeItem(const QualifiedName& name)
3644{
3645 for (unsigned i = 0; i < length(); ++i) {
3646 if (m_attributeVector.at(i).name().matches(name))
3647 return &m_attributeVector.at(i);
3648 }
3649 return 0;
3650}
3651
3652Attribute* UniqueElementData::attributeItem(unsigned index)
3653{
3654 ASSERT_WITH_SECURITY_IMPLICATION(index < length());
3655 return &m_attributeVector.at(index);
3656}
3657
3658} // namespace WebCore