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/units.h"
26 #include "skia/ext/platform_device.h"
27 #include "win8/util/win8_util.h"
30 #include "ui/aura/remote_root_window_host_win.h"
31 #include "ui/aura/root_window.h"
32 #include "ui/aura/window.h"
39 HWND
GetRootWindow(gfx::NativeView view
) {
43 window
= view
->GetDispatcher()->GetAcceleratedWidget();
45 if (view
&& IsWindow(view
)) {
46 window
= GetAncestor(view
, GA_ROOTOWNER
);
50 // TODO(maruel): bug 1214347 Get the right browser window instead.
51 return GetDesktopWindow();
56 } // anonymous namespace
60 class PrintingContextWin::CallbackHandler
: public IPrintDialogCallback
,
61 public IObjectWithSite
{
63 CallbackHandler(PrintingContextWin
& owner
, HWND owner_hwnd
)
65 owner_hwnd_(owner_hwnd
),
74 IUnknown
* ToIUnknown() {
75 return static_cast<IUnknown
*>(static_cast<IPrintDialogCallback
*>(this));
79 virtual HRESULT WINAPI
QueryInterface(REFIID riid
, void**object
) {
80 if (riid
== IID_IUnknown
) {
81 *object
= ToIUnknown();
82 } else if (riid
== IID_IPrintDialogCallback
) {
83 *object
= static_cast<IPrintDialogCallback
*>(this);
84 } else if (riid
== IID_IObjectWithSite
) {
85 *object
= static_cast<IObjectWithSite
*>(this);
92 // No real ref counting.
93 virtual ULONG WINAPI
AddRef() {
96 virtual ULONG WINAPI
Release() {
100 // IPrintDialogCallback methods
101 virtual HRESULT WINAPI
InitDone() {
105 virtual HRESULT WINAPI
SelectionChange() {
107 // TODO(maruel): Get the devmode for the new printer with
108 // services_->GetCurrentDevMode(&devmode, &size), send that information
109 // back to our client and continue. The client needs to recalculate the
110 // number of rendered pages and send back this information here.
115 virtual HRESULT WINAPI
HandleMessage(HWND dialog
,
120 // Cheap way to retrieve the window handle.
121 if (!owner_
.dialog_box_
) {
122 // The handle we receive is the one of the groupbox in the General tab. We
123 // need to get the grand-father to get the dialog box handle.
124 owner_
.dialog_box_
= GetAncestor(dialog
, GA_ROOT
);
125 // Trick to enable the owner window. This can cause issues with navigation
126 // events so it may have to be disabled if we don't fix the side-effects.
127 EnableWindow(owner_hwnd_
, TRUE
);
132 virtual HRESULT WINAPI
SetSite(IUnknown
* site
) {
135 services_
->Release();
137 // The dialog box is destroying, PrintJob::Worker don't need the handle
139 owner_
.dialog_box_
= NULL
;
141 DCHECK(services_
== NULL
);
142 HRESULT hr
= site
->QueryInterface(IID_IPrintDialogServices
,
143 reinterpret_cast<void**>(&services_
));
144 DCHECK(SUCCEEDED(hr
));
149 virtual HRESULT WINAPI
GetSite(REFIID riid
, void** site
) {
154 PrintingContextWin
& owner_
;
156 IPrintDialogServices
* services_
;
158 DISALLOW_COPY_AND_ASSIGN(CallbackHandler
);
162 PrintingContext
* PrintingContext::Create(const std::string
& app_locale
) {
163 return static_cast<PrintingContext
*>(new PrintingContextWin(app_locale
));
166 PrintingContextWin::PrintingContextWin(const std::string
& app_locale
)
167 : PrintingContext(app_locale
),
170 print_dialog_func_(&PrintDlgEx
) {
173 PrintingContextWin::~PrintingContextWin() {
177 void PrintingContextWin::AskUserForSettings(
178 gfx::NativeView view
, int max_pages
, bool has_selection
,
179 const PrintSettingsCallback
& callback
) {
180 DCHECK(!in_print_job_
);
181 // TODO(scottmg): Possibly this has to move into the threaded runner too?
182 if (win8::IsSingleWindowMetroMode()) {
183 // The system dialog can not be opened while running in Metro.
184 // But we can programatically launch the Metro print device charm though.
185 HMODULE metro_module
= base::win::GetMetroModule();
186 if (metro_module
!= NULL
) {
187 typedef void (*MetroShowPrintUI
)();
188 MetroShowPrintUI metro_show_print_ui
=
189 reinterpret_cast<MetroShowPrintUI
>(
190 ::GetProcAddress(metro_module
, "MetroShowPrintUI"));
191 if (metro_show_print_ui
) {
192 // TODO(mad): Remove this once we can send user metrics from the metro
193 // driver. crbug.com/142330
194 UMA_HISTOGRAM_ENUMERATION("Metro.Print", 1, 2);
195 metro_show_print_ui();
198 return callback
.Run(CANCEL
);
200 dialog_box_dismissed_
= false;
202 HWND window
= GetRootWindow(view
);
205 // Show the OS-dependent dialog box.
207 // - OK, the settings are reset and reinitialized with the new settings. OK is
209 // - Apply then Cancel, the settings are reset and reinitialized with the new
210 // settings. CANCEL is returned.
211 // - Cancel, the settings are not changed, the previous setting, if it was
212 // initialized before, are kept. CANCEL is returned.
213 // On failure, the settings are reset and FAILED is returned.
214 PRINTDLGEX
* dialog_options
=
215 reinterpret_cast<PRINTDLGEX
*>(malloc(sizeof(PRINTDLGEX
)));
216 ZeroMemory(dialog_options
, sizeof(PRINTDLGEX
));
217 dialog_options
->lStructSize
= sizeof(PRINTDLGEX
);
218 dialog_options
->hwndOwner
= window
;
219 // Disable options we don't support currently.
220 // TODO(maruel): Reuse the previously loaded settings!
221 dialog_options
->Flags
= PD_RETURNDC
| PD_USEDEVMODECOPIESANDCOLLATE
|
222 PD_NOCURRENTPAGE
| PD_HIDEPRINTTOFILE
;
224 dialog_options
->Flags
|= PD_NOSELECTION
;
226 const size_t max_page_ranges
= 32;
227 PRINTPAGERANGE
* ranges
= new PRINTPAGERANGE
[max_page_ranges
];
228 dialog_options
->lpPageRanges
= ranges
;
229 dialog_options
->nStartPage
= START_PAGE_GENERAL
;
231 // Default initialize to print all the pages.
232 memset(ranges
, 0, sizeof(ranges
));
233 ranges
[0].nFromPage
= 1;
234 ranges
[0].nToPage
= max_pages
;
235 dialog_options
->nPageRanges
= 1;
236 dialog_options
->nMaxPageRanges
= max_page_ranges
;
237 dialog_options
->nMinPage
= 1;
238 dialog_options
->nMaxPage
= max_pages
;
240 // No need to bother, we don't know how many pages are available.
241 dialog_options
->Flags
|= PD_NOPAGENUMS
;
244 callback_
= callback
;
245 print_settings_dialog_
= new ui::PrintSettingsDialogWin(this);
246 print_settings_dialog_
->GetPrintSettings(
247 print_dialog_func_
, window
, dialog_options
);
250 PrintingContext::Result
PrintingContextWin::UseDefaultSettings() {
251 DCHECK(!in_print_job_
);
253 PRINTDLG dialog_options
= { sizeof(PRINTDLG
) };
254 dialog_options
.Flags
= PD_RETURNDC
| PD_RETURNDEFAULT
;
255 if (PrintDlg(&dialog_options
))
256 return ParseDialogResult(dialog_options
);
258 // No default printer configured, do we have any printers at all?
259 DWORD bytes_needed
= 0;
260 DWORD count_returned
= 0;
261 (void)::EnumPrinters(PRINTER_ENUM_LOCAL
|PRINTER_ENUM_CONNECTIONS
,
262 NULL
, 2, NULL
, 0, &bytes_needed
, &count_returned
);
264 DCHECK(bytes_needed
>= count_returned
* sizeof(PRINTER_INFO_2
));
265 scoped_ptr
<BYTE
[]> printer_info_buffer(new BYTE
[bytes_needed
]);
266 BOOL ret
= ::EnumPrinters(PRINTER_ENUM_LOCAL
|PRINTER_ENUM_CONNECTIONS
,
267 NULL
, 2, printer_info_buffer
.get(),
268 bytes_needed
, &bytes_needed
,
270 if (ret
&& count_returned
) { // have printers
271 // Open the first successfully found printer.
272 for (DWORD count
= 0; count
< count_returned
; ++count
) {
273 PRINTER_INFO_2
* info_2
= reinterpret_cast<PRINTER_INFO_2
*>(
274 printer_info_buffer
.get() + count
* sizeof(PRINTER_INFO_2
));
275 std::wstring printer_name
= info_2
->pPrinterName
;
276 if (info_2
->pDevMode
== NULL
|| printer_name
.length() == 0)
278 if (!AllocateContext(printer_name
, info_2
->pDevMode
, &context_
))
280 if (InitializeSettings(*info_2
->pDevMode
, printer_name
,
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 LPWSTR device_name_wide
=
332 const_cast<wchar_t*>(settings_
.device_name().c_str());
333 if (!printer
.OpenPrinter(device_name_wide
))
336 // Make printer changes local to Chrome.
337 // See MSDN documentation regarding DocumentProperties.
338 scoped_ptr
<uint8
[]> buffer
;
339 DEVMODE
* dev_mode
= NULL
;
340 LONG buffer_size
= DocumentProperties(NULL
, printer
, device_name_wide
,
342 if (buffer_size
> 0) {
343 buffer
.reset(new uint8
[buffer_size
]);
344 memset(buffer
.get(), 0, buffer_size
);
345 if (DocumentProperties(NULL
, printer
, device_name_wide
,
346 reinterpret_cast<PDEVMODE
>(buffer
.get()), NULL
,
347 DM_OUT_BUFFER
) == IDOK
) {
348 dev_mode
= reinterpret_cast<PDEVMODE
>(buffer
.get());
351 if (dev_mode
== NULL
) {
356 if (settings_
.color() == GRAY
)
357 dev_mode
->dmColor
= DMCOLOR_MONOCHROME
;
359 dev_mode
->dmColor
= DMCOLOR_COLOR
;
361 dev_mode
->dmCopies
= std::max(settings_
.copies(), 1);
362 if (dev_mode
->dmCopies
> 1) { // do not change collate unless multiple copies
363 dev_mode
->dmCollate
= settings_
.collate() ? DMCOLLATE_TRUE
:
366 switch (settings_
.duplex_mode()) {
368 dev_mode
->dmDuplex
= DMDUP_VERTICAL
;
371 dev_mode
->dmDuplex
= DMDUP_HORIZONTAL
;
374 dev_mode
->dmDuplex
= DMDUP_SIMPLEX
;
376 default: // UNKNOWN_DUPLEX_MODE
379 dev_mode
->dmOrientation
= settings_
.landscape() ? DMORIENT_LANDSCAPE
:
382 // Update data using DocumentProperties.
383 if (DocumentProperties(NULL
, printer
, device_name_wide
, dev_mode
, dev_mode
,
384 DM_IN_BUFFER
| DM_OUT_BUFFER
) != IDOK
) {
388 // Set printer then refresh printer settings.
389 if (!AllocateContext(settings_
.device_name(), dev_mode
, &context_
)) {
392 PrintSettingsInitializerWin::InitPrintSettings(context_
, *dev_mode
,
397 PrintingContext::Result
PrintingContextWin::InitWithSettings(
398 const PrintSettings
& settings
) {
399 DCHECK(!in_print_job_
);
401 settings_
= settings
;
403 // TODO(maruel): settings_.ToDEVMODE()
404 ScopedPrinterHandle printer
;
405 if (!printer
.OpenPrinter(settings_
.device_name().c_str())) {
411 if (!GetPrinterSettings(printer
, settings_
.device_name()))
419 PrintingContext::Result
PrintingContextWin::NewDocument(
420 const base::string16
& document_name
) {
421 DCHECK(!in_print_job_
);
425 // Set the flag used by the AbortPrintJob dialog procedure.
426 abort_printing_
= false;
428 in_print_job_
= true;
430 // Register the application's AbortProc function with GDI.
431 if (SP_ERROR
== SetAbortProc(context_
, &AbortProc
))
434 DCHECK(PrintBackend::SimplifyDocumentTitle(document_name
) == document_name
);
435 DOCINFO di
= { sizeof(DOCINFO
) };
436 const std::wstring
& document_name_wide
= UTF16ToWide(document_name
);
437 di
.lpszDocName
= document_name_wide
.c_str();
439 // Is there a debug dump directory specified? If so, force to print to a file.
440 base::FilePath debug_dump_path
= PrintedDocument::debug_dump_path();
441 if (!debug_dump_path
.empty()) {
442 // Create a filename.
443 std::wstring filename
;
444 Time
now(Time::Now());
445 filename
= base::TimeFormatShortDateNumeric(now
);
447 filename
+= base::TimeFormatTimeOfDay(now
);
449 filename
+= UTF16ToWide(document_name
);
451 filename
+= L
"buffer.prn";
452 file_util::ReplaceIllegalCharactersInPath(&filename
, '_');
453 debug_dump_path
.Append(filename
);
454 di
.lpszOutput
= debug_dump_path
.value().c_str();
457 // No message loop running in unit tests.
458 DCHECK(!base::MessageLoop::current() ||
459 !base::MessageLoop::current()->NestableTasksAllowed());
461 // Begin a print job by calling the StartDoc function.
462 // NOTE: StartDoc() starts a message loop. That causes a lot of problems with
463 // IPC. Make sure recursive task processing is disabled.
464 if (StartDoc(context_
, &di
) <= 0)
470 PrintingContext::Result
PrintingContextWin::NewPage() {
474 DCHECK(in_print_job_
);
476 // Intentional No-op. NativeMetafile::SafePlayback takes care of calling
482 PrintingContext::Result
PrintingContextWin::PageDone() {
485 DCHECK(in_print_job_
);
487 // Intentional No-op. NativeMetafile::SafePlayback takes care of calling
493 PrintingContext::Result
PrintingContextWin::DocumentDone() {
496 DCHECK(in_print_job_
);
499 // Inform the driver that document has ended.
500 if (EndDoc(context_
) <= 0)
507 void PrintingContextWin::Cancel() {
508 abort_printing_
= true;
509 in_print_job_
= false;
513 DestroyWindow(dialog_box_
);
514 dialog_box_dismissed_
= true;
518 void PrintingContextWin::ReleaseContext() {
525 gfx::NativeDrawingContext
PrintingContextWin::context() const {
529 void PrintingContextWin::PrintSettingsConfirmed(PRINTDLGEX
* dialog_options
) {
530 // TODO(maruel): Support PD_PRINTTOFILE.
531 callback_
.Run(ParseDialogResultEx(*dialog_options
));
532 delete [] dialog_options
->lpPageRanges
;
533 free(dialog_options
);
536 void PrintingContextWin::PrintSettingsCancelled(PRINTDLGEX
* dialog_options
) {
538 callback_
.Run(FAILED
);
539 delete [] dialog_options
->lpPageRanges
;
540 free(dialog_options
);
544 BOOL
PrintingContextWin::AbortProc(HDC hdc
, int nCode
) {
546 // TODO(maruel): Need a way to find the right instance to set. Should
547 // leverage PrintJobManager here?
548 // abort_printing_ = true;
553 bool PrintingContextWin::InitializeSettings(const DEVMODE
& dev_mode
,
554 const std::wstring
& new_device_name
,
555 const PRINTPAGERANGE
* ranges
,
557 bool selection_only
) {
558 skia::InitializeDC(context_
);
559 DCHECK(GetDeviceCaps(context_
, CLIPCAPS
));
560 DCHECK(GetDeviceCaps(context_
, RASTERCAPS
) & RC_STRETCHDIB
);
561 DCHECK(GetDeviceCaps(context_
, RASTERCAPS
) & RC_BITMAP64
);
562 // Some printers don't advertise these.
563 // DCHECK(GetDeviceCaps(context_, RASTERCAPS) & RC_SCALING);
564 // DCHECK(GetDeviceCaps(context_, SHADEBLENDCAPS) & SB_CONST_ALPHA);
565 // DCHECK(GetDeviceCaps(context_, SHADEBLENDCAPS) & SB_PIXEL_ALPHA);
567 // StretchDIBits() support is needed for printing.
568 if (!(GetDeviceCaps(context_
, RASTERCAPS
) & RC_STRETCHDIB
) ||
569 !(GetDeviceCaps(context_
, RASTERCAPS
) & RC_BITMAP64
)) {
575 DCHECK(!in_print_job_
);
577 PageRanges ranges_vector
;
578 if (!selection_only
) {
579 // Convert the PRINTPAGERANGE array to a PrintSettings::PageRanges vector.
580 ranges_vector
.reserve(number_ranges
);
581 for (int i
= 0; i
< number_ranges
; ++i
) {
583 // Transfer from 1-based to 0-based.
584 range
.from
= ranges
[i
].nFromPage
- 1;
585 range
.to
= ranges
[i
].nToPage
- 1;
586 ranges_vector
.push_back(range
);
590 settings_
.set_ranges(ranges_vector
);
591 settings_
.set_device_name(new_device_name
);
592 settings_
.set_selection_only(selection_only
);
593 PrintSettingsInitializerWin::InitPrintSettings(context_
, dev_mode
,
599 bool PrintingContextWin::GetPrinterSettings(HANDLE printer
,
600 const std::wstring
& device_name
) {
601 DCHECK(!in_print_job_
);
603 UserDefaultDevMode user_settings
;
605 if (!user_settings
.Init(printer
) ||
606 !AllocateContext(device_name
, user_settings
.get(), &context_
)) {
611 return InitializeSettings(*user_settings
.get(), device_name
, NULL
, 0, false);
615 bool PrintingContextWin::AllocateContext(const std::wstring
& device_name
,
616 const DEVMODE
* dev_mode
,
617 gfx::NativeDrawingContext
* context
) {
618 *context
= CreateDC(L
"WINSPOOL", device_name
.c_str(), NULL
, dev_mode
);
620 return *context
!= NULL
;
623 PrintingContext::Result
PrintingContextWin::ParseDialogResultEx(
624 const PRINTDLGEX
& dialog_options
) {
625 // If the user clicked OK or Apply then Cancel, but not only Cancel.
626 if (dialog_options
.dwResultAction
!= PD_RESULT_CANCEL
) {
630 DEVMODE
* dev_mode
= NULL
;
631 if (dialog_options
.hDevMode
) {
633 reinterpret_cast<DEVMODE
*>(GlobalLock(dialog_options
.hDevMode
));
637 std::wstring device_name
;
638 if (dialog_options
.hDevNames
) {
639 DEVNAMES
* dev_names
=
640 reinterpret_cast<DEVNAMES
*>(GlobalLock(dialog_options
.hDevNames
));
643 device_name
= reinterpret_cast<const wchar_t*>(dev_names
) +
644 dev_names
->wDeviceOffset
;
645 GlobalUnlock(dialog_options
.hDevNames
);
649 bool success
= false;
650 if (dev_mode
&& !device_name
.empty()) {
651 context_
= dialog_options
.hDC
;
652 PRINTPAGERANGE
* page_ranges
= NULL
;
653 DWORD num_page_ranges
= 0;
654 bool print_selection_only
= false;
655 if (dialog_options
.Flags
& PD_PAGENUMS
) {
656 page_ranges
= dialog_options
.lpPageRanges
;
657 num_page_ranges
= dialog_options
.nPageRanges
;
659 if (dialog_options
.Flags
& PD_SELECTION
) {
660 print_selection_only
= true;
662 success
= InitializeSettings(*dev_mode
,
666 print_selection_only
);
669 if (!success
&& dialog_options
.hDC
) {
670 DeleteDC(dialog_options
.hDC
);
675 GlobalUnlock(dialog_options
.hDevMode
);
678 if (dialog_options
.hDC
) {
679 DeleteDC(dialog_options
.hDC
);
683 if (dialog_options
.hDevMode
!= NULL
)
684 GlobalFree(dialog_options
.hDevMode
);
685 if (dialog_options
.hDevNames
!= NULL
)
686 GlobalFree(dialog_options
.hDevNames
);
688 switch (dialog_options
.dwResultAction
) {
689 case PD_RESULT_PRINT
:
690 return context_
? OK
: FAILED
;
691 case PD_RESULT_APPLY
:
692 return context_
? CANCEL
: FAILED
;
693 case PD_RESULT_CANCEL
:
700 PrintingContext::Result
PrintingContextWin::ParseDialogResult(
701 const PRINTDLG
& dialog_options
) {
702 // If the user clicked OK or Apply then Cancel, but not only Cancel.
706 DEVMODE
* dev_mode
= NULL
;
707 if (dialog_options
.hDevMode
) {
709 reinterpret_cast<DEVMODE
*>(GlobalLock(dialog_options
.hDevMode
));
713 std::wstring device_name
;
714 if (dialog_options
.hDevNames
) {
715 DEVNAMES
* dev_names
=
716 reinterpret_cast<DEVNAMES
*>(GlobalLock(dialog_options
.hDevNames
));
720 reinterpret_cast<const wchar_t*>(
721 reinterpret_cast<const wchar_t*>(dev_names
) +
722 dev_names
->wDeviceOffset
);
723 GlobalUnlock(dialog_options
.hDevNames
);
727 bool success
= false;
728 if (dev_mode
&& !device_name
.empty()) {
729 context_
= dialog_options
.hDC
;
730 success
= InitializeSettings(*dev_mode
, device_name
, NULL
, 0, false);
733 if (!success
&& dialog_options
.hDC
) {
734 DeleteDC(dialog_options
.hDC
);
739 GlobalUnlock(dialog_options
.hDevMode
);
742 if (dialog_options
.hDevMode
!= NULL
)
743 GlobalFree(dialog_options
.hDevMode
);
744 if (dialog_options
.hDevNames
!= NULL
)
745 GlobalFree(dialog_options
.hDevNames
);
747 return context_
? OK
: FAILED
;
750 } // namespace printing