1 /* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
2 /* vim: set ts=8 sts=2 et sw=2 tw=80: */
3 /* This Source Code Form is subject to the terms of the Mozilla Public
4 * License, v. 2.0. If a copy of the MPL was not distributed with this
5 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
6
7 #include "nsPageSequenceFrame.h"
8
9 #include "mozilla/PresShell.h"
10 #include "mozilla/dom/HTMLCanvasElement.h"
11 #include "mozilla/StaticPresData.h"
12
13 #include "DateTimeFormat.h"
14 #include "nsCOMPtr.h"
15 #include "nsDeviceContext.h"
16 #include "nsPresContext.h"
17 #include "gfxContext.h"
18 #include "nsGkAtoms.h"
19 #include "nsIFrame.h"
20 #include "nsIFrameInlines.h"
21 #include "nsIPrintSettings.h"
22 #include "nsPageFrame.h"
23 #include "nsSubDocumentFrame.h"
24 #include "nsRegion.h"
25 #include "nsCSSFrameConstructor.h"
26 #include "nsContentUtils.h"
27 #include "nsDisplayList.h"
28 #include "nsHTMLCanvasFrame.h"
29 #include "nsICanvasRenderingContextInternal.h"
30 #include "nsServiceManagerUtils.h"
31 #include <algorithm>
32
33 #define OFFSET_NOT_SET -1
34
35 using namespace mozilla;
36 using namespace mozilla::dom;
37
38 #include "mozilla/Logging.h"
39 mozilla::LazyLogModule gLayoutPrintingLog("printing-layout");
40
41 #define PR_PL(_p1) MOZ_LOG(gLayoutPrintingLog, mozilla::LogLevel::Debug, _p1)
42
NS_NewPageSequenceFrame(PresShell * aPresShell,ComputedStyle * aStyle)43 nsPageSequenceFrame* NS_NewPageSequenceFrame(PresShell* aPresShell,
44 ComputedStyle* aStyle) {
45 return new (aPresShell)
46 nsPageSequenceFrame(aStyle, aPresShell->GetPresContext());
47 }
48
NS_IMPL_FRAMEARENA_HELPERS(nsPageSequenceFrame)49 NS_IMPL_FRAMEARENA_HELPERS(nsPageSequenceFrame)
50
51 nsPageSequenceFrame::nsPageSequenceFrame(ComputedStyle* aStyle,
52 nsPresContext* aPresContext)
53 : nsContainerFrame(aStyle, aPresContext, kClassID),
54 mTotalPages(-1),
55 mCalledBeginPage(false),
56 mCurrentCanvasListSetup(false) {
57 nscoord halfInch = PresContext()->CSSTwipsToAppUnits(NS_INCHES_TO_TWIPS(0.5));
58 mMargin.SizeTo(halfInch, halfInch, halfInch, halfInch);
59
60 mPageData = new nsSharedPageData();
61 mPageData->mHeadFootFont =
62 *PresContext()
63 ->Document()
64 ->GetFontPrefsForLang(aStyle->StyleFont()->mLanguage)
65 ->GetDefaultFont(StyleGenericFontFamily::Serif);
66 mPageData->mHeadFootFont.size = nsPresContext::CSSPointsToAppUnits(10);
67
68 // Doing this here so we only have to go get these formats once
69 SetPageNumberFormat("pagenumber", "%1$d", true);
70 SetPageNumberFormat("pageofpages", "%1$d of %2$d", false);
71 }
72
~nsPageSequenceFrame()73 nsPageSequenceFrame::~nsPageSequenceFrame() {
74 delete mPageData;
75 ResetPrintCanvasList();
76 }
77
78 NS_QUERYFRAME_HEAD(nsPageSequenceFrame)
NS_QUERYFRAME_ENTRY(nsPageSequenceFrame)79 NS_QUERYFRAME_ENTRY(nsPageSequenceFrame)
80 NS_QUERYFRAME_TAIL_INHERITING(nsContainerFrame)
81
82 //----------------------------------------------------------------------
83
84 void nsPageSequenceFrame::SetDesiredSize(ReflowOutput& aDesiredSize,
85 const ReflowInput& aReflowInput,
86 nscoord aWidth, nscoord aHeight) {
87 // Aim to fill the whole size of the document, not only so we
88 // can act as a background in print preview but also handle overflow
89 // in child page frames correctly.
90 // Use availableISize so we don't cause a needless horizontal scrollbar.
91 WritingMode wm = aReflowInput.GetWritingMode();
92 nscoord scaledWidth = aWidth * PresContext()->GetPrintPreviewScale();
93 nscoord scaledHeight = aHeight * PresContext()->GetPrintPreviewScale();
94
95 nscoord scaledISize = (wm.IsVertical() ? scaledHeight : scaledWidth);
96 nscoord scaledBSize = (wm.IsVertical() ? scaledWidth : scaledHeight);
97
98 aDesiredSize.ISize(wm) = std::max(scaledISize, aReflowInput.AvailableISize());
99 aDesiredSize.BSize(wm) = std::max(scaledBSize, aReflowInput.ComputedBSize());
100 }
101
102 // Helper function to compute the offset needed to center a child
103 // page-frame's margin-box inside our content-box.
ComputeCenteringMargin(nscoord aContainerContentBoxWidth,nscoord aChildPaddingBoxWidth,const nsMargin & aChildPhysicalMargin)104 nscoord nsPageSequenceFrame::ComputeCenteringMargin(
105 nscoord aContainerContentBoxWidth, nscoord aChildPaddingBoxWidth,
106 const nsMargin& aChildPhysicalMargin) {
107 // We'll be centering our child's margin-box, so get the size of that:
108 nscoord childMarginBoxWidth =
109 aChildPaddingBoxWidth + aChildPhysicalMargin.LeftRight();
110
111 // When rendered, our child's rect will actually be scaled up by the
112 // print-preview scale factor, via ComputePageSequenceTransform().
113 // We really want to center *that scaled-up rendering* inside of
114 // aContainerContentBoxWidth. So, we scale up its margin-box here...
115 auto ppScale = PresContext()->GetPrintPreviewScale();
116 nscoord scaledChildMarginBoxWidth =
117 NSToCoordRound(childMarginBoxWidth * ppScale);
118
119 // ...and see we how much space is left over, when we subtract that scaled-up
120 // size from the container width:
121 nscoord scaledExtraSpace =
122 aContainerContentBoxWidth - scaledChildMarginBoxWidth;
123
124 if (scaledExtraSpace <= 0) {
125 // (Don't bother centering if there's zero/negative space.)
126 return 0;
127 }
128
129 // To center the child, we want to give it an additional left-margin of half
130 // of the extra space. And then, we have to scale that space back down, so
131 // that it'll produce the correct scaled-up amount when we render (because
132 // rendering will scale it back up):
133 return NSToCoordRound(scaledExtraSpace * 0.5 / ppScale);
134 }
135
136 /*
137 * Note: we largely position/size out our children (page frames) using
138 * \*physical\* x/y/width/height values, because the print preview UI is always
139 * arranged in the same orientation, regardless of writing mode.
140 */
Reflow(nsPresContext * aPresContext,ReflowOutput & aDesiredSize,const ReflowInput & aReflowInput,nsReflowStatus & aStatus)141 void nsPageSequenceFrame::Reflow(nsPresContext* aPresContext,
142 ReflowOutput& aDesiredSize,
143 const ReflowInput& aReflowInput,
144 nsReflowStatus& aStatus) {
145 MarkInReflow();
146 MOZ_ASSERT(aPresContext->IsRootPaginatedDocument(),
147 "A Page Sequence is only for real pages");
148 DO_GLOBAL_REFLOW_COUNT("nsPageSequenceFrame");
149 DISPLAY_REFLOW(aPresContext, this, aReflowInput, aDesiredSize, aStatus);
150 MOZ_ASSERT(aStatus.IsEmpty(), "Caller should pass a fresh reflow status!");
151 NS_FRAME_TRACE_REFLOW_IN("nsPageSequenceFrame::Reflow");
152
153 // Don't do incremental reflow until we've taught tables how to do
154 // it right in paginated mode.
155 if (!(GetStateBits() & NS_FRAME_FIRST_REFLOW)) {
156 // Return our desired size
157 SetDesiredSize(aDesiredSize, aReflowInput, mSize.width, mSize.height);
158 aDesiredSize.SetOverflowAreasToDesiredBounds();
159 FinishAndStoreOverflow(&aDesiredSize);
160
161 if (GetRect().Width() != aDesiredSize.Width()) {
162 // Our width is changing; we need to re-center our children (our pages).
163 for (nsFrameList::Enumerator e(mFrames); !e.AtEnd(); e.Next()) {
164 nsIFrame* child = e.get();
165 nsMargin pageCSSMargin = child->GetUsedMargin();
166 nscoord centeringMargin =
167 ComputeCenteringMargin(aReflowInput.ComputedWidth(),
168 child->GetRect().Width(), pageCSSMargin);
169 nscoord newX = pageCSSMargin.left + centeringMargin;
170
171 // Adjust the child's x-position:
172 child->MovePositionBy(nsPoint(newX - child->GetNormalPosition().x, 0));
173 }
174 }
175 return;
176 }
177
178 // See if we can get a Print Settings from the Context
179 if (!mPageData->mPrintSettings &&
180 aPresContext->Medium() == nsGkAtoms::print) {
181 mPageData->mPrintSettings = aPresContext->GetPrintSettings();
182 }
183
184 // now get out margins & edges
185 if (mPageData->mPrintSettings) {
186 nsIntMargin unwriteableTwips;
187 mPageData->mPrintSettings->GetUnwriteableMarginInTwips(unwriteableTwips);
188 NS_ASSERTION(unwriteableTwips.left >= 0 && unwriteableTwips.top >= 0 &&
189 unwriteableTwips.right >= 0 &&
190 unwriteableTwips.bottom >= 0,
191 "Unwriteable twips should be non-negative");
192
193 nsIntMargin marginTwips;
194 mPageData->mPrintSettings->GetMarginInTwips(marginTwips);
195 mMargin = nsPresContext::CSSTwipsToAppUnits(marginTwips + unwriteableTwips);
196
197 int16_t printType;
198 mPageData->mPrintSettings->GetPrintRange(&printType);
199 mPrintRangeType = printType;
200
201 nsIntMargin edgeTwips;
202 mPageData->mPrintSettings->GetEdgeInTwips(edgeTwips);
203
204 // sanity check the values. three inches are sometimes needed
205 int32_t inchInTwips = NS_INCHES_TO_INT_TWIPS(3.0);
206 edgeTwips.top = clamped(edgeTwips.top, 0, inchInTwips);
207 edgeTwips.bottom = clamped(edgeTwips.bottom, 0, inchInTwips);
208 edgeTwips.left = clamped(edgeTwips.left, 0, inchInTwips);
209 edgeTwips.right = clamped(edgeTwips.right, 0, inchInTwips);
210
211 mPageData->mEdgePaperMargin =
212 nsPresContext::CSSTwipsToAppUnits(edgeTwips + unwriteableTwips);
213 }
214
215 // *** Special Override ***
216 // If this is a sub-sdoc (meaning it doesn't take the whole page)
217 // and if this Document is in the upper left hand corner
218 // we need to suppress the top margin or it will reflow too small
219
220 nsSize pageSize = aPresContext->GetPageSize();
221
222 mPageData->mReflowSize = pageSize;
223 mPageData->mReflowMargin = mMargin;
224
225 // We use the CSS "margin" property on the -moz-page pseudoelement
226 // to determine the space between each page in print preview.
227 // Keep a running y-offset for each page.
228 nscoord y = 0;
229 nscoord maxXMost = 0;
230
231 // Tile the pages vertically
232 ReflowOutput kidSize(aReflowInput);
233 for (nsFrameList::Enumerator e(mFrames); !e.AtEnd(); e.Next()) {
234 nsIFrame* kidFrame = e.get();
235 // Set the shared data into the page frame before reflow
236 nsPageFrame* pf = static_cast<nsPageFrame*>(kidFrame);
237 pf->SetSharedPageData(mPageData);
238
239 // Reflow the page
240 ReflowInput kidReflowInput(
241 aPresContext, aReflowInput, kidFrame,
242 LogicalSize(kidFrame->GetWritingMode(), pageSize));
243 nsReflowStatus status;
244
245 kidReflowInput.SetComputedISize(kidReflowInput.AvailableISize());
246 // kidReflowInput.SetComputedHeight(kidReflowInput.AvailableHeight());
247 PR_PL(("AV ISize: %d BSize: %d\n", kidReflowInput.AvailableISize(),
248 kidReflowInput.AvailableBSize()));
249
250 nsMargin pageCSSMargin = kidReflowInput.ComputedPhysicalMargin();
251 y += pageCSSMargin.top;
252
253 nscoord x = pageCSSMargin.left;
254
255 // Place and size the page.
256 ReflowChild(kidFrame, aPresContext, kidSize, kidReflowInput, x, y,
257 ReflowChildFlags::Default, status);
258
259 // If the page is narrower than our width, then center it horizontally:
260 x += ComputeCenteringMargin(aReflowInput.ComputedWidth(), kidSize.Width(),
261 pageCSSMargin);
262
263 FinishReflowChild(kidFrame, aPresContext, kidSize, &kidReflowInput, x, y,
264 ReflowChildFlags::Default);
265 y += kidSize.Height();
266 y += pageCSSMargin.bottom;
267
268 maxXMost = std::max(maxXMost, x + kidSize.Width() + pageCSSMargin.right);
269
270 // Is the page complete?
271 nsIFrame* kidNextInFlow = kidFrame->GetNextInFlow();
272
273 if (status.IsFullyComplete()) {
274 NS_ASSERTION(!kidNextInFlow, "bad child flow list");
275 } else if (!kidNextInFlow) {
276 // The page isn't complete and it doesn't have a next-in-flow, so
277 // create a continuing page.
278 nsIFrame* continuingPage =
279 PresShell()->FrameConstructor()->CreateContinuingFrame(kidFrame,
280 this);
281
282 // Add it to our child list
283 mFrames.InsertFrame(nullptr, kidFrame, continuingPage);
284 }
285 }
286
287 // Get Total Page Count
288 // XXXdholbert technically we could calculate this in the loop above,
289 // instead of needing a separate walk.
290 int32_t pageTot = mFrames.GetLength();
291
292 // Set Page Number Info
293 int32_t pageNum = 1;
294 for (nsFrameList::Enumerator e(mFrames); !e.AtEnd(); e.Next()) {
295 MOZ_ASSERT(e.get()->IsPageFrame(),
296 "only expecting nsPageFrame children. Other children will make "
297 "this static_cast bogus & probably violate other assumptions");
298 nsPageFrame* pf = static_cast<nsPageFrame*>(e.get());
299 pf->SetPageNumInfo(pageNum, pageTot);
300 pageNum++;
301 }
302
303 nsAutoString formattedDateString;
304 PRTime now = PR_Now();
305 if (NS_SUCCEEDED(DateTimeFormat::FormatPRTime(
306 kDateFormatShort, kTimeFormatNoSeconds, now, formattedDateString))) {
307 SetDateTimeStr(formattedDateString);
308 }
309
310 // Return our desired size
311 // Adjust the reflow size by PrintPreviewScale so the scrollbars end up the
312 // correct size
313 SetDesiredSize(aDesiredSize, aReflowInput, maxXMost, y);
314
315 aDesiredSize.SetOverflowAreasToDesiredBounds();
316 FinishAndStoreOverflow(&aDesiredSize);
317
318 // cache the size so we can set the desired size
319 // for the other reflows that happen
320 mSize.width = maxXMost;
321 mSize.height = y;
322
323 NS_FRAME_TRACE_REFLOW_OUT("nsPageSequenceFrame::Reflow", aStatus);
324 NS_FRAME_SET_TRUNCATION(aStatus, aReflowInput, aDesiredSize);
325 }
326
327 //----------------------------------------------------------------------
328
329 #ifdef DEBUG_FRAME_DUMP
GetFrameName(nsAString & aResult) const330 nsresult nsPageSequenceFrame::GetFrameName(nsAString& aResult) const {
331 return MakeFrameName(NS_LITERAL_STRING("PageSequence"), aResult);
332 }
333 #endif
334
335 //====================================================================
336 //== Asynch Printing
337 //====================================================================
GetPrintRange(int32_t * aFromPage,int32_t * aToPage) const338 void nsPageSequenceFrame::GetPrintRange(int32_t* aFromPage,
339 int32_t* aToPage) const {
340 *aFromPage = mFromPageNum;
341 *aToPage = mToPageNum;
342 }
343
344 // Helper Function
SetPageNumberFormat(const char * aPropName,const char * aDefPropVal,bool aPageNumOnly)345 void nsPageSequenceFrame::SetPageNumberFormat(const char* aPropName,
346 const char* aDefPropVal,
347 bool aPageNumOnly) {
348 // Doing this here so we only have to go get these formats once
349 nsAutoString pageNumberFormat;
350 // Now go get the Localized Page Formating String
351 nsresult rv = nsContentUtils::GetLocalizedString(
352 nsContentUtils::ePRINTING_PROPERTIES, aPropName, pageNumberFormat);
353 if (NS_FAILED(rv)) { // back stop formatting
354 pageNumberFormat.AssignASCII(aDefPropVal);
355 }
356
357 SetPageNumberFormat(pageNumberFormat, aPageNumOnly);
358 }
359
StartPrint(nsPresContext * aPresContext,nsIPrintSettings * aPrintSettings,const nsAString & aDocTitle,const nsAString & aDocURL)360 nsresult nsPageSequenceFrame::StartPrint(nsPresContext* aPresContext,
361 nsIPrintSettings* aPrintSettings,
362 const nsAString& aDocTitle,
363 const nsAString& aDocURL) {
364 NS_ENSURE_ARG_POINTER(aPresContext);
365 NS_ENSURE_ARG_POINTER(aPrintSettings);
366
367 if (!mPageData->mPrintSettings) {
368 mPageData->mPrintSettings = aPrintSettings;
369 }
370
371 if (!aDocTitle.IsEmpty()) {
372 mPageData->mDocTitle = aDocTitle;
373 }
374 if (!aDocURL.IsEmpty()) {
375 mPageData->mDocURL = aDocURL;
376 }
377
378 aPrintSettings->GetStartPageRange(&mFromPageNum);
379 aPrintSettings->GetEndPageRange(&mToPageNum);
380 aPrintSettings->GetPageRanges(mPageRanges);
381
382 mDoingPageRange =
383 nsIPrintSettings::kRangeSpecifiedPageRange == mPrintRangeType;
384
385 // If printing a range of pages make sure at least the starting page
386 // number is valid
387 mTotalPages = mFrames.GetLength();
388
389 if (mDoingPageRange) {
390 if (mFromPageNum > mTotalPages) {
391 return NS_ERROR_INVALID_ARG;
392 }
393 }
394
395 // Begin printing of the document
396 nsresult rv = NS_OK;
397
398 mPageNum = 1;
399
400 return rv;
401 }
402
GetPrintCanvasElementsInFrame(nsIFrame * aFrame,nsTArray<RefPtr<HTMLCanvasElement>> * aArr)403 static void GetPrintCanvasElementsInFrame(
404 nsIFrame* aFrame, nsTArray<RefPtr<HTMLCanvasElement> >* aArr) {
405 if (!aFrame) {
406 return;
407 }
408 for (const auto& childList : aFrame->ChildLists()) {
409 for (nsIFrame* child : childList.mList) {
410 // Check if child is a nsHTMLCanvasFrame.
411 nsHTMLCanvasFrame* canvasFrame = do_QueryFrame(child);
412
413 // If there is a canvasFrame, try to get actual canvas element.
414 if (canvasFrame) {
415 HTMLCanvasElement* canvas =
416 HTMLCanvasElement::FromNodeOrNull(canvasFrame->GetContent());
417 if (canvas && canvas->GetMozPrintCallback()) {
418 aArr->AppendElement(canvas);
419 continue;
420 }
421 }
422
423 if (!child->PrincipalChildList().FirstChild()) {
424 nsSubDocumentFrame* subdocumentFrame = do_QueryFrame(child);
425 if (subdocumentFrame) {
426 // Descend into the subdocument
427 nsIFrame* root = subdocumentFrame->GetSubdocumentRootFrame();
428 child = root;
429 }
430 }
431 // The current child is not a nsHTMLCanvasFrame OR it is but there is
432 // no HTMLCanvasElement on it. Check if children of `child` might
433 // contain a HTMLCanvasElement.
434 GetPrintCanvasElementsInFrame(child, aArr);
435 }
436 }
437 }
438
DetermineWhetherToPrintPage()439 void nsPageSequenceFrame::DetermineWhetherToPrintPage() {
440 // See whether we should print this page
441 mPrintThisPage = true;
442 bool printEvenPages, printOddPages;
443 mPageData->mPrintSettings->GetPrintOptions(nsIPrintSettings::kPrintEvenPages,
444 &printEvenPages);
445 mPageData->mPrintSettings->GetPrintOptions(nsIPrintSettings::kPrintOddPages,
446 &printOddPages);
447
448 // If printing a range of pages check whether the page number is in the
449 // range of pages to print
450 if (mDoingPageRange) {
451 if (mPageNum < mFromPageNum) {
452 mPrintThisPage = false;
453 } else if (mPageNum > mToPageNum) {
454 mPageNum++;
455 mPrintThisPage = false;
456 return;
457 } else {
458 int32_t length = mPageRanges.Length();
459
460 // Page ranges are pairs (start, end)
461 if (length && (length % 2 == 0)) {
462 mPrintThisPage = false;
463
464 int32_t i;
465 for (i = 0; i < length; i += 2) {
466 if (mPageRanges[i] <= mPageNum && mPageNum <= mPageRanges[i + 1]) {
467 mPrintThisPage = true;
468 break;
469 }
470 }
471 }
472 }
473 }
474
475 // Check for printing of odd and even pages
476 if (mPageNum & 0x1) {
477 if (!printOddPages) {
478 mPrintThisPage = false; // don't print odd numbered page
479 }
480 } else {
481 if (!printEvenPages) {
482 mPrintThisPage = false; // don't print even numbered page
483 }
484 }
485 }
486
GetCurrentPageFrame()487 nsIFrame* nsPageSequenceFrame::GetCurrentPageFrame() {
488 int32_t i = 1;
489 for (nsFrameList::Enumerator childFrames(mFrames); !childFrames.AtEnd();
490 childFrames.Next()) {
491 if (i == mPageNum) {
492 return childFrames.get();
493 }
494 ++i;
495 }
496 return nullptr;
497 }
498
PrePrintNextPage(nsITimerCallback * aCallback,bool * aDone)499 nsresult nsPageSequenceFrame::PrePrintNextPage(nsITimerCallback* aCallback,
500 bool* aDone) {
501 nsIFrame* currentPage = GetCurrentPageFrame();
502 if (!currentPage) {
503 *aDone = true;
504 return NS_ERROR_FAILURE;
505 }
506
507 DetermineWhetherToPrintPage();
508 // Nothing to do if the current page doesn't get printed OR rendering to
509 // preview. For preview, the `CallPrintCallback` is called from within the
510 // HTMLCanvasElement::HandlePrintCallback.
511 if (!mPrintThisPage || !PresContext()->IsRootPaginatedDocument()) {
512 *aDone = true;
513 return NS_OK;
514 }
515
516 // If the canvasList is null, then generate it and start the render
517 // process for all the canvas.
518 if (!mCurrentCanvasListSetup) {
519 mCurrentCanvasListSetup = true;
520 GetPrintCanvasElementsInFrame(currentPage, &mCurrentCanvasList);
521
522 if (mCurrentCanvasList.Length() != 0) {
523 nsresult rv = NS_OK;
524
525 // Begin printing of the document
526 nsDeviceContext* dc = PresContext()->DeviceContext();
527 PR_PL(("\n"));
528 PR_PL(("***************** BeginPage *****************\n"));
529 rv = dc->BeginPage();
530 NS_ENSURE_SUCCESS(rv, rv);
531
532 mCalledBeginPage = true;
533
534 RefPtr<gfxContext> renderingContext = dc->CreateRenderingContext();
535 NS_ENSURE_TRUE(renderingContext, NS_ERROR_OUT_OF_MEMORY);
536
537 DrawTarget* drawTarget = renderingContext->GetDrawTarget();
538 if (NS_WARN_IF(!drawTarget)) {
539 return NS_ERROR_FAILURE;
540 }
541
542 for (int32_t i = mCurrentCanvasList.Length() - 1; i >= 0; i--) {
543 HTMLCanvasElement* canvas = mCurrentCanvasList[i];
544 nsIntSize size = canvas->GetSize();
545
546 RefPtr<DrawTarget> canvasTarget =
547 drawTarget->CreateSimilarDrawTarget(size, drawTarget->GetFormat());
548 if (!canvasTarget) {
549 continue;
550 }
551
552 nsICanvasRenderingContextInternal* ctx = canvas->GetContextAtIndex(0);
553 if (!ctx) {
554 continue;
555 }
556
557 // Initialize the context with the new DrawTarget.
558 ctx->InitializeWithDrawTarget(nullptr, WrapNotNull(canvasTarget));
559
560 // Start the rendering process.
561 // Note: Other than drawing to our CanvasRenderingContext2D, the
562 // callback cannot access or mutate our static clone document. It is
563 // evaluated in its original context (the window of the original
564 // document) of course, and our canvas has a strong ref to the
565 // original HTMLCanvasElement (in mOriginalCanvas) so that if the
566 // callback calls GetCanvas() on our CanvasRenderingContext2D (passed
567 // to it via a MozCanvasPrintState argument) it will be given the
568 // original 'canvas' element.
569 AutoWeakFrame weakFrame = this;
570 canvas->DispatchPrintCallback(aCallback);
571 NS_ENSURE_STATE(weakFrame.IsAlive());
572 }
573 }
574 }
575 uint32_t doneCounter = 0;
576 for (int32_t i = mCurrentCanvasList.Length() - 1; i >= 0; i--) {
577 HTMLCanvasElement* canvas = mCurrentCanvasList[i];
578
579 if (canvas->IsPrintCallbackDone()) {
580 doneCounter++;
581 }
582 }
583 // If all canvas have finished rendering, return true, otherwise false.
584 *aDone = doneCounter == mCurrentCanvasList.Length();
585
586 return NS_OK;
587 }
588
ResetPrintCanvasList()589 void nsPageSequenceFrame::ResetPrintCanvasList() {
590 for (int32_t i = mCurrentCanvasList.Length() - 1; i >= 0; i--) {
591 HTMLCanvasElement* canvas = mCurrentCanvasList[i];
592 canvas->ResetPrintCallback();
593 }
594
595 mCurrentCanvasList.Clear();
596 mCurrentCanvasListSetup = false;
597 }
598
PrintNextPage()599 nsresult nsPageSequenceFrame::PrintNextPage() {
600 // Note: When print al the pages or a page range the printed page shows the
601 // actual page number, when printing selection it prints the page number
602 // starting with the first page of the selection. For example if the user has
603 // a selection that starts on page 2 and ends on page 3, the page numbers when
604 // print are 1 and then two (which is different than printing a page range,
605 // where the page numbers would have been 2 and then 3)
606
607 nsIFrame* currentPageFrame = GetCurrentPageFrame();
608 if (!currentPageFrame) {
609 return NS_ERROR_FAILURE;
610 }
611
612 nsresult rv = NS_OK;
613
614 DetermineWhetherToPrintPage();
615
616 if (mPrintThisPage) {
617 nsDeviceContext* dc = PresContext()->DeviceContext();
618
619 if (PresContext()->IsRootPaginatedDocument()) {
620 if (!mCalledBeginPage) {
621 // We must make sure BeginPage() has been called since some printing
622 // backends can't give us a valid rendering context for a [physical]
623 // page otherwise.
624 PR_PL(("\n"));
625 PR_PL(("***************** BeginPage *****************\n"));
626 rv = dc->BeginPage();
627 NS_ENSURE_SUCCESS(rv, rv);
628 }
629 }
630
631 PR_PL(
632 ("SeqFr::PrintNextPage -> %p PageNo: %d", currentPageFrame, mPageNum));
633
634 // CreateRenderingContext can fail
635 RefPtr<gfxContext> gCtx = dc->CreateRenderingContext();
636 NS_ENSURE_TRUE(gCtx, NS_ERROR_OUT_OF_MEMORY);
637
638 nsRect drawingRect(nsPoint(0, 0), currentPageFrame->GetSize());
639 nsRegion drawingRegion(drawingRect);
640 nsLayoutUtils::PaintFrame(gCtx, currentPageFrame, drawingRegion,
641 NS_RGBA(0, 0, 0, 0),
642 nsDisplayListBuilderMode::Painting,
643 nsLayoutUtils::PaintFrameFlags::SyncDecodeImages);
644 }
645 return rv;
646 }
647
DoPageEnd()648 nsresult nsPageSequenceFrame::DoPageEnd() {
649 nsresult rv = NS_OK;
650 if (PresContext()->IsRootPaginatedDocument() && mPrintThisPage) {
651 PR_PL(("***************** End Page (DoPageEnd) *****************\n"));
652 rv = PresContext()->DeviceContext()->EndPage();
653 NS_ENSURE_SUCCESS(rv, rv);
654 }
655
656 ResetPrintCanvasList();
657 mCalledBeginPage = false;
658
659 mPageNum++;
660
661 return rv;
662 }
663
ComputePageSequenceTransform(nsIFrame * aFrame,float aAppUnitsPerPixel)664 inline gfx::Matrix4x4 ComputePageSequenceTransform(nsIFrame* aFrame,
665 float aAppUnitsPerPixel) {
666 float scale = aFrame->PresContext()->GetPrintPreviewScale();
667 return gfx::Matrix4x4::Scaling(scale, scale, 1);
668 }
669
BuildDisplayList(nsDisplayListBuilder * aBuilder,const nsDisplayListSet & aLists)670 void nsPageSequenceFrame::BuildDisplayList(nsDisplayListBuilder* aBuilder,
671 const nsDisplayListSet& aLists) {
672 aBuilder->SetInPageSequence(true);
673 aBuilder->SetDisablePartialUpdates(true);
674 DisplayBorderBackgroundOutline(aBuilder, aLists);
675
676 nsDisplayList content;
677
678 {
679 // Clear clip state while we construct the children of the
680 // nsDisplayTransform, since they'll be in a different coordinate system.
681 DisplayListClipState::AutoSaveRestore clipState(aBuilder);
682 clipState.Clear();
683
684 nsIFrame* child = PrincipalChildList().FirstChild();
685 nsRect visible = aBuilder->GetVisibleRect();
686 visible.ScaleInverseRoundOut(PresContext()->GetPrintPreviewScale());
687
688 while (child) {
689 if (child->GetVisualOverflowRectRelativeToParent().Intersects(visible)) {
690 nsDisplayListBuilder::AutoBuildingDisplayList buildingForChild(
691 aBuilder, child, visible - child->GetPosition(),
692 visible - child->GetPosition());
693 child->BuildDisplayListForStackingContext(aBuilder, &content);
694 aBuilder->ResetMarkedFramesForDisplayList(this);
695 }
696 child = child->GetNextSibling();
697 }
698 }
699
700 content.AppendNewToTop<nsDisplayTransform>(aBuilder, this, &content,
701 content.GetBuildingRect(),
702 ::ComputePageSequenceTransform);
703
704 aLists.Content()->AppendToTop(&content);
705 aBuilder->SetInPageSequence(false);
706 }
707
708 //------------------------------------------------------------------------------
SetPageNumberFormat(const nsAString & aFormatStr,bool aForPageNumOnly)709 void nsPageSequenceFrame::SetPageNumberFormat(const nsAString& aFormatStr,
710 bool aForPageNumOnly) {
711 NS_ASSERTION(mPageData != nullptr, "mPageData string cannot be null!");
712
713 if (aForPageNumOnly) {
714 mPageData->mPageNumFormat = aFormatStr;
715 } else {
716 mPageData->mPageNumAndTotalsFormat = aFormatStr;
717 }
718 }
719
720 //------------------------------------------------------------------------------
SetDateTimeStr(const nsAString & aDateTimeStr)721 void nsPageSequenceFrame::SetDateTimeStr(const nsAString& aDateTimeStr) {
722 NS_ASSERTION(mPageData != nullptr, "mPageData string cannot be null!");
723
724 mPageData->mDateTimeStr = aDateTimeStr;
725 }
726
AppendDirectlyOwnedAnonBoxes(nsTArray<OwnedAnonBox> & aResult)727 void nsPageSequenceFrame::AppendDirectlyOwnedAnonBoxes(
728 nsTArray<OwnedAnonBox>& aResult) {
729 if (mFrames.NotEmpty()) {
730 aResult.AppendElement(mFrames.FirstChild());
731 }
732 }
733