Chromium Code Reviews
chromiumcodereview-hr@appspot.gserviceaccount.com (chromiumcodereview-hr) | Please choose your nickname with Settings | Help | Chromium Project | Gerrit Changes | Sign out
(561)

Side by Side Diff: chrome/renderer/printing/print_web_view_helper.cc

Issue 811563008: Moving files from //chrome to //components/printing (Closed) Base URL: https://chromium.googlesource.com/chromium/src.git@master
Patch Set: nit fix Created 5 years, 11 months ago
Use n/p to move between diff chunks; N/P to move between comments. Draft comments are only viewable by you.
Jump to:
View unified diff | Download patch
OLDNEW
(Empty)
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 "chrome/renderer/printing/print_web_view_helper.h"
6
7 #include <string>
8
9 #include "base/auto_reset.h"
10 #include "base/json/json_writer.h"
11 #include "base/logging.h"
12 #include "base/message_loop/message_loop.h"
13 #include "base/metrics/histogram.h"
14 #include "base/process/process_handle.h"
15 #include "base/strings/string_number_conversions.h"
16 #include "base/strings/stringprintf.h"
17 #include "base/strings/utf_string_conversions.h"
18 #include "chrome/common/print_messages.h"
19 #include "chrome/grit/browser_resources.h"
20 #include "content/public/common/web_preferences.h"
21 #include "content/public/renderer/render_frame.h"
22 #include "content/public/renderer/render_thread.h"
23 #include "content/public/renderer/render_view.h"
24 #include "net/base/escape.h"
25 #include "printing/pdf_metafile_skia.h"
26 #include "printing/units.h"
27 #include "third_party/WebKit/public/platform/WebSize.h"
28 #include "third_party/WebKit/public/platform/WebURLRequest.h"
29 #include "third_party/WebKit/public/web/WebConsoleMessage.h"
30 #include "third_party/WebKit/public/web/WebDocument.h"
31 #include "third_party/WebKit/public/web/WebElement.h"
32 #include "third_party/WebKit/public/web/WebFrameClient.h"
33 #include "third_party/WebKit/public/web/WebLocalFrame.h"
34 #include "third_party/WebKit/public/web/WebPlugin.h"
35 #include "third_party/WebKit/public/web/WebPluginDocument.h"
36 #include "third_party/WebKit/public/web/WebPrintParams.h"
37 #include "third_party/WebKit/public/web/WebPrintPresetOptions.h"
38 #include "third_party/WebKit/public/web/WebPrintScalingOption.h"
39 #include "third_party/WebKit/public/web/WebScriptSource.h"
40 #include "third_party/WebKit/public/web/WebSettings.h"
41 #include "third_party/WebKit/public/web/WebView.h"
42 #include "third_party/WebKit/public/web/WebViewClient.h"
43 #include "ui/base/resource/resource_bundle.h"
44
45 using content::WebPreferences;
46
47 namespace printing {
48
49 namespace {
50
51 enum PrintPreviewHelperEvents {
52 PREVIEW_EVENT_REQUESTED,
53 PREVIEW_EVENT_CACHE_HIT, // Unused
54 PREVIEW_EVENT_CREATE_DOCUMENT,
55 PREVIEW_EVENT_NEW_SETTINGS, // Unused
56 PREVIEW_EVENT_MAX,
57 };
58
59 const double kMinDpi = 1.0;
60
61 #if !defined(ENABLE_PRINT_PREVIEW)
62 bool g_is_preview_enabled_ = false;
63 #else
64 bool g_is_preview_enabled_ = true;
65
66 const char kPageLoadScriptFormat[] =
67 "document.open(); document.write(%s); document.close();";
68
69 const char kPageSetupScriptFormat[] = "setup(%s);";
70
71 void ExecuteScript(blink::WebFrame* frame,
72 const char* script_format,
73 const base::Value& parameters) {
74 std::string json;
75 base::JSONWriter::Write(&parameters, &json);
76 std::string script = base::StringPrintf(script_format, json.c_str());
77 frame->executeScript(blink::WebString(base::UTF8ToUTF16(script)));
78 }
79 #endif // !defined(ENABLE_PRINT_PREVIEW)
80
81 int GetDPI(const PrintMsg_Print_Params* print_params) {
82 #if defined(OS_MACOSX)
83 // On the Mac, the printable area is in points, don't do any scaling based
84 // on dpi.
85 return kPointsPerInch;
86 #else
87 return static_cast<int>(print_params->dpi);
88 #endif // defined(OS_MACOSX)
89 }
90
91 bool PrintMsg_Print_Params_IsValid(const PrintMsg_Print_Params& params) {
92 return !params.content_size.IsEmpty() && !params.page_size.IsEmpty() &&
93 !params.printable_area.IsEmpty() && params.document_cookie &&
94 params.desired_dpi && params.max_shrink && params.min_shrink &&
95 params.dpi && (params.margin_top >= 0) && (params.margin_left >= 0) &&
96 params.dpi > kMinDpi && params.document_cookie != 0;
97 }
98
99 PrintMsg_Print_Params GetCssPrintParams(
100 blink::WebFrame* frame,
101 int page_index,
102 const PrintMsg_Print_Params& page_params) {
103 PrintMsg_Print_Params page_css_params = page_params;
104 int dpi = GetDPI(&page_params);
105
106 blink::WebSize page_size_in_pixels(
107 ConvertUnit(page_params.page_size.width(), dpi, kPixelsPerInch),
108 ConvertUnit(page_params.page_size.height(), dpi, kPixelsPerInch));
109 int margin_top_in_pixels =
110 ConvertUnit(page_params.margin_top, dpi, kPixelsPerInch);
111 int margin_right_in_pixels = ConvertUnit(
112 page_params.page_size.width() -
113 page_params.content_size.width() - page_params.margin_left,
114 dpi, kPixelsPerInch);
115 int margin_bottom_in_pixels = ConvertUnit(
116 page_params.page_size.height() -
117 page_params.content_size.height() - page_params.margin_top,
118 dpi, kPixelsPerInch);
119 int margin_left_in_pixels = ConvertUnit(
120 page_params.margin_left,
121 dpi, kPixelsPerInch);
122
123 blink::WebSize original_page_size_in_pixels = page_size_in_pixels;
124
125 if (frame) {
126 frame->pageSizeAndMarginsInPixels(page_index,
127 page_size_in_pixels,
128 margin_top_in_pixels,
129 margin_right_in_pixels,
130 margin_bottom_in_pixels,
131 margin_left_in_pixels);
132 }
133
134 int new_content_width = page_size_in_pixels.width -
135 margin_left_in_pixels - margin_right_in_pixels;
136 int new_content_height = page_size_in_pixels.height -
137 margin_top_in_pixels - margin_bottom_in_pixels;
138
139 // Invalid page size and/or margins. We just use the default setting.
140 if (new_content_width < 1 || new_content_height < 1) {
141 CHECK(frame != NULL);
142 page_css_params = GetCssPrintParams(NULL, page_index, page_params);
143 return page_css_params;
144 }
145
146 page_css_params.content_size = gfx::Size(
147 ConvertUnit(new_content_width, kPixelsPerInch, dpi),
148 ConvertUnit(new_content_height, kPixelsPerInch, dpi));
149
150 if (original_page_size_in_pixels != page_size_in_pixels) {
151 page_css_params.page_size = gfx::Size(
152 ConvertUnit(page_size_in_pixels.width, kPixelsPerInch, dpi),
153 ConvertUnit(page_size_in_pixels.height, kPixelsPerInch, dpi));
154 } else {
155 // Printing frame doesn't have any page size css. Pixels to dpi conversion
156 // causes rounding off errors. Therefore use the default page size values
157 // directly.
158 page_css_params.page_size = page_params.page_size;
159 }
160
161 page_css_params.margin_top =
162 ConvertUnit(margin_top_in_pixels, kPixelsPerInch, dpi);
163 page_css_params.margin_left =
164 ConvertUnit(margin_left_in_pixels, kPixelsPerInch, dpi);
165 return page_css_params;
166 }
167
168 double FitPrintParamsToPage(const PrintMsg_Print_Params& page_params,
169 PrintMsg_Print_Params* params_to_fit) {
170 double content_width =
171 static_cast<double>(params_to_fit->content_size.width());
172 double content_height =
173 static_cast<double>(params_to_fit->content_size.height());
174 int default_page_size_height = page_params.page_size.height();
175 int default_page_size_width = page_params.page_size.width();
176 int css_page_size_height = params_to_fit->page_size.height();
177 int css_page_size_width = params_to_fit->page_size.width();
178
179 double scale_factor = 1.0f;
180 if (page_params.page_size == params_to_fit->page_size)
181 return scale_factor;
182
183 if (default_page_size_width < css_page_size_width ||
184 default_page_size_height < css_page_size_height) {
185 double ratio_width =
186 static_cast<double>(default_page_size_width) / css_page_size_width;
187 double ratio_height =
188 static_cast<double>(default_page_size_height) / css_page_size_height;
189 scale_factor = ratio_width < ratio_height ? ratio_width : ratio_height;
190 content_width *= scale_factor;
191 content_height *= scale_factor;
192 }
193 params_to_fit->margin_top = static_cast<int>(
194 (default_page_size_height - css_page_size_height * scale_factor) / 2 +
195 (params_to_fit->margin_top * scale_factor));
196 params_to_fit->margin_left = static_cast<int>(
197 (default_page_size_width - css_page_size_width * scale_factor) / 2 +
198 (params_to_fit->margin_left * scale_factor));
199 params_to_fit->content_size = gfx::Size(
200 static_cast<int>(content_width), static_cast<int>(content_height));
201 params_to_fit->page_size = page_params.page_size;
202 return scale_factor;
203 }
204
205 void CalculatePageLayoutFromPrintParams(
206 const PrintMsg_Print_Params& params,
207 PageSizeMargins* page_layout_in_points) {
208 int dpi = GetDPI(&params);
209 int content_width = params.content_size.width();
210 int content_height = params.content_size.height();
211
212 int margin_bottom = params.page_size.height() -
213 content_height - params.margin_top;
214 int margin_right = params.page_size.width() -
215 content_width - params.margin_left;
216
217 page_layout_in_points->content_width =
218 ConvertUnit(content_width, dpi, kPointsPerInch);
219 page_layout_in_points->content_height =
220 ConvertUnit(content_height, dpi, kPointsPerInch);
221 page_layout_in_points->margin_top =
222 ConvertUnit(params.margin_top, dpi, kPointsPerInch);
223 page_layout_in_points->margin_right =
224 ConvertUnit(margin_right, dpi, kPointsPerInch);
225 page_layout_in_points->margin_bottom =
226 ConvertUnit(margin_bottom, dpi, kPointsPerInch);
227 page_layout_in_points->margin_left =
228 ConvertUnit(params.margin_left, dpi, kPointsPerInch);
229 }
230
231 void EnsureOrientationMatches(const PrintMsg_Print_Params& css_params,
232 PrintMsg_Print_Params* page_params) {
233 if ((page_params->page_size.width() > page_params->page_size.height()) ==
234 (css_params.page_size.width() > css_params.page_size.height())) {
235 return;
236 }
237
238 // Swap the |width| and |height| values.
239 page_params->page_size.SetSize(page_params->page_size.height(),
240 page_params->page_size.width());
241 page_params->content_size.SetSize(page_params->content_size.height(),
242 page_params->content_size.width());
243 page_params->printable_area.set_size(
244 gfx::Size(page_params->printable_area.height(),
245 page_params->printable_area.width()));
246 }
247
248 void ComputeWebKitPrintParamsInDesiredDpi(
249 const PrintMsg_Print_Params& print_params,
250 blink::WebPrintParams* webkit_print_params) {
251 int dpi = GetDPI(&print_params);
252 webkit_print_params->printerDPI = dpi;
253 webkit_print_params->printScalingOption = print_params.print_scaling_option;
254
255 webkit_print_params->printContentArea.width =
256 ConvertUnit(print_params.content_size.width(), dpi,
257 print_params.desired_dpi);
258 webkit_print_params->printContentArea.height =
259 ConvertUnit(print_params.content_size.height(), dpi,
260 print_params.desired_dpi);
261
262 webkit_print_params->printableArea.x =
263 ConvertUnit(print_params.printable_area.x(), dpi,
264 print_params.desired_dpi);
265 webkit_print_params->printableArea.y =
266 ConvertUnit(print_params.printable_area.y(), dpi,
267 print_params.desired_dpi);
268 webkit_print_params->printableArea.width =
269 ConvertUnit(print_params.printable_area.width(), dpi,
270 print_params.desired_dpi);
271 webkit_print_params->printableArea.height =
272 ConvertUnit(print_params.printable_area.height(),
273 dpi, print_params.desired_dpi);
274
275 webkit_print_params->paperSize.width =
276 ConvertUnit(print_params.page_size.width(), dpi,
277 print_params.desired_dpi);
278 webkit_print_params->paperSize.height =
279 ConvertUnit(print_params.page_size.height(), dpi,
280 print_params.desired_dpi);
281 }
282
283 blink::WebPlugin* GetPlugin(const blink::WebFrame* frame) {
284 return frame->document().isPluginDocument() ?
285 frame->document().to<blink::WebPluginDocument>().plugin() : NULL;
286 }
287
288 bool PrintingNodeOrPdfFrame(const blink::WebFrame* frame,
289 const blink::WebNode& node) {
290 if (!node.isNull())
291 return true;
292 blink::WebPlugin* plugin = GetPlugin(frame);
293 return plugin && plugin->supportsPaginatedPrint();
294 }
295
296 bool PrintingFrameHasPageSizeStyle(blink::WebFrame* frame,
297 int total_page_count) {
298 if (!frame)
299 return false;
300 bool frame_has_custom_page_size_style = false;
301 for (int i = 0; i < total_page_count; ++i) {
302 if (frame->hasCustomPageSizeStyle(i)) {
303 frame_has_custom_page_size_style = true;
304 break;
305 }
306 }
307 return frame_has_custom_page_size_style;
308 }
309
310 MarginType GetMarginsForPdf(blink::WebFrame* frame,
311 const blink::WebNode& node) {
312 if (frame->isPrintScalingDisabledForPlugin(node))
313 return NO_MARGINS;
314 else
315 return PRINTABLE_AREA_MARGINS;
316 }
317
318 bool FitToPageEnabled(const base::DictionaryValue& job_settings) {
319 bool fit_to_paper_size = false;
320 if (!job_settings.GetBoolean(kSettingFitToPageEnabled, &fit_to_paper_size)) {
321 NOTREACHED();
322 }
323 return fit_to_paper_size;
324 }
325
326 // Returns the print scaling option to retain/scale/crop the source page size
327 // to fit the printable area of the paper.
328 //
329 // We retain the source page size when the current destination printer is
330 // SAVE_AS_PDF.
331 //
332 // We crop the source page size to fit the printable area or we print only the
333 // left top page contents when
334 // (1) Source is PDF and the user has requested not to fit to printable area
335 // via |job_settings|.
336 // (2) Source is PDF. This is the first preview request and print scaling
337 // option is disabled for initiator renderer plugin.
338 //
339 // In all other cases, we scale the source page to fit the printable area.
340 blink::WebPrintScalingOption GetPrintScalingOption(
341 blink::WebFrame* frame,
342 const blink::WebNode& node,
343 bool source_is_html,
344 const base::DictionaryValue& job_settings,
345 const PrintMsg_Print_Params& params) {
346 if (params.print_to_pdf)
347 return blink::WebPrintScalingOptionSourceSize;
348
349 if (!source_is_html) {
350 if (!FitToPageEnabled(job_settings))
351 return blink::WebPrintScalingOptionNone;
352
353 bool no_plugin_scaling = frame->isPrintScalingDisabledForPlugin(node);
354
355 if (params.is_first_request && no_plugin_scaling)
356 return blink::WebPrintScalingOptionNone;
357 }
358 return blink::WebPrintScalingOptionFitToPrintableArea;
359 }
360
361 PrintMsg_Print_Params CalculatePrintParamsForCss(
362 blink::WebFrame* frame,
363 int page_index,
364 const PrintMsg_Print_Params& page_params,
365 bool ignore_css_margins,
366 bool fit_to_page,
367 double* scale_factor) {
368 PrintMsg_Print_Params css_params = GetCssPrintParams(frame, page_index,
369 page_params);
370
371 PrintMsg_Print_Params params = page_params;
372 EnsureOrientationMatches(css_params, &params);
373
374 if (ignore_css_margins && fit_to_page)
375 return params;
376
377 PrintMsg_Print_Params result_params = css_params;
378 if (ignore_css_margins) {
379 result_params.margin_top = params.margin_top;
380 result_params.margin_left = params.margin_left;
381
382 DCHECK(!fit_to_page);
383 // Since we are ignoring the margins, the css page size is no longer
384 // valid.
385 int default_margin_right = params.page_size.width() -
386 params.content_size.width() - params.margin_left;
387 int default_margin_bottom = params.page_size.height() -
388 params.content_size.height() - params.margin_top;
389 result_params.content_size = gfx::Size(
390 result_params.page_size.width() - result_params.margin_left -
391 default_margin_right,
392 result_params.page_size.height() - result_params.margin_top -
393 default_margin_bottom);
394 }
395
396 if (fit_to_page) {
397 double factor = FitPrintParamsToPage(params, &result_params);
398 if (scale_factor)
399 *scale_factor = factor;
400 }
401 return result_params;
402 }
403
404 } // namespace
405
406 FrameReference::FrameReference(blink::WebLocalFrame* frame) {
407 Reset(frame);
408 }
409
410 FrameReference::FrameReference() {
411 Reset(NULL);
412 }
413
414 FrameReference::~FrameReference() {
415 }
416
417 void FrameReference::Reset(blink::WebLocalFrame* frame) {
418 if (frame) {
419 view_ = frame->view();
420 frame_ = frame;
421 } else {
422 view_ = NULL;
423 frame_ = NULL;
424 }
425 }
426
427 blink::WebLocalFrame* FrameReference::GetFrame() {
428 if (view_ == NULL || frame_ == NULL)
429 return NULL;
430 for (blink::WebFrame* frame = view_->mainFrame(); frame != NULL;
431 frame = frame->traverseNext(false)) {
432 if (frame == frame_)
433 return frame_;
434 }
435 return NULL;
436 }
437
438 blink::WebView* FrameReference::view() {
439 return view_;
440 }
441
442 #if defined(ENABLE_PRINT_PREVIEW)
443 // static - Not anonymous so that platform implementations can use it.
444 void PrintWebViewHelper::PrintHeaderAndFooter(
445 blink::WebCanvas* canvas,
446 int page_number,
447 int total_pages,
448 const blink::WebFrame& source_frame,
449 float webkit_scale_factor,
450 const PageSizeMargins& page_layout,
451 const PrintMsg_Print_Params& params) {
452 SkAutoCanvasRestore auto_restore(canvas, true);
453 canvas->scale(1 / webkit_scale_factor, 1 / webkit_scale_factor);
454
455 blink::WebSize page_size(page_layout.margin_left + page_layout.margin_right +
456 page_layout.content_width,
457 page_layout.margin_top + page_layout.margin_bottom +
458 page_layout.content_height);
459
460 blink::WebView* web_view = blink::WebView::create(NULL);
461 web_view->settings()->setJavaScriptEnabled(true);
462
463 blink::WebLocalFrame* frame = blink::WebLocalFrame::create(NULL);
464 web_view->setMainFrame(frame);
465
466 base::StringValue html(ResourceBundle::GetSharedInstance().GetLocalizedString(
467 IDR_PRINT_PREVIEW_PAGE));
468 // Load page with script to avoid async operations.
469 ExecuteScript(frame, kPageLoadScriptFormat, html);
470
471 scoped_ptr<base::DictionaryValue> options(new base::DictionaryValue());
472 options.reset(new base::DictionaryValue());
473 options->SetDouble(kSettingHeaderFooterDate, base::Time::Now().ToJsTime());
474 options->SetDouble("width", page_size.width);
475 options->SetDouble("height", page_size.height);
476 options->SetDouble("topMargin", page_layout.margin_top);
477 options->SetDouble("bottomMargin", page_layout.margin_bottom);
478 options->SetString("pageNumber",
479 base::StringPrintf("%d/%d", page_number, total_pages));
480
481 // Fallback to initiator URL and title if it's empty for printed frame.
482 base::string16 url = source_frame.document().url().string();
483 options->SetString("url", url.empty() ? params.url : url);
484 base::string16 title = source_frame.document().title();
485 options->SetString("title", title.empty() ? params.title : title);
486
487 ExecuteScript(frame, kPageSetupScriptFormat, *options);
488
489 blink::WebPrintParams webkit_params(page_size);
490 webkit_params.printerDPI = GetDPI(&params);
491
492 frame->printBegin(webkit_params);
493 frame->printPage(0, canvas);
494 frame->printEnd();
495
496 web_view->close();
497 frame->close();
498 }
499 #endif // defined(ENABLE_PRINT_PREVIEW)
500
501 // static - Not anonymous so that platform implementations can use it.
502 float PrintWebViewHelper::RenderPageContent(blink::WebFrame* frame,
503 int page_number,
504 const gfx::Rect& canvas_area,
505 const gfx::Rect& content_area,
506 double scale_factor,
507 blink::WebCanvas* canvas) {
508 SkAutoCanvasRestore auto_restore(canvas, true);
509 canvas->translate((content_area.x() - canvas_area.x()) / scale_factor,
510 (content_area.y() - canvas_area.y()) / scale_factor);
511 return frame->printPage(page_number, canvas);
512 }
513
514 // Class that calls the Begin and End print functions on the frame and changes
515 // the size of the view temporarily to support full page printing..
516 class PrepareFrameAndViewForPrint : public blink::WebViewClient,
517 public blink::WebFrameClient {
518 public:
519 PrepareFrameAndViewForPrint(const PrintMsg_Print_Params& params,
520 blink::WebLocalFrame* frame,
521 const blink::WebNode& node,
522 bool ignore_css_margins);
523 virtual ~PrepareFrameAndViewForPrint();
524
525 // Optional. Replaces |frame_| with selection if needed. Will call |on_ready|
526 // when completed.
527 void CopySelectionIfNeeded(const WebPreferences& preferences,
528 const base::Closure& on_ready);
529
530 // Prepares frame for printing.
531 void StartPrinting();
532
533 blink::WebLocalFrame* frame() {
534 return frame_.GetFrame();
535 }
536
537 const blink::WebNode& node() const {
538 return node_to_print_;
539 }
540
541 int GetExpectedPageCount() const {
542 return expected_pages_count_;
543 }
544
545 void FinishPrinting();
546
547 bool IsLoadingSelection() {
548 // It's not selection if not |owns_web_view_|.
549 return owns_web_view_ && frame() && frame()->isLoading();
550 }
551
552 // TODO(ojan): Remove this override and have this class use a non-null
553 // layerTreeView.
554 // blink::WebViewClient override:
555 virtual bool allowsBrokenNullLayerTreeView() const;
556
557 protected:
558 // blink::WebViewClient override:
559 virtual void didStopLoading();
560
561 // blink::WebFrameClient override:
562 virtual blink::WebFrame* createChildFrame(blink::WebLocalFrame* parent,
563 const blink::WebString& name);
564 virtual void frameDetached(blink::WebFrame* frame);
565
566 private:
567 void CallOnReady();
568 void ResizeForPrinting();
569 void RestoreSize();
570 void CopySelection(const WebPreferences& preferences);
571
572 FrameReference frame_;
573 blink::WebNode node_to_print_;
574 bool owns_web_view_;
575 blink::WebPrintParams web_print_params_;
576 gfx::Size prev_view_size_;
577 gfx::Size prev_scroll_offset_;
578 int expected_pages_count_;
579 base::Closure on_ready_;
580 bool should_print_backgrounds_;
581 bool should_print_selection_only_;
582 bool is_printing_started_;
583
584 base::WeakPtrFactory<PrepareFrameAndViewForPrint> weak_ptr_factory_;
585
586 DISALLOW_COPY_AND_ASSIGN(PrepareFrameAndViewForPrint);
587 };
588
589 PrepareFrameAndViewForPrint::PrepareFrameAndViewForPrint(
590 const PrintMsg_Print_Params& params,
591 blink::WebLocalFrame* frame,
592 const blink::WebNode& node,
593 bool ignore_css_margins)
594 : frame_(frame),
595 node_to_print_(node),
596 owns_web_view_(false),
597 expected_pages_count_(0),
598 should_print_backgrounds_(params.should_print_backgrounds),
599 should_print_selection_only_(params.selection_only),
600 is_printing_started_(false),
601 weak_ptr_factory_(this) {
602 PrintMsg_Print_Params print_params = params;
603 if (!should_print_selection_only_ ||
604 !PrintingNodeOrPdfFrame(frame, node_to_print_)) {
605 bool fit_to_page = ignore_css_margins &&
606 print_params.print_scaling_option ==
607 blink::WebPrintScalingOptionFitToPrintableArea;
608 ComputeWebKitPrintParamsInDesiredDpi(params, &web_print_params_);
609 frame->printBegin(web_print_params_, node_to_print_);
610 print_params = CalculatePrintParamsForCss(frame, 0, print_params,
611 ignore_css_margins, fit_to_page,
612 NULL);
613 frame->printEnd();
614 }
615 ComputeWebKitPrintParamsInDesiredDpi(print_params, &web_print_params_);
616 }
617
618 PrepareFrameAndViewForPrint::~PrepareFrameAndViewForPrint() {
619 FinishPrinting();
620 }
621
622 void PrepareFrameAndViewForPrint::ResizeForPrinting() {
623 // Layout page according to printer page size. Since WebKit shrinks the
624 // size of the page automatically (from 125% to 200%) we trick it to
625 // think the page is 125% larger so the size of the page is correct for
626 // minimum (default) scaling.
627 // This is important for sites that try to fill the page.
628 gfx::Size print_layout_size(web_print_params_.printContentArea.width,
629 web_print_params_.printContentArea.height);
630 print_layout_size.set_height(
631 static_cast<int>(static_cast<double>(print_layout_size.height()) * 1.25));
632
633 if (!frame())
634 return;
635 blink::WebView* web_view = frame_.view();
636 // Backup size and offset.
637 if (blink::WebFrame* web_frame = web_view->mainFrame())
638 prev_scroll_offset_ = web_frame->scrollOffset();
639 prev_view_size_ = web_view->size();
640
641 web_view->resize(print_layout_size);
642 }
643
644
645 void PrepareFrameAndViewForPrint::StartPrinting() {
646 ResizeForPrinting();
647 blink::WebView* web_view = frame_.view();
648 web_view->settings()->setShouldPrintBackgrounds(should_print_backgrounds_);
649 expected_pages_count_ =
650 frame()->printBegin(web_print_params_, node_to_print_);
651 is_printing_started_ = true;
652 }
653
654 void PrepareFrameAndViewForPrint::CopySelectionIfNeeded(
655 const WebPreferences& preferences,
656 const base::Closure& on_ready) {
657 on_ready_ = on_ready;
658 if (should_print_selection_only_) {
659 CopySelection(preferences);
660 } else {
661 // Call immediately, async call crashes scripting printing.
662 CallOnReady();
663 }
664 }
665
666 void PrepareFrameAndViewForPrint::CopySelection(
667 const WebPreferences& preferences) {
668 ResizeForPrinting();
669 std::string url_str = "data:text/html;charset=utf-8,";
670 url_str.append(
671 net::EscapeQueryParamValue(frame()->selectionAsMarkup().utf8(), false));
672 RestoreSize();
673 // Create a new WebView with the same settings as the current display one.
674 // Except that we disable javascript (don't want any active content running
675 // on the page).
676 WebPreferences prefs = preferences;
677 prefs.javascript_enabled = false;
678 prefs.java_enabled = false;
679
680 blink::WebView* web_view = blink::WebView::create(this);
681 owns_web_view_ = true;
682 content::RenderView::ApplyWebPreferences(prefs, web_view);
683 web_view->setMainFrame(blink::WebLocalFrame::create(this));
684 frame_.Reset(web_view->mainFrame()->toWebLocalFrame());
685 node_to_print_.reset();
686
687 // When loading is done this will call didStopLoading() and that will do the
688 // actual printing.
689 frame()->loadRequest(blink::WebURLRequest(GURL(url_str)));
690 }
691
692 bool PrepareFrameAndViewForPrint::allowsBrokenNullLayerTreeView() const {
693 return true;
694 }
695
696 void PrepareFrameAndViewForPrint::didStopLoading() {
697 DCHECK(!on_ready_.is_null());
698 // Don't call callback here, because it can delete |this| and WebView that is
699 // called didStopLoading.
700 base::MessageLoop::current()->PostTask(
701 FROM_HERE,
702 base::Bind(&PrepareFrameAndViewForPrint::CallOnReady,
703 weak_ptr_factory_.GetWeakPtr()));
704 }
705
706 blink::WebFrame* PrepareFrameAndViewForPrint::createChildFrame(
707 blink::WebLocalFrame* parent,
708 const blink::WebString& name) {
709 blink::WebFrame* frame = blink::WebLocalFrame::create(this);
710 parent->appendChild(frame);
711 return frame;
712 }
713
714 void PrepareFrameAndViewForPrint::frameDetached(blink::WebFrame* frame) {
715 if (frame->parent())
716 frame->parent()->removeChild(frame);
717 frame->close();
718 }
719
720 void PrepareFrameAndViewForPrint::CallOnReady() {
721 return on_ready_.Run(); // Can delete |this|.
722 }
723
724 void PrepareFrameAndViewForPrint::RestoreSize() {
725 if (frame()) {
726 blink::WebView* web_view = frame_.GetFrame()->view();
727 web_view->resize(prev_view_size_);
728 if (blink::WebFrame* web_frame = web_view->mainFrame())
729 web_frame->setScrollOffset(prev_scroll_offset_);
730 }
731 }
732
733 void PrepareFrameAndViewForPrint::FinishPrinting() {
734 blink::WebLocalFrame* frame = frame_.GetFrame();
735 if (frame) {
736 blink::WebView* web_view = frame->view();
737 if (is_printing_started_) {
738 is_printing_started_ = false;
739 frame->printEnd();
740 if (!owns_web_view_) {
741 web_view->settings()->setShouldPrintBackgrounds(false);
742 RestoreSize();
743 }
744 }
745 if (owns_web_view_) {
746 DCHECK(!frame->isLoading());
747 owns_web_view_ = false;
748 web_view->close();
749 }
750 }
751 frame_.Reset(NULL);
752 on_ready_.Reset();
753 }
754
755 PrintWebViewHelper::PrintWebViewHelper(
756 content::RenderView* render_view,
757 bool out_of_process_pdf_enabled,
758 bool print_preview_disabled,
759 scoped_ptr<Delegate> delegate)
760 : content::RenderViewObserver(render_view),
761 content::RenderViewObserverTracker<PrintWebViewHelper>(render_view),
762 reset_prep_frame_view_(false),
763 is_print_ready_metafile_sent_(false),
764 ignore_css_margins_(false),
765 is_scripted_printing_blocked_(false),
766 notify_browser_of_print_failure_(true),
767 print_for_preview_(false),
768 out_of_process_pdf_enabled_(out_of_process_pdf_enabled),
769 delegate_(delegate.Pass()),
770 print_node_in_progress_(false),
771 is_loading_(false),
772 is_scripted_preview_delayed_(false),
773 weak_ptr_factory_(this) {
774 if (print_preview_disabled)
775 DisablePreview();
776 }
777
778 PrintWebViewHelper::~PrintWebViewHelper() {}
779
780 // static
781 void PrintWebViewHelper::DisablePreview() {
782 g_is_preview_enabled_ = false;
783 }
784
785 bool PrintWebViewHelper::IsScriptInitiatedPrintAllowed(
786 blink::WebFrame* frame, bool user_initiated) {
787 // If preview is enabled, then the print dialog is tab modal, and the user
788 // can always close the tab on a mis-behaving page (the system print dialog
789 // is app modal). If the print was initiated through user action, don't
790 // throttle. Or, if the command line flag to skip throttling has been set.
791 return !is_scripted_printing_blocked_ &&
792 (user_initiated || g_is_preview_enabled_ ||
793 scripting_throttler_.IsAllowed(frame));
794 }
795
796 void PrintWebViewHelper::DidStartLoading() {
797 is_loading_ = true;
798 }
799
800 void PrintWebViewHelper::DidStopLoading() {
801 is_loading_ = false;
802 if (!on_stop_loading_closure_.is_null()) {
803 on_stop_loading_closure_.Run();
804 on_stop_loading_closure_.Reset();
805 }
806 }
807
808 // Prints |frame| which called window.print().
809 void PrintWebViewHelper::PrintPage(blink::WebLocalFrame* frame,
810 bool user_initiated) {
811 DCHECK(frame);
812
813 // Allow Prerendering to cancel this print request if necessary.
814 if (delegate_->CancelPrerender(render_view(), routing_id()))
815 return;
816
817 if (!IsScriptInitiatedPrintAllowed(frame, user_initiated))
818 return;
819
820 if (!g_is_preview_enabled_) {
821 Print(frame, blink::WebNode(), true);
822 } else {
823 print_preview_context_.InitWithFrame(frame);
824 RequestPrintPreview(PRINT_PREVIEW_SCRIPTED);
825 }
826 }
827
828 bool PrintWebViewHelper::OnMessageReceived(const IPC::Message& message) {
829 bool handled = true;
830 IPC_BEGIN_MESSAGE_MAP(PrintWebViewHelper, message)
831 #if defined(ENABLE_BASIC_PRINTING)
832 IPC_MESSAGE_HANDLER(PrintMsg_PrintPages, OnPrintPages)
833 IPC_MESSAGE_HANDLER(PrintMsg_PrintForSystemDialog, OnPrintForSystemDialog)
834 #endif // ENABLE_BASIC_PRINTING
835 IPC_MESSAGE_HANDLER(PrintMsg_InitiatePrintPreview, OnInitiatePrintPreview)
836 IPC_MESSAGE_HANDLER(PrintMsg_PrintPreview, OnPrintPreview)
837 IPC_MESSAGE_HANDLER(PrintMsg_PrintForPrintPreview, OnPrintForPrintPreview)
838 IPC_MESSAGE_HANDLER(PrintMsg_PrintingDone, OnPrintingDone)
839 IPC_MESSAGE_HANDLER(PrintMsg_SetScriptedPrintingBlocked,
840 SetScriptedPrintBlocked)
841 IPC_MESSAGE_UNHANDLED(handled = false)
842 IPC_END_MESSAGE_MAP()
843 return handled;
844 }
845
846 void PrintWebViewHelper::OnPrintForPrintPreview(
847 const base::DictionaryValue& job_settings) {
848 // If still not finished with earlier print request simply ignore.
849 if (prep_frame_view_)
850 return;
851
852 if (!render_view()->GetWebView())
853 return;
854 blink::WebFrame* main_frame = render_view()->GetWebView()->mainFrame();
855 if (!main_frame)
856 return;
857
858 blink::WebDocument document = main_frame->document();
859 // <object>/<iframe> with id="pdf-viewer" is created in
860 // chrome/browser/resources/print_preview/print_preview.js
861 blink::WebElement pdf_element = document.getElementById("pdf-viewer");
862 if (pdf_element.isNull()) {
863 NOTREACHED();
864 return;
865 }
866
867 // The out-of-process plugin element is nested within a frame. In tests, there
868 // may not be an iframe containing the out-of-process plugin, so continue with
869 // the element with ID "pdf-viewer" if it isn't an iframe.
870 blink::WebLocalFrame* plugin_frame = pdf_element.document().frame();
871 blink::WebElement plugin_element = pdf_element;
872 if (out_of_process_pdf_enabled_ && pdf_element.hasHTMLTagName("iframe")) {
873 plugin_frame = blink::WebLocalFrame::fromFrameOwnerElement(pdf_element);
874 plugin_element = delegate_->GetPdfElement(plugin_frame);
875 if (plugin_element.isNull()) {
876 NOTREACHED();
877 return;
878 }
879 }
880
881 // Set |print_for_preview_| flag and autoreset it to back to original
882 // on return.
883 base::AutoReset<bool> set_printing_flag(&print_for_preview_, true);
884
885 if (!UpdatePrintSettings(plugin_frame, plugin_element, job_settings)) {
886 LOG(ERROR) << "UpdatePrintSettings failed";
887 DidFinishPrinting(FAIL_PRINT);
888 return;
889 }
890
891 // Print page onto entire page not just printable area. Preview PDF already
892 // has content in correct position taking into account page size and printable
893 // area.
894 // TODO(vitalybuka) : Make this consistent on all platform. This change
895 // affects Windows only. On Linux and OSX RenderPagesForPrint does not use
896 // printable_area. Also we can't change printable_area deeper inside
897 // RenderPagesForPrint for Windows, because it's used also by native
898 // printing and it expects real printable_area value.
899 // See http://crbug.com/123408
900 PrintMsg_Print_Params& print_params = print_pages_params_->params;
901 print_params.printable_area = gfx::Rect(print_params.page_size);
902
903 // Render Pages for printing.
904 if (!RenderPagesForPrint(plugin_frame, plugin_element)) {
905 LOG(ERROR) << "RenderPagesForPrint failed";
906 DidFinishPrinting(FAIL_PRINT);
907 }
908 }
909
910 bool PrintWebViewHelper::GetPrintFrame(blink::WebLocalFrame** frame) {
911 DCHECK(frame);
912 blink::WebView* webView = render_view()->GetWebView();
913 DCHECK(webView);
914 if (!webView)
915 return false;
916
917 // If the user has selected text in the currently focused frame we print
918 // only that frame (this makes print selection work for multiple frames).
919 blink::WebLocalFrame* focusedFrame =
920 webView->focusedFrame()->toWebLocalFrame();
921 *frame = focusedFrame->hasSelection()
922 ? focusedFrame
923 : webView->mainFrame()->toWebLocalFrame();
924 return true;
925 }
926
927 #if defined(ENABLE_BASIC_PRINTING)
928 void PrintWebViewHelper::OnPrintPages() {
929 blink::WebLocalFrame* frame;
930 if (!GetPrintFrame(&frame))
931 return;
932 // If we are printing a PDF extension frame, find the plugin node and print
933 // that instead.
934 auto plugin = delegate_->GetPdfElement(frame);
935 Print(frame, plugin, false);
936 }
937
938 void PrintWebViewHelper::OnPrintForSystemDialog() {
939 blink::WebLocalFrame* frame = print_preview_context_.source_frame();
940 if (!frame) {
941 NOTREACHED();
942 return;
943 }
944 Print(frame, print_preview_context_.source_node(), false);
945 }
946 #endif // ENABLE_BASIC_PRINTING
947
948 void PrintWebViewHelper::GetPageSizeAndContentAreaFromPageLayout(
949 const PageSizeMargins& page_layout_in_points,
950 gfx::Size* page_size,
951 gfx::Rect* content_area) {
952 *page_size = gfx::Size(
953 page_layout_in_points.content_width +
954 page_layout_in_points.margin_right +
955 page_layout_in_points.margin_left,
956 page_layout_in_points.content_height +
957 page_layout_in_points.margin_top +
958 page_layout_in_points.margin_bottom);
959 *content_area = gfx::Rect(page_layout_in_points.margin_left,
960 page_layout_in_points.margin_top,
961 page_layout_in_points.content_width,
962 page_layout_in_points.content_height);
963 }
964
965 void PrintWebViewHelper::UpdateFrameMarginsCssInfo(
966 const base::DictionaryValue& settings) {
967 int margins_type = 0;
968 if (!settings.GetInteger(kSettingMarginsType, &margins_type))
969 margins_type = DEFAULT_MARGINS;
970 ignore_css_margins_ = (margins_type != DEFAULT_MARGINS);
971 }
972
973 bool PrintWebViewHelper::IsPrintToPdfRequested(
974 const base::DictionaryValue& job_settings) {
975 bool print_to_pdf = false;
976 if (!job_settings.GetBoolean(kSettingPrintToPDF, &print_to_pdf))
977 NOTREACHED();
978 return print_to_pdf;
979 }
980
981 void PrintWebViewHelper::OnPrintPreview(const base::DictionaryValue& settings) {
982 print_preview_context_.OnPrintPreview();
983
984 UMA_HISTOGRAM_ENUMERATION("PrintPreview.PreviewEvent",
985 PREVIEW_EVENT_REQUESTED, PREVIEW_EVENT_MAX);
986
987 if (!print_preview_context_.source_frame()) {
988 DidFinishPrinting(FAIL_PREVIEW);
989 return;
990 }
991
992 if (!UpdatePrintSettings(print_preview_context_.source_frame(),
993 print_preview_context_.source_node(), settings)) {
994 if (print_preview_context_.last_error() != PREVIEW_ERROR_BAD_SETTING) {
995 Send(new PrintHostMsg_PrintPreviewInvalidPrinterSettings(
996 routing_id(),
997 print_pages_params_ ?
998 print_pages_params_->params.document_cookie : 0));
999 notify_browser_of_print_failure_ = false; // Already sent.
1000 }
1001 DidFinishPrinting(FAIL_PREVIEW);
1002 return;
1003 }
1004
1005 // Set the options from document if we are previewing a pdf and send a
1006 // message to browser.
1007 if (print_pages_params_->params.is_first_request &&
1008 !print_preview_context_.IsModifiable()) {
1009 PrintHostMsg_SetOptionsFromDocument_Params params;
1010 SetOptionsFromDocument(params);
1011 Send(new PrintHostMsg_SetOptionsFromDocument(routing_id(), params));
1012 }
1013
1014 is_print_ready_metafile_sent_ = false;
1015
1016 // PDF printer device supports alpha blending.
1017 print_pages_params_->params.supports_alpha_blend = true;
1018
1019 bool generate_draft_pages = false;
1020 if (!settings.GetBoolean(kSettingGenerateDraftData,
1021 &generate_draft_pages)) {
1022 NOTREACHED();
1023 }
1024 print_preview_context_.set_generate_draft_pages(generate_draft_pages);
1025
1026 PrepareFrameForPreviewDocument();
1027 }
1028
1029 void PrintWebViewHelper::PrepareFrameForPreviewDocument() {
1030 reset_prep_frame_view_ = false;
1031
1032 if (!print_pages_params_ || CheckForCancel()) {
1033 DidFinishPrinting(FAIL_PREVIEW);
1034 return;
1035 }
1036
1037 // Don't reset loading frame or WebKit will fail assert. Just retry when
1038 // current selection is loaded.
1039 if (prep_frame_view_ && prep_frame_view_->IsLoadingSelection()) {
1040 reset_prep_frame_view_ = true;
1041 return;
1042 }
1043
1044 const PrintMsg_Print_Params& print_params = print_pages_params_->params;
1045 prep_frame_view_.reset(
1046 new PrepareFrameAndViewForPrint(print_params,
1047 print_preview_context_.source_frame(),
1048 print_preview_context_.source_node(),
1049 ignore_css_margins_));
1050 prep_frame_view_->CopySelectionIfNeeded(
1051 render_view()->GetWebkitPreferences(),
1052 base::Bind(&PrintWebViewHelper::OnFramePreparedForPreviewDocument,
1053 base::Unretained(this)));
1054 }
1055
1056 void PrintWebViewHelper::OnFramePreparedForPreviewDocument() {
1057 if (reset_prep_frame_view_) {
1058 PrepareFrameForPreviewDocument();
1059 return;
1060 }
1061 DidFinishPrinting(CreatePreviewDocument() ? OK : FAIL_PREVIEW);
1062 }
1063
1064 bool PrintWebViewHelper::CreatePreviewDocument() {
1065 if (!print_pages_params_ || CheckForCancel())
1066 return false;
1067
1068 UMA_HISTOGRAM_ENUMERATION("PrintPreview.PreviewEvent",
1069 PREVIEW_EVENT_CREATE_DOCUMENT, PREVIEW_EVENT_MAX);
1070
1071 const PrintMsg_Print_Params& print_params = print_pages_params_->params;
1072 const std::vector<int>& pages = print_pages_params_->pages;
1073
1074 if (!print_preview_context_.CreatePreviewDocument(prep_frame_view_.release(),
1075 pages)) {
1076 return false;
1077 }
1078
1079 PageSizeMargins default_page_layout;
1080 ComputePageLayoutInPointsForCss(print_preview_context_.prepared_frame(), 0,
1081 print_params, ignore_css_margins_, NULL,
1082 &default_page_layout);
1083
1084 bool has_page_size_style = PrintingFrameHasPageSizeStyle(
1085 print_preview_context_.prepared_frame(),
1086 print_preview_context_.total_page_count());
1087 int dpi = GetDPI(&print_params);
1088
1089 gfx::Rect printable_area_in_points(
1090 ConvertUnit(print_params.printable_area.x(), dpi, kPointsPerInch),
1091 ConvertUnit(print_params.printable_area.y(), dpi, kPointsPerInch),
1092 ConvertUnit(print_params.printable_area.width(), dpi, kPointsPerInch),
1093 ConvertUnit(print_params.printable_area.height(), dpi, kPointsPerInch));
1094
1095 // Margins: Send default page layout to browser process.
1096 Send(new PrintHostMsg_DidGetDefaultPageLayout(routing_id(),
1097 default_page_layout,
1098 printable_area_in_points,
1099 has_page_size_style));
1100
1101 PrintHostMsg_DidGetPreviewPageCount_Params params;
1102 params.page_count = print_preview_context_.total_page_count();
1103 params.is_modifiable = print_preview_context_.IsModifiable();
1104 params.document_cookie = print_params.document_cookie;
1105 params.preview_request_id = print_params.preview_request_id;
1106 params.clear_preview_data = print_preview_context_.generate_draft_pages();
1107 Send(new PrintHostMsg_DidGetPreviewPageCount(routing_id(), params));
1108 if (CheckForCancel())
1109 return false;
1110
1111 while (!print_preview_context_.IsFinalPageRendered()) {
1112 int page_number = print_preview_context_.GetNextPageNumber();
1113 DCHECK_GE(page_number, 0);
1114 if (!RenderPreviewPage(page_number, print_params))
1115 return false;
1116
1117 if (CheckForCancel())
1118 return false;
1119
1120 // We must call PrepareFrameAndViewForPrint::FinishPrinting() (by way of
1121 // print_preview_context_.AllPagesRendered()) before calling
1122 // FinalizePrintReadyDocument() when printing a PDF because the plugin
1123 // code does not generate output until we call FinishPrinting(). We do not
1124 // generate draft pages for PDFs, so IsFinalPageRendered() and
1125 // IsLastPageOfPrintReadyMetafile() will be true in the same iteration of
1126 // the loop.
1127 if (print_preview_context_.IsFinalPageRendered())
1128 print_preview_context_.AllPagesRendered();
1129
1130 if (print_preview_context_.IsLastPageOfPrintReadyMetafile()) {
1131 DCHECK(print_preview_context_.IsModifiable() ||
1132 print_preview_context_.IsFinalPageRendered());
1133 if (!FinalizePrintReadyDocument())
1134 return false;
1135 }
1136 }
1137 print_preview_context_.Finished();
1138 return true;
1139 }
1140
1141 bool PrintWebViewHelper::FinalizePrintReadyDocument() {
1142 DCHECK(!is_print_ready_metafile_sent_);
1143 print_preview_context_.FinalizePrintReadyDocument();
1144
1145 // Get the size of the resulting metafile.
1146 PdfMetafileSkia* metafile = print_preview_context_.metafile();
1147 uint32 buf_size = metafile->GetDataSize();
1148 DCHECK_GT(buf_size, 0u);
1149
1150 PrintHostMsg_DidPreviewDocument_Params preview_params;
1151 preview_params.data_size = buf_size;
1152 preview_params.document_cookie = print_pages_params_->params.document_cookie;
1153 preview_params.expected_pages_count =
1154 print_preview_context_.total_page_count();
1155 preview_params.modifiable = print_preview_context_.IsModifiable();
1156 preview_params.preview_request_id =
1157 print_pages_params_->params.preview_request_id;
1158
1159 // Ask the browser to create the shared memory for us.
1160 if (!CopyMetafileDataToSharedMem(metafile,
1161 &(preview_params.metafile_data_handle))) {
1162 LOG(ERROR) << "CopyMetafileDataToSharedMem failed";
1163 print_preview_context_.set_error(PREVIEW_ERROR_METAFILE_COPY_FAILED);
1164 return false;
1165 }
1166 is_print_ready_metafile_sent_ = true;
1167
1168 Send(new PrintHostMsg_MetafileReadyForPrinting(routing_id(), preview_params));
1169 return true;
1170 }
1171
1172 void PrintWebViewHelper::OnPrintingDone(bool success) {
1173 notify_browser_of_print_failure_ = false;
1174 if (!success)
1175 LOG(ERROR) << "Failure in OnPrintingDone";
1176 DidFinishPrinting(success ? OK : FAIL_PRINT);
1177 }
1178
1179 void PrintWebViewHelper::SetScriptedPrintBlocked(bool blocked) {
1180 is_scripted_printing_blocked_ = blocked;
1181 }
1182
1183 void PrintWebViewHelper::OnInitiatePrintPreview(bool selection_only) {
1184 blink::WebLocalFrame* frame = NULL;
1185 GetPrintFrame(&frame);
1186 DCHECK(frame);
1187 // If we are printing a PDF extension frame, find the plugin node and print
1188 // that instead.
1189 auto plugin = delegate_->GetPdfElement(frame);
1190 if (!plugin.isNull()) {
1191 PrintNode(plugin);
1192 return;
1193 }
1194 print_preview_context_.InitWithFrame(frame);
1195 RequestPrintPreview(selection_only ?
1196 PRINT_PREVIEW_USER_INITIATED_SELECTION :
1197 PRINT_PREVIEW_USER_INITIATED_ENTIRE_FRAME);
1198 }
1199
1200 bool PrintWebViewHelper::IsPrintingEnabled() {
1201 bool result = false;
1202 Send(new PrintHostMsg_IsPrintingEnabled(routing_id(), &result));
1203 return result;
1204 }
1205
1206 void PrintWebViewHelper::PrintNode(const blink::WebNode& node) {
1207 if (node.isNull() || !node.document().frame()) {
1208 // This can occur when the context menu refers to an invalid WebNode.
1209 // See http://crbug.com/100890#c17 for a repro case.
1210 return;
1211 }
1212
1213 if (print_node_in_progress_) {
1214 // This can happen as a result of processing sync messages when printing
1215 // from ppapi plugins. It's a rare case, so its OK to just fail here.
1216 // See http://crbug.com/159165.
1217 return;
1218 }
1219
1220 print_node_in_progress_ = true;
1221
1222 // Make a copy of the node, in case RenderView::OnContextMenuClosed resets
1223 // its |context_menu_node_|.
1224 if (!g_is_preview_enabled_) {
1225 blink::WebNode duplicate_node(node);
1226 Print(duplicate_node.document().frame(), duplicate_node, false);
1227 } else {
1228 print_preview_context_.InitWithNode(node);
1229 RequestPrintPreview(PRINT_PREVIEW_USER_INITIATED_CONTEXT_NODE);
1230 }
1231
1232 print_node_in_progress_ = false;
1233 }
1234
1235 void PrintWebViewHelper::Print(blink::WebLocalFrame* frame,
1236 const blink::WebNode& node,
1237 bool is_scripted) {
1238 // If still not finished with earlier print request simply ignore.
1239 if (prep_frame_view_)
1240 return;
1241
1242 FrameReference frame_ref(frame);
1243
1244 int expected_page_count = 0;
1245 if (!CalculateNumberOfPages(frame, node, &expected_page_count)) {
1246 DidFinishPrinting(FAIL_PRINT_INIT);
1247 return; // Failed to init print page settings.
1248 }
1249
1250 // Some full screen plugins can say they don't want to print.
1251 if (!expected_page_count) {
1252 DidFinishPrinting(FAIL_PRINT);
1253 return;
1254 }
1255
1256 // Ask the browser to show UI to retrieve the final print settings.
1257 if (!GetPrintSettingsFromUser(frame_ref.GetFrame(), node,
1258 expected_page_count,
1259 is_scripted)) {
1260 DidFinishPrinting(OK); // Release resources and fail silently.
1261 return;
1262 }
1263
1264 // Render Pages for printing.
1265 if (!RenderPagesForPrint(frame_ref.GetFrame(), node)) {
1266 LOG(ERROR) << "RenderPagesForPrint failed";
1267 DidFinishPrinting(FAIL_PRINT);
1268 }
1269 scripting_throttler_.Reset();
1270 }
1271
1272 void PrintWebViewHelper::DidFinishPrinting(PrintingResult result) {
1273 switch (result) {
1274 case OK:
1275 break;
1276
1277 case FAIL_PRINT_INIT:
1278 DCHECK(!notify_browser_of_print_failure_);
1279 break;
1280
1281 case FAIL_PRINT:
1282 if (notify_browser_of_print_failure_ && print_pages_params_) {
1283 int cookie = print_pages_params_->params.document_cookie;
1284 Send(new PrintHostMsg_PrintingFailed(routing_id(), cookie));
1285 }
1286 break;
1287
1288 case FAIL_PREVIEW:
1289 int cookie = print_pages_params_ ?
1290 print_pages_params_->params.document_cookie : 0;
1291 if (notify_browser_of_print_failure_) {
1292 LOG(ERROR) << "CreatePreviewDocument failed";
1293 Send(new PrintHostMsg_PrintPreviewFailed(routing_id(), cookie));
1294 } else {
1295 Send(new PrintHostMsg_PrintPreviewCancelled(routing_id(), cookie));
1296 }
1297 print_preview_context_.Failed(notify_browser_of_print_failure_);
1298 break;
1299 }
1300 prep_frame_view_.reset();
1301 print_pages_params_.reset();
1302 notify_browser_of_print_failure_ = true;
1303 }
1304
1305 void PrintWebViewHelper::OnFramePreparedForPrintPages() {
1306 PrintPages();
1307 FinishFramePrinting();
1308 }
1309
1310 void PrintWebViewHelper::PrintPages() {
1311 if (!prep_frame_view_) // Printing is already canceled or failed.
1312 return;
1313 prep_frame_view_->StartPrinting();
1314
1315 int page_count = prep_frame_view_->GetExpectedPageCount();
1316 if (!page_count) {
1317 LOG(ERROR) << "Can't print 0 pages.";
1318 return DidFinishPrinting(FAIL_PRINT);
1319 }
1320
1321 const PrintMsg_PrintPages_Params& params = *print_pages_params_;
1322 const PrintMsg_Print_Params& print_params = params.params;
1323
1324 #if !defined(OS_CHROMEOS) && !defined(OS_ANDROID)
1325 // TODO(vitalybuka): should be page_count or valid pages from params.pages.
1326 // See http://crbug.com/161576
1327 Send(new PrintHostMsg_DidGetPrintedPagesCount(routing_id(),
1328 print_params.document_cookie,
1329 page_count));
1330 #endif // !defined(OS_CHROMEOS)
1331
1332 if (print_params.preview_ui_id < 0) {
1333 // Printing for system dialog.
1334 int printed_count = params.pages.empty() ? page_count : params.pages.size();
1335 #if !defined(OS_CHROMEOS)
1336 UMA_HISTOGRAM_COUNTS("PrintPreview.PageCount.SystemDialog", printed_count);
1337 #else
1338 UMA_HISTOGRAM_COUNTS("PrintPreview.PageCount.PrintToCloudPrintWebDialog",
1339 printed_count);
1340 #endif // !defined(OS_CHROMEOS)
1341 }
1342
1343
1344 if (!PrintPagesNative(prep_frame_view_->frame(), page_count)) {
1345 LOG(ERROR) << "Printing failed.";
1346 return DidFinishPrinting(FAIL_PRINT);
1347 }
1348 }
1349
1350 void PrintWebViewHelper::FinishFramePrinting() {
1351 prep_frame_view_.reset();
1352 }
1353
1354 #if defined(OS_MACOSX)
1355 bool PrintWebViewHelper::PrintPagesNative(blink::WebFrame* frame,
1356 int page_count) {
1357 const PrintMsg_PrintPages_Params& params = *print_pages_params_;
1358 const PrintMsg_Print_Params& print_params = params.params;
1359
1360 PrintMsg_PrintPage_Params page_params;
1361 page_params.params = print_params;
1362 if (params.pages.empty()) {
1363 for (int i = 0; i < page_count; ++i) {
1364 page_params.page_number = i;
1365 PrintPageInternal(page_params, frame);
1366 }
1367 } else {
1368 for (size_t i = 0; i < params.pages.size(); ++i) {
1369 if (params.pages[i] >= page_count)
1370 break;
1371 page_params.page_number = params.pages[i];
1372 PrintPageInternal(page_params, frame);
1373 }
1374 }
1375 return true;
1376 }
1377
1378 #endif // OS_MACOSX
1379
1380 // static - Not anonymous so that platform implementations can use it.
1381 void PrintWebViewHelper::ComputePageLayoutInPointsForCss(
1382 blink::WebFrame* frame,
1383 int page_index,
1384 const PrintMsg_Print_Params& page_params,
1385 bool ignore_css_margins,
1386 double* scale_factor,
1387 PageSizeMargins* page_layout_in_points) {
1388 PrintMsg_Print_Params params = CalculatePrintParamsForCss(
1389 frame, page_index, page_params, ignore_css_margins,
1390 page_params.print_scaling_option ==
1391 blink::WebPrintScalingOptionFitToPrintableArea,
1392 scale_factor);
1393 CalculatePageLayoutFromPrintParams(params, page_layout_in_points);
1394 }
1395
1396 bool PrintWebViewHelper::InitPrintSettings(bool fit_to_paper_size) {
1397 PrintMsg_PrintPages_Params settings;
1398 Send(new PrintHostMsg_GetDefaultPrintSettings(routing_id(),
1399 &settings.params));
1400 // Check if the printer returned any settings, if the settings is empty, we
1401 // can safely assume there are no printer drivers configured. So we safely
1402 // terminate.
1403 bool result = true;
1404 if (!PrintMsg_Print_Params_IsValid(settings.params))
1405 result = false;
1406
1407 // Reset to default values.
1408 ignore_css_margins_ = false;
1409 settings.pages.clear();
1410
1411 settings.params.print_scaling_option =
1412 blink::WebPrintScalingOptionSourceSize;
1413 if (fit_to_paper_size) {
1414 settings.params.print_scaling_option =
1415 blink::WebPrintScalingOptionFitToPrintableArea;
1416 }
1417
1418 SetPrintPagesParams(settings);
1419 return result;
1420 }
1421
1422 bool PrintWebViewHelper::CalculateNumberOfPages(blink::WebLocalFrame* frame,
1423 const blink::WebNode& node,
1424 int* number_of_pages) {
1425 DCHECK(frame);
1426 bool fit_to_paper_size = !(PrintingNodeOrPdfFrame(frame, node));
1427 if (!InitPrintSettings(fit_to_paper_size)) {
1428 notify_browser_of_print_failure_ = false;
1429 Send(new PrintHostMsg_ShowInvalidPrinterSettingsError(routing_id()));
1430 return false;
1431 }
1432
1433 const PrintMsg_Print_Params& params = print_pages_params_->params;
1434 PrepareFrameAndViewForPrint prepare(params, frame, node, ignore_css_margins_);
1435 prepare.StartPrinting();
1436
1437 *number_of_pages = prepare.GetExpectedPageCount();
1438 return true;
1439 }
1440
1441 void PrintWebViewHelper::SetOptionsFromDocument(
1442 PrintHostMsg_SetOptionsFromDocument_Params& params) {
1443 blink::WebLocalFrame* source_frame = print_preview_context_.source_frame();
1444 const blink::WebNode& source_node = print_preview_context_.source_node();
1445
1446 blink::WebPrintPresetOptions preset_options;
1447 if (!source_frame->getPrintPresetOptionsForPlugin(source_node,
1448 &preset_options)) {
1449 return;
1450 }
1451
1452 params.is_scaling_disabled = preset_options.isScalingDisabled;
1453 params.copies = preset_options.copies;
1454 }
1455
1456 bool PrintWebViewHelper::UpdatePrintSettings(
1457 blink::WebLocalFrame* frame,
1458 const blink::WebNode& node,
1459 const base::DictionaryValue& passed_job_settings) {
1460 const base::DictionaryValue* job_settings = &passed_job_settings;
1461 base::DictionaryValue modified_job_settings;
1462 if (job_settings->empty()) {
1463 if (!print_for_preview_)
1464 print_preview_context_.set_error(PREVIEW_ERROR_BAD_SETTING);
1465 return false;
1466 }
1467
1468 bool source_is_html = true;
1469 if (print_for_preview_) {
1470 if (!job_settings->GetBoolean(kSettingPreviewModifiable, &source_is_html)) {
1471 NOTREACHED();
1472 }
1473 } else {
1474 source_is_html = !PrintingNodeOrPdfFrame(frame, node);
1475 }
1476
1477 if (print_for_preview_ || !source_is_html) {
1478 modified_job_settings.MergeDictionary(job_settings);
1479 modified_job_settings.SetBoolean(kSettingHeaderFooterEnabled, false);
1480 modified_job_settings.SetInteger(kSettingMarginsType, NO_MARGINS);
1481 job_settings = &modified_job_settings;
1482 }
1483
1484 // Send the cookie so that UpdatePrintSettings can reuse PrinterQuery when
1485 // possible.
1486 int cookie = print_pages_params_ ?
1487 print_pages_params_->params.document_cookie : 0;
1488 PrintMsg_PrintPages_Params settings;
1489 bool canceled = false;
1490 Send(new PrintHostMsg_UpdatePrintSettings(
1491 routing_id(), cookie, *job_settings, &settings, &canceled));
1492 if (canceled) {
1493 notify_browser_of_print_failure_ = false;
1494 return false;
1495 }
1496
1497 if (!job_settings->GetInteger(kPreviewUIID, &settings.params.preview_ui_id)) {
1498 NOTREACHED();
1499 print_preview_context_.set_error(PREVIEW_ERROR_BAD_SETTING);
1500 return false;
1501 }
1502
1503 if (!print_for_preview_) {
1504 // Validate expected print preview settings.
1505 if (!job_settings->GetInteger(kPreviewRequestID,
1506 &settings.params.preview_request_id) ||
1507 !job_settings->GetBoolean(kIsFirstRequest,
1508 &settings.params.is_first_request)) {
1509 NOTREACHED();
1510 print_preview_context_.set_error(PREVIEW_ERROR_BAD_SETTING);
1511 return false;
1512 }
1513
1514 settings.params.print_to_pdf = IsPrintToPdfRequested(*job_settings);
1515 UpdateFrameMarginsCssInfo(*job_settings);
1516 settings.params.print_scaling_option = GetPrintScalingOption(
1517 frame, node, source_is_html, *job_settings, settings.params);
1518 }
1519
1520 SetPrintPagesParams(settings);
1521
1522 if (!PrintMsg_Print_Params_IsValid(settings.params)) {
1523 if (!print_for_preview_)
1524 print_preview_context_.set_error(PREVIEW_ERROR_INVALID_PRINTER_SETTINGS);
1525 else
1526 Send(new PrintHostMsg_ShowInvalidPrinterSettingsError(routing_id()));
1527
1528 return false;
1529 }
1530
1531 return true;
1532 }
1533
1534 bool PrintWebViewHelper::GetPrintSettingsFromUser(blink::WebFrame* frame,
1535 const blink::WebNode& node,
1536 int expected_pages_count,
1537 bool is_scripted) {
1538 PrintHostMsg_ScriptedPrint_Params params;
1539 PrintMsg_PrintPages_Params print_settings;
1540
1541 params.cookie = print_pages_params_->params.document_cookie;
1542 params.has_selection = frame->hasSelection();
1543 params.expected_pages_count = expected_pages_count;
1544 MarginType margin_type = DEFAULT_MARGINS;
1545 if (PrintingNodeOrPdfFrame(frame, node))
1546 margin_type = GetMarginsForPdf(frame, node);
1547 params.margin_type = margin_type;
1548 params.is_scripted = is_scripted;
1549
1550 Send(new PrintHostMsg_DidShowPrintDialog(routing_id()));
1551
1552 // PrintHostMsg_ScriptedPrint will reset print_scaling_option, so we save the
1553 // value before and restore it afterwards.
1554 blink::WebPrintScalingOption scaling_option =
1555 print_pages_params_->params.print_scaling_option;
1556
1557 print_pages_params_.reset();
1558 IPC::SyncMessage* msg =
1559 new PrintHostMsg_ScriptedPrint(routing_id(), params, &print_settings);
1560 msg->EnableMessagePumping();
1561 Send(msg);
1562 print_settings.params.print_scaling_option = scaling_option;
1563 SetPrintPagesParams(print_settings);
1564 return (print_settings.params.dpi && print_settings.params.document_cookie);
1565 }
1566
1567 bool PrintWebViewHelper::RenderPagesForPrint(blink::WebLocalFrame* frame,
1568 const blink::WebNode& node) {
1569 if (!frame || prep_frame_view_)
1570 return false;
1571 const PrintMsg_PrintPages_Params& params = *print_pages_params_;
1572 const PrintMsg_Print_Params& print_params = params.params;
1573 prep_frame_view_.reset(new PrepareFrameAndViewForPrint(
1574 print_params, frame, node, ignore_css_margins_));
1575 DCHECK(!print_pages_params_->params.selection_only ||
1576 print_pages_params_->pages.empty());
1577 prep_frame_view_->CopySelectionIfNeeded(
1578 render_view()->GetWebkitPreferences(),
1579 base::Bind(&PrintWebViewHelper::OnFramePreparedForPrintPages,
1580 base::Unretained(this)));
1581 return true;
1582 }
1583
1584 #if defined(OS_POSIX)
1585 bool PrintWebViewHelper::CopyMetafileDataToSharedMem(
1586 PdfMetafileSkia* metafile,
1587 base::SharedMemoryHandle* shared_mem_handle) {
1588 uint32 buf_size = metafile->GetDataSize();
1589 scoped_ptr<base::SharedMemory> shared_buf(
1590 content::RenderThread::Get()->HostAllocateSharedMemoryBuffer(
1591 buf_size).release());
1592
1593 if (shared_buf) {
1594 if (shared_buf->Map(buf_size)) {
1595 metafile->GetData(shared_buf->memory(), buf_size);
1596 return shared_buf->GiveToProcess(base::GetCurrentProcessHandle(),
1597 shared_mem_handle);
1598 }
1599 }
1600 return false;
1601 }
1602 #endif // defined(OS_POSIX)
1603
1604 void PrintWebViewHelper::ShowScriptedPrintPreview() {
1605 if (is_scripted_preview_delayed_) {
1606 is_scripted_preview_delayed_ = false;
1607 Send(new PrintHostMsg_ShowScriptedPrintPreview(routing_id(),
1608 print_preview_context_.IsModifiable()));
1609 }
1610 }
1611
1612 void PrintWebViewHelper::RequestPrintPreview(PrintPreviewRequestType type) {
1613 const bool is_modifiable = print_preview_context_.IsModifiable();
1614 const bool has_selection = print_preview_context_.HasSelection();
1615 PrintHostMsg_RequestPrintPreview_Params params;
1616 params.is_modifiable = is_modifiable;
1617 params.has_selection = has_selection;
1618 switch (type) {
1619 case PRINT_PREVIEW_SCRIPTED: {
1620 // Shows scripted print preview in two stages.
1621 // 1. PrintHostMsg_SetupScriptedPrintPreview blocks this call and JS by
1622 // pumping messages here.
1623 // 2. PrintHostMsg_ShowScriptedPrintPreview shows preview once the
1624 // document has been loaded.
1625 is_scripted_preview_delayed_ = true;
1626 if (is_loading_ && GetPlugin(print_preview_context_.source_frame())) {
1627 // Wait for DidStopLoading. Plugins may not know the correct
1628 // |is_modifiable| value until they are fully loaded, which occurs when
1629 // DidStopLoading() is called. Defer showing the preview until then.
1630 on_stop_loading_closure_ =
1631 base::Bind(&PrintWebViewHelper::ShowScriptedPrintPreview,
1632 base::Unretained(this));
1633 } else {
1634 base::MessageLoop::current()->PostTask(
1635 FROM_HERE,
1636 base::Bind(&PrintWebViewHelper::ShowScriptedPrintPreview,
1637 weak_ptr_factory_.GetWeakPtr()));
1638 }
1639 IPC::SyncMessage* msg =
1640 new PrintHostMsg_SetupScriptedPrintPreview(routing_id());
1641 msg->EnableMessagePumping();
1642 Send(msg);
1643 is_scripted_preview_delayed_ = false;
1644 return;
1645 }
1646 case PRINT_PREVIEW_USER_INITIATED_ENTIRE_FRAME: {
1647 // Wait for DidStopLoading. Continuing with this function while
1648 // |is_loading_| is true will cause print preview to hang when try to
1649 // print a PDF document.
1650 if (is_loading_ && GetPlugin(print_preview_context_.source_frame())) {
1651 on_stop_loading_closure_ =
1652 base::Bind(&PrintWebViewHelper::RequestPrintPreview,
1653 base::Unretained(this),
1654 type);
1655 return;
1656 }
1657
1658 break;
1659 }
1660 case PRINT_PREVIEW_USER_INITIATED_SELECTION: {
1661 DCHECK(has_selection);
1662 DCHECK(!GetPlugin(print_preview_context_.source_frame()));
1663 params.selection_only = has_selection;
1664 break;
1665 }
1666 case PRINT_PREVIEW_USER_INITIATED_CONTEXT_NODE: {
1667 if (is_loading_ && GetPlugin(print_preview_context_.source_frame())) {
1668 on_stop_loading_closure_ =
1669 base::Bind(&PrintWebViewHelper::RequestPrintPreview,
1670 base::Unretained(this),
1671 type);
1672 return;
1673 }
1674
1675 params.webnode_only = true;
1676 break;
1677 }
1678 default: {
1679 NOTREACHED();
1680 return;
1681 }
1682 }
1683 Send(new PrintHostMsg_RequestPrintPreview(routing_id(), params));
1684 }
1685
1686 bool PrintWebViewHelper::CheckForCancel() {
1687 const PrintMsg_Print_Params& print_params = print_pages_params_->params;
1688 bool cancel = false;
1689 Send(new PrintHostMsg_CheckForCancel(routing_id(),
1690 print_params.preview_ui_id,
1691 print_params.preview_request_id,
1692 &cancel));
1693 if (cancel)
1694 notify_browser_of_print_failure_ = false;
1695 return cancel;
1696 }
1697
1698 bool PrintWebViewHelper::PreviewPageRendered(int page_number,
1699 PdfMetafileSkia* metafile) {
1700 DCHECK_GE(page_number, FIRST_PAGE_INDEX);
1701
1702 // For non-modifiable files, |metafile| should be NULL, so do not bother
1703 // sending a message. If we don't generate draft metafiles, |metafile| is
1704 // NULL.
1705 if (!print_preview_context_.IsModifiable() ||
1706 !print_preview_context_.generate_draft_pages()) {
1707 DCHECK(!metafile);
1708 return true;
1709 }
1710
1711 if (!metafile) {
1712 NOTREACHED();
1713 print_preview_context_.set_error(
1714 PREVIEW_ERROR_PAGE_RENDERED_WITHOUT_METAFILE);
1715 return false;
1716 }
1717
1718 PrintHostMsg_DidPreviewPage_Params preview_page_params;
1719 // Get the size of the resulting metafile.
1720 uint32 buf_size = metafile->GetDataSize();
1721 DCHECK_GT(buf_size, 0u);
1722 if (!CopyMetafileDataToSharedMem(
1723 metafile, &(preview_page_params.metafile_data_handle))) {
1724 LOG(ERROR) << "CopyMetafileDataToSharedMem failed";
1725 print_preview_context_.set_error(PREVIEW_ERROR_METAFILE_COPY_FAILED);
1726 return false;
1727 }
1728 preview_page_params.data_size = buf_size;
1729 preview_page_params.page_number = page_number;
1730 preview_page_params.preview_request_id =
1731 print_pages_params_->params.preview_request_id;
1732
1733 Send(new PrintHostMsg_DidPreviewPage(routing_id(), preview_page_params));
1734 return true;
1735 }
1736
1737 PrintWebViewHelper::PrintPreviewContext::PrintPreviewContext()
1738 : total_page_count_(0),
1739 current_page_index_(0),
1740 generate_draft_pages_(true),
1741 print_ready_metafile_page_count_(0),
1742 error_(PREVIEW_ERROR_NONE),
1743 state_(UNINITIALIZED) {
1744 }
1745
1746 PrintWebViewHelper::PrintPreviewContext::~PrintPreviewContext() {
1747 }
1748
1749 void PrintWebViewHelper::PrintPreviewContext::InitWithFrame(
1750 blink::WebLocalFrame* web_frame) {
1751 DCHECK(web_frame);
1752 DCHECK(!IsRendering());
1753 state_ = INITIALIZED;
1754 source_frame_.Reset(web_frame);
1755 source_node_.reset();
1756 }
1757
1758 void PrintWebViewHelper::PrintPreviewContext::InitWithNode(
1759 const blink::WebNode& web_node) {
1760 DCHECK(!web_node.isNull());
1761 DCHECK(web_node.document().frame());
1762 DCHECK(!IsRendering());
1763 state_ = INITIALIZED;
1764 source_frame_.Reset(web_node.document().frame());
1765 source_node_ = web_node;
1766 }
1767
1768 void PrintWebViewHelper::PrintPreviewContext::OnPrintPreview() {
1769 DCHECK_EQ(INITIALIZED, state_);
1770 ClearContext();
1771 }
1772
1773 bool PrintWebViewHelper::PrintPreviewContext::CreatePreviewDocument(
1774 PrepareFrameAndViewForPrint* prepared_frame,
1775 const std::vector<int>& pages) {
1776 DCHECK_EQ(INITIALIZED, state_);
1777 state_ = RENDERING;
1778
1779 // Need to make sure old object gets destroyed first.
1780 prep_frame_view_.reset(prepared_frame);
1781 prep_frame_view_->StartPrinting();
1782
1783 total_page_count_ = prep_frame_view_->GetExpectedPageCount();
1784 if (total_page_count_ == 0) {
1785 LOG(ERROR) << "CreatePreviewDocument got 0 page count";
1786 set_error(PREVIEW_ERROR_ZERO_PAGES);
1787 return false;
1788 }
1789
1790 metafile_.reset(new PdfMetafileSkia);
1791 if (!metafile_->Init()) {
1792 set_error(PREVIEW_ERROR_METAFILE_INIT_FAILED);
1793 LOG(ERROR) << "PdfMetafileSkia Init failed";
1794 return false;
1795 }
1796
1797 current_page_index_ = 0;
1798 pages_to_render_ = pages;
1799 // Sort and make unique.
1800 std::sort(pages_to_render_.begin(), pages_to_render_.end());
1801 pages_to_render_.resize(std::unique(pages_to_render_.begin(),
1802 pages_to_render_.end()) -
1803 pages_to_render_.begin());
1804 // Remove invalid pages.
1805 pages_to_render_.resize(std::lower_bound(pages_to_render_.begin(),
1806 pages_to_render_.end(),
1807 total_page_count_) -
1808 pages_to_render_.begin());
1809 print_ready_metafile_page_count_ = pages_to_render_.size();
1810 if (pages_to_render_.empty()) {
1811 print_ready_metafile_page_count_ = total_page_count_;
1812 // Render all pages.
1813 for (int i = 0; i < total_page_count_; ++i)
1814 pages_to_render_.push_back(i);
1815 } else if (generate_draft_pages_) {
1816 int pages_index = 0;
1817 for (int i = 0; i < total_page_count_; ++i) {
1818 if (pages_index < print_ready_metafile_page_count_ &&
1819 i == pages_to_render_[pages_index]) {
1820 pages_index++;
1821 continue;
1822 }
1823 pages_to_render_.push_back(i);
1824 }
1825 }
1826
1827 document_render_time_ = base::TimeDelta();
1828 begin_time_ = base::TimeTicks::Now();
1829
1830 return true;
1831 }
1832
1833 void PrintWebViewHelper::PrintPreviewContext::RenderedPreviewPage(
1834 const base::TimeDelta& page_time) {
1835 DCHECK_EQ(RENDERING, state_);
1836 document_render_time_ += page_time;
1837 UMA_HISTOGRAM_TIMES("PrintPreview.RenderPDFPageTime", page_time);
1838 }
1839
1840 void PrintWebViewHelper::PrintPreviewContext::AllPagesRendered() {
1841 DCHECK_EQ(RENDERING, state_);
1842 state_ = DONE;
1843 prep_frame_view_->FinishPrinting();
1844 }
1845
1846 void PrintWebViewHelper::PrintPreviewContext::FinalizePrintReadyDocument() {
1847 DCHECK(IsRendering());
1848
1849 base::TimeTicks begin_time = base::TimeTicks::Now();
1850 metafile_->FinishDocument();
1851
1852 if (print_ready_metafile_page_count_ <= 0) {
1853 NOTREACHED();
1854 return;
1855 }
1856
1857 UMA_HISTOGRAM_MEDIUM_TIMES("PrintPreview.RenderToPDFTime",
1858 document_render_time_);
1859 base::TimeDelta total_time = (base::TimeTicks::Now() - begin_time) +
1860 document_render_time_;
1861 UMA_HISTOGRAM_MEDIUM_TIMES("PrintPreview.RenderAndGeneratePDFTime",
1862 total_time);
1863 UMA_HISTOGRAM_MEDIUM_TIMES("PrintPreview.RenderAndGeneratePDFTimeAvgPerPage",
1864 total_time / pages_to_render_.size());
1865 }
1866
1867 void PrintWebViewHelper::PrintPreviewContext::Finished() {
1868 DCHECK_EQ(DONE, state_);
1869 state_ = INITIALIZED;
1870 ClearContext();
1871 }
1872
1873 void PrintWebViewHelper::PrintPreviewContext::Failed(bool report_error) {
1874 DCHECK(state_ == INITIALIZED || state_ == RENDERING);
1875 state_ = INITIALIZED;
1876 if (report_error) {
1877 DCHECK_NE(PREVIEW_ERROR_NONE, error_);
1878 UMA_HISTOGRAM_ENUMERATION("PrintPreview.RendererError", error_,
1879 PREVIEW_ERROR_LAST_ENUM);
1880 }
1881 ClearContext();
1882 }
1883
1884 int PrintWebViewHelper::PrintPreviewContext::GetNextPageNumber() {
1885 DCHECK_EQ(RENDERING, state_);
1886 if (IsFinalPageRendered())
1887 return -1;
1888 return pages_to_render_[current_page_index_++];
1889 }
1890
1891 bool PrintWebViewHelper::PrintPreviewContext::IsRendering() const {
1892 return state_ == RENDERING || state_ == DONE;
1893 }
1894
1895 bool PrintWebViewHelper::PrintPreviewContext::IsModifiable() {
1896 // The only kind of node we can print right now is a PDF node.
1897 return !PrintingNodeOrPdfFrame(source_frame(), source_node_);
1898 }
1899
1900 bool PrintWebViewHelper::PrintPreviewContext::HasSelection() {
1901 return IsModifiable() && source_frame()->hasSelection();
1902 }
1903
1904 bool PrintWebViewHelper::PrintPreviewContext::IsLastPageOfPrintReadyMetafile()
1905 const {
1906 DCHECK(IsRendering());
1907 return current_page_index_ == print_ready_metafile_page_count_;
1908 }
1909
1910 bool PrintWebViewHelper::PrintPreviewContext::IsFinalPageRendered() const {
1911 DCHECK(IsRendering());
1912 return static_cast<size_t>(current_page_index_) == pages_to_render_.size();
1913 }
1914
1915 void PrintWebViewHelper::PrintPreviewContext::set_generate_draft_pages(
1916 bool generate_draft_pages) {
1917 DCHECK_EQ(INITIALIZED, state_);
1918 generate_draft_pages_ = generate_draft_pages;
1919 }
1920
1921 void PrintWebViewHelper::PrintPreviewContext::set_error(
1922 enum PrintPreviewErrorBuckets error) {
1923 error_ = error;
1924 }
1925
1926 blink::WebLocalFrame* PrintWebViewHelper::PrintPreviewContext::source_frame() {
1927 DCHECK(state_ != UNINITIALIZED);
1928 return source_frame_.GetFrame();
1929 }
1930
1931 const blink::WebNode&
1932 PrintWebViewHelper::PrintPreviewContext::source_node() const {
1933 DCHECK(state_ != UNINITIALIZED);
1934 return source_node_;
1935 }
1936
1937 blink::WebLocalFrame*
1938 PrintWebViewHelper::PrintPreviewContext::prepared_frame() {
1939 DCHECK(state_ != UNINITIALIZED);
1940 return prep_frame_view_->frame();
1941 }
1942
1943 const blink::WebNode&
1944 PrintWebViewHelper::PrintPreviewContext::prepared_node() const {
1945 DCHECK(state_ != UNINITIALIZED);
1946 return prep_frame_view_->node();
1947 }
1948
1949 int PrintWebViewHelper::PrintPreviewContext::total_page_count() const {
1950 DCHECK(state_ != UNINITIALIZED);
1951 return total_page_count_;
1952 }
1953
1954 bool PrintWebViewHelper::PrintPreviewContext::generate_draft_pages() const {
1955 return generate_draft_pages_;
1956 }
1957
1958 PdfMetafileSkia* PrintWebViewHelper::PrintPreviewContext::metafile() {
1959 DCHECK(IsRendering());
1960 return metafile_.get();
1961 }
1962
1963 int PrintWebViewHelper::PrintPreviewContext::last_error() const {
1964 return error_;
1965 }
1966
1967 void PrintWebViewHelper::PrintPreviewContext::ClearContext() {
1968 prep_frame_view_.reset();
1969 metafile_.reset();
1970 pages_to_render_.clear();
1971 error_ = PREVIEW_ERROR_NONE;
1972 }
1973
1974 void PrintWebViewHelper::SetPrintPagesParams(
1975 const PrintMsg_PrintPages_Params& settings) {
1976 print_pages_params_.reset(new PrintMsg_PrintPages_Params(settings));
1977 Send(new PrintHostMsg_DidGetDocumentCookie(routing_id(),
1978 settings.params.document_cookie));
1979 }
1980
1981 PrintWebViewHelper::ScriptingThrottler::ScriptingThrottler() : count_(0) {
1982 }
1983
1984 bool PrintWebViewHelper::ScriptingThrottler::IsAllowed(blink::WebFrame* frame) {
1985 const int kMinSecondsToIgnoreJavascriptInitiatedPrint = 2;
1986 const int kMaxSecondsToIgnoreJavascriptInitiatedPrint = 32;
1987 bool too_frequent = false;
1988
1989 // Check if there is script repeatedly trying to print and ignore it if too
1990 // frequent. The first 3 times, we use a constant wait time, but if this
1991 // gets excessive, we switch to exponential wait time. So for a page that
1992 // calls print() in a loop the user will need to cancel the print dialog
1993 // after: [2, 2, 2, 4, 8, 16, 32, 32, ...] seconds.
1994 // This gives the user time to navigate from the page.
1995 if (count_ > 0) {
1996 base::TimeDelta diff = base::Time::Now() - last_print_;
1997 int min_wait_seconds = kMinSecondsToIgnoreJavascriptInitiatedPrint;
1998 if (count_ > 3) {
1999 min_wait_seconds =
2000 std::min(kMinSecondsToIgnoreJavascriptInitiatedPrint << (count_ - 3),
2001 kMaxSecondsToIgnoreJavascriptInitiatedPrint);
2002 }
2003 if (diff.InSeconds() < min_wait_seconds) {
2004 too_frequent = true;
2005 }
2006 }
2007
2008 if (!too_frequent) {
2009 ++count_;
2010 last_print_ = base::Time::Now();
2011 return true;
2012 }
2013
2014 blink::WebString message(
2015 blink::WebString::fromUTF8("Ignoring too frequent calls to print()."));
2016 frame->addMessageToConsole(blink::WebConsoleMessage(
2017 blink::WebConsoleMessage::LevelWarning, message));
2018 return false;
2019 }
2020
2021 void PrintWebViewHelper::ScriptingThrottler::Reset() {
2022 // Reset counter on successful print.
2023 count_ = 0;
2024 }
2025
2026 } // namespace printing
OLDNEW

Powered by Google App Engine
This is Rietveld 408576698