forked from Floorp-Projects/Floorp
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathnsPrintJob.cpp
3423 lines (2921 loc) · 117 KB
/
nsPrintJob.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* vim: set ts=8 sts=2 et sw=2 tw=80: */
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
#include "nsPrintJob.h"
#include "nsDocShell.h"
#include "nsIStringBundle.h"
#include "nsReadableUtils.h"
#include "nsCRT.h"
#include "mozilla/AsyncEventDispatcher.h"
#include "mozilla/ComputedStyleInlines.h"
#include "mozilla/dom/BrowsingContext.h"
#include "mozilla/dom/Selection.h"
#include "mozilla/dom/CustomEvent.h"
#include "mozilla/dom/ScriptSettings.h"
#include "nsIScriptGlobalObject.h"
#include "nsPIDOMWindow.h"
#include "nsIDocShell.h"
#include "nsIURI.h"
#include "nsITextToSubURI.h"
#include "nsError.h"
#include "nsView.h"
#include <algorithm>
// Print Options
#include "nsIPrintSettings.h"
#include "nsIPrintSettingsService.h"
#include "nsIPrintSession.h"
#include "nsGfxCIID.h"
#include "nsIServiceManager.h"
#include "nsGkAtoms.h"
#include "nsXPCOM.h"
#include "nsISupportsPrimitives.h"
static const char sPrintSettingsServiceContractID[] =
"@mozilla.org/gfx/printsettings-service;1";
#include "nsThreadUtils.h"
// Printing
#include "nsIWebBrowserPrint.h"
// Print Preview
#include "imgIContainer.h" // image animation mode constants
// Print Progress
#include "nsIPrintProgress.h"
#include "nsIPrintProgressParams.h"
#include "nsIObserver.h"
// Print error dialog
#include "nsIPrompt.h"
#include "nsIWindowWatcher.h"
// Printing Prompts
#include "nsIPrintingPromptService.h"
static const char kPrintingPromptService[] =
"@mozilla.org/embedcomp/printingprompt-service;1";
// Printing Timer
#include "nsPagePrintTimer.h"
// FrameSet
#include "mozilla/dom/Document.h"
#include "mozilla/dom/DocumentInlines.h"
// Focus
#include "nsISelectionController.h"
// Misc
#include "gfxContext.h"
#include "mozilla/gfx/DrawEventRecorder.h"
#include "mozilla/layout/RemotePrintJobChild.h"
#include "nsISupportsUtils.h"
#include "nsIScriptContext.h"
#include "nsIDocumentObserver.h"
#include "nsISelectionListener.h"
#include "nsContentCID.h"
#include "nsLayoutCID.h"
#include "nsContentUtils.h"
#include "nsLayoutStylesheetCache.h"
#include "nsLayoutUtils.h"
#include "mozilla/Preferences.h"
#include "mozilla/PresShell.h"
#include "Text.h"
#include "nsWidgetsCID.h"
#include "nsIDeviceContextSpec.h"
#include "nsDeviceContextSpecProxy.h"
#include "nsViewManager.h"
#include "nsPageSequenceFrame.h"
#include "nsIURL.h"
#include "nsIContentViewerEdit.h"
#include "nsIInterfaceRequestor.h"
#include "nsIInterfaceRequestorUtils.h"
#include "nsIDocShellTreeOwner.h"
#include "nsIWebBrowserChrome.h"
#include "nsIBaseWindow.h"
#include "nsILayoutHistoryState.h"
#include "nsFrameManager.h"
#include "mozilla/ReflowInput.h"
#include "nsIContentViewer.h"
#include "nsIDocumentViewerPrint.h"
#include "nsFocusManager.h"
#include "nsRange.h"
#include "nsIURIFixup.h"
#include "mozilla/Components.h"
#include "mozilla/dom/Element.h"
#include "mozilla/dom/HTMLFrameElement.h"
#include "nsContentList.h"
#include "nsIChannel.h"
#include "PrintPreviewUserEventSuppressor.h"
#include "xpcpublic.h"
#include "nsVariant.h"
#include "mozilla/ServoStyleSet.h"
using namespace mozilla;
using namespace mozilla::dom;
//-----------------------------------------------------
// PR LOGGING
#include "mozilla/Logging.h"
#ifdef DEBUG
// PR_LOGGING is force to always be on (even in release builds)
// but we only want some of it on,
//#define EXTENDED_DEBUG_PRINTING
#endif
// this log level turns on the dumping of each document's layout info
#define DUMP_LAYOUT_LEVEL (static_cast<mozilla::LogLevel>(9))
#ifndef PR_PL
static mozilla::LazyLogModule gPrintingLog("printing");
# define PR_PL(_p1) MOZ_LOG(gPrintingLog, mozilla::LogLevel::Debug, _p1);
#endif
#ifdef EXTENDED_DEBUG_PRINTING
static uint32_t gDumpFileNameCnt = 0;
static uint32_t gDumpLOFileNameCnt = 0;
#endif
#define PRT_YESNO(_p) ((_p) ? "YES" : "NO")
static const char* gFrameTypesStr[] = {"eDoc", "eFrame", "eIFrame",
"eFrameSet"};
static const char* gPrintRangeStr[] = {
"kRangeAllPages", "kRangeSpecifiedPageRange", "kRangeSelection"};
// This processes the selection on aOrigDoc and creates an inverted selection on
// aDoc, which it then deletes. If the start or end of the inverted selection
// ranges occur in text nodes then an ellipsis is added.
static nsresult DeleteUnselectedNodes(Document* aOrigDoc, Document* aDoc);
#ifdef EXTENDED_DEBUG_PRINTING
// Forward Declarations
static void DumpPrintObjectsListStart(const char* aStr,
const nsTArray<nsPrintObject*>& aDocList);
static void DumpPrintObjectsTree(nsPrintObject* aPO, int aLevel = 0,
FILE* aFD = nullptr);
static void DumpPrintObjectsTreeLayout(const UniquePtr<nsPrintObject>& aPO,
nsDeviceContext* aDC, int aLevel = 0,
FILE* aFD = nullptr);
# define DUMP_DOC_LIST(_title) \
DumpPrintObjectsListStart((_title), mPrt->mPrintDocList);
# define DUMP_DOC_TREE DumpPrintObjectsTree(mPrt->mPrintObject.get());
# define DUMP_DOC_TREELAYOUT \
DumpPrintObjectsTreeLayout(mPrt->mPrintObject, mPrt->mPrintDC);
#else
# define DUMP_DOC_LIST(_title)
# define DUMP_DOC_TREE
# define DUMP_DOC_TREELAYOUT
#endif
class nsScriptSuppressor {
public:
explicit nsScriptSuppressor(nsPrintJob* aPrintJob)
: mPrintJob(aPrintJob), mSuppressed(false) {}
~nsScriptSuppressor() { Unsuppress(); }
void Suppress() {
if (mPrintJob) {
mSuppressed = true;
mPrintJob->TurnScriptingOn(false);
}
}
void Unsuppress() {
if (mPrintJob && mSuppressed) {
mPrintJob->TurnScriptingOn(true);
}
mSuppressed = false;
}
void Disconnect() { mPrintJob = nullptr; }
protected:
RefPtr<nsPrintJob> mPrintJob;
bool mSuppressed;
};
// -------------------------------------------------------
// Helpers
// -------------------------------------------------------
static bool HasFramesetChild(nsIContent* aContent) {
if (!aContent) {
return false;
}
// do a breadth search across all siblings
for (nsIContent* child = aContent->GetFirstChild(); child;
child = child->GetNextSibling()) {
if (child->IsHTMLElement(nsGkAtoms::frameset)) {
return true;
}
}
return false;
}
static bool IsParentAFrameSet(nsIDocShell* aParent) {
// See if the incoming doc is the root document
if (!aParent) return false;
// When it is the top level document we need to check
// to see if it contains a frameset. If it does, then
// we only want to print the doc's children and not the document itself
// For anything else we always print all the children and the document
// for example, if the doc contains an IFRAME we eant to print the child
// document (the IFRAME) and then the rest of the document.
//
// XXX we really need to search the frame tree, and not the content
// but there is no way to distinguish between IFRAMEs and FRAMEs
// with the GetFrameType call.
// Bug 53459 has been files so we can eventually distinguish
// between IFRAME frames and FRAME frames
bool isFrameSet = false;
// only check to see if there is a frameset if there is
// NO parent doc for this doc. meaning this parent is the root doc
nsCOMPtr<Document> doc = aParent->GetDocument();
if (doc) {
nsIContent* rootElement = doc->GetRootElement();
if (rootElement) {
isFrameSet = HasFramesetChild(rootElement);
}
}
return isFrameSet;
}
static nsPrintObject* FindPrintObjectByDOMWin(nsPrintObject* aPO,
nsPIDOMWindowOuter* aDOMWin) {
NS_ASSERTION(aPO, "Pointer is null!");
// Often the CurFocused DOMWindow is passed in
// andit is valid for it to be null, so short circut
if (!aDOMWin) {
return nullptr;
}
nsCOMPtr<Document> doc = aDOMWin->GetDoc();
if (aPO->mDocument && aPO->mDocument->GetOriginalDocument() == doc) {
return aPO;
}
for (const UniquePtr<nsPrintObject>& kid : aPO->mKids) {
nsPrintObject* po = FindPrintObjectByDOMWin(kid.get(), aDOMWin);
if (po) {
return po;
}
}
return nullptr;
}
static void GetDocumentTitleAndURL(Document* aDoc, nsAString& aTitle,
nsAString& aURLStr) {
NS_ASSERTION(aDoc, "Pointer is null!");
aTitle.Truncate();
aURLStr.Truncate();
aDoc->GetTitle(aTitle);
nsIURI* url = aDoc->GetDocumentURI();
if (!url) return;
nsCOMPtr<nsIURIFixup> urifixup(components::URIFixup::Service());
if (!urifixup) return;
nsCOMPtr<nsIURI> exposableURI;
urifixup->CreateExposableURI(url, getter_AddRefs(exposableURI));
if (!exposableURI) return;
nsAutoCString urlCStr;
nsresult rv = exposableURI->GetSpec(urlCStr);
if (NS_FAILED(rv)) return;
nsCOMPtr<nsITextToSubURI> textToSubURI =
do_GetService(NS_ITEXTTOSUBURI_CONTRACTID, &rv);
if (NS_FAILED(rv)) return;
textToSubURI->UnEscapeURIForUI(NS_LITERAL_CSTRING("UTF-8"), urlCStr, aURLStr);
}
static nsresult GetSeqFrameAndCountPagesInternal(
const UniquePtr<nsPrintObject>& aPO, nsIFrame*& aSeqFrame,
int32_t& aCount) {
NS_ENSURE_ARG_POINTER(aPO);
// This is sometimes incorrectly called before the pres shell has been created
// (bug 1141756). MOZ_DIAGNOSTIC_ASSERT so we'll still see the crash in
// Nightly/Aurora in case the other patch fixes this.
if (!aPO->mPresShell) {
MOZ_DIAGNOSTIC_ASSERT(
false, "GetSeqFrameAndCountPages needs a non-null pres shell");
return NS_ERROR_FAILURE;
}
aSeqFrame = aPO->mPresShell->GetPageSequenceFrame();
if (!aSeqFrame) {
return NS_ERROR_FAILURE;
}
// count the total number of pages
aCount = aSeqFrame->PrincipalChildList().GetLength();
return NS_OK;
}
/**
* Recursively sets the PO items to be printed "As Is"
* from the given item down into the treei
*/
static void SetPrintAsIs(nsPrintObject* aPO, bool aAsIs = true) {
NS_ASSERTION(aPO, "Pointer is null!");
aPO->mPrintAsIs = aAsIs;
for (const UniquePtr<nsPrintObject>& kid : aPO->mKids) {
SetPrintAsIs(kid.get(), aAsIs);
}
}
/**
* This method is key to the entire print mechanism.
*
* This "maps" or figures out which sub-doc represents a
* given Frame or IFrame in its parent sub-doc.
*
* So the Mcontent pointer in the child sub-doc points to the
* content in the its parent document, that caused it to be printed.
* This is used later to (after reflow) to find the absolute location
* of the sub-doc on its parent's page frame so it can be
* printed in the correct location.
*
* This method recursvely "walks" the content for a document finding
* all the Frames and IFrames, then sets the "mFrameType" data member
* which tells us what type of PO we have
*/
static void MapContentForPO(const UniquePtr<nsPrintObject>& aPO,
nsIContent* aContent) {
MOZ_ASSERT(aPO && aContent, "Null argument");
Document* doc = aContent->GetComposedDoc();
NS_ASSERTION(doc, "Content without a document from a document tree?");
Document* subDoc = doc->GetSubDocumentFor(aContent);
if (subDoc) {
nsCOMPtr<nsIDocShell> docShell(subDoc->GetDocShell());
if (docShell) {
nsPrintObject* po = nullptr;
for (const UniquePtr<nsPrintObject>& kid : aPO->mKids) {
if (kid->mDocument == subDoc) {
po = kid.get();
break;
}
}
// XXX If a subdocument has no onscreen presentation, there will be no PO
// This is even if there should be a print presentation
if (po) {
// "frame" elements not in a frameset context should be treated
// as iframes
if (aContent->IsHTMLElement(nsGkAtoms::frame) &&
po->mParent->mFrameType == eFrameSet) {
po->mFrameType = eFrame;
} else {
// Assume something iframe-like, i.e. iframe, object, or embed
po->mFrameType = eIFrame;
SetPrintAsIs(po, true);
NS_ASSERTION(po->mParent, "The root must be a parent");
po->mParent->mPrintAsIs = true;
}
}
}
}
// walk children content
for (nsIContent* child = aContent->GetFirstChild(); child;
child = child->GetNextSibling()) {
MapContentForPO(aPO, child);
}
}
/**
* The walks the PO tree and for each document it walks the content
* tree looking for any content that are sub-shells
*
* It then sets the mContent pointer in the "found" PO object back to the
* the document that contained it.
*/
static void MapContentToWebShells(const UniquePtr<nsPrintObject>& aRootPO,
const UniquePtr<nsPrintObject>& aPO) {
NS_ASSERTION(aRootPO, "Pointer is null!");
NS_ASSERTION(aPO, "Pointer is null!");
// Recursively walk the content from the root item
// XXX Would be faster to enumerate the subdocuments, although right now
// Document doesn't expose quite what would be needed.
nsCOMPtr<nsIContentViewer> viewer;
aPO->mDocShell->GetContentViewer(getter_AddRefs(viewer));
if (!viewer) return;
nsCOMPtr<Document> doc = viewer->GetDocument();
if (!doc) return;
Element* rootElement = doc->GetRootElement();
if (rootElement) {
MapContentForPO(aPO, rootElement);
} else {
NS_WARNING("Null root content on (sub)document.");
}
// Continue recursively walking the chilren of this PO
for (const UniquePtr<nsPrintObject>& kid : aPO->mKids) {
MapContentToWebShells(aRootPO, kid);
}
}
/**
* The outparam aDocList returns a (depth first) flat list of all the
* nsPrintObjects created.
*/
static void BuildNestedPrintObjects(BrowsingContext* aBrowsingContext,
const UniquePtr<nsPrintObject>& aPO,
nsTArray<nsPrintObject*>* aDocList) {
MOZ_ASSERT(aBrowsingContext, "Pointer is null!");
MOZ_ASSERT(aDocList, "Pointer is null!");
MOZ_ASSERT(aPO, "Pointer is null!");
for (auto& childBC : aBrowsingContext->GetChildren()) {
auto window = childBC->GetDOMWindow();
if (!window) {
// XXXfission - handle OOP-iframes
continue;
}
auto childPO = MakeUnique<nsPrintObject>();
nsresult rv = childPO->InitAsNestedObject(
childBC->GetDocShell(), window->GetExtantDoc(), aPO.get());
if (NS_FAILED(rv)) {
MOZ_ASSERT_UNREACHABLE("Init failed?");
}
aPO->mKids.AppendElement(std::move(childPO));
aDocList->AppendElement(aPO->mKids.LastElement().get());
BuildNestedPrintObjects(childBC, aPO->mKids.LastElement(), aDocList);
}
}
/**
* On platforms that support it, sets the printer name stored in the
* nsIPrintSettings to the default printer if a printer name is not already
* set.
* XXXjwatt: Why is this necessary? Can't the code that reads the printer
* name later "just" use the default printer if a name isn't specified? Then
* we wouldn't have this inconsistency between platforms and processes.
*/
static nsresult EnsureSettingsHasPrinterNameSet(
nsIPrintSettings* aPrintSettings) {
#if defined(XP_MACOSX) || defined(ANDROID)
// Mac doesn't support retrieving a printer list.
return NS_OK;
#else
# if defined(MOZ_X11)
// On Linux, default printer name should be requested on the parent side.
// Unless we are in the parent, we ignore this function
if (!XRE_IsParentProcess()) {
return NS_OK;
}
# endif
NS_ENSURE_ARG_POINTER(aPrintSettings);
// See if aPrintSettings already has a printer
nsString printerName;
nsresult rv = aPrintSettings->GetPrinterName(printerName);
if (NS_SUCCEEDED(rv) && !printerName.IsEmpty()) {
return NS_OK;
}
// aPrintSettings doesn't have a printer set. Try to fetch the default.
nsCOMPtr<nsIPrintSettingsService> printSettingsService =
do_GetService(sPrintSettingsServiceContractID, &rv);
NS_ENSURE_SUCCESS(rv, rv);
rv = printSettingsService->GetDefaultPrinterName(printerName);
if (NS_SUCCEEDED(rv) && !printerName.IsEmpty()) {
rv = aPrintSettings->SetPrinterName(printerName);
}
return rv;
#endif
}
static bool DocHasPrintCallbackCanvas(Document* aDoc, void* aData) {
if (!aDoc) {
return true;
}
Element* root = aDoc->GetRootElement();
if (!root) {
return true;
}
RefPtr<nsContentList> canvases =
NS_GetContentList(root, kNameSpaceID_XHTML, NS_LITERAL_STRING("canvas"));
uint32_t canvasCount = canvases->Length(true);
for (uint32_t i = 0; i < canvasCount; ++i) {
HTMLCanvasElement* canvas =
HTMLCanvasElement::FromNodeOrNull(canvases->Item(i, false));
if (canvas && canvas->GetMozPrintCallback()) {
// This subdocument has a print callback. Set result and return false to
// stop iteration.
*static_cast<bool*>(aData) = true;
return false;
}
}
return true;
}
static bool AnySubdocHasPrintCallbackCanvas(Document* aDoc) {
bool result = false;
aDoc->EnumerateSubDocuments(&DocHasPrintCallbackCanvas,
static_cast<void*>(&result));
return result;
}
//-------------------------------------------------------
NS_IMPL_ISUPPORTS(nsPrintJob, nsIWebProgressListener, nsISupportsWeakReference,
nsIObserver)
//-------------------------------------------------------
nsPrintJob::~nsPrintJob() {
Destroy(); // for insurance
DisconnectPagePrintTimer();
}
//-------------------------------------------------------
void nsPrintJob::Destroy() {
if (mIsDestroying) {
return;
}
mIsDestroying = true;
mPrt = nullptr;
#ifdef NS_PRINT_PREVIEW
mPrtPreview = nullptr;
mOldPrtPreview = nullptr;
#endif
mDocViewerPrint = nullptr;
}
//-------------------------------------------------------
void nsPrintJob::DestroyPrintingData() { mPrt = nullptr; }
//---------------------------------------------------------------------------------
//-- Section: Methods needed by the DocViewer
//---------------------------------------------------------------------------------
//--------------------------------------------------------
nsresult nsPrintJob::Initialize(nsIDocumentViewerPrint* aDocViewerPrint,
nsIDocShell* aDocShell, Document* aOriginalDoc,
float aScreenDPI) {
NS_ENSURE_ARG_POINTER(aDocViewerPrint);
NS_ENSURE_ARG_POINTER(aDocShell);
NS_ENSURE_ARG_POINTER(aOriginalDoc);
mDocViewerPrint = aDocViewerPrint;
mDocShell = do_GetWeakReference(aDocShell);
mScreenDPI = aScreenDPI;
// XXX We should not be storing this. The original document that the user
// selected to print can be mutated while print preview is open. Anything
// we need to know about the original document should be checked and stored
// here instead.
mOriginalDoc = aOriginalDoc;
// Anything state that we need from aOriginalDoc must be fetched and stored
// here, since the document that the user selected to print may mutate
// across consecutive PrintPreview() calls.
Element* root = aOriginalDoc->GetRootElement();
mDisallowSelectionPrint =
root &&
root->HasAttr(kNameSpaceID_None, nsGkAtoms::mozdisallowselectionprint);
nsCOMPtr<nsIDocShellTreeOwner> owner;
aDocShell->GetTreeOwner(getter_AddRefs(owner));
nsCOMPtr<nsIWebBrowserChrome> browserChrome = do_GetInterface(owner);
if (browserChrome) {
browserChrome->IsWindowModal(&mIsForModalWindow);
}
bool hasMozPrintCallback = false;
DocHasPrintCallbackCanvas(aOriginalDoc,
static_cast<void*>(&hasMozPrintCallback));
mHasMozPrintCallback =
hasMozPrintCallback || AnySubdocHasPrintCallbackCanvas(aOriginalDoc);
return NS_OK;
}
//-------------------------------------------------------
nsresult nsPrintJob::Cancel() {
if (mPrt && mPrt->mPrintSettings) {
return mPrt->mPrintSettings->SetIsCancelled(true);
}
return NS_ERROR_FAILURE;
}
//-------------------------------------------------------
// Install our event listeners on the document to prevent
// some events from being processed while in PrintPreview
//
// No return code - if this fails, there isn't much we can do
void nsPrintJob::SuppressPrintPreviewUserEvents() {
if (!mPrt->mPPEventSuppressor) {
nsCOMPtr<nsIDocShell> docShell = do_QueryReferent(mDocShell);
if (!docShell) {
return;
}
if (nsPIDOMWindowOuter* win = docShell->GetWindow()) {
nsCOMPtr<EventTarget> target = win->GetFrameElementInternal();
mPrt->mPPEventSuppressor = new PrintPreviewUserEventSuppressor(target);
}
}
}
//-----------------------------------------------------------------
nsresult nsPrintJob::GetSeqFrameAndCountPages(nsIFrame*& aSeqFrame,
int32_t& aCount) {
MOZ_ASSERT(mPrtPreview);
// Guarantee that mPrintPreview->mPrintObject won't be deleted during a call
// of GetSeqFrameAndCountPagesInternal().
RefPtr<nsPrintData> printDataForPrintPreview = mPrtPreview;
return GetSeqFrameAndCountPagesInternal(
printDataForPrintPreview->mPrintObject, aSeqFrame, aCount);
}
//---------------------------------------------------------------------------------
//-- Done: Methods needed by the DocViewer
//---------------------------------------------------------------------------------
//---------------------------------------------------------------------------------
//-- Section: nsIWebBrowserPrint
//---------------------------------------------------------------------------------
// Foward decl for Debug Helper Functions
#ifdef EXTENDED_DEBUG_PRINTING
# ifdef XP_WIN
static int RemoveFilesInDir(const char* aDir);
# endif
static void GetDocTitleAndURL(const UniquePtr<nsPrintObject>& aPO,
nsACString& aDocStr, nsACString& aURLStr);
static void DumpPrintObjectsTree(nsPrintObject* aPO, int aLevel, FILE* aFD);
static void DumpPrintObjectsList(const nsTArray<nsPrintObject*>& aDocList);
static void RootFrameList(nsPresContext* aPresContext, FILE* out,
const char* aPrefix);
static void DumpViews(nsIDocShell* aDocShell, FILE* out);
static void DumpLayoutData(const char* aTitleStr, const char* aURLStr,
nsPresContext* aPresContext, nsDeviceContext* aDC,
nsIFrame* aRootFrame, nsIDocShell* aDocShell,
FILE* aFD);
#endif
//--------------------------------------------------------------------------------
nsresult nsPrintJob::CommonPrint(bool aIsPrintPreview,
nsIPrintSettings* aPrintSettings,
nsIWebProgressListener* aWebProgressListener,
Document* aSourceDoc) {
// Callers must hold a strong reference to |this| to ensure that we stay
// alive for the duration of this method, because our main owning reference
// (on nsDocumentViewer) might be cleared during this function (if we cause
// script to run and it cancels the print operation).
nsresult rv = DoCommonPrint(aIsPrintPreview, aPrintSettings,
aWebProgressListener, aSourceDoc);
if (NS_FAILED(rv)) {
if (aIsPrintPreview) {
mIsCreatingPrintPreview = false;
SetIsPrintPreview(false);
} else {
SetIsPrinting(false);
}
if (mProgressDialogIsShown) CloseProgressDialog(aWebProgressListener);
if (rv != NS_ERROR_ABORT && rv != NS_ERROR_OUT_OF_MEMORY) {
FirePrintingErrorEvent(rv);
}
mPrt = nullptr;
}
return rv;
}
nsresult nsPrintJob::DoCommonPrint(bool aIsPrintPreview,
nsIPrintSettings* aPrintSettings,
nsIWebProgressListener* aWebProgressListener,
Document* aSourceDoc) {
nsresult rv;
if (aIsPrintPreview) {
// The WebProgressListener can be QI'ed to nsIPrintingPromptService
// then that means the progress dialog is already being shown.
nsCOMPtr<nsIPrintingPromptService> pps(
do_QueryInterface(aWebProgressListener));
mProgressDialogIsShown = pps != nullptr;
if (mIsDoingPrintPreview) {
mOldPrtPreview = std::move(mPrtPreview);
}
} else {
mProgressDialogIsShown = false;
}
// Grab the new instance with local variable to guarantee that it won't be
// deleted during this method.
mPrt = new nsPrintData(aIsPrintPreview ? nsPrintData::eIsPrintPreview
: nsPrintData::eIsPrinting);
RefPtr<nsPrintData> printData = mPrt;
// if they don't pass in a PrintSettings, then get the Global PS
printData->mPrintSettings = aPrintSettings;
if (!printData->mPrintSettings) {
rv = GetGlobalPrintSettings(getter_AddRefs(printData->mPrintSettings));
NS_ENSURE_SUCCESS(rv, rv);
}
rv = EnsureSettingsHasPrinterNameSet(printData->mPrintSettings);
NS_ENSURE_SUCCESS(rv, rv);
printData->mPrintSettings->SetIsCancelled(false);
printData->mPrintSettings->GetShrinkToFit(&printData->mShrinkToFit);
if (aIsPrintPreview) {
mIsCreatingPrintPreview = true;
SetIsPrintPreview(true);
nsCOMPtr<nsIContentViewer> viewer = do_QueryInterface(mDocViewerPrint);
if (viewer) {
viewer->SetTextZoom(1.0f);
viewer->SetFullZoom(1.0f);
}
}
// Create a print session and let the print settings know about it.
// Don't overwrite an existing print session.
// The print settings hold an nsWeakPtr to the session so it does not
// need to be cleared from the settings at the end of the job.
// XXX What lifetime does the printSession need to have?
nsCOMPtr<nsIPrintSession> printSession;
bool remotePrintJobListening = false;
if (!aIsPrintPreview) {
rv = printData->mPrintSettings->GetPrintSession(
getter_AddRefs(printSession));
if (NS_FAILED(rv) || !printSession) {
printSession = do_CreateInstance("@mozilla.org/gfx/printsession;1", &rv);
NS_ENSURE_SUCCESS(rv, rv);
printData->mPrintSettings->SetPrintSession(printSession);
} else {
RefPtr<layout::RemotePrintJobChild> remotePrintJob =
printSession->GetRemotePrintJob();
if (remotePrintJob) {
// If we have a RemotePrintJob add it to the print progress listeners,
// so it can forward to the parent.
printData->mPrintProgressListeners.AppendElement(remotePrintJob);
remotePrintJobListening = true;
}
}
}
if (aWebProgressListener != nullptr) {
printData->mPrintProgressListeners.AppendObject(aWebProgressListener);
}
// Get the currently focused window and cache it
// because the Print Dialog will "steal" focus and later when you try
// to get the currently focused windows it will be nullptr
printData->mCurrentFocusWin = FindFocusedDOMWindow();
// Check to see if there is a "regular" selection
bool isSelection = IsThereARangeSelection(printData->mCurrentFocusWin);
// Get the docshell for this documentviewer
nsCOMPtr<nsIDocShell> docShell(do_QueryReferent(mDocShell, &rv));
NS_ENSURE_SUCCESS(rv, rv);
{
nsAutoScriptBlocker scriptBlocker;
printData->mPrintObject = MakeUnique<nsPrintObject>();
rv = printData->mPrintObject->InitAsRootObject(docShell, aSourceDoc,
aIsPrintPreview);
NS_ENSURE_SUCCESS(rv, rv);
NS_ENSURE_TRUE(
printData->mPrintDocList.AppendElement(printData->mPrintObject.get()),
NS_ERROR_OUT_OF_MEMORY);
printData->mIsParentAFrameSet = IsParentAFrameSet(docShell);
printData->mPrintObject->mFrameType =
printData->mIsParentAFrameSet ? eFrameSet : eDoc;
BuildNestedPrintObjects(nsDocShell::Cast(printData->mPrintObject->mDocShell)
->GetBrowsingContext(),
printData->mPrintObject, &printData->mPrintDocList);
}
// The nsAutoScriptBlocker above will now have been destroyed, which may
// cause our print/print-preview operation to finish. In this case, we
// should immediately return an error code so that the root caller knows
// it shouldn't continue to do anything with this instance.
if (mIsDestroying || (aIsPrintPreview && !mIsCreatingPrintPreview)) {
return NS_ERROR_FAILURE;
}
if (!aIsPrintPreview) {
SetIsPrinting(true);
}
// XXX This isn't really correct...
if (!printData->mPrintObject->mDocument ||
!printData->mPrintObject->mDocument->GetRootElement())
return NS_ERROR_GFX_PRINTER_STARTDOC;
// Create the linkage from the sub-docs back to the content element
// in the parent document
MapContentToWebShells(printData->mPrintObject, printData->mPrintObject);
printData->mIsIFrameSelected = IsThereAnIFrameSelected(
docShell, printData->mCurrentFocusWin, printData->mIsParentAFrameSet);
// Now determine how to set up the Frame print UI
printData->mPrintSettings->SetPrintOptions(
nsIPrintSettings::kEnableSelectionRB,
isSelection || printData->mIsIFrameSelected);
bool printingViaParent =
XRE_IsContentProcess() && Preferences::GetBool("print.print_via_parent");
nsCOMPtr<nsIDeviceContextSpec> devspec;
if (printingViaParent) {
devspec = new nsDeviceContextSpecProxy();
} else {
devspec = do_CreateInstance("@mozilla.org/gfx/devicecontextspec;1", &rv);
NS_ENSURE_SUCCESS(rv, rv);
}
nsScriptSuppressor scriptSuppressor(this);
// If printing via parent we still call ShowPrintDialog even for print preview
// because we use that to retrieve the print settings from the printer.
// The dialog is not shown, but this means we don't need to access the printer
// driver from the child, which causes sandboxing issues.
if (!aIsPrintPreview || printingViaParent) {
scriptSuppressor.Suppress();
bool printSilently;
printData->mPrintSettings->GetPrintSilent(&printSilently);
// Check prefs for a default setting as to whether we should print silently
printSilently =
Preferences::GetBool("print.always_print_silent", printSilently);
// Ask dialog to be Print Shown via the Plugable Printing Dialog Service
// This service is for the Print Dialog and the Print Progress Dialog
// If printing silently or you can't get the service continue on
// If printing via the parent then we need to confirm that the pref is set
// and get a remote print job, but the parent won't display a prompt.
if (!printSilently || printingViaParent) {
nsCOMPtr<nsIPrintingPromptService> printPromptService(
do_GetService(kPrintingPromptService));
if (printPromptService) {
nsPIDOMWindowOuter* domWin = nullptr;
// We leave domWin as nullptr to indicate a call for print preview.
if (!aIsPrintPreview) {
domWin = mOriginalDoc->GetWindow();
NS_ENSURE_TRUE(domWin, NS_ERROR_FAILURE);
}
// Platforms not implementing a given dialog for the service may
// return NS_ERROR_NOT_IMPLEMENTED or an error code.
//
// NS_ERROR_NOT_IMPLEMENTED indicates they want default behavior
// Any other error code means we must bail out
//
nsCOMPtr<nsIWebBrowserPrint> wbp(do_QueryInterface(mDocViewerPrint));
rv = printPromptService->ShowPrintDialog(domWin, wbp,
printData->mPrintSettings);
//
// ShowPrintDialog triggers an event loop which means we can't assume
// that the state of this->{anything} matches the state we've checked
// above. Including that a given {thing} is non null.
if (NS_WARN_IF(mPrt != printData)) {
return NS_ERROR_FAILURE;
}
if (NS_SUCCEEDED(rv)) {
// since we got the dialog and it worked then make sure we
// are telling GFX we want to print silent
printSilently = true;
if (printData->mPrintSettings && !aIsPrintPreview) {
// The user might have changed shrink-to-fit in the print dialog, so
// update our copy of its state
printData->mPrintSettings->GetShrinkToFit(&printData->mShrinkToFit);
// If we haven't already added the RemotePrintJob as a listener,
// add it now if there is one.
if (!remotePrintJobListening) {
RefPtr<layout::RemotePrintJobChild> remotePrintJob =
printSession->GetRemotePrintJob();
if (remotePrintJob) {
printData->mPrintProgressListeners.AppendElement(
remotePrintJob);
remotePrintJobListening = true;
}
}
}
} else if (rv == NS_ERROR_NOT_IMPLEMENTED) {
// This means the Dialog service was there,
// but they choose not to implement this dialog and
// are looking for default behavior from the toolkit
rv = NS_OK;
}
} else {
// No dialog service available
rv = NS_ERROR_NOT_IMPLEMENTED;
}
} else {
// Call any code that requires a run of the event loop.
rv = printData->mPrintSettings->SetupSilentPrinting();
}
// Check explicitly for abort because it's expected
if (rv == NS_ERROR_ABORT) return rv;
NS_ENSURE_SUCCESS(rv, rv);
}
rv = devspec->Init(nullptr, printData->mPrintSettings, aIsPrintPreview);
NS_ENSURE_SUCCESS(rv, rv);
printData->mPrintDC = new nsDeviceContext();
rv = printData->mPrintDC->InitForPrinting(devspec);
NS_ENSURE_SUCCESS(rv, rv);
if (XRE_IsParentProcess() && !printData->mPrintDC->IsSyncPagePrinting()) {
RefPtr<nsPrintJob> self(this);
printData->mPrintDC->RegisterPageDoneCallback(
[self](nsresult aResult) { self->PageDone(aResult); });
}
if (aIsPrintPreview) {
// override any UI that wants to PrintPreview any selection or page range
// we want to view every page in PrintPreview each time
printData->mPrintSettings->SetPrintRange(nsIPrintSettings::kRangeAllPages);
}
if (NS_FAILED(EnablePOsForPrinting())) {
return NS_ERROR_FAILURE;
}
// Attach progressListener to catch network requests.
nsCOMPtr<nsIWebProgress> webProgress =
do_QueryInterface(printData->mPrintObject->mDocShell);
webProgress->AddProgressListener(static_cast<nsIWebProgressListener*>(this),
nsIWebProgress::NOTIFY_STATE_REQUEST);
mLoadCounter = 0;
mDidLoadDataForPrinting = false;
if (aIsPrintPreview) {
bool notifyOnInit = false;
ShowPrintProgress(false, notifyOnInit);
// Very important! Turn Off scripting