Do not allow creation of not aligned EMF records by GDI code.
[wine] / dlls / gdi / enhmfdrv / init.c
1 /*
2  * Enhanced MetaFile driver initialisation functions
3  *
4  * Copyright 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
21 #include <assert.h>
22 #include <stdarg.h>
23 #include <string.h>
24
25 #include "windef.h"
26 #include "winbase.h"
27 #include "wingdi.h"
28 #include "gdi.h"
29 #include "gdi_private.h"
30 #include "enhmfdrv/enhmetafiledrv.h"
31 #include "wine/debug.h"
32
33 WINE_DEFAULT_DEBUG_CHANNEL(enhmetafile);
34
35 static const DC_FUNCTIONS EMFDRV_Funcs =
36 {
37     NULL,                            /* pAbortDoc */
38     EMFDRV_AbortPath,                /* pAbortPath */
39     NULL,                            /* pAngleArc */
40     EMFDRV_Arc,                      /* pArc */
41     NULL,                            /* pArcTo */
42     EMFDRV_BeginPath,                /* pBeginPath */
43     EMFDRV_BitBlt,                   /* pBitBlt */
44     NULL,                            /* pChoosePixelFormat */
45     EMFDRV_Chord,                    /* pChord */
46     EMFDRV_CloseFigure,              /* pCloseFigure */
47     NULL,                            /* pCreateBitmap */
48     NULL,                            /* pCreateDC */
49     NULL,                            /* pCreateDIBSection */
50     NULL,                            /* pDeleteBitmap */
51     NULL,                            /* pDeleteDC */
52     EMFDRV_DeleteObject,             /* pDeleteObject */
53     NULL,                            /* pDescribePixelFormat */
54     NULL,                            /* pDeviceCapabilities */
55     EMFDRV_Ellipse,                  /* pEllipse */
56     NULL,                            /* pEndDoc */
57     NULL,                            /* pEndPage */
58     EMFDRV_EndPath,                  /* pEndPath */
59     NULL,                            /* pEnumDeviceFonts */
60     EMFDRV_ExcludeClipRect,          /* pExcludeClipRect */
61     NULL,                            /* pExtDeviceMode */
62     NULL,                            /* pExtEscape */
63     EMFDRV_ExtFloodFill,             /* pExtFloodFill */
64     EMFDRV_ExtSelectClipRgn,         /* pExtSelectClipRgn */
65     EMFDRV_ExtTextOut,               /* pExtTextOut */
66     EMFDRV_FillPath,                 /* pFillPath */
67     EMFDRV_FillRgn,                  /* pFillRgn */
68     EMFDRV_FlattenPath,              /* pFlattenPath */
69     EMFDRV_FrameRgn,                 /* pFrameRgn */
70     EMFDRV_GdiComment,               /* pGdiComment */
71     NULL,                            /* pGetBitmapBits */
72     NULL,                            /* pGetCharWidth */
73     NULL,                            /* pGetDCOrgEx */
74     NULL,                            /* pGetDIBColorTable */
75     NULL,                            /* pGetDIBits */
76     EMFDRV_GetDeviceCaps,            /* pGetDeviceCaps */
77     NULL,                            /* pGetDeviceGammaRamp */
78     NULL,                            /* pGetNearestColor */
79     NULL,                            /* pGetPixel */
80     NULL,                            /* pGetPixelFormat */
81     NULL,                            /* pGetSystemPaletteEntries */
82     NULL,                            /* pGetTextExtentPoint */
83     NULL,                            /* pGetTextMetrics */
84     EMFDRV_IntersectClipRect,        /* pIntersectClipRect */
85     EMFDRV_InvertRgn,                /* pInvertRgn */
86     EMFDRV_LineTo,                   /* pLineTo */
87     EMFDRV_ModifyWorldTransform,     /* pModifyWorldTransform */
88     EMFDRV_MoveTo,                   /* pMoveTo */
89     EMFDRV_OffsetClipRgn,            /* pOffsetClipRgn */
90     EMFDRV_OffsetViewportOrg,        /* pOffsetViewportOrg */
91     EMFDRV_OffsetWindowOrg,          /* pOffsetWindowOrg */
92     EMFDRV_PaintRgn,                 /* pPaintRgn */
93     EMFDRV_PatBlt,                   /* pPatBlt */
94     EMFDRV_Pie,                      /* pPie */
95     NULL,                            /* pPolyBezier */
96     NULL,                            /* pPolyBezierTo */
97     NULL,                            /* pPolyDraw */
98     EMFDRV_PolyPolygon,              /* pPolyPolygon */
99     EMFDRV_PolyPolyline,             /* pPolyPolyline */
100     EMFDRV_Polygon,                  /* pPolygon */
101     EMFDRV_Polyline,                 /* pPolyline */
102     NULL,                            /* pPolylineTo */
103     NULL,                            /* pRealizeDefaultPalette */
104     NULL,                            /* pRealizePalette */
105     EMFDRV_Rectangle,                /* pRectangle */
106     NULL,                            /* pResetDC */
107     EMFDRV_RestoreDC,                /* pRestoreDC */
108     EMFDRV_RoundRect,                /* pRoundRect */
109     EMFDRV_SaveDC,                   /* pSaveDC */
110     EMFDRV_ScaleViewportExt,         /* pScaleViewportExt */
111     EMFDRV_ScaleWindowExt,           /* pScaleWindowExt */
112     EMFDRV_SelectBitmap,             /* pSelectBitmap */
113     EMFDRV_SelectBrush,              /* pSelectBrush */
114     EMFDRV_SelectClipPath,           /* pSelectClipPath */
115     EMFDRV_SelectFont,               /* pSelectFont */
116     NULL,                            /* pSelectPalette */
117     EMFDRV_SelectPen,                /* pSelectPen */
118     EMFDRV_SetArcDirection,          /* pSetArcDirection */
119     NULL,                            /* pSetBitmapBits */
120     EMFDRV_SetBkColor,               /* pSetBkColor */
121     EMFDRV_SetBkMode,                /* pSetBkMode */
122     NULL,                            /* pSetDCBrushColor */
123     NULL,                            /* pSetDCOrg */
124     NULL,                            /* pSetDCPenColor */
125     NULL,                            /* pSetDIBColorTable */
126     NULL,                            /* pSetDIBits */
127     EMFDRV_SetDIBitsToDevice,        /* pSetDIBitsToDevice */
128     NULL,                            /* pSetDeviceClipping */
129     NULL,                            /* pSetDeviceGammaRamp */
130     EMFDRV_SetMapMode,               /* pSetMapMode */
131     EMFDRV_SetMapperFlags,           /* pSetMapperFlags */
132     NULL,                            /* pSetPixel */
133     NULL,                            /* pSetPixelFormat */
134     EMFDRV_SetPolyFillMode,          /* pSetPolyFillMode */
135     EMFDRV_SetROP2,                  /* pSetROP2 */
136     NULL,                            /* pSetRelAbs */
137     EMFDRV_SetStretchBltMode,        /* pSetStretchBltMode */
138     EMFDRV_SetTextAlign,             /* pSetTextAlign */
139     NULL,                            /* pSetTextCharacterExtra */
140     EMFDRV_SetTextColor,             /* pSetTextColor */
141     EMFDRV_SetTextJustification,     /* pSetTextJustification */ 
142     EMFDRV_SetViewportExt,           /* pSetViewportExt */
143     EMFDRV_SetViewportOrg,           /* pSetViewportOrg */
144     EMFDRV_SetWindowExt,             /* pSetWindowExt */
145     EMFDRV_SetWindowOrg,             /* pSetWindowOrg */
146     EMFDRV_SetWorldTransform,        /* pSetWorldTransform */
147     NULL,                            /* pStartDoc */
148     NULL,                            /* pStartPage */
149     EMFDRV_StretchBlt,               /* pStretchBlt */
150     EMFDRV_StretchDIBits,            /* pStretchDIBits */
151     EMFDRV_StrokeAndFillPath,        /* pStrokeAndFillPath */
152     EMFDRV_StrokePath,               /* pStrokePath */
153     NULL,                            /* pSwapBuffers */
154     EMFDRV_WidenPath                 /* pWidenPath */
155 };
156
157
158 /**********************************************************************
159  *           EMFDRV_DeleteDC
160  */
161 static BOOL EMFDRV_DeleteDC( PHYSDEV dev )
162 {
163     EMFDRV_PDEVICE *physDev = (EMFDRV_PDEVICE *)dev;
164     DC *dc = physDev->dc;
165     UINT index;
166
167     if (physDev->emh) HeapFree( GetProcessHeap(), 0, physDev->emh );
168     for(index = 0; index < physDev->handles_size; index++)
169         if(physDev->handles[index])
170             GDI_hdc_not_using_object(physDev->handles[index], physDev->hdc);
171     HeapFree( GetProcessHeap(), 0, physDev->handles );
172     HeapFree( GetProcessHeap(), 0, physDev );
173     dc->physDev = NULL;
174     GDI_FreeObject( dc->hSelf, dc );
175     return TRUE;
176 }
177
178
179 /******************************************************************
180  *         EMFDRV_WriteRecord
181  *
182  * Warning: this function can change the pointer to the metafile header.
183  */
184 BOOL EMFDRV_WriteRecord( PHYSDEV dev, EMR *emr )
185 {
186     DWORD len;
187     ENHMETAHEADER *emh;
188     EMFDRV_PDEVICE *physDev = (EMFDRV_PDEVICE *)dev;
189
190     TRACE("record %ld, size %ld %s\n",
191           emr->iType, emr->nSize, physDev->hFile ? "(to disk)" : "");
192
193     assert( !(emr->nSize & 3) );
194
195     physDev->emh->nBytes += emr->nSize;
196     physDev->emh->nRecords++;
197
198     if(physDev->hFile) {
199         if (!WriteFile(physDev->hFile, (char *)emr, emr->nSize, NULL, NULL))
200             return FALSE;
201     } else {
202         DWORD nEmfSize = HeapSize(GetProcessHeap(), 0, physDev->emh);
203         len = physDev->emh->nBytes;
204         if (len > nEmfSize) {
205             nEmfSize += (nEmfSize / 2) + emr->nSize;
206             emh = HeapReAlloc(GetProcessHeap(), 0, physDev->emh, nEmfSize);
207             if (!emh) return FALSE;
208             physDev->emh = emh;
209         }
210         memcpy((CHAR *)physDev->emh + physDev->emh->nBytes - emr->nSize, emr,
211                emr->nSize);
212     }
213     return TRUE;
214 }
215
216
217 /******************************************************************
218  *         EMFDRV_UpdateBBox
219  */
220 void EMFDRV_UpdateBBox( PHYSDEV dev, RECTL *rect )
221 {
222     EMFDRV_PDEVICE *physDev = (EMFDRV_PDEVICE *)dev;
223     RECTL *bounds = &physDev->emh->rclBounds;
224     RECTL vportRect = *rect;
225
226     LPtoDP(physDev->hdc, (LPPOINT)&vportRect, 2);
227
228     if(bounds->left > bounds->right) {/* first rect */
229         *bounds = vportRect;
230         return;
231     }
232     bounds->left   = min(bounds->left,   vportRect.left);
233     bounds->top    = min(bounds->top,    vportRect.top);
234     bounds->right  = max(bounds->right,  vportRect.right);
235     bounds->bottom = max(bounds->bottom, vportRect.bottom);
236     return;
237 }
238
239 /**********************************************************************
240  *          CreateEnhMetaFileA   (GDI32.@)
241  */
242 HDC WINAPI CreateEnhMetaFileA(
243     HDC hdc,           /* [in] optional reference DC */
244     LPCSTR filename,   /* [in] optional filename for disk metafiles */
245     const RECT *rect,  /* [in] optional bounding rectangle */
246     LPCSTR description /* [in] optional description */
247     )
248 {
249     LPWSTR filenameW = NULL;
250     LPWSTR descriptionW = NULL;
251     HDC hReturnDC;
252     DWORD len1, len2, total;
253
254     if(filename)
255     {
256         total = MultiByteToWideChar( CP_ACP, 0, filename, -1, NULL, 0 );
257         filenameW = HeapAlloc( GetProcessHeap(), 0, total * sizeof(WCHAR) );
258         MultiByteToWideChar( CP_ACP, 0, filename, -1, filenameW, total );
259     }
260     if(description) {
261         len1 = strlen(description);
262         len2 = strlen(description + len1 + 1);
263         total = MultiByteToWideChar( CP_ACP, 0, description, len1 + len2 + 3, NULL, 0 );
264         descriptionW = HeapAlloc( GetProcessHeap(), 0, total * sizeof(WCHAR) );
265         MultiByteToWideChar( CP_ACP, 0, description, len1 + len2 + 3, descriptionW, total );
266     }
267
268     hReturnDC = CreateEnhMetaFileW(hdc, filenameW, rect, descriptionW);
269
270     if(filenameW)
271         HeapFree( GetProcessHeap(), 0, filenameW );
272     if(descriptionW)
273         HeapFree( GetProcessHeap(), 0, descriptionW );
274
275     return hReturnDC;
276 }
277
278 /**********************************************************************
279  *          CreateEnhMetaFileW   (GDI32.@)
280  */
281 HDC WINAPI CreateEnhMetaFileW(
282     HDC           hdc,        /* [in] optional reference DC */
283     LPCWSTR       filename,   /* [in] optional filename for disk metafiles */
284     const RECT*   rect,       /* [in] optional bounding rectangle */
285     LPCWSTR       description /* [in] optional description */
286     )
287 {
288     static const WCHAR displayW[] = {'D','I','S','P','L','A','Y',0};
289     HDC ret;
290     DC *dc;
291     HDC hRefDC = hdc ? hdc : CreateDCW(displayW,NULL,NULL,NULL); 
292         /* If no ref, use current display */
293     EMFDRV_PDEVICE *physDev;
294     HANDLE hFile;
295     DWORD size = 0, length = 0;
296
297     TRACE("%s\n", debugstr_w(filename) );
298
299     if (!(dc = DC_AllocDC( &EMFDRV_Funcs, ENHMETAFILE_DC_MAGIC ))) return 0;
300
301     physDev = (EMFDRV_PDEVICE *)HeapAlloc(GetProcessHeap(),0,sizeof(*physDev));
302     if (!physDev) {
303         GDI_FreeObject( dc->hSelf, dc );
304         return 0;
305     }
306     dc->physDev = (PHYSDEV)physDev;
307     physDev->hdc = dc->hSelf;
308     physDev->dc = dc;
309
310     if(description) { /* App name\0Title\0\0 */
311         length = lstrlenW(description);
312         length += lstrlenW(description + length + 1);
313         length += 3;
314         length *= 2;
315     }
316     size = sizeof(ENHMETAHEADER) + (length + 3) / 4 * 4;
317
318     if (!(physDev->emh = HeapAlloc( GetProcessHeap(), HEAP_ZERO_MEMORY, size))) {
319         HeapFree( GetProcessHeap(), 0, physDev );
320         GDI_FreeObject( dc->hSelf, dc );
321         return 0;
322     }
323
324     physDev->handles = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, HANDLE_LIST_INC * sizeof(physDev->handles[0]));
325     physDev->handles_size = HANDLE_LIST_INC;
326     physDev->cur_handles = 1;
327     physDev->hFile = 0;
328
329     physDev->horzres = GetDeviceCaps(hRefDC, HORZRES);
330     physDev->vertres = GetDeviceCaps(hRefDC, VERTRES);
331     physDev->logpixelsx = GetDeviceCaps(hRefDC, LOGPIXELSX);
332     physDev->logpixelsy = GetDeviceCaps(hRefDC, LOGPIXELSY);
333     physDev->horzsize = GetDeviceCaps(hRefDC, HORZSIZE);
334     physDev->vertsize = GetDeviceCaps(hRefDC, VERTSIZE);
335     physDev->bitspixel = GetDeviceCaps(hRefDC, BITSPIXEL);
336     physDev->textcaps = GetDeviceCaps(hRefDC, TEXTCAPS);
337     physDev->rastercaps = GetDeviceCaps(hRefDC, RASTERCAPS);
338     physDev->technology = GetDeviceCaps(hRefDC, TECHNOLOGY);
339     physDev->planes = GetDeviceCaps(hRefDC, PLANES);
340
341     physDev->emh->iType = EMR_HEADER;
342     physDev->emh->nSize = size;
343
344     physDev->emh->rclBounds.left = physDev->emh->rclBounds.top = 0;
345     physDev->emh->rclBounds.right = physDev->emh->rclBounds.bottom = -1;
346
347     if(rect) {
348         physDev->emh->rclFrame.left   = rect->left;
349         physDev->emh->rclFrame.top    = rect->top;
350         physDev->emh->rclFrame.right  = rect->right;
351         physDev->emh->rclFrame.bottom = rect->bottom;
352     } else {  /* Set this to {0,0 - -1,-1} and update it at the end */
353         physDev->emh->rclFrame.left = physDev->emh->rclFrame.top = 0;
354         physDev->emh->rclFrame.right = physDev->emh->rclFrame.bottom = -1;
355     }
356
357     physDev->emh->dSignature = ENHMETA_SIGNATURE;
358     physDev->emh->nVersion = 0x10000;
359     physDev->emh->nBytes = physDev->emh->nSize;
360     physDev->emh->nRecords = 1;
361     physDev->emh->nHandles = 1;
362
363     physDev->emh->sReserved = 0; /* According to docs, this is reserved and must be 0 */
364     physDev->emh->nDescription = length / 2;
365
366     physDev->emh->offDescription = length ? sizeof(ENHMETAHEADER) : 0;
367
368     physDev->emh->nPalEntries = 0; /* I guess this should start at 0 */
369
370     /* Size in pixels */
371     physDev->emh->szlDevice.cx = physDev->horzres;
372     physDev->emh->szlDevice.cy = physDev->vertres;
373
374     /* Size in millimeters */
375     physDev->emh->szlMillimeters.cx = physDev->horzsize;
376     physDev->emh->szlMillimeters.cy = physDev->vertsize;
377
378     /* Size in micrometers */
379     physDev->emh->szlMicrometers.cx = physDev->horzsize * 1000;
380     physDev->emh->szlMicrometers.cy = physDev->vertsize * 1000;
381
382     memcpy((char *)physDev->emh + sizeof(ENHMETAHEADER), description, length);
383
384     if (filename)  /* disk based metafile */
385     {
386         if ((hFile = CreateFileW(filename, GENERIC_WRITE | GENERIC_READ, 0,
387                                  NULL, CREATE_ALWAYS, 0, 0)) == INVALID_HANDLE_VALUE) {
388             EMFDRV_DeleteDC( dc->physDev );
389             return 0;
390         }
391         if (!WriteFile( hFile, (LPSTR)physDev->emh, size, NULL, NULL )) {
392             EMFDRV_DeleteDC( dc->physDev );
393             return 0;
394         }
395         physDev->hFile = hFile;
396     }
397
398     TRACE("returning %p\n", dc->hSelf);
399     ret = dc->hSelf;
400     GDI_ReleaseObj( dc->hSelf );
401
402     if( !hdc )
403       DeleteDC( hRefDC );
404
405     return ret;
406 }
407
408 /******************************************************************
409  *             CloseEnhMetaFile (GDI32.@)
410  */
411 HENHMETAFILE WINAPI CloseEnhMetaFile(HDC hdc) /* [in] metafile DC */
412 {
413     HENHMETAFILE hmf;
414     EMFDRV_PDEVICE *physDev;
415     DC *dc;
416     EMREOF emr;
417     HANDLE hMapping = 0;
418
419     TRACE("(%p)\n", hdc );
420
421     if (!(dc = (DC *) GDI_GetObjPtr( hdc, ENHMETAFILE_DC_MAGIC ))) return 0;
422     physDev = (EMFDRV_PDEVICE *)dc->physDev;
423
424     emr.emr.iType = EMR_EOF;
425     emr.emr.nSize = sizeof(emr);
426     emr.nPalEntries = 0;
427     emr.offPalEntries = 0;
428     emr.nSizeLast = emr.emr.nSize;
429     EMFDRV_WriteRecord( dc->physDev, &emr.emr );
430
431     /* Update rclFrame if not initialized in CreateEnhMetaFile */
432     if(physDev->emh->rclFrame.left > physDev->emh->rclFrame.right) {
433         physDev->emh->rclFrame.left = physDev->emh->rclBounds.left *
434           physDev->emh->szlMillimeters.cx * 100 / physDev->emh->szlDevice.cx;
435         physDev->emh->rclFrame.top = physDev->emh->rclBounds.top *
436           physDev->emh->szlMillimeters.cy * 100 / physDev->emh->szlDevice.cy;
437         physDev->emh->rclFrame.right = physDev->emh->rclBounds.right *
438           physDev->emh->szlMillimeters.cx * 100 / physDev->emh->szlDevice.cx;
439         physDev->emh->rclFrame.bottom = physDev->emh->rclBounds.bottom *
440           physDev->emh->szlMillimeters.cy * 100 / physDev->emh->szlDevice.cy;
441     }
442
443     if (physDev->hFile)  /* disk based metafile */
444     {
445         if (SetFilePointer(physDev->hFile, 0, NULL, FILE_BEGIN) != 0)
446         {
447             CloseHandle( physDev->hFile );
448             EMFDRV_DeleteDC( dc->physDev );
449             return 0;
450         }
451
452         if (!WriteFile(physDev->hFile, (LPSTR)physDev->emh,
453                        sizeof(*physDev->emh), NULL, NULL))
454         {
455             CloseHandle( physDev->hFile );
456             EMFDRV_DeleteDC( dc->physDev );
457             return 0;
458         }
459         HeapFree( GetProcessHeap(), 0, physDev->emh );
460         hMapping = CreateFileMappingA(physDev->hFile, NULL, PAGE_READONLY, 0,
461                                       0, NULL);
462         TRACE("hMapping = %p\n", hMapping );
463         physDev->emh = MapViewOfFile(hMapping, FILE_MAP_READ, 0, 0, 0);
464         TRACE("view = %p\n", physDev->emh );
465         CloseHandle( hMapping );
466         CloseHandle( physDev->hFile );
467     }
468
469     hmf = EMF_Create_HENHMETAFILE( physDev->emh, (physDev->hFile != 0) );
470     physDev->emh = NULL;  /* So it won't be deleted */
471     EMFDRV_DeleteDC( dc->physDev );
472     return hmf;
473 }