windowscodecs: Implement JpegEncoder_CreateNewFrame.
[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 to 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[256];
1787              GetDlgItemTextA(hDlg, LOWORD(wParam), PrinterName, 255);
1788              PRINTDLG_ChangePrinterA(hDlg, PrinterName, PrintStructures);
1789          }
1790          break;
1791
1792     case cmb2: /* Papersize */
1793       {
1794           DWORD Sel = SendDlgItemMessageA(hDlg, cmb2, CB_GETCURSEL, 0, 0);
1795           if(Sel != CB_ERR)
1796               lpdm->u1.s1.dmPaperSize = SendDlgItemMessageA(hDlg, cmb2,
1797                                                             CB_GETITEMDATA,
1798                                                             Sel, 0);
1799       }
1800       break;
1801
1802     case cmb3: /* Bin */
1803       {
1804           DWORD Sel = SendDlgItemMessageA(hDlg, cmb3, CB_GETCURSEL, 0, 0);
1805           if(Sel != CB_ERR)
1806               lpdm->u1.s1.dmDefaultSource = SendDlgItemMessageA(hDlg, cmb3,
1807                                                           CB_GETITEMDATA, Sel,
1808                                                           0);
1809       }
1810       break;
1811     }
1812     if(lppd->Flags & PD_PRINTSETUP) {
1813         switch (LOWORD(wParam)) {
1814         case rad1:                         /* orientation */
1815         case rad2:
1816             if (IsDlgButtonChecked(hDlg, rad1) == BST_CHECKED) {
1817                 if(lpdm->u1.s1.dmOrientation != DMORIENT_PORTRAIT) {
1818                     lpdm->u1.s1.dmOrientation = DMORIENT_PORTRAIT;
1819                     SendDlgItemMessageA(hDlg, stc10, STM_SETIMAGE, IMAGE_ICON,
1820                                         (LPARAM)PrintStructures->hPortraitIcon);
1821                     SendDlgItemMessageA(hDlg, ico1, STM_SETIMAGE, IMAGE_ICON,
1822                                         (LPARAM)PrintStructures->hPortraitIcon);
1823                 }
1824             } else {
1825                 if(lpdm->u1.s1.dmOrientation != DMORIENT_LANDSCAPE) {
1826                     lpdm->u1.s1.dmOrientation = DMORIENT_LANDSCAPE;
1827                     SendDlgItemMessageA(hDlg, stc10, STM_SETIMAGE, IMAGE_ICON,
1828                                         (LPARAM)PrintStructures->hLandscapeIcon);
1829                     SendDlgItemMessageA(hDlg, ico1, STM_SETIMAGE, IMAGE_ICON,
1830                                         (LPARAM)PrintStructures->hLandscapeIcon);
1831                 }
1832             }
1833             break;
1834         }
1835     }
1836     return FALSE;
1837 }
1838
1839 static LRESULT PRINTDLG_WMCommandW(HWND hDlg, WPARAM wParam,
1840                                    PRINT_PTRW* PrintStructures)
1841 {
1842     LPPRINTDLGW lppd = PrintStructures->lpPrintDlg;
1843     UINT PrinterComboID = (lppd->Flags & PD_PRINTSETUP) ? cmb1 : cmb4;
1844     LPDEVMODEW lpdm = PrintStructures->lpDevMode;
1845
1846     switch (LOWORD(wParam))  {
1847     case IDOK:
1848         TRACE(" OK button was hit\n");
1849         if (!PRINTDLG_UpdatePrintDlgW(hDlg, PrintStructures)) {
1850             FIXME("Update printdlg was not successful!\n");
1851             return(FALSE);
1852         }
1853         EndDialog(hDlg, TRUE);
1854         return(TRUE);
1855
1856     case IDCANCEL:
1857         TRACE(" CANCEL button was hit\n");
1858         EndDialog(hDlg, FALSE);
1859         return(FALSE);
1860
1861      case pshHelp:
1862         TRACE(" HELP button was hit\n");
1863         SendMessageW(lppd->hwndOwner, PrintStructures->HelpMessageID,
1864                                 (WPARAM) hDlg, (LPARAM) lppd);
1865         break;
1866
1867      case chx2:                         /* collate pages checkbox */
1868         if (IsDlgButtonChecked(hDlg, chx2) == BST_CHECKED)
1869             SendDlgItemMessageW(hDlg, ico3, STM_SETIMAGE, IMAGE_ICON,
1870                                     (LPARAM)PrintStructures->hCollateIcon);
1871         else
1872             SendDlgItemMessageW(hDlg, ico3, STM_SETIMAGE, IMAGE_ICON,
1873                                     (LPARAM)PrintStructures->hNoCollateIcon);
1874         break;
1875      case edt1:                         /* from page nr editbox */
1876      case edt2:                         /* to page nr editbox */
1877         if (HIWORD(wParam)==EN_CHANGE) {
1878             WORD nToPage;
1879             WORD nFromPage;
1880             nFromPage = GetDlgItemInt(hDlg, edt1, NULL, FALSE);
1881             nToPage   = GetDlgItemInt(hDlg, edt2, NULL, FALSE);
1882             if (nFromPage != lppd->nFromPage || nToPage != lppd->nToPage)
1883                 CheckRadioButton(hDlg, rad1, rad3, rad3);
1884         }
1885         break;
1886
1887     case edt3:
1888         if(HIWORD(wParam) == EN_CHANGE) {
1889             INT copies = GetDlgItemInt(hDlg, edt3, NULL, FALSE);
1890             if(copies <= 1)
1891                 EnableWindow(GetDlgItem(hDlg, chx2), FALSE);
1892             else
1893                 EnableWindow(GetDlgItem(hDlg, chx2), TRUE);
1894         }
1895         break;
1896
1897      case psh2:                       /* Properties button */
1898        {
1899          HANDLE hPrinter;
1900          WCHAR  PrinterName[256];
1901
1902          if (!GetDlgItemTextW(hDlg, PrinterComboID, PrinterName, 255)) break;
1903          if (!OpenPrinterW(PrinterName, &hPrinter, NULL)) {
1904              FIXME(" Call to OpenPrinter did not succeed!\n");
1905              break;
1906          }
1907          DocumentPropertiesW(hDlg, hPrinter, PrinterName,
1908                              PrintStructures->lpDevMode,
1909                              PrintStructures->lpDevMode,
1910                              DM_IN_BUFFER | DM_OUT_BUFFER | DM_IN_PROMPT);
1911          ClosePrinter(hPrinter);
1912          break;
1913        }
1914
1915     case rad1: /* Paperorientation */
1916         if (lppd->Flags & PD_PRINTSETUP)
1917         {
1918               lpdm->u1.s1.dmOrientation = DMORIENT_PORTRAIT;
1919               SendDlgItemMessageW(hDlg, ico1, STM_SETIMAGE, IMAGE_ICON,
1920                           (LPARAM)(PrintStructures->hPortraitIcon));
1921         }
1922         break;
1923
1924     case rad2: /* Paperorientation */
1925         if (lppd->Flags & PD_PRINTSETUP)
1926         {
1927               lpdm->u1.s1.dmOrientation = DMORIENT_LANDSCAPE;
1928               SendDlgItemMessageW(hDlg, ico1, STM_SETIMAGE, IMAGE_ICON,
1929                           (LPARAM)(PrintStructures->hLandscapeIcon));
1930         }
1931         break;
1932
1933     case cmb1: /* Printer Combobox in PRINT SETUP */
1934          /* FALLTHROUGH */
1935     case cmb4:                         /* Printer combobox */
1936          if (HIWORD(wParam)==CBN_SELCHANGE) {
1937              WCHAR   PrinterName[256];
1938              GetDlgItemTextW(hDlg, LOWORD(wParam), PrinterName, 255);
1939              PRINTDLG_ChangePrinterW(hDlg, PrinterName, PrintStructures);
1940          }
1941          break;
1942
1943     case cmb2: /* Papersize */
1944       {
1945           DWORD Sel = SendDlgItemMessageW(hDlg, cmb2, CB_GETCURSEL, 0, 0);
1946           if(Sel != CB_ERR)
1947               lpdm->u1.s1.dmPaperSize = SendDlgItemMessageW(hDlg, cmb2,
1948                                                             CB_GETITEMDATA,
1949                                                             Sel, 0);
1950       }
1951       break;
1952
1953     case cmb3: /* Bin */
1954       {
1955           DWORD Sel = SendDlgItemMessageW(hDlg, cmb3, CB_GETCURSEL, 0, 0);
1956           if(Sel != CB_ERR)
1957               lpdm->u1.s1.dmDefaultSource = SendDlgItemMessageW(hDlg, cmb3,
1958                                                           CB_GETITEMDATA, Sel,
1959                                                           0);
1960       }
1961       break;
1962     }
1963     if(lppd->Flags & PD_PRINTSETUP) {
1964         switch (LOWORD(wParam)) {
1965         case rad1:                         /* orientation */
1966         case rad2:
1967             if (IsDlgButtonChecked(hDlg, rad1) == BST_CHECKED) {
1968                 if(lpdm->u1.s1.dmOrientation != DMORIENT_PORTRAIT) {
1969                     lpdm->u1.s1.dmOrientation = DMORIENT_PORTRAIT;
1970                     SendDlgItemMessageW(hDlg, stc10, STM_SETIMAGE, IMAGE_ICON,
1971                                         (LPARAM)PrintStructures->hPortraitIcon);
1972                     SendDlgItemMessageW(hDlg, ico1, STM_SETIMAGE, IMAGE_ICON,
1973                                         (LPARAM)PrintStructures->hPortraitIcon);
1974                 }
1975             } else {
1976                 if(lpdm->u1.s1.dmOrientation != DMORIENT_LANDSCAPE) {
1977                     lpdm->u1.s1.dmOrientation = DMORIENT_LANDSCAPE;
1978                     SendDlgItemMessageW(hDlg, stc10, STM_SETIMAGE, IMAGE_ICON,
1979                                         (LPARAM)PrintStructures->hLandscapeIcon);
1980                     SendDlgItemMessageW(hDlg, ico1, STM_SETIMAGE, IMAGE_ICON,
1981                                         (LPARAM)PrintStructures->hLandscapeIcon);
1982                 }
1983             }
1984             break;
1985         }
1986     }
1987     return FALSE;
1988 }
1989
1990 /***********************************************************************
1991  *           PrintDlgProcA                      [internal]
1992  */
1993 static INT_PTR CALLBACK PrintDlgProcA(HWND hDlg, UINT uMsg, WPARAM wParam,
1994                                       LPARAM lParam)
1995 {
1996     PRINT_PTRA* PrintStructures;
1997     INT_PTR res = FALSE;
1998
1999     if (uMsg!=WM_INITDIALOG) {
2000         PrintStructures = GetPropW(hDlg, printdlg_prop);
2001         if (!PrintStructures)
2002             return FALSE;
2003     } else {
2004         PrintStructures = (PRINT_PTRA*) lParam;
2005         SetPropW(hDlg, printdlg_prop, PrintStructures);
2006         if(!check_printer_setup(hDlg))
2007         {
2008             EndDialog(hDlg,FALSE);
2009             return FALSE;
2010         }
2011         res = PRINTDLG_WMInitDialog(hDlg, PrintStructures);
2012
2013         if(PrintStructures->lpPrintDlg->Flags & PD_ENABLEPRINTHOOK)
2014             res = PrintStructures->lpPrintDlg->lpfnPrintHook(
2015                 hDlg, uMsg, wParam, (LPARAM)PrintStructures->lpPrintDlg
2016             );
2017         return res;
2018     }
2019
2020     if(PrintStructures->lpPrintDlg->Flags & PD_ENABLEPRINTHOOK) {
2021         res = PrintStructures->lpPrintDlg->lpfnPrintHook(hDlg,uMsg,wParam,
2022                                                          lParam);
2023         if(res) return res;
2024     }
2025
2026     switch (uMsg) {
2027     case WM_COMMAND:
2028         return PRINTDLG_WMCommandA(hDlg, wParam, PrintStructures);
2029
2030     case WM_DESTROY:
2031         DestroyIcon(PrintStructures->hCollateIcon);
2032         DestroyIcon(PrintStructures->hNoCollateIcon);
2033         DestroyIcon(PrintStructures->hPortraitIcon);
2034         DestroyIcon(PrintStructures->hLandscapeIcon);
2035         if(PrintStructures->hwndUpDown)
2036             DestroyWindow(PrintStructures->hwndUpDown);
2037         return FALSE;
2038     }
2039     return res;
2040 }
2041
2042 static INT_PTR CALLBACK PrintDlgProcW(HWND hDlg, UINT uMsg, WPARAM wParam,
2043                                       LPARAM lParam)
2044 {
2045     PRINT_PTRW* PrintStructures;
2046     INT_PTR res = FALSE;
2047
2048     if (uMsg!=WM_INITDIALOG) {
2049         PrintStructures = GetPropW(hDlg, printdlg_prop);
2050         if (!PrintStructures)
2051             return FALSE;
2052     } else {
2053         PrintStructures = (PRINT_PTRW*) lParam;
2054         SetPropW(hDlg, printdlg_prop, PrintStructures);
2055         if(!check_printer_setup(hDlg))
2056         {
2057             EndDialog(hDlg,FALSE);
2058             return FALSE;
2059         }
2060         res = PRINTDLG_WMInitDialogW(hDlg, PrintStructures);
2061
2062         if(PrintStructures->lpPrintDlg->Flags & PD_ENABLEPRINTHOOK)
2063             res = PrintStructures->lpPrintDlg->lpfnPrintHook(hDlg, uMsg, wParam, (LPARAM)PrintStructures->lpPrintDlg);
2064         return res;
2065     }
2066
2067     if(PrintStructures->lpPrintDlg->Flags & PD_ENABLEPRINTHOOK) {
2068         res = PrintStructures->lpPrintDlg->lpfnPrintHook(hDlg,uMsg,wParam, lParam);
2069         if(res) return res;
2070     }
2071
2072     switch (uMsg) {
2073     case WM_COMMAND:
2074         return PRINTDLG_WMCommandW(hDlg, wParam, PrintStructures);
2075
2076     case WM_DESTROY:
2077         DestroyIcon(PrintStructures->hCollateIcon);
2078         DestroyIcon(PrintStructures->hNoCollateIcon);
2079         DestroyIcon(PrintStructures->hPortraitIcon);
2080         DestroyIcon(PrintStructures->hLandscapeIcon);
2081         if(PrintStructures->hwndUpDown)
2082             DestroyWindow(PrintStructures->hwndUpDown);
2083         return FALSE;
2084     }
2085     return res;
2086 }
2087
2088 /************************************************************
2089  *
2090  *      PRINTDLG_GetDlgTemplate
2091  *
2092  */
2093 static HGLOBAL PRINTDLG_GetDlgTemplateA(const PRINTDLGA *lppd)
2094 {
2095     HRSRC hResInfo;
2096     HGLOBAL hDlgTmpl;
2097
2098     if (lppd->Flags & PD_PRINTSETUP) {
2099         if(lppd->Flags & PD_ENABLESETUPTEMPLATEHANDLE) {
2100             hDlgTmpl = lppd->hSetupTemplate;
2101         } else if(lppd->Flags & PD_ENABLESETUPTEMPLATE) {
2102             hResInfo = FindResourceA(lppd->hInstance,
2103                                      lppd->lpSetupTemplateName, (LPSTR)RT_DIALOG);
2104             hDlgTmpl = LoadResource(lppd->hInstance, hResInfo);
2105         } else {
2106             hResInfo = FindResourceA(COMDLG32_hInstance, "PRINT32_SETUP",
2107                                      (LPSTR)RT_DIALOG);
2108             hDlgTmpl = LoadResource(COMDLG32_hInstance, hResInfo);
2109         }
2110     } else {
2111         if(lppd->Flags & PD_ENABLEPRINTTEMPLATEHANDLE) {
2112             hDlgTmpl = lppd->hPrintTemplate;
2113         } else if(lppd->Flags & PD_ENABLEPRINTTEMPLATE) {
2114             hResInfo = FindResourceA(lppd->hInstance,
2115                                      lppd->lpPrintTemplateName,
2116                                      (LPSTR)RT_DIALOG);
2117             hDlgTmpl = LoadResource(lppd->hInstance, hResInfo);
2118         } else {
2119             hResInfo = FindResourceA(COMDLG32_hInstance, "PRINT32",
2120                                      (LPSTR)RT_DIALOG);
2121             hDlgTmpl = LoadResource(COMDLG32_hInstance, hResInfo);
2122         }
2123     }
2124     return hDlgTmpl;
2125 }
2126
2127 static HGLOBAL PRINTDLG_GetDlgTemplateW(const PRINTDLGW *lppd)
2128 {
2129     HRSRC hResInfo;
2130     HGLOBAL hDlgTmpl;
2131     static const WCHAR xpsetup[] = { 'P','R','I','N','T','3','2','_','S','E','T','U','P',0};
2132     static const WCHAR xprint[] = { 'P','R','I','N','T','3','2',0};
2133
2134     if (lppd->Flags & PD_PRINTSETUP) {
2135         if(lppd->Flags & PD_ENABLESETUPTEMPLATEHANDLE) {
2136             hDlgTmpl = lppd->hSetupTemplate;
2137         } else if(lppd->Flags & PD_ENABLESETUPTEMPLATE) {
2138             hResInfo = FindResourceW(lppd->hInstance,
2139                                      lppd->lpSetupTemplateName, (LPWSTR)RT_DIALOG);
2140             hDlgTmpl = LoadResource(lppd->hInstance, hResInfo);
2141         } else {
2142             hResInfo = FindResourceW(COMDLG32_hInstance, xpsetup, (LPWSTR)RT_DIALOG);
2143             hDlgTmpl = LoadResource(COMDLG32_hInstance, hResInfo);
2144         }
2145     } else {
2146         if(lppd->Flags & PD_ENABLEPRINTTEMPLATEHANDLE) {
2147             hDlgTmpl = lppd->hPrintTemplate;
2148         } else if(lppd->Flags & PD_ENABLEPRINTTEMPLATE) {
2149             hResInfo = FindResourceW(lppd->hInstance,
2150                                      lppd->lpPrintTemplateName,
2151                                      (LPWSTR)RT_DIALOG);
2152             hDlgTmpl = LoadResource(lppd->hInstance, hResInfo);
2153         } else {
2154             hResInfo = FindResourceW(COMDLG32_hInstance, xprint, (LPWSTR)RT_DIALOG);
2155             hDlgTmpl = LoadResource(COMDLG32_hInstance, hResInfo);
2156         }
2157     }
2158     return hDlgTmpl;
2159 }
2160
2161 /***********************************************************************
2162  *
2163  *      PRINTDLG_CreateDC
2164  *
2165  */
2166 static BOOL PRINTDLG_CreateDCA(LPPRINTDLGA lppd)
2167 {
2168     DEVNAMES *pdn = GlobalLock(lppd->hDevNames);
2169     DEVMODEA *pdm = GlobalLock(lppd->hDevMode);
2170
2171     if(lppd->Flags & PD_RETURNDC) {
2172         lppd->hDC = CreateDCA((char*)pdn + pdn->wDriverOffset,
2173                               (char*)pdn + pdn->wDeviceOffset,
2174                               (char*)pdn + pdn->wOutputOffset,
2175                               pdm );
2176     } else if(lppd->Flags & PD_RETURNIC) {
2177         lppd->hDC = CreateICA((char*)pdn + pdn->wDriverOffset,
2178                               (char*)pdn + pdn->wDeviceOffset,
2179                               (char*)pdn + pdn->wOutputOffset,
2180                               pdm );
2181     }
2182     GlobalUnlock(lppd->hDevNames);
2183     GlobalUnlock(lppd->hDevMode);
2184     return lppd->hDC ? TRUE : FALSE;
2185 }
2186
2187 static BOOL PRINTDLG_CreateDCW(LPPRINTDLGW lppd)
2188 {
2189     DEVNAMES *pdn = GlobalLock(lppd->hDevNames);
2190     DEVMODEW *pdm = GlobalLock(lppd->hDevMode);
2191
2192     if(lppd->Flags & PD_RETURNDC) {
2193         lppd->hDC = CreateDCW((WCHAR*)pdn + pdn->wDriverOffset,
2194                               (WCHAR*)pdn + pdn->wDeviceOffset,
2195                               (WCHAR*)pdn + pdn->wOutputOffset,
2196                               pdm );
2197     } else if(lppd->Flags & PD_RETURNIC) {
2198         lppd->hDC = CreateICW((WCHAR*)pdn + pdn->wDriverOffset,
2199                               (WCHAR*)pdn + pdn->wDeviceOffset,
2200                               (WCHAR*)pdn + pdn->wOutputOffset,
2201                               pdm );
2202     }
2203     GlobalUnlock(lppd->hDevNames);
2204     GlobalUnlock(lppd->hDevMode);
2205     return lppd->hDC ? TRUE : FALSE;
2206 }
2207
2208 /***********************************************************************
2209  *           PrintDlgA   (COMDLG32.@)
2210  *
2211  *  Displays the PRINT dialog box, which enables the user to specify
2212  *  specific properties of the print job.
2213  *  
2214  * PARAMS
2215  *  lppd  [IO] ptr to PRINTDLG32 struct
2216  * 
2217  * RETURNS
2218  *  nonzero if the user pressed the OK button
2219  *  zero    if the user cancelled the window or an error occurred
2220  *  
2221  * BUGS
2222  *  PrintDlg:
2223  *  * The Collate Icons do not display, even though they are in the code.
2224  *  * The Properties Button(s) should call DocumentPropertiesA().
2225  */
2226
2227 BOOL WINAPI PrintDlgA(LPPRINTDLGA lppd)
2228 {
2229     BOOL      bRet = FALSE;
2230     LPVOID    ptr;
2231     HINSTANCE hInst;
2232
2233     if (!lppd)
2234     {
2235         COMDLG32_SetCommDlgExtendedError(CDERR_INITIALIZATION);
2236         return FALSE;
2237     }
2238
2239     if(TRACE_ON(commdlg)) {
2240         char flagstr[1000] = "";
2241         const struct pd_flags *pflag = pd_flags;
2242         for( ; pflag->name; pflag++) {
2243             if(lppd->Flags & pflag->flag)
2244                 strcat(flagstr, pflag->name);
2245         }
2246         TRACE("(%p): hwndOwner = %p, hDevMode = %p, hDevNames = %p\n"
2247               "pp. %d-%d, min p %d, max p %d, copies %d, hinst %p\n"
2248               "flags %08x (%s)\n",
2249               lppd, lppd->hwndOwner, lppd->hDevMode, lppd->hDevNames,
2250               lppd->nFromPage, lppd->nToPage, lppd->nMinPage, lppd->nMaxPage,
2251               lppd->nCopies, lppd->hInstance, lppd->Flags, flagstr);
2252     }
2253
2254     if(lppd->lStructSize != sizeof(PRINTDLGA)) {
2255         WARN("structure size failure !!!\n");
2256         COMDLG32_SetCommDlgExtendedError(CDERR_STRUCTSIZE);
2257         return FALSE;
2258     }
2259
2260     if(lppd->Flags & PD_RETURNDEFAULT) {
2261         PRINTER_INFO_2A *pbuf;
2262         DRIVER_INFO_3A  *dbuf;
2263         HANDLE hprn;
2264         DWORD needed;
2265
2266         if(lppd->hDevMode || lppd->hDevNames) {
2267             WARN("hDevMode or hDevNames non-zero for PD_RETURNDEFAULT\n");
2268             COMDLG32_SetCommDlgExtendedError(PDERR_RETDEFFAILURE);
2269             return FALSE;
2270         }
2271         if(!PRINTDLG_OpenDefaultPrinter(&hprn)) {
2272             WARN("Can't find default printer\n");
2273             COMDLG32_SetCommDlgExtendedError(PDERR_NODEFAULTPRN);
2274             return FALSE;
2275         }
2276
2277         GetPrinterA(hprn, 2, NULL, 0, &needed);
2278         pbuf = HeapAlloc(GetProcessHeap(), 0, needed);
2279         GetPrinterA(hprn, 2, (LPBYTE)pbuf, needed, &needed);
2280
2281         GetPrinterDriverA(hprn, NULL, 3, NULL, 0, &needed);
2282         dbuf = HeapAlloc(GetProcessHeap(),0,needed);
2283         if (!GetPrinterDriverA(hprn, NULL, 3, (LPBYTE)dbuf, needed, &needed)) {
2284             ERR("GetPrinterDriverA failed, le %d, fix your config for printer %s!\n",
2285                 GetLastError(),pbuf->pPrinterName);
2286             HeapFree(GetProcessHeap(), 0, dbuf);
2287             HeapFree(GetProcessHeap(), 0, pbuf);
2288             COMDLG32_SetCommDlgExtendedError(PDERR_RETDEFFAILURE);
2289             return FALSE;
2290         }
2291         ClosePrinter(hprn);
2292
2293         PRINTDLG_CreateDevNames(&(lppd->hDevNames),
2294                                   dbuf->pDriverPath,
2295                                   pbuf->pPrinterName,
2296                                   pbuf->pPortName);
2297         lppd->hDevMode = GlobalAlloc(GMEM_MOVEABLE, pbuf->pDevMode->dmSize +
2298                                      pbuf->pDevMode->dmDriverExtra);
2299         ptr = GlobalLock(lppd->hDevMode);
2300         memcpy(ptr, pbuf->pDevMode, pbuf->pDevMode->dmSize +
2301                pbuf->pDevMode->dmDriverExtra);
2302         GlobalUnlock(lppd->hDevMode);
2303         HeapFree(GetProcessHeap(), 0, pbuf);
2304         HeapFree(GetProcessHeap(), 0, dbuf);
2305         bRet = TRUE;
2306     } else {
2307         HGLOBAL hDlgTmpl;
2308         PRINT_PTRA *PrintStructures;
2309
2310     /* load Dialog resources,
2311      * depending on Flags indicates Print32 or Print32_setup dialog
2312      */
2313         hDlgTmpl = PRINTDLG_GetDlgTemplateA(lppd);
2314         if (!hDlgTmpl) {
2315             COMDLG32_SetCommDlgExtendedError(CDERR_LOADRESFAILURE);
2316             return FALSE;
2317         }
2318         ptr = LockResource( hDlgTmpl );
2319         if (!ptr) {
2320             COMDLG32_SetCommDlgExtendedError(CDERR_LOADRESFAILURE);
2321             return FALSE;
2322         }
2323
2324         PrintStructures = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY,
2325                                     sizeof(PRINT_PTRA));
2326         PrintStructures->lpPrintDlg = lppd;
2327
2328         /* and create & process the dialog .
2329          * -1 is failure, 0 is broken hwnd, everything else is ok.
2330          */
2331         hInst = COMDLG32_hInstance;
2332         if (lppd->Flags & (PD_ENABLESETUPTEMPLATE | PD_ENABLEPRINTTEMPLATE)) hInst = lppd->hInstance;
2333         bRet = (0<DialogBoxIndirectParamA(hInst, ptr, lppd->hwndOwner,
2334                                            PrintDlgProcA,
2335                                            (LPARAM)PrintStructures));
2336
2337         if(bRet) {
2338             DEVMODEA *lpdm = PrintStructures->lpDevMode, *lpdmReturn;
2339             PRINTER_INFO_2A *pi = PrintStructures->lpPrinterInfo;
2340             DRIVER_INFO_3A *di = PrintStructures->lpDriverInfo;
2341
2342             if (lppd->hDevMode == 0) {
2343                 TRACE(" No hDevMode yet... Need to create my own\n");
2344                 lppd->hDevMode = GlobalAlloc(GMEM_MOVEABLE,
2345                                         lpdm->dmSize + lpdm->dmDriverExtra);
2346             } else {
2347                 lppd->hDevMode = GlobalReAlloc(lppd->hDevMode,
2348                                                lpdm->dmSize + lpdm->dmDriverExtra,
2349                                                GMEM_MOVEABLE);
2350             }
2351             lpdmReturn = GlobalLock(lppd->hDevMode);
2352             memcpy(lpdmReturn, lpdm, lpdm->dmSize + lpdm->dmDriverExtra);
2353
2354             PRINTDLG_CreateDevNames(&(lppd->hDevNames),
2355                     di->pDriverPath,
2356                     pi->pPrinterName,
2357                     pi->pPortName
2358             );
2359             GlobalUnlock(lppd->hDevMode);
2360         }
2361         HeapFree(GetProcessHeap(), 0, PrintStructures->lpDevMode);
2362         HeapFree(GetProcessHeap(), 0, PrintStructures->lpPrinterInfo);
2363         HeapFree(GetProcessHeap(), 0, PrintStructures->lpDriverInfo);
2364         HeapFree(GetProcessHeap(), 0, PrintStructures);
2365     }
2366     if(bRet && (lppd->Flags & PD_RETURNDC || lppd->Flags & PD_RETURNIC))
2367         bRet = PRINTDLG_CreateDCA(lppd);
2368
2369     TRACE("exit! (%d)\n", bRet);
2370     return bRet;
2371 }
2372
2373 /***********************************************************************
2374  *           PrintDlgW   (COMDLG32.@)
2375  *
2376  * See PrintDlgA.
2377  */
2378 BOOL WINAPI PrintDlgW(LPPRINTDLGW lppd)
2379 {
2380     BOOL      bRet = FALSE;
2381     LPVOID    ptr;
2382     HINSTANCE hInst;
2383
2384     if (!lppd)
2385     {
2386         COMDLG32_SetCommDlgExtendedError(CDERR_INITIALIZATION);
2387         return FALSE;
2388     }
2389
2390     if(TRACE_ON(commdlg)) {
2391         char flagstr[1000] = "";
2392         const struct pd_flags *pflag = pd_flags;
2393         for( ; pflag->name; pflag++) {
2394             if(lppd->Flags & pflag->flag)
2395                 strcat(flagstr, pflag->name);
2396         }
2397         TRACE("(%p): hwndOwner = %p, hDevMode = %p, hDevNames = %p\n"
2398               "pp. %d-%d, min p %d, max p %d, copies %d, hinst %p\n"
2399               "flags %08x (%s)\n",
2400               lppd, lppd->hwndOwner, lppd->hDevMode, lppd->hDevNames,
2401               lppd->nFromPage, lppd->nToPage, lppd->nMinPage, lppd->nMaxPage,
2402               lppd->nCopies, lppd->hInstance, lppd->Flags, flagstr);
2403     }
2404
2405     if(lppd->lStructSize != sizeof(PRINTDLGW)) {
2406         WARN("structure size failure !!!\n");
2407         COMDLG32_SetCommDlgExtendedError(CDERR_STRUCTSIZE);
2408         return FALSE;
2409     }
2410
2411     if(lppd->Flags & PD_RETURNDEFAULT) {
2412         PRINTER_INFO_2W *pbuf;
2413         DRIVER_INFO_3W  *dbuf;
2414         HANDLE hprn;
2415         DWORD needed;
2416
2417         if(lppd->hDevMode || lppd->hDevNames) {
2418             WARN("hDevMode or hDevNames non-zero for PD_RETURNDEFAULT\n");
2419             COMDLG32_SetCommDlgExtendedError(PDERR_RETDEFFAILURE);
2420             return FALSE;
2421         }
2422         if(!PRINTDLG_OpenDefaultPrinter(&hprn)) {
2423             WARN("Can't find default printer\n");
2424             COMDLG32_SetCommDlgExtendedError(PDERR_NODEFAULTPRN);
2425             return FALSE;
2426         }
2427
2428         GetPrinterW(hprn, 2, NULL, 0, &needed);
2429         pbuf = HeapAlloc(GetProcessHeap(), 0, needed);
2430         GetPrinterW(hprn, 2, (LPBYTE)pbuf, needed, &needed);
2431
2432         GetPrinterDriverW(hprn, NULL, 3, NULL, 0, &needed);
2433         dbuf = HeapAlloc(GetProcessHeap(),0,needed);
2434         if (!GetPrinterDriverW(hprn, NULL, 3, (LPBYTE)dbuf, needed, &needed)) {
2435             ERR("GetPrinterDriverA failed, le %d, fix your config for printer %s!\n",
2436                 GetLastError(),debugstr_w(pbuf->pPrinterName));
2437             HeapFree(GetProcessHeap(), 0, dbuf);
2438             HeapFree(GetProcessHeap(), 0, pbuf);
2439             COMDLG32_SetCommDlgExtendedError(PDERR_RETDEFFAILURE);
2440             return FALSE;
2441         }
2442         ClosePrinter(hprn);
2443
2444         PRINTDLG_CreateDevNamesW(&(lppd->hDevNames),
2445                                   dbuf->pDriverPath,
2446                                   pbuf->pPrinterName,
2447                                   pbuf->pPortName);
2448         lppd->hDevMode = GlobalAlloc(GMEM_MOVEABLE, pbuf->pDevMode->dmSize +
2449                                      pbuf->pDevMode->dmDriverExtra);
2450         ptr = GlobalLock(lppd->hDevMode);
2451         memcpy(ptr, pbuf->pDevMode, pbuf->pDevMode->dmSize +
2452                pbuf->pDevMode->dmDriverExtra);
2453         GlobalUnlock(lppd->hDevMode);
2454         HeapFree(GetProcessHeap(), 0, pbuf);
2455         HeapFree(GetProcessHeap(), 0, dbuf);
2456         bRet = TRUE;
2457     } else {
2458         HGLOBAL hDlgTmpl;
2459         PRINT_PTRW *PrintStructures;
2460
2461     /* load Dialog resources,
2462      * depending on Flags indicates Print32 or Print32_setup dialog
2463      */
2464         hDlgTmpl = PRINTDLG_GetDlgTemplateW(lppd);
2465         if (!hDlgTmpl) {
2466             COMDLG32_SetCommDlgExtendedError(CDERR_LOADRESFAILURE);
2467             return FALSE;
2468         }
2469         ptr = LockResource( hDlgTmpl );
2470         if (!ptr) {
2471             COMDLG32_SetCommDlgExtendedError(CDERR_LOADRESFAILURE);
2472             return FALSE;
2473         }
2474
2475         PrintStructures = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY,
2476                                     sizeof(PRINT_PTRW));
2477         PrintStructures->lpPrintDlg = lppd;
2478
2479         /* and create & process the dialog .
2480          * -1 is failure, 0 is broken hwnd, everything else is ok.
2481          */
2482         hInst = COMDLG32_hInstance;
2483         if (lppd->Flags & (PD_ENABLESETUPTEMPLATE | PD_ENABLEPRINTTEMPLATE)) hInst = lppd->hInstance;
2484         bRet = (0<DialogBoxIndirectParamW(hInst, ptr, lppd->hwndOwner,
2485                                            PrintDlgProcW,
2486                                            (LPARAM)PrintStructures));
2487
2488         if(bRet) {
2489             DEVMODEW *lpdm = PrintStructures->lpDevMode, *lpdmReturn;
2490             PRINTER_INFO_2W *pi = PrintStructures->lpPrinterInfo;
2491             DRIVER_INFO_3W *di = PrintStructures->lpDriverInfo;
2492
2493             if (lppd->hDevMode == 0) {
2494                 TRACE(" No hDevMode yet... Need to create my own\n");
2495                 lppd->hDevMode = GlobalAlloc(GMEM_MOVEABLE,
2496                                         lpdm->dmSize + lpdm->dmDriverExtra);
2497             } else {
2498                 WORD locks;
2499                 if((locks = (GlobalFlags(lppd->hDevMode) & GMEM_LOCKCOUNT))) {
2500                     WARN("hDevMode has %d locks on it. Unlocking it now\n", locks);
2501                     while(locks--) {
2502                         GlobalUnlock(lppd->hDevMode);
2503                         TRACE("Now got %d locks\n", locks);
2504                     }
2505                 }
2506                 lppd->hDevMode = GlobalReAlloc(lppd->hDevMode,
2507                                                lpdm->dmSize + lpdm->dmDriverExtra,
2508                                                GMEM_MOVEABLE);
2509             }
2510             lpdmReturn = GlobalLock(lppd->hDevMode);
2511             memcpy(lpdmReturn, lpdm, lpdm->dmSize + lpdm->dmDriverExtra);
2512
2513             if (lppd->hDevNames != 0) {
2514                 WORD locks;
2515                 if((locks = (GlobalFlags(lppd->hDevNames) & GMEM_LOCKCOUNT))) {
2516                     WARN("hDevNames has %d locks on it. Unlocking it now\n", locks);
2517                     while(locks--)
2518                         GlobalUnlock(lppd->hDevNames);
2519                 }
2520             }
2521             PRINTDLG_CreateDevNamesW(&(lppd->hDevNames),
2522                     di->pDriverPath,
2523                     pi->pPrinterName,
2524                     pi->pPortName
2525             );
2526             GlobalUnlock(lppd->hDevMode);
2527         }
2528         HeapFree(GetProcessHeap(), 0, PrintStructures->lpDevMode);
2529         HeapFree(GetProcessHeap(), 0, PrintStructures->lpPrinterInfo);
2530         HeapFree(GetProcessHeap(), 0, PrintStructures->lpDriverInfo);
2531         HeapFree(GetProcessHeap(), 0, PrintStructures);
2532     }
2533     if(bRet && (lppd->Flags & PD_RETURNDC || lppd->Flags & PD_RETURNIC))
2534         bRet = PRINTDLG_CreateDCW(lppd);
2535
2536     TRACE("exit! (%d)\n", bRet);
2537     return bRet;
2538 }
2539
2540 /***********************************************************************
2541  *
2542  *          PageSetupDlg
2543  * rad1 - portrait
2544  * rad2 - landscape
2545  * cmb1 - printer select (not in standard dialog template)
2546  * cmb2 - paper size
2547  * cmb3 - source (tray?)
2548  * edt4 - border left
2549  * edt5 - border top
2550  * edt6 - border right
2551  * edt7 - border bottom
2552  * psh3 - "Printer..."
2553  */
2554
2555 typedef struct
2556 {
2557     BOOL unicode;
2558     union
2559     {
2560         LPPAGESETUPDLGA dlga;
2561         LPPAGESETUPDLGW dlgw;
2562     } u;
2563     HWND hDlg;                /* Page Setup dialog handle */
2564     RECT rtDrawRect;          /* Drawing rect for page */
2565 } pagesetup_data;
2566
2567 static inline DWORD pagesetup_get_flags(const pagesetup_data *data)
2568 {
2569     return data->u.dlgw->Flags;
2570 }
2571
2572 static inline BOOL is_metric(const pagesetup_data *data)
2573 {
2574     return pagesetup_get_flags(data) & PSD_INHUNDREDTHSOFMILLIMETERS;
2575 }
2576
2577 static inline LONG tenths_mm_to_size(const pagesetup_data *data, LONG size)
2578 {
2579     if (is_metric(data))
2580         return 10 * size;
2581     else
2582         return 10 * size * 100 / 254;
2583 }
2584
2585 static inline LONG thousandths_inch_to_size(const pagesetup_data *data, LONG size)
2586 {
2587     if (is_metric(data))
2588         return size * 254 / 100;
2589     else
2590         return size;
2591 }
2592
2593 static WCHAR get_decimal_sep(void)
2594 {
2595     static WCHAR sep;
2596
2597     if(!sep)
2598     {
2599         WCHAR buf[] = {'.', 0};
2600         GetLocaleInfoW(LOCALE_USER_DEFAULT, LOCALE_SDECIMAL, buf, sizeof(buf) / sizeof(buf[0]));
2601         sep = buf[0];
2602     }
2603     return sep;
2604 }
2605
2606 static void size2str(const pagesetup_data *data, DWORD size, LPWSTR strout)
2607 {
2608     WCHAR integer_fmt[] = {'%','d',0};
2609     WCHAR hundredths_fmt[] = {'%','d','%','c','%','0','2','d',0};
2610     WCHAR thousandths_fmt[] = {'%','d','%','c','%','0','3','d',0};
2611
2612     /* FIXME use LOCALE_SDECIMAL when the edit parsing code can cope */
2613
2614     if (is_metric(data))
2615     {
2616         if(size % 100)
2617             wsprintfW(strout, hundredths_fmt, size / 100, get_decimal_sep(), size % 100);
2618         else
2619             wsprintfW(strout, integer_fmt, size / 100);
2620     }
2621     else
2622     {
2623         if(size % 1000)
2624             wsprintfW(strout, thousandths_fmt, size / 1000, get_decimal_sep(), size % 1000);
2625         else
2626             wsprintfW(strout, integer_fmt, size / 1000);
2627
2628     }
2629 }
2630
2631 static inline BOOL is_default_metric(void)
2632 {
2633     DWORD system;
2634     GetLocaleInfoW(LOCALE_USER_DEFAULT, LOCALE_IMEASURE | LOCALE_RETURN_NUMBER,
2635                    (LPWSTR)&system, sizeof(system));
2636     return system == 0;
2637 }
2638
2639 /**********************************************
2640  *           rotate_rect
2641  * Cyclically permute the four members of rc
2642  * If sense is TRUE l -> t -> r -> b
2643  * otherwise        l <- t <- r <- b
2644  */
2645 static inline void rotate_rect(RECT *rc, BOOL sense)
2646 {
2647     INT tmp;
2648     if(sense)
2649     {
2650         tmp        = rc->bottom;
2651         rc->bottom = rc->right;
2652         rc->right  = rc->top;
2653         rc->top    = rc->left;
2654         rc->left   = tmp;
2655     }
2656     else
2657     {
2658         tmp        = rc->left;
2659         rc->left   = rc->top;
2660         rc->top    = rc->right;
2661         rc->right  = rc->bottom;
2662         rc->bottom = tmp;
2663     }
2664 }
2665
2666 static void pagesetup_set_orientation(pagesetup_data *data, WORD orient)
2667 {
2668     DEVMODEW *dm = GlobalLock(data->u.dlgw->hDevMode);
2669
2670     assert(orient == DMORIENT_PORTRAIT || orient == DMORIENT_LANDSCAPE);
2671
2672     if(data->unicode)
2673         dm->u1.s1.dmOrientation = orient;
2674     else
2675     {
2676         DEVMODEA *dmA = (DEVMODEA *)dm;
2677         dmA->u1.s1.dmOrientation = orient;
2678     }
2679     GlobalUnlock(data->u.dlgw->hDevMode);
2680 }
2681
2682 static WORD pagesetup_get_orientation(const pagesetup_data *data)
2683 {
2684     DEVMODEW *dm = GlobalLock(data->u.dlgw->hDevMode);
2685     WORD orient;
2686
2687     if(data->unicode)
2688         orient = dm->u1.s1.dmOrientation;
2689     else
2690     {
2691         DEVMODEA *dmA = (DEVMODEA *)dm;
2692         orient = dmA->u1.s1.dmOrientation;
2693     }
2694     GlobalUnlock(data->u.dlgw->hDevMode);
2695     return orient;
2696 }
2697
2698 static void pagesetup_set_papersize(pagesetup_data *data, WORD paper)
2699 {
2700     DEVMODEW *dm = GlobalLock(data->u.dlgw->hDevMode);
2701
2702     if(data->unicode)
2703         dm->u1.s1.dmPaperSize = paper;
2704     else
2705     {
2706         DEVMODEA *dmA = (DEVMODEA *)dm;
2707         dmA->u1.s1.dmPaperSize = paper;
2708     }
2709     GlobalUnlock(data->u.dlgw->hDevMode);
2710 }
2711
2712 static WORD pagesetup_get_papersize(const pagesetup_data *data)
2713 {
2714     DEVMODEW *dm = GlobalLock(data->u.dlgw->hDevMode);
2715     WORD paper;
2716
2717     if(data->unicode)
2718         paper = dm->u1.s1.dmPaperSize;
2719     else
2720     {
2721         DEVMODEA *dmA = (DEVMODEA *)dm;
2722         paper = dmA->u1.s1.dmPaperSize;
2723     }
2724     GlobalUnlock(data->u.dlgw->hDevMode);
2725     return paper;
2726 }
2727
2728 static void pagesetup_set_defaultsource(pagesetup_data *data, WORD source)
2729 {
2730     DEVMODEW *dm = GlobalLock(data->u.dlgw->hDevMode);
2731
2732     if(data->unicode)
2733         dm->u1.s1.dmDefaultSource = source;
2734     else
2735     {
2736         DEVMODEA *dmA = (DEVMODEA *)dm;
2737         dmA->u1.s1.dmDefaultSource = source;
2738     }
2739     GlobalUnlock(data->u.dlgw->hDevMode);
2740 }
2741
2742 typedef enum
2743 {
2744     devnames_driver_name,
2745     devnames_device_name,
2746     devnames_output_name
2747 } devnames_name;
2748
2749
2750 static inline WORD get_devname_offset(const DEVNAMES *dn, devnames_name which)
2751 {
2752     switch(which)
2753     {
2754     case devnames_driver_name: return dn->wDriverOffset;
2755     case devnames_device_name: return dn->wDeviceOffset;
2756     case devnames_output_name: return dn->wOutputOffset;
2757     }
2758     ERR("Shouldn't be here\n");
2759     return 0;
2760 }
2761
2762 static WCHAR *pagesetup_get_a_devname(const pagesetup_data *data, devnames_name which)
2763 {
2764     DEVNAMES *dn;
2765     WCHAR *name;
2766
2767     dn = GlobalLock(data->u.dlgw->hDevNames);
2768     if(data->unicode)
2769         name = strdupW((WCHAR *)dn + get_devname_offset(dn, which));
2770     else
2771     {
2772         int len = MultiByteToWideChar(CP_ACP, 0, (char*)dn + get_devname_offset(dn, which), -1, NULL, 0);
2773         name = HeapAlloc(GetProcessHeap(), 0, len * sizeof(WCHAR));
2774         MultiByteToWideChar(CP_ACP, 0, (char*)dn + get_devname_offset(dn, which), -1, name, len);
2775     }
2776     GlobalUnlock(data->u.dlgw->hDevNames);
2777     return name;
2778 }
2779
2780 static WCHAR *pagesetup_get_drvname(const pagesetup_data *data)
2781 {
2782     return pagesetup_get_a_devname(data, devnames_driver_name);
2783 }
2784
2785 static WCHAR *pagesetup_get_devname(const pagesetup_data *data)
2786 {
2787     return pagesetup_get_a_devname(data, devnames_device_name);
2788 }
2789
2790 static WCHAR *pagesetup_get_portname(const pagesetup_data *data)
2791 {
2792     return pagesetup_get_a_devname(data, devnames_output_name);
2793 }
2794
2795 static void pagesetup_release_a_devname(const pagesetup_data *data, WCHAR *name)
2796 {
2797     HeapFree(GetProcessHeap(), 0, name);
2798 }
2799
2800 static void pagesetup_set_devnames(pagesetup_data *data, LPCWSTR drv, LPCWSTR devname, LPCWSTR port)
2801 {
2802     DEVNAMES *dn;
2803     WCHAR def[256];
2804     DWORD len = sizeof(DEVNAMES), drv_len, dev_len, port_len;
2805
2806     if(data->unicode)
2807     {
2808         drv_len  = (strlenW(drv) + 1) * sizeof(WCHAR);
2809         dev_len  = (strlenW(devname) + 1) * sizeof(WCHAR);
2810         port_len = (strlenW(port) + 1) * sizeof(WCHAR);
2811     }
2812     else
2813     {
2814         drv_len = WideCharToMultiByte(CP_ACP, 0, drv, -1, NULL, 0, NULL, NULL);
2815         dev_len = WideCharToMultiByte(CP_ACP, 0, devname, -1, NULL, 0, NULL, NULL);
2816         port_len = WideCharToMultiByte(CP_ACP, 0, port, -1, NULL, 0, NULL, NULL);
2817     }
2818     len += drv_len + dev_len + port_len;
2819
2820     if(data->u.dlgw->hDevNames)
2821         data->u.dlgw->hDevNames = GlobalReAlloc(data->u.dlgw->hDevNames, len, GMEM_MOVEABLE);
2822     else
2823         data->u.dlgw->hDevNames = GlobalAlloc(GMEM_MOVEABLE, len);
2824
2825     dn = GlobalLock(data->u.dlgw->hDevNames);
2826
2827     if(data->unicode)
2828     {
2829         WCHAR *ptr = (WCHAR *)(dn + 1);
2830         len = sizeof(DEVNAMES) / sizeof(WCHAR);
2831         dn->wDriverOffset = len;
2832         strcpyW(ptr, drv);
2833         ptr += drv_len / sizeof(WCHAR);
2834         len += drv_len / sizeof(WCHAR);
2835         dn->wDeviceOffset = len;
2836         strcpyW(ptr, devname);
2837         ptr += dev_len / sizeof(WCHAR);
2838         len += dev_len / sizeof(WCHAR);
2839         dn->wOutputOffset = len;
2840         strcpyW(ptr, port);
2841     }
2842     else
2843     {
2844         char *ptr = (char *)(dn + 1);
2845         len = sizeof(DEVNAMES);
2846         dn->wDriverOffset = len;
2847         WideCharToMultiByte(CP_ACP, 0, drv, -1, ptr, drv_len, NULL, NULL);
2848         ptr += drv_len;
2849         len += drv_len;
2850         dn->wDeviceOffset = len;
2851         WideCharToMultiByte(CP_ACP, 0, devname, -1, ptr, dev_len, NULL, NULL);
2852         ptr += dev_len;
2853         len += dev_len;
2854         dn->wOutputOffset = len;
2855         WideCharToMultiByte(CP_ACP, 0, port, -1, ptr, port_len, NULL, NULL);
2856     }
2857
2858     dn->wDefault = 0;
2859     len = sizeof(def) / sizeof(def[0]);
2860     GetDefaultPrinterW(def, &len);
2861     if(!lstrcmpW(def, devname))
2862         dn->wDefault = 1;
2863
2864     GlobalUnlock(data->u.dlgw->hDevNames);
2865 }
2866
2867 static DEVMODEW *pagesetup_get_devmode(const pagesetup_data *data)
2868 {
2869     DEVMODEW *dm = GlobalLock(data->u.dlgw->hDevMode);
2870     DEVMODEW *ret;
2871
2872     if(data->unicode)
2873     {
2874         /* We make a copy even in the unicode case because the ptr
2875            may get passed back to us in pagesetup_set_devmode. */
2876         ret = HeapAlloc(GetProcessHeap(), 0, dm->dmSize + dm->dmDriverExtra);
2877         memcpy(ret, dm, dm->dmSize + dm->dmDriverExtra);
2878     }
2879     else
2880         ret = GdiConvertToDevmodeW((DEVMODEA *)dm);
2881
2882     GlobalUnlock(data->u.dlgw->hDevMode);
2883     return ret;
2884 }
2885
2886 static void pagesetup_release_devmode(const pagesetup_data *data, DEVMODEW *dm)
2887 {
2888     HeapFree(GetProcessHeap(), 0, dm);
2889 }
2890
2891 static void pagesetup_set_devmode(pagesetup_data *data, DEVMODEW *dm)
2892 {
2893     DEVMODEA *dmA = NULL;
2894     void *src, *dst;
2895     DWORD size;
2896
2897     if(data->unicode)
2898     {
2899         size = dm->dmSize + dm->dmDriverExtra;
2900         src = dm;
2901     }
2902     else
2903     {
2904         dmA = convert_to_devmodeA(dm);
2905         size = dmA->dmSize + dmA->dmDriverExtra;
2906         src = dmA;
2907     }
2908
2909     if(data->u.dlgw->hDevMode)
2910         data->u.dlgw->hDevMode = GlobalReAlloc(data->u.dlgw->hDevMode, size,
2911                                                GMEM_MOVEABLE);
2912     else
2913         data->u.dlgw->hDevMode = GlobalAlloc(GMEM_MOVEABLE, size);
2914
2915     dst = GlobalLock(data->u.dlgw->hDevMode);
2916     memcpy(dst, src, size);
2917     GlobalUnlock(data->u.dlgw->hDevMode);
2918     HeapFree(GetProcessHeap(), 0, dmA);
2919 }
2920
2921 static inline POINT *pagesetup_get_papersize_pt(const pagesetup_data *data)
2922 {
2923     return &data->u.dlgw->ptPaperSize;
2924 }
2925
2926 static inline RECT *pagesetup_get_margin_rect(const pagesetup_data *data)
2927 {
2928     return &data->u.dlgw->rtMargin;
2929 }
2930
2931 typedef enum
2932 {
2933     page_setup_hook,
2934     page_paint_hook
2935 } hook_type;
2936
2937 static inline LPPAGESETUPHOOK pagesetup_get_hook(const pagesetup_data *data, hook_type which)
2938 {
2939     switch(which)
2940     {
2941     case page_setup_hook: return data->u.dlgw->lpfnPageSetupHook;
2942     case page_paint_hook: return data->u.dlgw->lpfnPagePaintHook;
2943     }
2944     return NULL;
2945 }
2946
2947 /* This should only be used in calls to hook procs so we return the ptr
2948    already cast to LPARAM */
2949 static inline LPARAM pagesetup_get_dlg_struct(const pagesetup_data *data)
2950 {
2951     return (LPARAM)data->u.dlgw;
2952 }
2953
2954 static inline void swap_point(POINT *pt)
2955 {
2956     LONG tmp = pt->x;
2957     pt->x = pt->y;
2958     pt->y = tmp;
2959 }
2960
2961 static BOOL pagesetup_update_papersize(pagesetup_data *data)
2962 {
2963     DEVMODEW *dm;
2964     LPWSTR devname, portname;
2965     int i, num;
2966     WORD *words = NULL, paperword;
2967     POINT *points = NULL;
2968     BOOL retval = FALSE;
2969
2970     dm       = pagesetup_get_devmode(data);
2971     devname  = pagesetup_get_devname(data);
2972     portname = pagesetup_get_portname(data);
2973
2974     num = DeviceCapabilitiesW(devname, portname, DC_PAPERS, NULL, dm);
2975     if (num <= 0)
2976     {
2977         FIXME("No papernames found for %s/%s\n", debugstr_w(devname), debugstr_w(portname));
2978         goto end;
2979     }
2980
2981     words = HeapAlloc(GetProcessHeap(), 0, num * sizeof(WORD));
2982     points = HeapAlloc(GetProcessHeap(), 0, num * sizeof(POINT));
2983
2984     if (num != DeviceCapabilitiesW(devname, portname, DC_PAPERS, (LPWSTR)words, dm))
2985     {
2986         FIXME("Number of returned words is not %d\n", num);
2987         goto end;
2988     }
2989
2990     if (num != DeviceCapabilitiesW(devname, portname, DC_PAPERSIZE, (LPWSTR)points, dm))
2991     {
2992         FIXME("Number of returned sizes is not %d\n", num);
2993         goto end;
2994     }
2995
2996     paperword = pagesetup_get_papersize(data);
2997
2998     for (i = 0; i < num; i++)
2999         if (words[i] == paperword)
3000             break;
3001
3002     if (i == num)
3003     {
3004         FIXME("Papersize %d not found in list?\n", paperword);
3005         goto end;
3006     }
3007
3008     /* this is _10ths_ of a millimeter */
3009     pagesetup_get_papersize_pt(data)->x = tenths_mm_to_size(data, points[i].x);
3010     pagesetup_get_papersize_pt(data)->y = tenths_mm_to_size(data, points[i].y);
3011
3012     if(pagesetup_get_orientation(data) == DMORIENT_LANDSCAPE)
3013         swap_point(pagesetup_get_papersize_pt(data));
3014
3015     retval = TRUE;
3016
3017 end:
3018     HeapFree(GetProcessHeap(), 0, words);
3019     HeapFree(GetProcessHeap(), 0, points);
3020     pagesetup_release_a_devname(data, portname);
3021     pagesetup_release_a_devname(data, devname);
3022     pagesetup_release_devmode(data, dm);
3023
3024     return retval;
3025 }
3026
3027 /**********************************************************************************************
3028  * pagesetup_change_printer
3029  *
3030  * Redefines hDevMode and hDevNames HANDLES and initialises it.
3031  * 
3032  */
3033 static BOOL pagesetup_change_printer(LPWSTR name, pagesetup_data *data)
3034 {
3035     HANDLE hprn;
3036     DWORD needed;
3037     PRINTER_INFO_2W *prn_info = NULL;
3038     DRIVER_INFO_3W *drv_info = NULL;
3039     DEVMODEW *dm = NULL;
3040     BOOL retval = FALSE;
3041
3042     if(!OpenPrinterW(name, &hprn, NULL))
3043     {
3044         ERR("Can't open printer %s\n", debugstr_w(name));
3045         goto end;
3046     }
3047
3048     GetPrinterW(hprn, 2, NULL, 0, &needed);
3049     prn_info = HeapAlloc(GetProcessHeap(), 0, needed);
3050     GetPrinterW(hprn, 2, (LPBYTE)prn_info, needed, &needed);
3051     GetPrinterDriverW(hprn, NULL, 3, NULL, 0, &needed);
3052     drv_info = HeapAlloc(GetProcessHeap(), 0, needed);
3053     if(!GetPrinterDriverW(hprn, NULL, 3, (LPBYTE)drv_info, needed, &needed))
3054     {
3055         ERR("GetPrinterDriverA failed for %s, fix your config!\n", debugstr_w(prn_info->pPrinterName));
3056         goto end;
3057     }
3058     ClosePrinter(hprn);
3059
3060     needed = DocumentPropertiesW(0, 0, name, NULL, NULL, 0);
3061     if(needed == -1)
3062     {
3063         ERR("DocumentProperties fails on %s\n", debugstr_w(name));
3064         goto end;
3065     }
3066
3067     dm = HeapAlloc(GetProcessHeap(), 0, needed);
3068     DocumentPropertiesW(0, 0, name, dm, NULL, DM_OUT_BUFFER);
3069
3070     pagesetup_set_devmode(data, dm);
3071     pagesetup_set_devnames(data, drv_info->pDriverPath, prn_info->pPrinterName,
3072                            prn_info->pPortName);
3073
3074     retval = TRUE;
3075 end:
3076     HeapFree(GetProcessHeap(), 0, dm);
3077     HeapFree(GetProcessHeap(), 0, prn_info);
3078     HeapFree(GetProcessHeap(), 0, drv_info);
3079     return retval;
3080 }
3081
3082 /****************************************************************************************
3083  *  pagesetup_init_combos
3084  *
3085  *  Fills Printers, Paper and Source combos
3086  *
3087  */
3088 static void pagesetup_init_combos(HWND hDlg, pagesetup_data *data)
3089 {
3090     DEVMODEW *dm;
3091     LPWSTR devname, portname;
3092
3093     dm       = pagesetup_get_devmode(data);
3094     devname  = pagesetup_get_devname(data);
3095     portname = pagesetup_get_portname(data);
3096
3097     PRINTDLG_SetUpPrinterListComboW(hDlg, cmb1, devname);
3098     PRINTDLG_SetUpPaperComboBoxW(hDlg, cmb2, devname, portname, dm);
3099     PRINTDLG_SetUpPaperComboBoxW(hDlg, cmb3, devname, portname, dm);
3100
3101     pagesetup_release_a_devname(data, portname);
3102     pagesetup_release_a_devname(data, devname);
3103     pagesetup_release_devmode(data, dm);
3104 }
3105
3106
3107 /****************************************************************************************
3108  *  pagesetup_change_printer_dialog
3109  *
3110  *  Pops up another dialog that lets the user pick another printer.
3111  *
3112  *  For now we display the PrintDlg, this should display a striped down version of it.
3113  */
3114 static void pagesetup_change_printer_dialog(HWND hDlg, pagesetup_data *data)
3115 {
3116     PRINTDLGW prnt;
3117     LPWSTR drvname, devname, portname;
3118     DEVMODEW *tmp_dm, *dm;
3119
3120     memset(&prnt, 0, sizeof(prnt));
3121     prnt.lStructSize = sizeof(prnt);
3122     prnt.Flags     = 0;
3123     prnt.hwndOwner = hDlg;
3124
3125     drvname = pagesetup_get_drvname(data);
3126     devname = pagesetup_get_devname(data);
3127     portname = pagesetup_get_portname(data);
3128     prnt.hDevNames = 0;
3129     PRINTDLG_CreateDevNamesW(&prnt.hDevNames, drvname, devname, portname);
3130     pagesetup_release_a_devname(data, portname);
3131     pagesetup_release_a_devname(data, devname);
3132     pagesetup_release_a_devname(data, drvname);
3133
3134     tmp_dm = pagesetup_get_devmode(data);
3135     prnt.hDevMode = GlobalAlloc(GMEM_MOVEABLE, tmp_dm->dmSize + tmp_dm->dmDriverExtra);
3136     dm = GlobalLock(prnt.hDevMode);
3137     memcpy(dm, tmp_dm, tmp_dm->dmSize + tmp_dm->dmDriverExtra);
3138     GlobalUnlock(prnt.hDevMode);
3139     pagesetup_release_devmode(data, tmp_dm);
3140
3141     if (PrintDlgW(&prnt))
3142     {
3143         DEVMODEW *dm = GlobalLock(prnt.hDevMode);
3144         DEVNAMES *dn = GlobalLock(prnt.hDevNames);
3145
3146         pagesetup_set_devnames(data, (WCHAR*)dn + dn->wDriverOffset,
3147                                (WCHAR*)dn + dn->wDeviceOffset, (WCHAR *)dn + dn->wOutputOffset);
3148         pagesetup_set_devmode(data, dm);
3149         GlobalUnlock(prnt.hDevNames);
3150         GlobalUnlock(prnt.hDevMode);
3151         pagesetup_init_combos(hDlg, data);
3152     }
3153
3154     GlobalFree(prnt.hDevMode);
3155     GlobalFree(prnt.hDevNames);
3156
3157 }
3158
3159 /******************************************************************************************
3160  * pagesetup_change_preview
3161  *
3162  * Changes paper preview size / position
3163  *
3164  */
3165 static void pagesetup_change_preview(const pagesetup_data *data)
3166 {
3167     LONG width, height, x, y;
3168     RECT tmp;
3169     const int shadow = 4;
3170
3171     if(pagesetup_get_orientation(data) == DMORIENT_LANDSCAPE)
3172     {
3173         width  = data->rtDrawRect.right - data->rtDrawRect.left;
3174         height = pagesetup_get_papersize_pt(data)->y * width / pagesetup_get_papersize_pt(data)->x;
3175     }
3176     else
3177     {
3178         height = data->rtDrawRect.bottom - data->rtDrawRect.top;
3179         width  = pagesetup_get_papersize_pt(data)->x * height / pagesetup_get_papersize_pt(data)->y;
3180     }
3181     x = (data->rtDrawRect.right + data->rtDrawRect.left - width) / 2;
3182     y = (data->rtDrawRect.bottom + data->rtDrawRect.top - height) / 2;
3183     TRACE("draw rect %s x=%d, y=%d, w=%d, h=%d\n",
3184           wine_dbgstr_rect(&data->rtDrawRect), x, y, width, height);
3185
3186     MoveWindow(GetDlgItem(data->hDlg, rct2), x + width, y + shadow, shadow, height, FALSE);
3187     MoveWindow(GetDlgItem(data->hDlg, rct3), x + shadow, y + height, width, shadow, FALSE);
3188     MoveWindow(GetDlgItem(data->hDlg, rct1), x, y, width, height, FALSE);
3189
3190     tmp = data->rtDrawRect;
3191     tmp.right  += shadow;
3192     tmp.bottom += shadow;
3193     InvalidateRect(data->hDlg, &tmp, TRUE);
3194 }
3195
3196 static inline LONG *element_from_margin_id(RECT *rc, WORD id)
3197 {
3198     switch(id)
3199     {
3200     case edt4: return &rc->left;
3201     case edt5: return &rc->top;
3202     case edt6: return &rc->right;
3203     case edt7: return &rc->bottom;
3204     }
3205     return NULL;
3206 }
3207
3208 static void update_margin_edits(HWND hDlg, const pagesetup_data *data, WORD id)
3209 {
3210     WCHAR str[100];
3211     WORD idx;
3212
3213     for(idx = edt4; idx <= edt7; idx++)
3214     {
3215         if(id == 0 || id == idx)
3216         {
3217             size2str(data, *element_from_margin_id(pagesetup_get_margin_rect(data), idx), str);
3218             SetDlgItemTextW(hDlg, idx, str);
3219         }
3220     }
3221 }
3222
3223 static void margin_edit_notification(HWND hDlg, const pagesetup_data *data, WORD msg, WORD id)
3224 {
3225     switch (msg)
3226     {
3227     case EN_CHANGE:
3228       {
3229         WCHAR buf[10];
3230         LONG val = 0;
3231         LONG *value = element_from_margin_id(pagesetup_get_margin_rect(data), id);
3232
3233         if (GetDlgItemTextW(hDlg, id, buf, sizeof(buf) / sizeof(buf[0])) != 0)
3234         {
3235             WCHAR *end;
3236             WCHAR decimal = get_decimal_sep();
3237
3238             val = strtolW(buf, &end, 10);
3239             if(end != buf || *end == decimal)
3240             {
3241                 int mult = is_metric(data) ? 100 : 1000;
3242                 val *= mult;
3243                 if(*end == decimal)
3244                 {
3245                     while(mult > 1)
3246                     {
3247                         end++;
3248                         mult /= 10;
3249                         if(isdigitW(*end))
3250                             val += (*end - '0') * mult;
3251                         else
3252                             break;
3253                     }
3254                 }
3255             }
3256         }
3257         *value = val;
3258         return;
3259       }
3260
3261     case EN_KILLFOCUS:
3262         update_margin_edits(hDlg, data, id);
3263         return;
3264     }
3265 }
3266
3267 static void set_margin_groupbox_title(HWND hDlg, const pagesetup_data *data)
3268 {
3269     WCHAR title[256];
3270
3271     if(LoadStringW(COMDLG32_hInstance, is_metric(data) ? PD32_MARGINS_IN_MILLIMETERS : PD32_MARGINS_IN_INCHES,
3272                    title, sizeof(title)/sizeof(title[0])))
3273         SetDlgItemTextW(hDlg, grp4, title);
3274 }
3275
3276 static void pagesetup_update_orientation_buttons(HWND hDlg, const pagesetup_data *data)
3277 {
3278     if (pagesetup_get_orientation(data) == DMORIENT_LANDSCAPE)
3279         CheckRadioButton(hDlg, rad1, rad2, rad2);
3280     else
3281         CheckRadioButton(hDlg, rad1, rad2, rad1);
3282 }
3283
3284 /****************************************************************************************
3285  *  pagesetup_printer_properties
3286  *
3287  *  Handle invocation of the 'Properties' button (not present in the default template).
3288  */
3289 static void pagesetup_printer_properties(HWND hDlg, pagesetup_data *data)
3290 {
3291     HANDLE hprn;
3292     LPWSTR devname;
3293     DEVMODEW *dm;
3294     LRESULT count;
3295     int i;
3296
3297     devname = pagesetup_get_devname(data);
3298
3299     if (!OpenPrinterW(devname, &hprn, NULL))
3300     {
3301         FIXME("Call to OpenPrinter did not succeed!\n");
3302         pagesetup_release_a_devname(data, devname);
3303         return;
3304     }
3305
3306     dm = pagesetup_get_devmode(data);
3307     DocumentPropertiesW(hDlg, hprn, devname, dm, dm, DM_IN_BUFFER | DM_OUT_BUFFER | DM_IN_PROMPT);
3308     pagesetup_set_devmode(data, dm);
3309     pagesetup_release_devmode(data, dm);
3310     pagesetup_release_a_devname(data, devname);
3311     ClosePrinter(hprn);
3312
3313     /* Changing paper */
3314     pagesetup_update_papersize(data);
3315     pagesetup_update_orientation_buttons(hDlg, data);
3316
3317     /* Changing paper preview */
3318     pagesetup_change_preview(data);
3319
3320     /* Selecting paper in combo */
3321     count = SendDlgItemMessageW(hDlg, cmb2, CB_GETCOUNT, 0, 0);
3322     if(count != CB_ERR)
3323     {
3324         WORD paperword = pagesetup_get_papersize(data);
3325         for(i = 0; i < count; i++)
3326         {
3327             if(SendDlgItemMessageW(hDlg, cmb2, CB_GETITEMDATA, i, 0) == paperword) {
3328                 SendDlgItemMessageW(hDlg, cmb2, CB_SETCURSEL, i, 0);
3329                 break;
3330             }
3331         }
3332     }
3333 }
3334
3335 /********************************************************************************
3336  * pagesetup_wm_command
3337  * process WM_COMMAND message for PageSetupDlg
3338  *
3339  * PARAMS
3340  *  hDlg        [in]    Main dialog HANDLE 
3341  *  wParam      [in]    WM_COMMAND wParam
3342  *  lParam      [in]    WM_COMMAND lParam
3343  *  pda         [in/out] ptr to PageSetupDataA
3344  */
3345
3346 static BOOL pagesetup_wm_command(HWND hDlg, WPARAM wParam, LPARAM lParam, pagesetup_data *data)
3347 {
3348     WORD msg = HIWORD(wParam);
3349     WORD id  = LOWORD(wParam);
3350
3351     TRACE("loword (lparam) %d, wparam 0x%lx, lparam %08lx\n",
3352             LOWORD(lParam),wParam,lParam);
3353     switch (id)  {
3354     case IDOK:
3355         EndDialog(hDlg, TRUE);
3356         return TRUE ;
3357
3358     case IDCANCEL:
3359         EndDialog(hDlg, FALSE);
3360         return FALSE ;
3361
3362     case psh3: /* Printer... */
3363         pagesetup_change_printer_dialog(hDlg, data);
3364         return TRUE;
3365
3366     case rad1: /* Portrait */
3367     case rad2: /* Landscape */
3368         if((id == rad1 && pagesetup_get_orientation(data) == DMORIENT_LANDSCAPE) ||
3369            (id == rad2 && pagesetup_get_orientation(data) == DMORIENT_PORTRAIT))
3370         {
3371             pagesetup_set_orientation(data, (id == rad1) ? DMORIENT_PORTRAIT : DMORIENT_LANDSCAPE);
3372             pagesetup_update_papersize(data);
3373             rotate_rect(pagesetup_get_margin_rect(data), (id == rad2));
3374             update_margin_edits(hDlg, data, 0);
3375             pagesetup_change_preview(data);
3376         }
3377         break;
3378     case cmb1: /* Printer combo */
3379         if(msg == CBN_SELCHANGE)
3380         {
3381             WCHAR name[256];
3382             GetDlgItemTextW(hDlg, id, name, sizeof(name) / sizeof(name[0]));
3383             pagesetup_change_printer(name, data);
3384             pagesetup_init_combos(hDlg, data);
3385         }
3386         break;
3387     case cmb2: /* Paper combo */
3388         if(msg == CBN_SELCHANGE)
3389         {
3390             DWORD paperword = SendDlgItemMessageW(hDlg, cmb2, CB_GETITEMDATA,
3391                                                   SendDlgItemMessageW(hDlg, cmb2, CB_GETCURSEL, 0, 0), 0);
3392             if (paperword != CB_ERR)
3393             {
3394                 pagesetup_set_papersize(data, paperword);
3395                 pagesetup_update_papersize(data);
3396                 pagesetup_change_preview(data);
3397             } else
3398                 FIXME("could not get dialog text for papersize cmbbox?\n");
3399         }
3400         break;
3401     case cmb3: /* Paper Source */
3402         if(msg == CBN_SELCHANGE)
3403         {
3404             WORD source = SendDlgItemMessageW(hDlg, cmb3, CB_GETITEMDATA,
3405                                               SendDlgItemMessageW(hDlg, cmb3, CB_GETCURSEL, 0, 0), 0);
3406             pagesetup_set_defaultsource(data, source);
3407         }
3408         break;
3409     case psh2: /* Printer Properties button */
3410         pagesetup_printer_properties(hDlg, data);
3411         break;
3412     case edt4:
3413     case edt5:
3414     case edt6:
3415     case edt7:
3416         margin_edit_notification(hDlg, data, msg, id);
3417         break;
3418     }
3419     InvalidateRect(GetDlgItem(hDlg, rct1), NULL, TRUE);
3420     return FALSE;
3421 }
3422
3423 /***********************************************************************
3424  *           default_page_paint_hook
3425  * Default hook paint procedure that receives WM_PSD_* messages from the dialog box 
3426  * whenever the sample page is redrawn.
3427  */
3428 static UINT_PTR default_page_paint_hook(HWND hwndDlg, UINT uMsg, WPARAM wParam, LPARAM lParam,
3429                                         const pagesetup_data *data)
3430 {
3431     LPRECT lprc = (LPRECT) lParam;
3432     HDC hdc = (HDC) wParam;
3433     HPEN hpen, holdpen;
3434     LOGFONTW lf;
3435     HFONT hfont, holdfont;
3436     INT oldbkmode;
3437     TRACE("uMsg: WM_USER+%d\n",uMsg-WM_USER);
3438     /* Call user paint hook if enable */
3439     if (pagesetup_get_flags(data) & PSD_ENABLEPAGEPAINTHOOK)
3440         if (pagesetup_get_hook(data, page_paint_hook)(hwndDlg, uMsg, wParam, lParam))
3441             return TRUE;
3442
3443     switch (uMsg) {
3444        /* LPPAGESETUPDLG in lParam */
3445        case WM_PSD_PAGESETUPDLG:
3446        /* Inform about the sample page rectangle */
3447        case WM_PSD_FULLPAGERECT:
3448        /* Inform about the margin rectangle */
3449        case WM_PSD_MINMARGINRECT:
3450             return FALSE;
3451
3452         /* Draw dashed rectangle showing margins */
3453         case WM_PSD_MARGINRECT:
3454             hpen = CreatePen(PS_DASH, 1, GetSysColor(COLOR_3DSHADOW));
3455             holdpen = SelectObject(hdc, hpen);
3456             Rectangle(hdc, lprc->left, lprc->top, lprc->right, lprc->bottom);
3457             DeleteObject(SelectObject(hdc, holdpen));
3458             return TRUE;
3459         /* Draw the fake document */
3460         case WM_PSD_GREEKTEXTRECT:
3461             /* select a nice scalable font, because we want the text really small */
3462             SystemParametersInfoW(SPI_GETICONTITLELOGFONT, sizeof(lf), &lf, 0);
3463             lf.lfHeight = 6; /* value chosen based on visual effect */
3464             hfont = CreateFontIndirectW(&lf);
3465             holdfont = SelectObject(hdc, hfont);
3466
3467             /* if text not loaded, then do so now */
3468             if (wszFakeDocumentText[0] == '\0')
3469                  LoadStringW(COMDLG32_hInstance,
3470                         IDS_FAKEDOCTEXT,
3471                         wszFakeDocumentText,
3472                         sizeof(wszFakeDocumentText)/sizeof(wszFakeDocumentText[0]));
3473
3474             oldbkmode = SetBkMode(hdc, TRANSPARENT);
3475             DrawTextW(hdc, wszFakeDocumentText, -1, lprc, DT_TOP|DT_LEFT|DT_NOPREFIX|DT_WORDBREAK);
3476             SetBkMode(hdc, oldbkmode);
3477
3478             DeleteObject(SelectObject(hdc, holdfont));
3479             return TRUE;
3480
3481         /* Envelope stamp */
3482         case WM_PSD_ENVSTAMPRECT:
3483         /* Return address */
3484         case WM_PSD_YAFULLPAGERECT:
3485             FIXME("envelope/stamp is not implemented\n");
3486             return FALSE;
3487         default:
3488             FIXME("Unknown message %x\n",uMsg);
3489             return FALSE;
3490     }
3491     return TRUE;
3492 }
3493
3494 /***********************************************************************
3495  *           PagePaintProc
3496  * The main paint procedure for the PageSetupDlg function.
3497  * The Page Setup dialog box includes an image of a sample page that shows how
3498  * the user's selections affect the appearance of the printed output.
3499  * The image consists of a rectangle that represents the selected paper
3500  * or envelope type, with a dotted-line rectangle representing
3501  * the current margins, and partial (Greek text) characters
3502  * to show how text looks on the printed page. 
3503  *
3504  * The following messages in the order sends to user hook procedure:
3505  *   WM_PSD_PAGESETUPDLG    Draw the contents of the sample page
3506  *   WM_PSD_FULLPAGERECT    Inform about the bounding rectangle
3507  *   WM_PSD_MINMARGINRECT   Inform about the margin rectangle (min margin?)
3508  *   WM_PSD_MARGINRECT      Draw the margin rectangle
3509  *   WM_PSD_GREEKTEXTRECT   Draw the Greek text inside the margin rectangle
3510  * If any of first three messages returns TRUE, painting done.
3511  *
3512  * PARAMS:
3513  *   hWnd   [in] Handle to the Page Setup dialog box
3514  *   uMsg   [in] Received message
3515  *
3516  * TODO:
3517  *   WM_PSD_ENVSTAMPRECT    Draw in the envelope-stamp rectangle (for envelopes only)
3518  *   WM_PSD_YAFULLPAGERECT  Draw the return address portion (for envelopes and other paper sizes)
3519  *
3520  * RETURNS:
3521  *   FALSE if all done correctly
3522  *
3523  */
3524
3525
3526 static LRESULT CALLBACK
3527 PRINTDLG_PagePaintProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
3528 {
3529     PAINTSTRUCT ps;
3530     RECT rcClient, rcMargin;
3531     HPEN hpen, holdpen;
3532     HDC hdc;
3533     HBRUSH hbrush, holdbrush;
3534     pagesetup_data *data;
3535     int papersize=0, orientation=0; /* FIXME: set these values for the user paint hook */
3536     double scalx, scaly;
3537
3538     if (uMsg != WM_PAINT)
3539         return CallWindowProcA(lpfnStaticWndProc, hWnd, uMsg, wParam, lParam);
3540
3541     /* Processing WM_PAINT message */
3542     data = GetPropW(hWnd, pagesetupdlg_prop);
3543     if (!data) {
3544         WARN("__WINE_PAGESETUPDLGDATA prop not set?\n");
3545         return FALSE;
3546     }
3547     if (default_page_paint_hook(hWnd, WM_PSD_PAGESETUPDLG, MAKELONG(papersize, orientation),
3548                                 pagesetup_get_dlg_struct(data), data))
3549         return FALSE;
3550
3551     hdc = BeginPaint(hWnd, &ps);
3552     GetClientRect(hWnd, &rcClient);
3553     
3554     scalx = rcClient.right  / (double)pagesetup_get_papersize_pt(data)->x;
3555     scaly = rcClient.bottom / (double)pagesetup_get_papersize_pt(data)->y;
3556     rcMargin = rcClient;
3557
3558     rcMargin.left   += pagesetup_get_margin_rect(data)->left   * scalx;
3559     rcMargin.top    += pagesetup_get_margin_rect(data)->top    * scaly;
3560     rcMargin.right  -= pagesetup_get_margin_rect(data)->right  * scalx;
3561     rcMargin.bottom -= pagesetup_get_margin_rect(data)->bottom * scaly;
3562
3563     /* if the space is too small then we make sure to not draw anything */
3564     rcMargin.left = min(rcMargin.left, rcMargin.right);
3565     rcMargin.top = min(rcMargin.top, rcMargin.bottom);
3566
3567     if (!default_page_paint_hook(hWnd, WM_PSD_FULLPAGERECT, (WPARAM)hdc, (LPARAM)&rcClient, data) &&
3568         !default_page_paint_hook(hWnd, WM_PSD_MINMARGINRECT, (WPARAM)hdc, (LPARAM)&rcMargin, data) )
3569     {
3570         /* fill background */
3571         hbrush = GetSysColorBrush(COLOR_3DHIGHLIGHT);
3572         FillRect(hdc, &rcClient, hbrush);
3573         holdbrush = SelectObject(hdc, hbrush);
3574
3575         hpen = CreatePen(PS_SOLID, 1, GetSysColor(COLOR_3DSHADOW));
3576         holdpen = SelectObject(hdc, hpen);
3577         
3578         /* paint left edge */
3579         MoveToEx(hdc, rcClient.left, rcClient.top, NULL);
3580         LineTo(hdc, rcClient.left, rcClient.bottom-1);
3581
3582         /* paint top edge */
3583         MoveToEx(hdc, rcClient.left, rcClient.top, NULL);
3584         LineTo(hdc, rcClient.right, rcClient.top);
3585
3586         hpen = CreatePen(PS_SOLID, 1, GetSysColor(COLOR_3DDKSHADOW));
3587         DeleteObject(SelectObject(hdc, hpen));
3588
3589         /* paint right edge */
3590         MoveToEx(hdc, rcClient.right-1, rcClient.top, NULL);
3591         LineTo(hdc, rcClient.right-1, rcClient.bottom);
3592
3593         /* paint bottom edge */
3594         MoveToEx(hdc, rcClient.left, rcClient.bottom-1, NULL);
3595         LineTo(hdc, rcClient.right, rcClient.bottom-1);
3596
3597         DeleteObject(SelectObject(hdc, holdpen));
3598         DeleteObject(SelectObject(hdc, holdbrush));
3599
3600         default_page_paint_hook(hWnd, WM_PSD_MARGINRECT, (WPARAM)hdc, (LPARAM)&rcMargin, data);
3601
3602         /* give text a bit of a space from the frame */
3603         rcMargin.left += 2;
3604         rcMargin.top += 2;
3605         rcMargin.right -= 2;
3606         rcMargin.bottom -= 2;
3607         
3608         /* if the space is too small then we make sure to not draw anything */
3609         rcMargin.left = min(rcMargin.left, rcMargin.right);
3610         rcMargin.top = min(rcMargin.top, rcMargin.bottom);
3611
3612         default_page_paint_hook(hWnd, WM_PSD_GREEKTEXTRECT, (WPARAM)hdc, (LPARAM)&rcMargin, data);
3613     }
3614
3615     EndPaint(hWnd, &ps);
3616     return FALSE;
3617 }
3618
3619 /*******************************************************
3620  * The margin edit controls are subclassed to filter
3621  * anything other than numbers and the decimal separator.
3622  */
3623 static LRESULT CALLBACK pagesetup_margin_editproc(HWND hwnd, UINT msg, WPARAM wparam, LPARAM lparam)
3624 {
3625     if (msg == WM_CHAR)
3626     {
3627         WCHAR decimal = get_decimal_sep();
3628         WCHAR wc = (WCHAR)wparam;
3629         if(!isdigitW(wc) && wc != decimal && wc != VK_BACK) return 0;
3630     }
3631     return CallWindowProcW(edit_wndproc, hwnd, msg, wparam, lparam);
3632 }
3633
3634 static void subclass_margin_edits(HWND hDlg)
3635 {
3636     int id;
3637     WNDPROC old_proc;
3638
3639     for(id = edt4; id <= edt7; id++)
3640     {
3641         old_proc = (WNDPROC)SetWindowLongPtrW(GetDlgItem(hDlg, id),
3642                                               GWLP_WNDPROC,
3643                                               (ULONG_PTR)pagesetup_margin_editproc);
3644         InterlockedCompareExchangePointer((void**)&edit_wndproc, old_proc, NULL);
3645     }
3646 }
3647
3648 /***********************************************************************
3649  *           pagesetup_dlg_proc
3650  *
3651  * Message handler for PageSetupDlg
3652  */
3653 static INT_PTR CALLBACK pagesetup_dlg_proc(HWND hDlg, UINT uMsg, WPARAM wParam, LPARAM lParam)
3654 {
3655     pagesetup_data *data;
3656     INT_PTR             res = FALSE;
3657     HWND                hDrawWnd;
3658
3659     if (uMsg == WM_INITDIALOG) { /*Init dialog*/
3660         data = (pagesetup_data *)lParam;
3661         data->hDlg = hDlg;
3662
3663         hDrawWnd = GetDlgItem(hDlg, rct1); 
3664         TRACE("set property to %p\n", data);
3665         SetPropW(hDlg, pagesetupdlg_prop, data);
3666         SetPropW(hDrawWnd, pagesetupdlg_prop, data);
3667         GetWindowRect(hDrawWnd, &data->rtDrawRect); /* Calculating rect in client coordinates where paper draws */
3668         MapWindowPoints( 0, hDlg, (LPPOINT)&data->rtDrawRect, 2 );
3669         lpfnStaticWndProc = (WNDPROC)SetWindowLongPtrW(
3670             hDrawWnd,
3671             GWLP_WNDPROC,
3672             (ULONG_PTR)PRINTDLG_PagePaintProc);
3673         
3674         /* FIXME: Paint hook. Must it be at begin of initialization or at end? */
3675         res = TRUE;
3676         if (pagesetup_get_flags(data) & PSD_ENABLEPAGESETUPHOOK)
3677         {
3678             if (!pagesetup_get_hook(data, page_setup_hook)(hDlg, uMsg, wParam,
3679                                                            pagesetup_get_dlg_struct(data)))
3680                 FIXME("Setup page hook failed?\n");
3681         }
3682
3683         /* if printer button disabled */
3684         if (pagesetup_get_flags(data) & PSD_DISABLEPRINTER)
3685             EnableWindow(GetDlgItem(hDlg, psh3), FALSE);
3686         /* if margin edit boxes disabled */
3687         if (pagesetup_get_flags(data) & PSD_DISABLEMARGINS)
3688         {
3689             EnableWindow(GetDlgItem(hDlg, edt4), FALSE);
3690             EnableWindow(GetDlgItem(hDlg, edt5), FALSE);
3691             EnableWindow(GetDlgItem(hDlg, edt6), FALSE);
3692             EnableWindow(GetDlgItem(hDlg, edt7), FALSE);
3693         }
3694
3695         /* Set orientation radiobuttons properly */
3696         pagesetup_update_orientation_buttons(hDlg, data);
3697
3698         /* if orientation disabled */
3699         if (pagesetup_get_flags(data) & PSD_DISABLEORIENTATION)
3700         {
3701             EnableWindow(GetDlgItem(hDlg,rad1),FALSE);
3702             EnableWindow(GetDlgItem(hDlg,rad2),FALSE);
3703         }
3704
3705         /* We fill them out enabled or not */
3706         if (!(pagesetup_get_flags(data) & PSD_MARGINS))
3707         {
3708             /* default is 1 inch */
3709             LONG size = thousandths_inch_to_size(data, 1000);
3710             SetRect(pagesetup_get_margin_rect(data), size, size, size, size);
3711         }
3712         update_margin_edits(hDlg, data, 0);
3713         subclass_margin_edits(hDlg);
3714         set_margin_groupbox_title(hDlg, data);
3715
3716         /* if paper disabled */
3717         if (pagesetup_get_flags(data) & PSD_DISABLEPAPER)
3718         {
3719             EnableWindow(GetDlgItem(hDlg,cmb2),FALSE);
3720             EnableWindow(GetDlgItem(hDlg,cmb3),FALSE);
3721         }
3722
3723         /* filling combos: printer, paper, source. selecting current printer (from DEVMODEA) */
3724         pagesetup_init_combos(hDlg, data);
3725         pagesetup_update_papersize(data);
3726         pagesetup_set_defaultsource(data, DMBIN_FORMSOURCE); /* FIXME: This is the auto select bin. Is this correct? */
3727
3728         /* Drawing paper prev */
3729         pagesetup_change_preview(data);
3730         return TRUE;
3731     } else {
3732         data = GetPropW(hDlg, pagesetupdlg_prop);
3733         if (!data)
3734         {
3735             WARN("__WINE_PAGESETUPDLGDATA prop not set?\n");
3736             return FALSE;
3737         }
3738         if (pagesetup_get_flags(data) & PSD_ENABLEPAGESETUPHOOK)
3739         {
3740             res = pagesetup_get_hook(data, page_setup_hook)(hDlg, uMsg, wParam, lParam);
3741             if (res) return res;
3742         }
3743     }
3744     switch (uMsg) {
3745     case WM_COMMAND:
3746         return pagesetup_wm_command(hDlg, wParam, lParam, data);
3747     }
3748     return FALSE;
3749 }
3750
3751 static WCHAR *get_default_printer(void)
3752 {
3753     WCHAR *name = NULL;
3754     DWORD len = 0;
3755
3756     GetDefaultPrinterW(NULL, &len);
3757     if(len)
3758     {
3759         name = HeapAlloc(GetProcessHeap(), 0, len * sizeof(WCHAR));
3760         GetDefaultPrinterW(name, &len);
3761     }
3762     return name;
3763 }
3764
3765 static void pagesetup_dump_dlg_struct(const pagesetup_data *data)
3766 {
3767     if(TRACE_ON(commdlg))
3768     {
3769         char flagstr[1000] = "";
3770         const struct pd_flags *pflag = psd_flags;
3771         for( ; pflag->name; pflag++)
3772         {
3773             if(pagesetup_get_flags(data) & pflag->flag)
3774             {
3775                 strcat(flagstr, pflag->name);
3776                 strcat(flagstr, "|");
3777             }
3778         }
3779         TRACE("%s: (%p): hwndOwner = %p, hDevMode = %p, hDevNames = %p\n"
3780               "hinst %p, flags %08x (%s)\n",
3781               data->unicode ? "unicode" : "ansi",
3782               data->u.dlgw, data->u.dlgw->hwndOwner, data->u.dlgw->hDevMode,
3783               data->u.dlgw->hDevNames, data->u.dlgw->hInstance,
3784               pagesetup_get_flags(data), flagstr);
3785     }
3786 }
3787
3788 static void *pagesetup_get_template(pagesetup_data *data)
3789 {
3790     HRSRC res;
3791     HGLOBAL tmpl_handle;
3792
3793     if(pagesetup_get_flags(data) & PSD_ENABLEPAGESETUPTEMPLATEHANDLE)
3794     {
3795         tmpl_handle = data->u.dlgw->hPageSetupTemplate;
3796     }
3797     else if(pagesetup_get_flags(data) & PSD_ENABLEPAGESETUPTEMPLATE)
3798     {
3799         if(data->unicode)
3800             res = FindResourceW(data->u.dlgw->hInstance,
3801                                 data->u.dlgw->lpPageSetupTemplateName, MAKEINTRESOURCEW(RT_DIALOG));
3802         else
3803             res = FindResourceA(data->u.dlga->hInstance,
3804                                 data->u.dlga->lpPageSetupTemplateName, MAKEINTRESOURCEA(RT_DIALOG));
3805         tmpl_handle = LoadResource(data->u.dlgw->hInstance, res);
3806     }
3807     else
3808     {
3809         res = FindResourceW(COMDLG32_hInstance, MAKEINTRESOURCEW(PAGESETUPDLGORD),
3810                             MAKEINTRESOURCEW(RT_DIALOG));
3811         tmpl_handle = LoadResource(COMDLG32_hInstance, res);
3812     }
3813     return LockResource(tmpl_handle);
3814 }
3815
3816 static BOOL pagesetup_common(pagesetup_data *data)
3817 {
3818     BOOL ret;
3819     void *tmpl;
3820
3821     if(!pagesetup_get_dlg_struct(data))
3822     {
3823         COMDLG32_SetCommDlgExtendedError(CDERR_INITIALIZATION);
3824         return FALSE;
3825     }
3826
3827     pagesetup_dump_dlg_struct(data);
3828
3829     if(data->u.dlgw->lStructSize != sizeof(PAGESETUPDLGW))
3830     {
3831         COMDLG32_SetCommDlgExtendedError(CDERR_STRUCTSIZE);
3832         return FALSE;
3833     }
3834
3835     if ((pagesetup_get_flags(data) & PSD_ENABLEPAGEPAINTHOOK) &&
3836         (pagesetup_get_hook(data, page_paint_hook) == NULL))
3837     {
3838         COMDLG32_SetCommDlgExtendedError(CDERR_NOHOOK);
3839         return FALSE;
3840     }
3841
3842     if(!(pagesetup_get_flags(data) & (PSD_INTHOUSANDTHSOFINCHES | PSD_INHUNDREDTHSOFMILLIMETERS)))
3843         data->u.dlgw->Flags |= is_default_metric() ?
3844             PSD_INHUNDREDTHSOFMILLIMETERS : PSD_INTHOUSANDTHSOFINCHES;
3845
3846     if (!data->u.dlgw->hDevMode || !data->u.dlgw->hDevNames)
3847     {
3848         WCHAR *def = get_default_printer();
3849         if(!def)
3850         {
3851             if (!(pagesetup_get_flags(data) & PSD_NOWARNING))
3852             {
3853                 WCHAR errstr[256];
3854                 LoadStringW(COMDLG32_hInstance, PD32_NO_DEFAULT_PRINTER, errstr, 255);
3855                 MessageBoxW(data->u.dlgw->hwndOwner, errstr, 0, MB_OK | MB_ICONERROR);
3856             }
3857             COMDLG32_SetCommDlgExtendedError(PDERR_NODEFAULTPRN);
3858             return FALSE;
3859         }
3860         pagesetup_change_printer(def, data);
3861         HeapFree(GetProcessHeap(), 0, def);
3862     }
3863
3864     if (pagesetup_get_flags(data) & PSD_RETURNDEFAULT)
3865     {
3866         pagesetup_update_papersize(data);
3867         return TRUE;
3868     }
3869
3870     tmpl = pagesetup_get_template(data);
3871
3872     ret = DialogBoxIndirectParamW(data->u.dlgw->hInstance, tmpl,
3873                                   data->u.dlgw->hwndOwner,
3874                                   pagesetup_dlg_proc, (LPARAM)data) > 0;
3875     return ret;
3876 }
3877
3878 /***********************************************************************
3879  *            PageSetupDlgA  (COMDLG32.@)
3880  *
3881  *  Displays the PAGE SETUP dialog box, which enables the user to specify
3882  *  specific properties of a printed page such as
3883  *  size, source, orientation and the width of the page margins.
3884  *
3885  * PARAMS
3886  *  setupdlg [IO] PAGESETUPDLGA struct
3887  *
3888  * RETURNS
3889  *  TRUE    if the user pressed the OK button
3890  *  FALSE   if the user cancelled the window or an error occurred
3891  *
3892  * NOTES
3893  *    The values of hDevMode and hDevNames are filled on output and can be
3894  *    changed in PAGESETUPDLG when they are passed in PageSetupDlg.
3895  *
3896  */
3897 BOOL WINAPI PageSetupDlgA(LPPAGESETUPDLGA setupdlg)
3898 {
3899     pagesetup_data data;
3900
3901     data.unicode = FALSE;
3902     data.u.dlga  = setupdlg;
3903
3904     return pagesetup_common(&data);
3905 }
3906
3907 /***********************************************************************
3908  *            PageSetupDlgW  (COMDLG32.@)
3909  *
3910  * See PageSetupDlgA.
3911  */
3912 BOOL WINAPI PageSetupDlgW(LPPAGESETUPDLGW setupdlg)
3913 {
3914     pagesetup_data data;
3915
3916     data.unicode = TRUE;
3917     data.u.dlgw  = setupdlg;
3918
3919     return pagesetup_common(&data);
3920 }
3921
3922 /***********************************************************************
3923  * PrintDlgExA (COMDLG32.@)
3924  *
3925  * See PrintDlgExW.
3926  *
3927  * BUGS
3928  *   Only a Stub
3929  *
3930  */
3931 HRESULT WINAPI PrintDlgExA(LPPRINTDLGEXA lppd)
3932 {
3933     PRINTER_INFO_2A *pbuf;
3934     DRIVER_INFO_3A *dbuf;
3935     DEVMODEA *dm;
3936     HRESULT hr = S_OK;
3937     HANDLE hprn;
3938
3939     if ((lppd == NULL) || (lppd->lStructSize != sizeof(PRINTDLGEXA)))
3940         return E_INVALIDARG;
3941
3942     if (!IsWindow(lppd->hwndOwner))
3943         return E_HANDLE;
3944
3945     if (lppd->nStartPage != START_PAGE_GENERAL)
3946     {
3947         if (!lppd->nPropertyPages)
3948             return E_INVALIDARG;
3949
3950         FIXME("custom property sheets (%d at %p) not supported\n", lppd->nPropertyPages, lppd->lphPropertyPages);
3951     }
3952
3953     /* Use PD_NOPAGENUMS or set nMaxPageRanges and lpPageRanges */
3954     if (!(lppd->Flags & PD_NOPAGENUMS) && (!lppd->nMaxPageRanges || !lppd->lpPageRanges))
3955     {
3956         return E_INVALIDARG;
3957     }
3958
3959     if (lppd->Flags & PD_RETURNDEFAULT)
3960     {
3961         if (lppd->hDevMode || lppd->hDevNames)
3962         {
3963             WARN("hDevMode or hDevNames non-zero for PD_RETURNDEFAULT\n");
3964             COMDLG32_SetCommDlgExtendedError(PDERR_RETDEFFAILURE);
3965             return E_INVALIDARG;
3966         }
3967         if (!PRINTDLG_OpenDefaultPrinter(&hprn))
3968         {
3969             WARN("Can't find default printer\n");
3970             COMDLG32_SetCommDlgExtendedError(PDERR_NODEFAULTPRN);
3971             return E_FAIL;
3972         }
3973
3974         pbuf = get_printer_infoA(hprn);
3975         if (!pbuf)
3976         {
3977             ClosePrinter(hprn);
3978             return E_FAIL;
3979         }
3980
3981         dbuf = get_driver_infoA(hprn);
3982         if (!dbuf)
3983         {
3984             HeapFree(GetProcessHeap(), 0, pbuf);
3985             COMDLG32_SetCommDlgExtendedError(PDERR_RETDEFFAILURE);
3986             ClosePrinter(hprn);
3987             return E_FAIL;
3988         }
3989         dm = pbuf->pDevMode;
3990     }
3991     else
3992     {
3993         FIXME("(%p) dialog not implemented\n", lppd);
3994         return E_NOTIMPL;
3995
3996     }
3997
3998     ClosePrinter(hprn);
3999
4000     PRINTDLG_CreateDevNames(&(lppd->hDevNames), dbuf->pDriverPath, pbuf->pPrinterName, pbuf->pPortName);
4001     if (!lppd->hDevNames)
4002         hr = E_FAIL;
4003
4004     lppd->hDevMode = update_devmode_handleA(lppd->hDevMode, dm);
4005     if (!hr && lppd->hDevMode) {
4006         if (lppd->Flags & PD_RETURNDC) {
4007             lppd->hDC = CreateDCA(dbuf->pDriverPath, pbuf->pPrinterName, pbuf->pPortName, dm);
4008             if (!lppd->hDC)
4009                 hr = E_FAIL;
4010         }
4011         else if (lppd->Flags & PD_RETURNIC) {
4012             lppd->hDC = CreateICA(dbuf->pDriverPath, pbuf->pPrinterName, pbuf->pPortName, dm);
4013             if (!lppd->hDC)
4014                 hr = E_FAIL;
4015         }
4016     }
4017     else
4018         hr = E_FAIL;
4019
4020     HeapFree(GetProcessHeap(), 0, pbuf);
4021     HeapFree(GetProcessHeap(), 0, dbuf);
4022
4023     return hr;
4024 }
4025
4026 /***********************************************************************
4027  * PrintDlgExW (COMDLG32.@)
4028  *
4029  * Display the property sheet style PRINT dialog box
4030  *  
4031  * PARAMS
4032  *  lppd  [IO] ptr to PRINTDLGEX struct
4033  * 
4034  * RETURNS
4035  *  Success: S_OK
4036  *  Failure: One of the following COM error codes:
4037  *    E_OUTOFMEMORY Insufficient memory.
4038  *    E_INVALIDARG  One or more arguments are invalid.
4039  *    E_POINTER     Invalid pointer.
4040  *    E_HANDLE      Invalid handle.
4041  *    E_FAIL        Unspecified error.
4042  *  
4043  * NOTES
4044  * This Dialog enables the user to specify specific properties of the print job.
4045  * The property sheet can also have additional application-specific and
4046  * driver-specific property pages.
4047  *
4048  * BUGS
4049  *   Not fully implemented
4050  *
4051  */
4052 HRESULT WINAPI PrintDlgExW(LPPRINTDLGEXW lppd)
4053 {
4054     PRINTER_INFO_2W *pbuf;
4055     DRIVER_INFO_3W *dbuf;
4056     DEVMODEW *dm;
4057     HRESULT hr = S_OK;
4058     HANDLE hprn;
4059
4060     if ((lppd == NULL) || (lppd->lStructSize != sizeof(PRINTDLGEXW))) {
4061         return E_INVALIDARG;
4062     }
4063
4064     if (!IsWindow(lppd->hwndOwner)) {
4065         return E_HANDLE;
4066     }
4067
4068     if (lppd->nStartPage != START_PAGE_GENERAL)
4069     {
4070         if (!lppd->nPropertyPages)
4071             return E_INVALIDARG;
4072
4073         FIXME("custom property sheets (%d at %p) not supported\n", lppd->nPropertyPages, lppd->lphPropertyPages);
4074     }
4075
4076     /* Use PD_NOPAGENUMS or set nMaxPageRanges and lpPageRanges */
4077     if (!(lppd->Flags & PD_NOPAGENUMS) && (!lppd->nMaxPageRanges || !lppd->lpPageRanges))
4078     {
4079         return E_INVALIDARG;
4080     }
4081
4082     if (lppd->Flags & PD_RETURNDEFAULT) {
4083
4084         if (lppd->hDevMode || lppd->hDevNames) {
4085             WARN("hDevMode or hDevNames non-zero for PD_RETURNDEFAULT\n");
4086             COMDLG32_SetCommDlgExtendedError(PDERR_RETDEFFAILURE);
4087             return E_INVALIDARG;
4088         }
4089         if (!PRINTDLG_OpenDefaultPrinter(&hprn)) {
4090             WARN("Can't find default printer\n");
4091             COMDLG32_SetCommDlgExtendedError(PDERR_NODEFAULTPRN);
4092             return E_FAIL;
4093         }
4094
4095         pbuf = get_printer_infoW(hprn);
4096         if (!pbuf)
4097         {
4098             ClosePrinter(hprn);
4099             return E_FAIL;
4100         }
4101
4102         dbuf = get_driver_infoW(hprn);
4103         if (!dbuf)
4104         {
4105             HeapFree(GetProcessHeap(), 0, pbuf);
4106             COMDLG32_SetCommDlgExtendedError(PDERR_RETDEFFAILURE);
4107             ClosePrinter(hprn);
4108             return E_FAIL;
4109         }
4110         dm = pbuf->pDevMode;
4111     }
4112     else
4113     {
4114         FIXME("(%p) dialog not implemented\n", lppd);
4115         return E_NOTIMPL;
4116
4117     }
4118
4119     ClosePrinter(hprn);
4120
4121     PRINTDLG_CreateDevNamesW(&(lppd->hDevNames), dbuf->pDriverPath, pbuf->pPrinterName, pbuf->pPortName);
4122     if (!lppd->hDevNames)
4123         hr = E_FAIL;
4124
4125     lppd->hDevMode = update_devmode_handleW(lppd->hDevMode, dm);
4126     if (!hr && lppd->hDevMode) {
4127         if (lppd->Flags & PD_RETURNDC) {
4128             lppd->hDC = CreateDCW(dbuf->pDriverPath, pbuf->pPrinterName, pbuf->pPortName, dm);
4129             if (!lppd->hDC)
4130                 hr = E_FAIL;
4131         }
4132         else if (lppd->Flags & PD_RETURNIC) {
4133             lppd->hDC = CreateICW(dbuf->pDriverPath, pbuf->pPrinterName, pbuf->pPortName, dm);
4134             if (!lppd->hDC)
4135                 hr = E_FAIL;
4136         }
4137     }
4138     else
4139         hr = E_FAIL;
4140
4141     HeapFree(GetProcessHeap(), 0, pbuf);
4142     HeapFree(GetProcessHeap(), 0, dbuf);
4143
4144     return hr;
4145 }