blob: 7f381978a9a9c09bdf91da623a831f7d4f3fc282 [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"
Ben Murdoch7757ec22013-07-23 11:17:36 +010032#include "RuntimeEnabledFeatures.h"
Torne (Richard Coles)93ac45c2013-05-29 14:40:20 +010033#include "SVGNames.h"
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +010034#include "XMLNames.h"
35#include "core/accessibility/AXObjectCache.h"
Ben Murdoch83750172013-07-24 10:36:59 +010036#include "core/animation/DocumentTimeline.h"
Ben Murdoch591b9582013-07-10 11:41:44 +010037#include "core/css/CSSParser.h"
38#include "core/css/CSSStyleSheet.h"
39#include "core/css/CSSValuePool.h"
40#include "core/css/PropertySetCSSStyleDeclaration.h"
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +010041#include "core/css/StylePropertySet.h"
Torne (Richard Coles)81a51572013-05-13 16:52:28 +010042#include "core/css/resolver/StyleResolver.h"
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +010043#include "core/dom/Attr.h"
Ben Murdoch591b9582013-07-10 11:41:44 +010044#include "core/dom/Attribute.h"
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +010045#include "core/dom/ClientRect.h"
46#include "core/dom/ClientRectList.h"
Ben Murdoch83750172013-07-24 10:36:59 +010047#include "core/dom/CustomElement.h"
Ben Murdoche69819b2013-07-17 14:56:49 +010048#include "core/dom/CustomElementRegistrationContext.h"
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +010049#include "core/dom/DatasetDOMStringMap.h"
50#include "core/dom/Document.h"
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +010051#include "core/dom/DocumentSharedObjectPool.h"
52#include "core/dom/ElementRareData.h"
Ben Murdoch02772c62013-07-26 10:21:05 +010053#include "core/dom/EventDispatcher.h"
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +010054#include "core/dom/ExceptionCode.h"
Ben Murdoch02772c62013-07-26 10:21:05 +010055#include "core/dom/FocusEvent.h"
Torne (Richard Coles)521d96e2013-06-19 11:58:24 +010056#include "core/dom/FullscreenController.h"
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +010057#include "core/dom/MutationObserverInterestGroup.h"
58#include "core/dom/MutationRecord.h"
59#include "core/dom/NamedNodeMap.h"
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +010060#include "core/dom/NodeRenderStyle.h"
61#include "core/dom/NodeRenderingContext.h"
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +010062#include "core/dom/PseudoElement.h"
Ben Murdoch591b9582013-07-10 11:41:44 +010063#include "core/dom/ScriptableDocumentParser.h"
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +010064#include "core/dom/SelectorQuery.h"
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +010065#include "core/dom/Text.h"
Torne (Richard Coles)e5249552013-05-15 11:35:13 +010066#include "core/dom/shadow/InsertionPoint.h"
67#include "core/dom/shadow/ShadowRoot.h"
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +010068#include "core/editing/FrameSelection.h"
69#include "core/editing/TextIterator.h"
70#include "core/editing/htmlediting.h"
71#include "core/html/ClassList.h"
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +010072#include "core/html/HTMLCollection.h"
73#include "core/html/HTMLDocument.h"
74#include "core/html/HTMLElement.h"
75#include "core/html/HTMLFormControlsCollection.h"
76#include "core/html/HTMLFrameOwnerElement.h"
77#include "core/html/HTMLLabelElement.h"
78#include "core/html/HTMLOptionsCollection.h"
79#include "core/html/HTMLTableRowsCollection.h"
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +010080#include "core/html/parser/HTMLParserIdioms.h"
Ben Murdoch591b9582013-07-10 11:41:44 +010081#include "core/page/ContentSecurityPolicy.h"
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +010082#include "core/page/FocusController.h"
83#include "core/page/Frame.h"
84#include "core/page/FrameView.h"
85#include "core/page/Page.h"
86#include "core/page/PointerLockController.h"
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +010087#include "core/rendering/FlowThreadController.h"
88#include "core/rendering/RenderRegion.h"
89#include "core/rendering/RenderView.h"
90#include "core/rendering/RenderWidget.h"
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +010091#include "core/svg/SVGDocumentExtensions.h"
92#include "core/svg/SVGElement.h"
Torne (Richard Coles)93ac45c2013-05-29 14:40:20 +010093#include "wtf/BitVector.h"
Ben Murdoch591b9582013-07-10 11:41:44 +010094#include "wtf/HashFunctions.h"
Torne (Richard Coles)93ac45c2013-05-29 14:40:20 +010095#include "wtf/text/CString.h"
Ben Murdoch591b9582013-07-10 11:41:44 +010096#include "wtf/text/TextPosition.h"
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +010097
98namespace WebCore {
99
100using namespace HTMLNames;
101using namespace XMLNames;
102
103static inline bool shouldIgnoreAttributeCase(const Element* e)
104{
105 return e && e->document()->isHTMLDocument() && e->isHTMLElement();
106}
Ben Murdoch591b9582013-07-10 11:41:44 +0100107
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100108class StyleResolverParentPusher {
109public:
110 StyleResolverParentPusher(Element* parent)
111 : m_parent(parent)
112 , m_pushedStyleResolver(0)
113 {
114 }
115 void push()
116 {
117 if (m_pushedStyleResolver)
118 return;
119 m_pushedStyleResolver = m_parent->document()->styleResolver();
120 m_pushedStyleResolver->pushParentElement(m_parent);
121 }
122 ~StyleResolverParentPusher()
123 {
124
125 if (!m_pushedStyleResolver)
126 return;
127
128 // This tells us that our pushed style selector is in a bad state,
129 // so we should just bail out in that scenario.
130 ASSERT(m_pushedStyleResolver == m_parent->document()->styleResolver());
131 if (m_pushedStyleResolver != m_parent->document()->styleResolver())
132 return;
133
134 m_pushedStyleResolver->popParentElement(m_parent);
135 }
136
137private:
138 Element* m_parent;
139 StyleResolver* m_pushedStyleResolver;
140};
141
142typedef Vector<RefPtr<Attr> > AttrNodeList;
143typedef HashMap<Element*, OwnPtr<AttrNodeList> > AttrNodeListMap;
144
145static AttrNodeListMap& attrNodeListMap()
146{
147 DEFINE_STATIC_LOCAL(AttrNodeListMap, map, ());
148 return map;
149}
150
151static AttrNodeList* attrNodeListForElement(Element* element)
152{
153 if (!element->hasSyntheticAttrChildNodes())
154 return 0;
155 ASSERT(attrNodeListMap().contains(element));
156 return attrNodeListMap().get(element);
157}
158
159static AttrNodeList* ensureAttrNodeListForElement(Element* element)
160{
161 if (element->hasSyntheticAttrChildNodes()) {
162 ASSERT(attrNodeListMap().contains(element));
163 return attrNodeListMap().get(element);
164 }
165 ASSERT(!attrNodeListMap().contains(element));
166 element->setHasSyntheticAttrChildNodes(true);
167 AttrNodeListMap::AddResult result = attrNodeListMap().add(element, adoptPtr(new AttrNodeList));
168 return result.iterator->value.get();
169}
170
171static void removeAttrNodeListForElement(Element* element)
172{
173 ASSERT(element->hasSyntheticAttrChildNodes());
174 ASSERT(attrNodeListMap().contains(element));
175 attrNodeListMap().remove(element);
176 element->setHasSyntheticAttrChildNodes(false);
177}
178
179static Attr* findAttrNodeInList(AttrNodeList* attrNodeList, const QualifiedName& name)
180{
181 for (unsigned i = 0; i < attrNodeList->size(); ++i) {
182 if (attrNodeList->at(i)->qualifiedName() == name)
183 return attrNodeList->at(i).get();
184 }
185 return 0;
186}
187
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100188PassRefPtr<Element> Element::create(const QualifiedName& tagName, Document* document)
189{
190 return adoptRef(new Element(tagName, document, CreateElement));
191}
192
193Element::~Element()
194{
195#ifndef NDEBUG
196 if (document() && document()->renderer()) {
197 // When the document is not destroyed, an element that was part of a named flow
198 // content nodes should have been removed from the content nodes collection
199 // and the inNamedFlow flag reset.
200 ASSERT(!inNamedFlow());
201 }
202#endif
203
Ben Murdoch591b9582013-07-10 11:41:44 +0100204 if (PropertySetCSSStyleDeclaration* cssomWrapper = inlineStyleCSSOMWrapper())
205 cssomWrapper->clearParentElement();
206
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100207 if (hasRareData()) {
208 ElementRareData* data = elementRareData();
209 data->setPseudoElement(BEFORE, 0);
210 data->setPseudoElement(AFTER, 0);
Ben Murdoche69819b2013-07-17 14:56:49 +0100211 data->setPseudoElement(BACKDROP, 0);
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100212 data->clearShadow();
213 }
214
Ben Murdoch83750172013-07-24 10:36:59 +0100215 if (isCustomElement())
216 CustomElement::wasDestroyed(this);
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100217
218 if (hasSyntheticAttrChildNodes())
219 detachAllAttrNodesFromElement();
220
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100221 if (hasPendingResources()) {
222 document()->accessSVGExtensions()->removeElementFromPendingResources(this);
223 ASSERT(!hasPendingResources());
224 }
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100225}
226
227inline ElementRareData* Element::elementRareData() const
228{
229 ASSERT(hasRareData());
230 return static_cast<ElementRareData*>(rareData());
231}
232
233inline ElementRareData* Element::ensureElementRareData()
234{
235 return static_cast<ElementRareData*>(ensureRareData());
236}
237
238void Element::clearTabIndexExplicitlyIfNeeded()
239{
240 if (hasRareData())
241 elementRareData()->clearTabIndexExplicitly();
242}
243
244void Element::setTabIndexExplicitly(short tabIndex)
245{
246 ensureElementRareData()->setTabIndexExplicitly(tabIndex);
247}
248
249bool Element::supportsFocus() const
250{
251 return hasRareData() && elementRareData()->tabIndexSetExplicitly();
252}
253
254short Element::tabIndex() const
255{
256 return hasRareData() ? elementRareData()->tabIndex() : 0;
257}
258
Torne (Richard Coles)521d96e2013-06-19 11:58:24 +0100259bool Element::rendererIsFocusable() const
260{
261 // Elements in canvas fallback content are not rendered, but they are allowed to be
262 // focusable as long as their canvas is displayed and visible.
263 if (isInCanvasSubtree()) {
264 const Element* e = this;
265 while (e && !e->hasLocalName(canvasTag))
266 e = e->parentElement();
267 ASSERT(e);
268 return e->renderer() && e->renderer()->style()->visibility() == VISIBLE;
269 }
270
271 // FIXME: These asserts should be in Node::isFocusable, but there are some
Ben Murdoche69819b2013-07-17 14:56:49 +0100272 // callsites like Document::setFocusedElement that would currently fail on
Torne (Richard Coles)521d96e2013-06-19 11:58:24 +0100273 // them. See crbug.com/251163
274 if (renderer()) {
275 ASSERT(!renderer()->needsLayout());
276 } else {
277 // We can't just use needsStyleRecalc() because if the node is in a
278 // display:none tree it might say it needs style recalc but the whole
279 // document is actually up to date.
280 ASSERT(!document()->childNeedsStyleRecalc());
281 }
282
283 // FIXME: Even if we are not visible, we might have a child that is visible.
284 // Hyatt wants to fix that some day with a "has visible content" flag or the like.
285 if (!renderer() || renderer()->style()->visibility() != VISIBLE)
286 return false;
287
288 return true;
289}
290
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100291DEFINE_VIRTUAL_ATTRIBUTE_EVENT_LISTENER(Element, blur);
292DEFINE_VIRTUAL_ATTRIBUTE_EVENT_LISTENER(Element, error);
293DEFINE_VIRTUAL_ATTRIBUTE_EVENT_LISTENER(Element, focus);
294DEFINE_VIRTUAL_ATTRIBUTE_EVENT_LISTENER(Element, load);
295
296PassRefPtr<Node> Element::cloneNode(bool deep)
297{
298 return deep ? cloneElementWithChildren() : cloneElementWithoutChildren();
299}
300
301PassRefPtr<Element> Element::cloneElementWithChildren()
302{
303 RefPtr<Element> clone = cloneElementWithoutChildren();
304 cloneChildNodes(clone.get());
305 return clone.release();
306}
307
308PassRefPtr<Element> Element::cloneElementWithoutChildren()
309{
310 RefPtr<Element> clone = cloneElementWithoutAttributesAndChildren();
311 // This will catch HTML elements in the wrong namespace that are not correctly copied.
312 // This is a sanity check as HTML overloads some of the DOM methods.
313 ASSERT(isHTMLElement() == clone->isHTMLElement());
314
315 clone->cloneDataFromElement(*this);
316 return clone.release();
317}
318
319PassRefPtr<Element> Element::cloneElementWithoutAttributesAndChildren()
320{
321 return document()->createElement(tagQName(), false);
322}
323
324PassRefPtr<Attr> Element::detachAttribute(size_t index)
325{
326 ASSERT(elementData());
Torne (Richard Coles)e5249552013-05-15 11:35:13 +0100327 const Attribute* attribute = elementData()->attributeItem(index);
328 RefPtr<Attr> attrNode = attrIfExists(attribute->name());
329 if (attrNode)
330 detachAttrNodeAtIndex(attrNode.get(), index);
331 else {
332 attrNode = Attr::create(document(), attribute->name(), attribute->value());
333 removeAttributeInternal(index, NotInSynchronizationOfLazyAttribute);
334 }
335 return attrNode.release();
336}
337
338void Element::detachAttrNodeAtIndex(Attr* attr, size_t index)
339{
340 ASSERT(attr);
341 ASSERT(elementData());
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100342
343 const Attribute* attribute = elementData()->attributeItem(index);
344 ASSERT(attribute);
Torne (Richard Coles)e5249552013-05-15 11:35:13 +0100345 ASSERT(attribute->name() == attr->qualifiedName());
346 detachAttrNodeFromElementWithValue(attr, attribute->value());
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100347 removeAttributeInternal(index, NotInSynchronizationOfLazyAttribute);
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100348}
349
350void Element::removeAttribute(const QualifiedName& name)
351{
352 if (!elementData())
353 return;
354
355 size_t index = elementData()->getAttributeItemIndex(name);
356 if (index == notFound)
357 return;
358
359 removeAttributeInternal(index, NotInSynchronizationOfLazyAttribute);
360}
361
362void Element::setBooleanAttribute(const QualifiedName& name, bool value)
363{
364 if (value)
365 setAttribute(name, emptyAtom);
366 else
367 removeAttribute(name);
368}
369
370NamedNodeMap* Element::attributes() const
371{
372 ElementRareData* rareData = const_cast<Element*>(this)->ensureElementRareData();
373 if (NamedNodeMap* attributeMap = rareData->attributeMap())
374 return attributeMap;
375
376 rareData->setAttributeMap(NamedNodeMap::create(const_cast<Element*>(this)));
377 return rareData->attributeMap();
378}
379
Ben Murdoch83750172013-07-24 10:36:59 +0100380ActiveAnimations* Element::activeAnimations() const
Torne (Richard Coles)81a51572013-05-13 16:52:28 +0100381{
Ben Murdoch83750172013-07-24 10:36:59 +0100382 if (hasActiveAnimations())
383 return elementRareData()->activeAnimations();
384 return 0;
Torne (Richard Coles)81a51572013-05-13 16:52:28 +0100385}
386
Ben Murdoch83750172013-07-24 10:36:59 +0100387ActiveAnimations* Element::ensureActiveAnimations()
Torne (Richard Coles)81a51572013-05-13 16:52:28 +0100388{
Ben Murdoch83750172013-07-24 10:36:59 +0100389 ElementRareData* rareData = ensureElementRareData();
390 if (!elementRareData()->activeAnimations())
391 rareData->setActiveAnimations(adoptPtr(new ActiveAnimations()));
392 return rareData->activeAnimations();
Torne (Richard Coles)81a51572013-05-13 16:52:28 +0100393}
394
395bool Element::hasActiveAnimations() const
396{
Ben Murdoch83750172013-07-24 10:36:59 +0100397 if (!RuntimeEnabledFeatures::webAnimationsEnabled())
398 return false;
Torne (Richard Coles)81a51572013-05-13 16:52:28 +0100399
Ben Murdoch83750172013-07-24 10:36:59 +0100400 if (!hasRareData())
401 return false;
402
403 ActiveAnimations* activeAnimations = elementRareData()->activeAnimations();
404 return activeAnimations && !activeAnimations->isEmpty();
Torne (Richard Coles)81a51572013-05-13 16:52:28 +0100405}
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
Ben Murdoch7757ec22013-07-23 11:17:36 +0100888static bool checkNeedsStyleInvalidationForIdChange(const AtomicString& oldId, const AtomicString& newId, const RuleFeatureSet& features)
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100889{
890 ASSERT(newId != oldId);
Ben Murdoch7757ec22013-07-23 11:17:36 +0100891 if (!oldId.isEmpty() && features.hasSelectorForId(oldId))
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100892 return true;
Ben Murdoch7757ec22013-07-23 11:17:36 +0100893 if (!newId.isEmpty() && features.hasSelectorForId(newId))
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100894 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);
Ben Murdoch7757ec22013-07-23 11:17:36 +0100925 shouldInvalidateStyle = testShouldInvalidateStyle && checkNeedsStyleInvalidationForIdChange(oldId, newId, styleResolver->ruleFeatureSet());
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100926 }
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)
Ben Murdoch0019e4e2013-07-18 11:57:54 +0100950 CustomElementRegistrationContext::setTypeExtension(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();
Ben Murdoch7757ec22013-07-23 11:17:36 +01001033 shouldInvalidateStyle = testShouldInvalidateStyle && checkSelectorForClassChange(oldClasses, newClasses, styleResolver->ruleFeatureSet());
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001034 } else {
1035 const SpaceSplitString& oldClasses = elementData()->classNames();
Ben Murdoch7757ec22013-07-23 11:17:36 +01001036 shouldInvalidateStyle = testShouldInvalidateStyle && checkSelectorForClassChange(oldClasses, styleResolver->ruleFeatureSet());
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001037 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
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001204bool Element::isInert() const
1205{
Torne (Richard Coles)93ac45c2013-05-29 14:40:20 +01001206 const Element* dialog = document()->activeModalDialog();
Ben Murdoch591b9582013-07-10 11:41:44 +01001207 if (dialog && !containsIncludingShadowDOM(dialog) && !dialog->containsIncludingShadowDOM(this))
1208 return true;
1209 return document()->ownerElement() && document()->ownerElement()->isInert();
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001210}
1211
1212Node::InsertionNotificationRequest Element::insertedInto(ContainerNode* insertionPoint)
1213{
1214 // need to do superclass processing first so inDocument() is true
1215 // by the time we reach updateId
1216 ContainerNode::insertedInto(insertionPoint);
1217
1218 if (containsFullScreenElement() && parentElement() && !parentElement()->containsFullScreenElement())
1219 setContainsFullScreenElementOnAncestorsCrossingFrameBoundaries(true);
1220
1221 if (Element* before = pseudoElement(BEFORE))
1222 before->insertedInto(insertionPoint);
1223
1224 if (Element* after = pseudoElement(AFTER))
1225 after->insertedInto(insertionPoint);
1226
1227 if (!insertionPoint->isInTreeScope())
1228 return InsertionDone;
1229
1230 if (hasRareData())
1231 elementRareData()->clearClassListValueForQuirksMode();
1232
1233 TreeScope* scope = insertionPoint->treeScope();
1234 if (scope != treeScope())
1235 return InsertionDone;
1236
Ben Murdoche69819b2013-07-17 14:56:49 +01001237 if (isUpgradedCustomElement())
Ben Murdochfff88842013-07-30 15:20:09 +01001238 CustomElement::didEnterDocument(this, document());
Ben Murdoche69819b2013-07-17 14:56:49 +01001239
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001240 const AtomicString& idValue = getIdAttribute();
1241 if (!idValue.isNull())
1242 updateId(scope, nullAtom, idValue);
1243
1244 const AtomicString& nameValue = getNameAttribute();
1245 if (!nameValue.isNull())
1246 updateName(nullAtom, nameValue);
1247
1248 if (hasTagName(labelTag)) {
1249 if (scope->shouldCacheLabelsByForAttribute())
1250 updateLabel(scope, nullAtom, fastGetAttribute(forAttr));
1251 }
1252
1253 return InsertionDone;
1254}
1255
1256void Element::removedFrom(ContainerNode* insertionPoint)
1257{
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001258 bool wasInDocument = insertionPoint->document();
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001259
1260 if (Element* before = pseudoElement(BEFORE))
1261 before->removedFrom(insertionPoint);
1262
1263 if (Element* after = pseudoElement(AFTER))
1264 after->removedFrom(insertionPoint);
1265
Ben Murdoche69819b2013-07-17 14:56:49 +01001266 if (Element* backdrop = pseudoElement(BACKDROP))
1267 backdrop->removedFrom(insertionPoint);
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001268 document()->removeFromTopLayer(this);
Ben Murdoche69819b2013-07-17 14:56:49 +01001269
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001270 if (containsFullScreenElement())
1271 setContainsFullScreenElementOnAncestorsCrossingFrameBoundaries(false);
1272
1273 if (document()->page())
1274 document()->page()->pointerLockController()->elementRemoved(this);
1275
1276 setSavedLayerScrollOffset(IntSize());
1277
1278 if (insertionPoint->isInTreeScope() && treeScope() == document()) {
1279 const AtomicString& idValue = getIdAttribute();
1280 if (!idValue.isNull())
1281 updateId(insertionPoint->treeScope(), idValue, nullAtom);
1282
1283 const AtomicString& nameValue = getNameAttribute();
1284 if (!nameValue.isNull())
1285 updateName(nameValue, nullAtom);
1286
1287 if (hasTagName(labelTag)) {
1288 TreeScope* treeScope = insertionPoint->treeScope();
1289 if (treeScope->shouldCacheLabelsByForAttribute())
1290 updateLabel(treeScope, fastGetAttribute(forAttr), nullAtom);
1291 }
1292 }
1293
1294 ContainerNode::removedFrom(insertionPoint);
Ben Murdoche69819b2013-07-17 14:56:49 +01001295 if (wasInDocument) {
1296 if (hasPendingResources())
1297 document()->accessSVGExtensions()->removeElementFromPendingResources(this);
1298
Ben Murdoch83750172013-07-24 10:36:59 +01001299 if (isUpgradedCustomElement())
Ben Murdochfff88842013-07-30 15:20:09 +01001300 CustomElement::didLeaveDocument(this, insertionPoint->document());
Ben Murdoche69819b2013-07-17 14:56:49 +01001301 }
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001302}
1303
Torne (Richard Coles)521d96e2013-06-19 11:58:24 +01001304void Element::createRendererIfNeeded(const AttachContext& context)
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001305{
Ben Murdoch83750172013-07-24 10:36:59 +01001306 NodeRenderingContext(this, context.resolvedStyle).createRendererForElementIfNeeded();
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001307}
1308
Torne (Richard Coles)521d96e2013-06-19 11:58:24 +01001309void Element::attach(const AttachContext& context)
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001310{
1311 PostAttachCallbackDisabler callbackDisabler(this);
1312 StyleResolverParentPusher parentPusher(this);
1313 WidgetHierarchyUpdatesSuspensionScope suspendWidgetHierarchyUpdates;
1314
Torne (Richard Coles)521d96e2013-06-19 11:58:24 +01001315 createRendererIfNeeded(context);
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001316
1317 if (parentElement() && parentElement()->isInCanvasSubtree())
1318 setIsInCanvasSubtree(true);
1319
1320 createPseudoElementIfNeeded(BEFORE);
1321
1322 // When a shadow root exists, it does the work of attaching the children.
1323 if (ElementShadow* shadow = this->shadow()) {
1324 parentPusher.push();
Ben Murdoch591b9582013-07-10 11:41:44 +01001325 shadow->attach(context);
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001326 } else if (firstChild())
1327 parentPusher.push();
1328
Torne (Richard Coles)521d96e2013-06-19 11:58:24 +01001329 ContainerNode::attach(context);
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001330
1331 createPseudoElementIfNeeded(AFTER);
Ben Murdoche69819b2013-07-17 14:56:49 +01001332 createPseudoElementIfNeeded(BACKDROP);
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001333
Ben Murdoch591b9582013-07-10 11:41:44 +01001334 if (hasRareData()) {
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001335 ElementRareData* data = elementRareData();
1336 if (data->needsFocusAppearanceUpdateSoonAfterAttach()) {
Ben Murdoch7757ec22013-07-23 11:17:36 +01001337 if (isFocusable() && document()->focusedElement() == this)
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001338 document()->updateFocusAppearanceSoon(false /* don't restore selection */);
1339 data->setNeedsFocusAppearanceUpdateSoonAfterAttach(false);
1340 }
1341 }
Ben Murdoch591b9582013-07-10 11:41:44 +01001342
1343 // FIXME: It doesn't appear safe to call didRecalculateStyleForElement when
1344 // not in a Document::recalcStyle. Since we're hopefully going to always
1345 // lazyAttach in the future that problem should go away.
1346 if (document()->inStyleRecalc())
1347 InspectorInstrumentation::didRecalculateStyleForElement(this);
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001348}
1349
1350void Element::unregisterNamedFlowContentNode()
1351{
1352 if (RuntimeEnabledFeatures::cssRegionsEnabled() && inNamedFlow() && document()->renderView())
1353 document()->renderView()->flowThreadController()->unregisterNamedFlowContentNode(this);
1354}
1355
Torne (Richard Coles)521d96e2013-06-19 11:58:24 +01001356void Element::detach(const AttachContext& context)
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001357{
1358 WidgetHierarchyUpdatesSuspensionScope suspendWidgetHierarchyUpdates;
1359 unregisterNamedFlowContentNode();
1360 cancelFocusAppearanceUpdate();
1361 if (hasRareData()) {
1362 ElementRareData* data = elementRareData();
1363 data->setPseudoElement(BEFORE, 0);
1364 data->setPseudoElement(AFTER, 0);
Ben Murdoche69819b2013-07-17 14:56:49 +01001365 data->setPseudoElement(BACKDROP, 0);
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001366 data->setIsInCanvasSubtree(false);
1367 data->resetComputedStyle();
1368 data->resetDynamicRestyleObservations();
Ben Murdoch591b9582013-07-10 11:41:44 +01001369 data->setIsInsideRegion(false);
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001370 }
Ben Murdoch591b9582013-07-10 11:41:44 +01001371 if (ElementShadow* shadow = this->shadow())
1372 shadow->detach(context);
Torne (Richard Coles)521d96e2013-06-19 11:58:24 +01001373 ContainerNode::detach(context);
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001374}
1375
1376bool Element::pseudoStyleCacheIsInvalid(const RenderStyle* currentStyle, RenderStyle* newStyle)
1377{
1378 ASSERT(currentStyle == renderStyle());
1379 ASSERT(renderer());
1380
1381 if (!currentStyle)
1382 return false;
1383
1384 const PseudoStyleCache* pseudoStyleCache = currentStyle->cachedPseudoStyles();
1385 if (!pseudoStyleCache)
1386 return false;
1387
1388 size_t cacheSize = pseudoStyleCache->size();
1389 for (size_t i = 0; i < cacheSize; ++i) {
1390 RefPtr<RenderStyle> newPseudoStyle;
1391 PseudoId pseudoId = pseudoStyleCache->at(i)->styleType();
1392 if (pseudoId == FIRST_LINE || pseudoId == FIRST_LINE_INHERITED)
1393 newPseudoStyle = renderer()->uncachedFirstLineStyle(newStyle);
1394 else
1395 newPseudoStyle = renderer()->getUncachedPseudoStyle(PseudoStyleRequest(pseudoId), newStyle, newStyle);
1396 if (!newPseudoStyle)
1397 return true;
1398 if (*newPseudoStyle != *pseudoStyleCache->at(i)) {
1399 if (pseudoId < FIRST_INTERNAL_PSEUDOID)
1400 newStyle->setHasPseudoStyle(pseudoId);
1401 newStyle->addCachedPseudoStyle(newPseudoStyle);
1402 if (pseudoId == FIRST_LINE || pseudoId == FIRST_LINE_INHERITED) {
1403 // FIXME: We should do an actual diff to determine whether a repaint vs. layout
1404 // is needed, but for now just assume a layout will be required. The diff code
1405 // in RenderObject::setStyle would need to be factored out so that it could be reused.
1406 renderer()->setNeedsLayoutAndPrefWidthsRecalc();
1407 }
1408 return true;
1409 }
1410 }
1411 return false;
1412}
1413
Torne (Richard Coles)521d96e2013-06-19 11:58:24 +01001414PassRefPtr<RenderStyle> Element::styleForRenderer()
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001415{
1416 if (hasCustomStyleCallbacks()) {
1417 if (RefPtr<RenderStyle> style = customStyleForRenderer())
1418 return style.release();
1419 }
1420
Torne (Richard Coles)521d96e2013-06-19 11:58:24 +01001421 return originalStyleForRenderer();
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001422}
1423
Torne (Richard Coles)521d96e2013-06-19 11:58:24 +01001424PassRefPtr<RenderStyle> Element::originalStyleForRenderer()
Torne (Richard Coles)5267f702013-06-11 10:57:24 +01001425{
Torne (Richard Coles)521d96e2013-06-19 11:58:24 +01001426 return document()->styleResolver()->styleForElement(this);
Torne (Richard Coles)5267f702013-06-11 10:57:24 +01001427}
1428
Ben Murdoche69819b2013-07-17 14:56:49 +01001429bool Element::recalcStyle(StyleChange change)
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001430{
Torne (Richard Coles)93ac45c2013-05-29 14:40:20 +01001431 ASSERT(document()->inStyleRecalc());
1432
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001433 if (hasCustomStyleCallbacks())
1434 willRecalcStyle(change);
1435
1436 // Ref currentStyle in case it would otherwise be deleted when setting the new style in the renderer.
Ben Murdoch83750172013-07-24 10:36:59 +01001437 RefPtr<RenderStyle> currentStyle = renderStyle();
1438 bool hasParentStyle = static_cast<bool>(parentRenderStyle());
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001439 bool hasDirectAdjacentRules = childrenAffectedByDirectAdjacentRules();
1440 bool hasIndirectAdjacentRules = childrenAffectedByForwardPositionalRules();
1441
Ben Murdoch83750172013-07-24 10:36:59 +01001442 if (change > NoChange || needsStyleRecalc()) {
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001443 if (hasRareData())
1444 elementRareData()->resetComputedStyle();
1445 }
1446 if (hasParentStyle && (change >= Inherit || needsStyleRecalc())) {
1447 StyleChange localChange = Detach;
1448 RefPtr<RenderStyle> newStyle;
1449 if (currentStyle) {
1450 // FIXME: This still recalcs style twice when changing display types, but saves
1451 // us from recalcing twice when going from none -> anything else which is more
1452 // common, especially during lazy attach.
Torne (Richard Coles)521d96e2013-06-19 11:58:24 +01001453 newStyle = styleForRenderer();
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001454 localChange = Node::diff(currentStyle.get(), newStyle.get(), document());
Torne (Richard Coles)521d96e2013-06-19 11:58:24 +01001455 } else if (attached() && isActiveInsertionPoint(this)) {
1456 // Active InsertionPoints will never have renderers so there's no reason to
1457 // reattach them repeatedly once they're already attached.
1458 localChange = change;
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001459 }
1460 if (localChange == Detach) {
Torne (Richard Coles)521d96e2013-06-19 11:58:24 +01001461 AttachContext reattachContext;
1462 reattachContext.resolvedStyle = newStyle.get();
1463 reattach(reattachContext);
1464
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001465 // attach recalculates the style for all children. No need to do it twice.
1466 clearNeedsStyleRecalc();
1467 clearChildNeedsStyleRecalc();
1468
1469 if (hasCustomStyleCallbacks())
1470 didRecalcStyle(change);
Ben Murdoche69819b2013-07-17 14:56:49 +01001471 return true;
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001472 }
1473
Ben Murdoch591b9582013-07-10 11:41:44 +01001474 InspectorInstrumentation::didRecalculateStyleForElement(this);
1475
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001476 if (RenderObject* renderer = this->renderer()) {
Ben Murdoche69819b2013-07-17 14:56:49 +01001477 if (localChange != NoChange || pseudoStyleCacheIsInvalid(currentStyle.get(), newStyle.get()) || (change == Force && renderer->requiresForcedStyleRecalcPropagation()) || shouldNotifyRendererWithIdenticalStyles())
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001478 renderer->setAnimatableStyle(newStyle.get());
1479 else if (needsStyleRecalc()) {
1480 // Although no change occurred, we use the new style so that the cousin style sharing code won't get
1481 // fooled into believing this style is the same.
1482 renderer->setStyleInternal(newStyle.get());
1483 }
1484 }
1485
1486 // 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
1487 // 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).
1488 if (document()->styleSheetCollection()->usesRemUnits() && document()->documentElement() == this && localChange != NoChange && currentStyle && newStyle && currentStyle->fontSize() != newStyle->fontSize()) {
1489 // Cached RenderStyles may depend on the re units.
1490 document()->styleResolver()->invalidateMatchedPropertiesCache();
1491 change = Force;
1492 }
1493
Ben Murdoche69819b2013-07-17 14:56:49 +01001494 if (styleChangeType() == SubtreeStyleChange)
Torne (Richard Coles)e5249552013-05-15 11:35:13 +01001495 change = Force;
1496 else if (change != Force)
1497 change = localChange;
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001498 }
1499 StyleResolverParentPusher parentPusher(this);
1500
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001501 if (ElementShadow* shadow = this->shadow()) {
Ben Murdoch83750172013-07-24 10:36:59 +01001502 for (ShadowRoot* root = shadow->youngestShadowRoot(); root; root = root->olderShadowRoot()) {
1503 if (shouldRecalcStyle(change, root)) {
1504 parentPusher.push();
1505 root->recalcStyle(change);
1506 }
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001507 }
1508 }
1509
1510 if (shouldRecalcStyle(change, this))
1511 updatePseudoElement(BEFORE, change);
1512
1513 // FIXME: This check is good enough for :hover + foo, but it is not good enough for :hover + foo + bar.
1514 // For now we will just worry about the common case, since it's a lot trickier to get the second case right
1515 // without doing way too much re-resolution.
1516 bool forceCheckOfNextElementSibling = false;
1517 bool forceCheckOfAnyElementSibling = false;
Ben Murdoche69819b2013-07-17 14:56:49 +01001518 bool forceReattachOfAnyWhitespaceSibling = false;
1519 for (Node* child = firstChild(); child; child = child->nextSibling()) {
1520 bool didReattach = false;
1521
1522 if (child->renderer())
1523 forceReattachOfAnyWhitespaceSibling = false;
1524
1525 if (child->isTextNode()) {
1526 if (forceReattachOfAnyWhitespaceSibling && toText(child)->containsOnlyWhitespace())
1527 child->reattach();
1528 else
1529 didReattach = toText(child)->recalcTextStyle(change);
1530 } else if (child->isElementNode()) {
1531 Element* element = toElement(child);
1532
1533 if (forceCheckOfNextElementSibling || forceCheckOfAnyElementSibling)
1534 element->setNeedsStyleRecalc();
1535
1536 bool childRulesChanged = element->needsStyleRecalc() && element->styleChangeType() == SubtreeStyleChange;
1537 forceCheckOfNextElementSibling = childRulesChanged && hasDirectAdjacentRules;
1538 forceCheckOfAnyElementSibling = forceCheckOfAnyElementSibling || (childRulesChanged && hasIndirectAdjacentRules);
1539
1540 if (shouldRecalcStyle(change, element)) {
1541 parentPusher.push();
1542 didReattach = element->recalcStyle(change);
1543 }
Ben Murdoch591b9582013-07-10 11:41:44 +01001544 }
Ben Murdoche69819b2013-07-17 14:56:49 +01001545
1546 forceReattachOfAnyWhitespaceSibling = didReattach || forceReattachOfAnyWhitespaceSibling;
Torne (Richard Coles)5267f702013-06-11 10:57:24 +01001547 }
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001548
1549 if (shouldRecalcStyle(change, this))
1550 updatePseudoElement(AFTER, change);
1551
1552 clearNeedsStyleRecalc();
1553 clearChildNeedsStyleRecalc();
Ben Murdoch591b9582013-07-10 11:41:44 +01001554
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001555 if (hasCustomStyleCallbacks())
1556 didRecalcStyle(change);
Ben Murdoche69819b2013-07-17 14:56:49 +01001557 return false;
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001558}
1559
1560ElementShadow* Element::shadow() const
1561{
1562 return hasRareData() ? elementRareData()->shadow() : 0;
1563}
1564
1565ElementShadow* Element::ensureShadow()
1566{
1567 return ensureElementRareData()->ensureShadow();
1568}
1569
1570void Element::didAffectSelector(AffectedSelectorMask mask)
1571{
1572 setNeedsStyleRecalc();
1573 if (ElementShadow* elementShadow = shadowOfParentForDistribution(this))
1574 elementShadow->didAffectSelector(mask);
1575}
1576
1577PassRefPtr<ShadowRoot> Element::createShadowRoot(ExceptionCode& ec)
1578{
1579 if (alwaysCreateUserAgentShadowRoot())
1580 ensureUserAgentShadowRoot();
1581
1582 if (RuntimeEnabledFeatures::authorShadowDOMForAnyElementEnabled())
1583 return ensureShadow()->addShadowRoot(this, ShadowRoot::AuthorShadowRoot);
1584
1585 // Since some elements recreates shadow root dynamically, multiple shadow
1586 // subtrees won't work well in that element. Until they are fixed, we disable
1587 // adding author shadow root for them.
1588 if (!areAuthorShadowsAllowed()) {
Ben Murdoche69819b2013-07-17 14:56:49 +01001589 ec = HierarchyRequestError;
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001590 return 0;
1591 }
1592 return ensureShadow()->addShadowRoot(this, ShadowRoot::AuthorShadowRoot);
1593}
1594
1595ShadowRoot* Element::shadowRoot() const
1596{
1597 ElementShadow* elementShadow = shadow();
1598 if (!elementShadow)
1599 return 0;
1600 ShadowRoot* shadowRoot = elementShadow->youngestShadowRoot();
1601 if (shadowRoot->type() == ShadowRoot::AuthorShadowRoot)
1602 return shadowRoot;
1603 return 0;
1604}
1605
1606ShadowRoot* Element::userAgentShadowRoot() const
1607{
1608 if (ElementShadow* elementShadow = shadow()) {
1609 if (ShadowRoot* shadowRoot = elementShadow->oldestShadowRoot()) {
1610 ASSERT(shadowRoot->type() == ShadowRoot::UserAgentShadowRoot);
1611 return shadowRoot;
1612 }
1613 }
1614
1615 return 0;
1616}
1617
1618ShadowRoot* Element::ensureUserAgentShadowRoot()
1619{
1620 if (ShadowRoot* shadowRoot = userAgentShadowRoot())
1621 return shadowRoot;
1622 ShadowRoot* shadowRoot = ensureShadow()->addShadowRoot(this, ShadowRoot::UserAgentShadowRoot);
1623 didAddUserAgentShadowRoot(shadowRoot);
1624 return shadowRoot;
1625}
1626
1627const AtomicString& Element::shadowPseudoId() const
1628{
1629 return pseudo();
1630}
1631
1632bool Element::childTypeAllowed(NodeType type) const
1633{
1634 switch (type) {
1635 case ELEMENT_NODE:
1636 case TEXT_NODE:
1637 case COMMENT_NODE:
1638 case PROCESSING_INSTRUCTION_NODE:
1639 case CDATA_SECTION_NODE:
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001640 return true;
1641 default:
1642 break;
1643 }
1644 return false;
1645}
1646
Ben Murdoch83750172013-07-24 10:36:59 +01001647static void inline checkForEmptyStyleChange(Element* element, RenderStyle* style)
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001648{
1649 if (!style && !element->styleAffectedByEmpty())
1650 return;
1651
1652 if (!style || (element->styleAffectedByEmpty() && (!style->emptyState() || element->hasChildNodes())))
1653 element->setNeedsStyleRecalc();
1654}
1655
1656static void checkForSiblingStyleChanges(Element* e, RenderStyle* style, bool finishedParsingCallback,
1657 Node* beforeChange, Node* afterChange, int childCountDelta)
1658{
Ben Murdoch83750172013-07-24 10:36:59 +01001659 if (!e->attached() || e->document()->hasPendingForcedStyleRecalc() || e->styleChangeType() == SubtreeStyleChange)
1660 return;
1661
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001662 // :empty selector.
1663 checkForEmptyStyleChange(e, style);
Ben Murdoch591b9582013-07-10 11:41:44 +01001664
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001665 if (!style || (e->needsStyleRecalc() && e->childrenAffectedByPositionalRules()))
1666 return;
1667
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001668 // Forward positional selectors include the ~ selector, nth-child, nth-of-type, first-of-type and only-of-type.
1669 // Backward positional selectors include nth-last-child, nth-last-of-type, last-of-type and only-of-type.
1670 // We have to invalidate everything following the insertion point in the forward case, and everything before the insertion point in the
1671 // backward case.
1672 // |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.
1673 // 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
Ben Murdoch83750172013-07-24 10:36:59 +01001674 // here. recalcStyle will then force a walk of the children when it sees that this has happened.
1675 if ((e->childrenAffectedByForwardPositionalRules() && afterChange) || (e->childrenAffectedByBackwardPositionalRules() && beforeChange)) {
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001676 e->setNeedsStyleRecalc();
Ben Murdoch83750172013-07-24 10:36:59 +01001677 return;
1678 }
1679
1680 // :first-child. In the parser callback case, we don't have to check anything, since we were right the first time.
1681 // In the DOM case, we only need to do something if |afterChange| is not 0.
1682 // |afterChange| is 0 in the parser case, so it works out that we'll skip this block.
1683 if (e->childrenAffectedByFirstChildRules() && afterChange) {
1684 // Find our new first child.
1685 Node* newFirstChild = e->firstElementChild();
1686 RenderStyle* newFirstChildStyle = newFirstChild ? newFirstChild->renderStyle() : 0;
1687
1688 // Find the first element node following |afterChange|
1689 Node* firstElementAfterInsertion = afterChange->isElementNode() ? afterChange : afterChange->nextElementSibling();
1690 RenderStyle* firstElementAfterInsertionStyle = firstElementAfterInsertion ? firstElementAfterInsertion->renderStyle() : 0;
1691
1692 // This is the insert/append case.
1693 if (newFirstChild != firstElementAfterInsertion && firstElementAfterInsertionStyle && firstElementAfterInsertionStyle->firstChildState())
1694 firstElementAfterInsertion->setNeedsStyleRecalc();
1695
1696 // We also have to handle node removal.
1697 if (childCountDelta < 0 && newFirstChild == firstElementAfterInsertion && newFirstChild && (!newFirstChildStyle || !newFirstChildStyle->firstChildState()))
1698 newFirstChild->setNeedsStyleRecalc();
1699 }
1700
1701 // :last-child. In the parser callback case, we don't have to check anything, since we were right the first time.
1702 // In the DOM case, we only need to do something if |afterChange| is not 0.
1703 if (e->childrenAffectedByLastChildRules() && beforeChange) {
1704 // Find our new last child.
1705 Node* newLastChild = e->lastElementChild();
1706 RenderStyle* newLastChildStyle = newLastChild ? newLastChild->renderStyle() : 0;
1707
1708 // Find the last element node going backwards from |beforeChange|
1709 Node* lastElementBeforeInsertion = beforeChange->isElementNode() ? beforeChange : beforeChange->previousElementSibling();
1710 RenderStyle* lastElementBeforeInsertionStyle = lastElementBeforeInsertion ? lastElementBeforeInsertion->renderStyle() : 0;
1711
1712 if (newLastChild != lastElementBeforeInsertion && lastElementBeforeInsertionStyle && lastElementBeforeInsertionStyle->lastChildState())
1713 lastElementBeforeInsertion->setNeedsStyleRecalc();
1714
1715 // 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
1716 // to match now.
1717 if ((childCountDelta < 0 || finishedParsingCallback) && newLastChild == lastElementBeforeInsertion && newLastChild && (!newLastChildStyle || !newLastChildStyle->lastChildState()))
1718 newLastChild->setNeedsStyleRecalc();
1719 }
1720
1721 // The + selector. We need to invalidate the first element following the insertion point. It is the only possible element
1722 // that could be affected by this DOM change.
1723 if (e->childrenAffectedByDirectAdjacentRules() && afterChange) {
1724 if (Node* firstElementAfterInsertion = afterChange->nextElementSibling())
1725 firstElementAfterInsertion->setNeedsStyleRecalc();
1726 }
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001727}
1728
1729void Element::childrenChanged(bool changedByParser, Node* beforeChange, Node* afterChange, int childCountDelta)
1730{
1731 ContainerNode::childrenChanged(changedByParser, beforeChange, afterChange, childCountDelta);
1732 if (changedByParser)
1733 checkForEmptyStyleChange(this, renderStyle());
1734 else
1735 checkForSiblingStyleChanges(this, renderStyle(), false, beforeChange, afterChange, childCountDelta);
1736
Ben Murdoch83750172013-07-24 10:36:59 +01001737 if (ElementShadow* shadow = this->shadow())
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001738 shadow->invalidateDistribution();
1739}
1740
1741void Element::removeAllEventListeners()
1742{
1743 ContainerNode::removeAllEventListeners();
1744 if (ElementShadow* shadow = this->shadow())
1745 shadow->removeAllEventListeners();
1746}
1747
1748void Element::beginParsingChildren()
1749{
1750 clearIsParsingChildrenFinished();
1751 StyleResolver* styleResolver = document()->styleResolverIfExists();
1752 if (styleResolver && attached())
1753 styleResolver->pushParentElement(this);
1754}
1755
1756void Element::finishParsingChildren()
1757{
1758 ContainerNode::finishParsingChildren();
1759 setIsParsingChildrenFinished();
1760 checkForSiblingStyleChanges(this, renderStyle(), true, lastChild(), 0, 0);
1761 if (StyleResolver* styleResolver = document()->styleResolverIfExists())
1762 styleResolver->popParentElement(this);
1763}
1764
1765#ifndef NDEBUG
1766void Element::formatForDebugger(char* buffer, unsigned length) const
1767{
1768 StringBuilder result;
1769 String s;
1770
1771 result.append(nodeName());
1772
1773 s = getIdAttribute();
1774 if (s.length() > 0) {
1775 if (result.length() > 0)
1776 result.appendLiteral("; ");
1777 result.appendLiteral("id=");
1778 result.append(s);
1779 }
1780
1781 s = getAttribute(classAttr);
1782 if (s.length() > 0) {
1783 if (result.length() > 0)
1784 result.appendLiteral("; ");
1785 result.appendLiteral("class=");
1786 result.append(s);
1787 }
1788
1789 strncpy(buffer, result.toString().utf8().data(), length - 1);
1790}
1791#endif
1792
1793const Vector<RefPtr<Attr> >& Element::attrNodeList()
1794{
1795 ASSERT(hasSyntheticAttrChildNodes());
1796 return *attrNodeListForElement(this);
1797}
1798
1799PassRefPtr<Attr> Element::setAttributeNode(Attr* attrNode, ExceptionCode& ec)
1800{
1801 if (!attrNode) {
Ben Murdoche69819b2013-07-17 14:56:49 +01001802 ec = TypeMismatchError;
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001803 return 0;
1804 }
1805
1806 RefPtr<Attr> oldAttrNode = attrIfExists(attrNode->qualifiedName());
1807 if (oldAttrNode.get() == attrNode)
1808 return attrNode; // This Attr is already attached to the element.
1809
Ben Murdoche69819b2013-07-17 14:56:49 +01001810 // 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 +01001811 // The DOM user must explicitly clone Attr nodes to re-use them in other elements.
1812 if (attrNode->ownerElement()) {
Ben Murdoche69819b2013-07-17 14:56:49 +01001813 ec = InUseAttributeError;
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001814 return 0;
1815 }
1816
1817 synchronizeAllAttributes();
1818 UniqueElementData* elementData = ensureUniqueElementData();
1819
1820 size_t index = elementData->getAttributeItemIndex(attrNode->qualifiedName());
1821 if (index != notFound) {
1822 if (oldAttrNode)
1823 detachAttrNodeFromElementWithValue(oldAttrNode.get(), elementData->attributeItem(index)->value());
1824 else
1825 oldAttrNode = Attr::create(document(), attrNode->qualifiedName(), elementData->attributeItem(index)->value());
1826 }
1827
1828 setAttributeInternal(index, attrNode->qualifiedName(), attrNode->value(), NotInSynchronizationOfLazyAttribute);
1829
1830 attrNode->attachToElement(this);
Ben Murdoch591b9582013-07-10 11:41:44 +01001831 treeScope()->adoptIfNeeded(attrNode);
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001832 ensureAttrNodeListForElement(this)->append(attrNode);
1833
1834 return oldAttrNode.release();
1835}
1836
1837PassRefPtr<Attr> Element::setAttributeNodeNS(Attr* attr, ExceptionCode& ec)
1838{
1839 return setAttributeNode(attr, ec);
1840}
1841
1842PassRefPtr<Attr> Element::removeAttributeNode(Attr* attr, ExceptionCode& ec)
1843{
1844 if (!attr) {
Ben Murdoche69819b2013-07-17 14:56:49 +01001845 ec = TypeMismatchError;
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001846 return 0;
1847 }
1848 if (attr->ownerElement() != this) {
Ben Murdoche69819b2013-07-17 14:56:49 +01001849 ec = NotFoundError;
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001850 return 0;
1851 }
1852
1853 ASSERT(document() == attr->document());
1854
1855 synchronizeAttribute(attr->qualifiedName());
1856
Torne (Richard Coles)e5249552013-05-15 11:35:13 +01001857 size_t index = elementData()->getAttrIndex(attr);
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001858 if (index == notFound) {
Ben Murdoche69819b2013-07-17 14:56:49 +01001859 ec = NotFoundError;
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001860 return 0;
1861 }
1862
Torne (Richard Coles)e5249552013-05-15 11:35:13 +01001863 RefPtr<Attr> guard(attr);
1864 detachAttrNodeAtIndex(attr, index);
1865 return guard.release();
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001866}
1867
1868bool Element::parseAttributeName(QualifiedName& out, const AtomicString& namespaceURI, const AtomicString& qualifiedName, ExceptionCode& ec)
1869{
1870 String prefix, localName;
1871 if (!Document::parseQualifiedName(qualifiedName, prefix, localName, ec))
1872 return false;
1873 ASSERT(!ec);
1874
1875 QualifiedName qName(prefix, localName, namespaceURI);
1876
1877 if (!Document::hasValidNamespaceForAttributes(qName)) {
Ben Murdoche69819b2013-07-17 14:56:49 +01001878 ec = NamespaceError;
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001879 return false;
1880 }
1881
1882 out = qName;
1883 return true;
1884}
1885
1886void Element::setAttributeNS(const AtomicString& namespaceURI, const AtomicString& qualifiedName, const AtomicString& value, ExceptionCode& ec)
1887{
1888 QualifiedName parsedName = anyName;
1889 if (!parseAttributeName(parsedName, namespaceURI, qualifiedName, ec))
1890 return;
1891 setAttribute(parsedName, value);
1892}
1893
1894void Element::removeAttributeInternal(size_t index, SynchronizationOfLazyAttribute inSynchronizationOfLazyAttribute)
1895{
1896 ASSERT_WITH_SECURITY_IMPLICATION(index < attributeCount());
1897
1898 UniqueElementData* elementData = ensureUniqueElementData();
1899
1900 QualifiedName name = elementData->attributeItem(index)->name();
1901 AtomicString valueBeingRemoved = elementData->attributeItem(index)->value();
1902
1903 if (!inSynchronizationOfLazyAttribute) {
1904 if (!valueBeingRemoved.isNull())
1905 willModifyAttribute(name, valueBeingRemoved, nullAtom);
1906 }
1907
1908 if (RefPtr<Attr> attrNode = attrIfExists(name))
1909 detachAttrNodeFromElementWithValue(attrNode.get(), elementData->attributeItem(index)->value());
1910
1911 elementData->removeAttribute(index);
1912
1913 if (!inSynchronizationOfLazyAttribute)
1914 didRemoveAttribute(name);
1915}
1916
1917void Element::addAttributeInternal(const QualifiedName& name, const AtomicString& value, SynchronizationOfLazyAttribute inSynchronizationOfLazyAttribute)
1918{
1919 if (!inSynchronizationOfLazyAttribute)
1920 willModifyAttribute(name, nullAtom, value);
1921 ensureUniqueElementData()->addAttribute(name, value);
1922 if (!inSynchronizationOfLazyAttribute)
1923 didAddAttribute(name, value);
1924}
1925
1926void Element::removeAttribute(const AtomicString& name)
1927{
1928 if (!elementData())
1929 return;
1930
1931 AtomicString localName = shouldIgnoreAttributeCase(this) ? name.lower() : name;
1932 size_t index = elementData()->getAttributeItemIndex(localName, false);
1933 if (index == notFound) {
1934 if (UNLIKELY(localName == styleAttr) && elementData()->m_styleAttributeIsDirty && isStyledElement())
Ben Murdoch591b9582013-07-10 11:41:44 +01001935 removeAllInlineStyleProperties();
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001936 return;
1937 }
1938
1939 removeAttributeInternal(index, NotInSynchronizationOfLazyAttribute);
1940}
1941
1942void Element::removeAttributeNS(const AtomicString& namespaceURI, const AtomicString& localName)
1943{
1944 removeAttribute(QualifiedName(nullAtom, localName, namespaceURI));
1945}
1946
1947PassRefPtr<Attr> Element::getAttributeNode(const AtomicString& localName)
1948{
1949 if (!elementData())
1950 return 0;
1951 synchronizeAttribute(localName);
1952 const Attribute* attribute = elementData()->getAttributeItem(localName, shouldIgnoreAttributeCase(this));
1953 if (!attribute)
1954 return 0;
1955 return ensureAttr(attribute->name());
1956}
1957
1958PassRefPtr<Attr> Element::getAttributeNodeNS(const AtomicString& namespaceURI, const AtomicString& localName)
1959{
1960 if (!elementData())
1961 return 0;
1962 QualifiedName qName(nullAtom, localName, namespaceURI);
1963 synchronizeAttribute(qName);
1964 const Attribute* attribute = elementData()->getAttributeItem(qName);
1965 if (!attribute)
1966 return 0;
1967 return ensureAttr(attribute->name());
1968}
1969
1970bool Element::hasAttribute(const AtomicString& localName) const
1971{
1972 if (!elementData())
1973 return false;
1974 synchronizeAttribute(localName);
1975 return elementData()->getAttributeItem(shouldIgnoreAttributeCase(this) ? localName.lower() : localName, false);
1976}
1977
1978bool Element::hasAttributeNS(const AtomicString& namespaceURI, const AtomicString& localName) const
1979{
1980 if (!elementData())
1981 return false;
1982 QualifiedName qName(nullAtom, localName, namespaceURI);
1983 synchronizeAttribute(qName);
1984 return elementData()->getAttributeItem(qName);
1985}
1986
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001987void Element::focus(bool restorePreviousSelection, FocusDirection direction)
1988{
1989 if (!inDocument())
1990 return;
1991
1992 Document* doc = document();
Ben Murdoch7757ec22013-07-23 11:17:36 +01001993 if (doc->focusedElement() == this)
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001994 return;
1995
1996 // If the stylesheets have already been loaded we can reliably check isFocusable.
1997 // If not, we continue and set the focused node on the focus controller below so
Ben Murdoch591b9582013-07-10 11:41:44 +01001998 // that it can be updated soon after attach.
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001999 if (doc->haveStylesheetsLoaded()) {
2000 doc->updateLayoutIgnorePendingStylesheets();
2001 if (!isFocusable())
2002 return;
2003 }
2004
2005 if (!supportsFocus())
2006 return;
2007
2008 RefPtr<Node> protect;
2009 if (Page* page = doc->page()) {
2010 // Focus and change event handlers can cause us to lose our last ref.
2011 // If a focus event handler changes the focus to a different node it
2012 // does not make sense to continue and update appearence.
2013 protect = this;
Ben Murdoche69819b2013-07-17 14:56:49 +01002014 if (!page->focusController()->setFocusedElement(this, doc->frame(), direction))
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002015 return;
2016 }
2017
2018 // Setting the focused node above might have invalidated the layout due to scripts.
2019 doc->updateLayoutIgnorePendingStylesheets();
2020
2021 if (!isFocusable()) {
2022 ensureElementRareData()->setNeedsFocusAppearanceUpdateSoonAfterAttach(true);
2023 return;
2024 }
Ben Murdoch591b9582013-07-10 11:41:44 +01002025
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002026 cancelFocusAppearanceUpdate();
2027 updateFocusAppearance(restorePreviousSelection);
2028}
2029
2030void Element::updateFocusAppearance(bool /*restorePreviousSelection*/)
2031{
2032 if (isRootEditableElement()) {
2033 Frame* frame = document()->frame();
2034 if (!frame)
2035 return;
Ben Murdoch591b9582013-07-10 11:41:44 +01002036
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002037 // When focusing an editable element in an iframe, don't reset the selection if it already contains a selection.
2038 if (this == frame->selection()->rootEditableElement())
2039 return;
2040
2041 // FIXME: We should restore the previous selection if there is one.
2042 VisibleSelection newSelection = VisibleSelection(firstPositionInOrBeforeNode(this), DOWNSTREAM);
Ben Murdoch591b9582013-07-10 11:41:44 +01002043
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002044 if (frame->selection()->shouldChangeSelection(newSelection)) {
2045 frame->selection()->setSelection(newSelection);
2046 frame->selection()->revealSelection();
2047 }
2048 } else if (renderer() && !renderer()->isWidget())
2049 renderer()->scrollRectToVisible(boundingBox());
2050}
2051
2052void Element::blur()
2053{
2054 cancelFocusAppearanceUpdate();
Ben Murdoche69819b2013-07-17 14:56:49 +01002055 if (treeScope()->adjustedFocusedElement() == this) {
2056 Document* doc = document();
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002057 if (doc->frame())
Ben Murdoche69819b2013-07-17 14:56:49 +01002058 doc->frame()->page()->focusController()->setFocusedElement(0, doc->frame());
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002059 else
Ben Murdoche69819b2013-07-17 14:56:49 +01002060 doc->setFocusedElement(0);
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002061 }
2062}
2063
Ben Murdoch02772c62013-07-26 10:21:05 +01002064void Element::dispatchFocusEvent(Element* oldFocusedElement, FocusDirection)
2065{
2066 RefPtr<FocusEvent> event = FocusEvent::create(eventNames().focusEvent, false, false, document()->defaultView(), 0, oldFocusedElement);
2067 EventDispatcher::dispatchEvent(this, FocusEventDispatchMediator::create(event.release()));
2068}
2069
2070void Element::dispatchBlurEvent(Element* newFocusedElement)
2071{
2072 RefPtr<FocusEvent> event = FocusEvent::create(eventNames().blurEvent, false, false, document()->defaultView(), 0, newFocusedElement);
2073 EventDispatcher::dispatchEvent(this, BlurEventDispatchMediator::create(event.release()));
2074}
2075
2076void Element::dispatchFocusInEvent(const AtomicString& eventType, Element* oldFocusedElement)
2077{
2078 ASSERT(!NoEventDispatchAssertion::isEventDispatchForbidden());
2079 ASSERT(eventType == eventNames().focusinEvent || eventType == eventNames().DOMFocusInEvent);
2080 dispatchScopedEventDispatchMediator(FocusInEventDispatchMediator::create(FocusEvent::create(eventType, true, false, document()->defaultView(), 0, oldFocusedElement)));
2081}
2082
2083void Element::dispatchFocusOutEvent(const AtomicString& eventType, Element* newFocusedElement)
2084{
2085 ASSERT(!NoEventDispatchAssertion::isEventDispatchForbidden());
2086 ASSERT(eventType == eventNames().focusoutEvent || eventType == eventNames().DOMFocusOutEvent);
2087 dispatchScopedEventDispatchMediator(FocusOutEventDispatchMediator::create(FocusEvent::create(eventType, true, false, document()->defaultView(), 0, newFocusedElement)));
2088}
2089
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002090String Element::innerText()
2091{
2092 // We need to update layout, since plainText uses line boxes in the render tree.
2093 document()->updateLayoutIgnorePendingStylesheets();
2094
2095 if (!renderer())
2096 return textContent(true);
2097
2098 return plainText(rangeOfContents(const_cast<Element*>(this)).get());
2099}
2100
2101String Element::outerText()
2102{
2103 // Getting outerText is the same as getting innerText, only
2104 // setting is different. You would think this should get the plain
2105 // text for the outer range, but this is wrong, <br> for instance
2106 // would return different values for inner and outer text by such
2107 // a rule, but it doesn't in WinIE, and we want to match that.
2108 return innerText();
2109}
2110
Ben Murdoch591b9582013-07-10 11:41:44 +01002111String Element::textFromChildren()
2112{
2113 Text* firstTextNode = 0;
2114 bool foundMultipleTextNodes = false;
2115 unsigned totalLength = 0;
2116
2117 for (Node* child = firstChild(); child; child = child->nextSibling()) {
2118 if (!child->isTextNode())
2119 continue;
2120 Text* text = toText(child);
2121 if (!firstTextNode)
2122 firstTextNode = text;
2123 else
2124 foundMultipleTextNodes = true;
2125 unsigned length = text->data().length();
2126 if (length > std::numeric_limits<unsigned>::max() - totalLength)
2127 return emptyString();
2128 totalLength += length;
2129 }
2130
2131 if (!firstTextNode)
2132 return emptyString();
2133
2134 if (firstTextNode && !foundMultipleTextNodes) {
2135 firstTextNode->atomize();
2136 return firstTextNode->data();
2137 }
2138
2139 StringBuilder content;
2140 content.reserveCapacity(totalLength);
2141 for (Node* child = firstTextNode; child; child = child->nextSibling()) {
2142 if (!child->isTextNode())
2143 continue;
2144 content.append(toText(child)->data());
2145 }
2146
2147 ASSERT(content.length() == totalLength);
2148 return content.toString();
2149}
2150
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002151const AtomicString& Element::pseudo() const
2152{
2153 return getAttribute(pseudoAttr);
2154}
2155
2156void Element::setPseudo(const AtomicString& value)
2157{
2158 setAttribute(pseudoAttr, value);
2159}
2160
2161LayoutSize Element::minimumSizeForResizing() const
2162{
2163 return hasRareData() ? elementRareData()->minimumSizeForResizing() : defaultMinimumSizeForResizing();
2164}
2165
2166void Element::setMinimumSizeForResizing(const LayoutSize& size)
2167{
2168 if (!hasRareData() && size == defaultMinimumSizeForResizing())
2169 return;
2170 ensureElementRareData()->setMinimumSizeForResizing(size);
2171}
2172
2173RenderStyle* Element::computedStyle(PseudoId pseudoElementSpecifier)
2174{
2175 if (PseudoElement* element = pseudoElement(pseudoElementSpecifier))
2176 return element->computedStyle();
2177
2178 // FIXME: Find and use the renderer from the pseudo element instead of the actual element so that the 'length'
2179 // properties, which are only known by the renderer because it did the layout, will be correct and so that the
2180 // values returned for the ":selection" pseudo-element will be correct.
2181 if (RenderStyle* usedStyle = renderStyle()) {
2182 if (pseudoElementSpecifier) {
2183 RenderStyle* cachedPseudoStyle = usedStyle->getCachedPseudoStyle(pseudoElementSpecifier);
2184 return cachedPseudoStyle ? cachedPseudoStyle : usedStyle;
2185 } else
2186 return usedStyle;
2187 }
2188
2189 if (!attached())
2190 // FIXME: Try to do better than this. Ensure that styleForElement() works for elements that are not in the
2191 // document tree and figure out when to destroy the computed style for such elements.
2192 return 0;
2193
2194 ElementRareData* data = ensureElementRareData();
2195 if (!data->computedStyle())
2196 data->setComputedStyle(document()->styleForElementIgnoringPendingStylesheets(this));
2197 return pseudoElementSpecifier ? data->computedStyle()->getCachedPseudoStyle(pseudoElementSpecifier) : data->computedStyle();
2198}
2199
2200void Element::setStyleAffectedByEmpty()
2201{
2202 ensureElementRareData()->setStyleAffectedByEmpty(true);
2203}
2204
2205void Element::setChildrenAffectedByHover(bool value)
2206{
2207 if (value || hasRareData())
2208 ensureElementRareData()->setChildrenAffectedByHover(value);
2209}
2210
2211void Element::setChildrenAffectedByActive(bool value)
2212{
2213 if (value || hasRareData())
2214 ensureElementRareData()->setChildrenAffectedByActive(value);
2215}
2216
2217void Element::setChildrenAffectedByDrag(bool value)
2218{
2219 if (value || hasRareData())
2220 ensureElementRareData()->setChildrenAffectedByDrag(value);
2221}
2222
2223void Element::setChildrenAffectedByFirstChildRules()
2224{
2225 ensureElementRareData()->setChildrenAffectedByFirstChildRules(true);
2226}
2227
2228void Element::setChildrenAffectedByLastChildRules()
2229{
2230 ensureElementRareData()->setChildrenAffectedByLastChildRules(true);
2231}
2232
2233void Element::setChildrenAffectedByDirectAdjacentRules()
2234{
2235 ensureElementRareData()->setChildrenAffectedByDirectAdjacentRules(true);
2236}
2237
2238void Element::setChildrenAffectedByForwardPositionalRules()
2239{
2240 ensureElementRareData()->setChildrenAffectedByForwardPositionalRules(true);
2241}
2242
2243void Element::setChildrenAffectedByBackwardPositionalRules()
2244{
2245 ensureElementRareData()->setChildrenAffectedByBackwardPositionalRules(true);
2246}
2247
2248void Element::setChildIndex(unsigned index)
2249{
2250 ElementRareData* rareData = ensureElementRareData();
2251 if (RenderStyle* style = renderStyle())
2252 style->setUnique();
2253 rareData->setChildIndex(index);
2254}
2255
2256bool Element::hasFlagsSetDuringStylingOfChildren() const
2257{
2258 if (!hasRareData())
2259 return false;
2260 return rareDataChildrenAffectedByHover()
2261 || rareDataChildrenAffectedByActive()
2262 || rareDataChildrenAffectedByDrag()
2263 || rareDataChildrenAffectedByFirstChildRules()
2264 || rareDataChildrenAffectedByLastChildRules()
2265 || rareDataChildrenAffectedByDirectAdjacentRules()
2266 || rareDataChildrenAffectedByForwardPositionalRules()
2267 || rareDataChildrenAffectedByBackwardPositionalRules();
2268}
2269
2270bool Element::rareDataStyleAffectedByEmpty() const
2271{
2272 ASSERT(hasRareData());
2273 return elementRareData()->styleAffectedByEmpty();
2274}
2275
2276bool Element::rareDataChildrenAffectedByHover() const
2277{
2278 ASSERT(hasRareData());
2279 return elementRareData()->childrenAffectedByHover();
2280}
2281
2282bool Element::rareDataChildrenAffectedByActive() const
2283{
2284 ASSERT(hasRareData());
2285 return elementRareData()->childrenAffectedByActive();
2286}
2287
2288bool Element::rareDataChildrenAffectedByDrag() const
2289{
2290 ASSERT(hasRareData());
2291 return elementRareData()->childrenAffectedByDrag();
2292}
2293
2294bool Element::rareDataChildrenAffectedByFirstChildRules() const
2295{
2296 ASSERT(hasRareData());
2297 return elementRareData()->childrenAffectedByFirstChildRules();
2298}
2299
2300bool Element::rareDataChildrenAffectedByLastChildRules() const
2301{
2302 ASSERT(hasRareData());
2303 return elementRareData()->childrenAffectedByLastChildRules();
2304}
2305
2306bool Element::rareDataChildrenAffectedByDirectAdjacentRules() const
2307{
2308 ASSERT(hasRareData());
2309 return elementRareData()->childrenAffectedByDirectAdjacentRules();
2310}
2311
2312bool Element::rareDataChildrenAffectedByForwardPositionalRules() const
2313{
2314 ASSERT(hasRareData());
2315 return elementRareData()->childrenAffectedByForwardPositionalRules();
2316}
2317
2318bool Element::rareDataChildrenAffectedByBackwardPositionalRules() const
2319{
2320 ASSERT(hasRareData());
2321 return elementRareData()->childrenAffectedByBackwardPositionalRules();
2322}
2323
2324unsigned Element::rareDataChildIndex() const
2325{
2326 ASSERT(hasRareData());
2327 return elementRareData()->childIndex();
2328}
2329
2330void Element::setIsInCanvasSubtree(bool isInCanvasSubtree)
2331{
2332 ensureElementRareData()->setIsInCanvasSubtree(isInCanvasSubtree);
2333}
2334
2335bool Element::isInCanvasSubtree() const
2336{
2337 return hasRareData() && elementRareData()->isInCanvasSubtree();
2338}
2339
Ben Murdoch591b9582013-07-10 11:41:44 +01002340void Element::setIsInsideRegion(bool value)
2341{
2342 if (value == isInsideRegion())
2343 return;
2344
2345 ensureElementRareData()->setIsInsideRegion(value);
2346}
2347
2348bool Element::isInsideRegion() const
2349{
2350 return hasRareData() ? elementRareData()->isInsideRegion() : false;
2351}
2352
2353void Element::setRegionOversetState(RegionOversetState state)
2354{
2355 ensureElementRareData()->setRegionOversetState(state);
2356}
2357
2358RegionOversetState Element::regionOversetState() const
2359{
2360 return hasRareData() ? elementRareData()->regionOversetState() : RegionUndefined;
2361}
2362
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002363AtomicString Element::computeInheritedLanguage() const
2364{
2365 const Node* n = this;
2366 AtomicString value;
2367 // The language property is inherited, so we iterate over the parents to find the first language.
2368 do {
2369 if (n->isElementNode()) {
2370 if (const ElementData* elementData = toElement(n)->elementData()) {
2371 // Spec: xml:lang takes precedence -- http://www.w3.org/TR/xhtml1/#C_7
2372 if (const Attribute* attribute = elementData->getAttributeItem(XMLNames::langAttr))
2373 value = attribute->value();
2374 else if (const Attribute* attribute = elementData->getAttributeItem(HTMLNames::langAttr))
2375 value = attribute->value();
2376 }
2377 } else if (n->isDocumentNode()) {
2378 // checking the MIME content-language
2379 value = toDocument(n)->contentLanguage();
2380 }
2381
2382 n = n->parentNode();
2383 } while (n && value.isNull());
2384
2385 return value;
2386}
2387
2388Locale& Element::locale() const
2389{
2390 return document()->getCachedLocale(computeInheritedLanguage());
2391}
2392
2393void Element::cancelFocusAppearanceUpdate()
2394{
2395 if (hasRareData())
2396 elementRareData()->setNeedsFocusAppearanceUpdateSoonAfterAttach(false);
Ben Murdoch7757ec22013-07-23 11:17:36 +01002397 if (document()->focusedElement() == this)
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002398 document()->cancelFocusAppearanceUpdate();
2399}
2400
2401void Element::normalizeAttributes()
2402{
2403 if (!hasAttributes())
2404 return;
2405 for (unsigned i = 0; i < attributeCount(); ++i) {
2406 if (RefPtr<Attr> attr = attrIfExists(attributeItem(i)->name()))
2407 attr->normalize();
2408 }
2409}
2410
2411void Element::updatePseudoElement(PseudoId pseudoId, StyleChange change)
2412{
2413 PseudoElement* element = pseudoElement(pseudoId);
2414 if (element && (needsStyleRecalc() || shouldRecalcStyle(change, element))) {
2415 // PseudoElement styles hang off their parent element's style so if we needed
2416 // a style recalc we should Force one on the pseudo.
2417 element->recalcStyle(needsStyleRecalc() ? Force : change);
2418
2419 // Wait until our parent is not displayed or pseudoElementRendererIsNeeded
2420 // is false, otherwise we could continously create and destroy PseudoElements
2421 // when RenderObject::isChildAllowed on our parent returns false for the
2422 // PseudoElement's renderer for each style recalc.
2423 if (!renderer() || !pseudoElementRendererIsNeeded(renderer()->getCachedPseudoStyle(pseudoId)))
Torne (Richard Coles)521d96e2013-06-19 11:58:24 +01002424 elementRareData()->setPseudoElement(pseudoId, 0);
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002425 } else if (change >= Inherit || needsStyleRecalc())
2426 createPseudoElementIfNeeded(pseudoId);
2427}
2428
2429void Element::createPseudoElementIfNeeded(PseudoId pseudoId)
2430{
Ben Murdoche69819b2013-07-17 14:56:49 +01002431 if ((pseudoId == BEFORE || pseudoId == AFTER) && !document()->styleSheetCollection()->usesBeforeAfterRules())
2432 return;
2433
2434 if (pseudoId == BACKDROP && !isInTopLayer())
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002435 return;
2436
2437 if (!renderer() || !pseudoElementRendererIsNeeded(renderer()->getCachedPseudoStyle(pseudoId)))
2438 return;
2439
2440 if (!renderer()->canHaveGeneratedChildren())
2441 return;
2442
2443 ASSERT(!isPseudoElement());
2444 RefPtr<PseudoElement> element = PseudoElement::create(this, pseudoId);
Ben Murdoche69819b2013-07-17 14:56:49 +01002445 if (pseudoId == BACKDROP)
2446 document()->addToTopLayer(element.get(), this);
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002447 element->attach();
Ben Murdoche69819b2013-07-17 14:56:49 +01002448
Torne (Richard Coles)521d96e2013-06-19 11:58:24 +01002449 ensureElementRareData()->setPseudoElement(pseudoId, element.release());
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002450}
2451
2452PseudoElement* Element::pseudoElement(PseudoId pseudoId) const
2453{
2454 return hasRareData() ? elementRareData()->pseudoElement(pseudoId) : 0;
2455}
2456
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002457RenderObject* Element::pseudoElementRenderer(PseudoId pseudoId) const
2458{
2459 if (PseudoElement* element = pseudoElement(pseudoId))
2460 return element->renderer();
2461 return 0;
2462}
2463
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002464bool Element::webkitMatchesSelector(const String& selector, ExceptionCode& ec)
2465{
2466 if (selector.isEmpty()) {
Ben Murdoche69819b2013-07-17 14:56:49 +01002467 ec = SyntaxError;
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002468 return false;
2469 }
2470
2471 SelectorQuery* selectorQuery = document()->selectorQueryCache()->add(selector, document(), ec);
2472 if (!selectorQuery)
2473 return false;
2474 return selectorQuery->matches(this);
2475}
2476
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002477DOMTokenList* Element::classList()
2478{
2479 ElementRareData* data = ensureElementRareData();
2480 if (!data->classList())
2481 data->setClassList(ClassList::create(this));
2482 return data->classList();
2483}
2484
2485DOMStringMap* Element::dataset()
2486{
2487 ElementRareData* data = ensureElementRareData();
2488 if (!data->dataset())
2489 data->setDataset(DatasetDOMStringMap::create(this));
2490 return data->dataset();
2491}
2492
2493KURL Element::getURLAttribute(const QualifiedName& name) const
2494{
2495#if !ASSERT_DISABLED
2496 if (elementData()) {
2497 if (const Attribute* attribute = getAttributeItem(name))
2498 ASSERT(isURLAttribute(*attribute));
2499 }
2500#endif
2501 return document()->completeURL(stripLeadingAndTrailingHTMLSpaces(getAttribute(name)));
2502}
2503
2504KURL Element::getNonEmptyURLAttribute(const QualifiedName& name) const
2505{
2506#if !ASSERT_DISABLED
2507 if (elementData()) {
2508 if (const Attribute* attribute = getAttributeItem(name))
2509 ASSERT(isURLAttribute(*attribute));
2510 }
2511#endif
2512 String value = stripLeadingAndTrailingHTMLSpaces(getAttribute(name));
2513 if (value.isEmpty())
2514 return KURL();
2515 return document()->completeURL(value);
2516}
2517
2518int Element::getIntegralAttribute(const QualifiedName& attributeName) const
2519{
2520 return getAttribute(attributeName).string().toInt();
2521}
2522
2523void Element::setIntegralAttribute(const QualifiedName& attributeName, int value)
2524{
2525 // FIXME: Need an AtomicString version of String::number.
2526 setAttribute(attributeName, String::number(value));
2527}
2528
2529unsigned Element::getUnsignedIntegralAttribute(const QualifiedName& attributeName) const
2530{
2531 return getAttribute(attributeName).string().toUInt();
2532}
2533
2534void Element::setUnsignedIntegralAttribute(const QualifiedName& attributeName, unsigned value)
2535{
2536 // FIXME: Need an AtomicString version of String::number.
2537 setAttribute(attributeName, String::number(value));
2538}
2539
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002540bool Element::childShouldCreateRenderer(const NodeRenderingContext& childContext) const
2541{
2542 // Only create renderers for SVG elements whose parents are SVG elements, or for proper <svg xmlns="svgNS"> subdocuments.
2543 if (childContext.node()->isSVGElement())
2544 return childContext.node()->hasTagName(SVGNames::svgTag) || isSVGElement();
2545
2546 return ContainerNode::childShouldCreateRenderer(childContext);
2547}
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002548
2549void Element::webkitRequestFullscreen()
2550{
Torne (Richard Coles)521d96e2013-06-19 11:58:24 +01002551 FullscreenController::from(document())->requestFullScreenForElement(this, ALLOW_KEYBOARD_INPUT, FullscreenController::EnforceIFrameAllowFullScreenRequirement);
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002552}
2553
2554void Element::webkitRequestFullScreen(unsigned short flags)
2555{
Torne (Richard Coles)521d96e2013-06-19 11:58:24 +01002556 FullscreenController::from(document())->requestFullScreenForElement(this, (flags | LEGACY_MOZILLA_REQUEST), FullscreenController::EnforceIFrameAllowFullScreenRequirement);
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002557}
2558
2559bool Element::containsFullScreenElement() const
2560{
2561 return hasRareData() && elementRareData()->containsFullScreenElement();
2562}
2563
2564void Element::setContainsFullScreenElement(bool flag)
2565{
2566 ensureElementRareData()->setContainsFullScreenElement(flag);
Ben Murdoche69819b2013-07-17 14:56:49 +01002567 setNeedsStyleRecalc(SubtreeStyleChange);
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002568}
2569
2570static Element* parentCrossingFrameBoundaries(Element* element)
2571{
2572 ASSERT(element);
2573 return element->parentElement() ? element->parentElement() : element->document()->ownerElement();
2574}
2575
2576void Element::setContainsFullScreenElementOnAncestorsCrossingFrameBoundaries(bool flag)
2577{
2578 Element* element = this;
2579 while ((element = parentCrossingFrameBoundaries(element)))
2580 element->setContainsFullScreenElement(flag);
2581}
2582
2583bool Element::isInTopLayer() const
2584{
2585 return hasRareData() && elementRareData()->isInTopLayer();
2586}
2587
2588void Element::setIsInTopLayer(bool inTopLayer)
2589{
2590 if (isInTopLayer() == inTopLayer)
2591 return;
2592 ensureElementRareData()->setIsInTopLayer(inTopLayer);
2593
2594 // We must ensure a reattach occurs so the renderer is inserted in the correct sibling order under RenderView according to its
2595 // top layer position, or in its usual place if not in the top layer.
Torne (Richard Coles)93ac45c2013-05-29 14:40:20 +01002596 lazyReattachIfAttached();
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002597}
2598
2599void Element::webkitRequestPointerLock()
2600{
2601 if (document()->page())
2602 document()->page()->pointerLockController()->requestPointerLock(this);
2603}
2604
2605SpellcheckAttributeState Element::spellcheckAttributeState() const
2606{
2607 const AtomicString& value = getAttribute(HTMLNames::spellcheckAttr);
2608 if (value == nullAtom)
2609 return SpellcheckAttributeDefault;
2610 if (equalIgnoringCase(value, "true") || equalIgnoringCase(value, ""))
2611 return SpellcheckAttributeTrue;
2612 if (equalIgnoringCase(value, "false"))
2613 return SpellcheckAttributeFalse;
2614
2615 return SpellcheckAttributeDefault;
2616}
2617
2618bool Element::isSpellCheckingEnabled() const
2619{
2620 for (const Element* element = this; element; element = element->parentOrShadowHostElement()) {
2621 switch (element->spellcheckAttributeState()) {
2622 case SpellcheckAttributeTrue:
2623 return true;
2624 case SpellcheckAttributeFalse:
2625 return false;
2626 case SpellcheckAttributeDefault:
2627 break;
2628 }
2629 }
2630
2631 return true;
2632}
2633
2634RenderRegion* Element::renderRegion() const
2635{
2636 if (renderer() && renderer()->isRenderRegion())
2637 return toRenderRegion(renderer());
2638
2639 return 0;
2640}
2641
Ben Murdoch591b9582013-07-10 11:41:44 +01002642bool Element::shouldMoveToFlowThread(RenderStyle* styleToUse) const
2643{
2644 ASSERT(styleToUse);
2645
2646 if (FullscreenController::isActiveFullScreenElement(this))
2647 return false;
2648
2649 if (isInShadowTree())
2650 return false;
2651
2652 if (styleToUse->flowThread().isEmpty())
2653 return false;
2654
2655 return !isRegisteredWithNamedFlow();
2656}
2657
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002658const AtomicString& Element::webkitRegionOverset() const
2659{
2660 document()->updateLayoutIgnorePendingStylesheets();
2661
2662 DEFINE_STATIC_LOCAL(AtomicString, undefinedState, ("undefined", AtomicString::ConstructFromLiteral));
2663 if (!RuntimeEnabledFeatures::cssRegionsEnabled() || !renderRegion())
2664 return undefinedState;
2665
Ben Murdoch591b9582013-07-10 11:41:44 +01002666 switch (renderRegion()->regionOversetState()) {
2667 case RegionFit: {
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002668 DEFINE_STATIC_LOCAL(AtomicString, fitState, ("fit", AtomicString::ConstructFromLiteral));
2669 return fitState;
2670 }
Ben Murdoch591b9582013-07-10 11:41:44 +01002671 case RegionEmpty: {
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002672 DEFINE_STATIC_LOCAL(AtomicString, emptyState, ("empty", AtomicString::ConstructFromLiteral));
2673 return emptyState;
2674 }
Ben Murdoch591b9582013-07-10 11:41:44 +01002675 case RegionOverset: {
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002676 DEFINE_STATIC_LOCAL(AtomicString, overflowState, ("overset", AtomicString::ConstructFromLiteral));
2677 return overflowState;
2678 }
Ben Murdoch591b9582013-07-10 11:41:44 +01002679 case RegionUndefined:
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002680 return undefinedState;
2681 }
2682
2683 ASSERT_NOT_REACHED();
2684 return undefinedState;
2685}
2686
2687Vector<RefPtr<Range> > Element::webkitGetRegionFlowRanges() const
2688{
2689 document()->updateLayoutIgnorePendingStylesheets();
2690
2691 Vector<RefPtr<Range> > rangeObjects;
2692 if (RuntimeEnabledFeatures::cssRegionsEnabled() && renderer() && renderer()->isRenderRegion()) {
2693 RenderRegion* region = toRenderRegion(renderer());
2694 if (region->isValid())
2695 region->getRanges(rangeObjects);
2696 }
2697
2698 return rangeObjects;
2699}
2700
2701#ifndef NDEBUG
2702bool Element::fastAttributeLookupAllowed(const QualifiedName& name) const
2703{
2704 if (name == HTMLNames::styleAttr)
2705 return false;
2706
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002707 if (isSVGElement())
2708 return !static_cast<const SVGElement*>(this)->isAnimatableAttribute(name);
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002709
2710 return true;
2711}
2712#endif
2713
2714#ifdef DUMP_NODE_STATISTICS
2715bool Element::hasNamedNodeMap() const
2716{
2717 return hasRareData() && elementRareData()->attributeMap();
2718}
2719#endif
2720
2721inline void Element::updateName(const AtomicString& oldName, const AtomicString& newName)
2722{
2723 if (!inDocument() || isInShadowTree())
2724 return;
2725
2726 if (oldName == newName)
2727 return;
2728
2729 if (shouldRegisterAsNamedItem())
2730 updateNamedItemRegistration(oldName, newName);
2731}
2732
2733inline void Element::updateId(const AtomicString& oldId, const AtomicString& newId)
2734{
2735 if (!isInTreeScope())
2736 return;
2737
2738 if (oldId == newId)
2739 return;
2740
2741 updateId(treeScope(), oldId, newId);
2742}
2743
2744inline void Element::updateId(TreeScope* scope, const AtomicString& oldId, const AtomicString& newId)
2745{
2746 ASSERT(isInTreeScope());
2747 ASSERT(oldId != newId);
2748
2749 if (!oldId.isEmpty())
2750 scope->removeElementById(oldId, this);
2751 if (!newId.isEmpty())
2752 scope->addElementById(newId, this);
2753
2754 if (shouldRegisterAsExtraNamedItem())
2755 updateExtraNamedItemRegistration(oldId, newId);
2756}
2757
2758void Element::updateLabel(TreeScope* scope, const AtomicString& oldForAttributeValue, const AtomicString& newForAttributeValue)
2759{
2760 ASSERT(hasTagName(labelTag));
2761
2762 if (!inDocument())
2763 return;
2764
2765 if (oldForAttributeValue == newForAttributeValue)
2766 return;
2767
2768 if (!oldForAttributeValue.isEmpty())
Ben Murdoche69819b2013-07-17 14:56:49 +01002769 scope->removeLabel(oldForAttributeValue, toHTMLLabelElement(this));
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002770 if (!newForAttributeValue.isEmpty())
Ben Murdoche69819b2013-07-17 14:56:49 +01002771 scope->addLabel(newForAttributeValue, toHTMLLabelElement(this));
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002772}
2773
Ben Murdoch7757ec22013-07-23 11:17:36 +01002774static bool hasSelectorForAttribute(Document* document, const AtomicString& localName)
2775{
2776 return document->styleResolver() && document->styleResolver()->ruleFeatureSet().hasSelectorForAttribute(localName);
2777}
2778
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002779void Element::willModifyAttribute(const QualifiedName& name, const AtomicString& oldValue, const AtomicString& newValue)
2780{
2781 if (isIdAttributeName(name))
2782 updateId(oldValue, newValue);
2783 else if (name == HTMLNames::nameAttr)
2784 updateName(oldValue, newValue);
2785 else if (name == HTMLNames::forAttr && hasTagName(labelTag)) {
2786 TreeScope* scope = treeScope();
2787 if (scope->shouldCacheLabelsByForAttribute())
2788 updateLabel(scope, oldValue, newValue);
2789 }
2790
2791 if (oldValue != newValue) {
Ben Murdoch7757ec22013-07-23 11:17:36 +01002792 if (attached() && hasSelectorForAttribute(document(), name.localName()))
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002793 setNeedsStyleRecalc();
Ben Murdoche69819b2013-07-17 14:56:49 +01002794
2795 if (isUpgradedCustomElement())
Ben Murdoch83750172013-07-24 10:36:59 +01002796 CustomElement::attributeDidChange(this, name.localName(), oldValue, newValue);
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002797 }
2798
2799 if (OwnPtr<MutationObserverInterestGroup> recipients = MutationObserverInterestGroup::createForAttributesMutation(this, name))
2800 recipients->enqueueMutationRecord(MutationRecord::createAttributes(this, name, oldValue));
2801
2802 InspectorInstrumentation::willModifyDOMAttr(document(), this, oldValue, newValue);
2803}
2804
2805void Element::didAddAttribute(const QualifiedName& name, const AtomicString& value)
2806{
2807 attributeChanged(name, value);
2808 InspectorInstrumentation::didModifyDOMAttr(document(), this, name.localName(), value);
2809 dispatchSubtreeModifiedEvent();
2810}
2811
2812void Element::didModifyAttribute(const QualifiedName& name, const AtomicString& value)
2813{
2814 attributeChanged(name, value);
2815 InspectorInstrumentation::didModifyDOMAttr(document(), this, name.localName(), value);
2816 // Do not dispatch a DOMSubtreeModified event here; see bug 81141.
2817}
2818
2819void Element::didRemoveAttribute(const QualifiedName& name)
2820{
2821 attributeChanged(name, nullAtom);
2822 InspectorInstrumentation::didRemoveDOMAttr(document(), this, name.localName());
2823 dispatchSubtreeModifiedEvent();
2824}
2825
Ben Murdoche69819b2013-07-17 14:56:49 +01002826void Element::didMoveToNewDocument(Document* oldDocument)
2827{
2828 Node::didMoveToNewDocument(oldDocument);
2829
2830 // If the documents differ by quirks mode then they differ by case sensitivity
2831 // for class and id names so we need to go through the attribute change logic
2832 // to pick up the new casing in the ElementData.
2833 if (oldDocument->inQuirksMode() != document()->inQuirksMode()) {
2834 if (hasID())
2835 setIdAttribute(getIdAttribute());
2836 if (hasClass())
2837 setAttribute(HTMLNames::classAttr, getClassAttribute());
2838 }
2839}
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002840
2841void Element::updateNamedItemRegistration(const AtomicString& oldName, const AtomicString& newName)
2842{
2843 if (!document()->isHTMLDocument())
2844 return;
2845
2846 if (!oldName.isEmpty())
2847 toHTMLDocument(document())->removeNamedItem(oldName);
2848
2849 if (!newName.isEmpty())
2850 toHTMLDocument(document())->addNamedItem(newName);
2851}
2852
2853void Element::updateExtraNamedItemRegistration(const AtomicString& oldId, const AtomicString& newId)
2854{
2855 if (!document()->isHTMLDocument())
2856 return;
2857
2858 if (!oldId.isEmpty())
2859 toHTMLDocument(document())->removeExtraNamedItem(oldId);
2860
2861 if (!newId.isEmpty())
2862 toHTMLDocument(document())->addExtraNamedItem(newId);
2863}
2864
2865PassRefPtr<HTMLCollection> Element::ensureCachedHTMLCollection(CollectionType type)
2866{
2867 if (HTMLCollection* collection = cachedHTMLCollection(type))
2868 return collection;
2869
2870 RefPtr<HTMLCollection> collection;
2871 if (type == TableRows) {
2872 ASSERT(hasTagName(tableTag));
2873 return ensureRareData()->ensureNodeLists()->addCacheWithAtomicName<HTMLTableRowsCollection>(this, type);
2874 } else if (type == SelectOptions) {
2875 ASSERT(hasTagName(selectTag));
2876 return ensureRareData()->ensureNodeLists()->addCacheWithAtomicName<HTMLOptionsCollection>(this, type);
2877 } else if (type == FormControls) {
2878 ASSERT(hasTagName(formTag) || hasTagName(fieldsetTag));
2879 return ensureRareData()->ensureNodeLists()->addCacheWithAtomicName<HTMLFormControlsCollection>(this, type);
2880 }
2881 return ensureRareData()->ensureNodeLists()->addCacheWithAtomicName<HTMLCollection>(this, type);
2882}
2883
Ben Murdoch591b9582013-07-10 11:41:44 +01002884static void scheduleLayerUpdateCallback(Node* node)
Torne (Richard Coles)93ac45c2013-05-29 14:40:20 +01002885{
Ben Murdoche69819b2013-07-17 14:56:49 +01002886 // Notify the renderer even is the styles are identical since it may need to
2887 // create or destroy a RenderLayer.
2888 node->setNeedsStyleRecalc(LocalStyleChange, StyleChangeFromRenderer);
Torne (Richard Coles)93ac45c2013-05-29 14:40:20 +01002889}
2890
Ben Murdoch591b9582013-07-10 11:41:44 +01002891void Element::scheduleLayerUpdate()
Torne (Richard Coles)93ac45c2013-05-29 14:40:20 +01002892{
2893 if (postAttachCallbacksAreSuspended())
Ben Murdoch591b9582013-07-10 11:41:44 +01002894 queuePostAttachCallback(scheduleLayerUpdateCallback, this);
Torne (Richard Coles)93ac45c2013-05-29 14:40:20 +01002895 else
Ben Murdoche69819b2013-07-17 14:56:49 +01002896 scheduleLayerUpdateCallback(this);
Torne (Richard Coles)93ac45c2013-05-29 14:40:20 +01002897}
2898
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002899HTMLCollection* Element::cachedHTMLCollection(CollectionType type)
2900{
2901 return hasRareData() && rareData()->nodeLists() ? rareData()->nodeLists()->cacheWithAtomicName<HTMLCollection>(type) : 0;
2902}
2903
2904IntSize Element::savedLayerScrollOffset() const
2905{
2906 return hasRareData() ? elementRareData()->savedLayerScrollOffset() : IntSize();
2907}
2908
2909void Element::setSavedLayerScrollOffset(const IntSize& size)
2910{
2911 if (size.isZero() && !hasRareData())
2912 return;
2913 ensureElementRareData()->setSavedLayerScrollOffset(size);
2914}
2915
2916PassRefPtr<Attr> Element::attrIfExists(const QualifiedName& name)
2917{
2918 if (AttrNodeList* attrNodeList = attrNodeListForElement(this))
2919 return findAttrNodeInList(attrNodeList, name);
2920 return 0;
2921}
2922
2923PassRefPtr<Attr> Element::ensureAttr(const QualifiedName& name)
2924{
2925 AttrNodeList* attrNodeList = ensureAttrNodeListForElement(this);
2926 RefPtr<Attr> attrNode = findAttrNodeInList(attrNodeList, name);
2927 if (!attrNode) {
2928 attrNode = Attr::create(this, name);
2929 treeScope()->adoptIfNeeded(attrNode.get());
2930 attrNodeList->append(attrNode);
2931 }
2932 return attrNode.release();
2933}
2934
2935void Element::detachAttrNodeFromElementWithValue(Attr* attrNode, const AtomicString& value)
2936{
2937 ASSERT(hasSyntheticAttrChildNodes());
2938 attrNode->detachFromElementWithValue(value);
2939
2940 AttrNodeList* attrNodeList = attrNodeListForElement(this);
2941 for (unsigned i = 0; i < attrNodeList->size(); ++i) {
2942 if (attrNodeList->at(i)->qualifiedName() == attrNode->qualifiedName()) {
2943 attrNodeList->remove(i);
2944 if (attrNodeList->isEmpty())
2945 removeAttrNodeListForElement(this);
2946 return;
2947 }
2948 }
2949 ASSERT_NOT_REACHED();
2950}
2951
2952void Element::detachAllAttrNodesFromElement()
2953{
2954 AttrNodeList* attrNodeList = attrNodeListForElement(this);
2955 ASSERT(attrNodeList);
2956
2957 for (unsigned i = 0; i < attributeCount(); ++i) {
2958 const Attribute* attribute = attributeItem(i);
2959 if (RefPtr<Attr> attrNode = findAttrNodeInList(attrNodeList, attribute->name()))
2960 attrNode->detachFromElementWithValue(attribute->value());
2961 }
2962
2963 removeAttrNodeListForElement(this);
2964}
2965
2966void Element::willRecalcStyle(StyleChange)
2967{
2968 ASSERT(hasCustomStyleCallbacks());
2969}
2970
2971void Element::didRecalcStyle(StyleChange)
2972{
2973 ASSERT(hasCustomStyleCallbacks());
2974}
2975
2976
2977PassRefPtr<RenderStyle> Element::customStyleForRenderer()
2978{
2979 ASSERT(hasCustomStyleCallbacks());
2980 return 0;
2981}
2982
2983void Element::cloneAttributesFromElement(const Element& other)
2984{
2985 if (hasSyntheticAttrChildNodes())
2986 detachAllAttrNodesFromElement();
2987
2988 other.synchronizeAllAttributes();
2989 if (!other.m_elementData) {
2990 m_elementData.clear();
2991 return;
2992 }
2993
2994 const AtomicString& oldID = getIdAttribute();
2995 const AtomicString& newID = other.getIdAttribute();
2996
2997 if (!oldID.isNull() || !newID.isNull())
2998 updateId(oldID, newID);
2999
3000 const AtomicString& oldName = getNameAttribute();
3001 const AtomicString& newName = other.getNameAttribute();
3002
3003 if (!oldName.isNull() || !newName.isNull())
3004 updateName(oldName, newName);
3005
Ben Murdoche69819b2013-07-17 14:56:49 +01003006 // Quirks mode makes class and id not case sensitive. We can't share the ElementData
3007 // if the idForStyleResolution and the className need different casing.
3008 bool ownerDocumentsHaveDifferentCaseSensitivity = false;
3009 if (other.hasClass() || other.hasID())
3010 ownerDocumentsHaveDifferentCaseSensitivity = other.document()->inQuirksMode() != document()->inQuirksMode();
3011
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01003012 // 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 +01003013 // We can only do this if there is no CSSOM wrapper for other's inline style, and there are no presentation attributes,
3014 // and sharing the data won't result in different case sensitivity of class or id.
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01003015 if (other.m_elementData->isUnique()
Ben Murdoche69819b2013-07-17 14:56:49 +01003016 && !ownerDocumentsHaveDifferentCaseSensitivity
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01003017 && !other.m_elementData->presentationAttributeStyle()
3018 && (!other.m_elementData->inlineStyle() || !other.m_elementData->inlineStyle()->hasCSSOMWrapper()))
3019 const_cast<Element&>(other).m_elementData = static_cast<const UniqueElementData*>(other.m_elementData.get())->makeShareableCopy();
3020
Ben Murdoche69819b2013-07-17 14:56:49 +01003021 if (!other.m_elementData->isUnique() && !ownerDocumentsHaveDifferentCaseSensitivity)
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01003022 m_elementData = other.m_elementData;
3023 else
3024 m_elementData = other.m_elementData->makeUniqueCopy();
3025
3026 for (unsigned i = 0; i < m_elementData->length(); ++i) {
3027 const Attribute* attribute = const_cast<const ElementData*>(m_elementData.get())->attributeItem(i);
3028 attributeChangedFromParserOrByCloning(attribute->name(), attribute->value(), ModifiedByCloning);
3029 }
3030}
3031
3032void Element::cloneDataFromElement(const Element& other)
3033{
3034 cloneAttributesFromElement(other);
3035 copyNonAttributePropertiesFromElement(other);
3036}
3037
3038void Element::createUniqueElementData()
3039{
3040 if (!m_elementData)
3041 m_elementData = UniqueElementData::create();
3042 else {
3043 ASSERT(!m_elementData->isUnique());
3044 m_elementData = static_cast<ShareableElementData*>(m_elementData.get())->makeUniqueCopy();
3045 }
3046}
3047
Torne (Richard Coles)81a51572013-05-13 16:52:28 +01003048InputMethodContext* Element::getInputContext()
3049{
3050 return ensureElementRareData()->ensureInputMethodContext(toHTMLElement(this));
3051}
3052
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01003053bool Element::hasPendingResources() const
3054{
3055 return hasRareData() && elementRareData()->hasPendingResources();
3056}
3057
3058void Element::setHasPendingResources()
3059{
3060 ensureElementRareData()->setHasPendingResources(true);
3061}
3062
3063void Element::clearHasPendingResources()
3064{
3065 ensureElementRareData()->setHasPendingResources(false);
3066}
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01003067
Ben Murdoch591b9582013-07-10 11:41:44 +01003068struct PresentationAttributeCacheKey {
3069 PresentationAttributeCacheKey() : tagName(0) { }
Ben Murdoch83750172013-07-24 10:36:59 +01003070 StringImpl* tagName;
Ben Murdoch591b9582013-07-10 11:41:44 +01003071 // Only the values need refcounting.
Ben Murdoch83750172013-07-24 10:36:59 +01003072 Vector<pair<StringImpl*, AtomicString>, 3> attributesAndValues;
Ben Murdoch591b9582013-07-10 11:41:44 +01003073};
3074
3075struct PresentationAttributeCacheEntry {
3076 WTF_MAKE_FAST_ALLOCATED;
3077public:
3078 PresentationAttributeCacheKey key;
3079 RefPtr<StylePropertySet> value;
3080};
3081
3082typedef HashMap<unsigned, OwnPtr<PresentationAttributeCacheEntry>, AlreadyHashed> PresentationAttributeCache;
3083
3084static bool operator!=(const PresentationAttributeCacheKey& a, const PresentationAttributeCacheKey& b)
3085{
3086 if (a.tagName != b.tagName)
3087 return true;
3088 return a.attributesAndValues != b.attributesAndValues;
3089}
3090
3091static PresentationAttributeCache& presentationAttributeCache()
3092{
3093 DEFINE_STATIC_LOCAL(PresentationAttributeCache, cache, ());
3094 return cache;
3095}
3096
3097class PresentationAttributeCacheCleaner {
3098 WTF_MAKE_NONCOPYABLE(PresentationAttributeCacheCleaner); WTF_MAKE_FAST_ALLOCATED;
3099public:
3100 PresentationAttributeCacheCleaner()
3101 : m_hitCount(0)
3102 , m_cleanTimer(this, &PresentationAttributeCacheCleaner::cleanCache)
3103 {
3104 }
3105
3106 void didHitPresentationAttributeCache()
3107 {
3108 if (presentationAttributeCache().size() < minimumPresentationAttributeCacheSizeForCleaning)
3109 return;
3110
3111 m_hitCount++;
3112
3113 if (!m_cleanTimer.isActive())
3114 m_cleanTimer.startOneShot(presentationAttributeCacheCleanTimeInSeconds);
3115 }
3116
3117private:
3118 static const unsigned presentationAttributeCacheCleanTimeInSeconds = 60;
3119 static const int minimumPresentationAttributeCacheSizeForCleaning = 100;
3120 static const unsigned minimumPresentationAttributeCacheHitCountPerMinute = (100 * presentationAttributeCacheCleanTimeInSeconds) / 60;
3121
3122 void cleanCache(Timer<PresentationAttributeCacheCleaner>* timer)
3123 {
3124 ASSERT_UNUSED(timer, timer == &m_cleanTimer);
3125 unsigned hitCount = m_hitCount;
3126 m_hitCount = 0;
3127 if (hitCount > minimumPresentationAttributeCacheHitCountPerMinute)
3128 return;
3129 presentationAttributeCache().clear();
3130 }
3131
3132 unsigned m_hitCount;
3133 Timer<PresentationAttributeCacheCleaner> m_cleanTimer;
3134};
3135
3136static PresentationAttributeCacheCleaner& presentationAttributeCacheCleaner()
3137{
3138 DEFINE_STATIC_LOCAL(PresentationAttributeCacheCleaner, cleaner, ());
3139 return cleaner;
3140}
3141
3142void Element::synchronizeStyleAttributeInternal() const
3143{
3144 ASSERT(isStyledElement());
3145 ASSERT(elementData());
3146 ASSERT(elementData()->m_styleAttributeIsDirty);
3147 elementData()->m_styleAttributeIsDirty = false;
3148 if (const StylePropertySet* inlineStyle = this->inlineStyle())
3149 const_cast<Element*>(this)->setSynchronizedLazyAttribute(styleAttr, inlineStyle->asText());
3150}
3151
3152CSSStyleDeclaration* Element::style()
3153{
3154 if (!isStyledElement())
3155 return 0;
3156 return ensureMutableInlineStyle()->ensureInlineCSSStyleDeclaration(this);
3157}
3158
3159MutableStylePropertySet* Element::ensureMutableInlineStyle()
3160{
3161 ASSERT(isStyledElement());
3162 RefPtr<StylePropertySet>& inlineStyle = ensureUniqueElementData()->m_inlineStyle;
3163 if (!inlineStyle)
3164 inlineStyle = MutableStylePropertySet::create(strictToCSSParserMode(isHTMLElement() && !document()->inQuirksMode()));
3165 else if (!inlineStyle->isMutable())
3166 inlineStyle = inlineStyle->mutableCopy();
3167 ASSERT(inlineStyle->isMutable());
3168 return static_cast<MutableStylePropertySet*>(inlineStyle.get());
3169}
3170
3171PropertySetCSSStyleDeclaration* Element::inlineStyleCSSOMWrapper()
3172{
3173 if (!inlineStyle() || !inlineStyle()->hasCSSOMWrapper())
3174 return 0;
3175 PropertySetCSSStyleDeclaration* cssomWrapper = ensureMutableInlineStyle()->cssStyleDeclaration();
3176 ASSERT(cssomWrapper && cssomWrapper->parentElement() == this);
3177 return cssomWrapper;
3178}
3179
3180inline void Element::setInlineStyleFromString(const AtomicString& newStyleString)
3181{
3182 ASSERT(isStyledElement());
3183 RefPtr<StylePropertySet>& inlineStyle = elementData()->m_inlineStyle;
3184
3185 // Avoid redundant work if we're using shared attribute data with already parsed inline style.
3186 if (inlineStyle && !elementData()->isUnique())
3187 return;
3188
3189 // We reconstruct the property set instead of mutating if there is no CSSOM wrapper.
3190 // This makes wrapperless property sets immutable and so cacheable.
3191 if (inlineStyle && !inlineStyle->isMutable())
3192 inlineStyle.clear();
3193
3194 if (!inlineStyle) {
3195 inlineStyle = CSSParser::parseInlineStyleDeclaration(newStyleString, this);
3196 } else {
3197 ASSERT(inlineStyle->isMutable());
3198 static_pointer_cast<MutableStylePropertySet>(inlineStyle)->parseDeclaration(newStyleString, document()->elementSheet()->contents());
3199 }
3200}
3201
3202void Element::styleAttributeChanged(const AtomicString& newStyleString, AttributeModificationReason modificationReason)
3203{
3204 ASSERT(isStyledElement());
3205 WTF::OrdinalNumber startLineNumber = WTF::OrdinalNumber::beforeFirst();
3206 if (document() && document()->scriptableDocumentParser() && !document()->isInDocumentWrite())
3207 startLineNumber = document()->scriptableDocumentParser()->lineNumber();
3208
3209 if (newStyleString.isNull()) {
3210 if (PropertySetCSSStyleDeclaration* cssomWrapper = inlineStyleCSSOMWrapper())
3211 cssomWrapper->clearParentElement();
3212 ensureUniqueElementData()->m_inlineStyle.clear();
3213 } else if (modificationReason == ModifiedByCloning || document()->contentSecurityPolicy()->allowInlineStyle(document()->url(), startLineNumber)) {
3214 setInlineStyleFromString(newStyleString);
3215 }
3216
3217 elementData()->m_styleAttributeIsDirty = false;
3218
Ben Murdoche69819b2013-07-17 14:56:49 +01003219 setNeedsStyleRecalc(LocalStyleChange);
Ben Murdoch591b9582013-07-10 11:41:44 +01003220 InspectorInstrumentation::didInvalidateStyleAttr(document(), this);
3221}
3222
3223void Element::inlineStyleChanged()
3224{
3225 ASSERT(isStyledElement());
Ben Murdoche69819b2013-07-17 14:56:49 +01003226 setNeedsStyleRecalc(LocalStyleChange);
Ben Murdoch591b9582013-07-10 11:41:44 +01003227 ASSERT(elementData());
3228 elementData()->m_styleAttributeIsDirty = true;
3229 InspectorInstrumentation::didInvalidateStyleAttr(document(), this);
3230}
3231
3232bool Element::setInlineStyleProperty(CSSPropertyID propertyID, CSSValueID identifier, bool important)
3233{
3234 ASSERT(isStyledElement());
3235 ensureMutableInlineStyle()->setProperty(propertyID, cssValuePool().createIdentifierValue(identifier), important);
3236 inlineStyleChanged();
3237 return true;
3238}
3239
3240bool Element::setInlineStyleProperty(CSSPropertyID propertyID, CSSPropertyID identifier, bool important)
3241{
3242 ASSERT(isStyledElement());
3243 ensureMutableInlineStyle()->setProperty(propertyID, cssValuePool().createIdentifierValue(identifier), important);
3244 inlineStyleChanged();
3245 return true;
3246}
3247
3248bool Element::setInlineStyleProperty(CSSPropertyID propertyID, double value, CSSPrimitiveValue::UnitTypes unit, bool important)
3249{
3250 ASSERT(isStyledElement());
3251 ensureMutableInlineStyle()->setProperty(propertyID, cssValuePool().createValue(value, unit), important);
3252 inlineStyleChanged();
3253 return true;
3254}
3255
3256bool Element::setInlineStyleProperty(CSSPropertyID propertyID, const String& value, bool important)
3257{
3258 ASSERT(isStyledElement());
3259 bool changes = ensureMutableInlineStyle()->setProperty(propertyID, value, important, document()->elementSheet()->contents());
3260 if (changes)
3261 inlineStyleChanged();
3262 return changes;
3263}
3264
3265bool Element::removeInlineStyleProperty(CSSPropertyID propertyID)
3266{
3267 ASSERT(isStyledElement());
3268 if (!inlineStyle())
3269 return false;
3270 bool changes = ensureMutableInlineStyle()->removeProperty(propertyID);
3271 if (changes)
3272 inlineStyleChanged();
3273 return changes;
3274}
3275
3276void Element::removeAllInlineStyleProperties()
3277{
3278 ASSERT(isStyledElement());
3279 if (!inlineStyle() || inlineStyle()->isEmpty())
3280 return;
3281 ensureMutableInlineStyle()->clear();
3282 inlineStyleChanged();
3283}
3284
3285void Element::addSubresourceAttributeURLs(ListHashSet<KURL>& urls) const
3286{
3287 ASSERT(isStyledElement());
3288 if (const StylePropertySet* inlineStyle = elementData() ? elementData()->inlineStyle() : 0)
3289 inlineStyle->addSubresourceStyleURLs(urls, document()->elementSheet()->contents());
3290}
3291
Ben Murdoch83750172013-07-24 10:36:59 +01003292static inline bool attributeNameSort(const pair<StringImpl*, AtomicString>& p1, const pair<StringImpl*, AtomicString>& p2)
Ben Murdoch591b9582013-07-10 11:41:44 +01003293{
3294 // Sort based on the attribute name pointers. It doesn't matter what the order is as long as it is always the same.
3295 return p1.first < p2.first;
3296}
3297
3298void Element::makePresentationAttributeCacheKey(PresentationAttributeCacheKey& result) const
3299{
3300 ASSERT(isStyledElement());
3301 // FIXME: Enable for SVG.
3302 if (namespaceURI() != xhtmlNamespaceURI)
3303 return;
3304 // Interpretation of the size attributes on <input> depends on the type attribute.
3305 if (hasTagName(inputTag))
3306 return;
3307 unsigned size = attributeCount();
3308 for (unsigned i = 0; i < size; ++i) {
3309 const Attribute* attribute = attributeItem(i);
3310 if (!isPresentationAttribute(attribute->name()))
3311 continue;
3312 if (!attribute->namespaceURI().isNull())
3313 return;
3314 // FIXME: Background URL may depend on the base URL and can't be shared. Disallow caching.
3315 if (attribute->name() == backgroundAttr)
3316 return;
3317 result.attributesAndValues.append(std::make_pair(attribute->localName().impl(), attribute->value()));
3318 }
3319 if (result.attributesAndValues.isEmpty())
3320 return;
3321 // Attribute order doesn't matter. Sort for easy equality comparison.
3322 std::sort(result.attributesAndValues.begin(), result.attributesAndValues.end(), attributeNameSort);
3323 // The cache key is non-null when the tagName is set.
3324 result.tagName = localName().impl();
3325}
3326
3327static unsigned computePresentationAttributeCacheHash(const PresentationAttributeCacheKey& key)
3328{
3329 if (!key.tagName)
3330 return 0;
3331 ASSERT(key.attributesAndValues.size());
3332 unsigned attributeHash = StringHasher::hashMemory(key.attributesAndValues.data(), key.attributesAndValues.size() * sizeof(key.attributesAndValues[0]));
3333 return WTF::pairIntHash(key.tagName->existingHash(), attributeHash);
3334}
3335
3336void Element::rebuildPresentationAttributeStyle()
3337{
3338 ASSERT(isStyledElement());
3339 PresentationAttributeCacheKey cacheKey;
3340 makePresentationAttributeCacheKey(cacheKey);
3341
3342 unsigned cacheHash = computePresentationAttributeCacheHash(cacheKey);
3343
3344 PresentationAttributeCache::iterator cacheIterator;
3345 if (cacheHash) {
3346 cacheIterator = presentationAttributeCache().add(cacheHash, nullptr).iterator;
3347 if (cacheIterator->value && cacheIterator->value->key != cacheKey)
3348 cacheHash = 0;
3349 } else {
3350 cacheIterator = presentationAttributeCache().end();
3351 }
3352
3353 RefPtr<StylePropertySet> style;
3354 if (cacheHash && cacheIterator->value) {
3355 style = cacheIterator->value->value;
3356 presentationAttributeCacheCleaner().didHitPresentationAttributeCache();
3357 } else {
3358 style = MutableStylePropertySet::create(isSVGElement() ? SVGAttributeMode : CSSQuirksMode);
3359 unsigned size = attributeCount();
3360 for (unsigned i = 0; i < size; ++i) {
3361 const Attribute* attribute = attributeItem(i);
3362 collectStyleForPresentationAttribute(attribute->name(), attribute->value(), static_cast<MutableStylePropertySet*>(style.get()));
3363 }
3364 }
3365
3366 // ShareableElementData doesn't store presentation attribute style, so make sure we have a UniqueElementData.
3367 UniqueElementData* elementData = ensureUniqueElementData();
3368
3369 elementData->m_presentationAttributeStyleIsDirty = false;
3370 elementData->m_presentationAttributeStyle = style->isEmpty() ? 0 : style;
3371
3372 if (!cacheHash || cacheIterator->value)
3373 return;
3374
3375 OwnPtr<PresentationAttributeCacheEntry> newEntry = adoptPtr(new PresentationAttributeCacheEntry);
3376 newEntry->key = cacheKey;
3377 newEntry->value = style.release();
3378
3379 static const int presentationAttributeCacheMaximumSize = 4096;
3380 if (presentationAttributeCache().size() > presentationAttributeCacheMaximumSize) {
3381 // Start building from scratch if the cache ever gets big.
3382 presentationAttributeCache().clear();
3383 presentationAttributeCache().set(cacheHash, newEntry.release());
3384 } else {
3385 cacheIterator->value = newEntry.release();
3386 }
3387}
3388
3389void Element::addPropertyToPresentationAttributeStyle(MutableStylePropertySet* style, CSSPropertyID propertyID, CSSValueID identifier)
3390{
3391 ASSERT(isStyledElement());
3392 style->setProperty(propertyID, cssValuePool().createIdentifierValue(identifier));
3393}
3394
3395void Element::addPropertyToPresentationAttributeStyle(MutableStylePropertySet* style, CSSPropertyID propertyID, double value, CSSPrimitiveValue::UnitTypes unit)
3396{
3397 ASSERT(isStyledElement());
3398 style->setProperty(propertyID, cssValuePool().createValue(value, unit));
3399}
3400
3401void Element::addPropertyToPresentationAttributeStyle(MutableStylePropertySet* style, CSSPropertyID propertyID, const String& value)
3402{
3403 ASSERT(isStyledElement());
3404 style->setProperty(propertyID, value, false, document()->elementSheet()->contents());
3405}
3406
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01003407void ElementData::deref()
3408{
3409 if (!derefBase())
3410 return;
3411
3412 if (m_isUnique)
3413 delete static_cast<UniqueElementData*>(this);
3414 else
3415 delete static_cast<ShareableElementData*>(this);
3416}
3417
3418ElementData::ElementData()
3419 : m_isUnique(true)
3420 , m_arraySize(0)
3421 , m_presentationAttributeStyleIsDirty(false)
3422 , m_styleAttributeIsDirty(false)
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01003423 , m_animatedSVGAttributesAreDirty(false)
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01003424{
3425}
3426
3427ElementData::ElementData(unsigned arraySize)
3428 : m_isUnique(false)
3429 , m_arraySize(arraySize)
3430 , m_presentationAttributeStyleIsDirty(false)
3431 , m_styleAttributeIsDirty(false)
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01003432 , m_animatedSVGAttributesAreDirty(false)
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01003433{
3434}
3435
3436struct SameSizeAsElementData : public RefCounted<SameSizeAsElementData> {
3437 unsigned bitfield;
3438 void* refPtrs[3];
3439};
3440
3441COMPILE_ASSERT(sizeof(ElementData) == sizeof(SameSizeAsElementData), element_attribute_data_should_stay_small);
3442
3443static size_t sizeForShareableElementDataWithAttributeCount(unsigned count)
3444{
3445 return sizeof(ShareableElementData) + sizeof(Attribute) * count;
3446}
3447
3448PassRefPtr<ShareableElementData> ShareableElementData::createWithAttributes(const Vector<Attribute>& attributes)
3449{
3450 void* slot = WTF::fastMalloc(sizeForShareableElementDataWithAttributeCount(attributes.size()));
3451 return adoptRef(new (slot) ShareableElementData(attributes));
3452}
3453
3454PassRefPtr<UniqueElementData> UniqueElementData::create()
3455{
3456 return adoptRef(new UniqueElementData);
3457}
3458
3459ShareableElementData::ShareableElementData(const Vector<Attribute>& attributes)
3460 : ElementData(attributes.size())
3461{
3462 for (unsigned i = 0; i < m_arraySize; ++i)
3463 new (&m_attributeArray[i]) Attribute(attributes[i]);
3464}
3465
3466ShareableElementData::~ShareableElementData()
3467{
3468 for (unsigned i = 0; i < m_arraySize; ++i)
3469 m_attributeArray[i].~Attribute();
3470}
3471
3472ShareableElementData::ShareableElementData(const UniqueElementData& other)
3473 : ElementData(other, false)
3474{
3475 ASSERT(!other.m_presentationAttributeStyle);
3476
3477 if (other.m_inlineStyle) {
3478 ASSERT(!other.m_inlineStyle->hasCSSOMWrapper());
3479 m_inlineStyle = other.m_inlineStyle->immutableCopyIfNeeded();
3480 }
3481
3482 for (unsigned i = 0; i < m_arraySize; ++i)
3483 new (&m_attributeArray[i]) Attribute(other.m_attributeVector.at(i));
3484}
3485
3486ElementData::ElementData(const ElementData& other, bool isUnique)
3487 : m_isUnique(isUnique)
3488 , m_arraySize(isUnique ? 0 : other.length())
3489 , m_presentationAttributeStyleIsDirty(other.m_presentationAttributeStyleIsDirty)
3490 , m_styleAttributeIsDirty(other.m_styleAttributeIsDirty)
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01003491 , m_animatedSVGAttributesAreDirty(other.m_animatedSVGAttributesAreDirty)
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01003492 , m_classNames(other.m_classNames)
3493 , m_idForStyleResolution(other.m_idForStyleResolution)
3494{
3495 // NOTE: The inline style is copied by the subclass copy constructor since we don't know what to do with it here.
3496}
3497
3498UniqueElementData::UniqueElementData()
3499{
3500}
3501
3502UniqueElementData::UniqueElementData(const UniqueElementData& other)
3503 : ElementData(other, true)
3504 , m_presentationAttributeStyle(other.m_presentationAttributeStyle)
3505 , m_attributeVector(other.m_attributeVector)
3506{
Torne (Richard Coles)93ac45c2013-05-29 14:40:20 +01003507 m_inlineStyle = other.m_inlineStyle ? other.m_inlineStyle->mutableCopy() : 0;
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01003508}
3509
3510UniqueElementData::UniqueElementData(const ShareableElementData& other)
3511 : ElementData(other, true)
3512{
3513 // An ShareableElementData should never have a mutable inline StylePropertySet attached.
3514 ASSERT(!other.m_inlineStyle || !other.m_inlineStyle->isMutable());
3515 m_inlineStyle = other.m_inlineStyle;
3516
3517 m_attributeVector.reserveCapacity(other.length());
3518 for (unsigned i = 0; i < other.length(); ++i)
3519 m_attributeVector.uncheckedAppend(other.m_attributeArray[i]);
3520}
3521
3522PassRefPtr<UniqueElementData> ElementData::makeUniqueCopy() const
3523{
3524 if (isUnique())
3525 return adoptRef(new UniqueElementData(static_cast<const UniqueElementData&>(*this)));
3526 return adoptRef(new UniqueElementData(static_cast<const ShareableElementData&>(*this)));
3527}
3528
3529PassRefPtr<ShareableElementData> UniqueElementData::makeShareableCopy() const
3530{
3531 void* slot = WTF::fastMalloc(sizeForShareableElementDataWithAttributeCount(m_attributeVector.size()));
3532 return adoptRef(new (slot) ShareableElementData(*this));
3533}
3534
3535void UniqueElementData::addAttribute(const QualifiedName& attributeName, const AtomicString& value)
3536{
3537 m_attributeVector.append(Attribute(attributeName, value));
3538}
3539
3540void UniqueElementData::removeAttribute(size_t index)
3541{
3542 ASSERT_WITH_SECURITY_IMPLICATION(index < length());
3543 m_attributeVector.remove(index);
3544}
3545
3546bool ElementData::isEquivalent(const ElementData* other) const
3547{
3548 if (!other)
3549 return isEmpty();
3550
3551 unsigned len = length();
3552 if (len != other->length())
3553 return false;
3554
3555 for (unsigned i = 0; i < len; i++) {
3556 const Attribute* attribute = attributeItem(i);
3557 const Attribute* otherAttr = other->getAttributeItem(attribute->name());
3558 if (!otherAttr || attribute->value() != otherAttr->value())
3559 return false;
3560 }
3561
3562 return true;
3563}
3564
Torne (Richard Coles)e5249552013-05-15 11:35:13 +01003565size_t ElementData::getAttrIndex(Attr* attr) const
3566{
3567 // This relies on the fact that Attr's QualifiedName == the Attribute's name.
3568 for (unsigned i = 0; i < length(); ++i) {
3569 if (attributeItem(i)->name() == attr->qualifiedName())
3570 return i;
3571 }
3572 return notFound;
3573}
3574
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01003575size_t ElementData::getAttributeItemIndexSlowCase(const AtomicString& name, bool shouldIgnoreAttributeCase) const
3576{
3577 // Continue to checking case-insensitively and/or full namespaced names if necessary:
3578 for (unsigned i = 0; i < length(); ++i) {
3579 const Attribute* attribute = attributeItem(i);
3580 if (!attribute->name().hasPrefix()) {
3581 if (shouldIgnoreAttributeCase && equalIgnoringCase(name, attribute->localName()))
3582 return i;
3583 } else {
3584 // FIXME: Would be faster to do this comparison without calling toString, which
3585 // generates a temporary string by concatenation. But this branch is only reached
3586 // if the attribute name has a prefix, which is rare in HTML.
3587 if (equalPossiblyIgnoringCase(name, attribute->name().toString(), shouldIgnoreAttributeCase))
3588 return i;
3589 }
3590 }
3591 return notFound;
3592}
3593
3594Attribute* UniqueElementData::getAttributeItem(const QualifiedName& name)
3595{
3596 for (unsigned i = 0; i < length(); ++i) {
3597 if (m_attributeVector.at(i).name().matches(name))
3598 return &m_attributeVector.at(i);
3599 }
3600 return 0;
3601}
3602
3603Attribute* UniqueElementData::attributeItem(unsigned index)
3604{
3605 ASSERT_WITH_SECURITY_IMPLICATION(index < length());
3606 return &m_attributeVector.at(index);
3607}
3608
3609} // namespace WebCore