Explicitly add python-numpy dependency to install-build-deps.
[chromium-blink-merge.git] / chrome / renderer / printing / print_web_view_helper.h
blobf4d7aaa3bf9a72bc40a494123397de8669f7a1f1
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 void Print(blink::WebLocalFrame* frame, const blink::WebNode& node);
174 // Notification when printing is done - signal tear-down/free resources.
175 void DidFinishPrinting(PrintingResult result);
177 // Print Settings -----------------------------------------------------------
179 // Initialize print page settings with default settings.
180 // Used only for native printing workflow.
181 bool InitPrintSettings(bool fit_to_paper_size);
183 // Calculate number of pages in source document.
184 bool CalculateNumberOfPages(blink::WebLocalFrame* frame,
185 const blink::WebNode& node,
186 int* number_of_pages);
188 // Set options for print preset from source PDF document.
189 void SetOptionsFromDocument(
190 PrintHostMsg_SetOptionsFromDocument_Params& params);
192 // Update the current print settings with new |passed_job_settings|.
193 // |passed_job_settings| dictionary contains print job details such as printer
194 // name, number of copies, page range, etc.
195 bool UpdatePrintSettings(blink::WebLocalFrame* frame,
196 const blink::WebNode& node,
197 const base::DictionaryValue& passed_job_settings);
199 // Get final print settings from the user.
200 // Return false if the user cancels or on error.
201 bool GetPrintSettingsFromUser(blink::WebFrame* frame,
202 const blink::WebNode& node,
203 int expected_pages_count);
205 // Page Printing / Rendering ------------------------------------------------
207 void OnFramePreparedForPrintPages();
208 void PrintPages();
209 bool PrintPagesNative(blink::WebFrame* frame, int page_count);
210 void FinishFramePrinting();
212 // Prints the page listed in |params|.
213 #if defined(OS_LINUX) || defined(OS_ANDROID)
214 void PrintPageInternal(const PrintMsg_PrintPage_Params& params,
215 blink::WebFrame* frame,
216 PdfMetafileSkia* metafile);
217 #elif defined(OS_WIN)
218 void PrintPageInternal(const PrintMsg_PrintPage_Params& params,
219 blink::WebFrame* frame,
220 PdfMetafileSkia* metafile,
221 gfx::Size* page_size_in_dpi,
222 gfx::Rect* content_area_in_dpi);
223 #else
224 void PrintPageInternal(const PrintMsg_PrintPage_Params& params,
225 blink::WebFrame* frame);
226 #endif
228 // Render the frame for printing.
229 bool RenderPagesForPrint(blink::WebLocalFrame* frame,
230 const blink::WebNode& node);
232 // Platform specific helper function for rendering page(s) to |metafile|.
233 #if defined(OS_MACOSX)
234 void RenderPage(const PrintMsg_Print_Params& params,
235 int page_number,
236 blink::WebFrame* frame,
237 bool is_preview,
238 PdfMetafileSkia* metafile,
239 gfx::Size* page_size,
240 gfx::Rect* content_rect);
241 #endif // defined(OS_MACOSX)
243 // Renders page contents from |frame| to |content_area| of |canvas|.
244 // |page_number| is zero-based.
245 // When method is called, canvas should be setup to draw to |canvas_area|
246 // with |scale_factor|.
247 static float RenderPageContent(blink::WebFrame* frame,
248 int page_number,
249 const gfx::Rect& canvas_area,
250 const gfx::Rect& content_area,
251 double scale_factor,
252 blink::WebCanvas* canvas);
254 // Helper methods -----------------------------------------------------------
256 bool CopyMetafileDataToSharedMem(PdfMetafileSkia* metafile,
257 base::SharedMemoryHandle* shared_mem_handle);
259 // Helper method to get page layout in points and fit to page if needed.
260 static void ComputePageLayoutInPointsForCss(
261 blink::WebFrame* frame,
262 int page_index,
263 const PrintMsg_Print_Params& default_params,
264 bool ignore_css_margins,
265 double* scale_factor,
266 PageSizeMargins* page_layout_in_points);
268 #if defined(ENABLE_PRINT_PREVIEW)
269 // Given the |device| and |canvas| to draw on, prints the appropriate headers
270 // and footers using strings from |header_footer_info| on to the canvas.
271 static void PrintHeaderAndFooter(blink::WebCanvas* canvas,
272 int page_number,
273 int total_pages,
274 const blink::WebFrame& source_frame,
275 float webkit_scale_factor,
276 const PageSizeMargins& page_layout_in_points,
277 const PrintMsg_Print_Params& params);
278 #endif // defined(ENABLE_PRINT_PREVIEW)
280 bool GetPrintFrame(blink::WebLocalFrame** frame);
282 // Script Initiated Printing ------------------------------------------------
284 // Return true if script initiated printing is currently
285 // allowed. |user_initiated| should be true when a user event triggered the
286 // script, most likely by pressing a print button on the page.
287 bool IsScriptInitiatedPrintAllowed(blink::WebFrame* frame,
288 bool user_initiated);
290 // Shows scripted print preview when options from plugin are available.
291 void ShowScriptedPrintPreview();
293 void RequestPrintPreview(PrintPreviewRequestType type);
295 // Checks whether print preview should continue or not.
296 // Returns true if canceling, false if continuing.
297 bool CheckForCancel();
299 // Notifies the browser a print preview page has been rendered.
300 // |page_number| is 0-based.
301 // For a valid |page_number| with modifiable content,
302 // |metafile| is the rendered page. Otherwise |metafile| is NULL.
303 // Returns true if print preview should continue, false on failure.
304 bool PreviewPageRendered(int page_number, PdfMetafileSkia* metafile);
306 void SetPrintPagesParams(const PrintMsg_PrintPages_Params& settings);
308 // WebView used only to print the selection.
309 scoped_ptr<PrepareFrameAndViewForPrint> prep_frame_view_;
310 bool reset_prep_frame_view_;
312 scoped_ptr<PrintMsg_PrintPages_Params> print_pages_params_;
313 bool is_print_ready_metafile_sent_;
314 bool ignore_css_margins_;
316 // Used for scripted initiated printing blocking.
317 bool is_scripted_printing_blocked_;
319 // Let the browser process know of a printing failure. Only set to false when
320 // the failure came from the browser in the first place.
321 bool notify_browser_of_print_failure_;
323 // True, when printing from print preview.
324 bool print_for_preview_;
326 // Keeps track of the state of print preview between messages.
327 // TODO(vitalybuka): Create PrintPreviewContext when needed and delete after
328 // use. Now it's interaction with various messages is confusing.
329 class PrintPreviewContext {
330 public:
331 PrintPreviewContext();
332 ~PrintPreviewContext();
334 // Initializes the print preview context. Need to be called to set
335 // the |web_frame| / |web_node| to generate the print preview for.
336 void InitWithFrame(blink::WebLocalFrame* web_frame);
337 void InitWithNode(const blink::WebNode& web_node);
339 // Does bookkeeping at the beginning of print preview.
340 void OnPrintPreview();
342 // Create the print preview document. |pages| is empty to print all pages.
343 // Takes ownership of |prepared_frame|.
344 bool CreatePreviewDocument(PrepareFrameAndViewForPrint* prepared_frame,
345 const std::vector<int>& pages);
347 // Called after a page gets rendered. |page_time| is how long the
348 // rendering took.
349 void RenderedPreviewPage(const base::TimeDelta& page_time);
351 // Updates the print preview context when the required pages are rendered.
352 void AllPagesRendered();
354 // Finalizes the print ready preview document.
355 void FinalizePrintReadyDocument();
357 // Cleanup after print preview finishes.
358 void Finished();
360 // Cleanup after print preview fails.
361 void Failed(bool report_error);
363 // Helper functions
364 int GetNextPageNumber();
365 bool IsRendering() const;
366 bool IsModifiable();
367 bool HasSelection();
368 bool IsLastPageOfPrintReadyMetafile() const;
369 bool IsFinalPageRendered() const;
371 // Setters
372 void set_generate_draft_pages(bool generate_draft_pages);
373 void set_error(enum PrintPreviewErrorBuckets error);
375 // Getters
376 // Original frame for which preview was requested.
377 blink::WebLocalFrame* source_frame();
378 // Original node for which preview was requested.
379 const blink::WebNode& source_node() const;
381 // Frame to be use to render preview. May be the same as source_frame(), or
382 // generated from it, e.g. copy of selected block.
383 blink::WebLocalFrame* prepared_frame();
384 // Node to be use to render preview. May be the same as source_node(), or
385 // generated from it, e.g. copy of selected block.
386 const blink::WebNode& prepared_node() const;
388 int total_page_count() const;
389 bool generate_draft_pages() const;
390 PdfMetafileSkia* metafile();
391 int last_error() const;
393 private:
394 enum State {
395 UNINITIALIZED, // Not ready to render.
396 INITIALIZED, // Ready to render.
397 RENDERING, // Rendering.
398 DONE // Finished rendering.
401 // Reset some of the internal rendering context.
402 void ClearContext();
404 // Specifies what to render for print preview.
405 FrameReference source_frame_;
406 blink::WebNode source_node_;
408 scoped_ptr<PrepareFrameAndViewForPrint> prep_frame_view_;
409 scoped_ptr<PdfMetafileSkia> metafile_;
411 // Total page count in the renderer.
412 int total_page_count_;
414 // The current page to render.
415 int current_page_index_;
417 // List of page indices that need to be rendered.
418 std::vector<int> pages_to_render_;
420 // True, when draft pages needs to be generated.
421 bool generate_draft_pages_;
423 // Specifies the total number of pages in the print ready metafile.
424 int print_ready_metafile_page_count_;
426 base::TimeDelta document_render_time_;
427 base::TimeTicks begin_time_;
429 enum PrintPreviewErrorBuckets error_;
431 State state_;
434 class ScriptingThrottler {
435 public:
436 ScriptingThrottler();
438 // Returns false if script initiated printing occurs too often.
439 bool IsAllowed(blink::WebFrame* frame);
441 // Reset the counter for script initiated printing.
442 // Scripted printing will be allowed to continue.
443 void Reset();
445 private:
446 base::Time last_print_;
447 int count_ = 0;
448 DISALLOW_COPY_AND_ASSIGN(ScriptingThrottler);
451 ScriptingThrottler scripting_throttler_;
453 bool print_node_in_progress_;
454 PrintPreviewContext print_preview_context_;
455 bool is_loading_;
456 bool is_scripted_preview_delayed_;
458 // Used to fix a race condition where the source is a PDF and print preview
459 // hangs because RequestPrintPreview is called before DidStopLoading() is
460 // called. This is a store for the RequestPrintPreview() call and its
461 // parameters so that it can be invoked after DidStopLoading.
462 base::Closure on_stop_loading_closure_;
464 base::WeakPtrFactory<PrintWebViewHelper> weak_ptr_factory_;
466 DISALLOW_COPY_AND_ASSIGN(PrintWebViewHelper);
469 } // namespace printing
471 #endif // CHROME_RENDERER_PRINTING_PRINT_WEB_VIEW_HELPER_H_