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"
12 #include "base/files/file.h"
13 #include "base/files/file_path.h"
14 #include "base/logging.h"
15 #include "base/macros.h"
16 #include "base/numerics/safe_conversions.h"
17 #include "skia/ext/skia_utils_win.h"
18 #include "third_party/skia/include/core/SkBitmap.h"
19 #include "ui/gfx/codec/jpeg_codec.h"
20 #include "ui/gfx/codec/png_codec.h"
21 #include "ui/gfx/geometry/rect.h"
22 #include "ui/gfx/geometry/size.h"
28 bool DIBFormatNativelySupported(HDC dc, uint32_t escape, const BYTE* bits,
30 BOOL supported = FALSE;
31 if (ExtEscape(dc, QUERYESCSUPPORT, sizeof(escape),
32 reinterpret_cast<LPCSTR>(&escape), 0, 0) > 0) {
33 ExtEscape(dc, escape, size, reinterpret_cast<LPCSTR>(bits),
34 sizeof(supported), reinterpret_cast<LPSTR>(&supported));
41 Emf::Emf() : emf_(nullptr), hdc_(nullptr) {}
50 DeleteEnhMetaFile(emf_);
54 bool Emf::InitToFile(const base::FilePath& metafile_path) {
55 DCHECK(!emf_ && !hdc_);
56 hdc_ = CreateEnhMetaFile(nullptr, metafile_path.value().c_str(), nullptr,
62 bool Emf::InitFromFile(const base::FilePath& metafile_path) {
63 DCHECK(!emf_ && !hdc_);
64 emf_ = GetEnhMetaFile(metafile_path.value().c_str());
70 DCHECK(!emf_ && !hdc_);
71 hdc_ = CreateEnhMetaFile(nullptr, nullptr, nullptr, nullptr);
76 bool Emf::InitFromData(const void* src_buffer, size_t src_buffer_size) {
77 DCHECK(!emf_ && !hdc_);
78 if (!base::IsValueInRangeForNumericType<UINT>(src_buffer_size))
81 emf_ = SetEnhMetaFileBits(static_cast<UINT>(src_buffer_size),
82 reinterpret_cast<const BYTE*>(src_buffer));
86 bool Emf::FinishDocument() {
87 DCHECK(!emf_ && hdc_);
88 emf_ = CloseEnhMetaFile(hdc_);
94 bool Emf::Playback(HDC hdc, const RECT* rect) const {
95 DCHECK(emf_ && !hdc_);
98 // Get the natural bounds of the EMF buffer.
99 bounds = GetPageBounds(1).ToRECT();
102 return PlayEnhMetaFile(hdc, emf_, rect) != 0;
105 bool Emf::SafePlayback(HDC context) const {
106 DCHECK(emf_ && !hdc_);
108 if (!GetWorldTransform(context, &base_matrix)) {
112 Emf::EnumerationContext playback_context;
113 playback_context.base_matrix = &base_matrix;
114 gfx::Rect bound = GetPageBounds(1);
115 RECT rect = bound.ToRECT();
116 return bound.IsEmpty() ||
117 EnumEnhMetaFile(context,
119 &Emf::SafePlaybackProc,
120 reinterpret_cast<void*>(&playback_context),
124 gfx::Rect Emf::GetPageBounds(unsigned int page_number) const {
125 DCHECK(emf_ && !hdc_);
126 DCHECK_EQ(1U, page_number);
127 ENHMETAHEADER header;
128 if (GetEnhMetaFileHeader(emf_, sizeof(header), &header) != sizeof(header)) {
132 // Add 1 to right and bottom because it's inclusive rectangle.
133 // See ENHMETAHEADER.
134 return gfx::Rect(header.rclBounds.left,
135 header.rclBounds.top,
136 header.rclBounds.right - header.rclBounds.left + 1,
137 header.rclBounds.bottom - header.rclBounds.top + 1);
140 unsigned int Emf::GetPageCount() const {
144 HDC Emf::context() const {
148 uint32_t Emf::GetDataSize() const {
149 DCHECK(emf_ && !hdc_);
150 return GetEnhMetaFileBits(emf_, 0, nullptr);
153 bool Emf::GetData(void* buffer, uint32_t size) const {
154 DCHECK(emf_ && !hdc_);
155 DCHECK(buffer && size);
157 GetEnhMetaFileBits(emf_, size, reinterpret_cast<BYTE*>(buffer));
158 DCHECK(size2 == size);
159 return size2 == size && size2 != 0;
162 int CALLBACK Emf::SafePlaybackProc(HDC hdc,
163 HANDLETABLE* handle_table,
164 const ENHMETARECORD* record,
167 Emf::EnumerationContext* context =
168 reinterpret_cast<Emf::EnumerationContext*>(param);
169 context->handle_table = handle_table;
170 context->objects_count = objects_count;
172 Record record_instance(record);
173 bool success = record_instance.SafePlayback(context);
178 Emf::EnumerationContext::EnumerationContext() {
179 memset(this, 0, sizeof(*this));
182 Emf::Record::Record(const ENHMETARECORD* record)
187 bool Emf::Record::Play(Emf::EnumerationContext* context) const {
188 return 0 != PlayEnhMetaFileRecord(context->hdc,
189 context->handle_table,
191 context->objects_count);
194 bool Emf::Record::SafePlayback(Emf::EnumerationContext* context) const {
195 // For EMF field description, see [MS-EMF] Enhanced Metafile Format
198 // This is the second major EMF breakage I get; the first one being
199 // SetDCBrushColor/SetDCPenColor/DC_PEN/DC_BRUSH being silently ignored.
201 // This function is the guts of the fix for bug 1186598. Some printer drivers
202 // somehow choke on certain EMF records, but calling the corresponding
203 // function directly on the printer HDC is fine. Still, playing the EMF record
206 // The main issue is that SetLayout is totally unsupported on these printers
207 // (HP 4500/4700). I used to call SetLayout and I stopped. I found out this is
208 // not sufficient because GDI32!PlayEnhMetaFile internally calls SetLayout(!)
211 // So I resorted to manually parse the EMF records and play them one by one.
212 // The issue with this method compared to using PlayEnhMetaFile to play back
213 // an EMF buffer is that the later silently fixes the matrix to take in
214 // account the matrix currently loaded at the time of the call.
215 // The matrix magic is done transparently when using PlayEnhMetaFile but since
216 // I'm processing one field at a time, I need to do the fixup myself. Note
217 // that PlayEnhMetaFileRecord doesn't fix the matrix correctly even when
218 // called inside an EnumEnhMetaFile loop. Go figure (bis).
220 // So when I see a EMR_SETWORLDTRANSFORM and EMR_MODIFYWORLDTRANSFORM, I need
221 // to fix the matrix according to the matrix previously loaded before playing
222 // back the buffer. Otherwise, the previously loaded matrix would be ignored
223 // and the EMF buffer would always be played back at its native resolution.
226 // I also use this opportunity to skip over eventual EMR_SETLAYOUT record that
229 // Another tweak we make is for JPEGs/PNGs in calls to StretchDIBits.
230 // (Our Pepper plugin code uses a JPEG). If the printer does not support
231 // JPEGs/PNGs natively we decompress the JPEG/PNG and then set it to the
233 // TODO(sanjeevr): We should also add JPEG/PNG support for SetSIBitsToDevice
235 // We also process any custom EMR_GDICOMMENT records which are our
236 // placeholders for StartPage and EndPage.
237 // Note: I should probably care about view ports and clipping, eventually.
239 const XFORM* base_matrix = context->base_matrix;
240 switch (record()->iType) {
241 case EMR_STRETCHDIBITS: {
242 const EMRSTRETCHDIBITS* sdib_record =
243 reinterpret_cast<const EMRSTRETCHDIBITS*>(record());
244 const BYTE* record_start = reinterpret_cast<const BYTE *>(record());
245 const BITMAPINFOHEADER* bmih = reinterpret_cast<const BITMAPINFOHEADER*>(
246 record_start + sdib_record->offBmiSrc);
247 const BYTE* bits = record_start + sdib_record->offBitsSrc;
248 bool play_normally = true;
250 HDC hdc = context->hdc;
251 std::unique_ptr<SkBitmap> bitmap;
252 if (bmih->biCompression == BI_JPEG) {
253 if (!DIBFormatNativelySupported(hdc, CHECKJPEGFORMAT, bits,
254 bmih->biSizeImage)) {
255 play_normally = false;
256 bitmap = gfx::JPEGCodec::Decode(bits, bmih->biSizeImage);
258 } else if (bmih->biCompression == BI_PNG) {
259 if (!DIBFormatNativelySupported(hdc, CHECKPNGFORMAT, bits,
260 bmih->biSizeImage)) {
261 play_normally = false;
262 bitmap = std::make_unique<SkBitmap>();
263 gfx::PNGCodec::Decode(bits, bmih->biSizeImage, bitmap.get());
269 DCHECK(bitmap.get());
271 DCHECK_EQ(bitmap->colorType(), kN32_SkColorType);
272 const uint32_t* pixels =
273 static_cast<const uint32_t*>(bitmap->getPixels());
278 BITMAPINFOHEADER bmi = {0};
279 skia::CreateBitmapHeader(bitmap->width(), bitmap->height(), &bmi);
280 res = (0 != StretchDIBits(hdc, sdib_record->xDest, sdib_record->yDest,
282 sdib_record->cyDest, sdib_record->xSrc,
284 sdib_record->cxSrc, sdib_record->cySrc,
286 reinterpret_cast<const BITMAPINFO *>(&bmi),
287 sdib_record->iUsageSrc,
288 sdib_record->dwRop));
293 case EMR_SETWORLDTRANSFORM: {
294 DCHECK_EQ(record()->nSize, sizeof(DWORD) * 2 + sizeof(XFORM));
295 const XFORM* xform = reinterpret_cast<const XFORM*>(record()->dParm);
296 HDC hdc = context->hdc;
298 res = 0 != SetWorldTransform(hdc, base_matrix) &&
299 ModifyWorldTransform(hdc, xform, MWT_LEFTMULTIPLY);
301 res = 0 != SetWorldTransform(hdc, xform);
305 case EMR_MODIFYWORLDTRANSFORM: {
306 DCHECK_EQ(record()->nSize,
307 sizeof(DWORD) * 2 + sizeof(XFORM) + sizeof(DWORD));
308 const XFORM* xform = reinterpret_cast<const XFORM*>(record()->dParm);
309 const DWORD* option = reinterpret_cast<const DWORD*>(xform + 1);
310 HDC hdc = context->hdc;
314 res = 0 != SetWorldTransform(hdc, base_matrix);
316 res = 0 != ModifyWorldTransform(hdc, xform, MWT_IDENTITY);
319 case MWT_LEFTMULTIPLY:
320 case MWT_RIGHTMULTIPLY:
321 res = 0 != ModifyWorldTransform(hdc, xform, *option);
325 res = 0 != SetWorldTransform(hdc, base_matrix) &&
326 ModifyWorldTransform(hdc, xform, MWT_LEFTMULTIPLY);
328 res = 0 != SetWorldTransform(hdc, xform);
349 void Emf::StartPage(const gfx::Size& /*page_size*/,
350 const gfx::Rect& /*content_area*/,
351 const float& /*scale_factor*/) {
354 bool Emf::FinishPage() {
358 Emf::Enumerator::Enumerator(const Emf& emf, HDC context, const RECT* rect) {
360 if (!EnumEnhMetaFile(context,
362 &Emf::Enumerator::EnhMetaFileProc,
363 reinterpret_cast<void*>(this),
368 DCHECK_EQ(context_.hdc, context);
371 Emf::Enumerator::~Enumerator() {
374 Emf::Enumerator::const_iterator Emf::Enumerator::begin() const {
375 return items_.begin();
378 Emf::Enumerator::const_iterator Emf::Enumerator::end() const {
382 int CALLBACK Emf::Enumerator::EnhMetaFileProc(HDC hdc,
383 HANDLETABLE* handle_table,
384 const ENHMETARECORD* record,
387 Enumerator& emf = *reinterpret_cast<Enumerator*>(param);
388 if (!emf.context_.handle_table) {
389 DCHECK(!emf.context_.handle_table);
390 DCHECK(!emf.context_.objects_count);
391 emf.context_.handle_table = handle_table;
392 emf.context_.objects_count = objects_count;
393 emf.context_.hdc = hdc;
395 DCHECK_EQ(emf.context_.handle_table, handle_table);
396 DCHECK_EQ(emf.context_.objects_count, objects_count);
397 DCHECK_EQ(emf.context_.hdc, hdc);
399 emf.items_.push_back(Record(record));
403 } // namespace printing