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