• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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.
4 
5 #include "printing/printing_context_win.h"
6 
7 #include <winspool.h>
8 
9 #include <algorithm>
10 
11 #include "base/message_loop/message_loop.h"
12 #include "base/metrics/histogram.h"
13 #include "base/strings/string_number_conversions.h"
14 #include "base/strings/utf_string_conversions.h"
15 #include "base/values.h"
16 #include "printing/backend/print_backend.h"
17 #include "printing/backend/printing_info_win.h"
18 #include "printing/backend/win_helper.h"
19 #include "printing/print_job_constants.h"
20 #include "printing/print_settings_initializer_win.h"
21 #include "printing/printed_document.h"
22 #include "printing/printing_utils.h"
23 #include "printing/units.h"
24 #include "skia/ext/platform_device.h"
25 
26 #if defined(USE_AURA)
27 #include "ui/aura/remote_window_tree_host_win.h"
28 #include "ui/aura/window.h"
29 #include "ui/aura/window_event_dispatcher.h"
30 #endif
31 
32 namespace {
33 
GetRootWindow(gfx::NativeView view)34 HWND GetRootWindow(gfx::NativeView view) {
35   HWND window = NULL;
36 #if defined(USE_AURA)
37   if (view)
38     window = view->GetHost()->GetAcceleratedWidget();
39 #else
40   if (view && IsWindow(view)) {
41     window = GetAncestor(view, GA_ROOTOWNER);
42   }
43 #endif
44   if (!window) {
45     // TODO(maruel):  bug 1214347 Get the right browser window instead.
46     return GetDesktopWindow();
47   }
48   return window;
49 }
50 
51 }  // anonymous namespace
52 
53 namespace printing {
54 
55 class PrintingContextWin::CallbackHandler : public IPrintDialogCallback,
56                                             public IObjectWithSite {
57  public:
CallbackHandler(PrintingContextWin & owner,HWND owner_hwnd)58   CallbackHandler(PrintingContextWin& owner, HWND owner_hwnd)
59       : owner_(owner),
60         owner_hwnd_(owner_hwnd),
61         services_(NULL) {
62   }
63 
~CallbackHandler()64   ~CallbackHandler() {
65     if (services_)
66       services_->Release();
67   }
68 
ToIUnknown()69   IUnknown* ToIUnknown() {
70     return static_cast<IUnknown*>(static_cast<IPrintDialogCallback*>(this));
71   }
72 
73   // IUnknown
QueryInterface(REFIID riid,void ** object)74   virtual HRESULT WINAPI QueryInterface(REFIID riid, void**object) {
75     if (riid == IID_IUnknown) {
76       *object = ToIUnknown();
77     } else if (riid == IID_IPrintDialogCallback) {
78       *object = static_cast<IPrintDialogCallback*>(this);
79     } else if (riid == IID_IObjectWithSite) {
80       *object = static_cast<IObjectWithSite*>(this);
81     } else {
82       return E_NOINTERFACE;
83     }
84     return S_OK;
85   }
86 
87   // No real ref counting.
AddRef()88   virtual ULONG WINAPI AddRef() {
89     return 1;
90   }
Release()91   virtual ULONG WINAPI Release() {
92     return 1;
93   }
94 
95   // IPrintDialogCallback methods
InitDone()96   virtual HRESULT WINAPI InitDone() {
97     return S_OK;
98   }
99 
SelectionChange()100   virtual HRESULT WINAPI SelectionChange() {
101     if (services_) {
102       // TODO(maruel): Get the devmode for the new printer with
103       // services_->GetCurrentDevMode(&devmode, &size), send that information
104       // back to our client and continue. The client needs to recalculate the
105       // number of rendered pages and send back this information here.
106     }
107     return S_OK;
108   }
109 
HandleMessage(HWND dialog,UINT message,WPARAM wparam,LPARAM lparam,LRESULT * result)110   virtual HRESULT WINAPI HandleMessage(HWND dialog,
111                                        UINT message,
112                                        WPARAM wparam,
113                                        LPARAM lparam,
114                                        LRESULT* result) {
115     // Cheap way to retrieve the window handle.
116     if (!owner_.dialog_box_) {
117       // The handle we receive is the one of the groupbox in the General tab. We
118       // need to get the grand-father to get the dialog box handle.
119       owner_.dialog_box_ = GetAncestor(dialog, GA_ROOT);
120       // Trick to enable the owner window. This can cause issues with navigation
121       // events so it may have to be disabled if we don't fix the side-effects.
122       EnableWindow(owner_hwnd_, TRUE);
123     }
124     return S_FALSE;
125   }
126 
SetSite(IUnknown * site)127   virtual HRESULT WINAPI SetSite(IUnknown* site) {
128     if (!site) {
129       DCHECK(services_);
130       services_->Release();
131       services_ = NULL;
132       // The dialog box is destroying, PrintJob::Worker don't need the handle
133       // anymore.
134       owner_.dialog_box_ = NULL;
135     } else {
136       DCHECK(services_ == NULL);
137       HRESULT hr = site->QueryInterface(IID_IPrintDialogServices,
138                                         reinterpret_cast<void**>(&services_));
139       DCHECK(SUCCEEDED(hr));
140     }
141     return S_OK;
142   }
143 
GetSite(REFIID riid,void ** site)144   virtual HRESULT WINAPI GetSite(REFIID riid, void** site) {
145     return E_NOTIMPL;
146   }
147 
148  private:
149   PrintingContextWin& owner_;
150   HWND owner_hwnd_;
151   IPrintDialogServices* services_;
152 
153   DISALLOW_COPY_AND_ASSIGN(CallbackHandler);
154 };
155 
156 // static
Create(const std::string & app_locale)157 PrintingContext* PrintingContext::Create(const std::string& app_locale) {
158   return static_cast<PrintingContext*>(new PrintingContextWin(app_locale));
159 }
160 
PrintingContextWin(const std::string & app_locale)161 PrintingContextWin::PrintingContextWin(const std::string& app_locale)
162     : PrintingContext(app_locale), context_(NULL), dialog_box_(NULL) {}
163 
~PrintingContextWin()164 PrintingContextWin::~PrintingContextWin() {
165   ReleaseContext();
166 }
167 
AskUserForSettings(gfx::NativeView view,int max_pages,bool has_selection,const PrintSettingsCallback & callback)168 void PrintingContextWin::AskUserForSettings(
169     gfx::NativeView view, int max_pages, bool has_selection,
170     const PrintSettingsCallback& callback) {
171   DCHECK(!in_print_job_);
172   dialog_box_dismissed_ = false;
173 
174   HWND window = GetRootWindow(view);
175   DCHECK(window);
176 
177   // Show the OS-dependent dialog box.
178   // If the user press
179   // - OK, the settings are reset and reinitialized with the new settings. OK is
180   //   returned.
181   // - Apply then Cancel, the settings are reset and reinitialized with the new
182   //   settings. CANCEL is returned.
183   // - Cancel, the settings are not changed, the previous setting, if it was
184   //   initialized before, are kept. CANCEL is returned.
185   // On failure, the settings are reset and FAILED is returned.
186   PRINTDLGEX dialog_options = { sizeof(PRINTDLGEX) };
187   dialog_options.hwndOwner = window;
188   // Disable options we don't support currently.
189   // TODO(maruel):  Reuse the previously loaded settings!
190   dialog_options.Flags = PD_RETURNDC | PD_USEDEVMODECOPIESANDCOLLATE  |
191                          PD_NOCURRENTPAGE | PD_HIDEPRINTTOFILE;
192   if (!has_selection)
193     dialog_options.Flags |= PD_NOSELECTION;
194 
195   PRINTPAGERANGE ranges[32];
196   dialog_options.nStartPage = START_PAGE_GENERAL;
197   if (max_pages) {
198     // Default initialize to print all the pages.
199     memset(ranges, 0, sizeof(ranges));
200     ranges[0].nFromPage = 1;
201     ranges[0].nToPage = max_pages;
202     dialog_options.nPageRanges = 1;
203     dialog_options.nMaxPageRanges = arraysize(ranges);
204     dialog_options.nMinPage = 1;
205     dialog_options.nMaxPage = max_pages;
206     dialog_options.lpPageRanges = ranges;
207   } else {
208     // No need to bother, we don't know how many pages are available.
209     dialog_options.Flags |= PD_NOPAGENUMS;
210   }
211 
212   if (ShowPrintDialog(&dialog_options) != S_OK) {
213     ResetSettings();
214     callback.Run(FAILED);
215   }
216 
217   // TODO(maruel):  Support PD_PRINTTOFILE.
218   callback.Run(ParseDialogResultEx(dialog_options));
219 }
220 
UseDefaultSettings()221 PrintingContext::Result PrintingContextWin::UseDefaultSettings() {
222   DCHECK(!in_print_job_);
223 
224   PRINTDLG dialog_options = { sizeof(PRINTDLG) };
225   dialog_options.Flags = PD_RETURNDC | PD_RETURNDEFAULT;
226   if (PrintDlg(&dialog_options))
227     return ParseDialogResult(dialog_options);
228 
229   // No default printer configured, do we have any printers at all?
230   DWORD bytes_needed = 0;
231   DWORD count_returned = 0;
232   (void)::EnumPrinters(PRINTER_ENUM_LOCAL|PRINTER_ENUM_CONNECTIONS,
233                        NULL, 2, NULL, 0, &bytes_needed, &count_returned);
234   if (bytes_needed) {
235     DCHECK_GE(bytes_needed, count_returned * sizeof(PRINTER_INFO_2));
236     scoped_ptr<BYTE[]> printer_info_buffer(new BYTE[bytes_needed]);
237     BOOL ret = ::EnumPrinters(PRINTER_ENUM_LOCAL|PRINTER_ENUM_CONNECTIONS,
238                               NULL, 2, printer_info_buffer.get(),
239                               bytes_needed, &bytes_needed,
240                               &count_returned);
241     if (ret && count_returned) {  // have printers
242       // Open the first successfully found printer.
243       const PRINTER_INFO_2* info_2 =
244           reinterpret_cast<PRINTER_INFO_2*>(printer_info_buffer.get());
245       const PRINTER_INFO_2* info_2_end = info_2 + count_returned;
246       for (; info_2 < info_2_end; ++info_2) {
247         ScopedPrinterHandle printer;
248         if (!printer.OpenPrinter(info_2->pPrinterName))
249           continue;
250         scoped_ptr<DEVMODE, base::FreeDeleter> dev_mode =
251             CreateDevMode(printer, NULL);
252         if (!dev_mode || !AllocateContext(info_2->pPrinterName, dev_mode.get(),
253                                           &context_)) {
254           continue;
255         }
256         if (InitializeSettings(*dev_mode.get(), info_2->pPrinterName, NULL, 0,
257                                false)) {
258           return OK;
259         }
260         ReleaseContext();
261       }
262       if (context_)
263         return OK;
264     }
265   }
266 
267   ResetSettings();
268   return FAILED;
269 }
270 
GetPdfPaperSizeDeviceUnits()271 gfx::Size PrintingContextWin::GetPdfPaperSizeDeviceUnits() {
272   // Default fallback to Letter size.
273   gfx::SizeF paper_size(kLetterWidthInch, kLetterHeightInch);
274 
275   // Get settings from locale. Paper type buffer length is at most 4.
276   const int paper_type_buffer_len = 4;
277   wchar_t paper_type_buffer[paper_type_buffer_len] = {0};
278   GetLocaleInfo(LOCALE_USER_DEFAULT, LOCALE_IPAPERSIZE, paper_type_buffer,
279                 paper_type_buffer_len);
280   if (wcslen(paper_type_buffer)) {  // The call succeeded.
281     int paper_code = _wtoi(paper_type_buffer);
282     switch (paper_code) {
283       case DMPAPER_LEGAL:
284         paper_size.SetSize(kLegalWidthInch, kLegalHeightInch);
285         break;
286       case DMPAPER_A4:
287         paper_size.SetSize(kA4WidthInch, kA4HeightInch);
288         break;
289       case DMPAPER_A3:
290         paper_size.SetSize(kA3WidthInch, kA3HeightInch);
291         break;
292       default:  // DMPAPER_LETTER is used for default fallback.
293         break;
294     }
295   }
296   return gfx::Size(
297       paper_size.width() * settings_.device_units_per_inch(),
298       paper_size.height() * settings_.device_units_per_inch());
299 }
300 
UpdatePrinterSettings(bool external_preview)301 PrintingContext::Result PrintingContextWin::UpdatePrinterSettings(
302     bool external_preview) {
303   DCHECK(!in_print_job_);
304   DCHECK(!external_preview) << "Not implemented";
305 
306   ScopedPrinterHandle printer;
307   if (!printer.OpenPrinter(settings_.device_name().c_str()))
308     return OnError();
309 
310   // Make printer changes local to Chrome.
311   // See MSDN documentation regarding DocumentProperties.
312   scoped_ptr<DEVMODE, base::FreeDeleter> scoped_dev_mode =
313       CreateDevModeWithColor(printer, settings_.device_name(),
314                              settings_.color() != GRAY);
315   if (!scoped_dev_mode)
316     return OnError();
317 
318   {
319     DEVMODE* dev_mode = scoped_dev_mode.get();
320     dev_mode->dmCopies = std::max(settings_.copies(), 1);
321     if (dev_mode->dmCopies > 1) {  // do not change unless multiple copies
322       dev_mode->dmFields |= DM_COPIES;
323       dev_mode->dmCollate = settings_.collate() ? DMCOLLATE_TRUE :
324                                                   DMCOLLATE_FALSE;
325     }
326 
327     switch (settings_.duplex_mode()) {
328       case LONG_EDGE:
329         dev_mode->dmFields |= DM_DUPLEX;
330         dev_mode->dmDuplex = DMDUP_VERTICAL;
331         break;
332       case SHORT_EDGE:
333         dev_mode->dmFields |= DM_DUPLEX;
334         dev_mode->dmDuplex = DMDUP_HORIZONTAL;
335         break;
336       case SIMPLEX:
337         dev_mode->dmFields |= DM_DUPLEX;
338         dev_mode->dmDuplex = DMDUP_SIMPLEX;
339         break;
340       default:  // UNKNOWN_DUPLEX_MODE
341         break;
342     }
343 
344     dev_mode->dmFields |= DM_ORIENTATION;
345     dev_mode->dmOrientation = settings_.landscape() ? DMORIENT_LANDSCAPE :
346                                                       DMORIENT_PORTRAIT;
347 
348     const PrintSettings::RequestedMedia& requested_media =
349         settings_.requested_media();
350     static const int kFromUm = 100;  // Windows uses 0.1mm.
351     int width = requested_media.size_microns.width() / kFromUm;
352     int height = requested_media.size_microns.height() / kFromUm;
353     unsigned id = 0;
354     if (base::StringToUint(requested_media.vendor_id, &id) && id) {
355       dev_mode->dmFields |= DM_PAPERSIZE;
356       dev_mode->dmPaperSize = static_cast<short>(id);
357     } else if (width > 0 && height > 0) {
358       dev_mode->dmFields |= DM_PAPERWIDTH;
359       dev_mode->dmPaperWidth = width;
360       dev_mode->dmFields |= DM_PAPERLENGTH;
361       dev_mode->dmPaperLength = height;
362     }
363   }
364 
365   // Update data using DocumentProperties.
366   scoped_dev_mode = CreateDevMode(printer, scoped_dev_mode.get());
367   if (!scoped_dev_mode)
368     return OnError();
369 
370   // Set printer then refresh printer settings.
371   if (!AllocateContext(settings_.device_name(), scoped_dev_mode.get(),
372                        &context_)) {
373     return OnError();
374   }
375   PrintSettingsInitializerWin::InitPrintSettings(context_,
376                                                  *scoped_dev_mode.get(),
377                                                  &settings_);
378   return OK;
379 }
380 
InitWithSettings(const PrintSettings & settings)381 PrintingContext::Result PrintingContextWin::InitWithSettings(
382     const PrintSettings& settings) {
383   DCHECK(!in_print_job_);
384 
385   settings_ = settings;
386 
387   // TODO(maruel): settings_.ToDEVMODE()
388   ScopedPrinterHandle printer;
389   if (!printer.OpenPrinter(settings_.device_name().c_str())) {
390     return FAILED;
391   }
392 
393   Result status = OK;
394 
395   if (!GetPrinterSettings(printer, settings_.device_name()))
396     status = FAILED;
397 
398   if (status != OK)
399     ResetSettings();
400   return status;
401 }
402 
NewDocument(const base::string16 & document_name)403 PrintingContext::Result PrintingContextWin::NewDocument(
404     const base::string16& document_name) {
405   DCHECK(!in_print_job_);
406   if (!context_)
407     return OnError();
408 
409   // Set the flag used by the AbortPrintJob dialog procedure.
410   abort_printing_ = false;
411 
412   in_print_job_ = true;
413 
414   // Register the application's AbortProc function with GDI.
415   if (SP_ERROR == SetAbortProc(context_, &AbortProc))
416     return OnError();
417 
418   DCHECK(SimplifyDocumentTitle(document_name) == document_name);
419   DOCINFO di = { sizeof(DOCINFO) };
420   di.lpszDocName = document_name.c_str();
421 
422   // Is there a debug dump directory specified? If so, force to print to a file.
423   base::string16 debug_dump_path =
424       PrintedDocument::CreateDebugDumpPath(document_name,
425                                            FILE_PATH_LITERAL(".prn")).value();
426   if (!debug_dump_path.empty())
427     di.lpszOutput = debug_dump_path.c_str();
428 
429   // No message loop running in unit tests.
430   DCHECK(!base::MessageLoop::current() ||
431          !base::MessageLoop::current()->NestableTasksAllowed());
432 
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)
437     return OnError();
438 
439   return OK;
440 }
441 
NewPage()442 PrintingContext::Result PrintingContextWin::NewPage() {
443   if (abort_printing_)
444     return CANCEL;
445   DCHECK(context_);
446   DCHECK(in_print_job_);
447 
448   // Intentional No-op. NativeMetafile::SafePlayback takes care of calling
449   // ::StartPage().
450 
451   return OK;
452 }
453 
PageDone()454 PrintingContext::Result PrintingContextWin::PageDone() {
455   if (abort_printing_)
456     return CANCEL;
457   DCHECK(in_print_job_);
458 
459   // Intentional No-op. NativeMetafile::SafePlayback takes care of calling
460   // ::EndPage().
461 
462   return OK;
463 }
464 
DocumentDone()465 PrintingContext::Result PrintingContextWin::DocumentDone() {
466   if (abort_printing_)
467     return CANCEL;
468   DCHECK(in_print_job_);
469   DCHECK(context_);
470 
471   // Inform the driver that document has ended.
472   if (EndDoc(context_) <= 0)
473     return OnError();
474 
475   ResetSettings();
476   return OK;
477 }
478 
Cancel()479 void PrintingContextWin::Cancel() {
480   abort_printing_ = true;
481   in_print_job_ = false;
482   if (context_)
483     CancelDC(context_);
484   if (dialog_box_) {
485     DestroyWindow(dialog_box_);
486     dialog_box_dismissed_ = true;
487   }
488 }
489 
ReleaseContext()490 void PrintingContextWin::ReleaseContext() {
491   if (context_) {
492     DeleteDC(context_);
493     context_ = NULL;
494   }
495 }
496 
context() const497 gfx::NativeDrawingContext PrintingContextWin::context() const {
498   return context_;
499 }
500 
501 // static
AbortProc(HDC hdc,int nCode)502 BOOL PrintingContextWin::AbortProc(HDC hdc, int nCode) {
503   if (nCode) {
504     // TODO(maruel):  Need a way to find the right instance to set. Should
505     // leverage PrintJobManager here?
506     // abort_printing_ = true;
507   }
508   return true;
509 }
510 
InitializeSettings(const DEVMODE & dev_mode,const std::wstring & new_device_name,const PRINTPAGERANGE * ranges,int number_ranges,bool selection_only)511 bool PrintingContextWin::InitializeSettings(const DEVMODE& dev_mode,
512                                             const std::wstring& new_device_name,
513                                             const PRINTPAGERANGE* ranges,
514                                             int number_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);
524 
525   // StretchDIBits() support is needed for printing.
526   if (!(GetDeviceCaps(context_, RASTERCAPS) & RC_STRETCHDIB) ||
527       !(GetDeviceCaps(context_, RASTERCAPS) & RC_BITMAP64)) {
528     NOTREACHED();
529     ResetSettings();
530     return false;
531   }
532 
533   DCHECK(!in_print_job_);
534   DCHECK(context_);
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) {
540       PageRange range;
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);
545     }
546   }
547 
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,
552                                                  &settings_);
553 
554   return true;
555 }
556 
GetPrinterSettings(HANDLE printer,const std::wstring & device_name)557 bool PrintingContextWin::GetPrinterSettings(HANDLE printer,
558                                             const std::wstring& device_name) {
559   DCHECK(!in_print_job_);
560 
561   scoped_ptr<DEVMODE, base::FreeDeleter> dev_mode =
562       CreateDevMode(printer, NULL);
563 
564   if (!dev_mode || !AllocateContext(device_name, dev_mode.get(), &context_)) {
565     ResetSettings();
566     return false;
567   }
568 
569   return InitializeSettings(*dev_mode.get(), device_name, NULL, 0, false);
570 }
571 
572 // static
AllocateContext(const std::wstring & device_name,const DEVMODE * dev_mode,gfx::NativeDrawingContext * context)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);
577   DCHECK(*context);
578   return *context != NULL;
579 }
580 
ParseDialogResultEx(const PRINTDLGEX & dialog_options)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) {
585     // Start fresh.
586     ResetSettings();
587 
588     DEVMODE* dev_mode = NULL;
589     if (dialog_options.hDevMode) {
590       dev_mode =
591           reinterpret_cast<DEVMODE*>(GlobalLock(dialog_options.hDevMode));
592       DCHECK(dev_mode);
593     }
594 
595     std::wstring device_name;
596     if (dialog_options.hDevNames) {
597       DEVNAMES* dev_names =
598           reinterpret_cast<DEVNAMES*>(GlobalLock(dialog_options.hDevNames));
599       DCHECK(dev_names);
600       if (dev_names) {
601         device_name = reinterpret_cast<const wchar_t*>(dev_names) +
602                       dev_names->wDeviceOffset;
603         GlobalUnlock(dialog_options.hDevNames);
604       }
605     }
606 
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;
616       }
617       if (dialog_options.Flags & PD_SELECTION) {
618         print_selection_only = true;
619       }
620       success = InitializeSettings(*dev_mode,
621                                    device_name,
622                                    page_ranges,
623                                    num_page_ranges,
624                                    print_selection_only);
625     }
626 
627     if (!success && dialog_options.hDC) {
628       DeleteDC(dialog_options.hDC);
629       context_ = NULL;
630     }
631 
632     if (dev_mode) {
633       GlobalUnlock(dialog_options.hDevMode);
634     }
635   } else {
636     if (dialog_options.hDC) {
637       DeleteDC(dialog_options.hDC);
638     }
639   }
640 
641   if (dialog_options.hDevMode != NULL)
642     GlobalFree(dialog_options.hDevMode);
643   if (dialog_options.hDevNames != NULL)
644     GlobalFree(dialog_options.hDevNames);
645 
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:
652       return CANCEL;
653     default:
654       return FAILED;
655   }
656 }
657 
ShowPrintDialog(PRINTDLGEX * options)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());
667 
668   return PrintDlgEx(options);
669 }
670 
ParseDialogResult(const PRINTDLG & dialog_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.
674   // Start fresh.
675   ResetSettings();
676 
677   DEVMODE* dev_mode = NULL;
678   if (dialog_options.hDevMode) {
679     dev_mode =
680         reinterpret_cast<DEVMODE*>(GlobalLock(dialog_options.hDevMode));
681     DCHECK(dev_mode);
682   }
683 
684   std::wstring device_name;
685   if (dialog_options.hDevNames) {
686     DEVNAMES* dev_names =
687         reinterpret_cast<DEVNAMES*>(GlobalLock(dialog_options.hDevNames));
688     DCHECK(dev_names);
689     if (dev_names) {
690       device_name =
691           reinterpret_cast<const wchar_t*>(
692               reinterpret_cast<const wchar_t*>(dev_names) +
693                   dev_names->wDeviceOffset);
694       GlobalUnlock(dialog_options.hDevNames);
695     }
696   }
697 
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);
702   }
703 
704   if (!success && dialog_options.hDC) {
705     DeleteDC(dialog_options.hDC);
706     context_ = NULL;
707   }
708 
709   if (dev_mode) {
710     GlobalUnlock(dialog_options.hDevMode);
711   }
712 
713   if (dialog_options.hDevMode != NULL)
714     GlobalFree(dialog_options.hDevMode);
715   if (dialog_options.hDevNames != NULL)
716     GlobalFree(dialog_options.hDevNames);
717 
718   return context_ ? OK : FAILED;
719 }
720 
721 }  // namespace printing
722