tor-browser

The Tor Browser
git clone https://git.dasho.dev/tor-browser.git
Log | Files | Refs | README | LICENSE

nsPageSequenceFrame.cpp (29824B)


      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 <algorithm>
     10 
     11 #include "gfxContext.h"
     12 #include "mozilla/Logging.h"
     13 #include "mozilla/PresShell.h"
     14 #include "mozilla/PrintedSheetFrame.h"
     15 #include "mozilla/StaticPresData.h"
     16 #include "mozilla/dom/HTMLCanvasElement.h"
     17 #include "mozilla/gfx/Point.h"
     18 #include "mozilla/intl/AppDateTimeFormat.h"
     19 #include "nsCOMPtr.h"
     20 #include "nsCSSFrameConstructor.h"
     21 #include "nsContentUtils.h"
     22 #include "nsDeviceContext.h"
     23 #include "nsDisplayList.h"
     24 #include "nsGkAtoms.h"
     25 #include "nsHTMLCanvasFrame.h"
     26 #include "nsICanvasRenderingContextInternal.h"
     27 #include "nsIFrame.h"
     28 #include "nsIFrameInlines.h"
     29 #include "nsIPrintSettings.h"
     30 #include "nsPageFrame.h"
     31 #include "nsPresContext.h"
     32 #include "nsRegion.h"
     33 #include "nsServiceManagerUtils.h"
     34 #include "nsSubDocumentFrame.h"
     35 
     36 using namespace mozilla;
     37 using namespace mozilla::dom;
     38 
     39 mozilla::LazyLogModule gLayoutPrintingLog("printing-layout");
     40 
     41 #define PR_PL(_p1) MOZ_LOG(gLayoutPrintingLog, mozilla::LogLevel::Debug, _p1)
     42 
     43 nsPageSequenceFrame* NS_NewPageSequenceFrame(PresShell* aPresShell,
     44                                             ComputedStyle* aStyle) {
     45  return new (aPresShell)
     46      nsPageSequenceFrame(aStyle, aPresShell->GetPresContext());
     47 }
     48 
     49 NS_IMPL_FRAMEARENA_HELPERS(nsPageSequenceFrame)
     50 
     51 static const nsPagesPerSheetInfo kSupportedPagesPerSheet[] = {
     52    /* Members are: {mNumPages, mLargerNumTracks} */
     53    // clang-format off
     54    {1, 1},
     55    {2, 2},
     56    {4, 2},
     57    {6, 3},
     58    {9, 3},
     59    {16, 4},
     60    // clang-format on
     61 };
     62 
     63 inline void SanityCheckPagesPerSheetInfo() {
     64 #ifdef DEBUG
     65  // Sanity-checks:
     66  MOZ_ASSERT(std::size(kSupportedPagesPerSheet) > 0,
     67             "Should have at least one pages-per-sheet option.");
     68  MOZ_ASSERT(kSupportedPagesPerSheet[0].mNumPages == 1,
     69             "The 0th index is reserved for default 1-page-per-sheet entry");
     70 
     71  uint16_t prevInfoPPS = 0;
     72  for (const auto& info : kSupportedPagesPerSheet) {
     73    MOZ_ASSERT(info.mNumPages > prevInfoPPS,
     74               "page count field should be positive & monotonically increase");
     75    MOZ_ASSERT(info.mLargerNumTracks > 0,
     76               "page grid has to have a positive number of tracks");
     77    MOZ_ASSERT(info.mNumPages % info.mLargerNumTracks == 0,
     78               "page count field should be evenly divisible by "
     79               "the given track-count");
     80    prevInfoPPS = info.mNumPages;
     81  }
     82 #endif
     83 }
     84 
     85 const nsPagesPerSheetInfo& nsPagesPerSheetInfo::LookupInfo(int32_t aPPS) {
     86  SanityCheckPagesPerSheetInfo();
     87 
     88  // Walk the array, looking for a match:
     89  for (const auto& info : kSupportedPagesPerSheet) {
     90    if (aPPS == info.mNumPages) {
     91      return info;
     92    }
     93  }
     94 
     95  NS_WARNING("Unsupported pages-per-sheet value");
     96  // If no match was found, return the first entry (for 1 page per sheet).
     97  return kSupportedPagesPerSheet[0];
     98 }
     99 
    100 const nsPagesPerSheetInfo* nsSharedPageData::PagesPerSheetInfo() {
    101  if (mPagesPerSheetInfo) {
    102    return mPagesPerSheetInfo;
    103  }
    104 
    105  int32_t pagesPerSheet;
    106  if (!mPrintSettings ||
    107      NS_FAILED(mPrintSettings->GetNumPagesPerSheet(&pagesPerSheet))) {
    108    // If we can't read the value from print settings, just fall back to 1.
    109    pagesPerSheet = 1;
    110  }
    111 
    112  mPagesPerSheetInfo = &nsPagesPerSheetInfo::LookupInfo(pagesPerSheet);
    113  return mPagesPerSheetInfo;
    114 }
    115 
    116 nsPageSequenceFrame::nsPageSequenceFrame(ComputedStyle* aStyle,
    117                                         nsPresContext* aPresContext)
    118    : nsContainerFrame(aStyle, aPresContext, kClassID),
    119      mMaxSheetSize(mWritingMode),
    120      mScrollportSize(mWritingMode),
    121      mCalledBeginPage(false),
    122      mCurrentCanvasListSetup(false) {
    123  mPageData = MakeUnique<nsSharedPageData>();
    124  mPageData->mHeadFootFont =
    125      *PresContext()
    126           ->Document()
    127           ->GetFontPrefsForLang(aStyle->StyleFont()->mLanguage)
    128           ->GetDefaultFont(StyleGenericFontFamily::Serif);
    129  mPageData->mHeadFootFont.size =
    130      Length::FromPixels(CSSPixel::FromPoints(10.0f));
    131  mPageData->mPrintSettings = aPresContext->GetPrintSettings();
    132  MOZ_RELEASE_ASSERT(mPageData->mPrintSettings, "How?");
    133 
    134  // Doing this here so we only have to go get these formats once
    135  SetPageNumberFormat("pagenumber", "%1$d", true);
    136  SetPageNumberFormat("pageofpages", "%1$d of %2$d", false);
    137 }
    138 
    139 nsPageSequenceFrame::~nsPageSequenceFrame() { ResetPrintCanvasList(); }
    140 
    141 NS_QUERYFRAME_HEAD(nsPageSequenceFrame)
    142  NS_QUERYFRAME_ENTRY(nsPageSequenceFrame)
    143 NS_QUERYFRAME_TAIL_INHERITING(nsContainerFrame)
    144 
    145 //----------------------------------------------------------------------
    146 
    147 float nsPageSequenceFrame::GetPrintPreviewScale() const {
    148  nsPresContext* pc = PresContext();
    149  float scale = pc->GetPrintPreviewScaleForSequenceFrameOrScrollbars();
    150 
    151  WritingMode wm = GetWritingMode();
    152  if (pc->IsScreen() && MOZ_LIKELY(mScrollportSize.ISize(wm) > 0 &&
    153                                   mScrollportSize.BSize(wm) > 0)) {
    154    // For print preview, scale down as-needed to ensure that each of our
    155    // sheets will fit in the the scrollport.
    156 
    157    // Check if the current scale is sufficient for our sheets to fit in inline
    158    // axis (and if not, reduce the scale so that it will fit).
    159    nscoord scaledISize = NSToCoordCeil(mMaxSheetSize.ISize(wm) * scale);
    160    if (scaledISize > mScrollportSize.ISize(wm)) {
    161      scale *= float(mScrollportSize.ISize(wm)) / float(scaledISize);
    162    }
    163 
    164    // Further reduce the scale (if needed) to be sure each sheet will fit in
    165    // block axis, too.
    166    // NOTE: in general, a scrollport's BSize *could* be unconstrained,
    167    // i.e. sized to its contents. If that happens, then shrinking the contents
    168    // to fit the scrollport is not a meaningful operation in this axis, so we
    169    // skip over this.  But we can be pretty sure that the print-preview UI
    170    // will have given the scrollport a fixed size; hence the MOZ_LIKELY here.
    171    if (MOZ_LIKELY(mScrollportSize.BSize(wm) != NS_UNCONSTRAINEDSIZE)) {
    172      nscoord scaledBSize = NSToCoordCeil(mMaxSheetSize.BSize(wm) * scale);
    173      if (scaledBSize > mScrollportSize.BSize(wm)) {
    174        scale *= float(mScrollportSize.BSize(wm)) / float(scaledBSize);
    175      }
    176    }
    177  }
    178  return scale;
    179 }
    180 
    181 void nsPageSequenceFrame::PopulateReflowOutput(
    182    ReflowOutput& aReflowOutput, const ReflowInput& aReflowInput) {
    183  // Aim to fill the whole available space, not only so we can act as a
    184  // background in print preview but also handle overflow in child page frames
    185  // correctly.
    186  // Use availableISize so we don't cause a needless horizontal scrollbar.
    187  float scale = GetPrintPreviewScale();
    188 
    189  WritingMode wm = aReflowInput.GetWritingMode();
    190  nscoord iSize = wm.IsVertical() ? mSize.Height() : mSize.Width();
    191  nscoord bSize = wm.IsVertical() ? mSize.Width() : mSize.Height();
    192 
    193  nscoord availableISize = aReflowInput.AvailableISize();
    194  nscoord computedBSize = aReflowInput.ComputedBSize();
    195  if (MOZ_UNLIKELY(computedBSize == NS_UNCONSTRAINEDSIZE)) {
    196    // We have unconstrained BSize, which should only happen if someone calls
    197    // SizeToContent() on our window (which we don't expect to happen for
    198    // actual user flows, but is possible for fuzzers to trigger). We just nerf
    199    // the ReflowInput's contributions to the std::max() expressions below,
    200    // which does indeed make us "size to content", via letting std::max()
    201    // choose the scaled iSize/bSize expressions.
    202    availableISize = computedBSize = 0;
    203  }
    204  aReflowOutput.ISize(wm) =
    205      std::max(NSToCoordFloor(iSize * scale), availableISize);
    206  aReflowOutput.BSize(wm) =
    207      std::max(NSToCoordFloor(bSize * scale), computedBSize);
    208  aReflowOutput.SetOverflowAreasToDesiredBounds();
    209 }
    210 
    211 // Helper function to compute the offset needed to center a child
    212 // page-frame's margin-box inside our content-box.
    213 nscoord nsPageSequenceFrame::ComputeCenteringMargin(
    214    nscoord aContainerContentBoxWidth, nscoord aChildPaddingBoxWidth,
    215    const nsMargin& aChildPhysicalMargin) {
    216  // We'll be centering our child's margin-box, so get the size of that:
    217  nscoord childMarginBoxWidth =
    218      aChildPaddingBoxWidth + aChildPhysicalMargin.LeftRight();
    219 
    220  // When rendered, our child's rect will actually be scaled up by the
    221  // print-preview scale factor, via ComputePageSequenceTransform().
    222  // We really want to center *that scaled-up rendering* inside of
    223  // aContainerContentBoxWidth.  So, we scale up its margin-box here...
    224  float scale = GetPrintPreviewScale();
    225  nscoord scaledChildMarginBoxWidth =
    226      NSToCoordRound(childMarginBoxWidth * scale);
    227 
    228  // ...and see we how much space is left over, when we subtract that scaled-up
    229  // size from the container width:
    230  nscoord scaledExtraSpace =
    231      aContainerContentBoxWidth - scaledChildMarginBoxWidth;
    232 
    233  if (scaledExtraSpace <= 0) {
    234    // (Don't bother centering if there's zero/negative space.)
    235    return 0;
    236  }
    237 
    238  // To center the child, we want to give it an additional left-margin of half
    239  // of the extra space.  And then, we have to scale that space back down, so
    240  // that it'll produce the correct scaled-up amount when we render (because
    241  // rendering will scale it back up):
    242  return NSToCoordRound(scaledExtraSpace * 0.5 / scale);
    243 }
    244 
    245 uint32_t nsPageSequenceFrame::GetPagesInFirstSheet() const {
    246  nsIFrame* firstSheet = mFrames.FirstChild();
    247  if (!firstSheet) {
    248    return 0;
    249  }
    250 
    251  MOZ_DIAGNOSTIC_ASSERT(firstSheet->IsPrintedSheetFrame());
    252  return static_cast<PrintedSheetFrame*>(firstSheet)->GetNumPages();
    253 }
    254 
    255 /*
    256 * Note: we largely position/size out our children (page frames) using
    257 * \*physical\* x/y/width/height values, because the print preview UI is always
    258 * arranged in the same orientation, regardless of writing mode.
    259 */
    260 void nsPageSequenceFrame::Reflow(nsPresContext* aPresContext,
    261                                 ReflowOutput& aReflowOutput,
    262                                 const ReflowInput& aReflowInput,
    263                                 nsReflowStatus& aStatus) {
    264  MarkInReflow();
    265  MOZ_ASSERT(aPresContext->IsRootPaginatedDocument(),
    266             "A Page Sequence is only for real pages");
    267  DO_GLOBAL_REFLOW_COUNT("nsPageSequenceFrame");
    268  MOZ_ASSERT(aStatus.IsEmpty(), "Caller should pass a fresh reflow status!");
    269  NS_FRAME_TRACE_REFLOW_IN("nsPageSequenceFrame::Reflow");
    270 
    271  auto CenterPages = [&] {
    272    for (nsIFrame* child : mFrames) {
    273      nsMargin pageCSSMargin = child->GetUsedMargin();
    274      nscoord centeringMargin =
    275          ComputeCenteringMargin(aReflowInput.ComputedWidth(),
    276                                 child->GetRect().Width(), pageCSSMargin);
    277      nscoord newX = pageCSSMargin.left + centeringMargin;
    278 
    279      // Adjust the child's x-position:
    280      child->MovePositionBy(nsPoint(newX - child->GetNormalPosition().x, 0));
    281    }
    282  };
    283 
    284  if (aPresContext->IsScreen()) {
    285    // When we're displayed on-screen, the computed size that we're given is
    286    // the size of our scrollport. We need to save this for use in
    287    // GetPrintPreviewScale.
    288    // (NOTE: It's possible but unlikely that we have an unconstrained BSize
    289    // here, if we're being sized to content. GetPrintPreviewScale() checks
    290    // for and handles this, when making use of this member-var.)
    291    mScrollportSize = aReflowInput.ComputedSize();
    292  }
    293 
    294  // Don't do incremental reflow until we've taught tables how to do
    295  // it right in paginated mode.
    296  if (!HasAnyStateBits(NS_FRAME_FIRST_REFLOW)) {
    297    // Return our desired size
    298    PopulateReflowOutput(aReflowOutput, aReflowInput);
    299    FinishAndStoreOverflow(&aReflowOutput);
    300 
    301    if (GetSize() != aReflowOutput.PhysicalSize()) {
    302      CenterPages();
    303    }
    304    return;
    305  }
    306 
    307  nsIntMargin unwriteableTwips =
    308      mPageData->mPrintSettings->GetUnwriteableMarginInTwips();
    309 
    310  nsIntMargin edgeTwips = mPageData->mPrintSettings->GetEdgeInTwips();
    311 
    312  // sanity check the values. three inches are sometimes needed
    313  int32_t threeInches = NS_INCHES_TO_INT_TWIPS(3.0);
    314  edgeTwips.EnsureAtMost(
    315      nsIntMargin(threeInches, threeInches, threeInches, threeInches));
    316  edgeTwips.EnsureAtLeast(unwriteableTwips);
    317 
    318  mPageData->mEdgePaperMargin = nsPresContext::CSSTwipsToAppUnits(edgeTwips);
    319 
    320  // Get the custom page-range state:
    321  mPageData->mPrintSettings->GetPageRanges(mPageData->mPageRanges);
    322 
    323  // We use the CSS "margin" property on the -moz-printed-sheet pseudoelement
    324  // to determine the space between each printed sheet in print preview.
    325  // Keep a running y-offset for each printed sheet.
    326  nscoord y = 0;
    327 
    328  // These represent the maximum sheet size across all our sheets (in each
    329  // axis), inflated a bit to account for the -moz-printed-sheet 'margin'.
    330  nscoord maxInflatedSheetWidth = 0;
    331  nscoord maxInflatedSheetHeight = 0;
    332 
    333  // Tile the sheets vertically
    334  for (nsIFrame* kidFrame : mFrames) {
    335    // Set the shared data into the page frame before reflow
    336    MOZ_ASSERT(kidFrame->IsPrintedSheetFrame(),
    337               "we're only expecting PrintedSheetFrame as children");
    338    auto* sheet = static_cast<PrintedSheetFrame*>(kidFrame);
    339    sheet->SetSharedPageData(mPageData.get());
    340 
    341    // If we want to reliably access the nsPageFrame before reflowing the sheet
    342    // frame, we need to call this:
    343    sheet->ClaimPageFrameFromPrevInFlow();
    344 
    345    const nsSize sheetSize = sheet->ComputeSheetSize(aPresContext);
    346 
    347    // Reflow the sheet
    348    ReflowInput kidReflowInput(
    349        aPresContext, aReflowInput, kidFrame,
    350        LogicalSize(kidFrame->GetWritingMode(), sheetSize));
    351    kidReflowInput.mBreakType = ReflowInput::BreakType::Page;
    352 
    353    ReflowOutput kidReflowOutput(kidReflowInput);
    354    nsReflowStatus status;
    355 
    356    kidReflowInput.SetComputedISize(kidReflowInput.AvailableISize());
    357    // kidReflowInput.SetComputedHeight(kidReflowInput.AvailableHeight());
    358    PR_PL(("AV ISize: %d   BSize: %d\n", kidReflowInput.AvailableISize(),
    359           kidReflowInput.AvailableBSize()));
    360 
    361    nsMargin pageCSSMargin = kidReflowInput.ComputedPhysicalMargin();
    362    y += pageCSSMargin.top;
    363 
    364    nscoord x = pageCSSMargin.left;
    365 
    366    // Place and size the sheet.
    367    ReflowChild(kidFrame, aPresContext, kidReflowOutput, kidReflowInput, x, y,
    368                ReflowChildFlags::Default, status);
    369 
    370    FinishReflowChild(kidFrame, aPresContext, kidReflowOutput, &kidReflowInput,
    371                      x, y, ReflowChildFlags::Default);
    372    MOZ_ASSERT(kidFrame->GetSize() == sheetSize,
    373               "PrintedSheetFrame::ComputeSheetSize() gave the wrong size!");
    374    y += kidReflowOutput.Height();
    375    y += pageCSSMargin.bottom;
    376 
    377    maxInflatedSheetWidth =
    378        std::max(maxInflatedSheetWidth,
    379                 kidReflowOutput.Width() + pageCSSMargin.LeftRight());
    380    maxInflatedSheetHeight =
    381        std::max(maxInflatedSheetHeight,
    382                 kidReflowOutput.Height() + pageCSSMargin.TopBottom());
    383 
    384    // Is the sheet complete?
    385    nsIFrame* kidNextInFlow = kidFrame->GetNextInFlow();
    386 
    387    if (status.IsFullyComplete()) {
    388      NS_ASSERTION(!kidNextInFlow, "bad child flow list");
    389    } else if (!kidNextInFlow) {
    390      // The sheet isn't complete and it doesn't have a next-in-flow, so
    391      // create a continuing sheet.
    392      nsIFrame* continuingSheet =
    393          PresShell()->FrameConstructor()->CreateContinuingFrame(kidFrame,
    394                                                                 this);
    395 
    396      // Add it to our child list
    397      mFrames.InsertFrame(nullptr, kidFrame, continuingSheet);
    398    }
    399  }
    400 
    401  nsAutoString formattedDateString;
    402  PRTime now = PR_Now();
    403  mozilla::intl::DateTimeFormat::StyleBag style;
    404  style.date = Some(mozilla::intl::DateTimeFormat::Style::Short);
    405  style.time = Some(mozilla::intl::DateTimeFormat::Style::Short);
    406  if (NS_SUCCEEDED(mozilla::intl::AppDateTimeFormat::Format(
    407          style, now, formattedDateString))) {
    408    SetDateTimeStr(formattedDateString);
    409  }
    410 
    411  // cache the size so we can set the desired size for the other reflows that
    412  // happen.  Since we're tiling our sheets vertically: in the x axis, we are
    413  // as wide as our widest sheet (inflated via "margin"); and in the y axis,
    414  // we're as tall as the sum of our sheets' inflated heights, which the 'y'
    415  // variable is conveniently storing at this point.
    416  mSize = nsSize(maxInflatedSheetWidth, y);
    417 
    418  if (aPresContext->IsScreen()) {
    419    // Also cache the maximum size of all our sheets, to use together with the
    420    // scrollport size (available as our computed size, and captured higher up
    421    // in this function), so that we can scale to ensure that every sheet will
    422    // fit in the scrollport.
    423    WritingMode wm = aReflowInput.GetWritingMode();
    424    mMaxSheetSize =
    425        LogicalSize(wm, nsSize(maxInflatedSheetWidth, maxInflatedSheetHeight));
    426  }
    427 
    428  // Return our desired size
    429  // Adjust the reflow size by PrintPreviewScale so the scrollbars end up the
    430  // correct size
    431  PopulateReflowOutput(aReflowOutput, aReflowInput);
    432 
    433  FinishAndStoreOverflow(&aReflowOutput);
    434 
    435  // Now center our pages.
    436  CenterPages();
    437 
    438  NS_FRAME_TRACE_REFLOW_OUT("nsPageSequenceFrame::Reflow", aStatus);
    439 }
    440 
    441 //----------------------------------------------------------------------
    442 
    443 #ifdef DEBUG_FRAME_DUMP
    444 nsresult nsPageSequenceFrame::GetFrameName(nsAString& aResult) const {
    445  return MakeFrameName(u"PageSequence"_ns, aResult);
    446 }
    447 #endif
    448 
    449 // Helper Function
    450 void nsPageSequenceFrame::SetPageNumberFormat(const char* aPropName,
    451                                              const char* aDefPropVal,
    452                                              bool aPageNumOnly) {
    453  // Doing this here so we only have to go get these formats once
    454  nsAutoString pageNumberFormat;
    455  // Now go get the Localized Page Formating String
    456  nsresult rv = nsContentUtils::GetLocalizedString(
    457      nsContentUtils::ePRINTING_PROPERTIES, aPropName, pageNumberFormat);
    458  if (NS_FAILED(rv)) {  // back stop formatting
    459    pageNumberFormat.AssignASCII(aDefPropVal);
    460  }
    461 
    462  SetPageNumberFormat(pageNumberFormat, aPageNumOnly);
    463 }
    464 
    465 nsresult nsPageSequenceFrame::StartPrint(nsPresContext* aPresContext,
    466                                         nsIPrintSettings* aPrintSettings,
    467                                         const nsAString& aDocTitle,
    468                                         const nsAString& aDocURL) {
    469  NS_ENSURE_ARG_POINTER(aPresContext);
    470  NS_ENSURE_ARG_POINTER(aPrintSettings);
    471 
    472  if (!mPageData->mPrintSettings) {
    473    mPageData->mPrintSettings = aPrintSettings;
    474  }
    475 
    476  if (!aDocTitle.IsEmpty()) {
    477    mPageData->mDocTitle = aDocTitle;
    478  }
    479  if (!aDocURL.IsEmpty()) {
    480    mPageData->mDocURL = aDocURL;
    481  }
    482 
    483  // Begin printing of the document
    484  mCurrentSheetIdx = 0;
    485  return NS_OK;
    486 }
    487 
    488 static void GetPrintCanvasElementsInFrame(
    489    nsIFrame* aFrame, nsTArray<RefPtr<HTMLCanvasElement>>* aArr) {
    490  if (!aFrame) {
    491    return;
    492  }
    493  for (const auto& childList : aFrame->ChildLists()) {
    494    for (nsIFrame* child : childList.mList) {
    495      // Check if child is a nsHTMLCanvasFrame.
    496      nsHTMLCanvasFrame* canvasFrame = do_QueryFrame(child);
    497 
    498      // If there is a canvasFrame, try to get actual canvas element.
    499      if (canvasFrame) {
    500        HTMLCanvasElement* canvas =
    501            HTMLCanvasElement::FromNodeOrNull(canvasFrame->GetContent());
    502        if (canvas && canvas->GetMozPrintCallback()) {
    503          aArr->AppendElement(canvas);
    504          continue;
    505        }
    506      }
    507 
    508      if (!child->PrincipalChildList().FirstChild()) {
    509        nsSubDocumentFrame* subdocumentFrame = do_QueryFrame(child);
    510        if (subdocumentFrame) {
    511          // Descend into the subdocument
    512          nsIFrame* root = subdocumentFrame->GetSubdocumentRootFrame();
    513          child = root;
    514        }
    515      }
    516      // The current child is not a nsHTMLCanvasFrame OR it is but there is
    517      // no HTMLCanvasElement on it. Check if children of `child` might
    518      // contain a HTMLCanvasElement.
    519      GetPrintCanvasElementsInFrame(child, aArr);
    520    }
    521  }
    522 }
    523 
    524 // Note: this isn't quite a full tree traversal, since we exclude any
    525 // nsPageFame children that have the NS_PAGE_SKIPPED_BY_CUSTOM_RANGE state-bit.
    526 static void GetPrintCanvasElementsInSheet(
    527    PrintedSheetFrame* aSheetFrame, nsTArray<RefPtr<HTMLCanvasElement>>* aArr) {
    528  MOZ_ASSERT(aSheetFrame, "Caller should've null-checked for us already");
    529  for (nsIFrame* child : aSheetFrame->PrincipalChildList()) {
    530    // Exclude any pages that are technically children but are skipped by a
    531    // custom range; they're not meant to be printed, so we don't want to
    532    // waste time rendering their canvas descendants.
    533    MOZ_ASSERT(child->IsPageFrame(),
    534               "PrintedSheetFrame's children must all be nsPageFrames");
    535    auto* pageFrame = static_cast<nsPageFrame*>(child);
    536    if (!pageFrame->HasAnyStateBits(NS_PAGE_SKIPPED_BY_CUSTOM_RANGE)) {
    537      GetPrintCanvasElementsInFrame(pageFrame, aArr);
    538    }
    539  }
    540 }
    541 
    542 PrintedSheetFrame* nsPageSequenceFrame::GetCurrentSheetFrame() {
    543  uint32_t i = 0;
    544  for (nsIFrame* child : mFrames) {
    545    MOZ_ASSERT(child->IsPrintedSheetFrame(),
    546               "Our children must all be PrintedSheetFrame");
    547    if (i == mCurrentSheetIdx) {
    548      return static_cast<PrintedSheetFrame*>(child);
    549    }
    550    ++i;
    551  }
    552  return nullptr;
    553 }
    554 
    555 nsresult nsPageSequenceFrame::PrePrintNextSheet(nsITimerCallback* aCallback,
    556                                                bool* aDone) {
    557  PrintedSheetFrame* currentSheet = GetCurrentSheetFrame();
    558  if (!currentSheet) {
    559    *aDone = true;
    560    return NS_ERROR_FAILURE;
    561  }
    562 
    563  if (!PresContext()->IsRootPaginatedDocument()) {
    564    // XXXdholbert I don't think this clause is ever actually visited in
    565    // practice... Maybe we should warn & return a failure code?  There used to
    566    // be a comment here explaining why we don't need to proceed past this
    567    // point for print preview, but in fact, this function isn't even called for
    568    // print preview.
    569    *aDone = true;
    570    return NS_OK;
    571  }
    572 
    573  // If the canvasList is null, then generate it and start the render
    574  // process for all the canvas.
    575  if (!mCurrentCanvasListSetup) {
    576    mCurrentCanvasListSetup = true;
    577    GetPrintCanvasElementsInSheet(currentSheet, &mCurrentCanvasList);
    578 
    579    if (!mCurrentCanvasList.IsEmpty()) {
    580      nsresult rv = NS_OK;
    581 
    582      // Begin printing of the document
    583      nsDeviceContext* dc = PresContext()->DeviceContext();
    584      PR_PL(("\n"));
    585      PR_PL(("***************** BeginPage *****************\n"));
    586      const gfx::IntSize sizeInPoints =
    587          currentSheet->GetPrintTargetSizeInPoints(
    588              dc->AppUnitsPerPhysicalInch());
    589      rv = dc->BeginPage(sizeInPoints);
    590      NS_ENSURE_SUCCESS(rv, rv);
    591 
    592      mCalledBeginPage = true;
    593 
    594      UniquePtr<gfxContext> renderingContext = dc->CreateRenderingContext();
    595      NS_ENSURE_TRUE(renderingContext, NS_ERROR_OUT_OF_MEMORY);
    596 
    597      DrawTarget* drawTarget = renderingContext->GetDrawTarget();
    598      if (NS_WARN_IF(!drawTarget)) {
    599        return NS_ERROR_FAILURE;
    600      }
    601 
    602      for (HTMLCanvasElement* canvas : Reversed(mCurrentCanvasList)) {
    603        CSSIntSize size = canvas->GetSize();
    604 
    605        RefPtr<DrawTarget> canvasTarget = drawTarget->CreateSimilarDrawTarget(
    606            size.ToUnknownSize(), drawTarget->GetFormat());
    607        if (!canvasTarget) {
    608          continue;
    609        }
    610 
    611        nsICanvasRenderingContextInternal* ctx = canvas->GetCurrentContext();
    612        if (!ctx) {
    613          continue;
    614        }
    615 
    616        // Initialize the context with the new DrawTarget.
    617        ctx->InitializeWithDrawTarget(nullptr, WrapNotNull(canvasTarget));
    618 
    619        // Start the rendering process.
    620        // Note: Other than drawing to our CanvasRenderingContext2D, the
    621        // callback cannot access or mutate our static clone document.  It is
    622        // evaluated in its original context (the window of the original
    623        // document) of course, and our canvas has a strong ref to the
    624        // original HTMLCanvasElement (in mOriginalCanvas) so that if the
    625        // callback calls GetCanvas() on our CanvasRenderingContext2D (passed
    626        // to it via a MozCanvasPrintState argument) it will be given the
    627        // original 'canvas' element.
    628        AutoWeakFrame weakFrame = this;
    629        canvas->DispatchPrintCallback(aCallback);
    630        NS_ENSURE_STATE(weakFrame.IsAlive());
    631      }
    632    }
    633  }
    634  uint32_t doneCounter = 0;
    635  for (HTMLCanvasElement* canvas : mCurrentCanvasList) {
    636    if (canvas->IsPrintCallbackDone()) {
    637      doneCounter++;
    638    }
    639  }
    640  // If all canvas have finished rendering, return true, otherwise false.
    641  *aDone = doneCounter == mCurrentCanvasList.Length();
    642 
    643  return NS_OK;
    644 }
    645 
    646 void nsPageSequenceFrame::ResetPrintCanvasList() {
    647  for (int32_t i = mCurrentCanvasList.Length() - 1; i >= 0; i--) {
    648    HTMLCanvasElement* canvas = mCurrentCanvasList[i];
    649    canvas->ResetPrintCallback();
    650  }
    651 
    652  mCurrentCanvasList.Clear();
    653  mCurrentCanvasListSetup = false;
    654 }
    655 
    656 nsresult nsPageSequenceFrame::PrintNextSheet() {
    657  // Note: When print al the pages or a page range the printed page shows the
    658  // actual page number, when printing selection it prints the page number
    659  // starting with the first page of the selection. For example if the user has
    660  // a selection that starts on page 2 and ends on page 3, the page numbers when
    661  // print are 1 and then two (which is different than printing a page range,
    662  // where the page numbers would have been 2 and then 3)
    663 
    664  PrintedSheetFrame* currentSheetFrame = GetCurrentSheetFrame();
    665  if (!currentSheetFrame) {
    666    return NS_ERROR_FAILURE;
    667  }
    668 
    669  nsresult rv = NS_OK;
    670 
    671  nsDeviceContext* dc = PresContext()->DeviceContext();
    672 
    673  if (PresContext()->IsRootPaginatedDocument()) {
    674    if (!mCalledBeginPage) {
    675      // We must make sure BeginPage() has been called since some printing
    676      // backends can't give us a valid rendering context for a [physical]
    677      // page otherwise.
    678      PR_PL(("\n"));
    679      PR_PL(("***************** BeginPage *****************\n"));
    680      const gfx::IntSize sizeInPoints =
    681          currentSheetFrame->GetPrintTargetSizeInPoints(
    682              dc->AppUnitsPerPhysicalInch());
    683      rv = dc->BeginPage(sizeInPoints);
    684      NS_ENSURE_SUCCESS(rv, rv);
    685    }
    686  }
    687 
    688  PR_PL(("SeqFr::PrintNextSheet -> %p SheetIdx: %d", currentSheetFrame,
    689         mCurrentSheetIdx));
    690 
    691  // CreateRenderingContext can fail
    692  UniquePtr<gfxContext> gCtx = dc->CreateRenderingContext();
    693  NS_ENSURE_TRUE(gCtx, NS_ERROR_OUT_OF_MEMORY);
    694 
    695  nsRect drawingRect(nsPoint(0, 0), currentSheetFrame->GetSize());
    696  nsRegion drawingRegion(drawingRect);
    697  nsLayoutUtils::PaintFrame(gCtx.get(), currentSheetFrame, drawingRegion,
    698                            NS_RGBA(0, 0, 0, 0),
    699                            nsDisplayListBuilderMode::PaintForPrinting,
    700                            nsLayoutUtils::PaintFrameFlags::SyncDecodeImages);
    701  return rv;
    702 }
    703 
    704 nsresult nsPageSequenceFrame::DoPageEnd() {
    705  nsresult rv = NS_OK;
    706  if (PresContext()->IsRootPaginatedDocument()) {
    707    PR_PL(("***************** End Page (DoPageEnd) *****************\n"));
    708    rv = PresContext()->DeviceContext()->EndPage();
    709    // Fall through to clean up resources/state below even if EndPage failed.
    710  }
    711 
    712  ResetPrintCanvasList();
    713  mCalledBeginPage = false;
    714 
    715  mCurrentSheetIdx++;
    716 
    717  return rv;
    718 }
    719 
    720 static gfx::Matrix4x4 ComputePageSequenceTransform(const nsIFrame* aFrame,
    721                                                   float aAppUnitsPerPixel) {
    722  MOZ_ASSERT(aFrame->IsPageSequenceFrame());
    723  float scale =
    724      static_cast<const nsPageSequenceFrame*>(aFrame)->GetPrintPreviewScale();
    725  return gfx::Matrix4x4::Scaling(scale, scale, 1);
    726 }
    727 
    728 nsIFrame::ComputeTransformFunction nsPageSequenceFrame::GetTransformGetter()
    729    const {
    730  return ComputePageSequenceTransform;
    731 }
    732 
    733 void nsPageSequenceFrame::BuildDisplayList(nsDisplayListBuilder* aBuilder,
    734                                           const nsDisplayListSet& aLists) {
    735  aBuilder->SetDisablePartialUpdates(true);
    736  DisplayBorderBackgroundOutline(aBuilder, aLists);
    737 
    738  nsDisplayList content(aBuilder);
    739 
    740  {
    741    // Clear clip state while we construct the children of the
    742    // nsDisplayTransform, since they'll be in a different coordinate system.
    743    DisplayListClipState::AutoSaveRestore clipState(aBuilder);
    744    clipState.Clear();
    745 
    746    nsIFrame* child = PrincipalChildList().FirstChild();
    747    nsRect visible = aBuilder->GetVisibleRect();
    748    visible.ScaleInverseRoundOut(GetPrintPreviewScale());
    749 
    750    while (child) {
    751      if (child->InkOverflowRectRelativeToParent().Intersects(visible)) {
    752        nsDisplayListBuilder::AutoBuildingDisplayList buildingForChild(
    753            aBuilder, child, visible - child->GetPosition(),
    754            visible - child->GetPosition());
    755        child->BuildDisplayListForStackingContext(aBuilder, &content);
    756        aBuilder->ResetMarkedFramesForDisplayList(this);
    757      }
    758      child = child->GetNextSibling();
    759    }
    760  }
    761 
    762  content.AppendNewToTop<nsDisplayTransform>(
    763      aBuilder, this, &content, content.GetBuildingRect(),
    764      nsDisplayTransform::WithTransformGetter);
    765 
    766  aLists.Content()->AppendToTop(&content);
    767 }
    768 
    769 //------------------------------------------------------------------------------
    770 void nsPageSequenceFrame::SetPageNumberFormat(const nsAString& aFormatStr,
    771                                              bool aForPageNumOnly) {
    772  NS_ASSERTION(mPageData != nullptr, "mPageData string cannot be null!");
    773 
    774  if (aForPageNumOnly) {
    775    mPageData->mPageNumFormat = aFormatStr;
    776  } else {
    777    mPageData->mPageNumAndTotalsFormat = aFormatStr;
    778  }
    779 }
    780 
    781 //------------------------------------------------------------------------------
    782 void nsPageSequenceFrame::SetDateTimeStr(const nsAString& aDateTimeStr) {
    783  NS_ASSERTION(mPageData != nullptr, "mPageData string cannot be null!");
    784 
    785  mPageData->mDateTimeStr = aDateTimeStr;
    786 }