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