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/renderer/printing/print_web_view_helper.h"
9 #include "base/auto_reset.h"
10 #include "base/command_line.h"
11 #include "base/json/json_writer.h"
12 #include "base/logging.h"
13 #include "base/message_loop/message_loop.h"
14 #include "base/metrics/histogram.h"
15 #include "base/process/process_handle.h"
16 #include "base/strings/string_number_conversions.h"
17 #include "base/strings/stringprintf.h"
18 #include "base/strings/utf_string_conversions.h"
19 #include "chrome/common/chrome_switches.h"
20 #include "chrome/common/print_messages.h"
21 #include "chrome/common/render_messages.h"
22 #include "chrome/grit/browser_resources.h"
23 #include "chrome/renderer/prerender/prerender_helper.h"
24 #include "content/public/common/web_preferences.h"
25 #include "content/public/renderer/render_frame.h"
26 #include "content/public/renderer/render_thread.h"
27 #include "content/public/renderer/render_view.h"
28 #include "net/base/escape.h"
29 #include "printing/pdf_metafile_skia.h"
30 #include "printing/units.h"
31 #include "skia/ext/vector_platform_device_skia.h"
32 #include "third_party/WebKit/public/platform/WebSize.h"
33 #include "third_party/WebKit/public/platform/WebURLRequest.h"
34 #include "third_party/WebKit/public/web/WebConsoleMessage.h"
35 #include "third_party/WebKit/public/web/WebDocument.h"
36 #include "third_party/WebKit/public/web/WebElement.h"
37 #include "third_party/WebKit/public/web/WebFrameClient.h"
38 #include "third_party/WebKit/public/web/WebLocalFrame.h"
39 #include "third_party/WebKit/public/web/WebPlugin.h"
40 #include "third_party/WebKit/public/web/WebPluginDocument.h"
41 #include "third_party/WebKit/public/web/WebPrintParams.h"
42 #include "third_party/WebKit/public/web/WebPrintScalingOption.h"
43 #include "third_party/WebKit/public/web/WebScriptSource.h"
44 #include "third_party/WebKit/public/web/WebSettings.h"
45 #include "third_party/WebKit/public/web/WebView.h"
46 #include "third_party/WebKit/public/web/WebViewClient.h"
47 #include "ui/base/resource/resource_bundle.h"
49 using content::WebPreferences;
55 enum PrintPreviewHelperEvents {
56 PREVIEW_EVENT_REQUESTED,
57 PREVIEW_EVENT_CACHE_HIT, // Unused
58 PREVIEW_EVENT_CREATE_DOCUMENT,
59 PREVIEW_EVENT_NEW_SETTINGS, // Unused
63 const double kMinDpi = 1.0;
65 #if !defined(ENABLE_PRINT_PREVIEW)
66 bool g_is_preview_enabled_ = false;
68 bool g_is_preview_enabled_ = true;
70 const char kPageLoadScriptFormat[] =
71 "document.open(); document.write(%s); document.close();";
73 const char kPageSetupScriptFormat[] = "setup(%s);";
75 void ExecuteScript(blink::WebFrame* frame,
76 const char* script_format,
77 const base::Value& parameters) {
79 base::JSONWriter::Write(¶meters, &json);
80 std::string script = base::StringPrintf(script_format, json.c_str());
81 frame->executeScript(blink::WebString(base::UTF8ToUTF16(script)));
83 #endif // !defined(ENABLE_PRINT_PREVIEW)
85 int GetDPI(const PrintMsg_Print_Params* print_params) {
86 #if defined(OS_MACOSX)
87 // On the Mac, the printable area is in points, don't do any scaling based
89 return kPointsPerInch;
91 return static_cast<int>(print_params->dpi);
92 #endif // defined(OS_MACOSX)
95 bool PrintMsg_Print_Params_IsValid(const PrintMsg_Print_Params& params) {
96 return !params.content_size.IsEmpty() && !params.page_size.IsEmpty() &&
97 !params.printable_area.IsEmpty() && params.document_cookie &&
98 params.desired_dpi && params.max_shrink && params.min_shrink &&
99 params.dpi && (params.margin_top >= 0) && (params.margin_left >= 0) &&
100 params.dpi > kMinDpi && params.document_cookie != 0;
103 PrintMsg_Print_Params GetCssPrintParams(
104 blink::WebFrame* frame,
106 const PrintMsg_Print_Params& page_params) {
107 PrintMsg_Print_Params page_css_params = page_params;
108 int dpi = GetDPI(&page_params);
110 blink::WebSize page_size_in_pixels(
111 ConvertUnit(page_params.page_size.width(), dpi, kPixelsPerInch),
112 ConvertUnit(page_params.page_size.height(), dpi, kPixelsPerInch));
113 int margin_top_in_pixels =
114 ConvertUnit(page_params.margin_top, dpi, kPixelsPerInch);
115 int margin_right_in_pixels = ConvertUnit(
116 page_params.page_size.width() -
117 page_params.content_size.width() - page_params.margin_left,
118 dpi, kPixelsPerInch);
119 int margin_bottom_in_pixels = ConvertUnit(
120 page_params.page_size.height() -
121 page_params.content_size.height() - page_params.margin_top,
122 dpi, kPixelsPerInch);
123 int margin_left_in_pixels = ConvertUnit(
124 page_params.margin_left,
125 dpi, kPixelsPerInch);
127 blink::WebSize original_page_size_in_pixels = page_size_in_pixels;
130 frame->pageSizeAndMarginsInPixels(page_index,
132 margin_top_in_pixels,
133 margin_right_in_pixels,
134 margin_bottom_in_pixels,
135 margin_left_in_pixels);
138 int new_content_width = page_size_in_pixels.width -
139 margin_left_in_pixels - margin_right_in_pixels;
140 int new_content_height = page_size_in_pixels.height -
141 margin_top_in_pixels - margin_bottom_in_pixels;
143 // Invalid page size and/or margins. We just use the default setting.
144 if (new_content_width < 1 || new_content_height < 1) {
145 CHECK(frame != NULL);
146 page_css_params = GetCssPrintParams(NULL, page_index, page_params);
147 return page_css_params;
150 page_css_params.content_size = gfx::Size(
151 ConvertUnit(new_content_width, kPixelsPerInch, dpi),
152 ConvertUnit(new_content_height, kPixelsPerInch, dpi));
154 if (original_page_size_in_pixels != page_size_in_pixels) {
155 page_css_params.page_size = gfx::Size(
156 ConvertUnit(page_size_in_pixels.width, kPixelsPerInch, dpi),
157 ConvertUnit(page_size_in_pixels.height, kPixelsPerInch, dpi));
159 // Printing frame doesn't have any page size css. Pixels to dpi conversion
160 // causes rounding off errors. Therefore use the default page size values
162 page_css_params.page_size = page_params.page_size;
165 page_css_params.margin_top =
166 ConvertUnit(margin_top_in_pixels, kPixelsPerInch, dpi);
167 page_css_params.margin_left =
168 ConvertUnit(margin_left_in_pixels, kPixelsPerInch, dpi);
169 return page_css_params;
172 double FitPrintParamsToPage(const PrintMsg_Print_Params& page_params,
173 PrintMsg_Print_Params* params_to_fit) {
174 double content_width =
175 static_cast<double>(params_to_fit->content_size.width());
176 double content_height =
177 static_cast<double>(params_to_fit->content_size.height());
178 int default_page_size_height = page_params.page_size.height();
179 int default_page_size_width = page_params.page_size.width();
180 int css_page_size_height = params_to_fit->page_size.height();
181 int css_page_size_width = params_to_fit->page_size.width();
183 double scale_factor = 1.0f;
184 if (page_params.page_size == params_to_fit->page_size)
187 if (default_page_size_width < css_page_size_width ||
188 default_page_size_height < css_page_size_height) {
190 static_cast<double>(default_page_size_width) / css_page_size_width;
191 double ratio_height =
192 static_cast<double>(default_page_size_height) / css_page_size_height;
193 scale_factor = ratio_width < ratio_height ? ratio_width : ratio_height;
194 content_width *= scale_factor;
195 content_height *= scale_factor;
197 params_to_fit->margin_top = static_cast<int>(
198 (default_page_size_height - css_page_size_height * scale_factor) / 2 +
199 (params_to_fit->margin_top * scale_factor));
200 params_to_fit->margin_left = static_cast<int>(
201 (default_page_size_width - css_page_size_width * scale_factor) / 2 +
202 (params_to_fit->margin_left * scale_factor));
203 params_to_fit->content_size = gfx::Size(
204 static_cast<int>(content_width), static_cast<int>(content_height));
205 params_to_fit->page_size = page_params.page_size;
209 void CalculatePageLayoutFromPrintParams(
210 const PrintMsg_Print_Params& params,
211 PageSizeMargins* page_layout_in_points) {
212 int dpi = GetDPI(¶ms);
213 int content_width = params.content_size.width();
214 int content_height = params.content_size.height();
216 int margin_bottom = params.page_size.height() -
217 content_height - params.margin_top;
218 int margin_right = params.page_size.width() -
219 content_width - params.margin_left;
221 page_layout_in_points->content_width =
222 ConvertUnit(content_width, dpi, kPointsPerInch);
223 page_layout_in_points->content_height =
224 ConvertUnit(content_height, dpi, kPointsPerInch);
225 page_layout_in_points->margin_top =
226 ConvertUnit(params.margin_top, dpi, kPointsPerInch);
227 page_layout_in_points->margin_right =
228 ConvertUnit(margin_right, dpi, kPointsPerInch);
229 page_layout_in_points->margin_bottom =
230 ConvertUnit(margin_bottom, dpi, kPointsPerInch);
231 page_layout_in_points->margin_left =
232 ConvertUnit(params.margin_left, dpi, kPointsPerInch);
235 void EnsureOrientationMatches(const PrintMsg_Print_Params& css_params,
236 PrintMsg_Print_Params* page_params) {
237 if ((page_params->page_size.width() > page_params->page_size.height()) ==
238 (css_params.page_size.width() > css_params.page_size.height())) {
242 // Swap the |width| and |height| values.
243 page_params->page_size.SetSize(page_params->page_size.height(),
244 page_params->page_size.width());
245 page_params->content_size.SetSize(page_params->content_size.height(),
246 page_params->content_size.width());
247 page_params->printable_area.set_size(
248 gfx::Size(page_params->printable_area.height(),
249 page_params->printable_area.width()));
252 void ComputeWebKitPrintParamsInDesiredDpi(
253 const PrintMsg_Print_Params& print_params,
254 blink::WebPrintParams* webkit_print_params) {
255 int dpi = GetDPI(&print_params);
256 webkit_print_params->printerDPI = dpi;
257 webkit_print_params->printScalingOption = print_params.print_scaling_option;
259 webkit_print_params->printContentArea.width =
260 ConvertUnit(print_params.content_size.width(), dpi,
261 print_params.desired_dpi);
262 webkit_print_params->printContentArea.height =
263 ConvertUnit(print_params.content_size.height(), dpi,
264 print_params.desired_dpi);
266 webkit_print_params->printableArea.x =
267 ConvertUnit(print_params.printable_area.x(), dpi,
268 print_params.desired_dpi);
269 webkit_print_params->printableArea.y =
270 ConvertUnit(print_params.printable_area.y(), dpi,
271 print_params.desired_dpi);
272 webkit_print_params->printableArea.width =
273 ConvertUnit(print_params.printable_area.width(), dpi,
274 print_params.desired_dpi);
275 webkit_print_params->printableArea.height =
276 ConvertUnit(print_params.printable_area.height(),
277 dpi, print_params.desired_dpi);
279 webkit_print_params->paperSize.width =
280 ConvertUnit(print_params.page_size.width(), dpi,
281 print_params.desired_dpi);
282 webkit_print_params->paperSize.height =
283 ConvertUnit(print_params.page_size.height(), dpi,
284 print_params.desired_dpi);
287 blink::WebPlugin* GetPlugin(const blink::WebFrame* frame) {
288 return frame->document().isPluginDocument() ?
289 frame->document().to<blink::WebPluginDocument>().plugin() : NULL;
292 bool PrintingNodeOrPdfFrame(const blink::WebFrame* frame,
293 const blink::WebNode& node) {
296 blink::WebPlugin* plugin = GetPlugin(frame);
297 return plugin && plugin->supportsPaginatedPrint();
300 bool PrintingFrameHasPageSizeStyle(blink::WebFrame* frame,
301 int total_page_count) {
304 bool frame_has_custom_page_size_style = false;
305 for (int i = 0; i < total_page_count; ++i) {
306 if (frame->hasCustomPageSizeStyle(i)) {
307 frame_has_custom_page_size_style = true;
311 return frame_has_custom_page_size_style;
314 MarginType GetMarginsForPdf(blink::WebFrame* frame,
315 const blink::WebNode& node) {
316 if (frame->isPrintScalingDisabledForPlugin(node))
319 return PRINTABLE_AREA_MARGINS;
322 bool FitToPageEnabled(const base::DictionaryValue& job_settings) {
323 bool fit_to_paper_size = false;
324 if (!job_settings.GetBoolean(kSettingFitToPageEnabled, &fit_to_paper_size)) {
327 return fit_to_paper_size;
330 // Returns the print scaling option to retain/scale/crop the source page size
331 // to fit the printable area of the paper.
333 // We retain the source page size when the current destination printer is
336 // We crop the source page size to fit the printable area or we print only the
337 // left top page contents when
338 // (1) Source is PDF and the user has requested not to fit to printable area
339 // via |job_settings|.
340 // (2) Source is PDF. This is the first preview request and print scaling
341 // option is disabled for initiator renderer plugin.
343 // In all other cases, we scale the source page to fit the printable area.
344 blink::WebPrintScalingOption GetPrintScalingOption(
345 blink::WebFrame* frame,
346 const blink::WebNode& node,
348 const base::DictionaryValue& job_settings,
349 const PrintMsg_Print_Params& params) {
350 if (params.print_to_pdf)
351 return blink::WebPrintScalingOptionSourceSize;
353 if (!source_is_html) {
354 if (!FitToPageEnabled(job_settings))
355 return blink::WebPrintScalingOptionNone;
357 bool no_plugin_scaling = frame->isPrintScalingDisabledForPlugin(node);
359 if (params.is_first_request && no_plugin_scaling)
360 return blink::WebPrintScalingOptionNone;
362 return blink::WebPrintScalingOptionFitToPrintableArea;
365 PrintMsg_Print_Params CalculatePrintParamsForCss(
366 blink::WebFrame* frame,
368 const PrintMsg_Print_Params& page_params,
369 bool ignore_css_margins,
371 double* scale_factor) {
372 PrintMsg_Print_Params css_params = GetCssPrintParams(frame, page_index,
375 PrintMsg_Print_Params params = page_params;
376 EnsureOrientationMatches(css_params, ¶ms);
378 if (ignore_css_margins && fit_to_page)
381 PrintMsg_Print_Params result_params = css_params;
382 if (ignore_css_margins) {
383 result_params.margin_top = params.margin_top;
384 result_params.margin_left = params.margin_left;
386 DCHECK(!fit_to_page);
387 // Since we are ignoring the margins, the css page size is no longer
389 int default_margin_right = params.page_size.width() -
390 params.content_size.width() - params.margin_left;
391 int default_margin_bottom = params.page_size.height() -
392 params.content_size.height() - params.margin_top;
393 result_params.content_size = gfx::Size(
394 result_params.page_size.width() - result_params.margin_left -
395 default_margin_right,
396 result_params.page_size.height() - result_params.margin_top -
397 default_margin_bottom);
401 double factor = FitPrintParamsToPage(params, &result_params);
403 *scale_factor = factor;
405 return result_params;
410 FrameReference::FrameReference(blink::WebLocalFrame* frame) {
414 FrameReference::FrameReference() {
418 FrameReference::~FrameReference() {
421 void FrameReference::Reset(blink::WebLocalFrame* frame) {
423 view_ = frame->view();
431 blink::WebLocalFrame* FrameReference::GetFrame() {
432 if (view_ == NULL || frame_ == NULL)
434 for (blink::WebFrame* frame = view_->mainFrame(); frame != NULL;
435 frame = frame->traverseNext(false)) {
442 blink::WebView* FrameReference::view() {
446 #if defined(ENABLE_PRINT_PREVIEW)
447 // static - Not anonymous so that platform implementations can use it.
448 void PrintWebViewHelper::PrintHeaderAndFooter(
449 blink::WebCanvas* canvas,
452 const blink::WebFrame& source_frame,
453 float webkit_scale_factor,
454 const PageSizeMargins& page_layout,
455 const PrintMsg_Print_Params& params) {
456 skia::VectorPlatformDeviceSkia* device =
457 static_cast<skia::VectorPlatformDeviceSkia*>(canvas->getTopDevice());
458 device->setDrawingArea(SkPDFDevice::kMargin_DrawingArea);
460 SkAutoCanvasRestore auto_restore(canvas, true);
461 canvas->scale(1 / webkit_scale_factor, 1 / webkit_scale_factor);
463 blink::WebSize page_size(page_layout.margin_left + page_layout.margin_right +
464 page_layout.content_width,
465 page_layout.margin_top + page_layout.margin_bottom +
466 page_layout.content_height);
468 blink::WebView* web_view = blink::WebView::create(NULL);
469 web_view->settings()->setJavaScriptEnabled(true);
471 blink::WebLocalFrame* frame = blink::WebLocalFrame::create(NULL);
472 web_view->setMainFrame(frame);
474 base::StringValue html(ResourceBundle::GetSharedInstance().GetLocalizedString(
475 IDR_PRINT_PREVIEW_PAGE));
476 // Load page with script to avoid async operations.
477 ExecuteScript(frame, kPageLoadScriptFormat, html);
479 scoped_ptr<base::DictionaryValue> options(new base::DictionaryValue());
480 options.reset(new base::DictionaryValue());
481 options->SetDouble(kSettingHeaderFooterDate, base::Time::Now().ToJsTime());
482 options->SetDouble("width", page_size.width);
483 options->SetDouble("height", page_size.height);
484 options->SetDouble("topMargin", page_layout.margin_top);
485 options->SetDouble("bottomMargin", page_layout.margin_bottom);
486 options->SetString("pageNumber",
487 base::StringPrintf("%d/%d", page_number, total_pages));
489 // Fallback to initiator URL and title if it's empty for printed frame.
490 base::string16 url = source_frame.document().url().string();
491 options->SetString("url", url.empty() ? params.url : url);
492 base::string16 title = source_frame.document().title();
493 options->SetString("title", title.empty() ? params.title : title);
495 ExecuteScript(frame, kPageSetupScriptFormat, *options);
497 blink::WebPrintParams webkit_params(page_size);
498 webkit_params.printerDPI = GetDPI(¶ms);
500 frame->printBegin(webkit_params);
501 frame->printPage(0, canvas);
507 device->setDrawingArea(SkPDFDevice::kContent_DrawingArea);
509 #endif // defined(ENABLE_PRINT_PREVIEW)
511 // static - Not anonymous so that platform implementations can use it.
512 float PrintWebViewHelper::RenderPageContent(blink::WebFrame* frame,
514 const gfx::Rect& canvas_area,
515 const gfx::Rect& content_area,
517 blink::WebCanvas* canvas) {
518 SkAutoCanvasRestore auto_restore(canvas, true);
519 if (content_area != canvas_area) {
520 canvas->translate((content_area.x() - canvas_area.x()) / scale_factor,
521 (content_area.y() - canvas_area.y()) / scale_factor);
523 SkRect::MakeXYWH(content_area.origin().x() / scale_factor,
524 content_area.origin().y() / scale_factor,
525 content_area.size().width() / scale_factor,
526 content_area.size().height() / scale_factor));
527 SkIRect clip_int_rect;
528 clip_rect.roundOut(&clip_int_rect);
529 SkRegion clip_region(clip_int_rect);
530 canvas->setClipRegion(clip_region);
532 return frame->printPage(page_number, canvas);
535 // Class that calls the Begin and End print functions on the frame and changes
536 // the size of the view temporarily to support full page printing..
537 class PrepareFrameAndViewForPrint : public blink::WebViewClient,
538 public blink::WebFrameClient {
540 PrepareFrameAndViewForPrint(const PrintMsg_Print_Params& params,
541 blink::WebLocalFrame* frame,
542 const blink::WebNode& node,
543 bool ignore_css_margins);
544 virtual ~PrepareFrameAndViewForPrint();
546 // Optional. Replaces |frame_| with selection if needed. Will call |on_ready|
548 void CopySelectionIfNeeded(const WebPreferences& preferences,
549 const base::Closure& on_ready);
551 // Prepares frame for printing.
552 void StartPrinting();
554 blink::WebLocalFrame* frame() {
555 return frame_.GetFrame();
558 const blink::WebNode& node() const {
559 return node_to_print_;
562 int GetExpectedPageCount() const {
563 return expected_pages_count_;
566 void FinishPrinting();
568 bool IsLoadingSelection() {
569 // It's not selection if not |owns_web_view_|.
570 return owns_web_view_ && frame() && frame()->isLoading();
573 // TODO(ojan): Remove this override and have this class use a non-null
575 // blink::WebViewClient override:
576 virtual bool allowsBrokenNullLayerTreeView() const;
579 // blink::WebViewClient override:
580 virtual void didStopLoading();
582 // blink::WebFrameClient override:
583 virtual blink::WebFrame* createChildFrame(blink::WebLocalFrame* parent,
584 const blink::WebString& name);
585 virtual void frameDetached(blink::WebFrame* frame);
589 void ResizeForPrinting();
591 void CopySelection(const WebPreferences& preferences);
593 base::WeakPtrFactory<PrepareFrameAndViewForPrint> weak_ptr_factory_;
595 FrameReference frame_;
596 blink::WebNode node_to_print_;
598 blink::WebPrintParams web_print_params_;
599 gfx::Size prev_view_size_;
600 gfx::Size prev_scroll_offset_;
601 int expected_pages_count_;
602 base::Closure on_ready_;
603 bool should_print_backgrounds_;
604 bool should_print_selection_only_;
605 bool is_printing_started_;
607 DISALLOW_COPY_AND_ASSIGN(PrepareFrameAndViewForPrint);
610 PrepareFrameAndViewForPrint::PrepareFrameAndViewForPrint(
611 const PrintMsg_Print_Params& params,
612 blink::WebLocalFrame* frame,
613 const blink::WebNode& node,
614 bool ignore_css_margins)
615 : weak_ptr_factory_(this),
617 node_to_print_(node),
618 owns_web_view_(false),
619 expected_pages_count_(0),
620 should_print_backgrounds_(params.should_print_backgrounds),
621 should_print_selection_only_(params.selection_only),
622 is_printing_started_(false) {
623 PrintMsg_Print_Params print_params = params;
624 if (!should_print_selection_only_ ||
625 !PrintingNodeOrPdfFrame(frame, node_to_print_)) {
626 bool fit_to_page = ignore_css_margins &&
627 print_params.print_scaling_option ==
628 blink::WebPrintScalingOptionFitToPrintableArea;
629 ComputeWebKitPrintParamsInDesiredDpi(params, &web_print_params_);
630 frame->printBegin(web_print_params_, node_to_print_);
631 print_params = CalculatePrintParamsForCss(frame, 0, print_params,
632 ignore_css_margins, fit_to_page,
636 ComputeWebKitPrintParamsInDesiredDpi(print_params, &web_print_params_);
639 PrepareFrameAndViewForPrint::~PrepareFrameAndViewForPrint() {
643 void PrepareFrameAndViewForPrint::ResizeForPrinting() {
644 // Layout page according to printer page size. Since WebKit shrinks the
645 // size of the page automatically (from 125% to 200%) we trick it to
646 // think the page is 125% larger so the size of the page is correct for
647 // minimum (default) scaling.
648 // This is important for sites that try to fill the page.
649 gfx::Size print_layout_size(web_print_params_.printContentArea.width,
650 web_print_params_.printContentArea.height);
651 print_layout_size.set_height(
652 static_cast<int>(static_cast<double>(print_layout_size.height()) * 1.25));
656 blink::WebView* web_view = frame_.view();
657 // Backup size and offset.
658 if (blink::WebFrame* web_frame = web_view->mainFrame())
659 prev_scroll_offset_ = web_frame->scrollOffset();
660 prev_view_size_ = web_view->size();
662 web_view->resize(print_layout_size);
666 void PrepareFrameAndViewForPrint::StartPrinting() {
668 blink::WebView* web_view = frame_.view();
669 web_view->settings()->setShouldPrintBackgrounds(should_print_backgrounds_);
670 expected_pages_count_ =
671 frame()->printBegin(web_print_params_, node_to_print_);
672 is_printing_started_ = true;
675 void PrepareFrameAndViewForPrint::CopySelectionIfNeeded(
676 const WebPreferences& preferences,
677 const base::Closure& on_ready) {
678 on_ready_ = on_ready;
679 if (should_print_selection_only_) {
680 CopySelection(preferences);
682 // Call immediately, async call crashes scripting printing.
687 void PrepareFrameAndViewForPrint::CopySelection(
688 const WebPreferences& preferences) {
690 std::string url_str = "data:text/html;charset=utf-8,";
692 net::EscapeQueryParamValue(frame()->selectionAsMarkup().utf8(), false));
694 // Create a new WebView with the same settings as the current display one.
695 // Except that we disable javascript (don't want any active content running
697 WebPreferences prefs = preferences;
698 prefs.javascript_enabled = false;
699 prefs.java_enabled = false;
701 blink::WebView* web_view = blink::WebView::create(this);
702 owns_web_view_ = true;
703 content::RenderView::ApplyWebPreferences(prefs, web_view);
704 web_view->setMainFrame(blink::WebLocalFrame::create(this));
705 frame_.Reset(web_view->mainFrame()->toWebLocalFrame());
706 node_to_print_.reset();
708 // When loading is done this will call didStopLoading() and that will do the
710 frame()->loadRequest(blink::WebURLRequest(GURL(url_str)));
713 bool PrepareFrameAndViewForPrint::allowsBrokenNullLayerTreeView() const {
717 void PrepareFrameAndViewForPrint::didStopLoading() {
718 DCHECK(!on_ready_.is_null());
719 // Don't call callback here, because it can delete |this| and WebView that is
720 // called didStopLoading.
721 base::MessageLoop::current()->PostTask(
723 base::Bind(&PrepareFrameAndViewForPrint::CallOnReady,
724 weak_ptr_factory_.GetWeakPtr()));
727 blink::WebFrame* PrepareFrameAndViewForPrint::createChildFrame(
728 blink::WebLocalFrame* parent,
729 const blink::WebString& name) {
730 blink::WebFrame* frame = blink::WebLocalFrame::create(this);
731 parent->appendChild(frame);
735 void PrepareFrameAndViewForPrint::frameDetached(blink::WebFrame* frame) {
737 frame->parent()->removeChild(frame);
741 void PrepareFrameAndViewForPrint::CallOnReady() {
742 return on_ready_.Run(); // Can delete |this|.
745 void PrepareFrameAndViewForPrint::RestoreSize() {
747 blink::WebView* web_view = frame_.GetFrame()->view();
748 web_view->resize(prev_view_size_);
749 if (blink::WebFrame* web_frame = web_view->mainFrame())
750 web_frame->setScrollOffset(prev_scroll_offset_);
754 void PrepareFrameAndViewForPrint::FinishPrinting() {
755 blink::WebLocalFrame* frame = frame_.GetFrame();
757 blink::WebView* web_view = frame->view();
758 if (is_printing_started_) {
759 is_printing_started_ = false;
761 if (!owns_web_view_) {
762 web_view->settings()->setShouldPrintBackgrounds(false);
766 if (owns_web_view_) {
767 DCHECK(!frame->isLoading());
768 owns_web_view_ = false;
776 PrintWebViewHelper::PrintWebViewHelper(content::RenderView* render_view)
777 : content::RenderViewObserver(render_view),
778 content::RenderViewObserverTracker<PrintWebViewHelper>(render_view),
779 reset_prep_frame_view_(false),
780 is_print_ready_metafile_sent_(false),
781 ignore_css_margins_(false),
782 is_scripted_printing_blocked_(false),
783 notify_browser_of_print_failure_(true),
784 print_for_preview_(false),
785 print_node_in_progress_(false),
787 is_scripted_preview_delayed_(false),
788 weak_ptr_factory_(this) {
789 if (CommandLine::ForCurrentProcess()->HasSwitch(
790 switches::kDisablePrintPreview)) {
795 PrintWebViewHelper::~PrintWebViewHelper() {}
798 void PrintWebViewHelper::DisablePreview() {
799 g_is_preview_enabled_ = false;
802 bool PrintWebViewHelper::IsScriptInitiatedPrintAllowed(
803 blink::WebFrame* frame, bool user_initiated) {
804 #if defined(OS_ANDROID)
806 #endif // defined(OS_ANDROID)
807 // If preview is enabled, then the print dialog is tab modal, and the user
808 // can always close the tab on a mis-behaving page (the system print dialog
809 // is app modal). If the print was initiated through user action, don't
810 // throttle. Or, if the command line flag to skip throttling has been set.
811 return !is_scripted_printing_blocked_ &&
812 (user_initiated || g_is_preview_enabled_ ||
813 scripting_throttler_.IsAllowed(frame));
816 void PrintWebViewHelper::DidStartLoading() {
820 void PrintWebViewHelper::DidStopLoading() {
822 if (!on_stop_loading_closure_.is_null()) {
823 on_stop_loading_closure_.Run();
824 on_stop_loading_closure_.Reset();
828 // Prints |frame| which called window.print().
829 void PrintWebViewHelper::PrintPage(blink::WebLocalFrame* frame,
830 bool user_initiated) {
833 // Allow Prerendering to cancel this print request if necessary.
834 if (prerender::PrerenderHelper::IsPrerendering(
835 render_view()->GetMainRenderFrame())) {
836 Send(new ChromeViewHostMsg_CancelPrerenderForPrinting(routing_id()));
840 if (!IsScriptInitiatedPrintAllowed(frame, user_initiated))
843 if (!g_is_preview_enabled_) {
844 Print(frame, blink::WebNode());
846 print_preview_context_.InitWithFrame(frame);
847 RequestPrintPreview(PRINT_PREVIEW_SCRIPTED);
851 bool PrintWebViewHelper::OnMessageReceived(const IPC::Message& message) {
853 IPC_BEGIN_MESSAGE_MAP(PrintWebViewHelper, message)
854 #if defined(ENABLE_BASIC_PRINTING)
855 IPC_MESSAGE_HANDLER(PrintMsg_PrintPages, OnPrintPages)
856 IPC_MESSAGE_HANDLER(PrintMsg_PrintForSystemDialog, OnPrintForSystemDialog)
857 #endif // ENABLE_BASIC_PRINTING
858 IPC_MESSAGE_HANDLER(PrintMsg_InitiatePrintPreview, OnInitiatePrintPreview)
859 IPC_MESSAGE_HANDLER(PrintMsg_PrintPreview, OnPrintPreview)
860 IPC_MESSAGE_HANDLER(PrintMsg_PrintForPrintPreview, OnPrintForPrintPreview)
861 IPC_MESSAGE_HANDLER(PrintMsg_PrintingDone, OnPrintingDone)
862 IPC_MESSAGE_HANDLER(PrintMsg_SetScriptedPrintingBlocked,
863 SetScriptedPrintBlocked)
864 IPC_MESSAGE_UNHANDLED(handled = false)
865 IPC_END_MESSAGE_MAP()
869 void PrintWebViewHelper::OnPrintForPrintPreview(
870 const base::DictionaryValue& job_settings) {
871 // If still not finished with earlier print request simply ignore.
872 if (prep_frame_view_)
875 if (!render_view()->GetWebView())
877 blink::WebFrame* main_frame = render_view()->GetWebView()->mainFrame();
881 blink::WebDocument document = main_frame->document();
882 // <object>/<iframe> with id="pdf-viewer" is created in
883 // chrome/browser/resources/print_preview/print_preview.js
884 blink::WebElement pdf_element = document.getElementById("pdf-viewer");
885 if (pdf_element.isNull()) {
890 // The out-of-process plugin element is nested within a frame.
891 blink::WebLocalFrame* plugin_frame = pdf_element.document().frame();
892 blink::WebElement plugin_element = pdf_element;
893 if (CommandLine::ForCurrentProcess()->HasSwitch(switches::kOutOfProcessPdf)) {
894 if (!pdf_element.hasHTMLTagName("iframe")) {
898 plugin_frame = blink::WebLocalFrame::fromFrameOwnerElement(pdf_element);
899 // <object> with id="plugin" is created in
900 // chrome/browser/resources/pdf/pdf.js.
901 plugin_element = plugin_frame->document().getElementById("plugin");
902 if (plugin_element.isNull()) {
908 // Set |print_for_preview_| flag and autoreset it to back to original
910 base::AutoReset<bool> set_printing_flag(&print_for_preview_, true);
912 if (!UpdatePrintSettings(plugin_frame, plugin_element, job_settings)) {
913 LOG(ERROR) << "UpdatePrintSettings failed";
914 DidFinishPrinting(FAIL_PRINT);
918 // Print page onto entire page not just printable area. Preview PDF already
919 // has content in correct position taking into account page size and printable
921 // TODO(vitalybuka) : Make this consistent on all platform. This change
922 // affects Windows only. On Linux and OSX RenderPagesForPrint does not use
923 // printable_area. Also we can't change printable_area deeper inside
924 // RenderPagesForPrint for Windows, because it's used also by native
925 // printing and it expects real printable_area value.
926 // See http://crbug.com/123408
927 PrintMsg_Print_Params& print_params = print_pages_params_->params;
928 print_params.printable_area = gfx::Rect(print_params.page_size);
930 // Render Pages for printing.
931 if (!RenderPagesForPrint(plugin_frame, plugin_element)) {
932 LOG(ERROR) << "RenderPagesForPrint failed";
933 DidFinishPrinting(FAIL_PRINT);
937 bool PrintWebViewHelper::GetPrintFrame(blink::WebLocalFrame** frame) {
939 blink::WebView* webView = render_view()->GetWebView();
944 // If the user has selected text in the currently focused frame we print
945 // only that frame (this makes print selection work for multiple frames).
946 blink::WebLocalFrame* focusedFrame =
947 webView->focusedFrame()->toWebLocalFrame();
948 *frame = focusedFrame->hasSelection()
950 : webView->mainFrame()->toWebLocalFrame();
954 #if defined(ENABLE_BASIC_PRINTING)
955 void PrintWebViewHelper::OnPrintPages() {
956 blink::WebLocalFrame* frame;
957 if (GetPrintFrame(&frame))
958 Print(frame, blink::WebNode());
961 void PrintWebViewHelper::OnPrintForSystemDialog() {
962 blink::WebLocalFrame* frame = print_preview_context_.source_frame();
967 Print(frame, print_preview_context_.source_node());
969 #endif // ENABLE_BASIC_PRINTING
971 void PrintWebViewHelper::GetPageSizeAndContentAreaFromPageLayout(
972 const PageSizeMargins& page_layout_in_points,
973 gfx::Size* page_size,
974 gfx::Rect* content_area) {
975 *page_size = gfx::Size(
976 page_layout_in_points.content_width +
977 page_layout_in_points.margin_right +
978 page_layout_in_points.margin_left,
979 page_layout_in_points.content_height +
980 page_layout_in_points.margin_top +
981 page_layout_in_points.margin_bottom);
982 *content_area = gfx::Rect(page_layout_in_points.margin_left,
983 page_layout_in_points.margin_top,
984 page_layout_in_points.content_width,
985 page_layout_in_points.content_height);
988 void PrintWebViewHelper::UpdateFrameMarginsCssInfo(
989 const base::DictionaryValue& settings) {
990 int margins_type = 0;
991 if (!settings.GetInteger(kSettingMarginsType, &margins_type))
992 margins_type = DEFAULT_MARGINS;
993 ignore_css_margins_ = (margins_type != DEFAULT_MARGINS);
996 bool PrintWebViewHelper::IsPrintToPdfRequested(
997 const base::DictionaryValue& job_settings) {
998 bool print_to_pdf = false;
999 if (!job_settings.GetBoolean(kSettingPrintToPDF, &print_to_pdf))
1001 return print_to_pdf;
1004 void PrintWebViewHelper::OnPrintPreview(const base::DictionaryValue& settings) {
1005 print_preview_context_.OnPrintPreview();
1007 UMA_HISTOGRAM_ENUMERATION("PrintPreview.PreviewEvent",
1008 PREVIEW_EVENT_REQUESTED, PREVIEW_EVENT_MAX);
1010 if (!print_preview_context_.source_frame()) {
1011 DidFinishPrinting(FAIL_PREVIEW);
1015 if (!UpdatePrintSettings(print_preview_context_.source_frame(),
1016 print_preview_context_.source_node(), settings)) {
1017 if (print_preview_context_.last_error() != PREVIEW_ERROR_BAD_SETTING) {
1018 Send(new PrintHostMsg_PrintPreviewInvalidPrinterSettings(
1020 print_pages_params_ ?
1021 print_pages_params_->params.document_cookie : 0));
1022 notify_browser_of_print_failure_ = false; // Already sent.
1024 DidFinishPrinting(FAIL_PREVIEW);
1028 // Set the options from document if we are previewing a pdf and send a
1029 // message to browser.
1030 if (print_pages_params_->params.is_first_request &&
1031 !print_preview_context_.IsModifiable()) {
1032 PrintHostMsg_SetOptionsFromDocument_Params params;
1033 SetOptionsFromDocument(params);
1034 Send(new PrintHostMsg_SetOptionsFromDocument(routing_id(), params));
1037 is_print_ready_metafile_sent_ = false;
1039 // PDF printer device supports alpha blending.
1040 print_pages_params_->params.supports_alpha_blend = true;
1042 bool generate_draft_pages = false;
1043 if (!settings.GetBoolean(kSettingGenerateDraftData,
1044 &generate_draft_pages)) {
1047 print_preview_context_.set_generate_draft_pages(generate_draft_pages);
1049 PrepareFrameForPreviewDocument();
1052 void PrintWebViewHelper::PrepareFrameForPreviewDocument() {
1053 reset_prep_frame_view_ = false;
1055 if (!print_pages_params_ || CheckForCancel()) {
1056 DidFinishPrinting(FAIL_PREVIEW);
1060 // Don't reset loading frame or WebKit will fail assert. Just retry when
1061 // current selection is loaded.
1062 if (prep_frame_view_ && prep_frame_view_->IsLoadingSelection()) {
1063 reset_prep_frame_view_ = true;
1067 const PrintMsg_Print_Params& print_params = print_pages_params_->params;
1068 prep_frame_view_.reset(
1069 new PrepareFrameAndViewForPrint(print_params,
1070 print_preview_context_.source_frame(),
1071 print_preview_context_.source_node(),
1072 ignore_css_margins_));
1073 prep_frame_view_->CopySelectionIfNeeded(
1074 render_view()->GetWebkitPreferences(),
1075 base::Bind(&PrintWebViewHelper::OnFramePreparedForPreviewDocument,
1076 base::Unretained(this)));
1079 void PrintWebViewHelper::OnFramePreparedForPreviewDocument() {
1080 if (reset_prep_frame_view_) {
1081 PrepareFrameForPreviewDocument();
1084 DidFinishPrinting(CreatePreviewDocument() ? OK : FAIL_PREVIEW);
1087 bool PrintWebViewHelper::CreatePreviewDocument() {
1088 if (!print_pages_params_ || CheckForCancel())
1091 UMA_HISTOGRAM_ENUMERATION("PrintPreview.PreviewEvent",
1092 PREVIEW_EVENT_CREATE_DOCUMENT, PREVIEW_EVENT_MAX);
1094 const PrintMsg_Print_Params& print_params = print_pages_params_->params;
1095 const std::vector<int>& pages = print_pages_params_->pages;
1097 if (!print_preview_context_.CreatePreviewDocument(prep_frame_view_.release(),
1102 PageSizeMargins default_page_layout;
1103 ComputePageLayoutInPointsForCss(print_preview_context_.prepared_frame(), 0,
1104 print_params, ignore_css_margins_, NULL,
1105 &default_page_layout);
1107 bool has_page_size_style = PrintingFrameHasPageSizeStyle(
1108 print_preview_context_.prepared_frame(),
1109 print_preview_context_.total_page_count());
1110 int dpi = GetDPI(&print_params);
1112 gfx::Rect printable_area_in_points(
1113 ConvertUnit(print_params.printable_area.x(), dpi, kPointsPerInch),
1114 ConvertUnit(print_params.printable_area.y(), dpi, kPointsPerInch),
1115 ConvertUnit(print_params.printable_area.width(), dpi, kPointsPerInch),
1116 ConvertUnit(print_params.printable_area.height(), dpi, kPointsPerInch));
1118 // Margins: Send default page layout to browser process.
1119 Send(new PrintHostMsg_DidGetDefaultPageLayout(routing_id(),
1120 default_page_layout,
1121 printable_area_in_points,
1122 has_page_size_style));
1124 PrintHostMsg_DidGetPreviewPageCount_Params params;
1125 params.page_count = print_preview_context_.total_page_count();
1126 params.is_modifiable = print_preview_context_.IsModifiable();
1127 params.document_cookie = print_params.document_cookie;
1128 params.preview_request_id = print_params.preview_request_id;
1129 params.clear_preview_data = print_preview_context_.generate_draft_pages();
1130 Send(new PrintHostMsg_DidGetPreviewPageCount(routing_id(), params));
1131 if (CheckForCancel())
1134 while (!print_preview_context_.IsFinalPageRendered()) {
1135 int page_number = print_preview_context_.GetNextPageNumber();
1136 DCHECK_GE(page_number, 0);
1137 if (!RenderPreviewPage(page_number, print_params))
1140 if (CheckForCancel())
1143 // We must call PrepareFrameAndViewForPrint::FinishPrinting() (by way of
1144 // print_preview_context_.AllPagesRendered()) before calling
1145 // FinalizePrintReadyDocument() when printing a PDF because the plugin
1146 // code does not generate output until we call FinishPrinting(). We do not
1147 // generate draft pages for PDFs, so IsFinalPageRendered() and
1148 // IsLastPageOfPrintReadyMetafile() will be true in the same iteration of
1150 if (print_preview_context_.IsFinalPageRendered())
1151 print_preview_context_.AllPagesRendered();
1153 if (print_preview_context_.IsLastPageOfPrintReadyMetafile()) {
1154 DCHECK(print_preview_context_.IsModifiable() ||
1155 print_preview_context_.IsFinalPageRendered());
1156 if (!FinalizePrintReadyDocument())
1160 print_preview_context_.Finished();
1164 bool PrintWebViewHelper::FinalizePrintReadyDocument() {
1165 DCHECK(!is_print_ready_metafile_sent_);
1166 print_preview_context_.FinalizePrintReadyDocument();
1168 // Get the size of the resulting metafile.
1169 PdfMetafileSkia* metafile = print_preview_context_.metafile();
1170 uint32 buf_size = metafile->GetDataSize();
1171 DCHECK_GT(buf_size, 0u);
1173 PrintHostMsg_DidPreviewDocument_Params preview_params;
1174 preview_params.data_size = buf_size;
1175 preview_params.document_cookie = print_pages_params_->params.document_cookie;
1176 preview_params.expected_pages_count =
1177 print_preview_context_.total_page_count();
1178 preview_params.modifiable = print_preview_context_.IsModifiable();
1179 preview_params.preview_request_id =
1180 print_pages_params_->params.preview_request_id;
1182 // Ask the browser to create the shared memory for us.
1183 if (!CopyMetafileDataToSharedMem(metafile,
1184 &(preview_params.metafile_data_handle))) {
1185 LOG(ERROR) << "CopyMetafileDataToSharedMem failed";
1186 print_preview_context_.set_error(PREVIEW_ERROR_METAFILE_COPY_FAILED);
1189 is_print_ready_metafile_sent_ = true;
1191 Send(new PrintHostMsg_MetafileReadyForPrinting(routing_id(), preview_params));
1195 void PrintWebViewHelper::OnPrintingDone(bool success) {
1196 notify_browser_of_print_failure_ = false;
1198 LOG(ERROR) << "Failure in OnPrintingDone";
1199 DidFinishPrinting(success ? OK : FAIL_PRINT);
1202 void PrintWebViewHelper::SetScriptedPrintBlocked(bool blocked) {
1203 is_scripted_printing_blocked_ = blocked;
1206 void PrintWebViewHelper::OnInitiatePrintPreview(bool selection_only) {
1207 blink::WebLocalFrame* frame = NULL;
1208 GetPrintFrame(&frame);
1210 print_preview_context_.InitWithFrame(frame);
1211 RequestPrintPreview(selection_only ?
1212 PRINT_PREVIEW_USER_INITIATED_SELECTION :
1213 PRINT_PREVIEW_USER_INITIATED_ENTIRE_FRAME);
1216 bool PrintWebViewHelper::IsPrintingEnabled() {
1217 bool result = false;
1218 Send(new PrintHostMsg_IsPrintingEnabled(routing_id(), &result));
1222 void PrintWebViewHelper::PrintNode(const blink::WebNode& node) {
1223 if (node.isNull() || !node.document().frame()) {
1224 // This can occur when the context menu refers to an invalid WebNode.
1225 // See http://crbug.com/100890#c17 for a repro case.
1229 if (print_node_in_progress_) {
1230 // This can happen as a result of processing sync messages when printing
1231 // from ppapi plugins. It's a rare case, so its OK to just fail here.
1232 // See http://crbug.com/159165.
1236 print_node_in_progress_ = true;
1238 // Make a copy of the node, in case RenderView::OnContextMenuClosed resets
1239 // its |context_menu_node_|.
1240 if (!g_is_preview_enabled_) {
1241 blink::WebNode duplicate_node(node);
1242 Print(duplicate_node.document().frame(), duplicate_node);
1244 print_preview_context_.InitWithNode(node);
1245 RequestPrintPreview(PRINT_PREVIEW_USER_INITIATED_CONTEXT_NODE);
1248 print_node_in_progress_ = false;
1251 void PrintWebViewHelper::Print(blink::WebLocalFrame* frame,
1252 const blink::WebNode& node) {
1253 // If still not finished with earlier print request simply ignore.
1254 if (prep_frame_view_)
1257 FrameReference frame_ref(frame);
1259 int expected_page_count = 0;
1260 if (!CalculateNumberOfPages(frame, node, &expected_page_count)) {
1261 DidFinishPrinting(FAIL_PRINT_INIT);
1262 return; // Failed to init print page settings.
1265 // Some full screen plugins can say they don't want to print.
1266 if (!expected_page_count) {
1267 DidFinishPrinting(FAIL_PRINT);
1271 // Ask the browser to show UI to retrieve the final print settings.
1272 if (!GetPrintSettingsFromUser(frame_ref.GetFrame(), node,
1273 expected_page_count)) {
1274 DidFinishPrinting(OK); // Release resources and fail silently.
1278 // Render Pages for printing.
1279 if (!RenderPagesForPrint(frame_ref.GetFrame(), node)) {
1280 LOG(ERROR) << "RenderPagesForPrint failed";
1281 DidFinishPrinting(FAIL_PRINT);
1283 scripting_throttler_.Reset();
1286 void PrintWebViewHelper::DidFinishPrinting(PrintingResult result) {
1291 case FAIL_PRINT_INIT:
1292 DCHECK(!notify_browser_of_print_failure_);
1296 if (notify_browser_of_print_failure_ && print_pages_params_) {
1297 int cookie = print_pages_params_->params.document_cookie;
1298 Send(new PrintHostMsg_PrintingFailed(routing_id(), cookie));
1303 int cookie = print_pages_params_ ?
1304 print_pages_params_->params.document_cookie : 0;
1305 if (notify_browser_of_print_failure_) {
1306 LOG(ERROR) << "CreatePreviewDocument failed";
1307 Send(new PrintHostMsg_PrintPreviewFailed(routing_id(), cookie));
1309 Send(new PrintHostMsg_PrintPreviewCancelled(routing_id(), cookie));
1311 print_preview_context_.Failed(notify_browser_of_print_failure_);
1314 prep_frame_view_.reset();
1315 print_pages_params_.reset();
1316 notify_browser_of_print_failure_ = true;
1319 void PrintWebViewHelper::OnFramePreparedForPrintPages() {
1321 FinishFramePrinting();
1324 void PrintWebViewHelper::PrintPages() {
1325 if (!prep_frame_view_) // Printing is already canceled or failed.
1327 prep_frame_view_->StartPrinting();
1329 int page_count = prep_frame_view_->GetExpectedPageCount();
1331 LOG(ERROR) << "Can't print 0 pages.";
1332 return DidFinishPrinting(FAIL_PRINT);
1335 const PrintMsg_PrintPages_Params& params = *print_pages_params_;
1336 const PrintMsg_Print_Params& print_params = params.params;
1338 #if !defined(OS_CHROMEOS) && !defined(OS_ANDROID)
1339 // TODO(vitalybuka): should be page_count or valid pages from params.pages.
1340 // See http://crbug.com/161576
1341 Send(new PrintHostMsg_DidGetPrintedPagesCount(routing_id(),
1342 print_params.document_cookie,
1344 #endif // !defined(OS_CHROMEOS)
1346 if (print_params.preview_ui_id < 0) {
1347 // Printing for system dialog.
1348 int printed_count = params.pages.empty() ? page_count : params.pages.size();
1349 #if !defined(OS_CHROMEOS)
1350 UMA_HISTOGRAM_COUNTS("PrintPreview.PageCount.SystemDialog", printed_count);
1352 UMA_HISTOGRAM_COUNTS("PrintPreview.PageCount.PrintToCloudPrintWebDialog",
1354 #endif // !defined(OS_CHROMEOS)
1358 if (!PrintPagesNative(prep_frame_view_->frame(), page_count)) {
1359 LOG(ERROR) << "Printing failed.";
1360 return DidFinishPrinting(FAIL_PRINT);
1364 void PrintWebViewHelper::FinishFramePrinting() {
1365 prep_frame_view_.reset();
1368 #if defined(OS_MACOSX)
1369 bool PrintWebViewHelper::PrintPagesNative(blink::WebFrame* frame,
1371 const PrintMsg_PrintPages_Params& params = *print_pages_params_;
1372 const PrintMsg_Print_Params& print_params = params.params;
1374 PrintMsg_PrintPage_Params page_params;
1375 page_params.params = print_params;
1376 if (params.pages.empty()) {
1377 for (int i = 0; i < page_count; ++i) {
1378 page_params.page_number = i;
1379 PrintPageInternal(page_params, frame);
1382 for (size_t i = 0; i < params.pages.size(); ++i) {
1383 if (params.pages[i] >= page_count)
1385 page_params.page_number = params.pages[i];
1386 PrintPageInternal(page_params, frame);
1394 // static - Not anonymous so that platform implementations can use it.
1395 void PrintWebViewHelper::ComputePageLayoutInPointsForCss(
1396 blink::WebFrame* frame,
1398 const PrintMsg_Print_Params& page_params,
1399 bool ignore_css_margins,
1400 double* scale_factor,
1401 PageSizeMargins* page_layout_in_points) {
1402 PrintMsg_Print_Params params = CalculatePrintParamsForCss(
1403 frame, page_index, page_params, ignore_css_margins,
1404 page_params.print_scaling_option ==
1405 blink::WebPrintScalingOptionFitToPrintableArea,
1407 CalculatePageLayoutFromPrintParams(params, page_layout_in_points);
1410 bool PrintWebViewHelper::InitPrintSettings(bool fit_to_paper_size) {
1411 PrintMsg_PrintPages_Params settings;
1412 Send(new PrintHostMsg_GetDefaultPrintSettings(routing_id(),
1414 // Check if the printer returned any settings, if the settings is empty, we
1415 // can safely assume there are no printer drivers configured. So we safely
1418 if (!PrintMsg_Print_Params_IsValid(settings.params))
1421 // Reset to default values.
1422 ignore_css_margins_ = false;
1423 settings.pages.clear();
1425 settings.params.print_scaling_option =
1426 blink::WebPrintScalingOptionSourceSize;
1427 if (fit_to_paper_size) {
1428 settings.params.print_scaling_option =
1429 blink::WebPrintScalingOptionFitToPrintableArea;
1432 SetPrintPagesParams(settings);
1436 bool PrintWebViewHelper::CalculateNumberOfPages(blink::WebLocalFrame* frame,
1437 const blink::WebNode& node,
1438 int* number_of_pages) {
1440 bool fit_to_paper_size = !(PrintingNodeOrPdfFrame(frame, node));
1441 if (!InitPrintSettings(fit_to_paper_size)) {
1442 notify_browser_of_print_failure_ = false;
1443 Send(new PrintHostMsg_ShowInvalidPrinterSettingsError(routing_id()));
1447 const PrintMsg_Print_Params& params = print_pages_params_->params;
1448 PrepareFrameAndViewForPrint prepare(params, frame, node, ignore_css_margins_);
1449 prepare.StartPrinting();
1451 *number_of_pages = prepare.GetExpectedPageCount();
1455 void PrintWebViewHelper::SetOptionsFromDocument(
1456 PrintHostMsg_SetOptionsFromDocument_Params& params) {
1457 blink::WebLocalFrame* source_frame = print_preview_context_.source_frame();
1458 const blink::WebNode& source_node = print_preview_context_.source_node();
1460 params.is_scaling_disabled =
1461 source_frame->isPrintScalingDisabledForPlugin(source_node);
1464 bool PrintWebViewHelper::UpdatePrintSettings(
1465 blink::WebLocalFrame* frame,
1466 const blink::WebNode& node,
1467 const base::DictionaryValue& passed_job_settings) {
1468 const base::DictionaryValue* job_settings = &passed_job_settings;
1469 base::DictionaryValue modified_job_settings;
1470 if (job_settings->empty()) {
1471 if (!print_for_preview_)
1472 print_preview_context_.set_error(PREVIEW_ERROR_BAD_SETTING);
1476 bool source_is_html = true;
1477 if (print_for_preview_) {
1478 if (!job_settings->GetBoolean(kSettingPreviewModifiable, &source_is_html)) {
1482 source_is_html = !PrintingNodeOrPdfFrame(frame, node);
1485 if (print_for_preview_ || !source_is_html) {
1486 modified_job_settings.MergeDictionary(job_settings);
1487 modified_job_settings.SetBoolean(kSettingHeaderFooterEnabled, false);
1488 modified_job_settings.SetInteger(kSettingMarginsType, NO_MARGINS);
1489 job_settings = &modified_job_settings;
1492 // Send the cookie so that UpdatePrintSettings can reuse PrinterQuery when
1494 int cookie = print_pages_params_ ?
1495 print_pages_params_->params.document_cookie : 0;
1496 PrintMsg_PrintPages_Params settings;
1497 bool canceled = false;
1498 Send(new PrintHostMsg_UpdatePrintSettings(
1499 routing_id(), cookie, *job_settings, &settings, &canceled));
1501 notify_browser_of_print_failure_ = false;
1505 if (!job_settings->GetInteger(kPreviewUIID, &settings.params.preview_ui_id)) {
1507 print_preview_context_.set_error(PREVIEW_ERROR_BAD_SETTING);
1511 if (!print_for_preview_) {
1512 // Validate expected print preview settings.
1513 if (!job_settings->GetInteger(kPreviewRequestID,
1514 &settings.params.preview_request_id) ||
1515 !job_settings->GetBoolean(kIsFirstRequest,
1516 &settings.params.is_first_request)) {
1518 print_preview_context_.set_error(PREVIEW_ERROR_BAD_SETTING);
1522 settings.params.print_to_pdf = IsPrintToPdfRequested(*job_settings);
1523 UpdateFrameMarginsCssInfo(*job_settings);
1524 settings.params.print_scaling_option = GetPrintScalingOption(
1525 frame, node, source_is_html, *job_settings, settings.params);
1528 SetPrintPagesParams(settings);
1530 if (!PrintMsg_Print_Params_IsValid(settings.params)) {
1531 if (!print_for_preview_)
1532 print_preview_context_.set_error(PREVIEW_ERROR_INVALID_PRINTER_SETTINGS);
1534 Send(new PrintHostMsg_ShowInvalidPrinterSettingsError(routing_id()));
1542 bool PrintWebViewHelper::GetPrintSettingsFromUser(blink::WebFrame* frame,
1543 const blink::WebNode& node,
1544 int expected_pages_count) {
1545 PrintHostMsg_ScriptedPrint_Params params;
1546 PrintMsg_PrintPages_Params print_settings;
1548 params.cookie = print_pages_params_->params.document_cookie;
1549 params.has_selection = frame->hasSelection();
1550 params.expected_pages_count = expected_pages_count;
1551 MarginType margin_type = DEFAULT_MARGINS;
1552 if (PrintingNodeOrPdfFrame(frame, node))
1553 margin_type = GetMarginsForPdf(frame, node);
1554 params.margin_type = margin_type;
1556 Send(new PrintHostMsg_DidShowPrintDialog(routing_id()));
1558 // PrintHostMsg_ScriptedPrint will reset print_scaling_option, so we save the
1559 // value before and restore it afterwards.
1560 blink::WebPrintScalingOption scaling_option =
1561 print_pages_params_->params.print_scaling_option;
1563 print_pages_params_.reset();
1564 IPC::SyncMessage* msg =
1565 new PrintHostMsg_ScriptedPrint(routing_id(), params, &print_settings);
1566 msg->EnableMessagePumping();
1568 print_settings.params.print_scaling_option = scaling_option;
1569 SetPrintPagesParams(print_settings);
1570 return (print_settings.params.dpi && print_settings.params.document_cookie);
1573 bool PrintWebViewHelper::RenderPagesForPrint(blink::WebLocalFrame* frame,
1574 const blink::WebNode& node) {
1575 if (!frame || prep_frame_view_)
1577 const PrintMsg_PrintPages_Params& params = *print_pages_params_;
1578 const PrintMsg_Print_Params& print_params = params.params;
1579 prep_frame_view_.reset(new PrepareFrameAndViewForPrint(
1580 print_params, frame, node, ignore_css_margins_));
1581 DCHECK(!print_pages_params_->params.selection_only ||
1582 print_pages_params_->pages.empty());
1583 prep_frame_view_->CopySelectionIfNeeded(
1584 render_view()->GetWebkitPreferences(),
1585 base::Bind(&PrintWebViewHelper::OnFramePreparedForPrintPages,
1586 base::Unretained(this)));
1590 #if defined(OS_POSIX)
1591 bool PrintWebViewHelper::CopyMetafileDataToSharedMem(
1592 PdfMetafileSkia* metafile,
1593 base::SharedMemoryHandle* shared_mem_handle) {
1594 uint32 buf_size = metafile->GetDataSize();
1595 scoped_ptr<base::SharedMemory> shared_buf(
1596 content::RenderThread::Get()->HostAllocateSharedMemoryBuffer(
1597 buf_size).release());
1600 if (shared_buf->Map(buf_size)) {
1601 metafile->GetData(shared_buf->memory(), buf_size);
1602 return shared_buf->GiveToProcess(base::GetCurrentProcessHandle(),
1608 #endif // defined(OS_POSIX)
1610 void PrintWebViewHelper::ShowScriptedPrintPreview() {
1611 if (is_scripted_preview_delayed_) {
1612 is_scripted_preview_delayed_ = false;
1613 Send(new PrintHostMsg_ShowScriptedPrintPreview(routing_id(),
1614 print_preview_context_.IsModifiable()));
1618 void PrintWebViewHelper::RequestPrintPreview(PrintPreviewRequestType type) {
1619 const bool is_modifiable = print_preview_context_.IsModifiable();
1620 const bool has_selection = print_preview_context_.HasSelection();
1621 PrintHostMsg_RequestPrintPreview_Params params;
1622 params.is_modifiable = is_modifiable;
1623 params.has_selection = has_selection;
1625 case PRINT_PREVIEW_SCRIPTED: {
1626 // Shows scripted print preview in two stages.
1627 // 1. PrintHostMsg_SetupScriptedPrintPreview blocks this call and JS by
1628 // pumping messages here.
1629 // 2. PrintHostMsg_ShowScriptedPrintPreview shows preview once the
1630 // document has been loaded.
1631 is_scripted_preview_delayed_ = true;
1632 if (is_loading_ && GetPlugin(print_preview_context_.source_frame())) {
1633 // Wait for DidStopLoading. Plugins may not know the correct
1634 // |is_modifiable| value until they are fully loaded, which occurs when
1635 // DidStopLoading() is called. Defer showing the preview until then.
1636 on_stop_loading_closure_ =
1637 base::Bind(&PrintWebViewHelper::ShowScriptedPrintPreview,
1638 base::Unretained(this));
1640 base::MessageLoop::current()->PostTask(
1642 base::Bind(&PrintWebViewHelper::ShowScriptedPrintPreview,
1643 weak_ptr_factory_.GetWeakPtr()));
1645 IPC::SyncMessage* msg =
1646 new PrintHostMsg_SetupScriptedPrintPreview(routing_id());
1647 msg->EnableMessagePumping();
1649 is_scripted_preview_delayed_ = false;
1652 case PRINT_PREVIEW_USER_INITIATED_ENTIRE_FRAME: {
1653 // Wait for DidStopLoading. Continuing with this function while
1654 // |is_loading_| is true will cause print preview to hang when try to
1655 // print a PDF document.
1656 if (is_loading_ && GetPlugin(print_preview_context_.source_frame())) {
1657 on_stop_loading_closure_ =
1658 base::Bind(&PrintWebViewHelper::RequestPrintPreview,
1659 base::Unretained(this),
1666 case PRINT_PREVIEW_USER_INITIATED_SELECTION: {
1667 DCHECK(has_selection);
1668 DCHECK(!GetPlugin(print_preview_context_.source_frame()));
1669 params.selection_only = has_selection;
1672 case PRINT_PREVIEW_USER_INITIATED_CONTEXT_NODE: {
1673 if (is_loading_ && GetPlugin(print_preview_context_.source_frame())) {
1674 on_stop_loading_closure_ =
1675 base::Bind(&PrintWebViewHelper::RequestPrintPreview,
1676 base::Unretained(this),
1681 params.webnode_only = true;
1689 Send(new PrintHostMsg_RequestPrintPreview(routing_id(), params));
1692 bool PrintWebViewHelper::CheckForCancel() {
1693 const PrintMsg_Print_Params& print_params = print_pages_params_->params;
1694 bool cancel = false;
1695 Send(new PrintHostMsg_CheckForCancel(routing_id(),
1696 print_params.preview_ui_id,
1697 print_params.preview_request_id,
1700 notify_browser_of_print_failure_ = false;
1704 bool PrintWebViewHelper::PreviewPageRendered(int page_number,
1705 PdfMetafileSkia* metafile) {
1706 DCHECK_GE(page_number, FIRST_PAGE_INDEX);
1708 // For non-modifiable files, |metafile| should be NULL, so do not bother
1709 // sending a message. If we don't generate draft metafiles, |metafile| is
1711 if (!print_preview_context_.IsModifiable() ||
1712 !print_preview_context_.generate_draft_pages()) {
1719 print_preview_context_.set_error(
1720 PREVIEW_ERROR_PAGE_RENDERED_WITHOUT_METAFILE);
1724 PrintHostMsg_DidPreviewPage_Params preview_page_params;
1725 // Get the size of the resulting metafile.
1726 uint32 buf_size = metafile->GetDataSize();
1727 DCHECK_GT(buf_size, 0u);
1728 if (!CopyMetafileDataToSharedMem(
1729 metafile, &(preview_page_params.metafile_data_handle))) {
1730 LOG(ERROR) << "CopyMetafileDataToSharedMem failed";
1731 print_preview_context_.set_error(PREVIEW_ERROR_METAFILE_COPY_FAILED);
1734 preview_page_params.data_size = buf_size;
1735 preview_page_params.page_number = page_number;
1736 preview_page_params.preview_request_id =
1737 print_pages_params_->params.preview_request_id;
1739 Send(new PrintHostMsg_DidPreviewPage(routing_id(), preview_page_params));
1743 PrintWebViewHelper::PrintPreviewContext::PrintPreviewContext()
1744 : total_page_count_(0),
1745 current_page_index_(0),
1746 generate_draft_pages_(true),
1747 print_ready_metafile_page_count_(0),
1748 error_(PREVIEW_ERROR_NONE),
1749 state_(UNINITIALIZED) {
1752 PrintWebViewHelper::PrintPreviewContext::~PrintPreviewContext() {
1755 void PrintWebViewHelper::PrintPreviewContext::InitWithFrame(
1756 blink::WebLocalFrame* web_frame) {
1758 DCHECK(!IsRendering());
1759 state_ = INITIALIZED;
1760 source_frame_.Reset(web_frame);
1761 source_node_.reset();
1764 void PrintWebViewHelper::PrintPreviewContext::InitWithNode(
1765 const blink::WebNode& web_node) {
1766 DCHECK(!web_node.isNull());
1767 DCHECK(web_node.document().frame());
1768 DCHECK(!IsRendering());
1769 state_ = INITIALIZED;
1770 source_frame_.Reset(web_node.document().frame());
1771 source_node_ = web_node;
1774 void PrintWebViewHelper::PrintPreviewContext::OnPrintPreview() {
1775 DCHECK_EQ(INITIALIZED, state_);
1779 bool PrintWebViewHelper::PrintPreviewContext::CreatePreviewDocument(
1780 PrepareFrameAndViewForPrint* prepared_frame,
1781 const std::vector<int>& pages) {
1782 DCHECK_EQ(INITIALIZED, state_);
1785 // Need to make sure old object gets destroyed first.
1786 prep_frame_view_.reset(prepared_frame);
1787 prep_frame_view_->StartPrinting();
1789 total_page_count_ = prep_frame_view_->GetExpectedPageCount();
1790 if (total_page_count_ == 0) {
1791 LOG(ERROR) << "CreatePreviewDocument got 0 page count";
1792 set_error(PREVIEW_ERROR_ZERO_PAGES);
1796 metafile_.reset(new PdfMetafileSkia);
1797 if (!metafile_->Init()) {
1798 set_error(PREVIEW_ERROR_METAFILE_INIT_FAILED);
1799 LOG(ERROR) << "PdfMetafileSkia Init failed";
1803 current_page_index_ = 0;
1804 pages_to_render_ = pages;
1805 // Sort and make unique.
1806 std::sort(pages_to_render_.begin(), pages_to_render_.end());
1807 pages_to_render_.resize(std::unique(pages_to_render_.begin(),
1808 pages_to_render_.end()) -
1809 pages_to_render_.begin());
1810 // Remove invalid pages.
1811 pages_to_render_.resize(std::lower_bound(pages_to_render_.begin(),
1812 pages_to_render_.end(),
1813 total_page_count_) -
1814 pages_to_render_.begin());
1815 print_ready_metafile_page_count_ = pages_to_render_.size();
1816 if (pages_to_render_.empty()) {
1817 print_ready_metafile_page_count_ = total_page_count_;
1818 // Render all pages.
1819 for (int i = 0; i < total_page_count_; ++i)
1820 pages_to_render_.push_back(i);
1821 } else if (generate_draft_pages_) {
1822 int pages_index = 0;
1823 for (int i = 0; i < total_page_count_; ++i) {
1824 if (pages_index < print_ready_metafile_page_count_ &&
1825 i == pages_to_render_[pages_index]) {
1829 pages_to_render_.push_back(i);
1833 document_render_time_ = base::TimeDelta();
1834 begin_time_ = base::TimeTicks::Now();
1839 void PrintWebViewHelper::PrintPreviewContext::RenderedPreviewPage(
1840 const base::TimeDelta& page_time) {
1841 DCHECK_EQ(RENDERING, state_);
1842 document_render_time_ += page_time;
1843 UMA_HISTOGRAM_TIMES("PrintPreview.RenderPDFPageTime", page_time);
1846 void PrintWebViewHelper::PrintPreviewContext::AllPagesRendered() {
1847 DCHECK_EQ(RENDERING, state_);
1849 prep_frame_view_->FinishPrinting();
1852 void PrintWebViewHelper::PrintPreviewContext::FinalizePrintReadyDocument() {
1853 DCHECK(IsRendering());
1855 base::TimeTicks begin_time = base::TimeTicks::Now();
1856 metafile_->FinishDocument();
1858 if (print_ready_metafile_page_count_ <= 0) {
1863 UMA_HISTOGRAM_MEDIUM_TIMES("PrintPreview.RenderToPDFTime",
1864 document_render_time_);
1865 base::TimeDelta total_time = (base::TimeTicks::Now() - begin_time) +
1866 document_render_time_;
1867 UMA_HISTOGRAM_MEDIUM_TIMES("PrintPreview.RenderAndGeneratePDFTime",
1869 UMA_HISTOGRAM_MEDIUM_TIMES("PrintPreview.RenderAndGeneratePDFTimeAvgPerPage",
1870 total_time / pages_to_render_.size());
1873 void PrintWebViewHelper::PrintPreviewContext::Finished() {
1874 DCHECK_EQ(DONE, state_);
1875 state_ = INITIALIZED;
1879 void PrintWebViewHelper::PrintPreviewContext::Failed(bool report_error) {
1880 DCHECK(state_ == INITIALIZED || state_ == RENDERING);
1881 state_ = INITIALIZED;
1883 DCHECK_NE(PREVIEW_ERROR_NONE, error_);
1884 UMA_HISTOGRAM_ENUMERATION("PrintPreview.RendererError", error_,
1885 PREVIEW_ERROR_LAST_ENUM);
1890 int PrintWebViewHelper::PrintPreviewContext::GetNextPageNumber() {
1891 DCHECK_EQ(RENDERING, state_);
1892 if (IsFinalPageRendered())
1894 return pages_to_render_[current_page_index_++];
1897 bool PrintWebViewHelper::PrintPreviewContext::IsRendering() const {
1898 return state_ == RENDERING || state_ == DONE;
1901 bool PrintWebViewHelper::PrintPreviewContext::IsModifiable() {
1902 // The only kind of node we can print right now is a PDF node.
1903 return !PrintingNodeOrPdfFrame(source_frame(), source_node_);
1906 bool PrintWebViewHelper::PrintPreviewContext::HasSelection() {
1907 return IsModifiable() && source_frame()->hasSelection();
1910 bool PrintWebViewHelper::PrintPreviewContext::IsLastPageOfPrintReadyMetafile()
1912 DCHECK(IsRendering());
1913 return current_page_index_ == print_ready_metafile_page_count_;
1916 bool PrintWebViewHelper::PrintPreviewContext::IsFinalPageRendered() const {
1917 DCHECK(IsRendering());
1918 return static_cast<size_t>(current_page_index_) == pages_to_render_.size();
1921 void PrintWebViewHelper::PrintPreviewContext::set_generate_draft_pages(
1922 bool generate_draft_pages) {
1923 DCHECK_EQ(INITIALIZED, state_);
1924 generate_draft_pages_ = generate_draft_pages;
1927 void PrintWebViewHelper::PrintPreviewContext::set_error(
1928 enum PrintPreviewErrorBuckets error) {
1932 blink::WebLocalFrame* PrintWebViewHelper::PrintPreviewContext::source_frame() {
1933 DCHECK(state_ != UNINITIALIZED);
1934 return source_frame_.GetFrame();
1937 const blink::WebNode&
1938 PrintWebViewHelper::PrintPreviewContext::source_node() const {
1939 DCHECK(state_ != UNINITIALIZED);
1940 return source_node_;
1943 blink::WebLocalFrame*
1944 PrintWebViewHelper::PrintPreviewContext::prepared_frame() {
1945 DCHECK(state_ != UNINITIALIZED);
1946 return prep_frame_view_->frame();
1949 const blink::WebNode&
1950 PrintWebViewHelper::PrintPreviewContext::prepared_node() const {
1951 DCHECK(state_ != UNINITIALIZED);
1952 return prep_frame_view_->node();
1955 int PrintWebViewHelper::PrintPreviewContext::total_page_count() const {
1956 DCHECK(state_ != UNINITIALIZED);
1957 return total_page_count_;
1960 bool PrintWebViewHelper::PrintPreviewContext::generate_draft_pages() const {
1961 return generate_draft_pages_;
1964 PdfMetafileSkia* PrintWebViewHelper::PrintPreviewContext::metafile() {
1965 DCHECK(IsRendering());
1966 return metafile_.get();
1969 int PrintWebViewHelper::PrintPreviewContext::last_error() const {
1973 void PrintWebViewHelper::PrintPreviewContext::ClearContext() {
1974 prep_frame_view_.reset();
1976 pages_to_render_.clear();
1977 error_ = PREVIEW_ERROR_NONE;
1980 void PrintWebViewHelper::SetPrintPagesParams(
1981 const PrintMsg_PrintPages_Params& settings) {
1982 print_pages_params_.reset(new PrintMsg_PrintPages_Params(settings));
1983 Send(new PrintHostMsg_DidGetDocumentCookie(routing_id(),
1984 settings.params.document_cookie));
1987 PrintWebViewHelper::ScriptingThrottler::ScriptingThrottler() : count_(0) {
1990 bool PrintWebViewHelper::ScriptingThrottler::IsAllowed(blink::WebFrame* frame) {
1991 const int kMinSecondsToIgnoreJavascriptInitiatedPrint = 2;
1992 const int kMaxSecondsToIgnoreJavascriptInitiatedPrint = 32;
1993 bool too_frequent = false;
1995 // Check if there is script repeatedly trying to print and ignore it if too
1996 // frequent. The first 3 times, we use a constant wait time, but if this
1997 // gets excessive, we switch to exponential wait time. So for a page that
1998 // calls print() in a loop the user will need to cancel the print dialog
1999 // after: [2, 2, 2, 4, 8, 16, 32, 32, ...] seconds.
2000 // This gives the user time to navigate from the page.
2002 base::TimeDelta diff = base::Time::Now() - last_print_;
2003 int min_wait_seconds = kMinSecondsToIgnoreJavascriptInitiatedPrint;
2006 std::min(kMinSecondsToIgnoreJavascriptInitiatedPrint << (count_ - 3),
2007 kMaxSecondsToIgnoreJavascriptInitiatedPrint);
2009 if (diff.InSeconds() < min_wait_seconds) {
2010 too_frequent = true;
2014 if (!too_frequent) {
2016 last_print_ = base::Time::Now();
2020 blink::WebString message(
2021 blink::WebString::fromUTF8("Ignoring too frequent calls to print()."));
2022 frame->addMessageToConsole(blink::WebConsoleMessage(
2023 blink::WebConsoleMessage::LevelWarning, message));
2027 void PrintWebViewHelper::ScriptingThrottler::Reset() {
2028 // Reset counter on successful print.
2032 } // namespace printing