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