2 * Copyright (C) 2011 Google Inc. All Rights Reserved.
3 * Copyright (C) 2012 Apple Inc. All rights reserved.
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
8 * 1. Redistributions of source code must retain the above copyright
9 * notice, this list of conditions and the following disclaimer.
10 * 2. Redistributions in binary form must reproduce the above copyright
11 * notice, this list of conditions and the following disclaimer in the
12 * documentation and/or other materials provided with the distribution.
14 * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY
15 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
16 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
17 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR
18 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
19 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
20 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
21 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
22 * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
23 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
24 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
28 #include "core/dom/TreeScope.h"
30 #include "core/HTMLNames.h"
31 #include "core/css/resolver/ScopedStyleResolver.h"
32 #include "core/dom/ContainerNode.h"
33 #include "core/dom/Document.h"
34 #include "core/dom/Element.h"
35 #include "core/dom/ElementTraversal.h"
36 #include "core/dom/IdTargetObserverRegistry.h"
37 #include "core/dom/NodeRenderStyle.h"
38 #include "core/dom/TreeScopeAdopter.h"
39 #include "core/dom/shadow/ElementShadow.h"
40 #include "core/dom/shadow/ShadowRoot.h"
41 #include "core/editing/DOMSelection.h"
42 #include "core/events/EventPath.h"
43 #include "core/frame/FrameView.h"
44 #include "core/frame/LocalFrame.h"
45 #include "core/html/HTMLAnchorElement.h"
46 #include "core/html/HTMLFrameOwnerElement.h"
47 #include "core/html/HTMLLabelElement.h"
48 #include "core/html/HTMLMapElement.h"
49 #include "core/page/FocusController.h"
50 #include "core/page/Page.h"
51 #include "core/rendering/HitTestResult.h"
52 #include "core/rendering/RenderView.h"
53 #include "wtf/Vector.h"
57 using namespace HTMLNames;
59 TreeScope::TreeScope(ContainerNode& rootNode, Document& document)
60 : m_rootNode(&rootNode)
61 , m_document(&document)
62 , m_parentTreeScope(&document)
66 , m_idTargetObserverRegistry(IdTargetObserverRegistry::create())
68 ASSERT(rootNode != document);
70 m_parentTreeScope->guardRef();
72 m_rootNode->setTreeScope(this);
75 TreeScope::TreeScope(Document& document)
76 : m_rootNode(document)
77 , m_document(&document)
78 , m_parentTreeScope(nullptr)
82 , m_idTargetObserverRegistry(IdTargetObserverRegistry::create())
84 m_rootNode->setTreeScope(this);
87 TreeScope::~TreeScope()
90 ASSERT(!m_guardRefCount);
91 m_rootNode->setTreeScope(0);
94 m_selection->clearTreeScope();
95 m_selection = nullptr;
98 if (m_parentTreeScope)
99 m_parentTreeScope->guardDeref();
103 TreeScope* TreeScope::olderShadowRootOrParentTreeScope() const
105 if (rootNode().isShadowRoot()) {
106 if (ShadowRoot* olderShadowRoot = toShadowRoot(rootNode()).olderShadowRoot())
107 return olderShadowRoot;
109 return parentTreeScope();
112 bool TreeScope::isInclusiveOlderSiblingShadowRootOrAncestorTreeScopeOf(const TreeScope& scope) const
114 for (const TreeScope* current = &scope; current; current = current->olderShadowRootOrParentTreeScope()) {
121 bool TreeScope::rootNodeHasTreeSharedParent() const
123 return rootNode().hasTreeSharedParent();
127 void TreeScope::destroyTreeScopeData()
129 m_elementsById.clear();
130 m_imageMapsByName.clear();
131 m_labelsByForAttribute.clear();
135 void TreeScope::setParentTreeScope(TreeScope& newParentScope)
137 // A document node cannot be re-parented.
138 ASSERT(!rootNode().isDocumentNode());
141 newParentScope.guardRef();
142 if (m_parentTreeScope)
143 m_parentTreeScope->guardDeref();
145 m_parentTreeScope = &newParentScope;
146 setDocument(newParentScope.document());
149 ScopedStyleResolver& TreeScope::ensureScopedStyleResolver()
151 RELEASE_ASSERT(this);
152 if (!m_scopedStyleResolver)
153 m_scopedStyleResolver = ScopedStyleResolver::create(*this);
154 return *m_scopedStyleResolver;
157 void TreeScope::clearScopedStyleResolver()
159 m_scopedStyleResolver.clear();
162 Element* TreeScope::getElementById(const AtomicString& elementId) const
164 if (elementId.isEmpty())
168 return m_elementsById->getElementById(elementId, this);
171 const WillBeHeapVector<RawPtrWillBeMember<Element> >& TreeScope::getAllElementsById(const AtomicString& elementId) const
173 DEFINE_STATIC_LOCAL(OwnPtrWillBePersistent<WillBeHeapVector<RawPtrWillBeMember<Element> > >, emptyVector, (adoptPtrWillBeNoop(new WillBeHeapVector<RawPtrWillBeMember<Element> >())));
174 if (elementId.isEmpty())
178 return m_elementsById->getAllElementsById(elementId, this);
181 void TreeScope::addElementById(const AtomicString& elementId, Element* element)
184 m_elementsById = DocumentOrderedMap::create();
185 m_elementsById->add(elementId, element);
186 m_idTargetObserverRegistry->notifyObservers(elementId);
189 void TreeScope::removeElementById(const AtomicString& elementId, Element* element)
193 m_elementsById->remove(elementId, element);
194 m_idTargetObserverRegistry->notifyObservers(elementId);
197 Node* TreeScope::ancestorInThisScope(Node* node) const
200 if (node->treeScope() == this)
202 if (!node->isInShadowTree())
205 node = node->shadowHost();
211 void TreeScope::addImageMap(HTMLMapElement* imageMap)
213 const AtomicString& name = imageMap->getName();
216 if (!m_imageMapsByName)
217 m_imageMapsByName = DocumentOrderedMap::create();
218 m_imageMapsByName->add(name, imageMap);
221 void TreeScope::removeImageMap(HTMLMapElement* imageMap)
223 if (!m_imageMapsByName)
225 const AtomicString& name = imageMap->getName();
228 m_imageMapsByName->remove(name, imageMap);
231 HTMLMapElement* TreeScope::getImageMap(const String& url) const
235 if (!m_imageMapsByName)
237 size_t hashPos = url.find('#');
238 String name = hashPos == kNotFound ? url : url.substring(hashPos + 1);
239 if (rootNode().document().isHTMLDocument())
240 return toHTMLMapElement(m_imageMapsByName->getElementByLowercasedMapName(AtomicString(name.lower()), this));
241 return toHTMLMapElement(m_imageMapsByName->getElementByMapName(AtomicString(name), this));
244 HitTestResult hitTestInDocument(const Document* document, int x, int y)
246 LocalFrame* frame = document->frame();
249 return HitTestResult();
250 FrameView* frameView = frame->view();
252 return HitTestResult();
254 float scaleFactor = frame->pageZoomFactor();
255 IntPoint point = roundedIntPoint(FloatPoint(x * scaleFactor + frameView->scrollX(), y * scaleFactor + frameView->scrollY()));
257 if (!frameView->visibleContentRect().contains(point))
258 return HitTestResult();
260 HitTestRequest request(HitTestRequest::ReadOnly | HitTestRequest::Active);
261 HitTestResult result(point);
262 document->renderView()->hitTest(request, result);
266 Element* TreeScope::elementFromPoint(int x, int y) const
268 HitTestResult result = hitTestInDocument(&rootNode().document(), x, y);
269 Node* node = result.innerNode();
270 if (!node || node->isDocumentNode())
272 if (node->isPseudoElement() || node->isTextNode())
273 node = node->parentOrShadowHostNode();
274 ASSERT(!node || node->isElementNode() || node->isShadowRoot());
275 node = ancestorInThisScope(node);
276 if (!node || !node->isElementNode())
278 return toElement(node);
281 void TreeScope::addLabel(const AtomicString& forAttributeValue, HTMLLabelElement* element)
283 ASSERT(m_labelsByForAttribute);
284 m_labelsByForAttribute->add(forAttributeValue, element);
287 void TreeScope::removeLabel(const AtomicString& forAttributeValue, HTMLLabelElement* element)
289 ASSERT(m_labelsByForAttribute);
290 m_labelsByForAttribute->remove(forAttributeValue, element);
293 HTMLLabelElement* TreeScope::labelElementForId(const AtomicString& forAttributeValue)
295 if (forAttributeValue.isEmpty())
298 if (!m_labelsByForAttribute) {
299 // Populate the map on first access.
300 m_labelsByForAttribute = DocumentOrderedMap::create();
301 for (HTMLLabelElement* label = Traversal<HTMLLabelElement>::firstWithin(rootNode()); label; label = Traversal<HTMLLabelElement>::next(*label)) {
302 const AtomicString& forValue = label->fastGetAttribute(forAttr);
303 if (!forValue.isEmpty())
304 addLabel(forValue, label);
308 return toHTMLLabelElement(m_labelsByForAttribute->getElementByLabelForAttribute(forAttributeValue, this));
311 DOMSelection* TreeScope::getSelection() const
313 if (!rootNode().document().frame())
317 return m_selection.get();
319 // FIXME: The correct selection in Shadow DOM requires that Position can have a ShadowRoot
321 // See https://bugs.webkit.org/show_bug.cgi?id=82697
322 m_selection = DOMSelection::create(this);
323 return m_selection.get();
326 Element* TreeScope::findAnchor(const String& name)
330 if (Element* element = getElementById(AtomicString(name)))
332 for (HTMLAnchorElement* anchor = Traversal<HTMLAnchorElement>::firstWithin(rootNode()); anchor; anchor = Traversal<HTMLAnchorElement>::next(*anchor)) {
333 if (rootNode().document().inQuirksMode()) {
334 // Quirks mode, case insensitive comparison of names.
335 if (equalIgnoringCase(anchor->name(), name))
338 // Strict mode, names need to match exactly.
339 if (anchor->name() == name)
346 bool TreeScope::applyAuthorStyles() const
348 return rootNode().isDocumentNode();
351 void TreeScope::adoptIfNeeded(Node& node)
354 ASSERT(!node.isDocumentNode());
356 ASSERT_WITH_SECURITY_IMPLICATION(!node.m_deletionHasBegun);
358 TreeScopeAdopter adopter(node, *this);
359 if (adopter.needsScopeChange())
363 static Element* focusedFrameOwnerElement(Frame* focusedFrame, Frame* currentFrame)
365 for (; focusedFrame; focusedFrame = focusedFrame->tree().parent()) {
366 if (focusedFrame->tree().parent() == currentFrame) {
367 // FIXME: This won't work for OOPI.
368 return focusedFrame->deprecatedLocalOwner();
374 Element* TreeScope::adjustedFocusedElement() const
376 Document& document = rootNode().document();
377 Element* element = document.focusedElement();
378 if (!element && document.page())
379 element = focusedFrameOwnerElement(document.page()->focusController().focusedFrame(), document.frame());
383 EventPath eventPath(element);
384 for (size_t i = 0; i < eventPath.size(); ++i) {
385 if (eventPath[i].node() == rootNode()) {
386 // eventPath.at(i).target() is one of the followings:
389 // - Document::focusedElement()
390 // So, it's safe to do toElement().
391 return toElement(eventPath[i].target()->toNode());
397 unsigned short TreeScope::comparePosition(const TreeScope& otherScope) const
399 if (otherScope == this)
400 return Node::DOCUMENT_POSITION_EQUIVALENT;
402 Vector<const TreeScope*, 16> chain1;
403 Vector<const TreeScope*, 16> chain2;
404 const TreeScope* current;
405 for (current = this; current; current = current->parentTreeScope())
406 chain1.append(current);
407 for (current = &otherScope; current; current = current->parentTreeScope())
408 chain2.append(current);
410 unsigned index1 = chain1.size();
411 unsigned index2 = chain2.size();
412 if (chain1[index1 - 1] != chain2[index2 - 1])
413 return Node::DOCUMENT_POSITION_DISCONNECTED | Node::DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC;
415 for (unsigned i = std::min(index1, index2); i; --i) {
416 const TreeScope* child1 = chain1[--index1];
417 const TreeScope* child2 = chain2[--index2];
418 if (child1 != child2) {
419 Node* shadowHost1 = child1->rootNode().parentOrShadowHostNode();
420 Node* shadowHost2 = child2->rootNode().parentOrShadowHostNode();
421 if (shadowHost1 != shadowHost2)
422 return shadowHost1->compareDocumentPosition(shadowHost2, Node::TreatShadowTreesAsDisconnected);
424 for (const ShadowRoot* child = toShadowRoot(child2->rootNode()).olderShadowRoot(); child; child = child->olderShadowRoot())
426 return Node::DOCUMENT_POSITION_FOLLOWING;
428 return Node::DOCUMENT_POSITION_PRECEDING;
432 // There was no difference between the two parent chains, i.e., one was a subset of the other. The shorter
433 // chain is the ancestor.
434 return index1 < index2 ?
435 Node::DOCUMENT_POSITION_FOLLOWING | Node::DOCUMENT_POSITION_CONTAINED_BY :
436 Node::DOCUMENT_POSITION_PRECEDING | Node::DOCUMENT_POSITION_CONTAINS;
439 const TreeScope* TreeScope::commonAncestorTreeScope(const TreeScope& other) const
441 Vector<const TreeScope*, 16> thisChain;
442 for (const TreeScope* tree = this; tree; tree = tree->parentTreeScope())
443 thisChain.append(tree);
445 Vector<const TreeScope*, 16> otherChain;
446 for (const TreeScope* tree = &other; tree; tree = tree->parentTreeScope())
447 otherChain.append(tree);
449 // Keep popping out the last elements of these chains until a mismatched pair is found. If |this| and |other|
450 // belong to different documents, null will be returned.
451 const TreeScope* lastAncestor = 0;
452 while (!thisChain.isEmpty() && !otherChain.isEmpty() && thisChain.last() == otherChain.last()) {
453 lastAncestor = thisChain.last();
454 thisChain.removeLast();
455 otherChain.removeLast();
460 TreeScope* TreeScope::commonAncestorTreeScope(TreeScope& other)
462 return const_cast<TreeScope*>(static_cast<const TreeScope&>(*this).commonAncestorTreeScope(other));
465 static void listTreeScopes(Node* node, Vector<TreeScope*, 5>& treeScopes)
468 treeScopes.append(&node->treeScope());
469 Element* ancestor = node->shadowHost();
476 TreeScope* commonTreeScope(Node* nodeA, Node* nodeB)
478 if (!nodeA || !nodeB)
481 if (nodeA->treeScope() == nodeB->treeScope())
482 return &nodeA->treeScope();
484 Vector<TreeScope*, 5> treeScopesA;
485 listTreeScopes(nodeA, treeScopesA);
487 Vector<TreeScope*, 5> treeScopesB;
488 listTreeScopes(nodeB, treeScopesB);
490 size_t indexA = treeScopesA.size();
491 size_t indexB = treeScopesB.size();
493 for (; indexA > 0 && indexB > 0 && treeScopesA[indexA - 1] == treeScopesB[indexB - 1]; --indexA, --indexB) { }
495 return treeScopesA[indexA] == treeScopesB[indexB] ? treeScopesA[indexA] : 0;
498 #if ENABLE(SECURITY_ASSERT) && !ENABLE(OILPAN)
499 bool TreeScope::deletionHasBegun()
501 return rootNode().m_deletionHasBegun;
504 void TreeScope::beginDeletion()
506 rootNode().m_deletionHasBegun = true;
511 int TreeScope::refCount() const
513 return rootNode().refCount();
517 bool TreeScope::isInclusiveAncestorOf(const TreeScope& scope) const
519 for (const TreeScope* current = &scope; current; current = current->parentTreeScope()) {
526 Element* TreeScope::getElementByAccessKey(const String& key) const
531 Node& root = rootNode();
532 for (Element* element = ElementTraversal::firstWithin(root); element; element = ElementTraversal::next(*element, &root)) {
533 if (equalIgnoringCase(element->fastGetAttribute(accesskeyAttr), key))
535 for (ShadowRoot* shadowRoot = element->youngestShadowRoot(); shadowRoot; shadowRoot = shadowRoot->olderShadowRoot()) {
536 if (Element* shadowResult = shadowRoot->getElementByAccessKey(key))
537 result = shadowResult;
543 void TreeScope::setNeedsStyleRecalcForViewportUnits()
545 for (Element* element = ElementTraversal::firstWithin(rootNode()); element; element = ElementTraversal::nextIncludingPseudo(*element)) {
546 for (ShadowRoot* root = element->youngestShadowRoot(); root; root = root->olderShadowRoot())
547 root->setNeedsStyleRecalcForViewportUnits();
548 RenderStyle* style = element->renderStyle();
549 if (style && style->hasViewportUnits())
550 element->setNeedsStyleRecalc(LocalStyleChange);
554 void TreeScope::trace(Visitor* visitor)
556 visitor->trace(m_rootNode);
557 visitor->trace(m_document);
558 visitor->trace(m_parentTreeScope);
559 visitor->trace(m_idTargetObserverRegistry);
560 visitor->trace(m_selection);
561 visitor->trace(m_elementsById);
562 visitor->trace(m_imageMapsByName);
563 visitor->trace(m_labelsByForAttribute);
564 visitor->trace(m_scopedStyleResolver);