Implement window.print() on Android
[chromium-blink-merge.git] / chrome / renderer / printing / print_web_view_helper.h
blobf144adc45d02b52059541420eb40cbd3c5d76e8d
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_
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/size.h"
24 struct PrintMsg_Print_Params;
25 struct PrintMsg_PrintPage_Params;
26 struct PrintMsg_PrintPages_Params;
27 struct PrintHostMsg_SetOptionsFromDocument_Params;
29 namespace base {
30 class DictionaryValue;
33 namespace blink {
34 class WebFrame;
35 class WebView;
38 namespace printing {
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 {
47 public:
48 explicit FrameReference(blink::WebLocalFrame* frame);
49 FrameReference();
50 ~FrameReference();
52 void Reset(blink::WebLocalFrame* frame);
54 blink::WebLocalFrame* GetFrame();
55 blink::WebView* view();
57 private:
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> {
68 public:
69 explicit PrintWebViewHelper(content::RenderView* render_view);
70 ~PrintWebViewHelper() override;
72 // Disable print preview and switch to system dialog printing even if full
73 // printing is build-in. This method is used by CEF.
74 static void DisablePreview();
76 bool IsPrintingEnabled();
78 void PrintNode(const blink::WebNode& node);
80 private:
81 friend class PrintWebViewHelperTestBase;
82 FRIEND_TEST_ALL_PREFIXES(PrintWebViewHelperPreviewTest,
83 BlockScriptInitiatedPrinting);
84 FRIEND_TEST_ALL_PREFIXES(PrintWebViewHelperTest, OnPrintPages);
85 FRIEND_TEST_ALL_PREFIXES(PrintWebViewHelperTest,
86 BlockScriptInitiatedPrinting);
87 FRIEND_TEST_ALL_PREFIXES(PrintWebViewHelperTest,
88 BlockScriptInitiatedPrintingFromPopup);
89 #if defined(OS_WIN) || defined(OS_MACOSX)
90 FRIEND_TEST_ALL_PREFIXES(PrintWebViewHelperTest, PrintLayoutTest);
91 FRIEND_TEST_ALL_PREFIXES(PrintWebViewHelperTest, PrintWithIframe);
92 #endif // defined(OS_WIN) || defined(OS_MACOSX)
94 enum PrintingResult {
95 OK,
96 FAIL_PRINT_INIT,
97 FAIL_PRINT,
98 FAIL_PREVIEW,
101 enum PrintPreviewErrorBuckets {
102 PREVIEW_ERROR_NONE, // Always first.
103 PREVIEW_ERROR_BAD_SETTING,
104 PREVIEW_ERROR_METAFILE_COPY_FAILED,
105 PREVIEW_ERROR_METAFILE_INIT_FAILED,
106 PREVIEW_ERROR_ZERO_PAGES,
107 PREVIEW_ERROR_MAC_DRAFT_METAFILE_INIT_FAILED,
108 PREVIEW_ERROR_PAGE_RENDERED_WITHOUT_METAFILE,
109 PREVIEW_ERROR_INVALID_PRINTER_SETTINGS,
110 PREVIEW_ERROR_LAST_ENUM // Always last.
113 enum PrintPreviewRequestType {
114 PRINT_PREVIEW_USER_INITIATED_ENTIRE_FRAME,
115 PRINT_PREVIEW_USER_INITIATED_SELECTION,
116 PRINT_PREVIEW_USER_INITIATED_CONTEXT_NODE,
117 PRINT_PREVIEW_SCRIPTED // triggered by window.print().
120 // RenderViewObserver implementation.
121 bool OnMessageReceived(const IPC::Message& message) override;
122 void PrintPage(blink::WebLocalFrame* frame, bool user_initiated) override;
123 void DidStartLoading() override;
124 void DidStopLoading() override;
126 // Message handlers ---------------------------------------------------------
127 #if defined(ENABLE_BASIC_PRINTING)
128 void OnPrintPages();
129 void OnPrintForSystemDialog();
130 #endif // ENABLE_BASIC_PRINTING
131 void OnInitiatePrintPreview(bool selection_only);
132 void OnPrintPreview(const base::DictionaryValue& settings);
133 void OnPrintForPrintPreview(const base::DictionaryValue& job_settings);
134 void OnPrintingDone(bool success);
136 // Get |page_size| and |content_area| information from
137 // |page_layout_in_points|.
138 void GetPageSizeAndContentAreaFromPageLayout(
139 const PageSizeMargins& page_layout_in_points,
140 gfx::Size* page_size,
141 gfx::Rect* content_area);
143 // Update |ignore_css_margins_| based on settings.
144 void UpdateFrameMarginsCssInfo(const base::DictionaryValue& settings);
146 // Returns true if the current destination printer is PRINT_TO_PDF.
147 bool IsPrintToPdfRequested(const base::DictionaryValue& settings);
149 // Prepare frame for creating preview document.
150 void PrepareFrameForPreviewDocument();
152 // Continue creating preview document.
153 void OnFramePreparedForPreviewDocument();
155 // Initialize the print preview document.
156 bool CreatePreviewDocument();
158 // Renders a print preview page. |page_number| is 0-based.
159 // Returns true if print preview should continue, false on failure.
160 bool RenderPreviewPage(int page_number,
161 const PrintMsg_Print_Params& print_params);
163 // Finalize the print ready preview document.
164 bool FinalizePrintReadyDocument();
166 // Enable/Disable window.print calls. If |blocked| is true window.print
167 // calls will silently fail. Call with |blocked| set to false to reenable.
168 void SetScriptedPrintBlocked(bool blocked);
170 // Main printing code -------------------------------------------------------
172 // |is_scripted| should be true when the call is coming from window.print()
173 void Print(blink::WebLocalFrame* frame,
174 const blink::WebNode& node,
175 bool is_scripted);
177 // Notification when printing is done - signal tear-down/free resources.
178 void DidFinishPrinting(PrintingResult result);
180 // Print Settings -----------------------------------------------------------
182 // Initialize print page settings with default settings.
183 // Used only for native printing workflow.
184 bool InitPrintSettings(bool fit_to_paper_size);
186 // Calculate number of pages in source document.
187 bool CalculateNumberOfPages(blink::WebLocalFrame* frame,
188 const blink::WebNode& node,
189 int* number_of_pages);
191 // Set options for print preset from source PDF document.
192 void SetOptionsFromDocument(
193 PrintHostMsg_SetOptionsFromDocument_Params& params);
195 // Update the current print settings with new |passed_job_settings|.
196 // |passed_job_settings| dictionary contains print job details such as printer
197 // name, number of copies, page range, etc.
198 bool UpdatePrintSettings(blink::WebLocalFrame* frame,
199 const blink::WebNode& node,
200 const base::DictionaryValue& passed_job_settings);
202 // Get final print settings from the user.
203 // Return false if the user cancels or on error.
204 bool GetPrintSettingsFromUser(blink::WebFrame* frame,
205 const blink::WebNode& node,
206 int expected_pages_count,
207 bool is_scripted);
209 // Page Printing / Rendering ------------------------------------------------
211 void OnFramePreparedForPrintPages();
212 void PrintPages();
213 bool PrintPagesNative(blink::WebFrame* frame, int page_count);
214 void FinishFramePrinting();
216 // Prints the page listed in |params|.
217 #if defined(OS_LINUX) || defined(OS_ANDROID)
218 void PrintPageInternal(const PrintMsg_PrintPage_Params& params,
219 blink::WebFrame* frame,
220 PdfMetafileSkia* metafile);
221 #elif defined(OS_WIN)
222 void PrintPageInternal(const PrintMsg_PrintPage_Params& params,
223 blink::WebFrame* frame,
224 PdfMetafileSkia* metafile,
225 gfx::Size* page_size_in_dpi,
226 gfx::Rect* content_area_in_dpi);
227 #else
228 void PrintPageInternal(const PrintMsg_PrintPage_Params& params,
229 blink::WebFrame* frame);
230 #endif
232 // Render the frame for printing.
233 bool RenderPagesForPrint(blink::WebLocalFrame* frame,
234 const blink::WebNode& node);
236 // Platform specific helper function for rendering page(s) to |metafile|.
237 #if defined(OS_MACOSX)
238 void RenderPage(const PrintMsg_Print_Params& params,
239 int page_number,
240 blink::WebFrame* frame,
241 bool is_preview,
242 PdfMetafileSkia* metafile,
243 gfx::Size* page_size,
244 gfx::Rect* content_rect);
245 #endif // defined(OS_MACOSX)
247 // Renders page contents from |frame| to |content_area| of |canvas|.
248 // |page_number| is zero-based.
249 // When method is called, canvas should be setup to draw to |canvas_area|
250 // with |scale_factor|.
251 static float RenderPageContent(blink::WebFrame* frame,
252 int page_number,
253 const gfx::Rect& canvas_area,
254 const gfx::Rect& content_area,
255 double scale_factor,
256 blink::WebCanvas* canvas);
258 // Helper methods -----------------------------------------------------------
260 bool CopyMetafileDataToSharedMem(PdfMetafileSkia* metafile,
261 base::SharedMemoryHandle* shared_mem_handle);
263 // Helper method to get page layout in points and fit to page if needed.
264 static void ComputePageLayoutInPointsForCss(
265 blink::WebFrame* frame,
266 int page_index,
267 const PrintMsg_Print_Params& default_params,
268 bool ignore_css_margins,
269 double* scale_factor,
270 PageSizeMargins* page_layout_in_points);
272 #if defined(ENABLE_PRINT_PREVIEW)
273 // Given the |device| and |canvas| to draw on, prints the appropriate headers
274 // and footers using strings from |header_footer_info| on to the canvas.
275 static void PrintHeaderAndFooter(blink::WebCanvas* canvas,
276 int page_number,
277 int total_pages,
278 const blink::WebFrame& source_frame,
279 float webkit_scale_factor,
280 const PageSizeMargins& page_layout_in_points,
281 const PrintMsg_Print_Params& params);
282 #endif // defined(ENABLE_PRINT_PREVIEW)
284 bool GetPrintFrame(blink::WebLocalFrame** frame);
286 // Script Initiated Printing ------------------------------------------------
288 // Return true if script initiated printing is currently
289 // allowed. |user_initiated| should be true when a user event triggered the
290 // script, most likely by pressing a print button on the page.
291 bool IsScriptInitiatedPrintAllowed(blink::WebFrame* frame,
292 bool user_initiated);
294 // Shows scripted print preview when options from plugin are available.
295 void ShowScriptedPrintPreview();
297 void RequestPrintPreview(PrintPreviewRequestType type);
299 // Checks whether print preview should continue or not.
300 // Returns true if canceling, false if continuing.
301 bool CheckForCancel();
303 // Notifies the browser a print preview page has been rendered.
304 // |page_number| is 0-based.
305 // For a valid |page_number| with modifiable content,
306 // |metafile| is the rendered page. Otherwise |metafile| is NULL.
307 // Returns true if print preview should continue, false on failure.
308 bool PreviewPageRendered(int page_number, PdfMetafileSkia* metafile);
310 void SetPrintPagesParams(const PrintMsg_PrintPages_Params& settings);
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_print_ready_metafile_sent_;
318 bool ignore_css_margins_;
320 // Used for scripted initiated printing blocking.
321 bool is_scripted_printing_blocked_;
323 // Let the browser process know of a printing failure. Only set to false when
324 // the failure came from the browser in the first place.
325 bool notify_browser_of_print_failure_;
327 // True, when printing from print preview.
328 bool print_for_preview_;
330 // Keeps track of the state of print preview between messages.
331 // TODO(vitalybuka): Create PrintPreviewContext when needed and delete after
332 // use. Now it's interaction with various messages is confusing.
333 class PrintPreviewContext {
334 public:
335 PrintPreviewContext();
336 ~PrintPreviewContext();
338 // Initializes the print preview context. Need to be called to set
339 // the |web_frame| / |web_node| to generate the print preview for.
340 void InitWithFrame(blink::WebLocalFrame* web_frame);
341 void InitWithNode(const blink::WebNode& web_node);
343 // Does bookkeeping at the beginning of print preview.
344 void OnPrintPreview();
346 // Create the print preview document. |pages| is empty to print all pages.
347 // Takes ownership of |prepared_frame|.
348 bool CreatePreviewDocument(PrepareFrameAndViewForPrint* prepared_frame,
349 const std::vector<int>& pages);
351 // Called after a page gets rendered. |page_time| is how long the
352 // rendering took.
353 void RenderedPreviewPage(const base::TimeDelta& page_time);
355 // Updates the print preview context when the required pages are rendered.
356 void AllPagesRendered();
358 // Finalizes the print ready preview document.
359 void FinalizePrintReadyDocument();
361 // Cleanup after print preview finishes.
362 void Finished();
364 // Cleanup after print preview fails.
365 void Failed(bool report_error);
367 // Helper functions
368 int GetNextPageNumber();
369 bool IsRendering() const;
370 bool IsModifiable();
371 bool HasSelection();
372 bool IsLastPageOfPrintReadyMetafile() const;
373 bool IsFinalPageRendered() const;
375 // Setters
376 void set_generate_draft_pages(bool generate_draft_pages);
377 void set_error(enum PrintPreviewErrorBuckets error);
379 // Getters
380 // Original frame for which preview was requested.
381 blink::WebLocalFrame* source_frame();
382 // Original node for which preview was requested.
383 const blink::WebNode& source_node() const;
385 // Frame to be use to render preview. May be the same as source_frame(), or
386 // generated from it, e.g. copy of selected block.
387 blink::WebLocalFrame* prepared_frame();
388 // Node to be use to render preview. May be the same as source_node(), or
389 // generated from it, e.g. copy of selected block.
390 const blink::WebNode& prepared_node() const;
392 int total_page_count() const;
393 bool generate_draft_pages() const;
394 PdfMetafileSkia* metafile();
395 int last_error() const;
397 private:
398 enum State {
399 UNINITIALIZED, // Not ready to render.
400 INITIALIZED, // Ready to render.
401 RENDERING, // Rendering.
402 DONE // Finished rendering.
405 // Reset some of the internal rendering context.
406 void ClearContext();
408 // Specifies what to render for print preview.
409 FrameReference source_frame_;
410 blink::WebNode source_node_;
412 scoped_ptr<PrepareFrameAndViewForPrint> prep_frame_view_;
413 scoped_ptr<PdfMetafileSkia> metafile_;
415 // Total page count in the renderer.
416 int total_page_count_;
418 // The current page to render.
419 int current_page_index_;
421 // List of page indices that need to be rendered.
422 std::vector<int> pages_to_render_;
424 // True, when draft pages needs to be generated.
425 bool generate_draft_pages_;
427 // Specifies the total number of pages in the print ready metafile.
428 int print_ready_metafile_page_count_;
430 base::TimeDelta document_render_time_;
431 base::TimeTicks begin_time_;
433 enum PrintPreviewErrorBuckets error_;
435 State state_;
438 class ScriptingThrottler {
439 public:
440 ScriptingThrottler();
442 // Returns false if script initiated printing occurs too often.
443 bool IsAllowed(blink::WebFrame* frame);
445 // Reset the counter for script initiated printing.
446 // Scripted printing will be allowed to continue.
447 void Reset();
449 private:
450 base::Time last_print_;
451 int count_ = 0;
452 DISALLOW_COPY_AND_ASSIGN(ScriptingThrottler);
455 ScriptingThrottler scripting_throttler_;
457 bool print_node_in_progress_;
458 PrintPreviewContext print_preview_context_;
459 bool is_loading_;
460 bool is_scripted_preview_delayed_;
462 // Used to fix a race condition where the source is a PDF and print preview
463 // hangs because RequestPrintPreview is called before DidStopLoading() is
464 // called. This is a store for the RequestPrintPreview() call and its
465 // parameters so that it can be invoked after DidStopLoading.
466 base::Closure on_stop_loading_closure_;
468 base::WeakPtrFactory<PrintWebViewHelper> weak_ptr_factory_;
470 DISALLOW_COPY_AND_ASSIGN(PrintWebViewHelper);
473 } // namespace printing
475 #endif // CHROME_RENDERER_PRINTING_PRINT_WEB_VIEW_HELPER_H_