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 COMPONENTS_PRINTING_RENDERER_PRINT_WEB_VIEW_HELPER_H_
6 #define COMPONENTS_PRINTING_RENDERER_PRINT_WEB_VIEW_HELPER_H_
10 #include "base/callback.h"
11 #include "base/gtest_prod_util.h"
12 #include "base/memory/scoped_ptr.h"
13 #include "base/memory/shared_memory.h"
14 #include "base/memory/weak_ptr.h"
15 #include "base/time/time.h"
16 #include "content/public/renderer/render_view_observer.h"
17 #include "content/public/renderer/render_view_observer_tracker.h"
18 #include "printing/pdf_metafile_skia.h"
19 #include "third_party/WebKit/public/platform/WebCanvas.h"
20 #include "third_party/WebKit/public/web/WebNode.h"
21 #include "third_party/WebKit/public/web/WebPrintParams.h"
22 #include "ui/gfx/geometry/size.h"
24 struct PrintMsg_Print_Params
;
25 struct PrintMsg_PrintPage_Params
;
26 struct PrintMsg_PrintPages_Params
;
27 struct PrintHostMsg_SetOptionsFromDocument_Params
;
30 class DictionaryValue
;
40 struct PageSizeMargins
;
41 class PrepareFrameAndViewForPrint
;
43 // Stores reference to frame using WebVew and unique name.
44 // Workaround to modal dialog issue on Linux. crbug.com/236147.
45 // If WebFrame someday supports WeakPtr, we should use it here.
46 class FrameReference
{
48 explicit FrameReference(blink::WebLocalFrame
* frame
);
52 void Reset(blink::WebLocalFrame
* frame
);
54 blink::WebLocalFrame
* GetFrame();
55 blink::WebView
* view();
58 blink::WebView
* view_
;
59 blink::WebLocalFrame
* frame_
;
62 // PrintWebViewHelper handles most of the printing grunt work for RenderView.
63 // We plan on making print asynchronous and that will require copying the DOM
64 // of the document and creating a new WebView with the contents.
65 class PrintWebViewHelper
66 : public content::RenderViewObserver
,
67 public content::RenderViewObserverTracker
<PrintWebViewHelper
> {
71 virtual ~Delegate() {}
73 // Cancels prerender if it's currently in progress and returns |true| if
74 // the cancellation was done with success.
75 virtual bool CancelPrerender(content::RenderView
* render_view
,
78 // Returns the element to be printed. Returns a null WebElement if
79 // a pdf plugin element can't be extracted from the frame.
80 virtual blink::WebElement
GetPdfElement(blink::WebLocalFrame
* frame
) = 0;
82 // Used to know whether the content to print could be nested in an iframe.
83 virtual bool IsOutOfProcessPdfEnabled() = 0;
85 virtual bool IsPrintPreviewEnabled() = 0;
87 // If true, the user can be asked to provide print settings.
88 // The default implementation returns |true|.
89 virtual bool IsAskPrintSettingsEnabled();
91 // If false, window.print() won't do anything.
92 // The default implementation returns |true|.
93 virtual bool IsScriptedPrintEnabled();
95 // Returns true if printing is overridden and the default behavior should be
96 // skipped for |frame|.
97 virtual bool OverridePrint(blink::WebLocalFrame
* frame
) = 0;
100 PrintWebViewHelper(content::RenderView
* render_view
,
101 scoped_ptr
<Delegate
> delegate
);
102 ~PrintWebViewHelper() override
;
104 // Disable print preview and switch to system dialog printing even if full
105 // printing is build-in. This method is used by CEF.
106 static void DisablePreview();
108 bool IsPrintingEnabled();
110 void PrintNode(const blink::WebNode
& node
);
113 friend class PrintWebViewHelperTestBase
;
114 FRIEND_TEST_ALL_PREFIXES(PrintWebViewHelperPreviewTest
,
115 BlockScriptInitiatedPrinting
);
116 FRIEND_TEST_ALL_PREFIXES(PrintWebViewHelperTest
, OnPrintPages
);
117 FRIEND_TEST_ALL_PREFIXES(PrintWebViewHelperTest
,
118 BlockScriptInitiatedPrinting
);
119 FRIEND_TEST_ALL_PREFIXES(PrintWebViewHelperTest
,
120 BlockScriptInitiatedPrintingFromPopup
);
121 #if defined(OS_WIN) || defined(OS_MACOSX)
122 FRIEND_TEST_ALL_PREFIXES(PrintWebViewHelperTest
, PrintLayoutTest
);
123 FRIEND_TEST_ALL_PREFIXES(PrintWebViewHelperTest
, PrintWithIframe
);
124 #endif // defined(OS_WIN) || defined(OS_MACOSX)
126 enum PrintingResult
{
133 enum PrintPreviewErrorBuckets
{
134 PREVIEW_ERROR_NONE
, // Always first.
135 PREVIEW_ERROR_BAD_SETTING
,
136 PREVIEW_ERROR_METAFILE_COPY_FAILED
,
137 PREVIEW_ERROR_METAFILE_INIT_FAILED
,
138 PREVIEW_ERROR_ZERO_PAGES
,
139 PREVIEW_ERROR_MAC_DRAFT_METAFILE_INIT_FAILED
,
140 PREVIEW_ERROR_PAGE_RENDERED_WITHOUT_METAFILE
,
141 PREVIEW_ERROR_INVALID_PRINTER_SETTINGS
,
142 PREVIEW_ERROR_LAST_ENUM
// Always last.
145 enum PrintPreviewRequestType
{
146 PRINT_PREVIEW_USER_INITIATED_ENTIRE_FRAME
,
147 PRINT_PREVIEW_USER_INITIATED_SELECTION
,
148 PRINT_PREVIEW_USER_INITIATED_CONTEXT_NODE
,
149 PRINT_PREVIEW_SCRIPTED
// triggered by window.print().
152 // RenderViewObserver implementation.
153 bool OnMessageReceived(const IPC::Message
& message
) override
;
154 void PrintPage(blink::WebLocalFrame
* frame
, bool user_initiated
) override
;
155 void DidStartLoading() override
;
156 void DidStopLoading() override
;
158 // Message handlers ---------------------------------------------------------
159 #if defined(ENABLE_BASIC_PRINTING)
161 void OnPrintForSystemDialog();
162 #endif // ENABLE_BASIC_PRINTING
163 void OnInitiatePrintPreview(bool selection_only
);
164 void OnPrintPreview(const base::DictionaryValue
& settings
);
165 void OnPrintForPrintPreview(const base::DictionaryValue
& job_settings
);
166 void OnPrintingDone(bool success
);
168 // Get |page_size| and |content_area| information from
169 // |page_layout_in_points|.
170 void GetPageSizeAndContentAreaFromPageLayout(
171 const PageSizeMargins
& page_layout_in_points
,
172 gfx::Size
* page_size
,
173 gfx::Rect
* content_area
);
175 // Update |ignore_css_margins_| based on settings.
176 void UpdateFrameMarginsCssInfo(const base::DictionaryValue
& settings
);
178 // Returns true if the current destination printer is PRINT_TO_PDF.
179 bool IsPrintToPdfRequested(const base::DictionaryValue
& settings
);
181 // Prepare frame for creating preview document.
182 void PrepareFrameForPreviewDocument();
184 // Continue creating preview document.
185 void OnFramePreparedForPreviewDocument();
187 // Initialize the print preview document.
188 bool CreatePreviewDocument();
190 // Renders a print preview page. |page_number| is 0-based.
191 // Returns true if print preview should continue, false on failure.
192 bool RenderPreviewPage(int page_number
,
193 const PrintMsg_Print_Params
& print_params
);
195 // Finalize the print ready preview document.
196 bool FinalizePrintReadyDocument();
198 // Enable/Disable window.print calls. If |blocked| is true window.print
199 // calls will silently fail. Call with |blocked| set to false to reenable.
200 void SetScriptedPrintBlocked(bool blocked
);
202 // Main printing code -------------------------------------------------------
204 // |is_scripted| should be true when the call is coming from window.print()
205 void Print(blink::WebLocalFrame
* frame
,
206 const blink::WebNode
& node
,
209 // Notification when printing is done - signal tear-down/free resources.
210 void DidFinishPrinting(PrintingResult result
);
212 // Print Settings -----------------------------------------------------------
214 // Initialize print page settings with default settings.
215 // Used only for native printing workflow.
216 bool InitPrintSettings(bool fit_to_paper_size
);
218 // Calculate number of pages in source document.
219 bool CalculateNumberOfPages(blink::WebLocalFrame
* frame
,
220 const blink::WebNode
& node
,
221 int* number_of_pages
);
223 // Set options for print preset from source PDF document.
224 bool SetOptionsFromPdfDocument(
225 PrintHostMsg_SetOptionsFromDocument_Params
* options
);
227 // Update the current print settings with new |passed_job_settings|.
228 // |passed_job_settings| dictionary contains print job details such as printer
229 // name, number of copies, page range, etc.
230 bool UpdatePrintSettings(blink::WebLocalFrame
* frame
,
231 const blink::WebNode
& node
,
232 const base::DictionaryValue
& passed_job_settings
);
234 // Get final print settings from the user.
235 // Return false if the user cancels or on error.
236 bool GetPrintSettingsFromUser(blink::WebLocalFrame
* frame
,
237 const blink::WebNode
& node
,
238 int expected_pages_count
,
241 // Page Printing / Rendering ------------------------------------------------
243 void OnFramePreparedForPrintPages();
245 bool PrintPagesNative(blink::WebFrame
* frame
, int page_count
);
246 void FinishFramePrinting();
248 // Prints the page listed in |params|.
249 #if defined(OS_LINUX) || defined(OS_ANDROID)
250 void PrintPageInternal(const PrintMsg_PrintPage_Params
& params
,
251 blink::WebFrame
* frame
,
252 PdfMetafileSkia
* metafile
);
253 #elif defined(OS_WIN)
254 void PrintPageInternal(const PrintMsg_PrintPage_Params
& params
,
255 blink::WebFrame
* frame
,
256 PdfMetafileSkia
* metafile
,
257 gfx::Size
* page_size_in_dpi
,
258 gfx::Rect
* content_area_in_dpi
);
260 void PrintPageInternal(const PrintMsg_PrintPage_Params
& params
,
261 blink::WebFrame
* frame
);
264 // Render the frame for printing.
265 bool RenderPagesForPrint(blink::WebLocalFrame
* frame
,
266 const blink::WebNode
& node
);
268 // Platform specific helper function for rendering page(s) to |metafile|.
269 #if defined(OS_MACOSX)
270 void RenderPage(const PrintMsg_Print_Params
& params
,
272 blink::WebFrame
* frame
,
274 PdfMetafileSkia
* metafile
,
275 gfx::Size
* page_size
,
276 gfx::Rect
* content_rect
);
277 #endif // defined(OS_MACOSX)
279 // Renders page contents from |frame| to |content_area| of |canvas|.
280 // |page_number| is zero-based.
281 // When method is called, canvas should be setup to draw to |canvas_area|
282 // with |scale_factor|.
283 static float RenderPageContent(blink::WebFrame
* frame
,
285 const gfx::Rect
& canvas_area
,
286 const gfx::Rect
& content_area
,
288 blink::WebCanvas
* canvas
);
290 // Helper methods -----------------------------------------------------------
292 bool CopyMetafileDataToSharedMem(PdfMetafileSkia
* metafile
,
293 base::SharedMemoryHandle
* shared_mem_handle
);
295 // Helper method to get page layout in points and fit to page if needed.
296 static void ComputePageLayoutInPointsForCss(
297 blink::WebFrame
* frame
,
299 const PrintMsg_Print_Params
& default_params
,
300 bool ignore_css_margins
,
301 double* scale_factor
,
302 PageSizeMargins
* page_layout_in_points
);
304 #if defined(ENABLE_PRINT_PREVIEW)
305 // Given the |device| and |canvas| to draw on, prints the appropriate headers
306 // and footers using strings from |header_footer_info| on to the canvas.
307 static void PrintHeaderAndFooter(blink::WebCanvas
* canvas
,
310 const blink::WebFrame
& source_frame
,
311 float webkit_scale_factor
,
312 const PageSizeMargins
& page_layout_in_points
,
313 const PrintMsg_Print_Params
& params
);
314 #endif // defined(ENABLE_PRINT_PREVIEW)
316 bool GetPrintFrame(blink::WebLocalFrame
** frame
);
318 // Script Initiated Printing ------------------------------------------------
320 // Return true if script initiated printing is currently
321 // allowed. |user_initiated| should be true when a user event triggered the
322 // script, most likely by pressing a print button on the page.
323 bool IsScriptInitiatedPrintAllowed(blink::WebFrame
* frame
,
324 bool user_initiated
);
326 // Shows scripted print preview when options from plugin are available.
327 void ShowScriptedPrintPreview();
329 void RequestPrintPreview(PrintPreviewRequestType type
);
331 // Checks whether print preview should continue or not.
332 // Returns true if canceling, false if continuing.
333 bool CheckForCancel();
335 // Notifies the browser a print preview page has been rendered.
336 // |page_number| is 0-based.
337 // For a valid |page_number| with modifiable content,
338 // |metafile| is the rendered page. Otherwise |metafile| is NULL.
339 // Returns true if print preview should continue, false on failure.
340 bool PreviewPageRendered(int page_number
, PdfMetafileSkia
* metafile
);
342 void SetPrintPagesParams(const PrintMsg_PrintPages_Params
& settings
);
344 // WebView used only to print the selection.
345 scoped_ptr
<PrepareFrameAndViewForPrint
> prep_frame_view_
;
346 bool reset_prep_frame_view_
;
348 scoped_ptr
<PrintMsg_PrintPages_Params
> print_pages_params_
;
349 bool is_print_ready_metafile_sent_
;
350 bool ignore_css_margins_
;
352 // Used for scripted initiated printing blocking.
353 bool is_scripted_printing_blocked_
;
355 // Let the browser process know of a printing failure. Only set to false when
356 // the failure came from the browser in the first place.
357 bool notify_browser_of_print_failure_
;
359 // True, when printing from print preview.
360 bool print_for_preview_
;
362 // Used to check the prerendering status.
363 const scoped_ptr
<Delegate
> delegate_
;
365 // Keeps track of the state of print preview between messages.
366 // TODO(vitalybuka): Create PrintPreviewContext when needed and delete after
367 // use. Now it's interaction with various messages is confusing.
368 class PrintPreviewContext
{
370 PrintPreviewContext();
371 ~PrintPreviewContext();
373 // Initializes the print preview context. Need to be called to set
374 // the |web_frame| / |web_node| to generate the print preview for.
375 void InitWithFrame(blink::WebLocalFrame
* web_frame
);
376 void InitWithNode(const blink::WebNode
& web_node
);
378 // Does bookkeeping at the beginning of print preview.
379 void OnPrintPreview();
381 // Create the print preview document. |pages| is empty to print all pages.
382 // Takes ownership of |prepared_frame|.
383 bool CreatePreviewDocument(PrepareFrameAndViewForPrint
* prepared_frame
,
384 const std::vector
<int>& pages
);
386 // Called after a page gets rendered. |page_time| is how long the
388 void RenderedPreviewPage(const base::TimeDelta
& page_time
);
390 // Updates the print preview context when the required pages are rendered.
391 void AllPagesRendered();
393 // Finalizes the print ready preview document.
394 void FinalizePrintReadyDocument();
396 // Cleanup after print preview finishes.
399 // Cleanup after print preview fails.
400 void Failed(bool report_error
);
403 int GetNextPageNumber();
404 bool IsRendering() const;
407 bool IsLastPageOfPrintReadyMetafile() const;
408 bool IsFinalPageRendered() const;
411 void set_generate_draft_pages(bool generate_draft_pages
);
412 void set_error(enum PrintPreviewErrorBuckets error
);
415 // Original frame for which preview was requested.
416 blink::WebLocalFrame
* source_frame();
417 // Original node for which preview was requested.
418 const blink::WebNode
& source_node() const;
420 // Frame to be use to render preview. May be the same as source_frame(), or
421 // generated from it, e.g. copy of selected block.
422 blink::WebLocalFrame
* prepared_frame();
423 // Node to be use to render preview. May be the same as source_node(), or
424 // generated from it, e.g. copy of selected block.
425 const blink::WebNode
& prepared_node() const;
427 int total_page_count() const;
428 bool generate_draft_pages() const;
429 PdfMetafileSkia
* metafile();
430 int last_error() const;
434 UNINITIALIZED
, // Not ready to render.
435 INITIALIZED
, // Ready to render.
436 RENDERING
, // Rendering.
437 DONE
// Finished rendering.
440 // Reset some of the internal rendering context.
443 // Specifies what to render for print preview.
444 FrameReference source_frame_
;
445 blink::WebNode source_node_
;
447 scoped_ptr
<PrepareFrameAndViewForPrint
> prep_frame_view_
;
448 scoped_ptr
<PdfMetafileSkia
> metafile_
;
450 // Total page count in the renderer.
451 int total_page_count_
;
453 // The current page to render.
454 int current_page_index_
;
456 // List of page indices that need to be rendered.
457 std::vector
<int> pages_to_render_
;
459 // True, when draft pages needs to be generated.
460 bool generate_draft_pages_
;
462 // Specifies the total number of pages in the print ready metafile.
463 int print_ready_metafile_page_count_
;
465 base::TimeDelta document_render_time_
;
466 base::TimeTicks begin_time_
;
468 enum PrintPreviewErrorBuckets error_
;
473 class ScriptingThrottler
{
475 ScriptingThrottler();
477 // Returns false if script initiated printing occurs too often.
478 bool IsAllowed(blink::WebFrame
* frame
);
480 // Reset the counter for script initiated printing.
481 // Scripted printing will be allowed to continue.
485 base::Time last_print_
;
487 DISALLOW_COPY_AND_ASSIGN(ScriptingThrottler
);
490 ScriptingThrottler scripting_throttler_
;
492 bool print_node_in_progress_
;
493 PrintPreviewContext print_preview_context_
;
495 bool is_scripted_preview_delayed_
;
497 // Used to fix a race condition where the source is a PDF and print preview
498 // hangs because RequestPrintPreview is called before DidStopLoading() is
499 // called. This is a store for the RequestPrintPreview() call and its
500 // parameters so that it can be invoked after DidStopLoading.
501 base::Closure on_stop_loading_closure_
;
503 base::WeakPtrFactory
<PrintWebViewHelper
> weak_ptr_factory_
;
505 DISALLOW_COPY_AND_ASSIGN(PrintWebViewHelper
);
508 } // namespace printing
510 #endif // COMPONENTS_PRINTING_RENDERER_PRINT_WEB_VIEW_HELPER_H_