Add experimental v8 code cache options.
[chromium-blink-merge.git] / android_webview / renderer / print_web_view_helper.cc
blobd334764a653a5c84327c1246919d5b3c37c8bdec
1 // Copyright 2013 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 // TODO(sgurun) copied from chrome/renderer. Remove after crbug.com/322276
7 #include "android_webview/renderer/print_web_view_helper.h"
9 #include <string>
11 #include "android_webview/common/print_messages.h"
12 #include "base/auto_reset.h"
13 #include "base/command_line.h"
14 #include "base/json/json_writer.h"
15 #include "base/logging.h"
16 #include "base/message_loop/message_loop.h"
17 #include "base/metrics/histogram.h"
18 #include "base/process/process_handle.h"
19 #include "base/strings/string_number_conversions.h"
20 #include "base/strings/stringprintf.h"
21 #include "base/strings/utf_string_conversions.h"
22 #include "content/public/common/web_preferences.h"
23 #include "content/public/renderer/render_thread.h"
24 #include "content/public/renderer/render_view.h"
25 #include "net/base/escape.h"
26 #include "printing/pdf_metafile_skia.h"
27 #include "printing/units.h"
28 #include "third_party/WebKit/public/platform/WebSize.h"
29 #include "third_party/WebKit/public/platform/WebURLRequest.h"
30 #include "third_party/WebKit/public/web/WebConsoleMessage.h"
31 #include "third_party/WebKit/public/web/WebDocument.h"
32 #include "third_party/WebKit/public/web/WebElement.h"
33 #include "third_party/WebKit/public/web/WebFrameClient.h"
34 #include "third_party/WebKit/public/web/WebLocalFrame.h"
35 #include "third_party/WebKit/public/web/WebPlugin.h"
36 #include "third_party/WebKit/public/web/WebPluginDocument.h"
37 #include "third_party/WebKit/public/web/WebPrintParams.h"
38 #include "third_party/WebKit/public/web/WebPrintScalingOption.h"
39 #include "third_party/WebKit/public/web/WebScriptSource.h"
40 #include "third_party/WebKit/public/web/WebSettings.h"
41 #include "third_party/WebKit/public/web/WebView.h"
42 #include "third_party/WebKit/public/web/WebViewClient.h"
43 #include "ui/base/l10n/l10n_util.h"
44 #include "ui/base/resource/resource_bundle.h"
46 // This code is copied from chrome/renderer/printing. Code is slightly
47 // modified to run it with webview, and the modifications are marked
48 // using OS_ANDROID.
49 // TODO(sgurun): remove the code as part of componentization of printing.
51 using content::WebPreferences;
53 namespace printing {
55 namespace {
57 enum PrintPreviewHelperEvents {
58 PREVIEW_EVENT_REQUESTED,
59 PREVIEW_EVENT_CACHE_HIT, // Unused
60 PREVIEW_EVENT_CREATE_DOCUMENT,
61 PREVIEW_EVENT_NEW_SETTINGS, // Unused
62 PREVIEW_EVENT_MAX,
65 const double kMinDpi = 1.0;
67 #if 0
68 // TODO(sgurun) android_webview hack
69 const char kPageLoadScriptFormat[] =
70 "document.open(); document.write(%s); document.close();";
72 const char kPageSetupScriptFormat[] = "setup(%s);";
74 void ExecuteScript(blink::WebFrame* frame,
75 const char* script_format,
76 const base::Value& parameters) {
77 std::string json;
78 base::JSONWriter::Write(&parameters, &json);
79 std::string script = base::StringPrintf(script_format, json.c_str());
80 frame->executeScript(blink::WebString(base::UTF8ToUTF16(script)));
82 #endif
84 int GetDPI(const PrintMsg_Print_Params* print_params) {
85 #if defined(OS_MACOSX)
86 // On the Mac, the printable area is in points, don't do any scaling based
87 // on dpi.
88 return kPointsPerInch;
89 #else
90 return static_cast<int>(print_params->dpi);
91 #endif // defined(OS_MACOSX)
94 bool PrintMsg_Print_Params_IsValid(const PrintMsg_Print_Params& params) {
95 return !params.content_size.IsEmpty() && !params.page_size.IsEmpty() &&
96 !params.printable_area.IsEmpty() && params.document_cookie &&
97 params.desired_dpi && params.max_shrink && params.min_shrink &&
98 params.dpi && (params.margin_top >= 0) && (params.margin_left >= 0);
101 PrintMsg_Print_Params GetCssPrintParams(
102 blink::WebFrame* frame,
103 int page_index,
104 const PrintMsg_Print_Params& page_params) {
105 PrintMsg_Print_Params page_css_params = page_params;
106 int dpi = GetDPI(&page_params);
108 blink::WebSize page_size_in_pixels(
109 ConvertUnit(page_params.page_size.width(), dpi, kPixelsPerInch),
110 ConvertUnit(page_params.page_size.height(), dpi, kPixelsPerInch));
111 int margin_top_in_pixels =
112 ConvertUnit(page_params.margin_top, dpi, kPixelsPerInch);
113 int margin_right_in_pixels = ConvertUnit(
114 page_params.page_size.width() -
115 page_params.content_size.width() - page_params.margin_left,
116 dpi, kPixelsPerInch);
117 int margin_bottom_in_pixels = ConvertUnit(
118 page_params.page_size.height() -
119 page_params.content_size.height() - page_params.margin_top,
120 dpi, kPixelsPerInch);
121 int margin_left_in_pixels = ConvertUnit(
122 page_params.margin_left,
123 dpi, kPixelsPerInch);
125 blink::WebSize original_page_size_in_pixels = page_size_in_pixels;
127 if (frame) {
128 frame->pageSizeAndMarginsInPixels(page_index,
129 page_size_in_pixels,
130 margin_top_in_pixels,
131 margin_right_in_pixels,
132 margin_bottom_in_pixels,
133 margin_left_in_pixels);
136 int new_content_width = page_size_in_pixels.width -
137 margin_left_in_pixels - margin_right_in_pixels;
138 int new_content_height = page_size_in_pixels.height -
139 margin_top_in_pixels - margin_bottom_in_pixels;
141 // Invalid page size and/or margins. We just use the default setting.
142 if (new_content_width < 1 || new_content_height < 1) {
143 CHECK(frame);
144 page_css_params = GetCssPrintParams(NULL, page_index, page_params);
145 return page_css_params;
148 page_css_params.content_size = gfx::Size(
149 ConvertUnit(new_content_width, kPixelsPerInch, dpi),
150 ConvertUnit(new_content_height, kPixelsPerInch, dpi));
152 if (original_page_size_in_pixels != page_size_in_pixels) {
153 page_css_params.page_size = gfx::Size(
154 ConvertUnit(page_size_in_pixels.width, kPixelsPerInch, dpi),
155 ConvertUnit(page_size_in_pixels.height, kPixelsPerInch, dpi));
156 } else {
157 // Printing frame doesn't have any page size css. Pixels to dpi conversion
158 // causes rounding off errors. Therefore use the default page size values
159 // directly.
160 page_css_params.page_size = page_params.page_size;
163 page_css_params.margin_top =
164 ConvertUnit(margin_top_in_pixels, kPixelsPerInch, dpi);
165 page_css_params.margin_left =
166 ConvertUnit(margin_left_in_pixels, kPixelsPerInch, dpi);
167 return page_css_params;
170 double FitPrintParamsToPage(const PrintMsg_Print_Params& page_params,
171 PrintMsg_Print_Params* params_to_fit) {
172 double content_width =
173 static_cast<double>(params_to_fit->content_size.width());
174 double content_height =
175 static_cast<double>(params_to_fit->content_size.height());
176 int default_page_size_height = page_params.page_size.height();
177 int default_page_size_width = page_params.page_size.width();
178 int css_page_size_height = params_to_fit->page_size.height();
179 int css_page_size_width = params_to_fit->page_size.width();
181 double scale_factor = 1.0f;
182 if (page_params.page_size == params_to_fit->page_size)
183 return scale_factor;
185 if (default_page_size_width < css_page_size_width ||
186 default_page_size_height < css_page_size_height) {
187 double ratio_width =
188 static_cast<double>(default_page_size_width) / css_page_size_width;
189 double ratio_height =
190 static_cast<double>(default_page_size_height) / css_page_size_height;
191 scale_factor = ratio_width < ratio_height ? ratio_width : ratio_height;
192 content_width *= scale_factor;
193 content_height *= scale_factor;
195 params_to_fit->margin_top = static_cast<int>(
196 (default_page_size_height - css_page_size_height * scale_factor) / 2 +
197 (params_to_fit->margin_top * scale_factor));
198 params_to_fit->margin_left = static_cast<int>(
199 (default_page_size_width - css_page_size_width * scale_factor) / 2 +
200 (params_to_fit->margin_left * scale_factor));
201 params_to_fit->content_size = gfx::Size(
202 static_cast<int>(content_width), static_cast<int>(content_height));
203 params_to_fit->page_size = page_params.page_size;
204 return scale_factor;
207 void CalculatePageLayoutFromPrintParams(
208 const PrintMsg_Print_Params& params,
209 PageSizeMargins* page_layout_in_points) {
210 int dpi = GetDPI(&params);
211 int content_width = params.content_size.width();
212 int content_height = params.content_size.height();
214 int margin_bottom = params.page_size.height() -
215 content_height - params.margin_top;
216 int margin_right = params.page_size.width() -
217 content_width - params.margin_left;
219 page_layout_in_points->content_width =
220 ConvertUnit(content_width, dpi, kPointsPerInch);
221 page_layout_in_points->content_height =
222 ConvertUnit(content_height, dpi, kPointsPerInch);
223 page_layout_in_points->margin_top =
224 ConvertUnit(params.margin_top, dpi, kPointsPerInch);
225 page_layout_in_points->margin_right =
226 ConvertUnit(margin_right, dpi, kPointsPerInch);
227 page_layout_in_points->margin_bottom =
228 ConvertUnit(margin_bottom, dpi, kPointsPerInch);
229 page_layout_in_points->margin_left =
230 ConvertUnit(params.margin_left, dpi, kPointsPerInch);
233 void EnsureOrientationMatches(const PrintMsg_Print_Params& css_params,
234 PrintMsg_Print_Params* page_params) {
235 if ((page_params->page_size.width() > page_params->page_size.height()) ==
236 (css_params.page_size.width() > css_params.page_size.height())) {
237 return;
240 // Swap the |width| and |height| values.
241 page_params->page_size.SetSize(page_params->page_size.height(),
242 page_params->page_size.width());
243 page_params->content_size.SetSize(page_params->content_size.height(),
244 page_params->content_size.width());
245 page_params->printable_area.set_size(
246 gfx::Size(page_params->printable_area.height(),
247 page_params->printable_area.width()));
250 void ComputeWebKitPrintParamsInDesiredDpi(
251 const PrintMsg_Print_Params& print_params,
252 blink::WebPrintParams* webkit_print_params) {
253 int dpi = GetDPI(&print_params);
254 webkit_print_params->printerDPI = dpi;
255 webkit_print_params->printScalingOption = print_params.print_scaling_option;
257 webkit_print_params->printContentArea.width =
258 ConvertUnit(print_params.content_size.width(), dpi,
259 print_params.desired_dpi);
260 webkit_print_params->printContentArea.height =
261 ConvertUnit(print_params.content_size.height(), dpi,
262 print_params.desired_dpi);
264 webkit_print_params->printableArea.x =
265 ConvertUnit(print_params.printable_area.x(), dpi,
266 print_params.desired_dpi);
267 webkit_print_params->printableArea.y =
268 ConvertUnit(print_params.printable_area.y(), dpi,
269 print_params.desired_dpi);
270 webkit_print_params->printableArea.width =
271 ConvertUnit(print_params.printable_area.width(), dpi,
272 print_params.desired_dpi);
273 webkit_print_params->printableArea.height =
274 ConvertUnit(print_params.printable_area.height(),
275 dpi, print_params.desired_dpi);
277 webkit_print_params->paperSize.width =
278 ConvertUnit(print_params.page_size.width(), dpi,
279 print_params.desired_dpi);
280 webkit_print_params->paperSize.height =
281 ConvertUnit(print_params.page_size.height(), dpi,
282 print_params.desired_dpi);
285 blink::WebPlugin* GetPlugin(const blink::WebFrame* frame) {
286 return frame->document().isPluginDocument() ?
287 frame->document().to<blink::WebPluginDocument>().plugin() : NULL;
290 bool PrintingNodeOrPdfFrame(const blink::WebFrame* frame,
291 const blink::WebNode& node) {
292 if (!node.isNull())
293 return true;
294 blink::WebPlugin* plugin = GetPlugin(frame);
295 return plugin && plugin->supportsPaginatedPrint();
298 bool PrintingFrameHasPageSizeStyle(blink::WebFrame* frame,
299 int total_page_count) {
300 if (!frame)
301 return false;
302 bool frame_has_custom_page_size_style = false;
303 for (int i = 0; i < total_page_count; ++i) {
304 if (frame->hasCustomPageSizeStyle(i)) {
305 frame_has_custom_page_size_style = true;
306 break;
309 return frame_has_custom_page_size_style;
312 MarginType GetMarginsForPdf(blink::WebFrame* frame,
313 const blink::WebNode& node) {
314 if (frame->isPrintScalingDisabledForPlugin(node))
315 return NO_MARGINS;
316 else
317 return PRINTABLE_AREA_MARGINS;
320 bool FitToPageEnabled(const base::DictionaryValue& job_settings) {
321 bool fit_to_paper_size = false;
322 if (!job_settings.GetBoolean(kSettingFitToPageEnabled, &fit_to_paper_size)) {
323 NOTREACHED();
325 return fit_to_paper_size;
328 PrintMsg_Print_Params CalculatePrintParamsForCss(
329 blink::WebFrame* frame,
330 int page_index,
331 const PrintMsg_Print_Params& page_params,
332 bool ignore_css_margins,
333 bool fit_to_page,
334 double* scale_factor) {
335 PrintMsg_Print_Params css_params = GetCssPrintParams(frame, page_index,
336 page_params);
338 PrintMsg_Print_Params params = page_params;
339 EnsureOrientationMatches(css_params, &params);
341 if (ignore_css_margins && fit_to_page)
342 return params;
344 PrintMsg_Print_Params result_params = css_params;
345 if (ignore_css_margins) {
346 result_params.margin_top = params.margin_top;
347 result_params.margin_left = params.margin_left;
349 DCHECK(!fit_to_page);
350 // Since we are ignoring the margins, the css page size is no longer
351 // valid.
352 int default_margin_right = params.page_size.width() -
353 params.content_size.width() - params.margin_left;
354 int default_margin_bottom = params.page_size.height() -
355 params.content_size.height() - params.margin_top;
356 result_params.content_size = gfx::Size(
357 result_params.page_size.width() - result_params.margin_left -
358 default_margin_right,
359 result_params.page_size.height() - result_params.margin_top -
360 default_margin_bottom);
363 if (fit_to_page) {
364 double factor = FitPrintParamsToPage(params, &result_params);
365 if (scale_factor)
366 *scale_factor = factor;
368 return result_params;
371 bool IsPrintPreviewEnabled() {
372 return false;
375 bool IsPrintThrottlingDisabled() {
376 return true;
379 } // namespace
381 FrameReference::FrameReference(blink::WebLocalFrame* frame) {
382 Reset(frame);
385 FrameReference::FrameReference() {
386 Reset(NULL);
389 FrameReference::~FrameReference() {
392 void FrameReference::Reset(blink::WebLocalFrame* frame) {
393 if (frame) {
394 view_ = frame->view();
395 frame_ = frame;
396 } else {
397 view_ = NULL;
398 frame_ = NULL;
402 blink::WebLocalFrame* FrameReference::GetFrame() {
403 if (view_ == NULL || frame_ == NULL)
404 return NULL;
405 for (blink::WebFrame* frame = view_->mainFrame(); frame != NULL;
406 frame = frame->traverseNext(false)) {
407 if (frame == frame_)
408 return frame_;
410 return NULL;
413 blink::WebView* FrameReference::view() {
414 return view_;
417 // static - Not anonymous so that platform implementations can use it.
418 void PrintWebViewHelper::PrintHeaderAndFooter(
419 blink::WebCanvas* canvas,
420 int page_number,
421 int total_pages,
422 float webkit_scale_factor,
423 const PageSizeMargins& page_layout,
424 const base::DictionaryValue& header_footer_info,
425 const PrintMsg_Print_Params& params) {
426 #if 0
427 // TODO(sgurun) android_webview hack
428 SkAutoCanvasRestore auto_restore(canvas, true);
429 canvas->scale(1 / webkit_scale_factor, 1 / webkit_scale_factor);
431 blink::WebSize page_size(page_layout.margin_left + page_layout.margin_right +
432 page_layout.content_width,
433 page_layout.margin_top + page_layout.margin_bottom +
434 page_layout.content_height);
436 blink::WebView* web_view = blink::WebView::create(NULL);
437 web_view->settings()->setJavaScriptEnabled(true);
438 blink::WebFrame* frame = blink::WebLocalFrame::create(NULL)
439 web_view->setMainFrame(web_frame);
441 base::StringValue html(
442 ResourceBundle::GetSharedInstance().GetLocalizedString(
443 IDR_PRINT_PREVIEW_PAGE));
444 // Load page with script to avoid async operations.
445 ExecuteScript(frame, kPageLoadScriptFormat, html);
447 scoped_ptr<base::DictionaryValue> options(header_footer_info.DeepCopy());
448 options->SetDouble("width", page_size.width);
449 options->SetDouble("height", page_size.height);
450 options->SetDouble("topMargin", page_layout.margin_top);
451 options->SetDouble("bottomMargin", page_layout.margin_bottom);
452 options->SetString("pageNumber",
453 base::StringPrintf("%d/%d", page_number, total_pages));
455 ExecuteScript(frame, kPageSetupScriptFormat, *options);
457 blink::WebPrintParams webkit_params(page_size);
458 webkit_params.printerDPI = GetDPI(&params);
460 frame->printBegin(webkit_params, WebKit::WebNode(), NULL);
461 frame->printPage(0, canvas);
462 frame->printEnd();
464 web_view->close();
465 frame->close();
466 #endif
469 // static - Not anonymous so that platform implementations can use it.
470 float PrintWebViewHelper::RenderPageContent(blink::WebFrame* frame,
471 int page_number,
472 const gfx::Rect& canvas_area,
473 const gfx::Rect& content_area,
474 double scale_factor,
475 blink::WebCanvas* canvas) {
476 SkAutoCanvasRestore auto_restore(canvas, true);
477 if (content_area != canvas_area) {
478 canvas->translate((content_area.x() - canvas_area.x()) / scale_factor,
479 (content_area.y() - canvas_area.y()) / scale_factor);
480 SkRect clip_rect(
481 SkRect::MakeXYWH(content_area.origin().x() / scale_factor,
482 content_area.origin().y() / scale_factor,
483 content_area.size().width() / scale_factor,
484 content_area.size().height() / scale_factor));
485 SkIRect clip_int_rect;
486 clip_rect.roundOut(&clip_int_rect);
487 SkRegion clip_region(clip_int_rect);
488 canvas->setClipRegion(clip_region);
490 return frame->printPage(page_number, canvas);
493 // Class that calls the Begin and End print functions on the frame and changes
494 // the size of the view temporarily to support full page printing..
495 class PrepareFrameAndViewForPrint : public blink::WebViewClient,
496 public blink::WebFrameClient {
497 public:
498 PrepareFrameAndViewForPrint(const PrintMsg_Print_Params& params,
499 blink::WebLocalFrame* frame,
500 const blink::WebNode& node,
501 bool ignore_css_margins);
502 virtual ~PrepareFrameAndViewForPrint();
504 // Optional. Replaces |frame_| with selection if needed. Will call |on_ready|
505 // when completed.
506 void CopySelectionIfNeeded(const WebPreferences& preferences,
507 const base::Closure& on_ready);
509 // Prepares frame for printing.
510 void StartPrinting();
512 blink::WebLocalFrame* frame() {
513 return frame_.GetFrame();
516 const blink::WebNode& node() const {
517 return node_to_print_;
520 int GetExpectedPageCount() const {
521 return expected_pages_count_;
524 gfx::Size GetPrintCanvasSize() const;
526 void FinishPrinting();
528 bool IsLoadingSelection() {
529 // It's not selection if not |owns_web_view_|.
530 return owns_web_view_ && frame() && frame()->isLoading();
533 // TODO(ojan): Remove this override and have this class use a non-null
534 // layerTreeView.
535 // blink::WebViewClient override:
536 virtual bool allowsBrokenNullLayerTreeView() const;
538 protected:
539 // blink::WebViewClient override:
540 virtual void didStopLoading();
542 // blink::WebFrameClient override:
543 virtual blink::WebFrame* createChildFrame(blink::WebLocalFrame* parent,
544 const blink::WebString& name);
545 virtual void frameDetached(blink::WebFrame* frame);
547 private:
548 void CallOnReady();
549 void ResizeForPrinting();
550 void RestoreSize();
551 void CopySelection(const WebPreferences& preferences);
553 FrameReference frame_;
554 blink::WebNode node_to_print_;
555 bool owns_web_view_;
556 blink::WebPrintParams web_print_params_;
557 gfx::Size prev_view_size_;
558 gfx::Size prev_scroll_offset_;
559 int expected_pages_count_;
560 base::Closure on_ready_;
561 bool should_print_backgrounds_;
562 bool should_print_selection_only_;
563 bool is_printing_started_;
565 base::WeakPtrFactory<PrepareFrameAndViewForPrint> weak_ptr_factory_;
567 DISALLOW_COPY_AND_ASSIGN(PrepareFrameAndViewForPrint);
570 PrepareFrameAndViewForPrint::PrepareFrameAndViewForPrint(
571 const PrintMsg_Print_Params& params,
572 blink::WebLocalFrame* frame,
573 const blink::WebNode& node,
574 bool ignore_css_margins)
575 : frame_(frame),
576 node_to_print_(node),
577 owns_web_view_(false),
578 expected_pages_count_(0),
579 should_print_backgrounds_(params.should_print_backgrounds),
580 should_print_selection_only_(params.selection_only),
581 is_printing_started_(false),
582 weak_ptr_factory_(this) {
583 PrintMsg_Print_Params print_params = params;
584 if (!should_print_selection_only_ ||
585 !PrintingNodeOrPdfFrame(frame, node_to_print_)) {
586 bool fit_to_page = ignore_css_margins &&
587 print_params.print_scaling_option ==
588 blink::WebPrintScalingOptionFitToPrintableArea;
589 ComputeWebKitPrintParamsInDesiredDpi(params, &web_print_params_);
590 frame->printBegin(web_print_params_, node_to_print_);
591 print_params = CalculatePrintParamsForCss(frame, 0, print_params,
592 ignore_css_margins, fit_to_page,
593 NULL);
594 frame->printEnd();
596 ComputeWebKitPrintParamsInDesiredDpi(print_params, &web_print_params_);
599 PrepareFrameAndViewForPrint::~PrepareFrameAndViewForPrint() {
600 FinishPrinting();
603 void PrepareFrameAndViewForPrint::ResizeForPrinting() {
604 // Layout page according to printer page size. Since WebKit shrinks the
605 // size of the page automatically (from 125% to 200%) we trick it to
606 // think the page is 125% larger so the size of the page is correct for
607 // minimum (default) scaling.
608 // This is important for sites that try to fill the page.
609 gfx::Size print_layout_size(web_print_params_.printContentArea.width,
610 web_print_params_.printContentArea.height);
611 print_layout_size.set_height(
612 static_cast<int>(static_cast<double>(print_layout_size.height()) * 1.25));
614 if (!frame())
615 return;
616 blink::WebView* web_view = frame_.view();
617 // Backup size and offset.
618 if (blink::WebFrame* web_frame = web_view->mainFrame())
619 prev_scroll_offset_ = web_frame->scrollOffset();
620 prev_view_size_ = web_view->size();
622 web_view->resize(print_layout_size);
626 void PrepareFrameAndViewForPrint::StartPrinting() {
627 ResizeForPrinting();
628 blink::WebView* web_view = frame_.view();
629 web_view->settings()->setShouldPrintBackgrounds(should_print_backgrounds_);
630 expected_pages_count_ =
631 frame()->printBegin(web_print_params_, node_to_print_);
632 is_printing_started_ = true;
635 void PrepareFrameAndViewForPrint::CopySelectionIfNeeded(
636 const WebPreferences& preferences,
637 const base::Closure& on_ready) {
638 on_ready_ = on_ready;
639 if (should_print_selection_only_)
640 CopySelection(preferences);
641 else
642 didStopLoading();
645 void PrepareFrameAndViewForPrint::CopySelection(
646 const WebPreferences& preferences) {
647 ResizeForPrinting();
648 std::string url_str = "data:text/html;charset=utf-8,";
649 url_str.append(
650 net::EscapeQueryParamValue(frame()->selectionAsMarkup().utf8(), false));
651 RestoreSize();
652 // Create a new WebView with the same settings as the current display one.
653 // Except that we disable javascript (don't want any active content running
654 // on the page).
655 WebPreferences prefs = preferences;
656 prefs.javascript_enabled = false;
657 prefs.java_enabled = false;
659 blink::WebView* web_view = blink::WebView::create(this);
660 owns_web_view_ = true;
661 content::RenderView::ApplyWebPreferences(prefs, web_view);
662 web_view->setMainFrame(blink::WebLocalFrame::create(this));
663 frame_.Reset(web_view->mainFrame()->toWebLocalFrame());
664 node_to_print_.reset();
666 // When loading is done this will call didStopLoading() and that will do the
667 // actual printing.
668 frame()->loadRequest(blink::WebURLRequest(GURL(url_str)));
671 bool PrepareFrameAndViewForPrint::allowsBrokenNullLayerTreeView() const {
672 return true;
675 void PrepareFrameAndViewForPrint::didStopLoading() {
676 DCHECK(!on_ready_.is_null());
677 // Don't call callback here, because it can delete |this| and WebView that is
678 // called didStopLoading.
679 base::MessageLoop::current()->PostTask(
680 FROM_HERE,
681 base::Bind(&PrepareFrameAndViewForPrint::CallOnReady,
682 weak_ptr_factory_.GetWeakPtr()));
685 blink::WebFrame* PrepareFrameAndViewForPrint::createChildFrame(
686 blink::WebLocalFrame* parent,
687 const blink::WebString& name) {
688 blink::WebFrame* frame = blink::WebLocalFrame::create(this);
689 parent->appendChild(frame);
690 return frame;
693 void PrepareFrameAndViewForPrint::frameDetached(blink::WebFrame* frame) {
694 if (frame->parent())
695 frame->parent()->removeChild(frame);
696 frame->close();
699 void PrepareFrameAndViewForPrint::CallOnReady() {
700 return on_ready_.Run(); // Can delete |this|.
703 gfx::Size PrepareFrameAndViewForPrint::GetPrintCanvasSize() const {
704 DCHECK(is_printing_started_);
705 return gfx::Size(web_print_params_.printContentArea.width,
706 web_print_params_.printContentArea.height);
709 void PrepareFrameAndViewForPrint::RestoreSize() {
710 if (frame()) {
711 blink::WebView* web_view = frame_.GetFrame()->view();
712 web_view->resize(prev_view_size_);
713 if (blink::WebFrame* web_frame = web_view->mainFrame())
714 web_frame->setScrollOffset(prev_scroll_offset_);
718 void PrepareFrameAndViewForPrint::FinishPrinting() {
719 blink::WebLocalFrame* frame = frame_.GetFrame();
720 if (frame) {
721 blink::WebView* web_view = frame->view();
722 if (is_printing_started_) {
723 is_printing_started_ = false;
724 frame->printEnd();
725 if (!owns_web_view_) {
726 web_view->settings()->setShouldPrintBackgrounds(false);
727 RestoreSize();
730 if (owns_web_view_) {
731 DCHECK(!frame->isLoading());
732 owns_web_view_ = false;
733 web_view->close();
736 frame_.Reset(NULL);
737 on_ready_.Reset();
740 PrintWebViewHelper::PrintWebViewHelper(content::RenderView* render_view)
741 : content::RenderViewObserver(render_view),
742 content::RenderViewObserverTracker<PrintWebViewHelper>(render_view),
743 reset_prep_frame_view_(false),
744 is_preview_enabled_(IsPrintPreviewEnabled()),
745 is_scripted_print_throttling_disabled_(IsPrintThrottlingDisabled()),
746 is_print_ready_metafile_sent_(false),
747 ignore_css_margins_(false),
748 user_cancelled_scripted_print_count_(0),
749 is_scripted_printing_blocked_(false),
750 notify_browser_of_print_failure_(true),
751 print_for_preview_(false),
752 print_node_in_progress_(false),
753 is_loading_(false),
754 is_scripted_preview_delayed_(false),
755 weak_ptr_factory_(this) {
756 // TODO(sgurun) enable window.print() for webview crbug.com/322303
757 SetScriptedPrintBlocked(true);
760 PrintWebViewHelper::~PrintWebViewHelper() {}
762 bool PrintWebViewHelper::IsScriptInitiatedPrintAllowed(
763 blink::WebFrame* frame, bool user_initiated) {
764 #if defined(OS_ANDROID)
765 return false;
766 #endif // defined(OS_ANDROID)
767 if (is_scripted_printing_blocked_)
768 return false;
769 // If preview is enabled, then the print dialog is tab modal, and the user
770 // can always close the tab on a mis-behaving page (the system print dialog
771 // is app modal). If the print was initiated through user action, don't
772 // throttle. Or, if the command line flag to skip throttling has been set.
773 if (!is_scripted_print_throttling_disabled_ &&
774 !is_preview_enabled_ &&
775 !user_initiated)
776 return !IsScriptInitiatedPrintTooFrequent(frame);
777 return true;
780 void PrintWebViewHelper::DidStartLoading() {
781 is_loading_ = true;
784 void PrintWebViewHelper::DidStopLoading() {
785 is_loading_ = false;
786 ShowScriptedPrintPreview();
789 // Prints |frame| which called window.print().
790 void PrintWebViewHelper::PrintPage(blink::WebLocalFrame* frame,
791 bool user_initiated) {
792 DCHECK(frame);
794 #if !defined(OS_ANDROID)
795 // TODO(sgurun) android_webview hack
796 // Allow Prerendering to cancel this print request if necessary.
797 if (prerender::PrerenderHelper::IsPrerendering(render_view())) {
798 Send(new ChromeViewHostMsg_CancelPrerenderForPrinting(routing_id()));
799 return;
801 #endif // !defined(OS_ANDROID)
803 if (!IsScriptInitiatedPrintAllowed(frame, user_initiated))
804 return;
805 IncrementScriptedPrintCount();
807 if (is_preview_enabled_) {
808 print_preview_context_.InitWithFrame(frame);
809 RequestPrintPreview(PRINT_PREVIEW_SCRIPTED);
810 } else {
811 Print(frame, blink::WebNode());
815 bool PrintWebViewHelper::OnMessageReceived(const IPC::Message& message) {
816 bool handled = true;
817 IPC_BEGIN_MESSAGE_MAP(PrintWebViewHelper, message)
818 IPC_MESSAGE_HANDLER(PrintMsg_PrintPages, OnPrintPages)
819 IPC_MESSAGE_HANDLER(PrintMsg_PrintForSystemDialog, OnPrintForSystemDialog)
820 IPC_MESSAGE_HANDLER(PrintMsg_InitiatePrintPreview, OnInitiatePrintPreview)
821 IPC_MESSAGE_HANDLER(PrintMsg_PrintPreview, OnPrintPreview)
822 IPC_MESSAGE_HANDLER(PrintMsg_PrintForPrintPreview, OnPrintForPrintPreview)
823 IPC_MESSAGE_HANDLER(PrintMsg_PrintingDone, OnPrintingDone)
824 IPC_MESSAGE_HANDLER(PrintMsg_ResetScriptedPrintCount,
825 ResetScriptedPrintCount)
826 IPC_MESSAGE_HANDLER(PrintMsg_SetScriptedPrintingBlocked,
827 SetScriptedPrintBlocked)
828 IPC_MESSAGE_UNHANDLED(handled = false)
829 IPC_END_MESSAGE_MAP()
830 return handled;
833 void PrintWebViewHelper::OnPrintForPrintPreview(
834 const base::DictionaryValue& job_settings) {
835 DCHECK(is_preview_enabled_);
836 // If still not finished with earlier print request simply ignore.
837 if (prep_frame_view_)
838 return;
840 if (!render_view()->GetWebView())
841 return;
842 blink::WebFrame* main_frame = render_view()->GetWebView()->mainFrame();
843 if (!main_frame)
844 return;
846 blink::WebDocument document = main_frame->document();
847 // <object> with id="pdf-viewer" is created in
848 // chrome/browser/resources/print_preview/print_preview.js
849 blink::WebElement pdf_element = document.getElementById("pdf-viewer");
850 if (pdf_element.isNull()) {
851 NOTREACHED();
852 return;
855 // Set |print_for_preview_| flag and autoreset it to back to original
856 // on return.
857 base::AutoReset<bool> set_printing_flag(&print_for_preview_, true);
859 blink::WebLocalFrame* pdf_frame = pdf_element.document().frame();
860 if (!UpdatePrintSettings(pdf_frame, pdf_element, job_settings)) {
861 LOG(ERROR) << "UpdatePrintSettings failed";
862 DidFinishPrinting(FAIL_PRINT);
863 return;
866 // Print page onto entire page not just printable area. Preview PDF already
867 // has content in correct position taking into account page size and printable
868 // area.
869 // TODO(vitalybuka) : Make this consistent on all platform. This change
870 // affects Windows only. On Linux and OSX RenderPagesForPrint does not use
871 // printable_area. Also we can't change printable_area deeper inside
872 // RenderPagesForPrint for Windows, because it's used also by native
873 // printing and it expects real printable_area value.
874 // See http://crbug.com/123408
875 PrintMsg_Print_Params& print_params = print_pages_params_->params;
876 print_params.printable_area = gfx::Rect(print_params.page_size);
878 // Render Pages for printing.
879 if (!RenderPagesForPrint(pdf_frame, pdf_element)) {
880 LOG(ERROR) << "RenderPagesForPrint failed";
881 DidFinishPrinting(FAIL_PRINT);
885 bool PrintWebViewHelper::GetPrintFrame(blink::WebLocalFrame** frame) {
886 DCHECK(frame);
887 blink::WebView* webView = render_view()->GetWebView();
888 DCHECK(webView);
889 if (!webView)
890 return false;
892 // If the user has selected text in the currently focused frame we print
893 // only that frame (this makes print selection work for multiple frames).
894 blink::WebLocalFrame* focusedFrame =
895 webView->focusedFrame()->toWebLocalFrame();
896 *frame = focusedFrame->hasSelection()
897 ? focusedFrame
898 : webView->mainFrame()->toWebLocalFrame();
899 return true;
902 void PrintWebViewHelper::OnPrintPages() {
903 blink::WebLocalFrame* frame;
904 if (GetPrintFrame(&frame))
905 Print(frame, blink::WebNode());
908 void PrintWebViewHelper::OnPrintForSystemDialog() {
909 blink::WebLocalFrame* frame = print_preview_context_.source_frame();
910 if (!frame) {
911 NOTREACHED();
912 return;
915 Print(frame, print_preview_context_.source_node());
918 void PrintWebViewHelper::GetPageSizeAndContentAreaFromPageLayout(
919 const PageSizeMargins& page_layout_in_points,
920 gfx::Size* page_size,
921 gfx::Rect* content_area) {
922 *page_size = gfx::Size(
923 page_layout_in_points.content_width +
924 page_layout_in_points.margin_right +
925 page_layout_in_points.margin_left,
926 page_layout_in_points.content_height +
927 page_layout_in_points.margin_top +
928 page_layout_in_points.margin_bottom);
929 *content_area = gfx::Rect(page_layout_in_points.margin_left,
930 page_layout_in_points.margin_top,
931 page_layout_in_points.content_width,
932 page_layout_in_points.content_height);
935 void PrintWebViewHelper::UpdateFrameMarginsCssInfo(
936 const base::DictionaryValue& settings) {
937 int margins_type = 0;
938 if (!settings.GetInteger(kSettingMarginsType, &margins_type))
939 margins_type = DEFAULT_MARGINS;
940 ignore_css_margins_ = (margins_type != DEFAULT_MARGINS);
943 bool PrintWebViewHelper::IsPrintToPdfRequested(
944 const base::DictionaryValue& job_settings) {
945 bool print_to_pdf = false;
946 if (!job_settings.GetBoolean(kSettingPrintToPDF, &print_to_pdf))
947 NOTREACHED();
948 return print_to_pdf;
951 blink::WebPrintScalingOption PrintWebViewHelper::GetPrintScalingOption(
952 bool source_is_html, const base::DictionaryValue& job_settings,
953 const PrintMsg_Print_Params& params) {
954 DCHECK(!print_for_preview_);
956 if (params.print_to_pdf)
957 return blink::WebPrintScalingOptionSourceSize;
959 if (!source_is_html) {
960 if (!FitToPageEnabled(job_settings))
961 return blink::WebPrintScalingOptionNone;
963 bool no_plugin_scaling =
964 print_preview_context_.source_frame()->isPrintScalingDisabledForPlugin(
965 print_preview_context_.source_node());
967 if (params.is_first_request && no_plugin_scaling)
968 return blink::WebPrintScalingOptionNone;
970 return blink::WebPrintScalingOptionFitToPrintableArea;
973 void PrintWebViewHelper::OnPrintPreview(const base::DictionaryValue& settings) {
974 DCHECK(is_preview_enabled_);
975 print_preview_context_.OnPrintPreview();
977 UMA_HISTOGRAM_ENUMERATION("PrintPreview.PreviewEvent",
978 PREVIEW_EVENT_REQUESTED, PREVIEW_EVENT_MAX);
980 if (!UpdatePrintSettings(print_preview_context_.source_frame(),
981 print_preview_context_.source_node(), settings)) {
982 if (print_preview_context_.last_error() != PREVIEW_ERROR_BAD_SETTING) {
983 Send(new PrintHostMsg_PrintPreviewInvalidPrinterSettings(
984 routing_id(), print_pages_params_->params.document_cookie));
985 notify_browser_of_print_failure_ = false; // Already sent.
987 DidFinishPrinting(FAIL_PREVIEW);
988 return;
991 // If we are previewing a pdf and the print scaling is disabled, send a
992 // message to browser.
993 if (print_pages_params_->params.is_first_request &&
994 !print_preview_context_.IsModifiable() &&
995 print_preview_context_.source_frame()->isPrintScalingDisabledForPlugin(
996 print_preview_context_.source_node())) {
997 Send(new PrintHostMsg_PrintPreviewScalingDisabled(routing_id()));
1000 is_print_ready_metafile_sent_ = false;
1002 // PDF printer device supports alpha blending.
1003 print_pages_params_->params.supports_alpha_blend = true;
1005 bool generate_draft_pages = false;
1006 if (!settings.GetBoolean(kSettingGenerateDraftData,
1007 &generate_draft_pages)) {
1008 NOTREACHED();
1010 print_preview_context_.set_generate_draft_pages(generate_draft_pages);
1012 PrepareFrameForPreviewDocument();
1015 void PrintWebViewHelper::PrepareFrameForPreviewDocument() {
1016 reset_prep_frame_view_ = false;
1018 if (!print_pages_params_ || CheckForCancel()) {
1019 DidFinishPrinting(FAIL_PREVIEW);
1020 return;
1023 // Don't reset loading frame or WebKit will fail assert. Just retry when
1024 // current selection is loaded.
1025 if (prep_frame_view_ && prep_frame_view_->IsLoadingSelection()) {
1026 reset_prep_frame_view_ = true;
1027 return;
1030 const PrintMsg_Print_Params& print_params = print_pages_params_->params;
1031 prep_frame_view_.reset(
1032 new PrepareFrameAndViewForPrint(print_params,
1033 print_preview_context_.source_frame(),
1034 print_preview_context_.source_node(),
1035 ignore_css_margins_));
1036 prep_frame_view_->CopySelectionIfNeeded(
1037 render_view()->GetWebkitPreferences(),
1038 base::Bind(&PrintWebViewHelper::OnFramePreparedForPreviewDocument,
1039 base::Unretained(this)));
1042 void PrintWebViewHelper::OnFramePreparedForPreviewDocument() {
1043 if (reset_prep_frame_view_) {
1044 PrepareFrameForPreviewDocument();
1045 return;
1047 DidFinishPrinting(CreatePreviewDocument() ? OK : FAIL_PREVIEW);
1050 bool PrintWebViewHelper::CreatePreviewDocument() {
1051 if (!print_pages_params_ || CheckForCancel())
1052 return false;
1054 UMA_HISTOGRAM_ENUMERATION("PrintPreview.PreviewEvent",
1055 PREVIEW_EVENT_CREATE_DOCUMENT, PREVIEW_EVENT_MAX);
1057 const PrintMsg_Print_Params& print_params = print_pages_params_->params;
1058 const std::vector<int>& pages = print_pages_params_->pages;
1060 if (!print_preview_context_.CreatePreviewDocument(prep_frame_view_.release(),
1061 pages)) {
1062 return false;
1065 PageSizeMargins default_page_layout;
1066 ComputePageLayoutInPointsForCss(print_preview_context_.prepared_frame(), 0,
1067 print_params, ignore_css_margins_, NULL,
1068 &default_page_layout);
1070 bool has_page_size_style = PrintingFrameHasPageSizeStyle(
1071 print_preview_context_.prepared_frame(),
1072 print_preview_context_.total_page_count());
1073 int dpi = GetDPI(&print_params);
1075 gfx::Rect printable_area_in_points(
1076 ConvertUnit(print_params.printable_area.x(), dpi, kPointsPerInch),
1077 ConvertUnit(print_params.printable_area.y(), dpi, kPointsPerInch),
1078 ConvertUnit(print_params.printable_area.width(), dpi, kPointsPerInch),
1079 ConvertUnit(print_params.printable_area.height(), dpi, kPointsPerInch));
1081 // Margins: Send default page layout to browser process.
1082 Send(new PrintHostMsg_DidGetDefaultPageLayout(routing_id(),
1083 default_page_layout,
1084 printable_area_in_points,
1085 has_page_size_style));
1087 PrintHostMsg_DidGetPreviewPageCount_Params params;
1088 params.page_count = print_preview_context_.total_page_count();
1089 params.is_modifiable = print_preview_context_.IsModifiable();
1090 params.document_cookie = print_params.document_cookie;
1091 params.preview_request_id = print_params.preview_request_id;
1092 params.clear_preview_data = print_preview_context_.generate_draft_pages();
1093 Send(new PrintHostMsg_DidGetPreviewPageCount(routing_id(), params));
1094 if (CheckForCancel())
1095 return false;
1097 while (!print_preview_context_.IsFinalPageRendered()) {
1098 int page_number = print_preview_context_.GetNextPageNumber();
1099 DCHECK_GE(page_number, 0);
1100 if (!RenderPreviewPage(page_number, print_params))
1101 return false;
1103 if (CheckForCancel())
1104 return false;
1106 // We must call PrepareFrameAndViewForPrint::FinishPrinting() (by way of
1107 // print_preview_context_.AllPagesRendered()) before calling
1108 // FinalizePrintReadyDocument() when printing a PDF because the plugin
1109 // code does not generate output until we call FinishPrinting(). We do not
1110 // generate draft pages for PDFs, so IsFinalPageRendered() and
1111 // IsLastPageOfPrintReadyMetafile() will be true in the same iteration of
1112 // the loop.
1113 if (print_preview_context_.IsFinalPageRendered())
1114 print_preview_context_.AllPagesRendered();
1116 if (print_preview_context_.IsLastPageOfPrintReadyMetafile()) {
1117 DCHECK(print_preview_context_.IsModifiable() ||
1118 print_preview_context_.IsFinalPageRendered());
1119 if (!FinalizePrintReadyDocument())
1120 return false;
1123 print_preview_context_.Finished();
1124 return true;
1127 bool PrintWebViewHelper::FinalizePrintReadyDocument() {
1128 DCHECK(!is_print_ready_metafile_sent_);
1129 print_preview_context_.FinalizePrintReadyDocument();
1131 // Get the size of the resulting metafile.
1132 PdfMetafileSkia* metafile = print_preview_context_.metafile();
1133 uint32 buf_size = metafile->GetDataSize();
1134 DCHECK_GT(buf_size, 0u);
1136 PrintHostMsg_DidPreviewDocument_Params preview_params;
1137 preview_params.reuse_existing_data = false;
1138 preview_params.data_size = buf_size;
1139 preview_params.document_cookie = print_pages_params_->params.document_cookie;
1140 preview_params.expected_pages_count =
1141 print_preview_context_.total_page_count();
1142 preview_params.modifiable = print_preview_context_.IsModifiable();
1143 preview_params.preview_request_id =
1144 print_pages_params_->params.preview_request_id;
1146 // Ask the browser to create the shared memory for us.
1147 if (!CopyMetafileDataToSharedMem(metafile,
1148 &(preview_params.metafile_data_handle))) {
1149 LOG(ERROR) << "CopyMetafileDataToSharedMem failed";
1150 print_preview_context_.set_error(PREVIEW_ERROR_METAFILE_COPY_FAILED);
1151 return false;
1153 is_print_ready_metafile_sent_ = true;
1155 Send(new PrintHostMsg_MetafileReadyForPrinting(routing_id(), preview_params));
1156 return true;
1159 void PrintWebViewHelper::OnPrintingDone(bool success) {
1160 notify_browser_of_print_failure_ = false;
1161 if (!success)
1162 LOG(ERROR) << "Failure in OnPrintingDone";
1163 DidFinishPrinting(success ? OK : FAIL_PRINT);
1166 void PrintWebViewHelper::SetScriptedPrintBlocked(bool blocked) {
1167 is_scripted_printing_blocked_ = blocked;
1170 void PrintWebViewHelper::OnInitiatePrintPreview(bool selection_only) {
1171 DCHECK(is_preview_enabled_);
1172 blink::WebLocalFrame* frame = NULL;
1173 GetPrintFrame(&frame);
1174 DCHECK(frame);
1175 print_preview_context_.InitWithFrame(frame);
1176 RequestPrintPreview(selection_only ?
1177 PRINT_PREVIEW_USER_INITIATED_SELECTION :
1178 PRINT_PREVIEW_USER_INITIATED_ENTIRE_FRAME);
1181 bool PrintWebViewHelper::IsPrintingEnabled() {
1182 bool result = false;
1183 Send(new PrintHostMsg_IsPrintingEnabled(routing_id(), &result));
1184 return result;
1187 void PrintWebViewHelper::PrintNode(const blink::WebNode& node) {
1188 if (node.isNull() || !node.document().frame()) {
1189 // This can occur when the context menu refers to an invalid WebNode.
1190 // See http://crbug.com/100890#c17 for a repro case.
1191 return;
1194 if (print_node_in_progress_) {
1195 // This can happen as a result of processing sync messages when printing
1196 // from ppapi plugins. It's a rare case, so its OK to just fail here.
1197 // See http://crbug.com/159165.
1198 return;
1201 print_node_in_progress_ = true;
1203 // Make a copy of the node, in case RenderView::OnContextMenuClosed resets
1204 // its |context_menu_node_|.
1205 if (is_preview_enabled_) {
1206 print_preview_context_.InitWithNode(node);
1207 RequestPrintPreview(PRINT_PREVIEW_USER_INITIATED_CONTEXT_NODE);
1208 } else {
1209 blink::WebNode duplicate_node(node);
1210 Print(duplicate_node.document().frame(), duplicate_node);
1213 print_node_in_progress_ = false;
1216 void PrintWebViewHelper::Print(blink::WebLocalFrame* frame,
1217 const blink::WebNode& node) {
1218 // If still not finished with earlier print request simply ignore.
1219 if (prep_frame_view_)
1220 return;
1222 FrameReference frame_ref(frame);
1224 int expected_page_count = 0;
1225 if (!CalculateNumberOfPages(frame, node, &expected_page_count)) {
1226 DidFinishPrinting(FAIL_PRINT_INIT);
1227 return; // Failed to init print page settings.
1230 // Some full screen plugins can say they don't want to print.
1231 if (!expected_page_count) {
1232 DidFinishPrinting(FAIL_PRINT);
1233 return;
1236 #if !defined(OS_ANDROID)
1237 // TODO(sgurun) android_webview hack
1238 // Ask the browser to show UI to retrieve the final print settings.
1239 if (!GetPrintSettingsFromUser(frame_ref.GetFrame(), node,
1240 expected_page_count)) {
1241 DidFinishPrinting(OK); // Release resources and fail silently.
1242 return;
1244 #endif // !defined(OS_ANDROID)
1246 // Render Pages for printing.
1247 if (!RenderPagesForPrint(frame_ref.GetFrame(), node)) {
1248 LOG(ERROR) << "RenderPagesForPrint failed";
1249 DidFinishPrinting(FAIL_PRINT);
1251 ResetScriptedPrintCount();
1254 void PrintWebViewHelper::DidFinishPrinting(PrintingResult result) {
1255 switch (result) {
1256 case OK:
1257 break;
1259 case FAIL_PRINT_INIT:
1260 DCHECK(!notify_browser_of_print_failure_);
1261 break;
1263 case FAIL_PRINT:
1264 if (notify_browser_of_print_failure_ && print_pages_params_.get()) {
1265 int cookie = print_pages_params_->params.document_cookie;
1266 Send(new PrintHostMsg_PrintingFailed(routing_id(), cookie));
1268 break;
1270 case FAIL_PREVIEW:
1271 DCHECK(is_preview_enabled_);
1272 int cookie = print_pages_params_.get() ?
1273 print_pages_params_->params.document_cookie : 0;
1274 if (notify_browser_of_print_failure_) {
1275 LOG(ERROR) << "CreatePreviewDocument failed";
1276 Send(new PrintHostMsg_PrintPreviewFailed(routing_id(), cookie));
1277 } else {
1278 Send(new PrintHostMsg_PrintPreviewCancelled(routing_id(), cookie));
1280 print_preview_context_.Failed(notify_browser_of_print_failure_);
1281 break;
1284 prep_frame_view_.reset();
1285 print_pages_params_.reset();
1286 notify_browser_of_print_failure_ = true;
1289 void PrintWebViewHelper::OnFramePreparedForPrintPages() {
1290 PrintPages();
1291 FinishFramePrinting();
1294 void PrintWebViewHelper::PrintPages() {
1295 if (!prep_frame_view_) // Printing is already canceled or failed.
1296 return;
1297 prep_frame_view_->StartPrinting();
1299 int page_count = prep_frame_view_->GetExpectedPageCount();
1300 if (!page_count) {
1301 LOG(ERROR) << "Can't print 0 pages.";
1302 return DidFinishPrinting(FAIL_PRINT);
1305 const PrintMsg_PrintPages_Params& params = *print_pages_params_;
1306 const PrintMsg_Print_Params& print_params = params.params;
1308 #if !defined(OS_CHROMEOS) && !defined(OS_ANDROID)
1309 // TODO(vitalybuka): should be page_count or valid pages from params.pages.
1310 // See http://crbug.com/161576
1311 Send(new PrintHostMsg_DidGetPrintedPagesCount(routing_id(),
1312 print_params.document_cookie,
1313 page_count));
1314 #endif // !defined(OS_CHROMEOS)
1316 if (print_params.preview_ui_id < 0) {
1317 // Printing for system dialog.
1318 int printed_count = params.pages.empty() ? page_count : params.pages.size();
1319 #if !defined(OS_CHROMEOS)
1320 UMA_HISTOGRAM_COUNTS("PrintPreview.PageCount.SystemDialog", printed_count);
1321 #else
1322 UMA_HISTOGRAM_COUNTS("PrintPreview.PageCount.PrintToCloudPrintWebDialog",
1323 printed_count);
1324 #endif // !defined(OS_CHROMEOS)
1328 if (!PrintPagesNative(prep_frame_view_->frame(), page_count,
1329 prep_frame_view_->GetPrintCanvasSize())) {
1330 LOG(ERROR) << "Printing failed.";
1331 return DidFinishPrinting(FAIL_PRINT);
1335 void PrintWebViewHelper::FinishFramePrinting() {
1336 prep_frame_view_.reset();
1339 #if defined(OS_MACOSX) || defined(OS_WIN)
1340 bool PrintWebViewHelper::PrintPagesNative(blink::WebFrame* frame,
1341 int page_count,
1342 const gfx::Size& canvas_size) {
1343 const PrintMsg_PrintPages_Params& params = *print_pages_params_;
1344 const PrintMsg_Print_Params& print_params = params.params;
1346 PrintMsg_PrintPage_Params page_params;
1347 page_params.params = print_params;
1348 if (params.pages.empty()) {
1349 for (int i = 0; i < page_count; ++i) {
1350 page_params.page_number = i;
1351 PrintPageInternal(page_params, canvas_size, frame);
1353 } else {
1354 for (size_t i = 0; i < params.pages.size(); ++i) {
1355 if (params.pages[i] >= page_count)
1356 break;
1357 page_params.page_number = params.pages[i];
1358 PrintPageInternal(page_params, canvas_size, frame);
1361 return true;
1364 #endif // OS_MACOSX || OS_WIN
1366 // static - Not anonymous so that platform implementations can use it.
1367 void PrintWebViewHelper::ComputePageLayoutInPointsForCss(
1368 blink::WebFrame* frame,
1369 int page_index,
1370 const PrintMsg_Print_Params& page_params,
1371 bool ignore_css_margins,
1372 double* scale_factor,
1373 PageSizeMargins* page_layout_in_points) {
1374 PrintMsg_Print_Params params = CalculatePrintParamsForCss(
1375 frame, page_index, page_params, ignore_css_margins,
1376 page_params.print_scaling_option ==
1377 blink::WebPrintScalingOptionFitToPrintableArea,
1378 scale_factor);
1379 CalculatePageLayoutFromPrintParams(params, page_layout_in_points);
1382 bool PrintWebViewHelper::InitPrintSettings(bool fit_to_paper_size) {
1383 PrintMsg_PrintPages_Params settings;
1384 Send(new PrintHostMsg_GetDefaultPrintSettings(routing_id(),
1385 &settings.params));
1386 // Check if the printer returned any settings, if the settings is empty, we
1387 // can safely assume there are no printer drivers configured. So we safely
1388 // terminate.
1389 bool result = true;
1390 if (!PrintMsg_Print_Params_IsValid(settings.params))
1391 result = false;
1393 if (result &&
1394 (settings.params.dpi < kMinDpi || settings.params.document_cookie == 0)) {
1395 // Invalid print page settings.
1396 NOTREACHED();
1397 result = false;
1400 // Reset to default values.
1401 ignore_css_margins_ = false;
1402 settings.pages.clear();
1404 settings.params.print_scaling_option =
1405 blink::WebPrintScalingOptionSourceSize;
1406 if (fit_to_paper_size) {
1407 settings.params.print_scaling_option =
1408 blink::WebPrintScalingOptionFitToPrintableArea;
1411 print_pages_params_.reset(new PrintMsg_PrintPages_Params(settings));
1412 return result;
1415 bool PrintWebViewHelper::CalculateNumberOfPages(blink::WebLocalFrame* frame,
1416 const blink::WebNode& node,
1417 int* number_of_pages) {
1418 DCHECK(frame);
1419 bool fit_to_paper_size = !(PrintingNodeOrPdfFrame(frame, node));
1420 if (!InitPrintSettings(fit_to_paper_size)) {
1421 notify_browser_of_print_failure_ = false;
1422 #if !defined(OS_ANDROID)
1423 // TODO(sgurun) android_webview hack
1424 render_view()->RunModalAlertDialog(
1425 frame,
1426 l10n_util::GetStringUTF16(IDS_PRINT_INVALID_PRINTER_SETTINGS));
1427 #endif // !defined(OS_ANDROID)
1428 return false;
1431 const PrintMsg_Print_Params& params = print_pages_params_->params;
1432 PrepareFrameAndViewForPrint prepare(params, frame, node, ignore_css_margins_);
1433 prepare.StartPrinting();
1435 Send(new PrintHostMsg_DidGetDocumentCookie(routing_id(),
1436 params.document_cookie));
1437 *number_of_pages = prepare.GetExpectedPageCount();
1438 return true;
1441 bool PrintWebViewHelper::UpdatePrintSettings(
1442 blink::WebLocalFrame* frame,
1443 const blink::WebNode& node,
1444 const base::DictionaryValue& passed_job_settings) {
1445 DCHECK(is_preview_enabled_);
1446 const base::DictionaryValue* job_settings = &passed_job_settings;
1447 base::DictionaryValue modified_job_settings;
1448 if (job_settings->empty()) {
1449 if (!print_for_preview_)
1450 print_preview_context_.set_error(PREVIEW_ERROR_BAD_SETTING);
1451 return false;
1454 bool source_is_html = true;
1455 if (print_for_preview_) {
1456 if (!job_settings->GetBoolean(kSettingPreviewModifiable, &source_is_html)) {
1457 NOTREACHED();
1459 } else {
1460 source_is_html = !PrintingNodeOrPdfFrame(frame, node);
1463 if (print_for_preview_ || !source_is_html) {
1464 modified_job_settings.MergeDictionary(job_settings);
1465 modified_job_settings.SetBoolean(kSettingHeaderFooterEnabled, false);
1466 modified_job_settings.SetInteger(kSettingMarginsType, NO_MARGINS);
1467 job_settings = &modified_job_settings;
1470 // Send the cookie so that UpdatePrintSettings can reuse PrinterQuery when
1471 // possible.
1472 int cookie = print_pages_params_.get() ?
1473 print_pages_params_->params.document_cookie : 0;
1474 PrintMsg_PrintPages_Params settings;
1475 Send(new PrintHostMsg_UpdatePrintSettings(routing_id(), cookie, *job_settings,
1476 &settings));
1477 print_pages_params_.reset(new PrintMsg_PrintPages_Params(settings));
1479 if (!PrintMsg_Print_Params_IsValid(settings.params)) {
1480 if (!print_for_preview_) {
1481 print_preview_context_.set_error(PREVIEW_ERROR_INVALID_PRINTER_SETTINGS);
1482 } else {
1483 #if !defined(OS_ANDROID)
1484 // TODO(sgurun) android_webview hack
1485 // PrintForPrintPreview
1486 blink::WebFrame* print_frame = NULL;
1487 // This may not be the right frame, but the alert will be modal,
1488 // therefore it works well enough.
1489 GetPrintFrame(&print_frame);
1490 if (print_frame) {
1491 render_view()->RunModalAlertDialog(
1492 print_frame,
1493 l10n_util::GetStringUTF16(
1494 IDS_PRINT_INVALID_PRINTER_SETTINGS));
1496 #endif // !defined(OS_ANDROID)
1498 return false;
1501 if (settings.params.dpi < kMinDpi || !settings.params.document_cookie) {
1502 print_preview_context_.set_error(PREVIEW_ERROR_UPDATING_PRINT_SETTINGS);
1503 return false;
1506 if (!job_settings->GetInteger(kPreviewUIID, &settings.params.preview_ui_id)) {
1507 NOTREACHED();
1508 print_preview_context_.set_error(PREVIEW_ERROR_BAD_SETTING);
1509 return false;
1512 if (!print_for_preview_) {
1513 // Validate expected print preview settings.
1514 if (!job_settings->GetInteger(kPreviewRequestID,
1515 &settings.params.preview_request_id) ||
1516 !job_settings->GetBoolean(kIsFirstRequest,
1517 &settings.params.is_first_request)) {
1518 NOTREACHED();
1519 print_preview_context_.set_error(PREVIEW_ERROR_BAD_SETTING);
1520 return false;
1523 settings.params.print_to_pdf = IsPrintToPdfRequested(*job_settings);
1524 UpdateFrameMarginsCssInfo(*job_settings);
1525 settings.params.print_scaling_option = GetPrintScalingOption(
1526 source_is_html, *job_settings, settings.params);
1528 // Header/Footer: Set |header_footer_info_|.
1529 if (settings.params.display_header_footer) {
1530 header_footer_info_.reset(new base::DictionaryValue());
1531 header_footer_info_->SetDouble(kSettingHeaderFooterDate,
1532 base::Time::Now().ToJsTime());
1533 header_footer_info_->SetString(kSettingHeaderFooterURL,
1534 settings.params.url);
1535 header_footer_info_->SetString(kSettingHeaderFooterTitle,
1536 settings.params.title);
1540 print_pages_params_.reset(new PrintMsg_PrintPages_Params(settings));
1541 Send(new PrintHostMsg_DidGetDocumentCookie(routing_id(),
1542 settings.params.document_cookie));
1544 return true;
1547 bool PrintWebViewHelper::GetPrintSettingsFromUser(blink::WebFrame* frame,
1548 const blink::WebNode& node,
1549 int expected_pages_count) {
1550 PrintHostMsg_ScriptedPrint_Params params;
1551 PrintMsg_PrintPages_Params print_settings;
1553 params.cookie = print_pages_params_->params.document_cookie;
1554 params.has_selection = frame->hasSelection();
1555 params.expected_pages_count = expected_pages_count;
1556 MarginType margin_type = DEFAULT_MARGINS;
1557 if (PrintingNodeOrPdfFrame(frame, node))
1558 margin_type = GetMarginsForPdf(frame, node);
1559 params.margin_type = margin_type;
1561 Send(new PrintHostMsg_DidShowPrintDialog(routing_id()));
1563 // PrintHostMsg_ScriptedPrint will reset print_scaling_option, so we save the
1564 // value before and restore it afterwards.
1565 blink::WebPrintScalingOption scaling_option =
1566 print_pages_params_->params.print_scaling_option;
1568 print_pages_params_.reset();
1569 IPC::SyncMessage* msg =
1570 new PrintHostMsg_ScriptedPrint(routing_id(), params, &print_settings);
1571 msg->EnableMessagePumping();
1572 Send(msg);
1573 print_pages_params_.reset(new PrintMsg_PrintPages_Params(print_settings));
1575 print_pages_params_->params.print_scaling_option = scaling_option;
1576 return (print_settings.params.dpi && print_settings.params.document_cookie);
1579 bool PrintWebViewHelper::RenderPagesForPrint(blink::WebLocalFrame* frame,
1580 const blink::WebNode& node) {
1581 if (!frame || prep_frame_view_)
1582 return false;
1583 const PrintMsg_PrintPages_Params& params = *print_pages_params_;
1584 const PrintMsg_Print_Params& print_params = params.params;
1585 prep_frame_view_.reset(new PrepareFrameAndViewForPrint(
1586 print_params, frame, node, ignore_css_margins_));
1587 DCHECK(!print_pages_params_->params.selection_only ||
1588 print_pages_params_->pages.empty());
1589 prep_frame_view_->CopySelectionIfNeeded(
1590 render_view()->GetWebkitPreferences(),
1591 base::Bind(&PrintWebViewHelper::OnFramePreparedForPrintPages,
1592 base::Unretained(this)));
1593 return true;
1596 #if defined(OS_POSIX)
1597 bool PrintWebViewHelper::CopyMetafileDataToSharedMem(
1598 PdfMetafileSkia* metafile,
1599 base::SharedMemoryHandle* shared_mem_handle) {
1600 uint32 buf_size = metafile->GetDataSize();
1601 scoped_ptr<base::SharedMemory> shared_buf(
1602 content::RenderThread::Get()->HostAllocateSharedMemoryBuffer(
1603 buf_size).release());
1605 if (shared_buf.get()) {
1606 if (shared_buf->Map(buf_size)) {
1607 metafile->GetData(shared_buf->memory(), buf_size);
1608 shared_buf->GiveToProcess(base::GetCurrentProcessHandle(),
1609 shared_mem_handle);
1610 return true;
1613 NOTREACHED();
1614 return false;
1616 #endif // defined(OS_POSIX)
1618 bool PrintWebViewHelper::IsScriptInitiatedPrintTooFrequent(
1619 blink::WebFrame* frame) {
1620 const int kMinSecondsToIgnoreJavascriptInitiatedPrint = 2;
1621 const int kMaxSecondsToIgnoreJavascriptInitiatedPrint = 32;
1622 bool too_frequent = false;
1624 // Check if there is script repeatedly trying to print and ignore it if too
1625 // frequent. The first 3 times, we use a constant wait time, but if this
1626 // gets excessive, we switch to exponential wait time. So for a page that
1627 // calls print() in a loop the user will need to cancel the print dialog
1628 // after: [2, 2, 2, 4, 8, 16, 32, 32, ...] seconds.
1629 // This gives the user time to navigate from the page.
1630 if (user_cancelled_scripted_print_count_ > 0) {
1631 base::TimeDelta diff = base::Time::Now() - last_cancelled_script_print_;
1632 int min_wait_seconds = kMinSecondsToIgnoreJavascriptInitiatedPrint;
1633 if (user_cancelled_scripted_print_count_ > 3) {
1634 min_wait_seconds = std::min(
1635 kMinSecondsToIgnoreJavascriptInitiatedPrint <<
1636 (user_cancelled_scripted_print_count_ - 3),
1637 kMaxSecondsToIgnoreJavascriptInitiatedPrint);
1639 if (diff.InSeconds() < min_wait_seconds) {
1640 too_frequent = true;
1644 if (!too_frequent)
1645 return false;
1647 blink::WebString message(
1648 blink::WebString::fromUTF8("Ignoring too frequent calls to print()."));
1649 frame->addMessageToConsole(
1650 blink::WebConsoleMessage(
1651 blink::WebConsoleMessage::LevelWarning, message));
1652 return true;
1655 void PrintWebViewHelper::ResetScriptedPrintCount() {
1656 // Reset cancel counter on successful print.
1657 user_cancelled_scripted_print_count_ = 0;
1660 void PrintWebViewHelper::IncrementScriptedPrintCount() {
1661 ++user_cancelled_scripted_print_count_;
1662 last_cancelled_script_print_ = base::Time::Now();
1665 void PrintWebViewHelper::ShowScriptedPrintPreview() {
1666 if (is_scripted_preview_delayed_) {
1667 is_scripted_preview_delayed_ = false;
1668 Send(new PrintHostMsg_ShowScriptedPrintPreview(routing_id(),
1669 print_preview_context_.IsModifiable()));
1673 void PrintWebViewHelper::RequestPrintPreview(PrintPreviewRequestType type) {
1674 const bool is_modifiable = print_preview_context_.IsModifiable();
1675 const bool has_selection = print_preview_context_.HasSelection();
1676 PrintHostMsg_RequestPrintPreview_Params params;
1677 params.is_modifiable = is_modifiable;
1678 params.has_selection = has_selection;
1679 switch (type) {
1680 case PRINT_PREVIEW_SCRIPTED: {
1681 // Shows scripted print preview in two stages.
1682 // 1. PrintHostMsg_SetupScriptedPrintPreview blocks this call and JS by
1683 // pumping messages here.
1684 // 2. PrintHostMsg_ShowScriptedPrintPreview shows preview once the
1685 // document has been loaded.
1686 is_scripted_preview_delayed_ = true;
1687 if (is_loading_ && GetPlugin(print_preview_context_.source_frame())) {
1688 // Wait for DidStopLoading. Plugins may not know the correct
1689 // |is_modifiable| value until they are fully loaded, which occurs when
1690 // DidStopLoading() is called. Defer showing the preview until then.
1691 } else {
1692 base::MessageLoop::current()->PostTask(
1693 FROM_HERE,
1694 base::Bind(&PrintWebViewHelper::ShowScriptedPrintPreview,
1695 weak_ptr_factory_.GetWeakPtr()));
1697 IPC::SyncMessage* msg =
1698 new PrintHostMsg_SetupScriptedPrintPreview(routing_id());
1699 msg->EnableMessagePumping();
1700 Send(msg);
1701 is_scripted_preview_delayed_ = false;
1702 return;
1704 case PRINT_PREVIEW_USER_INITIATED_ENTIRE_FRAME: {
1705 break;
1707 case PRINT_PREVIEW_USER_INITIATED_SELECTION: {
1708 DCHECK(has_selection);
1709 params.selection_only = has_selection;
1710 break;
1712 case PRINT_PREVIEW_USER_INITIATED_CONTEXT_NODE: {
1713 params.webnode_only = true;
1714 break;
1716 default: {
1717 NOTREACHED();
1718 return;
1721 Send(new PrintHostMsg_RequestPrintPreview(routing_id(), params));
1724 bool PrintWebViewHelper::CheckForCancel() {
1725 const PrintMsg_Print_Params& print_params = print_pages_params_->params;
1726 bool cancel = false;
1727 Send(new PrintHostMsg_CheckForCancel(routing_id(),
1728 print_params.preview_ui_id,
1729 print_params.preview_request_id,
1730 &cancel));
1731 if (cancel)
1732 notify_browser_of_print_failure_ = false;
1733 return cancel;
1736 bool PrintWebViewHelper::PreviewPageRendered(int page_number,
1737 PdfMetafileSkia* metafile) {
1738 DCHECK_GE(page_number, FIRST_PAGE_INDEX);
1740 // For non-modifiable files, |metafile| should be NULL, so do not bother
1741 // sending a message. If we don't generate draft metafiles, |metafile| is
1742 // NULL.
1743 if (!print_preview_context_.IsModifiable() ||
1744 !print_preview_context_.generate_draft_pages()) {
1745 DCHECK(!metafile);
1746 return true;
1749 if (!metafile) {
1750 NOTREACHED();
1751 print_preview_context_.set_error(
1752 PREVIEW_ERROR_PAGE_RENDERED_WITHOUT_METAFILE);
1753 return false;
1756 PrintHostMsg_DidPreviewPage_Params preview_page_params;
1757 // Get the size of the resulting metafile.
1758 uint32 buf_size = metafile->GetDataSize();
1759 DCHECK_GT(buf_size, 0u);
1760 if (!CopyMetafileDataToSharedMem(
1761 metafile, &(preview_page_params.metafile_data_handle))) {
1762 LOG(ERROR) << "CopyMetafileDataToSharedMem failed";
1763 print_preview_context_.set_error(PREVIEW_ERROR_METAFILE_COPY_FAILED);
1764 return false;
1766 preview_page_params.data_size = buf_size;
1767 preview_page_params.page_number = page_number;
1768 preview_page_params.preview_request_id =
1769 print_pages_params_->params.preview_request_id;
1771 Send(new PrintHostMsg_DidPreviewPage(routing_id(), preview_page_params));
1772 return true;
1775 PrintWebViewHelper::PrintPreviewContext::PrintPreviewContext()
1776 : total_page_count_(0),
1777 current_page_index_(0),
1778 generate_draft_pages_(true),
1779 print_ready_metafile_page_count_(0),
1780 error_(PREVIEW_ERROR_NONE),
1781 state_(UNINITIALIZED) {
1784 PrintWebViewHelper::PrintPreviewContext::~PrintPreviewContext() {
1787 void PrintWebViewHelper::PrintPreviewContext::InitWithFrame(
1788 blink::WebLocalFrame* web_frame) {
1789 DCHECK(web_frame);
1790 DCHECK(!IsRendering());
1791 state_ = INITIALIZED;
1792 source_frame_.Reset(web_frame);
1793 source_node_.reset();
1796 void PrintWebViewHelper::PrintPreviewContext::InitWithNode(
1797 const blink::WebNode& web_node) {
1798 DCHECK(!web_node.isNull());
1799 DCHECK(web_node.document().frame());
1800 DCHECK(!IsRendering());
1801 state_ = INITIALIZED;
1802 source_frame_.Reset(web_node.document().frame());
1803 source_node_ = web_node;
1806 void PrintWebViewHelper::PrintPreviewContext::OnPrintPreview() {
1807 DCHECK_EQ(INITIALIZED, state_);
1808 ClearContext();
1811 bool PrintWebViewHelper::PrintPreviewContext::CreatePreviewDocument(
1812 PrepareFrameAndViewForPrint* prepared_frame,
1813 const std::vector<int>& pages) {
1814 DCHECK_EQ(INITIALIZED, state_);
1815 state_ = RENDERING;
1817 // Need to make sure old object gets destroyed first.
1818 prep_frame_view_.reset(prepared_frame);
1819 prep_frame_view_->StartPrinting();
1821 total_page_count_ = prep_frame_view_->GetExpectedPageCount();
1822 if (total_page_count_ == 0) {
1823 LOG(ERROR) << "CreatePreviewDocument got 0 page count";
1824 set_error(PREVIEW_ERROR_ZERO_PAGES);
1825 return false;
1828 metafile_.reset(new PdfMetafileSkia);
1829 if (!metafile_->Init()) {
1830 set_error(PREVIEW_ERROR_METAFILE_INIT_FAILED);
1831 LOG(ERROR) << "PdfMetafileSkia Init failed";
1832 return false;
1835 current_page_index_ = 0;
1836 pages_to_render_ = pages;
1837 // Sort and make unique.
1838 std::sort(pages_to_render_.begin(), pages_to_render_.end());
1839 pages_to_render_.resize(std::unique(pages_to_render_.begin(),
1840 pages_to_render_.end()) -
1841 pages_to_render_.begin());
1842 // Remove invalid pages.
1843 pages_to_render_.resize(std::lower_bound(pages_to_render_.begin(),
1844 pages_to_render_.end(),
1845 total_page_count_) -
1846 pages_to_render_.begin());
1847 print_ready_metafile_page_count_ = pages_to_render_.size();
1848 if (pages_to_render_.empty()) {
1849 print_ready_metafile_page_count_ = total_page_count_;
1850 // Render all pages.
1851 for (int i = 0; i < total_page_count_; ++i)
1852 pages_to_render_.push_back(i);
1853 } else if (generate_draft_pages_) {
1854 int pages_index = 0;
1855 for (int i = 0; i < total_page_count_; ++i) {
1856 if (pages_index < print_ready_metafile_page_count_ &&
1857 i == pages_to_render_[pages_index]) {
1858 pages_index++;
1859 continue;
1861 pages_to_render_.push_back(i);
1865 document_render_time_ = base::TimeDelta();
1866 begin_time_ = base::TimeTicks::Now();
1868 return true;
1871 void PrintWebViewHelper::PrintPreviewContext::RenderedPreviewPage(
1872 const base::TimeDelta& page_time) {
1873 DCHECK_EQ(RENDERING, state_);
1874 document_render_time_ += page_time;
1875 UMA_HISTOGRAM_TIMES("PrintPreview.RenderPDFPageTime", page_time);
1878 void PrintWebViewHelper::PrintPreviewContext::AllPagesRendered() {
1879 DCHECK_EQ(RENDERING, state_);
1880 state_ = DONE;
1881 prep_frame_view_->FinishPrinting();
1884 void PrintWebViewHelper::PrintPreviewContext::FinalizePrintReadyDocument() {
1885 DCHECK(IsRendering());
1887 base::TimeTicks begin_time = base::TimeTicks::Now();
1888 metafile_->FinishDocument();
1890 if (print_ready_metafile_page_count_ <= 0) {
1891 NOTREACHED();
1892 return;
1895 UMA_HISTOGRAM_MEDIUM_TIMES("PrintPreview.RenderToPDFTime",
1896 document_render_time_);
1897 base::TimeDelta total_time = (base::TimeTicks::Now() - begin_time) +
1898 document_render_time_;
1899 UMA_HISTOGRAM_MEDIUM_TIMES("PrintPreview.RenderAndGeneratePDFTime",
1900 total_time);
1901 UMA_HISTOGRAM_MEDIUM_TIMES("PrintPreview.RenderAndGeneratePDFTimeAvgPerPage",
1902 total_time / pages_to_render_.size());
1905 void PrintWebViewHelper::PrintPreviewContext::Finished() {
1906 DCHECK_EQ(DONE, state_);
1907 state_ = INITIALIZED;
1908 ClearContext();
1911 void PrintWebViewHelper::PrintPreviewContext::Failed(bool report_error) {
1912 DCHECK(state_ == INITIALIZED || state_ == RENDERING);
1913 state_ = INITIALIZED;
1914 if (report_error) {
1915 DCHECK_NE(PREVIEW_ERROR_NONE, error_);
1916 UMA_HISTOGRAM_ENUMERATION("PrintPreview.RendererError", error_,
1917 PREVIEW_ERROR_LAST_ENUM);
1919 ClearContext();
1922 int PrintWebViewHelper::PrintPreviewContext::GetNextPageNumber() {
1923 DCHECK_EQ(RENDERING, state_);
1924 if (IsFinalPageRendered())
1925 return -1;
1926 return pages_to_render_[current_page_index_++];
1929 bool PrintWebViewHelper::PrintPreviewContext::IsRendering() const {
1930 return state_ == RENDERING || state_ == DONE;
1933 bool PrintWebViewHelper::PrintPreviewContext::IsModifiable() {
1934 // The only kind of node we can print right now is a PDF node.
1935 return !PrintingNodeOrPdfFrame(source_frame(), source_node_);
1938 bool PrintWebViewHelper::PrintPreviewContext::HasSelection() {
1939 return IsModifiable() && source_frame()->hasSelection();
1942 bool PrintWebViewHelper::PrintPreviewContext::IsLastPageOfPrintReadyMetafile()
1943 const {
1944 DCHECK(IsRendering());
1945 return current_page_index_ == print_ready_metafile_page_count_;
1948 bool PrintWebViewHelper::PrintPreviewContext::IsFinalPageRendered() const {
1949 DCHECK(IsRendering());
1950 return static_cast<size_t>(current_page_index_) == pages_to_render_.size();
1953 void PrintWebViewHelper::PrintPreviewContext::set_generate_draft_pages(
1954 bool generate_draft_pages) {
1955 DCHECK_EQ(INITIALIZED, state_);
1956 generate_draft_pages_ = generate_draft_pages;
1959 void PrintWebViewHelper::PrintPreviewContext::set_error(
1960 enum PrintPreviewErrorBuckets error) {
1961 error_ = error;
1964 blink::WebLocalFrame* PrintWebViewHelper::PrintPreviewContext::source_frame() {
1965 DCHECK_NE(UNINITIALIZED, state_);
1966 return source_frame_.GetFrame();
1969 const blink::WebNode&
1970 PrintWebViewHelper::PrintPreviewContext::source_node() const {
1971 DCHECK_NE(UNINITIALIZED, state_);
1972 return source_node_;
1975 blink::WebLocalFrame*
1976 PrintWebViewHelper::PrintPreviewContext::prepared_frame() {
1977 DCHECK_NE(UNINITIALIZED, state_);
1978 return prep_frame_view_->frame();
1981 const blink::WebNode&
1982 PrintWebViewHelper::PrintPreviewContext::prepared_node() const {
1983 DCHECK_NE(UNINITIALIZED, state_);
1984 return prep_frame_view_->node();
1987 int PrintWebViewHelper::PrintPreviewContext::total_page_count() const {
1988 DCHECK_NE(UNINITIALIZED, state_);
1989 return total_page_count_;
1992 bool PrintWebViewHelper::PrintPreviewContext::generate_draft_pages() const {
1993 return generate_draft_pages_;
1996 PdfMetafileSkia* PrintWebViewHelper::PrintPreviewContext::metafile() {
1997 DCHECK(IsRendering());
1998 return metafile_.get();
2001 int PrintWebViewHelper::PrintPreviewContext::last_error() const {
2002 return error_;
2005 gfx::Size PrintWebViewHelper::PrintPreviewContext::GetPrintCanvasSize() const {
2006 DCHECK(IsRendering());
2007 return prep_frame_view_->GetPrintCanvasSize();
2010 void PrintWebViewHelper::PrintPreviewContext::ClearContext() {
2011 prep_frame_view_.reset();
2012 metafile_.reset();
2013 pages_to_render_.clear();
2014 error_ = PREVIEW_ERROR_NONE;
2017 } // namespace printing