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