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