Upstream version 7.36.149.0
[platform/framework/web/crosswalk.git] / src / chrome / renderer / printing / print_web_view_helper.h
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 #ifndef CHROME_RENDERER_PRINTING_PRINT_WEB_VIEW_HELPER_H_
6 #define CHROME_RENDERER_PRINTING_PRINT_WEB_VIEW_HELPER_H_
7
8 #include <vector>
9
10 #include "base/gtest_prod_util.h"
11 #include "base/memory/scoped_ptr.h"
12 #include "base/memory/shared_memory.h"
13 #include "base/memory/weak_ptr.h"
14 #include "base/time/time.h"
15 #include "content/public/renderer/render_view_observer.h"
16 #include "content/public/renderer/render_view_observer_tracker.h"
17 #include "printing/metafile_impl.h"
18 #include "third_party/WebKit/public/platform/WebCanvas.h"
19 #include "third_party/WebKit/public/web/WebNode.h"
20 #include "third_party/WebKit/public/web/WebPrintParams.h"
21 #include "ui/gfx/size.h"
22
23 struct PrintMsg_Print_Params;
24 struct PrintMsg_PrintPage_Params;
25 struct PrintMsg_PrintPages_Params;
26
27 namespace base {
28 class DictionaryValue;
29 }
30
31 namespace blink {
32 class WebFrame;
33 class WebView;
34 }
35
36 namespace printing {
37
38 struct PageSizeMargins;
39 class PrepareFrameAndViewForPrint;
40
41 // Stores reference to frame using WebVew and unique name.
42 // Workaround to modal dialog issue on Linux. crbug.com/236147.
43 // If WebFrame someday supports WeakPtr, we should use it here.
44 class FrameReference {
45  public:
46   explicit FrameReference(blink::WebLocalFrame* frame);
47   FrameReference();
48   ~FrameReference();
49
50   void Reset(blink::WebLocalFrame* frame);
51
52   blink::WebLocalFrame* GetFrame();
53   blink::WebView* view();
54
55  private:
56   blink::WebView* view_;
57   blink::WebLocalFrame* frame_;
58 };
59
60 // PrintWebViewHelper handles most of the printing grunt work for RenderView.
61 // We plan on making print asynchronous and that will require copying the DOM
62 // of the document and creating a new WebView with the contents.
63 class PrintWebViewHelper
64     : public content::RenderViewObserver,
65       public content::RenderViewObserverTracker<PrintWebViewHelper> {
66  public:
67   explicit PrintWebViewHelper(content::RenderView* render_view);
68   virtual ~PrintWebViewHelper();
69
70   bool IsPrintingEnabled();
71
72   void PrintNode(const blink::WebNode& node);
73
74  private:
75   friend class PrintWebViewHelperTestBase;
76   FRIEND_TEST_ALL_PREFIXES(PrintWebViewHelperTest,
77                            BlockScriptInitiatedPrinting);
78   FRIEND_TEST_ALL_PREFIXES(PrintWebViewHelperTest,
79                            BlockScriptInitiatedPrintingFromPopup);
80   FRIEND_TEST_ALL_PREFIXES(PrintWebViewHelperTest, OnPrintPages);
81
82 #if defined(OS_WIN) || defined(OS_MACOSX)
83   FRIEND_TEST_ALL_PREFIXES(PrintWebViewHelperTest, PrintLayoutTest);
84   FRIEND_TEST_ALL_PREFIXES(PrintWebViewHelperTest, PrintWithIframe);
85 #endif  // defined(OS_WIN) || defined(OS_MACOSX)
86
87   enum PrintingResult {
88     OK,
89     FAIL_PRINT_INIT,
90     FAIL_PRINT,
91     FAIL_PREVIEW,
92   };
93
94   enum PrintPreviewErrorBuckets {
95     PREVIEW_ERROR_NONE,  // Always first.
96     PREVIEW_ERROR_BAD_SETTING,
97     PREVIEW_ERROR_METAFILE_COPY_FAILED,
98     PREVIEW_ERROR_METAFILE_INIT_FAILED,
99     PREVIEW_ERROR_ZERO_PAGES,
100     PREVIEW_ERROR_MAC_DRAFT_METAFILE_INIT_FAILED,
101     PREVIEW_ERROR_PAGE_RENDERED_WITHOUT_METAFILE,
102     PREVIEW_ERROR_UPDATING_PRINT_SETTINGS,
103     PREVIEW_ERROR_INVALID_PRINTER_SETTINGS,
104     PREVIEW_ERROR_LAST_ENUM  // Always last.
105   };
106
107   enum PrintPreviewRequestType {
108     PRINT_PREVIEW_USER_INITIATED_ENTIRE_FRAME,
109     PRINT_PREVIEW_USER_INITIATED_SELECTION,
110     PRINT_PREVIEW_USER_INITIATED_CONTEXT_NODE,
111     PRINT_PREVIEW_SCRIPTED  // triggered by window.print().
112   };
113
114   // RenderViewObserver implementation.
115   virtual bool OnMessageReceived(const IPC::Message& message) OVERRIDE;
116   virtual void PrintPage(blink::WebLocalFrame* frame,
117                          bool user_initiated) OVERRIDE;
118   virtual void DidStartLoading() OVERRIDE;
119   virtual void DidStopLoading() OVERRIDE;
120
121   // Message handlers ---------------------------------------------------------
122   void OnPrintPages();
123   void OnPrintForSystemDialog();
124   void OnInitiatePrintPreview(bool selection_only);
125   void OnPrintPreview(const base::DictionaryValue& settings);
126   void OnPrintForPrintPreview(const base::DictionaryValue& job_settings);
127   void OnPrintingDone(bool success);
128
129   // Get |page_size| and |content_area| information from
130   // |page_layout_in_points|.
131   void GetPageSizeAndContentAreaFromPageLayout(
132       const PageSizeMargins& page_layout_in_points,
133       gfx::Size* page_size,
134       gfx::Rect* content_area);
135
136   // Update |ignore_css_margins_| based on settings.
137   void UpdateFrameMarginsCssInfo(const base::DictionaryValue& settings);
138
139   // Returns true if the current destination printer is PRINT_TO_PDF.
140   bool IsPrintToPdfRequested(const base::DictionaryValue& settings);
141
142   // Prepare frame for creating preview document.
143   void PrepareFrameForPreviewDocument();
144
145   // Continue creating preview document.
146   void OnFramePreparedForPreviewDocument();
147
148   // Initialize the print preview document.
149   bool CreatePreviewDocument();
150
151   // Renders a print preview page. |page_number| is 0-based.
152   // Returns true if print preview should continue, false on failure.
153   bool RenderPreviewPage(int page_number,
154                          const PrintMsg_Print_Params& print_params);
155
156   // Finalize the print ready preview document.
157   bool FinalizePrintReadyDocument();
158
159   // Enable/Disable window.print calls.  If |blocked| is true window.print
160   // calls will silently fail.  Call with |blocked| set to false to reenable.
161   void SetScriptedPrintBlocked(bool blocked);
162
163   // Main printing code -------------------------------------------------------
164
165   void Print(blink::WebLocalFrame* frame, const blink::WebNode& node);
166
167   // Notification when printing is done - signal tear-down/free resources.
168   void DidFinishPrinting(PrintingResult result);
169
170   // Print Settings -----------------------------------------------------------
171
172   // Initialize print page settings with default settings.
173   // Used only for native printing workflow.
174   bool InitPrintSettings(bool fit_to_paper_size);
175
176   // Calculate number of pages in source document.
177   bool CalculateNumberOfPages(blink::WebLocalFrame* frame,
178                               const blink::WebNode& node,
179                               int* number_of_pages);
180
181   // Update the current print settings with new |passed_job_settings|.
182   // |passed_job_settings| dictionary contains print job details such as printer
183   // name, number of copies, page range, etc.
184   bool UpdatePrintSettings(blink::WebLocalFrame* frame,
185                            const blink::WebNode& node,
186                            const base::DictionaryValue& passed_job_settings);
187
188   // Get final print settings from the user.
189   // Return false if the user cancels or on error.
190   bool GetPrintSettingsFromUser(blink::WebFrame* frame,
191                                 const blink::WebNode& node,
192                                 int expected_pages_count);
193
194   // Page Printing / Rendering ------------------------------------------------
195
196   void OnFramePreparedForPrintPages();
197   void PrintPages();
198   bool PrintPagesNative(blink::WebFrame* frame,
199                         int page_count,
200                         const gfx::Size& canvas_size);
201   void FinishFramePrinting();
202
203   // Prints the page listed in |params|.
204 #if defined(OS_LINUX) || defined(OS_ANDROID)
205   void PrintPageInternal(const PrintMsg_PrintPage_Params& params,
206                          const gfx::Size& canvas_size,
207                          blink::WebFrame* frame,
208                          Metafile* metafile);
209 #else
210   void PrintPageInternal(const PrintMsg_PrintPage_Params& params,
211                          const gfx::Size& canvas_size,
212                          blink::WebFrame* frame);
213 #endif
214
215   // Render the frame for printing.
216   bool RenderPagesForPrint(blink::WebLocalFrame* frame,
217                            const blink::WebNode& node);
218
219   // Platform specific helper function for rendering page(s) to |metafile|.
220 #if defined(OS_WIN)
221   void RenderPage(const PrintMsg_Print_Params& params,
222                   int page_number,
223                   blink::WebFrame* frame,
224                   bool is_preview,
225                   Metafile* metafile,
226                   double* scale_factor,
227                   gfx::Size* page_size_in_dpi,
228                   gfx::Rect* content_area_in_dpi);
229 #elif defined(OS_MACOSX)
230   void RenderPage(const PrintMsg_Print_Params& params,
231                   int page_number,
232                   blink::WebFrame* frame,
233                   bool is_preview,
234                   Metafile* metafile,
235                   gfx::Size* page_size,
236                   gfx::Rect* content_rect);
237 #endif  // defined(OS_WIN)
238
239   // Renders page contents from |frame| to |content_area| of |canvas|.
240   // |page_number| is zero-based.
241   // When method is called, canvas should be setup to draw to |canvas_area|
242   // with |scale_factor|.
243   static float RenderPageContent(blink::WebFrame* frame,
244                                  int page_number,
245                                  const gfx::Rect& canvas_area,
246                                  const gfx::Rect& content_area,
247                                  double scale_factor,
248                                  blink::WebCanvas* canvas);
249
250   // Helper methods -----------------------------------------------------------
251
252   bool CopyMetafileDataToSharedMem(Metafile* metafile,
253                                    base::SharedMemoryHandle* shared_mem_handle);
254
255   // Helper method to get page layout in points and fit to page if needed.
256   static void ComputePageLayoutInPointsForCss(
257       blink::WebFrame* frame,
258       int page_index,
259       const PrintMsg_Print_Params& default_params,
260       bool ignore_css_margins,
261       double* scale_factor,
262       PageSizeMargins* page_layout_in_points);
263
264   // Given the |device| and |canvas| to draw on, prints the appropriate headers
265   // and footers using strings from |header_footer_info| on to the canvas.
266   static void PrintHeaderAndFooter(
267       blink::WebCanvas* canvas,
268       int page_number,
269       int total_pages,
270       float webkit_scale_factor,
271       const PageSizeMargins& page_layout_in_points,
272       const base::DictionaryValue& header_footer_info,
273       const PrintMsg_Print_Params& params);
274
275   bool GetPrintFrame(blink::WebLocalFrame** frame);
276
277   // Script Initiated Printing ------------------------------------------------
278
279   // Return true if script initiated printing is currently
280   // allowed. |user_initiated| should be true when a user event triggered the
281   // script, most likely by pressing a print button on the page.
282   bool IsScriptInitiatedPrintAllowed(blink::WebFrame* frame,
283                                      bool user_initiated);
284
285   // Returns true if script initiated printing occurs too often.
286   bool IsScriptInitiatedPrintTooFrequent(blink::WebFrame* frame);
287
288   // Reset the counter for script initiated printing.
289   // Scripted printing will be allowed to continue.
290   void ResetScriptedPrintCount();
291
292   // Increment the counter for script initiated printing.
293   // Scripted printing will be blocked for a limited amount of time.
294   void IncrementScriptedPrintCount();
295
296   // Shows scripted print preview when options from plugin are availible.
297   void ShowScriptedPrintPreview();
298
299   void RequestPrintPreview(PrintPreviewRequestType type);
300
301   // Checks whether print preview should continue or not.
302   // Returns true if cancelling, false if continuing.
303   bool CheckForCancel();
304
305   // Notifies the browser a print preview page has been rendered.
306   // |page_number| is 0-based.
307   // For a valid |page_number| with modifiable content,
308   // |metafile| is the rendered page. Otherwise |metafile| is NULL.
309   // Returns true if print preview should continue, false on failure.
310   bool PreviewPageRendered(int page_number, Metafile* metafile);
311
312   // WebView used only to print the selection.
313   scoped_ptr<PrepareFrameAndViewForPrint> prep_frame_view_;
314   bool reset_prep_frame_view_;
315
316   scoped_ptr<PrintMsg_PrintPages_Params> print_pages_params_;
317   bool is_preview_enabled_;
318   bool is_scripted_print_throttling_disabled_;
319   bool is_print_ready_metafile_sent_;
320   bool ignore_css_margins_;
321
322   // Used for scripted initiated printing blocking.
323   base::Time last_cancelled_script_print_;
324   int user_cancelled_scripted_print_count_;
325   bool is_scripted_printing_blocked_;
326
327   // Let the browser process know of a printing failure. Only set to false when
328   // the failure came from the browser in the first place.
329   bool notify_browser_of_print_failure_;
330
331   // True, when printing from print preview.
332   bool print_for_preview_;
333
334   // Strings generated by the browser process to be printed as headers and
335   // footers if requested by the user.
336   scoped_ptr<base::DictionaryValue> header_footer_info_;
337
338   // Keeps track of the state of print preview between messages.
339   // TODO(vitalybuka): Create PrintPreviewContext when needed and delete after
340   // use. Now it's interaction with various messages is confusing.
341   class PrintPreviewContext {
342    public:
343     PrintPreviewContext();
344     ~PrintPreviewContext();
345
346     // Initializes the print preview context. Need to be called to set
347     // the |web_frame| / |web_node| to generate the print preview for.
348     void InitWithFrame(blink::WebLocalFrame* web_frame);
349     void InitWithNode(const blink::WebNode& web_node);
350
351     // Does bookkeeping at the beginning of print preview.
352     void OnPrintPreview();
353
354     // Create the print preview document. |pages| is empty to print all pages.
355     // Takes ownership of |prepared_frame|.
356     bool CreatePreviewDocument(PrepareFrameAndViewForPrint* prepared_frame,
357                                const std::vector<int>& pages);
358
359     // Called after a page gets rendered. |page_time| is how long the
360     // rendering took.
361     void RenderedPreviewPage(const base::TimeDelta& page_time);
362
363     // Updates the print preview context when the required pages are rendered.
364     void AllPagesRendered();
365
366     // Finalizes the print ready preview document.
367     void FinalizePrintReadyDocument();
368
369     // Cleanup after print preview finishes.
370     void Finished();
371
372     // Cleanup after print preview fails.
373     void Failed(bool report_error);
374
375     // Helper functions
376     int GetNextPageNumber();
377     bool IsRendering() const;
378     bool IsModifiable();
379     bool HasSelection();
380     bool IsLastPageOfPrintReadyMetafile() const;
381     bool IsFinalPageRendered() const;
382
383     // Setters
384     void set_generate_draft_pages(bool generate_draft_pages);
385     void set_error(enum PrintPreviewErrorBuckets error);
386
387     // Getters
388     // Original frame for which preview was requested.
389     blink::WebLocalFrame* source_frame();
390     // Original node for which preview was requested.
391     const blink::WebNode& source_node() const;
392
393     // Frame to be use to render preview. May be the same as source_frame(), or
394     // generated from it, e.g. copy of selected block.
395     blink::WebLocalFrame* prepared_frame();
396     // Node to be use to render preview. May be the same as source_node(), or
397     // generated from it, e.g. copy of selected block.
398     const blink::WebNode& prepared_node() const;
399
400     int total_page_count() const;
401     bool generate_draft_pages() const;
402     PreviewMetafile* metafile();
403     gfx::Size GetPrintCanvasSize() const;
404     int last_error() const;
405
406    private:
407     enum State {
408       UNINITIALIZED,  // Not ready to render.
409       INITIALIZED,    // Ready to render.
410       RENDERING,      // Rendering.
411       DONE            // Finished rendering.
412     };
413
414     // Reset some of the internal rendering context.
415     void ClearContext();
416
417     // Specifies what to render for print preview.
418     FrameReference source_frame_;
419     blink::WebNode source_node_;
420
421     scoped_ptr<PrepareFrameAndViewForPrint> prep_frame_view_;
422     scoped_ptr<PreviewMetafile> metafile_;
423
424     // Total page count in the renderer.
425     int total_page_count_;
426
427     // The current page to render.
428     int current_page_index_;
429
430     // List of page indices that need to be rendered.
431     std::vector<int> pages_to_render_;
432
433     // True, when draft pages needs to be generated.
434     bool generate_draft_pages_;
435
436     // Specifies the total number of pages in the print ready metafile.
437     int print_ready_metafile_page_count_;
438
439     base::TimeDelta document_render_time_;
440     base::TimeTicks begin_time_;
441
442     enum PrintPreviewErrorBuckets error_;
443
444     State state_;
445   };
446
447   bool print_node_in_progress_;
448   PrintPreviewContext print_preview_context_;
449   bool is_loading_;
450   bool is_scripted_preview_delayed_;
451   base::WeakPtrFactory<PrintWebViewHelper> weak_ptr_factory_;
452   DISALLOW_COPY_AND_ASSIGN(PrintWebViewHelper);
453 };
454
455 }  // namespace printing
456
457 #endif  // CHROME_RENDERER_PRINTING_PRINT_WEB_VIEW_HELPER_H_