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