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 #include "printing/emf_win.h"
7 #include "base/files/file.h"
8 #include "base/files/file_path.h"
9 #include "base/logging.h"
10 #include "base/memory/scoped_ptr.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 "skia/ext/platform_device.h"
15 #include "third_party/skia/include/core/SkBitmap.h"
16 #include "ui/gfx/codec/jpeg_codec.h"
17 #include "ui/gfx/codec/png_codec.h"
18 #include "ui/gfx/gdi_util.h"
19 #include "ui/gfx/geometry/rect.h"
20 #include "ui/gfx/geometry/size.h"
24 int CALLBACK
IsAlphaBlendUsedEnumProc(HDC
,
26 const ENHMETARECORD
*record
,
29 bool* result
= reinterpret_cast<bool*>(data
);
32 switch (record
->iType
) {
33 case EMR_ALPHABLEND
: {
42 int CALLBACK
RasterizeAlphaBlendProc(HDC metafile_dc
,
43 HANDLETABLE
* handle_table
,
44 const ENHMETARECORD
*record
,
47 HDC bitmap_dc
= *reinterpret_cast<HDC
*>(data
);
48 // Play this command to the bitmap DC.
49 ::PlayEnhMetaFileRecord(bitmap_dc
, handle_table
, record
, num_objects
);
50 switch (record
->iType
) {
51 case EMR_ALPHABLEND
: {
52 const EMRALPHABLEND
* alpha_blend
=
53 reinterpret_cast<const EMRALPHABLEND
*>(record
);
54 // Don't modify transformation here.
55 // Old implementation did reset transformations for DC to identity matrix.
56 // That was not correct and cause some bugs, like unexpected cropping.
57 // EMRALPHABLEND is rendered into bitmap and metafile contexts with
58 // current transformation. If we don't touch them here BitBlt will copy
71 case EMR_CREATEBRUSHINDIRECT
:
72 case EMR_CREATECOLORSPACE
:
73 case EMR_CREATECOLORSPACEW
:
74 case EMR_CREATEDIBPATTERNBRUSHPT
:
75 case EMR_CREATEMONOBRUSH
:
76 case EMR_CREATEPALETTE
:
78 case EMR_DELETECOLORSPACE
:
79 case EMR_DELETEOBJECT
:
80 case EMR_EXTCREATEFONTINDIRECTW
:
81 // Play object creation command only once.
85 // Play this command to the metafile DC.
86 ::PlayEnhMetaFileRecord(metafile_dc
, handle_table
, record
, num_objects
);
89 return 1; // Continue enumeration
92 // Bitmapt for rasterization.
95 explicit RasterBitmap(const gfx::Size
& raster_size
)
96 : saved_object_(NULL
) {
97 context_
.Set(::CreateCompatibleDC(NULL
));
98 if (!context_
.IsValid()) {
99 NOTREACHED() << "Bitmap DC creation failed";
102 ::SetGraphicsMode(context_
.Get(), GM_ADVANCED
);
104 gfx::Rect
bitmap_rect(raster_size
);
105 gfx::CreateBitmapHeader(raster_size
.width(), raster_size
.height(),
107 bitmap_
.Set(::CreateDIBSection(context_
.Get(), &header_
, DIB_RGB_COLORS
,
110 NOTREACHED() << "Raster bitmap creation for printing failed";
112 saved_object_
= ::SelectObject(context_
.Get(), bitmap_
);
113 RECT rect
= bitmap_rect
.ToRECT();
114 ::FillRect(context_
.Get(), &rect
,
115 static_cast<HBRUSH
>(::GetStockObject(WHITE_BRUSH
)));
120 ::SelectObject(context_
.Get(), saved_object_
);
123 HDC
context() const {
124 return context_
.Get();
127 base::win::ScopedCreateDC context_
;
129 base::win::ScopedBitmap bitmap_
;
130 HGDIOBJ saved_object_
;
133 DISALLOW_COPY_AND_ASSIGN(RasterBitmap
);
142 bool DIBFormatNativelySupported(HDC dc
, uint32 escape
, const BYTE
* bits
,
144 BOOL supported
= FALSE
;
145 if (ExtEscape(dc
, QUERYESCSUPPORT
, sizeof(escape
),
146 reinterpret_cast<LPCSTR
>(&escape
), 0, 0) > 0) {
147 ExtEscape(dc
, escape
, size
, reinterpret_cast<LPCSTR
>(bits
),
148 sizeof(supported
), reinterpret_cast<LPSTR
>(&supported
));
153 Emf::Emf() : emf_(NULL
), hdc_(NULL
) {
163 DeleteEnhMetaFile(emf_
);
167 bool Emf::InitToFile(const base::FilePath
& metafile_path
) {
168 DCHECK(!emf_
&& !hdc_
);
169 hdc_
= CreateEnhMetaFile(NULL
, metafile_path
.value().c_str(), NULL
, NULL
);
174 bool Emf::InitFromFile(const base::FilePath
& metafile_path
) {
175 DCHECK(!emf_
&& !hdc_
);
176 emf_
= GetEnhMetaFile(metafile_path
.value().c_str());
182 DCHECK(!emf_
&& !hdc_
);
183 hdc_
= CreateEnhMetaFile(NULL
, NULL
, NULL
, NULL
);
188 bool Emf::InitFromData(const void* src_buffer
, uint32 src_buffer_size
) {
189 DCHECK(!emf_
&& !hdc_
);
190 emf_
= SetEnhMetaFileBits(src_buffer_size
,
191 reinterpret_cast<const BYTE
*>(src_buffer
));
195 bool Emf::FinishDocument() {
196 DCHECK(!emf_
&& hdc_
);
197 emf_
= CloseEnhMetaFile(hdc_
);
203 bool Emf::Playback(HDC hdc
, const RECT
* rect
) const {
204 DCHECK(emf_
&& !hdc_
);
207 // Get the natural bounds of the EMF buffer.
208 bounds
= GetPageBounds(1).ToRECT();
211 return PlayEnhMetaFile(hdc
, emf_
, rect
) != 0;
214 bool Emf::SafePlayback(HDC context
) const {
215 DCHECK(emf_
&& !hdc_
);
217 if (!GetWorldTransform(context
, &base_matrix
)) {
221 Emf::EnumerationContext playback_context
;
222 playback_context
.base_matrix
= &base_matrix
;
223 gfx::Rect bound
= GetPageBounds(1);
224 RECT rect
= bound
.ToRECT();
225 return bound
.IsEmpty() ||
226 EnumEnhMetaFile(context
,
228 &Emf::SafePlaybackProc
,
229 reinterpret_cast<void*>(&playback_context
),
233 gfx::Rect
Emf::GetPageBounds(unsigned int page_number
) const {
234 DCHECK(emf_
&& !hdc_
);
235 DCHECK_EQ(1U, page_number
);
236 ENHMETAHEADER header
;
237 if (GetEnhMetaFileHeader(emf_
, sizeof(header
), &header
) != sizeof(header
)) {
241 // Add 1 to right and bottom because it's inclusive rectangle.
242 // See ENHMETAHEADER.
243 return gfx::Rect(header
.rclBounds
.left
,
244 header
.rclBounds
.top
,
245 header
.rclBounds
.right
- header
.rclBounds
.left
+ 1,
246 header
.rclBounds
.bottom
- header
.rclBounds
.top
+ 1);
249 unsigned int Emf::GetPageCount() const {
253 HDC
Emf::context() const {
257 uint32
Emf::GetDataSize() const {
258 DCHECK(emf_
&& !hdc_
);
259 return GetEnhMetaFileBits(emf_
, 0, NULL
);
262 bool Emf::GetData(void* buffer
, uint32 size
) const {
263 DCHECK(emf_
&& !hdc_
);
264 DCHECK(buffer
&& size
);
266 GetEnhMetaFileBits(emf_
, size
, reinterpret_cast<BYTE
*>(buffer
));
267 DCHECK(size2
== size
);
268 return size2
== size
&& size2
!= 0;
271 int CALLBACK
Emf::SafePlaybackProc(HDC hdc
,
272 HANDLETABLE
* handle_table
,
273 const ENHMETARECORD
* record
,
276 Emf::EnumerationContext
* context
=
277 reinterpret_cast<Emf::EnumerationContext
*>(param
);
278 context
->handle_table
= handle_table
;
279 context
->objects_count
= objects_count
;
281 Record
record_instance(record
);
282 bool success
= record_instance
.SafePlayback(context
);
287 Emf::EnumerationContext::EnumerationContext() {
288 memset(this, 0, sizeof(*this));
291 Emf::Record::Record(const ENHMETARECORD
* record
)
296 bool Emf::Record::Play(Emf::EnumerationContext
* context
) const {
297 return 0 != PlayEnhMetaFileRecord(context
->hdc
,
298 context
->handle_table
,
300 context
->objects_count
);
303 bool Emf::Record::SafePlayback(Emf::EnumerationContext
* context
) const {
304 // For EMF field description, see [MS-EMF] Enhanced Metafile Format
307 // This is the second major EMF breakage I get; the first one being
308 // SetDCBrushColor/SetDCPenColor/DC_PEN/DC_BRUSH being silently ignored.
310 // This function is the guts of the fix for bug 1186598. Some printer drivers
311 // somehow choke on certain EMF records, but calling the corresponding
312 // function directly on the printer HDC is fine. Still, playing the EMF record
315 // The main issue is that SetLayout is totally unsupported on these printers
316 // (HP 4500/4700). I used to call SetLayout and I stopped. I found out this is
317 // not sufficient because GDI32!PlayEnhMetaFile internally calls SetLayout(!)
320 // So I resorted to manually parse the EMF records and play them one by one.
321 // The issue with this method compared to using PlayEnhMetaFile to play back
322 // an EMF buffer is that the later silently fixes the matrix to take in
323 // account the matrix currently loaded at the time of the call.
324 // The matrix magic is done transparently when using PlayEnhMetaFile but since
325 // I'm processing one field at a time, I need to do the fixup myself. Note
326 // that PlayEnhMetaFileRecord doesn't fix the matrix correctly even when
327 // called inside an EnumEnhMetaFile loop. Go figure (bis).
329 // So when I see a EMR_SETWORLDTRANSFORM and EMR_MODIFYWORLDTRANSFORM, I need
330 // to fix the matrix according to the matrix previously loaded before playing
331 // back the buffer. Otherwise, the previously loaded matrix would be ignored
332 // and the EMF buffer would always be played back at its native resolution.
335 // I also use this opportunity to skip over eventual EMR_SETLAYOUT record that
338 // Another tweak we make is for JPEGs/PNGs in calls to StretchDIBits.
339 // (Our Pepper plugin code uses a JPEG). If the printer does not support
340 // JPEGs/PNGs natively we decompress the JPEG/PNG and then set it to the
342 // TODO(sanjeevr): We should also add JPEG/PNG support for SetSIBitsToDevice
344 // We also process any custom EMR_GDICOMMENT records which are our
345 // placeholders for StartPage and EndPage.
346 // Note: I should probably care about view ports and clipping, eventually.
348 const XFORM
* base_matrix
= context
->base_matrix
;
349 switch (record()->iType
) {
350 case EMR_STRETCHDIBITS
: {
351 const EMRSTRETCHDIBITS
* sdib_record
=
352 reinterpret_cast<const EMRSTRETCHDIBITS
*>(record());
353 const BYTE
* record_start
= reinterpret_cast<const BYTE
*>(record());
354 const BITMAPINFOHEADER
*bmih
=
355 reinterpret_cast<const BITMAPINFOHEADER
*>(record_start
+
356 sdib_record
->offBmiSrc
);
357 const BYTE
* bits
= record_start
+ sdib_record
->offBitsSrc
;
358 bool play_normally
= true;
360 HDC hdc
= context
->hdc
;
361 scoped_ptr
<SkBitmap
> bitmap
;
362 if (bmih
->biCompression
== BI_JPEG
) {
363 if (!DIBFormatNativelySupported(hdc
, CHECKJPEGFORMAT
, bits
,
364 bmih
->biSizeImage
)) {
365 play_normally
= false;
366 bitmap
.reset(gfx::JPEGCodec::Decode(bits
, bmih
->biSizeImage
));
368 } else if (bmih
->biCompression
== BI_PNG
) {
369 if (!DIBFormatNativelySupported(hdc
, CHECKPNGFORMAT
, bits
,
370 bmih
->biSizeImage
)) {
371 play_normally
= false;
372 bitmap
.reset(new SkBitmap());
373 gfx::PNGCodec::Decode(bits
, bmih
->biSizeImage
, bitmap
.get());
376 if (!play_normally
) {
377 DCHECK(bitmap
.get());
379 SkAutoLockPixels
lock(*bitmap
.get());
380 DCHECK_EQ(bitmap
->colorType(), kN32_SkColorType
);
381 const uint32_t* pixels
=
382 static_cast<const uint32_t*>(bitmap
->getPixels());
383 if (pixels
== NULL
) {
387 BITMAPINFOHEADER bmi
= {0};
388 gfx::CreateBitmapHeader(bitmap
->width(), bitmap
->height(), &bmi
);
389 res
= (0 != StretchDIBits(hdc
, sdib_record
->xDest
, sdib_record
->yDest
,
391 sdib_record
->cyDest
, sdib_record
->xSrc
,
393 sdib_record
->cxSrc
, sdib_record
->cySrc
,
395 reinterpret_cast<const BITMAPINFO
*>(&bmi
),
396 sdib_record
->iUsageSrc
,
397 sdib_record
->dwRop
));
404 case EMR_SETWORLDTRANSFORM
: {
405 DCHECK_EQ(record()->nSize
, sizeof(DWORD
) * 2 + sizeof(XFORM
));
406 const XFORM
* xform
= reinterpret_cast<const XFORM
*>(record()->dParm
);
407 HDC hdc
= context
->hdc
;
409 res
= 0 != SetWorldTransform(hdc
, base_matrix
) &&
410 ModifyWorldTransform(hdc
, xform
, MWT_LEFTMULTIPLY
);
412 res
= 0 != SetWorldTransform(hdc
, xform
);
416 case EMR_MODIFYWORLDTRANSFORM
: {
417 DCHECK_EQ(record()->nSize
,
418 sizeof(DWORD
) * 2 + sizeof(XFORM
) + sizeof(DWORD
));
419 const XFORM
* xform
= reinterpret_cast<const XFORM
*>(record()->dParm
);
420 const DWORD
* option
= reinterpret_cast<const DWORD
*>(xform
+ 1);
421 HDC hdc
= context
->hdc
;
425 res
= 0 != SetWorldTransform(hdc
, base_matrix
);
427 res
= 0 != ModifyWorldTransform(hdc
, xform
, MWT_IDENTITY
);
430 case MWT_LEFTMULTIPLY
:
431 case MWT_RIGHTMULTIPLY
:
432 res
= 0 != ModifyWorldTransform(hdc
, xform
, *option
);
436 res
= 0 != SetWorldTransform(hdc
, base_matrix
) &&
437 ModifyWorldTransform(hdc
, xform
, MWT_LEFTMULTIPLY
);
439 res
= 0 != SetWorldTransform(hdc
, xform
);
460 bool Emf::StartPage(const gfx::Size
& /*page_size*/,
461 const gfx::Rect
& /*content_area*/,
462 const float& /*scale_factor*/) {
466 bool Emf::FinishPage() {
470 Emf::Enumerator::Enumerator(const Emf
& emf
, HDC context
, const RECT
* rect
) {
472 if (!EnumEnhMetaFile(context
,
474 &Emf::Enumerator::EnhMetaFileProc
,
475 reinterpret_cast<void*>(this),
480 DCHECK_EQ(context_
.hdc
, context
);
483 Emf::Enumerator::~Enumerator() {
486 Emf::Enumerator::const_iterator
Emf::Enumerator::begin() const {
487 return items_
.begin();
490 Emf::Enumerator::const_iterator
Emf::Enumerator::end() const {
494 int CALLBACK
Emf::Enumerator::EnhMetaFileProc(HDC hdc
,
495 HANDLETABLE
* handle_table
,
496 const ENHMETARECORD
* record
,
499 Enumerator
& emf
= *reinterpret_cast<Enumerator
*>(param
);
500 if (!emf
.context_
.handle_table
) {
501 DCHECK(!emf
.context_
.handle_table
);
502 DCHECK(!emf
.context_
.objects_count
);
503 emf
.context_
.handle_table
= handle_table
;
504 emf
.context_
.objects_count
= objects_count
;
505 emf
.context_
.hdc
= hdc
;
507 DCHECK_EQ(emf
.context_
.handle_table
, handle_table
);
508 DCHECK_EQ(emf
.context_
.objects_count
, objects_count
);
509 DCHECK_EQ(emf
.context_
.hdc
, hdc
);
511 emf
.items_
.push_back(Record(record
));
515 bool Emf::IsAlphaBlendUsed() const {
517 ::EnumEnhMetaFile(NULL
,
519 &IsAlphaBlendUsedEnumProc
,
525 scoped_ptr
<Emf
> Emf::RasterizeMetafile(int raster_area_in_pixels
) const {
526 gfx::Rect page_bounds
= GetPageBounds(1);
527 gfx::Size
page_size(page_bounds
.size());
528 if (page_size
.GetArea() <= 0) {
529 NOTREACHED() << "Metafile is empty";
530 page_bounds
= gfx::Rect(1, 1);
533 float scale
= sqrt(float(raster_area_in_pixels
) / page_size
.GetArea());
534 page_size
.set_width(std::max
<int>(1, page_size
.width() * scale
));
535 page_size
.set_height(std::max
<int>(1, page_size
.height() * scale
));
538 RasterBitmap
bitmap(page_size
);
540 gfx::Rect
bitmap_rect(page_size
);
541 RECT rect
= bitmap_rect
.ToRECT();
542 Playback(bitmap
.context(), &rect
);
544 scoped_ptr
<Emf
> result(new Emf
);
546 HDC hdc
= result
->context();
548 skia::InitializeDC(hdc
);
550 // Params are ignored.
551 result
->StartPage(page_bounds
.size(), page_bounds
, 1);
553 ::ModifyWorldTransform(hdc
, NULL
, MWT_IDENTITY
);
555 float(page_bounds
.width()) / bitmap_rect
.width(), 0,
556 0, float(page_bounds
.height()) / bitmap_rect
.height(),
557 static_cast<float>(page_bounds
.x()),
558 static_cast<float>(page_bounds
.y()),
560 ::SetWorldTransform(hdc
, &xform
);
561 ::BitBlt(hdc
, 0, 0, bitmap_rect
.width(), bitmap_rect
.height(),
562 bitmap
.context(), bitmap_rect
.x(), bitmap_rect
.y(), SRCCOPY
);
564 result
->FinishPage();
565 result
->FinishDocument();
567 return result
.Pass();
570 scoped_ptr
<Emf
> Emf::RasterizeAlphaBlend() const {
571 gfx::Rect page_bounds
= GetPageBounds(1);
572 if (page_bounds
.size().GetArea() <= 0) {
573 NOTREACHED() << "Metafile is empty";
574 page_bounds
= gfx::Rect(1, 1);
577 RasterBitmap
bitmap(page_bounds
.size());
579 // Map metafile page_bounds.x(), page_bounds.y() to bitmap 0, 0.
584 static_cast<float>(-page_bounds
.x()),
585 static_cast<float>(-page_bounds
.y())};
586 ::SetWorldTransform(bitmap
.context(), &xform
);
588 scoped_ptr
<Emf
> result(new Emf
);
590 HDC hdc
= result
->context();
592 skia::InitializeDC(hdc
);
594 HDC bitmap_dc
= bitmap
.context();
595 RECT rect
= page_bounds
.ToRECT();
596 ::EnumEnhMetaFile(hdc
, emf(), &RasterizeAlphaBlendProc
, &bitmap_dc
, &rect
);
598 result
->FinishDocument();
600 return result
.Pass();
604 } // namespace printing