Corrections to the Win95 and later frame drawing code.
[wine] / objects / enhmetafile.c
1 /*
2  * Enhanced metafile functions
3  * Copyright 1998 Douglas Ridgway
4  *           1999 Huw D M Davies 
5  *
6  * 
7  * The enhanced format consists of the following elements: 
8  *
9  *    A header 
10  *    A table of handles to GDI objects 
11  *    An array of metafile records 
12  *    A private palette 
13  *
14  * 
15  *  The standard format consists of a header and an array of metafile records. 
16  *
17  */ 
18
19 #include <string.h>
20 #include <assert.h>
21 #include "winnls.h"
22 #include "winbase.h"
23 #include "wingdi.h"
24 #include "winerror.h"
25 #include "enhmetafile.h"
26 #include "debugtools.h"
27 #include "heap.h"
28 #include "metafile.h"
29
30 DEFAULT_DEBUG_CHANNEL(enhmetafile);
31
32 /****************************************************************************
33  *          EMF_Create_HENHMETAFILE
34  */
35 HENHMETAFILE EMF_Create_HENHMETAFILE(ENHMETAHEADER *emh, HFILE hFile, HANDLE
36                                      hMapping )
37 {
38     HENHMETAFILE hmf = 0;
39     ENHMETAFILEOBJ *metaObj = GDI_AllocObject( sizeof(ENHMETAFILEOBJ),
40                                                ENHMETAFILE_MAGIC, &hmf );
41     if (metaObj)
42     {
43     metaObj->emh = emh;
44     metaObj->hFile = hFile;
45     metaObj->hMapping = hMapping;
46         GDI_ReleaseObj( hmf );
47     }
48     return hmf;
49 }
50
51 /****************************************************************************
52  *          EMF_Delete_HENHMETAFILE
53  */
54 static BOOL EMF_Delete_HENHMETAFILE( HENHMETAFILE hmf )
55 {
56     ENHMETAFILEOBJ *metaObj = (ENHMETAFILEOBJ *)GDI_GetObjPtr( hmf,
57                                                            ENHMETAFILE_MAGIC );
58     if(!metaObj) return FALSE;
59     if(metaObj->hMapping) {
60         UnmapViewOfFile( metaObj->emh );
61         CloseHandle( metaObj->hMapping );
62         CloseHandle( metaObj->hFile );
63     } else
64         HeapFree( GetProcessHeap(), 0, metaObj->emh );
65     return GDI_FreeObject( hmf, metaObj );
66 }
67
68 /******************************************************************
69  *         EMF_GetEnhMetaHeader
70  *
71  * Returns ptr to ENHMETAHEADER associated with HENHMETAFILE
72  * Should be followed by call to EMF_ReleaseEnhMetaHeader
73  */
74 static ENHMETAHEADER *EMF_GetEnhMetaHeader( HENHMETAFILE hmf )
75 {
76     ENHMETAFILEOBJ *metaObj = (ENHMETAFILEOBJ *)GDI_GetObjPtr( hmf,
77                                                            ENHMETAFILE_MAGIC );
78     TRACE("hmf %04x -> enhmetaObj %p\n", hmf, metaObj);
79     return metaObj ? metaObj->emh : NULL;
80 }
81
82 /******************************************************************
83  *         EMF_ReleaseEnhMetaHeader
84  *
85  * Releases ENHMETAHEADER associated with HENHMETAFILE
86  */
87 static void EMF_ReleaseEnhMetaHeader( HENHMETAFILE hmf )
88 {
89     GDI_ReleaseObj( hmf );
90 }
91
92 /*****************************************************************************
93  *         EMF_GetEnhMetaFile
94  *
95  */
96 static HENHMETAFILE EMF_GetEnhMetaFile( HANDLE hFile )
97 {
98     ENHMETAHEADER *emh;
99     HANDLE hMapping;
100     
101     hMapping = CreateFileMappingA( hFile, NULL, PAGE_READONLY, 0, 0, NULL );
102     emh = MapViewOfFile( hMapping, FILE_MAP_READ, 0, 0, 0 );
103
104     if (emh->iType != EMR_HEADER || emh->dSignature != ENHMETA_SIGNATURE) {
105         WARN("Invalid emf header type 0x%08lx sig 0x%08lx.\n",
106              emh->iType, emh->dSignature);
107         UnmapViewOfFile( emh );
108         CloseHandle( hMapping );
109         return 0;
110     }
111     return EMF_Create_HENHMETAFILE( emh, hFile, hMapping );
112 }
113
114
115 /*****************************************************************************
116  *          GetEnhMetaFileA (GDI32.@)
117  *
118  *
119  */
120 HENHMETAFILE WINAPI GetEnhMetaFileA( 
121              LPCSTR lpszMetaFile  /* [in] filename of enhanced metafile */
122     )
123 {
124     HENHMETAFILE hmf;
125     HANDLE hFile;
126
127     hFile = CreateFileA(lpszMetaFile, GENERIC_READ, FILE_SHARE_READ, 0,
128                         OPEN_EXISTING, 0, 0);
129     if (hFile == INVALID_HANDLE_VALUE) {
130         WARN("could not open %s\n", lpszMetaFile);
131         return 0;
132     }
133     hmf = EMF_GetEnhMetaFile( hFile );
134     if(!hmf)
135         CloseHandle( hFile );
136     return hmf;
137 }
138
139 /*****************************************************************************
140  *          GetEnhMetaFileW  (GDI32.@)
141  */
142 HENHMETAFILE WINAPI GetEnhMetaFileW(
143              LPCWSTR lpszMetaFile)  /* [in] filename of enhanced metafile */ 
144 {
145     HENHMETAFILE hmf;
146     HANDLE hFile;
147
148     hFile = CreateFileW(lpszMetaFile, GENERIC_READ, FILE_SHARE_READ, 0,
149                         OPEN_EXISTING, 0, 0);
150     if (hFile == INVALID_HANDLE_VALUE) {
151         WARN("could not open %s\n", debugstr_w(lpszMetaFile));
152         return 0;
153     }
154     hmf = EMF_GetEnhMetaFile( hFile );
155     if(!hmf)
156         CloseHandle( hFile );
157     return hmf;
158 }
159
160 /*****************************************************************************
161  *        GetEnhMetaFileHeader  (GDI32.@)
162  *
163  *  If buf is NULL, returns the size of buffer required.
164  *  Otherwise, copy up to bufsize bytes of enhanced metafile header into 
165  *  buf.
166  */
167 UINT WINAPI GetEnhMetaFileHeader( 
168        HENHMETAFILE hmf,   /* [in] enhanced metafile */
169        UINT bufsize,       /* [in] size of buffer */
170        LPENHMETAHEADER buf /* [out] buffer */ 
171     )
172 {
173     LPENHMETAHEADER emh;
174     UINT size;
175
176     emh = EMF_GetEnhMetaHeader(hmf);
177     if(!emh) return FALSE;
178     size = emh->nSize;
179     if (!buf) {
180         EMF_ReleaseEnhMetaHeader(hmf);
181         return size;
182     }
183     size = min(size, bufsize);
184     memmove(buf, emh, size);
185     EMF_ReleaseEnhMetaHeader(hmf);
186     return size;
187 }
188
189
190 /*****************************************************************************
191  *          GetEnhMetaFileDescriptionA  (GDI32.@)
192  */
193 UINT WINAPI GetEnhMetaFileDescriptionA( 
194        HENHMETAFILE hmf, /* [in] enhanced metafile */
195        UINT size,        /* [in] size of buf */ 
196        LPSTR buf         /* [out] buffer to receive description */
197     )
198 {
199      LPENHMETAHEADER emh = EMF_GetEnhMetaHeader(hmf);
200      DWORD len;
201      WCHAR *descrW;
202
203      if(!emh) return FALSE;
204      if(emh->nDescription == 0 || emh->offDescription == 0) {
205          EMF_ReleaseEnhMetaHeader(hmf);
206         return 0;
207      }
208      descrW = (WCHAR *) ((char *) emh + emh->offDescription);
209      len = WideCharToMultiByte( CP_ACP, 0, descrW, emh->nDescription, NULL, 0, NULL, NULL );
210
211      if (!buf || !size ) {
212          EMF_ReleaseEnhMetaHeader(hmf);
213          return len;
214      }
215
216      len = min( size, len );
217      WideCharToMultiByte( CP_ACP, 0, descrW, emh->nDescription, buf, len, NULL, NULL );
218      EMF_ReleaseEnhMetaHeader(hmf);
219      return len;
220 }
221
222 /*****************************************************************************
223  *          GetEnhMetaFileDescriptionW  (GDI32.@)
224  *
225  *  Copies the description string of an enhanced metafile into a buffer 
226  *  _buf_.
227  *
228  *  If _buf_ is NULL, returns size of _buf_ required. Otherwise, returns
229  *  number of characters copied.
230  */
231 UINT WINAPI GetEnhMetaFileDescriptionW( 
232        HENHMETAFILE hmf, /* [in] enhanced metafile */
233        UINT size,        /* [in] size of buf */ 
234        LPWSTR buf        /* [out] buffer to receive description */
235     )
236 {
237      LPENHMETAHEADER emh = EMF_GetEnhMetaHeader(hmf);
238
239      if(!emh) return FALSE;
240      if(emh->nDescription == 0 || emh->offDescription == 0) {
241          EMF_ReleaseEnhMetaHeader(hmf);
242         return 0;
243      }
244      if (!buf || !size ) {
245          EMF_ReleaseEnhMetaHeader(hmf);
246         return emh->nDescription;
247      }
248  
249      memmove(buf, (char *) emh + emh->offDescription, 
250             min(size,emh->nDescription)*sizeof(WCHAR));
251      EMF_ReleaseEnhMetaHeader(hmf);
252      return min(size, emh->nDescription);
253 }
254
255 /****************************************************************************
256  *    SetEnhMetaFileBits (GDI32.@)
257  *
258  *  Creates an enhanced metafile by copying _bufsize_ bytes from _buf_.
259  */
260 HENHMETAFILE WINAPI SetEnhMetaFileBits(UINT bufsize, const BYTE *buf)
261 {
262     ENHMETAHEADER *emh = HeapAlloc( GetProcessHeap(), 0, bufsize );
263     memmove(emh, buf, bufsize);
264     return EMF_Create_HENHMETAFILE( emh, 0, 0 );
265 }
266
267 /*****************************************************************************
268  *  GetEnhMetaFileBits (GDI32.@)
269  *
270  */
271 UINT WINAPI GetEnhMetaFileBits(
272     HENHMETAFILE hmf, 
273     UINT bufsize, 
274     LPBYTE buf  
275
276 {
277     LPENHMETAHEADER emh = EMF_GetEnhMetaHeader( hmf );
278     UINT size;
279
280     if(!emh) return 0;
281
282     size = emh->nBytes;
283     if( buf == NULL ) {
284         EMF_ReleaseEnhMetaHeader( hmf ); 
285         return size;
286     }
287
288     size = min( size, bufsize );
289     memmove(buf, emh, size);
290
291     EMF_ReleaseEnhMetaHeader( hmf ); 
292     return size;
293 }
294
295 /*****************************************************************************
296  *           PlayEnhMetaFileRecord  (GDI32.@)
297  *
298  *  Render a single enhanced metafile record in the device context hdc.
299  *
300  *  RETURNS
301  *    TRUE (non zero) on success, FALSE on error.
302  *  BUGS
303  *    Many unimplemented records.
304  *    No error handling on record play failures (ie checking return codes)
305  */
306 BOOL WINAPI PlayEnhMetaFileRecord( 
307      HDC hdc,                   /* [in] device context in which to render EMF record */
308      LPHANDLETABLE handletable, /* [in] array of handles to be used in rendering record */
309      const ENHMETARECORD *mr,   /* [in] EMF record to render */
310      UINT handles               /* [in] size of handle array */
311      ) 
312 {
313   int type;
314   TRACE(
315         "hdc = %08x, handletable = %p, record = %p, numHandles = %d\n", 
316           hdc, handletable, mr, handles);
317   if (!mr) return FALSE;
318
319   type = mr->iType;
320
321   TRACE(" type=%d\n", type);
322   switch(type) 
323     {
324     case EMR_HEADER:
325       break;
326     case EMR_EOF:
327       break;
328     case EMR_GDICOMMENT:
329       {
330         PEMRGDICOMMENT lpGdiComment = (PEMRGDICOMMENT)mr;
331         /* In an enhanced metafile, there can be both public and private GDI comments */
332         GdiComment( hdc, lpGdiComment->cbData, lpGdiComment->Data );
333         break;
334       } 
335     case EMR_SETMAPMODE:
336       {
337         PEMRSETMAPMODE pSetMapMode = (PEMRSETMAPMODE) mr;
338         SetMapMode(hdc, pSetMapMode->iMode);
339         break;
340       }
341     case EMR_SETBKMODE:
342       {
343         PEMRSETBKMODE pSetBkMode = (PEMRSETBKMODE) mr;
344         SetBkMode(hdc, pSetBkMode->iMode);
345         break;
346       }
347     case EMR_SETBKCOLOR:
348       {
349         PEMRSETBKCOLOR pSetBkColor = (PEMRSETBKCOLOR) mr;
350         SetBkColor(hdc, pSetBkColor->crColor);
351         break;
352       }
353     case EMR_SETPOLYFILLMODE:
354       {
355         PEMRSETPOLYFILLMODE pSetPolyFillMode = (PEMRSETPOLYFILLMODE) mr;
356         SetPolyFillMode(hdc, pSetPolyFillMode->iMode);
357         break;
358       }
359     case EMR_SETROP2:
360       {
361         PEMRSETROP2 pSetROP2 = (PEMRSETROP2) mr;
362         SetROP2(hdc, pSetROP2->iMode);
363         break;
364       }
365     case EMR_SETSTRETCHBLTMODE:
366       {
367         PEMRSETSTRETCHBLTMODE pSetStretchBltMode = (PEMRSETSTRETCHBLTMODE) mr;
368         SetStretchBltMode(hdc, pSetStretchBltMode->iMode);
369         break;
370       }
371     case EMR_SETTEXTALIGN:
372       {
373         PEMRSETTEXTALIGN pSetTextAlign = (PEMRSETTEXTALIGN) mr;
374         SetTextAlign(hdc, pSetTextAlign->iMode);
375         break;
376       }
377     case EMR_SETTEXTCOLOR:
378       {
379         PEMRSETTEXTCOLOR pSetTextColor = (PEMRSETTEXTCOLOR) mr;
380         SetTextColor(hdc, pSetTextColor->crColor);
381         break;
382       }
383     case EMR_SAVEDC:
384       {
385         SaveDC(hdc);
386         break;
387       }
388     case EMR_RESTOREDC:
389       {
390         PEMRRESTOREDC pRestoreDC = (PEMRRESTOREDC) mr;
391         RestoreDC(hdc, pRestoreDC->iRelative);
392         break;
393       }
394     case EMR_INTERSECTCLIPRECT:
395       {
396         PEMRINTERSECTCLIPRECT pClipRect = (PEMRINTERSECTCLIPRECT) mr;
397         IntersectClipRect(hdc, pClipRect->rclClip.left, pClipRect->rclClip.top,
398                           pClipRect->rclClip.right, pClipRect->rclClip.bottom);
399         break;
400       }
401     case EMR_SELECTOBJECT:
402       {
403         PEMRSELECTOBJECT pSelectObject = (PEMRSELECTOBJECT) mr;
404         if( pSelectObject->ihObject & 0x80000000 ) {
405           /* High order bit is set - it's a stock object
406            * Strip the high bit to get the index.
407            * See MSDN article Q142319
408            */
409           SelectObject( hdc, GetStockObject( pSelectObject->ihObject &
410                                              0x7fffffff ) );
411         } else {
412           /* High order bit wasn't set - not a stock object
413            */
414               SelectObject( hdc,
415                         (handletable->objectHandle)[pSelectObject->ihObject] );
416         }
417         break;
418       }
419     case EMR_DELETEOBJECT:
420       {
421         PEMRDELETEOBJECT pDeleteObject = (PEMRDELETEOBJECT) mr;
422         DeleteObject( (handletable->objectHandle)[pDeleteObject->ihObject]);
423         (handletable->objectHandle)[pDeleteObject->ihObject] = 0;
424         break;
425       }
426     case EMR_SETWINDOWORGEX:
427       {
428           /*
429            * FIXME: The call to SetWindowOrgEx prevents EMFs from being scrolled
430            *        by an application. This is very BAD!!!
431            */
432 #if 0
433         PEMRSETWINDOWORGEX pSetWindowOrgEx = (PEMRSETWINDOWORGEX) mr;
434         SetWindowOrgEx(hdc, pSetWindowOrgEx->ptlOrigin.x,
435                        pSetWindowOrgEx->ptlOrigin.y, NULL);
436 #endif
437         break;
438       }
439     case EMR_SETWINDOWEXTEX:
440       {
441         PEMRSETWINDOWEXTEX pSetWindowExtEx = (PEMRSETWINDOWEXTEX) mr;
442         SetWindowExtEx(hdc, pSetWindowExtEx->szlExtent.cx,
443                        pSetWindowExtEx->szlExtent.cy, NULL);
444         break;
445       }
446     case EMR_SETVIEWPORTORGEX:
447       {
448         PEMRSETVIEWPORTORGEX pSetViewportOrgEx = (PEMRSETVIEWPORTORGEX) mr;
449         SetViewportOrgEx(hdc, pSetViewportOrgEx->ptlOrigin.x,
450                          pSetViewportOrgEx->ptlOrigin.y, NULL);
451         break;
452       }
453     case EMR_SETVIEWPORTEXTEX:
454       {
455         PEMRSETVIEWPORTEXTEX pSetViewportExtEx = (PEMRSETVIEWPORTEXTEX) mr;
456         SetViewportExtEx(hdc, pSetViewportExtEx->szlExtent.cx,
457                          pSetViewportExtEx->szlExtent.cy, NULL);
458         break;
459       }
460     case EMR_CREATEPEN:
461       {
462         PEMRCREATEPEN pCreatePen = (PEMRCREATEPEN) mr;
463         (handletable->objectHandle)[pCreatePen->ihPen] = 
464           CreatePenIndirect(&pCreatePen->lopn);
465         break;
466       }
467     case EMR_EXTCREATEPEN:
468       {
469         PEMREXTCREATEPEN pPen = (PEMREXTCREATEPEN) mr;
470         LOGBRUSH lb;
471         lb.lbStyle = pPen->elp.elpBrushStyle;
472         lb.lbColor = pPen->elp.elpColor;
473         lb.lbHatch = pPen->elp.elpHatch;
474
475         if(pPen->offBmi || pPen->offBits)
476           FIXME("EMR_EXTCREATEPEN: Need to copy brush bitmap\n");
477
478         (handletable->objectHandle)[pPen->ihPen] = 
479           ExtCreatePen(pPen->elp.elpPenStyle, pPen->elp.elpWidth, &lb, 
480                        pPen->elp.elpNumEntries, pPen->elp.elpStyleEntry);
481         break;
482       }
483     case EMR_CREATEBRUSHINDIRECT:
484       {
485         PEMRCREATEBRUSHINDIRECT pBrush = (PEMRCREATEBRUSHINDIRECT) mr;
486         (handletable->objectHandle)[pBrush->ihBrush] = 
487           CreateBrushIndirect(&pBrush->lb);
488         break;
489       }
490     case EMR_EXTCREATEFONTINDIRECTW:
491       {
492         PEMREXTCREATEFONTINDIRECTW pFont = (PEMREXTCREATEFONTINDIRECTW) mr;
493         (handletable->objectHandle)[pFont->ihFont] = 
494           CreateFontIndirectW(&pFont->elfw.elfLogFont);
495         break;
496       }
497     case EMR_MOVETOEX:
498       {
499         PEMRMOVETOEX pMoveToEx = (PEMRMOVETOEX) mr;
500         MoveToEx(hdc, pMoveToEx->ptl.x, pMoveToEx->ptl.y, NULL);
501         break;
502       }
503     case EMR_LINETO:
504       {
505         PEMRLINETO pLineTo = (PEMRLINETO) mr;
506         LineTo(hdc, pLineTo->ptl.x, pLineTo->ptl.y);
507         break;
508       }
509     case EMR_RECTANGLE:
510       {
511         PEMRRECTANGLE pRect = (PEMRRECTANGLE) mr;
512         Rectangle(hdc, pRect->rclBox.left, pRect->rclBox.top,
513                   pRect->rclBox.right, pRect->rclBox.bottom);
514         break;
515       }
516     case EMR_ELLIPSE:
517       {
518         PEMRELLIPSE pEllipse = (PEMRELLIPSE) mr;
519         Ellipse(hdc, pEllipse->rclBox.left, pEllipse->rclBox.top,
520                 pEllipse->rclBox.right, pEllipse->rclBox.bottom);
521         break;
522       }
523     case EMR_POLYGON16:
524       {
525         PEMRPOLYGON16 pPoly = (PEMRPOLYGON16) mr;
526         /* Shouldn't use Polygon16 since pPoly->cpts is DWORD */
527         POINT *pts = HeapAlloc( GetProcessHeap(), 0,
528                                 pPoly->cpts * sizeof(POINT) );
529         DWORD i;
530         for(i = 0; i < pPoly->cpts; i++)
531           CONV_POINT16TO32(pPoly->apts + i, pts + i);
532         Polygon(hdc, pts, pPoly->cpts);
533         HeapFree( GetProcessHeap(), 0, pts );
534         break;
535       }
536     case EMR_POLYLINE16:
537       {
538         PEMRPOLYLINE16 pPoly = (PEMRPOLYLINE16) mr;
539         /* Shouldn't use Polyline16 since pPoly->cpts is DWORD */
540         POINT *pts = HeapAlloc( GetProcessHeap(), 0,
541                                 pPoly->cpts * sizeof(POINT) );
542         DWORD i;
543         for(i = 0; i < pPoly->cpts; i++)
544           CONV_POINT16TO32(pPoly->apts + i, pts + i);
545         Polyline(hdc, pts, pPoly->cpts);
546         HeapFree( GetProcessHeap(), 0, pts );
547         break;
548       }
549     case EMR_POLYLINETO16:
550       {
551         PEMRPOLYLINETO16 pPoly = (PEMRPOLYLINETO16) mr;
552         /* Shouldn't use PolylineTo16 since pPoly->cpts is DWORD */
553         POINT *pts = HeapAlloc( GetProcessHeap(), 0,
554                                 pPoly->cpts * sizeof(POINT) );
555         DWORD i;
556         for(i = 0; i < pPoly->cpts; i++)
557           CONV_POINT16TO32(pPoly->apts + i, pts + i);
558         PolylineTo(hdc, pts, pPoly->cpts);
559         HeapFree( GetProcessHeap(), 0, pts );
560         break;
561       }
562     case EMR_POLYBEZIER16:
563       {
564         PEMRPOLYBEZIER16 pPoly = (PEMRPOLYBEZIER16) mr;
565         /* Shouldn't use PolyBezier16 since pPoly->cpts is DWORD */
566         POINT *pts = HeapAlloc( GetProcessHeap(), 0,
567                                 pPoly->cpts * sizeof(POINT) );
568         DWORD i;
569         for(i = 0; i < pPoly->cpts; i++)
570           CONV_POINT16TO32(pPoly->apts + i, pts + i);
571         PolyBezier(hdc, pts, pPoly->cpts);
572         HeapFree( GetProcessHeap(), 0, pts );
573         break;
574       }
575     case EMR_POLYBEZIERTO16:
576       {
577         PEMRPOLYBEZIERTO16 pPoly = (PEMRPOLYBEZIERTO16) mr;
578         /* Shouldn't use PolyBezierTo16 since pPoly->cpts is DWORD */
579         POINT *pts = HeapAlloc( GetProcessHeap(), 0,
580                                 pPoly->cpts * sizeof(POINT) );
581         DWORD i;
582         for(i = 0; i < pPoly->cpts; i++)
583           CONV_POINT16TO32(pPoly->apts + i, pts + i);
584         PolyBezierTo(hdc, pts, pPoly->cpts);
585         HeapFree( GetProcessHeap(), 0, pts );
586         break;
587       }
588     case EMR_POLYPOLYGON16:
589       {
590         PEMRPOLYPOLYGON16 pPolyPoly = (PEMRPOLYPOLYGON16) mr;
591         /* NB POINTS array doesn't start at pPolyPoly->apts it's actually
592            pPolyPoly->aPolyCounts + pPolyPoly->nPolys */
593
594         POINT *pts = HeapAlloc( GetProcessHeap(), 0,
595                                 pPolyPoly->cpts * sizeof(POINT) );
596         DWORD i;
597         for(i = 0; i < pPolyPoly->cpts; i++)
598           CONV_POINT16TO32((POINT16*) (pPolyPoly->aPolyCounts +
599                                       pPolyPoly->nPolys) + i, pts + i);
600
601         PolyPolygon(hdc, pts, (INT*)pPolyPoly->aPolyCounts, pPolyPoly->nPolys);
602         HeapFree( GetProcessHeap(), 0, pts );
603         break;
604       }
605     case EMR_POLYPOLYLINE16:
606       {
607         PEMRPOLYPOLYLINE16 pPolyPoly = (PEMRPOLYPOLYLINE16) mr;
608         /* NB POINTS array doesn't start at pPolyPoly->apts it's actually
609            pPolyPoly->aPolyCounts + pPolyPoly->nPolys */
610
611         POINT *pts = HeapAlloc( GetProcessHeap(), 0,
612                                 pPolyPoly->cpts * sizeof(POINT) );
613         DWORD i;
614         for(i = 0; i < pPolyPoly->cpts; i++)
615           CONV_POINT16TO32((POINT16*) (pPolyPoly->aPolyCounts +
616                                       pPolyPoly->nPolys) + i, pts + i);
617
618         PolyPolyline(hdc, pts, pPolyPoly->aPolyCounts, pPolyPoly->nPolys);
619         HeapFree( GetProcessHeap(), 0, pts );
620         break;
621       }
622
623     case EMR_STRETCHDIBITS:
624       {
625         EMRSTRETCHDIBITS *pStretchDIBits = (EMRSTRETCHDIBITS *)mr;
626
627         StretchDIBits(hdc,
628                       pStretchDIBits->xDest,
629                       pStretchDIBits->yDest,
630                       pStretchDIBits->cxDest,
631                       pStretchDIBits->cyDest,
632                       pStretchDIBits->xSrc,
633                       pStretchDIBits->ySrc,
634                       pStretchDIBits->cxSrc,
635                       pStretchDIBits->cySrc,
636                       (BYTE *)mr + pStretchDIBits->offBitsSrc,
637                       (const BITMAPINFO *)((BYTE *)mr + pStretchDIBits->offBmiSrc),
638                       pStretchDIBits->iUsageSrc,
639                       pStretchDIBits->dwRop);
640         break;
641       }
642
643     case EMR_EXTTEXTOUTA:
644     {
645         PEMREXTTEXTOUTA pExtTextOutA = (PEMREXTTEXTOUTA)mr;
646         RECT rc;
647
648         rc.left = pExtTextOutA->emrtext.rcl.left;
649         rc.top = pExtTextOutA->emrtext.rcl.top;
650         rc.right = pExtTextOutA->emrtext.rcl.right;
651         rc.bottom = pExtTextOutA->emrtext.rcl.bottom;
652         ExtTextOutA(hdc, pExtTextOutA->emrtext.ptlReference.x, pExtTextOutA->emrtext.ptlReference.y,
653             pExtTextOutA->emrtext.fOptions, &rc,
654             (LPSTR)((BYTE *)mr + pExtTextOutA->emrtext.offString), pExtTextOutA->emrtext.nChars,
655             (INT *)((BYTE *)mr + pExtTextOutA->emrtext.offDx));
656         break;
657     }
658
659     case EMR_EXTTEXTOUTW:
660     {
661         PEMREXTTEXTOUTW pExtTextOutW = (PEMREXTTEXTOUTW)mr;
662         RECT rc;
663
664         rc.left = pExtTextOutW->emrtext.rcl.left;
665         rc.top = pExtTextOutW->emrtext.rcl.top;
666         rc.right = pExtTextOutW->emrtext.rcl.right;
667         rc.bottom = pExtTextOutW->emrtext.rcl.bottom;
668         ExtTextOutW(hdc, pExtTextOutW->emrtext.ptlReference.x, pExtTextOutW->emrtext.ptlReference.y,
669             pExtTextOutW->emrtext.fOptions, &rc,
670             (LPWSTR)((BYTE *)mr + pExtTextOutW->emrtext.offString), pExtTextOutW->emrtext.nChars,
671             (INT *)((BYTE *)mr + pExtTextOutW->emrtext.offDx));
672         break;
673     }
674
675     case EMR_CREATEPALETTE:
676       {
677         PEMRCREATEPALETTE lpCreatePal = (PEMRCREATEPALETTE)mr;
678
679         (handletable->objectHandle)[ lpCreatePal->ihPal ] = 
680                 CreatePalette( &lpCreatePal->lgpl );
681
682         break;
683       }
684
685     case EMR_SELECTPALETTE:
686       {
687         PEMRSELECTPALETTE lpSelectPal = (PEMRSELECTPALETTE)mr;
688
689         if( lpSelectPal->ihPal & 0x80000000 ) {
690                 SelectPalette( hdc, GetStockObject(lpSelectPal->ihPal & 0x7fffffff), TRUE);
691         } else {
692         (handletable->objectHandle)[ lpSelectPal->ihPal ] =
693                 SelectPalette( hdc, (handletable->objectHandle)[lpSelectPal->ihPal], TRUE);
694         }
695         break;
696       }
697
698     case EMR_REALIZEPALETTE:
699       {
700         RealizePalette( hdc );
701         break;
702       }
703
704     case EMR_EXTSELECTCLIPRGN:
705       {
706         PEMREXTSELECTCLIPRGN lpRgn = (PEMREXTSELECTCLIPRGN)mr;
707         HRGN hRgn = ExtCreateRegion(NULL, lpRgn->cbRgnData, (RGNDATA *)lpRgn->RgnData);
708         ExtSelectClipRgn(hdc, hRgn, (INT)(lpRgn->iMode));
709         /* ExtSelectClipRgn created a copy of the region */
710         DeleteObject(hRgn);
711         break;
712       }
713
714     case EMR_SETMETARGN:
715       {
716         SetMetaRgn( hdc );
717         break;
718       }
719
720     case EMR_SETWORLDTRANSFORM:
721       {
722         PEMRSETWORLDTRANSFORM lpXfrm = (PEMRSETWORLDTRANSFORM)mr;
723         SetWorldTransform( hdc, &lpXfrm->xform );
724         break;
725       }
726
727     case EMR_POLYBEZIER:
728       {
729         PEMRPOLYBEZIER lpPolyBez = (PEMRPOLYBEZIER)mr; 
730         PolyBezier(hdc, (const LPPOINT)lpPolyBez->aptl, (UINT)lpPolyBez->cptl);
731         break;
732       }
733
734     case EMR_POLYGON:
735       {
736         PEMRPOLYGON lpPoly = (PEMRPOLYGON)mr;
737         Polygon( hdc, (const LPPOINT)lpPoly->aptl, (UINT)lpPoly->cptl );
738         break;
739       }
740
741     case EMR_POLYLINE:
742       {
743         PEMRPOLYLINE lpPolyLine = (PEMRPOLYLINE)mr;
744         Polyline(hdc, (const LPPOINT)lpPolyLine->aptl, (UINT)lpPolyLine->cptl);
745         break; 
746       }
747
748     case EMR_POLYBEZIERTO:
749       {
750         PEMRPOLYBEZIERTO lpPolyBezierTo = (PEMRPOLYBEZIERTO)mr;
751         PolyBezierTo( hdc, (const LPPOINT)lpPolyBezierTo->aptl,
752                       (UINT)lpPolyBezierTo->cptl );
753         break; 
754       }
755
756     case EMR_POLYLINETO:
757       {
758         PEMRPOLYLINETO lpPolyLineTo = (PEMRPOLYLINETO)mr;
759         PolylineTo( hdc, (const LPPOINT)lpPolyLineTo->aptl,
760                     (UINT)lpPolyLineTo->cptl );
761         break;
762       }
763
764     case EMR_POLYPOLYLINE:
765       {
766         PEMRPOLYPOLYLINE pPolyPolyline = (PEMRPOLYPOLYLINE) mr;
767         /* NB Points at pPolyPolyline->aPolyCounts + pPolyPolyline->nPolys */
768
769         PolyPolyline(hdc, (LPPOINT)(pPolyPolyline->aPolyCounts +
770                                     pPolyPolyline->nPolys), 
771                      pPolyPolyline->aPolyCounts, 
772                      pPolyPolyline->nPolys ); 
773
774         break;
775       }
776
777     case EMR_POLYPOLYGON:
778       {
779         PEMRPOLYPOLYGON pPolyPolygon = (PEMRPOLYPOLYGON) mr;
780
781         /* NB Points at pPolyPolygon->aPolyCounts + pPolyPolygon->nPolys */
782
783         PolyPolygon(hdc, (LPPOINT)(pPolyPolygon->aPolyCounts +
784                                    pPolyPolygon->nPolys),
785                     (INT*)pPolyPolygon->aPolyCounts, pPolyPolygon->nPolys );
786         break;
787       }
788
789     case EMR_SETBRUSHORGEX:
790       {
791         PEMRSETBRUSHORGEX lpSetBrushOrgEx = (PEMRSETBRUSHORGEX)mr;
792
793         SetBrushOrgEx( hdc, 
794                        (INT)lpSetBrushOrgEx->ptlOrigin.x, 
795                        (INT)lpSetBrushOrgEx->ptlOrigin.y, 
796                        NULL );
797
798         break;
799       }
800  
801     case EMR_SETPIXELV:
802       {
803         PEMRSETPIXELV lpSetPixelV = (PEMRSETPIXELV)mr;
804
805         SetPixelV( hdc, 
806                    (INT)lpSetPixelV->ptlPixel.x, 
807                    (INT)lpSetPixelV->ptlPixel.y, 
808                    lpSetPixelV->crColor );
809
810         break;
811       }
812
813     case EMR_SETMAPPERFLAGS:
814       {
815         PEMRSETMAPPERFLAGS lpSetMapperFlags = (PEMRSETMAPPERFLAGS)mr;
816    
817         SetMapperFlags( hdc, lpSetMapperFlags->dwFlags );
818
819         break;
820       }
821
822     case EMR_SETCOLORADJUSTMENT:
823       {
824         PEMRSETCOLORADJUSTMENT lpSetColorAdjust = (PEMRSETCOLORADJUSTMENT)mr; 
825
826         SetColorAdjustment( hdc, &lpSetColorAdjust->ColorAdjustment );
827
828         break;
829       }
830
831     case EMR_OFFSETCLIPRGN:
832       {
833         PEMROFFSETCLIPRGN lpOffsetClipRgn = (PEMROFFSETCLIPRGN)mr;
834
835         OffsetClipRgn( hdc, 
836                        (INT)lpOffsetClipRgn->ptlOffset.x,
837                        (INT)lpOffsetClipRgn->ptlOffset.y );
838
839         break;
840       } 
841
842     case EMR_EXCLUDECLIPRECT:
843       {
844         PEMREXCLUDECLIPRECT lpExcludeClipRect = (PEMREXCLUDECLIPRECT)mr;
845
846         ExcludeClipRect( hdc, 
847                          lpExcludeClipRect->rclClip.left, 
848                          lpExcludeClipRect->rclClip.top, 
849                          lpExcludeClipRect->rclClip.right, 
850                          lpExcludeClipRect->rclClip.bottom  );
851
852          break;
853       }
854
855     case EMR_SCALEVIEWPORTEXTEX:
856       {
857         PEMRSCALEVIEWPORTEXTEX lpScaleViewportExtEx = (PEMRSCALEVIEWPORTEXTEX)mr;
858
859         ScaleViewportExtEx( hdc, 
860                             lpScaleViewportExtEx->xNum,
861                             lpScaleViewportExtEx->xDenom,
862                             lpScaleViewportExtEx->yNum,
863                             lpScaleViewportExtEx->yDenom,
864                             NULL );
865      
866         break;
867       }
868  
869     case EMR_SCALEWINDOWEXTEX:
870       {
871         PEMRSCALEWINDOWEXTEX lpScaleWindowExtEx = (PEMRSCALEWINDOWEXTEX)mr;
872
873         ScaleWindowExtEx( hdc,
874                           lpScaleWindowExtEx->xNum,
875                           lpScaleWindowExtEx->xDenom,
876                           lpScaleWindowExtEx->yNum,
877                           lpScaleWindowExtEx->yDenom, 
878                           NULL );
879
880         break;
881       }
882
883     case EMR_MODIFYWORLDTRANSFORM:
884       {
885         PEMRMODIFYWORLDTRANSFORM lpModifyWorldTrans = (PEMRMODIFYWORLDTRANSFORM)mr;
886
887         ModifyWorldTransform( hdc, &lpModifyWorldTrans->xform,
888                               lpModifyWorldTrans->iMode );
889
890         break;
891       }
892
893     case EMR_ANGLEARC:
894       {
895         PEMRANGLEARC lpAngleArc = (PEMRANGLEARC)mr; 
896
897         AngleArc( hdc, 
898                  (INT)lpAngleArc->ptlCenter.x, (INT)lpAngleArc->ptlCenter.y,
899                  lpAngleArc->nRadius, lpAngleArc->eStartAngle, 
900                  lpAngleArc->eSweepAngle );
901
902         break;
903       }
904  
905     case EMR_ROUNDRECT: 
906       {
907         PEMRROUNDRECT lpRoundRect = (PEMRROUNDRECT)mr;
908
909         RoundRect( hdc, 
910                    lpRoundRect->rclBox.left,
911                    lpRoundRect->rclBox.top,
912                    lpRoundRect->rclBox.right,
913                    lpRoundRect->rclBox.bottom,
914                    lpRoundRect->szlCorner.cx,
915                    lpRoundRect->szlCorner.cy );
916
917         break; 
918       }
919
920     case EMR_ARC:
921       {
922         PEMRARC lpArc = (PEMRARC)mr;
923
924         Arc( hdc,  
925              (INT)lpArc->rclBox.left,
926              (INT)lpArc->rclBox.top,
927              (INT)lpArc->rclBox.right,
928              (INT)lpArc->rclBox.bottom,
929              (INT)lpArc->ptlStart.x, 
930              (INT)lpArc->ptlStart.y,
931              (INT)lpArc->ptlEnd.x,
932              (INT)lpArc->ptlEnd.y );
933
934         break;  
935       }
936
937     case EMR_CHORD:
938       {
939         PEMRCHORD lpChord = (PEMRCHORD)mr;
940
941         Chord( hdc,
942              (INT)lpChord->rclBox.left,
943              (INT)lpChord->rclBox.top,
944              (INT)lpChord->rclBox.right,
945              (INT)lpChord->rclBox.bottom,
946              (INT)lpChord->ptlStart.x,
947              (INT)lpChord->ptlStart.y,
948              (INT)lpChord->ptlEnd.x,
949              (INT)lpChord->ptlEnd.y );
950
951         break;
952       }
953
954     case EMR_PIE:
955       {
956         PEMRPIE lpPie = (PEMRPIE)mr;
957
958         Pie( hdc,
959              (INT)lpPie->rclBox.left,
960              (INT)lpPie->rclBox.top,
961              (INT)lpPie->rclBox.right,
962              (INT)lpPie->rclBox.bottom,
963              (INT)lpPie->ptlStart.x,
964              (INT)lpPie->ptlStart.y,
965              (INT)lpPie->ptlEnd.x,
966              (INT)lpPie->ptlEnd.y );
967
968        break;
969       }
970
971     case EMR_ARCTO: 
972       {
973         PEMRARC lpArcTo = (PEMRARC)mr;
974
975         ArcTo( hdc,
976                (INT)lpArcTo->rclBox.left,
977                (INT)lpArcTo->rclBox.top,
978                (INT)lpArcTo->rclBox.right,
979                (INT)lpArcTo->rclBox.bottom,
980                (INT)lpArcTo->ptlStart.x,
981                (INT)lpArcTo->ptlStart.y,
982                (INT)lpArcTo->ptlEnd.x,
983                (INT)lpArcTo->ptlEnd.y );
984
985         break;
986       }
987
988     case EMR_EXTFLOODFILL:
989       {
990         PEMREXTFLOODFILL lpExtFloodFill = (PEMREXTFLOODFILL)mr;
991
992         ExtFloodFill( hdc, 
993                       (INT)lpExtFloodFill->ptlStart.x,
994                       (INT)lpExtFloodFill->ptlStart.y,
995                       lpExtFloodFill->crColor,
996                       (UINT)lpExtFloodFill->iMode );
997
998         break;
999       }
1000
1001     case EMR_POLYDRAW:
1002       {
1003         PEMRPOLYDRAW lpPolyDraw = (PEMRPOLYDRAW)mr;
1004         PolyDraw( hdc, 
1005                   (const LPPOINT)lpPolyDraw->aptl,
1006                   lpPolyDraw->abTypes,
1007                   (INT)lpPolyDraw->cptl );
1008  
1009         break;
1010       } 
1011
1012     case EMR_SETARCDIRECTION:
1013       {
1014         PEMRSETARCDIRECTION lpSetArcDirection = (PEMRSETARCDIRECTION)mr;
1015         SetArcDirection( hdc, (INT)lpSetArcDirection->iArcDirection );
1016         break;
1017       }
1018
1019     case EMR_SETMITERLIMIT:
1020       {
1021         PEMRSETMITERLIMIT lpSetMiterLimit = (PEMRSETMITERLIMIT)mr;
1022         SetMiterLimit( hdc, lpSetMiterLimit->eMiterLimit, NULL );
1023         break;
1024       } 
1025
1026     case EMR_BEGINPATH:
1027       {
1028         BeginPath( hdc );
1029         break;
1030       }
1031
1032     case EMR_ENDPATH: 
1033       {
1034         EndPath( hdc );
1035         break;
1036       }
1037
1038     case EMR_CLOSEFIGURE:
1039       {
1040         CloseFigure( hdc );
1041         break;
1042       }
1043
1044     case EMR_FILLPATH:
1045       {
1046         /*PEMRFILLPATH lpFillPath = (PEMRFILLPATH)mr;*/
1047         FillPath( hdc );
1048         break;
1049       }
1050
1051     case EMR_STROKEANDFILLPATH:
1052       {
1053         /*PEMRSTROKEANDFILLPATH lpStrokeAndFillPath = (PEMRSTROKEANDFILLPATH)mr;*/
1054         StrokeAndFillPath( hdc );
1055         break;
1056       }
1057
1058     case EMR_STROKEPATH:
1059       {
1060         /*PEMRSTROKEPATH lpStrokePath = (PEMRSTROKEPATH)mr;*/
1061         StrokePath( hdc );
1062         break;
1063       }
1064
1065     case EMR_FLATTENPATH:
1066       {
1067         FlattenPath( hdc ); 
1068         break;
1069       }
1070
1071     case EMR_WIDENPATH:
1072       {
1073         WidenPath( hdc );
1074         break;
1075       }
1076
1077     case EMR_SELECTCLIPPATH:
1078       {
1079         PEMRSELECTCLIPPATH lpSelectClipPath = (PEMRSELECTCLIPPATH)mr;
1080         SelectClipPath( hdc, (INT)lpSelectClipPath->iMode );
1081         break;
1082       }
1083  
1084     case EMR_ABORTPATH:
1085       {
1086         AbortPath( hdc );
1087         break;
1088       }
1089
1090     case EMR_CREATECOLORSPACE:
1091       {
1092         PEMRCREATECOLORSPACE lpCreateColorSpace = (PEMRCREATECOLORSPACE)mr;
1093         (handletable->objectHandle)[lpCreateColorSpace->ihCS] = 
1094            CreateColorSpaceA( &lpCreateColorSpace->lcs ); 
1095         break;
1096       }
1097
1098     case EMR_SETCOLORSPACE:
1099       {
1100         PEMRSETCOLORSPACE lpSetColorSpace = (PEMRSETCOLORSPACE)mr; 
1101         SetColorSpace( hdc, 
1102                        (handletable->objectHandle)[lpSetColorSpace->ihCS] );
1103         break;
1104       }
1105
1106     case EMR_DELETECOLORSPACE:
1107       {
1108         PEMRDELETECOLORSPACE lpDeleteColorSpace = (PEMRDELETECOLORSPACE)mr;
1109         DeleteColorSpace( (handletable->objectHandle)[lpDeleteColorSpace->ihCS] );
1110         break; 
1111       }
1112
1113     case EMR_SETICMMODE:
1114       {
1115         PERMSETICMMODE lpSetICMMode = (PERMSETICMMODE)mr;
1116         SetICMMode( hdc, (INT)lpSetICMMode->iMode );
1117         break;
1118       }
1119
1120     case EMR_PIXELFORMAT: 
1121       {
1122         INT iPixelFormat;
1123         PEMRPIXELFORMAT lpPixelFormat = (PEMRPIXELFORMAT)mr;
1124
1125         iPixelFormat = ChoosePixelFormat( hdc, &lpPixelFormat->pfd );
1126         SetPixelFormat( hdc, iPixelFormat, &lpPixelFormat->pfd ); 
1127          
1128         break;
1129       }
1130
1131     case EMR_SETPALETTEENTRIES:  
1132       {
1133         PEMRSETPALETTEENTRIES lpSetPaletteEntries = (PEMRSETPALETTEENTRIES)mr;
1134
1135         SetPaletteEntries( (handletable->objectHandle)[lpSetPaletteEntries->ihPal],
1136                            (UINT)lpSetPaletteEntries->iStart,
1137                            (UINT)lpSetPaletteEntries->cEntries,
1138                            lpSetPaletteEntries->aPalEntries ); 
1139                            
1140         break;
1141       }
1142
1143     case EMR_RESIZEPALETTE:
1144       {
1145         PEMRRESIZEPALETTE lpResizePalette = (PEMRRESIZEPALETTE)mr;
1146
1147         ResizePalette( (handletable->objectHandle)[lpResizePalette->ihPal],
1148                        (UINT)lpResizePalette->cEntries );
1149
1150         break;
1151       }
1152
1153     case EMR_CREATEDIBPATTERNBRUSHPT:
1154       {
1155         PEMRCREATEDIBPATTERNBRUSHPT lpCreate = (PEMRCREATEDIBPATTERNBRUSHPT)mr;
1156
1157         /* This is a BITMAPINFO struct followed directly by bitmap bits */
1158         LPVOID lpPackedStruct = HeapAlloc( GetProcessHeap(), 
1159                                            0, 
1160                                            lpCreate->cbBmi + lpCreate->cbBits );
1161         /* Now pack this structure */
1162         memcpy( lpPackedStruct, 
1163                 ((BYTE*)lpCreate) + lpCreate->offBmi,
1164                 lpCreate->cbBmi ); 
1165         memcpy( ((BYTE*)lpPackedStruct) + lpCreate->cbBmi,
1166                 ((BYTE*)lpCreate) + lpCreate->offBits,
1167                 lpCreate->cbBits );
1168
1169         (handletable->objectHandle)[lpCreate->ihBrush] = 
1170            CreateDIBPatternBrushPt( lpPackedStruct,
1171                                     (UINT)lpCreate->iUsage ); 
1172
1173         break; 
1174       }
1175
1176     case EMR_CREATEMONOBRUSH:
1177     {
1178         PEMRCREATEMONOBRUSH pCreateMonoBrush = (PEMRCREATEMONOBRUSH)mr;
1179         BITMAPINFO *pbi = (BITMAPINFO *)((BYTE *)mr + pCreateMonoBrush->offBmi);
1180         HBITMAP hBmp = CreateDIBitmap(0, (BITMAPINFOHEADER *)pbi, CBM_INIT,
1181                 (BYTE *)mr + pCreateMonoBrush->offBits, pbi, pCreateMonoBrush->iUsage);
1182         (handletable->objectHandle)[pCreateMonoBrush->ihBrush] = CreatePatternBrush(hBmp);
1183         /* CreatePatternBrush created a copy of the bitmap */
1184         DeleteObject(hBmp);
1185         break;
1186     }
1187
1188     case EMR_BITBLT:
1189     {
1190         PEMRBITBLT pBitBlt = (PEMRBITBLT)mr;
1191         HDC hdcSrc = CreateCompatibleDC(hdc);
1192         HBRUSH hBrush, hBrushOld;
1193         HBITMAP hBmp, hBmpOld;
1194         BITMAPINFO *pbi = (BITMAPINFO *)((BYTE *)mr + pBitBlt->offBmiSrc);
1195
1196         SetWorldTransform(hdcSrc, &pBitBlt->xformSrc);
1197
1198         hBrush = CreateSolidBrush(pBitBlt->crBkColorSrc);
1199         hBrushOld = SelectObject(hdcSrc, hBrush);
1200         PatBlt(hdcSrc, pBitBlt->rclBounds.left, pBitBlt->rclBounds.top,
1201                pBitBlt->rclBounds.right - pBitBlt->rclBounds.left,
1202                pBitBlt->rclBounds.bottom - pBitBlt->rclBounds.top, PATCOPY);
1203         SelectObject(hdcSrc, hBrushOld);
1204         DeleteObject(hBrush);
1205
1206         hBmp = CreateDIBitmap(0, (BITMAPINFOHEADER *)pbi, CBM_INIT,
1207                               (BYTE *)mr + pBitBlt->offBitsSrc, pbi, pBitBlt->iUsageSrc);
1208         hBmpOld = SelectObject(hdcSrc, hBmp);
1209         BitBlt(hdc,
1210                pBitBlt->xDest,
1211                pBitBlt->yDest,
1212                pBitBlt->cxDest,
1213                pBitBlt->cyDest,
1214                hdcSrc,
1215                pBitBlt->xSrc,
1216                pBitBlt->ySrc,
1217                pBitBlt->dwRop);
1218         SelectObject(hdcSrc, hBmpOld);
1219         DeleteObject(hBmp);
1220         DeleteDC(hdcSrc);
1221         break;
1222     }
1223
1224     case EMR_STRETCHBLT:
1225     {
1226         PEMRSTRETCHBLT pStretchBlt= (PEMRSTRETCHBLT)mr;
1227         HDC hdcSrc = CreateCompatibleDC(hdc);
1228         HBRUSH hBrush, hBrushOld;
1229         HBITMAP hBmp, hBmpOld;
1230         BITMAPINFO *pbi = (BITMAPINFO *)((BYTE *)mr + pStretchBlt->offBmiSrc);
1231
1232         SetWorldTransform(hdcSrc, &pStretchBlt->xformSrc);
1233
1234         hBrush = CreateSolidBrush(pStretchBlt->crBkColorSrc);
1235         hBrushOld = SelectObject(hdcSrc, hBrush);
1236         PatBlt(hdcSrc, pStretchBlt->rclBounds.left, pStretchBlt->rclBounds.top,
1237                pStretchBlt->rclBounds.right - pStretchBlt->rclBounds.left,
1238                pStretchBlt->rclBounds.bottom - pStretchBlt->rclBounds.top, PATCOPY);
1239         SelectObject(hdcSrc, hBrushOld);
1240         DeleteObject(hBrush);
1241
1242         hBmp = CreateDIBitmap(0, (BITMAPINFOHEADER *)pbi, CBM_INIT,
1243                               (BYTE *)mr + pStretchBlt->offBitsSrc, pbi, pStretchBlt->iUsageSrc);
1244         hBmpOld = SelectObject(hdcSrc, hBmp);
1245         StretchBlt(hdc,
1246                pStretchBlt->xDest,
1247                pStretchBlt->yDest,
1248                pStretchBlt->cxDest,
1249                pStretchBlt->cyDest,
1250                hdcSrc,
1251                pStretchBlt->xSrc,
1252                pStretchBlt->ySrc,
1253                pStretchBlt->cxSrc,
1254                pStretchBlt->cySrc,
1255                pStretchBlt->dwRop);
1256         SelectObject(hdcSrc, hBmpOld);
1257         DeleteObject(hBmp);
1258         DeleteDC(hdcSrc);
1259         break;
1260     }
1261
1262     case EMR_MASKBLT:
1263     {
1264         PEMRMASKBLT pMaskBlt= (PEMRMASKBLT)mr;
1265         HDC hdcSrc = CreateCompatibleDC(hdc);
1266         HBRUSH hBrush, hBrushOld;
1267         HBITMAP hBmp, hBmpOld, hBmpMask;
1268         BITMAPINFO *pbi;
1269
1270         SetWorldTransform(hdcSrc, &pMaskBlt->xformSrc);
1271
1272         hBrush = CreateSolidBrush(pMaskBlt->crBkColorSrc);
1273         hBrushOld = SelectObject(hdcSrc, hBrush);
1274         PatBlt(hdcSrc, pMaskBlt->rclBounds.left, pMaskBlt->rclBounds.top,
1275                pMaskBlt->rclBounds.right - pMaskBlt->rclBounds.left,
1276                pMaskBlt->rclBounds.bottom - pMaskBlt->rclBounds.top, PATCOPY);
1277         SelectObject(hdcSrc, hBrushOld);
1278         DeleteObject(hBrush);
1279
1280         pbi = (BITMAPINFO *)((BYTE *)mr + pMaskBlt->offBmiMask);
1281         hBmpMask = CreateDIBitmap(0, (BITMAPINFOHEADER *)pbi, CBM_INIT,
1282                               (BYTE *)mr + pMaskBlt->offBitsMask, pbi, pMaskBlt->iUsageMask);
1283
1284         pbi = (BITMAPINFO *)((BYTE *)mr + pMaskBlt->offBmiSrc);
1285         hBmp = CreateDIBitmap(0, (BITMAPINFOHEADER *)pbi, CBM_INIT,
1286                               (BYTE *)mr + pMaskBlt->offBitsSrc, pbi, pMaskBlt->iUsageSrc);
1287         hBmpOld = SelectObject(hdcSrc, hBmp);
1288         MaskBlt(hdc,
1289                 pMaskBlt->xDest,
1290                 pMaskBlt->yDest,
1291                 pMaskBlt->cxDest,
1292                 pMaskBlt->cyDest,
1293                 hdcSrc,
1294                 pMaskBlt->xSrc,
1295                 pMaskBlt->ySrc,
1296                 hBmpMask,
1297                 pMaskBlt->xMask,
1298                 pMaskBlt->yMask,
1299                 pMaskBlt->dwRop);
1300         SelectObject(hdcSrc, hBmpOld);
1301         DeleteObject(hBmp);
1302         DeleteObject(hBmpMask);
1303         DeleteDC(hdcSrc);
1304         break;
1305     }
1306
1307     case EMR_PLGBLT:
1308     {
1309         PEMRPLGBLT pPlgBlt= (PEMRPLGBLT)mr;
1310         HDC hdcSrc = CreateCompatibleDC(hdc);
1311         HBRUSH hBrush, hBrushOld;
1312         HBITMAP hBmp, hBmpOld, hBmpMask;
1313         BITMAPINFO *pbi;
1314         POINT pts[3];
1315
1316         SetWorldTransform(hdcSrc, &pPlgBlt->xformSrc);
1317
1318         pts[0].x = pPlgBlt->aptlDst[0].x; pts[0].y = pPlgBlt->aptlDst[0].y;
1319         pts[1].x = pPlgBlt->aptlDst[1].x; pts[1].y = pPlgBlt->aptlDst[1].y;
1320         pts[2].x = pPlgBlt->aptlDst[2].x; pts[2].y = pPlgBlt->aptlDst[2].y;
1321
1322         hBrush = CreateSolidBrush(pPlgBlt->crBkColorSrc);
1323         hBrushOld = SelectObject(hdcSrc, hBrush);
1324         PatBlt(hdcSrc, pPlgBlt->rclBounds.left, pPlgBlt->rclBounds.top,
1325                pPlgBlt->rclBounds.right - pPlgBlt->rclBounds.left,
1326                pPlgBlt->rclBounds.bottom - pPlgBlt->rclBounds.top, PATCOPY);
1327         SelectObject(hdcSrc, hBrushOld);
1328         DeleteObject(hBrush);
1329
1330         pbi = (BITMAPINFO *)((BYTE *)mr + pPlgBlt->offBmiMask);
1331         hBmpMask = CreateDIBitmap(0, (BITMAPINFOHEADER *)pbi, CBM_INIT,
1332                               (BYTE *)mr + pPlgBlt->offBitsMask, pbi, pPlgBlt->iUsageMask);
1333
1334         pbi = (BITMAPINFO *)((BYTE *)mr + pPlgBlt->offBmiSrc);
1335         hBmp = CreateDIBitmap(0, (BITMAPINFOHEADER *)pbi, CBM_INIT,
1336                               (BYTE *)mr + pPlgBlt->offBitsSrc, pbi, pPlgBlt->iUsageSrc);
1337         hBmpOld = SelectObject(hdcSrc, hBmp);
1338         PlgBlt(hdc,
1339                pts,
1340                hdcSrc,
1341                pPlgBlt->xSrc,
1342                pPlgBlt->ySrc,
1343                pPlgBlt->cxSrc,
1344                pPlgBlt->cySrc,
1345                hBmpMask,
1346                pPlgBlt->xMask,
1347                pPlgBlt->yMask);
1348         SelectObject(hdcSrc, hBmpOld);
1349         DeleteObject(hBmp);
1350         DeleteObject(hBmpMask);
1351         DeleteDC(hdcSrc);
1352         break;
1353     }
1354
1355     case EMR_SETDIBITSTODEVICE:
1356     {
1357         PEMRSETDIBITSTODEVICE pSetDIBitsToDevice = (PEMRSETDIBITSTODEVICE)mr;
1358
1359         SetDIBitsToDevice(hdc,
1360                           pSetDIBitsToDevice->xDest,
1361                           pSetDIBitsToDevice->yDest,
1362                           pSetDIBitsToDevice->cxSrc,
1363                           pSetDIBitsToDevice->cySrc,
1364                           pSetDIBitsToDevice->xSrc,
1365                           pSetDIBitsToDevice->ySrc,
1366                           pSetDIBitsToDevice->iStartScan,
1367                           pSetDIBitsToDevice->cScans,
1368                           (BYTE *)mr + pSetDIBitsToDevice->offBitsSrc,
1369                           (BITMAPINFO *)((BYTE *)mr + pSetDIBitsToDevice->offBmiSrc),
1370                           pSetDIBitsToDevice->iUsageSrc);
1371         break;
1372     }
1373
1374     case EMR_POLYTEXTOUTA:
1375     {
1376         PEMRPOLYTEXTOUTA pPolyTextOutA = (PEMRPOLYTEXTOUTA)mr;
1377         POLYTEXTA *polytextA = HeapAlloc(GetProcessHeap(), 0, pPolyTextOutA->cStrings * sizeof(POLYTEXTA));
1378         LONG i;
1379         XFORM xform, xformOld;
1380         int gModeOld;
1381
1382         gModeOld = SetGraphicsMode(hdc, pPolyTextOutA->iGraphicsMode);
1383         GetWorldTransform(hdc, &xformOld);
1384
1385         xform.eM11 = pPolyTextOutA->exScale;
1386         xform.eM12 = 0.0;
1387         xform.eM21 = 0.0;
1388         xform.eM22 = pPolyTextOutA->eyScale;
1389         xform.eDx = 0.0;
1390         xform.eDy = 0.0;
1391         SetWorldTransform(hdc, &xform);
1392
1393         /* Set up POLYTEXTA structures */
1394         for(i = 0; i < pPolyTextOutA->cStrings; i++)
1395         {
1396             polytextA[i].x = pPolyTextOutA->aemrtext[i].ptlReference.x;
1397             polytextA[i].y = pPolyTextOutA->aemrtext[i].ptlReference.y;
1398             polytextA[i].n = pPolyTextOutA->aemrtext[i].nChars;
1399             polytextA[i].lpstr = (LPSTR)((BYTE *)mr + pPolyTextOutA->aemrtext[i].offString);
1400             polytextA[i].uiFlags = pPolyTextOutA->aemrtext[i].fOptions;
1401             polytextA[i].rcl.left = pPolyTextOutA->aemrtext[i].rcl.left;
1402             polytextA[i].rcl.right = pPolyTextOutA->aemrtext[i].rcl.right;
1403             polytextA[i].rcl.top = pPolyTextOutA->aemrtext[i].rcl.top;
1404             polytextA[i].rcl.bottom = pPolyTextOutA->aemrtext[i].rcl.bottom;
1405             polytextA[i].pdx = (int *)((BYTE *)mr + pPolyTextOutA->aemrtext[i].offDx);
1406         }
1407         PolyTextOutA(hdc, polytextA, pPolyTextOutA->cStrings);
1408         HeapFree(GetProcessHeap(), 0, polytextA);
1409
1410         SetWorldTransform(hdc, &xformOld);
1411         SetGraphicsMode(hdc, gModeOld);
1412         break;
1413     }
1414
1415     case EMR_POLYTEXTOUTW:
1416     {
1417         PEMRPOLYTEXTOUTW pPolyTextOutW = (PEMRPOLYTEXTOUTW)mr;
1418         POLYTEXTW *polytextW = HeapAlloc(GetProcessHeap(), 0, pPolyTextOutW->cStrings * sizeof(POLYTEXTW));
1419         LONG i;
1420         XFORM xform, xformOld;
1421         int gModeOld;
1422
1423         gModeOld = SetGraphicsMode(hdc, pPolyTextOutW->iGraphicsMode);
1424         GetWorldTransform(hdc, &xformOld);
1425
1426         xform.eM11 = pPolyTextOutW->exScale;
1427         xform.eM12 = 0.0;
1428         xform.eM21 = 0.0;
1429         xform.eM22 = pPolyTextOutW->eyScale;
1430         xform.eDx = 0.0;
1431         xform.eDy = 0.0;
1432         SetWorldTransform(hdc, &xform);
1433
1434         /* Set up POLYTEXTW structures */
1435         for(i = 0; i < pPolyTextOutW->cStrings; i++)
1436         {
1437             polytextW[i].x = pPolyTextOutW->aemrtext[i].ptlReference.x;
1438             polytextW[i].y = pPolyTextOutW->aemrtext[i].ptlReference.y;
1439             polytextW[i].n = pPolyTextOutW->aemrtext[i].nChars;
1440             polytextW[i].lpstr = (LPWSTR)((BYTE *)mr + pPolyTextOutW->aemrtext[i].offString);
1441             polytextW[i].uiFlags = pPolyTextOutW->aemrtext[i].fOptions;
1442             polytextW[i].rcl.left = pPolyTextOutW->aemrtext[i].rcl.left;
1443             polytextW[i].rcl.right = pPolyTextOutW->aemrtext[i].rcl.right;
1444             polytextW[i].rcl.top = pPolyTextOutW->aemrtext[i].rcl.top;
1445             polytextW[i].rcl.bottom = pPolyTextOutW->aemrtext[i].rcl.bottom;
1446             polytextW[i].pdx = (int *)((BYTE *)mr + pPolyTextOutW->aemrtext[i].offDx);
1447         }
1448         PolyTextOutW(hdc, polytextW, pPolyTextOutW->cStrings);
1449         HeapFree(GetProcessHeap(), 0, polytextW);
1450
1451         SetWorldTransform(hdc, &xformOld);
1452         SetGraphicsMode(hdc, gModeOld);
1453         break;
1454     }
1455
1456     case EMR_FILLRGN:
1457     {
1458         PEMRFILLRGN pFillRgn = (PEMRFILLRGN)mr;
1459         HRGN hRgn = ExtCreateRegion(NULL, pFillRgn->cbRgnData, (RGNDATA *)pFillRgn->RgnData);
1460         FillRgn(hdc,
1461                 hRgn,
1462                 (handletable->objectHandle)[pFillRgn->ihBrush]);
1463         DeleteObject(hRgn);
1464         break;
1465     }
1466
1467     case EMR_FRAMERGN:
1468     {
1469         PEMRFRAMERGN pFrameRgn = (PEMRFRAMERGN)mr;
1470         HRGN hRgn = ExtCreateRegion(NULL, pFrameRgn->cbRgnData, (RGNDATA *)pFrameRgn->RgnData);
1471         FrameRgn(hdc,
1472                  hRgn,
1473                  (handletable->objectHandle)[pFrameRgn->ihBrush],
1474                  pFrameRgn->szlStroke.cx,
1475                  pFrameRgn->szlStroke.cy);
1476         DeleteObject(hRgn);
1477         break;
1478     }
1479
1480     case EMR_INVERTRGN:
1481     {
1482         PEMRINVERTRGN pInvertRgn = (PEMRINVERTRGN)mr;
1483         HRGN hRgn = ExtCreateRegion(NULL, pInvertRgn->cbRgnData, (RGNDATA *)pInvertRgn->RgnData);
1484         InvertRgn(hdc, hRgn);
1485         DeleteObject(hRgn);
1486         break;
1487     }
1488
1489     case EMR_PAINTRGN:
1490     {
1491         PEMRPAINTRGN pPaintRgn = (PEMRPAINTRGN)mr;
1492         HRGN hRgn = ExtCreateRegion(NULL, pPaintRgn->cbRgnData, (RGNDATA *)pPaintRgn->RgnData);
1493         PaintRgn(hdc, hRgn);
1494         DeleteObject(hRgn);
1495         break;
1496     }
1497
1498     case EMR_POLYDRAW16:
1499     case EMR_GLSRECORD:
1500     case EMR_GLSBOUNDEDRECORD:
1501     default:
1502       /* From docs: If PlayEnhMetaFileRecord doesn't recognize a 
1503                     record then ignore and return TRUE. */
1504       FIXME("type %d is unimplemented\n", type);
1505       break;
1506     }
1507   return TRUE;
1508 }
1509
1510
1511 /*****************************************************************************
1512  *
1513  *        EnumEnhMetaFile  (GDI32.@)
1514  *
1515  *  Walk an enhanced metafile, calling a user-specified function _EnhMetaFunc_
1516  *  for each
1517  *  record. Returns when either every record has been used or 
1518  *  when _EnhMetaFunc_ returns FALSE.
1519  *
1520  *
1521  * RETURNS
1522  *  TRUE if every record is used, FALSE if any invocation of _EnhMetaFunc_
1523  *  returns FALSE.
1524  *
1525  * BUGS
1526  *   Ignores rect.
1527  */
1528 BOOL WINAPI EnumEnhMetaFile( 
1529      HDC hdc,                /* [in] device context to pass to _EnhMetaFunc_ */
1530      HENHMETAFILE hmf,       /* [in] EMF to walk */
1531      ENHMFENUMPROC callback, /* [in] callback function */ 
1532      LPVOID data,            /* [in] optional data for callback function */
1533      const RECT *lpRect      /* [in] bounding rectangle for rendered metafile */
1534     )
1535 {
1536     BOOL ret;
1537     ENHMETAHEADER *emh, *emhTemp;
1538     ENHMETARECORD *emr;
1539     DWORD offset;
1540     UINT i;
1541     HANDLETABLE *ht;
1542     INT savedMode = 0;
1543     FLOAT xSrcPixSize, ySrcPixSize, xscale, yscale;
1544     XFORM savedXform, xform;
1545     HPEN hPen = (HPEN)NULL;
1546     HBRUSH hBrush = (HBRUSH)NULL;
1547     HFONT hFont = (HFONT)NULL;
1548
1549     if(!lpRect)
1550     {
1551         SetLastError(ERROR_INVALID_PARAMETER);
1552         return FALSE;
1553     }
1554
1555     emh = EMF_GetEnhMetaHeader(hmf);
1556     if(!emh) {
1557         SetLastError(ERROR_INVALID_HANDLE);
1558         return FALSE;
1559     }
1560
1561     /* Copy the metafile into memory, because we need to avoid deadlock. */
1562     emhTemp = HeapAlloc(GetProcessHeap(), 0, emh->nSize + emh->nBytes);
1563     if(!emhTemp)
1564     {
1565         EMF_ReleaseEnhMetaHeader(hmf);
1566         SetLastError(ERROR_NOT_ENOUGH_MEMORY);
1567         return FALSE;
1568     }
1569     memcpy(emhTemp, emh, emh->nSize + emh->nBytes);
1570     emh = emhTemp;
1571     EMF_ReleaseEnhMetaHeader(hmf);
1572
1573     ht = HeapAlloc( GetProcessHeap(), HEAP_ZERO_MEMORY,
1574                     sizeof(HANDLETABLE) * emh->nHandles );
1575     if(!ht)
1576     {
1577         HeapFree(GetProcessHeap(), 0, emhTemp);
1578         SetLastError(ERROR_NOT_ENOUGH_MEMORY);
1579         return FALSE;
1580     }
1581     ht->objectHandle[0] = hmf;
1582
1583     if (hdc)
1584     {
1585         TRACE("rect: %d,%d - %d,%d. rclFrame: %ld,%ld - %ld,%ld\n",
1586               lpRect->left, lpRect->top, lpRect->right, lpRect->bottom,
1587               emh->rclFrame.left, emh->rclFrame.top, emh->rclFrame.right,
1588               emh->rclFrame.bottom);
1589
1590         xSrcPixSize = (FLOAT) emh->szlMillimeters.cx / emh->szlDevice.cx;
1591         ySrcPixSize = (FLOAT) emh->szlMillimeters.cy / emh->szlDevice.cy;
1592         xscale = (FLOAT)(lpRect->right - lpRect->left) * 100.0 /
1593           (emh->rclFrame.right - emh->rclFrame.left) * xSrcPixSize;
1594         yscale = (FLOAT)(lpRect->bottom - lpRect->top) * 100.0 /
1595           (emh->rclFrame.bottom - emh->rclFrame.top) * ySrcPixSize;
1596
1597         xform.eM11 = xscale;
1598         xform.eM12 = 0;
1599         xform.eM21 = 0;
1600         xform.eM22 = yscale;
1601         xform.eDx = (FLOAT) lpRect->left - (lpRect->right - lpRect->left) *
1602           emh->rclFrame.left / (emh->rclFrame.right - emh->rclFrame.left);
1603         xform.eDy = (FLOAT) lpRect->top - (lpRect->bottom - lpRect->top) *
1604           emh->rclFrame.top / (emh->rclFrame.bottom - emh->rclFrame.top);
1605
1606         savedMode = SetGraphicsMode(hdc, GM_ADVANCED);
1607         GetWorldTransform(hdc, &savedXform);
1608
1609         if (!ModifyWorldTransform(hdc, &xform, MWT_RIGHTMULTIPLY)) {
1610             ERR("World transform failed!\n");
1611         }
1612
1613         /* save the current pen, brush and font */
1614         hPen = GetCurrentObject(hdc, OBJ_PEN);
1615         hBrush = GetCurrentObject(hdc, OBJ_BRUSH);
1616         hFont = GetCurrentObject(hdc, OBJ_FONT);
1617     }
1618
1619     TRACE("nSize = %ld, nBytes = %ld, nHandles = %d, nRecords = %ld, nPalEntries = %ld\n",
1620         emh->nSize, emh->nBytes, emh->nHandles, emh->nRecords, emh->nPalEntries);
1621
1622     ret = TRUE;
1623     offset = 0;
1624     while(ret && offset < emh->nBytes)
1625     {
1626         emr = (ENHMETARECORD *)((char *)emh + offset);
1627         TRACE("Calling EnumFunc with record type %ld, size %ld\n", emr->iType, emr->nSize);
1628         ret = (*callback)(hdc, ht, emr, emh->nHandles, data);
1629         offset += emr->nSize;
1630     }
1631
1632     if (hdc)
1633     {
1634         /* restore pen, brush and font */
1635         SelectObject(hdc, hBrush);
1636         SelectObject(hdc, hPen);
1637         SelectObject(hdc, hFont);
1638
1639         SetWorldTransform(hdc, &savedXform);
1640         if (savedMode)
1641             SetGraphicsMode(hdc, savedMode);
1642     }
1643
1644     for(i = 1; i < emh->nHandles; i++) /* Don't delete element 0 (hmf) */
1645         if( (ht->objectHandle)[i] )
1646             DeleteObject( (ht->objectHandle)[i] );
1647
1648     HeapFree( GetProcessHeap(), 0, ht );
1649     HeapFree(GetProcessHeap(), 0, emhTemp);
1650
1651     return ret;
1652 }
1653
1654 static INT CALLBACK EMF_PlayEnhMetaFileCallback(HDC hdc, HANDLETABLE *ht,
1655                                                 ENHMETARECORD *emr,
1656                                                 INT handles, LPVOID data)
1657 {
1658     return PlayEnhMetaFileRecord(hdc, ht, emr, handles);
1659 }
1660                                                 
1661 /**************************************************************************
1662  *    PlayEnhMetaFile  (GDI32.@)
1663  *
1664  *    Renders an enhanced metafile into a specified rectangle *lpRect
1665  *    in device context hdc.
1666  *
1667  */
1668 BOOL WINAPI PlayEnhMetaFile( 
1669        HDC hdc,           /* [in] DC to render into */
1670        HENHMETAFILE hmf,  /* [in] metafile to render */
1671        const RECT *lpRect /* [in] rectangle to place metafile inside */
1672       )
1673 {
1674     return EnumEnhMetaFile(hdc, hmf, EMF_PlayEnhMetaFileCallback, NULL,
1675                            lpRect);
1676 }
1677
1678 /*****************************************************************************
1679  *  DeleteEnhMetaFile (GDI32.@)
1680  *
1681  *  Deletes an enhanced metafile and frees the associated storage.
1682  */
1683 BOOL WINAPI DeleteEnhMetaFile(HENHMETAFILE hmf)
1684 {
1685     return EMF_Delete_HENHMETAFILE( hmf );
1686 }
1687
1688 /*****************************************************************************
1689  *  CopyEnhMetaFileA (GDI32.@)  Duplicate an enhanced metafile
1690  *
1691  *   
1692  */
1693 HENHMETAFILE WINAPI CopyEnhMetaFileA(
1694     HENHMETAFILE hmfSrc, 
1695     LPCSTR file)
1696 {
1697     ENHMETAHEADER *emrSrc = EMF_GetEnhMetaHeader( hmfSrc ), *emrDst;
1698     HENHMETAFILE hmfDst;
1699
1700     if(!emrSrc) return FALSE;
1701     if (!file) {
1702         emrDst = HeapAlloc( GetProcessHeap(), 0, emrSrc->nBytes );
1703         memcpy( emrDst, emrSrc, emrSrc->nBytes );
1704         hmfDst = EMF_Create_HENHMETAFILE( emrDst, 0, 0 );
1705     } else {
1706         HANDLE hFile;
1707         hFile = CreateFileA( file, GENERIC_WRITE | GENERIC_READ, 0, NULL,
1708                              CREATE_ALWAYS, 0, 0);
1709         WriteFile( hFile, emrSrc, emrSrc->nBytes, 0, 0);
1710         hmfDst = EMF_GetEnhMetaFile( hFile );
1711     }
1712     EMF_ReleaseEnhMetaHeader( hmfSrc );
1713     return hmfDst;
1714 }
1715
1716
1717 /* Struct to be used to be passed in the LPVOID parameter for cbEnhPaletteCopy */
1718 typedef struct tagEMF_PaletteCopy
1719 {
1720    UINT cEntries;
1721    LPPALETTEENTRY lpPe;
1722 } EMF_PaletteCopy;
1723
1724 /***************************************************************  
1725  * Find the EMR_EOF record and then use it to find the
1726  * palette entries for this enhanced metafile. 
1727  * The lpData is actually a pointer to a EMF_PaletteCopy struct  
1728  * which contains the max number of elements to copy and where
1729  * to copy them to.
1730  *
1731  * NOTE: To be used by GetEnhMetaFilePaletteEntries only!
1732  */
1733 INT CALLBACK cbEnhPaletteCopy( HDC a,
1734                                LPHANDLETABLE b,
1735                                LPENHMETARECORD lpEMR,
1736                                INT c,
1737                                LPVOID lpData )
1738 {
1739  
1740   if ( lpEMR->iType == EMR_EOF )
1741   {
1742     PEMREOF lpEof = (PEMREOF)lpEMR;
1743     EMF_PaletteCopy* info = (EMF_PaletteCopy*)lpData;
1744     DWORD dwNumPalToCopy = min( lpEof->nPalEntries, info->cEntries );
1745
1746     TRACE( "copying 0x%08lx palettes\n", dwNumPalToCopy );
1747
1748     memcpy( (LPVOID)info->lpPe, 
1749             (LPVOID)(((LPSTR)lpEof) + lpEof->offPalEntries), 
1750             sizeof( *(info->lpPe) ) * dwNumPalToCopy );
1751
1752     /* Update the passed data as a return code */
1753     info->lpPe     = NULL; /* Palettes were copied! */
1754     info->cEntries = (UINT)dwNumPalToCopy;  
1755
1756     return FALSE; /* That's all we need */
1757   }
1758   
1759   return TRUE;
1760 }
1761
1762 /*****************************************************************************
1763  *  GetEnhMetaFilePaletteEntries (GDI32.@)  
1764  * 
1765  *  Copy the palette and report size  
1766  * 
1767  *  BUGS: Error codes (SetLastError) are not set on failures
1768  */
1769 UINT WINAPI GetEnhMetaFilePaletteEntries( HENHMETAFILE hEmf,
1770                                           UINT cEntries,
1771                                           LPPALETTEENTRY lpPe )
1772 {
1773   ENHMETAHEADER* enhHeader = EMF_GetEnhMetaHeader( hEmf );
1774   UINT uReturnValue = GDI_ERROR;
1775   EMF_PaletteCopy infoForCallBack; 
1776
1777   TRACE( "(%04x,%d,%p)\n", hEmf, cEntries, lpPe ); 
1778
1779   /* First check if there are any palettes associated with
1780      this metafile. */
1781   if ( enhHeader->nPalEntries == 0 )
1782   {
1783     /* No palette associated with this enhanced metafile */
1784     uReturnValue = 0;
1785     goto done; 
1786   }
1787
1788   /* Is the user requesting the number of palettes? */
1789   if ( lpPe == NULL )
1790   {
1791      uReturnValue = (UINT)enhHeader->nPalEntries;
1792      goto done;
1793   } 
1794
1795   /* Copy cEntries worth of PALETTEENTRY structs into the buffer */
1796   infoForCallBack.cEntries = cEntries;
1797   infoForCallBack.lpPe     = lpPe; 
1798
1799   if ( !EnumEnhMetaFile( 0, hEmf, cbEnhPaletteCopy, 
1800                          &infoForCallBack, NULL ) )
1801   {
1802      goto done; 
1803   }
1804
1805   /* Verify that the callback executed correctly */
1806   if ( infoForCallBack.lpPe != NULL )
1807   {
1808      /* Callback proc had error! */
1809      ERR( "cbEnhPaletteCopy didn't execute correctly\n" );
1810      goto done;
1811   }
1812
1813   uReturnValue = infoForCallBack.cEntries;
1814
1815 done:
1816   
1817   EMF_ReleaseEnhMetaHeader( hEmf );
1818
1819   return uReturnValue;
1820 }
1821
1822 /******************************************************************
1823  *         SetWinMetaFileBits   (GDI32.@)
1824  *      
1825  *         Translate from old style to new style.
1826  *
1827  * BUGS: - This doesn't take the DC and scaling into account
1828  *       - Most record conversions aren't implemented
1829  *       - Handle slot assignement is primative and most likely doesn't work
1830  */
1831 HENHMETAFILE WINAPI SetWinMetaFileBits(UINT cbBuffer,
1832                                            CONST BYTE *lpbBuffer,
1833                                            HDC hdcRef,
1834                                            CONST METAFILEPICT *lpmfp
1835                                            ) 
1836 {
1837      HENHMETAFILE    hMf;
1838      LPVOID          lpNewEnhMetaFileBuffer = NULL;
1839      UINT            uNewEnhMetaFileBufferSize = 0;
1840      BOOL            bFoundEOF = FALSE;
1841
1842      FIXME( "(%d,%p,%04x,%p):stub\n", cbBuffer, lpbBuffer, hdcRef, lpmfp );
1843
1844      /* 1. Get the header - skip over this and get straight to the records  */
1845
1846      uNewEnhMetaFileBufferSize = sizeof( ENHMETAHEADER );
1847      lpNewEnhMetaFileBuffer = HeapAlloc( GetProcessHeap(), HEAP_ZERO_MEMORY, 
1848                                          uNewEnhMetaFileBufferSize );
1849
1850      if( lpNewEnhMetaFileBuffer == NULL )
1851      {
1852        goto error; 
1853      }
1854
1855      /* Fill in the header record */ 
1856      {
1857        LPENHMETAHEADER lpNewEnhMetaFileHeader = (LPENHMETAHEADER)lpNewEnhMetaFileBuffer;
1858
1859        lpNewEnhMetaFileHeader->iType = EMR_HEADER;
1860        lpNewEnhMetaFileHeader->nSize = sizeof( ENHMETAHEADER );
1861
1862        /* FIXME: Not right. Must be able to get this from the DC */
1863        lpNewEnhMetaFileHeader->rclBounds.left   = 0;
1864        lpNewEnhMetaFileHeader->rclBounds.right  = 0;
1865        lpNewEnhMetaFileHeader->rclBounds.top    = 0;
1866        lpNewEnhMetaFileHeader->rclBounds.bottom = 0;
1867
1868        /* FIXME: Not right. Must be able to get this from the DC */
1869        lpNewEnhMetaFileHeader->rclFrame.left   = 0;
1870        lpNewEnhMetaFileHeader->rclFrame.right  = 0;
1871        lpNewEnhMetaFileHeader->rclFrame.top    = 0;
1872        lpNewEnhMetaFileHeader->rclFrame.bottom = 0;
1873
1874        lpNewEnhMetaFileHeader->nHandles = 0; /* No handles yet */
1875
1876        /* FIXME: Add in the rest of the fields to the header */
1877        /* dSignature
1878           nVersion
1879           nRecords
1880           sReserved
1881           nDescription
1882           offDescription
1883           nPalEntries
1884           szlDevice
1885           szlMillimeters
1886           cbPixelFormat
1887           offPixelFormat,
1888           bOpenGL */
1889      } 
1890
1891      (char*)lpbBuffer += ((METAHEADER*)lpbBuffer)->mtHeaderSize * 2; /* Point past the header - FIXME: metafile quirk? */ 
1892
1893      /* 2. Enum over individual records and convert them to the new type of records */
1894      while( !bFoundEOF )
1895      { 
1896
1897         LPMETARECORD lpMetaRecord = (LPMETARECORD)lpbBuffer;
1898
1899 #define EMF_ReAllocAndAdjustPointers( a , b ) \
1900                                         { \
1901                                           LPVOID lpTmp; \
1902                                           lpTmp = HeapReAlloc( GetProcessHeap(), 0, \
1903                                                                lpNewEnhMetaFileBuffer, \
1904                                                                uNewEnhMetaFileBufferSize + (b) ); \
1905                                           if( lpTmp == NULL ) { ERR( "No memory!\n" ); goto error; } \
1906                                           lpNewEnhMetaFileBuffer = lpTmp; \
1907                                           lpRecord = (a)( (char*)lpNewEnhMetaFileBuffer + uNewEnhMetaFileBufferSize ); \
1908                                           uNewEnhMetaFileBufferSize += (b); \
1909                                         }
1910
1911         switch( lpMetaRecord->rdFunction )
1912         {
1913           case META_EOF:  
1914           { 
1915              PEMREOF lpRecord;
1916              size_t uRecord = sizeof(*lpRecord);
1917
1918              EMF_ReAllocAndAdjustPointers(PEMREOF,uRecord);
1919               
1920              /* Fill the new record - FIXME: This is not right */
1921              lpRecord->emr.iType = EMR_EOF; 
1922              lpRecord->emr.nSize = sizeof( *lpRecord );
1923              lpRecord->nPalEntries = 0;     /* FIXME */
1924              lpRecord->offPalEntries = 0;   /* FIXME */ 
1925              lpRecord->nSizeLast = 0;       /* FIXME */
1926
1927              /* No more records after this one */
1928              bFoundEOF = TRUE;
1929
1930              FIXME( "META_EOF conversion not correct\n" );
1931              break;
1932           }
1933
1934           case META_SETMAPMODE:
1935           {  
1936              PEMRSETMAPMODE lpRecord;
1937              size_t uRecord = sizeof(*lpRecord);
1938
1939              EMF_ReAllocAndAdjustPointers(PEMRSETMAPMODE,uRecord);
1940
1941              lpRecord->emr.iType = EMR_SETMAPMODE;
1942              lpRecord->emr.nSize = sizeof( *lpRecord );
1943
1944              lpRecord->iMode = lpMetaRecord->rdParm[0];
1945
1946              break;
1947           }
1948
1949           case META_DELETEOBJECT: /* Select and Delete structures are the same */
1950           case META_SELECTOBJECT: 
1951           {
1952             PEMRDELETEOBJECT lpRecord;
1953             size_t uRecord = sizeof(*lpRecord);
1954
1955             EMF_ReAllocAndAdjustPointers(PEMRDELETEOBJECT,uRecord);
1956
1957             if( lpMetaRecord->rdFunction == META_DELETEOBJECT )
1958             {
1959               lpRecord->emr.iType = EMR_DELETEOBJECT;
1960             }
1961             else
1962             {
1963               lpRecord->emr.iType = EMR_SELECTOBJECT;
1964             }
1965             lpRecord->emr.nSize = sizeof( *lpRecord );
1966
1967             lpRecord->ihObject = lpMetaRecord->rdParm[0]; /* FIXME: Handle */
1968
1969             break;
1970           }
1971
1972           case META_POLYGON: /* This is just plain busted. I don't know what I'm doing */
1973           {
1974              PEMRPOLYGON16 lpRecord; /* FIXME: Should it be a poly or poly16? */  
1975              size_t uRecord = sizeof(*lpRecord);
1976
1977              EMF_ReAllocAndAdjustPointers(PEMRPOLYGON16,uRecord);
1978
1979              /* FIXME: This is mostly all wrong */
1980              lpRecord->emr.iType = EMR_POLYGON16;
1981              lpRecord->emr.nSize = sizeof( *lpRecord );
1982
1983              lpRecord->rclBounds.left   = 0;
1984              lpRecord->rclBounds.right  = 0;
1985              lpRecord->rclBounds.top    = 0;
1986              lpRecord->rclBounds.bottom = 0;
1987
1988              lpRecord->cpts = 0;
1989              lpRecord->apts[0].x = 0;
1990              lpRecord->apts[0].y = 0;
1991
1992              FIXME( "META_POLYGON conversion not correct\n" );
1993
1994              break;
1995           }
1996
1997           case META_SETPOLYFILLMODE:
1998           {
1999              PEMRSETPOLYFILLMODE lpRecord;
2000              size_t uRecord = sizeof(*lpRecord);
2001
2002              EMF_ReAllocAndAdjustPointers(PEMRSETPOLYFILLMODE,uRecord);
2003
2004              lpRecord->emr.iType = EMR_SETPOLYFILLMODE;
2005              lpRecord->emr.nSize = sizeof( *lpRecord );
2006
2007              lpRecord->iMode = lpMetaRecord->rdParm[0];
2008              
2009              break;
2010           }
2011
2012           case META_SETWINDOWORG:
2013           {
2014              PEMRSETWINDOWORGEX lpRecord; /* Seems to be the closest thing */
2015              size_t uRecord = sizeof(*lpRecord);
2016
2017              EMF_ReAllocAndAdjustPointers(PEMRSETWINDOWORGEX,uRecord);
2018
2019              lpRecord->emr.iType = EMR_SETWINDOWORGEX;
2020              lpRecord->emr.nSize = sizeof( *lpRecord );
2021
2022              lpRecord->ptlOrigin.x = lpMetaRecord->rdParm[1];
2023              lpRecord->ptlOrigin.y = lpMetaRecord->rdParm[0];
2024
2025              break;
2026           }
2027
2028           case META_SETWINDOWEXT:  /* Structure is the same for SETWINDOWEXT & SETVIEWPORTEXT */
2029           case META_SETVIEWPORTEXT:
2030           {
2031              PEMRSETWINDOWEXTEX lpRecord;
2032              size_t uRecord = sizeof(*lpRecord);
2033
2034              EMF_ReAllocAndAdjustPointers(PEMRSETWINDOWEXTEX,uRecord);
2035
2036              if ( lpMetaRecord->rdFunction == META_SETWINDOWEXT )
2037              {
2038                lpRecord->emr.iType = EMR_SETWINDOWORGEX;
2039              }
2040              else
2041              {
2042                lpRecord->emr.iType = EMR_SETVIEWPORTEXTEX;
2043              }
2044              lpRecord->emr.nSize = sizeof( *lpRecord );
2045
2046              lpRecord->szlExtent.cx = lpMetaRecord->rdParm[1];
2047              lpRecord->szlExtent.cy = lpMetaRecord->rdParm[0];
2048
2049              break;
2050           }
2051
2052           case META_CREATEBRUSHINDIRECT:
2053           {
2054              PEMRCREATEBRUSHINDIRECT lpRecord;
2055              size_t uRecord = sizeof(*lpRecord);
2056
2057              EMF_ReAllocAndAdjustPointers(PEMRCREATEBRUSHINDIRECT,uRecord);
2058
2059              lpRecord->emr.iType = EMR_CREATEBRUSHINDIRECT;
2060              lpRecord->emr.nSize = sizeof( *lpRecord );
2061
2062              lpRecord->ihBrush    = ((LPENHMETAHEADER)lpNewEnhMetaFileBuffer)->nHandles;
2063              lpRecord->lb.lbStyle = ((LPLOGBRUSH16)lpMetaRecord->rdParm)->lbStyle; 
2064              lpRecord->lb.lbColor = ((LPLOGBRUSH16)lpMetaRecord->rdParm)->lbColor; 
2065              lpRecord->lb.lbHatch = ((LPLOGBRUSH16)lpMetaRecord->rdParm)->lbHatch; 
2066              
2067              ((LPENHMETAHEADER)lpNewEnhMetaFileBuffer)->nHandles += 1; /* New handle */
2068
2069              break;
2070           }
2071
2072
2073           /* These are all unimplemented and as such are intended to fall through to the default case */
2074           case META_SETBKCOLOR:
2075           case META_SETBKMODE:
2076           case META_SETROP2:
2077           case META_SETRELABS:
2078           case META_SETSTRETCHBLTMODE:
2079           case META_SETTEXTCOLOR:
2080           case META_SETVIEWPORTORG:
2081           case META_OFFSETWINDOWORG:
2082           case META_SCALEWINDOWEXT:
2083           case META_OFFSETVIEWPORTORG:
2084           case META_SCALEVIEWPORTEXT:
2085           case META_LINETO:
2086           case META_MOVETO:
2087           case META_EXCLUDECLIPRECT:
2088           case META_INTERSECTCLIPRECT:
2089           case META_ARC:
2090           case META_ELLIPSE:
2091           case META_FLOODFILL:
2092           case META_PIE:
2093           case META_RECTANGLE:
2094           case META_ROUNDRECT:
2095           case META_PATBLT:
2096           case META_SAVEDC:
2097           case META_SETPIXEL:
2098           case META_OFFSETCLIPRGN:
2099           case META_TEXTOUT:
2100           case META_POLYPOLYGON:
2101           case META_POLYLINE:
2102           case META_RESTOREDC:  
2103           case META_CHORD:
2104           case META_CREATEPATTERNBRUSH:
2105           case META_CREATEPENINDIRECT:
2106           case META_CREATEFONTINDIRECT:
2107           case META_CREATEPALETTE:
2108           case META_SETTEXTALIGN:
2109           case META_SELECTPALETTE:
2110           case META_SETMAPPERFLAGS:
2111           case META_REALIZEPALETTE:
2112           case META_ESCAPE:
2113           case META_EXTTEXTOUT:
2114           case META_STRETCHDIB:
2115           case META_DIBSTRETCHBLT:
2116           case META_STRETCHBLT:
2117           case META_BITBLT:
2118           case META_CREATEREGION:
2119           case META_FILLREGION:
2120           case META_FRAMEREGION:
2121           case META_INVERTREGION:
2122           case META_PAINTREGION:
2123           case META_SELECTCLIPREGION:
2124           case META_DIBCREATEPATTERNBRUSH:
2125           case META_DIBBITBLT:
2126           case META_SETTEXTCHAREXTRA:
2127           case META_SETTEXTJUSTIFICATION:
2128           case META_EXTFLOODFILL:
2129           case META_SETDIBTODEV:
2130           case META_DRAWTEXT:
2131           case META_ANIMATEPALETTE:
2132           case META_SETPALENTRIES:
2133           case META_RESIZEPALETTE:
2134           case META_RESETDC:
2135           case META_STARTDOC:
2136           case META_STARTPAGE:
2137           case META_ENDPAGE:
2138           case META_ABORTDOC:
2139           case META_ENDDOC:
2140           case META_CREATEBRUSH:
2141           case META_CREATEBITMAPINDIRECT:
2142           case META_CREATEBITMAP:    
2143           /* Fall through to unimplemented */
2144           default:
2145           {
2146             /* Not implemented yet */
2147             FIXME( "Conversion of record type 0x%x not implemented.\n", lpMetaRecord->rdFunction );
2148             break;
2149           }
2150        }
2151
2152        /* Move to the next record */
2153        (char*)lpbBuffer += ((LPMETARECORD)lpbBuffer)->rdSize * 2; /* FIXME: Seem to be doing this in metafile.c */ 
2154
2155 #undef ReAllocAndAdjustPointers
2156      } 
2157
2158      /* We know the last of the header information now */
2159      ((LPENHMETAHEADER)lpNewEnhMetaFileBuffer)->nBytes = uNewEnhMetaFileBufferSize;
2160
2161      /* Create the enhanced metafile */
2162      hMf = SetEnhMetaFileBits( uNewEnhMetaFileBufferSize, (const BYTE*)lpNewEnhMetaFileBuffer ); 
2163
2164      if( !hMf )
2165        ERR( "Problem creating metafile. Did the conversion fail somewhere?\n" );
2166
2167      return hMf;
2168
2169 error:
2170      /* Free the data associated with our copy since it's been copied */
2171      HeapFree( GetProcessHeap(), 0, lpNewEnhMetaFileBuffer ); 
2172
2173      return 0;  
2174 }
2175
2176
2177