File: print_job_worker.cc

package info (click to toggle)
chromium 138.0.7204.157-1
  • links: PTS, VCS
  • area: main
  • in suites: trixie
  • size: 6,071,864 kB
  • sloc: cpp: 34,936,859; ansic: 7,176,967; javascript: 4,110,704; python: 1,419,953; asm: 946,768; xml: 739,967; pascal: 187,324; sh: 89,623; perl: 88,663; objc: 79,944; sql: 50,304; cs: 41,786; fortran: 24,137; makefile: 21,806; php: 13,980; tcl: 13,166; yacc: 8,925; ruby: 7,485; awk: 3,720; lisp: 3,096; lex: 1,327; ada: 727; jsp: 228; sed: 36
file content (346 lines) | stat: -rw-r--r-- 9,844 bytes parent folder | download | duplicates (4)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
// Copyright 2012 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/browser/printing/print_job_worker.h"

#include <memory>
#include <string>
#include <utility>

#include "base/compiler_specific.h"
#include "base/functional/bind.h"
#include "base/functional/callback.h"
#include "base/functional/callback_helpers.h"
#include "base/location.h"
#include "base/numerics/safe_conversions.h"
#include "base/task/single_thread_task_runner.h"
#include "base/values.h"
#include "build/build_config.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/printing/print_job.h"
#include "chrome/grit/generated_resources.h"
#include "components/device_event_log/device_event_log.h"
#include "components/enterprise/buildflags/buildflags.h"
#include "content/public/browser/browser_task_traits.h"
#include "content/public/browser/browser_thread.h"
#include "content/public/browser/global_routing_id.h"
#include "content/public/browser/render_frame_host.h"
#include "content/public/browser/web_contents.h"
#include "printing/mojom/print.mojom.h"
#include "printing/print_job_constants.h"
#include "printing/printed_document.h"
#include "printing/printing_context.h"
#include "printing/printing_utils.h"
#include "ui/base/l10n/l10n_util.h"

#if BUILDFLAG(IS_WIN)
#include "base/threading/thread_restrictions.h"
#include "chrome/browser/printing/xps_features.h"
#include "printing/printed_page_win.h"
#endif

using content::BrowserThread;

namespace printing {

namespace {

void DocDoneNotificationCallback(PrintJob* print_job,
                                 int job_id,
                                 PrintedDocument* document) {
  print_job->OnDocDone(job_id, document);
}

void FailedNotificationCallback(PrintJob* print_job) {
  print_job->OnFailed();
}

}  // namespace

PrintJobWorker::PrintJobWorker(
    std::unique_ptr<PrintingContext::Delegate> printing_context_delegate,
    std::unique_ptr<PrintingContext> printing_context,
    PrintJob* print_job)
    : printing_context_delegate_(std::move(printing_context_delegate)),
      printing_context_(std::move(printing_context)),
      print_job_(print_job),
      thread_("Printing_Worker") {
  DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
}

PrintJobWorker::~PrintJobWorker() {
  DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
  Stop();
}

bool PrintJobWorker::StartPrintingSanityCheck(
    const PrintedDocument* new_document) const {
  DCHECK(task_runner_->RunsTasksInCurrentSequence());

  if (page_number_ != PageNumber::npos()) {
    NOTREACHED();
  }

  if (!document_) {
    NOTREACHED();
  }

  if (document_.get() != new_document) {
    NOTREACHED();
  }

  return true;
}

std::u16string PrintJobWorker::GetDocumentName(
    const PrintedDocument* new_document) const {
  DCHECK(task_runner_->RunsTasksInCurrentSequence());

  std::u16string document_name = SimplifyDocumentTitle(document_->name());
  if (document_name.empty()) {
    document_name = SimplifyDocumentTitle(
        l10n_util::GetStringUTF16(IDS_DEFAULT_PRINT_DOCUMENT_TITLE));
  }
  return document_name;
}

bool PrintJobWorker::SetupDocument(const std::u16string& document_name) {
  mojom::ResultCode result = printing_context_->NewDocument(document_name);
  switch (result) {
    case mojom::ResultCode::kSuccess:
      return true;
    case mojom::ResultCode::kCanceled:
      OnCancel();
      return false;
    default:
      OnFailure();
      return false;
  }
}

void PrintJobWorker::StartPrinting(PrintedDocument* new_document) {
  if (!StartPrintingSanityCheck(new_document))
    return;

  if (!SetupDocument(GetDocumentName(new_document))) {
    return;
  }

  // This will start a loop to wait for the page data.
  OnNewPage();
  // Don't touch this anymore since the instance could be destroyed. It happens
  // if all the pages are printed a one sweep and the client doesn't have a
  // handle to us anymore. There's a timing issue involved between the worker
  // thread and the UI thread. Take no chance.
}

void PrintJobWorker::OnDocumentChanged(PrintedDocument* new_document) {
  DCHECK(task_runner_->RunsTasksInCurrentSequence());

  if (page_number_ != PageNumber::npos()) {
    NOTREACHED();
  }

  document_ = new_document;
}

void PrintJobWorker::PostWaitForPage() {
  // We need to wait for the page to be available.
  base::SingleThreadTaskRunner::GetCurrentDefault()->PostDelayedTask(
      FROM_HERE,
      base::BindOnce(&PrintJobWorker::OnNewPage, weak_factory_.GetWeakPtr()),
      base::Milliseconds(500));
}

void PrintJobWorker::OnNewPage() {
  DCHECK(task_runner_->RunsTasksInCurrentSequence());

  if (!document_)
    return;

  bool do_spool_document = true;
#if BUILDFLAG(IS_WIN)
  const bool source_is_pdf =
      !print_job_->document()->settings().is_modifiable();
  if (!ShouldPrintUsingXps(source_is_pdf)) {
    // Using the Windows GDI print API.
    if (!OnNewPageHelperGdi())
      return;

    do_spool_document = false;
  }
#endif  // BUILDFLAG(IS_WIN)

  if (do_spool_document) {
    if (!document_->GetMetafile()) {
      PostWaitForPage();
      return;
    }
    if (!SpoolDocument())
      return;
  }

  OnDocumentDone();
  // Don't touch `this` anymore since the instance could be destroyed.
}

#if BUILDFLAG(IS_WIN)
bool PrintJobWorker::OnNewPageHelperGdi() {
  if (page_number_ == PageNumber::npos()) {
    // Find first page to print.
    int page_count = document_->page_count();
    if (!page_count) {
      // We still don't know how many pages the document contains.
      return false;
    }
    // We have enough information to initialize `page_number_`.
    page_number_.Init(document_->settings().ranges(), page_count);
  }

  while (true) {
    scoped_refptr<PrintedPage> page = document_->GetPage(page_number_.ToUint());
    if (!page) {
      PostWaitForPage();
      return false;
    }
    // The page is there, print it.
    if (!SpoolPage(page.get()))
      return false;
    ++page_number_;
    if (page_number_ == PageNumber::npos())
      break;
  }
  return true;
}
#endif  // BUILDFLAG(IS_WIN)

void PrintJobWorker::Cancel() {
  // This is the only function that can be called from any thread.
  printing_context_->Cancel();
  // Cannot touch any member variable since we don't know in which thread
  // context we run.
}

#if BUILDFLAG(ENTERPRISE_CONTENT_ANALYSIS)
void PrintJobWorker::CleanupAfterContentAnalysisDenial() {
  DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
  DVLOG(1) << "Canceling job due to content analysis";
}
#endif

bool PrintJobWorker::IsRunning() const {
  return thread_.IsRunning();
}

bool PrintJobWorker::PostTask(const base::Location& from_here,
                              base::OnceClosure task) {
  return task_runner_ && task_runner_->PostTask(from_here, std::move(task));
}

void PrintJobWorker::StopSoon() {
  thread_.StopSoon();
}

void PrintJobWorker::Stop() {
  thread_.Stop();
}

bool PrintJobWorker::Start() {
  bool result = thread_.Start();
  task_runner_ = thread_.task_runner();
  return result;
}

void PrintJobWorker::CheckDocumentSpoolingComplete() {
  DCHECK(task_runner_->RunsTasksInCurrentSequence());
  DCHECK_EQ(page_number_, PageNumber::npos());
  // PrintJob must own this, because only PrintJob can send notifications.
  DCHECK(print_job_);
}

void PrintJobWorker::OnDocumentDone() {
  CheckDocumentSpoolingComplete();

  int job_id = printing_context_->job_id();
  if (printing_context_->DocumentDone() != mojom::ResultCode::kSuccess) {
    OnFailure();
    return;
  }

  FinishDocumentDone(job_id);
}

void PrintJobWorker::FinishDocumentDone(int job_id) {
  DCHECK(task_runner_->RunsTasksInCurrentSequence());
  DCHECK(document_);
  print_job_->PostTask(
      FROM_HERE, base::BindOnce(&DocDoneNotificationCallback,
                                base::RetainedRef(print_job_.get()), job_id,
                                base::RetainedRef(document_)));

  // Makes sure the variables are reinitialized.
  document_ = nullptr;
}

#if BUILDFLAG(IS_WIN)
bool PrintJobWorker::SpoolPage(PrintedPage* page) {
  DCHECK(task_runner_->RunsTasksInCurrentSequence());
  DCHECK_NE(page_number_, PageNumber::npos());

  // Actual printing.
  if (document_->RenderPrintedPage(*page, printing_context_.get()) !=
      mojom::ResultCode::kSuccess) {
    OnFailure();
    return false;
  }

  // Signal everyone that the page is printed.
  DCHECK(print_job_);
  print_job_->PostTask(FROM_HERE,
                       base::BindOnce(&PrintJob::OnPageDone, print_job_,
                                      base::RetainedRef(page)));
  return true;
}
#endif  // BUILDFLAG(IS_WIN)

bool PrintJobWorker::SpoolDocument() {
  DCHECK(task_runner_->RunsTasksInCurrentSequence());
  mojom::ResultCode result =
      document_->RenderPrintedDocument(printing_context_.get());
  if (result != mojom::ResultCode::kSuccess) {
    PRINTER_LOG(ERROR) << "Failure to render printed document - error "
                       << result;
    OnFailure();
    return false;
  }
  return true;
}

void PrintJobWorker::OnCancel() {
  DCHECK(task_runner_->RunsTasksInCurrentSequence());
  DCHECK(print_job_);

  print_job_->PostTask(
      FROM_HERE,
      base::BindOnce(&PrintJob::Cancel, base::RetainedRef(print_job_.get())));
}

void PrintJobWorker::OnFailure() {
  DCHECK(task_runner_->RunsTasksInCurrentSequence());
  DCHECK(print_job_);

  // We may loose our last reference by broadcasting the FAILED event.
  scoped_refptr<PrintJob> handle(print_job_.get());

  print_job_->PostTask(FROM_HERE,
                       base::BindOnce(&FailedNotificationCallback,
                                      base::RetainedRef(print_job_.get())));
  Cancel();

  // Makes sure the variables are reinitialized.
  document_ = nullptr;
  page_number_ = PageNumber::npos();
}

}  // namespace printing