Merge Chromium + Blink git repositories
[chromium-blink-merge.git] / components / printing / renderer / print_web_view_helper.h
blobd9ea441e2aab29979644d50d4583cb94eb1d84af
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_
8 #include <vector>
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
35 #else
36 #define MAYBE_PrintWebViewHelperTest PrintWebViewHelperTest
37 #define MAYBE_PrintWebViewHelperPreviewTest PrintWebViewHelperPreviewTest
38 #endif // defined(OS_ANDROID)
40 namespace base {
41 class DictionaryValue;
44 namespace blink {
45 class WebFrame;
46 class WebView;
49 namespace printing {
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 {
58 public:
59 explicit FrameReference(blink::WebLocalFrame* frame);
60 FrameReference();
61 ~FrameReference();
63 void Reset(blink::WebLocalFrame* frame);
65 blink::WebLocalFrame* GetFrame();
66 blink::WebView* view();
68 private:
69 blink::WebView* view_;
70 blink::WebLocalFrame* frame_;
73 // PrintWebViewHelper handles most of the printing grunt work for RenderView.
74 // We plan on making print asynchronous and that will require copying the DOM
75 // of the document and creating a new WebView with the contents.
76 class PrintWebViewHelper
77 : public content::RenderViewObserver,
78 public content::RenderViewObserverTracker<PrintWebViewHelper> {
79 public:
80 class Delegate {
81 public:
82 virtual ~Delegate() {}
84 // Cancels prerender if it's currently in progress and returns |true| if
85 // the cancellation was done with success.
86 virtual bool CancelPrerender(content::RenderView* render_view,
87 int routing_id) = 0;
89 // Returns the element to be printed. Returns a null WebElement if
90 // a pdf plugin element can't be extracted from the frame.
91 virtual blink::WebElement GetPdfElement(blink::WebLocalFrame* frame) = 0;
93 virtual bool IsPrintPreviewEnabled() = 0;
95 // If true, the user can be asked to provide print settings.
96 // The default implementation returns |true|.
97 virtual bool IsAskPrintSettingsEnabled();
99 // If false, window.print() won't do anything.
100 // The default implementation returns |true|.
101 virtual bool IsScriptedPrintEnabled();
103 // Returns true if printing is overridden and the default behavior should be
104 // skipped for |frame|.
105 virtual bool OverridePrint(blink::WebLocalFrame* frame) = 0;
108 PrintWebViewHelper(content::RenderView* render_view,
109 scoped_ptr<Delegate> delegate);
110 ~PrintWebViewHelper() override;
112 // Disable print preview and switch to system dialog printing even if full
113 // printing is build-in. This method is used by CEF.
114 static void DisablePreview();
116 bool IsPrintingEnabled();
118 void PrintNode(const blink::WebNode& node);
120 private:
121 friend class PrintWebViewHelperTestBase;
122 FRIEND_TEST_ALL_PREFIXES(MAYBE_PrintWebViewHelperPreviewTest,
123 BlockScriptInitiatedPrinting);
124 FRIEND_TEST_ALL_PREFIXES(MAYBE_PrintWebViewHelperTest, OnPrintPages);
125 FRIEND_TEST_ALL_PREFIXES(MAYBE_PrintWebViewHelperTest,
126 BlockScriptInitiatedPrinting);
127 FRIEND_TEST_ALL_PREFIXES(MAYBE_PrintWebViewHelperTest,
128 BlockScriptInitiatedPrintingFromPopup);
129 #if defined(OS_WIN) || defined(OS_MACOSX)
130 FRIEND_TEST_ALL_PREFIXES(MAYBE_PrintWebViewHelperTest, PrintLayoutTest);
131 FRIEND_TEST_ALL_PREFIXES(MAYBE_PrintWebViewHelperTest, PrintWithIframe);
132 #endif // defined(OS_WIN) || defined(OS_MACOSX)
134 enum PrintingResult {
136 FAIL_PRINT_INIT,
137 FAIL_PRINT,
138 FAIL_PREVIEW,
141 enum PrintPreviewErrorBuckets {
142 PREVIEW_ERROR_NONE, // Always first.
143 PREVIEW_ERROR_BAD_SETTING,
144 PREVIEW_ERROR_METAFILE_COPY_FAILED,
145 PREVIEW_ERROR_METAFILE_INIT_FAILED,
146 PREVIEW_ERROR_ZERO_PAGES,
147 PREVIEW_ERROR_MAC_DRAFT_METAFILE_INIT_FAILED,
148 PREVIEW_ERROR_PAGE_RENDERED_WITHOUT_METAFILE,
149 PREVIEW_ERROR_INVALID_PRINTER_SETTINGS,
150 PREVIEW_ERROR_LAST_ENUM // Always last.
153 enum PrintPreviewRequestType {
154 PRINT_PREVIEW_USER_INITIATED_ENTIRE_FRAME,
155 PRINT_PREVIEW_USER_INITIATED_SELECTION,
156 PRINT_PREVIEW_USER_INITIATED_CONTEXT_NODE,
157 PRINT_PREVIEW_SCRIPTED // triggered by window.print().
160 // RenderViewObserver implementation.
161 bool OnMessageReceived(const IPC::Message& message) override;
162 void PrintPage(blink::WebLocalFrame* frame, bool user_initiated) override;
163 void DidStartLoading() override;
164 void DidStopLoading() override;
166 // Message handlers ---------------------------------------------------------
167 #if defined(ENABLE_BASIC_PRINTING)
168 void OnPrintPages();
169 void OnPrintForSystemDialog();
170 #endif // ENABLE_BASIC_PRINTING
171 void OnInitiatePrintPreview(bool selection_only);
172 void OnPrintPreview(const base::DictionaryValue& settings);
173 void OnPrintForPrintPreview(const base::DictionaryValue& job_settings);
174 void OnPrintingDone(bool success);
176 // Get |page_size| and |content_area| information from
177 // |page_layout_in_points|.
178 void GetPageSizeAndContentAreaFromPageLayout(
179 const PageSizeMargins& page_layout_in_points,
180 gfx::Size* page_size,
181 gfx::Rect* content_area);
183 // Update |ignore_css_margins_| based on settings.
184 void UpdateFrameMarginsCssInfo(const base::DictionaryValue& settings);
186 // Returns true if the current destination printer is PRINT_TO_PDF.
187 bool IsPrintToPdfRequested(const base::DictionaryValue& settings);
189 // Prepare frame for creating preview document.
190 void PrepareFrameForPreviewDocument();
192 // Continue creating preview document.
193 void OnFramePreparedForPreviewDocument();
195 // Initialize the print preview document.
196 bool CreatePreviewDocument();
198 // Renders a print preview page. |page_number| is 0-based.
199 // Returns true if print preview should continue, false on failure.
200 bool RenderPreviewPage(int page_number,
201 const PrintMsg_Print_Params& print_params);
203 // Finalize the print ready preview document.
204 bool FinalizePrintReadyDocument();
206 // Enable/Disable window.print calls. If |blocked| is true window.print
207 // calls will silently fail. Call with |blocked| set to false to reenable.
208 void SetScriptedPrintBlocked(bool blocked);
210 // Main printing code -------------------------------------------------------
212 // |is_scripted| should be true when the call is coming from window.print()
213 void Print(blink::WebLocalFrame* frame,
214 const blink::WebNode& node,
215 bool is_scripted);
217 // Notification when printing is done - signal tear-down/free resources.
218 void DidFinishPrinting(PrintingResult result);
220 // Print Settings -----------------------------------------------------------
222 // Initialize print page settings with default settings.
223 // Used only for native printing workflow.
224 bool InitPrintSettings(bool fit_to_paper_size);
226 // Calculate number of pages in source document.
227 bool CalculateNumberOfPages(blink::WebLocalFrame* frame,
228 const blink::WebNode& node,
229 int* number_of_pages);
231 // Set options for print preset from source PDF document.
232 bool SetOptionsFromPdfDocument(
233 PrintHostMsg_SetOptionsFromDocument_Params* options);
235 // Update the current print settings with new |passed_job_settings|.
236 // |passed_job_settings| dictionary contains print job details such as printer
237 // name, number of copies, page range, etc.
238 bool UpdatePrintSettings(blink::WebLocalFrame* frame,
239 const blink::WebNode& node,
240 const base::DictionaryValue& passed_job_settings);
242 // Get final print settings from the user.
243 // Return false if the user cancels or on error.
244 bool GetPrintSettingsFromUser(blink::WebLocalFrame* frame,
245 const blink::WebNode& node,
246 int expected_pages_count,
247 bool is_scripted);
249 // Page Printing / Rendering ------------------------------------------------
251 void OnFramePreparedForPrintPages();
252 void PrintPages();
253 bool PrintPagesNative(blink::WebFrame* frame, int page_count);
254 void FinishFramePrinting();
256 // Prints the page listed in |params|.
257 #if defined(OS_LINUX) || defined(OS_ANDROID)
258 void PrintPageInternal(const PrintMsg_PrintPage_Params& params,
259 blink::WebFrame* frame,
260 PdfMetafileSkia* metafile);
261 #elif defined(OS_WIN)
262 void PrintPageInternal(const PrintMsg_PrintPage_Params& params,
263 blink::WebFrame* frame,
264 PdfMetafileSkia* metafile,
265 gfx::Size* page_size_in_dpi,
266 gfx::Rect* content_area_in_dpi);
267 #else
268 void PrintPageInternal(const PrintMsg_PrintPage_Params& params,
269 blink::WebFrame* frame);
270 #endif
272 // Render the frame for printing.
273 bool RenderPagesForPrint(blink::WebLocalFrame* frame,
274 const blink::WebNode& node);
276 // Platform specific helper function for rendering page(s) to |metafile|.
277 #if defined(OS_MACOSX)
278 void RenderPage(const PrintMsg_Print_Params& params,
279 int page_number,
280 blink::WebFrame* frame,
281 bool is_preview,
282 PdfMetafileSkia* metafile,
283 gfx::Size* page_size,
284 gfx::Rect* content_rect);
285 #endif // defined(OS_MACOSX)
287 // Renders page contents from |frame| to |content_area| of |canvas|.
288 // |page_number| is zero-based.
289 // When method is called, canvas should be setup to draw to |canvas_area|
290 // with |scale_factor|.
291 static float RenderPageContent(blink::WebFrame* frame,
292 int page_number,
293 const gfx::Rect& canvas_area,
294 const gfx::Rect& content_area,
295 double scale_factor,
296 blink::WebCanvas* canvas);
298 // Helper methods -----------------------------------------------------------
300 bool CopyMetafileDataToSharedMem(const PdfMetafileSkia& metafile,
301 base::SharedMemoryHandle* shared_mem_handle);
303 // Helper method to get page layout in points and fit to page if needed.
304 static void ComputePageLayoutInPointsForCss(
305 blink::WebFrame* frame,
306 int page_index,
307 const PrintMsg_Print_Params& default_params,
308 bool ignore_css_margins,
309 double* scale_factor,
310 PageSizeMargins* page_layout_in_points);
312 #if defined(ENABLE_PRINT_PREVIEW)
313 // Given the |device| and |canvas| to draw on, prints the appropriate headers
314 // and footers using strings from |header_footer_info| on to the canvas.
315 static void PrintHeaderAndFooter(blink::WebCanvas* canvas,
316 int page_number,
317 int total_pages,
318 const blink::WebFrame& source_frame,
319 float webkit_scale_factor,
320 const PageSizeMargins& page_layout_in_points,
321 const PrintMsg_Print_Params& params);
322 #endif // defined(ENABLE_PRINT_PREVIEW)
324 bool GetPrintFrame(blink::WebLocalFrame** frame);
326 // Script Initiated Printing ------------------------------------------------
328 // Return true if script initiated printing is currently
329 // allowed. |user_initiated| should be true when a user event triggered the
330 // script, most likely by pressing a print button on the page.
331 bool IsScriptInitiatedPrintAllowed(blink::WebFrame* frame,
332 bool user_initiated);
334 // Shows scripted print preview when options from plugin are available.
335 void ShowScriptedPrintPreview();
337 void RequestPrintPreview(PrintPreviewRequestType type);
339 // Checks whether print preview should continue or not.
340 // Returns true if canceling, false if continuing.
341 bool CheckForCancel();
343 // Notifies the browser a print preview page has been rendered.
344 // |page_number| is 0-based.
345 // For a valid |page_number| with modifiable content,
346 // |metafile| is the rendered page. Otherwise |metafile| is NULL.
347 // Returns true if print preview should continue, false on failure.
348 bool PreviewPageRendered(int page_number, PdfMetafileSkia* metafile);
350 void SetPrintPagesParams(const PrintMsg_PrintPages_Params& settings);
352 // WebView used only to print the selection.
353 scoped_ptr<PrepareFrameAndViewForPrint> prep_frame_view_;
354 bool reset_prep_frame_view_;
356 scoped_ptr<PrintMsg_PrintPages_Params> print_pages_params_;
357 bool is_print_ready_metafile_sent_;
358 bool ignore_css_margins_;
360 // Used for scripted initiated printing blocking.
361 bool is_scripted_printing_blocked_;
363 // Let the browser process know of a printing failure. Only set to false when
364 // the failure came from the browser in the first place.
365 bool notify_browser_of_print_failure_;
367 // True, when printing from print preview.
368 bool print_for_preview_;
370 // Used to check the prerendering status.
371 const scoped_ptr<Delegate> delegate_;
373 // Keeps track of the state of print preview between messages.
374 // TODO(vitalybuka): Create PrintPreviewContext when needed and delete after
375 // use. Now it's interaction with various messages is confusing.
376 class PrintPreviewContext {
377 public:
378 PrintPreviewContext();
379 ~PrintPreviewContext();
381 // Initializes the print preview context. Need to be called to set
382 // the |web_frame| / |web_node| to generate the print preview for.
383 void InitWithFrame(blink::WebLocalFrame* web_frame);
384 void InitWithNode(const blink::WebNode& web_node);
386 // Does bookkeeping at the beginning of print preview.
387 void OnPrintPreview();
389 // Create the print preview document. |pages| is empty to print all pages.
390 // Takes ownership of |prepared_frame|.
391 bool CreatePreviewDocument(PrepareFrameAndViewForPrint* prepared_frame,
392 const std::vector<int>& pages);
394 // Called after a page gets rendered. |page_time| is how long the
395 // rendering took.
396 void RenderedPreviewPage(const base::TimeDelta& page_time);
398 // Updates the print preview context when the required pages are rendered.
399 void AllPagesRendered();
401 // Finalizes the print ready preview document.
402 void FinalizePrintReadyDocument();
404 // Cleanup after print preview finishes.
405 void Finished();
407 // Cleanup after print preview fails.
408 void Failed(bool report_error);
410 // Helper functions
411 int GetNextPageNumber();
412 bool IsRendering() const;
413 bool IsModifiable();
414 bool HasSelection();
415 bool IsLastPageOfPrintReadyMetafile() const;
416 bool IsFinalPageRendered() const;
418 // Setters
419 void set_generate_draft_pages(bool generate_draft_pages);
420 void set_error(enum PrintPreviewErrorBuckets error);
422 // Getters
423 // Original frame for which preview was requested.
424 blink::WebLocalFrame* source_frame();
425 // Original node for which preview was requested.
426 const blink::WebNode& source_node() const;
428 // Frame to be use to render preview. May be the same as source_frame(), or
429 // generated from it, e.g. copy of selected block.
430 blink::WebLocalFrame* prepared_frame();
431 // Node to be use to render preview. May be the same as source_node(), or
432 // generated from it, e.g. copy of selected block.
433 const blink::WebNode& prepared_node() const;
435 int total_page_count() const;
436 bool generate_draft_pages() const;
437 PdfMetafileSkia* metafile();
438 int last_error() const;
440 private:
441 enum State {
442 UNINITIALIZED, // Not ready to render.
443 INITIALIZED, // Ready to render.
444 RENDERING, // Rendering.
445 DONE // Finished rendering.
448 // Reset some of the internal rendering context.
449 void ClearContext();
451 // Specifies what to render for print preview.
452 FrameReference source_frame_;
453 blink::WebNode source_node_;
455 scoped_ptr<PrepareFrameAndViewForPrint> prep_frame_view_;
456 scoped_ptr<PdfMetafileSkia> metafile_;
458 // Total page count in the renderer.
459 int total_page_count_;
461 // The current page to render.
462 int current_page_index_;
464 // List of page indices that need to be rendered.
465 std::vector<int> pages_to_render_;
467 // True, when draft pages needs to be generated.
468 bool generate_draft_pages_;
470 // Specifies the total number of pages in the print ready metafile.
471 int print_ready_metafile_page_count_;
473 base::TimeDelta document_render_time_;
474 base::TimeTicks begin_time_;
476 enum PrintPreviewErrorBuckets error_;
478 State state_;
481 class ScriptingThrottler {
482 public:
483 ScriptingThrottler();
485 // Returns false if script initiated printing occurs too often.
486 bool IsAllowed(blink::WebFrame* frame);
488 // Reset the counter for script initiated printing.
489 // Scripted printing will be allowed to continue.
490 void Reset();
492 private:
493 base::Time last_print_;
494 int count_ = 0;
495 DISALLOW_COPY_AND_ASSIGN(ScriptingThrottler);
498 ScriptingThrottler scripting_throttler_;
500 bool print_node_in_progress_;
501 PrintPreviewContext print_preview_context_;
502 bool is_loading_;
503 bool is_scripted_preview_delayed_;
504 int ipc_nesting_level_;
506 // Used to fix a race condition where the source is a PDF and print preview
507 // hangs because RequestPrintPreview is called before DidStopLoading() is
508 // called. This is a store for the RequestPrintPreview() call and its
509 // parameters so that it can be invoked after DidStopLoading.
510 base::Closure on_stop_loading_closure_;
512 base::WeakPtrFactory<PrintWebViewHelper> weak_ptr_factory_;
514 DISALLOW_COPY_AND_ASSIGN(PrintWebViewHelper);
517 } // namespace printing
519 #endif // COMPONENTS_PRINTING_RENDERER_PRINT_WEB_VIEW_HELPER_H_