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.
5 #include "printing/printing_context_win.h"
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"
42 // Helper class to ensure that a saved device context state gets restored at end
44 class ScopedSavedState {
46 ScopedSavedState(HDC context)
47 : context_(context), saved_state_(SaveDC(context)) {
48 DCHECK_NE(saved_state_, 0);
51 BOOL res = RestoreDC(context_, saved_state_);
60 void AssignResult(mojom::ResultCode* out, mojom::ResultCode in) {
64 void SimpleModifyWorldTransform(HDC context,
67 float shrink_factor) {
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);
79 std::unique_ptr<PrintingContext> PrintingContext::CreateImpl(
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();
91 PrintingContextWin::PrintingContextWin(Delegate* delegate)
92 : PrintingContext(delegate), context_(nullptr) {}
94 PrintingContextWin::~PrintingContextWin() {
98 void PrintingContextWin::AskUserForSettings(int max_pages,
101 PrintSettingsCallback callback) {
105 mojom::ResultCode PrintingContextWin::UseDefaultSettings() {
106 DCHECK(!in_print_job_);
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)
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;
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;
145 if (code != ERROR_INSUFFICIENT_BUFFER) {
146 LOG(ERROR) << "Error enumerating printers: "
147 << logging::SystemErrorCodeToString(code);
148 return GetResultCodeFromSystemErrorCode(code);
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)) {
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;
174 return mojom::ResultCode::kSuccess;
181 gfx::Size PrintingContextWin::GetPdfPaperSizeDeviceUnits() {
182 // Default fallback to Letter size.
183 gfx::SizeF paper_size(kLetterWidthInch, kLetterHeightInch);
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) {
194 paper_size.SetSize(kLegalWidthInch, kLegalHeightInch);
197 paper_size.SetSize(kA4WidthInch, kA4HeightInch);
200 paper_size.SetSize(kA3WidthInch, kA3HeightInch);
202 default: // DMPAPER_LETTER is used for default fallback.
206 return gfx::Size(paper_size.width() * settings_->device_units_per_inch(),
207 paper_size.height() * settings_->device_units_per_inch());
210 mojom::ResultCode PrintingContextWin::UpdatePrinterSettings(
211 const PrinterSettings& printer_settings) {
212 DCHECK(!in_print_job_);
214 ScopedPrinterHandle printer;
215 if (!printer.OpenPrinterWithName(base::as_wcstr(settings_->device_name())))
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)
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;
236 switch (settings_->duplex_mode()) {
237 case mojom::DuplexMode::kLongEdge:
238 dev_mode->dmFields |= DM_DUPLEX;
239 dev_mode->dmDuplex = DMDUP_VERTICAL;
241 case mojom::DuplexMode::kShortEdge:
242 dev_mode->dmFields |= DM_DUPLEX;
243 dev_mode->dmDuplex = DMDUP_HORIZONTAL;
245 case mojom::DuplexMode::kSimplex:
246 dev_mode->dmFields |= DM_DUPLEX;
247 dev_mode->dmDuplex = DMDUP_SIMPLEX;
249 default: // kUnknownDuplexMode
253 dev_mode->dmFields |= DM_ORIENTATION;
254 dev_mode->dmOrientation =
255 settings_->landscape() ? DMORIENT_LANDSCAPE : DMORIENT_PORTRAIT;
257 if (settings_->dpi_horizontal() > 0) {
258 dev_mode->dmPrintQuality = settings_->dpi_horizontal();
259 dev_mode->dmFields |= DM_PRINTQUALITY;
261 if (settings_->dpi_vertical() > 0) {
262 dev_mode->dmYResolution = settings_->dpi_vertical();
263 dev_mode->dmFields |= DM_YRESOLUTION;
266 const PrintSettings::RequestedMedia& requested_media =
267 settings_->requested_media();
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 &&
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;
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));
290 // Set printer then refresh printer settings.
291 scoped_dev_mode = CreateDevMode(printer.Get(), scoped_dev_mode.get());
292 if (!scoped_dev_mode)
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
300 : DMCOLOR_MONOCHROME;
302 return InitializeSettings(base::UTF16ToWide(settings_->device_name()),
303 scoped_dev_mode.get());
306 mojom::ResultCode PrintingContextWin::InitWithSettingsForTest(
307 std::unique_ptr<PrintSettings> settings) {
308 DCHECK(!in_print_job_);
310 settings_ = std::move(settings);
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;
320 std::unique_ptr<DEVMODE, base::FreeDeleter> dev_mode =
321 CreateDevMode(printer.Get(), nullptr);
323 return InitializeSettings(base::UTF16ToWide(settings_->device_name()),
327 mojom::ResultCode PrintingContextWin::NewDocument(
328 const std::u16string& document_name) {
329 DCHECK(!in_print_job_);
330 if (!context_ && !skip_system_calls())
333 // Set the flag used by the AbortPrintJob dialog procedure.
334 abort_printing_ = false;
336 in_print_job_ = true;
338 if (skip_system_calls())
339 return mojom::ResultCode::kSuccess;
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;
346 // Need more context setup when using GDI.
348 // Register the application's AbortProc function with GDI.
349 if (SP_ERROR == SetAbortProc(context_, &AbortProc))
352 DCHECK(SimplifyDocumentTitle(document_name) == document_name);
353 DOCINFO di = {sizeof(DOCINFO)};
354 di.lpszDocName = base::as_wcstr(document_name);
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();
364 // No message loop running in unit tests.
366 !base::CurrentThread::Get() ||
367 !base::CurrentThread::Get()->ApplicationTasksAllowedInNativeNestedLoop());
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)
375 return mojom::ResultCode::kSuccess;
378 mojom::ResultCode PrintingContextWin::RenderPage(const PrintedPage& page,
379 const PageSetup& page_setup) {
381 return mojom::ResultCode::kCanceled;
383 DCHECK(in_print_job_);
385 gfx::Rect content_area = GetCenteredPageContentRect(
386 page_setup.physical_size(), page.page_size(), page.page_content_rect());
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_);
393 // Save the state (again) to apply the necessary world transformation.
394 ScopedSavedState saved_state_inner(context_);
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());
405 if (::StartPage(context_) <= 0)
406 return mojom::ResultCode::kFailed;
407 bool played_back = page.metafile()->SafePlayback(context_);
409 if (::EndPage(context_) <= 0)
410 return mojom::ResultCode::kFailed;
413 return mojom::ResultCode::kSuccess;
416 mojom::ResultCode PrintingContextWin::PrintDocument(
417 const MetafilePlayer& metafile,
418 const PrintSettings& settings,
419 uint32_t num_pages) {
420 // TODO(crbug.com/1008222)
422 return mojom::ResultCode::kFailed;
425 mojom::ResultCode PrintingContextWin::DocumentDone() {
427 return mojom::ResultCode::kCanceled;
428 DCHECK(in_print_job_);
431 // Inform the driver that document has ended.
432 if (EndDoc(context_) <= 0)
436 return mojom::ResultCode::kSuccess;
439 void PrintingContextWin::Cancel() {
440 abort_printing_ = true;
441 in_print_job_ = false;
446 void PrintingContextWin::ReleaseContext() {
453 printing::NativeDrawingContext PrintingContextWin::context() const {
458 BOOL PrintingContextWin::AbortProc(HDC hdc, int nCode) {
460 // TODO(maruel): Need a way to find the right instance to set. Should
461 // leverage PrintJobManager here?
462 // abort_printing_ = true;
467 mojom::ResultCode PrintingContextWin::InitializeSettings(
468 const std::wstring& device_name,
474 context_ = CreateDC(L"WINSPOOL", device_name.c_str(), nullptr, dev_mode);
478 skia::InitializeDC(context_);
480 DCHECK(!in_print_job_);
481 settings_->set_device_name(base::WideToUTF16(device_name));
482 PrintSettingsInitializerWin::InitPrintSettings(context_, *dev_mode,
485 return mojom::ResultCode::kSuccess;
488 mojom::ResultCode PrintingContextWin::OnError() {
489 mojom::ResultCode result;
490 if (abort_printing_) {
491 result = mojom::ResultCode::kCanceled;
493 switch (logging::GetLastSystemErrorCode()) {
494 case ERROR_ACCESS_DENIED:
495 result = mojom::ResultCode::kAccessDenied;
497 case ERROR_CANCELLED:
498 result = mojom::ResultCode::kCanceled;
501 result = mojom::ResultCode::kFailed;
509 HWND PrintingContextWin::GetRootWindow(gfx::NativeView view) {
510 HWND window = nullptr;
511 if (view && view->GetHost())
512 window = view->GetHost()->GetAcceleratedWidget();
514 // TODO(maruel): b/1214347 Get the right browser window instead.
515 return GetDesktopWindow();
520 } // namespace printing