Bug 454821. Better signature for GetChildArray. r+sr=sicking
[mozilla-central.git] / content / base / src / nsGenericElement.cpp
blob3f43bf8eb860d7c1d7d4c9df72e3767453b77aa3
1 /* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
2 /* ***** BEGIN LICENSE BLOCK *****
3 * Version: MPL 1.1/GPL 2.0/LGPL 2.1
5 * The contents of this file are subject to the Mozilla Public License Version
6 * 1.1 (the "License"); you may not use this file except in compliance with
7 * the License. You may obtain a copy of the License at
8 * http://www.mozilla.org/MPL/
10 * Software distributed under the License is distributed on an "AS IS" basis,
11 * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
12 * for the specific language governing rights and limitations under the
13 * License.
15 * The Original Code is Mozilla Communicator client code.
17 * The Initial Developer of the Original Code is
18 * Netscape Communications Corporation.
19 * Portions created by the Initial Developer are Copyright (C) 1998
20 * the Initial Developer. All Rights Reserved.
22 * Contributor(s):
24 * Alternatively, the contents of this file may be used under the terms of
25 * either of the GNU General Public License Version 2 or later (the "GPL"),
26 * or the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
27 * in which case the provisions of the GPL or the LGPL are applicable instead
28 * of those above. If you wish to allow use of your version of this file only
29 * under the terms of either the GPL or the LGPL, and not to allow others to
30 * use your version of this file under the terms of the MPL, indicate your
31 * decision by deleting the provisions above and replace them with the notice
32 * and other provisions required by the GPL or the LGPL. If you do not delete
33 * the provisions above, a recipient may use your version of this file under
34 * the terms of any one of the MPL, the GPL or the LGPL.
36 * ***** END LICENSE BLOCK ***** */
39 * Base class for all element classes; this provides an implementation
40 * of DOM Core's nsIDOMElement, implements nsIContent, provides
41 * utility methods for subclasses, and so forth.
44 #include "nsGenericElement.h"
46 #include "nsDOMAttribute.h"
47 #include "nsDOMAttributeMap.h"
48 #include "nsIAtom.h"
49 #include "nsINodeInfo.h"
50 #include "nsIDocument.h"
51 #include "nsIDOMNodeList.h"
52 #include "nsIDOMDocument.h"
53 #include "nsIDOMText.h"
54 #include "nsIContentIterator.h"
55 #include "nsIEventListenerManager.h"
56 #include "nsIFocusController.h"
57 #include "nsILinkHandler.h"
58 #include "nsIScriptGlobalObject.h"
59 #include "nsIURL.h"
60 #include "nsNetUtil.h"
61 #include "nsIFrame.h"
62 #include "nsIPresShell.h"
63 #include "nsPresContext.h"
64 #include "nsStyleConsts.h"
65 #include "nsString.h"
66 #include "nsUnicharUtils.h"
67 #include "nsIEventStateManager.h"
68 #include "nsIDOMEvent.h"
69 #include "nsIPrivateDOMEvent.h"
70 #include "nsDOMCID.h"
71 #include "nsIServiceManager.h"
72 #include "nsIDOMCSSStyleDeclaration.h"
73 #include "nsDOMCSSDeclaration.h"
74 #include "nsINameSpaceManager.h"
75 #include "nsContentList.h"
76 #include "nsDOMError.h"
77 #include "nsDOMString.h"
78 #include "nsIScriptSecurityManager.h"
79 #include "nsIDOMMutationEvent.h"
80 #include "nsMutationEvent.h"
81 #include "nsNodeUtils.h"
82 #include "nsDocument.h"
83 #ifdef MOZ_XUL
84 #include "nsXULElement.h"
85 #endif /* MOZ_XUL */
86 #include "nsFrameManager.h"
87 #include "nsFrameSelection.h"
89 #include "nsBindingManager.h"
90 #include "nsXBLBinding.h"
91 #include "nsIDOMCSSStyleDeclaration.h"
92 #include "nsIDOMViewCSS.h"
93 #include "nsIXBLService.h"
94 #include "nsPIDOMWindow.h"
95 #include "nsIBoxObject.h"
96 #include "nsPIBoxObject.h"
97 #include "nsIDOMNSDocument.h"
98 #include "nsIDOMNSElement.h"
99 #include "nsClientRect.h"
100 #ifdef MOZ_SVG
101 #include "nsSVGUtils.h"
102 #endif
103 #include "nsLayoutUtils.h"
104 #include "nsGkAtoms.h"
105 #include "nsContentUtils.h"
106 #include "nsIJSContextStack.h"
108 #include "nsIServiceManager.h"
109 #include "nsIDOMEventListener.h"
111 #include "nsIWebNavigation.h"
112 #include "nsIBaseWindow.h"
114 #include "jsapi.h"
116 #include "nsNodeInfoManager.h"
117 #include "nsICategoryManager.h"
118 #include "nsIDOMNSFeatureFactory.h"
119 #include "nsIDOMDocumentType.h"
120 #include "nsIDOMUserDataHandler.h"
121 #include "nsIDOMNSEditableElement.h"
122 #include "nsIEditor.h"
123 #include "nsIEditorDocShell.h"
124 #include "nsEventDispatcher.h"
125 #include "nsContentCreatorFunctions.h"
126 #include "nsIFocusController.h"
127 #include "nsIControllers.h"
128 #include "nsLayoutUtils.h"
129 #include "nsIView.h"
130 #include "nsIViewManager.h"
131 #include "nsIScrollableFrame.h"
132 #include "nsIScrollableView.h"
133 #include "nsIScrollableViewProvider.h"
134 #include "nsXBLInsertionPoint.h"
135 #include "nsICSSStyleRule.h" /* For nsCSSSelectorList */
136 #include "nsCSSRuleProcessor.h"
138 #ifdef MOZ_XUL
139 #include "nsIXULDocument.h"
140 #endif /* MOZ_XUL */
142 #ifdef ACCESSIBILITY
143 #include "nsIAccessibilityService.h"
144 #include "nsIAccessibleEvent.h"
145 #endif /* ACCESSIBILITY */
147 #include "nsCycleCollectionParticipant.h"
148 #include "nsCCUncollectableMarker.h"
150 #include "mozAutoDocUpdate.h"
152 #include "nsICSSParser.h"
154 #ifdef MOZ_SVG
155 PRBool NS_SVG_HaveFeature(const nsAString &aFeature);
156 #endif /* MOZ_SVG */
158 #ifdef DEBUG_waterson
161 * List a content tree to stdout. Meant to be called from gdb.
163 void
164 DebugListContentTree(nsIContent* aElement)
166 aElement->List(stdout, 0);
167 printf("\n");
170 #endif
172 NS_DEFINE_IID(kThisPtrOffsetsSID, NS_THISPTROFFSETS_SID);
174 PRInt32 nsIContent::sTabFocusModel = eTabFocus_any;
175 PRBool nsIContent::sTabFocusModelAppliesToXUL = PR_FALSE;
176 nsresult NS_NewContentIterator(nsIContentIterator** aInstancePtrResult);
178 //----------------------------------------------------------------------
180 nsINode::nsSlots::~nsSlots()
182 if (mChildNodes) {
183 mChildNodes->DropReference();
184 NS_RELEASE(mChildNodes);
187 if (mWeakReference) {
188 mWeakReference->NoticeNodeDestruction();
192 //----------------------------------------------------------------------
194 nsINode::~nsINode()
196 NS_ASSERTION(!HasSlots(), "nsNodeUtils::LastRelease was not called?");
199 void*
200 nsINode::GetProperty(PRUint16 aCategory, nsIAtom *aPropertyName,
201 nsresult *aStatus) const
203 nsIDocument *doc = GetOwnerDoc();
204 if (!doc)
205 return nsnull;
207 return doc->PropertyTable()->GetProperty(this, aCategory, aPropertyName,
208 aStatus);
211 nsresult
212 nsINode::SetProperty(PRUint16 aCategory, nsIAtom *aPropertyName, void *aValue,
213 NSPropertyDtorFunc aDtor, PRBool aTransfer,
214 void **aOldValue)
216 nsIDocument *doc = GetOwnerDoc();
217 if (!doc)
218 return NS_ERROR_FAILURE;
220 nsresult rv = doc->PropertyTable()->SetProperty(this, aCategory,
221 aPropertyName, aValue, aDtor,
222 nsnull, aTransfer, aOldValue);
223 if (NS_SUCCEEDED(rv)) {
224 SetFlags(NODE_HAS_PROPERTIES);
227 return rv;
230 nsresult
231 nsINode::DeleteProperty(PRUint16 aCategory, nsIAtom *aPropertyName)
233 nsIDocument *doc = GetOwnerDoc();
234 if (!doc)
235 return nsnull;
237 return doc->PropertyTable()->DeleteProperty(this, aCategory, aPropertyName);
240 void*
241 nsINode::UnsetProperty(PRUint16 aCategory, nsIAtom *aPropertyName,
242 nsresult *aStatus)
244 nsIDocument *doc = GetOwnerDoc();
245 if (!doc)
246 return nsnull;
248 return doc->PropertyTable()->UnsetProperty(this, aCategory, aPropertyName,
249 aStatus);
252 nsresult
253 nsGenericElement::GetListenerManager(PRBool aCreateIfNotFound,
254 nsIEventListenerManager** aResult)
256 return nsContentUtils::GetListenerManager(this, aCreateIfNotFound, aResult);
259 nsresult
260 nsGenericElement::AddEventListenerByIID(nsIDOMEventListener *aListener,
261 const nsIID& aIID)
263 nsCOMPtr<nsIEventListenerManager> elm;
264 nsresult rv = GetListenerManager(PR_TRUE, getter_AddRefs(elm));
265 if (elm) {
266 return elm->AddEventListenerByIID(aListener, aIID, NS_EVENT_FLAG_BUBBLE);
268 return rv;
271 nsresult
272 nsGenericElement::RemoveEventListenerByIID(nsIDOMEventListener *aListener,
273 const nsIID& aIID)
275 nsCOMPtr<nsIEventListenerManager> elm;
276 GetListenerManager(PR_FALSE, getter_AddRefs(elm));
277 if (elm) {
278 return elm->RemoveEventListenerByIID(aListener, aIID, NS_EVENT_FLAG_BUBBLE);
280 return NS_OK;
283 nsresult
284 nsGenericElement::GetSystemEventGroup(nsIDOMEventGroup** aGroup)
286 nsCOMPtr<nsIEventListenerManager> elm;
287 nsresult rv = GetListenerManager(PR_TRUE, getter_AddRefs(elm));
288 if (elm) {
289 return elm->GetSystemEventGroupLM(aGroup);
291 return rv;
294 nsINode::nsSlots*
295 nsINode::CreateSlots()
297 return new nsSlots(mFlagsOrSlots);
300 void
301 nsINode::AddMutationObserver(nsIMutationObserver* aMutationObserver)
303 nsSlots* slots = GetSlots();
304 if (slots) {
305 slots->mMutationObservers.AppendElementUnlessExists(aMutationObserver);
309 void
310 nsINode::RemoveMutationObserver(nsIMutationObserver* aMutationObserver)
312 nsSlots* slots = GetExistingSlots();
313 if (slots) {
314 slots->mMutationObservers.RemoveElement(aMutationObserver);
318 PRBool
319 nsINode::IsEditableInternal() const
321 if (HasFlag(NODE_IS_EDITABLE)) {
322 // The node is in an editable contentEditable subtree.
323 return PR_TRUE;
326 nsIDocument *doc = GetCurrentDoc();
328 // Check if the node is in a document and the document is in designMode.
329 return doc && doc->HasFlag(NODE_IS_EDITABLE);
332 static nsIContent* GetEditorRootContent(nsIEditor* aEditor)
334 nsCOMPtr<nsIDOMElement> rootElement;
335 aEditor->GetRootElement(getter_AddRefs(rootElement));
336 nsCOMPtr<nsIContent> rootContent(do_QueryInterface(rootElement));
337 return rootContent;
340 nsIContent*
341 nsINode::GetTextEditorRootContent(nsIEditor** aEditor)
343 if (aEditor)
344 *aEditor = nsnull;
345 for (nsINode* node = this; node; node = node->GetNodeParent()) {
346 nsCOMPtr<nsIDOMNSEditableElement> editableElement(do_QueryInterface(node));
347 if (!editableElement)
348 continue;
350 nsCOMPtr<nsIEditor> editor;
351 editableElement->GetEditor(getter_AddRefs(editor));
352 NS_ENSURE_TRUE(editor, nsnull);
353 nsIContent* rootContent = GetEditorRootContent(editor);
354 if (aEditor)
355 editor.swap(*aEditor);
356 return rootContent;
358 return nsnull;
361 static nsIEditor* GetHTMLEditor(nsPresContext* aPresContext)
363 nsCOMPtr<nsISupports> container = aPresContext->GetContainer();
364 nsCOMPtr<nsIEditorDocShell> editorDocShell(do_QueryInterface(container));
365 PRBool isEditable;
366 if (!editorDocShell ||
367 NS_FAILED(editorDocShell->GetEditable(&isEditable)) || !isEditable)
368 return nsnull;
370 nsCOMPtr<nsIEditor> editor;
371 editorDocShell->GetEditor(getter_AddRefs(editor));
372 return editor;
375 nsIContent*
376 nsINode::GetSelectionRootContent(nsIPresShell* aPresShell)
378 NS_ENSURE_TRUE(aPresShell, nsnull);
380 if (IsNodeOfType(eDOCUMENT))
381 return static_cast<nsIDocument*>(this)->GetRootContent();
382 if (!IsNodeOfType(eCONTENT))
383 return nsnull;
385 nsIFrame* frame =
386 aPresShell->GetPrimaryFrameFor(static_cast<nsIContent*>(this));
387 if (frame && frame->GetStateBits() & NS_FRAME_INDEPENDENT_SELECTION) {
388 // This node should be a descendant of input/textarea editor.
389 nsIContent* content = GetTextEditorRootContent();
390 if (content)
391 return content;
392 NS_ERROR("Editor is not found!");
395 nsPresContext* presContext = aPresShell->GetPresContext();
396 if (presContext) {
397 nsIEditor* editor = GetHTMLEditor(presContext);
398 if (editor) {
399 // This node is in HTML editor.
400 nsIDocument* doc = GetCurrentDoc();
401 if (!doc || doc->HasFlag(NODE_IS_EDITABLE) || !HasFlag(NODE_IS_EDITABLE))
402 return GetEditorRootContent(editor);
403 // If the current document is not editable, but current content is
404 // editable, we should assume that the child of the nearest non-editable
405 // ancestor is selection root.
406 nsIContent* content = static_cast<nsIContent*>(this);
407 for (nsIContent* parent = GetParent();
408 parent && parent->HasFlag(NODE_IS_EDITABLE);
409 parent = content->GetParent())
410 content = parent;
411 return content;
415 nsCOMPtr<nsFrameSelection> fs = aPresShell->FrameSelection();
416 nsIContent* content = fs->GetLimiter();
417 if (content)
418 return content;
419 content = fs->GetAncestorLimiter();
420 if (content)
421 return content;
422 nsIDocument* doc = aPresShell->GetDocument();
423 NS_ENSURE_TRUE(doc, nsnull);
424 return doc->GetRootContent();
427 //----------------------------------------------------------------------
429 PRInt32
430 nsIContent::IntrinsicState() const
432 return IsEditable() ? NS_EVENT_STATE_MOZ_READWRITE :
433 NS_EVENT_STATE_MOZ_READONLY;
436 void
437 nsIContent::UpdateEditableState()
439 nsIContent *parent = GetParent();
441 SetEditableFlag(parent && parent->HasFlag(NODE_IS_EDITABLE));
444 nsIContent*
445 nsIContent::FindFirstNonNativeAnonymous() const
447 // This handles also nested native anonymous content.
448 for (const nsIContent *content = this; content;
449 content = content->GetBindingParent()) {
450 if (!content->IsInNativeAnonymousSubtree()) {
451 // Oops, this function signature allows casting const to
452 // non-const. (Then again, so does GetChildAt(0)->GetParent().)
453 return const_cast<nsIContent*>(content);
456 return nsnull;
459 //----------------------------------------------------------------------
461 NS_IMPL_ADDREF(nsChildContentList)
462 NS_IMPL_RELEASE(nsChildContentList)
464 NS_INTERFACE_TABLE_HEAD(nsChildContentList)
465 NS_WRAPPERCACHE_INTERFACE_MAP_ENTRY
466 NS_NODELIST_OFFSET_AND_INTERFACE_TABLE_BEGIN(nsChildContentList)
467 NS_INTERFACE_TABLE_ENTRY(nsChildContentList, nsINodeList)
468 NS_INTERFACE_TABLE_ENTRY(nsChildContentList, nsIDOMNodeList)
469 NS_OFFSET_AND_INTERFACE_TABLE_END
470 NS_OFFSET_AND_INTERFACE_TABLE_TO_MAP_SEGUE
471 NS_INTERFACE_MAP_ENTRY_CONTENT_CLASSINFO(NodeList)
472 NS_INTERFACE_MAP_END
474 NS_IMETHODIMP
475 nsChildContentList::GetLength(PRUint32* aLength)
477 *aLength = mNode ? mNode->GetChildCount() : 0;
479 return NS_OK;
482 NS_IMETHODIMP
483 nsChildContentList::Item(PRUint32 aIndex, nsIDOMNode** aReturn)
485 nsINode* node = GetNodeAt(aIndex);
486 if (!node) {
487 *aReturn = nsnull;
489 return NS_OK;
492 return CallQueryInterface(node, aReturn);
495 nsINode*
496 nsChildContentList::GetNodeAt(PRUint32 aIndex)
498 if (mNode) {
499 return mNode->GetChildAt(aIndex);
502 return nsnull;
505 //----------------------------------------------------------------------
507 NS_IMPL_CYCLE_COLLECTION_1(nsNode3Tearoff, mContent)
509 NS_INTERFACE_MAP_BEGIN_CYCLE_COLLECTION(nsNode3Tearoff)
510 NS_INTERFACE_MAP_ENTRY(nsIDOM3Node)
511 NS_INTERFACE_MAP_END_AGGREGATED(mContent)
513 NS_IMPL_CYCLE_COLLECTING_ADDREF(nsNode3Tearoff)
514 NS_IMPL_CYCLE_COLLECTING_RELEASE(nsNode3Tearoff)
516 NS_IMETHODIMP
517 nsNode3Tearoff::GetBaseURI(nsAString& aURI)
519 nsCOMPtr<nsIURI> baseURI = mContent->GetBaseURI();
520 nsCAutoString spec;
522 if (baseURI) {
523 baseURI->GetSpec(spec);
526 CopyUTF8toUTF16(spec, aURI);
528 return NS_OK;
531 NS_IMETHODIMP
532 nsNode3Tearoff::GetTextContent(nsAString &aTextContent)
534 nsCOMPtr<nsIDOMNode> node(do_QueryInterface(mContent));
535 NS_ASSERTION(node, "We have an nsIContent which doesn't support nsIDOMNode");
537 PRUint16 nodeType;
538 node->GetNodeType(&nodeType);
539 if (nodeType == nsIDOMNode::DOCUMENT_TYPE_NODE ||
540 nodeType == nsIDOMNode::NOTATION_NODE) {
541 SetDOMStringToNull(aTextContent);
543 return NS_OK;
546 if (nodeType == nsIDOMNode::TEXT_NODE ||
547 nodeType == nsIDOMNode::CDATA_SECTION_NODE ||
548 nodeType == nsIDOMNode::COMMENT_NODE ||
549 nodeType == nsIDOMNode::PROCESSING_INSTRUCTION_NODE) {
550 return node->GetNodeValue(aTextContent);
553 nsContentUtils::GetNodeTextContent(mContent, PR_TRUE, aTextContent);
555 return NS_OK;
558 NS_IMETHODIMP
559 nsNode3Tearoff::SetTextContent(const nsAString &aTextContent)
561 // Batch possible DOMSubtreeModified events.
562 mozAutoSubtreeModified subtree(mContent->GetOwnerDoc(), nsnull);
564 nsCOMPtr<nsIDOMNode> node(do_QueryInterface(mContent));
565 NS_ASSERTION(node, "We have an nsIContent which doesn't support nsIDOMNode");
567 PRUint16 nodeType;
568 node->GetNodeType(&nodeType);
569 if (nodeType == nsIDOMNode::DOCUMENT_TYPE_NODE ||
570 nodeType == nsIDOMNode::NOTATION_NODE) {
571 return NS_OK;
574 if (nodeType == nsIDOMNode::TEXT_NODE ||
575 nodeType == nsIDOMNode::CDATA_SECTION_NODE ||
576 nodeType == nsIDOMNode::COMMENT_NODE ||
577 nodeType == nsIDOMNode::PROCESSING_INSTRUCTION_NODE) {
578 return node->SetNodeValue(aTextContent);
581 return nsContentUtils::SetNodeTextContent(mContent, aTextContent, PR_FALSE);
584 NS_IMETHODIMP
585 nsNode3Tearoff::CompareDocumentPosition(nsIDOMNode* aOther,
586 PRUint16* aReturn)
588 NS_ENSURE_ARG_POINTER(aOther);
590 nsCOMPtr<nsINode> other = do_QueryInterface(aOther);
591 NS_ENSURE_TRUE(other, NS_ERROR_DOM_NOT_SUPPORTED_ERR);
593 *aReturn = nsContentUtils::ComparePosition(other, mContent);
594 return NS_OK;
597 NS_IMETHODIMP
598 nsNode3Tearoff::IsSameNode(nsIDOMNode* aOther,
599 PRBool* aReturn)
601 nsCOMPtr<nsIContent> other(do_QueryInterface(aOther));
602 *aReturn = mContent == other;
604 return NS_OK;
607 PRBool
608 nsNode3Tearoff::AreNodesEqual(nsIContent* aContent1,
609 nsIContent* aContent2)
611 // We use nsIContent instead of nsINode for the attributes of elements.
613 NS_PRECONDITION(aContent1 && aContent2, "Who called AreNodesEqual?");
615 nsAutoString string1, string2;
617 // Prefix, namespace URI, local name, node name check.
618 if (!aContent1->NodeInfo()->Equals(aContent2->NodeInfo())) {
619 return PR_FALSE;
622 if (aContent1->Tag() == nsGkAtoms::documentTypeNodeName) {
623 nsCOMPtr<nsIDOMDocumentType> docType1 = do_QueryInterface(aContent1);
624 nsCOMPtr<nsIDOMDocumentType> docType2 = do_QueryInterface(aContent2);
626 NS_ASSERTION(docType1 && docType2, "Why don't we have a document type node?");
628 // Public ID
629 docType1->GetPublicId(string1);
630 docType2->GetPublicId(string2);
632 if (!string1.Equals(string2)) {
633 return PR_FALSE;
636 // System ID
637 docType1->GetSystemId(string1);
638 docType2->GetSystemId(string2);
640 if (!string1.Equals(string2)) {
641 return PR_FALSE;
644 // Internal subset
645 docType1->GetInternalSubset(string1);
646 docType2->GetInternalSubset(string2);
648 if (!string1.Equals(string2)) {
649 return PR_FALSE;
653 if (aContent1->IsNodeOfType(nsINode::eELEMENT)) {
654 // aContent1 is an element. Do the check on attributes.
655 PRUint32 attrCount = aContent1->GetAttrCount();
656 if (attrCount != aContent2->GetAttrCount()) {
657 return PR_FALSE;
660 // Iterate over attributes.
661 for (PRUint32 i = 0; i < attrCount; ++i) {
662 const nsAttrName* attrName1 = aContent1->GetAttrNameAt(i);
663 #ifdef DEBUG
664 PRBool hasAttr =
665 #endif
666 aContent1->GetAttr(attrName1->NamespaceID(),
667 attrName1->LocalName(),
668 string1);
669 NS_ASSERTION(hasAttr, "Why don't we have an attr?");
671 if (!aContent2->AttrValueIs(attrName1->NamespaceID(),
672 attrName1->LocalName(),
673 string1,
674 eCaseMatters)) {
675 return PR_FALSE;
678 } else {
679 // aContent1 is not an element. Node value check.
680 nsCOMPtr<nsIDOMNode> domNode1 = do_QueryInterface(aContent1);
681 nsCOMPtr<nsIDOMNode> domNode2 = do_QueryInterface(aContent2);
682 NS_ASSERTION(domNode1 && domNode2, "How'd we get nsIContent without nsIDOMNode?");
683 domNode1->GetNodeValue(string1);
684 domNode2->GetNodeValue(string2);
685 if (!string1.Equals(string2)) {
686 return PR_FALSE;
690 // Child nodes count.
691 PRUint32 childCount = aContent1->GetChildCount();
692 if (childCount != aContent2->GetChildCount()) {
693 return PR_FALSE;
696 // Iterate over child nodes.
697 for (PRUint32 i = 0; i < childCount; ++i) {
698 nsIContent* child1 = aContent1->GetChildAt(i);
699 nsIContent* child2 = aContent2->GetChildAt(i);
700 if (!AreNodesEqual(child1, child2)) {
701 return PR_FALSE;
705 return PR_TRUE;
708 NS_IMETHODIMP
709 nsNode3Tearoff::IsEqualNode(nsIDOMNode* aOther, PRBool* aReturn)
711 NS_ENSURE_ARG_POINTER(aOther);
713 *aReturn = PR_FALSE;
715 // Since we implement nsIContent, aOther must as well.
716 nsCOMPtr<nsIContent> aOtherContent = do_QueryInterface(aOther);
717 // Documents and attributes don't implement nsIContent.
718 if (!aOtherContent) {
719 return NS_OK;
722 *aReturn = nsNode3Tearoff::AreNodesEqual(mContent, aOtherContent);
723 return NS_OK;
726 NS_IMETHODIMP
727 nsNode3Tearoff::GetFeature(const nsAString& aFeature,
728 const nsAString& aVersion,
729 nsISupports** aReturn)
731 return nsGenericElement::InternalGetFeature(this, aFeature, aVersion, aReturn);
734 NS_IMETHODIMP
735 nsNode3Tearoff::SetUserData(const nsAString& aKey,
736 nsIVariant* aData,
737 nsIDOMUserDataHandler* aHandler,
738 nsIVariant** aResult)
740 return nsNodeUtils::SetUserData(mContent, aKey, aData, aHandler, aResult);
743 NS_IMETHODIMP
744 nsNode3Tearoff::GetUserData(const nsAString& aKey,
745 nsIVariant** aResult)
747 return nsNodeUtils::GetUserData(mContent, aKey, aResult);
750 NS_IMETHODIMP
751 nsNode3Tearoff::LookupPrefix(const nsAString& aNamespaceURI,
752 nsAString& aPrefix)
754 SetDOMStringToNull(aPrefix);
756 // XXX Waiting for DOM spec to list error codes.
758 // Trace up the content parent chain looking for the namespace
759 // declaration that defines the aNamespaceURI namespace. Once found,
760 // return the prefix (i.e. the attribute localName).
761 for (nsIContent* content = mContent; content;
762 content = content->GetParent()) {
763 PRUint32 attrCount = content->GetAttrCount();
765 for (PRUint32 i = 0; i < attrCount; ++i) {
766 const nsAttrName* name = content->GetAttrNameAt(i);
768 if (name->NamespaceEquals(kNameSpaceID_XMLNS) &&
769 content->AttrValueIs(kNameSpaceID_XMLNS, name->LocalName(),
770 aNamespaceURI, eCaseMatters)) {
771 // If the localName is "xmlns", the prefix we output should be
772 // null.
773 if (name->LocalName() != nsGkAtoms::xmlns) {
774 name->LocalName()->ToString(aPrefix);
777 return NS_OK;
782 return NS_OK;
785 NS_IMETHODIMP
786 nsNode3Tearoff::LookupNamespaceURI(const nsAString& aNamespacePrefix,
787 nsAString& aNamespaceURI)
789 if (NS_FAILED(nsContentUtils::LookupNamespaceURI(mContent,
790 aNamespacePrefix,
791 aNamespaceURI))) {
792 SetDOMStringToNull(aNamespaceURI);
794 return NS_OK;
797 NS_IMETHODIMP
798 nsNode3Tearoff::IsDefaultNamespace(const nsAString& aNamespaceURI,
799 PRBool* aReturn)
801 nsAutoString defaultNamespace;
802 LookupNamespaceURI(EmptyString(), defaultNamespace);
803 *aReturn = aNamespaceURI.Equals(defaultNamespace);
804 return NS_OK;
807 NS_IMETHODIMP
808 nsNSElementTearoff::GetFirstElementChild(nsIDOMElement** aResult)
810 *aResult = nsnull;
812 nsAttrAndChildArray& children = mContent->mAttrsAndChildren;
813 PRUint32 i, count = children.ChildCount();
814 for (i = 0; i < count; ++i) {
815 nsIContent* child = children.ChildAt(i);
816 if (child->IsNodeOfType(nsINode::eELEMENT)) {
817 return CallQueryInterface(child, aResult);
821 return NS_OK;
824 NS_IMETHODIMP
825 nsNSElementTearoff::GetLastElementChild(nsIDOMElement** aResult)
827 *aResult = nsnull;
829 nsAttrAndChildArray& children = mContent->mAttrsAndChildren;
830 PRUint32 i = children.ChildCount();
831 while (i > 0) {
832 nsIContent* child = children.ChildAt(--i);
833 if (child->IsNodeOfType(nsINode::eELEMENT)) {
834 return CallQueryInterface(child, aResult);
838 return NS_OK;
841 NS_IMETHODIMP
842 nsNSElementTearoff::GetPreviousElementSibling(nsIDOMElement** aResult)
844 *aResult = nsnull;
846 nsIContent* parent = mContent->GetParent();
847 if (!parent) {
848 return NS_OK;
851 NS_ASSERTION(parent->IsNodeOfType(nsINode::eELEMENT) ||
852 parent->IsNodeOfType(nsINode::eDOCUMENT_FRAGMENT),
853 "Parent content must be an element or a doc fragment");
855 nsAttrAndChildArray& children =
856 static_cast<nsGenericElement*>(parent)->mAttrsAndChildren;
857 PRInt32 index = children.IndexOfChild(mContent);
858 if (index < 0) {
859 return NS_OK;
862 PRUint32 i = index;
863 while (i > 0) {
864 nsIContent* child = children.ChildAt((PRUint32)--i);
865 if (child->IsNodeOfType(nsINode::eELEMENT)) {
866 return CallQueryInterface(child, aResult);
870 return NS_OK;
873 NS_IMETHODIMP
874 nsNSElementTearoff::GetNextElementSibling(nsIDOMElement** aResult)
876 *aResult = nsnull;
878 nsIContent* parent = mContent->GetParent();
879 if (!parent) {
880 return NS_OK;
883 NS_ASSERTION(parent->IsNodeOfType(nsINode::eELEMENT) ||
884 parent->IsNodeOfType(nsINode::eDOCUMENT_FRAGMENT),
885 "Parent content must be an element or a doc fragment");
887 nsAttrAndChildArray& children =
888 static_cast<nsGenericElement*>(parent)->mAttrsAndChildren;
889 PRInt32 index = children.IndexOfChild(mContent);
890 if (index < 0) {
891 return NS_OK;
894 PRUint32 i, count = children.ChildCount();
895 for (i = (PRUint32)index + 1; i < count; ++i) {
896 nsIContent* child = children.ChildAt(i);
897 if (child->IsNodeOfType(nsINode::eELEMENT)) {
898 return CallQueryInterface(child, aResult);
902 return NS_OK;
905 nsContentList*
906 nsNSElementTearoff::GetChildrenList()
908 nsGenericElement::nsDOMSlots *slots = mContent->GetDOMSlots();
909 NS_ENSURE_TRUE(slots, nsnull);
911 if (!slots->mChildrenList) {
912 slots->mChildrenList = new nsContentList(mContent, nsGkAtoms::_asterix,
913 kNameSpaceID_Wildcard, PR_FALSE);
916 return slots->mChildrenList;
919 NS_IMETHODIMP
920 nsNSElementTearoff::GetChildElementCount(PRUint32* aResult)
922 *aResult = 0;
924 nsContentList* list = GetChildrenList();
925 NS_ENSURE_TRUE(list, NS_ERROR_OUT_OF_MEMORY);
927 *aResult = list->Length(PR_TRUE);
929 return NS_OK;
932 NS_IMETHODIMP
933 nsNSElementTearoff::GetChildren(nsIDOMNodeList** aResult)
935 *aResult = nsnull;
937 nsContentList* list = GetChildrenList();
938 NS_ENSURE_TRUE(list, NS_ERROR_OUT_OF_MEMORY);
940 NS_ADDREF(*aResult = list);
942 return NS_OK;
945 //----------------------------------------------------------------------
948 NS_IMPL_CYCLE_COLLECTION_1(nsNSElementTearoff, mContent)
950 NS_INTERFACE_MAP_BEGIN(nsNSElementTearoff)
951 NS_INTERFACE_MAP_ENTRY(nsIDOMNSElement)
952 NS_INTERFACE_MAP_ENTRIES_CYCLE_COLLECTION(nsNSElementTearoff)
953 NS_INTERFACE_MAP_END_AGGREGATED(mContent)
955 NS_IMPL_CYCLE_COLLECTING_ADDREF(nsNSElementTearoff)
956 NS_IMPL_CYCLE_COLLECTING_RELEASE(nsNSElementTearoff)
958 NS_IMETHODIMP
959 nsNSElementTearoff::GetElementsByClassName(const nsAString& aClasses,
960 nsIDOMNodeList** aReturn)
962 return nsDocument::GetElementsByClassNameHelper(mContent, aClasses, aReturn);
965 nsIFrame*
966 nsGenericElement::GetStyledFrame()
968 nsIFrame *frame = GetPrimaryFrame(Flush_Layout);
970 return (frame && frame->GetType() == nsGkAtoms::tableOuterFrame) ?
971 frame->GetFirstChild(nsnull) : frame;
974 void
975 nsGenericElement::GetOffsetRect(nsRect& aRect, nsIContent** aOffsetParent)
977 *aOffsetParent = nsnull;
978 aRect = nsRect();
980 nsIFrame* frame = GetStyledFrame();
981 if (!frame) {
982 return;
985 nsPoint origin = frame->GetPosition();
986 aRect.x = nsPresContext::AppUnitsToIntCSSPixels(origin.x);
987 aRect.y = nsPresContext::AppUnitsToIntCSSPixels(origin.y);
989 // Get the union of all rectangles in this and continuation frames.
990 // It doesn't really matter what we use as aRelativeTo here, since
991 // we only care about the size. Using 'parent' might make things
992 // a bit faster by speeding up the internal GetOffsetTo operations.
993 nsIFrame* parent = frame->GetParent() ? frame->GetParent() : frame;
994 nsRect rcFrame = nsLayoutUtils::GetAllInFlowRectsUnion(frame, parent);
995 aRect.width = nsPresContext::AppUnitsToIntCSSPixels(rcFrame.width);
996 aRect.height = nsPresContext::AppUnitsToIntCSSPixels(rcFrame.height);
999 void
1000 nsNSElementTearoff::GetScrollInfo(nsIScrollableView **aScrollableView,
1001 nsIFrame **aFrame)
1003 *aScrollableView = nsnull;
1005 // it isn't clear what to return for SVG nodes, so just return nothing
1006 if (mContent->IsNodeOfType(nsINode::eSVG)) {
1007 if (aFrame)
1008 *aFrame = nsnull;
1009 return;
1012 nsIFrame* frame =
1013 (static_cast<nsGenericElement*>(mContent))->GetStyledFrame();
1015 if (aFrame) {
1016 *aFrame = frame;
1018 if (!frame) {
1019 return;
1022 // Get the scrollable frame
1023 nsIScrollableFrame *scrollFrame = nsnull;
1024 CallQueryInterface(frame, &scrollFrame);
1026 if (!scrollFrame) {
1027 nsIScrollableViewProvider *scrollProvider = nsnull;
1028 CallQueryInterface(frame, &scrollProvider);
1029 // menu frames implement nsIScrollableViewProvider but we don't want
1030 // to use it here.
1031 if (scrollProvider && frame->GetType() != nsGkAtoms::menuFrame) {
1032 *aScrollableView = scrollProvider->GetScrollableView();
1033 if (*aScrollableView) {
1034 return;
1038 nsIDocument* doc = mContent->GetCurrentDoc();
1039 PRBool quirksMode = doc &&
1040 doc->GetCompatibilityMode() == eCompatibility_NavQuirks;
1041 if ((quirksMode && mContent->NodeInfo()->Equals(nsGkAtoms::body)) ||
1042 (!quirksMode && mContent->NodeInfo()->Equals(nsGkAtoms::html))) {
1043 // In quirks mode, the scroll info for the body element should map to the
1044 // scroll info for the nearest scrollable frame above the body element
1045 // (i.e. the root scrollable frame). This is what IE6 does in quirks
1046 // mode. In strict mode the root scrollable frame corresponds to the
1047 // html element in IE6, so we map the scroll info for the html element to
1048 // the root scrollable frame.
1050 do {
1051 frame = frame->GetParent();
1053 if (!frame) {
1054 break;
1057 CallQueryInterface(frame, &scrollFrame);
1058 } while (!scrollFrame);
1061 if (!scrollFrame) {
1062 return;
1066 // Get the scrollable view
1067 *aScrollableView = scrollFrame->GetScrollableView();
1070 nsresult
1071 nsNSElementTearoff::GetScrollTop(PRInt32* aScrollTop)
1073 NS_ENSURE_ARG_POINTER(aScrollTop);
1074 *aScrollTop = 0;
1076 nsIScrollableView *view;
1077 nsresult rv = NS_OK;
1079 GetScrollInfo(&view);
1081 if (view) {
1082 nscoord xPos, yPos;
1083 rv = view->GetScrollPosition(xPos, yPos);
1085 *aScrollTop = nsPresContext::AppUnitsToIntCSSPixels(yPos);
1088 return rv;
1091 nsresult
1092 nsNSElementTearoff::SetScrollTop(PRInt32 aScrollTop)
1094 nsIScrollableView *view;
1095 nsresult rv = NS_OK;
1097 GetScrollInfo(&view);
1099 if (view) {
1100 nscoord xPos, yPos;
1102 rv = view->GetScrollPosition(xPos, yPos);
1104 if (NS_SUCCEEDED(rv)) {
1105 rv = view->ScrollTo(xPos, nsPresContext::CSSPixelsToAppUnits(aScrollTop),
1110 return rv;
1113 nsresult
1114 nsNSElementTearoff::GetScrollLeft(PRInt32* aScrollLeft)
1116 NS_ENSURE_ARG_POINTER(aScrollLeft);
1117 *aScrollLeft = 0;
1119 nsIScrollableView *view;
1120 nsresult rv = NS_OK;
1122 GetScrollInfo(&view);
1124 if (view) {
1125 nscoord xPos, yPos;
1126 rv = view->GetScrollPosition(xPos, yPos);
1128 *aScrollLeft = nsPresContext::AppUnitsToIntCSSPixels(xPos);
1131 return rv;
1134 nsresult
1135 nsNSElementTearoff::SetScrollLeft(PRInt32 aScrollLeft)
1137 nsIScrollableView *view;
1138 nsresult rv = NS_OK;
1140 GetScrollInfo(&view);
1142 if (view) {
1143 nscoord xPos, yPos;
1144 rv = view->GetScrollPosition(xPos, yPos);
1146 if (NS_SUCCEEDED(rv)) {
1147 rv = view->ScrollTo(nsPresContext::CSSPixelsToAppUnits(aScrollLeft),
1148 yPos, 0);
1152 return rv;
1155 nsresult
1156 nsNSElementTearoff::GetScrollHeight(PRInt32* aScrollHeight)
1158 NS_ENSURE_ARG_POINTER(aScrollHeight);
1159 *aScrollHeight = 0;
1161 if (mContent->IsNodeOfType(nsINode::eSVG))
1162 return NS_OK;
1164 nsIScrollableView *scrollView;
1165 nsresult rv = NS_OK;
1167 GetScrollInfo(&scrollView);
1169 if (!scrollView) {
1170 nsRect rcFrame;
1171 nsCOMPtr<nsIContent> parent;
1172 (static_cast<nsGenericElement *>(mContent))->GetOffsetRect(rcFrame, getter_AddRefs(parent));
1173 *aScrollHeight = rcFrame.height;
1174 return NS_OK;
1177 // xMax and yMax is the total length of our container
1178 nscoord xMax, yMax;
1179 rv = scrollView->GetContainerSize(&xMax, &yMax);
1181 *aScrollHeight = nsPresContext::AppUnitsToIntCSSPixels(yMax);
1183 return rv;
1186 nsresult
1187 nsNSElementTearoff::GetScrollWidth(PRInt32* aScrollWidth)
1189 NS_ENSURE_ARG_POINTER(aScrollWidth);
1190 *aScrollWidth = 0;
1192 if (mContent->IsNodeOfType(nsINode::eSVG))
1193 return NS_OK;
1195 nsIScrollableView *scrollView;
1196 nsresult rv = NS_OK;
1198 GetScrollInfo(&scrollView);
1200 if (!scrollView) {
1201 nsRect rcFrame;
1202 nsCOMPtr<nsIContent> parent;
1203 (static_cast<nsGenericElement *>(mContent))->GetOffsetRect(rcFrame, getter_AddRefs(parent));
1204 *aScrollWidth = rcFrame.width;
1205 return NS_OK;
1208 nscoord xMax, yMax;
1209 rv = scrollView->GetContainerSize(&xMax, &yMax);
1211 *aScrollWidth = nsPresContext::AppUnitsToIntCSSPixels(xMax);
1213 return rv;
1216 nsRect
1217 nsNSElementTearoff::GetClientAreaRect()
1219 nsIScrollableView *scrollView;
1220 nsIFrame *frame;
1222 // it isn't clear what to return for SVG nodes, so just return 0
1223 if (mContent->IsNodeOfType(nsINode::eSVG))
1224 return nsRect(0, 0, 0, 0);
1226 GetScrollInfo(&scrollView, &frame);
1228 if (scrollView) {
1229 return scrollView->View()->GetBounds();
1232 if (frame &&
1233 (frame->GetStyleDisplay()->mDisplay != NS_STYLE_DISPLAY_INLINE ||
1234 frame->IsFrameOfType(nsIFrame::eReplaced))) {
1235 // Special case code to make client area work even when there isn't
1236 // a scroll view, see bug 180552, bug 227567.
1237 return frame->GetPaddingRect() - frame->GetPositionIgnoringScrolling();
1240 return nsRect(0, 0, 0, 0);
1243 nsresult
1244 nsNSElementTearoff::GetClientTop(PRInt32* aLength)
1246 NS_ENSURE_ARG_POINTER(aLength);
1247 *aLength = nsPresContext::AppUnitsToIntCSSPixels(GetClientAreaRect().y);
1248 return NS_OK;
1251 nsresult
1252 nsNSElementTearoff::GetClientLeft(PRInt32* aLength)
1254 NS_ENSURE_ARG_POINTER(aLength);
1255 *aLength = nsPresContext::AppUnitsToIntCSSPixels(GetClientAreaRect().x);
1256 return NS_OK;
1259 nsresult
1260 nsNSElementTearoff::GetClientHeight(PRInt32* aLength)
1262 NS_ENSURE_ARG_POINTER(aLength);
1263 *aLength = nsPresContext::AppUnitsToIntCSSPixels(GetClientAreaRect().height);
1264 return NS_OK;
1267 nsresult
1268 nsNSElementTearoff::GetClientWidth(PRInt32* aLength)
1270 NS_ENSURE_ARG_POINTER(aLength);
1271 *aLength = nsPresContext::AppUnitsToIntCSSPixels(GetClientAreaRect().width);
1272 return NS_OK;
1275 static nsIFrame*
1276 GetContainingBlockForClientRect(nsIFrame* aFrame)
1278 // get the nearest enclosing SVG foreign object frame or the root frame
1279 while (aFrame->GetParent() &&
1280 !aFrame->IsFrameOfType(nsIFrame::eSVGForeignObject)) {
1281 aFrame = aFrame->GetParent();
1284 return aFrame;
1287 NS_IMETHODIMP
1288 nsNSElementTearoff::GetBoundingClientRect(nsIDOMClientRect** aResult)
1290 // Weak ref, since we addref it below
1291 nsClientRect* rect = new nsClientRect();
1292 if (!rect)
1293 return NS_ERROR_OUT_OF_MEMORY;
1295 NS_ADDREF(*aResult = rect);
1297 nsIFrame* frame = mContent->GetPrimaryFrame(Flush_Layout);
1298 if (!frame) {
1299 // display:none, perhaps? Return the empty rect
1300 return NS_OK;
1303 nsPresContext* presContext = frame->PresContext();
1304 nsRect r = nsLayoutUtils::GetAllInFlowRectsUnion(frame,
1305 GetContainingBlockForClientRect(frame));
1306 rect->SetLayoutRect(r, presContext);
1307 return NS_OK;
1310 struct RectListBuilder : public nsLayoutUtils::RectCallback {
1311 nsPresContext* mPresContext;
1312 nsClientRectList* mRectList;
1313 nsresult mRV;
1315 RectListBuilder(nsPresContext* aPresContext, nsClientRectList* aList)
1316 : mPresContext(aPresContext), mRectList(aList),
1317 mRV(NS_OK) {}
1319 virtual void AddRect(const nsRect& aRect) {
1320 nsRefPtr<nsClientRect> rect = new nsClientRect();
1321 if (!rect) {
1322 mRV = NS_ERROR_OUT_OF_MEMORY;
1323 return;
1326 rect->SetLayoutRect(aRect, mPresContext);
1327 mRectList->Append(rect);
1331 NS_IMETHODIMP
1332 nsNSElementTearoff::GetClientRects(nsIDOMClientRectList** aResult)
1334 *aResult = nsnull;
1336 nsRefPtr<nsClientRectList> rectList = new nsClientRectList();
1337 if (!rectList)
1338 return NS_ERROR_OUT_OF_MEMORY;
1340 nsIFrame* frame = mContent->GetPrimaryFrame(Flush_Layout);
1341 if (!frame) {
1342 // display:none, perhaps? Return an empty list
1343 *aResult = rectList.forget().get();
1344 return NS_OK;
1347 RectListBuilder builder(frame->PresContext(), rectList);
1348 nsLayoutUtils::GetAllInFlowRects(frame,
1349 GetContainingBlockForClientRect(frame), &builder);
1350 if (NS_FAILED(builder.mRV))
1351 return builder.mRV;
1352 *aResult = rectList.forget().get();
1353 return NS_OK;
1356 //----------------------------------------------------------------------
1359 NS_IMPL_ISUPPORTS1(nsNodeWeakReference,
1360 nsIWeakReference)
1362 nsNodeWeakReference::~nsNodeWeakReference()
1364 if (mNode) {
1365 NS_ASSERTION(mNode->GetSlots() &&
1366 mNode->GetSlots()->mWeakReference == this,
1367 "Weak reference has wrong value");
1368 mNode->GetSlots()->mWeakReference = nsnull;
1372 NS_IMETHODIMP
1373 nsNodeWeakReference::QueryReferent(const nsIID& aIID, void** aInstancePtr)
1375 return mNode ? mNode->QueryInterface(aIID, aInstancePtr) :
1376 NS_ERROR_NULL_POINTER;
1380 NS_IMPL_CYCLE_COLLECTION_1(nsNodeSupportsWeakRefTearoff, mNode)
1382 NS_INTERFACE_MAP_BEGIN_CYCLE_COLLECTION(nsNodeSupportsWeakRefTearoff)
1383 NS_INTERFACE_MAP_ENTRY(nsISupportsWeakReference)
1384 NS_INTERFACE_MAP_END_AGGREGATED(mNode)
1386 NS_IMPL_CYCLE_COLLECTING_ADDREF(nsNodeSupportsWeakRefTearoff)
1387 NS_IMPL_CYCLE_COLLECTING_RELEASE(nsNodeSupportsWeakRefTearoff)
1389 NS_IMETHODIMP
1390 nsNodeSupportsWeakRefTearoff::GetWeakReference(nsIWeakReference** aInstancePtr)
1392 nsINode::nsSlots* slots = mNode->GetSlots();
1393 NS_ENSURE_TRUE(slots, NS_ERROR_OUT_OF_MEMORY);
1395 if (!slots->mWeakReference) {
1396 slots->mWeakReference = new nsNodeWeakReference(mNode);
1397 NS_ENSURE_TRUE(slots->mWeakReference, NS_ERROR_OUT_OF_MEMORY);
1400 NS_ADDREF(*aInstancePtr = slots->mWeakReference);
1402 return NS_OK;
1405 //----------------------------------------------------------------------
1407 nsDOMEventRTTearoff *
1408 nsDOMEventRTTearoff::mCachedEventTearoff[NS_EVENT_TEAROFF_CACHE_SIZE];
1410 PRUint32 nsDOMEventRTTearoff::mCachedEventTearoffCount = 0;
1413 nsDOMEventRTTearoff::nsDOMEventRTTearoff(nsIContent *aContent)
1414 : mContent(aContent)
1418 nsDOMEventRTTearoff::~nsDOMEventRTTearoff()
1422 NS_IMPL_CYCLE_COLLECTION_1(nsDOMEventRTTearoff, mContent)
1424 NS_INTERFACE_MAP_BEGIN_CYCLE_COLLECTION(nsDOMEventRTTearoff)
1425 NS_INTERFACE_MAP_ENTRY(nsIDOMEventTarget)
1426 NS_INTERFACE_MAP_ENTRY(nsIDOM3EventTarget)
1427 NS_INTERFACE_MAP_ENTRY(nsIDOMNSEventTarget)
1428 NS_INTERFACE_MAP_END_AGGREGATED(mContent)
1430 NS_IMPL_CYCLE_COLLECTING_ADDREF_AMBIGUOUS(nsDOMEventRTTearoff,
1431 nsIDOMEventTarget)
1432 NS_IMPL_CYCLE_COLLECTING_RELEASE_AMBIGUOUS_WITH_DESTROY(nsDOMEventRTTearoff,
1433 nsIDOMEventTarget,
1434 LastRelease())
1436 nsDOMEventRTTearoff *
1437 nsDOMEventRTTearoff::Create(nsIContent *aContent)
1439 if (mCachedEventTearoffCount) {
1440 // We have cached unused instances of this class, return a cached
1441 // instance in stead of always creating a new one.
1442 nsDOMEventRTTearoff *tearoff =
1443 mCachedEventTearoff[--mCachedEventTearoffCount];
1445 // Set the back pointer to the content object
1446 tearoff->mContent = aContent;
1448 return tearoff;
1451 // The cache is empty, this means we haveto create a new instance.
1452 return new nsDOMEventRTTearoff(aContent);
1455 // static
1456 void
1457 nsDOMEventRTTearoff::Shutdown()
1459 // Clear our cache.
1460 while (mCachedEventTearoffCount) {
1461 delete mCachedEventTearoff[--mCachedEventTearoffCount];
1465 void
1466 nsDOMEventRTTearoff::LastRelease()
1468 if (mCachedEventTearoffCount < NS_EVENT_TEAROFF_CACHE_SIZE) {
1469 // There's still space in the cache for one more instance, put
1470 // this instance in the cache in stead of deleting it.
1471 mCachedEventTearoff[mCachedEventTearoffCount++] = this;
1473 // Don't set mContent to null directly since setting mContent to null
1474 // could result in code that grabs a tearoff from the cache and we don't
1475 // want to get reused while still being torn down.
1476 // See bug 330526.
1477 nsCOMPtr<nsIContent> kungFuDeathGrip;
1478 kungFuDeathGrip.swap(mContent);
1480 // The refcount balancing and destructor re-entrancy protection
1481 // code in Release() sets mRefCnt to 1 so we have to set it to 0
1482 // here to prevent leaks
1483 mRefCnt = 0;
1485 return;
1488 delete this;
1491 nsresult
1492 nsDOMEventRTTearoff::GetDOM3EventTarget(nsIDOM3EventTarget **aTarget)
1494 nsCOMPtr<nsIEventListenerManager> listener_manager;
1495 nsresult rv =
1496 mContent->GetListenerManager(PR_TRUE, getter_AddRefs(listener_manager));
1497 NS_ENSURE_SUCCESS(rv, rv);
1499 return CallQueryInterface(listener_manager, aTarget);
1502 NS_IMETHODIMP
1503 nsDOMEventRTTearoff::GetScriptTypeID(PRUint32 *aLang)
1505 *aLang = mContent->GetScriptTypeID();
1506 return NS_OK;
1509 NS_IMETHODIMP
1510 nsDOMEventRTTearoff::SetScriptTypeID(PRUint32 aLang)
1512 return mContent->SetScriptTypeID(aLang);
1516 // nsIDOMEventTarget
1517 NS_IMETHODIMP
1518 nsDOMEventRTTearoff::AddEventListener(const nsAString& aType,
1519 nsIDOMEventListener *aListener,
1520 PRBool useCapture)
1522 return
1523 AddEventListener(aType, aListener, useCapture,
1524 !nsContentUtils::IsChromeDoc(mContent->GetOwnerDoc()));
1527 NS_IMETHODIMP
1528 nsDOMEventRTTearoff::RemoveEventListener(const nsAString& aType,
1529 nsIDOMEventListener* aListener,
1530 PRBool aUseCapture)
1532 return RemoveGroupedEventListener(aType, aListener, aUseCapture, nsnull);
1535 NS_IMETHODIMP
1536 nsDOMEventRTTearoff::DispatchEvent(nsIDOMEvent *aEvt, PRBool* _retval)
1538 nsCOMPtr<nsIEventListenerManager> listener_manager;
1539 nsresult rv =
1540 mContent->GetListenerManager(PR_TRUE, getter_AddRefs(listener_manager));
1541 NS_ENSURE_SUCCESS(rv, rv);
1542 nsCOMPtr<nsIDOMEventTarget> target = do_QueryInterface(listener_manager);
1543 NS_ENSURE_STATE(target);
1544 return target->DispatchEvent(aEvt, _retval);
1547 // nsIDOM3EventTarget
1548 NS_IMETHODIMP
1549 nsDOMEventRTTearoff::AddGroupedEventListener(const nsAString& aType,
1550 nsIDOMEventListener *aListener,
1551 PRBool aUseCapture,
1552 nsIDOMEventGroup *aEvtGrp)
1554 nsCOMPtr<nsIDOM3EventTarget> event_target;
1555 nsresult rv = GetDOM3EventTarget(getter_AddRefs(event_target));
1556 NS_ENSURE_SUCCESS(rv, rv);
1558 return event_target->AddGroupedEventListener(aType, aListener, aUseCapture,
1559 aEvtGrp);
1562 NS_IMETHODIMP
1563 nsDOMEventRTTearoff::RemoveGroupedEventListener(const nsAString& aType,
1564 nsIDOMEventListener *aListener,
1565 PRBool aUseCapture,
1566 nsIDOMEventGroup *aEvtGrp)
1568 nsCOMPtr<nsIDOM3EventTarget> event_target;
1569 nsresult rv = GetDOM3EventTarget(getter_AddRefs(event_target));
1570 NS_ENSURE_SUCCESS(rv, rv);
1572 return event_target->RemoveGroupedEventListener(aType, aListener,
1573 aUseCapture, aEvtGrp);
1576 NS_IMETHODIMP
1577 nsDOMEventRTTearoff::CanTrigger(const nsAString & type, PRBool *_retval)
1579 return NS_ERROR_NOT_IMPLEMENTED;
1582 NS_IMETHODIMP
1583 nsDOMEventRTTearoff::IsRegisteredHere(const nsAString & type, PRBool *_retval)
1585 return NS_ERROR_NOT_IMPLEMENTED;
1588 // nsIDOMNSEventTarget
1589 NS_IMETHODIMP
1590 nsDOMEventRTTearoff::AddEventListener(const nsAString& aType,
1591 nsIDOMEventListener *aListener,
1592 PRBool aUseCapture,
1593 PRBool aWantsUntrusted)
1595 nsCOMPtr<nsIEventListenerManager> listener_manager;
1596 nsresult rv =
1597 mContent->GetListenerManager(PR_TRUE, getter_AddRefs(listener_manager));
1598 NS_ENSURE_SUCCESS(rv, rv);
1600 PRInt32 flags = aUseCapture ? NS_EVENT_FLAG_CAPTURE : NS_EVENT_FLAG_BUBBLE;
1602 if (aWantsUntrusted) {
1603 flags |= NS_PRIV_EVENT_UNTRUSTED_PERMITTED;
1606 return listener_manager->AddEventListenerByType(aListener, aType, flags,
1607 nsnull);
1610 //----------------------------------------------------------------------
1612 NS_IMPL_CYCLE_COLLECTION_1(nsNodeSelectorTearoff, mContent)
1614 NS_INTERFACE_MAP_BEGIN_CYCLE_COLLECTION(nsNodeSelectorTearoff)
1615 NS_INTERFACE_MAP_ENTRY(nsIDOMNodeSelector)
1616 NS_INTERFACE_MAP_END_AGGREGATED(mContent)
1618 NS_IMPL_CYCLE_COLLECTING_ADDREF(nsNodeSelectorTearoff)
1619 NS_IMPL_CYCLE_COLLECTING_RELEASE(nsNodeSelectorTearoff)
1621 NS_IMETHODIMP
1622 nsNodeSelectorTearoff::QuerySelector(const nsAString& aSelector,
1623 nsIDOMElement **aReturn)
1625 return nsGenericElement::doQuerySelector(mContent, aSelector, aReturn);
1628 NS_IMETHODIMP
1629 nsNodeSelectorTearoff::QuerySelectorAll(const nsAString& aSelector,
1630 nsIDOMNodeList **aReturn)
1632 return nsGenericElement::doQuerySelectorAll(mContent, aSelector, aReturn);
1635 //----------------------------------------------------------------------
1636 nsGenericElement::nsDOMSlots::nsDOMSlots(PtrBits aFlags)
1637 : nsINode::nsSlots(aFlags),
1638 mBindingParent(nsnull)
1642 nsGenericElement::nsDOMSlots::~nsDOMSlots()
1644 if (mStyle) {
1645 mStyle->DropReference();
1648 if (mAttributeMap) {
1649 mAttributeMap->DropReference();
1653 nsGenericElement::nsGenericElement(nsINodeInfo *aNodeInfo)
1654 : nsIContent(aNodeInfo)
1656 // Set the default scriptID to JS - but skip SetScriptTypeID as it
1657 // does extra work we know isn't necessary here...
1658 SetFlags(nsIProgrammingLanguage::JAVASCRIPT << NODE_SCRIPT_TYPE_OFFSET);
1661 nsGenericElement::~nsGenericElement()
1663 NS_PRECONDITION(!IsInDoc(),
1664 "Please remove this from the document properly");
1667 NS_IMETHODIMP
1668 nsGenericElement::GetNodeName(nsAString& aNodeName)
1670 mNodeInfo->GetQualifiedName(aNodeName);
1671 return NS_OK;
1674 NS_IMETHODIMP
1675 nsGenericElement::GetLocalName(nsAString& aLocalName)
1677 mNodeInfo->GetLocalName(aLocalName);
1678 return NS_OK;
1681 NS_IMETHODIMP
1682 nsGenericElement::GetNodeValue(nsAString& aNodeValue)
1684 SetDOMStringToNull(aNodeValue);
1686 return NS_OK;
1689 NS_IMETHODIMP
1690 nsGenericElement::SetNodeValue(const nsAString& aNodeValue)
1692 // The DOM spec says that when nodeValue is defined to be null "setting it
1693 // has no effect", so we don't throw an exception.
1694 return NS_OK;
1697 NS_IMETHODIMP
1698 nsGenericElement::GetNodeType(PRUint16* aNodeType)
1700 *aNodeType = (PRUint16)nsIDOMNode::ELEMENT_NODE;
1701 return NS_OK;
1704 NS_IMETHODIMP
1705 nsGenericElement::GetParentNode(nsIDOMNode** aParentNode)
1707 *aParentNode = nsnull;
1708 nsINode *parent = GetNodeParent();
1710 return parent ? CallQueryInterface(parent, aParentNode) : NS_OK;
1713 NS_IMETHODIMP
1714 nsGenericElement::GetPreviousSibling(nsIDOMNode** aPrevSibling)
1716 *aPrevSibling = nsnull;
1718 nsINode *parent = GetNodeParent();
1719 if (!parent) {
1720 return NS_OK;
1723 PRInt32 pos = parent->IndexOf(this);
1724 nsIContent *sibling = parent->GetChildAt(pos - 1);
1726 return sibling ? CallQueryInterface(sibling, aPrevSibling) : NS_OK;
1729 NS_IMETHODIMP
1730 nsGenericElement::GetNextSibling(nsIDOMNode** aNextSibling)
1732 *aNextSibling = nsnull;
1734 nsINode *parent = GetNodeParent();
1735 if (!parent) {
1736 return NS_OK;
1739 PRInt32 pos = parent->IndexOf(this);
1740 nsIContent *sibling = parent->GetChildAt(pos + 1);
1742 return sibling ? CallQueryInterface(sibling, aNextSibling) : NS_OK;
1745 NS_IMETHODIMP
1746 nsGenericElement::GetOwnerDocument(nsIDOMDocument** aOwnerDocument)
1748 nsIDocument *doc = GetOwnerDoc();
1749 if (doc) {
1750 return CallQueryInterface(doc, aOwnerDocument);
1753 *aOwnerDocument = nsnull;
1755 return NS_OK;
1758 NS_IMETHODIMP
1759 nsGenericElement::GetNamespaceURI(nsAString& aNamespaceURI)
1761 return mNodeInfo->GetNamespaceURI(aNamespaceURI);
1764 NS_IMETHODIMP
1765 nsGenericElement::GetPrefix(nsAString& aPrefix)
1767 mNodeInfo->GetPrefix(aPrefix);
1768 return NS_OK;
1771 NS_IMETHODIMP
1772 nsGenericElement::SetPrefix(const nsAString& aPrefix)
1774 // XXX: Validate the prefix string!
1776 nsCOMPtr<nsIAtom> prefix;
1778 if (!aPrefix.IsEmpty()) {
1779 prefix = do_GetAtom(aPrefix);
1780 NS_ENSURE_TRUE(prefix, NS_ERROR_OUT_OF_MEMORY);
1783 if (!nsContentUtils::IsValidNodeName(mNodeInfo->NameAtom(), prefix,
1784 mNodeInfo->NamespaceID())) {
1785 return NS_ERROR_DOM_NAMESPACE_ERR;
1788 nsCOMPtr<nsINodeInfo> newNodeInfo;
1789 nsresult rv = nsContentUtils::PrefixChanged(mNodeInfo, prefix,
1790 getter_AddRefs(newNodeInfo));
1791 NS_ENSURE_SUCCESS(rv, rv);
1793 mNodeInfo = newNodeInfo;
1795 return NS_OK;
1798 nsresult
1799 nsGenericElement::InternalIsSupported(nsISupports* aObject,
1800 const nsAString& aFeature,
1801 const nsAString& aVersion,
1802 PRBool* aReturn)
1804 NS_ENSURE_ARG_POINTER(aReturn);
1805 *aReturn = PR_FALSE;
1807 // Convert the incoming UTF16 strings to raw char*'s to save us some
1808 // code when doing all those string compares.
1809 NS_ConvertUTF16toUTF8 feature(aFeature);
1810 NS_ConvertUTF16toUTF8 version(aVersion);
1812 const char *f = feature.get();
1813 const char *v = version.get();
1815 if (PL_strcasecmp(f, "XML") == 0 ||
1816 PL_strcasecmp(f, "HTML") == 0) {
1817 if (aVersion.IsEmpty() ||
1818 PL_strcmp(v, "1.0") == 0 ||
1819 PL_strcmp(v, "2.0") == 0) {
1820 *aReturn = PR_TRUE;
1822 } else if (PL_strcasecmp(f, "Views") == 0 ||
1823 PL_strcasecmp(f, "StyleSheets") == 0 ||
1824 PL_strcasecmp(f, "Core") == 0 ||
1825 PL_strcasecmp(f, "CSS") == 0 ||
1826 PL_strcasecmp(f, "CSS2") == 0 ||
1827 PL_strcasecmp(f, "Events") == 0 ||
1828 PL_strcasecmp(f, "UIEvents") == 0 ||
1829 PL_strcasecmp(f, "MouseEvents") == 0 ||
1830 // Non-standard!
1831 PL_strcasecmp(f, "MouseScrollEvents") == 0 ||
1832 PL_strcasecmp(f, "HTMLEvents") == 0 ||
1833 PL_strcasecmp(f, "Range") == 0 ||
1834 PL_strcasecmp(f, "XHTML") == 0) {
1835 if (aVersion.IsEmpty() ||
1836 PL_strcmp(v, "2.0") == 0) {
1837 *aReturn = PR_TRUE;
1839 } else if (PL_strcasecmp(f, "XPath") == 0) {
1840 if (aVersion.IsEmpty() ||
1841 PL_strcmp(v, "3.0") == 0) {
1842 *aReturn = PR_TRUE;
1845 #ifdef MOZ_SVG
1846 else if (PL_strcasecmp(f, "SVGEvents") == 0 ||
1847 PL_strcasecmp(f, "SVGZoomEvents") == 0 ||
1848 NS_SVG_HaveFeature(aFeature)) {
1849 if (aVersion.IsEmpty() ||
1850 PL_strcmp(v, "1.0") == 0 ||
1851 PL_strcmp(v, "1.1") == 0) {
1852 *aReturn = PR_TRUE;
1855 #endif /* MOZ_SVG */
1856 else {
1857 nsCOMPtr<nsIDOMNSFeatureFactory> factory =
1858 GetDOMFeatureFactory(aFeature, aVersion);
1860 if (factory) {
1861 factory->HasFeature(aObject, aFeature, aVersion, aReturn);
1864 return NS_OK;
1867 nsresult
1868 nsGenericElement::InternalGetFeature(nsISupports* aObject,
1869 const nsAString& aFeature,
1870 const nsAString& aVersion,
1871 nsISupports** aReturn)
1873 *aReturn = nsnull;
1874 nsCOMPtr<nsIDOMNSFeatureFactory> factory =
1875 GetDOMFeatureFactory(aFeature, aVersion);
1877 if (factory) {
1878 factory->GetFeature(aObject, aFeature, aVersion, aReturn);
1881 return NS_OK;
1884 already_AddRefed<nsIDOMNSFeatureFactory>
1885 nsGenericElement::GetDOMFeatureFactory(const nsAString& aFeature,
1886 const nsAString& aVersion)
1888 nsIDOMNSFeatureFactory *factory = nsnull;
1889 nsCOMPtr<nsICategoryManager> categoryManager =
1890 do_GetService(NS_CATEGORYMANAGER_CONTRACTID);
1891 if (categoryManager) {
1892 nsCAutoString featureCategory(NS_DOMNS_FEATURE_PREFIX);
1893 AppendUTF16toUTF8(aFeature, featureCategory);
1894 nsXPIDLCString contractID;
1895 nsresult rv = categoryManager->GetCategoryEntry(featureCategory.get(),
1896 NS_ConvertUTF16toUTF8(aVersion).get(),
1897 getter_Copies(contractID));
1898 if (NS_SUCCEEDED(rv)) {
1899 CallGetService(contractID.get(), &factory); // addrefs
1902 return factory;
1905 NS_IMETHODIMP
1906 nsGenericElement::IsSupported(const nsAString& aFeature,
1907 const nsAString& aVersion,
1908 PRBool* aReturn)
1910 return InternalIsSupported(this, aFeature, aVersion, aReturn);
1913 NS_IMETHODIMP
1914 nsGenericElement::HasAttributes(PRBool* aReturn)
1916 NS_ENSURE_ARG_POINTER(aReturn);
1918 *aReturn = GetAttrCount() > 0;
1920 return NS_OK;
1923 NS_IMETHODIMP
1924 nsGenericElement::GetAttributes(nsIDOMNamedNodeMap** aAttributes)
1926 NS_ENSURE_ARG_POINTER(aAttributes);
1927 nsDOMSlots *slots = GetDOMSlots();
1929 if (!slots) {
1930 return NS_ERROR_OUT_OF_MEMORY;
1933 if (!slots->mAttributeMap) {
1934 slots->mAttributeMap = new nsDOMAttributeMap(this);
1935 if (!slots->mAttributeMap) {
1936 return NS_ERROR_OUT_OF_MEMORY;
1938 if (!slots->mAttributeMap->Init()) {
1939 slots->mAttributeMap = nsnull;
1940 return NS_ERROR_FAILURE;
1944 NS_ADDREF(*aAttributes = slots->mAttributeMap);
1946 return NS_OK;
1949 nsresult
1950 nsGenericElement::GetChildNodes(nsIDOMNodeList** aChildNodes)
1952 nsSlots *slots = GetSlots();
1954 if (!slots) {
1955 return NS_ERROR_OUT_OF_MEMORY;
1958 if (!slots->mChildNodes) {
1959 slots->mChildNodes = new nsChildContentList(this);
1960 if (!slots->mChildNodes) {
1961 return NS_ERROR_OUT_OF_MEMORY;
1963 NS_ADDREF(slots->mChildNodes);
1966 NS_ADDREF(*aChildNodes = slots->mChildNodes);
1968 return NS_OK;
1971 nsresult
1972 nsGenericElement::HasChildNodes(PRBool* aReturn)
1974 *aReturn = mAttrsAndChildren.ChildCount() > 0;
1976 return NS_OK;
1979 nsresult
1980 nsGenericElement::GetFirstChild(nsIDOMNode** aNode)
1982 nsIContent* child = GetChildAt(0);
1983 if (child) {
1984 return CallQueryInterface(child, aNode);
1987 *aNode = nsnull;
1989 return NS_OK;
1992 nsresult
1993 nsGenericElement::GetLastChild(nsIDOMNode** aNode)
1995 PRUint32 count = GetChildCount();
1997 if (count > 0) {
1998 return CallQueryInterface(GetChildAt(count - 1), aNode);
2001 *aNode = nsnull;
2003 return NS_OK;
2006 NS_IMETHODIMP
2007 nsGenericElement::GetTagName(nsAString& aTagName)
2009 mNodeInfo->GetQualifiedName(aTagName);
2010 return NS_OK;
2013 nsresult
2014 nsGenericElement::GetAttribute(const nsAString& aName,
2015 nsAString& aReturn)
2017 const nsAttrName* name = InternalGetExistingAttrNameFromQName(aName);
2019 if (!name) {
2020 if (mNodeInfo->NamespaceID() == kNameSpaceID_XUL) {
2021 // XXX should be SetDOMStringToNull(aReturn);
2022 // See bug 232598
2023 aReturn.Truncate();
2025 else {
2026 SetDOMStringToNull(aReturn);
2029 return NS_OK;
2032 GetAttr(name->NamespaceID(), name->LocalName(), aReturn);
2034 return NS_OK;
2037 nsresult
2038 nsGenericElement::SetAttribute(const nsAString& aName,
2039 const nsAString& aValue)
2041 const nsAttrName* name = InternalGetExistingAttrNameFromQName(aName);
2043 if (!name) {
2044 nsresult rv = nsContentUtils::CheckQName(aName, PR_FALSE);
2045 NS_ENSURE_SUCCESS(rv, rv);
2047 nsCOMPtr<nsIAtom> nameAtom = do_GetAtom(aName);
2048 NS_ENSURE_TRUE(nameAtom, NS_ERROR_OUT_OF_MEMORY);
2050 return SetAttr(kNameSpaceID_None, nameAtom, aValue, PR_TRUE);
2053 return SetAttr(name->NamespaceID(), name->LocalName(), name->GetPrefix(),
2054 aValue, PR_TRUE);
2057 nsresult
2058 nsGenericElement::RemoveAttribute(const nsAString& aName)
2060 const nsAttrName* name = InternalGetExistingAttrNameFromQName(aName);
2062 if (!name) {
2063 return NS_OK;
2066 // Hold a strong reference here so that the atom or nodeinfo doesn't go
2067 // away during UnsetAttr. If it did UnsetAttr would be left with a
2068 // dangling pointer as argument without knowing it.
2069 nsAttrName tmp(*name);
2071 return UnsetAttr(name->NamespaceID(), name->LocalName(), PR_TRUE);
2074 nsresult
2075 nsGenericElement::GetAttributeNode(const nsAString& aName,
2076 nsIDOMAttr** aReturn)
2078 NS_ENSURE_ARG_POINTER(aReturn);
2079 *aReturn = nsnull;
2081 nsCOMPtr<nsIDOMNamedNodeMap> map;
2082 nsresult rv = GetAttributes(getter_AddRefs(map));
2083 NS_ENSURE_SUCCESS(rv, rv);
2085 nsCOMPtr<nsIDOMNode> node;
2086 rv = map->GetNamedItem(aName, getter_AddRefs(node));
2088 if (NS_SUCCEEDED(rv) && node) {
2089 rv = CallQueryInterface(node, aReturn);
2092 return rv;
2095 nsresult
2096 nsGenericElement::SetAttributeNode(nsIDOMAttr* aAttribute,
2097 nsIDOMAttr** aReturn)
2099 NS_ENSURE_ARG_POINTER(aReturn);
2100 NS_ENSURE_ARG_POINTER(aAttribute);
2102 *aReturn = nsnull;
2104 nsCOMPtr<nsIDOMNamedNodeMap> map;
2105 nsresult rv = GetAttributes(getter_AddRefs(map));
2106 NS_ENSURE_SUCCESS(rv, rv);
2108 nsCOMPtr<nsIDOMNode> returnNode;
2109 rv = map->SetNamedItem(aAttribute, getter_AddRefs(returnNode));
2110 NS_ENSURE_SUCCESS(rv, rv);
2112 if (returnNode) {
2113 rv = CallQueryInterface(returnNode, aReturn);
2116 return rv;
2119 nsresult
2120 nsGenericElement::RemoveAttributeNode(nsIDOMAttr* aAttribute,
2121 nsIDOMAttr** aReturn)
2123 NS_ENSURE_ARG_POINTER(aReturn);
2124 NS_ENSURE_ARG_POINTER(aAttribute);
2126 *aReturn = nsnull;
2128 nsCOMPtr<nsIDOMNamedNodeMap> map;
2129 nsresult rv = GetAttributes(getter_AddRefs(map));
2130 NS_ENSURE_SUCCESS(rv, rv);
2132 nsAutoString name;
2134 rv = aAttribute->GetName(name);
2135 if (NS_SUCCEEDED(rv)) {
2136 nsCOMPtr<nsIDOMNode> node;
2137 rv = map->RemoveNamedItem(name, getter_AddRefs(node));
2139 if (NS_SUCCEEDED(rv) && node) {
2140 rv = CallQueryInterface(node, aReturn);
2144 return rv;
2147 nsresult
2148 nsGenericElement::GetElementsByTagName(const nsAString& aTagname,
2149 nsIDOMNodeList** aReturn)
2151 nsCOMPtr<nsIAtom> nameAtom = do_GetAtom(aTagname);
2152 NS_ENSURE_TRUE(nameAtom, NS_ERROR_OUT_OF_MEMORY);
2154 nsContentList *list = NS_GetContentList(this, nameAtom,
2155 kNameSpaceID_Unknown).get();
2156 NS_ENSURE_TRUE(list, NS_ERROR_OUT_OF_MEMORY);
2158 // transfer ref to aReturn
2159 *aReturn = list;
2160 return NS_OK;
2163 nsresult
2164 nsGenericElement::GetAttributeNS(const nsAString& aNamespaceURI,
2165 const nsAString& aLocalName,
2166 nsAString& aReturn)
2168 PRInt32 nsid =
2169 nsContentUtils::NameSpaceManager()->GetNameSpaceID(aNamespaceURI);
2171 if (nsid == kNameSpaceID_Unknown) {
2172 // Unknown namespace means no attr...
2174 aReturn.Truncate();
2176 return NS_OK;
2179 nsCOMPtr<nsIAtom> name = do_GetAtom(aLocalName);
2180 GetAttr(nsid, name, aReturn);
2182 return NS_OK;
2185 nsresult
2186 nsGenericElement::SetAttributeNS(const nsAString& aNamespaceURI,
2187 const nsAString& aQualifiedName,
2188 const nsAString& aValue)
2190 nsCOMPtr<nsINodeInfo> ni;
2191 nsresult rv =
2192 nsContentUtils::GetNodeInfoFromQName(aNamespaceURI, aQualifiedName,
2193 mNodeInfo->NodeInfoManager(),
2194 getter_AddRefs(ni));
2195 NS_ENSURE_SUCCESS(rv, rv);
2197 return SetAttr(ni->NamespaceID(), ni->NameAtom(), ni->GetPrefixAtom(),
2198 aValue, PR_TRUE);
2201 nsresult
2202 nsGenericElement::RemoveAttributeNS(const nsAString& aNamespaceURI,
2203 const nsAString& aLocalName)
2205 nsCOMPtr<nsIAtom> name = do_GetAtom(aLocalName);
2206 PRInt32 nsid =
2207 nsContentUtils::NameSpaceManager()->GetNameSpaceID(aNamespaceURI);
2209 if (nsid == kNameSpaceID_Unknown) {
2210 // Unknown namespace means no attr...
2212 return NS_OK;
2215 nsAutoString tmp;
2216 UnsetAttr(nsid, name, PR_TRUE);
2218 return NS_OK;
2221 nsresult
2222 nsGenericElement::GetAttributeNodeNS(const nsAString& aNamespaceURI,
2223 const nsAString& aLocalName,
2224 nsIDOMAttr** aReturn)
2226 NS_ENSURE_ARG_POINTER(aReturn);
2228 *aReturn = nsnull;
2230 nsCOMPtr<nsIDOMNamedNodeMap> map;
2231 nsresult rv = GetAttributes(getter_AddRefs(map));
2232 NS_ENSURE_SUCCESS(rv, rv);
2234 nsCOMPtr<nsIDOMNode> node;
2235 rv = map->GetNamedItemNS(aNamespaceURI, aLocalName, getter_AddRefs(node));
2237 if (NS_SUCCEEDED(rv) && node) {
2238 rv = CallQueryInterface(node, aReturn);
2241 return rv;
2244 nsresult
2245 nsGenericElement::SetAttributeNodeNS(nsIDOMAttr* aNewAttr,
2246 nsIDOMAttr** aReturn)
2248 NS_ENSURE_ARG_POINTER(aReturn);
2249 NS_ENSURE_ARG_POINTER(aNewAttr);
2251 *aReturn = nsnull;
2253 nsCOMPtr<nsIDOMNamedNodeMap> map;
2254 nsresult rv = GetAttributes(getter_AddRefs(map));
2255 NS_ENSURE_SUCCESS(rv, rv);
2257 nsCOMPtr<nsIDOMNode> returnNode;
2258 rv = map->SetNamedItemNS(aNewAttr, getter_AddRefs(returnNode));
2259 NS_ENSURE_SUCCESS(rv, rv);
2261 if (returnNode) {
2262 rv = CallQueryInterface(returnNode, aReturn);
2265 return rv;
2268 nsresult
2269 nsGenericElement::GetElementsByTagNameNS(const nsAString& aNamespaceURI,
2270 const nsAString& aLocalName,
2271 nsIDOMNodeList** aReturn)
2273 PRInt32 nameSpaceId = kNameSpaceID_Wildcard;
2275 if (!aNamespaceURI.EqualsLiteral("*")) {
2276 nsresult rv =
2277 nsContentUtils::NameSpaceManager()->RegisterNameSpace(aNamespaceURI,
2278 nameSpaceId);
2279 NS_ENSURE_SUCCESS(rv, rv);
2282 nsCOMPtr<nsIAtom> nameAtom = do_GetAtom(aLocalName);
2283 NS_ENSURE_TRUE(nameAtom, NS_ERROR_OUT_OF_MEMORY);
2285 nsContentList *list = NS_GetContentList(this, nameAtom, nameSpaceId).get();
2286 NS_ENSURE_TRUE(list, NS_ERROR_OUT_OF_MEMORY);
2288 // transfer ref to aReturn
2289 *aReturn = list;
2290 return NS_OK;
2293 nsresult
2294 nsGenericElement::HasAttribute(const nsAString& aName, PRBool* aReturn)
2296 NS_ENSURE_ARG_POINTER(aReturn);
2298 const nsAttrName* name = InternalGetExistingAttrNameFromQName(aName);
2299 *aReturn = (name != nsnull);
2301 return NS_OK;
2304 nsresult
2305 nsGenericElement::HasAttributeNS(const nsAString& aNamespaceURI,
2306 const nsAString& aLocalName,
2307 PRBool* aReturn)
2309 NS_ENSURE_ARG_POINTER(aReturn);
2311 PRInt32 nsid =
2312 nsContentUtils::NameSpaceManager()->GetNameSpaceID(aNamespaceURI);
2314 if (nsid == kNameSpaceID_Unknown) {
2315 // Unknown namespace means no attr...
2317 *aReturn = PR_FALSE;
2319 return NS_OK;
2322 nsCOMPtr<nsIAtom> name = do_GetAtom(aLocalName);
2323 *aReturn = HasAttr(nsid, name);
2325 return NS_OK;
2328 nsresult
2329 nsGenericElement::JoinTextNodes(nsIContent* aFirst,
2330 nsIContent* aSecond)
2332 nsresult rv = NS_OK;
2333 nsCOMPtr<nsIDOMText> firstText(do_QueryInterface(aFirst, &rv));
2335 if (NS_SUCCEEDED(rv)) {
2336 nsCOMPtr<nsIDOMText> secondText(do_QueryInterface(aSecond, &rv));
2338 if (NS_SUCCEEDED(rv)) {
2339 nsAutoString str;
2341 rv = secondText->GetData(str);
2342 if (NS_SUCCEEDED(rv)) {
2343 rv = firstText->AppendData(str);
2348 return rv;
2351 nsresult
2352 nsGenericElement::Normalize()
2354 // Batch possible DOMSubtreeModified events.
2355 mozAutoSubtreeModified subtree(GetOwnerDoc(), nsnull);
2357 nsresult result = NS_OK;
2358 PRUint32 index, count = GetChildCount();
2360 for (index = 0; (index < count) && (NS_OK == result); index++) {
2361 nsIContent *child = GetChildAt(index);
2363 nsCOMPtr<nsIDOMNode> node = do_QueryInterface(child);
2364 if (node) {
2365 PRUint16 nodeType;
2366 node->GetNodeType(&nodeType);
2368 switch (nodeType) {
2369 case nsIDOMNode::TEXT_NODE:
2371 // ensure that if the text node is empty, it is removed
2372 if (0 == child->TextLength()) {
2373 result = RemoveChildAt(index, PR_TRUE);
2374 if (NS_FAILED(result)) {
2375 return result;
2378 count--;
2379 index--;
2380 break;
2383 if (index+1 < count) {
2384 // Get the sibling. If it's also a text node, then
2385 // remove it from the tree and join the two text
2386 // nodes.
2387 nsIContent *sibling = GetChildAt(index + 1);
2389 nsCOMPtr<nsIDOMNode> siblingNode = do_QueryInterface(sibling);
2391 if (siblingNode) {
2392 PRUint16 siblingNodeType;
2393 siblingNode->GetNodeType(&siblingNodeType);
2395 if (siblingNodeType == nsIDOMNode::TEXT_NODE) {
2396 result = RemoveChildAt(index+1, PR_TRUE);
2397 if (NS_FAILED(result)) {
2398 return result;
2401 result = JoinTextNodes(child, sibling);
2402 if (NS_FAILED(result)) {
2403 return result;
2405 count--;
2406 index--;
2410 break;
2412 case nsIDOMNode::ELEMENT_NODE:
2413 nsCOMPtr<nsIDOMElement> element = do_QueryInterface(child);
2415 if (element) {
2416 result = element->Normalize();
2418 break;
2423 return result;
2426 static nsXBLBinding*
2427 GetFirstBindingWithContent(nsBindingManager* aBmgr, nsIContent* aBoundElem)
2429 nsXBLBinding* binding = aBmgr->GetBinding(aBoundElem);
2430 while (binding) {
2431 if (binding->GetAnonymousContent()) {
2432 return binding;
2434 binding = binding->GetBaseBinding();
2437 return nsnull;
2440 static nsresult
2441 BindNodesInInsertPoints(nsXBLBinding* aBinding, nsIContent* aInsertParent,
2442 nsIDocument* aDocument)
2444 NS_PRECONDITION(aBinding && aInsertParent, "Missing arguments");
2446 nsresult rv;
2447 // These should be refcounted or otherwise protectable.
2448 nsInsertionPointList* inserts =
2449 aBinding->GetExistingInsertionPointsFor(aInsertParent);
2450 if (inserts) {
2451 PRBool allowScripts = aBinding->AllowScripts();
2452 #ifdef MOZ_XUL
2453 nsCOMPtr<nsIXULDocument> xulDoc = do_QueryInterface(aDocument);
2454 #endif
2455 PRUint32 i;
2456 for (i = 0; i < inserts->Length(); ++i) {
2457 nsCOMPtr<nsIContent> insertRoot =
2458 inserts->ElementAt(i)->GetDefaultContent();
2459 if (insertRoot) {
2460 PRUint32 j;
2461 for (j = 0; j < insertRoot->GetChildCount(); ++j) {
2462 nsCOMPtr<nsIContent> child = insertRoot->GetChildAt(j);
2463 rv = child->BindToTree(aDocument, aInsertParent,
2464 aBinding->GetBoundElement(), allowScripts);
2465 NS_ENSURE_SUCCESS(rv, rv);
2467 #ifdef MOZ_XUL
2468 if (xulDoc) {
2469 xulDoc->AddSubtreeToDocument(child);
2471 #endif
2477 return NS_OK;
2480 nsresult
2481 nsGenericElement::BindToTree(nsIDocument* aDocument, nsIContent* aParent,
2482 nsIContent* aBindingParent,
2483 PRBool aCompileEventHandlers)
2485 NS_PRECONDITION(aParent || aDocument, "Must have document if no parent!");
2486 NS_PRECONDITION(HasSameOwnerDoc(NODE_FROM(aParent, aDocument)),
2487 "Must have the same owner document");
2488 NS_PRECONDITION(!aParent || aDocument == aParent->GetCurrentDoc(),
2489 "aDocument must be current doc of aParent");
2490 NS_PRECONDITION(!GetCurrentDoc(), "Already have a document. Unbind first!");
2491 // Note that as we recurse into the kids, they'll have a non-null parent. So
2492 // only assert if our parent is _changing_ while we have a parent.
2493 NS_PRECONDITION(!GetParent() || aParent == GetParent(),
2494 "Already have a parent. Unbind first!");
2495 NS_PRECONDITION(!GetBindingParent() ||
2496 aBindingParent == GetBindingParent() ||
2497 (!aBindingParent && aParent &&
2498 aParent->GetBindingParent() == GetBindingParent()),
2499 "Already have a binding parent. Unbind first!");
2500 NS_PRECONDITION(!aParent || !aDocument ||
2501 !aParent->HasFlag(NODE_FORCE_XBL_BINDINGS),
2502 "Parent in document but flagged as forcing XBL");
2503 NS_PRECONDITION(aBindingParent != this,
2504 "Content must not be its own binding parent");
2505 NS_PRECONDITION(!IsRootOfNativeAnonymousSubtree() ||
2506 aBindingParent == aParent,
2507 "Native anonymous content must have its parent as its "
2508 "own binding parent");
2510 if (!aBindingParent && aParent) {
2511 aBindingParent = aParent->GetBindingParent();
2514 #ifdef MOZ_XUL
2515 // First set the binding parent
2516 nsXULElement* xulElem = nsXULElement::FromContent(this);
2517 if (xulElem) {
2518 xulElem->SetXULBindingParent(aBindingParent);
2520 else
2521 #endif
2523 if (aBindingParent) {
2524 nsDOMSlots *slots = GetDOMSlots();
2526 if (!slots) {
2527 return NS_ERROR_OUT_OF_MEMORY;
2530 slots->mBindingParent = aBindingParent; // Weak, so no addref happens.
2533 NS_ASSERTION(!aBindingParent || IsRootOfNativeAnonymousSubtree() ||
2534 !HasFlag(NODE_IS_IN_ANONYMOUS_SUBTREE) ||
2535 (aParent && aParent->IsInNativeAnonymousSubtree()),
2536 "Trying to re-bind content from native anonymous subtree to "
2537 "non-native anonymous parent!");
2538 if (IsRootOfNativeAnonymousSubtree() ||
2539 aParent && aParent->IsInNativeAnonymousSubtree()) {
2540 SetFlags(NODE_IS_IN_ANONYMOUS_SUBTREE);
2543 PRBool hadForceXBL = HasFlag(NODE_FORCE_XBL_BINDINGS);
2545 // Now set the parent and set the "Force attach xbl" flag if needed.
2546 if (aParent) {
2547 mParentPtrBits = reinterpret_cast<PtrBits>(aParent) | PARENT_BIT_PARENT_IS_CONTENT;
2549 if (aParent->HasFlag(NODE_FORCE_XBL_BINDINGS)) {
2550 SetFlags(NODE_FORCE_XBL_BINDINGS);
2553 else {
2554 mParentPtrBits = reinterpret_cast<PtrBits>(aDocument);
2557 // XXXbz sXBL/XBL2 issue!
2559 // Finally, set the document
2560 if (aDocument) {
2561 // Notify XBL- & nsIAnonymousContentCreator-generated
2562 // anonymous content that the document is changing.
2563 // XXXbz ordering issues here? Probably not, since ChangeDocumentFor is
2564 // just pretty broken anyway.... Need to get it working.
2565 // XXXbz XBL doesn't handle this (asserts), and we don't really want
2566 // to be doing this during parsing anyway... sort this out.
2567 // aDocument->BindingManager()->ChangeDocumentFor(this, nsnull,
2568 // aDocument);
2570 // Being added to a document.
2571 mParentPtrBits |= PARENT_BIT_INDOCUMENT;
2573 // Unset this flag since we now really are in a document.
2574 UnsetFlags(NODE_FORCE_XBL_BINDINGS);
2577 // If NODE_FORCE_XBL_BINDINGS was set we might have anonymous children
2578 // that also need to be told that they are moving.
2579 nsresult rv;
2580 if (hadForceXBL) {
2581 nsIDocument* ownerDoc = GetOwnerDoc();
2582 if (ownerDoc) {
2583 nsBindingManager* bmgr = ownerDoc->BindingManager();
2585 // First check if we have a binding...
2586 nsXBLBinding* contBinding =
2587 GetFirstBindingWithContent(bmgr, this);
2588 if (contBinding) {
2589 nsCOMPtr<nsIContent> anonRoot = contBinding->GetAnonymousContent();
2590 PRBool allowScripts = contBinding->AllowScripts();
2591 PRUint32 i;
2592 for (i = 0; i < anonRoot->GetChildCount(); ++i) {
2593 nsCOMPtr<nsIContent> child = anonRoot->GetChildAt(i);
2594 rv = child->BindToTree(aDocument, this, this, allowScripts);
2595 NS_ENSURE_SUCCESS(rv, rv);
2598 // ...then check if we have content in insertion points that are
2599 // direct children of the <content>
2600 rv = BindNodesInInsertPoints(contBinding, this, aDocument);
2601 NS_ENSURE_SUCCESS(rv, rv);
2604 // ...and finally check if we're in a binding where we have content in
2605 // insertion points.
2606 if (aBindingParent) {
2607 nsXBLBinding* binding = bmgr->GetBinding(aBindingParent);
2608 if (binding) {
2609 rv = BindNodesInInsertPoints(binding, this, aDocument);
2610 NS_ENSURE_SUCCESS(rv, rv);
2616 UpdateEditableState();
2618 // Now recurse into our kids
2619 PRUint32 i;
2620 // Don't call GetChildCount() here since that'll make XUL generate
2621 // template children, which we're not in a consistent enough state for.
2622 // Additionally, there's not really a need to generate the children here.
2623 for (i = 0; i < mAttrsAndChildren.ChildCount(); ++i) {
2624 // The child can remove itself from the parent in BindToTree.
2625 nsCOMPtr<nsIContent> child = mAttrsAndChildren.ChildAt(i);
2626 rv = child->BindToTree(aDocument, this, aBindingParent,
2627 aCompileEventHandlers);
2628 NS_ENSURE_SUCCESS(rv, rv);
2631 nsNodeUtils::ParentChainChanged(this);
2633 // XXXbz script execution during binding can trigger some of these
2634 // postcondition asserts.... But we do want that, since things will
2635 // generally be quite broken when that happens.
2636 NS_POSTCONDITION(aDocument == GetCurrentDoc(), "Bound to wrong document");
2637 NS_POSTCONDITION(aParent == GetParent(), "Bound to wrong parent");
2638 NS_POSTCONDITION(aBindingParent == GetBindingParent(),
2639 "Bound to wrong binding parent");
2641 return NS_OK;
2644 void
2645 nsGenericElement::UnbindFromTree(PRBool aDeep, PRBool aNullParent)
2647 NS_PRECONDITION(aDeep || (!GetCurrentDoc() && !GetBindingParent()),
2648 "Shallow unbind won't clear document and binding parent on "
2649 "kids!");
2650 // Make sure to unbind this node before doing the kids
2651 nsIDocument *document =
2652 HasFlag(NODE_FORCE_XBL_BINDINGS) ? GetOwnerDoc() : GetCurrentDoc();
2653 if (document) {
2654 // Notify XBL- & nsIAnonymousContentCreator-generated
2655 // anonymous content that the document is changing.
2656 document->BindingManager()->ChangeDocumentFor(this, document, nsnull);
2658 if (HasAttr(kNameSpaceID_XLink, nsGkAtoms::href)) {
2659 document->ForgetLink(this);
2662 document->ClearBoxObjectFor(this);
2665 // Unset things in the reverse order from how we set them in BindToTree
2666 mParentPtrBits = aNullParent ? 0 : mParentPtrBits & ~PARENT_BIT_INDOCUMENT;
2668 // Unset this since that's what the old code effectively did.
2669 UnsetFlags(NODE_FORCE_XBL_BINDINGS);
2671 #ifdef MOZ_XUL
2672 nsXULElement* xulElem = nsXULElement::FromContent(this);
2673 if (xulElem) {
2674 xulElem->SetXULBindingParent(nsnull);
2676 else
2677 #endif
2679 nsDOMSlots *slots = GetExistingDOMSlots();
2680 if (slots) {
2681 slots->mBindingParent = nsnull;
2685 if (aDeep) {
2686 // Do the kids. Don't call GetChildCount() here since that'll force
2687 // XUL to generate template children, which there is no need for since
2688 // all we're going to do is unbind them anyway.
2689 PRUint32 i, n = mAttrsAndChildren.ChildCount();
2691 for (i = 0; i < n; ++i) {
2692 // Note that we pass PR_FALSE for aNullParent here, since we don't want
2693 // the kids to forget us. We _do_ want them to forget their binding
2694 // parent, though, since this only walks non-anonymous kids.
2695 mAttrsAndChildren.ChildAt(i)->UnbindFromTree(PR_TRUE, PR_FALSE);
2699 nsNodeUtils::ParentChainChanged(this);
2702 nsresult
2703 nsGenericElement::PreHandleEvent(nsEventChainPreVisitor& aVisitor)
2705 return nsGenericElement::doPreHandleEvent(this, aVisitor);
2708 static nsIContent*
2709 FindNativeAnonymousSubtreeOwner(nsIContent* aContent)
2711 if (aContent->IsInNativeAnonymousSubtree()) {
2712 PRBool isNativeAnon = PR_FALSE;
2713 while (aContent && !isNativeAnon) {
2714 isNativeAnon = aContent->IsRootOfNativeAnonymousSubtree();
2715 aContent = aContent->GetParent();
2718 return aContent;
2721 nsresult
2722 nsGenericElement::doPreHandleEvent(nsIContent* aContent,
2723 nsEventChainPreVisitor& aVisitor)
2725 //FIXME! Document how this event retargeting works, Bug 329124.
2726 aVisitor.mCanHandle = PR_TRUE;
2728 // Don't propagate mouseover and mouseout events when mouse is moving
2729 // inside native anonymous content.
2730 PRBool isAnonForEvents = aContent->IsRootOfNativeAnonymousSubtree();
2731 if ((aVisitor.mEvent->message == NS_MOUSE_ENTER_SYNTH ||
2732 aVisitor.mEvent->message == NS_MOUSE_EXIT_SYNTH) &&
2733 // Check if we should stop event propagation when event has just been
2734 // dispatched or when we're about to propagate from
2735 // native anonymous subtree.
2736 ((static_cast<nsISupports*>(aContent) == aVisitor.mEvent->originalTarget &&
2737 !aContent->IsInNativeAnonymousSubtree()) || isAnonForEvents)) {
2738 nsCOMPtr<nsIContent> relatedTarget =
2739 do_QueryInterface(static_cast<nsMouseEvent*>
2740 (aVisitor.mEvent)->relatedTarget);
2741 if (relatedTarget &&
2742 relatedTarget->GetOwnerDoc() == aContent->GetOwnerDoc()) {
2744 // If current target is anonymous for events or we know that related
2745 // target is descendant of an element which is anonymous for events,
2746 // we may want to stop event propagation.
2747 // If aContent is the original target, aVisitor.mRelatedTargetIsInAnon
2748 // must be updated.
2749 if (isAnonForEvents || aVisitor.mRelatedTargetIsInAnon ||
2750 (aVisitor.mEvent->originalTarget == aContent &&
2751 (aVisitor.mRelatedTargetIsInAnon =
2752 relatedTarget->IsInNativeAnonymousSubtree()))) {
2753 nsIContent* anonOwner = FindNativeAnonymousSubtreeOwner(aContent);
2754 if (anonOwner) {
2755 nsIContent* anonOwnerRelated =
2756 FindNativeAnonymousSubtreeOwner(relatedTarget);
2757 if (anonOwnerRelated) {
2758 // Note, anonOwnerRelated may still be inside some other
2759 // native anonymous subtree. The case where anonOwner is still
2760 // inside native anonymous subtree will be handled when event
2761 // propagates up in the DOM tree.
2762 while (anonOwner != anonOwnerRelated &&
2763 anonOwnerRelated->IsInNativeAnonymousSubtree()) {
2764 anonOwnerRelated = FindNativeAnonymousSubtreeOwner(anonOwnerRelated);
2766 if (anonOwner == anonOwnerRelated) {
2767 #ifdef DEBUG_smaug
2768 nsCOMPtr<nsIContent> originalTarget =
2769 do_QueryInterface(aVisitor.mEvent->originalTarget);
2770 nsAutoString ot, ct, rt;
2771 if (originalTarget) {
2772 originalTarget->Tag()->ToString(ot);
2774 aContent->Tag()->ToString(ct);
2775 relatedTarget->Tag()->ToString(rt);
2776 printf("Stopping %s propagation:"
2777 "\n\toriginalTarget=%s \n\tcurrentTarget=%s %s"
2778 "\n\trelatedTarget=%s %s \n%s",
2779 (aVisitor.mEvent->message == NS_MOUSE_ENTER_SYNTH)
2780 ? "mouseover" : "mouseout",
2781 NS_ConvertUTF16toUTF8(ot).get(),
2782 NS_ConvertUTF16toUTF8(ct).get(),
2783 isAnonForEvents
2784 ? "(is native anonymous)"
2785 : (aContent->IsInNativeAnonymousSubtree()
2786 ? "(is in native anonymous subtree)" : ""),
2787 NS_ConvertUTF16toUTF8(rt).get(),
2788 relatedTarget->IsInNativeAnonymousSubtree()
2789 ? "(is in native anonymous subtree)" : "",
2790 (originalTarget && relatedTarget->FindFirstNonNativeAnonymous() ==
2791 originalTarget->FindFirstNonNativeAnonymous())
2792 ? "" : "Wrong event propagation!?!\n");
2793 #endif
2794 aVisitor.mParentTarget = nsnull;
2795 // Event should not propagate to non-anon content.
2796 aVisitor.mCanHandle = isAnonForEvents;
2797 return NS_OK;
2805 nsIContent* parent = aContent->GetParent();
2806 // Event may need to be retargeted if aContent is the root of a native
2807 // anonymous content subtree or event is dispatched somewhere inside XBL.
2808 if (isAnonForEvents) {
2809 // If a DOM event is explicitly dispatched using node.dispatchEvent(), then
2810 // all the events are allowed even in the native anonymous content..
2811 NS_ASSERTION(aVisitor.mEvent->eventStructType != NS_MUTATION_EVENT ||
2812 aVisitor.mDOMEvent,
2813 "Mutation event dispatched in native anonymous content!?!");
2814 aVisitor.mEventTargetAtParent = parent;
2815 } else if (parent && aVisitor.mOriginalTargetIsInAnon) {
2816 nsCOMPtr<nsIContent> content(do_QueryInterface(aVisitor.mEvent->target));
2817 if (content && content->GetBindingParent() == parent) {
2818 aVisitor.mEventTargetAtParent = parent;
2822 // check for an anonymous parent
2823 // XXX XBL2/sXBL issue
2824 nsIDocument* ownerDoc = aContent->GetOwnerDoc();
2825 if (ownerDoc) {
2826 nsIContent* insertionParent = ownerDoc->BindingManager()->
2827 GetInsertionParent(aContent);
2828 NS_ASSERTION(!(aVisitor.mEventTargetAtParent && insertionParent &&
2829 aVisitor.mEventTargetAtParent != insertionParent),
2830 "Retargeting and having insertion parent!");
2831 if (insertionParent) {
2832 parent = insertionParent;
2836 if (parent) {
2837 aVisitor.mParentTarget = parent;
2838 } else {
2839 aVisitor.mParentTarget = aContent->GetCurrentDoc();
2841 return NS_OK;
2844 nsresult
2845 nsGenericElement::PostHandleEvent(nsEventChainPostVisitor& /*aVisitor*/)
2847 return NS_OK;
2850 nsresult
2851 nsGenericElement::DispatchDOMEvent(nsEvent* aEvent,
2852 nsIDOMEvent* aDOMEvent,
2853 nsPresContext* aPresContext,
2854 nsEventStatus* aEventStatus)
2856 return nsEventDispatcher::DispatchDOMEvent(static_cast<nsIContent*>(this),
2857 aEvent, aDOMEvent,
2858 aPresContext, aEventStatus);
2861 nsIAtom*
2862 nsGenericElement::GetID() const
2864 if (!HasFlag(NODE_MAY_HAVE_ID)) {
2865 return nsnull;
2868 nsIAtom* IDName = GetIDAttributeName();
2869 if (IDName) {
2870 const nsAttrValue* attrVal = mAttrsAndChildren.GetAttr(IDName);
2871 if (attrVal){
2872 if (attrVal->Type() == nsAttrValue::eAtom) {
2873 return attrVal->GetAtomValue();
2875 if(attrVal->IsEmptyString()){
2876 return nsnull;
2878 // Check if the ID has been stored as a string.
2879 // This would occur if the ID attribute name changed after
2880 // the ID was parsed.
2881 if (attrVal->Type() == nsAttrValue::eString) {
2882 nsAutoString idVal(attrVal->GetStringValue());
2884 // Create an atom from the value and set it into the attribute list.
2885 const_cast<nsAttrValue*>(attrVal)->ParseAtom(idVal);
2886 return attrVal->GetAtomValue();
2890 return nsnull;
2893 const nsAttrValue*
2894 nsGenericElement::DoGetClasses() const
2896 NS_NOTREACHED("Shouldn't ever be called");
2897 return nsnull;
2900 NS_IMETHODIMP
2901 nsGenericElement::WalkContentStyleRules(nsRuleWalker* aRuleWalker)
2903 return NS_OK;
2906 nsICSSStyleRule*
2907 nsGenericElement::GetInlineStyleRule()
2909 return nsnull;
2912 NS_IMETHODIMP
2913 nsGenericElement::SetInlineStyleRule(nsICSSStyleRule* aStyleRule,
2914 PRBool aNotify)
2916 NS_NOTYETIMPLEMENTED("nsGenericElement::SetInlineStyleRule");
2917 return NS_ERROR_NOT_IMPLEMENTED;
2920 NS_IMETHODIMP_(PRBool)
2921 nsGenericElement::IsAttributeMapped(const nsIAtom* aAttribute) const
2923 return PR_FALSE;
2926 nsChangeHint
2927 nsGenericElement::GetAttributeChangeHint(const nsIAtom* aAttribute,
2928 PRInt32 aModType) const
2930 return nsChangeHint(0);
2933 nsIAtom *
2934 nsGenericElement::GetIDAttributeName() const
2936 return mNodeInfo->GetIDAttributeAtom();
2939 nsIAtom *
2940 nsGenericElement::GetClassAttributeName() const
2942 return nsnull;
2945 PRBool
2946 nsGenericElement::FindAttributeDependence(const nsIAtom* aAttribute,
2947 const MappedAttributeEntry* const aMaps[],
2948 PRUint32 aMapCount)
2950 for (PRUint32 mapindex = 0; mapindex < aMapCount; ++mapindex) {
2951 for (const MappedAttributeEntry* map = aMaps[mapindex];
2952 map->attribute; ++map) {
2953 if (aAttribute == *map->attribute) {
2954 return PR_TRUE;
2959 return PR_FALSE;
2962 already_AddRefed<nsINodeInfo>
2963 nsGenericElement::GetExistingAttrNameFromQName(const nsAString& aStr) const
2965 const nsAttrName* name = InternalGetExistingAttrNameFromQName(aStr);
2966 if (!name) {
2967 return nsnull;
2970 nsINodeInfo* nodeInfo;
2971 if (name->IsAtom()) {
2972 nodeInfo = mNodeInfo->NodeInfoManager()->GetNodeInfo(name->Atom(), nsnull,
2973 kNameSpaceID_None).get();
2975 else {
2976 NS_ADDREF(nodeInfo = name->NodeInfo());
2979 return nodeInfo;
2982 already_AddRefed<nsIURI>
2983 nsGenericElement::GetBaseURI() const
2985 nsIDocument* doc = GetOwnerDoc();
2986 if (!doc) {
2987 // We won't be able to do security checks, etc. So don't go any
2988 // further. That said, this really shouldn't happen...
2989 NS_ERROR("Element without owner document");
2990 return nsnull;
2993 // Our base URL depends on whether we have an xml:base attribute, as
2994 // well as on whether any of our ancestors do.
2995 nsCOMPtr<nsIURI> parentBase;
2997 nsIContent *parent = GetParent();
2998 if (parent) {
2999 parentBase = parent->GetBaseURI();
3000 } else {
3001 // No parent, so just use the document (we must be the root or not in the
3002 // tree).
3003 parentBase = doc->GetBaseURI();
3006 // Now check for an xml:base attr
3007 nsAutoString value;
3008 GetAttr(kNameSpaceID_XML, nsGkAtoms::base, value);
3009 if (value.IsEmpty()) {
3010 // No xml:base, so we just use the parent's base URL
3011 nsIURI *base = nsnull;
3012 parentBase.swap(base);
3014 return base;
3017 nsCOMPtr<nsIURI> ourBase;
3018 nsresult rv = NS_NewURI(getter_AddRefs(ourBase), value,
3019 doc->GetDocumentCharacterSet().get(), parentBase);
3020 if (NS_SUCCEEDED(rv)) {
3021 // do a security check, almost the same as nsDocument::SetBaseURL()
3022 rv = nsContentUtils::GetSecurityManager()->
3023 CheckLoadURIWithPrincipal(NodePrincipal(), ourBase,
3024 nsIScriptSecurityManager::STANDARD);
3027 nsIURI *base;
3028 if (NS_FAILED(rv)) {
3029 base = parentBase;
3030 } else {
3031 base = ourBase;
3034 NS_IF_ADDREF(base);
3036 return base;
3039 PRBool
3040 nsGenericElement::IsLink(nsIURI** aURI) const
3042 *aURI = nsnull;
3043 return PR_FALSE;
3046 void
3047 nsGenericElement::SetFocus(nsPresContext* aPresContext)
3049 // Traditionally focusable elements can take focus as long as they don't set
3050 // the disabled attribute
3052 nsCOMPtr<nsIPresShell> presShell = aPresContext->PresShell();
3053 if (!presShell) {
3054 return;
3056 nsIFrame* frame = presShell->GetPrimaryFrameFor(this);
3057 if (frame && frame->IsFocusable() &&
3058 aPresContext->EventStateManager()->SetContentState(this,
3059 NS_EVENT_STATE_FOCUS)) {
3060 presShell->ScrollContentIntoView(this, NS_PRESSHELL_SCROLL_IF_NOT_VISIBLE,
3061 NS_PRESSHELL_SCROLL_IF_NOT_VISIBLE);
3065 // static
3066 PRBool
3067 nsGenericElement::ShouldFocus(nsIContent *aContent)
3069 // Default to false, since if the document is not attached to a window,
3070 // we should not focus any of its content.
3071 PRBool visible = PR_FALSE;
3073 // Figure out if we're focusing an element in an inactive (hidden)
3074 // tab (whose docshell is not visible), if so, drop this focus
3075 // request on the floor
3077 nsIDocument *document = aContent->GetDocument();
3079 if (document) {
3080 nsIScriptGlobalObject *sgo = document->GetScriptGlobalObject();
3082 if (sgo) {
3083 nsCOMPtr<nsIWebNavigation> webNav(do_GetInterface(sgo));
3084 nsCOMPtr<nsIBaseWindow> baseWin(do_QueryInterface(webNav));
3086 if (baseWin) {
3087 baseWin->GetVisibility(&visible);
3092 return visible;
3095 // static
3096 PRBool
3097 nsGenericElement::ShouldBlur(nsIContent *aContent)
3099 // Determine if the current element is focused, if it is not focused
3100 // then we should not try to blur
3101 PRBool isFocused = PR_FALSE;
3103 nsIDocument *document = aContent->GetDocument();
3105 if (document) {
3106 nsPIDOMWindow *win = document->GetWindow();
3108 if (win) {
3109 nsCOMPtr<nsIFocusController> focusController =
3110 win->GetRootFocusController();
3112 if (focusController) {
3113 nsCOMPtr<nsIDOMElement> focusedElement;
3114 focusController->GetFocusedElement(getter_AddRefs(focusedElement));
3115 nsCOMPtr<nsIDOMElement> domElement = do_QueryInterface(aContent);
3116 //when the element is the same as the focused element, blur it
3117 if (domElement == focusedElement)
3118 isFocused = PR_TRUE;
3123 return isFocused;
3126 nsIContent*
3127 nsGenericElement::GetBindingParent() const
3129 nsDOMSlots *slots = GetExistingDOMSlots();
3131 if (slots) {
3132 return slots->mBindingParent;
3134 return nsnull;
3137 PRBool
3138 nsGenericElement::IsNodeOfType(PRUint32 aFlags) const
3140 return !(aFlags & ~(eCONTENT | eELEMENT));
3143 //----------------------------------------------------------------------
3145 // virtual
3146 void
3147 nsGenericElement::SetMayHaveFrame(PRBool aMayHaveFrame)
3149 if (aMayHaveFrame) {
3150 SetFlags(NODE_MAY_HAVE_FRAME);
3151 } else {
3152 UnsetFlags(NODE_MAY_HAVE_FRAME);
3156 // virtual
3157 PRBool
3158 nsGenericElement::MayHaveFrame() const
3160 return HasFlag(NODE_MAY_HAVE_FRAME);
3163 PRUint32
3164 nsGenericElement::GetScriptTypeID() const
3166 PtrBits flags = GetFlags();
3168 /* 4 bits reserved for script-type ID. */
3169 return (flags >> NODE_SCRIPT_TYPE_OFFSET) & 0x000F;
3172 nsresult
3173 nsGenericElement::SetScriptTypeID(PRUint32 aLang)
3175 if ((aLang & 0x000F) != aLang) {
3176 NS_ERROR("script ID too large!");
3177 return NS_ERROR_FAILURE;
3179 /* SetFlags will just mask in the specific flags set, leaving existing
3180 ones alone. So we must clear all the bits first */
3181 UnsetFlags(0x000FU << NODE_SCRIPT_TYPE_OFFSET);
3182 SetFlags(aLang << NODE_SCRIPT_TYPE_OFFSET);
3183 return NS_OK;
3186 nsresult
3187 nsGenericElement::InsertChildAt(nsIContent* aKid,
3188 PRUint32 aIndex,
3189 PRBool aNotify)
3191 NS_PRECONDITION(aKid, "null ptr");
3193 return doInsertChildAt(aKid, aIndex, aNotify, this, GetCurrentDoc(),
3194 mAttrsAndChildren);
3198 /* static */
3199 nsresult
3200 nsGenericElement::doInsertChildAt(nsIContent* aKid, PRUint32 aIndex,
3201 PRBool aNotify, nsIContent* aParent,
3202 nsIDocument* aDocument,
3203 nsAttrAndChildArray& aChildArray)
3205 NS_PRECONDITION(aParent || aDocument, "Must have document if no parent!");
3206 NS_PRECONDITION(!aParent || aParent->GetCurrentDoc() == aDocument,
3207 "Incorrect aDocument");
3209 nsresult rv;
3210 nsINode* container = NODE_FROM(aParent, aDocument);
3212 if (!container->HasSameOwnerDoc(aKid)) {
3213 nsCOMPtr<nsIDOMNode> kid = do_QueryInterface(aKid, &rv);
3214 NS_ENSURE_SUCCESS(rv, rv);
3216 PRUint16 nodeType = 0;
3217 rv = kid->GetNodeType(&nodeType);
3218 NS_ENSURE_SUCCESS(rv, rv);
3220 nsCOMPtr<nsIDOM3Document> domDoc =
3221 do_QueryInterface(container->GetOwnerDoc());
3223 // DocumentType nodes are the only nodes that can have a null
3224 // ownerDocument according to the DOM spec, and we need to allow
3225 // inserting them w/o calling AdoptNode().
3227 if (domDoc && (nodeType != nsIDOMNode::DOCUMENT_TYPE_NODE ||
3228 aKid->GetOwnerDoc())) {
3229 nsCOMPtr<nsIDOMNode> adoptedKid;
3230 rv = domDoc->AdoptNode(kid, getter_AddRefs(adoptedKid));
3231 NS_ENSURE_SUCCESS(rv, rv);
3233 NS_ASSERTION(adoptedKid == kid, "Uh, adopt node changed nodes?");
3237 PRUint32 childCount = aChildArray.ChildCount();
3238 NS_ENSURE_TRUE(aIndex <= childCount, NS_ERROR_ILLEGAL_VALUE);
3240 nsMutationGuard::DidMutate();
3242 PRBool isAppend = (aIndex == childCount);
3244 mozAutoDocUpdate updateBatch(aDocument, UPDATE_CONTENT_MODEL, aNotify);
3246 rv = aChildArray.InsertChildAt(aKid, aIndex);
3247 NS_ENSURE_SUCCESS(rv, rv);
3249 rv = aKid->BindToTree(aDocument, aParent, nsnull, PR_TRUE);
3250 if (NS_FAILED(rv)) {
3251 aChildArray.RemoveChildAt(aIndex);
3252 aKid->UnbindFromTree();
3253 return rv;
3256 // The kid may have removed its parent from the document, so recheck that
3257 // that's still in the document before proceeding. Also, the kid may have
3258 // just removed itself, in which case we don't really want to fire
3259 // ContentAppended or a mutation event.
3260 // XXXbz What if the kid just moved us in the document? Scripts suck. We
3261 // really need to stop running them while we're in the middle of modifying
3262 // the DOM....
3264 if (aNotify && aKid->GetNodeParent() == container) {
3265 // Note that we always want to call ContentInserted when things are added
3266 // as kids to documents
3267 if (aParent && isAppend) {
3268 nsNodeUtils::ContentAppended(aParent, aIndex);
3269 } else {
3270 nsNodeUtils::ContentInserted(container, aKid, aIndex);
3273 if (nsContentUtils::HasMutationListeners(aKid,
3274 NS_EVENT_BITS_MUTATION_NODEINSERTED, container)) {
3275 mozAutoRemovableBlockerRemover blockerRemover;
3277 nsMutationEvent mutation(PR_TRUE, NS_MUTATION_NODEINSERTED);
3278 mutation.mRelatedNode = do_QueryInterface(container);
3280 mozAutoSubtreeModified subtree(container->GetOwnerDoc(), container);
3281 nsEventDispatcher::Dispatch(aKid, nsnull, &mutation);
3285 return NS_OK;
3288 nsresult
3289 nsGenericElement::RemoveChildAt(PRUint32 aIndex, PRBool aNotify)
3291 nsCOMPtr<nsIContent> oldKid = mAttrsAndChildren.GetSafeChildAt(aIndex);
3292 NS_ASSERTION(oldKid == GetChildAt(aIndex), "Unexpected child in RemoveChildAt");
3294 if (oldKid) {
3295 return doRemoveChildAt(aIndex, aNotify, oldKid, this, GetCurrentDoc(),
3296 mAttrsAndChildren);
3299 return NS_OK;
3302 /* static */
3303 nsresult
3304 nsGenericElement::doRemoveChildAt(PRUint32 aIndex, PRBool aNotify,
3305 nsIContent* aKid, nsIContent* aParent,
3306 nsIDocument* aDocument,
3307 nsAttrAndChildArray& aChildArray)
3309 NS_PRECONDITION(aParent || aDocument, "Must have document if no parent!");
3310 NS_PRECONDITION(!aParent || aParent->GetCurrentDoc() == aDocument,
3311 "Incorrect aDocument");
3313 #ifdef ACCESSIBILITY
3314 // A11y needs to be notified of content removals first, so accessibility
3315 // events can be fired before any changes occur
3316 if (aNotify && aDocument) {
3317 nsIPresShell *presShell = aDocument->GetPrimaryShell();
3318 if (presShell && presShell->IsAccessibilityActive()) {
3319 nsCOMPtr<nsIAccessibilityService> accService =
3320 do_GetService("@mozilla.org/accessibilityService;1");
3321 if (accService) {
3322 accService->InvalidateSubtreeFor(presShell, aKid,
3323 nsIAccessibleEvent::EVENT_DOM_DESTROY);
3327 #endif
3329 nsMutationGuard::DidMutate();
3331 nsINode* container = NODE_FROM(aParent, aDocument);
3333 NS_PRECONDITION(aKid && aKid->GetParent() == aParent &&
3334 aKid == container->GetChildAt(aIndex) &&
3335 container->IndexOf(aKid) == (PRInt32)aIndex, "Bogus aKid");
3337 mozAutoDocUpdate updateBatch(aDocument, UPDATE_CONTENT_MODEL, aNotify);
3339 nsMutationGuard guard;
3341 mozAutoSubtreeModified subtree(nsnull, nsnull);
3342 if (aNotify &&
3343 nsContentUtils::HasMutationListeners(aKid,
3344 NS_EVENT_BITS_MUTATION_NODEREMOVED, container)) {
3345 mozAutoRemovableBlockerRemover blockerRemover;
3347 nsMutationEvent mutation(PR_TRUE, NS_MUTATION_NODEREMOVED);
3348 mutation.mRelatedNode = do_QueryInterface(container);
3350 subtree.UpdateTarget(container->GetOwnerDoc(), container);
3351 nsEventDispatcher::Dispatch(aKid, nsnull, &mutation);
3354 // Someone may have removed the kid or any of its siblings while that event
3355 // was processing.
3356 if (guard.Mutated(0)) {
3357 aIndex = container->IndexOf(aKid);
3358 if (static_cast<PRInt32>(aIndex) < 0) {
3359 return NS_OK;
3363 aChildArray.RemoveChildAt(aIndex);
3365 if (aNotify) {
3366 nsNodeUtils::ContentRemoved(container, aKid, aIndex);
3369 aKid->UnbindFromTree();
3371 return NS_OK;
3374 /* static */
3375 nsresult
3376 nsGenericElement::DispatchEvent(nsPresContext* aPresContext,
3377 nsEvent* aEvent,
3378 nsIContent* aTarget,
3379 PRBool aFullDispatch,
3380 nsEventStatus* aStatus)
3382 NS_PRECONDITION(aTarget, "Must have target");
3383 NS_PRECONDITION(aEvent, "Must have source event");
3384 NS_PRECONDITION(aStatus, "Null out param?");
3386 if (!aPresContext) {
3387 return NS_OK;
3390 nsCOMPtr<nsIPresShell> shell = aPresContext->GetPresShell();
3391 if (!shell) {
3392 return NS_OK;
3395 if (aFullDispatch) {
3396 return shell->HandleEventWithTarget(aEvent, nsnull, aTarget, aStatus);
3399 return shell->HandleDOMEventWithTarget(aTarget, aEvent, aStatus);
3402 /* static */
3403 nsresult
3404 nsGenericElement::DispatchClickEvent(nsPresContext* aPresContext,
3405 nsInputEvent* aSourceEvent,
3406 nsIContent* aTarget,
3407 PRBool aFullDispatch,
3408 nsEventStatus* aStatus)
3410 NS_PRECONDITION(aTarget, "Must have target");
3411 NS_PRECONDITION(aSourceEvent, "Must have source event");
3412 NS_PRECONDITION(aStatus, "Null out param?");
3414 nsMouseEvent event(NS_IS_TRUSTED_EVENT(aSourceEvent), NS_MOUSE_CLICK,
3415 aSourceEvent->widget, nsMouseEvent::eReal);
3416 event.refPoint = aSourceEvent->refPoint;
3417 PRUint32 clickCount = 1;
3418 if (aSourceEvent->eventStructType == NS_MOUSE_EVENT) {
3419 clickCount = static_cast<nsMouseEvent*>(aSourceEvent)->clickCount;
3421 event.clickCount = clickCount;
3422 event.isShift = aSourceEvent->isShift;
3423 event.isControl = aSourceEvent->isControl;
3424 event.isAlt = aSourceEvent->isAlt;
3425 event.isMeta = aSourceEvent->isMeta;
3427 return DispatchEvent(aPresContext, &event, aTarget, aFullDispatch, aStatus);
3430 nsIFrame*
3431 nsGenericElement::GetPrimaryFrame()
3433 nsIDocument* doc = GetCurrentDoc();
3434 if (!doc) {
3435 return nsnull;
3438 return GetPrimaryFrameFor(this, doc);
3441 nsIFrame*
3442 nsGenericElement::GetPrimaryFrame(mozFlushType aType)
3444 nsIDocument* doc = GetCurrentDoc();
3445 if (!doc) {
3446 return nsnull;
3449 // Cause a flush, so we get up-to-date frame
3450 // information
3451 doc->FlushPendingNotifications(aType);
3453 return GetPrimaryFrameFor(this, doc);
3456 /* static */
3457 nsIFrame*
3458 nsGenericElement::GetPrimaryFrameFor(nsIContent* aContent,
3459 nsIDocument* aDocument)
3461 // Get presentation shell 0
3462 nsIPresShell *presShell = aDocument->GetPrimaryShell();
3463 if (!presShell) {
3464 return nsnull;
3467 return presShell->GetPrimaryFrameFor(aContent);
3470 void
3471 nsGenericElement::DestroyContent()
3473 nsIDocument *document = GetOwnerDoc();
3474 if (document) {
3475 document->BindingManager()->ChangeDocumentFor(this, document, nsnull);
3476 document->ClearBoxObjectFor(this);
3479 // XXX We really should let cycle collection do this, but that currently still
3480 // leaks (see https://bugzilla.mozilla.org/show_bug.cgi?id=406684).
3481 ReleaseWrapper();
3483 PRUint32 i, count = mAttrsAndChildren.ChildCount();
3484 for (i = 0; i < count; ++i) {
3485 // The child can remove itself from the parent in BindToTree.
3486 mAttrsAndChildren.ChildAt(i)->DestroyContent();
3490 void
3491 nsGenericElement::SaveSubtreeState()
3493 PRUint32 i, count = mAttrsAndChildren.ChildCount();
3494 for (i = 0; i < count; ++i) {
3495 mAttrsAndChildren.ChildAt(i)->SaveSubtreeState();
3499 //----------------------------------------------------------------------
3501 // Generic DOMNode implementations
3504 * This helper function checks if aChild is the same as aNode or if
3505 * aChild is one of aNode's ancestors. -- jst@citec.fi
3508 NS_IMETHODIMP
3509 nsGenericElement::InsertBefore(nsIDOMNode *aNewChild, nsIDOMNode *aRefChild,
3510 nsIDOMNode **aReturn)
3512 return doReplaceOrInsertBefore(PR_FALSE, aNewChild, aRefChild, this, GetCurrentDoc(),
3513 aReturn);
3516 NS_IMETHODIMP
3517 nsGenericElement::ReplaceChild(nsIDOMNode* aNewChild, nsIDOMNode* aOldChild,
3518 nsIDOMNode** aReturn)
3520 return doReplaceOrInsertBefore(PR_TRUE, aNewChild, aOldChild, this, GetCurrentDoc(),
3521 aReturn);
3524 NS_IMETHODIMP
3525 nsGenericElement::RemoveChild(nsIDOMNode *aOldChild, nsIDOMNode **aReturn)
3527 return doRemoveChild(aOldChild, this, GetCurrentDoc(),
3528 aReturn);
3531 // When replacing, aRefContent is the content being replaced; when
3532 // inserting it's the content before which we're inserting. In the
3533 // latter case it may be null.
3534 static
3535 PRBool IsAllowedAsChild(nsIContent* aNewChild, PRUint16 aNewNodeType,
3536 nsIContent* aParent, nsIDocument* aDocument,
3537 PRBool aIsReplace, nsIContent* aRefContent)
3539 NS_PRECONDITION(aNewChild, "Must have new child");
3540 NS_PRECONDITION(!aIsReplace || aRefContent,
3541 "Must have ref content for replace");
3542 #ifdef DEBUG
3543 PRUint16 debugNodeType = 0;
3544 nsCOMPtr<nsIDOMNode> debugNode(do_QueryInterface(aNewChild));
3545 nsresult debugRv = debugNode->GetNodeType(&debugNodeType);
3547 NS_PRECONDITION(NS_SUCCEEDED(debugRv) && debugNodeType == aNewNodeType,
3548 "Bogus node type passed");
3549 #endif
3551 if (aParent && nsContentUtils::ContentIsDescendantOf(aParent, aNewChild)) {
3552 return PR_FALSE;
3555 // The allowed child nodes differ for documents and elements
3556 switch (aNewNodeType) {
3557 case nsIDOMNode::COMMENT_NODE :
3558 case nsIDOMNode::PROCESSING_INSTRUCTION_NODE :
3559 // OK in both cases
3560 return PR_TRUE;
3561 case nsIDOMNode::TEXT_NODE :
3562 case nsIDOMNode::CDATA_SECTION_NODE :
3563 case nsIDOMNode::ENTITY_REFERENCE_NODE :
3564 // Only allowed under elements
3565 return aParent != nsnull;
3566 case nsIDOMNode::ELEMENT_NODE :
3568 if (aParent) {
3569 // Always ok to have elements under other elements
3570 return PR_TRUE;
3573 nsIContent* rootContent = aDocument->GetRootContent();
3574 if (rootContent) {
3575 // Already have a documentElement, so this is only OK if we're
3576 // replacing it.
3577 return aIsReplace && rootContent == aRefContent;
3580 // We don't have a documentElement yet. Our one remaining constraint is
3581 // that the documentElement must come after the doctype.
3582 if (!aRefContent) {
3583 // Appending is just fine.
3584 return PR_TRUE;
3587 // Now grovel for a doctype
3588 nsCOMPtr<nsIDOMDocument> doc = do_QueryInterface(aDocument);
3589 NS_ASSERTION(doc, "Shouldn't happen");
3590 nsCOMPtr<nsIDOMDocumentType> docType;
3591 doc->GetDoctype(getter_AddRefs(docType));
3592 nsCOMPtr<nsIContent> docTypeContent = do_QueryInterface(docType);
3594 if (!docTypeContent) {
3595 // It's all good.
3596 return PR_TRUE;
3599 PRInt32 doctypeIndex = aDocument->IndexOf(docTypeContent);
3600 PRInt32 insertIndex = aDocument->IndexOf(aRefContent);
3602 // Now we're OK in the following two cases only:
3603 // 1) We're replacing something that's not before the doctype
3604 // 2) We're inserting before something that comes after the doctype
3605 return aIsReplace ? (insertIndex >= doctypeIndex) :
3606 insertIndex > doctypeIndex;
3608 case nsIDOMNode::DOCUMENT_TYPE_NODE :
3610 if (aParent) {
3611 // no doctypes allowed under elements
3612 return PR_FALSE;
3615 nsCOMPtr<nsIDOMDocument> doc = do_QueryInterface(aDocument);
3616 NS_ASSERTION(doc, "Shouldn't happen");
3617 nsCOMPtr<nsIDOMDocumentType> docType;
3618 doc->GetDoctype(getter_AddRefs(docType));
3619 nsCOMPtr<nsIContent> docTypeContent = do_QueryInterface(docType);
3620 if (docTypeContent) {
3621 // Already have a doctype, so this is only OK if we're replacing it
3622 return aIsReplace && docTypeContent == aRefContent;
3625 // We don't have a doctype yet. Our one remaining constraint is
3626 // that the doctype must come before the documentElement.
3627 nsIContent* rootContent = aDocument->GetRootContent();
3628 if (!rootContent) {
3629 // It's all good
3630 return PR_TRUE;
3633 if (!aRefContent) {
3634 // Trying to append a doctype, but have a documentElement
3635 return PR_FALSE;
3638 PRInt32 rootIndex = aDocument->IndexOf(rootContent);
3639 PRInt32 insertIndex = aDocument->IndexOf(aRefContent);
3641 // Now we're OK if and only if insertIndex <= rootIndex. Indeed, either
3642 // we end up replacing aRefContent or we end up before it. Either one is
3643 // ok as long as aRefContent is not after rootContent.
3644 return insertIndex <= rootIndex;
3646 case nsIDOMNode::DOCUMENT_FRAGMENT_NODE :
3648 // Note that for now we only allow nodes inside document fragments if
3649 // they're allowed inside elements. If we ever change this to allow
3650 // doctype nodes in document fragments, we'll need to update this code
3651 if (aParent) {
3652 // All good here
3653 return PR_TRUE;
3656 PRBool sawElement = PR_FALSE;
3657 PRUint32 count = aNewChild->GetChildCount();
3658 for (PRUint32 index = 0; index < count; ++index) {
3659 nsIContent* childContent = aNewChild->GetChildAt(index);
3660 NS_ASSERTION(childContent, "Something went wrong");
3661 if (childContent->IsNodeOfType(nsINode::eELEMENT)) {
3662 if (sawElement) {
3663 // Can't put two elements into a document
3664 return PR_FALSE;
3666 sawElement = PR_TRUE;
3668 // If we can put this content at the the right place, we might be ok;
3669 // if not, we bail out.
3670 nsCOMPtr<nsIDOMNode> childNode(do_QueryInterface(childContent));
3671 PRUint16 type;
3672 childNode->GetNodeType(&type);
3673 if (!IsAllowedAsChild(childContent, type, aParent, aDocument,
3674 aIsReplace, aRefContent)) {
3675 return PR_FALSE;
3679 // Everything in the fragment checked out ok, so we can stick it in here
3680 return PR_TRUE;
3682 default:
3684 * aNewChild is of invalid type.
3686 break;
3689 return PR_FALSE;
3692 /* static */
3693 nsresult
3694 nsGenericElement::doReplaceOrInsertBefore(PRBool aReplace,
3695 nsIDOMNode* aNewChild,
3696 nsIDOMNode* aRefChild,
3697 nsIContent* aParent,
3698 nsIDocument* aDocument,
3699 nsIDOMNode** aReturn)
3701 NS_PRECONDITION(aParent || aDocument, "Must have document if no parent!");
3702 NS_PRECONDITION(!aParent || aParent->GetCurrentDoc() == aDocument,
3703 "Incorrect aDocument");
3705 *aReturn = nsnull;
3707 if (!aNewChild || (aReplace && !aRefChild)) {
3708 return NS_ERROR_NULL_POINTER;
3711 // Keep a strong reference to the node that we'll return to ensure it
3712 // doesn't go away.
3713 nsCOMPtr<nsIDOMNode> returnVal = aReplace ? aRefChild : aNewChild;
3715 nsCOMPtr<nsIContent> refContent;
3716 nsresult res = NS_OK;
3717 PRInt32 insPos;
3719 nsINode* container = NODE_FROM(aParent, aDocument);
3721 // Figure out which index to insert at
3722 if (aRefChild) {
3723 refContent = do_QueryInterface(aRefChild);
3724 insPos = container->IndexOf(refContent);
3725 if (insPos < 0) {
3726 return NS_ERROR_DOM_NOT_FOUND_ERR;
3729 if (aRefChild == aNewChild) {
3730 NS_ADDREF(*aReturn = aNewChild);
3732 return NS_OK;
3734 } else {
3735 insPos = container->GetChildCount();
3738 nsCOMPtr<nsIContent> newContent = do_QueryInterface(aNewChild);
3739 if (!newContent) {
3740 return NS_ERROR_DOM_HIERARCHY_REQUEST_ERR;
3743 PRUint16 nodeType = 0;
3744 res = aNewChild->GetNodeType(&nodeType);
3745 NS_ENSURE_SUCCESS(res, res);
3747 // Make sure that the inserted node is allowed as a child of its new parent.
3748 if (!IsAllowedAsChild(newContent, nodeType, aParent, aDocument, aReplace,
3749 refContent)) {
3750 return NS_ERROR_DOM_HIERARCHY_REQUEST_ERR;
3753 // DocumentType nodes are the only nodes that can have a null
3754 // ownerDocument according to the DOM spec, and we need to allow
3755 // inserting them w/o calling AdoptNode().
3756 if (!container->HasSameOwnerDoc(newContent) &&
3757 (nodeType != nsIDOMNode::DOCUMENT_TYPE_NODE ||
3758 newContent->GetOwnerDoc())) {
3759 nsCOMPtr<nsIDOM3Document> domDoc = do_QueryInterface(aDocument);
3761 if (domDoc) {
3762 nsCOMPtr<nsIDOMNode> adoptedKid;
3763 nsresult rv = domDoc->AdoptNode(aNewChild, getter_AddRefs(adoptedKid));
3764 NS_ENSURE_SUCCESS(rv, rv);
3766 NS_ASSERTION(adoptedKid == aNewChild, "Uh, adopt node changed nodes?");
3770 // We want an update batch when we expect several mutations to be performed,
3771 // which is when we're replacing a node, or when we're inserting a fragment.
3772 mozAutoDocConditionalContentUpdateBatch(aDocument,
3773 aReplace || nodeType == nsIDOMNode::DOCUMENT_FRAGMENT_NODE);
3775 // If we're replacing
3776 if (aReplace) {
3777 // Getting (and addrefing) the following child here is sort of wasteful
3778 // in the common case, but really, it's not that expensive. Get over it.
3779 refContent = container->GetChildAt(insPos + 1);
3781 nsMutationGuard guard;
3783 res = container->RemoveChildAt(insPos, PR_TRUE);
3784 NS_ENSURE_SUCCESS(res, res);
3786 if (guard.Mutated(1)) {
3787 insPos = refContent ? container->IndexOf(refContent) :
3788 container->GetChildCount();
3789 if (insPos < 0) {
3790 return NS_ERROR_DOM_NOT_FOUND_ERR;
3793 // Passing PR_FALSE for aIsReplace since we now have removed the node
3794 // to be replaced.
3795 if (!IsAllowedAsChild(newContent, nodeType, aParent, aDocument,
3796 PR_FALSE, refContent)) {
3797 return NS_ERROR_DOM_HIERARCHY_REQUEST_ERR;
3803 * Check if we're inserting a document fragment. If we are, we need
3804 * to remove the children of the document fragment and add them
3805 * individually (i.e. we don't add the actual document fragment).
3807 if (nodeType == nsIDOMNode::DOCUMENT_FRAGMENT_NODE) {
3808 PRUint32 count = newContent->GetChildCount();
3810 // Copy the children into a separate array to avoid having to deal with
3811 // mutations to the fragment while we're inserting.
3812 nsCOMArray<nsIContent> fragChildren;
3813 if (!fragChildren.SetCapacity(count)) {
3814 return NS_ERROR_OUT_OF_MEMORY;
3816 PRUint32 i;
3817 for (i = 0; i < count; i++) {
3818 nsIContent* child = newContent->GetChildAt(i);
3819 NS_ASSERTION(child->GetCurrentDoc() == nsnull,
3820 "How did we get a child with a current doc?");
3821 fragChildren.AppendObject(child);
3824 // Remove the children from the fragment and flag for possible mutations.
3825 PRBool mutated = PR_FALSE;
3826 for (i = count; i > 0;) {
3827 // We don't need to update i if someone mutates the DOM. The only thing
3828 // that'd happen is that the resulting child list might be unexpected,
3829 // but we should never crash since RemoveChildAt is out-of-bounds safe.
3830 nsMutationGuard guard;
3831 newContent->RemoveChildAt(--i, PR_TRUE);
3832 mutated = mutated || guard.Mutated(1);
3835 // Iterate through the fragment's children, and insert them in the new
3836 // parent
3837 for (i = 0; i < count; ++i) {
3838 // Get the n:th child from the array.
3839 nsIContent* childContent = fragChildren[i];
3841 // If we've had any unexpeted mutations so far we need to recheck that
3842 // the child can still be inserted.
3843 if (mutated) {
3844 // We really only need to update insPos if we *just* got an unexpected
3845 // mutation as opposed to 3 insertions ago. But this is an edgecase so
3846 // no need to over optimize.
3847 insPos = refContent ? container->IndexOf(refContent) :
3848 container->GetChildCount();
3849 if (insPos < 0) {
3850 // Someone seriously messed up the childlist. We have no idea
3851 // where to insert the remaining children, so just bail.
3852 return NS_ERROR_DOM_NOT_FOUND_ERR;
3855 nsCOMPtr<nsIDOMNode> tmpNode = do_QueryInterface(childContent);
3856 PRUint16 tmpType = 0;
3857 tmpNode->GetNodeType(&tmpType);
3859 if (childContent->GetNodeParent() ||
3860 !IsAllowedAsChild(childContent, tmpType, aParent, aDocument, PR_FALSE,
3861 refContent)) {
3862 return NS_ERROR_DOM_HIERARCHY_REQUEST_ERR;
3866 nsMutationGuard guard;
3868 // XXXbz how come no reparenting here? That seems odd...
3869 // Insert the child.
3870 res = container->InsertChildAt(childContent, insPos, PR_TRUE);
3871 NS_ENSURE_SUCCESS(res, res);
3873 // Check to see if any evil mutation events mucked around with the
3874 // child list.
3875 mutated = mutated || guard.Mutated(1);
3877 ++insPos;
3880 else {
3881 // Not inserting a fragment but rather a single node.
3883 // Remove the element from the old parent if one exists
3884 nsINode* oldParent = newContent->GetNodeParent();
3886 if (oldParent) {
3887 PRInt32 removeIndex = oldParent->IndexOf(newContent);
3889 if (removeIndex < 0) {
3890 // newContent is anonymous. We can't deal with this, so just bail
3891 return NS_ERROR_DOM_NOT_SUPPORTED_ERR;
3894 NS_ASSERTION(!(oldParent == container && removeIndex == insPos),
3895 "invalid removeIndex");
3897 nsMutationGuard guard;
3899 res = oldParent->RemoveChildAt(removeIndex, PR_TRUE);
3900 NS_ENSURE_SUCCESS(res, res);
3902 // Adjust insert index if the node we ripped out was a sibling
3903 // of the node we're inserting before
3904 if (oldParent == container && removeIndex < insPos) {
3905 --insPos;
3908 if (guard.Mutated(1)) {
3909 insPos = refContent ? container->IndexOf(refContent) :
3910 container->GetChildCount();
3911 if (insPos < 0) {
3912 // Someone seriously messed up the childlist. We have no idea
3913 // where to insert the new child, so just bail.
3914 return NS_ERROR_DOM_NOT_FOUND_ERR;
3917 if (newContent->GetNodeParent() ||
3918 !IsAllowedAsChild(newContent, nodeType, aParent, aDocument,
3919 PR_FALSE, refContent)) {
3920 return NS_ERROR_DOM_HIERARCHY_REQUEST_ERR;
3925 if (!newContent->IsNodeOfType(eXUL)) {
3926 nsContentUtils::ReparentContentWrapper(newContent, aParent,
3927 container->GetOwnerDoc(),
3928 container->GetOwnerDoc());
3931 res = container->InsertChildAt(newContent, insPos, PR_TRUE);
3932 NS_ENSURE_SUCCESS(res, res);
3935 returnVal.swap(*aReturn);
3937 return res;
3940 /* static */
3941 nsresult
3942 nsGenericElement::doRemoveChild(nsIDOMNode* aOldChild, nsIContent* aParent,
3943 nsIDocument* aDocument, nsIDOMNode** aReturn)
3945 NS_PRECONDITION(aParent || aDocument, "Must have document if no parent!");
3946 NS_PRECONDITION(!aParent || aParent->GetCurrentDoc() == aDocument,
3947 "Incorrect aDocument");
3949 *aReturn = nsnull;
3950 NS_ENSURE_TRUE(aOldChild, NS_ERROR_NULL_POINTER);
3952 nsINode* container = NODE_FROM(aParent, aDocument);
3954 nsCOMPtr<nsIContent> content = do_QueryInterface(aOldChild);
3955 // fix children to be a passed argument
3956 PRInt32 index = container->IndexOf(content);
3957 if (index == -1) {
3958 // aOldChild isn't one of our children.
3959 return NS_ERROR_DOM_NOT_FOUND_ERR;
3962 nsresult rv = container->RemoveChildAt(index, PR_TRUE);
3964 *aReturn = aOldChild;
3965 NS_ADDREF(aOldChild);
3967 return rv;
3970 //----------------------------------------------------------------------
3972 // nsISupports implementation
3974 NS_IMPL_CYCLE_COLLECTION_CLASS(nsGenericElement)
3976 NS_IMPL_CYCLE_COLLECTION_UNLINK_BEGIN(nsGenericElement)
3977 NS_IMPL_CYCLE_COLLECTION_UNLINK_LISTENERMANAGER
3978 NS_IMPL_CYCLE_COLLECTION_UNLINK_USERDATA
3979 NS_IMPL_CYCLE_COLLECTION_UNLINK_PRESERVED_WRAPPER
3981 if (tmp->HasProperties() && tmp->IsNodeOfType(nsINode::eXUL)) {
3982 tmp->DeleteProperty(nsGkAtoms::contextmenulistener);
3983 tmp->DeleteProperty(nsGkAtoms::popuplistener);
3986 // Unlink child content (and unbind our subtree).
3988 PRUint32 childCount = tmp->mAttrsAndChildren.ChildCount();
3989 if (childCount) {
3990 // Don't allow script to run while we're unbinding everything.
3991 nsAutoScriptBlocker scriptBlocker;
3992 while (childCount-- > 0) {
3993 // Once we have XPCOMGC we shouldn't need to call UnbindFromTree.
3994 // We could probably do a non-deep unbind here when IsInDoc is false
3995 // for better performance.
3996 tmp->mAttrsAndChildren.ChildAt(childCount)->UnbindFromTree();
3997 tmp->mAttrsAndChildren.RemoveChildAt(childCount);
4002 // Unlink any DOM slots of interest.
4004 nsDOMSlots *slots = tmp->GetExistingDOMSlots();
4005 if (slots) {
4006 if (slots->mAttributeMap) {
4007 slots->mAttributeMap->DropReference();
4008 slots->mAttributeMap = nsnull;
4010 if (tmp->IsNodeOfType(nsINode::eXUL))
4011 NS_IF_RELEASE(slots->mControllers);
4012 slots->mChildrenList = nsnull;
4015 NS_IMPL_CYCLE_COLLECTION_UNLINK_END
4017 NS_IMPL_CYCLE_COLLECTION_TRAVERSE_BEGIN(nsGenericElement)
4018 nsIDocument* currentDoc = tmp->GetCurrentDoc();
4019 if (currentDoc && nsCCUncollectableMarker::InGeneration(
4020 currentDoc->GetMarkedCCGeneration())) {
4021 return NS_OK;
4024 nsIDocument* ownerDoc = tmp->GetOwnerDoc();
4025 if (ownerDoc) {
4026 ownerDoc->BindingManager()->Traverse(tmp, cb);
4029 NS_IMPL_CYCLE_COLLECTION_TRAVERSE_LISTENERMANAGER
4030 NS_IMPL_CYCLE_COLLECTION_TRAVERSE_USERDATA
4031 NS_IMPL_CYCLE_COLLECTION_TRAVERSE_PRESERVED_WRAPPER
4033 if (tmp->HasProperties() && tmp->IsNodeOfType(nsINode::eXUL)) {
4034 nsISupports* property =
4035 static_cast<nsISupports*>
4036 (tmp->GetProperty(nsGkAtoms::contextmenulistener));
4037 cb.NoteXPCOMChild(property);
4038 property = static_cast<nsISupports*>
4039 (tmp->GetProperty(nsGkAtoms::popuplistener));
4040 cb.NoteXPCOMChild(property);
4043 // Traverse attribute names and child content.
4045 PRUint32 i;
4046 PRUint32 attrs = tmp->mAttrsAndChildren.AttrCount();
4047 for (i = 0; i < attrs; i++) {
4048 const nsAttrName* name = tmp->mAttrsAndChildren.AttrNameAt(i);
4049 if (!name->IsAtom()) {
4050 NS_CYCLE_COLLECTION_NOTE_EDGE_NAME(cb,
4051 "mAttrsAndChildren[i]->NodeInfo()");
4052 cb.NoteXPCOMChild(name->NodeInfo());
4056 PRUint32 kids = tmp->mAttrsAndChildren.ChildCount();
4057 for (i = 0; i < kids; i++) {
4058 NS_CYCLE_COLLECTION_NOTE_EDGE_NAME(cb, "mAttrsAndChildren[i]");
4059 cb.NoteXPCOMChild(tmp->mAttrsAndChildren.GetSafeChildAt(i));
4063 NS_IMPL_CYCLE_COLLECTION_TRAVERSE_NSCOMPTR(mNodeInfo)
4065 // Traverse any DOM slots of interest.
4067 nsDOMSlots *slots = tmp->GetExistingDOMSlots();
4068 if (slots) {
4069 cb.NoteXPCOMChild(slots->mAttributeMap.get());
4070 if (tmp->IsNodeOfType(nsINode::eXUL))
4071 cb.NoteXPCOMChild(slots->mControllers);
4072 cb.NoteXPCOMChild(
4073 static_cast<nsIDOMNodeList*>(slots->mChildrenList.get()));
4076 NS_IMPL_CYCLE_COLLECTION_TRAVERSE_END
4079 NS_INTERFACE_MAP_BEGIN(nsGenericElement)
4080 NS_WRAPPERCACHE_INTERFACE_MAP_ENTRY
4081 NS_INTERFACE_MAP_ENTRIES_CYCLE_COLLECTION(nsGenericElement)
4082 NS_INTERFACE_MAP_ENTRY(nsIContent)
4083 NS_INTERFACE_MAP_ENTRY(nsINode)
4084 NS_INTERFACE_MAP_ENTRY(nsPIDOMEventTarget)
4085 NS_INTERFACE_MAP_ENTRY_TEAROFF(nsIDOM3Node, new nsNode3Tearoff(this))
4086 NS_INTERFACE_MAP_ENTRY_TEAROFF(nsIDOMNSElement, new nsNSElementTearoff(this))
4087 NS_INTERFACE_MAP_ENTRY_TEAROFF(nsIDOMEventTarget,
4088 nsDOMEventRTTearoff::Create(this))
4089 NS_INTERFACE_MAP_ENTRY_TEAROFF(nsIDOM3EventTarget,
4090 nsDOMEventRTTearoff::Create(this))
4091 NS_INTERFACE_MAP_ENTRY_TEAROFF(nsIDOMNSEventTarget,
4092 nsDOMEventRTTearoff::Create(this))
4093 NS_INTERFACE_MAP_ENTRY_TEAROFF(nsISupportsWeakReference,
4094 new nsNodeSupportsWeakRefTearoff(this))
4095 NS_INTERFACE_MAP_ENTRY_TEAROFF(nsIDOMNodeSelector,
4096 new nsNodeSelectorTearoff(this))
4097 // nsNodeSH::PreCreate() depends on the identity pointer being the
4098 // same as nsINode (which nsIContent inherits), so if you change the
4099 // below line, make sure nsNodeSH::PreCreate() still does the right
4100 // thing!
4101 NS_INTERFACE_MAP_ENTRY_AMBIGUOUS(nsISupports, nsIContent)
4102 NS_INTERFACE_MAP_END
4104 NS_IMPL_CYCLE_COLLECTING_ADDREF_AMBIGUOUS(nsGenericElement, nsIContent)
4105 NS_IMPL_CYCLE_COLLECTING_RELEASE_AMBIGUOUS_WITH_DESTROY(nsGenericElement,
4106 nsIContent,
4107 nsNodeUtils::LastRelease(this))
4109 nsresult
4110 nsGenericElement::PostQueryInterface(REFNSIID aIID, void** aInstancePtr)
4112 nsIDocument *document = GetOwnerDoc();
4113 if (document) {
4114 return document->BindingManager()->GetBindingImplementation(this, aIID,
4115 aInstancePtr);
4118 *aInstancePtr = nsnull;
4119 return NS_ERROR_NO_INTERFACE;
4122 //----------------------------------------------------------------------
4123 nsresult
4124 nsGenericElement::LeaveLink(nsPresContext* aPresContext)
4126 nsILinkHandler *handler = aPresContext->GetLinkHandler();
4127 if (!handler) {
4128 return NS_OK;
4131 return handler->OnLeaveLink();
4134 nsresult
4135 nsGenericElement::AddScriptEventListener(nsIAtom* aEventName,
4136 const nsAString& aValue,
4137 PRBool aDefer)
4139 nsIDocument *ownerDoc = GetOwnerDoc();
4140 if (!ownerDoc || ownerDoc->IsLoadedAsData()) {
4141 // Make this a no-op rather than throwing an error to avoid
4142 // the error causing problems setting the attribute.
4143 return NS_OK;
4146 NS_PRECONDITION(aEventName, "Must have event name!");
4147 nsCOMPtr<nsISupports> target;
4148 PRBool defer = PR_TRUE;
4149 nsCOMPtr<nsIEventListenerManager> manager;
4151 nsresult rv = GetEventListenerManagerForAttr(getter_AddRefs(manager),
4152 getter_AddRefs(target),
4153 &defer);
4154 NS_ENSURE_SUCCESS(rv, rv);
4156 if (manager) {
4157 defer = defer && aDefer; // only defer if everyone agrees...
4159 PRUint32 lang = GetScriptTypeID();
4160 rv =
4161 manager->AddScriptEventListener(target, aEventName, aValue, lang, defer,
4162 !nsContentUtils::IsChromeDoc(ownerDoc));
4165 return rv;
4169 //----------------------------------------------------------------------
4171 const nsAttrName*
4172 nsGenericElement::InternalGetExistingAttrNameFromQName(const nsAString& aStr) const
4174 return mAttrsAndChildren.GetExistingAttrNameFromQName(
4175 NS_ConvertUTF16toUTF8(aStr));
4178 nsresult
4179 nsGenericElement::CopyInnerTo(nsGenericElement* aDst) const
4181 PRUint32 i, count = mAttrsAndChildren.AttrCount();
4182 for (i = 0; i < count; ++i) {
4183 const nsAttrName* name = mAttrsAndChildren.AttrNameAt(i);
4184 const nsAttrValue* value = mAttrsAndChildren.AttrAt(i);
4185 nsAutoString valStr;
4186 value->ToString(valStr);
4187 nsresult rv = aDst->SetAttr(name->NamespaceID(), name->LocalName(),
4188 name->GetPrefix(), valStr, PR_FALSE);
4189 NS_ENSURE_SUCCESS(rv, rv);
4192 return NS_OK;
4195 nsresult
4196 nsGenericElement::SetAttr(PRInt32 aNamespaceID, nsIAtom* aName,
4197 nsIAtom* aPrefix, const nsAString& aValue,
4198 PRBool aNotify)
4200 NS_ENSURE_ARG_POINTER(aName);
4201 NS_ASSERTION(aNamespaceID != kNameSpaceID_Unknown,
4202 "Don't call SetAttr with unknown namespace");
4204 nsIDocument* doc = GetCurrentDoc();
4205 if (kNameSpaceID_XLink == aNamespaceID && nsGkAtoms::href == aName) {
4206 // XLink URI(s) might be changing. Drop the link from the map. If it
4207 // is still style relevant it will be re-added by
4208 // nsStyleUtil::IsLink. Make sure to keep the style system
4209 // consistent so this remains true! In particular if the style system
4210 // were to get smarter and not restyling an XLink element if the href
4211 // doesn't change in a "significant" way, we'd need to do the same
4212 // significance check here.
4213 if (doc) {
4214 doc->ForgetLink(this);
4218 nsAutoString oldValue;
4219 PRBool modification = PR_FALSE;
4220 PRBool hasListeners = aNotify &&
4221 nsContentUtils::HasMutationListeners(this,
4222 NS_EVENT_BITS_MUTATION_ATTRMODIFIED,
4223 this);
4225 // If we have no listeners and aNotify is false, we are almost certainly
4226 // coming from the content sink and will almost certainly have no previous
4227 // value. Even if we do, setting the value is cheap when we have no
4228 // listeners and don't plan to notify. The check for aNotify here is an
4229 // optimization, the check for haveListeners is a correctness issue.
4230 if (hasListeners || aNotify) {
4231 nsAttrInfo info(GetAttrInfo(aNamespaceID, aName));
4232 if (info.mValue) {
4233 // Check whether the old value is the same as the new one. Note that we
4234 // only need to actually _get_ the old value if we have listeners.
4235 PRBool valueMatches;
4236 if (hasListeners) {
4237 // Need to store the old value
4238 info.mValue->ToString(oldValue);
4239 valueMatches = aValue.Equals(oldValue);
4240 } else if (aNotify) {
4241 valueMatches = info.mValue->Equals(aValue, eCaseMatters);
4243 if (valueMatches && aPrefix == info.mName->GetPrefix()) {
4244 return NS_OK;
4246 modification = PR_TRUE;
4250 nsresult rv = BeforeSetAttr(aNamespaceID, aName, &aValue, aNotify);
4251 NS_ENSURE_SUCCESS(rv, rv);
4253 nsAttrValue attrValue;
4254 if (!ParseAttribute(aNamespaceID, aName, aValue, attrValue)) {
4255 attrValue.SetTo(aValue);
4258 return SetAttrAndNotify(aNamespaceID, aName, aPrefix, oldValue,
4259 attrValue, modification, hasListeners, aNotify,
4260 &aValue);
4263 nsresult
4264 nsGenericElement::SetAttrAndNotify(PRInt32 aNamespaceID,
4265 nsIAtom* aName,
4266 nsIAtom* aPrefix,
4267 const nsAString& aOldValue,
4268 nsAttrValue& aParsedValue,
4269 PRBool aModification,
4270 PRBool aFireMutation,
4271 PRBool aNotify,
4272 const nsAString* aValueForAfterSetAttr)
4274 nsresult rv;
4275 PRUint8 modType = aModification ?
4276 static_cast<PRUint8>(nsIDOMMutationEvent::MODIFICATION) :
4277 static_cast<PRUint8>(nsIDOMMutationEvent::ADDITION);
4279 nsIDocument* document = GetCurrentDoc();
4280 mozAutoDocUpdate updateBatch(document, UPDATE_CONTENT_MODEL, aNotify);
4282 // When notifying, make sure to keep track of states whose value
4283 // depends solely on the value of an attribute.
4284 PRUint32 stateMask;
4285 if (aNotify) {
4286 stateMask = PRUint32(IntrinsicState());
4288 if (document) {
4289 document->AttributeWillChange(this, aNamespaceID, aName);
4293 if (aNamespaceID == kNameSpaceID_None) {
4294 // XXXbz Perhaps we should push up the attribute mapping function
4295 // stuff to nsGenericElement?
4296 if (!IsAttributeMapped(aName) ||
4297 !SetMappedAttribute(document, aName, aParsedValue, &rv)) {
4298 rv = mAttrsAndChildren.SetAndTakeAttr(aName, aParsedValue);
4301 else {
4302 nsCOMPtr<nsINodeInfo> ni;
4303 ni = mNodeInfo->NodeInfoManager()->GetNodeInfo(aName, aPrefix,
4304 aNamespaceID);
4305 NS_ENSURE_TRUE(ni, NS_ERROR_OUT_OF_MEMORY);
4307 rv = mAttrsAndChildren.SetAndTakeAttr(ni, aParsedValue);
4309 NS_ENSURE_SUCCESS(rv, rv);
4311 if (document || HasFlag(NODE_FORCE_XBL_BINDINGS)) {
4312 nsIDocument* ownerDoc = GetOwnerDoc();
4313 if (ownerDoc) {
4314 nsRefPtr<nsXBLBinding> binding =
4315 ownerDoc->BindingManager()->GetBinding(this);
4316 if (binding) {
4317 binding->AttributeChanged(aName, aNamespaceID, PR_FALSE, aNotify);
4322 if (aNotify) {
4323 stateMask = stateMask ^ PRUint32(IntrinsicState());
4324 if (stateMask && document) {
4325 MOZ_AUTO_DOC_UPDATE(document, UPDATE_CONTENT_STATE, aNotify);
4326 document->ContentStatesChanged(this, nsnull, stateMask);
4328 nsNodeUtils::AttributeChanged(this, aNamespaceID, aName, modType,
4329 stateMask);
4332 if (aNamespaceID == kNameSpaceID_XMLEvents &&
4333 aName == nsGkAtoms::event && mNodeInfo->GetDocument()) {
4334 mNodeInfo->GetDocument()->AddXMLEventsContent(this);
4336 if (aValueForAfterSetAttr) {
4337 rv = AfterSetAttr(aNamespaceID, aName, aValueForAfterSetAttr, aNotify);
4338 NS_ENSURE_SUCCESS(rv, rv);
4341 if (aFireMutation) {
4342 mozAutoRemovableBlockerRemover blockerRemover;
4344 nsMutationEvent mutation(PR_TRUE, NS_MUTATION_ATTRMODIFIED);
4346 nsAutoString attrName;
4347 aName->ToString(attrName);
4348 nsCOMPtr<nsIDOMAttr> attrNode;
4349 nsAutoString ns;
4350 nsContentUtils::NameSpaceManager()->GetNameSpaceURI(aNamespaceID, ns);
4351 GetAttributeNodeNS(ns, attrName, getter_AddRefs(attrNode));
4352 mutation.mRelatedNode = attrNode;
4354 mutation.mAttrName = aName;
4355 nsAutoString newValue;
4356 GetAttr(aNamespaceID, aName, newValue);
4357 if (!newValue.IsEmpty()) {
4358 mutation.mNewAttrValue = do_GetAtom(newValue);
4360 if (!aOldValue.IsEmpty()) {
4361 mutation.mPrevAttrValue = do_GetAtom(aOldValue);
4363 mutation.mAttrChange = modType;
4365 mozAutoSubtreeModified subtree(GetOwnerDoc(), this);
4366 nsEventDispatcher::Dispatch(this, nsnull, &mutation);
4369 return NS_OK;
4372 PRBool
4373 nsGenericElement::ParseAttribute(PRInt32 aNamespaceID,
4374 nsIAtom* aAttribute,
4375 const nsAString& aValue,
4376 nsAttrValue& aResult)
4378 if (aNamespaceID == kNameSpaceID_None &&
4379 aAttribute == GetIDAttributeName() && !aValue.IsEmpty()) {
4380 SetFlags(NODE_MAY_HAVE_ID);
4381 // Store id as an atom. id="" means that the element has no id,
4382 // not that it has an emptystring as the id.
4383 aResult.ParseAtom(aValue);
4384 return PR_TRUE;
4387 return PR_FALSE;
4390 PRBool
4391 nsGenericElement::SetMappedAttribute(nsIDocument* aDocument,
4392 nsIAtom* aName,
4393 nsAttrValue& aValue,
4394 nsresult* aRetval)
4396 *aRetval = NS_OK;
4397 return PR_FALSE;
4400 nsresult
4401 nsGenericElement::GetEventListenerManagerForAttr(nsIEventListenerManager** aManager,
4402 nsISupports** aTarget,
4403 PRBool* aDefer)
4405 nsresult rv = GetListenerManager(PR_TRUE, aManager);
4406 if (NS_SUCCEEDED(rv)) {
4407 NS_ADDREF(*aTarget = static_cast<nsIContent*>(this));
4409 *aDefer = PR_TRUE;
4410 return rv;
4413 nsGenericElement::nsAttrInfo
4414 nsGenericElement::GetAttrInfo(PRInt32 aNamespaceID, nsIAtom* aName) const
4416 NS_ASSERTION(nsnull != aName, "must have attribute name");
4417 NS_ASSERTION(aNamespaceID != kNameSpaceID_Unknown,
4418 "must have a real namespace ID!");
4420 PRInt32 index = mAttrsAndChildren.IndexOfAttr(aName, aNamespaceID);
4421 if (index >= 0) {
4422 return nsAttrInfo(mAttrsAndChildren.AttrNameAt(index),
4423 mAttrsAndChildren.AttrAt(index));
4426 return nsAttrInfo(nsnull, nsnull);
4430 PRBool
4431 nsGenericElement::GetAttr(PRInt32 aNameSpaceID, nsIAtom* aName,
4432 nsAString& aResult) const
4434 NS_ASSERTION(nsnull != aName, "must have attribute name");
4435 NS_ASSERTION(aNameSpaceID != kNameSpaceID_Unknown,
4436 "must have a real namespace ID!");
4438 const nsAttrValue* val = mAttrsAndChildren.GetAttr(aName, aNameSpaceID);
4439 if (!val) {
4440 // Since we are returning a success code we'd better do
4441 // something about the out parameters (someone may have
4442 // given us a non-empty string).
4443 aResult.Truncate();
4445 return PR_FALSE;
4448 val->ToString(aResult);
4450 return PR_TRUE;
4453 PRBool
4454 nsGenericElement::HasAttr(PRInt32 aNameSpaceID, nsIAtom* aName) const
4456 NS_ASSERTION(nsnull != aName, "must have attribute name");
4457 NS_ASSERTION(aNameSpaceID != kNameSpaceID_Unknown,
4458 "must have a real namespace ID!");
4460 return mAttrsAndChildren.IndexOfAttr(aName, aNameSpaceID) >= 0;
4463 PRBool
4464 nsGenericElement::AttrValueIs(PRInt32 aNameSpaceID,
4465 nsIAtom* aName,
4466 const nsAString& aValue,
4467 nsCaseTreatment aCaseSensitive) const
4469 NS_ASSERTION(aName, "Must have attr name");
4470 NS_ASSERTION(aNameSpaceID != kNameSpaceID_Unknown, "Must have namespace");
4472 const nsAttrValue* val = mAttrsAndChildren.GetAttr(aName, aNameSpaceID);
4473 return val && val->Equals(aValue, aCaseSensitive);
4476 PRBool
4477 nsGenericElement::AttrValueIs(PRInt32 aNameSpaceID,
4478 nsIAtom* aName,
4479 nsIAtom* aValue,
4480 nsCaseTreatment aCaseSensitive) const
4482 NS_ASSERTION(aName, "Must have attr name");
4483 NS_ASSERTION(aNameSpaceID != kNameSpaceID_Unknown, "Must have namespace");
4484 NS_ASSERTION(aValue, "Null value atom");
4486 const nsAttrValue* val = mAttrsAndChildren.GetAttr(aName, aNameSpaceID);
4487 return val && val->Equals(aValue, aCaseSensitive);
4490 PRInt32
4491 nsGenericElement::FindAttrValueIn(PRInt32 aNameSpaceID,
4492 nsIAtom* aName,
4493 AttrValuesArray* aValues,
4494 nsCaseTreatment aCaseSensitive) const
4496 NS_ASSERTION(aName, "Must have attr name");
4497 NS_ASSERTION(aNameSpaceID != kNameSpaceID_Unknown, "Must have namespace");
4498 NS_ASSERTION(aValues, "Null value array");
4500 const nsAttrValue* val = mAttrsAndChildren.GetAttr(aName, aNameSpaceID);
4501 if (val) {
4502 for (PRInt32 i = 0; aValues[i]; ++i) {
4503 if (val->Equals(*aValues[i], aCaseSensitive)) {
4504 return i;
4507 return ATTR_VALUE_NO_MATCH;
4509 return ATTR_MISSING;
4512 nsresult
4513 nsGenericElement::UnsetAttr(PRInt32 aNameSpaceID, nsIAtom* aName,
4514 PRBool aNotify)
4516 NS_ASSERTION(nsnull != aName, "must have attribute name");
4518 PRInt32 index = mAttrsAndChildren.IndexOfAttr(aName, aNameSpaceID);
4519 if (index < 0) {
4520 return NS_OK;
4523 nsresult rv = BeforeSetAttr(aNameSpaceID, aName, nsnull, aNotify);
4524 NS_ENSURE_SUCCESS(rv, rv);
4526 nsIDocument *document = GetCurrentDoc();
4527 mozAutoDocUpdate updateBatch(document, UPDATE_CONTENT_MODEL, aNotify);
4528 if (document) {
4529 if (kNameSpaceID_XLink == aNameSpaceID && nsGkAtoms::href == aName) {
4530 // XLink URI might be changing.
4531 document->ForgetLink(this);
4534 if (aNotify) {
4535 document->AttributeWillChange(this, aNameSpaceID, aName);
4539 // When notifying, make sure to keep track of states whose value
4540 // depends solely on the value of an attribute.
4541 PRUint32 stateMask;
4542 if (aNotify) {
4543 stateMask = PRUint32(IntrinsicState());
4546 PRBool hasMutationListeners = aNotify &&
4547 nsContentUtils::HasMutationListeners(this,
4548 NS_EVENT_BITS_MUTATION_ATTRMODIFIED,
4549 this);
4551 // Grab the attr node if needed before we remove it from the attr map
4552 nsCOMPtr<nsIDOMAttr> attrNode;
4553 if (hasMutationListeners) {
4554 nsAutoString attrName;
4555 aName->ToString(attrName);
4556 nsAutoString ns;
4557 nsContentUtils::NameSpaceManager()->GetNameSpaceURI(aNameSpaceID, ns);
4558 GetAttributeNodeNS(ns, attrName, getter_AddRefs(attrNode));
4561 // Clear binding to nsIDOMNamedNodeMap
4562 nsDOMSlots *slots = GetExistingDOMSlots();
4563 if (slots && slots->mAttributeMap) {
4564 slots->mAttributeMap->DropAttribute(aNameSpaceID, aName);
4567 nsAttrValue oldValue;
4568 rv = mAttrsAndChildren.RemoveAttrAt(index, oldValue);
4569 NS_ENSURE_SUCCESS(rv, rv);
4571 if (document || HasFlag(NODE_FORCE_XBL_BINDINGS)) {
4572 nsIDocument* ownerDoc = GetOwnerDoc();
4573 if (ownerDoc) {
4574 nsRefPtr<nsXBLBinding> binding =
4575 ownerDoc->BindingManager()->GetBinding(this);
4576 if (binding) {
4577 binding->AttributeChanged(aName, aNameSpaceID, PR_TRUE, aNotify);
4582 if (aNotify) {
4583 stateMask = stateMask ^ PRUint32(IntrinsicState());
4584 if (stateMask && document) {
4585 MOZ_AUTO_DOC_UPDATE(document, UPDATE_CONTENT_STATE, aNotify);
4586 document->ContentStatesChanged(this, nsnull, stateMask);
4588 nsNodeUtils::AttributeChanged(this, aNameSpaceID, aName,
4589 nsIDOMMutationEvent::REMOVAL,
4590 stateMask);
4593 rv = AfterSetAttr(aNameSpaceID, aName, nsnull, aNotify);
4594 NS_ENSURE_SUCCESS(rv, rv);
4596 if (hasMutationListeners) {
4597 mozAutoRemovableBlockerRemover blockerRemover;
4599 nsCOMPtr<nsIDOMEventTarget> node =
4600 do_QueryInterface(static_cast<nsIContent *>(this));
4601 nsMutationEvent mutation(PR_TRUE, NS_MUTATION_ATTRMODIFIED);
4603 mutation.mRelatedNode = attrNode;
4604 mutation.mAttrName = aName;
4606 nsAutoString value;
4607 oldValue.ToString(value);
4608 if (!value.IsEmpty())
4609 mutation.mPrevAttrValue = do_GetAtom(value);
4610 mutation.mAttrChange = nsIDOMMutationEvent::REMOVAL;
4612 mozAutoSubtreeModified subtree(GetOwnerDoc(), this);
4613 nsEventDispatcher::Dispatch(this, nsnull, &mutation);
4616 return NS_OK;
4619 const nsAttrName*
4620 nsGenericElement::GetAttrNameAt(PRUint32 aIndex) const
4622 return mAttrsAndChildren.GetSafeAttrNameAt(aIndex);
4625 PRUint32
4626 nsGenericElement::GetAttrCount() const
4628 return mAttrsAndChildren.AttrCount();
4631 const nsTextFragment*
4632 nsGenericElement::GetText()
4634 return nsnull;
4637 PRUint32
4638 nsGenericElement::TextLength()
4640 // We can remove this assertion if it turns out to be useful to be able
4641 // to depend on this returning 0
4642 NS_NOTREACHED("called nsGenericElement::TextLength");
4644 return 0;
4647 nsresult
4648 nsGenericElement::SetText(const PRUnichar* aBuffer, PRUint32 aLength,
4649 PRBool aNotify)
4651 NS_ERROR("called nsGenericElement::SetText");
4653 return NS_ERROR_FAILURE;
4656 nsresult
4657 nsGenericElement::AppendText(const PRUnichar* aBuffer, PRUint32 aLength,
4658 PRBool aNotify)
4660 NS_ERROR("called nsGenericElement::AppendText");
4662 return NS_ERROR_FAILURE;
4665 PRBool
4666 nsGenericElement::TextIsOnlyWhitespace()
4668 return PR_FALSE;
4671 void
4672 nsGenericElement::AppendTextTo(nsAString& aResult)
4674 // We can remove this assertion if it turns out to be useful to be able
4675 // to depend on this appending nothing.
4676 NS_NOTREACHED("called nsGenericElement::TextLength");
4679 #ifdef DEBUG
4680 void
4681 nsGenericElement::ListAttributes(FILE* out) const
4683 PRUint32 index, count = mAttrsAndChildren.AttrCount();
4684 for (index = 0; index < count; index++) {
4685 nsAutoString buffer;
4687 // name
4688 mAttrsAndChildren.AttrNameAt(index)->GetQualifiedName(buffer);
4690 // value
4691 buffer.AppendLiteral("=\"");
4692 nsAutoString value;
4693 mAttrsAndChildren.AttrAt(index)->ToString(value);
4694 for (int i = value.Length(); i >= 0; --i) {
4695 if (value[i] == PRUnichar('"'))
4696 value.Insert(PRUnichar('\\'), PRUint32(i));
4698 buffer.Append(value);
4699 buffer.AppendLiteral("\"");
4701 fputs(" ", out);
4702 fputs(NS_LossyConvertUTF16toASCII(buffer).get(), out);
4706 void
4707 nsGenericElement::List(FILE* out, PRInt32 aIndent,
4708 const nsCString& aPrefix) const
4710 PRInt32 indent;
4711 for (indent = aIndent; --indent >= 0; ) fputs(" ", out);
4713 fputs(aPrefix.get(), out);
4715 nsAutoString buf;
4716 mNodeInfo->GetQualifiedName(buf);
4717 fputs(NS_LossyConvertUTF16toASCII(buf).get(), out);
4719 fprintf(out, "@%p", (void *)this);
4721 ListAttributes(out);
4723 fprintf(out, " intrinsicstate=[%08x]", IntrinsicState());
4724 fprintf(out, " refcount=%d<", mRefCnt.get());
4726 PRUint32 i, length = GetChildCount();
4727 if (length > 0) {
4728 fputs("\n", out);
4730 for (i = 0; i < length; ++i) {
4731 nsIContent *kid = GetChildAt(i);
4732 kid->List(out, aIndent + 1);
4735 for (indent = aIndent; --indent >= 0; ) fputs(" ", out);
4738 fputs(">\n", out);
4740 nsGenericElement* nonConstThis = const_cast<nsGenericElement*>(this);
4742 // XXX sXBL/XBL2 issue! Owner or current document?
4743 nsIDocument *document = GetOwnerDoc();
4744 if (document) {
4745 // Note: not listing nsIAnonymousContentCreator-created content...
4747 nsBindingManager* bindingManager = document->BindingManager();
4748 nsCOMPtr<nsIDOMNodeList> anonymousChildren;
4749 bindingManager->GetAnonymousNodesFor(nonConstThis,
4750 getter_AddRefs(anonymousChildren));
4752 if (anonymousChildren) {
4753 anonymousChildren->GetLength(&length);
4754 if (length > 0) {
4755 for (indent = aIndent; --indent >= 0; ) fputs(" ", out);
4756 fputs("anonymous-children<\n", out);
4758 for (i = 0; i < length; ++i) {
4759 nsCOMPtr<nsIDOMNode> node;
4760 anonymousChildren->Item(i, getter_AddRefs(node));
4761 nsCOMPtr<nsIContent> child = do_QueryInterface(node);
4762 child->List(out, aIndent + 1);
4765 for (indent = aIndent; --indent >= 0; ) fputs(" ", out);
4766 fputs(">\n", out);
4770 if (bindingManager->HasContentListFor(nonConstThis)) {
4771 nsCOMPtr<nsIDOMNodeList> contentList;
4772 bindingManager->GetContentListFor(nonConstThis,
4773 getter_AddRefs(contentList));
4775 NS_ASSERTION(contentList != nsnull, "oops, binding manager lied");
4777 contentList->GetLength(&length);
4778 if (length > 0) {
4779 for (indent = aIndent; --indent >= 0; ) fputs(" ", out);
4780 fputs("content-list<\n", out);
4782 for (i = 0; i < length; ++i) {
4783 nsCOMPtr<nsIDOMNode> node;
4784 contentList->Item(i, getter_AddRefs(node));
4785 nsCOMPtr<nsIContent> child = do_QueryInterface(node);
4786 child->List(out, aIndent + 1);
4789 for (indent = aIndent; --indent >= 0; ) fputs(" ", out);
4790 fputs(">\n", out);
4796 void
4797 nsGenericElement::DumpContent(FILE* out, PRInt32 aIndent,
4798 PRBool aDumpAll) const
4800 PRInt32 indent;
4801 for (indent = aIndent; --indent >= 0; ) fputs(" ", out);
4803 nsAutoString buf;
4804 mNodeInfo->GetQualifiedName(buf);
4805 fputs("<", out);
4806 fputs(NS_LossyConvertUTF16toASCII(buf).get(), out);
4808 if(aDumpAll) ListAttributes(out);
4810 fputs(">", out);
4812 if(aIndent) fputs("\n", out);
4814 PRInt32 index, kids = GetChildCount();
4815 for (index = 0; index < kids; index++) {
4816 nsIContent *kid = GetChildAt(index);
4817 PRInt32 indent = aIndent ? aIndent + 1 : 0;
4818 kid->DumpContent(out, indent, aDumpAll);
4820 for (indent = aIndent; --indent >= 0; ) fputs(" ", out);
4821 fputs("</", out);
4822 fputs(NS_LossyConvertUTF16toASCII(buf).get(), out);
4823 fputs(">", out);
4825 if(aIndent) fputs("\n", out);
4827 #endif
4829 PRUint32
4830 nsGenericElement::GetChildCount() const
4832 return mAttrsAndChildren.ChildCount();
4835 nsIContent *
4836 nsGenericElement::GetChildAt(PRUint32 aIndex) const
4838 return mAttrsAndChildren.GetSafeChildAt(aIndex);
4841 nsIContent * const *
4842 nsGenericElement::GetChildArray(PRUint32* aChildCount) const
4844 return mAttrsAndChildren.GetChildArray(aChildCount);
4847 PRInt32
4848 nsGenericElement::IndexOf(nsINode* aPossibleChild) const
4850 return mAttrsAndChildren.IndexOfChild(aPossibleChild);
4853 nsINode::nsSlots*
4854 nsGenericElement::CreateSlots()
4856 return new nsDOMSlots(mFlagsOrSlots);
4859 PRBool
4860 nsGenericElement::CheckHandleEventForLinksPrecondition(nsEventChainVisitor& aVisitor,
4861 nsIURI** aURI) const
4863 if (aVisitor.mEventStatus == nsEventStatus_eConsumeNoDefault ||
4864 !NS_IS_TRUSTED_EVENT(aVisitor.mEvent) ||
4865 !aVisitor.mPresContext) {
4866 return PR_FALSE;
4869 // Make sure we actually are a link
4870 return IsLink(aURI);
4873 nsresult
4874 nsGenericElement::PreHandleEventForLinks(nsEventChainPreVisitor& aVisitor)
4876 // Optimisation: return early if this event doesn't interest us.
4877 // IMPORTANT: this switch and the switch below it must be kept in sync!
4878 switch (aVisitor.mEvent->message) {
4879 case NS_MOUSE_ENTER_SYNTH:
4880 case NS_FOCUS_CONTENT:
4881 case NS_MOUSE_EXIT_SYNTH:
4882 case NS_BLUR_CONTENT:
4883 break;
4884 default:
4885 return NS_OK;
4888 // Make sure we meet the preconditions before continuing
4889 nsCOMPtr<nsIURI> absURI;
4890 if (!CheckHandleEventForLinksPrecondition(aVisitor, getter_AddRefs(absURI))) {
4891 return NS_OK;
4894 nsresult rv = NS_OK;
4896 // We do the status bar updates in PreHandleEvent so that the status bar gets
4897 // updated even if the event is consumed before we have a chance to set it.
4898 switch (aVisitor.mEvent->message) {
4899 // Set the status bar the same for focus and mouseover
4900 case NS_MOUSE_ENTER_SYNTH:
4901 aVisitor.mEventStatus = nsEventStatus_eConsumeNoDefault;
4902 // FALL THROUGH
4903 case NS_FOCUS_CONTENT:
4905 nsAutoString target;
4906 GetLinkTarget(target);
4907 nsContentUtils::TriggerLink(this, aVisitor.mPresContext, absURI, target,
4908 PR_FALSE, PR_TRUE);
4910 break;
4912 case NS_MOUSE_EXIT_SYNTH:
4913 aVisitor.mEventStatus = nsEventStatus_eConsumeNoDefault;
4914 // FALL THROUGH
4915 case NS_BLUR_CONTENT:
4916 rv = LeaveLink(aVisitor.mPresContext);
4917 break;
4919 default:
4920 // switch not in sync with the optimization switch earlier in this function
4921 NS_NOTREACHED("switch statements not in sync");
4922 return NS_ERROR_UNEXPECTED;
4925 return rv;
4928 nsresult
4929 nsGenericElement::PostHandleEventForLinks(nsEventChainPostVisitor& aVisitor)
4931 // Optimisation: return early if this event doesn't interest us.
4932 // IMPORTANT: this switch and the switch below it must be kept in sync!
4933 switch (aVisitor.mEvent->message) {
4934 case NS_MOUSE_BUTTON_DOWN:
4935 case NS_MOUSE_CLICK:
4936 case NS_UI_ACTIVATE:
4937 case NS_KEY_PRESS:
4938 break;
4939 default:
4940 return NS_OK;
4943 // Make sure we meet the preconditions before continuing
4944 nsCOMPtr<nsIURI> absURI;
4945 if (!CheckHandleEventForLinksPrecondition(aVisitor, getter_AddRefs(absURI))) {
4946 return NS_OK;
4949 nsresult rv = NS_OK;
4951 switch (aVisitor.mEvent->message) {
4952 case NS_MOUSE_BUTTON_DOWN:
4954 if (aVisitor.mEvent->eventStructType == NS_MOUSE_EVENT &&
4955 static_cast<nsMouseEvent*>(aVisitor.mEvent)->button ==
4956 nsMouseEvent::eLeftButton) {
4957 // don't make the link grab the focus if there is no link handler
4958 nsILinkHandler *handler = aVisitor.mPresContext->GetLinkHandler();
4959 nsIDocument *document = GetCurrentDoc();
4960 if (handler && document && ShouldFocus(this)) {
4961 // If the window is not active, do not allow the focus to bring the
4962 // window to the front. We update the focus controller, but do nothing
4963 // else.
4964 nsPIDOMWindow *win = document->GetWindow();
4965 if (win) {
4966 nsIFocusController *focusController =
4967 win->GetRootFocusController();
4968 if (focusController) {
4969 PRBool isActive = PR_FALSE;
4970 focusController->GetActive(&isActive);
4971 if (!isActive) {
4972 nsCOMPtr<nsIDOMElement> domElement = do_QueryInterface(this);
4973 if(domElement)
4974 focusController->SetFocusedElement(domElement);
4975 break;
4980 aVisitor.mPresContext->EventStateManager()->
4981 SetContentState(this, NS_EVENT_STATE_ACTIVE | NS_EVENT_STATE_FOCUS);
4985 break;
4987 case NS_MOUSE_CLICK:
4988 if (NS_IS_MOUSE_LEFT_CLICK(aVisitor.mEvent)) {
4989 nsInputEvent* inputEvent = static_cast<nsInputEvent*>(aVisitor.mEvent);
4990 if (inputEvent->isControl || inputEvent->isMeta ||
4991 inputEvent->isAlt ||inputEvent->isShift) {
4992 break;
4995 // The default action is simply to dispatch DOMActivate
4996 nsCOMPtr<nsIPresShell> shell = aVisitor.mPresContext->GetPresShell();
4997 if (shell) {
4998 // single-click
4999 nsEventStatus status = nsEventStatus_eIgnore;
5000 nsUIEvent actEvent(NS_IS_TRUSTED_EVENT(aVisitor.mEvent),
5001 NS_UI_ACTIVATE, 1);
5003 rv = shell->HandleDOMEventWithTarget(this, &actEvent, &status);
5006 break;
5008 case NS_UI_ACTIVATE:
5010 nsAutoString target;
5011 GetLinkTarget(target);
5012 nsContentUtils::TriggerLink(this, aVisitor.mPresContext, absURI, target,
5013 PR_TRUE, PR_TRUE);
5015 break;
5017 case NS_KEY_PRESS:
5019 if (aVisitor.mEvent->eventStructType == NS_KEY_EVENT) {
5020 nsKeyEvent* keyEvent = static_cast<nsKeyEvent*>(aVisitor.mEvent);
5021 if (keyEvent->keyCode == NS_VK_RETURN) {
5022 nsEventStatus status = nsEventStatus_eIgnore;
5023 rv = DispatchClickEvent(aVisitor.mPresContext, keyEvent, this,
5024 PR_FALSE, &status);
5025 if (NS_SUCCEEDED(rv)) {
5026 aVisitor.mEventStatus = nsEventStatus_eConsumeNoDefault;
5031 break;
5033 default:
5034 // switch not in sync with the optimization switch earlier in this function
5035 NS_NOTREACHED("switch statements not in sync");
5036 return NS_ERROR_UNEXPECTED;
5039 return rv;
5042 void
5043 nsGenericElement::GetLinkTarget(nsAString& aTarget)
5045 aTarget.Truncate();
5048 // NOTE: The aPresContext pointer is NOT addrefed.
5049 static nsresult
5050 ParseSelectorList(nsINode* aNode,
5051 const nsAString& aSelectorString,
5052 nsCSSSelectorList** aSelectorList,
5053 nsPresContext** aPresContext)
5055 NS_ENSURE_ARG(aNode);
5057 nsIDocument* doc = aNode->GetOwnerDoc();
5058 NS_ENSURE_STATE(doc);
5060 nsCOMPtr<nsICSSParser> parser;
5061 nsresult rv = doc->CSSLoader()->GetParserFor(nsnull, getter_AddRefs(parser));
5062 NS_ENSURE_SUCCESS(rv, rv);
5064 rv = parser->ParseSelectorString(aSelectorString,
5065 doc->GetDocumentURI(),
5066 0, // XXXbz get the right line number!
5067 aSelectorList);
5068 doc->CSSLoader()->RecycleParser(parser);
5069 NS_ENSURE_SUCCESS(rv, rv);
5071 // It's not strictly necessary to have a prescontext here, but it's
5072 // a bit of an optimization for various stuff.
5073 *aPresContext = nsnull;
5074 nsIPresShell* shell = doc->GetPrimaryShell();
5075 if (shell) {
5076 *aPresContext = shell->GetPresContext();
5079 return NS_OK;
5083 * Callback to be called as we iterate over the tree and match elements. If
5084 * the callbacks returns false, the iteration should be stopped.
5086 typedef PRBool
5087 (* ElementMatchedCallback)(nsIContent* aMatchingElement, void* aClosure);
5089 // returning false means stop iteration
5090 static PRBool
5091 TryMatchingElementsInSubtree(nsINode* aRoot,
5092 RuleProcessorData* aParentData,
5093 nsPresContext* aPresContext,
5094 nsCSSSelectorList* aSelectorList,
5095 ElementMatchedCallback aCallback,
5096 void* aClosure)
5098 /* To improve the performance of '+' and '~' combinators and the :nth-*
5099 * selectors, we keep track of the immediately previous sibling data. That's
5100 * cheaper than heap-allocating all the datas and keeping track of them all,
5101 * and helps a good bit in the common cases. We also keep track of the whole
5102 * parent data chain, since we have those Around anyway */
5103 char databuf[2 * sizeof(RuleProcessorData)];
5104 RuleProcessorData* prevSibling = nsnull;
5105 RuleProcessorData* data = reinterpret_cast<RuleProcessorData*>(databuf);
5106 PRUint32 count;
5107 nsIContent * const * kidSlot = aRoot->GetChildArray(&count);
5108 nsIContent * const * end = kidSlot + count;
5110 #ifdef DEBUG
5111 nsMutationGuard debugMutationGuard;
5112 #endif
5114 PRBool continueIteration = PR_TRUE;
5115 for (; kidSlot != end; ++kidSlot) {
5116 nsIContent* kid = *kidSlot;
5117 if (!kid->IsNodeOfType(nsINode::eELEMENT)) {
5118 continue;
5120 /* See whether we match */
5121 new (data) RuleProcessorData(aPresContext, kid, nsnull);
5122 NS_ASSERTION(!data->mParentData, "Shouldn't happen");
5123 NS_ASSERTION(!data->mPreviousSiblingData, "Shouldn't happen");
5124 data->mParentData = aParentData;
5125 data->mPreviousSiblingData = prevSibling;
5127 if (nsCSSRuleProcessor::SelectorListMatches(*data, aSelectorList)) {
5128 continueIteration = (*aCallback)(kid, aClosure);
5131 if (continueIteration) {
5132 continueIteration =
5133 TryMatchingElementsInSubtree(kid, data, aPresContext, aSelectorList,
5134 aCallback, aClosure);
5137 /* Clear out the parent and previous sibling data if we set them, so that
5138 * ~RuleProcessorData won't try to delete a placement-new'd object. Make
5139 * sure this happens before our possible early break. Note that we can
5140 * have null aParentData but non-null data->mParentData if we're scoped to
5141 * an element. However, prevSibling and data->mPreviousSiblingData must
5142 * always match.
5144 NS_ASSERTION(!aParentData || data->mParentData == aParentData,
5145 "Unexpected parent");
5146 NS_ASSERTION(data->mPreviousSiblingData == prevSibling,
5147 "Unexpected prev sibling");
5148 data->mPreviousSiblingData = nsnull;
5149 if (prevSibling) {
5150 if (aParentData) {
5151 prevSibling->mParentData = nsnull;
5153 prevSibling->~RuleProcessorData();
5154 } else {
5155 /* This is the first time through, so point |prevSibling| to the location
5156 we want to have |data| end up pointing to. */
5157 prevSibling = data + 1;
5160 /* Now swap |prevSibling| and |data|. Again, before the early break */
5161 RuleProcessorData* temp = prevSibling;
5162 prevSibling = data;
5163 data = temp;
5164 if (!continueIteration) {
5165 break;
5168 if (prevSibling) {
5169 if (aParentData) {
5170 prevSibling->mParentData = nsnull;
5172 /* Make sure to clean this up */
5173 prevSibling->~RuleProcessorData();
5176 #ifdef DEBUG
5177 NS_ASSERTION(!debugMutationGuard.Mutated(0), "Unexpected mutations happened");
5178 #endif
5180 return continueIteration;
5183 static PRBool
5184 FindFirstMatchingElement(nsIContent* aMatchingElement,
5185 void* aClosure)
5187 NS_PRECONDITION(aMatchingElement && aClosure, "How did that happen?");
5188 nsIContent** slot = static_cast<nsIContent**>(aClosure);
5189 *slot = aMatchingElement;
5190 return PR_FALSE;
5193 /* static */
5194 nsresult
5195 nsGenericElement::doQuerySelector(nsINode* aRoot, const nsAString& aSelector,
5196 nsIDOMElement **aReturn)
5198 NS_PRECONDITION(aReturn, "Null out param?");
5200 nsAutoPtr<nsCSSSelectorList> selectorList;
5201 nsPresContext* presContext;
5202 nsresult rv = ParseSelectorList(aRoot, aSelector,
5203 getter_Transfers(selectorList),
5204 &presContext);
5205 NS_ENSURE_SUCCESS(rv, rv);
5207 nsIContent* foundElement = nsnull;
5208 TryMatchingElementsInSubtree(aRoot, nsnull, presContext, selectorList,
5209 FindFirstMatchingElement, &foundElement);
5211 if (foundElement) {
5212 return CallQueryInterface(foundElement, aReturn);
5215 *aReturn = nsnull;
5216 return NS_OK;
5219 static PRBool
5220 AppendAllMatchingElements(nsIContent* aMatchingElement,
5221 void* aClosure)
5223 NS_PRECONDITION(aMatchingElement && aClosure, "How did that happen?");
5224 static_cast<nsBaseContentList*>(aClosure)->AppendElement(aMatchingElement);
5225 return PR_TRUE;
5228 /* static */
5229 nsresult
5230 nsGenericElement::doQuerySelectorAll(nsINode* aRoot,
5231 const nsAString& aSelector,
5232 nsIDOMNodeList **aReturn)
5234 NS_PRECONDITION(aReturn, "Null out param?");
5236 nsBaseContentList* contentList = new nsBaseContentList();
5237 NS_ENSURE_TRUE(contentList, NS_ERROR_OUT_OF_MEMORY);
5238 NS_ADDREF(*aReturn = contentList);
5240 nsAutoPtr<nsCSSSelectorList> selectorList;
5241 nsPresContext* presContext;
5242 nsresult rv = ParseSelectorList(aRoot, aSelector,
5243 getter_Transfers(selectorList),
5244 &presContext);
5245 NS_ENSURE_SUCCESS(rv, rv);
5247 TryMatchingElementsInSubtree(aRoot, nsnull, presContext, selectorList,
5248 AppendAllMatchingElements, contentList);
5249 return NS_OK;