Revert 264226 "Reduce dependency of TiclInvalidationService on P..."
[chromium-blink-merge.git] / printing / printing_context_win.cc
bloba9e22b3467b5fa5ad8e30cf1b7923b29d837a507
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/printing_utils.h"
26 #include "printing/units.h"
27 #include "skia/ext/platform_device.h"
28 #include "win8/util/win8_util.h"
30 #if defined(USE_AURA)
31 #include "ui/aura/remote_window_tree_host_win.h"
32 #include "ui/aura/window.h"
33 #include "ui/aura/window_event_dispatcher.h"
34 #endif
36 using base::Time;
38 namespace {
40 HWND GetRootWindow(gfx::NativeView view) {
41 HWND window = NULL;
42 #if defined(USE_AURA)
43 if (view)
44 window = view->GetHost()->GetAcceleratedWidget();
45 #else
46 if (view && IsWindow(view)) {
47 window = GetAncestor(view, GA_ROOTOWNER);
49 #endif
50 if (!window) {
51 // TODO(maruel): bug 1214347 Get the right browser window instead.
52 return GetDesktopWindow();
54 return window;
57 } // anonymous namespace
59 namespace printing {
61 class PrintingContextWin::CallbackHandler : public IPrintDialogCallback,
62 public IObjectWithSite {
63 public:
64 CallbackHandler(PrintingContextWin& owner, HWND owner_hwnd)
65 : owner_(owner),
66 owner_hwnd_(owner_hwnd),
67 services_(NULL) {
70 ~CallbackHandler() {
71 if (services_)
72 services_->Release();
75 IUnknown* ToIUnknown() {
76 return static_cast<IUnknown*>(static_cast<IPrintDialogCallback*>(this));
79 // IUnknown
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);
87 } else {
88 return E_NOINTERFACE;
90 return S_OK;
93 // No real ref counting.
94 virtual ULONG WINAPI AddRef() {
95 return 1;
97 virtual ULONG WINAPI Release() {
98 return 1;
101 // IPrintDialogCallback methods
102 virtual HRESULT WINAPI InitDone() {
103 return S_OK;
106 virtual HRESULT WINAPI SelectionChange() {
107 if (services_) {
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.
113 return S_OK;
116 virtual HRESULT WINAPI HandleMessage(HWND dialog,
117 UINT message,
118 WPARAM wparam,
119 LPARAM lparam,
120 LRESULT* result) {
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);
130 return S_FALSE;
133 virtual HRESULT WINAPI SetSite(IUnknown* site) {
134 if (!site) {
135 DCHECK(services_);
136 services_->Release();
137 services_ = NULL;
138 // The dialog box is destroying, PrintJob::Worker don't need the handle
139 // anymore.
140 owner_.dialog_box_ = NULL;
141 } else {
142 DCHECK(services_ == NULL);
143 HRESULT hr = site->QueryInterface(IID_IPrintDialogServices,
144 reinterpret_cast<void**>(&services_));
145 DCHECK(SUCCEEDED(hr));
147 return S_OK;
150 virtual HRESULT WINAPI GetSite(REFIID riid, void** site) {
151 return E_NOTIMPL;
154 private:
155 PrintingContextWin& owner_;
156 HWND owner_hwnd_;
157 IPrintDialogServices* services_;
159 DISALLOW_COPY_AND_ASSIGN(CallbackHandler);
162 // static
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() {
171 ReleaseContext();
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);
199 DCHECK(window);
201 // Show the OS-dependent dialog box.
202 // If the user press
203 // - OK, the settings are reset and reinitialized with the new settings. OK is
204 // returned.
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;
216 if (!has_selection)
217 dialog_options.Flags |= PD_NOSELECTION;
219 PRINTPAGERANGE ranges[32];
220 dialog_options.nStartPage = START_PAGE_GENERAL;
221 if (max_pages) {
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;
231 } else {
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) {
237 ResetSettings();
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);
258 if (bytes_needed) {
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,
264 &count_returned);
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))
273 continue;
274 scoped_ptr<DEVMODE, base::FreeDeleter> dev_mode =
275 CreateDevMode(printer, NULL);
276 if (!dev_mode || !AllocateContext(info_2->pPrinterName, dev_mode.get(),
277 &context_)) {
278 continue;
280 if (InitializeSettings(*dev_mode.get(), info_2->pPrinterName, NULL, 0,
281 false)) {
282 return OK;
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 if (!printer.OpenPrinter(settings_.device_name().c_str()))
332 return OnError();
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)
340 return OnError();
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 :
348 DMCOLLATE_FALSE;
351 switch (settings_.duplex_mode()) {
352 case LONG_EDGE:
353 dev_mode->dmFields |= DM_DUPLEX;
354 dev_mode->dmDuplex = DMDUP_VERTICAL;
355 break;
356 case SHORT_EDGE:
357 dev_mode->dmFields |= DM_DUPLEX;
358 dev_mode->dmDuplex = DMDUP_HORIZONTAL;
359 break;
360 case SIMPLEX:
361 dev_mode->dmFields |= DM_DUPLEX;
362 dev_mode->dmDuplex = DMDUP_SIMPLEX;
363 break;
364 default: // UNKNOWN_DUPLEX_MODE
365 break;
368 dev_mode->dmFields |= DM_ORIENTATION;
369 dev_mode->dmOrientation = settings_.landscape() ? DMORIENT_LANDSCAPE :
370 DMORIENT_PORTRAIT;
373 // Update data using DocumentProperties.
374 scoped_dev_mode = CreateDevMode(printer, scoped_dev_mode.get());
375 if (!scoped_dev_mode)
376 return OnError();
378 // Set printer then refresh printer settings.
379 if (!AllocateContext(settings_.device_name(), scoped_dev_mode.get(),
380 &context_)) {
381 return OnError();
383 PrintSettingsInitializerWin::InitPrintSettings(context_,
384 *scoped_dev_mode.get(),
385 &settings_);
386 return OK;
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())) {
398 return FAILED;
401 Result status = OK;
403 if (!GetPrinterSettings(printer, settings_.device_name()))
404 status = FAILED;
406 if (status != OK)
407 ResetSettings();
408 return status;
411 PrintingContext::Result PrintingContextWin::NewDocument(
412 const base::string16& document_name) {
413 DCHECK(!in_print_job_);
414 if (!context_)
415 return OnError();
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))
424 return OnError();
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);
438 filename += L"_";
439 filename += base::TimeFormatTimeOfDay(now);
440 filename += L"_";
441 filename += base::UTF16ToWide(document_name);
442 filename += L"_";
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)
457 return OnError();
459 return OK;
462 PrintingContext::Result PrintingContextWin::NewPage() {
463 if (abort_printing_)
464 return CANCEL;
465 DCHECK(context_);
466 DCHECK(in_print_job_);
468 // Intentional No-op. NativeMetafile::SafePlayback takes care of calling
469 // ::StartPage().
471 return OK;
474 PrintingContext::Result PrintingContextWin::PageDone() {
475 if (abort_printing_)
476 return CANCEL;
477 DCHECK(in_print_job_);
479 // Intentional No-op. NativeMetafile::SafePlayback takes care of calling
480 // ::EndPage().
482 return OK;
485 PrintingContext::Result PrintingContextWin::DocumentDone() {
486 if (abort_printing_)
487 return CANCEL;
488 DCHECK(in_print_job_);
489 DCHECK(context_);
491 // Inform the driver that document has ended.
492 if (EndDoc(context_) <= 0)
493 return OnError();
495 ResetSettings();
496 return OK;
499 void PrintingContextWin::Cancel() {
500 abort_printing_ = true;
501 in_print_job_ = false;
502 if (context_)
503 CancelDC(context_);
504 if (dialog_box_) {
505 DestroyWindow(dialog_box_);
506 dialog_box_dismissed_ = true;
510 void PrintingContextWin::ReleaseContext() {
511 if (context_) {
512 DeleteDC(context_);
513 context_ = NULL;
517 gfx::NativeDrawingContext PrintingContextWin::context() const {
518 return context_;
521 // static
522 BOOL PrintingContextWin::AbortProc(HDC hdc, int nCode) {
523 if (nCode) {
524 // TODO(maruel): Need a way to find the right instance to set. Should
525 // leverage PrintJobManager here?
526 // abort_printing_ = true;
528 return true;
531 bool PrintingContextWin::InitializeSettings(const DEVMODE& dev_mode,
532 const std::wstring& new_device_name,
533 const PRINTPAGERANGE* ranges,
534 int number_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)) {
548 NOTREACHED();
549 ResetSettings();
550 return false;
553 DCHECK(!in_print_job_);
554 DCHECK(context_);
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) {
560 PageRange range;
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,
572 &settings_);
574 return true;
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_)) {
585 ResetSettings();
586 return false;
589 return InitializeSettings(*dev_mode.get(), device_name, NULL, 0, false);
592 // static
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);
597 DCHECK(*context);
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) {
605 // Start fresh.
606 ResetSettings();
608 DEVMODE* dev_mode = NULL;
609 if (dialog_options.hDevMode) {
610 dev_mode =
611 reinterpret_cast<DEVMODE*>(GlobalLock(dialog_options.hDevMode));
612 DCHECK(dev_mode);
615 std::wstring device_name;
616 if (dialog_options.hDevNames) {
617 DEVNAMES* dev_names =
618 reinterpret_cast<DEVNAMES*>(GlobalLock(dialog_options.hDevNames));
619 DCHECK(dev_names);
620 if (dev_names) {
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,
641 device_name,
642 page_ranges,
643 num_page_ranges,
644 print_selection_only);
647 if (!success && dialog_options.hDC) {
648 DeleteDC(dialog_options.hDC);
649 context_ = NULL;
652 if (dev_mode) {
653 GlobalUnlock(dialog_options.hDevMode);
655 } else {
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:
672 return CANCEL;
673 default:
674 return FAILED;
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.
694 // Start fresh.
695 ResetSettings();
697 DEVMODE* dev_mode = NULL;
698 if (dialog_options.hDevMode) {
699 dev_mode =
700 reinterpret_cast<DEVMODE*>(GlobalLock(dialog_options.hDevMode));
701 DCHECK(dev_mode);
704 std::wstring device_name;
705 if (dialog_options.hDevNames) {
706 DEVNAMES* dev_names =
707 reinterpret_cast<DEVNAMES*>(GlobalLock(dialog_options.hDevNames));
708 DCHECK(dev_names);
709 if (dev_names) {
710 device_name =
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);
726 context_ = NULL;
729 if (dev_mode) {
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