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