1 /* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
2 /* vim: set ts=8 sts=2 et sw=2 tw=80: */
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/. */
8 #include "nsXMLContentSink.h"
10 #include "mozilla/dom/Document.h"
11 #include "nsIContent.h"
13 #include "nsNetUtil.h"
14 #include "nsHTMLParts.h"
16 #include "mozilla/StyleSheetInlines.h"
17 #include "mozilla/css/Loader.h"
18 #include "nsGkAtoms.h"
19 #include "nsContentUtils.h"
20 #include "nsDocElementCreatedNotificationRunner.h"
21 #include "nsIDocShell.h"
22 #include "nsIScriptContext.h"
23 #include "nsNameSpaceManager.h"
24 #include "nsIScriptSecurityManager.h"
25 #include "nsIContentViewer.h"
27 #include "mozilla/Logging.h"
29 #include "nsIScriptElement.h"
30 #include "nsReadableUtils.h"
31 #include "nsUnicharUtils.h"
32 #include "nsIChannel.h"
33 #include "nsXMLPrettyPrinter.h"
34 #include "nsNodeInfoManager.h"
35 #include "nsContentCreatorFunctions.h"
36 #include "nsIContentPolicy.h"
37 #include "nsContentPolicyUtils.h"
39 #include "nsIScriptGlobalObject.h"
40 #include "mozAutoDocUpdate.h"
41 #include "nsMimeTypes.h"
42 #include "nsHtml5SVGLoadDispatcher.h"
43 #include "nsTextNode.h"
44 #include "mozilla/dom/CDATASection.h"
45 #include "mozilla/dom/Comment.h"
46 #include "mozilla/dom/DocumentType.h"
47 #include "mozilla/dom/Element.h"
48 #include "mozilla/dom/HTMLTemplateElement.h"
49 #include "mozilla/dom/MutationObservers.h"
50 #include "mozilla/dom/ProcessingInstruction.h"
51 #include "mozilla/dom/ScriptLoader.h"
52 #include "mozilla/dom/txMozillaXSLTProcessor.h"
53 #include "mozilla/CycleCollectedJSContext.h"
54 #include "mozilla/LoadInfo.h"
55 #include "mozilla/UseCounter.h"
57 using namespace mozilla
;
58 using namespace mozilla::dom
;
61 // 1) what's not allowed - We need to figure out which HTML tags
62 // (prefixed with a HTML namespace qualifier) are explicitly not
64 // 2) factoring code with nsHTMLContentSink - There's some amount of
65 // common code between this and the HTML content sink. This will
66 // increase as we support more and more HTML elements. How can code
67 // from the code be factored?
69 nsresult
NS_NewXMLContentSink(nsIXMLContentSink
** aResult
, Document
* aDoc
,
70 nsIURI
* aURI
, nsISupports
* aContainer
,
71 nsIChannel
* aChannel
) {
72 MOZ_ASSERT(nullptr != aResult
, "null ptr");
73 if (nullptr == aResult
) {
74 return NS_ERROR_NULL_POINTER
;
76 RefPtr
<nsXMLContentSink
> it
= new nsXMLContentSink();
78 nsresult rv
= it
->Init(aDoc
, aURI
, aContainer
, aChannel
);
79 NS_ENSURE_SUCCESS(rv
, rv
);
85 nsXMLContentSink::nsXMLContentSink()
86 : mState(eXMLContentSinkState_InProlog
),
89 mPrettyPrintXML(true),
90 mPrettyPrintHasSpecialRoot(0),
91 mPrettyPrintHasFactoredElements(0),
93 mPreventScriptExecution(0) {
97 nsXMLContentSink::~nsXMLContentSink() = default;
99 nsresult
nsXMLContentSink::Init(Document
* aDoc
, nsIURI
* aURI
,
100 nsISupports
* aContainer
, nsIChannel
* aChannel
) {
101 nsresult rv
= nsContentSink::Init(aDoc
, aURI
, aContainer
, aChannel
);
102 NS_ENSURE_SUCCESS(rv
, rv
);
104 aDoc
->AddObserver(this);
105 mIsDocumentObserver
= true;
108 mPrettyPrintXML
= false;
111 mState
= eXMLContentSinkState_InProlog
;
112 mDocElement
= nullptr;
117 inline void ImplCycleCollectionTraverse(
118 nsCycleCollectionTraversalCallback
& aCallback
,
119 nsXMLContentSink::StackNode
& aField
, const char* aName
,
120 uint32_t aFlags
= 0) {
121 ImplCycleCollectionTraverse(aCallback
, aField
.mContent
, aName
, aFlags
);
124 inline void ImplCycleCollectionUnlink(nsXMLContentSink::StackNode
& aField
) {
125 ImplCycleCollectionUnlink(aField
.mContent
);
128 NS_INTERFACE_MAP_BEGIN_CYCLE_COLLECTION(nsXMLContentSink
)
129 NS_INTERFACE_MAP_ENTRY(nsIContentSink
)
130 NS_INTERFACE_MAP_ENTRY(nsIXMLContentSink
)
131 NS_INTERFACE_MAP_ENTRY(nsIExpatSink
)
132 NS_INTERFACE_MAP_ENTRY(nsITransformObserver
)
133 NS_INTERFACE_MAP_END_INHERITING(nsContentSink
)
135 NS_IMPL_ADDREF_INHERITED(nsXMLContentSink
, nsContentSink
)
136 NS_IMPL_RELEASE_INHERITED(nsXMLContentSink
, nsContentSink
)
138 NS_IMPL_CYCLE_COLLECTION_INHERITED(nsXMLContentSink
, nsContentSink
,
139 mCurrentHead
, mDocElement
, mLastTextNode
,
140 mContentStack
, mDocumentChildren
)
144 nsXMLContentSink::WillParse(void) { return WillParseImpl(); }
147 nsXMLContentSink::WillBuildModel(nsDTDMode aDTDMode
) {
148 WillBuildModelImpl();
150 // Notify document that the load is beginning
151 mDocument
->BeginLoad();
153 // Check for correct load-command for maybe prettyprinting
154 if (mPrettyPrintXML
) {
155 nsAutoCString command
;
156 GetParser()->GetCommand(command
);
157 if (!command
.EqualsLiteral("view")) {
158 mPrettyPrintXML
= false;
165 bool nsXMLContentSink::CanStillPrettyPrint() {
166 return mPrettyPrintXML
&&
167 (!mPrettyPrintHasFactoredElements
|| mPrettyPrintHasSpecialRoot
);
170 nsresult
nsXMLContentSink::MaybePrettyPrint() {
171 if (!CanStillPrettyPrint()) {
172 mPrettyPrintXML
= false;
178 // Try to perform a microtask checkpoint; this avoids always breaking
179 // pretty-printing if webextensions insert new content right after the
184 // stop observing in order to avoid crashing when replacing content
185 mDocument
->RemoveObserver(this);
186 mIsDocumentObserver
= false;
188 // Reenable the CSSLoader so that the prettyprinting stylesheets can load
190 mCSSLoader
->SetEnabled(true);
193 RefPtr
<nsXMLPrettyPrinter
> printer
;
194 nsresult rv
= NS_NewXMLPrettyPrinter(getter_AddRefs(printer
));
195 NS_ENSURE_SUCCESS(rv
, rv
);
197 bool isPrettyPrinting
;
198 rv
= printer
->PrettyPrint(mDocument
, &isPrettyPrinting
);
199 NS_ENSURE_SUCCESS(rv
, rv
);
201 mPrettyPrinting
= isPrettyPrinting
;
205 static void CheckXSLTParamPI(ProcessingInstruction
* aPi
,
206 nsIDocumentTransformer
* aProcessor
,
208 nsAutoString target
, data
;
209 aPi
->GetTarget(target
);
211 // Check for namespace declarations
212 if (target
.EqualsLiteral("xslt-param-namespace")) {
214 nsAutoString prefix
, namespaceAttr
;
215 nsContentUtils::GetPseudoAttributeValue(data
, nsGkAtoms::prefix
, prefix
);
216 if (!prefix
.IsEmpty() && nsContentUtils::GetPseudoAttributeValue(
217 data
, nsGkAtoms::_namespace
, namespaceAttr
)) {
218 aProcessor
->AddXSLTParamNamespace(prefix
, namespaceAttr
);
222 // Check for actual parameters
223 else if (target
.EqualsLiteral("xslt-param")) {
225 nsAutoString name
, namespaceAttr
, select
, value
;
226 nsContentUtils::GetPseudoAttributeValue(data
, nsGkAtoms::name
, name
);
227 nsContentUtils::GetPseudoAttributeValue(data
, nsGkAtoms::_namespace
,
229 if (!nsContentUtils::GetPseudoAttributeValue(data
, nsGkAtoms::select
,
231 select
.SetIsVoid(true);
233 if (!nsContentUtils::GetPseudoAttributeValue(data
, nsGkAtoms::value
,
235 value
.SetIsVoid(true);
237 if (!name
.IsEmpty()) {
238 aProcessor
->AddXSLTParam(name
, namespaceAttr
, select
, value
, aSource
);
244 nsXMLContentSink::DidBuildModel(bool aTerminated
) {
246 // If mParser is null, this parse has already been terminated and must
247 // not been terminated again. However, Document may still think that
248 // the parse has not been terminated and call back into here in the case
249 // where the XML parser has finished but the XSLT transform associated
250 // with the document has not.
256 DidBuildModelImpl(aTerminated
);
258 if (mXSLTProcessor
) {
259 // stop observing in order to avoid crashing when replacing content
260 mDocument
->RemoveObserver(this);
261 mIsDocumentObserver
= false;
264 RefPtr
<DocumentFragment
> source
= mDocument
->CreateDocumentFragment();
265 for (nsIContent
* child
: mDocumentChildren
) {
266 // XPath data model doesn't have DocumentType nodes.
267 if (child
->NodeType() != nsINode::DOCUMENT_TYPE_NODE
) {
268 source
->AppendChild(*child
, rv
);
270 return rv
.StealNSResult();
275 // Check for xslt-param and xslt-param-namespace PIs
276 for (nsIContent
* child
: mDocumentChildren
) {
277 if (auto pi
= ProcessingInstruction::FromNode(child
)) {
278 CheckXSLTParamPI(pi
, mXSLTProcessor
, source
);
279 } else if (child
->IsElement()) {
280 // Only honor PIs in the prolog
285 mXSLTProcessor
->SetSourceContentModel(source
);
286 // Since the processor now holds a reference to us we drop our reference
287 // to it to avoid owning cycles
288 mXSLTProcessor
= nullptr;
290 // Kick off layout for non-XSLT transformed documents.
292 // Check if we want to prettyprint
295 bool startLayout
= true;
297 if (mPrettyPrinting
) {
298 NS_ASSERTION(!mPendingSheetCount
, "Shouldn't have pending sheets here!");
300 // We're pretty-printing now. See whether we should wait up on
302 if (mDocument
->CSSLoader()->HasPendingLoads()) {
303 mDocument
->CSSLoader()->AddObserver(this);
304 // wait for those sheets to load
315 mDocument
->RemoveObserver(this);
316 mIsDocumentObserver
= false;
318 mDocument
->EndLoad();
320 DropParserAndPerfHint();
326 nsresult
nsXMLContentSink::OnDocumentCreated(Document
* aSourceDocument
,
327 Document
* aResultDocument
) {
328 aResultDocument
->SetDocWriteDisabled(true);
330 nsCOMPtr
<nsIContentViewer
> contentViewer
;
331 mDocShell
->GetContentViewer(getter_AddRefs(contentViewer
));
332 // Make sure that we haven't loaded a new document into the contentviewer
333 // after starting the XSLT transform.
334 if (contentViewer
&& contentViewer
->GetDocument() == aSourceDocument
) {
335 return contentViewer
->SetDocumentInternal(aResultDocument
, true);
340 nsresult
nsXMLContentSink::OnTransformDone(Document
* aSourceDocument
,
342 Document
* aResultDocument
) {
343 MOZ_ASSERT(aResultDocument
,
344 "Don't notify about transform end without a document.");
346 mDocumentChildren
.Clear();
348 nsCOMPtr
<nsIContentViewer
> contentViewer
;
349 mDocShell
->GetContentViewer(getter_AddRefs(contentViewer
));
351 RefPtr
<Document
> originalDocument
= mDocument
;
352 bool blockingOnload
= mIsBlockingOnload
;
354 // Make sure that we haven't loaded a new document into the contentviewer
355 // after starting the XSLT transform.
356 if (contentViewer
&& (contentViewer
->GetDocument() == aSourceDocument
||
357 contentViewer
->GetDocument() == aResultDocument
)) {
358 if (NS_FAILED(aResult
)) {
360 aResultDocument
->SetMayStartLayout(false);
361 // We have an error document.
362 contentViewer
->SetDocument(aResultDocument
);
365 if (!mRunsToCompletion
) {
366 // This BlockOnload call corresponds to the UnblockOnload call in
367 // nsContentSink::DropParserAndPerfHint.
368 aResultDocument
->BlockOnload();
369 mIsBlockingOnload
= true;
371 // Transform succeeded, or it failed and we have an error document to
373 mDocument
= aResultDocument
;
374 aResultDocument
->SetDocWriteDisabled(false);
376 // Notify document observers that all the content has been stuck
377 // into the document.
378 // XXX do we need to notify for things like PIs? Or just the
380 nsIContent
* rootElement
= mDocument
->GetRootElement();
382 NS_ASSERTION(mDocument
->ComputeIndexOf(rootElement
).isSome(),
383 "rootElement not in doc?");
384 mDocument
->BeginUpdate();
385 MutationObservers::NotifyContentInserted(mDocument
, rootElement
);
386 mDocument
->EndUpdate();
389 // Start the layout process
395 originalDocument
->EndLoad();
396 if (blockingOnload
) {
397 // This UnblockOnload call corresponds to the BlockOnload call in
398 // nsContentSink::WillBuildModelImpl.
399 originalDocument
->UnblockOnload(true);
402 DropParserAndPerfHint();
404 // By this point, the result document has been set in the content viewer. But
405 // the content viewer does not call Destroy on the original document, so we
406 // won't end up reporting document use counters. It's possible we should be
407 // detaching the document from the window, but for now, we call
408 // ReportDocumentUseCounters on the original document here, to avoid
409 // assertions in ~Document about not having reported them.
410 originalDocument
->ReportDocumentUseCounters();
416 nsXMLContentSink::StyleSheetLoaded(StyleSheet
* aSheet
, bool aWasDeferred
,
418 if (!mPrettyPrinting
) {
419 return nsContentSink::StyleSheetLoaded(aSheet
, aWasDeferred
, aStatus
);
422 if (!mDocument
->CSSLoader()->HasPendingLoads()) {
423 mDocument
->CSSLoader()->RemoveObserver(this);
432 nsXMLContentSink::WillInterrupt(void) { return WillInterruptImpl(); }
434 void nsXMLContentSink::WillResume() { WillResumeImpl(); }
437 nsXMLContentSink::SetParser(nsParserBase
* aParser
) {
438 MOZ_ASSERT(aParser
, "Should have a parser here!");
443 static bool FindIsAttrValue(const char16_t
** aAtts
, const char16_t
** aResult
) {
444 RefPtr
<nsAtom
> prefix
, localName
;
445 for (; *aAtts
; aAtts
+= 2) {
447 nsContentUtils::SplitExpatName(aAtts
[0], getter_AddRefs(prefix
),
448 getter_AddRefs(localName
), &nameSpaceID
);
449 if (nameSpaceID
== kNameSpaceID_None
&& localName
== nsGkAtoms::is
) {
459 nsresult
nsXMLContentSink::CreateElement(
460 const char16_t
** aAtts
, uint32_t aAttsCount
,
461 mozilla::dom::NodeInfo
* aNodeInfo
, uint32_t aLineNumber
,
462 uint32_t aColumnNumber
, nsIContent
** aResult
, bool* aAppendContent
,
463 FromParser aFromParser
) {
464 NS_ASSERTION(aNodeInfo
, "can't create element without nodeinfo");
467 *aAppendContent
= true;
470 RefPtr
<mozilla::dom::NodeInfo
> ni
= aNodeInfo
;
471 RefPtr
<Element
> element
;
473 const char16_t
* is
= nullptr;
474 if ((aNodeInfo
->NamespaceEquals(kNameSpaceID_XHTML
) ||
475 aNodeInfo
->NamespaceEquals(kNameSpaceID_XUL
)) &&
476 FindIsAttrValue(aAtts
, &is
)) {
477 const nsDependentString
isStr(is
);
478 rv
= NS_NewElement(getter_AddRefs(element
), ni
.forget(), aFromParser
,
481 rv
= NS_NewElement(getter_AddRefs(element
), ni
.forget(), aFromParser
);
484 NS_ENSURE_SUCCESS(rv
, rv
);
486 if (aNodeInfo
->Equals(nsGkAtoms::script
, kNameSpaceID_XHTML
) ||
487 aNodeInfo
->Equals(nsGkAtoms::script
, kNameSpaceID_SVG
)) {
488 if (nsCOMPtr
<nsIScriptElement
> sele
= do_QueryInterface(element
)) {
489 sele
->SetScriptLineNumber(aLineNumber
);
490 sele
->SetScriptColumnNumber(aColumnNumber
);
491 sele
->SetCreatorParser(GetParser());
493 MOZ_ASSERT(nsNameSpaceManager::GetInstance()->mSVGDisabled
,
494 "Node didn't QI to script, but SVG wasn't disabled.");
498 // XHTML needs some special attention
499 if (aNodeInfo
->NamespaceEquals(kNameSpaceID_XHTML
)) {
500 mPrettyPrintHasFactoredElements
= true;
502 // If we care, find out if we just used a special factory.
503 if (!mPrettyPrintHasFactoredElements
&& !mPrettyPrintHasSpecialRoot
&&
505 mPrettyPrintHasFactoredElements
=
506 nsNameSpaceManager::GetInstance()->HasElementCreator(
507 aNodeInfo
->NamespaceID());
510 if (!aNodeInfo
->NamespaceEquals(kNameSpaceID_SVG
)) {
511 element
.forget(aResult
);
516 if (auto* linkStyle
= LinkStyle::FromNode(*element
)) {
518 linkStyle
->DisableUpdates();
520 if (!aNodeInfo
->Equals(nsGkAtoms::link
, kNameSpaceID_XHTML
)) {
521 linkStyle
->SetLineNumber(aFromParser
? aLineNumber
: 0);
522 linkStyle
->SetColumnNumber(aFromParser
? aColumnNumber
: 0);
526 element
.forget(aResult
);
530 nsresult
nsXMLContentSink::CloseElement(nsIContent
* aContent
) {
531 NS_ASSERTION(aContent
, "missing element to close");
533 mozilla::dom::NodeInfo
* nodeInfo
= aContent
->NodeInfo();
535 // Some HTML nodes need DoneAddingChildren() called to initialize
536 // properly (eg form state restoration).
537 if (nsIContent::RequiresDoneAddingChildren(nodeInfo
->NamespaceID(),
538 nodeInfo
->NameAtom())) {
539 aContent
->DoneAddingChildren(HaveNotifiedForCurrentContent());
542 if (IsMonolithicContainer(nodeInfo
)) {
543 mInMonolithicContainer
--;
546 if (!nodeInfo
->NamespaceEquals(kNameSpaceID_XHTML
) &&
547 !nodeInfo
->NamespaceEquals(kNameSpaceID_SVG
)) {
551 if (nodeInfo
->Equals(nsGkAtoms::script
, kNameSpaceID_XHTML
) ||
552 nodeInfo
->Equals(nsGkAtoms::script
, kNameSpaceID_SVG
)) {
553 nsCOMPtr
<nsIScriptElement
> sele
= do_QueryInterface(aContent
);
555 MOZ_ASSERT(nsNameSpaceManager::GetInstance()->mSVGDisabled
,
556 "Node didn't QI to script, but SVG wasn't disabled.");
560 if (mPreventScriptExecution
) {
561 sele
->PreventExecution();
565 // Always check the clock in nsContentSink right after a script
568 // Now tell the script that it's ready to go. This may execute the script
569 // or return true, or neither if the script doesn't need executing.
570 bool block
= sele
->AttemptToExecute();
573 GetParser()->BlockParser();
576 // If the parser got blocked, make sure to return the appropriate rv.
577 // I'm not sure if this is actually needed or not.
578 if (!mParser
->IsParserEnabled()) {
583 return block
? NS_ERROR_HTMLPARSER_BLOCK
: NS_OK
;
587 if (auto* linkStyle
= LinkStyle::FromNode(*aContent
)) {
588 auto updateOrError
= linkStyle
->EnableUpdatesAndUpdateStyleSheet(
589 mRunsToCompletion
? nullptr : this);
590 if (updateOrError
.isErr()) {
591 rv
= updateOrError
.unwrapErr();
592 } else if (updateOrError
.unwrap().ShouldBlock() && !mRunsToCompletion
) {
593 ++mPendingSheetCount
;
594 mScriptLoader
->AddParserBlockingScriptExecutionBlocker();
601 nsresult
nsXMLContentSink::AddContentAsLeaf(nsIContent
* aContent
) {
602 nsresult result
= NS_OK
;
604 if (mState
== eXMLContentSinkState_InProlog
) {
605 NS_ASSERTION(mDocument
, "Fragments have no prolog");
606 mDocumentChildren
.AppendElement(aContent
);
607 } else if (mState
== eXMLContentSinkState_InEpilog
) {
608 NS_ASSERTION(mDocument
, "Fragments have no epilog");
609 if (mXSLTProcessor
) {
610 mDocumentChildren
.AppendElement(aContent
);
612 mDocument
->AppendChildTo(aContent
, false, IgnoreErrors());
615 nsCOMPtr
<nsIContent
> parent
= GetCurrentContent();
619 parent
->AppendChildTo(aContent
, false, rv
);
620 result
= rv
.StealNSResult();
626 // Create an XML parser and an XSL content sink and start parsing
627 // the XSL stylesheet located at the given URI.
628 nsresult
nsXMLContentSink::LoadXSLStyleSheet(nsIURI
* aUrl
) {
629 nsCOMPtr
<nsIDocumentTransformer
> processor
= new txMozillaXSLTProcessor();
630 mDocument
->SetUseCounter(eUseCounter_custom_XSLStylesheet
);
632 processor
->SetTransformObserver(this);
634 if (NS_SUCCEEDED(processor
->LoadStyleSheet(aUrl
, mDocument
))) {
635 mXSLTProcessor
.swap(processor
);
638 // Intentionally ignore errors here, we should continue loading the
639 // XML document whether we're able to load the XSLT stylesheet or
645 nsresult
nsXMLContentSink::ProcessStyleLinkFromHeader(
646 const nsAString
& aHref
, bool aAlternate
, const nsAString
& aTitle
,
647 const nsAString
& aIntegrity
, const nsAString
& aType
,
648 const nsAString
& aMedia
, const nsAString
& aReferrerPolicy
) {
649 mPrettyPrintXML
= false;
652 if (mParser
) GetParser()->GetCommand(cmd
);
653 if (cmd
.EqualsASCII(kLoadAsData
))
654 return NS_OK
; // Do not load stylesheets when loading as data
657 nsresult rv
= MaybeProcessXSLTLink(nullptr, aHref
, aAlternate
, aType
, aType
,
658 aMedia
, aReferrerPolicy
, &wasXSLT
);
659 NS_ENSURE_SUCCESS(rv
, rv
);
665 // Otherwise fall through to nsContentSink to handle CSS Link headers.
666 return nsContentSink::ProcessStyleLinkFromHeader(
667 aHref
, aAlternate
, aTitle
, aIntegrity
, aType
, aMedia
, aReferrerPolicy
);
670 nsresult
nsXMLContentSink::MaybeProcessXSLTLink(
671 ProcessingInstruction
* aProcessingInstruction
, const nsAString
& aHref
,
672 bool aAlternate
, const nsAString
& aTitle
, const nsAString
& aType
,
673 const nsAString
& aMedia
, const nsAString
& aReferrerPolicy
, bool* aWasXSLT
) {
674 bool wasXSLT
= aType
.LowerCaseEqualsLiteral(TEXT_XSL
) ||
675 aType
.LowerCaseEqualsLiteral(APPLICATION_XSLT_XML
) ||
676 aType
.LowerCaseEqualsLiteral(TEXT_XML
) ||
677 aType
.LowerCaseEqualsLiteral(APPLICATION_XML
);
688 // don't load alternate XSLT
691 // LoadXSLStyleSheet needs a mDocShell.
696 nsCOMPtr
<nsIURI
> url
;
697 nsresult rv
= NS_NewURI(getter_AddRefs(url
), aHref
, nullptr,
698 mDocument
->GetDocBaseURI());
699 NS_ENSURE_SUCCESS(rv
, rv
);
702 nsIScriptSecurityManager
* secMan
= nsContentUtils::GetSecurityManager();
703 rv
= secMan
->CheckLoadURIWithPrincipal(mDocument
->NodePrincipal(), url
,
704 nsIScriptSecurityManager::ALLOW_CHROME
,
705 mDocument
->InnerWindowID());
706 NS_ENSURE_SUCCESS(rv
, NS_OK
);
708 nsCOMPtr
<nsILoadInfo
> secCheckLoadInfo
=
709 new net::LoadInfo(mDocument
->NodePrincipal(), // loading principal
710 mDocument
->NodePrincipal(), // triggering principal
711 aProcessingInstruction
,
712 nsILoadInfo::SEC_ONLY_FOR_EXPLICIT_CONTENTSEC_CHECK
,
713 nsIContentPolicy::TYPE_XSLT
);
715 // Do content policy check
716 int16_t decision
= nsIContentPolicy::ACCEPT
;
717 rv
= NS_CheckContentLoadPolicy(url
, secCheckLoadInfo
,
718 NS_ConvertUTF16toUTF8(aType
), &decision
,
719 nsContentUtils::GetContentPolicy());
721 NS_ENSURE_SUCCESS(rv
, rv
);
723 if (NS_CP_REJECTED(decision
)) {
727 return LoadXSLStyleSheet(url
);
730 void nsXMLContentSink::SetDocumentCharset(NotNull
<const Encoding
*> aEncoding
) {
732 mDocument
->SetDocumentCharacterSet(aEncoding
);
736 nsISupports
* nsXMLContentSink::GetTarget() { return ToSupports(mDocument
); }
738 bool nsXMLContentSink::IsScriptExecuting() { return IsScriptExecutingImpl(); }
740 nsresult
nsXMLContentSink::FlushText(bool aReleaseTextNode
) {
743 if (mTextLength
!= 0) {
745 bool notify
= HaveNotifiedForCurrentContent();
746 // We could probably always increase mInNotification here since
747 // if AppendText doesn't notify it shouldn't trigger evil code.
748 // But just in case it does, we don't want to mask any notifications.
752 rv
= mLastTextNode
->AppendText(mText
, mTextLength
, notify
);
759 RefPtr
<nsTextNode
> textContent
=
760 new (mNodeInfoManager
) nsTextNode(mNodeInfoManager
);
762 mLastTextNode
= textContent
;
764 // Set the text in the text node
765 textContent
->SetText(mText
, mTextLength
, false);
768 // Add text to its parent
769 rv
= AddContentAsLeaf(textContent
);
773 if (aReleaseTextNode
) {
774 mLastTextNode
= nullptr;
780 nsIContent
* nsXMLContentSink::GetCurrentContent() {
781 if (mContentStack
.Length() == 0) {
784 return GetCurrentStackNode()->mContent
;
787 nsXMLContentSink::StackNode
* nsXMLContentSink::GetCurrentStackNode() {
788 int32_t count
= mContentStack
.Length();
789 return count
!= 0 ? &mContentStack
[count
- 1] : nullptr;
792 nsresult
nsXMLContentSink::PushContent(nsIContent
* aContent
) {
793 MOZ_ASSERT(aContent
, "Null content being pushed!");
794 StackNode
* sn
= mContentStack
.AppendElement();
795 NS_ENSURE_TRUE(sn
, NS_ERROR_OUT_OF_MEMORY
);
797 nsIContent
* contentToPush
= aContent
;
799 // When an XML parser would append a node to a template element, it
800 // must instead append it to the template element's template contents.
801 if (contentToPush
->IsHTMLElement(nsGkAtoms::_template
)) {
802 HTMLTemplateElement
* templateElement
=
803 static_cast<HTMLTemplateElement
*>(contentToPush
);
804 contentToPush
= templateElement
->Content();
807 sn
->mContent
= contentToPush
;
812 void nsXMLContentSink::PopContent() {
813 if (mContentStack
.IsEmpty()) {
814 NS_WARNING("Popping empty stack");
818 mContentStack
.RemoveLastElement();
821 bool nsXMLContentSink::HaveNotifiedForCurrentContent() const {
822 uint32_t stackLength
= mContentStack
.Length();
824 const StackNode
& stackNode
= mContentStack
[stackLength
- 1];
825 nsIContent
* parent
= stackNode
.mContent
;
826 return stackNode
.mNumFlushed
== parent
->GetChildCount();
831 void nsXMLContentSink::MaybeStartLayout(bool aIgnorePendingSheets
) {
832 // XXXbz if aIgnorePendingSheets is true, what should we do when
833 // mXSLTProcessor or CanStillPrettyPrint()?
834 if (mLayoutStarted
|| mXSLTProcessor
|| CanStillPrettyPrint()) {
837 StartLayout(aIgnorePendingSheets
);
840 ////////////////////////////////////////////////////////////////////////
842 bool nsXMLContentSink::SetDocElement(int32_t aNameSpaceID
, nsAtom
* aTagName
,
843 nsIContent
* aContent
) {
844 if (mDocElement
) return false;
846 mDocElement
= aContent
;
848 if (mXSLTProcessor
) {
849 mDocumentChildren
.AppendElement(aContent
);
853 if (!mDocumentChildren
.IsEmpty()) {
854 for (nsIContent
* child
: mDocumentChildren
) {
855 mDocument
->AppendChildTo(child
, false, IgnoreErrors());
857 mDocumentChildren
.Clear();
860 // check for root elements that needs special handling for
862 if (aNameSpaceID
== kNameSpaceID_XSLT
&&
863 (aTagName
== nsGkAtoms::stylesheet
|| aTagName
== nsGkAtoms::transform
)) {
864 mPrettyPrintHasSpecialRoot
= true;
865 if (mPrettyPrintXML
) {
866 // In this case, disable script execution, stylesheet
867 // loading, and auto XLinks since we plan to prettyprint.
868 mDocument
->ScriptLoader()->SetEnabled(false);
870 mCSSLoader
->SetEnabled(false);
875 IgnoredErrorResult rv
;
876 mDocument
->AppendChildTo(mDocElement
, NotifyForDocElement(), rv
);
878 // If we return false here, the caller will bail out because it won't
879 // find a parent content node to append to, which is fine.
887 nsXMLContentSink::HandleStartElement(const char16_t
* aName
,
888 const char16_t
** aAtts
,
889 uint32_t aAttsCount
, uint32_t aLineNumber
,
890 uint32_t aColumnNumber
) {
891 return HandleStartElement(aName
, aAtts
, aAttsCount
, aLineNumber
,
892 aColumnNumber
, true);
895 nsresult
nsXMLContentSink::HandleStartElement(
896 const char16_t
* aName
, const char16_t
** aAtts
, uint32_t aAttsCount
,
897 uint32_t aLineNumber
, uint32_t aColumnNumber
, bool aInterruptable
) {
898 MOZ_ASSERT(aAttsCount
% 2 == 0, "incorrect aAttsCount");
899 // Adjust aAttsCount so it's the actual number of attributes
902 nsresult result
= NS_OK
;
903 bool appendContent
= true;
904 nsCOMPtr
<nsIContent
> content
;
906 // XXX Hopefully the parser will flag this before we get
907 // here. If we're in the epilog, there should be no
909 MOZ_ASSERT(eXMLContentSinkState_InEpilog
!= mState
);
914 mState
= eXMLContentSinkState_InDocumentElement
;
917 RefPtr
<nsAtom
> prefix
, localName
;
918 nsContentUtils::SplitExpatName(aName
, getter_AddRefs(prefix
),
919 getter_AddRefs(localName
), &nameSpaceID
);
921 if (!OnOpenContainer(aAtts
, aAttsCount
, nameSpaceID
, localName
,
926 RefPtr
<mozilla::dom::NodeInfo
> nodeInfo
;
927 nodeInfo
= mNodeInfoManager
->GetNodeInfo(localName
, prefix
, nameSpaceID
,
928 nsINode::ELEMENT_NODE
);
930 result
= CreateElement(aAtts
, aAttsCount
, nodeInfo
, aLineNumber
,
931 aColumnNumber
, getter_AddRefs(content
), &appendContent
,
932 FROM_PARSER_NETWORK
);
933 NS_ENSURE_SUCCESS(result
, result
);
935 // Have to do this before we push the new content on the stack... and have to
936 // do that before we set attributes, call BindToTree, etc. Ideally we'd push
937 // on the stack inside CreateElement (which is effectively what the HTML sink
938 // does), but that's hard with all the subclass overrides going on.
939 nsCOMPtr
<nsIContent
> parent
= GetCurrentContent();
941 result
= PushContent(content
);
942 NS_ENSURE_SUCCESS(result
, result
);
944 // Set the attributes on the new content element
945 result
= AddAttributes(aAtts
, content
->AsElement());
947 if (NS_OK
== result
) {
949 if (!SetDocElement(nameSpaceID
, localName
, content
) && appendContent
) {
950 NS_ENSURE_TRUE(parent
, NS_ERROR_UNEXPECTED
);
952 parent
->AppendChildTo(content
, false, IgnoreErrors());
956 // Some HTML nodes need DoneCreatingElement() called to initialize
957 // properly (eg form state restoration).
958 if (nsIContent::RequiresDoneCreatingElement(nodeInfo
->NamespaceID(),
959 nodeInfo
->NameAtom())) {
960 content
->DoneCreatingElement();
963 if (nodeInfo
->NamespaceID() == kNameSpaceID_XHTML
&&
964 nodeInfo
->NameAtom() == nsGkAtoms::head
&& !mCurrentHead
) {
965 mCurrentHead
= content
;
968 if (IsMonolithicContainer(nodeInfo
)) {
969 mInMonolithicContainer
++;
972 if (!mXSLTProcessor
) {
973 if (content
== mDocElement
) {
974 nsContentUtils::AddScriptRunner(
975 new nsDocElementCreatedNotificationRunner(mDocument
));
977 if (aInterruptable
&& NS_SUCCEEDED(result
) && mParser
&&
978 !mParser
->IsParserEnabled()) {
979 return NS_ERROR_HTMLPARSER_BLOCK
;
981 } else if (!mCurrentHead
) {
982 // This isn't the root and we're not inside an XHTML <head>.
983 // Might need to start layout
984 MaybeStartLayout(false);
988 return aInterruptable
&& NS_SUCCEEDED(result
) ? DidProcessATokenImpl()
993 nsXMLContentSink::HandleEndElement(const char16_t
* aName
) {
994 return HandleEndElement(aName
, true);
997 nsresult
nsXMLContentSink::HandleEndElement(const char16_t
* aName
,
998 bool aInterruptable
) {
999 nsresult result
= NS_OK
;
1001 // XXX Hopefully the parser will flag this before we get
1002 // here. If we're in the prolog or epilog, there should be
1003 // no close tags for elements.
1004 MOZ_ASSERT(eXMLContentSinkState_InDocumentElement
== mState
);
1008 StackNode
* sn
= GetCurrentStackNode();
1010 return NS_ERROR_UNEXPECTED
;
1013 nsCOMPtr
<nsIContent
> content
;
1014 sn
->mContent
.swap(content
);
1015 uint32_t numFlushed
= sn
->mNumFlushed
;
1018 NS_ASSERTION(content
, "failed to pop content");
1020 // Check that we're closing the right thing
1021 RefPtr
<nsAtom
> debugNameSpacePrefix
, debugTagAtom
;
1022 int32_t debugNameSpaceID
;
1023 nsContentUtils::SplitExpatName(aName
, getter_AddRefs(debugNameSpacePrefix
),
1024 getter_AddRefs(debugTagAtom
),
1026 // Check if we are closing a template element because template
1027 // elements do not get pushed on the stack, the template
1028 // element content is pushed instead.
1029 bool isTemplateElement
= debugTagAtom
== nsGkAtoms::_template
&&
1030 debugNameSpaceID
== kNameSpaceID_XHTML
;
1032 content
->NodeInfo()->Equals(debugTagAtom
, debugNameSpaceID
) ||
1033 (debugNameSpaceID
== kNameSpaceID_MathML
&&
1034 content
->NodeInfo()->NamespaceID() == kNameSpaceID_disabled_MathML
&&
1035 content
->NodeInfo()->Equals(debugTagAtom
)) ||
1036 (debugNameSpaceID
== kNameSpaceID_SVG
&&
1037 content
->NodeInfo()->NamespaceID() == kNameSpaceID_disabled_SVG
&&
1038 content
->NodeInfo()->Equals(debugTagAtom
)) ||
1040 "Wrong element being closed");
1043 // Make sure to notify on our kids before we call out to any other code that
1044 // might reenter us and call FlushTags, in a state in which we've already
1045 // popped "content" from the stack but haven't notified on its kids yet.
1046 int32_t stackLen
= mContentStack
.Length();
1047 if (mNotifyLevel
>= stackLen
) {
1048 if (numFlushed
< content
->GetChildCount()) {
1049 NotifyAppend(content
, numFlushed
);
1051 mNotifyLevel
= stackLen
- 1;
1054 result
= CloseElement(content
);
1056 if (mCurrentHead
== content
) {
1057 mCurrentHead
= nullptr;
1060 if (mDocElement
== content
) {
1061 // XXXbz for roots that don't want to be appended on open, we
1062 // probably need to deal here.... (and stop appending them on open).
1063 mState
= eXMLContentSinkState_InEpilog
;
1065 mDocument
->OnParsingCompleted();
1067 // We might have had no occasion to start layout yet. Do so now.
1068 MaybeStartLayout(false);
1073 if (content
->IsSVGElement(nsGkAtoms::svg
)) {
1075 nsCOMPtr
<nsIRunnable
> event
= new nsHtml5SVGLoadDispatcher(content
);
1076 if (NS_FAILED(content
->OwnerDoc()->Dispatch(event
.forget()))) {
1077 NS_WARNING("failed to dispatch svg load dispatcher");
1081 return aInterruptable
&& NS_SUCCEEDED(result
) ? DidProcessATokenImpl()
1086 nsXMLContentSink::HandleComment(const char16_t
* aName
) {
1089 RefPtr
<Comment
> comment
= new (mNodeInfoManager
) Comment(mNodeInfoManager
);
1090 comment
->SetText(nsDependentString(aName
), false);
1091 nsresult rv
= AddContentAsLeaf(comment
);
1094 return NS_SUCCEEDED(rv
) ? DidProcessATokenImpl() : rv
;
1098 nsXMLContentSink::HandleCDataSection(const char16_t
* aData
, uint32_t aLength
) {
1099 // XSLT doesn't differentiate between text and cdata and wants adjacent
1100 // textnodes merged, so add as text.
1101 if (mXSLTProcessor
) {
1102 return AddText(aData
, aLength
);
1107 RefPtr
<CDATASection
> cdata
=
1108 new (mNodeInfoManager
) CDATASection(mNodeInfoManager
);
1109 cdata
->SetText(aData
, aLength
, false);
1110 nsresult rv
= AddContentAsLeaf(cdata
);
1113 return NS_SUCCEEDED(rv
) ? DidProcessATokenImpl() : rv
;
1117 nsXMLContentSink::HandleDoctypeDecl(const nsAString
& aSubset
,
1118 const nsAString
& aName
,
1119 const nsAString
& aSystemId
,
1120 const nsAString
& aPublicId
,
1121 nsISupports
* aCatalogData
) {
1124 NS_ASSERTION(mDocument
, "Shouldn't get here from a document fragment");
1126 RefPtr
<nsAtom
> name
= NS_Atomize(aName
);
1127 NS_ENSURE_TRUE(name
, NS_ERROR_OUT_OF_MEMORY
);
1129 // Create a new doctype node
1130 RefPtr
<DocumentType
> docType
= NS_NewDOMDocumentType(
1131 mNodeInfoManager
, name
, aPublicId
, aSystemId
, aSubset
);
1133 MOZ_ASSERT(!aCatalogData
,
1134 "Need to add back support for catalog style "
1137 mDocumentChildren
.AppendElement(docType
);
1139 return DidProcessATokenImpl();
1143 nsXMLContentSink::HandleCharacterData(const char16_t
* aData
, uint32_t aLength
) {
1144 return HandleCharacterData(aData
, aLength
, true);
1147 nsresult
nsXMLContentSink::HandleCharacterData(const char16_t
* aData
,
1149 bool aInterruptable
) {
1150 nsresult rv
= NS_OK
;
1151 if (aData
&& mState
!= eXMLContentSinkState_InProlog
&&
1152 mState
!= eXMLContentSinkState_InEpilog
) {
1153 rv
= AddText(aData
, aLength
);
1155 return aInterruptable
&& NS_SUCCEEDED(rv
) ? DidProcessATokenImpl() : rv
;
1159 nsXMLContentSink::HandleProcessingInstruction(const char16_t
* aTarget
,
1160 const char16_t
* aData
) {
1163 const nsDependentString
target(aTarget
);
1164 const nsDependentString
data(aData
);
1166 RefPtr
<ProcessingInstruction
> node
=
1167 NS_NewXMLProcessingInstruction(mNodeInfoManager
, target
, data
);
1169 auto* linkStyle
= LinkStyle::FromNode(*node
);
1171 linkStyle
->DisableUpdates();
1172 mPrettyPrintXML
= false;
1175 nsresult rv
= AddContentAsLeaf(node
);
1176 NS_ENSURE_SUCCESS(rv
, rv
);
1180 // This is an xml-stylesheet processing instruction... but it might not be
1181 // a CSS one if the type is set to something else.
1182 auto updateOrError
= linkStyle
->EnableUpdatesAndUpdateStyleSheet(
1183 mRunsToCompletion
? nullptr : this);
1184 if (updateOrError
.isErr()) {
1185 return updateOrError
.unwrapErr();
1188 auto update
= updateOrError
.unwrap();
1189 if (update
.WillNotify()) {
1190 // Successfully started a stylesheet load
1191 if (update
.ShouldBlock() && !mRunsToCompletion
) {
1192 ++mPendingSheetCount
;
1193 mScriptLoader
->AddParserBlockingScriptExecutionBlocker();
1199 // Check whether this is a CSS stylesheet PI. Make sure the type
1200 // handling here matches
1201 // XMLStylesheetProcessingInstruction::GetStyleSheetInfo.
1203 nsContentUtils::GetPseudoAttributeValue(data
, nsGkAtoms::type
, type
);
1204 nsAutoString mimeType
, notUsed
;
1205 nsContentUtils::SplitMimeType(type
, mimeType
, notUsed
);
1207 if (mState
!= eXMLContentSinkState_InProlog
||
1208 !target
.EqualsLiteral("xml-stylesheet") || mimeType
.IsEmpty() ||
1209 mimeType
.LowerCaseEqualsLiteral("text/css")) {
1210 // Either not a useful stylesheet PI, or a CSS stylesheet PI that
1211 // got handled above by the "ssle" bits. We're done here.
1212 return DidProcessATokenImpl();
1215 // If it's not a CSS stylesheet PI...
1216 nsAutoString href
, title
, media
;
1217 bool isAlternate
= false;
1219 // If there was no href, we can't do anything with this PI
1220 if (!ParsePIData(data
, href
, title
, media
, isAlternate
)) {
1221 return DidProcessATokenImpl();
1224 // <?xml-stylesheet?> processing instructions don't have a referrerpolicy
1225 // pseudo-attribute, so we pass in an empty string
1227 MaybeProcessXSLTLink(node
, href
, isAlternate
, title
, type
, media
, u
""_ns
);
1228 return NS_SUCCEEDED(rv
) ? DidProcessATokenImpl() : rv
;
1232 bool nsXMLContentSink::ParsePIData(const nsString
& aData
, nsString
& aHref
,
1233 nsString
& aTitle
, nsString
& aMedia
,
1234 bool& aIsAlternate
) {
1235 // If there was no href, we can't do anything with this PI
1236 if (!nsContentUtils::GetPseudoAttributeValue(aData
, nsGkAtoms::href
, aHref
)) {
1240 nsContentUtils::GetPseudoAttributeValue(aData
, nsGkAtoms::title
, aTitle
);
1242 nsContentUtils::GetPseudoAttributeValue(aData
, nsGkAtoms::media
, aMedia
);
1244 nsAutoString alternate
;
1245 nsContentUtils::GetPseudoAttributeValue(aData
, nsGkAtoms::alternate
,
1248 aIsAlternate
= alternate
.EqualsLiteral("yes");
1254 nsXMLContentSink::HandleXMLDeclaration(const char16_t
* aVersion
,
1255 const char16_t
* aEncoding
,
1256 int32_t aStandalone
) {
1257 mDocument
->SetXMLDeclaration(aVersion
, aEncoding
, aStandalone
);
1259 return DidProcessATokenImpl();
1263 nsXMLContentSink::ReportError(const char16_t
* aErrorText
,
1264 const char16_t
* aSourceText
,
1265 nsIScriptError
* aError
, bool* _retval
) {
1266 MOZ_ASSERT(aError
&& aSourceText
&& aErrorText
, "Check arguments!!!");
1267 nsresult rv
= NS_OK
;
1269 // The expat driver should report the error. We're just cleaning up the mess.
1272 mPrettyPrintXML
= false;
1274 mState
= eXMLContentSinkState_InProlog
;
1276 // XXX need to stop scripts here -- hsivonen
1278 // stop observing in order to avoid crashing when removing content
1279 mDocument
->RemoveObserver(this);
1280 mIsDocumentObserver
= false;
1282 // Clear the current content
1283 mDocumentChildren
.Clear();
1284 while (mDocument
->GetLastChild()) {
1285 mDocument
->GetLastChild()->Remove();
1287 mDocElement
= nullptr;
1289 // Clear any buffered-up text we have. It's enough to set the length to 0.
1290 // The buffer itself is allocated when we're created and deleted in our
1291 // destructor, so don't mess with it.
1294 if (mXSLTProcessor
) {
1295 // Get rid of the XSLT processor.
1296 mXSLTProcessor
->CancelLoads();
1297 mXSLTProcessor
= nullptr;
1300 // release the nodes on stack
1301 mContentStack
.Clear();
1304 // return leaving the document empty if we're asked to not add a <parsererror>
1306 if (mDocument
->SuppressParserErrorElement()) {
1310 // prepare to set <parsererror> as the document root
1311 rv
= HandleProcessingInstruction(
1313 u
"href=\"chrome://global/locale/intl.css\" type=\"text/css\"");
1314 NS_ENSURE_SUCCESS(rv
, rv
);
1316 const char16_t
* noAtts
[] = {0, 0};
1318 constexpr auto errorNs
=
1319 u
"http://www.mozilla.org/newlayout/xml/parsererror.xml"_ns
;
1321 nsAutoString
parsererror(errorNs
);
1322 parsererror
.Append((char16_t
)0xFFFF);
1323 parsererror
.AppendLiteral("parsererror");
1325 rv
= HandleStartElement(parsererror
.get(), noAtts
, 0, (uint32_t)-1, false);
1326 NS_ENSURE_SUCCESS(rv
, rv
);
1328 rv
= HandleCharacterData(aErrorText
, NS_strlen(aErrorText
), false);
1329 NS_ENSURE_SUCCESS(rv
, rv
);
1331 nsAutoString
sourcetext(errorNs
);
1332 sourcetext
.Append((char16_t
)0xFFFF);
1333 sourcetext
.AppendLiteral("sourcetext");
1335 rv
= HandleStartElement(sourcetext
.get(), noAtts
, 0, (uint32_t)-1, false);
1336 NS_ENSURE_SUCCESS(rv
, rv
);
1338 rv
= HandleCharacterData(aSourceText
, NS_strlen(aSourceText
), false);
1339 NS_ENSURE_SUCCESS(rv
, rv
);
1341 rv
= HandleEndElement(sourcetext
.get(), false);
1342 NS_ENSURE_SUCCESS(rv
, rv
);
1344 rv
= HandleEndElement(parsererror
.get(), false);
1345 NS_ENSURE_SUCCESS(rv
, rv
);
1352 nsresult
nsXMLContentSink::AddAttributes(const char16_t
** aAtts
,
1353 Element
* aContent
) {
1354 // Add tag attributes to the content attributes
1355 RefPtr
<nsAtom
> prefix
, localName
;
1357 int32_t nameSpaceID
;
1358 nsContentUtils::SplitExpatName(aAtts
[0], getter_AddRefs(prefix
),
1359 getter_AddRefs(localName
), &nameSpaceID
);
1361 // Add attribute to content
1362 aContent
->SetAttr(nameSpaceID
, localName
, prefix
,
1363 nsDependentString(aAtts
[1]), false);
1370 #define NS_ACCUMULATION_BUFFER_SIZE 4096
1372 nsresult
nsXMLContentSink::AddText(const char16_t
* aText
, int32_t aLength
) {
1373 // Copy data from string into our buffer; flush buffer when it fills up.
1375 while (0 != aLength
) {
1376 int32_t amount
= NS_ACCUMULATION_BUFFER_SIZE
- mTextLength
;
1378 nsresult rv
= FlushText(false);
1379 if (NS_WARN_IF(NS_FAILED(rv
))) {
1382 MOZ_ASSERT(mTextLength
== 0);
1383 amount
= NS_ACCUMULATION_BUFFER_SIZE
;
1386 if (amount
> aLength
) {
1389 memcpy(&mText
[mTextLength
], &aText
[offset
], sizeof(char16_t
) * amount
);
1390 mTextLength
+= amount
;
1398 void nsXMLContentSink::InitialTranslationCompleted() { StartLayout(false); }
1400 void nsXMLContentSink::FlushPendingNotifications(FlushType aType
) {
1401 // Only flush tags if we're not doing the notification ourselves
1402 // (since we aren't reentrant)
1403 if (!mInNotification
) {
1404 if (mIsDocumentObserver
) {
1405 // Only flush if we're still a document observer (so that our child
1406 // counts should be correct).
1407 if (aType
>= FlushType::ContentAndNotify
) {
1413 if (aType
>= FlushType::EnsurePresShellInitAndFrames
) {
1414 // Make sure that layout has started so that the reflow flush
1415 // will actually happen.
1416 MaybeStartLayout(true);
1422 * NOTE!! Forked from SinkContext. Please keep in sync.
1424 * Flush all elements that have been seen so far such that
1425 * they are visible in the tree. Specifically, make sure
1426 * that they are all added to their respective parents.
1427 * Also, do notification at the top for all content that
1428 * has been newly added so that the frame tree is complete.
1430 nsresult
nsXMLContentSink::FlushTags() {
1431 mDeferredFlushTags
= false;
1432 uint32_t oldUpdates
= mUpdatesInNotification
;
1434 mUpdatesInNotification
= 0;
1437 // Scope so we call EndUpdate before we decrease mInNotification
1438 mozAutoDocUpdate
updateBatch(mDocument
, true);
1440 // Don't release last text node in case we need to add to it again
1443 // Start from the base of the stack (growing downward) and do
1444 // a notification from the node that is closest to the root of
1445 // tree for any content that has been added.
1448 int32_t stackLen
= mContentStack
.Length();
1449 bool flushed
= false;
1450 uint32_t childCount
;
1451 nsIContent
* content
;
1453 for (stackPos
= 0; stackPos
< stackLen
; ++stackPos
) {
1454 content
= mContentStack
[stackPos
].mContent
;
1455 childCount
= content
->GetChildCount();
1457 if (!flushed
&& (mContentStack
[stackPos
].mNumFlushed
< childCount
)) {
1458 NotifyAppend(content
, mContentStack
[stackPos
].mNumFlushed
);
1462 mContentStack
[stackPos
].mNumFlushed
= childCount
;
1464 mNotifyLevel
= stackLen
- 1;
1468 if (mUpdatesInNotification
> 1) {
1469 UpdateChildCounts();
1472 mUpdatesInNotification
= oldUpdates
;
1477 * NOTE!! Forked from SinkContext. Please keep in sync.
1479 void nsXMLContentSink::UpdateChildCounts() {
1480 // Start from the top of the stack (growing upwards) and see if any
1481 // new content has been appended. If so, we recognize that reflows
1482 // have been generated for it and we should make sure that no
1483 // further reflows occur. Note that we have to include stackPos == 0
1484 // to properly notify on kids of <html>.
1485 int32_t stackLen
= mContentStack
.Length();
1486 int32_t stackPos
= stackLen
- 1;
1487 while (stackPos
>= 0) {
1488 StackNode
& node
= mContentStack
[stackPos
];
1489 node
.mNumFlushed
= node
.mContent
->GetChildCount();
1493 mNotifyLevel
= stackLen
- 1;
1496 bool nsXMLContentSink::IsMonolithicContainer(
1497 mozilla::dom::NodeInfo
* aNodeInfo
) {
1498 return ((aNodeInfo
->NamespaceID() == kNameSpaceID_XHTML
&&
1499 (aNodeInfo
->NameAtom() == nsGkAtoms::tr
||
1500 aNodeInfo
->NameAtom() == nsGkAtoms::select
||
1501 aNodeInfo
->NameAtom() == nsGkAtoms::object
)) ||
1502 (aNodeInfo
->NamespaceID() == kNameSpaceID_MathML
&&
1503 (aNodeInfo
->NameAtom() == nsGkAtoms::math
)));
1506 void nsXMLContentSink::ContinueInterruptedParsingIfEnabled() {
1507 if (mParser
&& mParser
->IsParserEnabled()) {
1508 GetParser()->ContinueInterruptedParsing();
1512 void nsXMLContentSink::ContinueInterruptedParsingAsync() {
1513 nsCOMPtr
<nsIRunnable
> ev
= NewRunnableMethod(
1514 "nsXMLContentSink::ContinueInterruptedParsingIfEnabled", this,
1515 &nsXMLContentSink::ContinueInterruptedParsingIfEnabled
);
1516 mDocument
->Dispatch(ev
.forget());
1519 nsIParser
* nsXMLContentSink::GetParser() {
1520 return static_cast<nsIParser
*>(mParser
.get());