gdi32: Add a driver entry point for CreateCompatibleDC.
[wine] / dlls / wineps.drv / init.c
1 /*
2  *      PostScript driver initialization functions
3  *
4  *      Copyright 1998 Huw D M Davies
5  *      Copyright 2001 Marcus Meissner
6  *
7  * This library is free software; you can redistribute it and/or
8  * modify it under the terms of the GNU Lesser General Public
9  * License as published by the Free Software Foundation; either
10  * version 2.1 of the License, or (at your option) any later version.
11  *
12  * This library is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15  * Lesser General Public License for more details.
16  *
17  * You should have received a copy of the GNU Lesser General Public
18  * License along with this library; if not, write to the Free Software
19  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
20  */
21
22 #include "config.h"
23 #include "wine/port.h"
24
25 #include <stdarg.h>
26 #include <string.h>
27 #ifdef HAVE_UNISTD_H
28 # include <unistd.h>
29 #endif
30 #ifdef HAVE_CUPS_CUPS_H
31 # include <cups/cups.h>
32 #endif
33
34 #define NONAMELESSUNION
35 #define NONAMELESSSTRUCT
36
37 #include "windef.h"
38 #include "winbase.h"
39 #include "winerror.h"
40 #include "winreg.h"
41 #include "winnls.h"
42 #include "psdrv.h"
43 #include "winspool.h"
44 #include "wine/library.h"
45 #include "wine/debug.h"
46
47 WINE_DEFAULT_DEBUG_CHANNEL(psdrv);
48
49 #ifdef SONAME_LIBCUPS
50 static void *cupshandle = NULL;
51 #endif
52
53 static const PSDRV_DEVMODEA DefaultDevmode =
54 {
55   { /* dmPublic */
56 /* dmDeviceName */      "Wine PostScript Driver",
57 /* dmSpecVersion */     0x30a,
58 /* dmDriverVersion */   0x001,
59 /* dmSize */            sizeof(DEVMODEA),
60 /* dmDriverExtra */     sizeof(PSDRV_DEVMODEA)-sizeof(DEVMODEA),
61 /* dmFields */          DM_ORIENTATION | DM_PAPERSIZE | DM_SCALE |
62                         DM_COPIES | DM_DEFAULTSOURCE | DM_COLOR |
63                         DM_YRESOLUTION | DM_TTOPTION,
64    { /* u1 */
65      { /* s1 */
66 /* dmOrientation */     DMORIENT_PORTRAIT,
67 /* dmPaperSize */       DMPAPER_LETTER,
68 /* dmPaperLength */     2794,
69 /* dmPaperWidth */      2159,
70 /* dmScale */           100, /* ?? */
71 /* dmCopies */          1,
72 /* dmDefaultSource */   DMBIN_AUTO,
73 /* dmPrintQuality */    0
74      }
75    },
76 /* dmColor */           DMCOLOR_COLOR,
77 /* dmDuplex */          DMDUP_SIMPLEX,
78 /* dmYResolution */     0,
79 /* dmTTOption */        DMTT_SUBDEV,
80 /* dmCollate */         0,
81 /* dmFormName */        "",
82 /* dmUnusedPadding */   0,
83 /* dmBitsPerPel */      0,
84 /* dmPelsWidth */       0,
85 /* dmPelsHeight */      0,
86    { /* u2 */
87 /* dmDisplayFlags */    0
88    },
89 /* dmDisplayFrequency */ 0,
90 /* dmICMMethod */       0,
91 /* dmICMIntent */       0,
92 /* dmMediaType */       0,
93 /* dmDitherType */      0,
94 /* dmReserved1 */       0,
95 /* dmReserved2 */       0,
96 /* dmPanningWidth */    0,
97 /* dmPanningHeight */   0
98   },
99   { /* dmDocPrivate */
100     /* dummy */ 0
101   },
102   { /* dmDrvPrivate */
103     /* numInstalledOptions */ 0
104   }
105 };
106
107 HINSTANCE PSDRV_hInstance = 0;
108 HANDLE PSDRV_Heap = 0;
109
110 static HFONT PSDRV_DefaultFont = 0;
111 static const LOGFONTA DefaultLogFont = {
112     100, 0, 0, 0, FW_NORMAL, FALSE, FALSE, FALSE, ANSI_CHARSET, 0, 0,
113     DEFAULT_QUALITY, FIXED_PITCH | FF_MODERN, ""
114 };
115
116 static const CHAR default_devmodeA[] = "Default DevMode";
117 static const struct gdi_dc_funcs psdrv_funcs;
118
119 /*********************************************************************
120  *           DllMain
121  *
122  * Initializes font metrics and registers driver. wineps dll entry point.
123  *
124  */
125 BOOL WINAPI DllMain( HINSTANCE hinst, DWORD reason, LPVOID reserved )
126 {
127     TRACE("(%p, %d, %p)\n", hinst, reason, reserved);
128
129     switch(reason) {
130
131         case DLL_PROCESS_ATTACH:
132             PSDRV_hInstance = hinst;
133             DisableThreadLibraryCalls(hinst);
134
135             PSDRV_Heap = HeapCreate(0, 0x10000, 0);
136             if (PSDRV_Heap == NULL)
137                 return FALSE;
138
139             if (PSDRV_GetFontMetrics() == FALSE) {
140                 HeapDestroy(PSDRV_Heap);
141                 return FALSE;
142             }
143
144             PSDRV_DefaultFont = CreateFontIndirectA(&DefaultLogFont);
145             if (PSDRV_DefaultFont == NULL) {
146                 HeapDestroy(PSDRV_Heap);
147                 return FALSE;
148             }
149 #ifdef SONAME_LIBCUPS
150             /* dynamically load CUPS if not yet loaded */
151             if (!cupshandle) {
152                 cupshandle = wine_dlopen(SONAME_LIBCUPS, RTLD_NOW, NULL, 0);
153                 if (!cupshandle) cupshandle = (void*)-1;
154             }
155 #endif
156             break;
157
158         case DLL_PROCESS_DETACH:
159
160             DeleteObject( PSDRV_DefaultFont );
161             HeapDestroy( PSDRV_Heap );
162 #ifdef SONAME_LIBCUPS
163             if (cupshandle && (cupshandle != (void*)-1)) {
164                 wine_dlclose(cupshandle, NULL, 0);
165                 cupshandle = NULL;
166             }
167 #endif
168             break;
169     }
170
171     return TRUE;
172 }
173
174
175 static void PSDRV_UpdateDevCaps( PSDRV_PDEVICE *physDev )
176 {
177     PAGESIZE *page;
178     INT width = 0, height = 0;
179
180     if(physDev->Devmode->dmPublic.dmFields & DM_PAPERSIZE) {
181         LIST_FOR_EACH_ENTRY(page, &physDev->pi->ppd->PageSizes, PAGESIZE, entry) {
182             if(page->WinPage == physDev->Devmode->dmPublic.u1.s1.dmPaperSize)
183                 break;
184         }
185
186         if(&page->entry == &physDev->pi->ppd->PageSizes) {
187             FIXME("Can't find page\n");
188             physDev->ImageableArea.left = 0;
189             physDev->ImageableArea.right = 0;
190             physDev->ImageableArea.bottom = 0;
191             physDev->ImageableArea.top = 0;
192             physDev->PageSize.cx = 0;
193             physDev->PageSize.cy = 0;
194         } else if(page->ImageableArea) {
195           /* physDev sizes in device units; ppd sizes in 1/72" */
196             physDev->ImageableArea.left = page->ImageableArea->llx *
197               physDev->logPixelsX / 72;
198             physDev->ImageableArea.right = page->ImageableArea->urx *
199               physDev->logPixelsX / 72;
200             physDev->ImageableArea.bottom = page->ImageableArea->lly *
201               physDev->logPixelsY / 72;
202             physDev->ImageableArea.top = page->ImageableArea->ury *
203               physDev->logPixelsY / 72;
204             physDev->PageSize.cx = page->PaperDimension->x *
205               physDev->logPixelsX / 72;
206             physDev->PageSize.cy = page->PaperDimension->y *
207               physDev->logPixelsY / 72;
208         } else {
209             physDev->ImageableArea.left = physDev->ImageableArea.bottom = 0;
210             physDev->ImageableArea.right = physDev->PageSize.cx =
211               page->PaperDimension->x * physDev->logPixelsX / 72;
212             physDev->ImageableArea.top = physDev->PageSize.cy =
213               page->PaperDimension->y * physDev->logPixelsY / 72;
214         }
215     } else if((physDev->Devmode->dmPublic.dmFields & DM_PAPERLENGTH) &&
216               (physDev->Devmode->dmPublic.dmFields & DM_PAPERWIDTH)) {
217       /* physDev sizes in device units; Devmode sizes in 1/10 mm */
218         physDev->ImageableArea.left = physDev->ImageableArea.bottom = 0;
219         physDev->ImageableArea.right = physDev->PageSize.cx =
220           physDev->Devmode->dmPublic.u1.s1.dmPaperWidth *
221           physDev->logPixelsX / 254;
222         physDev->ImageableArea.top = physDev->PageSize.cy =
223           physDev->Devmode->dmPublic.u1.s1.dmPaperLength *
224           physDev->logPixelsY / 254;
225     } else {
226         FIXME("Odd dmFields %x\n", physDev->Devmode->dmPublic.dmFields);
227         physDev->ImageableArea.left = 0;
228         physDev->ImageableArea.right = 0;
229         physDev->ImageableArea.bottom = 0;
230         physDev->ImageableArea.top = 0;
231         physDev->PageSize.cx = 0;
232         physDev->PageSize.cy = 0;
233     }
234
235     TRACE("ImageableArea = %d,%d - %d,%d: PageSize = %dx%d\n",
236           physDev->ImageableArea.left, physDev->ImageableArea.bottom,
237           physDev->ImageableArea.right, physDev->ImageableArea.top,
238           physDev->PageSize.cx, physDev->PageSize.cy);
239
240     /* these are in device units */
241     width = physDev->ImageableArea.right - physDev->ImageableArea.left;
242     height = physDev->ImageableArea.top - physDev->ImageableArea.bottom;
243
244     if(physDev->Devmode->dmPublic.u1.s1.dmOrientation == DMORIENT_PORTRAIT) {
245         physDev->horzRes = width;
246         physDev->vertRes = height;
247     } else {
248         physDev->horzRes = height;
249         physDev->vertRes = width;
250     }
251
252     /* these are in mm */
253     physDev->horzSize = (physDev->horzRes * 25.4) / physDev->logPixelsX;
254     physDev->vertSize = (physDev->vertRes * 25.4) / physDev->logPixelsY;
255
256     TRACE("devcaps: horzSize = %dmm, vertSize = %dmm, "
257           "horzRes = %d, vertRes = %d\n",
258           physDev->horzSize, physDev->vertSize,
259           physDev->horzRes, physDev->vertRes);
260 }
261
262
263 /***********************************************************
264  *      DEVMODEdupWtoA
265  *
266  * Creates an ascii copy of supplied devmode on heap
267  *
268  * Copied from dlls/winspool/info.c until full unicodification
269  */
270 static LPDEVMODEA DEVMODEdupWtoA(HANDLE heap, const DEVMODEW *dmW)
271 {
272     LPDEVMODEA dmA;
273     DWORD size;
274     BOOL Formname;
275     /* there is no pointer dereference here, if your code checking tool complains it's broken */
276     ptrdiff_t off_formname = (const char *)dmW->dmFormName - (const char *)dmW;
277
278     if(!dmW) return NULL;
279     Formname = (dmW->dmSize > off_formname);
280     size = dmW->dmSize - CCHDEVICENAME - (Formname ? CCHFORMNAME : 0);
281     dmA = HeapAlloc(heap, HEAP_ZERO_MEMORY, size + dmW->dmDriverExtra);
282     WideCharToMultiByte(CP_ACP, 0, dmW->dmDeviceName, -1, (LPSTR)dmA->dmDeviceName,
283                         CCHDEVICENAME, NULL, NULL);
284     if(!Formname) {
285       memcpy(&dmA->dmSpecVersion, &dmW->dmSpecVersion,
286              dmW->dmSize - CCHDEVICENAME * sizeof(WCHAR));
287     } else {
288       memcpy(&dmA->dmSpecVersion, &dmW->dmSpecVersion,
289              off_formname - CCHDEVICENAME * sizeof(WCHAR));
290       WideCharToMultiByte(CP_ACP, 0, dmW->dmFormName, -1, (LPSTR)dmA->dmFormName,
291                           CCHFORMNAME, NULL, NULL);
292       memcpy(&dmA->dmLogPixels, &dmW->dmLogPixels, dmW->dmSize -
293              (off_formname + CCHFORMNAME * sizeof(WCHAR)));
294     }
295     dmA->dmSize = size;
296     memcpy((char *)dmA + dmA->dmSize, (const char *)dmW + dmW->dmSize,
297            dmW->dmDriverExtra);
298     return dmA;
299 }
300
301
302 static PSDRV_PDEVICE *create_psdrv_physdev( PRINTERINFO *pi )
303 {
304     PSDRV_PDEVICE *physDev;
305
306     physDev = HeapAlloc( PSDRV_Heap, HEAP_ZERO_MEMORY, sizeof(*physDev) );
307     if (!physDev) return NULL;
308
309     physDev->Devmode = HeapAlloc( PSDRV_Heap, 0, sizeof(PSDRV_DEVMODEA) );
310     if (!physDev->Devmode)
311     {
312         HeapFree( PSDRV_Heap, 0, physDev );
313         return NULL;
314     }
315
316     *physDev->Devmode = *pi->Devmode;
317     physDev->pi = pi;
318     physDev->logPixelsX = pi->ppd->DefaultResolution;
319     physDev->logPixelsY = pi->ppd->DefaultResolution;
320     return physDev;
321 }
322
323 /**********************************************************************
324  *           PSDRV_CreateDC
325  */
326 static BOOL PSDRV_CreateDC( HDC hdc, PHYSDEV *pdev, LPCWSTR driver, LPCWSTR device,
327                      LPCWSTR output, const DEVMODEW* initData )
328 {
329     PSDRV_PDEVICE *physDev;
330     PRINTERINFO *pi;
331     DWORD len;
332     char *deviceA;
333
334     TRACE("(%s %s %s %p)\n", debugstr_w(driver), debugstr_w(device),
335                              debugstr_w(output), initData);
336
337     if (!device) return FALSE;
338     len = WideCharToMultiByte(CP_ACP, 0, device, -1, NULL, 0, NULL, NULL);
339     deviceA = HeapAlloc(GetProcessHeap(), 0, len);
340     WideCharToMultiByte(CP_ACP, 0, device, -1, deviceA, len, NULL, NULL);
341     pi = PSDRV_FindPrinterInfo(deviceA);
342     HeapFree(GetProcessHeap(), 0, deviceA);
343     if(!pi) return FALSE;
344
345     if(!pi->Fonts) {
346         RASTERIZER_STATUS status;
347         if(!GetRasterizerCaps(&status, sizeof(status)) ||
348            !(status.wFlags & TT_AVAILABLE) ||
349            !(status.wFlags & TT_ENABLED)) {
350             MESSAGE("Disabling printer %s since it has no builtin fonts and there are no TrueType fonts available.\n",
351                     debugstr_w(device));
352             return FALSE;
353         }
354     }
355
356     if (!(physDev = create_psdrv_physdev( pi ))) return FALSE;
357     *pdev = &physDev->dev;
358
359     if (output && *output) {
360         INT len = WideCharToMultiByte( CP_ACP, 0, output, -1, NULL, 0, NULL, NULL );
361         if ((physDev->job.output = HeapAlloc( PSDRV_Heap, 0, len )))
362             WideCharToMultiByte( CP_ACP, 0, output, -1, physDev->job.output, len, NULL, NULL );
363     }
364
365     if(initData) {
366         DEVMODEA *devmodeA = DEVMODEdupWtoA(PSDRV_Heap, initData);
367         PSDRV_MergeDevmodes(physDev->Devmode, (PSDRV_DEVMODEA *)devmodeA, pi);
368         HeapFree(PSDRV_Heap, 0, devmodeA);
369     }
370
371     PSDRV_UpdateDevCaps(physDev);
372     SelectObject( hdc, PSDRV_DefaultFont );
373     return TRUE;
374 }
375
376
377 /**********************************************************************
378  *           PSDRV_CreateCompatibleDC
379  */
380 static BOOL PSDRV_CreateCompatibleDC( PHYSDEV orig, PHYSDEV *pdev )
381 {
382     HDC hdc = (*pdev)->hdc;
383     PSDRV_PDEVICE *physDev, *orig_dev = get_psdrv_dev( orig );
384     PRINTERINFO *pi = PSDRV_FindPrinterInfo( orig_dev->pi->FriendlyName );
385
386     if (!pi) return FALSE;
387     if (!(physDev = create_psdrv_physdev( pi ))) return FALSE;
388     PSDRV_UpdateDevCaps(physDev);
389     SelectObject( hdc, PSDRV_DefaultFont );
390     push_dc_driver( pdev, &physDev->dev, &psdrv_funcs );
391     return TRUE;
392 }
393
394
395
396 /**********************************************************************
397  *           PSDRV_DeleteDC
398  */
399 static BOOL PSDRV_DeleteDC( PHYSDEV dev )
400 {
401     PSDRV_PDEVICE *physDev = get_psdrv_dev( dev );
402
403     TRACE("\n");
404
405     HeapFree( PSDRV_Heap, 0, physDev->Devmode );
406     HeapFree( PSDRV_Heap, 0, physDev->job.output );
407     HeapFree( PSDRV_Heap, 0, physDev );
408
409     return TRUE;
410 }
411
412
413 /**********************************************************************
414  *           ResetDC   (WINEPS.@)
415  */
416 static HDC PSDRV_ResetDC( PHYSDEV dev, const DEVMODEW *lpInitData )
417 {
418     PSDRV_PDEVICE *physDev = get_psdrv_dev( dev );
419
420     if(lpInitData) {
421         DEVMODEA *devmodeA = DEVMODEdupWtoA(PSDRV_Heap, lpInitData);
422         PSDRV_MergeDevmodes(physDev->Devmode, (PSDRV_DEVMODEA *)devmodeA, physDev->pi);
423         HeapFree(PSDRV_Heap, 0, devmodeA);
424         PSDRV_UpdateDevCaps(physDev);
425     }
426     return dev->hdc;
427 }
428
429 /***********************************************************************
430  *           GetDeviceCaps    (WINEPS.@)
431  */
432 static INT PSDRV_GetDeviceCaps( PHYSDEV dev, INT cap )
433 {
434     PSDRV_PDEVICE *physDev = get_psdrv_dev( dev );
435
436     switch(cap)
437     {
438     case DRIVERVERSION:
439         return 0;
440     case TECHNOLOGY:
441         return DT_RASPRINTER;
442     case HORZSIZE:
443         return MulDiv(physDev->horzSize, 100,
444                       physDev->Devmode->dmPublic.u1.s1.dmScale);
445     case VERTSIZE:
446         return MulDiv(physDev->vertSize, 100,
447                       physDev->Devmode->dmPublic.u1.s1.dmScale);
448     case HORZRES:
449     case DESKTOPHORZRES:
450         return physDev->horzRes;
451     case VERTRES:
452     case DESKTOPVERTRES:
453         return physDev->vertRes;
454     case BITSPIXEL:
455         return (physDev->pi->ppd->ColorDevice != CD_False) ? 8 : 1;
456     case PLANES:
457         return 1;
458     case NUMBRUSHES:
459         return -1;
460     case NUMPENS:
461         return 10;
462     case NUMMARKERS:
463         return 0;
464     case NUMFONTS:
465         return 39;
466     case NUMCOLORS:
467         return (physDev->pi->ppd->ColorDevice != CD_False) ? 256 : -1;
468     case PDEVICESIZE:
469         return sizeof(PSDRV_PDEVICE);
470     case CURVECAPS:
471         return (CC_CIRCLES | CC_PIE | CC_CHORD | CC_ELLIPSES | CC_WIDE |
472                 CC_STYLED | CC_WIDESTYLED | CC_INTERIORS | CC_ROUNDRECT);
473     case LINECAPS:
474         return (LC_POLYLINE | LC_MARKER | LC_POLYMARKER | LC_WIDE |
475                 LC_STYLED | LC_WIDESTYLED | LC_INTERIORS);
476     case POLYGONALCAPS:
477         return (PC_POLYGON | PC_RECTANGLE | PC_WINDPOLYGON | PC_SCANLINE |
478                 PC_WIDE | PC_STYLED | PC_WIDESTYLED | PC_INTERIORS);
479     case TEXTCAPS:
480         return TC_CR_ANY | TC_VA_ABLE; /* psdrv 0x59f7 */
481     case CLIPCAPS:
482         return CP_RECTANGLE;
483     case RASTERCAPS:
484         return (RC_BITBLT | RC_BITMAP64 | RC_GDI20_OUTPUT | RC_DIBTODEV |
485                 RC_STRETCHBLT | RC_STRETCHDIB); /* psdrv 0x6e99 */
486     /* Are aspect[XY] and logPixels[XY] correct? */
487     /* Need to handle different res in x and y => fix ppd */
488     case ASPECTX:
489     case ASPECTY:
490         return physDev->pi->ppd->DefaultResolution;
491     case ASPECTXY:
492         return (int)hypot( (double)physDev->pi->ppd->DefaultResolution,
493                            (double)physDev->pi->ppd->DefaultResolution );
494     case LOGPIXELSX:
495         return MulDiv(physDev->logPixelsX,
496                       physDev->Devmode->dmPublic.u1.s1.dmScale, 100);
497     case LOGPIXELSY:
498         return MulDiv(physDev->logPixelsY,
499                       physDev->Devmode->dmPublic.u1.s1.dmScale, 100);
500     case SIZEPALETTE:
501         return 0;
502     case NUMRESERVED:
503         return 0;
504     case COLORRES:
505         return 0;
506     case PHYSICALWIDTH:
507         return (physDev->Devmode->dmPublic.u1.s1.dmOrientation == DMORIENT_LANDSCAPE) ?
508           physDev->PageSize.cy : physDev->PageSize.cx;
509     case PHYSICALHEIGHT:
510         return (physDev->Devmode->dmPublic.u1.s1.dmOrientation == DMORIENT_LANDSCAPE) ?
511           physDev->PageSize.cx : physDev->PageSize.cy;
512     case PHYSICALOFFSETX:
513       if(physDev->Devmode->dmPublic.u1.s1.dmOrientation == DMORIENT_LANDSCAPE) {
514           if(physDev->pi->ppd->LandscapeOrientation == -90)
515               return physDev->PageSize.cy - physDev->ImageableArea.top;
516           else
517               return physDev->ImageableArea.bottom;
518       }
519       return physDev->ImageableArea.left;
520
521     case PHYSICALOFFSETY:
522       if(physDev->Devmode->dmPublic.u1.s1.dmOrientation == DMORIENT_LANDSCAPE) {
523           if(physDev->pi->ppd->LandscapeOrientation == -90)
524               return physDev->PageSize.cx - physDev->ImageableArea.right;
525           else
526               return physDev->ImageableArea.left;
527       }
528       return physDev->PageSize.cy - physDev->ImageableArea.top;
529
530     case SCALINGFACTORX:
531     case SCALINGFACTORY:
532     case VREFRESH:
533     case BLTALIGNMENT:
534         return 0;
535     case SHADEBLENDCAPS:
536         return SB_NONE;
537     default:
538         FIXME("(%p): unsupported capability %d, will return 0\n", dev->hdc, cap );
539         return 0;
540     }
541 }
542
543
544 /**********************************************************************
545  *              PSDRV_FindPrinterInfo
546  */
547 PRINTERINFO *PSDRV_FindPrinterInfo(LPCSTR name)
548 {
549     static PRINTERINFO *PSDRV_PrinterList;
550     DWORD type = REG_BINARY, needed, res, dwPaperSize;
551     PRINTERINFO *pi = PSDRV_PrinterList, **last = &PSDRV_PrinterList;
552     FONTNAME *font;
553     const AFM *afm;
554     HANDLE hPrinter = 0;
555     const char *ppd = NULL;
556     DWORD ppdType;
557     char* ppdFileName = NULL;
558     HKEY hkey;
559     BOOL using_default_devmode = FALSE;
560
561     TRACE("'%s'\n", name);
562
563     /*
564      *  If this loop completes, last will point to the 'next' element of the
565      *  final PRINTERINFO in the list
566      */
567     for( ; pi; last = &pi->next, pi = pi->next)
568         if(!strcmp(pi->FriendlyName, name))
569             return pi;
570
571     pi = *last = HeapAlloc( PSDRV_Heap, HEAP_ZERO_MEMORY, sizeof(*pi) );
572     if (pi == NULL)
573         return NULL;
574
575     if (!(pi->FriendlyName = HeapAlloc( PSDRV_Heap, 0, strlen(name)+1 ))) goto fail;
576     strcpy( pi->FriendlyName, name );
577
578     if (OpenPrinterA (pi->FriendlyName, &hPrinter, NULL) == 0) {
579         ERR ("OpenPrinterA failed with code %i\n", GetLastError ());
580         goto cleanup;
581     }
582
583     needed = 0;
584     res = GetPrinterDataExA(hPrinter, NULL, default_devmodeA, &type, NULL, 0, &needed);
585
586     if (needed < sizeof(DefaultDevmode)) {
587         pi->Devmode = HeapAlloc( PSDRV_Heap, 0, sizeof(DefaultDevmode) );
588         if (pi->Devmode == NULL)
589             goto closeprinter;
590
591         *pi->Devmode = DefaultDevmode;
592         lstrcpynA((LPSTR)pi->Devmode->dmPublic.dmDeviceName,name,CCHDEVICENAME);
593         using_default_devmode = TRUE;
594     }
595     else {
596         pi->Devmode = HeapAlloc( PSDRV_Heap, 0, needed );
597         if (pi->Devmode == NULL)
598             goto closeprinter;
599
600         GetPrinterDataExA(hPrinter, NULL, default_devmodeA, &type, (LPBYTE)pi->Devmode, needed, &needed);
601     }
602
603
604
605 #ifdef SONAME_LIBCUPS
606     if (cupshandle != (void*)-1) {
607         typeof(cupsGetPPD) * pcupsGetPPD = NULL;
608
609         pcupsGetPPD = wine_dlsym(cupshandle, "cupsGetPPD", NULL, 0);
610         if (pcupsGetPPD) {
611             ppd = pcupsGetPPD(name);
612
613             if (ppd) {
614                 needed=strlen(ppd)+1;
615                 ppdFileName=HeapAlloc(PSDRV_Heap, 0, needed);
616                 memcpy(ppdFileName, ppd, needed);
617                 ppdType=REG_SZ;
618                 res = ERROR_SUCCESS;
619                 /* we should unlink() that file later */
620             } else {
621                 res = ERROR_FILE_NOT_FOUND;
622                 WARN("Did not find ppd for %s\n",name);
623             }
624         }
625     }
626 #endif
627     if (!ppdFileName) {
628         res = GetPrinterDataExA(hPrinter, "PrinterDriverData", "PPD File", NULL, NULL, 0, &needed);
629         if ((res==ERROR_SUCCESS) || (res==ERROR_MORE_DATA)) {
630             ppdFileName=HeapAlloc(PSDRV_Heap, 0, needed);
631             res = GetPrinterDataExA(hPrinter, "PrinterDriverData", "PPD File", &ppdType,
632                                     (LPBYTE)ppdFileName, needed, &needed);
633         }
634     }
635     /* Look for a ppd file for this printer in the config file.
636      * First look under that printer's name, and then under 'generic'
637      */
638     /* @@ Wine registry key: HKCU\Software\Wine\Printing\PPD Files */
639     if((res != ERROR_SUCCESS) && !RegOpenKeyA(HKEY_CURRENT_USER, "Software\\Wine\\Printing\\PPD Files", &hkey))
640     {
641         const char* value_name;
642
643         if (RegQueryValueExA(hkey, name, 0, NULL, NULL, &needed) == ERROR_SUCCESS) {
644             value_name=name;
645         } else if (RegQueryValueExA(hkey, "generic", 0, NULL, NULL, &needed) == ERROR_SUCCESS) {
646             value_name="generic";
647         } else {
648             value_name=NULL;
649         }
650         if (value_name) {
651             HeapFree(PSDRV_Heap, 0, ppdFileName);
652             ppdFileName=HeapAlloc(PSDRV_Heap, 0, needed);
653             RegQueryValueExA(hkey, value_name, 0, &ppdType, (LPBYTE)ppdFileName, &needed);
654         }
655         RegCloseKey(hkey);
656     }
657
658     if (!ppdFileName)
659     {
660         const char *data_dir, *filename;
661
662         if ((data_dir = wine_get_data_dir())) filename = "/generic.ppd";
663         else if ((data_dir = wine_get_build_dir())) filename = "/dlls/wineps.drv/generic.ppd";
664         else
665         {
666             res = ERROR_FILE_NOT_FOUND;
667             ERR ("Error %i getting PPD file name for printer '%s'\n", res, name);
668             goto closeprinter;
669         }
670         ppdFileName = HeapAlloc( PSDRV_Heap, 0, strlen(data_dir) + strlen(filename) + 1 );
671         strcpy( ppdFileName, data_dir );
672         strcat( ppdFileName, filename );
673     } else {
674         res = ERROR_SUCCESS;
675         if (ppdType==REG_EXPAND_SZ) {
676             char* tmp;
677
678             /* Expand environment variable references */
679             needed=ExpandEnvironmentStringsA(ppdFileName,NULL,0);
680             tmp=HeapAlloc(PSDRV_Heap, 0, needed);
681             ExpandEnvironmentStringsA(ppdFileName,tmp,needed);
682             HeapFree(PSDRV_Heap, 0, ppdFileName);
683             ppdFileName=tmp;
684         }
685     }
686
687     pi->ppd = PSDRV_ParsePPD(ppdFileName);
688     if(!pi->ppd) {
689         MESSAGE("Couldn't find PPD file '%s', expect a crash now!\n",
690             ppdFileName);
691         goto closeprinter;
692     }
693
694     /* Some gimp-print ppd files don't contain a DefaultResolution line
695        set it to 300 if it's not specified */
696     if(pi->ppd->DefaultResolution == 0)
697         pi->ppd->DefaultResolution = 300;
698
699     if(using_default_devmode) {
700         DWORD papersize;
701
702         if(GetLocaleInfoW(LOCALE_USER_DEFAULT, LOCALE_IPAPERSIZE | LOCALE_RETURN_NUMBER,
703                           (LPWSTR)&papersize, sizeof(papersize)/sizeof(WCHAR))) {
704             PSDRV_DEVMODEA dm;
705             memset(&dm, 0, sizeof(dm));
706             dm.dmPublic.dmFields = DM_PAPERSIZE;
707             dm.dmPublic.u1.s1.dmPaperSize = papersize;
708             PSDRV_MergeDevmodes(pi->Devmode, &dm, pi);
709         }
710
711         SetPrinterDataExA(hPrinter, NULL, default_devmodeA, REG_BINARY,
712                             (LPBYTE)pi->Devmode, sizeof(DefaultDevmode));
713     }
714
715     if(pi->ppd->DefaultPageSize) { /* We'll let the ppd override the devmode */
716         PSDRV_DEVMODEA dm;
717         memset(&dm, 0, sizeof(dm));
718         dm.dmPublic.dmFields = DM_PAPERSIZE;
719         dm.dmPublic.u1.s1.dmPaperSize = pi->ppd->DefaultPageSize->WinPage;
720         PSDRV_MergeDevmodes(pi->Devmode, &dm, pi);
721     }
722
723     /*
724      *  This is a hack.  The default paper size should be read in as part of
725      *  the Devmode structure, but Wine doesn't currently provide a convenient
726      *  way to configure printers.
727      */
728     res = GetPrinterDataExA(hPrinter, "PrinterDriverData", "Paper Size", NULL,
729                             (LPBYTE)&dwPaperSize, sizeof(DWORD), &needed);
730     if (res == ERROR_SUCCESS)
731         pi->Devmode->dmPublic.u1.s1.dmPaperSize = (SHORT) dwPaperSize;
732     else if (res == ERROR_FILE_NOT_FOUND)
733         TRACE ("No 'Paper Size' for printer '%s'\n", name);
734     else {
735         ERR ("GetPrinterDataA returned %i\n", res);
736         goto closeprinter;
737     }
738
739     /* Duplex is indicated by the setting of the DM_DUPLEX bit in dmFields.
740        WinDuplex == 0 is a special case which means that the ppd has a
741        *DefaultDuplex: NotCapable entry.  In this case we'll try not to confuse
742        apps and set dmDuplex to DMDUP_SIMPLEX but leave the DM_DUPLEX clear.
743        PSDRV_WriteHeader understands this and copes. */
744     pi->Devmode->dmPublic.dmFields &= ~DM_DUPLEX;
745     if(pi->ppd->DefaultDuplex) {
746         pi->Devmode->dmPublic.dmDuplex = pi->ppd->DefaultDuplex->WinDuplex;
747         if(pi->Devmode->dmPublic.dmDuplex != 0)
748             pi->Devmode->dmPublic.dmFields |= DM_DUPLEX;
749         else
750             pi->Devmode->dmPublic.dmDuplex = DMDUP_SIMPLEX;
751     }
752
753     res = EnumPrinterDataExA (hPrinter, "PrinterDriverData\\FontSubTable", NULL,
754             0, &needed, &pi->FontSubTableSize);
755     if (res == ERROR_SUCCESS || res == ERROR_FILE_NOT_FOUND) {
756         TRACE ("No 'FontSubTable' for printer '%s'\n", name);
757     }
758     else if (res == ERROR_MORE_DATA) {
759         pi->FontSubTable = HeapAlloc (PSDRV_Heap, 0, needed);
760         if (pi->FontSubTable == NULL) {
761             ERR ("Failed to allocate %i bytes from heap\n", needed);
762             goto closeprinter;
763         }
764
765         res = EnumPrinterDataExA (hPrinter, "PrinterDriverData\\FontSubTable",
766                 (LPBYTE) pi->FontSubTable, needed, &needed,
767                 &pi->FontSubTableSize);
768         if (res != ERROR_SUCCESS) {
769             ERR ("EnumPrinterDataExA returned %i\n", res);
770             goto closeprinter;
771         }
772     }
773     else {
774         ERR("EnumPrinterDataExA returned %i\n", res);
775         goto closeprinter;
776     }
777
778     if (ClosePrinter (hPrinter) == 0) {
779         ERR ("ClosePrinter failed with code %i\n", GetLastError ());
780         goto cleanup;
781     }
782
783     pi->next = NULL;
784     pi->Fonts = NULL;
785
786     for(font = pi->ppd->InstalledFonts; font; font = font->next) {
787         afm = PSDRV_FindAFMinList(PSDRV_AFMFontList, font->Name);
788         if(!afm) {
789             TRACE( "Couldn't find AFM file for installed printer font '%s' - "
790                     "ignoring\n", font->Name);
791         }
792         else {
793             BOOL added;
794             if (PSDRV_AddAFMtoList(&pi->Fonts, afm, &added) == FALSE) {
795                 PSDRV_FreeAFMList(pi->Fonts);
796                 goto cleanup;
797             }
798         }
799
800     }
801     if (ppd) unlink(ppd);
802     return pi;
803
804 closeprinter:
805     ClosePrinter(hPrinter);
806 cleanup:
807     HeapFree(PSDRV_Heap, 0, ppdFileName);
808     HeapFree(PSDRV_Heap, 0, pi->FontSubTable);
809     HeapFree(PSDRV_Heap, 0, pi->FriendlyName);
810     HeapFree(PSDRV_Heap, 0, pi->Devmode);
811 fail:
812     HeapFree(PSDRV_Heap, 0, pi);
813     if (ppd) unlink(ppd);
814     *last = NULL;
815     return NULL;
816 }
817
818
819 static const struct gdi_dc_funcs psdrv_funcs =
820 {
821     NULL,                               /* pAbortDoc */
822     NULL,                               /* pAbortPath */
823     NULL,                               /* pAlphaBlend */
824     NULL,                               /* pAngleArc */
825     PSDRV_Arc,                          /* pArc */
826     NULL,                               /* pArcTo */
827     NULL,                               /* pBeginPath */
828     NULL,                               /* pChoosePixelFormat */
829     PSDRV_Chord,                        /* pChord */
830     NULL,                               /* pCloseFigure */
831     NULL,                               /* pCreateBitmap */
832     PSDRV_CreateCompatibleDC,           /* pCreateCompatibleDC */
833     PSDRV_CreateDC,                     /* pCreateDC */
834     NULL,                               /* pCreateDIBSection */
835     NULL,                               /* pDeleteBitmap */
836     PSDRV_DeleteDC,                     /* pDeleteDC */
837     NULL,                               /* pDeleteObject */
838     NULL,                               /* pDescribePixelFormat */
839     PSDRV_DeviceCapabilities,           /* pDeviceCapabilities */
840     PSDRV_Ellipse,                      /* pEllipse */
841     PSDRV_EndDoc,                       /* pEndDoc */
842     PSDRV_EndPage,                      /* pEndPage */
843     NULL,                               /* pEndPath */
844     PSDRV_EnumDeviceFonts,              /* pEnumDeviceFonts */
845     NULL,                               /* pEnumICMProfiles */
846     NULL,                               /* pExcludeClipRect */
847     PSDRV_ExtDeviceMode,                /* pExtDeviceMode */
848     PSDRV_ExtEscape,                    /* pExtEscape */
849     NULL,                               /* pExtFloodFill */
850     NULL,                               /* pExtSelectClipRgn */
851     PSDRV_ExtTextOut,                   /* pExtTextOut */
852     NULL,                               /* pFillPath */
853     NULL,                               /* pFillRgn */
854     NULL,                               /* pFlattenPath */
855     NULL,                               /* pFrameRgn */
856     NULL,                               /* pGdiComment */
857     PSDRV_GetCharWidth,                 /* pGetCharWidth */
858     PSDRV_GetDeviceCaps,                /* pGetDeviceCaps */
859     NULL,                               /* pGetDeviceGammaRamp */
860     NULL,                               /* pGetICMProfile */
861     NULL,                               /* pGetImage */
862     NULL,                               /* pGetNearestColor */
863     NULL,                               /* pGetPixel */
864     NULL,                               /* pGetPixelFormat */
865     NULL,                               /* pGetSystemPaletteEntries */
866     PSDRV_GetTextExtentExPoint,         /* pGetTextExtentExPoint */
867     PSDRV_GetTextMetrics,               /* pGetTextMetrics */
868     NULL,                               /* pIntersectClipRect */
869     NULL,                               /* pInvertRgn */
870     PSDRV_LineTo,                       /* pLineTo */
871     NULL,                               /* pModifyWorldTransform */
872     NULL,                               /* pMoveTo */
873     NULL,                               /* pOffsetClipRgn */
874     NULL,                               /* pOffsetViewportOrg */
875     NULL,                               /* pOffsetWindowOrg */
876     PSDRV_PaintRgn,                     /* pPaintRgn */
877     PSDRV_PatBlt,                       /* pPatBlt */
878     PSDRV_Pie,                          /* pPie */
879     NULL,                               /* pPolyBezier */
880     NULL,                               /* pPolyBezierTo */
881     NULL,                               /* pPolyDraw */
882     PSDRV_PolyPolygon,                  /* pPolyPolygon */
883     PSDRV_PolyPolyline,                 /* pPolyPolyline */
884     PSDRV_Polygon,                      /* pPolygon */
885     PSDRV_Polyline,                     /* pPolyline */
886     NULL,                               /* pPolylineTo */
887     PSDRV_PutImage,                     /* pPutImage */
888     NULL,                               /* pRealizeDefaultPalette */
889     NULL,                               /* pRealizePalette */
890     PSDRV_Rectangle,                    /* pRectangle */
891     PSDRV_ResetDC,                      /* pResetDC */
892     NULL,                               /* pRestoreDC */
893     PSDRV_RoundRect,                    /* pRoundRect */
894     NULL,                               /* pSaveDC */
895     NULL,                               /* pScaleViewportExt */
896     NULL,                               /* pScaleWindowExt */
897     NULL,                               /* pSelectBitmap */
898     PSDRV_SelectBrush,                  /* pSelectBrush */
899     NULL,                               /* pSelectClipPath */
900     PSDRV_SelectFont,                   /* pSelectFont */
901     NULL,                               /* pSelectPalette */
902     PSDRV_SelectPen,                    /* pSelectPen */
903     NULL,                               /* pSetArcDirection */
904     PSDRV_SetBkColor,                   /* pSetBkColor */
905     NULL,                               /* pSetBkMode */
906     PSDRV_SetDCBrushColor,              /* pSetDCBrushColor */
907     PSDRV_SetDCPenColor,                /* pSetDCPenColor */
908     NULL,                               /* pSetDIBColorTable */
909     NULL,                               /* pSetDIBitsToDevice */
910     NULL,                               /* pSetDeviceClipping */
911     NULL,                               /* pSetDeviceGammaRamp */
912     NULL,                               /* pSetLayout */
913     NULL,                               /* pSetMapMode */
914     NULL,                               /* pSetMapperFlags */
915     PSDRV_SetPixel,                     /* pSetPixel */
916     NULL,                               /* pSetPixelFormat */
917     NULL,                               /* pSetPolyFillMode */
918     NULL,                               /* pSetROP2 */
919     NULL,                               /* pSetRelAbs */
920     NULL,                               /* pSetStretchBltMode */
921     NULL,                               /* pSetTextAlign */
922     NULL,                               /* pSetTextCharacterExtra */
923     PSDRV_SetTextColor,                 /* pSetTextColor */
924     NULL,                               /* pSetTextJustification */
925     NULL,                               /* pSetViewportExt */
926     NULL,                               /* pSetViewportOrg */
927     NULL,                               /* pSetWindowExt */
928     NULL,                               /* pSetWindowOrg */
929     NULL,                               /* pSetWorldTransform */
930     PSDRV_StartDoc,                     /* pStartDoc */
931     PSDRV_StartPage,                    /* pStartPage */
932     NULL,                               /* pStretchBlt */
933     PSDRV_StretchDIBits,                /* pStretchDIBits */
934     NULL,                               /* pStrokeAndFillPath */
935     NULL,                               /* pStrokePath */
936     NULL,                               /* pSwapBuffers */
937     NULL,                               /* pUnrealizePalette */
938     NULL,                               /* pWidenPath */
939     /* OpenGL not supported */
940 };
941
942
943 /******************************************************************************
944  *      PSDRV_get_gdi_driver
945  */
946 const struct gdi_dc_funcs * CDECL PSDRV_get_gdi_driver( unsigned int version )
947 {
948     if (version != WINE_GDI_DRIVER_VERSION)
949     {
950         ERR( "version mismatch, gdi32 wants %u but wineps has %u\n", version, WINE_GDI_DRIVER_VERSION );
951         return NULL;
952     }
953     return &psdrv_funcs;
954 }