Disable view source for Developer Tools.
[chromium-blink-merge.git] / chrome / renderer / printing / print_web_view_helper.h
blobbf54d3afc1df772ca69d044913b60530e6d2e28a
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/gtest_prod_util.h"
11 #include "base/memory/scoped_ptr.h"
12 #include "base/memory/shared_memory.h"
13 #include "base/memory/weak_ptr.h"
14 #include "base/time/time.h"
15 #include "content/public/renderer/render_view_observer.h"
16 #include "content/public/renderer/render_view_observer_tracker.h"
17 #include "printing/metafile_impl.h"
18 #include "third_party/WebKit/public/platform/WebCanvas.h"
19 #include "third_party/WebKit/public/web/WebNode.h"
20 #include "third_party/WebKit/public/web/WebPrintParams.h"
21 #include "ui/gfx/size.h"
23 struct PrintMsg_Print_Params;
24 struct PrintMsg_PrintPage_Params;
25 struct PrintMsg_PrintPages_Params;
27 namespace base {
28 class DictionaryValue;
31 namespace blink {
32 class WebFrame;
33 class WebView;
36 namespace printing {
38 struct PageSizeMargins;
39 class PrepareFrameAndViewForPrint;
41 // Stores reference to frame using WebVew and unique name.
42 // Workaround to modal dialog issue on Linux. crbug.com/236147.
43 class FrameReference {
44 public:
45 explicit FrameReference(const blink::WebFrame* frame);
46 FrameReference();
47 ~FrameReference();
49 void Reset(const blink::WebFrame* frame);
51 blink::WebFrame* GetFrame();
52 blink::WebView* view();
54 private:
55 blink::WebView* view_;
56 blink::WebString frame_name_;
59 // PrintWebViewHelper handles most of the printing grunt work for RenderView.
60 // We plan on making print asynchronous and that will require copying the DOM
61 // of the document and creating a new WebView with the contents.
62 class PrintWebViewHelper
63 : public content::RenderViewObserver,
64 public content::RenderViewObserverTracker<PrintWebViewHelper> {
65 public:
66 explicit PrintWebViewHelper(content::RenderView* render_view);
67 virtual ~PrintWebViewHelper();
69 bool IsPrintingEnabled();
71 void PrintNode(const blink::WebNode& node);
73 private:
74 friend class PrintWebViewHelperTestBase;
75 FRIEND_TEST_ALL_PREFIXES(PrintWebViewHelperTest,
76 BlockScriptInitiatedPrinting);
77 FRIEND_TEST_ALL_PREFIXES(PrintWebViewHelperTest,
78 BlockScriptInitiatedPrintingFromPopup);
79 FRIEND_TEST_ALL_PREFIXES(PrintWebViewHelperTest, OnPrintPages);
81 #if defined(OS_WIN) || defined(OS_MACOSX)
82 FRIEND_TEST_ALL_PREFIXES(PrintWebViewHelperTest, PrintLayoutTest);
83 FRIEND_TEST_ALL_PREFIXES(PrintWebViewHelperTest, PrintWithIframe);
84 #endif // defined(OS_WIN) || defined(OS_MACOSX)
86 enum PrintingResult {
87 OK,
88 FAIL_PRINT_INIT,
89 FAIL_PRINT,
90 FAIL_PREVIEW,
93 enum PrintPreviewErrorBuckets {
94 PREVIEW_ERROR_NONE, // Always first.
95 PREVIEW_ERROR_BAD_SETTING,
96 PREVIEW_ERROR_METAFILE_COPY_FAILED,
97 PREVIEW_ERROR_METAFILE_INIT_FAILED,
98 PREVIEW_ERROR_ZERO_PAGES,
99 PREVIEW_ERROR_MAC_DRAFT_METAFILE_INIT_FAILED,
100 PREVIEW_ERROR_PAGE_RENDERED_WITHOUT_METAFILE,
101 PREVIEW_ERROR_UPDATING_PRINT_SETTINGS,
102 PREVIEW_ERROR_INVALID_PRINTER_SETTINGS,
103 PREVIEW_ERROR_LAST_ENUM // Always last.
106 enum PrintPreviewRequestType {
107 PRINT_PREVIEW_USER_INITIATED_ENTIRE_FRAME,
108 PRINT_PREVIEW_USER_INITIATED_SELECTION,
109 PRINT_PREVIEW_USER_INITIATED_CONTEXT_NODE,
110 PRINT_PREVIEW_SCRIPTED // triggered by window.print().
113 // RenderViewObserver implementation.
114 virtual bool OnMessageReceived(const IPC::Message& message) OVERRIDE;
115 virtual void PrintPage(blink::WebFrame* frame, bool user_initiated) OVERRIDE;
116 virtual void DidStartLoading() OVERRIDE;
117 virtual void DidStopLoading() OVERRIDE;
119 // Message handlers ---------------------------------------------------------
121 // Print the document.
122 void OnPrintPages();
124 // Print the document with the print preview frame/node.
125 void OnPrintForSystemDialog();
127 // Get |page_size| and |content_area| information from
128 // |page_layout_in_points|.
129 void GetPageSizeAndContentAreaFromPageLayout(
130 const PageSizeMargins& page_layout_in_points,
131 gfx::Size* page_size,
132 gfx::Rect* content_area);
134 // Update |ignore_css_margins_| based on settings.
135 void UpdateFrameMarginsCssInfo(const base::DictionaryValue& settings);
137 // Returns true if the current destination printer is PRINT_TO_PDF.
138 bool IsPrintToPdfRequested(const base::DictionaryValue& settings);
140 // Initiate print preview.
141 void OnInitiatePrintPreview(bool selection_only);
143 // Start the process of generating a print preview using |settings|.
144 void OnPrintPreview(const base::DictionaryValue& settings);
146 // Prepare frame for creating preview document.
147 void PrepareFrameForPreviewDocument();
149 // Continue creating preview document.
150 void OnFramePreparedForPreviewDocument();
152 // Initialize the print preview document.
153 bool CreatePreviewDocument();
155 // Renders a print preview page. |page_number| is 0-based.
156 // Returns true if print preview should continue, false on failure.
157 bool RenderPreviewPage(int page_number,
158 const PrintMsg_Print_Params& print_params);
160 // Finalize the print ready preview document.
161 bool FinalizePrintReadyDocument();
163 // Print / preview the node under the context menu.
164 void OnPrintNodeUnderContextMenu();
166 // Print the pages for print preview. Do not display the native print dialog
167 // for user settings. |job_settings| has new print job settings values.
168 void OnPrintForPrintPreview(const base::DictionaryValue& job_settings);
170 void OnPrintingDone(bool success);
172 // Enable/Disable window.print calls. If |blocked| is true window.print
173 // calls will silently fail. Call with |blocked| set to false to reenable.
174 void SetScriptedPrintBlocked(bool blocked);
176 // Main printing code -------------------------------------------------------
178 void Print(blink::WebFrame* frame, const blink::WebNode& node);
180 // Notification when printing is done - signal tear-down/free resources.
181 void DidFinishPrinting(PrintingResult result);
183 // Print Settings -----------------------------------------------------------
185 // Initialize print page settings with default settings.
186 // Used only for native printing workflow.
187 bool InitPrintSettings(bool fit_to_paper_size);
189 // Calculate number of pages in source document.
190 bool CalculateNumberOfPages(blink::WebFrame* frame,
191 const blink::WebNode& node,
192 int* number_of_pages);
194 // Update the current print settings with new |passed_job_settings|.
195 // |passed_job_settings| dictionary contains print job details such as printer
196 // name, number of copies, page range, etc.
197 bool UpdatePrintSettings(blink::WebFrame* frame,
198 const blink::WebNode& node,
199 const base::DictionaryValue& passed_job_settings);
201 // Get final print settings from the user.
202 // Return false if the user cancels or on error.
203 bool GetPrintSettingsFromUser(blink::WebFrame* frame,
204 const blink::WebNode& node,
205 int expected_pages_count);
207 // Page Printing / Rendering ------------------------------------------------
209 void OnFramePreparedForPrintPages();
210 void PrintPages();
211 bool PrintPagesNative(blink::WebFrame* frame,
212 int page_count,
213 const gfx::Size& canvas_size);
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 const gfx::Size& canvas_size,
220 blink::WebFrame* frame,
221 Metafile* metafile);
222 #else
223 void PrintPageInternal(const PrintMsg_PrintPage_Params& params,
224 const gfx::Size& canvas_size,
225 blink::WebFrame* frame);
226 #endif
228 // Render the frame for printing.
229 bool RenderPagesForPrint(blink::WebFrame* frame,
230 const blink::WebNode& node);
232 // Platform specific helper function for rendering page(s) to |metafile|.
233 #if defined(OS_WIN)
234 void RenderPage(const PrintMsg_Print_Params& params,
235 int page_number,
236 blink::WebFrame* frame,
237 bool is_preview,
238 Metafile* metafile,
239 double* scale_factor,
240 gfx::Size* page_size_in_dpi,
241 gfx::Rect* content_area_in_dpi);
242 #elif defined(OS_MACOSX)
243 void RenderPage(const PrintMsg_Print_Params& params,
244 int page_number,
245 blink::WebFrame* frame,
246 bool is_preview,
247 Metafile* metafile,
248 gfx::Size* page_size,
249 gfx::Rect* content_rect);
250 #endif // defined(OS_WIN)
252 // Renders page contents from |frame| to |content_area| of |canvas|.
253 // |page_number| is zero-based.
254 // When method is called, canvas should be setup to draw to |canvas_area|
255 // with |scale_factor|.
256 static float RenderPageContent(blink::WebFrame* frame,
257 int page_number,
258 const gfx::Rect& canvas_area,
259 const gfx::Rect& content_area,
260 double scale_factor,
261 blink::WebCanvas* canvas);
263 // Helper methods -----------------------------------------------------------
265 bool CopyMetafileDataToSharedMem(Metafile* metafile,
266 base::SharedMemoryHandle* shared_mem_handle);
268 // Helper method to get page layout in points and fit to page if needed.
269 static void ComputePageLayoutInPointsForCss(
270 blink::WebFrame* frame,
271 int page_index,
272 const PrintMsg_Print_Params& default_params,
273 bool ignore_css_margins,
274 double* scale_factor,
275 PageSizeMargins* page_layout_in_points);
277 // Given the |device| and |canvas| to draw on, prints the appropriate headers
278 // and footers using strings from |header_footer_info| on to the canvas.
279 static void PrintHeaderAndFooter(
280 blink::WebCanvas* canvas,
281 int page_number,
282 int total_pages,
283 float webkit_scale_factor,
284 const PageSizeMargins& page_layout_in_points,
285 const base::DictionaryValue& header_footer_info,
286 const PrintMsg_Print_Params& params);
288 bool GetPrintFrame(blink::WebFrame** frame);
290 // Script Initiated Printing ------------------------------------------------
292 // Return true if script initiated printing is currently
293 // allowed. |user_initiated| should be true when a user event triggered the
294 // script, most likely by pressing a print button on the page.
295 bool IsScriptInitiatedPrintAllowed(blink::WebFrame* frame,
296 bool user_initiated);
298 // Returns true if script initiated printing occurs too often.
299 bool IsScriptInitiatedPrintTooFrequent(blink::WebFrame* frame);
301 // Reset the counter for script initiated printing.
302 // Scripted printing will be allowed to continue.
303 void ResetScriptedPrintCount();
305 // Increment the counter for script initiated printing.
306 // Scripted printing will be blocked for a limited amount of time.
307 void IncrementScriptedPrintCount();
309 // Shows scripted print preview when options from plugin are availible.
310 void ShowScriptedPrintPreview();
312 void RequestPrintPreview(PrintPreviewRequestType type);
314 // Checks whether print preview should continue or not.
315 // Returns true if cancelling, false if continuing.
316 bool CheckForCancel();
318 // Notifies the browser a print preview page has been rendered.
319 // |page_number| is 0-based.
320 // For a valid |page_number| with modifiable content,
321 // |metafile| is the rendered page. Otherwise |metafile| is NULL.
322 // Returns true if print preview should continue, false on failure.
323 bool PreviewPageRendered(int page_number, Metafile* metafile);
325 // WebView used only to print the selection.
326 scoped_ptr<PrepareFrameAndViewForPrint> prep_frame_view_;
327 bool reset_prep_frame_view_;
329 scoped_ptr<PrintMsg_PrintPages_Params> print_pages_params_;
330 bool is_preview_enabled_;
331 bool is_scripted_print_throttling_disabled_;
332 bool is_print_ready_metafile_sent_;
333 bool ignore_css_margins_;
335 // Used for scripted initiated printing blocking.
336 base::Time last_cancelled_script_print_;
337 int user_cancelled_scripted_print_count_;
338 bool is_scripted_printing_blocked_;
340 // Let the browser process know of a printing failure. Only set to false when
341 // the failure came from the browser in the first place.
342 bool notify_browser_of_print_failure_;
344 // True, when printing from print preview.
345 bool print_for_preview_;
347 // Strings generated by the browser process to be printed as headers and
348 // footers if requested by the user.
349 scoped_ptr<base::DictionaryValue> header_footer_info_;
351 // Keeps track of the state of print preview between messages.
352 // TODO(vitalybuka): Create PrintPreviewContext when needed and delete after
353 // use. Now it's interaction with various messages is confusing.
354 class PrintPreviewContext {
355 public:
356 PrintPreviewContext();
357 ~PrintPreviewContext();
359 // Initializes the print preview context. Need to be called to set
360 // the |web_frame| / |web_node| to generate the print preview for.
361 void InitWithFrame(blink::WebFrame* web_frame);
362 void InitWithNode(const blink::WebNode& web_node);
364 // Does bookkeeping at the beginning of print preview.
365 void OnPrintPreview();
367 // Create the print preview document. |pages| is empty to print all pages.
368 // Takes ownership of |prepared_frame|.
369 bool CreatePreviewDocument(PrepareFrameAndViewForPrint* prepared_frame,
370 const std::vector<int>& pages);
372 // Called after a page gets rendered. |page_time| is how long the
373 // rendering took.
374 void RenderedPreviewPage(const base::TimeDelta& page_time);
376 // Updates the print preview context when the required pages are rendered.
377 void AllPagesRendered();
379 // Finalizes the print ready preview document.
380 void FinalizePrintReadyDocument();
382 // Cleanup after print preview finishes.
383 void Finished();
385 // Cleanup after print preview fails.
386 void Failed(bool report_error);
388 // Helper functions
389 int GetNextPageNumber();
390 bool IsRendering() const;
391 bool IsModifiable();
392 bool HasSelection();
393 bool IsLastPageOfPrintReadyMetafile() const;
394 bool IsFinalPageRendered() const;
396 // Setters
397 void set_generate_draft_pages(bool generate_draft_pages);
398 void set_error(enum PrintPreviewErrorBuckets error);
400 // Getters
401 // Original frame for which preview was requested.
402 blink::WebFrame* source_frame();
403 // Original node for which preview was requested.
404 const blink::WebNode& source_node() const;
406 // Frame to be use to render preview. May be the same as source_frame(), or
407 // generated from it, e.g. copy of selected block.
408 blink::WebFrame* prepared_frame();
409 // Node to be use to render preview. May be the same as source_node(), or
410 // generated from it, e.g. copy of selected block.
411 const blink::WebNode& prepared_node() const;
413 int total_page_count() const;
414 bool generate_draft_pages() const;
415 PreviewMetafile* metafile();
416 gfx::Size GetPrintCanvasSize() const;
417 int last_error() const;
419 private:
420 enum State {
421 UNINITIALIZED, // Not ready to render.
422 INITIALIZED, // Ready to render.
423 RENDERING, // Rendering.
424 DONE // Finished rendering.
427 // Reset some of the internal rendering context.
428 void ClearContext();
430 // Specifies what to render for print preview.
431 FrameReference source_frame_;
432 blink::WebNode source_node_;
434 scoped_ptr<PrepareFrameAndViewForPrint> prep_frame_view_;
435 scoped_ptr<PreviewMetafile> metafile_;
437 // Total page count in the renderer.
438 int total_page_count_;
440 // The current page to render.
441 int current_page_index_;
443 // List of page indices that need to be rendered.
444 std::vector<int> pages_to_render_;
446 // True, when draft pages needs to be generated.
447 bool generate_draft_pages_;
449 // Specifies the total number of pages in the print ready metafile.
450 int print_ready_metafile_page_count_;
452 base::TimeDelta document_render_time_;
453 base::TimeTicks begin_time_;
455 enum PrintPreviewErrorBuckets error_;
457 State state_;
460 bool print_node_in_progress_;
461 PrintPreviewContext print_preview_context_;
462 bool is_loading_;
463 bool is_scripted_preview_delayed_;
464 base::WeakPtrFactory<PrintWebViewHelper> weak_ptr_factory_;
465 DISALLOW_COPY_AND_ASSIGN(PrintWebViewHelper);
468 } // namespace printing
470 #endif // CHROME_RENDERER_PRINTING_PRINT_WEB_VIEW_HELPER_H_