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