6039f940a092af61a31822d0e22b33e51d9f0b28
[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   blink::WebFrame* frame = blink::WebFrame::create(this);
680   parent->appendChild(frame);
681   return frame;
682 }
683
684 void PrepareFrameAndViewForPrint::frameDetached(blink::WebFrame* frame) {
685   if (frame->parent())
686     frame->parent()->removeChild(frame);
687   frame->close();
688 }
689
690 void PrepareFrameAndViewForPrint::CallOnReady() {
691   return on_ready_.Run();  // Can delete |this|.
692 }
693
694 gfx::Size PrepareFrameAndViewForPrint::GetPrintCanvasSize() const {
695   DCHECK(is_printing_started_);
696   return gfx::Size(web_print_params_.printContentArea.width,
697                    web_print_params_.printContentArea.height);
698 }
699
700 void PrepareFrameAndViewForPrint::RestoreSize() {
701   if (frame()) {
702     blink::WebView* web_view = frame_.GetFrame()->view();
703     web_view->resize(prev_view_size_);
704     if (blink::WebFrame* web_frame = web_view->mainFrame())
705       web_frame->setScrollOffset(prev_scroll_offset_);
706   }
707 }
708
709 void PrepareFrameAndViewForPrint::FinishPrinting() {
710   blink::WebFrame* frame = frame_.GetFrame();
711   if (frame) {
712     blink::WebView* web_view = frame->view();
713     if (is_printing_started_) {
714       is_printing_started_ = false;
715       frame->printEnd();
716       if (!owns_web_view_) {
717         web_view->settings()->setShouldPrintBackgrounds(false);
718         RestoreSize();
719       }
720     }
721     if (owns_web_view_) {
722       DCHECK(!frame->isLoading());
723       owns_web_view_ = false;
724       web_view->close();
725     }
726   }
727   frame_.Reset(NULL);
728   on_ready_.Reset();
729 }
730
731 PrintWebViewHelper::PrintWebViewHelper(content::RenderView* render_view)
732     : content::RenderViewObserver(render_view),
733       content::RenderViewObserverTracker<PrintWebViewHelper>(render_view),
734       reset_prep_frame_view_(false),
735       is_preview_enabled_(IsPrintPreviewEnabled()),
736       is_scripted_print_throttling_disabled_(IsPrintThrottlingDisabled()),
737       is_print_ready_metafile_sent_(false),
738       ignore_css_margins_(false),
739       user_cancelled_scripted_print_count_(0),
740       is_scripted_printing_blocked_(false),
741       notify_browser_of_print_failure_(true),
742       print_for_preview_(false),
743       print_node_in_progress_(false),
744       is_loading_(false),
745       is_scripted_preview_delayed_(false),
746       weak_ptr_factory_(this) {
747   // TODO(sgurun) enable window.print() for webview crbug.com/322303
748   SetScriptedPrintBlocked(true);
749 }
750
751 PrintWebViewHelper::~PrintWebViewHelper() {}
752
753 bool PrintWebViewHelper::IsScriptInitiatedPrintAllowed(
754     blink::WebFrame* frame, bool user_initiated) {
755 #if defined(OS_ANDROID)
756   return false;
757 #endif  // defined(OS_ANDROID)
758   if (is_scripted_printing_blocked_)
759     return false;
760   // If preview is enabled, then the print dialog is tab modal, and the user
761   // can always close the tab on a mis-behaving page (the system print dialog
762   // is app modal). If the print was initiated through user action, don't
763   // throttle. Or, if the command line flag to skip throttling has been set.
764   if (!is_scripted_print_throttling_disabled_ &&
765       !is_preview_enabled_ &&
766       !user_initiated)
767     return !IsScriptInitiatedPrintTooFrequent(frame);
768   return true;
769 }
770
771 void PrintWebViewHelper::DidStartLoading() {
772   is_loading_ = true;
773 }
774
775 void PrintWebViewHelper::DidStopLoading() {
776   is_loading_ = false;
777   ShowScriptedPrintPreview();
778 }
779
780 // Prints |frame| which called window.print().
781 void PrintWebViewHelper::PrintPage(blink::WebFrame* frame,
782                                    bool user_initiated) {
783   DCHECK(frame);
784
785 #if !defined(OS_ANDROID)
786   // TODO(sgurun) android_webview hack
787   // Allow Prerendering to cancel this print request if necessary.
788   if (prerender::PrerenderHelper::IsPrerendering(render_view())) {
789     Send(new ChromeViewHostMsg_CancelPrerenderForPrinting(routing_id()));
790     return;
791   }
792 #endif  // !defined(OS_ANDROID)
793
794   if (!IsScriptInitiatedPrintAllowed(frame, user_initiated))
795     return;
796   IncrementScriptedPrintCount();
797
798   if (is_preview_enabled_) {
799     print_preview_context_.InitWithFrame(frame);
800     RequestPrintPreview(PRINT_PREVIEW_SCRIPTED);
801   } else {
802     Print(frame, blink::WebNode());
803   }
804 }
805
806 bool PrintWebViewHelper::OnMessageReceived(const IPC::Message& message) {
807   bool handled = true;
808   IPC_BEGIN_MESSAGE_MAP(PrintWebViewHelper, message)
809     IPC_MESSAGE_HANDLER(PrintMsg_PrintPages, OnPrintPages)
810     IPC_MESSAGE_HANDLER(PrintMsg_PrintForSystemDialog, OnPrintForSystemDialog)
811     IPC_MESSAGE_HANDLER(PrintMsg_InitiatePrintPreview, OnInitiatePrintPreview)
812     IPC_MESSAGE_HANDLER(PrintMsg_PrintNodeUnderContextMenu,
813                         OnPrintNodeUnderContextMenu)
814     IPC_MESSAGE_HANDLER(PrintMsg_PrintPreview, OnPrintPreview)
815     IPC_MESSAGE_HANDLER(PrintMsg_PrintForPrintPreview, OnPrintForPrintPreview)
816     IPC_MESSAGE_HANDLER(PrintMsg_PrintingDone, OnPrintingDone)
817     IPC_MESSAGE_HANDLER(PrintMsg_ResetScriptedPrintCount,
818                         ResetScriptedPrintCount)
819     IPC_MESSAGE_HANDLER(PrintMsg_SetScriptedPrintingBlocked,
820                         SetScriptedPrintBlocked)
821     IPC_MESSAGE_UNHANDLED(handled = false)
822     IPC_END_MESSAGE_MAP()
823   return handled;
824 }
825
826 void PrintWebViewHelper::OnPrintForPrintPreview(
827     const base::DictionaryValue& job_settings) {
828   DCHECK(is_preview_enabled_);
829   // If still not finished with earlier print request simply ignore.
830   if (prep_frame_view_)
831     return;
832
833   if (!render_view()->GetWebView())
834     return;
835   blink::WebFrame* main_frame = render_view()->GetWebView()->mainFrame();
836   if (!main_frame)
837     return;
838
839   blink::WebDocument document = main_frame->document();
840   // <object> with id="pdf-viewer" is created in
841   // chrome/browser/resources/print_preview/print_preview.js
842   blink::WebElement pdf_element = document.getElementById("pdf-viewer");
843   if (pdf_element.isNull()) {
844     NOTREACHED();
845     return;
846   }
847
848   // Set |print_for_preview_| flag and autoreset it to back to original
849   // on return.
850   base::AutoReset<bool> set_printing_flag(&print_for_preview_, true);
851
852   blink::WebFrame* pdf_frame = pdf_element.document().frame();
853   if (!UpdatePrintSettings(pdf_frame, pdf_element, job_settings)) {
854     LOG(ERROR) << "UpdatePrintSettings failed";
855     DidFinishPrinting(FAIL_PRINT);
856     return;
857   }
858
859   // Print page onto entire page not just printable area. Preview PDF already
860   // has content in correct position taking into account page size and printable
861   // area.
862   // TODO(vitalybuka) : Make this consistent on all platform. This change
863   // affects Windows only. On Linux and OSX RenderPagesForPrint does not use
864   // printable_area. Also we can't change printable_area deeper inside
865   // RenderPagesForPrint for Windows, because it's used also by native
866   // printing and it expects real printable_area value.
867   // See http://crbug.com/123408
868   PrintMsg_Print_Params& print_params = print_pages_params_->params;
869   print_params.printable_area = gfx::Rect(print_params.page_size);
870
871   // Render Pages for printing.
872   if (!RenderPagesForPrint(pdf_frame, pdf_element)) {
873     LOG(ERROR) << "RenderPagesForPrint failed";
874     DidFinishPrinting(FAIL_PRINT);
875   }
876 }
877
878 bool PrintWebViewHelper::GetPrintFrame(blink::WebFrame** frame) {
879   DCHECK(frame);
880   blink::WebView* webView = render_view()->GetWebView();
881   DCHECK(webView);
882   if (!webView)
883     return false;
884
885   // If the user has selected text in the currently focused frame we print
886   // only that frame (this makes print selection work for multiple frames).
887   blink::WebFrame* focusedFrame = webView->focusedFrame();
888   *frame = focusedFrame->hasSelection() ? focusedFrame : webView->mainFrame();
889   return true;
890 }
891
892 void PrintWebViewHelper::OnPrintPages() {
893   blink::WebFrame* frame;
894   if (GetPrintFrame(&frame))
895     Print(frame, blink::WebNode());
896 }
897
898 void PrintWebViewHelper::OnPrintForSystemDialog() {
899   blink::WebFrame* frame = print_preview_context_.source_frame();
900   if (!frame) {
901     NOTREACHED();
902     return;
903   }
904
905   Print(frame, print_preview_context_.source_node());
906 }
907
908 void PrintWebViewHelper::GetPageSizeAndContentAreaFromPageLayout(
909     const PageSizeMargins& page_layout_in_points,
910     gfx::Size* page_size,
911     gfx::Rect* content_area) {
912   *page_size = gfx::Size(
913       page_layout_in_points.content_width +
914           page_layout_in_points.margin_right +
915           page_layout_in_points.margin_left,
916       page_layout_in_points.content_height +
917           page_layout_in_points.margin_top +
918           page_layout_in_points.margin_bottom);
919   *content_area = gfx::Rect(page_layout_in_points.margin_left,
920                             page_layout_in_points.margin_top,
921                             page_layout_in_points.content_width,
922                             page_layout_in_points.content_height);
923 }
924
925 void PrintWebViewHelper::UpdateFrameMarginsCssInfo(
926     const base::DictionaryValue& settings) {
927   int margins_type = 0;
928   if (!settings.GetInteger(kSettingMarginsType, &margins_type))
929     margins_type = DEFAULT_MARGINS;
930   ignore_css_margins_ = (margins_type != DEFAULT_MARGINS);
931 }
932
933 bool PrintWebViewHelper::IsPrintToPdfRequested(
934     const base::DictionaryValue& job_settings) {
935   bool print_to_pdf = false;
936   if (!job_settings.GetBoolean(kSettingPrintToPDF, &print_to_pdf))
937     NOTREACHED();
938   return print_to_pdf;
939 }
940
941 blink::WebPrintScalingOption PrintWebViewHelper::GetPrintScalingOption(
942     bool source_is_html, const base::DictionaryValue& job_settings,
943     const PrintMsg_Print_Params& params) {
944   DCHECK(!print_for_preview_);
945
946   if (params.print_to_pdf)
947     return blink::WebPrintScalingOptionSourceSize;
948
949   if (!source_is_html) {
950     if (!FitToPageEnabled(job_settings))
951       return blink::WebPrintScalingOptionNone;
952
953     bool no_plugin_scaling =
954         print_preview_context_.source_frame()->isPrintScalingDisabledForPlugin(
955             print_preview_context_.source_node());
956
957     if (params.is_first_request && no_plugin_scaling)
958       return blink::WebPrintScalingOptionNone;
959   }
960   return blink::WebPrintScalingOptionFitToPrintableArea;
961 }
962
963 void PrintWebViewHelper::OnPrintPreview(const base::DictionaryValue& settings) {
964   DCHECK(is_preview_enabled_);
965   print_preview_context_.OnPrintPreview();
966
967   UMA_HISTOGRAM_ENUMERATION("PrintPreview.PreviewEvent",
968                             PREVIEW_EVENT_REQUESTED, PREVIEW_EVENT_MAX);
969
970   if (!UpdatePrintSettings(print_preview_context_.source_frame(),
971                            print_preview_context_.source_node(), settings)) {
972     if (print_preview_context_.last_error() != PREVIEW_ERROR_BAD_SETTING) {
973       Send(new PrintHostMsg_PrintPreviewInvalidPrinterSettings(
974           routing_id(), print_pages_params_->params.document_cookie));
975       notify_browser_of_print_failure_ = false;  // Already sent.
976     }
977     DidFinishPrinting(FAIL_PREVIEW);
978     return;
979   }
980
981   // If we are previewing a pdf and the print scaling is disabled, send a
982   // message to browser.
983   if (print_pages_params_->params.is_first_request &&
984       !print_preview_context_.IsModifiable() &&
985       print_preview_context_.source_frame()->isPrintScalingDisabledForPlugin(
986           print_preview_context_.source_node())) {
987     Send(new PrintHostMsg_PrintPreviewScalingDisabled(routing_id()));
988   }
989
990   is_print_ready_metafile_sent_ = false;
991
992   // PDF printer device supports alpha blending.
993   print_pages_params_->params.supports_alpha_blend = true;
994
995   bool generate_draft_pages = false;
996   if (!settings.GetBoolean(kSettingGenerateDraftData,
997                            &generate_draft_pages)) {
998     NOTREACHED();
999   }
1000   print_preview_context_.set_generate_draft_pages(generate_draft_pages);
1001
1002   PrepareFrameForPreviewDocument();
1003 }
1004
1005 void PrintWebViewHelper::PrepareFrameForPreviewDocument() {
1006   reset_prep_frame_view_ = false;
1007
1008   if (!print_pages_params_ || CheckForCancel()) {
1009     DidFinishPrinting(FAIL_PREVIEW);
1010     return;
1011   }
1012
1013   // Don't reset loading frame or WebKit will fail assert. Just retry when
1014   // current selection is loaded.
1015   if (prep_frame_view_ && prep_frame_view_->IsLoadingSelection()) {
1016     reset_prep_frame_view_ = true;
1017     return;
1018   }
1019
1020   const PrintMsg_Print_Params& print_params = print_pages_params_->params;
1021   prep_frame_view_.reset(
1022       new PrepareFrameAndViewForPrint(print_params,
1023                                       print_preview_context_.source_frame(),
1024                                       print_preview_context_.source_node(),
1025                                       ignore_css_margins_));
1026   prep_frame_view_->CopySelectionIfNeeded(
1027       render_view()->GetWebkitPreferences(),
1028       base::Bind(&PrintWebViewHelper::OnFramePreparedForPreviewDocument,
1029                  base::Unretained(this)));
1030 }
1031
1032 void PrintWebViewHelper::OnFramePreparedForPreviewDocument() {
1033   if (reset_prep_frame_view_) {
1034     PrepareFrameForPreviewDocument();
1035     return;
1036   }
1037   DidFinishPrinting(CreatePreviewDocument() ? OK : FAIL_PREVIEW);
1038 }
1039
1040 bool PrintWebViewHelper::CreatePreviewDocument() {
1041   if (!print_pages_params_ || CheckForCancel())
1042     return false;
1043
1044   UMA_HISTOGRAM_ENUMERATION("PrintPreview.PreviewEvent",
1045                             PREVIEW_EVENT_CREATE_DOCUMENT, PREVIEW_EVENT_MAX);
1046
1047   const PrintMsg_Print_Params& print_params = print_pages_params_->params;
1048   const std::vector<int>& pages = print_pages_params_->pages;
1049
1050   if (!print_preview_context_.CreatePreviewDocument(prep_frame_view_.release(),
1051                                                     pages)) {
1052     return false;
1053   }
1054
1055   PageSizeMargins default_page_layout;
1056   ComputePageLayoutInPointsForCss(print_preview_context_.prepared_frame(), 0,
1057                                   print_params, ignore_css_margins_, NULL,
1058                                   &default_page_layout);
1059
1060   bool has_page_size_style = PrintingFrameHasPageSizeStyle(
1061       print_preview_context_.prepared_frame(),
1062       print_preview_context_.total_page_count());
1063   int dpi = GetDPI(&print_params);
1064
1065   gfx::Rect printable_area_in_points(
1066       ConvertUnit(print_params.printable_area.x(), dpi, kPointsPerInch),
1067       ConvertUnit(print_params.printable_area.y(), dpi, kPointsPerInch),
1068       ConvertUnit(print_params.printable_area.width(), dpi, kPointsPerInch),
1069       ConvertUnit(print_params.printable_area.height(), dpi, kPointsPerInch));
1070
1071   // Margins: Send default page layout to browser process.
1072   Send(new PrintHostMsg_DidGetDefaultPageLayout(routing_id(),
1073                                                 default_page_layout,
1074                                                 printable_area_in_points,
1075                                                 has_page_size_style));
1076
1077   PrintHostMsg_DidGetPreviewPageCount_Params params;
1078   params.page_count = print_preview_context_.total_page_count();
1079   params.is_modifiable = print_preview_context_.IsModifiable();
1080   params.document_cookie = print_params.document_cookie;
1081   params.preview_request_id = print_params.preview_request_id;
1082   params.clear_preview_data = print_preview_context_.generate_draft_pages();
1083   Send(new PrintHostMsg_DidGetPreviewPageCount(routing_id(), params));
1084   if (CheckForCancel())
1085     return false;
1086
1087   while (!print_preview_context_.IsFinalPageRendered()) {
1088     int page_number = print_preview_context_.GetNextPageNumber();
1089     DCHECK_GE(page_number, 0);
1090     if (!RenderPreviewPage(page_number, print_params))
1091       return false;
1092
1093     if (CheckForCancel())
1094       return false;
1095
1096     // We must call PrepareFrameAndViewForPrint::FinishPrinting() (by way of
1097     // print_preview_context_.AllPagesRendered()) before calling
1098     // FinalizePrintReadyDocument() when printing a PDF because the plugin
1099     // code does not generate output until we call FinishPrinting().  We do not
1100     // generate draft pages for PDFs, so IsFinalPageRendered() and
1101     // IsLastPageOfPrintReadyMetafile() will be true in the same iteration of
1102     // the loop.
1103     if (print_preview_context_.IsFinalPageRendered())
1104       print_preview_context_.AllPagesRendered();
1105
1106     if (print_preview_context_.IsLastPageOfPrintReadyMetafile()) {
1107       DCHECK(print_preview_context_.IsModifiable() ||
1108              print_preview_context_.IsFinalPageRendered());
1109       if (!FinalizePrintReadyDocument())
1110         return false;
1111     }
1112   }
1113   print_preview_context_.Finished();
1114   return true;
1115 }
1116
1117 bool PrintWebViewHelper::FinalizePrintReadyDocument() {
1118   DCHECK(!is_print_ready_metafile_sent_);
1119   print_preview_context_.FinalizePrintReadyDocument();
1120
1121   // Get the size of the resulting metafile.
1122   PreviewMetafile* metafile = print_preview_context_.metafile();
1123   uint32 buf_size = metafile->GetDataSize();
1124   DCHECK_GT(buf_size, 0u);
1125
1126   PrintHostMsg_DidPreviewDocument_Params preview_params;
1127   preview_params.reuse_existing_data = false;
1128   preview_params.data_size = buf_size;
1129   preview_params.document_cookie = print_pages_params_->params.document_cookie;
1130   preview_params.expected_pages_count =
1131       print_preview_context_.total_page_count();
1132   preview_params.modifiable = print_preview_context_.IsModifiable();
1133   preview_params.preview_request_id =
1134       print_pages_params_->params.preview_request_id;
1135
1136   // Ask the browser to create the shared memory for us.
1137   if (!CopyMetafileDataToSharedMem(metafile,
1138                                    &(preview_params.metafile_data_handle))) {
1139     LOG(ERROR) << "CopyMetafileDataToSharedMem failed";
1140     print_preview_context_.set_error(PREVIEW_ERROR_METAFILE_COPY_FAILED);
1141     return false;
1142   }
1143   is_print_ready_metafile_sent_ = true;
1144
1145   Send(new PrintHostMsg_MetafileReadyForPrinting(routing_id(), preview_params));
1146   return true;
1147 }
1148
1149 void PrintWebViewHelper::OnPrintingDone(bool success) {
1150   notify_browser_of_print_failure_ = false;
1151   if (!success)
1152     LOG(ERROR) << "Failure in OnPrintingDone";
1153   DidFinishPrinting(success ? OK : FAIL_PRINT);
1154 }
1155
1156 void PrintWebViewHelper::SetScriptedPrintBlocked(bool blocked) {
1157   is_scripted_printing_blocked_ = blocked;
1158 }
1159
1160 void PrintWebViewHelper::OnPrintNodeUnderContextMenu() {
1161   PrintNode(render_view()->GetContextMenuNode());
1162 }
1163
1164 void PrintWebViewHelper::OnInitiatePrintPreview(bool selection_only) {
1165   DCHECK(is_preview_enabled_);
1166   blink::WebFrame* frame = NULL;
1167   GetPrintFrame(&frame);
1168   DCHECK(frame);
1169   print_preview_context_.InitWithFrame(frame);
1170   RequestPrintPreview(selection_only ?
1171                       PRINT_PREVIEW_USER_INITIATED_SELECTION :
1172                       PRINT_PREVIEW_USER_INITIATED_ENTIRE_FRAME);
1173 }
1174
1175 bool PrintWebViewHelper::IsPrintingEnabled() {
1176   bool result = false;
1177   Send(new PrintHostMsg_IsPrintingEnabled(routing_id(), &result));
1178   return result;
1179 }
1180
1181 void PrintWebViewHelper::PrintNode(const blink::WebNode& node) {
1182   if (node.isNull() || !node.document().frame()) {
1183     // This can occur when the context menu refers to an invalid WebNode.
1184     // See http://crbug.com/100890#c17 for a repro case.
1185     return;
1186   }
1187
1188   if (print_node_in_progress_) {
1189     // This can happen as a result of processing sync messages when printing
1190     // from ppapi plugins. It's a rare case, so its OK to just fail here.
1191     // See http://crbug.com/159165.
1192     return;
1193   }
1194
1195   print_node_in_progress_ = true;
1196
1197   // Make a copy of the node, in case RenderView::OnContextMenuClosed resets
1198   // its |context_menu_node_|.
1199   if (is_preview_enabled_) {
1200     print_preview_context_.InitWithNode(node);
1201     RequestPrintPreview(PRINT_PREVIEW_USER_INITIATED_CONTEXT_NODE);
1202   } else {
1203     blink::WebNode duplicate_node(node);
1204     Print(duplicate_node.document().frame(), duplicate_node);
1205   }
1206
1207   print_node_in_progress_ = false;
1208 }
1209
1210 void PrintWebViewHelper::Print(blink::WebFrame* frame,
1211                                const blink::WebNode& node) {
1212   // If still not finished with earlier print request simply ignore.
1213   if (prep_frame_view_)
1214     return;
1215
1216   FrameReference frame_ref(frame);
1217
1218   int expected_page_count = 0;
1219   if (!CalculateNumberOfPages(frame, node, &expected_page_count)) {
1220     DidFinishPrinting(FAIL_PRINT_INIT);
1221     return;  // Failed to init print page settings.
1222   }
1223
1224   // Some full screen plugins can say they don't want to print.
1225   if (!expected_page_count) {
1226     DidFinishPrinting(FAIL_PRINT);
1227     return;
1228   }
1229
1230 #if !defined(OS_ANDROID)
1231   // TODO(sgurun) android_webview hack
1232   // Ask the browser to show UI to retrieve the final print settings.
1233   if (!GetPrintSettingsFromUser(frame_ref.GetFrame(), node,
1234                                 expected_page_count)) {
1235     DidFinishPrinting(OK);  // Release resources and fail silently.
1236     return;
1237   }
1238 #endif  // !defined(OS_ANDROID)
1239
1240   // Render Pages for printing.
1241   if (!RenderPagesForPrint(frame_ref.GetFrame(), node)) {
1242     LOG(ERROR) << "RenderPagesForPrint failed";
1243     DidFinishPrinting(FAIL_PRINT);
1244   }
1245   ResetScriptedPrintCount();
1246 }
1247
1248 void PrintWebViewHelper::DidFinishPrinting(PrintingResult result) {
1249   switch (result) {
1250     case OK:
1251       break;
1252
1253     case FAIL_PRINT_INIT:
1254       DCHECK(!notify_browser_of_print_failure_);
1255       break;
1256
1257     case FAIL_PRINT:
1258       if (notify_browser_of_print_failure_ && print_pages_params_.get()) {
1259         int cookie = print_pages_params_->params.document_cookie;
1260         Send(new PrintHostMsg_PrintingFailed(routing_id(), cookie));
1261       }
1262       break;
1263
1264     case FAIL_PREVIEW:
1265       DCHECK(is_preview_enabled_);
1266       int cookie = print_pages_params_.get() ?
1267           print_pages_params_->params.document_cookie : 0;
1268       if (notify_browser_of_print_failure_) {
1269         LOG(ERROR) << "CreatePreviewDocument failed";
1270         Send(new PrintHostMsg_PrintPreviewFailed(routing_id(), cookie));
1271       } else {
1272         Send(new PrintHostMsg_PrintPreviewCancelled(routing_id(), cookie));
1273       }
1274       print_preview_context_.Failed(notify_browser_of_print_failure_);
1275       break;
1276   }
1277
1278   prep_frame_view_.reset();
1279   print_pages_params_.reset();
1280   notify_browser_of_print_failure_ = true;
1281 }
1282
1283 void PrintWebViewHelper::OnFramePreparedForPrintPages() {
1284   PrintPages();
1285   FinishFramePrinting();
1286 }
1287
1288 void PrintWebViewHelper::PrintPages() {
1289   if (!prep_frame_view_)  // Printing is already canceled or failed.
1290     return;
1291   prep_frame_view_->StartPrinting();
1292
1293   int page_count = prep_frame_view_->GetExpectedPageCount();
1294   if (!page_count) {
1295     LOG(ERROR) << "Can't print 0 pages.";
1296     return DidFinishPrinting(FAIL_PRINT);
1297   }
1298
1299   const PrintMsg_PrintPages_Params& params = *print_pages_params_;
1300   const PrintMsg_Print_Params& print_params = params.params;
1301
1302 #if !defined(OS_CHROMEOS) && !defined(OS_ANDROID)
1303   // TODO(vitalybuka): should be page_count or valid pages from params.pages.
1304   // See http://crbug.com/161576
1305   Send(new PrintHostMsg_DidGetPrintedPagesCount(routing_id(),
1306                                                 print_params.document_cookie,
1307                                                 page_count));
1308 #endif  // !defined(OS_CHROMEOS)
1309
1310   if (print_params.preview_ui_id < 0) {
1311     // Printing for system dialog.
1312     int printed_count = params.pages.empty() ? page_count : params.pages.size();
1313 #if !defined(OS_CHROMEOS)
1314     UMA_HISTOGRAM_COUNTS("PrintPreview.PageCount.SystemDialog", printed_count);
1315 #else
1316     UMA_HISTOGRAM_COUNTS("PrintPreview.PageCount.PrintToCloudPrintWebDialog",
1317                          printed_count);
1318 #endif  // !defined(OS_CHROMEOS)
1319   }
1320
1321
1322   if (!PrintPagesNative(prep_frame_view_->frame(), page_count,
1323                         prep_frame_view_->GetPrintCanvasSize())) {
1324     LOG(ERROR) << "Printing failed.";
1325     return DidFinishPrinting(FAIL_PRINT);
1326   }
1327 }
1328
1329 void PrintWebViewHelper::FinishFramePrinting() {
1330   prep_frame_view_.reset();
1331 }
1332
1333 #if defined(OS_MACOSX) || defined(OS_WIN)
1334 bool PrintWebViewHelper::PrintPagesNative(blink::WebFrame* frame,
1335                                           int page_count,
1336                                           const gfx::Size& canvas_size) {
1337   const PrintMsg_PrintPages_Params& params = *print_pages_params_;
1338   const PrintMsg_Print_Params& print_params = params.params;
1339
1340   PrintMsg_PrintPage_Params page_params;
1341   page_params.params = print_params;
1342   if (params.pages.empty()) {
1343     for (int i = 0; i < page_count; ++i) {
1344       page_params.page_number = i;
1345       PrintPageInternal(page_params, canvas_size, frame);
1346     }
1347   } else {
1348     for (size_t i = 0; i < params.pages.size(); ++i) {
1349       if (params.pages[i] >= page_count)
1350         break;
1351       page_params.page_number = params.pages[i];
1352       PrintPageInternal(page_params, canvas_size, frame);
1353     }
1354   }
1355   return true;
1356 }
1357
1358 #endif  // OS_MACOSX || OS_WIN
1359
1360 // static - Not anonymous so that platform implementations can use it.
1361 void PrintWebViewHelper::ComputePageLayoutInPointsForCss(
1362     blink::WebFrame* frame,
1363     int page_index,
1364     const PrintMsg_Print_Params& page_params,
1365     bool ignore_css_margins,
1366     double* scale_factor,
1367     PageSizeMargins* page_layout_in_points) {
1368   PrintMsg_Print_Params params = CalculatePrintParamsForCss(
1369       frame, page_index, page_params, ignore_css_margins,
1370       page_params.print_scaling_option ==
1371           blink::WebPrintScalingOptionFitToPrintableArea,
1372       scale_factor);
1373   CalculatePageLayoutFromPrintParams(params, page_layout_in_points);
1374 }
1375
1376 bool PrintWebViewHelper::InitPrintSettings(bool fit_to_paper_size) {
1377   PrintMsg_PrintPages_Params settings;
1378   Send(new PrintHostMsg_GetDefaultPrintSettings(routing_id(),
1379                                                 &settings.params));
1380   // Check if the printer returned any settings, if the settings is empty, we
1381   // can safely assume there are no printer drivers configured. So we safely
1382   // terminate.
1383   bool result = true;
1384   if (!PrintMsg_Print_Params_IsValid(settings.params))
1385     result = false;
1386
1387   if (result &&
1388       (settings.params.dpi < kMinDpi || settings.params.document_cookie == 0)) {
1389     // Invalid print page settings.
1390     NOTREACHED();
1391     result = false;
1392   }
1393
1394   // Reset to default values.
1395   ignore_css_margins_ = false;
1396   settings.pages.clear();
1397
1398   settings.params.print_scaling_option =
1399       blink::WebPrintScalingOptionSourceSize;
1400   if (fit_to_paper_size) {
1401     settings.params.print_scaling_option =
1402         blink::WebPrintScalingOptionFitToPrintableArea;
1403   }
1404
1405   print_pages_params_.reset(new PrintMsg_PrintPages_Params(settings));
1406   return result;
1407 }
1408
1409 bool PrintWebViewHelper::CalculateNumberOfPages(blink::WebFrame* frame,
1410                                                 const blink::WebNode& node,
1411                                                 int* number_of_pages) {
1412   DCHECK(frame);
1413   bool fit_to_paper_size = !(PrintingNodeOrPdfFrame(frame, node));
1414   if (!InitPrintSettings(fit_to_paper_size)) {
1415     notify_browser_of_print_failure_ = false;
1416 #if !defined(OS_ANDROID)
1417     // TODO(sgurun) android_webview hack
1418     render_view()->RunModalAlertDialog(
1419         frame,
1420         l10n_util::GetStringUTF16(IDS_PRINT_INVALID_PRINTER_SETTINGS));
1421 #endif  //  !defined(OS_ANDROID)
1422     return false;
1423   }
1424
1425   const PrintMsg_Print_Params& params = print_pages_params_->params;
1426   PrepareFrameAndViewForPrint prepare(params, frame, node, ignore_css_margins_);
1427   prepare.StartPrinting();
1428
1429   Send(new PrintHostMsg_DidGetDocumentCookie(routing_id(),
1430                                              params.document_cookie));
1431   *number_of_pages = prepare.GetExpectedPageCount();
1432   return true;
1433 }
1434
1435 bool PrintWebViewHelper::UpdatePrintSettings(
1436     blink::WebFrame* frame,
1437     const blink::WebNode& node,
1438     const base::DictionaryValue& passed_job_settings) {
1439   DCHECK(is_preview_enabled_);
1440   const base::DictionaryValue* job_settings = &passed_job_settings;
1441   base::DictionaryValue modified_job_settings;
1442   if (job_settings->empty()) {
1443     if (!print_for_preview_)
1444       print_preview_context_.set_error(PREVIEW_ERROR_BAD_SETTING);
1445     return false;
1446   }
1447
1448   bool source_is_html = true;
1449   if (print_for_preview_) {
1450     if (!job_settings->GetBoolean(kSettingPreviewModifiable, &source_is_html)) {
1451       NOTREACHED();
1452     }
1453   } else {
1454     source_is_html = !PrintingNodeOrPdfFrame(frame, node);
1455   }
1456
1457   if (print_for_preview_ || !source_is_html) {
1458     modified_job_settings.MergeDictionary(job_settings);
1459     modified_job_settings.SetBoolean(kSettingHeaderFooterEnabled, false);
1460     modified_job_settings.SetInteger(kSettingMarginsType, NO_MARGINS);
1461     job_settings = &modified_job_settings;
1462   }
1463
1464   // Send the cookie so that UpdatePrintSettings can reuse PrinterQuery when
1465   // possible.
1466   int cookie = print_pages_params_.get() ?
1467       print_pages_params_->params.document_cookie : 0;
1468   PrintMsg_PrintPages_Params settings;
1469   Send(new PrintHostMsg_UpdatePrintSettings(routing_id(), cookie, *job_settings,
1470                                             &settings));
1471   print_pages_params_.reset(new PrintMsg_PrintPages_Params(settings));
1472
1473   if (!PrintMsg_Print_Params_IsValid(settings.params)) {
1474     if (!print_for_preview_) {
1475       print_preview_context_.set_error(PREVIEW_ERROR_INVALID_PRINTER_SETTINGS);
1476     } else {
1477 #if !defined(OS_ANDROID)
1478       // TODO(sgurun) android_webview hack
1479       // PrintForPrintPreview
1480       blink::WebFrame* print_frame = NULL;
1481       // This may not be the right frame, but the alert will be modal,
1482       // therefore it works well enough.
1483       GetPrintFrame(&print_frame);
1484       if (print_frame) {
1485         render_view()->RunModalAlertDialog(
1486             print_frame,
1487             l10n_util::GetStringUTF16(
1488                 IDS_PRINT_INVALID_PRINTER_SETTINGS));
1489       }
1490 #endif  // !defined(OS_ANDROID)
1491     }
1492     return false;
1493   }
1494
1495   if (settings.params.dpi < kMinDpi || !settings.params.document_cookie) {
1496     print_preview_context_.set_error(PREVIEW_ERROR_UPDATING_PRINT_SETTINGS);
1497     return false;
1498   }
1499
1500   if (!job_settings->GetInteger(kPreviewUIID, &settings.params.preview_ui_id)) {
1501     NOTREACHED();
1502     print_preview_context_.set_error(PREVIEW_ERROR_BAD_SETTING);
1503     return false;
1504   }
1505
1506   if (!print_for_preview_) {
1507     // Validate expected print preview settings.
1508     if (!job_settings->GetInteger(kPreviewRequestID,
1509                                   &settings.params.preview_request_id) ||
1510         !job_settings->GetBoolean(kIsFirstRequest,
1511                                   &settings.params.is_first_request)) {
1512       NOTREACHED();
1513       print_preview_context_.set_error(PREVIEW_ERROR_BAD_SETTING);
1514       return false;
1515     }
1516
1517     settings.params.print_to_pdf = IsPrintToPdfRequested(*job_settings);
1518     UpdateFrameMarginsCssInfo(*job_settings);
1519     settings.params.print_scaling_option = GetPrintScalingOption(
1520         source_is_html, *job_settings, settings.params);
1521
1522     // Header/Footer: Set |header_footer_info_|.
1523     if (settings.params.display_header_footer) {
1524       header_footer_info_.reset(new base::DictionaryValue());
1525       header_footer_info_->SetDouble(kSettingHeaderFooterDate,
1526                                      base::Time::Now().ToJsTime());
1527       header_footer_info_->SetString(kSettingHeaderFooterURL,
1528                                      settings.params.url);
1529       header_footer_info_->SetString(kSettingHeaderFooterTitle,
1530                                      settings.params.title);
1531     }
1532   }
1533
1534   print_pages_params_.reset(new PrintMsg_PrintPages_Params(settings));
1535   Send(new PrintHostMsg_DidGetDocumentCookie(routing_id(),
1536                                              settings.params.document_cookie));
1537
1538   return true;
1539 }
1540
1541 bool PrintWebViewHelper::GetPrintSettingsFromUser(blink::WebFrame* frame,
1542                                                   const blink::WebNode& node,
1543                                                   int expected_pages_count) {
1544   PrintHostMsg_ScriptedPrint_Params params;
1545   PrintMsg_PrintPages_Params print_settings;
1546
1547   params.cookie = print_pages_params_->params.document_cookie;
1548   params.has_selection = frame->hasSelection();
1549   params.expected_pages_count = expected_pages_count;
1550   MarginType margin_type = DEFAULT_MARGINS;
1551   if (PrintingNodeOrPdfFrame(frame, node))
1552     margin_type = GetMarginsForPdf(frame, node);
1553   params.margin_type = margin_type;
1554
1555   Send(new PrintHostMsg_DidShowPrintDialog(routing_id()));
1556
1557   // PrintHostMsg_ScriptedPrint will reset print_scaling_option, so we save the
1558   // value before and restore it afterwards.
1559   blink::WebPrintScalingOption scaling_option =
1560       print_pages_params_->params.print_scaling_option;
1561
1562   print_pages_params_.reset();
1563   IPC::SyncMessage* msg =
1564       new PrintHostMsg_ScriptedPrint(routing_id(), params, &print_settings);
1565   msg->EnableMessagePumping();
1566   Send(msg);
1567   print_pages_params_.reset(new PrintMsg_PrintPages_Params(print_settings));
1568
1569   print_pages_params_->params.print_scaling_option = scaling_option;
1570   return (print_settings.params.dpi && print_settings.params.document_cookie);
1571 }
1572
1573 bool PrintWebViewHelper::RenderPagesForPrint(blink::WebFrame* frame,
1574                                              const blink::WebNode& node) {
1575   if (!frame || prep_frame_view_)
1576     return false;
1577   const PrintMsg_PrintPages_Params& params = *print_pages_params_;
1578   const PrintMsg_Print_Params& print_params = params.params;
1579   prep_frame_view_.reset(
1580       new PrepareFrameAndViewForPrint(print_params, frame, node,
1581                                       ignore_css_margins_));
1582   DCHECK(!print_pages_params_->params.selection_only ||
1583          print_pages_params_->pages.empty());
1584   prep_frame_view_->CopySelectionIfNeeded(
1585       render_view()->GetWebkitPreferences(),
1586       base::Bind(&PrintWebViewHelper::OnFramePreparedForPrintPages,
1587                  base::Unretained(this)));
1588   return true;
1589 }
1590
1591 #if defined(OS_POSIX)
1592 bool PrintWebViewHelper::CopyMetafileDataToSharedMem(
1593     Metafile* metafile,
1594     base::SharedMemoryHandle* shared_mem_handle) {
1595   uint32 buf_size = metafile->GetDataSize();
1596   scoped_ptr<base::SharedMemory> shared_buf(
1597       content::RenderThread::Get()->HostAllocateSharedMemoryBuffer(
1598           buf_size).release());
1599
1600   if (shared_buf.get()) {
1601     if (shared_buf->Map(buf_size)) {
1602       metafile->GetData(shared_buf->memory(), buf_size);
1603       shared_buf->GiveToProcess(base::GetCurrentProcessHandle(),
1604                                 shared_mem_handle);
1605       return true;
1606     }
1607   }
1608   NOTREACHED();
1609   return false;
1610 }
1611 #endif  // defined(OS_POSIX)
1612
1613 bool PrintWebViewHelper::IsScriptInitiatedPrintTooFrequent(
1614     blink::WebFrame* frame) {
1615   const int kMinSecondsToIgnoreJavascriptInitiatedPrint = 2;
1616   const int kMaxSecondsToIgnoreJavascriptInitiatedPrint = 32;
1617   bool too_frequent = false;
1618
1619   // Check if there is script repeatedly trying to print and ignore it if too
1620   // frequent.  The first 3 times, we use a constant wait time, but if this
1621   // gets excessive, we switch to exponential wait time. So for a page that
1622   // calls print() in a loop the user will need to cancel the print dialog
1623   // after: [2, 2, 2, 4, 8, 16, 32, 32, ...] seconds.
1624   // This gives the user time to navigate from the page.
1625   if (user_cancelled_scripted_print_count_ > 0) {
1626     base::TimeDelta diff = base::Time::Now() - last_cancelled_script_print_;
1627     int min_wait_seconds = kMinSecondsToIgnoreJavascriptInitiatedPrint;
1628     if (user_cancelled_scripted_print_count_ > 3) {
1629       min_wait_seconds = std::min(
1630           kMinSecondsToIgnoreJavascriptInitiatedPrint <<
1631               (user_cancelled_scripted_print_count_ - 3),
1632           kMaxSecondsToIgnoreJavascriptInitiatedPrint);
1633     }
1634     if (diff.InSeconds() < min_wait_seconds) {
1635       too_frequent = true;
1636     }
1637   }
1638
1639   if (!too_frequent)
1640     return false;
1641
1642   blink::WebString message(
1643       blink::WebString::fromUTF8("Ignoring too frequent calls to print()."));
1644   frame->addMessageToConsole(
1645       blink::WebConsoleMessage(
1646           blink::WebConsoleMessage::LevelWarning, message));
1647   return true;
1648 }
1649
1650 void PrintWebViewHelper::ResetScriptedPrintCount() {
1651   // Reset cancel counter on successful print.
1652   user_cancelled_scripted_print_count_ = 0;
1653 }
1654
1655 void PrintWebViewHelper::IncrementScriptedPrintCount() {
1656   ++user_cancelled_scripted_print_count_;
1657   last_cancelled_script_print_ = base::Time::Now();
1658 }
1659
1660 void PrintWebViewHelper::ShowScriptedPrintPreview() {
1661   if (is_scripted_preview_delayed_) {
1662     is_scripted_preview_delayed_ = false;
1663     Send(new PrintHostMsg_ShowScriptedPrintPreview(routing_id(),
1664             print_preview_context_.IsModifiable()));
1665   }
1666 }
1667
1668 void PrintWebViewHelper::RequestPrintPreview(PrintPreviewRequestType type) {
1669   const bool is_modifiable = print_preview_context_.IsModifiable();
1670   const bool has_selection = print_preview_context_.HasSelection();
1671   PrintHostMsg_RequestPrintPreview_Params params;
1672   params.is_modifiable = is_modifiable;
1673   params.has_selection = has_selection;
1674   switch (type) {
1675     case PRINT_PREVIEW_SCRIPTED: {
1676       // Shows scripted print preview in two stages.
1677       // 1. PrintHostMsg_SetupScriptedPrintPreview blocks this call and JS by
1678       //    pumping messages here.
1679       // 2. PrintHostMsg_ShowScriptedPrintPreview shows preview once the
1680       //    document has been loaded.
1681       is_scripted_preview_delayed_ = true;
1682       if (is_loading_ && GetPlugin(print_preview_context_.source_frame())) {
1683         // Wait for DidStopLoading. Plugins may not know the correct
1684         // |is_modifiable| value until they are fully loaded, which occurs when
1685         // DidStopLoading() is called. Defer showing the preview until then.
1686       } else {
1687         base::MessageLoop::current()->PostTask(
1688             FROM_HERE,
1689             base::Bind(&PrintWebViewHelper::ShowScriptedPrintPreview,
1690                        weak_ptr_factory_.GetWeakPtr()));
1691       }
1692       IPC::SyncMessage* msg =
1693           new PrintHostMsg_SetupScriptedPrintPreview(routing_id());
1694       msg->EnableMessagePumping();
1695       Send(msg);
1696       is_scripted_preview_delayed_ = false;
1697       return;
1698     }
1699     case PRINT_PREVIEW_USER_INITIATED_ENTIRE_FRAME: {
1700       break;
1701     }
1702     case PRINT_PREVIEW_USER_INITIATED_SELECTION: {
1703       DCHECK(has_selection);
1704       params.selection_only = has_selection;
1705       break;
1706     }
1707     case PRINT_PREVIEW_USER_INITIATED_CONTEXT_NODE: {
1708       params.webnode_only = true;
1709       break;
1710     }
1711     default: {
1712       NOTREACHED();
1713       return;
1714     }
1715   }
1716   Send(new PrintHostMsg_RequestPrintPreview(routing_id(), params));
1717 }
1718
1719 bool PrintWebViewHelper::CheckForCancel() {
1720   const PrintMsg_Print_Params& print_params = print_pages_params_->params;
1721   bool cancel = false;
1722   Send(new PrintHostMsg_CheckForCancel(routing_id(),
1723                                        print_params.preview_ui_id,
1724                                        print_params.preview_request_id,
1725                                        &cancel));
1726   if (cancel)
1727     notify_browser_of_print_failure_ = false;
1728   return cancel;
1729 }
1730
1731 bool PrintWebViewHelper::PreviewPageRendered(int page_number,
1732                                              Metafile* metafile) {
1733   DCHECK_GE(page_number, FIRST_PAGE_INDEX);
1734
1735   // For non-modifiable files, |metafile| should be NULL, so do not bother
1736   // sending a message. If we don't generate draft metafiles, |metafile| is
1737   // NULL.
1738   if (!print_preview_context_.IsModifiable() ||
1739       !print_preview_context_.generate_draft_pages()) {
1740     DCHECK(!metafile);
1741     return true;
1742   }
1743
1744   if (!metafile) {
1745     NOTREACHED();
1746     print_preview_context_.set_error(
1747         PREVIEW_ERROR_PAGE_RENDERED_WITHOUT_METAFILE);
1748     return false;
1749   }
1750
1751   PrintHostMsg_DidPreviewPage_Params preview_page_params;
1752   // Get the size of the resulting metafile.
1753   uint32 buf_size = metafile->GetDataSize();
1754   DCHECK_GT(buf_size, 0u);
1755   if (!CopyMetafileDataToSharedMem(
1756       metafile, &(preview_page_params.metafile_data_handle))) {
1757     LOG(ERROR) << "CopyMetafileDataToSharedMem failed";
1758     print_preview_context_.set_error(PREVIEW_ERROR_METAFILE_COPY_FAILED);
1759     return false;
1760   }
1761   preview_page_params.data_size = buf_size;
1762   preview_page_params.page_number = page_number;
1763   preview_page_params.preview_request_id =
1764       print_pages_params_->params.preview_request_id;
1765
1766   Send(new PrintHostMsg_DidPreviewPage(routing_id(), preview_page_params));
1767   return true;
1768 }
1769
1770 PrintWebViewHelper::PrintPreviewContext::PrintPreviewContext()
1771     : total_page_count_(0),
1772       current_page_index_(0),
1773       generate_draft_pages_(true),
1774       print_ready_metafile_page_count_(0),
1775       error_(PREVIEW_ERROR_NONE),
1776       state_(UNINITIALIZED) {
1777 }
1778
1779 PrintWebViewHelper::PrintPreviewContext::~PrintPreviewContext() {
1780 }
1781
1782 void PrintWebViewHelper::PrintPreviewContext::InitWithFrame(
1783     blink::WebFrame* web_frame) {
1784   DCHECK(web_frame);
1785   DCHECK(!IsRendering());
1786   state_ = INITIALIZED;
1787   source_frame_.Reset(web_frame);
1788   source_node_.reset();
1789 }
1790
1791 void PrintWebViewHelper::PrintPreviewContext::InitWithNode(
1792     const blink::WebNode& web_node) {
1793   DCHECK(!web_node.isNull());
1794   DCHECK(web_node.document().frame());
1795   DCHECK(!IsRendering());
1796   state_ = INITIALIZED;
1797   source_frame_.Reset(web_node.document().frame());
1798   source_node_ = web_node;
1799 }
1800
1801 void PrintWebViewHelper::PrintPreviewContext::OnPrintPreview() {
1802   DCHECK_EQ(INITIALIZED, state_);
1803   ClearContext();
1804 }
1805
1806 bool PrintWebViewHelper::PrintPreviewContext::CreatePreviewDocument(
1807     PrepareFrameAndViewForPrint* prepared_frame,
1808     const std::vector<int>& pages) {
1809   DCHECK_EQ(INITIALIZED, state_);
1810   state_ = RENDERING;
1811
1812   // Need to make sure old object gets destroyed first.
1813   prep_frame_view_.reset(prepared_frame);
1814   prep_frame_view_->StartPrinting();
1815
1816   total_page_count_ = prep_frame_view_->GetExpectedPageCount();
1817   if (total_page_count_ == 0) {
1818     LOG(ERROR) << "CreatePreviewDocument got 0 page count";
1819     set_error(PREVIEW_ERROR_ZERO_PAGES);
1820     return false;
1821   }
1822
1823   metafile_.reset(new PreviewMetafile);
1824   if (!metafile_->Init()) {
1825     set_error(PREVIEW_ERROR_METAFILE_INIT_FAILED);
1826     LOG(ERROR) << "PreviewMetafile Init failed";
1827     return false;
1828   }
1829
1830   current_page_index_ = 0;
1831   pages_to_render_ = pages;
1832   // Sort and make unique.
1833   std::sort(pages_to_render_.begin(), pages_to_render_.end());
1834   pages_to_render_.resize(std::unique(pages_to_render_.begin(),
1835                                       pages_to_render_.end()) -
1836                           pages_to_render_.begin());
1837   // Remove invalid pages.
1838   pages_to_render_.resize(std::lower_bound(pages_to_render_.begin(),
1839                                            pages_to_render_.end(),
1840                                            total_page_count_) -
1841                           pages_to_render_.begin());
1842   print_ready_metafile_page_count_ = pages_to_render_.size();
1843   if (pages_to_render_.empty()) {
1844     print_ready_metafile_page_count_ = total_page_count_;
1845     // Render all pages.
1846     for (int i = 0; i < total_page_count_; ++i)
1847       pages_to_render_.push_back(i);
1848   } else if (generate_draft_pages_) {
1849     int pages_index = 0;
1850     for (int i = 0; i < total_page_count_; ++i) {
1851       if (pages_index < print_ready_metafile_page_count_ &&
1852           i == pages_to_render_[pages_index]) {
1853         pages_index++;
1854         continue;
1855       }
1856       pages_to_render_.push_back(i);
1857     }
1858   }
1859
1860   document_render_time_ = base::TimeDelta();
1861   begin_time_ = base::TimeTicks::Now();
1862
1863   return true;
1864 }
1865
1866 void PrintWebViewHelper::PrintPreviewContext::RenderedPreviewPage(
1867     const base::TimeDelta& page_time) {
1868   DCHECK_EQ(RENDERING, state_);
1869   document_render_time_ += page_time;
1870   UMA_HISTOGRAM_TIMES("PrintPreview.RenderPDFPageTime", page_time);
1871 }
1872
1873 void PrintWebViewHelper::PrintPreviewContext::AllPagesRendered() {
1874   DCHECK_EQ(RENDERING, state_);
1875   state_ = DONE;
1876   prep_frame_view_->FinishPrinting();
1877 }
1878
1879 void PrintWebViewHelper::PrintPreviewContext::FinalizePrintReadyDocument() {
1880   DCHECK(IsRendering());
1881
1882   base::TimeTicks begin_time = base::TimeTicks::Now();
1883   metafile_->FinishDocument();
1884
1885   if (print_ready_metafile_page_count_ <= 0) {
1886     NOTREACHED();
1887     return;
1888   }
1889
1890   UMA_HISTOGRAM_MEDIUM_TIMES("PrintPreview.RenderToPDFTime",
1891                              document_render_time_);
1892   base::TimeDelta total_time = (base::TimeTicks::Now() - begin_time) +
1893                                document_render_time_;
1894   UMA_HISTOGRAM_MEDIUM_TIMES("PrintPreview.RenderAndGeneratePDFTime",
1895                              total_time);
1896   UMA_HISTOGRAM_MEDIUM_TIMES("PrintPreview.RenderAndGeneratePDFTimeAvgPerPage",
1897                              total_time / pages_to_render_.size());
1898 }
1899
1900 void PrintWebViewHelper::PrintPreviewContext::Finished() {
1901   DCHECK_EQ(DONE, state_);
1902   state_ = INITIALIZED;
1903   ClearContext();
1904 }
1905
1906 void PrintWebViewHelper::PrintPreviewContext::Failed(bool report_error) {
1907   DCHECK(state_ == INITIALIZED || state_ == RENDERING);
1908   state_ = INITIALIZED;
1909   if (report_error) {
1910     DCHECK_NE(PREVIEW_ERROR_NONE, error_);
1911     UMA_HISTOGRAM_ENUMERATION("PrintPreview.RendererError", error_,
1912                               PREVIEW_ERROR_LAST_ENUM);
1913   }
1914   ClearContext();
1915 }
1916
1917 int PrintWebViewHelper::PrintPreviewContext::GetNextPageNumber() {
1918   DCHECK_EQ(RENDERING, state_);
1919   if (IsFinalPageRendered())
1920     return -1;
1921   return pages_to_render_[current_page_index_++];
1922 }
1923
1924 bool PrintWebViewHelper::PrintPreviewContext::IsRendering() const {
1925   return state_ == RENDERING || state_ == DONE;
1926 }
1927
1928 bool PrintWebViewHelper::PrintPreviewContext::IsModifiable() {
1929   // The only kind of node we can print right now is a PDF node.
1930   return !PrintingNodeOrPdfFrame(source_frame(), source_node_);
1931 }
1932
1933 bool PrintWebViewHelper::PrintPreviewContext::HasSelection() {
1934   return IsModifiable() && source_frame()->hasSelection();
1935 }
1936
1937 bool PrintWebViewHelper::PrintPreviewContext::IsLastPageOfPrintReadyMetafile()
1938     const {
1939   DCHECK(IsRendering());
1940   return current_page_index_ == print_ready_metafile_page_count_;
1941 }
1942
1943 bool  PrintWebViewHelper::PrintPreviewContext::IsFinalPageRendered() const {
1944   DCHECK(IsRendering());
1945   return static_cast<size_t>(current_page_index_) == pages_to_render_.size();
1946 }
1947
1948 void PrintWebViewHelper::PrintPreviewContext::set_generate_draft_pages(
1949     bool generate_draft_pages) {
1950   DCHECK_EQ(INITIALIZED, state_);
1951   generate_draft_pages_ = generate_draft_pages;
1952 }
1953
1954 void PrintWebViewHelper::PrintPreviewContext::set_error(
1955     enum PrintPreviewErrorBuckets error) {
1956   error_ = error;
1957 }
1958
1959 blink::WebFrame* PrintWebViewHelper::PrintPreviewContext::source_frame() {
1960   DCHECK(state_ != UNINITIALIZED);
1961   return source_frame_.GetFrame();
1962 }
1963
1964 const blink::WebNode&
1965     PrintWebViewHelper::PrintPreviewContext::source_node() const {
1966   DCHECK(state_ != UNINITIALIZED);
1967   return source_node_;
1968 }
1969
1970 blink::WebFrame* PrintWebViewHelper::PrintPreviewContext::prepared_frame() {
1971   DCHECK(state_ != UNINITIALIZED);
1972   return prep_frame_view_->frame();
1973 }
1974
1975 const blink::WebNode&
1976     PrintWebViewHelper::PrintPreviewContext::prepared_node() const {
1977   DCHECK(state_ != UNINITIALIZED);
1978   return prep_frame_view_->node();
1979 }
1980
1981 int PrintWebViewHelper::PrintPreviewContext::total_page_count() const {
1982   DCHECK(state_ != UNINITIALIZED);
1983   return total_page_count_;
1984 }
1985
1986 bool PrintWebViewHelper::PrintPreviewContext::generate_draft_pages() const {
1987   return generate_draft_pages_;
1988 }
1989
1990 PreviewMetafile* PrintWebViewHelper::PrintPreviewContext::metafile() {
1991   DCHECK(IsRendering());
1992   return metafile_.get();
1993 }
1994
1995 int PrintWebViewHelper::PrintPreviewContext::last_error() const {
1996   return error_;
1997 }
1998
1999 gfx::Size PrintWebViewHelper::PrintPreviewContext::GetPrintCanvasSize() const {
2000   DCHECK(IsRendering());
2001   return prep_frame_view_->GetPrintCanvasSize();
2002 }
2003
2004 void PrintWebViewHelper::PrintPreviewContext::ClearContext() {
2005   prep_frame_view_.reset();
2006   metafile_.reset();
2007   pages_to_render_.clear();
2008   error_ = PREVIEW_ERROR_NONE;
2009 }
2010
2011 }  // namespace printing