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