/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

Large files are truncated click here to view the full 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. {