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/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"
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);
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))
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;
159 return mojom::ResultCode::kSuccess;
166 gfx::Size PrintingContextWin::GetPdfPaperSizeDeviceUnits() {
167 // Default fallback to Letter size.
168 gfx::SizeF paper_size(kLetterWidthInch, kLetterHeightInch);
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) {
179 paper_size.SetSize(kLegalWidthInch, kLegalHeightInch);
182 paper_size.SetSize(kA4WidthInch, kA4HeightInch);
185 paper_size.SetSize(kA3WidthInch, kA3HeightInch);
187 default: // DMPAPER_LETTER is used for default fallback.
191 return gfx::Size(paper_size.width() * settings_->device_units_per_inch(),
192 paper_size.height() * settings_->device_units_per_inch());
195 mojom::ResultCode PrintingContextWin::UpdatePrinterSettings(
196 const PrinterSettings& printer_settings) {
197 DCHECK(!in_print_job_);
199 ScopedPrinterHandle printer;
200 if (!printer.OpenPrinterWithName(base::as_wcstr(settings_->device_name())))
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)
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;
221 switch (settings_->duplex_mode()) {
222 case mojom::DuplexMode::kLongEdge:
223 dev_mode->dmFields |= DM_DUPLEX;
224 dev_mode->dmDuplex = DMDUP_VERTICAL;
226 case mojom::DuplexMode::kShortEdge:
227 dev_mode->dmFields |= DM_DUPLEX;
228 dev_mode->dmDuplex = DMDUP_HORIZONTAL;
230 case mojom::DuplexMode::kSimplex:
231 dev_mode->dmFields |= DM_DUPLEX;
232 dev_mode->dmDuplex = DMDUP_SIMPLEX;
234 default: // kUnknownDuplexMode
238 dev_mode->dmFields |= DM_ORIENTATION;
239 dev_mode->dmOrientation =
240 settings_->landscape() ? DMORIENT_LANDSCAPE : DMORIENT_PORTRAIT;
242 if (settings_->dpi_horizontal() > 0) {
243 dev_mode->dmPrintQuality = settings_->dpi_horizontal();
244 dev_mode->dmFields |= DM_PRINTQUALITY;
246 if (settings_->dpi_vertical() > 0) {
247 dev_mode->dmYResolution = settings_->dpi_vertical();
248 dev_mode->dmFields |= DM_YRESOLUTION;
251 const PrintSettings::RequestedMedia& requested_media =
252 settings_->requested_media();
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 &&
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;
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));
275 // Set printer then refresh printer settings.
276 scoped_dev_mode = CreateDevMode(printer.Get(), scoped_dev_mode.get());
277 if (!scoped_dev_mode)
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
285 : DMCOLOR_MONOCHROME;
287 return InitializeSettings(base::UTF16ToWide(settings_->device_name()),
288 scoped_dev_mode.get());
291 mojom::ResultCode PrintingContextWin::InitWithSettingsForTest(
292 std::unique_ptr<PrintSettings> settings) {
293 DCHECK(!in_print_job_);
295 settings_ = std::move(settings);
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;
305 std::unique_ptr<DEVMODE, base::FreeDeleter> dev_mode =
306 CreateDevMode(printer.Get(), nullptr);
308 return InitializeSettings(base::UTF16ToWide(settings_->device_name()),
312 mojom::ResultCode PrintingContextWin::NewDocument(
313 const std::u16string& document_name) {
314 DCHECK(!in_print_job_);
315 if (!context_ && !skip_system_calls())
318 // Set the flag used by the AbortPrintJob dialog procedure.
319 abort_printing_ = false;
321 in_print_job_ = true;
323 if (skip_system_calls())
324 return mojom::ResultCode::kSuccess;
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;
331 // Need more context setup when using GDI.
333 // Register the application's AbortProc function with GDI.
334 if (SP_ERROR == SetAbortProc(context_, &AbortProc))
337 DCHECK(SimplifyDocumentTitle(document_name) == document_name);
338 DOCINFO di = {sizeof(DOCINFO)};
339 di.lpszDocName = base::as_wcstr(document_name);
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();
349 // No message loop running in unit tests.
350 DCHECK(!base::CurrentThread::Get() ||
351 !base::CurrentThread::Get()->NestableTasksAllowed());
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)
359 return mojom::ResultCode::kSuccess;
362 mojom::ResultCode PrintingContextWin::RenderPage(const PrintedPage& page,
363 const PageSetup& page_setup) {
365 return mojom::ResultCode::kCanceled;
367 DCHECK(in_print_job_);
369 gfx::Rect content_area = GetCenteredPageContentRect(
370 page_setup.physical_size(), page.page_size(), page.page_content_rect());
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_);
377 // Save the state (again) to apply the necessary world transformation.
378 ScopedSavedState saved_state_inner(context_);
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());
389 if (::StartPage(context_) <= 0)
390 return mojom::ResultCode::kFailed;
391 bool played_back = page.metafile()->SafePlayback(context_);
393 if (::EndPage(context_) <= 0)
394 return mojom::ResultCode::kFailed;
397 return mojom::ResultCode::kSuccess;
400 mojom::ResultCode PrintingContextWin::PrintDocument(
401 const MetafilePlayer& metafile,
402 const PrintSettings& settings,
403 uint32_t num_pages) {
404 // TODO(crbug.com/1008222)
406 return mojom::ResultCode::kFailed;
409 mojom::ResultCode PrintingContextWin::DocumentDone() {
411 return mojom::ResultCode::kCanceled;
412 DCHECK(in_print_job_);
415 // Inform the driver that document has ended.
416 if (EndDoc(context_) <= 0)
420 return mojom::ResultCode::kSuccess;
423 void PrintingContextWin::Cancel() {
424 abort_printing_ = true;
425 in_print_job_ = false;
430 void PrintingContextWin::ReleaseContext() {
437 printing::NativeDrawingContext PrintingContextWin::context() const {
442 BOOL PrintingContextWin::AbortProc(HDC hdc, int nCode) {
444 // TODO(maruel): Need a way to find the right instance to set. Should
445 // leverage PrintJobManager here?
446 // abort_printing_ = true;
451 mojom::ResultCode PrintingContextWin::InitializeSettings(
452 const std::wstring& device_name,
458 context_ = CreateDC(L"WINSPOOL", device_name.c_str(), nullptr, dev_mode);
462 skia::InitializeDC(context_);
464 DCHECK(!in_print_job_);
465 settings_->set_device_name(base::WideToUTF16(device_name));
466 PrintSettingsInitializerWin::InitPrintSettings(context_, *dev_mode,
469 return mojom::ResultCode::kSuccess;
472 mojom::ResultCode PrintingContextWin::OnError() {
473 mojom::ResultCode result;
474 if (abort_printing_) {
475 result = mojom::ResultCode::kCanceled;
477 result = logging::GetLastSystemErrorCode() == ERROR_ACCESS_DENIED
478 ? mojom::ResultCode::kAccessDenied
479 : mojom::ResultCode::kFailed;
485 HWND PrintingContextWin::GetRootWindow(gfx::NativeView view) {
486 HWND window = nullptr;
487 if (view && view->GetHost())
488 window = view->GetHost()->GetAcceleratedWidget();
490 // TODO(maruel): b/1214347 Get the right browser window instead.
491 return GetDesktopWindow();
496 } // namespace printing