blob: 7d79c4509285dd9a56b10a3a931230cbccdaa47d [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"
Ben Murdochdf957042013-08-06 11:01:27 +010035#include "bindings/v8/ExceptionState.h"
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +010036#include "core/accessibility/AXObjectCache.h"
Ben Murdoch83750172013-07-24 10:36:59 +010037#include "core/animation/DocumentTimeline.h"
Torne (Richard Coles)c0e19a62013-08-30 15:15:11 +010038#include "core/animation/css/CSSAnimations.h"
Ben Murdoch591b9582013-07-10 11:41:44 +010039#include "core/css/CSSParser.h"
40#include "core/css/CSSStyleSheet.h"
41#include "core/css/CSSValuePool.h"
42#include "core/css/PropertySetCSSStyleDeclaration.h"
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +010043#include "core/css/StylePropertySet.h"
Torne (Richard Coles)81a51572013-05-13 16:52:28 +010044#include "core/css/resolver/StyleResolver.h"
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +010045#include "core/dom/Attr.h"
Ben Murdoch591b9582013-07-10 11:41:44 +010046#include "core/dom/Attribute.h"
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +010047#include "core/dom/ClientRect.h"
48#include "core/dom/ClientRectList.h"
Ben Murdoch83750172013-07-24 10:36:59 +010049#include "core/dom/CustomElement.h"
Ben Murdoche69819b2013-07-17 14:56:49 +010050#include "core/dom/CustomElementRegistrationContext.h"
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +010051#include "core/dom/DatasetDOMStringMap.h"
52#include "core/dom/Document.h"
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +010053#include "core/dom/DocumentSharedObjectPool.h"
54#include "core/dom/ElementRareData.h"
Torne (Richard Coles)06f816c2013-09-26 13:25:12 +010055#include "core/events/EventDispatcher.h"
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +010056#include "core/dom/ExceptionCode.h"
Torne (Richard Coles)06f816c2013-09-26 13:25:12 +010057#include "core/events/FocusEvent.h"
Torne (Richard Coles)f5e4ad52013-08-05 13:57:57 +010058#include "core/dom/FullscreenElementStack.h"
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +010059#include "core/dom/MutationObserverInterestGroup.h"
60#include "core/dom/MutationRecord.h"
61#include "core/dom/NamedNodeMap.h"
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +010062#include "core/dom/NodeRenderStyle.h"
63#include "core/dom/NodeRenderingContext.h"
Torne (Richard Coles)8abfc582013-09-12 12:10:38 +010064#include "core/dom/PostAttachCallbacks.h"
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +010065#include "core/dom/PseudoElement.h"
Ben Murdoch591b9582013-07-10 11:41:44 +010066#include "core/dom/ScriptableDocumentParser.h"
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +010067#include "core/dom/SelectorQuery.h"
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +010068#include "core/dom/Text.h"
Torne (Richard Coles)e5249552013-05-15 11:35:13 +010069#include "core/dom/shadow/InsertionPoint.h"
70#include "core/dom/shadow/ShadowRoot.h"
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +010071#include "core/editing/FrameSelection.h"
72#include "core/editing/TextIterator.h"
73#include "core/editing/htmlediting.h"
74#include "core/html/ClassList.h"
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +010075#include "core/html/HTMLCollection.h"
76#include "core/html/HTMLDocument.h"
77#include "core/html/HTMLElement.h"
78#include "core/html/HTMLFormControlsCollection.h"
79#include "core/html/HTMLFrameOwnerElement.h"
80#include "core/html/HTMLLabelElement.h"
81#include "core/html/HTMLOptionsCollection.h"
82#include "core/html/HTMLTableRowsCollection.h"
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +010083#include "core/html/parser/HTMLParserIdioms.h"
Ben Murdoch591b9582013-07-10 11:41:44 +010084#include "core/page/ContentSecurityPolicy.h"
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +010085#include "core/page/FocusController.h"
86#include "core/page/Frame.h"
87#include "core/page/FrameView.h"
88#include "core/page/Page.h"
89#include "core/page/PointerLockController.h"
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +010090#include "core/rendering/FlowThreadController.h"
91#include "core/rendering/RenderRegion.h"
92#include "core/rendering/RenderView.h"
93#include "core/rendering/RenderWidget.h"
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +010094#include "core/svg/SVGDocumentExtensions.h"
95#include "core/svg/SVGElement.h"
Torne (Richard Coles)93ac45c2013-05-29 14:40:20 +010096#include "wtf/BitVector.h"
Ben Murdoch591b9582013-07-10 11:41:44 +010097#include "wtf/HashFunctions.h"
Torne (Richard Coles)93ac45c2013-05-29 14:40:20 +010098#include "wtf/text/CString.h"
Ben Murdoch591b9582013-07-10 11:41:44 +010099#include "wtf/text/TextPosition.h"
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100100
101namespace WebCore {
102
103using namespace HTMLNames;
104using namespace XMLNames;
105
106static inline bool shouldIgnoreAttributeCase(const Element* e)
107{
Torne (Richard Coles)8abfc582013-09-12 12:10:38 +0100108 return e && e->document().isHTMLDocument() && e->isHTMLElement();
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100109}
Ben Murdoch591b9582013-07-10 11:41:44 +0100110
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100111class StyleResolverParentPusher {
112public:
113 StyleResolverParentPusher(Element* parent)
114 : m_parent(parent)
115 , m_pushedStyleResolver(0)
116 {
117 }
118 void push()
119 {
120 if (m_pushedStyleResolver)
121 return;
Torne (Richard Coles)8abfc582013-09-12 12:10:38 +0100122 m_pushedStyleResolver = m_parent->document().styleResolver();
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100123 m_pushedStyleResolver->pushParentElement(m_parent);
124 }
125 ~StyleResolverParentPusher()
126 {
127
128 if (!m_pushedStyleResolver)
129 return;
130
131 // This tells us that our pushed style selector is in a bad state,
132 // so we should just bail out in that scenario.
Torne (Richard Coles)8abfc582013-09-12 12:10:38 +0100133 ASSERT(m_pushedStyleResolver == m_parent->document().styleResolver());
134 if (m_pushedStyleResolver != m_parent->document().styleResolver())
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100135 return;
136
137 m_pushedStyleResolver->popParentElement(m_parent);
138 }
139
140private:
141 Element* m_parent;
142 StyleResolver* m_pushedStyleResolver;
143};
144
145typedef Vector<RefPtr<Attr> > AttrNodeList;
146typedef HashMap<Element*, OwnPtr<AttrNodeList> > AttrNodeListMap;
147
148static AttrNodeListMap& attrNodeListMap()
149{
150 DEFINE_STATIC_LOCAL(AttrNodeListMap, map, ());
151 return map;
152}
153
154static AttrNodeList* attrNodeListForElement(Element* element)
155{
156 if (!element->hasSyntheticAttrChildNodes())
157 return 0;
158 ASSERT(attrNodeListMap().contains(element));
159 return attrNodeListMap().get(element);
160}
161
162static AttrNodeList* ensureAttrNodeListForElement(Element* element)
163{
164 if (element->hasSyntheticAttrChildNodes()) {
165 ASSERT(attrNodeListMap().contains(element));
166 return attrNodeListMap().get(element);
167 }
168 ASSERT(!attrNodeListMap().contains(element));
169 element->setHasSyntheticAttrChildNodes(true);
170 AttrNodeListMap::AddResult result = attrNodeListMap().add(element, adoptPtr(new AttrNodeList));
171 return result.iterator->value.get();
172}
173
174static void removeAttrNodeListForElement(Element* element)
175{
176 ASSERT(element->hasSyntheticAttrChildNodes());
177 ASSERT(attrNodeListMap().contains(element));
178 attrNodeListMap().remove(element);
179 element->setHasSyntheticAttrChildNodes(false);
180}
181
182static Attr* findAttrNodeInList(AttrNodeList* attrNodeList, const QualifiedName& name)
183{
184 for (unsigned i = 0; i < attrNodeList->size(); ++i) {
185 if (attrNodeList->at(i)->qualifiedName() == name)
186 return attrNodeList->at(i).get();
187 }
188 return 0;
189}
190
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100191PassRefPtr<Element> Element::create(const QualifiedName& tagName, Document* document)
192{
193 return adoptRef(new Element(tagName, document, CreateElement));
194}
195
196Element::~Element()
197{
198#ifndef NDEBUG
Torne (Richard Coles)8abfc582013-09-12 12:10:38 +0100199 if (document().renderer()) {
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100200 // When the document is not destroyed, an element that was part of a named flow
201 // content nodes should have been removed from the content nodes collection
202 // and the inNamedFlow flag reset.
203 ASSERT(!inNamedFlow());
204 }
205#endif
206
Ben Murdoch591b9582013-07-10 11:41:44 +0100207 if (PropertySetCSSStyleDeclaration* cssomWrapper = inlineStyleCSSOMWrapper())
208 cssomWrapper->clearParentElement();
209
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100210 if (hasRareData()) {
211 ElementRareData* data = elementRareData();
212 data->setPseudoElement(BEFORE, 0);
213 data->setPseudoElement(AFTER, 0);
Ben Murdoche69819b2013-07-17 14:56:49 +0100214 data->setPseudoElement(BACKDROP, 0);
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100215 data->clearShadow();
Torne (Richard Coles)f5e4ad52013-08-05 13:57:57 +0100216
217 if (RuntimeEnabledFeatures::webAnimationsCSSEnabled()) {
218 if (ActiveAnimations* activeAnimations = data->activeAnimations())
219 activeAnimations->cssAnimations()->cancel();
220 }
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100221 }
222
Ben Murdoch83750172013-07-24 10:36:59 +0100223 if (isCustomElement())
224 CustomElement::wasDestroyed(this);
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100225
226 if (hasSyntheticAttrChildNodes())
227 detachAllAttrNodesFromElement();
228
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100229 if (hasPendingResources()) {
Torne (Richard Coles)8abfc582013-09-12 12:10:38 +0100230 document().accessSVGExtensions()->removeElementFromPendingResources(this);
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100231 ASSERT(!hasPendingResources());
232 }
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100233}
234
235inline ElementRareData* Element::elementRareData() const
236{
237 ASSERT(hasRareData());
238 return static_cast<ElementRareData*>(rareData());
239}
240
241inline ElementRareData* Element::ensureElementRareData()
242{
243 return static_cast<ElementRareData*>(ensureRareData());
244}
245
246void Element::clearTabIndexExplicitlyIfNeeded()
247{
248 if (hasRareData())
249 elementRareData()->clearTabIndexExplicitly();
250}
251
252void Element::setTabIndexExplicitly(short tabIndex)
253{
254 ensureElementRareData()->setTabIndexExplicitly(tabIndex);
255}
256
257bool Element::supportsFocus() const
258{
259 return hasRareData() && elementRareData()->tabIndexSetExplicitly();
260}
261
262short Element::tabIndex() const
263{
264 return hasRareData() ? elementRareData()->tabIndex() : 0;
265}
266
Torne (Richard Coles)521d96e2013-06-19 11:58:24 +0100267bool Element::rendererIsFocusable() const
268{
269 // Elements in canvas fallback content are not rendered, but they are allowed to be
270 // focusable as long as their canvas is displayed and visible.
271 if (isInCanvasSubtree()) {
272 const Element* e = this;
273 while (e && !e->hasLocalName(canvasTag))
274 e = e->parentElement();
275 ASSERT(e);
276 return e->renderer() && e->renderer()->style()->visibility() == VISIBLE;
277 }
278
279 // FIXME: These asserts should be in Node::isFocusable, but there are some
Ben Murdoche69819b2013-07-17 14:56:49 +0100280 // callsites like Document::setFocusedElement that would currently fail on
Torne (Richard Coles)521d96e2013-06-19 11:58:24 +0100281 // them. See crbug.com/251163
282 if (renderer()) {
283 ASSERT(!renderer()->needsLayout());
284 } else {
285 // We can't just use needsStyleRecalc() because if the node is in a
286 // display:none tree it might say it needs style recalc but the whole
287 // document is actually up to date.
Torne (Richard Coles)8abfc582013-09-12 12:10:38 +0100288 ASSERT(!document().childNeedsStyleRecalc());
Torne (Richard Coles)521d96e2013-06-19 11:58:24 +0100289 }
290
291 // FIXME: Even if we are not visible, we might have a child that is visible.
292 // Hyatt wants to fix that some day with a "has visible content" flag or the like.
293 if (!renderer() || renderer()->style()->visibility() != VISIBLE)
294 return false;
295
296 return true;
297}
298
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100299DEFINE_VIRTUAL_ATTRIBUTE_EVENT_LISTENER(Element, blur);
300DEFINE_VIRTUAL_ATTRIBUTE_EVENT_LISTENER(Element, error);
301DEFINE_VIRTUAL_ATTRIBUTE_EVENT_LISTENER(Element, focus);
302DEFINE_VIRTUAL_ATTRIBUTE_EVENT_LISTENER(Element, load);
303
304PassRefPtr<Node> Element::cloneNode(bool deep)
305{
306 return deep ? cloneElementWithChildren() : cloneElementWithoutChildren();
307}
308
309PassRefPtr<Element> Element::cloneElementWithChildren()
310{
311 RefPtr<Element> clone = cloneElementWithoutChildren();
312 cloneChildNodes(clone.get());
313 return clone.release();
314}
315
316PassRefPtr<Element> Element::cloneElementWithoutChildren()
317{
318 RefPtr<Element> clone = cloneElementWithoutAttributesAndChildren();
319 // This will catch HTML elements in the wrong namespace that are not correctly copied.
320 // This is a sanity check as HTML overloads some of the DOM methods.
321 ASSERT(isHTMLElement() == clone->isHTMLElement());
322
323 clone->cloneDataFromElement(*this);
324 return clone.release();
325}
326
327PassRefPtr<Element> Element::cloneElementWithoutAttributesAndChildren()
328{
Torne (Richard Coles)8abfc582013-09-12 12:10:38 +0100329 return document().createElement(tagQName(), false);
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100330}
331
332PassRefPtr<Attr> Element::detachAttribute(size_t index)
333{
334 ASSERT(elementData());
Torne (Richard Coles)e5249552013-05-15 11:35:13 +0100335 const Attribute* attribute = elementData()->attributeItem(index);
336 RefPtr<Attr> attrNode = attrIfExists(attribute->name());
337 if (attrNode)
338 detachAttrNodeAtIndex(attrNode.get(), index);
339 else {
340 attrNode = Attr::create(document(), attribute->name(), attribute->value());
341 removeAttributeInternal(index, NotInSynchronizationOfLazyAttribute);
342 }
343 return attrNode.release();
344}
345
346void Element::detachAttrNodeAtIndex(Attr* attr, size_t index)
347{
348 ASSERT(attr);
349 ASSERT(elementData());
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100350
351 const Attribute* attribute = elementData()->attributeItem(index);
352 ASSERT(attribute);
Torne (Richard Coles)e5249552013-05-15 11:35:13 +0100353 ASSERT(attribute->name() == attr->qualifiedName());
354 detachAttrNodeFromElementWithValue(attr, attribute->value());
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100355 removeAttributeInternal(index, NotInSynchronizationOfLazyAttribute);
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100356}
357
358void Element::removeAttribute(const QualifiedName& name)
359{
360 if (!elementData())
361 return;
362
363 size_t index = elementData()->getAttributeItemIndex(name);
Torne (Richard Coles)06f816c2013-09-26 13:25:12 +0100364 if (index == kNotFound)
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100365 return;
366
367 removeAttributeInternal(index, NotInSynchronizationOfLazyAttribute);
368}
369
370void Element::setBooleanAttribute(const QualifiedName& name, bool value)
371{
372 if (value)
373 setAttribute(name, emptyAtom);
374 else
375 removeAttribute(name);
376}
377
378NamedNodeMap* Element::attributes() const
379{
380 ElementRareData* rareData = const_cast<Element*>(this)->ensureElementRareData();
381 if (NamedNodeMap* attributeMap = rareData->attributeMap())
382 return attributeMap;
383
384 rareData->setAttributeMap(NamedNodeMap::create(const_cast<Element*>(this)));
385 return rareData->attributeMap();
386}
387
Ben Murdoch83750172013-07-24 10:36:59 +0100388ActiveAnimations* Element::activeAnimations() const
Torne (Richard Coles)81a51572013-05-13 16:52:28 +0100389{
Ben Murdoch83750172013-07-24 10:36:59 +0100390 if (hasActiveAnimations())
391 return elementRareData()->activeAnimations();
392 return 0;
Torne (Richard Coles)81a51572013-05-13 16:52:28 +0100393}
394
Ben Murdoch83750172013-07-24 10:36:59 +0100395ActiveAnimations* Element::ensureActiveAnimations()
Torne (Richard Coles)81a51572013-05-13 16:52:28 +0100396{
Ben Murdoch83750172013-07-24 10:36:59 +0100397 ElementRareData* rareData = ensureElementRareData();
398 if (!elementRareData()->activeAnimations())
399 rareData->setActiveAnimations(adoptPtr(new ActiveAnimations()));
400 return rareData->activeAnimations();
Torne (Richard Coles)81a51572013-05-13 16:52:28 +0100401}
402
403bool Element::hasActiveAnimations() const
404{
Ben Murdoch83750172013-07-24 10:36:59 +0100405 if (!RuntimeEnabledFeatures::webAnimationsEnabled())
406 return false;
Torne (Richard Coles)81a51572013-05-13 16:52:28 +0100407
Ben Murdoch83750172013-07-24 10:36:59 +0100408 if (!hasRareData())
409 return false;
410
411 ActiveAnimations* activeAnimations = elementRareData()->activeAnimations();
412 return activeAnimations && !activeAnimations->isEmpty();
Torne (Richard Coles)81a51572013-05-13 16:52:28 +0100413}
414
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100415Node::NodeType Element::nodeType() const
416{
417 return ELEMENT_NODE;
418}
419
420bool Element::hasAttribute(const QualifiedName& name) const
421{
422 return hasAttributeNS(name.namespaceURI(), name.localName());
423}
424
425void Element::synchronizeAllAttributes() const
426{
427 if (!elementData())
428 return;
429 if (elementData()->m_styleAttributeIsDirty) {
430 ASSERT(isStyledElement());
Ben Murdoch591b9582013-07-10 11:41:44 +0100431 synchronizeStyleAttributeInternal();
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100432 }
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100433 if (elementData()->m_animatedSVGAttributesAreDirty) {
434 ASSERT(isSVGElement());
435 toSVGElement(this)->synchronizeAnimatedSVGAttribute(anyQName());
436 }
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100437}
438
439inline void Element::synchronizeAttribute(const QualifiedName& name) const
440{
441 if (!elementData())
442 return;
443 if (UNLIKELY(name == styleAttr && elementData()->m_styleAttributeIsDirty)) {
444 ASSERT(isStyledElement());
Ben Murdoch591b9582013-07-10 11:41:44 +0100445 synchronizeStyleAttributeInternal();
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100446 return;
447 }
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100448 if (UNLIKELY(elementData()->m_animatedSVGAttributesAreDirty)) {
449 ASSERT(isSVGElement());
450 toSVGElement(this)->synchronizeAnimatedSVGAttribute(name);
451 }
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100452}
453
454inline void Element::synchronizeAttribute(const AtomicString& localName) const
455{
456 // This version of synchronizeAttribute() is streamlined for the case where you don't have a full QualifiedName,
457 // e.g when called from DOM API.
458 if (!elementData())
459 return;
460 if (elementData()->m_styleAttributeIsDirty && equalPossiblyIgnoringCase(localName, styleAttr.localName(), shouldIgnoreAttributeCase(this))) {
461 ASSERT(isStyledElement());
Ben Murdoch591b9582013-07-10 11:41:44 +0100462 synchronizeStyleAttributeInternal();
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100463 return;
464 }
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100465 if (elementData()->m_animatedSVGAttributesAreDirty) {
466 // We're not passing a namespace argument on purpose. SVGNames::*Attr are defined w/o namespaces as well.
467 ASSERT(isSVGElement());
468 static_cast<const SVGElement*>(this)->synchronizeAnimatedSVGAttribute(QualifiedName(nullAtom, localName, nullAtom));
469 }
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100470}
471
472const AtomicString& Element::getAttribute(const QualifiedName& name) const
473{
474 if (!elementData())
475 return nullAtom;
476 synchronizeAttribute(name);
477 if (const Attribute* attribute = getAttributeItem(name))
478 return attribute->value();
479 return nullAtom;
480}
481
Ben Murdoch591b9582013-07-10 11:41:44 +0100482void Element::scrollIntoView(bool alignToTop)
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100483{
Torne (Richard Coles)8abfc582013-09-12 12:10:38 +0100484 document().updateLayoutIgnorePendingStylesheets();
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100485
486 if (!renderer())
487 return;
488
489 LayoutRect bounds = boundingBox();
490 // Align to the top / bottom and to the closest edge.
491 if (alignToTop)
492 renderer()->scrollRectToVisible(bounds, ScrollAlignment::alignToEdgeIfNeeded, ScrollAlignment::alignTopAlways);
493 else
494 renderer()->scrollRectToVisible(bounds, ScrollAlignment::alignToEdgeIfNeeded, ScrollAlignment::alignBottomAlways);
495}
496
497void Element::scrollIntoViewIfNeeded(bool centerIfNeeded)
498{
Torne (Richard Coles)8abfc582013-09-12 12:10:38 +0100499 document().updateLayoutIgnorePendingStylesheets();
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100500
501 if (!renderer())
502 return;
503
504 LayoutRect bounds = boundingBox();
505 if (centerIfNeeded)
506 renderer()->scrollRectToVisible(bounds, ScrollAlignment::alignCenterIfNeeded, ScrollAlignment::alignCenterIfNeeded);
507 else
508 renderer()->scrollRectToVisible(bounds, ScrollAlignment::alignToEdgeIfNeeded, ScrollAlignment::alignToEdgeIfNeeded);
509}
510
511void Element::scrollByUnits(int units, ScrollGranularity granularity)
512{
Torne (Richard Coles)8abfc582013-09-12 12:10:38 +0100513 document().updateLayoutIgnorePendingStylesheets();
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100514
515 if (!renderer())
516 return;
517
518 if (!renderer()->hasOverflowClip())
519 return;
520
521 ScrollDirection direction = ScrollDown;
522 if (units < 0) {
523 direction = ScrollUp;
524 units = -units;
525 }
526 Node* stopNode = this;
527 toRenderBox(renderer())->scroll(direction, granularity, units, &stopNode);
528}
529
530void Element::scrollByLines(int lines)
531{
532 scrollByUnits(lines, ScrollByLine);
533}
534
535void Element::scrollByPages(int pages)
536{
537 scrollByUnits(pages, ScrollByPage);
538}
539
540static float localZoomForRenderer(RenderObject* renderer)
541{
542 // FIXME: This does the wrong thing if two opposing zooms are in effect and canceled each
543 // other out, but the alternative is that we'd have to crawl up the whole render tree every
544 // time (or store an additional bit in the RenderStyle to indicate that a zoom was specified).
545 float zoomFactor = 1;
546 if (renderer->style()->effectiveZoom() != 1) {
547 // Need to find the nearest enclosing RenderObject that set up
548 // a differing zoom, and then we divide our result by it to eliminate the zoom.
549 RenderObject* prev = renderer;
550 for (RenderObject* curr = prev->parent(); curr; curr = curr->parent()) {
551 if (curr->style()->effectiveZoom() != prev->style()->effectiveZoom()) {
552 zoomFactor = prev->style()->zoom();
553 break;
554 }
555 prev = curr;
556 }
557 if (prev->isRenderView())
558 zoomFactor = prev->style()->zoom();
559 }
560 return zoomFactor;
561}
562
563static int adjustForLocalZoom(LayoutUnit value, RenderObject* renderer)
564{
565 float zoomFactor = localZoomForRenderer(renderer);
566 if (zoomFactor == 1)
567 return value;
568 return lroundf(value / zoomFactor);
569}
570
571int Element::offsetLeft()
572{
Torne (Richard Coles)8abfc582013-09-12 12:10:38 +0100573 document().partialUpdateLayoutIgnorePendingStylesheets(this);
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100574 if (RenderBoxModelObject* renderer = renderBoxModelObject())
575 return adjustForLocalZoom(renderer->pixelSnappedOffsetLeft(), renderer);
576 return 0;
577}
578
579int Element::offsetTop()
580{
Torne (Richard Coles)8abfc582013-09-12 12:10:38 +0100581 document().partialUpdateLayoutIgnorePendingStylesheets(this);
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100582 if (RenderBoxModelObject* renderer = renderBoxModelObject())
583 return adjustForLocalZoom(renderer->pixelSnappedOffsetTop(), renderer);
584 return 0;
585}
586
587int Element::offsetWidth()
588{
Torne (Richard Coles)8abfc582013-09-12 12:10:38 +0100589 document().updateStyleForNodeIfNeeded(this);
Ben Murdoch591b9582013-07-10 11:41:44 +0100590
591 if (RenderBox* renderer = renderBox()) {
592 if (!renderer->requiresLayoutToDetermineWidth())
593 return adjustLayoutUnitForAbsoluteZoom(renderer->fixedOffsetWidth(), renderer).round();
594 }
595
Torne (Richard Coles)8abfc582013-09-12 12:10:38 +0100596 document().partialUpdateLayoutIgnorePendingStylesheets(this);
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100597 if (RenderBoxModelObject* renderer = renderBoxModelObject())
598 return adjustLayoutUnitForAbsoluteZoom(renderer->pixelSnappedOffsetWidth(), renderer).round();
599 return 0;
600}
601
602int Element::offsetHeight()
603{
Torne (Richard Coles)8abfc582013-09-12 12:10:38 +0100604 document().partialUpdateLayoutIgnorePendingStylesheets(this);
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100605 if (RenderBoxModelObject* renderer = renderBoxModelObject())
606 return adjustLayoutUnitForAbsoluteZoom(renderer->pixelSnappedOffsetHeight(), renderer).round();
607 return 0;
608}
609
610Element* Element::bindingsOffsetParent()
611{
612 Element* element = offsetParent();
613 if (!element || !element->isInShadowTree())
614 return element;
Torne (Richard Coles)521d96e2013-06-19 11:58:24 +0100615 return element->containingShadowRoot()->shouldExposeToBindings() ? element : 0;
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100616}
617
618Element* Element::offsetParent()
619{
Torne (Richard Coles)8abfc582013-09-12 12:10:38 +0100620 document().updateLayoutIgnorePendingStylesheets();
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100621 if (RenderObject* renderer = this->renderer())
622 return renderer->offsetParent();
623 return 0;
624}
625
626int Element::clientLeft()
627{
Torne (Richard Coles)8abfc582013-09-12 12:10:38 +0100628 document().updateLayoutIgnorePendingStylesheets();
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100629
630 if (RenderBox* renderer = renderBox())
631 return adjustForAbsoluteZoom(roundToInt(renderer->clientLeft()), renderer);
632 return 0;
633}
634
635int Element::clientTop()
636{
Torne (Richard Coles)8abfc582013-09-12 12:10:38 +0100637 document().updateLayoutIgnorePendingStylesheets();
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100638
639 if (RenderBox* renderer = renderBox())
640 return adjustForAbsoluteZoom(roundToInt(renderer->clientTop()), renderer);
641 return 0;
642}
643
644int Element::clientWidth()
645{
Torne (Richard Coles)8abfc582013-09-12 12:10:38 +0100646 document().updateLayoutIgnorePendingStylesheets();
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100647
648 // When in strict mode, clientWidth for the document element should return the width of the containing frame.
649 // When in quirks mode, clientWidth for the body element should return the width of the containing frame.
Torne (Richard Coles)8abfc582013-09-12 12:10:38 +0100650 bool inQuirksMode = document().inQuirksMode();
651 if ((!inQuirksMode && document().documentElement() == this)
652 || (inQuirksMode && isHTMLElement() && document().body() == this)) {
653 if (FrameView* view = document().view()) {
654 if (RenderView* renderView = document().renderView())
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100655 return adjustForAbsoluteZoom(view->layoutWidth(), renderView);
656 }
657 }
Ben Murdoch591b9582013-07-10 11:41:44 +0100658
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100659 if (RenderBox* renderer = renderBox())
660 return adjustLayoutUnitForAbsoluteZoom(renderer->pixelSnappedClientWidth(), renderer).round();
661 return 0;
662}
663
664int Element::clientHeight()
665{
Torne (Richard Coles)8abfc582013-09-12 12:10:38 +0100666 document().updateLayoutIgnorePendingStylesheets();
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100667
668 // When in strict mode, clientHeight for the document element should return the height of the containing frame.
669 // When in quirks mode, clientHeight for the body element should return the height of the containing frame.
Torne (Richard Coles)8abfc582013-09-12 12:10:38 +0100670 bool inQuirksMode = document().inQuirksMode();
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100671
Torne (Richard Coles)8abfc582013-09-12 12:10:38 +0100672 if ((!inQuirksMode && document().documentElement() == this)
673 || (inQuirksMode && isHTMLElement() && document().body() == this)) {
674 if (FrameView* view = document().view()) {
675 if (RenderView* renderView = document().renderView())
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100676 return adjustForAbsoluteZoom(view->layoutHeight(), renderView);
677 }
678 }
Ben Murdoch591b9582013-07-10 11:41:44 +0100679
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100680 if (RenderBox* renderer = renderBox())
681 return adjustLayoutUnitForAbsoluteZoom(renderer->pixelSnappedClientHeight(), renderer).round();
682 return 0;
683}
684
685int Element::scrollLeft()
686{
Torne (Richard Coles)8abfc582013-09-12 12:10:38 +0100687 document().updateLayoutIgnorePendingStylesheets();
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100688 if (RenderBox* rend = renderBox())
689 return adjustForAbsoluteZoom(rend->scrollLeft(), rend);
690 return 0;
691}
692
693int Element::scrollTop()
694{
Torne (Richard Coles)8abfc582013-09-12 12:10:38 +0100695 document().updateLayoutIgnorePendingStylesheets();
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100696 if (RenderBox* rend = renderBox())
697 return adjustForAbsoluteZoom(rend->scrollTop(), rend);
698 return 0;
699}
700
701void Element::setScrollLeft(int newLeft)
702{
Torne (Richard Coles)8abfc582013-09-12 12:10:38 +0100703 document().updateLayoutIgnorePendingStylesheets();
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100704 if (RenderBox* rend = renderBox())
705 rend->setScrollLeft(static_cast<int>(newLeft * rend->style()->effectiveZoom()));
706}
707
708void Element::setScrollTop(int newTop)
709{
Torne (Richard Coles)8abfc582013-09-12 12:10:38 +0100710 document().updateLayoutIgnorePendingStylesheets();
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100711 if (RenderBox* rend = renderBox())
712 rend->setScrollTop(static_cast<int>(newTop * rend->style()->effectiveZoom()));
713}
714
715int Element::scrollWidth()
716{
Torne (Richard Coles)8abfc582013-09-12 12:10:38 +0100717 document().updateLayoutIgnorePendingStylesheets();
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100718 if (RenderBox* rend = renderBox())
719 return adjustForAbsoluteZoom(rend->scrollWidth(), rend);
720 return 0;
721}
722
723int Element::scrollHeight()
724{
Torne (Richard Coles)8abfc582013-09-12 12:10:38 +0100725 document().updateLayoutIgnorePendingStylesheets();
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100726 if (RenderBox* rend = renderBox())
727 return adjustForAbsoluteZoom(rend->scrollHeight(), rend);
728 return 0;
729}
730
731IntRect Element::boundsInRootViewSpace()
732{
Torne (Richard Coles)8abfc582013-09-12 12:10:38 +0100733 document().updateLayoutIgnorePendingStylesheets();
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100734
Torne (Richard Coles)8abfc582013-09-12 12:10:38 +0100735 FrameView* view = document().view();
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100736 if (!view)
737 return IntRect();
738
739 Vector<FloatQuad> quads;
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100740 if (isSVGElement() && renderer()) {
741 // Get the bounding rectangle from the SVG model.
742 SVGElement* svgElement = toSVGElement(this);
743 FloatRect localRect;
744 if (svgElement->getBoundingBox(localRect))
745 quads.append(renderer()->localToAbsoluteQuad(localRect));
Torne (Richard Coles)93ac45c2013-05-29 14:40:20 +0100746 } else {
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100747 // Get the bounding rectangle from the box model.
748 if (renderBoxModelObject())
749 renderBoxModelObject()->absoluteQuads(quads);
750 }
751
752 if (quads.isEmpty())
753 return IntRect();
754
755 IntRect result = quads[0].enclosingBoundingBox();
756 for (size_t i = 1; i < quads.size(); ++i)
757 result.unite(quads[i].enclosingBoundingBox());
758
759 result = view->contentsToRootView(result);
760 return result;
761}
762
763PassRefPtr<ClientRectList> Element::getClientRects()
764{
Torne (Richard Coles)8abfc582013-09-12 12:10:38 +0100765 document().updateLayoutIgnorePendingStylesheets();
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100766
767 RenderBoxModelObject* renderBoxModelObject = this->renderBoxModelObject();
768 if (!renderBoxModelObject)
769 return ClientRectList::create();
770
771 // FIXME: Handle SVG elements.
772 // FIXME: Handle table/inline-table with a caption.
773
774 Vector<FloatQuad> quads;
775 renderBoxModelObject->absoluteQuads(quads);
Torne (Richard Coles)8abfc582013-09-12 12:10:38 +0100776 document().adjustFloatQuadsForScrollAndAbsoluteZoom(quads, renderBoxModelObject);
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100777 return ClientRectList::create(quads);
778}
779
780PassRefPtr<ClientRect> Element::getBoundingClientRect()
781{
Torne (Richard Coles)8abfc582013-09-12 12:10:38 +0100782 document().updateLayoutIgnorePendingStylesheets();
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100783
784 Vector<FloatQuad> quads;
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100785 if (isSVGElement() && renderer() && !renderer()->isSVGRoot()) {
786 // Get the bounding rectangle from the SVG model.
787 SVGElement* svgElement = toSVGElement(this);
788 FloatRect localRect;
789 if (svgElement->getBoundingBox(localRect))
790 quads.append(renderer()->localToAbsoluteQuad(localRect));
Torne (Richard Coles)93ac45c2013-05-29 14:40:20 +0100791 } else {
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100792 // Get the bounding rectangle from the box model.
793 if (renderBoxModelObject())
794 renderBoxModelObject()->absoluteQuads(quads);
795 }
796
797 if (quads.isEmpty())
798 return ClientRect::create();
799
800 FloatRect result = quads[0].boundingBox();
801 for (size_t i = 1; i < quads.size(); ++i)
802 result.unite(quads[i].boundingBox());
803
Torne (Richard Coles)8abfc582013-09-12 12:10:38 +0100804 document().adjustFloatRectForScrollAndAbsoluteZoom(result, renderer());
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100805 return ClientRect::create(result);
806}
Ben Murdoch591b9582013-07-10 11:41:44 +0100807
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100808IntRect Element::screenRect() const
809{
810 if (!renderer())
811 return IntRect();
812 // FIXME: this should probably respect transforms
Torne (Richard Coles)8abfc582013-09-12 12:10:38 +0100813 return document().view()->contentsToScreen(renderer()->absoluteBoundingBoxRectIgnoringTransforms());
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100814}
815
816const AtomicString& Element::getAttribute(const AtomicString& localName) const
817{
818 if (!elementData())
819 return nullAtom;
820 synchronizeAttribute(localName);
821 if (const Attribute* attribute = elementData()->getAttributeItem(localName, shouldIgnoreAttributeCase(this)))
822 return attribute->value();
823 return nullAtom;
824}
825
826const AtomicString& Element::getAttributeNS(const AtomicString& namespaceURI, const AtomicString& localName) const
827{
828 return getAttribute(QualifiedName(nullAtom, localName, namespaceURI));
829}
830
Ben Murdochdf957042013-08-06 11:01:27 +0100831void Element::setAttribute(const AtomicString& localName, const AtomicString& value, ExceptionState& es)
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100832{
833 if (!Document::isValidName(localName)) {
Torne (Richard Coles)06f816c2013-09-26 13:25:12 +0100834 es.throwUninformativeAndGenericDOMException(InvalidCharacterError);
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100835 return;
836 }
837
838 synchronizeAttribute(localName);
839 const AtomicString& caseAdjustedLocalName = shouldIgnoreAttributeCase(this) ? localName.lower() : localName;
840
Torne (Richard Coles)06f816c2013-09-26 13:25:12 +0100841 size_t index = elementData() ? elementData()->getAttributeItemIndex(caseAdjustedLocalName, false) : kNotFound;
842 const QualifiedName& qName = index != kNotFound ? attributeItem(index)->name() : QualifiedName(nullAtom, caseAdjustedLocalName, nullAtom);
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100843 setAttributeInternal(index, qName, value, NotInSynchronizationOfLazyAttribute);
844}
845
846void Element::setAttribute(const QualifiedName& name, const AtomicString& value)
847{
848 synchronizeAttribute(name);
Torne (Richard Coles)06f816c2013-09-26 13:25:12 +0100849 size_t index = elementData() ? elementData()->getAttributeItemIndex(name) : kNotFound;
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100850 setAttributeInternal(index, name, value, NotInSynchronizationOfLazyAttribute);
851}
852
853void Element::setSynchronizedLazyAttribute(const QualifiedName& name, const AtomicString& value)
854{
Torne (Richard Coles)06f816c2013-09-26 13:25:12 +0100855 size_t index = elementData() ? elementData()->getAttributeItemIndex(name) : kNotFound;
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100856 setAttributeInternal(index, name, value, InSynchronizationOfLazyAttribute);
857}
858
859inline void Element::setAttributeInternal(size_t index, const QualifiedName& name, const AtomicString& newValue, SynchronizationOfLazyAttribute inSynchronizationOfLazyAttribute)
860{
861 if (newValue.isNull()) {
Torne (Richard Coles)06f816c2013-09-26 13:25:12 +0100862 if (index != kNotFound)
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100863 removeAttributeInternal(index, inSynchronizationOfLazyAttribute);
864 return;
865 }
866
Torne (Richard Coles)06f816c2013-09-26 13:25:12 +0100867 if (index == kNotFound) {
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100868 addAttributeInternal(name, newValue, inSynchronizationOfLazyAttribute);
869 return;
870 }
871
Torne (Richard Coles)8abfc582013-09-12 12:10:38 +0100872 QualifiedName existingAttributeName = attributeItem(index)->name();
873
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100874 if (!inSynchronizationOfLazyAttribute)
Torne (Richard Coles)8abfc582013-09-12 12:10:38 +0100875 willModifyAttribute(existingAttributeName, attributeItem(index)->value(), newValue);
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100876
877 if (newValue != attributeItem(index)->value()) {
878 // If there is an Attr node hooked to this attribute, the Attr::setValue() call below
879 // will write into the ElementData.
880 // FIXME: Refactor this so it makes some sense.
Torne (Richard Coles)8abfc582013-09-12 12:10:38 +0100881 if (RefPtr<Attr> attrNode = inSynchronizationOfLazyAttribute ? 0 : attrIfExists(existingAttributeName))
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100882 attrNode->setValue(newValue);
883 else
884 ensureUniqueElementData()->attributeItem(index)->setValue(newValue);
885 }
886
887 if (!inSynchronizationOfLazyAttribute)
Torne (Richard Coles)8abfc582013-09-12 12:10:38 +0100888 didModifyAttribute(existingAttributeName, newValue);
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100889}
890
891static inline AtomicString makeIdForStyleResolution(const AtomicString& value, bool inQuirksMode)
892{
893 if (inQuirksMode)
894 return value.lower();
895 return value;
896}
897
Ben Murdoch7757ec22013-07-23 11:17:36 +0100898static bool checkNeedsStyleInvalidationForIdChange(const AtomicString& oldId, const AtomicString& newId, const RuleFeatureSet& features)
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100899{
900 ASSERT(newId != oldId);
Ben Murdoch7757ec22013-07-23 11:17:36 +0100901 if (!oldId.isEmpty() && features.hasSelectorForId(oldId))
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100902 return true;
Ben Murdoch7757ec22013-07-23 11:17:36 +0100903 if (!newId.isEmpty() && features.hasSelectorForId(newId))
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100904 return true;
905 return false;
906}
907
Ben Murdoch591b9582013-07-10 11:41:44 +0100908void Element::attributeChanged(const QualifiedName& name, const AtomicString& newValue, AttributeModificationReason reason)
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100909{
910 if (ElementShadow* parentElementShadow = shadowOfParentForDistribution(this)) {
911 if (shouldInvalidateDistributionWhenAttributeChanged(parentElementShadow, name, newValue))
Torne (Richard Coles)f5e4ad52013-08-05 13:57:57 +0100912 parentElementShadow->setNeedsDistributionRecalc();
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100913 }
914
915 parseAttribute(name, newValue);
916
Torne (Richard Coles)8abfc582013-09-12 12:10:38 +0100917 document().incDOMTreeVersion();
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100918
Torne (Richard Coles)8abfc582013-09-12 12:10:38 +0100919 StyleResolver* styleResolver = document().styleResolverIfExists();
Ben Murdoche69819b2013-07-17 14:56:49 +0100920 bool testShouldInvalidateStyle = attached() && styleResolver && styleChangeType() < SubtreeStyleChange;
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100921 bool shouldInvalidateStyle = false;
922
Ben Murdoch591b9582013-07-10 11:41:44 +0100923 if (isStyledElement() && name == styleAttr) {
924 styleAttributeChanged(newValue, reason);
925 } else if (isStyledElement() && isPresentationAttribute(name)) {
926 elementData()->m_presentationAttributeStyleIsDirty = true;
Ben Murdoche69819b2013-07-17 14:56:49 +0100927 setNeedsStyleRecalc(LocalStyleChange);
Ben Murdoch591b9582013-07-10 11:41:44 +0100928 }
929
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100930 if (isIdAttributeName(name)) {
931 AtomicString oldId = elementData()->idForStyleResolution();
Torne (Richard Coles)8abfc582013-09-12 12:10:38 +0100932 AtomicString newId = makeIdForStyleResolution(newValue, document().inQuirksMode());
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100933 if (newId != oldId) {
934 elementData()->setIdForStyleResolution(newId);
Ben Murdoch7757ec22013-07-23 11:17:36 +0100935 shouldInvalidateStyle = testShouldInvalidateStyle && checkNeedsStyleInvalidationForIdChange(oldId, newId, styleResolver->ruleFeatureSet());
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100936 }
Ben Murdoch591b9582013-07-10 11:41:44 +0100937 } else if (name == classAttr) {
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100938 classAttributeChanged(newValue);
Ben Murdoch591b9582013-07-10 11:41:44 +0100939 } else if (name == HTMLNames::nameAttr) {
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100940 setHasName(!newValue.isNull());
Ben Murdoch591b9582013-07-10 11:41:44 +0100941 } else if (name == HTMLNames::pseudoAttr) {
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100942 shouldInvalidateStyle |= testShouldInvalidateStyle && isInShadowTree();
Ben Murdoch591b9582013-07-10 11:41:44 +0100943 }
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100944
945 invalidateNodeListCachesInAncestors(&name, this);
946
947 // If there is currently no StyleResolver, we can't be sure that this attribute change won't affect style.
948 shouldInvalidateStyle |= !styleResolver;
949
950 if (shouldInvalidateStyle)
951 setNeedsStyleRecalc();
952
Torne (Richard Coles)8abfc582013-09-12 12:10:38 +0100953 if (AXObjectCache* cache = document().existingAXObjectCache())
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100954 cache->handleAttributeChanged(name, this);
955}
956
957inline void Element::attributeChangedFromParserOrByCloning(const QualifiedName& name, const AtomicString& newValue, AttributeModificationReason reason)
958{
Ben Murdoche69819b2013-07-17 14:56:49 +0100959 if (name == isAttr)
Torne (Richard Coles)e1f1df52013-08-23 16:39:30 +0100960 CustomElementRegistrationContext::setTypeExtension(this, newValue, reason == ModifiedDirectly ? CustomElementRegistrationContext::CreatedByParser : CustomElementRegistrationContext::NotCreatedByParser);
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100961 attributeChanged(name, newValue, reason);
962}
963
964template <typename CharacterType>
965static inline bool classStringHasClassName(const CharacterType* characters, unsigned length)
966{
967 ASSERT(length > 0);
968
969 unsigned i = 0;
970 do {
Torne (Richard Coles)06f816c2013-09-26 13:25:12 +0100971 if (isNotHTMLSpace<CharacterType>(characters[i]))
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100972 break;
973 ++i;
974 } while (i < length);
975
976 return i < length;
977}
978
979static inline bool classStringHasClassName(const AtomicString& newClassString)
980{
981 unsigned length = newClassString.length();
982
983 if (!length)
984 return false;
985
986 if (newClassString.is8Bit())
987 return classStringHasClassName(newClassString.characters8(), length);
988 return classStringHasClassName(newClassString.characters16(), length);
989}
990
991template<typename Checker>
992static bool checkSelectorForClassChange(const SpaceSplitString& changedClasses, const Checker& checker)
993{
994 unsigned changedSize = changedClasses.size();
995 for (unsigned i = 0; i < changedSize; ++i) {
996 if (checker.hasSelectorForClass(changedClasses[i]))
997 return true;
998 }
999 return false;
1000}
1001
1002template<typename Checker>
1003static bool checkSelectorForClassChange(const SpaceSplitString& oldClasses, const SpaceSplitString& newClasses, const Checker& checker)
1004{
1005 unsigned oldSize = oldClasses.size();
1006 if (!oldSize)
1007 return checkSelectorForClassChange(newClasses, checker);
1008 BitVector remainingClassBits;
1009 remainingClassBits.ensureSize(oldSize);
1010 // Class vectors tend to be very short. This is faster than using a hash table.
1011 unsigned newSize = newClasses.size();
1012 for (unsigned i = 0; i < newSize; ++i) {
1013 for (unsigned j = 0; j < oldSize; ++j) {
1014 if (newClasses[i] == oldClasses[j]) {
1015 remainingClassBits.quickSet(j);
1016 continue;
1017 }
1018 }
1019 if (checker.hasSelectorForClass(newClasses[i]))
1020 return true;
1021 }
1022 for (unsigned i = 0; i < oldSize; ++i) {
1023 // If the bit is not set the the corresponding class has been removed.
1024 if (remainingClassBits.quickGet(i))
1025 continue;
1026 if (checker.hasSelectorForClass(oldClasses[i]))
1027 return true;
1028 }
1029 return false;
1030}
1031
1032void Element::classAttributeChanged(const AtomicString& newClassString)
1033{
Torne (Richard Coles)8abfc582013-09-12 12:10:38 +01001034 StyleResolver* styleResolver = document().styleResolverIfExists();
Ben Murdoche69819b2013-07-17 14:56:49 +01001035 bool testShouldInvalidateStyle = attached() && styleResolver && styleChangeType() < SubtreeStyleChange;
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001036 bool shouldInvalidateStyle = false;
1037
1038 if (classStringHasClassName(newClassString)) {
Torne (Richard Coles)8abfc582013-09-12 12:10:38 +01001039 const bool shouldFoldCase = document().inQuirksMode();
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001040 const SpaceSplitString oldClasses = elementData()->classNames();
1041 elementData()->setClass(newClassString, shouldFoldCase);
1042 const SpaceSplitString& newClasses = elementData()->classNames();
Ben Murdoch7757ec22013-07-23 11:17:36 +01001043 shouldInvalidateStyle = testShouldInvalidateStyle && checkSelectorForClassChange(oldClasses, newClasses, styleResolver->ruleFeatureSet());
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001044 } else {
1045 const SpaceSplitString& oldClasses = elementData()->classNames();
Ben Murdoch7757ec22013-07-23 11:17:36 +01001046 shouldInvalidateStyle = testShouldInvalidateStyle && checkSelectorForClassChange(oldClasses, styleResolver->ruleFeatureSet());
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001047 elementData()->clearClass();
1048 }
1049
1050 if (hasRareData())
1051 elementRareData()->clearClassListValueForQuirksMode();
1052
1053 if (shouldInvalidateStyle)
1054 setNeedsStyleRecalc();
1055}
1056
1057bool Element::shouldInvalidateDistributionWhenAttributeChanged(ElementShadow* elementShadow, const QualifiedName& name, const AtomicString& newValue)
1058{
1059 ASSERT(elementShadow);
Torne (Richard Coles)e1f1df52013-08-23 16:39:30 +01001060 const SelectRuleFeatureSet& featureSet = elementShadow->ensureSelectFeatureSet();
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001061
1062 if (isIdAttributeName(name)) {
1063 AtomicString oldId = elementData()->idForStyleResolution();
Torne (Richard Coles)8abfc582013-09-12 12:10:38 +01001064 AtomicString newId = makeIdForStyleResolution(newValue, document().inQuirksMode());
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001065 if (newId != oldId) {
1066 if (!oldId.isEmpty() && featureSet.hasSelectorForId(oldId))
1067 return true;
1068 if (!newId.isEmpty() && featureSet.hasSelectorForId(newId))
1069 return true;
1070 }
1071 }
1072
1073 if (name == HTMLNames::classAttr) {
1074 const AtomicString& newClassString = newValue;
1075 if (classStringHasClassName(newClassString)) {
Torne (Richard Coles)8abfc582013-09-12 12:10:38 +01001076 const bool shouldFoldCase = document().inQuirksMode();
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001077 const SpaceSplitString& oldClasses = elementData()->classNames();
1078 const SpaceSplitString newClasses(newClassString, shouldFoldCase);
1079 if (checkSelectorForClassChange(oldClasses, newClasses, featureSet))
1080 return true;
1081 } else {
1082 const SpaceSplitString& oldClasses = elementData()->classNames();
1083 if (checkSelectorForClassChange(oldClasses, featureSet))
1084 return true;
1085 }
1086 }
1087
1088 return featureSet.hasSelectorForAttribute(name.localName());
1089}
1090
1091// Returns true is the given attribute is an event handler.
1092// We consider an event handler any attribute that begins with "on".
1093// It is a simple solution that has the advantage of not requiring any
1094// code or configuration change if a new event handler is defined.
1095
1096static inline bool isEventHandlerAttribute(const Attribute& attribute)
1097{
1098 return attribute.name().namespaceURI().isNull() && attribute.name().localName().startsWith("on");
1099}
1100
1101bool Element::isJavaScriptURLAttribute(const Attribute& attribute) const
1102{
1103 return isURLAttribute(attribute) && protocolIsJavaScript(stripLeadingAndTrailingHTMLSpaces(attribute.value()));
1104}
1105
1106void Element::stripScriptingAttributes(Vector<Attribute>& attributeVector) const
1107{
1108 size_t destination = 0;
1109 for (size_t source = 0; source < attributeVector.size(); ++source) {
1110 if (isEventHandlerAttribute(attributeVector[source])
1111 || isJavaScriptURLAttribute(attributeVector[source])
1112 || isHTMLContentAttribute(attributeVector[source]))
1113 continue;
1114
1115 if (source != destination)
1116 attributeVector[destination] = attributeVector[source];
1117
1118 ++destination;
1119 }
1120 attributeVector.shrink(destination);
1121}
1122
1123void Element::parserSetAttributes(const Vector<Attribute>& attributeVector)
1124{
1125 ASSERT(!inDocument());
1126 ASSERT(!parentNode());
1127 ASSERT(!m_elementData);
1128
1129 if (attributeVector.isEmpty())
1130 return;
1131
Torne (Richard Coles)8abfc582013-09-12 12:10:38 +01001132 if (document().sharedObjectPool())
1133 m_elementData = document().sharedObjectPool()->cachedShareableElementDataWithAttributes(attributeVector);
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001134 else
1135 m_elementData = ShareableElementData::createWithAttributes(attributeVector);
1136
1137 // Use attributeVector instead of m_elementData because attributeChanged might modify m_elementData.
1138 for (unsigned i = 0; i < attributeVector.size(); ++i)
1139 attributeChangedFromParserOrByCloning(attributeVector[i].name(), attributeVector[i].value(), ModifiedDirectly);
1140}
1141
1142bool Element::hasAttributes() const
1143{
1144 synchronizeAllAttributes();
1145 return elementData() && elementData()->length();
1146}
1147
1148bool Element::hasEquivalentAttributes(const Element* other) const
1149{
1150 synchronizeAllAttributes();
1151 other->synchronizeAllAttributes();
1152 if (elementData() == other->elementData())
1153 return true;
1154 if (elementData())
1155 return elementData()->isEquivalent(other->elementData());
1156 if (other->elementData())
1157 return other->elementData()->isEquivalent(elementData());
1158 return true;
1159}
1160
1161String Element::nodeName() const
1162{
1163 return m_tagName.toString();
1164}
1165
1166String Element::nodeNamePreservingCase() const
1167{
1168 return m_tagName.toString();
1169}
1170
Ben Murdochdf957042013-08-06 11:01:27 +01001171void Element::setPrefix(const AtomicString& prefix, ExceptionState& es)
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001172{
Ben Murdochdf957042013-08-06 11:01:27 +01001173 checkSetPrefix(prefix, es);
1174 if (es.hadException())
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001175 return;
1176
1177 m_tagName.setPrefix(prefix.isEmpty() ? AtomicString() : prefix);
1178}
1179
1180KURL Element::baseURI() const
1181{
1182 const AtomicString& baseAttribute = getAttribute(baseAttr);
1183 KURL base(KURL(), baseAttribute);
1184 if (!base.protocol().isEmpty())
1185 return base;
1186
1187 ContainerNode* parent = parentNode();
1188 if (!parent)
1189 return base;
1190
1191 const KURL& parentBase = parent->baseURI();
1192 if (parentBase.isNull())
1193 return base;
1194
1195 return KURL(parentBase, baseAttribute);
1196}
1197
Torne (Richard Coles)8abfc582013-09-12 12:10:38 +01001198const AtomicString Element::imageSourceURL() const
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001199{
1200 return getAttribute(srcAttr);
1201}
1202
Torne (Richard Coles)8abfc582013-09-12 12:10:38 +01001203bool Element::rendererIsNeeded(const RenderStyle& style)
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001204{
Torne (Richard Coles)8abfc582013-09-12 12:10:38 +01001205 return style.display() != NONE;
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001206}
1207
Ben Murdoch591b9582013-07-10 11:41:44 +01001208RenderObject* Element::createRenderer(RenderStyle* style)
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001209{
1210 return RenderObject::createObject(this, style);
1211}
1212
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001213Node::InsertionNotificationRequest Element::insertedInto(ContainerNode* insertionPoint)
1214{
1215 // need to do superclass processing first so inDocument() is true
1216 // by the time we reach updateId
1217 ContainerNode::insertedInto(insertionPoint);
1218
1219 if (containsFullScreenElement() && parentElement() && !parentElement()->containsFullScreenElement())
1220 setContainsFullScreenElementOnAncestorsCrossingFrameBoundaries(true);
1221
1222 if (Element* before = pseudoElement(BEFORE))
1223 before->insertedInto(insertionPoint);
1224
1225 if (Element* after = pseudoElement(AFTER))
1226 after->insertedInto(insertionPoint);
1227
Torne (Richard Coles)e1f1df52013-08-23 16:39:30 +01001228 if (Element* backdrop = pseudoElement(BACKDROP))
1229 backdrop->insertedInto(insertionPoint);
1230
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001231 if (!insertionPoint->isInTreeScope())
1232 return InsertionDone;
1233
1234 if (hasRareData())
1235 elementRareData()->clearClassListValueForQuirksMode();
1236
Torne (Richard Coles)f5e4ad52013-08-05 13:57:57 +01001237 if (isUpgradedCustomElement() && inDocument())
1238 CustomElement::didEnterDocument(this, document());
1239
Torne (Richard Coles)8abfc582013-09-12 12:10:38 +01001240 TreeScope& scope = insertionPoint->treeScope();
1241 if (&scope != &treeScope())
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001242 return InsertionDone;
1243
1244 const AtomicString& idValue = getIdAttribute();
Ben Murdoch00d3faa2013-08-14 11:52:03 +01001245 if (!idValue.isNull())
1246 updateId(scope, nullAtom, idValue);
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001247
1248 const AtomicString& nameValue = getNameAttribute();
Ben Murdoch00d3faa2013-08-14 11:52:03 +01001249 if (!nameValue.isNull())
1250 updateName(nullAtom, nameValue);
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001251
1252 if (hasTagName(labelTag)) {
Torne (Richard Coles)8abfc582013-09-12 12:10:38 +01001253 if (scope.shouldCacheLabelsByForAttribute())
Ben Murdoch00d3faa2013-08-14 11:52:03 +01001254 updateLabel(scope, nullAtom, fastGetAttribute(forAttr));
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001255 }
1256
Ben Murdoch3c9e4ae2013-08-12 14:20:44 +01001257 if (parentElement() && parentElement()->isInCanvasSubtree())
1258 setIsInCanvasSubtree(true);
1259
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001260 return InsertionDone;
1261}
1262
1263void Element::removedFrom(ContainerNode* insertionPoint)
1264{
Torne (Richard Coles)f5e4ad52013-08-05 13:57:57 +01001265 bool wasInDocument = insertionPoint->inDocument();
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001266
1267 if (Element* before = pseudoElement(BEFORE))
1268 before->removedFrom(insertionPoint);
1269
1270 if (Element* after = pseudoElement(AFTER))
1271 after->removedFrom(insertionPoint);
1272
Ben Murdoche69819b2013-07-17 14:56:49 +01001273 if (Element* backdrop = pseudoElement(BACKDROP))
1274 backdrop->removedFrom(insertionPoint);
Torne (Richard Coles)8abfc582013-09-12 12:10:38 +01001275 document().removeFromTopLayer(this);
Ben Murdoche69819b2013-07-17 14:56:49 +01001276
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001277 if (containsFullScreenElement())
1278 setContainsFullScreenElementOnAncestorsCrossingFrameBoundaries(false);
1279
Torne (Richard Coles)8abfc582013-09-12 12:10:38 +01001280 if (document().page())
1281 document().page()->pointerLockController().elementRemoved(this);
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001282
1283 setSavedLayerScrollOffset(IntSize());
1284
Torne (Richard Coles)8abfc582013-09-12 12:10:38 +01001285 if (insertionPoint->isInTreeScope() && &treeScope() == &document()) {
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001286 const AtomicString& idValue = getIdAttribute();
Ben Murdoch00d3faa2013-08-14 11:52:03 +01001287 if (!idValue.isNull())
1288 updateId(insertionPoint->treeScope(), idValue, nullAtom);
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001289
1290 const AtomicString& nameValue = getNameAttribute();
Ben Murdoch00d3faa2013-08-14 11:52:03 +01001291 if (!nameValue.isNull())
1292 updateName(nameValue, nullAtom);
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001293
1294 if (hasTagName(labelTag)) {
Torne (Richard Coles)8abfc582013-09-12 12:10:38 +01001295 TreeScope& treeScope = insertionPoint->treeScope();
1296 if (treeScope.shouldCacheLabelsByForAttribute())
Ben Murdoch00d3faa2013-08-14 11:52:03 +01001297 updateLabel(treeScope, fastGetAttribute(forAttr), nullAtom);
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001298 }
1299 }
1300
1301 ContainerNode::removedFrom(insertionPoint);
Ben Murdoche69819b2013-07-17 14:56:49 +01001302 if (wasInDocument) {
1303 if (hasPendingResources())
Torne (Richard Coles)8abfc582013-09-12 12:10:38 +01001304 document().accessSVGExtensions()->removeElementFromPendingResources(this);
Ben Murdoche69819b2013-07-17 14:56:49 +01001305
Ben Murdoch83750172013-07-24 10:36:59 +01001306 if (isUpgradedCustomElement())
Ben Murdochfff88842013-07-30 15:20:09 +01001307 CustomElement::didLeaveDocument(this, insertionPoint->document());
Ben Murdoche69819b2013-07-17 14:56:49 +01001308 }
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001309
Ben Murdoch3c9e4ae2013-08-12 14:20:44 +01001310 if (hasRareData())
1311 elementRareData()->setIsInCanvasSubtree(false);
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001312}
1313
Torne (Richard Coles)521d96e2013-06-19 11:58:24 +01001314void Element::attach(const AttachContext& context)
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001315{
Torne (Richard Coles)8abfc582013-09-12 12:10:38 +01001316 ASSERT(document().inStyleRecalc());
1317
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001318 StyleResolverParentPusher parentPusher(this);
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001319
Torne (Richard Coles)e1f1df52013-08-23 16:39:30 +01001320 // We've already been through detach when doing a lazyAttach, but we might
1321 // need to clear any state that's been added since then.
1322 if (hasRareData() && styleChangeType() == LazyAttachStyleChange) {
1323 ElementRareData* data = elementRareData();
1324 data->clearComputedStyle();
1325 data->resetDynamicRestyleObservations();
1326 if (!context.resolvedStyle)
1327 data->resetStyleState();
1328 }
1329
Ben Murdoch3c9e4ae2013-08-12 14:20:44 +01001330 NodeRenderingContext(this, context.resolvedStyle).createRendererForElementIfNeeded();
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001331
1332 createPseudoElementIfNeeded(BEFORE);
1333
1334 // When a shadow root exists, it does the work of attaching the children.
1335 if (ElementShadow* shadow = this->shadow()) {
1336 parentPusher.push();
Ben Murdoch591b9582013-07-10 11:41:44 +01001337 shadow->attach(context);
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001338 } else if (firstChild())
1339 parentPusher.push();
1340
Torne (Richard Coles)521d96e2013-06-19 11:58:24 +01001341 ContainerNode::attach(context);
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001342
1343 createPseudoElementIfNeeded(AFTER);
Ben Murdoche69819b2013-07-17 14:56:49 +01001344 createPseudoElementIfNeeded(BACKDROP);
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001345
Ben Murdoch591b9582013-07-10 11:41:44 +01001346 if (hasRareData()) {
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001347 ElementRareData* data = elementRareData();
1348 if (data->needsFocusAppearanceUpdateSoonAfterAttach()) {
Torne (Richard Coles)8abfc582013-09-12 12:10:38 +01001349 if (isFocusable() && document().focusedElement() == this)
1350 document().updateFocusAppearanceSoon(false /* don't restore selection */);
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001351 data->setNeedsFocusAppearanceUpdateSoonAfterAttach(false);
1352 }
1353 }
Ben Murdoch591b9582013-07-10 11:41:44 +01001354
Torne (Richard Coles)8abfc582013-09-12 12:10:38 +01001355 InspectorInstrumentation::didRecalculateStyleForElement(this);
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001356}
1357
1358void Element::unregisterNamedFlowContentNode()
1359{
Torne (Richard Coles)8abfc582013-09-12 12:10:38 +01001360 if (RuntimeEnabledFeatures::cssRegionsEnabled() && inNamedFlow() && document().renderView())
1361 document().renderView()->flowThreadController()->unregisterNamedFlowContentNode(this);
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001362}
1363
Torne (Richard Coles)521d96e2013-06-19 11:58:24 +01001364void Element::detach(const AttachContext& context)
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001365{
1366 WidgetHierarchyUpdatesSuspensionScope suspendWidgetHierarchyUpdates;
1367 unregisterNamedFlowContentNode();
1368 cancelFocusAppearanceUpdate();
1369 if (hasRareData()) {
1370 ElementRareData* data = elementRareData();
1371 data->setPseudoElement(BEFORE, 0);
1372 data->setPseudoElement(AFTER, 0);
Ben Murdoche69819b2013-07-17 14:56:49 +01001373 data->setPseudoElement(BACKDROP, 0);
Ben Murdoch3c9e4ae2013-08-12 14:20:44 +01001374 data->clearComputedStyle();
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001375 data->resetDynamicRestyleObservations();
Ben Murdoch591b9582013-07-10 11:41:44 +01001376 data->setIsInsideRegion(false);
Torne (Richard Coles)f5e4ad52013-08-05 13:57:57 +01001377
Ben Murdoch3c9e4ae2013-08-12 14:20:44 +01001378 // Only clear the style state if we're not going to reuse the style from recalcStyle.
1379 if (!context.resolvedStyle)
1380 data->resetStyleState();
1381
Torne (Richard Coles)f5e4ad52013-08-05 13:57:57 +01001382 if (RuntimeEnabledFeatures::webAnimationsCSSEnabled() && !context.performingReattach) {
1383 if (ActiveAnimations* activeAnimations = data->activeAnimations())
1384 activeAnimations->cssAnimations()->cancel();
1385 }
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001386 }
Ben Murdoch591b9582013-07-10 11:41:44 +01001387 if (ElementShadow* shadow = this->shadow())
1388 shadow->detach(context);
Torne (Richard Coles)521d96e2013-06-19 11:58:24 +01001389 ContainerNode::detach(context);
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001390}
1391
1392bool Element::pseudoStyleCacheIsInvalid(const RenderStyle* currentStyle, RenderStyle* newStyle)
1393{
1394 ASSERT(currentStyle == renderStyle());
1395 ASSERT(renderer());
1396
1397 if (!currentStyle)
1398 return false;
1399
1400 const PseudoStyleCache* pseudoStyleCache = currentStyle->cachedPseudoStyles();
1401 if (!pseudoStyleCache)
1402 return false;
1403
1404 size_t cacheSize = pseudoStyleCache->size();
1405 for (size_t i = 0; i < cacheSize; ++i) {
1406 RefPtr<RenderStyle> newPseudoStyle;
1407 PseudoId pseudoId = pseudoStyleCache->at(i)->styleType();
1408 if (pseudoId == FIRST_LINE || pseudoId == FIRST_LINE_INHERITED)
1409 newPseudoStyle = renderer()->uncachedFirstLineStyle(newStyle);
1410 else
1411 newPseudoStyle = renderer()->getUncachedPseudoStyle(PseudoStyleRequest(pseudoId), newStyle, newStyle);
1412 if (!newPseudoStyle)
1413 return true;
1414 if (*newPseudoStyle != *pseudoStyleCache->at(i)) {
1415 if (pseudoId < FIRST_INTERNAL_PSEUDOID)
1416 newStyle->setHasPseudoStyle(pseudoId);
1417 newStyle->addCachedPseudoStyle(newPseudoStyle);
1418 if (pseudoId == FIRST_LINE || pseudoId == FIRST_LINE_INHERITED) {
1419 // FIXME: We should do an actual diff to determine whether a repaint vs. layout
1420 // is needed, but for now just assume a layout will be required. The diff code
1421 // in RenderObject::setStyle would need to be factored out so that it could be reused.
1422 renderer()->setNeedsLayoutAndPrefWidthsRecalc();
1423 }
1424 return true;
1425 }
1426 }
1427 return false;
1428}
1429
Torne (Richard Coles)521d96e2013-06-19 11:58:24 +01001430PassRefPtr<RenderStyle> Element::styleForRenderer()
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001431{
1432 if (hasCustomStyleCallbacks()) {
1433 if (RefPtr<RenderStyle> style = customStyleForRenderer())
1434 return style.release();
1435 }
1436
Torne (Richard Coles)521d96e2013-06-19 11:58:24 +01001437 return originalStyleForRenderer();
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001438}
1439
Torne (Richard Coles)521d96e2013-06-19 11:58:24 +01001440PassRefPtr<RenderStyle> Element::originalStyleForRenderer()
Torne (Richard Coles)5267f702013-06-11 10:57:24 +01001441{
Torne (Richard Coles)8abfc582013-09-12 12:10:38 +01001442 return document().styleResolver()->styleForElement(this);
Torne (Richard Coles)5267f702013-06-11 10:57:24 +01001443}
1444
Torne (Richard Coles)8abfc582013-09-12 12:10:38 +01001445bool Element::recalcStyle(StyleRecalcChange change)
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001446{
Torne (Richard Coles)8abfc582013-09-12 12:10:38 +01001447 ASSERT(document().inStyleRecalc());
Torne (Richard Coles)93ac45c2013-05-29 14:40:20 +01001448
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001449 if (hasCustomStyleCallbacks())
1450 willRecalcStyle(change);
1451
Ben Murdoch3c9e4ae2013-08-12 14:20:44 +01001452 if (hasRareData() && (change > NoChange || needsStyleRecalc())) {
1453 ElementRareData* data = elementRareData();
1454 data->resetStyleState();
1455 data->clearComputedStyle();
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001456 }
Ben Murdoch3c9e4ae2013-08-12 14:20:44 +01001457
Torne (Richard Coles)c0e19a62013-08-30 15:15:11 +01001458 // Active InsertionPoints have no renderers so they never need to go through a recalc.
1459 if ((change >= Inherit || needsStyleRecalc()) && parentRenderStyle() && !isActiveInsertionPoint(this))
1460 change = recalcOwnStyle(change);
Torne (Richard Coles)521d96e2013-06-19 11:58:24 +01001461
Torne (Richard Coles)c0e19a62013-08-30 15:15:11 +01001462 // If we reattached we don't need to recalc the style of our descendants anymore.
1463 if (change < Reattach)
1464 recalcChildStyle(change);
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001465
Torne (Richard Coles)c0e19a62013-08-30 15:15:11 +01001466 clearNeedsStyleRecalc();
1467 clearChildNeedsStyleRecalc();
Ben Murdoch591b9582013-07-10 11:41:44 +01001468
Torne (Richard Coles)c0e19a62013-08-30 15:15:11 +01001469 if (hasCustomStyleCallbacks())
1470 didRecalcStyle(change);
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001471
Torne (Richard Coles)c0e19a62013-08-30 15:15:11 +01001472 return change == Reattach;
1473}
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001474
Torne (Richard Coles)8abfc582013-09-12 12:10:38 +01001475StyleRecalcChange Element::recalcOwnStyle(StyleRecalcChange change)
Torne (Richard Coles)c0e19a62013-08-30 15:15:11 +01001476{
Torne (Richard Coles)8abfc582013-09-12 12:10:38 +01001477 ASSERT(document().inStyleRecalc());
Torne (Richard Coles)c0e19a62013-08-30 15:15:11 +01001478
1479 CSSAnimationUpdateScope cssAnimationUpdateScope(this);
1480 RefPtr<RenderStyle> oldStyle = renderStyle();
1481 RefPtr<RenderStyle> newStyle = styleForRenderer();
Torne (Richard Coles)8abfc582013-09-12 12:10:38 +01001482 StyleRecalcChange localChange = RenderStyle::compare(oldStyle.get(), newStyle.get());
Torne (Richard Coles)c0e19a62013-08-30 15:15:11 +01001483
1484 if (localChange == Reattach) {
1485 AttachContext reattachContext;
1486 reattachContext.resolvedStyle = newStyle.get();
1487 reattach(reattachContext);
1488 return Reattach;
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001489 }
Torne (Richard Coles)c0e19a62013-08-30 15:15:11 +01001490
1491 InspectorInstrumentation::didRecalculateStyleForElement(this);
1492
1493 if (RenderObject* renderer = this->renderer()) {
1494 if (localChange != NoChange || pseudoStyleCacheIsInvalid(oldStyle.get(), newStyle.get()) || (change == Force && renderer->requiresForcedStyleRecalcPropagation()) || shouldNotifyRendererWithIdenticalStyles()) {
1495 renderer->setAnimatableStyle(newStyle.get());
1496 } else if (needsStyleRecalc()) {
1497 // Although no change occurred, we use the new style so that the cousin style sharing code won't get
1498 // fooled into believing this style is the same.
1499 renderer->setStyleInternal(newStyle.get());
1500 }
1501 }
1502
1503 // 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
1504 // 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).
Torne (Richard Coles)9bbd2f52013-09-19 22:37:05 +01001505 if (document().styleEngine()->usesRemUnits() && document().documentElement() == this && oldStyle && newStyle && oldStyle->fontSize() != newStyle->fontSize()) {
Torne (Richard Coles)c0e19a62013-08-30 15:15:11 +01001506 // Cached RenderStyles may depend on the re units.
Torne (Richard Coles)8abfc582013-09-12 12:10:38 +01001507 document().styleResolver()->invalidateMatchedPropertiesCache();
Torne (Richard Coles)c0e19a62013-08-30 15:15:11 +01001508 return Force;
1509 }
1510
1511 if (styleChangeType() >= SubtreeStyleChange)
1512 return Force;
1513
1514 return max(localChange, change);
1515}
1516
Torne (Richard Coles)8abfc582013-09-12 12:10:38 +01001517void Element::recalcChildStyle(StyleRecalcChange change)
Torne (Richard Coles)c0e19a62013-08-30 15:15:11 +01001518{
Torne (Richard Coles)8abfc582013-09-12 12:10:38 +01001519 ASSERT(document().inStyleRecalc());
Torne (Richard Coles)c0e19a62013-08-30 15:15:11 +01001520
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001521 StyleResolverParentPusher parentPusher(this);
1522
Torne (Richard Coles)f5e4ad52013-08-05 13:57:57 +01001523 for (ShadowRoot* root = youngestShadowRoot(); root; root = root->olderShadowRoot()) {
1524 if (shouldRecalcStyle(change, root)) {
1525 parentPusher.push();
1526 root->recalcStyle(change);
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001527 }
1528 }
1529
1530 if (shouldRecalcStyle(change, this))
1531 updatePseudoElement(BEFORE, change);
1532
1533 // FIXME: This check is good enough for :hover + foo, but it is not good enough for :hover + foo + bar.
1534 // For now we will just worry about the common case, since it's a lot trickier to get the second case right
1535 // without doing way too much re-resolution.
Torne (Richard Coles)c0e19a62013-08-30 15:15:11 +01001536 bool hasDirectAdjacentRules = childrenAffectedByDirectAdjacentRules();
1537 bool hasIndirectAdjacentRules = childrenAffectedByForwardPositionalRules();
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001538 bool forceCheckOfNextElementSibling = false;
1539 bool forceCheckOfAnyElementSibling = false;
Ben Murdoche69819b2013-07-17 14:56:49 +01001540 bool forceReattachOfAnyWhitespaceSibling = false;
1541 for (Node* child = firstChild(); child; child = child->nextSibling()) {
1542 bool didReattach = false;
1543
1544 if (child->renderer())
1545 forceReattachOfAnyWhitespaceSibling = false;
1546
1547 if (child->isTextNode()) {
1548 if (forceReattachOfAnyWhitespaceSibling && toText(child)->containsOnlyWhitespace())
1549 child->reattach();
1550 else
1551 didReattach = toText(child)->recalcTextStyle(change);
1552 } else if (child->isElementNode()) {
1553 Element* element = toElement(child);
1554
Torne (Richard Coles)e1f1df52013-08-23 16:39:30 +01001555 bool childRulesChanged = element->needsStyleRecalc() && element->styleChangeType() >= SubtreeStyleChange;
1556
Ben Murdoche69819b2013-07-17 14:56:49 +01001557 if (forceCheckOfNextElementSibling || forceCheckOfAnyElementSibling)
1558 element->setNeedsStyleRecalc();
1559
Ben Murdoche69819b2013-07-17 14:56:49 +01001560 forceCheckOfNextElementSibling = childRulesChanged && hasDirectAdjacentRules;
1561 forceCheckOfAnyElementSibling = forceCheckOfAnyElementSibling || (childRulesChanged && hasIndirectAdjacentRules);
1562
1563 if (shouldRecalcStyle(change, element)) {
1564 parentPusher.push();
1565 didReattach = element->recalcStyle(change);
Torne (Richard Coles)8abfc582013-09-12 12:10:38 +01001566 } else if (document().styleResolver()->supportsStyleSharing(element)) {
1567 document().styleResolver()->addToStyleSharingList(element);
Ben Murdoche69819b2013-07-17 14:56:49 +01001568 }
Ben Murdoch591b9582013-07-10 11:41:44 +01001569 }
Ben Murdoche69819b2013-07-17 14:56:49 +01001570
1571 forceReattachOfAnyWhitespaceSibling = didReattach || forceReattachOfAnyWhitespaceSibling;
Torne (Richard Coles)5267f702013-06-11 10:57:24 +01001572 }
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001573
Torne (Richard Coles)e1f1df52013-08-23 16:39:30 +01001574 if (shouldRecalcStyle(change, this)) {
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001575 updatePseudoElement(AFTER, change);
Torne (Richard Coles)e1f1df52013-08-23 16:39:30 +01001576 updatePseudoElement(BACKDROP, change);
1577 }
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001578}
1579
1580ElementShadow* Element::shadow() const
1581{
1582 return hasRareData() ? elementRareData()->shadow() : 0;
1583}
1584
1585ElementShadow* Element::ensureShadow()
1586{
1587 return ensureElementRareData()->ensureShadow();
1588}
1589
1590void Element::didAffectSelector(AffectedSelectorMask mask)
1591{
1592 setNeedsStyleRecalc();
1593 if (ElementShadow* elementShadow = shadowOfParentForDistribution(this))
1594 elementShadow->didAffectSelector(mask);
1595}
1596
Ben Murdochdf957042013-08-06 11:01:27 +01001597PassRefPtr<ShadowRoot> Element::createShadowRoot(ExceptionState& es)
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001598{
1599 if (alwaysCreateUserAgentShadowRoot())
1600 ensureUserAgentShadowRoot();
1601
1602 if (RuntimeEnabledFeatures::authorShadowDOMForAnyElementEnabled())
1603 return ensureShadow()->addShadowRoot(this, ShadowRoot::AuthorShadowRoot);
1604
1605 // Since some elements recreates shadow root dynamically, multiple shadow
1606 // subtrees won't work well in that element. Until they are fixed, we disable
1607 // adding author shadow root for them.
1608 if (!areAuthorShadowsAllowed()) {
Torne (Richard Coles)06f816c2013-09-26 13:25:12 +01001609 es.throwUninformativeAndGenericDOMException(HierarchyRequestError);
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001610 return 0;
1611 }
1612 return ensureShadow()->addShadowRoot(this, ShadowRoot::AuthorShadowRoot);
1613}
1614
1615ShadowRoot* Element::shadowRoot() const
1616{
1617 ElementShadow* elementShadow = shadow();
1618 if (!elementShadow)
1619 return 0;
1620 ShadowRoot* shadowRoot = elementShadow->youngestShadowRoot();
1621 if (shadowRoot->type() == ShadowRoot::AuthorShadowRoot)
1622 return shadowRoot;
1623 return 0;
1624}
1625
Torne (Richard Coles)8abfc582013-09-12 12:10:38 +01001626void Element::didAddShadowRoot(ShadowRoot&)
1627{
1628}
1629
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001630ShadowRoot* Element::userAgentShadowRoot() const
1631{
1632 if (ElementShadow* elementShadow = shadow()) {
1633 if (ShadowRoot* shadowRoot = elementShadow->oldestShadowRoot()) {
1634 ASSERT(shadowRoot->type() == ShadowRoot::UserAgentShadowRoot);
1635 return shadowRoot;
1636 }
1637 }
1638
1639 return 0;
1640}
1641
1642ShadowRoot* Element::ensureUserAgentShadowRoot()
1643{
1644 if (ShadowRoot* shadowRoot = userAgentShadowRoot())
1645 return shadowRoot;
1646 ShadowRoot* shadowRoot = ensureShadow()->addShadowRoot(this, ShadowRoot::UserAgentShadowRoot);
1647 didAddUserAgentShadowRoot(shadowRoot);
1648 return shadowRoot;
1649}
1650
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001651bool Element::childTypeAllowed(NodeType type) const
1652{
1653 switch (type) {
1654 case ELEMENT_NODE:
1655 case TEXT_NODE:
1656 case COMMENT_NODE:
1657 case PROCESSING_INSTRUCTION_NODE:
1658 case CDATA_SECTION_NODE:
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001659 return true;
1660 default:
1661 break;
1662 }
1663 return false;
1664}
1665
Ben Murdoch83750172013-07-24 10:36:59 +01001666static void inline checkForEmptyStyleChange(Element* element, RenderStyle* style)
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001667{
1668 if (!style && !element->styleAffectedByEmpty())
1669 return;
1670
1671 if (!style || (element->styleAffectedByEmpty() && (!style->emptyState() || element->hasChildNodes())))
1672 element->setNeedsStyleRecalc();
1673}
1674
1675static void checkForSiblingStyleChanges(Element* e, RenderStyle* style, bool finishedParsingCallback,
1676 Node* beforeChange, Node* afterChange, int childCountDelta)
1677{
Torne (Richard Coles)8abfc582013-09-12 12:10:38 +01001678 if (!e->attached() || e->document().hasPendingForcedStyleRecalc() || e->styleChangeType() >= SubtreeStyleChange)
Ben Murdoch83750172013-07-24 10:36:59 +01001679 return;
1680
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001681 // :empty selector.
1682 checkForEmptyStyleChange(e, style);
Ben Murdoch591b9582013-07-10 11:41:44 +01001683
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001684 if (!style || (e->needsStyleRecalc() && e->childrenAffectedByPositionalRules()))
1685 return;
1686
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001687 // Forward positional selectors include the ~ selector, nth-child, nth-of-type, first-of-type and only-of-type.
1688 // Backward positional selectors include nth-last-child, nth-last-of-type, last-of-type and only-of-type.
1689 // We have to invalidate everything following the insertion point in the forward case, and everything before the insertion point in the
1690 // backward case.
1691 // |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.
1692 // 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 +01001693 // here. recalcStyle will then force a walk of the children when it sees that this has happened.
1694 if ((e->childrenAffectedByForwardPositionalRules() && afterChange) || (e->childrenAffectedByBackwardPositionalRules() && beforeChange)) {
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001695 e->setNeedsStyleRecalc();
Ben Murdoch83750172013-07-24 10:36:59 +01001696 return;
1697 }
1698
1699 // :first-child. In the parser callback case, we don't have to check anything, since we were right the first time.
1700 // In the DOM case, we only need to do something if |afterChange| is not 0.
1701 // |afterChange| is 0 in the parser case, so it works out that we'll skip this block.
1702 if (e->childrenAffectedByFirstChildRules() && afterChange) {
1703 // Find our new first child.
1704 Node* newFirstChild = e->firstElementChild();
1705 RenderStyle* newFirstChildStyle = newFirstChild ? newFirstChild->renderStyle() : 0;
1706
1707 // Find the first element node following |afterChange|
1708 Node* firstElementAfterInsertion = afterChange->isElementNode() ? afterChange : afterChange->nextElementSibling();
1709 RenderStyle* firstElementAfterInsertionStyle = firstElementAfterInsertion ? firstElementAfterInsertion->renderStyle() : 0;
1710
1711 // This is the insert/append case.
1712 if (newFirstChild != firstElementAfterInsertion && firstElementAfterInsertionStyle && firstElementAfterInsertionStyle->firstChildState())
1713 firstElementAfterInsertion->setNeedsStyleRecalc();
1714
1715 // We also have to handle node removal.
1716 if (childCountDelta < 0 && newFirstChild == firstElementAfterInsertion && newFirstChild && (!newFirstChildStyle || !newFirstChildStyle->firstChildState()))
1717 newFirstChild->setNeedsStyleRecalc();
1718 }
1719
1720 // :last-child. In the parser callback case, we don't have to check anything, since we were right the first time.
1721 // In the DOM case, we only need to do something if |afterChange| is not 0.
1722 if (e->childrenAffectedByLastChildRules() && beforeChange) {
1723 // Find our new last child.
1724 Node* newLastChild = e->lastElementChild();
1725 RenderStyle* newLastChildStyle = newLastChild ? newLastChild->renderStyle() : 0;
1726
1727 // Find the last element node going backwards from |beforeChange|
1728 Node* lastElementBeforeInsertion = beforeChange->isElementNode() ? beforeChange : beforeChange->previousElementSibling();
1729 RenderStyle* lastElementBeforeInsertionStyle = lastElementBeforeInsertion ? lastElementBeforeInsertion->renderStyle() : 0;
1730
1731 if (newLastChild != lastElementBeforeInsertion && lastElementBeforeInsertionStyle && lastElementBeforeInsertionStyle->lastChildState())
1732 lastElementBeforeInsertion->setNeedsStyleRecalc();
1733
1734 // 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
1735 // to match now.
1736 if ((childCountDelta < 0 || finishedParsingCallback) && newLastChild == lastElementBeforeInsertion && newLastChild && (!newLastChildStyle || !newLastChildStyle->lastChildState()))
1737 newLastChild->setNeedsStyleRecalc();
1738 }
1739
1740 // The + selector. We need to invalidate the first element following the insertion point. It is the only possible element
1741 // that could be affected by this DOM change.
1742 if (e->childrenAffectedByDirectAdjacentRules() && afterChange) {
1743 if (Node* firstElementAfterInsertion = afterChange->nextElementSibling())
1744 firstElementAfterInsertion->setNeedsStyleRecalc();
1745 }
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001746}
1747
1748void Element::childrenChanged(bool changedByParser, Node* beforeChange, Node* afterChange, int childCountDelta)
1749{
1750 ContainerNode::childrenChanged(changedByParser, beforeChange, afterChange, childCountDelta);
1751 if (changedByParser)
1752 checkForEmptyStyleChange(this, renderStyle());
1753 else
1754 checkForSiblingStyleChanges(this, renderStyle(), false, beforeChange, afterChange, childCountDelta);
1755
Ben Murdoch83750172013-07-24 10:36:59 +01001756 if (ElementShadow* shadow = this->shadow())
Torne (Richard Coles)f5e4ad52013-08-05 13:57:57 +01001757 shadow->setNeedsDistributionRecalc();
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001758}
1759
1760void Element::removeAllEventListeners()
1761{
1762 ContainerNode::removeAllEventListeners();
1763 if (ElementShadow* shadow = this->shadow())
1764 shadow->removeAllEventListeners();
1765}
1766
1767void Element::beginParsingChildren()
1768{
1769 clearIsParsingChildrenFinished();
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001770}
1771
1772void Element::finishParsingChildren()
1773{
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001774 setIsParsingChildrenFinished();
1775 checkForSiblingStyleChanges(this, renderStyle(), true, lastChild(), 0, 0);
Torne (Richard Coles)e1f1df52013-08-23 16:39:30 +01001776 if (isCustomElement())
1777 CustomElement::didFinishParsingChildren(this);
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001778}
1779
1780#ifndef NDEBUG
1781void Element::formatForDebugger(char* buffer, unsigned length) const
1782{
1783 StringBuilder result;
1784 String s;
1785
1786 result.append(nodeName());
1787
1788 s = getIdAttribute();
1789 if (s.length() > 0) {
1790 if (result.length() > 0)
1791 result.appendLiteral("; ");
1792 result.appendLiteral("id=");
1793 result.append(s);
1794 }
1795
1796 s = getAttribute(classAttr);
1797 if (s.length() > 0) {
1798 if (result.length() > 0)
1799 result.appendLiteral("; ");
1800 result.appendLiteral("class=");
1801 result.append(s);
1802 }
1803
1804 strncpy(buffer, result.toString().utf8().data(), length - 1);
1805}
1806#endif
1807
1808const Vector<RefPtr<Attr> >& Element::attrNodeList()
1809{
1810 ASSERT(hasSyntheticAttrChildNodes());
1811 return *attrNodeListForElement(this);
1812}
1813
Ben Murdochdf957042013-08-06 11:01:27 +01001814PassRefPtr<Attr> Element::setAttributeNode(Attr* attrNode, ExceptionState& es)
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001815{
1816 if (!attrNode) {
Torne (Richard Coles)06f816c2013-09-26 13:25:12 +01001817 es.throwUninformativeAndGenericDOMException(TypeMismatchError);
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001818 return 0;
1819 }
1820
1821 RefPtr<Attr> oldAttrNode = attrIfExists(attrNode->qualifiedName());
1822 if (oldAttrNode.get() == attrNode)
1823 return attrNode; // This Attr is already attached to the element.
1824
Ben Murdoche69819b2013-07-17 14:56:49 +01001825 // 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 +01001826 // The DOM user must explicitly clone Attr nodes to re-use them in other elements.
1827 if (attrNode->ownerElement()) {
Torne (Richard Coles)06f816c2013-09-26 13:25:12 +01001828 es.throwUninformativeAndGenericDOMException(InUseAttributeError);
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001829 return 0;
1830 }
1831
1832 synchronizeAllAttributes();
1833 UniqueElementData* elementData = ensureUniqueElementData();
1834
Torne (Richard Coles)e1f1df52013-08-23 16:39:30 +01001835 size_t index = elementData->getAttributeItemIndex(attrNode->qualifiedName(), shouldIgnoreAttributeCase(this));
Torne (Richard Coles)06f816c2013-09-26 13:25:12 +01001836 if (index != kNotFound) {
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001837 if (oldAttrNode)
1838 detachAttrNodeFromElementWithValue(oldAttrNode.get(), elementData->attributeItem(index)->value());
1839 else
1840 oldAttrNode = Attr::create(document(), attrNode->qualifiedName(), elementData->attributeItem(index)->value());
1841 }
1842
1843 setAttributeInternal(index, attrNode->qualifiedName(), attrNode->value(), NotInSynchronizationOfLazyAttribute);
1844
1845 attrNode->attachToElement(this);
Torne (Richard Coles)8abfc582013-09-12 12:10:38 +01001846 treeScope().adoptIfNeeded(attrNode);
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001847 ensureAttrNodeListForElement(this)->append(attrNode);
1848
1849 return oldAttrNode.release();
1850}
1851
Ben Murdochdf957042013-08-06 11:01:27 +01001852PassRefPtr<Attr> Element::setAttributeNodeNS(Attr* attr, ExceptionState& es)
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001853{
Ben Murdochdf957042013-08-06 11:01:27 +01001854 return setAttributeNode(attr, es);
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001855}
1856
Ben Murdochdf957042013-08-06 11:01:27 +01001857PassRefPtr<Attr> Element::removeAttributeNode(Attr* attr, ExceptionState& es)
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001858{
1859 if (!attr) {
Torne (Richard Coles)06f816c2013-09-26 13:25:12 +01001860 es.throwUninformativeAndGenericDOMException(TypeMismatchError);
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001861 return 0;
1862 }
1863 if (attr->ownerElement() != this) {
Torne (Richard Coles)06f816c2013-09-26 13:25:12 +01001864 es.throwUninformativeAndGenericDOMException(NotFoundError);
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001865 return 0;
1866 }
1867
Torne (Richard Coles)8abfc582013-09-12 12:10:38 +01001868 ASSERT(&document() == &attr->document());
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001869
1870 synchronizeAttribute(attr->qualifiedName());
1871
Torne (Richard Coles)e5249552013-05-15 11:35:13 +01001872 size_t index = elementData()->getAttrIndex(attr);
Torne (Richard Coles)06f816c2013-09-26 13:25:12 +01001873 if (index == kNotFound) {
1874 es.throwUninformativeAndGenericDOMException(NotFoundError);
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001875 return 0;
1876 }
1877
Torne (Richard Coles)e5249552013-05-15 11:35:13 +01001878 RefPtr<Attr> guard(attr);
1879 detachAttrNodeAtIndex(attr, index);
1880 return guard.release();
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001881}
1882
Ben Murdochdf957042013-08-06 11:01:27 +01001883bool Element::parseAttributeName(QualifiedName& out, const AtomicString& namespaceURI, const AtomicString& qualifiedName, ExceptionState& es)
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001884{
1885 String prefix, localName;
Ben Murdochdf957042013-08-06 11:01:27 +01001886 if (!Document::parseQualifiedName(qualifiedName, prefix, localName, es))
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001887 return false;
Ben Murdochdf957042013-08-06 11:01:27 +01001888 ASSERT(!es.hadException());
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001889
1890 QualifiedName qName(prefix, localName, namespaceURI);
1891
1892 if (!Document::hasValidNamespaceForAttributes(qName)) {
Torne (Richard Coles)06f816c2013-09-26 13:25:12 +01001893 es.throwUninformativeAndGenericDOMException(NamespaceError);
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001894 return false;
1895 }
1896
1897 out = qName;
1898 return true;
1899}
1900
Ben Murdochdf957042013-08-06 11:01:27 +01001901void Element::setAttributeNS(const AtomicString& namespaceURI, const AtomicString& qualifiedName, const AtomicString& value, ExceptionState& es)
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001902{
1903 QualifiedName parsedName = anyName;
Ben Murdochdf957042013-08-06 11:01:27 +01001904 if (!parseAttributeName(parsedName, namespaceURI, qualifiedName, es))
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001905 return;
1906 setAttribute(parsedName, value);
1907}
1908
1909void Element::removeAttributeInternal(size_t index, SynchronizationOfLazyAttribute inSynchronizationOfLazyAttribute)
1910{
1911 ASSERT_WITH_SECURITY_IMPLICATION(index < attributeCount());
1912
1913 UniqueElementData* elementData = ensureUniqueElementData();
1914
1915 QualifiedName name = elementData->attributeItem(index)->name();
1916 AtomicString valueBeingRemoved = elementData->attributeItem(index)->value();
1917
1918 if (!inSynchronizationOfLazyAttribute) {
1919 if (!valueBeingRemoved.isNull())
1920 willModifyAttribute(name, valueBeingRemoved, nullAtom);
1921 }
1922
1923 if (RefPtr<Attr> attrNode = attrIfExists(name))
1924 detachAttrNodeFromElementWithValue(attrNode.get(), elementData->attributeItem(index)->value());
1925
1926 elementData->removeAttribute(index);
1927
1928 if (!inSynchronizationOfLazyAttribute)
1929 didRemoveAttribute(name);
1930}
1931
1932void Element::addAttributeInternal(const QualifiedName& name, const AtomicString& value, SynchronizationOfLazyAttribute inSynchronizationOfLazyAttribute)
1933{
1934 if (!inSynchronizationOfLazyAttribute)
1935 willModifyAttribute(name, nullAtom, value);
1936 ensureUniqueElementData()->addAttribute(name, value);
1937 if (!inSynchronizationOfLazyAttribute)
1938 didAddAttribute(name, value);
1939}
1940
1941void Element::removeAttribute(const AtomicString& name)
1942{
1943 if (!elementData())
1944 return;
1945
1946 AtomicString localName = shouldIgnoreAttributeCase(this) ? name.lower() : name;
1947 size_t index = elementData()->getAttributeItemIndex(localName, false);
Torne (Richard Coles)06f816c2013-09-26 13:25:12 +01001948 if (index == kNotFound) {
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001949 if (UNLIKELY(localName == styleAttr) && elementData()->m_styleAttributeIsDirty && isStyledElement())
Ben Murdoch591b9582013-07-10 11:41:44 +01001950 removeAllInlineStyleProperties();
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001951 return;
1952 }
1953
1954 removeAttributeInternal(index, NotInSynchronizationOfLazyAttribute);
1955}
1956
1957void Element::removeAttributeNS(const AtomicString& namespaceURI, const AtomicString& localName)
1958{
1959 removeAttribute(QualifiedName(nullAtom, localName, namespaceURI));
1960}
1961
1962PassRefPtr<Attr> Element::getAttributeNode(const AtomicString& localName)
1963{
1964 if (!elementData())
1965 return 0;
1966 synchronizeAttribute(localName);
1967 const Attribute* attribute = elementData()->getAttributeItem(localName, shouldIgnoreAttributeCase(this));
1968 if (!attribute)
1969 return 0;
1970 return ensureAttr(attribute->name());
1971}
1972
1973PassRefPtr<Attr> Element::getAttributeNodeNS(const AtomicString& namespaceURI, const AtomicString& localName)
1974{
1975 if (!elementData())
1976 return 0;
1977 QualifiedName qName(nullAtom, localName, namespaceURI);
1978 synchronizeAttribute(qName);
1979 const Attribute* attribute = elementData()->getAttributeItem(qName);
1980 if (!attribute)
1981 return 0;
1982 return ensureAttr(attribute->name());
1983}
1984
1985bool Element::hasAttribute(const AtomicString& localName) const
1986{
1987 if (!elementData())
1988 return false;
1989 synchronizeAttribute(localName);
1990 return elementData()->getAttributeItem(shouldIgnoreAttributeCase(this) ? localName.lower() : localName, false);
1991}
1992
1993bool Element::hasAttributeNS(const AtomicString& namespaceURI, const AtomicString& localName) const
1994{
1995 if (!elementData())
1996 return false;
1997 QualifiedName qName(nullAtom, localName, namespaceURI);
1998 synchronizeAttribute(qName);
1999 return elementData()->getAttributeItem(qName);
2000}
2001
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002002void Element::focus(bool restorePreviousSelection, FocusDirection direction)
2003{
2004 if (!inDocument())
2005 return;
2006
Torne (Richard Coles)8abfc582013-09-12 12:10:38 +01002007 Document& doc = document();
2008 if (doc.focusedElement() == this)
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002009 return;
2010
2011 // If the stylesheets have already been loaded we can reliably check isFocusable.
2012 // If not, we continue and set the focused node on the focus controller below so
Ben Murdoch591b9582013-07-10 11:41:44 +01002013 // that it can be updated soon after attach.
Torne (Richard Coles)8abfc582013-09-12 12:10:38 +01002014 if (doc.haveStylesheetsLoaded()) {
2015 doc.updateLayoutIgnorePendingStylesheets();
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002016 if (!isFocusable())
2017 return;
2018 }
2019
2020 if (!supportsFocus())
2021 return;
2022
2023 RefPtr<Node> protect;
Torne (Richard Coles)8abfc582013-09-12 12:10:38 +01002024 if (Page* page = doc.page()) {
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002025 // Focus and change event handlers can cause us to lose our last ref.
2026 // If a focus event handler changes the focus to a different node it
2027 // does not make sense to continue and update appearence.
2028 protect = this;
Torne (Richard Coles)8abfc582013-09-12 12:10:38 +01002029 if (!page->focusController().setFocusedElement(this, doc.frame(), direction))
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002030 return;
2031 }
2032
2033 // Setting the focused node above might have invalidated the layout due to scripts.
Torne (Richard Coles)8abfc582013-09-12 12:10:38 +01002034 doc.updateLayoutIgnorePendingStylesheets();
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002035
2036 if (!isFocusable()) {
2037 ensureElementRareData()->setNeedsFocusAppearanceUpdateSoonAfterAttach(true);
2038 return;
2039 }
Ben Murdoch591b9582013-07-10 11:41:44 +01002040
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002041 cancelFocusAppearanceUpdate();
2042 updateFocusAppearance(restorePreviousSelection);
2043}
2044
2045void Element::updateFocusAppearance(bool /*restorePreviousSelection*/)
2046{
2047 if (isRootEditableElement()) {
Torne (Richard Coles)8abfc582013-09-12 12:10:38 +01002048 Frame* frame = document().frame();
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002049 if (!frame)
2050 return;
Ben Murdoch591b9582013-07-10 11:41:44 +01002051
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002052 // When focusing an editable element in an iframe, don't reset the selection if it already contains a selection.
Torne (Richard Coles)8abfc582013-09-12 12:10:38 +01002053 if (this == frame->selection().rootEditableElement())
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002054 return;
2055
2056 // FIXME: We should restore the previous selection if there is one.
2057 VisibleSelection newSelection = VisibleSelection(firstPositionInOrBeforeNode(this), DOWNSTREAM);
Ben Murdoch591b9582013-07-10 11:41:44 +01002058
Torne (Richard Coles)8abfc582013-09-12 12:10:38 +01002059 if (frame->selection().shouldChangeSelection(newSelection)) {
2060 frame->selection().setSelection(newSelection);
2061 frame->selection().revealSelection();
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002062 }
2063 } else if (renderer() && !renderer()->isWidget())
2064 renderer()->scrollRectToVisible(boundingBox());
2065}
2066
2067void Element::blur()
2068{
2069 cancelFocusAppearanceUpdate();
Torne (Richard Coles)8abfc582013-09-12 12:10:38 +01002070 if (treeScope().adjustedFocusedElement() == this) {
2071 Document& doc = document();
2072 if (doc.page())
2073 doc.page()->focusController().setFocusedElement(0, doc.frame());
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002074 else
Torne (Richard Coles)8abfc582013-09-12 12:10:38 +01002075 doc.setFocusedElement(0);
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002076 }
2077}
2078
Ben Murdochdf957042013-08-06 11:01:27 +01002079bool Element::isFocusable() const
2080{
2081 return inDocument() && supportsFocus() && !isInert() && rendererIsFocusable();
2082}
2083
Torne (Richard Coles)f5e4ad52013-08-05 13:57:57 +01002084bool Element::isKeyboardFocusable() const
2085{
2086 return isFocusable() && tabIndex() >= 0;
2087}
2088
2089bool Element::isMouseFocusable() const
2090{
2091 return isFocusable();
2092}
2093
Ben Murdoch02772c62013-07-26 10:21:05 +01002094void Element::dispatchFocusEvent(Element* oldFocusedElement, FocusDirection)
2095{
Torne (Richard Coles)8abfc582013-09-12 12:10:38 +01002096 RefPtr<FocusEvent> event = FocusEvent::create(eventNames().focusEvent, false, false, document().defaultView(), 0, oldFocusedElement);
Ben Murdoch02772c62013-07-26 10:21:05 +01002097 EventDispatcher::dispatchEvent(this, FocusEventDispatchMediator::create(event.release()));
2098}
2099
2100void Element::dispatchBlurEvent(Element* newFocusedElement)
2101{
Torne (Richard Coles)8abfc582013-09-12 12:10:38 +01002102 RefPtr<FocusEvent> event = FocusEvent::create(eventNames().blurEvent, false, false, document().defaultView(), 0, newFocusedElement);
Ben Murdoch02772c62013-07-26 10:21:05 +01002103 EventDispatcher::dispatchEvent(this, BlurEventDispatchMediator::create(event.release()));
2104}
2105
2106void Element::dispatchFocusInEvent(const AtomicString& eventType, Element* oldFocusedElement)
2107{
2108 ASSERT(!NoEventDispatchAssertion::isEventDispatchForbidden());
2109 ASSERT(eventType == eventNames().focusinEvent || eventType == eventNames().DOMFocusInEvent);
Torne (Richard Coles)8abfc582013-09-12 12:10:38 +01002110 dispatchScopedEventDispatchMediator(FocusInEventDispatchMediator::create(FocusEvent::create(eventType, true, false, document().defaultView(), 0, oldFocusedElement)));
Ben Murdoch02772c62013-07-26 10:21:05 +01002111}
2112
2113void Element::dispatchFocusOutEvent(const AtomicString& eventType, Element* newFocusedElement)
2114{
2115 ASSERT(!NoEventDispatchAssertion::isEventDispatchForbidden());
2116 ASSERT(eventType == eventNames().focusoutEvent || eventType == eventNames().DOMFocusOutEvent);
Torne (Richard Coles)8abfc582013-09-12 12:10:38 +01002117 dispatchScopedEventDispatchMediator(FocusOutEventDispatchMediator::create(FocusEvent::create(eventType, true, false, document().defaultView(), 0, newFocusedElement)));
Ben Murdoch02772c62013-07-26 10:21:05 +01002118}
2119
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002120String Element::innerText()
2121{
2122 // We need to update layout, since plainText uses line boxes in the render tree.
Torne (Richard Coles)8abfc582013-09-12 12:10:38 +01002123 document().updateLayoutIgnorePendingStylesheets();
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002124
2125 if (!renderer())
2126 return textContent(true);
2127
2128 return plainText(rangeOfContents(const_cast<Element*>(this)).get());
2129}
2130
2131String Element::outerText()
2132{
2133 // Getting outerText is the same as getting innerText, only
2134 // setting is different. You would think this should get the plain
2135 // text for the outer range, but this is wrong, <br> for instance
2136 // would return different values for inner and outer text by such
2137 // a rule, but it doesn't in WinIE, and we want to match that.
2138 return innerText();
2139}
2140
Ben Murdoch591b9582013-07-10 11:41:44 +01002141String Element::textFromChildren()
2142{
2143 Text* firstTextNode = 0;
2144 bool foundMultipleTextNodes = false;
2145 unsigned totalLength = 0;
2146
2147 for (Node* child = firstChild(); child; child = child->nextSibling()) {
2148 if (!child->isTextNode())
2149 continue;
2150 Text* text = toText(child);
2151 if (!firstTextNode)
2152 firstTextNode = text;
2153 else
2154 foundMultipleTextNodes = true;
2155 unsigned length = text->data().length();
2156 if (length > std::numeric_limits<unsigned>::max() - totalLength)
2157 return emptyString();
2158 totalLength += length;
2159 }
2160
2161 if (!firstTextNode)
2162 return emptyString();
2163
2164 if (firstTextNode && !foundMultipleTextNodes) {
2165 firstTextNode->atomize();
2166 return firstTextNode->data();
2167 }
2168
2169 StringBuilder content;
2170 content.reserveCapacity(totalLength);
2171 for (Node* child = firstTextNode; child; child = child->nextSibling()) {
2172 if (!child->isTextNode())
2173 continue;
2174 content.append(toText(child)->data());
2175 }
2176
2177 ASSERT(content.length() == totalLength);
2178 return content.toString();
2179}
2180
Ben Murdoch3c9e4ae2013-08-12 14:20:44 +01002181// pseudo is used via shadowPseudoId.
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002182const AtomicString& Element::pseudo() const
2183{
2184 return getAttribute(pseudoAttr);
2185}
2186
Torne (Richard Coles)f5e4ad52013-08-05 13:57:57 +01002187const AtomicString& Element::part() const
2188{
2189 return getAttribute(partAttr);
2190}
2191
2192void Element::setPart(const AtomicString& value)
2193{
2194 setAttribute(partAttr, value);
2195}
2196
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002197LayoutSize Element::minimumSizeForResizing() const
2198{
2199 return hasRareData() ? elementRareData()->minimumSizeForResizing() : defaultMinimumSizeForResizing();
2200}
2201
2202void Element::setMinimumSizeForResizing(const LayoutSize& size)
2203{
2204 if (!hasRareData() && size == defaultMinimumSizeForResizing())
2205 return;
2206 ensureElementRareData()->setMinimumSizeForResizing(size);
2207}
2208
2209RenderStyle* Element::computedStyle(PseudoId pseudoElementSpecifier)
2210{
2211 if (PseudoElement* element = pseudoElement(pseudoElementSpecifier))
2212 return element->computedStyle();
2213
2214 // FIXME: Find and use the renderer from the pseudo element instead of the actual element so that the 'length'
2215 // properties, which are only known by the renderer because it did the layout, will be correct and so that the
2216 // values returned for the ":selection" pseudo-element will be correct.
2217 if (RenderStyle* usedStyle = renderStyle()) {
2218 if (pseudoElementSpecifier) {
2219 RenderStyle* cachedPseudoStyle = usedStyle->getCachedPseudoStyle(pseudoElementSpecifier);
2220 return cachedPseudoStyle ? cachedPseudoStyle : usedStyle;
2221 } else
2222 return usedStyle;
2223 }
2224
2225 if (!attached())
2226 // FIXME: Try to do better than this. Ensure that styleForElement() works for elements that are not in the
2227 // document tree and figure out when to destroy the computed style for such elements.
2228 return 0;
2229
2230 ElementRareData* data = ensureElementRareData();
2231 if (!data->computedStyle())
Torne (Richard Coles)8abfc582013-09-12 12:10:38 +01002232 data->setComputedStyle(document().styleForElementIgnoringPendingStylesheets(this));
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002233 return pseudoElementSpecifier ? data->computedStyle()->getCachedPseudoStyle(pseudoElementSpecifier) : data->computedStyle();
2234}
2235
2236void Element::setStyleAffectedByEmpty()
2237{
2238 ensureElementRareData()->setStyleAffectedByEmpty(true);
2239}
2240
2241void Element::setChildrenAffectedByHover(bool value)
2242{
2243 if (value || hasRareData())
2244 ensureElementRareData()->setChildrenAffectedByHover(value);
2245}
2246
2247void Element::setChildrenAffectedByActive(bool value)
2248{
2249 if (value || hasRareData())
2250 ensureElementRareData()->setChildrenAffectedByActive(value);
2251}
2252
2253void Element::setChildrenAffectedByDrag(bool value)
2254{
2255 if (value || hasRareData())
2256 ensureElementRareData()->setChildrenAffectedByDrag(value);
2257}
2258
2259void Element::setChildrenAffectedByFirstChildRules()
2260{
2261 ensureElementRareData()->setChildrenAffectedByFirstChildRules(true);
2262}
2263
2264void Element::setChildrenAffectedByLastChildRules()
2265{
2266 ensureElementRareData()->setChildrenAffectedByLastChildRules(true);
2267}
2268
2269void Element::setChildrenAffectedByDirectAdjacentRules()
2270{
2271 ensureElementRareData()->setChildrenAffectedByDirectAdjacentRules(true);
2272}
2273
2274void Element::setChildrenAffectedByForwardPositionalRules()
2275{
2276 ensureElementRareData()->setChildrenAffectedByForwardPositionalRules(true);
2277}
2278
2279void Element::setChildrenAffectedByBackwardPositionalRules()
2280{
2281 ensureElementRareData()->setChildrenAffectedByBackwardPositionalRules(true);
2282}
2283
2284void Element::setChildIndex(unsigned index)
2285{
2286 ElementRareData* rareData = ensureElementRareData();
2287 if (RenderStyle* style = renderStyle())
2288 style->setUnique();
2289 rareData->setChildIndex(index);
2290}
2291
2292bool Element::hasFlagsSetDuringStylingOfChildren() const
2293{
2294 if (!hasRareData())
2295 return false;
2296 return rareDataChildrenAffectedByHover()
2297 || rareDataChildrenAffectedByActive()
2298 || rareDataChildrenAffectedByDrag()
2299 || rareDataChildrenAffectedByFirstChildRules()
2300 || rareDataChildrenAffectedByLastChildRules()
2301 || rareDataChildrenAffectedByDirectAdjacentRules()
2302 || rareDataChildrenAffectedByForwardPositionalRules()
2303 || rareDataChildrenAffectedByBackwardPositionalRules();
2304}
2305
2306bool Element::rareDataStyleAffectedByEmpty() const
2307{
2308 ASSERT(hasRareData());
2309 return elementRareData()->styleAffectedByEmpty();
2310}
2311
2312bool Element::rareDataChildrenAffectedByHover() const
2313{
2314 ASSERT(hasRareData());
2315 return elementRareData()->childrenAffectedByHover();
2316}
2317
2318bool Element::rareDataChildrenAffectedByActive() const
2319{
2320 ASSERT(hasRareData());
2321 return elementRareData()->childrenAffectedByActive();
2322}
2323
2324bool Element::rareDataChildrenAffectedByDrag() const
2325{
2326 ASSERT(hasRareData());
2327 return elementRareData()->childrenAffectedByDrag();
2328}
2329
2330bool Element::rareDataChildrenAffectedByFirstChildRules() const
2331{
2332 ASSERT(hasRareData());
2333 return elementRareData()->childrenAffectedByFirstChildRules();
2334}
2335
2336bool Element::rareDataChildrenAffectedByLastChildRules() const
2337{
2338 ASSERT(hasRareData());
2339 return elementRareData()->childrenAffectedByLastChildRules();
2340}
2341
2342bool Element::rareDataChildrenAffectedByDirectAdjacentRules() const
2343{
2344 ASSERT(hasRareData());
2345 return elementRareData()->childrenAffectedByDirectAdjacentRules();
2346}
2347
2348bool Element::rareDataChildrenAffectedByForwardPositionalRules() const
2349{
2350 ASSERT(hasRareData());
2351 return elementRareData()->childrenAffectedByForwardPositionalRules();
2352}
2353
2354bool Element::rareDataChildrenAffectedByBackwardPositionalRules() const
2355{
2356 ASSERT(hasRareData());
2357 return elementRareData()->childrenAffectedByBackwardPositionalRules();
2358}
2359
2360unsigned Element::rareDataChildIndex() const
2361{
2362 ASSERT(hasRareData());
2363 return elementRareData()->childIndex();
2364}
2365
2366void Element::setIsInCanvasSubtree(bool isInCanvasSubtree)
2367{
2368 ensureElementRareData()->setIsInCanvasSubtree(isInCanvasSubtree);
2369}
2370
2371bool Element::isInCanvasSubtree() const
2372{
2373 return hasRareData() && elementRareData()->isInCanvasSubtree();
2374}
2375
Ben Murdoch591b9582013-07-10 11:41:44 +01002376void Element::setIsInsideRegion(bool value)
2377{
2378 if (value == isInsideRegion())
2379 return;
2380
2381 ensureElementRareData()->setIsInsideRegion(value);
2382}
2383
2384bool Element::isInsideRegion() const
2385{
2386 return hasRareData() ? elementRareData()->isInsideRegion() : false;
2387}
2388
2389void Element::setRegionOversetState(RegionOversetState state)
2390{
2391 ensureElementRareData()->setRegionOversetState(state);
2392}
2393
2394RegionOversetState Element::regionOversetState() const
2395{
2396 return hasRareData() ? elementRareData()->regionOversetState() : RegionUndefined;
2397}
2398
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002399AtomicString Element::computeInheritedLanguage() const
2400{
2401 const Node* n = this;
2402 AtomicString value;
2403 // The language property is inherited, so we iterate over the parents to find the first language.
2404 do {
2405 if (n->isElementNode()) {
2406 if (const ElementData* elementData = toElement(n)->elementData()) {
2407 // Spec: xml:lang takes precedence -- http://www.w3.org/TR/xhtml1/#C_7
2408 if (const Attribute* attribute = elementData->getAttributeItem(XMLNames::langAttr))
2409 value = attribute->value();
2410 else if (const Attribute* attribute = elementData->getAttributeItem(HTMLNames::langAttr))
2411 value = attribute->value();
2412 }
2413 } else if (n->isDocumentNode()) {
2414 // checking the MIME content-language
2415 value = toDocument(n)->contentLanguage();
2416 }
2417
2418 n = n->parentNode();
2419 } while (n && value.isNull());
2420
2421 return value;
2422}
2423
2424Locale& Element::locale() const
2425{
Torne (Richard Coles)8abfc582013-09-12 12:10:38 +01002426 return document().getCachedLocale(computeInheritedLanguage());
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002427}
2428
2429void Element::cancelFocusAppearanceUpdate()
2430{
2431 if (hasRareData())
2432 elementRareData()->setNeedsFocusAppearanceUpdateSoonAfterAttach(false);
Torne (Richard Coles)8abfc582013-09-12 12:10:38 +01002433 if (document().focusedElement() == this)
2434 document().cancelFocusAppearanceUpdate();
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002435}
2436
2437void Element::normalizeAttributes()
2438{
2439 if (!hasAttributes())
2440 return;
2441 for (unsigned i = 0; i < attributeCount(); ++i) {
2442 if (RefPtr<Attr> attr = attrIfExists(attributeItem(i)->name()))
2443 attr->normalize();
2444 }
2445}
2446
Torne (Richard Coles)8abfc582013-09-12 12:10:38 +01002447void Element::updatePseudoElement(PseudoId pseudoId, StyleRecalcChange change)
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002448{
2449 PseudoElement* element = pseudoElement(pseudoId);
2450 if (element && (needsStyleRecalc() || shouldRecalcStyle(change, element))) {
2451 // PseudoElement styles hang off their parent element's style so if we needed
2452 // a style recalc we should Force one on the pseudo.
2453 element->recalcStyle(needsStyleRecalc() ? Force : change);
2454
2455 // Wait until our parent is not displayed or pseudoElementRendererIsNeeded
2456 // is false, otherwise we could continously create and destroy PseudoElements
2457 // when RenderObject::isChildAllowed on our parent returns false for the
2458 // PseudoElement's renderer for each style recalc.
2459 if (!renderer() || !pseudoElementRendererIsNeeded(renderer()->getCachedPseudoStyle(pseudoId)))
Torne (Richard Coles)521d96e2013-06-19 11:58:24 +01002460 elementRareData()->setPseudoElement(pseudoId, 0);
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002461 } else if (change >= Inherit || needsStyleRecalc())
2462 createPseudoElementIfNeeded(pseudoId);
2463}
2464
2465void Element::createPseudoElementIfNeeded(PseudoId pseudoId)
2466{
Torne (Richard Coles)9bbd2f52013-09-19 22:37:05 +01002467 if (needsPseudoElement(pseudoId))
2468 createPseudoElement(pseudoId);
2469}
2470
2471bool Element::needsPseudoElement(PseudoId pseudoId) const
2472{
Ben Murdoche69819b2013-07-17 14:56:49 +01002473 if (pseudoId == BACKDROP && !isInTopLayer())
Torne (Richard Coles)9bbd2f52013-09-19 22:37:05 +01002474 return false;
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002475 if (!renderer() || !pseudoElementRendererIsNeeded(renderer()->getCachedPseudoStyle(pseudoId)))
Torne (Richard Coles)9bbd2f52013-09-19 22:37:05 +01002476 return false;
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002477 if (!renderer()->canHaveGeneratedChildren())
Torne (Richard Coles)9bbd2f52013-09-19 22:37:05 +01002478 return false;
2479 return true;
2480}
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002481
Torne (Richard Coles)9bbd2f52013-09-19 22:37:05 +01002482void Element::createPseudoElement(PseudoId pseudoId)
2483{
2484 ASSERT(needsPseudoElement(pseudoId));
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002485 ASSERT(!isPseudoElement());
2486 RefPtr<PseudoElement> element = PseudoElement::create(this, pseudoId);
Ben Murdoche69819b2013-07-17 14:56:49 +01002487 if (pseudoId == BACKDROP)
Torne (Richard Coles)8abfc582013-09-12 12:10:38 +01002488 document().addToTopLayer(element.get(), this);
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002489 element->attach();
Ben Murdoche69819b2013-07-17 14:56:49 +01002490
Torne (Richard Coles)521d96e2013-06-19 11:58:24 +01002491 ensureElementRareData()->setPseudoElement(pseudoId, element.release());
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002492}
2493
2494PseudoElement* Element::pseudoElement(PseudoId pseudoId) const
2495{
2496 return hasRareData() ? elementRareData()->pseudoElement(pseudoId) : 0;
2497}
2498
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002499RenderObject* Element::pseudoElementRenderer(PseudoId pseudoId) const
2500{
2501 if (PseudoElement* element = pseudoElement(pseudoId))
2502 return element->renderer();
2503 return 0;
2504}
2505
Ben Murdochdf957042013-08-06 11:01:27 +01002506bool Element::webkitMatchesSelector(const String& selector, ExceptionState& es)
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002507{
2508 if (selector.isEmpty()) {
Torne (Richard Coles)06f816c2013-09-26 13:25:12 +01002509 es.throwUninformativeAndGenericDOMException(SyntaxError);
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002510 return false;
2511 }
2512
Torne (Richard Coles)8abfc582013-09-12 12:10:38 +01002513 SelectorQuery* selectorQuery = document().selectorQueryCache()->add(selector, document(), es);
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002514 if (!selectorQuery)
2515 return false;
2516 return selectorQuery->matches(this);
2517}
2518
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002519DOMTokenList* Element::classList()
2520{
2521 ElementRareData* data = ensureElementRareData();
2522 if (!data->classList())
2523 data->setClassList(ClassList::create(this));
2524 return data->classList();
2525}
2526
2527DOMStringMap* Element::dataset()
2528{
2529 ElementRareData* data = ensureElementRareData();
2530 if (!data->dataset())
2531 data->setDataset(DatasetDOMStringMap::create(this));
2532 return data->dataset();
2533}
2534
2535KURL Element::getURLAttribute(const QualifiedName& name) const
2536{
2537#if !ASSERT_DISABLED
2538 if (elementData()) {
2539 if (const Attribute* attribute = getAttributeItem(name))
2540 ASSERT(isURLAttribute(*attribute));
2541 }
2542#endif
Torne (Richard Coles)8abfc582013-09-12 12:10:38 +01002543 return document().completeURL(stripLeadingAndTrailingHTMLSpaces(getAttribute(name)));
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002544}
2545
2546KURL Element::getNonEmptyURLAttribute(const QualifiedName& name) const
2547{
2548#if !ASSERT_DISABLED
2549 if (elementData()) {
2550 if (const Attribute* attribute = getAttributeItem(name))
2551 ASSERT(isURLAttribute(*attribute));
2552 }
2553#endif
2554 String value = stripLeadingAndTrailingHTMLSpaces(getAttribute(name));
2555 if (value.isEmpty())
2556 return KURL();
Torne (Richard Coles)8abfc582013-09-12 12:10:38 +01002557 return document().completeURL(value);
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002558}
2559
2560int Element::getIntegralAttribute(const QualifiedName& attributeName) const
2561{
2562 return getAttribute(attributeName).string().toInt();
2563}
2564
2565void Element::setIntegralAttribute(const QualifiedName& attributeName, int value)
2566{
2567 // FIXME: Need an AtomicString version of String::number.
2568 setAttribute(attributeName, String::number(value));
2569}
2570
2571unsigned Element::getUnsignedIntegralAttribute(const QualifiedName& attributeName) const
2572{
2573 return getAttribute(attributeName).string().toUInt();
2574}
2575
2576void Element::setUnsignedIntegralAttribute(const QualifiedName& attributeName, unsigned value)
2577{
2578 // FIXME: Need an AtomicString version of String::number.
2579 setAttribute(attributeName, String::number(value));
2580}
2581
Torne (Richard Coles)8abfc582013-09-12 12:10:38 +01002582bool Element::childShouldCreateRenderer(const Node& child) const
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002583{
2584 // Only create renderers for SVG elements whose parents are SVG elements, or for proper <svg xmlns="svgNS"> subdocuments.
Torne (Richard Coles)8abfc582013-09-12 12:10:38 +01002585 if (child.isSVGElement())
2586 return child.hasTagName(SVGNames::svgTag) || isSVGElement();
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002587
Torne (Richard Coles)8abfc582013-09-12 12:10:38 +01002588 return ContainerNode::childShouldCreateRenderer(child);
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002589}
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002590
2591void Element::webkitRequestFullscreen()
2592{
Torne (Richard Coles)8abfc582013-09-12 12:10:38 +01002593 FullscreenElementStack::from(&document())->requestFullScreenForElement(this, ALLOW_KEYBOARD_INPUT, FullscreenElementStack::EnforceIFrameAllowFullScreenRequirement);
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002594}
2595
2596void Element::webkitRequestFullScreen(unsigned short flags)
2597{
Torne (Richard Coles)8abfc582013-09-12 12:10:38 +01002598 FullscreenElementStack::from(&document())->requestFullScreenForElement(this, (flags | LEGACY_MOZILLA_REQUEST), FullscreenElementStack::EnforceIFrameAllowFullScreenRequirement);
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002599}
2600
2601bool Element::containsFullScreenElement() const
2602{
2603 return hasRareData() && elementRareData()->containsFullScreenElement();
2604}
2605
2606void Element::setContainsFullScreenElement(bool flag)
2607{
2608 ensureElementRareData()->setContainsFullScreenElement(flag);
Ben Murdoche69819b2013-07-17 14:56:49 +01002609 setNeedsStyleRecalc(SubtreeStyleChange);
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002610}
2611
2612static Element* parentCrossingFrameBoundaries(Element* element)
2613{
2614 ASSERT(element);
Torne (Richard Coles)8abfc582013-09-12 12:10:38 +01002615 return element->parentElement() ? element->parentElement() : element->document().ownerElement();
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002616}
2617
2618void Element::setContainsFullScreenElementOnAncestorsCrossingFrameBoundaries(bool flag)
2619{
2620 Element* element = this;
2621 while ((element = parentCrossingFrameBoundaries(element)))
2622 element->setContainsFullScreenElement(flag);
2623}
2624
2625bool Element::isInTopLayer() const
2626{
2627 return hasRareData() && elementRareData()->isInTopLayer();
2628}
2629
2630void Element::setIsInTopLayer(bool inTopLayer)
2631{
2632 if (isInTopLayer() == inTopLayer)
2633 return;
2634 ensureElementRareData()->setIsInTopLayer(inTopLayer);
2635
2636 // We must ensure a reattach occurs so the renderer is inserted in the correct sibling order under RenderView according to its
2637 // top layer position, or in its usual place if not in the top layer.
Torne (Richard Coles)93ac45c2013-05-29 14:40:20 +01002638 lazyReattachIfAttached();
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002639}
2640
2641void Element::webkitRequestPointerLock()
2642{
Torne (Richard Coles)8abfc582013-09-12 12:10:38 +01002643 if (document().page())
2644 document().page()->pointerLockController().requestPointerLock(this);
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002645}
2646
2647SpellcheckAttributeState Element::spellcheckAttributeState() const
2648{
2649 const AtomicString& value = getAttribute(HTMLNames::spellcheckAttr);
2650 if (value == nullAtom)
2651 return SpellcheckAttributeDefault;
2652 if (equalIgnoringCase(value, "true") || equalIgnoringCase(value, ""))
2653 return SpellcheckAttributeTrue;
2654 if (equalIgnoringCase(value, "false"))
2655 return SpellcheckAttributeFalse;
2656
2657 return SpellcheckAttributeDefault;
2658}
2659
2660bool Element::isSpellCheckingEnabled() const
2661{
2662 for (const Element* element = this; element; element = element->parentOrShadowHostElement()) {
2663 switch (element->spellcheckAttributeState()) {
2664 case SpellcheckAttributeTrue:
2665 return true;
2666 case SpellcheckAttributeFalse:
2667 return false;
2668 case SpellcheckAttributeDefault:
2669 break;
2670 }
2671 }
2672
2673 return true;
2674}
2675
2676RenderRegion* Element::renderRegion() const
2677{
2678 if (renderer() && renderer()->isRenderRegion())
2679 return toRenderRegion(renderer());
2680
2681 return 0;
2682}
2683
Ben Murdoch591b9582013-07-10 11:41:44 +01002684bool Element::shouldMoveToFlowThread(RenderStyle* styleToUse) const
2685{
2686 ASSERT(styleToUse);
2687
Torne (Richard Coles)f5e4ad52013-08-05 13:57:57 +01002688 if (FullscreenElementStack::isActiveFullScreenElement(this))
Ben Murdoch591b9582013-07-10 11:41:44 +01002689 return false;
2690
2691 if (isInShadowTree())
2692 return false;
2693
2694 if (styleToUse->flowThread().isEmpty())
2695 return false;
2696
2697 return !isRegisteredWithNamedFlow();
2698}
2699
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002700const AtomicString& Element::webkitRegionOverset() const
2701{
Torne (Richard Coles)8abfc582013-09-12 12:10:38 +01002702 document().updateLayoutIgnorePendingStylesheets();
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002703
2704 DEFINE_STATIC_LOCAL(AtomicString, undefinedState, ("undefined", AtomicString::ConstructFromLiteral));
2705 if (!RuntimeEnabledFeatures::cssRegionsEnabled() || !renderRegion())
2706 return undefinedState;
2707
Ben Murdoch591b9582013-07-10 11:41:44 +01002708 switch (renderRegion()->regionOversetState()) {
2709 case RegionFit: {
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002710 DEFINE_STATIC_LOCAL(AtomicString, fitState, ("fit", AtomicString::ConstructFromLiteral));
2711 return fitState;
2712 }
Ben Murdoch591b9582013-07-10 11:41:44 +01002713 case RegionEmpty: {
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002714 DEFINE_STATIC_LOCAL(AtomicString, emptyState, ("empty", AtomicString::ConstructFromLiteral));
2715 return emptyState;
2716 }
Ben Murdoch591b9582013-07-10 11:41:44 +01002717 case RegionOverset: {
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002718 DEFINE_STATIC_LOCAL(AtomicString, overflowState, ("overset", AtomicString::ConstructFromLiteral));
2719 return overflowState;
2720 }
Ben Murdoch591b9582013-07-10 11:41:44 +01002721 case RegionUndefined:
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002722 return undefinedState;
2723 }
2724
2725 ASSERT_NOT_REACHED();
2726 return undefinedState;
2727}
2728
2729Vector<RefPtr<Range> > Element::webkitGetRegionFlowRanges() const
2730{
Torne (Richard Coles)8abfc582013-09-12 12:10:38 +01002731 document().updateLayoutIgnorePendingStylesheets();
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002732
2733 Vector<RefPtr<Range> > rangeObjects;
2734 if (RuntimeEnabledFeatures::cssRegionsEnabled() && renderer() && renderer()->isRenderRegion()) {
2735 RenderRegion* region = toRenderRegion(renderer());
2736 if (region->isValid())
2737 region->getRanges(rangeObjects);
2738 }
2739
2740 return rangeObjects;
2741}
2742
2743#ifndef NDEBUG
2744bool Element::fastAttributeLookupAllowed(const QualifiedName& name) const
2745{
2746 if (name == HTMLNames::styleAttr)
2747 return false;
2748
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002749 if (isSVGElement())
2750 return !static_cast<const SVGElement*>(this)->isAnimatableAttribute(name);
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002751
2752 return true;
2753}
2754#endif
2755
2756#ifdef DUMP_NODE_STATISTICS
2757bool Element::hasNamedNodeMap() const
2758{
2759 return hasRareData() && elementRareData()->attributeMap();
2760}
2761#endif
2762
Ben Murdoch00d3faa2013-08-14 11:52:03 +01002763inline void Element::updateName(const AtomicString& oldName, const AtomicString& newName)
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002764{
Ben Murdoch00d3faa2013-08-14 11:52:03 +01002765 if (!inDocument() || isInShadowTree())
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002766 return;
2767
2768 if (oldName == newName)
2769 return;
2770
Ben Murdochdf957042013-08-06 11:01:27 +01002771 if (shouldRegisterAsNamedItem())
2772 updateNamedItemRegistration(oldName, newName);
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002773}
2774
Ben Murdoch00d3faa2013-08-14 11:52:03 +01002775inline void Element::updateId(const AtomicString& oldId, const AtomicString& newId)
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002776{
2777 if (!isInTreeScope())
2778 return;
2779
2780 if (oldId == newId)
2781 return;
2782
Ben Murdoch00d3faa2013-08-14 11:52:03 +01002783 updateId(treeScope(), oldId, newId);
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002784}
2785
Torne (Richard Coles)8abfc582013-09-12 12:10:38 +01002786inline void Element::updateId(TreeScope& scope, const AtomicString& oldId, const AtomicString& newId)
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002787{
2788 ASSERT(isInTreeScope());
2789 ASSERT(oldId != newId);
2790
2791 if (!oldId.isEmpty())
Torne (Richard Coles)8abfc582013-09-12 12:10:38 +01002792 scope.removeElementById(oldId, this);
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002793 if (!newId.isEmpty())
Torne (Richard Coles)8abfc582013-09-12 12:10:38 +01002794 scope.addElementById(newId, this);
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002795
Ben Murdochdf957042013-08-06 11:01:27 +01002796 if (shouldRegisterAsExtraNamedItem())
2797 updateExtraNamedItemRegistration(oldId, newId);
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002798}
2799
Torne (Richard Coles)8abfc582013-09-12 12:10:38 +01002800void Element::updateLabel(TreeScope& scope, const AtomicString& oldForAttributeValue, const AtomicString& newForAttributeValue)
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002801{
2802 ASSERT(hasTagName(labelTag));
2803
2804 if (!inDocument())
2805 return;
2806
2807 if (oldForAttributeValue == newForAttributeValue)
2808 return;
2809
2810 if (!oldForAttributeValue.isEmpty())
Torne (Richard Coles)8abfc582013-09-12 12:10:38 +01002811 scope.removeLabel(oldForAttributeValue, toHTMLLabelElement(this));
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002812 if (!newForAttributeValue.isEmpty())
Torne (Richard Coles)8abfc582013-09-12 12:10:38 +01002813 scope.addLabel(newForAttributeValue, toHTMLLabelElement(this));
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002814}
2815
Ben Murdoch7757ec22013-07-23 11:17:36 +01002816static bool hasSelectorForAttribute(Document* document, const AtomicString& localName)
2817{
2818 return document->styleResolver() && document->styleResolver()->ruleFeatureSet().hasSelectorForAttribute(localName);
2819}
2820
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002821void Element::willModifyAttribute(const QualifiedName& name, const AtomicString& oldValue, const AtomicString& newValue)
2822{
2823 if (isIdAttributeName(name))
2824 updateId(oldValue, newValue);
2825 else if (name == HTMLNames::nameAttr)
2826 updateName(oldValue, newValue);
2827 else if (name == HTMLNames::forAttr && hasTagName(labelTag)) {
Torne (Richard Coles)8abfc582013-09-12 12:10:38 +01002828 TreeScope& scope = treeScope();
2829 if (scope.shouldCacheLabelsByForAttribute())
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002830 updateLabel(scope, oldValue, newValue);
2831 }
2832
2833 if (oldValue != newValue) {
Torne (Richard Coles)8abfc582013-09-12 12:10:38 +01002834 if (attached() && hasSelectorForAttribute(&document(), name.localName()))
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002835 setNeedsStyleRecalc();
Ben Murdoche69819b2013-07-17 14:56:49 +01002836
2837 if (isUpgradedCustomElement())
Ben Murdoch83750172013-07-24 10:36:59 +01002838 CustomElement::attributeDidChange(this, name.localName(), oldValue, newValue);
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002839 }
2840
2841 if (OwnPtr<MutationObserverInterestGroup> recipients = MutationObserverInterestGroup::createForAttributesMutation(this, name))
2842 recipients->enqueueMutationRecord(MutationRecord::createAttributes(this, name, oldValue));
2843
Torne (Richard Coles)8abfc582013-09-12 12:10:38 +01002844 InspectorInstrumentation::willModifyDOMAttr(&document(), this, oldValue, newValue);
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002845}
2846
2847void Element::didAddAttribute(const QualifiedName& name, const AtomicString& value)
2848{
2849 attributeChanged(name, value);
Torne (Richard Coles)8abfc582013-09-12 12:10:38 +01002850 InspectorInstrumentation::didModifyDOMAttr(&document(), this, name.localName(), value);
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002851 dispatchSubtreeModifiedEvent();
2852}
2853
2854void Element::didModifyAttribute(const QualifiedName& name, const AtomicString& value)
2855{
2856 attributeChanged(name, value);
Torne (Richard Coles)8abfc582013-09-12 12:10:38 +01002857 InspectorInstrumentation::didModifyDOMAttr(&document(), this, name.localName(), value);
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002858 // Do not dispatch a DOMSubtreeModified event here; see bug 81141.
2859}
2860
2861void Element::didRemoveAttribute(const QualifiedName& name)
2862{
2863 attributeChanged(name, nullAtom);
Torne (Richard Coles)8abfc582013-09-12 12:10:38 +01002864 InspectorInstrumentation::didRemoveDOMAttr(&document(), this, name.localName());
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002865 dispatchSubtreeModifiedEvent();
2866}
2867
Ben Murdoche69819b2013-07-17 14:56:49 +01002868void Element::didMoveToNewDocument(Document* oldDocument)
2869{
2870 Node::didMoveToNewDocument(oldDocument);
2871
2872 // If the documents differ by quirks mode then they differ by case sensitivity
2873 // for class and id names so we need to go through the attribute change logic
2874 // to pick up the new casing in the ElementData.
Torne (Richard Coles)8abfc582013-09-12 12:10:38 +01002875 if (oldDocument->inQuirksMode() != document().inQuirksMode()) {
Ben Murdoche69819b2013-07-17 14:56:49 +01002876 if (hasID())
2877 setIdAttribute(getIdAttribute());
2878 if (hasClass())
2879 setAttribute(HTMLNames::classAttr, getClassAttribute());
2880 }
2881}
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002882
Ben Murdochdf957042013-08-06 11:01:27 +01002883void Element::updateNamedItemRegistration(const AtomicString& oldName, const AtomicString& newName)
2884{
Torne (Richard Coles)8abfc582013-09-12 12:10:38 +01002885 if (!document().isHTMLDocument())
Ben Murdoch00d3faa2013-08-14 11:52:03 +01002886 return;
Ben Murdochdf957042013-08-06 11:01:27 +01002887
2888 if (!oldName.isEmpty())
Torne (Richard Coles)8abfc582013-09-12 12:10:38 +01002889 toHTMLDocument(document()).removeNamedItem(oldName);
Ben Murdochdf957042013-08-06 11:01:27 +01002890
2891 if (!newName.isEmpty())
Torne (Richard Coles)8abfc582013-09-12 12:10:38 +01002892 toHTMLDocument(document()).addNamedItem(newName);
Ben Murdochdf957042013-08-06 11:01:27 +01002893}
2894
2895void Element::updateExtraNamedItemRegistration(const AtomicString& oldId, const AtomicString& newId)
2896{
Torne (Richard Coles)8abfc582013-09-12 12:10:38 +01002897 if (!document().isHTMLDocument())
Ben Murdoch00d3faa2013-08-14 11:52:03 +01002898 return;
Ben Murdochdf957042013-08-06 11:01:27 +01002899
2900 if (!oldId.isEmpty())
Torne (Richard Coles)8abfc582013-09-12 12:10:38 +01002901 toHTMLDocument(document()).removeExtraNamedItem(oldId);
Ben Murdochdf957042013-08-06 11:01:27 +01002902
2903 if (!newId.isEmpty())
Torne (Richard Coles)8abfc582013-09-12 12:10:38 +01002904 toHTMLDocument(document()).addExtraNamedItem(newId);
Ben Murdochdf957042013-08-06 11:01:27 +01002905}
2906
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002907PassRefPtr<HTMLCollection> Element::ensureCachedHTMLCollection(CollectionType type)
2908{
2909 if (HTMLCollection* collection = cachedHTMLCollection(type))
2910 return collection;
2911
2912 RefPtr<HTMLCollection> collection;
2913 if (type == TableRows) {
2914 ASSERT(hasTagName(tableTag));
2915 return ensureRareData()->ensureNodeLists()->addCacheWithAtomicName<HTMLTableRowsCollection>(this, type);
2916 } else if (type == SelectOptions) {
2917 ASSERT(hasTagName(selectTag));
2918 return ensureRareData()->ensureNodeLists()->addCacheWithAtomicName<HTMLOptionsCollection>(this, type);
2919 } else if (type == FormControls) {
2920 ASSERT(hasTagName(formTag) || hasTagName(fieldsetTag));
2921 return ensureRareData()->ensureNodeLists()->addCacheWithAtomicName<HTMLFormControlsCollection>(this, type);
2922 }
2923 return ensureRareData()->ensureNodeLists()->addCacheWithAtomicName<HTMLCollection>(this, type);
2924}
2925
Ben Murdoch591b9582013-07-10 11:41:44 +01002926static void scheduleLayerUpdateCallback(Node* node)
Torne (Richard Coles)93ac45c2013-05-29 14:40:20 +01002927{
Ben Murdoche69819b2013-07-17 14:56:49 +01002928 // Notify the renderer even is the styles are identical since it may need to
2929 // create or destroy a RenderLayer.
2930 node->setNeedsStyleRecalc(LocalStyleChange, StyleChangeFromRenderer);
Torne (Richard Coles)93ac45c2013-05-29 14:40:20 +01002931}
2932
Ben Murdoch591b9582013-07-10 11:41:44 +01002933void Element::scheduleLayerUpdate()
Torne (Richard Coles)93ac45c2013-05-29 14:40:20 +01002934{
Torne (Richard Coles)8abfc582013-09-12 12:10:38 +01002935 if (document().inStyleRecalc())
2936 PostAttachCallbacks::queueCallback(scheduleLayerUpdateCallback, this);
Torne (Richard Coles)93ac45c2013-05-29 14:40:20 +01002937 else
Ben Murdoche69819b2013-07-17 14:56:49 +01002938 scheduleLayerUpdateCallback(this);
Torne (Richard Coles)93ac45c2013-05-29 14:40:20 +01002939}
2940
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002941HTMLCollection* Element::cachedHTMLCollection(CollectionType type)
2942{
2943 return hasRareData() && rareData()->nodeLists() ? rareData()->nodeLists()->cacheWithAtomicName<HTMLCollection>(type) : 0;
2944}
2945
2946IntSize Element::savedLayerScrollOffset() const
2947{
2948 return hasRareData() ? elementRareData()->savedLayerScrollOffset() : IntSize();
2949}
2950
2951void Element::setSavedLayerScrollOffset(const IntSize& size)
2952{
2953 if (size.isZero() && !hasRareData())
2954 return;
2955 ensureElementRareData()->setSavedLayerScrollOffset(size);
2956}
2957
2958PassRefPtr<Attr> Element::attrIfExists(const QualifiedName& name)
2959{
2960 if (AttrNodeList* attrNodeList = attrNodeListForElement(this))
2961 return findAttrNodeInList(attrNodeList, name);
2962 return 0;
2963}
2964
2965PassRefPtr<Attr> Element::ensureAttr(const QualifiedName& name)
2966{
2967 AttrNodeList* attrNodeList = ensureAttrNodeListForElement(this);
2968 RefPtr<Attr> attrNode = findAttrNodeInList(attrNodeList, name);
2969 if (!attrNode) {
Torne (Richard Coles)8abfc582013-09-12 12:10:38 +01002970 attrNode = Attr::create(*this, name);
2971 treeScope().adoptIfNeeded(attrNode.get());
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002972 attrNodeList->append(attrNode);
2973 }
2974 return attrNode.release();
2975}
2976
2977void Element::detachAttrNodeFromElementWithValue(Attr* attrNode, const AtomicString& value)
2978{
2979 ASSERT(hasSyntheticAttrChildNodes());
2980 attrNode->detachFromElementWithValue(value);
2981
2982 AttrNodeList* attrNodeList = attrNodeListForElement(this);
2983 for (unsigned i = 0; i < attrNodeList->size(); ++i) {
2984 if (attrNodeList->at(i)->qualifiedName() == attrNode->qualifiedName()) {
2985 attrNodeList->remove(i);
2986 if (attrNodeList->isEmpty())
2987 removeAttrNodeListForElement(this);
2988 return;
2989 }
2990 }
2991 ASSERT_NOT_REACHED();
2992}
2993
2994void Element::detachAllAttrNodesFromElement()
2995{
2996 AttrNodeList* attrNodeList = attrNodeListForElement(this);
2997 ASSERT(attrNodeList);
2998
2999 for (unsigned i = 0; i < attributeCount(); ++i) {
3000 const Attribute* attribute = attributeItem(i);
3001 if (RefPtr<Attr> attrNode = findAttrNodeInList(attrNodeList, attribute->name()))
3002 attrNode->detachFromElementWithValue(attribute->value());
3003 }
3004
3005 removeAttrNodeListForElement(this);
3006}
3007
Torne (Richard Coles)8abfc582013-09-12 12:10:38 +01003008void Element::willRecalcStyle(StyleRecalcChange)
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01003009{
3010 ASSERT(hasCustomStyleCallbacks());
3011}
3012
Torne (Richard Coles)8abfc582013-09-12 12:10:38 +01003013void Element::didRecalcStyle(StyleRecalcChange)
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01003014{
3015 ASSERT(hasCustomStyleCallbacks());
3016}
3017
3018
3019PassRefPtr<RenderStyle> Element::customStyleForRenderer()
3020{
3021 ASSERT(hasCustomStyleCallbacks());
3022 return 0;
3023}
3024
3025void Element::cloneAttributesFromElement(const Element& other)
3026{
3027 if (hasSyntheticAttrChildNodes())
3028 detachAllAttrNodesFromElement();
3029
3030 other.synchronizeAllAttributes();
3031 if (!other.m_elementData) {
3032 m_elementData.clear();
3033 return;
3034 }
3035
3036 const AtomicString& oldID = getIdAttribute();
3037 const AtomicString& newID = other.getIdAttribute();
3038
3039 if (!oldID.isNull() || !newID.isNull())
3040 updateId(oldID, newID);
3041
3042 const AtomicString& oldName = getNameAttribute();
3043 const AtomicString& newName = other.getNameAttribute();
3044
3045 if (!oldName.isNull() || !newName.isNull())
3046 updateName(oldName, newName);
3047
Ben Murdoche69819b2013-07-17 14:56:49 +01003048 // Quirks mode makes class and id not case sensitive. We can't share the ElementData
3049 // if the idForStyleResolution and the className need different casing.
3050 bool ownerDocumentsHaveDifferentCaseSensitivity = false;
3051 if (other.hasClass() || other.hasID())
Torne (Richard Coles)8abfc582013-09-12 12:10:38 +01003052 ownerDocumentsHaveDifferentCaseSensitivity = other.document().inQuirksMode() != document().inQuirksMode();
Ben Murdoche69819b2013-07-17 14:56:49 +01003053
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01003054 // 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 +01003055 // We can only do this if there is no CSSOM wrapper for other's inline style, and there are no presentation attributes,
3056 // and sharing the data won't result in different case sensitivity of class or id.
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01003057 if (other.m_elementData->isUnique()
Ben Murdoche69819b2013-07-17 14:56:49 +01003058 && !ownerDocumentsHaveDifferentCaseSensitivity
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01003059 && !other.m_elementData->presentationAttributeStyle()
3060 && (!other.m_elementData->inlineStyle() || !other.m_elementData->inlineStyle()->hasCSSOMWrapper()))
3061 const_cast<Element&>(other).m_elementData = static_cast<const UniqueElementData*>(other.m_elementData.get())->makeShareableCopy();
3062
Ben Murdoche69819b2013-07-17 14:56:49 +01003063 if (!other.m_elementData->isUnique() && !ownerDocumentsHaveDifferentCaseSensitivity)
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01003064 m_elementData = other.m_elementData;
3065 else
3066 m_elementData = other.m_elementData->makeUniqueCopy();
3067
3068 for (unsigned i = 0; i < m_elementData->length(); ++i) {
3069 const Attribute* attribute = const_cast<const ElementData*>(m_elementData.get())->attributeItem(i);
3070 attributeChangedFromParserOrByCloning(attribute->name(), attribute->value(), ModifiedByCloning);
3071 }
3072}
3073
3074void Element::cloneDataFromElement(const Element& other)
3075{
3076 cloneAttributesFromElement(other);
3077 copyNonAttributePropertiesFromElement(other);
3078}
3079
3080void Element::createUniqueElementData()
3081{
3082 if (!m_elementData)
3083 m_elementData = UniqueElementData::create();
3084 else {
3085 ASSERT(!m_elementData->isUnique());
3086 m_elementData = static_cast<ShareableElementData*>(m_elementData.get())->makeUniqueCopy();
3087 }
3088}
3089
Ben Murdoch1fad5ca2013-08-07 11:05:11 +01003090InputMethodContext* Element::inputMethodContext()
Torne (Richard Coles)81a51572013-05-13 16:52:28 +01003091{
3092 return ensureElementRareData()->ensureInputMethodContext(toHTMLElement(this));
3093}
3094
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01003095bool Element::hasPendingResources() const
3096{
3097 return hasRareData() && elementRareData()->hasPendingResources();
3098}
3099
3100void Element::setHasPendingResources()
3101{
3102 ensureElementRareData()->setHasPendingResources(true);
3103}
3104
3105void Element::clearHasPendingResources()
3106{
3107 ensureElementRareData()->setHasPendingResources(false);
3108}
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01003109
Ben Murdoch591b9582013-07-10 11:41:44 +01003110struct PresentationAttributeCacheKey {
3111 PresentationAttributeCacheKey() : tagName(0) { }
Ben Murdoch83750172013-07-24 10:36:59 +01003112 StringImpl* tagName;
Ben Murdoch591b9582013-07-10 11:41:44 +01003113 // Only the values need refcounting.
Ben Murdoch83750172013-07-24 10:36:59 +01003114 Vector<pair<StringImpl*, AtomicString>, 3> attributesAndValues;
Ben Murdoch591b9582013-07-10 11:41:44 +01003115};
3116
3117struct PresentationAttributeCacheEntry {
3118 WTF_MAKE_FAST_ALLOCATED;
3119public:
3120 PresentationAttributeCacheKey key;
3121 RefPtr<StylePropertySet> value;
3122};
3123
3124typedef HashMap<unsigned, OwnPtr<PresentationAttributeCacheEntry>, AlreadyHashed> PresentationAttributeCache;
3125
3126static bool operator!=(const PresentationAttributeCacheKey& a, const PresentationAttributeCacheKey& b)
3127{
3128 if (a.tagName != b.tagName)
3129 return true;
3130 return a.attributesAndValues != b.attributesAndValues;
3131}
3132
3133static PresentationAttributeCache& presentationAttributeCache()
3134{
3135 DEFINE_STATIC_LOCAL(PresentationAttributeCache, cache, ());
3136 return cache;
3137}
3138
3139class PresentationAttributeCacheCleaner {
3140 WTF_MAKE_NONCOPYABLE(PresentationAttributeCacheCleaner); WTF_MAKE_FAST_ALLOCATED;
3141public:
3142 PresentationAttributeCacheCleaner()
3143 : m_hitCount(0)
3144 , m_cleanTimer(this, &PresentationAttributeCacheCleaner::cleanCache)
3145 {
3146 }
3147
3148 void didHitPresentationAttributeCache()
3149 {
3150 if (presentationAttributeCache().size() < minimumPresentationAttributeCacheSizeForCleaning)
3151 return;
3152
3153 m_hitCount++;
3154
3155 if (!m_cleanTimer.isActive())
3156 m_cleanTimer.startOneShot(presentationAttributeCacheCleanTimeInSeconds);
3157 }
3158
3159private:
3160 static const unsigned presentationAttributeCacheCleanTimeInSeconds = 60;
3161 static const int minimumPresentationAttributeCacheSizeForCleaning = 100;
3162 static const unsigned minimumPresentationAttributeCacheHitCountPerMinute = (100 * presentationAttributeCacheCleanTimeInSeconds) / 60;
3163
3164 void cleanCache(Timer<PresentationAttributeCacheCleaner>* timer)
3165 {
3166 ASSERT_UNUSED(timer, timer == &m_cleanTimer);
3167 unsigned hitCount = m_hitCount;
3168 m_hitCount = 0;
3169 if (hitCount > minimumPresentationAttributeCacheHitCountPerMinute)
3170 return;
3171 presentationAttributeCache().clear();
3172 }
3173
3174 unsigned m_hitCount;
3175 Timer<PresentationAttributeCacheCleaner> m_cleanTimer;
3176};
3177
3178static PresentationAttributeCacheCleaner& presentationAttributeCacheCleaner()
3179{
3180 DEFINE_STATIC_LOCAL(PresentationAttributeCacheCleaner, cleaner, ());
3181 return cleaner;
3182}
3183
3184void Element::synchronizeStyleAttributeInternal() const
3185{
3186 ASSERT(isStyledElement());
3187 ASSERT(elementData());
3188 ASSERT(elementData()->m_styleAttributeIsDirty);
3189 elementData()->m_styleAttributeIsDirty = false;
3190 if (const StylePropertySet* inlineStyle = this->inlineStyle())
3191 const_cast<Element*>(this)->setSynchronizedLazyAttribute(styleAttr, inlineStyle->asText());
3192}
3193
3194CSSStyleDeclaration* Element::style()
3195{
3196 if (!isStyledElement())
3197 return 0;
3198 return ensureMutableInlineStyle()->ensureInlineCSSStyleDeclaration(this);
3199}
3200
3201MutableStylePropertySet* Element::ensureMutableInlineStyle()
3202{
3203 ASSERT(isStyledElement());
3204 RefPtr<StylePropertySet>& inlineStyle = ensureUniqueElementData()->m_inlineStyle;
3205 if (!inlineStyle)
Torne (Richard Coles)8abfc582013-09-12 12:10:38 +01003206 inlineStyle = MutableStylePropertySet::create(strictToCSSParserMode(isHTMLElement() && !document().inQuirksMode()));
Ben Murdoch591b9582013-07-10 11:41:44 +01003207 else if (!inlineStyle->isMutable())
3208 inlineStyle = inlineStyle->mutableCopy();
3209 ASSERT(inlineStyle->isMutable());
3210 return static_cast<MutableStylePropertySet*>(inlineStyle.get());
3211}
3212
3213PropertySetCSSStyleDeclaration* Element::inlineStyleCSSOMWrapper()
3214{
3215 if (!inlineStyle() || !inlineStyle()->hasCSSOMWrapper())
3216 return 0;
3217 PropertySetCSSStyleDeclaration* cssomWrapper = ensureMutableInlineStyle()->cssStyleDeclaration();
3218 ASSERT(cssomWrapper && cssomWrapper->parentElement() == this);
3219 return cssomWrapper;
3220}
3221
3222inline void Element::setInlineStyleFromString(const AtomicString& newStyleString)
3223{
3224 ASSERT(isStyledElement());
3225 RefPtr<StylePropertySet>& inlineStyle = elementData()->m_inlineStyle;
3226
3227 // Avoid redundant work if we're using shared attribute data with already parsed inline style.
3228 if (inlineStyle && !elementData()->isUnique())
3229 return;
3230
3231 // We reconstruct the property set instead of mutating if there is no CSSOM wrapper.
3232 // This makes wrapperless property sets immutable and so cacheable.
3233 if (inlineStyle && !inlineStyle->isMutable())
3234 inlineStyle.clear();
3235
3236 if (!inlineStyle) {
3237 inlineStyle = CSSParser::parseInlineStyleDeclaration(newStyleString, this);
3238 } else {
3239 ASSERT(inlineStyle->isMutable());
Torne (Richard Coles)8abfc582013-09-12 12:10:38 +01003240 static_pointer_cast<MutableStylePropertySet>(inlineStyle)->parseDeclaration(newStyleString, document().elementSheet()->contents());
Ben Murdoch591b9582013-07-10 11:41:44 +01003241 }
3242}
3243
3244void Element::styleAttributeChanged(const AtomicString& newStyleString, AttributeModificationReason modificationReason)
3245{
3246 ASSERT(isStyledElement());
3247 WTF::OrdinalNumber startLineNumber = WTF::OrdinalNumber::beforeFirst();
Torne (Richard Coles)8abfc582013-09-12 12:10:38 +01003248 if (document().scriptableDocumentParser() && !document().isInDocumentWrite())
3249 startLineNumber = document().scriptableDocumentParser()->lineNumber();
Ben Murdoch591b9582013-07-10 11:41:44 +01003250
3251 if (newStyleString.isNull()) {
3252 if (PropertySetCSSStyleDeclaration* cssomWrapper = inlineStyleCSSOMWrapper())
3253 cssomWrapper->clearParentElement();
3254 ensureUniqueElementData()->m_inlineStyle.clear();
Torne (Richard Coles)8abfc582013-09-12 12:10:38 +01003255 } else if (modificationReason == ModifiedByCloning || document().contentSecurityPolicy()->allowInlineStyle(document().url(), startLineNumber)) {
Ben Murdoch591b9582013-07-10 11:41:44 +01003256 setInlineStyleFromString(newStyleString);
3257 }
3258
3259 elementData()->m_styleAttributeIsDirty = false;
3260
Ben Murdoche69819b2013-07-17 14:56:49 +01003261 setNeedsStyleRecalc(LocalStyleChange);
Torne (Richard Coles)8abfc582013-09-12 12:10:38 +01003262 InspectorInstrumentation::didInvalidateStyleAttr(&document(), this);
Ben Murdoch591b9582013-07-10 11:41:44 +01003263}
3264
3265void Element::inlineStyleChanged()
3266{
3267 ASSERT(isStyledElement());
Ben Murdoche69819b2013-07-17 14:56:49 +01003268 setNeedsStyleRecalc(LocalStyleChange);
Ben Murdoch591b9582013-07-10 11:41:44 +01003269 ASSERT(elementData());
3270 elementData()->m_styleAttributeIsDirty = true;
Torne (Richard Coles)8abfc582013-09-12 12:10:38 +01003271 InspectorInstrumentation::didInvalidateStyleAttr(&document(), this);
Ben Murdoch591b9582013-07-10 11:41:44 +01003272}
3273
3274bool Element::setInlineStyleProperty(CSSPropertyID propertyID, CSSValueID identifier, bool important)
3275{
3276 ASSERT(isStyledElement());
3277 ensureMutableInlineStyle()->setProperty(propertyID, cssValuePool().createIdentifierValue(identifier), important);
3278 inlineStyleChanged();
3279 return true;
3280}
3281
3282bool Element::setInlineStyleProperty(CSSPropertyID propertyID, CSSPropertyID identifier, bool important)
3283{
3284 ASSERT(isStyledElement());
3285 ensureMutableInlineStyle()->setProperty(propertyID, cssValuePool().createIdentifierValue(identifier), important);
3286 inlineStyleChanged();
3287 return true;
3288}
3289
3290bool Element::setInlineStyleProperty(CSSPropertyID propertyID, double value, CSSPrimitiveValue::UnitTypes unit, bool important)
3291{
3292 ASSERT(isStyledElement());
3293 ensureMutableInlineStyle()->setProperty(propertyID, cssValuePool().createValue(value, unit), important);
3294 inlineStyleChanged();
3295 return true;
3296}
3297
3298bool Element::setInlineStyleProperty(CSSPropertyID propertyID, const String& value, bool important)
3299{
3300 ASSERT(isStyledElement());
Torne (Richard Coles)8abfc582013-09-12 12:10:38 +01003301 bool changes = ensureMutableInlineStyle()->setProperty(propertyID, value, important, document().elementSheet()->contents());
Ben Murdoch591b9582013-07-10 11:41:44 +01003302 if (changes)
3303 inlineStyleChanged();
3304 return changes;
3305}
3306
3307bool Element::removeInlineStyleProperty(CSSPropertyID propertyID)
3308{
3309 ASSERT(isStyledElement());
3310 if (!inlineStyle())
3311 return false;
3312 bool changes = ensureMutableInlineStyle()->removeProperty(propertyID);
3313 if (changes)
3314 inlineStyleChanged();
3315 return changes;
3316}
3317
3318void Element::removeAllInlineStyleProperties()
3319{
3320 ASSERT(isStyledElement());
3321 if (!inlineStyle() || inlineStyle()->isEmpty())
3322 return;
3323 ensureMutableInlineStyle()->clear();
3324 inlineStyleChanged();
3325}
3326
3327void Element::addSubresourceAttributeURLs(ListHashSet<KURL>& urls) const
3328{
3329 ASSERT(isStyledElement());
3330 if (const StylePropertySet* inlineStyle = elementData() ? elementData()->inlineStyle() : 0)
Torne (Richard Coles)8abfc582013-09-12 12:10:38 +01003331 inlineStyle->addSubresourceStyleURLs(urls, document().elementSheet()->contents());
Ben Murdoch591b9582013-07-10 11:41:44 +01003332}
3333
Ben Murdoch83750172013-07-24 10:36:59 +01003334static inline bool attributeNameSort(const pair<StringImpl*, AtomicString>& p1, const pair<StringImpl*, AtomicString>& p2)
Ben Murdoch591b9582013-07-10 11:41:44 +01003335{
3336 // Sort based on the attribute name pointers. It doesn't matter what the order is as long as it is always the same.
3337 return p1.first < p2.first;
3338}
3339
3340void Element::makePresentationAttributeCacheKey(PresentationAttributeCacheKey& result) const
3341{
3342 ASSERT(isStyledElement());
3343 // FIXME: Enable for SVG.
3344 if (namespaceURI() != xhtmlNamespaceURI)
3345 return;
3346 // Interpretation of the size attributes on <input> depends on the type attribute.
3347 if (hasTagName(inputTag))
3348 return;
3349 unsigned size = attributeCount();
3350 for (unsigned i = 0; i < size; ++i) {
3351 const Attribute* attribute = attributeItem(i);
3352 if (!isPresentationAttribute(attribute->name()))
3353 continue;
3354 if (!attribute->namespaceURI().isNull())
3355 return;
3356 // FIXME: Background URL may depend on the base URL and can't be shared. Disallow caching.
3357 if (attribute->name() == backgroundAttr)
3358 return;
3359 result.attributesAndValues.append(std::make_pair(attribute->localName().impl(), attribute->value()));
3360 }
3361 if (result.attributesAndValues.isEmpty())
3362 return;
3363 // Attribute order doesn't matter. Sort for easy equality comparison.
3364 std::sort(result.attributesAndValues.begin(), result.attributesAndValues.end(), attributeNameSort);
3365 // The cache key is non-null when the tagName is set.
3366 result.tagName = localName().impl();
3367}
3368
3369static unsigned computePresentationAttributeCacheHash(const PresentationAttributeCacheKey& key)
3370{
3371 if (!key.tagName)
3372 return 0;
3373 ASSERT(key.attributesAndValues.size());
3374 unsigned attributeHash = StringHasher::hashMemory(key.attributesAndValues.data(), key.attributesAndValues.size() * sizeof(key.attributesAndValues[0]));
3375 return WTF::pairIntHash(key.tagName->existingHash(), attributeHash);
3376}
3377
3378void Element::rebuildPresentationAttributeStyle()
3379{
3380 ASSERT(isStyledElement());
3381 PresentationAttributeCacheKey cacheKey;
3382 makePresentationAttributeCacheKey(cacheKey);
3383
3384 unsigned cacheHash = computePresentationAttributeCacheHash(cacheKey);
3385
3386 PresentationAttributeCache::iterator cacheIterator;
3387 if (cacheHash) {
3388 cacheIterator = presentationAttributeCache().add(cacheHash, nullptr).iterator;
3389 if (cacheIterator->value && cacheIterator->value->key != cacheKey)
3390 cacheHash = 0;
3391 } else {
3392 cacheIterator = presentationAttributeCache().end();
3393 }
3394
3395 RefPtr<StylePropertySet> style;
3396 if (cacheHash && cacheIterator->value) {
3397 style = cacheIterator->value->value;
3398 presentationAttributeCacheCleaner().didHitPresentationAttributeCache();
3399 } else {
3400 style = MutableStylePropertySet::create(isSVGElement() ? SVGAttributeMode : CSSQuirksMode);
3401 unsigned size = attributeCount();
3402 for (unsigned i = 0; i < size; ++i) {
3403 const Attribute* attribute = attributeItem(i);
3404 collectStyleForPresentationAttribute(attribute->name(), attribute->value(), static_cast<MutableStylePropertySet*>(style.get()));
3405 }
3406 }
3407
3408 // ShareableElementData doesn't store presentation attribute style, so make sure we have a UniqueElementData.
3409 UniqueElementData* elementData = ensureUniqueElementData();
3410
3411 elementData->m_presentationAttributeStyleIsDirty = false;
3412 elementData->m_presentationAttributeStyle = style->isEmpty() ? 0 : style;
3413
3414 if (!cacheHash || cacheIterator->value)
3415 return;
3416
3417 OwnPtr<PresentationAttributeCacheEntry> newEntry = adoptPtr(new PresentationAttributeCacheEntry);
3418 newEntry->key = cacheKey;
3419 newEntry->value = style.release();
3420
3421 static const int presentationAttributeCacheMaximumSize = 4096;
3422 if (presentationAttributeCache().size() > presentationAttributeCacheMaximumSize) {
3423 // Start building from scratch if the cache ever gets big.
3424 presentationAttributeCache().clear();
3425 presentationAttributeCache().set(cacheHash, newEntry.release());
3426 } else {
3427 cacheIterator->value = newEntry.release();
3428 }
3429}
3430
3431void Element::addPropertyToPresentationAttributeStyle(MutableStylePropertySet* style, CSSPropertyID propertyID, CSSValueID identifier)
3432{
3433 ASSERT(isStyledElement());
3434 style->setProperty(propertyID, cssValuePool().createIdentifierValue(identifier));
3435}
3436
3437void Element::addPropertyToPresentationAttributeStyle(MutableStylePropertySet* style, CSSPropertyID propertyID, double value, CSSPrimitiveValue::UnitTypes unit)
3438{
3439 ASSERT(isStyledElement());
3440 style->setProperty(propertyID, cssValuePool().createValue(value, unit));
3441}
3442
3443void Element::addPropertyToPresentationAttributeStyle(MutableStylePropertySet* style, CSSPropertyID propertyID, const String& value)
3444{
3445 ASSERT(isStyledElement());
Torne (Richard Coles)8abfc582013-09-12 12:10:38 +01003446 style->setProperty(propertyID, value, false, document().elementSheet()->contents());
Ben Murdoch591b9582013-07-10 11:41:44 +01003447}
3448
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01003449void ElementData::deref()
3450{
3451 if (!derefBase())
3452 return;
3453
3454 if (m_isUnique)
3455 delete static_cast<UniqueElementData*>(this);
3456 else
3457 delete static_cast<ShareableElementData*>(this);
3458}
3459
3460ElementData::ElementData()
3461 : m_isUnique(true)
3462 , m_arraySize(0)
3463 , m_presentationAttributeStyleIsDirty(false)
3464 , m_styleAttributeIsDirty(false)
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01003465 , m_animatedSVGAttributesAreDirty(false)
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01003466{
3467}
3468
3469ElementData::ElementData(unsigned arraySize)
3470 : m_isUnique(false)
3471 , m_arraySize(arraySize)
3472 , m_presentationAttributeStyleIsDirty(false)
3473 , m_styleAttributeIsDirty(false)
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01003474 , m_animatedSVGAttributesAreDirty(false)
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01003475{
3476}
3477
3478struct SameSizeAsElementData : public RefCounted<SameSizeAsElementData> {
3479 unsigned bitfield;
3480 void* refPtrs[3];
3481};
3482
3483COMPILE_ASSERT(sizeof(ElementData) == sizeof(SameSizeAsElementData), element_attribute_data_should_stay_small);
3484
3485static size_t sizeForShareableElementDataWithAttributeCount(unsigned count)
3486{
3487 return sizeof(ShareableElementData) + sizeof(Attribute) * count;
3488}
3489
3490PassRefPtr<ShareableElementData> ShareableElementData::createWithAttributes(const Vector<Attribute>& attributes)
3491{
3492 void* slot = WTF::fastMalloc(sizeForShareableElementDataWithAttributeCount(attributes.size()));
3493 return adoptRef(new (slot) ShareableElementData(attributes));
3494}
3495
3496PassRefPtr<UniqueElementData> UniqueElementData::create()
3497{
3498 return adoptRef(new UniqueElementData);
3499}
3500
3501ShareableElementData::ShareableElementData(const Vector<Attribute>& attributes)
3502 : ElementData(attributes.size())
3503{
3504 for (unsigned i = 0; i < m_arraySize; ++i)
3505 new (&m_attributeArray[i]) Attribute(attributes[i]);
3506}
3507
3508ShareableElementData::~ShareableElementData()
3509{
3510 for (unsigned i = 0; i < m_arraySize; ++i)
3511 m_attributeArray[i].~Attribute();
3512}
3513
3514ShareableElementData::ShareableElementData(const UniqueElementData& other)
3515 : ElementData(other, false)
3516{
3517 ASSERT(!other.m_presentationAttributeStyle);
3518
3519 if (other.m_inlineStyle) {
3520 ASSERT(!other.m_inlineStyle->hasCSSOMWrapper());
3521 m_inlineStyle = other.m_inlineStyle->immutableCopyIfNeeded();
3522 }
3523
3524 for (unsigned i = 0; i < m_arraySize; ++i)
3525 new (&m_attributeArray[i]) Attribute(other.m_attributeVector.at(i));
3526}
3527
3528ElementData::ElementData(const ElementData& other, bool isUnique)
3529 : m_isUnique(isUnique)
3530 , m_arraySize(isUnique ? 0 : other.length())
3531 , m_presentationAttributeStyleIsDirty(other.m_presentationAttributeStyleIsDirty)
3532 , m_styleAttributeIsDirty(other.m_styleAttributeIsDirty)
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01003533 , m_animatedSVGAttributesAreDirty(other.m_animatedSVGAttributesAreDirty)
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01003534 , m_classNames(other.m_classNames)
3535 , m_idForStyleResolution(other.m_idForStyleResolution)
3536{
3537 // NOTE: The inline style is copied by the subclass copy constructor since we don't know what to do with it here.
3538}
3539
3540UniqueElementData::UniqueElementData()
3541{
3542}
3543
3544UniqueElementData::UniqueElementData(const UniqueElementData& other)
3545 : ElementData(other, true)
3546 , m_presentationAttributeStyle(other.m_presentationAttributeStyle)
3547 , m_attributeVector(other.m_attributeVector)
3548{
Torne (Richard Coles)93ac45c2013-05-29 14:40:20 +01003549 m_inlineStyle = other.m_inlineStyle ? other.m_inlineStyle->mutableCopy() : 0;
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01003550}
3551
3552UniqueElementData::UniqueElementData(const ShareableElementData& other)
3553 : ElementData(other, true)
3554{
3555 // An ShareableElementData should never have a mutable inline StylePropertySet attached.
3556 ASSERT(!other.m_inlineStyle || !other.m_inlineStyle->isMutable());
3557 m_inlineStyle = other.m_inlineStyle;
3558
3559 m_attributeVector.reserveCapacity(other.length());
3560 for (unsigned i = 0; i < other.length(); ++i)
3561 m_attributeVector.uncheckedAppend(other.m_attributeArray[i]);
3562}
3563
3564PassRefPtr<UniqueElementData> ElementData::makeUniqueCopy() const
3565{
3566 if (isUnique())
3567 return adoptRef(new UniqueElementData(static_cast<const UniqueElementData&>(*this)));
3568 return adoptRef(new UniqueElementData(static_cast<const ShareableElementData&>(*this)));
3569}
3570
3571PassRefPtr<ShareableElementData> UniqueElementData::makeShareableCopy() const
3572{
3573 void* slot = WTF::fastMalloc(sizeForShareableElementDataWithAttributeCount(m_attributeVector.size()));
3574 return adoptRef(new (slot) ShareableElementData(*this));
3575}
3576
3577void UniqueElementData::addAttribute(const QualifiedName& attributeName, const AtomicString& value)
3578{
3579 m_attributeVector.append(Attribute(attributeName, value));
3580}
3581
3582void UniqueElementData::removeAttribute(size_t index)
3583{
3584 ASSERT_WITH_SECURITY_IMPLICATION(index < length());
3585 m_attributeVector.remove(index);
3586}
3587
3588bool ElementData::isEquivalent(const ElementData* other) const
3589{
3590 if (!other)
3591 return isEmpty();
3592
3593 unsigned len = length();
3594 if (len != other->length())
3595 return false;
3596
3597 for (unsigned i = 0; i < len; i++) {
3598 const Attribute* attribute = attributeItem(i);
3599 const Attribute* otherAttr = other->getAttributeItem(attribute->name());
3600 if (!otherAttr || attribute->value() != otherAttr->value())
3601 return false;
3602 }
3603
3604 return true;
3605}
3606
Torne (Richard Coles)e5249552013-05-15 11:35:13 +01003607size_t ElementData::getAttrIndex(Attr* attr) const
3608{
3609 // This relies on the fact that Attr's QualifiedName == the Attribute's name.
3610 for (unsigned i = 0; i < length(); ++i) {
3611 if (attributeItem(i)->name() == attr->qualifiedName())
3612 return i;
3613 }
Torne (Richard Coles)06f816c2013-09-26 13:25:12 +01003614 return kNotFound;
Torne (Richard Coles)e5249552013-05-15 11:35:13 +01003615}
3616
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01003617size_t ElementData::getAttributeItemIndexSlowCase(const AtomicString& name, bool shouldIgnoreAttributeCase) const
3618{
3619 // Continue to checking case-insensitively and/or full namespaced names if necessary:
3620 for (unsigned i = 0; i < length(); ++i) {
3621 const Attribute* attribute = attributeItem(i);
3622 if (!attribute->name().hasPrefix()) {
3623 if (shouldIgnoreAttributeCase && equalIgnoringCase(name, attribute->localName()))
3624 return i;
3625 } else {
3626 // FIXME: Would be faster to do this comparison without calling toString, which
3627 // generates a temporary string by concatenation. But this branch is only reached
3628 // if the attribute name has a prefix, which is rare in HTML.
3629 if (equalPossiblyIgnoringCase(name, attribute->name().toString(), shouldIgnoreAttributeCase))
3630 return i;
3631 }
3632 }
Torne (Richard Coles)06f816c2013-09-26 13:25:12 +01003633 return kNotFound;
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01003634}
3635
3636Attribute* UniqueElementData::getAttributeItem(const QualifiedName& name)
3637{
3638 for (unsigned i = 0; i < length(); ++i) {
3639 if (m_attributeVector.at(i).name().matches(name))
3640 return &m_attributeVector.at(i);
3641 }
3642 return 0;
3643}
3644
3645Attribute* UniqueElementData::attributeItem(unsigned index)
3646{
3647 ASSERT_WITH_SECURITY_IMPLICATION(index < length());
3648 return &m_attributeVector.at(index);
3649}
3650
3651} // namespace WebCore