/src/3rdparty/webkit/Source/WebCore/dom/Node.cpp

https://bitbucket.org/ultra_iter/qt-vtl · C++ · 2960 lines · 2314 code · 481 blank · 165 comment · 673 complexity · 27dad3ef17dc58223f9107ed1f49c358 MD5 · raw file

  1. /*
  2. * Copyright (C) 1999 Lars Knoll (knoll@kde.org)
  3. * (C) 1999 Antti Koivisto (koivisto@kde.org)
  4. * (C) 2001 Dirk Mueller (mueller@kde.org)
  5. * Copyright (C) 2004, 2005, 2006, 2007, 2008, 2009, 2010 Apple Inc. All rights reserved.
  6. * Copyright (C) 2008 Nokia Corporation and/or its subsidiary(-ies)
  7. * Copyright (C) 2009 Torch Mobile Inc. All rights reserved. (http://www.torchmobile.com/)
  8. *
  9. * This library is free software; you can redistribute it and/or
  10. * modify it under the terms of the GNU Library General Public
  11. * License as published by the Free Software Foundation; either
  12. * version 2 of the License, or (at your option) any later version.
  13. *
  14. * This library is distributed in the hope that it will be useful,
  15. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  16. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  17. * Library General Public License for more details.
  18. *
  19. * You should have received a copy of the GNU Library General Public License
  20. * along with this library; see the file COPYING.LIB. If not, write to
  21. * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
  22. * Boston, MA 02110-1301, USA.
  23. */
  24. #include "config.h"
  25. #include "Node.h"
  26. #include "AXObjectCache.h"
  27. #include "Attr.h"
  28. #include "Attribute.h"
  29. #include "CSSParser.h"
  30. #include "CSSRule.h"
  31. #include "CSSRuleList.h"
  32. #include "CSSSelector.h"
  33. #include "CSSSelectorList.h"
  34. #include "CSSStyleRule.h"
  35. #include "CSSStyleSelector.h"
  36. #include "CSSStyleSheet.h"
  37. #include "ChildNodeList.h"
  38. #include "ClassNodeList.h"
  39. #include "ContextMenuController.h"
  40. #include "DOMImplementation.h"
  41. #include "Document.h"
  42. #include "DocumentType.h"
  43. #include "DynamicNodeList.h"
  44. #include "Element.h"
  45. #include "Event.h"
  46. #include "EventContext.h"
  47. #include "EventDispatcher.h"
  48. #include "EventException.h"
  49. #include "EventHandler.h"
  50. #include "EventListener.h"
  51. #include "EventNames.h"
  52. #include "ExceptionCode.h"
  53. #include "Frame.h"
  54. #include "FrameView.h"
  55. #include "HTMLElement.h"
  56. #include "HTMLNames.h"
  57. #include "InspectorInstrumentation.h"
  58. #include "KeyboardEvent.h"
  59. #include "LabelsNodeList.h"
  60. #include "Logging.h"
  61. #include "MouseEvent.h"
  62. #include "MutationEvent.h"
  63. #include "NameNodeList.h"
  64. #include "NamedNodeMap.h"
  65. #include "NodeRareData.h"
  66. #include "Page.h"
  67. #include "PlatformMouseEvent.h"
  68. #include "PlatformWheelEvent.h"
  69. #include "ProcessingInstruction.h"
  70. #include "ProgressEvent.h"
  71. #include "RegisteredEventListener.h"
  72. #include "RenderBlock.h"
  73. #include "RenderBox.h"
  74. #include "RenderFullScreen.h"
  75. #include "RenderTextControl.h"
  76. #include "RenderView.h"
  77. #include "ScopedEventQueue.h"
  78. #include "SelectorNodeList.h"
  79. #include "ShadowRoot.h"
  80. #include "StaticNodeList.h"
  81. #include "TagNodeList.h"
  82. #include "Text.h"
  83. #include "TextEvent.h"
  84. #include "UIEvent.h"
  85. #include "UIEventWithKeyState.h"
  86. #include "WebKitAnimationEvent.h"
  87. #include "WebKitTransitionEvent.h"
  88. #include "WheelEvent.h"
  89. #include "WindowEventContext.h"
  90. #include "XMLNames.h"
  91. #include "htmlediting.h"
  92. #include <wtf/HashSet.h>
  93. #include <wtf/PassOwnPtr.h>
  94. #include <wtf/RefCountedLeakCounter.h>
  95. #include <wtf/UnusedParam.h>
  96. #include <wtf/text/CString.h>
  97. #include <wtf/text/StringBuilder.h>
  98. #if ENABLE(DOM_STORAGE)
  99. #include "StorageEvent.h"
  100. #endif
  101. #if ENABLE(SVG)
  102. #include "SVGElementInstance.h"
  103. #include "SVGUseElement.h"
  104. #endif
  105. #if ENABLE(XHTMLMP)
  106. #include "HTMLNoScriptElement.h"
  107. #endif
  108. #if USE(JSC)
  109. #include <runtime/JSGlobalData.h>
  110. #endif
  111. #define DUMP_NODE_STATISTICS 0
  112. using namespace std;
  113. namespace WebCore {
  114. using namespace HTMLNames;
  115. bool Node::isSupported(const String& feature, const String& version)
  116. {
  117. return DOMImplementation::hasFeature(feature, version);
  118. }
  119. #if DUMP_NODE_STATISTICS
  120. static HashSet<Node*> liveNodeSet;
  121. #endif
  122. void Node::dumpStatistics()
  123. {
  124. #if DUMP_NODE_STATISTICS
  125. size_t nodesWithRareData = 0;
  126. size_t elementNodes = 0;
  127. size_t attrNodes = 0;
  128. size_t textNodes = 0;
  129. size_t cdataNodes = 0;
  130. size_t commentNodes = 0;
  131. size_t entityReferenceNodes = 0;
  132. size_t entityNodes = 0;
  133. size_t piNodes = 0;
  134. size_t documentNodes = 0;
  135. size_t docTypeNodes = 0;
  136. size_t fragmentNodes = 0;
  137. size_t notationNodes = 0;
  138. size_t xpathNSNodes = 0;
  139. size_t shadowRootNodes = 0;
  140. HashMap<String, size_t> perTagCount;
  141. size_t attributes = 0;
  142. size_t mappedAttributes = 0;
  143. size_t mappedAttributesWithStyleDecl = 0;
  144. size_t attributesWithAttr = 0;
  145. size_t attrMaps = 0;
  146. for (HashSet<Node*>::iterator it = liveNodeSet.begin(); it != liveNodeSet.end(); ++it) {
  147. Node* node = *it;
  148. if (node->hasRareData())
  149. ++nodesWithRareData;
  150. switch (node->nodeType()) {
  151. case ELEMENT_NODE: {
  152. ++elementNodes;
  153. // Tag stats
  154. Element* element = static_cast<Element*>(node);
  155. pair<HashMap<String, size_t>::iterator, bool> result = perTagCount.add(element->tagName(), 1);
  156. if (!result.second)
  157. result.first->second++;
  158. // AttributeMap stats
  159. if (NamedNodeMap* attrMap = element->attributes(true)) {
  160. attributes += attrMap->length();
  161. ++attrMaps;
  162. for (unsigned i = 0; i < attrMap->length(); ++i) {
  163. Attribute* attr = attrMap->attributeItem(i);
  164. if (attr->attr())
  165. ++attributesWithAttr;
  166. if (attr->isMappedAttribute()) {
  167. ++mappedAttributes;
  168. if (attr->style())
  169. ++mappedAttributesWithStyleDecl;
  170. }
  171. }
  172. }
  173. break;
  174. }
  175. case ATTRIBUTE_NODE: {
  176. ++attrNodes;
  177. break;
  178. }
  179. case TEXT_NODE: {
  180. ++textNodes;
  181. break;
  182. }
  183. case CDATA_SECTION_NODE: {
  184. ++cdataNodes;
  185. break;
  186. }
  187. case COMMENT_NODE: {
  188. ++commentNodes;
  189. break;
  190. }
  191. case ENTITY_REFERENCE_NODE: {
  192. ++entityReferenceNodes;
  193. break;
  194. }
  195. case ENTITY_NODE: {
  196. ++entityNodes;
  197. break;
  198. }
  199. case PROCESSING_INSTRUCTION_NODE: {
  200. ++piNodes;
  201. break;
  202. }
  203. case DOCUMENT_NODE: {
  204. ++documentNodes;
  205. break;
  206. }
  207. case DOCUMENT_TYPE_NODE: {
  208. ++docTypeNodes;
  209. break;
  210. }
  211. case DOCUMENT_FRAGMENT_NODE: {
  212. ++fragmentNodes;
  213. break;
  214. }
  215. case NOTATION_NODE: {
  216. ++notationNodes;
  217. break;
  218. }
  219. case XPATH_NAMESPACE_NODE: {
  220. ++xpathNSNodes;
  221. break;
  222. }
  223. case SHADOW_ROOT_NODE: {
  224. ++shadowRootNodes;
  225. break;
  226. }
  227. }
  228. }
  229. printf("Number of Nodes: %d\n\n", liveNodeSet.size());
  230. printf("Number of Nodes with RareData: %zu\n\n", nodesWithRareData);
  231. printf("NodeType distrubution:\n");
  232. printf(" Number of Element nodes: %zu\n", elementNodes);
  233. printf(" Number of Attribute nodes: %zu\n", attrNodes);
  234. printf(" Number of Text nodes: %zu\n", textNodes);
  235. printf(" Number of CDATASection nodes: %zu\n", cdataNodes);
  236. printf(" Number of Comment nodes: %zu\n", commentNodes);
  237. printf(" Number of EntityReference nodes: %zu\n", entityReferenceNodes);
  238. printf(" Number of Entity nodes: %zu\n", entityNodes);
  239. printf(" Number of ProcessingInstruction nodes: %zu\n", piNodes);
  240. printf(" Number of Document nodes: %zu\n", documentNodes);
  241. printf(" Number of DocumentType nodes: %zu\n", docTypeNodes);
  242. printf(" Number of DocumentFragment nodes: %zu\n", fragmentNodes);
  243. printf(" Number of Notation nodes: %zu\n", notationNodes);
  244. printf(" Number of XPathNS nodes: %zu\n", xpathNSNodes);
  245. printf(" Number of ShadowRoot nodes: %zu\n", shadowRootNodes);
  246. printf("Element tag name distibution:\n");
  247. for (HashMap<String, size_t>::iterator it = perTagCount.begin(); it != perTagCount.end(); ++it)
  248. printf(" Number of <%s> tags: %zu\n", it->first.utf8().data(), it->second);
  249. printf("Attribute Maps:\n");
  250. printf(" Number of Attributes (non-Node and Node): %zu [%zu]\n", attributes, sizeof(Attribute));
  251. printf(" Number of Attributes that are mapped: %zu\n", mappedAttributes);
  252. printf(" Number of Attributes with a StyleDeclaration: %zu\n", mappedAttributesWithStyleDecl);
  253. printf(" Number of Attributes with an Attr: %zu\n", attributesWithAttr);
  254. printf(" Number of NamedNodeMaps: %zu [%zu]\n", attrMaps, sizeof(NamedNodeMap));
  255. #endif
  256. }
  257. #ifndef NDEBUG
  258. static WTF::RefCountedLeakCounter nodeCounter("WebCoreNode");
  259. static bool shouldIgnoreLeaks = false;
  260. static HashSet<Node*> ignoreSet;
  261. #endif
  262. void Node::startIgnoringLeaks()
  263. {
  264. #ifndef NDEBUG
  265. shouldIgnoreLeaks = true;
  266. #endif
  267. }
  268. void Node::stopIgnoringLeaks()
  269. {
  270. #ifndef NDEBUG
  271. shouldIgnoreLeaks = false;
  272. #endif
  273. }
  274. Node::StyleChange Node::diff(const RenderStyle* s1, const RenderStyle* s2)
  275. {
  276. // FIXME: The behavior of this function is just totally wrong. It doesn't handle
  277. // explicit inheritance of non-inherited properties and so you end up not re-resolving
  278. // style in cases where you need to.
  279. StyleChange ch = NoInherit;
  280. EDisplay display1 = s1 ? s1->display() : NONE;
  281. bool fl1 = s1 && s1->hasPseudoStyle(FIRST_LETTER);
  282. EDisplay display2 = s2 ? s2->display() : NONE;
  283. bool fl2 = s2 && s2->hasPseudoStyle(FIRST_LETTER);
  284. // We just detach if a renderer acquires or loses a column-span, since spanning elements
  285. // typically won't contain much content.
  286. bool colSpan1 = s1 && s1->columnSpan();
  287. bool colSpan2 = s2 && s2->columnSpan();
  288. if (display1 != display2 || fl1 != fl2 || colSpan1 != colSpan2 || (s1 && s2 && !s1->contentDataEquivalent(s2)))
  289. ch = Detach;
  290. else if (!s1 || !s2)
  291. ch = Inherit;
  292. else if (*s1 == *s2)
  293. ch = NoChange;
  294. else if (s1->inheritedNotEqual(s2))
  295. ch = Inherit;
  296. // For nth-child and other positional rules, treat styles as different if they have
  297. // changed positionally in the DOM. This way subsequent sibling resolutions won't be confused
  298. // by the wrong child index and evaluate to incorrect results.
  299. if (ch == NoChange && s1->childIndex() != s2->childIndex())
  300. ch = NoInherit;
  301. // If the pseudoStyles have changed, we want any StyleChange that is not NoChange
  302. // because setStyle will do the right thing with anything else.
  303. if (ch == NoChange && s1->hasAnyPublicPseudoStyles()) {
  304. for (PseudoId pseudoId = FIRST_PUBLIC_PSEUDOID; ch == NoChange && pseudoId < FIRST_INTERNAL_PSEUDOID; pseudoId = static_cast<PseudoId>(pseudoId + 1)) {
  305. if (s1->hasPseudoStyle(pseudoId)) {
  306. RenderStyle* ps2 = s2->getCachedPseudoStyle(pseudoId);
  307. if (!ps2)
  308. ch = NoInherit;
  309. else {
  310. RenderStyle* ps1 = s1->getCachedPseudoStyle(pseudoId);
  311. ch = ps1 && *ps1 == *ps2 ? NoChange : NoInherit;
  312. }
  313. }
  314. }
  315. }
  316. // When text-combine property has been changed, we need to prepare a separate renderer object.
  317. // When text-combine is on, we use RenderCombineText, otherwise RenderText.
  318. // https://bugs.webkit.org/show_bug.cgi?id=55069
  319. if ((s1 && s2) && (s1->hasTextCombine() != s2->hasTextCombine()))
  320. ch = Detach;
  321. return ch;
  322. }
  323. void Node::trackForDebugging()
  324. {
  325. #ifndef NDEBUG
  326. if (shouldIgnoreLeaks)
  327. ignoreSet.add(this);
  328. else
  329. nodeCounter.increment();
  330. #endif
  331. #if DUMP_NODE_STATISTICS
  332. liveNodeSet.add(this);
  333. #endif
  334. }
  335. Node::~Node()
  336. {
  337. #ifndef NDEBUG
  338. HashSet<Node*>::iterator it = ignoreSet.find(this);
  339. if (it != ignoreSet.end())
  340. ignoreSet.remove(it);
  341. else
  342. nodeCounter.decrement();
  343. #endif
  344. #if DUMP_NODE_STATISTICS
  345. liveNodeSet.remove(this);
  346. #endif
  347. if (!hasRareData())
  348. ASSERT(!NodeRareData::rareDataMap().contains(this));
  349. else {
  350. if (m_document && rareData()->nodeLists())
  351. m_document->removeNodeListCache();
  352. NodeRareData::NodeRareDataMap& dataMap = NodeRareData::rareDataMap();
  353. NodeRareData::NodeRareDataMap::iterator it = dataMap.find(this);
  354. ASSERT(it != dataMap.end());
  355. delete it->second;
  356. dataMap.remove(it);
  357. }
  358. if (renderer())
  359. detach();
  360. if (AXObjectCache::accessibilityEnabled() && m_document && m_document->axObjectCacheExists())
  361. m_document->axObjectCache()->removeNodeForUse(this);
  362. if (m_previous)
  363. m_previous->setNextSibling(0);
  364. if (m_next)
  365. m_next->setPreviousSibling(0);
  366. if (m_document)
  367. m_document->guardDeref();
  368. }
  369. #ifdef NDEBUG
  370. static inline void setWillMoveToNewOwnerDocumentWasCalled(bool)
  371. {
  372. }
  373. static inline void setDidMoveToNewOwnerDocumentWasCalled(bool)
  374. {
  375. }
  376. #else
  377. static bool willMoveToNewOwnerDocumentWasCalled;
  378. static bool didMoveToNewOwnerDocumentWasCalled;
  379. static void setWillMoveToNewOwnerDocumentWasCalled(bool wasCalled)
  380. {
  381. willMoveToNewOwnerDocumentWasCalled = wasCalled;
  382. }
  383. static void setDidMoveToNewOwnerDocumentWasCalled(bool wasCalled)
  384. {
  385. didMoveToNewOwnerDocumentWasCalled = wasCalled;
  386. }
  387. #endif
  388. void Node::setDocument(Document* document)
  389. {
  390. ASSERT(!inDocument() || m_document == document);
  391. if (inDocument() || m_document == document)
  392. return;
  393. document->guardRef();
  394. setWillMoveToNewOwnerDocumentWasCalled(false);
  395. willMoveToNewOwnerDocument();
  396. ASSERT(willMoveToNewOwnerDocumentWasCalled);
  397. if (hasRareData() && rareData()->nodeLists()) {
  398. if (m_document)
  399. m_document->removeNodeListCache();
  400. document->addNodeListCache();
  401. }
  402. if (m_document) {
  403. m_document->moveNodeIteratorsToNewDocument(this, document);
  404. m_document->guardDeref();
  405. }
  406. m_document = document;
  407. setDidMoveToNewOwnerDocumentWasCalled(false);
  408. didMoveToNewOwnerDocument();
  409. ASSERT(didMoveToNewOwnerDocumentWasCalled);
  410. }
  411. TreeScope* Node::treeScope() const
  412. {
  413. // FIXME: Using m_document directly is not good -> see comment with document() in the header file.
  414. if (!hasRareData())
  415. return m_document;
  416. TreeScope* scope = rareData()->treeScope();
  417. return scope ? scope : m_document;
  418. }
  419. void Node::setTreeScopeRecursively(TreeScope* newTreeScope, bool includeRoot)
  420. {
  421. ASSERT(this);
  422. ASSERT(!includeRoot || !isDocumentNode());
  423. ASSERT(newTreeScope);
  424. ASSERT(!m_deletionHasBegun);
  425. TreeScope* currentTreeScope = treeScope();
  426. if (currentTreeScope == newTreeScope)
  427. return;
  428. Document* currentDocument = document();
  429. Document* newDocument = newTreeScope->document();
  430. // If an element is moved from a document and then eventually back again the collection cache for
  431. // that element may contain stale data as changes made to it will have updated the DOMTreeVersion
  432. // of the document it was moved to. By increasing the DOMTreeVersion of the donating document here
  433. // we ensure that the collection cache will be invalidated as needed when the element is moved back.
  434. if (currentDocument && currentDocument != newDocument)
  435. currentDocument->incDOMTreeVersion();
  436. for (Node* node = includeRoot ? this : traverseNextNode(this); node; node = node->traverseNextNode(this)) {
  437. if (newTreeScope == newDocument) {
  438. if (node->hasRareData())
  439. node->rareData()->setTreeScope(0);
  440. // Setting the new document tree scope will be handled implicitly
  441. // by setDocument() below.
  442. } else
  443. node->ensureRareData()->setTreeScope(newTreeScope);
  444. node->setDocument(newDocument);
  445. if (!node->isElementNode())
  446. continue;
  447. if (ShadowRoot* shadowRoot = toElement(node)->shadowRoot()) {
  448. shadowRoot->setParentTreeScope(newTreeScope);
  449. if (currentDocument != newDocument)
  450. shadowRoot->setDocumentRecursively(newDocument);
  451. }
  452. }
  453. }
  454. NodeRareData* Node::rareData() const
  455. {
  456. ASSERT(hasRareData());
  457. return NodeRareData::rareDataFromMap(this);
  458. }
  459. NodeRareData* Node::ensureRareData()
  460. {
  461. if (hasRareData())
  462. return rareData();
  463. ASSERT(!NodeRareData::rareDataMap().contains(this));
  464. NodeRareData* data = createRareData();
  465. NodeRareData::rareDataMap().set(this, data);
  466. setFlag(HasRareDataFlag);
  467. return data;
  468. }
  469. NodeRareData* Node::createRareData()
  470. {
  471. return new NodeRareData;
  472. }
  473. Element* Node::shadowHost() const
  474. {
  475. return toElement(getFlag(IsShadowRootFlag) ? parent() : 0);
  476. }
  477. void Node::setShadowHost(Element* host)
  478. {
  479. ASSERT(!parentNode() && !isSVGShadowRoot());
  480. if (host)
  481. setFlag(IsShadowRootFlag);
  482. else
  483. clearFlag(IsShadowRootFlag);
  484. setParent(host);
  485. }
  486. InputElement* Node::toInputElement()
  487. {
  488. // If one of the below ASSERTs trigger, you are calling this function
  489. // directly or indirectly from a constructor or destructor of this object.
  490. // Don't do this!
  491. ASSERT(!(isHTMLElement() && hasTagName(inputTag)));
  492. return 0;
  493. }
  494. short Node::tabIndex() const
  495. {
  496. return hasRareData() ? rareData()->tabIndex() : 0;
  497. }
  498. void Node::setTabIndexExplicitly(short i)
  499. {
  500. ensureRareData()->setTabIndexExplicitly(i);
  501. }
  502. void Node::clearTabIndexExplicitly()
  503. {
  504. ensureRareData()->clearTabIndexExplicitly();
  505. }
  506. String Node::nodeValue() const
  507. {
  508. return String();
  509. }
  510. void Node::setNodeValue(const String& /*nodeValue*/, ExceptionCode& ec)
  511. {
  512. // NO_MODIFICATION_ALLOWED_ERR: Raised when the node is readonly
  513. if (isReadOnlyNode()) {
  514. ec = NO_MODIFICATION_ALLOWED_ERR;
  515. return;
  516. }
  517. // By default, setting nodeValue has no effect.
  518. }
  519. PassRefPtr<NodeList> Node::childNodes()
  520. {
  521. NodeRareData* data = ensureRareData();
  522. if (!data->nodeLists()) {
  523. data->setNodeLists(NodeListsNodeData::create());
  524. if (document())
  525. document()->addNodeListCache();
  526. }
  527. return ChildNodeList::create(this, data->nodeLists()->m_childNodeListCaches.get());
  528. }
  529. Node *Node::lastDescendant() const
  530. {
  531. Node *n = const_cast<Node *>(this);
  532. while (n && n->lastChild())
  533. n = n->lastChild();
  534. return n;
  535. }
  536. Node* Node::firstDescendant() const
  537. {
  538. Node *n = const_cast<Node *>(this);
  539. while (n && n->firstChild())
  540. n = n->firstChild();
  541. return n;
  542. }
  543. bool Node::insertBefore(PassRefPtr<Node> newChild, Node* refChild, ExceptionCode& ec, bool shouldLazyAttach)
  544. {
  545. if (!isContainerNode()) {
  546. ec = HIERARCHY_REQUEST_ERR;
  547. return false;
  548. }
  549. return toContainerNode(this)->insertBefore(newChild, refChild, ec, shouldLazyAttach);
  550. }
  551. bool Node::replaceChild(PassRefPtr<Node> newChild, Node* oldChild, ExceptionCode& ec, bool shouldLazyAttach)
  552. {
  553. if (!isContainerNode()) {
  554. ec = HIERARCHY_REQUEST_ERR;
  555. return false;
  556. }
  557. return toContainerNode(this)->replaceChild(newChild, oldChild, ec, shouldLazyAttach);
  558. }
  559. bool Node::removeChild(Node* oldChild, ExceptionCode& ec)
  560. {
  561. if (!isContainerNode()) {
  562. ec = NOT_FOUND_ERR;
  563. return false;
  564. }
  565. return toContainerNode(this)->removeChild(oldChild, ec);
  566. }
  567. bool Node::appendChild(PassRefPtr<Node> newChild, ExceptionCode& ec, bool shouldLazyAttach)
  568. {
  569. if (!isContainerNode()) {
  570. ec = HIERARCHY_REQUEST_ERR;
  571. return false;
  572. }
  573. return toContainerNode(this)->appendChild(newChild, ec, shouldLazyAttach);
  574. }
  575. void Node::remove(ExceptionCode& ec)
  576. {
  577. if (ContainerNode* parent = parentNode())
  578. parent->removeChild(this, ec);
  579. else
  580. ec = HIERARCHY_REQUEST_ERR;
  581. }
  582. void Node::normalize()
  583. {
  584. // Go through the subtree beneath us, normalizing all nodes. This means that
  585. // any two adjacent text nodes are merged and any empty text nodes are removed.
  586. RefPtr<Node> node = this;
  587. while (Node* firstChild = node->firstChild())
  588. node = firstChild;
  589. while (node) {
  590. NodeType type = node->nodeType();
  591. if (type == ELEMENT_NODE)
  592. static_cast<Element*>(node.get())->normalizeAttributes();
  593. if (node == this)
  594. break;
  595. if (type != TEXT_NODE) {
  596. node = node->traverseNextNodePostOrder();
  597. continue;
  598. }
  599. Text* text = static_cast<Text*>(node.get());
  600. // Remove empty text nodes.
  601. if (!text->length()) {
  602. // Care must be taken to get the next node before removing the current node.
  603. node = node->traverseNextNodePostOrder();
  604. ExceptionCode ec;
  605. text->remove(ec);
  606. continue;
  607. }
  608. // Merge text nodes.
  609. while (Node* nextSibling = node->nextSibling()) {
  610. if (nextSibling->nodeType() != TEXT_NODE)
  611. break;
  612. RefPtr<Text> nextText = static_cast<Text*>(nextSibling);
  613. // Remove empty text nodes.
  614. if (!nextText->length()) {
  615. ExceptionCode ec;
  616. nextText->remove(ec);
  617. continue;
  618. }
  619. // Both non-empty text nodes. Merge them.
  620. unsigned offset = text->length();
  621. ExceptionCode ec;
  622. text->appendData(nextText->data(), ec);
  623. document()->textNodesMerged(nextText.get(), offset);
  624. nextText->remove(ec);
  625. }
  626. node = node->traverseNextNodePostOrder();
  627. }
  628. }
  629. const AtomicString& Node::virtualPrefix() const
  630. {
  631. // For nodes other than elements and attributes, the prefix is always null
  632. return nullAtom;
  633. }
  634. void Node::setPrefix(const AtomicString& /*prefix*/, ExceptionCode& ec)
  635. {
  636. // The spec says that for nodes other than elements and attributes, prefix is always null.
  637. // It does not say what to do when the user tries to set the prefix on another type of
  638. // node, however Mozilla throws a NAMESPACE_ERR exception.
  639. ec = NAMESPACE_ERR;
  640. }
  641. const AtomicString& Node::virtualLocalName() const
  642. {
  643. return nullAtom;
  644. }
  645. const AtomicString& Node::virtualNamespaceURI() const
  646. {
  647. return nullAtom;
  648. }
  649. void Node::deprecatedParserAddChild(PassRefPtr<Node>)
  650. {
  651. }
  652. bool Node::isContentEditable() const
  653. {
  654. document()->updateLayoutIgnorePendingStylesheets();
  655. return rendererIsEditable(Editable);
  656. }
  657. bool Node::rendererIsEditable(EditableLevel editableLevel) const
  658. {
  659. if (document()->frame() && document()->frame()->page() && document()->frame()->page()->isEditable())
  660. return true;
  661. // Ideally we'd call ASSERT(!needsStyleRecalc()) here, but
  662. // ContainerNode::setFocus() calls setNeedsStyleRecalc(), so the assertion
  663. // would fire in the middle of Document::setFocusedNode().
  664. for (const Node* node = this; node; node = node->parentNode()) {
  665. if ((node->isHTMLElement() || node->isDocumentNode()) && node->renderer()) {
  666. switch (node->renderer()->style()->userModify()) {
  667. case READ_ONLY:
  668. return false;
  669. case READ_WRITE:
  670. return true;
  671. case READ_WRITE_PLAINTEXT_ONLY:
  672. return editableLevel != RichlyEditable;
  673. }
  674. ASSERT_NOT_REACHED();
  675. return false;
  676. }
  677. }
  678. return false;
  679. }
  680. bool Node::shouldUseInputMethod() const
  681. {
  682. return isContentEditable();
  683. }
  684. RenderBox* Node::renderBox() const
  685. {
  686. return m_renderer && m_renderer->isBox() ? toRenderBox(m_renderer) : 0;
  687. }
  688. RenderBoxModelObject* Node::renderBoxModelObject() const
  689. {
  690. return m_renderer && m_renderer->isBoxModelObject() ? toRenderBoxModelObject(m_renderer) : 0;
  691. }
  692. IntRect Node::getRect() const
  693. {
  694. if (renderer())
  695. return renderer()->absoluteBoundingBoxRect(true);
  696. return IntRect();
  697. }
  698. IntRect Node::renderRect(bool* isReplaced)
  699. {
  700. RenderObject* hitRenderer = this->renderer();
  701. ASSERT(hitRenderer);
  702. RenderObject* renderer = hitRenderer;
  703. while (renderer && !renderer->isBody() && !renderer->isRoot()) {
  704. if (renderer->isRenderBlock() || renderer->isInlineBlockOrInlineTable() || renderer->isReplaced()) {
  705. *isReplaced = renderer->isReplaced();
  706. return renderer->absoluteBoundingBoxRect(true);
  707. }
  708. renderer = renderer->parent();
  709. }
  710. return IntRect();
  711. }
  712. bool Node::hasNonEmptyBoundingBox() const
  713. {
  714. // Before calling absoluteRects, check for the common case where the renderer
  715. // is non-empty, since this is a faster check and almost always returns true.
  716. RenderBoxModelObject* box = renderBoxModelObject();
  717. if (!box)
  718. return false;
  719. if (!box->borderBoundingBox().isEmpty())
  720. return true;
  721. Vector<IntRect> rects;
  722. FloatPoint absPos = renderer()->localToAbsolute();
  723. renderer()->absoluteRects(rects, absPos.x(), absPos.y());
  724. size_t n = rects.size();
  725. for (size_t i = 0; i < n; ++i)
  726. if (!rects[i].isEmpty())
  727. return true;
  728. return false;
  729. }
  730. inline static ShadowRoot* shadowRoot(Node* node)
  731. {
  732. return node->isElementNode() ? toElement(node)->shadowRoot() : 0;
  733. }
  734. void Node::setDocumentRecursively(Document* newDocument)
  735. {
  736. ASSERT(document() != newDocument);
  737. for (Node* node = this; node; node = node->traverseNextNode(this)) {
  738. node->setDocument(newDocument);
  739. if (!node->isElementNode())
  740. continue;
  741. if (ShadowRoot* shadow = shadowRoot(node))
  742. shadow->setDocumentRecursively(newDocument);
  743. }
  744. }
  745. inline void Node::setStyleChange(StyleChangeType changeType)
  746. {
  747. m_nodeFlags = (m_nodeFlags & ~StyleChangeMask) | changeType;
  748. }
  749. inline void Node::markAncestorsWithChildNeedsStyleRecalc()
  750. {
  751. for (ContainerNode* p = parentOrHostNode(); p && !p->childNeedsStyleRecalc(); p = p->parentOrHostNode())
  752. p->setChildNeedsStyleRecalc();
  753. if (document()->childNeedsStyleRecalc())
  754. document()->scheduleStyleRecalc();
  755. }
  756. void Node::refEventTarget()
  757. {
  758. ref();
  759. }
  760. void Node::derefEventTarget()
  761. {
  762. deref();
  763. }
  764. void Node::setNeedsStyleRecalc(StyleChangeType changeType)
  765. {
  766. ASSERT(changeType != NoStyleChange);
  767. if (!attached()) // changed compared to what?
  768. return;
  769. StyleChangeType existingChangeType = styleChangeType();
  770. if (changeType > existingChangeType)
  771. setStyleChange(changeType);
  772. if (existingChangeType == NoStyleChange)
  773. markAncestorsWithChildNeedsStyleRecalc();
  774. }
  775. void Node::lazyAttach(ShouldSetAttached shouldSetAttached)
  776. {
  777. for (Node* n = this; n; n = n->traverseNextNode(this)) {
  778. if (n->firstChild())
  779. n->setChildNeedsStyleRecalc();
  780. n->setStyleChange(FullStyleChange);
  781. if (shouldSetAttached == SetAttached)
  782. n->setAttached();
  783. }
  784. markAncestorsWithChildNeedsStyleRecalc();
  785. }
  786. void Node::setFocus(bool b)
  787. {
  788. if (b || hasRareData())
  789. ensureRareData()->setFocused(b);
  790. }
  791. bool Node::rareDataFocused() const
  792. {
  793. ASSERT(hasRareData());
  794. return rareData()->isFocused();
  795. }
  796. bool Node::supportsFocus() const
  797. {
  798. return hasRareData() && rareData()->tabIndexSetExplicitly();
  799. }
  800. bool Node::isFocusable() const
  801. {
  802. if (!inDocument() || !supportsFocus())
  803. return false;
  804. if (renderer())
  805. ASSERT(!renderer()->needsLayout());
  806. else
  807. // If the node is in a display:none tree it might say it needs style recalc but
  808. // the whole document is actually up to date.
  809. ASSERT(!document()->childNeedsStyleRecalc());
  810. // FIXME: Even if we are not visible, we might have a child that is visible.
  811. // Hyatt wants to fix that some day with a "has visible content" flag or the like.
  812. if (!renderer() || renderer()->style()->visibility() != VISIBLE)
  813. return false;
  814. return true;
  815. }
  816. bool Node::isKeyboardFocusable(KeyboardEvent*) const
  817. {
  818. return isFocusable() && tabIndex() >= 0;
  819. }
  820. bool Node::isMouseFocusable() const
  821. {
  822. return isFocusable();
  823. }
  824. unsigned Node::nodeIndex() const
  825. {
  826. Node *_tempNode = previousSibling();
  827. unsigned count=0;
  828. for ( count=0; _tempNode; count++ )
  829. _tempNode = _tempNode->previousSibling();
  830. return count;
  831. }
  832. void Node::registerDynamicNodeList(DynamicNodeList* list)
  833. {
  834. NodeRareData* data = ensureRareData();
  835. if (!data->nodeLists()) {
  836. data->setNodeLists(NodeListsNodeData::create());
  837. document()->addNodeListCache();
  838. } else if (!m_document || !m_document->hasNodeListCaches()) {
  839. // We haven't been receiving notifications while there were no registered lists, so the cache is invalid now.
  840. data->nodeLists()->invalidateCaches();
  841. }
  842. if (list->hasOwnCaches())
  843. data->nodeLists()->m_listsWithCaches.add(list);
  844. }
  845. void Node::unregisterDynamicNodeList(DynamicNodeList* list)
  846. {
  847. ASSERT(rareData());
  848. ASSERT(rareData()->nodeLists());
  849. if (list->hasOwnCaches()) {
  850. NodeRareData* data = rareData();
  851. data->nodeLists()->m_listsWithCaches.remove(list);
  852. if (data->nodeLists()->isEmpty()) {
  853. data->clearNodeLists();
  854. if (document())
  855. document()->removeNodeListCache();
  856. }
  857. }
  858. }
  859. void Node::notifyLocalNodeListsAttributeChanged()
  860. {
  861. if (!hasRareData())
  862. return;
  863. NodeRareData* data = rareData();
  864. if (!data->nodeLists())
  865. return;
  866. if (!isAttributeNode())
  867. data->nodeLists()->invalidateCachesThatDependOnAttributes();
  868. else
  869. data->nodeLists()->invalidateCaches();
  870. if (data->nodeLists()->isEmpty()) {
  871. data->clearNodeLists();
  872. document()->removeNodeListCache();
  873. }
  874. }
  875. void Node::notifyNodeListsAttributeChanged()
  876. {
  877. for (Node *n = this; n; n = n->parentNode())
  878. n->notifyLocalNodeListsAttributeChanged();
  879. }
  880. void Node::notifyLocalNodeListsChildrenChanged()
  881. {
  882. if (!hasRareData())
  883. return;
  884. NodeRareData* data = rareData();
  885. if (!data->nodeLists())
  886. return;
  887. data->nodeLists()->invalidateCaches();
  888. NodeListsNodeData::NodeListSet::iterator end = data->nodeLists()->m_listsWithCaches.end();
  889. for (NodeListsNodeData::NodeListSet::iterator i = data->nodeLists()->m_listsWithCaches.begin(); i != end; ++i)
  890. (*i)->invalidateCache();
  891. if (data->nodeLists()->isEmpty()) {
  892. data->clearNodeLists();
  893. document()->removeNodeListCache();
  894. }
  895. }
  896. void Node::notifyNodeListsChildrenChanged()
  897. {
  898. for (Node* n = this; n; n = n->parentNode())
  899. n->notifyLocalNodeListsChildrenChanged();
  900. }
  901. void Node::notifyLocalNodeListsLabelChanged()
  902. {
  903. if (!hasRareData())
  904. return;
  905. NodeRareData* data = rareData();
  906. if (!data->nodeLists())
  907. return;
  908. if (data->nodeLists()->m_labelsNodeListCache)
  909. data->nodeLists()->m_labelsNodeListCache->invalidateCache();
  910. }
  911. void Node::removeCachedClassNodeList(ClassNodeList* list, const String& className)
  912. {
  913. ASSERT(rareData());
  914. ASSERT(rareData()->nodeLists());
  915. ASSERT_UNUSED(list, list->hasOwnCaches());
  916. NodeListsNodeData* data = rareData()->nodeLists();
  917. ASSERT_UNUSED(list, list == data->m_classNodeListCache.get(className));
  918. data->m_classNodeListCache.remove(className);
  919. }
  920. void Node::removeCachedNameNodeList(NameNodeList* list, const String& nodeName)
  921. {
  922. ASSERT(rareData());
  923. ASSERT(rareData()->nodeLists());
  924. ASSERT_UNUSED(list, list->hasOwnCaches());
  925. NodeListsNodeData* data = rareData()->nodeLists();
  926. ASSERT_UNUSED(list, list == data->m_nameNodeListCache.get(nodeName));
  927. data->m_nameNodeListCache.remove(nodeName);
  928. }
  929. void Node::removeCachedTagNodeList(TagNodeList* list, const AtomicString& name)
  930. {
  931. ASSERT(rareData());
  932. ASSERT(rareData()->nodeLists());
  933. ASSERT_UNUSED(list, list->hasOwnCaches());
  934. NodeListsNodeData* data = rareData()->nodeLists();
  935. ASSERT_UNUSED(list, list == data->m_tagNodeListCache.get(name.impl()));
  936. data->m_tagNodeListCache.remove(name.impl());
  937. }
  938. void Node::removeCachedTagNodeList(TagNodeList* list, const QualifiedName& name)
  939. {
  940. ASSERT(rareData());
  941. ASSERT(rareData()->nodeLists());
  942. ASSERT_UNUSED(list, list->hasOwnCaches());
  943. NodeListsNodeData* data = rareData()->nodeLists();
  944. ASSERT_UNUSED(list, list == data->m_tagNodeListCacheNS.get(name.impl()));
  945. data->m_tagNodeListCacheNS.remove(name.impl());
  946. }
  947. void Node::removeCachedLabelsNodeList(DynamicNodeList* list)
  948. {
  949. ASSERT(rareData());
  950. ASSERT(rareData()->nodeLists());
  951. ASSERT_UNUSED(list, list->hasOwnCaches());
  952. NodeListsNodeData* data = rareData()->nodeLists();
  953. data->m_labelsNodeListCache = 0;
  954. }
  955. Node* Node::traverseNextNode(const Node* stayWithin) const
  956. {
  957. if (firstChild())
  958. return firstChild();
  959. if (this == stayWithin)
  960. return 0;
  961. if (nextSibling())
  962. return nextSibling();
  963. const Node *n = this;
  964. while (n && !n->nextSibling() && (!stayWithin || n->parentNode() != stayWithin))
  965. n = n->parentNode();
  966. if (n)
  967. return n->nextSibling();
  968. return 0;
  969. }
  970. Node* Node::traverseNextSibling(const Node* stayWithin) const
  971. {
  972. if (this == stayWithin)
  973. return 0;
  974. if (nextSibling())
  975. return nextSibling();
  976. const Node *n = this;
  977. while (n && !n->nextSibling() && (!stayWithin || n->parentNode() != stayWithin))
  978. n = n->parentNode();
  979. if (n)
  980. return n->nextSibling();
  981. return 0;
  982. }
  983. Node* Node::traverseNextNodePostOrder() const
  984. {
  985. Node* next = nextSibling();
  986. if (!next)
  987. return parentNode();
  988. while (Node* firstChild = next->firstChild())
  989. next = firstChild;
  990. return next;
  991. }
  992. Node* Node::traversePreviousNode(const Node* stayWithin) const
  993. {
  994. if (this == stayWithin)
  995. return 0;
  996. if (previousSibling()) {
  997. Node *n = previousSibling();
  998. while (n->lastChild())
  999. n = n->lastChild();
  1000. return n;
  1001. }
  1002. return parentNode();
  1003. }
  1004. Node* Node::traversePreviousNodePostOrder(const Node* stayWithin) const
  1005. {
  1006. if (lastChild())
  1007. return lastChild();
  1008. if (this == stayWithin)
  1009. return 0;
  1010. if (previousSibling())
  1011. return previousSibling();
  1012. const Node *n = this;
  1013. while (n && !n->previousSibling() && (!stayWithin || n->parentNode() != stayWithin))
  1014. n = n->parentNode();
  1015. if (n)
  1016. return n->previousSibling();
  1017. return 0;
  1018. }
  1019. Node* Node::traversePreviousSiblingPostOrder(const Node* stayWithin) const
  1020. {
  1021. if (this == stayWithin)
  1022. return 0;
  1023. if (previousSibling())
  1024. return previousSibling();
  1025. const Node *n = this;
  1026. while (n && !n->previousSibling() && (!stayWithin || n->parentNode() != stayWithin))
  1027. n = n->parentNode();
  1028. if (n)
  1029. return n->previousSibling();
  1030. return 0;
  1031. }
  1032. void Node::checkSetPrefix(const AtomicString& prefix, ExceptionCode& ec)
  1033. {
  1034. // Perform error checking as required by spec for setting Node.prefix. Used by
  1035. // Element::setPrefix() and Attr::setPrefix()
  1036. // FIXME: Implement support for INVALID_CHARACTER_ERR: Raised if the specified prefix contains an illegal character.
  1037. if (isReadOnlyNode()) {
  1038. ec = NO_MODIFICATION_ALLOWED_ERR;
  1039. return;
  1040. }
  1041. // FIXME: Raise NAMESPACE_ERR if prefix is malformed per the Namespaces in XML specification.
  1042. const AtomicString& nodeNamespaceURI = namespaceURI();
  1043. if ((nodeNamespaceURI.isEmpty() && !prefix.isEmpty())
  1044. || (prefix == xmlAtom && nodeNamespaceURI != XMLNames::xmlNamespaceURI)) {
  1045. ec = NAMESPACE_ERR;
  1046. return;
  1047. }
  1048. // Attribute-specific checks are in Attr::setPrefix().
  1049. }
  1050. static bool isChildTypeAllowed(Node* newParent, Node* child)
  1051. {
  1052. if (child->nodeType() != Node::DOCUMENT_FRAGMENT_NODE) {
  1053. if (!newParent->childTypeAllowed(child->nodeType()))
  1054. return false;
  1055. return true;
  1056. }
  1057. for (Node *n = child->firstChild(); n; n = n->nextSibling()) {
  1058. if (!newParent->childTypeAllowed(n->nodeType()))
  1059. return false;
  1060. }
  1061. return true;
  1062. }
  1063. bool Node::canReplaceChild(Node* newChild, Node*)
  1064. {
  1065. return isChildTypeAllowed(this, newChild);
  1066. }
  1067. static void checkAcceptChild(Node* newParent, Node* newChild, ExceptionCode& ec)
  1068. {
  1069. // Not mentioned in spec: throw NOT_FOUND_ERR if newChild is null
  1070. if (!newChild) {
  1071. ec = NOT_FOUND_ERR;
  1072. return;
  1073. }
  1074. if (newParent->isReadOnlyNode()) {
  1075. ec = NO_MODIFICATION_ALLOWED_ERR;
  1076. return;
  1077. }
  1078. if (newChild->inDocument() && newChild->nodeType() == Node::DOCUMENT_TYPE_NODE) {
  1079. ec = HIERARCHY_REQUEST_ERR;
  1080. return;
  1081. }
  1082. // HIERARCHY_REQUEST_ERR: Raised if this node is of a type that does not allow children of the type of the
  1083. // newChild node, or if the node to append is one of this node's ancestors.
  1084. if (newChild == newParent || newParent->isDescendantOf(newChild)) {
  1085. ec = HIERARCHY_REQUEST_ERR;
  1086. return;
  1087. }
  1088. }
  1089. void Node::checkReplaceChild(Node* newChild, Node* oldChild, ExceptionCode& ec)
  1090. {
  1091. if (!oldChild) {
  1092. ec = NOT_FOUND_ERR;
  1093. return;
  1094. }
  1095. checkAcceptChild(this, newChild, ec);
  1096. if (ec)
  1097. return;
  1098. if (!canReplaceChild(newChild, oldChild)) {
  1099. ec = HIERARCHY_REQUEST_ERR;
  1100. return;
  1101. }
  1102. }
  1103. void Node::checkAddChild(Node *newChild, ExceptionCode& ec)
  1104. {
  1105. checkAcceptChild(this, newChild, ec);
  1106. if (ec)
  1107. return;
  1108. if (!isChildTypeAllowed(this, newChild)) {
  1109. ec = HIERARCHY_REQUEST_ERR;
  1110. return;
  1111. }
  1112. }
  1113. bool Node::isDescendantOf(const Node *other) const
  1114. {
  1115. // Return true if other is an ancestor of this, otherwise false
  1116. if (!other)
  1117. return false;
  1118. for (const ContainerNode* n = parentNode(); n; n = n->parentNode()) {
  1119. if (n == other)
  1120. return true;
  1121. }
  1122. return false;
  1123. }
  1124. bool Node::contains(const Node* node) const
  1125. {
  1126. if (!node)
  1127. return false;
  1128. return this == node || node->isDescendantOf(this);
  1129. }
  1130. bool Node::containsIncludingShadowDOM(Node* node)
  1131. {
  1132. if (!node)
  1133. return false;
  1134. for (Node* n = node; n; n = n->parentOrHostNode()) {
  1135. if (n == this)
  1136. return true;
  1137. }
  1138. return false;
  1139. }
  1140. void Node::attach()
  1141. {
  1142. ASSERT(!attached());
  1143. ASSERT(!renderer() || (renderer()->style() && renderer()->parent()));
  1144. // FIXME: This is O(N^2) for the innerHTML case, where all children are replaced at once (and not attached).
  1145. // If this node got a renderer it may be the previousRenderer() of sibling text nodes and thus affect the
  1146. // result of Text::rendererIsNeeded() for those nodes.
  1147. if (renderer()) {
  1148. for (Node* next = nextSibling(); next; next = next->nextSibling()) {
  1149. if (next->renderer())
  1150. break;
  1151. if (!next->attached())
  1152. break; // Assume this means none of the following siblings are attached.
  1153. if (next->isTextNode())
  1154. next->createRendererIfNeeded();
  1155. }
  1156. }
  1157. setAttached();
  1158. clearNeedsStyleRecalc();
  1159. }
  1160. void Node::willRemove()
  1161. {
  1162. }
  1163. void Node::detach()
  1164. {
  1165. setFlag(InDetachFlag);
  1166. if (renderer())
  1167. renderer()->destroy();
  1168. setRenderer(0);
  1169. Document* doc = document();
  1170. if (hovered())
  1171. doc->hoveredNodeDetached(this);
  1172. if (inActiveChain())
  1173. doc->activeChainNodeDetached(this);
  1174. clearFlag(IsActiveFlag);
  1175. clearFlag(IsHoveredFlag);
  1176. clearFlag(InActiveChainFlag);
  1177. clearFlag(IsAttachedFlag);
  1178. clearFlag(InDetachFlag);
  1179. }
  1180. RenderObject* Node::previousRenderer()
  1181. {
  1182. // FIXME: We should have the same O(N^2) avoidance as nextRenderer does
  1183. // however, when I tried adding it, several tests failed.
  1184. for (Node* n = previousSibling(); n; n = n->previousSibling()) {
  1185. if (n->renderer())
  1186. return n->renderer();
  1187. }
  1188. return 0;
  1189. }
  1190. RenderObject* Node::nextRenderer()
  1191. {
  1192. // Avoid an O(n^2) problem with this function by not checking for
  1193. // nextRenderer() when the parent element hasn't attached yet.
  1194. if (parentOrHostNode() && !parentOrHostNode()->attached())
  1195. return 0;
  1196. for (Node* n = nextSibling(); n; n = n->nextSibling()) {
  1197. if (n->renderer())
  1198. return n->renderer();
  1199. }
  1200. return 0;
  1201. }
  1202. // FIXME: This code is used by editing. Seems like it could move over there and not pollute Node.
  1203. Node *Node::previousNodeConsideringAtomicNodes() const
  1204. {
  1205. if (previousSibling()) {
  1206. Node *n = previousSibling();
  1207. while (!isAtomicNode(n) && n->lastChild())
  1208. n = n->lastChild();
  1209. return n;
  1210. }
  1211. else if (parentNode()) {
  1212. return parentNode();
  1213. }
  1214. else {
  1215. return 0;
  1216. }
  1217. }
  1218. Node *Node::nextNodeConsideringAtomicNodes() const
  1219. {
  1220. if (!isAtomicNode(this) && firstChild())
  1221. return firstChild();
  1222. if (nextSibling())
  1223. return nextSibling();
  1224. const Node *n = this;
  1225. while (n && !n->nextSibling())
  1226. n = n->parentNode();
  1227. if (n)
  1228. return n->nextSibling();
  1229. return 0;
  1230. }
  1231. Node *Node::previousLeafNode() const
  1232. {
  1233. Node *node = previousNodeConsideringAtomicNodes();
  1234. while (node) {
  1235. if (isAtomicNode(node))
  1236. return node;
  1237. node = node->previousNodeConsideringAtomicNodes();
  1238. }
  1239. return 0;
  1240. }
  1241. Node *Node::nextLeafNode() const
  1242. {
  1243. Node *node = nextNodeConsideringAtomicNodes();
  1244. while (node) {
  1245. if (isAtomicNode(node))
  1246. return node;
  1247. node = node->nextNodeConsideringAtomicNodes();
  1248. }
  1249. return 0;
  1250. }
  1251. class NodeRendererFactory {
  1252. public:
  1253. enum Type {
  1254. NotFound,
  1255. AsLightChild,
  1256. AsShadowChild,
  1257. AsContentChild
  1258. };
  1259. NodeRendererFactory(Node* node)
  1260. : m_type(NotFound)
  1261. , m_node(node)
  1262. , m_visualParentShadowRoot(0)
  1263. {
  1264. m_parentNodeForRenderingAndStyle = findVisualParent();
  1265. }
  1266. ContainerNode* parentNodeForRenderingAndStyle() const { return m_parentNodeForRenderingAndStyle; }
  1267. void createRendererIfNeeded();
  1268. private:
  1269. Document* document() { return m_node->document(); }
  1270. ContainerNode* findVisualParent();
  1271. RenderObject* nextRenderer() const { return m_node->nextRenderer(); }
  1272. RenderObject* createRendererAndStyle();
  1273. bool shouldCreateRenderer() const;
  1274. Type m_type;
  1275. Node* m_node;
  1276. ContainerNode* m_parentNodeForRenderingAndStyle;
  1277. ShadowRoot* m_visualParentShadowRoot;
  1278. };
  1279. ContainerNode* NodeRendererFactory::findVisualParent()
  1280. {
  1281. ContainerNode* parent = m_node->parentOrHostNode();
  1282. if (!parent)
  1283. return 0;
  1284. if (parent->isShadowBoundary()) {
  1285. m_type = AsShadowChild;
  1286. return parent->shadowHost();
  1287. }
  1288. if (parent->isElementNode()) {
  1289. m_visualParentShadowRoot = toElement(parent)->shadowRoot();
  1290. if (m_visualParentShadowRoot) {
  1291. if (ContainerNode* contentContainer = m_visualParentShadowRoot->contentContainerFor(m_node)) {
  1292. m_type = AsContentChild;
  1293. return NodeRendererFactory(contentContainer).parentNodeForRenderingAndStyle();
  1294. }
  1295. // FIXME: should be not found once light/shadow is mutual exclusive.
  1296. }
  1297. }
  1298. m_type = AsLightChild;
  1299. return parent;
  1300. }
  1301. bool NodeRendererFactory::shouldCreateRenderer() const
  1302. {
  1303. ASSERT(m_parentNodeForRenderingAndStyle);
  1304. RenderObject* parentRenderer = m_parentNodeForRenderingAndStyle->renderer();
  1305. if (!parentRenderer)
  1306. return false;
  1307. if (m_type == AsLightChild) {
  1308. // FIXME: Ignoring canHaveChildren() in a case of shadow children might be wrong.
  1309. // See https://bugs.webkit.org/show_bug.cgi?id=52423
  1310. if (!parentRenderer->canHaveChildren())
  1311. return false;
  1312. if (m_visualParentShadowRoot && !m_parentNodeForRenderingAndStyle->canHaveLightChildRendererWithShadow())
  1313. return false;
  1314. }
  1315. if (!m_parentNodeForRenderingAndStyle->childShouldCreateRenderer(m_node))
  1316. return false;
  1317. return true;
  1318. }
  1319. RenderObject* NodeRendererFactory::createRendererAndStyle()
  1320. {
  1321. ASSERT(!m_node->renderer());
  1322. ASSERT(document()->shouldCreateRenderers());
  1323. if (!shouldCreateRenderer())
  1324. return 0;
  1325. RefPtr<RenderStyle> style = m_node->styleForRenderer();
  1326. if (!m_node->rendererIsNeeded(style.get()))
  1327. return 0;
  1328. RenderObject* newRenderer = m_node->createRenderer(document()->renderArena(), style.get());
  1329. if (!newRenderer)
  1330. return 0;
  1331. if (!m_parentNodeForRenderingAndStyle->renderer()->isChildAllowed(newRenderer, style.get())) {
  1332. newRenderer->destroy();
  1333. return 0;
  1334. }
  1335. m_node->setRenderer(newRenderer);
  1336. newRenderer->setAnimatableStyle(style.release()); // setAnimatableStyle() can depend on renderer() already being set.
  1337. return newRenderer;
  1338. }
  1339. #if ENABLE(FULLSCREEN_API)
  1340. static RenderFullScreen* wrapWithRenderFullScreen(RenderObject* object, Document* document)
  1341. {
  1342. RenderFullScreen* fullscreenRenderer = new (document->renderArena()) RenderFullScreen(document);
  1343. fullscreenRenderer->setStyle(RenderFullScreen::createFullScreenStyle());
  1344. // It's possible that we failed to create the new render and end up wrapping nothing.
  1345. // We'll end up displaying a black screen, but Jer says this is expected.
  1346. if (object)
  1347. fullscreenRenderer->addChild(object);
  1348. document->setFullScreenRenderer(fullscreenRenderer);
  1349. return fullscreenRenderer;
  1350. }
  1351. #endif
  1352. void NodeRendererFactory::createRendererIfNeeded()
  1353. {
  1354. if (!document()->shouldCreateRenderers())
  1355. return;
  1356. ASSERT(!m_node->renderer());
  1357. RenderObject* newRenderer = createRendererAndStyle();
  1358. #if ENABLE(FULLSCREEN_API)
  1359. if (document()->webkitIsFullScreen() && document()->webkitCurrentFullScreenElement() == m_node)
  1360. newRenderer = wrapWithRenderFullScreen(newRenderer, document());
  1361. #endif
  1362. if (!newRenderer)
  1363. return;
  1364. // Note: Adding newRenderer instead of renderer(). renderer() may be a child of newRenderer.
  1365. m_parentNodeForRenderingAndStyle->renderer()->addChild(newRenderer, nextRenderer());
  1366. }
  1367. ContainerNode* Node::parentNodeForRenderingAndStyle()
  1368. {
  1369. return NodeRendererFactory(this).parentNodeForRenderingAndStyle();
  1370. }
  1371. void Node::createRendererIfNeeded()
  1372. {
  1373. NodeRendererFactory(this).createRendererIfNeeded();
  1374. }
  1375. PassRefPtr<RenderStyle> Node::styleForRenderer()
  1376. {
  1377. if (isElementNode()) {
  1378. bool allowSharing = true;
  1379. #if ENABLE(XHTMLMP)
  1380. // noscript needs the display property protected - it's a special case
  1381. allowSharing = localName() != HTMLNames::noscriptTag.localName();
  1382. #endif
  1383. return document()->styleSelector()->styleForElement(static_cast<Element*>(this), 0, allowSharing);
  1384. }
  1385. return parentNode() && parentNode()->renderer() ? parentNode()->renderer()->style() : 0;
  1386. }
  1387. bool Node::rendererIsNeeded(RenderStyle *style)
  1388. {
  1389. return (document()->documentElement() == this) || (style->display() != NONE);
  1390. }
  1391. RenderObject* Node::createRenderer(RenderArena*, RenderStyle*)
  1392. {
  1393. ASSERT(false);
  1394. return 0;
  1395. }
  1396. RenderStyle* Node::nonRendererRenderStyle() const
  1397. {
  1398. return 0;
  1399. }
  1400. void Node::setRenderStyle(PassRefPtr<RenderStyle> s)
  1401. {
  1402. if (m_renderer)
  1403. m_renderer->setAnimatableStyle(s);
  1404. }
  1405. RenderStyle* Node::virtualComputedStyle(PseudoId pseudoElementSpecifier)
  1406. {
  1407. return parentOrHostNode() ? parentOrHostNode()->computedStyle(pseudoElementSpecifier) : 0;
  1408. }
  1409. int Node::maxCharacterOffset() const
  1410. {
  1411. ASSERT_NOT_REACHED();
  1412. return 0;
  1413. }
  1414. // FIXME: Shouldn't these functions be in the editing code? Code that asks questions about HTML in the core DOM class
  1415. // is obviously misplaced.
  1416. bool Node::canStartSelection() const
  1417. {
  1418. if (rendererIsEditable())
  1419. return true;
  1420. if (renderer()) {
  1421. RenderStyle* style = renderer()->style();
  1422. // We allow selections to begin within an element that has -webkit-user-select: none set,
  1423. // but if the element is draggable then dragging should take priority over selection.
  1424. if (style->userDrag() == DRAG_ELEMENT && style->userSelect() == SELECT_NONE)
  1425. return false;
  1426. }
  1427. return parentOrHostNode() ? parentOrHostNode()->canStartSelection() : true;
  1428. }
  1429. #if ENABLE(SVG)
  1430. SVGUseElement* Node::svgShadowHost() const
  1431. {
  1432. return isSVGShadowRoot() ? static_cast<SVGUseElement*>(parent()) : 0;
  1433. }
  1434. #endif
  1435. Node* Node::shadowAncestorNode()
  1436. {
  1437. #if ENABLE(SVG)
  1438. // SVG elements living in a shadow tree only occur when <use> created them.
  1439. // For these cases we do NOT want to return the shadowParentNode() here
  1440. // but the actual shadow tree element - as main difference to the HTML forms
  1441. // shadow tree concept. (This function _could_ be made virtual - opinions?)
  1442. if (isSVGElement())
  1443. return this;
  1444. #endif
  1445. Node* root = shadowTreeRootNode();
  1446. if (root)
  1447. return root->shadowHost();
  1448. return this;
  1449. }
  1450. Node* Node::shadowTreeRootNode()
  1451. {
  1452. Node* root = this;
  1453. while (root) {
  1454. if (root->isShadowRoot() || root->isSVGShadowRoot())
  1455. return root;
  1456. root = root->parentNodeGuaranteedHostFree();
  1457. }
  1458. return 0;
  1459. }
  1460. bool Node::isInShadowTree()
  1461. {
  1462. for (Node* n = this; n; n = n->parentNode())
  1463. if (n->isShadowRoot())
  1464. return true;
  1465. return false;
  1466. }
  1467. Element* Node::parentOrHostElement() const
  1468. {
  1469. ContainerNode* parent = parentOrHostNode();
  1470. if (!parent)
  1471. return 0;
  1472. if (parent->isShadowRoot())
  1473. parent = parent->shadowHost();
  1474. if (!parent->isElementNode())
  1475. return 0;
  1476. return toElement(parent);
  1477. }
  1478. bool Node::isBlockFlow() const
  1479. {
  1480. return renderer() && renderer()->isBlockFlow();
  1481. }
  1482. bool Node::isBlockFlowOrBlockTable() const
  1483. {
  1484. return renderer() && (renderer()->isBlockFlow() || (renderer()->isTable() && !renderer()->isInline()));
  1485. }
  1486. Element *Node::enclosingBlockFlowElement() const
  1487. {
  1488. Node *n = const_cast<Node *>(this);
  1489. if (isBlockFlow())
  1490. return static_cast<Element *>(n);
  1491. while (1) {
  1492. n = n->parentNode();
  1493. if (!n)
  1494. break;
  1495. if (n->isBlockFlow() || n->hasTagName(bodyTag))
  1496. return static_cast<Element *>(n);
  1497. }
  1498. return 0;
  1499. }
  1500. Element* Node::rootEditableElement() const
  1501. {
  1502. Element* result = 0;
  1503. for (Node* n = const_cast<Node*>(this); n && n->rendererIsEditable(); n = n->parentNode()) {
  1504. if (n->isElementNode())
  1505. result = static_cast<Element*>(n);
  1506. if (n->hasTagName(bodyTag))
  1507. break;
  1508. }
  1509. return result;
  1510. }
  1511. bool Node::inSameContainingBlockFlowElement(Node *n)
  1512. {
  1513. return n ? enclosingBlockFlowElement() == n->enclosingBlockFlowElement() : false;
  1514. }
  1515. // FIXME: End of obviously misplaced HTML editing functions. Try to move these out of Node.
  1516. PassRefPtr<NodeList> Node::getElementsByTagName(const AtomicString& localName)
  1517. {
  1518. if (localName.isNull())
  1519. return 0;
  1520. NodeRareData* data = ensureRareData();
  1521. if (!data->nodeLists()) {
  1522. data->setNodeLists(NodeListsNodeData::create());
  1523. document()->addNodeListCache();
  1524. }
  1525. String name = localName;
  1526. if (document()->isHTMLDocument())
  1527. name = localName.lower();
  1528. AtomicString localNameAtom = name;
  1529. pair<NodeListsNodeData::TagNodeListCache::iterator, bool> result = data->nodeLists()->m_tagNodeListCache.add(localNameAtom, 0);
  1530. if (!result.second)
  1531. return PassRefPtr<TagNodeList>(result.first->second);
  1532. RefPtr<TagNodeList> list = TagNodeList::create(this, starAtom, localNameAtom);
  1533. result.first->second = list.get();
  1534. return list.release();
  1535. }
  1536. PassRefPtr<NodeList> Node::getElementsByTagNameNS(const AtomicString& namespaceURI, const AtomicString& localName)
  1537. {
  1538. if (localName.isNull())
  1539. return 0;
  1540. if (namespaceURI == starAtom)
  1541. return getElementsByTagName(localName);
  1542. NodeRareData* data = ensureRareData();
  1543. if (!data->nodeLists()) {
  1544. data->setNodeLists(NodeListsNodeData::create());
  1545. document()->addNodeListCache();
  1546. }
  1547. String name = localName;
  1548. if (document()->isHTMLDocument())
  1549. name = localName.lower();
  1550. AtomicString localNameAtom = name;
  1551. pair<NodeListsNodeData::TagNodeListCacheNS::iterator, bool> result = data->nodeLists()->m_tagNodeListCacheNS.add(QualifiedName(nullAtom, localNameAtom, namespaceURI).impl(), 0);
  1552. if (!result.second)
  1553. return PassRefPtr<TagNodeList>(result.first->second);
  1554. RefPtr<TagNodeList> list = TagNodeList::create(this, namespaceURI.isEmpty() ? nullAtom : namespaceURI, localNameAtom);
  1555. result.first->second = list.get();
  1556. return list.release();
  1557. }
  1558. PassRefPtr<NodeList> Node::getElementsByName(const String& elementName)
  1559. {
  1560. NodeRareData* data = ensureRareData();
  1561. if (!data->nodeLists()) {
  1562. data->setNodeLists(NodeListsNodeData::create());
  1563. document()->addNodeListCache();
  1564. }
  1565. pair<NodeListsNodeData::NameNodeListCache::iterator, bool> result = data->nodeLists()->m_nameNodeListCache.add(elementName, 0);
  1566. if (!result.second)
  1567. return PassRefPtr<NodeList>(result.first->second);
  1568. RefPtr<NameNodeList> list = NameNodeList::create(this, elementName);
  1569. result.first->second = list.get();
  1570. return list.release();
  1571. }
  1572. PassRefPtr<NodeList> Node::getElementsByClassName(const String& classNames)
  1573. {
  1574. NodeRareData* data = ensureRareData();
  1575. if (!data->nodeLists()) {
  1576. data->setNodeLists(NodeListsNodeData::create());
  1577. document()->addNodeListCache();
  1578. }
  1579. pair<NodeListsNodeData::ClassNodeListCache::iterator, bool> result = data->nodeLists()->m_classNodeListCache.add(classNames, 0);
  1580. if (!result.second)
  1581. return PassRefPtr<NodeList>(result.first->second);
  1582. RefPtr<ClassNodeList> list = ClassNodeList::create(this, classNames);
  1583. result.first->second = list.get();
  1584. return list.release();
  1585. }
  1586. PassRefPtr<Element> Node::querySelector(const String& selectors, ExceptionCode& ec)
  1587. {
  1588. if (selectors.isEmpty()) {
  1589. ec = SYNTAX_ERR;
  1590. return 0;
  1591. }
  1592. bool strictParsing = !document()->inQuirksMode();
  1593. CSSParser p(strictParsing);
  1594. CSSSelectorList querySelectorList;
  1595. p.parseSelector(selectors, document(), querySelectorList);
  1596. if (!querySelectorList.first() || querySelectorList.hasUnknownPseudoElements()) {
  1597. ec = SYNTAX_ERR;
  1598. return 0;
  1599. }
  1600. // throw a NAMESPACE_ERR if the selector includes any namespace prefixes.
  1601. if (querySelectorList.selectorsNeedNamespaceResolution()) {
  1602. ec = NAMESPACE_ERR;
  1603. return 0;
  1604. }
  1605. CSSStyleSelector::SelectorChecker selectorChecker(document(), strictParsing);
  1606. // FIXME: we could also optimize for the the [id="foo"] case
  1607. if (strictParsing && inDocument() && querySelectorList.hasOneSelector() && querySelectorList.first()->m_match == CSSSelector::Id) {
  1608. Element* element = treeScope()->getElementById(querySelectorList.first()->value());
  1609. if (element && (isDocumentNode() || element->isDescendantOf(this)) && selectorChecker.checkSelector(querySelectorList.first(), element))
  1610. return element;
  1611. return 0;
  1612. }
  1613. // FIXME: We can speed this up by implementing caching similar to the one use by getElementById
  1614. for (Node* n = firstChild(); n; n = n->traverseNextNode(this)) {
  1615. if (n->isElementNode()) {
  1616. Element* element = static_cast<Element*>(n);
  1617. for (CSSSelector* selector = querySelectorList.first(); selector; selector = CSSSelectorList::next(selector)) {
  1618. if (selectorChecker.checkSelector(selector, element))
  1619. return element;
  1620. }
  1621. }
  1622. }
  1623. return 0;
  1624. }
  1625. PassRefPtr<NodeList> Node::querySelectorAll(const String& selectors, ExceptionCode& ec)
  1626. {
  1627. if (selectors.isEmpty()) {
  1628. ec = SYNTAX_ERR;
  1629. return 0;
  1630. }
  1631. bool strictParsing = !document()->inQuirksMode();
  1632. CSSParser p(strictParsing);
  1633. CSSSelectorList querySelectorList;
  1634. p.parseSelector(selectors, document(), querySelectorList);
  1635. if (!querySelectorList.first() || querySelectorList.hasUnknownPseudoElements()) {
  1636. ec = SYNTAX_ERR;
  1637. return 0;
  1638. }
  1639. // Throw a NAMESPACE_ERR if the selector includes any namespace prefixes.
  1640. if (querySelectorList.selectorsNeedNamespaceResolution()) {
  1641. ec = NAMESPACE_ERR;
  1642. return 0;
  1643. }
  1644. return createSelectorNodeList(this, querySelectorList);
  1645. }
  1646. Document *Node::ownerDocument() const
  1647. {
  1648. Document *doc = document();
  1649. return doc == this ? 0 : doc;
  1650. }
  1651. KURL Node::baseURI() const
  1652. {
  1653. return parentNode() ? parentNode()->baseURI() : KURL();
  1654. }
  1655. bool Node::isEqualNode(Node* other) const
  1656. {
  1657. if (!other)
  1658. return false;
  1659. NodeType nodeType = this->nodeType();
  1660. if (nodeType != other->nodeType())
  1661. return false;
  1662. if (nodeName() != other->nodeName())
  1663. return false;
  1664. if (localName() != other->localName())
  1665. return false;
  1666. if (namespaceURI() != other->namespaceURI())
  1667. return false;
  1668. if (prefix() != other->prefix())
  1669. return false;
  1670. if (nodeValue() != other->nodeValue())
  1671. return false;
  1672. NamedNodeMap* attributes = this->attributes();
  1673. NamedNodeMap* otherAttributes = other->attributes();
  1674. if (!attributes && otherAttributes)
  1675. return false;
  1676. if (attributes && !attributes->mapsEquivalent(otherAttributes))
  1677. return false;
  1678. Node* child = firstChild();
  1679. Node* otherChild = other->firstChild();
  1680. while (child) {
  1681. if (!child->isEqualNode(otherChild))
  1682. return false;
  1683. child = child->nextSibling();
  1684. otherChild = otherChild->nextSibling();
  1685. }
  1686. if (otherChild)
  1687. return false;
  1688. if (nodeType == DOCUMENT_TYPE_NODE) {
  1689. const DocumentType* documentTypeThis = static_cast<const DocumentType*>(this);
  1690. const DocumentType* documentTypeOther = static_cast<const DocumentType*>(other);
  1691. if (documentTypeThis->publicId() != documentTypeOther->publicId())
  1692. return false;
  1693. if (documentTypeThis->systemId() != documentTypeOther->systemId())
  1694. return false;
  1695. if (documentTypeThis->internalSubset() != documentTypeOther->internalSubset())
  1696. return false;
  1697. NamedNodeMap* entities = documentTypeThis->entities();
  1698. NamedNodeMap* otherEntities = documentTypeOther->entities();
  1699. if (!entities && otherEntities)
  1700. return false;
  1701. if (entities && !entities->mapsEquivalent(otherEntities))
  1702. return false;
  1703. NamedNodeMap* notations = documentTypeThis->notations();
  1704. NamedNodeMap* otherNotations = documentTypeOther->notations();
  1705. if (!notations && otherNotations)
  1706. return false;
  1707. if (notations && !notations->mapsEquivalent(otherNotations))
  1708. return false;
  1709. }
  1710. return true;
  1711. }
  1712. bool Node::isDefaultNamespace(const AtomicString& namespaceURIMaybeEmpty) const
  1713. {
  1714. const AtomicString& namespaceURI = namespaceURIMaybeEmpty.isEmpty() ? nullAtom : namespaceURIMaybeEmpty;
  1715. switch (nodeType()) {
  1716. case ELEMENT_NODE: {
  1717. const Element* elem = static_cast<const Element*>(this);
  1718. if (elem->prefix().isNull())
  1719. return elem->namespaceURI() == namespaceURI;
  1720. if (elem->hasAttributes()) {
  1721. NamedNodeMap* attrs = elem->attributes();
  1722. for (unsigned i = 0; i < attrs->length(); i++) {
  1723. Attribute* attr = attrs->attributeItem(i);
  1724. if (attr->localName() == xmlnsAtom)
  1725. return attr->value() == namespaceURI;
  1726. }
  1727. }
  1728. if (Element* ancestor = ancestorElement())
  1729. return ancestor->isDefaultNamespace(namespaceURI);
  1730. return false;
  1731. }
  1732. case DOCUMENT_NODE:
  1733. if (Element* de = static_cast<const Document*>(this)->documentElement())
  1734. return de->isDefaultNamespace(namespaceURI);
  1735. return false;
  1736. case ENTITY_NODE:
  1737. case NOTATION_NODE:
  1738. case DOCUMENT_TYPE_NODE:
  1739. case DOCUMENT_FRAGMENT_NODE:
  1740. case SHADOW_ROOT_NODE:
  1741. return false;
  1742. case ATTRIBUTE_NODE: {
  1743. const Attr* attr = static_cast<const Attr*>(this);
  1744. if (attr->ownerElement())
  1745. return attr->ownerElement()->isDefaultNamespace(namespaceURI);
  1746. return false;
  1747. }
  1748. default:
  1749. if (Element* ancestor = ancestorElement())
  1750. return ancestor->isDefaultNamespace(namespaceURI);
  1751. return false;
  1752. }
  1753. }
  1754. String Node::lookupPrefix(const AtomicString &namespaceURI) const
  1755. {
  1756. // Implemented according to
  1757. // http://www.w3.org/TR/2004/REC-DOM-Level-3-Core-20040407/namespaces-algorithms.html#lookupNamespacePrefixAlgo
  1758. if (namespaceURI.isEmpty())
  1759. return String();
  1760. switch (nodeType()) {
  1761. case ELEMENT_NODE:
  1762. return lookupNamespacePrefix(namespaceURI, static_cast<const Element *>(this));
  1763. case DOCUMENT_NODE:
  1764. if (Element* de = static_cast<const Document*>(this)->documentElement())
  1765. return de->lookupPrefix(namespaceURI);
  1766. return String();
  1767. case ENTITY_NODE:
  1768. case NOTATION_NODE:
  1769. case DOCUMENT_FRAGMENT_NODE:
  1770. case DOCUMENT_TYPE_NODE:
  1771. case SHADOW_ROOT_NODE:
  1772. return String();
  1773. case ATTRIBUTE_NODE: {
  1774. const Attr *attr = static_cast<const Attr *>(this);
  1775. if (attr->ownerElement())
  1776. return attr->ownerElement()->lookupPrefix(namespaceURI);
  1777. return String();
  1778. }
  1779. default:
  1780. if (Element* ancestor = ancestorElement())
  1781. return ancestor->lookupPrefix(namespaceURI);
  1782. return String();
  1783. }
  1784. }
  1785. String Node::lookupNamespaceURI(const String &prefix) const
  1786. {
  1787. // Implemented according to
  1788. // http://www.w3.org/TR/2004/REC-DOM-Level-3-Core-20040407/namespaces-algorithms.html#lookupNamespaceURIAlgo
  1789. if (!prefix.isNull() && prefix.isEmpty())
  1790. return String();
  1791. switch (nodeType()) {
  1792. case ELEMENT_NODE: {
  1793. const Element *elem = static_cast<const Element *>(this);
  1794. if (!elem->namespaceURI().isNull() && elem->prefix() == prefix)
  1795. return elem->namespaceURI();
  1796. if (elem->hasAttributes()) {
  1797. NamedNodeMap *attrs = elem->attributes();
  1798. for (unsigned i = 0; i < attrs->length(); i++) {
  1799. Attribute *attr = attrs->attributeItem(i);
  1800. if (attr->prefix() == xmlnsAtom && attr->localName() == prefix) {
  1801. if (!attr->value().isEmpty())
  1802. return attr->value();
  1803. return String();
  1804. } else if (attr->localName() == xmlnsAtom && prefix.isNull()) {
  1805. if (!attr->value().isEmpty())
  1806. return attr->value();
  1807. return String();
  1808. }
  1809. }
  1810. }
  1811. if (Element* ancestor = ancestorElement())
  1812. return ancestor->lookupNamespaceURI(prefix);
  1813. return String();
  1814. }
  1815. case DOCUMENT_NODE:
  1816. if (Element* de = static_cast<const Document*>(this)->documentElement())
  1817. return de->lookupNamespaceURI(prefix);
  1818. return String();
  1819. case ENTITY_NODE:
  1820. case NOTATION_NODE:
  1821. case DOCUMENT_TYPE_NODE:
  1822. case DOCUMENT_FRAGMENT_NODE:
  1823. case SHADOW_ROOT_NODE:
  1824. return String();
  1825. case ATTRIBUTE_NODE: {
  1826. const Attr *attr = static_cast<const Attr *>(this);
  1827. if (attr->ownerElement())
  1828. return attr->ownerElement()->lookupNamespaceURI(prefix);
  1829. else
  1830. return String();
  1831. }
  1832. default:
  1833. if (Element* ancestor = ancestorElement())
  1834. return ancestor->lookupNamespaceURI(prefix);
  1835. return String();
  1836. }
  1837. }
  1838. String Node::lookupNamespacePrefix(const AtomicString &_namespaceURI, const Element *originalElement) const
  1839. {
  1840. if (_namespaceURI.isNull())
  1841. return String();
  1842. if (originalElement->lookupNamespaceURI(prefix()) == _namespaceURI)
  1843. return prefix();
  1844. if (hasAttributes()) {
  1845. NamedNodeMap *attrs = attributes();
  1846. for (unsigned i = 0; i < attrs->length(); i++) {
  1847. Attribute *attr = attrs->attributeItem(i);
  1848. if (attr->prefix() == xmlnsAtom &&
  1849. attr->value() == _namespaceURI &&
  1850. originalElement->lookupNamespaceURI(attr->localName()) == _namespaceURI)
  1851. return attr->localName();
  1852. }
  1853. }
  1854. if (Element* ancestor = ancestorElement())
  1855. return ancestor->lookupNamespacePrefix(_namespaceURI, originalElement);
  1856. return String();
  1857. }
  1858. static void appendTextContent(const Node* node, bool convertBRsToNewlines, bool& isNullString, StringBuilder& content)
  1859. {
  1860. switch (node->nodeType()) {
  1861. case Node::TEXT_NODE:
  1862. case Node::CDATA_SECTION_NODE:
  1863. case Node::COMMENT_NODE:
  1864. isNullString = false;
  1865. content.append(static_cast<const CharacterData*>(node)->data());
  1866. break;
  1867. case Node::PROCESSING_INSTRUCTION_NODE:
  1868. isNullString = false;
  1869. content.append(static_cast<const ProcessingInstruction*>(node)->data());
  1870. break;
  1871. case Node::ELEMENT_NODE:
  1872. if (node->hasTagName(brTag) && convertBRsToNewlines) {
  1873. isNullString = false;
  1874. content.append('\n');
  1875. break;
  1876. }
  1877. // Fall through.
  1878. case Node::ATTRIBUTE_NODE:
  1879. case Node::ENTITY_NODE:
  1880. case Node::ENTITY_REFERENCE_NODE:
  1881. case Node::DOCUMENT_FRAGMENT_NODE:
  1882. case Node::SHADOW_ROOT_NODE:
  1883. isNullString = false;
  1884. for (Node* child = node->firstChild(); child; child = child->nextSibling()) {
  1885. if (child->nodeType() == Node::COMMENT_NODE || child->nodeType() == Node::PROCESSING_INSTRUCTION_NODE)
  1886. continue;
  1887. appendTextContent(child, convertBRsToNewlines, isNullString, content);
  1888. }
  1889. break;
  1890. case Node::DOCUMENT_NODE:
  1891. case Node::DOCUMENT_TYPE_NODE:
  1892. case Node::NOTATION_NODE:
  1893. case Node::XPATH_NAMESPACE_NODE:
  1894. break;
  1895. }
  1896. }
  1897. String Node::textContent(bool convertBRsToNewlines) const
  1898. {
  1899. StringBuilder content;
  1900. bool isNullString = true;
  1901. appendTextContent(this, convertBRsToNewlines, isNullString, content);
  1902. return isNullString ? String() : content.toString();
  1903. }
  1904. void Node::setTextContent(const String& text, ExceptionCode& ec)
  1905. {
  1906. switch (nodeType()) {
  1907. case TEXT_NODE:
  1908. case CDATA_SECTION_NODE:
  1909. case COMMENT_NODE:
  1910. case PROCESSING_INSTRUCTION_NODE:
  1911. setNodeValue(text, ec);
  1912. return;
  1913. case ELEMENT_NODE:
  1914. case ATTRIBUTE_NODE:
  1915. case ENTITY_NODE:
  1916. case ENTITY_REFERENCE_NODE:
  1917. case DOCUMENT_FRAGMENT_NODE:
  1918. case SHADOW_ROOT_NODE: {
  1919. ContainerNode* container = toContainerNode(this);
  1920. container->removeChildren();
  1921. if (!text.isEmpty())
  1922. container->appendChild(document()->createTextNode(text), ec);
  1923. return;
  1924. }
  1925. case DOCUMENT_NODE:
  1926. case DOCUMENT_TYPE_NODE:
  1927. case NOTATION_NODE:
  1928. case XPATH_NAMESPACE_NODE:
  1929. // Do nothing.
  1930. return;
  1931. }
  1932. ASSERT_NOT_REACHED();
  1933. }
  1934. Element* Node::ancestorElement() const
  1935. {
  1936. // In theory, there can be EntityReference nodes between elements, but this is currently not supported.
  1937. for (ContainerNode* n = parentNode(); n; n = n->parentNode()) {
  1938. if (n->isElementNode())
  1939. return static_cast<Element*>(n);
  1940. }
  1941. return 0;
  1942. }
  1943. bool Node::offsetInCharacters() const
  1944. {
  1945. return false;
  1946. }
  1947. unsigned short Node::compareDocumentPosition(Node* otherNode)
  1948. {
  1949. // It is not clear what should be done if |otherNode| is 0.
  1950. if (!otherNode)
  1951. return DOCUMENT_POSITION_DISCONNECTED;
  1952. if (otherNode == this)
  1953. return DOCUMENT_POSITION_EQUIVALENT;
  1954. Attr* attr1 = nodeType() == ATTRIBUTE_NODE ? static_cast<Attr*>(this) : 0;
  1955. Attr* attr2 = otherNode->nodeType() == ATTRIBUTE_NODE ? static_cast<Attr*>(otherNode) : 0;
  1956. Node* start1 = attr1 ? attr1->ownerElement() : this;
  1957. Node* start2 = attr2 ? attr2->ownerElement() : otherNode;
  1958. // If either of start1 or start2 is null, then we are disconnected, since one of the nodes is
  1959. // an orphaned attribute node.
  1960. if (!start1 || !start2)
  1961. return DOCUMENT_POSITION_DISCONNECTED | DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC;
  1962. Vector<Node*, 16> chain1;
  1963. Vector<Node*, 16> chain2;
  1964. if (attr1)
  1965. chain1.append(attr1);
  1966. if (attr2)
  1967. chain2.append(attr2);
  1968. if (attr1 && attr2 && start1 == start2 && start1) {
  1969. // We are comparing two attributes on the same node. Crawl our attribute map
  1970. // and see which one we hit first.
  1971. NamedNodeMap* map = attr1->ownerElement()->attributes(true);
  1972. unsigned length = map->length();
  1973. for (unsigned i = 0; i < length; ++i) {
  1974. // If neither of the two determining nodes is a child node and nodeType is the same for both determining nodes, then an
  1975. // implementation-dependent order between the determining nodes is returned. This order is stable as long as no nodes of
  1976. // the same nodeType are inserted into or removed from the direct container. This would be the case, for example,
  1977. // when comparing two attributes of the same element, and inserting or removing additional attributes might change
  1978. // the order between existing attributes.
  1979. Attribute* attr = map->attributeItem(i);
  1980. if (attr1->attr() == attr)
  1981. return DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC | DOCUMENT_POSITION_FOLLOWING;
  1982. if (attr2->attr() == attr)
  1983. return DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC | DOCUMENT_POSITION_PRECEDING;
  1984. }
  1985. ASSERT_NOT_REACHED();
  1986. return DOCUMENT_POSITION_DISCONNECTED;
  1987. }
  1988. // If one node is in the document and the other is not, we must be disconnected.
  1989. // If the nodes have different owning documents, they must be disconnected. Note that we avoid
  1990. // comparing Attr nodes here, since they return false from inDocument() all the time (which seems like a bug).
  1991. if (start1->inDocument() != start2->inDocument() ||
  1992. start1->document() != start2->document())
  1993. return DOCUMENT_POSITION_DISCONNECTED | DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC;
  1994. // We need to find a common ancestor container, and then compare the indices of the two immediate children.
  1995. Node* current;
  1996. for (current = start1; current; current = current->parentNode())
  1997. chain1.append(current);
  1998. for (current = start2; current; current = current->parentNode())
  1999. chain2.append(current);
  2000. // Walk the two chains backwards and look for the first difference.
  2001. unsigned index1 = chain1.size();
  2002. unsigned index2 = chain2.size();
  2003. for (unsigned i = min(index1, index2); i; --i) {
  2004. Node* child1 = chain1[--index1];
  2005. Node* child2 = chain2[--index2];
  2006. if (child1 != child2) {
  2007. // If one of the children is an attribute, it wins.
  2008. if (child1->nodeType() == ATTRIBUTE_NODE)
  2009. return DOCUMENT_POSITION_FOLLOWING;
  2010. if (child2->nodeType() == ATTRIBUTE_NODE)
  2011. return DOCUMENT_POSITION_PRECEDING;
  2012. if (!child2->nextSibling())
  2013. return DOCUMENT_POSITION_FOLLOWING;
  2014. if (!child1->nextSibling())
  2015. return DOCUMENT_POSITION_PRECEDING;
  2016. // Otherwise we need to see which node occurs first. Crawl backwards from child2 looking for child1.
  2017. for (Node* child = child2->previousSibling(); child; child = child->previousSibling()) {
  2018. if (child == child1)
  2019. return DOCUMENT_POSITION_FOLLOWING;
  2020. }
  2021. return DOCUMENT_POSITION_PRECEDING;
  2022. }
  2023. }
  2024. // There was no difference between the two parent chains, i.e., one was a subset of the other. The shorter
  2025. // chain is the ancestor.
  2026. return index1 < index2 ?
  2027. DOCUMENT_POSITION_FOLLOWING | DOCUMENT_POSITION_CONTAINED_BY :
  2028. DOCUMENT_POSITION_PRECEDING | DOCUMENT_POSITION_CONTAINS;
  2029. }
  2030. FloatPoint Node::convertToPage(const FloatPoint& p) const
  2031. {
  2032. // If there is a renderer, just ask it to do the conversion
  2033. if (renderer())
  2034. return renderer()->localToAbsolute(p, false, true);
  2035. // Otherwise go up the tree looking for a renderer
  2036. Element *parent = ancestorElement();
  2037. if (parent)
  2038. return parent->convertToPage(p);
  2039. // No parent - no conversion needed
  2040. return p;
  2041. }
  2042. FloatPoint Node::convertFromPage(const FloatPoint& p) const
  2043. {
  2044. // If there is a renderer, just ask it to do the conversion
  2045. if (renderer())
  2046. return renderer()->absoluteToLocal(p, false, true);
  2047. // Otherwise go up the tree looking for a renderer
  2048. Element *parent = ancestorElement();
  2049. if (parent)
  2050. return parent->convertFromPage(p);
  2051. // No parent - no conversion needed
  2052. return p;
  2053. }
  2054. #ifndef NDEBUG
  2055. static void appendAttributeDesc(const Node* node, String& string, const QualifiedName& name, const char* attrDesc)
  2056. {
  2057. if (node->isElementNode()) {
  2058. String attr = static_cast<const Element*>(node)->getAttribute(name);
  2059. if (!attr.isEmpty()) {
  2060. string += attrDesc;
  2061. string += attr;
  2062. }
  2063. }
  2064. }
  2065. void Node::showNode(const char* prefix) const
  2066. {
  2067. if (!prefix)
  2068. prefix = "";
  2069. if (isTextNode()) {
  2070. String value = nodeValue();
  2071. value.replace('\\', "\\\\");
  2072. value.replace('\n', "\\n");
  2073. fprintf(stderr, "%s%s\t%p \"%s\"\n", prefix, nodeName().utf8().data(), this, value.utf8().data());
  2074. } else {
  2075. String attrs = "";
  2076. appendAttributeDesc(this, attrs, classAttr, " CLASS=");
  2077. appendAttributeDesc(this, attrs, styleAttr, " STYLE=");
  2078. fprintf(stderr, "%s%s\t%p%s\n", prefix, nodeName().utf8().data(), this, attrs.utf8().data());
  2079. }
  2080. }
  2081. void Node::showTreeForThis() const
  2082. {
  2083. showTreeAndMark(this, "*");
  2084. }
  2085. static void traverseTreeAndMark(const String& baseIndent, const Node* rootNode, const Node* markedNode1, const char* markedLabel1, const Node* markedNode2, const char* markedLabel2)
  2086. {
  2087. for (const Node* node = rootNode; node; node = node->traverseNextNode()) {
  2088. if (node == markedNode1)
  2089. fprintf(stderr, "%s", markedLabel1);
  2090. if (node == markedNode2)
  2091. fprintf(stderr, "%s", markedLabel2);
  2092. String indent = baseIndent;
  2093. for (const Node* tmpNode = node; tmpNode && tmpNode != rootNode; tmpNode = tmpNode->parentOrHostNode())
  2094. indent += "\t";
  2095. fprintf(stderr, "%s", indent.utf8().data());
  2096. node->showNode();
  2097. ContainerNode* shadow = shadowRoot(const_cast<Node*>(node));
  2098. if (!shadow && node->renderer() && node->renderer()->isTextControl())
  2099. shadow = static_cast<RenderTextControl*>(node->renderer())->innerTextElement();
  2100. if (shadow) {
  2101. indent += "\t";
  2102. traverseTreeAndMark(indent, shadow, markedNode1, markedLabel1, markedNode2, markedLabel2);
  2103. }
  2104. }
  2105. }
  2106. void Node::showTreeAndMark(const Node* markedNode1, const char* markedLabel1, const Node* markedNode2, const char* markedLabel2) const
  2107. {
  2108. const Node* rootNode;
  2109. const Node* node = this;
  2110. while (node->parentOrHostNode() && !node->hasTagName(bodyTag))
  2111. node = node->parentOrHostNode();
  2112. rootNode = node;
  2113. String startingIndent;
  2114. traverseTreeAndMark(startingIndent, rootNode, markedNode1, markedLabel1, markedNode2, markedLabel2);
  2115. }
  2116. void Node::formatForDebugger(char* buffer, unsigned length) const
  2117. {
  2118. String result;
  2119. String s;
  2120. s = nodeName();
  2121. if (s.length() == 0)
  2122. result += "<none>";
  2123. else
  2124. result += s;
  2125. strncpy(buffer, result.utf8().data(), length - 1);
  2126. }
  2127. #endif
  2128. // --------
  2129. void NodeListsNodeData::invalidateCaches()
  2130. {
  2131. m_childNodeListCaches->reset();
  2132. if (m_labelsNodeListCache)
  2133. m_labelsNodeListCache->invalidateCache();
  2134. TagNodeListCache::const_iterator tagCacheEnd = m_tagNodeListCache.end();
  2135. for (TagNodeListCache::const_iterator it = m_tagNodeListCache.begin(); it != tagCacheEnd; ++it)
  2136. it->second->invalidateCache();
  2137. TagNodeListCacheNS::const_iterator tagCacheNSEnd = m_tagNodeListCacheNS.end();
  2138. for (TagNodeListCacheNS::const_iterator it = m_tagNodeListCacheNS.begin(); it != tagCacheNSEnd; ++it)
  2139. it->second->invalidateCache();
  2140. invalidateCachesThatDependOnAttributes();
  2141. }
  2142. void NodeListsNodeData::invalidateCachesThatDependOnAttributes()
  2143. {
  2144. ClassNodeListCache::iterator classCacheEnd = m_classNodeListCache.end();
  2145. for (ClassNodeListCache::iterator it = m_classNodeListCache.begin(); it != classCacheEnd; ++it)
  2146. it->second->invalidateCache();
  2147. NameNodeListCache::iterator nameCacheEnd = m_nameNodeListCache.end();
  2148. for (NameNodeListCache::iterator it = m_nameNodeListCache.begin(); it != nameCacheEnd; ++it)
  2149. it->second->invalidateCache();
  2150. if (m_labelsNodeListCache)
  2151. m_labelsNodeListCache->invalidateCache();
  2152. }
  2153. bool NodeListsNodeData::isEmpty() const
  2154. {
  2155. if (!m_listsWithCaches.isEmpty())
  2156. return false;
  2157. if (m_childNodeListCaches->refCount())
  2158. return false;
  2159. TagNodeListCache::const_iterator tagCacheEnd = m_tagNodeListCache.end();
  2160. for (TagNodeListCache::const_iterator it = m_tagNodeListCache.begin(); it != tagCacheEnd; ++it) {
  2161. if (it->second->refCount())
  2162. return false;
  2163. }
  2164. TagNodeListCacheNS::const_iterator tagCacheNSEnd = m_tagNodeListCacheNS.end();
  2165. for (TagNodeListCacheNS::const_iterator it = m_tagNodeListCacheNS.begin(); it != tagCacheNSEnd; ++it) {
  2166. if (it->second->refCount())
  2167. return false;
  2168. }
  2169. ClassNodeListCache::const_iterator classCacheEnd = m_classNodeListCache.end();
  2170. for (ClassNodeListCache::const_iterator it = m_classNodeListCache.begin(); it != classCacheEnd; ++it) {
  2171. if (it->second->refCount())
  2172. return false;
  2173. }
  2174. NameNodeListCache::const_iterator nameCacheEnd = m_nameNodeListCache.end();
  2175. for (NameNodeListCache::const_iterator it = m_nameNodeListCache.begin(); it != nameCacheEnd; ++it) {
  2176. if (it->second->refCount())
  2177. return false;
  2178. }
  2179. if (m_labelsNodeListCache)
  2180. return false;
  2181. return true;
  2182. }
  2183. void Node::getSubresourceURLs(ListHashSet<KURL>& urls) const
  2184. {
  2185. addSubresourceAttributeURLs(urls);
  2186. }
  2187. Node* Node::enclosingLinkEventParentOrSelf()
  2188. {
  2189. for (Node* node = this; node; node = node->parentOrHostNode()) {
  2190. // For imagemaps, the enclosing link node is the associated area element not the image itself.
  2191. // So we don't let images be the enclosingLinkNode, even though isLink sometimes returns true
  2192. // for them.
  2193. if (node->isLink() && !node->hasTagName(imgTag))
  2194. return node;
  2195. }
  2196. return 0;
  2197. }
  2198. // --------
  2199. ScriptExecutionContext* Node::scriptExecutionContext() const
  2200. {
  2201. return document();
  2202. }
  2203. void Node::insertedIntoDocument()
  2204. {
  2205. setInDocument();
  2206. }
  2207. void Node::removedFromDocument()
  2208. {
  2209. clearInDocument();
  2210. }
  2211. void Node::willMoveToNewOwnerDocument()
  2212. {
  2213. ASSERT(!willMoveToNewOwnerDocumentWasCalled);
  2214. setWillMoveToNewOwnerDocumentWasCalled(true);
  2215. }
  2216. void Node::didMoveToNewOwnerDocument()
  2217. {
  2218. ASSERT(!didMoveToNewOwnerDocumentWasCalled);
  2219. setDidMoveToNewOwnerDocumentWasCalled(true);
  2220. }
  2221. #if ENABLE(SVG)
  2222. static inline HashSet<SVGElementInstance*> instancesForSVGElement(Node* node)
  2223. {
  2224. HashSet<SVGElementInstance*> instances;
  2225. ASSERT(node);
  2226. if (!node->isSVGElement() || node->shadowTreeRootNode())
  2227. return HashSet<SVGElementInstance*>();
  2228. SVGElement* element = static_cast<SVGElement*>(node);
  2229. if (!element->isStyled())
  2230. return HashSet<SVGElementInstance*>();
  2231. SVGStyledElement* styledElement = static_cast<SVGStyledElement*>(element);
  2232. ASSERT(!styledElement->instanceUpdatesBlocked());
  2233. return styledElement->instancesForElement();
  2234. }
  2235. #endif
  2236. static inline bool tryAddEventListener(Node* targetNode, const AtomicString& eventType, PassRefPtr<EventListener> listener, bool useCapture)
  2237. {
  2238. if (!targetNode->EventTarget::addEventListener(eventType, listener, useCapture))
  2239. return false;
  2240. if (Document* document = targetNode->document())
  2241. document->addListenerTypeIfNeeded(eventType);
  2242. return true;
  2243. }
  2244. bool Node::addEventListener(const AtomicString& eventType, PassRefPtr<EventListener> listener, bool useCapture)
  2245. {
  2246. #if !ENABLE(SVG)
  2247. return tryAddEventListener(this, eventType, listener, useCapture);
  2248. #else
  2249. if (!isSVGElement())
  2250. return tryAddEventListener(this, eventType, listener, useCapture);
  2251. HashSet<SVGElementInstance*> instances = instancesForSVGElement(this);
  2252. if (instances.isEmpty())
  2253. return tryAddEventListener(this, eventType, listener, useCapture);
  2254. RefPtr<EventListener> listenerForRegularTree = listener;
  2255. RefPtr<EventListener> listenerForShadowTree = listenerForRegularTree;
  2256. // Add event listener to regular DOM element
  2257. if (!tryAddEventListener(this, eventType, listenerForRegularTree.release(), useCapture))
  2258. return false;
  2259. // Add event listener to all shadow tree DOM element instances
  2260. const HashSet<SVGElementInstance*>::const_iterator end = instances.end();
  2261. for (HashSet<SVGElementInstance*>::const_iterator it = instances.begin(); it != end; ++it) {
  2262. ASSERT((*it)->shadowTreeElement());
  2263. ASSERT((*it)->correspondingElement() == this);
  2264. RefPtr<EventListener> listenerForCurrentShadowTreeElement = listenerForShadowTree;
  2265. bool result = tryAddEventListener((*it)->shadowTreeElement(), eventType, listenerForCurrentShadowTreeElement.release(), useCapture);
  2266. ASSERT_UNUSED(result, result);
  2267. }
  2268. return true;
  2269. #endif
  2270. }
  2271. static inline bool tryRemoveEventListener(Node* targetNode, const AtomicString& eventType, EventListener* listener, bool useCapture)
  2272. {
  2273. if (!targetNode->EventTarget::removeEventListener(eventType, listener, useCapture))
  2274. return false;
  2275. // FIXME: Notify Document that the listener has vanished. We need to keep track of a number of
  2276. // listeners for each type, not just a bool - see https://bugs.webkit.org/show_bug.cgi?id=33861
  2277. return true;
  2278. }
  2279. bool Node::removeEventListener(const AtomicString& eventType, EventListener* listener, bool useCapture)
  2280. {
  2281. #if !ENABLE(SVG)
  2282. return tryRemoveEventListener(this, eventType, listener, useCapture);
  2283. #else
  2284. if (!isSVGElement())
  2285. return tryRemoveEventListener(this, eventType, listener, useCapture);
  2286. HashSet<SVGElementInstance*> instances = instancesForSVGElement(this);
  2287. if (instances.isEmpty())
  2288. return tryRemoveEventListener(this, eventType, listener, useCapture);
  2289. // EventTarget::removeEventListener creates a PassRefPtr around the given EventListener
  2290. // object when creating a temporary RegisteredEventListener object used to look up the
  2291. // event listener in a cache. If we want to be able to call removeEventListener() multiple
  2292. // times on different nodes, we have to delay its immediate destruction, which would happen
  2293. // after the first call below.
  2294. RefPtr<EventListener> protector(listener);
  2295. // Remove event listener from regular DOM element
  2296. if (!tryRemoveEventListener(this, eventType, listener, useCapture))
  2297. return false;
  2298. // Remove event listener from all shadow tree DOM element instances
  2299. const HashSet<SVGElementInstance*>::const_iterator end = instances.end();
  2300. for (HashSet<SVGElementInstance*>::const_iterator it = instances.begin(); it != end; ++it) {
  2301. ASSERT((*it)->correspondingElement() == this);
  2302. SVGElement* shadowTreeElement = (*it)->shadowTreeElement();
  2303. ASSERT(shadowTreeElement);
  2304. if (tryRemoveEventListener(shadowTreeElement, eventType, listener, useCapture))
  2305. continue;
  2306. // This case can only be hit for event listeners created from markup
  2307. ASSERT(listener->wasCreatedFromMarkup());
  2308. // If the event listener 'listener' has been created from markup and has been fired before
  2309. // then JSLazyEventListener::parseCode() has been called and m_jsFunction of that listener
  2310. // has been created (read: it's not 0 anymore). During shadow tree creation, the event
  2311. // listener DOM attribute has been cloned, and another event listener has been setup in
  2312. // the shadow tree. If that event listener has not been used yet, m_jsFunction is still 0,
  2313. // and tryRemoveEventListener() above will fail. Work around that very seldom problem.
  2314. EventTargetData* data = shadowTreeElement->eventTargetData();
  2315. ASSERT(data);
  2316. EventListenerMap::iterator result = data->eventListenerMap.find(eventType);
  2317. ASSERT(result != data->eventListenerMap.end());
  2318. EventListenerVector* entry = result->second;
  2319. ASSERT(entry);
  2320. unsigned int index = 0;
  2321. bool foundListener = false;
  2322. EventListenerVector::iterator end = entry->end();
  2323. for (EventListenerVector::iterator it = entry->begin(); it != end; ++it) {
  2324. if (!(*it).listener->wasCreatedFromMarkup()) {
  2325. ++index;
  2326. continue;
  2327. }
  2328. foundListener = true;
  2329. entry->remove(index);
  2330. break;
  2331. }
  2332. ASSERT_UNUSED(foundListener, foundListener);
  2333. if (entry->isEmpty()) {
  2334. delete entry;
  2335. data->eventListenerMap.remove(result);
  2336. }
  2337. }
  2338. return true;
  2339. #endif
  2340. }
  2341. EventTargetData* Node::eventTargetData()
  2342. {
  2343. return hasRareData() ? rareData()->eventTargetData() : 0;
  2344. }
  2345. EventTargetData* Node::ensureEventTargetData()
  2346. {
  2347. return ensureRareData()->ensureEventTargetData();
  2348. }
  2349. void Node::handleLocalEvents(Event* event)
  2350. {
  2351. if (!hasRareData() || !rareData()->eventTargetData())
  2352. return;
  2353. if (disabled() && event->isMouseEvent())
  2354. return;
  2355. fireEventListeners(event);
  2356. }
  2357. void Node::dispatchScopedEvent(PassRefPtr<Event> event)
  2358. {
  2359. EventDispatcher::dispatchScopedEvent(this, event);
  2360. }
  2361. bool Node::dispatchEvent(PassRefPtr<Event> event)
  2362. {
  2363. return EventDispatcher::dispatchEvent(this, EventDispatchMediator(event));
  2364. }
  2365. void Node::dispatchSubtreeModifiedEvent()
  2366. {
  2367. ASSERT(!eventDispatchForbidden());
  2368. document()->incDOMTreeVersion();
  2369. notifyNodeListsAttributeChanged(); // FIXME: Can do better some day. Really only care about the name attribute changing.
  2370. if (!document()->hasListenerType(Document::DOMSUBTREEMODIFIED_LISTENER))
  2371. return;
  2372. dispatchScopedEvent(MutationEvent::create(eventNames().DOMSubtreeModifiedEvent, true));
  2373. }
  2374. void Node::dispatchUIEvent(const AtomicString& eventType, int detail, PassRefPtr<Event> underlyingEvent)
  2375. {
  2376. ASSERT(!eventDispatchForbidden());
  2377. ASSERT(eventType == eventNames().focusinEvent || eventType == eventNames().focusoutEvent ||
  2378. eventType == eventNames().DOMFocusInEvent || eventType == eventNames().DOMFocusOutEvent || eventType == eventNames().DOMActivateEvent);
  2379. bool cancelable = eventType == eventNames().DOMActivateEvent;
  2380. RefPtr<UIEvent> event = UIEvent::create(eventType, true, cancelable, document()->defaultView(), detail);
  2381. event->setUnderlyingEvent(underlyingEvent);
  2382. dispatchScopedEvent(event.release());
  2383. }
  2384. bool Node::dispatchKeyEvent(const PlatformKeyboardEvent& event)
  2385. {
  2386. return EventDispatcher::dispatchEvent(this, KeyboardEventDispatchMediator(KeyboardEvent::create(event, document()->defaultView())));
  2387. }
  2388. bool Node::dispatchMouseEvent(const PlatformMouseEvent& event, const AtomicString& eventType,
  2389. int detail, Node* relatedTarget)
  2390. {
  2391. return EventDispatcher::dispatchEvent(this, MouseEventDispatchMediator(MouseEvent::create(eventType, document()->defaultView(), event, detail, relatedTarget)));
  2392. }
  2393. void Node::dispatchSimulatedClick(PassRefPtr<Event> event, bool sendMouseEvents, bool showPressedLook)
  2394. {
  2395. EventDispatcher::dispatchSimulatedClick(this, event, sendMouseEvents, showPressedLook);
  2396. }
  2397. bool Node::dispatchWheelEvent(const PlatformWheelEvent& event)
  2398. {
  2399. return EventDispatcher::dispatchEvent(this, WheelEventDispatchMediator(event, document()->defaultView()));
  2400. }
  2401. void Node::dispatchFocusEvent()
  2402. {
  2403. dispatchEvent(Event::create(eventNames().focusEvent, false, false));
  2404. }
  2405. void Node::dispatchBlurEvent()
  2406. {
  2407. dispatchEvent(Event::create(eventNames().blurEvent, false, false));
  2408. }
  2409. void Node::dispatchChangeEvent()
  2410. {
  2411. dispatchEvent(Event::create(eventNames().changeEvent, true, false));
  2412. }
  2413. void Node::dispatchInputEvent()
  2414. {
  2415. dispatchEvent(Event::create(eventNames().inputEvent, true, false));
  2416. }
  2417. bool Node::disabled() const
  2418. {
  2419. return false;
  2420. }
  2421. void Node::defaultEventHandler(Event* event)
  2422. {
  2423. if (event->target() != this)
  2424. return;
  2425. const AtomicString& eventType = event->type();
  2426. if (eventType == eventNames().keydownEvent || eventType == eventNames().keypressEvent) {
  2427. if (event->isKeyboardEvent())
  2428. if (Frame* frame = document()->frame())
  2429. frame->eventHandler()->defaultKeyboardEventHandler(static_cast<KeyboardEvent*>(event));
  2430. } else if (eventType == eventNames().clickEvent) {
  2431. int detail = event->isUIEvent() ? static_cast<UIEvent*>(event)->detail() : 0;
  2432. dispatchUIEvent(eventNames().DOMActivateEvent, detail, event);
  2433. #if ENABLE(CONTEXT_MENUS)
  2434. } else if (eventType == eventNames().contextmenuEvent) {
  2435. if (Frame* frame = document()->frame())
  2436. if (Page* page = frame->page())
  2437. page->contextMenuController()->handleContextMenuEvent(event);
  2438. #endif
  2439. } else if (eventType == eventNames().textInputEvent) {
  2440. if (event->isTextEvent())
  2441. if (Frame* frame = document()->frame())
  2442. frame->eventHandler()->defaultTextInputEventHandler(static_cast<TextEvent*>(event));
  2443. #if ENABLE(PAN_SCROLLING)
  2444. } else if (eventType == eventNames().mousedownEvent && event->isMouseEvent()) {
  2445. MouseEvent* mouseEvent = static_cast<MouseEvent*>(event);
  2446. if (mouseEvent->button() == MiddleButton) {
  2447. if (enclosingLinkEventParentOrSelf())
  2448. return;
  2449. RenderObject* renderer = this->renderer();
  2450. while (renderer && (!renderer->isBox() || !toRenderBox(renderer)->canBeScrolledAndHasScrollableArea()))
  2451. renderer = renderer->parent();
  2452. if (renderer) {
  2453. if (Frame* frame = document()->frame())
  2454. frame->eventHandler()->startPanScrolling(renderer);
  2455. }
  2456. }
  2457. #endif
  2458. } else if (eventType == eventNames().mousewheelEvent && event->isWheelEvent()) {
  2459. WheelEvent* wheelEvent = static_cast<WheelEvent*>(event);
  2460. // If we don't have a renderer, send the wheel event to the first node we find with a renderer.
  2461. // This is needed for <option> and <optgroup> elements so that <select>s get a wheel scroll.
  2462. Node* startNode = this;
  2463. while (startNode && !startNode->renderer())
  2464. startNode = startNode->parentOrHostNode();
  2465. if (startNode && startNode->renderer())
  2466. if (Frame* frame = document()->frame())
  2467. frame->eventHandler()->defaultWheelEventHandler(startNode, wheelEvent);
  2468. } else if (event->type() == eventNames().webkitEditableContentChangedEvent) {
  2469. dispatchInputEvent();
  2470. }
  2471. }
  2472. } // namespace WebCore
  2473. #ifndef NDEBUG
  2474. void showTree(const WebCore::Node* node)
  2475. {
  2476. if (node)
  2477. node->showTreeForThis();
  2478. }
  2479. #endif