Revert "[M120 Migration]Fix for crash during chrome exit"
[platform/framework/web/chromium-efl.git] / printing / printing_context_win.cc
1 // Copyright 2012 The Chromium Authors
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 #include <utility>
11 #include <vector>
12
13 #include "base/check.h"
14 #include "base/check_op.h"
15 #include "base/functional/bind.h"
16 #include "base/memory/free_deleter.h"
17 #include "base/strings/string_number_conversions.h"
18 #include "base/strings/utf_string_conversions.h"
19 #include "base/task/current_thread.h"
20 #include "printing/backend/print_backend.h"
21 #include "printing/backend/win_helper.h"
22 #include "printing/buildflags/buildflags.h"
23 #include "printing/metafile.h"
24 #include "printing/metafile_skia.h"
25 #include "printing/mojom/print.mojom.h"
26 #include "printing/page_setup.h"
27 #include "printing/print_settings_initializer_win.h"
28 #include "printing/printed_document.h"
29 #include "printing/printed_page_win.h"
30 #include "printing/printing_context_system_dialog_win.h"
31 #include "printing/printing_features.h"
32 #include "printing/printing_utils.h"
33 #include "printing/units.h"
34 #include "skia/ext/skia_utils_win.h"
35 #include "ui/aura/window.h"
36 #include "ui/aura/window_tree_host.h"
37
38 namespace printing {
39
40 namespace {
41
42 // Helper class to ensure that a saved device context state gets restored at end
43 // of scope.
44 class ScopedSavedState {
45  public:
46   ScopedSavedState(HDC context)
47       : context_(context), saved_state_(SaveDC(context)) {
48     DCHECK_NE(saved_state_, 0);
49   }
50   ~ScopedSavedState() {
51     BOOL res = RestoreDC(context_, saved_state_);
52     DCHECK_NE(res, 0);
53   }
54
55  private:
56   HDC context_;
57   int saved_state_;
58 };
59
60 void AssignResult(mojom::ResultCode* out, mojom::ResultCode in) {
61   *out = in;
62 }
63
64 void SimpleModifyWorldTransform(HDC context,
65                                 int offset_x,
66                                 int offset_y,
67                                 float shrink_factor) {
68   XFORM xform = {0};
69   xform.eDx = static_cast<float>(offset_x);
70   xform.eDy = static_cast<float>(offset_y);
71   xform.eM11 = xform.eM22 = 1.f / shrink_factor;
72   BOOL res = ModifyWorldTransform(context, &xform, MWT_LEFTMULTIPLY);
73   DCHECK_NE(res, 0);
74 }
75
76 }  // namespace
77
78 // static
79 std::unique_ptr<PrintingContext> PrintingContext::CreateImpl(
80     Delegate* delegate,
81     bool skip_system_calls) {
82   std::unique_ptr<PrintingContext> context;
83   context = std::make_unique<PrintingContextSystemDialogWin>(delegate);
84 #if BUILDFLAG(ENABLE_OOP_PRINTING)
85   if (skip_system_calls)
86     context->set_skip_system_calls();
87 #endif
88   return context;
89 }
90
91 PrintingContextWin::PrintingContextWin(Delegate* delegate)
92     : PrintingContext(delegate), context_(nullptr) {}
93
94 PrintingContextWin::~PrintingContextWin() {
95   ReleaseContext();
96 }
97
98 void PrintingContextWin::AskUserForSettings(int max_pages,
99                                             bool has_selection,
100                                             bool is_scripted,
101                                             PrintSettingsCallback callback) {
102   NOTIMPLEMENTED();
103 }
104
105 mojom::ResultCode PrintingContextWin::UseDefaultSettings() {
106   DCHECK(!in_print_job_);
107
108   scoped_refptr<PrintBackend> backend =
109       PrintBackend::CreateInstance(delegate_->GetAppLocale());
110   std::string default_printer_name;
111   mojom::ResultCode result =
112       backend->GetDefaultPrinterName(default_printer_name);
113   if (result != mojom::ResultCode::kSuccess)
114     return result;
115
116   std::wstring default_printer = base::UTF8ToWide(default_printer_name);
117   if (!default_printer.empty()) {
118     ScopedPrinterHandle printer;
119     if (printer.OpenPrinterWithName(default_printer.c_str())) {
120       std::unique_ptr<DEVMODE, base::FreeDeleter> dev_mode =
121           CreateDevMode(printer.Get(), nullptr);
122       if (InitializeSettings(default_printer, dev_mode.get()) ==
123           mojom::ResultCode::kSuccess) {
124         return mojom::ResultCode::kSuccess;
125       }
126     }
127   }
128
129   ReleaseContext();
130
131   // No default printer configured, do we have any printers at all?
132   DWORD bytes_needed = 0;
133   DWORD count_returned = 0;
134   (void)::EnumPrinters(PRINTER_ENUM_LOCAL | PRINTER_ENUM_CONNECTIONS, nullptr,
135                        2, nullptr, 0, &bytes_needed, &count_returned);
136   logging::SystemErrorCode code = logging::GetLastSystemErrorCode();
137   if (code == ERROR_SUCCESS) {
138     // If EnumPrinters() succeeded, that means there are no printer drivers
139     // installed because 0 bytes was sufficient.
140     DCHECK_EQ(bytes_needed, 0u);
141     VLOG(1) << "Found no printers";
142     return mojom::ResultCode::kSuccess;
143   }
144
145   if (code != ERROR_INSUFFICIENT_BUFFER) {
146     LOG(ERROR) << "Error enumerating printers: "
147                << logging::SystemErrorCodeToString(code);
148     return GetResultCodeFromSystemErrorCode(code);
149   }
150
151   DCHECK_GE(bytes_needed, count_returned * sizeof(PRINTER_INFO_2));
152   std::vector<BYTE> printer_info_buffer(bytes_needed);
153   BOOL ret = ::EnumPrinters(PRINTER_ENUM_LOCAL | PRINTER_ENUM_CONNECTIONS,
154                             nullptr, 2, printer_info_buffer.data(),
155                             bytes_needed, &bytes_needed, &count_returned);
156   if (ret && count_returned) {  // have printers
157     // Open the first successfully found printer.
158     const PRINTER_INFO_2* info_2 =
159         reinterpret_cast<PRINTER_INFO_2*>(printer_info_buffer.data());
160     const PRINTER_INFO_2* info_2_end = info_2 + count_returned;
161     for (; info_2 < info_2_end; ++info_2) {
162       ScopedPrinterHandle printer;
163       if (!printer.OpenPrinterWithName(info_2->pPrinterName)) {
164         continue;
165       }
166       std::unique_ptr<DEVMODE, base::FreeDeleter> dev_mode =
167           CreateDevMode(printer.Get(), nullptr);
168       if (InitializeSettings(info_2->pPrinterName, dev_mode.get()) ==
169           mojom::ResultCode::kSuccess) {
170         return mojom::ResultCode::kSuccess;
171       }
172     }
173     if (context_) {
174       return mojom::ResultCode::kSuccess;
175     }
176   }
177
178   return OnError();
179 }
180
181 gfx::Size PrintingContextWin::GetPdfPaperSizeDeviceUnits() {
182   // Default fallback to Letter size.
183   gfx::SizeF paper_size(kLetterWidthInch, kLetterHeightInch);
184
185   // Get settings from locale. Paper type buffer length is at most 4.
186   const int paper_type_buffer_len = 4;
187   wchar_t paper_type_buffer[paper_type_buffer_len] = {0};
188   GetLocaleInfo(LOCALE_USER_DEFAULT, LOCALE_IPAPERSIZE, paper_type_buffer,
189                 paper_type_buffer_len);
190   if (wcslen(paper_type_buffer)) {  // The call succeeded.
191     int paper_code = _wtoi(paper_type_buffer);
192     switch (paper_code) {
193       case DMPAPER_LEGAL:
194         paper_size.SetSize(kLegalWidthInch, kLegalHeightInch);
195         break;
196       case DMPAPER_A4:
197         paper_size.SetSize(kA4WidthInch, kA4HeightInch);
198         break;
199       case DMPAPER_A3:
200         paper_size.SetSize(kA3WidthInch, kA3HeightInch);
201         break;
202       default:  // DMPAPER_LETTER is used for default fallback.
203         break;
204     }
205   }
206   return gfx::Size(paper_size.width() * settings_->device_units_per_inch(),
207                    paper_size.height() * settings_->device_units_per_inch());
208 }
209
210 mojom::ResultCode PrintingContextWin::UpdatePrinterSettings(
211     const PrinterSettings& printer_settings) {
212   DCHECK(!in_print_job_);
213
214   ScopedPrinterHandle printer;
215   if (!printer.OpenPrinterWithName(base::as_wcstr(settings_->device_name())))
216     return OnError();
217
218   // Make printer changes local to Chrome.
219   // See MSDN documentation regarding DocumentProperties.
220   std::unique_ptr<DEVMODE, base::FreeDeleter> scoped_dev_mode =
221       CreateDevModeWithColor(printer.Get(),
222                              base::UTF16ToWide(settings_->device_name()),
223                              settings_->color() != mojom::ColorModel::kGray);
224   if (!scoped_dev_mode)
225     return OnError();
226
227   {
228     DEVMODE* dev_mode = scoped_dev_mode.get();
229     dev_mode->dmCopies = std::max(settings_->copies(), 1);
230     if (dev_mode->dmCopies > 1) {  // do not change unless multiple copies
231       dev_mode->dmFields |= DM_COPIES;
232       dev_mode->dmCollate =
233           settings_->collate() ? DMCOLLATE_TRUE : DMCOLLATE_FALSE;
234     }
235
236     switch (settings_->duplex_mode()) {
237       case mojom::DuplexMode::kLongEdge:
238         dev_mode->dmFields |= DM_DUPLEX;
239         dev_mode->dmDuplex = DMDUP_VERTICAL;
240         break;
241       case mojom::DuplexMode::kShortEdge:
242         dev_mode->dmFields |= DM_DUPLEX;
243         dev_mode->dmDuplex = DMDUP_HORIZONTAL;
244         break;
245       case mojom::DuplexMode::kSimplex:
246         dev_mode->dmFields |= DM_DUPLEX;
247         dev_mode->dmDuplex = DMDUP_SIMPLEX;
248         break;
249       default:  // kUnknownDuplexMode
250         break;
251     }
252
253     dev_mode->dmFields |= DM_ORIENTATION;
254     dev_mode->dmOrientation =
255         settings_->landscape() ? DMORIENT_LANDSCAPE : DMORIENT_PORTRAIT;
256
257     if (settings_->dpi_horizontal() > 0) {
258       dev_mode->dmPrintQuality = settings_->dpi_horizontal();
259       dev_mode->dmFields |= DM_PRINTQUALITY;
260     }
261     if (settings_->dpi_vertical() > 0) {
262       dev_mode->dmYResolution = settings_->dpi_vertical();
263       dev_mode->dmFields |= DM_YRESOLUTION;
264     }
265
266     const PrintSettings::RequestedMedia& requested_media =
267         settings_->requested_media();
268     unsigned id = 0;
269     // If the paper size is a custom user size, setting by ID may not work.
270     if (base::StringToUint(requested_media.vendor_id, &id) && id &&
271         id < DMPAPER_USER) {
272       dev_mode->dmFields |= DM_PAPERSIZE;
273       dev_mode->dmPaperSize = static_cast<short>(id);
274     } else if (!requested_media.size_microns.IsEmpty()) {
275       static constexpr int kFromUm = 100;  // Windows uses 0.1mm.
276       dev_mode->dmFields |= DM_PAPERWIDTH | DM_PAPERLENGTH;
277       dev_mode->dmPaperWidth = requested_media.size_microns.width() / kFromUm;
278       dev_mode->dmPaperLength = requested_media.size_microns.height() / kFromUm;
279     }
280   }
281
282   // Update data using DocumentProperties.
283   if (printer_settings.show_system_dialog) {
284     mojom::ResultCode result = mojom::ResultCode::kFailed;
285     AskUserForSettings(printer_settings.page_count, /*has_selection=*/false,
286                        /*is_scripted=*/false,
287                        base::BindOnce(&AssignResult, &result));
288     return result;
289   }
290   // Set printer then refresh printer settings.
291   scoped_dev_mode = CreateDevMode(printer.Get(), scoped_dev_mode.get());
292   if (!scoped_dev_mode)
293     return OnError();
294
295   // Since CreateDevMode() doesn't honor color settings through the GDI call
296   // to DocumentProperties(), ensure the requested values persist here.
297   scoped_dev_mode->dmFields |= DM_COLOR;
298   scoped_dev_mode->dmColor = settings_->color() != mojom::ColorModel::kGray
299                                  ? DMCOLOR_COLOR
300                                  : DMCOLOR_MONOCHROME;
301
302   return InitializeSettings(base::UTF16ToWide(settings_->device_name()),
303                             scoped_dev_mode.get());
304 }
305
306 mojom::ResultCode PrintingContextWin::InitWithSettingsForTest(
307     std::unique_ptr<PrintSettings> settings) {
308   DCHECK(!in_print_job_);
309
310   settings_ = std::move(settings);
311
312   // TODO(maruel): settings_.ToDEVMODE()
313   ScopedPrinterHandle printer;
314   if (!printer.OpenPrinterWithName(base::as_wcstr(settings_->device_name()))) {
315     return logging::GetLastSystemErrorCode() == ERROR_ACCESS_DENIED
316                ? mojom::ResultCode::kAccessDenied
317                : mojom::ResultCode::kFailed;
318   }
319
320   std::unique_ptr<DEVMODE, base::FreeDeleter> dev_mode =
321       CreateDevMode(printer.Get(), nullptr);
322
323   return InitializeSettings(base::UTF16ToWide(settings_->device_name()),
324                             dev_mode.get());
325 }
326
327 mojom::ResultCode PrintingContextWin::NewDocument(
328     const std::u16string& document_name) {
329   DCHECK(!in_print_job_);
330   if (!context_ && !skip_system_calls())
331     return OnError();
332
333   // Set the flag used by the AbortPrintJob dialog procedure.
334   abort_printing_ = false;
335
336   in_print_job_ = true;
337
338   if (skip_system_calls())
339     return mojom::ResultCode::kSuccess;
340
341   if (base::FeatureList::IsEnabled(printing::features::kUseXpsForPrinting)) {
342     // This is all the new document context needed when using XPS.
343     return mojom::ResultCode::kSuccess;
344   }
345
346   // Need more context setup when using GDI.
347
348   // Register the application's AbortProc function with GDI.
349   if (SP_ERROR == SetAbortProc(context_, &AbortProc))
350     return OnError();
351
352   DCHECK(SimplifyDocumentTitle(document_name) == document_name);
353   DOCINFO di = {sizeof(DOCINFO)};
354   di.lpszDocName = base::as_wcstr(document_name);
355
356   // Is there a debug dump directory specified? If so, force to print to a file.
357   if (PrintedDocument::HasDebugDumpPath()) {
358     base::FilePath debug_dump_path = PrintedDocument::CreateDebugDumpPath(
359         document_name, FILE_PATH_LITERAL(".prn"));
360     if (!debug_dump_path.empty())
361       di.lpszOutput = debug_dump_path.value().c_str();
362   }
363
364   // No message loop running in unit tests.
365   DCHECK(
366       !base::CurrentThread::Get() ||
367       !base::CurrentThread::Get()->ApplicationTasksAllowedInNativeNestedLoop());
368
369   // Begin a print job by calling the StartDoc function.
370   // NOTE: StartDoc() starts a message loop. That causes a lot of problems with
371   // IPC. Make sure recursive task processing is disabled.
372   if (StartDoc(context_, &di) <= 0)
373     return OnError();
374
375   return mojom::ResultCode::kSuccess;
376 }
377
378 mojom::ResultCode PrintingContextWin::RenderPage(const PrintedPage& page,
379                                                  const PageSetup& page_setup) {
380   if (abort_printing_)
381     return mojom::ResultCode::kCanceled;
382   DCHECK(context_);
383   DCHECK(in_print_job_);
384
385   gfx::Rect content_area = GetCenteredPageContentRect(
386       page_setup.physical_size(), page.page_size(), page.page_content_rect());
387
388   // Save the state to make sure the context this function call does not modify
389   // the device context.
390   ScopedSavedState saved_state(context_);
391   skia::InitializeDC(context_);
392   {
393     // Save the state (again) to apply the necessary world transformation.
394     ScopedSavedState saved_state_inner(context_);
395
396     // Setup the matrix to translate and scale to the right place. Take in
397     // account the actual shrinking factor.
398     // Note that the printing output is relative to printable area of the page.
399     // That is 0,0 is offset by PHYSICALOFFSETX/Y from the page.
400     SimpleModifyWorldTransform(
401         context_, content_area.x() - page_setup.printable_area().x(),
402         content_area.y() - page_setup.printable_area().y(),
403         page.shrink_factor());
404
405     if (::StartPage(context_) <= 0)
406       return mojom::ResultCode::kFailed;
407     bool played_back = page.metafile()->SafePlayback(context_);
408     DCHECK(played_back);
409     if (::EndPage(context_) <= 0)
410       return mojom::ResultCode::kFailed;
411   }
412
413   return mojom::ResultCode::kSuccess;
414 }
415
416 mojom::ResultCode PrintingContextWin::PrintDocument(
417     const MetafilePlayer& metafile,
418     const PrintSettings& settings,
419     uint32_t num_pages) {
420   // TODO(crbug.com/1008222)
421   NOTIMPLEMENTED();
422   return mojom::ResultCode::kFailed;
423 }
424
425 mojom::ResultCode PrintingContextWin::DocumentDone() {
426   if (abort_printing_)
427     return mojom::ResultCode::kCanceled;
428   DCHECK(in_print_job_);
429   DCHECK(context_);
430
431   // Inform the driver that document has ended.
432   if (EndDoc(context_) <= 0)
433     return OnError();
434
435   ResetSettings();
436   return mojom::ResultCode::kSuccess;
437 }
438
439 void PrintingContextWin::Cancel() {
440   abort_printing_ = true;
441   in_print_job_ = false;
442   if (context_)
443     CancelDC(context_);
444 }
445
446 void PrintingContextWin::ReleaseContext() {
447   if (context_) {
448     DeleteDC(context_);
449     context_ = nullptr;
450   }
451 }
452
453 printing::NativeDrawingContext PrintingContextWin::context() const {
454   return context_;
455 }
456
457 // static
458 BOOL PrintingContextWin::AbortProc(HDC hdc, int nCode) {
459   if (nCode) {
460     // TODO(maruel):  Need a way to find the right instance to set. Should
461     // leverage PrintJobManager here?
462     // abort_printing_ = true;
463   }
464   return true;
465 }
466
467 mojom::ResultCode PrintingContextWin::InitializeSettings(
468     const std::wstring& device_name,
469     DEVMODE* dev_mode) {
470   if (!dev_mode)
471     return OnError();
472
473   ReleaseContext();
474   context_ = CreateDC(L"WINSPOOL", device_name.c_str(), nullptr, dev_mode);
475   if (!context_)
476     return OnError();
477
478   skia::InitializeDC(context_);
479
480   DCHECK(!in_print_job_);
481   settings_->set_device_name(base::WideToUTF16(device_name));
482   PrintSettingsInitializerWin::InitPrintSettings(context_, *dev_mode,
483                                                  settings_.get());
484
485   return mojom::ResultCode::kSuccess;
486 }
487
488 mojom::ResultCode PrintingContextWin::OnError() {
489   mojom::ResultCode result;
490   if (abort_printing_) {
491     result = mojom::ResultCode::kCanceled;
492   } else {
493     switch (logging::GetLastSystemErrorCode()) {
494       case ERROR_ACCESS_DENIED:
495         result = mojom::ResultCode::kAccessDenied;
496         break;
497       case ERROR_CANCELLED:
498         result = mojom::ResultCode::kCanceled;
499         break;
500       default:
501         result = mojom::ResultCode::kFailed;
502         break;
503     }
504   }
505   ResetSettings();
506   return result;
507 }
508
509 HWND PrintingContextWin::GetRootWindow(gfx::NativeView view) {
510   HWND window = nullptr;
511   if (view && view->GetHost())
512     window = view->GetHost()->GetAcceleratedWidget();
513   if (!window) {
514     // TODO(maruel):  b/1214347 Get the right browser window instead.
515     return GetDesktopWindow();
516   }
517   return window;
518 }
519
520 }  // namespace printing