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 "chrome/browser/printing/print_job_worker.h"
8 #include "base/bind_helpers.h"
9 #include "base/callback.h"
10 #include "base/compiler_specific.h"
11 #include "base/location.h"
12 #include "base/message_loop/message_loop.h"
13 #include "base/single_thread_task_runner.h"
14 #include "base/thread_task_runner_handle.h"
15 #include "base/values.h"
16 #include "chrome/browser/browser_process.h"
17 #include "chrome/browser/chrome_notification_types.h"
18 #include "chrome/browser/printing/print_job.h"
19 #include "chrome/grit/generated_resources.h"
20 #include "content/public/browser/browser_thread.h"
21 #include "content/public/browser/notification_service.h"
22 #include "content/public/browser/render_view_host.h"
23 #include "content/public/browser/web_contents.h"
24 #include "printing/print_job_constants.h"
25 #include "printing/printed_document.h"
26 #include "printing/printed_page.h"
27 #include "printing/printing_utils.h"
28 #include "ui/base/l10n/l10n_util.h"
30 #if defined(OS_ANDROID)
31 #include "chrome/browser/android/tab_android.h"
34 using content::BrowserThread
;
40 // Helper function to ensure |owner| is valid until at least |callback| returns.
41 void HoldRefCallback(const scoped_refptr
<printing::PrintJobWorkerOwner
>& owner
,
42 const base::Closure
& callback
) {
46 class PrintingContextDelegate
: public PrintingContext::Delegate
{
48 PrintingContextDelegate(int render_process_id
, int render_view_id
);
49 ~PrintingContextDelegate() override
;
51 gfx::NativeView
GetParentView() override
;
52 std::string
GetAppLocale() override
;
54 // Not exposed to PrintingContext::Delegate because of dependency issues.
55 content::WebContents
* GetWebContents();
58 int render_process_id_
;
62 PrintingContextDelegate::PrintingContextDelegate(int render_process_id
,
64 : render_process_id_(render_process_id
),
65 render_view_id_(render_view_id
) {
68 PrintingContextDelegate::~PrintingContextDelegate() {
71 gfx::NativeView
PrintingContextDelegate::GetParentView() {
72 content::WebContents
* wc
= GetWebContents();
73 return wc
? wc
->GetNativeView() : nullptr;
76 content::WebContents
* PrintingContextDelegate::GetWebContents() {
77 DCHECK_CURRENTLY_ON(BrowserThread::UI
);
78 content::RenderViewHost
* view
=
79 content::RenderViewHost::FromID(render_process_id_
, render_view_id_
);
80 return view
? content::WebContents::FromRenderViewHost(view
) : nullptr;
83 std::string
PrintingContextDelegate::GetAppLocale() {
84 return g_browser_process
->GetApplicationLocale();
87 void NotificationCallback(PrintJobWorkerOwner
* print_job
,
88 JobEventDetails::Type detail_type
,
89 PrintedDocument
* document
,
91 JobEventDetails
* details
= new JobEventDetails(detail_type
, document
, page
);
92 content::NotificationService::current()->Notify(
93 chrome::NOTIFICATION_PRINT_JOB_EVENT
,
94 // We know that is is a PrintJob object in this circumstance.
95 content::Source
<PrintJob
>(static_cast<PrintJob
*>(print_job
)),
96 content::Details
<JobEventDetails
>(details
));
99 void PostOnOwnerThread(const scoped_refptr
<PrintJobWorkerOwner
>& owner
,
100 const PrintingContext::PrintSettingsCallback
& callback
,
101 PrintingContext::Result result
) {
102 owner
->PostTask(FROM_HERE
, base::Bind(&HoldRefCallback
, owner
,
103 base::Bind(callback
, result
)));
108 PrintJobWorker::PrintJobWorker(int render_process_id
,
110 PrintJobWorkerOwner
* owner
)
111 : owner_(owner
), thread_("Printing_Worker"), weak_factory_(this) {
112 // The object is created in the IO thread.
113 DCHECK(owner_
->RunsTasksOnCurrentThread());
115 printing_context_delegate_
.reset(
116 new PrintingContextDelegate(render_process_id
, render_view_id
));
117 printing_context_
= PrintingContext::Create(printing_context_delegate_
.get());
120 PrintJobWorker::~PrintJobWorker() {
121 // The object is normally deleted in the UI thread, but when the user
122 // cancels printing or in the case of print preview, the worker is destroyed
123 // on the I/O thread.
124 DCHECK(owner_
->RunsTasksOnCurrentThread());
128 void PrintJobWorker::SetNewOwner(PrintJobWorkerOwner
* new_owner
) {
129 DCHECK(page_number_
== PageNumber::npos());
133 void PrintJobWorker::GetSettings(
134 bool ask_user_for_settings
,
135 int document_page_count
,
137 MarginType margin_type
,
139 DCHECK(task_runner_
->RunsTasksOnCurrentThread());
140 DCHECK_EQ(page_number_
, PageNumber::npos());
142 // Recursive task processing is needed for the dialog in case it needs to be
143 // destroyed by a task.
144 // TODO(thestig): This code is wrong. SetNestableTasksAllowed(true) is needed
145 // on the thread where the PrintDlgEx is called, and definitely both calls
146 // should happen on the same thread. See http://crbug.com/73466
147 // MessageLoop::current()->SetNestableTasksAllowed(true);
148 printing_context_
->set_margin_type(margin_type
);
150 // When we delegate to a destination, we don't ask the user for settings.
151 // TODO(mad): Ask the destination for settings.
152 if (ask_user_for_settings
) {
153 BrowserThread::PostTask(
154 BrowserThread::UI
, FROM_HERE
,
155 base::Bind(&HoldRefCallback
, make_scoped_refptr(owner_
),
156 base::Bind(&PrintJobWorker::GetSettingsWithUI
,
157 base::Unretained(this),
162 BrowserThread::PostTask(
163 BrowserThread::UI
, FROM_HERE
,
164 base::Bind(&HoldRefCallback
, make_scoped_refptr(owner_
),
165 base::Bind(&PrintJobWorker::UseDefaultSettings
,
166 base::Unretained(this))));
170 void PrintJobWorker::SetSettings(
171 scoped_ptr
<base::DictionaryValue
> new_settings
) {
172 DCHECK(task_runner_
->RunsTasksOnCurrentThread());
174 BrowserThread::PostTask(
177 base::Bind(&HoldRefCallback
,
178 make_scoped_refptr(owner_
),
179 base::Bind(&PrintJobWorker::UpdatePrintSettings
,
180 base::Unretained(this),
181 base::Passed(&new_settings
))));
184 void PrintJobWorker::UpdatePrintSettings(
185 scoped_ptr
<base::DictionaryValue
> new_settings
) {
186 DCHECK_CURRENTLY_ON(BrowserThread::UI
);
187 PrintingContext::Result result
=
188 printing_context_
->UpdatePrintSettings(*new_settings
);
189 GetSettingsDone(result
);
192 void PrintJobWorker::GetSettingsDone(PrintingContext::Result result
) {
193 // Most PrintingContext functions may start a message loop and process
194 // message recursively, so disable recursive task processing.
195 // TODO(thestig): See above comment. SetNestableTasksAllowed(false) needs to
196 // be called on the same thread as the previous call. See
197 // http://crbug.com/73466
198 // MessageLoop::current()->SetNestableTasksAllowed(false);
200 // We can't use OnFailure() here since owner_ may not support notifications.
202 // PrintJob will create the new PrintedDocument.
203 owner_
->PostTask(FROM_HERE
,
204 base::Bind(&PrintJobWorkerOwner::GetSettingsDone
,
205 make_scoped_refptr(owner_
),
206 printing_context_
->settings(),
210 void PrintJobWorker::GetSettingsWithUI(
211 int document_page_count
,
214 DCHECK_CURRENTLY_ON(BrowserThread::UI
);
216 #if defined(OS_ANDROID)
218 PrintingContextDelegate
* printing_context_delegate
=
219 static_cast<PrintingContextDelegate
*>(printing_context_delegate_
.get());
220 content::WebContents
* web_contents
=
221 printing_context_delegate
->GetWebContents();
222 TabAndroid
* tab
= TabAndroid::FromWebContents(web_contents
);
224 // Regardless of whether the following call fails or not, the javascript
225 // call will return since startPendingPrint will make it return immediately
228 tab
->SetPendingPrint();
232 // weak_factory_ creates pointers valid only on owner_ thread.
233 printing_context_
->AskUserForSettings(
234 document_page_count
, has_selection
, is_scripted
,
235 base::Bind(&PostOnOwnerThread
, make_scoped_refptr(owner_
),
236 base::Bind(&PrintJobWorker::GetSettingsDone
,
237 weak_factory_
.GetWeakPtr())));
240 void PrintJobWorker::UseDefaultSettings() {
241 PrintingContext::Result result
= printing_context_
->UseDefaultSettings();
242 GetSettingsDone(result
);
245 void PrintJobWorker::StartPrinting(PrintedDocument
* new_document
) {
246 DCHECK(task_runner_
->RunsTasksOnCurrentThread());
247 DCHECK_EQ(page_number_
, PageNumber::npos());
248 DCHECK_EQ(document_
.get(), new_document
);
249 DCHECK(document_
.get());
251 if (!document_
.get() || page_number_
!= PageNumber::npos() ||
252 document_
.get() != new_document
) {
256 base::string16 document_name
=
257 printing::SimplifyDocumentTitle(document_
->name());
258 if (document_name
.empty()) {
259 document_name
= printing::SimplifyDocumentTitle(
260 l10n_util::GetStringUTF16(IDS_DEFAULT_PRINT_DOCUMENT_TITLE
));
262 PrintingContext::Result result
=
263 printing_context_
->NewDocument(document_name
);
264 if (result
!= PrintingContext::OK
) {
269 // Try to print already cached data. It may already have been generated for
270 // the print preview.
272 // Don't touch this anymore since the instance could be destroyed. It happens
273 // if all the pages are printed a one sweep and the client doesn't have a
274 // handle to us anymore. There's a timing issue involved between the worker
275 // thread and the UI thread. Take no chance.
278 void PrintJobWorker::OnDocumentChanged(PrintedDocument
* new_document
) {
279 DCHECK(task_runner_
->RunsTasksOnCurrentThread());
280 DCHECK_EQ(page_number_
, PageNumber::npos());
282 if (page_number_
!= PageNumber::npos())
285 document_
= new_document
;
288 void PrintJobWorker::OnNewPage() {
289 if (!document_
.get()) // Spurious message.
292 // message_loop() could return NULL when the print job is cancelled.
293 DCHECK(task_runner_
->RunsTasksOnCurrentThread());
295 if (page_number_
== PageNumber::npos()) {
296 // Find first page to print.
297 int page_count
= document_
->page_count();
299 // We still don't know how many pages the document contains. We can't
300 // start to print the document yet since the header/footer may refer to
301 // the document's page count.
304 // We have enough information to initialize page_number_.
305 page_number_
.Init(document_
->settings(), page_count
);
307 DCHECK_NE(page_number_
, PageNumber::npos());
310 // Is the page available?
311 scoped_refptr
<PrintedPage
> page
= document_
->GetPage(page_number_
.ToInt());
313 // We need to wait for the page to be available.
314 base::ThreadTaskRunnerHandle::Get()->PostDelayedTask(
316 base::Bind(&PrintJobWorker::OnNewPage
, weak_factory_
.GetWeakPtr()),
317 base::TimeDelta::FromMilliseconds(500));
320 // The page is there, print it.
321 SpoolPage(page
.get());
323 if (page_number_
== PageNumber::npos()) {
325 // Don't touch this anymore since the instance could be destroyed.
331 void PrintJobWorker::Cancel() {
332 // This is the only function that can be called from any thread.
333 printing_context_
->Cancel();
334 // Cannot touch any member variable since we don't know in which thread
338 bool PrintJobWorker::IsRunning() const {
339 return thread_
.IsRunning();
342 bool PrintJobWorker::PostTask(const tracked_objects::Location
& from_here
,
343 const base::Closure
& task
) {
344 if (task_runner_
.get())
345 return task_runner_
->PostTask(from_here
, task
);
349 void PrintJobWorker::StopSoon() {
353 void PrintJobWorker::Stop() {
357 bool PrintJobWorker::Start() {
358 bool result
= thread_
.Start();
359 task_runner_
= thread_
.task_runner();
363 void PrintJobWorker::OnDocumentDone() {
364 DCHECK(task_runner_
->RunsTasksOnCurrentThread());
365 DCHECK_EQ(page_number_
, PageNumber::npos());
366 DCHECK(document_
.get());
368 if (printing_context_
->DocumentDone() != PrintingContext::OK
) {
373 owner_
->PostTask(FROM_HERE
,
374 base::Bind(&NotificationCallback
,
375 make_scoped_refptr(owner_
),
376 JobEventDetails::DOC_DONE
,
378 scoped_refptr
<PrintedPage
>()));
380 // Makes sure the variables are reinitialized.
384 void PrintJobWorker::SpoolPage(PrintedPage
* page
) {
385 DCHECK(task_runner_
->RunsTasksOnCurrentThread());
386 DCHECK_NE(page_number_
, PageNumber::npos());
388 // Signal everyone that the page is about to be printed.
389 owner_
->PostTask(FROM_HERE
,
390 base::Bind(&NotificationCallback
,
391 make_scoped_refptr(owner_
),
392 JobEventDetails::NEW_PAGE
,
394 make_scoped_refptr(page
)));
397 if (printing_context_
->NewPage() != PrintingContext::OK
) {
403 #if defined(OS_WIN) || defined(OS_MACOSX)
404 document_
->RenderPrintedPage(*page
, printing_context_
->context());
405 #elif defined(OS_POSIX)
406 document_
->RenderPrintedPage(*page
, printing_context_
.get());
410 if (printing_context_
->PageDone() != PrintingContext::OK
) {
415 // Signal everyone that the page is printed.
416 owner_
->PostTask(FROM_HERE
,
417 base::Bind(&NotificationCallback
,
418 make_scoped_refptr(owner_
),
419 JobEventDetails::PAGE_DONE
,
421 make_scoped_refptr(page
)));
424 void PrintJobWorker::OnFailure() {
425 DCHECK(task_runner_
->RunsTasksOnCurrentThread());
427 // We may loose our last reference by broadcasting the FAILED event.
428 scoped_refptr
<PrintJobWorkerOwner
> handle(owner_
);
430 owner_
->PostTask(FROM_HERE
,
431 base::Bind(&NotificationCallback
,
432 make_scoped_refptr(owner_
),
433 JobEventDetails::FAILED
,
435 scoped_refptr
<PrintedPage
>()));
438 // Makes sure the variables are reinitialized.
440 page_number_
= PageNumber::npos();
443 } // namespace printing