Remove unused parameter.
[chromium-blink-merge.git] / printing / backend / win_helper.cc
blob914dacb06f71fd0dc3fd8246502b8dd48e6b21b4
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/backend/win_helper.h"
7 #include <algorithm>
9 #include "base/file_version_info.h"
10 #include "base/files/file_path.h"
11 #include "base/logging.h"
12 #include "base/memory/scoped_ptr.h"
13 #include "base/numerics/safe_conversions.h"
14 #include "base/strings/string_util.h"
15 #include "base/strings/stringprintf.h"
16 #include "base/strings/utf_string_conversions.h"
17 #include "base/win/scoped_comptr.h"
18 #include "printing/backend/print_backend.h"
19 #include "printing/backend/print_backend_consts.h"
20 #include "printing/backend/printing_info_win.h"
22 namespace {
24 typedef HRESULT (WINAPI* PTOpenProviderProc)(PCWSTR printer_name,
25 DWORD version,
26 HPTPROVIDER* provider);
28 typedef HRESULT (WINAPI* PTGetPrintCapabilitiesProc)(HPTPROVIDER provider,
29 IStream* print_ticket,
30 IStream* capabilities,
31 BSTR* error_message);
33 typedef HRESULT (WINAPI* PTConvertDevModeToPrintTicketProc)(
34 HPTPROVIDER provider,
35 ULONG devmode_size_in_bytes,
36 PDEVMODE devmode,
37 EPrintTicketScope scope,
38 IStream* print_ticket);
40 typedef HRESULT (WINAPI* PTConvertPrintTicketToDevModeProc)(
41 HPTPROVIDER provider,
42 IStream* print_ticket,
43 EDefaultDevmodeType base_devmode_type,
44 EPrintTicketScope scope,
45 ULONG* devmode_byte_count,
46 PDEVMODE* devmode,
47 BSTR* error_message);
49 typedef HRESULT (WINAPI* PTMergeAndValidatePrintTicketProc)(
50 HPTPROVIDER provider,
51 IStream* base_ticket,
52 IStream* delta_ticket,
53 EPrintTicketScope scope,
54 IStream* result_ticket,
55 BSTR* error_message);
57 typedef HRESULT (WINAPI* PTReleaseMemoryProc)(PVOID buffer);
59 typedef HRESULT (WINAPI* PTCloseProviderProc)(HPTPROVIDER provider);
61 typedef HRESULT (WINAPI* StartXpsPrintJobProc)(
62 const LPCWSTR printer_name,
63 const LPCWSTR job_name,
64 const LPCWSTR output_file_name,
65 HANDLE progress_event,
66 HANDLE completion_event,
67 UINT8* printable_pages_on,
68 UINT32 printable_pages_on_count,
69 IXpsPrintJob** xps_print_job,
70 IXpsPrintJobStream** document_stream,
71 IXpsPrintJobStream** print_ticket_stream);
73 PTOpenProviderProc g_open_provider_proc = NULL;
74 PTGetPrintCapabilitiesProc g_get_print_capabilities_proc = NULL;
75 PTConvertDevModeToPrintTicketProc g_convert_devmode_to_print_ticket_proc = NULL;
76 PTConvertPrintTicketToDevModeProc g_convert_print_ticket_to_devmode_proc = NULL;
77 PTMergeAndValidatePrintTicketProc g_merge_and_validate_print_ticket_proc = NULL;
78 PTReleaseMemoryProc g_release_memory_proc = NULL;
79 PTCloseProviderProc g_close_provider_proc = NULL;
80 StartXpsPrintJobProc g_start_xps_print_job_proc = NULL;
82 HRESULT StreamFromPrintTicket(const std::string& print_ticket,
83 IStream** stream) {
84 DCHECK(stream);
85 HRESULT hr = CreateStreamOnHGlobal(NULL, TRUE, stream);
86 if (FAILED(hr)) {
87 return hr;
89 ULONG bytes_written = 0;
90 (*stream)->Write(print_ticket.c_str(),
91 base::checked_cast<ULONG>(print_ticket.length()),
92 &bytes_written);
93 DCHECK(bytes_written == print_ticket.length());
94 LARGE_INTEGER pos = {0};
95 ULARGE_INTEGER new_pos = {0};
96 (*stream)->Seek(pos, STREAM_SEEK_SET, &new_pos);
97 return S_OK;
100 const char kXpsTicketTemplate[] =
101 "<?xml version='1.0' encoding='UTF-8'?>"
102 "<psf:PrintTicket "
103 "xmlns:psf='"
104 "http://schemas.microsoft.com/windows/2003/08/printing/printschemaframework' "
105 "xmlns:psk="
106 "'http://schemas.microsoft.com/windows/2003/08/printing/printschemakeywords' "
107 "version='1'>"
108 "<psf:Feature name='psk:PageOutputColor'>"
109 "<psf:Option name='psk:%s'>"
110 "</psf:Option>"
111 "</psf:Feature>"
112 "</psf:PrintTicket>";
114 const char kXpsTicketColor[] = "Color";
115 const char kXpsTicketMonochrome[] = "Monochrome";
118 } // namespace
121 namespace printing {
123 bool XPSModule::Init() {
124 static bool initialized = InitImpl();
125 return initialized;
128 bool XPSModule::InitImpl() {
129 HMODULE prntvpt_module = LoadLibrary(L"prntvpt.dll");
130 if (prntvpt_module == NULL)
131 return false;
132 g_open_provider_proc = reinterpret_cast<PTOpenProviderProc>(
133 GetProcAddress(prntvpt_module, "PTOpenProvider"));
134 if (!g_open_provider_proc) {
135 NOTREACHED();
136 return false;
138 g_get_print_capabilities_proc = reinterpret_cast<PTGetPrintCapabilitiesProc>(
139 GetProcAddress(prntvpt_module, "PTGetPrintCapabilities"));
140 if (!g_get_print_capabilities_proc) {
141 NOTREACHED();
142 return false;
144 g_convert_devmode_to_print_ticket_proc =
145 reinterpret_cast<PTConvertDevModeToPrintTicketProc>(
146 GetProcAddress(prntvpt_module, "PTConvertDevModeToPrintTicket"));
147 if (!g_convert_devmode_to_print_ticket_proc) {
148 NOTREACHED();
149 return false;
151 g_convert_print_ticket_to_devmode_proc =
152 reinterpret_cast<PTConvertPrintTicketToDevModeProc>(
153 GetProcAddress(prntvpt_module, "PTConvertPrintTicketToDevMode"));
154 if (!g_convert_print_ticket_to_devmode_proc) {
155 NOTREACHED();
156 return false;
158 g_merge_and_validate_print_ticket_proc =
159 reinterpret_cast<PTMergeAndValidatePrintTicketProc>(
160 GetProcAddress(prntvpt_module, "PTMergeAndValidatePrintTicket"));
161 if (!g_merge_and_validate_print_ticket_proc) {
162 NOTREACHED();
163 return false;
165 g_release_memory_proc =
166 reinterpret_cast<PTReleaseMemoryProc>(
167 GetProcAddress(prntvpt_module, "PTReleaseMemory"));
168 if (!g_release_memory_proc) {
169 NOTREACHED();
170 return false;
172 g_close_provider_proc =
173 reinterpret_cast<PTCloseProviderProc>(
174 GetProcAddress(prntvpt_module, "PTCloseProvider"));
175 if (!g_close_provider_proc) {
176 NOTREACHED();
177 return false;
179 return true;
182 HRESULT XPSModule::OpenProvider(const base::string16& printer_name,
183 DWORD version,
184 HPTPROVIDER* provider) {
185 return g_open_provider_proc(printer_name.c_str(), version, provider);
188 HRESULT XPSModule::GetPrintCapabilities(HPTPROVIDER provider,
189 IStream* print_ticket,
190 IStream* capabilities,
191 BSTR* error_message) {
192 return g_get_print_capabilities_proc(provider,
193 print_ticket,
194 capabilities,
195 error_message);
198 HRESULT XPSModule::ConvertDevModeToPrintTicket(HPTPROVIDER provider,
199 ULONG devmode_size_in_bytes,
200 PDEVMODE devmode,
201 EPrintTicketScope scope,
202 IStream* print_ticket) {
203 return g_convert_devmode_to_print_ticket_proc(provider,
204 devmode_size_in_bytes,
205 devmode,
206 scope,
207 print_ticket);
210 HRESULT XPSModule::ConvertPrintTicketToDevMode(
211 HPTPROVIDER provider,
212 IStream* print_ticket,
213 EDefaultDevmodeType base_devmode_type,
214 EPrintTicketScope scope,
215 ULONG* devmode_byte_count,
216 PDEVMODE* devmode,
217 BSTR* error_message) {
218 return g_convert_print_ticket_to_devmode_proc(provider,
219 print_ticket,
220 base_devmode_type,
221 scope,
222 devmode_byte_count,
223 devmode,
224 error_message);
227 HRESULT XPSModule::MergeAndValidatePrintTicket(HPTPROVIDER provider,
228 IStream* base_ticket,
229 IStream* delta_ticket,
230 EPrintTicketScope scope,
231 IStream* result_ticket,
232 BSTR* error_message) {
233 return g_merge_and_validate_print_ticket_proc(provider,
234 base_ticket,
235 delta_ticket,
236 scope,
237 result_ticket,
238 error_message);
241 HRESULT XPSModule::ReleaseMemory(PVOID buffer) {
242 return g_release_memory_proc(buffer);
245 HRESULT XPSModule::CloseProvider(HPTPROVIDER provider) {
246 return g_close_provider_proc(provider);
249 ScopedXPSInitializer::ScopedXPSInitializer() : initialized_(false) {
250 if (!XPSModule::Init())
251 return;
252 // Calls to XPS APIs typically require the XPS provider to be opened with
253 // PTOpenProvider. PTOpenProvider calls CoInitializeEx with
254 // COINIT_MULTITHREADED. We have seen certain buggy HP printer driver DLLs
255 // that call CoInitializeEx with COINIT_APARTMENTTHREADED in the context of
256 // PTGetPrintCapabilities. This call fails but the printer driver calls
257 // CoUninitialize anyway. This results in the apartment being torn down too
258 // early and the msxml DLL being unloaded which in turn causes code in
259 // unidrvui.dll to have a dangling pointer to an XML document which causes a
260 // crash. To protect ourselves from such drivers we make sure we always have
261 // an extra CoInitialize (calls to CoInitialize/CoUninitialize are
262 // refcounted).
263 HRESULT hr = CoInitializeEx(NULL, COINIT_MULTITHREADED);
264 // If this succeeded we are done because the PTOpenProvider call will provide
265 // the extra refcount on the apartment. If it failed because someone already
266 // called CoInitializeEx with COINIT_APARTMENTTHREADED, we try the other model
267 // to provide the additional refcount (since we don't know which model buggy
268 // printer drivers will use).
269 if (!SUCCEEDED(hr))
270 hr = CoInitializeEx(NULL, COINIT_APARTMENTTHREADED);
271 DCHECK(SUCCEEDED(hr));
272 initialized_ = true;
275 ScopedXPSInitializer::~ScopedXPSInitializer() {
276 if (initialized_)
277 CoUninitialize();
278 initialized_ = false;
281 bool XPSPrintModule::Init() {
282 static bool initialized = InitImpl();
283 return initialized;
286 bool XPSPrintModule::InitImpl() {
287 HMODULE xpsprint_module = LoadLibrary(L"xpsprint.dll");
288 if (xpsprint_module == NULL)
289 return false;
290 g_start_xps_print_job_proc = reinterpret_cast<StartXpsPrintJobProc>(
291 GetProcAddress(xpsprint_module, "StartXpsPrintJob"));
292 if (!g_start_xps_print_job_proc) {
293 NOTREACHED();
294 return false;
296 return true;
299 HRESULT XPSPrintModule::StartXpsPrintJob(
300 const LPCWSTR printer_name,
301 const LPCWSTR job_name,
302 const LPCWSTR output_file_name,
303 HANDLE progress_event,
304 HANDLE completion_event,
305 UINT8* printable_pages_on,
306 UINT32 printable_pages_on_count,
307 IXpsPrintJob** xps_print_job,
308 IXpsPrintJobStream** document_stream,
309 IXpsPrintJobStream** print_ticket_stream) {
310 return g_start_xps_print_job_proc(printer_name,
311 job_name,
312 output_file_name,
313 progress_event,
314 completion_event,
315 printable_pages_on,
316 printable_pages_on_count,
317 xps_print_job,
318 document_stream,
319 print_ticket_stream);
322 bool InitBasicPrinterInfo(HANDLE printer, PrinterBasicInfo* printer_info) {
323 DCHECK(printer);
324 DCHECK(printer_info);
325 if (!printer)
326 return false;
328 PrinterInfo2 info_2;
329 if (!info_2.Init(printer))
330 return false;
332 printer_info->printer_name = base::WideToUTF8(info_2.get()->pPrinterName);
333 if (info_2.get()->pComment) {
334 printer_info->printer_description =
335 base::WideToUTF8(info_2.get()->pComment);
337 if (info_2.get()->pLocation) {
338 printer_info->options[kLocationTagName] =
339 base::WideToUTF8(info_2.get()->pLocation);
341 if (info_2.get()->pDriverName) {
342 printer_info->options[kDriverNameTagName] =
343 base::WideToUTF8(info_2.get()->pDriverName);
345 printer_info->printer_status = info_2.get()->Status;
347 std::string driver_info = GetDriverInfo(printer);
348 if (!driver_info.empty())
349 printer_info->options[kDriverInfoTagName] = driver_info;
350 return true;
353 std::string GetDriverInfo(HANDLE printer) {
354 DCHECK(printer);
355 std::string driver_info;
357 if (!printer)
358 return driver_info;
360 DriverInfo6 info_6;
361 if (!info_6.Init(printer))
362 return driver_info;
364 std::string info[4];
365 if (info_6.get()->pName)
366 info[0] = base::WideToUTF8(info_6.get()->pName);
368 if (info_6.get()->pDriverPath) {
369 scoped_ptr<FileVersionInfo> version_info(
370 FileVersionInfo::CreateFileVersionInfo(
371 base::FilePath(info_6.get()->pDriverPath)));
372 if (version_info.get()) {
373 info[1] = base::WideToUTF8(version_info->file_version());
374 info[2] = base::WideToUTF8(version_info->product_name());
375 info[3] = base::WideToUTF8(version_info->product_version());
379 for (size_t i = 0; i < arraysize(info); ++i) {
380 std::replace(info[i].begin(), info[i].end(), ';', ',');
381 driver_info.append(info[i]);
382 if (i < arraysize(info) - 1)
383 driver_info.append(";");
385 return driver_info;
388 scoped_ptr<DEVMODE, base::FreeDeleter> XpsTicketToDevMode(
389 const base::string16& printer_name,
390 const std::string& print_ticket) {
391 scoped_ptr<DEVMODE, base::FreeDeleter> dev_mode;
392 printing::ScopedXPSInitializer xps_initializer;
393 if (!xps_initializer.initialized()) {
394 // TODO(sanjeevr): Handle legacy proxy case (with no prntvpt.dll)
395 return dev_mode.Pass();
398 printing::ScopedPrinterHandle printer;
399 if (!printer.OpenPrinter(printer_name.c_str()))
400 return dev_mode.Pass();
402 base::win::ScopedComPtr<IStream> pt_stream;
403 HRESULT hr = StreamFromPrintTicket(print_ticket, pt_stream.Receive());
404 if (FAILED(hr))
405 return dev_mode.Pass();
407 HPTPROVIDER provider = NULL;
408 hr = printing::XPSModule::OpenProvider(printer_name, 1, &provider);
409 if (SUCCEEDED(hr)) {
410 ULONG size = 0;
411 DEVMODE* dm = NULL;
412 // Use kPTJobScope, because kPTDocumentScope breaks duplex.
413 hr = printing::XPSModule::ConvertPrintTicketToDevMode(
414 provider, pt_stream.get(), kUserDefaultDevmode, kPTJobScope, &size, &dm,
415 NULL);
416 if (SUCCEEDED(hr)) {
417 // Correct DEVMODE using DocumentProperties. See documentation for
418 // PTConvertPrintTicketToDevMode.
419 dev_mode = CreateDevMode(printer.Get(), dm);
420 printing::XPSModule::ReleaseMemory(dm);
422 printing::XPSModule::CloseProvider(provider);
424 return dev_mode.Pass();
427 scoped_ptr<DEVMODE, base::FreeDeleter> CreateDevModeWithColor(
428 HANDLE printer,
429 const base::string16& printer_name,
430 bool color) {
431 scoped_ptr<DEVMODE, base::FreeDeleter> default_ticket =
432 CreateDevMode(printer, NULL);
433 if (!default_ticket)
434 return default_ticket.Pass();
436 if ((default_ticket->dmFields & DM_COLOR) &&
437 ((default_ticket->dmColor == DMCOLOR_COLOR) == color)) {
438 return default_ticket.Pass();
441 default_ticket->dmFields |= DM_COLOR;
442 default_ticket->dmColor = color ? DMCOLOR_COLOR : DMCOLOR_MONOCHROME;
444 DriverInfo6 info_6;
445 if (!info_6.Init(printer))
446 return default_ticket.Pass();
448 const DRIVER_INFO_6* p = info_6.get();
450 // Only HP known to have issues.
451 if (!p->pszMfgName || wcscmp(p->pszMfgName, L"HP") != 0)
452 return default_ticket.Pass();
454 // Need XPS for this workaround.
455 printing::ScopedXPSInitializer xps_initializer;
456 if (!xps_initializer.initialized())
457 return default_ticket.Pass();
459 const char* xps_color = color ? kXpsTicketColor : kXpsTicketMonochrome;
460 std::string xps_ticket = base::StringPrintf(kXpsTicketTemplate, xps_color);
461 scoped_ptr<DEVMODE, base::FreeDeleter> ticket =
462 printing::XpsTicketToDevMode(printer_name, xps_ticket);
463 if (!ticket)
464 return default_ticket.Pass();
466 return ticket.Pass();
469 scoped_ptr<DEVMODE, base::FreeDeleter> CreateDevMode(HANDLE printer,
470 DEVMODE* in) {
471 LONG buffer_size = DocumentProperties(
472 NULL, printer, const_cast<wchar_t*>(L""), NULL, NULL, 0);
473 if (buffer_size < static_cast<int>(sizeof(DEVMODE)))
474 return scoped_ptr<DEVMODE, base::FreeDeleter>();
476 // Some drivers request buffers with size smaller than dmSize + dmDriverExtra.
477 // crbug.com/421402
478 buffer_size *= 2;
480 scoped_ptr<DEVMODE, base::FreeDeleter> out(
481 reinterpret_cast<DEVMODE*>(calloc(buffer_size, 1)));
482 DWORD flags = (in ? (DM_IN_BUFFER) : 0) | DM_OUT_BUFFER;
483 if (DocumentProperties(
484 NULL, printer, const_cast<wchar_t*>(L""), out.get(), in, flags) !=
485 IDOK) {
486 return scoped_ptr<DEVMODE, base::FreeDeleter>();
488 int size = out->dmSize;
489 int extra_size = out->dmDriverExtra;
490 CHECK_GE(buffer_size, size + extra_size);
491 return out.Pass();
494 scoped_ptr<DEVMODE, base::FreeDeleter> PromptDevMode(
495 HANDLE printer,
496 const base::string16& printer_name,
497 DEVMODE* in,
498 HWND window,
499 bool* canceled) {
500 LONG buffer_size =
501 DocumentProperties(window,
502 printer,
503 const_cast<wchar_t*>(printer_name.c_str()),
504 NULL,
505 NULL,
507 if (buffer_size < static_cast<int>(sizeof(DEVMODE)))
508 return scoped_ptr<DEVMODE, base::FreeDeleter>();
510 // Some drivers request buffers with size smaller than dmSize + dmDriverExtra.
511 // crbug.com/421402
512 buffer_size *= 2;
514 scoped_ptr<DEVMODE, base::FreeDeleter> out(
515 reinterpret_cast<DEVMODE*>(calloc(buffer_size, 1)));
516 DWORD flags = (in ? (DM_IN_BUFFER) : 0) | DM_OUT_BUFFER | DM_IN_PROMPT;
517 LONG result = DocumentProperties(window,
518 printer,
519 const_cast<wchar_t*>(printer_name.c_str()),
520 out.get(),
522 flags);
523 if (canceled)
524 *canceled = (result == IDCANCEL);
525 if (result != IDOK)
526 return scoped_ptr<DEVMODE, base::FreeDeleter>();
527 int size = out->dmSize;
528 int extra_size = out->dmDriverExtra;
529 CHECK_GE(buffer_size, size + extra_size);
530 return out.Pass();
533 } // namespace printing