Update To 11.40.268.0
[platform/framework/web/crosswalk.git] / src / chrome / renderer / printing / print_web_view_helper.cc
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.
4
5 #include "chrome/renderer/printing/print_web_view_helper.h"
6
7 #include <string>
8
9 #include "base/auto_reset.h"
10 #include "base/command_line.h"
11 #include "base/json/json_writer.h"
12 #include "base/logging.h"
13 #include "base/message_loop/message_loop.h"
14 #include "base/metrics/histogram.h"
15 #include "base/process/process_handle.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 "chrome/common/chrome_switches.h"
20 #include "chrome/common/print_messages.h"
21 #include "chrome/common/render_messages.h"
22 #include "chrome/grit/browser_resources.h"
23 #include "chrome/renderer/prerender/prerender_helper.h"
24 #include "content/public/common/web_preferences.h"
25 #include "content/public/renderer/render_frame.h"
26 #include "content/public/renderer/render_thread.h"
27 #include "content/public/renderer/render_view.h"
28 #include "net/base/escape.h"
29 #include "printing/pdf_metafile_skia.h"
30 #include "printing/units.h"
31 #include "skia/ext/vector_platform_device_skia.h"
32 #include "third_party/WebKit/public/platform/WebSize.h"
33 #include "third_party/WebKit/public/platform/WebURLRequest.h"
34 #include "third_party/WebKit/public/web/WebConsoleMessage.h"
35 #include "third_party/WebKit/public/web/WebDocument.h"
36 #include "third_party/WebKit/public/web/WebElement.h"
37 #include "third_party/WebKit/public/web/WebFrameClient.h"
38 #include "third_party/WebKit/public/web/WebLocalFrame.h"
39 #include "third_party/WebKit/public/web/WebPlugin.h"
40 #include "third_party/WebKit/public/web/WebPluginDocument.h"
41 #include "third_party/WebKit/public/web/WebPrintParams.h"
42 #include "third_party/WebKit/public/web/WebPrintScalingOption.h"
43 #include "third_party/WebKit/public/web/WebScriptSource.h"
44 #include "third_party/WebKit/public/web/WebSettings.h"
45 #include "third_party/WebKit/public/web/WebView.h"
46 #include "third_party/WebKit/public/web/WebViewClient.h"
47 #include "ui/base/resource/resource_bundle.h"
48
49 using content::WebPreferences;
50
51 namespace printing {
52
53 namespace {
54
55 enum PrintPreviewHelperEvents {
56   PREVIEW_EVENT_REQUESTED,
57   PREVIEW_EVENT_CACHE_HIT,  // Unused
58   PREVIEW_EVENT_CREATE_DOCUMENT,
59   PREVIEW_EVENT_NEW_SETTINGS,  // Unused
60   PREVIEW_EVENT_MAX,
61 };
62
63 const double kMinDpi = 1.0;
64
65 #if !defined(ENABLE_PRINT_PREVIEW)
66 bool g_is_preview_enabled_ = false;
67 #else
68 bool g_is_preview_enabled_ = true;
69
70 const char kPageLoadScriptFormat[] =
71     "document.open(); document.write(%s); document.close();";
72
73 const char kPageSetupScriptFormat[] = "setup(%s);";
74
75 void ExecuteScript(blink::WebFrame* frame,
76                    const char* script_format,
77                    const base::Value& parameters) {
78   std::string json;
79   base::JSONWriter::Write(&parameters, &json);
80   std::string script = base::StringPrintf(script_format, json.c_str());
81   frame->executeScript(blink::WebString(base::UTF8ToUTF16(script)));
82 }
83 #endif  // !defined(ENABLE_PRINT_PREVIEW)
84
85 int GetDPI(const PrintMsg_Print_Params* print_params) {
86 #if defined(OS_MACOSX)
87   // On the Mac, the printable area is in points, don't do any scaling based
88   // on dpi.
89   return kPointsPerInch;
90 #else
91   return static_cast<int>(print_params->dpi);
92 #endif  // defined(OS_MACOSX)
93 }
94
95 bool PrintMsg_Print_Params_IsValid(const PrintMsg_Print_Params& params) {
96   return !params.content_size.IsEmpty() && !params.page_size.IsEmpty() &&
97          !params.printable_area.IsEmpty() && params.document_cookie &&
98          params.desired_dpi && params.max_shrink && params.min_shrink &&
99          params.dpi && (params.margin_top >= 0) && (params.margin_left >= 0) &&
100          params.dpi > kMinDpi && params.document_cookie != 0;
101 }
102
103 PrintMsg_Print_Params GetCssPrintParams(
104     blink::WebFrame* frame,
105     int page_index,
106     const PrintMsg_Print_Params& page_params) {
107   PrintMsg_Print_Params page_css_params = page_params;
108   int dpi = GetDPI(&page_params);
109
110   blink::WebSize page_size_in_pixels(
111       ConvertUnit(page_params.page_size.width(), dpi, kPixelsPerInch),
112       ConvertUnit(page_params.page_size.height(), dpi, kPixelsPerInch));
113   int margin_top_in_pixels =
114       ConvertUnit(page_params.margin_top, dpi, kPixelsPerInch);
115   int margin_right_in_pixels = ConvertUnit(
116       page_params.page_size.width() -
117       page_params.content_size.width() - page_params.margin_left,
118       dpi, kPixelsPerInch);
119   int margin_bottom_in_pixels = ConvertUnit(
120       page_params.page_size.height() -
121       page_params.content_size.height() - page_params.margin_top,
122       dpi, kPixelsPerInch);
123   int margin_left_in_pixels = ConvertUnit(
124       page_params.margin_left,
125       dpi, kPixelsPerInch);
126
127   blink::WebSize original_page_size_in_pixels = page_size_in_pixels;
128
129   if (frame) {
130     frame->pageSizeAndMarginsInPixels(page_index,
131                                       page_size_in_pixels,
132                                       margin_top_in_pixels,
133                                       margin_right_in_pixels,
134                                       margin_bottom_in_pixels,
135                                       margin_left_in_pixels);
136   }
137
138   int new_content_width = page_size_in_pixels.width -
139                           margin_left_in_pixels - margin_right_in_pixels;
140   int new_content_height = page_size_in_pixels.height -
141                            margin_top_in_pixels - margin_bottom_in_pixels;
142
143   // Invalid page size and/or margins. We just use the default setting.
144   if (new_content_width < 1 || new_content_height < 1) {
145     CHECK(frame != NULL);
146     page_css_params = GetCssPrintParams(NULL, page_index, page_params);
147     return page_css_params;
148   }
149
150   page_css_params.content_size = gfx::Size(
151       ConvertUnit(new_content_width, kPixelsPerInch, dpi),
152       ConvertUnit(new_content_height, kPixelsPerInch, dpi));
153
154   if (original_page_size_in_pixels != page_size_in_pixels) {
155     page_css_params.page_size = gfx::Size(
156         ConvertUnit(page_size_in_pixels.width, kPixelsPerInch, dpi),
157         ConvertUnit(page_size_in_pixels.height, kPixelsPerInch, dpi));
158   } else {
159     // Printing frame doesn't have any page size css. Pixels to dpi conversion
160     // causes rounding off errors. Therefore use the default page size values
161     // directly.
162     page_css_params.page_size = page_params.page_size;
163   }
164
165   page_css_params.margin_top =
166       ConvertUnit(margin_top_in_pixels, kPixelsPerInch, dpi);
167   page_css_params.margin_left =
168       ConvertUnit(margin_left_in_pixels, kPixelsPerInch, dpi);
169   return page_css_params;
170 }
171
172 double FitPrintParamsToPage(const PrintMsg_Print_Params& page_params,
173                             PrintMsg_Print_Params* params_to_fit) {
174   double content_width =
175       static_cast<double>(params_to_fit->content_size.width());
176   double content_height =
177       static_cast<double>(params_to_fit->content_size.height());
178   int default_page_size_height = page_params.page_size.height();
179   int default_page_size_width = page_params.page_size.width();
180   int css_page_size_height = params_to_fit->page_size.height();
181   int css_page_size_width = params_to_fit->page_size.width();
182
183   double scale_factor = 1.0f;
184   if (page_params.page_size == params_to_fit->page_size)
185     return scale_factor;
186
187   if (default_page_size_width < css_page_size_width ||
188       default_page_size_height < css_page_size_height) {
189     double ratio_width =
190         static_cast<double>(default_page_size_width) / css_page_size_width;
191     double ratio_height =
192         static_cast<double>(default_page_size_height) / css_page_size_height;
193     scale_factor = ratio_width < ratio_height ? ratio_width : ratio_height;
194     content_width *= scale_factor;
195     content_height *= scale_factor;
196   }
197   params_to_fit->margin_top = static_cast<int>(
198       (default_page_size_height - css_page_size_height * scale_factor) / 2 +
199       (params_to_fit->margin_top * scale_factor));
200   params_to_fit->margin_left = static_cast<int>(
201       (default_page_size_width - css_page_size_width * scale_factor) / 2 +
202       (params_to_fit->margin_left * scale_factor));
203   params_to_fit->content_size = gfx::Size(
204       static_cast<int>(content_width), static_cast<int>(content_height));
205   params_to_fit->page_size = page_params.page_size;
206   return scale_factor;
207 }
208
209 void CalculatePageLayoutFromPrintParams(
210     const PrintMsg_Print_Params& params,
211     PageSizeMargins* page_layout_in_points) {
212   int dpi = GetDPI(&params);
213   int content_width = params.content_size.width();
214   int content_height = params.content_size.height();
215
216   int margin_bottom = params.page_size.height() -
217                       content_height - params.margin_top;
218   int margin_right = params.page_size.width() -
219                       content_width - params.margin_left;
220
221   page_layout_in_points->content_width =
222       ConvertUnit(content_width, dpi, kPointsPerInch);
223   page_layout_in_points->content_height =
224       ConvertUnit(content_height, dpi, kPointsPerInch);
225   page_layout_in_points->margin_top =
226       ConvertUnit(params.margin_top, dpi, kPointsPerInch);
227   page_layout_in_points->margin_right =
228       ConvertUnit(margin_right, dpi, kPointsPerInch);
229   page_layout_in_points->margin_bottom =
230       ConvertUnit(margin_bottom, dpi, kPointsPerInch);
231   page_layout_in_points->margin_left =
232       ConvertUnit(params.margin_left, dpi, kPointsPerInch);
233 }
234
235 void EnsureOrientationMatches(const PrintMsg_Print_Params& css_params,
236                               PrintMsg_Print_Params* page_params) {
237   if ((page_params->page_size.width() > page_params->page_size.height()) ==
238       (css_params.page_size.width() > css_params.page_size.height())) {
239     return;
240   }
241
242   // Swap the |width| and |height| values.
243   page_params->page_size.SetSize(page_params->page_size.height(),
244                                  page_params->page_size.width());
245   page_params->content_size.SetSize(page_params->content_size.height(),
246                                     page_params->content_size.width());
247   page_params->printable_area.set_size(
248       gfx::Size(page_params->printable_area.height(),
249                 page_params->printable_area.width()));
250 }
251
252 void ComputeWebKitPrintParamsInDesiredDpi(
253     const PrintMsg_Print_Params& print_params,
254     blink::WebPrintParams* webkit_print_params) {
255   int dpi = GetDPI(&print_params);
256   webkit_print_params->printerDPI = dpi;
257   webkit_print_params->printScalingOption = print_params.print_scaling_option;
258
259   webkit_print_params->printContentArea.width =
260       ConvertUnit(print_params.content_size.width(), dpi,
261                   print_params.desired_dpi);
262   webkit_print_params->printContentArea.height =
263       ConvertUnit(print_params.content_size.height(), dpi,
264                   print_params.desired_dpi);
265
266   webkit_print_params->printableArea.x =
267       ConvertUnit(print_params.printable_area.x(), dpi,
268                   print_params.desired_dpi);
269   webkit_print_params->printableArea.y =
270       ConvertUnit(print_params.printable_area.y(), dpi,
271                   print_params.desired_dpi);
272   webkit_print_params->printableArea.width =
273       ConvertUnit(print_params.printable_area.width(), dpi,
274                   print_params.desired_dpi);
275   webkit_print_params->printableArea.height =
276       ConvertUnit(print_params.printable_area.height(),
277                   dpi, print_params.desired_dpi);
278
279   webkit_print_params->paperSize.width =
280       ConvertUnit(print_params.page_size.width(), dpi,
281                   print_params.desired_dpi);
282   webkit_print_params->paperSize.height =
283       ConvertUnit(print_params.page_size.height(), dpi,
284                   print_params.desired_dpi);
285 }
286
287 blink::WebPlugin* GetPlugin(const blink::WebFrame* frame) {
288   return frame->document().isPluginDocument() ?
289          frame->document().to<blink::WebPluginDocument>().plugin() : NULL;
290 }
291
292 bool PrintingNodeOrPdfFrame(const blink::WebFrame* frame,
293                             const blink::WebNode& node) {
294   if (!node.isNull())
295     return true;
296   blink::WebPlugin* plugin = GetPlugin(frame);
297   return plugin && plugin->supportsPaginatedPrint();
298 }
299
300 bool PrintingFrameHasPageSizeStyle(blink::WebFrame* frame,
301                                    int total_page_count) {
302   if (!frame)
303     return false;
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;
308       break;
309     }
310   }
311   return frame_has_custom_page_size_style;
312 }
313
314 MarginType GetMarginsForPdf(blink::WebFrame* frame,
315                             const blink::WebNode& node) {
316   if (frame->isPrintScalingDisabledForPlugin(node))
317     return NO_MARGINS;
318   else
319     return PRINTABLE_AREA_MARGINS;
320 }
321
322 bool FitToPageEnabled(const base::DictionaryValue& job_settings) {
323   bool fit_to_paper_size = false;
324   if (!job_settings.GetBoolean(kSettingFitToPageEnabled, &fit_to_paper_size)) {
325     NOTREACHED();
326   }
327   return fit_to_paper_size;
328 }
329
330 // Returns the print scaling option to retain/scale/crop the source page size
331 // to fit the printable area of the paper.
332 //
333 // We retain the source page size when the current destination printer is
334 // SAVE_AS_PDF.
335 //
336 // We crop the source page size to fit the printable area or we print only the
337 // left top page contents when
338 // (1) Source is PDF and the user has requested not to fit to printable area
339 // via |job_settings|.
340 // (2) Source is PDF. This is the first preview request and print scaling
341 // option is disabled for initiator renderer plugin.
342 //
343 // In all other cases, we scale the source page to fit the printable area.
344 blink::WebPrintScalingOption GetPrintScalingOption(
345     blink::WebFrame* frame,
346     const blink::WebNode& node,
347     bool source_is_html,
348     const base::DictionaryValue& job_settings,
349     const PrintMsg_Print_Params& params) {
350   if (params.print_to_pdf)
351     return blink::WebPrintScalingOptionSourceSize;
352
353   if (!source_is_html) {
354     if (!FitToPageEnabled(job_settings))
355       return blink::WebPrintScalingOptionNone;
356
357     bool no_plugin_scaling = frame->isPrintScalingDisabledForPlugin(node);
358
359     if (params.is_first_request && no_plugin_scaling)
360       return blink::WebPrintScalingOptionNone;
361   }
362   return blink::WebPrintScalingOptionFitToPrintableArea;
363 }
364
365 PrintMsg_Print_Params CalculatePrintParamsForCss(
366     blink::WebFrame* frame,
367     int page_index,
368     const PrintMsg_Print_Params& page_params,
369     bool ignore_css_margins,
370     bool fit_to_page,
371     double* scale_factor) {
372   PrintMsg_Print_Params css_params = GetCssPrintParams(frame, page_index,
373                                                        page_params);
374
375   PrintMsg_Print_Params params = page_params;
376   EnsureOrientationMatches(css_params, &params);
377
378   if (ignore_css_margins && fit_to_page)
379     return params;
380
381   PrintMsg_Print_Params result_params = css_params;
382   if (ignore_css_margins) {
383     result_params.margin_top = params.margin_top;
384     result_params.margin_left = params.margin_left;
385
386     DCHECK(!fit_to_page);
387     // Since we are ignoring the margins, the css page size is no longer
388     // valid.
389     int default_margin_right = params.page_size.width() -
390         params.content_size.width() - params.margin_left;
391     int default_margin_bottom = params.page_size.height() -
392         params.content_size.height() - params.margin_top;
393     result_params.content_size = gfx::Size(
394         result_params.page_size.width() - result_params.margin_left -
395             default_margin_right,
396         result_params.page_size.height() - result_params.margin_top -
397             default_margin_bottom);
398   }
399
400   if (fit_to_page) {
401     double factor = FitPrintParamsToPage(params, &result_params);
402     if (scale_factor)
403       *scale_factor = factor;
404   }
405   return result_params;
406 }
407
408 }  // namespace
409
410 FrameReference::FrameReference(blink::WebLocalFrame* frame) {
411   Reset(frame);
412 }
413
414 FrameReference::FrameReference() {
415   Reset(NULL);
416 }
417
418 FrameReference::~FrameReference() {
419 }
420
421 void FrameReference::Reset(blink::WebLocalFrame* frame) {
422   if (frame) {
423     view_ = frame->view();
424     frame_ = frame;
425   } else {
426     view_ = NULL;
427     frame_ = NULL;
428   }
429 }
430
431 blink::WebLocalFrame* FrameReference::GetFrame() {
432   if (view_ == NULL || frame_ == NULL)
433     return NULL;
434   for (blink::WebFrame* frame = view_->mainFrame(); frame != NULL;
435            frame = frame->traverseNext(false)) {
436     if (frame == frame_)
437       return frame_;
438   }
439   return NULL;
440 }
441
442 blink::WebView* FrameReference::view() {
443   return view_;
444 }
445
446 #if defined(ENABLE_PRINT_PREVIEW)
447 // static - Not anonymous so that platform implementations can use it.
448 void PrintWebViewHelper::PrintHeaderAndFooter(
449     blink::WebCanvas* canvas,
450     int page_number,
451     int total_pages,
452     const blink::WebFrame& source_frame,
453     float webkit_scale_factor,
454     const PageSizeMargins& page_layout,
455     const PrintMsg_Print_Params& params) {
456   skia::VectorPlatformDeviceSkia* device =
457       static_cast<skia::VectorPlatformDeviceSkia*>(canvas->getTopDevice());
458   device->setDrawingArea(SkPDFDevice::kMargin_DrawingArea);
459
460   SkAutoCanvasRestore auto_restore(canvas, true);
461   canvas->scale(1 / webkit_scale_factor, 1 / webkit_scale_factor);
462
463   blink::WebSize page_size(page_layout.margin_left + page_layout.margin_right +
464                                page_layout.content_width,
465                            page_layout.margin_top + page_layout.margin_bottom +
466                                page_layout.content_height);
467
468   blink::WebView* web_view = blink::WebView::create(NULL);
469   web_view->settings()->setJavaScriptEnabled(true);
470
471   blink::WebLocalFrame* frame = blink::WebLocalFrame::create(NULL);
472   web_view->setMainFrame(frame);
473
474   base::StringValue html(ResourceBundle::GetSharedInstance().GetLocalizedString(
475       IDR_PRINT_PREVIEW_PAGE));
476   // Load page with script to avoid async operations.
477   ExecuteScript(frame, kPageLoadScriptFormat, html);
478
479   scoped_ptr<base::DictionaryValue> options(new base::DictionaryValue());
480   options.reset(new base::DictionaryValue());
481   options->SetDouble(kSettingHeaderFooterDate, base::Time::Now().ToJsTime());
482   options->SetDouble("width", page_size.width);
483   options->SetDouble("height", page_size.height);
484   options->SetDouble("topMargin", page_layout.margin_top);
485   options->SetDouble("bottomMargin", page_layout.margin_bottom);
486   options->SetString("pageNumber",
487                      base::StringPrintf("%d/%d", page_number, total_pages));
488
489   // Fallback to initiator URL and title if it's empty for printed frame.
490   base::string16 url = source_frame.document().url().string();
491   options->SetString("url", url.empty() ? params.url : url);
492   base::string16 title = source_frame.document().title();
493   options->SetString("title", title.empty() ? params.title : title);
494
495   ExecuteScript(frame, kPageSetupScriptFormat, *options);
496
497   blink::WebPrintParams webkit_params(page_size);
498   webkit_params.printerDPI = GetDPI(&params);
499
500   frame->printBegin(webkit_params);
501   frame->printPage(0, canvas);
502   frame->printEnd();
503
504   web_view->close();
505   frame->close();
506
507   device->setDrawingArea(SkPDFDevice::kContent_DrawingArea);
508 }
509 #endif  // defined(ENABLE_PRINT_PREVIEW)
510
511 // static - Not anonymous so that platform implementations can use it.
512 float PrintWebViewHelper::RenderPageContent(blink::WebFrame* frame,
513                                             int page_number,
514                                             const gfx::Rect& canvas_area,
515                                             const gfx::Rect& content_area,
516                                             double scale_factor,
517                                             blink::WebCanvas* canvas) {
518   SkAutoCanvasRestore auto_restore(canvas, true);
519   if (content_area != canvas_area) {
520     canvas->translate((content_area.x() - canvas_area.x()) / scale_factor,
521                       (content_area.y() - canvas_area.y()) / scale_factor);
522     SkRect clip_rect(
523         SkRect::MakeXYWH(content_area.origin().x() / scale_factor,
524                          content_area.origin().y() / scale_factor,
525                          content_area.size().width() / scale_factor,
526                          content_area.size().height() / scale_factor));
527     SkIRect clip_int_rect;
528     clip_rect.roundOut(&clip_int_rect);
529     SkRegion clip_region(clip_int_rect);
530     canvas->setClipRegion(clip_region);
531   }
532   return frame->printPage(page_number, canvas);
533 }
534
535 // Class that calls the Begin and End print functions on the frame and changes
536 // the size of the view temporarily to support full page printing..
537 class PrepareFrameAndViewForPrint : public blink::WebViewClient,
538                                     public blink::WebFrameClient {
539  public:
540   PrepareFrameAndViewForPrint(const PrintMsg_Print_Params& params,
541                               blink::WebLocalFrame* frame,
542                               const blink::WebNode& node,
543                               bool ignore_css_margins);
544   virtual ~PrepareFrameAndViewForPrint();
545
546   // Optional. Replaces |frame_| with selection if needed. Will call |on_ready|
547   // when completed.
548   void CopySelectionIfNeeded(const WebPreferences& preferences,
549                              const base::Closure& on_ready);
550
551   // Prepares frame for printing.
552   void StartPrinting();
553
554   blink::WebLocalFrame* frame() {
555     return frame_.GetFrame();
556   }
557
558   const blink::WebNode& node() const {
559     return node_to_print_;
560   }
561
562   int GetExpectedPageCount() const {
563     return expected_pages_count_;
564   }
565
566   void FinishPrinting();
567
568   bool IsLoadingSelection() {
569     // It's not selection if not |owns_web_view_|.
570     return owns_web_view_ && frame() && frame()->isLoading();
571   }
572
573   // TODO(ojan): Remove this override and have this class use a non-null
574   // layerTreeView.
575   // blink::WebViewClient override:
576   virtual bool allowsBrokenNullLayerTreeView() const;
577
578  protected:
579   // blink::WebViewClient override:
580   virtual void didStopLoading();
581
582   // blink::WebFrameClient override:
583   virtual blink::WebFrame* createChildFrame(blink::WebLocalFrame* parent,
584                                             const blink::WebString& name);
585   virtual void frameDetached(blink::WebFrame* frame);
586
587  private:
588   void CallOnReady();
589   void ResizeForPrinting();
590   void RestoreSize();
591   void CopySelection(const WebPreferences& preferences);
592
593   base::WeakPtrFactory<PrepareFrameAndViewForPrint> weak_ptr_factory_;
594
595   FrameReference frame_;
596   blink::WebNode node_to_print_;
597   bool owns_web_view_;
598   blink::WebPrintParams web_print_params_;
599   gfx::Size prev_view_size_;
600   gfx::Size prev_scroll_offset_;
601   int expected_pages_count_;
602   base::Closure on_ready_;
603   bool should_print_backgrounds_;
604   bool should_print_selection_only_;
605   bool is_printing_started_;
606
607   DISALLOW_COPY_AND_ASSIGN(PrepareFrameAndViewForPrint);
608 };
609
610 PrepareFrameAndViewForPrint::PrepareFrameAndViewForPrint(
611     const PrintMsg_Print_Params& params,
612     blink::WebLocalFrame* frame,
613     const blink::WebNode& node,
614     bool ignore_css_margins)
615     : weak_ptr_factory_(this),
616       frame_(frame),
617       node_to_print_(node),
618       owns_web_view_(false),
619       expected_pages_count_(0),
620       should_print_backgrounds_(params.should_print_backgrounds),
621       should_print_selection_only_(params.selection_only),
622       is_printing_started_(false) {
623   PrintMsg_Print_Params print_params = params;
624   if (!should_print_selection_only_ ||
625       !PrintingNodeOrPdfFrame(frame, node_to_print_)) {
626     bool fit_to_page = ignore_css_margins &&
627                        print_params.print_scaling_option ==
628                             blink::WebPrintScalingOptionFitToPrintableArea;
629     ComputeWebKitPrintParamsInDesiredDpi(params, &web_print_params_);
630     frame->printBegin(web_print_params_, node_to_print_);
631     print_params = CalculatePrintParamsForCss(frame, 0, print_params,
632                                               ignore_css_margins, fit_to_page,
633                                               NULL);
634     frame->printEnd();
635   }
636   ComputeWebKitPrintParamsInDesiredDpi(print_params, &web_print_params_);
637 }
638
639 PrepareFrameAndViewForPrint::~PrepareFrameAndViewForPrint() {
640   FinishPrinting();
641 }
642
643 void PrepareFrameAndViewForPrint::ResizeForPrinting() {
644   // Layout page according to printer page size. Since WebKit shrinks the
645   // size of the page automatically (from 125% to 200%) we trick it to
646   // think the page is 125% larger so the size of the page is correct for
647   // minimum (default) scaling.
648   // This is important for sites that try to fill the page.
649   gfx::Size print_layout_size(web_print_params_.printContentArea.width,
650                               web_print_params_.printContentArea.height);
651   print_layout_size.set_height(
652       static_cast<int>(static_cast<double>(print_layout_size.height()) * 1.25));
653
654   if (!frame())
655     return;
656   blink::WebView* web_view = frame_.view();
657   // Backup size and offset.
658   if (blink::WebFrame* web_frame = web_view->mainFrame())
659     prev_scroll_offset_ = web_frame->scrollOffset();
660   prev_view_size_ = web_view->size();
661
662   web_view->resize(print_layout_size);
663 }
664
665
666 void PrepareFrameAndViewForPrint::StartPrinting() {
667   ResizeForPrinting();
668   blink::WebView* web_view = frame_.view();
669   web_view->settings()->setShouldPrintBackgrounds(should_print_backgrounds_);
670   expected_pages_count_ =
671       frame()->printBegin(web_print_params_, node_to_print_);
672   is_printing_started_ = true;
673 }
674
675 void PrepareFrameAndViewForPrint::CopySelectionIfNeeded(
676     const WebPreferences& preferences,
677     const base::Closure& on_ready) {
678   on_ready_ = on_ready;
679   if (should_print_selection_only_) {
680     CopySelection(preferences);
681   } else {
682     // Call immediately, async call crashes scripting printing.
683     CallOnReady();
684   }
685 }
686
687 void PrepareFrameAndViewForPrint::CopySelection(
688     const WebPreferences& preferences) {
689   ResizeForPrinting();
690   std::string url_str = "data:text/html;charset=utf-8,";
691   url_str.append(
692       net::EscapeQueryParamValue(frame()->selectionAsMarkup().utf8(), false));
693   RestoreSize();
694   // Create a new WebView with the same settings as the current display one.
695   // Except that we disable javascript (don't want any active content running
696   // on the page).
697   WebPreferences prefs = preferences;
698   prefs.javascript_enabled = false;
699   prefs.java_enabled = false;
700
701   blink::WebView* web_view = blink::WebView::create(this);
702   owns_web_view_ = true;
703   content::RenderView::ApplyWebPreferences(prefs, web_view);
704   web_view->setMainFrame(blink::WebLocalFrame::create(this));
705   frame_.Reset(web_view->mainFrame()->toWebLocalFrame());
706   node_to_print_.reset();
707
708   // When loading is done this will call didStopLoading() and that will do the
709   // actual printing.
710   frame()->loadRequest(blink::WebURLRequest(GURL(url_str)));
711 }
712
713 bool PrepareFrameAndViewForPrint::allowsBrokenNullLayerTreeView() const {
714   return true;
715 }
716
717 void PrepareFrameAndViewForPrint::didStopLoading() {
718   DCHECK(!on_ready_.is_null());
719   // Don't call callback here, because it can delete |this| and WebView that is
720   // called didStopLoading.
721   base::MessageLoop::current()->PostTask(
722       FROM_HERE,
723       base::Bind(&PrepareFrameAndViewForPrint::CallOnReady,
724                  weak_ptr_factory_.GetWeakPtr()));
725 }
726
727 blink::WebFrame* PrepareFrameAndViewForPrint::createChildFrame(
728     blink::WebLocalFrame* parent,
729     const blink::WebString& name) {
730   blink::WebFrame* frame = blink::WebLocalFrame::create(this);
731   parent->appendChild(frame);
732   return frame;
733 }
734
735 void PrepareFrameAndViewForPrint::frameDetached(blink::WebFrame* frame) {
736   if (frame->parent())
737     frame->parent()->removeChild(frame);
738   frame->close();
739 }
740
741 void PrepareFrameAndViewForPrint::CallOnReady() {
742   return on_ready_.Run();  // Can delete |this|.
743 }
744
745 void PrepareFrameAndViewForPrint::RestoreSize() {
746   if (frame()) {
747     blink::WebView* web_view = frame_.GetFrame()->view();
748     web_view->resize(prev_view_size_);
749     if (blink::WebFrame* web_frame = web_view->mainFrame())
750       web_frame->setScrollOffset(prev_scroll_offset_);
751   }
752 }
753
754 void PrepareFrameAndViewForPrint::FinishPrinting() {
755   blink::WebLocalFrame* frame = frame_.GetFrame();
756   if (frame) {
757     blink::WebView* web_view = frame->view();
758     if (is_printing_started_) {
759       is_printing_started_ = false;
760       frame->printEnd();
761       if (!owns_web_view_) {
762         web_view->settings()->setShouldPrintBackgrounds(false);
763         RestoreSize();
764       }
765     }
766     if (owns_web_view_) {
767       DCHECK(!frame->isLoading());
768       owns_web_view_ = false;
769       web_view->close();
770     }
771   }
772   frame_.Reset(NULL);
773   on_ready_.Reset();
774 }
775
776 PrintWebViewHelper::PrintWebViewHelper(content::RenderView* render_view)
777     : content::RenderViewObserver(render_view),
778       content::RenderViewObserverTracker<PrintWebViewHelper>(render_view),
779       reset_prep_frame_view_(false),
780       is_print_ready_metafile_sent_(false),
781       ignore_css_margins_(false),
782       is_scripted_printing_blocked_(false),
783       notify_browser_of_print_failure_(true),
784       print_for_preview_(false),
785       print_node_in_progress_(false),
786       is_loading_(false),
787       is_scripted_preview_delayed_(false),
788       weak_ptr_factory_(this) {
789   if (CommandLine::ForCurrentProcess()->HasSwitch(
790           switches::kDisablePrintPreview)) {
791     DisablePreview();
792   }
793 }
794
795 PrintWebViewHelper::~PrintWebViewHelper() {}
796
797 // static
798 void PrintWebViewHelper::DisablePreview() {
799   g_is_preview_enabled_ = false;
800 }
801
802 bool PrintWebViewHelper::IsScriptInitiatedPrintAllowed(
803     blink::WebFrame* frame, bool user_initiated) {
804 #if defined(OS_ANDROID)
805   return false;
806 #endif  // defined(OS_ANDROID)
807   // If preview is enabled, then the print dialog is tab modal, and the user
808   // can always close the tab on a mis-behaving page (the system print dialog
809   // is app modal). If the print was initiated through user action, don't
810   // throttle. Or, if the command line flag to skip throttling has been set.
811   return !is_scripted_printing_blocked_ &&
812          (user_initiated || g_is_preview_enabled_ ||
813           scripting_throttler_.IsAllowed(frame));
814 }
815
816 void PrintWebViewHelper::DidStartLoading() {
817   is_loading_ = true;
818 }
819
820 void PrintWebViewHelper::DidStopLoading() {
821   is_loading_ = false;
822   if (!on_stop_loading_closure_.is_null()) {
823     on_stop_loading_closure_.Run();
824     on_stop_loading_closure_.Reset();
825   }
826 }
827
828 // Prints |frame| which called window.print().
829 void PrintWebViewHelper::PrintPage(blink::WebLocalFrame* frame,
830                                    bool user_initiated) {
831   DCHECK(frame);
832
833   // Allow Prerendering to cancel this print request if necessary.
834   if (prerender::PrerenderHelper::IsPrerendering(
835           render_view()->GetMainRenderFrame())) {
836     Send(new ChromeViewHostMsg_CancelPrerenderForPrinting(routing_id()));
837     return;
838   }
839
840   if (!IsScriptInitiatedPrintAllowed(frame, user_initiated))
841     return;
842
843   if (!g_is_preview_enabled_) {
844     Print(frame, blink::WebNode());
845   } else {
846     print_preview_context_.InitWithFrame(frame);
847     RequestPrintPreview(PRINT_PREVIEW_SCRIPTED);
848   }
849 }
850
851 bool PrintWebViewHelper::OnMessageReceived(const IPC::Message& message) {
852   bool handled = true;
853   IPC_BEGIN_MESSAGE_MAP(PrintWebViewHelper, message)
854 #if defined(ENABLE_BASIC_PRINTING)
855     IPC_MESSAGE_HANDLER(PrintMsg_PrintPages, OnPrintPages)
856     IPC_MESSAGE_HANDLER(PrintMsg_PrintForSystemDialog, OnPrintForSystemDialog)
857 #endif  // ENABLE_BASIC_PRINTING
858     IPC_MESSAGE_HANDLER(PrintMsg_InitiatePrintPreview, OnInitiatePrintPreview)
859     IPC_MESSAGE_HANDLER(PrintMsg_PrintPreview, OnPrintPreview)
860     IPC_MESSAGE_HANDLER(PrintMsg_PrintForPrintPreview, OnPrintForPrintPreview)
861     IPC_MESSAGE_HANDLER(PrintMsg_PrintingDone, OnPrintingDone)
862     IPC_MESSAGE_HANDLER(PrintMsg_SetScriptedPrintingBlocked,
863                         SetScriptedPrintBlocked)
864     IPC_MESSAGE_UNHANDLED(handled = false)
865     IPC_END_MESSAGE_MAP()
866   return handled;
867 }
868
869 void PrintWebViewHelper::OnPrintForPrintPreview(
870     const base::DictionaryValue& job_settings) {
871   // If still not finished with earlier print request simply ignore.
872   if (prep_frame_view_)
873     return;
874
875   if (!render_view()->GetWebView())
876     return;
877   blink::WebFrame* main_frame = render_view()->GetWebView()->mainFrame();
878   if (!main_frame)
879     return;
880
881   blink::WebDocument document = main_frame->document();
882   // <object>/<iframe> with id="pdf-viewer" is created in
883   // chrome/browser/resources/print_preview/print_preview.js
884   blink::WebElement pdf_element = document.getElementById("pdf-viewer");
885   if (pdf_element.isNull()) {
886     NOTREACHED();
887     return;
888   }
889
890   // The out-of-process plugin element is nested within a frame.
891   blink::WebLocalFrame* plugin_frame = pdf_element.document().frame();
892   blink::WebElement plugin_element = pdf_element;
893   if (CommandLine::ForCurrentProcess()->HasSwitch(switches::kOutOfProcessPdf)) {
894     if (!pdf_element.hasHTMLTagName("iframe")) {
895       NOTREACHED();
896       return;
897     }
898     plugin_frame = blink::WebLocalFrame::fromFrameOwnerElement(pdf_element);
899     // <object> with id="plugin" is created in
900     // chrome/browser/resources/pdf/pdf.js.
901     plugin_element = plugin_frame->document().getElementById("plugin");
902     if (plugin_element.isNull()) {
903       NOTREACHED();
904       return;
905     }
906   }
907
908   // Set |print_for_preview_| flag and autoreset it to back to original
909   // on return.
910   base::AutoReset<bool> set_printing_flag(&print_for_preview_, true);
911
912   if (!UpdatePrintSettings(plugin_frame, plugin_element, job_settings)) {
913     LOG(ERROR) << "UpdatePrintSettings failed";
914     DidFinishPrinting(FAIL_PRINT);
915     return;
916   }
917
918   // Print page onto entire page not just printable area. Preview PDF already
919   // has content in correct position taking into account page size and printable
920   // area.
921   // TODO(vitalybuka) : Make this consistent on all platform. This change
922   // affects Windows only. On Linux and OSX RenderPagesForPrint does not use
923   // printable_area. Also we can't change printable_area deeper inside
924   // RenderPagesForPrint for Windows, because it's used also by native
925   // printing and it expects real printable_area value.
926   // See http://crbug.com/123408
927   PrintMsg_Print_Params& print_params = print_pages_params_->params;
928   print_params.printable_area = gfx::Rect(print_params.page_size);
929
930   // Render Pages for printing.
931   if (!RenderPagesForPrint(plugin_frame, plugin_element)) {
932     LOG(ERROR) << "RenderPagesForPrint failed";
933     DidFinishPrinting(FAIL_PRINT);
934   }
935 }
936
937 bool PrintWebViewHelper::GetPrintFrame(blink::WebLocalFrame** frame) {
938   DCHECK(frame);
939   blink::WebView* webView = render_view()->GetWebView();
940   DCHECK(webView);
941   if (!webView)
942     return false;
943
944   // If the user has selected text in the currently focused frame we print
945   // only that frame (this makes print selection work for multiple frames).
946   blink::WebLocalFrame* focusedFrame =
947       webView->focusedFrame()->toWebLocalFrame();
948   *frame = focusedFrame->hasSelection()
949                ? focusedFrame
950                : webView->mainFrame()->toWebLocalFrame();
951   return true;
952 }
953
954 #if defined(ENABLE_BASIC_PRINTING)
955 void PrintWebViewHelper::OnPrintPages() {
956   blink::WebLocalFrame* frame;
957   if (GetPrintFrame(&frame))
958     Print(frame, blink::WebNode());
959 }
960
961 void PrintWebViewHelper::OnPrintForSystemDialog() {
962   blink::WebLocalFrame* frame = print_preview_context_.source_frame();
963   if (!frame) {
964     NOTREACHED();
965     return;
966   }
967   Print(frame, print_preview_context_.source_node());
968 }
969 #endif  // ENABLE_BASIC_PRINTING
970
971 void PrintWebViewHelper::GetPageSizeAndContentAreaFromPageLayout(
972     const PageSizeMargins& page_layout_in_points,
973     gfx::Size* page_size,
974     gfx::Rect* content_area) {
975   *page_size = gfx::Size(
976       page_layout_in_points.content_width +
977           page_layout_in_points.margin_right +
978           page_layout_in_points.margin_left,
979       page_layout_in_points.content_height +
980           page_layout_in_points.margin_top +
981           page_layout_in_points.margin_bottom);
982   *content_area = gfx::Rect(page_layout_in_points.margin_left,
983                             page_layout_in_points.margin_top,
984                             page_layout_in_points.content_width,
985                             page_layout_in_points.content_height);
986 }
987
988 void PrintWebViewHelper::UpdateFrameMarginsCssInfo(
989     const base::DictionaryValue& settings) {
990   int margins_type = 0;
991   if (!settings.GetInteger(kSettingMarginsType, &margins_type))
992     margins_type = DEFAULT_MARGINS;
993   ignore_css_margins_ = (margins_type != DEFAULT_MARGINS);
994 }
995
996 bool PrintWebViewHelper::IsPrintToPdfRequested(
997     const base::DictionaryValue& job_settings) {
998   bool print_to_pdf = false;
999   if (!job_settings.GetBoolean(kSettingPrintToPDF, &print_to_pdf))
1000     NOTREACHED();
1001   return print_to_pdf;
1002 }
1003
1004 void PrintWebViewHelper::OnPrintPreview(const base::DictionaryValue& settings) {
1005   print_preview_context_.OnPrintPreview();
1006
1007   UMA_HISTOGRAM_ENUMERATION("PrintPreview.PreviewEvent",
1008                             PREVIEW_EVENT_REQUESTED, PREVIEW_EVENT_MAX);
1009
1010   if (!print_preview_context_.source_frame()) {
1011     DidFinishPrinting(FAIL_PREVIEW);
1012     return;
1013   }
1014
1015   if (!UpdatePrintSettings(print_preview_context_.source_frame(),
1016                            print_preview_context_.source_node(), settings)) {
1017     if (print_preview_context_.last_error() != PREVIEW_ERROR_BAD_SETTING) {
1018       Send(new PrintHostMsg_PrintPreviewInvalidPrinterSettings(
1019           routing_id(),
1020           print_pages_params_ ?
1021               print_pages_params_->params.document_cookie : 0));
1022       notify_browser_of_print_failure_ = false;  // Already sent.
1023     }
1024     DidFinishPrinting(FAIL_PREVIEW);
1025     return;
1026   }
1027
1028   // Set the options from document if we are previewing a pdf and send a
1029   // message to browser.
1030   if (print_pages_params_->params.is_first_request &&
1031       !print_preview_context_.IsModifiable()) {
1032     PrintHostMsg_SetOptionsFromDocument_Params params;
1033     SetOptionsFromDocument(params);
1034     Send(new PrintHostMsg_SetOptionsFromDocument(routing_id(), params));
1035   }
1036
1037   is_print_ready_metafile_sent_ = false;
1038
1039   // PDF printer device supports alpha blending.
1040   print_pages_params_->params.supports_alpha_blend = true;
1041
1042   bool generate_draft_pages = false;
1043   if (!settings.GetBoolean(kSettingGenerateDraftData,
1044                            &generate_draft_pages)) {
1045     NOTREACHED();
1046   }
1047   print_preview_context_.set_generate_draft_pages(generate_draft_pages);
1048
1049   PrepareFrameForPreviewDocument();
1050 }
1051
1052 void PrintWebViewHelper::PrepareFrameForPreviewDocument() {
1053   reset_prep_frame_view_ = false;
1054
1055   if (!print_pages_params_ || CheckForCancel()) {
1056     DidFinishPrinting(FAIL_PREVIEW);
1057     return;
1058   }
1059
1060   // Don't reset loading frame or WebKit will fail assert. Just retry when
1061   // current selection is loaded.
1062   if (prep_frame_view_ && prep_frame_view_->IsLoadingSelection()) {
1063     reset_prep_frame_view_ = true;
1064     return;
1065   }
1066
1067   const PrintMsg_Print_Params& print_params = print_pages_params_->params;
1068   prep_frame_view_.reset(
1069       new PrepareFrameAndViewForPrint(print_params,
1070                                       print_preview_context_.source_frame(),
1071                                       print_preview_context_.source_node(),
1072                                       ignore_css_margins_));
1073   prep_frame_view_->CopySelectionIfNeeded(
1074       render_view()->GetWebkitPreferences(),
1075       base::Bind(&PrintWebViewHelper::OnFramePreparedForPreviewDocument,
1076                  base::Unretained(this)));
1077 }
1078
1079 void PrintWebViewHelper::OnFramePreparedForPreviewDocument() {
1080   if (reset_prep_frame_view_) {
1081     PrepareFrameForPreviewDocument();
1082     return;
1083   }
1084   DidFinishPrinting(CreatePreviewDocument() ? OK : FAIL_PREVIEW);
1085 }
1086
1087 bool PrintWebViewHelper::CreatePreviewDocument() {
1088   if (!print_pages_params_ || CheckForCancel())
1089     return false;
1090
1091   UMA_HISTOGRAM_ENUMERATION("PrintPreview.PreviewEvent",
1092                             PREVIEW_EVENT_CREATE_DOCUMENT, PREVIEW_EVENT_MAX);
1093
1094   const PrintMsg_Print_Params& print_params = print_pages_params_->params;
1095   const std::vector<int>& pages = print_pages_params_->pages;
1096
1097   if (!print_preview_context_.CreatePreviewDocument(prep_frame_view_.release(),
1098                                                     pages)) {
1099     return false;
1100   }
1101
1102   PageSizeMargins default_page_layout;
1103   ComputePageLayoutInPointsForCss(print_preview_context_.prepared_frame(), 0,
1104                                   print_params, ignore_css_margins_, NULL,
1105                                   &default_page_layout);
1106
1107   bool has_page_size_style = PrintingFrameHasPageSizeStyle(
1108       print_preview_context_.prepared_frame(),
1109       print_preview_context_.total_page_count());
1110   int dpi = GetDPI(&print_params);
1111
1112   gfx::Rect printable_area_in_points(
1113       ConvertUnit(print_params.printable_area.x(), dpi, kPointsPerInch),
1114       ConvertUnit(print_params.printable_area.y(), dpi, kPointsPerInch),
1115       ConvertUnit(print_params.printable_area.width(), dpi, kPointsPerInch),
1116       ConvertUnit(print_params.printable_area.height(), dpi, kPointsPerInch));
1117
1118   // Margins: Send default page layout to browser process.
1119   Send(new PrintHostMsg_DidGetDefaultPageLayout(routing_id(),
1120                                                 default_page_layout,
1121                                                 printable_area_in_points,
1122                                                 has_page_size_style));
1123
1124   PrintHostMsg_DidGetPreviewPageCount_Params params;
1125   params.page_count = print_preview_context_.total_page_count();
1126   params.is_modifiable = print_preview_context_.IsModifiable();
1127   params.document_cookie = print_params.document_cookie;
1128   params.preview_request_id = print_params.preview_request_id;
1129   params.clear_preview_data = print_preview_context_.generate_draft_pages();
1130   Send(new PrintHostMsg_DidGetPreviewPageCount(routing_id(), params));
1131   if (CheckForCancel())
1132     return false;
1133
1134   while (!print_preview_context_.IsFinalPageRendered()) {
1135     int page_number = print_preview_context_.GetNextPageNumber();
1136     DCHECK_GE(page_number, 0);
1137     if (!RenderPreviewPage(page_number, print_params))
1138       return false;
1139
1140     if (CheckForCancel())
1141       return false;
1142
1143     // We must call PrepareFrameAndViewForPrint::FinishPrinting() (by way of
1144     // print_preview_context_.AllPagesRendered()) before calling
1145     // FinalizePrintReadyDocument() when printing a PDF because the plugin
1146     // code does not generate output until we call FinishPrinting().  We do not
1147     // generate draft pages for PDFs, so IsFinalPageRendered() and
1148     // IsLastPageOfPrintReadyMetafile() will be true in the same iteration of
1149     // the loop.
1150     if (print_preview_context_.IsFinalPageRendered())
1151       print_preview_context_.AllPagesRendered();
1152
1153     if (print_preview_context_.IsLastPageOfPrintReadyMetafile()) {
1154       DCHECK(print_preview_context_.IsModifiable() ||
1155              print_preview_context_.IsFinalPageRendered());
1156       if (!FinalizePrintReadyDocument())
1157         return false;
1158     }
1159   }
1160   print_preview_context_.Finished();
1161   return true;
1162 }
1163
1164 bool PrintWebViewHelper::FinalizePrintReadyDocument() {
1165   DCHECK(!is_print_ready_metafile_sent_);
1166   print_preview_context_.FinalizePrintReadyDocument();
1167
1168   // Get the size of the resulting metafile.
1169   PdfMetafileSkia* metafile = print_preview_context_.metafile();
1170   uint32 buf_size = metafile->GetDataSize();
1171   DCHECK_GT(buf_size, 0u);
1172
1173   PrintHostMsg_DidPreviewDocument_Params preview_params;
1174   preview_params.data_size = buf_size;
1175   preview_params.document_cookie = print_pages_params_->params.document_cookie;
1176   preview_params.expected_pages_count =
1177       print_preview_context_.total_page_count();
1178   preview_params.modifiable = print_preview_context_.IsModifiable();
1179   preview_params.preview_request_id =
1180       print_pages_params_->params.preview_request_id;
1181
1182   // Ask the browser to create the shared memory for us.
1183   if (!CopyMetafileDataToSharedMem(metafile,
1184                                    &(preview_params.metafile_data_handle))) {
1185     LOG(ERROR) << "CopyMetafileDataToSharedMem failed";
1186     print_preview_context_.set_error(PREVIEW_ERROR_METAFILE_COPY_FAILED);
1187     return false;
1188   }
1189   is_print_ready_metafile_sent_ = true;
1190
1191   Send(new PrintHostMsg_MetafileReadyForPrinting(routing_id(), preview_params));
1192   return true;
1193 }
1194
1195 void PrintWebViewHelper::OnPrintingDone(bool success) {
1196   notify_browser_of_print_failure_ = false;
1197   if (!success)
1198     LOG(ERROR) << "Failure in OnPrintingDone";
1199   DidFinishPrinting(success ? OK : FAIL_PRINT);
1200 }
1201
1202 void PrintWebViewHelper::SetScriptedPrintBlocked(bool blocked) {
1203   is_scripted_printing_blocked_ = blocked;
1204 }
1205
1206 void PrintWebViewHelper::OnInitiatePrintPreview(bool selection_only) {
1207   blink::WebLocalFrame* frame = NULL;
1208   GetPrintFrame(&frame);
1209   DCHECK(frame);
1210   print_preview_context_.InitWithFrame(frame);
1211   RequestPrintPreview(selection_only ?
1212                       PRINT_PREVIEW_USER_INITIATED_SELECTION :
1213                       PRINT_PREVIEW_USER_INITIATED_ENTIRE_FRAME);
1214 }
1215
1216 bool PrintWebViewHelper::IsPrintingEnabled() {
1217   bool result = false;
1218   Send(new PrintHostMsg_IsPrintingEnabled(routing_id(), &result));
1219   return result;
1220 }
1221
1222 void PrintWebViewHelper::PrintNode(const blink::WebNode& node) {
1223   if (node.isNull() || !node.document().frame()) {
1224     // This can occur when the context menu refers to an invalid WebNode.
1225     // See http://crbug.com/100890#c17 for a repro case.
1226     return;
1227   }
1228
1229   if (print_node_in_progress_) {
1230     // This can happen as a result of processing sync messages when printing
1231     // from ppapi plugins. It's a rare case, so its OK to just fail here.
1232     // See http://crbug.com/159165.
1233     return;
1234   }
1235
1236   print_node_in_progress_ = true;
1237
1238   // Make a copy of the node, in case RenderView::OnContextMenuClosed resets
1239   // its |context_menu_node_|.
1240   if (!g_is_preview_enabled_) {
1241     blink::WebNode duplicate_node(node);
1242     Print(duplicate_node.document().frame(), duplicate_node);
1243   } else {
1244     print_preview_context_.InitWithNode(node);
1245     RequestPrintPreview(PRINT_PREVIEW_USER_INITIATED_CONTEXT_NODE);
1246   }
1247
1248   print_node_in_progress_ = false;
1249 }
1250
1251 void PrintWebViewHelper::Print(blink::WebLocalFrame* frame,
1252                                const blink::WebNode& node) {
1253   // If still not finished with earlier print request simply ignore.
1254   if (prep_frame_view_)
1255     return;
1256
1257   FrameReference frame_ref(frame);
1258
1259   int expected_page_count = 0;
1260   if (!CalculateNumberOfPages(frame, node, &expected_page_count)) {
1261     DidFinishPrinting(FAIL_PRINT_INIT);
1262     return;  // Failed to init print page settings.
1263   }
1264
1265   // Some full screen plugins can say they don't want to print.
1266   if (!expected_page_count) {
1267     DidFinishPrinting(FAIL_PRINT);
1268     return;
1269   }
1270
1271   // Ask the browser to show UI to retrieve the final print settings.
1272   if (!GetPrintSettingsFromUser(frame_ref.GetFrame(), node,
1273                                 expected_page_count)) {
1274     DidFinishPrinting(OK);  // Release resources and fail silently.
1275     return;
1276   }
1277
1278   // Render Pages for printing.
1279   if (!RenderPagesForPrint(frame_ref.GetFrame(), node)) {
1280     LOG(ERROR) << "RenderPagesForPrint failed";
1281     DidFinishPrinting(FAIL_PRINT);
1282   }
1283   scripting_throttler_.Reset();
1284 }
1285
1286 void PrintWebViewHelper::DidFinishPrinting(PrintingResult result) {
1287   switch (result) {
1288     case OK:
1289       break;
1290
1291     case FAIL_PRINT_INIT:
1292       DCHECK(!notify_browser_of_print_failure_);
1293       break;
1294
1295     case FAIL_PRINT:
1296       if (notify_browser_of_print_failure_ && print_pages_params_) {
1297         int cookie = print_pages_params_->params.document_cookie;
1298         Send(new PrintHostMsg_PrintingFailed(routing_id(), cookie));
1299       }
1300       break;
1301
1302     case FAIL_PREVIEW:
1303       int cookie = print_pages_params_ ?
1304           print_pages_params_->params.document_cookie : 0;
1305       if (notify_browser_of_print_failure_) {
1306         LOG(ERROR) << "CreatePreviewDocument failed";
1307         Send(new PrintHostMsg_PrintPreviewFailed(routing_id(), cookie));
1308       } else {
1309         Send(new PrintHostMsg_PrintPreviewCancelled(routing_id(), cookie));
1310       }
1311       print_preview_context_.Failed(notify_browser_of_print_failure_);
1312       break;
1313   }
1314   prep_frame_view_.reset();
1315   print_pages_params_.reset();
1316   notify_browser_of_print_failure_ = true;
1317 }
1318
1319 void PrintWebViewHelper::OnFramePreparedForPrintPages() {
1320   PrintPages();
1321   FinishFramePrinting();
1322 }
1323
1324 void PrintWebViewHelper::PrintPages() {
1325   if (!prep_frame_view_)  // Printing is already canceled or failed.
1326     return;
1327   prep_frame_view_->StartPrinting();
1328
1329   int page_count = prep_frame_view_->GetExpectedPageCount();
1330   if (!page_count) {
1331     LOG(ERROR) << "Can't print 0 pages.";
1332     return DidFinishPrinting(FAIL_PRINT);
1333   }
1334
1335   const PrintMsg_PrintPages_Params& params = *print_pages_params_;
1336   const PrintMsg_Print_Params& print_params = params.params;
1337
1338 #if !defined(OS_CHROMEOS) && !defined(OS_ANDROID)
1339   // TODO(vitalybuka): should be page_count or valid pages from params.pages.
1340   // See http://crbug.com/161576
1341   Send(new PrintHostMsg_DidGetPrintedPagesCount(routing_id(),
1342                                                 print_params.document_cookie,
1343                                                 page_count));
1344 #endif  // !defined(OS_CHROMEOS)
1345
1346   if (print_params.preview_ui_id < 0) {
1347     // Printing for system dialog.
1348     int printed_count = params.pages.empty() ? page_count : params.pages.size();
1349 #if !defined(OS_CHROMEOS)
1350     UMA_HISTOGRAM_COUNTS("PrintPreview.PageCount.SystemDialog", printed_count);
1351 #else
1352     UMA_HISTOGRAM_COUNTS("PrintPreview.PageCount.PrintToCloudPrintWebDialog",
1353                          printed_count);
1354 #endif  // !defined(OS_CHROMEOS)
1355   }
1356
1357
1358   if (!PrintPagesNative(prep_frame_view_->frame(), page_count)) {
1359     LOG(ERROR) << "Printing failed.";
1360     return DidFinishPrinting(FAIL_PRINT);
1361   }
1362 }
1363
1364 void PrintWebViewHelper::FinishFramePrinting() {
1365   prep_frame_view_.reset();
1366 }
1367
1368 #if defined(OS_MACOSX)
1369 bool PrintWebViewHelper::PrintPagesNative(blink::WebFrame* frame,
1370                                           int page_count) {
1371   const PrintMsg_PrintPages_Params& params = *print_pages_params_;
1372   const PrintMsg_Print_Params& print_params = params.params;
1373
1374   PrintMsg_PrintPage_Params page_params;
1375   page_params.params = print_params;
1376   if (params.pages.empty()) {
1377     for (int i = 0; i < page_count; ++i) {
1378       page_params.page_number = i;
1379       PrintPageInternal(page_params, frame);
1380     }
1381   } else {
1382     for (size_t i = 0; i < params.pages.size(); ++i) {
1383       if (params.pages[i] >= page_count)
1384         break;
1385       page_params.page_number = params.pages[i];
1386       PrintPageInternal(page_params, frame);
1387     }
1388   }
1389   return true;
1390 }
1391
1392 #endif  // OS_MACOSX
1393
1394 // static - Not anonymous so that platform implementations can use it.
1395 void PrintWebViewHelper::ComputePageLayoutInPointsForCss(
1396     blink::WebFrame* frame,
1397     int page_index,
1398     const PrintMsg_Print_Params& page_params,
1399     bool ignore_css_margins,
1400     double* scale_factor,
1401     PageSizeMargins* page_layout_in_points) {
1402   PrintMsg_Print_Params params = CalculatePrintParamsForCss(
1403       frame, page_index, page_params, ignore_css_margins,
1404       page_params.print_scaling_option ==
1405           blink::WebPrintScalingOptionFitToPrintableArea,
1406       scale_factor);
1407   CalculatePageLayoutFromPrintParams(params, page_layout_in_points);
1408 }
1409
1410 bool PrintWebViewHelper::InitPrintSettings(bool fit_to_paper_size) {
1411   PrintMsg_PrintPages_Params settings;
1412   Send(new PrintHostMsg_GetDefaultPrintSettings(routing_id(),
1413                                                 &settings.params));
1414   // Check if the printer returned any settings, if the settings is empty, we
1415   // can safely assume there are no printer drivers configured. So we safely
1416   // terminate.
1417   bool result = true;
1418   if (!PrintMsg_Print_Params_IsValid(settings.params))
1419     result = false;
1420
1421   // Reset to default values.
1422   ignore_css_margins_ = false;
1423   settings.pages.clear();
1424
1425   settings.params.print_scaling_option =
1426       blink::WebPrintScalingOptionSourceSize;
1427   if (fit_to_paper_size) {
1428     settings.params.print_scaling_option =
1429         blink::WebPrintScalingOptionFitToPrintableArea;
1430   }
1431
1432   SetPrintPagesParams(settings);
1433   return result;
1434 }
1435
1436 bool PrintWebViewHelper::CalculateNumberOfPages(blink::WebLocalFrame* frame,
1437                                                 const blink::WebNode& node,
1438                                                 int* number_of_pages) {
1439   DCHECK(frame);
1440   bool fit_to_paper_size = !(PrintingNodeOrPdfFrame(frame, node));
1441   if (!InitPrintSettings(fit_to_paper_size)) {
1442     notify_browser_of_print_failure_ = false;
1443     Send(new PrintHostMsg_ShowInvalidPrinterSettingsError(routing_id()));
1444     return false;
1445   }
1446
1447   const PrintMsg_Print_Params& params = print_pages_params_->params;
1448   PrepareFrameAndViewForPrint prepare(params, frame, node, ignore_css_margins_);
1449   prepare.StartPrinting();
1450
1451   *number_of_pages = prepare.GetExpectedPageCount();
1452   return true;
1453 }
1454
1455 void PrintWebViewHelper::SetOptionsFromDocument(
1456     PrintHostMsg_SetOptionsFromDocument_Params& params) {
1457   blink::WebLocalFrame* source_frame = print_preview_context_.source_frame();
1458   const blink::WebNode& source_node = print_preview_context_.source_node();
1459
1460   params.is_scaling_disabled =
1461       source_frame->isPrintScalingDisabledForPlugin(source_node);
1462 }
1463
1464 bool PrintWebViewHelper::UpdatePrintSettings(
1465     blink::WebLocalFrame* frame,
1466     const blink::WebNode& node,
1467     const base::DictionaryValue& passed_job_settings) {
1468   const base::DictionaryValue* job_settings = &passed_job_settings;
1469   base::DictionaryValue modified_job_settings;
1470   if (job_settings->empty()) {
1471     if (!print_for_preview_)
1472       print_preview_context_.set_error(PREVIEW_ERROR_BAD_SETTING);
1473     return false;
1474   }
1475
1476   bool source_is_html = true;
1477   if (print_for_preview_) {
1478     if (!job_settings->GetBoolean(kSettingPreviewModifiable, &source_is_html)) {
1479       NOTREACHED();
1480     }
1481   } else {
1482     source_is_html = !PrintingNodeOrPdfFrame(frame, node);
1483   }
1484
1485   if (print_for_preview_ || !source_is_html) {
1486     modified_job_settings.MergeDictionary(job_settings);
1487     modified_job_settings.SetBoolean(kSettingHeaderFooterEnabled, false);
1488     modified_job_settings.SetInteger(kSettingMarginsType, NO_MARGINS);
1489     job_settings = &modified_job_settings;
1490   }
1491
1492   // Send the cookie so that UpdatePrintSettings can reuse PrinterQuery when
1493   // possible.
1494   int cookie = print_pages_params_ ?
1495       print_pages_params_->params.document_cookie : 0;
1496   PrintMsg_PrintPages_Params settings;
1497   bool canceled = false;
1498   Send(new PrintHostMsg_UpdatePrintSettings(
1499       routing_id(), cookie, *job_settings, &settings, &canceled));
1500   if (canceled) {
1501     notify_browser_of_print_failure_ = false;
1502     return false;
1503   }
1504
1505   if (!job_settings->GetInteger(kPreviewUIID, &settings.params.preview_ui_id)) {
1506     NOTREACHED();
1507     print_preview_context_.set_error(PREVIEW_ERROR_BAD_SETTING);
1508     return false;
1509   }
1510
1511   if (!print_for_preview_) {
1512     // Validate expected print preview settings.
1513     if (!job_settings->GetInteger(kPreviewRequestID,
1514                                   &settings.params.preview_request_id) ||
1515         !job_settings->GetBoolean(kIsFirstRequest,
1516                                   &settings.params.is_first_request)) {
1517       NOTREACHED();
1518       print_preview_context_.set_error(PREVIEW_ERROR_BAD_SETTING);
1519       return false;
1520     }
1521
1522     settings.params.print_to_pdf = IsPrintToPdfRequested(*job_settings);
1523     UpdateFrameMarginsCssInfo(*job_settings);
1524     settings.params.print_scaling_option = GetPrintScalingOption(
1525         frame, node, source_is_html, *job_settings, settings.params);
1526   }
1527
1528   SetPrintPagesParams(settings);
1529
1530   if (!PrintMsg_Print_Params_IsValid(settings.params)) {
1531     if (!print_for_preview_)
1532       print_preview_context_.set_error(PREVIEW_ERROR_INVALID_PRINTER_SETTINGS);
1533     else
1534       Send(new PrintHostMsg_ShowInvalidPrinterSettingsError(routing_id()));
1535
1536     return false;
1537   }
1538
1539   return true;
1540 }
1541
1542 bool PrintWebViewHelper::GetPrintSettingsFromUser(blink::WebFrame* frame,
1543                                                   const blink::WebNode& node,
1544                                                   int expected_pages_count) {
1545   PrintHostMsg_ScriptedPrint_Params params;
1546   PrintMsg_PrintPages_Params print_settings;
1547
1548   params.cookie = print_pages_params_->params.document_cookie;
1549   params.has_selection = frame->hasSelection();
1550   params.expected_pages_count = expected_pages_count;
1551   MarginType margin_type = DEFAULT_MARGINS;
1552   if (PrintingNodeOrPdfFrame(frame, node))
1553     margin_type = GetMarginsForPdf(frame, node);
1554   params.margin_type = margin_type;
1555
1556   Send(new PrintHostMsg_DidShowPrintDialog(routing_id()));
1557
1558   // PrintHostMsg_ScriptedPrint will reset print_scaling_option, so we save the
1559   // value before and restore it afterwards.
1560   blink::WebPrintScalingOption scaling_option =
1561       print_pages_params_->params.print_scaling_option;
1562
1563   print_pages_params_.reset();
1564   IPC::SyncMessage* msg =
1565       new PrintHostMsg_ScriptedPrint(routing_id(), params, &print_settings);
1566   msg->EnableMessagePumping();
1567   Send(msg);
1568   print_settings.params.print_scaling_option = scaling_option;
1569   SetPrintPagesParams(print_settings);
1570   return (print_settings.params.dpi && print_settings.params.document_cookie);
1571 }
1572
1573 bool PrintWebViewHelper::RenderPagesForPrint(blink::WebLocalFrame* frame,
1574                                              const blink::WebNode& node) {
1575   if (!frame || prep_frame_view_)
1576     return false;
1577   const PrintMsg_PrintPages_Params& params = *print_pages_params_;
1578   const PrintMsg_Print_Params& print_params = params.params;
1579   prep_frame_view_.reset(new PrepareFrameAndViewForPrint(
1580       print_params, frame, node, ignore_css_margins_));
1581   DCHECK(!print_pages_params_->params.selection_only ||
1582          print_pages_params_->pages.empty());
1583   prep_frame_view_->CopySelectionIfNeeded(
1584       render_view()->GetWebkitPreferences(),
1585       base::Bind(&PrintWebViewHelper::OnFramePreparedForPrintPages,
1586                  base::Unretained(this)));
1587   return true;
1588 }
1589
1590 #if defined(OS_POSIX)
1591 bool PrintWebViewHelper::CopyMetafileDataToSharedMem(
1592     PdfMetafileSkia* metafile,
1593     base::SharedMemoryHandle* shared_mem_handle) {
1594   uint32 buf_size = metafile->GetDataSize();
1595   scoped_ptr<base::SharedMemory> shared_buf(
1596       content::RenderThread::Get()->HostAllocateSharedMemoryBuffer(
1597           buf_size).release());
1598
1599   if (shared_buf) {
1600     if (shared_buf->Map(buf_size)) {
1601       metafile->GetData(shared_buf->memory(), buf_size);
1602       return shared_buf->GiveToProcess(base::GetCurrentProcessHandle(),
1603                                        shared_mem_handle);
1604     }
1605   }
1606   return false;
1607 }
1608 #endif  // defined(OS_POSIX)
1609
1610 void PrintWebViewHelper::ShowScriptedPrintPreview() {
1611   if (is_scripted_preview_delayed_) {
1612     is_scripted_preview_delayed_ = false;
1613     Send(new PrintHostMsg_ShowScriptedPrintPreview(routing_id(),
1614             print_preview_context_.IsModifiable()));
1615   }
1616 }
1617
1618 void PrintWebViewHelper::RequestPrintPreview(PrintPreviewRequestType type) {
1619   const bool is_modifiable = print_preview_context_.IsModifiable();
1620   const bool has_selection = print_preview_context_.HasSelection();
1621   PrintHostMsg_RequestPrintPreview_Params params;
1622   params.is_modifiable = is_modifiable;
1623   params.has_selection = has_selection;
1624   switch (type) {
1625     case PRINT_PREVIEW_SCRIPTED: {
1626       // Shows scripted print preview in two stages.
1627       // 1. PrintHostMsg_SetupScriptedPrintPreview blocks this call and JS by
1628       //    pumping messages here.
1629       // 2. PrintHostMsg_ShowScriptedPrintPreview shows preview once the
1630       //    document has been loaded.
1631       is_scripted_preview_delayed_ = true;
1632       if (is_loading_ && GetPlugin(print_preview_context_.source_frame())) {
1633         // Wait for DidStopLoading. Plugins may not know the correct
1634         // |is_modifiable| value until they are fully loaded, which occurs when
1635         // DidStopLoading() is called. Defer showing the preview until then.
1636         on_stop_loading_closure_ =
1637             base::Bind(&PrintWebViewHelper::ShowScriptedPrintPreview,
1638                        base::Unretained(this));
1639       } else {
1640         base::MessageLoop::current()->PostTask(
1641             FROM_HERE,
1642             base::Bind(&PrintWebViewHelper::ShowScriptedPrintPreview,
1643                        weak_ptr_factory_.GetWeakPtr()));
1644       }
1645       IPC::SyncMessage* msg =
1646           new PrintHostMsg_SetupScriptedPrintPreview(routing_id());
1647       msg->EnableMessagePumping();
1648       Send(msg);
1649       is_scripted_preview_delayed_ = false;
1650       return;
1651     }
1652     case PRINT_PREVIEW_USER_INITIATED_ENTIRE_FRAME: {
1653       // Wait for DidStopLoading. Continuing with this function while
1654       // |is_loading_| is true will cause print preview to hang when try to
1655       // print a PDF document.
1656       if (is_loading_ && GetPlugin(print_preview_context_.source_frame())) {
1657         on_stop_loading_closure_ =
1658             base::Bind(&PrintWebViewHelper::RequestPrintPreview,
1659                        base::Unretained(this),
1660                        type);
1661         return;
1662       }
1663
1664       break;
1665     }
1666     case PRINT_PREVIEW_USER_INITIATED_SELECTION: {
1667       DCHECK(has_selection);
1668       DCHECK(!GetPlugin(print_preview_context_.source_frame()));
1669       params.selection_only = has_selection;
1670       break;
1671     }
1672     case PRINT_PREVIEW_USER_INITIATED_CONTEXT_NODE: {
1673       if (is_loading_ && GetPlugin(print_preview_context_.source_frame())) {
1674         on_stop_loading_closure_ =
1675             base::Bind(&PrintWebViewHelper::RequestPrintPreview,
1676                        base::Unretained(this),
1677                        type);
1678         return;
1679       }
1680
1681       params.webnode_only = true;
1682       break;
1683     }
1684     default: {
1685       NOTREACHED();
1686       return;
1687     }
1688   }
1689   Send(new PrintHostMsg_RequestPrintPreview(routing_id(), params));
1690 }
1691
1692 bool PrintWebViewHelper::CheckForCancel() {
1693   const PrintMsg_Print_Params& print_params = print_pages_params_->params;
1694   bool cancel = false;
1695   Send(new PrintHostMsg_CheckForCancel(routing_id(),
1696                                        print_params.preview_ui_id,
1697                                        print_params.preview_request_id,
1698                                        &cancel));
1699   if (cancel)
1700     notify_browser_of_print_failure_ = false;
1701   return cancel;
1702 }
1703
1704 bool PrintWebViewHelper::PreviewPageRendered(int page_number,
1705                                              PdfMetafileSkia* metafile) {
1706   DCHECK_GE(page_number, FIRST_PAGE_INDEX);
1707
1708   // For non-modifiable files, |metafile| should be NULL, so do not bother
1709   // sending a message. If we don't generate draft metafiles, |metafile| is
1710   // NULL.
1711   if (!print_preview_context_.IsModifiable() ||
1712       !print_preview_context_.generate_draft_pages()) {
1713     DCHECK(!metafile);
1714     return true;
1715   }
1716
1717   if (!metafile) {
1718     NOTREACHED();
1719     print_preview_context_.set_error(
1720         PREVIEW_ERROR_PAGE_RENDERED_WITHOUT_METAFILE);
1721     return false;
1722   }
1723
1724   PrintHostMsg_DidPreviewPage_Params preview_page_params;
1725   // Get the size of the resulting metafile.
1726   uint32 buf_size = metafile->GetDataSize();
1727   DCHECK_GT(buf_size, 0u);
1728   if (!CopyMetafileDataToSharedMem(
1729       metafile, &(preview_page_params.metafile_data_handle))) {
1730     LOG(ERROR) << "CopyMetafileDataToSharedMem failed";
1731     print_preview_context_.set_error(PREVIEW_ERROR_METAFILE_COPY_FAILED);
1732     return false;
1733   }
1734   preview_page_params.data_size = buf_size;
1735   preview_page_params.page_number = page_number;
1736   preview_page_params.preview_request_id =
1737       print_pages_params_->params.preview_request_id;
1738
1739   Send(new PrintHostMsg_DidPreviewPage(routing_id(), preview_page_params));
1740   return true;
1741 }
1742
1743 PrintWebViewHelper::PrintPreviewContext::PrintPreviewContext()
1744     : total_page_count_(0),
1745       current_page_index_(0),
1746       generate_draft_pages_(true),
1747       print_ready_metafile_page_count_(0),
1748       error_(PREVIEW_ERROR_NONE),
1749       state_(UNINITIALIZED) {
1750 }
1751
1752 PrintWebViewHelper::PrintPreviewContext::~PrintPreviewContext() {
1753 }
1754
1755 void PrintWebViewHelper::PrintPreviewContext::InitWithFrame(
1756     blink::WebLocalFrame* web_frame) {
1757   DCHECK(web_frame);
1758   DCHECK(!IsRendering());
1759   state_ = INITIALIZED;
1760   source_frame_.Reset(web_frame);
1761   source_node_.reset();
1762 }
1763
1764 void PrintWebViewHelper::PrintPreviewContext::InitWithNode(
1765     const blink::WebNode& web_node) {
1766   DCHECK(!web_node.isNull());
1767   DCHECK(web_node.document().frame());
1768   DCHECK(!IsRendering());
1769   state_ = INITIALIZED;
1770   source_frame_.Reset(web_node.document().frame());
1771   source_node_ = web_node;
1772 }
1773
1774 void PrintWebViewHelper::PrintPreviewContext::OnPrintPreview() {
1775   DCHECK_EQ(INITIALIZED, state_);
1776   ClearContext();
1777 }
1778
1779 bool PrintWebViewHelper::PrintPreviewContext::CreatePreviewDocument(
1780     PrepareFrameAndViewForPrint* prepared_frame,
1781     const std::vector<int>& pages) {
1782   DCHECK_EQ(INITIALIZED, state_);
1783   state_ = RENDERING;
1784
1785   // Need to make sure old object gets destroyed first.
1786   prep_frame_view_.reset(prepared_frame);
1787   prep_frame_view_->StartPrinting();
1788
1789   total_page_count_ = prep_frame_view_->GetExpectedPageCount();
1790   if (total_page_count_ == 0) {
1791     LOG(ERROR) << "CreatePreviewDocument got 0 page count";
1792     set_error(PREVIEW_ERROR_ZERO_PAGES);
1793     return false;
1794   }
1795
1796   metafile_.reset(new PdfMetafileSkia);
1797   if (!metafile_->Init()) {
1798     set_error(PREVIEW_ERROR_METAFILE_INIT_FAILED);
1799     LOG(ERROR) << "PdfMetafileSkia Init failed";
1800     return false;
1801   }
1802
1803   current_page_index_ = 0;
1804   pages_to_render_ = pages;
1805   // Sort and make unique.
1806   std::sort(pages_to_render_.begin(), pages_to_render_.end());
1807   pages_to_render_.resize(std::unique(pages_to_render_.begin(),
1808                                       pages_to_render_.end()) -
1809                           pages_to_render_.begin());
1810   // Remove invalid pages.
1811   pages_to_render_.resize(std::lower_bound(pages_to_render_.begin(),
1812                                            pages_to_render_.end(),
1813                                            total_page_count_) -
1814                           pages_to_render_.begin());
1815   print_ready_metafile_page_count_ = pages_to_render_.size();
1816   if (pages_to_render_.empty()) {
1817     print_ready_metafile_page_count_ = total_page_count_;
1818     // Render all pages.
1819     for (int i = 0; i < total_page_count_; ++i)
1820       pages_to_render_.push_back(i);
1821   } else if (generate_draft_pages_) {
1822     int pages_index = 0;
1823     for (int i = 0; i < total_page_count_; ++i) {
1824       if (pages_index < print_ready_metafile_page_count_ &&
1825           i == pages_to_render_[pages_index]) {
1826         pages_index++;
1827         continue;
1828       }
1829       pages_to_render_.push_back(i);
1830     }
1831   }
1832
1833   document_render_time_ = base::TimeDelta();
1834   begin_time_ = base::TimeTicks::Now();
1835
1836   return true;
1837 }
1838
1839 void PrintWebViewHelper::PrintPreviewContext::RenderedPreviewPage(
1840     const base::TimeDelta& page_time) {
1841   DCHECK_EQ(RENDERING, state_);
1842   document_render_time_ += page_time;
1843   UMA_HISTOGRAM_TIMES("PrintPreview.RenderPDFPageTime", page_time);
1844 }
1845
1846 void PrintWebViewHelper::PrintPreviewContext::AllPagesRendered() {
1847   DCHECK_EQ(RENDERING, state_);
1848   state_ = DONE;
1849   prep_frame_view_->FinishPrinting();
1850 }
1851
1852 void PrintWebViewHelper::PrintPreviewContext::FinalizePrintReadyDocument() {
1853   DCHECK(IsRendering());
1854
1855   base::TimeTicks begin_time = base::TimeTicks::Now();
1856   metafile_->FinishDocument();
1857
1858   if (print_ready_metafile_page_count_ <= 0) {
1859     NOTREACHED();
1860     return;
1861   }
1862
1863   UMA_HISTOGRAM_MEDIUM_TIMES("PrintPreview.RenderToPDFTime",
1864                              document_render_time_);
1865   base::TimeDelta total_time = (base::TimeTicks::Now() - begin_time) +
1866                                document_render_time_;
1867   UMA_HISTOGRAM_MEDIUM_TIMES("PrintPreview.RenderAndGeneratePDFTime",
1868                              total_time);
1869   UMA_HISTOGRAM_MEDIUM_TIMES("PrintPreview.RenderAndGeneratePDFTimeAvgPerPage",
1870                              total_time / pages_to_render_.size());
1871 }
1872
1873 void PrintWebViewHelper::PrintPreviewContext::Finished() {
1874   DCHECK_EQ(DONE, state_);
1875   state_ = INITIALIZED;
1876   ClearContext();
1877 }
1878
1879 void PrintWebViewHelper::PrintPreviewContext::Failed(bool report_error) {
1880   DCHECK(state_ == INITIALIZED || state_ == RENDERING);
1881   state_ = INITIALIZED;
1882   if (report_error) {
1883     DCHECK_NE(PREVIEW_ERROR_NONE, error_);
1884     UMA_HISTOGRAM_ENUMERATION("PrintPreview.RendererError", error_,
1885                               PREVIEW_ERROR_LAST_ENUM);
1886   }
1887   ClearContext();
1888 }
1889
1890 int PrintWebViewHelper::PrintPreviewContext::GetNextPageNumber() {
1891   DCHECK_EQ(RENDERING, state_);
1892   if (IsFinalPageRendered())
1893     return -1;
1894   return pages_to_render_[current_page_index_++];
1895 }
1896
1897 bool PrintWebViewHelper::PrintPreviewContext::IsRendering() const {
1898   return state_ == RENDERING || state_ == DONE;
1899 }
1900
1901 bool PrintWebViewHelper::PrintPreviewContext::IsModifiable() {
1902   // The only kind of node we can print right now is a PDF node.
1903   return !PrintingNodeOrPdfFrame(source_frame(), source_node_);
1904 }
1905
1906 bool PrintWebViewHelper::PrintPreviewContext::HasSelection() {
1907   return IsModifiable() && source_frame()->hasSelection();
1908 }
1909
1910 bool PrintWebViewHelper::PrintPreviewContext::IsLastPageOfPrintReadyMetafile()
1911     const {
1912   DCHECK(IsRendering());
1913   return current_page_index_ == print_ready_metafile_page_count_;
1914 }
1915
1916 bool  PrintWebViewHelper::PrintPreviewContext::IsFinalPageRendered() const {
1917   DCHECK(IsRendering());
1918   return static_cast<size_t>(current_page_index_) == pages_to_render_.size();
1919 }
1920
1921 void PrintWebViewHelper::PrintPreviewContext::set_generate_draft_pages(
1922     bool generate_draft_pages) {
1923   DCHECK_EQ(INITIALIZED, state_);
1924   generate_draft_pages_ = generate_draft_pages;
1925 }
1926
1927 void PrintWebViewHelper::PrintPreviewContext::set_error(
1928     enum PrintPreviewErrorBuckets error) {
1929   error_ = error;
1930 }
1931
1932 blink::WebLocalFrame* PrintWebViewHelper::PrintPreviewContext::source_frame() {
1933   DCHECK(state_ != UNINITIALIZED);
1934   return source_frame_.GetFrame();
1935 }
1936
1937 const blink::WebNode&
1938     PrintWebViewHelper::PrintPreviewContext::source_node() const {
1939   DCHECK(state_ != UNINITIALIZED);
1940   return source_node_;
1941 }
1942
1943 blink::WebLocalFrame*
1944 PrintWebViewHelper::PrintPreviewContext::prepared_frame() {
1945   DCHECK(state_ != UNINITIALIZED);
1946   return prep_frame_view_->frame();
1947 }
1948
1949 const blink::WebNode&
1950     PrintWebViewHelper::PrintPreviewContext::prepared_node() const {
1951   DCHECK(state_ != UNINITIALIZED);
1952   return prep_frame_view_->node();
1953 }
1954
1955 int PrintWebViewHelper::PrintPreviewContext::total_page_count() const {
1956   DCHECK(state_ != UNINITIALIZED);
1957   return total_page_count_;
1958 }
1959
1960 bool PrintWebViewHelper::PrintPreviewContext::generate_draft_pages() const {
1961   return generate_draft_pages_;
1962 }
1963
1964 PdfMetafileSkia* PrintWebViewHelper::PrintPreviewContext::metafile() {
1965   DCHECK(IsRendering());
1966   return metafile_.get();
1967 }
1968
1969 int PrintWebViewHelper::PrintPreviewContext::last_error() const {
1970   return error_;
1971 }
1972
1973 void PrintWebViewHelper::PrintPreviewContext::ClearContext() {
1974   prep_frame_view_.reset();
1975   metafile_.reset();
1976   pages_to_render_.clear();
1977   error_ = PREVIEW_ERROR_NONE;
1978 }
1979
1980 void PrintWebViewHelper::SetPrintPagesParams(
1981     const PrintMsg_PrintPages_Params& settings) {
1982   print_pages_params_.reset(new PrintMsg_PrintPages_Params(settings));
1983   Send(new PrintHostMsg_DidGetDocumentCookie(routing_id(),
1984                                              settings.params.document_cookie));
1985 }
1986
1987 PrintWebViewHelper::ScriptingThrottler::ScriptingThrottler() : count_(0) {
1988 }
1989
1990 bool PrintWebViewHelper::ScriptingThrottler::IsAllowed(blink::WebFrame* frame) {
1991   const int kMinSecondsToIgnoreJavascriptInitiatedPrint = 2;
1992   const int kMaxSecondsToIgnoreJavascriptInitiatedPrint = 32;
1993   bool too_frequent = false;
1994
1995   // Check if there is script repeatedly trying to print and ignore it if too
1996   // frequent.  The first 3 times, we use a constant wait time, but if this
1997   // gets excessive, we switch to exponential wait time. So for a page that
1998   // calls print() in a loop the user will need to cancel the print dialog
1999   // after: [2, 2, 2, 4, 8, 16, 32, 32, ...] seconds.
2000   // This gives the user time to navigate from the page.
2001   if (count_ > 0) {
2002     base::TimeDelta diff = base::Time::Now() - last_print_;
2003     int min_wait_seconds = kMinSecondsToIgnoreJavascriptInitiatedPrint;
2004     if (count_ > 3) {
2005       min_wait_seconds =
2006           std::min(kMinSecondsToIgnoreJavascriptInitiatedPrint << (count_ - 3),
2007                    kMaxSecondsToIgnoreJavascriptInitiatedPrint);
2008     }
2009     if (diff.InSeconds() < min_wait_seconds) {
2010       too_frequent = true;
2011     }
2012   }
2013
2014   if (!too_frequent) {
2015     ++count_;
2016     last_print_ = base::Time::Now();
2017     return true;
2018   }
2019
2020   blink::WebString message(
2021       blink::WebString::fromUTF8("Ignoring too frequent calls to print()."));
2022   frame->addMessageToConsole(blink::WebConsoleMessage(
2023       blink::WebConsoleMessage::LevelWarning, message));
2024   return false;
2025 }
2026
2027 void PrintWebViewHelper::ScriptingThrottler::Reset() {
2028   // Reset counter on successful print.
2029   count_ = 0;
2030 }
2031
2032 }  // namespace printing