summaryrefslogtreecommitdiffstats
path: root/widget/cocoa/nsDeviceContextSpecX.mm
blob: 9bb8449b705e09e206a16f0d55e9231911d79e33 (plain)
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
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* 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 "nsDeviceContextSpecX.h"

#import <Cocoa/Cocoa.h>
#include "mozilla/gfx/PrintPromise.h"
#include <CoreFoundation/CoreFoundation.h>
#include <unistd.h>

#ifdef MOZ_ENABLE_SKIA_PDF
#  include "mozilla/gfx/PrintTargetSkPDF.h"
#endif
#include "mozilla/gfx/PrintTargetCG.h"
#include "mozilla/Logging.h"
#include "mozilla/Preferences.h"
#include "mozilla/RefPtr.h"
#include "mozilla/Telemetry.h"

#include "AppleUtils.h"
#include "nsCocoaUtils.h"
#include "nsCRT.h"
#include "nsCUPSShim.h"
#include "nsDirectoryServiceDefs.h"
#include "nsILocalFileMac.h"
#include "nsIOutputStream.h"
#include "nsPaper.h"
#include "nsPrinterListCUPS.h"
#include "nsPrintSettingsX.h"
#include "nsQueryObject.h"
#include "prenv.h"

// This must be the last include:
#include "nsObjCExceptions.h"

using namespace mozilla;
using mozilla::gfx::IntSize;
using mozilla::gfx::PrintEndDocumentPromise;
using mozilla::gfx::PrintTarget;
using mozilla::gfx::PrintTargetCG;
#ifdef MOZ_ENABLE_SKIA_PDF
using mozilla::gfx::PrintTargetSkPDF;
#endif

//----------------------------------------------------------------------
// nsDeviceContentSpecX

nsDeviceContextSpecX::nsDeviceContextSpecX() = default;

nsDeviceContextSpecX::~nsDeviceContextSpecX() {
  NS_OBJC_BEGIN_TRY_IGNORE_BLOCK;

  if (mPrintSession) {
    ::PMRelease(mPrintSession);
  }
  if (mPageFormat) {
    ::PMRelease(mPageFormat);
  }
  if (mPMPrintSettings) {
    ::PMRelease(mPMPrintSettings);
  }

  NS_OBJC_END_TRY_IGNORE_BLOCK;
}

NS_IMPL_ISUPPORTS(nsDeviceContextSpecX, nsIDeviceContextSpec)

NS_IMETHODIMP nsDeviceContextSpecX::Init(nsIPrintSettings* aPS,
                                         bool aIsPrintPreview) {
  NS_OBJC_BEGIN_TRY_BLOCK_RETURN;

  RefPtr<nsPrintSettingsX> settings(do_QueryObject(aPS));
  if (!settings) {
    return NS_ERROR_NO_INTERFACE;
  }
  // Note: unlike other platforms, we don't set our base class's mPrintSettings
  // here since we don't need it currently (we do set mPMPrintSettings below).

  NSPrintInfo* printInfo = settings->CreateOrCopyPrintInfo();
  if (!printInfo) {
    return NS_ERROR_FAILURE;
  }
  if (aPS->GetOutputDestination() ==
      nsIPrintSettings::kOutputDestinationStream) {
    aPS->GetOutputStream(getter_AddRefs(mOutputStream));
    if (!mOutputStream) {
      return NS_ERROR_FAILURE;
    }
  }
  mPrintSession = static_cast<PMPrintSession>([printInfo PMPrintSession]);
  mPageFormat = static_cast<PMPageFormat>([printInfo PMPageFormat]);
  mPMPrintSettings = static_cast<PMPrintSettings>([printInfo PMPrintSettings]);
  MOZ_ASSERT(mPrintSession && mPageFormat && mPMPrintSettings);
  ::PMRetain(mPrintSession);
  ::PMRetain(mPageFormat);
  ::PMRetain(mPMPrintSettings);
  [printInfo release];

#ifdef MOZ_ENABLE_SKIA_PDF
  nsAutoString printViaPdf;
  mozilla::Preferences::GetString("print.print_via_pdf_encoder", printViaPdf);
  if (printViaPdf.EqualsLiteral("skia-pdf")) {
    // Annoyingly, PMPrinterPrintWithFile does not pay attention to the
    // kPMDestination* value set in the PMPrintSession; it always sends the PDF
    // to the specified printer.  This means that if we create the PDF using
    // SkPDF then we need to manually handle user actions like "Open PDF in
    // Preview" and "Save as PDF...".
    // TODO: Currently we do not support using SkPDF for kPMDestinationFax or
    // kPMDestinationProcessPDF ("Add PDF to iBooks, etc.), and we only support
    // it for kPMDestinationFile if the destination file is a PDF.
    // XXX Could PMWorkflowSubmitPDFWithSettings/PMPrinterPrintWithProvider
    // help?
    OSStatus status = noErr;
    PMDestinationType destination;
    status = ::PMSessionGetDestinationType(mPrintSession, mPMPrintSettings,
                                           &destination);
    if (status == noErr) {
      if (destination == kPMDestinationPrinter ||
          destination == kPMDestinationPreview) {
        mPrintViaSkPDF = true;
      } else if (destination == kPMDestinationFile) {
        AutoCFRelease<CFURLRef> destURL(nullptr);
        status = ::PMSessionCopyDestinationLocation(
            mPrintSession, mPMPrintSettings, destURL.receive());
        if (status == noErr) {
          AutoCFRelease<CFStringRef> destPathRef =
              CFURLCopyFileSystemPath(destURL, kCFURLPOSIXPathStyle);
          NSString* destPath = (NSString*)CFStringRef(destPathRef);
          NSString* destPathExt = [destPath pathExtension];
          if ([destPathExt isEqualToString:@"pdf"]) {
            mPrintViaSkPDF = true;
          }
        }
      }
    }
  }
#endif

  int16_t outputFormat = aPS->GetOutputFormat();

  if (outputFormat == nsIPrintSettings::kOutputFormatPDF) {
    // We don't actually currently support/use kOutputFormatPDF on mac, but
    // this is for completeness in case we add that (we probably need to in
    // order to support adding links into saved PDFs, for example).
    Telemetry::ScalarAdd(Telemetry::ScalarID::PRINTING_TARGET_TYPE,
                         u"pdf_file"_ns, 1);
  } else {
    PMDestinationType destination;
    OSStatus status = ::PMSessionGetDestinationType(
        mPrintSession, mPMPrintSettings, &destination);
    if (status == noErr && (destination == kPMDestinationFile ||
                            destination == kPMDestinationPreview ||
                            destination == kPMDestinationProcessPDF)) {
      Telemetry::ScalarAdd(Telemetry::ScalarID::PRINTING_TARGET_TYPE,
                           u"pdf_file"_ns, 1);
    } else {
      Telemetry::ScalarAdd(Telemetry::ScalarID::PRINTING_TARGET_TYPE,
                           u"unknown"_ns, 1);
    }
  }

  return NS_OK;

  NS_OBJC_END_TRY_BLOCK_RETURN(NS_ERROR_FAILURE);
}

NS_IMETHODIMP nsDeviceContextSpecX::BeginDocument(
    const nsAString& aTitle, const nsAString& aPrintToFileName,
    int32_t aStartPage, int32_t aEndPage) {
  NS_OBJC_BEGIN_TRY_BLOCK_RETURN;

  return NS_OK;

  NS_OBJC_END_TRY_BLOCK_RETURN(NS_ERROR_FAILURE);
}

RefPtr<PrintEndDocumentPromise> nsDeviceContextSpecX::EndDocument() {
  return nsIDeviceContextSpec::EndDocumentPromiseFromResult(DoEndDocument(),
                                                            __func__);
}

nsresult nsDeviceContextSpecX::DoEndDocument() {
  NS_OBJC_BEGIN_TRY_BLOCK_RETURN;

#ifdef MOZ_ENABLE_SKIA_PDF
  if (mPrintViaSkPDF) {
    OSStatus status = noErr;

    nsCOMPtr<nsILocalFileMac> tmpPDFFile = do_QueryInterface(mTempFile);
    if (!tmpPDFFile) {
      return NS_ERROR_FAILURE;
    }
    AutoCFRelease<CFURLRef> pdfURL(nullptr);
    // Note that the caller is responsible to release pdfURL according to
    // nsILocalFileMac.idl, even though we didn't follow the Core Foundation
    // naming conventions here (the method should've been called CopyCFURL).
    nsresult rv = tmpPDFFile->GetCFURL(pdfURL.receive());
    NS_ENSURE_SUCCESS(rv, rv);

    PMDestinationType destination;
    status = ::PMSessionGetDestinationType(mPrintSession, mPMPrintSettings,
                                           &destination);

    switch (destination) {
      case kPMDestinationPrinter: {
        PMPrinter currentPrinter = NULL;
        status = ::PMSessionGetCurrentPrinter(mPrintSession, &currentPrinter);
        if (status != noErr) {
          return NS_ERROR_FAILURE;
        }
        CFStringRef mimeType = CFSTR("application/pdf");
        status = ::PMPrinterPrintWithFile(currentPrinter, mPMPrintSettings,
                                          mPageFormat, mimeType, pdfURL);
        break;
      }
      case kPMDestinationPreview: {
        // XXXjwatt Or should we use CocoaFileUtils::RevealFileInFinder(pdfURL);
        AutoCFRelease<CFStringRef> pdfPath =
            CFURLCopyFileSystemPath(pdfURL, kCFURLPOSIXPathStyle);
        NSString* path = (NSString*)CFStringRef(pdfPath);
        NSWorkspace* ws = [NSWorkspace sharedWorkspace];
        [ws openFile:path];
        break;
      }
      case kPMDestinationFile: {
        AutoCFRelease<CFURLRef> destURL(nullptr);
        status = ::PMSessionCopyDestinationLocation(
            mPrintSession, mPMPrintSettings, destURL.receive());
        if (status == noErr) {
          AutoCFRelease<CFStringRef> sourcePathRef =
              CFURLCopyFileSystemPath(pdfURL, kCFURLPOSIXPathStyle);
          NSString* sourcePath = (NSString*)CFStringRef(sourcePathRef);
#  ifdef DEBUG
          AutoCFRelease<CFStringRef> destPathRef =
              CFURLCopyFileSystemPath(destURL, kCFURLPOSIXPathStyle);
          NSString* destPath = (NSString*)CFStringRef(destPathRef);
          NSString* destPathExt = [destPath pathExtension];
          MOZ_ASSERT([destPathExt isEqualToString:@"pdf"],
                     "nsDeviceContextSpecX::Init only allows '.pdf' for now");
          // We could use /usr/sbin/cupsfilter to convert the PDF to PS, but
          // currently we don't.
#  endif
          NSFileManager* fileManager = [NSFileManager defaultManager];
          if ([fileManager fileExistsAtPath:sourcePath]) {
            NSURL* src = static_cast<NSURL*>(CFURLRef(pdfURL));
            NSURL* dest = static_cast<NSURL*>(CFURLRef(destURL));
            bool ok = [fileManager
                replaceItemAtURL:dest
                   withItemAtURL:src
                  backupItemName:nil
                         options:
                             NSFileManagerItemReplacementUsingNewMetadataOnly
                resultingItemURL:nil
                           error:nil];
            if (!ok) {
              return NS_ERROR_FAILURE;
            }
          }
        }
        break;
      }
      default:
        MOZ_ASSERT_UNREACHABLE("nsDeviceContextSpecX::Init doesn't set "
                               "mPrintViaSkPDF for other values");
    }

    return (status == noErr) ? NS_OK : NS_ERROR_FAILURE;
  }
#endif

  return NS_OK;

  NS_OBJC_END_TRY_BLOCK_RETURN(NS_ERROR_FAILURE);
}

void nsDeviceContextSpecX::GetPaperRect(double* aTop, double* aLeft,
                                        double* aBottom, double* aRight) {
  NS_OBJC_BEGIN_TRY_IGNORE_BLOCK;

  PMRect paperRect;
  ::PMGetAdjustedPaperRect(mPageFormat, &paperRect);

  *aTop = paperRect.top;
  *aLeft = paperRect.left;
  *aBottom = paperRect.bottom;
  *aRight = paperRect.right;

  NS_OBJC_END_TRY_IGNORE_BLOCK;
}

already_AddRefed<PrintTarget> nsDeviceContextSpecX::MakePrintTarget() {
  double top, left, bottom, right;
  GetPaperRect(&top, &left, &bottom, &right);
  const double width = right - left;
  const double height = bottom - top;
  IntSize size = IntSize::Ceil(width, height);

#ifdef MOZ_ENABLE_SKIA_PDF
  if (mPrintViaSkPDF) {
    // TODO: Add support for stream printing via SkPDF if we enable that again.
    nsresult rv =
        NS_GetSpecialDirectory(NS_OS_TEMP_DIR, getter_AddRefs(mTempFile));
    NS_ENSURE_SUCCESS(rv, nullptr);
    nsAutoCString tempPath("tmp-printing.pdf");
    mTempFile->AppendNative(tempPath);
    rv = mTempFile->CreateUnique(nsIFile::NORMAL_FILE_TYPE, 0600);
    NS_ENSURE_SUCCESS(rv, nullptr);
    mTempFile->GetNativePath(tempPath);
    auto stream = MakeUnique<SkFILEWStream>(tempPath.get());
    return PrintTargetSkPDF::CreateOrNull(std::move(stream), size);
  }
#endif

  return PrintTargetCG::CreateOrNull(mOutputStream, mPrintSession, mPageFormat,
                                     mPMPrintSettings, size);
}