Revert 233039 "Blink roll 161254:161319"
[chromium-blink-merge.git] / printing / printing_context_win.cc
blob76d96bf24c28f984a697c86b85991a47dd083386
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"
7 #include <winspool.h>
9 #include <algorithm>
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"
29 #if defined(USE_AURA)
30 #include "ui/aura/remote_root_window_host_win.h"
31 #include "ui/aura/root_window.h"
32 #include "ui/aura/window.h"
33 #endif
35 using base::Time;
37 namespace {
39 HWND GetRootWindow(gfx::NativeView view) {
40 HWND window = NULL;
41 #if defined(USE_AURA)
42 if (view)
43 window = view->GetDispatcher()->GetAcceleratedWidget();
44 #else
45 if (view && IsWindow(view)) {
46 window = GetAncestor(view, GA_ROOTOWNER);
48 #endif
49 if (!window) {
50 // TODO(maruel): bug 1214347 Get the right browser window instead.
51 return GetDesktopWindow();
53 return window;
56 } // anonymous namespace
58 namespace printing {
60 class PrintingContextWin::CallbackHandler : public IPrintDialogCallback,
61 public IObjectWithSite {
62 public:
63 CallbackHandler(PrintingContextWin& owner, HWND owner_hwnd)
64 : owner_(owner),
65 owner_hwnd_(owner_hwnd),
66 services_(NULL) {
69 ~CallbackHandler() {
70 if (services_)
71 services_->Release();
74 IUnknown* ToIUnknown() {
75 return static_cast<IUnknown*>(static_cast<IPrintDialogCallback*>(this));
78 // IUnknown
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);
86 } else {
87 return E_NOINTERFACE;
89 return S_OK;
92 // No real ref counting.
93 virtual ULONG WINAPI AddRef() {
94 return 1;
96 virtual ULONG WINAPI Release() {
97 return 1;
100 // IPrintDialogCallback methods
101 virtual HRESULT WINAPI InitDone() {
102 return S_OK;
105 virtual HRESULT WINAPI SelectionChange() {
106 if (services_) {
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.
112 return S_OK;
115 virtual HRESULT WINAPI HandleMessage(HWND dialog,
116 UINT message,
117 WPARAM wparam,
118 LPARAM lparam,
119 LRESULT* result) {
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);
129 return S_FALSE;
132 virtual HRESULT WINAPI SetSite(IUnknown* site) {
133 if (!site) {
134 DCHECK(services_);
135 services_->Release();
136 services_ = NULL;
137 // The dialog box is destroying, PrintJob::Worker don't need the handle
138 // anymore.
139 owner_.dialog_box_ = NULL;
140 } else {
141 DCHECK(services_ == NULL);
142 HRESULT hr = site->QueryInterface(IID_IPrintDialogServices,
143 reinterpret_cast<void**>(&services_));
144 DCHECK(SUCCEEDED(hr));
146 return S_OK;
149 virtual HRESULT WINAPI GetSite(REFIID riid, void** site) {
150 return E_NOTIMPL;
153 private:
154 PrintingContextWin& owner_;
155 HWND owner_hwnd_;
156 IPrintDialogServices* services_;
158 DISALLOW_COPY_AND_ASSIGN(CallbackHandler);
161 // static
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),
168 context_(NULL),
169 dialog_box_(NULL),
170 print_dialog_func_(&PrintDlgEx) {
173 PrintingContextWin::~PrintingContextWin() {
174 ReleaseContext();
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);
203 DCHECK(window);
205 // Show the OS-dependent dialog box.
206 // If the user press
207 // - OK, the settings are reset and reinitialized with the new settings. OK is
208 // returned.
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;
223 if (!has_selection)
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;
230 if (max_pages) {
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;
239 } else {
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);
263 if (bytes_needed) {
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,
269 &count_returned);
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)
277 continue;
278 if (!AllocateContext(printer_name, info_2->pDevMode, &context_))
279 break;
280 if (InitializeSettings(*info_2->pDevMode, printer_name,
281 NULL, 0, false)) {
282 break;
284 ReleaseContext();
286 if (context_)
287 return OK;
291 ResetSettings();
292 return FAILED;
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) {
307 case DMPAPER_LEGAL:
308 paper_size.SetSize(kLegalWidthInch, kLegalHeightInch);
309 break;
310 case DMPAPER_A4:
311 paper_size.SetSize(kA4WidthInch, kA4HeightInch);
312 break;
313 case DMPAPER_A3:
314 paper_size.SetSize(kA3WidthInch, kA3HeightInch);
315 break;
316 default: // DMPAPER_LETTER is used for default fallback.
317 break;
320 return gfx::Size(
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))
334 return OnError();
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,
341 NULL, NULL, 0);
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) {
352 buffer.reset();
353 return OnError();
356 if (settings_.color() == GRAY)
357 dev_mode->dmColor = DMCOLOR_MONOCHROME;
358 else
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 :
364 DMCOLLATE_FALSE;
366 switch (settings_.duplex_mode()) {
367 case LONG_EDGE:
368 dev_mode->dmDuplex = DMDUP_VERTICAL;
369 break;
370 case SHORT_EDGE:
371 dev_mode->dmDuplex = DMDUP_HORIZONTAL;
372 break;
373 case SIMPLEX:
374 dev_mode->dmDuplex = DMDUP_SIMPLEX;
375 break;
376 default: // UNKNOWN_DUPLEX_MODE
377 break;
379 dev_mode->dmOrientation = settings_.landscape() ? DMORIENT_LANDSCAPE :
380 DMORIENT_PORTRAIT;
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) {
385 return OnError();
388 // Set printer then refresh printer settings.
389 if (!AllocateContext(settings_.device_name(), dev_mode, &context_)) {
390 return OnError();
392 PrintSettingsInitializerWin::InitPrintSettings(context_, *dev_mode,
393 &settings_);
394 return OK;
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())) {
406 return FAILED;
409 Result status = OK;
411 if (!GetPrinterSettings(printer, settings_.device_name()))
412 status = FAILED;
414 if (status != OK)
415 ResetSettings();
416 return status;
419 PrintingContext::Result PrintingContextWin::NewDocument(
420 const base::string16& document_name) {
421 DCHECK(!in_print_job_);
422 if (!context_)
423 return OnError();
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))
432 return OnError();
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);
446 filename += L"_";
447 filename += base::TimeFormatTimeOfDay(now);
448 filename += L"_";
449 filename += UTF16ToWide(document_name);
450 filename += L"_";
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)
465 return OnError();
467 return OK;
470 PrintingContext::Result PrintingContextWin::NewPage() {
471 if (abort_printing_)
472 return CANCEL;
473 DCHECK(context_);
474 DCHECK(in_print_job_);
476 // Intentional No-op. NativeMetafile::SafePlayback takes care of calling
477 // ::StartPage().
479 return OK;
482 PrintingContext::Result PrintingContextWin::PageDone() {
483 if (abort_printing_)
484 return CANCEL;
485 DCHECK(in_print_job_);
487 // Intentional No-op. NativeMetafile::SafePlayback takes care of calling
488 // ::EndPage().
490 return OK;
493 PrintingContext::Result PrintingContextWin::DocumentDone() {
494 if (abort_printing_)
495 return CANCEL;
496 DCHECK(in_print_job_);
497 DCHECK(context_);
499 // Inform the driver that document has ended.
500 if (EndDoc(context_) <= 0)
501 return OnError();
503 ResetSettings();
504 return OK;
507 void PrintingContextWin::Cancel() {
508 abort_printing_ = true;
509 in_print_job_ = false;
510 if (context_)
511 CancelDC(context_);
512 if (dialog_box_) {
513 DestroyWindow(dialog_box_);
514 dialog_box_dismissed_ = true;
518 void PrintingContextWin::ReleaseContext() {
519 if (context_) {
520 DeleteDC(context_);
521 context_ = NULL;
525 gfx::NativeDrawingContext PrintingContextWin::context() const {
526 return context_;
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) {
537 ResetSettings();
538 callback_.Run(FAILED);
539 delete [] dialog_options->lpPageRanges;
540 free(dialog_options);
543 // static
544 BOOL PrintingContextWin::AbortProc(HDC hdc, int nCode) {
545 if (nCode) {
546 // TODO(maruel): Need a way to find the right instance to set. Should
547 // leverage PrintJobManager here?
548 // abort_printing_ = true;
550 return true;
553 bool PrintingContextWin::InitializeSettings(const DEVMODE& dev_mode,
554 const std::wstring& new_device_name,
555 const PRINTPAGERANGE* ranges,
556 int number_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)) {
570 NOTREACHED();
571 ResetSettings();
572 return false;
575 DCHECK(!in_print_job_);
576 DCHECK(context_);
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) {
582 PageRange range;
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,
594 &settings_);
596 return true;
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_)) {
607 ResetSettings();
608 return false;
611 return InitializeSettings(*user_settings.get(), device_name, NULL, 0, false);
614 // static
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);
619 DCHECK(*context);
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) {
627 // Start fresh.
628 ResetSettings();
630 DEVMODE* dev_mode = NULL;
631 if (dialog_options.hDevMode) {
632 dev_mode =
633 reinterpret_cast<DEVMODE*>(GlobalLock(dialog_options.hDevMode));
634 DCHECK(dev_mode);
637 std::wstring device_name;
638 if (dialog_options.hDevNames) {
639 DEVNAMES* dev_names =
640 reinterpret_cast<DEVNAMES*>(GlobalLock(dialog_options.hDevNames));
641 DCHECK(dev_names);
642 if (dev_names) {
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,
663 device_name,
664 page_ranges,
665 num_page_ranges,
666 print_selection_only);
669 if (!success && dialog_options.hDC) {
670 DeleteDC(dialog_options.hDC);
671 context_ = NULL;
674 if (dev_mode) {
675 GlobalUnlock(dialog_options.hDevMode);
677 } else {
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:
694 return CANCEL;
695 default:
696 return FAILED;
700 PrintingContext::Result PrintingContextWin::ParseDialogResult(
701 const PRINTDLG& dialog_options) {
702 // If the user clicked OK or Apply then Cancel, but not only Cancel.
703 // Start fresh.
704 ResetSettings();
706 DEVMODE* dev_mode = NULL;
707 if (dialog_options.hDevMode) {
708 dev_mode =
709 reinterpret_cast<DEVMODE*>(GlobalLock(dialog_options.hDevMode));
710 DCHECK(dev_mode);
713 std::wstring device_name;
714 if (dialog_options.hDevNames) {
715 DEVNAMES* dev_names =
716 reinterpret_cast<DEVNAMES*>(GlobalLock(dialog_options.hDevNames));
717 DCHECK(dev_names);
718 if (dev_names) {
719 device_name =
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);
735 context_ = NULL;
738 if (dev_mode) {
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