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/. */
6
7 /**
8 * This file is near-OBSOLETE. It is used for about:blank only and for the
9 * HTML element factory.
10 * Don't bother adding new stuff in this file.
11 */
12
13 #include "mozilla/ArrayUtils.h"
14
15 #include "nsContentSink.h"
16 #include "nsCOMPtr.h"
17 #include "nsHTMLTags.h"
18 #include "nsReadableUtils.h"
19 #include "nsUnicharUtils.h"
20 #include "nsIHTMLContentSink.h"
21 #include "nsIInterfaceRequestor.h"
22 #include "nsIInterfaceRequestorUtils.h"
23 #include "nsIURI.h"
24 #include "mozilla/dom/NodeInfo.h"
25 #include "mozilla/dom/ScriptLoader.h"
26 #include "nsCRT.h"
27 #include "prtime.h"
28 #include "mozilla/Logging.h"
29 #include "nsIContent.h"
30 #include "mozilla/dom/CustomElementRegistry.h"
31 #include "mozilla/dom/Element.h"
32 #include "mozilla/dom/MutationObservers.h"
33 #include "mozilla/Preferences.h"
34
35 #include "nsGenericHTMLElement.h"
36
37 #include "nsIScriptElement.h"
38
39 #include "nsDocElementCreatedNotificationRunner.h"
40 #include "nsGkAtoms.h"
41 #include "nsContentUtils.h"
42 #include "nsIChannel.h"
43 #include "mozilla/dom/Document.h"
44 #include "nsStubDocumentObserver.h"
45 #include "nsHTMLDocument.h"
46 #include "nsTArray.h"
47 #include "nsTextFragment.h"
48 #include "nsIScriptGlobalObject.h"
49 #include "nsNameSpaceManager.h"
50
51 #include "nsError.h"
52 #include "nsContentPolicyUtils.h"
53 #include "nsIDocShell.h"
54 #include "nsIScriptContext.h"
55
56 #include "nsLayoutCID.h"
57
58 #include "nsEscape.h"
59 #include "nsNodeInfoManager.h"
60 #include "nsContentCreatorFunctions.h"
61 #include "mozAutoDocUpdate.h"
62 #include "nsTextNode.h"
63
64 using namespace mozilla;
65 using namespace mozilla::dom;
66
67 //----------------------------------------------------------------------
68
NS_NewHTMLNOTUSEDElement(already_AddRefed<mozilla::dom::NodeInfo> && aNodeInfo,FromParser aFromParser)69 nsGenericHTMLElement* NS_NewHTMLNOTUSEDElement(
70 already_AddRefed<mozilla::dom::NodeInfo>&& aNodeInfo,
71 FromParser aFromParser) {
72 MOZ_ASSERT_UNREACHABLE("The element ctor should never be called");
73 return nullptr;
74 }
75
76 #define HTML_TAG(_tag, _classname, _interfacename) \
77 NS_NewHTML##_classname##Element,
78 #define HTML_OTHER(_tag) NS_NewHTMLNOTUSEDElement,
79 static const HTMLContentCreatorFunction sHTMLContentCreatorFunctions[] = {
80 NS_NewHTMLUnknownElement,
81 #include "nsHTMLTagList.h"
82 #undef HTML_TAG
83 #undef HTML_OTHER
84 NS_NewHTMLUnknownElement};
85
86 class SinkContext;
87 class HTMLContentSink;
88
89 /**
90 * This class is near-OBSOLETE. It is used for about:blank only.
91 * Don't bother adding new stuff in this file.
92 */
93 class HTMLContentSink : public nsContentSink, public nsIHTMLContentSink {
94 public:
95 friend class SinkContext;
96
97 HTMLContentSink();
98
99 nsresult Init(Document* aDoc, nsIURI* aURI, nsISupports* aContainer,
100 nsIChannel* aChannel);
101
102 // nsISupports
103 NS_DECL_ISUPPORTS_INHERITED
104 NS_DECL_CYCLE_COLLECTION_CLASS_INHERITED(HTMLContentSink, nsContentSink)
105
106 // nsIContentSink
107 NS_IMETHOD WillParse(void) override;
108 NS_IMETHOD WillBuildModel(nsDTDMode aDTDMode) override;
109 NS_IMETHOD DidBuildModel(bool aTerminated) override;
110 NS_IMETHOD WillInterrupt(void) override;
111 NS_IMETHOD WillResume(void) override;
112 NS_IMETHOD SetParser(nsParserBase* aParser) override;
113 virtual void FlushPendingNotifications(FlushType aType) override;
114 virtual void SetDocumentCharset(NotNull<const Encoding*> aEncoding) override;
115 virtual nsISupports* GetTarget() override;
116 virtual bool IsScriptExecuting() override;
117 virtual void ContinueInterruptedParsingAsync() override;
118
119 // nsIHTMLContentSink
120 NS_IMETHOD OpenContainer(ElementType aNodeType) override;
121 NS_IMETHOD CloseContainer(ElementType aTag) override;
122
123 protected:
124 virtual ~HTMLContentSink();
125
126 RefPtr<nsHTMLDocument> mHTMLDocument;
127
128 // The maximum length of a text run
129 int32_t mMaxTextRun;
130
131 RefPtr<nsGenericHTMLElement> mRoot;
132 RefPtr<nsGenericHTMLElement> mBody;
133 RefPtr<nsGenericHTMLElement> mHead;
134
135 AutoTArray<SinkContext*, 8> mContextStack;
136 SinkContext* mCurrentContext;
137 SinkContext* mHeadContext;
138
139 // Boolean indicating whether we've seen a <head> tag that might have had
140 // attributes once already.
141 bool mHaveSeenHead;
142
143 // Boolean indicating whether we've notified insertion of our root content
144 // yet. We want to make sure to only do this once.
145 bool mNotifiedRootInsertion;
146
147 nsresult FlushTags() override;
148
149 // Routines for tags that require special handling
150 nsresult CloseHTML();
151 nsresult OpenBody();
152 nsresult CloseBody();
153
154 void CloseHeadContext();
155
156 // nsContentSink overrides
157 void UpdateChildCounts() override;
158
159 void NotifyInsert(nsIContent* aContent, nsIContent* aChildContent);
160 void NotifyRootInsertion();
161
162 private:
163 void ContinueInterruptedParsingIfEnabled();
164 };
165
166 class SinkContext {
167 public:
168 explicit SinkContext(HTMLContentSink* aSink);
169 ~SinkContext();
170
171 nsresult Begin(nsHTMLTag aNodeType, nsGenericHTMLElement* aRoot,
172 uint32_t aNumFlushed, int32_t aInsertionPoint);
173 nsresult OpenBody();
174 nsresult CloseBody();
175 nsresult End();
176
177 nsresult GrowStack();
178 nsresult FlushTags();
179
180 bool IsCurrentContainer(nsHTMLTag mType);
181
182 void DidAddContent(nsIContent* aContent);
183 void UpdateChildCounts();
184
185 private:
186 // Function to check whether we've notified for the current content.
187 // What this actually does is check whether we've notified for all
188 // of the parent's kids.
189 bool HaveNotifiedForCurrentContent() const;
190
191 public:
192 HTMLContentSink* mSink;
193 int32_t mNotifyLevel;
194
195 struct Node {
196 nsHTMLTag mType;
197 nsGenericHTMLElement* mContent;
198 uint32_t mNumFlushed;
199 int32_t mInsertionPoint;
200
201 nsIContent* Add(nsIContent* child);
202 };
203
204 Node* mStack;
205 int32_t mStackSize;
206 int32_t mStackPos;
207 };
208
NS_NewHTMLElement(Element ** aResult,already_AddRefed<mozilla::dom::NodeInfo> && aNodeInfo,FromParser aFromParser,nsAtom * aIsAtom,mozilla::dom::CustomElementDefinition * aDefinition)209 nsresult NS_NewHTMLElement(Element** aResult,
210 already_AddRefed<mozilla::dom::NodeInfo>&& aNodeInfo,
211 FromParser aFromParser, nsAtom* aIsAtom,
212 mozilla::dom::CustomElementDefinition* aDefinition) {
213 RefPtr<mozilla::dom::NodeInfo> nodeInfo = aNodeInfo;
214
215 NS_ASSERTION(
216 nodeInfo->NamespaceEquals(kNameSpaceID_XHTML),
217 "Trying to create HTML elements that don't have the XHTML namespace");
218
219 return nsContentUtils::NewXULOrHTMLElement(aResult, nodeInfo, aFromParser,
220 aIsAtom, aDefinition);
221 }
222
CreateHTMLElement(uint32_t aNodeType,already_AddRefed<mozilla::dom::NodeInfo> && aNodeInfo,FromParser aFromParser)223 already_AddRefed<nsGenericHTMLElement> CreateHTMLElement(
224 uint32_t aNodeType, already_AddRefed<mozilla::dom::NodeInfo>&& aNodeInfo,
225 FromParser aFromParser) {
226 NS_ASSERTION(
227 aNodeType <= NS_HTML_TAG_MAX || aNodeType == eHTMLTag_userdefined,
228 "aNodeType is out of bounds");
229
230 HTMLContentCreatorFunction cb = sHTMLContentCreatorFunctions[aNodeType];
231
232 NS_ASSERTION(cb != NS_NewHTMLNOTUSEDElement,
233 "Don't know how to construct tag element!");
234
235 RefPtr<nsGenericHTMLElement> result = cb(std::move(aNodeInfo), aFromParser);
236
237 return result.forget();
238 }
239
240 //----------------------------------------------------------------------
241
SinkContext(HTMLContentSink * aSink)242 SinkContext::SinkContext(HTMLContentSink* aSink)
243 : mSink(aSink),
244 mNotifyLevel(0),
245 mStack(nullptr),
246 mStackSize(0),
247 mStackPos(0) {
248 MOZ_COUNT_CTOR(SinkContext);
249 }
250
~SinkContext()251 SinkContext::~SinkContext() {
252 MOZ_COUNT_DTOR(SinkContext);
253
254 if (mStack) {
255 for (int32_t i = 0; i < mStackPos; i++) {
256 NS_RELEASE(mStack[i].mContent);
257 }
258 delete[] mStack;
259 }
260 }
261
Begin(nsHTMLTag aNodeType,nsGenericHTMLElement * aRoot,uint32_t aNumFlushed,int32_t aInsertionPoint)262 nsresult SinkContext::Begin(nsHTMLTag aNodeType, nsGenericHTMLElement* aRoot,
263 uint32_t aNumFlushed, int32_t aInsertionPoint) {
264 if (mStackSize < 1) {
265 nsresult rv = GrowStack();
266 if (NS_FAILED(rv)) {
267 return rv;
268 }
269 }
270
271 mStack[0].mType = aNodeType;
272 mStack[0].mContent = aRoot;
273 mStack[0].mNumFlushed = aNumFlushed;
274 mStack[0].mInsertionPoint = aInsertionPoint;
275 NS_ADDREF(aRoot);
276 mStackPos = 1;
277
278 return NS_OK;
279 }
280
IsCurrentContainer(nsHTMLTag aTag)281 bool SinkContext::IsCurrentContainer(nsHTMLTag aTag) {
282 if (aTag == mStack[mStackPos - 1].mType) {
283 return true;
284 }
285
286 return false;
287 }
288
DidAddContent(nsIContent * aContent)289 void SinkContext::DidAddContent(nsIContent* aContent) {
290 if ((mStackPos == 2) && (mSink->mBody == mStack[1].mContent)) {
291 // We just finished adding something to the body
292 mNotifyLevel = 0;
293 }
294
295 // If we just added content to a node for which
296 // an insertion happen, we need to do an immediate
297 // notification for that insertion.
298 if (0 < mStackPos && mStack[mStackPos - 1].mInsertionPoint != -1 &&
299 mStack[mStackPos - 1].mNumFlushed <
300 mStack[mStackPos - 1].mContent->GetChildCount()) {
301 nsIContent* parent = mStack[mStackPos - 1].mContent;
302 mSink->NotifyInsert(parent, aContent);
303 mStack[mStackPos - 1].mNumFlushed = parent->GetChildCount();
304 } else if (mSink->IsTimeToNotify()) {
305 FlushTags();
306 }
307 }
308
OpenBody()309 nsresult SinkContext::OpenBody() {
310 if (mStackPos <= 0) {
311 NS_ERROR("container w/o parent");
312
313 return NS_ERROR_FAILURE;
314 }
315
316 nsresult rv;
317 if (mStackPos + 1 > mStackSize) {
318 rv = GrowStack();
319 if (NS_FAILED(rv)) {
320 return rv;
321 }
322 }
323
324 RefPtr<mozilla::dom::NodeInfo> nodeInfo =
325 mSink->mNodeInfoManager->GetNodeInfo(
326 nsGkAtoms::body, nullptr, kNameSpaceID_XHTML, nsINode::ELEMENT_NODE);
327 NS_ENSURE_TRUE(nodeInfo, NS_ERROR_UNEXPECTED);
328
329 // Make the content object
330 RefPtr<nsGenericHTMLElement> body =
331 NS_NewHTMLBodyElement(nodeInfo.forget(), FROM_PARSER_NETWORK);
332 if (!body) {
333 return NS_ERROR_OUT_OF_MEMORY;
334 }
335
336 mStack[mStackPos].mType = eHTMLTag_body;
337 body.forget(&mStack[mStackPos].mContent);
338 mStack[mStackPos].mNumFlushed = 0;
339 mStack[mStackPos].mInsertionPoint = -1;
340 ++mStackPos;
341 mStack[mStackPos - 2].Add(mStack[mStackPos - 1].mContent);
342
343 return NS_OK;
344 }
345
HaveNotifiedForCurrentContent() const346 bool SinkContext::HaveNotifiedForCurrentContent() const {
347 if (0 < mStackPos) {
348 nsIContent* parent = mStack[mStackPos - 1].mContent;
349 return mStack[mStackPos - 1].mNumFlushed == parent->GetChildCount();
350 }
351
352 return true;
353 }
354
Add(nsIContent * child)355 nsIContent* SinkContext::Node::Add(nsIContent* child) {
356 NS_ASSERTION(mContent, "No parent to insert/append into!");
357 if (mInsertionPoint != -1) {
358 NS_ASSERTION(mNumFlushed == mContent->GetChildCount(),
359 "Inserting multiple children without flushing.");
360 nsCOMPtr<nsIContent> nodeToInsertBefore =
361 mContent->GetChildAt_Deprecated(mInsertionPoint++);
362 mContent->InsertChildBefore(child, nodeToInsertBefore, false,
363 IgnoreErrors());
364 } else {
365 mContent->AppendChildTo(child, false, IgnoreErrors());
366 }
367 return child;
368 }
369
CloseBody()370 nsresult SinkContext::CloseBody() {
371 NS_ASSERTION(mStackPos > 0, "stack out of bounds. wrong context probably!");
372
373 if (mStackPos <= 0) {
374 return NS_OK; // Fix crash - Ref. bug 45975 or 45007
375 }
376
377 --mStackPos;
378 NS_ASSERTION(mStack[mStackPos].mType == eHTMLTag_body,
379 "Tag mismatch. Closing tag on wrong context or something?");
380
381 nsGenericHTMLElement* content = mStack[mStackPos].mContent;
382
383 content->Compact();
384
385 // If we're in a state where we do append notifications as
386 // we go up the tree, and we're at the level where the next
387 // notification needs to be done, do the notification.
388 if (mNotifyLevel >= mStackPos) {
389 // Check to see if new content has been added after our last
390 // notification
391
392 if (mStack[mStackPos].mNumFlushed < content->GetChildCount()) {
393 mSink->NotifyAppend(content, mStack[mStackPos].mNumFlushed);
394 mStack[mStackPos].mNumFlushed = content->GetChildCount();
395 }
396
397 // Indicate that notification has now happened at this level
398 mNotifyLevel = mStackPos - 1;
399 }
400
401 DidAddContent(content);
402 NS_IF_RELEASE(content);
403
404 return NS_OK;
405 }
406
End()407 nsresult SinkContext::End() {
408 for (int32_t i = 0; i < mStackPos; i++) {
409 NS_RELEASE(mStack[i].mContent);
410 }
411
412 mStackPos = 0;
413
414 return NS_OK;
415 }
416
GrowStack()417 nsresult SinkContext::GrowStack() {
418 int32_t newSize = mStackSize * 2;
419 if (newSize == 0) {
420 newSize = 32;
421 }
422
423 Node* stack = new Node[newSize];
424
425 if (mStackPos != 0) {
426 memcpy(stack, mStack, sizeof(Node) * mStackPos);
427 delete[] mStack;
428 }
429
430 mStack = stack;
431 mStackSize = newSize;
432
433 return NS_OK;
434 }
435
436 /**
437 * NOTE!! Forked into nsXMLContentSink. Please keep in sync.
438 *
439 * Flush all elements that have been seen so far such that
440 * they are visible in the tree. Specifically, make sure
441 * that they are all added to their respective parents.
442 * Also, do notification at the top for all content that
443 * has been newly added so that the frame tree is complete.
444 */
FlushTags()445 nsresult SinkContext::FlushTags() {
446 mSink->mDeferredFlushTags = false;
447 uint32_t oldUpdates = mSink->mUpdatesInNotification;
448
449 ++(mSink->mInNotification);
450 mSink->mUpdatesInNotification = 0;
451 {
452 // Scope so we call EndUpdate before we decrease mInNotification
453 mozAutoDocUpdate updateBatch(mSink->mDocument, true);
454
455 // Start from the base of the stack (growing downward) and do
456 // a notification from the node that is closest to the root of
457 // tree for any content that has been added.
458
459 // Note that we can start at stackPos == 0 here, because it's the caller's
460 // responsibility to handle flushing interactions between contexts (see
461 // HTMLContentSink::BeginContext).
462 int32_t stackPos = 0;
463 bool flushed = false;
464 uint32_t childCount;
465 nsGenericHTMLElement* content;
466
467 while (stackPos < mStackPos) {
468 content = mStack[stackPos].mContent;
469 childCount = content->GetChildCount();
470
471 if (!flushed && (mStack[stackPos].mNumFlushed < childCount)) {
472 if (mStack[stackPos].mInsertionPoint != -1) {
473 // We might have popped the child off our stack already
474 // but not notified on it yet, which is why we have to get it
475 // directly from its parent node.
476
477 int32_t childIndex = mStack[stackPos].mInsertionPoint - 1;
478 nsIContent* child = content->GetChildAt_Deprecated(childIndex);
479 // Child not on stack anymore; can't assert it's correct
480 NS_ASSERTION(!(mStackPos > (stackPos + 1)) ||
481 (child == mStack[stackPos + 1].mContent),
482 "Flushing the wrong child.");
483 mSink->NotifyInsert(content, child);
484 } else {
485 mSink->NotifyAppend(content, mStack[stackPos].mNumFlushed);
486 }
487
488 flushed = true;
489 }
490
491 mStack[stackPos].mNumFlushed = childCount;
492 stackPos++;
493 }
494 mNotifyLevel = mStackPos - 1;
495 }
496 --(mSink->mInNotification);
497
498 if (mSink->mUpdatesInNotification > 1) {
499 UpdateChildCounts();
500 }
501
502 mSink->mUpdatesInNotification = oldUpdates;
503
504 return NS_OK;
505 }
506
507 /**
508 * NOTE!! Forked into nsXMLContentSink. Please keep in sync.
509 */
UpdateChildCounts()510 void SinkContext::UpdateChildCounts() {
511 // Start from the top of the stack (growing upwards) and see if any
512 // new content has been appended. If so, we recognize that reflows
513 // have been generated for it and we should make sure that no
514 // further reflows occur. Note that we have to include stackPos == 0
515 // to properly notify on kids of <html>.
516 int32_t stackPos = mStackPos - 1;
517 while (stackPos >= 0) {
518 Node& node = mStack[stackPos];
519 node.mNumFlushed = node.mContent->GetChildCount();
520
521 stackPos--;
522 }
523
524 mNotifyLevel = mStackPos - 1;
525 }
526
NS_NewHTMLContentSink(nsIHTMLContentSink ** aResult,Document * aDoc,nsIURI * aURI,nsISupports * aContainer,nsIChannel * aChannel)527 nsresult NS_NewHTMLContentSink(nsIHTMLContentSink** aResult, Document* aDoc,
528 nsIURI* aURI, nsISupports* aContainer,
529 nsIChannel* aChannel) {
530 NS_ENSURE_ARG_POINTER(aResult);
531
532 RefPtr<HTMLContentSink> it = new HTMLContentSink();
533
534 nsresult rv = it->Init(aDoc, aURI, aContainer, aChannel);
535
536 NS_ENSURE_SUCCESS(rv, rv);
537
538 *aResult = it;
539 NS_ADDREF(*aResult);
540
541 return NS_OK;
542 }
543
HTMLContentSink()544 HTMLContentSink::HTMLContentSink()
545 : mMaxTextRun(0),
546 mCurrentContext(nullptr),
547 mHeadContext(nullptr),
548 mHaveSeenHead(false),
549 mNotifiedRootInsertion(false) {}
550
~HTMLContentSink()551 HTMLContentSink::~HTMLContentSink() {
552 if (mNotificationTimer) {
553 mNotificationTimer->Cancel();
554 }
555
556 if (mCurrentContext == mHeadContext && !mContextStack.IsEmpty()) {
557 // Pop off the second html context if it's not done earlier
558 mContextStack.RemoveLastElement();
559 }
560
561 for (int32_t i = 0, numContexts = mContextStack.Length(); i < numContexts;
562 i++) {
563 SinkContext* sc = mContextStack.ElementAt(i);
564 if (sc) {
565 sc->End();
566 if (sc == mCurrentContext) {
567 mCurrentContext = nullptr;
568 }
569
570 delete sc;
571 }
572 }
573
574 if (mCurrentContext == mHeadContext) {
575 mCurrentContext = nullptr;
576 }
577
578 delete mCurrentContext;
579
580 delete mHeadContext;
581 }
582
NS_IMPL_CYCLE_COLLECTION_INHERITED(HTMLContentSink,nsContentSink,mHTMLDocument,mRoot,mBody,mHead)583 NS_IMPL_CYCLE_COLLECTION_INHERITED(HTMLContentSink, nsContentSink,
584 mHTMLDocument, mRoot, mBody, mHead)
585
586 NS_IMPL_ISUPPORTS_CYCLE_COLLECTION_INHERITED(HTMLContentSink, nsContentSink,
587 nsIContentSink, nsIHTMLContentSink)
588
589 nsresult HTMLContentSink::Init(Document* aDoc, nsIURI* aURI,
590 nsISupports* aContainer, nsIChannel* aChannel) {
591 NS_ENSURE_TRUE(aContainer, NS_ERROR_NULL_POINTER);
592
593 nsresult rv = nsContentSink::Init(aDoc, aURI, aContainer, aChannel);
594 if (NS_FAILED(rv)) {
595 return rv;
596 }
597
598 aDoc->AddObserver(this);
599 mIsDocumentObserver = true;
600 mHTMLDocument = aDoc->AsHTMLDocument();
601
602 NS_ASSERTION(mDocShell, "oops no docshell!");
603
604 // Changed from 8192 to greatly improve page loading performance on
605 // large pages. See bugzilla bug 77540.
606 mMaxTextRun = Preferences::GetInt("content.maxtextrun", 8191);
607
608 RefPtr<mozilla::dom::NodeInfo> nodeInfo;
609 nodeInfo = mNodeInfoManager->GetNodeInfo(
610 nsGkAtoms::html, nullptr, kNameSpaceID_XHTML, nsINode::ELEMENT_NODE);
611
612 // Make root part
613 mRoot = NS_NewHTMLHtmlElement(nodeInfo.forget());
614 if (!mRoot) {
615 return NS_ERROR_OUT_OF_MEMORY;
616 }
617
618 NS_ASSERTION(mDocument->GetChildCount() == 0,
619 "Document should have no kids here!");
620 ErrorResult error;
621 mDocument->AppendChildTo(mRoot, false, error);
622 if (error.Failed()) {
623 return error.StealNSResult();
624 }
625
626 // Make head part
627 nodeInfo = mNodeInfoManager->GetNodeInfo(
628 nsGkAtoms::head, nullptr, kNameSpaceID_XHTML, nsINode::ELEMENT_NODE);
629
630 mHead = NS_NewHTMLHeadElement(nodeInfo.forget());
631 if (NS_FAILED(rv)) {
632 return NS_ERROR_OUT_OF_MEMORY;
633 }
634
635 mRoot->AppendChildTo(mHead, false, IgnoreErrors());
636
637 mCurrentContext = new SinkContext(this);
638 mCurrentContext->Begin(eHTMLTag_html, mRoot, 0, -1);
639 mContextStack.AppendElement(mCurrentContext);
640
641 return NS_OK;
642 }
643
644 NS_IMETHODIMP
WillParse(void)645 HTMLContentSink::WillParse(void) { return WillParseImpl(); }
646
647 NS_IMETHODIMP
WillBuildModel(nsDTDMode aDTDMode)648 HTMLContentSink::WillBuildModel(nsDTDMode aDTDMode) {
649 WillBuildModelImpl();
650
651 nsCompatibility mode = eCompatibility_NavQuirks;
652 switch (aDTDMode) {
653 case eDTDMode_full_standards:
654 mode = eCompatibility_FullStandards;
655 break;
656 case eDTDMode_almost_standards:
657 mode = eCompatibility_AlmostStandards;
658 break;
659 default:
660 break;
661 }
662 mDocument->SetCompatibilityMode(mode);
663
664 // Notify document that the load is beginning
665 mDocument->BeginLoad();
666
667 return NS_OK;
668 }
669
670 NS_IMETHODIMP
DidBuildModel(bool aTerminated)671 HTMLContentSink::DidBuildModel(bool aTerminated) {
672 DidBuildModelImpl(aTerminated);
673
674 // Reflow the last batch of content
675 if (mBody) {
676 mCurrentContext->FlushTags();
677 } else if (!mLayoutStarted) {
678 // We never saw the body, and layout never got started. Force
679 // layout *now*, to get an initial reflow.
680 // NOTE: only force the layout if we are NOT destroying the
681 // docshell. If we are destroying it, then starting layout will
682 // likely cause us to crash, or at best waste a lot of time as we
683 // are just going to tear it down anyway.
684 bool bDestroying = true;
685 if (mDocShell) {
686 mDocShell->IsBeingDestroyed(&bDestroying);
687 }
688
689 if (!bDestroying) {
690 StartLayout(false);
691 }
692 }
693
694 ScrollToRef();
695
696 // Make sure we no longer respond to document mutations. We've flushed all
697 // our notifications out, so there's no need to do anything else here.
698
699 // XXXbz I wonder whether we could End() our contexts here too, or something,
700 // just to make sure we no longer notify... Or is the mIsDocumentObserver
701 // thing sufficient?
702 mDocument->RemoveObserver(this);
703 mIsDocumentObserver = false;
704
705 mDocument->EndLoad();
706
707 DropParserAndPerfHint();
708
709 return NS_OK;
710 }
711
712 NS_IMETHODIMP
SetParser(nsParserBase * aParser)713 HTMLContentSink::SetParser(nsParserBase* aParser) {
714 MOZ_ASSERT(aParser, "Should have a parser here!");
715 mParser = aParser;
716 return NS_OK;
717 }
718
CloseHTML()719 nsresult HTMLContentSink::CloseHTML() {
720 if (mHeadContext) {
721 if (mCurrentContext == mHeadContext) {
722 // Pop off the second html context if it's not done earlier
723 mCurrentContext = mContextStack.PopLastElement();
724 }
725
726 mHeadContext->End();
727
728 delete mHeadContext;
729 mHeadContext = nullptr;
730 }
731
732 return NS_OK;
733 }
734
OpenBody()735 nsresult HTMLContentSink::OpenBody() {
736 CloseHeadContext(); // do this just in case if the HEAD was left open!
737
738 // if we already have a body we're done
739 if (mBody) {
740 return NS_OK;
741 }
742
743 nsresult rv = mCurrentContext->OpenBody();
744
745 if (NS_FAILED(rv)) {
746 return rv;
747 }
748
749 mBody = mCurrentContext->mStack[mCurrentContext->mStackPos - 1].mContent;
750
751 if (mCurrentContext->mStackPos > 1) {
752 int32_t parentIndex = mCurrentContext->mStackPos - 2;
753 nsGenericHTMLElement* parent =
754 mCurrentContext->mStack[parentIndex].mContent;
755 int32_t numFlushed = mCurrentContext->mStack[parentIndex].mNumFlushed;
756 int32_t childCount = parent->GetChildCount();
757 NS_ASSERTION(numFlushed < childCount, "Already notified on the body?");
758
759 int32_t insertionPoint =
760 mCurrentContext->mStack[parentIndex].mInsertionPoint;
761
762 // XXX: I have yet to see a case where numFlushed is non-zero and
763 // insertionPoint is not -1, but this code will try to handle
764 // those cases too.
765
766 uint32_t oldUpdates = mUpdatesInNotification;
767 mUpdatesInNotification = 0;
768 if (insertionPoint != -1) {
769 NotifyInsert(parent, mBody);
770 } else {
771 NotifyAppend(parent, numFlushed);
772 }
773 mCurrentContext->mStack[parentIndex].mNumFlushed = childCount;
774 if (mUpdatesInNotification > 1) {
775 UpdateChildCounts();
776 }
777 mUpdatesInNotification = oldUpdates;
778 }
779
780 StartLayout(false);
781
782 return NS_OK;
783 }
784
CloseBody()785 nsresult HTMLContentSink::CloseBody() {
786 // Flush out anything that's left
787 mCurrentContext->FlushTags();
788 mCurrentContext->CloseBody();
789
790 return NS_OK;
791 }
792
793 NS_IMETHODIMP
OpenContainer(ElementType aElementType)794 HTMLContentSink::OpenContainer(ElementType aElementType) {
795 nsresult rv = NS_OK;
796
797 switch (aElementType) {
798 case eBody:
799 rv = OpenBody();
800 break;
801 case eHTML:
802 if (mRoot) {
803 // If we've already hit this code once, then we're done
804 if (!mNotifiedRootInsertion) {
805 NotifyRootInsertion();
806 }
807 }
808 break;
809 }
810
811 return rv;
812 }
813
814 NS_IMETHODIMP
CloseContainer(const ElementType aTag)815 HTMLContentSink::CloseContainer(const ElementType aTag) {
816 nsresult rv = NS_OK;
817
818 switch (aTag) {
819 case eBody:
820 rv = CloseBody();
821 break;
822 case eHTML:
823 rv = CloseHTML();
824 break;
825 }
826
827 return rv;
828 }
829
830 NS_IMETHODIMP
WillInterrupt()831 HTMLContentSink::WillInterrupt() { return WillInterruptImpl(); }
832
833 NS_IMETHODIMP
WillResume()834 HTMLContentSink::WillResume() { return WillResumeImpl(); }
835
CloseHeadContext()836 void HTMLContentSink::CloseHeadContext() {
837 if (mCurrentContext) {
838 if (!mCurrentContext->IsCurrentContainer(eHTMLTag_head)) return;
839
840 mCurrentContext->FlushTags();
841 }
842
843 if (!mContextStack.IsEmpty()) {
844 mCurrentContext = mContextStack.PopLastElement();
845 }
846 }
847
NotifyInsert(nsIContent * aContent,nsIContent * aChildContent)848 void HTMLContentSink::NotifyInsert(nsIContent* aContent,
849 nsIContent* aChildContent) {
850 mInNotification++;
851
852 {
853 // Scope so we call EndUpdate before we decrease mInNotification
854 // Note that aContent->OwnerDoc() may be different to mDocument already.
855 MOZ_AUTO_DOC_UPDATE(aContent ? aContent->OwnerDoc() : mDocument.get(),
856 true);
857 MutationObservers::NotifyContentInserted(NODE_FROM(aContent, mDocument),
858 aChildContent);
859 mLastNotificationTime = PR_Now();
860 }
861
862 mInNotification--;
863 }
864
NotifyRootInsertion()865 void HTMLContentSink::NotifyRootInsertion() {
866 MOZ_ASSERT(!mNotifiedRootInsertion, "Double-notifying on root?");
867 NS_ASSERTION(!mLayoutStarted,
868 "How did we start layout without notifying on root?");
869 // Now make sure to notify that we have now inserted our root. If
870 // there has been no initial reflow yet it'll be a no-op, but if
871 // there has been one we need this to get its frames constructed.
872 // Note that if mNotifiedRootInsertion is true we don't notify here,
873 // since that just means there are multiple <html> tags in the
874 // document; in those cases we just want to put all the attrs on one
875 // tag.
876 mNotifiedRootInsertion = true;
877 NotifyInsert(nullptr, mRoot);
878
879 // Now update the notification information in all our
880 // contexts, since we just inserted the root and notified on
881 // our whole tree
882 UpdateChildCounts();
883
884 nsContentUtils::AddScriptRunner(
885 new nsDocElementCreatedNotificationRunner(mDocument));
886 }
887
UpdateChildCounts()888 void HTMLContentSink::UpdateChildCounts() {
889 uint32_t numContexts = mContextStack.Length();
890 for (uint32_t i = 0; i < numContexts; i++) {
891 SinkContext* sc = mContextStack.ElementAt(i);
892
893 sc->UpdateChildCounts();
894 }
895
896 mCurrentContext->UpdateChildCounts();
897 }
898
FlushPendingNotifications(FlushType aType)899 void HTMLContentSink::FlushPendingNotifications(FlushType aType) {
900 // Only flush tags if we're not doing the notification ourselves
901 // (since we aren't reentrant)
902 if (!mInNotification) {
903 // Only flush if we're still a document observer (so that our child counts
904 // should be correct).
905 if (mIsDocumentObserver) {
906 if (aType >= FlushType::ContentAndNotify) {
907 FlushTags();
908 }
909 }
910 if (aType >= FlushType::EnsurePresShellInitAndFrames) {
911 // Make sure that layout has started so that the reflow flush
912 // will actually happen.
913 StartLayout(true);
914 }
915 }
916 }
917
FlushTags()918 nsresult HTMLContentSink::FlushTags() {
919 if (!mNotifiedRootInsertion) {
920 NotifyRootInsertion();
921 return NS_OK;
922 }
923
924 return mCurrentContext ? mCurrentContext->FlushTags() : NS_OK;
925 }
926
SetDocumentCharset(NotNull<const Encoding * > aEncoding)927 void HTMLContentSink::SetDocumentCharset(NotNull<const Encoding*> aEncoding) {
928 MOZ_ASSERT_UNREACHABLE("<meta charset> case doesn't occur with about:blank");
929 }
930
GetTarget()931 nsISupports* HTMLContentSink::GetTarget() { return ToSupports(mDocument); }
932
IsScriptExecuting()933 bool HTMLContentSink::IsScriptExecuting() { return IsScriptExecutingImpl(); }
934
ContinueInterruptedParsingIfEnabled()935 void HTMLContentSink::ContinueInterruptedParsingIfEnabled() {
936 if (mParser && mParser->IsParserEnabled()) {
937 static_cast<nsIParser*>(mParser.get())->ContinueInterruptedParsing();
938 }
939 }
940
ContinueInterruptedParsingAsync()941 void HTMLContentSink::ContinueInterruptedParsingAsync() {
942 nsCOMPtr<nsIRunnable> ev = NewRunnableMethod(
943 "HTMLContentSink::ContinueInterruptedParsingIfEnabled", this,
944 &HTMLContentSink::ContinueInterruptedParsingIfEnabled);
945
946 RefPtr<Document> doc = mHTMLDocument;
947 doc->Dispatch(mozilla::TaskCategory::Other, ev.forget());
948 }
949