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