1 // Copyright (c) 2011 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 #include "chrome/renderer/print_web_view_helper.h"
7 #include "base/logging.h"
8 #include "base/memory/scoped_ptr.h"
9 #include "base/metrics/histogram.h"
10 #include "base/process_util.h"
11 #include "base/win/scoped_gdi_object.h"
12 #include "base/win/scoped_hdc.h"
13 #include "base/win/scoped_select_object.h"
14 #include "chrome/common/print_messages.h"
15 #include "printing/metafile.h"
16 #include "printing/metafile_impl.h"
17 #include "printing/metafile_skia_wrapper.h"
18 #include "printing/page_size_margins.h"
19 #include "printing/units.h"
20 #include "skia/ext/vector_canvas.h"
21 #include "skia/ext/platform_device.h"
22 #include "third_party/skia/include/core/SkRefCnt.h"
23 #include "third_party/WebKit/Source/WebKit/chromium/public/WebFrame.h"
24 #include "ui/gfx/gdi_util.h"
25 #include "ui/gfx/point.h"
26 #include "ui/gfx/rect.h"
27 #include "ui/gfx/size.h"
29 using printing::ConvertUnit
;
30 using printing::ConvertUnitDouble
;
31 using printing::kPointsPerInch
;
32 using printing::Metafile
;
33 using WebKit::WebFrame
;
37 int CALLBACK
EnhMetaFileProc(HDC dc
,
38 HANDLETABLE
* handle_table
,
39 const ENHMETARECORD
*record
,
42 HDC
* bitmap_dc
= reinterpret_cast<HDC
*>(data
);
43 // Play this command to the bitmap DC.
44 PlayEnhMetaFileRecord(*bitmap_dc
, handle_table
, record
, num_objects
);
45 switch (record
->iType
) {
46 case EMR_ALPHABLEND
: {
47 const EMRALPHABLEND
* emr_alpha_blend
=
48 reinterpret_cast<const EMRALPHABLEND
*>(record
);
49 XFORM bitmap_dc_transform
, metafile_dc_transform
;
50 XFORM identity
= { 1.0f
, 0.0f
, 0.0f
, 1.0f
, 0.0f
, 0.0f
};
51 // Temporarily set the world transforms of both DC's to identity.
52 GetWorldTransform(dc
, &metafile_dc_transform
);
53 SetWorldTransform(dc
, &identity
);
54 GetWorldTransform(*bitmap_dc
, &bitmap_dc_transform
);
55 SetWorldTransform(*bitmap_dc
, &identity
);
56 const RECTL
& rect
= emr_alpha_blend
->rclBounds
;
57 // Since the printer does not support alpha blend, copy the alpha
58 // blended region from our (software-rendered) bitmap DC to the
63 rect
.right
- rect
.left
+ 1,
64 rect
.bottom
- rect
.top
+ 1,
69 // Restore the world transforms of both DC's.
70 SetWorldTransform(dc
, &metafile_dc_transform
);
71 SetWorldTransform(*bitmap_dc
, &bitmap_dc_transform
);
75 case EMR_CREATEBRUSHINDIRECT
:
76 case EMR_CREATECOLORSPACE
:
77 case EMR_CREATECOLORSPACEW
:
78 case EMR_CREATEDIBPATTERNBRUSHPT
:
79 case EMR_CREATEMONOBRUSH
:
80 case EMR_CREATEPALETTE
:
82 case EMR_DELETECOLORSPACE
:
83 case EMR_DELETEOBJECT
:
84 case EMR_EXTCREATEFONTINDIRECTW
:
85 // Play object creation command only once.
89 // Play this command to the metafile DC.
90 PlayEnhMetaFileRecord(dc
, handle_table
, record
, num_objects
);
93 return 1; // Continue enumeration
98 void PrintWebViewHelper::PrintPageInternal(
99 const PrintMsg_PrintPage_Params
& params
,
100 const gfx::Size
& canvas_size
,
102 // Generate a memory-based metafile. It will use the current screen's DPI.
103 // Each metafile contains a single page.
104 scoped_ptr
<Metafile
> metafile(new printing::NativeMetafile
);
106 DCHECK(metafile
->context());
107 skia::InitializeDC(metafile
->context());
109 int page_number
= params
.page_number
;
111 // Calculate the dpi adjustment.
112 float scale_factor
= static_cast<float>(params
.params
.desired_dpi
/
115 // Render page for printing.
116 metafile
.reset(RenderPage(params
.params
, &scale_factor
, page_number
, false,
117 frame
, metafile
.get()));
119 // Close the device context to retrieve the compiled metafile.
120 if (!metafile
->FinishDocument())
123 // Get the size of the compiled metafile.
124 uint32 buf_size
= metafile
->GetDataSize();
125 DCHECK_GT(buf_size
, 128u);
127 PrintHostMsg_DidPrintPage_Params page_params
;
128 page_params
.data_size
= buf_size
;
129 page_params
.metafile_data_handle
= NULL
;
130 page_params
.page_number
= page_number
;
131 page_params
.document_cookie
= params
.params
.document_cookie
;
132 page_params
.actual_shrink
= scale_factor
;
133 page_params
.page_size
= params
.params
.page_size
;
134 page_params
.content_area
= gfx::Rect(params
.params
.margin_left
,
135 params
.params
.margin_top
, params
.params
.content_size
.width(),
136 params
.params
.content_size
.height());
138 if (!CopyMetafileDataToSharedMem(metafile
.get(),
139 &(page_params
.metafile_data_handle
))) {
140 page_params
.data_size
= 0;
143 Send(new PrintHostMsg_DidPrintPage(routing_id(), page_params
));
146 bool PrintWebViewHelper::RenderPreviewPage(int page_number
) {
147 PrintMsg_Print_Params print_params
= print_preview_context_
.print_params();
148 // Calculate the dpi adjustment.
149 float scale_factor
= static_cast<float>(print_params
.desired_dpi
/
151 scoped_ptr
<Metafile
> draft_metafile
;
152 printing::Metafile
* initial_render_metafile
=
153 print_preview_context_
.metafile();
155 if (print_preview_context_
.IsModifiable() && is_print_ready_metafile_sent_
) {
156 draft_metafile
.reset(new printing::PreviewMetafile
);
157 initial_render_metafile
= draft_metafile
.get();
160 base::TimeTicks begin_time
= base::TimeTicks::Now();
161 printing::Metafile
* render_page_result
=
162 RenderPage(print_params
, &scale_factor
, page_number
, true,
163 print_preview_context_
.frame(), initial_render_metafile
);
164 // In the preview flow, RenderPage will never return a new metafile.
165 DCHECK_EQ(render_page_result
, initial_render_metafile
);
166 print_preview_context_
.RenderedPreviewPage(
167 base::TimeTicks::Now() - begin_time
);
169 if (draft_metafile
.get()) {
170 draft_metafile
->FinishDocument();
171 } else if (print_preview_context_
.IsModifiable() &&
172 print_preview_context_
.generate_draft_pages()) {
173 DCHECK(!draft_metafile
.get());
174 draft_metafile
.reset(
175 print_preview_context_
.metafile()->GetMetafileForCurrentPage());
177 return PreviewPageRendered(page_number
, draft_metafile
.get());
180 Metafile
* PrintWebViewHelper::RenderPage(
181 const PrintMsg_Print_Params
& params
, float* scale_factor
, int page_number
,
182 bool is_preview
, WebFrame
* frame
, Metafile
* metafile
) {
183 printing::PageSizeMargins page_layout_in_points
;
184 GetPageSizeAndMarginsInPoints(frame
, page_number
, params
,
185 &page_layout_in_points
);
190 int dpi
= static_cast<int>(params
.dpi
);
191 int desired_dpi
= printing::kPointsPerInch
;
192 width
= ConvertUnit(params
.page_size
.width(), dpi
, desired_dpi
);
193 height
= ConvertUnit(params
.page_size
.height(), dpi
, desired_dpi
);
195 // Since WebKit extends the page width depending on the magical scale factor
196 // we make sure the canvas covers the worst case scenario (x2.0 currently).
197 // PrintContext will then set the correct clipping region.
198 width
= static_cast<int>(page_layout_in_points
.content_width
*
200 height
= static_cast<int>(page_layout_in_points
.content_height
*
204 gfx::Size
page_size(width
, height
);
205 gfx::Rect
content_area(
206 static_cast<int>(page_layout_in_points
.margin_left
),
207 static_cast<int>(page_layout_in_points
.margin_top
),
208 static_cast<int>(page_layout_in_points
.content_width
),
209 static_cast<int>(page_layout_in_points
.content_height
));
210 SkDevice
* device
= metafile
->StartPageForVectorCanvas(
211 page_size
, content_area
, frame
->getPrintPageShrink(page_number
));
213 // The printPage method may take a reference to the canvas we pass down, so it
214 // can't be a stack object.
215 SkRefPtr
<skia::VectorCanvas
> canvas
= new skia::VectorCanvas(device
);
216 canvas
->unref(); // SkRefPtr and new both took a reference.
218 printing::MetafileSkiaWrapper::SetMetafileOnCanvas(*canvas
, metafile
);
219 skia::SetIsDraftMode(*canvas
, is_print_ready_metafile_sent_
);
220 skia::SetIsPreviewMetafile(*canvas
, is_preview
);
223 float webkit_scale_factor
= frame
->printPage(page_number
, canvas
.get());
225 if (params
.display_header_footer
) {
226 // |page_number| is 0-based, so 1 is added.
227 PrintHeaderAndFooter(canvas
.get(), page_number
+ 1,
228 print_preview_context_
.total_page_count(),
229 webkit_scale_factor
, page_layout_in_points
,
230 *header_footer_info_
);
233 if (*scale_factor
<= 0 || webkit_scale_factor
<= 0) {
234 NOTREACHED() << "Printing page " << page_number
<< " failed.";
236 // Update the dpi adjustment with the "page |scale_factor|" calculated in
238 *scale_factor
/= webkit_scale_factor
;
241 bool result
= metafile
->FinishPage();
244 if (!params
.supports_alpha_blend
) {
245 // PreviewMetafile (PDF) supports alpha blend, so we only hit this case
246 // for NativeMetafile.
248 skia::PlatformDevice
* platform_device
= skia::GetPlatformDevice(device
);
249 if (platform_device
&& platform_device
->AlphaBlendUsed()) {
250 // Currently, we handle alpha blend transparency for a single page.
251 // Therefore, expecting a metafile with page count 1.
252 DCHECK_EQ(1U, metafile
->GetPageCount());
254 // Close the device context to retrieve the compiled metafile.
255 if (!metafile
->FinishDocument())
258 // Page used alpha blend, but printer doesn't support it. Rewrite the
259 // metafile and flatten out the transparency.
260 base::win::ScopedGetDC
screen_dc(NULL
);
261 base::win::ScopedCreateDC
bitmap_dc(CreateCompatibleDC(screen_dc
));
263 NOTREACHED() << "Bitmap DC creation failed";
264 SetGraphicsMode(bitmap_dc
, GM_ADVANCED
);
267 gfx::CreateBitmapHeader(width
, height
, &hdr
.bmiHeader
);
268 base::win::ScopedBitmap
hbitmap(CreateDIBSection(
269 bitmap_dc
, &hdr
, DIB_RGB_COLORS
, &bits
, NULL
, 0));
271 NOTREACHED() << "Raster bitmap creation for printing failed";
273 base::win::ScopedSelectObject
selectBitmap(bitmap_dc
, hbitmap
);
274 RECT rect
= {0, 0, width
, height
};
275 HBRUSH whiteBrush
= static_cast<HBRUSH
>(GetStockObject(WHITE_BRUSH
));
276 FillRect(bitmap_dc
, &rect
, whiteBrush
);
278 Metafile
* metafile2(new printing::NativeMetafile
);
280 HDC hdc
= metafile2
->context();
282 skia::InitializeDC(hdc
);
284 RECT metafile_bounds
= metafile
->GetPageBounds(1).ToRECT();
285 // Process the old metafile, placing all non-AlphaBlend calls into the
286 // new metafile, and copying the results of all the AlphaBlend calls
287 // from the bitmap DC.
299 bool PrintWebViewHelper::CopyMetafileDataToSharedMem(
300 Metafile
* metafile
, base::SharedMemoryHandle
* shared_mem_handle
) {
301 uint32 buf_size
= metafile
->GetDataSize();
302 base::SharedMemory shared_buf
;
303 // http://msdn2.microsoft.com/en-us/library/ms535522.aspx
304 // Windows 2000/XP: When a page in a spooled file exceeds approximately 350
305 // MB, it can fail to print and not send an error message.
306 if (buf_size
>= 350*1024*1024) {
307 NOTREACHED() << "Buffer too large: " << buf_size
;
311 // Allocate a shared memory buffer to hold the generated metafile data.
312 if (!shared_buf
.CreateAndMapAnonymous(buf_size
)) {
313 NOTREACHED() << "Buffer allocation failed";
317 // Copy the bits into shared memory.
318 if (!metafile
->GetData(shared_buf
.memory(), buf_size
)) {
319 NOTREACHED() << "GetData() failed";
323 shared_buf
.GiveToProcess(base::GetCurrentProcessHandle(), shared_mem_handle
);
326 Send(new PrintHostMsg_DuplicateSection(routing_id(), *shared_mem_handle
,