Bumping manifests a=b2g-bump
[gecko.git] / dom / xml / nsXMLContentSink.cpp
blobcb360a102c37f9ad16e6536068056f5418cb7552
1 /* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
2 /* vim: set ts=2 sw=2 et tw=78: */
3 /* This Source Code Form is subject to the terms of the Mozilla Public
4 * License, v. 2.0. If a copy of the MPL was not distributed with this
5 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
7 #include "nsCOMPtr.h"
8 #include "nsXMLContentSink.h"
9 #include "nsIParser.h"
10 #include "nsIDocument.h"
11 #include "nsIDOMDocument.h"
12 #include "nsIDOMDocumentType.h"
13 #include "nsIContent.h"
14 #include "nsIURI.h"
15 #include "nsNetUtil.h"
16 #include "nsIDocShell.h"
17 #include "nsIStyleSheetLinkingElement.h"
18 #include "nsIDOMComment.h"
19 #include "nsIDOMCDATASection.h"
20 #include "DocumentType.h"
21 #include "nsHTMLParts.h"
22 #include "nsCRT.h"
23 #include "mozilla/CSSStyleSheet.h"
24 #include "mozilla/css/Loader.h"
25 #include "nsGkAtoms.h"
26 #include "nsContentUtils.h"
27 #include "nsIScriptContext.h"
28 #include "nsNameSpaceManager.h"
29 #include "nsIServiceManager.h"
30 #include "nsIScriptSecurityManager.h"
31 #include "nsIContentViewer.h"
32 #include "prtime.h"
33 #include "prlog.h"
34 #include "prmem.h"
35 #include "nsRect.h"
36 #include "nsIWebNavigation.h"
37 #include "nsIScriptElement.h"
38 #include "nsScriptLoader.h"
39 #include "nsStyleLinkElement.h"
40 #include "nsReadableUtils.h"
41 #include "nsUnicharUtils.h"
42 #include "nsICookieService.h"
43 #include "nsIPrompt.h"
44 #include "nsIChannel.h"
45 #include "nsIPrincipal.h"
46 #include "nsXMLPrettyPrinter.h"
47 #include "nsNodeInfoManager.h"
48 #include "nsContentCreatorFunctions.h"
49 #include "nsIContentPolicy.h"
50 #include "nsContentPolicyUtils.h"
51 #include "nsError.h"
52 #include "nsIDOMProcessingInstruction.h"
53 #include "nsNodeUtils.h"
54 #include "nsIScriptGlobalObject.h"
55 #include "nsIHTMLDocument.h"
56 #include "mozAutoDocUpdate.h"
57 #include "nsMimeTypes.h"
58 #include "nsHtml5SVGLoadDispatcher.h"
59 #include "nsTextNode.h"
60 #include "mozilla/dom/CDATASection.h"
61 #include "mozilla/dom/Comment.h"
62 #include "mozilla/dom/Element.h"
63 #include "mozilla/dom/HTMLTemplateElement.h"
64 #include "mozilla/dom/ProcessingInstruction.h"
66 using namespace mozilla;
67 using namespace mozilla::dom;
69 // XXX Open Issues:
70 // 1) what's not allowed - We need to figure out which HTML tags
71 // (prefixed with a HTML namespace qualifier) are explicitly not
72 // allowed (if any).
73 // 2) factoring code with nsHTMLContentSink - There's some amount of
74 // common code between this and the HTML content sink. This will
75 // increase as we support more and more HTML elements. How can code
76 // from the code be factored?
78 nsresult
79 NS_NewXMLContentSink(nsIXMLContentSink** aResult,
80 nsIDocument* aDoc,
81 nsIURI* aURI,
82 nsISupports* aContainer,
83 nsIChannel* aChannel)
85 NS_PRECONDITION(nullptr != aResult, "null ptr");
86 if (nullptr == aResult) {
87 return NS_ERROR_NULL_POINTER;
89 nsXMLContentSink* it = new nsXMLContentSink();
91 nsCOMPtr<nsIXMLContentSink> kungFuDeathGrip = it;
92 nsresult rv = it->Init(aDoc, aURI, aContainer, aChannel);
93 NS_ENSURE_SUCCESS(rv, rv);
95 return CallQueryInterface(it, aResult);
98 nsXMLContentSink::nsXMLContentSink()
99 : mConstrainSize(true),
100 mPrettyPrintXML(true)
104 nsXMLContentSink::~nsXMLContentSink()
106 if (mText) {
107 PR_Free(mText); // Doesn't null out, unlike PR_FREEIF
111 nsresult
112 nsXMLContentSink::Init(nsIDocument* aDoc,
113 nsIURI* aURI,
114 nsISupports* aContainer,
115 nsIChannel* aChannel)
117 nsresult rv = nsContentSink::Init(aDoc, aURI, aContainer, aChannel);
118 NS_ENSURE_SUCCESS(rv, rv);
120 aDoc->AddObserver(this);
121 mIsDocumentObserver = true;
123 if (!mDocShell) {
124 mPrettyPrintXML = false;
127 mState = eXMLContentSinkState_InProlog;
128 mDocElement = nullptr;
130 return NS_OK;
133 NS_INTERFACE_MAP_BEGIN_CYCLE_COLLECTION_INHERITED(nsXMLContentSink)
134 NS_INTERFACE_MAP_ENTRY(nsIContentSink)
135 NS_INTERFACE_MAP_ENTRY(nsIXMLContentSink)
136 NS_INTERFACE_MAP_ENTRY(nsIExpatSink)
137 NS_INTERFACE_MAP_ENTRY(nsITransformObserver)
138 NS_INTERFACE_MAP_END_INHERITING(nsContentSink)
140 NS_IMPL_ADDREF_INHERITED(nsXMLContentSink, nsContentSink)
141 NS_IMPL_RELEASE_INHERITED(nsXMLContentSink, nsContentSink)
143 NS_IMPL_CYCLE_COLLECTION_CLASS(nsXMLContentSink)
145 NS_IMPL_CYCLE_COLLECTION_TRAVERSE_BEGIN_INHERITED(nsXMLContentSink,
146 nsContentSink)
147 NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mCurrentHead)
148 NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mDocElement)
149 for (uint32_t i = 0, count = tmp->mContentStack.Length(); i < count; i++) {
150 const StackNode& node = tmp->mContentStack.ElementAt(i);
151 cb.NoteXPCOMChild(node.mContent);
153 NS_IMPL_CYCLE_COLLECTION_TRAVERSE_END
155 // nsIContentSink
156 NS_IMETHODIMP
157 nsXMLContentSink::WillParse(void)
159 return WillParseImpl();
162 NS_IMETHODIMP
163 nsXMLContentSink::WillBuildModel(nsDTDMode aDTDMode)
165 WillBuildModelImpl();
167 // Notify document that the load is beginning
168 mDocument->BeginLoad();
170 // Check for correct load-command for maybe prettyprinting
171 if (mPrettyPrintXML) {
172 nsAutoCString command;
173 GetParser()->GetCommand(command);
174 if (!command.EqualsLiteral("view")) {
175 mPrettyPrintXML = false;
179 return NS_OK;
182 bool
183 nsXMLContentSink::CanStillPrettyPrint()
185 return mPrettyPrintXML &&
186 (!mPrettyPrintHasFactoredElements || mPrettyPrintHasSpecialRoot);
189 nsresult
190 nsXMLContentSink::MaybePrettyPrint()
192 if (!CanStillPrettyPrint()) {
193 mPrettyPrintXML = false;
195 return NS_OK;
198 // stop observing in order to avoid crashing when replacing content
199 mDocument->RemoveObserver(this);
200 mIsDocumentObserver = false;
202 // Reenable the CSSLoader so that the prettyprinting stylesheets can load
203 if (mCSSLoader) {
204 mCSSLoader->SetEnabled(true);
207 nsRefPtr<nsXMLPrettyPrinter> printer;
208 nsresult rv = NS_NewXMLPrettyPrinter(getter_AddRefs(printer));
209 NS_ENSURE_SUCCESS(rv, rv);
211 bool isPrettyPrinting;
212 rv = printer->PrettyPrint(mDocument, &isPrettyPrinting);
213 NS_ENSURE_SUCCESS(rv, rv);
215 mPrettyPrinting = isPrettyPrinting;
216 return NS_OK;
219 static void
220 CheckXSLTParamPI(nsIDOMProcessingInstruction* aPi,
221 nsIDocumentTransformer* aProcessor,
222 nsIDocument* aDocument)
224 nsAutoString target, data;
225 aPi->GetTarget(target);
227 // Check for namespace declarations
228 if (target.EqualsLiteral("xslt-param-namespace")) {
229 aPi->GetData(data);
230 nsAutoString prefix, namespaceAttr;
231 nsContentUtils::GetPseudoAttributeValue(data, nsGkAtoms::prefix,
232 prefix);
233 if (!prefix.IsEmpty() &&
234 nsContentUtils::GetPseudoAttributeValue(data, nsGkAtoms::_namespace,
235 namespaceAttr)) {
236 aProcessor->AddXSLTParamNamespace(prefix, namespaceAttr);
240 // Check for actual parameters
241 else if (target.EqualsLiteral("xslt-param")) {
242 aPi->GetData(data);
243 nsAutoString name, namespaceAttr, select, value;
244 nsContentUtils::GetPseudoAttributeValue(data, nsGkAtoms::name,
245 name);
246 nsContentUtils::GetPseudoAttributeValue(data, nsGkAtoms::_namespace,
247 namespaceAttr);
248 if (!nsContentUtils::GetPseudoAttributeValue(data, nsGkAtoms::select, select)) {
249 select.SetIsVoid(true);
251 if (!nsContentUtils::GetPseudoAttributeValue(data, nsGkAtoms::value, value)) {
252 value.SetIsVoid(true);
254 if (!name.IsEmpty()) {
255 nsCOMPtr<nsIDOMNode> doc = do_QueryInterface(aDocument);
256 aProcessor->AddXSLTParam(name, namespaceAttr, select, value, doc);
261 NS_IMETHODIMP
262 nsXMLContentSink::DidBuildModel(bool aTerminated)
264 if (!mParser) {
265 // If mParser is null, this parse has already been terminated and must
266 // not been terminated again. However, nsDocument may still think that
267 // the parse has not been terminated and call back into here in the case
268 // where the XML parser has finished but the XSLT transform associated
269 // with the document has not.
270 return NS_OK;
273 DidBuildModelImpl(aTerminated);
275 if (mXSLTProcessor) {
276 // stop observing in order to avoid crashing when replacing content
277 mDocument->RemoveObserver(this);
278 mIsDocumentObserver = false;
280 // Check for xslt-param and xslt-param-namespace PIs
281 for (nsIContent* child = mDocument->GetFirstChild();
282 child;
283 child = child->GetNextSibling()) {
284 if (child->IsNodeOfType(nsINode::ePROCESSING_INSTRUCTION)) {
285 nsCOMPtr<nsIDOMProcessingInstruction> pi = do_QueryInterface(child);
286 CheckXSLTParamPI(pi, mXSLTProcessor, mDocument);
288 else if (child->IsElement()) {
289 // Only honor PIs in the prolog
290 break;
294 nsCOMPtr<nsIDOMDocument> currentDOMDoc(do_QueryInterface(mDocument));
295 mXSLTProcessor->SetSourceContentModel(currentDOMDoc);
296 // Since the processor now holds a reference to us we drop our reference
297 // to it to avoid owning cycles
298 mXSLTProcessor = nullptr;
300 else {
301 // Kick off layout for non-XSLT transformed documents.
303 // Check if we want to prettyprint
304 MaybePrettyPrint();
306 bool startLayout = true;
308 if (mPrettyPrinting) {
309 NS_ASSERTION(!mPendingSheetCount, "Shouldn't have pending sheets here!");
311 // We're pretty-printing now. See whether we should wait up on
312 // stylesheet loads
313 if (mDocument->CSSLoader()->HasPendingLoads() &&
314 NS_SUCCEEDED(mDocument->CSSLoader()->AddObserver(this))) {
315 // wait for those sheets to load
316 startLayout = false;
320 if (startLayout) {
321 StartLayout(false);
323 ScrollToRef();
326 mDocument->RemoveObserver(this);
327 mIsDocumentObserver = false;
329 mDocument->EndLoad();
332 DropParserAndPerfHint();
334 return NS_OK;
337 NS_IMETHODIMP
338 nsXMLContentSink::OnDocumentCreated(nsIDocument* aResultDocument)
340 NS_ENSURE_ARG(aResultDocument);
342 nsCOMPtr<nsIHTMLDocument> htmlDoc = do_QueryInterface(aResultDocument);
343 if (htmlDoc) {
344 htmlDoc->SetDocWriteDisabled(true);
347 nsCOMPtr<nsIContentViewer> contentViewer;
348 mDocShell->GetContentViewer(getter_AddRefs(contentViewer));
349 if (contentViewer) {
350 return contentViewer->SetDocumentInternal(aResultDocument, true);
352 return NS_OK;
355 NS_IMETHODIMP
356 nsXMLContentSink::OnTransformDone(nsresult aResult,
357 nsIDocument* aResultDocument)
359 NS_ASSERTION(NS_FAILED(aResult) || aResultDocument,
360 "Don't notify about transform success without a document.");
362 nsCOMPtr<nsIDOMDocument> domDoc = do_QueryInterface(aResultDocument);
364 nsCOMPtr<nsIContentViewer> contentViewer;
365 mDocShell->GetContentViewer(getter_AddRefs(contentViewer));
367 if (NS_FAILED(aResult) && contentViewer) {
368 // Transform failed.
369 if (domDoc) {
370 aResultDocument->SetMayStartLayout(false);
371 // We have an error document.
372 contentViewer->SetDOMDocument(domDoc);
374 else {
375 // We don't have an error document, display the
376 // untransformed source document.
377 nsCOMPtr<nsIDOMDocument> document = do_QueryInterface(mDocument);
378 contentViewer->SetDOMDocument(document);
382 nsCOMPtr<nsIDocument> originalDocument = mDocument;
383 if (NS_SUCCEEDED(aResult) || aResultDocument) {
384 // Transform succeeded or it failed and we have an error
385 // document to display.
386 mDocument = aResultDocument;
387 nsCOMPtr<nsIHTMLDocument> htmlDoc = do_QueryInterface(mDocument);
388 if (htmlDoc) {
389 htmlDoc->SetDocWriteDisabled(false);
393 // Notify document observers that all the content has been stuck
394 // into the document.
395 // XXX do we need to notify for things like PIs? Or just the
396 // documentElement?
397 nsIContent *rootElement = mDocument->GetRootElement();
398 if (rootElement) {
399 NS_ASSERTION(mDocument->IndexOf(rootElement) != -1,
400 "rootElement not in doc?");
401 mDocument->BeginUpdate(UPDATE_CONTENT_MODEL);
402 nsNodeUtils::ContentInserted(mDocument, rootElement,
403 mDocument->IndexOf(rootElement));
404 mDocument->EndUpdate(UPDATE_CONTENT_MODEL);
407 // Start the layout process
408 StartLayout(false);
410 ScrollToRef();
412 originalDocument->EndLoad();
414 return NS_OK;
417 NS_IMETHODIMP
418 nsXMLContentSink::StyleSheetLoaded(CSSStyleSheet* aSheet,
419 bool aWasAlternate,
420 nsresult aStatus)
422 if (!mPrettyPrinting) {
423 return nsContentSink::StyleSheetLoaded(aSheet, aWasAlternate, aStatus);
426 if (!mDocument->CSSLoader()->HasPendingLoads()) {
427 mDocument->CSSLoader()->RemoveObserver(this);
428 StartLayout(false);
429 ScrollToRef();
432 return NS_OK;
435 NS_IMETHODIMP
436 nsXMLContentSink::WillInterrupt(void)
438 return WillInterruptImpl();
441 NS_IMETHODIMP
442 nsXMLContentSink::WillResume(void)
444 return WillResumeImpl();
447 NS_IMETHODIMP
448 nsXMLContentSink::SetParser(nsParserBase* aParser)
450 NS_PRECONDITION(aParser, "Should have a parser here!");
451 mParser = aParser;
452 return NS_OK;
455 nsresult
456 nsXMLContentSink::CreateElement(const char16_t** aAtts, uint32_t aAttsCount,
457 mozilla::dom::NodeInfo* aNodeInfo, uint32_t aLineNumber,
458 nsIContent** aResult, bool* aAppendContent,
459 FromParser aFromParser)
461 NS_ASSERTION(aNodeInfo, "can't create element without nodeinfo");
463 *aResult = nullptr;
464 *aAppendContent = true;
465 nsresult rv = NS_OK;
467 nsRefPtr<mozilla::dom::NodeInfo> ni = aNodeInfo;
468 nsRefPtr<Element> content;
469 rv = NS_NewElement(getter_AddRefs(content), ni.forget(), aFromParser);
470 NS_ENSURE_SUCCESS(rv, rv);
472 if (aNodeInfo->Equals(nsGkAtoms::script, kNameSpaceID_XHTML)
473 || aNodeInfo->Equals(nsGkAtoms::script, kNameSpaceID_SVG)
475 nsCOMPtr<nsIScriptElement> sele = do_QueryInterface(content);
476 sele->SetScriptLineNumber(aLineNumber);
477 sele->SetCreatorParser(GetParser());
478 mConstrainSize = false;
481 // XHTML needs some special attention
482 if (aNodeInfo->NamespaceEquals(kNameSpaceID_XHTML)) {
483 mPrettyPrintHasFactoredElements = true;
485 else {
486 // If we care, find out if we just used a special factory.
487 if (!mPrettyPrintHasFactoredElements && !mPrettyPrintHasSpecialRoot &&
488 mPrettyPrintXML) {
489 mPrettyPrintHasFactoredElements =
490 nsContentUtils::NameSpaceManager()->
491 HasElementCreator(aNodeInfo->NamespaceID());
494 if (!aNodeInfo->NamespaceEquals(kNameSpaceID_SVG)) {
495 content.forget(aResult);
497 return NS_OK;
501 if (aNodeInfo->Equals(nsGkAtoms::link, kNameSpaceID_XHTML) ||
502 aNodeInfo->Equals(nsGkAtoms::style, kNameSpaceID_XHTML) ||
503 aNodeInfo->Equals(nsGkAtoms::style, kNameSpaceID_SVG)) {
504 nsCOMPtr<nsIStyleSheetLinkingElement> ssle(do_QueryInterface(content));
505 if (ssle) {
506 ssle->InitStyleLinkElement(false);
507 if (aFromParser) {
508 ssle->SetEnableUpdates(false);
510 if (!aNodeInfo->Equals(nsGkAtoms::link, kNameSpaceID_XHTML)) {
511 ssle->SetLineNumber(aFromParser ? aLineNumber : 0);
516 content.forget(aResult);
518 return NS_OK;
522 nsresult
523 nsXMLContentSink::CloseElement(nsIContent* aContent)
525 NS_ASSERTION(aContent, "missing element to close");
527 mozilla::dom::NodeInfo *nodeInfo = aContent->NodeInfo();
529 // Some HTML nodes need DoneAddingChildren() called to initialize
530 // properly (eg form state restoration).
531 if ((nodeInfo->NamespaceID() == kNameSpaceID_XHTML &&
532 (nodeInfo->NameAtom() == nsGkAtoms::select ||
533 nodeInfo->NameAtom() == nsGkAtoms::textarea ||
534 nodeInfo->NameAtom() == nsGkAtoms::video ||
535 nodeInfo->NameAtom() == nsGkAtoms::audio ||
536 nodeInfo->NameAtom() == nsGkAtoms::object ||
537 nodeInfo->NameAtom() == nsGkAtoms::applet))
538 || nodeInfo->NameAtom() == nsGkAtoms::title
540 aContent->DoneAddingChildren(HaveNotifiedForCurrentContent());
543 if (IsMonolithicContainer(nodeInfo)) {
544 mInMonolithicContainer--;
547 if (!nodeInfo->NamespaceEquals(kNameSpaceID_XHTML) &&
548 !nodeInfo->NamespaceEquals(kNameSpaceID_SVG)) {
549 return NS_OK;
552 if (nodeInfo->Equals(nsGkAtoms::script, kNameSpaceID_XHTML)
553 || nodeInfo->Equals(nsGkAtoms::script, kNameSpaceID_SVG)
555 mConstrainSize = true;
556 nsCOMPtr<nsIScriptElement> sele = do_QueryInterface(aContent);
558 if (mPreventScriptExecution) {
559 sele->PreventExecution();
560 return NS_OK;
563 // Always check the clock in nsContentSink right after a script
564 StopDeflecting();
566 // Now tell the script that it's ready to go. This may execute the script
567 // or return true, or neither if the script doesn't need executing.
568 bool block = sele->AttemptToExecute();
570 // If the parser got blocked, make sure to return the appropriate rv.
571 // I'm not sure if this is actually needed or not.
572 if (mParser && !mParser->IsParserEnabled()) {
573 // XXX The HTML sink doesn't call BlockParser here, why do we?
574 GetParser()->BlockParser();
575 block = true;
578 return block ? NS_ERROR_HTMLPARSER_BLOCK : NS_OK;
581 nsresult rv = NS_OK;
582 if (nodeInfo->Equals(nsGkAtoms::meta, kNameSpaceID_XHTML) &&
583 // Need to check here to make sure this meta tag does not set
584 // mPrettyPrintXML to false when we have a special root!
585 (!mPrettyPrintXML || !mPrettyPrintHasSpecialRoot)) {
586 rv = ProcessMETATag(aContent);
588 else if (nodeInfo->Equals(nsGkAtoms::link, kNameSpaceID_XHTML) ||
589 nodeInfo->Equals(nsGkAtoms::style, kNameSpaceID_XHTML) ||
590 nodeInfo->Equals(nsGkAtoms::style, kNameSpaceID_SVG)) {
591 nsCOMPtr<nsIStyleSheetLinkingElement> ssle(do_QueryInterface(aContent));
592 if (ssle) {
593 ssle->SetEnableUpdates(true);
594 bool willNotify;
595 bool isAlternate;
596 rv = ssle->UpdateStyleSheet(mRunsToCompletion ? nullptr : this,
597 &willNotify,
598 &isAlternate);
599 if (NS_SUCCEEDED(rv) && willNotify && !isAlternate && !mRunsToCompletion) {
600 ++mPendingSheetCount;
601 mScriptLoader->AddExecuteBlocker();
604 // Look for <link rel="dns-prefetch" href="hostname">
605 // and look for <link rel="next" href="hostname"> like in HTML sink
606 if (nodeInfo->Equals(nsGkAtoms::link, kNameSpaceID_XHTML)) {
607 nsAutoString relVal;
608 aContent->GetAttr(kNameSpaceID_None, nsGkAtoms::rel, relVal);
609 if (!relVal.IsEmpty()) {
610 uint32_t linkTypes =
611 nsStyleLinkElement::ParseLinkTypes(relVal, aContent->NodePrincipal());
612 bool hasPrefetch = linkTypes & nsStyleLinkElement::ePREFETCH;
613 if (hasPrefetch || (linkTypes & nsStyleLinkElement::eNEXT)) {
614 nsAutoString hrefVal;
615 aContent->GetAttr(kNameSpaceID_None, nsGkAtoms::href, hrefVal);
616 if (!hrefVal.IsEmpty()) {
617 PrefetchHref(hrefVal, aContent, hasPrefetch);
620 if (linkTypes & nsStyleLinkElement::eDNS_PREFETCH) {
621 nsAutoString hrefVal;
622 aContent->GetAttr(kNameSpaceID_None, nsGkAtoms::href, hrefVal);
623 if (!hrefVal.IsEmpty()) {
624 PrefetchDNS(hrefVal);
631 return rv;
634 nsresult
635 nsXMLContentSink::AddContentAsLeaf(nsIContent *aContent)
637 nsresult result = NS_OK;
639 if ((eXMLContentSinkState_InProlog == mState) ||
640 (eXMLContentSinkState_InEpilog == mState)) {
641 NS_ASSERTION(mDocument, "Fragments have no prolog or epilog");
642 mDocument->AppendChildTo(aContent, false);
644 else {
645 nsCOMPtr<nsIContent> parent = GetCurrentContent();
647 if (parent) {
648 result = parent->AppendChildTo(aContent, false);
651 return result;
654 // Create an XML parser and an XSL content sink and start parsing
655 // the XSL stylesheet located at the given URI.
656 nsresult
657 nsXMLContentSink::LoadXSLStyleSheet(nsIURI* aUrl)
659 nsCOMPtr<nsIDocumentTransformer> processor =
660 do_CreateInstance("@mozilla.org/document-transformer;1?type=xslt");
661 if (!processor) {
662 // No XSLT processor available, continue normal document loading
663 return NS_OK;
666 processor->SetTransformObserver(this);
668 if (NS_SUCCEEDED(processor->LoadStyleSheet(aUrl, mDocument))) {
669 mXSLTProcessor.swap(processor);
672 // Intentionally ignore errors here, we should continue loading the
673 // XML document whether we're able to load the XSLT stylesheet or
674 // not.
676 return NS_OK;
679 nsresult
680 nsXMLContentSink::ProcessStyleLink(nsIContent* aElement,
681 const nsSubstring& aHref,
682 bool aAlternate,
683 const nsSubstring& aTitle,
684 const nsSubstring& aType,
685 const nsSubstring& aMedia)
687 nsresult rv = NS_OK;
688 mPrettyPrintXML = false;
690 nsAutoCString cmd;
691 if (mParser)
692 GetParser()->GetCommand(cmd);
693 if (cmd.EqualsASCII(kLoadAsData))
694 return NS_OK; // Do not load stylesheets when loading as data
696 NS_ConvertUTF16toUTF8 type(aType);
697 if (type.EqualsIgnoreCase(TEXT_XSL) ||
698 type.EqualsIgnoreCase(APPLICATION_XSLT_XML) ||
699 type.EqualsIgnoreCase(TEXT_XML) ||
700 type.EqualsIgnoreCase(APPLICATION_XML)) {
701 if (aAlternate) {
702 // don't load alternate XSLT
703 return NS_OK;
705 // LoadXSLStyleSheet needs a mDocShell.
706 if (!mDocShell)
707 return NS_OK;
709 nsCOMPtr<nsIURI> url;
710 rv = NS_NewURI(getter_AddRefs(url), aHref, nullptr,
711 mDocument->GetDocBaseURI());
712 NS_ENSURE_SUCCESS(rv, rv);
714 // Do security check
715 nsIScriptSecurityManager *secMan = nsContentUtils::GetSecurityManager();
716 rv = secMan->
717 CheckLoadURIWithPrincipal(mDocument->NodePrincipal(), url,
718 nsIScriptSecurityManager::ALLOW_CHROME);
719 NS_ENSURE_SUCCESS(rv, NS_OK);
721 // Do content policy check
722 int16_t decision = nsIContentPolicy::ACCEPT;
723 rv = NS_CheckContentLoadPolicy(nsIContentPolicy::TYPE_XSLT,
724 url,
725 mDocument->NodePrincipal(),
726 aElement,
727 type,
728 nullptr,
729 &decision,
730 nsContentUtils::GetContentPolicy(),
731 nsContentUtils::GetSecurityManager());
733 NS_ENSURE_SUCCESS(rv, rv);
735 if (NS_CP_REJECTED(decision)) {
736 return NS_OK;
739 return LoadXSLStyleSheet(url);
742 // Let nsContentSink deal with css.
743 rv = nsContentSink::ProcessStyleLink(aElement, aHref, aAlternate,
744 aTitle, aType, aMedia);
746 // nsContentSink::ProcessStyleLink handles the bookkeeping here wrt
747 // pending sheets.
749 return rv;
752 NS_IMETHODIMP
753 nsXMLContentSink::SetDocumentCharset(nsACString& aCharset)
755 if (mDocument) {
756 mDocument->SetDocumentCharacterSet(aCharset);
759 return NS_OK;
762 nsISupports *
763 nsXMLContentSink::GetTarget()
765 return mDocument;
768 bool
769 nsXMLContentSink::IsScriptExecuting()
771 return IsScriptExecutingImpl();
774 nsresult
775 nsXMLContentSink::FlushText(bool aReleaseTextNode)
777 nsresult rv = NS_OK;
779 if (mTextLength != 0) {
780 if (mLastTextNode) {
781 if ((mLastTextNodeSize + mTextLength) > mTextSize && !mXSLTProcessor) {
782 mLastTextNodeSize = 0;
783 mLastTextNode = nullptr;
784 FlushText(aReleaseTextNode);
785 } else {
786 bool notify = HaveNotifiedForCurrentContent();
787 // We could probably always increase mInNotification here since
788 // if AppendText doesn't notify it shouldn't trigger evil code.
789 // But just in case it does, we don't want to mask any notifications.
790 if (notify) {
791 ++mInNotification;
793 rv = mLastTextNode->AppendText(mText, mTextLength, notify);
794 if (notify) {
795 --mInNotification;
798 mLastTextNodeSize += mTextLength;
799 mTextLength = 0;
801 } else {
802 nsRefPtr<nsTextNode> textContent = new nsTextNode(mNodeInfoManager);
804 mLastTextNode = textContent;
806 // Set the text in the text node
807 textContent->SetText(mText, mTextLength, false);
808 mLastTextNodeSize += mTextLength;
809 mTextLength = 0;
811 // Add text to its parent
812 rv = AddContentAsLeaf(textContent);
816 if (aReleaseTextNode) {
817 mLastTextNodeSize = 0;
818 mLastTextNode = nullptr;
821 return rv;
824 nsIContent*
825 nsXMLContentSink::GetCurrentContent()
827 if (mContentStack.Length() == 0) {
828 return nullptr;
830 return GetCurrentStackNode()->mContent;
833 StackNode*
834 nsXMLContentSink::GetCurrentStackNode()
836 int32_t count = mContentStack.Length();
837 return count != 0 ? &mContentStack[count-1] : nullptr;
841 nsresult
842 nsXMLContentSink::PushContent(nsIContent *aContent)
844 NS_PRECONDITION(aContent, "Null content being pushed!");
845 StackNode *sn = mContentStack.AppendElement();
846 NS_ENSURE_TRUE(sn, NS_ERROR_OUT_OF_MEMORY);
848 nsIContent* contentToPush = aContent;
850 // When an XML parser would append a node to a template element, it
851 // must instead append it to the template element's template contents.
852 if (contentToPush->IsHTML(nsGkAtoms::_template)) {
853 HTMLTemplateElement* templateElement =
854 static_cast<HTMLTemplateElement*>(contentToPush);
855 contentToPush = templateElement->Content();
858 sn->mContent = contentToPush;
859 sn->mNumFlushed = 0;
860 return NS_OK;
863 void
864 nsXMLContentSink::PopContent()
866 int32_t count = mContentStack.Length();
868 if (count == 0) {
869 NS_WARNING("Popping empty stack");
870 return;
873 mContentStack.RemoveElementAt(count - 1);
876 bool
877 nsXMLContentSink::HaveNotifiedForCurrentContent() const
879 uint32_t stackLength = mContentStack.Length();
880 if (stackLength) {
881 const StackNode& stackNode = mContentStack[stackLength - 1];
882 nsIContent* parent = stackNode.mContent;
883 return stackNode.mNumFlushed == parent->GetChildCount();
885 return true;
888 void
889 nsXMLContentSink::MaybeStartLayout(bool aIgnorePendingSheets)
891 // XXXbz if aIgnorePendingSheets is true, what should we do when
892 // mXSLTProcessor or CanStillPrettyPrint()?
893 if (mLayoutStarted || mXSLTProcessor || CanStillPrettyPrint()) {
894 return;
896 StartLayout(aIgnorePendingSheets);
899 ////////////////////////////////////////////////////////////////////////
901 bool
902 nsXMLContentSink::SetDocElement(int32_t aNameSpaceID,
903 nsIAtom* aTagName,
904 nsIContent *aContent)
906 if (mDocElement)
907 return false;
909 // check for root elements that needs special handling for
910 // prettyprinting
911 if ((aNameSpaceID == kNameSpaceID_XBL &&
912 aTagName == nsGkAtoms::bindings) ||
913 (aNameSpaceID == kNameSpaceID_XSLT &&
914 (aTagName == nsGkAtoms::stylesheet ||
915 aTagName == nsGkAtoms::transform))) {
916 mPrettyPrintHasSpecialRoot = true;
917 if (mPrettyPrintXML) {
918 // In this case, disable script execution, stylesheet
919 // loading, and auto XLinks since we plan to prettyprint.
920 mDocument->ScriptLoader()->SetEnabled(false);
921 if (mCSSLoader) {
922 mCSSLoader->SetEnabled(false);
927 mDocElement = aContent;
928 nsresult rv = mDocument->AppendChildTo(mDocElement, NotifyForDocElement());
929 if (NS_FAILED(rv)) {
930 // If we return false here, the caller will bail out because it won't
931 // find a parent content node to append to, which is fine.
932 return false;
935 if (aTagName == nsGkAtoms::html &&
936 aNameSpaceID == kNameSpaceID_XHTML) {
937 ProcessOfflineManifest(aContent);
940 return true;
943 NS_IMETHODIMP
944 nsXMLContentSink::HandleStartElement(const char16_t *aName,
945 const char16_t **aAtts,
946 uint32_t aAttsCount,
947 uint32_t aLineNumber)
949 return HandleStartElement(aName, aAtts, aAttsCount, aLineNumber,
950 true);
953 nsresult
954 nsXMLContentSink::HandleStartElement(const char16_t *aName,
955 const char16_t **aAtts,
956 uint32_t aAttsCount,
957 uint32_t aLineNumber,
958 bool aInterruptable)
960 NS_PRECONDITION(aAttsCount % 2 == 0, "incorrect aAttsCount");
961 // Adjust aAttsCount so it's the actual number of attributes
962 aAttsCount /= 2;
964 nsresult result = NS_OK;
965 bool appendContent = true;
966 nsCOMPtr<nsIContent> content;
968 // XXX Hopefully the parser will flag this before we get
969 // here. If we're in the epilog, there should be no
970 // new elements
971 PR_ASSERT(eXMLContentSinkState_InEpilog != mState);
973 FlushText();
974 DidAddContent();
976 mState = eXMLContentSinkState_InDocumentElement;
978 int32_t nameSpaceID;
979 nsCOMPtr<nsIAtom> prefix, localName;
980 nsContentUtils::SplitExpatName(aName, getter_AddRefs(prefix),
981 getter_AddRefs(localName), &nameSpaceID);
983 if (!OnOpenContainer(aAtts, aAttsCount, nameSpaceID, localName, aLineNumber)) {
984 return NS_OK;
987 nsRefPtr<mozilla::dom::NodeInfo> nodeInfo;
988 nodeInfo = mNodeInfoManager->GetNodeInfo(localName, prefix, nameSpaceID,
989 nsIDOMNode::ELEMENT_NODE);
991 result = CreateElement(aAtts, aAttsCount, nodeInfo, aLineNumber,
992 getter_AddRefs(content), &appendContent,
993 FROM_PARSER_NETWORK);
994 NS_ENSURE_SUCCESS(result, result);
996 // Have to do this before we push the new content on the stack... and have to
997 // do that before we set attributes, call BindToTree, etc. Ideally we'd push
998 // on the stack inside CreateElement (which is effectively what the HTML sink
999 // does), but that's hard with all the subclass overrides going on.
1000 nsCOMPtr<nsIContent> parent = GetCurrentContent();
1002 result = PushContent(content);
1003 NS_ENSURE_SUCCESS(result, result);
1005 // Set the attributes on the new content element
1006 result = AddAttributes(aAtts, content);
1008 if (NS_OK == result) {
1009 // Store the element
1010 if (!SetDocElement(nameSpaceID, localName, content) && appendContent) {
1011 NS_ENSURE_TRUE(parent, NS_ERROR_UNEXPECTED);
1013 parent->AppendChildTo(content, false);
1017 // Some HTML nodes need DoneCreatingElement() called to initialize
1018 // properly (eg form state restoration).
1019 if (nodeInfo->NamespaceID() == kNameSpaceID_XHTML) {
1020 if (nodeInfo->NameAtom() == nsGkAtoms::input ||
1021 nodeInfo->NameAtom() == nsGkAtoms::button ||
1022 nodeInfo->NameAtom() == nsGkAtoms::menuitem ||
1023 nodeInfo->NameAtom() == nsGkAtoms::audio ||
1024 nodeInfo->NameAtom() == nsGkAtoms::video) {
1025 content->DoneCreatingElement();
1026 } else if (nodeInfo->NameAtom() == nsGkAtoms::head && !mCurrentHead) {
1027 mCurrentHead = content;
1031 if (IsMonolithicContainer(nodeInfo)) {
1032 mInMonolithicContainer++;
1035 if (content != mDocElement && !mCurrentHead) {
1036 // This isn't the root and we're not inside an XHTML <head>.
1037 // Might need to start layout
1038 MaybeStartLayout(false);
1041 if (content == mDocElement) {
1042 NotifyDocElementCreated(mDocument);
1045 return aInterruptable && NS_SUCCEEDED(result) ? DidProcessATokenImpl() :
1046 result;
1049 NS_IMETHODIMP
1050 nsXMLContentSink::HandleEndElement(const char16_t *aName)
1052 return HandleEndElement(aName, true);
1055 nsresult
1056 nsXMLContentSink::HandleEndElement(const char16_t *aName,
1057 bool aInterruptable)
1059 nsresult result = NS_OK;
1061 // XXX Hopefully the parser will flag this before we get
1062 // here. If we're in the prolog or epilog, there should be
1063 // no close tags for elements.
1064 PR_ASSERT(eXMLContentSinkState_InDocumentElement == mState);
1066 FlushText();
1068 StackNode* sn = GetCurrentStackNode();
1069 if (!sn) {
1070 return NS_ERROR_UNEXPECTED;
1073 nsCOMPtr<nsIContent> content;
1074 sn->mContent.swap(content);
1075 uint32_t numFlushed = sn->mNumFlushed;
1077 PopContent();
1078 NS_ASSERTION(content, "failed to pop content");
1079 #ifdef DEBUG
1080 // Check that we're closing the right thing
1081 nsCOMPtr<nsIAtom> debugNameSpacePrefix, debugTagAtom;
1082 int32_t debugNameSpaceID;
1083 nsContentUtils::SplitExpatName(aName, getter_AddRefs(debugNameSpacePrefix),
1084 getter_AddRefs(debugTagAtom),
1085 &debugNameSpaceID);
1086 // Check if we are closing a template element because template
1087 // elements do not get pushed on the stack, the template
1088 // element content is pushed instead.
1089 bool isTemplateElement = debugTagAtom == nsGkAtoms::_template &&
1090 debugNameSpaceID == kNameSpaceID_XHTML;
1091 NS_ASSERTION(content->NodeInfo()->Equals(debugTagAtom, debugNameSpaceID) ||
1092 isTemplateElement, "Wrong element being closed");
1093 #endif
1095 result = CloseElement(content);
1097 if (mCurrentHead == content) {
1098 mCurrentHead = nullptr;
1101 if (mDocElement == content) {
1102 // XXXbz for roots that don't want to be appended on open, we
1103 // probably need to deal here.... (and stop appending them on open).
1104 mState = eXMLContentSinkState_InEpilog;
1106 // We might have had no occasion to start layout yet. Do so now.
1107 MaybeStartLayout(false);
1110 int32_t stackLen = mContentStack.Length();
1111 if (mNotifyLevel >= stackLen) {
1112 if (numFlushed < content->GetChildCount()) {
1113 NotifyAppend(content, numFlushed);
1115 mNotifyLevel = stackLen - 1;
1117 DidAddContent();
1119 if (content->IsSVG(nsGkAtoms::svg)) {
1120 FlushTags();
1121 nsCOMPtr<nsIRunnable> event = new nsHtml5SVGLoadDispatcher(content);
1122 if (NS_FAILED(NS_DispatchToMainThread(event))) {
1123 NS_WARNING("failed to dispatch svg load dispatcher");
1127 return aInterruptable && NS_SUCCEEDED(result) ? DidProcessATokenImpl() :
1128 result;
1131 NS_IMETHODIMP
1132 nsXMLContentSink::HandleComment(const char16_t *aName)
1134 FlushText();
1136 nsRefPtr<Comment> comment = new Comment(mNodeInfoManager);
1137 comment->SetText(nsDependentString(aName), false);
1138 nsresult rv = AddContentAsLeaf(comment);
1139 DidAddContent();
1141 return NS_SUCCEEDED(rv) ? DidProcessATokenImpl() : rv;
1144 NS_IMETHODIMP
1145 nsXMLContentSink::HandleCDataSection(const char16_t *aData,
1146 uint32_t aLength)
1148 // XSLT doesn't differentiate between text and cdata and wants adjacent
1149 // textnodes merged, so add as text.
1150 if (mXSLTProcessor) {
1151 return AddText(aData, aLength);
1154 FlushText();
1156 nsRefPtr<CDATASection> cdata = new CDATASection(mNodeInfoManager);
1157 cdata->SetText(aData, aLength, false);
1158 nsresult rv = AddContentAsLeaf(cdata);
1159 DidAddContent();
1161 return NS_SUCCEEDED(rv) ? DidProcessATokenImpl() : rv;
1164 NS_IMETHODIMP
1165 nsXMLContentSink::HandleDoctypeDecl(const nsAString & aSubset,
1166 const nsAString & aName,
1167 const nsAString & aSystemId,
1168 const nsAString & aPublicId,
1169 nsISupports* aCatalogData)
1171 FlushText();
1173 nsresult rv = NS_OK;
1175 NS_ASSERTION(mDocument, "Shouldn't get here from a document fragment");
1177 nsCOMPtr<nsIAtom> name = do_GetAtom(aName);
1178 NS_ENSURE_TRUE(name, NS_ERROR_OUT_OF_MEMORY);
1180 // Create a new doctype node
1181 nsCOMPtr<nsIDOMDocumentType> docType;
1182 rv = NS_NewDOMDocumentType(getter_AddRefs(docType), mNodeInfoManager,
1183 name, aPublicId, aSystemId, aSubset);
1184 if (NS_FAILED(rv) || !docType) {
1185 return rv;
1188 MOZ_ASSERT(!aCatalogData, "Need to add back support for catalog style "
1189 "sheets");
1191 nsCOMPtr<nsIContent> content = do_QueryInterface(docType);
1192 NS_ASSERTION(content, "doctype isn't content?");
1194 rv = mDocument->AppendChildTo(content, false);
1195 DidAddContent();
1196 return NS_SUCCEEDED(rv) ? DidProcessATokenImpl() : rv;
1199 NS_IMETHODIMP
1200 nsXMLContentSink::HandleCharacterData(const char16_t *aData,
1201 uint32_t aLength)
1203 return HandleCharacterData(aData, aLength, true);
1206 nsresult
1207 nsXMLContentSink::HandleCharacterData(const char16_t *aData, uint32_t aLength,
1208 bool aInterruptable)
1210 nsresult rv = NS_OK;
1211 if (aData && mState != eXMLContentSinkState_InProlog &&
1212 mState != eXMLContentSinkState_InEpilog) {
1213 rv = AddText(aData, aLength);
1215 return aInterruptable && NS_SUCCEEDED(rv) ? DidProcessATokenImpl() : rv;
1218 NS_IMETHODIMP
1219 nsXMLContentSink::HandleProcessingInstruction(const char16_t *aTarget,
1220 const char16_t *aData)
1222 FlushText();
1224 const nsDependentString target(aTarget);
1225 const nsDependentString data(aData);
1227 nsCOMPtr<nsIContent> node =
1228 NS_NewXMLProcessingInstruction(mNodeInfoManager, target, data);
1230 nsCOMPtr<nsIStyleSheetLinkingElement> ssle(do_QueryInterface(node));
1231 if (ssle) {
1232 ssle->InitStyleLinkElement(false);
1233 ssle->SetEnableUpdates(false);
1234 mPrettyPrintXML = false;
1237 nsresult rv = AddContentAsLeaf(node);
1238 NS_ENSURE_SUCCESS(rv, rv);
1239 DidAddContent();
1241 if (ssle) {
1242 // This is an xml-stylesheet processing instruction... but it might not be
1243 // a CSS one if the type is set to something else.
1244 ssle->SetEnableUpdates(true);
1245 bool willNotify;
1246 bool isAlternate;
1247 rv = ssle->UpdateStyleSheet(mRunsToCompletion ? nullptr : this,
1248 &willNotify,
1249 &isAlternate);
1250 NS_ENSURE_SUCCESS(rv, rv);
1252 if (willNotify) {
1253 // Successfully started a stylesheet load
1254 if (!isAlternate && !mRunsToCompletion) {
1255 ++mPendingSheetCount;
1256 mScriptLoader->AddExecuteBlocker();
1259 return NS_OK;
1263 // If it's not a CSS stylesheet PI...
1264 nsAutoString type;
1265 nsContentUtils::GetPseudoAttributeValue(data, nsGkAtoms::type, type);
1267 if (mState != eXMLContentSinkState_InProlog ||
1268 !target.EqualsLiteral("xml-stylesheet") ||
1269 type.IsEmpty() ||
1270 type.LowerCaseEqualsLiteral("text/css")) {
1271 return DidProcessATokenImpl();
1274 nsAutoString href, title, media;
1275 bool isAlternate = false;
1277 // If there was no href, we can't do anything with this PI
1278 if (!ParsePIData(data, href, title, media, isAlternate)) {
1279 return DidProcessATokenImpl();
1282 rv = ProcessStyleLink(node, href, isAlternate, title, type, media);
1283 return NS_SUCCEEDED(rv) ? DidProcessATokenImpl() : rv;
1286 /* static */
1287 bool
1288 nsXMLContentSink::ParsePIData(const nsString &aData, nsString &aHref,
1289 nsString &aTitle, nsString &aMedia,
1290 bool &aIsAlternate)
1292 // If there was no href, we can't do anything with this PI
1293 if (!nsContentUtils::GetPseudoAttributeValue(aData, nsGkAtoms::href, aHref)) {
1294 return false;
1297 nsContentUtils::GetPseudoAttributeValue(aData, nsGkAtoms::title, aTitle);
1299 nsContentUtils::GetPseudoAttributeValue(aData, nsGkAtoms::media, aMedia);
1301 nsAutoString alternate;
1302 nsContentUtils::GetPseudoAttributeValue(aData,
1303 nsGkAtoms::alternate,
1304 alternate);
1306 aIsAlternate = alternate.EqualsLiteral("yes");
1308 return true;
1311 NS_IMETHODIMP
1312 nsXMLContentSink::HandleXMLDeclaration(const char16_t *aVersion,
1313 const char16_t *aEncoding,
1314 int32_t aStandalone)
1316 mDocument->SetXMLDeclaration(aVersion, aEncoding, aStandalone);
1318 return DidProcessATokenImpl();
1321 NS_IMETHODIMP
1322 nsXMLContentSink::ReportError(const char16_t* aErrorText,
1323 const char16_t* aSourceText,
1324 nsIScriptError *aError,
1325 bool *_retval)
1327 NS_PRECONDITION(aError && aSourceText && aErrorText, "Check arguments!!!");
1328 nsresult rv = NS_OK;
1330 // The expat driver should report the error. We're just cleaning up the mess.
1331 *_retval = true;
1333 mPrettyPrintXML = false;
1335 mState = eXMLContentSinkState_InProlog;
1337 // XXX need to stop scripts here -- hsivonen
1339 // stop observing in order to avoid crashing when removing content
1340 mDocument->RemoveObserver(this);
1341 mIsDocumentObserver = false;
1343 // Clear the current content and
1344 // prepare to set <parsererror> as the document root
1345 nsCOMPtr<nsIDOMNode> node(do_QueryInterface(mDocument));
1346 if (node) {
1347 for (;;) {
1348 nsCOMPtr<nsIDOMNode> child, dummy;
1349 node->GetLastChild(getter_AddRefs(child));
1350 if (!child)
1351 break;
1352 node->RemoveChild(child, getter_AddRefs(dummy));
1355 mDocElement = nullptr;
1357 // Clear any buffered-up text we have. It's enough to set the length to 0.
1358 // The buffer itself is allocated when we're created and deleted in our
1359 // destructor, so don't mess with it.
1360 mTextLength = 0;
1362 if (mXSLTProcessor) {
1363 // Get rid of the XSLT processor.
1364 mXSLTProcessor->CancelLoads();
1365 mXSLTProcessor = nullptr;
1368 // release the nodes on stack
1369 mContentStack.Clear();
1370 mNotifyLevel = 0;
1372 rv = HandleProcessingInstruction(MOZ_UTF16("xml-stylesheet"),
1373 MOZ_UTF16("href=\"chrome://global/locale/intl.css\" type=\"text/css\""));
1374 NS_ENSURE_SUCCESS(rv, rv);
1376 const char16_t* noAtts[] = { 0, 0 };
1378 NS_NAMED_LITERAL_STRING(errorNs,
1379 "http://www.mozilla.org/newlayout/xml/parsererror.xml");
1381 nsAutoString parsererror(errorNs);
1382 parsererror.Append((char16_t)0xFFFF);
1383 parsererror.AppendLiteral("parsererror");
1385 rv = HandleStartElement(parsererror.get(), noAtts, 0, (uint32_t)-1,
1386 false);
1387 NS_ENSURE_SUCCESS(rv, rv);
1389 rv = HandleCharacterData(aErrorText, NS_strlen(aErrorText), false);
1390 NS_ENSURE_SUCCESS(rv, rv);
1392 nsAutoString sourcetext(errorNs);
1393 sourcetext.Append((char16_t)0xFFFF);
1394 sourcetext.AppendLiteral("sourcetext");
1396 rv = HandleStartElement(sourcetext.get(), noAtts, 0, (uint32_t)-1,
1397 false);
1398 NS_ENSURE_SUCCESS(rv, rv);
1400 rv = HandleCharacterData(aSourceText, NS_strlen(aSourceText), false);
1401 NS_ENSURE_SUCCESS(rv, rv);
1403 rv = HandleEndElement(sourcetext.get(), false);
1404 NS_ENSURE_SUCCESS(rv, rv);
1406 rv = HandleEndElement(parsererror.get(), false);
1407 NS_ENSURE_SUCCESS(rv, rv);
1409 FlushTags();
1411 return NS_OK;
1414 nsresult
1415 nsXMLContentSink::AddAttributes(const char16_t** aAtts,
1416 nsIContent* aContent)
1418 // Add tag attributes to the content attributes
1419 nsCOMPtr<nsIAtom> prefix, localName;
1420 while (*aAtts) {
1421 int32_t nameSpaceID;
1422 nsContentUtils::SplitExpatName(aAtts[0], getter_AddRefs(prefix),
1423 getter_AddRefs(localName), &nameSpaceID);
1425 // Add attribute to content
1426 aContent->SetAttr(nameSpaceID, localName, prefix,
1427 nsDependentString(aAtts[1]), false);
1428 aAtts += 2;
1431 return NS_OK;
1434 #define NS_ACCUMULATION_BUFFER_SIZE 4096
1436 nsresult
1437 nsXMLContentSink::AddText(const char16_t* aText,
1438 int32_t aLength)
1440 // Create buffer when we first need it
1441 if (0 == mTextSize) {
1442 mText = (char16_t *) PR_MALLOC(sizeof(char16_t) * NS_ACCUMULATION_BUFFER_SIZE);
1443 if (nullptr == mText) {
1444 return NS_ERROR_OUT_OF_MEMORY;
1446 mTextSize = NS_ACCUMULATION_BUFFER_SIZE;
1449 // Copy data from string into our buffer; flush buffer when it fills up
1450 int32_t offset = 0;
1451 while (0 != aLength) {
1452 int32_t amount = mTextSize - mTextLength;
1453 if (0 == amount) {
1454 // XSLT wants adjacent textnodes merged.
1455 if (mConstrainSize && !mXSLTProcessor) {
1456 nsresult rv = FlushText();
1457 if (NS_OK != rv) {
1458 return rv;
1461 amount = mTextSize - mTextLength;
1463 else {
1464 mTextSize += aLength;
1465 mText = (char16_t *) PR_REALLOC(mText, sizeof(char16_t) * mTextSize);
1466 if (nullptr == mText) {
1467 mTextSize = 0;
1469 return NS_ERROR_OUT_OF_MEMORY;
1472 amount = aLength;
1475 if (amount > aLength) {
1476 amount = aLength;
1478 memcpy(&mText[mTextLength], &aText[offset], sizeof(char16_t) * amount);
1479 mTextLength += amount;
1480 offset += amount;
1481 aLength -= amount;
1484 return NS_OK;
1487 void
1488 nsXMLContentSink::FlushPendingNotifications(mozFlushType aType)
1490 // Only flush tags if we're not doing the notification ourselves
1491 // (since we aren't reentrant)
1492 if (!mInNotification) {
1493 if (mIsDocumentObserver) {
1494 // Only flush if we're still a document observer (so that our child
1495 // counts should be correct).
1496 if (aType >= Flush_ContentAndNotify) {
1497 FlushTags();
1499 else {
1500 FlushText(false);
1503 if (aType >= Flush_InterruptibleLayout) {
1504 // Make sure that layout has started so that the reflow flush
1505 // will actually happen.
1506 MaybeStartLayout(true);
1512 * NOTE!! Forked from SinkContext. Please keep in sync.
1514 * Flush all elements that have been seen so far such that
1515 * they are visible in the tree. Specifically, make sure
1516 * that they are all added to their respective parents.
1517 * Also, do notification at the top for all content that
1518 * has been newly added so that the frame tree is complete.
1520 nsresult
1521 nsXMLContentSink::FlushTags()
1523 mDeferredFlushTags = false;
1524 bool oldBeganUpdate = mBeganUpdate;
1525 uint32_t oldUpdates = mUpdatesInNotification;
1527 mUpdatesInNotification = 0;
1528 ++mInNotification;
1530 // Scope so we call EndUpdate before we decrease mInNotification
1531 mozAutoDocUpdate updateBatch(mDocument, UPDATE_CONTENT_MODEL, true);
1532 mBeganUpdate = true;
1534 // Don't release last text node in case we need to add to it again
1535 FlushText(false);
1537 // Start from the base of the stack (growing downward) and do
1538 // a notification from the node that is closest to the root of
1539 // tree for any content that has been added.
1541 int32_t stackPos;
1542 int32_t stackLen = mContentStack.Length();
1543 bool flushed = false;
1544 uint32_t childCount;
1545 nsIContent* content;
1547 for (stackPos = 0; stackPos < stackLen; ++stackPos) {
1548 content = mContentStack[stackPos].mContent;
1549 childCount = content->GetChildCount();
1551 if (!flushed && (mContentStack[stackPos].mNumFlushed < childCount)) {
1552 NotifyAppend(content, mContentStack[stackPos].mNumFlushed);
1553 flushed = true;
1556 mContentStack[stackPos].mNumFlushed = childCount;
1558 mNotifyLevel = stackLen - 1;
1560 --mInNotification;
1562 if (mUpdatesInNotification > 1) {
1563 UpdateChildCounts();
1566 mUpdatesInNotification = oldUpdates;
1567 mBeganUpdate = oldBeganUpdate;
1569 return NS_OK;
1573 * NOTE!! Forked from SinkContext. Please keep in sync.
1575 void
1576 nsXMLContentSink::UpdateChildCounts()
1578 // Start from the top of the stack (growing upwards) and see if any
1579 // new content has been appended. If so, we recognize that reflows
1580 // have been generated for it and we should make sure that no
1581 // further reflows occur. Note that we have to include stackPos == 0
1582 // to properly notify on kids of <html>.
1583 int32_t stackLen = mContentStack.Length();
1584 int32_t stackPos = stackLen - 1;
1585 while (stackPos >= 0) {
1586 StackNode & node = mContentStack[stackPos];
1587 node.mNumFlushed = node.mContent->GetChildCount();
1589 stackPos--;
1591 mNotifyLevel = stackLen - 1;
1594 bool
1595 nsXMLContentSink::IsMonolithicContainer(mozilla::dom::NodeInfo* aNodeInfo)
1597 return ((aNodeInfo->NamespaceID() == kNameSpaceID_XHTML &&
1598 (aNodeInfo->NameAtom() == nsGkAtoms::tr ||
1599 aNodeInfo->NameAtom() == nsGkAtoms::select ||
1600 aNodeInfo->NameAtom() == nsGkAtoms::object ||
1601 aNodeInfo->NameAtom() == nsGkAtoms::applet)) ||
1602 (aNodeInfo->NamespaceID() == kNameSpaceID_MathML &&
1603 (aNodeInfo->NameAtom() == nsGkAtoms::math))
1607 void
1608 nsXMLContentSink::ContinueInterruptedParsingIfEnabled()
1610 if (mParser && mParser->IsParserEnabled()) {
1611 GetParser()->ContinueInterruptedParsing();
1615 void
1616 nsXMLContentSink::ContinueInterruptedParsingAsync()
1618 nsCOMPtr<nsIRunnable> ev = NS_NewRunnableMethod(this,
1619 &nsXMLContentSink::ContinueInterruptedParsingIfEnabled);
1621 NS_DispatchToCurrentThread(ev);
1624 nsIParser*
1625 nsXMLContentSink::GetParser()
1627 return static_cast<nsIParser*>(mParser.get());