1 // Copyright (c) 2012 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #include "components/printing/renderer/print_web_view_helper.h"
9 #include "base/auto_reset.h"
10 #include "base/json/json_writer.h"
11 #include "base/location.h"
12 #include "base/logging.h"
13 #include "base/metrics/histogram_macros.h"
14 #include "base/process/process_handle.h"
15 #include "base/single_thread_task_runner.h"
16 #include "base/strings/string_number_conversions.h"
17 #include "base/strings/stringprintf.h"
18 #include "base/strings/utf_string_conversions.h"
19 #include "base/thread_task_runner_handle.h"
20 #include "components/printing/common/print_messages.h"
21 #include "content/public/common/web_preferences.h"
22 #include "content/public/renderer/render_frame.h"
23 #include "content/public/renderer/render_thread.h"
24 #include "content/public/renderer/render_view.h"
25 #include "grit/components_resources.h"
26 #include "net/base/escape.h"
27 #include "printing/pdf_metafile_skia.h"
28 #include "printing/units.h"
29 #include "third_party/WebKit/public/platform/WebSize.h"
30 #include "third_party/WebKit/public/platform/WebURLRequest.h"
31 #include "third_party/WebKit/public/web/WebConsoleMessage.h"
32 #include "third_party/WebKit/public/web/WebDocument.h"
33 #include "third_party/WebKit/public/web/WebElement.h"
34 #include "third_party/WebKit/public/web/WebFrameClient.h"
35 #include "third_party/WebKit/public/web/WebLocalFrame.h"
36 #include "third_party/WebKit/public/web/WebPlugin.h"
37 #include "third_party/WebKit/public/web/WebPluginDocument.h"
38 #include "third_party/WebKit/public/web/WebPrintParams.h"
39 #include "third_party/WebKit/public/web/WebPrintPresetOptions.h"
40 #include "third_party/WebKit/public/web/WebSandboxFlags.h"
41 #include "third_party/WebKit/public/web/WebScriptSource.h"
42 #include "third_party/WebKit/public/web/WebSettings.h"
43 #include "third_party/WebKit/public/web/WebView.h"
44 #include "third_party/WebKit/public/web/WebViewClient.h"
45 #include "ui/base/resource/resource_bundle.h"
47 using content::WebPreferences
;
53 #define STATIC_ASSERT_PP_MATCHING_ENUM(a, b) \
54 static_assert(static_cast<int>(a) == static_cast<int>(b), \
55 "mismatching enums: " #a)
57 // Check blink::WebDuplexMode and printing::DuplexMode are kept in sync.
58 STATIC_ASSERT_PP_MATCHING_ENUM(blink::WebUnknownDuplexMode
,
60 STATIC_ASSERT_PP_MATCHING_ENUM(blink::WebSimplex
, SIMPLEX
);
61 STATIC_ASSERT_PP_MATCHING_ENUM(blink::WebLongEdge
, LONG_EDGE
);
62 STATIC_ASSERT_PP_MATCHING_ENUM(blink::WebShortEdge
, SHORT_EDGE
);
64 enum PrintPreviewHelperEvents
{
65 PREVIEW_EVENT_REQUESTED
,
66 PREVIEW_EVENT_CACHE_HIT
, // Unused
67 PREVIEW_EVENT_CREATE_DOCUMENT
,
68 PREVIEW_EVENT_NEW_SETTINGS
, // Unused
72 const double kMinDpi
= 1.0;
74 #if !defined(ENABLE_PRINT_PREVIEW)
75 bool g_is_preview_enabled_
= false;
77 bool g_is_preview_enabled_
= true;
79 const char kPageLoadScriptFormat
[] =
80 "document.open(); document.write(%s); document.close();";
82 const char kPageSetupScriptFormat
[] = "setup(%s);";
84 void ExecuteScript(blink::WebFrame
* frame
,
85 const char* script_format
,
86 const base::Value
& parameters
) {
88 base::JSONWriter::Write(parameters
, &json
);
89 std::string script
= base::StringPrintf(script_format
, json
.c_str());
90 frame
->executeScript(blink::WebString(base::UTF8ToUTF16(script
)));
92 #endif // !defined(ENABLE_PRINT_PREVIEW)
94 int GetDPI(const PrintMsg_Print_Params
* print_params
) {
95 #if defined(OS_MACOSX)
96 // On the Mac, the printable area is in points, don't do any scaling based
98 return kPointsPerInch
;
100 return static_cast<int>(print_params
->dpi
);
101 #endif // defined(OS_MACOSX)
104 bool PrintMsg_Print_Params_IsValid(const PrintMsg_Print_Params
& params
) {
105 return !params
.content_size
.IsEmpty() && !params
.page_size
.IsEmpty() &&
106 !params
.printable_area
.IsEmpty() && params
.document_cookie
&&
107 params
.desired_dpi
&& params
.max_shrink
&& params
.min_shrink
&&
108 params
.dpi
&& (params
.margin_top
>= 0) && (params
.margin_left
>= 0) &&
109 params
.dpi
> kMinDpi
&& params
.document_cookie
!= 0;
112 PrintMsg_Print_Params
GetCssPrintParams(
113 blink::WebFrame
* frame
,
115 const PrintMsg_Print_Params
& page_params
) {
116 PrintMsg_Print_Params page_css_params
= page_params
;
117 int dpi
= GetDPI(&page_params
);
119 blink::WebSize
page_size_in_pixels(
120 ConvertUnit(page_params
.page_size
.width(), dpi
, kPixelsPerInch
),
121 ConvertUnit(page_params
.page_size
.height(), dpi
, kPixelsPerInch
));
122 int margin_top_in_pixels
=
123 ConvertUnit(page_params
.margin_top
, dpi
, kPixelsPerInch
);
124 int margin_right_in_pixels
= ConvertUnit(
125 page_params
.page_size
.width() -
126 page_params
.content_size
.width() - page_params
.margin_left
,
127 dpi
, kPixelsPerInch
);
128 int margin_bottom_in_pixels
= ConvertUnit(
129 page_params
.page_size
.height() -
130 page_params
.content_size
.height() - page_params
.margin_top
,
131 dpi
, kPixelsPerInch
);
132 int margin_left_in_pixels
= ConvertUnit(
133 page_params
.margin_left
,
134 dpi
, kPixelsPerInch
);
136 blink::WebSize original_page_size_in_pixels
= page_size_in_pixels
;
139 frame
->pageSizeAndMarginsInPixels(page_index
,
141 margin_top_in_pixels
,
142 margin_right_in_pixels
,
143 margin_bottom_in_pixels
,
144 margin_left_in_pixels
);
147 int new_content_width
= page_size_in_pixels
.width
-
148 margin_left_in_pixels
- margin_right_in_pixels
;
149 int new_content_height
= page_size_in_pixels
.height
-
150 margin_top_in_pixels
- margin_bottom_in_pixels
;
152 // Invalid page size and/or margins. We just use the default setting.
153 if (new_content_width
< 1 || new_content_height
< 1) {
154 CHECK(frame
!= NULL
);
155 page_css_params
= GetCssPrintParams(NULL
, page_index
, page_params
);
156 return page_css_params
;
159 page_css_params
.content_size
=
160 gfx::Size(ConvertUnit(new_content_width
, kPixelsPerInch
, dpi
),
161 ConvertUnit(new_content_height
, kPixelsPerInch
, dpi
));
163 if (original_page_size_in_pixels
!= page_size_in_pixels
) {
164 page_css_params
.page_size
=
165 gfx::Size(ConvertUnit(page_size_in_pixels
.width
, kPixelsPerInch
, dpi
),
166 ConvertUnit(page_size_in_pixels
.height
, kPixelsPerInch
, dpi
));
168 // Printing frame doesn't have any page size css. Pixels to dpi conversion
169 // causes rounding off errors. Therefore use the default page size values
171 page_css_params
.page_size
= page_params
.page_size
;
174 page_css_params
.margin_top
=
175 ConvertUnit(margin_top_in_pixels
, kPixelsPerInch
, dpi
);
176 page_css_params
.margin_left
=
177 ConvertUnit(margin_left_in_pixels
, kPixelsPerInch
, dpi
);
178 return page_css_params
;
181 double FitPrintParamsToPage(const PrintMsg_Print_Params
& page_params
,
182 PrintMsg_Print_Params
* params_to_fit
) {
183 double content_width
=
184 static_cast<double>(params_to_fit
->content_size
.width());
185 double content_height
=
186 static_cast<double>(params_to_fit
->content_size
.height());
187 int default_page_size_height
= page_params
.page_size
.height();
188 int default_page_size_width
= page_params
.page_size
.width();
189 int css_page_size_height
= params_to_fit
->page_size
.height();
190 int css_page_size_width
= params_to_fit
->page_size
.width();
192 double scale_factor
= 1.0f
;
193 if (page_params
.page_size
== params_to_fit
->page_size
)
196 if (default_page_size_width
< css_page_size_width
||
197 default_page_size_height
< css_page_size_height
) {
199 static_cast<double>(default_page_size_width
) / css_page_size_width
;
200 double ratio_height
=
201 static_cast<double>(default_page_size_height
) / css_page_size_height
;
202 scale_factor
= ratio_width
< ratio_height
? ratio_width
: ratio_height
;
203 content_width
*= scale_factor
;
204 content_height
*= scale_factor
;
206 params_to_fit
->margin_top
= static_cast<int>(
207 (default_page_size_height
- css_page_size_height
* scale_factor
) / 2 +
208 (params_to_fit
->margin_top
* scale_factor
));
209 params_to_fit
->margin_left
= static_cast<int>(
210 (default_page_size_width
- css_page_size_width
* scale_factor
) / 2 +
211 (params_to_fit
->margin_left
* scale_factor
));
212 params_to_fit
->content_size
= gfx::Size(static_cast<int>(content_width
),
213 static_cast<int>(content_height
));
214 params_to_fit
->page_size
= page_params
.page_size
;
218 void CalculatePageLayoutFromPrintParams(
219 const PrintMsg_Print_Params
& params
,
220 PageSizeMargins
* page_layout_in_points
) {
221 int dpi
= GetDPI(¶ms
);
222 int content_width
= params
.content_size
.width();
223 int content_height
= params
.content_size
.height();
226 params
.page_size
.height() - content_height
- params
.margin_top
;
228 params
.page_size
.width() - content_width
- params
.margin_left
;
230 page_layout_in_points
->content_width
=
231 ConvertUnit(content_width
, dpi
, kPointsPerInch
);
232 page_layout_in_points
->content_height
=
233 ConvertUnit(content_height
, dpi
, kPointsPerInch
);
234 page_layout_in_points
->margin_top
=
235 ConvertUnit(params
.margin_top
, dpi
, kPointsPerInch
);
236 page_layout_in_points
->margin_right
=
237 ConvertUnit(margin_right
, dpi
, kPointsPerInch
);
238 page_layout_in_points
->margin_bottom
=
239 ConvertUnit(margin_bottom
, dpi
, kPointsPerInch
);
240 page_layout_in_points
->margin_left
=
241 ConvertUnit(params
.margin_left
, dpi
, kPointsPerInch
);
244 void EnsureOrientationMatches(const PrintMsg_Print_Params
& css_params
,
245 PrintMsg_Print_Params
* page_params
) {
246 if ((page_params
->page_size
.width() > page_params
->page_size
.height()) ==
247 (css_params
.page_size
.width() > css_params
.page_size
.height())) {
251 // Swap the |width| and |height| values.
252 page_params
->page_size
.SetSize(page_params
->page_size
.height(),
253 page_params
->page_size
.width());
254 page_params
->content_size
.SetSize(page_params
->content_size
.height(),
255 page_params
->content_size
.width());
256 page_params
->printable_area
.set_size(
257 gfx::Size(page_params
->printable_area
.height(),
258 page_params
->printable_area
.width()));
261 void ComputeWebKitPrintParamsInDesiredDpi(
262 const PrintMsg_Print_Params
& print_params
,
263 blink::WebPrintParams
* webkit_print_params
) {
264 int dpi
= GetDPI(&print_params
);
265 webkit_print_params
->printerDPI
= dpi
;
266 webkit_print_params
->printScalingOption
= print_params
.print_scaling_option
;
268 webkit_print_params
->printContentArea
.width
= ConvertUnit(
269 print_params
.content_size
.width(), dpi
, print_params
.desired_dpi
);
270 webkit_print_params
->printContentArea
.height
= ConvertUnit(
271 print_params
.content_size
.height(), dpi
, print_params
.desired_dpi
);
273 webkit_print_params
->printableArea
.x
= ConvertUnit(
274 print_params
.printable_area
.x(), dpi
, print_params
.desired_dpi
);
275 webkit_print_params
->printableArea
.y
= ConvertUnit(
276 print_params
.printable_area
.y(), dpi
, print_params
.desired_dpi
);
277 webkit_print_params
->printableArea
.width
= ConvertUnit(
278 print_params
.printable_area
.width(), dpi
, print_params
.desired_dpi
);
279 webkit_print_params
->printableArea
.height
= ConvertUnit(
280 print_params
.printable_area
.height(), dpi
, print_params
.desired_dpi
);
282 webkit_print_params
->paperSize
.width
= ConvertUnit(
283 print_params
.page_size
.width(), dpi
, print_params
.desired_dpi
);
284 webkit_print_params
->paperSize
.height
= ConvertUnit(
285 print_params
.page_size
.height(), dpi
, print_params
.desired_dpi
);
288 blink::WebPlugin
* GetPlugin(const blink::WebLocalFrame
* frame
) {
289 return frame
->document().isPluginDocument()
290 ? frame
->document().to
<blink::WebPluginDocument
>().plugin()
294 bool PrintingNodeOrPdfFrame(const blink::WebLocalFrame
* frame
,
295 const blink::WebNode
& node
) {
298 blink::WebPlugin
* plugin
= GetPlugin(frame
);
299 return plugin
&& plugin
->supportsPaginatedPrint();
302 bool PrintingFrameHasPageSizeStyle(blink::WebFrame
* frame
,
303 int total_page_count
) {
306 bool frame_has_custom_page_size_style
= false;
307 for (int i
= 0; i
< total_page_count
; ++i
) {
308 if (frame
->hasCustomPageSizeStyle(i
)) {
309 frame_has_custom_page_size_style
= true;
313 return frame_has_custom_page_size_style
;
316 // Disable scaling when either:
317 // - The PDF specifies disabling scaling.
318 // - All the pages in the PDF are the same size, and that size is the same as
320 bool PDFShouldDisableScalingBasedOnPreset(
321 const blink::WebPrintPresetOptions
& options
,
322 const PrintMsg_Print_Params
& params
) {
323 if (options
.isScalingDisabled
)
326 if (!options
.isPageSizeUniform
)
329 int dpi
= GetDPI(¶ms
);
331 // Likely |params| is invalid, in which case the return result does not
332 // matter. Check for this so ConvertUnit() does not divide by zero.
336 blink::WebSize
page_size(
337 ConvertUnit(params
.page_size
.width(), dpi
, kPointsPerInch
),
338 ConvertUnit(params
.page_size
.height(), dpi
, kPointsPerInch
));
339 return options
.uniformPageSize
== page_size
;
342 bool PDFShouldDisableScaling(blink::WebLocalFrame
* frame
,
343 const blink::WebNode
& node
,
344 const PrintMsg_Print_Params
& params
) {
345 const bool kDefaultPDFShouldDisableScalingSetting
= true;
346 blink::WebPrintPresetOptions preset_options
;
347 if (!frame
->getPrintPresetOptionsForPlugin(node
, &preset_options
))
348 return kDefaultPDFShouldDisableScalingSetting
;
349 return PDFShouldDisableScalingBasedOnPreset(preset_options
, params
);
352 MarginType
GetMarginsForPdf(blink::WebLocalFrame
* frame
,
353 const blink::WebNode
& node
,
354 const PrintMsg_Print_Params
& params
) {
355 return PDFShouldDisableScaling(frame
, node
, params
) ?
356 NO_MARGINS
: PRINTABLE_AREA_MARGINS
;
359 bool FitToPageEnabled(const base::DictionaryValue
& job_settings
) {
360 bool fit_to_paper_size
= false;
361 if (!job_settings
.GetBoolean(kSettingFitToPageEnabled
, &fit_to_paper_size
)) {
364 return fit_to_paper_size
;
367 // Returns the print scaling option to retain/scale/crop the source page size
368 // to fit the printable area of the paper.
370 // We retain the source page size when the current destination printer is
373 // We crop the source page size to fit the printable area or we print only the
374 // left top page contents when
375 // (1) Source is PDF and the user has requested not to fit to printable area
376 // via |job_settings|.
377 // (2) Source is PDF. This is the first preview request and print scaling
378 // option is disabled for initiator renderer plugin.
380 // In all other cases, we scale the source page to fit the printable area.
381 blink::WebPrintScalingOption
GetPrintScalingOption(
382 blink::WebLocalFrame
* frame
,
383 const blink::WebNode
& node
,
385 const base::DictionaryValue
& job_settings
,
386 const PrintMsg_Print_Params
& params
) {
387 if (params
.print_to_pdf
)
388 return blink::WebPrintScalingOptionSourceSize
;
390 if (!source_is_html
) {
391 if (!FitToPageEnabled(job_settings
))
392 return blink::WebPrintScalingOptionNone
;
394 bool no_plugin_scaling
= PDFShouldDisableScaling(frame
, node
, params
);
395 if (params
.is_first_request
&& no_plugin_scaling
)
396 return blink::WebPrintScalingOptionNone
;
398 return blink::WebPrintScalingOptionFitToPrintableArea
;
401 PrintMsg_Print_Params
CalculatePrintParamsForCss(
402 blink::WebFrame
* frame
,
404 const PrintMsg_Print_Params
& page_params
,
405 bool ignore_css_margins
,
407 double* scale_factor
) {
408 PrintMsg_Print_Params css_params
=
409 GetCssPrintParams(frame
, page_index
, page_params
);
411 PrintMsg_Print_Params params
= page_params
;
412 EnsureOrientationMatches(css_params
, ¶ms
);
414 if (ignore_css_margins
&& fit_to_page
)
417 PrintMsg_Print_Params result_params
= css_params
;
418 if (ignore_css_margins
) {
419 result_params
.margin_top
= params
.margin_top
;
420 result_params
.margin_left
= params
.margin_left
;
422 DCHECK(!fit_to_page
);
423 // Since we are ignoring the margins, the css page size is no longer
425 int default_margin_right
= params
.page_size
.width() -
426 params
.content_size
.width() - params
.margin_left
;
427 int default_margin_bottom
= params
.page_size
.height() -
428 params
.content_size
.height() -
430 result_params
.content_size
=
431 gfx::Size(result_params
.page_size
.width() - result_params
.margin_left
-
432 default_margin_right
,
433 result_params
.page_size
.height() - result_params
.margin_top
-
434 default_margin_bottom
);
438 double factor
= FitPrintParamsToPage(params
, &result_params
);
440 *scale_factor
= factor
;
442 return result_params
;
447 FrameReference::FrameReference(blink::WebLocalFrame
* frame
) {
451 FrameReference::FrameReference() {
455 FrameReference::~FrameReference() {
458 void FrameReference::Reset(blink::WebLocalFrame
* frame
) {
460 view_
= frame
->view();
468 blink::WebLocalFrame
* FrameReference::GetFrame() {
469 if (view_
== NULL
|| frame_
== NULL
)
471 for (blink::WebFrame
* frame
= view_
->mainFrame(); frame
!= NULL
;
472 frame
= frame
->traverseNext(false)) {
479 blink::WebView
* FrameReference::view() {
483 #if defined(ENABLE_PRINT_PREVIEW)
484 // static - Not anonymous so that platform implementations can use it.
485 void PrintWebViewHelper::PrintHeaderAndFooter(
486 blink::WebCanvas
* canvas
,
489 const blink::WebFrame
& source_frame
,
490 float webkit_scale_factor
,
491 const PageSizeMargins
& page_layout
,
492 const PrintMsg_Print_Params
& params
) {
493 SkAutoCanvasRestore
auto_restore(canvas
, true);
494 canvas
->scale(1 / webkit_scale_factor
, 1 / webkit_scale_factor
);
496 blink::WebSize
page_size(page_layout
.margin_left
+ page_layout
.margin_right
+
497 page_layout
.content_width
,
498 page_layout
.margin_top
+ page_layout
.margin_bottom
+
499 page_layout
.content_height
);
501 blink::WebView
* web_view
= blink::WebView::create(NULL
);
502 web_view
->settings()->setJavaScriptEnabled(true);
504 blink::WebLocalFrame
* frame
=
505 blink::WebLocalFrame::create(blink::WebTreeScopeType::Document
, NULL
);
506 web_view
->setMainFrame(frame
);
508 base::StringValue
html(ResourceBundle::GetSharedInstance().GetLocalizedString(
509 IDR_PRINT_PREVIEW_PAGE
));
510 // Load page with script to avoid async operations.
511 ExecuteScript(frame
, kPageLoadScriptFormat
, html
);
513 scoped_ptr
<base::DictionaryValue
> options(new base::DictionaryValue());
514 options
.reset(new base::DictionaryValue());
515 options
->SetDouble(kSettingHeaderFooterDate
, base::Time::Now().ToJsTime());
516 options
->SetDouble("width", page_size
.width
);
517 options
->SetDouble("height", page_size
.height
);
518 options
->SetDouble("topMargin", page_layout
.margin_top
);
519 options
->SetDouble("bottomMargin", page_layout
.margin_bottom
);
520 options
->SetString("pageNumber",
521 base::StringPrintf("%d/%d", page_number
, total_pages
));
523 options
->SetString("url", params
.url
);
524 base::string16 title
= source_frame
.document().title();
525 options
->SetString("title", title
.empty() ? params
.title
: title
);
527 ExecuteScript(frame
, kPageSetupScriptFormat
, *options
);
529 blink::WebPrintParams
webkit_params(page_size
);
530 webkit_params
.printerDPI
= GetDPI(¶ms
);
532 frame
->printBegin(webkit_params
);
533 frame
->printPage(0, canvas
);
539 #endif // defined(ENABLE_PRINT_PREVIEW)
541 // static - Not anonymous so that platform implementations can use it.
542 float PrintWebViewHelper::RenderPageContent(blink::WebFrame
* frame
,
544 const gfx::Rect
& canvas_area
,
545 const gfx::Rect
& content_area
,
547 blink::WebCanvas
* canvas
) {
548 SkAutoCanvasRestore
auto_restore(canvas
, true);
549 canvas
->translate((content_area
.x() - canvas_area
.x()) / scale_factor
,
550 (content_area
.y() - canvas_area
.y()) / scale_factor
);
551 return frame
->printPage(page_number
, canvas
);
554 // Class that calls the Begin and End print functions on the frame and changes
555 // the size of the view temporarily to support full page printing..
556 class PrepareFrameAndViewForPrint
: public blink::WebViewClient
,
557 public blink::WebFrameClient
{
559 PrepareFrameAndViewForPrint(const PrintMsg_Print_Params
& params
,
560 blink::WebLocalFrame
* frame
,
561 const blink::WebNode
& node
,
562 bool ignore_css_margins
);
563 virtual ~PrepareFrameAndViewForPrint();
565 // Optional. Replaces |frame_| with selection if needed. Will call |on_ready|
567 void CopySelectionIfNeeded(const WebPreferences
& preferences
,
568 const base::Closure
& on_ready
);
570 // Prepares frame for printing.
571 void StartPrinting();
573 blink::WebLocalFrame
* frame() { return frame_
.GetFrame(); }
575 const blink::WebNode
& node() const { return node_to_print_
; }
577 int GetExpectedPageCount() const { return expected_pages_count_
; }
579 void FinishPrinting();
581 bool IsLoadingSelection() {
582 // It's not selection if not |owns_web_view_|.
583 return owns_web_view_
&& frame() && frame()->isLoading();
586 // TODO(ojan): Remove this override and have this class use a non-null
588 // blink::WebViewClient override:
589 virtual bool allowsBrokenNullLayerTreeView() const;
592 // blink::WebViewClient override:
593 virtual void didStopLoading();
595 // blink::WebFrameClient override:
596 virtual blink::WebFrame
* createChildFrame(
597 blink::WebLocalFrame
* parent
,
598 blink::WebTreeScopeType scope
,
599 const blink::WebString
& name
,
600 blink::WebSandboxFlags sandboxFlags
);
601 virtual void frameDetached(blink::WebFrame
* frame
, DetachType type
);
605 void ResizeForPrinting();
607 void CopySelection(const WebPreferences
& preferences
);
609 FrameReference frame_
;
610 blink::WebNode node_to_print_
;
612 blink::WebPrintParams web_print_params_
;
613 gfx::Size prev_view_size_
;
614 gfx::Size prev_scroll_offset_
;
615 int expected_pages_count_
;
616 base::Closure on_ready_
;
617 bool should_print_backgrounds_
;
618 bool should_print_selection_only_
;
619 bool is_printing_started_
;
621 base::WeakPtrFactory
<PrepareFrameAndViewForPrint
> weak_ptr_factory_
;
623 DISALLOW_COPY_AND_ASSIGN(PrepareFrameAndViewForPrint
);
626 PrepareFrameAndViewForPrint::PrepareFrameAndViewForPrint(
627 const PrintMsg_Print_Params
& params
,
628 blink::WebLocalFrame
* frame
,
629 const blink::WebNode
& node
,
630 bool ignore_css_margins
)
632 node_to_print_(node
),
633 owns_web_view_(false),
634 expected_pages_count_(0),
635 should_print_backgrounds_(params
.should_print_backgrounds
),
636 should_print_selection_only_(params
.selection_only
),
637 is_printing_started_(false),
638 weak_ptr_factory_(this) {
639 PrintMsg_Print_Params print_params
= params
;
640 if (!should_print_selection_only_
||
641 !PrintingNodeOrPdfFrame(frame
, node_to_print_
)) {
642 bool fit_to_page
= ignore_css_margins
&&
643 print_params
.print_scaling_option
==
644 blink::WebPrintScalingOptionFitToPrintableArea
;
645 ComputeWebKitPrintParamsInDesiredDpi(params
, &web_print_params_
);
646 frame
->printBegin(web_print_params_
, node_to_print_
);
647 print_params
= CalculatePrintParamsForCss(
648 frame
, 0, print_params
, ignore_css_margins
, fit_to_page
, NULL
);
651 ComputeWebKitPrintParamsInDesiredDpi(print_params
, &web_print_params_
);
654 PrepareFrameAndViewForPrint::~PrepareFrameAndViewForPrint() {
658 void PrepareFrameAndViewForPrint::ResizeForPrinting() {
659 // Layout page according to printer page size. Since WebKit shrinks the
660 // size of the page automatically (from 125% to 200%) we trick it to
661 // think the page is 125% larger so the size of the page is correct for
662 // minimum (default) scaling.
663 // This is important for sites that try to fill the page.
664 gfx::Size
print_layout_size(web_print_params_
.printContentArea
.width
,
665 web_print_params_
.printContentArea
.height
);
666 print_layout_size
.set_height(
667 static_cast<int>(static_cast<double>(print_layout_size
.height()) * 1.25));
671 blink::WebView
* web_view
= frame_
.view();
672 // Backup size and offset.
673 if (blink::WebFrame
* web_frame
= web_view
->mainFrame())
674 prev_scroll_offset_
= web_frame
->scrollOffset();
675 prev_view_size_
= web_view
->size();
677 web_view
->resize(print_layout_size
);
680 void PrepareFrameAndViewForPrint::StartPrinting() {
682 blink::WebView
* web_view
= frame_
.view();
683 web_view
->settings()->setShouldPrintBackgrounds(should_print_backgrounds_
);
684 expected_pages_count_
=
685 frame()->printBegin(web_print_params_
, node_to_print_
);
686 is_printing_started_
= true;
689 void PrepareFrameAndViewForPrint::CopySelectionIfNeeded(
690 const WebPreferences
& preferences
,
691 const base::Closure
& on_ready
) {
692 on_ready_
= on_ready
;
693 if (should_print_selection_only_
) {
694 CopySelection(preferences
);
696 // Call immediately, async call crashes scripting printing.
701 void PrepareFrameAndViewForPrint::CopySelection(
702 const WebPreferences
& preferences
) {
704 std::string url_str
= "data:text/html;charset=utf-8,";
706 net::EscapeQueryParamValue(frame()->selectionAsMarkup().utf8(), false));
708 // Create a new WebView with the same settings as the current display one.
709 // Except that we disable javascript (don't want any active content running
711 WebPreferences prefs
= preferences
;
712 prefs
.javascript_enabled
= false;
714 blink::WebView
* web_view
= blink::WebView::create(this);
715 owns_web_view_
= true;
716 content::RenderView::ApplyWebPreferences(prefs
, web_view
);
717 web_view
->setMainFrame(
718 blink::WebLocalFrame::create(blink::WebTreeScopeType::Document
, this));
719 frame_
.Reset(web_view
->mainFrame()->toWebLocalFrame());
720 node_to_print_
.reset();
722 // When loading is done this will call didStopLoading() and that will do the
724 frame()->loadRequest(blink::WebURLRequest(GURL(url_str
)));
727 bool PrepareFrameAndViewForPrint::allowsBrokenNullLayerTreeView() const {
731 void PrepareFrameAndViewForPrint::didStopLoading() {
732 DCHECK(!on_ready_
.is_null());
733 // Don't call callback here, because it can delete |this| and WebView that is
734 // called didStopLoading.
735 base::ThreadTaskRunnerHandle::Get()->PostTask(
736 FROM_HERE
, base::Bind(&PrepareFrameAndViewForPrint::CallOnReady
,
737 weak_ptr_factory_
.GetWeakPtr()));
740 blink::WebFrame
* PrepareFrameAndViewForPrint::createChildFrame(
741 blink::WebLocalFrame
* parent
,
742 blink::WebTreeScopeType scope
,
743 const blink::WebString
& name
,
744 blink::WebSandboxFlags sandboxFlags
) {
745 blink::WebFrame
* frame
= blink::WebLocalFrame::create(scope
, this);
746 parent
->appendChild(frame
);
750 void PrepareFrameAndViewForPrint::frameDetached(blink::WebFrame
* frame
,
752 DCHECK(type
== DetachType::Remove
);
754 frame
->parent()->removeChild(frame
);
758 void PrepareFrameAndViewForPrint::CallOnReady() {
759 return on_ready_
.Run(); // Can delete |this|.
762 void PrepareFrameAndViewForPrint::RestoreSize() {
764 blink::WebView
* web_view
= frame_
.GetFrame()->view();
765 web_view
->resize(prev_view_size_
);
766 if (blink::WebFrame
* web_frame
= web_view
->mainFrame())
767 web_frame
->setScrollOffset(prev_scroll_offset_
);
771 void PrepareFrameAndViewForPrint::FinishPrinting() {
772 blink::WebLocalFrame
* frame
= frame_
.GetFrame();
774 blink::WebView
* web_view
= frame
->view();
775 if (is_printing_started_
) {
776 is_printing_started_
= false;
778 if (!owns_web_view_
) {
779 web_view
->settings()->setShouldPrintBackgrounds(false);
783 if (owns_web_view_
) {
784 DCHECK(!frame
->isLoading());
785 owns_web_view_
= false;
793 bool PrintWebViewHelper::Delegate::IsAskPrintSettingsEnabled() {
797 bool PrintWebViewHelper::Delegate::IsScriptedPrintEnabled() {
801 PrintWebViewHelper::PrintWebViewHelper(content::RenderView
* render_view
,
802 scoped_ptr
<Delegate
> delegate
)
803 : content::RenderViewObserver(render_view
),
804 content::RenderViewObserverTracker
<PrintWebViewHelper
>(render_view
),
805 reset_prep_frame_view_(false),
806 is_print_ready_metafile_sent_(false),
807 ignore_css_margins_(false),
808 is_scripted_printing_blocked_(false),
809 notify_browser_of_print_failure_(true),
810 print_for_preview_(false),
811 delegate_(delegate
.Pass()),
812 print_node_in_progress_(false),
814 is_scripted_preview_delayed_(false),
815 ipc_nesting_level_(0),
816 weak_ptr_factory_(this) {
817 if (!delegate_
->IsPrintPreviewEnabled())
821 PrintWebViewHelper::~PrintWebViewHelper() {
825 void PrintWebViewHelper::DisablePreview() {
826 g_is_preview_enabled_
= false;
829 bool PrintWebViewHelper::IsScriptInitiatedPrintAllowed(blink::WebFrame
* frame
,
830 bool user_initiated
) {
831 if (!delegate_
->IsScriptedPrintEnabled())
834 // If preview is enabled, then the print dialog is tab modal, and the user
835 // can always close the tab on a mis-behaving page (the system print dialog
836 // is app modal). If the print was initiated through user action, don't
837 // throttle. Or, if the command line flag to skip throttling has been set.
838 return !is_scripted_printing_blocked_
&&
839 (user_initiated
|| g_is_preview_enabled_
||
840 scripting_throttler_
.IsAllowed(frame
));
843 void PrintWebViewHelper::DidStartLoading() {
847 void PrintWebViewHelper::DidStopLoading() {
849 if (!on_stop_loading_closure_
.is_null()) {
850 on_stop_loading_closure_
.Run();
851 on_stop_loading_closure_
.Reset();
855 // Prints |frame| which called window.print().
856 void PrintWebViewHelper::PrintPage(blink::WebLocalFrame
* frame
,
857 bool user_initiated
) {
860 // Allow Prerendering to cancel this print request if necessary.
861 if (delegate_
->CancelPrerender(render_view(), routing_id()))
864 if (!IsScriptInitiatedPrintAllowed(frame
, user_initiated
))
867 if (delegate_
->OverridePrint(frame
))
870 if (!g_is_preview_enabled_
) {
871 Print(frame
, blink::WebNode(), true);
873 print_preview_context_
.InitWithFrame(frame
);
874 RequestPrintPreview(PRINT_PREVIEW_SCRIPTED
);
878 bool PrintWebViewHelper::OnMessageReceived(const IPC::Message
& message
) {
879 // The class is not designed to handle recursive messages. This is not
880 // expected during regular flow. However, during rendering of content for
881 // printing, lower level code may run nested message loop. E.g. PDF may has
882 // script to show message box http://crbug.com/502562. In that moment browser
883 // may receive updated printer capabilities and decide to restart print
884 // preview generation. When this happened message handling function may
885 // choose to ignore message or safely crash process.
886 ++ipc_nesting_level_
;
889 IPC_BEGIN_MESSAGE_MAP(PrintWebViewHelper
, message
)
890 #if defined(ENABLE_BASIC_PRINTING)
891 IPC_MESSAGE_HANDLER(PrintMsg_PrintPages
, OnPrintPages
)
892 IPC_MESSAGE_HANDLER(PrintMsg_PrintForSystemDialog
, OnPrintForSystemDialog
)
893 #endif // ENABLE_BASIC_PRINTING
894 IPC_MESSAGE_HANDLER(PrintMsg_InitiatePrintPreview
, OnInitiatePrintPreview
)
895 IPC_MESSAGE_HANDLER(PrintMsg_PrintPreview
, OnPrintPreview
)
896 IPC_MESSAGE_HANDLER(PrintMsg_PrintForPrintPreview
, OnPrintForPrintPreview
)
897 IPC_MESSAGE_HANDLER(PrintMsg_PrintingDone
, OnPrintingDone
)
898 IPC_MESSAGE_HANDLER(PrintMsg_SetScriptedPrintingBlocked
,
899 SetScriptedPrintBlocked
)
900 IPC_MESSAGE_UNHANDLED(handled
= false)
901 IPC_END_MESSAGE_MAP()
903 --ipc_nesting_level_
;
907 void PrintWebViewHelper::OnPrintForPrintPreview(
908 const base::DictionaryValue
& job_settings
) {
909 CHECK_LE(ipc_nesting_level_
, 1);
910 // If still not finished with earlier print request simply ignore.
911 if (prep_frame_view_
)
914 if (!render_view()->GetWebView())
916 blink::WebFrame
* main_frame
= render_view()->GetWebView()->mainFrame();
920 blink::WebDocument document
= main_frame
->document();
921 // <object>/<iframe> with id="pdf-viewer" is created in
922 // chrome/browser/resources/print_preview/print_preview.js
923 blink::WebElement pdf_element
= document
.getElementById("pdf-viewer");
924 if (pdf_element
.isNull()) {
929 // The out-of-process plugin element is nested within a frame. In tests, there
930 // may not be an iframe containing the out-of-process plugin, so continue with
931 // the element with ID "pdf-viewer" if it isn't an iframe.
932 blink::WebLocalFrame
* plugin_frame
= pdf_element
.document().frame();
933 blink::WebElement plugin_element
= pdf_element
;
934 if (pdf_element
.hasHTMLTagName("iframe")) {
935 plugin_frame
= blink::WebLocalFrame::fromFrameOwnerElement(pdf_element
);
936 plugin_element
= delegate_
->GetPdfElement(plugin_frame
);
937 if (plugin_element
.isNull()) {
943 // Set |print_for_preview_| flag and autoreset it to back to original
945 base::AutoReset
<bool> set_printing_flag(&print_for_preview_
, true);
947 if (!UpdatePrintSettings(plugin_frame
, plugin_element
, job_settings
)) {
948 LOG(ERROR
) << "UpdatePrintSettings failed";
949 DidFinishPrinting(FAIL_PRINT
);
953 // Print page onto entire page not just printable area. Preview PDF already
954 // has content in correct position taking into account page size and printable
956 // TODO(vitalybuka) : Make this consistent on all platform. This change
957 // affects Windows only. On Linux and OSX RenderPagesForPrint does not use
958 // printable_area. Also we can't change printable_area deeper inside
959 // RenderPagesForPrint for Windows, because it's used also by native
960 // printing and it expects real printable_area value.
961 // See http://crbug.com/123408
962 PrintMsg_Print_Params
& print_params
= print_pages_params_
->params
;
963 print_params
.printable_area
= gfx::Rect(print_params
.page_size
);
965 // Render Pages for printing.
966 if (!RenderPagesForPrint(plugin_frame
, plugin_element
)) {
967 LOG(ERROR
) << "RenderPagesForPrint failed";
968 DidFinishPrinting(FAIL_PRINT
);
972 bool PrintWebViewHelper::GetPrintFrame(blink::WebLocalFrame
** frame
) {
974 blink::WebView
* webView
= render_view()->GetWebView();
979 // If the user has selected text in the currently focused frame we print
980 // only that frame (this makes print selection work for multiple frames).
981 blink::WebLocalFrame
* focusedFrame
=
982 webView
->focusedFrame()->toWebLocalFrame();
983 *frame
= focusedFrame
->hasSelection()
985 : webView
->mainFrame()->toWebLocalFrame();
989 #if defined(ENABLE_BASIC_PRINTING)
990 void PrintWebViewHelper::OnPrintPages() {
991 CHECK_LE(ipc_nesting_level_
, 1);
992 blink::WebLocalFrame
* frame
;
993 if (!GetPrintFrame(&frame
))
995 // If we are printing a PDF extension frame, find the plugin node and print
997 auto plugin
= delegate_
->GetPdfElement(frame
);
998 Print(frame
, plugin
, false);
1001 void PrintWebViewHelper::OnPrintForSystemDialog() {
1002 CHECK_LE(ipc_nesting_level_
, 1);
1003 blink::WebLocalFrame
* frame
= print_preview_context_
.source_frame();
1008 Print(frame
, print_preview_context_
.source_node(), false);
1010 #endif // ENABLE_BASIC_PRINTING
1012 void PrintWebViewHelper::GetPageSizeAndContentAreaFromPageLayout(
1013 const PageSizeMargins
& page_layout_in_points
,
1014 gfx::Size
* page_size
,
1015 gfx::Rect
* content_area
) {
1016 *page_size
= gfx::Size(
1017 page_layout_in_points
.content_width
+ page_layout_in_points
.margin_right
+
1018 page_layout_in_points
.margin_left
,
1019 page_layout_in_points
.content_height
+ page_layout_in_points
.margin_top
+
1020 page_layout_in_points
.margin_bottom
);
1021 *content_area
= gfx::Rect(page_layout_in_points
.margin_left
,
1022 page_layout_in_points
.margin_top
,
1023 page_layout_in_points
.content_width
,
1024 page_layout_in_points
.content_height
);
1027 void PrintWebViewHelper::UpdateFrameMarginsCssInfo(
1028 const base::DictionaryValue
& settings
) {
1029 int margins_type
= 0;
1030 if (!settings
.GetInteger(kSettingMarginsType
, &margins_type
))
1031 margins_type
= DEFAULT_MARGINS
;
1032 ignore_css_margins_
= (margins_type
!= DEFAULT_MARGINS
);
1035 bool PrintWebViewHelper::IsPrintToPdfRequested(
1036 const base::DictionaryValue
& job_settings
) {
1037 bool print_to_pdf
= false;
1038 if (!job_settings
.GetBoolean(kSettingPrintToPDF
, &print_to_pdf
))
1040 return print_to_pdf
;
1043 void PrintWebViewHelper::OnPrintPreview(const base::DictionaryValue
& settings
) {
1044 CHECK_LE(ipc_nesting_level_
, 1);
1046 print_preview_context_
.OnPrintPreview();
1048 UMA_HISTOGRAM_ENUMERATION("PrintPreview.PreviewEvent",
1049 PREVIEW_EVENT_REQUESTED
, PREVIEW_EVENT_MAX
);
1051 if (!print_preview_context_
.source_frame()) {
1052 DidFinishPrinting(FAIL_PREVIEW
);
1056 if (!UpdatePrintSettings(print_preview_context_
.source_frame(),
1057 print_preview_context_
.source_node(), settings
)) {
1058 if (print_preview_context_
.last_error() != PREVIEW_ERROR_BAD_SETTING
) {
1059 Send(new PrintHostMsg_PrintPreviewInvalidPrinterSettings(
1060 routing_id(), print_pages_params_
1061 ? print_pages_params_
->params
.document_cookie
1063 notify_browser_of_print_failure_
= false; // Already sent.
1065 DidFinishPrinting(FAIL_PREVIEW
);
1069 // Set the options from document if we are previewing a pdf and send a
1070 // message to browser.
1071 if (print_pages_params_
->params
.is_first_request
&&
1072 !print_preview_context_
.IsModifiable()) {
1073 PrintHostMsg_SetOptionsFromDocument_Params options
;
1074 if (SetOptionsFromPdfDocument(&options
))
1075 Send(new PrintHostMsg_SetOptionsFromDocument(routing_id(), options
));
1078 is_print_ready_metafile_sent_
= false;
1080 // PDF printer device supports alpha blending.
1081 print_pages_params_
->params
.supports_alpha_blend
= true;
1083 bool generate_draft_pages
= false;
1084 if (!settings
.GetBoolean(kSettingGenerateDraftData
, &generate_draft_pages
)) {
1087 print_preview_context_
.set_generate_draft_pages(generate_draft_pages
);
1089 PrepareFrameForPreviewDocument();
1092 void PrintWebViewHelper::PrepareFrameForPreviewDocument() {
1093 reset_prep_frame_view_
= false;
1095 if (!print_pages_params_
|| CheckForCancel()) {
1096 DidFinishPrinting(FAIL_PREVIEW
);
1100 // Don't reset loading frame or WebKit will fail assert. Just retry when
1101 // current selection is loaded.
1102 if (prep_frame_view_
&& prep_frame_view_
->IsLoadingSelection()) {
1103 reset_prep_frame_view_
= true;
1107 const PrintMsg_Print_Params
& print_params
= print_pages_params_
->params
;
1108 prep_frame_view_
.reset(new PrepareFrameAndViewForPrint(
1109 print_params
, print_preview_context_
.source_frame(),
1110 print_preview_context_
.source_node(), ignore_css_margins_
));
1111 prep_frame_view_
->CopySelectionIfNeeded(
1112 render_view()->GetWebkitPreferences(),
1113 base::Bind(&PrintWebViewHelper::OnFramePreparedForPreviewDocument
,
1114 base::Unretained(this)));
1117 void PrintWebViewHelper::OnFramePreparedForPreviewDocument() {
1118 if (reset_prep_frame_view_
) {
1119 PrepareFrameForPreviewDocument();
1122 DidFinishPrinting(CreatePreviewDocument() ? OK
: FAIL_PREVIEW
);
1125 bool PrintWebViewHelper::CreatePreviewDocument() {
1126 if (!print_pages_params_
|| CheckForCancel())
1129 UMA_HISTOGRAM_ENUMERATION("PrintPreview.PreviewEvent",
1130 PREVIEW_EVENT_CREATE_DOCUMENT
, PREVIEW_EVENT_MAX
);
1132 const PrintMsg_Print_Params
& print_params
= print_pages_params_
->params
;
1133 const std::vector
<int>& pages
= print_pages_params_
->pages
;
1135 if (!print_preview_context_
.CreatePreviewDocument(prep_frame_view_
.release(),
1140 PageSizeMargins default_page_layout
;
1141 ComputePageLayoutInPointsForCss(print_preview_context_
.prepared_frame(), 0,
1142 print_params
, ignore_css_margins_
, NULL
,
1143 &default_page_layout
);
1145 bool has_page_size_style
=
1146 PrintingFrameHasPageSizeStyle(print_preview_context_
.prepared_frame(),
1147 print_preview_context_
.total_page_count());
1148 int dpi
= GetDPI(&print_params
);
1150 gfx::Rect
printable_area_in_points(
1151 ConvertUnit(print_params
.printable_area
.x(), dpi
, kPointsPerInch
),
1152 ConvertUnit(print_params
.printable_area
.y(), dpi
, kPointsPerInch
),
1153 ConvertUnit(print_params
.printable_area
.width(), dpi
, kPointsPerInch
),
1154 ConvertUnit(print_params
.printable_area
.height(), dpi
, kPointsPerInch
));
1156 // Margins: Send default page layout to browser process.
1157 Send(new PrintHostMsg_DidGetDefaultPageLayout(routing_id(),
1158 default_page_layout
,
1159 printable_area_in_points
,
1160 has_page_size_style
));
1162 PrintHostMsg_DidGetPreviewPageCount_Params params
;
1163 params
.page_count
= print_preview_context_
.total_page_count();
1164 params
.is_modifiable
= print_preview_context_
.IsModifiable();
1165 params
.document_cookie
= print_params
.document_cookie
;
1166 params
.preview_request_id
= print_params
.preview_request_id
;
1167 params
.clear_preview_data
= print_preview_context_
.generate_draft_pages();
1168 Send(new PrintHostMsg_DidGetPreviewPageCount(routing_id(), params
));
1169 if (CheckForCancel())
1172 while (!print_preview_context_
.IsFinalPageRendered()) {
1173 int page_number
= print_preview_context_
.GetNextPageNumber();
1174 DCHECK_GE(page_number
, 0);
1175 if (!RenderPreviewPage(page_number
, print_params
))
1178 if (CheckForCancel())
1181 // We must call PrepareFrameAndViewForPrint::FinishPrinting() (by way of
1182 // print_preview_context_.AllPagesRendered()) before calling
1183 // FinalizePrintReadyDocument() when printing a PDF because the plugin
1184 // code does not generate output until we call FinishPrinting(). We do not
1185 // generate draft pages for PDFs, so IsFinalPageRendered() and
1186 // IsLastPageOfPrintReadyMetafile() will be true in the same iteration of
1188 if (print_preview_context_
.IsFinalPageRendered())
1189 print_preview_context_
.AllPagesRendered();
1191 if (print_preview_context_
.IsLastPageOfPrintReadyMetafile()) {
1192 DCHECK(print_preview_context_
.IsModifiable() ||
1193 print_preview_context_
.IsFinalPageRendered());
1194 if (!FinalizePrintReadyDocument())
1198 print_preview_context_
.Finished();
1202 bool PrintWebViewHelper::FinalizePrintReadyDocument() {
1203 DCHECK(!is_print_ready_metafile_sent_
);
1204 print_preview_context_
.FinalizePrintReadyDocument();
1206 // Get the size of the resulting metafile.
1207 PdfMetafileSkia
* metafile
= print_preview_context_
.metafile();
1208 uint32 buf_size
= metafile
->GetDataSize();
1209 DCHECK_GT(buf_size
, 0u);
1211 PrintHostMsg_DidPreviewDocument_Params preview_params
;
1212 preview_params
.data_size
= buf_size
;
1213 preview_params
.document_cookie
= print_pages_params_
->params
.document_cookie
;
1214 preview_params
.expected_pages_count
=
1215 print_preview_context_
.total_page_count();
1216 preview_params
.modifiable
= print_preview_context_
.IsModifiable();
1217 preview_params
.preview_request_id
=
1218 print_pages_params_
->params
.preview_request_id
;
1220 // Ask the browser to create the shared memory for us.
1221 if (!CopyMetafileDataToSharedMem(metafile
,
1222 &(preview_params
.metafile_data_handle
))) {
1223 LOG(ERROR
) << "CopyMetafileDataToSharedMem failed";
1224 print_preview_context_
.set_error(PREVIEW_ERROR_METAFILE_COPY_FAILED
);
1227 is_print_ready_metafile_sent_
= true;
1229 Send(new PrintHostMsg_MetafileReadyForPrinting(routing_id(), preview_params
));
1233 void PrintWebViewHelper::OnPrintingDone(bool success
) {
1234 CHECK_LE(ipc_nesting_level_
, 1);
1235 notify_browser_of_print_failure_
= false;
1237 LOG(ERROR
) << "Failure in OnPrintingDone";
1238 DidFinishPrinting(success
? OK
: FAIL_PRINT
);
1241 void PrintWebViewHelper::SetScriptedPrintBlocked(bool blocked
) {
1242 is_scripted_printing_blocked_
= blocked
;
1245 void PrintWebViewHelper::OnInitiatePrintPreview(bool selection_only
) {
1246 CHECK_LE(ipc_nesting_level_
, 1);
1247 blink::WebLocalFrame
* frame
= NULL
;
1248 GetPrintFrame(&frame
);
1250 // If we are printing a PDF extension frame, find the plugin node and print
1252 auto plugin
= delegate_
->GetPdfElement(frame
);
1253 if (!plugin
.isNull()) {
1257 print_preview_context_
.InitWithFrame(frame
);
1258 RequestPrintPreview(selection_only
1259 ? PRINT_PREVIEW_USER_INITIATED_SELECTION
1260 : PRINT_PREVIEW_USER_INITIATED_ENTIRE_FRAME
);
1263 bool PrintWebViewHelper::IsPrintingEnabled() {
1264 bool result
= false;
1265 Send(new PrintHostMsg_IsPrintingEnabled(routing_id(), &result
));
1269 void PrintWebViewHelper::PrintNode(const blink::WebNode
& node
) {
1270 if (node
.isNull() || !node
.document().frame()) {
1271 // This can occur when the context menu refers to an invalid WebNode.
1272 // See http://crbug.com/100890#c17 for a repro case.
1276 if (print_node_in_progress_
) {
1277 // This can happen as a result of processing sync messages when printing
1278 // from ppapi plugins. It's a rare case, so its OK to just fail here.
1279 // See http://crbug.com/159165.
1283 print_node_in_progress_
= true;
1285 // Make a copy of the node, in case RenderView::OnContextMenuClosed resets
1286 // its |context_menu_node_|.
1287 if (!g_is_preview_enabled_
) {
1288 blink::WebNode
duplicate_node(node
);
1289 Print(duplicate_node
.document().frame(), duplicate_node
, false);
1291 print_preview_context_
.InitWithNode(node
);
1292 RequestPrintPreview(PRINT_PREVIEW_USER_INITIATED_CONTEXT_NODE
);
1295 print_node_in_progress_
= false;
1298 void PrintWebViewHelper::Print(blink::WebLocalFrame
* frame
,
1299 const blink::WebNode
& node
,
1301 // If still not finished with earlier print request simply ignore.
1302 if (prep_frame_view_
)
1305 FrameReference
frame_ref(frame
);
1307 int expected_page_count
= 0;
1308 if (!CalculateNumberOfPages(frame
, node
, &expected_page_count
)) {
1309 DidFinishPrinting(FAIL_PRINT_INIT
);
1310 return; // Failed to init print page settings.
1313 // Some full screen plugins can say they don't want to print.
1314 if (!expected_page_count
) {
1315 DidFinishPrinting(FAIL_PRINT
);
1319 // Ask the browser to show UI to retrieve the final print settings.
1320 if (delegate_
->IsAskPrintSettingsEnabled() &&
1321 !GetPrintSettingsFromUser(frame_ref
.GetFrame(), node
, expected_page_count
,
1323 DidFinishPrinting(OK
); // Release resources and fail silently.
1327 // Render Pages for printing.
1328 if (!RenderPagesForPrint(frame_ref
.GetFrame(), node
)) {
1329 LOG(ERROR
) << "RenderPagesForPrint failed";
1330 DidFinishPrinting(FAIL_PRINT
);
1332 scripting_throttler_
.Reset();
1335 void PrintWebViewHelper::DidFinishPrinting(PrintingResult result
) {
1340 case FAIL_PRINT_INIT
:
1341 DCHECK(!notify_browser_of_print_failure_
);
1345 if (notify_browser_of_print_failure_
&& print_pages_params_
) {
1346 int cookie
= print_pages_params_
->params
.document_cookie
;
1347 Send(new PrintHostMsg_PrintingFailed(routing_id(), cookie
));
1353 print_pages_params_
? print_pages_params_
->params
.document_cookie
: 0;
1354 if (notify_browser_of_print_failure_
) {
1355 LOG(ERROR
) << "CreatePreviewDocument failed";
1356 Send(new PrintHostMsg_PrintPreviewFailed(routing_id(), cookie
));
1358 Send(new PrintHostMsg_PrintPreviewCancelled(routing_id(), cookie
));
1360 print_preview_context_
.Failed(notify_browser_of_print_failure_
);
1363 prep_frame_view_
.reset();
1364 print_pages_params_
.reset();
1365 notify_browser_of_print_failure_
= true;
1368 void PrintWebViewHelper::OnFramePreparedForPrintPages() {
1370 FinishFramePrinting();
1373 void PrintWebViewHelper::PrintPages() {
1374 if (!prep_frame_view_
) // Printing is already canceled or failed.
1376 prep_frame_view_
->StartPrinting();
1378 int page_count
= prep_frame_view_
->GetExpectedPageCount();
1380 LOG(ERROR
) << "Can't print 0 pages.";
1381 return DidFinishPrinting(FAIL_PRINT
);
1384 const PrintMsg_PrintPages_Params
& params
= *print_pages_params_
;
1385 const PrintMsg_Print_Params
& print_params
= params
.params
;
1387 #if !defined(OS_CHROMEOS) && !defined(OS_ANDROID)
1388 // TODO(vitalybuka): should be page_count or valid pages from params.pages.
1389 // See http://crbug.com/161576
1390 Send(new PrintHostMsg_DidGetPrintedPagesCount(routing_id(),
1391 print_params
.document_cookie
,
1393 #endif // !defined(OS_CHROMEOS)
1395 if (print_params
.preview_ui_id
< 0) {
1396 // Printing for system dialog.
1397 int printed_count
= params
.pages
.empty() ? page_count
: params
.pages
.size();
1398 #if !defined(OS_CHROMEOS)
1399 UMA_HISTOGRAM_COUNTS("PrintPreview.PageCount.SystemDialog", printed_count
);
1401 UMA_HISTOGRAM_COUNTS("PrintPreview.PageCount.PrintToCloudPrintWebDialog",
1403 #endif // !defined(OS_CHROMEOS)
1406 if (!PrintPagesNative(prep_frame_view_
->frame(), page_count
)) {
1407 LOG(ERROR
) << "Printing failed.";
1408 return DidFinishPrinting(FAIL_PRINT
);
1412 void PrintWebViewHelper::FinishFramePrinting() {
1413 prep_frame_view_
.reset();
1416 #if defined(OS_MACOSX)
1417 bool PrintWebViewHelper::PrintPagesNative(blink::WebFrame
* frame
,
1419 const PrintMsg_PrintPages_Params
& params
= *print_pages_params_
;
1420 const PrintMsg_Print_Params
& print_params
= params
.params
;
1422 PrintMsg_PrintPage_Params page_params
;
1423 page_params
.params
= print_params
;
1424 if (params
.pages
.empty()) {
1425 for (int i
= 0; i
< page_count
; ++i
) {
1426 page_params
.page_number
= i
;
1427 PrintPageInternal(page_params
, frame
);
1430 for (size_t i
= 0; i
< params
.pages
.size(); ++i
) {
1431 if (params
.pages
[i
] >= page_count
)
1433 page_params
.page_number
= params
.pages
[i
];
1434 PrintPageInternal(page_params
, frame
);
1442 // static - Not anonymous so that platform implementations can use it.
1443 void PrintWebViewHelper::ComputePageLayoutInPointsForCss(
1444 blink::WebFrame
* frame
,
1446 const PrintMsg_Print_Params
& page_params
,
1447 bool ignore_css_margins
,
1448 double* scale_factor
,
1449 PageSizeMargins
* page_layout_in_points
) {
1450 PrintMsg_Print_Params params
= CalculatePrintParamsForCss(
1451 frame
, page_index
, page_params
, ignore_css_margins
,
1452 page_params
.print_scaling_option
==
1453 blink::WebPrintScalingOptionFitToPrintableArea
,
1455 CalculatePageLayoutFromPrintParams(params
, page_layout_in_points
);
1458 bool PrintWebViewHelper::InitPrintSettings(bool fit_to_paper_size
) {
1459 PrintMsg_PrintPages_Params settings
;
1460 Send(new PrintHostMsg_GetDefaultPrintSettings(routing_id(),
1462 // Check if the printer returned any settings, if the settings is empty, we
1463 // can safely assume there are no printer drivers configured. So we safely
1466 if (!PrintMsg_Print_Params_IsValid(settings
.params
))
1469 // Reset to default values.
1470 ignore_css_margins_
= false;
1471 settings
.pages
.clear();
1473 settings
.params
.print_scaling_option
= blink::WebPrintScalingOptionSourceSize
;
1474 if (fit_to_paper_size
) {
1475 settings
.params
.print_scaling_option
=
1476 blink::WebPrintScalingOptionFitToPrintableArea
;
1479 SetPrintPagesParams(settings
);
1483 bool PrintWebViewHelper::CalculateNumberOfPages(blink::WebLocalFrame
* frame
,
1484 const blink::WebNode
& node
,
1485 int* number_of_pages
) {
1487 bool fit_to_paper_size
= !(PrintingNodeOrPdfFrame(frame
, node
));
1488 if (!InitPrintSettings(fit_to_paper_size
)) {
1489 notify_browser_of_print_failure_
= false;
1490 Send(new PrintHostMsg_ShowInvalidPrinterSettingsError(routing_id()));
1494 const PrintMsg_Print_Params
& params
= print_pages_params_
->params
;
1495 PrepareFrameAndViewForPrint
prepare(params
, frame
, node
, ignore_css_margins_
);
1496 prepare
.StartPrinting();
1498 *number_of_pages
= prepare
.GetExpectedPageCount();
1502 bool PrintWebViewHelper::SetOptionsFromPdfDocument(
1503 PrintHostMsg_SetOptionsFromDocument_Params
* options
) {
1504 blink::WebLocalFrame
* source_frame
= print_preview_context_
.source_frame();
1505 const blink::WebNode
& source_node
= print_preview_context_
.source_node();
1507 blink::WebPrintPresetOptions preset_options
;
1508 if (!source_frame
->getPrintPresetOptionsForPlugin(source_node
,
1513 options
->is_scaling_disabled
= PDFShouldDisableScalingBasedOnPreset(
1514 preset_options
, print_pages_params_
->params
);
1515 options
->copies
= preset_options
.copies
;
1517 // TODO(thestig) This should be a straight pass-through, but print preview
1518 // does not currently support short-edge printing.
1519 switch (preset_options
.duplexMode
) {
1520 case blink::WebSimplex
:
1521 options
->duplex
= SIMPLEX
;
1523 case blink::WebLongEdge
:
1524 options
->duplex
= LONG_EDGE
;
1527 options
->duplex
= UNKNOWN_DUPLEX_MODE
;
1533 bool PrintWebViewHelper::UpdatePrintSettings(
1534 blink::WebLocalFrame
* frame
,
1535 const blink::WebNode
& node
,
1536 const base::DictionaryValue
& passed_job_settings
) {
1537 const base::DictionaryValue
* job_settings
= &passed_job_settings
;
1538 base::DictionaryValue modified_job_settings
;
1539 if (job_settings
->empty()) {
1540 if (!print_for_preview_
)
1541 print_preview_context_
.set_error(PREVIEW_ERROR_BAD_SETTING
);
1545 bool source_is_html
= true;
1546 if (print_for_preview_
) {
1547 if (!job_settings
->GetBoolean(kSettingPreviewModifiable
, &source_is_html
)) {
1551 source_is_html
= !PrintingNodeOrPdfFrame(frame
, node
);
1554 if (print_for_preview_
|| !source_is_html
) {
1555 modified_job_settings
.MergeDictionary(job_settings
);
1556 modified_job_settings
.SetBoolean(kSettingHeaderFooterEnabled
, false);
1557 modified_job_settings
.SetInteger(kSettingMarginsType
, NO_MARGINS
);
1558 job_settings
= &modified_job_settings
;
1561 // Send the cookie so that UpdatePrintSettings can reuse PrinterQuery when
1564 print_pages_params_
? print_pages_params_
->params
.document_cookie
: 0;
1565 PrintMsg_PrintPages_Params settings
;
1566 bool canceled
= false;
1567 Send(new PrintHostMsg_UpdatePrintSettings(routing_id(), cookie
, *job_settings
,
1568 &settings
, &canceled
));
1570 notify_browser_of_print_failure_
= false;
1574 if (!job_settings
->GetInteger(kPreviewUIID
, &settings
.params
.preview_ui_id
)) {
1576 print_preview_context_
.set_error(PREVIEW_ERROR_BAD_SETTING
);
1580 if (!print_for_preview_
) {
1581 // Validate expected print preview settings.
1582 if (!job_settings
->GetInteger(kPreviewRequestID
,
1583 &settings
.params
.preview_request_id
) ||
1584 !job_settings
->GetBoolean(kIsFirstRequest
,
1585 &settings
.params
.is_first_request
)) {
1587 print_preview_context_
.set_error(PREVIEW_ERROR_BAD_SETTING
);
1591 settings
.params
.print_to_pdf
= IsPrintToPdfRequested(*job_settings
);
1592 UpdateFrameMarginsCssInfo(*job_settings
);
1593 settings
.params
.print_scaling_option
= GetPrintScalingOption(
1594 frame
, node
, source_is_html
, *job_settings
, settings
.params
);
1597 SetPrintPagesParams(settings
);
1599 if (!PrintMsg_Print_Params_IsValid(settings
.params
)) {
1600 if (!print_for_preview_
)
1601 print_preview_context_
.set_error(PREVIEW_ERROR_INVALID_PRINTER_SETTINGS
);
1603 Send(new PrintHostMsg_ShowInvalidPrinterSettingsError(routing_id()));
1611 bool PrintWebViewHelper::GetPrintSettingsFromUser(blink::WebLocalFrame
* frame
,
1612 const blink::WebNode
& node
,
1613 int expected_pages_count
,
1615 PrintHostMsg_ScriptedPrint_Params params
;
1616 PrintMsg_PrintPages_Params print_settings
;
1618 params
.cookie
= print_pages_params_
->params
.document_cookie
;
1619 params
.has_selection
= frame
->hasSelection();
1620 params
.expected_pages_count
= expected_pages_count
;
1621 MarginType margin_type
= DEFAULT_MARGINS
;
1622 if (PrintingNodeOrPdfFrame(frame
, node
)) {
1624 GetMarginsForPdf(frame
, node
, print_pages_params_
->params
);
1626 params
.margin_type
= margin_type
;
1627 params
.is_scripted
= is_scripted
;
1629 Send(new PrintHostMsg_DidShowPrintDialog(routing_id()));
1631 // PrintHostMsg_ScriptedPrint will reset print_scaling_option, so we save the
1632 // value before and restore it afterwards.
1633 blink::WebPrintScalingOption scaling_option
=
1634 print_pages_params_
->params
.print_scaling_option
;
1636 print_pages_params_
.reset();
1637 IPC::SyncMessage
* msg
=
1638 new PrintHostMsg_ScriptedPrint(routing_id(), params
, &print_settings
);
1639 msg
->EnableMessagePumping();
1641 print_settings
.params
.print_scaling_option
= scaling_option
;
1642 SetPrintPagesParams(print_settings
);
1643 return (print_settings
.params
.dpi
&& print_settings
.params
.document_cookie
);
1646 bool PrintWebViewHelper::RenderPagesForPrint(blink::WebLocalFrame
* frame
,
1647 const blink::WebNode
& node
) {
1648 if (!frame
|| prep_frame_view_
)
1650 const PrintMsg_PrintPages_Params
& params
= *print_pages_params_
;
1651 const PrintMsg_Print_Params
& print_params
= params
.params
;
1652 prep_frame_view_
.reset(new PrepareFrameAndViewForPrint(
1653 print_params
, frame
, node
, ignore_css_margins_
));
1654 DCHECK(!print_pages_params_
->params
.selection_only
||
1655 print_pages_params_
->pages
.empty());
1656 prep_frame_view_
->CopySelectionIfNeeded(
1657 render_view()->GetWebkitPreferences(),
1658 base::Bind(&PrintWebViewHelper::OnFramePreparedForPrintPages
,
1659 base::Unretained(this)));
1663 #if defined(OS_POSIX)
1664 bool PrintWebViewHelper::CopyMetafileDataToSharedMem(
1665 PdfMetafileSkia
* metafile
,
1666 base::SharedMemoryHandle
* shared_mem_handle
) {
1667 uint32 buf_size
= metafile
->GetDataSize();
1668 scoped_ptr
<base::SharedMemory
> shared_buf(
1669 content::RenderThread::Get()
1670 ->HostAllocateSharedMemoryBuffer(buf_size
)
1674 if (shared_buf
->Map(buf_size
)) {
1675 metafile
->GetData(shared_buf
->memory(), buf_size
);
1676 return shared_buf
->GiveToProcess(base::GetCurrentProcessHandle(),
1682 #endif // defined(OS_POSIX)
1684 void PrintWebViewHelper::ShowScriptedPrintPreview() {
1685 if (is_scripted_preview_delayed_
) {
1686 is_scripted_preview_delayed_
= false;
1687 Send(new PrintHostMsg_ShowScriptedPrintPreview(
1688 routing_id(), print_preview_context_
.IsModifiable()));
1692 void PrintWebViewHelper::RequestPrintPreview(PrintPreviewRequestType type
) {
1693 const bool is_modifiable
= print_preview_context_
.IsModifiable();
1694 const bool has_selection
= print_preview_context_
.HasSelection();
1695 PrintHostMsg_RequestPrintPreview_Params params
;
1696 params
.is_modifiable
= is_modifiable
;
1697 params
.has_selection
= has_selection
;
1699 case PRINT_PREVIEW_SCRIPTED
: {
1700 // Shows scripted print preview in two stages.
1701 // 1. PrintHostMsg_SetupScriptedPrintPreview blocks this call and JS by
1702 // pumping messages here.
1703 // 2. PrintHostMsg_ShowScriptedPrintPreview shows preview once the
1704 // document has been loaded.
1705 is_scripted_preview_delayed_
= true;
1706 if (is_loading_
&& GetPlugin(print_preview_context_
.source_frame())) {
1707 // Wait for DidStopLoading. Plugins may not know the correct
1708 // |is_modifiable| value until they are fully loaded, which occurs when
1709 // DidStopLoading() is called. Defer showing the preview until then.
1710 on_stop_loading_closure_
=
1711 base::Bind(&PrintWebViewHelper::ShowScriptedPrintPreview
,
1712 base::Unretained(this));
1714 base::ThreadTaskRunnerHandle::Get()->PostTask(
1715 FROM_HERE
, base::Bind(&PrintWebViewHelper::ShowScriptedPrintPreview
,
1716 weak_ptr_factory_
.GetWeakPtr()));
1718 IPC::SyncMessage
* msg
=
1719 new PrintHostMsg_SetupScriptedPrintPreview(routing_id());
1720 msg
->EnableMessagePumping();
1722 is_scripted_preview_delayed_
= false;
1725 case PRINT_PREVIEW_USER_INITIATED_ENTIRE_FRAME
: {
1726 // Wait for DidStopLoading. Continuing with this function while
1727 // |is_loading_| is true will cause print preview to hang when try to
1728 // print a PDF document.
1729 if (is_loading_
&& GetPlugin(print_preview_context_
.source_frame())) {
1730 on_stop_loading_closure_
=
1731 base::Bind(&PrintWebViewHelper::RequestPrintPreview
,
1732 base::Unretained(this), type
);
1738 case PRINT_PREVIEW_USER_INITIATED_SELECTION
: {
1739 DCHECK(has_selection
);
1740 DCHECK(!GetPlugin(print_preview_context_
.source_frame()));
1741 params
.selection_only
= has_selection
;
1744 case PRINT_PREVIEW_USER_INITIATED_CONTEXT_NODE
: {
1745 if (is_loading_
&& GetPlugin(print_preview_context_
.source_frame())) {
1746 on_stop_loading_closure_
=
1747 base::Bind(&PrintWebViewHelper::RequestPrintPreview
,
1748 base::Unretained(this), type
);
1752 params
.webnode_only
= true;
1760 Send(new PrintHostMsg_RequestPrintPreview(routing_id(), params
));
1763 bool PrintWebViewHelper::CheckForCancel() {
1764 const PrintMsg_Print_Params
& print_params
= print_pages_params_
->params
;
1765 bool cancel
= false;
1766 Send(new PrintHostMsg_CheckForCancel(routing_id(),
1767 print_params
.preview_ui_id
,
1768 print_params
.preview_request_id
,
1771 notify_browser_of_print_failure_
= false;
1775 bool PrintWebViewHelper::PreviewPageRendered(int page_number
,
1776 PdfMetafileSkia
* metafile
) {
1777 DCHECK_GE(page_number
, FIRST_PAGE_INDEX
);
1779 // For non-modifiable files, |metafile| should be NULL, so do not bother
1780 // sending a message. If we don't generate draft metafiles, |metafile| is
1782 if (!print_preview_context_
.IsModifiable() ||
1783 !print_preview_context_
.generate_draft_pages()) {
1790 print_preview_context_
.set_error(
1791 PREVIEW_ERROR_PAGE_RENDERED_WITHOUT_METAFILE
);
1795 PrintHostMsg_DidPreviewPage_Params preview_page_params
;
1796 // Get the size of the resulting metafile.
1797 uint32 buf_size
= metafile
->GetDataSize();
1798 DCHECK_GT(buf_size
, 0u);
1799 if (!CopyMetafileDataToSharedMem(
1800 metafile
, &(preview_page_params
.metafile_data_handle
))) {
1801 LOG(ERROR
) << "CopyMetafileDataToSharedMem failed";
1802 print_preview_context_
.set_error(PREVIEW_ERROR_METAFILE_COPY_FAILED
);
1805 preview_page_params
.data_size
= buf_size
;
1806 preview_page_params
.page_number
= page_number
;
1807 preview_page_params
.preview_request_id
=
1808 print_pages_params_
->params
.preview_request_id
;
1810 Send(new PrintHostMsg_DidPreviewPage(routing_id(), preview_page_params
));
1814 PrintWebViewHelper::PrintPreviewContext::PrintPreviewContext()
1815 : total_page_count_(0),
1816 current_page_index_(0),
1817 generate_draft_pages_(true),
1818 print_ready_metafile_page_count_(0),
1819 error_(PREVIEW_ERROR_NONE
),
1820 state_(UNINITIALIZED
) {
1823 PrintWebViewHelper::PrintPreviewContext::~PrintPreviewContext() {
1826 void PrintWebViewHelper::PrintPreviewContext::InitWithFrame(
1827 blink::WebLocalFrame
* web_frame
) {
1829 DCHECK(!IsRendering());
1830 state_
= INITIALIZED
;
1831 source_frame_
.Reset(web_frame
);
1832 source_node_
.reset();
1835 void PrintWebViewHelper::PrintPreviewContext::InitWithNode(
1836 const blink::WebNode
& web_node
) {
1837 DCHECK(!web_node
.isNull());
1838 DCHECK(web_node
.document().frame());
1839 DCHECK(!IsRendering());
1840 state_
= INITIALIZED
;
1841 source_frame_
.Reset(web_node
.document().frame());
1842 source_node_
= web_node
;
1845 void PrintWebViewHelper::PrintPreviewContext::OnPrintPreview() {
1846 DCHECK_EQ(INITIALIZED
, state_
);
1850 bool PrintWebViewHelper::PrintPreviewContext::CreatePreviewDocument(
1851 PrepareFrameAndViewForPrint
* prepared_frame
,
1852 const std::vector
<int>& pages
) {
1853 DCHECK_EQ(INITIALIZED
, state_
);
1856 // Need to make sure old object gets destroyed first.
1857 prep_frame_view_
.reset(prepared_frame
);
1858 prep_frame_view_
->StartPrinting();
1860 total_page_count_
= prep_frame_view_
->GetExpectedPageCount();
1861 if (total_page_count_
== 0) {
1862 LOG(ERROR
) << "CreatePreviewDocument got 0 page count";
1863 set_error(PREVIEW_ERROR_ZERO_PAGES
);
1867 metafile_
.reset(new PdfMetafileSkia
);
1868 if (!metafile_
->Init()) {
1869 set_error(PREVIEW_ERROR_METAFILE_INIT_FAILED
);
1870 LOG(ERROR
) << "PdfMetafileSkia Init failed";
1874 current_page_index_
= 0;
1875 pages_to_render_
= pages
;
1876 // Sort and make unique.
1877 std::sort(pages_to_render_
.begin(), pages_to_render_
.end());
1878 pages_to_render_
.resize(
1879 std::unique(pages_to_render_
.begin(), pages_to_render_
.end()) -
1880 pages_to_render_
.begin());
1881 // Remove invalid pages.
1882 pages_to_render_
.resize(std::lower_bound(pages_to_render_
.begin(),
1883 pages_to_render_
.end(),
1884 total_page_count_
) -
1885 pages_to_render_
.begin());
1886 print_ready_metafile_page_count_
= pages_to_render_
.size();
1887 if (pages_to_render_
.empty()) {
1888 print_ready_metafile_page_count_
= total_page_count_
;
1889 // Render all pages.
1890 for (int i
= 0; i
< total_page_count_
; ++i
)
1891 pages_to_render_
.push_back(i
);
1892 } else if (generate_draft_pages_
) {
1893 int pages_index
= 0;
1894 for (int i
= 0; i
< total_page_count_
; ++i
) {
1895 if (pages_index
< print_ready_metafile_page_count_
&&
1896 i
== pages_to_render_
[pages_index
]) {
1900 pages_to_render_
.push_back(i
);
1904 document_render_time_
= base::TimeDelta();
1905 begin_time_
= base::TimeTicks::Now();
1910 void PrintWebViewHelper::PrintPreviewContext::RenderedPreviewPage(
1911 const base::TimeDelta
& page_time
) {
1912 DCHECK_EQ(RENDERING
, state_
);
1913 document_render_time_
+= page_time
;
1914 UMA_HISTOGRAM_TIMES("PrintPreview.RenderPDFPageTime", page_time
);
1917 void PrintWebViewHelper::PrintPreviewContext::AllPagesRendered() {
1918 DCHECK_EQ(RENDERING
, state_
);
1920 prep_frame_view_
->FinishPrinting();
1923 void PrintWebViewHelper::PrintPreviewContext::FinalizePrintReadyDocument() {
1924 DCHECK(IsRendering());
1926 base::TimeTicks begin_time
= base::TimeTicks::Now();
1927 metafile_
->FinishDocument();
1929 if (print_ready_metafile_page_count_
<= 0) {
1934 UMA_HISTOGRAM_MEDIUM_TIMES("PrintPreview.RenderToPDFTime",
1935 document_render_time_
);
1936 base::TimeDelta total_time
=
1937 (base::TimeTicks::Now() - begin_time
) + document_render_time_
;
1938 UMA_HISTOGRAM_MEDIUM_TIMES("PrintPreview.RenderAndGeneratePDFTime",
1940 UMA_HISTOGRAM_MEDIUM_TIMES("PrintPreview.RenderAndGeneratePDFTimeAvgPerPage",
1941 total_time
/ pages_to_render_
.size());
1944 void PrintWebViewHelper::PrintPreviewContext::Finished() {
1945 DCHECK_EQ(DONE
, state_
);
1946 state_
= INITIALIZED
;
1950 void PrintWebViewHelper::PrintPreviewContext::Failed(bool report_error
) {
1951 DCHECK(state_
== INITIALIZED
|| state_
== RENDERING
);
1952 state_
= INITIALIZED
;
1954 DCHECK_NE(PREVIEW_ERROR_NONE
, error_
);
1955 UMA_HISTOGRAM_ENUMERATION("PrintPreview.RendererError", error_
,
1956 PREVIEW_ERROR_LAST_ENUM
);
1961 int PrintWebViewHelper::PrintPreviewContext::GetNextPageNumber() {
1962 DCHECK_EQ(RENDERING
, state_
);
1963 if (IsFinalPageRendered())
1965 return pages_to_render_
[current_page_index_
++];
1968 bool PrintWebViewHelper::PrintPreviewContext::IsRendering() const {
1969 return state_
== RENDERING
|| state_
== DONE
;
1972 bool PrintWebViewHelper::PrintPreviewContext::IsModifiable() {
1973 // The only kind of node we can print right now is a PDF node.
1974 return !PrintingNodeOrPdfFrame(source_frame(), source_node_
);
1977 bool PrintWebViewHelper::PrintPreviewContext::HasSelection() {
1978 return IsModifiable() && source_frame()->hasSelection();
1981 bool PrintWebViewHelper::PrintPreviewContext::IsLastPageOfPrintReadyMetafile()
1983 DCHECK(IsRendering());
1984 return current_page_index_
== print_ready_metafile_page_count_
;
1987 bool PrintWebViewHelper::PrintPreviewContext::IsFinalPageRendered() const {
1988 DCHECK(IsRendering());
1989 return static_cast<size_t>(current_page_index_
) == pages_to_render_
.size();
1992 void PrintWebViewHelper::PrintPreviewContext::set_generate_draft_pages(
1993 bool generate_draft_pages
) {
1994 DCHECK_EQ(INITIALIZED
, state_
);
1995 generate_draft_pages_
= generate_draft_pages
;
1998 void PrintWebViewHelper::PrintPreviewContext::set_error(
1999 enum PrintPreviewErrorBuckets error
) {
2003 blink::WebLocalFrame
* PrintWebViewHelper::PrintPreviewContext::source_frame() {
2004 DCHECK(state_
!= UNINITIALIZED
);
2005 return source_frame_
.GetFrame();
2008 const blink::WebNode
&
2009 PrintWebViewHelper::PrintPreviewContext::source_node() const {
2010 DCHECK(state_
!= UNINITIALIZED
);
2011 return source_node_
;
2014 blink::WebLocalFrame
*
2015 PrintWebViewHelper::PrintPreviewContext::prepared_frame() {
2016 DCHECK(state_
!= UNINITIALIZED
);
2017 return prep_frame_view_
->frame();
2020 const blink::WebNode
&
2021 PrintWebViewHelper::PrintPreviewContext::prepared_node() const {
2022 DCHECK(state_
!= UNINITIALIZED
);
2023 return prep_frame_view_
->node();
2026 int PrintWebViewHelper::PrintPreviewContext::total_page_count() const {
2027 DCHECK(state_
!= UNINITIALIZED
);
2028 return total_page_count_
;
2031 bool PrintWebViewHelper::PrintPreviewContext::generate_draft_pages() const {
2032 return generate_draft_pages_
;
2035 PdfMetafileSkia
* PrintWebViewHelper::PrintPreviewContext::metafile() {
2036 DCHECK(IsRendering());
2037 return metafile_
.get();
2040 int PrintWebViewHelper::PrintPreviewContext::last_error() const {
2044 void PrintWebViewHelper::PrintPreviewContext::ClearContext() {
2045 prep_frame_view_
.reset();
2047 pages_to_render_
.clear();
2048 error_
= PREVIEW_ERROR_NONE
;
2051 void PrintWebViewHelper::SetPrintPagesParams(
2052 const PrintMsg_PrintPages_Params
& settings
) {
2053 print_pages_params_
.reset(new PrintMsg_PrintPages_Params(settings
));
2054 Send(new PrintHostMsg_DidGetDocumentCookie(routing_id(),
2055 settings
.params
.document_cookie
));
2058 PrintWebViewHelper::ScriptingThrottler::ScriptingThrottler() : count_(0) {
2061 bool PrintWebViewHelper::ScriptingThrottler::IsAllowed(blink::WebFrame
* frame
) {
2062 const int kMinSecondsToIgnoreJavascriptInitiatedPrint
= 2;
2063 const int kMaxSecondsToIgnoreJavascriptInitiatedPrint
= 32;
2064 bool too_frequent
= false;
2066 // Check if there is script repeatedly trying to print and ignore it if too
2067 // frequent. The first 3 times, we use a constant wait time, but if this
2068 // gets excessive, we switch to exponential wait time. So for a page that
2069 // calls print() in a loop the user will need to cancel the print dialog
2070 // after: [2, 2, 2, 4, 8, 16, 32, 32, ...] seconds.
2071 // This gives the user time to navigate from the page.
2073 base::TimeDelta diff
= base::Time::Now() - last_print_
;
2074 int min_wait_seconds
= kMinSecondsToIgnoreJavascriptInitiatedPrint
;
2077 std::min(kMinSecondsToIgnoreJavascriptInitiatedPrint
<< (count_
- 3),
2078 kMaxSecondsToIgnoreJavascriptInitiatedPrint
);
2080 if (diff
.InSeconds() < min_wait_seconds
) {
2081 too_frequent
= true;
2085 if (!too_frequent
) {
2087 last_print_
= base::Time::Now();
2091 blink::WebString
message(
2092 blink::WebString::fromUTF8("Ignoring too frequent calls to print()."));
2093 frame
->addMessageToConsole(blink::WebConsoleMessage(
2094 blink::WebConsoleMessage::LevelWarning
, message
));
2098 void PrintWebViewHelper::ScriptingThrottler::Reset() {
2099 // Reset counter on successful print.
2103 } // namespace printing