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