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