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 Apple Inc. All rights reserved.
6 * Copyright (C) 2007 Trolltech ASA
8 * This library is free software; you can redistribute it and/or
9 * modify it under the terms of the GNU Library General Public
10 * License as published by the Free Software Foundation; either
11 * version 2 of the License, or (at your option) any later version.
13 * This library is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
16 * Library General Public License for more details.
18 * You should have received a copy of the GNU Library General Public License
19 * along with this library; see the file COPYING.LIB. If not, write to
20 * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
21 * Boston, MA 02110-1301, USA.
28 #include "ChildNodeList.h"
29 #include "ClassNodeList.h"
30 #include "DOMImplementation.h"
33 #include "ExceptionCode.h"
35 #include "HTMLNames.h"
36 #include "HTMLNames.h"
39 #include "NameNodeList.h"
40 #include "NamedAttrMap.h"
41 #include "RenderObject.h"
43 #include "TextStream.h"
45 #include "htmlediting.h"
46 #include "kjs_binding.h"
50 using namespace HTMLNames;
52 typedef HashSet<NodeList*> NodeListSet;
53 struct NodeListsNodeData {
54 NodeListSet m_listsToNotify;
55 NodeList::Caches m_childNodeListCaches;
56 HashMap<String, NodeList::Caches> m_classNodeListCaches;
57 HashMap<String, NodeList::Caches> m_nameNodeListCaches;
60 // NodeList that limits to a particular tag.
61 class TagNodeList : public NodeList {
63 TagNodeList(PassRefPtr<Node> rootNode, const AtomicString& namespaceURI, const AtomicString& localName);
65 virtual unsigned length() const;
66 virtual Node* item(unsigned index) const;
69 virtual bool nodeMatches(Node*) const;
71 AtomicString m_namespaceURI;
72 AtomicString m_localName;
75 inline TagNodeList::TagNodeList(PassRefPtr<Node> rootNode, const AtomicString& namespaceURI, const AtomicString& localName)
76 : NodeList(rootNode, true)
77 , m_namespaceURI(namespaceURI)
78 , m_localName(localName)
80 ASSERT(m_namespaceURI.isNull() || !m_namespaceURI.isEmpty());
83 unsigned TagNodeList::length() const
85 return recursiveLength();
88 Node* TagNodeList::item(unsigned index) const
90 return recursiveItem(index);
93 bool TagNodeList::nodeMatches(Node* testNode) const
95 if (!testNode->isElementNode())
98 if (m_namespaceURI != starAtom && m_namespaceURI != testNode->namespaceURI())
101 return m_localName == starAtom || m_localName == testNode->localName();
105 bool Node::isSupported(const String& feature, const String& version)
107 return DOMImplementation::instance()->hasFeature(feature, version);
111 WTFLogChannel LogWebCoreNodeLeaks = { 0x00000000, "", WTFLogChannelOn };
114 static unsigned count;
119 LOG(WebCoreNodeLeaks, "LEAK: %u Node\n", count);
122 unsigned NodeCounter::count = 0;
123 static NodeCounter nodeCounter;
125 static bool shouldIgnoreLeaks = false;
126 static HashSet<Node*> ignoreSet;
129 void Node::startIgnoringLeaks()
132 shouldIgnoreLeaks = true;
136 void Node::stopIgnoringLeaks()
139 shouldIgnoreLeaks = false;
143 Node::Node(Document *doc)
152 m_styleChange(NoStyleChange),
153 m_hasChangedChild(false),
156 m_attrWasSpecifiedOrElementHasRareData(false),
160 m_inActiveChain(false),
162 m_dispatchingSimulatedEvent(false),
163 m_inSubtreeMark(false)
166 if (shouldIgnoreLeaks)
169 ++NodeCounter::count;
173 void Node::setDocument(Document* doc)
175 if (inDocument() || m_document == doc)
178 willMoveToNewOwnerDocument();
182 KJS::ScriptInterpreter::updateDOMNodeDocument(this, m_document.get(), doc);
186 didMoveToNewOwnerDocument();
192 HashSet<Node*>::iterator it = ignoreSet.find(this);
193 if (it != ignoreSet.end())
194 ignoreSet.remove(it);
196 --NodeCounter::count;
202 m_previous->setNextSibling(0);
204 m_next->setPreviousSibling(0);
207 String Node::nodeValue() const
212 void Node::setNodeValue(const String& /*nodeValue*/, ExceptionCode& ec)
214 // NO_MODIFICATION_ALLOWED_ERR: Raised when the node is readonly
215 if (isReadOnlyNode()) {
216 ec = NO_MODIFICATION_ALLOWED_ERR;
220 // by default nodeValue is null, so setting it has no effect
223 PassRefPtr<NodeList> Node::childNodes()
226 m_nodeLists.set(new NodeListsNodeData);
228 return new ChildNodeList(this, &m_nodeLists->m_childNodeListCaches);
231 Node* Node::virtualFirstChild() const
236 Node* Node::virtualLastChild() const
241 Node *Node::lastDescendant() const
243 Node *n = const_cast<Node *>(this);
244 while (n && n->lastChild())
249 Node* Node::firstDescendant() const
251 Node *n = const_cast<Node *>(this);
252 while (n && n->firstChild())
257 bool Node::insertBefore(PassRefPtr<Node>, Node*, ExceptionCode& ec)
259 ec = HIERARCHY_REQUEST_ERR;
263 bool Node::replaceChild(PassRefPtr<Node>, Node*, ExceptionCode& ec)
265 ec = HIERARCHY_REQUEST_ERR;
269 bool Node::removeChild(Node*, ExceptionCode& ec)
275 bool Node::appendChild(PassRefPtr<Node>, ExceptionCode& ec)
277 ec = HIERARCHY_REQUEST_ERR;
281 void Node::remove(ExceptionCode& ec)
284 if (Node *p = parentNode())
285 p->removeChild(this, ec);
287 ec = HIERARCHY_REQUEST_ERR;
291 bool Node::hasChildNodes( ) const
296 void Node::normalize ()
298 ExceptionCode ec = 0;
299 Node *child = firstChild();
301 if (isElementNode()) {
302 // Normalize any attribute children we might have
303 Element *element = static_cast<Element *>(this);
304 NamedAttrMap *attrMap = element->attributes();
307 unsigned numAttrs = attrMap->length();
309 for (unsigned i = 0; i < numAttrs; i++) {
310 Attribute *attribute = attrMap->attributeItem(i);
311 Attr *attr = attribute->attr();
319 // Recursively go through the subtree beneath us, normalizing all nodes. In the case
320 // where there are two adjacent text nodes, they are merged together
322 Node *nextChild = child->nextSibling();
324 if (nextChild && child->nodeType() == TEXT_NODE && nextChild->nodeType() == TEXT_NODE) {
325 // Current child and the next one are both text nodes... merge them
326 Text *currentText = static_cast<Text*>(child);
327 Text *nextText = static_cast<Text*>(nextChild);
329 currentText->appendData(nextText->data(),ec);
333 nextChild->remove(ec);
343 // Check if we have a single empty text node left and remove it if so
344 child = firstChild();
345 if (child && !child->nextSibling() && child->isTextNode()) {
346 Text *text = static_cast<Text*>(child);
347 if (text->data().isEmpty())
352 const AtomicString& Node::prefix() const
354 // For nodes other than elements and attributes, the prefix is always null
358 void Node::setPrefix(const AtomicString& /*prefix*/, ExceptionCode& ec)
360 // The spec says that for nodes other than elements and attributes, prefix is always null.
361 // It does not say what to do when the user tries to set the prefix on another type of
362 // node, however Mozilla throws a NAMESPACE_ERR exception.
366 const AtomicString& Node::localName() const
371 const AtomicString& Node::namespaceURI() const
376 ContainerNode* Node::addChild(PassRefPtr<Node>)
381 bool Node::isContentEditable() const
383 return parent() && parent()->isContentEditable();
386 bool Node::isContentRichlyEditable() const
388 return parent() && parent()->isContentRichlyEditable();
391 bool Node::shouldUseInputMethod() const
393 return isContentEditable();
396 IntRect Node::getRect() const
399 if (renderer() && renderer()->absolutePosition(_x, _y))
400 return IntRect( _x, _y, renderer()->width(), renderer()->height() + renderer()->borderTopExtra() + renderer()->borderBottomExtra());
405 void Node::setChanged(StyleChangeType changeType)
407 if ((changeType != NoStyleChange) && !attached()) // changed compared to what?
410 if (!(changeType == InlineStyleChange && m_styleChange == FullStyleChange))
411 m_styleChange = changeType;
413 if (m_styleChange != NoStyleChange) {
414 for (Node* p = parentNode(); p; p = p->parentNode())
415 p->setHasChangedChild(true);
416 document()->setDocumentChanged(true);
420 bool Node::isFocusable() const
425 bool Node::isKeyboardFocusable(KeyboardEvent*) const
427 return isFocusable();
430 bool Node::isMouseFocusable() const
432 return isFocusable();
435 unsigned Node::nodeIndex() const
437 Node *_tempNode = previousSibling();
439 for( count=0; _tempNode; count++ )
440 _tempNode = _tempNode->previousSibling();
444 void Node::registerNodeList(NodeList* list)
447 m_nodeLists.set(new NodeListsNodeData);
448 else if (!m_document->hasNodeLists())
449 // We haven't been receiving notifications while there were no registered lists, so the cache is invalid now.
450 m_nodeLists->m_childNodeListCaches.reset();
452 if (list->needsNotifications())
453 m_nodeLists->m_listsToNotify.add(list);
454 m_document->addNodeList();
457 void Node::unregisterNodeList(NodeList* list)
460 m_document->removeNodeList();
461 if (list->needsNotifications())
462 m_nodeLists->m_listsToNotify.remove(list);
465 void Node::notifyLocalNodeListsAttributeChanged()
470 NodeListSet::iterator end = m_nodeLists->m_listsToNotify.end();
471 for (NodeListSet::iterator i = m_nodeLists->m_listsToNotify.begin(); i != end; ++i)
472 (*i)->rootNodeAttributeChanged();
475 void Node::notifyNodeListsAttributeChanged()
477 for (Node *n = this; n; n = n->parentNode())
478 n->notifyLocalNodeListsAttributeChanged();
481 void Node::notifyLocalNodeListsChildrenChanged()
486 m_nodeLists->m_childNodeListCaches.reset();
488 NodeListSet::iterator end = m_nodeLists->m_listsToNotify.end();
489 for (NodeListSet::iterator i = m_nodeLists->m_listsToNotify.begin(); i != end; ++i)
490 (*i)->rootNodeChildrenChanged();
493 void Node::notifyNodeListsChildrenChanged()
495 for (Node *n = this; n; n = n->parentNode())
496 n->notifyLocalNodeListsChildrenChanged();
499 unsigned Node::childNodeCount() const
504 Node *Node::childNode(unsigned /*index*/) const
509 Node *Node::traverseNextNode(const Node *stayWithin) const
512 ASSERT(!stayWithin || firstChild()->isDescendantOf(stayWithin));
515 if (this == stayWithin)
518 ASSERT(!stayWithin || nextSibling()->isDescendantOf(stayWithin));
519 return nextSibling();
521 const Node *n = this;
522 while (n && !n->nextSibling() && (!stayWithin || n->parentNode() != stayWithin))
525 ASSERT(!stayWithin || !n->nextSibling() || n->nextSibling()->isDescendantOf(stayWithin));
526 return n->nextSibling();
531 Node *Node::traverseNextSibling(const Node *stayWithin) const
533 if (this == stayWithin)
536 ASSERT(!stayWithin || nextSibling()->isDescendantOf(stayWithin));
537 return nextSibling();
539 const Node *n = this;
540 while (n && !n->nextSibling() && (!stayWithin || n->parentNode() != stayWithin))
543 ASSERT(!stayWithin || !n->nextSibling() || n->nextSibling()->isDescendantOf(stayWithin));
544 return n->nextSibling();
549 Node *Node::traversePreviousNode(const Node *stayWithin) const
551 if (this == stayWithin)
553 if (previousSibling()) {
554 Node *n = previousSibling();
555 while (n->lastChild())
562 Node *Node::traversePreviousNodePostOrder(const Node *stayWithin) const
565 ASSERT(!stayWithin || lastChild()->isDescendantOf(stayWithin));
568 if (this == stayWithin)
570 if (previousSibling()) {
571 ASSERT(!stayWithin || previousSibling()->isDescendantOf(stayWithin));
572 return previousSibling();
574 const Node *n = this;
575 while (n && !n->previousSibling() && (!stayWithin || n->parentNode() != stayWithin))
578 ASSERT(!stayWithin || !n->previousSibling() || n->previousSibling()->isDescendantOf(stayWithin));
579 return n->previousSibling();
584 void Node::checkSetPrefix(const AtomicString &_prefix, ExceptionCode& ec)
586 // Perform error checking as required by spec for setting Node.prefix. Used by
587 // Element::setPrefix() and Attr::setPrefix()
589 // FIXME: Implement support for INVALID_CHARACTER_ERR: Raised if the specified prefix contains an illegal character.
591 // NO_MODIFICATION_ALLOWED_ERR: Raised if this node is readonly.
592 if (isReadOnlyNode()) {
593 ec = NO_MODIFICATION_ALLOWED_ERR;
597 // FIXME: Implement NAMESPACE_ERR: - Raised if the specified prefix is malformed
598 // We have to comment this out, since it's used for attributes and tag names, and we've only
599 // switched one over.
601 // - if the namespaceURI of this node is null,
602 // - if the specified prefix is "xml" and the namespaceURI of this node is different from
603 // "http://www.w3.org/XML/1998/namespace",
604 // - if this node is an attribute and the specified prefix is "xmlns" and
605 // the namespaceURI of this node is different from "http://www.w3.org/2000/xmlns/",
606 // - or if this node is an attribute and the qualifiedName of this node is "xmlns" [Namespaces].
607 if ((namespacePart(id()) == noNamespace && id() > ID_LAST_TAG) ||
608 (_prefix == "xml" && String(document()->namespaceURI(id())) != "http://www.w3.org/XML/1998/namespace")) {
614 bool Node::canReplaceChild(Node* newChild, Node* oldChild)
616 if (newChild->nodeType() != DOCUMENT_FRAGMENT_NODE) {
617 if (!childTypeAllowed(newChild->nodeType()))
621 for (Node *n = newChild->firstChild(); n; n = n->nextSibling()) {
622 if (!childTypeAllowed(n->nodeType()))
630 void Node::checkReplaceChild(Node* newChild, Node* oldChild, ExceptionCode& ec)
632 // Perform error checking as required by spec for adding a new child. Used by
633 // appendChild(), replaceChild() and insertBefore()
635 // Not mentioned in spec: throw NOT_FOUND_ERR if newChild is null
641 // NO_MODIFICATION_ALLOWED_ERR: Raised if this node is readonly
642 if (isReadOnlyNode()) {
643 ec = NO_MODIFICATION_ALLOWED_ERR;
647 bool shouldAdoptChild = false;
649 // WRONG_DOCUMENT_ERR: Raised if newChild was created from a different document than the one that
650 // created this node.
651 // We assume that if newChild is a DocumentFragment, all children are created from the same document
652 // as the fragment itself (otherwise they could not have been added as children)
653 if (newChild->document() != document()) {
654 // but if the child is not in a document yet then loosen the
655 // restriction, so that e.g. creating an element with the Option()
656 // constructor and then adding it to a different document works,
657 // as it does in Mozilla and Mac IE.
658 if (!newChild->inDocument()) {
659 shouldAdoptChild = true;
661 ec = WRONG_DOCUMENT_ERR;
666 // HIERARCHY_REQUEST_ERR: Raised if this node is of a type that does not allow children of the type of the
667 // newChild node, or if the node to append is one of this node's ancestors.
669 // check for ancestor/same node
670 if (newChild == this || isDescendantOf(newChild)) {
671 ec = HIERARCHY_REQUEST_ERR;
675 if (!canReplaceChild(newChild, oldChild)) {
676 ec = HIERARCHY_REQUEST_ERR;
680 // change the document pointer of newChild and all of its children to be the new document
681 if (shouldAdoptChild)
682 for (Node* node = newChild; node; node = node->traverseNextNode(newChild))
683 node->setDocument(document());
686 void Node::checkAddChild(Node *newChild, ExceptionCode& ec)
688 // Perform error checking as required by spec for adding a new child. Used by
689 // appendChild(), replaceChild() and insertBefore()
691 // Not mentioned in spec: throw NOT_FOUND_ERR if newChild is null
697 // NO_MODIFICATION_ALLOWED_ERR: Raised if this node is readonly
698 if (isReadOnlyNode()) {
699 ec = NO_MODIFICATION_ALLOWED_ERR;
703 bool shouldAdoptChild = false;
705 // WRONG_DOCUMENT_ERR: Raised if newChild was created from a different document than the one that
706 // created this node.
707 // We assume that if newChild is a DocumentFragment, all children are created from the same document
708 // as the fragment itself (otherwise they could not have been added as children)
709 if (newChild->document() != document()) {
710 // but if the child is not in a document yet then loosen the
711 // restriction, so that e.g. creating an element with the Option()
712 // constructor and then adding it to a different document works,
713 // as it does in Mozilla and Mac IE.
714 if (!newChild->inDocument()) {
715 shouldAdoptChild = true;
717 ec = WRONG_DOCUMENT_ERR;
722 // HIERARCHY_REQUEST_ERR: Raised if this node is of a type that does not allow children of the type of the
723 // newChild node, or if the node to append is one of this node's ancestors.
725 // check for ancestor/same node
726 if (newChild == this || isDescendantOf(newChild)) {
727 ec = HIERARCHY_REQUEST_ERR;
731 if (newChild->nodeType() != DOCUMENT_FRAGMENT_NODE) {
732 if (!childTypeAllowed(newChild->nodeType())) {
733 ec = HIERARCHY_REQUEST_ERR;
738 for (Node *n = newChild->firstChild(); n; n = n->nextSibling()) {
739 if (!childTypeAllowed(n->nodeType())) {
740 ec = HIERARCHY_REQUEST_ERR;
746 // change the document pointer of newChild and all of its children to be the new document
747 if (shouldAdoptChild)
748 for (Node* node = newChild; node; node = node->traverseNextNode(newChild))
749 node->setDocument(document());
752 bool Node::isDescendantOf(const Node *other) const
754 // Return true if other is an ancestor of this, otherwise false
757 for (const Node *n = parentNode(); n; n = n->parentNode()) {
764 bool Node::childAllowed( Node *newChild )
766 return childTypeAllowed(newChild->nodeType());
769 Node::StyleChange Node::diff( RenderStyle *s1, RenderStyle *s2 ) const
771 // FIXME: The behavior of this function is just totally wrong. It doesn't handle
772 // explicit inheritance of non-inherited properties and so you end up not re-resolving
773 // style in cases where you need to.
774 StyleChange ch = NoInherit;
775 EDisplay display1 = s1 ? s1->display() : NONE;
776 bool fl1 = s1 && s1->hasPseudoStyle(RenderStyle::FIRST_LETTER);
777 EDisplay display2 = s2 ? s2->display() : NONE;
778 bool fl2 = s2 && s2->hasPseudoStyle(RenderStyle::FIRST_LETTER);
780 if (display1 != display2 || fl1 != fl2 || (s1 && s2 && !s1->contentDataEquivalent(s2)))
786 else if (s1->inheritedNotEqual(s2))
789 // If the pseudoStyles have changed, we want any StyleChange that is not NoChange
790 // because setStyle will do the right thing with anything else.
791 if (ch == NoChange && s1->hasPseudoStyle(RenderStyle::BEFORE)) {
792 RenderStyle* ps2 = s2->getPseudoStyle(RenderStyle::BEFORE);
796 RenderStyle* ps1 = s1->getPseudoStyle(RenderStyle::BEFORE);
797 ch = ps1 && *ps1 == *ps2 ? NoChange : NoInherit;
800 if (ch == NoChange && s1->hasPseudoStyle(RenderStyle::AFTER)) {
801 RenderStyle* ps2 = s2->getPseudoStyle(RenderStyle::AFTER);
805 RenderStyle* ps1 = s1->getPseudoStyle(RenderStyle::AFTER);
806 ch = ps2 && *ps1 == *ps2 ? NoChange : NoInherit;
814 void Node::dump(TextStream* stream, DeprecatedString ind) const
816 if (m_hasId) { *stream << " hasId"; }
817 if (m_hasClass) { *stream << " hasClass"; }
818 if (m_focused) { *stream << " focused"; }
819 if (m_active) { *stream << " active"; }
821 *stream << " tabIndex=" << m_tabIndex;
824 for (Node* child = firstChild(); child; child = child->nextSibling()) {
825 *stream << ind << child->nodeName() << ": ";
826 child->dump(stream, ind + " ");
834 ASSERT(!renderer() || (renderer()->style() && renderer()->parent()));
835 document()->incDOMTreeVersion();
839 void Node::willRemove()
848 renderer()->destroy();
851 Document* doc = document();
853 doc->hoveredNodeDetached(this);
855 doc->activeChainNodeDetached(this);
856 doc->incDOMTreeVersion();
860 m_inActiveChain = false;
865 void Node::insertedIntoDocument()
868 insertedIntoTree(false);
871 void Node::removedFromDocument()
873 setInDocument(false);
874 removedFromTree(false);
877 void Node::childrenChanged()
881 bool Node::isReadOnlyNode()
883 // Entity & Entity Reference nodes and their descendants are read-only
886 if (n->nodeType() == ENTITY_NODE || n->nodeType() == ENTITY_REFERENCE_NODE)
893 Node *Node::previousEditable() const
895 Node *node = previousLeafNode();
897 if (node->isContentEditable())
899 node = node->previousLeafNode();
904 // Offset specifies the child node to start at. If it is past
905 // the last child, it specifies to start at next sibling.
906 Node *Node::nextEditable(int offset) const
911 node = (offset >= (int)childNodeCount()) ? nextSibling() : childNode(offset)->nextLeafNode();
913 node = nextLeafNode();
915 if (node->isContentEditable())
917 node = node->nextLeafNode();
922 Node *Node::nextEditable() const
924 Node *node = nextLeafNode();
926 if (node->isContentEditable())
928 node = node->nextLeafNode();
933 RenderObject * Node::previousRenderer()
935 for (Node *n = previousSibling(); n; n = n->previousSibling()) {
937 return n->renderer();
942 RenderObject * Node::nextRenderer()
944 // Avoid an O(n^2) problem with this function by not checking for nextRenderer() when the parent element hasn't even
945 // been attached yet.
946 if (parent() && !parent()->attached())
949 for (Node *n = nextSibling(); n; n = n->nextSibling()) {
951 return n->renderer();
956 // FIXME: This code is used by editing. Seems like it could move over there and not pollute Node.
957 Node *Node::previousNodeConsideringAtomicNodes() const
959 if (previousSibling()) {
960 Node *n = previousSibling();
961 while (!isAtomicNode(n) && n->lastChild())
965 else if (parentNode()) {
973 Node *Node::nextNodeConsideringAtomicNodes() const
975 if (!isAtomicNode(this) && firstChild())
978 return nextSibling();
979 const Node *n = this;
980 while (n && !n->nextSibling())
983 return n->nextSibling();
987 Node *Node::previousLeafNode() const
989 Node *node = previousNodeConsideringAtomicNodes();
991 if (isAtomicNode(node))
993 node = node->previousNodeConsideringAtomicNodes();
998 Node *Node::nextLeafNode() const
1000 Node *node = nextNodeConsideringAtomicNodes();
1002 if (isAtomicNode(node))
1004 node = node->nextNodeConsideringAtomicNodes();
1009 void Node::createRendererIfNeeded()
1011 if (!document()->shouldCreateRenderers())
1014 ASSERT(!attached());
1015 ASSERT(!renderer());
1017 Node *parent = parentNode();
1020 RenderObject *parentRenderer = parent->renderer();
1021 if (parentRenderer && parentRenderer->canHaveChildren()
1023 && parent->childShouldCreateRenderer(this)
1026 RenderStyle* style = styleForRenderer(parentRenderer);
1027 if (rendererIsNeeded(style)) {
1028 if (RenderObject* r = createRenderer(document()->renderArena(), style)) {
1029 if (!parentRenderer->isChildAllowed(r, style))
1033 renderer()->setAnimatableStyle(style);
1034 parentRenderer->addChild(renderer(), nextRenderer());
1038 style->deref(document()->renderArena());
1042 RenderStyle *Node::styleForRenderer(RenderObject *parent)
1044 RenderStyle *style = parent->style();
1049 bool Node::rendererIsNeeded(RenderStyle *style)
1051 return (document()->documentElement() == this) || (style->display() != NONE);
1054 RenderObject *Node::createRenderer(RenderArena *arena, RenderStyle *style)
1060 RenderStyle* Node::renderStyle() const
1062 return m_renderer ? m_renderer->style() : 0;
1065 void Node::setRenderStyle(RenderStyle* s)
1068 m_renderer->setAnimatableStyle(s);
1071 RenderStyle* Node::computedStyle()
1073 return parent() ? parent()->computedStyle() : 0;
1076 int Node::maxCharacterOffset() const
1078 ASSERT_NOT_REACHED();
1082 // FIXME: Shouldn't these functions be in the editing code? Code that asks questions about HTML in the core DOM class
1083 // is obviously misplaced.
1084 bool Node::canStartSelection() const
1086 if (isContentEditable())
1088 return parent() ? parent()->canStartSelection() : true;
1091 Node* Node::shadowAncestorNode()
1094 // SVG elements living in a shadow tree only occour when <use> created them.
1095 // For these cases we do NOT want to return the shadowParentNode() here
1096 // but the actual shadow tree element - as main difference to the HTML forms
1097 // shadow tree concept. (This function _could_ be made virtual - opinions?)
1104 if (n->isShadowNode())
1105 return n->shadowParentNode();
1106 n = n->parentNode();
1111 bool Node::isBlockFlow() const
1113 return renderer() && renderer()->isBlockFlow();
1116 bool Node::isBlockFlowOrBlockTable() const
1118 return renderer() && (renderer()->isBlockFlow() || renderer()->isTable() && !renderer()->isInline());
1121 bool Node::isEditableBlock() const
1123 return isContentEditable() && isBlockFlow();
1126 Element *Node::enclosingBlockFlowOrTableElement() const
1128 Node *n = const_cast<Node *>(this);
1129 if (isBlockFlowOrBlockTable())
1130 return static_cast<Element *>(n);
1133 n = n->parentNode();
1136 if (n->isBlockFlowOrBlockTable() || n->hasTagName(bodyTag))
1137 return static_cast<Element *>(n);
1142 Element *Node::enclosingBlockFlowElement() const
1144 Node *n = const_cast<Node *>(this);
1146 return static_cast<Element *>(n);
1149 n = n->parentNode();
1152 if (n->isBlockFlow() || n->hasTagName(bodyTag))
1153 return static_cast<Element *>(n);
1158 Element *Node::enclosingInlineElement() const
1160 Node *n = const_cast<Node *>(this);
1164 p = n->parentNode();
1165 if (!p || p->isBlockFlow() || p->hasTagName(bodyTag))
1166 return static_cast<Element *>(n);
1167 // Also stop if any previous sibling is a block
1168 for (Node *sibling = n->previousSibling(); sibling; sibling = sibling->previousSibling()) {
1169 if (sibling->isBlockFlow())
1170 return static_cast<Element *>(n);
1174 ASSERT_NOT_REACHED();
1178 Element* Node::rootEditableElement() const
1180 Element* result = 0;
1181 for (Node* n = const_cast<Node*>(this); n && n->isContentEditable(); n = n->parentNode()) {
1182 if (n->isElementNode())
1183 result = static_cast<Element*>(n);
1184 if (n->hasTagName(bodyTag))
1190 bool Node::inSameContainingBlockFlowElement(Node *n)
1192 return n ? enclosingBlockFlowElement() == n->enclosingBlockFlowElement() : false;
1195 // FIXME: End of obviously misplaced HTML editing functions. Try to move these out of Node.
1197 PassRefPtr<NodeList> Node::getElementsByTagName(const String& name)
1199 return getElementsByTagNameNS("*", name);
1202 PassRefPtr<NodeList> Node::getElementsByTagNameNS(const String& namespaceURI, const String& localName)
1204 if (localName.isNull())
1207 String name = localName;
1208 if (document()->isHTMLDocument())
1209 name = localName.lower();
1210 return new TagNodeList(this, namespaceURI.isEmpty() ? nullAtom : AtomicString(namespaceURI), name);
1213 PassRefPtr<NodeList> Node::getElementsByName(const String& elementName)
1216 m_nodeLists.set(new NodeListsNodeData);
1218 return new NameNodeList(this, elementName, &m_nodeLists->m_nameNodeListCaches.add(elementName, NodeList::Caches()).first->second);
1221 PassRefPtr<NodeList> Node::getElementsByClassName(const String& classNames)
1224 m_nodeLists.set(new NodeListsNodeData);
1226 return new ClassNodeList(this, classNames, &m_nodeLists->m_classNodeListCaches.add(classNames, NodeList::Caches()).first->second);
1229 Document *Node::ownerDocument() const
1231 Document *doc = document();
1232 return doc == this ? 0 : doc;
1235 bool Node::hasAttributes() const
1240 NamedAttrMap *Node::attributes() const
1245 String Node::baseURI() const
1247 Node* parent = parentNode();
1249 return parent->baseURI();
1254 bool Node::isEqualNode(Node *other) const
1259 if (nodeType() != other->nodeType())
1262 if (nodeName() != other->nodeName())
1265 if (localName() != other->localName())
1268 if (namespaceURI() != other->namespaceURI())
1271 if (prefix() != other->prefix())
1274 if (nodeValue() != other->nodeValue())
1277 NamedAttrMap *attrs = attributes();
1278 NamedAttrMap *otherAttrs = other->attributes();
1280 if (!attrs && otherAttrs)
1283 if (attrs && !attrs->mapsEquivalent(otherAttrs))
1286 Node *child = firstChild();
1287 Node *otherChild = other->firstChild();
1290 if (!child->isEqualNode(otherChild))
1293 child = child->nextSibling();
1294 otherChild = otherChild->nextSibling();
1300 // FIXME: For DocumentType nodes we should check equality on
1301 // the entities and notations NamedNodeMaps as well.
1306 bool Node::isDefaultNamespace(const String &namespaceURI) const
1308 // Implemented according to
1309 // http://www.w3.org/TR/2004/REC-DOM-Level-3-Core-20040407/namespaces-algorithms.html#isDefaultNamespaceAlgo
1311 switch (nodeType()) {
1312 case ELEMENT_NODE: {
1313 const Element *elem = static_cast<const Element *>(this);
1315 if (elem->prefix().isNull())
1316 return elem->namespaceURI() == namespaceURI;
1318 if (elem->hasAttributes()) {
1319 NamedAttrMap *attrs = elem->attributes();
1321 for (unsigned i = 0; i < attrs->length(); i++) {
1322 Attribute *attr = attrs->attributeItem(i);
1324 if (attr->localName() == "xmlns")
1325 return attr->value() == namespaceURI;
1329 if (Element* ancestor = ancestorElement())
1330 return ancestor->isDefaultNamespace(namespaceURI);
1335 return static_cast <const Document *>(this)->documentElement()->isDefaultNamespace(namespaceURI);
1338 case DOCUMENT_TYPE_NODE:
1339 case DOCUMENT_FRAGMENT_NODE:
1341 case ATTRIBUTE_NODE: {
1342 const Attr *attr = static_cast<const Attr *>(this);
1343 if (attr->ownerElement())
1344 return attr->ownerElement()->isDefaultNamespace(namespaceURI);
1348 if (Element* ancestor = ancestorElement())
1349 return ancestor->isDefaultNamespace(namespaceURI);
1354 String Node::lookupPrefix(const String &namespaceURI) const
1356 // Implemented according to
1357 // http://www.w3.org/TR/2004/REC-DOM-Level-3-Core-20040407/namespaces-algorithms.html#lookupNamespacePrefixAlgo
1359 if (namespaceURI.isEmpty())
1362 switch (nodeType()) {
1364 return lookupNamespacePrefix(namespaceURI, static_cast<const Element *>(this));
1366 return static_cast<const Document *>(this)->documentElement()->lookupPrefix(namespaceURI);
1369 case DOCUMENT_FRAGMENT_NODE:
1370 case DOCUMENT_TYPE_NODE:
1372 case ATTRIBUTE_NODE: {
1373 const Attr *attr = static_cast<const Attr *>(this);
1374 if (attr->ownerElement())
1375 return attr->ownerElement()->lookupPrefix(namespaceURI);
1379 if (Element* ancestor = ancestorElement())
1380 return ancestor->lookupPrefix(namespaceURI);
1385 String Node::lookupNamespaceURI(const String &prefix) const
1387 // Implemented according to
1388 // http://www.w3.org/TR/2004/REC-DOM-Level-3-Core-20040407/namespaces-algorithms.html#lookupNamespaceURIAlgo
1390 if (!prefix.isNull() && prefix.isEmpty())
1393 switch (nodeType()) {
1394 case ELEMENT_NODE: {
1395 const Element *elem = static_cast<const Element *>(this);
1397 if (!elem->namespaceURI().isNull() && elem->prefix() == prefix)
1398 return elem->namespaceURI();
1400 if (elem->hasAttributes()) {
1401 NamedAttrMap *attrs = elem->attributes();
1403 for (unsigned i = 0; i < attrs->length(); i++) {
1404 Attribute *attr = attrs->attributeItem(i);
1406 if (attr->prefix() == "xmlns" && attr->localName() == prefix) {
1407 if (!attr->value().isEmpty())
1408 return attr->value();
1411 } else if (attr->localName() == "xmlns" && prefix.isNull()) {
1412 if (!attr->value().isEmpty())
1413 return attr->value();
1419 if (Element* ancestor = ancestorElement())
1420 return ancestor->lookupNamespaceURI(prefix);
1424 return static_cast<const Document *>(this)->documentElement()->lookupNamespaceURI(prefix);
1427 case DOCUMENT_TYPE_NODE:
1428 case DOCUMENT_FRAGMENT_NODE:
1430 case ATTRIBUTE_NODE: {
1431 const Attr *attr = static_cast<const Attr *>(this);
1433 if (attr->ownerElement())
1434 return attr->ownerElement()->lookupNamespaceURI(prefix);
1439 if (Element* ancestor = ancestorElement())
1440 return ancestor->lookupNamespaceURI(prefix);
1445 String Node::lookupNamespacePrefix(const String &_namespaceURI, const Element *originalElement) const
1447 if (_namespaceURI.isNull())
1450 if (originalElement->lookupNamespaceURI(prefix()) == _namespaceURI)
1453 if (hasAttributes()) {
1454 NamedAttrMap *attrs = attributes();
1456 for (unsigned i = 0; i < attrs->length(); i++) {
1457 Attribute *attr = attrs->attributeItem(i);
1459 if (attr->prefix() == "xmlns" &&
1460 attr->value() == _namespaceURI &&
1461 originalElement->lookupNamespaceURI(attr->localName()) == _namespaceURI)
1462 return attr->localName();
1466 if (Element* ancestor = ancestorElement())
1467 return ancestor->lookupNamespacePrefix(_namespaceURI, originalElement);
1471 String Node::textContent(bool convertBRsToNewlines) const
1473 switch (nodeType()) {
1475 case CDATA_SECTION_NODE:
1477 case PROCESSING_INSTRUCTION_NODE:
1481 if (hasTagName(brTag) &&
1482 convertBRsToNewlines)
1484 case ATTRIBUTE_NODE:
1486 case ENTITY_REFERENCE_NODE:
1487 case DOCUMENT_FRAGMENT_NODE: {
1490 for (Node *child = firstChild(); child; child = child->nextSibling()) {
1491 if (child->nodeType() == COMMENT_NODE || child->nodeType() == PROCESSING_INSTRUCTION_NODE)
1494 s += child->textContent(convertBRsToNewlines);
1501 case DOCUMENT_TYPE_NODE:
1508 void Node::setTextContent(const String &text, ExceptionCode& ec)
1510 switch (nodeType()) {
1512 case CDATA_SECTION_NODE:
1514 case PROCESSING_INSTRUCTION_NODE:
1515 setNodeValue(text, ec);
1518 case ATTRIBUTE_NODE:
1520 case ENTITY_REFERENCE_NODE:
1521 case DOCUMENT_FRAGMENT_NODE: {
1522 ContainerNode *container = static_cast<ContainerNode *>(this);
1524 container->removeChildren();
1526 if (!text.isEmpty())
1527 appendChild(document()->createTextNode(text), ec);
1531 case DOCUMENT_TYPE_NODE:
1539 Element* Node::ancestorElement() const
1541 // In theory, there can be EntityReference nodes between elements, but this is currently not supported.
1542 for (Node* n = parentNode(); n; n = n->parentNode()) {
1543 if (n->isElementNode())
1544 return static_cast<Element*>(n);
1549 bool Node::offsetInCharacters() const
1556 static void appendAttributeDesc(const Node* node, String& string, const QualifiedName& name, const char* attrDesc)
1558 if (node->isElementNode()) {
1559 String attr = static_cast<const Element*>(node)->getAttribute(name);
1560 if (!attr.isEmpty()) {
1567 void Node::showNode(const char* prefix) const
1572 String value = nodeValue();
1573 value.replace('\\', "\\\\");
1574 value.replace('\n', "\\n");
1575 fprintf(stderr, "%s%s\t%p \"%s\"\n", prefix, nodeName().utf8().data(), this, value.utf8().data());
1578 appendAttributeDesc(this, attrs, classAttr, " CLASS=");
1579 appendAttributeDesc(this, attrs, styleAttr, " STYLE=");
1580 fprintf(stderr, "%s%s\t%p%s\n", prefix, nodeName().utf8().data(), this, attrs.utf8().data());
1584 void Node::showTreeForThis() const
1586 showTreeAndMark(this, "*");
1589 void Node::showTreeAndMark(const Node* markedNode1, const char* markedLabel1, const Node* markedNode2, const char * markedLabel2) const
1591 const Node* rootNode;
1592 const Node* node = this;
1593 while (node->parentNode() && !node->hasTagName(bodyTag))
1594 node = node->parentNode();
1597 for (node = rootNode; node; node = node->traverseNextNode()) {
1598 if (node == markedNode1)
1599 fprintf(stderr, "%s", markedLabel1);
1600 if (node == markedNode2)
1601 fprintf(stderr, "%s", markedLabel2);
1603 for (const Node* tmpNode = node; tmpNode && tmpNode != rootNode; tmpNode = tmpNode->parentNode())
1604 fprintf(stderr, "\t");
1609 void Node::formatForDebugger(char* buffer, unsigned length) const
1615 if (s.length() == 0)
1620 strncpy(buffer, result.utf8().data(), length - 1);
1629 void showTree(const WebCore::Node* node)
1632 node->showTreeForThis();