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