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