blob: c18dec26cb64e342055e8b78335188f741c76195 [file] [log] [blame]
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001/*
2 * Copyright (C) 1999 Lars Knoll (knoll@kde.org)
3 * (C) 1999 Antti Koivisto (koivisto@kde.org)
4 * (C) 2001 Peter Kelly (pmk@post.com)
5 * (C) 2001 Dirk Mueller (mueller@kde.org)
6 * (C) 2007 David Smith (catfish.man@gmail.com)
7 * Copyright (C) 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2012, 2013 Apple Inc. All rights reserved.
8 * (C) 2007 Eric Seidel (eric@webkit.org)
9 *
10 * This library is free software; you can redistribute it and/or
11 * modify it under the terms of the GNU Library General Public
12 * License as published by the Free Software Foundation; either
13 * version 2 of the License, or (at your option) any later version.
14 *
15 * This library is distributed in the hope that it will be useful,
16 * but WITHOUT ANY WARRANTY; without even the implied warranty of
17 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
18 * Library General Public License for more details.
19 *
20 * You should have received a copy of the GNU Library General Public License
21 * along with this library; see the file COPYING.LIB. If not, write to
22 * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
23 * Boston, MA 02110-1301, USA.
24 */
25
26#include "config.h"
27#include "core/dom/Element.h"
28
Ben Murdoch591b9582013-07-10 11:41:44 +010029#include "CSSPropertyNames.h"
30#include "CSSValueKeywords.h"
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +010031#include "HTMLNames.h"
Ben Murdoch7757ec22013-07-23 11:17:36 +010032#include "RuntimeEnabledFeatures.h"
Torne (Richard Coles)93ac45c2013-05-29 14:40:20 +010033#include "SVGNames.h"
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +010034#include "XMLNames.h"
35#include "core/accessibility/AXObjectCache.h"
Ben Murdoch83750172013-07-24 10:36:59 +010036#include "core/animation/DocumentTimeline.h"
Ben Murdoch591b9582013-07-10 11:41:44 +010037#include "core/css/CSSParser.h"
38#include "core/css/CSSStyleSheet.h"
39#include "core/css/CSSValuePool.h"
40#include "core/css/PropertySetCSSStyleDeclaration.h"
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +010041#include "core/css/StylePropertySet.h"
Torne (Richard Coles)81a51572013-05-13 16:52:28 +010042#include "core/css/resolver/StyleResolver.h"
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +010043#include "core/dom/Attr.h"
Ben Murdoch591b9582013-07-10 11:41:44 +010044#include "core/dom/Attribute.h"
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +010045#include "core/dom/ClientRect.h"
46#include "core/dom/ClientRectList.h"
Ben Murdoch83750172013-07-24 10:36:59 +010047#include "core/dom/CustomElement.h"
Ben Murdoche69819b2013-07-17 14:56:49 +010048#include "core/dom/CustomElementRegistrationContext.h"
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +010049#include "core/dom/DatasetDOMStringMap.h"
50#include "core/dom/Document.h"
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +010051#include "core/dom/DocumentSharedObjectPool.h"
52#include "core/dom/ElementRareData.h"
Ben Murdoch02772c62013-07-26 10:21:05 +010053#include "core/dom/EventDispatcher.h"
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +010054#include "core/dom/ExceptionCode.h"
Ben Murdoch02772c62013-07-26 10:21:05 +010055#include "core/dom/FocusEvent.h"
Torne (Richard Coles)f5e4ad52013-08-05 13:57:57 +010056#include "core/dom/FullscreenElementStack.h"
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +010057#include "core/dom/MutationObserverInterestGroup.h"
58#include "core/dom/MutationRecord.h"
59#include "core/dom/NamedNodeMap.h"
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +010060#include "core/dom/NodeRenderStyle.h"
61#include "core/dom/NodeRenderingContext.h"
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +010062#include "core/dom/PseudoElement.h"
Ben Murdoch591b9582013-07-10 11:41:44 +010063#include "core/dom/ScriptableDocumentParser.h"
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +010064#include "core/dom/SelectorQuery.h"
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +010065#include "core/dom/Text.h"
Torne (Richard Coles)e5249552013-05-15 11:35:13 +010066#include "core/dom/shadow/InsertionPoint.h"
67#include "core/dom/shadow/ShadowRoot.h"
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +010068#include "core/editing/FrameSelection.h"
69#include "core/editing/TextIterator.h"
70#include "core/editing/htmlediting.h"
71#include "core/html/ClassList.h"
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +010072#include "core/html/HTMLCollection.h"
73#include "core/html/HTMLDocument.h"
74#include "core/html/HTMLElement.h"
75#include "core/html/HTMLFormControlsCollection.h"
76#include "core/html/HTMLFrameOwnerElement.h"
77#include "core/html/HTMLLabelElement.h"
Torne (Richard Coles)f5e4ad52013-08-05 13:57:57 +010078#include "core/html/HTMLNameCollection.h"
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +010079#include "core/html/HTMLOptionsCollection.h"
80#include "core/html/HTMLTableRowsCollection.h"
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +010081#include "core/html/parser/HTMLParserIdioms.h"
Ben Murdoch591b9582013-07-10 11:41:44 +010082#include "core/page/ContentSecurityPolicy.h"
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +010083#include "core/page/FocusController.h"
84#include "core/page/Frame.h"
85#include "core/page/FrameView.h"
86#include "core/page/Page.h"
87#include "core/page/PointerLockController.h"
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +010088#include "core/rendering/FlowThreadController.h"
89#include "core/rendering/RenderRegion.h"
90#include "core/rendering/RenderView.h"
91#include "core/rendering/RenderWidget.h"
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +010092#include "core/svg/SVGDocumentExtensions.h"
93#include "core/svg/SVGElement.h"
Torne (Richard Coles)93ac45c2013-05-29 14:40:20 +010094#include "wtf/BitVector.h"
Ben Murdoch591b9582013-07-10 11:41:44 +010095#include "wtf/HashFunctions.h"
Torne (Richard Coles)93ac45c2013-05-29 14:40:20 +010096#include "wtf/text/CString.h"
Ben Murdoch591b9582013-07-10 11:41:44 +010097#include "wtf/text/TextPosition.h"
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +010098
99namespace WebCore {
100
101using namespace HTMLNames;
102using namespace XMLNames;
103
104static inline bool shouldIgnoreAttributeCase(const Element* e)
105{
106 return e && e->document()->isHTMLDocument() && e->isHTMLElement();
107}
Ben Murdoch591b9582013-07-10 11:41:44 +0100108
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100109class StyleResolverParentPusher {
110public:
111 StyleResolverParentPusher(Element* parent)
112 : m_parent(parent)
113 , m_pushedStyleResolver(0)
114 {
115 }
116 void push()
117 {
118 if (m_pushedStyleResolver)
119 return;
120 m_pushedStyleResolver = m_parent->document()->styleResolver();
121 m_pushedStyleResolver->pushParentElement(m_parent);
122 }
123 ~StyleResolverParentPusher()
124 {
125
126 if (!m_pushedStyleResolver)
127 return;
128
129 // This tells us that our pushed style selector is in a bad state,
130 // so we should just bail out in that scenario.
131 ASSERT(m_pushedStyleResolver == m_parent->document()->styleResolver());
132 if (m_pushedStyleResolver != m_parent->document()->styleResolver())
133 return;
134
135 m_pushedStyleResolver->popParentElement(m_parent);
136 }
137
138private:
139 Element* m_parent;
140 StyleResolver* m_pushedStyleResolver;
141};
142
143typedef Vector<RefPtr<Attr> > AttrNodeList;
144typedef HashMap<Element*, OwnPtr<AttrNodeList> > AttrNodeListMap;
145
146static AttrNodeListMap& attrNodeListMap()
147{
148 DEFINE_STATIC_LOCAL(AttrNodeListMap, map, ());
149 return map;
150}
151
152static AttrNodeList* attrNodeListForElement(Element* element)
153{
154 if (!element->hasSyntheticAttrChildNodes())
155 return 0;
156 ASSERT(attrNodeListMap().contains(element));
157 return attrNodeListMap().get(element);
158}
159
160static AttrNodeList* ensureAttrNodeListForElement(Element* element)
161{
162 if (element->hasSyntheticAttrChildNodes()) {
163 ASSERT(attrNodeListMap().contains(element));
164 return attrNodeListMap().get(element);
165 }
166 ASSERT(!attrNodeListMap().contains(element));
167 element->setHasSyntheticAttrChildNodes(true);
168 AttrNodeListMap::AddResult result = attrNodeListMap().add(element, adoptPtr(new AttrNodeList));
169 return result.iterator->value.get();
170}
171
172static void removeAttrNodeListForElement(Element* element)
173{
174 ASSERT(element->hasSyntheticAttrChildNodes());
175 ASSERT(attrNodeListMap().contains(element));
176 attrNodeListMap().remove(element);
177 element->setHasSyntheticAttrChildNodes(false);
178}
179
180static Attr* findAttrNodeInList(AttrNodeList* attrNodeList, const QualifiedName& name)
181{
182 for (unsigned i = 0; i < attrNodeList->size(); ++i) {
183 if (attrNodeList->at(i)->qualifiedName() == name)
184 return attrNodeList->at(i).get();
185 }
186 return 0;
187}
188
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100189PassRefPtr<Element> Element::create(const QualifiedName& tagName, Document* document)
190{
191 return adoptRef(new Element(tagName, document, CreateElement));
192}
193
194Element::~Element()
195{
196#ifndef NDEBUG
197 if (document() && document()->renderer()) {
198 // When the document is not destroyed, an element that was part of a named flow
199 // content nodes should have been removed from the content nodes collection
200 // and the inNamedFlow flag reset.
201 ASSERT(!inNamedFlow());
202 }
203#endif
204
Ben Murdoch591b9582013-07-10 11:41:44 +0100205 if (PropertySetCSSStyleDeclaration* cssomWrapper = inlineStyleCSSOMWrapper())
206 cssomWrapper->clearParentElement();
207
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100208 if (hasRareData()) {
209 ElementRareData* data = elementRareData();
210 data->setPseudoElement(BEFORE, 0);
211 data->setPseudoElement(AFTER, 0);
Ben Murdoche69819b2013-07-17 14:56:49 +0100212 data->setPseudoElement(BACKDROP, 0);
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100213 data->clearShadow();
Torne (Richard Coles)f5e4ad52013-08-05 13:57:57 +0100214
215 if (RuntimeEnabledFeatures::webAnimationsCSSEnabled()) {
216 if (ActiveAnimations* activeAnimations = data->activeAnimations())
217 activeAnimations->cssAnimations()->cancel();
218 }
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100219 }
220
Ben Murdoch83750172013-07-24 10:36:59 +0100221 if (isCustomElement())
222 CustomElement::wasDestroyed(this);
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100223
224 if (hasSyntheticAttrChildNodes())
225 detachAllAttrNodesFromElement();
226
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100227 if (hasPendingResources()) {
228 document()->accessSVGExtensions()->removeElementFromPendingResources(this);
229 ASSERT(!hasPendingResources());
230 }
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100231}
232
233inline ElementRareData* Element::elementRareData() const
234{
235 ASSERT(hasRareData());
236 return static_cast<ElementRareData*>(rareData());
237}
238
239inline ElementRareData* Element::ensureElementRareData()
240{
241 return static_cast<ElementRareData*>(ensureRareData());
242}
243
244void Element::clearTabIndexExplicitlyIfNeeded()
245{
246 if (hasRareData())
247 elementRareData()->clearTabIndexExplicitly();
248}
249
250void Element::setTabIndexExplicitly(short tabIndex)
251{
252 ensureElementRareData()->setTabIndexExplicitly(tabIndex);
253}
254
255bool Element::supportsFocus() const
256{
257 return hasRareData() && elementRareData()->tabIndexSetExplicitly();
258}
259
260short Element::tabIndex() const
261{
262 return hasRareData() ? elementRareData()->tabIndex() : 0;
263}
264
Torne (Richard Coles)521d96e2013-06-19 11:58:24 +0100265bool Element::rendererIsFocusable() const
266{
267 // Elements in canvas fallback content are not rendered, but they are allowed to be
268 // focusable as long as their canvas is displayed and visible.
269 if (isInCanvasSubtree()) {
270 const Element* e = this;
271 while (e && !e->hasLocalName(canvasTag))
272 e = e->parentElement();
273 ASSERT(e);
274 return e->renderer() && e->renderer()->style()->visibility() == VISIBLE;
275 }
276
277 // FIXME: These asserts should be in Node::isFocusable, but there are some
Ben Murdoche69819b2013-07-17 14:56:49 +0100278 // callsites like Document::setFocusedElement that would currently fail on
Torne (Richard Coles)521d96e2013-06-19 11:58:24 +0100279 // them. See crbug.com/251163
280 if (renderer()) {
281 ASSERT(!renderer()->needsLayout());
282 } else {
283 // We can't just use needsStyleRecalc() because if the node is in a
284 // display:none tree it might say it needs style recalc but the whole
285 // document is actually up to date.
286 ASSERT(!document()->childNeedsStyleRecalc());
287 }
288
289 // FIXME: Even if we are not visible, we might have a child that is visible.
290 // Hyatt wants to fix that some day with a "has visible content" flag or the like.
291 if (!renderer() || renderer()->style()->visibility() != VISIBLE)
292 return false;
293
294 return true;
295}
296
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100297DEFINE_VIRTUAL_ATTRIBUTE_EVENT_LISTENER(Element, blur);
298DEFINE_VIRTUAL_ATTRIBUTE_EVENT_LISTENER(Element, error);
299DEFINE_VIRTUAL_ATTRIBUTE_EVENT_LISTENER(Element, focus);
300DEFINE_VIRTUAL_ATTRIBUTE_EVENT_LISTENER(Element, load);
301
302PassRefPtr<Node> Element::cloneNode(bool deep)
303{
304 return deep ? cloneElementWithChildren() : cloneElementWithoutChildren();
305}
306
307PassRefPtr<Element> Element::cloneElementWithChildren()
308{
309 RefPtr<Element> clone = cloneElementWithoutChildren();
310 cloneChildNodes(clone.get());
311 return clone.release();
312}
313
314PassRefPtr<Element> Element::cloneElementWithoutChildren()
315{
316 RefPtr<Element> clone = cloneElementWithoutAttributesAndChildren();
317 // This will catch HTML elements in the wrong namespace that are not correctly copied.
318 // This is a sanity check as HTML overloads some of the DOM methods.
319 ASSERT(isHTMLElement() == clone->isHTMLElement());
320
321 clone->cloneDataFromElement(*this);
322 return clone.release();
323}
324
325PassRefPtr<Element> Element::cloneElementWithoutAttributesAndChildren()
326{
327 return document()->createElement(tagQName(), false);
328}
329
330PassRefPtr<Attr> Element::detachAttribute(size_t index)
331{
332 ASSERT(elementData());
Torne (Richard Coles)e5249552013-05-15 11:35:13 +0100333 const Attribute* attribute = elementData()->attributeItem(index);
334 RefPtr<Attr> attrNode = attrIfExists(attribute->name());
335 if (attrNode)
336 detachAttrNodeAtIndex(attrNode.get(), index);
337 else {
338 attrNode = Attr::create(document(), attribute->name(), attribute->value());
339 removeAttributeInternal(index, NotInSynchronizationOfLazyAttribute);
340 }
341 return attrNode.release();
342}
343
344void Element::detachAttrNodeAtIndex(Attr* attr, size_t index)
345{
346 ASSERT(attr);
347 ASSERT(elementData());
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100348
349 const Attribute* attribute = elementData()->attributeItem(index);
350 ASSERT(attribute);
Torne (Richard Coles)e5249552013-05-15 11:35:13 +0100351 ASSERT(attribute->name() == attr->qualifiedName());
352 detachAttrNodeFromElementWithValue(attr, attribute->value());
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100353 removeAttributeInternal(index, NotInSynchronizationOfLazyAttribute);
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100354}
355
356void Element::removeAttribute(const QualifiedName& name)
357{
358 if (!elementData())
359 return;
360
361 size_t index = elementData()->getAttributeItemIndex(name);
362 if (index == notFound)
363 return;
364
365 removeAttributeInternal(index, NotInSynchronizationOfLazyAttribute);
366}
367
368void Element::setBooleanAttribute(const QualifiedName& name, bool value)
369{
370 if (value)
371 setAttribute(name, emptyAtom);
372 else
373 removeAttribute(name);
374}
375
376NamedNodeMap* Element::attributes() const
377{
378 ElementRareData* rareData = const_cast<Element*>(this)->ensureElementRareData();
379 if (NamedNodeMap* attributeMap = rareData->attributeMap())
380 return attributeMap;
381
382 rareData->setAttributeMap(NamedNodeMap::create(const_cast<Element*>(this)));
383 return rareData->attributeMap();
384}
385
Ben Murdoch83750172013-07-24 10:36:59 +0100386ActiveAnimations* Element::activeAnimations() const
Torne (Richard Coles)81a51572013-05-13 16:52:28 +0100387{
Ben Murdoch83750172013-07-24 10:36:59 +0100388 if (hasActiveAnimations())
389 return elementRareData()->activeAnimations();
390 return 0;
Torne (Richard Coles)81a51572013-05-13 16:52:28 +0100391}
392
Ben Murdoch83750172013-07-24 10:36:59 +0100393ActiveAnimations* Element::ensureActiveAnimations()
Torne (Richard Coles)81a51572013-05-13 16:52:28 +0100394{
Ben Murdoch83750172013-07-24 10:36:59 +0100395 ElementRareData* rareData = ensureElementRareData();
396 if (!elementRareData()->activeAnimations())
397 rareData->setActiveAnimations(adoptPtr(new ActiveAnimations()));
398 return rareData->activeAnimations();
Torne (Richard Coles)81a51572013-05-13 16:52:28 +0100399}
400
401bool Element::hasActiveAnimations() const
402{
Ben Murdoch83750172013-07-24 10:36:59 +0100403 if (!RuntimeEnabledFeatures::webAnimationsEnabled())
404 return false;
Torne (Richard Coles)81a51572013-05-13 16:52:28 +0100405
Ben Murdoch83750172013-07-24 10:36:59 +0100406 if (!hasRareData())
407 return false;
408
409 ActiveAnimations* activeAnimations = elementRareData()->activeAnimations();
410 return activeAnimations && !activeAnimations->isEmpty();
Torne (Richard Coles)81a51572013-05-13 16:52:28 +0100411}
412
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100413Node::NodeType Element::nodeType() const
414{
415 return ELEMENT_NODE;
416}
417
418bool Element::hasAttribute(const QualifiedName& name) const
419{
420 return hasAttributeNS(name.namespaceURI(), name.localName());
421}
422
423void Element::synchronizeAllAttributes() const
424{
425 if (!elementData())
426 return;
427 if (elementData()->m_styleAttributeIsDirty) {
428 ASSERT(isStyledElement());
Ben Murdoch591b9582013-07-10 11:41:44 +0100429 synchronizeStyleAttributeInternal();
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100430 }
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100431 if (elementData()->m_animatedSVGAttributesAreDirty) {
432 ASSERT(isSVGElement());
433 toSVGElement(this)->synchronizeAnimatedSVGAttribute(anyQName());
434 }
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100435}
436
437inline void Element::synchronizeAttribute(const QualifiedName& name) const
438{
439 if (!elementData())
440 return;
441 if (UNLIKELY(name == styleAttr && elementData()->m_styleAttributeIsDirty)) {
442 ASSERT(isStyledElement());
Ben Murdoch591b9582013-07-10 11:41:44 +0100443 synchronizeStyleAttributeInternal();
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100444 return;
445 }
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100446 if (UNLIKELY(elementData()->m_animatedSVGAttributesAreDirty)) {
447 ASSERT(isSVGElement());
448 toSVGElement(this)->synchronizeAnimatedSVGAttribute(name);
449 }
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100450}
451
452inline void Element::synchronizeAttribute(const AtomicString& localName) const
453{
454 // This version of synchronizeAttribute() is streamlined for the case where you don't have a full QualifiedName,
455 // e.g when called from DOM API.
456 if (!elementData())
457 return;
458 if (elementData()->m_styleAttributeIsDirty && equalPossiblyIgnoringCase(localName, styleAttr.localName(), shouldIgnoreAttributeCase(this))) {
459 ASSERT(isStyledElement());
Ben Murdoch591b9582013-07-10 11:41:44 +0100460 synchronizeStyleAttributeInternal();
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100461 return;
462 }
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100463 if (elementData()->m_animatedSVGAttributesAreDirty) {
464 // We're not passing a namespace argument on purpose. SVGNames::*Attr are defined w/o namespaces as well.
465 ASSERT(isSVGElement());
466 static_cast<const SVGElement*>(this)->synchronizeAnimatedSVGAttribute(QualifiedName(nullAtom, localName, nullAtom));
467 }
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100468}
469
470const AtomicString& Element::getAttribute(const QualifiedName& name) const
471{
472 if (!elementData())
473 return nullAtom;
474 synchronizeAttribute(name);
475 if (const Attribute* attribute = getAttributeItem(name))
476 return attribute->value();
477 return nullAtom;
478}
479
Ben Murdoch591b9582013-07-10 11:41:44 +0100480void Element::scrollIntoView(bool alignToTop)
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100481{
482 document()->updateLayoutIgnorePendingStylesheets();
483
484 if (!renderer())
485 return;
486
487 LayoutRect bounds = boundingBox();
488 // Align to the top / bottom and to the closest edge.
489 if (alignToTop)
490 renderer()->scrollRectToVisible(bounds, ScrollAlignment::alignToEdgeIfNeeded, ScrollAlignment::alignTopAlways);
491 else
492 renderer()->scrollRectToVisible(bounds, ScrollAlignment::alignToEdgeIfNeeded, ScrollAlignment::alignBottomAlways);
493}
494
495void Element::scrollIntoViewIfNeeded(bool centerIfNeeded)
496{
497 document()->updateLayoutIgnorePendingStylesheets();
498
499 if (!renderer())
500 return;
501
502 LayoutRect bounds = boundingBox();
503 if (centerIfNeeded)
504 renderer()->scrollRectToVisible(bounds, ScrollAlignment::alignCenterIfNeeded, ScrollAlignment::alignCenterIfNeeded);
505 else
506 renderer()->scrollRectToVisible(bounds, ScrollAlignment::alignToEdgeIfNeeded, ScrollAlignment::alignToEdgeIfNeeded);
507}
508
509void Element::scrollByUnits(int units, ScrollGranularity granularity)
510{
511 document()->updateLayoutIgnorePendingStylesheets();
512
513 if (!renderer())
514 return;
515
516 if (!renderer()->hasOverflowClip())
517 return;
518
519 ScrollDirection direction = ScrollDown;
520 if (units < 0) {
521 direction = ScrollUp;
522 units = -units;
523 }
524 Node* stopNode = this;
525 toRenderBox(renderer())->scroll(direction, granularity, units, &stopNode);
526}
527
528void Element::scrollByLines(int lines)
529{
530 scrollByUnits(lines, ScrollByLine);
531}
532
533void Element::scrollByPages(int pages)
534{
535 scrollByUnits(pages, ScrollByPage);
536}
537
538static float localZoomForRenderer(RenderObject* renderer)
539{
540 // FIXME: This does the wrong thing if two opposing zooms are in effect and canceled each
541 // other out, but the alternative is that we'd have to crawl up the whole render tree every
542 // time (or store an additional bit in the RenderStyle to indicate that a zoom was specified).
543 float zoomFactor = 1;
544 if (renderer->style()->effectiveZoom() != 1) {
545 // Need to find the nearest enclosing RenderObject that set up
546 // a differing zoom, and then we divide our result by it to eliminate the zoom.
547 RenderObject* prev = renderer;
548 for (RenderObject* curr = prev->parent(); curr; curr = curr->parent()) {
549 if (curr->style()->effectiveZoom() != prev->style()->effectiveZoom()) {
550 zoomFactor = prev->style()->zoom();
551 break;
552 }
553 prev = curr;
554 }
555 if (prev->isRenderView())
556 zoomFactor = prev->style()->zoom();
557 }
558 return zoomFactor;
559}
560
561static int adjustForLocalZoom(LayoutUnit value, RenderObject* renderer)
562{
563 float zoomFactor = localZoomForRenderer(renderer);
564 if (zoomFactor == 1)
565 return value;
566 return lroundf(value / zoomFactor);
567}
568
569int Element::offsetLeft()
570{
571 document()->updateLayoutIgnorePendingStylesheets();
572 if (RenderBoxModelObject* renderer = renderBoxModelObject())
573 return adjustForLocalZoom(renderer->pixelSnappedOffsetLeft(), renderer);
574 return 0;
575}
576
577int Element::offsetTop()
578{
579 document()->updateLayoutIgnorePendingStylesheets();
580 if (RenderBoxModelObject* renderer = renderBoxModelObject())
581 return adjustForLocalZoom(renderer->pixelSnappedOffsetTop(), renderer);
582 return 0;
583}
584
585int Element::offsetWidth()
586{
Ben Murdoch591b9582013-07-10 11:41:44 +0100587 document()->updateStyleForNodeIfNeeded(this);
588
589 if (RenderBox* renderer = renderBox()) {
590 if (!renderer->requiresLayoutToDetermineWidth())
591 return adjustLayoutUnitForAbsoluteZoom(renderer->fixedOffsetWidth(), renderer).round();
592 }
593
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100594 document()->updateLayoutIgnorePendingStylesheets();
595 if (RenderBoxModelObject* renderer = renderBoxModelObject())
596 return adjustLayoutUnitForAbsoluteZoom(renderer->pixelSnappedOffsetWidth(), renderer).round();
597 return 0;
598}
599
600int Element::offsetHeight()
601{
602 document()->updateLayoutIgnorePendingStylesheets();
603 if (RenderBoxModelObject* renderer = renderBoxModelObject())
604 return adjustLayoutUnitForAbsoluteZoom(renderer->pixelSnappedOffsetHeight(), renderer).round();
605 return 0;
606}
607
608Element* Element::bindingsOffsetParent()
609{
610 Element* element = offsetParent();
611 if (!element || !element->isInShadowTree())
612 return element;
Torne (Richard Coles)521d96e2013-06-19 11:58:24 +0100613 return element->containingShadowRoot()->shouldExposeToBindings() ? element : 0;
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100614}
615
616Element* Element::offsetParent()
617{
618 document()->updateLayoutIgnorePendingStylesheets();
619 if (RenderObject* renderer = this->renderer())
620 return renderer->offsetParent();
621 return 0;
622}
623
624int Element::clientLeft()
625{
626 document()->updateLayoutIgnorePendingStylesheets();
627
628 if (RenderBox* renderer = renderBox())
629 return adjustForAbsoluteZoom(roundToInt(renderer->clientLeft()), renderer);
630 return 0;
631}
632
633int Element::clientTop()
634{
635 document()->updateLayoutIgnorePendingStylesheets();
636
637 if (RenderBox* renderer = renderBox())
638 return adjustForAbsoluteZoom(roundToInt(renderer->clientTop()), renderer);
639 return 0;
640}
641
642int Element::clientWidth()
643{
644 document()->updateLayoutIgnorePendingStylesheets();
645
646 // When in strict mode, clientWidth for the document element should return the width of the containing frame.
647 // When in quirks mode, clientWidth for the body element should return the width of the containing frame.
648 bool inQuirksMode = document()->inQuirksMode();
649 if ((!inQuirksMode && document()->documentElement() == this) ||
650 (inQuirksMode && isHTMLElement() && document()->body() == this)) {
651 if (FrameView* view = document()->view()) {
652 if (RenderView* renderView = document()->renderView())
653 return adjustForAbsoluteZoom(view->layoutWidth(), renderView);
654 }
655 }
Ben Murdoch591b9582013-07-10 11:41:44 +0100656
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100657 if (RenderBox* renderer = renderBox())
658 return adjustLayoutUnitForAbsoluteZoom(renderer->pixelSnappedClientWidth(), renderer).round();
659 return 0;
660}
661
662int Element::clientHeight()
663{
664 document()->updateLayoutIgnorePendingStylesheets();
665
666 // When in strict mode, clientHeight for the document element should return the height of the containing frame.
667 // When in quirks mode, clientHeight for the body element should return the height of the containing frame.
Ben Murdoch591b9582013-07-10 11:41:44 +0100668 bool inQuirksMode = document()->inQuirksMode();
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100669
670 if ((!inQuirksMode && document()->documentElement() == this) ||
671 (inQuirksMode && isHTMLElement() && document()->body() == this)) {
672 if (FrameView* view = document()->view()) {
673 if (RenderView* renderView = document()->renderView())
674 return adjustForAbsoluteZoom(view->layoutHeight(), renderView);
675 }
676 }
Ben Murdoch591b9582013-07-10 11:41:44 +0100677
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100678 if (RenderBox* renderer = renderBox())
679 return adjustLayoutUnitForAbsoluteZoom(renderer->pixelSnappedClientHeight(), renderer).round();
680 return 0;
681}
682
683int Element::scrollLeft()
684{
685 document()->updateLayoutIgnorePendingStylesheets();
686 if (RenderBox* rend = renderBox())
687 return adjustForAbsoluteZoom(rend->scrollLeft(), rend);
688 return 0;
689}
690
691int Element::scrollTop()
692{
693 document()->updateLayoutIgnorePendingStylesheets();
694 if (RenderBox* rend = renderBox())
695 return adjustForAbsoluteZoom(rend->scrollTop(), rend);
696 return 0;
697}
698
699void Element::setScrollLeft(int newLeft)
700{
701 document()->updateLayoutIgnorePendingStylesheets();
702 if (RenderBox* rend = renderBox())
703 rend->setScrollLeft(static_cast<int>(newLeft * rend->style()->effectiveZoom()));
704}
705
706void Element::setScrollTop(int newTop)
707{
708 document()->updateLayoutIgnorePendingStylesheets();
709 if (RenderBox* rend = renderBox())
710 rend->setScrollTop(static_cast<int>(newTop * rend->style()->effectiveZoom()));
711}
712
713int Element::scrollWidth()
714{
715 document()->updateLayoutIgnorePendingStylesheets();
716 if (RenderBox* rend = renderBox())
717 return adjustForAbsoluteZoom(rend->scrollWidth(), rend);
718 return 0;
719}
720
721int Element::scrollHeight()
722{
723 document()->updateLayoutIgnorePendingStylesheets();
724 if (RenderBox* rend = renderBox())
725 return adjustForAbsoluteZoom(rend->scrollHeight(), rend);
726 return 0;
727}
728
729IntRect Element::boundsInRootViewSpace()
730{
731 document()->updateLayoutIgnorePendingStylesheets();
732
733 FrameView* view = document()->view();
734 if (!view)
735 return IntRect();
736
737 Vector<FloatQuad> quads;
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100738 if (isSVGElement() && renderer()) {
739 // Get the bounding rectangle from the SVG model.
740 SVGElement* svgElement = toSVGElement(this);
741 FloatRect localRect;
742 if (svgElement->getBoundingBox(localRect))
743 quads.append(renderer()->localToAbsoluteQuad(localRect));
Torne (Richard Coles)93ac45c2013-05-29 14:40:20 +0100744 } else {
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100745 // Get the bounding rectangle from the box model.
746 if (renderBoxModelObject())
747 renderBoxModelObject()->absoluteQuads(quads);
748 }
749
750 if (quads.isEmpty())
751 return IntRect();
752
753 IntRect result = quads[0].enclosingBoundingBox();
754 for (size_t i = 1; i < quads.size(); ++i)
755 result.unite(quads[i].enclosingBoundingBox());
756
757 result = view->contentsToRootView(result);
758 return result;
759}
760
761PassRefPtr<ClientRectList> Element::getClientRects()
762{
763 document()->updateLayoutIgnorePendingStylesheets();
764
765 RenderBoxModelObject* renderBoxModelObject = this->renderBoxModelObject();
766 if (!renderBoxModelObject)
767 return ClientRectList::create();
768
769 // FIXME: Handle SVG elements.
770 // FIXME: Handle table/inline-table with a caption.
771
772 Vector<FloatQuad> quads;
773 renderBoxModelObject->absoluteQuads(quads);
774 document()->adjustFloatQuadsForScrollAndAbsoluteZoom(quads, renderBoxModelObject);
775 return ClientRectList::create(quads);
776}
777
778PassRefPtr<ClientRect> Element::getBoundingClientRect()
779{
780 document()->updateLayoutIgnorePendingStylesheets();
781
782 Vector<FloatQuad> quads;
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100783 if (isSVGElement() && renderer() && !renderer()->isSVGRoot()) {
784 // Get the bounding rectangle from the SVG model.
785 SVGElement* svgElement = toSVGElement(this);
786 FloatRect localRect;
787 if (svgElement->getBoundingBox(localRect))
788 quads.append(renderer()->localToAbsoluteQuad(localRect));
Torne (Richard Coles)93ac45c2013-05-29 14:40:20 +0100789 } else {
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100790 // Get the bounding rectangle from the box model.
791 if (renderBoxModelObject())
792 renderBoxModelObject()->absoluteQuads(quads);
793 }
794
795 if (quads.isEmpty())
796 return ClientRect::create();
797
798 FloatRect result = quads[0].boundingBox();
799 for (size_t i = 1; i < quads.size(); ++i)
800 result.unite(quads[i].boundingBox());
801
802 document()->adjustFloatRectForScrollAndAbsoluteZoom(result, renderer());
803 return ClientRect::create(result);
804}
Ben Murdoch591b9582013-07-10 11:41:44 +0100805
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100806IntRect Element::screenRect() const
807{
808 if (!renderer())
809 return IntRect();
810 // FIXME: this should probably respect transforms
811 return document()->view()->contentsToScreen(renderer()->absoluteBoundingBoxRectIgnoringTransforms());
812}
813
814const AtomicString& Element::getAttribute(const AtomicString& localName) const
815{
816 if (!elementData())
817 return nullAtom;
818 synchronizeAttribute(localName);
819 if (const Attribute* attribute = elementData()->getAttributeItem(localName, shouldIgnoreAttributeCase(this)))
820 return attribute->value();
821 return nullAtom;
822}
823
824const AtomicString& Element::getAttributeNS(const AtomicString& namespaceURI, const AtomicString& localName) const
825{
826 return getAttribute(QualifiedName(nullAtom, localName, namespaceURI));
827}
828
829void Element::setAttribute(const AtomicString& localName, const AtomicString& value, ExceptionCode& ec)
830{
831 if (!Document::isValidName(localName)) {
Ben Murdoche69819b2013-07-17 14:56:49 +0100832 ec = InvalidCharacterError;
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100833 return;
834 }
835
836 synchronizeAttribute(localName);
837 const AtomicString& caseAdjustedLocalName = shouldIgnoreAttributeCase(this) ? localName.lower() : localName;
838
839 size_t index = elementData() ? elementData()->getAttributeItemIndex(caseAdjustedLocalName, false) : notFound;
840 const QualifiedName& qName = index != notFound ? attributeItem(index)->name() : QualifiedName(nullAtom, caseAdjustedLocalName, nullAtom);
841 setAttributeInternal(index, qName, value, NotInSynchronizationOfLazyAttribute);
842}
843
844void Element::setAttribute(const QualifiedName& name, const AtomicString& value)
845{
846 synchronizeAttribute(name);
847 size_t index = elementData() ? elementData()->getAttributeItemIndex(name) : notFound;
848 setAttributeInternal(index, name, value, NotInSynchronizationOfLazyAttribute);
849}
850
851void Element::setSynchronizedLazyAttribute(const QualifiedName& name, const AtomicString& value)
852{
853 size_t index = elementData() ? elementData()->getAttributeItemIndex(name) : notFound;
854 setAttributeInternal(index, name, value, InSynchronizationOfLazyAttribute);
855}
856
857inline void Element::setAttributeInternal(size_t index, const QualifiedName& name, const AtomicString& newValue, SynchronizationOfLazyAttribute inSynchronizationOfLazyAttribute)
858{
859 if (newValue.isNull()) {
860 if (index != notFound)
861 removeAttributeInternal(index, inSynchronizationOfLazyAttribute);
862 return;
863 }
864
865 if (index == notFound) {
866 addAttributeInternal(name, newValue, inSynchronizationOfLazyAttribute);
867 return;
868 }
869
870 if (!inSynchronizationOfLazyAttribute)
871 willModifyAttribute(name, attributeItem(index)->value(), newValue);
872
873 if (newValue != attributeItem(index)->value()) {
874 // If there is an Attr node hooked to this attribute, the Attr::setValue() call below
875 // will write into the ElementData.
876 // FIXME: Refactor this so it makes some sense.
877 if (RefPtr<Attr> attrNode = inSynchronizationOfLazyAttribute ? 0 : attrIfExists(name))
878 attrNode->setValue(newValue);
879 else
880 ensureUniqueElementData()->attributeItem(index)->setValue(newValue);
881 }
882
883 if (!inSynchronizationOfLazyAttribute)
884 didModifyAttribute(name, newValue);
885}
886
887static inline AtomicString makeIdForStyleResolution(const AtomicString& value, bool inQuirksMode)
888{
889 if (inQuirksMode)
890 return value.lower();
891 return value;
892}
893
Ben Murdoch7757ec22013-07-23 11:17:36 +0100894static bool checkNeedsStyleInvalidationForIdChange(const AtomicString& oldId, const AtomicString& newId, const RuleFeatureSet& features)
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100895{
896 ASSERT(newId != oldId);
Ben Murdoch7757ec22013-07-23 11:17:36 +0100897 if (!oldId.isEmpty() && features.hasSelectorForId(oldId))
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100898 return true;
Ben Murdoch7757ec22013-07-23 11:17:36 +0100899 if (!newId.isEmpty() && features.hasSelectorForId(newId))
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100900 return true;
901 return false;
902}
903
Ben Murdoch591b9582013-07-10 11:41:44 +0100904void Element::attributeChanged(const QualifiedName& name, const AtomicString& newValue, AttributeModificationReason reason)
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100905{
906 if (ElementShadow* parentElementShadow = shadowOfParentForDistribution(this)) {
907 if (shouldInvalidateDistributionWhenAttributeChanged(parentElementShadow, name, newValue))
Torne (Richard Coles)f5e4ad52013-08-05 13:57:57 +0100908 parentElementShadow->setNeedsDistributionRecalc();
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100909 }
910
911 parseAttribute(name, newValue);
912
913 document()->incDOMTreeVersion();
914
915 StyleResolver* styleResolver = document()->styleResolverIfExists();
Ben Murdoche69819b2013-07-17 14:56:49 +0100916 bool testShouldInvalidateStyle = attached() && styleResolver && styleChangeType() < SubtreeStyleChange;
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100917 bool shouldInvalidateStyle = false;
918
Ben Murdoch591b9582013-07-10 11:41:44 +0100919 if (isStyledElement() && name == styleAttr) {
920 styleAttributeChanged(newValue, reason);
921 } else if (isStyledElement() && isPresentationAttribute(name)) {
922 elementData()->m_presentationAttributeStyleIsDirty = true;
Ben Murdoche69819b2013-07-17 14:56:49 +0100923 setNeedsStyleRecalc(LocalStyleChange);
Ben Murdoch591b9582013-07-10 11:41:44 +0100924 }
925
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100926 if (isIdAttributeName(name)) {
927 AtomicString oldId = elementData()->idForStyleResolution();
928 AtomicString newId = makeIdForStyleResolution(newValue, document()->inQuirksMode());
929 if (newId != oldId) {
930 elementData()->setIdForStyleResolution(newId);
Ben Murdoch7757ec22013-07-23 11:17:36 +0100931 shouldInvalidateStyle = testShouldInvalidateStyle && checkNeedsStyleInvalidationForIdChange(oldId, newId, styleResolver->ruleFeatureSet());
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100932 }
Ben Murdoch591b9582013-07-10 11:41:44 +0100933 } else if (name == classAttr) {
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100934 classAttributeChanged(newValue);
Ben Murdoch591b9582013-07-10 11:41:44 +0100935 } else if (name == HTMLNames::nameAttr) {
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100936 setHasName(!newValue.isNull());
Ben Murdoch591b9582013-07-10 11:41:44 +0100937 } else if (name == HTMLNames::pseudoAttr) {
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100938 shouldInvalidateStyle |= testShouldInvalidateStyle && isInShadowTree();
Ben Murdoch591b9582013-07-10 11:41:44 +0100939 }
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100940
941 invalidateNodeListCachesInAncestors(&name, this);
942
943 // If there is currently no StyleResolver, we can't be sure that this attribute change won't affect style.
944 shouldInvalidateStyle |= !styleResolver;
945
946 if (shouldInvalidateStyle)
947 setNeedsStyleRecalc();
948
949 if (AXObjectCache* cache = document()->existingAXObjectCache())
950 cache->handleAttributeChanged(name, this);
951}
952
953inline void Element::attributeChangedFromParserOrByCloning(const QualifiedName& name, const AtomicString& newValue, AttributeModificationReason reason)
954{
Ben Murdoche69819b2013-07-17 14:56:49 +0100955 if (name == isAttr)
Ben Murdoch0019e4e2013-07-18 11:57:54 +0100956 CustomElementRegistrationContext::setTypeExtension(this, newValue);
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100957 attributeChanged(name, newValue, reason);
958}
959
960template <typename CharacterType>
961static inline bool classStringHasClassName(const CharacterType* characters, unsigned length)
962{
963 ASSERT(length > 0);
964
965 unsigned i = 0;
966 do {
967 if (isNotHTMLSpace(characters[i]))
968 break;
969 ++i;
970 } while (i < length);
971
972 return i < length;
973}
974
975static inline bool classStringHasClassName(const AtomicString& newClassString)
976{
977 unsigned length = newClassString.length();
978
979 if (!length)
980 return false;
981
982 if (newClassString.is8Bit())
983 return classStringHasClassName(newClassString.characters8(), length);
984 return classStringHasClassName(newClassString.characters16(), length);
985}
986
987template<typename Checker>
988static bool checkSelectorForClassChange(const SpaceSplitString& changedClasses, const Checker& checker)
989{
990 unsigned changedSize = changedClasses.size();
991 for (unsigned i = 0; i < changedSize; ++i) {
992 if (checker.hasSelectorForClass(changedClasses[i]))
993 return true;
994 }
995 return false;
996}
997
998template<typename Checker>
999static bool checkSelectorForClassChange(const SpaceSplitString& oldClasses, const SpaceSplitString& newClasses, const Checker& checker)
1000{
1001 unsigned oldSize = oldClasses.size();
1002 if (!oldSize)
1003 return checkSelectorForClassChange(newClasses, checker);
1004 BitVector remainingClassBits;
1005 remainingClassBits.ensureSize(oldSize);
1006 // Class vectors tend to be very short. This is faster than using a hash table.
1007 unsigned newSize = newClasses.size();
1008 for (unsigned i = 0; i < newSize; ++i) {
1009 for (unsigned j = 0; j < oldSize; ++j) {
1010 if (newClasses[i] == oldClasses[j]) {
1011 remainingClassBits.quickSet(j);
1012 continue;
1013 }
1014 }
1015 if (checker.hasSelectorForClass(newClasses[i]))
1016 return true;
1017 }
1018 for (unsigned i = 0; i < oldSize; ++i) {
1019 // If the bit is not set the the corresponding class has been removed.
1020 if (remainingClassBits.quickGet(i))
1021 continue;
1022 if (checker.hasSelectorForClass(oldClasses[i]))
1023 return true;
1024 }
1025 return false;
1026}
1027
1028void Element::classAttributeChanged(const AtomicString& newClassString)
1029{
1030 StyleResolver* styleResolver = document()->styleResolverIfExists();
Ben Murdoche69819b2013-07-17 14:56:49 +01001031 bool testShouldInvalidateStyle = attached() && styleResolver && styleChangeType() < SubtreeStyleChange;
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001032 bool shouldInvalidateStyle = false;
1033
1034 if (classStringHasClassName(newClassString)) {
1035 const bool shouldFoldCase = document()->inQuirksMode();
1036 const SpaceSplitString oldClasses = elementData()->classNames();
1037 elementData()->setClass(newClassString, shouldFoldCase);
1038 const SpaceSplitString& newClasses = elementData()->classNames();
Ben Murdoch7757ec22013-07-23 11:17:36 +01001039 shouldInvalidateStyle = testShouldInvalidateStyle && checkSelectorForClassChange(oldClasses, newClasses, styleResolver->ruleFeatureSet());
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001040 } else {
1041 const SpaceSplitString& oldClasses = elementData()->classNames();
Ben Murdoch7757ec22013-07-23 11:17:36 +01001042 shouldInvalidateStyle = testShouldInvalidateStyle && checkSelectorForClassChange(oldClasses, styleResolver->ruleFeatureSet());
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001043 elementData()->clearClass();
1044 }
1045
1046 if (hasRareData())
1047 elementRareData()->clearClassListValueForQuirksMode();
1048
1049 if (shouldInvalidateStyle)
1050 setNeedsStyleRecalc();
1051}
1052
1053bool Element::shouldInvalidateDistributionWhenAttributeChanged(ElementShadow* elementShadow, const QualifiedName& name, const AtomicString& newValue)
1054{
1055 ASSERT(elementShadow);
1056 const SelectRuleFeatureSet& featureSet = elementShadow->distributor().ensureSelectFeatureSet(elementShadow);
1057
1058 if (isIdAttributeName(name)) {
1059 AtomicString oldId = elementData()->idForStyleResolution();
1060 AtomicString newId = makeIdForStyleResolution(newValue, document()->inQuirksMode());
1061 if (newId != oldId) {
1062 if (!oldId.isEmpty() && featureSet.hasSelectorForId(oldId))
1063 return true;
1064 if (!newId.isEmpty() && featureSet.hasSelectorForId(newId))
1065 return true;
1066 }
1067 }
1068
1069 if (name == HTMLNames::classAttr) {
1070 const AtomicString& newClassString = newValue;
1071 if (classStringHasClassName(newClassString)) {
1072 const bool shouldFoldCase = document()->inQuirksMode();
1073 const SpaceSplitString& oldClasses = elementData()->classNames();
1074 const SpaceSplitString newClasses(newClassString, shouldFoldCase);
1075 if (checkSelectorForClassChange(oldClasses, newClasses, featureSet))
1076 return true;
1077 } else {
1078 const SpaceSplitString& oldClasses = elementData()->classNames();
1079 if (checkSelectorForClassChange(oldClasses, featureSet))
1080 return true;
1081 }
1082 }
1083
1084 return featureSet.hasSelectorForAttribute(name.localName());
1085}
1086
1087// Returns true is the given attribute is an event handler.
1088// We consider an event handler any attribute that begins with "on".
1089// It is a simple solution that has the advantage of not requiring any
1090// code or configuration change if a new event handler is defined.
1091
1092static inline bool isEventHandlerAttribute(const Attribute& attribute)
1093{
1094 return attribute.name().namespaceURI().isNull() && attribute.name().localName().startsWith("on");
1095}
1096
1097bool Element::isJavaScriptURLAttribute(const Attribute& attribute) const
1098{
1099 return isURLAttribute(attribute) && protocolIsJavaScript(stripLeadingAndTrailingHTMLSpaces(attribute.value()));
1100}
1101
1102void Element::stripScriptingAttributes(Vector<Attribute>& attributeVector) const
1103{
1104 size_t destination = 0;
1105 for (size_t source = 0; source < attributeVector.size(); ++source) {
1106 if (isEventHandlerAttribute(attributeVector[source])
1107 || isJavaScriptURLAttribute(attributeVector[source])
1108 || isHTMLContentAttribute(attributeVector[source]))
1109 continue;
1110
1111 if (source != destination)
1112 attributeVector[destination] = attributeVector[source];
1113
1114 ++destination;
1115 }
1116 attributeVector.shrink(destination);
1117}
1118
1119void Element::parserSetAttributes(const Vector<Attribute>& attributeVector)
1120{
1121 ASSERT(!inDocument());
1122 ASSERT(!parentNode());
1123 ASSERT(!m_elementData);
1124
1125 if (attributeVector.isEmpty())
1126 return;
1127
1128 if (document() && document()->sharedObjectPool())
1129 m_elementData = document()->sharedObjectPool()->cachedShareableElementDataWithAttributes(attributeVector);
1130 else
1131 m_elementData = ShareableElementData::createWithAttributes(attributeVector);
1132
1133 // Use attributeVector instead of m_elementData because attributeChanged might modify m_elementData.
1134 for (unsigned i = 0; i < attributeVector.size(); ++i)
1135 attributeChangedFromParserOrByCloning(attributeVector[i].name(), attributeVector[i].value(), ModifiedDirectly);
1136}
1137
1138bool Element::hasAttributes() const
1139{
1140 synchronizeAllAttributes();
1141 return elementData() && elementData()->length();
1142}
1143
1144bool Element::hasEquivalentAttributes(const Element* other) const
1145{
1146 synchronizeAllAttributes();
1147 other->synchronizeAllAttributes();
1148 if (elementData() == other->elementData())
1149 return true;
1150 if (elementData())
1151 return elementData()->isEquivalent(other->elementData());
1152 if (other->elementData())
1153 return other->elementData()->isEquivalent(elementData());
1154 return true;
1155}
1156
1157String Element::nodeName() const
1158{
1159 return m_tagName.toString();
1160}
1161
1162String Element::nodeNamePreservingCase() const
1163{
1164 return m_tagName.toString();
1165}
1166
1167void Element::setPrefix(const AtomicString& prefix, ExceptionCode& ec)
1168{
1169 ec = 0;
1170 checkSetPrefix(prefix, ec);
1171 if (ec)
1172 return;
1173
1174 m_tagName.setPrefix(prefix.isEmpty() ? AtomicString() : prefix);
1175}
1176
1177KURL Element::baseURI() const
1178{
1179 const AtomicString& baseAttribute = getAttribute(baseAttr);
1180 KURL base(KURL(), baseAttribute);
1181 if (!base.protocol().isEmpty())
1182 return base;
1183
1184 ContainerNode* parent = parentNode();
1185 if (!parent)
1186 return base;
1187
1188 const KURL& parentBase = parent->baseURI();
1189 if (parentBase.isNull())
1190 return base;
1191
1192 return KURL(parentBase, baseAttribute);
1193}
1194
1195const AtomicString& Element::imageSourceURL() const
1196{
1197 return getAttribute(srcAttr);
1198}
1199
1200bool Element::rendererIsNeeded(const NodeRenderingContext& context)
1201{
1202 return context.style()->display() != NONE;
1203}
1204
Ben Murdoch591b9582013-07-10 11:41:44 +01001205RenderObject* Element::createRenderer(RenderStyle* style)
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001206{
1207 return RenderObject::createObject(this, style);
1208}
1209
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001210bool Element::isInert() const
1211{
Torne (Richard Coles)93ac45c2013-05-29 14:40:20 +01001212 const Element* dialog = document()->activeModalDialog();
Ben Murdoch591b9582013-07-10 11:41:44 +01001213 if (dialog && !containsIncludingShadowDOM(dialog) && !dialog->containsIncludingShadowDOM(this))
1214 return true;
1215 return document()->ownerElement() && document()->ownerElement()->isInert();
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001216}
1217
1218Node::InsertionNotificationRequest Element::insertedInto(ContainerNode* insertionPoint)
1219{
1220 // need to do superclass processing first so inDocument() is true
1221 // by the time we reach updateId
1222 ContainerNode::insertedInto(insertionPoint);
1223
1224 if (containsFullScreenElement() && parentElement() && !parentElement()->containsFullScreenElement())
1225 setContainsFullScreenElementOnAncestorsCrossingFrameBoundaries(true);
1226
1227 if (Element* before = pseudoElement(BEFORE))
1228 before->insertedInto(insertionPoint);
1229
1230 if (Element* after = pseudoElement(AFTER))
1231 after->insertedInto(insertionPoint);
1232
1233 if (!insertionPoint->isInTreeScope())
1234 return InsertionDone;
1235
1236 if (hasRareData())
1237 elementRareData()->clearClassListValueForQuirksMode();
1238
Torne (Richard Coles)f5e4ad52013-08-05 13:57:57 +01001239 if (isUpgradedCustomElement() && inDocument())
1240 CustomElement::didEnterDocument(this, document());
1241
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001242 TreeScope* scope = insertionPoint->treeScope();
1243 if (scope != treeScope())
1244 return InsertionDone;
1245
1246 const AtomicString& idValue = getIdAttribute();
1247 if (!idValue.isNull())
1248 updateId(scope, nullAtom, idValue);
1249
1250 const AtomicString& nameValue = getNameAttribute();
1251 if (!nameValue.isNull())
Torne (Richard Coles)f5e4ad52013-08-05 13:57:57 +01001252 updateName(scope, nullAtom, nameValue);
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001253
1254 if (hasTagName(labelTag)) {
1255 if (scope->shouldCacheLabelsByForAttribute())
1256 updateLabel(scope, nullAtom, fastGetAttribute(forAttr));
1257 }
1258
1259 return InsertionDone;
1260}
1261
1262void Element::removedFrom(ContainerNode* insertionPoint)
1263{
Torne (Richard Coles)f5e4ad52013-08-05 13:57:57 +01001264 bool wasInDocument = insertionPoint->inDocument();
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001265
1266 if (Element* before = pseudoElement(BEFORE))
1267 before->removedFrom(insertionPoint);
1268
1269 if (Element* after = pseudoElement(AFTER))
1270 after->removedFrom(insertionPoint);
1271
Ben Murdoche69819b2013-07-17 14:56:49 +01001272 if (Element* backdrop = pseudoElement(BACKDROP))
1273 backdrop->removedFrom(insertionPoint);
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001274 document()->removeFromTopLayer(this);
Ben Murdoche69819b2013-07-17 14:56:49 +01001275
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001276 if (containsFullScreenElement())
1277 setContainsFullScreenElementOnAncestorsCrossingFrameBoundaries(false);
1278
1279 if (document()->page())
1280 document()->page()->pointerLockController()->elementRemoved(this);
1281
1282 setSavedLayerScrollOffset(IntSize());
1283
1284 if (insertionPoint->isInTreeScope() && treeScope() == document()) {
1285 const AtomicString& idValue = getIdAttribute();
1286 if (!idValue.isNull())
1287 updateId(insertionPoint->treeScope(), idValue, nullAtom);
1288
1289 const AtomicString& nameValue = getNameAttribute();
1290 if (!nameValue.isNull())
Torne (Richard Coles)f5e4ad52013-08-05 13:57:57 +01001291 updateName(insertionPoint->treeScope(), nameValue, nullAtom);
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001292
1293 if (hasTagName(labelTag)) {
1294 TreeScope* treeScope = insertionPoint->treeScope();
1295 if (treeScope->shouldCacheLabelsByForAttribute())
1296 updateLabel(treeScope, fastGetAttribute(forAttr), nullAtom);
1297 }
1298 }
1299
1300 ContainerNode::removedFrom(insertionPoint);
Ben Murdoche69819b2013-07-17 14:56:49 +01001301 if (wasInDocument) {
1302 if (hasPendingResources())
1303 document()->accessSVGExtensions()->removeElementFromPendingResources(this);
1304
Ben Murdoch83750172013-07-24 10:36:59 +01001305 if (isUpgradedCustomElement())
Ben Murdochfff88842013-07-30 15:20:09 +01001306 CustomElement::didLeaveDocument(this, insertionPoint->document());
Ben Murdoche69819b2013-07-17 14:56:49 +01001307 }
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001308}
1309
Torne (Richard Coles)521d96e2013-06-19 11:58:24 +01001310void Element::createRendererIfNeeded(const AttachContext& context)
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001311{
Ben Murdoch83750172013-07-24 10:36:59 +01001312 NodeRenderingContext(this, context.resolvedStyle).createRendererForElementIfNeeded();
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001313}
1314
Torne (Richard Coles)521d96e2013-06-19 11:58:24 +01001315void Element::attach(const AttachContext& context)
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001316{
1317 PostAttachCallbackDisabler callbackDisabler(this);
1318 StyleResolverParentPusher parentPusher(this);
1319 WidgetHierarchyUpdatesSuspensionScope suspendWidgetHierarchyUpdates;
1320
Torne (Richard Coles)521d96e2013-06-19 11:58:24 +01001321 createRendererIfNeeded(context);
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001322
1323 if (parentElement() && parentElement()->isInCanvasSubtree())
1324 setIsInCanvasSubtree(true);
1325
1326 createPseudoElementIfNeeded(BEFORE);
1327
1328 // When a shadow root exists, it does the work of attaching the children.
1329 if (ElementShadow* shadow = this->shadow()) {
1330 parentPusher.push();
Ben Murdoch591b9582013-07-10 11:41:44 +01001331 shadow->attach(context);
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001332 } else if (firstChild())
1333 parentPusher.push();
1334
Torne (Richard Coles)521d96e2013-06-19 11:58:24 +01001335 ContainerNode::attach(context);
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001336
1337 createPseudoElementIfNeeded(AFTER);
Ben Murdoche69819b2013-07-17 14:56:49 +01001338 createPseudoElementIfNeeded(BACKDROP);
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001339
Ben Murdoch591b9582013-07-10 11:41:44 +01001340 if (hasRareData()) {
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001341 ElementRareData* data = elementRareData();
1342 if (data->needsFocusAppearanceUpdateSoonAfterAttach()) {
Ben Murdoch7757ec22013-07-23 11:17:36 +01001343 if (isFocusable() && document()->focusedElement() == this)
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001344 document()->updateFocusAppearanceSoon(false /* don't restore selection */);
1345 data->setNeedsFocusAppearanceUpdateSoonAfterAttach(false);
1346 }
1347 }
Ben Murdoch591b9582013-07-10 11:41:44 +01001348
1349 // FIXME: It doesn't appear safe to call didRecalculateStyleForElement when
1350 // not in a Document::recalcStyle. Since we're hopefully going to always
1351 // lazyAttach in the future that problem should go away.
1352 if (document()->inStyleRecalc())
1353 InspectorInstrumentation::didRecalculateStyleForElement(this);
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001354}
1355
1356void Element::unregisterNamedFlowContentNode()
1357{
1358 if (RuntimeEnabledFeatures::cssRegionsEnabled() && inNamedFlow() && document()->renderView())
1359 document()->renderView()->flowThreadController()->unregisterNamedFlowContentNode(this);
1360}
1361
Torne (Richard Coles)521d96e2013-06-19 11:58:24 +01001362void Element::detach(const AttachContext& context)
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001363{
1364 WidgetHierarchyUpdatesSuspensionScope suspendWidgetHierarchyUpdates;
1365 unregisterNamedFlowContentNode();
1366 cancelFocusAppearanceUpdate();
1367 if (hasRareData()) {
1368 ElementRareData* data = elementRareData();
1369 data->setPseudoElement(BEFORE, 0);
1370 data->setPseudoElement(AFTER, 0);
Ben Murdoche69819b2013-07-17 14:56:49 +01001371 data->setPseudoElement(BACKDROP, 0);
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001372 data->setIsInCanvasSubtree(false);
1373 data->resetComputedStyle();
1374 data->resetDynamicRestyleObservations();
Ben Murdoch591b9582013-07-10 11:41:44 +01001375 data->setIsInsideRegion(false);
Torne (Richard Coles)f5e4ad52013-08-05 13:57:57 +01001376
1377 if (RuntimeEnabledFeatures::webAnimationsCSSEnabled() && !context.performingReattach) {
1378 if (ActiveAnimations* activeAnimations = data->activeAnimations())
1379 activeAnimations->cssAnimations()->cancel();
1380 }
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001381 }
Ben Murdoch591b9582013-07-10 11:41:44 +01001382 if (ElementShadow* shadow = this->shadow())
1383 shadow->detach(context);
Torne (Richard Coles)521d96e2013-06-19 11:58:24 +01001384 ContainerNode::detach(context);
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001385}
1386
1387bool Element::pseudoStyleCacheIsInvalid(const RenderStyle* currentStyle, RenderStyle* newStyle)
1388{
1389 ASSERT(currentStyle == renderStyle());
1390 ASSERT(renderer());
1391
1392 if (!currentStyle)
1393 return false;
1394
1395 const PseudoStyleCache* pseudoStyleCache = currentStyle->cachedPseudoStyles();
1396 if (!pseudoStyleCache)
1397 return false;
1398
1399 size_t cacheSize = pseudoStyleCache->size();
1400 for (size_t i = 0; i < cacheSize; ++i) {
1401 RefPtr<RenderStyle> newPseudoStyle;
1402 PseudoId pseudoId = pseudoStyleCache->at(i)->styleType();
1403 if (pseudoId == FIRST_LINE || pseudoId == FIRST_LINE_INHERITED)
1404 newPseudoStyle = renderer()->uncachedFirstLineStyle(newStyle);
1405 else
1406 newPseudoStyle = renderer()->getUncachedPseudoStyle(PseudoStyleRequest(pseudoId), newStyle, newStyle);
1407 if (!newPseudoStyle)
1408 return true;
1409 if (*newPseudoStyle != *pseudoStyleCache->at(i)) {
1410 if (pseudoId < FIRST_INTERNAL_PSEUDOID)
1411 newStyle->setHasPseudoStyle(pseudoId);
1412 newStyle->addCachedPseudoStyle(newPseudoStyle);
1413 if (pseudoId == FIRST_LINE || pseudoId == FIRST_LINE_INHERITED) {
1414 // FIXME: We should do an actual diff to determine whether a repaint vs. layout
1415 // is needed, but for now just assume a layout will be required. The diff code
1416 // in RenderObject::setStyle would need to be factored out so that it could be reused.
1417 renderer()->setNeedsLayoutAndPrefWidthsRecalc();
1418 }
1419 return true;
1420 }
1421 }
1422 return false;
1423}
1424
Torne (Richard Coles)521d96e2013-06-19 11:58:24 +01001425PassRefPtr<RenderStyle> Element::styleForRenderer()
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001426{
1427 if (hasCustomStyleCallbacks()) {
1428 if (RefPtr<RenderStyle> style = customStyleForRenderer())
1429 return style.release();
1430 }
1431
Torne (Richard Coles)521d96e2013-06-19 11:58:24 +01001432 return originalStyleForRenderer();
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001433}
1434
Torne (Richard Coles)521d96e2013-06-19 11:58:24 +01001435PassRefPtr<RenderStyle> Element::originalStyleForRenderer()
Torne (Richard Coles)5267f702013-06-11 10:57:24 +01001436{
Torne (Richard Coles)521d96e2013-06-19 11:58:24 +01001437 return document()->styleResolver()->styleForElement(this);
Torne (Richard Coles)5267f702013-06-11 10:57:24 +01001438}
1439
Ben Murdoche69819b2013-07-17 14:56:49 +01001440bool Element::recalcStyle(StyleChange change)
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001441{
Torne (Richard Coles)93ac45c2013-05-29 14:40:20 +01001442 ASSERT(document()->inStyleRecalc());
1443
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001444 if (hasCustomStyleCallbacks())
1445 willRecalcStyle(change);
1446
1447 // Ref currentStyle in case it would otherwise be deleted when setting the new style in the renderer.
Ben Murdoch83750172013-07-24 10:36:59 +01001448 RefPtr<RenderStyle> currentStyle = renderStyle();
1449 bool hasParentStyle = static_cast<bool>(parentRenderStyle());
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001450 bool hasDirectAdjacentRules = childrenAffectedByDirectAdjacentRules();
1451 bool hasIndirectAdjacentRules = childrenAffectedByForwardPositionalRules();
1452
Ben Murdoch83750172013-07-24 10:36:59 +01001453 if (change > NoChange || needsStyleRecalc()) {
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001454 if (hasRareData())
1455 elementRareData()->resetComputedStyle();
1456 }
1457 if (hasParentStyle && (change >= Inherit || needsStyleRecalc())) {
1458 StyleChange localChange = Detach;
1459 RefPtr<RenderStyle> newStyle;
1460 if (currentStyle) {
1461 // FIXME: This still recalcs style twice when changing display types, but saves
1462 // us from recalcing twice when going from none -> anything else which is more
1463 // common, especially during lazy attach.
Torne (Richard Coles)521d96e2013-06-19 11:58:24 +01001464 newStyle = styleForRenderer();
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001465 localChange = Node::diff(currentStyle.get(), newStyle.get(), document());
Torne (Richard Coles)521d96e2013-06-19 11:58:24 +01001466 } else if (attached() && isActiveInsertionPoint(this)) {
1467 // Active InsertionPoints will never have renderers so there's no reason to
1468 // reattach them repeatedly once they're already attached.
1469 localChange = change;
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001470 }
1471 if (localChange == Detach) {
Torne (Richard Coles)521d96e2013-06-19 11:58:24 +01001472 AttachContext reattachContext;
1473 reattachContext.resolvedStyle = newStyle.get();
1474 reattach(reattachContext);
1475
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001476 // attach recalculates the style for all children. No need to do it twice.
1477 clearNeedsStyleRecalc();
1478 clearChildNeedsStyleRecalc();
1479
1480 if (hasCustomStyleCallbacks())
1481 didRecalcStyle(change);
Ben Murdoche69819b2013-07-17 14:56:49 +01001482 return true;
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001483 }
1484
Ben Murdoch591b9582013-07-10 11:41:44 +01001485 InspectorInstrumentation::didRecalculateStyleForElement(this);
1486
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001487 if (RenderObject* renderer = this->renderer()) {
Torne (Richard Coles)f5e4ad52013-08-05 13:57:57 +01001488 if (localChange != NoChange || pseudoStyleCacheIsInvalid(currentStyle.get(), newStyle.get()) || (change == Force && renderer->requiresForcedStyleRecalcPropagation()) || shouldNotifyRendererWithIdenticalStyles()) {
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001489 renderer->setAnimatableStyle(newStyle.get());
Torne (Richard Coles)f5e4ad52013-08-05 13:57:57 +01001490 } else if (needsStyleRecalc()) {
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001491 // Although no change occurred, we use the new style so that the cousin style sharing code won't get
1492 // fooled into believing this style is the same.
1493 renderer->setStyleInternal(newStyle.get());
1494 }
1495 }
1496
1497 // 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
1498 // 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).
1499 if (document()->styleSheetCollection()->usesRemUnits() && document()->documentElement() == this && localChange != NoChange && currentStyle && newStyle && currentStyle->fontSize() != newStyle->fontSize()) {
1500 // Cached RenderStyles may depend on the re units.
1501 document()->styleResolver()->invalidateMatchedPropertiesCache();
1502 change = Force;
1503 }
1504
Ben Murdoche69819b2013-07-17 14:56:49 +01001505 if (styleChangeType() == SubtreeStyleChange)
Torne (Richard Coles)e5249552013-05-15 11:35:13 +01001506 change = Force;
1507 else if (change != Force)
1508 change = localChange;
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001509 }
1510 StyleResolverParentPusher parentPusher(this);
1511
Torne (Richard Coles)f5e4ad52013-08-05 13:57:57 +01001512 for (ShadowRoot* root = youngestShadowRoot(); root; root = root->olderShadowRoot()) {
1513 if (shouldRecalcStyle(change, root)) {
1514 parentPusher.push();
1515 root->recalcStyle(change);
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001516 }
1517 }
1518
1519 if (shouldRecalcStyle(change, this))
1520 updatePseudoElement(BEFORE, change);
1521
1522 // FIXME: This check is good enough for :hover + foo, but it is not good enough for :hover + foo + bar.
1523 // For now we will just worry about the common case, since it's a lot trickier to get the second case right
1524 // without doing way too much re-resolution.
1525 bool forceCheckOfNextElementSibling = false;
1526 bool forceCheckOfAnyElementSibling = false;
Ben Murdoche69819b2013-07-17 14:56:49 +01001527 bool forceReattachOfAnyWhitespaceSibling = false;
1528 for (Node* child = firstChild(); child; child = child->nextSibling()) {
1529 bool didReattach = false;
1530
1531 if (child->renderer())
1532 forceReattachOfAnyWhitespaceSibling = false;
1533
1534 if (child->isTextNode()) {
1535 if (forceReattachOfAnyWhitespaceSibling && toText(child)->containsOnlyWhitespace())
1536 child->reattach();
1537 else
1538 didReattach = toText(child)->recalcTextStyle(change);
1539 } else if (child->isElementNode()) {
1540 Element* element = toElement(child);
1541
1542 if (forceCheckOfNextElementSibling || forceCheckOfAnyElementSibling)
1543 element->setNeedsStyleRecalc();
1544
1545 bool childRulesChanged = element->needsStyleRecalc() && element->styleChangeType() == SubtreeStyleChange;
1546 forceCheckOfNextElementSibling = childRulesChanged && hasDirectAdjacentRules;
1547 forceCheckOfAnyElementSibling = forceCheckOfAnyElementSibling || (childRulesChanged && hasIndirectAdjacentRules);
1548
1549 if (shouldRecalcStyle(change, element)) {
1550 parentPusher.push();
1551 didReattach = element->recalcStyle(change);
1552 }
Ben Murdoch591b9582013-07-10 11:41:44 +01001553 }
Ben Murdoche69819b2013-07-17 14:56:49 +01001554
1555 forceReattachOfAnyWhitespaceSibling = didReattach || forceReattachOfAnyWhitespaceSibling;
Torne (Richard Coles)5267f702013-06-11 10:57:24 +01001556 }
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001557
1558 if (shouldRecalcStyle(change, this))
1559 updatePseudoElement(AFTER, change);
1560
1561 clearNeedsStyleRecalc();
1562 clearChildNeedsStyleRecalc();
Ben Murdoch591b9582013-07-10 11:41:44 +01001563
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001564 if (hasCustomStyleCallbacks())
1565 didRecalcStyle(change);
Ben Murdoche69819b2013-07-17 14:56:49 +01001566 return false;
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001567}
1568
1569ElementShadow* Element::shadow() const
1570{
1571 return hasRareData() ? elementRareData()->shadow() : 0;
1572}
1573
1574ElementShadow* Element::ensureShadow()
1575{
1576 return ensureElementRareData()->ensureShadow();
1577}
1578
1579void Element::didAffectSelector(AffectedSelectorMask mask)
1580{
1581 setNeedsStyleRecalc();
1582 if (ElementShadow* elementShadow = shadowOfParentForDistribution(this))
1583 elementShadow->didAffectSelector(mask);
1584}
1585
1586PassRefPtr<ShadowRoot> Element::createShadowRoot(ExceptionCode& ec)
1587{
1588 if (alwaysCreateUserAgentShadowRoot())
1589 ensureUserAgentShadowRoot();
1590
1591 if (RuntimeEnabledFeatures::authorShadowDOMForAnyElementEnabled())
1592 return ensureShadow()->addShadowRoot(this, ShadowRoot::AuthorShadowRoot);
1593
1594 // Since some elements recreates shadow root dynamically, multiple shadow
1595 // subtrees won't work well in that element. Until they are fixed, we disable
1596 // adding author shadow root for them.
1597 if (!areAuthorShadowsAllowed()) {
Ben Murdoche69819b2013-07-17 14:56:49 +01001598 ec = HierarchyRequestError;
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001599 return 0;
1600 }
1601 return ensureShadow()->addShadowRoot(this, ShadowRoot::AuthorShadowRoot);
1602}
1603
1604ShadowRoot* Element::shadowRoot() const
1605{
1606 ElementShadow* elementShadow = shadow();
1607 if (!elementShadow)
1608 return 0;
1609 ShadowRoot* shadowRoot = elementShadow->youngestShadowRoot();
1610 if (shadowRoot->type() == ShadowRoot::AuthorShadowRoot)
1611 return shadowRoot;
1612 return 0;
1613}
1614
1615ShadowRoot* Element::userAgentShadowRoot() const
1616{
1617 if (ElementShadow* elementShadow = shadow()) {
1618 if (ShadowRoot* shadowRoot = elementShadow->oldestShadowRoot()) {
1619 ASSERT(shadowRoot->type() == ShadowRoot::UserAgentShadowRoot);
1620 return shadowRoot;
1621 }
1622 }
1623
1624 return 0;
1625}
1626
1627ShadowRoot* Element::ensureUserAgentShadowRoot()
1628{
1629 if (ShadowRoot* shadowRoot = userAgentShadowRoot())
1630 return shadowRoot;
1631 ShadowRoot* shadowRoot = ensureShadow()->addShadowRoot(this, ShadowRoot::UserAgentShadowRoot);
1632 didAddUserAgentShadowRoot(shadowRoot);
1633 return shadowRoot;
1634}
1635
Torne (Richard Coles)f5e4ad52013-08-05 13:57:57 +01001636// FIXME: After replacing all internal shadowPseudoId with shadowPartId, remove this method.
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001637const AtomicString& Element::shadowPseudoId() const
1638{
1639 return pseudo();
1640}
1641
Torne (Richard Coles)f5e4ad52013-08-05 13:57:57 +01001642const AtomicString& Element::shadowPartId() const
1643{
1644 return part();
1645}
1646
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001647bool Element::childTypeAllowed(NodeType type) const
1648{
1649 switch (type) {
1650 case ELEMENT_NODE:
1651 case TEXT_NODE:
1652 case COMMENT_NODE:
1653 case PROCESSING_INSTRUCTION_NODE:
1654 case CDATA_SECTION_NODE:
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001655 return true;
1656 default:
1657 break;
1658 }
1659 return false;
1660}
1661
Ben Murdoch83750172013-07-24 10:36:59 +01001662static void inline checkForEmptyStyleChange(Element* element, RenderStyle* style)
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001663{
1664 if (!style && !element->styleAffectedByEmpty())
1665 return;
1666
1667 if (!style || (element->styleAffectedByEmpty() && (!style->emptyState() || element->hasChildNodes())))
1668 element->setNeedsStyleRecalc();
1669}
1670
1671static void checkForSiblingStyleChanges(Element* e, RenderStyle* style, bool finishedParsingCallback,
1672 Node* beforeChange, Node* afterChange, int childCountDelta)
1673{
Ben Murdoch83750172013-07-24 10:36:59 +01001674 if (!e->attached() || e->document()->hasPendingForcedStyleRecalc() || e->styleChangeType() == SubtreeStyleChange)
1675 return;
1676
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001677 // :empty selector.
1678 checkForEmptyStyleChange(e, style);
Ben Murdoch591b9582013-07-10 11:41:44 +01001679
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001680 if (!style || (e->needsStyleRecalc() && e->childrenAffectedByPositionalRules()))
1681 return;
1682
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001683 // Forward positional selectors include the ~ selector, nth-child, nth-of-type, first-of-type and only-of-type.
1684 // Backward positional selectors include nth-last-child, nth-last-of-type, last-of-type and only-of-type.
1685 // We have to invalidate everything following the insertion point in the forward case, and everything before the insertion point in the
1686 // backward case.
1687 // |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.
1688 // 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 +01001689 // here. recalcStyle will then force a walk of the children when it sees that this has happened.
1690 if ((e->childrenAffectedByForwardPositionalRules() && afterChange) || (e->childrenAffectedByBackwardPositionalRules() && beforeChange)) {
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001691 e->setNeedsStyleRecalc();
Ben Murdoch83750172013-07-24 10:36:59 +01001692 return;
1693 }
1694
1695 // :first-child. In the parser callback case, we don't have to check anything, since we were right the first time.
1696 // In the DOM case, we only need to do something if |afterChange| is not 0.
1697 // |afterChange| is 0 in the parser case, so it works out that we'll skip this block.
1698 if (e->childrenAffectedByFirstChildRules() && afterChange) {
1699 // Find our new first child.
1700 Node* newFirstChild = e->firstElementChild();
1701 RenderStyle* newFirstChildStyle = newFirstChild ? newFirstChild->renderStyle() : 0;
1702
1703 // Find the first element node following |afterChange|
1704 Node* firstElementAfterInsertion = afterChange->isElementNode() ? afterChange : afterChange->nextElementSibling();
1705 RenderStyle* firstElementAfterInsertionStyle = firstElementAfterInsertion ? firstElementAfterInsertion->renderStyle() : 0;
1706
1707 // This is the insert/append case.
1708 if (newFirstChild != firstElementAfterInsertion && firstElementAfterInsertionStyle && firstElementAfterInsertionStyle->firstChildState())
1709 firstElementAfterInsertion->setNeedsStyleRecalc();
1710
1711 // We also have to handle node removal.
1712 if (childCountDelta < 0 && newFirstChild == firstElementAfterInsertion && newFirstChild && (!newFirstChildStyle || !newFirstChildStyle->firstChildState()))
1713 newFirstChild->setNeedsStyleRecalc();
1714 }
1715
1716 // :last-child. In the parser callback case, we don't have to check anything, since we were right the first time.
1717 // In the DOM case, we only need to do something if |afterChange| is not 0.
1718 if (e->childrenAffectedByLastChildRules() && beforeChange) {
1719 // Find our new last child.
1720 Node* newLastChild = e->lastElementChild();
1721 RenderStyle* newLastChildStyle = newLastChild ? newLastChild->renderStyle() : 0;
1722
1723 // Find the last element node going backwards from |beforeChange|
1724 Node* lastElementBeforeInsertion = beforeChange->isElementNode() ? beforeChange : beforeChange->previousElementSibling();
1725 RenderStyle* lastElementBeforeInsertionStyle = lastElementBeforeInsertion ? lastElementBeforeInsertion->renderStyle() : 0;
1726
1727 if (newLastChild != lastElementBeforeInsertion && lastElementBeforeInsertionStyle && lastElementBeforeInsertionStyle->lastChildState())
1728 lastElementBeforeInsertion->setNeedsStyleRecalc();
1729
1730 // 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
1731 // to match now.
1732 if ((childCountDelta < 0 || finishedParsingCallback) && newLastChild == lastElementBeforeInsertion && newLastChild && (!newLastChildStyle || !newLastChildStyle->lastChildState()))
1733 newLastChild->setNeedsStyleRecalc();
1734 }
1735
1736 // The + selector. We need to invalidate the first element following the insertion point. It is the only possible element
1737 // that could be affected by this DOM change.
1738 if (e->childrenAffectedByDirectAdjacentRules() && afterChange) {
1739 if (Node* firstElementAfterInsertion = afterChange->nextElementSibling())
1740 firstElementAfterInsertion->setNeedsStyleRecalc();
1741 }
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001742}
1743
1744void Element::childrenChanged(bool changedByParser, Node* beforeChange, Node* afterChange, int childCountDelta)
1745{
1746 ContainerNode::childrenChanged(changedByParser, beforeChange, afterChange, childCountDelta);
1747 if (changedByParser)
1748 checkForEmptyStyleChange(this, renderStyle());
1749 else
1750 checkForSiblingStyleChanges(this, renderStyle(), false, beforeChange, afterChange, childCountDelta);
1751
Ben Murdoch83750172013-07-24 10:36:59 +01001752 if (ElementShadow* shadow = this->shadow())
Torne (Richard Coles)f5e4ad52013-08-05 13:57:57 +01001753 shadow->setNeedsDistributionRecalc();
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001754}
1755
1756void Element::removeAllEventListeners()
1757{
1758 ContainerNode::removeAllEventListeners();
1759 if (ElementShadow* shadow = this->shadow())
1760 shadow->removeAllEventListeners();
1761}
1762
1763void Element::beginParsingChildren()
1764{
1765 clearIsParsingChildrenFinished();
1766 StyleResolver* styleResolver = document()->styleResolverIfExists();
1767 if (styleResolver && attached())
1768 styleResolver->pushParentElement(this);
1769}
1770
1771void Element::finishParsingChildren()
1772{
1773 ContainerNode::finishParsingChildren();
1774 setIsParsingChildrenFinished();
1775 checkForSiblingStyleChanges(this, renderStyle(), true, lastChild(), 0, 0);
1776 if (StyleResolver* styleResolver = document()->styleResolverIfExists())
1777 styleResolver->popParentElement(this);
1778}
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
1814PassRefPtr<Attr> Element::setAttributeNode(Attr* attrNode, ExceptionCode& ec)
1815{
1816 if (!attrNode) {
Ben Murdoche69819b2013-07-17 14:56:49 +01001817 ec = 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()) {
Ben Murdoche69819b2013-07-17 14:56:49 +01001828 ec = InUseAttributeError;
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001829 return 0;
1830 }
1831
1832 synchronizeAllAttributes();
1833 UniqueElementData* elementData = ensureUniqueElementData();
1834
1835 size_t index = elementData->getAttributeItemIndex(attrNode->qualifiedName());
1836 if (index != notFound) {
1837 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);
Ben Murdoch591b9582013-07-10 11:41:44 +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
1852PassRefPtr<Attr> Element::setAttributeNodeNS(Attr* attr, ExceptionCode& ec)
1853{
1854 return setAttributeNode(attr, ec);
1855}
1856
1857PassRefPtr<Attr> Element::removeAttributeNode(Attr* attr, ExceptionCode& ec)
1858{
1859 if (!attr) {
Ben Murdoche69819b2013-07-17 14:56:49 +01001860 ec = TypeMismatchError;
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001861 return 0;
1862 }
1863 if (attr->ownerElement() != this) {
Ben Murdoche69819b2013-07-17 14:56:49 +01001864 ec = NotFoundError;
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001865 return 0;
1866 }
1867
1868 ASSERT(document() == attr->document());
1869
1870 synchronizeAttribute(attr->qualifiedName());
1871
Torne (Richard Coles)e5249552013-05-15 11:35:13 +01001872 size_t index = elementData()->getAttrIndex(attr);
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001873 if (index == notFound) {
Ben Murdoche69819b2013-07-17 14:56:49 +01001874 ec = 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
1883bool Element::parseAttributeName(QualifiedName& out, const AtomicString& namespaceURI, const AtomicString& qualifiedName, ExceptionCode& ec)
1884{
1885 String prefix, localName;
1886 if (!Document::parseQualifiedName(qualifiedName, prefix, localName, ec))
1887 return false;
1888 ASSERT(!ec);
1889
1890 QualifiedName qName(prefix, localName, namespaceURI);
1891
1892 if (!Document::hasValidNamespaceForAttributes(qName)) {
Ben Murdoche69819b2013-07-17 14:56:49 +01001893 ec = NamespaceError;
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001894 return false;
1895 }
1896
1897 out = qName;
1898 return true;
1899}
1900
1901void Element::setAttributeNS(const AtomicString& namespaceURI, const AtomicString& qualifiedName, const AtomicString& value, ExceptionCode& ec)
1902{
1903 QualifiedName parsedName = anyName;
1904 if (!parseAttributeName(parsedName, namespaceURI, qualifiedName, ec))
1905 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);
1948 if (index == notFound) {
1949 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
2007 Document* doc = document();
Ben Murdoch7757ec22013-07-23 11:17:36 +01002008 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)53e740f2013-05-09 18:38:43 +01002014 if (doc->haveStylesheetsLoaded()) {
2015 doc->updateLayoutIgnorePendingStylesheets();
2016 if (!isFocusable())
2017 return;
2018 }
2019
2020 if (!supportsFocus())
2021 return;
2022
2023 RefPtr<Node> protect;
2024 if (Page* page = doc->page()) {
2025 // 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;
Ben Murdoche69819b2013-07-17 14:56:49 +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.
2034 doc->updateLayoutIgnorePendingStylesheets();
2035
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()) {
2048 Frame* frame = document()->frame();
2049 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.
2053 if (this == frame->selection()->rootEditableElement())
2054 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)53e740f2013-05-09 18:38:43 +01002059 if (frame->selection()->shouldChangeSelection(newSelection)) {
2060 frame->selection()->setSelection(newSelection);
2061 frame->selection()->revealSelection();
2062 }
2063 } else if (renderer() && !renderer()->isWidget())
2064 renderer()->scrollRectToVisible(boundingBox());
2065}
2066
2067void Element::blur()
2068{
2069 cancelFocusAppearanceUpdate();
Ben Murdoche69819b2013-07-17 14:56:49 +01002070 if (treeScope()->adjustedFocusedElement() == this) {
2071 Document* doc = document();
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002072 if (doc->frame())
Ben Murdoche69819b2013-07-17 14:56:49 +01002073 doc->frame()->page()->focusController()->setFocusedElement(0, doc->frame());
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002074 else
Ben Murdoche69819b2013-07-17 14:56:49 +01002075 doc->setFocusedElement(0);
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002076 }
2077}
2078
Torne (Richard Coles)f5e4ad52013-08-05 13:57:57 +01002079bool Element::isKeyboardFocusable() const
2080{
2081 return isFocusable() && tabIndex() >= 0;
2082}
2083
2084bool Element::isMouseFocusable() const
2085{
2086 return isFocusable();
2087}
2088
Ben Murdoch02772c62013-07-26 10:21:05 +01002089void Element::dispatchFocusEvent(Element* oldFocusedElement, FocusDirection)
2090{
2091 RefPtr<FocusEvent> event = FocusEvent::create(eventNames().focusEvent, false, false, document()->defaultView(), 0, oldFocusedElement);
2092 EventDispatcher::dispatchEvent(this, FocusEventDispatchMediator::create(event.release()));
2093}
2094
2095void Element::dispatchBlurEvent(Element* newFocusedElement)
2096{
2097 RefPtr<FocusEvent> event = FocusEvent::create(eventNames().blurEvent, false, false, document()->defaultView(), 0, newFocusedElement);
2098 EventDispatcher::dispatchEvent(this, BlurEventDispatchMediator::create(event.release()));
2099}
2100
2101void Element::dispatchFocusInEvent(const AtomicString& eventType, Element* oldFocusedElement)
2102{
2103 ASSERT(!NoEventDispatchAssertion::isEventDispatchForbidden());
2104 ASSERT(eventType == eventNames().focusinEvent || eventType == eventNames().DOMFocusInEvent);
2105 dispatchScopedEventDispatchMediator(FocusInEventDispatchMediator::create(FocusEvent::create(eventType, true, false, document()->defaultView(), 0, oldFocusedElement)));
2106}
2107
2108void Element::dispatchFocusOutEvent(const AtomicString& eventType, Element* newFocusedElement)
2109{
2110 ASSERT(!NoEventDispatchAssertion::isEventDispatchForbidden());
2111 ASSERT(eventType == eventNames().focusoutEvent || eventType == eventNames().DOMFocusOutEvent);
2112 dispatchScopedEventDispatchMediator(FocusOutEventDispatchMediator::create(FocusEvent::create(eventType, true, false, document()->defaultView(), 0, newFocusedElement)));
2113}
2114
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002115String Element::innerText()
2116{
2117 // We need to update layout, since plainText uses line boxes in the render tree.
2118 document()->updateLayoutIgnorePendingStylesheets();
2119
2120 if (!renderer())
2121 return textContent(true);
2122
2123 return plainText(rangeOfContents(const_cast<Element*>(this)).get());
2124}
2125
2126String Element::outerText()
2127{
2128 // Getting outerText is the same as getting innerText, only
2129 // setting is different. You would think this should get the plain
2130 // text for the outer range, but this is wrong, <br> for instance
2131 // would return different values for inner and outer text by such
2132 // a rule, but it doesn't in WinIE, and we want to match that.
2133 return innerText();
2134}
2135
Ben Murdoch591b9582013-07-10 11:41:44 +01002136String Element::textFromChildren()
2137{
2138 Text* firstTextNode = 0;
2139 bool foundMultipleTextNodes = false;
2140 unsigned totalLength = 0;
2141
2142 for (Node* child = firstChild(); child; child = child->nextSibling()) {
2143 if (!child->isTextNode())
2144 continue;
2145 Text* text = toText(child);
2146 if (!firstTextNode)
2147 firstTextNode = text;
2148 else
2149 foundMultipleTextNodes = true;
2150 unsigned length = text->data().length();
2151 if (length > std::numeric_limits<unsigned>::max() - totalLength)
2152 return emptyString();
2153 totalLength += length;
2154 }
2155
2156 if (!firstTextNode)
2157 return emptyString();
2158
2159 if (firstTextNode && !foundMultipleTextNodes) {
2160 firstTextNode->atomize();
2161 return firstTextNode->data();
2162 }
2163
2164 StringBuilder content;
2165 content.reserveCapacity(totalLength);
2166 for (Node* child = firstTextNode; child; child = child->nextSibling()) {
2167 if (!child->isTextNode())
2168 continue;
2169 content.append(toText(child)->data());
2170 }
2171
2172 ASSERT(content.length() == totalLength);
2173 return content.toString();
2174}
2175
Torne (Richard Coles)f5e4ad52013-08-05 13:57:57 +01002176// FIXME: pseudo should be deprecated after all pseudo is replaced with ::part.
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002177const AtomicString& Element::pseudo() const
2178{
2179 return getAttribute(pseudoAttr);
2180}
2181
2182void Element::setPseudo(const AtomicString& value)
2183{
2184 setAttribute(pseudoAttr, value);
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())
2232 data->setComputedStyle(document()->styleForElementIgnoringPendingStylesheets(this));
2233 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{
2426 return document()->getCachedLocale(computeInheritedLanguage());
2427}
2428
2429void Element::cancelFocusAppearanceUpdate()
2430{
2431 if (hasRareData())
2432 elementRareData()->setNeedsFocusAppearanceUpdateSoonAfterAttach(false);
Ben Murdoch7757ec22013-07-23 11:17:36 +01002433 if (document()->focusedElement() == this)
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002434 document()->cancelFocusAppearanceUpdate();
2435}
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
2447void Element::updatePseudoElement(PseudoId pseudoId, StyleChange change)
2448{
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{
Ben Murdoche69819b2013-07-17 14:56:49 +01002467 if ((pseudoId == BEFORE || pseudoId == AFTER) && !document()->styleSheetCollection()->usesBeforeAfterRules())
2468 return;
2469
2470 if (pseudoId == BACKDROP && !isInTopLayer())
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002471 return;
2472
2473 if (!renderer() || !pseudoElementRendererIsNeeded(renderer()->getCachedPseudoStyle(pseudoId)))
2474 return;
2475
2476 if (!renderer()->canHaveGeneratedChildren())
2477 return;
2478
2479 ASSERT(!isPseudoElement());
2480 RefPtr<PseudoElement> element = PseudoElement::create(this, pseudoId);
Ben Murdoche69819b2013-07-17 14:56:49 +01002481 if (pseudoId == BACKDROP)
2482 document()->addToTopLayer(element.get(), this);
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002483 element->attach();
Ben Murdoche69819b2013-07-17 14:56:49 +01002484
Torne (Richard Coles)521d96e2013-06-19 11:58:24 +01002485 ensureElementRareData()->setPseudoElement(pseudoId, element.release());
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002486}
2487
2488PseudoElement* Element::pseudoElement(PseudoId pseudoId) const
2489{
2490 return hasRareData() ? elementRareData()->pseudoElement(pseudoId) : 0;
2491}
2492
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002493RenderObject* Element::pseudoElementRenderer(PseudoId pseudoId) const
2494{
2495 if (PseudoElement* element = pseudoElement(pseudoId))
2496 return element->renderer();
2497 return 0;
2498}
2499
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002500bool Element::webkitMatchesSelector(const String& selector, ExceptionCode& ec)
2501{
2502 if (selector.isEmpty()) {
Ben Murdoche69819b2013-07-17 14:56:49 +01002503 ec = SyntaxError;
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002504 return false;
2505 }
2506
2507 SelectorQuery* selectorQuery = document()->selectorQueryCache()->add(selector, document(), ec);
2508 if (!selectorQuery)
2509 return false;
2510 return selectorQuery->matches(this);
2511}
2512
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002513DOMTokenList* Element::classList()
2514{
2515 ElementRareData* data = ensureElementRareData();
2516 if (!data->classList())
2517 data->setClassList(ClassList::create(this));
2518 return data->classList();
2519}
2520
2521DOMStringMap* Element::dataset()
2522{
2523 ElementRareData* data = ensureElementRareData();
2524 if (!data->dataset())
2525 data->setDataset(DatasetDOMStringMap::create(this));
2526 return data->dataset();
2527}
2528
2529KURL Element::getURLAttribute(const QualifiedName& name) const
2530{
2531#if !ASSERT_DISABLED
2532 if (elementData()) {
2533 if (const Attribute* attribute = getAttributeItem(name))
2534 ASSERT(isURLAttribute(*attribute));
2535 }
2536#endif
2537 return document()->completeURL(stripLeadingAndTrailingHTMLSpaces(getAttribute(name)));
2538}
2539
2540KURL Element::getNonEmptyURLAttribute(const QualifiedName& name) const
2541{
2542#if !ASSERT_DISABLED
2543 if (elementData()) {
2544 if (const Attribute* attribute = getAttributeItem(name))
2545 ASSERT(isURLAttribute(*attribute));
2546 }
2547#endif
2548 String value = stripLeadingAndTrailingHTMLSpaces(getAttribute(name));
2549 if (value.isEmpty())
2550 return KURL();
2551 return document()->completeURL(value);
2552}
2553
2554int Element::getIntegralAttribute(const QualifiedName& attributeName) const
2555{
2556 return getAttribute(attributeName).string().toInt();
2557}
2558
2559void Element::setIntegralAttribute(const QualifiedName& attributeName, int value)
2560{
2561 // FIXME: Need an AtomicString version of String::number.
2562 setAttribute(attributeName, String::number(value));
2563}
2564
2565unsigned Element::getUnsignedIntegralAttribute(const QualifiedName& attributeName) const
2566{
2567 return getAttribute(attributeName).string().toUInt();
2568}
2569
2570void Element::setUnsignedIntegralAttribute(const QualifiedName& attributeName, unsigned value)
2571{
2572 // FIXME: Need an AtomicString version of String::number.
2573 setAttribute(attributeName, String::number(value));
2574}
2575
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002576bool Element::childShouldCreateRenderer(const NodeRenderingContext& childContext) const
2577{
2578 // Only create renderers for SVG elements whose parents are SVG elements, or for proper <svg xmlns="svgNS"> subdocuments.
2579 if (childContext.node()->isSVGElement())
2580 return childContext.node()->hasTagName(SVGNames::svgTag) || isSVGElement();
2581
2582 return ContainerNode::childShouldCreateRenderer(childContext);
2583}
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002584
2585void Element::webkitRequestFullscreen()
2586{
Torne (Richard Coles)f5e4ad52013-08-05 13:57:57 +01002587 FullscreenElementStack::from(document())->requestFullScreenForElement(this, ALLOW_KEYBOARD_INPUT, FullscreenElementStack::EnforceIFrameAllowFullScreenRequirement);
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002588}
2589
2590void Element::webkitRequestFullScreen(unsigned short flags)
2591{
Torne (Richard Coles)f5e4ad52013-08-05 13:57:57 +01002592 FullscreenElementStack::from(document())->requestFullScreenForElement(this, (flags | LEGACY_MOZILLA_REQUEST), FullscreenElementStack::EnforceIFrameAllowFullScreenRequirement);
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002593}
2594
2595bool Element::containsFullScreenElement() const
2596{
2597 return hasRareData() && elementRareData()->containsFullScreenElement();
2598}
2599
2600void Element::setContainsFullScreenElement(bool flag)
2601{
2602 ensureElementRareData()->setContainsFullScreenElement(flag);
Ben Murdoche69819b2013-07-17 14:56:49 +01002603 setNeedsStyleRecalc(SubtreeStyleChange);
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002604}
2605
2606static Element* parentCrossingFrameBoundaries(Element* element)
2607{
2608 ASSERT(element);
2609 return element->parentElement() ? element->parentElement() : element->document()->ownerElement();
2610}
2611
2612void Element::setContainsFullScreenElementOnAncestorsCrossingFrameBoundaries(bool flag)
2613{
2614 Element* element = this;
2615 while ((element = parentCrossingFrameBoundaries(element)))
2616 element->setContainsFullScreenElement(flag);
2617}
2618
2619bool Element::isInTopLayer() const
2620{
2621 return hasRareData() && elementRareData()->isInTopLayer();
2622}
2623
2624void Element::setIsInTopLayer(bool inTopLayer)
2625{
2626 if (isInTopLayer() == inTopLayer)
2627 return;
2628 ensureElementRareData()->setIsInTopLayer(inTopLayer);
2629
2630 // We must ensure a reattach occurs so the renderer is inserted in the correct sibling order under RenderView according to its
2631 // top layer position, or in its usual place if not in the top layer.
Torne (Richard Coles)93ac45c2013-05-29 14:40:20 +01002632 lazyReattachIfAttached();
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002633}
2634
2635void Element::webkitRequestPointerLock()
2636{
2637 if (document()->page())
2638 document()->page()->pointerLockController()->requestPointerLock(this);
2639}
2640
2641SpellcheckAttributeState Element::spellcheckAttributeState() const
2642{
2643 const AtomicString& value = getAttribute(HTMLNames::spellcheckAttr);
2644 if (value == nullAtom)
2645 return SpellcheckAttributeDefault;
2646 if (equalIgnoringCase(value, "true") || equalIgnoringCase(value, ""))
2647 return SpellcheckAttributeTrue;
2648 if (equalIgnoringCase(value, "false"))
2649 return SpellcheckAttributeFalse;
2650
2651 return SpellcheckAttributeDefault;
2652}
2653
2654bool Element::isSpellCheckingEnabled() const
2655{
2656 for (const Element* element = this; element; element = element->parentOrShadowHostElement()) {
2657 switch (element->spellcheckAttributeState()) {
2658 case SpellcheckAttributeTrue:
2659 return true;
2660 case SpellcheckAttributeFalse:
2661 return false;
2662 case SpellcheckAttributeDefault:
2663 break;
2664 }
2665 }
2666
2667 return true;
2668}
2669
2670RenderRegion* Element::renderRegion() const
2671{
2672 if (renderer() && renderer()->isRenderRegion())
2673 return toRenderRegion(renderer());
2674
2675 return 0;
2676}
2677
Ben Murdoch591b9582013-07-10 11:41:44 +01002678bool Element::shouldMoveToFlowThread(RenderStyle* styleToUse) const
2679{
2680 ASSERT(styleToUse);
2681
Torne (Richard Coles)f5e4ad52013-08-05 13:57:57 +01002682 if (FullscreenElementStack::isActiveFullScreenElement(this))
Ben Murdoch591b9582013-07-10 11:41:44 +01002683 return false;
2684
2685 if (isInShadowTree())
2686 return false;
2687
2688 if (styleToUse->flowThread().isEmpty())
2689 return false;
2690
2691 return !isRegisteredWithNamedFlow();
2692}
2693
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002694const AtomicString& Element::webkitRegionOverset() const
2695{
2696 document()->updateLayoutIgnorePendingStylesheets();
2697
2698 DEFINE_STATIC_LOCAL(AtomicString, undefinedState, ("undefined", AtomicString::ConstructFromLiteral));
2699 if (!RuntimeEnabledFeatures::cssRegionsEnabled() || !renderRegion())
2700 return undefinedState;
2701
Ben Murdoch591b9582013-07-10 11:41:44 +01002702 switch (renderRegion()->regionOversetState()) {
2703 case RegionFit: {
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002704 DEFINE_STATIC_LOCAL(AtomicString, fitState, ("fit", AtomicString::ConstructFromLiteral));
2705 return fitState;
2706 }
Ben Murdoch591b9582013-07-10 11:41:44 +01002707 case RegionEmpty: {
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002708 DEFINE_STATIC_LOCAL(AtomicString, emptyState, ("empty", AtomicString::ConstructFromLiteral));
2709 return emptyState;
2710 }
Ben Murdoch591b9582013-07-10 11:41:44 +01002711 case RegionOverset: {
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002712 DEFINE_STATIC_LOCAL(AtomicString, overflowState, ("overset", AtomicString::ConstructFromLiteral));
2713 return overflowState;
2714 }
Ben Murdoch591b9582013-07-10 11:41:44 +01002715 case RegionUndefined:
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002716 return undefinedState;
2717 }
2718
2719 ASSERT_NOT_REACHED();
2720 return undefinedState;
2721}
2722
2723Vector<RefPtr<Range> > Element::webkitGetRegionFlowRanges() const
2724{
2725 document()->updateLayoutIgnorePendingStylesheets();
2726
2727 Vector<RefPtr<Range> > rangeObjects;
2728 if (RuntimeEnabledFeatures::cssRegionsEnabled() && renderer() && renderer()->isRenderRegion()) {
2729 RenderRegion* region = toRenderRegion(renderer());
2730 if (region->isValid())
2731 region->getRanges(rangeObjects);
2732 }
2733
2734 return rangeObjects;
2735}
2736
2737#ifndef NDEBUG
2738bool Element::fastAttributeLookupAllowed(const QualifiedName& name) const
2739{
2740 if (name == HTMLNames::styleAttr)
2741 return false;
2742
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002743 if (isSVGElement())
2744 return !static_cast<const SVGElement*>(this)->isAnimatableAttribute(name);
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002745
2746 return true;
2747}
2748#endif
2749
2750#ifdef DUMP_NODE_STATISTICS
2751bool Element::hasNamedNodeMap() const
2752{
2753 return hasRareData() && elementRareData()->attributeMap();
2754}
2755#endif
2756
2757inline void Element::updateName(const AtomicString& oldName, const AtomicString& newName)
2758{
Torne (Richard Coles)f5e4ad52013-08-05 13:57:57 +01002759 if (!isInTreeScope())
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002760 return;
2761
2762 if (oldName == newName)
2763 return;
2764
Torne (Richard Coles)f5e4ad52013-08-05 13:57:57 +01002765 updateName(treeScope(), oldName, newName);
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002766}
2767
Torne (Richard Coles)f5e4ad52013-08-05 13:57:57 +01002768void Element::updateName(TreeScope* scope, const AtomicString& oldName, const AtomicString& newName)
2769{
2770 ASSERT(isInTreeScope());
2771 ASSERT(oldName != newName);
2772
2773 if (!oldName.isEmpty())
2774 scope->removeElementByName(oldName, this);
2775 if (!newName.isEmpty())
2776 scope->addElementByName(newName, this);
2777
2778 if (!inDocument() || isInShadowTree())
2779 return;
2780
2781 Document* ownerDocument = document();
2782 if (!ownerDocument->isHTMLDocument())
2783 return;
2784
2785 if (WindowNameCollection::nodeMatchesIfNameAttributeMatch(this)) {
2786 if (!oldName.isEmpty())
2787 toHTMLDocument(ownerDocument)->windowNamedItemMap().remove(oldName.impl(), this);
2788 if (!newName.isEmpty())
2789 toHTMLDocument(ownerDocument)->windowNamedItemMap().add(newName.impl(), this);
2790 }
2791
2792 if (DocumentNameCollection::nodeMatchesIfNameAttributeMatch(this)) {
2793 if (!oldName.isEmpty())
2794 toHTMLDocument(ownerDocument)->removeNamedDocumentItem(oldName, this);
2795 if (!newName.isEmpty())
2796 toHTMLDocument(ownerDocument)->addNamedDocumentItem(newName, this);
2797 }
2798}
2799
2800void Element::updateId(const AtomicString& oldId, const AtomicString& newId)
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002801{
2802 if (!isInTreeScope())
2803 return;
2804
2805 if (oldId == newId)
2806 return;
2807
2808 updateId(treeScope(), oldId, newId);
2809}
2810
2811inline void Element::updateId(TreeScope* scope, const AtomicString& oldId, const AtomicString& newId)
2812{
2813 ASSERT(isInTreeScope());
2814 ASSERT(oldId != newId);
2815
2816 if (!oldId.isEmpty())
2817 scope->removeElementById(oldId, this);
2818 if (!newId.isEmpty())
2819 scope->addElementById(newId, this);
2820
Torne (Richard Coles)f5e4ad52013-08-05 13:57:57 +01002821 if (!inDocument() || isInShadowTree())
2822 return;
2823
2824 Document* ownerDocument = document();
2825 if (!ownerDocument->isHTMLDocument())
2826 return;
2827
2828 if (WindowNameCollection::nodeMatchesIfIdAttributeMatch(this)) {
2829 if (!oldId.isEmpty())
2830 toHTMLDocument(ownerDocument)->windowNamedItemMap().remove(oldId.impl(), this);
2831 if (!newId.isEmpty())
2832 toHTMLDocument(ownerDocument)->windowNamedItemMap().add(newId.impl(), this);
2833 }
2834
2835 if (DocumentNameCollection::nodeMatchesIfIdAttributeMatch(this)) {
2836 if (!oldId.isEmpty())
2837 toHTMLDocument(ownerDocument)->removeNamedDocumentItem(oldId, this);
2838 if (!newId.isEmpty())
2839 toHTMLDocument(ownerDocument)->addNamedDocumentItem(newId, this);
2840 }
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002841}
2842
2843void Element::updateLabel(TreeScope* scope, const AtomicString& oldForAttributeValue, const AtomicString& newForAttributeValue)
2844{
2845 ASSERT(hasTagName(labelTag));
2846
2847 if (!inDocument())
2848 return;
2849
2850 if (oldForAttributeValue == newForAttributeValue)
2851 return;
2852
2853 if (!oldForAttributeValue.isEmpty())
Ben Murdoche69819b2013-07-17 14:56:49 +01002854 scope->removeLabel(oldForAttributeValue, toHTMLLabelElement(this));
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002855 if (!newForAttributeValue.isEmpty())
Ben Murdoche69819b2013-07-17 14:56:49 +01002856 scope->addLabel(newForAttributeValue, toHTMLLabelElement(this));
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002857}
2858
Ben Murdoch7757ec22013-07-23 11:17:36 +01002859static bool hasSelectorForAttribute(Document* document, const AtomicString& localName)
2860{
2861 return document->styleResolver() && document->styleResolver()->ruleFeatureSet().hasSelectorForAttribute(localName);
2862}
2863
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002864void Element::willModifyAttribute(const QualifiedName& name, const AtomicString& oldValue, const AtomicString& newValue)
2865{
2866 if (isIdAttributeName(name))
2867 updateId(oldValue, newValue);
2868 else if (name == HTMLNames::nameAttr)
2869 updateName(oldValue, newValue);
2870 else if (name == HTMLNames::forAttr && hasTagName(labelTag)) {
2871 TreeScope* scope = treeScope();
2872 if (scope->shouldCacheLabelsByForAttribute())
2873 updateLabel(scope, oldValue, newValue);
2874 }
2875
2876 if (oldValue != newValue) {
Ben Murdoch7757ec22013-07-23 11:17:36 +01002877 if (attached() && hasSelectorForAttribute(document(), name.localName()))
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002878 setNeedsStyleRecalc();
Ben Murdoche69819b2013-07-17 14:56:49 +01002879
2880 if (isUpgradedCustomElement())
Ben Murdoch83750172013-07-24 10:36:59 +01002881 CustomElement::attributeDidChange(this, name.localName(), oldValue, newValue);
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002882 }
2883
2884 if (OwnPtr<MutationObserverInterestGroup> recipients = MutationObserverInterestGroup::createForAttributesMutation(this, name))
2885 recipients->enqueueMutationRecord(MutationRecord::createAttributes(this, name, oldValue));
2886
2887 InspectorInstrumentation::willModifyDOMAttr(document(), this, oldValue, newValue);
2888}
2889
2890void Element::didAddAttribute(const QualifiedName& name, const AtomicString& value)
2891{
2892 attributeChanged(name, value);
2893 InspectorInstrumentation::didModifyDOMAttr(document(), this, name.localName(), value);
2894 dispatchSubtreeModifiedEvent();
2895}
2896
2897void Element::didModifyAttribute(const QualifiedName& name, const AtomicString& value)
2898{
2899 attributeChanged(name, value);
2900 InspectorInstrumentation::didModifyDOMAttr(document(), this, name.localName(), value);
2901 // Do not dispatch a DOMSubtreeModified event here; see bug 81141.
2902}
2903
2904void Element::didRemoveAttribute(const QualifiedName& name)
2905{
2906 attributeChanged(name, nullAtom);
2907 InspectorInstrumentation::didRemoveDOMAttr(document(), this, name.localName());
2908 dispatchSubtreeModifiedEvent();
2909}
2910
Ben Murdoche69819b2013-07-17 14:56:49 +01002911void Element::didMoveToNewDocument(Document* oldDocument)
2912{
2913 Node::didMoveToNewDocument(oldDocument);
2914
2915 // If the documents differ by quirks mode then they differ by case sensitivity
2916 // for class and id names so we need to go through the attribute change logic
2917 // to pick up the new casing in the ElementData.
2918 if (oldDocument->inQuirksMode() != document()->inQuirksMode()) {
2919 if (hasID())
2920 setIdAttribute(getIdAttribute());
2921 if (hasClass())
2922 setAttribute(HTMLNames::classAttr, getClassAttribute());
2923 }
2924}
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002925
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002926PassRefPtr<HTMLCollection> Element::ensureCachedHTMLCollection(CollectionType type)
2927{
2928 if (HTMLCollection* collection = cachedHTMLCollection(type))
2929 return collection;
2930
2931 RefPtr<HTMLCollection> collection;
2932 if (type == TableRows) {
2933 ASSERT(hasTagName(tableTag));
2934 return ensureRareData()->ensureNodeLists()->addCacheWithAtomicName<HTMLTableRowsCollection>(this, type);
2935 } else if (type == SelectOptions) {
2936 ASSERT(hasTagName(selectTag));
2937 return ensureRareData()->ensureNodeLists()->addCacheWithAtomicName<HTMLOptionsCollection>(this, type);
2938 } else if (type == FormControls) {
2939 ASSERT(hasTagName(formTag) || hasTagName(fieldsetTag));
2940 return ensureRareData()->ensureNodeLists()->addCacheWithAtomicName<HTMLFormControlsCollection>(this, type);
2941 }
2942 return ensureRareData()->ensureNodeLists()->addCacheWithAtomicName<HTMLCollection>(this, type);
2943}
2944
Ben Murdoch591b9582013-07-10 11:41:44 +01002945static void scheduleLayerUpdateCallback(Node* node)
Torne (Richard Coles)93ac45c2013-05-29 14:40:20 +01002946{
Ben Murdoche69819b2013-07-17 14:56:49 +01002947 // Notify the renderer even is the styles are identical since it may need to
2948 // create or destroy a RenderLayer.
2949 node->setNeedsStyleRecalc(LocalStyleChange, StyleChangeFromRenderer);
Torne (Richard Coles)93ac45c2013-05-29 14:40:20 +01002950}
2951
Ben Murdoch591b9582013-07-10 11:41:44 +01002952void Element::scheduleLayerUpdate()
Torne (Richard Coles)93ac45c2013-05-29 14:40:20 +01002953{
2954 if (postAttachCallbacksAreSuspended())
Ben Murdoch591b9582013-07-10 11:41:44 +01002955 queuePostAttachCallback(scheduleLayerUpdateCallback, this);
Torne (Richard Coles)93ac45c2013-05-29 14:40:20 +01002956 else
Ben Murdoche69819b2013-07-17 14:56:49 +01002957 scheduleLayerUpdateCallback(this);
Torne (Richard Coles)93ac45c2013-05-29 14:40:20 +01002958}
2959
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01002960HTMLCollection* Element::cachedHTMLCollection(CollectionType type)
2961{
2962 return hasRareData() && rareData()->nodeLists() ? rareData()->nodeLists()->cacheWithAtomicName<HTMLCollection>(type) : 0;
2963}
2964
2965IntSize Element::savedLayerScrollOffset() const
2966{
2967 return hasRareData() ? elementRareData()->savedLayerScrollOffset() : IntSize();
2968}
2969
2970void Element::setSavedLayerScrollOffset(const IntSize& size)
2971{
2972 if (size.isZero() && !hasRareData())
2973 return;
2974 ensureElementRareData()->setSavedLayerScrollOffset(size);
2975}
2976
2977PassRefPtr<Attr> Element::attrIfExists(const QualifiedName& name)
2978{
2979 if (AttrNodeList* attrNodeList = attrNodeListForElement(this))
2980 return findAttrNodeInList(attrNodeList, name);
2981 return 0;
2982}
2983
2984PassRefPtr<Attr> Element::ensureAttr(const QualifiedName& name)
2985{
2986 AttrNodeList* attrNodeList = ensureAttrNodeListForElement(this);
2987 RefPtr<Attr> attrNode = findAttrNodeInList(attrNodeList, name);
2988 if (!attrNode) {
2989 attrNode = Attr::create(this, name);
2990 treeScope()->adoptIfNeeded(attrNode.get());
2991 attrNodeList->append(attrNode);
2992 }
2993 return attrNode.release();
2994}
2995
2996void Element::detachAttrNodeFromElementWithValue(Attr* attrNode, const AtomicString& value)
2997{
2998 ASSERT(hasSyntheticAttrChildNodes());
2999 attrNode->detachFromElementWithValue(value);
3000
3001 AttrNodeList* attrNodeList = attrNodeListForElement(this);
3002 for (unsigned i = 0; i < attrNodeList->size(); ++i) {
3003 if (attrNodeList->at(i)->qualifiedName() == attrNode->qualifiedName()) {
3004 attrNodeList->remove(i);
3005 if (attrNodeList->isEmpty())
3006 removeAttrNodeListForElement(this);
3007 return;
3008 }
3009 }
3010 ASSERT_NOT_REACHED();
3011}
3012
3013void Element::detachAllAttrNodesFromElement()
3014{
3015 AttrNodeList* attrNodeList = attrNodeListForElement(this);
3016 ASSERT(attrNodeList);
3017
3018 for (unsigned i = 0; i < attributeCount(); ++i) {
3019 const Attribute* attribute = attributeItem(i);
3020 if (RefPtr<Attr> attrNode = findAttrNodeInList(attrNodeList, attribute->name()))
3021 attrNode->detachFromElementWithValue(attribute->value());
3022 }
3023
3024 removeAttrNodeListForElement(this);
3025}
3026
3027void Element::willRecalcStyle(StyleChange)
3028{
3029 ASSERT(hasCustomStyleCallbacks());
3030}
3031
3032void Element::didRecalcStyle(StyleChange)
3033{
3034 ASSERT(hasCustomStyleCallbacks());
3035}
3036
3037
3038PassRefPtr<RenderStyle> Element::customStyleForRenderer()
3039{
3040 ASSERT(hasCustomStyleCallbacks());
3041 return 0;
3042}
3043
3044void Element::cloneAttributesFromElement(const Element& other)
3045{
3046 if (hasSyntheticAttrChildNodes())
3047 detachAllAttrNodesFromElement();
3048
3049 other.synchronizeAllAttributes();
3050 if (!other.m_elementData) {
3051 m_elementData.clear();
3052 return;
3053 }
3054
3055 const AtomicString& oldID = getIdAttribute();
3056 const AtomicString& newID = other.getIdAttribute();
3057
3058 if (!oldID.isNull() || !newID.isNull())
3059 updateId(oldID, newID);
3060
3061 const AtomicString& oldName = getNameAttribute();
3062 const AtomicString& newName = other.getNameAttribute();
3063
3064 if (!oldName.isNull() || !newName.isNull())
3065 updateName(oldName, newName);
3066
Ben Murdoche69819b2013-07-17 14:56:49 +01003067 // Quirks mode makes class and id not case sensitive. We can't share the ElementData
3068 // if the idForStyleResolution and the className need different casing.
3069 bool ownerDocumentsHaveDifferentCaseSensitivity = false;
3070 if (other.hasClass() || other.hasID())
3071 ownerDocumentsHaveDifferentCaseSensitivity = other.document()->inQuirksMode() != document()->inQuirksMode();
3072
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01003073 // 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 +01003074 // We can only do this if there is no CSSOM wrapper for other's inline style, and there are no presentation attributes,
3075 // and sharing the data won't result in different case sensitivity of class or id.
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01003076 if (other.m_elementData->isUnique()
Ben Murdoche69819b2013-07-17 14:56:49 +01003077 && !ownerDocumentsHaveDifferentCaseSensitivity
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01003078 && !other.m_elementData->presentationAttributeStyle()
3079 && (!other.m_elementData->inlineStyle() || !other.m_elementData->inlineStyle()->hasCSSOMWrapper()))
3080 const_cast<Element&>(other).m_elementData = static_cast<const UniqueElementData*>(other.m_elementData.get())->makeShareableCopy();
3081
Ben Murdoche69819b2013-07-17 14:56:49 +01003082 if (!other.m_elementData->isUnique() && !ownerDocumentsHaveDifferentCaseSensitivity)
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01003083 m_elementData = other.m_elementData;
3084 else
3085 m_elementData = other.m_elementData->makeUniqueCopy();
3086
3087 for (unsigned i = 0; i < m_elementData->length(); ++i) {
3088 const Attribute* attribute = const_cast<const ElementData*>(m_elementData.get())->attributeItem(i);
3089 attributeChangedFromParserOrByCloning(attribute->name(), attribute->value(), ModifiedByCloning);
3090 }
3091}
3092
3093void Element::cloneDataFromElement(const Element& other)
3094{
3095 cloneAttributesFromElement(other);
3096 copyNonAttributePropertiesFromElement(other);
3097}
3098
3099void Element::createUniqueElementData()
3100{
3101 if (!m_elementData)
3102 m_elementData = UniqueElementData::create();
3103 else {
3104 ASSERT(!m_elementData->isUnique());
3105 m_elementData = static_cast<ShareableElementData*>(m_elementData.get())->makeUniqueCopy();
3106 }
3107}
3108
Torne (Richard Coles)81a51572013-05-13 16:52:28 +01003109InputMethodContext* Element::getInputContext()
3110{
3111 return ensureElementRareData()->ensureInputMethodContext(toHTMLElement(this));
3112}
3113
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01003114bool Element::hasPendingResources() const
3115{
3116 return hasRareData() && elementRareData()->hasPendingResources();
3117}
3118
3119void Element::setHasPendingResources()
3120{
3121 ensureElementRareData()->setHasPendingResources(true);
3122}
3123
3124void Element::clearHasPendingResources()
3125{
3126 ensureElementRareData()->setHasPendingResources(false);
3127}
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01003128
Ben Murdoch591b9582013-07-10 11:41:44 +01003129struct PresentationAttributeCacheKey {
3130 PresentationAttributeCacheKey() : tagName(0) { }
Ben Murdoch83750172013-07-24 10:36:59 +01003131 StringImpl* tagName;
Ben Murdoch591b9582013-07-10 11:41:44 +01003132 // Only the values need refcounting.
Ben Murdoch83750172013-07-24 10:36:59 +01003133 Vector<pair<StringImpl*, AtomicString>, 3> attributesAndValues;
Ben Murdoch591b9582013-07-10 11:41:44 +01003134};
3135
3136struct PresentationAttributeCacheEntry {
3137 WTF_MAKE_FAST_ALLOCATED;
3138public:
3139 PresentationAttributeCacheKey key;
3140 RefPtr<StylePropertySet> value;
3141};
3142
3143typedef HashMap<unsigned, OwnPtr<PresentationAttributeCacheEntry>, AlreadyHashed> PresentationAttributeCache;
3144
3145static bool operator!=(const PresentationAttributeCacheKey& a, const PresentationAttributeCacheKey& b)
3146{
3147 if (a.tagName != b.tagName)
3148 return true;
3149 return a.attributesAndValues != b.attributesAndValues;
3150}
3151
3152static PresentationAttributeCache& presentationAttributeCache()
3153{
3154 DEFINE_STATIC_LOCAL(PresentationAttributeCache, cache, ());
3155 return cache;
3156}
3157
3158class PresentationAttributeCacheCleaner {
3159 WTF_MAKE_NONCOPYABLE(PresentationAttributeCacheCleaner); WTF_MAKE_FAST_ALLOCATED;
3160public:
3161 PresentationAttributeCacheCleaner()
3162 : m_hitCount(0)
3163 , m_cleanTimer(this, &PresentationAttributeCacheCleaner::cleanCache)
3164 {
3165 }
3166
3167 void didHitPresentationAttributeCache()
3168 {
3169 if (presentationAttributeCache().size() < minimumPresentationAttributeCacheSizeForCleaning)
3170 return;
3171
3172 m_hitCount++;
3173
3174 if (!m_cleanTimer.isActive())
3175 m_cleanTimer.startOneShot(presentationAttributeCacheCleanTimeInSeconds);
3176 }
3177
3178private:
3179 static const unsigned presentationAttributeCacheCleanTimeInSeconds = 60;
3180 static const int minimumPresentationAttributeCacheSizeForCleaning = 100;
3181 static const unsigned minimumPresentationAttributeCacheHitCountPerMinute = (100 * presentationAttributeCacheCleanTimeInSeconds) / 60;
3182
3183 void cleanCache(Timer<PresentationAttributeCacheCleaner>* timer)
3184 {
3185 ASSERT_UNUSED(timer, timer == &m_cleanTimer);
3186 unsigned hitCount = m_hitCount;
3187 m_hitCount = 0;
3188 if (hitCount > minimumPresentationAttributeCacheHitCountPerMinute)
3189 return;
3190 presentationAttributeCache().clear();
3191 }
3192
3193 unsigned m_hitCount;
3194 Timer<PresentationAttributeCacheCleaner> m_cleanTimer;
3195};
3196
3197static PresentationAttributeCacheCleaner& presentationAttributeCacheCleaner()
3198{
3199 DEFINE_STATIC_LOCAL(PresentationAttributeCacheCleaner, cleaner, ());
3200 return cleaner;
3201}
3202
3203void Element::synchronizeStyleAttributeInternal() const
3204{
3205 ASSERT(isStyledElement());
3206 ASSERT(elementData());
3207 ASSERT(elementData()->m_styleAttributeIsDirty);
3208 elementData()->m_styleAttributeIsDirty = false;
3209 if (const StylePropertySet* inlineStyle = this->inlineStyle())
3210 const_cast<Element*>(this)->setSynchronizedLazyAttribute(styleAttr, inlineStyle->asText());
3211}
3212
3213CSSStyleDeclaration* Element::style()
3214{
3215 if (!isStyledElement())
3216 return 0;
3217 return ensureMutableInlineStyle()->ensureInlineCSSStyleDeclaration(this);
3218}
3219
3220MutableStylePropertySet* Element::ensureMutableInlineStyle()
3221{
3222 ASSERT(isStyledElement());
3223 RefPtr<StylePropertySet>& inlineStyle = ensureUniqueElementData()->m_inlineStyle;
3224 if (!inlineStyle)
3225 inlineStyle = MutableStylePropertySet::create(strictToCSSParserMode(isHTMLElement() && !document()->inQuirksMode()));
3226 else if (!inlineStyle->isMutable())
3227 inlineStyle = inlineStyle->mutableCopy();
3228 ASSERT(inlineStyle->isMutable());
3229 return static_cast<MutableStylePropertySet*>(inlineStyle.get());
3230}
3231
3232PropertySetCSSStyleDeclaration* Element::inlineStyleCSSOMWrapper()
3233{
3234 if (!inlineStyle() || !inlineStyle()->hasCSSOMWrapper())
3235 return 0;
3236 PropertySetCSSStyleDeclaration* cssomWrapper = ensureMutableInlineStyle()->cssStyleDeclaration();
3237 ASSERT(cssomWrapper && cssomWrapper->parentElement() == this);
3238 return cssomWrapper;
3239}
3240
3241inline void Element::setInlineStyleFromString(const AtomicString& newStyleString)
3242{
3243 ASSERT(isStyledElement());
3244 RefPtr<StylePropertySet>& inlineStyle = elementData()->m_inlineStyle;
3245
3246 // Avoid redundant work if we're using shared attribute data with already parsed inline style.
3247 if (inlineStyle && !elementData()->isUnique())
3248 return;
3249
3250 // We reconstruct the property set instead of mutating if there is no CSSOM wrapper.
3251 // This makes wrapperless property sets immutable and so cacheable.
3252 if (inlineStyle && !inlineStyle->isMutable())
3253 inlineStyle.clear();
3254
3255 if (!inlineStyle) {
3256 inlineStyle = CSSParser::parseInlineStyleDeclaration(newStyleString, this);
3257 } else {
3258 ASSERT(inlineStyle->isMutable());
3259 static_pointer_cast<MutableStylePropertySet>(inlineStyle)->parseDeclaration(newStyleString, document()->elementSheet()->contents());
3260 }
3261}
3262
3263void Element::styleAttributeChanged(const AtomicString& newStyleString, AttributeModificationReason modificationReason)
3264{
3265 ASSERT(isStyledElement());
3266 WTF::OrdinalNumber startLineNumber = WTF::OrdinalNumber::beforeFirst();
3267 if (document() && document()->scriptableDocumentParser() && !document()->isInDocumentWrite())
3268 startLineNumber = document()->scriptableDocumentParser()->lineNumber();
3269
3270 if (newStyleString.isNull()) {
3271 if (PropertySetCSSStyleDeclaration* cssomWrapper = inlineStyleCSSOMWrapper())
3272 cssomWrapper->clearParentElement();
3273 ensureUniqueElementData()->m_inlineStyle.clear();
3274 } else if (modificationReason == ModifiedByCloning || document()->contentSecurityPolicy()->allowInlineStyle(document()->url(), startLineNumber)) {
3275 setInlineStyleFromString(newStyleString);
3276 }
3277
3278 elementData()->m_styleAttributeIsDirty = false;
3279
Ben Murdoche69819b2013-07-17 14:56:49 +01003280 setNeedsStyleRecalc(LocalStyleChange);
Ben Murdoch591b9582013-07-10 11:41:44 +01003281 InspectorInstrumentation::didInvalidateStyleAttr(document(), this);
3282}
3283
3284void Element::inlineStyleChanged()
3285{
3286 ASSERT(isStyledElement());
Ben Murdoche69819b2013-07-17 14:56:49 +01003287 setNeedsStyleRecalc(LocalStyleChange);
Ben Murdoch591b9582013-07-10 11:41:44 +01003288 ASSERT(elementData());
3289 elementData()->m_styleAttributeIsDirty = true;
3290 InspectorInstrumentation::didInvalidateStyleAttr(document(), this);
3291}
3292
3293bool Element::setInlineStyleProperty(CSSPropertyID propertyID, CSSValueID identifier, bool important)
3294{
3295 ASSERT(isStyledElement());
3296 ensureMutableInlineStyle()->setProperty(propertyID, cssValuePool().createIdentifierValue(identifier), important);
3297 inlineStyleChanged();
3298 return true;
3299}
3300
3301bool Element::setInlineStyleProperty(CSSPropertyID propertyID, CSSPropertyID identifier, bool important)
3302{
3303 ASSERT(isStyledElement());
3304 ensureMutableInlineStyle()->setProperty(propertyID, cssValuePool().createIdentifierValue(identifier), important);
3305 inlineStyleChanged();
3306 return true;
3307}
3308
3309bool Element::setInlineStyleProperty(CSSPropertyID propertyID, double value, CSSPrimitiveValue::UnitTypes unit, bool important)
3310{
3311 ASSERT(isStyledElement());
3312 ensureMutableInlineStyle()->setProperty(propertyID, cssValuePool().createValue(value, unit), important);
3313 inlineStyleChanged();
3314 return true;
3315}
3316
3317bool Element::setInlineStyleProperty(CSSPropertyID propertyID, const String& value, bool important)
3318{
3319 ASSERT(isStyledElement());
3320 bool changes = ensureMutableInlineStyle()->setProperty(propertyID, value, important, document()->elementSheet()->contents());
3321 if (changes)
3322 inlineStyleChanged();
3323 return changes;
3324}
3325
3326bool Element::removeInlineStyleProperty(CSSPropertyID propertyID)
3327{
3328 ASSERT(isStyledElement());
3329 if (!inlineStyle())
3330 return false;
3331 bool changes = ensureMutableInlineStyle()->removeProperty(propertyID);
3332 if (changes)
3333 inlineStyleChanged();
3334 return changes;
3335}
3336
3337void Element::removeAllInlineStyleProperties()
3338{
3339 ASSERT(isStyledElement());
3340 if (!inlineStyle() || inlineStyle()->isEmpty())
3341 return;
3342 ensureMutableInlineStyle()->clear();
3343 inlineStyleChanged();
3344}
3345
3346void Element::addSubresourceAttributeURLs(ListHashSet<KURL>& urls) const
3347{
3348 ASSERT(isStyledElement());
3349 if (const StylePropertySet* inlineStyle = elementData() ? elementData()->inlineStyle() : 0)
3350 inlineStyle->addSubresourceStyleURLs(urls, document()->elementSheet()->contents());
3351}
3352
Ben Murdoch83750172013-07-24 10:36:59 +01003353static inline bool attributeNameSort(const pair<StringImpl*, AtomicString>& p1, const pair<StringImpl*, AtomicString>& p2)
Ben Murdoch591b9582013-07-10 11:41:44 +01003354{
3355 // Sort based on the attribute name pointers. It doesn't matter what the order is as long as it is always the same.
3356 return p1.first < p2.first;
3357}
3358
3359void Element::makePresentationAttributeCacheKey(PresentationAttributeCacheKey& result) const
3360{
3361 ASSERT(isStyledElement());
3362 // FIXME: Enable for SVG.
3363 if (namespaceURI() != xhtmlNamespaceURI)
3364 return;
3365 // Interpretation of the size attributes on <input> depends on the type attribute.
3366 if (hasTagName(inputTag))
3367 return;
3368 unsigned size = attributeCount();
3369 for (unsigned i = 0; i < size; ++i) {
3370 const Attribute* attribute = attributeItem(i);
3371 if (!isPresentationAttribute(attribute->name()))
3372 continue;
3373 if (!attribute->namespaceURI().isNull())
3374 return;
3375 // FIXME: Background URL may depend on the base URL and can't be shared. Disallow caching.
3376 if (attribute->name() == backgroundAttr)
3377 return;
3378 result.attributesAndValues.append(std::make_pair(attribute->localName().impl(), attribute->value()));
3379 }
3380 if (result.attributesAndValues.isEmpty())
3381 return;
3382 // Attribute order doesn't matter. Sort for easy equality comparison.
3383 std::sort(result.attributesAndValues.begin(), result.attributesAndValues.end(), attributeNameSort);
3384 // The cache key is non-null when the tagName is set.
3385 result.tagName = localName().impl();
3386}
3387
3388static unsigned computePresentationAttributeCacheHash(const PresentationAttributeCacheKey& key)
3389{
3390 if (!key.tagName)
3391 return 0;
3392 ASSERT(key.attributesAndValues.size());
3393 unsigned attributeHash = StringHasher::hashMemory(key.attributesAndValues.data(), key.attributesAndValues.size() * sizeof(key.attributesAndValues[0]));
3394 return WTF::pairIntHash(key.tagName->existingHash(), attributeHash);
3395}
3396
3397void Element::rebuildPresentationAttributeStyle()
3398{
3399 ASSERT(isStyledElement());
3400 PresentationAttributeCacheKey cacheKey;
3401 makePresentationAttributeCacheKey(cacheKey);
3402
3403 unsigned cacheHash = computePresentationAttributeCacheHash(cacheKey);
3404
3405 PresentationAttributeCache::iterator cacheIterator;
3406 if (cacheHash) {
3407 cacheIterator = presentationAttributeCache().add(cacheHash, nullptr).iterator;
3408 if (cacheIterator->value && cacheIterator->value->key != cacheKey)
3409 cacheHash = 0;
3410 } else {
3411 cacheIterator = presentationAttributeCache().end();
3412 }
3413
3414 RefPtr<StylePropertySet> style;
3415 if (cacheHash && cacheIterator->value) {
3416 style = cacheIterator->value->value;
3417 presentationAttributeCacheCleaner().didHitPresentationAttributeCache();
3418 } else {
3419 style = MutableStylePropertySet::create(isSVGElement() ? SVGAttributeMode : CSSQuirksMode);
3420 unsigned size = attributeCount();
3421 for (unsigned i = 0; i < size; ++i) {
3422 const Attribute* attribute = attributeItem(i);
3423 collectStyleForPresentationAttribute(attribute->name(), attribute->value(), static_cast<MutableStylePropertySet*>(style.get()));
3424 }
3425 }
3426
3427 // ShareableElementData doesn't store presentation attribute style, so make sure we have a UniqueElementData.
3428 UniqueElementData* elementData = ensureUniqueElementData();
3429
3430 elementData->m_presentationAttributeStyleIsDirty = false;
3431 elementData->m_presentationAttributeStyle = style->isEmpty() ? 0 : style;
3432
3433 if (!cacheHash || cacheIterator->value)
3434 return;
3435
3436 OwnPtr<PresentationAttributeCacheEntry> newEntry = adoptPtr(new PresentationAttributeCacheEntry);
3437 newEntry->key = cacheKey;
3438 newEntry->value = style.release();
3439
3440 static const int presentationAttributeCacheMaximumSize = 4096;
3441 if (presentationAttributeCache().size() > presentationAttributeCacheMaximumSize) {
3442 // Start building from scratch if the cache ever gets big.
3443 presentationAttributeCache().clear();
3444 presentationAttributeCache().set(cacheHash, newEntry.release());
3445 } else {
3446 cacheIterator->value = newEntry.release();
3447 }
3448}
3449
3450void Element::addPropertyToPresentationAttributeStyle(MutableStylePropertySet* style, CSSPropertyID propertyID, CSSValueID identifier)
3451{
3452 ASSERT(isStyledElement());
3453 style->setProperty(propertyID, cssValuePool().createIdentifierValue(identifier));
3454}
3455
3456void Element::addPropertyToPresentationAttributeStyle(MutableStylePropertySet* style, CSSPropertyID propertyID, double value, CSSPrimitiveValue::UnitTypes unit)
3457{
3458 ASSERT(isStyledElement());
3459 style->setProperty(propertyID, cssValuePool().createValue(value, unit));
3460}
3461
3462void Element::addPropertyToPresentationAttributeStyle(MutableStylePropertySet* style, CSSPropertyID propertyID, const String& value)
3463{
3464 ASSERT(isStyledElement());
3465 style->setProperty(propertyID, value, false, document()->elementSheet()->contents());
3466}
3467
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01003468void ElementData::deref()
3469{
3470 if (!derefBase())
3471 return;
3472
3473 if (m_isUnique)
3474 delete static_cast<UniqueElementData*>(this);
3475 else
3476 delete static_cast<ShareableElementData*>(this);
3477}
3478
3479ElementData::ElementData()
3480 : m_isUnique(true)
3481 , m_arraySize(0)
3482 , m_presentationAttributeStyleIsDirty(false)
3483 , m_styleAttributeIsDirty(false)
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01003484 , m_animatedSVGAttributesAreDirty(false)
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01003485{
3486}
3487
3488ElementData::ElementData(unsigned arraySize)
3489 : m_isUnique(false)
3490 , m_arraySize(arraySize)
3491 , m_presentationAttributeStyleIsDirty(false)
3492 , m_styleAttributeIsDirty(false)
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01003493 , m_animatedSVGAttributesAreDirty(false)
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01003494{
3495}
3496
3497struct SameSizeAsElementData : public RefCounted<SameSizeAsElementData> {
3498 unsigned bitfield;
3499 void* refPtrs[3];
3500};
3501
3502COMPILE_ASSERT(sizeof(ElementData) == sizeof(SameSizeAsElementData), element_attribute_data_should_stay_small);
3503
3504static size_t sizeForShareableElementDataWithAttributeCount(unsigned count)
3505{
3506 return sizeof(ShareableElementData) + sizeof(Attribute) * count;
3507}
3508
3509PassRefPtr<ShareableElementData> ShareableElementData::createWithAttributes(const Vector<Attribute>& attributes)
3510{
3511 void* slot = WTF::fastMalloc(sizeForShareableElementDataWithAttributeCount(attributes.size()));
3512 return adoptRef(new (slot) ShareableElementData(attributes));
3513}
3514
3515PassRefPtr<UniqueElementData> UniqueElementData::create()
3516{
3517 return adoptRef(new UniqueElementData);
3518}
3519
3520ShareableElementData::ShareableElementData(const Vector<Attribute>& attributes)
3521 : ElementData(attributes.size())
3522{
3523 for (unsigned i = 0; i < m_arraySize; ++i)
3524 new (&m_attributeArray[i]) Attribute(attributes[i]);
3525}
3526
3527ShareableElementData::~ShareableElementData()
3528{
3529 for (unsigned i = 0; i < m_arraySize; ++i)
3530 m_attributeArray[i].~Attribute();
3531}
3532
3533ShareableElementData::ShareableElementData(const UniqueElementData& other)
3534 : ElementData(other, false)
3535{
3536 ASSERT(!other.m_presentationAttributeStyle);
3537
3538 if (other.m_inlineStyle) {
3539 ASSERT(!other.m_inlineStyle->hasCSSOMWrapper());
3540 m_inlineStyle = other.m_inlineStyle->immutableCopyIfNeeded();
3541 }
3542
3543 for (unsigned i = 0; i < m_arraySize; ++i)
3544 new (&m_attributeArray[i]) Attribute(other.m_attributeVector.at(i));
3545}
3546
3547ElementData::ElementData(const ElementData& other, bool isUnique)
3548 : m_isUnique(isUnique)
3549 , m_arraySize(isUnique ? 0 : other.length())
3550 , m_presentationAttributeStyleIsDirty(other.m_presentationAttributeStyleIsDirty)
3551 , m_styleAttributeIsDirty(other.m_styleAttributeIsDirty)
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01003552 , m_animatedSVGAttributesAreDirty(other.m_animatedSVGAttributesAreDirty)
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01003553 , m_classNames(other.m_classNames)
3554 , m_idForStyleResolution(other.m_idForStyleResolution)
3555{
3556 // NOTE: The inline style is copied by the subclass copy constructor since we don't know what to do with it here.
3557}
3558
3559UniqueElementData::UniqueElementData()
3560{
3561}
3562
3563UniqueElementData::UniqueElementData(const UniqueElementData& other)
3564 : ElementData(other, true)
3565 , m_presentationAttributeStyle(other.m_presentationAttributeStyle)
3566 , m_attributeVector(other.m_attributeVector)
3567{
Torne (Richard Coles)93ac45c2013-05-29 14:40:20 +01003568 m_inlineStyle = other.m_inlineStyle ? other.m_inlineStyle->mutableCopy() : 0;
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01003569}
3570
3571UniqueElementData::UniqueElementData(const ShareableElementData& other)
3572 : ElementData(other, true)
3573{
3574 // An ShareableElementData should never have a mutable inline StylePropertySet attached.
3575 ASSERT(!other.m_inlineStyle || !other.m_inlineStyle->isMutable());
3576 m_inlineStyle = other.m_inlineStyle;
3577
3578 m_attributeVector.reserveCapacity(other.length());
3579 for (unsigned i = 0; i < other.length(); ++i)
3580 m_attributeVector.uncheckedAppend(other.m_attributeArray[i]);
3581}
3582
3583PassRefPtr<UniqueElementData> ElementData::makeUniqueCopy() const
3584{
3585 if (isUnique())
3586 return adoptRef(new UniqueElementData(static_cast<const UniqueElementData&>(*this)));
3587 return adoptRef(new UniqueElementData(static_cast<const ShareableElementData&>(*this)));
3588}
3589
3590PassRefPtr<ShareableElementData> UniqueElementData::makeShareableCopy() const
3591{
3592 void* slot = WTF::fastMalloc(sizeForShareableElementDataWithAttributeCount(m_attributeVector.size()));
3593 return adoptRef(new (slot) ShareableElementData(*this));
3594}
3595
3596void UniqueElementData::addAttribute(const QualifiedName& attributeName, const AtomicString& value)
3597{
3598 m_attributeVector.append(Attribute(attributeName, value));
3599}
3600
3601void UniqueElementData::removeAttribute(size_t index)
3602{
3603 ASSERT_WITH_SECURITY_IMPLICATION(index < length());
3604 m_attributeVector.remove(index);
3605}
3606
3607bool ElementData::isEquivalent(const ElementData* other) const
3608{
3609 if (!other)
3610 return isEmpty();
3611
3612 unsigned len = length();
3613 if (len != other->length())
3614 return false;
3615
3616 for (unsigned i = 0; i < len; i++) {
3617 const Attribute* attribute = attributeItem(i);
3618 const Attribute* otherAttr = other->getAttributeItem(attribute->name());
3619 if (!otherAttr || attribute->value() != otherAttr->value())
3620 return false;
3621 }
3622
3623 return true;
3624}
3625
Torne (Richard Coles)e5249552013-05-15 11:35:13 +01003626size_t ElementData::getAttrIndex(Attr* attr) const
3627{
3628 // This relies on the fact that Attr's QualifiedName == the Attribute's name.
3629 for (unsigned i = 0; i < length(); ++i) {
3630 if (attributeItem(i)->name() == attr->qualifiedName())
3631 return i;
3632 }
3633 return notFound;
3634}
3635
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01003636size_t ElementData::getAttributeItemIndexSlowCase(const AtomicString& name, bool shouldIgnoreAttributeCase) const
3637{
3638 // Continue to checking case-insensitively and/or full namespaced names if necessary:
3639 for (unsigned i = 0; i < length(); ++i) {
3640 const Attribute* attribute = attributeItem(i);
3641 if (!attribute->name().hasPrefix()) {
3642 if (shouldIgnoreAttributeCase && equalIgnoringCase(name, attribute->localName()))
3643 return i;
3644 } else {
3645 // FIXME: Would be faster to do this comparison without calling toString, which
3646 // generates a temporary string by concatenation. But this branch is only reached
3647 // if the attribute name has a prefix, which is rare in HTML.
3648 if (equalPossiblyIgnoringCase(name, attribute->name().toString(), shouldIgnoreAttributeCase))
3649 return i;
3650 }
3651 }
3652 return notFound;
3653}
3654
3655Attribute* UniqueElementData::getAttributeItem(const QualifiedName& name)
3656{
3657 for (unsigned i = 0; i < length(); ++i) {
3658 if (m_attributeVector.at(i).name().matches(name))
3659 return &m_attributeVector.at(i);
3660 }
3661 return 0;
3662}
3663
3664Attribute* UniqueElementData::attributeItem(unsigned index)
3665{
3666 ASSERT_WITH_SECURITY_IMPLICATION(index < length());
3667 return &m_attributeVector.at(index);
3668}
3669
3670} // namespace WebCore