Avoid double-InitCache() in SimpleDoomBetween test, leak
[chromium-blink-merge.git] / printing / printing_context_win.cc
blobddfae1aa2b8c371b6b2e9c900f448f94081687e1
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.h"
14 #include "base/metrics/histogram.h"
15 #include "base/time.h"
16 #include "base/utf_string_conversions.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 using base::Time;
31 namespace {
33 // Constants for setting default PDF settings.
34 const int kPDFDpi = 300; // 300 dpi
35 // LETTER: 8.5 x 11 inches
36 const int kPDFLetterWidth = 8.5 * kPDFDpi;
37 const int kPDFLetterHeight = 11 * kPDFDpi;
38 // LEGAL: 8.5 x 14 inches
39 const int kPDFLegalWidth = 8.5 * kPDFDpi;
40 const int kPDFLegalHeight = 14 * kPDFDpi;
41 // A4: 8.27 x 11.69 inches
42 const int kPDFA4Width = 8.27 * kPDFDpi;
43 const int kPDFA4Height = 11.69 * kPDFDpi;
44 // A3: 11.69 x 16.54 inches
45 const int kPDFA3Width = 11.69 * kPDFDpi;
46 const int kPDFA3Height = 16.54 * kPDFDpi;
48 } // anonymous namespace
50 namespace printing {
52 class PrintingContextWin::CallbackHandler : public IPrintDialogCallback,
53 public IObjectWithSite {
54 public:
55 CallbackHandler(PrintingContextWin& owner, HWND owner_hwnd)
56 : owner_(owner),
57 owner_hwnd_(owner_hwnd),
58 services_(NULL) {
61 ~CallbackHandler() {
62 if (services_)
63 services_->Release();
66 IUnknown* ToIUnknown() {
67 return static_cast<IUnknown*>(static_cast<IPrintDialogCallback*>(this));
70 // IUnknown
71 virtual HRESULT WINAPI QueryInterface(REFIID riid, void**object) {
72 if (riid == IID_IUnknown) {
73 *object = ToIUnknown();
74 } else if (riid == IID_IPrintDialogCallback) {
75 *object = static_cast<IPrintDialogCallback*>(this);
76 } else if (riid == IID_IObjectWithSite) {
77 *object = static_cast<IObjectWithSite*>(this);
78 } else {
79 return E_NOINTERFACE;
81 return S_OK;
84 // No real ref counting.
85 virtual ULONG WINAPI AddRef() {
86 return 1;
88 virtual ULONG WINAPI Release() {
89 return 1;
92 // IPrintDialogCallback methods
93 virtual HRESULT WINAPI InitDone() {
94 return S_OK;
97 virtual HRESULT WINAPI SelectionChange() {
98 if (services_) {
99 // TODO(maruel): Get the devmode for the new printer with
100 // services_->GetCurrentDevMode(&devmode, &size), send that information
101 // back to our client and continue. The client needs to recalculate the
102 // number of rendered pages and send back this information here.
104 return S_OK;
107 virtual HRESULT WINAPI HandleMessage(HWND dialog,
108 UINT message,
109 WPARAM wparam,
110 LPARAM lparam,
111 LRESULT* result) {
112 // Cheap way to retrieve the window handle.
113 if (!owner_.dialog_box_) {
114 // The handle we receive is the one of the groupbox in the General tab. We
115 // need to get the grand-father to get the dialog box handle.
116 owner_.dialog_box_ = GetAncestor(dialog, GA_ROOT);
117 // Trick to enable the owner window. This can cause issues with navigation
118 // events so it may have to be disabled if we don't fix the side-effects.
119 EnableWindow(owner_hwnd_, TRUE);
121 return S_FALSE;
124 virtual HRESULT WINAPI SetSite(IUnknown* site) {
125 if (!site) {
126 DCHECK(services_);
127 services_->Release();
128 services_ = NULL;
129 // The dialog box is destroying, PrintJob::Worker don't need the handle
130 // anymore.
131 owner_.dialog_box_ = NULL;
132 } else {
133 DCHECK(services_ == NULL);
134 HRESULT hr = site->QueryInterface(IID_IPrintDialogServices,
135 reinterpret_cast<void**>(&services_));
136 DCHECK(SUCCEEDED(hr));
138 return S_OK;
141 virtual HRESULT WINAPI GetSite(REFIID riid, void** site) {
142 return E_NOTIMPL;
145 private:
146 PrintingContextWin& owner_;
147 HWND owner_hwnd_;
148 IPrintDialogServices* services_;
150 DISALLOW_COPY_AND_ASSIGN(CallbackHandler);
153 // static
154 PrintingContext* PrintingContext::Create(const std::string& app_locale) {
155 return static_cast<PrintingContext*>(new PrintingContextWin(app_locale));
158 PrintingContextWin::PrintingContextWin(const std::string& app_locale)
159 : PrintingContext(app_locale),
160 context_(NULL),
161 dialog_box_(NULL),
162 print_dialog_func_(&PrintDlgEx) {
165 PrintingContextWin::~PrintingContextWin() {
166 ReleaseContext();
169 void PrintingContextWin::AskUserForSettings(
170 gfx::NativeView view, int max_pages, bool has_selection,
171 const PrintSettingsCallback& callback) {
172 #if !defined(USE_AURA)
173 DCHECK(!in_print_job_);
175 if (win8::IsSingleWindowMetroMode()) {
176 // The system dialog can not be opened while running in Metro.
177 // But we can programatically launch the Metro print device charm though.
178 HMODULE metro_module = base::win::GetMetroModule();
179 if (metro_module != NULL) {
180 typedef void (*MetroShowPrintUI)();
181 MetroShowPrintUI metro_show_print_ui =
182 reinterpret_cast<MetroShowPrintUI>(
183 ::GetProcAddress(metro_module, "MetroShowPrintUI"));
184 if (metro_show_print_ui) {
185 // TODO(mad): Remove this once we can send user metrics from the metro
186 // driver. crbug.com/142330
187 UMA_HISTOGRAM_ENUMERATION("Metro.Print", 1, 2);
188 metro_show_print_ui();
191 return callback.Run(CANCEL);
193 dialog_box_dismissed_ = false;
195 HWND window;
196 if (!view || !IsWindow(view)) {
197 // TODO(maruel): bug 1214347 Get the right browser window instead.
198 window = GetDesktopWindow();
199 } else {
200 window = GetAncestor(view, GA_ROOTOWNER);
202 DCHECK(window);
204 // Show the OS-dependent dialog box.
205 // If the user press
206 // - OK, the settings are reset and reinitialized with the new settings. OK is
207 // returned.
208 // - Apply then Cancel, the settings are reset and reinitialized with the new
209 // settings. CANCEL is returned.
210 // - Cancel, the settings are not changed, the previous setting, if it was
211 // initialized before, are kept. CANCEL is returned.
212 // On failure, the settings are reset and FAILED is returned.
213 PRINTDLGEX dialog_options = { sizeof(PRINTDLGEX) };
214 dialog_options.hwndOwner = window;
215 // Disable options we don't support currently.
216 // TODO(maruel): Reuse the previously loaded settings!
217 dialog_options.Flags = PD_RETURNDC | PD_USEDEVMODECOPIESANDCOLLATE |
218 PD_NOCURRENTPAGE | PD_HIDEPRINTTOFILE;
219 if (!has_selection)
220 dialog_options.Flags |= PD_NOSELECTION;
222 PRINTPAGERANGE ranges[32];
223 dialog_options.nStartPage = START_PAGE_GENERAL;
224 if (max_pages) {
225 // Default initialize to print all the pages.
226 memset(ranges, 0, sizeof(ranges));
227 ranges[0].nFromPage = 1;
228 ranges[0].nToPage = max_pages;
229 dialog_options.nPageRanges = 1;
230 dialog_options.nMaxPageRanges = arraysize(ranges);
231 dialog_options.nMinPage = 1;
232 dialog_options.nMaxPage = max_pages;
233 dialog_options.lpPageRanges = ranges;
234 } else {
235 // No need to bother, we don't know how many pages are available.
236 dialog_options.Flags |= PD_NOPAGENUMS;
239 if ((*print_dialog_func_)(&dialog_options) != S_OK) {
240 ResetSettings();
241 callback.Run(FAILED);
244 // TODO(maruel): Support PD_PRINTTOFILE.
245 callback.Run(ParseDialogResultEx(dialog_options));
246 #endif
249 PrintingContext::Result PrintingContextWin::UseDefaultSettings() {
250 DCHECK(!in_print_job_);
252 PRINTDLG dialog_options = { sizeof(PRINTDLG) };
253 dialog_options.Flags = PD_RETURNDC | PD_RETURNDEFAULT;
254 if (PrintDlg(&dialog_options))
255 return ParseDialogResult(dialog_options);
257 // No default printer configured, do we have any printers at all?
258 DWORD bytes_needed = 0;
259 DWORD count_returned = 0;
260 (void)::EnumPrinters(PRINTER_ENUM_LOCAL|PRINTER_ENUM_CONNECTIONS,
261 NULL, 2, NULL, 0, &bytes_needed, &count_returned);
262 if (bytes_needed) {
263 DCHECK(bytes_needed >= count_returned * sizeof(PRINTER_INFO_2));
264 scoped_ptr<BYTE[]> printer_info_buffer(new BYTE[bytes_needed]);
265 BOOL ret = ::EnumPrinters(PRINTER_ENUM_LOCAL|PRINTER_ENUM_CONNECTIONS,
266 NULL, 2, printer_info_buffer.get(),
267 bytes_needed, &bytes_needed,
268 &count_returned);
269 if (ret && count_returned) { // have printers
270 // Open the first successfully found printer.
271 for (DWORD count = 0; count < count_returned; ++count) {
272 PRINTER_INFO_2* info_2 = reinterpret_cast<PRINTER_INFO_2*>(
273 printer_info_buffer.get() + count * sizeof(PRINTER_INFO_2));
274 std::wstring printer_name = info_2->pPrinterName;
275 if (info_2->pDevMode == NULL || printer_name.length() == 0)
276 continue;
277 if (!AllocateContext(printer_name, info_2->pDevMode, &context_))
278 break;
279 if (InitializeSettings(*info_2->pDevMode, printer_name,
280 NULL, 0, false)) {
281 break;
283 ReleaseContext();
285 if (context_)
286 return OK;
290 ResetSettings();
291 return FAILED;
294 PrintingContext::Result PrintingContextWin::UpdatePrinterSettings(
295 const DictionaryValue& job_settings,
296 const PageRanges& ranges) {
297 DCHECK(!in_print_job_);
299 bool collate;
300 int color;
301 bool landscape;
302 bool print_to_pdf;
303 bool is_cloud_dialog;
304 int copies;
305 int duplex_mode;
306 string16 device_name;
308 if (!job_settings.GetBoolean(kSettingLandscape, &landscape) ||
309 !job_settings.GetBoolean(kSettingCollate, &collate) ||
310 !job_settings.GetInteger(kSettingColor, &color) ||
311 !job_settings.GetBoolean(kSettingPrintToPDF, &print_to_pdf) ||
312 !job_settings.GetInteger(kSettingDuplexMode, &duplex_mode) ||
313 !job_settings.GetInteger(kSettingCopies, &copies) ||
314 !job_settings.GetString(kSettingDeviceName, &device_name) ||
315 !job_settings.GetBoolean(kSettingCloudPrintDialog, &is_cloud_dialog)) {
316 return OnError();
319 bool print_to_cloud = job_settings.HasKey(kSettingCloudPrintId);
321 if (print_to_pdf || print_to_cloud || is_cloud_dialog) {
322 // Default fallback to Letter size.
323 gfx::Size paper_size;
324 gfx::Rect paper_rect;
325 paper_size.SetSize(kPDFLetterWidth, kPDFLetterHeight);
327 // Get settings from locale. Paper type buffer length is at most 4.
328 const int paper_type_buffer_len = 4;
329 wchar_t paper_type_buffer[paper_type_buffer_len] = {0};
330 GetLocaleInfo(LOCALE_USER_DEFAULT, LOCALE_IPAPERSIZE, paper_type_buffer,
331 paper_type_buffer_len);
332 if (wcslen(paper_type_buffer)) { // The call succeeded.
333 int paper_code = _wtoi(paper_type_buffer);
334 switch (paper_code) {
335 case DMPAPER_LEGAL:
336 paper_size.SetSize(kPDFLegalWidth, kPDFLegalHeight);
337 break;
338 case DMPAPER_A4:
339 paper_size.SetSize(kPDFA4Width, kPDFA4Height);
340 break;
341 case DMPAPER_A3:
342 paper_size.SetSize(kPDFA3Width, kPDFA3Height);
343 break;
344 default: // DMPAPER_LETTER is used for default fallback.
345 break;
348 paper_rect.SetRect(0, 0, paper_size.width(), paper_size.height());
349 settings_.SetPrinterPrintableArea(paper_size, paper_rect, kPDFDpi);
350 settings_.set_dpi(kPDFDpi);
351 settings_.SetOrientation(landscape);
352 settings_.ranges = ranges;
353 return OK;
356 ScopedPrinterHandle printer;
357 LPWSTR device_name_wide = const_cast<wchar_t*>(device_name.c_str());
358 if (!OpenPrinter(device_name_wide, printer.Receive(), NULL))
359 return OnError();
361 // Make printer changes local to Chrome.
362 // See MSDN documentation regarding DocumentProperties.
363 scoped_ptr<uint8[]> buffer;
364 DEVMODE* dev_mode = NULL;
365 LONG buffer_size = DocumentProperties(NULL, printer, device_name_wide,
366 NULL, NULL, 0);
367 if (buffer_size > 0) {
368 buffer.reset(new uint8[buffer_size]);
369 memset(buffer.get(), 0, buffer_size);
370 if (DocumentProperties(NULL, printer, device_name_wide,
371 reinterpret_cast<PDEVMODE>(buffer.get()), NULL,
372 DM_OUT_BUFFER) == IDOK) {
373 dev_mode = reinterpret_cast<PDEVMODE>(buffer.get());
376 if (dev_mode == NULL) {
377 buffer.reset();
378 return OnError();
381 if (color == GRAY)
382 dev_mode->dmColor = DMCOLOR_MONOCHROME;
383 else
384 dev_mode->dmColor = DMCOLOR_COLOR;
386 dev_mode->dmCopies = std::max(copies, 1);
387 if (dev_mode->dmCopies > 1) // do not change collate unless multiple copies
388 dev_mode->dmCollate = collate ? DMCOLLATE_TRUE : DMCOLLATE_FALSE;
389 switch (duplex_mode) {
390 case LONG_EDGE:
391 dev_mode->dmDuplex = DMDUP_VERTICAL;
392 break;
393 case SHORT_EDGE:
394 dev_mode->dmDuplex = DMDUP_HORIZONTAL;
395 break;
396 case SIMPLEX:
397 dev_mode->dmDuplex = DMDUP_SIMPLEX;
398 break;
399 default: // UNKNOWN_DUPLEX_MODE
400 break;
402 dev_mode->dmOrientation = landscape ? DMORIENT_LANDSCAPE : DMORIENT_PORTRAIT;
404 // Update data using DocumentProperties.
405 if (DocumentProperties(NULL, printer, device_name_wide, dev_mode, dev_mode,
406 DM_IN_BUFFER | DM_OUT_BUFFER) != IDOK) {
407 return OnError();
410 // Set printer then refresh printer settings.
411 if (!AllocateContext(device_name, dev_mode, &context_)) {
412 return OnError();
414 PrintSettingsInitializerWin::InitPrintSettings(context_, *dev_mode,
415 ranges, device_name,
416 false, &settings_);
417 return OK;
420 PrintingContext::Result PrintingContextWin::InitWithSettings(
421 const PrintSettings& settings) {
422 DCHECK(!in_print_job_);
424 settings_ = settings;
426 // TODO(maruel): settings_.ToDEVMODE()
427 ScopedPrinterHandle printer;
428 if (!OpenPrinter(const_cast<wchar_t*>(settings_.device_name().c_str()),
429 printer.Receive(), NULL))
430 return FAILED;
432 Result status = OK;
434 if (!GetPrinterSettings(printer, settings_.device_name()))
435 status = FAILED;
437 if (status != OK)
438 ResetSettings();
439 return status;
442 PrintingContext::Result PrintingContextWin::NewDocument(
443 const string16& document_name) {
444 DCHECK(!in_print_job_);
445 if (!context_)
446 return OnError();
448 // Set the flag used by the AbortPrintJob dialog procedure.
449 abort_printing_ = false;
451 in_print_job_ = true;
453 // Register the application's AbortProc function with GDI.
454 if (SP_ERROR == SetAbortProc(context_, &AbortProc))
455 return OnError();
457 DCHECK(PrintBackend::SimplifyDocumentTitle(document_name) == document_name);
458 DOCINFO di = { sizeof(DOCINFO) };
459 const std::wstring& document_name_wide = UTF16ToWide(document_name);
460 di.lpszDocName = document_name_wide.c_str();
462 // Is there a debug dump directory specified? If so, force to print to a file.
463 base::FilePath debug_dump_path = PrintedDocument::debug_dump_path();
464 if (!debug_dump_path.empty()) {
465 // Create a filename.
466 std::wstring filename;
467 Time now(Time::Now());
468 filename = base::TimeFormatShortDateNumeric(now);
469 filename += L"_";
470 filename += base::TimeFormatTimeOfDay(now);
471 filename += L"_";
472 filename += UTF16ToWide(document_name);
473 filename += L"_";
474 filename += L"buffer.prn";
475 file_util::ReplaceIllegalCharactersInPath(&filename, '_');
476 debug_dump_path.Append(filename);
477 di.lpszOutput = debug_dump_path.value().c_str();
480 // No message loop running in unit tests.
481 DCHECK(!MessageLoop::current() ? true :
482 !MessageLoop::current()->NestableTasksAllowed());
484 // Begin a print job by calling the StartDoc function.
485 // NOTE: StartDoc() starts a message loop. That causes a lot of problems with
486 // IPC. Make sure recursive task processing is disabled.
487 if (StartDoc(context_, &di) <= 0)
488 return OnError();
490 return OK;
493 PrintingContext::Result PrintingContextWin::NewPage() {
494 if (abort_printing_)
495 return CANCEL;
496 DCHECK(context_);
497 DCHECK(in_print_job_);
499 // Intentional No-op. NativeMetafile::SafePlayback takes care of calling
500 // ::StartPage().
502 return OK;
505 PrintingContext::Result PrintingContextWin::PageDone() {
506 if (abort_printing_)
507 return CANCEL;
508 DCHECK(in_print_job_);
510 // Intentional No-op. NativeMetafile::SafePlayback takes care of calling
511 // ::EndPage().
513 return OK;
516 PrintingContext::Result PrintingContextWin::DocumentDone() {
517 if (abort_printing_)
518 return CANCEL;
519 DCHECK(in_print_job_);
520 DCHECK(context_);
522 // Inform the driver that document has ended.
523 if (EndDoc(context_) <= 0)
524 return OnError();
526 ResetSettings();
527 return OK;
530 void PrintingContextWin::Cancel() {
531 abort_printing_ = true;
532 in_print_job_ = false;
533 if (context_)
534 CancelDC(context_);
535 if (dialog_box_) {
536 DestroyWindow(dialog_box_);
537 dialog_box_dismissed_ = true;
541 void PrintingContextWin::ReleaseContext() {
542 if (context_) {
543 DeleteDC(context_);
544 context_ = NULL;
548 gfx::NativeDrawingContext PrintingContextWin::context() const {
549 return context_;
552 // static
553 BOOL PrintingContextWin::AbortProc(HDC hdc, int nCode) {
554 if (nCode) {
555 // TODO(maruel): Need a way to find the right instance to set. Should
556 // leverage PrintJobManager here?
557 // abort_printing_ = true;
559 return true;
562 bool PrintingContextWin::InitializeSettings(const DEVMODE& dev_mode,
563 const std::wstring& new_device_name,
564 const PRINTPAGERANGE* ranges,
565 int number_ranges,
566 bool selection_only) {
567 skia::InitializeDC(context_);
568 DCHECK(GetDeviceCaps(context_, CLIPCAPS));
569 DCHECK(GetDeviceCaps(context_, RASTERCAPS) & RC_STRETCHDIB);
570 DCHECK(GetDeviceCaps(context_, RASTERCAPS) & RC_BITMAP64);
571 // Some printers don't advertise these.
572 // DCHECK(GetDeviceCaps(context_, RASTERCAPS) & RC_SCALING);
573 // DCHECK(GetDeviceCaps(context_, SHADEBLENDCAPS) & SB_CONST_ALPHA);
574 // DCHECK(GetDeviceCaps(context_, SHADEBLENDCAPS) & SB_PIXEL_ALPHA);
576 // StretchDIBits() support is needed for printing.
577 if (!(GetDeviceCaps(context_, RASTERCAPS) & RC_STRETCHDIB) ||
578 !(GetDeviceCaps(context_, RASTERCAPS) & RC_BITMAP64)) {
579 NOTREACHED();
580 ResetSettings();
581 return false;
584 DCHECK(!in_print_job_);
585 DCHECK(context_);
586 PageRanges ranges_vector;
587 if (!selection_only) {
588 // Convert the PRINTPAGERANGE array to a PrintSettings::PageRanges vector.
589 ranges_vector.reserve(number_ranges);
590 for (int i = 0; i < number_ranges; ++i) {
591 PageRange range;
592 // Transfer from 1-based to 0-based.
593 range.from = ranges[i].nFromPage - 1;
594 range.to = ranges[i].nToPage - 1;
595 ranges_vector.push_back(range);
599 PrintSettingsInitializerWin::InitPrintSettings(context_,
600 dev_mode,
601 ranges_vector,
602 new_device_name,
603 selection_only,
604 &settings_);
606 return true;
609 bool PrintingContextWin::GetPrinterSettings(HANDLE printer,
610 const std::wstring& device_name) {
611 DCHECK(!in_print_job_);
613 UserDefaultDevMode user_settings;
615 if (!user_settings.Init(printer) ||
616 !AllocateContext(device_name, user_settings.get(), &context_)) {
617 ResetSettings();
618 return false;
621 return InitializeSettings(*user_settings.get(), device_name, NULL, 0, false);
624 // static
625 bool PrintingContextWin::AllocateContext(const std::wstring& device_name,
626 const DEVMODE* dev_mode,
627 gfx::NativeDrawingContext* context) {
628 *context = CreateDC(L"WINSPOOL", device_name.c_str(), NULL, dev_mode);
629 DCHECK(*context);
630 return *context != NULL;
633 PrintingContext::Result PrintingContextWin::ParseDialogResultEx(
634 const PRINTDLGEX& dialog_options) {
635 // If the user clicked OK or Apply then Cancel, but not only Cancel.
636 if (dialog_options.dwResultAction != PD_RESULT_CANCEL) {
637 // Start fresh.
638 ResetSettings();
640 DEVMODE* dev_mode = NULL;
641 if (dialog_options.hDevMode) {
642 dev_mode =
643 reinterpret_cast<DEVMODE*>(GlobalLock(dialog_options.hDevMode));
644 DCHECK(dev_mode);
647 std::wstring device_name;
648 if (dialog_options.hDevNames) {
649 DEVNAMES* dev_names =
650 reinterpret_cast<DEVNAMES*>(GlobalLock(dialog_options.hDevNames));
651 DCHECK(dev_names);
652 if (dev_names) {
653 device_name =
654 reinterpret_cast<const wchar_t*>(
655 reinterpret_cast<const wchar_t*>(dev_names) +
656 dev_names->wDeviceOffset);
657 GlobalUnlock(dialog_options.hDevNames);
661 bool success = false;
662 if (dev_mode && !device_name.empty()) {
663 context_ = dialog_options.hDC;
664 PRINTPAGERANGE* page_ranges = NULL;
665 DWORD num_page_ranges = 0;
666 bool print_selection_only = false;
667 if (dialog_options.Flags & PD_PAGENUMS) {
668 page_ranges = dialog_options.lpPageRanges;
669 num_page_ranges = dialog_options.nPageRanges;
671 if (dialog_options.Flags & PD_SELECTION) {
672 print_selection_only = true;
674 success = InitializeSettings(*dev_mode,
675 device_name,
676 page_ranges,
677 num_page_ranges,
678 print_selection_only);
681 if (!success && dialog_options.hDC) {
682 DeleteDC(dialog_options.hDC);
683 context_ = NULL;
686 if (dev_mode) {
687 GlobalUnlock(dialog_options.hDevMode);
689 } else {
690 if (dialog_options.hDC) {
691 DeleteDC(dialog_options.hDC);
695 if (dialog_options.hDevMode != NULL)
696 GlobalFree(dialog_options.hDevMode);
697 if (dialog_options.hDevNames != NULL)
698 GlobalFree(dialog_options.hDevNames);
700 switch (dialog_options.dwResultAction) {
701 case PD_RESULT_PRINT:
702 return context_ ? OK : FAILED;
703 case PD_RESULT_APPLY:
704 return context_ ? CANCEL : FAILED;
705 case PD_RESULT_CANCEL:
706 return CANCEL;
707 default:
708 return FAILED;
712 PrintingContext::Result PrintingContextWin::ParseDialogResult(
713 const PRINTDLG& dialog_options) {
714 // If the user clicked OK or Apply then Cancel, but not only Cancel.
715 // Start fresh.
716 ResetSettings();
718 DEVMODE* dev_mode = NULL;
719 if (dialog_options.hDevMode) {
720 dev_mode =
721 reinterpret_cast<DEVMODE*>(GlobalLock(dialog_options.hDevMode));
722 DCHECK(dev_mode);
725 std::wstring device_name;
726 if (dialog_options.hDevNames) {
727 DEVNAMES* dev_names =
728 reinterpret_cast<DEVNAMES*>(GlobalLock(dialog_options.hDevNames));
729 DCHECK(dev_names);
730 if (dev_names) {
731 device_name =
732 reinterpret_cast<const wchar_t*>(
733 reinterpret_cast<const wchar_t*>(dev_names) +
734 dev_names->wDeviceOffset);
735 GlobalUnlock(dialog_options.hDevNames);
739 bool success = false;
740 if (dev_mode && !device_name.empty()) {
741 context_ = dialog_options.hDC;
742 success = InitializeSettings(*dev_mode, device_name, NULL, 0, false);
745 if (!success && dialog_options.hDC) {
746 DeleteDC(dialog_options.hDC);
747 context_ = NULL;
750 if (dev_mode) {
751 GlobalUnlock(dialog_options.hDevMode);
754 if (dialog_options.hDevMode != NULL)
755 GlobalFree(dialog_options.hDevMode);
756 if (dialog_options.hDevNames != NULL)
757 GlobalFree(dialog_options.hDevNames);
759 return context_ ? OK : FAILED;
762 } // namespace printing