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