Fix redundant flushes in CommandBufferHelper::WaitForToken().
[chromium-blink-merge.git] / printing / printing_context_mac.mm
blob8b40da34cd2ebb06354368c2a796a596ece10d4d
1 // Copyright (c) 2011 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #include "printing/printing_context_mac.h"
7 #import <ApplicationServices/ApplicationServices.h>
8 #import <AppKit/AppKit.h>
10 #import <iomanip>
11 #import <numeric>
13 #include "base/logging.h"
14 #include "base/mac/scoped_cftyperef.h"
15 #include "base/mac/scoped_nsautorelease_pool.h"
16 #include "base/mac/scoped_nsexception_enabler.h"
17 #include "base/strings/sys_string_conversions.h"
18 #include "base/strings/utf_string_conversions.h"
19 #include "base/values.h"
20 #include "printing/print_settings_initializer_mac.h"
21 #include "printing/units.h"
23 namespace printing {
25 namespace {
27 // Return true if PPD name of paper is equal.
28 bool IsPaperNameEqual(const PMPaper& paper1, const PMPaper& paper2) {
29   CFStringRef name1 = NULL;
30   CFStringRef name2 = NULL;
31   return (PMPaperGetPPDPaperName(paper1, &name1) == noErr) &&
32          (PMPaperGetPPDPaperName(paper2, &name2) == noErr) &&
33          (CFStringCompare(name1, name2,
34                           kCFCompareCaseInsensitive) == kCFCompareEqualTo);
37 }  // namespace
39 // static
40 PrintingContext* PrintingContext::Create(const std::string& app_locale) {
41   return static_cast<PrintingContext*>(new PrintingContextMac(app_locale));
44 PrintingContextMac::PrintingContextMac(const std::string& app_locale)
45     : PrintingContext(app_locale),
46       print_info_([[NSPrintInfo sharedPrintInfo] copy]),
47       context_(NULL) {
50 PrintingContextMac::~PrintingContextMac() {
51   ReleaseContext();
54 void PrintingContextMac::AskUserForSettings(
55     gfx::NativeView parent_view,
56     int max_pages,
57     bool has_selection,
58     const PrintSettingsCallback& callback) {
59   // Third-party print drivers seem to be an area prone to raising exceptions.
60   // This will allow exceptions to be raised, but does not handle them.  The
61   // NSPrintPanel appears to have appropriate NSException handlers.
62   base::mac::ScopedNSExceptionEnabler enabler;
64   // Exceptions can also happen when the NSPrintPanel is being
65   // deallocated, so it must be autoreleased within this scope.
66   base::mac::ScopedNSAutoreleasePool pool;
68   DCHECK([NSThread isMainThread]);
70   // We deliberately don't feed max_pages into the dialog, because setting
71   // NSPrintLastPage makes the print dialog pre-select the option to only print
72   // a range.
74   // TODO(stuartmorgan): implement 'print selection only' (probably requires
75   // adding a new custom view to the panel on 10.5; 10.6 has
76   // NSPrintPanelShowsPrintSelection).
77   NSPrintPanel* panel = [NSPrintPanel printPanel];
78   NSPrintInfo* printInfo = print_info_.get();
80   NSPrintPanelOptions options = [panel options];
81   options |= NSPrintPanelShowsPaperSize;
82   options |= NSPrintPanelShowsOrientation;
83   options |= NSPrintPanelShowsScaling;
84   [panel setOptions:options];
86   // Set the print job title text.
87   if (parent_view) {
88     NSString* job_title = [[parent_view window] title];
89     if (job_title) {
90       PMPrintSettings printSettings =
91           (PMPrintSettings)[printInfo PMPrintSettings];
92       PMPrintSettingsSetJobName(printSettings, (CFStringRef)job_title);
93       [printInfo updateFromPMPrintSettings];
94     }
95   }
97   // TODO(stuartmorgan): We really want a tab sheet here, not a modal window.
98   // Will require restructuring the PrintingContext API to use a callback.
99   NSInteger selection = [panel runModalWithPrintInfo:printInfo];
100   if (selection == NSOKButton) {
101     print_info_.reset([[panel printInfo] retain]);
102     settings_.set_ranges(GetPageRangesFromPrintInfo());
103     InitPrintSettingsFromPrintInfo();
104     callback.Run(OK);
105   } else {
106     callback.Run(CANCEL);
107   }
110 gfx::Size PrintingContextMac::GetPdfPaperSizeDeviceUnits() {
111   // NOTE: Reset |print_info_| with a copy of |sharedPrintInfo| so as to start
112   // with a clean slate.
113   print_info_.reset([[NSPrintInfo sharedPrintInfo] copy]);
114   UpdatePageFormatWithPaperInfo();
116   PMPageFormat page_format =
117       static_cast<PMPageFormat>([print_info_.get() PMPageFormat]);
118   PMRect paper_rect;
119   PMGetAdjustedPaperRect(page_format, &paper_rect);
121   // Device units are in points. Units per inch is 72.
122   gfx::Size physical_size_device_units(
123       (paper_rect.right - paper_rect.left),
124       (paper_rect.bottom - paper_rect.top));
125   DCHECK(settings_.device_units_per_inch() == kPointsPerInch);
126   return physical_size_device_units;
129 PrintingContext::Result PrintingContextMac::UseDefaultSettings() {
130   DCHECK(!in_print_job_);
132   print_info_.reset([[NSPrintInfo sharedPrintInfo] copy]);
133   settings_.set_ranges(GetPageRangesFromPrintInfo());
134   InitPrintSettingsFromPrintInfo();
136   return OK;
139 PrintingContext::Result PrintingContextMac::UpdatePrinterSettings(
140     bool external_preview) {
141   DCHECK(!in_print_job_);
143   // NOTE: Reset |print_info_| with a copy of |sharedPrintInfo| so as to start
144   // with a clean slate.
145   print_info_.reset([[NSPrintInfo sharedPrintInfo] copy]);
147   if (external_preview) {
148     if (!SetPrintPreviewJob())
149       return OnError();
150   } else {
151     // Don't need this for preview.
152     if (!SetPrinter(base::UTF16ToUTF8(settings_.device_name())) ||
153         !SetCopiesInPrintSettings(settings_.copies()) ||
154         !SetCollateInPrintSettings(settings_.collate()) ||
155         !SetDuplexModeInPrintSettings(settings_.duplex_mode()) ||
156         !SetOutputColor(settings_.color())) {
157       return OnError();
158     }
159   }
161   if (!UpdatePageFormatWithPaperInfo() ||
162       !SetOrientationIsLandscape(settings_.landscape())) {
163     return OnError();
164   }
166   [print_info_.get() updateFromPMPrintSettings];
168   InitPrintSettingsFromPrintInfo();
169   return OK;
172 bool PrintingContextMac::SetPrintPreviewJob() {
173   PMPrintSession print_session =
174       static_cast<PMPrintSession>([print_info_.get() PMPrintSession]);
175   PMPrintSettings print_settings =
176       static_cast<PMPrintSettings>([print_info_.get() PMPrintSettings]);
177   return PMSessionSetDestination(
178       print_session, print_settings, kPMDestinationPreview,
179       NULL, NULL) == noErr;
182 void PrintingContextMac::InitPrintSettingsFromPrintInfo() {
183   PMPrintSession print_session =
184       static_cast<PMPrintSession>([print_info_.get() PMPrintSession]);
185   PMPageFormat page_format =
186       static_cast<PMPageFormat>([print_info_.get() PMPageFormat]);
187   PMPrinter printer;
188   PMSessionGetCurrentPrinter(print_session, &printer);
189   PrintSettingsInitializerMac::InitPrintSettings(
190       printer, page_format, &settings_);
193 bool PrintingContextMac::SetPrinter(const std::string& device_name) {
194   DCHECK(print_info_.get());
195   PMPrintSession print_session =
196       static_cast<PMPrintSession>([print_info_.get() PMPrintSession]);
198   PMPrinter current_printer;
199   if (PMSessionGetCurrentPrinter(print_session, &current_printer) != noErr)
200     return false;
202   CFStringRef current_printer_id = PMPrinterGetID(current_printer);
203   if (!current_printer_id)
204     return false;
206   base::ScopedCFTypeRef<CFStringRef> new_printer_id(
207       base::SysUTF8ToCFStringRef(device_name));
208   if (!new_printer_id.get())
209     return false;
211   if (CFStringCompare(new_printer_id.get(), current_printer_id, 0) ==
212           kCFCompareEqualTo) {
213     return true;
214   }
216   PMPrinter new_printer = PMPrinterCreateFromPrinterID(new_printer_id.get());
217   if (new_printer == NULL)
218     return false;
220   OSStatus status = PMSessionSetCurrentPMPrinter(print_session, new_printer);
221   PMRelease(new_printer);
222   return status == noErr;
225 bool PrintingContextMac::UpdatePageFormatWithPaperInfo() {
226   PMPrintSession print_session =
227       static_cast<PMPrintSession>([print_info_.get() PMPrintSession]);
229   PMPageFormat default_page_format =
230       static_cast<PMPageFormat>([print_info_.get() PMPageFormat]);
232   PMPaper default_paper;
233   if (PMGetPageFormatPaper(default_page_format, &default_paper) != noErr)
234     return false;
236   double default_page_width = 0.0;
237   double default_page_height = 0.0;
238   if (PMPaperGetWidth(default_paper, &default_page_width) != noErr)
239     return false;
241   if (PMPaperGetHeight(default_paper, &default_page_height) != noErr)
242     return false;
244   PMPrinter current_printer = NULL;
245   if (PMSessionGetCurrentPrinter(print_session, &current_printer) != noErr)
246     return false;
248   if (current_printer == nil)
249     return false;
251   CFArrayRef paper_list = NULL;
252   if (PMPrinterGetPaperList(current_printer, &paper_list) != noErr)
253     return false;
255   double best_match = std::numeric_limits<double>::max();
256   PMPaper best_matching_paper = kPMNoData;
257   int num_papers = CFArrayGetCount(paper_list);
258   for (int i = 0; i < num_papers; ++i) {
259     PMPaper paper = (PMPaper)[(NSArray*)paper_list objectAtIndex: i];
260     double paper_width = 0.0;
261     double paper_height = 0.0;
262     PMPaperGetWidth(paper, &paper_width);
263     PMPaperGetHeight(paper, &paper_height);
264     double current_match = std::max(fabs(default_page_width - paper_width),
265                                     fabs(default_page_height - paper_height));
266     // Ignore paper sizes that are very different.
267     if (current_match > 2)
268       continue;
269     current_match += IsPaperNameEqual(paper, default_paper) ? 0 : 1;
270     if (current_match < best_match) {
271       best_matching_paper = paper;
272       best_match = current_match;
273     }
274   }
276   if (best_matching_paper == kPMNoData) {
277     PMPaper paper = kPMNoData;
278     // Create a custom paper for the specified default page size.
279     PMPaperMargins default_margins;
280     if (PMPaperGetMargins(default_paper, &default_margins) != noErr)
281       return false;
283     const PMPaperMargins margins =
284         {default_margins.top, default_margins.left, default_margins.bottom,
285          default_margins.right};
286     CFStringRef paper_id = CFSTR("Custom paper ID");
287     CFStringRef paper_name = CFSTR("Custom paper");
288     if (PMPaperCreateCustom(current_printer, paper_id, paper_name,
289             default_page_width, default_page_height, &margins, &paper) !=
290             noErr) {
291       return false;
292     }
293     [print_info_.get() updateFromPMPageFormat];
294     PMRelease(paper);
295   } else {
296     PMPageFormat chosen_page_format = NULL;
297     if (PMCreatePageFormat((PMPageFormat*) &chosen_page_format) != noErr)
298       return false;
300     // Create page format from that paper.
301     if (PMCreatePageFormatWithPMPaper(&chosen_page_format,
302             best_matching_paper) != noErr) {
303       PMRelease(chosen_page_format);
304       return false;
305     }
306     // Copy over the original format with the new page format.
307     if (PMCopyPageFormat(chosen_page_format, default_page_format) != noErr) {
308       PMRelease(chosen_page_format);
309       return false;
310     }
311     [print_info_.get() updateFromPMPageFormat];
312     PMRelease(chosen_page_format);
313   }
314   return true;
317 bool PrintingContextMac::SetCopiesInPrintSettings(int copies) {
318   if (copies < 1)
319     return false;
321   PMPrintSettings pmPrintSettings =
322       static_cast<PMPrintSettings>([print_info_.get() PMPrintSettings]);
323   return PMSetCopies(pmPrintSettings, copies, false) == noErr;
326 bool PrintingContextMac::SetCollateInPrintSettings(bool collate) {
327   PMPrintSettings pmPrintSettings =
328       static_cast<PMPrintSettings>([print_info_.get() PMPrintSettings]);
329   return PMSetCollate(pmPrintSettings, collate) == noErr;
332 bool PrintingContextMac::SetOrientationIsLandscape(bool landscape) {
333   PMPageFormat page_format =
334       static_cast<PMPageFormat>([print_info_.get() PMPageFormat]);
336   PMOrientation orientation = landscape ? kPMLandscape : kPMPortrait;
338   if (PMSetOrientation(page_format, orientation, false) != noErr)
339     return false;
341   PMPrintSession print_session =
342       static_cast<PMPrintSession>([print_info_.get() PMPrintSession]);
344   PMSessionValidatePageFormat(print_session, page_format, kPMDontWantBoolean);
346   [print_info_.get() updateFromPMPageFormat];
347   return true;
350 bool PrintingContextMac::SetDuplexModeInPrintSettings(DuplexMode mode) {
351   PMDuplexMode duplexSetting;
352   switch (mode) {
353     case LONG_EDGE:
354       duplexSetting = kPMDuplexNoTumble;
355       break;
356     case SHORT_EDGE:
357       duplexSetting = kPMDuplexTumble;
358       break;
359     case SIMPLEX:
360       duplexSetting = kPMDuplexNone;
361       break;
362     default:  // UNKNOWN_DUPLEX_MODE
363       return true;
364   }
366   PMPrintSettings pmPrintSettings =
367       static_cast<PMPrintSettings>([print_info_.get() PMPrintSettings]);
368   return PMSetDuplex(pmPrintSettings, duplexSetting) == noErr;
371 bool PrintingContextMac::SetOutputColor(int color_mode) {
372   PMPrintSettings pmPrintSettings =
373       static_cast<PMPrintSettings>([print_info_.get() PMPrintSettings]);
374   std::string color_setting_name;
375   std::string color_value;
376   GetColorModelForMode(color_mode, &color_setting_name, &color_value);
377   base::ScopedCFTypeRef<CFStringRef> color_setting(
378       base::SysUTF8ToCFStringRef(color_setting_name));
379   base::ScopedCFTypeRef<CFStringRef> output_color(
380       base::SysUTF8ToCFStringRef(color_value));
382   return PMPrintSettingsSetValue(pmPrintSettings,
383                                  color_setting.get(),
384                                  output_color.get(),
385                                  false) == noErr;
388 PageRanges PrintingContextMac::GetPageRangesFromPrintInfo() {
389   PageRanges page_ranges;
390   NSDictionary* print_info_dict = [print_info_.get() dictionary];
391   if (![[print_info_dict objectForKey:NSPrintAllPages] boolValue]) {
392     PageRange range;
393     range.from = [[print_info_dict objectForKey:NSPrintFirstPage] intValue] - 1;
394     range.to = [[print_info_dict objectForKey:NSPrintLastPage] intValue] - 1;
395     page_ranges.push_back(range);
396   }
397   return page_ranges;
400 PrintingContext::Result PrintingContextMac::InitWithSettings(
401     const PrintSettings& settings) {
402   DCHECK(!in_print_job_);
404   settings_ = settings;
406   NOTIMPLEMENTED();
408   return FAILED;
411 PrintingContext::Result PrintingContextMac::NewDocument(
412     const base::string16& document_name) {
413   DCHECK(!in_print_job_);
415   in_print_job_ = true;
417   PMPrintSession print_session =
418       static_cast<PMPrintSession>([print_info_.get() PMPrintSession]);
419   PMPrintSettings print_settings =
420       static_cast<PMPrintSettings>([print_info_.get() PMPrintSettings]);
421   PMPageFormat page_format =
422       static_cast<PMPageFormat>([print_info_.get() PMPageFormat]);
424   base::ScopedCFTypeRef<CFStringRef> job_title(
425       base::SysUTF16ToCFStringRef(document_name));
426   PMPrintSettingsSetJobName(print_settings, job_title.get());
428   OSStatus status = PMSessionBeginCGDocumentNoDialog(print_session,
429                                                      print_settings,
430                                                      page_format);
431   if (status != noErr)
432     return OnError();
434   return OK;
437 PrintingContext::Result PrintingContextMac::NewPage() {
438   if (abort_printing_)
439     return CANCEL;
440   DCHECK(in_print_job_);
441   DCHECK(!context_);
443   PMPrintSession print_session =
444       static_cast<PMPrintSession>([print_info_.get() PMPrintSession]);
445   PMPageFormat page_format =
446       static_cast<PMPageFormat>([print_info_.get() PMPageFormat]);
447   OSStatus status;
448   status = PMSessionBeginPageNoDialog(print_session, page_format, NULL);
449   if (status != noErr)
450     return OnError();
451   status = PMSessionGetCGGraphicsContext(print_session, &context_);
452   if (status != noErr)
453     return OnError();
455   return OK;
458 PrintingContext::Result PrintingContextMac::PageDone() {
459   if (abort_printing_)
460     return CANCEL;
461   DCHECK(in_print_job_);
462   DCHECK(context_);
464   PMPrintSession print_session =
465       static_cast<PMPrintSession>([print_info_.get() PMPrintSession]);
466   OSStatus status = PMSessionEndPageNoDialog(print_session);
467   if (status != noErr)
468     OnError();
469   context_ = NULL;
471   return OK;
474 PrintingContext::Result PrintingContextMac::DocumentDone() {
475   if (abort_printing_)
476     return CANCEL;
477   DCHECK(in_print_job_);
479   PMPrintSession print_session =
480       static_cast<PMPrintSession>([print_info_.get() PMPrintSession]);
481   OSStatus status = PMSessionEndDocumentNoDialog(print_session);
482   if (status != noErr)
483     OnError();
485   ResetSettings();
486   return OK;
489 void PrintingContextMac::Cancel() {
490   abort_printing_ = true;
491   in_print_job_ = false;
492   context_ = NULL;
494   PMPrintSession print_session =
495       static_cast<PMPrintSession>([print_info_.get() PMPrintSession]);
496   PMSessionEndPageNoDialog(print_session);
499 void PrintingContextMac::ReleaseContext() {
500   print_info_.reset();
501   context_ = NULL;
504 gfx::NativeDrawingContext PrintingContextMac::context() const {
505   return context_;
508 }  // namespace printing