Back to index

lightning-sunbird  0.9+nobinonly
nsXMLDocument.cpp
Go to the documentation of this file.
00001 /* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
00002 /* ***** BEGIN LICENSE BLOCK *****
00003  * Version: MPL 1.1/GPL 2.0/LGPL 2.1
00004  *
00005  * The contents of this file are subject to the Mozilla Public License Version
00006  * 1.1 (the "License"); you may not use this file except in compliance with
00007  * the License. You may obtain a copy of the License at
00008  * http://www.mozilla.org/MPL/
00009  *
00010  * Software distributed under the License is distributed on an "AS IS" basis,
00011  * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
00012  * for the specific language governing rights and limitations under the
00013  * License.
00014  *
00015  * The Original Code is Mozilla Communicator client code.
00016  *
00017  * The Initial Developer of the Original Code is
00018  * Netscape Communications Corporation.
00019  * Portions created by the Initial Developer are Copyright (C) 1998
00020  * the Initial Developer. All Rights Reserved.
00021  *
00022  * Contributor(s):
00023  *   Pierre Phaneuf <pp@ludusdesign.com>
00024  *
00025  * Alternatively, the contents of this file may be used under the terms of
00026  * either of the GNU General Public License Version 2 or later (the "GPL"),
00027  * or the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
00028  * in which case the provisions of the GPL or the LGPL are applicable instead
00029  * of those above. If you wish to allow use of your version of this file only
00030  * under the terms of either the GPL or the LGPL, and not to allow others to
00031  * use your version of this file under the terms of the MPL, indicate your
00032  * decision by deleting the provisions above and replace them with the notice
00033  * and other provisions required by the GPL or the LGPL. If you do not delete
00034  * the provisions above, a recipient may use your version of this file under
00035  * the terms of any one of the MPL, the GPL or the LGPL.
00036  *
00037  * ***** END LICENSE BLOCK ***** */
00038 
00039 
00040 #include "nsXMLDocument.h"
00041 #include "nsParserCIID.h"
00042 #include "nsIParser.h"
00043 #include "nsIXMLContent.h"
00044 #include "nsIXMLContentSink.h"
00045 #include "nsIPresShell.h"
00046 #include "nsPresContext.h" 
00047 #include "nsIContent.h"
00048 #include "nsIContentViewerContainer.h"
00049 #include "nsIContentViewer.h"
00050 #include "nsIDocShell.h"
00051 #include "nsIMarkupDocumentViewer.h"
00052 #include "nsIDocumentLoader.h"
00053 #include "nsHTMLParts.h"
00054 #include "nsHTMLStyleSheet.h"
00055 #include "nsIHTMLCSSStyleSheet.h"
00056 #include "nsIComponentManager.h"
00057 #include "nsIDOMComment.h"
00058 #include "nsIDOMElement.h"
00059 #include "nsIDOMText.h"
00060 #include "nsIBaseWindow.h"
00061 #include "nsIDOMWindow.h"
00062 #include "nsIDOMDocumentType.h"
00063 #include "nsINameSpaceManager.h"
00064 #include "nsCOMPtr.h"
00065 #include "nsXPIDLString.h"
00066 #include "nsIHttpChannel.h"
00067 #include "nsIURI.h"
00068 #include "nsIServiceManager.h"
00069 #include "nsICharsetAlias.h"
00070 #include "nsICharsetAlias.h"
00071 #include "nsNetUtil.h"
00072 #include "nsDOMError.h"
00073 #include "nsIScriptSecurityManager.h"
00074 #include "nsIPrincipal.h"
00075 #include "nsLayoutCID.h"
00076 #include "nsDOMAttribute.h"
00077 #include "nsGUIEvent.h"
00078 #include "nsIFIXptr.h"
00079 #include "nsIXPointer.h"
00080 #include "nsCExternalHandlerService.h"
00081 #include "nsNetUtil.h"
00082 #include "nsMimeTypes.h"
00083 #include "nsIEventListenerManager.h"
00084 #include "nsContentUtils.h"
00085 #include "nsJSUtils.h"
00086 #include "nsCRT.h"
00087 #include "nsIWindowWatcher.h"
00088 #include "nsIAuthPrompt.h"
00089 #include "nsIScriptGlobalObjectOwner.h"
00090 #include "nsIJSContextStack.h"
00091 #include "nsNodeInfoManager.h"
00092 #include "nsContentCreatorFunctions.h"
00093 
00094 // XXX The XML world depends on the html atoms
00095 #include "nsHTMLAtoms.h"
00096 
00097 static const char kLoadAsData[] = "loadAsData";
00098 
00099 static NS_DEFINE_CID(kEventQueueServiceCID, NS_EVENTQUEUESERVICE_CID);
00100 static NS_DEFINE_CID(kCharsetAliasCID, NS_CHARSETALIAS_CID);
00101 
00102 
00103 // ==================================================================
00104 // =
00105 // ==================================================================
00106 
00107 
00108 nsresult
00109 NS_NewDOMDocument(nsIDOMDocument** aInstancePtrResult,
00110                   const nsAString& aNamespaceURI, 
00111                   const nsAString& aQualifiedName, 
00112                   nsIDOMDocumentType* aDoctype,
00113                   nsIURI* aBaseURI)
00114 {
00115   return NS_NewDOMDocument_MOZILLA_1_8_BRANCH(aInstancePtrResult,
00116                                               aNamespaceURI,
00117                                               aQualifiedName,
00118                                               aDoctype,
00119                                               aBaseURI,
00120                                               nsnull,
00121                                               PR_FALSE);
00122 }
00123 
00124 nsresult
00125 NS_NewDOMDocument_MOZILLA_1_8_BRANCH(nsIDOMDocument** aInstancePtrResult,
00126                                      const nsAString& aNamespaceURI,
00127                                      const nsAString& aQualifiedName,
00128                                      nsIDOMDocumentType* aDoctype,
00129                                      nsIURI* aBaseURI,
00130                                      nsIScriptGlobalObject* aScriptHandler,
00131                                      PRBool aLoadedAsData)
00132 {
00133   nsresult rv;
00134 
00135   *aInstancePtrResult = nsnull;
00136 
00137   nsRefPtr<nsXMLDocument> doc = new nsXMLDocument();
00138   if (!doc)
00139     return NS_ERROR_OUT_OF_MEMORY;
00140 
00141   rv = doc->Init();
00142 
00143   if (NS_FAILED(rv)) {
00144     return rv;
00145   }
00146 
00147   doc->SetScriptHandlingObject(aScriptHandler);
00148   // This is not used on 1.8 branch because of
00149   // https://bugzilla.mozilla.org/show_bug.cgi?id=414856
00150   // doc->SetLoadedAsData(aLoadedAsData);
00151   doc->nsIDocument::SetDocumentURI(aBaseURI);
00152   doc->SetBaseURI(aBaseURI);
00153 
00154   if (aDoctype) {
00155     nsCOMPtr<nsIDOMNode> tmpNode;
00156     rv = doc->AppendChild(aDoctype, getter_AddRefs(tmpNode));
00157     NS_ENSURE_SUCCESS(rv, rv);
00158   }
00159   
00160   if (!aQualifiedName.IsEmpty()) {
00161     nsCOMPtr<nsIDOMElement> root;
00162     rv = doc->CreateElementNS(aNamespaceURI, aQualifiedName,
00163                               getter_AddRefs(root));
00164     NS_ENSURE_SUCCESS(rv, rv);
00165 
00166     nsCOMPtr<nsIDOMNode> tmpNode;
00167 
00168     rv = doc->AppendChild(root, getter_AddRefs(tmpNode));
00169     NS_ENSURE_SUCCESS(rv, rv);
00170   }
00171 
00172   *aInstancePtrResult = doc;
00173   NS_ADDREF(*aInstancePtrResult);
00174 
00175   return NS_OK;
00176 }
00177 
00178 
00179 nsresult
00180 NS_NewXMLDocument(nsIDocument** aInstancePtrResult)
00181 {
00182   nsXMLDocument* doc = new nsXMLDocument();
00183   NS_ENSURE_TRUE(doc, NS_ERROR_OUT_OF_MEMORY);
00184 
00185   NS_ADDREF(doc);
00186   nsresult rv = doc->Init();
00187 
00188   if (NS_FAILED(rv)) {
00189     NS_RELEASE(doc);
00190   }
00191 
00192   *aInstancePtrResult = doc;
00193 
00194   return rv;
00195 }
00196 
00197   // NOTE! nsDocument::operator new() zeroes out all members, so don't
00198   // bother initializing members to 0.
00199 
00200 nsXMLDocument::nsXMLDocument() 
00201   : mAsync(PR_TRUE)
00202 {
00203 
00204   // NOTE! nsDocument::operator new() zeroes out all members, so don't
00205   // bother initializing members to 0.
00206 }
00207 
00208 nsXMLDocument::~nsXMLDocument()
00209 {
00210   // XXX We rather crash than hang
00211   mLoopingForSyncLoad = PR_FALSE;
00212 }
00213 
00214 
00215 // QueryInterface implementation for nsXMLDocument
00216 NS_INTERFACE_MAP_BEGIN(nsXMLDocument)
00217   NS_INTERFACE_MAP_ENTRY(nsIInterfaceRequestor)
00218   NS_INTERFACE_MAP_ENTRY(nsIChannelEventSink)
00219   NS_INTERFACE_MAP_ENTRY(nsIDOMXMLDocument)
00220   NS_INTERFACE_MAP_ENTRY_CONTENT_CLASSINFO(XMLDocument)
00221 NS_INTERFACE_MAP_END_INHERITING(nsDocument)
00222 
00223 
00224 NS_IMPL_ADDREF_INHERITED(nsXMLDocument, nsDocument)
00225 NS_IMPL_RELEASE_INHERITED(nsXMLDocument, nsDocument)
00226 
00227 
00228 nsresult
00229 nsXMLDocument::Init()
00230 {
00231   nsresult rv = nsDocument::Init();
00232   NS_ENSURE_SUCCESS(rv, rv);
00233 
00234   mEventQService = do_GetService(kEventQueueServiceCID, &rv);
00235 
00236   return rv;
00237 }
00238 
00239 void
00240 nsXMLDocument::Reset(nsIChannel* aChannel, nsILoadGroup* aLoadGroup)
00241 {
00242   nsDocument::Reset(aChannel, aLoadGroup);
00243 
00244   mScriptContext = nsnull;
00245 }
00246 
00247 void
00248 nsXMLDocument::ResetToURI(nsIURI *aURI, nsILoadGroup *aLoadGroup)
00249 {
00250   if (mChannelIsPending) {
00251     StopDocumentLoad();
00252     mChannel->Cancel(NS_BINDING_ABORTED);
00253     mChannelIsPending = nsnull;
00254   }
00255   
00256   nsDocument::ResetToURI(aURI, aLoadGroup);
00257 }
00258 
00260 // nsIInterfaceRequestor methods:
00261 //
00262 NS_IMETHODIMP
00263 nsXMLDocument::GetInterface(const nsIID& aIID, void** aSink)
00264 {
00265   if (aIID.Equals(NS_GET_IID(nsIAuthPrompt))) {
00266     NS_ENSURE_ARG_POINTER(aSink);
00267     *aSink = nsnull;
00268 
00269     nsresult rv;
00270     nsCOMPtr<nsIWindowWatcher> ww(do_GetService(NS_WINDOWWATCHER_CONTRACTID, &rv));
00271     if (NS_FAILED(rv))
00272       return rv;
00273 
00274     nsCOMPtr<nsIAuthPrompt> prompt;
00275     rv = ww->GetNewAuthPrompter(nsnull, getter_AddRefs(prompt));
00276     if (NS_FAILED(rv))
00277       return rv;
00278 
00279     nsIAuthPrompt *p = prompt.get();
00280     NS_ADDREF(p);
00281     *aSink = p;
00282     return NS_OK;
00283   }
00284 
00285 
00286   return QueryInterface(aIID, aSink);
00287 }
00288 
00289 // nsIChannelEventSink
00290 NS_IMETHODIMP
00291 nsXMLDocument::OnChannelRedirect(nsIChannel *aOldChannel,
00292                                  nsIChannel *aNewChannel,
00293                                  PRUint32 aFlags)
00294 {
00295   NS_PRECONDITION(aNewChannel, "Redirecting to null channel?");
00296 
00297   nsCOMPtr<nsIURI> oldURI;
00298   nsresult rv = aOldChannel->GetURI(getter_AddRefs(oldURI));
00299   NS_ENSURE_SUCCESS(rv, rv);
00300 
00301   nsCOMPtr<nsIURI> newURI;
00302   rv = aNewChannel->GetURI(getter_AddRefs(newURI));
00303   NS_ENSURE_SUCCESS(rv, rv);
00304 
00305   return nsContentUtils::GetSecurityManager()->
00306     CheckSameOriginURI(oldURI, newURI);
00307 }
00308 
00309 NS_IMETHODIMP
00310 nsXMLDocument::EvaluateFIXptr(const nsAString& aExpression, nsIDOMRange **aRange)
00311 {
00312   nsresult rv;
00313   nsCOMPtr<nsIFIXptrEvaluator> e =
00314     do_CreateInstance("@mozilla.org/xmlextras/fixptrevaluator;1", &rv);
00315   NS_ENSURE_SUCCESS(rv, rv);
00316   
00317   return e->Evaluate(this, aExpression, aRange);
00318 }
00319 
00320 NS_IMETHODIMP
00321 nsXMLDocument::EvaluateXPointer(const nsAString& aExpression,
00322                                 nsIXPointerResult **aResult)
00323 {
00324   nsresult rv;
00325   nsCOMPtr<nsIXPointerEvaluator> e =
00326     do_CreateInstance("@mozilla.org/xmlextras/xpointerevaluator;1", &rv);
00327   NS_ENSURE_SUCCESS(rv, rv);
00328   
00329   return e->Evaluate(this, aExpression, aResult);
00330 }
00331 
00332 NS_IMETHODIMP
00333 nsXMLDocument::GetAsync(PRBool *aAsync)
00334 {
00335   NS_ENSURE_ARG_POINTER(aAsync);
00336   *aAsync = mAsync;
00337   return NS_OK;
00338 }
00339 
00340 NS_IMETHODIMP
00341 nsXMLDocument::SetAsync(PRBool aAsync)
00342 {
00343   mAsync = aAsync;
00344   return NS_OK;
00345 }
00346 
00347 nsresult 
00348 nsXMLDocument::GetLoadGroup(nsILoadGroup **aLoadGroup)
00349 {
00350   NS_ENSURE_ARG_POINTER(aLoadGroup);
00351   *aLoadGroup = nsnull;
00352 
00353   if (mScriptContext) {
00354     nsCOMPtr<nsIDOMWindow> window =
00355       do_QueryInterface(mScriptContext->GetGlobalObject());
00356 
00357     if (window) {
00358       nsCOMPtr<nsIDOMDocument> domdoc;
00359       window->GetDocument(getter_AddRefs(domdoc));
00360       nsCOMPtr<nsIDocument> doc = do_QueryInterface(domdoc);
00361       if (doc) {
00362         *aLoadGroup = doc->GetDocumentLoadGroup().get(); // already_AddRefed
00363       }
00364     }
00365   }
00366 
00367   return NS_OK;
00368 }
00369 
00370 
00371 NS_IMETHODIMP
00372 nsXMLDocument::Load(const nsAString& aUrl, PRBool *aReturn)
00373 {
00374   NS_ENSURE_ARG_POINTER(aReturn);
00375   *aReturn = PR_FALSE;
00376 
00377   nsIScriptContext *callingContext = nsnull;
00378 
00379   nsCOMPtr<nsIJSContextStack> stack =
00380     do_GetService("@mozilla.org/js/xpc/ContextStack;1");
00381   if (stack) {
00382     JSContext *cx;
00383     if (NS_SUCCEEDED(stack->Peek(&cx)) && cx) {
00384       callingContext = nsJSUtils::GetDynamicScriptContext(cx);
00385     }
00386   }
00387 
00388   nsIURI *baseURI = mDocumentURI;
00389   nsCAutoString charset;
00390 
00391   if (callingContext) {
00392     nsCOMPtr<nsIDOMWindow> window =
00393       do_QueryInterface(callingContext->GetGlobalObject());
00394 
00395     if (window) {
00396       nsCOMPtr<nsIDOMDocument> dom_doc;
00397       window->GetDocument(getter_AddRefs(dom_doc));
00398       nsCOMPtr<nsIDocument> doc(do_QueryInterface(dom_doc));
00399 
00400       if (doc) {
00401         baseURI = doc->GetBaseURI();
00402         charset = doc->GetDocumentCharacterSet();
00403       }
00404     }
00405   }
00406 
00407   // Create a new URI
00408   nsCOMPtr<nsIURI> uri;
00409   nsresult rv = NS_NewURI(getter_AddRefs(uri), aUrl, charset.get(), baseURI);
00410   if (NS_FAILED(rv)) {
00411     return rv;
00412   }
00413 
00414   // Partial Reset, need to restore principal for security reasons and
00415   // event listener manager so that load listeners etc. will
00416   // remain. This should be done before the security check is done to
00417   // ensure that the document is reset even if the new document can't
00418   // be loaded.
00419   nsCOMPtr<nsIPrincipal> principal(mPrincipal);
00420   nsCOMPtr<nsIEventListenerManager> elm(mListenerManager);
00421   mListenerManager = nsnull;
00422 
00423   ResetToURI(uri, nsnull);
00424 
00425   mPrincipal = principal;
00426   mListenerManager = elm;
00427 
00428   // Get security manager, check to see if we're allowed to load this URI
00429   nsCOMPtr<nsIScriptSecurityManager> secMan = 
00430            do_GetService(NS_SCRIPTSECURITYMANAGER_CONTRACTID, &rv);
00431   if (NS_FAILED(rv)) {
00432     return rv;
00433   }
00434 
00435   rv = secMan->CheckConnect(nsnull, uri, "XMLDocument", "load");
00436   if (NS_FAILED(rv)) {
00437     // We need to return success here so that JS will get a proper
00438     // exception thrown later. Native calls should always result in
00439     // CheckConnect() succeeding, but in case JS calls C++ which calls
00440     // this code the exception might be lost.
00441     return NS_OK;
00442   }
00443 
00444   // Store script context, if any, in case we encounter redirect
00445   // (because we need it there)
00446 
00447   mScriptContext = callingContext;
00448 
00449   // Create a channel
00450   // When we are called from JS we can find the load group for the page,
00451   // and add ourselves to it. This way any pending requests
00452   // will be automatically aborted if the user leaves the page.
00453   nsCOMPtr<nsILoadGroup> loadGroup;
00454   GetLoadGroup(getter_AddRefs(loadGroup));
00455 
00456   nsCOMPtr<nsIChannel> channel;
00457   // nsIRequest::LOAD_BACKGROUND prevents throbber from becoming active,
00458   // which in turn keeps STOP button from becoming active  
00459   rv = NS_NewChannel(getter_AddRefs(channel), uri, nsnull, loadGroup, this, 
00460                      nsIRequest::LOAD_BACKGROUND);
00461   if (NS_FAILED(rv)) {
00462     return rv;
00463   }
00464 
00465   // Set a principal for this document
00466   nsCOMPtr<nsISupports> channelOwner;
00467   rv = channel->GetOwner(getter_AddRefs(channelOwner));
00468 
00469   // We don't care if GetOwner() succeeded here, if it failed,
00470   // channelOwner will be null, which is what we want in that case.
00471 
00472   mPrincipal = do_QueryInterface(channelOwner);
00473 
00474   if (NS_FAILED(rv) || !mPrincipal) {
00475     rv = secMan->GetCodebasePrincipal(uri, getter_AddRefs(mPrincipal));
00476     NS_ENSURE_TRUE(mPrincipal, rv);
00477   }
00478 
00479   nsCOMPtr<nsIEventQueue> modalEventQueue;
00480 
00481   if(!mAsync) {
00482     NS_ENSURE_TRUE(mEventQService, NS_ERROR_FAILURE);
00483 
00484     rv = mEventQService->PushThreadEventQueue(getter_AddRefs(modalEventQueue));
00485     if (NS_FAILED(rv)) {
00486       return rv;
00487     }
00488   }
00489 
00490   // Prepare for loading the XML document "into oneself"
00491   nsCOMPtr<nsIStreamListener> listener;
00492   if (NS_FAILED(rv = StartDocumentLoad(kLoadAsData, channel, 
00493                                        loadGroup, nsnull, 
00494                                        getter_AddRefs(listener),
00495                                        PR_FALSE))) {
00496     NS_ERROR("nsXMLDocument::Load: Failed to start the document load.");
00497     if (modalEventQueue) {
00498       mEventQService->PopThreadEventQueue(modalEventQueue);
00499     }
00500     return rv;
00501   }
00502 
00503   // After this point, if we error out of this method we should clear
00504   // mChannelIsPending.
00505 
00506   // Start an asynchronous read of the XML document
00507   rv = channel->AsyncOpen(listener, nsnull);
00508   if (NS_FAILED(rv)) {
00509     mChannelIsPending = PR_FALSE;
00510     if (modalEventQueue) {
00511       mEventQService->PopThreadEventQueue(modalEventQueue);
00512     }
00513     return rv;
00514   }
00515 
00516   if (!mAsync) {
00517     mLoopingForSyncLoad = PR_TRUE;
00518 
00519     while (mLoopingForSyncLoad) {
00520       modalEventQueue->ProcessPendingEvents();
00521     }
00522 
00523     mEventQService->PopThreadEventQueue(modalEventQueue);
00524 
00525     // We set return to true unless there was a parsing error
00526     nsCOMPtr<nsIDOMNode> node = do_QueryInterface(mRootContent);
00527     if (node) {
00528       nsAutoString name, ns;      
00529       if (NS_SUCCEEDED(node->GetLocalName(name)) &&
00530           name.EqualsLiteral("parsererror") &&
00531           NS_SUCCEEDED(node->GetNamespaceURI(ns)) &&
00532           ns.EqualsLiteral("http://www.mozilla.org/newlayout/xml/parsererror.xml")) {
00533         //return is already false
00534       } else {
00535         *aReturn = PR_TRUE;
00536       }
00537     }
00538   } else {
00539     *aReturn = PR_TRUE;
00540   }
00541 
00542   return NS_OK;
00543 }
00544 
00545 nsresult
00546 nsXMLDocument::StartDocumentLoad(const char* aCommand,
00547                                  nsIChannel* aChannel,
00548                                  nsILoadGroup* aLoadGroup,
00549                                  nsISupports* aContainer,
00550                                  nsIStreamListener **aDocListener,
00551                                  PRBool aReset,
00552                                  nsIContentSink* aSink)
00553 {
00554   if (nsCRT::strcmp(kLoadAsData, aCommand) == 0) {
00555     mLoadedAsData = PR_TRUE;
00556     // We need to disable script & style loading in this case.
00557     // We leave them disabled even in EndLoad(), and let anyone
00558     // who puts the document on display to worry about enabling.
00559 
00560     // scripts
00561     nsIScriptLoader *loader = GetScriptLoader();
00562     if (loader) {
00563       loader->SetEnabled(PR_FALSE); // Do not load/process scripts when loading as data
00564     }
00565 
00566     // styles
00567     CSSLoader()->SetEnabled(PR_FALSE); // Do not load/process styles when loading as data
00568   } else if (nsCRT::strcmp("loadAsInteractiveData", aCommand) == 0) {
00569     mLoadedAsInteractiveData = PR_TRUE;
00570     aCommand = kLoadAsData; // XBL, for example, needs scripts and styles
00571   }
00572 
00573   nsresult rv = nsDocument::StartDocumentLoad(aCommand,
00574                                               aChannel, aLoadGroup,
00575                                               aContainer, 
00576                                               aDocListener, aReset, aSink);
00577   if (NS_FAILED(rv)) return rv;
00578 
00579   PRInt32 charsetSource = kCharsetFromDocTypeDefault;
00580   nsCAutoString charset(NS_LITERAL_CSTRING("UTF-8"));
00581   TryChannelCharset(aChannel, charsetSource, charset);
00582 
00583   nsCOMPtr<nsIURI> aUrl;
00584   rv = aChannel->GetURI(getter_AddRefs(aUrl));
00585   if (NS_FAILED(rv)) return rv;
00586 
00587   static NS_DEFINE_CID(kCParserCID, NS_PARSER_CID);
00588 
00589   mParser = do_CreateInstance(kCParserCID, &rv);
00590   NS_ENSURE_SUCCESS(rv, rv);
00591 
00592   nsCOMPtr<nsIXMLContentSink> sink;
00593     
00594   if (aSink) {
00595     sink = do_QueryInterface(aSink);
00596   }
00597   else {
00598     nsCOMPtr<nsIDocShell> docShell;
00599     if (aContainer) {
00600       docShell = do_QueryInterface(aContainer);
00601       NS_ENSURE_TRUE(docShell, NS_ERROR_FAILURE);
00602     }
00603     rv = NS_NewXMLContentSink(getter_AddRefs(sink), this, aUrl, docShell,
00604                               aChannel);
00605     NS_ENSURE_SUCCESS(rv, rv);
00606   }
00607 
00608   // Set the parser as the stream listener for the document loader...
00609   rv = CallQueryInterface(mParser, aDocListener);
00610   NS_ENSURE_SUCCESS(rv, rv);
00611 
00612   NS_ASSERTION(mChannel, "How can we not have a channel here?");
00613   mChannelIsPending = PR_TRUE;
00614   
00615   SetDocumentCharacterSet(charset);
00616   mParser->SetDocumentCharset(charset, charsetSource);
00617   mParser->SetCommand(aCommand);
00618   mParser->SetContentSink(sink);
00619   mParser->Parse(aUrl, nsnull, PR_FALSE, (void *)this);
00620 
00621   return NS_OK;
00622 }
00623 
00624 void
00625 nsXMLDocument::EndLoad()
00626 {
00627   mChannelIsPending = PR_FALSE;
00628   mLoopingForSyncLoad = PR_FALSE;
00629 
00630   if (mLoadedAsData || mLoadedAsInteractiveData) {
00631     // Generate a document load event for the case when an XML
00632     // document was loaded as pure data without any presentation
00633     // attached to it.
00634     nsEvent event(PR_TRUE, NS_PAGE_LOAD);
00635     nsEventStatus status = nsEventStatus_eIgnore;
00636 
00637     nsIScriptGlobalObject* sgo = nsnull;
00638     nsCOMPtr<nsIScriptGlobalObjectOwner> container =
00639       do_QueryReferent(mDocumentContainer);
00640     if (container) {
00641       sgo = container->GetScriptGlobalObject();
00642     }
00643 
00644     nsCxPusher pusher;
00645     if (pusher.Push(sgo)) {
00646       HandleDOMEvent(nsnull, &event, nsnull, NS_EVENT_FLAG_INIT, &status);
00647     }
00648   }    
00649   nsDocument::EndLoad();  
00650 }
00651 
00652 PRBool
00653 nsXMLDocument::IsLoadedAsData()
00654 {
00655   return mLoadedAsData;
00656 }
00657   
00658 
00659 // nsIDOMNode interface
00660 
00661 NS_IMETHODIMP    
00662 nsXMLDocument::CloneNode(PRBool aDeep, nsIDOMNode** aReturn)
00663 {
00664   NS_ENSURE_ARG_POINTER(aReturn);
00665   *aReturn = nsnull;
00666 
00667   nsresult rv;
00668   nsCOMPtr<nsIDOMDocumentType> docType, newDocType;
00669   nsCOMPtr<nsIDOMDocument> newDoc;
00670 
00671   // Get the doctype prior to new document construction. There's no big 
00672   // advantage now to dealing with the doctype separately, but maybe one 
00673   // day we'll do something significant with the doctype on document creation.
00674   GetDoctype(getter_AddRefs(docType));
00675   if (docType) {
00676     nsCOMPtr<nsIDOMNode> newDocTypeNode;
00677     rv = docType->CloneNode(PR_TRUE, getter_AddRefs(newDocTypeNode));
00678     if (NS_FAILED(rv)) return rv;
00679     newDocType = do_QueryInterface(newDocTypeNode);
00680   }
00681 
00682   PRBool hasHadScriptObject = PR_TRUE;
00683   nsIScriptGlobalObject* scriptObject =
00684     GetScriptHandlingObject(hasHadScriptObject);
00685   NS_ENSURE_STATE(scriptObject || !hasHadScriptObject);
00686 
00687   // Create an empty document
00688   nsAutoString emptyStr;
00689   emptyStr.Truncate();
00690   rv = NS_NewDOMDocument_MOZILLA_1_8_BRANCH(getter_AddRefs(newDoc), emptyStr,
00691                                             emptyStr, newDocType, mDocumentURI,
00692                                             scriptObject, PR_TRUE);
00693   if (NS_FAILED(rv)) return rv;
00694 
00695   if (aDeep) {
00696     // If there was a doctype, a new one has already been inserted into the
00697     // new document. We might have to add nodes before it.
00698     PRBool beforeDocType = (docType.get() != nsnull);
00699     nsCOMPtr<nsIDOMNodeList> childNodes;
00700     
00701     GetChildNodes(getter_AddRefs(childNodes));
00702     if (childNodes) {
00703       PRUint32 index, count;
00704       childNodes->GetLength(&count);
00705       for (index=0; index < count; index++) {
00706         nsCOMPtr<nsIDOMNode> child;
00707         childNodes->Item(index, getter_AddRefs(child));
00708         if (child && (child != docType)) {
00709           nsCOMPtr<nsIDOMNode> newChild;
00710           rv = child->CloneNode(aDeep, getter_AddRefs(newChild));
00711           if (NS_FAILED(rv)) return rv;
00712           
00713           nsCOMPtr<nsIDOMNode> dummyNode;
00714           if (beforeDocType) {
00715             rv = newDoc->InsertBefore(newChild, 
00716                                       docType, 
00717                                       getter_AddRefs(dummyNode));
00718             if (NS_FAILED(rv)) return NS_ERROR_FAILURE;
00719           }
00720           else {
00721             rv = newDoc->AppendChild(newChild, 
00722                                      getter_AddRefs(dummyNode));
00723             if (NS_FAILED(rv)) return NS_ERROR_FAILURE;
00724           }
00725         }
00726         else {
00727           beforeDocType = PR_FALSE;
00728         }
00729       }
00730     }
00731   }
00732 
00733   return CallQueryInterface(newDoc, aReturn);
00734 }
00735  
00736 // Id attribute matching function used by nsXMLDocument and
00737 // nsHTMLDocument.
00738 nsIContent *
00739 MatchElementId(nsIContent *aContent, const nsACString& aUTF8Id, const nsAString& aId)
00740 {
00741   if (aContent->IsContentOfType(nsIContent::eHTML)) {
00742     if (aContent->HasAttr(kNameSpaceID_None, nsHTMLAtoms::id)) {
00743       nsAutoString value;
00744       aContent->GetAttr(kNameSpaceID_None, nsHTMLAtoms::id, value);
00745 
00746       if (aId.Equals(value)) {
00747         return aContent;
00748       }
00749     }
00750   }
00751   else if (aContent->IsContentOfType(nsIContent::eELEMENT)) {
00752     nsCOMPtr<nsIXMLContent> xmlContent = do_QueryInterface(aContent);    
00753 
00754     if (xmlContent) {
00755       nsIAtom* value = xmlContent->GetID();
00756       if (value && value->EqualsUTF8(aUTF8Id)) {
00757         return aContent;
00758       }
00759     }
00760   }
00761   
00762   nsIContent *result = nsnull;
00763   PRUint32 i, count = aContent->GetChildCount();
00764 
00765   for (i = 0; i < count && result == nsnull; i++) {
00766     result = MatchElementId(aContent->GetChildAt(i), aUTF8Id, aId);
00767   }  
00768 
00769   return result;
00770 }
00771 
00772 // nsIDOMDocument interface
00773 
00774 NS_IMETHODIMP
00775 nsXMLDocument::GetElementById(const nsAString& aElementId,
00776                               nsIDOMElement** aReturn)
00777 {
00778   NS_ENSURE_ARG_POINTER(aReturn);
00779   *aReturn = nsnull;
00780 
00781   NS_WARN_IF_FALSE(!aElementId.IsEmpty(), "getElementById(\"\"), fix caller?");
00782   if (aElementId.IsEmpty())
00783     return NS_OK;
00784 
00785   // If we tried to load a document and something went wrong, we might not have
00786   // root content. This can happen when you do document.load() and the document
00787   // to load is not XML, for example.
00788   if (!mRootContent)
00789     return NS_OK;
00790 
00791   // XXX For now, we do a brute force search of the content tree.
00792   // We should come up with a more efficient solution.
00793   // Note that content is *not* refcounted here, so do *not* release it!
00794   nsIContent *content = MatchElementId(mRootContent,
00795                                        NS_ConvertUCS2toUTF8(aElementId),
00796                                        aElementId);
00797 
00798   if (!content) {
00799     return NS_OK;
00800   }
00801 
00802   return CallQueryInterface(content, aReturn);
00803 }