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