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"
11 #include "base/i18n/file_util_icu.h"
12 #include "base/i18n/time_formatting.h"
13 #include "base/message_loop/message_loop.h"
14 #include "base/metrics/histogram.h"
15 #include "base/strings/utf_string_conversions.h"
16 #include "base/time/time.h"
17 #include "base/values.h"
18 #include "base/win/metro.h"
19 #include "printing/backend/print_backend.h"
20 #include "printing/backend/printing_info_win.h"
21 #include "printing/backend/win_helper.h"
22 #include "printing/print_job_constants.h"
23 #include "printing/print_settings_initializer_win.h"
24 #include "printing/printed_document.h"
25 #include "printing/printing_utils.h"
26 #include "printing/units.h"
27 #include "skia/ext/platform_device.h"
28 #include "win8/util/win8_util.h"
31 #include "ui/aura/remote_window_tree_host_win.h"
32 #include "ui/aura/window.h"
33 #include "ui/aura/window_event_dispatcher.h"
40 HWND
GetRootWindow(gfx::NativeView view
) {
44 window
= view
->GetHost()->GetAcceleratedWidget();
46 if (view
&& IsWindow(view
)) {
47 window
= GetAncestor(view
, GA_ROOTOWNER
);
51 // TODO(maruel): bug 1214347 Get the right browser window instead.
52 return GetDesktopWindow();
57 } // anonymous namespace
61 class PrintingContextWin::CallbackHandler
: public IPrintDialogCallback
,
62 public IObjectWithSite
{
64 CallbackHandler(PrintingContextWin
& owner
, HWND owner_hwnd
)
66 owner_hwnd_(owner_hwnd
),
75 IUnknown
* ToIUnknown() {
76 return static_cast<IUnknown
*>(static_cast<IPrintDialogCallback
*>(this));
80 virtual HRESULT WINAPI
QueryInterface(REFIID riid
, void**object
) {
81 if (riid
== IID_IUnknown
) {
82 *object
= ToIUnknown();
83 } else if (riid
== IID_IPrintDialogCallback
) {
84 *object
= static_cast<IPrintDialogCallback
*>(this);
85 } else if (riid
== IID_IObjectWithSite
) {
86 *object
= static_cast<IObjectWithSite
*>(this);
93 // No real ref counting.
94 virtual ULONG WINAPI
AddRef() {
97 virtual ULONG WINAPI
Release() {
101 // IPrintDialogCallback methods
102 virtual HRESULT WINAPI
InitDone() {
106 virtual HRESULT WINAPI
SelectionChange() {
108 // TODO(maruel): Get the devmode for the new printer with
109 // services_->GetCurrentDevMode(&devmode, &size), send that information
110 // back to our client and continue. The client needs to recalculate the
111 // number of rendered pages and send back this information here.
116 virtual HRESULT WINAPI
HandleMessage(HWND dialog
,
121 // Cheap way to retrieve the window handle.
122 if (!owner_
.dialog_box_
) {
123 // The handle we receive is the one of the groupbox in the General tab. We
124 // need to get the grand-father to get the dialog box handle.
125 owner_
.dialog_box_
= GetAncestor(dialog
, GA_ROOT
);
126 // Trick to enable the owner window. This can cause issues with navigation
127 // events so it may have to be disabled if we don't fix the side-effects.
128 EnableWindow(owner_hwnd_
, TRUE
);
133 virtual HRESULT WINAPI
SetSite(IUnknown
* site
) {
136 services_
->Release();
138 // The dialog box is destroying, PrintJob::Worker don't need the handle
140 owner_
.dialog_box_
= NULL
;
142 DCHECK(services_
== NULL
);
143 HRESULT hr
= site
->QueryInterface(IID_IPrintDialogServices
,
144 reinterpret_cast<void**>(&services_
));
145 DCHECK(SUCCEEDED(hr
));
150 virtual HRESULT WINAPI
GetSite(REFIID riid
, void** site
) {
155 PrintingContextWin
& owner_
;
157 IPrintDialogServices
* services_
;
159 DISALLOW_COPY_AND_ASSIGN(CallbackHandler
);
163 PrintingContext
* PrintingContext::Create(const std::string
& app_locale
) {
164 return static_cast<PrintingContext
*>(new PrintingContextWin(app_locale
));
167 PrintingContextWin::PrintingContextWin(const std::string
& app_locale
)
168 : PrintingContext(app_locale
), context_(NULL
), dialog_box_(NULL
) {}
170 PrintingContextWin::~PrintingContextWin() {
174 void PrintingContextWin::AskUserForSettings(
175 gfx::NativeView view
, int max_pages
, bool has_selection
,
176 const PrintSettingsCallback
& callback
) {
177 DCHECK(!in_print_job_
);
178 if (win8::IsSingleWindowMetroMode()) {
179 // The system dialog can not be opened while running in Metro.
180 // But we can programatically launch the Metro print device charm though.
181 HMODULE metro_module
= base::win::GetMetroModule();
182 if (metro_module
!= NULL
) {
183 typedef void (*MetroShowPrintUI
)();
184 MetroShowPrintUI metro_show_print_ui
=
185 reinterpret_cast<MetroShowPrintUI
>(
186 ::GetProcAddress(metro_module
, "MetroShowPrintUI"));
187 if (metro_show_print_ui
) {
188 // TODO(mad): Remove this once we can send user metrics from the metro
189 // driver. crbug.com/142330
190 UMA_HISTOGRAM_ENUMERATION("Metro.Print", 1, 2);
191 metro_show_print_ui();
194 return callback
.Run(CANCEL
);
196 dialog_box_dismissed_
= false;
198 HWND window
= GetRootWindow(view
);
201 // Show the OS-dependent dialog box.
203 // - OK, the settings are reset and reinitialized with the new settings. OK is
205 // - Apply then Cancel, the settings are reset and reinitialized with the new
206 // settings. CANCEL is returned.
207 // - Cancel, the settings are not changed, the previous setting, if it was
208 // initialized before, are kept. CANCEL is returned.
209 // On failure, the settings are reset and FAILED is returned.
210 PRINTDLGEX dialog_options
= { sizeof(PRINTDLGEX
) };
211 dialog_options
.hwndOwner
= window
;
212 // Disable options we don't support currently.
213 // TODO(maruel): Reuse the previously loaded settings!
214 dialog_options
.Flags
= PD_RETURNDC
| PD_USEDEVMODECOPIESANDCOLLATE
|
215 PD_NOCURRENTPAGE
| PD_HIDEPRINTTOFILE
;
217 dialog_options
.Flags
|= PD_NOSELECTION
;
219 PRINTPAGERANGE ranges
[32];
220 dialog_options
.nStartPage
= START_PAGE_GENERAL
;
222 // Default initialize to print all the pages.
223 memset(ranges
, 0, sizeof(ranges
));
224 ranges
[0].nFromPage
= 1;
225 ranges
[0].nToPage
= max_pages
;
226 dialog_options
.nPageRanges
= 1;
227 dialog_options
.nMaxPageRanges
= arraysize(ranges
);
228 dialog_options
.nMinPage
= 1;
229 dialog_options
.nMaxPage
= max_pages
;
230 dialog_options
.lpPageRanges
= ranges
;
232 // No need to bother, we don't know how many pages are available.
233 dialog_options
.Flags
|= PD_NOPAGENUMS
;
236 if (ShowPrintDialog(&dialog_options
) != S_OK
) {
238 callback
.Run(FAILED
);
241 // TODO(maruel): Support PD_PRINTTOFILE.
242 callback
.Run(ParseDialogResultEx(dialog_options
));
245 PrintingContext::Result
PrintingContextWin::UseDefaultSettings() {
246 DCHECK(!in_print_job_
);
248 PRINTDLG dialog_options
= { sizeof(PRINTDLG
) };
249 dialog_options
.Flags
= PD_RETURNDC
| PD_RETURNDEFAULT
;
250 if (PrintDlg(&dialog_options
))
251 return ParseDialogResult(dialog_options
);
253 // No default printer configured, do we have any printers at all?
254 DWORD bytes_needed
= 0;
255 DWORD count_returned
= 0;
256 (void)::EnumPrinters(PRINTER_ENUM_LOCAL
|PRINTER_ENUM_CONNECTIONS
,
257 NULL
, 2, NULL
, 0, &bytes_needed
, &count_returned
);
259 DCHECK_GE(bytes_needed
, count_returned
* sizeof(PRINTER_INFO_2
));
260 scoped_ptr
<BYTE
[]> printer_info_buffer(new BYTE
[bytes_needed
]);
261 BOOL ret
= ::EnumPrinters(PRINTER_ENUM_LOCAL
|PRINTER_ENUM_CONNECTIONS
,
262 NULL
, 2, printer_info_buffer
.get(),
263 bytes_needed
, &bytes_needed
,
265 if (ret
&& count_returned
) { // have printers
266 // Open the first successfully found printer.
267 const PRINTER_INFO_2
* info_2
=
268 reinterpret_cast<PRINTER_INFO_2
*>(printer_info_buffer
.get());
269 const PRINTER_INFO_2
* info_2_end
= info_2
+ count_returned
;
270 for (; info_2
< info_2_end
; ++info_2
) {
271 ScopedPrinterHandle printer
;
272 if (!printer
.OpenPrinter(info_2
->pPrinterName
))
274 scoped_ptr
<DEVMODE
, base::FreeDeleter
> dev_mode
=
275 CreateDevMode(printer
, NULL
);
276 if (!dev_mode
|| !AllocateContext(info_2
->pPrinterName
, dev_mode
.get(),
280 if (InitializeSettings(*dev_mode
.get(), info_2
->pPrinterName
, NULL
, 0,
295 gfx::Size
PrintingContextWin::GetPdfPaperSizeDeviceUnits() {
296 // Default fallback to Letter size.
297 gfx::SizeF
paper_size(kLetterWidthInch
, kLetterHeightInch
);
299 // Get settings from locale. Paper type buffer length is at most 4.
300 const int paper_type_buffer_len
= 4;
301 wchar_t paper_type_buffer
[paper_type_buffer_len
] = {0};
302 GetLocaleInfo(LOCALE_USER_DEFAULT
, LOCALE_IPAPERSIZE
, paper_type_buffer
,
303 paper_type_buffer_len
);
304 if (wcslen(paper_type_buffer
)) { // The call succeeded.
305 int paper_code
= _wtoi(paper_type_buffer
);
306 switch (paper_code
) {
308 paper_size
.SetSize(kLegalWidthInch
, kLegalHeightInch
);
311 paper_size
.SetSize(kA4WidthInch
, kA4HeightInch
);
314 paper_size
.SetSize(kA3WidthInch
, kA3HeightInch
);
316 default: // DMPAPER_LETTER is used for default fallback.
321 paper_size
.width() * settings_
.device_units_per_inch(),
322 paper_size
.height() * settings_
.device_units_per_inch());
325 PrintingContext::Result
PrintingContextWin::UpdatePrinterSettings(
326 bool external_preview
) {
327 DCHECK(!in_print_job_
);
328 DCHECK(!external_preview
) << "Not implemented";
330 ScopedPrinterHandle printer
;
331 if (!printer
.OpenPrinter(settings_
.device_name().c_str()))
334 // Make printer changes local to Chrome.
335 // See MSDN documentation regarding DocumentProperties.
336 scoped_ptr
<DEVMODE
, base::FreeDeleter
> scoped_dev_mode
=
337 CreateDevModeWithColor(printer
, settings_
.device_name(),
338 settings_
.color() != GRAY
);
339 if (!scoped_dev_mode
)
343 DEVMODE
* dev_mode
= scoped_dev_mode
.get();
344 dev_mode
->dmCopies
= std::max(settings_
.copies(), 1);
345 if (dev_mode
->dmCopies
> 1) { // do not change unless multiple copies
346 dev_mode
->dmFields
|= DM_COPIES
;
347 dev_mode
->dmCollate
= settings_
.collate() ? DMCOLLATE_TRUE
:
351 switch (settings_
.duplex_mode()) {
353 dev_mode
->dmFields
|= DM_DUPLEX
;
354 dev_mode
->dmDuplex
= DMDUP_VERTICAL
;
357 dev_mode
->dmFields
|= DM_DUPLEX
;
358 dev_mode
->dmDuplex
= DMDUP_HORIZONTAL
;
361 dev_mode
->dmFields
|= DM_DUPLEX
;
362 dev_mode
->dmDuplex
= DMDUP_SIMPLEX
;
364 default: // UNKNOWN_DUPLEX_MODE
368 dev_mode
->dmFields
|= DM_ORIENTATION
;
369 dev_mode
->dmOrientation
= settings_
.landscape() ? DMORIENT_LANDSCAPE
:
373 // Update data using DocumentProperties.
374 scoped_dev_mode
= CreateDevMode(printer
, scoped_dev_mode
.get());
375 if (!scoped_dev_mode
)
378 // Set printer then refresh printer settings.
379 if (!AllocateContext(settings_
.device_name(), scoped_dev_mode
.get(),
383 PrintSettingsInitializerWin::InitPrintSettings(context_
,
384 *scoped_dev_mode
.get(),
389 PrintingContext::Result
PrintingContextWin::InitWithSettings(
390 const PrintSettings
& settings
) {
391 DCHECK(!in_print_job_
);
393 settings_
= settings
;
395 // TODO(maruel): settings_.ToDEVMODE()
396 ScopedPrinterHandle printer
;
397 if (!printer
.OpenPrinter(settings_
.device_name().c_str())) {
403 if (!GetPrinterSettings(printer
, settings_
.device_name()))
411 PrintingContext::Result
PrintingContextWin::NewDocument(
412 const base::string16
& document_name
) {
413 DCHECK(!in_print_job_
);
417 // Set the flag used by the AbortPrintJob dialog procedure.
418 abort_printing_
= false;
420 in_print_job_
= true;
422 // Register the application's AbortProc function with GDI.
423 if (SP_ERROR
== SetAbortProc(context_
, &AbortProc
))
426 DCHECK(SimplifyDocumentTitle(document_name
) == document_name
);
427 DOCINFO di
= { sizeof(DOCINFO
) };
428 const std::wstring
& document_name_wide
= base::UTF16ToWide(document_name
);
429 di
.lpszDocName
= document_name_wide
.c_str();
431 // Is there a debug dump directory specified? If so, force to print to a file.
432 base::FilePath debug_dump_path
= PrintedDocument::debug_dump_path();
433 if (!debug_dump_path
.empty()) {
434 // Create a filename.
435 std::wstring filename
;
436 Time
now(Time::Now());
437 filename
= base::TimeFormatShortDateNumeric(now
);
439 filename
+= base::TimeFormatTimeOfDay(now
);
441 filename
+= base::UTF16ToWide(document_name
);
443 filename
+= L
"buffer.prn";
444 file_util::ReplaceIllegalCharactersInPath(&filename
, '_');
445 debug_dump_path
= debug_dump_path
.Append(filename
);
446 di
.lpszOutput
= debug_dump_path
.value().c_str();
449 // No message loop running in unit tests.
450 DCHECK(!base::MessageLoop::current() ||
451 !base::MessageLoop::current()->NestableTasksAllowed());
453 // Begin a print job by calling the StartDoc function.
454 // NOTE: StartDoc() starts a message loop. That causes a lot of problems with
455 // IPC. Make sure recursive task processing is disabled.
456 if (StartDoc(context_
, &di
) <= 0)
462 PrintingContext::Result
PrintingContextWin::NewPage() {
466 DCHECK(in_print_job_
);
468 // Intentional No-op. NativeMetafile::SafePlayback takes care of calling
474 PrintingContext::Result
PrintingContextWin::PageDone() {
477 DCHECK(in_print_job_
);
479 // Intentional No-op. NativeMetafile::SafePlayback takes care of calling
485 PrintingContext::Result
PrintingContextWin::DocumentDone() {
488 DCHECK(in_print_job_
);
491 // Inform the driver that document has ended.
492 if (EndDoc(context_
) <= 0)
499 void PrintingContextWin::Cancel() {
500 abort_printing_
= true;
501 in_print_job_
= false;
505 DestroyWindow(dialog_box_
);
506 dialog_box_dismissed_
= true;
510 void PrintingContextWin::ReleaseContext() {
517 gfx::NativeDrawingContext
PrintingContextWin::context() const {
522 BOOL
PrintingContextWin::AbortProc(HDC hdc
, int nCode
) {
524 // TODO(maruel): Need a way to find the right instance to set. Should
525 // leverage PrintJobManager here?
526 // abort_printing_ = true;
531 bool PrintingContextWin::InitializeSettings(const DEVMODE
& dev_mode
,
532 const std::wstring
& new_device_name
,
533 const PRINTPAGERANGE
* ranges
,
535 bool selection_only
) {
536 skia::InitializeDC(context_
);
537 DCHECK(GetDeviceCaps(context_
, CLIPCAPS
));
538 DCHECK(GetDeviceCaps(context_
, RASTERCAPS
) & RC_STRETCHDIB
);
539 DCHECK(GetDeviceCaps(context_
, RASTERCAPS
) & RC_BITMAP64
);
540 // Some printers don't advertise these.
541 // DCHECK(GetDeviceCaps(context_, RASTERCAPS) & RC_SCALING);
542 // DCHECK(GetDeviceCaps(context_, SHADEBLENDCAPS) & SB_CONST_ALPHA);
543 // DCHECK(GetDeviceCaps(context_, SHADEBLENDCAPS) & SB_PIXEL_ALPHA);
545 // StretchDIBits() support is needed for printing.
546 if (!(GetDeviceCaps(context_
, RASTERCAPS
) & RC_STRETCHDIB
) ||
547 !(GetDeviceCaps(context_
, RASTERCAPS
) & RC_BITMAP64
)) {
553 DCHECK(!in_print_job_
);
555 PageRanges ranges_vector
;
556 if (!selection_only
) {
557 // Convert the PRINTPAGERANGE array to a PrintSettings::PageRanges vector.
558 ranges_vector
.reserve(number_ranges
);
559 for (int i
= 0; i
< number_ranges
; ++i
) {
561 // Transfer from 1-based to 0-based.
562 range
.from
= ranges
[i
].nFromPage
- 1;
563 range
.to
= ranges
[i
].nToPage
- 1;
564 ranges_vector
.push_back(range
);
568 settings_
.set_ranges(ranges_vector
);
569 settings_
.set_device_name(new_device_name
);
570 settings_
.set_selection_only(selection_only
);
571 PrintSettingsInitializerWin::InitPrintSettings(context_
, dev_mode
,
577 bool PrintingContextWin::GetPrinterSettings(HANDLE printer
,
578 const std::wstring
& device_name
) {
579 DCHECK(!in_print_job_
);
581 scoped_ptr
<DEVMODE
, base::FreeDeleter
> dev_mode
=
582 CreateDevMode(printer
, NULL
);
584 if (!dev_mode
|| !AllocateContext(device_name
, dev_mode
.get(), &context_
)) {
589 return InitializeSettings(*dev_mode
.get(), device_name
, NULL
, 0, false);
593 bool PrintingContextWin::AllocateContext(const std::wstring
& device_name
,
594 const DEVMODE
* dev_mode
,
595 gfx::NativeDrawingContext
* context
) {
596 *context
= CreateDC(L
"WINSPOOL", device_name
.c_str(), NULL
, dev_mode
);
598 return *context
!= NULL
;
601 PrintingContext::Result
PrintingContextWin::ParseDialogResultEx(
602 const PRINTDLGEX
& dialog_options
) {
603 // If the user clicked OK or Apply then Cancel, but not only Cancel.
604 if (dialog_options
.dwResultAction
!= PD_RESULT_CANCEL
) {
608 DEVMODE
* dev_mode
= NULL
;
609 if (dialog_options
.hDevMode
) {
611 reinterpret_cast<DEVMODE
*>(GlobalLock(dialog_options
.hDevMode
));
615 std::wstring device_name
;
616 if (dialog_options
.hDevNames
) {
617 DEVNAMES
* dev_names
=
618 reinterpret_cast<DEVNAMES
*>(GlobalLock(dialog_options
.hDevNames
));
621 device_name
= reinterpret_cast<const wchar_t*>(dev_names
) +
622 dev_names
->wDeviceOffset
;
623 GlobalUnlock(dialog_options
.hDevNames
);
627 bool success
= false;
628 if (dev_mode
&& !device_name
.empty()) {
629 context_
= dialog_options
.hDC
;
630 PRINTPAGERANGE
* page_ranges
= NULL
;
631 DWORD num_page_ranges
= 0;
632 bool print_selection_only
= false;
633 if (dialog_options
.Flags
& PD_PAGENUMS
) {
634 page_ranges
= dialog_options
.lpPageRanges
;
635 num_page_ranges
= dialog_options
.nPageRanges
;
637 if (dialog_options
.Flags
& PD_SELECTION
) {
638 print_selection_only
= true;
640 success
= InitializeSettings(*dev_mode
,
644 print_selection_only
);
647 if (!success
&& dialog_options
.hDC
) {
648 DeleteDC(dialog_options
.hDC
);
653 GlobalUnlock(dialog_options
.hDevMode
);
656 if (dialog_options
.hDC
) {
657 DeleteDC(dialog_options
.hDC
);
661 if (dialog_options
.hDevMode
!= NULL
)
662 GlobalFree(dialog_options
.hDevMode
);
663 if (dialog_options
.hDevNames
!= NULL
)
664 GlobalFree(dialog_options
.hDevNames
);
666 switch (dialog_options
.dwResultAction
) {
667 case PD_RESULT_PRINT
:
668 return context_
? OK
: FAILED
;
669 case PD_RESULT_APPLY
:
670 return context_
? CANCEL
: FAILED
;
671 case PD_RESULT_CANCEL
:
678 HRESULT
PrintingContextWin::ShowPrintDialog(PRINTDLGEX
* options
) {
679 // Note that this cannot use ui::BaseShellDialog as the print dialog is
680 // system modal: opening it from a background thread can cause Windows to
681 // get the wrong Z-order which will make the print dialog appear behind the
682 // browser frame (but still being modal) so neither the browser frame nor
683 // the print dialog will get any input. See http://crbug.com/342697
684 // http://crbug.com/180997 for details.
685 base::MessageLoop::ScopedNestableTaskAllower
allow(
686 base::MessageLoop::current());
688 return PrintDlgEx(options
);
691 PrintingContext::Result
PrintingContextWin::ParseDialogResult(
692 const PRINTDLG
& dialog_options
) {
693 // If the user clicked OK or Apply then Cancel, but not only Cancel.
697 DEVMODE
* dev_mode
= NULL
;
698 if (dialog_options
.hDevMode
) {
700 reinterpret_cast<DEVMODE
*>(GlobalLock(dialog_options
.hDevMode
));
704 std::wstring device_name
;
705 if (dialog_options
.hDevNames
) {
706 DEVNAMES
* dev_names
=
707 reinterpret_cast<DEVNAMES
*>(GlobalLock(dialog_options
.hDevNames
));
711 reinterpret_cast<const wchar_t*>(
712 reinterpret_cast<const wchar_t*>(dev_names
) +
713 dev_names
->wDeviceOffset
);
714 GlobalUnlock(dialog_options
.hDevNames
);
718 bool success
= false;
719 if (dev_mode
&& !device_name
.empty()) {
720 context_
= dialog_options
.hDC
;
721 success
= InitializeSettings(*dev_mode
, device_name
, NULL
, 0, false);
724 if (!success
&& dialog_options
.hDC
) {
725 DeleteDC(dialog_options
.hDC
);
730 GlobalUnlock(dialog_options
.hDevMode
);
733 if (dialog_options
.hDevMode
!= NULL
)
734 GlobalFree(dialog_options
.hDevMode
);
735 if (dialog_options
.hDevNames
!= NULL
)
736 GlobalFree(dialog_options
.hDevNames
);
738 return context_
? OK
: FAILED
;
741 } // namespace printing