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.
5 #ifndef CHROME_RENDERER_PRINTING_PRINT_WEB_VIEW_HELPER_H_
6 #define CHROME_RENDERER_PRINTING_PRINT_WEB_VIEW_HELPER_H_
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"
23 struct PrintMsg_Print_Params
;
24 struct PrintMsg_PrintPage_Params
;
25 struct PrintMsg_PrintPages_Params
;
28 class DictionaryValue
;
38 struct PageSizeMargins
;
39 class PrepareFrameAndViewForPrint
;
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
{
46 explicit FrameReference(blink::WebLocalFrame
* frame
);
50 void Reset(blink::WebLocalFrame
* frame
);
52 blink::WebLocalFrame
* GetFrame();
53 blink::WebView
* view();
56 blink::WebView
* view_
;
57 blink::WebLocalFrame
* frame_
;
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
> {
67 explicit PrintWebViewHelper(content::RenderView
* render_view
);
68 virtual ~PrintWebViewHelper();
70 bool IsPrintingEnabled();
72 void PrintNode(const blink::WebNode
& node
);
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
);
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)
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.
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().
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
;
121 // Message handlers ---------------------------------------------------------
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
);
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
);
136 // Update |ignore_css_margins_| based on settings.
137 void UpdateFrameMarginsCssInfo(const base::DictionaryValue
& settings
);
139 // Returns true if the current destination printer is PRINT_TO_PDF.
140 bool IsPrintToPdfRequested(const base::DictionaryValue
& settings
);
142 // Prepare frame for creating preview document.
143 void PrepareFrameForPreviewDocument();
145 // Continue creating preview document.
146 void OnFramePreparedForPreviewDocument();
148 // Initialize the print preview document.
149 bool CreatePreviewDocument();
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
);
156 // Finalize the print ready preview document.
157 bool FinalizePrintReadyDocument();
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
);
163 // Main printing code -------------------------------------------------------
165 void Print(blink::WebLocalFrame
* frame
, const blink::WebNode
& node
);
167 // Notification when printing is done - signal tear-down/free resources.
168 void DidFinishPrinting(PrintingResult result
);
170 // Print Settings -----------------------------------------------------------
172 // Initialize print page settings with default settings.
173 // Used only for native printing workflow.
174 bool InitPrintSettings(bool fit_to_paper_size
);
176 // Calculate number of pages in source document.
177 bool CalculateNumberOfPages(blink::WebLocalFrame
* frame
,
178 const blink::WebNode
& node
,
179 int* number_of_pages
);
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
);
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
);
194 // Page Printing / Rendering ------------------------------------------------
196 void OnFramePreparedForPrintPages();
198 bool PrintPagesNative(blink::WebFrame
* frame
,
200 const gfx::Size
& canvas_size
);
201 void FinishFramePrinting();
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
,
210 void PrintPageInternal(const PrintMsg_PrintPage_Params
& params
,
211 const gfx::Size
& canvas_size
,
212 blink::WebFrame
* frame
);
215 // Render the frame for printing.
216 bool RenderPagesForPrint(blink::WebLocalFrame
* frame
,
217 const blink::WebNode
& node
);
219 // Platform specific helper function for rendering page(s) to |metafile|.
221 void RenderPage(const PrintMsg_Print_Params
& params
,
223 blink::WebFrame
* frame
,
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
,
232 blink::WebFrame
* frame
,
235 gfx::Size
* page_size
,
236 gfx::Rect
* content_rect
);
237 #endif // defined(OS_WIN)
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
,
245 const gfx::Rect
& canvas_area
,
246 const gfx::Rect
& content_area
,
248 blink::WebCanvas
* canvas
);
250 // Helper methods -----------------------------------------------------------
252 bool CopyMetafileDataToSharedMem(Metafile
* metafile
,
253 base::SharedMemoryHandle
* shared_mem_handle
);
255 // Helper method to get page layout in points and fit to page if needed.
256 static void ComputePageLayoutInPointsForCss(
257 blink::WebFrame
* frame
,
259 const PrintMsg_Print_Params
& default_params
,
260 bool ignore_css_margins
,
261 double* scale_factor
,
262 PageSizeMargins
* page_layout_in_points
);
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
,
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
);
275 bool GetPrintFrame(blink::WebLocalFrame
** frame
);
277 // Script Initiated Printing ------------------------------------------------
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
);
285 // Returns true if script initiated printing occurs too often.
286 bool IsScriptInitiatedPrintTooFrequent(blink::WebFrame
* frame
);
288 // Reset the counter for script initiated printing.
289 // Scripted printing will be allowed to continue.
290 void ResetScriptedPrintCount();
292 // Increment the counter for script initiated printing.
293 // Scripted printing will be blocked for a limited amount of time.
294 void IncrementScriptedPrintCount();
296 // Shows scripted print preview when options from plugin are availible.
297 void ShowScriptedPrintPreview();
299 void RequestPrintPreview(PrintPreviewRequestType type
);
301 // Checks whether print preview should continue or not.
302 // Returns true if cancelling, false if continuing.
303 bool CheckForCancel();
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
);
312 // WebView used only to print the selection.
313 scoped_ptr
<PrepareFrameAndViewForPrint
> prep_frame_view_
;
314 bool reset_prep_frame_view_
;
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_
;
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_
;
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_
;
331 // True, when printing from print preview.
332 bool print_for_preview_
;
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_
;
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
{
343 PrintPreviewContext();
344 ~PrintPreviewContext();
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
);
351 // Does bookkeeping at the beginning of print preview.
352 void OnPrintPreview();
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
);
359 // Called after a page gets rendered. |page_time| is how long the
361 void RenderedPreviewPage(const base::TimeDelta
& page_time
);
363 // Updates the print preview context when the required pages are rendered.
364 void AllPagesRendered();
366 // Finalizes the print ready preview document.
367 void FinalizePrintReadyDocument();
369 // Cleanup after print preview finishes.
372 // Cleanup after print preview fails.
373 void Failed(bool report_error
);
376 int GetNextPageNumber();
377 bool IsRendering() const;
380 bool IsLastPageOfPrintReadyMetafile() const;
381 bool IsFinalPageRendered() const;
384 void set_generate_draft_pages(bool generate_draft_pages
);
385 void set_error(enum PrintPreviewErrorBuckets error
);
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;
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;
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;
408 UNINITIALIZED
, // Not ready to render.
409 INITIALIZED
, // Ready to render.
410 RENDERING
, // Rendering.
411 DONE
// Finished rendering.
414 // Reset some of the internal rendering context.
417 // Specifies what to render for print preview.
418 FrameReference source_frame_
;
419 blink::WebNode source_node_
;
421 scoped_ptr
<PrepareFrameAndViewForPrint
> prep_frame_view_
;
422 scoped_ptr
<PreviewMetafile
> metafile_
;
424 // Total page count in the renderer.
425 int total_page_count_
;
427 // The current page to render.
428 int current_page_index_
;
430 // List of page indices that need to be rendered.
431 std::vector
<int> pages_to_render_
;
433 // True, when draft pages needs to be generated.
434 bool generate_draft_pages_
;
436 // Specifies the total number of pages in the print ready metafile.
437 int print_ready_metafile_page_count_
;
439 base::TimeDelta document_render_time_
;
440 base::TimeTicks begin_time_
;
442 enum PrintPreviewErrorBuckets error_
;
447 bool print_node_in_progress_
;
448 PrintPreviewContext print_preview_context_
;
450 bool is_scripted_preview_delayed_
;
451 base::WeakPtrFactory
<PrintWebViewHelper
> weak_ptr_factory_
;
452 DISALLOW_COPY_AND_ASSIGN(PrintWebViewHelper
);
455 } // namespace printing
457 #endif // CHROME_RENDERER_PRINTING_PRINT_WEB_VIEW_HELPER_H_