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