Enable chrome with aura for tizen
[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/bind.h"
14 #include "base/check.h"
15 #include "base/check_op.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   if (bytes_needed) {
137     DCHECK_GE(bytes_needed, count_returned * sizeof(PRINTER_INFO_2));
138     std::vector<BYTE> printer_info_buffer(bytes_needed);
139     BOOL ret = ::EnumPrinters(PRINTER_ENUM_LOCAL | PRINTER_ENUM_CONNECTIONS,
140                               nullptr, 2, printer_info_buffer.data(),
141                               bytes_needed, &bytes_needed, &count_returned);
142     if (ret && count_returned) {  // have printers
143       // Open the first successfully found printer.
144       const PRINTER_INFO_2* info_2 =
145           reinterpret_cast<PRINTER_INFO_2*>(printer_info_buffer.data());
146       const PRINTER_INFO_2* info_2_end = info_2 + count_returned;
147       for (; info_2 < info_2_end; ++info_2) {
148         ScopedPrinterHandle printer;
149         if (!printer.OpenPrinterWithName(info_2->pPrinterName))
150           continue;
151         std::unique_ptr<DEVMODE, base::FreeDeleter> dev_mode =
152             CreateDevMode(printer.Get(), nullptr);
153         if (InitializeSettings(info_2->pPrinterName, dev_mode.get()) ==
154             mojom::ResultCode::kSuccess) {
155           return mojom::ResultCode::kSuccess;
156         }
157       }
158       if (context_)
159         return mojom::ResultCode::kSuccess;
160     }
161   }
162
163   return OnError();
164 }
165
166 gfx::Size PrintingContextWin::GetPdfPaperSizeDeviceUnits() {
167   // Default fallback to Letter size.
168   gfx::SizeF paper_size(kLetterWidthInch, kLetterHeightInch);
169
170   // Get settings from locale. Paper type buffer length is at most 4.
171   const int paper_type_buffer_len = 4;
172   wchar_t paper_type_buffer[paper_type_buffer_len] = {0};
173   GetLocaleInfo(LOCALE_USER_DEFAULT, LOCALE_IPAPERSIZE, paper_type_buffer,
174                 paper_type_buffer_len);
175   if (wcslen(paper_type_buffer)) {  // The call succeeded.
176     int paper_code = _wtoi(paper_type_buffer);
177     switch (paper_code) {
178       case DMPAPER_LEGAL:
179         paper_size.SetSize(kLegalWidthInch, kLegalHeightInch);
180         break;
181       case DMPAPER_A4:
182         paper_size.SetSize(kA4WidthInch, kA4HeightInch);
183         break;
184       case DMPAPER_A3:
185         paper_size.SetSize(kA3WidthInch, kA3HeightInch);
186         break;
187       default:  // DMPAPER_LETTER is used for default fallback.
188         break;
189     }
190   }
191   return gfx::Size(paper_size.width() * settings_->device_units_per_inch(),
192                    paper_size.height() * settings_->device_units_per_inch());
193 }
194
195 mojom::ResultCode PrintingContextWin::UpdatePrinterSettings(
196     const PrinterSettings& printer_settings) {
197   DCHECK(!in_print_job_);
198
199   ScopedPrinterHandle printer;
200   if (!printer.OpenPrinterWithName(base::as_wcstr(settings_->device_name())))
201     return OnError();
202
203   // Make printer changes local to Chrome.
204   // See MSDN documentation regarding DocumentProperties.
205   std::unique_ptr<DEVMODE, base::FreeDeleter> scoped_dev_mode =
206       CreateDevModeWithColor(printer.Get(),
207                              base::UTF16ToWide(settings_->device_name()),
208                              settings_->color() != mojom::ColorModel::kGray);
209   if (!scoped_dev_mode)
210     return OnError();
211
212   {
213     DEVMODE* dev_mode = scoped_dev_mode.get();
214     dev_mode->dmCopies = std::max(settings_->copies(), 1);
215     if (dev_mode->dmCopies > 1) {  // do not change unless multiple copies
216       dev_mode->dmFields |= DM_COPIES;
217       dev_mode->dmCollate =
218           settings_->collate() ? DMCOLLATE_TRUE : DMCOLLATE_FALSE;
219     }
220
221     switch (settings_->duplex_mode()) {
222       case mojom::DuplexMode::kLongEdge:
223         dev_mode->dmFields |= DM_DUPLEX;
224         dev_mode->dmDuplex = DMDUP_VERTICAL;
225         break;
226       case mojom::DuplexMode::kShortEdge:
227         dev_mode->dmFields |= DM_DUPLEX;
228         dev_mode->dmDuplex = DMDUP_HORIZONTAL;
229         break;
230       case mojom::DuplexMode::kSimplex:
231         dev_mode->dmFields |= DM_DUPLEX;
232         dev_mode->dmDuplex = DMDUP_SIMPLEX;
233         break;
234       default:  // kUnknownDuplexMode
235         break;
236     }
237
238     dev_mode->dmFields |= DM_ORIENTATION;
239     dev_mode->dmOrientation =
240         settings_->landscape() ? DMORIENT_LANDSCAPE : DMORIENT_PORTRAIT;
241
242     if (settings_->dpi_horizontal() > 0) {
243       dev_mode->dmPrintQuality = settings_->dpi_horizontal();
244       dev_mode->dmFields |= DM_PRINTQUALITY;
245     }
246     if (settings_->dpi_vertical() > 0) {
247       dev_mode->dmYResolution = settings_->dpi_vertical();
248       dev_mode->dmFields |= DM_YRESOLUTION;
249     }
250
251     const PrintSettings::RequestedMedia& requested_media =
252         settings_->requested_media();
253     unsigned id = 0;
254     // If the paper size is a custom user size, setting by ID may not work.
255     if (base::StringToUint(requested_media.vendor_id, &id) && id &&
256         id < DMPAPER_USER) {
257       dev_mode->dmFields |= DM_PAPERSIZE;
258       dev_mode->dmPaperSize = static_cast<short>(id);
259     } else if (!requested_media.size_microns.IsEmpty()) {
260       static constexpr int kFromUm = 100;  // Windows uses 0.1mm.
261       dev_mode->dmFields |= DM_PAPERWIDTH | DM_PAPERLENGTH;
262       dev_mode->dmPaperWidth = requested_media.size_microns.width() / kFromUm;
263       dev_mode->dmPaperLength = requested_media.size_microns.height() / kFromUm;
264     }
265   }
266
267   // Update data using DocumentProperties.
268   if (printer_settings.show_system_dialog) {
269     mojom::ResultCode result = mojom::ResultCode::kFailed;
270     AskUserForSettings(printer_settings.page_count, /*has_selection=*/false,
271                        /*is_scripted=*/false,
272                        base::BindOnce(&AssignResult, &result));
273     return result;
274   }
275   // Set printer then refresh printer settings.
276   scoped_dev_mode = CreateDevMode(printer.Get(), scoped_dev_mode.get());
277   if (!scoped_dev_mode)
278     return OnError();
279
280   // Since CreateDevMode() doesn't honor color settings through the GDI call
281   // to DocumentProperties(), ensure the requested values persist here.
282   scoped_dev_mode->dmFields |= DM_COLOR;
283   scoped_dev_mode->dmColor = settings_->color() != mojom::ColorModel::kGray
284                                  ? DMCOLOR_COLOR
285                                  : DMCOLOR_MONOCHROME;
286
287   return InitializeSettings(base::UTF16ToWide(settings_->device_name()),
288                             scoped_dev_mode.get());
289 }
290
291 mojom::ResultCode PrintingContextWin::InitWithSettingsForTest(
292     std::unique_ptr<PrintSettings> settings) {
293   DCHECK(!in_print_job_);
294
295   settings_ = std::move(settings);
296
297   // TODO(maruel): settings_.ToDEVMODE()
298   ScopedPrinterHandle printer;
299   if (!printer.OpenPrinterWithName(base::as_wcstr(settings_->device_name()))) {
300     return logging::GetLastSystemErrorCode() == ERROR_ACCESS_DENIED
301                ? mojom::ResultCode::kAccessDenied
302                : mojom::ResultCode::kFailed;
303   }
304
305   std::unique_ptr<DEVMODE, base::FreeDeleter> dev_mode =
306       CreateDevMode(printer.Get(), nullptr);
307
308   return InitializeSettings(base::UTF16ToWide(settings_->device_name()),
309                             dev_mode.get());
310 }
311
312 mojom::ResultCode PrintingContextWin::NewDocument(
313     const std::u16string& document_name) {
314   DCHECK(!in_print_job_);
315   if (!context_ && !skip_system_calls())
316     return OnError();
317
318   // Set the flag used by the AbortPrintJob dialog procedure.
319   abort_printing_ = false;
320
321   in_print_job_ = true;
322
323   if (skip_system_calls())
324     return mojom::ResultCode::kSuccess;
325
326   if (base::FeatureList::IsEnabled(printing::features::kUseXpsForPrinting)) {
327     // This is all the new document context needed when using XPS.
328     return mojom::ResultCode::kSuccess;
329   }
330
331   // Need more context setup when using GDI.
332
333   // Register the application's AbortProc function with GDI.
334   if (SP_ERROR == SetAbortProc(context_, &AbortProc))
335     return OnError();
336
337   DCHECK(SimplifyDocumentTitle(document_name) == document_name);
338   DOCINFO di = {sizeof(DOCINFO)};
339   di.lpszDocName = base::as_wcstr(document_name);
340
341   // Is there a debug dump directory specified? If so, force to print to a file.
342   if (PrintedDocument::HasDebugDumpPath()) {
343     base::FilePath debug_dump_path = PrintedDocument::CreateDebugDumpPath(
344         document_name, FILE_PATH_LITERAL(".prn"));
345     if (!debug_dump_path.empty())
346       di.lpszOutput = debug_dump_path.value().c_str();
347   }
348
349   // No message loop running in unit tests.
350   DCHECK(!base::CurrentThread::Get() ||
351          !base::CurrentThread::Get()->NestableTasksAllowed());
352
353   // Begin a print job by calling the StartDoc function.
354   // NOTE: StartDoc() starts a message loop. That causes a lot of problems with
355   // IPC. Make sure recursive task processing is disabled.
356   if (StartDoc(context_, &di) <= 0)
357     return OnError();
358
359   return mojom::ResultCode::kSuccess;
360 }
361
362 mojom::ResultCode PrintingContextWin::RenderPage(const PrintedPage& page,
363                                                  const PageSetup& page_setup) {
364   if (abort_printing_)
365     return mojom::ResultCode::kCanceled;
366   DCHECK(context_);
367   DCHECK(in_print_job_);
368
369   gfx::Rect content_area = GetCenteredPageContentRect(
370       page_setup.physical_size(), page.page_size(), page.page_content_rect());
371
372   // Save the state to make sure the context this function call does not modify
373   // the device context.
374   ScopedSavedState saved_state(context_);
375   skia::InitializeDC(context_);
376   {
377     // Save the state (again) to apply the necessary world transformation.
378     ScopedSavedState saved_state_inner(context_);
379
380     // Setup the matrix to translate and scale to the right place. Take in
381     // account the actual shrinking factor.
382     // Note that the printing output is relative to printable area of the page.
383     // That is 0,0 is offset by PHYSICALOFFSETX/Y from the page.
384     SimpleModifyWorldTransform(
385         context_, content_area.x() - page_setup.printable_area().x(),
386         content_area.y() - page_setup.printable_area().y(),
387         page.shrink_factor());
388
389     if (::StartPage(context_) <= 0)
390       return mojom::ResultCode::kFailed;
391     bool played_back = page.metafile()->SafePlayback(context_);
392     DCHECK(played_back);
393     if (::EndPage(context_) <= 0)
394       return mojom::ResultCode::kFailed;
395   }
396
397   return mojom::ResultCode::kSuccess;
398 }
399
400 mojom::ResultCode PrintingContextWin::PrintDocument(
401     const MetafilePlayer& metafile,
402     const PrintSettings& settings,
403     uint32_t num_pages) {
404   // TODO(crbug.com/1008222)
405   NOTIMPLEMENTED();
406   return mojom::ResultCode::kFailed;
407 }
408
409 mojom::ResultCode PrintingContextWin::DocumentDone() {
410   if (abort_printing_)
411     return mojom::ResultCode::kCanceled;
412   DCHECK(in_print_job_);
413   DCHECK(context_);
414
415   // Inform the driver that document has ended.
416   if (EndDoc(context_) <= 0)
417     return OnError();
418
419   ResetSettings();
420   return mojom::ResultCode::kSuccess;
421 }
422
423 void PrintingContextWin::Cancel() {
424   abort_printing_ = true;
425   in_print_job_ = false;
426   if (context_)
427     CancelDC(context_);
428 }
429
430 void PrintingContextWin::ReleaseContext() {
431   if (context_) {
432     DeleteDC(context_);
433     context_ = nullptr;
434   }
435 }
436
437 printing::NativeDrawingContext PrintingContextWin::context() const {
438   return context_;
439 }
440
441 // static
442 BOOL PrintingContextWin::AbortProc(HDC hdc, int nCode) {
443   if (nCode) {
444     // TODO(maruel):  Need a way to find the right instance to set. Should
445     // leverage PrintJobManager here?
446     // abort_printing_ = true;
447   }
448   return true;
449 }
450
451 mojom::ResultCode PrintingContextWin::InitializeSettings(
452     const std::wstring& device_name,
453     DEVMODE* dev_mode) {
454   if (!dev_mode)
455     return OnError();
456
457   ReleaseContext();
458   context_ = CreateDC(L"WINSPOOL", device_name.c_str(), nullptr, dev_mode);
459   if (!context_)
460     return OnError();
461
462   skia::InitializeDC(context_);
463
464   DCHECK(!in_print_job_);
465   settings_->set_device_name(base::WideToUTF16(device_name));
466   PrintSettingsInitializerWin::InitPrintSettings(context_, *dev_mode,
467                                                  settings_.get());
468
469   return mojom::ResultCode::kSuccess;
470 }
471
472 mojom::ResultCode PrintingContextWin::OnError() {
473   mojom::ResultCode result;
474   if (abort_printing_) {
475     result = mojom::ResultCode::kCanceled;
476   } else {
477     result = logging::GetLastSystemErrorCode() == ERROR_ACCESS_DENIED
478                  ? mojom::ResultCode::kAccessDenied
479                  : mojom::ResultCode::kFailed;
480   }
481   ResetSettings();
482   return result;
483 }
484
485 HWND PrintingContextWin::GetRootWindow(gfx::NativeView view) {
486   HWND window = nullptr;
487   if (view && view->GetHost())
488     window = view->GetHost()->GetAcceleratedWidget();
489   if (!window) {
490     // TODO(maruel):  b/1214347 Get the right browser window instead.
491     return GetDesktopWindow();
492   }
493   return window;
494 }
495
496 }  // namespace printing