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