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"
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/WebSandboxFlags.h"
40 #include "third_party/WebKit/public/web/WebScriptSource.h"
41 #include "third_party/WebKit/public/web/WebSettings.h"
42 #include "third_party/WebKit/public/web/WebView.h"
43 #include "third_party/WebKit/public/web/WebViewClient.h"
44 #include "ui/base/l10n/l10n_util.h"
45 #include "ui/base/resource/resource_bundle.h"
47 // This code is copied from chrome/renderer/printing. Code is slightly
48 // modified to run it with webview, and the modifications are marked
50 // TODO(sgurun): remove the code as part of componentization of printing.
52 using content::WebPreferences
;
58 enum PrintPreviewHelperEvents
{
59 PREVIEW_EVENT_REQUESTED
,
60 PREVIEW_EVENT_CACHE_HIT
, // Unused
61 PREVIEW_EVENT_CREATE_DOCUMENT
,
62 PREVIEW_EVENT_NEW_SETTINGS
, // Unused
66 const double kMinDpi
= 1.0;
69 // TODO(sgurun) android_webview hack
70 const char kPageLoadScriptFormat
[] =
71 "document.open(); document.write(%s); document.close();";
73 const char kPageSetupScriptFormat
[] = "setup(%s);";
75 void ExecuteScript(blink::WebFrame
* frame
,
76 const char* script_format
,
77 const base::Value
& parameters
) {
79 base::JSONWriter::Write(¶meters
, &json
);
80 std::string script
= base::StringPrintf(script_format
, json
.c_str());
81 frame
->executeScript(blink::WebString(base::UTF8ToUTF16(script
)));
85 int GetDPI(const PrintMsg_Print_Params
* print_params
) {
86 #if defined(OS_MACOSX)
87 // On the Mac, the printable area is in points, don't do any scaling based
89 return kPointsPerInch
;
91 return static_cast<int>(print_params
->dpi
);
92 #endif // defined(OS_MACOSX)
95 bool PrintMsg_Print_Params_IsValid(const PrintMsg_Print_Params
& params
) {
96 return !params
.content_size
.IsEmpty() && !params
.page_size
.IsEmpty() &&
97 !params
.printable_area
.IsEmpty() && params
.document_cookie
&&
98 params
.desired_dpi
&& params
.max_shrink
&& params
.min_shrink
&&
99 params
.dpi
&& (params
.margin_top
>= 0) && (params
.margin_left
>= 0);
102 PrintMsg_Print_Params
GetCssPrintParams(
103 blink::WebFrame
* frame
,
105 const PrintMsg_Print_Params
& page_params
) {
106 PrintMsg_Print_Params page_css_params
= page_params
;
107 int dpi
= GetDPI(&page_params
);
109 blink::WebSize
page_size_in_pixels(
110 ConvertUnit(page_params
.page_size
.width(), dpi
, kPixelsPerInch
),
111 ConvertUnit(page_params
.page_size
.height(), dpi
, kPixelsPerInch
));
112 int margin_top_in_pixels
=
113 ConvertUnit(page_params
.margin_top
, dpi
, kPixelsPerInch
);
114 int margin_right_in_pixels
= ConvertUnit(
115 page_params
.page_size
.width() -
116 page_params
.content_size
.width() - page_params
.margin_left
,
117 dpi
, kPixelsPerInch
);
118 int margin_bottom_in_pixels
= ConvertUnit(
119 page_params
.page_size
.height() -
120 page_params
.content_size
.height() - page_params
.margin_top
,
121 dpi
, kPixelsPerInch
);
122 int margin_left_in_pixels
= ConvertUnit(
123 page_params
.margin_left
,
124 dpi
, kPixelsPerInch
);
126 blink::WebSize original_page_size_in_pixels
= page_size_in_pixels
;
129 frame
->pageSizeAndMarginsInPixels(page_index
,
131 margin_top_in_pixels
,
132 margin_right_in_pixels
,
133 margin_bottom_in_pixels
,
134 margin_left_in_pixels
);
137 int new_content_width
= page_size_in_pixels
.width
-
138 margin_left_in_pixels
- margin_right_in_pixels
;
139 int new_content_height
= page_size_in_pixels
.height
-
140 margin_top_in_pixels
- margin_bottom_in_pixels
;
142 // Invalid page size and/or margins. We just use the default setting.
143 if (new_content_width
< 1 || new_content_height
< 1) {
145 page_css_params
= GetCssPrintParams(NULL
, page_index
, page_params
);
146 return page_css_params
;
149 page_css_params
.content_size
= gfx::Size(
150 ConvertUnit(new_content_width
, kPixelsPerInch
, dpi
),
151 ConvertUnit(new_content_height
, kPixelsPerInch
, dpi
));
153 if (original_page_size_in_pixels
!= page_size_in_pixels
) {
154 page_css_params
.page_size
= gfx::Size(
155 ConvertUnit(page_size_in_pixels
.width
, kPixelsPerInch
, dpi
),
156 ConvertUnit(page_size_in_pixels
.height
, kPixelsPerInch
, dpi
));
158 // Printing frame doesn't have any page size css. Pixels to dpi conversion
159 // causes rounding off errors. Therefore use the default page size values
161 page_css_params
.page_size
= page_params
.page_size
;
164 page_css_params
.margin_top
=
165 ConvertUnit(margin_top_in_pixels
, kPixelsPerInch
, dpi
);
166 page_css_params
.margin_left
=
167 ConvertUnit(margin_left_in_pixels
, kPixelsPerInch
, dpi
);
168 return page_css_params
;
171 double FitPrintParamsToPage(const PrintMsg_Print_Params
& page_params
,
172 PrintMsg_Print_Params
* params_to_fit
) {
173 double content_width
=
174 static_cast<double>(params_to_fit
->content_size
.width());
175 double content_height
=
176 static_cast<double>(params_to_fit
->content_size
.height());
177 int default_page_size_height
= page_params
.page_size
.height();
178 int default_page_size_width
= page_params
.page_size
.width();
179 int css_page_size_height
= params_to_fit
->page_size
.height();
180 int css_page_size_width
= params_to_fit
->page_size
.width();
182 double scale_factor
= 1.0f
;
183 if (page_params
.page_size
== params_to_fit
->page_size
)
186 if (default_page_size_width
< css_page_size_width
||
187 default_page_size_height
< css_page_size_height
) {
189 static_cast<double>(default_page_size_width
) / css_page_size_width
;
190 double ratio_height
=
191 static_cast<double>(default_page_size_height
) / css_page_size_height
;
192 scale_factor
= ratio_width
< ratio_height
? ratio_width
: ratio_height
;
193 content_width
*= scale_factor
;
194 content_height
*= scale_factor
;
196 params_to_fit
->margin_top
= static_cast<int>(
197 (default_page_size_height
- css_page_size_height
* scale_factor
) / 2 +
198 (params_to_fit
->margin_top
* scale_factor
));
199 params_to_fit
->margin_left
= static_cast<int>(
200 (default_page_size_width
- css_page_size_width
* scale_factor
) / 2 +
201 (params_to_fit
->margin_left
* scale_factor
));
202 params_to_fit
->content_size
= gfx::Size(
203 static_cast<int>(content_width
), static_cast<int>(content_height
));
204 params_to_fit
->page_size
= page_params
.page_size
;
208 void CalculatePageLayoutFromPrintParams(
209 const PrintMsg_Print_Params
& params
,
210 PageSizeMargins
* page_layout_in_points
) {
211 int dpi
= GetDPI(¶ms
);
212 int content_width
= params
.content_size
.width();
213 int content_height
= params
.content_size
.height();
215 int margin_bottom
= params
.page_size
.height() -
216 content_height
- params
.margin_top
;
217 int margin_right
= params
.page_size
.width() -
218 content_width
- params
.margin_left
;
220 page_layout_in_points
->content_width
=
221 ConvertUnit(content_width
, dpi
, kPointsPerInch
);
222 page_layout_in_points
->content_height
=
223 ConvertUnit(content_height
, dpi
, kPointsPerInch
);
224 page_layout_in_points
->margin_top
=
225 ConvertUnit(params
.margin_top
, dpi
, kPointsPerInch
);
226 page_layout_in_points
->margin_right
=
227 ConvertUnit(margin_right
, dpi
, kPointsPerInch
);
228 page_layout_in_points
->margin_bottom
=
229 ConvertUnit(margin_bottom
, dpi
, kPointsPerInch
);
230 page_layout_in_points
->margin_left
=
231 ConvertUnit(params
.margin_left
, dpi
, kPointsPerInch
);
234 void EnsureOrientationMatches(const PrintMsg_Print_Params
& css_params
,
235 PrintMsg_Print_Params
* page_params
) {
236 if ((page_params
->page_size
.width() > page_params
->page_size
.height()) ==
237 (css_params
.page_size
.width() > css_params
.page_size
.height())) {
241 // Swap the |width| and |height| values.
242 page_params
->page_size
.SetSize(page_params
->page_size
.height(),
243 page_params
->page_size
.width());
244 page_params
->content_size
.SetSize(page_params
->content_size
.height(),
245 page_params
->content_size
.width());
246 page_params
->printable_area
.set_size(
247 gfx::Size(page_params
->printable_area
.height(),
248 page_params
->printable_area
.width()));
251 void ComputeWebKitPrintParamsInDesiredDpi(
252 const PrintMsg_Print_Params
& print_params
,
253 blink::WebPrintParams
* webkit_print_params
) {
254 int dpi
= GetDPI(&print_params
);
255 webkit_print_params
->printerDPI
= dpi
;
256 webkit_print_params
->printScalingOption
= print_params
.print_scaling_option
;
258 webkit_print_params
->printContentArea
.width
=
259 ConvertUnit(print_params
.content_size
.width(), dpi
,
260 print_params
.desired_dpi
);
261 webkit_print_params
->printContentArea
.height
=
262 ConvertUnit(print_params
.content_size
.height(), dpi
,
263 print_params
.desired_dpi
);
265 webkit_print_params
->printableArea
.x
=
266 ConvertUnit(print_params
.printable_area
.x(), dpi
,
267 print_params
.desired_dpi
);
268 webkit_print_params
->printableArea
.y
=
269 ConvertUnit(print_params
.printable_area
.y(), dpi
,
270 print_params
.desired_dpi
);
271 webkit_print_params
->printableArea
.width
=
272 ConvertUnit(print_params
.printable_area
.width(), dpi
,
273 print_params
.desired_dpi
);
274 webkit_print_params
->printableArea
.height
=
275 ConvertUnit(print_params
.printable_area
.height(),
276 dpi
, print_params
.desired_dpi
);
278 webkit_print_params
->paperSize
.width
=
279 ConvertUnit(print_params
.page_size
.width(), dpi
,
280 print_params
.desired_dpi
);
281 webkit_print_params
->paperSize
.height
=
282 ConvertUnit(print_params
.page_size
.height(), dpi
,
283 print_params
.desired_dpi
);
286 blink::WebPlugin
* GetPlugin(const blink::WebFrame
* frame
) {
287 return frame
->document().isPluginDocument() ?
288 frame
->document().to
<blink::WebPluginDocument
>().plugin() : NULL
;
291 bool PrintingNodeOrPdfFrame(const blink::WebFrame
* frame
,
292 const blink::WebNode
& node
) {
295 blink::WebPlugin
* plugin
= GetPlugin(frame
);
296 return plugin
&& plugin
->supportsPaginatedPrint();
299 bool PrintingFrameHasPageSizeStyle(blink::WebFrame
* frame
,
300 int total_page_count
) {
303 bool frame_has_custom_page_size_style
= false;
304 for (int i
= 0; i
< total_page_count
; ++i
) {
305 if (frame
->hasCustomPageSizeStyle(i
)) {
306 frame_has_custom_page_size_style
= true;
310 return frame_has_custom_page_size_style
;
313 MarginType
GetMarginsForPdf(blink::WebFrame
* frame
,
314 const blink::WebNode
& node
) {
315 if (frame
->isPrintScalingDisabledForPlugin(node
))
318 return PRINTABLE_AREA_MARGINS
;
321 bool FitToPageEnabled(const base::DictionaryValue
& job_settings
) {
322 bool fit_to_paper_size
= false;
323 if (!job_settings
.GetBoolean(kSettingFitToPageEnabled
, &fit_to_paper_size
)) {
326 return fit_to_paper_size
;
329 PrintMsg_Print_Params
CalculatePrintParamsForCss(
330 blink::WebFrame
* frame
,
332 const PrintMsg_Print_Params
& page_params
,
333 bool ignore_css_margins
,
335 double* scale_factor
) {
336 PrintMsg_Print_Params css_params
= GetCssPrintParams(frame
, page_index
,
339 PrintMsg_Print_Params params
= page_params
;
340 EnsureOrientationMatches(css_params
, ¶ms
);
342 if (ignore_css_margins
&& fit_to_page
)
345 PrintMsg_Print_Params result_params
= css_params
;
346 if (ignore_css_margins
) {
347 result_params
.margin_top
= params
.margin_top
;
348 result_params
.margin_left
= params
.margin_left
;
350 DCHECK(!fit_to_page
);
351 // Since we are ignoring the margins, the css page size is no longer
353 int default_margin_right
= params
.page_size
.width() -
354 params
.content_size
.width() - params
.margin_left
;
355 int default_margin_bottom
= params
.page_size
.height() -
356 params
.content_size
.height() - params
.margin_top
;
357 result_params
.content_size
= gfx::Size(
358 result_params
.page_size
.width() - result_params
.margin_left
-
359 default_margin_right
,
360 result_params
.page_size
.height() - result_params
.margin_top
-
361 default_margin_bottom
);
365 double factor
= FitPrintParamsToPage(params
, &result_params
);
367 *scale_factor
= factor
;
369 return result_params
;
372 bool IsPrintPreviewEnabled() {
376 bool IsPrintThrottlingDisabled() {
382 FrameReference::FrameReference(blink::WebLocalFrame
* frame
) {
386 FrameReference::FrameReference() {
390 FrameReference::~FrameReference() {
393 void FrameReference::Reset(blink::WebLocalFrame
* frame
) {
395 view_
= frame
->view();
403 blink::WebLocalFrame
* FrameReference::GetFrame() {
404 if (view_
== NULL
|| frame_
== NULL
)
406 for (blink::WebFrame
* frame
= view_
->mainFrame(); frame
!= NULL
;
407 frame
= frame
->traverseNext(false)) {
414 blink::WebView
* FrameReference::view() {
418 // static - Not anonymous so that platform implementations can use it.
419 void PrintWebViewHelper::PrintHeaderAndFooter(
420 blink::WebCanvas
* canvas
,
423 float webkit_scale_factor
,
424 const PageSizeMargins
& page_layout
,
425 const base::DictionaryValue
& header_footer_info
,
426 const PrintMsg_Print_Params
& params
) {
428 // TODO(sgurun) android_webview hack
429 SkAutoCanvasRestore
auto_restore(canvas
, true);
430 canvas
->scale(1 / webkit_scale_factor
, 1 / webkit_scale_factor
);
432 blink::WebSize
page_size(page_layout
.margin_left
+ page_layout
.margin_right
+
433 page_layout
.content_width
,
434 page_layout
.margin_top
+ page_layout
.margin_bottom
+
435 page_layout
.content_height
);
437 blink::WebView
* web_view
= blink::WebView::create(NULL
);
438 web_view
->settings()->setJavaScriptEnabled(true);
439 blink::WebFrame
* frame
= blink::WebLocalFrame::create(NULL
)
440 web_view
->setMainFrame(web_frame
);
442 base::StringValue
html(
443 ResourceBundle::GetSharedInstance().GetLocalizedString(
444 IDR_PRINT_PREVIEW_PAGE
));
445 // Load page with script to avoid async operations.
446 ExecuteScript(frame
, kPageLoadScriptFormat
, html
);
448 scoped_ptr
<base::DictionaryValue
> options(header_footer_info
.DeepCopy());
449 options
->SetDouble("width", page_size
.width
);
450 options
->SetDouble("height", page_size
.height
);
451 options
->SetDouble("topMargin", page_layout
.margin_top
);
452 options
->SetDouble("bottomMargin", page_layout
.margin_bottom
);
453 options
->SetString("pageNumber",
454 base::StringPrintf("%d/%d", page_number
, total_pages
));
456 ExecuteScript(frame
, kPageSetupScriptFormat
, *options
);
458 blink::WebPrintParams
webkit_params(page_size
);
459 webkit_params
.printerDPI
= GetDPI(¶ms
);
461 frame
->printBegin(webkit_params
, WebKit::WebNode(), NULL
);
462 frame
->printPage(0, canvas
);
470 // static - Not anonymous so that platform implementations can use it.
471 float PrintWebViewHelper::RenderPageContent(blink::WebFrame
* frame
,
473 const gfx::Rect
& canvas_area
,
474 const gfx::Rect
& content_area
,
476 blink::WebCanvas
* canvas
) {
477 SkAutoCanvasRestore
auto_restore(canvas
, true);
478 if (content_area
!= canvas_area
) {
479 canvas
->translate((content_area
.x() - canvas_area
.x()) / scale_factor
,
480 (content_area
.y() - canvas_area
.y()) / scale_factor
);
482 SkRect::MakeXYWH(content_area
.origin().x() / scale_factor
,
483 content_area
.origin().y() / scale_factor
,
484 content_area
.size().width() / scale_factor
,
485 content_area
.size().height() / scale_factor
));
486 SkIRect clip_int_rect
;
487 clip_rect
.roundOut(&clip_int_rect
);
488 SkRegion
clip_region(clip_int_rect
);
489 canvas
->setClipRegion(clip_region
);
491 return frame
->printPage(page_number
, canvas
);
494 // Class that calls the Begin and End print functions on the frame and changes
495 // the size of the view temporarily to support full page printing..
496 class PrepareFrameAndViewForPrint
: public blink::WebViewClient
,
497 public blink::WebFrameClient
{
499 PrepareFrameAndViewForPrint(const PrintMsg_Print_Params
& params
,
500 blink::WebLocalFrame
* frame
,
501 const blink::WebNode
& node
,
502 bool ignore_css_margins
);
503 virtual ~PrepareFrameAndViewForPrint();
505 // Optional. Replaces |frame_| with selection if needed. Will call |on_ready|
507 void CopySelectionIfNeeded(const WebPreferences
& preferences
,
508 const base::Closure
& on_ready
);
510 // Prepares frame for printing.
511 void StartPrinting();
513 blink::WebLocalFrame
* frame() {
514 return frame_
.GetFrame();
517 const blink::WebNode
& node() const {
518 return node_to_print_
;
521 int GetExpectedPageCount() const {
522 return expected_pages_count_
;
525 gfx::Size
GetPrintCanvasSize() const;
527 void FinishPrinting();
529 bool IsLoadingSelection() {
530 // It's not selection if not |owns_web_view_|.
531 return owns_web_view_
&& frame() && frame()->isLoading();
534 // TODO(ojan): Remove this override and have this class use a non-null
536 // blink::WebViewClient override:
537 virtual bool allowsBrokenNullLayerTreeView() const;
540 // blink::WebViewClient override:
541 virtual void didStopLoading();
543 // blink::WebFrameClient override:
544 virtual blink::WebFrame
* createChildFrame(
545 blink::WebLocalFrame
* parent
,
546 const blink::WebString
& name
,
547 blink::WebSandboxFlags sandboxFlags
);
548 virtual void frameDetached(blink::WebFrame
* frame
);
552 void ResizeForPrinting();
554 void CopySelection(const WebPreferences
& preferences
);
556 FrameReference frame_
;
557 blink::WebNode node_to_print_
;
559 blink::WebPrintParams web_print_params_
;
560 gfx::Size prev_view_size_
;
561 gfx::Size prev_scroll_offset_
;
562 int expected_pages_count_
;
563 base::Closure on_ready_
;
564 bool should_print_backgrounds_
;
565 bool should_print_selection_only_
;
566 bool is_printing_started_
;
568 base::WeakPtrFactory
<PrepareFrameAndViewForPrint
> weak_ptr_factory_
;
570 DISALLOW_COPY_AND_ASSIGN(PrepareFrameAndViewForPrint
);
573 PrepareFrameAndViewForPrint::PrepareFrameAndViewForPrint(
574 const PrintMsg_Print_Params
& params
,
575 blink::WebLocalFrame
* frame
,
576 const blink::WebNode
& node
,
577 bool ignore_css_margins
)
579 node_to_print_(node
),
580 owns_web_view_(false),
581 expected_pages_count_(0),
582 should_print_backgrounds_(params
.should_print_backgrounds
),
583 should_print_selection_only_(params
.selection_only
),
584 is_printing_started_(false),
585 weak_ptr_factory_(this) {
586 PrintMsg_Print_Params print_params
= params
;
587 if (!should_print_selection_only_
||
588 !PrintingNodeOrPdfFrame(frame
, node_to_print_
)) {
589 bool fit_to_page
= ignore_css_margins
&&
590 print_params
.print_scaling_option
==
591 blink::WebPrintScalingOptionFitToPrintableArea
;
592 ComputeWebKitPrintParamsInDesiredDpi(params
, &web_print_params_
);
593 frame
->printBegin(web_print_params_
, node_to_print_
);
594 print_params
= CalculatePrintParamsForCss(frame
, 0, print_params
,
595 ignore_css_margins
, fit_to_page
,
599 ComputeWebKitPrintParamsInDesiredDpi(print_params
, &web_print_params_
);
602 PrepareFrameAndViewForPrint::~PrepareFrameAndViewForPrint() {
606 void PrepareFrameAndViewForPrint::ResizeForPrinting() {
607 // Layout page according to printer page size. Since WebKit shrinks the
608 // size of the page automatically (from 125% to 200%) we trick it to
609 // think the page is 125% larger so the size of the page is correct for
610 // minimum (default) scaling.
611 // This is important for sites that try to fill the page.
612 gfx::Size
print_layout_size(web_print_params_
.printContentArea
.width
,
613 web_print_params_
.printContentArea
.height
);
614 print_layout_size
.set_height(
615 static_cast<int>(static_cast<double>(print_layout_size
.height()) * 1.25));
619 blink::WebView
* web_view
= frame_
.view();
620 // Backup size and offset.
621 if (blink::WebFrame
* web_frame
= web_view
->mainFrame())
622 prev_scroll_offset_
= web_frame
->scrollOffset();
623 prev_view_size_
= web_view
->size();
625 web_view
->resize(print_layout_size
);
629 void PrepareFrameAndViewForPrint::StartPrinting() {
631 blink::WebView
* web_view
= frame_
.view();
632 web_view
->settings()->setShouldPrintBackgrounds(should_print_backgrounds_
);
633 expected_pages_count_
=
634 frame()->printBegin(web_print_params_
, node_to_print_
);
635 is_printing_started_
= true;
638 void PrepareFrameAndViewForPrint::CopySelectionIfNeeded(
639 const WebPreferences
& preferences
,
640 const base::Closure
& on_ready
) {
641 on_ready_
= on_ready
;
642 if (should_print_selection_only_
)
643 CopySelection(preferences
);
648 void PrepareFrameAndViewForPrint::CopySelection(
649 const WebPreferences
& preferences
) {
651 std::string url_str
= "data:text/html;charset=utf-8,";
653 net::EscapeQueryParamValue(frame()->selectionAsMarkup().utf8(), false));
655 // Create a new WebView with the same settings as the current display one.
656 // Except that we disable javascript (don't want any active content running
658 WebPreferences prefs
= preferences
;
659 prefs
.javascript_enabled
= false;
660 prefs
.java_enabled
= false;
662 blink::WebView
* web_view
= blink::WebView::create(this);
663 owns_web_view_
= true;
664 content::RenderView::ApplyWebPreferences(prefs
, web_view
);
665 web_view
->setMainFrame(blink::WebLocalFrame::create(this));
666 frame_
.Reset(web_view
->mainFrame()->toWebLocalFrame());
667 node_to_print_
.reset();
669 // When loading is done this will call didStopLoading() and that will do the
671 frame()->loadRequest(blink::WebURLRequest(GURL(url_str
)));
674 bool PrepareFrameAndViewForPrint::allowsBrokenNullLayerTreeView() const {
678 void PrepareFrameAndViewForPrint::didStopLoading() {
679 DCHECK(!on_ready_
.is_null());
680 // Don't call callback here, because it can delete |this| and WebView that is
681 // called didStopLoading.
682 base::MessageLoop::current()->PostTask(
684 base::Bind(&PrepareFrameAndViewForPrint::CallOnReady
,
685 weak_ptr_factory_
.GetWeakPtr()));
688 blink::WebFrame
* PrepareFrameAndViewForPrint::createChildFrame(
689 blink::WebLocalFrame
* parent
,
690 const blink::WebString
& name
,
691 blink::WebSandboxFlags sandboxFlags
) {
692 blink::WebFrame
* frame
= blink::WebLocalFrame::create(this);
693 parent
->appendChild(frame
);
697 void PrepareFrameAndViewForPrint::frameDetached(blink::WebFrame
* frame
) {
699 frame
->parent()->removeChild(frame
);
703 void PrepareFrameAndViewForPrint::CallOnReady() {
704 return on_ready_
.Run(); // Can delete |this|.
707 gfx::Size
PrepareFrameAndViewForPrint::GetPrintCanvasSize() const {
708 DCHECK(is_printing_started_
);
709 return gfx::Size(web_print_params_
.printContentArea
.width
,
710 web_print_params_
.printContentArea
.height
);
713 void PrepareFrameAndViewForPrint::RestoreSize() {
715 blink::WebView
* web_view
= frame_
.GetFrame()->view();
716 web_view
->resize(prev_view_size_
);
717 if (blink::WebFrame
* web_frame
= web_view
->mainFrame())
718 web_frame
->setScrollOffset(prev_scroll_offset_
);
722 void PrepareFrameAndViewForPrint::FinishPrinting() {
723 blink::WebLocalFrame
* frame
= frame_
.GetFrame();
725 blink::WebView
* web_view
= frame
->view();
726 if (is_printing_started_
) {
727 is_printing_started_
= false;
729 if (!owns_web_view_
) {
730 web_view
->settings()->setShouldPrintBackgrounds(false);
734 if (owns_web_view_
) {
735 DCHECK(!frame
->isLoading());
736 owns_web_view_
= false;
744 PrintWebViewHelper::PrintWebViewHelper(content::RenderView
* render_view
)
745 : content::RenderViewObserver(render_view
),
746 content::RenderViewObserverTracker
<PrintWebViewHelper
>(render_view
),
747 reset_prep_frame_view_(false),
748 is_preview_enabled_(IsPrintPreviewEnabled()),
749 is_scripted_print_throttling_disabled_(IsPrintThrottlingDisabled()),
750 is_print_ready_metafile_sent_(false),
751 ignore_css_margins_(false),
752 user_cancelled_scripted_print_count_(0),
753 is_scripted_printing_blocked_(false),
754 notify_browser_of_print_failure_(true),
755 print_for_preview_(false),
756 print_node_in_progress_(false),
758 is_scripted_preview_delayed_(false),
759 weak_ptr_factory_(this) {
760 // TODO(sgurun) enable window.print() for webview crbug.com/322303
761 SetScriptedPrintBlocked(true);
764 PrintWebViewHelper::~PrintWebViewHelper() {}
766 bool PrintWebViewHelper::IsScriptInitiatedPrintAllowed(
767 blink::WebFrame
* frame
, bool user_initiated
) {
768 #if defined(OS_ANDROID)
770 #endif // defined(OS_ANDROID)
771 if (is_scripted_printing_blocked_
)
773 // If preview is enabled, then the print dialog is tab modal, and the user
774 // can always close the tab on a mis-behaving page (the system print dialog
775 // is app modal). If the print was initiated through user action, don't
776 // throttle. Or, if the command line flag to skip throttling has been set.
777 if (!is_scripted_print_throttling_disabled_
&&
778 !is_preview_enabled_
&&
780 return !IsScriptInitiatedPrintTooFrequent(frame
);
784 void PrintWebViewHelper::DidStartLoading() {
788 void PrintWebViewHelper::DidStopLoading() {
790 ShowScriptedPrintPreview();
793 // Prints |frame| which called window.print().
794 void PrintWebViewHelper::PrintPage(blink::WebLocalFrame
* frame
,
795 bool user_initiated
) {
798 #if !defined(OS_ANDROID)
799 // TODO(sgurun) android_webview hack
800 // Allow Prerendering to cancel this print request if necessary.
801 if (prerender::PrerenderHelper::IsPrerendering(render_view())) {
802 Send(new ChromeViewHostMsg_CancelPrerenderForPrinting(routing_id()));
805 #endif // !defined(OS_ANDROID)
807 if (!IsScriptInitiatedPrintAllowed(frame
, user_initiated
))
809 IncrementScriptedPrintCount();
811 if (is_preview_enabled_
) {
812 print_preview_context_
.InitWithFrame(frame
);
813 RequestPrintPreview(PRINT_PREVIEW_SCRIPTED
);
815 Print(frame
, blink::WebNode());
819 bool PrintWebViewHelper::OnMessageReceived(const IPC::Message
& message
) {
821 IPC_BEGIN_MESSAGE_MAP(PrintWebViewHelper
, message
)
822 IPC_MESSAGE_HANDLER(PrintMsg_PrintPages
, OnPrintPages
)
823 IPC_MESSAGE_HANDLER(PrintMsg_PrintForSystemDialog
, OnPrintForSystemDialog
)
824 IPC_MESSAGE_HANDLER(PrintMsg_InitiatePrintPreview
, OnInitiatePrintPreview
)
825 IPC_MESSAGE_HANDLER(PrintMsg_PrintPreview
, OnPrintPreview
)
826 IPC_MESSAGE_HANDLER(PrintMsg_PrintForPrintPreview
, OnPrintForPrintPreview
)
827 IPC_MESSAGE_HANDLER(PrintMsg_PrintingDone
, OnPrintingDone
)
828 IPC_MESSAGE_HANDLER(PrintMsg_ResetScriptedPrintCount
,
829 ResetScriptedPrintCount
)
830 IPC_MESSAGE_HANDLER(PrintMsg_SetScriptedPrintingBlocked
,
831 SetScriptedPrintBlocked
)
832 IPC_MESSAGE_UNHANDLED(handled
= false)
833 IPC_END_MESSAGE_MAP()
837 void PrintWebViewHelper::OnPrintForPrintPreview(
838 const base::DictionaryValue
& job_settings
) {
839 DCHECK(is_preview_enabled_
);
840 // If still not finished with earlier print request simply ignore.
841 if (prep_frame_view_
)
844 if (!render_view()->GetWebView())
846 blink::WebFrame
* main_frame
= render_view()->GetWebView()->mainFrame();
850 blink::WebDocument document
= main_frame
->document();
851 // <object> with id="pdf-viewer" is created in
852 // chrome/browser/resources/print_preview/print_preview.js
853 blink::WebElement pdf_element
= document
.getElementById("pdf-viewer");
854 if (pdf_element
.isNull()) {
859 // Set |print_for_preview_| flag and autoreset it to back to original
861 base::AutoReset
<bool> set_printing_flag(&print_for_preview_
, true);
863 blink::WebLocalFrame
* pdf_frame
= pdf_element
.document().frame();
864 if (!UpdatePrintSettings(pdf_frame
, pdf_element
, job_settings
)) {
865 LOG(ERROR
) << "UpdatePrintSettings failed";
866 DidFinishPrinting(FAIL_PRINT
);
870 // Print page onto entire page not just printable area. Preview PDF already
871 // has content in correct position taking into account page size and printable
873 // TODO(vitalybuka) : Make this consistent on all platform. This change
874 // affects Windows only. On Linux and OSX RenderPagesForPrint does not use
875 // printable_area. Also we can't change printable_area deeper inside
876 // RenderPagesForPrint for Windows, because it's used also by native
877 // printing and it expects real printable_area value.
878 // See http://crbug.com/123408
879 PrintMsg_Print_Params
& print_params
= print_pages_params_
->params
;
880 print_params
.printable_area
= gfx::Rect(print_params
.page_size
);
882 // Render Pages for printing.
883 if (!RenderPagesForPrint(pdf_frame
, pdf_element
)) {
884 LOG(ERROR
) << "RenderPagesForPrint failed";
885 DidFinishPrinting(FAIL_PRINT
);
889 bool PrintWebViewHelper::GetPrintFrame(blink::WebLocalFrame
** frame
) {
891 blink::WebView
* webView
= render_view()->GetWebView();
896 // If the user has selected text in the currently focused frame we print
897 // only that frame (this makes print selection work for multiple frames).
898 blink::WebLocalFrame
* focusedFrame
=
899 webView
->focusedFrame()->toWebLocalFrame();
900 *frame
= focusedFrame
->hasSelection()
902 : webView
->mainFrame()->toWebLocalFrame();
906 void PrintWebViewHelper::OnPrintPages() {
907 blink::WebLocalFrame
* frame
;
908 if (GetPrintFrame(&frame
))
909 Print(frame
, blink::WebNode());
912 void PrintWebViewHelper::OnPrintForSystemDialog() {
913 blink::WebLocalFrame
* frame
= print_preview_context_
.source_frame();
919 Print(frame
, print_preview_context_
.source_node());
922 void PrintWebViewHelper::GetPageSizeAndContentAreaFromPageLayout(
923 const PageSizeMargins
& page_layout_in_points
,
924 gfx::Size
* page_size
,
925 gfx::Rect
* content_area
) {
926 *page_size
= gfx::Size(
927 page_layout_in_points
.content_width
+
928 page_layout_in_points
.margin_right
+
929 page_layout_in_points
.margin_left
,
930 page_layout_in_points
.content_height
+
931 page_layout_in_points
.margin_top
+
932 page_layout_in_points
.margin_bottom
);
933 *content_area
= gfx::Rect(page_layout_in_points
.margin_left
,
934 page_layout_in_points
.margin_top
,
935 page_layout_in_points
.content_width
,
936 page_layout_in_points
.content_height
);
939 void PrintWebViewHelper::UpdateFrameMarginsCssInfo(
940 const base::DictionaryValue
& settings
) {
941 int margins_type
= 0;
942 if (!settings
.GetInteger(kSettingMarginsType
, &margins_type
))
943 margins_type
= DEFAULT_MARGINS
;
944 ignore_css_margins_
= (margins_type
!= DEFAULT_MARGINS
);
947 bool PrintWebViewHelper::IsPrintToPdfRequested(
948 const base::DictionaryValue
& job_settings
) {
949 bool print_to_pdf
= false;
950 if (!job_settings
.GetBoolean(kSettingPrintToPDF
, &print_to_pdf
))
955 blink::WebPrintScalingOption
PrintWebViewHelper::GetPrintScalingOption(
956 bool source_is_html
, const base::DictionaryValue
& job_settings
,
957 const PrintMsg_Print_Params
& params
) {
958 DCHECK(!print_for_preview_
);
960 if (params
.print_to_pdf
)
961 return blink::WebPrintScalingOptionSourceSize
;
963 if (!source_is_html
) {
964 if (!FitToPageEnabled(job_settings
))
965 return blink::WebPrintScalingOptionNone
;
967 bool no_plugin_scaling
=
968 print_preview_context_
.source_frame()->isPrintScalingDisabledForPlugin(
969 print_preview_context_
.source_node());
971 if (params
.is_first_request
&& no_plugin_scaling
)
972 return blink::WebPrintScalingOptionNone
;
974 return blink::WebPrintScalingOptionFitToPrintableArea
;
977 void PrintWebViewHelper::OnPrintPreview(const base::DictionaryValue
& settings
) {
978 DCHECK(is_preview_enabled_
);
979 print_preview_context_
.OnPrintPreview();
981 UMA_HISTOGRAM_ENUMERATION("PrintPreview.PreviewEvent",
982 PREVIEW_EVENT_REQUESTED
, PREVIEW_EVENT_MAX
);
984 if (!UpdatePrintSettings(print_preview_context_
.source_frame(),
985 print_preview_context_
.source_node(), settings
)) {
986 if (print_preview_context_
.last_error() != PREVIEW_ERROR_BAD_SETTING
) {
987 Send(new PrintHostMsg_PrintPreviewInvalidPrinterSettings(
988 routing_id(), print_pages_params_
->params
.document_cookie
));
989 notify_browser_of_print_failure_
= false; // Already sent.
991 DidFinishPrinting(FAIL_PREVIEW
);
995 // If we are previewing a pdf and the print scaling is disabled, send a
996 // message to browser.
997 if (print_pages_params_
->params
.is_first_request
&&
998 !print_preview_context_
.IsModifiable() &&
999 print_preview_context_
.source_frame()->isPrintScalingDisabledForPlugin(
1000 print_preview_context_
.source_node())) {
1001 Send(new PrintHostMsg_PrintPreviewScalingDisabled(routing_id()));
1004 is_print_ready_metafile_sent_
= false;
1006 // PDF printer device supports alpha blending.
1007 print_pages_params_
->params
.supports_alpha_blend
= true;
1009 bool generate_draft_pages
= false;
1010 if (!settings
.GetBoolean(kSettingGenerateDraftData
,
1011 &generate_draft_pages
)) {
1014 print_preview_context_
.set_generate_draft_pages(generate_draft_pages
);
1016 PrepareFrameForPreviewDocument();
1019 void PrintWebViewHelper::PrepareFrameForPreviewDocument() {
1020 reset_prep_frame_view_
= false;
1022 if (!print_pages_params_
|| CheckForCancel()) {
1023 DidFinishPrinting(FAIL_PREVIEW
);
1027 // Don't reset loading frame or WebKit will fail assert. Just retry when
1028 // current selection is loaded.
1029 if (prep_frame_view_
&& prep_frame_view_
->IsLoadingSelection()) {
1030 reset_prep_frame_view_
= true;
1034 const PrintMsg_Print_Params
& print_params
= print_pages_params_
->params
;
1035 prep_frame_view_
.reset(
1036 new PrepareFrameAndViewForPrint(print_params
,
1037 print_preview_context_
.source_frame(),
1038 print_preview_context_
.source_node(),
1039 ignore_css_margins_
));
1040 prep_frame_view_
->CopySelectionIfNeeded(
1041 render_view()->GetWebkitPreferences(),
1042 base::Bind(&PrintWebViewHelper::OnFramePreparedForPreviewDocument
,
1043 base::Unretained(this)));
1046 void PrintWebViewHelper::OnFramePreparedForPreviewDocument() {
1047 if (reset_prep_frame_view_
) {
1048 PrepareFrameForPreviewDocument();
1051 DidFinishPrinting(CreatePreviewDocument() ? OK
: FAIL_PREVIEW
);
1054 bool PrintWebViewHelper::CreatePreviewDocument() {
1055 if (!print_pages_params_
|| CheckForCancel())
1058 UMA_HISTOGRAM_ENUMERATION("PrintPreview.PreviewEvent",
1059 PREVIEW_EVENT_CREATE_DOCUMENT
, PREVIEW_EVENT_MAX
);
1061 const PrintMsg_Print_Params
& print_params
= print_pages_params_
->params
;
1062 const std::vector
<int>& pages
= print_pages_params_
->pages
;
1064 if (!print_preview_context_
.CreatePreviewDocument(prep_frame_view_
.release(),
1069 PageSizeMargins default_page_layout
;
1070 ComputePageLayoutInPointsForCss(print_preview_context_
.prepared_frame(), 0,
1071 print_params
, ignore_css_margins_
, NULL
,
1072 &default_page_layout
);
1074 bool has_page_size_style
= PrintingFrameHasPageSizeStyle(
1075 print_preview_context_
.prepared_frame(),
1076 print_preview_context_
.total_page_count());
1077 int dpi
= GetDPI(&print_params
);
1079 gfx::Rect
printable_area_in_points(
1080 ConvertUnit(print_params
.printable_area
.x(), dpi
, kPointsPerInch
),
1081 ConvertUnit(print_params
.printable_area
.y(), dpi
, kPointsPerInch
),
1082 ConvertUnit(print_params
.printable_area
.width(), dpi
, kPointsPerInch
),
1083 ConvertUnit(print_params
.printable_area
.height(), dpi
, kPointsPerInch
));
1085 // Margins: Send default page layout to browser process.
1086 Send(new PrintHostMsg_DidGetDefaultPageLayout(routing_id(),
1087 default_page_layout
,
1088 printable_area_in_points
,
1089 has_page_size_style
));
1091 PrintHostMsg_DidGetPreviewPageCount_Params params
;
1092 params
.page_count
= print_preview_context_
.total_page_count();
1093 params
.is_modifiable
= print_preview_context_
.IsModifiable();
1094 params
.document_cookie
= print_params
.document_cookie
;
1095 params
.preview_request_id
= print_params
.preview_request_id
;
1096 params
.clear_preview_data
= print_preview_context_
.generate_draft_pages();
1097 Send(new PrintHostMsg_DidGetPreviewPageCount(routing_id(), params
));
1098 if (CheckForCancel())
1101 while (!print_preview_context_
.IsFinalPageRendered()) {
1102 int page_number
= print_preview_context_
.GetNextPageNumber();
1103 DCHECK_GE(page_number
, 0);
1104 if (!RenderPreviewPage(page_number
, print_params
))
1107 if (CheckForCancel())
1110 // We must call PrepareFrameAndViewForPrint::FinishPrinting() (by way of
1111 // print_preview_context_.AllPagesRendered()) before calling
1112 // FinalizePrintReadyDocument() when printing a PDF because the plugin
1113 // code does not generate output until we call FinishPrinting(). We do not
1114 // generate draft pages for PDFs, so IsFinalPageRendered() and
1115 // IsLastPageOfPrintReadyMetafile() will be true in the same iteration of
1117 if (print_preview_context_
.IsFinalPageRendered())
1118 print_preview_context_
.AllPagesRendered();
1120 if (print_preview_context_
.IsLastPageOfPrintReadyMetafile()) {
1121 DCHECK(print_preview_context_
.IsModifiable() ||
1122 print_preview_context_
.IsFinalPageRendered());
1123 if (!FinalizePrintReadyDocument())
1127 print_preview_context_
.Finished();
1131 bool PrintWebViewHelper::FinalizePrintReadyDocument() {
1132 DCHECK(!is_print_ready_metafile_sent_
);
1133 print_preview_context_
.FinalizePrintReadyDocument();
1135 // Get the size of the resulting metafile.
1136 PdfMetafileSkia
* metafile
= print_preview_context_
.metafile();
1137 uint32 buf_size
= metafile
->GetDataSize();
1138 DCHECK_GT(buf_size
, 0u);
1140 PrintHostMsg_DidPreviewDocument_Params preview_params
;
1141 preview_params
.reuse_existing_data
= false;
1142 preview_params
.data_size
= buf_size
;
1143 preview_params
.document_cookie
= print_pages_params_
->params
.document_cookie
;
1144 preview_params
.expected_pages_count
=
1145 print_preview_context_
.total_page_count();
1146 preview_params
.modifiable
= print_preview_context_
.IsModifiable();
1147 preview_params
.preview_request_id
=
1148 print_pages_params_
->params
.preview_request_id
;
1150 // Ask the browser to create the shared memory for us.
1151 if (!CopyMetafileDataToSharedMem(metafile
,
1152 &(preview_params
.metafile_data_handle
))) {
1153 LOG(ERROR
) << "CopyMetafileDataToSharedMem failed";
1154 print_preview_context_
.set_error(PREVIEW_ERROR_METAFILE_COPY_FAILED
);
1157 is_print_ready_metafile_sent_
= true;
1159 Send(new PrintHostMsg_MetafileReadyForPrinting(routing_id(), preview_params
));
1163 void PrintWebViewHelper::OnPrintingDone(bool success
) {
1164 notify_browser_of_print_failure_
= false;
1166 LOG(ERROR
) << "Failure in OnPrintingDone";
1167 DidFinishPrinting(success
? OK
: FAIL_PRINT
);
1170 void PrintWebViewHelper::SetScriptedPrintBlocked(bool blocked
) {
1171 is_scripted_printing_blocked_
= blocked
;
1174 void PrintWebViewHelper::OnInitiatePrintPreview(bool selection_only
) {
1175 DCHECK(is_preview_enabled_
);
1176 blink::WebLocalFrame
* frame
= NULL
;
1177 GetPrintFrame(&frame
);
1179 print_preview_context_
.InitWithFrame(frame
);
1180 RequestPrintPreview(selection_only
?
1181 PRINT_PREVIEW_USER_INITIATED_SELECTION
:
1182 PRINT_PREVIEW_USER_INITIATED_ENTIRE_FRAME
);
1185 bool PrintWebViewHelper::IsPrintingEnabled() {
1186 bool result
= false;
1187 Send(new PrintHostMsg_IsPrintingEnabled(routing_id(), &result
));
1191 void PrintWebViewHelper::PrintNode(const blink::WebNode
& node
) {
1192 if (node
.isNull() || !node
.document().frame()) {
1193 // This can occur when the context menu refers to an invalid WebNode.
1194 // See http://crbug.com/100890#c17 for a repro case.
1198 if (print_node_in_progress_
) {
1199 // This can happen as a result of processing sync messages when printing
1200 // from ppapi plugins. It's a rare case, so its OK to just fail here.
1201 // See http://crbug.com/159165.
1205 print_node_in_progress_
= true;
1207 // Make a copy of the node, in case RenderView::OnContextMenuClosed resets
1208 // its |context_menu_node_|.
1209 if (is_preview_enabled_
) {
1210 print_preview_context_
.InitWithNode(node
);
1211 RequestPrintPreview(PRINT_PREVIEW_USER_INITIATED_CONTEXT_NODE
);
1213 blink::WebNode
duplicate_node(node
);
1214 Print(duplicate_node
.document().frame(), duplicate_node
);
1217 print_node_in_progress_
= false;
1220 void PrintWebViewHelper::Print(blink::WebLocalFrame
* frame
,
1221 const blink::WebNode
& node
) {
1222 // If still not finished with earlier print request simply ignore.
1223 if (prep_frame_view_
)
1226 FrameReference
frame_ref(frame
);
1228 int expected_page_count
= 0;
1229 if (!CalculateNumberOfPages(frame
, node
, &expected_page_count
)) {
1230 DidFinishPrinting(FAIL_PRINT_INIT
);
1231 return; // Failed to init print page settings.
1234 // Some full screen plugins can say they don't want to print.
1235 if (!expected_page_count
) {
1236 DidFinishPrinting(FAIL_PRINT
);
1240 #if !defined(OS_ANDROID)
1241 // TODO(sgurun) android_webview hack
1242 // Ask the browser to show UI to retrieve the final print settings.
1243 if (!GetPrintSettingsFromUser(frame_ref
.GetFrame(), node
,
1244 expected_page_count
)) {
1245 DidFinishPrinting(OK
); // Release resources and fail silently.
1248 #endif // !defined(OS_ANDROID)
1250 // Render Pages for printing.
1251 if (!RenderPagesForPrint(frame_ref
.GetFrame(), node
)) {
1252 LOG(ERROR
) << "RenderPagesForPrint failed";
1253 DidFinishPrinting(FAIL_PRINT
);
1255 ResetScriptedPrintCount();
1258 void PrintWebViewHelper::DidFinishPrinting(PrintingResult result
) {
1263 case FAIL_PRINT_INIT
:
1264 DCHECK(!notify_browser_of_print_failure_
);
1268 if (notify_browser_of_print_failure_
&& print_pages_params_
.get()) {
1269 int cookie
= print_pages_params_
->params
.document_cookie
;
1270 Send(new PrintHostMsg_PrintingFailed(routing_id(), cookie
));
1275 DCHECK(is_preview_enabled_
);
1276 int cookie
= print_pages_params_
.get() ?
1277 print_pages_params_
->params
.document_cookie
: 0;
1278 if (notify_browser_of_print_failure_
) {
1279 LOG(ERROR
) << "CreatePreviewDocument failed";
1280 Send(new PrintHostMsg_PrintPreviewFailed(routing_id(), cookie
));
1282 Send(new PrintHostMsg_PrintPreviewCancelled(routing_id(), cookie
));
1284 print_preview_context_
.Failed(notify_browser_of_print_failure_
);
1288 prep_frame_view_
.reset();
1289 print_pages_params_
.reset();
1290 notify_browser_of_print_failure_
= true;
1293 void PrintWebViewHelper::OnFramePreparedForPrintPages() {
1295 FinishFramePrinting();
1298 void PrintWebViewHelper::PrintPages() {
1299 if (!prep_frame_view_
) // Printing is already canceled or failed.
1301 prep_frame_view_
->StartPrinting();
1303 int page_count
= prep_frame_view_
->GetExpectedPageCount();
1305 LOG(ERROR
) << "Can't print 0 pages.";
1306 return DidFinishPrinting(FAIL_PRINT
);
1309 const PrintMsg_PrintPages_Params
& params
= *print_pages_params_
;
1310 const PrintMsg_Print_Params
& print_params
= params
.params
;
1312 #if !defined(OS_CHROMEOS) && !defined(OS_ANDROID)
1313 // TODO(vitalybuka): should be page_count or valid pages from params.pages.
1314 // See http://crbug.com/161576
1315 Send(new PrintHostMsg_DidGetPrintedPagesCount(routing_id(),
1316 print_params
.document_cookie
,
1318 #endif // !defined(OS_CHROMEOS)
1320 if (print_params
.preview_ui_id
< 0) {
1321 // Printing for system dialog.
1322 int printed_count
= params
.pages
.empty() ? page_count
: params
.pages
.size();
1323 #if !defined(OS_CHROMEOS)
1324 UMA_HISTOGRAM_COUNTS("PrintPreview.PageCount.SystemDialog", printed_count
);
1326 UMA_HISTOGRAM_COUNTS("PrintPreview.PageCount.PrintToCloudPrintWebDialog",
1328 #endif // !defined(OS_CHROMEOS)
1332 if (!PrintPagesNative(prep_frame_view_
->frame(), page_count
,
1333 prep_frame_view_
->GetPrintCanvasSize())) {
1334 LOG(ERROR
) << "Printing failed.";
1335 return DidFinishPrinting(FAIL_PRINT
);
1339 void PrintWebViewHelper::FinishFramePrinting() {
1340 prep_frame_view_
.reset();
1343 #if defined(OS_MACOSX) || defined(OS_WIN)
1344 bool PrintWebViewHelper::PrintPagesNative(blink::WebFrame
* frame
,
1346 const gfx::Size
& canvas_size
) {
1347 const PrintMsg_PrintPages_Params
& params
= *print_pages_params_
;
1348 const PrintMsg_Print_Params
& print_params
= params
.params
;
1350 PrintMsg_PrintPage_Params page_params
;
1351 page_params
.params
= print_params
;
1352 if (params
.pages
.empty()) {
1353 for (int i
= 0; i
< page_count
; ++i
) {
1354 page_params
.page_number
= i
;
1355 PrintPageInternal(page_params
, canvas_size
, frame
);
1358 for (size_t i
= 0; i
< params
.pages
.size(); ++i
) {
1359 if (params
.pages
[i
] >= page_count
)
1361 page_params
.page_number
= params
.pages
[i
];
1362 PrintPageInternal(page_params
, canvas_size
, frame
);
1368 #endif // OS_MACOSX || OS_WIN
1370 // static - Not anonymous so that platform implementations can use it.
1371 void PrintWebViewHelper::ComputePageLayoutInPointsForCss(
1372 blink::WebFrame
* frame
,
1374 const PrintMsg_Print_Params
& page_params
,
1375 bool ignore_css_margins
,
1376 double* scale_factor
,
1377 PageSizeMargins
* page_layout_in_points
) {
1378 PrintMsg_Print_Params params
= CalculatePrintParamsForCss(
1379 frame
, page_index
, page_params
, ignore_css_margins
,
1380 page_params
.print_scaling_option
==
1381 blink::WebPrintScalingOptionFitToPrintableArea
,
1383 CalculatePageLayoutFromPrintParams(params
, page_layout_in_points
);
1386 bool PrintWebViewHelper::InitPrintSettings(bool fit_to_paper_size
) {
1387 PrintMsg_PrintPages_Params settings
;
1388 Send(new PrintHostMsg_GetDefaultPrintSettings(routing_id(),
1390 // Check if the printer returned any settings, if the settings is empty, we
1391 // can safely assume there are no printer drivers configured. So we safely
1394 if (!PrintMsg_Print_Params_IsValid(settings
.params
))
1398 (settings
.params
.dpi
< kMinDpi
|| settings
.params
.document_cookie
== 0)) {
1399 // Invalid print page settings.
1404 // Reset to default values.
1405 ignore_css_margins_
= false;
1406 settings
.pages
.clear();
1408 settings
.params
.print_scaling_option
=
1409 blink::WebPrintScalingOptionSourceSize
;
1410 if (fit_to_paper_size
) {
1411 settings
.params
.print_scaling_option
=
1412 blink::WebPrintScalingOptionFitToPrintableArea
;
1415 print_pages_params_
.reset(new PrintMsg_PrintPages_Params(settings
));
1419 bool PrintWebViewHelper::CalculateNumberOfPages(blink::WebLocalFrame
* frame
,
1420 const blink::WebNode
& node
,
1421 int* number_of_pages
) {
1423 bool fit_to_paper_size
= !(PrintingNodeOrPdfFrame(frame
, node
));
1424 if (!InitPrintSettings(fit_to_paper_size
)) {
1425 notify_browser_of_print_failure_
= false;
1426 #if !defined(OS_ANDROID)
1427 // TODO(sgurun) android_webview hack
1428 render_view()->RunModalAlertDialog(
1430 l10n_util::GetStringUTF16(IDS_PRINT_INVALID_PRINTER_SETTINGS
));
1431 #endif // !defined(OS_ANDROID)
1435 const PrintMsg_Print_Params
& params
= print_pages_params_
->params
;
1436 PrepareFrameAndViewForPrint
prepare(params
, frame
, node
, ignore_css_margins_
);
1437 prepare
.StartPrinting();
1439 Send(new PrintHostMsg_DidGetDocumentCookie(routing_id(),
1440 params
.document_cookie
));
1441 *number_of_pages
= prepare
.GetExpectedPageCount();
1445 bool PrintWebViewHelper::UpdatePrintSettings(
1446 blink::WebLocalFrame
* frame
,
1447 const blink::WebNode
& node
,
1448 const base::DictionaryValue
& passed_job_settings
) {
1449 DCHECK(is_preview_enabled_
);
1450 const base::DictionaryValue
* job_settings
= &passed_job_settings
;
1451 base::DictionaryValue modified_job_settings
;
1452 if (job_settings
->empty()) {
1453 if (!print_for_preview_
)
1454 print_preview_context_
.set_error(PREVIEW_ERROR_BAD_SETTING
);
1458 bool source_is_html
= true;
1459 if (print_for_preview_
) {
1460 if (!job_settings
->GetBoolean(kSettingPreviewModifiable
, &source_is_html
)) {
1464 source_is_html
= !PrintingNodeOrPdfFrame(frame
, node
);
1467 if (print_for_preview_
|| !source_is_html
) {
1468 modified_job_settings
.MergeDictionary(job_settings
);
1469 modified_job_settings
.SetBoolean(kSettingHeaderFooterEnabled
, false);
1470 modified_job_settings
.SetInteger(kSettingMarginsType
, NO_MARGINS
);
1471 job_settings
= &modified_job_settings
;
1474 // Send the cookie so that UpdatePrintSettings can reuse PrinterQuery when
1476 int cookie
= print_pages_params_
.get() ?
1477 print_pages_params_
->params
.document_cookie
: 0;
1478 PrintMsg_PrintPages_Params settings
;
1479 Send(new PrintHostMsg_UpdatePrintSettings(routing_id(), cookie
, *job_settings
,
1481 print_pages_params_
.reset(new PrintMsg_PrintPages_Params(settings
));
1483 if (!PrintMsg_Print_Params_IsValid(settings
.params
)) {
1484 if (!print_for_preview_
) {
1485 print_preview_context_
.set_error(PREVIEW_ERROR_INVALID_PRINTER_SETTINGS
);
1487 #if !defined(OS_ANDROID)
1488 // TODO(sgurun) android_webview hack
1489 // PrintForPrintPreview
1490 blink::WebFrame
* print_frame
= NULL
;
1491 // This may not be the right frame, but the alert will be modal,
1492 // therefore it works well enough.
1493 GetPrintFrame(&print_frame
);
1495 render_view()->RunModalAlertDialog(
1497 l10n_util::GetStringUTF16(
1498 IDS_PRINT_INVALID_PRINTER_SETTINGS
));
1500 #endif // !defined(OS_ANDROID)
1505 if (settings
.params
.dpi
< kMinDpi
|| !settings
.params
.document_cookie
) {
1506 print_preview_context_
.set_error(PREVIEW_ERROR_UPDATING_PRINT_SETTINGS
);
1510 if (!job_settings
->GetInteger(kPreviewUIID
, &settings
.params
.preview_ui_id
)) {
1512 print_preview_context_
.set_error(PREVIEW_ERROR_BAD_SETTING
);
1516 if (!print_for_preview_
) {
1517 // Validate expected print preview settings.
1518 if (!job_settings
->GetInteger(kPreviewRequestID
,
1519 &settings
.params
.preview_request_id
) ||
1520 !job_settings
->GetBoolean(kIsFirstRequest
,
1521 &settings
.params
.is_first_request
)) {
1523 print_preview_context_
.set_error(PREVIEW_ERROR_BAD_SETTING
);
1527 settings
.params
.print_to_pdf
= IsPrintToPdfRequested(*job_settings
);
1528 UpdateFrameMarginsCssInfo(*job_settings
);
1529 settings
.params
.print_scaling_option
= GetPrintScalingOption(
1530 source_is_html
, *job_settings
, settings
.params
);
1532 // Header/Footer: Set |header_footer_info_|.
1533 if (settings
.params
.display_header_footer
) {
1534 header_footer_info_
.reset(new base::DictionaryValue());
1535 header_footer_info_
->SetDouble(kSettingHeaderFooterDate
,
1536 base::Time::Now().ToJsTime());
1537 header_footer_info_
->SetString(kSettingHeaderFooterURL
,
1538 settings
.params
.url
);
1539 header_footer_info_
->SetString(kSettingHeaderFooterTitle
,
1540 settings
.params
.title
);
1544 print_pages_params_
.reset(new PrintMsg_PrintPages_Params(settings
));
1545 Send(new PrintHostMsg_DidGetDocumentCookie(routing_id(),
1546 settings
.params
.document_cookie
));
1551 bool PrintWebViewHelper::GetPrintSettingsFromUser(blink::WebFrame
* frame
,
1552 const blink::WebNode
& node
,
1553 int expected_pages_count
) {
1554 PrintHostMsg_ScriptedPrint_Params params
;
1555 PrintMsg_PrintPages_Params print_settings
;
1557 params
.cookie
= print_pages_params_
->params
.document_cookie
;
1558 params
.has_selection
= frame
->hasSelection();
1559 params
.expected_pages_count
= expected_pages_count
;
1560 MarginType margin_type
= DEFAULT_MARGINS
;
1561 if (PrintingNodeOrPdfFrame(frame
, node
))
1562 margin_type
= GetMarginsForPdf(frame
, node
);
1563 params
.margin_type
= margin_type
;
1565 Send(new PrintHostMsg_DidShowPrintDialog(routing_id()));
1567 // PrintHostMsg_ScriptedPrint will reset print_scaling_option, so we save the
1568 // value before and restore it afterwards.
1569 blink::WebPrintScalingOption scaling_option
=
1570 print_pages_params_
->params
.print_scaling_option
;
1572 print_pages_params_
.reset();
1573 IPC::SyncMessage
* msg
=
1574 new PrintHostMsg_ScriptedPrint(routing_id(), params
, &print_settings
);
1575 msg
->EnableMessagePumping();
1577 print_pages_params_
.reset(new PrintMsg_PrintPages_Params(print_settings
));
1579 print_pages_params_
->params
.print_scaling_option
= scaling_option
;
1580 return (print_settings
.params
.dpi
&& print_settings
.params
.document_cookie
);
1583 bool PrintWebViewHelper::RenderPagesForPrint(blink::WebLocalFrame
* frame
,
1584 const blink::WebNode
& node
) {
1585 if (!frame
|| prep_frame_view_
)
1587 const PrintMsg_PrintPages_Params
& params
= *print_pages_params_
;
1588 const PrintMsg_Print_Params
& print_params
= params
.params
;
1589 prep_frame_view_
.reset(new PrepareFrameAndViewForPrint(
1590 print_params
, frame
, node
, ignore_css_margins_
));
1591 DCHECK(!print_pages_params_
->params
.selection_only
||
1592 print_pages_params_
->pages
.empty());
1593 prep_frame_view_
->CopySelectionIfNeeded(
1594 render_view()->GetWebkitPreferences(),
1595 base::Bind(&PrintWebViewHelper::OnFramePreparedForPrintPages
,
1596 base::Unretained(this)));
1600 #if defined(OS_POSIX)
1601 bool PrintWebViewHelper::CopyMetafileDataToSharedMem(
1602 PdfMetafileSkia
* metafile
,
1603 base::SharedMemoryHandle
* shared_mem_handle
) {
1604 uint32 buf_size
= metafile
->GetDataSize();
1605 scoped_ptr
<base::SharedMemory
> shared_buf(
1606 content::RenderThread::Get()->HostAllocateSharedMemoryBuffer(
1607 buf_size
).release());
1609 if (shared_buf
.get()) {
1610 if (shared_buf
->Map(buf_size
)) {
1611 metafile
->GetData(shared_buf
->memory(), buf_size
);
1612 shared_buf
->GiveToProcess(base::GetCurrentProcessHandle(),
1620 #endif // defined(OS_POSIX)
1622 bool PrintWebViewHelper::IsScriptInitiatedPrintTooFrequent(
1623 blink::WebFrame
* frame
) {
1624 const int kMinSecondsToIgnoreJavascriptInitiatedPrint
= 2;
1625 const int kMaxSecondsToIgnoreJavascriptInitiatedPrint
= 32;
1626 bool too_frequent
= false;
1628 // Check if there is script repeatedly trying to print and ignore it if too
1629 // frequent. The first 3 times, we use a constant wait time, but if this
1630 // gets excessive, we switch to exponential wait time. So for a page that
1631 // calls print() in a loop the user will need to cancel the print dialog
1632 // after: [2, 2, 2, 4, 8, 16, 32, 32, ...] seconds.
1633 // This gives the user time to navigate from the page.
1634 if (user_cancelled_scripted_print_count_
> 0) {
1635 base::TimeDelta diff
= base::Time::Now() - last_cancelled_script_print_
;
1636 int min_wait_seconds
= kMinSecondsToIgnoreJavascriptInitiatedPrint
;
1637 if (user_cancelled_scripted_print_count_
> 3) {
1638 min_wait_seconds
= std::min(
1639 kMinSecondsToIgnoreJavascriptInitiatedPrint
<<
1640 (user_cancelled_scripted_print_count_
- 3),
1641 kMaxSecondsToIgnoreJavascriptInitiatedPrint
);
1643 if (diff
.InSeconds() < min_wait_seconds
) {
1644 too_frequent
= true;
1651 blink::WebString
message(
1652 blink::WebString::fromUTF8("Ignoring too frequent calls to print()."));
1653 frame
->addMessageToConsole(
1654 blink::WebConsoleMessage(
1655 blink::WebConsoleMessage::LevelWarning
, message
));
1659 void PrintWebViewHelper::ResetScriptedPrintCount() {
1660 // Reset cancel counter on successful print.
1661 user_cancelled_scripted_print_count_
= 0;
1664 void PrintWebViewHelper::IncrementScriptedPrintCount() {
1665 ++user_cancelled_scripted_print_count_
;
1666 last_cancelled_script_print_
= base::Time::Now();
1669 void PrintWebViewHelper::ShowScriptedPrintPreview() {
1670 if (is_scripted_preview_delayed_
) {
1671 is_scripted_preview_delayed_
= false;
1672 Send(new PrintHostMsg_ShowScriptedPrintPreview(routing_id(),
1673 print_preview_context_
.IsModifiable()));
1677 void PrintWebViewHelper::RequestPrintPreview(PrintPreviewRequestType type
) {
1678 const bool is_modifiable
= print_preview_context_
.IsModifiable();
1679 const bool has_selection
= print_preview_context_
.HasSelection();
1680 PrintHostMsg_RequestPrintPreview_Params params
;
1681 params
.is_modifiable
= is_modifiable
;
1682 params
.has_selection
= has_selection
;
1684 case PRINT_PREVIEW_SCRIPTED
: {
1685 // Shows scripted print preview in two stages.
1686 // 1. PrintHostMsg_SetupScriptedPrintPreview blocks this call and JS by
1687 // pumping messages here.
1688 // 2. PrintHostMsg_ShowScriptedPrintPreview shows preview once the
1689 // document has been loaded.
1690 is_scripted_preview_delayed_
= true;
1691 if (is_loading_
&& GetPlugin(print_preview_context_
.source_frame())) {
1692 // Wait for DidStopLoading. Plugins may not know the correct
1693 // |is_modifiable| value until they are fully loaded, which occurs when
1694 // DidStopLoading() is called. Defer showing the preview until then.
1696 base::MessageLoop::current()->PostTask(
1698 base::Bind(&PrintWebViewHelper::ShowScriptedPrintPreview
,
1699 weak_ptr_factory_
.GetWeakPtr()));
1701 IPC::SyncMessage
* msg
=
1702 new PrintHostMsg_SetupScriptedPrintPreview(routing_id());
1703 msg
->EnableMessagePumping();
1705 is_scripted_preview_delayed_
= false;
1708 case PRINT_PREVIEW_USER_INITIATED_ENTIRE_FRAME
: {
1711 case PRINT_PREVIEW_USER_INITIATED_SELECTION
: {
1712 DCHECK(has_selection
);
1713 params
.selection_only
= has_selection
;
1716 case PRINT_PREVIEW_USER_INITIATED_CONTEXT_NODE
: {
1717 params
.webnode_only
= true;
1725 Send(new PrintHostMsg_RequestPrintPreview(routing_id(), params
));
1728 bool PrintWebViewHelper::CheckForCancel() {
1729 const PrintMsg_Print_Params
& print_params
= print_pages_params_
->params
;
1730 bool cancel
= false;
1731 Send(new PrintHostMsg_CheckForCancel(routing_id(),
1732 print_params
.preview_ui_id
,
1733 print_params
.preview_request_id
,
1736 notify_browser_of_print_failure_
= false;
1740 bool PrintWebViewHelper::PreviewPageRendered(int page_number
,
1741 PdfMetafileSkia
* metafile
) {
1742 DCHECK_GE(page_number
, FIRST_PAGE_INDEX
);
1744 // For non-modifiable files, |metafile| should be NULL, so do not bother
1745 // sending a message. If we don't generate draft metafiles, |metafile| is
1747 if (!print_preview_context_
.IsModifiable() ||
1748 !print_preview_context_
.generate_draft_pages()) {
1755 print_preview_context_
.set_error(
1756 PREVIEW_ERROR_PAGE_RENDERED_WITHOUT_METAFILE
);
1760 PrintHostMsg_DidPreviewPage_Params preview_page_params
;
1761 // Get the size of the resulting metafile.
1762 uint32 buf_size
= metafile
->GetDataSize();
1763 DCHECK_GT(buf_size
, 0u);
1764 if (!CopyMetafileDataToSharedMem(
1765 metafile
, &(preview_page_params
.metafile_data_handle
))) {
1766 LOG(ERROR
) << "CopyMetafileDataToSharedMem failed";
1767 print_preview_context_
.set_error(PREVIEW_ERROR_METAFILE_COPY_FAILED
);
1770 preview_page_params
.data_size
= buf_size
;
1771 preview_page_params
.page_number
= page_number
;
1772 preview_page_params
.preview_request_id
=
1773 print_pages_params_
->params
.preview_request_id
;
1775 Send(new PrintHostMsg_DidPreviewPage(routing_id(), preview_page_params
));
1779 PrintWebViewHelper::PrintPreviewContext::PrintPreviewContext()
1780 : total_page_count_(0),
1781 current_page_index_(0),
1782 generate_draft_pages_(true),
1783 print_ready_metafile_page_count_(0),
1784 error_(PREVIEW_ERROR_NONE
),
1785 state_(UNINITIALIZED
) {
1788 PrintWebViewHelper::PrintPreviewContext::~PrintPreviewContext() {
1791 void PrintWebViewHelper::PrintPreviewContext::InitWithFrame(
1792 blink::WebLocalFrame
* web_frame
) {
1794 DCHECK(!IsRendering());
1795 state_
= INITIALIZED
;
1796 source_frame_
.Reset(web_frame
);
1797 source_node_
.reset();
1800 void PrintWebViewHelper::PrintPreviewContext::InitWithNode(
1801 const blink::WebNode
& web_node
) {
1802 DCHECK(!web_node
.isNull());
1803 DCHECK(web_node
.document().frame());
1804 DCHECK(!IsRendering());
1805 state_
= INITIALIZED
;
1806 source_frame_
.Reset(web_node
.document().frame());
1807 source_node_
= web_node
;
1810 void PrintWebViewHelper::PrintPreviewContext::OnPrintPreview() {
1811 DCHECK_EQ(INITIALIZED
, state_
);
1815 bool PrintWebViewHelper::PrintPreviewContext::CreatePreviewDocument(
1816 PrepareFrameAndViewForPrint
* prepared_frame
,
1817 const std::vector
<int>& pages
) {
1818 DCHECK_EQ(INITIALIZED
, state_
);
1821 // Need to make sure old object gets destroyed first.
1822 prep_frame_view_
.reset(prepared_frame
);
1823 prep_frame_view_
->StartPrinting();
1825 total_page_count_
= prep_frame_view_
->GetExpectedPageCount();
1826 if (total_page_count_
== 0) {
1827 LOG(ERROR
) << "CreatePreviewDocument got 0 page count";
1828 set_error(PREVIEW_ERROR_ZERO_PAGES
);
1832 metafile_
.reset(new PdfMetafileSkia
);
1833 if (!metafile_
->Init()) {
1834 set_error(PREVIEW_ERROR_METAFILE_INIT_FAILED
);
1835 LOG(ERROR
) << "PdfMetafileSkia Init failed";
1839 current_page_index_
= 0;
1840 pages_to_render_
= pages
;
1841 // Sort and make unique.
1842 std::sort(pages_to_render_
.begin(), pages_to_render_
.end());
1843 pages_to_render_
.resize(std::unique(pages_to_render_
.begin(),
1844 pages_to_render_
.end()) -
1845 pages_to_render_
.begin());
1846 // Remove invalid pages.
1847 pages_to_render_
.resize(std::lower_bound(pages_to_render_
.begin(),
1848 pages_to_render_
.end(),
1849 total_page_count_
) -
1850 pages_to_render_
.begin());
1851 print_ready_metafile_page_count_
= pages_to_render_
.size();
1852 if (pages_to_render_
.empty()) {
1853 print_ready_metafile_page_count_
= total_page_count_
;
1854 // Render all pages.
1855 for (int i
= 0; i
< total_page_count_
; ++i
)
1856 pages_to_render_
.push_back(i
);
1857 } else if (generate_draft_pages_
) {
1858 int pages_index
= 0;
1859 for (int i
= 0; i
< total_page_count_
; ++i
) {
1860 if (pages_index
< print_ready_metafile_page_count_
&&
1861 i
== pages_to_render_
[pages_index
]) {
1865 pages_to_render_
.push_back(i
);
1869 document_render_time_
= base::TimeDelta();
1870 begin_time_
= base::TimeTicks::Now();
1875 void PrintWebViewHelper::PrintPreviewContext::RenderedPreviewPage(
1876 const base::TimeDelta
& page_time
) {
1877 DCHECK_EQ(RENDERING
, state_
);
1878 document_render_time_
+= page_time
;
1879 UMA_HISTOGRAM_TIMES("PrintPreview.RenderPDFPageTime", page_time
);
1882 void PrintWebViewHelper::PrintPreviewContext::AllPagesRendered() {
1883 DCHECK_EQ(RENDERING
, state_
);
1885 prep_frame_view_
->FinishPrinting();
1888 void PrintWebViewHelper::PrintPreviewContext::FinalizePrintReadyDocument() {
1889 DCHECK(IsRendering());
1891 base::TimeTicks begin_time
= base::TimeTicks::Now();
1892 metafile_
->FinishDocument();
1894 if (print_ready_metafile_page_count_
<= 0) {
1899 UMA_HISTOGRAM_MEDIUM_TIMES("PrintPreview.RenderToPDFTime",
1900 document_render_time_
);
1901 base::TimeDelta total_time
= (base::TimeTicks::Now() - begin_time
) +
1902 document_render_time_
;
1903 UMA_HISTOGRAM_MEDIUM_TIMES("PrintPreview.RenderAndGeneratePDFTime",
1905 UMA_HISTOGRAM_MEDIUM_TIMES("PrintPreview.RenderAndGeneratePDFTimeAvgPerPage",
1906 total_time
/ pages_to_render_
.size());
1909 void PrintWebViewHelper::PrintPreviewContext::Finished() {
1910 DCHECK_EQ(DONE
, state_
);
1911 state_
= INITIALIZED
;
1915 void PrintWebViewHelper::PrintPreviewContext::Failed(bool report_error
) {
1916 DCHECK(state_
== INITIALIZED
|| state_
== RENDERING
);
1917 state_
= INITIALIZED
;
1919 DCHECK_NE(PREVIEW_ERROR_NONE
, error_
);
1920 UMA_HISTOGRAM_ENUMERATION("PrintPreview.RendererError", error_
,
1921 PREVIEW_ERROR_LAST_ENUM
);
1926 int PrintWebViewHelper::PrintPreviewContext::GetNextPageNumber() {
1927 DCHECK_EQ(RENDERING
, state_
);
1928 if (IsFinalPageRendered())
1930 return pages_to_render_
[current_page_index_
++];
1933 bool PrintWebViewHelper::PrintPreviewContext::IsRendering() const {
1934 return state_
== RENDERING
|| state_
== DONE
;
1937 bool PrintWebViewHelper::PrintPreviewContext::IsModifiable() {
1938 // The only kind of node we can print right now is a PDF node.
1939 return !PrintingNodeOrPdfFrame(source_frame(), source_node_
);
1942 bool PrintWebViewHelper::PrintPreviewContext::HasSelection() {
1943 return IsModifiable() && source_frame()->hasSelection();
1946 bool PrintWebViewHelper::PrintPreviewContext::IsLastPageOfPrintReadyMetafile()
1948 DCHECK(IsRendering());
1949 return current_page_index_
== print_ready_metafile_page_count_
;
1952 bool PrintWebViewHelper::PrintPreviewContext::IsFinalPageRendered() const {
1953 DCHECK(IsRendering());
1954 return static_cast<size_t>(current_page_index_
) == pages_to_render_
.size();
1957 void PrintWebViewHelper::PrintPreviewContext::set_generate_draft_pages(
1958 bool generate_draft_pages
) {
1959 DCHECK_EQ(INITIALIZED
, state_
);
1960 generate_draft_pages_
= generate_draft_pages
;
1963 void PrintWebViewHelper::PrintPreviewContext::set_error(
1964 enum PrintPreviewErrorBuckets error
) {
1968 blink::WebLocalFrame
* PrintWebViewHelper::PrintPreviewContext::source_frame() {
1969 DCHECK_NE(UNINITIALIZED
, state_
);
1970 return source_frame_
.GetFrame();
1973 const blink::WebNode
&
1974 PrintWebViewHelper::PrintPreviewContext::source_node() const {
1975 DCHECK_NE(UNINITIALIZED
, state_
);
1976 return source_node_
;
1979 blink::WebLocalFrame
*
1980 PrintWebViewHelper::PrintPreviewContext::prepared_frame() {
1981 DCHECK_NE(UNINITIALIZED
, state_
);
1982 return prep_frame_view_
->frame();
1985 const blink::WebNode
&
1986 PrintWebViewHelper::PrintPreviewContext::prepared_node() const {
1987 DCHECK_NE(UNINITIALIZED
, state_
);
1988 return prep_frame_view_
->node();
1991 int PrintWebViewHelper::PrintPreviewContext::total_page_count() const {
1992 DCHECK_NE(UNINITIALIZED
, state_
);
1993 return total_page_count_
;
1996 bool PrintWebViewHelper::PrintPreviewContext::generate_draft_pages() const {
1997 return generate_draft_pages_
;
2000 PdfMetafileSkia
* PrintWebViewHelper::PrintPreviewContext::metafile() {
2001 DCHECK(IsRendering());
2002 return metafile_
.get();
2005 int PrintWebViewHelper::PrintPreviewContext::last_error() const {
2009 gfx::Size
PrintWebViewHelper::PrintPreviewContext::GetPrintCanvasSize() const {
2010 DCHECK(IsRendering());
2011 return prep_frame_view_
->GetPrintCanvasSize();
2014 void PrintWebViewHelper::PrintPreviewContext::ClearContext() {
2015 prep_frame_view_
.reset();
2017 pages_to_render_
.clear();
2018 error_
= PREVIEW_ERROR_NONE
;
2021 } // namespace printing