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 "printing/backend/print_backend.h"
19 #include "printing/backend/printing_info_win.h"
20 #include "printing/backend/win_helper.h"
21 #include "printing/print_job_constants.h"
22 #include "printing/print_settings_initializer_win.h"
23 #include "printing/printed_document.h"
24 #include "printing/printing_utils.h"
25 #include "printing/units.h"
26 #include "skia/ext/platform_device.h"
29 #include "ui/aura/remote_window_tree_host_win.h"
30 #include "ui/aura/window.h"
31 #include "ui/aura/window_event_dispatcher.h"
38 HWND
GetRootWindow(gfx::NativeView view
) {
42 window
= view
->GetHost()->GetAcceleratedWidget();
44 if (view
&& IsWindow(view
)) {
45 window
= GetAncestor(view
, GA_ROOTOWNER
);
49 // TODO(maruel): bug 1214347 Get the right browser window instead.
50 return GetDesktopWindow();
55 } // anonymous namespace
59 class PrintingContextWin::CallbackHandler
: public IPrintDialogCallback
,
60 public IObjectWithSite
{
62 CallbackHandler(PrintingContextWin
& owner
, HWND owner_hwnd
)
64 owner_hwnd_(owner_hwnd
),
73 IUnknown
* ToIUnknown() {
74 return static_cast<IUnknown
*>(static_cast<IPrintDialogCallback
*>(this));
78 virtual HRESULT WINAPI
QueryInterface(REFIID riid
, void**object
) {
79 if (riid
== IID_IUnknown
) {
80 *object
= ToIUnknown();
81 } else if (riid
== IID_IPrintDialogCallback
) {
82 *object
= static_cast<IPrintDialogCallback
*>(this);
83 } else if (riid
== IID_IObjectWithSite
) {
84 *object
= static_cast<IObjectWithSite
*>(this);
91 // No real ref counting.
92 virtual ULONG WINAPI
AddRef() {
95 virtual ULONG WINAPI
Release() {
99 // IPrintDialogCallback methods
100 virtual HRESULT WINAPI
InitDone() {
104 virtual HRESULT WINAPI
SelectionChange() {
106 // TODO(maruel): Get the devmode for the new printer with
107 // services_->GetCurrentDevMode(&devmode, &size), send that information
108 // back to our client and continue. The client needs to recalculate the
109 // number of rendered pages and send back this information here.
114 virtual HRESULT WINAPI
HandleMessage(HWND dialog
,
119 // Cheap way to retrieve the window handle.
120 if (!owner_
.dialog_box_
) {
121 // The handle we receive is the one of the groupbox in the General tab. We
122 // need to get the grand-father to get the dialog box handle.
123 owner_
.dialog_box_
= GetAncestor(dialog
, GA_ROOT
);
124 // Trick to enable the owner window. This can cause issues with navigation
125 // events so it may have to be disabled if we don't fix the side-effects.
126 EnableWindow(owner_hwnd_
, TRUE
);
131 virtual HRESULT WINAPI
SetSite(IUnknown
* site
) {
134 services_
->Release();
136 // The dialog box is destroying, PrintJob::Worker don't need the handle
138 owner_
.dialog_box_
= NULL
;
140 DCHECK(services_
== NULL
);
141 HRESULT hr
= site
->QueryInterface(IID_IPrintDialogServices
,
142 reinterpret_cast<void**>(&services_
));
143 DCHECK(SUCCEEDED(hr
));
148 virtual HRESULT WINAPI
GetSite(REFIID riid
, void** site
) {
153 PrintingContextWin
& owner_
;
155 IPrintDialogServices
* services_
;
157 DISALLOW_COPY_AND_ASSIGN(CallbackHandler
);
161 PrintingContext
* PrintingContext::Create(const std::string
& app_locale
) {
162 return static_cast<PrintingContext
*>(new PrintingContextWin(app_locale
));
165 PrintingContextWin::PrintingContextWin(const std::string
& app_locale
)
166 : PrintingContext(app_locale
), context_(NULL
), dialog_box_(NULL
) {}
168 PrintingContextWin::~PrintingContextWin() {
172 void PrintingContextWin::AskUserForSettings(
173 gfx::NativeView view
, int max_pages
, bool has_selection
,
174 const PrintSettingsCallback
& callback
) {
175 DCHECK(!in_print_job_
);
176 dialog_box_dismissed_
= false;
178 HWND window
= GetRootWindow(view
);
181 // Show the OS-dependent dialog box.
183 // - OK, the settings are reset and reinitialized with the new settings. OK is
185 // - Apply then Cancel, the settings are reset and reinitialized with the new
186 // settings. CANCEL is returned.
187 // - Cancel, the settings are not changed, the previous setting, if it was
188 // initialized before, are kept. CANCEL is returned.
189 // On failure, the settings are reset and FAILED is returned.
190 PRINTDLGEX dialog_options
= { sizeof(PRINTDLGEX
) };
191 dialog_options
.hwndOwner
= window
;
192 // Disable options we don't support currently.
193 // TODO(maruel): Reuse the previously loaded settings!
194 dialog_options
.Flags
= PD_RETURNDC
| PD_USEDEVMODECOPIESANDCOLLATE
|
195 PD_NOCURRENTPAGE
| PD_HIDEPRINTTOFILE
;
197 dialog_options
.Flags
|= PD_NOSELECTION
;
199 PRINTPAGERANGE ranges
[32];
200 dialog_options
.nStartPage
= START_PAGE_GENERAL
;
202 // Default initialize to print all the pages.
203 memset(ranges
, 0, sizeof(ranges
));
204 ranges
[0].nFromPage
= 1;
205 ranges
[0].nToPage
= max_pages
;
206 dialog_options
.nPageRanges
= 1;
207 dialog_options
.nMaxPageRanges
= arraysize(ranges
);
208 dialog_options
.nMinPage
= 1;
209 dialog_options
.nMaxPage
= max_pages
;
210 dialog_options
.lpPageRanges
= ranges
;
212 // No need to bother, we don't know how many pages are available.
213 dialog_options
.Flags
|= PD_NOPAGENUMS
;
216 if (ShowPrintDialog(&dialog_options
) != S_OK
) {
218 callback
.Run(FAILED
);
221 // TODO(maruel): Support PD_PRINTTOFILE.
222 callback
.Run(ParseDialogResultEx(dialog_options
));
225 PrintingContext::Result
PrintingContextWin::UseDefaultSettings() {
226 DCHECK(!in_print_job_
);
228 PRINTDLG dialog_options
= { sizeof(PRINTDLG
) };
229 dialog_options
.Flags
= PD_RETURNDC
| PD_RETURNDEFAULT
;
230 if (PrintDlg(&dialog_options
))
231 return ParseDialogResult(dialog_options
);
233 // No default printer configured, do we have any printers at all?
234 DWORD bytes_needed
= 0;
235 DWORD count_returned
= 0;
236 (void)::EnumPrinters(PRINTER_ENUM_LOCAL
|PRINTER_ENUM_CONNECTIONS
,
237 NULL
, 2, NULL
, 0, &bytes_needed
, &count_returned
);
239 DCHECK_GE(bytes_needed
, count_returned
* sizeof(PRINTER_INFO_2
));
240 scoped_ptr
<BYTE
[]> printer_info_buffer(new BYTE
[bytes_needed
]);
241 BOOL ret
= ::EnumPrinters(PRINTER_ENUM_LOCAL
|PRINTER_ENUM_CONNECTIONS
,
242 NULL
, 2, printer_info_buffer
.get(),
243 bytes_needed
, &bytes_needed
,
245 if (ret
&& count_returned
) { // have printers
246 // Open the first successfully found printer.
247 const PRINTER_INFO_2
* info_2
=
248 reinterpret_cast<PRINTER_INFO_2
*>(printer_info_buffer
.get());
249 const PRINTER_INFO_2
* info_2_end
= info_2
+ count_returned
;
250 for (; info_2
< info_2_end
; ++info_2
) {
251 ScopedPrinterHandle printer
;
252 if (!printer
.OpenPrinter(info_2
->pPrinterName
))
254 scoped_ptr
<DEVMODE
, base::FreeDeleter
> dev_mode
=
255 CreateDevMode(printer
, NULL
);
256 if (!dev_mode
|| !AllocateContext(info_2
->pPrinterName
, dev_mode
.get(),
260 if (InitializeSettings(*dev_mode
.get(), info_2
->pPrinterName
, NULL
, 0,
275 gfx::Size
PrintingContextWin::GetPdfPaperSizeDeviceUnits() {
276 // Default fallback to Letter size.
277 gfx::SizeF
paper_size(kLetterWidthInch
, kLetterHeightInch
);
279 // Get settings from locale. Paper type buffer length is at most 4.
280 const int paper_type_buffer_len
= 4;
281 wchar_t paper_type_buffer
[paper_type_buffer_len
] = {0};
282 GetLocaleInfo(LOCALE_USER_DEFAULT
, LOCALE_IPAPERSIZE
, paper_type_buffer
,
283 paper_type_buffer_len
);
284 if (wcslen(paper_type_buffer
)) { // The call succeeded.
285 int paper_code
= _wtoi(paper_type_buffer
);
286 switch (paper_code
) {
288 paper_size
.SetSize(kLegalWidthInch
, kLegalHeightInch
);
291 paper_size
.SetSize(kA4WidthInch
, kA4HeightInch
);
294 paper_size
.SetSize(kA3WidthInch
, kA3HeightInch
);
296 default: // DMPAPER_LETTER is used for default fallback.
301 paper_size
.width() * settings_
.device_units_per_inch(),
302 paper_size
.height() * settings_
.device_units_per_inch());
305 PrintingContext::Result
PrintingContextWin::UpdatePrinterSettings(
306 bool external_preview
) {
307 DCHECK(!in_print_job_
);
308 DCHECK(!external_preview
) << "Not implemented";
310 ScopedPrinterHandle printer
;
311 if (!printer
.OpenPrinter(settings_
.device_name().c_str()))
314 // Make printer changes local to Chrome.
315 // See MSDN documentation regarding DocumentProperties.
316 scoped_ptr
<DEVMODE
, base::FreeDeleter
> scoped_dev_mode
=
317 CreateDevModeWithColor(printer
, settings_
.device_name(),
318 settings_
.color() != GRAY
);
319 if (!scoped_dev_mode
)
323 DEVMODE
* dev_mode
= scoped_dev_mode
.get();
324 dev_mode
->dmCopies
= std::max(settings_
.copies(), 1);
325 if (dev_mode
->dmCopies
> 1) { // do not change unless multiple copies
326 dev_mode
->dmFields
|= DM_COPIES
;
327 dev_mode
->dmCollate
= settings_
.collate() ? DMCOLLATE_TRUE
:
331 switch (settings_
.duplex_mode()) {
333 dev_mode
->dmFields
|= DM_DUPLEX
;
334 dev_mode
->dmDuplex
= DMDUP_VERTICAL
;
337 dev_mode
->dmFields
|= DM_DUPLEX
;
338 dev_mode
->dmDuplex
= DMDUP_HORIZONTAL
;
341 dev_mode
->dmFields
|= DM_DUPLEX
;
342 dev_mode
->dmDuplex
= DMDUP_SIMPLEX
;
344 default: // UNKNOWN_DUPLEX_MODE
348 dev_mode
->dmFields
|= DM_ORIENTATION
;
349 dev_mode
->dmOrientation
= settings_
.landscape() ? DMORIENT_LANDSCAPE
:
353 // Update data using DocumentProperties.
354 scoped_dev_mode
= CreateDevMode(printer
, scoped_dev_mode
.get());
355 if (!scoped_dev_mode
)
358 // Set printer then refresh printer settings.
359 if (!AllocateContext(settings_
.device_name(), scoped_dev_mode
.get(),
363 PrintSettingsInitializerWin::InitPrintSettings(context_
,
364 *scoped_dev_mode
.get(),
369 PrintingContext::Result
PrintingContextWin::InitWithSettings(
370 const PrintSettings
& settings
) {
371 DCHECK(!in_print_job_
);
373 settings_
= settings
;
375 // TODO(maruel): settings_.ToDEVMODE()
376 ScopedPrinterHandle printer
;
377 if (!printer
.OpenPrinter(settings_
.device_name().c_str())) {
383 if (!GetPrinterSettings(printer
, settings_
.device_name()))
391 PrintingContext::Result
PrintingContextWin::NewDocument(
392 const base::string16
& document_name
) {
393 DCHECK(!in_print_job_
);
397 // Set the flag used by the AbortPrintJob dialog procedure.
398 abort_printing_
= false;
400 in_print_job_
= true;
402 // Register the application's AbortProc function with GDI.
403 if (SP_ERROR
== SetAbortProc(context_
, &AbortProc
))
406 DCHECK(SimplifyDocumentTitle(document_name
) == document_name
);
407 DOCINFO di
= { sizeof(DOCINFO
) };
408 const std::wstring
& document_name_wide
= base::UTF16ToWide(document_name
);
409 di
.lpszDocName
= document_name_wide
.c_str();
411 // Is there a debug dump directory specified? If so, force to print to a file.
412 base::FilePath debug_dump_path
= PrintedDocument::debug_dump_path();
413 if (!debug_dump_path
.empty()) {
414 // Create a filename.
415 std::wstring filename
;
416 Time
now(Time::Now());
417 filename
= base::TimeFormatShortDateNumeric(now
);
419 filename
+= base::TimeFormatTimeOfDay(now
);
421 filename
+= base::UTF16ToWide(document_name
);
423 filename
+= L
"buffer.prn";
424 file_util::ReplaceIllegalCharactersInPath(&filename
, '_');
425 debug_dump_path
= debug_dump_path
.Append(filename
);
426 di
.lpszOutput
= debug_dump_path
.value().c_str();
429 // No message loop running in unit tests.
430 DCHECK(!base::MessageLoop::current() ||
431 !base::MessageLoop::current()->NestableTasksAllowed());
433 // Begin a print job by calling the StartDoc function.
434 // NOTE: StartDoc() starts a message loop. That causes a lot of problems with
435 // IPC. Make sure recursive task processing is disabled.
436 if (StartDoc(context_
, &di
) <= 0)
442 PrintingContext::Result
PrintingContextWin::NewPage() {
446 DCHECK(in_print_job_
);
448 // Intentional No-op. NativeMetafile::SafePlayback takes care of calling
454 PrintingContext::Result
PrintingContextWin::PageDone() {
457 DCHECK(in_print_job_
);
459 // Intentional No-op. NativeMetafile::SafePlayback takes care of calling
465 PrintingContext::Result
PrintingContextWin::DocumentDone() {
468 DCHECK(in_print_job_
);
471 // Inform the driver that document has ended.
472 if (EndDoc(context_
) <= 0)
479 void PrintingContextWin::Cancel() {
480 abort_printing_
= true;
481 in_print_job_
= false;
485 DestroyWindow(dialog_box_
);
486 dialog_box_dismissed_
= true;
490 void PrintingContextWin::ReleaseContext() {
497 gfx::NativeDrawingContext
PrintingContextWin::context() const {
502 BOOL
PrintingContextWin::AbortProc(HDC hdc
, int nCode
) {
504 // TODO(maruel): Need a way to find the right instance to set. Should
505 // leverage PrintJobManager here?
506 // abort_printing_ = true;
511 bool PrintingContextWin::InitializeSettings(const DEVMODE
& dev_mode
,
512 const std::wstring
& new_device_name
,
513 const PRINTPAGERANGE
* ranges
,
515 bool selection_only
) {
516 skia::InitializeDC(context_
);
517 DCHECK(GetDeviceCaps(context_
, CLIPCAPS
));
518 DCHECK(GetDeviceCaps(context_
, RASTERCAPS
) & RC_STRETCHDIB
);
519 DCHECK(GetDeviceCaps(context_
, RASTERCAPS
) & RC_BITMAP64
);
520 // Some printers don't advertise these.
521 // DCHECK(GetDeviceCaps(context_, RASTERCAPS) & RC_SCALING);
522 // DCHECK(GetDeviceCaps(context_, SHADEBLENDCAPS) & SB_CONST_ALPHA);
523 // DCHECK(GetDeviceCaps(context_, SHADEBLENDCAPS) & SB_PIXEL_ALPHA);
525 // StretchDIBits() support is needed for printing.
526 if (!(GetDeviceCaps(context_
, RASTERCAPS
) & RC_STRETCHDIB
) ||
527 !(GetDeviceCaps(context_
, RASTERCAPS
) & RC_BITMAP64
)) {
533 DCHECK(!in_print_job_
);
535 PageRanges ranges_vector
;
536 if (!selection_only
) {
537 // Convert the PRINTPAGERANGE array to a PrintSettings::PageRanges vector.
538 ranges_vector
.reserve(number_ranges
);
539 for (int i
= 0; i
< number_ranges
; ++i
) {
541 // Transfer from 1-based to 0-based.
542 range
.from
= ranges
[i
].nFromPage
- 1;
543 range
.to
= ranges
[i
].nToPage
- 1;
544 ranges_vector
.push_back(range
);
548 settings_
.set_ranges(ranges_vector
);
549 settings_
.set_device_name(new_device_name
);
550 settings_
.set_selection_only(selection_only
);
551 PrintSettingsInitializerWin::InitPrintSettings(context_
, dev_mode
,
557 bool PrintingContextWin::GetPrinterSettings(HANDLE printer
,
558 const std::wstring
& device_name
) {
559 DCHECK(!in_print_job_
);
561 scoped_ptr
<DEVMODE
, base::FreeDeleter
> dev_mode
=
562 CreateDevMode(printer
, NULL
);
564 if (!dev_mode
|| !AllocateContext(device_name
, dev_mode
.get(), &context_
)) {
569 return InitializeSettings(*dev_mode
.get(), device_name
, NULL
, 0, false);
573 bool PrintingContextWin::AllocateContext(const std::wstring
& device_name
,
574 const DEVMODE
* dev_mode
,
575 gfx::NativeDrawingContext
* context
) {
576 *context
= CreateDC(L
"WINSPOOL", device_name
.c_str(), NULL
, dev_mode
);
578 return *context
!= NULL
;
581 PrintingContext::Result
PrintingContextWin::ParseDialogResultEx(
582 const PRINTDLGEX
& dialog_options
) {
583 // If the user clicked OK or Apply then Cancel, but not only Cancel.
584 if (dialog_options
.dwResultAction
!= PD_RESULT_CANCEL
) {
588 DEVMODE
* dev_mode
= NULL
;
589 if (dialog_options
.hDevMode
) {
591 reinterpret_cast<DEVMODE
*>(GlobalLock(dialog_options
.hDevMode
));
595 std::wstring device_name
;
596 if (dialog_options
.hDevNames
) {
597 DEVNAMES
* dev_names
=
598 reinterpret_cast<DEVNAMES
*>(GlobalLock(dialog_options
.hDevNames
));
601 device_name
= reinterpret_cast<const wchar_t*>(dev_names
) +
602 dev_names
->wDeviceOffset
;
603 GlobalUnlock(dialog_options
.hDevNames
);
607 bool success
= false;
608 if (dev_mode
&& !device_name
.empty()) {
609 context_
= dialog_options
.hDC
;
610 PRINTPAGERANGE
* page_ranges
= NULL
;
611 DWORD num_page_ranges
= 0;
612 bool print_selection_only
= false;
613 if (dialog_options
.Flags
& PD_PAGENUMS
) {
614 page_ranges
= dialog_options
.lpPageRanges
;
615 num_page_ranges
= dialog_options
.nPageRanges
;
617 if (dialog_options
.Flags
& PD_SELECTION
) {
618 print_selection_only
= true;
620 success
= InitializeSettings(*dev_mode
,
624 print_selection_only
);
627 if (!success
&& dialog_options
.hDC
) {
628 DeleteDC(dialog_options
.hDC
);
633 GlobalUnlock(dialog_options
.hDevMode
);
636 if (dialog_options
.hDC
) {
637 DeleteDC(dialog_options
.hDC
);
641 if (dialog_options
.hDevMode
!= NULL
)
642 GlobalFree(dialog_options
.hDevMode
);
643 if (dialog_options
.hDevNames
!= NULL
)
644 GlobalFree(dialog_options
.hDevNames
);
646 switch (dialog_options
.dwResultAction
) {
647 case PD_RESULT_PRINT
:
648 return context_
? OK
: FAILED
;
649 case PD_RESULT_APPLY
:
650 return context_
? CANCEL
: FAILED
;
651 case PD_RESULT_CANCEL
:
658 HRESULT
PrintingContextWin::ShowPrintDialog(PRINTDLGEX
* options
) {
659 // Note that this cannot use ui::BaseShellDialog as the print dialog is
660 // system modal: opening it from a background thread can cause Windows to
661 // get the wrong Z-order which will make the print dialog appear behind the
662 // browser frame (but still being modal) so neither the browser frame nor
663 // the print dialog will get any input. See http://crbug.com/342697
664 // http://crbug.com/180997 for details.
665 base::MessageLoop::ScopedNestableTaskAllower
allow(
666 base::MessageLoop::current());
668 return PrintDlgEx(options
);
671 PrintingContext::Result
PrintingContextWin::ParseDialogResult(
672 const PRINTDLG
& dialog_options
) {
673 // If the user clicked OK or Apply then Cancel, but not only Cancel.
677 DEVMODE
* dev_mode
= NULL
;
678 if (dialog_options
.hDevMode
) {
680 reinterpret_cast<DEVMODE
*>(GlobalLock(dialog_options
.hDevMode
));
684 std::wstring device_name
;
685 if (dialog_options
.hDevNames
) {
686 DEVNAMES
* dev_names
=
687 reinterpret_cast<DEVNAMES
*>(GlobalLock(dialog_options
.hDevNames
));
691 reinterpret_cast<const wchar_t*>(
692 reinterpret_cast<const wchar_t*>(dev_names
) +
693 dev_names
->wDeviceOffset
);
694 GlobalUnlock(dialog_options
.hDevNames
);
698 bool success
= false;
699 if (dev_mode
&& !device_name
.empty()) {
700 context_
= dialog_options
.hDC
;
701 success
= InitializeSettings(*dev_mode
, device_name
, NULL
, 0, false);
704 if (!success
&& dialog_options
.hDC
) {
705 DeleteDC(dialog_options
.hDC
);
710 GlobalUnlock(dialog_options
.hDevMode
);
713 if (dialog_options
.hDevMode
!= NULL
)
714 GlobalFree(dialog_options
.hDevMode
);
715 if (dialog_options
.hDevNames
!= NULL
)
716 GlobalFree(dialog_options
.hDevNames
);
718 return context_
? OK
: FAILED
;
721 } // namespace printing