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.
4
5 #include "libcef/browser/printing/print_view_manager.h"
6
7 #include "include/internal/cef_types_wrappers.h"
8 #include "libcef/browser/browser_info.h"
9 #include "libcef/browser/browser_info_manager.h"
10 #include "libcef/browser/download_manager_delegate.h"
11 #include "libcef/browser/extensions/extension_web_contents_observer.h"
12 #include "libcef/browser/thread_util.h"
13
14 #include <map>
15 #include <utility>
16
17 #include "base/bind.h"
18 #include "base/lazy_instance.h"
19 #include "base/memory/ptr_util.h"
20 #include "base/memory/ref_counted_memory.h"
21 #include "base/task/post_task.h"
22 #include "chrome/browser/browser_process.h"
23 #include "chrome/browser/printing/print_job_manager.h"
24 #include "chrome/browser/printing/print_preview_dialog_controller.h"
25 #include "chrome/browser/printing/printer_query.h"
26 #include "chrome/browser/profiles/profile.h"
27 #include "chrome/browser/ui/webui/print_preview/print_preview_ui.h"
28 #include "components/printing/common/print.mojom.h"
29 #include "content/browser/download/download_manager_impl.h"
30 #include "content/public/browser/browser_context.h"
31 #include "content/public/browser/browser_task_traits.h"
32 #include "content/public/browser/browser_thread.h"
33 #include "content/public/browser/download_manager.h"
34 #include "content/public/browser/render_frame_host.h"
35 #include "content/public/browser/render_process_host.h"
36 #include "content/public/browser/render_view_host.h"
37 #include "content/public/browser/web_contents.h"
38 #include "content/public/browser/web_contents_observer.h"
39 #include "mojo/public/cpp/bindings/associated_remote.h"
40 #include "printing/metafile_skia.h"
41 #include "third_party/blink/public/common/associated_interfaces/associated_interface_provider.h"
42
43 #if BUILDFLAG(IS_LINUX)
44 #include "libcef/browser/printing/print_dialog_linux.h"
45 #endif
46
47 using content::BrowserThread;
48
49 namespace printing {
50
51 namespace {
52
53 const int PREVIEW_UIID = 12345678;
54
55 // Convert CefPdfPrintSettings into base::DictionaryValue.
FillInDictionaryFromPdfPrintSettings(const CefPdfPrintSettings & pdf_settings,int request_id,base::DictionaryValue & print_settings)56 void FillInDictionaryFromPdfPrintSettings(
57 const CefPdfPrintSettings& pdf_settings,
58 int request_id,
59 base::DictionaryValue& print_settings) {
60 // Fixed settings.
61 print_settings.SetIntKey(kSettingPrinterType,
62 static_cast<int>(mojom::PrinterType::kPdf));
63 print_settings.SetInteger(kSettingColor,
64 static_cast<int>(mojom::ColorModel::kGray));
65 print_settings.SetInteger(kSettingDuplexMode,
66 static_cast<int>(mojom::DuplexMode::kSimplex));
67 print_settings.SetInteger(kSettingCopies, 1);
68 print_settings.SetBoolean(kSettingCollate, false);
69 print_settings.SetString(kSettingDeviceName, "");
70 print_settings.SetBoolean(kSettingRasterizePdf, false);
71 print_settings.SetBoolean(kSettingPreviewModifiable, false);
72 print_settings.SetInteger(kSettingDpiHorizontal, 0);
73 print_settings.SetInteger(kSettingDpiVertical, 0);
74 print_settings.SetInteger(kSettingPagesPerSheet, 1);
75
76 // User defined settings.
77 print_settings.SetBoolean(kSettingLandscape, !!pdf_settings.landscape);
78 print_settings.SetBoolean(kSettingShouldPrintSelectionOnly,
79 !!pdf_settings.selection_only);
80 print_settings.SetBoolean(kSettingShouldPrintBackgrounds,
81 !!pdf_settings.backgrounds_enabled);
82 print_settings.SetBoolean(kSettingHeaderFooterEnabled,
83 !!pdf_settings.header_footer_enabled);
84 print_settings.SetInteger(kSettingScaleFactor, pdf_settings.scale_factor > 0
85 ? pdf_settings.scale_factor
86 : 100);
87
88 if (pdf_settings.header_footer_enabled) {
89 print_settings.SetString(
90 kSettingHeaderFooterTitle,
91 CefString(&pdf_settings.header_footer_title).ToString16());
92 print_settings.SetString(
93 kSettingHeaderFooterURL,
94 CefString(&pdf_settings.header_footer_url).ToString16());
95 }
96
97 if (pdf_settings.page_width > 0 && pdf_settings.page_height > 0) {
98 std::unique_ptr<base::DictionaryValue> dict(new base::DictionaryValue);
99 dict->SetInteger(kSettingMediaSizeWidthMicrons, pdf_settings.page_width);
100 dict->SetInteger(kSettingMediaSizeHeightMicrons, pdf_settings.page_height);
101 print_settings.Set(kSettingMediaSize, std::move(dict));
102 }
103
104 auto margin_type = printing::mojom::MarginType::kDefaultMargins;
105 switch (pdf_settings.margin_type) {
106 case PDF_PRINT_MARGIN_NONE:
107 margin_type = printing::mojom::MarginType::kNoMargins;
108 break;
109 case PDF_PRINT_MARGIN_MINIMUM:
110 margin_type = printing::mojom::MarginType::kPrintableAreaMargins;
111 break;
112 case PDF_PRINT_MARGIN_CUSTOM:
113 margin_type = printing::mojom::MarginType::kCustomMargins;
114 break;
115 default:
116 break;
117 }
118
119 print_settings.SetInteger(kSettingMarginsType, static_cast<int>(margin_type));
120 if (margin_type == printing::mojom::MarginType::kCustomMargins) {
121 std::unique_ptr<base::DictionaryValue> dict(new base::DictionaryValue);
122 dict->SetInteger(kSettingMarginTop, pdf_settings.margin_top);
123 dict->SetInteger(kSettingMarginRight, pdf_settings.margin_right);
124 dict->SetInteger(kSettingMarginBottom, pdf_settings.margin_bottom);
125 dict->SetInteger(kSettingMarginLeft, pdf_settings.margin_left);
126 print_settings.Set(kSettingMarginsCustom, std::move(dict));
127 }
128
129 // Service settings.
130 print_settings.SetInteger(kPreviewUIID, PREVIEW_UIID);
131 print_settings.SetInteger(kPreviewRequestID, request_id);
132 print_settings.SetBoolean(kIsFirstRequest, request_id != 0);
133 }
134
StopWorker(int document_cookie)135 void StopWorker(int document_cookie) {
136 if (document_cookie <= 0)
137 return;
138 scoped_refptr<PrintQueriesQueue> queue =
139 g_browser_process->print_job_manager()->queue();
140 std::unique_ptr<PrinterQuery> printer_query =
141 queue->PopPrinterQuery(document_cookie);
142 if (printer_query.get()) {
143 content::GetIOThreadTaskRunner({})->PostTask(
144 FROM_HERE,
145 base::BindOnce(&PrinterQuery::StopWorker, std::move(printer_query)));
146 }
147 }
148
149 // Write the PDF file to disk.
SavePdfFile(scoped_refptr<base::RefCountedSharedMemoryMapping> data,const base::FilePath & path,CefPrintViewManager::PdfPrintCallback callback)150 void SavePdfFile(scoped_refptr<base::RefCountedSharedMemoryMapping> data,
151 const base::FilePath& path,
152 CefPrintViewManager::PdfPrintCallback callback) {
153 CEF_REQUIRE_BLOCKING();
154 DCHECK_GT(data->size(), 0U);
155
156 MetafileSkia metafile;
157 metafile.InitFromData(*data);
158
159 base::File file(path,
160 base::File::FLAG_CREATE_ALWAYS | base::File::FLAG_WRITE);
161 bool ok = file.IsValid() && metafile.SaveTo(&file);
162
163 if (!callback.is_null()) {
164 content::GetUIThreadTaskRunner({})->PostTask(
165 FROM_HERE, base::BindOnce(std::move(callback), ok));
166 }
167 }
168
169 } // namespace
170
171 struct CefPrintViewManager::PdfPrintState {
172 content::RenderFrameHost* printing_rfh_ = nullptr;
173 base::FilePath output_path_;
174 base::DictionaryValue settings_;
175 PdfPrintCallback callback_;
176 };
177
CefPrintViewManager(content::WebContents * web_contents)178 CefPrintViewManager::CefPrintViewManager(content::WebContents* web_contents)
179 : PrintViewManager(web_contents) {}
180
~CefPrintViewManager()181 CefPrintViewManager::~CefPrintViewManager() {
182 TerminatePdfPrintJob();
183 }
184
185 // static
BindPrintManagerHost(mojo::PendingAssociatedReceiver<mojom::PrintManagerHost> receiver,content::RenderFrameHost * rfh)186 void CefPrintViewManager::BindPrintManagerHost(
187 mojo::PendingAssociatedReceiver<mojom::PrintManagerHost> receiver,
188 content::RenderFrameHost* rfh) {
189 auto* web_contents = content::WebContents::FromRenderFrameHost(rfh);
190 if (!web_contents)
191 return;
192 auto* print_manager = CefPrintViewManager::FromWebContents(web_contents);
193 if (!print_manager)
194 return;
195 print_manager->BindReceiver(std::move(receiver), rfh);
196 }
197
PrintToPDF(content::RenderFrameHost * rfh,const base::FilePath & path,const CefPdfPrintSettings & settings,PdfPrintCallback callback)198 bool CefPrintViewManager::PrintToPDF(content::RenderFrameHost* rfh,
199 const base::FilePath& path,
200 const CefPdfPrintSettings& settings,
201 PdfPrintCallback callback) {
202 DCHECK_CURRENTLY_ON(BrowserThread::UI);
203
204 // Don't start print again while printing is currently in progress.
205 if (pdf_print_state_)
206 return false;
207
208 // Don't print crashed tabs.
209 if (!web_contents() || web_contents()->IsCrashed() || !rfh->IsRenderFrameLive()) {
210 return false;
211 }
212
213 pdf_print_state_.reset(new PdfPrintState);
214 pdf_print_state_->printing_rfh_ = rfh;
215 pdf_print_state_->output_path_ = path;
216 pdf_print_state_->callback_ = std::move(callback);
217
218 FillInDictionaryFromPdfPrintSettings(settings, ++next_pdf_request_id_,
219 pdf_print_state_->settings_);
220
221 auto& print_render_frame = GetPrintRenderFrame(rfh);
222 if (!pdf_print_receiver_.is_bound()) {
223 print_render_frame->SetPrintPreviewUI(
224 pdf_print_receiver_.BindNewEndpointAndPassRemote());
225 }
226
227 print_render_frame->InitiatePrintPreview({}, !!settings.selection_only);
228
229 return true;
230 }
231
GetDefaultPrintSettings(GetDefaultPrintSettingsCallback callback)232 void CefPrintViewManager::GetDefaultPrintSettings(
233 GetDefaultPrintSettingsCallback callback) {
234 #if BUILDFLAG(IS_LINUX)
235 // Send notification to the client.
236 auto browser = CefBrowserHostBase::GetBrowserForContents(web_contents());
237 if (browser) {
238 CefPrintDialogLinux::OnPrintStart(browser);
239 }
240 #endif
241 PrintViewManager::GetDefaultPrintSettings(std::move(callback));
242 }
243
DidShowPrintDialog()244 void CefPrintViewManager::DidShowPrintDialog() {
245 if (pdf_print_state_)
246 return;
247 PrintViewManager::DidShowPrintDialog();
248 }
249
RequestPrintPreview(mojom::RequestPrintPreviewParamsPtr params)250 void CefPrintViewManager::RequestPrintPreview(
251 mojom::RequestPrintPreviewParamsPtr params) {
252 if (!pdf_print_state_) {
253 PrintViewManager::RequestPrintPreview(std::move(params));
254 return;
255 }
256
257 GetPrintRenderFrame(pdf_print_state_->printing_rfh_)
258 ->PrintPreview(pdf_print_state_->settings_.Clone());
259 }
260
CheckForCancel(int32_t preview_ui_id,int32_t request_id,CheckForCancelCallback callback)261 void CefPrintViewManager::CheckForCancel(int32_t preview_ui_id,
262 int32_t request_id,
263 CheckForCancelCallback callback) {
264 if (!pdf_print_state_) {
265 return PrintViewManager::CheckForCancel(preview_ui_id, request_id,
266 std::move(callback));
267 }
268
269 std::move(callback).Run(/*cancel=*/false);
270 }
271
MetafileReadyForPrinting(mojom::DidPreviewDocumentParamsPtr params,int32_t request_id)272 void CefPrintViewManager::MetafileReadyForPrinting(
273 mojom::DidPreviewDocumentParamsPtr params,
274 int32_t request_id) {
275 DCHECK_CURRENTLY_ON(BrowserThread::UI);
276 StopWorker(params->document_cookie);
277
278 if (!pdf_print_state_)
279 return;
280
281 GetPrintRenderFrame(pdf_print_state_->printing_rfh_)
282 ->OnPrintPreviewDialogClosed();
283
284 auto shared_buf = base::RefCountedSharedMemoryMapping::CreateFromWholeRegion(
285 params->content->metafile_data_region);
286 if (!shared_buf) {
287 TerminatePdfPrintJob();
288 return;
289 }
290
291 const base::FilePath output_path = pdf_print_state_->output_path_;
292 PdfPrintCallback print_callback = std::move(pdf_print_state_->callback_);
293
294 // Reset state information.
295 pdf_print_state_.reset();
296 pdf_print_receiver_.reset();
297
298 // Save the PDF file to disk and then execute the callback.
299 CEF_POST_USER_VISIBLE_TASK(base::BindOnce(
300 &SavePdfFile, shared_buf, output_path, std::move(print_callback)));
301 }
302
PrintPreviewFailed(int32_t document_cookie,int32_t request_id)303 void CefPrintViewManager::PrintPreviewFailed(int32_t document_cookie,
304 int32_t request_id) {
305 TerminatePdfPrintJob();
306 }
307
PrintPreviewCancelled(int32_t document_cookie,int32_t request_id)308 void CefPrintViewManager::PrintPreviewCancelled(int32_t document_cookie,
309 int32_t request_id) {
310 // Should never be canceled by CheckForCancel().
311 NOTREACHED();
312 }
313
RenderFrameDeleted(content::RenderFrameHost * render_frame_host)314 void CefPrintViewManager::RenderFrameDeleted(
315 content::RenderFrameHost* render_frame_host) {
316 if (pdf_print_state_ &&
317 render_frame_host == pdf_print_state_->printing_rfh_) {
318 TerminatePdfPrintJob();
319 }
320 PrintViewManager::RenderFrameDeleted(render_frame_host);
321 }
322
NavigationStopped()323 void CefPrintViewManager::NavigationStopped() {
324 TerminatePdfPrintJob();
325 PrintViewManager::NavigationStopped();
326 }
327
PrimaryMainFrameRenderProcessGone(base::TerminationStatus status)328 void CefPrintViewManager::PrimaryMainFrameRenderProcessGone(
329 base::TerminationStatus status) {
330 TerminatePdfPrintJob();
331 PrintViewManager::PrimaryMainFrameRenderProcessGone(status);
332 }
333
334 // static
CreateForWebContents(content::WebContents * contents)335 void CefPrintViewManager::CreateForWebContents(content::WebContents* contents) {
336 DCHECK(contents);
337 if (!FromWebContents(contents)) {
338 contents->SetUserData(PrintViewManager::UserDataKey(),
339 base::WrapUnique(new CefPrintViewManager(contents)));
340 }
341 }
342
343 // static
FromWebContents(content::WebContents * contents)344 CefPrintViewManager* CefPrintViewManager::FromWebContents(
345 content::WebContents* contents) {
346 DCHECK(contents);
347 return static_cast<CefPrintViewManager*>(
348 contents->GetUserData(PrintViewManager::UserDataKey()));
349 }
350
351 // static
FromWebContents(const content::WebContents * contents)352 const CefPrintViewManager* CefPrintViewManager::FromWebContents(
353 const content::WebContents* contents) {
354 DCHECK(contents);
355 return static_cast<const CefPrintViewManager*>(
356 contents->GetUserData(PrintViewManager::UserDataKey()));
357 }
358
TerminatePdfPrintJob()359 void CefPrintViewManager::TerminatePdfPrintJob() {
360 DCHECK_CURRENTLY_ON(BrowserThread::UI);
361 if (!pdf_print_state_)
362 return;
363
364 if (!pdf_print_state_->callback_.is_null()) {
365 // Execute the callback.
366 content::GetUIThreadTaskRunner({})->PostTask(
367 FROM_HERE,
368 base::BindOnce(std::move(pdf_print_state_->callback_), false));
369 }
370
371 // Reset state information.
372 pdf_print_state_.reset();
373 pdf_print_receiver_.reset();
374 }
375
376 } // namespace printing
377