Bug 1717887 Part 2: Make RenderThread backed by nsIThread, with a hang monitor. r...
[gecko.git] / layout / base / nsDocumentViewer.cpp
blob23616d66288c221b8d7744d8867a4d3962ea2246
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/. */
7 /* container for a document and its presentation */
9 #include "gfxContext.h"
10 #include "mozilla/PresShell.h"
11 #include "mozilla/RestyleManager.h"
12 #include "mozilla/ServoStyleSet.h"
13 #include "mozilla/StaticPrefs_print.h"
14 #include "mozilla/Telemetry.h"
15 #include "nsThreadUtils.h"
16 #include "nscore.h"
17 #include "nsCOMPtr.h"
18 #include "nsCRT.h"
19 #include "nsFrameSelection.h"
20 #include "nsString.h"
21 #include "nsReadableUtils.h"
22 #include "nsIContent.h"
23 #include "nsIContentViewer.h"
24 #include "nsIDocumentViewerPrint.h"
25 #include "nsIScreen.h"
26 #include "mozilla/dom/AutoSuppressEventHandlingAndSuspend.h"
27 #include "mozilla/dom/BrowsingContext.h"
28 #include "mozilla/dom/BeforeUnloadEvent.h"
29 #include "mozilla/dom/PopupBlocker.h"
30 #include "mozilla/dom/Document.h"
31 #include "mozilla/dom/DocumentInlines.h"
32 #include "mozilla/dom/DocGroup.h"
33 #include "nsPresContext.h"
34 #include "nsIFrame.h"
35 #include "nsIWritablePropertyBag2.h"
36 #include "nsSubDocumentFrame.h"
37 #include "nsGenericHTMLElement.h"
38 #include "nsStubMutationObserver.h"
40 #include "nsISelectionListener.h"
41 #include "mozilla/dom/Selection.h"
42 #include "nsContentUtils.h"
43 #ifdef ACCESSIBILITY
44 # include "mozilla/a11y/DocAccessible.h"
45 #endif
46 #include "mozilla/BasicEvents.h"
47 #include "mozilla/Encoding.h"
48 #include "mozilla/ErrorResult.h"
49 #include "mozilla/Preferences.h"
50 #include "mozilla/SpinEventLoopUntil.h"
51 #include "mozilla/WeakPtr.h"
52 #include "mozilla/StaticPrefs_dom.h"
53 #include "mozilla/StaticPrefs_javascript.h"
54 #include "mozilla/StaticPrefs_fission.h"
55 #include "mozilla/StaticPrefs_print.h"
56 #include "mozilla/StyleSheet.h"
57 #include "mozilla/StyleSheetInlines.h"
59 #include "nsViewManager.h"
60 #include "nsView.h"
62 #include "nsPageSequenceFrame.h"
63 #include "nsNetUtil.h"
64 #include "nsIContentViewerEdit.h"
65 #include "mozilla/css/Loader.h"
66 #include "nsIInterfaceRequestor.h"
67 #include "nsIInterfaceRequestorUtils.h"
68 #include "nsDocShell.h"
69 #include "nsIBaseWindow.h"
70 #include "nsILayoutHistoryState.h"
71 #include "nsIScreen.h"
72 #include "nsCharsetSource.h"
73 #include "mozilla/ReflowInput.h"
74 #include "nsIImageLoadingContent.h"
75 #include "nsCopySupport.h"
76 #ifdef MOZ_XUL
77 # include "nsXULPopupManager.h"
78 #endif
80 #include "nsIClipboardHelper.h"
82 #include "nsPIDOMWindow.h"
83 #include "nsGlobalWindow.h"
84 #include "nsDOMNavigationTiming.h"
85 #include "nsPIWindowRoot.h"
86 #include "nsJSEnvironment.h"
87 #include "nsFocusManager.h"
89 #include "nsIScrollableFrame.h"
90 #include "nsStyleSheetService.h"
91 #include "nsILoadContext.h"
92 #include "mozilla/ThrottledEventQueue.h"
93 #include "nsIPromptCollection.h"
94 #include "nsIPromptService.h"
95 #include "imgIContainer.h" // image animation mode constants
96 #include "nsIXULRuntime.h"
97 #include "nsSandboxFlags.h"
99 #include "mozilla/DocLoadingTimelineMarker.h"
101 //--------------------------
102 // Printing Include
103 //---------------------------
104 #ifdef NS_PRINTING
106 # include "nsIWebBrowserPrint.h"
108 # include "nsPrintJob.h"
109 # include "nsDeviceContextSpecProxy.h"
111 // Print Options
112 # include "nsIPrintSettings.h"
113 # include "nsIPrintSettingsService.h"
114 # include "nsISimpleEnumerator.h"
116 #endif // NS_PRINTING
118 // focus
119 #include "nsIDOMEventListener.h"
120 #include "nsISelectionController.h"
122 #include "mozilla/EventDispatcher.h"
123 #include "nsISHEntry.h"
124 #include "nsISHistory.h"
125 #include "nsIWebNavigation.h"
126 #include "mozilla/dom/XMLHttpRequestMainThread.h"
128 // paint forcing
129 #include <stdio.h>
130 #include "mozilla/BasePrincipal.h"
131 #include "mozilla/dom/Element.h"
132 #include "mozilla/dom/Event.h"
133 #include "mozilla/Telemetry.h"
134 #include "mozilla/dom/ScriptLoader.h"
135 #include "mozilla/dom/WindowGlobalChild.h"
137 namespace mozilla {
138 namespace dom {
139 class PrintPreviewResultInfo;
140 } // namespace dom
141 } // namespace mozilla
143 using namespace mozilla;
144 using namespace mozilla::dom;
146 using PrintPreviewResolver =
147 std::function<void(const mozilla::dom::PrintPreviewResultInfo&)>;
149 //-----------------------------------------------------
150 // LOGGING
151 #include "LayoutLogging.h"
152 #include "mozilla/Logging.h"
154 extern mozilla::LazyLogModule gPageCacheLog;
156 #ifdef NS_PRINTING
157 mozilla::LazyLogModule gPrintingLog("printing");
159 # define PR_PL(_p1) MOZ_LOG(gPrintingLog, mozilla::LogLevel::Debug, _p1);
160 #endif // NS_PRINTING
162 #define PRT_YESNO(_p) ((_p) ? "YES" : "NO")
163 //-----------------------------------------------------
165 class nsDocumentViewer;
167 // a small delegate class used to avoid circular references
169 class nsDocViewerSelectionListener final : public nsISelectionListener {
170 public:
171 // nsISupports interface...
172 NS_DECL_ISUPPORTS
174 // nsISelectionListerner interface
175 NS_DECL_NSISELECTIONLISTENER
177 explicit nsDocViewerSelectionListener(nsDocumentViewer* aDocViewer)
178 : mDocViewer(aDocViewer), mSelectionWasCollapsed(true) {}
180 void Disconnect() { mDocViewer = nullptr; }
182 protected:
183 virtual ~nsDocViewerSelectionListener() = default;
185 nsDocumentViewer* mDocViewer;
186 bool mSelectionWasCollapsed;
189 /** editor Implementation of the FocusListener interface */
190 class nsDocViewerFocusListener final : public nsIDOMEventListener {
191 public:
192 explicit nsDocViewerFocusListener(nsDocumentViewer* aDocViewer)
193 : mDocViewer(aDocViewer) {}
195 NS_DECL_ISUPPORTS
196 NS_DECL_NSIDOMEVENTLISTENER
198 void Disconnect() { mDocViewer = nullptr; }
200 protected:
201 virtual ~nsDocViewerFocusListener() = default;
203 nsDocumentViewer* mDocViewer;
206 namespace viewer_detail {
209 * Mutation observer for use until we hand ourselves over to our SHEntry.
211 class BFCachePreventionObserver final : public nsStubMutationObserver {
212 public:
213 explicit BFCachePreventionObserver(Document* aDocument)
214 : mDocument(aDocument) {}
216 NS_DECL_ISUPPORTS
218 NS_DECL_NSIMUTATIONOBSERVER_CHARACTERDATACHANGED
219 NS_DECL_NSIMUTATIONOBSERVER_ATTRIBUTECHANGED
220 NS_DECL_NSIMUTATIONOBSERVER_CONTENTAPPENDED
221 NS_DECL_NSIMUTATIONOBSERVER_CONTENTINSERTED
222 NS_DECL_NSIMUTATIONOBSERVER_CONTENTREMOVED
223 NS_DECL_NSIMUTATIONOBSERVER_NODEWILLBEDESTROYED
225 // Stop observing the document.
226 void Disconnect();
228 private:
229 ~BFCachePreventionObserver() = default;
231 // Helper for the work that needs to happen when mutations happen.
232 void MutationHappened();
234 Document* mDocument; // Weak; we get notified if it dies
237 NS_IMPL_ISUPPORTS(BFCachePreventionObserver, nsIMutationObserver)
239 void BFCachePreventionObserver::CharacterDataChanged(
240 nsIContent* aContent, const CharacterDataChangeInfo&) {
241 if (aContent->IsInNativeAnonymousSubtree()) {
242 return;
244 MutationHappened();
247 void BFCachePreventionObserver::AttributeChanged(Element* aElement,
248 int32_t aNameSpaceID,
249 nsAtom* aAttribute,
250 int32_t aModType,
251 const nsAttrValue* aOldValue) {
252 if (aElement->IsInNativeAnonymousSubtree()) {
253 return;
255 MutationHappened();
258 void BFCachePreventionObserver::ContentAppended(nsIContent* aFirstNewContent) {
259 if (aFirstNewContent->IsInNativeAnonymousSubtree()) {
260 return;
262 MutationHappened();
265 void BFCachePreventionObserver::ContentInserted(nsIContent* aChild) {
266 if (aChild->IsInNativeAnonymousSubtree()) {
267 return;
269 MutationHappened();
272 void BFCachePreventionObserver::ContentRemoved(nsIContent* aChild,
273 nsIContent* aPreviousSibling) {
274 if (aChild->IsInNativeAnonymousSubtree()) {
275 return;
277 MutationHappened();
280 void BFCachePreventionObserver::NodeWillBeDestroyed(const nsINode* aNode) {
281 mDocument = nullptr;
284 void BFCachePreventionObserver::Disconnect() {
285 if (mDocument) {
286 mDocument->RemoveMutationObserver(this);
287 // It will no longer tell us when it goes away, so make sure we're
288 // not holding a dangling ref.
289 mDocument = nullptr;
293 void BFCachePreventionObserver::MutationHappened() {
294 MOZ_ASSERT(
295 mDocument,
296 "How can we not have a document but be getting notified for mutations?");
297 mDocument->DisallowBFCaching();
298 Disconnect();
301 } // namespace viewer_detail
303 using viewer_detail::BFCachePreventionObserver;
305 //-------------------------------------------------------------
306 class nsDocumentViewer final : public nsIContentViewer,
307 public nsIContentViewerEdit,
308 public nsIDocumentViewerPrint
309 #ifdef NS_PRINTING
311 public nsIWebBrowserPrint
312 #endif
315 friend class nsDocViewerSelectionListener;
316 friend class nsPagePrintTimer;
317 friend class nsPrintJob;
319 public:
320 nsDocumentViewer();
322 // nsISupports interface...
323 NS_DECL_ISUPPORTS
325 // nsIContentViewer interface...
326 NS_DECL_NSICONTENTVIEWER
328 // nsIContentViewerEdit
329 NS_DECL_NSICONTENTVIEWEREDIT
331 #ifdef NS_PRINTING
332 // nsIWebBrowserPrint
333 NS_DECL_NSIWEBBROWSERPRINT
334 #endif
336 // nsIDocumentViewerPrint Printing Methods
337 NS_DECL_NSIDOCUMENTVIEWERPRINT
339 protected:
340 virtual ~nsDocumentViewer();
342 private:
344 * Creates a view manager, root view, and widget for the root view, setting
345 * mViewManager and mWindow.
346 * @param aSize the initial size in appunits
347 * @param aContainerView the container view to hook our root view up
348 * to as a child, or null if this will be the root view manager
350 nsresult MakeWindow(const nsSize& aSize, nsView* aContainerView);
353 * Create our device context
355 nsresult CreateDeviceContext(nsView* aContainerView);
358 * If aDoCreation is true, this creates the device context, creates a
359 * prescontext if necessary, and calls MakeWindow.
361 * If aForceSetNewDocument is false, then SetNewDocument won't be
362 * called if the window's current document is already mDocument.
364 nsresult InitInternal(nsIWidget* aParentWidget, nsISupports* aState,
365 mozilla::dom::WindowGlobalChild* aActor,
366 const nsIntRect& aBounds, bool aDoCreation,
367 bool aNeedMakeCX = true,
368 bool aForceSetNewDocument = true);
370 * @param aDoInitialReflow set to true if you want to kick off the initial
371 * reflow
373 MOZ_CAN_RUN_SCRIPT_BOUNDARY
374 nsresult InitPresentationStuff(bool aDoInitialReflow);
376 already_AddRefed<nsINode> GetPopupNode();
377 already_AddRefed<nsINode> GetPopupLinkNode();
378 already_AddRefed<nsIImageLoadingContent> GetPopupImageNode();
380 MOZ_CAN_RUN_SCRIPT_BOUNDARY
381 nsresult GetContentSizeInternal(int32_t* aWidth, int32_t* aHeight,
382 nscoord aMaxWidth, nscoord aMaxHeight);
384 void PrepareToStartLoad(void);
386 nsresult SyncParentSubDocMap();
388 void RemoveFocusListener();
389 void ReinitializeFocusListener();
391 mozilla::dom::Selection* GetDocumentSelection();
393 void DestroyPresShell();
394 void DestroyPresContext();
396 void InvalidatePotentialSubDocDisplayItem();
398 // Whether we should attach to the top level widget. This is true if we
399 // are sharing/recycling a single base widget and not creating multiple
400 // child widgets.
401 bool ShouldAttachToTopLevel();
403 nsresult PrintPreviewScrollToPageForOldUI(int16_t aType, int32_t aPageNum);
405 std::tuple<const nsIFrame*, int32_t> GetCurrentSheetFrameAndNumber() const;
407 protected:
408 // Returns the current viewmanager. Might be null.
409 nsViewManager* GetViewManager();
411 void DetachFromTopLevelWidget();
413 // IMPORTANT: The ownership implicit in the following member
414 // variables has been explicitly checked and set using nsCOMPtr
415 // for owning pointers and raw COM interface pointers for weak
416 // (ie, non owning) references. If you add any members to this
417 // class, please make the ownership explicit (pinkerton, scc).
419 WeakPtr<nsDocShell> mContainer; // it owns me!
420 RefPtr<nsDeviceContext> mDeviceContext; // We create and own this baby
422 // the following six items are explicitly in this order
423 // so they will be destroyed in the reverse order (pinkerton, scc)
424 nsCOMPtr<Document> mDocument;
425 nsCOMPtr<nsIWidget> mWindow; // may be null
426 RefPtr<nsViewManager> mViewManager;
427 RefPtr<nsPresContext> mPresContext;
428 RefPtr<PresShell> mPresShell;
430 RefPtr<nsDocViewerSelectionListener> mSelectionListener;
431 RefPtr<nsDocViewerFocusListener> mFocusListener;
433 nsCOMPtr<nsIContentViewer> mPreviousViewer;
434 nsCOMPtr<nsISHEntry> mSHEntry;
435 // Observer that will prevent bfcaching if it gets notified. This
436 // is non-null precisely when mSHEntry is non-null.
437 RefPtr<BFCachePreventionObserver> mBFCachePreventionObserver;
439 nsIWidget* mParentWidget; // purposely won't be ref counted. May be null
440 bool mAttachedToParent; // view is attached to the parent widget
442 nsIntRect mBounds;
444 int16_t mNumURLStarts;
445 int16_t mDestroyBlockedCount;
447 unsigned mStopped : 1;
448 unsigned mLoaded : 1;
449 unsigned mDeferredWindowClose : 1;
450 // document management data
451 // these items are specific to markup documents (html and xml)
452 // may consider splitting these out into a subclass
453 unsigned mIsSticky : 1;
454 unsigned mInPermitUnload : 1;
455 unsigned mInPermitUnloadPrompt : 1;
457 #ifdef NS_PRINTING
458 unsigned mClosingWhilePrinting : 1;
460 # if NS_PRINT_PREVIEW
461 RefPtr<nsPrintJob> mPrintJob;
462 # endif // NS_PRINT_PREVIEW
464 #endif // NS_PRINTING
466 /* character set member data */
467 int32_t mReloadEncodingSource;
468 const Encoding* mReloadEncoding;
470 bool mIsPageMode;
471 bool mInitializedForPrintPreview;
472 bool mHidden;
475 class nsDocumentShownDispatcher : public Runnable {
476 public:
477 explicit nsDocumentShownDispatcher(nsCOMPtr<Document> aDocument)
478 : Runnable("nsDocumentShownDispatcher"), mDocument(aDocument) {}
480 NS_IMETHOD Run() override;
482 private:
483 nsCOMPtr<Document> mDocument;
486 //------------------------------------------------------------------
487 // nsDocumentViewer
488 //------------------------------------------------------------------
490 //------------------------------------------------------------------
491 already_AddRefed<nsIContentViewer> NS_NewContentViewer() {
492 RefPtr<nsDocumentViewer> viewer = new nsDocumentViewer();
493 return viewer.forget();
496 void nsDocumentViewer::PrepareToStartLoad() {
497 MOZ_DIAGNOSTIC_ASSERT(!GetIsPrintPreview(),
498 "Print preview tab should never navigate");
500 mStopped = false;
501 mLoaded = false;
502 mAttachedToParent = false;
503 mDeferredWindowClose = false;
505 #ifdef NS_PRINTING
506 mClosingWhilePrinting = false;
508 // Make sure we have destroyed it and cleared the data member
509 if (mPrintJob) {
510 mPrintJob->Destroy();
511 mPrintJob = nullptr;
514 #endif // NS_PRINTING
517 nsDocumentViewer::nsDocumentViewer()
518 : mParentWidget(nullptr),
519 mAttachedToParent(false),
520 mNumURLStarts(0),
521 mDestroyBlockedCount(0),
522 mStopped(false),
523 mLoaded(false),
524 mDeferredWindowClose(false),
525 mIsSticky(true),
526 mInPermitUnload(false),
527 mInPermitUnloadPrompt(false),
528 #ifdef NS_PRINTING
529 mClosingWhilePrinting(false),
530 #endif // NS_PRINTING
531 mReloadEncodingSource(kCharsetUninitialized),
532 mReloadEncoding(nullptr),
533 mIsPageMode(false),
534 mInitializedForPrintPreview(false),
535 mHidden(false) {
536 PrepareToStartLoad();
539 NS_IMPL_ADDREF(nsDocumentViewer)
540 NS_IMPL_RELEASE(nsDocumentViewer)
542 NS_INTERFACE_MAP_BEGIN(nsDocumentViewer)
543 NS_INTERFACE_MAP_ENTRY(nsIContentViewer)
544 NS_INTERFACE_MAP_ENTRY(nsIContentViewerEdit)
545 NS_INTERFACE_MAP_ENTRY(nsIDocumentViewerPrint)
546 NS_INTERFACE_MAP_ENTRY_AMBIGUOUS(nsISupports, nsIContentViewer)
547 #ifdef NS_PRINTING
548 NS_INTERFACE_MAP_ENTRY(nsIWebBrowserPrint)
549 #endif
550 NS_INTERFACE_MAP_END
552 nsDocumentViewer::~nsDocumentViewer() {
553 if (mDocument) {
554 Close(nullptr);
555 mDocument->Destroy();
558 #ifdef NS_PRINTING
559 if (mPrintJob) {
560 mPrintJob->Destroy();
561 mPrintJob = nullptr;
563 #endif
565 MOZ_RELEASE_ASSERT(mDestroyBlockedCount == 0);
566 NS_ASSERTION(!mPresShell && !mPresContext,
567 "User did not call nsIContentViewer::Destroy");
568 if (mPresShell || mPresContext) {
569 // Make sure we don't hand out a reference to the content viewer to
570 // the SHEntry!
571 mSHEntry = nullptr;
573 Destroy();
576 if (mSelectionListener) {
577 mSelectionListener->Disconnect();
580 RemoveFocusListener();
582 // XXX(?) Revoke pending invalidate events
586 * This method is called by the Document Loader once a document has
587 * been created for a particular data stream... The content viewer
588 * must cache this document for later use when Init(...) is called.
590 * This method is also called when an out of band document.write() happens.
591 * In that case, the document passed in is the same as the previous document.
593 /* virtual */
594 void nsDocumentViewer::LoadStart(Document* aDocument) {
595 MOZ_ASSERT(aDocument);
597 if (!mDocument) {
598 mDocument = aDocument;
602 void nsDocumentViewer::RemoveFocusListener() {
603 if (RefPtr<nsDocViewerFocusListener> oldListener =
604 std::move(mFocusListener)) {
605 oldListener->Disconnect();
606 if (mDocument) {
607 mDocument->RemoveEventListener(u"focus"_ns, oldListener, false);
608 mDocument->RemoveEventListener(u"blur"_ns, oldListener, false);
613 void nsDocumentViewer::ReinitializeFocusListener() {
614 RemoveFocusListener();
615 mFocusListener = new nsDocViewerFocusListener(this);
616 if (mDocument) {
617 mDocument->AddEventListener(u"focus"_ns, mFocusListener, false, false);
618 mDocument->AddEventListener(u"blur"_ns, mFocusListener, false, false);
622 nsresult nsDocumentViewer::SyncParentSubDocMap() {
623 nsCOMPtr<nsIDocShell> docShell(mContainer);
624 if (!docShell) {
625 return NS_OK;
628 nsCOMPtr<nsPIDOMWindowOuter> pwin(docShell->GetWindow());
629 if (!mDocument || !pwin) {
630 return NS_OK;
633 nsCOMPtr<Element> element = pwin->GetFrameElementInternal();
634 if (!element) {
635 return NS_OK;
638 nsCOMPtr<nsIDocShellTreeItem> parent;
639 docShell->GetInProcessParent(getter_AddRefs(parent));
641 nsCOMPtr<nsPIDOMWindowOuter> parent_win =
642 parent ? parent->GetWindow() : nullptr;
643 if (!parent_win) {
644 return NS_OK;
647 nsCOMPtr<Document> parent_doc = parent_win->GetDoc();
648 if (!parent_doc) {
649 return NS_OK;
652 if (mDocument && parent_doc->GetSubDocumentFor(element) != mDocument &&
653 parent_doc->EventHandlingSuppressed()) {
654 mDocument->SuppressEventHandling(parent_doc->EventHandlingSuppressed());
656 return parent_doc->SetSubDocumentFor(element, mDocument);
659 NS_IMETHODIMP
660 nsDocumentViewer::SetContainer(nsIDocShell* aContainer) {
661 mContainer = static_cast<nsDocShell*>(aContainer);
663 // We're loading a new document into the window where this document
664 // viewer lives, sync the parent document's frame element -> sub
665 // document map
667 return SyncParentSubDocMap();
670 NS_IMETHODIMP
671 nsDocumentViewer::GetContainer(nsIDocShell** aResult) {
672 NS_ENSURE_ARG_POINTER(aResult);
674 nsCOMPtr<nsIDocShell> container(mContainer);
675 container.swap(*aResult);
676 return NS_OK;
679 NS_IMETHODIMP
680 nsDocumentViewer::Init(nsIWidget* aParentWidget, const nsIntRect& aBounds,
681 WindowGlobalChild* aActor) {
682 return InitInternal(aParentWidget, nullptr, aActor, aBounds, true);
685 nsresult nsDocumentViewer::InitPresentationStuff(bool aDoInitialReflow) {
686 // We assert this because initializing the pres shell could otherwise cause
687 // re-entrancy into nsDocumentViewer methods, which might cause a different
688 // pres shell to be created. Callers of InitPresentationStuff should ensure
689 // the call is appropriately bounded by an nsAutoScriptBlocker to decide
690 // when it is safe for these re-entrant calls to be made.
691 MOZ_ASSERT(!nsContentUtils::IsSafeToRunScript(),
692 "InitPresentationStuff must only be called when scripts are "
693 "blocked");
695 #ifdef NS_PRINTING
696 // When getting printed, either for print or print preview, the print job
697 // takes care of setting up the presentation of the document.
698 if (mPrintJob) {
699 return NS_OK;
701 #endif
703 NS_ASSERTION(!mPresShell, "Someone should have destroyed the presshell!");
705 // Now make the shell for the document
706 mPresShell = mDocument->CreatePresShell(mPresContext, mViewManager);
707 if (!mPresShell) {
708 return NS_ERROR_FAILURE;
711 if (aDoInitialReflow) {
712 // Since Initialize() will create frames for *all* items
713 // that are currently in the document tree, we need to flush
714 // any pending notifications to prevent the content sink from
715 // duplicating layout frames for content it has added to the tree
716 // but hasn't notified the document about. (Bug 154018)
718 // Note that we are flushing before we add mPresShell as an observer
719 // to avoid bogus notifications.
720 mDocument->FlushPendingNotifications(FlushType::ContentAndNotify);
723 mPresShell->BeginObservingDocument();
725 // Initialize our view manager
728 int32_t p2a = mPresContext->AppUnitsPerDevPixel();
729 MOZ_ASSERT(
730 p2a ==
731 mPresContext->DeviceContext()->AppUnitsPerDevPixelAtUnitFullZoom());
733 nscoord width = p2a * mBounds.width;
734 nscoord height = p2a * mBounds.height;
736 mViewManager->SetWindowDimensions(width, height);
737 mPresContext->SetVisibleArea(nsRect(0, 0, width, height));
738 // We rely on the default zoom not being initialized until here.
739 mPresContext->RecomputeBrowsingContextDependentData();
742 if (mWindow && mDocument->IsTopLevelContentDocument()) {
743 // Set initial safe area insets
744 ScreenIntMargin windowSafeAreaInsets;
745 LayoutDeviceIntRect windowRect = mWindow->GetScreenBounds();
746 nsCOMPtr<nsIScreen> screen = mWindow->GetWidgetScreen();
747 if (screen) {
748 windowSafeAreaInsets = nsContentUtils::GetWindowSafeAreaInsets(
749 screen, mWindow->GetSafeAreaInsets(), windowRect);
752 mPresContext->SetSafeAreaInsets(windowSafeAreaInsets);
755 if (aDoInitialReflow) {
756 RefPtr<PresShell> presShell = mPresShell;
757 // Initial reflow
758 presShell->Initialize();
761 // now register ourselves as a selection listener, so that we get
762 // called when the selection changes in the window
763 if (!mSelectionListener) {
764 mSelectionListener = new nsDocViewerSelectionListener(this);
767 RefPtr<mozilla::dom::Selection> selection = GetDocumentSelection();
768 if (!selection) {
769 return NS_ERROR_FAILURE;
772 selection->AddSelectionListener(mSelectionListener);
774 ReinitializeFocusListener();
776 if (aDoInitialReflow && mDocument) {
777 nsCOMPtr<Document> document = mDocument;
778 document->ScrollToRef();
781 return NS_OK;
784 static nsPresContext* CreatePresContext(Document* aDocument,
785 nsPresContext::nsPresContextType aType,
786 nsView* aContainerView) {
787 if (aContainerView) {
788 return new nsPresContext(aDocument, aType);
790 return new nsRootPresContext(aDocument, aType);
793 //-----------------------------------------------
794 // This method can be used to initial the "presentation"
795 // The aDoCreation indicates whether it should create
796 // all the new objects or just initialize the existing ones
797 nsresult nsDocumentViewer::InitInternal(
798 nsIWidget* aParentWidget, nsISupports* aState, WindowGlobalChild* aActor,
799 const nsIntRect& aBounds, bool aDoCreation, bool aNeedMakeCX /*= true*/,
800 bool aForceSetNewDocument /* = true*/) {
801 // We don't want any scripts to run here. That can cause flushing,
802 // which can cause reentry into initialization of this document viewer,
803 // which would be disastrous.
804 nsAutoScriptBlocker blockScripts;
806 mParentWidget = aParentWidget; // not ref counted
807 mBounds = aBounds;
809 nsresult rv = NS_OK;
810 NS_ENSURE_TRUE(mDocument, NS_ERROR_NULL_POINTER);
812 nsView* containerView = FindContainerView();
814 bool makeCX = false;
815 if (aDoCreation) {
816 nsresult rv = CreateDeviceContext(containerView);
817 NS_ENSURE_SUCCESS(rv, rv);
819 // XXXbz this is a nasty hack to do with the fact that we create
820 // presentations both in Init() and in Show()... Ideally we would only do
821 // it in one place (Show()) and require that callers call init(), open(),
822 // show() in that order or something.
823 if (!mPresContext &&
824 (aParentWidget || containerView || mDocument->IsBeingUsedAsImage() ||
825 (mDocument->GetDisplayDocument() &&
826 mDocument->GetDisplayDocument()->GetPresShell()))) {
827 // Create presentation context
828 if (mIsPageMode) {
829 // Presentation context already created in SetPageModeForTesting which
830 // is calling this method
831 } else {
832 mPresContext = CreatePresContext(
833 mDocument, nsPresContext::eContext_Galley, containerView);
835 NS_ENSURE_TRUE(mPresContext, NS_ERROR_OUT_OF_MEMORY);
837 nsresult rv = mPresContext->Init(mDeviceContext);
838 if (NS_FAILED(rv)) {
839 mPresContext = nullptr;
840 return rv;
843 #if defined(NS_PRINTING) && defined(NS_PRINT_PREVIEW)
844 makeCX = !GetIsPrintPreview() &&
845 aNeedMakeCX; // needs to be true except when we are already in
846 // PP or we are enabling/disabling paginated mode.
847 #else
848 makeCX = true;
849 #endif
852 if (mPresContext) {
853 // Create the ViewManager and Root View...
855 // We must do this before we tell the script global object about
856 // this new document since doing that will cause us to re-enter
857 // into nsSubDocumentFrame code through reflows caused by
858 // FlushPendingNotifications() calls down the road...
860 rv = MakeWindow(nsSize(mPresContext->DevPixelsToAppUnits(aBounds.width),
861 mPresContext->DevPixelsToAppUnits(aBounds.height)),
862 containerView);
863 NS_ENSURE_SUCCESS(rv, rv);
864 Hide();
866 #ifdef NS_PRINT_PREVIEW
867 if (mIsPageMode) {
868 // I'm leaving this in a broken state for the moment; we should
869 // be measuring/scaling with the print device context, not the
870 // screen device context, but this is good enough to allow
871 // printing reftests to work.
872 double pageWidth = 0, pageHeight = 0;
873 mPresContext->GetPrintSettings()->GetEffectivePageSize(&pageWidth,
874 &pageHeight);
875 mPresContext->SetPageSize(
876 nsSize(mPresContext->CSSTwipsToAppUnits(NSToIntFloor(pageWidth)),
877 mPresContext->CSSTwipsToAppUnits(NSToIntFloor(pageHeight))));
878 mPresContext->SetIsRootPaginatedDocument(true);
879 mPresContext->SetPageScale(1.0f);
881 #endif
882 } else {
883 // Avoid leaking the old viewer.
884 if (mPreviousViewer) {
885 mPreviousViewer->Destroy();
886 mPreviousViewer = nullptr;
891 nsCOMPtr<nsIInterfaceRequestor> requestor(mContainer);
892 if (requestor) {
893 // Set script-context-owner in the document
895 nsCOMPtr<nsPIDOMWindowOuter> window = do_GetInterface(requestor);
897 if (window) {
898 nsCOMPtr<Document> curDoc = window->GetExtantDoc();
899 if (aForceSetNewDocument || curDoc != mDocument) {
900 rv = window->SetNewDocument(mDocument, aState, false, aActor);
901 if (NS_FAILED(rv)) {
902 Destroy();
903 return rv;
909 if (aDoCreation && mPresContext) {
910 // The ViewManager and Root View was created above (in
911 // MakeWindow())...
913 rv = InitPresentationStuff(!makeCX);
916 return rv;
919 void nsDocumentViewer::SetNavigationTiming(nsDOMNavigationTiming* timing) {
920 NS_ASSERTION(mDocument, "Must have a document to set navigation timing.");
921 if (mDocument) {
922 mDocument->SetNavigationTiming(timing);
927 // LoadComplete(aStatus)
929 // aStatus - The status returned from loading the document.
931 // This method is called by the container when the document has been
932 // completely loaded.
934 NS_IMETHODIMP
935 nsDocumentViewer::LoadComplete(nsresult aStatus) {
936 /* We need to protect ourself against auto-destruction in case the
937 window is closed while processing the OnLoad event. See bug
938 http://bugzilla.mozilla.org/show_bug.cgi?id=78445 for more
939 explanation.
941 RefPtr<nsDocumentViewer> kungFuDeathGrip(this);
943 // Flush out layout so it's up-to-date by the time onload is called.
944 // Note that this could destroy the window, so do this before
945 // checking for our mDocument and its window.
946 if (mPresShell && !mStopped) {
947 // Hold strong ref because this could conceivably run script
948 RefPtr<PresShell> presShell = mPresShell;
949 presShell->FlushPendingNotifications(FlushType::Layout);
952 nsresult rv = NS_OK;
953 NS_ENSURE_TRUE(mDocument, NS_ERROR_NOT_AVAILABLE);
955 // First, get the window from the document...
956 nsCOMPtr<nsPIDOMWindowOuter> window = mDocument->GetWindow();
958 mLoaded = true;
960 // Now, fire either an OnLoad or OnError event to the document...
961 bool restoring = false;
962 // XXXbz imagelib kills off the document load for a full-page image with
963 // NS_ERROR_PARSED_DATA_CACHED if it's in the cache. So we want to treat
964 // that one as a success code; otherwise whether we fire onload for the image
965 // will depend on whether it's cached!
966 if (window &&
967 (NS_SUCCEEDED(aStatus) || aStatus == NS_ERROR_PARSED_DATA_CACHED)) {
968 // If this code changes, the code in nsDocLoader::DocLoaderIsEmpty
969 // that fires load events for document.open() cases might need to
970 // be updated too.
971 nsEventStatus status = nsEventStatus_eIgnore;
972 WidgetEvent event(true, eLoad);
973 event.mFlags.mBubbles = false;
974 event.mFlags.mCancelable = false;
975 // XXX Dispatching to |window|, but using |document| as the target.
976 event.mTarget = mDocument;
978 // If the document presentation is being restored, we don't want to fire
979 // onload to the document content since that would likely confuse scripts
980 // on the page.
982 nsIDocShell* docShell = window->GetDocShell();
983 NS_ENSURE_TRUE(docShell, NS_ERROR_UNEXPECTED);
985 // Unfortunately, docShell->GetRestoringDocument() might no longer be set
986 // correctly. In particular, it can be false by now if someone took it upon
987 // themselves to block onload from inside restoration and unblock it later.
988 // But we can detect the restoring case very simply: by whether our
989 // document's readyState is COMPLETE.
990 restoring =
991 (mDocument->GetReadyStateEnum() == Document::READYSTATE_COMPLETE);
992 if (!restoring) {
993 NS_ASSERTION(
994 mDocument->GetReadyStateEnum() == Document::READYSTATE_INTERACTIVE ||
995 // test_stricttransportsecurity.html has old-style
996 // docshell-generated about:blank docs reach this code!
997 (mDocument->GetReadyStateEnum() ==
998 Document::READYSTATE_UNINITIALIZED &&
999 NS_IsAboutBlank(mDocument->GetDocumentURI())),
1000 "Bad readystate");
1001 #ifdef DEBUG
1002 bool docShellThinksWeAreRestoring;
1003 docShell->GetRestoringDocument(&docShellThinksWeAreRestoring);
1004 MOZ_ASSERT(!docShellThinksWeAreRestoring,
1005 "How can docshell think we are restoring if we don't have a "
1006 "READYSTATE_COMPLETE document?");
1007 #endif // DEBUG
1008 nsCOMPtr<Document> d = mDocument;
1009 mDocument->SetReadyStateInternal(Document::READYSTATE_COMPLETE);
1011 RefPtr<nsDOMNavigationTiming> timing(d->GetNavigationTiming());
1012 if (timing) {
1013 timing->NotifyLoadEventStart();
1016 // Dispatch observer notification to notify observers document load is
1017 // complete.
1018 nsCOMPtr<nsIObserverService> os = mozilla::services::GetObserverService();
1019 if (os) {
1020 nsIPrincipal* principal = d->NodePrincipal();
1021 os->NotifyObservers(ToSupports(d),
1022 principal->IsSystemPrincipal()
1023 ? "chrome-document-loaded"
1024 : "content-document-loaded",
1025 nullptr);
1028 // Notify any devtools about the load.
1029 RefPtr<TimelineConsumers> timelines = TimelineConsumers::Get();
1031 if (timelines && timelines->HasConsumer(docShell)) {
1032 timelines->AddMarkerForDocShell(
1033 docShell, MakeUnique<DocLoadingTimelineMarker>("document::Load"));
1036 nsPIDOMWindowInner* innerWindow = window->GetCurrentInnerWindow();
1037 RefPtr<DocGroup> docGroup = d->GetDocGroup();
1038 // It is possible that the parent document's load event fires earlier than
1039 // childs' load event, and in this case we need to fire some artificial
1040 // load events to make the parent thinks the load events for child has
1041 // been done
1042 if (innerWindow && DocGroup::TryToLoadIframesInBackground()) {
1043 nsTArray<nsCOMPtr<nsIDocShell>> docShells;
1044 nsCOMPtr<nsIDocShell> container(mContainer);
1045 if (container) {
1046 int32_t count;
1047 container->GetInProcessChildCount(&count);
1048 // We first find all background loading iframes that need to
1049 // fire artificial load events, and instead of firing them as
1050 // soon as we find them, we store them in an array, to prevent
1051 // us from skipping some events.
1052 for (int32_t i = 0; i < count; ++i) {
1053 nsCOMPtr<nsIDocShellTreeItem> child;
1054 container->GetInProcessChildAt(i, getter_AddRefs(child));
1055 nsCOMPtr<nsIDocShell> childIDocShell = do_QueryInterface(child);
1056 RefPtr<nsDocShell> docShell = nsDocShell::Cast(childIDocShell);
1057 if (docShell && docShell->TreatAsBackgroundLoad() &&
1058 docShell->GetDocument()->GetReadyStateEnum() <
1059 Document::READYSTATE_COMPLETE) {
1060 docShells.AppendElement(childIDocShell);
1064 // Re-iterate the stored docShells to fire artificial load events
1065 for (size_t i = 0; i < docShells.Length(); ++i) {
1066 RefPtr<nsDocShell> docShell = nsDocShell::Cast(docShells[i]);
1067 if (docShell && docShell->TreatAsBackgroundLoad() &&
1068 docShell->GetDocument()->GetReadyStateEnum() <
1069 Document::READYSTATE_COMPLETE) {
1070 nsEventStatus status = nsEventStatus_eIgnore;
1071 WidgetEvent event(true, eLoad);
1072 event.mFlags.mBubbles = false;
1073 event.mFlags.mCancelable = false;
1075 nsCOMPtr<nsPIDOMWindowOuter> win = docShell->GetWindow();
1076 nsCOMPtr<Element> element = win->GetFrameElementInternal();
1078 docShell->SetFakeOnLoadDispatched();
1079 EventDispatcher::Dispatch(element, nullptr, &event, nullptr,
1080 &status);
1086 d->SetLoadEventFiring(true);
1087 EventDispatcher::Dispatch(window, mPresContext, &event, nullptr, &status);
1088 d->SetLoadEventFiring(false);
1090 RefPtr<nsDocShell> dShell = nsDocShell::Cast(docShell);
1091 if (docGroup && dShell->TreatAsBackgroundLoad()) {
1092 docGroup->TryFlushIframePostMessages(dShell->GetOuterWindowID());
1095 if (timing) {
1096 timing->NotifyLoadEventEnd();
1099 if (innerWindow) {
1100 innerWindow->QueuePerformanceNavigationTiming();
1103 } else {
1104 // XXX: Should fire error event to the document...
1106 // If our load was explicitly aborted, then we want to set our
1107 // readyState to COMPLETE, and fire a readystatechange event.
1108 if (aStatus == NS_BINDING_ABORTED && mDocument) {
1109 mDocument->NotifyAbortedLoad();
1113 // Notify the document that it has been shown (regardless of whether
1114 // it was just loaded). Note: mDocument may be null now if the above
1115 // firing of onload caused the document to unload. Or, mDocument may not be
1116 // the "current active" document, if the above firing of onload caused our
1117 // docshell to navigate away. NOTE: In this latter scenario, it's likely that
1118 // we fired pagehide (when navigating away) without ever having fired
1119 // pageshow, and that's pretty broken... Fortunately, this should be rare.
1120 // (It requires us to spin the event loop in onload handler, e.g. via sync
1121 // XHR, in order for the navigation-away to happen before onload completes.)
1122 // We skip firing pageshow if we're currently handling unload, or if loading
1123 // was explicitly aborted.
1124 if (mDocument && mDocument->IsCurrentActiveDocument() &&
1125 aStatus != NS_BINDING_ABORTED) {
1126 // Re-get window, since it might have changed during above firing of onload
1127 window = mDocument->GetWindow();
1128 if (window) {
1129 nsIDocShell* docShell = window->GetDocShell();
1130 bool isInUnload;
1131 if (docShell && NS_SUCCEEDED(docShell->GetIsInUnload(&isInUnload)) &&
1132 !isInUnload) {
1133 mDocument->OnPageShow(restoring, nullptr);
1138 if (!mStopped) {
1139 if (mDocument) {
1140 nsCOMPtr<Document> document = mDocument;
1141 document->ScrollToRef();
1144 // Now that the document has loaded, we can tell the presshell
1145 // to unsuppress painting.
1146 if (mPresShell) {
1147 RefPtr<PresShell> presShell = mPresShell;
1148 presShell->UnsuppressPainting();
1149 // mPresShell could have been removed now, see bug 378682/421432
1150 if (mPresShell) {
1151 mPresShell->LoadComplete();
1156 if (mDocument && !restoring) {
1157 mDocument->LoadEventFired();
1160 // It's probably a good idea to GC soon since we have finished loading.
1161 nsJSContext::PokeGC(
1162 JS::GCReason::LOAD_END,
1163 mDocument ? mDocument->GetWrapperPreserveColor() : nullptr);
1165 #ifdef NS_PRINTING
1166 // Check to see if someone tried to print during the load
1167 if (window) {
1168 auto* outerWin = nsGlobalWindowOuter::Cast(window);
1169 outerWin->StopDelayingPrintingUntilAfterLoad();
1170 if (outerWin->DelayedPrintUntilAfterLoad()) {
1171 // We call into the inner because it ensures there's an active document
1172 // and such, and it also waits until the whole thing completes, which is
1173 // nice because it allows us to close if needed right here.
1174 if (RefPtr<nsPIDOMWindowInner> inner = window->GetCurrentInnerWindow()) {
1175 nsGlobalWindowInner::Cast(inner)->Print(IgnoreErrors());
1177 if (outerWin->DelayedCloseForPrinting()) {
1178 outerWin->Close();
1180 } else {
1181 MOZ_ASSERT(!outerWin->DelayedCloseForPrinting());
1184 #endif
1186 return rv;
1189 bool nsDocumentViewer::GetLoadCompleted() { return mLoaded; }
1191 bool nsDocumentViewer::GetIsStopped() { return mStopped; }
1193 NS_IMETHODIMP
1194 nsDocumentViewer::PermitUnload(PermitUnloadAction aAction,
1195 bool* aPermitUnload) {
1196 // We're going to be running JS and nested event loops, which could cause our
1197 // DocShell to be destroyed. Make sure we stay alive until the end of the
1198 // function.
1199 RefPtr<nsDocumentViewer> kungFuDeathGrip(this);
1201 if (StaticPrefs::dom_disable_beforeunload()) {
1202 aAction = eDontPromptAndUnload;
1205 *aPermitUnload = true;
1207 RefPtr<BrowsingContext> bc = mContainer->GetBrowsingContext();
1208 if (!bc) {
1209 return NS_OK;
1212 // Per spec, we need to increase the ignore-opens-during-unload counter while
1213 // dispatching the "beforeunload" event on both the document we're currently
1214 // dispatching the event to and the document that we explicitly asked to
1215 // unload.
1216 IgnoreOpensDuringUnload ignoreOpens(mDocument);
1218 bool foundBlocker = false;
1219 bool foundOOPListener = false;
1220 bc->PreOrderWalk([&](BrowsingContext* aBC) {
1221 if (!aBC->IsInProcess()) {
1222 WindowContext* wc = aBC->GetCurrentWindowContext();
1223 if (wc && wc->HasBeforeUnload()) {
1224 foundOOPListener = true;
1226 } else if (aBC->GetDocShell()) {
1227 nsCOMPtr<nsIContentViewer> contentViewer(
1228 aBC->GetDocShell()->GetContentViewer());
1229 if (contentViewer &&
1230 contentViewer->DispatchBeforeUnload() == eRequestBlockNavigation) {
1231 foundBlocker = true;
1236 if (!foundOOPListener) {
1237 if (!foundBlocker) {
1238 return NS_OK;
1240 if (aAction != ePrompt) {
1241 *aPermitUnload = aAction == eDontPromptAndUnload;
1242 return NS_OK;
1246 // NB: we nullcheck mDocument because it might now be dead as a result of
1247 // the event being dispatched.
1248 RefPtr<WindowGlobalChild> wgc(mDocument ? mDocument->GetWindowGlobalChild()
1249 : nullptr);
1250 if (!wgc) {
1251 return NS_OK;
1254 nsAutoSyncOperation sync(mDocument, SyncOperationBehavior::eSuspendInput);
1255 AutoSuppressEventHandlingAndSuspend seh(bc->Group());
1257 mInPermitUnloadPrompt = true;
1259 bool done = false;
1260 wgc->SendCheckPermitUnload(
1261 foundBlocker, aAction,
1262 [&](bool aPermit) {
1263 done = true;
1264 *aPermitUnload = aPermit;
1266 [&](auto) {
1267 // If the prompt aborted, we tell our consumer that it is not allowed
1268 // to unload the page. One reason that prompts abort is that the user
1269 // performed some action that caused the page to unload while our prompt
1270 // was active. In those cases we don't want our consumer to also unload
1271 // the page.
1273 // XXX: Are there other cases where prompts can abort? Is it ok to
1274 // prevent unloading the page in those cases?
1275 done = true;
1276 *aPermitUnload = false;
1279 SpinEventLoopUntil([&]() { return done; });
1281 mInPermitUnloadPrompt = false;
1282 return NS_OK;
1285 PermitUnloadResult nsDocumentViewer::DispatchBeforeUnload() {
1286 AutoDontWarnAboutSyncXHR disableSyncXHRWarning;
1288 if (!mDocument || mInPermitUnload || mInPermitUnloadPrompt) {
1289 return eAllowNavigation;
1292 // First, get the script global object from the document...
1293 auto* window = nsGlobalWindowOuter::Cast(mDocument->GetWindow());
1294 if (!window) {
1295 // This is odd, but not fatal
1296 NS_WARNING("window not set for document!");
1297 return eAllowNavigation;
1300 NS_ASSERTION(nsContentUtils::IsSafeToRunScript(), "This is unsafe");
1302 // https://html.spec.whatwg.org/multipage/browsing-the-web.html#prompt-to-unload-a-document
1303 // Create an RAII object on mDocument that will increment the
1304 // should-ignore-opens-during-unload counter on initialization
1305 // and decrement it again when it goes out of score (regardless
1306 // of how we exit this function).
1307 IgnoreOpensDuringUnload ignoreOpens(mDocument);
1309 // Now, fire an BeforeUnload event to the document and see if it's ok
1310 // to unload...
1311 nsPresContext* presContext = mDocument->GetPresContext();
1312 RefPtr<BeforeUnloadEvent> event =
1313 new BeforeUnloadEvent(mDocument, presContext, nullptr);
1314 event->InitEvent(u"beforeunload"_ns, false, true);
1316 // Dispatching to |window|, but using |document| as the target.
1317 event->SetTarget(mDocument);
1318 event->SetTrusted(true);
1320 // In evil cases we might be destroyed while handling the
1321 // onbeforeunload event, don't let that happen. (see also bug#331040)
1322 RefPtr<nsDocumentViewer> kungFuDeathGrip(this);
1325 // Never permit popups from the beforeunload handler, no matter
1326 // how we get here.
1327 AutoPopupStatePusher popupStatePusher(PopupBlocker::openAbused, true);
1329 RefPtr<BrowsingContext> bc = mContainer->GetBrowsingContext();
1330 NS_ASSERTION(bc, "should have a browsing context in document viewer");
1332 // Never permit dialogs from the beforeunload handler
1333 nsGlobalWindowOuter::TemporarilyDisableDialogs disableDialogs(bc);
1335 Document::PageUnloadingEventTimeStamp timestamp(mDocument);
1337 mInPermitUnload = true;
1338 EventDispatcher::DispatchDOMEvent(ToSupports(window), nullptr, event,
1339 mPresContext, nullptr);
1340 mInPermitUnload = false;
1343 nsAutoString text;
1344 event->GetReturnValue(text);
1346 // NB: we nullcheck mDocument because it might now be dead as a result of
1347 // the event being dispatched.
1348 if (window->AreDialogsEnabled() && mDocument &&
1349 !(mDocument->GetSandboxFlags() & SANDBOXED_MODALS) &&
1350 (!StaticPrefs::dom_require_user_interaction_for_beforeunload() ||
1351 mDocument->UserHasInteracted()) &&
1352 (event->WidgetEventPtr()->DefaultPrevented() || !text.IsEmpty())) {
1353 return eRequestBlockNavigation;
1355 return eAllowNavigation;
1358 NS_IMETHODIMP
1359 nsDocumentViewer::GetBeforeUnloadFiring(bool* aInEvent) {
1360 *aInEvent = mInPermitUnload;
1361 return NS_OK;
1364 NS_IMETHODIMP
1365 nsDocumentViewer::GetInPermitUnload(bool* aInEvent) {
1366 *aInEvent = mInPermitUnloadPrompt;
1367 return NS_OK;
1370 NS_IMETHODIMP
1371 nsDocumentViewer::PageHide(bool aIsUnload) {
1372 AutoDontWarnAboutSyncXHR disableSyncXHRWarning;
1374 mHidden = true;
1376 if (!mDocument) {
1377 return NS_ERROR_NULL_POINTER;
1380 if (aIsUnload) {
1381 // Poke the GC. The window might be collectable garbage now.
1382 nsJSContext::PokeGC(JS::GCReason::PAGE_HIDE,
1383 mDocument->GetWrapperPreserveColor(),
1384 TimeDuration::FromMilliseconds(
1385 StaticPrefs::javascript_options_gc_delay() * 2));
1388 mDocument->OnPageHide(!aIsUnload, nullptr);
1390 // inform the window so that the focus state is reset.
1391 NS_ENSURE_STATE(mDocument);
1392 nsPIDOMWindowOuter* window = mDocument->GetWindow();
1393 if (window) window->PageHidden();
1395 if (aIsUnload) {
1396 // if Destroy() was called during OnPageHide(), mDocument is nullptr.
1397 NS_ENSURE_STATE(mDocument);
1399 // First, get the window from the document...
1400 nsPIDOMWindowOuter* window = mDocument->GetWindow();
1402 if (!window) {
1403 // Fail if no window is available...
1404 NS_WARNING("window not set for document!");
1405 return NS_ERROR_NULL_POINTER;
1408 // https://html.spec.whatwg.org/multipage/browsing-the-web.html#unload-a-document
1409 // Create an RAII object on mDocument that will increment the
1410 // should-ignore-opens-during-unload counter on initialization
1411 // and decrement it again when it goes out of scope.
1412 IgnoreOpensDuringUnload ignoreOpens(mDocument);
1414 // Now, fire an Unload event to the document...
1415 nsEventStatus status = nsEventStatus_eIgnore;
1416 WidgetEvent event(true, eUnload);
1417 event.mFlags.mBubbles = false;
1418 // XXX Dispatching to |window|, but using |document| as the target.
1419 event.mTarget = mDocument;
1421 // Never permit popups from the unload handler, no matter how we get
1422 // here.
1423 AutoPopupStatePusher popupStatePusher(PopupBlocker::openAbused, true);
1425 Document::PageUnloadingEventTimeStamp timestamp(mDocument);
1427 EventDispatcher::Dispatch(window, mPresContext, &event, nullptr, &status);
1430 #ifdef MOZ_XUL
1431 // look for open menupopups and close them after the unload event, in case
1432 // the unload event listeners open any new popups
1433 nsContentUtils::HidePopupsInDocument(mDocument);
1434 #endif
1436 return NS_OK;
1439 static void AttachContainerRecurse(nsIDocShell* aShell) {
1440 nsCOMPtr<nsIContentViewer> viewer;
1441 aShell->GetContentViewer(getter_AddRefs(viewer));
1442 if (viewer) {
1443 viewer->SetIsHidden(false);
1444 Document* doc = viewer->GetDocument();
1445 if (doc) {
1446 doc->SetContainer(static_cast<nsDocShell*>(aShell));
1448 if (PresShell* presShell = viewer->GetPresShell()) {
1449 presShell->SetForwardingContainer(WeakPtr<nsDocShell>());
1453 // Now recurse through the children
1454 int32_t childCount;
1455 aShell->GetInProcessChildCount(&childCount);
1456 for (int32_t i = 0; i < childCount; ++i) {
1457 nsCOMPtr<nsIDocShellTreeItem> childItem;
1458 aShell->GetInProcessChildAt(i, getter_AddRefs(childItem));
1459 nsCOMPtr<nsIDocShell> shell = do_QueryInterface(childItem);
1460 AttachContainerRecurse(shell);
1464 NS_IMETHODIMP
1465 nsDocumentViewer::Open(nsISupports* aState, nsISHEntry* aSHEntry) {
1466 NS_ENSURE_TRUE(mPresShell, NS_ERROR_NOT_INITIALIZED);
1468 if (mDocument) {
1469 mDocument->SetContainer(mContainer);
1472 nsresult rv = InitInternal(mParentWidget, aState, nullptr, mBounds, false);
1473 NS_ENSURE_SUCCESS(rv, rv);
1475 mHidden = false;
1477 if (mPresShell) mPresShell->SetForwardingContainer(WeakPtr<nsDocShell>());
1479 // Rehook the child presentations. The child shells are still in
1480 // session history, so get them from there.
1482 if (aSHEntry) {
1483 nsCOMPtr<nsIDocShellTreeItem> item;
1484 int32_t itemIndex = 0;
1485 while (NS_SUCCEEDED(
1486 aSHEntry->ChildShellAt(itemIndex++, getter_AddRefs(item))) &&
1487 item) {
1488 nsCOMPtr<nsIDocShell> shell = do_QueryInterface(item);
1489 AttachContainerRecurse(shell);
1493 SyncParentSubDocMap();
1495 ReinitializeFocusListener();
1497 // XXX re-enable image animations once that works correctly
1499 PrepareToStartLoad();
1501 // When loading a page from the bfcache with puppet widgets, we do the
1502 // widget attachment here (it is otherwise done in MakeWindow, which is
1503 // called for non-bfcache pages in the history, but not bfcache pages).
1504 // Attachment is necessary, since we get detached when another page
1505 // is browsed to. That is, if we are one page A, then when we go to
1506 // page B, we detach. So page A's view has no widget. If we then go
1507 // back to it, and it is in the bfcache, we will use that view, which
1508 // doesn't have a widget. The attach call here will properly attach us.
1509 if (nsIWidget::UsePuppetWidgets() && mPresContext &&
1510 ShouldAttachToTopLevel()) {
1511 // If the old view is already attached to our parent, detach
1512 DetachFromTopLevelWidget();
1514 nsViewManager* vm = GetViewManager();
1515 MOZ_ASSERT(vm, "no view manager");
1516 nsView* v = vm->GetRootView();
1517 MOZ_ASSERT(v, "no root view");
1518 MOZ_ASSERT(mParentWidget, "no mParentWidget to set");
1519 v->AttachToTopLevelWidget(mParentWidget);
1521 mAttachedToParent = true;
1524 return NS_OK;
1527 NS_IMETHODIMP
1528 nsDocumentViewer::Close(nsISHEntry* aSHEntry) {
1529 // All callers are supposed to call close to break circular
1530 // references. If we do this stuff in the destructor, the
1531 // destructor might never be called (especially if we're being
1532 // used from JS.
1534 mSHEntry = aSHEntry;
1536 // Close is also needed to disable scripts during paint suppression,
1537 // since we transfer the existing global object to the new document
1538 // that is loaded. In the future, the global object may become a proxy
1539 // for an object that can be switched in and out so that we don't need
1540 // to disable scripts during paint suppression.
1542 if (!mDocument) return NS_OK;
1544 if (mSHEntry) {
1545 if (mBFCachePreventionObserver) {
1546 mBFCachePreventionObserver->Disconnect();
1548 mBFCachePreventionObserver = new BFCachePreventionObserver(mDocument);
1549 mDocument->AddMutationObserver(mBFCachePreventionObserver);
1552 #ifdef NS_PRINTING
1553 // A Close was called while we were printing
1554 // so don't clear the ScriptGlobalObject
1555 // or clear the mDocument below
1556 if (mPrintJob && !mClosingWhilePrinting) {
1557 mClosingWhilePrinting = true;
1558 } else
1559 #endif
1561 // out of band cleanup of docshell
1562 mDocument->SetScriptGlobalObject(nullptr);
1564 if (!mSHEntry && mDocument) mDocument->RemovedFromDocShell();
1567 RemoveFocusListener();
1568 return NS_OK;
1571 static void DetachContainerRecurse(nsIDocShell* aShell) {
1572 // Unhook this docshell's presentation
1573 aShell->SynchronizeLayoutHistoryState();
1574 nsCOMPtr<nsIContentViewer> viewer;
1575 aShell->GetContentViewer(getter_AddRefs(viewer));
1576 if (viewer) {
1577 if (Document* doc = viewer->GetDocument()) {
1578 doc->SetContainer(nullptr);
1580 if (PresShell* presShell = viewer->GetPresShell()) {
1581 auto weakShell = static_cast<nsDocShell*>(aShell);
1582 presShell->SetForwardingContainer(weakShell);
1586 // Now recurse through the children
1587 int32_t childCount;
1588 aShell->GetInProcessChildCount(&childCount);
1589 for (int32_t i = 0; i < childCount; ++i) {
1590 nsCOMPtr<nsIDocShellTreeItem> childItem;
1591 aShell->GetInProcessChildAt(i, getter_AddRefs(childItem));
1592 nsCOMPtr<nsIDocShell> shell = do_QueryInterface(childItem);
1593 DetachContainerRecurse(shell);
1597 NS_IMETHODIMP
1598 nsDocumentViewer::Destroy() {
1599 NS_ASSERTION(mDocument, "No document in Destroy()!");
1601 // Don't let the document get unloaded while we are printing.
1602 // this could happen if we hit the back button during printing.
1603 // We also keep the viewer from being cached in session history, since
1604 // we require all documents there to be sanitized.
1605 if (mDestroyBlockedCount != 0) {
1606 return NS_OK;
1609 #ifdef NS_PRINTING
1610 // Here is where we check to see if the document was still being prepared
1611 // for printing when it was asked to be destroy from someone externally
1612 // This usually happens if the document is unloaded while the user is in the
1613 // Print Dialog
1615 // So we flip the bool to remember that the document is going away
1616 // and we can clean up and abort later after returning from the Print Dialog
1617 if (mPrintJob && mPrintJob->CheckBeforeDestroy()) {
1618 return NS_OK;
1620 #endif
1622 // We want to make sure to disconnect mBFCachePreventionObserver before we
1623 // Sanitize() below.
1624 if (mBFCachePreventionObserver) {
1625 mBFCachePreventionObserver->Disconnect();
1626 mBFCachePreventionObserver = nullptr;
1629 if (mSHEntry && mDocument && !mDocument->IsBFCachingAllowed()) {
1630 // Just drop the SHEntry now and pretend like we never even tried to bfcache
1631 // this viewer. This should only happen when someone calls
1632 // DisallowBFCaching() after CanSavePresentation() already ran. Ensure that
1633 // the SHEntry has no viewer and its state is synced up. We want to do this
1634 // via a stack reference, in case those calls mess with our members.
1635 MOZ_LOG(gPageCacheLog, LogLevel::Debug,
1636 ("BFCache not allowed, dropping SHEntry"));
1637 nsCOMPtr<nsISHEntry> shEntry = std::move(mSHEntry);
1638 shEntry->SetContentViewer(nullptr);
1639 shEntry->SyncPresentationState();
1642 // If we were told to put ourselves into session history instead of destroy
1643 // the presentation, do that now.
1644 if (mSHEntry) {
1645 if (mPresShell) mPresShell->Freeze();
1647 // Make sure the presentation isn't torn down by Hide().
1648 mSHEntry->SetSticky(mIsSticky);
1649 mIsSticky = true;
1651 // Remove our root view from the view hierarchy.
1652 if (mPresShell) {
1653 nsViewManager* vm = mPresShell->GetViewManager();
1654 if (vm) {
1655 nsView* rootView = vm->GetRootView();
1657 if (rootView) {
1658 nsView* rootViewParent = rootView->GetParent();
1659 if (rootViewParent) {
1660 nsView* subdocview = rootViewParent->GetParent();
1661 if (subdocview) {
1662 nsIFrame* f = subdocview->GetFrame();
1663 if (f) {
1664 nsSubDocumentFrame* s = do_QueryFrame(f);
1665 if (s) {
1666 s->ClearDisplayItems();
1670 nsViewManager* parentVM = rootViewParent->GetViewManager();
1671 if (parentVM) {
1672 parentVM->RemoveChild(rootView);
1679 Hide();
1681 // This is after Hide() so that the user doesn't see the inputs clear.
1682 if (mDocument) {
1683 mDocument->Sanitize();
1686 // Reverse ownership. Do this *after* calling sanitize so that sanitize
1687 // doesn't cause mutations that make the SHEntry drop the presentation
1689 // Grab a reference to mSHEntry before calling into things like
1690 // SyncPresentationState that might mess with our members.
1691 nsCOMPtr<nsISHEntry> shEntry =
1692 std::move(mSHEntry); // we'll need this below
1694 MOZ_LOG(gPageCacheLog, LogLevel::Debug,
1695 ("Storing content viewer into cache entry"));
1696 shEntry->SetContentViewer(this);
1698 // Always sync the presentation state. That way even if someone screws up
1699 // and shEntry has no window state at this point we'll be ok; we just won't
1700 // cache ourselves.
1701 shEntry->SyncPresentationState();
1702 // XXX Synchronize layout history state to parent once bfcache is supported
1703 // in session-history-in-parent.
1705 // Shut down accessibility for the document before we start to tear it down.
1706 #ifdef ACCESSIBILITY
1707 if (mPresShell) {
1708 a11y::DocAccessible* docAcc = mPresShell->GetDocAccessible();
1709 if (docAcc) {
1710 docAcc->Shutdown();
1713 #endif
1715 // Break the link from the document/presentation to the docshell, so that
1716 // link traversals cannot affect the currently-loaded document.
1717 // When the presentation is restored, Open() and InitInternal() will reset
1718 // these pointers to their original values.
1720 if (mDocument) {
1721 mDocument->SetContainer(nullptr);
1723 if (mPresShell) {
1724 mPresShell->SetForwardingContainer(mContainer);
1727 // Do the same for our children. Note that we need to get the child
1728 // docshells from the SHEntry now; the docshell will have cleared them.
1729 nsCOMPtr<nsIDocShellTreeItem> item;
1730 int32_t itemIndex = 0;
1731 while (NS_SUCCEEDED(
1732 shEntry->ChildShellAt(itemIndex++, getter_AddRefs(item))) &&
1733 item) {
1734 nsCOMPtr<nsIDocShell> shell = do_QueryInterface(item);
1735 DetachContainerRecurse(shell);
1738 return NS_OK;
1741 // The document was not put in the bfcache
1743 // Protect against pres shell destruction running scripts and re-entrantly
1744 // creating a new presentation.
1745 nsAutoScriptBlocker scriptBlocker;
1747 if (mPresShell) {
1748 DestroyPresShell();
1750 if (mDocument) {
1751 mDocument->Destroy();
1752 mDocument = nullptr;
1755 // All callers are supposed to call destroy to break circular
1756 // references. If we do this stuff in the destructor, the
1757 // destructor might never be called (especially if we're being
1758 // used from JS.
1760 #ifdef NS_PRINTING
1761 if (mPrintJob) {
1762 RefPtr<nsPrintJob> printJob = std::move(mPrintJob);
1763 # ifdef NS_PRINT_PREVIEW
1764 if (printJob->CreatedForPrintPreview()) {
1765 printJob->FinishPrintPreview();
1767 # endif
1768 printJob->Destroy();
1769 MOZ_ASSERT(!mPrintJob,
1770 "mPrintJob shouldn't be recreated while destroying it");
1772 #endif
1774 // Avoid leaking the old viewer.
1775 if (mPreviousViewer) {
1776 mPreviousViewer->Destroy();
1777 mPreviousViewer = nullptr;
1780 mDeviceContext = nullptr;
1782 if (mPresContext) {
1783 DestroyPresContext();
1786 mWindow = nullptr;
1787 mViewManager = nullptr;
1788 mContainer = WeakPtr<nsDocShell>();
1790 return NS_OK;
1793 NS_IMETHODIMP
1794 nsDocumentViewer::Stop(void) {
1795 NS_ASSERTION(mDocument, "Stop called too early or too late");
1796 if (mDocument) {
1797 mDocument->StopDocumentLoad();
1800 if (!mHidden && (mLoaded || mStopped) && mPresContext && !mSHEntry)
1801 mPresContext->SetImageAnimationMode(imgIContainer::kDontAnimMode);
1803 mStopped = true;
1805 if (!mLoaded && mPresShell) {
1806 // Well, we might as well paint what we have so far.
1807 RefPtr<PresShell> presShell = mPresShell; // bug 378682
1808 presShell->UnsuppressPainting();
1811 return NS_OK;
1814 NS_IMETHODIMP
1815 nsDocumentViewer::GetDOMDocument(Document** aResult) {
1816 NS_ENSURE_TRUE(mDocument, NS_ERROR_NOT_AVAILABLE);
1817 nsCOMPtr<Document> document = mDocument;
1818 document.forget(aResult);
1819 return NS_OK;
1822 Document* nsDocumentViewer::GetDocument() { return mDocument; }
1824 nsresult nsDocumentViewer::SetDocument(Document* aDocument) {
1825 // Assumptions:
1827 // 1) this document viewer has been initialized with a call to Init().
1828 // 2) the stylesheets associated with the document have been added
1829 // to the document.
1831 // XXX Right now, this method assumes that the layout of the current
1832 // document hasn't started yet. More cleanup will probably be
1833 // necessary to make this method work for the case when layout *has*
1834 // occurred for the current document.
1835 // That work can happen when and if it is needed.
1837 if (!aDocument) return NS_ERROR_NULL_POINTER;
1839 return SetDocumentInternal(aDocument, false);
1842 NS_IMETHODIMP
1843 nsDocumentViewer::SetDocumentInternal(Document* aDocument,
1844 bool aForceReuseInnerWindow) {
1845 MOZ_ASSERT(aDocument);
1847 // Set new container
1848 aDocument->SetContainer(mContainer);
1850 if (mDocument != aDocument) {
1851 if (aForceReuseInnerWindow) {
1852 // Transfer the navigation timing information to the new document, since
1853 // we're keeping the same inner and hence should really have the same
1854 // timing information.
1855 aDocument->SetNavigationTiming(mDocument->GetNavigationTiming());
1858 if (mDocument &&
1859 (mDocument->IsStaticDocument() || aDocument->IsStaticDocument())) {
1860 nsContentUtils::AddScriptRunner(NewRunnableMethod(
1861 "Document::Destroy", mDocument, &Document::Destroy));
1864 // Clear the list of old child docshells. Child docshells for the new
1865 // document will be constructed as frames are created.
1866 if (!aDocument->IsStaticDocument()) {
1867 nsCOMPtr<nsIDocShell> node(mContainer);
1868 if (node) {
1869 int32_t count;
1870 node->GetInProcessChildCount(&count);
1871 for (int32_t i = 0; i < count; ++i) {
1872 nsCOMPtr<nsIDocShellTreeItem> child;
1873 node->GetInProcessChildAt(0, getter_AddRefs(child));
1874 node->RemoveChild(child);
1879 // Replace the old document with the new one. Do this only when
1880 // the new document really is a new document.
1881 mDocument = aDocument;
1883 // Set the script global object on the new document
1884 nsCOMPtr<nsPIDOMWindowOuter> window =
1885 mContainer ? mContainer->GetWindow() : nullptr;
1886 if (window) {
1887 nsresult rv =
1888 window->SetNewDocument(aDocument, nullptr, aForceReuseInnerWindow);
1889 if (NS_FAILED(rv)) {
1890 Destroy();
1891 return rv;
1896 nsresult rv = SyncParentSubDocMap();
1897 NS_ENSURE_SUCCESS(rv, rv);
1899 // Replace the current pres shell with a new shell for the new document
1901 // Protect against pres shell destruction running scripts and re-entrantly
1902 // creating a new presentation.
1903 nsAutoScriptBlocker scriptBlocker;
1905 if (mPresShell) {
1906 DestroyPresShell();
1909 if (mPresContext) {
1910 DestroyPresContext();
1912 mWindow = nullptr;
1913 rv = InitInternal(mParentWidget, nullptr, nullptr, mBounds, true, true,
1914 false);
1917 return rv;
1920 PresShell* nsDocumentViewer::GetPresShell() { return mPresShell; }
1922 nsPresContext* nsDocumentViewer::GetPresContext() { return mPresContext; }
1924 nsViewManager* nsDocumentViewer::GetViewManager() { return mViewManager; }
1926 NS_IMETHODIMP
1927 nsDocumentViewer::GetBounds(nsIntRect& aResult) {
1928 NS_ENSURE_TRUE(mDocument, NS_ERROR_NOT_AVAILABLE);
1929 aResult = mBounds;
1930 return NS_OK;
1933 nsIContentViewer* nsDocumentViewer::GetPreviousViewer() {
1934 return mPreviousViewer;
1937 void nsDocumentViewer::SetPreviousViewer(nsIContentViewer* aViewer) {
1938 // NOTE: |Show| sets |mPreviousViewer| to null without calling this
1939 // function.
1941 if (aViewer) {
1942 NS_ASSERTION(!mPreviousViewer,
1943 "can't set previous viewer when there already is one");
1945 // In a multiple chaining situation (which occurs when running a thrashing
1946 // test like i-bench or jrgm's tests with no delay), we can build up a
1947 // whole chain of viewers. In order to avoid this, we always set our
1948 // previous viewer to the MOST previous viewer in the chain, and then dump
1949 // the intermediate link from the chain. This ensures that at most only 2
1950 // documents are alive and undestroyed at any given time (the one that is
1951 // showing and the one that is loading with painting suppressed). It's very
1952 // important that if this ever gets changed the code before the
1953 // RestorePresentation call in nsDocShell::InternalLoad be changed
1954 // accordingly.
1956 // Make sure we hold a strong ref to prevViewer here, since we'll
1957 // tell aViewer to drop it.
1958 nsCOMPtr<nsIContentViewer> prevViewer = aViewer->GetPreviousViewer();
1959 if (prevViewer) {
1960 aViewer->SetPreviousViewer(nullptr);
1961 aViewer->Destroy();
1962 return SetPreviousViewer(prevViewer);
1966 mPreviousViewer = aViewer;
1969 NS_IMETHODIMP
1970 nsDocumentViewer::SetBoundsWithFlags(const nsIntRect& aBounds,
1971 uint32_t aFlags) {
1972 NS_ENSURE_TRUE(mDocument, NS_ERROR_NOT_AVAILABLE);
1974 bool boundsChanged = !mBounds.IsEqualEdges(aBounds);
1975 mBounds = aBounds;
1977 if (mWindow && !mAttachedToParent) {
1978 // Resize the widget, but don't trigger repaint. Layout will generate
1979 // repaint requests during reflow.
1980 mWindow->Resize(aBounds.x, aBounds.y, aBounds.width, aBounds.height, false);
1981 } else if (mPresContext && mViewManager) {
1982 // Ensure presContext's deviceContext is up to date, as we sometimes get
1983 // here before a resolution-change notification has been fully handled
1984 // during display configuration changes, especially when there are lots
1985 // of windows/widgets competing to handle the notifications.
1986 // (See bug 1154125.)
1987 if (mPresContext->DeviceContext()->CheckDPIChange()) {
1988 mPresContext->UIResolutionChanged();
1991 int32_t p2a = mPresContext->AppUnitsPerDevPixel();
1992 nscoord width = NSIntPixelsToAppUnits(mBounds.width, p2a);
1993 nscoord height = NSIntPixelsToAppUnits(mBounds.height, p2a);
1994 nsView* rootView = mViewManager->GetRootView();
1995 if (boundsChanged && rootView) {
1996 nsRect viewDims = rootView->GetDimensions();
1997 // If the view/frame tree and prescontext visible area already has the new
1998 // size but we did not, then it's likely that we got reflowed in response
1999 // to a call to GetContentSize. Thus there is a disconnect between the
2000 // size on the document viewer/docshell/containing widget and view
2001 // tree/frame tree/prescontext visible area). SetWindowDimensions compares
2002 // to the root view dimenstions to determine if it needs to do anything;
2003 // if they are the same as the new size it won't do anything, but we still
2004 // need to invalidate because what we want to draw to the screen has
2005 // changed.
2006 if (viewDims.width == width && viewDims.height == height) {
2007 nsIFrame* f = rootView->GetFrame();
2008 if (f) {
2009 f->InvalidateFrame();
2014 mViewManager->SetWindowDimensions(
2015 width, height, !!(aFlags & nsIContentViewer::eDelayResize));
2018 // If there's a previous viewer, it's the one that's actually showing,
2019 // so be sure to resize it as well so it paints over the right area.
2020 // This may slow down the performance of the new page load, but resize
2021 // during load is also probably a relatively unusual condition
2022 // relating to things being hidden while something is loaded. It so
2023 // happens that Firefox does this a good bit with its infobar, and it
2024 // looks ugly if we don't do this.
2025 if (mPreviousViewer) {
2026 nsCOMPtr<nsIContentViewer> previousViewer = mPreviousViewer;
2027 previousViewer->SetBounds(aBounds);
2030 return NS_OK;
2033 NS_IMETHODIMP
2034 nsDocumentViewer::SetBounds(const nsIntRect& aBounds) {
2035 return SetBoundsWithFlags(aBounds, 0);
2038 NS_IMETHODIMP
2039 nsDocumentViewer::Move(int32_t aX, int32_t aY) {
2040 NS_ENSURE_TRUE(mDocument, NS_ERROR_NOT_AVAILABLE);
2041 mBounds.MoveTo(aX, aY);
2042 if (mWindow) {
2043 mWindow->Move(aX, aY);
2045 return NS_OK;
2048 NS_IMETHODIMP
2049 nsDocumentViewer::Show() {
2050 NS_ENSURE_TRUE(mDocument, NS_ERROR_NOT_AVAILABLE);
2052 // We don't need the previous viewer anymore since we're not
2053 // displaying it.
2054 if (mPreviousViewer) {
2055 // This little dance *may* only be to keep
2056 // PresShell::EndObservingDocument happy, but I'm not sure.
2057 nsCOMPtr<nsIContentViewer> prevViewer(mPreviousViewer);
2058 mPreviousViewer = nullptr;
2059 prevViewer->Destroy();
2061 // Make sure we don't have too many cached ContentViewers
2062 nsCOMPtr<nsIDocShellTreeItem> treeItem(mContainer);
2063 if (treeItem) {
2064 // We need to find the root DocShell since only that object has an
2065 // SHistory and we need the SHistory to evict content viewers
2066 nsCOMPtr<nsIDocShellTreeItem> root;
2067 treeItem->GetInProcessSameTypeRootTreeItem(getter_AddRefs(root));
2068 nsCOMPtr<nsIWebNavigation> webNav = do_QueryInterface(root);
2069 RefPtr<ChildSHistory> history = webNav->GetSessionHistory();
2070 if (!mozilla::SessionHistoryInParent() && history) {
2071 int32_t prevIndex, loadedIndex;
2072 nsCOMPtr<nsIDocShell> docShell = do_QueryInterface(treeItem);
2073 docShell->GetPreviousEntryIndex(&prevIndex);
2074 docShell->GetLoadedEntryIndex(&loadedIndex);
2075 MOZ_LOG(gPageCacheLog, LogLevel::Verbose,
2076 ("About to evict content viewers: prev=%d, loaded=%d",
2077 prevIndex, loadedIndex));
2078 history->LegacySHistory()->EvictOutOfRangeContentViewers(loadedIndex);
2083 if (mWindow) {
2084 // When attached to a top level xul window, we do not need to call
2085 // Show on the widget. Underlying window management code handles
2086 // this when the window is initialized.
2087 if (!mAttachedToParent) {
2088 mWindow->Show(true);
2092 // Hold on to the document so we can use it after the script blocker below
2093 // has been released (which might re-entrantly call into other
2094 // nsDocumentViewer methods).
2095 nsCOMPtr<Document> document = mDocument;
2097 if (mDocument && !mPresShell) {
2098 // The InitPresentationStuff call below requires a script blocker, because
2099 // its PresShell::Initialize call can cause scripts to run and therefore
2100 // re-entrant calls to nsDocumentViewer methods to be made.
2101 nsAutoScriptBlocker scriptBlocker;
2103 NS_ASSERTION(!mWindow, "Window already created but no presshell?");
2105 nsCOMPtr<nsIBaseWindow> base_win(mContainer);
2106 if (base_win) {
2107 base_win->GetParentWidget(&mParentWidget);
2108 if (mParentWidget) {
2109 // GetParentWidget AddRefs, but mParentWidget is weak
2110 mParentWidget->Release();
2114 nsView* containerView = FindContainerView();
2116 nsresult rv = CreateDeviceContext(containerView);
2117 NS_ENSURE_SUCCESS(rv, rv);
2119 // Create presentation context
2120 NS_ASSERTION(!mPresContext,
2121 "Shouldn't have a prescontext if we have no shell!");
2122 mPresContext = CreatePresContext(mDocument, nsPresContext::eContext_Galley,
2123 containerView);
2124 NS_ENSURE_TRUE(mPresContext, NS_ERROR_OUT_OF_MEMORY);
2126 rv = mPresContext->Init(mDeviceContext);
2127 if (NS_FAILED(rv)) {
2128 mPresContext = nullptr;
2129 return rv;
2132 rv = MakeWindow(nsSize(mPresContext->DevPixelsToAppUnits(mBounds.width),
2133 mPresContext->DevPixelsToAppUnits(mBounds.height)),
2134 containerView);
2135 if (NS_FAILED(rv)) return rv;
2137 if (mPresContext) {
2138 Hide();
2140 rv = InitPresentationStuff(mDocument->MayStartLayout());
2143 // If we get here the document load has already started and the
2144 // window is shown because some JS on the page caused it to be
2145 // shown...
2147 if (mPresShell) {
2148 RefPtr<PresShell> presShell = mPresShell; // bug 378682
2149 presShell->UnsuppressPainting();
2153 // Notify observers that a new page has been shown. This will get run
2154 // from the event loop after we actually draw the page.
2155 RefPtr<nsDocumentShownDispatcher> event =
2156 new nsDocumentShownDispatcher(document);
2157 document->Dispatch(TaskCategory::Other, event.forget());
2159 return NS_OK;
2162 NS_IMETHODIMP
2163 nsDocumentViewer::Hide() {
2164 if (!mAttachedToParent && mWindow) {
2165 mWindow->Show(false);
2168 if (!mPresShell) return NS_OK;
2170 NS_ASSERTION(mPresContext, "Can't have a presshell and no prescontext!");
2172 // Avoid leaking the old viewer.
2173 if (mPreviousViewer) {
2174 mPreviousViewer->Destroy();
2175 mPreviousViewer = nullptr;
2178 if (mIsSticky) {
2179 // This window is sticky, that means that it might be shown again
2180 // and we don't want the presshell n' all that to be thrown away
2181 // just because the window is hidden.
2183 return NS_OK;
2186 nsCOMPtr<nsIDocShell> docShell(mContainer);
2187 if (docShell) {
2188 #ifdef DEBUG
2189 nsCOMPtr<nsIContentViewer> currentViewer;
2190 docShell->GetContentViewer(getter_AddRefs(currentViewer));
2191 MOZ_ASSERT(currentViewer == this);
2192 #endif
2193 nsCOMPtr<nsILayoutHistoryState> layoutState;
2194 mPresShell->CaptureHistoryState(getter_AddRefs(layoutState));
2197 // Do not run ScriptRunners queued by DestroyPresShell() in the intermediate
2198 // state before we're done destroying PresShell, PresContext, ViewManager,
2199 // etc.
2200 nsAutoScriptBlocker scriptBlocker;
2202 DestroyPresShell();
2204 DestroyPresContext();
2206 mViewManager = nullptr;
2207 mWindow = nullptr;
2208 mDeviceContext = nullptr;
2209 mParentWidget = nullptr;
2211 nsCOMPtr<nsIBaseWindow> base_win(mContainer);
2213 if (base_win && !mAttachedToParent) {
2214 base_win->SetParentWidget(nullptr);
2217 return NS_OK;
2220 NS_IMETHODIMP
2221 nsDocumentViewer::GetSticky(bool* aSticky) {
2222 *aSticky = mIsSticky;
2224 return NS_OK;
2227 NS_IMETHODIMP
2228 nsDocumentViewer::SetSticky(bool aSticky) {
2229 mIsSticky = aSticky;
2231 return NS_OK;
2234 NS_IMETHODIMP
2235 nsDocumentViewer::ClearHistoryEntry() {
2236 if (mDocument) {
2237 nsJSContext::PokeGC(JS::GCReason::PAGE_HIDE,
2238 mDocument->GetWrapperPreserveColor(),
2239 TimeDuration::FromMilliseconds(
2240 StaticPrefs::javascript_options_gc_delay() * 2));
2243 mSHEntry = nullptr;
2244 return NS_OK;
2247 //-------------------------------------------------------
2249 nsresult nsDocumentViewer::MakeWindow(const nsSize& aSize,
2250 nsView* aContainerView) {
2251 if (GetIsPrintPreview()) {
2252 return NS_OK;
2255 bool shouldAttach = ShouldAttachToTopLevel();
2257 if (shouldAttach) {
2258 // If the old view is already attached to our parent, detach
2259 DetachFromTopLevelWidget();
2262 mViewManager = new nsViewManager();
2264 nsDeviceContext* dx = mPresContext->DeviceContext();
2266 nsresult rv = mViewManager->Init(dx);
2267 if (NS_FAILED(rv)) return rv;
2269 // The root view is always at 0,0.
2270 nsRect tbounds(nsPoint(0, 0), aSize);
2271 // Create a view
2272 nsView* view = mViewManager->CreateView(tbounds, aContainerView);
2273 if (!view) return NS_ERROR_OUT_OF_MEMORY;
2275 // Create a widget if we were given a parent widget or don't have a
2276 // container view that we can hook up to without a widget.
2277 // Don't create widgets for ResourceDocs (external resources & svg images),
2278 // because when they're displayed, they're painted into *another* document's
2279 // widget.
2280 if (!mDocument->IsResourceDoc() && (mParentWidget || !aContainerView)) {
2281 // pass in a native widget to be the parent widget ONLY if the view
2282 // hierarchy will stand alone. otherwise the view will find its own parent
2283 // widget and "do the right thing" to establish a parent/child widget
2284 // relationship
2285 nsWidgetInitData initData;
2286 nsWidgetInitData* initDataPtr;
2287 if (!mParentWidget) {
2288 initDataPtr = &initData;
2289 initData.mWindowType = eWindowType_invisible;
2290 } else {
2291 initDataPtr = nullptr;
2294 if (shouldAttach) {
2295 // Reuse the top level parent widget.
2296 rv = view->AttachToTopLevelWidget(mParentWidget);
2297 mAttachedToParent = true;
2298 } else if (!aContainerView && mParentWidget) {
2299 rv = view->CreateWidgetForParent(mParentWidget, initDataPtr, true, false);
2300 } else {
2301 rv = view->CreateWidget(initDataPtr, true, false);
2303 if (NS_FAILED(rv)) return rv;
2306 // Setup hierarchical relationship in view manager
2307 mViewManager->SetRootView(view);
2309 mWindow = view->GetWidget();
2311 // This SetFocus is necessary so the Arrow Key and Page Key events
2312 // go to the scrolled view as soon as the Window is created instead of going
2313 // to the browser window (this enables keyboard scrolling of the document)
2314 // mWindow->SetFocus();
2316 return rv;
2319 void nsDocumentViewer::DetachFromTopLevelWidget() {
2320 if (mViewManager) {
2321 nsView* oldView = mViewManager->GetRootView();
2322 if (oldView && oldView->IsAttachedToTopLevel()) {
2323 oldView->DetachFromTopLevelWidget();
2326 mAttachedToParent = false;
2329 nsView* nsDocumentViewer::FindContainerView() {
2330 if (!mContainer) {
2331 return nullptr;
2334 nsCOMPtr<nsIDocShell> docShell(mContainer);
2335 nsCOMPtr<nsPIDOMWindowOuter> pwin(docShell->GetWindow());
2336 if (!pwin) {
2337 return nullptr;
2340 nsCOMPtr<Element> containerElement = pwin->GetFrameElementInternal();
2341 if (!containerElement) {
2342 return nullptr;
2345 nsIFrame* subdocFrame = containerElement->GetPrimaryFrame();
2346 if (!subdocFrame) {
2347 // XXX Silenced by default in bug 1175289
2348 LAYOUT_WARNING("Subdocument container has no frame");
2349 return nullptr;
2352 // Check subdocFrame just to be safe. If this somehow fails we treat that as
2353 // display:none, the document is not displayed.
2354 if (!subdocFrame->IsSubDocumentFrame()) {
2355 NS_WARNING_ASSERTION(subdocFrame->Type() == LayoutFrameType::None,
2356 "Subdocument container has non-subdocument frame");
2357 return nullptr;
2360 NS_ASSERTION(subdocFrame->GetView(), "Subdoc frames must have views");
2361 return static_cast<nsSubDocumentFrame*>(subdocFrame)->EnsureInnerView();
2364 nsresult nsDocumentViewer::CreateDeviceContext(nsView* aContainerView) {
2365 MOZ_ASSERT(!mPresShell && !mWindow,
2366 "This will screw up our existing presentation");
2367 MOZ_ASSERT(mDocument, "Gotta have a document here");
2369 Document* doc = mDocument->GetDisplayDocument();
2370 if (doc) {
2371 NS_ASSERTION(!aContainerView,
2372 "External resource document embedded somewhere?");
2373 // We want to use our display document's device context if possible
2374 nsPresContext* ctx = doc->GetPresContext();
2375 if (ctx) {
2376 mDeviceContext = ctx->DeviceContext();
2377 return NS_OK;
2381 // Create a device context even if we already have one, since our widget
2382 // might have changed.
2383 nsIWidget* widget = nullptr;
2384 if (aContainerView) {
2385 widget = aContainerView->GetNearestWidget(nullptr);
2387 if (!widget) {
2388 widget = mParentWidget;
2390 if (widget) {
2391 widget = widget->GetTopLevelWidget();
2394 mDeviceContext = new nsDeviceContext();
2395 mDeviceContext->Init(widget);
2396 return NS_OK;
2399 // Return the selection for the document. Note that text fields have their
2400 // own selection, which cannot be accessed with this method.
2401 mozilla::dom::Selection* nsDocumentViewer::GetDocumentSelection() {
2402 if (!mPresShell) {
2403 return nullptr;
2406 return mPresShell->GetCurrentSelection(SelectionType::eNormal);
2409 /* ============================================================================
2410 * nsIContentViewerEdit
2411 * ============================================================================
2414 MOZ_CAN_RUN_SCRIPT_BOUNDARY NS_IMETHODIMP nsDocumentViewer::ClearSelection() {
2415 // use nsCopySupport::GetSelectionForCopy() ?
2416 RefPtr<mozilla::dom::Selection> selection = GetDocumentSelection();
2417 if (!selection) {
2418 return NS_ERROR_FAILURE;
2421 ErrorResult rv;
2422 selection->CollapseToStart(rv);
2423 return rv.StealNSResult();
2426 MOZ_CAN_RUN_SCRIPT_BOUNDARY NS_IMETHODIMP nsDocumentViewer::SelectAll() {
2427 // XXX this is a temporary implementation copied from nsWebShell
2428 // for now. I think Document and friends should have some helper
2429 // functions to make this easier.
2431 // use nsCopySupport::GetSelectionForCopy() ?
2432 RefPtr<mozilla::dom::Selection> selection = GetDocumentSelection();
2433 if (!selection) {
2434 return NS_ERROR_FAILURE;
2437 if (!mDocument) {
2438 return NS_ERROR_FAILURE;
2441 nsCOMPtr<nsINode> bodyNode;
2442 if (mDocument->IsHTMLOrXHTML()) {
2443 // XXXbz why not just do GetBody() for all documents, then GetRootElement()
2444 // if GetBody() is null?
2445 bodyNode = mDocument->GetBody();
2446 } else {
2447 bodyNode = mDocument->GetRootElement();
2449 if (!bodyNode) return NS_ERROR_FAILURE;
2451 ErrorResult err;
2452 selection->RemoveAllRanges(err);
2453 if (err.Failed()) {
2454 return err.StealNSResult();
2457 mozilla::dom::Selection::AutoUserInitiated userSelection(selection);
2458 selection->SelectAllChildren(*bodyNode, err);
2459 return err.StealNSResult();
2462 NS_IMETHODIMP nsDocumentViewer::CopySelection() {
2463 RefPtr<PresShell> presShell = mPresShell;
2464 nsCopySupport::FireClipboardEvent(eCopy, nsIClipboard::kGlobalClipboard,
2465 presShell, nullptr);
2466 return NS_OK;
2469 NS_IMETHODIMP nsDocumentViewer::CopyLinkLocation() {
2470 NS_ENSURE_TRUE(mPresShell, NS_ERROR_NOT_INITIALIZED);
2471 nsCOMPtr<nsINode> node = GetPopupLinkNode();
2472 // make noise if we're not in a link
2473 NS_ENSURE_TRUE(node, NS_ERROR_FAILURE);
2475 nsCOMPtr<dom::Element> elm(do_QueryInterface(node));
2476 NS_ENSURE_TRUE(elm, NS_ERROR_FAILURE);
2478 nsAutoString locationText;
2479 nsContentUtils::GetLinkLocation(elm, locationText);
2480 if (locationText.IsEmpty()) return NS_ERROR_FAILURE;
2482 nsresult rv = NS_OK;
2483 nsCOMPtr<nsIClipboardHelper> clipboard(
2484 do_GetService("@mozilla.org/widget/clipboardhelper;1", &rv));
2485 NS_ENSURE_SUCCESS(rv, rv);
2487 // copy the href onto the clipboard
2488 return clipboard->CopyString(locationText);
2491 NS_IMETHODIMP nsDocumentViewer::CopyImage(int32_t aCopyFlags) {
2492 NS_ENSURE_TRUE(mPresShell, NS_ERROR_NOT_INITIALIZED);
2493 nsCOMPtr<nsIImageLoadingContent> node = GetPopupImageNode();
2494 // make noise if we're not in an image
2495 NS_ENSURE_TRUE(node, NS_ERROR_FAILURE);
2497 nsCOMPtr<nsILoadContext> loadContext(mContainer);
2498 return nsCopySupport::ImageCopy(node, loadContext, aCopyFlags);
2501 NS_IMETHODIMP nsDocumentViewer::GetCopyable(bool* aCopyable) {
2502 NS_ENSURE_ARG_POINTER(aCopyable);
2503 *aCopyable = nsCopySupport::CanCopy(mDocument);
2504 return NS_OK;
2507 NS_IMETHODIMP nsDocumentViewer::GetContents(const char* mimeType,
2508 bool selectionOnly,
2509 nsAString& aOutValue) {
2510 aOutValue.Truncate();
2512 NS_ENSURE_TRUE(mPresShell, NS_ERROR_NOT_INITIALIZED);
2513 NS_ENSURE_TRUE(mDocument, NS_ERROR_NOT_INITIALIZED);
2515 // Now we have the selection. Make sure it's nonzero:
2516 RefPtr<Selection> sel;
2517 if (selectionOnly) {
2518 sel = nsCopySupport::GetSelectionForCopy(mDocument);
2519 NS_ENSURE_TRUE(sel, NS_ERROR_FAILURE);
2521 if (sel->IsCollapsed()) {
2522 return NS_OK;
2526 // call the copy code
2527 return nsCopySupport::GetContents(nsDependentCString(mimeType), 0, sel,
2528 mDocument, aOutValue);
2531 NS_IMETHODIMP nsDocumentViewer::GetCanGetContents(bool* aCanGetContents) {
2532 NS_ENSURE_ARG_POINTER(aCanGetContents);
2533 *aCanGetContents = false;
2534 NS_ENSURE_STATE(mDocument);
2535 *aCanGetContents = nsCopySupport::CanCopy(mDocument);
2536 return NS_OK;
2539 NS_IMETHODIMP nsDocumentViewer::SetCommandNode(nsINode* aNode) {
2540 Document* document = GetDocument();
2541 NS_ENSURE_STATE(document);
2543 nsCOMPtr<nsPIDOMWindowOuter> window(document->GetWindow());
2544 NS_ENSURE_TRUE(window, NS_ERROR_NOT_AVAILABLE);
2546 nsCOMPtr<nsPIWindowRoot> root = window->GetTopWindowRoot();
2547 NS_ENSURE_STATE(root);
2549 root->SetPopupNode(aNode);
2550 return NS_OK;
2553 NS_IMETHODIMP
2554 nsDocumentViewer::GetDeviceFullZoomForTest(float* aDeviceFullZoom) {
2555 NS_ENSURE_ARG_POINTER(aDeviceFullZoom);
2556 nsPresContext* pc = GetPresContext();
2557 *aDeviceFullZoom = pc ? pc->GetDeviceFullZoom() : 1.0;
2558 return NS_OK;
2561 NS_IMETHODIMP
2562 nsDocumentViewer::SetAuthorStyleDisabled(bool aStyleDisabled) {
2563 if (mPresShell) {
2564 mPresShell->SetAuthorStyleDisabled(aStyleDisabled);
2566 return NS_OK;
2569 NS_IMETHODIMP
2570 nsDocumentViewer::GetAuthorStyleDisabled(bool* aStyleDisabled) {
2571 if (mPresShell) {
2572 *aStyleDisabled = mPresShell->GetAuthorStyleDisabled();
2573 } else {
2574 *aStyleDisabled = false;
2576 return NS_OK;
2579 /* [noscript,notxpcom] Encoding getHintCharset (); */
2580 NS_IMETHODIMP_(const Encoding*)
2581 nsDocumentViewer::GetReloadEncodingAndSource(int32_t* aSource) {
2582 *aSource = mReloadEncodingSource;
2583 if (kCharsetUninitialized == mReloadEncodingSource) {
2584 return nullptr;
2586 return mReloadEncoding;
2589 NS_IMETHODIMP_(void)
2590 nsDocumentViewer::SetReloadEncodingAndSource(const Encoding* aEncoding,
2591 int32_t aSource) {
2592 mReloadEncoding = aEncoding;
2593 mReloadEncodingSource = aSource;
2596 NS_IMETHODIMP_(void)
2597 nsDocumentViewer::ForgetReloadEncoding() {
2598 mReloadEncoding = nullptr;
2599 mReloadEncodingSource = kCharsetUninitialized;
2602 nsresult nsDocumentViewer::GetContentSizeInternal(int32_t* aWidth,
2603 int32_t* aHeight,
2604 nscoord aMaxWidth,
2605 nscoord aMaxHeight) {
2606 NS_ENSURE_TRUE(mDocument, NS_ERROR_NOT_AVAILABLE);
2608 RefPtr<PresShell> presShell = GetPresShell();
2609 NS_ENSURE_TRUE(presShell, NS_ERROR_FAILURE);
2611 // Flush out all content and style updates. We can't use a resize reflow
2612 // because it won't change some sizes that a style change reflow will.
2613 mDocument->FlushPendingNotifications(FlushType::Layout);
2615 nsIFrame* root = presShell->GetRootFrame();
2616 NS_ENSURE_TRUE(root, NS_ERROR_FAILURE);
2618 WritingMode wm = root->GetWritingMode();
2620 nscoord prefISize;
2622 RefPtr<gfxContext> rcx(presShell->CreateReferenceRenderingContext());
2623 nscoord maxISize = wm.IsVertical() ? aMaxHeight : aMaxWidth;
2624 prefISize = std::min(root->GetPrefISize(rcx), maxISize);
2627 // We should never intentionally get here with this sentinel value, but it's
2628 // possible that a document with huge sizes might inadvertently have a
2629 // prefISize that exactly matches NS_UNCONSTRAINEDSIZE.
2630 // Just bail if that happens.
2631 NS_ENSURE_TRUE(prefISize != NS_UNCONSTRAINEDSIZE, NS_ERROR_FAILURE);
2633 nscoord height = wm.IsVertical() ? prefISize : aMaxHeight;
2634 nscoord width = wm.IsVertical() ? aMaxWidth : prefISize;
2635 nsresult rv =
2636 presShell->ResizeReflow(width, height, ResizeReflowOptions::BSizeLimit);
2637 NS_ENSURE_SUCCESS(rv, rv);
2639 RefPtr<nsPresContext> presContext = GetPresContext();
2640 NS_ENSURE_TRUE(presContext, NS_ERROR_FAILURE);
2642 // Protect against bogus returns here
2643 nsRect shellArea = presContext->GetVisibleArea();
2644 NS_ENSURE_TRUE(shellArea.width != NS_UNCONSTRAINEDSIZE &&
2645 shellArea.height != NS_UNCONSTRAINEDSIZE,
2646 NS_ERROR_FAILURE);
2648 // Ceil instead of rounding here, so we can actually guarantee showing all the
2649 // content.
2650 *aWidth = std::ceil(presContext->AppUnitsToFloatDevPixels(shellArea.width));
2651 *aHeight = std::ceil(presContext->AppUnitsToFloatDevPixels(shellArea.height));
2653 return NS_OK;
2656 NS_IMETHODIMP
2657 nsDocumentViewer::GetContentSize(int32_t* aWidth, int32_t* aHeight) {
2658 NS_ENSURE_TRUE(mContainer, NS_ERROR_NOT_AVAILABLE);
2660 RefPtr<BrowsingContext> bc = mContainer->GetBrowsingContext();
2661 NS_ENSURE_TRUE(bc, NS_ERROR_NOT_AVAILABLE);
2663 // It's only valid to access this from a top frame. Doesn't work from
2664 // sub-frames.
2665 NS_ENSURE_TRUE(bc->IsTop(), NS_ERROR_FAILURE);
2667 return GetContentSizeInternal(aWidth, aHeight, NS_UNCONSTRAINEDSIZE,
2668 NS_UNCONSTRAINEDSIZE);
2671 NS_IMETHODIMP
2672 nsDocumentViewer::GetContentSizeConstrained(int32_t aMaxWidth,
2673 int32_t aMaxHeight, int32_t* aWidth,
2674 int32_t* aHeight) {
2675 RefPtr<nsPresContext> presContext = GetPresContext();
2676 NS_ENSURE_TRUE(presContext, NS_ERROR_FAILURE);
2678 nscoord maxWidth = NS_UNCONSTRAINEDSIZE;
2679 nscoord maxHeight = NS_UNCONSTRAINEDSIZE;
2680 if (aMaxWidth > 0) {
2681 maxWidth = presContext->DevPixelsToAppUnits(aMaxWidth);
2683 if (aMaxHeight > 0) {
2684 maxHeight = presContext->DevPixelsToAppUnits(aMaxHeight);
2687 return GetContentSizeInternal(aWidth, aHeight, maxWidth, maxHeight);
2690 NS_IMPL_ISUPPORTS(nsDocViewerSelectionListener, nsISelectionListener)
2693 * GetPopupNode, GetPopupLinkNode and GetPopupImageNode are helpers
2694 * for the cmd_copyLink / cmd_copyImageLocation / cmd_copyImageContents family
2695 * of commands. The focus controller stores the popup node, these retrieve
2696 * them and munge appropriately. Note that we have to store the popup node
2697 * rather than retrieving it from EventStateManager::GetFocusedContent because
2698 * not all content (images included) can receive focus.
2701 already_AddRefed<nsINode> nsDocumentViewer::GetPopupNode() {
2702 // get the document
2703 Document* document = GetDocument();
2704 NS_ENSURE_TRUE(document, nullptr);
2706 // get the private dom window
2707 nsCOMPtr<nsPIDOMWindowOuter> window(document->GetWindow());
2708 NS_ENSURE_TRUE(window, nullptr);
2709 if (window) {
2710 nsCOMPtr<nsPIWindowRoot> root = window->GetTopWindowRoot();
2711 NS_ENSURE_TRUE(root, nullptr);
2713 // get the popup node
2714 nsCOMPtr<nsINode> node = root->GetPopupNode();
2715 #ifdef MOZ_XUL
2716 if (!node) {
2717 nsPIDOMWindowOuter* rootWindow = root->GetWindow();
2718 if (rootWindow) {
2719 nsCOMPtr<Document> rootDoc = rootWindow->GetExtantDoc();
2720 if (rootDoc) {
2721 nsXULPopupManager* pm = nsXULPopupManager::GetInstance();
2722 if (pm) {
2723 node = pm->GetLastTriggerPopupNode(rootDoc);
2728 #endif
2729 return node.forget();
2732 return nullptr;
2735 // GetPopupLinkNode: return popup link node or fail
2736 already_AddRefed<nsINode> nsDocumentViewer::GetPopupLinkNode() {
2737 // find popup node
2738 nsCOMPtr<nsINode> node = GetPopupNode();
2740 // find out if we have a link in our ancestry
2741 while (node) {
2742 nsCOMPtr<nsIContent> content(do_QueryInterface(node));
2743 if (content) {
2744 nsCOMPtr<nsIURI> hrefURI = content->GetHrefURI();
2745 if (hrefURI) {
2746 return node.forget();
2750 // get our parent and keep trying...
2751 node = node->GetParentNode();
2754 // if we have no node, fail
2755 return nullptr;
2758 // GetPopupLinkNode: return popup image node or fail
2759 already_AddRefed<nsIImageLoadingContent> nsDocumentViewer::GetPopupImageNode() {
2760 // find popup node
2761 nsCOMPtr<nsINode> node = GetPopupNode();
2762 nsCOMPtr<nsIImageLoadingContent> img = do_QueryInterface(node);
2763 return img.forget();
2767 * XXX dr
2768 * ------
2769 * These two functions -- GetInLink and GetInImage -- are kind of annoying
2770 * in that they only get called from the controller (in
2771 * nsDOMWindowController::IsCommandEnabled). The actual construction of the
2772 * context menus in communicator (nsContextMenu.js) has its own, redundant
2773 * tests. No big deal, but good to keep in mind if we ever clean context
2774 * menus.
2777 NS_IMETHODIMP nsDocumentViewer::GetInLink(bool* aInLink) {
2778 #ifdef DEBUG_dr
2779 printf("dr :: nsDocumentViewer::GetInLink\n");
2780 #endif
2782 NS_ENSURE_ARG_POINTER(aInLink);
2784 // we're not in a link unless i say so
2785 *aInLink = false;
2787 // get the popup link
2788 nsCOMPtr<nsINode> node = GetPopupLinkNode();
2789 if (!node) {
2790 return NS_ERROR_FAILURE;
2793 // if we made it here, we're in a link
2794 *aInLink = true;
2795 return NS_OK;
2798 NS_IMETHODIMP nsDocumentViewer::GetInImage(bool* aInImage) {
2799 #ifdef DEBUG_dr
2800 printf("dr :: nsDocumentViewer::GetInImage\n");
2801 #endif
2803 NS_ENSURE_ARG_POINTER(aInImage);
2805 // we're not in an image unless i say so
2806 *aInImage = false;
2808 // get the popup image
2809 nsCOMPtr<nsIImageLoadingContent> node = GetPopupImageNode();
2810 if (!node) {
2811 return NS_ERROR_FAILURE;
2814 // Make sure there is a URI assigned. This allows <input type="image"> to
2815 // be an image but rejects other <input> types. This matches what
2816 // nsContextMenu.js does.
2817 nsCOMPtr<nsIURI> uri;
2818 node->GetCurrentURI(getter_AddRefs(uri));
2819 if (uri) {
2820 // if we made it here, we're in an image
2821 *aInImage = true;
2824 return NS_OK;
2827 NS_IMETHODIMP nsDocViewerSelectionListener::NotifySelectionChanged(
2828 Document*, Selection*, int16_t aReason) {
2829 if (!mDocViewer) {
2830 return NS_OK;
2833 // get the selection state
2834 RefPtr<mozilla::dom::Selection> selection =
2835 mDocViewer->GetDocumentSelection();
2836 if (!selection) {
2837 return NS_ERROR_FAILURE;
2840 Document* theDoc = mDocViewer->GetDocument();
2841 if (!theDoc) return NS_ERROR_FAILURE;
2843 nsCOMPtr<nsPIDOMWindowOuter> domWindow = theDoc->GetWindow();
2844 if (!domWindow) return NS_ERROR_FAILURE;
2846 bool selectionCollapsed = selection->IsCollapsed();
2847 // We only call UpdateCommands when the selection changes from collapsed to
2848 // non-collapsed or vice versa, however we skip the initializing collapse. We
2849 // might need another update string for simple selection changes, but that
2850 // would be expenseive.
2851 if (mSelectionWasCollapsed != selectionCollapsed) {
2852 domWindow->UpdateCommands(u"select"_ns, selection, aReason);
2853 mSelectionWasCollapsed = selectionCollapsed;
2856 return NS_OK;
2859 // nsDocViewerFocusListener
2860 NS_IMPL_ISUPPORTS(nsDocViewerFocusListener, nsIDOMEventListener)
2862 nsresult nsDocViewerFocusListener::HandleEvent(Event* aEvent) {
2863 NS_ENSURE_STATE(mDocViewer);
2865 RefPtr<PresShell> presShell = mDocViewer->GetPresShell();
2866 NS_ENSURE_TRUE(presShell, NS_ERROR_FAILURE);
2868 RefPtr<nsFrameSelection> selection =
2869 presShell->GetLastFocusedFrameSelection();
2870 NS_ENSURE_TRUE(selection, NS_ERROR_FAILURE);
2871 auto selectionStatus = selection->GetDisplaySelection();
2872 nsAutoString eventType;
2873 aEvent->GetType(eventType);
2874 if (eventType.EqualsLiteral("focus")) {
2875 // If selection was disabled, re-enable it.
2876 if (selectionStatus == nsISelectionController::SELECTION_DISABLED ||
2877 selectionStatus == nsISelectionController::SELECTION_HIDDEN) {
2878 selection->SetDisplaySelection(nsISelectionController::SELECTION_ON);
2879 selection->RepaintSelection(SelectionType::eNormal);
2881 } else {
2882 MOZ_ASSERT(eventType.EqualsLiteral("blur"), "Unexpected event type");
2883 // If selection was on, disable it.
2884 if (selectionStatus == nsISelectionController::SELECTION_ON ||
2885 selectionStatus == nsISelectionController::SELECTION_ATTENTION) {
2886 selection->SetDisplaySelection(
2887 nsISelectionController::SELECTION_DISABLED);
2888 selection->RepaintSelection(SelectionType::eNormal);
2892 return NS_OK;
2895 /** ---------------------------------------------------
2896 * From nsIWebBrowserPrint
2899 #ifdef NS_PRINTING
2901 NS_IMETHODIMP
2902 nsDocumentViewer::Print(nsIPrintSettings* aPrintSettings,
2903 nsIWebProgressListener* aWebProgressListener) {
2904 if (NS_WARN_IF(!mContainer)) {
2905 PR_PL(("Container was destroyed yet we are still trying to use it!"));
2906 return NS_ERROR_FAILURE;
2909 if (NS_WARN_IF(!mDocument) || NS_WARN_IF(!mDeviceContext)) {
2910 PR_PL(("Can't Print without a document and a device context"));
2911 return NS_ERROR_FAILURE;
2914 if (NS_WARN_IF(mPrintJob && mPrintJob->GetIsPrinting())) {
2915 // If we are printing another URL, then exit.
2916 // The reason we check here is because this method can be called while
2917 // another is still in here (the printing dialog is a good example). the
2918 // only time we can print more than one job at a time is the regression
2919 // tests.
2920 nsresult rv = NS_ERROR_NOT_AVAILABLE;
2921 RefPtr<nsPrintJob>(mPrintJob)->FirePrintingErrorEvent(rv);
2922 return rv;
2925 OnDonePrinting();
2926 RefPtr<nsPrintJob> printJob = new nsPrintJob();
2927 nsresult rv =
2928 printJob->Initialize(this, mContainer, mDocument,
2929 float(AppUnitsPerCSSInch()) /
2930 float(mDeviceContext->AppUnitsPerDevPixel()));
2931 if (NS_WARN_IF(NS_FAILED(rv))) {
2932 printJob->Destroy();
2933 return rv;
2936 mPrintJob = printJob;
2937 rv = printJob->Print(mDocument, aPrintSettings, aWebProgressListener);
2938 if (NS_WARN_IF(NS_FAILED(rv))) {
2939 OnDonePrinting();
2941 return rv;
2944 NS_IMETHODIMP
2945 nsDocumentViewer::PrintPreview(nsIPrintSettings* aPrintSettings,
2946 nsIWebProgressListener* aWebProgressListener,
2947 PrintPreviewResolver&& aCallback) {
2948 # ifdef NS_PRINT_PREVIEW
2949 RefPtr<Document> doc = mDocument.get();
2950 NS_ENSURE_STATE(doc);
2952 if (NS_WARN_IF(GetIsPrinting())) {
2953 nsPrintJob::CloseProgressDialog(aWebProgressListener);
2954 return NS_ERROR_FAILURE;
2957 nsCOMPtr<nsIDocShell> docShell(mContainer);
2958 if (NS_WARN_IF(!docShell) || NS_WARN_IF(!mDeviceContext)) {
2959 PR_PL(("Can't Print Preview without device context and docshell"));
2960 return NS_ERROR_FAILURE;
2963 NS_ENSURE_STATE(!GetIsPrinting());
2964 // beforeprint event may have caused ContentViewer to be shutdown.
2965 NS_ENSURE_STATE(mContainer);
2966 NS_ENSURE_STATE(mDeviceContext);
2968 // Our call to nsPrintJob::PrintPreview() may cause mPrintJob to be
2969 // Release()'d in Destroy(). Therefore, we need to grab the instance with
2970 // a local variable, so that it won't be deleted during its own method.
2971 const bool hadPrintJob = !!mPrintJob;
2972 OnDonePrinting();
2974 RefPtr<nsPrintJob> printJob = new nsPrintJob();
2976 nsresult rv =
2977 printJob->Initialize(this, mContainer, doc,
2978 float(AppUnitsPerCSSInch()) /
2979 float(mDeviceContext->AppUnitsPerDevPixel()));
2980 if (NS_WARN_IF(NS_FAILED(rv))) {
2981 printJob->Destroy();
2982 return rv;
2984 mPrintJob = printJob;
2986 if (!hadPrintJob && !StaticPrefs::print_tab_modal_enabled()) {
2987 Telemetry::ScalarAdd(Telemetry::ScalarID::PRINTING_PREVIEW_OPENED, 1);
2989 rv = printJob->PrintPreview(doc, aPrintSettings, aWebProgressListener,
2990 std::move(aCallback));
2991 if (NS_WARN_IF(NS_FAILED(rv))) {
2992 OnDonePrinting();
2994 return rv;
2995 # else
2996 return NS_ERROR_FAILURE;
2997 # endif // NS_PRINT_PREVIEW
3000 nsresult nsDocumentViewer::PrintPreviewScrollToPageForOldUI(int16_t aType,
3001 int32_t aPageNum) {
3002 MOZ_ASSERT(GetIsPrintPreview() && !mPrintJob->GetIsCreatingPrintPreview());
3004 nsIScrollableFrame* sf =
3005 mPrintJob->GetPrintPreviewPresShell()->GetRootScrollFrameAsScrollable();
3006 if (!sf) {
3007 return NS_OK;
3010 // Check to see if we can short circut scrolling to the top
3011 if (aType == nsIWebBrowserPrint::PRINTPREVIEW_HOME ||
3012 (aType == nsIWebBrowserPrint::PRINTPREVIEW_GOTO_PAGENUM &&
3013 aPageNum == 1)) {
3014 sf->ScrollTo(nsPoint(0, 0), ScrollMode::Instant);
3015 return NS_OK;
3018 // in PP mPrtPreview->mPrintObject->mSeqFrame is null
3019 auto [seqFrame, sheetCount] = mPrintJob->GetSeqFrameAndCountSheets();
3020 if (!seqFrame) {
3021 return NS_ERROR_FAILURE;
3024 // Figure where we are currently scrolled to
3025 nsPoint currentScrollPosition = sf->GetScrollPosition();
3027 int32_t pageNum = 1;
3028 nsIFrame* fndPageFrame = nullptr;
3029 nsIFrame* currentPage = nullptr;
3031 // If it is "End" then just do a "goto" to the last page
3032 if (aType == nsIWebBrowserPrint::PRINTPREVIEW_END) {
3033 aType = nsIWebBrowserPrint::PRINTPREVIEW_GOTO_PAGENUM;
3034 aPageNum = sheetCount;
3037 // Now, locate the current page we are on and
3038 // and the page of the page number
3039 for (nsIFrame* sheetFrame : seqFrame->PrincipalChildList()) {
3040 nsRect sheetRect = sheetFrame->GetRect();
3041 if (sheetRect.Contains(sheetRect.x, currentScrollPosition.y)) {
3042 currentPage = sheetFrame;
3044 if (pageNum == aPageNum) {
3045 fndPageFrame = sheetFrame;
3046 break;
3048 pageNum++;
3051 if (aType == nsIWebBrowserPrint::PRINTPREVIEW_PREV_PAGE) {
3052 if (currentPage) {
3053 fndPageFrame = currentPage->GetPrevInFlow();
3054 if (!fndPageFrame) {
3055 return NS_OK;
3057 } else {
3058 return NS_OK;
3060 } else if (aType == nsIWebBrowserPrint::PRINTPREVIEW_NEXT_PAGE) {
3061 if (currentPage) {
3062 fndPageFrame = currentPage->GetNextInFlow();
3063 if (!fndPageFrame) {
3064 return NS_OK;
3066 } else {
3067 return NS_OK;
3069 } else { // If we get here we are doing "GoTo"
3070 if (aPageNum < 0 || aPageNum > sheetCount) {
3071 return NS_OK;
3075 if (fndPageFrame) {
3076 nscoord newYPosn = nscoord(seqFrame->GetPrintPreviewScale() *
3077 fndPageFrame->GetPosition().y);
3078 sf->ScrollTo(nsPoint(currentScrollPosition.x, newYPosn),
3079 ScrollMode::Instant);
3081 return NS_OK;
3084 static const nsIFrame* GetTargetPageFrame(int32_t aTargetPageNum,
3085 nsPageSequenceFrame* aSequenceFrame) {
3086 MOZ_ASSERT(aTargetPageNum > 0 &&
3087 aTargetPageNum <=
3088 aSequenceFrame->PrincipalChildList().GetLength());
3089 return aSequenceFrame->PrincipalChildList().FrameAt(aTargetPageNum - 1);
3092 // Calculate the scroll position where the center of |aFrame| is positioned at
3093 // the center of |aScrollable|'s scroll port for the print preview.
3094 // So what we do for that is;
3095 // 1) Calculate the position of the center of |aFrame| in the print preview
3096 // coordinates.
3097 // 2) Reduce the half height of the scroll port from the result of 1.
3098 static nscoord ScrollPositionForFrame(const nsIFrame* aFrame,
3099 nsIScrollableFrame* aScrollable,
3100 float aPreviewScale) {
3101 // Note that even if the computed scroll position is out of the range of
3102 // the scroll port, it gets clamped in nsIScrollableFrame::ScrollTo.
3103 return nscoord(aPreviewScale * aFrame->GetRect().Center().y -
3104 float(aScrollable->GetScrollPortRect().height) / 2.0f);
3107 //----------------------------------------------------------------------
3108 NS_IMETHODIMP
3109 nsDocumentViewer::PrintPreviewScrollToPage(int16_t aType, int32_t aPageNum) {
3110 if (!GetIsPrintPreview() || mPrintJob->GetIsCreatingPrintPreview())
3111 return NS_ERROR_FAILURE;
3113 if (!StaticPrefs::print_tab_modal_enabled()) {
3114 return PrintPreviewScrollToPageForOldUI(aType, aPageNum);
3117 nsIScrollableFrame* sf =
3118 mPrintJob->GetPrintPreviewPresShell()->GetRootScrollFrameAsScrollable();
3119 if (!sf) return NS_OK;
3121 auto [seqFrame, sheetCount] = mPrintJob->GetSeqFrameAndCountSheets();
3122 Unused << sheetCount;
3123 if (!seqFrame) {
3124 return NS_ERROR_FAILURE;
3127 float previewScale = seqFrame->GetPrintPreviewScale();
3129 nsPoint dest = sf->GetScrollPosition();
3131 switch (aType) {
3132 case nsIWebBrowserPrint::PRINTPREVIEW_HOME:
3133 dest.y = 0;
3134 break;
3135 case nsIWebBrowserPrint::PRINTPREVIEW_END:
3136 dest.y = sf->GetScrollRange().YMost();
3137 break;
3138 case nsIWebBrowserPrint::PRINTPREVIEW_PREV_PAGE:
3139 case nsIWebBrowserPrint::PRINTPREVIEW_NEXT_PAGE: {
3140 auto [currentFrame, currentSheetNumber] = GetCurrentSheetFrameAndNumber();
3141 Unused << currentSheetNumber;
3142 if (!currentFrame) {
3143 return NS_OK;
3146 const nsIFrame* targetFrame = nullptr;
3147 if (aType == nsIWebBrowserPrint::PRINTPREVIEW_PREV_PAGE) {
3148 targetFrame = currentFrame->GetPrevInFlow();
3149 } else {
3150 targetFrame = currentFrame->GetNextInFlow();
3152 if (!targetFrame) {
3153 return NS_OK;
3156 dest.y = ScrollPositionForFrame(targetFrame, sf, previewScale);
3157 break;
3159 case nsIWebBrowserPrint::PRINTPREVIEW_GOTO_PAGENUM: {
3160 if (aPageNum <= 0 || aPageNum > sheetCount) {
3161 return NS_ERROR_INVALID_ARG;
3164 const nsIFrame* targetFrame = GetTargetPageFrame(aPageNum, seqFrame);
3165 MOZ_ASSERT(targetFrame);
3167 dest.y = ScrollPositionForFrame(targetFrame, sf, previewScale);
3168 break;
3170 default:
3171 return NS_ERROR_INVALID_ARG;
3172 break;
3175 sf->ScrollTo(dest, ScrollMode::Instant);
3177 return NS_OK;
3180 std::tuple<const nsIFrame*, int32_t>
3181 nsDocumentViewer::GetCurrentSheetFrameAndNumber() const {
3182 MOZ_ASSERT(mPrintJob);
3183 MOZ_ASSERT(GetIsPrintPreview() && !mPrintJob->GetIsCreatingPrintPreview());
3185 // in PP mPrtPreview->mPrintObject->mSeqFrame is null
3186 auto [seqFrame, sheetCount] = mPrintJob->GetSeqFrameAndCountSheets();
3187 Unused << sheetCount;
3188 if (!seqFrame) {
3189 return {nullptr, 0};
3192 nsIScrollableFrame* sf =
3193 mPrintJob->GetPrintPreviewPresShell()->GetRootScrollFrameAsScrollable();
3194 if (!sf) {
3195 // No scrollable contents, returns 1 even if there are multiple sheets.
3196 return {seqFrame->PrincipalChildList().FirstChild(), 1};
3199 nsPoint currentScrollPosition = sf->GetScrollPosition();
3200 float halfwayPoint =
3201 currentScrollPosition.y + float(sf->GetScrollPortRect().height) / 2.0f;
3202 float lastDistanceFromHalfwayPoint = std::numeric_limits<float>::max();
3203 int32_t sheetNumber = 0;
3204 const nsIFrame* currentSheet = nullptr;
3205 float previewScale = seqFrame->GetPrintPreviewScale();
3206 for (const nsIFrame* sheetFrame : seqFrame->PrincipalChildList()) {
3207 nsRect sheetRect = sheetFrame->GetRect();
3208 sheetNumber++;
3209 currentSheet = sheetFrame;
3211 float bottomOfSheet = sheetRect.YMost() * previewScale;
3212 if (bottomOfSheet < halfwayPoint) {
3213 // If the bottom of the sheet is not yet over the halfway point, iterate
3214 // the next frame to see if the next frame is over the halfway point and
3215 // compare the distance from the halfway point.
3216 lastDistanceFromHalfwayPoint = halfwayPoint - bottomOfSheet;
3217 continue;
3220 float topOfSheet = sheetRect.Y() * previewScale;
3221 if (topOfSheet <= halfwayPoint) {
3222 // If the top of the sheet is not yet over the halfway point or on the
3223 // point, it's the current sheet.
3224 break;
3227 // Now the sheet rect is completely over the halfway point, compare the
3228 // distances from the halfway point.
3229 if ((topOfSheet - halfwayPoint) >= lastDistanceFromHalfwayPoint) {
3230 // If the previous sheet distance is less than or equal to the current
3231 // sheet distance, choose the previous one as the current.
3232 sheetNumber--;
3233 MOZ_ASSERT(sheetNumber > 0);
3234 currentSheet = currentSheet->GetPrevInFlow();
3235 MOZ_ASSERT(currentSheet);
3237 break;
3240 MOZ_ASSERT(sheetNumber <= sheetCount);
3241 return {currentSheet, sheetNumber};
3244 // XXXdholbert As noted in nsIWebBrowserPrint.idl, this API (the IDL attr
3245 // 'printPreviewCurrentPageNumber') is misnamed and needs s/Page/Sheet/. See
3246 // bug 1669762.
3247 NS_IMETHODIMP
3248 nsDocumentViewer::GetPrintPreviewCurrentPageNumber(int32_t* aNumber) {
3249 NS_ENSURE_ARG_POINTER(aNumber);
3250 NS_ENSURE_TRUE(mPrintJob, NS_ERROR_FAILURE);
3251 if (!GetIsPrintPreview() || mPrintJob->GetIsCreatingPrintPreview()) {
3252 return NS_ERROR_FAILURE;
3255 auto [currentFrame, currentSheetNumber] = GetCurrentSheetFrameAndNumber();
3256 Unused << currentFrame;
3257 if (!currentSheetNumber) {
3258 return NS_ERROR_FAILURE;
3261 *aNumber = currentSheetNumber;
3263 return NS_OK;
3266 // XXX This always returns false for subdocuments
3267 NS_IMETHODIMP
3268 nsDocumentViewer::GetDoingPrint(bool* aDoingPrint) {
3269 NS_ENSURE_ARG_POINTER(aDoingPrint);
3271 // XXX shouldn't this be GetDoingPrint() ?
3272 *aDoingPrint = mPrintJob ? mPrintJob->CreatedForPrintPreview() : false;
3273 return NS_OK;
3276 // XXX This always returns false for subdocuments
3277 NS_IMETHODIMP
3278 nsDocumentViewer::GetDoingPrintPreview(bool* aDoingPrintPreview) {
3279 NS_ENSURE_ARG_POINTER(aDoingPrintPreview);
3281 *aDoingPrintPreview = mPrintJob ? mPrintJob->CreatedForPrintPreview() : false;
3282 return NS_OK;
3285 NS_IMETHODIMP
3286 nsDocumentViewer::GetCurrentPrintSettings(
3287 nsIPrintSettings** aCurrentPrintSettings) {
3288 NS_ENSURE_ARG_POINTER(aCurrentPrintSettings);
3290 *aCurrentPrintSettings = nullptr;
3291 NS_ENSURE_TRUE(mPrintJob, NS_ERROR_FAILURE);
3293 *aCurrentPrintSettings = mPrintJob->GetCurrentPrintSettings().take();
3294 return NS_OK;
3297 NS_IMETHODIMP
3298 nsDocumentViewer::Cancel() {
3299 NS_ENSURE_TRUE(mPrintJob, NS_ERROR_FAILURE);
3300 return mPrintJob->Cancel();
3303 NS_IMETHODIMP
3304 nsDocumentViewer::ExitPrintPreview() {
3305 NS_ENSURE_TRUE(mPrintJob, NS_ERROR_FAILURE);
3307 if (GetIsPrinting()) {
3308 // Block exiting the print preview window if we're in the middle of an
3309 // actual print.
3310 return NS_ERROR_FAILURE;
3313 if (!GetIsPrintPreview()) {
3314 NS_ERROR("Wow, we should never get here!");
3315 return NS_OK;
3318 if (!mPrintJob->HasEverPrinted() && !StaticPrefs::print_tab_modal_enabled()) {
3319 Telemetry::ScalarAdd(Telemetry::ScalarID::PRINTING_PREVIEW_CANCELLED, 1);
3322 # ifdef NS_PRINT_PREVIEW
3323 mPrintJob->Destroy();
3324 mPrintJob = nullptr;
3326 // Since the print preview implementation discards the window that was used
3327 // to show the print preview, we skip certain cleanup that we would otherwise
3328 // want to do. Specifically, we do not call `SetIsPrintPreview(false)` to
3329 // unblock navigation, we do not call `SetOverrideDPPX` to reset the
3330 // devicePixelRatio, and we do not call `Show` to make such changes take
3331 // affect.
3332 # endif // NS_PRINT_PREVIEW
3334 return NS_OK;
3337 NS_IMETHODIMP
3338 nsDocumentViewer::GetRawNumPages(int32_t* aRawNumPages) {
3339 NS_ENSURE_ARG_POINTER(aRawNumPages);
3340 NS_ENSURE_TRUE(mPrintJob, NS_ERROR_FAILURE);
3342 *aRawNumPages = mPrintJob->GetRawNumPages();
3343 return *aRawNumPages > 0 ? NS_OK : NS_ERROR_FAILURE;
3346 // XXXdholbert As noted in nsIWebBrowserPrint.idl, this API (the IDL attr
3347 // 'printPreviewNumPages') is misnamed and needs s/Page/Sheet/.
3348 // See bug 1669762.
3349 NS_IMETHODIMP
3350 nsDocumentViewer::GetPrintPreviewNumPages(int32_t* aPrintPreviewNumPages) {
3351 NS_ENSURE_ARG_POINTER(aPrintPreviewNumPages);
3352 NS_ENSURE_TRUE(mPrintJob, NS_ERROR_FAILURE);
3353 *aPrintPreviewNumPages = mPrintJob->GetPrintPreviewNumSheets();
3354 return *aPrintPreviewNumPages > 0 ? NS_OK : NS_ERROR_FAILURE;
3357 //----------------------------------------------------------------------------------
3358 // Printing/Print Preview Helpers
3359 //----------------------------------------------------------------------------------
3361 //----------------------------------------------------------------------------------
3362 // Walks the document tree and tells each DocShell whether Printing/PP is
3363 // happening
3364 #endif // NS_PRINTING
3366 bool nsDocumentViewer::ShouldAttachToTopLevel() {
3367 if (!mParentWidget) {
3368 return false;
3371 if (!mContainer) {
3372 return false;
3375 // We always attach when using puppet widgets
3376 if (nsIWidget::UsePuppetWidgets()) {
3377 return true;
3380 #if defined(XP_WIN) || defined(MOZ_WIDGET_GTK) || \
3381 defined(MOZ_WIDGET_ANDROID) || defined(MOZ_WIDGET_UIKIT)
3382 if (!mPresContext) {
3383 return false;
3386 // On windows, in the parent process we also attach, but just to
3387 // chrome items
3388 nsWindowType winType = mParentWidget->WindowType();
3389 if ((winType == eWindowType_toplevel || winType == eWindowType_dialog ||
3390 winType == eWindowType_invisible) &&
3391 mPresContext->IsChrome()) {
3392 return true;
3394 #endif
3396 return false;
3399 //------------------------------------------------------------
3400 // XXX this always returns false for subdocuments
3401 bool nsDocumentViewer::GetIsPrinting() const {
3402 #ifdef NS_PRINTING
3403 if (mPrintJob) {
3404 return mPrintJob->GetIsPrinting();
3406 #endif
3407 return false;
3410 //------------------------------------------------------------
3411 // The PrintJob holds the current value
3412 // this called from inside the DocViewer.
3413 // XXX it always returns false for subdocuments
3414 bool nsDocumentViewer::GetIsPrintPreview() const {
3415 #ifdef NS_PRINTING
3416 return mPrintJob && mPrintJob->CreatedForPrintPreview();
3417 #else
3418 return false;
3419 #endif
3422 //------------------------------------------------------------
3423 // Notification from the PrintJob of the current PP status
3424 void nsDocumentViewer::SetIsPrintPreview(bool aIsPrintPreview) {
3425 // Protect against pres shell destruction running scripts.
3426 nsAutoScriptBlocker scriptBlocker;
3428 if (!aIsPrintPreview) {
3429 InvalidatePotentialSubDocDisplayItem();
3430 if (mPresShell) {
3431 DestroyPresShell();
3433 mWindow = nullptr;
3434 mViewManager = nullptr;
3435 mPresContext = nullptr;
3436 mPresShell = nullptr;
3440 //----------------------------------------------------------------------------------
3441 // nsIDocumentViewerPrint IFace
3442 //----------------------------------------------------------------------------------
3444 //------------------------------------------------------------
3445 void nsDocumentViewer::IncrementDestroyBlockedCount() {
3446 ++mDestroyBlockedCount;
3449 void nsDocumentViewer::DecrementDestroyBlockedCount() {
3450 --mDestroyBlockedCount;
3453 //------------------------------------------------------------
3454 // This called ONLY when printing has completed and the DV
3455 // is being notified that it should get rid of the nsPrintJob.
3457 // BUT, if we are in Print Preview then we want to ignore the
3458 // notification (we do not get rid of the nsPrintJob)
3460 // One small caveat:
3461 // This IS called from two places in this module for cleaning
3462 // up when an error occurred during the start up printing
3463 // and print preview
3465 void nsDocumentViewer::OnDonePrinting() {
3466 #if defined(NS_PRINTING) && defined(NS_PRINT_PREVIEW)
3467 // If Destroy() has been called during calling nsPrintJob::Print() or
3468 // nsPrintJob::PrintPreview(), mPrintJob is already nullptr here.
3469 // So, the following clean up does nothing in such case.
3470 // (Do we need some of this for that case?)
3471 if (mPrintJob) {
3472 RefPtr<nsPrintJob> printJob = std::move(mPrintJob);
3473 if (GetIsPrintPreview()) {
3474 printJob->DestroyPrintingData();
3475 } else {
3476 printJob->Destroy();
3479 // We are done printing, now clean up.
3481 // For non-print-preview jobs, we are actually responsible for cleaning up
3482 // our whole <browser> or window (see the OPEN_PRINT_BROWSER code), so gotta
3483 // run window.close(), which will take care of this.
3485 // For print preview jobs the front-end code is responsible for cleaning the
3486 // UI.
3487 if (!printJob->CreatedForPrintPreview()) {
3488 if (mContainer) {
3489 if (nsCOMPtr<nsPIDOMWindowOuter> win = mContainer->GetWindow()) {
3490 win->Close();
3493 } else if (mClosingWhilePrinting) {
3494 if (mDocument) {
3495 mDocument->Destroy();
3496 mDocument = nullptr;
3498 mClosingWhilePrinting = false;
3501 #endif // NS_PRINTING && NS_PRINT_PREVIEW
3504 NS_IMETHODIMP nsDocumentViewer::SetPrintSettingsForSubdocument(
3505 nsIPrintSettings* aPrintSettings) {
3506 #ifdef NS_PRINTING
3508 nsAutoScriptBlocker scriptBlocker;
3510 if (mPresShell) {
3511 DestroyPresShell();
3514 if (mPresContext) {
3515 DestroyPresContext();
3518 MOZ_ASSERT(!mPresContext);
3519 MOZ_ASSERT(!mPresShell);
3521 RefPtr<nsIDeviceContextSpec> devspec = new nsDeviceContextSpecProxy();
3522 nsresult rv =
3523 devspec->Init(nullptr, aPrintSettings, /* aIsPrintPreview = */ true);
3524 NS_ENSURE_SUCCESS(rv, rv);
3526 mDeviceContext = new nsDeviceContext();
3527 rv = mDeviceContext->InitForPrinting(devspec);
3529 NS_ENSURE_SUCCESS(rv, rv);
3531 mPresContext = CreatePresContext(
3532 mDocument, nsPresContext::eContext_PrintPreview, FindContainerView());
3533 mPresContext->SetPrintSettings(aPrintSettings);
3534 rv = mPresContext->Init(mDeviceContext);
3535 NS_ENSURE_SUCCESS(rv, rv);
3537 rv = MakeWindow(nsSize(mPresContext->DevPixelsToAppUnits(mBounds.width),
3538 mPresContext->DevPixelsToAppUnits(mBounds.height)),
3539 FindContainerView());
3540 NS_ENSURE_SUCCESS(rv, rv);
3542 MOZ_TRY(InitPresentationStuff(true));
3545 RefPtr<PresShell> shell = mPresShell;
3546 shell->FlushPendingNotifications(FlushType::Layout);
3547 #endif
3548 return NS_OK;
3551 NS_IMETHODIMP nsDocumentViewer::SetPageModeForTesting(
3552 bool aPageMode, nsIPrintSettings* aPrintSettings) {
3553 // XXX Page mode is only partially working; it's currently used for
3554 // reftests that require a paginated context
3555 mIsPageMode = aPageMode;
3557 // The DestroyPresShell call requires a script blocker, since the
3558 // PresShell::Destroy call it does can cause scripts to run, which could
3559 // re-entrantly call methods on the nsDocumentViewer.
3560 nsAutoScriptBlocker scriptBlocker;
3562 if (mPresShell) {
3563 DestroyPresShell();
3566 if (mPresContext) {
3567 DestroyPresContext();
3570 mViewManager = nullptr;
3571 mWindow = nullptr;
3573 NS_ENSURE_STATE(mDocument);
3574 if (aPageMode) {
3575 mPresContext = CreatePresContext(
3576 mDocument, nsPresContext::eContext_PageLayout, FindContainerView());
3577 NS_ENSURE_TRUE(mPresContext, NS_ERROR_OUT_OF_MEMORY);
3578 mPresContext->SetPaginatedScrolling(true);
3579 mPresContext->SetPrintSettings(aPrintSettings);
3580 nsresult rv = mPresContext->Init(mDeviceContext);
3581 NS_ENSURE_SUCCESS(rv, rv);
3583 NS_ENSURE_SUCCESS(InitInternal(mParentWidget, nullptr, nullptr, mBounds, true,
3584 false, false),
3585 NS_ERROR_FAILURE);
3587 Show();
3588 return NS_OK;
3591 NS_IMETHODIMP
3592 nsDocumentViewer::GetHistoryEntry(nsISHEntry** aHistoryEntry) {
3593 NS_IF_ADDREF(*aHistoryEntry = mSHEntry);
3594 return NS_OK;
3597 NS_IMETHODIMP
3598 nsDocumentViewer::GetIsTabModalPromptAllowed(bool* aAllowed) {
3599 *aAllowed = !mHidden;
3600 return NS_OK;
3603 NS_IMETHODIMP
3604 nsDocumentViewer::GetIsHidden(bool* aHidden) {
3605 *aHidden = mHidden;
3606 return NS_OK;
3609 NS_IMETHODIMP
3610 nsDocumentViewer::SetIsHidden(bool aHidden) {
3611 mHidden = aHidden;
3612 return NS_OK;
3615 void nsDocumentViewer::DestroyPresShell() {
3616 // We assert this because destroying the pres shell could otherwise cause
3617 // re-entrancy into nsDocumentViewer methods, and all callers of
3618 // DestroyPresShell need to do other cleanup work afterwards before it
3619 // is safe for those re-entrant method calls to be made.
3620 MOZ_ASSERT(!nsContentUtils::IsSafeToRunScript(),
3621 "DestroyPresShell must only be called when scripts are blocked");
3623 // Break circular reference (or something)
3624 mPresShell->EndObservingDocument();
3626 RefPtr<mozilla::dom::Selection> selection = GetDocumentSelection();
3627 if (selection && mSelectionListener)
3628 selection->RemoveSelectionListener(mSelectionListener);
3630 mPresShell->Destroy();
3631 mPresShell = nullptr;
3634 void nsDocumentViewer::InvalidatePotentialSubDocDisplayItem() {
3635 if (mViewManager) {
3636 if (nsView* rootView = mViewManager->GetRootView()) {
3637 if (nsView* rootViewParent = rootView->GetParent()) {
3638 if (nsView* subdocview = rootViewParent->GetParent()) {
3639 if (nsIFrame* f = subdocview->GetFrame()) {
3640 if (nsSubDocumentFrame* s = do_QueryFrame(f)) {
3641 s->MarkNeedsDisplayItemRebuild();
3650 void nsDocumentViewer::DestroyPresContext() {
3651 InvalidatePotentialSubDocDisplayItem();
3652 mPresContext = nullptr;
3655 void nsDocumentViewer::SetPrintPreviewPresentation(nsViewManager* aViewManager,
3656 nsPresContext* aPresContext,
3657 PresShell* aPresShell) {
3658 // Protect against pres shell destruction running scripts and re-entrantly
3659 // creating a new presentation.
3660 nsAutoScriptBlocker scriptBlocker;
3662 if (mPresShell) {
3663 DestroyPresShell();
3666 mWindow = nullptr;
3667 mViewManager = aViewManager;
3668 mPresContext = aPresContext;
3669 mPresShell = aPresShell;
3671 if (ShouldAttachToTopLevel()) {
3672 DetachFromTopLevelWidget();
3673 nsView* rootView = mViewManager->GetRootView();
3674 rootView->AttachToTopLevelWidget(mParentWidget);
3675 mAttachedToParent = true;
3679 // Fires the "document-shown" event so that interested parties are aware of it.
3680 NS_IMETHODIMP
3681 nsDocumentShownDispatcher::Run() {
3682 nsCOMPtr<nsIObserverService> observerService =
3683 mozilla::services::GetObserverService();
3684 if (observerService) {
3685 observerService->NotifyObservers(ToSupports(mDocument), "document-shown",
3686 nullptr);
3688 return NS_OK;