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