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