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