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>
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"
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);
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]),
50 PrintingContextMac::~PrintingContextMac() {
54 void PrintingContextMac::AskUserForSettings(
55 gfx::NativeView parent_view,
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
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.
88 NSString* job_title = [[parent_view window] title];
90 PMPrintSettings printSettings =
91 (PMPrintSettings)[printInfo PMPrintSettings];
92 PMPrintSettingsSetJobName(printSettings, (CFStringRef)job_title);
93 [printInfo updateFromPMPrintSettings];
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();
106 callback.Run(CANCEL);
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]);
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();
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())
151 // Don't need this for preview.
152 if (!SetPrinter(UTF16ToUTF8(settings_.device_name())) ||
153 !SetCopiesInPrintSettings(settings_.copies()) ||
154 !SetCollateInPrintSettings(settings_.collate()) ||
155 !SetDuplexModeInPrintSettings(settings_.duplex_mode()) ||
156 !SetOutputColor(settings_.color())) {
161 if (!UpdatePageFormatWithPaperInfo() ||
162 !SetOrientationIsLandscape(settings_.landscape())) {
166 [print_info_.get() updateFromPMPrintSettings];
168 InitPrintSettingsFromPrintInfo();
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]);
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, ¤t_printer) != noErr)
202 CFStringRef current_printer_id = PMPrinterGetID(current_printer);
203 if (!current_printer_id)
206 base::ScopedCFTypeRef<CFStringRef> new_printer_id(
207 base::SysUTF8ToCFStringRef(device_name));
208 if (!new_printer_id.get())
211 if (CFStringCompare(new_printer_id.get(), current_printer_id, 0) ==
216 PMPrinter new_printer = PMPrinterCreateFromPrinterID(new_printer_id.get());
217 if (new_printer == NULL)
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)
236 double default_page_width = 0.0;
237 double default_page_height = 0.0;
238 if (PMPaperGetWidth(default_paper, &default_page_width) != noErr)
241 if (PMPaperGetHeight(default_paper, &default_page_height) != noErr)
244 PMPrinter current_printer = NULL;
245 if (PMSessionGetCurrentPrinter(print_session, ¤t_printer) != noErr)
248 if (current_printer == nil)
251 CFArrayRef paper_list = NULL;
252 if (PMPrinterGetPaperList(current_printer, &paper_list) != noErr)
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)
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;
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)
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) !=
293 [print_info_.get() updateFromPMPageFormat];
296 PMPageFormat chosen_page_format = NULL;
297 if (PMCreatePageFormat((PMPageFormat*) &chosen_page_format) != noErr)
300 // Create page format from that paper.
301 if (PMCreatePageFormatWithPMPaper(&chosen_page_format,
302 best_matching_paper) != noErr) {
303 PMRelease(chosen_page_format);
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);
311 [print_info_.get() updateFromPMPageFormat];
312 PMRelease(chosen_page_format);
317 bool PrintingContextMac::SetCopiesInPrintSettings(int copies) {
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)
341 PMPrintSession print_session =
342 static_cast<PMPrintSession>([print_info_.get() PMPrintSession]);
344 PMSessionValidatePageFormat(print_session, page_format, kPMDontWantBoolean);
346 [print_info_.get() updateFromPMPageFormat];
350 bool PrintingContextMac::SetDuplexModeInPrintSettings(DuplexMode mode) {
351 PMDuplexMode duplexSetting;
354 duplexSetting = kPMDuplexNoTumble;
357 duplexSetting = kPMDuplexTumble;
360 duplexSetting = kPMDuplexNone;
362 default: // UNKNOWN_DUPLEX_MODE
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,
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]) {
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);
400 PrintingContext::Result PrintingContextMac::InitWithSettings(
401 const PrintSettings& settings) {
402 DCHECK(!in_print_job_);
404 settings_ = settings;
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,
437 PrintingContext::Result PrintingContextMac::NewPage() {
440 DCHECK(in_print_job_);
443 PMPrintSession print_session =
444 static_cast<PMPrintSession>([print_info_.get() PMPrintSession]);
445 PMPageFormat page_format =
446 static_cast<PMPageFormat>([print_info_.get() PMPageFormat]);
448 status = PMSessionBeginPageNoDialog(print_session, page_format, NULL);
451 status = PMSessionGetCGGraphicsContext(print_session, &context_);
458 PrintingContext::Result PrintingContextMac::PageDone() {
461 DCHECK(in_print_job_);
464 PMPrintSession print_session =
465 static_cast<PMPrintSession>([print_info_.get() PMPrintSession]);
466 OSStatus status = PMSessionEndPageNoDialog(print_session);
474 PrintingContext::Result PrintingContextMac::DocumentDone() {
477 DCHECK(in_print_job_);
479 PMPrintSession print_session =
480 static_cast<PMPrintSession>([print_info_.get() PMPrintSession]);
481 OSStatus status = PMSessionEndDocumentNoDialog(print_session);
489 void PrintingContextMac::Cancel() {
490 abort_printing_ = true;
491 in_print_job_ = false;
494 PMPrintSession print_session =
495 static_cast<PMPrintSession>([print_info_.get() PMPrintSession]);
496 PMSessionEndPageNoDialog(print_session);
499 void PrintingContextMac::ReleaseContext() {
504 gfx::NativeDrawingContext PrintingContextMac::context() const {
508 } // namespace printing