1 // Copyright (c) 2012 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_win.h"
9 #include "base/strings/string_number_conversions.h"
10 #include "base/strings/utf_string_conversions.h"
11 #include "printing/backend/print_backend.h"
12 #include "printing/backend/win_helper.h"
13 #include "printing/print_settings_initializer_win.h"
14 #include "printing/printed_document.h"
15 #include "printing/printing_utils.h"
16 #include "printing/units.h"
17 #include "skia/ext/platform_device.h"
20 #include "ui/aura/remote_window_tree_host_win.h"
21 #include "ui/aura/window.h"
26 HWND
GetRootWindow(gfx::NativeView view
) {
30 window
= view
->GetHost()->GetAcceleratedWidget();
32 if (view
&& IsWindow(view
)) {
33 window
= GetAncestor(view
, GA_ROOTOWNER
);
37 // TODO(maruel): bug 1214347 Get the right browser window instead.
38 return GetDesktopWindow();
43 } // anonymous namespace
48 PrintingContext
* PrintingContext::Create(const std::string
& app_locale
) {
49 return static_cast<PrintingContext
*>(new PrintingContextWin(app_locale
));
52 PrintingContextWin::PrintingContextWin(const std::string
& app_locale
)
53 : PrintingContext(app_locale
), context_(NULL
), dialog_box_(NULL
) {}
55 PrintingContextWin::~PrintingContextWin() {
59 void PrintingContextWin::AskUserForSettings(
60 gfx::NativeView view
, int max_pages
, bool has_selection
,
61 const PrintSettingsCallback
& callback
) {
62 DCHECK(!in_print_job_
);
63 dialog_box_dismissed_
= false;
65 HWND window
= GetRootWindow(view
);
68 // Show the OS-dependent dialog box.
70 // - OK, the settings are reset and reinitialized with the new settings. OK is
72 // - Apply then Cancel, the settings are reset and reinitialized with the new
73 // settings. CANCEL is returned.
74 // - Cancel, the settings are not changed, the previous setting, if it was
75 // initialized before, are kept. CANCEL is returned.
76 // On failure, the settings are reset and FAILED is returned.
77 PRINTDLGEX dialog_options
= { sizeof(PRINTDLGEX
) };
78 dialog_options
.hwndOwner
= window
;
79 // Disable options we don't support currently.
80 // TODO(maruel): Reuse the previously loaded settings!
81 dialog_options
.Flags
= PD_RETURNDC
| PD_USEDEVMODECOPIESANDCOLLATE
|
82 PD_NOCURRENTPAGE
| PD_HIDEPRINTTOFILE
;
84 dialog_options
.Flags
|= PD_NOSELECTION
;
86 PRINTPAGERANGE ranges
[32];
87 dialog_options
.nStartPage
= START_PAGE_GENERAL
;
89 // Default initialize to print all the pages.
90 memset(ranges
, 0, sizeof(ranges
));
91 ranges
[0].nFromPage
= 1;
92 ranges
[0].nToPage
= max_pages
;
93 dialog_options
.nPageRanges
= 1;
94 dialog_options
.nMaxPageRanges
= arraysize(ranges
);
95 dialog_options
.nMinPage
= 1;
96 dialog_options
.nMaxPage
= max_pages
;
97 dialog_options
.lpPageRanges
= ranges
;
99 // No need to bother, we don't know how many pages are available.
100 dialog_options
.Flags
|= PD_NOPAGENUMS
;
103 if (ShowPrintDialog(&dialog_options
) != S_OK
) {
105 callback
.Run(FAILED
);
108 // TODO(maruel): Support PD_PRINTTOFILE.
109 callback
.Run(ParseDialogResultEx(dialog_options
));
112 PrintingContext::Result
PrintingContextWin::UseDefaultSettings() {
113 DCHECK(!in_print_job_
);
115 PRINTDLG dialog_options
= { sizeof(PRINTDLG
) };
116 dialog_options
.Flags
= PD_RETURNDC
| PD_RETURNDEFAULT
;
117 if (PrintDlg(&dialog_options
))
118 return ParseDialogResult(dialog_options
);
120 // No default printer configured, do we have any printers at all?
121 DWORD bytes_needed
= 0;
122 DWORD count_returned
= 0;
123 (void)::EnumPrinters(PRINTER_ENUM_LOCAL
|PRINTER_ENUM_CONNECTIONS
,
124 NULL
, 2, NULL
, 0, &bytes_needed
, &count_returned
);
126 DCHECK_GE(bytes_needed
, count_returned
* sizeof(PRINTER_INFO_2
));
127 scoped_ptr
<BYTE
[]> printer_info_buffer(new BYTE
[bytes_needed
]);
128 BOOL ret
= ::EnumPrinters(PRINTER_ENUM_LOCAL
|PRINTER_ENUM_CONNECTIONS
,
129 NULL
, 2, printer_info_buffer
.get(),
130 bytes_needed
, &bytes_needed
,
132 if (ret
&& count_returned
) { // have printers
133 // Open the first successfully found printer.
134 const PRINTER_INFO_2
* info_2
=
135 reinterpret_cast<PRINTER_INFO_2
*>(printer_info_buffer
.get());
136 const PRINTER_INFO_2
* info_2_end
= info_2
+ count_returned
;
137 for (; info_2
< info_2_end
; ++info_2
) {
138 ScopedPrinterHandle printer
;
139 if (!printer
.OpenPrinter(info_2
->pPrinterName
))
141 scoped_ptr
<DEVMODE
, base::FreeDeleter
> dev_mode
=
142 CreateDevMode(printer
, NULL
);
143 if (!dev_mode
|| !AllocateContext(info_2
->pPrinterName
, dev_mode
.get(),
147 if (InitializeSettings(*dev_mode
.get(), info_2
->pPrinterName
, NULL
, 0,
162 gfx::Size
PrintingContextWin::GetPdfPaperSizeDeviceUnits() {
163 // Default fallback to Letter size.
164 gfx::SizeF
paper_size(kLetterWidthInch
, kLetterHeightInch
);
166 // Get settings from locale. Paper type buffer length is at most 4.
167 const int paper_type_buffer_len
= 4;
168 wchar_t paper_type_buffer
[paper_type_buffer_len
] = {0};
169 GetLocaleInfo(LOCALE_USER_DEFAULT
, LOCALE_IPAPERSIZE
, paper_type_buffer
,
170 paper_type_buffer_len
);
171 if (wcslen(paper_type_buffer
)) { // The call succeeded.
172 int paper_code
= _wtoi(paper_type_buffer
);
173 switch (paper_code
) {
175 paper_size
.SetSize(kLegalWidthInch
, kLegalHeightInch
);
178 paper_size
.SetSize(kA4WidthInch
, kA4HeightInch
);
181 paper_size
.SetSize(kA3WidthInch
, kA3HeightInch
);
183 default: // DMPAPER_LETTER is used for default fallback.
188 paper_size
.width() * settings_
.device_units_per_inch(),
189 paper_size
.height() * settings_
.device_units_per_inch());
192 PrintingContext::Result
PrintingContextWin::UpdatePrinterSettings(
193 bool external_preview
) {
194 DCHECK(!in_print_job_
);
195 DCHECK(!external_preview
) << "Not implemented";
197 ScopedPrinterHandle printer
;
198 if (!printer
.OpenPrinter(settings_
.device_name().c_str()))
201 // Make printer changes local to Chrome.
202 // See MSDN documentation regarding DocumentProperties.
203 scoped_ptr
<DEVMODE
, base::FreeDeleter
> scoped_dev_mode
=
204 CreateDevModeWithColor(printer
, settings_
.device_name(),
205 settings_
.color() != GRAY
);
206 if (!scoped_dev_mode
)
210 DEVMODE
* dev_mode
= scoped_dev_mode
.get();
211 dev_mode
->dmCopies
= std::max(settings_
.copies(), 1);
212 if (dev_mode
->dmCopies
> 1) { // do not change unless multiple copies
213 dev_mode
->dmFields
|= DM_COPIES
;
214 dev_mode
->dmCollate
= settings_
.collate() ? DMCOLLATE_TRUE
:
218 switch (settings_
.duplex_mode()) {
220 dev_mode
->dmFields
|= DM_DUPLEX
;
221 dev_mode
->dmDuplex
= DMDUP_VERTICAL
;
224 dev_mode
->dmFields
|= DM_DUPLEX
;
225 dev_mode
->dmDuplex
= DMDUP_HORIZONTAL
;
228 dev_mode
->dmFields
|= DM_DUPLEX
;
229 dev_mode
->dmDuplex
= DMDUP_SIMPLEX
;
231 default: // UNKNOWN_DUPLEX_MODE
235 dev_mode
->dmFields
|= DM_ORIENTATION
;
236 dev_mode
->dmOrientation
= settings_
.landscape() ? DMORIENT_LANDSCAPE
:
239 const PrintSettings::RequestedMedia
& requested_media
=
240 settings_
.requested_media();
241 static const int kFromUm
= 100; // Windows uses 0.1mm.
242 int width
= requested_media
.size_microns
.width() / kFromUm
;
243 int height
= requested_media
.size_microns
.height() / kFromUm
;
245 if (base::StringToUint(requested_media
.vendor_id
, &id
) && id
) {
246 dev_mode
->dmFields
|= DM_PAPERSIZE
;
247 dev_mode
->dmPaperSize
= static_cast<short>(id
);
248 } else if (width
> 0 && height
> 0) {
249 dev_mode
->dmFields
|= DM_PAPERWIDTH
;
250 dev_mode
->dmPaperWidth
= width
;
251 dev_mode
->dmFields
|= DM_PAPERLENGTH
;
252 dev_mode
->dmPaperLength
= height
;
256 // Update data using DocumentProperties.
257 scoped_dev_mode
= CreateDevMode(printer
, scoped_dev_mode
.get());
258 if (!scoped_dev_mode
)
261 // Set printer then refresh printer settings.
262 if (!AllocateContext(settings_
.device_name(), scoped_dev_mode
.get(),
266 PrintSettingsInitializerWin::InitPrintSettings(context_
,
267 *scoped_dev_mode
.get(),
272 PrintingContext::Result
PrintingContextWin::InitWithSettings(
273 const PrintSettings
& settings
) {
274 DCHECK(!in_print_job_
);
276 settings_
= settings
;
278 // TODO(maruel): settings_.ToDEVMODE()
279 ScopedPrinterHandle printer
;
280 if (!printer
.OpenPrinter(settings_
.device_name().c_str())) {
286 if (!GetPrinterSettings(printer
, settings_
.device_name()))
294 PrintingContext::Result
PrintingContextWin::NewDocument(
295 const base::string16
& document_name
) {
296 DCHECK(!in_print_job_
);
300 // Set the flag used by the AbortPrintJob dialog procedure.
301 abort_printing_
= false;
303 in_print_job_
= true;
305 // Register the application's AbortProc function with GDI.
306 if (SP_ERROR
== SetAbortProc(context_
, &AbortProc
))
309 DCHECK(SimplifyDocumentTitle(document_name
) == document_name
);
310 DOCINFO di
= { sizeof(DOCINFO
) };
311 di
.lpszDocName
= document_name
.c_str();
313 // Is there a debug dump directory specified? If so, force to print to a file.
314 base::string16 debug_dump_path
=
315 PrintedDocument::CreateDebugDumpPath(document_name
,
316 FILE_PATH_LITERAL(".prn")).value();
317 if (!debug_dump_path
.empty())
318 di
.lpszOutput
= debug_dump_path
.c_str();
320 // No message loop running in unit tests.
321 DCHECK(!base::MessageLoop::current() ||
322 !base::MessageLoop::current()->NestableTasksAllowed());
324 // Begin a print job by calling the StartDoc function.
325 // NOTE: StartDoc() starts a message loop. That causes a lot of problems with
326 // IPC. Make sure recursive task processing is disabled.
327 if (StartDoc(context_
, &di
) <= 0)
333 PrintingContext::Result
PrintingContextWin::NewPage() {
337 DCHECK(in_print_job_
);
339 // Intentional No-op. NativeMetafile::SafePlayback takes care of calling
345 PrintingContext::Result
PrintingContextWin::PageDone() {
348 DCHECK(in_print_job_
);
350 // Intentional No-op. NativeMetafile::SafePlayback takes care of calling
356 PrintingContext::Result
PrintingContextWin::DocumentDone() {
359 DCHECK(in_print_job_
);
362 // Inform the driver that document has ended.
363 if (EndDoc(context_
) <= 0)
370 void PrintingContextWin::Cancel() {
371 abort_printing_
= true;
372 in_print_job_
= false;
376 DestroyWindow(dialog_box_
);
377 dialog_box_dismissed_
= true;
381 void PrintingContextWin::ReleaseContext() {
388 gfx::NativeDrawingContext
PrintingContextWin::context() const {
393 BOOL
PrintingContextWin::AbortProc(HDC hdc
, int nCode
) {
395 // TODO(maruel): Need a way to find the right instance to set. Should
396 // leverage PrintJobManager here?
397 // abort_printing_ = true;
402 bool PrintingContextWin::InitializeSettings(const DEVMODE
& dev_mode
,
403 const std::wstring
& new_device_name
,
404 const PRINTPAGERANGE
* ranges
,
406 bool selection_only
) {
407 skia::InitializeDC(context_
);
408 DCHECK(GetDeviceCaps(context_
, CLIPCAPS
));
409 DCHECK(GetDeviceCaps(context_
, RASTERCAPS
) & RC_STRETCHDIB
);
410 DCHECK(GetDeviceCaps(context_
, RASTERCAPS
) & RC_BITMAP64
);
411 // Some printers don't advertise these.
412 // DCHECK(GetDeviceCaps(context_, RASTERCAPS) & RC_SCALING);
413 // DCHECK(GetDeviceCaps(context_, SHADEBLENDCAPS) & SB_CONST_ALPHA);
414 // DCHECK(GetDeviceCaps(context_, SHADEBLENDCAPS) & SB_PIXEL_ALPHA);
416 // StretchDIBits() support is needed for printing.
417 if (!(GetDeviceCaps(context_
, RASTERCAPS
) & RC_STRETCHDIB
) ||
418 !(GetDeviceCaps(context_
, RASTERCAPS
) & RC_BITMAP64
)) {
424 DCHECK(!in_print_job_
);
426 PageRanges ranges_vector
;
427 if (!selection_only
) {
428 // Convert the PRINTPAGERANGE array to a PrintSettings::PageRanges vector.
429 ranges_vector
.reserve(number_ranges
);
430 for (int i
= 0; i
< number_ranges
; ++i
) {
432 // Transfer from 1-based to 0-based.
433 range
.from
= ranges
[i
].nFromPage
- 1;
434 range
.to
= ranges
[i
].nToPage
- 1;
435 ranges_vector
.push_back(range
);
439 settings_
.set_ranges(ranges_vector
);
440 settings_
.set_device_name(new_device_name
);
441 settings_
.set_selection_only(selection_only
);
442 PrintSettingsInitializerWin::InitPrintSettings(context_
, dev_mode
,
448 bool PrintingContextWin::GetPrinterSettings(HANDLE printer
,
449 const std::wstring
& device_name
) {
450 DCHECK(!in_print_job_
);
452 scoped_ptr
<DEVMODE
, base::FreeDeleter
> dev_mode
=
453 CreateDevMode(printer
, NULL
);
455 if (!dev_mode
|| !AllocateContext(device_name
, dev_mode
.get(), &context_
)) {
460 return InitializeSettings(*dev_mode
.get(), device_name
, NULL
, 0, false);
464 bool PrintingContextWin::AllocateContext(const std::wstring
& device_name
,
465 const DEVMODE
* dev_mode
,
466 gfx::NativeDrawingContext
* context
) {
467 *context
= CreateDC(L
"WINSPOOL", device_name
.c_str(), NULL
, dev_mode
);
469 return *context
!= NULL
;
472 PrintingContext::Result
PrintingContextWin::ParseDialogResultEx(
473 const PRINTDLGEX
& dialog_options
) {
474 // If the user clicked OK or Apply then Cancel, but not only Cancel.
475 if (dialog_options
.dwResultAction
!= PD_RESULT_CANCEL
) {
479 DEVMODE
* dev_mode
= NULL
;
480 if (dialog_options
.hDevMode
) {
482 reinterpret_cast<DEVMODE
*>(GlobalLock(dialog_options
.hDevMode
));
486 std::wstring device_name
;
487 if (dialog_options
.hDevNames
) {
488 DEVNAMES
* dev_names
=
489 reinterpret_cast<DEVNAMES
*>(GlobalLock(dialog_options
.hDevNames
));
492 device_name
= reinterpret_cast<const wchar_t*>(dev_names
) +
493 dev_names
->wDeviceOffset
;
494 GlobalUnlock(dialog_options
.hDevNames
);
498 bool success
= false;
499 if (dev_mode
&& !device_name
.empty()) {
500 context_
= dialog_options
.hDC
;
501 PRINTPAGERANGE
* page_ranges
= NULL
;
502 DWORD num_page_ranges
= 0;
503 bool print_selection_only
= false;
504 if (dialog_options
.Flags
& PD_PAGENUMS
) {
505 page_ranges
= dialog_options
.lpPageRanges
;
506 num_page_ranges
= dialog_options
.nPageRanges
;
508 if (dialog_options
.Flags
& PD_SELECTION
) {
509 print_selection_only
= true;
511 success
= InitializeSettings(*dev_mode
,
515 print_selection_only
);
518 if (!success
&& dialog_options
.hDC
) {
519 DeleteDC(dialog_options
.hDC
);
524 GlobalUnlock(dialog_options
.hDevMode
);
527 if (dialog_options
.hDC
) {
528 DeleteDC(dialog_options
.hDC
);
532 if (dialog_options
.hDevMode
!= NULL
)
533 GlobalFree(dialog_options
.hDevMode
);
534 if (dialog_options
.hDevNames
!= NULL
)
535 GlobalFree(dialog_options
.hDevNames
);
537 switch (dialog_options
.dwResultAction
) {
538 case PD_RESULT_PRINT
:
539 return context_
? OK
: FAILED
;
540 case PD_RESULT_APPLY
:
541 return context_
? CANCEL
: FAILED
;
542 case PD_RESULT_CANCEL
:
549 HRESULT
PrintingContextWin::ShowPrintDialog(PRINTDLGEX
* options
) {
550 // Note that this cannot use ui::BaseShellDialog as the print dialog is
551 // system modal: opening it from a background thread can cause Windows to
552 // get the wrong Z-order which will make the print dialog appear behind the
553 // browser frame (but still being modal) so neither the browser frame nor
554 // the print dialog will get any input. See http://crbug.com/342697
555 // http://crbug.com/180997 for details.
556 base::MessageLoop::ScopedNestableTaskAllower
allow(
557 base::MessageLoop::current());
559 return PrintDlgEx(options
);
562 PrintingContext::Result
PrintingContextWin::ParseDialogResult(
563 const PRINTDLG
& dialog_options
) {
564 // If the user clicked OK or Apply then Cancel, but not only Cancel.
568 DEVMODE
* dev_mode
= NULL
;
569 if (dialog_options
.hDevMode
) {
571 reinterpret_cast<DEVMODE
*>(GlobalLock(dialog_options
.hDevMode
));
575 std::wstring device_name
;
576 if (dialog_options
.hDevNames
) {
577 DEVNAMES
* dev_names
=
578 reinterpret_cast<DEVNAMES
*>(GlobalLock(dialog_options
.hDevNames
));
582 reinterpret_cast<const wchar_t*>(
583 reinterpret_cast<const wchar_t*>(dev_names
) +
584 dev_names
->wDeviceOffset
);
585 GlobalUnlock(dialog_options
.hDevNames
);
589 bool success
= false;
590 if (dev_mode
&& !device_name
.empty()) {
591 context_
= dialog_options
.hDC
;
592 success
= InitializeSettings(*dev_mode
, device_name
, NULL
, 0, false);
595 if (!success
&& dialog_options
.hDC
) {
596 DeleteDC(dialog_options
.hDC
);
601 GlobalUnlock(dialog_options
.hDevMode
);
604 if (dialog_options
.hDevMode
!= NULL
)
605 GlobalFree(dialog_options
.hDevMode
);
606 if (dialog_options
.hDevNames
!= NULL
)
607 GlobalFree(dialog_options
.hDevNames
);
609 return context_
? OK
: FAILED
;
612 } // namespace printing