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/renderer/prerender/prerender_helper.h"
23 #include "content/public/renderer/render_frame.h"
24 #include "content/public/renderer/render_thread.h"
25 #include "content/public/renderer/render_view.h"
26 #include "content/public/renderer/web_preferences.h"
27 #include "grit/browser_resources.h"
28 #include "grit/generated_resources.h"
29 #include "net/base/escape.h"
30 #include "printing/metafile.h"
31 #include "printing/metafile_impl.h"
32 #include "printing/units.h"
33 #include "skia/ext/vector_platform_device_skia.h"
34 #include "third_party/WebKit/public/platform/WebSize.h"
35 #include "third_party/WebKit/public/platform/WebURLRequest.h"
36 #include "third_party/WebKit/public/web/WebConsoleMessage.h"
37 #include "third_party/WebKit/public/web/WebDocument.h"
38 #include "third_party/WebKit/public/web/WebElement.h"
39 #include "third_party/WebKit/public/web/WebFrame.h"
40 #include "third_party/WebKit/public/web/WebFrameClient.h"
41 #include "third_party/WebKit/public/web/WebPlugin.h"
42 #include "third_party/WebKit/public/web/WebPluginDocument.h"
43 #include "third_party/WebKit/public/web/WebPrintParams.h"
44 #include "third_party/WebKit/public/web/WebPrintScalingOption.h"
45 #include "third_party/WebKit/public/web/WebScriptSource.h"
46 #include "third_party/WebKit/public/web/WebSettings.h"
47 #include "third_party/WebKit/public/web/WebView.h"
48 #include "third_party/WebKit/public/web/WebViewClient.h"
49 #include "ui/base/l10n/l10n_util.h"
50 #include "ui/base/resource/resource_bundle.h"
51 #include "webkit/common/webpreferences.h"
57 enum PrintPreviewHelperEvents {
58 PREVIEW_EVENT_REQUESTED,
59 PREVIEW_EVENT_CACHE_HIT, // Unused
60 PREVIEW_EVENT_CREATE_DOCUMENT,
61 PREVIEW_EVENT_NEW_SETTINGS, // Unused
65 const double kMinDpi = 1.0;
67 const char kPageLoadScriptFormat[] =
68 "document.open(); document.write(%s); document.close();";
70 const char kPageSetupScriptFormat[] = "setup(%s);";
72 void ExecuteScript(blink::WebFrame* frame,
73 const char* script_format,
74 const base::Value& parameters) {
76 base::JSONWriter::Write(¶meters, &json);
77 std::string script = base::StringPrintf(script_format, json.c_str());
78 frame->executeScript(blink::WebString(base::UTF8ToUTF16(script)));
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
85 return kPointsPerInch;
87 return static_cast<int>(print_params->dpi);
88 #endif // defined(OS_MACOSX)
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);
98 PrintMsg_Print_Params GetCssPrintParams(
99 blink::WebFrame* frame,
101 const PrintMsg_Print_Params& page_params) {
102 PrintMsg_Print_Params page_css_params = page_params;
103 int dpi = GetDPI(&page_params);
105 blink::WebSize page_size_in_pixels(
106 ConvertUnit(page_params.page_size.width(), dpi, kPixelsPerInch),
107 ConvertUnit(page_params.page_size.height(), dpi, kPixelsPerInch));
108 int margin_top_in_pixels =
109 ConvertUnit(page_params.margin_top, dpi, kPixelsPerInch);
110 int margin_right_in_pixels = ConvertUnit(
111 page_params.page_size.width() -
112 page_params.content_size.width() - page_params.margin_left,
113 dpi, kPixelsPerInch);
114 int margin_bottom_in_pixels = ConvertUnit(
115 page_params.page_size.height() -
116 page_params.content_size.height() - page_params.margin_top,
117 dpi, kPixelsPerInch);
118 int margin_left_in_pixels = ConvertUnit(
119 page_params.margin_left,
120 dpi, kPixelsPerInch);
122 blink::WebSize original_page_size_in_pixels = page_size_in_pixels;
125 frame->pageSizeAndMarginsInPixels(page_index,
127 margin_top_in_pixels,
128 margin_right_in_pixels,
129 margin_bottom_in_pixels,
130 margin_left_in_pixels);
133 int new_content_width = page_size_in_pixels.width -
134 margin_left_in_pixels - margin_right_in_pixels;
135 int new_content_height = page_size_in_pixels.height -
136 margin_top_in_pixels - margin_bottom_in_pixels;
138 // Invalid page size and/or margins. We just use the default setting.
139 if (new_content_width < 1 || new_content_height < 1) {
140 CHECK(frame != NULL);
141 page_css_params = GetCssPrintParams(NULL, page_index, page_params);
142 return page_css_params;
145 page_css_params.content_size = gfx::Size(
146 ConvertUnit(new_content_width, kPixelsPerInch, dpi),
147 ConvertUnit(new_content_height, kPixelsPerInch, dpi));
149 if (original_page_size_in_pixels != page_size_in_pixels) {
150 page_css_params.page_size = gfx::Size(
151 ConvertUnit(page_size_in_pixels.width, kPixelsPerInch, dpi),
152 ConvertUnit(page_size_in_pixels.height, kPixelsPerInch, dpi));
154 // Printing frame doesn't have any page size css. Pixels to dpi conversion
155 // causes rounding off errors. Therefore use the default page size values
157 page_css_params.page_size = page_params.page_size;
160 page_css_params.margin_top =
161 ConvertUnit(margin_top_in_pixels, kPixelsPerInch, dpi);
162 page_css_params.margin_left =
163 ConvertUnit(margin_left_in_pixels, kPixelsPerInch, dpi);
164 return page_css_params;
167 double FitPrintParamsToPage(const PrintMsg_Print_Params& page_params,
168 PrintMsg_Print_Params* params_to_fit) {
169 double content_width =
170 static_cast<double>(params_to_fit->content_size.width());
171 double content_height =
172 static_cast<double>(params_to_fit->content_size.height());
173 int default_page_size_height = page_params.page_size.height();
174 int default_page_size_width = page_params.page_size.width();
175 int css_page_size_height = params_to_fit->page_size.height();
176 int css_page_size_width = params_to_fit->page_size.width();
178 double scale_factor = 1.0f;
179 if (page_params.page_size == params_to_fit->page_size)
182 if (default_page_size_width < css_page_size_width ||
183 default_page_size_height < css_page_size_height) {
185 static_cast<double>(default_page_size_width) / css_page_size_width;
186 double ratio_height =
187 static_cast<double>(default_page_size_height) / css_page_size_height;
188 scale_factor = ratio_width < ratio_height ? ratio_width : ratio_height;
189 content_width *= scale_factor;
190 content_height *= scale_factor;
192 params_to_fit->margin_top = static_cast<int>(
193 (default_page_size_height - css_page_size_height * scale_factor) / 2 +
194 (params_to_fit->margin_top * scale_factor));
195 params_to_fit->margin_left = static_cast<int>(
196 (default_page_size_width - css_page_size_width * scale_factor) / 2 +
197 (params_to_fit->margin_left * scale_factor));
198 params_to_fit->content_size = gfx::Size(
199 static_cast<int>(content_width), static_cast<int>(content_height));
200 params_to_fit->page_size = page_params.page_size;
204 void CalculatePageLayoutFromPrintParams(
205 const PrintMsg_Print_Params& params,
206 PageSizeMargins* page_layout_in_points) {
207 int dpi = GetDPI(¶ms);
208 int content_width = params.content_size.width();
209 int content_height = params.content_size.height();
211 int margin_bottom = params.page_size.height() -
212 content_height - params.margin_top;
213 int margin_right = params.page_size.width() -
214 content_width - params.margin_left;
216 page_layout_in_points->content_width =
217 ConvertUnit(content_width, dpi, kPointsPerInch);
218 page_layout_in_points->content_height =
219 ConvertUnit(content_height, dpi, kPointsPerInch);
220 page_layout_in_points->margin_top =
221 ConvertUnit(params.margin_top, dpi, kPointsPerInch);
222 page_layout_in_points->margin_right =
223 ConvertUnit(margin_right, dpi, kPointsPerInch);
224 page_layout_in_points->margin_bottom =
225 ConvertUnit(margin_bottom, dpi, kPointsPerInch);
226 page_layout_in_points->margin_left =
227 ConvertUnit(params.margin_left, dpi, kPointsPerInch);
230 void EnsureOrientationMatches(const PrintMsg_Print_Params& css_params,
231 PrintMsg_Print_Params* page_params) {
232 if ((page_params->page_size.width() > page_params->page_size.height()) ==
233 (css_params.page_size.width() > css_params.page_size.height())) {
237 // Swap the |width| and |height| values.
238 page_params->page_size.SetSize(page_params->page_size.height(),
239 page_params->page_size.width());
240 page_params->content_size.SetSize(page_params->content_size.height(),
241 page_params->content_size.width());
242 page_params->printable_area.set_size(
243 gfx::Size(page_params->printable_area.height(),
244 page_params->printable_area.width()));
247 void ComputeWebKitPrintParamsInDesiredDpi(
248 const PrintMsg_Print_Params& print_params,
249 blink::WebPrintParams* webkit_print_params) {
250 int dpi = GetDPI(&print_params);
251 webkit_print_params->printerDPI = dpi;
252 webkit_print_params->printScalingOption = print_params.print_scaling_option;
254 webkit_print_params->printContentArea.width =
255 ConvertUnit(print_params.content_size.width(), dpi,
256 print_params.desired_dpi);
257 webkit_print_params->printContentArea.height =
258 ConvertUnit(print_params.content_size.height(), dpi,
259 print_params.desired_dpi);
261 webkit_print_params->printableArea.x =
262 ConvertUnit(print_params.printable_area.x(), dpi,
263 print_params.desired_dpi);
264 webkit_print_params->printableArea.y =
265 ConvertUnit(print_params.printable_area.y(), dpi,
266 print_params.desired_dpi);
267 webkit_print_params->printableArea.width =
268 ConvertUnit(print_params.printable_area.width(), dpi,
269 print_params.desired_dpi);
270 webkit_print_params->printableArea.height =
271 ConvertUnit(print_params.printable_area.height(),
272 dpi, print_params.desired_dpi);
274 webkit_print_params->paperSize.width =
275 ConvertUnit(print_params.page_size.width(), dpi,
276 print_params.desired_dpi);
277 webkit_print_params->paperSize.height =
278 ConvertUnit(print_params.page_size.height(), dpi,
279 print_params.desired_dpi);
282 blink::WebPlugin* GetPlugin(const blink::WebFrame* frame) {
283 return frame->document().isPluginDocument() ?
284 frame->document().to<blink::WebPluginDocument>().plugin() : NULL;
287 bool PrintingNodeOrPdfFrame(const blink::WebFrame* frame,
288 const blink::WebNode& node) {
291 blink::WebPlugin* plugin = GetPlugin(frame);
292 return plugin && plugin->supportsPaginatedPrint();
295 bool PrintingFrameHasPageSizeStyle(blink::WebFrame* frame,
296 int total_page_count) {
299 bool frame_has_custom_page_size_style = false;
300 for (int i = 0; i < total_page_count; ++i) {
301 if (frame->hasCustomPageSizeStyle(i)) {
302 frame_has_custom_page_size_style = true;
306 return frame_has_custom_page_size_style;
309 MarginType GetMarginsForPdf(blink::WebFrame* frame,
310 const blink::WebNode& node) {
311 if (frame->isPrintScalingDisabledForPlugin(node))
314 return PRINTABLE_AREA_MARGINS;
317 bool FitToPageEnabled(const base::DictionaryValue& job_settings) {
318 bool fit_to_paper_size = false;
319 if (!job_settings.GetBoolean(kSettingFitToPageEnabled, &fit_to_paper_size)) {
322 return fit_to_paper_size;
325 // Returns the print scaling option to retain/scale/crop the source page size
326 // to fit the printable area of the paper.
328 // We retain the source page size when the current destination printer is
331 // We crop the source page size to fit the printable area or we print only the
332 // left top page contents when
333 // (1) Source is PDF and the user has requested not to fit to printable area
334 // via |job_settings|.
335 // (2) Source is PDF. This is the first preview request and print scaling
336 // option is disabled for initiator renderer plugin.
338 // In all other cases, we scale the source page to fit the printable area.
339 blink::WebPrintScalingOption GetPrintScalingOption(
340 blink::WebFrame* frame,
341 const blink::WebNode& node,
343 const base::DictionaryValue& job_settings,
344 const PrintMsg_Print_Params& params) {
345 if (params.print_to_pdf)
346 return blink::WebPrintScalingOptionSourceSize;
348 if (!source_is_html) {
349 if (!FitToPageEnabled(job_settings))
350 return blink::WebPrintScalingOptionNone;
352 bool no_plugin_scaling = frame->isPrintScalingDisabledForPlugin(node);
354 if (params.is_first_request && no_plugin_scaling)
355 return blink::WebPrintScalingOptionNone;
357 return blink::WebPrintScalingOptionFitToPrintableArea;
360 PrintMsg_Print_Params CalculatePrintParamsForCss(
361 blink::WebFrame* frame,
363 const PrintMsg_Print_Params& page_params,
364 bool ignore_css_margins,
366 double* scale_factor) {
367 PrintMsg_Print_Params css_params = GetCssPrintParams(frame, page_index,
370 PrintMsg_Print_Params params = page_params;
371 EnsureOrientationMatches(css_params, ¶ms);
373 if (ignore_css_margins && fit_to_page)
376 PrintMsg_Print_Params result_params = css_params;
377 if (ignore_css_margins) {
378 result_params.margin_top = params.margin_top;
379 result_params.margin_left = params.margin_left;
381 DCHECK(!fit_to_page);
382 // Since we are ignoring the margins, the css page size is no longer
384 int default_margin_right = params.page_size.width() -
385 params.content_size.width() - params.margin_left;
386 int default_margin_bottom = params.page_size.height() -
387 params.content_size.height() - params.margin_top;
388 result_params.content_size = gfx::Size(
389 result_params.page_size.width() - result_params.margin_left -
390 default_margin_right,
391 result_params.page_size.height() - result_params.margin_top -
392 default_margin_bottom);
396 double factor = FitPrintParamsToPage(params, &result_params);
398 *scale_factor = factor;
400 return result_params;
403 bool IsPrintPreviewEnabled() {
404 return CommandLine::ForCurrentProcess()->HasSwitch(
405 switches::kRendererPrintPreview);
408 bool IsPrintThrottlingDisabled() {
409 return CommandLine::ForCurrentProcess()->HasSwitch(
410 switches::kDisableScriptedPrintThrottling);
415 FrameReference::FrameReference(const blink::WebFrame* frame) {
419 FrameReference::FrameReference() {
423 FrameReference::~FrameReference() {
426 void FrameReference::Reset(const blink::WebFrame* frame) {
428 view_ = frame->view();
429 frame_name_ = frame->uniqueName();
436 blink::WebFrame* FrameReference::GetFrame() {
437 return view_ ? view_->findFrameByName(frame_name_) : NULL;
440 blink::WebView* FrameReference::view() {
444 // static - Not anonymous so that platform implementations can use it.
445 void PrintWebViewHelper::PrintHeaderAndFooter(
446 blink::WebCanvas* canvas,
449 float webkit_scale_factor,
450 const PageSizeMargins& page_layout,
451 const base::DictionaryValue& header_footer_info,
452 const PrintMsg_Print_Params& params) {
453 skia::VectorPlatformDeviceSkia* device =
454 static_cast<skia::VectorPlatformDeviceSkia*>(canvas->getTopDevice());
455 device->setDrawingArea(SkPDFDevice::kMargin_DrawingArea);
457 SkAutoCanvasRestore auto_restore(canvas, true);
458 canvas->scale(1 / webkit_scale_factor, 1 / webkit_scale_factor);
460 blink::WebSize page_size(page_layout.margin_left + page_layout.margin_right +
461 page_layout.content_width,
462 page_layout.margin_top + page_layout.margin_bottom +
463 page_layout.content_height);
465 blink::WebView* web_view = blink::WebView::create(NULL);
466 web_view->settings()->setJavaScriptEnabled(true);
467 blink::WebFrame* frame = blink::WebFrame::create(NULL);
468 web_view->setMainFrame(frame);
470 base::StringValue html(
471 ResourceBundle::GetSharedInstance().GetLocalizedString(
472 IDR_PRINT_PREVIEW_PAGE));
473 // Load page with script to avoid async operations.
474 ExecuteScript(frame, kPageLoadScriptFormat, html);
476 scoped_ptr<base::DictionaryValue> options(header_footer_info.DeepCopy());
477 options->SetDouble("width", page_size.width);
478 options->SetDouble("height", page_size.height);
479 options->SetDouble("topMargin", page_layout.margin_top);
480 options->SetDouble("bottomMargin", page_layout.margin_bottom);
481 options->SetString("pageNumber",
482 base::StringPrintf("%d/%d", page_number, total_pages));
484 ExecuteScript(frame, kPageSetupScriptFormat, *options);
486 blink::WebPrintParams webkit_params(page_size);
487 webkit_params.printerDPI = GetDPI(¶ms);
489 frame->printBegin(webkit_params);
490 frame->printPage(0, canvas);
496 device->setDrawingArea(SkPDFDevice::kContent_DrawingArea);
499 // static - Not anonymous so that platform implementations can use it.
500 float PrintWebViewHelper::RenderPageContent(blink::WebFrame* frame,
502 const gfx::Rect& canvas_area,
503 const gfx::Rect& content_area,
505 blink::WebCanvas* canvas) {
506 SkAutoCanvasRestore auto_restore(canvas, true);
507 if (content_area != canvas_area) {
508 canvas->translate((content_area.x() - canvas_area.x()) / scale_factor,
509 (content_area.y() - canvas_area.y()) / scale_factor);
511 SkRect::MakeXYWH(content_area.origin().x() / scale_factor,
512 content_area.origin().y() / scale_factor,
513 content_area.size().width() / scale_factor,
514 content_area.size().height() / scale_factor));
515 SkIRect clip_int_rect;
516 clip_rect.roundOut(&clip_int_rect);
517 SkRegion clip_region(clip_int_rect);
518 canvas->setClipRegion(clip_region);
520 return frame->printPage(page_number, canvas);
523 // Class that calls the Begin and End print functions on the frame and changes
524 // the size of the view temporarily to support full page printing..
525 class PrepareFrameAndViewForPrint : public blink::WebViewClient,
526 public blink::WebFrameClient {
528 PrepareFrameAndViewForPrint(const PrintMsg_Print_Params& params,
529 blink::WebFrame* frame,
530 const blink::WebNode& node,
531 bool ignore_css_margins);
532 virtual ~PrepareFrameAndViewForPrint();
534 // Optional. Replaces |frame_| with selection if needed. Will call |on_ready|
536 void CopySelectionIfNeeded(const WebPreferences& preferences,
537 const base::Closure& on_ready);
539 // Prepares frame for printing.
540 void StartPrinting();
542 blink::WebFrame* frame() {
543 return frame_.GetFrame();
546 const blink::WebNode& node() const {
547 return node_to_print_;
550 int GetExpectedPageCount() const {
551 return expected_pages_count_;
554 gfx::Size GetPrintCanvasSize() const;
556 void FinishPrinting();
558 bool IsLoadingSelection() {
559 // It's not selection if not |owns_web_view_|.
560 return owns_web_view_ && frame() && frame()->isLoading();
564 // blink::WebViewClient override:
565 virtual void didStopLoading();
567 // blink::WebFrameClient override:
568 virtual blink::WebFrame* createChildFrame(blink::WebFrame* parent,
569 const blink::WebString& name);
570 virtual void frameDetached(blink::WebFrame* frame);
574 void ResizeForPrinting();
576 void CopySelection(const WebPreferences& preferences);
578 base::WeakPtrFactory<PrepareFrameAndViewForPrint> weak_ptr_factory_;
580 FrameReference frame_;
581 blink::WebNode node_to_print_;
583 blink::WebPrintParams web_print_params_;
584 gfx::Size prev_view_size_;
585 gfx::Size prev_scroll_offset_;
586 int expected_pages_count_;
587 base::Closure on_ready_;
588 bool should_print_backgrounds_;
589 bool should_print_selection_only_;
590 bool is_printing_started_;
592 DISALLOW_COPY_AND_ASSIGN(PrepareFrameAndViewForPrint);
595 PrepareFrameAndViewForPrint::PrepareFrameAndViewForPrint(
596 const PrintMsg_Print_Params& params,
597 blink::WebFrame* frame,
598 const blink::WebNode& node,
599 bool ignore_css_margins)
600 : weak_ptr_factory_(this),
602 node_to_print_(node),
603 owns_web_view_(false),
604 expected_pages_count_(0),
605 should_print_backgrounds_(params.should_print_backgrounds),
606 should_print_selection_only_(params.selection_only),
607 is_printing_started_(false) {
608 PrintMsg_Print_Params print_params = params;
609 if (!should_print_selection_only_ ||
610 !PrintingNodeOrPdfFrame(frame, node_to_print_)) {
611 bool fit_to_page = ignore_css_margins &&
612 print_params.print_scaling_option ==
613 blink::WebPrintScalingOptionFitToPrintableArea;
614 ComputeWebKitPrintParamsInDesiredDpi(params, &web_print_params_);
615 frame->printBegin(web_print_params_, node_to_print_);
616 print_params = CalculatePrintParamsForCss(frame, 0, print_params,
617 ignore_css_margins, fit_to_page,
621 ComputeWebKitPrintParamsInDesiredDpi(print_params, &web_print_params_);
624 PrepareFrameAndViewForPrint::~PrepareFrameAndViewForPrint() {
628 void PrepareFrameAndViewForPrint::ResizeForPrinting() {
629 // Layout page according to printer page size. Since WebKit shrinks the
630 // size of the page automatically (from 125% to 200%) we trick it to
631 // think the page is 125% larger so the size of the page is correct for
632 // minimum (default) scaling.
633 // This is important for sites that try to fill the page.
634 gfx::Size print_layout_size(web_print_params_.printContentArea.width,
635 web_print_params_.printContentArea.height);
636 print_layout_size.set_height(
637 static_cast<int>(static_cast<double>(print_layout_size.height()) * 1.25));
641 blink::WebView* web_view = frame_.view();
642 // Backup size and offset.
643 if (blink::WebFrame* web_frame = web_view->mainFrame())
644 prev_scroll_offset_ = web_frame->scrollOffset();
645 prev_view_size_ = web_view->size();
647 web_view->resize(print_layout_size);
651 void PrepareFrameAndViewForPrint::StartPrinting() {
653 blink::WebView* web_view = frame_.view();
654 web_view->settings()->setShouldPrintBackgrounds(should_print_backgrounds_);
655 expected_pages_count_ =
656 frame()->printBegin(web_print_params_, node_to_print_);
657 is_printing_started_ = true;
660 void PrepareFrameAndViewForPrint::CopySelectionIfNeeded(
661 const WebPreferences& preferences,
662 const base::Closure& on_ready) {
663 on_ready_ = on_ready;
664 if (should_print_selection_only_)
665 CopySelection(preferences);
670 void PrepareFrameAndViewForPrint::CopySelection(
671 const WebPreferences& preferences) {
673 std::string url_str = "data:text/html;charset=utf-8,";
675 net::EscapeQueryParamValue(frame()->selectionAsMarkup().utf8(), false));
677 // Create a new WebView with the same settings as the current display one.
678 // Except that we disable javascript (don't want any active content running
680 WebPreferences prefs = preferences;
681 prefs.javascript_enabled = false;
682 prefs.java_enabled = false;
684 blink::WebView* web_view = blink::WebView::create(this);
685 owns_web_view_ = true;
686 content::ApplyWebPreferences(prefs, web_view);
687 web_view->setMainFrame(blink::WebFrame::create(this));
688 frame_.Reset(web_view->mainFrame());
689 node_to_print_.reset();
691 // When loading is done this will call didStopLoading() and that will do the
693 frame()->loadRequest(blink::WebURLRequest(GURL(url_str)));
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(
702 base::Bind(&PrepareFrameAndViewForPrint::CallOnReady,
703 weak_ptr_factory_.GetWeakPtr()));
706 blink::WebFrame* PrepareFrameAndViewForPrint::createChildFrame(
707 blink::WebFrame* parent,
708 const blink::WebString& name) {
709 return blink::WebFrame::create(this);
712 void PrepareFrameAndViewForPrint::frameDetached(blink::WebFrame* frame) {
716 void PrepareFrameAndViewForPrint::CallOnReady() {
717 return on_ready_.Run(); // Can delete |this|.
720 gfx::Size PrepareFrameAndViewForPrint::GetPrintCanvasSize() const {
721 DCHECK(is_printing_started_);
722 return gfx::Size(web_print_params_.printContentArea.width,
723 web_print_params_.printContentArea.height);
726 void PrepareFrameAndViewForPrint::RestoreSize() {
728 blink::WebView* web_view = frame_.GetFrame()->view();
729 web_view->resize(prev_view_size_);
730 if (blink::WebFrame* web_frame = web_view->mainFrame())
731 web_frame->setScrollOffset(prev_scroll_offset_);
735 void PrepareFrameAndViewForPrint::FinishPrinting() {
736 blink::WebFrame* frame = frame_.GetFrame();
738 blink::WebView* web_view = frame->view();
739 if (is_printing_started_) {
740 is_printing_started_ = false;
742 if (!owns_web_view_) {
743 web_view->settings()->setShouldPrintBackgrounds(false);
747 if (owns_web_view_) {
748 DCHECK(!frame->isLoading());
749 owns_web_view_ = false;
757 PrintWebViewHelper::PrintWebViewHelper(content::RenderView* render_view)
758 : content::RenderViewObserver(render_view),
759 content::RenderViewObserverTracker<PrintWebViewHelper>(render_view),
760 reset_prep_frame_view_(false),
761 is_preview_enabled_(IsPrintPreviewEnabled()),
762 is_scripted_print_throttling_disabled_(IsPrintThrottlingDisabled()),
763 is_print_ready_metafile_sent_(false),
764 ignore_css_margins_(false),
765 user_cancelled_scripted_print_count_(0),
766 is_scripted_printing_blocked_(false),
767 notify_browser_of_print_failure_(true),
768 print_for_preview_(false),
769 print_node_in_progress_(false),
771 is_scripted_preview_delayed_(false),
772 weak_ptr_factory_(this) {
775 PrintWebViewHelper::~PrintWebViewHelper() {}
777 bool PrintWebViewHelper::IsScriptInitiatedPrintAllowed(
778 blink::WebFrame* frame, bool user_initiated) {
779 #if defined(OS_ANDROID)
781 #endif // defined(OS_ANDROID)
782 if (is_scripted_printing_blocked_)
784 // If preview is enabled, then the print dialog is tab modal, and the user
785 // can always close the tab on a mis-behaving page (the system print dialog
786 // is app modal). If the print was initiated through user action, don't
787 // throttle. Or, if the command line flag to skip throttling has been set.
788 if (!is_scripted_print_throttling_disabled_ &&
789 !is_preview_enabled_ &&
791 return !IsScriptInitiatedPrintTooFrequent(frame);
795 void PrintWebViewHelper::DidStartLoading() {
799 void PrintWebViewHelper::DidStopLoading() {
801 ShowScriptedPrintPreview();
804 // Prints |frame| which called window.print().
805 void PrintWebViewHelper::PrintPage(blink::WebFrame* frame,
806 bool user_initiated) {
809 // Allow Prerendering to cancel this print request if necessary.
810 if (prerender::PrerenderHelper::IsPrerendering(
811 render_view()->GetMainRenderFrame())) {
812 Send(new ChromeViewHostMsg_CancelPrerenderForPrinting(routing_id()));
816 if (!IsScriptInitiatedPrintAllowed(frame, user_initiated))
818 IncrementScriptedPrintCount();
820 if (is_preview_enabled_) {
821 print_preview_context_.InitWithFrame(frame);
822 RequestPrintPreview(PRINT_PREVIEW_SCRIPTED);
824 Print(frame, blink::WebNode());
828 bool PrintWebViewHelper::OnMessageReceived(const IPC::Message& message) {
830 IPC_BEGIN_MESSAGE_MAP(PrintWebViewHelper, message)
831 IPC_MESSAGE_HANDLER(PrintMsg_PrintPages, OnPrintPages)
832 IPC_MESSAGE_HANDLER(PrintMsg_PrintForSystemDialog, OnPrintForSystemDialog)
833 IPC_MESSAGE_HANDLER(PrintMsg_InitiatePrintPreview, OnInitiatePrintPreview)
834 IPC_MESSAGE_HANDLER(PrintMsg_PrintNodeUnderContextMenu,
835 OnPrintNodeUnderContextMenu)
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_ResetScriptedPrintCount,
840 ResetScriptedPrintCount)
841 IPC_MESSAGE_HANDLER(PrintMsg_SetScriptedPrintingBlocked,
842 SetScriptedPrintBlocked)
843 IPC_MESSAGE_UNHANDLED(handled = false)
844 IPC_END_MESSAGE_MAP()
848 void PrintWebViewHelper::OnPrintForPrintPreview(
849 const base::DictionaryValue& job_settings) {
850 DCHECK(is_preview_enabled_);
851 // If still not finished with earlier print request simply ignore.
852 if (prep_frame_view_)
855 if (!render_view()->GetWebView())
857 blink::WebFrame* main_frame = render_view()->GetWebView()->mainFrame();
861 blink::WebDocument document = main_frame->document();
862 // <object> with id="pdf-viewer" is created in
863 // chrome/browser/resources/print_preview/print_preview.js
864 blink::WebElement pdf_element = document.getElementById("pdf-viewer");
865 if (pdf_element.isNull()) {
870 // Set |print_for_preview_| flag and autoreset it to back to original
872 base::AutoReset<bool> set_printing_flag(&print_for_preview_, true);
874 blink::WebFrame* pdf_frame = pdf_element.document().frame();
875 if (!UpdatePrintSettings(pdf_frame, pdf_element, job_settings)) {
876 LOG(ERROR) << "UpdatePrintSettings failed";
877 DidFinishPrinting(FAIL_PRINT);
881 // Print page onto entire page not just printable area. Preview PDF already
882 // has content in correct position taking into account page size and printable
884 // TODO(vitalybuka) : Make this consistent on all platform. This change
885 // affects Windows only. On Linux and OSX RenderPagesForPrint does not use
886 // printable_area. Also we can't change printable_area deeper inside
887 // RenderPagesForPrint for Windows, because it's used also by native
888 // printing and it expects real printable_area value.
889 // See http://crbug.com/123408
890 PrintMsg_Print_Params& print_params = print_pages_params_->params;
891 print_params.printable_area = gfx::Rect(print_params.page_size);
893 // Render Pages for printing.
894 if (!RenderPagesForPrint(pdf_frame, pdf_element)) {
895 LOG(ERROR) << "RenderPagesForPrint failed";
896 DidFinishPrinting(FAIL_PRINT);
900 bool PrintWebViewHelper::GetPrintFrame(blink::WebFrame** frame) {
902 blink::WebView* webView = render_view()->GetWebView();
907 // If the user has selected text in the currently focused frame we print
908 // only that frame (this makes print selection work for multiple frames).
909 blink::WebFrame* focusedFrame = webView->focusedFrame();
910 *frame = focusedFrame->hasSelection() ? focusedFrame : webView->mainFrame();
914 void PrintWebViewHelper::OnPrintPages() {
915 blink::WebFrame* frame;
916 if (GetPrintFrame(&frame))
917 Print(frame, blink::WebNode());
920 void PrintWebViewHelper::OnPrintForSystemDialog() {
921 blink::WebFrame* frame = print_preview_context_.source_frame();
927 Print(frame, print_preview_context_.source_node());
930 void PrintWebViewHelper::GetPageSizeAndContentAreaFromPageLayout(
931 const PageSizeMargins& page_layout_in_points,
932 gfx::Size* page_size,
933 gfx::Rect* content_area) {
934 *page_size = gfx::Size(
935 page_layout_in_points.content_width +
936 page_layout_in_points.margin_right +
937 page_layout_in_points.margin_left,
938 page_layout_in_points.content_height +
939 page_layout_in_points.margin_top +
940 page_layout_in_points.margin_bottom);
941 *content_area = gfx::Rect(page_layout_in_points.margin_left,
942 page_layout_in_points.margin_top,
943 page_layout_in_points.content_width,
944 page_layout_in_points.content_height);
947 void PrintWebViewHelper::UpdateFrameMarginsCssInfo(
948 const base::DictionaryValue& settings) {
949 int margins_type = 0;
950 if (!settings.GetInteger(kSettingMarginsType, &margins_type))
951 margins_type = DEFAULT_MARGINS;
952 ignore_css_margins_ = (margins_type != DEFAULT_MARGINS);
955 bool PrintWebViewHelper::IsPrintToPdfRequested(
956 const base::DictionaryValue& job_settings) {
957 bool print_to_pdf = false;
958 if (!job_settings.GetBoolean(kSettingPrintToPDF, &print_to_pdf))
963 void PrintWebViewHelper::OnPrintPreview(const base::DictionaryValue& settings) {
964 DCHECK(is_preview_enabled_);
965 print_preview_context_.OnPrintPreview();
967 UMA_HISTOGRAM_ENUMERATION("PrintPreview.PreviewEvent",
968 PREVIEW_EVENT_REQUESTED, PREVIEW_EVENT_MAX);
969 if (!print_preview_context_.source_frame() ||
970 !UpdatePrintSettings(print_preview_context_.source_frame(),
971 print_preview_context_.source_node(), settings)) {
972 if (print_preview_context_.last_error() != PREVIEW_ERROR_BAD_SETTING) {
973 Send(new PrintHostMsg_PrintPreviewInvalidPrinterSettings(
974 routing_id(), print_pages_params_->params.document_cookie));
975 notify_browser_of_print_failure_ = false; // Already sent.
977 DidFinishPrinting(FAIL_PREVIEW);
981 // If we are previewing a pdf and the print scaling is disabled, send a
982 // message to browser.
983 if (print_pages_params_->params.is_first_request &&
984 !print_preview_context_.IsModifiable() &&
985 print_preview_context_.source_frame()->isPrintScalingDisabledForPlugin(
986 print_preview_context_.source_node())) {
987 Send(new PrintHostMsg_PrintPreviewScalingDisabled(routing_id()));
990 is_print_ready_metafile_sent_ = false;
992 // PDF printer device supports alpha blending.
993 print_pages_params_->params.supports_alpha_blend = true;
995 bool generate_draft_pages = false;
996 if (!settings.GetBoolean(kSettingGenerateDraftData,
997 &generate_draft_pages)) {
1000 print_preview_context_.set_generate_draft_pages(generate_draft_pages);
1002 PrepareFrameForPreviewDocument();
1005 void PrintWebViewHelper::PrepareFrameForPreviewDocument() {
1006 reset_prep_frame_view_ = false;
1008 if (!print_pages_params_ || CheckForCancel()) {
1009 DidFinishPrinting(FAIL_PREVIEW);
1013 // Don't reset loading frame or WebKit will fail assert. Just retry when
1014 // current selection is loaded.
1015 if (prep_frame_view_ && prep_frame_view_->IsLoadingSelection()) {
1016 reset_prep_frame_view_ = true;
1020 const PrintMsg_Print_Params& print_params = print_pages_params_->params;
1021 prep_frame_view_.reset(
1022 new PrepareFrameAndViewForPrint(print_params,
1023 print_preview_context_.source_frame(),
1024 print_preview_context_.source_node(),
1025 ignore_css_margins_));
1026 prep_frame_view_->CopySelectionIfNeeded(
1027 render_view()->GetWebkitPreferences(),
1028 base::Bind(&PrintWebViewHelper::OnFramePreparedForPreviewDocument,
1029 base::Unretained(this)));
1032 void PrintWebViewHelper::OnFramePreparedForPreviewDocument() {
1033 if (reset_prep_frame_view_) {
1034 PrepareFrameForPreviewDocument();
1037 DidFinishPrinting(CreatePreviewDocument() ? OK : FAIL_PREVIEW);
1040 bool PrintWebViewHelper::CreatePreviewDocument() {
1041 if (!print_pages_params_ || CheckForCancel())
1044 UMA_HISTOGRAM_ENUMERATION("PrintPreview.PreviewEvent",
1045 PREVIEW_EVENT_CREATE_DOCUMENT, PREVIEW_EVENT_MAX);
1047 const PrintMsg_Print_Params& print_params = print_pages_params_->params;
1048 const std::vector<int>& pages = print_pages_params_->pages;
1050 if (!print_preview_context_.CreatePreviewDocument(prep_frame_view_.release(),
1055 PageSizeMargins default_page_layout;
1056 ComputePageLayoutInPointsForCss(print_preview_context_.prepared_frame(), 0,
1057 print_params, ignore_css_margins_, NULL,
1058 &default_page_layout);
1060 bool has_page_size_style = PrintingFrameHasPageSizeStyle(
1061 print_preview_context_.prepared_frame(),
1062 print_preview_context_.total_page_count());
1063 int dpi = GetDPI(&print_params);
1065 gfx::Rect printable_area_in_points(
1066 ConvertUnit(print_params.printable_area.x(), dpi, kPointsPerInch),
1067 ConvertUnit(print_params.printable_area.y(), dpi, kPointsPerInch),
1068 ConvertUnit(print_params.printable_area.width(), dpi, kPointsPerInch),
1069 ConvertUnit(print_params.printable_area.height(), dpi, kPointsPerInch));
1071 // Margins: Send default page layout to browser process.
1072 Send(new PrintHostMsg_DidGetDefaultPageLayout(routing_id(),
1073 default_page_layout,
1074 printable_area_in_points,
1075 has_page_size_style));
1077 PrintHostMsg_DidGetPreviewPageCount_Params params;
1078 params.page_count = print_preview_context_.total_page_count();
1079 params.is_modifiable = print_preview_context_.IsModifiable();
1080 params.document_cookie = print_params.document_cookie;
1081 params.preview_request_id = print_params.preview_request_id;
1082 params.clear_preview_data = print_preview_context_.generate_draft_pages();
1083 Send(new PrintHostMsg_DidGetPreviewPageCount(routing_id(), params));
1084 if (CheckForCancel())
1087 while (!print_preview_context_.IsFinalPageRendered()) {
1088 int page_number = print_preview_context_.GetNextPageNumber();
1089 DCHECK_GE(page_number, 0);
1090 if (!RenderPreviewPage(page_number, print_params))
1093 if (CheckForCancel())
1096 // We must call PrepareFrameAndViewForPrint::FinishPrinting() (by way of
1097 // print_preview_context_.AllPagesRendered()) before calling
1098 // FinalizePrintReadyDocument() when printing a PDF because the plugin
1099 // code does not generate output until we call FinishPrinting(). We do not
1100 // generate draft pages for PDFs, so IsFinalPageRendered() and
1101 // IsLastPageOfPrintReadyMetafile() will be true in the same iteration of
1103 if (print_preview_context_.IsFinalPageRendered())
1104 print_preview_context_.AllPagesRendered();
1106 if (print_preview_context_.IsLastPageOfPrintReadyMetafile()) {
1107 DCHECK(print_preview_context_.IsModifiable() ||
1108 print_preview_context_.IsFinalPageRendered());
1109 if (!FinalizePrintReadyDocument())
1113 print_preview_context_.Finished();
1117 bool PrintWebViewHelper::FinalizePrintReadyDocument() {
1118 DCHECK(!is_print_ready_metafile_sent_);
1119 print_preview_context_.FinalizePrintReadyDocument();
1121 // Get the size of the resulting metafile.
1122 PreviewMetafile* metafile = print_preview_context_.metafile();
1123 uint32 buf_size = metafile->GetDataSize();
1124 DCHECK_GT(buf_size, 0u);
1126 PrintHostMsg_DidPreviewDocument_Params preview_params;
1127 preview_params.data_size = buf_size;
1128 preview_params.document_cookie = print_pages_params_->params.document_cookie;
1129 preview_params.expected_pages_count =
1130 print_preview_context_.total_page_count();
1131 preview_params.modifiable = print_preview_context_.IsModifiable();
1132 preview_params.preview_request_id =
1133 print_pages_params_->params.preview_request_id;
1135 // Ask the browser to create the shared memory for us.
1136 if (!CopyMetafileDataToSharedMem(metafile,
1137 &(preview_params.metafile_data_handle))) {
1138 LOG(ERROR) << "CopyMetafileDataToSharedMem failed";
1139 print_preview_context_.set_error(PREVIEW_ERROR_METAFILE_COPY_FAILED);
1142 is_print_ready_metafile_sent_ = true;
1144 Send(new PrintHostMsg_MetafileReadyForPrinting(routing_id(), preview_params));
1148 void PrintWebViewHelper::OnPrintingDone(bool success) {
1149 notify_browser_of_print_failure_ = false;
1151 LOG(ERROR) << "Failure in OnPrintingDone";
1152 DidFinishPrinting(success ? OK : FAIL_PRINT);
1155 void PrintWebViewHelper::SetScriptedPrintBlocked(bool blocked) {
1156 is_scripted_printing_blocked_ = blocked;
1159 void PrintWebViewHelper::OnPrintNodeUnderContextMenu() {
1160 PrintNode(render_view()->GetContextMenuNode());
1163 void PrintWebViewHelper::OnInitiatePrintPreview(bool selection_only) {
1164 DCHECK(is_preview_enabled_);
1165 blink::WebFrame* frame = NULL;
1166 GetPrintFrame(&frame);
1168 print_preview_context_.InitWithFrame(frame);
1169 RequestPrintPreview(selection_only ?
1170 PRINT_PREVIEW_USER_INITIATED_SELECTION :
1171 PRINT_PREVIEW_USER_INITIATED_ENTIRE_FRAME);
1174 bool PrintWebViewHelper::IsPrintingEnabled() {
1175 bool result = false;
1176 Send(new PrintHostMsg_IsPrintingEnabled(routing_id(), &result));
1180 void PrintWebViewHelper::PrintNode(const blink::WebNode& node) {
1181 if (node.isNull() || !node.document().frame()) {
1182 // This can occur when the context menu refers to an invalid WebNode.
1183 // See http://crbug.com/100890#c17 for a repro case.
1187 if (print_node_in_progress_) {
1188 // This can happen as a result of processing sync messages when printing
1189 // from ppapi plugins. It's a rare case, so its OK to just fail here.
1190 // See http://crbug.com/159165.
1194 print_node_in_progress_ = true;
1196 // Make a copy of the node, in case RenderView::OnContextMenuClosed resets
1197 // its |context_menu_node_|.
1198 if (is_preview_enabled_) {
1199 print_preview_context_.InitWithNode(node);
1200 RequestPrintPreview(PRINT_PREVIEW_USER_INITIATED_CONTEXT_NODE);
1202 blink::WebNode duplicate_node(node);
1203 Print(duplicate_node.document().frame(), duplicate_node);
1206 print_node_in_progress_ = false;
1209 void PrintWebViewHelper::Print(blink::WebFrame* frame,
1210 const blink::WebNode& node) {
1211 // If still not finished with earlier print request simply ignore.
1212 if (prep_frame_view_)
1215 FrameReference frame_ref(frame);
1217 int expected_page_count = 0;
1218 if (!CalculateNumberOfPages(frame, node, &expected_page_count)) {
1219 DidFinishPrinting(FAIL_PRINT_INIT);
1220 return; // Failed to init print page settings.
1223 // Some full screen plugins can say they don't want to print.
1224 if (!expected_page_count) {
1225 DidFinishPrinting(FAIL_PRINT);
1229 // Ask the browser to show UI to retrieve the final print settings.
1230 if (!GetPrintSettingsFromUser(frame_ref.GetFrame(), node,
1231 expected_page_count)) {
1232 DidFinishPrinting(OK); // Release resources and fail silently.
1236 // Render Pages for printing.
1237 if (!RenderPagesForPrint(frame_ref.GetFrame(), node)) {
1238 LOG(ERROR) << "RenderPagesForPrint failed";
1239 DidFinishPrinting(FAIL_PRINT);
1241 ResetScriptedPrintCount();
1244 void PrintWebViewHelper::DidFinishPrinting(PrintingResult result) {
1249 case FAIL_PRINT_INIT:
1250 DCHECK(!notify_browser_of_print_failure_);
1254 if (notify_browser_of_print_failure_ && print_pages_params_.get()) {
1255 int cookie = print_pages_params_->params.document_cookie;
1256 Send(new PrintHostMsg_PrintingFailed(routing_id(), cookie));
1261 DCHECK(is_preview_enabled_);
1262 int cookie = print_pages_params_.get() ?
1263 print_pages_params_->params.document_cookie : 0;
1264 if (notify_browser_of_print_failure_) {
1265 LOG(ERROR) << "CreatePreviewDocument failed";
1266 Send(new PrintHostMsg_PrintPreviewFailed(routing_id(), cookie));
1268 Send(new PrintHostMsg_PrintPreviewCancelled(routing_id(), cookie));
1270 print_preview_context_.Failed(notify_browser_of_print_failure_);
1273 prep_frame_view_.reset();
1274 print_pages_params_.reset();
1275 notify_browser_of_print_failure_ = true;
1278 void PrintWebViewHelper::OnFramePreparedForPrintPages() {
1280 FinishFramePrinting();
1283 void PrintWebViewHelper::PrintPages() {
1284 if (!prep_frame_view_) // Printing is already canceled or failed.
1286 prep_frame_view_->StartPrinting();
1288 int page_count = prep_frame_view_->GetExpectedPageCount();
1290 LOG(ERROR) << "Can't print 0 pages.";
1291 return DidFinishPrinting(FAIL_PRINT);
1294 const PrintMsg_PrintPages_Params& params = *print_pages_params_;
1295 const PrintMsg_Print_Params& print_params = params.params;
1297 #if !defined(OS_CHROMEOS) && !defined(OS_ANDROID)
1298 // TODO(vitalybuka): should be page_count or valid pages from params.pages.
1299 // See http://crbug.com/161576
1300 Send(new PrintHostMsg_DidGetPrintedPagesCount(routing_id(),
1301 print_params.document_cookie,
1303 #endif // !defined(OS_CHROMEOS)
1305 if (print_params.preview_ui_id < 0) {
1306 // Printing for system dialog.
1307 int printed_count = params.pages.empty() ? page_count : params.pages.size();
1308 #if !defined(OS_CHROMEOS)
1309 UMA_HISTOGRAM_COUNTS("PrintPreview.PageCount.SystemDialog", printed_count);
1311 UMA_HISTOGRAM_COUNTS("PrintPreview.PageCount.PrintToCloudPrintWebDialog",
1313 #endif // !defined(OS_CHROMEOS)
1317 if (!PrintPagesNative(prep_frame_view_->frame(), page_count,
1318 prep_frame_view_->GetPrintCanvasSize())) {
1319 LOG(ERROR) << "Printing failed.";
1320 return DidFinishPrinting(FAIL_PRINT);
1324 void PrintWebViewHelper::FinishFramePrinting() {
1325 prep_frame_view_.reset();
1328 #if defined(OS_MACOSX) || defined(OS_WIN)
1329 bool PrintWebViewHelper::PrintPagesNative(blink::WebFrame* frame,
1331 const gfx::Size& canvas_size) {
1332 const PrintMsg_PrintPages_Params& params = *print_pages_params_;
1333 const PrintMsg_Print_Params& print_params = params.params;
1335 PrintMsg_PrintPage_Params page_params;
1336 page_params.params = print_params;
1337 if (params.pages.empty()) {
1338 for (int i = 0; i < page_count; ++i) {
1339 page_params.page_number = i;
1340 PrintPageInternal(page_params, canvas_size, frame);
1343 for (size_t i = 0; i < params.pages.size(); ++i) {
1344 if (params.pages[i] >= page_count)
1346 page_params.page_number = params.pages[i];
1347 PrintPageInternal(page_params, canvas_size, frame);
1353 #endif // OS_MACOSX || OS_WIN
1355 // static - Not anonymous so that platform implementations can use it.
1356 void PrintWebViewHelper::ComputePageLayoutInPointsForCss(
1357 blink::WebFrame* frame,
1359 const PrintMsg_Print_Params& page_params,
1360 bool ignore_css_margins,
1361 double* scale_factor,
1362 PageSizeMargins* page_layout_in_points) {
1363 PrintMsg_Print_Params params = CalculatePrintParamsForCss(
1364 frame, page_index, page_params, ignore_css_margins,
1365 page_params.print_scaling_option ==
1366 blink::WebPrintScalingOptionFitToPrintableArea,
1368 CalculatePageLayoutFromPrintParams(params, page_layout_in_points);
1371 bool PrintWebViewHelper::InitPrintSettings(bool fit_to_paper_size) {
1372 PrintMsg_PrintPages_Params settings;
1373 Send(new PrintHostMsg_GetDefaultPrintSettings(routing_id(),
1375 // Check if the printer returned any settings, if the settings is empty, we
1376 // can safely assume there are no printer drivers configured. So we safely
1379 if (!PrintMsg_Print_Params_IsValid(settings.params))
1383 (settings.params.dpi < kMinDpi || settings.params.document_cookie == 0)) {
1384 // Invalid print page settings.
1389 // Reset to default values.
1390 ignore_css_margins_ = false;
1391 settings.pages.clear();
1393 settings.params.print_scaling_option =
1394 blink::WebPrintScalingOptionSourceSize;
1395 if (fit_to_paper_size) {
1396 settings.params.print_scaling_option =
1397 blink::WebPrintScalingOptionFitToPrintableArea;
1400 print_pages_params_.reset(new PrintMsg_PrintPages_Params(settings));
1404 bool PrintWebViewHelper::CalculateNumberOfPages(blink::WebFrame* frame,
1405 const blink::WebNode& node,
1406 int* number_of_pages) {
1408 bool fit_to_paper_size = !(PrintingNodeOrPdfFrame(frame, node));
1409 if (!InitPrintSettings(fit_to_paper_size)) {
1410 notify_browser_of_print_failure_ = false;
1411 render_view()->RunModalAlertDialog(
1413 l10n_util::GetStringUTF16(IDS_PRINT_INVALID_PRINTER_SETTINGS));
1417 const PrintMsg_Print_Params& params = print_pages_params_->params;
1418 PrepareFrameAndViewForPrint prepare(params, frame, node, ignore_css_margins_);
1419 prepare.StartPrinting();
1421 Send(new PrintHostMsg_DidGetDocumentCookie(routing_id(),
1422 params.document_cookie));
1423 *number_of_pages = prepare.GetExpectedPageCount();
1427 bool PrintWebViewHelper::UpdatePrintSettings(
1428 blink::WebFrame* frame,
1429 const blink::WebNode& node,
1430 const base::DictionaryValue& passed_job_settings) {
1431 DCHECK(is_preview_enabled_);
1432 const base::DictionaryValue* job_settings = &passed_job_settings;
1433 base::DictionaryValue modified_job_settings;
1434 if (job_settings->empty()) {
1435 if (!print_for_preview_)
1436 print_preview_context_.set_error(PREVIEW_ERROR_BAD_SETTING);
1440 bool source_is_html = true;
1441 if (print_for_preview_) {
1442 if (!job_settings->GetBoolean(kSettingPreviewModifiable, &source_is_html)) {
1446 source_is_html = !PrintingNodeOrPdfFrame(frame, node);
1449 if (print_for_preview_ || !source_is_html) {
1450 modified_job_settings.MergeDictionary(job_settings);
1451 modified_job_settings.SetBoolean(kSettingHeaderFooterEnabled, false);
1452 modified_job_settings.SetInteger(kSettingMarginsType, NO_MARGINS);
1453 job_settings = &modified_job_settings;
1456 // Send the cookie so that UpdatePrintSettings can reuse PrinterQuery when
1458 int cookie = print_pages_params_.get() ?
1459 print_pages_params_->params.document_cookie : 0;
1460 PrintMsg_PrintPages_Params settings;
1461 Send(new PrintHostMsg_UpdatePrintSettings(routing_id(), cookie, *job_settings,
1463 print_pages_params_.reset(new PrintMsg_PrintPages_Params(settings));
1465 if (!PrintMsg_Print_Params_IsValid(settings.params)) {
1466 if (!print_for_preview_) {
1467 print_preview_context_.set_error(PREVIEW_ERROR_INVALID_PRINTER_SETTINGS);
1469 // PrintForPrintPreview
1470 blink::WebFrame* print_frame = NULL;
1471 // This may not be the right frame, but the alert will be modal,
1472 // therefore it works well enough.
1473 GetPrintFrame(&print_frame);
1475 render_view()->RunModalAlertDialog(
1477 l10n_util::GetStringUTF16(
1478 IDS_PRINT_INVALID_PRINTER_SETTINGS));
1484 if (settings.params.dpi < kMinDpi || !settings.params.document_cookie) {
1485 print_preview_context_.set_error(PREVIEW_ERROR_UPDATING_PRINT_SETTINGS);
1489 if (!job_settings->GetInteger(kPreviewUIID, &settings.params.preview_ui_id)) {
1491 print_preview_context_.set_error(PREVIEW_ERROR_BAD_SETTING);
1495 if (!print_for_preview_) {
1496 // Validate expected print preview settings.
1497 if (!job_settings->GetInteger(kPreviewRequestID,
1498 &settings.params.preview_request_id) ||
1499 !job_settings->GetBoolean(kIsFirstRequest,
1500 &settings.params.is_first_request)) {
1502 print_preview_context_.set_error(PREVIEW_ERROR_BAD_SETTING);
1506 settings.params.print_to_pdf = IsPrintToPdfRequested(*job_settings);
1507 UpdateFrameMarginsCssInfo(*job_settings);
1508 settings.params.print_scaling_option = GetPrintScalingOption(
1509 frame, node, source_is_html, *job_settings, settings.params);
1511 // Header/Footer: Set |header_footer_info_|.
1512 if (settings.params.display_header_footer) {
1513 header_footer_info_.reset(new base::DictionaryValue());
1514 header_footer_info_->SetDouble(kSettingHeaderFooterDate,
1515 base::Time::Now().ToJsTime());
1516 header_footer_info_->SetString(kSettingHeaderFooterURL,
1517 settings.params.url);
1518 header_footer_info_->SetString(kSettingHeaderFooterTitle,
1519 settings.params.title);
1523 print_pages_params_.reset(new PrintMsg_PrintPages_Params(settings));
1524 Send(new PrintHostMsg_DidGetDocumentCookie(routing_id(),
1525 settings.params.document_cookie));
1530 bool PrintWebViewHelper::GetPrintSettingsFromUser(blink::WebFrame* frame,
1531 const blink::WebNode& node,
1532 int expected_pages_count) {
1533 PrintHostMsg_ScriptedPrint_Params params;
1534 PrintMsg_PrintPages_Params print_settings;
1536 params.cookie = print_pages_params_->params.document_cookie;
1537 params.has_selection = frame->hasSelection();
1538 params.expected_pages_count = expected_pages_count;
1539 MarginType margin_type = DEFAULT_MARGINS;
1540 if (PrintingNodeOrPdfFrame(frame, node))
1541 margin_type = GetMarginsForPdf(frame, node);
1542 params.margin_type = margin_type;
1544 Send(new PrintHostMsg_DidShowPrintDialog(routing_id()));
1546 // PrintHostMsg_ScriptedPrint will reset print_scaling_option, so we save the
1547 // value before and restore it afterwards.
1548 blink::WebPrintScalingOption scaling_option =
1549 print_pages_params_->params.print_scaling_option;
1551 print_pages_params_.reset();
1552 IPC::SyncMessage* msg =
1553 new PrintHostMsg_ScriptedPrint(routing_id(), params, &print_settings);
1554 msg->EnableMessagePumping();
1556 print_pages_params_.reset(new PrintMsg_PrintPages_Params(print_settings));
1558 print_pages_params_->params.print_scaling_option = scaling_option;
1559 return (print_settings.params.dpi && print_settings.params.document_cookie);
1562 bool PrintWebViewHelper::RenderPagesForPrint(blink::WebFrame* frame,
1563 const blink::WebNode& node) {
1564 if (!frame || prep_frame_view_)
1566 const PrintMsg_PrintPages_Params& params = *print_pages_params_;
1567 const PrintMsg_Print_Params& print_params = params.params;
1568 prep_frame_view_.reset(
1569 new PrepareFrameAndViewForPrint(print_params, frame, node,
1570 ignore_css_margins_));
1571 DCHECK(!print_pages_params_->params.selection_only ||
1572 print_pages_params_->pages.empty());
1573 prep_frame_view_->CopySelectionIfNeeded(
1574 render_view()->GetWebkitPreferences(),
1575 base::Bind(&PrintWebViewHelper::OnFramePreparedForPrintPages,
1576 base::Unretained(this)));
1580 #if defined(OS_POSIX)
1581 bool PrintWebViewHelper::CopyMetafileDataToSharedMem(
1583 base::SharedMemoryHandle* shared_mem_handle) {
1584 uint32 buf_size = metafile->GetDataSize();
1585 scoped_ptr<base::SharedMemory> shared_buf(
1586 content::RenderThread::Get()->HostAllocateSharedMemoryBuffer(
1587 buf_size).release());
1589 if (shared_buf.get()) {
1590 if (shared_buf->Map(buf_size)) {
1591 metafile->GetData(shared_buf->memory(), buf_size);
1592 shared_buf->GiveToProcess(base::GetCurrentProcessHandle(),
1600 #endif // defined(OS_POSIX)
1602 bool PrintWebViewHelper::IsScriptInitiatedPrintTooFrequent(
1603 blink::WebFrame* frame) {
1604 const int kMinSecondsToIgnoreJavascriptInitiatedPrint = 2;
1605 const int kMaxSecondsToIgnoreJavascriptInitiatedPrint = 32;
1606 bool too_frequent = false;
1608 // Check if there is script repeatedly trying to print and ignore it if too
1609 // frequent. The first 3 times, we use a constant wait time, but if this
1610 // gets excessive, we switch to exponential wait time. So for a page that
1611 // calls print() in a loop the user will need to cancel the print dialog
1612 // after: [2, 2, 2, 4, 8, 16, 32, 32, ...] seconds.
1613 // This gives the user time to navigate from the page.
1614 if (user_cancelled_scripted_print_count_ > 0) {
1615 base::TimeDelta diff = base::Time::Now() - last_cancelled_script_print_;
1616 int min_wait_seconds = kMinSecondsToIgnoreJavascriptInitiatedPrint;
1617 if (user_cancelled_scripted_print_count_ > 3) {
1618 min_wait_seconds = std::min(
1619 kMinSecondsToIgnoreJavascriptInitiatedPrint <<
1620 (user_cancelled_scripted_print_count_ - 3),
1621 kMaxSecondsToIgnoreJavascriptInitiatedPrint);
1623 if (diff.InSeconds() < min_wait_seconds) {
1624 too_frequent = true;
1631 blink::WebString message(
1632 blink::WebString::fromUTF8("Ignoring too frequent calls to print()."));
1633 frame->addMessageToConsole(
1634 blink::WebConsoleMessage(
1635 blink::WebConsoleMessage::LevelWarning, message));
1639 void PrintWebViewHelper::ResetScriptedPrintCount() {
1640 // Reset cancel counter on successful print.
1641 user_cancelled_scripted_print_count_ = 0;
1644 void PrintWebViewHelper::IncrementScriptedPrintCount() {
1645 ++user_cancelled_scripted_print_count_;
1646 last_cancelled_script_print_ = base::Time::Now();
1650 void PrintWebViewHelper::ShowScriptedPrintPreview() {
1651 if (is_scripted_preview_delayed_) {
1652 is_scripted_preview_delayed_ = false;
1653 Send(new PrintHostMsg_ShowScriptedPrintPreview(routing_id(),
1654 print_preview_context_.IsModifiable()));
1658 void PrintWebViewHelper::RequestPrintPreview(PrintPreviewRequestType type) {
1659 const bool is_modifiable = print_preview_context_.IsModifiable();
1660 const bool has_selection = print_preview_context_.HasSelection();
1661 PrintHostMsg_RequestPrintPreview_Params params;
1662 params.is_modifiable = is_modifiable;
1663 params.has_selection = has_selection;
1665 case PRINT_PREVIEW_SCRIPTED: {
1666 // Shows scripted print preview in two stages.
1667 // 1. PrintHostMsg_SetupScriptedPrintPreview blocks this call and JS by
1668 // pumping messages here.
1669 // 2. PrintHostMsg_ShowScriptedPrintPreview shows preview once the
1670 // document has been loaded.
1671 is_scripted_preview_delayed_ = true;
1672 if (is_loading_ && GetPlugin(print_preview_context_.source_frame())) {
1673 // Wait for DidStopLoading. Plugins may not know the correct
1674 // |is_modifiable| value until they are fully loaded, which occurs when
1675 // DidStopLoading() is called. Defer showing the preview until then.
1677 base::MessageLoop::current()->PostTask(
1679 base::Bind(&PrintWebViewHelper::ShowScriptedPrintPreview,
1680 weak_ptr_factory_.GetWeakPtr()));
1682 IPC::SyncMessage* msg =
1683 new PrintHostMsg_SetupScriptedPrintPreview(routing_id());
1684 msg->EnableMessagePumping();
1686 is_scripted_preview_delayed_ = false;
1689 case PRINT_PREVIEW_USER_INITIATED_ENTIRE_FRAME: {
1692 case PRINT_PREVIEW_USER_INITIATED_SELECTION: {
1693 DCHECK(has_selection);
1694 params.selection_only = has_selection;
1697 case PRINT_PREVIEW_USER_INITIATED_CONTEXT_NODE: {
1698 params.webnode_only = true;
1706 Send(new PrintHostMsg_RequestPrintPreview(routing_id(), params));
1709 bool PrintWebViewHelper::CheckForCancel() {
1710 const PrintMsg_Print_Params& print_params = print_pages_params_->params;
1711 bool cancel = false;
1712 Send(new PrintHostMsg_CheckForCancel(routing_id(),
1713 print_params.preview_ui_id,
1714 print_params.preview_request_id,
1717 notify_browser_of_print_failure_ = false;
1721 bool PrintWebViewHelper::PreviewPageRendered(int page_number,
1722 Metafile* metafile) {
1723 DCHECK_GE(page_number, FIRST_PAGE_INDEX);
1725 // For non-modifiable files, |metafile| should be NULL, so do not bother
1726 // sending a message. If we don't generate draft metafiles, |metafile| is
1728 if (!print_preview_context_.IsModifiable() ||
1729 !print_preview_context_.generate_draft_pages()) {
1736 print_preview_context_.set_error(
1737 PREVIEW_ERROR_PAGE_RENDERED_WITHOUT_METAFILE);
1741 PrintHostMsg_DidPreviewPage_Params preview_page_params;
1742 // Get the size of the resulting metafile.
1743 uint32 buf_size = metafile->GetDataSize();
1744 DCHECK_GT(buf_size, 0u);
1745 if (!CopyMetafileDataToSharedMem(
1746 metafile, &(preview_page_params.metafile_data_handle))) {
1747 LOG(ERROR) << "CopyMetafileDataToSharedMem failed";
1748 print_preview_context_.set_error(PREVIEW_ERROR_METAFILE_COPY_FAILED);
1751 preview_page_params.data_size = buf_size;
1752 preview_page_params.page_number = page_number;
1753 preview_page_params.preview_request_id =
1754 print_pages_params_->params.preview_request_id;
1756 Send(new PrintHostMsg_DidPreviewPage(routing_id(), preview_page_params));
1760 PrintWebViewHelper::PrintPreviewContext::PrintPreviewContext()
1761 : total_page_count_(0),
1762 current_page_index_(0),
1763 generate_draft_pages_(true),
1764 print_ready_metafile_page_count_(0),
1765 error_(PREVIEW_ERROR_NONE),
1766 state_(UNINITIALIZED) {
1769 PrintWebViewHelper::PrintPreviewContext::~PrintPreviewContext() {
1772 void PrintWebViewHelper::PrintPreviewContext::InitWithFrame(
1773 blink::WebFrame* web_frame) {
1775 DCHECK(!IsRendering());
1776 state_ = INITIALIZED;
1777 source_frame_.Reset(web_frame);
1778 source_node_.reset();
1781 void PrintWebViewHelper::PrintPreviewContext::InitWithNode(
1782 const blink::WebNode& web_node) {
1783 DCHECK(!web_node.isNull());
1784 DCHECK(web_node.document().frame());
1785 DCHECK(!IsRendering());
1786 state_ = INITIALIZED;
1787 source_frame_.Reset(web_node.document().frame());
1788 source_node_ = web_node;
1791 void PrintWebViewHelper::PrintPreviewContext::OnPrintPreview() {
1792 DCHECK_EQ(INITIALIZED, state_);
1796 bool PrintWebViewHelper::PrintPreviewContext::CreatePreviewDocument(
1797 PrepareFrameAndViewForPrint* prepared_frame,
1798 const std::vector<int>& pages) {
1799 DCHECK_EQ(INITIALIZED, state_);
1802 // Need to make sure old object gets destroyed first.
1803 prep_frame_view_.reset(prepared_frame);
1804 prep_frame_view_->StartPrinting();
1806 total_page_count_ = prep_frame_view_->GetExpectedPageCount();
1807 if (total_page_count_ == 0) {
1808 LOG(ERROR) << "CreatePreviewDocument got 0 page count";
1809 set_error(PREVIEW_ERROR_ZERO_PAGES);
1813 metafile_.reset(new PreviewMetafile);
1814 if (!metafile_->Init()) {
1815 set_error(PREVIEW_ERROR_METAFILE_INIT_FAILED);
1816 LOG(ERROR) << "PreviewMetafile Init failed";
1820 current_page_index_ = 0;
1821 pages_to_render_ = pages;
1822 // Sort and make unique.
1823 std::sort(pages_to_render_.begin(), pages_to_render_.end());
1824 pages_to_render_.resize(std::unique(pages_to_render_.begin(),
1825 pages_to_render_.end()) -
1826 pages_to_render_.begin());
1827 // Remove invalid pages.
1828 pages_to_render_.resize(std::lower_bound(pages_to_render_.begin(),
1829 pages_to_render_.end(),
1830 total_page_count_) -
1831 pages_to_render_.begin());
1832 print_ready_metafile_page_count_ = pages_to_render_.size();
1833 if (pages_to_render_.empty()) {
1834 print_ready_metafile_page_count_ = total_page_count_;
1835 // Render all pages.
1836 for (int i = 0; i < total_page_count_; ++i)
1837 pages_to_render_.push_back(i);
1838 } else if (generate_draft_pages_) {
1839 int pages_index = 0;
1840 for (int i = 0; i < total_page_count_; ++i) {
1841 if (pages_index < print_ready_metafile_page_count_ &&
1842 i == pages_to_render_[pages_index]) {
1846 pages_to_render_.push_back(i);
1850 document_render_time_ = base::TimeDelta();
1851 begin_time_ = base::TimeTicks::Now();
1856 void PrintWebViewHelper::PrintPreviewContext::RenderedPreviewPage(
1857 const base::TimeDelta& page_time) {
1858 DCHECK_EQ(RENDERING, state_);
1859 document_render_time_ += page_time;
1860 UMA_HISTOGRAM_TIMES("PrintPreview.RenderPDFPageTime", page_time);
1863 void PrintWebViewHelper::PrintPreviewContext::AllPagesRendered() {
1864 DCHECK_EQ(RENDERING, state_);
1866 prep_frame_view_->FinishPrinting();
1869 void PrintWebViewHelper::PrintPreviewContext::FinalizePrintReadyDocument() {
1870 DCHECK(IsRendering());
1872 base::TimeTicks begin_time = base::TimeTicks::Now();
1873 metafile_->FinishDocument();
1875 if (print_ready_metafile_page_count_ <= 0) {
1880 UMA_HISTOGRAM_MEDIUM_TIMES("PrintPreview.RenderToPDFTime",
1881 document_render_time_);
1882 base::TimeDelta total_time = (base::TimeTicks::Now() - begin_time) +
1883 document_render_time_;
1884 UMA_HISTOGRAM_MEDIUM_TIMES("PrintPreview.RenderAndGeneratePDFTime",
1886 UMA_HISTOGRAM_MEDIUM_TIMES("PrintPreview.RenderAndGeneratePDFTimeAvgPerPage",
1887 total_time / pages_to_render_.size());
1890 void PrintWebViewHelper::PrintPreviewContext::Finished() {
1891 DCHECK_EQ(DONE, state_);
1892 state_ = INITIALIZED;
1896 void PrintWebViewHelper::PrintPreviewContext::Failed(bool report_error) {
1897 DCHECK(state_ == INITIALIZED || state_ == RENDERING);
1898 state_ = INITIALIZED;
1900 DCHECK_NE(PREVIEW_ERROR_NONE, error_);
1901 UMA_HISTOGRAM_ENUMERATION("PrintPreview.RendererError", error_,
1902 PREVIEW_ERROR_LAST_ENUM);
1907 int PrintWebViewHelper::PrintPreviewContext::GetNextPageNumber() {
1908 DCHECK_EQ(RENDERING, state_);
1909 if (IsFinalPageRendered())
1911 return pages_to_render_[current_page_index_++];
1914 bool PrintWebViewHelper::PrintPreviewContext::IsRendering() const {
1915 return state_ == RENDERING || state_ == DONE;
1918 bool PrintWebViewHelper::PrintPreviewContext::IsModifiable() {
1919 // The only kind of node we can print right now is a PDF node.
1920 return !PrintingNodeOrPdfFrame(source_frame(), source_node_);
1923 bool PrintWebViewHelper::PrintPreviewContext::HasSelection() {
1924 return IsModifiable() && source_frame()->hasSelection();
1927 bool PrintWebViewHelper::PrintPreviewContext::IsLastPageOfPrintReadyMetafile()
1929 DCHECK(IsRendering());
1930 return current_page_index_ == print_ready_metafile_page_count_;
1933 bool PrintWebViewHelper::PrintPreviewContext::IsFinalPageRendered() const {
1934 DCHECK(IsRendering());
1935 return static_cast<size_t>(current_page_index_) == pages_to_render_.size();
1938 void PrintWebViewHelper::PrintPreviewContext::set_generate_draft_pages(
1939 bool generate_draft_pages) {
1940 DCHECK_EQ(INITIALIZED, state_);
1941 generate_draft_pages_ = generate_draft_pages;
1944 void PrintWebViewHelper::PrintPreviewContext::set_error(
1945 enum PrintPreviewErrorBuckets error) {
1949 blink::WebFrame* PrintWebViewHelper::PrintPreviewContext::source_frame() {
1950 DCHECK(state_ != UNINITIALIZED);
1951 return source_frame_.GetFrame();
1954 const blink::WebNode&
1955 PrintWebViewHelper::PrintPreviewContext::source_node() const {
1956 DCHECK(state_ != UNINITIALIZED);
1957 return source_node_;
1960 blink::WebFrame* PrintWebViewHelper::PrintPreviewContext::prepared_frame() {
1961 DCHECK(state_ != UNINITIALIZED);
1962 return prep_frame_view_->frame();
1965 const blink::WebNode&
1966 PrintWebViewHelper::PrintPreviewContext::prepared_node() const {
1967 DCHECK(state_ != UNINITIALIZED);
1968 return prep_frame_view_->node();
1971 int PrintWebViewHelper::PrintPreviewContext::total_page_count() const {
1972 DCHECK(state_ != UNINITIALIZED);
1973 return total_page_count_;
1976 bool PrintWebViewHelper::PrintPreviewContext::generate_draft_pages() const {
1977 return generate_draft_pages_;
1980 PreviewMetafile* PrintWebViewHelper::PrintPreviewContext::metafile() {
1981 DCHECK(IsRendering());
1982 return metafile_.get();
1985 int PrintWebViewHelper::PrintPreviewContext::last_error() const {
1989 gfx::Size PrintWebViewHelper::PrintPreviewContext::GetPrintCanvasSize() const {
1990 DCHECK(IsRendering());
1991 return prep_frame_view_->GetPrintCanvasSize();
1994 void PrintWebViewHelper::PrintPreviewContext::ClearContext() {
1995 prep_frame_view_.reset();
1997 pages_to_render_.clear();
1998 error_ = PREVIEW_ERROR_NONE;
2001 } // namespace printing