include: Assorted spelling fixes.
[wine] / dlls / gdi32 / enhmetafile.c
1 /*
2  * Enhanced metafile functions
3  * Copyright 1998 Douglas Ridgway
4  *           1999 Huw D M Davies
5  *
6  * This library is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU Lesser General Public
8  * License as published by the Free Software Foundation; either
9  * version 2.1 of the License, or (at your option) any later version.
10  *
11  * This library is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14  * Lesser General Public License for more details.
15  *
16  * You should have received a copy of the GNU Lesser General Public
17  * License along with this library; if not, write to the Free Software
18  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
19  *
20  * NOTES:
21  *
22  * The enhanced format consists of the following elements:
23  *
24  *    A header
25  *    A table of handles to GDI objects
26  *    An array of metafile records
27  *    A private palette
28  *
29  *
30  *  The standard format consists of a header and an array of metafile records.
31  *
32  */
33
34 #include "config.h"
35 #include "wine/port.h"
36
37 #include <stdarg.h>
38 #include <stdlib.h>
39 #include <string.h>
40 #include <assert.h>
41 #include "windef.h"
42 #include "winbase.h"
43 #include "wingdi.h"
44 #include "winnls.h"
45 #include "winerror.h"
46 #include "gdi_private.h"
47 #include "wine/debug.h"
48
49 WINE_DEFAULT_DEBUG_CHANNEL(enhmetafile);
50
51 typedef struct
52 {
53     ENHMETAHEADER  *emh;
54     BOOL           on_disk;   /* true if metafile is on disk */
55 } ENHMETAFILEOBJ;
56
57 static const struct emr_name {
58     DWORD type;
59     const char *name;
60 } emr_names[] = {
61 #define X(p) {p, #p}
62 X(EMR_HEADER),
63 X(EMR_POLYBEZIER),
64 X(EMR_POLYGON),
65 X(EMR_POLYLINE),
66 X(EMR_POLYBEZIERTO),
67 X(EMR_POLYLINETO),
68 X(EMR_POLYPOLYLINE),
69 X(EMR_POLYPOLYGON),
70 X(EMR_SETWINDOWEXTEX),
71 X(EMR_SETWINDOWORGEX),
72 X(EMR_SETVIEWPORTEXTEX),
73 X(EMR_SETVIEWPORTORGEX),
74 X(EMR_SETBRUSHORGEX),
75 X(EMR_EOF),
76 X(EMR_SETPIXELV),
77 X(EMR_SETMAPPERFLAGS),
78 X(EMR_SETMAPMODE),
79 X(EMR_SETBKMODE),
80 X(EMR_SETPOLYFILLMODE),
81 X(EMR_SETROP2),
82 X(EMR_SETSTRETCHBLTMODE),
83 X(EMR_SETTEXTALIGN),
84 X(EMR_SETCOLORADJUSTMENT),
85 X(EMR_SETTEXTCOLOR),
86 X(EMR_SETBKCOLOR),
87 X(EMR_OFFSETCLIPRGN),
88 X(EMR_MOVETOEX),
89 X(EMR_SETMETARGN),
90 X(EMR_EXCLUDECLIPRECT),
91 X(EMR_INTERSECTCLIPRECT),
92 X(EMR_SCALEVIEWPORTEXTEX),
93 X(EMR_SCALEWINDOWEXTEX),
94 X(EMR_SAVEDC),
95 X(EMR_RESTOREDC),
96 X(EMR_SETWORLDTRANSFORM),
97 X(EMR_MODIFYWORLDTRANSFORM),
98 X(EMR_SELECTOBJECT),
99 X(EMR_CREATEPEN),
100 X(EMR_CREATEBRUSHINDIRECT),
101 X(EMR_DELETEOBJECT),
102 X(EMR_ANGLEARC),
103 X(EMR_ELLIPSE),
104 X(EMR_RECTANGLE),
105 X(EMR_ROUNDRECT),
106 X(EMR_ARC),
107 X(EMR_CHORD),
108 X(EMR_PIE),
109 X(EMR_SELECTPALETTE),
110 X(EMR_CREATEPALETTE),
111 X(EMR_SETPALETTEENTRIES),
112 X(EMR_RESIZEPALETTE),
113 X(EMR_REALIZEPALETTE),
114 X(EMR_EXTFLOODFILL),
115 X(EMR_LINETO),
116 X(EMR_ARCTO),
117 X(EMR_POLYDRAW),
118 X(EMR_SETARCDIRECTION),
119 X(EMR_SETMITERLIMIT),
120 X(EMR_BEGINPATH),
121 X(EMR_ENDPATH),
122 X(EMR_CLOSEFIGURE),
123 X(EMR_FILLPATH),
124 X(EMR_STROKEANDFILLPATH),
125 X(EMR_STROKEPATH),
126 X(EMR_FLATTENPATH),
127 X(EMR_WIDENPATH),
128 X(EMR_SELECTCLIPPATH),
129 X(EMR_ABORTPATH),
130 X(EMR_GDICOMMENT),
131 X(EMR_FILLRGN),
132 X(EMR_FRAMERGN),
133 X(EMR_INVERTRGN),
134 X(EMR_PAINTRGN),
135 X(EMR_EXTSELECTCLIPRGN),
136 X(EMR_BITBLT),
137 X(EMR_STRETCHBLT),
138 X(EMR_MASKBLT),
139 X(EMR_PLGBLT),
140 X(EMR_SETDIBITSTODEVICE),
141 X(EMR_STRETCHDIBITS),
142 X(EMR_EXTCREATEFONTINDIRECTW),
143 X(EMR_EXTTEXTOUTA),
144 X(EMR_EXTTEXTOUTW),
145 X(EMR_POLYBEZIER16),
146 X(EMR_POLYGON16),
147 X(EMR_POLYLINE16),
148 X(EMR_POLYBEZIERTO16),
149 X(EMR_POLYLINETO16),
150 X(EMR_POLYPOLYLINE16),
151 X(EMR_POLYPOLYGON16),
152 X(EMR_POLYDRAW16),
153 X(EMR_CREATEMONOBRUSH),
154 X(EMR_CREATEDIBPATTERNBRUSHPT),
155 X(EMR_EXTCREATEPEN),
156 X(EMR_POLYTEXTOUTA),
157 X(EMR_POLYTEXTOUTW),
158 X(EMR_SETICMMODE),
159 X(EMR_CREATECOLORSPACE),
160 X(EMR_SETCOLORSPACE),
161 X(EMR_DELETECOLORSPACE),
162 X(EMR_GLSRECORD),
163 X(EMR_GLSBOUNDEDRECORD),
164 X(EMR_PIXELFORMAT),
165 X(EMR_DRAWESCAPE),
166 X(EMR_EXTESCAPE),
167 X(EMR_STARTDOC),
168 X(EMR_SMALLTEXTOUT),
169 X(EMR_FORCEUFIMAPPING),
170 X(EMR_NAMEDESCAPE),
171 X(EMR_COLORCORRECTPALETTE),
172 X(EMR_SETICMPROFILEA),
173 X(EMR_SETICMPROFILEW),
174 X(EMR_ALPHABLEND),
175 X(EMR_SETLAYOUT),
176 X(EMR_TRANSPARENTBLT),
177 X(EMR_RESERVED_117),
178 X(EMR_GRADIENTFILL),
179 X(EMR_SETLINKEDUFI),
180 X(EMR_SETTEXTJUSTIFICATION),
181 X(EMR_COLORMATCHTOTARGETW),
182 X(EMR_CREATECOLORSPACEW)
183 #undef X
184 };
185
186 /****************************************************************************
187  *         get_emr_name
188  */
189 static const char *get_emr_name(DWORD type)
190 {
191     unsigned int i;
192     for(i = 0; i < sizeof(emr_names) / sizeof(emr_names[0]); i++)
193         if(type == emr_names[i].type) return emr_names[i].name;
194     TRACE("Unknown record type %d\n", type);
195    return NULL;
196 }
197
198 /***********************************************************************
199  *          is_dib_monochrome
200  *
201  * Returns whether a DIB can be converted to a monochrome DDB.
202  *
203  * A DIB can be converted if its color table contains only black and
204  * white. Black must be the first color in the color table.
205  *
206  * Note : If the first color in the color table is white followed by
207  *        black, we can't convert it to a monochrome DDB with
208  *        SetDIBits, because black and white would be inverted.
209  */
210 static inline BOOL is_dib_monochrome( const BITMAPINFO* info )
211 {
212     if (info->bmiHeader.biBitCount != 1) return FALSE;
213
214     if (info->bmiHeader.biSize == sizeof(BITMAPCOREHEADER))
215     {
216         const RGBTRIPLE *rgb = ((const BITMAPCOREINFO *) info)->bmciColors;
217
218         /* Check if the first color is black */
219         if ((rgb->rgbtRed == 0) && (rgb->rgbtGreen == 0) && (rgb->rgbtBlue == 0))
220         {
221             rgb++;
222             /* Check if the second color is white */
223             return ((rgb->rgbtRed == 0xff) && (rgb->rgbtGreen == 0xff)
224                  && (rgb->rgbtBlue == 0xff));
225         }
226         else return FALSE;
227     }
228     else  /* assume BITMAPINFOHEADER */
229     {
230         const RGBQUAD *rgb = info->bmiColors;
231
232         /* Check if the first color is black */
233         if ((rgb->rgbRed == 0) && (rgb->rgbGreen == 0) &&
234             (rgb->rgbBlue == 0) && (rgb->rgbReserved == 0))
235         {
236             rgb++;
237
238             /* Check if the second color is white */
239             return ((rgb->rgbRed == 0xff) && (rgb->rgbGreen == 0xff)
240                  && (rgb->rgbBlue == 0xff) && (rgb->rgbReserved == 0));
241         }
242         else return FALSE;
243     }
244 }
245
246 /****************************************************************************
247  *          EMF_Create_HENHMETAFILE
248  */
249 HENHMETAFILE EMF_Create_HENHMETAFILE(ENHMETAHEADER *emh, BOOL on_disk )
250 {
251     HENHMETAFILE hmf;
252     ENHMETAFILEOBJ *metaObj;
253
254     if (emh->iType != EMR_HEADER)
255     {
256         SetLastError(ERROR_INVALID_DATA);
257         return 0;
258     }
259     if (emh->dSignature != ENHMETA_SIGNATURE ||
260         (emh->nBytes & 3)) /* refuse to load unaligned EMF as Windows does */
261     {
262         WARN("Invalid emf header type 0x%08x sig 0x%08x.\n",
263              emh->iType, emh->dSignature);
264         return 0;
265     }
266
267     if (!(metaObj = HeapAlloc( GetProcessHeap(), 0, sizeof(*metaObj) ))) return 0;
268
269     metaObj->emh = emh;
270     metaObj->on_disk = on_disk;
271
272     if (!(hmf = alloc_gdi_handle( metaObj, OBJ_ENHMETAFILE, NULL )))
273         HeapFree( GetProcessHeap(), 0, metaObj );
274     return hmf;
275 }
276
277 /****************************************************************************
278  *          EMF_Delete_HENHMETAFILE
279  */
280 static BOOL EMF_Delete_HENHMETAFILE( HENHMETAFILE hmf )
281 {
282     ENHMETAFILEOBJ *metaObj = free_gdi_handle( hmf );
283
284     if(!metaObj) return FALSE;
285
286     if(metaObj->on_disk)
287         UnmapViewOfFile( metaObj->emh );
288     else
289         HeapFree( GetProcessHeap(), 0, metaObj->emh );
290     return HeapFree( GetProcessHeap(), 0, metaObj );
291 }
292
293 /******************************************************************
294  *         EMF_GetEnhMetaHeader
295  *
296  * Returns ptr to ENHMETAHEADER associated with HENHMETAFILE
297  */
298 static ENHMETAHEADER *EMF_GetEnhMetaHeader( HENHMETAFILE hmf )
299 {
300     ENHMETAHEADER *ret = NULL;
301     ENHMETAFILEOBJ *metaObj = GDI_GetObjPtr( hmf, OBJ_ENHMETAFILE );
302     TRACE("hmf %p -> enhmetaObj %p\n", hmf, metaObj);
303     if (metaObj)
304     {
305         ret = metaObj->emh;
306         GDI_ReleaseObj( hmf );
307     }
308     return ret;
309 }
310
311 /*****************************************************************************
312  *         EMF_GetEnhMetaFile
313  *
314  */
315 static HENHMETAFILE EMF_GetEnhMetaFile( HANDLE hFile )
316 {
317     ENHMETAHEADER *emh;
318     HANDLE hMapping;
319     HENHMETAFILE hemf;
320
321     hMapping = CreateFileMappingA( hFile, NULL, PAGE_READONLY, 0, 0, NULL );
322     emh = MapViewOfFile( hMapping, FILE_MAP_READ, 0, 0, 0 );
323     CloseHandle( hMapping );
324
325     if (!emh) return 0;
326
327     hemf = EMF_Create_HENHMETAFILE( emh, TRUE );
328     if (!hemf)
329         UnmapViewOfFile( emh );
330     return hemf;
331 }
332
333
334 /*****************************************************************************
335  *          GetEnhMetaFileA (GDI32.@)
336  *
337  *
338  */
339 HENHMETAFILE WINAPI GetEnhMetaFileA(
340              LPCSTR lpszMetaFile  /* [in] filename of enhanced metafile */
341     )
342 {
343     HENHMETAFILE hmf;
344     HANDLE hFile;
345
346     hFile = CreateFileA(lpszMetaFile, GENERIC_READ, FILE_SHARE_READ, 0,
347                         OPEN_EXISTING, 0, 0);
348     if (hFile == INVALID_HANDLE_VALUE) {
349         WARN("could not open %s\n", lpszMetaFile);
350         return 0;
351     }
352     hmf = EMF_GetEnhMetaFile( hFile );
353     CloseHandle( hFile );
354     return hmf;
355 }
356
357 /*****************************************************************************
358  *          GetEnhMetaFileW  (GDI32.@)
359  */
360 HENHMETAFILE WINAPI GetEnhMetaFileW(
361              LPCWSTR lpszMetaFile)  /* [in] filename of enhanced metafile */
362 {
363     HENHMETAFILE hmf;
364     HANDLE hFile;
365
366     hFile = CreateFileW(lpszMetaFile, GENERIC_READ, FILE_SHARE_READ, 0,
367                         OPEN_EXISTING, 0, 0);
368     if (hFile == INVALID_HANDLE_VALUE) {
369         WARN("could not open %s\n", debugstr_w(lpszMetaFile));
370         return 0;
371     }
372     hmf = EMF_GetEnhMetaFile( hFile );
373     CloseHandle( hFile );
374     return hmf;
375 }
376
377 /*****************************************************************************
378  *        GetEnhMetaFileHeader  (GDI32.@)
379  *
380  * Retrieves the record containing the header for the specified
381  * enhanced-format metafile.
382  *
383  * RETURNS
384  *  If buf is NULL, returns the size of buffer required.
385  *  Otherwise, copy up to bufsize bytes of enhanced metafile header into
386  *  buf.
387  */
388 UINT WINAPI GetEnhMetaFileHeader(
389        HENHMETAFILE hmf,   /* [in] enhanced metafile */
390        UINT bufsize,       /* [in] size of buffer */
391        LPENHMETAHEADER buf /* [out] buffer */
392     )
393 {
394     LPENHMETAHEADER emh;
395     UINT size;
396
397     emh = EMF_GetEnhMetaHeader(hmf);
398     if(!emh) return FALSE;
399     size = emh->nSize;
400     if (!buf) return size;
401     size = min(size, bufsize);
402     memmove(buf, emh, size);
403     return size;
404 }
405
406
407 /*****************************************************************************
408  *          GetEnhMetaFileDescriptionA  (GDI32.@)
409  *
410  * See GetEnhMetaFileDescriptionW.
411  */
412 UINT WINAPI GetEnhMetaFileDescriptionA(
413        HENHMETAFILE hmf, /* [in] enhanced metafile */
414        UINT size,        /* [in] size of buf */
415        LPSTR buf         /* [out] buffer to receive description */
416     )
417 {
418      LPENHMETAHEADER emh = EMF_GetEnhMetaHeader(hmf);
419      DWORD len;
420      WCHAR *descrW;
421
422      if(!emh) return FALSE;
423      if(emh->nDescription == 0 || emh->offDescription == 0) return 0;
424      descrW = (WCHAR *) ((char *) emh + emh->offDescription);
425      len = WideCharToMultiByte( CP_ACP, 0, descrW, emh->nDescription, NULL, 0, NULL, NULL );
426
427      if (!buf || !size ) return len;
428
429      len = min( size, len );
430      WideCharToMultiByte( CP_ACP, 0, descrW, emh->nDescription, buf, len, NULL, NULL );
431      return len;
432 }
433
434 /*****************************************************************************
435  *          GetEnhMetaFileDescriptionW  (GDI32.@)
436  *
437  *  Copies the description string of an enhanced metafile into a buffer
438  *  _buf_.
439  *
440  * RETURNS
441  *  If _buf_ is NULL, returns size of _buf_ required. Otherwise, returns
442  *  number of characters copied.
443  */
444 UINT WINAPI GetEnhMetaFileDescriptionW(
445        HENHMETAFILE hmf, /* [in] enhanced metafile */
446        UINT size,        /* [in] size of buf */
447        LPWSTR buf        /* [out] buffer to receive description */
448     )
449 {
450      LPENHMETAHEADER emh = EMF_GetEnhMetaHeader(hmf);
451
452      if(!emh) return FALSE;
453      if(emh->nDescription == 0 || emh->offDescription == 0) return 0;
454      if (!buf || !size ) return emh->nDescription;
455
456      memmove(buf, (char *) emh + emh->offDescription, min(size,emh->nDescription)*sizeof(WCHAR));
457      return min(size, emh->nDescription);
458 }
459
460 /****************************************************************************
461  *    SetEnhMetaFileBits (GDI32.@)
462  *
463  *  Creates an enhanced metafile by copying _bufsize_ bytes from _buf_.
464  */
465 HENHMETAFILE WINAPI SetEnhMetaFileBits(UINT bufsize, const BYTE *buf)
466 {
467     ENHMETAHEADER *emh = HeapAlloc( GetProcessHeap(), 0, bufsize );
468     HENHMETAFILE hmf;
469     memmove(emh, buf, bufsize);
470     hmf = EMF_Create_HENHMETAFILE( emh, FALSE );
471     if (!hmf)
472         HeapFree( GetProcessHeap(), 0, emh );
473     return hmf;
474 }
475
476 /*****************************************************************************
477  *  GetEnhMetaFileBits (GDI32.@)
478  *
479  */
480 UINT WINAPI GetEnhMetaFileBits(
481     HENHMETAFILE hmf,
482     UINT bufsize,
483     LPBYTE buf
484 )
485 {
486     LPENHMETAHEADER emh = EMF_GetEnhMetaHeader( hmf );
487     UINT size;
488
489     if(!emh) return 0;
490
491     size = emh->nBytes;
492     if( buf == NULL ) return size;
493
494     size = min( size, bufsize );
495     memmove(buf, emh, size);
496     return size;
497 }
498
499 typedef struct EMF_dc_state
500 {
501     INT   mode;
502     XFORM world_transform;
503     INT   wndOrgX;
504     INT   wndOrgY;
505     INT   wndExtX;
506     INT   wndExtY;
507     INT   vportOrgX;
508     INT   vportOrgY;
509     INT   vportExtX;
510     INT   vportExtY;
511     struct EMF_dc_state *next;
512 } EMF_dc_state;
513
514 typedef struct enum_emh_data
515 {
516     XFORM init_transform;
517     EMF_dc_state state;
518     INT save_level;
519     EMF_dc_state *saved_state;
520 } enum_emh_data;
521
522 #define ENUM_GET_PRIVATE_DATA(ht) \
523     ((enum_emh_data*)(((unsigned char*)(ht))-sizeof (enum_emh_data)))
524
525 #define WIDTH(rect) ( (rect).right - (rect).left )
526 #define HEIGHT(rect) ( (rect).bottom - (rect).top )
527
528 #define IS_WIN9X() (GetVersion()&0x80000000)
529
530 static void EMF_Update_MF_Xform(HDC hdc, const enum_emh_data *info)
531 {
532     XFORM mapping_mode_trans, final_trans;
533     double scaleX, scaleY;
534
535     scaleX = (double)info->state.vportExtX / (double)info->state.wndExtX;
536     scaleY = (double)info->state.vportExtY / (double)info->state.wndExtY;
537     mapping_mode_trans.eM11 = scaleX;
538     mapping_mode_trans.eM12 = 0.0;
539     mapping_mode_trans.eM21 = 0.0;
540     mapping_mode_trans.eM22 = scaleY;
541     mapping_mode_trans.eDx  = (double)info->state.vportOrgX - scaleX * (double)info->state.wndOrgX;
542     mapping_mode_trans.eDy  = (double)info->state.vportOrgY - scaleY * (double)info->state.wndOrgY;
543
544     CombineTransform(&final_trans, &info->state.world_transform, &mapping_mode_trans);
545     CombineTransform(&final_trans, &final_trans, &info->init_transform);
546  
547     if (!SetWorldTransform(hdc, &final_trans))
548     {
549         ERR("World transform failed!\n");
550     }
551 }
552
553 static void EMF_RestoreDC( enum_emh_data *info, INT level )
554 {
555     if (abs(level) > info->save_level || level == 0) return;
556
557     if (level < 0) level = info->save_level + level + 1;
558
559     while (info->save_level >= level)
560     {
561         EMF_dc_state *state = info->saved_state;
562         info->saved_state = state->next;
563         state->next = NULL;
564         if (--info->save_level < level)
565             info->state = *state;
566         HeapFree( GetProcessHeap(), 0, state );
567     }
568 }
569
570 static void EMF_SaveDC( enum_emh_data *info )
571 {
572     EMF_dc_state *state = HeapAlloc( GetProcessHeap(), 0, sizeof(*state));
573     if (state)
574     {
575         *state = info->state;
576         state->next = info->saved_state;
577         info->saved_state = state;
578         info->save_level++;
579         TRACE("save_level %d\n", info->save_level);
580     }
581 }
582
583 static void EMF_SetMapMode(HDC hdc, enum_emh_data *info)
584 {
585     INT horzSize = GetDeviceCaps( hdc, HORZSIZE );
586     INT vertSize = GetDeviceCaps( hdc, VERTSIZE );
587     INT horzRes  = GetDeviceCaps( hdc, HORZRES );
588     INT vertRes  = GetDeviceCaps( hdc, VERTRES );
589
590     TRACE("%d\n", info->state.mode);
591
592     switch(info->state.mode)
593     {
594     case MM_TEXT:
595         info->state.wndExtX   = 1;
596         info->state.wndExtY   = 1;
597         info->state.vportExtX = 1;
598         info->state.vportExtY = 1;
599         break;
600     case MM_LOMETRIC:
601     case MM_ISOTROPIC:
602         info->state.wndExtX   = horzSize * 10;
603         info->state.wndExtY   = vertSize * 10;
604         info->state.vportExtX = horzRes;
605         info->state.vportExtY = -vertRes;
606         break;
607     case MM_HIMETRIC:
608         info->state.wndExtX   = horzSize * 100;
609         info->state.wndExtY   = vertSize * 100;
610         info->state.vportExtX = horzRes;
611         info->state.vportExtY = -vertRes;
612         break;
613     case MM_LOENGLISH:
614         info->state.wndExtX   = MulDiv(1000, horzSize, 254);
615         info->state.wndExtY   = MulDiv(1000, vertSize, 254);
616         info->state.vportExtX = horzRes;
617         info->state.vportExtY = -vertRes;
618         break;
619     case MM_HIENGLISH:
620         info->state.wndExtX   = MulDiv(10000, horzSize, 254);
621         info->state.wndExtY   = MulDiv(10000, vertSize, 254);
622         info->state.vportExtX = horzRes;
623         info->state.vportExtY = -vertRes;
624         break;
625     case MM_TWIPS:
626         info->state.wndExtX   = MulDiv(14400, horzSize, 254);
627         info->state.wndExtY   = MulDiv(14400, vertSize, 254);
628         info->state.vportExtX = horzRes;
629         info->state.vportExtY = -vertRes;
630         break;
631     case MM_ANISOTROPIC:
632         break;
633     default:
634         return;
635     }
636 }
637
638 /***********************************************************************
639  *           EMF_FixIsotropic
640  *
641  * Fix viewport extensions for isotropic mode.
642  */
643
644 static void EMF_FixIsotropic(HDC hdc, enum_emh_data *info)
645 {
646     double xdim = fabs((double)info->state.vportExtX * GetDeviceCaps( hdc, HORZSIZE ) /
647                   (GetDeviceCaps( hdc, HORZRES ) * info->state.wndExtX));
648     double ydim = fabs((double)info->state.vportExtY * GetDeviceCaps( hdc, VERTSIZE ) /
649                   (GetDeviceCaps( hdc, VERTRES ) * info->state.wndExtY));
650
651     if (xdim > ydim)
652     {
653         INT mincx = (info->state.vportExtX >= 0) ? 1 : -1;
654         info->state.vportExtX = floor(info->state.vportExtX * ydim / xdim + 0.5);
655         if (!info->state.vportExtX) info->state.vportExtX = mincx;
656     }
657     else
658     {
659         INT mincy = (info->state.vportExtY >= 0) ? 1 : -1;
660         info->state.vportExtY = floor(info->state.vportExtY * xdim / ydim + 0.5);
661         if (!info->state.vportExtY) info->state.vportExtY = mincy;
662     }
663 }
664
665 /*****************************************************************************
666  *       emr_produces_output
667  *
668  * Returns TRUE if the record type writes something to the dc.  Used by
669  * PlayEnhMetaFileRecord to determine whether it needs to update the
670  * dc's xform when in win9x mode.
671  *
672  * FIXME: need to test which records should be here.
673  */
674 static BOOL emr_produces_output(int type)
675 {
676     switch(type) {
677     case EMR_POLYBEZIER:
678     case EMR_POLYGON:
679     case EMR_POLYLINE:
680     case EMR_POLYBEZIERTO:
681     case EMR_POLYLINETO:
682     case EMR_POLYPOLYLINE:
683     case EMR_POLYPOLYGON:
684     case EMR_SETPIXELV:
685     case EMR_MOVETOEX:
686     case EMR_EXCLUDECLIPRECT:
687     case EMR_INTERSECTCLIPRECT:
688     case EMR_SELECTOBJECT:
689     case EMR_ANGLEARC:
690     case EMR_ELLIPSE:
691     case EMR_RECTANGLE:
692     case EMR_ROUNDRECT:
693     case EMR_ARC:
694     case EMR_CHORD:
695     case EMR_PIE:
696     case EMR_EXTFLOODFILL:
697     case EMR_LINETO:
698     case EMR_ARCTO:
699     case EMR_POLYDRAW:
700     case EMR_GDICOMMENT:
701     case EMR_FILLRGN:
702     case EMR_FRAMERGN:
703     case EMR_INVERTRGN:
704     case EMR_PAINTRGN:
705     case EMR_BITBLT:
706     case EMR_STRETCHBLT:
707     case EMR_MASKBLT:
708     case EMR_PLGBLT:
709     case EMR_SETDIBITSTODEVICE:
710     case EMR_STRETCHDIBITS:
711     case EMR_EXTTEXTOUTA:
712     case EMR_EXTTEXTOUTW:
713     case EMR_POLYBEZIER16:
714     case EMR_POLYGON16:
715     case EMR_POLYLINE16:
716     case EMR_POLYBEZIERTO16:
717     case EMR_POLYLINETO16:
718     case EMR_POLYPOLYLINE16:
719     case EMR_POLYPOLYGON16:
720     case EMR_POLYDRAW16:
721     case EMR_POLYTEXTOUTA:
722     case EMR_POLYTEXTOUTW:
723     case EMR_SMALLTEXTOUT:
724     case EMR_ALPHABLEND:
725     case EMR_TRANSPARENTBLT:
726         return TRUE;
727     default:
728         return FALSE;
729     }
730 }
731
732
733 /*****************************************************************************
734  *           PlayEnhMetaFileRecord  (GDI32.@)
735  *
736  *  Render a single enhanced metafile record in the device context hdc.
737  *
738  *  RETURNS
739  *    TRUE (non zero) on success, FALSE on error.
740  *  BUGS
741  *    Many unimplemented records.
742  *    No error handling on record play failures (ie checking return codes)
743  *
744  * NOTES
745  *    WinNT actually updates the current world transform in this function
746  *     whereas Win9x does not.
747  */
748 BOOL WINAPI PlayEnhMetaFileRecord(
749      HDC hdc,                   /* [in] device context in which to render EMF record */
750      LPHANDLETABLE handletable, /* [in] array of handles to be used in rendering record */
751      const ENHMETARECORD *mr,   /* [in] EMF record to render */
752      UINT handles               /* [in] size of handle array */
753      )
754 {
755   int type;
756   RECT tmprc;
757   enum_emh_data *info = ENUM_GET_PRIVATE_DATA(handletable);
758
759   TRACE("hdc = %p, handletable = %p, record = %p, numHandles = %d\n",
760         hdc, handletable, mr, handles);
761   if (!mr) return FALSE;
762
763   type = mr->iType;
764
765   TRACE("record %s\n", get_emr_name(type));
766   switch(type)
767     {
768     case EMR_HEADER:
769       break;
770     case EMR_EOF:
771       break;
772     case EMR_GDICOMMENT:
773       {
774         const EMRGDICOMMENT *lpGdiComment = (const EMRGDICOMMENT *)mr;
775         /* In an enhanced metafile, there can be both public and private GDI comments */
776         GdiComment( hdc, lpGdiComment->cbData, lpGdiComment->Data );
777         break;
778       }
779     case EMR_SETMAPMODE:
780       {
781         const EMRSETMAPMODE *pSetMapMode = (const EMRSETMAPMODE *)mr;
782
783         if (info->state.mode == pSetMapMode->iMode &&
784             (info->state.mode == MM_ISOTROPIC || info->state.mode == MM_ANISOTROPIC))
785             break;
786         info->state.mode = pSetMapMode->iMode;
787         EMF_SetMapMode(hdc, info);
788         break;
789       }
790     case EMR_SETBKMODE:
791       {
792         const EMRSETBKMODE *pSetBkMode = (const EMRSETBKMODE *)mr;
793         SetBkMode(hdc, pSetBkMode->iMode);
794         break;
795       }
796     case EMR_SETBKCOLOR:
797       {
798         const EMRSETBKCOLOR *pSetBkColor = (const EMRSETBKCOLOR *)mr;
799         SetBkColor(hdc, pSetBkColor->crColor);
800         break;
801       }
802     case EMR_SETPOLYFILLMODE:
803       {
804         const EMRSETPOLYFILLMODE *pSetPolyFillMode = (const EMRSETPOLYFILLMODE *)mr;
805         SetPolyFillMode(hdc, pSetPolyFillMode->iMode);
806         break;
807       }
808     case EMR_SETROP2:
809       {
810         const EMRSETROP2 *pSetROP2 = (const EMRSETROP2 *)mr;
811         SetROP2(hdc, pSetROP2->iMode);
812         break;
813       }
814     case EMR_SETSTRETCHBLTMODE:
815       {
816         const EMRSETSTRETCHBLTMODE *pSetStretchBltMode = (const EMRSETSTRETCHBLTMODE *)mr;
817         SetStretchBltMode(hdc, pSetStretchBltMode->iMode);
818         break;
819       }
820     case EMR_SETTEXTALIGN:
821       {
822         const EMRSETTEXTALIGN *pSetTextAlign = (const EMRSETTEXTALIGN *)mr;
823         SetTextAlign(hdc, pSetTextAlign->iMode);
824         break;
825       }
826     case EMR_SETTEXTCOLOR:
827       {
828         const EMRSETTEXTCOLOR *pSetTextColor = (const EMRSETTEXTCOLOR *)mr;
829         SetTextColor(hdc, pSetTextColor->crColor);
830         break;
831       }
832     case EMR_SAVEDC:
833       {
834         if (SaveDC( hdc ))
835             EMF_SaveDC( info );
836         break;
837       }
838     case EMR_RESTOREDC:
839       {
840         const EMRRESTOREDC *pRestoreDC = (const EMRRESTOREDC *)mr;
841         TRACE("EMR_RESTORE: %d\n", pRestoreDC->iRelative);
842         if (RestoreDC( hdc, pRestoreDC->iRelative ))
843             EMF_RestoreDC( info, pRestoreDC->iRelative );
844         break;
845       }
846     case EMR_INTERSECTCLIPRECT:
847       {
848         const EMRINTERSECTCLIPRECT *pClipRect = (const EMRINTERSECTCLIPRECT *)mr;
849         TRACE("EMR_INTERSECTCLIPRECT: rect %d,%d - %d, %d\n",
850               pClipRect->rclClip.left, pClipRect->rclClip.top,
851               pClipRect->rclClip.right, pClipRect->rclClip.bottom);
852         IntersectClipRect(hdc, pClipRect->rclClip.left, pClipRect->rclClip.top,
853                           pClipRect->rclClip.right, pClipRect->rclClip.bottom);
854         break;
855       }
856     case EMR_SELECTOBJECT:
857       {
858         const EMRSELECTOBJECT *pSelectObject = (const EMRSELECTOBJECT *)mr;
859         if( pSelectObject->ihObject & 0x80000000 ) {
860           /* High order bit is set - it's a stock object
861            * Strip the high bit to get the index.
862            * See MSDN article Q142319
863            */
864           SelectObject( hdc, GetStockObject( pSelectObject->ihObject &
865                                              0x7fffffff ) );
866         } else {
867           /* High order bit wasn't set - not a stock object
868            */
869               SelectObject( hdc,
870                         (handletable->objectHandle)[pSelectObject->ihObject] );
871         }
872         break;
873       }
874     case EMR_DELETEOBJECT:
875       {
876         const EMRDELETEOBJECT *pDeleteObject = (const EMRDELETEOBJECT *)mr;
877         DeleteObject( (handletable->objectHandle)[pDeleteObject->ihObject]);
878         (handletable->objectHandle)[pDeleteObject->ihObject] = 0;
879         break;
880       }
881     case EMR_SETWINDOWORGEX:
882       {
883         const EMRSETWINDOWORGEX *pSetWindowOrgEx = (const EMRSETWINDOWORGEX *)mr;
884
885         info->state.wndOrgX = pSetWindowOrgEx->ptlOrigin.x;
886         info->state.wndOrgY = pSetWindowOrgEx->ptlOrigin.y;
887
888         TRACE("SetWindowOrgEx: %d,%d\n", info->state.wndOrgX, info->state.wndOrgY);
889         break;
890       }
891     case EMR_SETWINDOWEXTEX:
892       {
893         const EMRSETWINDOWEXTEX *pSetWindowExtEx = (const EMRSETWINDOWEXTEX *)mr;
894         
895         if (info->state.mode != MM_ISOTROPIC && info->state.mode != MM_ANISOTROPIC)
896             break;
897         info->state.wndExtX = pSetWindowExtEx->szlExtent.cx;
898         info->state.wndExtY = pSetWindowExtEx->szlExtent.cy;
899         if (info->state.mode == MM_ISOTROPIC)
900             EMF_FixIsotropic(hdc, info);
901
902         TRACE("SetWindowExtEx: %d,%d\n",info->state.wndExtX, info->state.wndExtY);
903         break;
904       }
905     case EMR_SETVIEWPORTORGEX:
906       {
907         const EMRSETVIEWPORTORGEX *pSetViewportOrgEx = (const EMRSETVIEWPORTORGEX *)mr;
908
909         info->state.vportOrgX = pSetViewportOrgEx->ptlOrigin.x;
910         info->state.vportOrgY = pSetViewportOrgEx->ptlOrigin.y;
911         TRACE("SetViewportOrgEx: %d,%d\n", info->state.vportOrgX, info->state.vportOrgY);
912         break;
913       }
914     case EMR_SETVIEWPORTEXTEX:
915       {
916         const EMRSETVIEWPORTEXTEX *pSetViewportExtEx = (const EMRSETVIEWPORTEXTEX *)mr;
917
918         if (info->state.mode != MM_ISOTROPIC && info->state.mode != MM_ANISOTROPIC)
919             break;
920         info->state.vportExtX = pSetViewportExtEx->szlExtent.cx;
921         info->state.vportExtY = pSetViewportExtEx->szlExtent.cy;
922         if (info->state.mode == MM_ISOTROPIC)
923             EMF_FixIsotropic(hdc, info);
924         TRACE("SetViewportExtEx: %d,%d\n", info->state.vportExtX, info->state.vportExtY);
925         break;
926       }
927     case EMR_CREATEPEN:
928       {
929         const EMRCREATEPEN *pCreatePen = (const EMRCREATEPEN *)mr;
930         (handletable->objectHandle)[pCreatePen->ihPen] =
931           CreatePenIndirect(&pCreatePen->lopn);
932         break;
933       }
934     case EMR_EXTCREATEPEN:
935       {
936         const EMREXTCREATEPEN *pPen = (const EMREXTCREATEPEN *)mr;
937         LOGBRUSH lb;
938         lb.lbStyle = pPen->elp.elpBrushStyle;
939         lb.lbColor = pPen->elp.elpColor;
940         lb.lbHatch = pPen->elp.elpHatch;
941
942         if(pPen->offBmi || pPen->offBits)
943           FIXME("EMR_EXTCREATEPEN: Need to copy brush bitmap\n");
944
945         (handletable->objectHandle)[pPen->ihPen] =
946           ExtCreatePen(pPen->elp.elpPenStyle, pPen->elp.elpWidth, &lb,
947                        pPen->elp.elpNumEntries, pPen->elp.elpNumEntries ? pPen->elp.elpStyleEntry : NULL);
948         break;
949       }
950     case EMR_CREATEBRUSHINDIRECT:
951       {
952         const EMRCREATEBRUSHINDIRECT *pBrush = (const EMRCREATEBRUSHINDIRECT *)mr;
953         LOGBRUSH brush;
954         brush.lbStyle = pBrush->lb.lbStyle;
955         brush.lbColor = pBrush->lb.lbColor;
956         brush.lbHatch = pBrush->lb.lbHatch;
957         (handletable->objectHandle)[pBrush->ihBrush] = CreateBrushIndirect(&brush);
958         break;
959       }
960     case EMR_EXTCREATEFONTINDIRECTW:
961       {
962         const EMREXTCREATEFONTINDIRECTW *pFont = (const EMREXTCREATEFONTINDIRECTW *)mr;
963         (handletable->objectHandle)[pFont->ihFont] =
964           CreateFontIndirectW(&pFont->elfw.elfLogFont);
965         break;
966       }
967     case EMR_MOVETOEX:
968       {
969         const EMRMOVETOEX *pMoveToEx = (const EMRMOVETOEX *)mr;
970         MoveToEx(hdc, pMoveToEx->ptl.x, pMoveToEx->ptl.y, NULL);
971         break;
972       }
973     case EMR_LINETO:
974       {
975         const EMRLINETO *pLineTo = (const EMRLINETO *)mr;
976         LineTo(hdc, pLineTo->ptl.x, pLineTo->ptl.y);
977         break;
978       }
979     case EMR_RECTANGLE:
980       {
981         const EMRRECTANGLE *pRect = (const EMRRECTANGLE *)mr;
982         Rectangle(hdc, pRect->rclBox.left, pRect->rclBox.top,
983                   pRect->rclBox.right, pRect->rclBox.bottom);
984         break;
985       }
986     case EMR_ELLIPSE:
987       {
988         const EMRELLIPSE *pEllipse = (const EMRELLIPSE *)mr;
989         Ellipse(hdc, pEllipse->rclBox.left, pEllipse->rclBox.top,
990                 pEllipse->rclBox.right, pEllipse->rclBox.bottom);
991         break;
992       }
993     case EMR_POLYGON16:
994       {
995         const EMRPOLYGON16 *pPoly = (const EMRPOLYGON16 *)mr;
996         /* Shouldn't use Polygon16 since pPoly->cpts is DWORD */
997         POINT *pts = HeapAlloc( GetProcessHeap(), 0,
998                                 pPoly->cpts * sizeof(POINT) );
999         DWORD i;
1000         for(i = 0; i < pPoly->cpts; i++)
1001         {
1002             pts[i].x = pPoly->apts[i].x;
1003             pts[i].y = pPoly->apts[i].y;
1004         }
1005         Polygon(hdc, pts, pPoly->cpts);
1006         HeapFree( GetProcessHeap(), 0, pts );
1007         break;
1008       }
1009     case EMR_POLYLINE16:
1010       {
1011         const EMRPOLYLINE16 *pPoly = (const EMRPOLYLINE16 *)mr;
1012         /* Shouldn't use Polyline16 since pPoly->cpts is DWORD */
1013         POINT *pts = HeapAlloc( GetProcessHeap(), 0,
1014                                 pPoly->cpts * sizeof(POINT) );
1015         DWORD i;
1016         for(i = 0; i < pPoly->cpts; i++)
1017         {
1018             pts[i].x = pPoly->apts[i].x;
1019             pts[i].y = pPoly->apts[i].y;
1020         }
1021         Polyline(hdc, pts, pPoly->cpts);
1022         HeapFree( GetProcessHeap(), 0, pts );
1023         break;
1024       }
1025     case EMR_POLYLINETO16:
1026       {
1027         const EMRPOLYLINETO16 *pPoly = (const EMRPOLYLINETO16 *)mr;
1028         /* Shouldn't use PolylineTo16 since pPoly->cpts is DWORD */
1029         POINT *pts = HeapAlloc( GetProcessHeap(), 0,
1030                                 pPoly->cpts * sizeof(POINT) );
1031         DWORD i;
1032         for(i = 0; i < pPoly->cpts; i++)
1033         {
1034             pts[i].x = pPoly->apts[i].x;
1035             pts[i].y = pPoly->apts[i].y;
1036         }
1037         PolylineTo(hdc, pts, pPoly->cpts);
1038         HeapFree( GetProcessHeap(), 0, pts );
1039         break;
1040       }
1041     case EMR_POLYBEZIER16:
1042       {
1043         const EMRPOLYBEZIER16 *pPoly = (const EMRPOLYBEZIER16 *)mr;
1044         /* Shouldn't use PolyBezier16 since pPoly->cpts is DWORD */
1045         POINT *pts = HeapAlloc( GetProcessHeap(), 0,
1046                                 pPoly->cpts * sizeof(POINT) );
1047         DWORD i;
1048         for(i = 0; i < pPoly->cpts; i++)
1049         {
1050             pts[i].x = pPoly->apts[i].x;
1051             pts[i].y = pPoly->apts[i].y;
1052         }
1053         PolyBezier(hdc, pts, pPoly->cpts);
1054         HeapFree( GetProcessHeap(), 0, pts );
1055         break;
1056       }
1057     case EMR_POLYBEZIERTO16:
1058       {
1059         const EMRPOLYBEZIERTO16 *pPoly = (const EMRPOLYBEZIERTO16 *)mr;
1060         /* Shouldn't use PolyBezierTo16 since pPoly->cpts is DWORD */
1061         POINT *pts = HeapAlloc( GetProcessHeap(), 0,
1062                                 pPoly->cpts * sizeof(POINT) );
1063         DWORD i;
1064         for(i = 0; i < pPoly->cpts; i++)
1065         {
1066             pts[i].x = pPoly->apts[i].x;
1067             pts[i].y = pPoly->apts[i].y;
1068         }
1069         PolyBezierTo(hdc, pts, pPoly->cpts);
1070         HeapFree( GetProcessHeap(), 0, pts );
1071         break;
1072       }
1073     case EMR_POLYPOLYGON16:
1074       {
1075         const EMRPOLYPOLYGON16 *pPolyPoly = (const EMRPOLYPOLYGON16 *)mr;
1076         /* NB POINTS array doesn't start at pPolyPoly->apts it's actually
1077            pPolyPoly->aPolyCounts + pPolyPoly->nPolys */
1078
1079         const POINTS *pts = (const POINTS *)(pPolyPoly->aPolyCounts + pPolyPoly->nPolys);
1080         POINT *pt = HeapAlloc( GetProcessHeap(), 0, pPolyPoly->cpts * sizeof(POINT) );
1081         DWORD i;
1082         for(i = 0; i < pPolyPoly->cpts; i++)
1083         {
1084             pt[i].x = pts[i].x;
1085             pt[i].y = pts[i].y;
1086         }
1087         PolyPolygon(hdc, pt, (const INT*)pPolyPoly->aPolyCounts, pPolyPoly->nPolys);
1088         HeapFree( GetProcessHeap(), 0, pt );
1089         break;
1090       }
1091     case EMR_POLYPOLYLINE16:
1092       {
1093         const EMRPOLYPOLYLINE16 *pPolyPoly = (const EMRPOLYPOLYLINE16 *)mr;
1094         /* NB POINTS array doesn't start at pPolyPoly->apts it's actually
1095            pPolyPoly->aPolyCounts + pPolyPoly->nPolys */
1096
1097         const POINTS *pts = (const POINTS *)(pPolyPoly->aPolyCounts + pPolyPoly->nPolys);
1098         POINT *pt = HeapAlloc( GetProcessHeap(), 0, pPolyPoly->cpts * sizeof(POINT) );
1099         DWORD i;
1100         for(i = 0; i < pPolyPoly->cpts; i++)
1101         {
1102             pt[i].x = pts[i].x;
1103             pt[i].y = pts[i].y;
1104         }
1105         PolyPolyline(hdc, pt, pPolyPoly->aPolyCounts, pPolyPoly->nPolys);
1106         HeapFree( GetProcessHeap(), 0, pt );
1107         break;
1108       }
1109
1110     case EMR_STRETCHDIBITS:
1111       {
1112         const EMRSTRETCHDIBITS *pStretchDIBits = (const EMRSTRETCHDIBITS *)mr;
1113
1114         StretchDIBits(hdc,
1115                       pStretchDIBits->xDest,
1116                       pStretchDIBits->yDest,
1117                       pStretchDIBits->cxDest,
1118                       pStretchDIBits->cyDest,
1119                       pStretchDIBits->xSrc,
1120                       pStretchDIBits->ySrc,
1121                       pStretchDIBits->cxSrc,
1122                       pStretchDIBits->cySrc,
1123                       (const BYTE *)mr + pStretchDIBits->offBitsSrc,
1124                       (const BITMAPINFO *)((const BYTE *)mr + pStretchDIBits->offBmiSrc),
1125                       pStretchDIBits->iUsageSrc,
1126                       pStretchDIBits->dwRop);
1127         break;
1128       }
1129
1130     case EMR_EXTTEXTOUTA:
1131     {
1132         const EMREXTTEXTOUTA *pExtTextOutA = (const EMREXTTEXTOUTA *)mr;
1133         RECT rc;
1134         const INT *dx = NULL;
1135         int old_mode;
1136
1137         rc.left = pExtTextOutA->emrtext.rcl.left;
1138         rc.top = pExtTextOutA->emrtext.rcl.top;
1139         rc.right = pExtTextOutA->emrtext.rcl.right;
1140         rc.bottom = pExtTextOutA->emrtext.rcl.bottom;
1141         TRACE("EMR_EXTTEXTOUTA: x,y = %d, %d. rect = %d, %d - %d, %d. flags %08x\n",
1142               pExtTextOutA->emrtext.ptlReference.x, pExtTextOutA->emrtext.ptlReference.y,
1143               rc.left, rc.top, rc.right, rc.bottom, pExtTextOutA->emrtext.fOptions);
1144
1145         old_mode = SetGraphicsMode(hdc, pExtTextOutA->iGraphicsMode);
1146         /* Reselect the font back into the dc so that the transformation
1147            gets updated. */
1148         SelectObject(hdc, GetCurrentObject(hdc, OBJ_FONT));
1149
1150         /* Linux version of pstoedit produces EMFs with offDx set to 0.
1151          * These files can be enumerated and played under Win98 just
1152          * fine, but at least Win2k chokes on them.
1153          */
1154         if (pExtTextOutA->emrtext.offDx)
1155             dx = (const INT *)((const BYTE *)mr + pExtTextOutA->emrtext.offDx);
1156
1157         ExtTextOutA(hdc, pExtTextOutA->emrtext.ptlReference.x, pExtTextOutA->emrtext.ptlReference.y,
1158             pExtTextOutA->emrtext.fOptions, &rc,
1159             (LPCSTR)((const BYTE *)mr + pExtTextOutA->emrtext.offString), pExtTextOutA->emrtext.nChars,
1160             dx);
1161
1162         SetGraphicsMode(hdc, old_mode);
1163         break;
1164     }
1165
1166     case EMR_EXTTEXTOUTW:
1167     {
1168         const EMREXTTEXTOUTW *pExtTextOutW = (const EMREXTTEXTOUTW *)mr;
1169         RECT rc;
1170         const INT *dx = NULL;
1171         int old_mode;
1172
1173         rc.left = pExtTextOutW->emrtext.rcl.left;
1174         rc.top = pExtTextOutW->emrtext.rcl.top;
1175         rc.right = pExtTextOutW->emrtext.rcl.right;
1176         rc.bottom = pExtTextOutW->emrtext.rcl.bottom;
1177         TRACE("EMR_EXTTEXTOUTW: x,y = %d, %d.  rect = %d, %d - %d, %d. flags %08x\n",
1178               pExtTextOutW->emrtext.ptlReference.x, pExtTextOutW->emrtext.ptlReference.y,
1179               rc.left, rc.top, rc.right, rc.bottom, pExtTextOutW->emrtext.fOptions);
1180
1181         old_mode = SetGraphicsMode(hdc, pExtTextOutW->iGraphicsMode);
1182         /* Reselect the font back into the dc so that the transformation
1183            gets updated. */
1184         SelectObject(hdc, GetCurrentObject(hdc, OBJ_FONT));
1185
1186         /* Linux version of pstoedit produces EMFs with offDx set to 0.
1187          * These files can be enumerated and played under Win98 just
1188          * fine, but at least Win2k chokes on them.
1189          */
1190         if (pExtTextOutW->emrtext.offDx)
1191             dx = (const INT *)((const BYTE *)mr + pExtTextOutW->emrtext.offDx);
1192
1193         ExtTextOutW(hdc, pExtTextOutW->emrtext.ptlReference.x, pExtTextOutW->emrtext.ptlReference.y,
1194             pExtTextOutW->emrtext.fOptions, &rc,
1195             (LPCWSTR)((const BYTE *)mr + pExtTextOutW->emrtext.offString), pExtTextOutW->emrtext.nChars,
1196             dx);
1197
1198         SetGraphicsMode(hdc, old_mode);
1199         break;
1200     }
1201
1202     case EMR_CREATEPALETTE:
1203       {
1204         const EMRCREATEPALETTE *lpCreatePal = (const EMRCREATEPALETTE *)mr;
1205
1206         (handletable->objectHandle)[ lpCreatePal->ihPal ] =
1207                 CreatePalette( &lpCreatePal->lgpl );
1208
1209         break;
1210       }
1211
1212     case EMR_SELECTPALETTE:
1213       {
1214         const EMRSELECTPALETTE *lpSelectPal = (const EMRSELECTPALETTE *)mr;
1215
1216         if( lpSelectPal->ihPal & 0x80000000 ) {
1217                 SelectPalette( hdc, GetStockObject(lpSelectPal->ihPal & 0x7fffffff), TRUE);
1218         } else {
1219                 SelectPalette( hdc, (handletable->objectHandle)[lpSelectPal->ihPal], TRUE);
1220         }
1221         break;
1222       }
1223
1224     case EMR_REALIZEPALETTE:
1225       {
1226         RealizePalette( hdc );
1227         break;
1228       }
1229
1230     case EMR_EXTSELECTCLIPRGN:
1231       {
1232         const EMREXTSELECTCLIPRGN *lpRgn = (const EMREXTSELECTCLIPRGN *)mr;
1233         HRGN hRgn = 0;
1234
1235         if (mr->nSize >= sizeof(*lpRgn) + sizeof(RGNDATAHEADER))
1236             hRgn = ExtCreateRegion( &info->init_transform, 0, (const RGNDATA *)lpRgn->RgnData );
1237
1238         ExtSelectClipRgn(hdc, hRgn, (INT)(lpRgn->iMode));
1239         /* ExtSelectClipRgn created a copy of the region */
1240         DeleteObject(hRgn);
1241         break;
1242       }
1243
1244     case EMR_SETMETARGN:
1245       {
1246         SetMetaRgn( hdc );
1247         break;
1248       }
1249
1250     case EMR_SETWORLDTRANSFORM:
1251       {
1252         const EMRSETWORLDTRANSFORM *lpXfrm = (const EMRSETWORLDTRANSFORM *)mr;
1253         info->state.world_transform = lpXfrm->xform;
1254         break;
1255       }
1256
1257     case EMR_POLYBEZIER:
1258       {
1259         const EMRPOLYBEZIER *lpPolyBez = (const EMRPOLYBEZIER *)mr;
1260         PolyBezier(hdc, (const POINT*)lpPolyBez->aptl, (UINT)lpPolyBez->cptl);
1261         break;
1262       }
1263
1264     case EMR_POLYGON:
1265       {
1266         const EMRPOLYGON *lpPoly = (const EMRPOLYGON *)mr;
1267         Polygon( hdc, (const POINT*)lpPoly->aptl, (UINT)lpPoly->cptl );
1268         break;
1269       }
1270
1271     case EMR_POLYLINE:
1272       {
1273         const EMRPOLYLINE *lpPolyLine = (const EMRPOLYLINE *)mr;
1274         Polyline(hdc, (const POINT*)lpPolyLine->aptl, (UINT)lpPolyLine->cptl);
1275         break;
1276       }
1277
1278     case EMR_POLYBEZIERTO:
1279       {
1280         const EMRPOLYBEZIERTO *lpPolyBezierTo = (const EMRPOLYBEZIERTO *)mr;
1281         PolyBezierTo( hdc, (const POINT*)lpPolyBezierTo->aptl,
1282                       (UINT)lpPolyBezierTo->cptl );
1283         break;
1284       }
1285
1286     case EMR_POLYLINETO:
1287       {
1288         const EMRPOLYLINETO *lpPolyLineTo = (const EMRPOLYLINETO *)mr;
1289         PolylineTo( hdc, (const POINT*)lpPolyLineTo->aptl,
1290                     (UINT)lpPolyLineTo->cptl );
1291         break;
1292       }
1293
1294     case EMR_POLYPOLYLINE:
1295       {
1296         const EMRPOLYPOLYLINE *pPolyPolyline = (const EMRPOLYPOLYLINE *)mr;
1297         /* NB Points at pPolyPolyline->aPolyCounts + pPolyPolyline->nPolys */
1298
1299         PolyPolyline(hdc, (const POINT*)(pPolyPolyline->aPolyCounts +
1300                                     pPolyPolyline->nPolys),
1301                      pPolyPolyline->aPolyCounts,
1302                      pPolyPolyline->nPolys );
1303
1304         break;
1305       }
1306
1307     case EMR_POLYPOLYGON:
1308       {
1309         const EMRPOLYPOLYGON *pPolyPolygon = (const EMRPOLYPOLYGON *)mr;
1310
1311         /* NB Points at pPolyPolygon->aPolyCounts + pPolyPolygon->nPolys */
1312
1313         PolyPolygon(hdc, (const POINT*)(pPolyPolygon->aPolyCounts +
1314                                    pPolyPolygon->nPolys),
1315                     (const INT*)pPolyPolygon->aPolyCounts, pPolyPolygon->nPolys );
1316         break;
1317       }
1318
1319     case EMR_SETBRUSHORGEX:
1320       {
1321         const EMRSETBRUSHORGEX *lpSetBrushOrgEx = (const EMRSETBRUSHORGEX *)mr;
1322
1323         SetBrushOrgEx( hdc,
1324                        (INT)lpSetBrushOrgEx->ptlOrigin.x,
1325                        (INT)lpSetBrushOrgEx->ptlOrigin.y,
1326                        NULL );
1327
1328         break;
1329       }
1330
1331     case EMR_SETPIXELV:
1332       {
1333         const EMRSETPIXELV *lpSetPixelV = (const EMRSETPIXELV *)mr;
1334
1335         SetPixelV( hdc,
1336                    (INT)lpSetPixelV->ptlPixel.x,
1337                    (INT)lpSetPixelV->ptlPixel.y,
1338                    lpSetPixelV->crColor );
1339
1340         break;
1341       }
1342
1343     case EMR_SETMAPPERFLAGS:
1344       {
1345         const EMRSETMAPPERFLAGS *lpSetMapperFlags = (const EMRSETMAPPERFLAGS *)mr;
1346
1347         SetMapperFlags( hdc, lpSetMapperFlags->dwFlags );
1348
1349         break;
1350       }
1351
1352     case EMR_SETCOLORADJUSTMENT:
1353       {
1354         const EMRSETCOLORADJUSTMENT *lpSetColorAdjust = (const EMRSETCOLORADJUSTMENT *)mr;
1355
1356         SetColorAdjustment( hdc, &lpSetColorAdjust->ColorAdjustment );
1357
1358         break;
1359       }
1360
1361     case EMR_OFFSETCLIPRGN:
1362       {
1363         const EMROFFSETCLIPRGN *lpOffsetClipRgn = (const EMROFFSETCLIPRGN *)mr;
1364
1365         OffsetClipRgn( hdc,
1366                        (INT)lpOffsetClipRgn->ptlOffset.x,
1367                        (INT)lpOffsetClipRgn->ptlOffset.y );
1368         FIXME("OffsetClipRgn\n");
1369
1370         break;
1371       }
1372
1373     case EMR_EXCLUDECLIPRECT:
1374       {
1375         const EMREXCLUDECLIPRECT *lpExcludeClipRect = (const EMREXCLUDECLIPRECT *)mr;
1376
1377         ExcludeClipRect( hdc,
1378                          lpExcludeClipRect->rclClip.left,
1379                          lpExcludeClipRect->rclClip.top,
1380                          lpExcludeClipRect->rclClip.right,
1381                          lpExcludeClipRect->rclClip.bottom  );
1382         FIXME("ExcludeClipRect\n");
1383
1384          break;
1385       }
1386
1387     case EMR_SCALEVIEWPORTEXTEX:
1388       {
1389         const EMRSCALEVIEWPORTEXTEX *lpScaleViewportExtEx = (const EMRSCALEVIEWPORTEXTEX *)mr;
1390
1391         if ((info->state.mode != MM_ISOTROPIC) && (info->state.mode != MM_ANISOTROPIC))
1392             break;
1393         if (!lpScaleViewportExtEx->xNum || !lpScaleViewportExtEx->xDenom || 
1394             !lpScaleViewportExtEx->yNum || !lpScaleViewportExtEx->yDenom)
1395             break;
1396         info->state.vportExtX = MulDiv(info->state.vportExtX, lpScaleViewportExtEx->xNum,
1397                                  lpScaleViewportExtEx->xDenom);
1398         info->state.vportExtY = MulDiv(info->state.vportExtY, lpScaleViewportExtEx->yNum,
1399                                  lpScaleViewportExtEx->yDenom);
1400         if (info->state.vportExtX == 0) info->state.vportExtX = 1;
1401         if (info->state.vportExtY == 0) info->state.vportExtY = 1;
1402         if (info->state.mode == MM_ISOTROPIC)
1403             EMF_FixIsotropic(hdc, info);
1404
1405         TRACE("EMRSCALEVIEWPORTEXTEX %d/%d %d/%d\n",
1406              lpScaleViewportExtEx->xNum,lpScaleViewportExtEx->xDenom,
1407              lpScaleViewportExtEx->yNum,lpScaleViewportExtEx->yDenom);
1408
1409         break;
1410       }
1411
1412     case EMR_SCALEWINDOWEXTEX:
1413       {
1414         const EMRSCALEWINDOWEXTEX *lpScaleWindowExtEx = (const EMRSCALEWINDOWEXTEX *)mr;
1415
1416         if ((info->state.mode != MM_ISOTROPIC) && (info->state.mode != MM_ANISOTROPIC))
1417             break;
1418         if (!lpScaleWindowExtEx->xNum || !lpScaleWindowExtEx->xDenom || 
1419             !lpScaleWindowExtEx->xNum || !lpScaleWindowExtEx->yDenom)
1420             break;
1421         info->state.wndExtX = MulDiv(info->state.wndExtX, lpScaleWindowExtEx->xNum,
1422                                lpScaleWindowExtEx->xDenom);
1423         info->state.wndExtY = MulDiv(info->state.wndExtY, lpScaleWindowExtEx->yNum,
1424                                lpScaleWindowExtEx->yDenom);
1425         if (info->state.wndExtX == 0) info->state.wndExtX = 1;
1426         if (info->state.wndExtY == 0) info->state.wndExtY = 1;
1427         if (info->state.mode == MM_ISOTROPIC)
1428             EMF_FixIsotropic(hdc, info);
1429
1430         TRACE("EMRSCALEWINDOWEXTEX %d/%d %d/%d\n",
1431              lpScaleWindowExtEx->xNum,lpScaleWindowExtEx->xDenom,
1432              lpScaleWindowExtEx->yNum,lpScaleWindowExtEx->yDenom);
1433
1434         break;
1435       }
1436
1437     case EMR_MODIFYWORLDTRANSFORM:
1438       {
1439         const EMRMODIFYWORLDTRANSFORM *lpModifyWorldTrans = (const EMRMODIFYWORLDTRANSFORM *)mr;
1440
1441         switch(lpModifyWorldTrans->iMode) {
1442         case MWT_IDENTITY:
1443             info->state.world_transform.eM11 = info->state.world_transform.eM22 = 1;
1444             info->state.world_transform.eM12 = info->state.world_transform.eM21 = 0;
1445             info->state.world_transform.eDx  = info->state.world_transform.eDy  = 0;
1446             break;
1447         case MWT_LEFTMULTIPLY:
1448             CombineTransform(&info->state.world_transform, &lpModifyWorldTrans->xform,
1449                              &info->state.world_transform);
1450             break;
1451         case MWT_RIGHTMULTIPLY:
1452             CombineTransform(&info->state.world_transform, &info->state.world_transform,
1453                              &lpModifyWorldTrans->xform);
1454             break;
1455         default:
1456             FIXME("Unknown imode %d\n", lpModifyWorldTrans->iMode);
1457             break;
1458         }
1459         break;
1460       }
1461
1462     case EMR_ANGLEARC:
1463       {
1464         const EMRANGLEARC *lpAngleArc = (const EMRANGLEARC *)mr;
1465
1466         AngleArc( hdc,
1467                  (INT)lpAngleArc->ptlCenter.x, (INT)lpAngleArc->ptlCenter.y,
1468                  lpAngleArc->nRadius, lpAngleArc->eStartAngle,
1469                  lpAngleArc->eSweepAngle );
1470
1471         break;
1472       }
1473
1474     case EMR_ROUNDRECT:
1475       {
1476         const EMRROUNDRECT *lpRoundRect = (const EMRROUNDRECT *)mr;
1477
1478         RoundRect( hdc,
1479                    lpRoundRect->rclBox.left,
1480                    lpRoundRect->rclBox.top,
1481                    lpRoundRect->rclBox.right,
1482                    lpRoundRect->rclBox.bottom,
1483                    lpRoundRect->szlCorner.cx,
1484                    lpRoundRect->szlCorner.cy );
1485
1486         break;
1487       }
1488
1489     case EMR_ARC:
1490       {
1491         const EMRARC *lpArc = (const EMRARC *)mr;
1492
1493         Arc( hdc,
1494              (INT)lpArc->rclBox.left,
1495              (INT)lpArc->rclBox.top,
1496              (INT)lpArc->rclBox.right,
1497              (INT)lpArc->rclBox.bottom,
1498              (INT)lpArc->ptlStart.x,
1499              (INT)lpArc->ptlStart.y,
1500              (INT)lpArc->ptlEnd.x,
1501              (INT)lpArc->ptlEnd.y );
1502
1503         break;
1504       }
1505
1506     case EMR_CHORD:
1507       {
1508         const EMRCHORD *lpChord = (const EMRCHORD *)mr;
1509
1510         Chord( hdc,
1511              (INT)lpChord->rclBox.left,
1512              (INT)lpChord->rclBox.top,
1513              (INT)lpChord->rclBox.right,
1514              (INT)lpChord->rclBox.bottom,
1515              (INT)lpChord->ptlStart.x,
1516              (INT)lpChord->ptlStart.y,
1517              (INT)lpChord->ptlEnd.x,
1518              (INT)lpChord->ptlEnd.y );
1519
1520         break;
1521       }
1522
1523     case EMR_PIE:
1524       {
1525         const EMRPIE *lpPie = (const EMRPIE *)mr;
1526
1527         Pie( hdc,
1528              (INT)lpPie->rclBox.left,
1529              (INT)lpPie->rclBox.top,
1530              (INT)lpPie->rclBox.right,
1531              (INT)lpPie->rclBox.bottom,
1532              (INT)lpPie->ptlStart.x,
1533              (INT)lpPie->ptlStart.y,
1534              (INT)lpPie->ptlEnd.x,
1535              (INT)lpPie->ptlEnd.y );
1536
1537        break;
1538       }
1539
1540     case EMR_ARCTO:
1541       {
1542         const EMRARC *lpArcTo = (const EMRARC *)mr;
1543
1544         ArcTo( hdc,
1545                (INT)lpArcTo->rclBox.left,
1546                (INT)lpArcTo->rclBox.top,
1547                (INT)lpArcTo->rclBox.right,
1548                (INT)lpArcTo->rclBox.bottom,
1549                (INT)lpArcTo->ptlStart.x,
1550                (INT)lpArcTo->ptlStart.y,
1551                (INT)lpArcTo->ptlEnd.x,
1552                (INT)lpArcTo->ptlEnd.y );
1553
1554         break;
1555       }
1556
1557     case EMR_EXTFLOODFILL:
1558       {
1559         const EMREXTFLOODFILL *lpExtFloodFill = (const EMREXTFLOODFILL *)mr;
1560
1561         ExtFloodFill( hdc,
1562                       (INT)lpExtFloodFill->ptlStart.x,
1563                       (INT)lpExtFloodFill->ptlStart.y,
1564                       lpExtFloodFill->crColor,
1565                       (UINT)lpExtFloodFill->iMode );
1566
1567         break;
1568       }
1569
1570     case EMR_POLYDRAW:
1571       {
1572         const EMRPOLYDRAW *lpPolyDraw = (const EMRPOLYDRAW *)mr;
1573         PolyDraw( hdc,
1574                   (const POINT*)lpPolyDraw->aptl,
1575                   lpPolyDraw->abTypes,
1576                   (INT)lpPolyDraw->cptl );
1577
1578         break;
1579       }
1580
1581     case EMR_SETARCDIRECTION:
1582       {
1583         const EMRSETARCDIRECTION *lpSetArcDirection = (const EMRSETARCDIRECTION *)mr;
1584         SetArcDirection( hdc, (INT)lpSetArcDirection->iArcDirection );
1585         break;
1586       }
1587
1588     case EMR_SETMITERLIMIT:
1589       {
1590         const EMRSETMITERLIMIT *lpSetMiterLimit = (const EMRSETMITERLIMIT *)mr;
1591         SetMiterLimit( hdc, lpSetMiterLimit->eMiterLimit, NULL );
1592         break;
1593       }
1594
1595     case EMR_BEGINPATH:
1596       {
1597         BeginPath( hdc );
1598         break;
1599       }
1600
1601     case EMR_ENDPATH:
1602       {
1603         EndPath( hdc );
1604         break;
1605       }
1606
1607     case EMR_CLOSEFIGURE:
1608       {
1609         CloseFigure( hdc );
1610         break;
1611       }
1612
1613     case EMR_FILLPATH:
1614       {
1615         /*const EMRFILLPATH lpFillPath = (const EMRFILLPATH *)mr;*/
1616         FillPath( hdc );
1617         break;
1618       }
1619
1620     case EMR_STROKEANDFILLPATH:
1621       {
1622         /*const EMRSTROKEANDFILLPATH lpStrokeAndFillPath = (const EMRSTROKEANDFILLPATH *)mr;*/
1623         StrokeAndFillPath( hdc );
1624         break;
1625       }
1626
1627     case EMR_STROKEPATH:
1628       {
1629         /*const EMRSTROKEPATH lpStrokePath = (const EMRSTROKEPATH *)mr;*/
1630         StrokePath( hdc );
1631         break;
1632       }
1633
1634     case EMR_FLATTENPATH:
1635       {
1636         FlattenPath( hdc );
1637         break;
1638       }
1639
1640     case EMR_WIDENPATH:
1641       {
1642         WidenPath( hdc );
1643         break;
1644       }
1645
1646     case EMR_SELECTCLIPPATH:
1647       {
1648         const EMRSELECTCLIPPATH *lpSelectClipPath = (const EMRSELECTCLIPPATH *)mr;
1649         SelectClipPath( hdc, (INT)lpSelectClipPath->iMode );
1650         break;
1651       }
1652
1653     case EMR_ABORTPATH:
1654       {
1655         AbortPath( hdc );
1656         break;
1657       }
1658
1659     case EMR_CREATECOLORSPACE:
1660       {
1661         PEMRCREATECOLORSPACE lpCreateColorSpace = (PEMRCREATECOLORSPACE)mr;
1662         (handletable->objectHandle)[lpCreateColorSpace->ihCS] =
1663            CreateColorSpaceA( &lpCreateColorSpace->lcs );
1664         break;
1665       }
1666
1667     case EMR_SETCOLORSPACE:
1668       {
1669         const EMRSETCOLORSPACE *lpSetColorSpace = (const EMRSETCOLORSPACE *)mr;
1670         SetColorSpace( hdc,
1671                        (handletable->objectHandle)[lpSetColorSpace->ihCS] );
1672         break;
1673       }
1674
1675     case EMR_DELETECOLORSPACE:
1676       {
1677         const EMRDELETECOLORSPACE *lpDeleteColorSpace = (const EMRDELETECOLORSPACE *)mr;
1678         DeleteColorSpace( (handletable->objectHandle)[lpDeleteColorSpace->ihCS] );
1679         break;
1680       }
1681
1682     case EMR_SETICMMODE:
1683       {
1684         const EMRSETICMMODE *lpSetICMMode = (const EMRSETICMMODE *)mr;
1685         SetICMMode( hdc, (INT)lpSetICMMode->iMode );
1686         break;
1687       }
1688
1689     case EMR_PIXELFORMAT:
1690       {
1691         INT iPixelFormat;
1692         const EMRPIXELFORMAT *lpPixelFormat = (const EMRPIXELFORMAT *)mr;
1693
1694         iPixelFormat = ChoosePixelFormat( hdc, &lpPixelFormat->pfd );
1695         SetPixelFormat( hdc, iPixelFormat, &lpPixelFormat->pfd );
1696
1697         break;
1698       }
1699
1700     case EMR_SETPALETTEENTRIES:
1701       {
1702         const EMRSETPALETTEENTRIES *lpSetPaletteEntries = (const EMRSETPALETTEENTRIES *)mr;
1703
1704         SetPaletteEntries( (handletable->objectHandle)[lpSetPaletteEntries->ihPal],
1705                            (UINT)lpSetPaletteEntries->iStart,
1706                            (UINT)lpSetPaletteEntries->cEntries,
1707                            lpSetPaletteEntries->aPalEntries );
1708
1709         break;
1710       }
1711
1712     case EMR_RESIZEPALETTE:
1713       {
1714         const EMRRESIZEPALETTE *lpResizePalette = (const EMRRESIZEPALETTE *)mr;
1715
1716         ResizePalette( (handletable->objectHandle)[lpResizePalette->ihPal],
1717                        (UINT)lpResizePalette->cEntries );
1718
1719         break;
1720       }
1721
1722     case EMR_CREATEDIBPATTERNBRUSHPT:
1723       {
1724         const EMRCREATEDIBPATTERNBRUSHPT *lpCreate = (const EMRCREATEDIBPATTERNBRUSHPT *)mr;
1725         LPVOID lpPackedStruct;
1726
1727         /* Check that offsets and data are contained within the record
1728          * (including checking for wrap-arounds).
1729          */
1730         if (    lpCreate->offBmi  + lpCreate->cbBmi  > mr->nSize
1731              || lpCreate->offBits + lpCreate->cbBits > mr->nSize
1732              || lpCreate->offBmi  + lpCreate->cbBmi  < lpCreate->offBmi
1733              || lpCreate->offBits + lpCreate->cbBits < lpCreate->offBits )
1734         {
1735             ERR("Invalid EMR_CREATEDIBPATTERNBRUSHPT record\n");
1736             break;
1737         }
1738
1739         /* This is a BITMAPINFO struct followed directly by bitmap bits */
1740         lpPackedStruct = HeapAlloc( GetProcessHeap(), 0,
1741                                     lpCreate->cbBmi + lpCreate->cbBits );
1742         if(!lpPackedStruct)
1743         {
1744             SetLastError(ERROR_NOT_ENOUGH_MEMORY);
1745             break;
1746         }
1747
1748         /* Now pack this structure */
1749         memcpy( lpPackedStruct,
1750                 ((const BYTE *)lpCreate) + lpCreate->offBmi,
1751                 lpCreate->cbBmi );
1752         memcpy( ((BYTE*)lpPackedStruct) + lpCreate->cbBmi,
1753                 ((const BYTE *)lpCreate) + lpCreate->offBits,
1754                 lpCreate->cbBits );
1755
1756         (handletable->objectHandle)[lpCreate->ihBrush] =
1757            CreateDIBPatternBrushPt( lpPackedStruct,
1758                                     (UINT)lpCreate->iUsage );
1759
1760         HeapFree(GetProcessHeap(), 0, lpPackedStruct);
1761         break;
1762       }
1763
1764     case EMR_CREATEMONOBRUSH:
1765     {
1766         const EMRCREATEMONOBRUSH *pCreateMonoBrush = (const EMRCREATEMONOBRUSH *)mr;
1767         const BITMAPINFO *pbi = (const BITMAPINFO *)((const BYTE *)mr + pCreateMonoBrush->offBmi);
1768         HBITMAP hBmp;
1769
1770         /* Need to check if the bitmap is monochrome, and if the
1771            two colors are really black and white */
1772         if (pCreateMonoBrush->iUsage == DIB_PAL_MONO)
1773         {
1774             BITMAP bm;
1775
1776             /* Undocumented iUsage indicates a mono bitmap with no palette table,
1777              * aligned to 32 rather than 16 bits.
1778              */
1779             bm.bmType = 0;
1780             bm.bmWidth = pbi->bmiHeader.biWidth;
1781             bm.bmHeight = abs(pbi->bmiHeader.biHeight);
1782             bm.bmWidthBytes = 4 * ((pbi->bmiHeader.biWidth + 31) / 32);
1783             bm.bmPlanes = pbi->bmiHeader.biPlanes;
1784             bm.bmBitsPixel = pbi->bmiHeader.biBitCount;
1785             bm.bmBits = (BYTE *)mr + pCreateMonoBrush->offBits;
1786             hBmp = CreateBitmapIndirect(&bm);
1787         }
1788         else if (is_dib_monochrome(pbi))
1789         {
1790           /* Top-down DIBs have a negative height */
1791           LONG height = pbi->bmiHeader.biHeight;
1792
1793           hBmp = CreateBitmap(pbi->bmiHeader.biWidth, abs(height), 1, 1, NULL);
1794           SetDIBits(hdc, hBmp, 0, pbi->bmiHeader.biHeight,
1795               (const BYTE *)mr + pCreateMonoBrush->offBits, pbi, pCreateMonoBrush->iUsage);
1796         }
1797         else
1798         {
1799             hBmp = CreateDIBitmap(hdc, (const BITMAPINFOHEADER *)pbi, CBM_INIT,
1800               (const BYTE *)mr + pCreateMonoBrush->offBits, pbi, pCreateMonoBrush->iUsage);
1801         }
1802
1803         (handletable->objectHandle)[pCreateMonoBrush->ihBrush] = CreatePatternBrush(hBmp);
1804
1805         /* CreatePatternBrush created a copy of the bitmap */
1806         DeleteObject(hBmp);
1807         break;
1808     }
1809
1810     case EMR_BITBLT:
1811     {
1812         const EMRBITBLT *pBitBlt = (const EMRBITBLT *)mr;
1813
1814         if(pBitBlt->offBmiSrc == 0) { /* Record is a PatBlt */
1815             PatBlt(hdc, pBitBlt->xDest, pBitBlt->yDest, pBitBlt->cxDest, pBitBlt->cyDest,
1816                    pBitBlt->dwRop);
1817         } else { /* BitBlt */
1818             HDC hdcSrc = CreateCompatibleDC(hdc);
1819             HBRUSH hBrush, hBrushOld;
1820             HBITMAP hBmp = 0, hBmpOld = 0;
1821             const BITMAPINFO *pbi = (const BITMAPINFO *)((const BYTE *)mr + pBitBlt->offBmiSrc);
1822
1823             SetWorldTransform(hdcSrc, &pBitBlt->xformSrc);
1824
1825             hBrush = CreateSolidBrush(pBitBlt->crBkColorSrc);
1826             hBrushOld = SelectObject(hdcSrc, hBrush);
1827             PatBlt(hdcSrc, pBitBlt->rclBounds.left, pBitBlt->rclBounds.top,
1828                    pBitBlt->rclBounds.right - pBitBlt->rclBounds.left,
1829                    pBitBlt->rclBounds.bottom - pBitBlt->rclBounds.top, PATCOPY);
1830             SelectObject(hdcSrc, hBrushOld);
1831             DeleteObject(hBrush);
1832
1833             hBmp = CreateDIBitmap(hdc, (const BITMAPINFOHEADER *)pbi, CBM_INIT,
1834                                   (const BYTE *)mr + pBitBlt->offBitsSrc, pbi, pBitBlt->iUsageSrc);
1835             hBmpOld = SelectObject(hdcSrc, hBmp);
1836
1837             BitBlt(hdc, pBitBlt->xDest, pBitBlt->yDest, pBitBlt->cxDest, pBitBlt->cyDest,
1838                    hdcSrc, pBitBlt->xSrc, pBitBlt->ySrc, pBitBlt->dwRop);
1839
1840             SelectObject(hdcSrc, hBmpOld);
1841             DeleteObject(hBmp);
1842             DeleteDC(hdcSrc);
1843         }
1844         break;
1845     }
1846
1847     case EMR_STRETCHBLT:
1848     {
1849         const EMRSTRETCHBLT *pStretchBlt = (const EMRSTRETCHBLT *)mr;
1850
1851         TRACE("EMR_STRETCHBLT: %d, %d %dx%d -> %d, %d %dx%d. rop %08x offBitsSrc %d\n",
1852                pStretchBlt->xSrc, pStretchBlt->ySrc, pStretchBlt->cxSrc, pStretchBlt->cySrc,
1853                pStretchBlt->xDest, pStretchBlt->yDest, pStretchBlt->cxDest, pStretchBlt->cyDest,
1854                pStretchBlt->dwRop, pStretchBlt->offBitsSrc);
1855
1856         if(pStretchBlt->offBmiSrc == 0) { /* Record is a PatBlt */
1857             PatBlt(hdc, pStretchBlt->xDest, pStretchBlt->yDest, pStretchBlt->cxDest, pStretchBlt->cyDest,
1858                    pStretchBlt->dwRop);
1859         } else { /* StretchBlt */
1860             HDC hdcSrc = CreateCompatibleDC(hdc);
1861             HBRUSH hBrush, hBrushOld;
1862             HBITMAP hBmp = 0, hBmpOld = 0;
1863             const BITMAPINFO *pbi = (const BITMAPINFO *)((const BYTE *)mr + pStretchBlt->offBmiSrc);
1864
1865             SetWorldTransform(hdcSrc, &pStretchBlt->xformSrc);
1866
1867             hBrush = CreateSolidBrush(pStretchBlt->crBkColorSrc);
1868             hBrushOld = SelectObject(hdcSrc, hBrush);
1869             PatBlt(hdcSrc, pStretchBlt->rclBounds.left, pStretchBlt->rclBounds.top,
1870                    pStretchBlt->rclBounds.right - pStretchBlt->rclBounds.left,
1871                    pStretchBlt->rclBounds.bottom - pStretchBlt->rclBounds.top, PATCOPY);
1872             SelectObject(hdcSrc, hBrushOld);
1873             DeleteObject(hBrush);
1874
1875             hBmp = CreateDIBitmap(hdc, (const BITMAPINFOHEADER *)pbi, CBM_INIT,
1876                                   (const BYTE *)mr + pStretchBlt->offBitsSrc, pbi, pStretchBlt->iUsageSrc);
1877             hBmpOld = SelectObject(hdcSrc, hBmp);
1878
1879             StretchBlt(hdc, pStretchBlt->xDest, pStretchBlt->yDest, pStretchBlt->cxDest, pStretchBlt->cyDest,
1880                        hdcSrc, pStretchBlt->xSrc, pStretchBlt->ySrc, pStretchBlt->cxSrc, pStretchBlt->cySrc,
1881                        pStretchBlt->dwRop);
1882
1883             SelectObject(hdcSrc, hBmpOld);
1884             DeleteObject(hBmp);
1885             DeleteDC(hdcSrc);
1886         }
1887         break;
1888     }
1889
1890     case EMR_ALPHABLEND:
1891     {
1892         const EMRALPHABLEND *pAlphaBlend = (const EMRALPHABLEND *)mr;
1893
1894         TRACE("EMR_ALPHABLEND: %d, %d %dx%d -> %d, %d %dx%d. blendfn %08x offBitsSrc %d\n",
1895                pAlphaBlend->xSrc, pAlphaBlend->ySrc, pAlphaBlend->cxSrc, pAlphaBlend->cySrc,
1896                pAlphaBlend->xDest, pAlphaBlend->yDest, pAlphaBlend->cxDest, pAlphaBlend->cyDest,
1897                pAlphaBlend->dwRop, pAlphaBlend->offBitsSrc);
1898
1899         if(pAlphaBlend->offBmiSrc == 0) {
1900             FIXME("EMR_ALPHABLEND: offBmiSrc == 0\n");
1901         } else {
1902             HDC hdcSrc = CreateCompatibleDC(hdc);
1903             HBITMAP hBmp = 0, hBmpOld = 0;
1904             const BITMAPINFO *pbi = (const BITMAPINFO *)((const BYTE *)mr + pAlphaBlend->offBmiSrc);
1905             void *bits;
1906
1907             SetWorldTransform(hdcSrc, &pAlphaBlend->xformSrc);
1908
1909             hBmp = CreateDIBSection(hdc, pbi, pAlphaBlend->iUsageSrc, &bits, NULL, 0);
1910             memcpy(bits, (const BYTE *)mr + pAlphaBlend->offBitsSrc, pAlphaBlend->cbBitsSrc);
1911             hBmpOld = SelectObject(hdcSrc, hBmp);
1912
1913             GdiAlphaBlend(hdc, pAlphaBlend->xDest, pAlphaBlend->yDest, pAlphaBlend->cxDest, pAlphaBlend->cyDest,
1914                        hdcSrc, pAlphaBlend->xSrc, pAlphaBlend->ySrc, pAlphaBlend->cxSrc, pAlphaBlend->cySrc,
1915                           *(BLENDFUNCTION *)&pAlphaBlend->dwRop);
1916
1917             SelectObject(hdcSrc, hBmpOld);
1918             DeleteObject(hBmp);
1919             DeleteDC(hdcSrc);
1920         }
1921         break;
1922     }
1923
1924     case EMR_MASKBLT:
1925     {
1926         const EMRMASKBLT *pMaskBlt = (const EMRMASKBLT *)mr;
1927         HDC hdcSrc = CreateCompatibleDC(hdc);
1928         HBRUSH hBrush, hBrushOld;
1929         HBITMAP hBmp, hBmpOld, hBmpMask;
1930         const BITMAPINFO *pbi;
1931
1932         SetWorldTransform(hdcSrc, &pMaskBlt->xformSrc);
1933
1934         hBrush = CreateSolidBrush(pMaskBlt->crBkColorSrc);
1935         hBrushOld = SelectObject(hdcSrc, hBrush);
1936         PatBlt(hdcSrc, pMaskBlt->rclBounds.left, pMaskBlt->rclBounds.top,
1937                pMaskBlt->rclBounds.right - pMaskBlt->rclBounds.left,
1938                pMaskBlt->rclBounds.bottom - pMaskBlt->rclBounds.top, PATCOPY);
1939         SelectObject(hdcSrc, hBrushOld);
1940         DeleteObject(hBrush);
1941
1942         pbi = (const BITMAPINFO *)((const BYTE *)mr + pMaskBlt->offBmiMask);
1943         hBmpMask = CreateBitmap(pbi->bmiHeader.biWidth, pbi->bmiHeader.biHeight,
1944                      1, 1, NULL);
1945         SetDIBits(hdc, hBmpMask, 0, pbi->bmiHeader.biHeight,
1946           (const BYTE *)mr + pMaskBlt->offBitsMask, pbi, pMaskBlt->iUsageMask);
1947
1948         pbi = (const BITMAPINFO *)((const BYTE *)mr + pMaskBlt->offBmiSrc);
1949         hBmp = CreateDIBitmap(hdc, (const BITMAPINFOHEADER *)pbi, CBM_INIT,
1950                               (const BYTE *)mr + pMaskBlt->offBitsSrc, pbi, pMaskBlt->iUsageSrc);
1951         hBmpOld = SelectObject(hdcSrc, hBmp);
1952         MaskBlt(hdc,
1953                 pMaskBlt->xDest,
1954                 pMaskBlt->yDest,
1955                 pMaskBlt->cxDest,
1956                 pMaskBlt->cyDest,
1957                 hdcSrc,
1958                 pMaskBlt->xSrc,
1959                 pMaskBlt->ySrc,
1960                 hBmpMask,
1961                 pMaskBlt->xMask,
1962                 pMaskBlt->yMask,
1963                 pMaskBlt->dwRop);
1964         SelectObject(hdcSrc, hBmpOld);
1965         DeleteObject(hBmp);
1966         DeleteObject(hBmpMask);
1967         DeleteDC(hdcSrc);
1968         break;
1969     }
1970
1971     case EMR_PLGBLT:
1972     {
1973         const EMRPLGBLT *pPlgBlt = (const EMRPLGBLT *)mr;
1974         HDC hdcSrc = CreateCompatibleDC(hdc);
1975         HBRUSH hBrush, hBrushOld;
1976         HBITMAP hBmp, hBmpOld, hBmpMask;
1977         const BITMAPINFO *pbi;
1978         POINT pts[3];
1979
1980         SetWorldTransform(hdcSrc, &pPlgBlt->xformSrc);
1981
1982         pts[0].x = pPlgBlt->aptlDest[0].x; pts[0].y = pPlgBlt->aptlDest[0].y;
1983         pts[1].x = pPlgBlt->aptlDest[1].x; pts[1].y = pPlgBlt->aptlDest[1].y;
1984         pts[2].x = pPlgBlt->aptlDest[2].x; pts[2].y = pPlgBlt->aptlDest[2].y;
1985
1986         hBrush = CreateSolidBrush(pPlgBlt->crBkColorSrc);
1987         hBrushOld = SelectObject(hdcSrc, hBrush);
1988         PatBlt(hdcSrc, pPlgBlt->rclBounds.left, pPlgBlt->rclBounds.top,
1989                pPlgBlt->rclBounds.right - pPlgBlt->rclBounds.left,
1990                pPlgBlt->rclBounds.bottom - pPlgBlt->rclBounds.top, PATCOPY);
1991         SelectObject(hdcSrc, hBrushOld);
1992         DeleteObject(hBrush);
1993
1994         pbi = (const BITMAPINFO *)((const BYTE *)mr + pPlgBlt->offBmiMask);
1995         hBmpMask = CreateBitmap(pbi->bmiHeader.biWidth, pbi->bmiHeader.biHeight,
1996                      1, 1, NULL);
1997         SetDIBits(hdc, hBmpMask, 0, pbi->bmiHeader.biHeight,
1998           (const BYTE *)mr + pPlgBlt->offBitsMask, pbi, pPlgBlt->iUsageMask);
1999
2000         pbi = (const BITMAPINFO *)((const BYTE *)mr + pPlgBlt->offBmiSrc);
2001         hBmp = CreateDIBitmap(hdc, (const BITMAPINFOHEADER *)pbi, CBM_INIT,
2002                               (const BYTE *)mr + pPlgBlt->offBitsSrc, pbi, pPlgBlt->iUsageSrc);
2003         hBmpOld = SelectObject(hdcSrc, hBmp);
2004         PlgBlt(hdc,
2005                pts,
2006                hdcSrc,
2007                pPlgBlt->xSrc,
2008                pPlgBlt->ySrc,
2009                pPlgBlt->cxSrc,
2010                pPlgBlt->cySrc,
2011                hBmpMask,
2012                pPlgBlt->xMask,
2013                pPlgBlt->yMask);
2014         SelectObject(hdcSrc, hBmpOld);
2015         DeleteObject(hBmp);
2016         DeleteObject(hBmpMask);
2017         DeleteDC(hdcSrc);
2018         break;
2019     }
2020
2021     case EMR_SETDIBITSTODEVICE:
2022     {
2023         const EMRSETDIBITSTODEVICE *pSetDIBitsToDevice = (const EMRSETDIBITSTODEVICE *)mr;
2024
2025         SetDIBitsToDevice(hdc,
2026                           pSetDIBitsToDevice->xDest,
2027                           pSetDIBitsToDevice->yDest,
2028                           pSetDIBitsToDevice->cxSrc,
2029                           pSetDIBitsToDevice->cySrc,
2030                           pSetDIBitsToDevice->xSrc,
2031                           pSetDIBitsToDevice->ySrc,
2032                           pSetDIBitsToDevice->iStartScan,
2033                           pSetDIBitsToDevice->cScans,
2034                           (const BYTE *)mr + pSetDIBitsToDevice->offBitsSrc,
2035                           (const BITMAPINFO *)((const BYTE *)mr + pSetDIBitsToDevice->offBmiSrc),
2036                           pSetDIBitsToDevice->iUsageSrc);
2037         break;
2038     }
2039
2040     case EMR_POLYTEXTOUTA:
2041     {
2042         const EMRPOLYTEXTOUTA *pPolyTextOutA = (const EMRPOLYTEXTOUTA *)mr;
2043         POLYTEXTA *polytextA = HeapAlloc(GetProcessHeap(), 0, pPolyTextOutA->cStrings * sizeof(POLYTEXTA));
2044         LONG i;
2045         XFORM xform, xformOld;
2046         int gModeOld;
2047
2048         gModeOld = SetGraphicsMode(hdc, pPolyTextOutA->iGraphicsMode);
2049         GetWorldTransform(hdc, &xformOld);
2050
2051         xform.eM11 = pPolyTextOutA->exScale;
2052         xform.eM12 = 0.0;
2053         xform.eM21 = 0.0;
2054         xform.eM22 = pPolyTextOutA->eyScale;
2055         xform.eDx = 0.0;
2056         xform.eDy = 0.0;
2057         SetWorldTransform(hdc, &xform);
2058
2059         /* Set up POLYTEXTA structures */
2060         for(i = 0; i < pPolyTextOutA->cStrings; i++)
2061         {
2062             polytextA[i].x = pPolyTextOutA->aemrtext[i].ptlReference.x;
2063             polytextA[i].y = pPolyTextOutA->aemrtext[i].ptlReference.y;
2064             polytextA[i].n = pPolyTextOutA->aemrtext[i].nChars;
2065             polytextA[i].lpstr = (LPCSTR)((const BYTE *)mr + pPolyTextOutA->aemrtext[i].offString);
2066             polytextA[i].uiFlags = pPolyTextOutA->aemrtext[i].fOptions;
2067             polytextA[i].rcl.left = pPolyTextOutA->aemrtext[i].rcl.left;
2068             polytextA[i].rcl.right = pPolyTextOutA->aemrtext[i].rcl.right;
2069             polytextA[i].rcl.top = pPolyTextOutA->aemrtext[i].rcl.top;
2070             polytextA[i].rcl.bottom = pPolyTextOutA->aemrtext[i].rcl.bottom;
2071             polytextA[i].pdx = (int *)((BYTE *)mr + pPolyTextOutA->aemrtext[i].offDx);
2072         }
2073         PolyTextOutA(hdc, polytextA, pPolyTextOutA->cStrings);
2074         HeapFree(GetProcessHeap(), 0, polytextA);
2075
2076         SetWorldTransform(hdc, &xformOld);
2077         SetGraphicsMode(hdc, gModeOld);
2078         break;
2079     }
2080
2081     case EMR_POLYTEXTOUTW:
2082     {
2083         const EMRPOLYTEXTOUTW *pPolyTextOutW = (const EMRPOLYTEXTOUTW *)mr;
2084         POLYTEXTW *polytextW = HeapAlloc(GetProcessHeap(), 0, pPolyTextOutW->cStrings * sizeof(POLYTEXTW));
2085         LONG i;
2086         XFORM xform, xformOld;
2087         int gModeOld;
2088
2089         gModeOld = SetGraphicsMode(hdc, pPolyTextOutW->iGraphicsMode);
2090         GetWorldTransform(hdc, &xformOld);
2091
2092         xform.eM11 = pPolyTextOutW->exScale;
2093         xform.eM12 = 0.0;
2094         xform.eM21 = 0.0;
2095         xform.eM22 = pPolyTextOutW->eyScale;
2096         xform.eDx = 0.0;
2097         xform.eDy = 0.0;
2098         SetWorldTransform(hdc, &xform);
2099
2100         /* Set up POLYTEXTW structures */
2101         for(i = 0; i < pPolyTextOutW->cStrings; i++)
2102         {
2103             polytextW[i].x = pPolyTextOutW->aemrtext[i].ptlReference.x;
2104             polytextW[i].y = pPolyTextOutW->aemrtext[i].ptlReference.y;
2105             polytextW[i].n = pPolyTextOutW->aemrtext[i].nChars;
2106             polytextW[i].lpstr = (LPCWSTR)((const BYTE *)mr + pPolyTextOutW->aemrtext[i].offString);
2107             polytextW[i].uiFlags = pPolyTextOutW->aemrtext[i].fOptions;
2108             polytextW[i].rcl.left = pPolyTextOutW->aemrtext[i].rcl.left;
2109             polytextW[i].rcl.right = pPolyTextOutW->aemrtext[i].rcl.right;
2110             polytextW[i].rcl.top = pPolyTextOutW->aemrtext[i].rcl.top;
2111             polytextW[i].rcl.bottom = pPolyTextOutW->aemrtext[i].rcl.bottom;
2112             polytextW[i].pdx = (int *)((BYTE *)mr + pPolyTextOutW->aemrtext[i].offDx);
2113         }
2114         PolyTextOutW(hdc, polytextW, pPolyTextOutW->cStrings);
2115         HeapFree(GetProcessHeap(), 0, polytextW);
2116
2117         SetWorldTransform(hdc, &xformOld);
2118         SetGraphicsMode(hdc, gModeOld);
2119         break;
2120     }
2121
2122     case EMR_FILLRGN:
2123     {
2124         const EMRFILLRGN *pFillRgn = (const EMRFILLRGN *)mr;
2125         HRGN hRgn = ExtCreateRegion(NULL, pFillRgn->cbRgnData, (const RGNDATA *)pFillRgn->RgnData);
2126         FillRgn(hdc,
2127                 hRgn,
2128                 (handletable->objectHandle)[pFillRgn->ihBrush]);
2129         DeleteObject(hRgn);
2130         break;
2131     }
2132
2133     case EMR_FRAMERGN:
2134     {
2135         const EMRFRAMERGN *pFrameRgn = (const EMRFRAMERGN *)mr;
2136         HRGN hRgn = ExtCreateRegion(NULL, pFrameRgn->cbRgnData, (const RGNDATA *)pFrameRgn->RgnData);
2137         FrameRgn(hdc,
2138                  hRgn,
2139                  (handletable->objectHandle)[pFrameRgn->ihBrush],
2140                  pFrameRgn->szlStroke.cx,
2141                  pFrameRgn->szlStroke.cy);
2142         DeleteObject(hRgn);
2143         break;
2144     }
2145
2146     case EMR_INVERTRGN:
2147     {
2148         const EMRINVERTRGN *pInvertRgn = (const EMRINVERTRGN *)mr;
2149         HRGN hRgn = ExtCreateRegion(NULL, pInvertRgn->cbRgnData, (const RGNDATA *)pInvertRgn->RgnData);
2150         InvertRgn(hdc, hRgn);
2151         DeleteObject(hRgn);
2152         break;
2153     }
2154
2155     case EMR_PAINTRGN:
2156     {
2157         const EMRPAINTRGN *pPaintRgn = (const EMRPAINTRGN *)mr;
2158         HRGN hRgn = ExtCreateRegion(NULL, pPaintRgn->cbRgnData, (const RGNDATA *)pPaintRgn->RgnData);
2159         PaintRgn(hdc, hRgn);
2160         DeleteObject(hRgn);
2161         break;
2162     }
2163
2164     case EMR_SETTEXTJUSTIFICATION:
2165     {
2166         const EMRSETTEXTJUSTIFICATION *pSetTextJust = (const EMRSETTEXTJUSTIFICATION *)mr;
2167         SetTextJustification(hdc, pSetTextJust->nBreakExtra, pSetTextJust->nBreakCount);
2168         break;
2169     }
2170
2171     case EMR_SETLAYOUT:
2172     {
2173         const EMRSETLAYOUT *pSetLayout = (const EMRSETLAYOUT *)mr;
2174         SetLayout(hdc, pSetLayout->iMode);
2175         break;
2176     }
2177
2178     case EMR_POLYDRAW16:
2179     case EMR_GLSRECORD:
2180     case EMR_GLSBOUNDEDRECORD:
2181         case EMR_DRAWESCAPE :
2182         case EMR_EXTESCAPE:
2183         case EMR_STARTDOC:
2184         case EMR_SMALLTEXTOUT:
2185         case EMR_FORCEUFIMAPPING:
2186         case EMR_NAMEDESCAPE:
2187         case EMR_COLORCORRECTPALETTE:
2188         case EMR_SETICMPROFILEA:
2189         case EMR_SETICMPROFILEW:
2190         case EMR_TRANSPARENTBLT:
2191         case EMR_GRADIENTFILL:
2192         case EMR_SETLINKEDUFI:
2193         case EMR_COLORMATCHTOTARGETW:
2194         case EMR_CREATECOLORSPACEW:
2195
2196     default:
2197       /* From docs: If PlayEnhMetaFileRecord doesn't recognize a
2198                     record then ignore and return TRUE. */
2199       FIXME("type %d is unimplemented\n", type);
2200       break;
2201     }
2202   tmprc.left = tmprc.top = 0;
2203   tmprc.right = tmprc.bottom = 1000;
2204   LPtoDP(hdc, (POINT*)&tmprc, 2);
2205   TRACE("L:0,0 - 1000,1000 -> D:%d,%d - %d,%d\n", tmprc.left,
2206         tmprc.top, tmprc.right, tmprc.bottom);
2207
2208   return TRUE;
2209 }
2210
2211
2212 /*****************************************************************************
2213  *
2214  *        EnumEnhMetaFile  (GDI32.@)
2215  *
2216  *  Walk an enhanced metafile, calling a user-specified function _EnhMetaFunc_
2217  *  for each
2218  *  record. Returns when either every record has been used or
2219  *  when _EnhMetaFunc_ returns FALSE.
2220  *
2221  *
2222  * RETURNS
2223  *  TRUE if every record is used, FALSE if any invocation of _EnhMetaFunc_
2224  *  returns FALSE.
2225  *
2226  * BUGS
2227  *   Ignores rect.
2228  *
2229  * NOTES
2230  *   This function behaves differently in Win9x and WinNT.
2231  *
2232  *   In WinNT, the DC's world transform is updated as the EMF changes
2233  *    the Window/Viewport Extent and Origin or it's world transform.
2234  *    The actual Window/Viewport Extent and Origin are left untouched.
2235  *
2236  *   In Win9x, the DC is left untouched, and PlayEnhMetaFileRecord
2237  *    updates the scaling itself but only just before a record that
2238  *    writes anything to the DC.
2239  *
2240  *   I'm not sure where the data (enum_emh_data) is stored in either
2241  *    version. For this implementation, it is stored before the handle
2242  *    table, but it could be stored in the DC, in the EMF handle or in
2243  *    TLS.
2244  *             MJM  5 Oct 2002
2245  */
2246 BOOL WINAPI EnumEnhMetaFile(
2247      HDC hdc,                /* [in] device context to pass to _EnhMetaFunc_ */
2248      HENHMETAFILE hmf,       /* [in] EMF to walk */
2249      ENHMFENUMPROC callback, /* [in] callback function */
2250      LPVOID data,            /* [in] optional data for callback function */
2251      const RECT *lpRect      /* [in] bounding rectangle for rendered metafile */
2252     )
2253 {
2254     BOOL ret;
2255     ENHMETAHEADER *emh;
2256     ENHMETARECORD *emr;
2257     DWORD offset;
2258     UINT i;
2259     HANDLETABLE *ht;
2260     INT savedMode = 0;
2261     XFORM savedXform;
2262     HPEN hPen = NULL;
2263     HBRUSH hBrush = NULL;
2264     HFONT hFont = NULL;
2265     HRGN hRgn = NULL;
2266     enum_emh_data *info;
2267     SIZE vp_size, win_size;
2268     POINT vp_org, win_org;
2269     INT mapMode = MM_TEXT, old_align = 0, old_rop2 = 0, old_arcdir = 0, old_polyfill = 0, old_stretchblt = 0;
2270     COLORREF old_text_color = 0, old_bk_color = 0;
2271
2272     if(!lpRect && hdc)
2273     {
2274         SetLastError(ERROR_INVALID_PARAMETER);
2275         return FALSE;
2276     }
2277
2278     emh = EMF_GetEnhMetaHeader(hmf);
2279     if(!emh) {
2280         SetLastError(ERROR_INVALID_HANDLE);
2281         return FALSE;
2282     }
2283
2284     info = HeapAlloc( GetProcessHeap(), 0,
2285                     sizeof (enum_emh_data) + sizeof(HANDLETABLE) * emh->nHandles );
2286     if(!info)
2287     {
2288         SetLastError(ERROR_NOT_ENOUGH_MEMORY);
2289         return FALSE;
2290     }
2291     info->state.wndOrgX = 0;
2292     info->state.wndOrgY = 0;
2293     info->state.wndExtX = 1;
2294     info->state.wndExtY = 1;
2295     info->state.vportOrgX = 0;
2296     info->state.vportOrgY = 0;
2297     info->state.vportExtX = 1;
2298     info->state.vportExtY = 1;
2299     info->state.world_transform.eM11 = info->state.world_transform.eM22 = 1;
2300     info->state.world_transform.eM12 = info->state.world_transform.eM21 = 0;
2301     info->state.world_transform.eDx  = info->state.world_transform.eDy =  0;
2302
2303     info->state.next = NULL;
2304     info->save_level = 0;
2305     info->saved_state = NULL;
2306
2307     ht = (HANDLETABLE*) &info[1];
2308     ht->objectHandle[0] = hmf;
2309     for(i = 1; i < emh->nHandles; i++)
2310         ht->objectHandle[i] = NULL;
2311
2312     if(hdc)
2313     {
2314         savedMode = SetGraphicsMode(hdc, GM_ADVANCED);
2315         GetWorldTransform(hdc, &savedXform);
2316         GetViewportExtEx(hdc, &vp_size);
2317         GetWindowExtEx(hdc, &win_size);
2318         GetViewportOrgEx(hdc, &vp_org);
2319         GetWindowOrgEx(hdc, &win_org);
2320         mapMode = GetMapMode(hdc);
2321
2322         /* save DC */
2323         hPen = GetCurrentObject(hdc, OBJ_PEN);
2324         hBrush = GetCurrentObject(hdc, OBJ_BRUSH);
2325         hFont = GetCurrentObject(hdc, OBJ_FONT);
2326
2327         hRgn = CreateRectRgn(0, 0, 0, 0);
2328         if (!GetClipRgn(hdc, hRgn))
2329         {
2330             DeleteObject(hRgn);
2331             hRgn = 0;
2332         }
2333
2334         old_text_color = SetTextColor(hdc, RGB(0,0,0));
2335         old_bk_color = SetBkColor(hdc, RGB(0xff, 0xff, 0xff));
2336         old_align = SetTextAlign(hdc, 0);
2337         old_rop2 = SetROP2(hdc, R2_COPYPEN);
2338         old_arcdir = SetArcDirection(hdc, AD_COUNTERCLOCKWISE);
2339         old_polyfill = SetPolyFillMode(hdc, ALTERNATE);
2340         old_stretchblt = SetStretchBltMode(hdc, BLACKONWHITE);
2341     }
2342
2343     info->state.mode = MM_TEXT;
2344
2345     if ( IS_WIN9X() )
2346     {
2347         /* Win95 leaves the vp/win ext/org info alone */
2348         info->init_transform.eM11 = 1.0;
2349         info->init_transform.eM12 = 0.0;
2350         info->init_transform.eM21 = 0.0;
2351         info->init_transform.eM22 = 1.0;
2352         info->init_transform.eDx  = 0.0;
2353         info->init_transform.eDy  = 0.0;
2354     }
2355     else
2356     {
2357         /* WinNT combines the vp/win ext/org info into a transform */
2358         double xscale, yscale;
2359         xscale = (double)vp_size.cx / (double)win_size.cx;
2360         yscale = (double)vp_size.cy / (double)win_size.cy;
2361         info->init_transform.eM11 = xscale;
2362         info->init_transform.eM12 = 0.0;
2363         info->init_transform.eM21 = 0.0;
2364         info->init_transform.eM22 = yscale;
2365         info->init_transform.eDx  = (double)vp_org.x - xscale * (double)win_org.x;
2366         info->init_transform.eDy  = (double)vp_org.y - yscale * (double)win_org.y;
2367
2368         CombineTransform(&info->init_transform, &savedXform, &info->init_transform);
2369     }
2370
2371     if ( lpRect && WIDTH(emh->rclFrame) && HEIGHT(emh->rclFrame) )
2372     {
2373         double xSrcPixSize, ySrcPixSize, xscale, yscale;
2374         XFORM xform;
2375
2376         TRACE("rect: %d,%d - %d,%d. rclFrame: %d,%d - %d,%d\n",
2377            lpRect->left, lpRect->top, lpRect->right, lpRect->bottom,
2378            emh->rclFrame.left, emh->rclFrame.top, emh->rclFrame.right,
2379            emh->rclFrame.bottom);
2380
2381         xSrcPixSize = (double) emh->szlMillimeters.cx / emh->szlDevice.cx;
2382         ySrcPixSize = (double) emh->szlMillimeters.cy / emh->szlDevice.cy;
2383         xscale = (double) WIDTH(*lpRect) * 100.0 /
2384                  WIDTH(emh->rclFrame) * xSrcPixSize;
2385         yscale = (double) HEIGHT(*lpRect) * 100.0 /
2386                  HEIGHT(emh->rclFrame) * ySrcPixSize;
2387         TRACE("xscale = %f, yscale = %f\n", xscale, yscale);
2388
2389         xform.eM11 = xscale;
2390         xform.eM12 = 0;
2391         xform.eM21 = 0;
2392         xform.eM22 = yscale;
2393         xform.eDx = (double) lpRect->left - (double) WIDTH(*lpRect) / WIDTH(emh->rclFrame) * emh->rclFrame.left;
2394         xform.eDy = (double) lpRect->top - (double) HEIGHT(*lpRect) / HEIGHT(emh->rclFrame) * emh->rclFrame.top;
2395
2396         CombineTransform(&info->init_transform, &xform, &info->init_transform);
2397     }
2398
2399     /* WinNT resets the current vp/win org/ext */
2400     if ( !IS_WIN9X() && hdc )
2401     {
2402         SetMapMode(hdc, MM_TEXT);
2403         SetWindowOrgEx(hdc, 0, 0, NULL);
2404         SetViewportOrgEx(hdc, 0, 0, NULL);
2405         EMF_Update_MF_Xform(hdc, info);
2406     }
2407
2408     ret = TRUE;
2409     offset = 0;
2410     while(ret && offset < emh->nBytes)
2411     {
2412         emr = (ENHMETARECORD *)((char *)emh + offset);
2413
2414         /* In Win9x mode we update the xform if the record will produce output */
2415         if (hdc && IS_WIN9X() && emr_produces_output(emr->iType))
2416             EMF_Update_MF_Xform(hdc, info);
2417
2418         TRACE("Calling EnumFunc with record %s, size %d\n", get_emr_name(emr->iType), emr->nSize);
2419         ret = (*callback)(hdc, ht, emr, emh->nHandles, (LPARAM)data);
2420         offset += emr->nSize;
2421
2422         /* WinNT - update the transform (win9x updates when the next graphics
2423            output record is played). */
2424         if (hdc && !IS_WIN9X())
2425             EMF_Update_MF_Xform(hdc, info);
2426     }
2427
2428     if (hdc)
2429     {
2430         SetStretchBltMode(hdc, old_stretchblt);
2431         SetPolyFillMode(hdc, old_polyfill);
2432         SetArcDirection(hdc, old_arcdir);
2433         SetROP2(hdc, old_rop2);
2434         SetTextAlign(hdc, old_align);
2435         SetBkColor(hdc, old_bk_color);
2436         SetTextColor(hdc, old_text_color);
2437
2438         /* restore DC */
2439         SelectObject(hdc, hBrush);
2440         SelectObject(hdc, hPen);
2441         SelectObject(hdc, hFont);
2442         ExtSelectClipRgn(hdc, hRgn, RGN_COPY);
2443         DeleteObject(hRgn);
2444
2445         SetWorldTransform(hdc, &savedXform);
2446         if (savedMode)
2447             SetGraphicsMode(hdc, savedMode);
2448         SetMapMode(hdc, mapMode);
2449         SetWindowOrgEx(hdc, win_org.x, win_org.y, NULL);
2450         SetWindowExtEx(hdc, win_size.cx, win_size.cy, NULL);
2451         SetViewportOrgEx(hdc, vp_org.x, vp_org.y, NULL);
2452         SetViewportExtEx(hdc, vp_size.cx, vp_size.cy, NULL);
2453     }
2454
2455     for(i = 1; i < emh->nHandles; i++) /* Don't delete element 0 (hmf) */
2456         if( (ht->objectHandle)[i] )
2457             DeleteObject( (ht->objectHandle)[i] );
2458
2459     while (info->saved_state)
2460     {
2461         EMF_dc_state *state = info->saved_state;
2462         info->saved_state = info->saved_state->next;
2463         HeapFree( GetProcessHeap(), 0, state );
2464     }
2465     HeapFree( GetProcessHeap(), 0, info );
2466     return ret;
2467 }
2468
2469 static INT CALLBACK EMF_PlayEnhMetaFileCallback(HDC hdc, HANDLETABLE *ht,
2470                                                 const ENHMETARECORD *emr,
2471                                                 INT handles, LPARAM data)
2472 {
2473     return PlayEnhMetaFileRecord(hdc, ht, emr, handles);
2474 }
2475
2476 /**************************************************************************
2477  *    PlayEnhMetaFile  (GDI32.@)
2478  *
2479  *    Renders an enhanced metafile into a specified rectangle *lpRect
2480  *    in device context hdc.
2481  *
2482  * RETURNS
2483  *    Success: TRUE
2484  *    Failure: FALSE
2485  */
2486 BOOL WINAPI PlayEnhMetaFile(
2487        HDC hdc,           /* [in] DC to render into */
2488        HENHMETAFILE hmf,  /* [in] metafile to render */
2489        const RECT *lpRect /* [in] rectangle to place metafile inside */
2490       )
2491 {
2492     return EnumEnhMetaFile(hdc, hmf, EMF_PlayEnhMetaFileCallback, NULL,
2493                            lpRect);
2494 }
2495
2496 /*****************************************************************************
2497  *  DeleteEnhMetaFile (GDI32.@)
2498  *
2499  *  Deletes an enhanced metafile and frees the associated storage.
2500  */
2501 BOOL WINAPI DeleteEnhMetaFile(HENHMETAFILE hmf)
2502 {
2503     return EMF_Delete_HENHMETAFILE( hmf );
2504 }
2505
2506 /*****************************************************************************
2507  *  CopyEnhMetaFileA (GDI32.@)
2508  *
2509  * Duplicate an enhanced metafile.
2510  *
2511  *
2512  */
2513 HENHMETAFILE WINAPI CopyEnhMetaFileA(
2514     HENHMETAFILE hmfSrc,
2515     LPCSTR file)
2516 {
2517     ENHMETAHEADER *emrSrc = EMF_GetEnhMetaHeader( hmfSrc ), *emrDst;
2518     HENHMETAFILE hmfDst;
2519
2520     if(!emrSrc) return FALSE;
2521     if (!file) {
2522         emrDst = HeapAlloc( GetProcessHeap(), 0, emrSrc->nBytes );
2523         memcpy( emrDst, emrSrc, emrSrc->nBytes );
2524         hmfDst = EMF_Create_HENHMETAFILE( emrDst, FALSE );
2525         if (!hmfDst)
2526                 HeapFree( GetProcessHeap(), 0, emrDst );
2527     } else {
2528         HANDLE hFile;
2529         DWORD w;
2530         hFile = CreateFileA( file, GENERIC_WRITE | GENERIC_READ, 0,
2531                              NULL, CREATE_ALWAYS, 0, 0);
2532         WriteFile( hFile, emrSrc, emrSrc->nBytes, &w, NULL);
2533         CloseHandle( hFile );
2534         /* Reopen file for reading only, so that apps can share
2535            read access to the file while hmf is still valid */
2536         hFile = CreateFileA( file, GENERIC_READ, FILE_SHARE_READ,
2537                              NULL, OPEN_EXISTING, 0, 0);
2538         if(hFile == INVALID_HANDLE_VALUE) {
2539             ERR("Can't reopen emf for reading\n");
2540             return 0;
2541         }
2542         hmfDst = EMF_GetEnhMetaFile( hFile );
2543         CloseHandle( hFile );
2544     }
2545     return hmfDst;
2546 }
2547
2548 /*****************************************************************************
2549  *  CopyEnhMetaFileW (GDI32.@)
2550  *
2551  * See CopyEnhMetaFileA.
2552  *
2553  *
2554  */
2555 HENHMETAFILE WINAPI CopyEnhMetaFileW(
2556     HENHMETAFILE hmfSrc,
2557     LPCWSTR file)
2558 {
2559     ENHMETAHEADER *emrSrc = EMF_GetEnhMetaHeader( hmfSrc ), *emrDst;
2560     HENHMETAFILE hmfDst;
2561
2562     if(!emrSrc) return FALSE;
2563     if (!file) {
2564         emrDst = HeapAlloc( GetProcessHeap(), 0, emrSrc->nBytes );
2565         memcpy( emrDst, emrSrc, emrSrc->nBytes );
2566         hmfDst = EMF_Create_HENHMETAFILE( emrDst, FALSE );
2567         if (!hmfDst)
2568                 HeapFree( GetProcessHeap(), 0, emrDst );
2569     } else {
2570         HANDLE hFile;
2571         DWORD w;
2572         hFile = CreateFileW( file, GENERIC_WRITE | GENERIC_READ, 0,
2573                              NULL, CREATE_ALWAYS, 0, 0);
2574         WriteFile( hFile, emrSrc, emrSrc->nBytes, &w, NULL);
2575         CloseHandle( hFile );
2576         /* Reopen file for reading only, so that apps can share
2577            read access to the file while hmf is still valid */
2578         hFile = CreateFileW( file, GENERIC_READ, FILE_SHARE_READ,
2579                              NULL, OPEN_EXISTING, 0, 0);
2580         if(hFile == INVALID_HANDLE_VALUE) {
2581             ERR("Can't reopen emf for reading\n");
2582             return 0;
2583         }
2584         hmfDst = EMF_GetEnhMetaFile( hFile );
2585         CloseHandle( hFile );
2586     }
2587     return hmfDst;
2588 }
2589
2590
2591 /* Struct to be used to be passed in the LPVOID parameter for cbEnhPaletteCopy */
2592 typedef struct tagEMF_PaletteCopy
2593 {
2594    UINT cEntries;
2595    LPPALETTEENTRY lpPe;
2596 } EMF_PaletteCopy;
2597
2598 /***************************************************************
2599  * Find the EMR_EOF record and then use it to find the
2600  * palette entries for this enhanced metafile.
2601  * The lpData is actually a pointer to an EMF_PaletteCopy struct
2602  * which contains the max number of elements to copy and where
2603  * to copy them to.
2604  *
2605  * NOTE: To be used by GetEnhMetaFilePaletteEntries only!
2606  */
2607 static INT CALLBACK cbEnhPaletteCopy( HDC a,
2608                                HANDLETABLE *b,
2609                                const ENHMETARECORD *lpEMR,
2610                                INT c,
2611                                LPARAM lpData )
2612 {
2613
2614   if ( lpEMR->iType == EMR_EOF )
2615   {
2616     const EMREOF *lpEof = (const EMREOF *)lpEMR;
2617     EMF_PaletteCopy* info = (EMF_PaletteCopy*)lpData;
2618     DWORD dwNumPalToCopy = min( lpEof->nPalEntries, info->cEntries );
2619
2620     TRACE( "copying 0x%08x palettes\n", dwNumPalToCopy );
2621
2622     memcpy( info->lpPe, (LPCSTR)lpEof + lpEof->offPalEntries,
2623             sizeof( *(info->lpPe) ) * dwNumPalToCopy );
2624
2625     /* Update the passed data as a return code */
2626     info->lpPe     = NULL; /* Palettes were copied! */
2627     info->cEntries = dwNumPalToCopy;
2628
2629     return FALSE; /* That's all we need */
2630   }
2631
2632   return TRUE;
2633 }
2634
2635 /*****************************************************************************
2636  *  GetEnhMetaFilePaletteEntries (GDI32.@)
2637  *
2638  *  Copy the palette and report size
2639  *
2640  *  BUGS: Error codes (SetLastError) are not set on failures
2641  */
2642 UINT WINAPI GetEnhMetaFilePaletteEntries( HENHMETAFILE hEmf,
2643                                           UINT cEntries,
2644                                           LPPALETTEENTRY lpPe )
2645 {
2646   ENHMETAHEADER* enhHeader = EMF_GetEnhMetaHeader( hEmf );
2647   EMF_PaletteCopy infoForCallBack;
2648
2649   TRACE( "(%p,%d,%p)\n", hEmf, cEntries, lpPe );
2650
2651   if (!enhHeader) return 0;
2652
2653   /* First check if there are any palettes associated with
2654      this metafile. */
2655   if ( enhHeader->nPalEntries == 0 ) return 0;
2656
2657   /* Is the user requesting the number of palettes? */
2658   if ( lpPe == NULL ) return enhHeader->nPalEntries;
2659
2660   /* Copy cEntries worth of PALETTEENTRY structs into the buffer */
2661   infoForCallBack.cEntries = cEntries;
2662   infoForCallBack.lpPe     = lpPe;
2663
2664   if ( !EnumEnhMetaFile( 0, hEmf, cbEnhPaletteCopy,
2665                          &infoForCallBack, 0 ) )
2666       return GDI_ERROR;
2667
2668   /* Verify that the callback executed correctly */
2669   if ( infoForCallBack.lpPe != NULL )
2670   {
2671      /* Callback proc had error! */
2672      ERR( "cbEnhPaletteCopy didn't execute correctly\n" );
2673      return GDI_ERROR;
2674   }
2675
2676   return infoForCallBack.cEntries;
2677 }
2678
2679 typedef struct gdi_mf_comment
2680 {
2681     DWORD ident;
2682     DWORD iComment;
2683     DWORD nVersion;
2684     DWORD nChecksum;
2685     DWORD fFlags;
2686     DWORD cbWinMetaFile;
2687 } gdi_mf_comment;
2688
2689 /******************************************************************
2690  *         SetWinMetaFileBits   (GDI32.@)
2691  *
2692  *         Translate from old style to new style.
2693  *
2694  */
2695 HENHMETAFILE WINAPI SetWinMetaFileBits(UINT cbBuffer,
2696                                            CONST BYTE *lpbBuffer,
2697                                            HDC hdcRef,
2698                                            CONST METAFILEPICT *lpmfp
2699                                            )
2700 {
2701     static const WCHAR szDisplayW[] = { 'D','I','S','P','L','A','Y','\0' };
2702     HMETAFILE hmf = NULL;
2703     HENHMETAFILE ret = NULL;
2704     HDC hdc = NULL, hdcdisp = NULL;
2705     RECT rc, *prcFrame = NULL;
2706     LONG mm, xExt, yExt;
2707     INT horzsize, vertsize, horzres, vertres;
2708
2709     TRACE("(%d, %p, %p, %p)\n", cbBuffer, lpbBuffer, hdcRef, lpmfp);
2710
2711     hmf = SetMetaFileBitsEx(cbBuffer, lpbBuffer);
2712     if(!hmf)
2713     {
2714         WARN("SetMetaFileBitsEx failed\n");
2715         return NULL;
2716     }
2717
2718     if(!hdcRef)
2719         hdcRef = hdcdisp = CreateDCW(szDisplayW, NULL, NULL, NULL);
2720
2721     if (lpmfp)
2722     {
2723         TRACE("mm = %d %dx%d\n", lpmfp->mm, lpmfp->xExt, lpmfp->yExt);
2724
2725         mm = lpmfp->mm;
2726         xExt = lpmfp->xExt;
2727         yExt = lpmfp->yExt;
2728     }
2729     else
2730     {
2731         TRACE("lpmfp == NULL\n");
2732
2733         /* Use the whole device surface */
2734         mm = MM_ANISOTROPIC;
2735         xExt = 0;
2736         yExt = 0;
2737     }
2738
2739     if (mm == MM_ISOTROPIC || mm == MM_ANISOTROPIC)
2740     {
2741         if (xExt < 0 || yExt < 0)
2742         {
2743           /* Use the whole device surface */
2744           xExt = 0;
2745           yExt = 0;
2746         }
2747
2748         /* Use the x and y extents as the frame box */
2749         if (xExt && yExt)
2750         {
2751             rc.left = rc.top = 0;
2752             rc.right = xExt;
2753             rc.bottom = yExt;
2754             prcFrame = &rc;
2755         }
2756     }
2757
2758     if(!(hdc = CreateEnhMetaFileW(hdcRef, NULL, prcFrame, NULL)))
2759     {
2760         ERR("CreateEnhMetaFile failed\n");
2761         goto end;
2762     }
2763
2764     /*
2765      * Write the original METAFILE into the enhanced metafile.
2766      * It is encapsulated in a GDICOMMENT_WINDOWS_METAFILE record.
2767      */
2768     if (mm != MM_TEXT)
2769     {
2770         gdi_mf_comment *mfcomment;
2771         UINT mfcomment_size;
2772
2773         mfcomment_size = sizeof (gdi_mf_comment) + cbBuffer;
2774         mfcomment = HeapAlloc(GetProcessHeap(), 0, mfcomment_size);
2775         if (mfcomment)
2776         {
2777             mfcomment->ident = GDICOMMENT_IDENTIFIER;
2778             mfcomment->iComment = GDICOMMENT_WINDOWS_METAFILE;
2779             mfcomment->nVersion = 0x00000300;
2780             mfcomment->nChecksum = 0; /* FIXME */
2781             mfcomment->fFlags = 0;
2782             mfcomment->cbWinMetaFile = cbBuffer;
2783             memcpy(&mfcomment[1], lpbBuffer, cbBuffer);
2784             GdiComment(hdc, mfcomment_size, (BYTE*) mfcomment);
2785             HeapFree(GetProcessHeap(), 0, mfcomment);
2786         }
2787         SetMapMode(hdc, mm);
2788     }
2789
2790
2791     horzsize = GetDeviceCaps(hdcRef, HORZSIZE);
2792     vertsize = GetDeviceCaps(hdcRef, VERTSIZE);
2793     horzres = GetDeviceCaps(hdcRef, HORZRES);
2794     vertres = GetDeviceCaps(hdcRef, VERTRES);
2795
2796     if (!xExt || !yExt)
2797     {
2798         /* Use the whole device surface */
2799        xExt = horzres;
2800        yExt = vertres;
2801     }
2802     else
2803     {
2804         xExt = MulDiv(xExt, horzres, 100 * horzsize);
2805         yExt = MulDiv(yExt, vertres, 100 * vertsize);
2806     }
2807
2808     /* set the initial viewport:window ratio as 1:1 */
2809     SetViewportExtEx(hdc, xExt, yExt, NULL);
2810     SetWindowExtEx(hdc,   xExt, yExt, NULL);
2811
2812     PlayMetaFile(hdc, hmf);
2813
2814     ret = CloseEnhMetaFile(hdc);
2815 end:
2816     if (hdcdisp) DeleteDC(hdcdisp);
2817     DeleteMetaFile(hmf);
2818     return ret;
2819 }