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
;
29 // RenderVIewTest-based tests crash on Android
30 // http://crbug.com/187500
31 #if defined(OS_ANDROID)
32 #define MAYBE_PrintWebViewHelperTest DISABLED_PrintWebViewHelperTest
33 #define MAYBE_PrintWebViewHelperPreviewTest \
34 DISABLED_PrintWebViewHelperPreviewTest
36 #define MAYBE_PrintWebViewHelperTest PrintWebViewHelperTest
37 #define MAYBE_PrintWebViewHelperPreviewTest PrintWebViewHelperPreviewTest
38 #endif // defined(OS_ANDROID)
41 class DictionaryValue
;
51 struct PageSizeMargins
;
52 class PrepareFrameAndViewForPrint
;
54 // Stores reference to frame using WebVew and unique name.
55 // Workaround to modal dialog issue on Linux. crbug.com/236147.
56 // If WebFrame someday supports WeakPtr, we should use it here.
57 class FrameReference
{
59 explicit FrameReference(blink::WebLocalFrame
* frame
);
63 void Reset(blink::WebLocalFrame
* frame
);
65 bool IsFrameValid() const;
67 const blink::WebLocalFrame
* GetFrame() const;
68 blink::WebLocalFrame
* GetFrame();
69 const blink::WebView
* view() const;
70 blink::WebView
* view();
73 blink::WebView
* view_
;
74 blink::WebLocalFrame
* frame_
;
77 // PrintWebViewHelper handles most of the printing grunt work for RenderView.
78 // We plan on making print asynchronous and that will require copying the DOM
79 // of the document and creating a new WebView with the contents.
80 class PrintWebViewHelper
81 : public content::RenderViewObserver
,
82 public content::RenderViewObserverTracker
<PrintWebViewHelper
> {
86 virtual ~Delegate() {}
88 // Cancels prerender if it's currently in progress and returns |true| if
89 // the cancellation was done with success.
90 virtual bool CancelPrerender(content::RenderView
* render_view
,
93 // Returns the element to be printed. Returns a null WebElement if
94 // a pdf plugin element can't be extracted from the frame.
95 virtual blink::WebElement
GetPdfElement(blink::WebLocalFrame
* frame
) = 0;
97 // Used to know whether the content to print could be nested in an iframe.
98 virtual bool IsOutOfProcessPdfEnabled() = 0;
100 virtual bool IsPrintPreviewEnabled() = 0;
102 // If true, the user can be asked to provide print settings.
103 // The default implementation returns |true|.
104 virtual bool IsAskPrintSettingsEnabled();
106 // If false, window.print() won't do anything.
107 // The default implementation returns |true|.
108 virtual bool IsScriptedPrintEnabled();
110 // Returns true if printing is overridden and the default behavior should be
111 // skipped for |frame|.
112 virtual bool OverridePrint(blink::WebLocalFrame
* frame
) = 0;
115 PrintWebViewHelper(content::RenderView
* render_view
,
116 scoped_ptr
<Delegate
> delegate
);
117 ~PrintWebViewHelper() override
;
119 // Disable print preview and switch to system dialog printing even if full
120 // printing is build-in. This method is used by CEF.
121 static void DisablePreview();
123 bool IsPrintingEnabled();
125 void PrintNode(const blink::WebNode
& node
);
128 friend class PrintWebViewHelperTestBase
;
129 FRIEND_TEST_ALL_PREFIXES(MAYBE_PrintWebViewHelperPreviewTest
,
130 BlockScriptInitiatedPrinting
);
131 FRIEND_TEST_ALL_PREFIXES(MAYBE_PrintWebViewHelperTest
, OnPrintPages
);
132 FRIEND_TEST_ALL_PREFIXES(MAYBE_PrintWebViewHelperTest
,
133 BlockScriptInitiatedPrinting
);
134 FRIEND_TEST_ALL_PREFIXES(MAYBE_PrintWebViewHelperTest
,
135 BlockScriptInitiatedPrintingFromPopup
);
136 #if defined(OS_WIN) || defined(OS_MACOSX)
137 FRIEND_TEST_ALL_PREFIXES(MAYBE_PrintWebViewHelperTest
, PrintLayoutTest
);
138 FRIEND_TEST_ALL_PREFIXES(MAYBE_PrintWebViewHelperTest
, PrintWithIframe
);
139 #endif // defined(OS_WIN) || defined(OS_MACOSX)
141 enum PrintingResult
{
148 enum PrintPreviewErrorBuckets
{
149 PREVIEW_ERROR_NONE
, // Always first.
150 PREVIEW_ERROR_BAD_SETTING
,
151 PREVIEW_ERROR_METAFILE_COPY_FAILED
,
152 PREVIEW_ERROR_METAFILE_INIT_FAILED
,
153 PREVIEW_ERROR_ZERO_PAGES
,
154 PREVIEW_ERROR_MAC_DRAFT_METAFILE_INIT_FAILED
,
155 PREVIEW_ERROR_PAGE_RENDERED_WITHOUT_METAFILE
,
156 PREVIEW_ERROR_INVALID_PRINTER_SETTINGS
,
157 PREVIEW_ERROR_LAST_ENUM
// Always last.
160 enum PrintPreviewRequestType
{
161 PRINT_PREVIEW_USER_INITIATED_ENTIRE_FRAME
,
162 PRINT_PREVIEW_USER_INITIATED_SELECTION
,
163 PRINT_PREVIEW_USER_INITIATED_CONTEXT_NODE
,
164 PRINT_PREVIEW_SCRIPTED
// triggered by window.print().
167 // RenderViewObserver implementation.
168 bool OnMessageReceived(const IPC::Message
& message
) override
;
169 void PrintPage(blink::WebLocalFrame
* frame
, bool user_initiated
) override
;
170 void DidStartLoading() override
;
171 void DidStopLoading() override
;
173 // Message handlers ---------------------------------------------------------
174 #if defined(ENABLE_BASIC_PRINTING)
176 void OnPrintForSystemDialog();
177 #endif // ENABLE_BASIC_PRINTING
178 void OnInitiatePrintPreview(bool selection_only
);
179 void OnPrintPreview(const base::DictionaryValue
& settings
);
180 void OnPrintForPrintPreview(const base::DictionaryValue
& job_settings
);
181 void OnPrintingDone(bool success
);
183 // Get |page_size| and |content_area| information from
184 // |page_layout_in_points|.
185 void GetPageSizeAndContentAreaFromPageLayout(
186 const PageSizeMargins
& page_layout_in_points
,
187 gfx::Size
* page_size
,
188 gfx::Rect
* content_area
);
190 // Update |ignore_css_margins_| based on settings.
191 void UpdateFrameMarginsCssInfo(const base::DictionaryValue
& settings
);
193 // Returns true if the current destination printer is PRINT_TO_PDF.
194 bool IsPrintToPdfRequested(const base::DictionaryValue
& settings
);
196 // Prepare frame for creating preview document.
197 void PrepareFrameForPreviewDocument();
199 // Continue creating preview document.
200 void OnFramePreparedForPreviewDocument();
202 // Initialize the print preview document.
203 bool CreatePreviewDocument();
205 // Renders a print preview page. |page_number| is 0-based.
206 // Returns true if print preview should continue, false on failure.
207 bool RenderPreviewPage(int page_number
,
208 const PrintMsg_Print_Params
& print_params
);
210 // Finalize the print ready preview document.
211 bool FinalizePrintReadyDocument();
213 // Enable/Disable window.print calls. If |blocked| is true window.print
214 // calls will silently fail. Call with |blocked| set to false to reenable.
215 void SetScriptedPrintBlocked(bool blocked
);
217 // Main printing code -------------------------------------------------------
219 // |is_scripted| should be true when the call is coming from window.print()
220 void Print(blink::WebLocalFrame
* frame
,
221 const blink::WebNode
& node
,
224 // Notification when printing is done - signal tear-down/free resources.
225 void DidFinishPrinting(PrintingResult result
);
227 // Print Settings -----------------------------------------------------------
229 // Initialize print page settings with default settings.
230 // Used only for native printing workflow.
231 bool InitPrintSettings(bool fit_to_paper_size
);
233 // Calculate number of pages in source document.
234 bool CalculateNumberOfPages(blink::WebLocalFrame
* frame
,
235 const blink::WebNode
& node
,
236 int* number_of_pages
);
238 // Set options for print preset from source PDF document.
239 bool SetOptionsFromPdfDocument(
240 PrintHostMsg_SetOptionsFromDocument_Params
* options
);
242 // Update the current print settings with new |passed_job_settings|.
243 // |passed_job_settings| dictionary contains print job details such as printer
244 // name, number of copies, page range, etc.
245 bool UpdatePrintSettings(blink::WebLocalFrame
* frame
,
246 const blink::WebNode
& node
,
247 const base::DictionaryValue
& passed_job_settings
);
249 // Get final print settings from the user.
250 // Return false if the user cancels or on error.
251 bool GetPrintSettingsFromUser(blink::WebLocalFrame
* frame
,
252 const blink::WebNode
& node
,
253 int expected_pages_count
,
256 // Page Printing / Rendering ------------------------------------------------
258 void OnFramePreparedForPrintPages();
260 bool PrintPagesNative(blink::WebFrame
* frame
, int page_count
);
261 void FinishFramePrinting();
263 // Prints the page listed in |params|.
264 #if defined(OS_LINUX) || defined(OS_ANDROID)
265 void PrintPageInternal(const PrintMsg_PrintPage_Params
& params
,
266 blink::WebFrame
* frame
,
267 PdfMetafileSkia
* metafile
);
268 #elif defined(OS_WIN)
269 void PrintPageInternal(const PrintMsg_PrintPage_Params
& params
,
270 blink::WebFrame
* frame
,
271 PdfMetafileSkia
* metafile
,
272 gfx::Size
* page_size_in_dpi
,
273 gfx::Rect
* content_area_in_dpi
);
275 void PrintPageInternal(const PrintMsg_PrintPage_Params
& params
,
276 blink::WebFrame
* frame
);
279 // Render the frame for printing.
280 bool RenderPagesForPrint(blink::WebLocalFrame
* frame
,
281 const blink::WebNode
& node
);
283 // Platform specific helper function for rendering page(s) to |metafile|.
284 #if defined(OS_MACOSX)
285 void RenderPage(const PrintMsg_Print_Params
& params
,
287 blink::WebFrame
* frame
,
289 PdfMetafileSkia
* metafile
,
290 gfx::Size
* page_size
,
291 gfx::Rect
* content_rect
);
292 #endif // defined(OS_MACOSX)
294 // Renders page contents from |frame| to |content_area| of |canvas|.
295 // |page_number| is zero-based.
296 // When method is called, canvas should be setup to draw to |canvas_area|
297 // with |scale_factor|.
298 static float RenderPageContent(blink::WebFrame
* frame
,
300 const gfx::Rect
& canvas_area
,
301 const gfx::Rect
& content_area
,
303 blink::WebCanvas
* canvas
);
305 // Helper methods -----------------------------------------------------------
307 bool CopyMetafileDataToSharedMem(PdfMetafileSkia
* metafile
,
308 base::SharedMemoryHandle
* shared_mem_handle
);
310 // Helper method to get page layout in points and fit to page if needed.
311 static void ComputePageLayoutInPointsForCss(
312 blink::WebFrame
* frame
,
314 const PrintMsg_Print_Params
& default_params
,
315 bool ignore_css_margins
,
316 double* scale_factor
,
317 PageSizeMargins
* page_layout_in_points
);
319 #if defined(ENABLE_PRINT_PREVIEW)
320 // Given the |device| and |canvas| to draw on, prints the appropriate headers
321 // and footers using strings from |header_footer_info| on to the canvas.
322 static void PrintHeaderAndFooter(blink::WebCanvas
* canvas
,
325 const blink::WebFrame
& source_frame
,
326 float webkit_scale_factor
,
327 const PageSizeMargins
& page_layout_in_points
,
328 const PrintMsg_Print_Params
& params
);
329 #endif // defined(ENABLE_PRINT_PREVIEW)
331 bool GetPrintFrame(blink::WebLocalFrame
** frame
);
333 // Script Initiated Printing ------------------------------------------------
335 // Return true if script initiated printing is currently
336 // allowed. |user_initiated| should be true when a user event triggered the
337 // script, most likely by pressing a print button on the page.
338 bool IsScriptInitiatedPrintAllowed(blink::WebFrame
* frame
,
339 bool user_initiated
);
341 // Shows scripted print preview when options from plugin are available.
342 void ShowScriptedPrintPreview();
344 void RequestPrintPreview(PrintPreviewRequestType type
);
346 // Checks whether print preview should continue or not.
347 // Returns true if canceling, false if continuing.
348 bool CheckForCancel();
350 // Notifies the browser a print preview page has been rendered.
351 // |page_number| is 0-based.
352 // For a valid |page_number| with modifiable content,
353 // |metafile| is the rendered page. Otherwise |metafile| is NULL.
354 // Returns true if print preview should continue, false on failure.
355 bool PreviewPageRendered(int page_number
, PdfMetafileSkia
* metafile
);
357 void SetPrintPagesParams(const PrintMsg_PrintPages_Params
& settings
);
359 // WebView used only to print the selection.
360 scoped_ptr
<PrepareFrameAndViewForPrint
> prep_frame_view_
;
361 bool reset_prep_frame_view_
;
363 scoped_ptr
<PrintMsg_PrintPages_Params
> print_pages_params_
;
364 bool is_print_ready_metafile_sent_
;
365 bool ignore_css_margins_
;
367 // Used for scripted initiated printing blocking.
368 bool is_scripted_printing_blocked_
;
370 // Let the browser process know of a printing failure. Only set to false when
371 // the failure came from the browser in the first place.
372 bool notify_browser_of_print_failure_
;
374 // True, when printing from print preview.
375 bool print_for_preview_
;
377 // Used to check the prerendering status.
378 const scoped_ptr
<Delegate
> delegate_
;
380 // Keeps track of the state of print preview between messages.
381 // TODO(vitalybuka): Create PrintPreviewContext when needed and delete after
382 // use. Now it's interaction with various messages is confusing.
383 class PrintPreviewContext
{
385 PrintPreviewContext();
386 ~PrintPreviewContext();
388 // Initializes the print preview context. Need to be called to set
389 // the |web_frame| / |web_node| to generate the print preview for.
390 void InitWithFrame(blink::WebLocalFrame
* web_frame
);
391 void InitWithNode(const blink::WebNode
& web_node
);
393 // Does bookkeeping at the beginning of print preview.
394 void OnPrintPreview();
396 // Create the print preview document. |pages| is empty to print all pages.
397 // Takes ownership of |prepared_frame|.
398 bool CreatePreviewDocument(PrepareFrameAndViewForPrint
* prepared_frame
,
399 const std::vector
<int>& pages
);
401 // Called after a page gets rendered. |page_time| is how long the
403 void RenderedPreviewPage(const base::TimeDelta
& page_time
);
405 // Updates the print preview context when the required pages are rendered.
406 void AllPagesRendered();
408 // Finalizes the print ready preview document.
409 void FinalizePrintReadyDocument();
411 // Cleanup after print preview finishes.
414 // Cleanup after print preview fails.
415 void Failed(bool report_error
);
418 int GetNextPageNumber();
419 bool IsRendering() const;
422 bool IsLastPageOfPrintReadyMetafile() const;
423 bool IsFinalPageRendered() const;
426 void set_generate_draft_pages(bool generate_draft_pages
);
427 void set_error(enum PrintPreviewErrorBuckets error
);
430 // Original frame for which preview was requested.
431 blink::WebLocalFrame
* source_frame();
432 // Original node for which preview was requested.
433 const blink::WebNode
& source_node() const;
435 // Frame to be use to render preview. May be the same as source_frame(), or
436 // generated from it, e.g. copy of selected block.
437 blink::WebLocalFrame
* prepared_frame();
438 // Node to be use to render preview. May be the same as source_node(), or
439 // generated from it, e.g. copy of selected block.
440 const blink::WebNode
& prepared_node() const;
442 int total_page_count() const;
443 bool generate_draft_pages() const;
444 PdfMetafileSkia
* metafile();
445 int last_error() const;
449 UNINITIALIZED
, // Not ready to render.
450 INITIALIZED
, // Ready to render.
451 RENDERING
, // Rendering.
452 DONE
// Finished rendering.
455 // Reset some of the internal rendering context.
458 // Specifies what to render for print preview.
459 FrameReference source_frame_
;
460 blink::WebNode source_node_
;
462 scoped_ptr
<PrepareFrameAndViewForPrint
> prep_frame_view_
;
463 scoped_ptr
<PdfMetafileSkia
> metafile_
;
465 // Total page count in the renderer.
466 int total_page_count_
;
468 // The current page to render.
469 int current_page_index_
;
471 // List of page indices that need to be rendered.
472 std::vector
<int> pages_to_render_
;
474 // True, when draft pages needs to be generated.
475 bool generate_draft_pages_
;
477 // Specifies the total number of pages in the print ready metafile.
478 int print_ready_metafile_page_count_
;
480 base::TimeDelta document_render_time_
;
481 base::TimeTicks begin_time_
;
483 enum PrintPreviewErrorBuckets error_
;
488 class ScriptingThrottler
{
490 ScriptingThrottler();
492 // Returns false if script initiated printing occurs too often.
493 bool IsAllowed(blink::WebFrame
* frame
);
495 // Reset the counter for script initiated printing.
496 // Scripted printing will be allowed to continue.
500 base::Time last_print_
;
502 DISALLOW_COPY_AND_ASSIGN(ScriptingThrottler
);
505 ScriptingThrottler scripting_throttler_
;
507 bool print_node_in_progress_
;
508 PrintPreviewContext print_preview_context_
;
510 bool is_scripted_preview_delayed_
;
512 // Used to fix a race condition where the source is a PDF and print preview
513 // hangs because RequestPrintPreview is called before DidStopLoading() is
514 // called. This is a store for the RequestPrintPreview() call and its
515 // parameters so that it can be invoked after DidStopLoading.
516 base::Closure on_stop_loading_closure_
;
518 base::WeakPtrFactory
<PrintWebViewHelper
> weak_ptr_factory_
;
520 DISALLOW_COPY_AND_ASSIGN(PrintWebViewHelper
);
523 } // namespace printing
525 #endif // COMPONENTS_PRINTING_RENDERER_PRINT_WEB_VIEW_HELPER_H_