ole32: Fix memory leaks in the storage test.
[wine] / dlls / comdlg32 / printdlg.c
1 /*
2  * COMMDLG - Print Dialog
3  *
4  * Copyright 1994 Martin Ayotte
5  * Copyright 1996 Albrecht Kleine
6  * Copyright 1999 Klaas van Gend
7  * Copyright 2000 Huw D M Davies
8  *
9  * This library is free software; you can redistribute it and/or
10  * modify it under the terms of the GNU Lesser General Public
11  * License as published by the Free Software Foundation; either
12  * version 2.1 of the License, or (at your option) any later version.
13  *
14  * This library is distributed in the hope that it will be useful,
15  * but WITHOUT ANY WARRANTY; without even the implied warranty of
16  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
17  * Lesser General Public License for more details.
18  *
19  * You should have received a copy of the GNU Lesser General Public
20  * License along with this library; if not, write to the Free Software
21  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
22  */
23 #include <ctype.h>
24 #include <stdlib.h>
25 #include <stdarg.h>
26 #include <stdio.h>
27 #include <string.h>
28 #include <assert.h>
29
30 #define NONAMELESSUNION
31 #define NONAMELESSSTRUCT
32 #include "windef.h"
33 #include "winbase.h"
34 #include "wingdi.h"
35 #include "winuser.h"
36 #include "winspool.h"
37 #include "winerror.h"
38
39 #include "wine/unicode.h"
40 #include "wine/debug.h"
41
42 #include "commdlg.h"
43 #include "dlgs.h"
44 #include "cderr.h"
45 #include "cdlg.h"
46
47 WINE_DEFAULT_DEBUG_CHANNEL(commdlg);
48
49 /* Yes these constants are the same, but we're just copying win98 */
50 #define UPDOWN_ID 0x270f
51 #define MAX_COPIES 9999
52
53 /* This PRINTDLGA internal structure stores
54  * pointers to several throughout useful structures.
55  */
56
57 typedef struct
58 {
59   LPDEVMODEA        lpDevMode;
60   LPPRINTDLGA       lpPrintDlg;
61   LPPRINTER_INFO_2A lpPrinterInfo;
62   LPDRIVER_INFO_3A  lpDriverInfo;
63   UINT              HelpMessageID;
64   HICON             hCollateIcon;    /* PrintDlg only */
65   HICON             hNoCollateIcon;  /* PrintDlg only */
66   HICON             hPortraitIcon;   /* PrintSetupDlg only */
67   HICON             hLandscapeIcon;  /* PrintSetupDlg only */
68   HWND              hwndUpDown;
69 } PRINT_PTRA;
70
71 typedef struct
72 {
73   LPDEVMODEW        lpDevMode;
74   LPPRINTDLGW       lpPrintDlg;
75   LPPRINTER_INFO_2W lpPrinterInfo;
76   LPDRIVER_INFO_3W  lpDriverInfo;
77   UINT              HelpMessageID;
78   HICON             hCollateIcon;    /* PrintDlg only */
79   HICON             hNoCollateIcon;  /* PrintDlg only */
80   HICON             hPortraitIcon;   /* PrintSetupDlg only */
81   HICON             hLandscapeIcon;  /* PrintSetupDlg only */
82   HWND              hwndUpDown;
83 } PRINT_PTRW;
84
85 /* Debugging info */
86 struct pd_flags
87 {
88   DWORD  flag;
89   LPCSTR name;
90 };
91
92 static const struct pd_flags psd_flags[] = {
93   {PSD_MINMARGINS,"PSD_MINMARGINS"},
94   {PSD_MARGINS,"PSD_MARGINS"},
95   {PSD_INTHOUSANDTHSOFINCHES,"PSD_INTHOUSANDTHSOFINCHES"},
96   {PSD_INHUNDREDTHSOFMILLIMETERS,"PSD_INHUNDREDTHSOFMILLIMETERS"},
97   {PSD_DISABLEMARGINS,"PSD_DISABLEMARGINS"},
98   {PSD_DISABLEPRINTER,"PSD_DISABLEPRINTER"},
99   {PSD_NOWARNING,"PSD_NOWARNING"},
100   {PSD_DISABLEORIENTATION,"PSD_DISABLEORIENTATION"},
101   {PSD_RETURNDEFAULT,"PSD_RETURNDEFAULT"},
102   {PSD_DISABLEPAPER,"PSD_DISABLEPAPER"},
103   {PSD_SHOWHELP,"PSD_SHOWHELP"},
104   {PSD_ENABLEPAGESETUPHOOK,"PSD_ENABLEPAGESETUPHOOK"},
105   {PSD_ENABLEPAGESETUPTEMPLATE,"PSD_ENABLEPAGESETUPTEMPLATE"},
106   {PSD_ENABLEPAGESETUPTEMPLATEHANDLE,"PSD_ENABLEPAGESETUPTEMPLATEHANDLE"},
107   {PSD_ENABLEPAGEPAINTHOOK,"PSD_ENABLEPAGEPAINTHOOK"},
108   {PSD_DISABLEPAGEPAINTING,"PSD_DISABLEPAGEPAINTING"},
109   {-1, NULL}
110 };
111
112 static const struct pd_flags pd_flags[] = {
113   {PD_SELECTION, "PD_SELECTION "},
114   {PD_PAGENUMS, "PD_PAGENUMS "},
115   {PD_NOSELECTION, "PD_NOSELECTION "},
116   {PD_NOPAGENUMS, "PD_NOPAGENUMS "},
117   {PD_COLLATE, "PD_COLLATE "},
118   {PD_PRINTTOFILE, "PD_PRINTTOFILE "},
119   {PD_PRINTSETUP, "PD_PRINTSETUP "},
120   {PD_NOWARNING, "PD_NOWARNING "},
121   {PD_RETURNDC, "PD_RETURNDC "},
122   {PD_RETURNIC, "PD_RETURNIC "},
123   {PD_RETURNDEFAULT, "PD_RETURNDEFAULT "},
124   {PD_SHOWHELP, "PD_SHOWHELP "},
125   {PD_ENABLEPRINTHOOK, "PD_ENABLEPRINTHOOK "},
126   {PD_ENABLESETUPHOOK, "PD_ENABLESETUPHOOK "},
127   {PD_ENABLEPRINTTEMPLATE, "PD_ENABLEPRINTTEMPLATE "},
128   {PD_ENABLESETUPTEMPLATE, "PD_ENABLESETUPTEMPLATE "},
129   {PD_ENABLEPRINTTEMPLATEHANDLE, "PD_ENABLEPRINTTEMPLATEHANDLE "},
130   {PD_ENABLESETUPTEMPLATEHANDLE, "PD_ENABLESETUPTEMPLATEHANDLE "},
131   {PD_USEDEVMODECOPIES, "PD_USEDEVMODECOPIES[ANDCOLLATE] "},
132   {PD_DISABLEPRINTTOFILE, "PD_DISABLEPRINTTOFILE "},
133   {PD_HIDEPRINTTOFILE, "PD_HIDEPRINTTOFILE "},
134   {PD_NONETWORKBUTTON, "PD_NONETWORKBUTTON "},
135   {-1, NULL}
136 };
137 /* address of wndproc for subclassed Static control */
138 static WNDPROC lpfnStaticWndProc;
139 static WNDPROC edit_wndproc;
140 /* the text of the fake document to render for the Page Setup dialog */
141 static WCHAR wszFakeDocumentText[1024];
142 static const WCHAR pd32_collateW[] = { 'P', 'D', '3', '2', '_', 'C', 'O', 'L', 'L', 'A', 'T', 'E', 0 };
143 static const WCHAR pd32_nocollateW[] = { 'P', 'D', '3', '2', '_', 'N', 'O', 'C', 'O', 'L', 'L', 'A', 'T', 'E', 0 };
144 static const WCHAR pd32_portraitW[] = { 'P', 'D', '3', '2', '_', 'P', 'O', 'R', 'T', 'R', 'A', 'I', 'T', 0 };
145 static const WCHAR pd32_landscapeW[] = { 'P', 'D', '3', '2', '_', 'L', 'A', 'N', 'D', 'S', 'C', 'A', 'P', 'E', 0 };
146 static const WCHAR printdlg_prop[] = {'_','_','W','I','N','E','_','P','R','I','N','T','D','L','G','D','A','T','A',0};
147 static const WCHAR pagesetupdlg_prop[] = { '_', '_', 'W', 'I', 'N', 'E', '_', 'P', 'A', 'G', 'E',
148                                            'S', 'E', 'T', 'U', 'P', 'D', 'L', 'G', 'D', 'A', 'T', 'A', 0 };
149
150
151 static LPWSTR strdupW(LPCWSTR p)
152 {
153     LPWSTR ret;
154     DWORD len;
155
156     if(!p) return NULL;
157     len = (strlenW(p) + 1) * sizeof(WCHAR);
158     ret = HeapAlloc(GetProcessHeap(), 0, len);
159     memcpy(ret, p, len);
160     return ret;
161 }
162
163 /***********************************************************
164  * convert_to_devmodeA
165  *
166  * Creates an ansi copy of supplied devmode
167  */
168 static DEVMODEA *convert_to_devmodeA(const DEVMODEW *dmW)
169 {
170     DEVMODEA *dmA;
171     DWORD size;
172
173     if (!dmW) return NULL;
174     size = dmW->dmSize - CCHDEVICENAME -
175                         ((dmW->dmSize > FIELD_OFFSET(DEVMODEW, dmFormName)) ? CCHFORMNAME : 0);
176
177     dmA = HeapAlloc(GetProcessHeap(), 0, size + dmW->dmDriverExtra);
178     if (!dmA) return NULL;
179
180     WideCharToMultiByte(CP_ACP, 0, dmW->dmDeviceName, -1,
181                         (LPSTR)dmA->dmDeviceName, CCHDEVICENAME, NULL, NULL);
182
183     if (FIELD_OFFSET(DEVMODEW, dmFormName) >= dmW->dmSize)
184     {
185         memcpy(&dmA->dmSpecVersion, &dmW->dmSpecVersion,
186                dmW->dmSize - FIELD_OFFSET(DEVMODEW, dmSpecVersion));
187     }
188     else
189     {
190         memcpy(&dmA->dmSpecVersion, &dmW->dmSpecVersion,
191                FIELD_OFFSET(DEVMODEW, dmFormName) - FIELD_OFFSET(DEVMODEW, dmSpecVersion));
192         WideCharToMultiByte(CP_ACP, 0, dmW->dmFormName, -1,
193                             (LPSTR)dmA->dmFormName, CCHFORMNAME, NULL, NULL);
194
195         memcpy(&dmA->dmLogPixels, &dmW->dmLogPixels, dmW->dmSize - FIELD_OFFSET(DEVMODEW, dmLogPixels));
196     }
197
198     dmA->dmSize = size;
199     memcpy((char *)dmA + dmA->dmSize, (const char *)dmW + dmW->dmSize, dmW->dmDriverExtra);
200     return dmA;
201 }
202
203 /***********************************************************************
204  *    PRINTDLG_OpenDefaultPrinter
205  *
206  * Returns a winspool printer handle to the default printer in *hprn
207  * Caller must call ClosePrinter on the handle
208  *
209  * Returns TRUE on success else FALSE
210  */
211 static BOOL PRINTDLG_OpenDefaultPrinter(HANDLE *hprn)
212 {
213     WCHAR buf[260];
214     DWORD dwBufLen = sizeof(buf) / sizeof(buf[0]);
215     BOOL res;
216     if(!GetDefaultPrinterW(buf, &dwBufLen))
217         return FALSE;
218     res = OpenPrinterW(buf, hprn, NULL);
219     if (!res)
220         WARN("Could not open printer %s\n", debugstr_w(buf));
221     return res;
222 }
223
224 /***********************************************************************
225  *    PRINTDLG_SetUpPrinterListCombo
226  *
227  * Initializes printer list combox.
228  * hDlg:  HWND of dialog
229  * id:    Control id of combo
230  * name:  Name of printer to select
231  *
232  * Initializes combo with list of available printers.  Selects printer 'name'
233  * If name is NULL or does not exist select the default printer.
234  *
235  * Returns number of printers added to list.
236  */
237 static INT PRINTDLG_SetUpPrinterListComboA(HWND hDlg, UINT id, LPCSTR name)
238 {
239     DWORD needed, num;
240     INT i;
241     LPPRINTER_INFO_2A pi;
242     EnumPrintersA(PRINTER_ENUM_LOCAL, NULL, 2, NULL, 0, &needed, &num);
243     pi = HeapAlloc(GetProcessHeap(), 0, needed);
244     EnumPrintersA(PRINTER_ENUM_LOCAL, NULL, 2, (LPBYTE)pi, needed, &needed,
245                   &num);
246
247     SendDlgItemMessageA(hDlg, id, CB_RESETCONTENT, 0, 0);
248     
249     for(i = 0; i < num; i++) {
250         SendDlgItemMessageA(hDlg, id, CB_ADDSTRING, 0,
251                             (LPARAM)pi[i].pPrinterName );
252     }
253     HeapFree(GetProcessHeap(), 0, pi);
254     if(!name ||
255        (i = SendDlgItemMessageA(hDlg, id, CB_FINDSTRINGEXACT, -1,
256                                 (LPARAM)name)) == CB_ERR) {
257
258         char buf[260];
259         DWORD dwBufLen = sizeof(buf);
260         if (name != NULL)
261             WARN("Can't find %s in printer list so trying to find default\n",
262                 debugstr_a(name));
263         if(!GetDefaultPrinterA(buf, &dwBufLen))
264             return num;
265         i = SendDlgItemMessageA(hDlg, id, CB_FINDSTRINGEXACT, -1, (LPARAM)buf);
266         if(i == CB_ERR)
267             FIXME("Can't find default printer in printer list\n");
268     }
269     SendDlgItemMessageA(hDlg, id, CB_SETCURSEL, i, 0);
270     return num;
271 }
272
273 static INT PRINTDLG_SetUpPrinterListComboW(HWND hDlg, UINT id, LPCWSTR name)
274 {
275     DWORD needed, num;
276     INT i;
277     LPPRINTER_INFO_2W pi;
278     EnumPrintersW(PRINTER_ENUM_LOCAL, NULL, 2, NULL, 0, &needed, &num);
279     pi = HeapAlloc(GetProcessHeap(), 0, needed);
280     EnumPrintersW(PRINTER_ENUM_LOCAL, NULL, 2, (LPBYTE)pi, needed, &needed,
281                   &num);
282
283     for(i = 0; i < num; i++) {
284         SendDlgItemMessageW(hDlg, id, CB_ADDSTRING, 0,
285                             (LPARAM)pi[i].pPrinterName );
286     }
287     HeapFree(GetProcessHeap(), 0, pi);
288     if(!name ||
289        (i = SendDlgItemMessageW(hDlg, id, CB_FINDSTRINGEXACT, -1,
290                                 (LPARAM)name)) == CB_ERR) {
291         WCHAR buf[260];
292         DWORD dwBufLen = sizeof(buf)/sizeof(buf[0]);
293         if (name != NULL)
294             WARN("Can't find %s in printer list so trying to find default\n",
295                 debugstr_w(name));
296         if(!GetDefaultPrinterW(buf, &dwBufLen))
297             return num;
298         i = SendDlgItemMessageW(hDlg, id, CB_FINDSTRINGEXACT, -1, (LPARAM)buf);
299         if(i == CB_ERR)
300             TRACE("Can't find default printer in printer list\n");
301     }
302     SendDlgItemMessageW(hDlg, id, CB_SETCURSEL, i, 0);
303     return num;
304 }
305
306 /***********************************************************************
307  *             PRINTDLG_CreateDevNames          [internal]
308  *
309  *
310  *   creates a DevNames structure.
311  *
312  *  (NB. when we handle unicode the offsets will be in wchars).
313  */
314 static BOOL PRINTDLG_CreateDevNames(HGLOBAL *hmem, const char* DeviceDriverName,
315                                     const char* DeviceName, const char* OutputPort)
316 {
317     long size;
318     char*   pDevNamesSpace;
319     char*   pTempPtr;
320     LPDEVNAMES lpDevNames;
321     char buf[260];
322     DWORD dwBufLen = sizeof(buf);
323
324     size = strlen(DeviceDriverName) + 1
325             + strlen(DeviceName) + 1
326             + strlen(OutputPort) + 1
327             + sizeof(DEVNAMES);
328
329     if(*hmem)
330         *hmem = GlobalReAlloc(*hmem, size, GMEM_MOVEABLE);
331     else
332         *hmem = GlobalAlloc(GMEM_MOVEABLE, size);
333     if (*hmem == 0)
334         return FALSE;
335
336     pDevNamesSpace = GlobalLock(*hmem);
337     lpDevNames = (LPDEVNAMES) pDevNamesSpace;
338
339     pTempPtr = pDevNamesSpace + sizeof(DEVNAMES);
340     strcpy(pTempPtr, DeviceDriverName);
341     lpDevNames->wDriverOffset = pTempPtr - pDevNamesSpace;
342
343     pTempPtr += strlen(DeviceDriverName) + 1;
344     strcpy(pTempPtr, DeviceName);
345     lpDevNames->wDeviceOffset = pTempPtr - pDevNamesSpace;
346
347     pTempPtr += strlen(DeviceName) + 1;
348     strcpy(pTempPtr, OutputPort);
349     lpDevNames->wOutputOffset = pTempPtr - pDevNamesSpace;
350
351     GetDefaultPrinterA(buf, &dwBufLen);
352     lpDevNames->wDefault = (strcmp(buf, DeviceName) == 0) ? 1 : 0;
353     GlobalUnlock(*hmem);
354     return TRUE;
355 }
356
357 static BOOL PRINTDLG_CreateDevNamesW(HGLOBAL *hmem, LPCWSTR DeviceDriverName,
358                                     LPCWSTR DeviceName, LPCWSTR OutputPort)
359 {
360     long size;
361     LPWSTR   pDevNamesSpace;
362     LPWSTR   pTempPtr;
363     LPDEVNAMES lpDevNames;
364     WCHAR bufW[260];
365     DWORD dwBufLen = sizeof(bufW) / sizeof(WCHAR);
366
367     size = sizeof(WCHAR)*lstrlenW(DeviceDriverName) + 2
368             + sizeof(WCHAR)*lstrlenW(DeviceName) + 2
369             + sizeof(WCHAR)*lstrlenW(OutputPort) + 2
370             + sizeof(DEVNAMES);
371
372     if(*hmem)
373         *hmem = GlobalReAlloc(*hmem, size, GMEM_MOVEABLE);
374     else
375         *hmem = GlobalAlloc(GMEM_MOVEABLE, size);
376     if (*hmem == 0)
377         return FALSE;
378
379     pDevNamesSpace = GlobalLock(*hmem);
380     lpDevNames = (LPDEVNAMES) pDevNamesSpace;
381
382     pTempPtr = (LPWSTR)((LPDEVNAMES)pDevNamesSpace + 1);
383     lstrcpyW(pTempPtr, DeviceDriverName);
384     lpDevNames->wDriverOffset = pTempPtr - pDevNamesSpace;
385
386     pTempPtr += lstrlenW(DeviceDriverName) + 1;
387     lstrcpyW(pTempPtr, DeviceName);
388     lpDevNames->wDeviceOffset = pTempPtr - pDevNamesSpace;
389
390     pTempPtr += lstrlenW(DeviceName) + 1;
391     lstrcpyW(pTempPtr, OutputPort);
392     lpDevNames->wOutputOffset = pTempPtr - pDevNamesSpace;
393
394     GetDefaultPrinterW(bufW, &dwBufLen);
395     lpDevNames->wDefault = (lstrcmpW(bufW, DeviceName) == 0) ? 1 : 0;
396     GlobalUnlock(*hmem);
397     return TRUE;
398 }
399
400 /***********************************************************************
401  *             PRINTDLG_UpdatePrintDlg          [internal]
402  *
403  *
404  *   updates the PrintDlg structure for return values.
405  *
406  * RETURNS
407  *   FALSE if user is not allowed to close (i.e. wrong nTo or nFrom values)
408  *   TRUE  if successful.
409  */
410 static BOOL PRINTDLG_UpdatePrintDlgA(HWND hDlg,
411                                     PRINT_PTRA* PrintStructures)
412 {
413     LPPRINTDLGA       lppd = PrintStructures->lpPrintDlg;
414     PDEVMODEA         lpdm = PrintStructures->lpDevMode;
415     LPPRINTER_INFO_2A pi = PrintStructures->lpPrinterInfo;
416
417
418     if(!lpdm) {
419         FIXME("No lpdm ptr?\n");
420         return FALSE;
421     }
422
423
424     if(!(lppd->Flags & PD_PRINTSETUP)) {
425         /* check whether nFromPage and nToPage are within range defined by
426          * nMinPage and nMaxPage
427          */
428         if (IsDlgButtonChecked(hDlg, rad3) == BST_CHECKED) { /* Pages */
429             WORD nToPage;
430             WORD nFromPage;
431             BOOL translated;
432             nFromPage = GetDlgItemInt(hDlg, edt1, NULL, FALSE);
433             nToPage   = GetDlgItemInt(hDlg, edt2, &translated, FALSE);
434
435             /* if no ToPage value is entered, use the FromPage value */
436             if(!translated) nToPage = nFromPage;
437
438             if (nFromPage < lppd->nMinPage || nFromPage > lppd->nMaxPage ||
439                 nToPage < lppd->nMinPage || nToPage > lppd->nMaxPage) {
440                 WCHAR resourcestr[256];
441                 WCHAR resultstr[256];
442                 LoadStringW(COMDLG32_hInstance, PD32_INVALID_PAGE_RANGE, resourcestr, 255);
443                 wsprintfW(resultstr,resourcestr, lppd->nMinPage, lppd->nMaxPage);
444                 LoadStringW(COMDLG32_hInstance, PD32_PRINT_TITLE, resourcestr, 255);
445                 MessageBoxW(hDlg, resultstr, resourcestr, MB_OK | MB_ICONWARNING);
446                 return FALSE;
447             }
448             lppd->nFromPage = nFromPage;
449             lppd->nToPage   = nToPage;
450             lppd->Flags |= PD_PAGENUMS;
451         }
452         else
453             lppd->Flags &= ~PD_PAGENUMS;
454
455         if (IsDlgButtonChecked(hDlg, rad2) == BST_CHECKED) /* Selection */
456             lppd->Flags |= PD_SELECTION;
457         else
458             lppd->Flags &= ~PD_SELECTION;
459
460         if (IsDlgButtonChecked(hDlg, chx1) == BST_CHECKED) {/* Print to file */
461             static char file[] = "FILE:";
462             lppd->Flags |= PD_PRINTTOFILE;
463             pi->pPortName = file;
464         }
465
466         if (IsDlgButtonChecked(hDlg, chx2) == BST_CHECKED) { /* Collate */
467             FIXME("Collate lppd not yet implemented as output\n");
468         }
469
470         /* set PD_Collate and nCopies */
471         if (lppd->Flags & PD_USEDEVMODECOPIESANDCOLLATE) {
472           /*  The application doesn't support multiple copies or collate...
473            */
474             lppd->Flags &= ~PD_COLLATE;
475             lppd->nCopies = 1;
476           /* if the printer driver supports it... store info there
477            * otherwise no collate & multiple copies !
478            */
479             if (lpdm->dmFields & DM_COLLATE)
480                 lpdm->dmCollate =
481                   (IsDlgButtonChecked(hDlg, chx2) == BST_CHECKED);
482             if (lpdm->dmFields & DM_COPIES)
483                 lpdm->u1.s1.dmCopies = GetDlgItemInt(hDlg, edt3, NULL, FALSE);
484         } else {
485             /* Application is responsible for multiple copies */
486             if (IsDlgButtonChecked(hDlg, chx2) == BST_CHECKED)
487                 lppd->Flags |= PD_COLLATE;
488             else
489                lppd->Flags &= ~PD_COLLATE;
490             lppd->nCopies = GetDlgItemInt(hDlg, edt3, NULL, FALSE);
491             /* multiple copies already included in the document. Driver must print only one copy */
492             lpdm->u1.s1.dmCopies = 1;
493         }
494
495         /* Print quality, PrintDlg16 */
496         if(GetDlgItem(hDlg, cmb1))
497         {
498             HWND hQuality = GetDlgItem(hDlg, cmb1);
499             int Sel = SendMessageA(hQuality, CB_GETCURSEL, 0, 0);
500
501             if(Sel != CB_ERR)
502             {
503                 LONG dpi = SendMessageA(hQuality, CB_GETITEMDATA, Sel, 0);
504                 lpdm->dmFields |= DM_PRINTQUALITY | DM_YRESOLUTION;
505                 lpdm->u1.s1.dmPrintQuality = LOWORD(dpi);
506                 lpdm->dmYResolution = HIWORD(dpi);
507             }
508         }
509     }
510     return TRUE;
511 }
512
513 static BOOL PRINTDLG_UpdatePrintDlgW(HWND hDlg,
514                                     PRINT_PTRW* PrintStructures)
515 {
516     LPPRINTDLGW       lppd = PrintStructures->lpPrintDlg;
517     PDEVMODEW         lpdm = PrintStructures->lpDevMode;
518     LPPRINTER_INFO_2W pi = PrintStructures->lpPrinterInfo;
519
520
521     if(!lpdm) {
522         FIXME("No lpdm ptr?\n");
523         return FALSE;
524     }
525
526
527     if(!(lppd->Flags & PD_PRINTSETUP)) {
528         /* check whether nFromPage and nToPage are within range defined by
529          * nMinPage and nMaxPage
530          */
531         if (IsDlgButtonChecked(hDlg, rad3) == BST_CHECKED) { /* Pages */
532             WORD nToPage;
533             WORD nFromPage;
534             BOOL translated;
535             nFromPage = GetDlgItemInt(hDlg, edt1, NULL, FALSE);
536             nToPage   = GetDlgItemInt(hDlg, edt2, &translated, FALSE);
537
538             /* if no ToPage value is entered, use the FromPage value */
539             if(!translated) nToPage = nFromPage;
540
541             if (nFromPage < lppd->nMinPage || nFromPage > lppd->nMaxPage ||
542                 nToPage < lppd->nMinPage || nToPage > lppd->nMaxPage) {
543                 WCHAR resourcestr[256];
544                 WCHAR resultstr[256];
545                 LoadStringW(COMDLG32_hInstance, PD32_INVALID_PAGE_RANGE,
546                             resourcestr, 255);
547                 wsprintfW(resultstr,resourcestr, lppd->nMinPage, lppd->nMaxPage);
548                 LoadStringW(COMDLG32_hInstance, PD32_PRINT_TITLE,
549                             resourcestr, 255);
550                 MessageBoxW(hDlg, resultstr, resourcestr,
551                             MB_OK | MB_ICONWARNING);
552                 return FALSE;
553             }
554             lppd->nFromPage = nFromPage;
555             lppd->nToPage   = nToPage;
556             lppd->Flags |= PD_PAGENUMS;
557         }
558         else
559             lppd->Flags &= ~PD_PAGENUMS;
560
561         if (IsDlgButtonChecked(hDlg, rad2) == BST_CHECKED) /* Selection */
562             lppd->Flags |= PD_SELECTION;
563         else
564             lppd->Flags &= ~PD_SELECTION;
565
566         if (IsDlgButtonChecked(hDlg, chx1) == BST_CHECKED) {/* Print to file */
567             static WCHAR file[] = {'F','I','L','E',':',0};
568             lppd->Flags |= PD_PRINTTOFILE;
569             pi->pPortName = file;
570         }
571
572         if (IsDlgButtonChecked(hDlg, chx2) == BST_CHECKED) { /* Collate */
573             FIXME("Collate lppd not yet implemented as output\n");
574         }
575
576         /* set PD_Collate and nCopies */
577         if (lppd->Flags & PD_USEDEVMODECOPIESANDCOLLATE) {
578           /*  The application doesn't support multiple copies or collate...
579            */
580             lppd->Flags &= ~PD_COLLATE;
581             lppd->nCopies = 1;
582           /* if the printer driver supports it... store info there
583            * otherwise no collate & multiple copies !
584            */
585             if (lpdm->dmFields & DM_COLLATE)
586                 lpdm->dmCollate =
587                   (IsDlgButtonChecked(hDlg, chx2) == BST_CHECKED);
588             if (lpdm->dmFields & DM_COPIES)
589                 lpdm->u1.s1.dmCopies = GetDlgItemInt(hDlg, edt3, NULL, FALSE);
590         } else {
591             if (IsDlgButtonChecked(hDlg, chx2) == BST_CHECKED)
592                 lppd->Flags |= PD_COLLATE;
593             else
594                lppd->Flags &= ~PD_COLLATE;
595             lppd->nCopies = GetDlgItemInt(hDlg, edt3, NULL, FALSE);
596         }
597     }
598     return TRUE;
599 }
600
601 /************************************************************************
602  * PRINTDLG_SetUpPaperComboBox
603  *
604  * Initialize either the papersize or inputslot combos of the Printer Setup
605  * dialog.  We store the associated word (eg DMPAPER_A4) as the item data.
606  * We also try to re-select the old selection.
607  */
608 static BOOL PRINTDLG_SetUpPaperComboBoxA(HWND hDlg,
609                                         int   nIDComboBox,
610                                         char* PrinterName,
611                                         char* PortName,
612                                         LPDEVMODEA dm)
613 {
614     int     i;
615     int     NrOfEntries;
616     char*   Names;
617     WORD*   Words;
618     DWORD   Sel;
619     WORD    oldWord = 0;
620     int     NamesSize;
621     int     fwCapability_Names;
622     int     fwCapability_Words;
623
624     TRACE(" Printer: %s, Port: %s, ComboID: %d\n",PrinterName,PortName,nIDComboBox);
625
626     /* query the dialog box for the current selected value */
627     Sel = SendDlgItemMessageA(hDlg, nIDComboBox, CB_GETCURSEL, 0, 0);
628     if(Sel != CB_ERR) {
629         /* we enter here only if a different printer is selected after
630          * the Print Setup dialog is opened. The current settings are
631          * stored into the newly selected printer.
632          */
633         oldWord = SendDlgItemMessageA(hDlg, nIDComboBox, CB_GETITEMDATA,
634                                       Sel, 0);
635         if (dm) {
636             if (nIDComboBox == cmb2)
637                 dm->u1.s1.dmPaperSize = oldWord;
638             else
639                 dm->u1.s1.dmDefaultSource = oldWord;
640         }
641     }
642     else {
643         /* we enter here only when the Print setup dialog is initially
644          * opened. In this case the settings are restored from when
645          * the dialog was last closed.
646          */
647         if (dm) {
648             if (nIDComboBox == cmb2)
649                 oldWord = dm->u1.s1.dmPaperSize;
650             else
651                 oldWord = dm->u1.s1.dmDefaultSource;
652         }
653     }
654
655     if (nIDComboBox == cmb2) {
656          NamesSize          = 64;
657          fwCapability_Names = DC_PAPERNAMES;
658          fwCapability_Words = DC_PAPERS;
659     } else {
660          nIDComboBox        = cmb3;
661          NamesSize          = 24;
662          fwCapability_Names = DC_BINNAMES;
663          fwCapability_Words = DC_BINS;
664     }
665
666     NrOfEntries = DeviceCapabilitiesA(PrinterName, PortName,
667                                       fwCapability_Names, NULL, dm);
668     if (NrOfEntries == 0)
669          WARN("no Name Entries found!\n");
670     else if (NrOfEntries < 0)
671          return FALSE;
672
673     if(DeviceCapabilitiesA(PrinterName, PortName, fwCapability_Words, NULL, dm)
674        != NrOfEntries) {
675         ERR("Number of caps is different\n");
676         NrOfEntries = 0;
677     }
678
679     Names = HeapAlloc(GetProcessHeap(),0, NrOfEntries*sizeof(char)*NamesSize);
680     Words = HeapAlloc(GetProcessHeap(),0, NrOfEntries*sizeof(WORD));
681     NrOfEntries = DeviceCapabilitiesA(PrinterName, PortName,
682                                       fwCapability_Names, Names, dm);
683     NrOfEntries = DeviceCapabilitiesA(PrinterName, PortName,
684                                       fwCapability_Words, (LPSTR)Words, dm);
685
686     /* reset any current content in the combobox */
687     SendDlgItemMessageA(hDlg, nIDComboBox, CB_RESETCONTENT, 0, 0);
688
689     /* store new content */
690     for (i = 0; i < NrOfEntries; i++) {
691         DWORD pos = SendDlgItemMessageA(hDlg, nIDComboBox, CB_ADDSTRING, 0,
692                                         (LPARAM)(&Names[i*NamesSize]) );
693         SendDlgItemMessageA(hDlg, nIDComboBox, CB_SETITEMDATA, pos,
694                             Words[i]);
695     }
696
697     /* Look for old selection - can't do this is previous loop since
698        item order will change as more items are added */
699     Sel = 0;
700     for (i = 0; i < NrOfEntries; i++) {
701         if(SendDlgItemMessageA(hDlg, nIDComboBox, CB_GETITEMDATA, i, 0) ==
702            oldWord) {
703             Sel = i;
704             break;
705         }
706     }
707     SendDlgItemMessageA(hDlg, nIDComboBox, CB_SETCURSEL, Sel, 0);
708
709     HeapFree(GetProcessHeap(),0,Words);
710     HeapFree(GetProcessHeap(),0,Names);
711     return TRUE;
712 }
713
714 static BOOL PRINTDLG_SetUpPaperComboBoxW(HWND hDlg,
715                                         int   nIDComboBox,
716                                         const WCHAR* PrinterName,
717                                         const WCHAR* PortName,
718                                         LPDEVMODEW dm)
719 {
720     int     i;
721     int     NrOfEntries;
722     WCHAR*  Names;
723     WORD*   Words;
724     DWORD   Sel;
725     WORD    oldWord = 0;
726     int     NamesSize;
727     int     fwCapability_Names;
728     int     fwCapability_Words;
729
730     TRACE(" Printer: %s, Port: %s, ComboID: %d\n",debugstr_w(PrinterName),debugstr_w(PortName),nIDComboBox);
731
732     /* query the dialog box for the current selected value */
733     Sel = SendDlgItemMessageW(hDlg, nIDComboBox, CB_GETCURSEL, 0, 0);
734     if(Sel != CB_ERR) {
735         /* we enter here only if a different printer is selected after
736          * the Print Setup dialog is opened. The current settings are
737          * stored into the newly selected printer.
738          */
739         oldWord = SendDlgItemMessageW(hDlg, nIDComboBox, CB_GETITEMDATA,
740                                       Sel, 0);
741         if (dm) {
742             if (nIDComboBox == cmb2)
743                 dm->u1.s1.dmPaperSize = oldWord;
744             else
745                 dm->u1.s1.dmDefaultSource = oldWord;
746         }
747     }
748     else {
749         /* we enter here only when the Print setup dialog is initially
750          * opened. In this case the settings are restored from when
751          * the dialog was last closed.
752          */
753         if (dm) {
754             if (nIDComboBox == cmb2)
755                 oldWord = dm->u1.s1.dmPaperSize;
756             else
757                 oldWord = dm->u1.s1.dmDefaultSource;
758         }
759     }
760
761     if (nIDComboBox == cmb2) {
762          NamesSize          = 64;
763          fwCapability_Names = DC_PAPERNAMES;
764          fwCapability_Words = DC_PAPERS;
765     } else {
766          nIDComboBox        = cmb3;
767          NamesSize          = 24;
768          fwCapability_Names = DC_BINNAMES;
769          fwCapability_Words = DC_BINS;
770     }
771
772     NrOfEntries = DeviceCapabilitiesW(PrinterName, PortName,
773                                       fwCapability_Names, NULL, dm);
774     if (NrOfEntries == 0)
775          WARN("no Name Entries found!\n");
776     else if (NrOfEntries < 0)
777          return FALSE;
778
779     if(DeviceCapabilitiesW(PrinterName, PortName, fwCapability_Words, NULL, dm)
780        != NrOfEntries) {
781         ERR("Number of caps is different\n");
782         NrOfEntries = 0;
783     }
784
785     Names = HeapAlloc(GetProcessHeap(),0, NrOfEntries*sizeof(WCHAR)*NamesSize);
786     Words = HeapAlloc(GetProcessHeap(),0, NrOfEntries*sizeof(WORD));
787     NrOfEntries = DeviceCapabilitiesW(PrinterName, PortName,
788                                       fwCapability_Names, Names, dm);
789     NrOfEntries = DeviceCapabilitiesW(PrinterName, PortName,
790                                       fwCapability_Words, Words, dm);
791
792     /* reset any current content in the combobox */
793     SendDlgItemMessageW(hDlg, nIDComboBox, CB_RESETCONTENT, 0, 0);
794
795     /* store new content */
796     for (i = 0; i < NrOfEntries; i++) {
797         DWORD pos = SendDlgItemMessageW(hDlg, nIDComboBox, CB_ADDSTRING, 0,
798                                         (LPARAM)(&Names[i*NamesSize]) );
799         SendDlgItemMessageW(hDlg, nIDComboBox, CB_SETITEMDATA, pos,
800                             Words[i]);
801     }
802
803     /* Look for old selection - can't do this is previous loop since
804        item order will change as more items are added */
805     Sel = 0;
806     for (i = 0; i < NrOfEntries; i++) {
807         if(SendDlgItemMessageW(hDlg, nIDComboBox, CB_GETITEMDATA, i, 0) ==
808            oldWord) {
809             Sel = i;
810             break;
811         }
812     }
813     SendDlgItemMessageW(hDlg, nIDComboBox, CB_SETCURSEL, Sel, 0);
814
815     HeapFree(GetProcessHeap(),0,Words);
816     HeapFree(GetProcessHeap(),0,Names);
817     return TRUE;
818 }
819
820
821 /***********************************************************************
822  *               PRINTDLG_UpdatePrinterInfoTexts               [internal]
823  */
824 static void PRINTDLG_UpdatePrinterInfoTextsA(HWND hDlg, const PRINTER_INFO_2A *pi)
825 {
826     char   StatusMsg[256];
827     char   ResourceString[256];
828     int    i;
829
830     /* Status Message */
831     StatusMsg[0]='\0';
832
833     /* add all status messages */
834     for (i = 0; i < 25; i++) {
835         if (pi->Status & (1<<i)) {
836             LoadStringA(COMDLG32_hInstance, PD32_PRINTER_STATUS_PAUSED+i,
837                         ResourceString, 255);
838             strcat(StatusMsg,ResourceString);
839         }
840     }
841     /* append "ready" */
842     /* FIXME: status==ready must only be appended if really so.
843               but how to detect? */
844     LoadStringA(COMDLG32_hInstance, PD32_PRINTER_STATUS_READY,
845                 ResourceString, 255);
846     strcat(StatusMsg,ResourceString);
847     SetDlgItemTextA(hDlg, stc12, StatusMsg);
848
849     /* set all other printer info texts */
850     SetDlgItemTextA(hDlg, stc11, pi->pDriverName);
851     
852     if (pi->pLocation != NULL && pi->pLocation[0] != '\0')
853         SetDlgItemTextA(hDlg, stc14, pi->pLocation);
854     else
855         SetDlgItemTextA(hDlg, stc14, pi->pPortName);
856     SetDlgItemTextA(hDlg, stc13, pi->pComment ? pi->pComment : "");
857     return;
858 }
859
860 static void PRINTDLG_UpdatePrinterInfoTextsW(HWND hDlg, const PRINTER_INFO_2W *pi)
861 {
862     WCHAR   StatusMsg[256];
863     WCHAR   ResourceString[256];
864     static const WCHAR emptyW[] = {0};
865     int    i;
866
867     /* Status Message */
868     StatusMsg[0]='\0';
869
870     /* add all status messages */
871     for (i = 0; i < 25; i++) {
872         if (pi->Status & (1<<i)) {
873             LoadStringW(COMDLG32_hInstance, PD32_PRINTER_STATUS_PAUSED+i,
874                         ResourceString, 255);
875             lstrcatW(StatusMsg,ResourceString);
876         }
877     }
878     /* append "ready" */
879     /* FIXME: status==ready must only be appended if really so.
880               but how to detect? */
881     LoadStringW(COMDLG32_hInstance, PD32_PRINTER_STATUS_READY,
882                 ResourceString, 255);
883     lstrcatW(StatusMsg,ResourceString);
884     SetDlgItemTextW(hDlg, stc12, StatusMsg);
885
886     /* set all other printer info texts */
887     SetDlgItemTextW(hDlg, stc11, pi->pDriverName);
888     if (pi->pLocation != NULL && pi->pLocation[0] != '\0')
889         SetDlgItemTextW(hDlg, stc14, pi->pLocation);
890     else
891         SetDlgItemTextW(hDlg, stc14, pi->pPortName);
892     SetDlgItemTextW(hDlg, stc13, pi->pComment ? pi->pComment : emptyW);
893 }
894
895
896 /*******************************************************************
897  *
898  *                 PRINTDLG_ChangePrinter
899  *
900  */
901 static BOOL PRINTDLG_ChangePrinterA(HWND hDlg, char *name, PRINT_PTRA *PrintStructures)
902 {
903     LPPRINTDLGA lppd = PrintStructures->lpPrintDlg;
904     LPDEVMODEA lpdm = NULL;
905     LONG dmSize;
906     DWORD needed;
907     HANDLE hprn;
908
909     HeapFree(GetProcessHeap(),0, PrintStructures->lpPrinterInfo);
910     HeapFree(GetProcessHeap(),0, PrintStructures->lpDriverInfo);
911     if(!OpenPrinterA(name, &hprn, NULL)) {
912         ERR("Can't open printer %s\n", name);
913         return FALSE;
914     }
915     GetPrinterA(hprn, 2, NULL, 0, &needed);
916     PrintStructures->lpPrinterInfo = HeapAlloc(GetProcessHeap(),0,needed);
917     GetPrinterA(hprn, 2, (LPBYTE)PrintStructures->lpPrinterInfo, needed,
918                 &needed);
919     GetPrinterDriverA(hprn, NULL, 3, NULL, 0, &needed);
920     PrintStructures->lpDriverInfo = HeapAlloc(GetProcessHeap(),0,needed);
921     if (!GetPrinterDriverA(hprn, NULL, 3, (LPBYTE)PrintStructures->lpDriverInfo,
922             needed, &needed)) {
923         ERR("GetPrinterDriverA failed for %s, fix your config!\n",PrintStructures->lpPrinterInfo->pPrinterName);
924         return FALSE;
925     }
926     ClosePrinter(hprn);
927
928     PRINTDLG_UpdatePrinterInfoTextsA(hDlg, PrintStructures->lpPrinterInfo);
929
930     HeapFree(GetProcessHeap(), 0, PrintStructures->lpDevMode);
931     PrintStructures->lpDevMode = NULL;
932
933     dmSize = DocumentPropertiesA(0, 0, name, NULL, NULL, 0);
934     if(dmSize == -1) {
935         ERR("DocumentProperties fails on %s\n", debugstr_a(name));
936         return FALSE;
937     }
938     PrintStructures->lpDevMode = HeapAlloc(GetProcessHeap(), 0, dmSize);
939     dmSize = DocumentPropertiesA(0, 0, name, PrintStructures->lpDevMode, NULL,
940                                  DM_OUT_BUFFER);
941     if(lppd->hDevMode && (lpdm = GlobalLock(lppd->hDevMode)) &&
942                           !lstrcmpA( (LPSTR) lpdm->dmDeviceName,
943                                      (LPSTR) PrintStructures->lpDevMode->dmDeviceName)) {
944       /* Supplied devicemode matches current printer so try to use it */
945         DocumentPropertiesA(0, 0, name, PrintStructures->lpDevMode, lpdm,
946                             DM_OUT_BUFFER | DM_IN_BUFFER);
947     }
948     if(lpdm)
949         GlobalUnlock(lppd->hDevMode);
950
951     lpdm = PrintStructures->lpDevMode;  /* use this as a shortcut */
952
953     if(!(lppd->Flags & PD_PRINTSETUP)) {
954         /* Print range (All/Range/Selection) */
955         if(lppd->nFromPage != 0xffff)
956             SetDlgItemInt(hDlg, edt1, lppd->nFromPage, FALSE);
957         if(lppd->nToPage != 0xffff)
958             SetDlgItemInt(hDlg, edt2, lppd->nToPage, FALSE);
959
960         CheckRadioButton(hDlg, rad1, rad3, rad1);               /* default */
961         if (lppd->Flags & PD_NOSELECTION)
962             EnableWindow(GetDlgItem(hDlg, rad2), FALSE);
963         else
964             if (lppd->Flags & PD_SELECTION)
965                 CheckRadioButton(hDlg, rad1, rad3, rad2);
966         if (lppd->Flags & PD_NOPAGENUMS) {
967             EnableWindow(GetDlgItem(hDlg, rad3), FALSE);
968             EnableWindow(GetDlgItem(hDlg, stc2),FALSE);
969             EnableWindow(GetDlgItem(hDlg, edt1), FALSE);
970             EnableWindow(GetDlgItem(hDlg, stc3),FALSE);
971             EnableWindow(GetDlgItem(hDlg, edt2), FALSE);
972         } else {
973             if (lppd->Flags & PD_PAGENUMS)
974                 CheckRadioButton(hDlg, rad1, rad3, rad3);
975         }
976
977         /* Collate pages
978          *
979          * FIXME: The ico3 is not displayed for some reason. I don't know why.
980          */
981         if (lppd->Flags & PD_COLLATE) {
982             SendDlgItemMessageA(hDlg, ico3, STM_SETIMAGE, (WPARAM) IMAGE_ICON,
983                                 (LPARAM)PrintStructures->hCollateIcon);
984             CheckDlgButton(hDlg, chx2, 1);
985         } else {
986             SendDlgItemMessageA(hDlg, ico3, STM_SETIMAGE, (WPARAM) IMAGE_ICON,
987                                 (LPARAM)PrintStructures->hNoCollateIcon);
988             CheckDlgButton(hDlg, chx2, 0);
989         }
990
991         if (lppd->Flags & PD_USEDEVMODECOPIESANDCOLLATE) {
992           /* if printer doesn't support it: no Collate */
993             if (!(lpdm->dmFields & DM_COLLATE)) {
994                 EnableWindow(GetDlgItem(hDlg, chx2), FALSE);
995                 EnableWindow(GetDlgItem(hDlg, ico3), FALSE);
996             }
997         }
998
999         /* nCopies */
1000         {
1001           INT copies;
1002           if (lppd->hDevMode == 0)
1003               copies = lppd->nCopies;
1004           else
1005               copies = lpdm->u1.s1.dmCopies;
1006           if(copies == 0) copies = 1;
1007           else if(copies < 0) copies = MAX_COPIES;
1008           SetDlgItemInt(hDlg, edt3, copies, FALSE);
1009         }
1010
1011         if (lppd->Flags & PD_USEDEVMODECOPIESANDCOLLATE) {
1012           /* if printer doesn't support it: no nCopies */
1013             if (!(lpdm->dmFields & DM_COPIES)) {
1014                 EnableWindow(GetDlgItem(hDlg, edt3), FALSE);
1015                 EnableWindow(GetDlgItem(hDlg, stc5), FALSE);
1016             }
1017         }
1018
1019         /* print to file */
1020         CheckDlgButton(hDlg, chx1, (lppd->Flags & PD_PRINTTOFILE) ? 1 : 0);
1021         if (lppd->Flags & PD_DISABLEPRINTTOFILE)
1022             EnableWindow(GetDlgItem(hDlg, chx1), FALSE);
1023         if (lppd->Flags & PD_HIDEPRINTTOFILE)
1024             ShowWindow(GetDlgItem(hDlg, chx1), SW_HIDE);
1025
1026         /* Fill print quality combo, PrintDlg16 */
1027         if(GetDlgItem(hDlg, cmb1))
1028         {
1029             DWORD numResolutions = DeviceCapabilitiesA(PrintStructures->lpPrinterInfo->pPrinterName,
1030                                                        PrintStructures->lpPrinterInfo->pPortName,
1031                                                        DC_ENUMRESOLUTIONS, NULL, lpdm);
1032
1033             if(numResolutions != -1)
1034             {
1035                 HWND hQuality = GetDlgItem(hDlg, cmb1);
1036                 LONG* Resolutions;
1037                 char buf[255];
1038                 DWORD i;
1039                 int dpiX, dpiY;
1040                 HDC hPrinterDC = CreateDCA(PrintStructures->lpPrinterInfo->pDriverName,
1041                                            PrintStructures->lpPrinterInfo->pPrinterName,
1042                                            0, lpdm);
1043
1044                 Resolutions = HeapAlloc(GetProcessHeap(), 0, numResolutions*sizeof(LONG)*2);
1045                 DeviceCapabilitiesA(PrintStructures->lpPrinterInfo->pPrinterName,
1046                                     PrintStructures->lpPrinterInfo->pPortName,
1047                                     DC_ENUMRESOLUTIONS, (LPSTR)Resolutions, lpdm);
1048
1049                 dpiX = GetDeviceCaps(hPrinterDC, LOGPIXELSX);
1050                 dpiY = GetDeviceCaps(hPrinterDC, LOGPIXELSY);
1051                 DeleteDC(hPrinterDC);
1052
1053                 SendMessageA(hQuality, CB_RESETCONTENT, 0, 0);
1054                 for(i = 0; i < (numResolutions * 2); i += 2)
1055                 {
1056                     BOOL IsDefault = FALSE;
1057                     LRESULT Index;
1058
1059                     if(Resolutions[i] == Resolutions[i+1])
1060                     {
1061                         if(dpiX == Resolutions[i])
1062                             IsDefault = TRUE;
1063                         sprintf(buf, "%d dpi", Resolutions[i]);
1064                     } else
1065                     {
1066                         if(dpiX == Resolutions[i] && dpiY == Resolutions[i+1])
1067                             IsDefault = TRUE;
1068                         sprintf(buf, "%d dpi x %d dpi", Resolutions[i], Resolutions[i+1]);
1069                     }
1070
1071                     Index = SendMessageA(hQuality, CB_ADDSTRING, 0, (LPARAM)buf);
1072
1073                     if(IsDefault)
1074                         SendMessageA(hQuality, CB_SETCURSEL, Index, 0);
1075
1076                     SendMessageA(hQuality, CB_SETITEMDATA, Index, MAKELONG(dpiX,dpiY));
1077                 }
1078                 HeapFree(GetProcessHeap(), 0, Resolutions);
1079             }
1080         }
1081     } else { /* PD_PRINTSETUP */
1082       BOOL bPortrait = (lpdm->u1.s1.dmOrientation == DMORIENT_PORTRAIT);
1083
1084       PRINTDLG_SetUpPaperComboBoxA(hDlg, cmb2,
1085                                   PrintStructures->lpPrinterInfo->pPrinterName,
1086                                   PrintStructures->lpPrinterInfo->pPortName,
1087                                   lpdm);
1088       PRINTDLG_SetUpPaperComboBoxA(hDlg, cmb3,
1089                                   PrintStructures->lpPrinterInfo->pPrinterName,
1090                                   PrintStructures->lpPrinterInfo->pPortName,
1091                                   lpdm);
1092       CheckRadioButton(hDlg, rad1, rad2, bPortrait ? rad1: rad2);
1093       SendDlgItemMessageA(hDlg, ico1, STM_SETIMAGE, (WPARAM) IMAGE_ICON,
1094                           (LPARAM)(bPortrait ? PrintStructures->hPortraitIcon :
1095                                    PrintStructures->hLandscapeIcon));
1096
1097     }
1098
1099     /* help button */
1100     if ((lppd->Flags & PD_SHOWHELP)==0) {
1101         /* hide if PD_SHOWHELP not specified */
1102         ShowWindow(GetDlgItem(hDlg, pshHelp), SW_HIDE);
1103     }
1104     return TRUE;
1105 }
1106
1107 static BOOL PRINTDLG_ChangePrinterW(HWND hDlg, WCHAR *name,
1108                                    PRINT_PTRW *PrintStructures)
1109 {
1110     LPPRINTDLGW lppd = PrintStructures->lpPrintDlg;
1111     LPDEVMODEW lpdm = NULL;
1112     LONG dmSize;
1113     DWORD needed;
1114     HANDLE hprn;
1115
1116     HeapFree(GetProcessHeap(),0, PrintStructures->lpPrinterInfo);
1117     HeapFree(GetProcessHeap(),0, PrintStructures->lpDriverInfo);
1118     if(!OpenPrinterW(name, &hprn, NULL)) {
1119         ERR("Can't open printer %s\n", debugstr_w(name));
1120         return FALSE;
1121     }
1122     GetPrinterW(hprn, 2, NULL, 0, &needed);
1123     PrintStructures->lpPrinterInfo = HeapAlloc(GetProcessHeap(),0,needed);
1124     GetPrinterW(hprn, 2, (LPBYTE)PrintStructures->lpPrinterInfo, needed,
1125                 &needed);
1126     GetPrinterDriverW(hprn, NULL, 3, NULL, 0, &needed);
1127     PrintStructures->lpDriverInfo = HeapAlloc(GetProcessHeap(),0,needed);
1128     if (!GetPrinterDriverW(hprn, NULL, 3, (LPBYTE)PrintStructures->lpDriverInfo,
1129             needed, &needed)) {
1130         ERR("GetPrinterDriverA failed for %s, fix your config!\n",debugstr_w(PrintStructures->lpPrinterInfo->pPrinterName));
1131         return FALSE;
1132     }
1133     ClosePrinter(hprn);
1134
1135     PRINTDLG_UpdatePrinterInfoTextsW(hDlg, PrintStructures->lpPrinterInfo);
1136
1137     HeapFree(GetProcessHeap(), 0, PrintStructures->lpDevMode);
1138     PrintStructures->lpDevMode = NULL;
1139
1140     dmSize = DocumentPropertiesW(0, 0, name, NULL, NULL, 0);
1141     if(dmSize == -1) {
1142         ERR("DocumentProperties fails on %s\n", debugstr_w(name));
1143         return FALSE;
1144     }
1145     PrintStructures->lpDevMode = HeapAlloc(GetProcessHeap(), 0, dmSize);
1146     dmSize = DocumentPropertiesW(0, 0, name, PrintStructures->lpDevMode, NULL,
1147                                  DM_OUT_BUFFER);
1148     if(lppd->hDevMode && (lpdm = GlobalLock(lppd->hDevMode)) &&
1149                           !lstrcmpW(lpdm->dmDeviceName,
1150                                   PrintStructures->lpDevMode->dmDeviceName)) {
1151       /* Supplied devicemode matches current printer so try to use it */
1152         DocumentPropertiesW(0, 0, name, PrintStructures->lpDevMode, lpdm,
1153                             DM_OUT_BUFFER | DM_IN_BUFFER);
1154     }
1155     if(lpdm)
1156         GlobalUnlock(lppd->hDevMode);
1157
1158     lpdm = PrintStructures->lpDevMode;  /* use this as a shortcut */
1159
1160     if(!(lppd->Flags & PD_PRINTSETUP)) {
1161         /* Print range (All/Range/Selection) */
1162         if(lppd->nFromPage != 0xffff)
1163             SetDlgItemInt(hDlg, edt1, lppd->nFromPage, FALSE);
1164         if(lppd->nToPage != 0xffff)
1165             SetDlgItemInt(hDlg, edt2, lppd->nToPage, FALSE);
1166
1167         CheckRadioButton(hDlg, rad1, rad3, rad1);               /* default */
1168         if (lppd->Flags & PD_NOSELECTION)
1169             EnableWindow(GetDlgItem(hDlg, rad2), FALSE);
1170         else
1171             if (lppd->Flags & PD_SELECTION)
1172                 CheckRadioButton(hDlg, rad1, rad3, rad2);
1173         if (lppd->Flags & PD_NOPAGENUMS) {
1174             EnableWindow(GetDlgItem(hDlg, rad3), FALSE);
1175             EnableWindow(GetDlgItem(hDlg, stc2),FALSE);
1176             EnableWindow(GetDlgItem(hDlg, edt1), FALSE);
1177             EnableWindow(GetDlgItem(hDlg, stc3),FALSE);
1178             EnableWindow(GetDlgItem(hDlg, edt2), FALSE);
1179         } else {
1180             if (lppd->Flags & PD_PAGENUMS)
1181                 CheckRadioButton(hDlg, rad1, rad3, rad3);
1182         }
1183
1184         /* Collate pages
1185          *
1186          * FIXME: The ico3 is not displayed for some reason. I don't know why.
1187          */
1188         if (lppd->Flags & PD_COLLATE) {
1189             SendDlgItemMessageW(hDlg, ico3, STM_SETIMAGE, (WPARAM) IMAGE_ICON,
1190                                 (LPARAM)PrintStructures->hCollateIcon);
1191             CheckDlgButton(hDlg, chx2, 1);
1192         } else {
1193             SendDlgItemMessageW(hDlg, ico3, STM_SETIMAGE, (WPARAM) IMAGE_ICON,
1194                                 (LPARAM)PrintStructures->hNoCollateIcon);
1195             CheckDlgButton(hDlg, chx2, 0);
1196         }
1197
1198         if (lppd->Flags & PD_USEDEVMODECOPIESANDCOLLATE) {
1199           /* if printer doesn't support it: no Collate */
1200             if (!(lpdm->dmFields & DM_COLLATE)) {
1201                 EnableWindow(GetDlgItem(hDlg, chx2), FALSE);
1202                 EnableWindow(GetDlgItem(hDlg, ico3), FALSE);
1203             }
1204         }
1205
1206         /* nCopies */
1207         {
1208           INT copies;
1209           if (lppd->hDevMode == 0)
1210               copies = lppd->nCopies;
1211           else
1212               copies = lpdm->u1.s1.dmCopies;
1213           if(copies == 0) copies = 1;
1214           else if(copies < 0) copies = MAX_COPIES;
1215           SetDlgItemInt(hDlg, edt3, copies, FALSE);
1216         }
1217
1218         if (lppd->Flags & PD_USEDEVMODECOPIESANDCOLLATE) {
1219           /* if printer doesn't support it: no nCopies */
1220             if (!(lpdm->dmFields & DM_COPIES)) {
1221                 EnableWindow(GetDlgItem(hDlg, edt3), FALSE);
1222                 EnableWindow(GetDlgItem(hDlg, stc5), FALSE);
1223             }
1224         }
1225
1226         /* print to file */
1227         CheckDlgButton(hDlg, chx1, (lppd->Flags & PD_PRINTTOFILE) ? 1 : 0);
1228         if (lppd->Flags & PD_DISABLEPRINTTOFILE)
1229             EnableWindow(GetDlgItem(hDlg, chx1), FALSE);
1230         if (lppd->Flags & PD_HIDEPRINTTOFILE)
1231             ShowWindow(GetDlgItem(hDlg, chx1), SW_HIDE);
1232
1233     } else { /* PD_PRINTSETUP */
1234       BOOL bPortrait = (lpdm->u1.s1.dmOrientation == DMORIENT_PORTRAIT);
1235
1236       PRINTDLG_SetUpPaperComboBoxW(hDlg, cmb2,
1237                                   PrintStructures->lpPrinterInfo->pPrinterName,
1238                                   PrintStructures->lpPrinterInfo->pPortName,
1239                                   lpdm);
1240       PRINTDLG_SetUpPaperComboBoxW(hDlg, cmb3,
1241                                   PrintStructures->lpPrinterInfo->pPrinterName,
1242                                   PrintStructures->lpPrinterInfo->pPortName,
1243                                   lpdm);
1244       CheckRadioButton(hDlg, rad1, rad2, bPortrait ? rad1: rad2);
1245       SendDlgItemMessageW(hDlg, ico1, STM_SETIMAGE, (WPARAM) IMAGE_ICON,
1246                           (LPARAM)(bPortrait ? PrintStructures->hPortraitIcon :
1247                                    PrintStructures->hLandscapeIcon));
1248
1249     }
1250
1251     /* help button */
1252     if ((lppd->Flags & PD_SHOWHELP)==0) {
1253         /* hide if PD_SHOWHELP not specified */
1254         ShowWindow(GetDlgItem(hDlg, pshHelp), SW_HIDE);
1255     }
1256     return TRUE;
1257 }
1258
1259  /***********************************************************************
1260  *           check_printer_setup                        [internal]
1261  */
1262 static LRESULT check_printer_setup(HWND hDlg)
1263 {
1264     DWORD needed,num;
1265     WCHAR resourcestr[256],resultstr[256];
1266
1267     EnumPrintersW(PRINTER_ENUM_LOCAL, NULL, 2, NULL, 0, &needed, &num);
1268     if(needed == 0)
1269     {
1270           EnumPrintersW(PRINTER_ENUM_CONNECTIONS, NULL, 2, NULL, 0, &needed, &num);
1271     }
1272     if(needed > 0)
1273           return TRUE;
1274     else
1275     {
1276           LoadStringW(COMDLG32_hInstance, PD32_NO_DEVICES,resultstr, 255);
1277           LoadStringW(COMDLG32_hInstance, PD32_PRINT_TITLE,resourcestr, 255);
1278           MessageBoxW(hDlg, resultstr, resourcestr,MB_OK | MB_ICONWARNING);
1279           return FALSE;
1280     }
1281 }
1282
1283 /***********************************************************************
1284  *           PRINTDLG_WMInitDialog                      [internal]
1285  */
1286 static LRESULT PRINTDLG_WMInitDialog(HWND hDlg, WPARAM wParam,
1287                                      PRINT_PTRA* PrintStructures)
1288 {
1289     LPPRINTDLGA lppd = PrintStructures->lpPrintDlg;
1290     DEVNAMES *pdn;
1291     DEVMODEA *pdm;
1292     char *name = NULL;
1293     UINT comboID = (lppd->Flags & PD_PRINTSETUP) ? cmb1 : cmb4;
1294
1295     /* load Collate ICONs */
1296     /* We load these with LoadImage because they are not a standard
1297        size and we don't want them rescaled */
1298     PrintStructures->hCollateIcon =
1299       LoadImageA(COMDLG32_hInstance, "PD32_COLLATE", IMAGE_ICON, 0, 0, 0);
1300     PrintStructures->hNoCollateIcon =
1301       LoadImageA(COMDLG32_hInstance, "PD32_NOCOLLATE", IMAGE_ICON, 0, 0, 0);
1302
1303     /* These can be done with LoadIcon */
1304     PrintStructures->hPortraitIcon =
1305       LoadIconA(COMDLG32_hInstance, "PD32_PORTRAIT");
1306     PrintStructures->hLandscapeIcon =
1307       LoadIconA(COMDLG32_hInstance, "PD32_LANDSCAPE");
1308
1309     /* display the collate/no_collate icon */
1310     SendDlgItemMessageA(hDlg, ico3, STM_SETIMAGE, (WPARAM) IMAGE_ICON,
1311                         (LPARAM)PrintStructures->hNoCollateIcon);
1312
1313     if(PrintStructures->hCollateIcon == 0 ||
1314        PrintStructures->hNoCollateIcon == 0 ||
1315        PrintStructures->hPortraitIcon == 0 ||
1316        PrintStructures->hLandscapeIcon == 0) {
1317         ERR("no icon in resourcefile\n");
1318         COMDLG32_SetCommDlgExtendedError(CDERR_LOADRESFAILURE);
1319         EndDialog(hDlg, FALSE);
1320     }
1321
1322     /*
1323      * if lppd->Flags PD_SHOWHELP is specified, a HELPMESGSTRING message
1324      * must be registered and the Help button must be shown.
1325      */
1326     if (lppd->Flags & PD_SHOWHELP) {
1327         if((PrintStructures->HelpMessageID =
1328             RegisterWindowMessageA(HELPMSGSTRINGA)) == 0) {
1329             COMDLG32_SetCommDlgExtendedError(CDERR_REGISTERMSGFAIL);
1330             return FALSE;
1331         }
1332     } else
1333         PrintStructures->HelpMessageID = 0;
1334
1335     if(!(lppd->Flags &PD_PRINTSETUP)) {
1336         PrintStructures->hwndUpDown =
1337           CreateUpDownControl(WS_CHILD | WS_VISIBLE | WS_BORDER |
1338                               UDS_NOTHOUSANDS | UDS_ARROWKEYS |
1339                               UDS_ALIGNRIGHT | UDS_SETBUDDYINT, 0, 0, 0, 0,
1340                               hDlg, UPDOWN_ID, COMDLG32_hInstance,
1341                               GetDlgItem(hDlg, edt3), MAX_COPIES, 1, 1);
1342     }
1343
1344     /* FIXME: I allow more freedom than either Win95 or WinNT,
1345      *        which do not agree to what errors should be thrown or not
1346      *        in case nToPage or nFromPage is out-of-range.
1347      */
1348     if (lppd->nMaxPage < lppd->nMinPage)
1349         lppd->nMaxPage = lppd->nMinPage;
1350     if (lppd->nMinPage == lppd->nMaxPage)
1351         lppd->Flags |= PD_NOPAGENUMS;
1352     if (lppd->nToPage < lppd->nMinPage)
1353         lppd->nToPage = lppd->nMinPage;
1354     if (lppd->nToPage > lppd->nMaxPage)
1355         lppd->nToPage = lppd->nMaxPage;
1356     if (lppd->nFromPage < lppd->nMinPage)
1357         lppd->nFromPage = lppd->nMinPage;
1358     if (lppd->nFromPage > lppd->nMaxPage)
1359         lppd->nFromPage = lppd->nMaxPage;
1360
1361     /* if we have the combo box, fill it */
1362     if (GetDlgItem(hDlg,comboID)) {
1363         /* Fill Combobox
1364          */
1365         pdn = GlobalLock(lppd->hDevNames);
1366         pdm = GlobalLock(lppd->hDevMode);
1367         if(pdn)
1368             name = (char*)pdn + pdn->wDeviceOffset;
1369         else if(pdm)
1370             name = (char*)pdm->dmDeviceName;
1371         PRINTDLG_SetUpPrinterListComboA(hDlg, comboID, name);
1372         if(pdm) GlobalUnlock(lppd->hDevMode);
1373         if(pdn) GlobalUnlock(lppd->hDevNames);
1374
1375         /* Now find selected printer and update rest of dlg */
1376         name = HeapAlloc(GetProcessHeap(),0,256);
1377         if (GetDlgItemTextA(hDlg, comboID, name, 255))
1378             PRINTDLG_ChangePrinterA(hDlg, name, PrintStructures);
1379         HeapFree(GetProcessHeap(),0,name);
1380     } else {
1381         /* else use default printer */
1382         char name[200];
1383         DWORD dwBufLen = sizeof(name);
1384         BOOL ret = GetDefaultPrinterA(name, &dwBufLen);
1385
1386         if (ret)
1387             PRINTDLG_ChangePrinterA(hDlg, name, PrintStructures);
1388         else
1389             FIXME("No default printer found, expect problems!\n");
1390     }
1391     return TRUE;
1392 }
1393
1394 static LRESULT PRINTDLG_WMInitDialogW(HWND hDlg, WPARAM wParam,
1395                                      PRINT_PTRW* PrintStructures)
1396 {
1397     LPPRINTDLGW lppd = PrintStructures->lpPrintDlg;
1398     DEVNAMES *pdn;
1399     DEVMODEW *pdm;
1400     WCHAR *name = NULL;
1401     UINT comboID = (lppd->Flags & PD_PRINTSETUP) ? cmb1 : cmb4;
1402
1403     /* load Collate ICONs */
1404     /* We load these with LoadImage because they are not a standard
1405        size and we don't want them rescaled */
1406     PrintStructures->hCollateIcon =
1407       LoadImageW(COMDLG32_hInstance, pd32_collateW, IMAGE_ICON, 0, 0, 0);
1408     PrintStructures->hNoCollateIcon =
1409       LoadImageW(COMDLG32_hInstance, pd32_nocollateW, IMAGE_ICON, 0, 0, 0);
1410
1411     /* These can be done with LoadIcon */
1412     PrintStructures->hPortraitIcon =
1413       LoadIconW(COMDLG32_hInstance, pd32_portraitW);
1414     PrintStructures->hLandscapeIcon =
1415       LoadIconW(COMDLG32_hInstance, pd32_landscapeW);
1416
1417     /* display the collate/no_collate icon */
1418     SendDlgItemMessageW(hDlg, ico3, STM_SETIMAGE, (WPARAM) IMAGE_ICON,
1419                         (LPARAM)PrintStructures->hNoCollateIcon);
1420
1421     if(PrintStructures->hCollateIcon == 0 ||
1422        PrintStructures->hNoCollateIcon == 0 ||
1423        PrintStructures->hPortraitIcon == 0 ||
1424        PrintStructures->hLandscapeIcon == 0) {
1425         ERR("no icon in resourcefile\n");
1426         COMDLG32_SetCommDlgExtendedError(CDERR_LOADRESFAILURE);
1427         EndDialog(hDlg, FALSE);
1428     }
1429
1430     /*
1431      * if lppd->Flags PD_SHOWHELP is specified, a HELPMESGSTRING message
1432      * must be registered and the Help button must be shown.
1433      */
1434     if (lppd->Flags & PD_SHOWHELP) {
1435         if((PrintStructures->HelpMessageID =
1436             RegisterWindowMessageW(HELPMSGSTRINGW)) == 0) {
1437             COMDLG32_SetCommDlgExtendedError(CDERR_REGISTERMSGFAIL);
1438             return FALSE;
1439         }
1440     } else
1441         PrintStructures->HelpMessageID = 0;
1442
1443     if(!(lppd->Flags &PD_PRINTSETUP)) {
1444         PrintStructures->hwndUpDown =
1445           CreateUpDownControl(WS_CHILD | WS_VISIBLE | WS_BORDER |
1446                               UDS_NOTHOUSANDS | UDS_ARROWKEYS |
1447                               UDS_ALIGNRIGHT | UDS_SETBUDDYINT, 0, 0, 0, 0,
1448                               hDlg, UPDOWN_ID, COMDLG32_hInstance,
1449                               GetDlgItem(hDlg, edt3), MAX_COPIES, 1, 1);
1450     }
1451
1452     /* FIXME: I allow more freedom than either Win95 or WinNT,
1453      *        which do not agree to what errors should be thrown or not
1454      *        in case nToPage or nFromPage is out-of-range.
1455      */
1456     if (lppd->nMaxPage < lppd->nMinPage)
1457         lppd->nMaxPage = lppd->nMinPage;
1458     if (lppd->nMinPage == lppd->nMaxPage)
1459         lppd->Flags |= PD_NOPAGENUMS;
1460     if (lppd->nToPage < lppd->nMinPage)
1461         lppd->nToPage = lppd->nMinPage;
1462     if (lppd->nToPage > lppd->nMaxPage)
1463         lppd->nToPage = lppd->nMaxPage;
1464     if (lppd->nFromPage < lppd->nMinPage)
1465         lppd->nFromPage = lppd->nMinPage;
1466     if (lppd->nFromPage > lppd->nMaxPage)
1467         lppd->nFromPage = lppd->nMaxPage;
1468
1469     /* if we have the combo box, fill it */
1470     if (GetDlgItem(hDlg,comboID)) {
1471         /* Fill Combobox
1472          */
1473         pdn = GlobalLock(lppd->hDevNames);
1474         pdm = GlobalLock(lppd->hDevMode);
1475         if(pdn)
1476             name = (WCHAR*)pdn + pdn->wDeviceOffset;
1477         else if(pdm)
1478             name = pdm->dmDeviceName;
1479         PRINTDLG_SetUpPrinterListComboW(hDlg, comboID, name);
1480         if(pdm) GlobalUnlock(lppd->hDevMode);
1481         if(pdn) GlobalUnlock(lppd->hDevNames);
1482
1483         /* Now find selected printer and update rest of dlg */
1484         /* ansi is ok here */
1485         name = HeapAlloc(GetProcessHeap(),0,256*sizeof(WCHAR));
1486         if (GetDlgItemTextW(hDlg, comboID, name, 255))
1487             PRINTDLG_ChangePrinterW(hDlg, name, PrintStructures);
1488         HeapFree(GetProcessHeap(),0,name);
1489     } else {
1490         /* else use default printer */
1491         WCHAR name[200];
1492         DWORD dwBufLen = sizeof(name) / sizeof(WCHAR);
1493         BOOL ret = GetDefaultPrinterW(name, &dwBufLen);
1494
1495         if (ret)
1496             PRINTDLG_ChangePrinterW(hDlg, name, PrintStructures);
1497         else
1498             FIXME("No default printer found, expect problems!\n");
1499     }
1500     return TRUE;
1501 }
1502
1503 /***********************************************************************
1504  *                              PRINTDLG_WMCommand               [internal]
1505  */
1506 static LRESULT PRINTDLG_WMCommandA(HWND hDlg, WPARAM wParam,
1507                                    LPARAM lParam, PRINT_PTRA* PrintStructures)
1508 {
1509     LPPRINTDLGA lppd = PrintStructures->lpPrintDlg;
1510     UINT PrinterComboID = (lppd->Flags & PD_PRINTSETUP) ? cmb1 : cmb4;
1511     LPDEVMODEA lpdm = PrintStructures->lpDevMode;
1512
1513     switch (LOWORD(wParam))  {
1514     case IDOK:
1515         TRACE(" OK button was hit\n");
1516         if (!PRINTDLG_UpdatePrintDlgA(hDlg, PrintStructures)) {
1517             FIXME("Update printdlg was not successful!\n");
1518             return(FALSE);
1519         }
1520         EndDialog(hDlg, TRUE);
1521         return(TRUE);
1522
1523     case IDCANCEL:
1524         TRACE(" CANCEL button was hit\n");
1525         EndDialog(hDlg, FALSE);
1526         return(FALSE);
1527
1528      case pshHelp:
1529         TRACE(" HELP button was hit\n");
1530         SendMessageA(lppd->hwndOwner, PrintStructures->HelpMessageID,
1531                                 (WPARAM) hDlg, (LPARAM) lppd);
1532         break;
1533
1534      case chx2:                         /* collate pages checkbox */
1535         if (IsDlgButtonChecked(hDlg, chx2) == BST_CHECKED)
1536             SendDlgItemMessageA(hDlg, ico3, STM_SETIMAGE, (WPARAM) IMAGE_ICON,
1537                                     (LPARAM)PrintStructures->hCollateIcon);
1538         else
1539             SendDlgItemMessageA(hDlg, ico3, STM_SETIMAGE, (WPARAM) IMAGE_ICON,
1540                                     (LPARAM)PrintStructures->hNoCollateIcon);
1541         break;
1542      case edt1:                         /* from page nr editbox */
1543      case edt2:                         /* to page nr editbox */
1544         if (HIWORD(wParam)==EN_CHANGE) {
1545             WORD nToPage;
1546             WORD nFromPage;
1547             nFromPage = GetDlgItemInt(hDlg, edt1, NULL, FALSE);
1548             nToPage   = GetDlgItemInt(hDlg, edt2, NULL, FALSE);
1549             if (nFromPage != lppd->nFromPage || nToPage != lppd->nToPage)
1550                 CheckRadioButton(hDlg, rad1, rad3, rad3);
1551         }
1552         break;
1553
1554     case edt3:
1555         if(HIWORD(wParam) == EN_CHANGE) {
1556             INT copies = GetDlgItemInt(hDlg, edt3, NULL, FALSE);
1557             if(copies <= 1)
1558                 EnableWindow(GetDlgItem(hDlg, chx2), FALSE);
1559             else
1560                 EnableWindow(GetDlgItem(hDlg, chx2), TRUE);
1561         }
1562         break;
1563
1564 #if 0
1565      case psh1:                       /* Print Setup */
1566         {
1567             PRINTDLG16  pdlg;
1568
1569             if (!PrintStructures->dlg.lpPrintDlg16) {
1570                 FIXME("The 32bit print dialog does not have this button!?\n");
1571                 break;
1572             }
1573
1574             memcpy(&pdlg,PrintStructures->dlg.lpPrintDlg16,sizeof(pdlg));
1575             pdlg.Flags |= PD_PRINTSETUP;
1576             pdlg.hwndOwner = HWND_16(hDlg);
1577             if (!PrintDlg16(&pdlg))
1578                 break;
1579         }
1580         break;
1581 #endif
1582      case psh2:                       /* Properties button */
1583        {
1584          HANDLE hPrinter;
1585          char   PrinterName[256];
1586
1587          GetDlgItemTextA(hDlg, PrinterComboID, PrinterName, 255);
1588          if (!OpenPrinterA(PrinterName, &hPrinter, NULL)) {
1589              FIXME(" Call to OpenPrinter did not succeed!\n");
1590              break;
1591          }
1592          DocumentPropertiesA(hDlg, hPrinter, PrinterName,
1593                              PrintStructures->lpDevMode,
1594                              PrintStructures->lpDevMode,
1595                              DM_IN_BUFFER | DM_OUT_BUFFER | DM_IN_PROMPT);
1596          ClosePrinter(hPrinter);
1597          break;
1598        }
1599
1600     case rad1: /* Paperorientation */
1601         if (lppd->Flags & PD_PRINTSETUP)
1602         {
1603               lpdm->u1.s1.dmOrientation = DMORIENT_PORTRAIT;
1604               SendDlgItemMessageA(hDlg, ico1, STM_SETIMAGE, (WPARAM) IMAGE_ICON,
1605                           (LPARAM)(PrintStructures->hPortraitIcon));
1606         }
1607         break;
1608
1609     case rad2: /* Paperorientation */
1610         if (lppd->Flags & PD_PRINTSETUP)
1611         {
1612               lpdm->u1.s1.dmOrientation = DMORIENT_LANDSCAPE;
1613               SendDlgItemMessageA(hDlg, ico1, STM_SETIMAGE, (WPARAM) IMAGE_ICON,
1614                           (LPARAM)(PrintStructures->hLandscapeIcon));
1615         }
1616         break;
1617
1618     case cmb1: /* Printer Combobox in PRINT SETUP, quality combobox in PRINT16 */
1619          if (PrinterComboID != LOWORD(wParam)) {
1620              break;
1621          }
1622          /* FALLTHROUGH */
1623     case cmb4:                         /* Printer combobox */
1624          if (HIWORD(wParam)==CBN_SELCHANGE) {
1625              char   PrinterName[256];
1626              GetDlgItemTextA(hDlg, LOWORD(wParam), PrinterName, 255);
1627              PRINTDLG_ChangePrinterA(hDlg, PrinterName, PrintStructures);
1628          }
1629          break;
1630
1631     case cmb2: /* Papersize */
1632       {
1633           DWORD Sel = SendDlgItemMessageA(hDlg, cmb2, CB_GETCURSEL, 0, 0);
1634           if(Sel != CB_ERR)
1635               lpdm->u1.s1.dmPaperSize = SendDlgItemMessageA(hDlg, cmb2,
1636                                                             CB_GETITEMDATA,
1637                                                             Sel, 0);
1638       }
1639       break;
1640
1641     case cmb3: /* Bin */
1642       {
1643           DWORD Sel = SendDlgItemMessageA(hDlg, cmb3, CB_GETCURSEL, 0, 0);
1644           if(Sel != CB_ERR)
1645               lpdm->u1.s1.dmDefaultSource = SendDlgItemMessageA(hDlg, cmb3,
1646                                                           CB_GETITEMDATA, Sel,
1647                                                           0);
1648       }
1649       break;
1650     }
1651     if(lppd->Flags & PD_PRINTSETUP) {
1652         switch (LOWORD(wParam)) {
1653         case rad1:                         /* orientation */
1654         case rad2:
1655             if (IsDlgButtonChecked(hDlg, rad1) == BST_CHECKED) {
1656                 if(lpdm->u1.s1.dmOrientation != DMORIENT_PORTRAIT) {
1657                     lpdm->u1.s1.dmOrientation = DMORIENT_PORTRAIT;
1658                     SendDlgItemMessageA(hDlg, stc10, STM_SETIMAGE,
1659                                         (WPARAM)IMAGE_ICON,
1660                                         (LPARAM)PrintStructures->hPortraitIcon);
1661                     SendDlgItemMessageA(hDlg, ico1, STM_SETIMAGE,
1662                                         (WPARAM)IMAGE_ICON,
1663                                         (LPARAM)PrintStructures->hPortraitIcon);
1664                 }
1665             } else {
1666                 if(lpdm->u1.s1.dmOrientation != DMORIENT_LANDSCAPE) {
1667                     lpdm->u1.s1.dmOrientation = DMORIENT_LANDSCAPE;
1668                     SendDlgItemMessageA(hDlg, stc10, STM_SETIMAGE,
1669                                         (WPARAM)IMAGE_ICON,
1670                                         (LPARAM)PrintStructures->hLandscapeIcon);
1671                     SendDlgItemMessageA(hDlg, ico1, STM_SETIMAGE,
1672                                         (WPARAM)IMAGE_ICON,
1673                                         (LPARAM)PrintStructures->hLandscapeIcon);
1674                 }
1675             }
1676             break;
1677         }
1678     }
1679     return FALSE;
1680 }
1681
1682 static LRESULT PRINTDLG_WMCommandW(HWND hDlg, WPARAM wParam,
1683                         LPARAM lParam, PRINT_PTRW* PrintStructures)
1684 {
1685     LPPRINTDLGW lppd = PrintStructures->lpPrintDlg;
1686     UINT PrinterComboID = (lppd->Flags & PD_PRINTSETUP) ? cmb1 : cmb4;
1687     LPDEVMODEW lpdm = PrintStructures->lpDevMode;
1688
1689     switch (LOWORD(wParam))  {
1690     case IDOK:
1691         TRACE(" OK button was hit\n");
1692         if (!PRINTDLG_UpdatePrintDlgW(hDlg, PrintStructures)) {
1693             FIXME("Update printdlg was not successful!\n");
1694             return(FALSE);
1695         }
1696         EndDialog(hDlg, TRUE);
1697         return(TRUE);
1698
1699     case IDCANCEL:
1700         TRACE(" CANCEL button was hit\n");
1701         EndDialog(hDlg, FALSE);
1702         return(FALSE);
1703
1704      case pshHelp:
1705         TRACE(" HELP button was hit\n");
1706         SendMessageW(lppd->hwndOwner, PrintStructures->HelpMessageID,
1707                                 (WPARAM) hDlg, (LPARAM) lppd);
1708         break;
1709
1710      case chx2:                         /* collate pages checkbox */
1711         if (IsDlgButtonChecked(hDlg, chx2) == BST_CHECKED)
1712             SendDlgItemMessageW(hDlg, ico3, STM_SETIMAGE, (WPARAM) IMAGE_ICON,
1713                                     (LPARAM)PrintStructures->hCollateIcon);
1714         else
1715             SendDlgItemMessageW(hDlg, ico3, STM_SETIMAGE, (WPARAM) IMAGE_ICON,
1716                                     (LPARAM)PrintStructures->hNoCollateIcon);
1717         break;
1718      case edt1:                         /* from page nr editbox */
1719      case edt2:                         /* to page nr editbox */
1720         if (HIWORD(wParam)==EN_CHANGE) {
1721             WORD nToPage;
1722             WORD nFromPage;
1723             nFromPage = GetDlgItemInt(hDlg, edt1, NULL, FALSE);
1724             nToPage   = GetDlgItemInt(hDlg, edt2, NULL, FALSE);
1725             if (nFromPage != lppd->nFromPage || nToPage != lppd->nToPage)
1726                 CheckRadioButton(hDlg, rad1, rad3, rad3);
1727         }
1728         break;
1729
1730     case edt3:
1731         if(HIWORD(wParam) == EN_CHANGE) {
1732             INT copies = GetDlgItemInt(hDlg, edt3, NULL, FALSE);
1733             if(copies <= 1)
1734                 EnableWindow(GetDlgItem(hDlg, chx2), FALSE);
1735             else
1736                 EnableWindow(GetDlgItem(hDlg, chx2), TRUE);
1737         }
1738         break;
1739
1740      case psh1:                       /* Print Setup */
1741         {
1742                 ERR("psh1 is called from 16bit code only, we should not get here.\n");
1743         }
1744         break;
1745      case psh2:                       /* Properties button */
1746        {
1747          HANDLE hPrinter;
1748          WCHAR  PrinterName[256];
1749
1750          if (!GetDlgItemTextW(hDlg, PrinterComboID, PrinterName, 255)) break;
1751          if (!OpenPrinterW(PrinterName, &hPrinter, NULL)) {
1752              FIXME(" Call to OpenPrinter did not succeed!\n");
1753              break;
1754          }
1755          DocumentPropertiesW(hDlg, hPrinter, PrinterName,
1756                              PrintStructures->lpDevMode,
1757                              PrintStructures->lpDevMode,
1758                              DM_IN_BUFFER | DM_OUT_BUFFER | DM_IN_PROMPT);
1759          ClosePrinter(hPrinter);
1760          break;
1761        }
1762
1763     case rad1: /* Paperorientation */
1764         if (lppd->Flags & PD_PRINTSETUP)
1765         {
1766               lpdm->u1.s1.dmOrientation = DMORIENT_PORTRAIT;
1767               SendDlgItemMessageW(hDlg, ico1, STM_SETIMAGE, (WPARAM) IMAGE_ICON,
1768                           (LPARAM)(PrintStructures->hPortraitIcon));
1769         }
1770         break;
1771
1772     case rad2: /* Paperorientation */
1773         if (lppd->Flags & PD_PRINTSETUP)
1774         {
1775               lpdm->u1.s1.dmOrientation = DMORIENT_LANDSCAPE;
1776               SendDlgItemMessageW(hDlg, ico1, STM_SETIMAGE, (WPARAM) IMAGE_ICON,
1777                           (LPARAM)(PrintStructures->hLandscapeIcon));
1778         }
1779         break;
1780
1781     case cmb1: /* Printer Combobox in PRINT SETUP */
1782          /* FALLTHROUGH */
1783     case cmb4:                         /* Printer combobox */
1784          if (HIWORD(wParam)==CBN_SELCHANGE) {
1785              WCHAR   PrinterName[256];
1786              GetDlgItemTextW(hDlg, LOWORD(wParam), PrinterName, 255);
1787              PRINTDLG_ChangePrinterW(hDlg, PrinterName, PrintStructures);
1788          }
1789          break;
1790
1791     case cmb2: /* Papersize */
1792       {
1793           DWORD Sel = SendDlgItemMessageW(hDlg, cmb2, CB_GETCURSEL, 0, 0);
1794           if(Sel != CB_ERR)
1795               lpdm->u1.s1.dmPaperSize = SendDlgItemMessageW(hDlg, cmb2,
1796                                                             CB_GETITEMDATA,
1797                                                             Sel, 0);
1798       }
1799       break;
1800
1801     case cmb3: /* Bin */
1802       {
1803           DWORD Sel = SendDlgItemMessageW(hDlg, cmb3, CB_GETCURSEL, 0, 0);
1804           if(Sel != CB_ERR)
1805               lpdm->u1.s1.dmDefaultSource = SendDlgItemMessageW(hDlg, cmb3,
1806                                                           CB_GETITEMDATA, Sel,
1807                                                           0);
1808       }
1809       break;
1810     }
1811     if(lppd->Flags & PD_PRINTSETUP) {
1812         switch (LOWORD(wParam)) {
1813         case rad1:                         /* orientation */
1814         case rad2:
1815             if (IsDlgButtonChecked(hDlg, rad1) == BST_CHECKED) {
1816                 if(lpdm->u1.s1.dmOrientation != DMORIENT_PORTRAIT) {
1817                     lpdm->u1.s1.dmOrientation = DMORIENT_PORTRAIT;
1818                     SendDlgItemMessageW(hDlg, stc10, STM_SETIMAGE,
1819                                         (WPARAM)IMAGE_ICON,
1820                                         (LPARAM)PrintStructures->hPortraitIcon);
1821                     SendDlgItemMessageW(hDlg, ico1, STM_SETIMAGE,
1822                                         (WPARAM)IMAGE_ICON,
1823                                         (LPARAM)PrintStructures->hPortraitIcon);
1824                 }
1825             } else {
1826                 if(lpdm->u1.s1.dmOrientation != DMORIENT_LANDSCAPE) {
1827                     lpdm->u1.s1.dmOrientation = DMORIENT_LANDSCAPE;
1828                     SendDlgItemMessageW(hDlg, stc10, STM_SETIMAGE,
1829                                         (WPARAM)IMAGE_ICON,
1830                                         (LPARAM)PrintStructures->hLandscapeIcon);
1831                     SendDlgItemMessageW(hDlg, ico1, STM_SETIMAGE,
1832                                         (WPARAM)IMAGE_ICON,
1833                                         (LPARAM)PrintStructures->hLandscapeIcon);
1834                 }
1835             }
1836             break;
1837         }
1838     }
1839     return FALSE;
1840 }
1841
1842 /***********************************************************************
1843  *           PrintDlgProcA                      [internal]
1844  */
1845 static INT_PTR CALLBACK PrintDlgProcA(HWND hDlg, UINT uMsg, WPARAM wParam,
1846                                       LPARAM lParam)
1847 {
1848     PRINT_PTRA* PrintStructures;
1849     INT_PTR res = FALSE;
1850
1851     if (uMsg!=WM_INITDIALOG) {
1852         PrintStructures = GetPropW(hDlg, printdlg_prop);
1853         if (!PrintStructures)
1854             return FALSE;
1855     } else {
1856         PrintStructures = (PRINT_PTRA*) lParam;
1857         SetPropW(hDlg, printdlg_prop, PrintStructures);
1858         if(!check_printer_setup(hDlg))
1859         {
1860             EndDialog(hDlg,FALSE);
1861             return FALSE;
1862         }
1863         res = PRINTDLG_WMInitDialog(hDlg, wParam, PrintStructures);
1864
1865         if(PrintStructures->lpPrintDlg->Flags & PD_ENABLEPRINTHOOK)
1866             res = PrintStructures->lpPrintDlg->lpfnPrintHook(
1867                 hDlg, uMsg, wParam, (LPARAM)PrintStructures->lpPrintDlg
1868             );
1869         return res;
1870     }
1871
1872     if(PrintStructures->lpPrintDlg->Flags & PD_ENABLEPRINTHOOK) {
1873         res = PrintStructures->lpPrintDlg->lpfnPrintHook(hDlg,uMsg,wParam,
1874                                                          lParam);
1875         if(res) return res;
1876     }
1877
1878     switch (uMsg) {
1879     case WM_COMMAND:
1880         return PRINTDLG_WMCommandA(hDlg, wParam, lParam, PrintStructures);
1881
1882     case WM_DESTROY:
1883         DestroyIcon(PrintStructures->hCollateIcon);
1884         DestroyIcon(PrintStructures->hNoCollateIcon);
1885         DestroyIcon(PrintStructures->hPortraitIcon);
1886         DestroyIcon(PrintStructures->hLandscapeIcon);
1887         if(PrintStructures->hwndUpDown)
1888             DestroyWindow(PrintStructures->hwndUpDown);
1889         return FALSE;
1890     }
1891     return res;
1892 }
1893
1894 static INT_PTR CALLBACK PrintDlgProcW(HWND hDlg, UINT uMsg, WPARAM wParam,
1895                                       LPARAM lParam)
1896 {
1897     PRINT_PTRW* PrintStructures;
1898     INT_PTR res = FALSE;
1899
1900     if (uMsg!=WM_INITDIALOG) {
1901         PrintStructures = GetPropW(hDlg, printdlg_prop);
1902         if (!PrintStructures)
1903             return FALSE;
1904     } else {
1905         PrintStructures = (PRINT_PTRW*) lParam;
1906         SetPropW(hDlg, printdlg_prop, PrintStructures);
1907         if(!check_printer_setup(hDlg))
1908         {
1909             EndDialog(hDlg,FALSE);
1910             return FALSE;
1911         }
1912         res = PRINTDLG_WMInitDialogW(hDlg, wParam, PrintStructures);
1913
1914         if(PrintStructures->lpPrintDlg->Flags & PD_ENABLEPRINTHOOK)
1915             res = PrintStructures->lpPrintDlg->lpfnPrintHook(hDlg, uMsg, wParam, (LPARAM)PrintStructures->lpPrintDlg);
1916         return res;
1917     }
1918
1919     if(PrintStructures->lpPrintDlg->Flags & PD_ENABLEPRINTHOOK) {
1920         res = PrintStructures->lpPrintDlg->lpfnPrintHook(hDlg,uMsg,wParam, lParam);
1921         if(res) return res;
1922     }
1923
1924     switch (uMsg) {
1925     case WM_COMMAND:
1926         return PRINTDLG_WMCommandW(hDlg, wParam, lParam, PrintStructures);
1927
1928     case WM_DESTROY:
1929         DestroyIcon(PrintStructures->hCollateIcon);
1930         DestroyIcon(PrintStructures->hNoCollateIcon);
1931         DestroyIcon(PrintStructures->hPortraitIcon);
1932         DestroyIcon(PrintStructures->hLandscapeIcon);
1933         if(PrintStructures->hwndUpDown)
1934             DestroyWindow(PrintStructures->hwndUpDown);
1935         return FALSE;
1936     }
1937     return res;
1938 }
1939
1940 /************************************************************
1941  *
1942  *      PRINTDLG_GetDlgTemplate
1943  *
1944  */
1945 static HGLOBAL PRINTDLG_GetDlgTemplateA(const PRINTDLGA *lppd)
1946 {
1947     HRSRC hResInfo;
1948     HGLOBAL hDlgTmpl;
1949
1950     if (lppd->Flags & PD_PRINTSETUP) {
1951         if(lppd->Flags & PD_ENABLESETUPTEMPLATEHANDLE) {
1952             hDlgTmpl = lppd->hSetupTemplate;
1953         } else if(lppd->Flags & PD_ENABLESETUPTEMPLATE) {
1954             hResInfo = FindResourceA(lppd->hInstance,
1955                                      lppd->lpSetupTemplateName, (LPSTR)RT_DIALOG);
1956             hDlgTmpl = LoadResource(lppd->hInstance, hResInfo);
1957         } else {
1958             hResInfo = FindResourceA(COMDLG32_hInstance, "PRINT32_SETUP",
1959                                      (LPSTR)RT_DIALOG);
1960             hDlgTmpl = LoadResource(COMDLG32_hInstance, hResInfo);
1961         }
1962     } else {
1963         if(lppd->Flags & PD_ENABLEPRINTTEMPLATEHANDLE) {
1964             hDlgTmpl = lppd->hPrintTemplate;
1965         } else if(lppd->Flags & PD_ENABLEPRINTTEMPLATE) {
1966             hResInfo = FindResourceA(lppd->hInstance,
1967                                      lppd->lpPrintTemplateName,
1968                                      (LPSTR)RT_DIALOG);
1969             hDlgTmpl = LoadResource(lppd->hInstance, hResInfo);
1970         } else {
1971             hResInfo = FindResourceA(COMDLG32_hInstance, "PRINT32",
1972                                      (LPSTR)RT_DIALOG);
1973             hDlgTmpl = LoadResource(COMDLG32_hInstance, hResInfo);
1974         }
1975     }
1976     return hDlgTmpl;
1977 }
1978
1979 static HGLOBAL PRINTDLG_GetDlgTemplateW(const PRINTDLGW *lppd)
1980 {
1981     HRSRC hResInfo;
1982     HGLOBAL hDlgTmpl;
1983     static const WCHAR xpsetup[] = { 'P','R','I','N','T','3','2','_','S','E','T','U','P',0};
1984     static const WCHAR xprint[] = { 'P','R','I','N','T','3','2',0};
1985
1986     if (lppd->Flags & PD_PRINTSETUP) {
1987         if(lppd->Flags & PD_ENABLESETUPTEMPLATEHANDLE) {
1988             hDlgTmpl = lppd->hSetupTemplate;
1989         } else if(lppd->Flags & PD_ENABLESETUPTEMPLATE) {
1990             hResInfo = FindResourceW(lppd->hInstance,
1991                                      lppd->lpSetupTemplateName, (LPWSTR)RT_DIALOG);
1992             hDlgTmpl = LoadResource(lppd->hInstance, hResInfo);
1993         } else {
1994             hResInfo = FindResourceW(COMDLG32_hInstance, xpsetup, (LPWSTR)RT_DIALOG);
1995             hDlgTmpl = LoadResource(COMDLG32_hInstance, hResInfo);
1996         }
1997     } else {
1998         if(lppd->Flags & PD_ENABLEPRINTTEMPLATEHANDLE) {
1999             hDlgTmpl = lppd->hPrintTemplate;
2000         } else if(lppd->Flags & PD_ENABLEPRINTTEMPLATE) {
2001             hResInfo = FindResourceW(lppd->hInstance,
2002                                      lppd->lpPrintTemplateName,
2003                                      (LPWSTR)RT_DIALOG);
2004             hDlgTmpl = LoadResource(lppd->hInstance, hResInfo);
2005         } else {
2006             hResInfo = FindResourceW(COMDLG32_hInstance, xprint, (LPWSTR)RT_DIALOG);
2007             hDlgTmpl = LoadResource(COMDLG32_hInstance, hResInfo);
2008         }
2009     }
2010     return hDlgTmpl;
2011 }
2012
2013 /***********************************************************************
2014  *
2015  *      PRINTDLG_CreateDC
2016  *
2017  */
2018 static BOOL PRINTDLG_CreateDCA(LPPRINTDLGA lppd)
2019 {
2020     DEVNAMES *pdn = GlobalLock(lppd->hDevNames);
2021     DEVMODEA *pdm = GlobalLock(lppd->hDevMode);
2022
2023     if(lppd->Flags & PD_RETURNDC) {
2024         lppd->hDC = CreateDCA((char*)pdn + pdn->wDriverOffset,
2025                               (char*)pdn + pdn->wDeviceOffset,
2026                               (char*)pdn + pdn->wOutputOffset,
2027                               pdm );
2028     } else if(lppd->Flags & PD_RETURNIC) {
2029         lppd->hDC = CreateICA((char*)pdn + pdn->wDriverOffset,
2030                               (char*)pdn + pdn->wDeviceOffset,
2031                               (char*)pdn + pdn->wOutputOffset,
2032                               pdm );
2033     }
2034     GlobalUnlock(lppd->hDevNames);
2035     GlobalUnlock(lppd->hDevMode);
2036     return lppd->hDC ? TRUE : FALSE;
2037 }
2038
2039 static BOOL PRINTDLG_CreateDCW(LPPRINTDLGW lppd)
2040 {
2041     DEVNAMES *pdn = GlobalLock(lppd->hDevNames);
2042     DEVMODEW *pdm = GlobalLock(lppd->hDevMode);
2043
2044     if(lppd->Flags & PD_RETURNDC) {
2045         lppd->hDC = CreateDCW((WCHAR*)pdn + pdn->wDriverOffset,
2046                               (WCHAR*)pdn + pdn->wDeviceOffset,
2047                               (WCHAR*)pdn + pdn->wOutputOffset,
2048                               pdm );
2049     } else if(lppd->Flags & PD_RETURNIC) {
2050         lppd->hDC = CreateICW((WCHAR*)pdn + pdn->wDriverOffset,
2051                               (WCHAR*)pdn + pdn->wDeviceOffset,
2052                               (WCHAR*)pdn + pdn->wOutputOffset,
2053                               pdm );
2054     }
2055     GlobalUnlock(lppd->hDevNames);
2056     GlobalUnlock(lppd->hDevMode);
2057     return lppd->hDC ? TRUE : FALSE;
2058 }
2059
2060 /***********************************************************************
2061  *           PrintDlgA   (COMDLG32.@)
2062  *
2063  *  Displays the PRINT dialog box, which enables the user to specify
2064  *  specific properties of the print job.
2065  *  
2066  * PARAMS
2067  *  lppd  [IO] ptr to PRINTDLG32 struct
2068  * 
2069  * RETURNS
2070  *  nonzero if the user pressed the OK button
2071  *  zero    if the user cancelled the window or an error occurred
2072  *  
2073  * BUGS
2074  *  PrintDlg:
2075  *  * The Collate Icons do not display, even though they are in the code.
2076  *  * The Properties Button(s) should call DocumentPropertiesA().
2077  */
2078
2079 BOOL WINAPI PrintDlgA(LPPRINTDLGA lppd)
2080 {
2081     BOOL      bRet = FALSE;
2082     LPVOID    ptr;
2083     HINSTANCE hInst;
2084
2085     if (!lppd)
2086     {
2087         COMDLG32_SetCommDlgExtendedError(CDERR_INITIALIZATION);
2088         return FALSE;
2089     }
2090
2091     hInst = (HINSTANCE)GetWindowLongPtrA( lppd->hwndOwner, GWLP_HINSTANCE );
2092     if(TRACE_ON(commdlg)) {
2093         char flagstr[1000] = "";
2094         const struct pd_flags *pflag = pd_flags;
2095         for( ; pflag->name; pflag++) {
2096             if(lppd->Flags & pflag->flag)
2097                 strcat(flagstr, pflag->name);
2098         }
2099         TRACE("(%p): hwndOwner = %p, hDevMode = %p, hDevNames = %p\n"
2100               "pp. %d-%d, min p %d, max p %d, copies %d, hinst %p\n"
2101               "flags %08x (%s)\n",
2102               lppd, lppd->hwndOwner, lppd->hDevMode, lppd->hDevNames,
2103               lppd->nFromPage, lppd->nToPage, lppd->nMinPage, lppd->nMaxPage,
2104               lppd->nCopies, lppd->hInstance, lppd->Flags, flagstr);
2105     }
2106
2107     if(lppd->lStructSize != sizeof(PRINTDLGA)) {
2108         WARN("structure size failure !!!\n");
2109         COMDLG32_SetCommDlgExtendedError(CDERR_STRUCTSIZE);
2110         return FALSE;
2111     }
2112
2113     if(lppd->Flags & PD_RETURNDEFAULT) {
2114         PRINTER_INFO_2A *pbuf;
2115         DRIVER_INFO_3A  *dbuf;
2116         HANDLE hprn;
2117         DWORD needed;
2118
2119         if(lppd->hDevMode || lppd->hDevNames) {
2120             WARN("hDevMode or hDevNames non-zero for PD_RETURNDEFAULT\n");
2121             COMDLG32_SetCommDlgExtendedError(PDERR_RETDEFFAILURE);
2122             return FALSE;
2123         }
2124         if(!PRINTDLG_OpenDefaultPrinter(&hprn)) {
2125             WARN("Can't find default printer\n");
2126             COMDLG32_SetCommDlgExtendedError(PDERR_NODEFAULTPRN);
2127             return FALSE;
2128         }
2129
2130         GetPrinterA(hprn, 2, NULL, 0, &needed);
2131         pbuf = HeapAlloc(GetProcessHeap(), 0, needed);
2132         GetPrinterA(hprn, 2, (LPBYTE)pbuf, needed, &needed);
2133
2134         GetPrinterDriverA(hprn, NULL, 3, NULL, 0, &needed);
2135         dbuf = HeapAlloc(GetProcessHeap(),0,needed);
2136         if (!GetPrinterDriverA(hprn, NULL, 3, (LPBYTE)dbuf, needed, &needed)) {
2137             ERR("GetPrinterDriverA failed, le %d, fix your config for printer %s!\n",
2138                 GetLastError(),pbuf->pPrinterName);
2139             HeapFree(GetProcessHeap(), 0, dbuf);
2140             HeapFree(GetProcessHeap(), 0, pbuf);
2141             COMDLG32_SetCommDlgExtendedError(PDERR_RETDEFFAILURE);
2142             return FALSE;
2143         }
2144         ClosePrinter(hprn);
2145
2146         PRINTDLG_CreateDevNames(&(lppd->hDevNames),
2147                                   dbuf->pDriverPath,
2148                                   pbuf->pPrinterName,
2149                                   pbuf->pPortName);
2150         lppd->hDevMode = GlobalAlloc(GMEM_MOVEABLE, pbuf->pDevMode->dmSize +
2151                                      pbuf->pDevMode->dmDriverExtra);
2152         ptr = GlobalLock(lppd->hDevMode);
2153         memcpy(ptr, pbuf->pDevMode, pbuf->pDevMode->dmSize +
2154                pbuf->pDevMode->dmDriverExtra);
2155         GlobalUnlock(lppd->hDevMode);
2156         HeapFree(GetProcessHeap(), 0, pbuf);
2157         HeapFree(GetProcessHeap(), 0, dbuf);
2158         bRet = TRUE;
2159     } else {
2160         HGLOBAL hDlgTmpl;
2161         PRINT_PTRA *PrintStructures;
2162
2163     /* load Dialog resources,
2164      * depending on Flags indicates Print32 or Print32_setup dialog
2165      */
2166         hDlgTmpl = PRINTDLG_GetDlgTemplateA(lppd);
2167         if (!hDlgTmpl) {
2168             COMDLG32_SetCommDlgExtendedError(CDERR_LOADRESFAILURE);
2169             return FALSE;
2170         }
2171         ptr = LockResource( hDlgTmpl );
2172         if (!ptr) {
2173             COMDLG32_SetCommDlgExtendedError(CDERR_LOADRESFAILURE);
2174             return FALSE;
2175         }
2176
2177         PrintStructures = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY,
2178                                     sizeof(PRINT_PTRA));
2179         PrintStructures->lpPrintDlg = lppd;
2180
2181         /* and create & process the dialog .
2182          * -1 is failure, 0 is broken hwnd, everything else is ok.
2183          */
2184         bRet = (0<DialogBoxIndirectParamA(hInst, ptr, lppd->hwndOwner,
2185                                            PrintDlgProcA,
2186                                            (LPARAM)PrintStructures));
2187
2188         if(bRet) {
2189             DEVMODEA *lpdm = PrintStructures->lpDevMode, *lpdmReturn;
2190             PRINTER_INFO_2A *pi = PrintStructures->lpPrinterInfo;
2191             DRIVER_INFO_3A *di = PrintStructures->lpDriverInfo;
2192
2193             if (lppd->hDevMode == 0) {
2194                 TRACE(" No hDevMode yet... Need to create my own\n");
2195                 lppd->hDevMode = GlobalAlloc(GMEM_MOVEABLE,
2196                                         lpdm->dmSize + lpdm->dmDriverExtra);
2197             } else {
2198                 lppd->hDevMode = GlobalReAlloc(lppd->hDevMode,
2199                                                lpdm->dmSize + lpdm->dmDriverExtra,
2200                                                GMEM_MOVEABLE);
2201             }
2202             lpdmReturn = GlobalLock(lppd->hDevMode);
2203             memcpy(lpdmReturn, lpdm, lpdm->dmSize + lpdm->dmDriverExtra);
2204
2205             PRINTDLG_CreateDevNames(&(lppd->hDevNames),
2206                     di->pDriverPath,
2207                     pi->pPrinterName,
2208                     pi->pPortName
2209             );
2210             GlobalUnlock(lppd->hDevMode);
2211         }
2212         HeapFree(GetProcessHeap(), 0, PrintStructures->lpDevMode);
2213         HeapFree(GetProcessHeap(), 0, PrintStructures->lpPrinterInfo);
2214         HeapFree(GetProcessHeap(), 0, PrintStructures->lpDriverInfo);
2215         HeapFree(GetProcessHeap(), 0, PrintStructures);
2216     }
2217     if(bRet && (lppd->Flags & PD_RETURNDC || lppd->Flags & PD_RETURNIC))
2218         bRet = PRINTDLG_CreateDCA(lppd);
2219
2220     TRACE("exit! (%d)\n", bRet);
2221     return bRet;
2222 }
2223
2224 /***********************************************************************
2225  *           PrintDlgW   (COMDLG32.@)
2226  *
2227  * See PrintDlgA.
2228  */
2229 BOOL WINAPI PrintDlgW(LPPRINTDLGW lppd)
2230 {
2231     BOOL      bRet = FALSE;
2232     LPVOID    ptr;
2233     HINSTANCE hInst;
2234
2235     if (!lppd)
2236     {
2237         COMDLG32_SetCommDlgExtendedError(CDERR_INITIALIZATION);
2238         return FALSE;
2239     }
2240
2241     hInst = (HINSTANCE)GetWindowLongPtrW( lppd->hwndOwner, GWLP_HINSTANCE );
2242     if(TRACE_ON(commdlg)) {
2243         char flagstr[1000] = "";
2244         const struct pd_flags *pflag = pd_flags;
2245         for( ; pflag->name; pflag++) {
2246             if(lppd->Flags & pflag->flag)
2247                 strcat(flagstr, pflag->name);
2248         }
2249         TRACE("(%p): hwndOwner = %p, hDevMode = %p, hDevNames = %p\n"
2250               "pp. %d-%d, min p %d, max p %d, copies %d, hinst %p\n"
2251               "flags %08x (%s)\n",
2252               lppd, lppd->hwndOwner, lppd->hDevMode, lppd->hDevNames,
2253               lppd->nFromPage, lppd->nToPage, lppd->nMinPage, lppd->nMaxPage,
2254               lppd->nCopies, lppd->hInstance, lppd->Flags, flagstr);
2255     }
2256
2257     if(lppd->lStructSize != sizeof(PRINTDLGW)) {
2258         WARN("structure size failure !!!\n");
2259         COMDLG32_SetCommDlgExtendedError(CDERR_STRUCTSIZE);
2260         return FALSE;
2261     }
2262
2263     if(lppd->Flags & PD_RETURNDEFAULT) {
2264         PRINTER_INFO_2W *pbuf;
2265         DRIVER_INFO_3W  *dbuf;
2266         HANDLE hprn;
2267         DWORD needed;
2268
2269         if(lppd->hDevMode || lppd->hDevNames) {
2270             WARN("hDevMode or hDevNames non-zero for PD_RETURNDEFAULT\n");
2271             COMDLG32_SetCommDlgExtendedError(PDERR_RETDEFFAILURE);
2272             return FALSE;
2273         }
2274         if(!PRINTDLG_OpenDefaultPrinter(&hprn)) {
2275             WARN("Can't find default printer\n");
2276             COMDLG32_SetCommDlgExtendedError(PDERR_NODEFAULTPRN);
2277             return FALSE;
2278         }
2279
2280         GetPrinterW(hprn, 2, NULL, 0, &needed);
2281         pbuf = HeapAlloc(GetProcessHeap(), 0, needed);
2282         GetPrinterW(hprn, 2, (LPBYTE)pbuf, needed, &needed);
2283
2284         GetPrinterDriverW(hprn, NULL, 3, NULL, 0, &needed);
2285         dbuf = HeapAlloc(GetProcessHeap(),0,needed);
2286         if (!GetPrinterDriverW(hprn, NULL, 3, (LPBYTE)dbuf, needed, &needed)) {
2287             ERR("GetPrinterDriverA failed, le %d, fix your config for printer %s!\n",
2288                 GetLastError(),debugstr_w(pbuf->pPrinterName));
2289             HeapFree(GetProcessHeap(), 0, dbuf);
2290             HeapFree(GetProcessHeap(), 0, pbuf);
2291             COMDLG32_SetCommDlgExtendedError(PDERR_RETDEFFAILURE);
2292             return FALSE;
2293         }
2294         ClosePrinter(hprn);
2295
2296         PRINTDLG_CreateDevNamesW(&(lppd->hDevNames),
2297                                   dbuf->pDriverPath,
2298                                   pbuf->pPrinterName,
2299                                   pbuf->pPortName);
2300         lppd->hDevMode = GlobalAlloc(GMEM_MOVEABLE, pbuf->pDevMode->dmSize +
2301                                      pbuf->pDevMode->dmDriverExtra);
2302         ptr = GlobalLock(lppd->hDevMode);
2303         memcpy(ptr, pbuf->pDevMode, pbuf->pDevMode->dmSize +
2304                pbuf->pDevMode->dmDriverExtra);
2305         GlobalUnlock(lppd->hDevMode);
2306         HeapFree(GetProcessHeap(), 0, pbuf);
2307         HeapFree(GetProcessHeap(), 0, dbuf);
2308         bRet = TRUE;
2309     } else {
2310         HGLOBAL hDlgTmpl;
2311         PRINT_PTRW *PrintStructures;
2312
2313     /* load Dialog resources,
2314      * depending on Flags indicates Print32 or Print32_setup dialog
2315      */
2316         hDlgTmpl = PRINTDLG_GetDlgTemplateW(lppd);
2317         if (!hDlgTmpl) {
2318             COMDLG32_SetCommDlgExtendedError(CDERR_LOADRESFAILURE);
2319             return FALSE;
2320         }
2321         ptr = LockResource( hDlgTmpl );
2322         if (!ptr) {
2323             COMDLG32_SetCommDlgExtendedError(CDERR_LOADRESFAILURE);
2324             return FALSE;
2325         }
2326
2327         PrintStructures = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY,
2328                                     sizeof(PRINT_PTRW));
2329         PrintStructures->lpPrintDlg = lppd;
2330
2331         /* and create & process the dialog .
2332          * -1 is failure, 0 is broken hwnd, everything else is ok.
2333          */
2334         bRet = (0<DialogBoxIndirectParamW(hInst, ptr, lppd->hwndOwner,
2335                                            PrintDlgProcW,
2336                                            (LPARAM)PrintStructures));
2337
2338         if(bRet) {
2339             DEVMODEW *lpdm = PrintStructures->lpDevMode, *lpdmReturn;
2340             PRINTER_INFO_2W *pi = PrintStructures->lpPrinterInfo;
2341             DRIVER_INFO_3W *di = PrintStructures->lpDriverInfo;
2342
2343             if (lppd->hDevMode == 0) {
2344                 TRACE(" No hDevMode yet... Need to create my own\n");
2345                 lppd->hDevMode = GlobalAlloc(GMEM_MOVEABLE,
2346                                         lpdm->dmSize + lpdm->dmDriverExtra);
2347             } else {
2348                 WORD locks;
2349                 if((locks = (GlobalFlags(lppd->hDevMode) & GMEM_LOCKCOUNT))) {
2350                     WARN("hDevMode has %d locks on it. Unlocking it now\n", locks);
2351                     while(locks--) {
2352                         GlobalUnlock(lppd->hDevMode);
2353                         TRACE("Now got %d locks\n", locks);
2354                     }
2355                 }
2356                 lppd->hDevMode = GlobalReAlloc(lppd->hDevMode,
2357                                                lpdm->dmSize + lpdm->dmDriverExtra,
2358                                                GMEM_MOVEABLE);
2359             }
2360             lpdmReturn = GlobalLock(lppd->hDevMode);
2361             memcpy(lpdmReturn, lpdm, lpdm->dmSize + lpdm->dmDriverExtra);
2362
2363             if (lppd->hDevNames != 0) {
2364                 WORD locks;
2365                 if((locks = (GlobalFlags(lppd->hDevNames) & GMEM_LOCKCOUNT))) {
2366                     WARN("hDevNames has %d locks on it. Unlocking it now\n", locks);
2367                     while(locks--)
2368                         GlobalUnlock(lppd->hDevNames);
2369                 }
2370             }
2371             PRINTDLG_CreateDevNamesW(&(lppd->hDevNames),
2372                     di->pDriverPath,
2373                     pi->pPrinterName,
2374                     pi->pPortName
2375             );
2376             GlobalUnlock(lppd->hDevMode);
2377         }
2378         HeapFree(GetProcessHeap(), 0, PrintStructures->lpDevMode);
2379         HeapFree(GetProcessHeap(), 0, PrintStructures->lpPrinterInfo);
2380         HeapFree(GetProcessHeap(), 0, PrintStructures->lpDriverInfo);
2381         HeapFree(GetProcessHeap(), 0, PrintStructures);
2382     }
2383     if(bRet && (lppd->Flags & PD_RETURNDC || lppd->Flags & PD_RETURNIC))
2384         bRet = PRINTDLG_CreateDCW(lppd);
2385
2386     TRACE("exit! (%d)\n", bRet);
2387     return bRet;
2388 }
2389
2390 /***********************************************************************
2391  *
2392  *          PageSetupDlg
2393  * rad1 - portrait
2394  * rad2 - landscape
2395  * cmb1 - printer select (not in standard dialog template)
2396  * cmb2 - paper size
2397  * cmb3 - source (tray?)
2398  * edt4 - border left
2399  * edt5 - border top
2400  * edt6 - border right
2401  * edt7 - border bottom
2402  * psh3 - "Printer..."
2403  */
2404
2405 typedef struct
2406 {
2407     BOOL unicode;
2408     union
2409     {
2410         LPPAGESETUPDLGA dlga;
2411         LPPAGESETUPDLGW dlgw;
2412     } u;
2413     HWND hDlg;                /* Page Setup dialog handle */
2414     RECT rtDrawRect;          /* Drawing rect for page */
2415 } pagesetup_data;
2416
2417 static inline DWORD pagesetup_get_flags(const pagesetup_data *data)
2418 {
2419     return data->u.dlgw->Flags;
2420 }
2421
2422 static inline BOOL is_metric(const pagesetup_data *data)
2423 {
2424     return pagesetup_get_flags(data) & PSD_INHUNDREDTHSOFMILLIMETERS;
2425 }
2426
2427 static inline LONG tenths_mm_to_size(const pagesetup_data *data, LONG size)
2428 {
2429     if (is_metric(data))
2430         return 10 * size;
2431     else
2432         return 10 * size * 100 / 254;
2433 }
2434
2435 static inline LONG thousandths_inch_to_size(const pagesetup_data *data, LONG size)
2436 {
2437     if (is_metric(data))
2438         return size * 254 / 100;
2439     else
2440         return size;
2441 }
2442
2443 static WCHAR get_decimal_sep(void)
2444 {
2445     static WCHAR sep;
2446
2447     if(!sep)
2448     {
2449         WCHAR buf[2] = {'.',0};
2450         GetLocaleInfoW(LOCALE_USER_DEFAULT, LOCALE_SDECIMAL, buf, sizeof(buf) / sizeof(buf[0]));
2451         sep = buf[0];
2452     }
2453     return sep;
2454 }
2455
2456 static void size2str(const pagesetup_data *data, DWORD size, LPWSTR strout)
2457 {
2458     WCHAR integer_fmt[] = {'%','d',0};
2459     WCHAR hundredths_fmt[] = {'%','d','%','c','%','0','2','d',0};
2460     WCHAR thousandths_fmt[] = {'%','d','%','c','%','0','3','d',0};
2461
2462     /* FIXME use LOCALE_SDECIMAL when the edit parsing code can cope */
2463
2464     if (is_metric(data))
2465     {
2466         if(size % 100)
2467             wsprintfW(strout, hundredths_fmt, size / 100, get_decimal_sep(), size % 100);
2468         else
2469             wsprintfW(strout, integer_fmt, size / 100);
2470     }
2471     else
2472     {
2473         if(size % 1000)
2474             wsprintfW(strout, thousandths_fmt, size / 1000, get_decimal_sep(), size % 1000);
2475         else
2476             wsprintfW(strout, integer_fmt, size / 1000);
2477
2478     }
2479 }
2480
2481 static inline BOOL is_default_metric(void)
2482 {
2483     DWORD system;
2484     GetLocaleInfoW(LOCALE_USER_DEFAULT, LOCALE_IMEASURE | LOCALE_RETURN_NUMBER,
2485                    (LPWSTR)&system, sizeof(system));
2486     return system == 0;
2487 }
2488
2489 /**********************************************
2490  *           rotate_rect
2491  * Cyclically permute the four members of rc
2492  * If sense is TRUE l -> t -> r -> b
2493  * otherwise        l <- t <- r <- b
2494  */
2495 static inline void rotate_rect(RECT *rc, BOOL sense)
2496 {
2497     INT tmp;
2498     if(sense)
2499     {
2500         tmp        = rc->bottom;
2501         rc->bottom = rc->right;
2502         rc->right  = rc->top;
2503         rc->top    = rc->left;
2504         rc->left   = tmp;
2505     }
2506     else
2507     {
2508         tmp        = rc->left;
2509         rc->left   = rc->top;
2510         rc->top    = rc->right;
2511         rc->right  = rc->bottom;
2512         rc->bottom = tmp;
2513     }
2514 }
2515
2516 static void pagesetup_set_orientation(pagesetup_data *data, WORD orient)
2517 {
2518     DEVMODEW *dm = GlobalLock(data->u.dlgw->hDevMode);
2519
2520     assert(orient == DMORIENT_PORTRAIT || orient == DMORIENT_LANDSCAPE);
2521
2522     if(data->unicode)
2523         dm->u1.s1.dmOrientation = orient;
2524     else
2525     {
2526         DEVMODEA *dmA = (DEVMODEA *)dm;
2527         dmA->u1.s1.dmOrientation = orient;
2528     }
2529     GlobalUnlock(data->u.dlgw->hDevMode);
2530 }
2531
2532 static WORD pagesetup_get_orientation(const pagesetup_data *data)
2533 {
2534     DEVMODEW *dm = GlobalLock(data->u.dlgw->hDevMode);
2535     WORD orient;
2536
2537     if(data->unicode)
2538         orient = dm->u1.s1.dmOrientation;
2539     else
2540     {
2541         DEVMODEA *dmA = (DEVMODEA *)dm;
2542         orient = dmA->u1.s1.dmOrientation;
2543     }
2544     GlobalUnlock(data->u.dlgw->hDevMode);
2545     return orient;
2546 }
2547
2548 static void pagesetup_set_papersize(pagesetup_data *data, WORD paper)
2549 {
2550     DEVMODEW *dm = GlobalLock(data->u.dlgw->hDevMode);
2551
2552     if(data->unicode)
2553         dm->u1.s1.dmPaperSize = paper;
2554     else
2555     {
2556         DEVMODEA *dmA = (DEVMODEA *)dm;
2557         dmA->u1.s1.dmPaperSize = paper;
2558     }
2559     GlobalUnlock(data->u.dlgw->hDevMode);
2560 }
2561
2562 static WORD pagesetup_get_papersize(const pagesetup_data *data)
2563 {
2564     DEVMODEW *dm = GlobalLock(data->u.dlgw->hDevMode);
2565     WORD paper;
2566
2567     if(data->unicode)
2568         paper = dm->u1.s1.dmPaperSize;
2569     else
2570     {
2571         DEVMODEA *dmA = (DEVMODEA *)dm;
2572         paper = dmA->u1.s1.dmPaperSize;
2573     }
2574     GlobalUnlock(data->u.dlgw->hDevMode);
2575     return paper;
2576 }
2577
2578 static void pagesetup_set_defaultsource(pagesetup_data *data, WORD source)
2579 {
2580     DEVMODEW *dm = GlobalLock(data->u.dlgw->hDevMode);
2581
2582     if(data->unicode)
2583         dm->u1.s1.dmDefaultSource = source;
2584     else
2585     {
2586         DEVMODEA *dmA = (DEVMODEA *)dm;
2587         dmA->u1.s1.dmDefaultSource = source;
2588     }
2589     GlobalUnlock(data->u.dlgw->hDevMode);
2590 }
2591
2592 typedef enum
2593 {
2594     devnames_driver_name,
2595     devnames_device_name,
2596     devnames_output_name
2597 } devnames_name;
2598
2599
2600 static inline WORD get_devname_offset(const DEVNAMES *dn, devnames_name which)
2601 {
2602     switch(which)
2603     {
2604     case devnames_driver_name: return dn->wDriverOffset;
2605     case devnames_device_name: return dn->wDeviceOffset;
2606     case devnames_output_name: return dn->wOutputOffset;
2607     }
2608     ERR("Souldn't be here\n");
2609     return 0;
2610 }
2611
2612 static WCHAR *pagesetup_get_a_devname(const pagesetup_data *data, devnames_name which)
2613 {
2614     DEVNAMES *dn;
2615     WCHAR *name;
2616
2617     dn = GlobalLock(data->u.dlgw->hDevNames);
2618     if(data->unicode)
2619         name = strdupW((WCHAR *)dn + get_devname_offset(dn, which));
2620     else
2621     {
2622         int len = MultiByteToWideChar(CP_ACP, 0, (char*)dn + get_devname_offset(dn, which), -1, NULL, 0);
2623         name = HeapAlloc(GetProcessHeap(), 0, len * sizeof(WCHAR));
2624         MultiByteToWideChar(CP_ACP, 0, (char*)dn + get_devname_offset(dn, which), -1, name, len);
2625     }
2626     GlobalUnlock(data->u.dlgw->hDevNames);
2627     return name;
2628 }
2629
2630 static WCHAR *pagesetup_get_drvname(const pagesetup_data *data)
2631 {
2632     return pagesetup_get_a_devname(data, devnames_driver_name);
2633 }
2634
2635 static WCHAR *pagesetup_get_devname(const pagesetup_data *data)
2636 {
2637     return pagesetup_get_a_devname(data, devnames_device_name);
2638 }
2639
2640 static WCHAR *pagesetup_get_portname(const pagesetup_data *data)
2641 {
2642     return pagesetup_get_a_devname(data, devnames_output_name);
2643 }
2644
2645 static void pagesetup_release_a_devname(const pagesetup_data *data, WCHAR *name)
2646 {
2647     HeapFree(GetProcessHeap(), 0, name);
2648 }
2649
2650 static void pagesetup_set_devnames(pagesetup_data *data, LPCWSTR drv, LPCWSTR devname, LPCWSTR port)
2651 {
2652     DEVNAMES *dn;
2653     WCHAR def[256];
2654     DWORD len = sizeof(DEVNAMES), drv_len, dev_len, port_len;
2655
2656     if(data->unicode)
2657     {
2658         drv_len  = (strlenW(drv) + 1) * sizeof(WCHAR);
2659         dev_len  = (strlenW(devname) + 1) * sizeof(WCHAR);
2660         port_len = (strlenW(port) + 1) * sizeof(WCHAR);
2661     }
2662     else
2663     {
2664         drv_len = WideCharToMultiByte(CP_ACP, 0, drv, -1, NULL, 0, NULL, NULL);
2665         dev_len = WideCharToMultiByte(CP_ACP, 0, devname, -1, NULL, 0, NULL, NULL);
2666         port_len = WideCharToMultiByte(CP_ACP, 0, port, -1, NULL, 0, NULL, NULL);
2667     }
2668     len += drv_len + dev_len + port_len;
2669
2670     if(data->u.dlgw->hDevNames)
2671         data->u.dlgw->hDevNames = GlobalReAlloc(data->u.dlgw->hDevNames, len, GMEM_MOVEABLE);
2672     else
2673         data->u.dlgw->hDevNames = GlobalAlloc(GMEM_MOVEABLE, len);
2674
2675     dn = GlobalLock(data->u.dlgw->hDevNames);
2676
2677     if(data->unicode)
2678     {
2679         WCHAR *ptr = (WCHAR *)(dn + 1);
2680         len = sizeof(DEVNAMES) / sizeof(WCHAR);
2681         dn->wDriverOffset = len;
2682         strcpyW(ptr, drv);
2683         ptr += drv_len / sizeof(WCHAR);
2684         len += drv_len / sizeof(WCHAR);
2685         dn->wDeviceOffset = len;
2686         strcpyW(ptr, devname);
2687         ptr += dev_len / sizeof(WCHAR);
2688         len += dev_len / sizeof(WCHAR);
2689         dn->wOutputOffset = len;
2690         strcpyW(ptr, port);
2691     }
2692     else
2693     {
2694         char *ptr = (char *)(dn + 1);
2695         len = sizeof(DEVNAMES);
2696         dn->wDriverOffset = len;
2697         WideCharToMultiByte(CP_ACP, 0, drv, -1, ptr, drv_len, NULL, NULL);
2698         ptr += drv_len;
2699         len += drv_len;
2700         dn->wDeviceOffset = len;
2701         WideCharToMultiByte(CP_ACP, 0, devname, -1, ptr, dev_len, NULL, NULL);
2702         ptr += dev_len;
2703         len += dev_len;
2704         dn->wOutputOffset = len;
2705         WideCharToMultiByte(CP_ACP, 0, port, -1, ptr, port_len, NULL, NULL);
2706     }
2707
2708     dn->wDefault = 0;
2709     len = sizeof(def) / sizeof(def[0]);
2710     GetDefaultPrinterW(def, &len);
2711     if(!lstrcmpW(def, devname))
2712         dn->wDefault = 1;
2713
2714     GlobalUnlock(data->u.dlgw->hDevNames);
2715 }
2716
2717 static DEVMODEW *pagesetup_get_devmode(const pagesetup_data *data)
2718 {
2719     DEVMODEW *dm = GlobalLock(data->u.dlgw->hDevMode);
2720     DEVMODEW *ret;
2721
2722     if(data->unicode)
2723     {
2724         /* We make a copy even in the unicode case because the ptr
2725            may get passed back to us in pagesetup_set_devmode. */
2726         ret = HeapAlloc(GetProcessHeap(), 0, dm->dmSize + dm->dmDriverExtra);
2727         memcpy(ret, dm, dm->dmSize + dm->dmDriverExtra);
2728     }
2729     else
2730         ret = GdiConvertToDevmodeW((DEVMODEA *)dm);
2731
2732     GlobalUnlock(data->u.dlgw->hDevMode);
2733     return ret;
2734 }
2735
2736 static void pagesetup_release_devmode(const pagesetup_data *data, DEVMODEW *dm)
2737 {
2738     HeapFree(GetProcessHeap(), 0, dm);
2739 }
2740
2741 static void pagesetup_set_devmode(pagesetup_data *data, DEVMODEW *dm)
2742 {
2743     DEVMODEA *dmA = NULL;
2744     void *src, *dst;
2745     DWORD size;
2746
2747     if(data->unicode)
2748     {
2749         size = dm->dmSize + dm->dmDriverExtra;
2750         src = dm;
2751     }
2752     else
2753     {
2754         dmA = convert_to_devmodeA(dm);
2755         size = dmA->dmSize + dmA->dmDriverExtra;
2756         src = dmA;
2757     }
2758
2759     if(data->u.dlgw->hDevMode)
2760         data->u.dlgw->hDevMode = GlobalReAlloc(data->u.dlgw->hDevMode, size,
2761                                                GMEM_MOVEABLE);
2762     else
2763         data->u.dlgw->hDevMode = GlobalAlloc(GMEM_MOVEABLE, size);
2764
2765     dst = GlobalLock(data->u.dlgw->hDevMode);
2766     memcpy(dst, src, size);
2767     GlobalUnlock(data->u.dlgw->hDevMode);
2768     HeapFree(GetProcessHeap(), 0, dmA);
2769 }
2770
2771 static inline POINT *pagesetup_get_papersize_pt(const pagesetup_data *data)
2772 {
2773     return &data->u.dlgw->ptPaperSize;
2774 }
2775
2776 static inline RECT *pagesetup_get_margin_rect(const pagesetup_data *data)
2777 {
2778     return &data->u.dlgw->rtMargin;
2779 }
2780
2781 typedef enum
2782 {
2783     page_setup_hook,
2784     page_paint_hook
2785 } hook_type;
2786
2787 static inline LPPAGESETUPHOOK pagesetup_get_hook(const pagesetup_data *data, hook_type which)
2788 {
2789     switch(which)
2790     {
2791     case page_setup_hook: return data->u.dlgw->lpfnPageSetupHook;
2792     case page_paint_hook: return data->u.dlgw->lpfnPagePaintHook;
2793     }
2794     return NULL;
2795 }
2796
2797 /* This should only be used in calls to hook procs so we return the ptr
2798    already cast to LPARAM */
2799 static inline LPARAM pagesetup_get_dlg_struct(const pagesetup_data *data)
2800 {
2801     return (LPARAM)data->u.dlgw;
2802 }
2803
2804 static inline void swap_point(POINT *pt)
2805 {
2806     LONG tmp = pt->x;
2807     pt->x = pt->y;
2808     pt->y = tmp;
2809 }
2810
2811 static BOOL pagesetup_update_papersize(pagesetup_data *data)
2812 {
2813     DEVMODEW *dm;
2814     LPWSTR devname, portname;
2815     int i, num;
2816     WORD *words = NULL, paperword;
2817     POINT *points = NULL;
2818     BOOL retval = FALSE;
2819
2820     dm       = pagesetup_get_devmode(data);
2821     devname  = pagesetup_get_devname(data);
2822     portname = pagesetup_get_portname(data);
2823
2824     num = DeviceCapabilitiesW(devname, portname, DC_PAPERS, NULL, dm);
2825     if (num <= 0)
2826     {
2827         FIXME("No papernames found for %s/%s\n", debugstr_w(devname), debugstr_w(portname));
2828         goto end;
2829     }
2830
2831     words = HeapAlloc(GetProcessHeap(), 0, num * sizeof(WORD));
2832     points = HeapAlloc(GetProcessHeap(), 0, num * sizeof(POINT));
2833
2834     if (num != DeviceCapabilitiesW(devname, portname, DC_PAPERS, (LPWSTR)words, dm))
2835     {
2836         FIXME("Number of returned words is not %d\n", num);
2837         goto end;
2838     }
2839
2840     if (num != DeviceCapabilitiesW(devname, portname, DC_PAPERSIZE, (LPWSTR)points, dm))
2841     {
2842         FIXME("Number of returned sizes is not %d\n", num);
2843         goto end;
2844     }
2845
2846     paperword = pagesetup_get_papersize(data);
2847
2848     for (i = 0; i < num; i++)
2849         if (words[i] == paperword)
2850             break;
2851
2852     if (i == num)
2853     {
2854         FIXME("Papersize %d not found in list?\n", paperword);
2855         goto end;
2856     }
2857
2858     /* this is _10ths_ of a millimeter */
2859     pagesetup_get_papersize_pt(data)->x = tenths_mm_to_size(data, points[i].x);
2860     pagesetup_get_papersize_pt(data)->y = tenths_mm_to_size(data, points[i].y);
2861
2862     if(pagesetup_get_orientation(data) == DMORIENT_LANDSCAPE)
2863         swap_point(pagesetup_get_papersize_pt(data));
2864
2865     retval = TRUE;
2866
2867 end:
2868     HeapFree(GetProcessHeap(), 0, words);
2869     HeapFree(GetProcessHeap(), 0, points);
2870     pagesetup_release_a_devname(data, portname);
2871     pagesetup_release_a_devname(data, devname);
2872     pagesetup_release_devmode(data, dm);
2873
2874     return retval;
2875 }
2876
2877 /**********************************************************************************************
2878  * pagesetup_change_printer
2879  *
2880  * Redefines hDevMode and hDevNames HANDLES and initialises it.
2881  * 
2882  */
2883 static BOOL pagesetup_change_printer(LPWSTR name, pagesetup_data *data)
2884 {
2885     HANDLE hprn;
2886     DWORD needed;
2887     PRINTER_INFO_2W *prn_info = NULL;
2888     DRIVER_INFO_3W *drv_info = NULL;
2889     DEVMODEW *dm = NULL;
2890     BOOL retval = FALSE;
2891
2892     if(!OpenPrinterW(name, &hprn, NULL))
2893     {
2894         ERR("Can't open printer %s\n", debugstr_w(name));
2895         goto end;
2896     }
2897
2898     GetPrinterW(hprn, 2, NULL, 0, &needed);
2899     prn_info = HeapAlloc(GetProcessHeap(), 0, needed);
2900     GetPrinterW(hprn, 2, (LPBYTE)prn_info, needed, &needed);
2901     GetPrinterDriverW(hprn, NULL, 3, NULL, 0, &needed);
2902     drv_info = HeapAlloc(GetProcessHeap(), 0, needed);
2903     if(!GetPrinterDriverW(hprn, NULL, 3, (LPBYTE)drv_info, needed, &needed))
2904     {
2905         ERR("GetPrinterDriverA failed for %s, fix your config!\n", debugstr_w(prn_info->pPrinterName));
2906         goto end;
2907     }
2908     ClosePrinter(hprn);
2909
2910     needed = DocumentPropertiesW(0, 0, name, NULL, NULL, 0);
2911     if(needed == -1)
2912     {
2913         ERR("DocumentProperties fails on %s\n", debugstr_w(name));
2914         goto end;
2915     }
2916
2917     dm = HeapAlloc(GetProcessHeap(), 0, needed);
2918     DocumentPropertiesW(0, 0, name, dm, NULL, DM_OUT_BUFFER);
2919
2920     pagesetup_set_devmode(data, dm);
2921     pagesetup_set_devnames(data, drv_info->pDriverPath, prn_info->pPrinterName,
2922                            prn_info->pPortName);
2923
2924     retval = TRUE;
2925 end:
2926     HeapFree(GetProcessHeap(), 0, dm);
2927     HeapFree(GetProcessHeap(), 0, prn_info);
2928     HeapFree(GetProcessHeap(), 0, drv_info);
2929     return retval;
2930 }
2931
2932 /****************************************************************************************
2933  *  pagesetup_init_combos
2934  *
2935  *  Fills Printers, Paper and Source combos
2936  *
2937  */
2938 static void pagesetup_init_combos(HWND hDlg, pagesetup_data *data)
2939 {
2940     DEVMODEW *dm;
2941     LPWSTR devname, portname;
2942
2943     dm       = pagesetup_get_devmode(data);
2944     devname  = pagesetup_get_devname(data);
2945     portname = pagesetup_get_portname(data);
2946
2947     PRINTDLG_SetUpPrinterListComboW(hDlg, cmb1, devname);
2948     PRINTDLG_SetUpPaperComboBoxW(hDlg, cmb2, devname, portname, dm);
2949     PRINTDLG_SetUpPaperComboBoxW(hDlg, cmb3, devname, portname, dm);
2950
2951     pagesetup_release_a_devname(data, portname);
2952     pagesetup_release_a_devname(data, devname);
2953     pagesetup_release_devmode(data, dm);
2954 }
2955
2956
2957 /****************************************************************************************
2958  *  pagesetup_change_printer_dialog
2959  *
2960  *  Pops up another dialog that lets the user pick another printer.
2961  *
2962  *  For now we display the PrintDlg, this should display a striped down version of it.
2963  */
2964 static void pagesetup_change_printer_dialog(HWND hDlg, pagesetup_data *data)
2965 {
2966     PRINTDLGW prnt;
2967     LPWSTR drvname, devname, portname;
2968     DEVMODEW *tmp_dm, *dm;
2969
2970     memset(&prnt, 0, sizeof(prnt));
2971     prnt.lStructSize = sizeof(prnt);
2972     prnt.Flags     = 0;
2973     prnt.hwndOwner = hDlg;
2974
2975     drvname = pagesetup_get_drvname(data);
2976     devname = pagesetup_get_devname(data);
2977     portname = pagesetup_get_portname(data);
2978     prnt.hDevNames = 0;
2979     PRINTDLG_CreateDevNamesW(&prnt.hDevNames, drvname, devname, portname);
2980     pagesetup_release_a_devname(data, portname);
2981     pagesetup_release_a_devname(data, devname);
2982     pagesetup_release_a_devname(data, drvname);
2983
2984     tmp_dm = pagesetup_get_devmode(data);
2985     prnt.hDevMode = GlobalAlloc(GMEM_MOVEABLE, tmp_dm->dmSize + tmp_dm->dmDriverExtra);
2986     dm = GlobalLock(prnt.hDevMode);
2987     memcpy(dm, tmp_dm, tmp_dm->dmSize + tmp_dm->dmDriverExtra);
2988     GlobalUnlock(prnt.hDevMode);
2989     pagesetup_release_devmode(data, tmp_dm);
2990
2991     if (PrintDlgW(&prnt))
2992     {
2993         DEVMODEW *dm = GlobalLock(prnt.hDevMode);
2994         DEVNAMES *dn = GlobalLock(prnt.hDevNames);
2995
2996         pagesetup_set_devnames(data, (WCHAR*)dn + dn->wDriverOffset,
2997                                (WCHAR*)dn + dn->wDeviceOffset, (WCHAR *)dn + dn->wOutputOffset);
2998         pagesetup_set_devmode(data, dm);
2999         GlobalUnlock(prnt.hDevNames);
3000         GlobalUnlock(prnt.hDevMode);
3001         pagesetup_init_combos(hDlg, data);
3002     }
3003
3004     GlobalFree(prnt.hDevMode);
3005     GlobalFree(prnt.hDevNames);
3006
3007 }
3008
3009 /******************************************************************************************
3010  * pagesetup_change_preview
3011  *
3012  * Changes paper preview size / position
3013  *
3014  */
3015 static void pagesetup_change_preview(const pagesetup_data *data)
3016 {
3017     LONG width, height, x, y;
3018     RECT tmp;
3019     const int shadow = 4;
3020
3021     if(pagesetup_get_orientation(data) == DMORIENT_LANDSCAPE)
3022     {
3023         width  = data->rtDrawRect.right - data->rtDrawRect.left;
3024         height = pagesetup_get_papersize_pt(data)->y * width / pagesetup_get_papersize_pt(data)->x;
3025     }
3026     else
3027     {
3028         height = data->rtDrawRect.bottom - data->rtDrawRect.top;
3029         width  = pagesetup_get_papersize_pt(data)->x * height / pagesetup_get_papersize_pt(data)->y;
3030     }
3031     x = (data->rtDrawRect.right + data->rtDrawRect.left - width) / 2;
3032     y = (data->rtDrawRect.bottom + data->rtDrawRect.top - height) / 2;
3033     TRACE("draw rect %s x=%d, y=%d, w=%d, h=%d\n",
3034           wine_dbgstr_rect(&data->rtDrawRect), x, y, width, height);
3035
3036     MoveWindow(GetDlgItem(data->hDlg, rct2), x + width, y + shadow, shadow, height, FALSE);
3037     MoveWindow(GetDlgItem(data->hDlg, rct3), x + shadow, y + height, width, shadow, FALSE);
3038     MoveWindow(GetDlgItem(data->hDlg, rct1), x, y, width, height, FALSE);
3039
3040     tmp = data->rtDrawRect;
3041     tmp.right  += shadow;
3042     tmp.bottom += shadow;
3043     InvalidateRect(data->hDlg, &tmp, TRUE);
3044 }
3045
3046 static inline LONG *element_from_margin_id(RECT *rc, WORD id)
3047 {
3048     switch(id)
3049     {
3050     case edt4: return &rc->left;
3051     case edt5: return &rc->top;
3052     case edt6: return &rc->right;
3053     case edt7: return &rc->bottom;
3054     }
3055     return NULL;
3056 }
3057
3058 static void update_margin_edits(HWND hDlg, const pagesetup_data *data, WORD id)
3059 {
3060     WCHAR str[100];
3061     WORD idx;
3062
3063     for(idx = edt4; idx <= edt7; idx++)
3064     {
3065         if(id == 0 || id == idx)
3066         {
3067             size2str(data, *element_from_margin_id(pagesetup_get_margin_rect(data), idx), str);
3068             SetDlgItemTextW(hDlg, idx, str);
3069         }
3070     }
3071 }
3072
3073 static void margin_edit_notification(HWND hDlg, const pagesetup_data *data, WORD msg, WORD id)
3074 {
3075     switch (msg)
3076     {
3077     case EN_CHANGE:
3078       {
3079         WCHAR buf[10];
3080         LONG val = 0;
3081         LONG *value = element_from_margin_id(pagesetup_get_margin_rect(data), id);
3082
3083         if (GetDlgItemTextW(hDlg, id, buf, sizeof(buf) / sizeof(buf[0])) != 0)
3084         {
3085             WCHAR *end;
3086             WCHAR decimal = get_decimal_sep();
3087
3088             val = strtolW(buf, &end, 10);
3089             if(end != buf || *end == decimal)
3090             {
3091                 int mult = is_metric(data) ? 100 : 1000;
3092                 val *= mult;
3093                 if(*end == decimal)
3094                 {
3095                     while(mult > 1)
3096                     {
3097                         end++;
3098                         mult /= 10;
3099                         if(isdigitW(*end))
3100                             val += (*end - '0') * mult;
3101                         else
3102                             break;
3103                     }
3104                 }
3105             }
3106         }
3107         *value = val;
3108         return;
3109       }
3110
3111     case EN_KILLFOCUS:
3112         update_margin_edits(hDlg, data, id);
3113         return;
3114     }
3115 }
3116
3117 static void set_margin_groupbox_title(HWND hDlg, const pagesetup_data *data)
3118 {
3119     WCHAR title[256];
3120
3121     if(LoadStringW(COMDLG32_hInstance, is_metric(data) ? PD32_MARGINS_IN_MILLIMETERS : PD32_MARGINS_IN_INCHES,
3122                    title, sizeof(title)/sizeof(title[0])))
3123         SetDlgItemTextW(hDlg, grp4, title);
3124 }
3125
3126 static void pagesetup_update_orientation_buttons(HWND hDlg, const pagesetup_data *data)
3127 {
3128     if (pagesetup_get_orientation(data) == DMORIENT_LANDSCAPE)
3129         CheckRadioButton(hDlg, rad1, rad2, rad2);
3130     else
3131         CheckRadioButton(hDlg, rad1, rad2, rad1);
3132 }
3133
3134 /****************************************************************************************
3135  *  pagesetup_printer_properties
3136  *
3137  *  Handle invocation of the 'Properties' button (not present in the default template).
3138  */
3139 static void pagesetup_printer_properties(HWND hDlg, pagesetup_data *data)
3140 {
3141     HANDLE hprn;
3142     LPWSTR devname;
3143     DEVMODEW *dm;
3144     LRESULT count;
3145     int i;
3146
3147     devname = pagesetup_get_devname(data);
3148
3149     if (!OpenPrinterW(devname, &hprn, NULL))
3150     {
3151         FIXME("Call to OpenPrinter did not succeed!\n");
3152         pagesetup_release_a_devname(data, devname);
3153         return;
3154     }
3155
3156     dm = pagesetup_get_devmode(data);
3157     DocumentPropertiesW(hDlg, hprn, devname, dm, dm, DM_IN_BUFFER | DM_OUT_BUFFER | DM_IN_PROMPT);
3158     pagesetup_set_devmode(data, dm);
3159     pagesetup_release_devmode(data, dm);
3160     pagesetup_release_a_devname(data, devname);
3161     ClosePrinter(hprn);
3162
3163     /* Changing paper */
3164     pagesetup_update_papersize(data);
3165     pagesetup_update_orientation_buttons(hDlg, data);
3166
3167     /* Changing paper preview */
3168     pagesetup_change_preview(data);
3169
3170     /* Selecting paper in combo */
3171     count = SendDlgItemMessageW(hDlg, cmb2, CB_GETCOUNT, 0, 0);
3172     if(count != CB_ERR)
3173     {
3174         WORD paperword = pagesetup_get_papersize(data);
3175         for(i = 0; i < count; i++)
3176         {
3177             if(SendDlgItemMessageW(hDlg, cmb2, CB_GETITEMDATA, i, 0) == paperword) {
3178                 SendDlgItemMessageW(hDlg, cmb2, CB_SETCURSEL, i, 0);
3179                 break;
3180             }
3181         }
3182     }
3183 }
3184
3185 /********************************************************************************
3186  * pagesetup_wm_command
3187  * process WM_COMMAND message for PageSetupDlg
3188  *
3189  * PARAMS
3190  *  hDlg        [in]    Main dialog HANDLE 
3191  *  wParam      [in]    WM_COMMAND wParam
3192  *  lParam      [in]    WM_COMMAND lParam
3193  *  pda         [in/out] ptr to PageSetupDataA
3194  */
3195
3196 static BOOL pagesetup_wm_command(HWND hDlg, WPARAM wParam, LPARAM lParam, pagesetup_data *data)
3197 {
3198     WORD msg = HIWORD(wParam);
3199     WORD id  = LOWORD(wParam);
3200
3201     TRACE("loword (lparam) %d, wparam 0x%lx, lparam %08lx\n",
3202             LOWORD(lParam),wParam,lParam);
3203     switch (id)  {
3204     case IDOK:
3205         EndDialog(hDlg, TRUE);
3206         return TRUE ;
3207
3208     case IDCANCEL:
3209         EndDialog(hDlg, FALSE);
3210         return FALSE ;
3211
3212     case psh3: /* Printer... */
3213         pagesetup_change_printer_dialog(hDlg, data);
3214         return TRUE;
3215
3216     case rad1: /* Portrait */
3217     case rad2: /* Landscape */
3218         if((id == rad1 && pagesetup_get_orientation(data) == DMORIENT_LANDSCAPE) ||
3219            (id == rad2 && pagesetup_get_orientation(data) == DMORIENT_PORTRAIT))
3220         {
3221             pagesetup_set_orientation(data, (id == rad1) ? DMORIENT_PORTRAIT : DMORIENT_LANDSCAPE);
3222             pagesetup_update_papersize(data);
3223             rotate_rect(pagesetup_get_margin_rect(data), (id == rad2));
3224             update_margin_edits(hDlg, data, 0);
3225             pagesetup_change_preview(data);
3226         }
3227         break;
3228     case cmb1: /* Printer combo */
3229         if(msg == CBN_SELCHANGE)
3230         {
3231             WCHAR name[256];
3232             GetDlgItemTextW(hDlg, id, name, sizeof(name) / sizeof(name[0]));
3233             pagesetup_change_printer(name, data);
3234             pagesetup_init_combos(hDlg, data);
3235         }
3236         break;
3237     case cmb2: /* Paper combo */
3238         if(msg == CBN_SELCHANGE)
3239         {
3240             DWORD paperword = SendDlgItemMessageW(hDlg, cmb2, CB_GETITEMDATA,
3241                                                   SendDlgItemMessageW(hDlg, cmb2, CB_GETCURSEL, 0, 0), 0);
3242             if (paperword != CB_ERR)
3243             {
3244                 pagesetup_set_papersize(data, paperword);
3245                 pagesetup_update_papersize(data);
3246                 pagesetup_change_preview(data);
3247             } else
3248                 FIXME("could not get dialog text for papersize cmbbox?\n");
3249         }
3250         break;
3251     case cmb3: /* Paper Source */
3252         if(msg == CBN_SELCHANGE)
3253         {
3254             WORD source = SendDlgItemMessageW(hDlg, cmb3, CB_GETITEMDATA,
3255                                               SendDlgItemMessageW(hDlg, cmb3, CB_GETCURSEL, 0, 0), 0);
3256             pagesetup_set_defaultsource(data, source);
3257         }
3258         break;
3259     case psh2: /* Printer Properties button */
3260         pagesetup_printer_properties(hDlg, data);
3261         break;
3262     case edt4:
3263     case edt5:
3264     case edt6:
3265     case edt7:
3266         margin_edit_notification(hDlg, data, msg, id);
3267         break;
3268     }
3269     InvalidateRect(GetDlgItem(hDlg, rct1), NULL, TRUE);
3270     return FALSE;
3271 }
3272
3273 /***********************************************************************
3274  *           default_page_paint_hook
3275  * Default hook paint procedure that receives WM_PSD_* messages from the dialog box 
3276  * whenever the sample page is redrawn.
3277  */
3278 static UINT_PTR default_page_paint_hook(HWND hwndDlg, UINT uMsg, WPARAM wParam, LPARAM lParam,
3279                                         const pagesetup_data *data)
3280 {
3281     LPRECT lprc = (LPRECT) lParam;
3282     HDC hdc = (HDC) wParam;
3283     HPEN hpen, holdpen;
3284     LOGFONTW lf;
3285     HFONT hfont, holdfont;
3286     INT oldbkmode;
3287     TRACE("uMsg: WM_USER+%d\n",uMsg-WM_USER);
3288     /* Call user paint hook if enable */
3289     if (pagesetup_get_flags(data) & PSD_ENABLEPAGEPAINTHOOK)
3290         if (pagesetup_get_hook(data, page_paint_hook)(hwndDlg, uMsg, wParam, lParam))
3291             return TRUE;
3292
3293     switch (uMsg) {
3294        /* LPPAGESETUPDLG in lParam */
3295        case WM_PSD_PAGESETUPDLG:
3296        /* Inform about the sample page rectangle */
3297        case WM_PSD_FULLPAGERECT:
3298        /* Inform about the margin rectangle */
3299        case WM_PSD_MINMARGINRECT:
3300             return FALSE;
3301
3302         /* Draw dashed rectangle showing margins */
3303         case WM_PSD_MARGINRECT:
3304             hpen = CreatePen(PS_DASH, 1, GetSysColor(COLOR_3DSHADOW));
3305             holdpen = SelectObject(hdc, hpen);
3306             Rectangle(hdc, lprc->left, lprc->top, lprc->right, lprc->bottom);
3307             DeleteObject(SelectObject(hdc, holdpen));
3308             return TRUE;
3309         /* Draw the fake document */
3310         case WM_PSD_GREEKTEXTRECT:
3311             /* select a nice scalable font, because we want the text really small */
3312             SystemParametersInfoW(SPI_GETICONTITLELOGFONT, sizeof(lf), &lf, 0);
3313             lf.lfHeight = 6; /* value chosen based on visual effect */
3314             hfont = CreateFontIndirectW(&lf);
3315             holdfont = SelectObject(hdc, hfont);
3316
3317             /* if text not loaded, then do so now */
3318             if (wszFakeDocumentText[0] == '\0')
3319                  LoadStringW(COMDLG32_hInstance,
3320                         IDS_FAKEDOCTEXT,
3321                         wszFakeDocumentText,
3322                         sizeof(wszFakeDocumentText)/sizeof(wszFakeDocumentText[0]));
3323
3324             oldbkmode = SetBkMode(hdc, TRANSPARENT);
3325             DrawTextW(hdc, wszFakeDocumentText, -1, lprc, DT_TOP|DT_LEFT|DT_NOPREFIX|DT_WORDBREAK);
3326             SetBkMode(hdc, oldbkmode);
3327
3328             DeleteObject(SelectObject(hdc, holdfont));
3329             return TRUE;
3330
3331         /* Envelope stamp */
3332         case WM_PSD_ENVSTAMPRECT:
3333         /* Return address */
3334         case WM_PSD_YAFULLPAGERECT:
3335             FIXME("envelope/stamp is not implemented\n");
3336             return FALSE;
3337         default:
3338             FIXME("Unknown message %x\n",uMsg);
3339             return FALSE;
3340     }
3341     return TRUE;
3342 }
3343
3344 /***********************************************************************
3345  *           PagePaintProc
3346  * The main paint procedure for the PageSetupDlg function.
3347  * The Page Setup dialog box includes an image of a sample page that shows how
3348  * the user's selections affect the appearance of the printed output.
3349  * The image consists of a rectangle that represents the selected paper
3350  * or envelope type, with a dotted-line rectangle representing
3351  * the current margins, and partial (Greek text) characters
3352  * to show how text looks on the printed page. 
3353  *
3354  * The following messages in the order sends to user hook procedure:
3355  *   WM_PSD_PAGESETUPDLG    Draw the contents of the sample page
3356  *   WM_PSD_FULLPAGERECT    Inform about the bounding rectangle
3357  *   WM_PSD_MINMARGINRECT   Inform about the margin rectangle (min margin?)
3358  *   WM_PSD_MARGINRECT      Draw the margin rectangle
3359  *   WM_PSD_GREEKTEXTRECT   Draw the Greek text inside the margin rectangle
3360  * If any of first three messages returns TRUE, painting done.
3361  *
3362  * PARAMS:
3363  *   hWnd   [in] Handle to the Page Setup dialog box
3364  *   uMsg   [in] Received message
3365  *
3366  * TODO:
3367  *   WM_PSD_ENVSTAMPRECT    Draw in the envelope-stamp rectangle (for envelopes only)
3368  *   WM_PSD_YAFULLPAGERECT  Draw the return address portion (for envelopes and other paper sizes)
3369  *
3370  * RETURNS:
3371  *   FALSE if all done correctly
3372  *
3373  */
3374
3375
3376 static LRESULT CALLBACK
3377 PRINTDLG_PagePaintProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
3378 {
3379     PAINTSTRUCT ps;
3380     RECT rcClient, rcMargin;
3381     HPEN hpen, holdpen;
3382     HDC hdc;
3383     HBRUSH hbrush, holdbrush;
3384     pagesetup_data *data;
3385     int papersize=0, orientation=0; /* FIXME: set this values for user paint hook */
3386     double scalx, scaly;
3387
3388     if (uMsg != WM_PAINT)
3389         return CallWindowProcA(lpfnStaticWndProc, hWnd, uMsg, wParam, lParam);
3390
3391     /* Processing WM_PAINT message */
3392     data = GetPropW(hWnd, pagesetupdlg_prop);
3393     if (!data) {
3394         WARN("__WINE_PAGESETUPDLGDATA prop not set?\n");
3395         return FALSE;
3396     }
3397     if (default_page_paint_hook(hWnd, WM_PSD_PAGESETUPDLG, MAKELONG(papersize, orientation),
3398                                 pagesetup_get_dlg_struct(data), data))
3399         return FALSE;
3400
3401     hdc = BeginPaint(hWnd, &ps);
3402     GetClientRect(hWnd, &rcClient);
3403     
3404     scalx = rcClient.right  / (double)pagesetup_get_papersize_pt(data)->x;
3405     scaly = rcClient.bottom / (double)pagesetup_get_papersize_pt(data)->y;
3406     rcMargin = rcClient;
3407
3408     rcMargin.left   += pagesetup_get_margin_rect(data)->left   * scalx;
3409     rcMargin.top    += pagesetup_get_margin_rect(data)->top    * scaly;
3410     rcMargin.right  -= pagesetup_get_margin_rect(data)->right  * scalx;
3411     rcMargin.bottom -= pagesetup_get_margin_rect(data)->bottom * scaly;
3412
3413     /* if the space is too small then we make sure to not draw anything */
3414     rcMargin.left = min(rcMargin.left, rcMargin.right);
3415     rcMargin.top = min(rcMargin.top, rcMargin.bottom);
3416
3417     if (!default_page_paint_hook(hWnd, WM_PSD_FULLPAGERECT, (WPARAM)hdc, (LPARAM)&rcClient, data) &&
3418         !default_page_paint_hook(hWnd, WM_PSD_MINMARGINRECT, (WPARAM)hdc, (LPARAM)&rcMargin, data) )
3419     {
3420         /* fill background */
3421         hbrush = GetSysColorBrush(COLOR_3DHIGHLIGHT);
3422         FillRect(hdc, &rcClient, hbrush);
3423         holdbrush = SelectObject(hdc, hbrush);
3424
3425         hpen = CreatePen(PS_SOLID, 1, GetSysColor(COLOR_3DSHADOW));
3426         holdpen = SelectObject(hdc, hpen);
3427         
3428         /* paint left edge */
3429         MoveToEx(hdc, rcClient.left, rcClient.top, NULL);
3430         LineTo(hdc, rcClient.left, rcClient.bottom-1);
3431
3432         /* paint top edge */
3433         MoveToEx(hdc, rcClient.left, rcClient.top, NULL);
3434         LineTo(hdc, rcClient.right, rcClient.top);
3435
3436         hpen = CreatePen(PS_SOLID, 1, GetSysColor(COLOR_3DDKSHADOW));
3437         DeleteObject(SelectObject(hdc, hpen));
3438
3439         /* paint right edge */
3440         MoveToEx(hdc, rcClient.right-1, rcClient.top, NULL);
3441         LineTo(hdc, rcClient.right-1, rcClient.bottom);
3442
3443         /* paint bottom edge */
3444         MoveToEx(hdc, rcClient.left, rcClient.bottom-1, NULL);
3445         LineTo(hdc, rcClient.right, rcClient.bottom-1);
3446
3447         DeleteObject(SelectObject(hdc, holdpen));
3448         DeleteObject(SelectObject(hdc, holdbrush));
3449
3450         default_page_paint_hook(hWnd, WM_PSD_MARGINRECT, (WPARAM)hdc, (LPARAM)&rcMargin, data);
3451
3452         /* give text a bit of a space from the frame */
3453         rcMargin.left += 2;
3454         rcMargin.top += 2;
3455         rcMargin.right -= 2;
3456         rcMargin.bottom -= 2;
3457         
3458         /* if the space is too small then we make sure to not draw anything */
3459         rcMargin.left = min(rcMargin.left, rcMargin.right);
3460         rcMargin.top = min(rcMargin.top, rcMargin.bottom);
3461
3462         default_page_paint_hook(hWnd, WM_PSD_GREEKTEXTRECT, (WPARAM)hdc, (LPARAM)&rcMargin, data);
3463     }
3464
3465     EndPaint(hWnd, &ps);
3466     return FALSE;
3467 }
3468
3469 /*******************************************************
3470  * The margin edit controls are subclassed to filter
3471  * anything other than numbers and the decimal separator.
3472  */
3473 static LRESULT CALLBACK pagesetup_margin_editproc(HWND hwnd, UINT msg, WPARAM wparam, LPARAM lparam)
3474 {
3475     if (msg == WM_CHAR)
3476     {
3477         WCHAR decimal = get_decimal_sep();
3478         WCHAR wc = (WCHAR)wparam;
3479         if(!isdigitW(wc) && wc != decimal && wc != VK_BACK) return 0;
3480     }
3481     return CallWindowProcW(edit_wndproc, hwnd, msg, wparam, lparam);
3482 }
3483
3484 static void subclass_margin_edits(HWND hDlg)
3485 {
3486     int id;
3487     WNDPROC old_proc;
3488
3489     for(id = edt4; id <= edt7; id++)
3490     {
3491         old_proc = (WNDPROC)SetWindowLongPtrW(GetDlgItem(hDlg, id),
3492                                               GWLP_WNDPROC,
3493                                               (ULONG_PTR)pagesetup_margin_editproc);
3494         InterlockedCompareExchangePointer((void**)&edit_wndproc, old_proc, NULL);
3495     }
3496 }
3497
3498 /***********************************************************************
3499  *           pagesetup_dlg_proc
3500  *
3501  * Message handler for PageSetupDlg
3502  */
3503 static INT_PTR CALLBACK pagesetup_dlg_proc(HWND hDlg, UINT uMsg, WPARAM wParam, LPARAM lParam)
3504 {
3505     pagesetup_data *data;
3506     INT_PTR             res = FALSE;
3507     HWND                hDrawWnd;
3508
3509     if (uMsg == WM_INITDIALOG) { /*Init dialog*/
3510         data = (pagesetup_data *)lParam;
3511         data->hDlg = hDlg;
3512
3513         hDrawWnd = GetDlgItem(hDlg, rct1); 
3514         TRACE("set property to %p\n", data);
3515         SetPropW(hDlg, pagesetupdlg_prop, data);
3516         SetPropW(hDrawWnd, pagesetupdlg_prop, data);
3517         GetWindowRect(hDrawWnd, &data->rtDrawRect); /* Calculating rect in client coordinates where paper draws */
3518         ScreenToClient(hDlg, (LPPOINT)&data->rtDrawRect);
3519         ScreenToClient(hDlg, (LPPOINT)(&data->rtDrawRect.right));
3520         lpfnStaticWndProc = (WNDPROC)SetWindowLongPtrW(
3521             hDrawWnd,
3522             GWLP_WNDPROC,
3523             (ULONG_PTR)PRINTDLG_PagePaintProc);
3524         
3525         /* FIXME: Paint hook. Must it be at begin of initialization or at end? */
3526         res = TRUE;
3527         if (pagesetup_get_flags(data) & PSD_ENABLEPAGESETUPHOOK)
3528         {
3529             if (!pagesetup_get_hook(data, page_setup_hook)(hDlg, uMsg, wParam,
3530                                                            pagesetup_get_dlg_struct(data)))
3531                 FIXME("Setup page hook failed?\n");
3532         }
3533
3534         /* if printer button disabled */
3535         if (pagesetup_get_flags(data) & PSD_DISABLEPRINTER)
3536             EnableWindow(GetDlgItem(hDlg, psh3), FALSE);
3537         /* if margin edit boxes disabled */
3538         if (pagesetup_get_flags(data) & PSD_DISABLEMARGINS)
3539         {
3540             EnableWindow(GetDlgItem(hDlg, edt4), FALSE);
3541             EnableWindow(GetDlgItem(hDlg, edt5), FALSE);
3542             EnableWindow(GetDlgItem(hDlg, edt6), FALSE);
3543             EnableWindow(GetDlgItem(hDlg, edt7), FALSE);
3544         }
3545
3546         /* Set orientation radiobuttons properly */
3547         pagesetup_update_orientation_buttons(hDlg, data);
3548
3549         /* if orientation disabled */
3550         if (pagesetup_get_flags(data) & PSD_DISABLEORIENTATION)
3551         {
3552             EnableWindow(GetDlgItem(hDlg,rad1),FALSE);
3553             EnableWindow(GetDlgItem(hDlg,rad2),FALSE);
3554         }
3555
3556         /* We fill them out enabled or not */
3557         if (!(pagesetup_get_flags(data) & PSD_MARGINS))
3558         {
3559             /* default is 1 inch */
3560             LONG size = thousandths_inch_to_size(data, 1000);
3561             SetRect(pagesetup_get_margin_rect(data), size, size, size, size);
3562         }
3563         update_margin_edits(hDlg, data, 0);
3564         subclass_margin_edits(hDlg);
3565         set_margin_groupbox_title(hDlg, data);
3566
3567         /* if paper disabled */
3568         if (pagesetup_get_flags(data) & PSD_DISABLEPAPER)
3569         {
3570             EnableWindow(GetDlgItem(hDlg,cmb2),FALSE);
3571             EnableWindow(GetDlgItem(hDlg,cmb3),FALSE);
3572         }
3573
3574         /* filling combos: printer, paper, source. selecting current printer (from DEVMODEA) */
3575         pagesetup_init_combos(hDlg, data);
3576         pagesetup_update_papersize(data);
3577         pagesetup_set_defaultsource(data, DMBIN_FORMSOURCE); /* FIXME: This is the auto select bin. Is this correct? */
3578
3579         /* Drawing paper prev */
3580         pagesetup_change_preview(data);
3581         return TRUE;
3582     } else {
3583         data = GetPropW(hDlg, pagesetupdlg_prop);
3584         if (!data)
3585         {
3586             WARN("__WINE_PAGESETUPDLGDATA prop not set?\n");
3587             return FALSE;
3588         }
3589         if (pagesetup_get_flags(data) & PSD_ENABLEPAGESETUPHOOK)
3590         {
3591             res = pagesetup_get_hook(data, page_setup_hook)(hDlg, uMsg, wParam, lParam);
3592             if (res) return res;
3593         }
3594     }
3595     switch (uMsg) {
3596     case WM_COMMAND:
3597         return pagesetup_wm_command(hDlg, wParam, lParam, data);
3598     }
3599     return FALSE;
3600 }
3601
3602 static WCHAR *get_default_printer(void)
3603 {
3604     WCHAR *name = NULL;
3605     DWORD len = 0;
3606
3607     GetDefaultPrinterW(NULL, &len);
3608     if(len)
3609     {
3610         name = HeapAlloc(GetProcessHeap(), 0, len * sizeof(WCHAR));
3611         GetDefaultPrinterW(name, &len);
3612     }
3613     return name;
3614 }
3615
3616 static void pagesetup_dump_dlg_struct(pagesetup_data *data)
3617 {
3618     if(TRACE_ON(commdlg))
3619     {
3620         char flagstr[1000] = "";
3621         const struct pd_flags *pflag = psd_flags;
3622         for( ; pflag->name; pflag++)
3623         {
3624             if(pagesetup_get_flags(data) & pflag->flag)
3625             {
3626                 strcat(flagstr, pflag->name);
3627                 strcat(flagstr, "|");
3628             }
3629         }
3630         TRACE("%s: (%p): hwndOwner = %p, hDevMode = %p, hDevNames = %p\n"
3631               "hinst %p, flags %08x (%s)\n",
3632               data->unicode ? "unicode" : "ansi",
3633               data->u.dlgw, data->u.dlgw->hwndOwner, data->u.dlgw->hDevMode,
3634               data->u.dlgw->hDevNames, data->u.dlgw->hInstance,
3635               pagesetup_get_flags(data), flagstr);
3636     }
3637 }
3638
3639 static void *pagesetup_get_template(pagesetup_data *data)
3640 {
3641     HRSRC res;
3642     HGLOBAL tmpl_handle;
3643
3644     if(pagesetup_get_flags(data) & PSD_ENABLEPAGESETUPTEMPLATEHANDLE)
3645     {
3646         tmpl_handle = data->u.dlgw->hPageSetupTemplate;
3647     }
3648     else if(pagesetup_get_flags(data) & PSD_ENABLEPAGESETUPTEMPLATE)
3649     {
3650         if(data->unicode)
3651             res = FindResourceW(data->u.dlgw->hInstance,
3652                                 data->u.dlgw->lpPageSetupTemplateName, MAKEINTRESOURCEW(RT_DIALOG));
3653         else
3654             res = FindResourceA(data->u.dlga->hInstance,
3655                                 data->u.dlga->lpPageSetupTemplateName, MAKEINTRESOURCEA(RT_DIALOG));
3656         tmpl_handle = LoadResource(data->u.dlgw->hInstance, res);
3657     }
3658     else
3659     {
3660         res = FindResourceW(COMDLG32_hInstance, MAKEINTRESOURCEW(PAGESETUPDLGORD),
3661                             MAKEINTRESOURCEW(RT_DIALOG));
3662         tmpl_handle = LoadResource(COMDLG32_hInstance, res);
3663     }
3664     return LockResource(tmpl_handle);
3665 }
3666
3667 static BOOL pagesetup_common(pagesetup_data *data)
3668 {
3669     BOOL ret;
3670     void *tmpl;
3671
3672     if(!pagesetup_get_dlg_struct(data))
3673     {
3674         COMDLG32_SetCommDlgExtendedError(CDERR_INITIALIZATION);
3675         return FALSE;
3676     }
3677
3678     pagesetup_dump_dlg_struct(data);
3679
3680     if(data->u.dlgw->lStructSize != sizeof(PAGESETUPDLGW))
3681     {
3682         COMDLG32_SetCommDlgExtendedError(CDERR_STRUCTSIZE);
3683         return FALSE;
3684     }
3685
3686     if ((pagesetup_get_flags(data) & PSD_ENABLEPAGEPAINTHOOK) &&
3687         (pagesetup_get_hook(data, page_paint_hook) == NULL))
3688     {
3689         COMDLG32_SetCommDlgExtendedError(CDERR_NOHOOK);
3690         return FALSE;
3691     }
3692
3693     if(!(pagesetup_get_flags(data) & (PSD_INTHOUSANDTHSOFINCHES | PSD_INHUNDREDTHSOFMILLIMETERS)))
3694         data->u.dlgw->Flags |= is_default_metric() ?
3695             PSD_INHUNDREDTHSOFMILLIMETERS : PSD_INTHOUSANDTHSOFINCHES;
3696
3697     if (!data->u.dlgw->hDevMode || !data->u.dlgw->hDevNames)
3698     {
3699         WCHAR *def = get_default_printer();
3700         if(!def)
3701         {
3702             if (!(pagesetup_get_flags(data) & PSD_NOWARNING))
3703             {
3704                 WCHAR errstr[256];
3705                 LoadStringW(COMDLG32_hInstance, PD32_NO_DEFAULT_PRINTER, errstr, 255);
3706                 MessageBoxW(data->u.dlgw->hwndOwner, errstr, 0, MB_OK | MB_ICONERROR);
3707             }
3708             COMDLG32_SetCommDlgExtendedError(PDERR_NODEFAULTPRN);
3709             return FALSE;
3710         }
3711         pagesetup_change_printer(def, data);
3712         HeapFree(GetProcessHeap(), 0, def);
3713     }
3714
3715     if (pagesetup_get_flags(data) & PSD_RETURNDEFAULT)
3716     {
3717         pagesetup_update_papersize(data);
3718         return TRUE;
3719     }
3720
3721     tmpl = pagesetup_get_template(data);
3722
3723     ret = DialogBoxIndirectParamW(data->u.dlgw->hInstance, tmpl,
3724                                   data->u.dlgw->hwndOwner,
3725                                   pagesetup_dlg_proc, (LPARAM)data) > 0;
3726     return ret;
3727 }
3728
3729 /***********************************************************************
3730  *            PageSetupDlgA  (COMDLG32.@)
3731  *
3732  *  Displays the PAGE SETUP dialog box, which enables the user to specify
3733  *  specific properties of a printed page such as
3734  *  size, source, orientation and the width of the page margins.
3735  *
3736  * PARAMS
3737  *  setupdlg [IO] PAGESETUPDLGA struct
3738  *
3739  * RETURNS
3740  *  TRUE    if the user pressed the OK button
3741  *  FALSE   if the user cancelled the window or an error occurred
3742  *
3743  * NOTES
3744  *    The values of hDevMode and hDevNames are filled on output and can be
3745  *    changed in PAGESETUPDLG when they are passed in PageSetupDlg.
3746  *
3747  */
3748 BOOL WINAPI PageSetupDlgA(LPPAGESETUPDLGA setupdlg)
3749 {
3750     pagesetup_data data;
3751
3752     data.unicode = FALSE;
3753     data.u.dlga  = setupdlg;
3754
3755     return pagesetup_common(&data);
3756 }
3757
3758 /***********************************************************************
3759  *            PageSetupDlgW  (COMDLG32.@)
3760  *
3761  * See PageSetupDlgA.
3762  */
3763 BOOL WINAPI PageSetupDlgW(LPPAGESETUPDLGW setupdlg)
3764 {
3765     pagesetup_data data;
3766
3767     data.unicode = TRUE;
3768     data.u.dlgw  = setupdlg;
3769
3770     return pagesetup_common(&data);
3771 }
3772
3773 /***********************************************************************
3774  * PrintDlgExA (COMDLG32.@)
3775  *
3776  * See PrintDlgExW.
3777  *
3778  * BUGS
3779  *   Only a Stub
3780  *
3781  */
3782 HRESULT WINAPI PrintDlgExA(LPPRINTDLGEXA lppd)
3783 {
3784
3785     FIXME("(%p) stub\n", lppd);
3786     if ((lppd == NULL) || (lppd->lStructSize != sizeof(PRINTDLGEXA))) {
3787         return E_INVALIDARG;
3788     }
3789
3790     if (!IsWindow(lppd->hwndOwner)) {
3791         return E_HANDLE;
3792     }
3793
3794     return E_NOTIMPL;
3795 }
3796
3797 /***********************************************************************
3798  * PrintDlgExW (COMDLG32.@)
3799  *
3800  * Display the property sheet style PRINT dialog box
3801  *  
3802  * PARAMS
3803  *  lppd  [IO] ptr to PRINTDLGEX struct
3804  * 
3805  * RETURNS
3806  *  Success: S_OK
3807  *  Failure: One of the following COM error codes:
3808  *    E_OUTOFMEMORY Insufficient memory.
3809  *    E_INVALIDARG  One or more arguments are invalid.
3810  *    E_POINTER     Invalid pointer.
3811  *    E_HANDLE      Invalid handle.
3812  *    E_FAIL        Unspecified error.
3813  *  
3814  * NOTES
3815  * This Dialog enables the user to specify specific properties of the print job.
3816  * The property sheet can also have additional application-specific and
3817  * driver-specific property pages.
3818  *
3819  * BUGS
3820  *   Not fully implemented
3821  *
3822  */
3823 HRESULT WINAPI PrintDlgExW(LPPRINTDLGEXW lppd)
3824 {
3825     DWORD     ret = E_FAIL;
3826     LPVOID    ptr;
3827
3828     FIXME("(%p) not fully implemented\n", lppd);
3829
3830     if ((lppd == NULL) || (lppd->lStructSize != sizeof(PRINTDLGEXW))) {
3831         return E_INVALIDARG;
3832     }
3833
3834     if (!IsWindow(lppd->hwndOwner)) {
3835         return E_HANDLE;
3836     }
3837
3838     if (lppd->Flags & PD_RETURNDEFAULT) {
3839         PRINTER_INFO_2W *pbuf;
3840         DRIVER_INFO_2W  *dbuf;
3841         HANDLE hprn;
3842         DWORD needed = 1024;
3843         BOOL bRet;
3844
3845         if (lppd->hDevMode || lppd->hDevNames) {
3846             WARN("hDevMode or hDevNames non-zero for PD_RETURNDEFAULT\n");
3847             COMDLG32_SetCommDlgExtendedError(PDERR_RETDEFFAILURE);
3848             return E_INVALIDARG;
3849         }
3850         if (!PRINTDLG_OpenDefaultPrinter(&hprn)) {
3851             WARN("Can't find default printer\n");
3852             COMDLG32_SetCommDlgExtendedError(PDERR_NODEFAULTPRN);
3853             return E_FAIL;
3854         }
3855
3856         pbuf = HeapAlloc(GetProcessHeap(), 0, needed);
3857         bRet = GetPrinterW(hprn, 2, (LPBYTE)pbuf, needed, &needed);
3858         if (!bRet && (GetLastError() == ERROR_INSUFFICIENT_BUFFER)) {
3859             HeapFree(GetProcessHeap(), 0, pbuf);
3860             pbuf = HeapAlloc(GetProcessHeap(), 0, needed);
3861             bRet = GetPrinterW(hprn, 2, (LPBYTE)pbuf, needed, &needed);
3862         }
3863         if (!bRet) {
3864             HeapFree(GetProcessHeap(), 0, pbuf);
3865             ClosePrinter(hprn);
3866             return E_FAIL;
3867         }
3868
3869         needed = 1024;
3870         dbuf = HeapAlloc(GetProcessHeap(), 0, needed);
3871         bRet = GetPrinterDriverW(hprn, NULL, 3, (LPBYTE)dbuf, needed, &needed);
3872         if (!bRet && (GetLastError() == ERROR_INSUFFICIENT_BUFFER)) {
3873             HeapFree(GetProcessHeap(), 0, dbuf);
3874             dbuf = HeapAlloc(GetProcessHeap(), 0, needed);
3875             bRet = GetPrinterDriverW(hprn, NULL, 3, (LPBYTE)dbuf, needed, &needed);
3876         }
3877         if (!bRet) {
3878             ERR("GetPrinterDriverW failed, last error %d, fix your config for printer %s!\n",
3879                 GetLastError(), debugstr_w(pbuf->pPrinterName));
3880             HeapFree(GetProcessHeap(), 0, dbuf);
3881             HeapFree(GetProcessHeap(), 0, pbuf);
3882             COMDLG32_SetCommDlgExtendedError(PDERR_RETDEFFAILURE);
3883             ClosePrinter(hprn);
3884             return E_FAIL;
3885         }
3886         ClosePrinter(hprn);
3887
3888         PRINTDLG_CreateDevNamesW(&(lppd->hDevNames),
3889                       dbuf->pDriverPath,
3890                       pbuf->pPrinterName,
3891                       pbuf->pPortName);
3892         lppd->hDevMode = GlobalAlloc(GMEM_MOVEABLE, pbuf->pDevMode->dmSize +
3893                          pbuf->pDevMode->dmDriverExtra);
3894         if (lppd->hDevMode) {
3895             ptr = GlobalLock(lppd->hDevMode);
3896             if (ptr) {
3897                 memcpy(ptr, pbuf->pDevMode, pbuf->pDevMode->dmSize +
3898                     pbuf->pDevMode->dmDriverExtra);
3899                 GlobalUnlock(lppd->hDevMode);
3900                 ret = S_OK;
3901             }
3902         }
3903         HeapFree(GetProcessHeap(), 0, pbuf);
3904         HeapFree(GetProcessHeap(), 0, dbuf);
3905
3906         return ret;
3907     }
3908
3909     return E_NOTIMPL;
3910 }