printdlg.c 123 KB
Newer Older
1 2 3 4 5 6
/*
 * COMMDLG - Print Dialog
 *
 * Copyright 1994 Martin Ayotte
 * Copyright 1996 Albrecht Kleine
 * Copyright 1999 Klaas van Gend
7
 * Copyright 2000 Huw D M Davies
8 9 10 11 12 13 14 15 16 17 18 19 20
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
21
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
22 23 24
 */
#include <ctype.h>
#include <stdlib.h>
25
#include <stdarg.h>
26
#include <stdio.h>
27
#include <string.h>
28
#include <assert.h>
29 30 31

#define NONAMELESSUNION
#define NONAMELESSSTRUCT
32
#include "windef.h"
33
#include "winbase.h"
34
#include "wingdi.h"
35
#include "winuser.h"
36 37 38
#include "winspool.h"
#include "winerror.h"

39
#include "wine/unicode.h"
40 41
#include "wine/debug.h"

42 43
#include "commdlg.h"
#include "dlgs.h"
44
#include "cderr.h"
45
#include "cdlg.h"
46

47
WINE_DEFAULT_DEBUG_CHANNEL(commdlg);
48

49 50 51
/* Yes these constants are the same, but we're just copying win98 */
#define UPDOWN_ID 0x270f
#define MAX_COPIES 9999
52

53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84
/* This PRINTDLGA internal structure stores
 * pointers to several throughout useful structures.
 */

typedef struct
{
  LPDEVMODEA        lpDevMode;
  LPPRINTDLGA       lpPrintDlg;
  LPPRINTER_INFO_2A lpPrinterInfo;
  LPDRIVER_INFO_3A  lpDriverInfo;
  UINT              HelpMessageID;
  HICON             hCollateIcon;    /* PrintDlg only */
  HICON             hNoCollateIcon;  /* PrintDlg only */
  HICON             hPortraitIcon;   /* PrintSetupDlg only */
  HICON             hLandscapeIcon;  /* PrintSetupDlg only */
  HWND              hwndUpDown;
} PRINT_PTRA;

typedef struct
{
  LPDEVMODEW        lpDevMode;
  LPPRINTDLGW       lpPrintDlg;
  LPPRINTER_INFO_2W lpPrinterInfo;
  LPDRIVER_INFO_3W  lpDriverInfo;
  UINT              HelpMessageID;
  HICON             hCollateIcon;    /* PrintDlg only */
  HICON             hNoCollateIcon;  /* PrintDlg only */
  HICON             hPortraitIcon;   /* PrintSetupDlg only */
  HICON             hLandscapeIcon;  /* PrintSetupDlg only */
  HWND              hwndUpDown;
} PRINT_PTRW;

85
/* Debugging info */
86 87 88 89 90 91
struct pd_flags
{
  DWORD  flag;
  LPCSTR name;
};

92
static const struct pd_flags psd_flags[] = {
93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111
  {PSD_MINMARGINS,"PSD_MINMARGINS"},
  {PSD_MARGINS,"PSD_MARGINS"},
  {PSD_INTHOUSANDTHSOFINCHES,"PSD_INTHOUSANDTHSOFINCHES"},
  {PSD_INHUNDREDTHSOFMILLIMETERS,"PSD_INHUNDREDTHSOFMILLIMETERS"},
  {PSD_DISABLEMARGINS,"PSD_DISABLEMARGINS"},
  {PSD_DISABLEPRINTER,"PSD_DISABLEPRINTER"},
  {PSD_NOWARNING,"PSD_NOWARNING"},
  {PSD_DISABLEORIENTATION,"PSD_DISABLEORIENTATION"},
  {PSD_RETURNDEFAULT,"PSD_RETURNDEFAULT"},
  {PSD_DISABLEPAPER,"PSD_DISABLEPAPER"},
  {PSD_SHOWHELP,"PSD_SHOWHELP"},
  {PSD_ENABLEPAGESETUPHOOK,"PSD_ENABLEPAGESETUPHOOK"},
  {PSD_ENABLEPAGESETUPTEMPLATE,"PSD_ENABLEPAGESETUPTEMPLATE"},
  {PSD_ENABLEPAGESETUPTEMPLATEHANDLE,"PSD_ENABLEPAGESETUPTEMPLATEHANDLE"},
  {PSD_ENABLEPAGEPAINTHOOK,"PSD_ENABLEPAGEPAINTHOOK"},
  {PSD_DISABLEPAGEPAINTING,"PSD_DISABLEPAGEPAINTING"},
  {-1, NULL}
};

112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136
static const struct pd_flags pd_flags[] = {
  {PD_SELECTION, "PD_SELECTION "},
  {PD_PAGENUMS, "PD_PAGENUMS "},
  {PD_NOSELECTION, "PD_NOSELECTION "},
  {PD_NOPAGENUMS, "PD_NOPAGENUMS "},
  {PD_COLLATE, "PD_COLLATE "},
  {PD_PRINTTOFILE, "PD_PRINTTOFILE "},
  {PD_PRINTSETUP, "PD_PRINTSETUP "},
  {PD_NOWARNING, "PD_NOWARNING "},
  {PD_RETURNDC, "PD_RETURNDC "},
  {PD_RETURNIC, "PD_RETURNIC "},
  {PD_RETURNDEFAULT, "PD_RETURNDEFAULT "},
  {PD_SHOWHELP, "PD_SHOWHELP "},
  {PD_ENABLEPRINTHOOK, "PD_ENABLEPRINTHOOK "},
  {PD_ENABLESETUPHOOK, "PD_ENABLESETUPHOOK "},
  {PD_ENABLEPRINTTEMPLATE, "PD_ENABLEPRINTTEMPLATE "},
  {PD_ENABLESETUPTEMPLATE, "PD_ENABLESETUPTEMPLATE "},
  {PD_ENABLEPRINTTEMPLATEHANDLE, "PD_ENABLEPRINTTEMPLATEHANDLE "},
  {PD_ENABLESETUPTEMPLATEHANDLE, "PD_ENABLESETUPTEMPLATEHANDLE "},
  {PD_USEDEVMODECOPIES, "PD_USEDEVMODECOPIES[ANDCOLLATE] "},
  {PD_DISABLEPRINTTOFILE, "PD_DISABLEPRINTTOFILE "},
  {PD_HIDEPRINTTOFILE, "PD_HIDEPRINTTOFILE "},
  {PD_NONETWORKBUTTON, "PD_NONETWORKBUTTON "},
  {-1, NULL}
};
137 138
/* address of wndproc for subclassed Static control */
static WNDPROC lpfnStaticWndProc;
139
static WNDPROC edit_wndproc;
140 141
/* the text of the fake document to render for the Page Setup dialog */
static WCHAR wszFakeDocumentText[1024];
142 143 144 145
static const WCHAR pd32_collateW[] = { 'P', 'D', '3', '2', '_', 'C', 'O', 'L', 'L', 'A', 'T', 'E', 0 };
static const WCHAR pd32_nocollateW[] = { 'P', 'D', '3', '2', '_', 'N', 'O', 'C', 'O', 'L', 'L', 'A', 'T', 'E', 0 };
static const WCHAR pd32_portraitW[] = { 'P', 'D', '3', '2', '_', 'P', 'O', 'R', 'T', 'R', 'A', 'I', 'T', 0 };
static const WCHAR pd32_landscapeW[] = { 'P', 'D', '3', '2', '_', 'L', 'A', 'N', 'D', 'S', 'C', 'A', 'P', 'E', 0 };
146 147 148
static const WCHAR printdlg_prop[] = {'_','_','W','I','N','E','_','P','R','I','N','T','D','L','G','D','A','T','A',0};
static const WCHAR pagesetupdlg_prop[] = { '_', '_', 'W', 'I', 'N', 'E', '_', 'P', 'A', 'G', 'E',
                                           'S', 'E', 'T', 'U', 'P', 'D', 'L', 'G', 'D', 'A', 'T', 'A', 0 };
149

150

151 152 153 154 155 156 157 158 159 160 161 162
static LPWSTR strdupW(LPCWSTR p)
{
    LPWSTR ret;
    DWORD len;

    if(!p) return NULL;
    len = (strlenW(p) + 1) * sizeof(WCHAR);
    ret = HeapAlloc(GetProcessHeap(), 0, len);
    memcpy(ret, p, len);
    return ret;
}

163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202
/***********************************************************
 * convert_to_devmodeA
 *
 * Creates an ansi copy of supplied devmode
 */
static DEVMODEA *convert_to_devmodeA(const DEVMODEW *dmW)
{
    DEVMODEA *dmA;
    DWORD size;

    if (!dmW) return NULL;
    size = dmW->dmSize - CCHDEVICENAME -
                        ((dmW->dmSize > FIELD_OFFSET(DEVMODEW, dmFormName)) ? CCHFORMNAME : 0);

    dmA = HeapAlloc(GetProcessHeap(), 0, size + dmW->dmDriverExtra);
    if (!dmA) return NULL;

    WideCharToMultiByte(CP_ACP, 0, dmW->dmDeviceName, -1,
                        (LPSTR)dmA->dmDeviceName, CCHDEVICENAME, NULL, NULL);

    if (FIELD_OFFSET(DEVMODEW, dmFormName) >= dmW->dmSize)
    {
        memcpy(&dmA->dmSpecVersion, &dmW->dmSpecVersion,
               dmW->dmSize - FIELD_OFFSET(DEVMODEW, dmSpecVersion));
    }
    else
    {
        memcpy(&dmA->dmSpecVersion, &dmW->dmSpecVersion,
               FIELD_OFFSET(DEVMODEW, dmFormName) - FIELD_OFFSET(DEVMODEW, dmSpecVersion));
        WideCharToMultiByte(CP_ACP, 0, dmW->dmFormName, -1,
                            (LPSTR)dmA->dmFormName, CCHFORMNAME, NULL, NULL);

        memcpy(&dmA->dmLogPixels, &dmW->dmLogPixels, dmW->dmSize - FIELD_OFFSET(DEVMODEW, dmLogPixels));
    }

    dmA->dmSize = size;
    memcpy((char *)dmA + dmA->dmSize, (const char *)dmW + dmW->dmSize, dmW->dmDriverExtra);
    return dmA;
}

203
/***********************************************************************
204
 *    PRINTDLG_OpenDefaultPrinter
205
 *
206 207
 * Returns a winspool printer handle to the default printer in *hprn
 * Caller must call ClosePrinter on the handle
208
 *
209
 * Returns TRUE on success else FALSE
210
 */
211
static BOOL PRINTDLG_OpenDefaultPrinter(HANDLE *hprn)
212
{
213 214
    WCHAR buf[260];
    DWORD dwBufLen = sizeof(buf) / sizeof(buf[0]);
215
    BOOL res;
216
    if(!GetDefaultPrinterW(buf, &dwBufLen))
217
        return FALSE;
218
    res = OpenPrinterW(buf, hprn, NULL);
219
    if (!res)
220
        WARN("Could not open printer %s\n", debugstr_w(buf));
221
    return res;
222
}
223

224 225 226 227 228 229 230 231 232 233 234 235 236
/***********************************************************************
 *    PRINTDLG_SetUpPrinterListCombo
 *
 * Initializes printer list combox.
 * hDlg:  HWND of dialog
 * id:    Control id of combo
 * name:  Name of printer to select
 *
 * Initializes combo with list of available printers.  Selects printer 'name'
 * If name is NULL or does not exist select the default printer.
 *
 * Returns number of printers added to list.
 */
237
static INT PRINTDLG_SetUpPrinterListComboA(HWND hDlg, UINT id, LPCSTR name)
238 239 240 241 242 243
{
    DWORD needed, num;
    INT i;
    LPPRINTER_INFO_2A pi;
    EnumPrintersA(PRINTER_ENUM_LOCAL, NULL, 2, NULL, 0, &needed, &num);
    pi = HeapAlloc(GetProcessHeap(), 0, needed);
244
    EnumPrintersA(PRINTER_ENUM_LOCAL, NULL, 2, (LPBYTE)pi, needed, &needed,
245 246
		  &num);

247 248
    SendDlgItemMessageA(hDlg, id, CB_RESETCONTENT, 0, 0);
    
249 250 251
    for(i = 0; i < num; i++) {
        SendDlgItemMessageA(hDlg, id, CB_ADDSTRING, 0,
			    (LPARAM)pi[i].pPrinterName );
252
    }
253 254 255 256 257 258
    HeapFree(GetProcessHeap(), 0, pi);
    if(!name ||
       (i = SendDlgItemMessageA(hDlg, id, CB_FINDSTRINGEXACT, -1,
				(LPARAM)name)) == CB_ERR) {

        char buf[260];
259
        DWORD dwBufLen = sizeof(buf);
260 261 262
        if (name != NULL)
            WARN("Can't find %s in printer list so trying to find default\n",
	        debugstr_a(name));
263
	if(!GetDefaultPrinterA(buf, &dwBufLen))
264 265 266
	    return num;
	i = SendDlgItemMessageA(hDlg, id, CB_FINDSTRINGEXACT, -1, (LPARAM)buf);
	if(i == CB_ERR)
267
	    FIXME("Can't find default printer in printer list\n");
268
    }
269 270
    SendDlgItemMessageA(hDlg, id, CB_SETCURSEL, i, 0);
    return num;
271 272
}

273 274 275 276 277 278 279
static INT PRINTDLG_SetUpPrinterListComboW(HWND hDlg, UINT id, LPCWSTR name)
{
    DWORD needed, num;
    INT i;
    LPPRINTER_INFO_2W pi;
    EnumPrintersW(PRINTER_ENUM_LOCAL, NULL, 2, NULL, 0, &needed, &num);
    pi = HeapAlloc(GetProcessHeap(), 0, needed);
280
    EnumPrintersW(PRINTER_ENUM_LOCAL, NULL, 2, (LPBYTE)pi, needed, &needed,
281 282 283 284 285 286 287 288 289 290
		  &num);

    for(i = 0; i < num; i++) {
        SendDlgItemMessageW(hDlg, id, CB_ADDSTRING, 0,
			    (LPARAM)pi[i].pPrinterName );
    }
    HeapFree(GetProcessHeap(), 0, pi);
    if(!name ||
       (i = SendDlgItemMessageW(hDlg, id, CB_FINDSTRINGEXACT, -1,
				(LPARAM)name)) == CB_ERR) {
291 292
        WCHAR buf[260];
        DWORD dwBufLen = sizeof(buf)/sizeof(buf[0]);
293 294 295
        if (name != NULL)
            WARN("Can't find %s in printer list so trying to find default\n",
	        debugstr_w(name));
296
	if(!GetDefaultPrinterW(buf, &dwBufLen))
297
	    return num;
298
	i = SendDlgItemMessageW(hDlg, id, CB_FINDSTRINGEXACT, -1, (LPARAM)buf);
299
	if(i == CB_ERR)
300
	    TRACE("Can't find default printer in printer list\n");
301 302 303 304 305
    }
    SendDlgItemMessageW(hDlg, id, CB_SETCURSEL, i, 0);
    return num;
}

306
/***********************************************************************
307
 *             PRINTDLG_CreateDevNames          [internal]
308 309
 *
 *
310
 *   creates a DevNames structure.
311
 *
312
 *  (NB. when we handle unicode the offsets will be in wchars).
313
 */
314 315
static BOOL PRINTDLG_CreateDevNames(HGLOBAL *hmem, const char* DeviceDriverName,
				    const char* DeviceName, const char* OutputPort)
316
{
317 318 319 320 321
    long size;
    char*   pDevNamesSpace;
    char*   pTempPtr;
    LPDEVNAMES lpDevNames;
    char buf[260];
322
    DWORD dwBufLen = sizeof(buf);
323

324 325 326 327
    size = strlen(DeviceDriverName) + 1
            + strlen(DeviceName) + 1
            + strlen(OutputPort) + 1
            + sizeof(DEVNAMES);
328

329 330
    if(*hmem)
        *hmem = GlobalReAlloc(*hmem, size, GMEM_MOVEABLE);
331
    else
332 333
        *hmem = GlobalAlloc(GMEM_MOVEABLE, size);
    if (*hmem == 0)
334
        return FALSE;
335

336 337
    pDevNamesSpace = GlobalLock(*hmem);
    lpDevNames = (LPDEVNAMES) pDevNamesSpace;
338

339 340 341
    pTempPtr = pDevNamesSpace + sizeof(DEVNAMES);
    strcpy(pTempPtr, DeviceDriverName);
    lpDevNames->wDriverOffset = pTempPtr - pDevNamesSpace;
342

343 344 345
    pTempPtr += strlen(DeviceDriverName) + 1;
    strcpy(pTempPtr, DeviceName);
    lpDevNames->wDeviceOffset = pTempPtr - pDevNamesSpace;
346

347 348 349 350
    pTempPtr += strlen(DeviceName) + 1;
    strcpy(pTempPtr, OutputPort);
    lpDevNames->wOutputOffset = pTempPtr - pDevNamesSpace;

351
    GetDefaultPrinterA(buf, &dwBufLen);
352 353 354 355
    lpDevNames->wDefault = (strcmp(buf, DeviceName) == 0) ? 1 : 0;
    GlobalUnlock(*hmem);
    return TRUE;
}
356

357
static BOOL PRINTDLG_CreateDevNamesW(HGLOBAL *hmem, LPCWSTR DeviceDriverName,
358 359 360 361 362 363 364
				    LPCWSTR DeviceName, LPCWSTR OutputPort)
{
    long size;
    LPWSTR   pDevNamesSpace;
    LPWSTR   pTempPtr;
    LPDEVNAMES lpDevNames;
    WCHAR bufW[260];
365
    DWORD dwBufLen = sizeof(bufW) / sizeof(WCHAR);
366 367 368 369 370

    size = sizeof(WCHAR)*lstrlenW(DeviceDriverName) + 2
            + sizeof(WCHAR)*lstrlenW(DeviceName) + 2
            + sizeof(WCHAR)*lstrlenW(OutputPort) + 2
            + sizeof(DEVNAMES);
371

372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388
    if(*hmem)
        *hmem = GlobalReAlloc(*hmem, size, GMEM_MOVEABLE);
    else
        *hmem = GlobalAlloc(GMEM_MOVEABLE, size);
    if (*hmem == 0)
        return FALSE;

    pDevNamesSpace = GlobalLock(*hmem);
    lpDevNames = (LPDEVNAMES) pDevNamesSpace;

    pTempPtr = (LPWSTR)((LPDEVNAMES)pDevNamesSpace + 1);
    lstrcpyW(pTempPtr, DeviceDriverName);
    lpDevNames->wDriverOffset = pTempPtr - pDevNamesSpace;

    pTempPtr += lstrlenW(DeviceDriverName) + 1;
    lstrcpyW(pTempPtr, DeviceName);
    lpDevNames->wDeviceOffset = pTempPtr - pDevNamesSpace;
389

390 391 392 393
    pTempPtr += lstrlenW(DeviceName) + 1;
    lstrcpyW(pTempPtr, OutputPort);
    lpDevNames->wOutputOffset = pTempPtr - pDevNamesSpace;

394
    GetDefaultPrinterW(bufW, &dwBufLen);
395 396 397 398 399
    lpDevNames->wDefault = (lstrcmpW(bufW, DeviceName) == 0) ? 1 : 0;
    GlobalUnlock(*hmem);
    return TRUE;
}

400
/***********************************************************************
401 402 403
 *             PRINTDLG_UpdatePrintDlg          [internal]
 *
 *
Francois Gouget's avatar
Francois Gouget committed
404
 *   updates the PrintDlg structure for return values.
405
 *
406 407
 * RETURNS
 *   FALSE if user is not allowed to close (i.e. wrong nTo or nFrom values)
Francois Gouget's avatar
Francois Gouget committed
408
 *   TRUE  if successful.
409
 */
410
static BOOL PRINTDLG_UpdatePrintDlgA(HWND hDlg,
411
				    PRINT_PTRA* PrintStructures)
412
{
413
    LPPRINTDLGA       lppd = PrintStructures->lpPrintDlg;
414 415 416 417
    PDEVMODEA         lpdm = PrintStructures->lpDevMode;
    LPPRINTER_INFO_2A pi = PrintStructures->lpPrinterInfo;


418 419 420 421
    if(!lpdm) {
	FIXME("No lpdm ptr?\n");
	return FALSE;
    }
422 423 424 425 426 427 428 429 430


    if(!(lppd->Flags & PD_PRINTSETUP)) {
        /* check whether nFromPage and nToPage are within range defined by
	 * nMinPage and nMaxPage
	 */
        if (IsDlgButtonChecked(hDlg, rad3) == BST_CHECKED) { /* Pages */
	    WORD nToPage;
	    WORD nFromPage;
431
            BOOL translated;
432
	    nFromPage = GetDlgItemInt(hDlg, edt1, NULL, FALSE);
433 434 435 436 437
	    nToPage   = GetDlgItemInt(hDlg, edt2, &translated, FALSE);

	    /* if no ToPage value is entered, use the FromPage value */
	    if(!translated) nToPage = nFromPage;

438 439
	    if (nFromPage < lppd->nMinPage || nFromPage > lppd->nMaxPage ||
		nToPage < lppd->nMinPage || nToPage > lppd->nMaxPage) {
440 441 442 443 444 445
	        WCHAR resourcestr[256];
		WCHAR resultstr[256];
		LoadStringW(COMDLG32_hInstance, PD32_INVALID_PAGE_RANGE, resourcestr, 255);
		wsprintfW(resultstr,resourcestr, lppd->nMinPage, lppd->nMaxPage);
		LoadStringW(COMDLG32_hInstance, PD32_PRINT_TITLE, resourcestr, 255);
		MessageBoxW(hDlg, resultstr, resourcestr, MB_OK | MB_ICONWARNING);
446 447 448 449
		return FALSE;
	    }
	    lppd->nFromPage = nFromPage;
	    lppd->nToPage   = nToPage;
450
	    lppd->Flags |= PD_PAGENUMS;
451
	}
452 453
	else
	    lppd->Flags &= ~PD_PAGENUMS;
454

455 456 457 458 459
        if (IsDlgButtonChecked(hDlg, rad2) == BST_CHECKED) /* Selection */
            lppd->Flags |= PD_SELECTION;
        else
            lppd->Flags &= ~PD_SELECTION;

460
	if (IsDlgButtonChecked(hDlg, chx1) == BST_CHECKED) {/* Print to file */
461
	    static char file[] = "FILE:";
462
	    lppd->Flags |= PD_PRINTTOFILE;
463
	    pi->pPortName = file;
464
	}
465

466 467 468
	if (IsDlgButtonChecked(hDlg, chx2) == BST_CHECKED) { /* Collate */
	    FIXME("Collate lppd not yet implemented as output\n");
	}
469

470 471 472 473 474 475 476 477 478 479
	/* set PD_Collate and nCopies */
	if (lppd->Flags & PD_USEDEVMODECOPIESANDCOLLATE) {
	  /*  The application doesn't support multiple copies or collate...
	   */
	    lppd->Flags &= ~PD_COLLATE;
	    lppd->nCopies = 1;
	  /* if the printer driver supports it... store info there
	   * otherwise no collate & multiple copies !
	   */
	    if (lpdm->dmFields & DM_COLLATE)
480
	        lpdm->dmCollate =
481 482
		  (IsDlgButtonChecked(hDlg, chx2) == BST_CHECKED);
	    if (lpdm->dmFields & DM_COPIES)
483
	        lpdm->u1.s1.dmCopies = GetDlgItemInt(hDlg, edt3, NULL, FALSE);
484
	} else {
485
            /* Application is responsible for multiple copies */
486 487 488 489 490
	    if (IsDlgButtonChecked(hDlg, chx2) == BST_CHECKED)
	        lppd->Flags |= PD_COLLATE;
            else
               lppd->Flags &= ~PD_COLLATE;
            lppd->nCopies = GetDlgItemInt(hDlg, edt3, NULL, FALSE);
491 492
            /* multiple copies already included in the document. Driver must print only one copy */
            lpdm->u1.s1.dmCopies = 1;
493
	}
494 495 496 497 498 499 500 501 502 503 504 505 506 507 508

	/* Print quality, PrintDlg16 */
	if(GetDlgItem(hDlg, cmb1))
	{
	    HWND hQuality = GetDlgItem(hDlg, cmb1);
	    int Sel = SendMessageA(hQuality, CB_GETCURSEL, 0, 0);

	    if(Sel != CB_ERR)
	    {
		LONG dpi = SendMessageA(hQuality, CB_GETITEMDATA, Sel, 0);
		lpdm->dmFields |= DM_PRINTQUALITY | DM_YRESOLUTION;
		lpdm->u1.s1.dmPrintQuality = LOWORD(dpi);
		lpdm->dmYResolution = HIWORD(dpi);
	    }
	}
509 510
    }
    return TRUE;
511 512
}

513
static BOOL PRINTDLG_UpdatePrintDlgW(HWND hDlg,
514 515
				    PRINT_PTRW* PrintStructures)
{
516
    LPPRINTDLGW       lppd = PrintStructures->lpPrintDlg;
517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533
    PDEVMODEW         lpdm = PrintStructures->lpDevMode;
    LPPRINTER_INFO_2W pi = PrintStructures->lpPrinterInfo;


    if(!lpdm) {
	FIXME("No lpdm ptr?\n");
	return FALSE;
    }


    if(!(lppd->Flags & PD_PRINTSETUP)) {
        /* check whether nFromPage and nToPage are within range defined by
	 * nMinPage and nMaxPage
	 */
        if (IsDlgButtonChecked(hDlg, rad3) == BST_CHECKED) { /* Pages */
	    WORD nToPage;
	    WORD nFromPage;
534
            BOOL translated;
535
	    nFromPage = GetDlgItemInt(hDlg, edt1, NULL, FALSE);
536 537 538 539 540
	    nToPage   = GetDlgItemInt(hDlg, edt2, &translated, FALSE);

	    /* if no ToPage value is entered, use the FromPage value */
	    if(!translated) nToPage = nFromPage;

541 542
	    if (nFromPage < lppd->nMinPage || nFromPage > lppd->nMaxPage ||
		nToPage < lppd->nMinPage || nToPage > lppd->nMaxPage) {
543 544 545
	        WCHAR resourcestr[256];
		WCHAR resultstr[256];
		LoadStringW(COMDLG32_hInstance, PD32_INVALID_PAGE_RANGE,
546
			    resourcestr, 255);
547 548
		wsprintfW(resultstr,resourcestr, lppd->nMinPage, lppd->nMaxPage);
		LoadStringW(COMDLG32_hInstance, PD32_PRINT_TITLE,
549
			    resourcestr, 255);
550
		MessageBoxW(hDlg, resultstr, resourcestr,
551 552 553 554 555
			    MB_OK | MB_ICONWARNING);
		return FALSE;
	    }
	    lppd->nFromPage = nFromPage;
	    lppd->nToPage   = nToPage;
556
	    lppd->Flags |= PD_PAGENUMS;
557
	}
558 559
	else
	    lppd->Flags &= ~PD_PAGENUMS;
560

561 562 563 564 565
        if (IsDlgButtonChecked(hDlg, rad2) == BST_CHECKED) /* Selection */
            lppd->Flags |= PD_SELECTION;
        else
            lppd->Flags &= ~PD_SELECTION;

566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585
	if (IsDlgButtonChecked(hDlg, chx1) == BST_CHECKED) {/* Print to file */
	    static WCHAR file[] = {'F','I','L','E',':',0};
	    lppd->Flags |= PD_PRINTTOFILE;
	    pi->pPortName = file;
	}

	if (IsDlgButtonChecked(hDlg, chx2) == BST_CHECKED) { /* Collate */
	    FIXME("Collate lppd not yet implemented as output\n");
	}

	/* set PD_Collate and nCopies */
	if (lppd->Flags & PD_USEDEVMODECOPIESANDCOLLATE) {
	  /*  The application doesn't support multiple copies or collate...
	   */
	    lppd->Flags &= ~PD_COLLATE;
	    lppd->nCopies = 1;
	  /* if the printer driver supports it... store info there
	   * otherwise no collate & multiple copies !
	   */
	    if (lpdm->dmFields & DM_COLLATE)
586
	        lpdm->dmCollate =
587 588
		  (IsDlgButtonChecked(hDlg, chx2) == BST_CHECKED);
	    if (lpdm->dmFields & DM_COPIES)
589
	        lpdm->u1.s1.dmCopies = GetDlgItemInt(hDlg, edt3, NULL, FALSE);
590 591 592 593 594 595 596 597 598 599 600
	} else {
	    if (IsDlgButtonChecked(hDlg, chx2) == BST_CHECKED)
	        lppd->Flags |= PD_COLLATE;
            else
               lppd->Flags &= ~PD_COLLATE;
            lppd->nCopies = GetDlgItemInt(hDlg, edt3, NULL, FALSE);
	}
    }
    return TRUE;
}

601 602
/************************************************************************
 * PRINTDLG_SetUpPaperComboBox
603
 *
604 605 606
 * Initialize either the papersize or inputslot combos of the Printer Setup
 * dialog.  We store the associated word (eg DMPAPER_A4) as the item data.
 * We also try to re-select the old selection.
607
 */
608
static BOOL PRINTDLG_SetUpPaperComboBoxA(HWND hDlg,
609
					int   nIDComboBox,
610
					char* PrinterName,
611 612
					char* PortName,
					LPDEVMODEA dm)
613 614
{
    int     i;
615
    int     NrOfEntries;
616
    char*   Names;
617 618 619
    WORD*   Words;
    DWORD   Sel;
    WORD    oldWord = 0;
620 621 622
    int     NamesSize;
    int     fwCapability_Names;
    int     fwCapability_Words;
623

624
    TRACE(" Printer: %s, Port: %s, ComboID: %d\n",PrinterName,PortName,nIDComboBox);
625

626
    /* query the dialog box for the current selected value */
627 628
    Sel = SendDlgItemMessageA(hDlg, nIDComboBox, CB_GETCURSEL, 0, 0);
    if(Sel != CB_ERR) {
629 630 631 632 633 634 635 636 637 638
        /* we enter here only if a different printer is selected after
         * the Print Setup dialog is opened. The current settings are
         * stored into the newly selected printer.
         */
        oldWord = SendDlgItemMessageA(hDlg, nIDComboBox, CB_GETITEMDATA,
                                      Sel, 0);
        if (dm) {
            if (nIDComboBox == cmb2)
                dm->u1.s1.dmPaperSize = oldWord;
            else
639
                dm->u1.s1.dmDefaultSource = oldWord;
640 641 642 643 644 645 646 647 648 649 650
        }
    }
    else {
        /* we enter here only when the Print setup dialog is initially
         * opened. In this case the settings are restored from when
         * the dialog was last closed.
         */
        if (dm) {
            if (nIDComboBox == cmb2)
                oldWord = dm->u1.s1.dmPaperSize;
            else
651
                oldWord = dm->u1.s1.dmDefaultSource;
652
        }
653
    }
654

655
    if (nIDComboBox == cmb2) {
656 657 658
         NamesSize          = 64;
         fwCapability_Names = DC_PAPERNAMES;
         fwCapability_Words = DC_PAPERS;
659
    } else {
660 661 662 663
         nIDComboBox        = cmb3;
         NamesSize          = 24;
         fwCapability_Names = DC_BINNAMES;
         fwCapability_Words = DC_BINS;
664
    }
665

666
    NrOfEntries = DeviceCapabilitiesA(PrinterName, PortName,
667
                                      fwCapability_Names, NULL, dm);
668
    if (NrOfEntries == 0)
669
         WARN("no Name Entries found!\n");
670 671
    else if (NrOfEntries < 0)
         return FALSE;
672 673 674 675 676 677 678

    if(DeviceCapabilitiesA(PrinterName, PortName, fwCapability_Words, NULL, dm)
       != NrOfEntries) {
        ERR("Number of caps is different\n");
	NrOfEntries = 0;
    }

679
    Names = HeapAlloc(GetProcessHeap(),0, NrOfEntries*sizeof(char)*NamesSize);
680
    Words = HeapAlloc(GetProcessHeap(),0, NrOfEntries*sizeof(WORD));
681
    NrOfEntries = DeviceCapabilitiesA(PrinterName, PortName,
682 683 684 685
                                      fwCapability_Names, Names, dm);
    NrOfEntries = DeviceCapabilitiesA(PrinterName, PortName,
				      fwCapability_Words, (LPSTR)Words, dm);

686 687
    /* reset any current content in the combobox */
    SendDlgItemMessageA(hDlg, nIDComboBox, CB_RESETCONTENT, 0, 0);
688

689
    /* store new content */
690 691 692
    for (i = 0; i < NrOfEntries; i++) {
        DWORD pos = SendDlgItemMessageA(hDlg, nIDComboBox, CB_ADDSTRING, 0,
					(LPARAM)(&Names[i*NamesSize]) );
693
	SendDlgItemMessageA(hDlg, nIDComboBox, CB_SETITEMDATA, pos,
694 695
			    Words[i]);
    }
696

697 698 699 700 701 702 703 704 705 706 707
    /* Look for old selection - can't do this is previous loop since
       item order will change as more items are added */
    Sel = 0;
    for (i = 0; i < NrOfEntries; i++) {
        if(SendDlgItemMessageA(hDlg, nIDComboBox, CB_GETITEMDATA, i, 0) ==
	   oldWord) {
	    Sel = i;
	    break;
	}
    }
    SendDlgItemMessageA(hDlg, nIDComboBox, CB_SETCURSEL, Sel, 0);
708

709 710 711 712
    HeapFree(GetProcessHeap(),0,Words);
    HeapFree(GetProcessHeap(),0,Names);
    return TRUE;
}
713

714 715
static BOOL PRINTDLG_SetUpPaperComboBoxW(HWND hDlg,
					int   nIDComboBox,
716 717
					const WCHAR* PrinterName,
					const WCHAR* PortName,
718
					LPDEVMODEW dm)
719
{
720 721 722 723 724 725 726 727 728
    int     i;
    int     NrOfEntries;
    WCHAR*  Names;
    WORD*   Words;
    DWORD   Sel;
    WORD    oldWord = 0;
    int     NamesSize;
    int     fwCapability_Names;
    int     fwCapability_Words;
729

730
    TRACE(" Printer: %s, Port: %s, ComboID: %d\n",debugstr_w(PrinterName),debugstr_w(PortName),nIDComboBox);
731

732
    /* query the dialog box for the current selected value */
733
    Sel = SendDlgItemMessageW(hDlg, nIDComboBox, CB_GETCURSEL, 0, 0);
734 735 736 737 738
    if(Sel != CB_ERR) {
        /* we enter here only if a different printer is selected after
         * the Print Setup dialog is opened. The current settings are
         * stored into the newly selected printer.
         */
739
        oldWord = SendDlgItemMessageW(hDlg, nIDComboBox, CB_GETITEMDATA,
740 741 742 743 744
                                      Sel, 0);
        if (dm) {
            if (nIDComboBox == cmb2)
                dm->u1.s1.dmPaperSize = oldWord;
            else
745
                dm->u1.s1.dmDefaultSource = oldWord;
746 747 748 749 750 751 752 753 754 755 756
        }
    }
    else {
        /* we enter here only when the Print setup dialog is initially
         * opened. In this case the settings are restored from when
         * the dialog was last closed.
         */
        if (dm) {
            if (nIDComboBox == cmb2)
                oldWord = dm->u1.s1.dmPaperSize;
            else
757
                oldWord = dm->u1.s1.dmDefaultSource;
758
        }
759
    }
760

761 762 763 764 765 766 767 768 769 770
    if (nIDComboBox == cmb2) {
         NamesSize          = 64;
         fwCapability_Names = DC_PAPERNAMES;
         fwCapability_Words = DC_PAPERS;
    } else {
         nIDComboBox        = cmb3;
         NamesSize          = 24;
         fwCapability_Names = DC_BINNAMES;
         fwCapability_Words = DC_BINS;
    }
771

772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789
    NrOfEntries = DeviceCapabilitiesW(PrinterName, PortName,
                                      fwCapability_Names, NULL, dm);
    if (NrOfEntries == 0)
         WARN("no Name Entries found!\n");
    else if (NrOfEntries < 0)
         return FALSE;

    if(DeviceCapabilitiesW(PrinterName, PortName, fwCapability_Words, NULL, dm)
       != NrOfEntries) {
        ERR("Number of caps is different\n");
	NrOfEntries = 0;
    }

    Names = HeapAlloc(GetProcessHeap(),0, NrOfEntries*sizeof(WCHAR)*NamesSize);
    Words = HeapAlloc(GetProcessHeap(),0, NrOfEntries*sizeof(WORD));
    NrOfEntries = DeviceCapabilitiesW(PrinterName, PortName,
                                      fwCapability_Names, Names, dm);
    NrOfEntries = DeviceCapabilitiesW(PrinterName, PortName,
790
                                      fwCapability_Words, Words, dm);
791 792

    /* reset any current content in the combobox */
793
    SendDlgItemMessageW(hDlg, nIDComboBox, CB_RESETCONTENT, 0, 0);
794

795 796 797 798
    /* store new content */
    for (i = 0; i < NrOfEntries; i++) {
        DWORD pos = SendDlgItemMessageW(hDlg, nIDComboBox, CB_ADDSTRING, 0,
					(LPARAM)(&Names[i*NamesSize]) );
799
	SendDlgItemMessageW(hDlg, nIDComboBox, CB_SETITEMDATA, pos,
800 801 802 803 804 805 806
			    Words[i]);
    }

    /* Look for old selection - can't do this is previous loop since
       item order will change as more items are added */
    Sel = 0;
    for (i = 0; i < NrOfEntries; i++) {
807
        if(SendDlgItemMessageW(hDlg, nIDComboBox, CB_GETITEMDATA, i, 0) ==
808 809 810 811 812
	   oldWord) {
	    Sel = i;
	    break;
	}
    }
813
    SendDlgItemMessageW(hDlg, nIDComboBox, CB_SETCURSEL, Sel, 0);
814 815 816 817 818 819 820 821 822 823

    HeapFree(GetProcessHeap(),0,Words);
    HeapFree(GetProcessHeap(),0,Names);
    return TRUE;
}


/***********************************************************************
 *               PRINTDLG_UpdatePrinterInfoTexts               [internal]
 */
824
static void PRINTDLG_UpdatePrinterInfoTextsA(HWND hDlg, const PRINTER_INFO_2A *pi)
825 826 827 828 829 830 831 832 833 834 835
{
    char   StatusMsg[256];
    char   ResourceString[256];
    int    i;

    /* Status Message */
    StatusMsg[0]='\0';

    /* add all status messages */
    for (i = 0; i < 25; i++) {
        if (pi->Status & (1<<i)) {
836
	    LoadStringA(COMDLG32_hInstance, PD32_PRINTER_STATUS_PAUSED+i,
837 838 839 840 841
			ResourceString, 255);
	    strcat(StatusMsg,ResourceString);
        }
    }
    /* append "ready" */
842
    /* FIXME: status==ready must only be appended if really so.
843
              but how to detect? */
844
    LoadStringA(COMDLG32_hInstance, PD32_PRINTER_STATUS_READY,
845 846
		ResourceString, 255);
    strcat(StatusMsg,ResourceString);
847
    SetDlgItemTextA(hDlg, stc12, StatusMsg);
848 849

    /* set all other printer info texts */
850 851
    SetDlgItemTextA(hDlg, stc11, pi->pDriverName);
    
852
    if (pi->pLocation != NULL && pi->pLocation[0] != '\0')
853
        SetDlgItemTextA(hDlg, stc14, pi->pLocation);
854
    else
855 856
        SetDlgItemTextA(hDlg, stc14, pi->pPortName);
    SetDlgItemTextA(hDlg, stc13, pi->pComment ? pi->pComment : "");
857 858 859
    return;
}

860
static void PRINTDLG_UpdatePrinterInfoTextsW(HWND hDlg, const PRINTER_INFO_2W *pi)
861 862 863
{
    WCHAR   StatusMsg[256];
    WCHAR   ResourceString[256];
864
    static const WCHAR emptyW[] = {0};
865 866 867 868 869 870 871 872
    int    i;

    /* Status Message */
    StatusMsg[0]='\0';

    /* add all status messages */
    for (i = 0; i < 25; i++) {
        if (pi->Status & (1<<i)) {
873
	    LoadStringW(COMDLG32_hInstance, PD32_PRINTER_STATUS_PAUSED+i,
874 875 876 877 878
			ResourceString, 255);
	    lstrcatW(StatusMsg,ResourceString);
        }
    }
    /* append "ready" */
879
    /* FIXME: status==ready must only be appended if really so.
880
              but how to detect? */
881
    LoadStringW(COMDLG32_hInstance, PD32_PRINTER_STATUS_READY,
882 883
		ResourceString, 255);
    lstrcatW(StatusMsg,ResourceString);
884
    SetDlgItemTextW(hDlg, stc12, StatusMsg);
885 886

    /* set all other printer info texts */
887
    SetDlgItemTextW(hDlg, stc11, pi->pDriverName);
888
    if (pi->pLocation != NULL && pi->pLocation[0] != '\0')
889
        SetDlgItemTextW(hDlg, stc14, pi->pLocation);
890
    else
891 892
        SetDlgItemTextW(hDlg, stc14, pi->pPortName);
    SetDlgItemTextW(hDlg, stc13, pi->pComment ? pi->pComment : emptyW);
893 894
}

895

896 897 898 899
/*******************************************************************
 *
 *                 PRINTDLG_ChangePrinter
 *
900
 */
901
static BOOL PRINTDLG_ChangePrinterA(HWND hDlg, char *name, PRINT_PTRA *PrintStructures)
902
{
903
    LPPRINTDLGA lppd = PrintStructures->lpPrintDlg;
904 905 906 907 908
    LPDEVMODEA lpdm = NULL;
    LONG dmSize;
    DWORD needed;
    HANDLE hprn;

909 910
    HeapFree(GetProcessHeap(),0, PrintStructures->lpPrinterInfo);
    HeapFree(GetProcessHeap(),0, PrintStructures->lpDriverInfo);
911 912 913 914 915 916 917 918
    if(!OpenPrinterA(name, &hprn, NULL)) {
        ERR("Can't open printer %s\n", name);
	return FALSE;
    }
    GetPrinterA(hprn, 2, NULL, 0, &needed);
    PrintStructures->lpPrinterInfo = HeapAlloc(GetProcessHeap(),0,needed);
    GetPrinterA(hprn, 2, (LPBYTE)PrintStructures->lpPrinterInfo, needed,
		&needed);
919 920 921 922 923 924 925
    GetPrinterDriverA(hprn, NULL, 3, NULL, 0, &needed);
    PrintStructures->lpDriverInfo = HeapAlloc(GetProcessHeap(),0,needed);
    if (!GetPrinterDriverA(hprn, NULL, 3, (LPBYTE)PrintStructures->lpDriverInfo,
	    needed, &needed)) {
	ERR("GetPrinterDriverA failed for %s, fix your config!\n",PrintStructures->lpPrinterInfo->pPrinterName);
	return FALSE;
    }
926
    ClosePrinter(hprn);
927

928
    PRINTDLG_UpdatePrinterInfoTextsA(hDlg, PrintStructures->lpPrinterInfo);
929

930 931
    HeapFree(GetProcessHeap(), 0, PrintStructures->lpDevMode);
    PrintStructures->lpDevMode = NULL;
932

933 934 935 936
    dmSize = DocumentPropertiesA(0, 0, name, NULL, NULL, 0);
    if(dmSize == -1) {
        ERR("DocumentProperties fails on %s\n", debugstr_a(name));
	return FALSE;
937
    }
938 939 940 941
    PrintStructures->lpDevMode = HeapAlloc(GetProcessHeap(), 0, dmSize);
    dmSize = DocumentPropertiesA(0, 0, name, PrintStructures->lpDevMode, NULL,
				 DM_OUT_BUFFER);
    if(lppd->hDevMode && (lpdm = GlobalLock(lppd->hDevMode)) &&
Mike McCormack's avatar
Mike McCormack committed
942 943
			  !lstrcmpA( (LPSTR) lpdm->dmDeviceName,
				     (LPSTR) PrintStructures->lpDevMode->dmDeviceName)) {
944 945 946
      /* Supplied devicemode matches current printer so try to use it */
        DocumentPropertiesA(0, 0, name, PrintStructures->lpDevMode, lpdm,
			    DM_OUT_BUFFER | DM_IN_BUFFER);
947
    }
948 949 950 951 952 953
    if(lpdm)
        GlobalUnlock(lppd->hDevMode);

    lpdm = PrintStructures->lpDevMode;  /* use this as a shortcut */

    if(!(lppd->Flags & PD_PRINTSETUP)) {
954 955 956 957 958 959
	/* Print range (All/Range/Selection) */
	if(lppd->nFromPage != 0xffff)
	    SetDlgItemInt(hDlg, edt1, lppd->nFromPage, FALSE);
	if(lppd->nToPage != 0xffff)
	    SetDlgItemInt(hDlg, edt2, lppd->nToPage, FALSE);

960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975
	CheckRadioButton(hDlg, rad1, rad3, rad1);		/* default */
	if (lppd->Flags & PD_NOSELECTION)
	    EnableWindow(GetDlgItem(hDlg, rad2), FALSE);
	else
	    if (lppd->Flags & PD_SELECTION)
	        CheckRadioButton(hDlg, rad1, rad3, rad2);
	if (lppd->Flags & PD_NOPAGENUMS) {
	    EnableWindow(GetDlgItem(hDlg, rad3), FALSE);
	    EnableWindow(GetDlgItem(hDlg, stc2),FALSE);
	    EnableWindow(GetDlgItem(hDlg, edt1), FALSE);
	    EnableWindow(GetDlgItem(hDlg, stc3),FALSE);
	    EnableWindow(GetDlgItem(hDlg, edt2), FALSE);
	} else {
	    if (lppd->Flags & PD_PAGENUMS)
	        CheckRadioButton(hDlg, rad1, rad3, rad3);
	}
976 977

	/* Collate pages
978 979 980 981
	 *
	 * FIXME: The ico3 is not displayed for some reason. I don't know why.
	 */
	if (lppd->Flags & PD_COLLATE) {
982
            SendDlgItemMessageA(hDlg, ico3, STM_SETIMAGE, IMAGE_ICON,
983 984 985
				(LPARAM)PrintStructures->hCollateIcon);
	    CheckDlgButton(hDlg, chx2, 1);
	} else {
986
            SendDlgItemMessageA(hDlg, ico3, STM_SETIMAGE, IMAGE_ICON,
987 988 989
				(LPARAM)PrintStructures->hNoCollateIcon);
	    CheckDlgButton(hDlg, chx2, 0);
	}
990

991 992 993
	if (lppd->Flags & PD_USEDEVMODECOPIESANDCOLLATE) {
	  /* if printer doesn't support it: no Collate */
	    if (!(lpdm->dmFields & DM_COLLATE)) {
994 995
	        EnableWindow(GetDlgItem(hDlg, chx2), FALSE);
		EnableWindow(GetDlgItem(hDlg, ico3), FALSE);
996 997
	    }
	}
998

999
	/* nCopies */
1000 1001 1002 1003 1004
	{
	  INT copies;
	  if (lppd->hDevMode == 0)
	      copies = lppd->nCopies;
	  else
1005
	      copies = lpdm->u1.s1.dmCopies;
1006 1007 1008 1009
	  if(copies == 0) copies = 1;
	  else if(copies < 0) copies = MAX_COPIES;
	  SetDlgItemInt(hDlg, edt3, copies, FALSE);
	}
1010 1011 1012 1013

	if (lppd->Flags & PD_USEDEVMODECOPIESANDCOLLATE) {
	  /* if printer doesn't support it: no nCopies */
	    if (!(lpdm->dmFields & DM_COPIES)) {
1014 1015
	        EnableWindow(GetDlgItem(hDlg, edt3), FALSE);
		EnableWindow(GetDlgItem(hDlg, stc5), FALSE);
1016
	    }
1017
	}
1018

1019 1020 1021
	/* print to file */
	CheckDlgButton(hDlg, chx1, (lppd->Flags & PD_PRINTTOFILE) ? 1 : 0);
	if (lppd->Flags & PD_DISABLEPRINTTOFILE)
1022
            EnableWindow(GetDlgItem(hDlg, chx1), FALSE);
1023 1024 1025
	if (lppd->Flags & PD_HIDEPRINTTOFILE)
            ShowWindow(GetDlgItem(hDlg, chx1), SW_HIDE);

1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037
	/* Fill print quality combo, PrintDlg16 */
	if(GetDlgItem(hDlg, cmb1))
	{
	    DWORD numResolutions = DeviceCapabilitiesA(PrintStructures->lpPrinterInfo->pPrinterName,
						       PrintStructures->lpPrinterInfo->pPortName,
						       DC_ENUMRESOLUTIONS, NULL, lpdm);

	    if(numResolutions != -1)
	    {
		HWND hQuality = GetDlgItem(hDlg, cmb1);
		LONG* Resolutions;
		char buf[255];
1038
		DWORD i;
1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080
		int dpiX, dpiY;
		HDC hPrinterDC = CreateDCA(PrintStructures->lpPrinterInfo->pDriverName,
					   PrintStructures->lpPrinterInfo->pPrinterName,
					   0, lpdm);

		Resolutions = HeapAlloc(GetProcessHeap(), 0, numResolutions*sizeof(LONG)*2);
		DeviceCapabilitiesA(PrintStructures->lpPrinterInfo->pPrinterName,
				    PrintStructures->lpPrinterInfo->pPortName,
				    DC_ENUMRESOLUTIONS, (LPSTR)Resolutions, lpdm);

		dpiX = GetDeviceCaps(hPrinterDC, LOGPIXELSX);
		dpiY = GetDeviceCaps(hPrinterDC, LOGPIXELSY);
		DeleteDC(hPrinterDC);

		SendMessageA(hQuality, CB_RESETCONTENT, 0, 0);
		for(i = 0; i < (numResolutions * 2); i += 2)
		{
		    BOOL IsDefault = FALSE;
		    LRESULT Index;

		    if(Resolutions[i] == Resolutions[i+1])
		    {
			if(dpiX == Resolutions[i])
			    IsDefault = TRUE;
			sprintf(buf, "%d dpi", Resolutions[i]);
		    } else
		    {
			if(dpiX == Resolutions[i] && dpiY == Resolutions[i+1])
			    IsDefault = TRUE;
			sprintf(buf, "%d dpi x %d dpi", Resolutions[i], Resolutions[i+1]);
		    }

		    Index = SendMessageA(hQuality, CB_ADDSTRING, 0, (LPARAM)buf);

		    if(IsDefault)
			SendMessageA(hQuality, CB_SETCURSEL, Index, 0);

		    SendMessageA(hQuality, CB_SETITEMDATA, Index, MAKELONG(dpiX,dpiY));
		}
		HeapFree(GetProcessHeap(), 0, Resolutions);
	    }
	}
1081
    } else { /* PD_PRINTSETUP */
1082 1083
      BOOL bPortrait = (lpdm->u1.s1.dmOrientation == DMORIENT_PORTRAIT);

1084 1085 1086 1087 1088 1089 1090 1091 1092
      PRINTDLG_SetUpPaperComboBoxA(hDlg, cmb2,
				  PrintStructures->lpPrinterInfo->pPrinterName,
				  PrintStructures->lpPrinterInfo->pPortName,
				  lpdm);
      PRINTDLG_SetUpPaperComboBoxA(hDlg, cmb3,
				  PrintStructures->lpPrinterInfo->pPrinterName,
				  PrintStructures->lpPrinterInfo->pPortName,
				  lpdm);
      CheckRadioButton(hDlg, rad1, rad2, bPortrait ? rad1: rad2);
1093
      SendDlgItemMessageA(hDlg, ico1, STM_SETIMAGE, IMAGE_ICON,
1094 1095
                          (LPARAM)(bPortrait ? PrintStructures->hPortraitIcon :
                                   PrintStructures->hLandscapeIcon));
1096

1097 1098 1099 1100 1101
    }

    /* help button */
    if ((lppd->Flags & PD_SHOWHELP)==0) {
        /* hide if PD_SHOWHELP not specified */
1102
        ShowWindow(GetDlgItem(hDlg, pshHelp), SW_HIDE);
1103 1104 1105 1106 1107 1108 1109
    }
    return TRUE;
}

static BOOL PRINTDLG_ChangePrinterW(HWND hDlg, WCHAR *name,
				   PRINT_PTRW *PrintStructures)
{
1110
    LPPRINTDLGW lppd = PrintStructures->lpPrintDlg;
1111 1112 1113 1114 1115
    LPDEVMODEW lpdm = NULL;
    LONG dmSize;
    DWORD needed;
    HANDLE hprn;

1116 1117
    HeapFree(GetProcessHeap(),0, PrintStructures->lpPrinterInfo);
    HeapFree(GetProcessHeap(),0, PrintStructures->lpDriverInfo);
1118 1119 1120 1121 1122
    if(!OpenPrinterW(name, &hprn, NULL)) {
        ERR("Can't open printer %s\n", debugstr_w(name));
	return FALSE;
    }
    GetPrinterW(hprn, 2, NULL, 0, &needed);
1123
    PrintStructures->lpPrinterInfo = HeapAlloc(GetProcessHeap(),0,needed);
1124 1125 1126
    GetPrinterW(hprn, 2, (LPBYTE)PrintStructures->lpPrinterInfo, needed,
		&needed);
    GetPrinterDriverW(hprn, NULL, 3, NULL, 0, &needed);
1127
    PrintStructures->lpDriverInfo = HeapAlloc(GetProcessHeap(),0,needed);
1128 1129 1130 1131 1132 1133 1134 1135 1136
    if (!GetPrinterDriverW(hprn, NULL, 3, (LPBYTE)PrintStructures->lpDriverInfo,
	    needed, &needed)) {
	ERR("GetPrinterDriverA failed for %s, fix your config!\n",debugstr_w(PrintStructures->lpPrinterInfo->pPrinterName));
	return FALSE;
    }
    ClosePrinter(hprn);

    PRINTDLG_UpdatePrinterInfoTextsW(hDlg, PrintStructures->lpPrinterInfo);

1137 1138
    HeapFree(GetProcessHeap(), 0, PrintStructures->lpDevMode);
    PrintStructures->lpDevMode = NULL;
1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160

    dmSize = DocumentPropertiesW(0, 0, name, NULL, NULL, 0);
    if(dmSize == -1) {
        ERR("DocumentProperties fails on %s\n", debugstr_w(name));
	return FALSE;
    }
    PrintStructures->lpDevMode = HeapAlloc(GetProcessHeap(), 0, dmSize);
    dmSize = DocumentPropertiesW(0, 0, name, PrintStructures->lpDevMode, NULL,
				 DM_OUT_BUFFER);
    if(lppd->hDevMode && (lpdm = GlobalLock(lppd->hDevMode)) &&
			  !lstrcmpW(lpdm->dmDeviceName,
				  PrintStructures->lpDevMode->dmDeviceName)) {
      /* Supplied devicemode matches current printer so try to use it */
        DocumentPropertiesW(0, 0, name, PrintStructures->lpDevMode, lpdm,
			    DM_OUT_BUFFER | DM_IN_BUFFER);
    }
    if(lpdm)
        GlobalUnlock(lppd->hDevMode);

    lpdm = PrintStructures->lpDevMode;  /* use this as a shortcut */

    if(!(lppd->Flags & PD_PRINTSETUP)) {
1161 1162 1163 1164 1165 1166
	/* Print range (All/Range/Selection) */
	if(lppd->nFromPage != 0xffff)
	    SetDlgItemInt(hDlg, edt1, lppd->nFromPage, FALSE);
	if(lppd->nToPage != 0xffff)
	    SetDlgItemInt(hDlg, edt2, lppd->nToPage, FALSE);

1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182
	CheckRadioButton(hDlg, rad1, rad3, rad1);		/* default */
	if (lppd->Flags & PD_NOSELECTION)
	    EnableWindow(GetDlgItem(hDlg, rad2), FALSE);
	else
	    if (lppd->Flags & PD_SELECTION)
	        CheckRadioButton(hDlg, rad1, rad3, rad2);
	if (lppd->Flags & PD_NOPAGENUMS) {
	    EnableWindow(GetDlgItem(hDlg, rad3), FALSE);
	    EnableWindow(GetDlgItem(hDlg, stc2),FALSE);
	    EnableWindow(GetDlgItem(hDlg, edt1), FALSE);
	    EnableWindow(GetDlgItem(hDlg, stc3),FALSE);
	    EnableWindow(GetDlgItem(hDlg, edt2), FALSE);
	} else {
	    if (lppd->Flags & PD_PAGENUMS)
	        CheckRadioButton(hDlg, rad1, rad3, rad3);
	}
1183 1184

	/* Collate pages
1185 1186 1187 1188
	 *
	 * FIXME: The ico3 is not displayed for some reason. I don't know why.
	 */
	if (lppd->Flags & PD_COLLATE) {
1189
            SendDlgItemMessageW(hDlg, ico3, STM_SETIMAGE, IMAGE_ICON,
1190 1191 1192
				(LPARAM)PrintStructures->hCollateIcon);
	    CheckDlgButton(hDlg, chx2, 1);
	} else {
1193
            SendDlgItemMessageW(hDlg, ico3, STM_SETIMAGE, IMAGE_ICON,
1194 1195 1196 1197 1198 1199 1200
				(LPARAM)PrintStructures->hNoCollateIcon);
	    CheckDlgButton(hDlg, chx2, 0);
	}

	if (lppd->Flags & PD_USEDEVMODECOPIESANDCOLLATE) {
	  /* if printer doesn't support it: no Collate */
	    if (!(lpdm->dmFields & DM_COLLATE)) {
1201 1202
	        EnableWindow(GetDlgItem(hDlg, chx2), FALSE);
		EnableWindow(GetDlgItem(hDlg, ico3), FALSE);
1203 1204 1205 1206 1207 1208 1209 1210 1211
	    }
	}

	/* nCopies */
	{
	  INT copies;
	  if (lppd->hDevMode == 0)
	      copies = lppd->nCopies;
	  else
1212
	      copies = lpdm->u1.s1.dmCopies;
1213 1214 1215 1216 1217 1218 1219 1220
	  if(copies == 0) copies = 1;
	  else if(copies < 0) copies = MAX_COPIES;
	  SetDlgItemInt(hDlg, edt3, copies, FALSE);
	}

	if (lppd->Flags & PD_USEDEVMODECOPIESANDCOLLATE) {
	  /* if printer doesn't support it: no nCopies */
	    if (!(lpdm->dmFields & DM_COPIES)) {
1221 1222
	        EnableWindow(GetDlgItem(hDlg, edt3), FALSE);
		EnableWindow(GetDlgItem(hDlg, stc5), FALSE);
1223 1224 1225 1226 1227 1228
	    }
	}

	/* print to file */
	CheckDlgButton(hDlg, chx1, (lppd->Flags & PD_PRINTTOFILE) ? 1 : 0);
	if (lppd->Flags & PD_DISABLEPRINTTOFILE)
1229
            EnableWindow(GetDlgItem(hDlg, chx1), FALSE);
1230 1231 1232 1233 1234 1235 1236
	if (lppd->Flags & PD_HIDEPRINTTOFILE)
            ShowWindow(GetDlgItem(hDlg, chx1), SW_HIDE);

    } else { /* PD_PRINTSETUP */
      BOOL bPortrait = (lpdm->u1.s1.dmOrientation == DMORIENT_PORTRAIT);

      PRINTDLG_SetUpPaperComboBoxW(hDlg, cmb2,
1237 1238 1239
				  PrintStructures->lpPrinterInfo->pPrinterName,
				  PrintStructures->lpPrinterInfo->pPortName,
				  lpdm);
1240
      PRINTDLG_SetUpPaperComboBoxW(hDlg, cmb3,
1241 1242 1243
				  PrintStructures->lpPrinterInfo->pPrinterName,
				  PrintStructures->lpPrinterInfo->pPortName,
				  lpdm);
1244
      CheckRadioButton(hDlg, rad1, rad2, bPortrait ? rad1: rad2);
1245
      SendDlgItemMessageW(hDlg, ico1, STM_SETIMAGE, IMAGE_ICON,
1246 1247
                          (LPARAM)(bPortrait ? PrintStructures->hPortraitIcon :
                                   PrintStructures->hLandscapeIcon));
1248

Alexandre Julliard's avatar
Alexandre Julliard committed
1249 1250
    }

1251 1252 1253
    /* help button */
    if ((lppd->Flags & PD_SHOWHELP)==0) {
        /* hide if PD_SHOWHELP not specified */
1254
        ShowWindow(GetDlgItem(hDlg, pshHelp), SW_HIDE);
1255 1256
    }
    return TRUE;
1257
}
1258

1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277
 /***********************************************************************
 *           check_printer_setup			[internal]
 */
static LRESULT check_printer_setup(HWND hDlg)
{
    DWORD needed,num;
    WCHAR resourcestr[256],resultstr[256];

    EnumPrintersW(PRINTER_ENUM_LOCAL, NULL, 2, NULL, 0, &needed, &num);
    if(needed == 0)
    {
          EnumPrintersW(PRINTER_ENUM_CONNECTIONS, NULL, 2, NULL, 0, &needed, &num);
    }
    if(needed > 0)
          return TRUE;
    else
    {
          LoadStringW(COMDLG32_hInstance, PD32_NO_DEVICES,resultstr, 255);
          LoadStringW(COMDLG32_hInstance, PD32_PRINT_TITLE,resourcestr, 255);
1278
          MessageBoxW(hDlg, resultstr, resourcestr,MB_OK | MB_ICONWARNING);
1279 1280 1281 1282
          return FALSE;
    }
}

1283
/***********************************************************************
1284
 *           PRINTDLG_WMInitDialog                      [internal]
1285
 */
1286 1287
static LRESULT PRINTDLG_WMInitDialog(HWND hDlg, WPARAM wParam,
				     PRINT_PTRA* PrintStructures)
1288
{
1289
    LPPRINTDLGA lppd = PrintStructures->lpPrintDlg;
1290 1291 1292 1293
    DEVNAMES *pdn;
    DEVMODEA *pdm;
    char *name = NULL;
    UINT comboID = (lppd->Flags & PD_PRINTSETUP) ? cmb1 : cmb4;
1294

1295
    /* load Collate ICONs */
1296
    /* We load these with LoadImage because they are not a standard
1297
       size and we don't want them rescaled */
1298
    PrintStructures->hCollateIcon =
1299
      LoadImageA(COMDLG32_hInstance, "PD32_COLLATE", IMAGE_ICON, 0, 0, 0);
1300
    PrintStructures->hNoCollateIcon =
1301
      LoadImageA(COMDLG32_hInstance, "PD32_NOCOLLATE", IMAGE_ICON, 0, 0, 0);
1302 1303 1304 1305 1306 1307 1308

    /* These can be done with LoadIcon */
    PrintStructures->hPortraitIcon =
      LoadIconA(COMDLG32_hInstance, "PD32_PORTRAIT");
    PrintStructures->hLandscapeIcon =
      LoadIconA(COMDLG32_hInstance, "PD32_LANDSCAPE");

1309
    /* display the collate/no_collate icon */
1310
    SendDlgItemMessageA(hDlg, ico3, STM_SETIMAGE, IMAGE_ICON,
1311 1312
                        (LPARAM)PrintStructures->hNoCollateIcon);

1313
    if(PrintStructures->hCollateIcon == 0 ||
1314 1315 1316
       PrintStructures->hNoCollateIcon == 0 ||
       PrintStructures->hPortraitIcon == 0 ||
       PrintStructures->hLandscapeIcon == 0) {
1317 1318 1319 1320
        ERR("no icon in resourcefile\n");
	COMDLG32_SetCommDlgExtendedError(CDERR_LOADRESFAILURE);
	EndDialog(hDlg, FALSE);
    }
1321

1322 1323 1324 1325 1326
    /*
     * if lppd->Flags PD_SHOWHELP is specified, a HELPMESGSTRING message
     * must be registered and the Help button must be shown.
     */
    if (lppd->Flags & PD_SHOWHELP) {
1327
        if((PrintStructures->HelpMessageID =
1328
	    RegisterWindowMessageA(HELPMSGSTRINGA)) == 0) {
1329 1330 1331 1332 1333
	    COMDLG32_SetCommDlgExtendedError(CDERR_REGISTERMSGFAIL);
	    return FALSE;
	}
    } else
        PrintStructures->HelpMessageID = 0;
1334

1335 1336 1337 1338 1339 1340 1341 1342 1343
    if(!(lppd->Flags &PD_PRINTSETUP)) {
        PrintStructures->hwndUpDown =
	  CreateUpDownControl(WS_CHILD | WS_VISIBLE | WS_BORDER |
			      UDS_NOTHOUSANDS | UDS_ARROWKEYS |
			      UDS_ALIGNRIGHT | UDS_SETBUDDYINT, 0, 0, 0, 0,
			      hDlg, UPDOWN_ID, COMDLG32_hInstance,
			      GetDlgItem(hDlg, edt3), MAX_COPIES, 1, 1);
    }

1344 1345 1346 1347 1348 1349
    /* FIXME: I allow more freedom than either Win95 or WinNT,
     *        which do not agree to what errors should be thrown or not
     *        in case nToPage or nFromPage is out-of-range.
     */
    if (lppd->nMaxPage < lppd->nMinPage)
    	lppd->nMaxPage = lppd->nMinPage;
1350 1351
    if (lppd->nMinPage == lppd->nMaxPage)
    	lppd->Flags |= PD_NOPAGENUMS;
1352 1353 1354 1355 1356 1357 1358 1359
    if (lppd->nToPage < lppd->nMinPage)
        lppd->nToPage = lppd->nMinPage;
    if (lppd->nToPage > lppd->nMaxPage)
        lppd->nToPage = lppd->nMaxPage;
    if (lppd->nFromPage < lppd->nMinPage)
        lppd->nFromPage = lppd->nMinPage;
    if (lppd->nFromPage > lppd->nMaxPage)
        lppd->nFromPage = lppd->nMaxPage;
1360

1361 1362
    /* if we have the combo box, fill it */
    if (GetDlgItem(hDlg,comboID)) {
1363
	/* Fill Combobox
1364 1365 1366 1367 1368 1369
	 */
	pdn = GlobalLock(lppd->hDevNames);
	pdm = GlobalLock(lppd->hDevMode);
	if(pdn)
	    name = (char*)pdn + pdn->wDeviceOffset;
	else if(pdm)
1370
	    name = (char*)pdm->dmDeviceName;
1371
	PRINTDLG_SetUpPrinterListComboA(hDlg, comboID, name);
1372 1373 1374 1375 1376 1377
	if(pdm) GlobalUnlock(lppd->hDevMode);
	if(pdn) GlobalUnlock(lppd->hDevNames);

	/* Now find selected printer and update rest of dlg */
	name = HeapAlloc(GetProcessHeap(),0,256);
	if (GetDlgItemTextA(hDlg, comboID, name, 255))
1378
	    PRINTDLG_ChangePrinterA(hDlg, name, PrintStructures);
1379 1380 1381 1382
	HeapFree(GetProcessHeap(),0,name);
    } else {
	/* else use default printer */
	char name[200];
1383 1384
        DWORD dwBufLen = sizeof(name);
	BOOL ret = GetDefaultPrinterA(name, &dwBufLen);
1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396

	if (ret)
	    PRINTDLG_ChangePrinterA(hDlg, name, PrintStructures);
	else
	    FIXME("No default printer found, expect problems!\n");
    }
    return TRUE;
}

static LRESULT PRINTDLG_WMInitDialogW(HWND hDlg, WPARAM wParam,
				     PRINT_PTRW* PrintStructures)
{
1397
    LPPRINTDLGW lppd = PrintStructures->lpPrintDlg;
1398 1399 1400 1401 1402 1403 1404 1405 1406
    DEVNAMES *pdn;
    DEVMODEW *pdm;
    WCHAR *name = NULL;
    UINT comboID = (lppd->Flags & PD_PRINTSETUP) ? cmb1 : cmb4;

    /* load Collate ICONs */
    /* We load these with LoadImage because they are not a standard
       size and we don't want them rescaled */
    PrintStructures->hCollateIcon =
1407
      LoadImageW(COMDLG32_hInstance, pd32_collateW, IMAGE_ICON, 0, 0, 0);
1408
    PrintStructures->hNoCollateIcon =
1409
      LoadImageW(COMDLG32_hInstance, pd32_nocollateW, IMAGE_ICON, 0, 0, 0);
1410 1411 1412

    /* These can be done with LoadIcon */
    PrintStructures->hPortraitIcon =
1413
      LoadIconW(COMDLG32_hInstance, pd32_portraitW);
1414
    PrintStructures->hLandscapeIcon =
1415
      LoadIconW(COMDLG32_hInstance, pd32_landscapeW);
1416

1417
    /* display the collate/no_collate icon */
1418
    SendDlgItemMessageW(hDlg, ico3, STM_SETIMAGE, IMAGE_ICON,
1419 1420
                        (LPARAM)PrintStructures->hNoCollateIcon);

1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434
    if(PrintStructures->hCollateIcon == 0 ||
       PrintStructures->hNoCollateIcon == 0 ||
       PrintStructures->hPortraitIcon == 0 ||
       PrintStructures->hLandscapeIcon == 0) {
        ERR("no icon in resourcefile\n");
	COMDLG32_SetCommDlgExtendedError(CDERR_LOADRESFAILURE);
	EndDialog(hDlg, FALSE);
    }

    /*
     * if lppd->Flags PD_SHOWHELP is specified, a HELPMESGSTRING message
     * must be registered and the Help button must be shown.
     */
    if (lppd->Flags & PD_SHOWHELP) {
1435
        if((PrintStructures->HelpMessageID =
1436
	    RegisterWindowMessageW(HELPMSGSTRINGW)) == 0) {
1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457
	    COMDLG32_SetCommDlgExtendedError(CDERR_REGISTERMSGFAIL);
	    return FALSE;
	}
    } else
        PrintStructures->HelpMessageID = 0;

    if(!(lppd->Flags &PD_PRINTSETUP)) {
        PrintStructures->hwndUpDown =
	  CreateUpDownControl(WS_CHILD | WS_VISIBLE | WS_BORDER |
			      UDS_NOTHOUSANDS | UDS_ARROWKEYS |
			      UDS_ALIGNRIGHT | UDS_SETBUDDYINT, 0, 0, 0, 0,
			      hDlg, UPDOWN_ID, COMDLG32_hInstance,
			      GetDlgItem(hDlg, edt3), MAX_COPIES, 1, 1);
    }

    /* FIXME: I allow more freedom than either Win95 or WinNT,
     *        which do not agree to what errors should be thrown or not
     *        in case nToPage or nFromPage is out-of-range.
     */
    if (lppd->nMaxPage < lppd->nMinPage)
    	lppd->nMaxPage = lppd->nMinPage;
1458 1459
    if (lppd->nMinPage == lppd->nMaxPage)
    	lppd->Flags |= PD_NOPAGENUMS;
1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470
    if (lppd->nToPage < lppd->nMinPage)
        lppd->nToPage = lppd->nMinPage;
    if (lppd->nToPage > lppd->nMaxPage)
        lppd->nToPage = lppd->nMaxPage;
    if (lppd->nFromPage < lppd->nMinPage)
        lppd->nFromPage = lppd->nMinPage;
    if (lppd->nFromPage > lppd->nMaxPage)
        lppd->nFromPage = lppd->nMaxPage;

    /* if we have the combo box, fill it */
    if (GetDlgItem(hDlg,comboID)) {
1471
	/* Fill Combobox
1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491
	 */
	pdn = GlobalLock(lppd->hDevNames);
	pdm = GlobalLock(lppd->hDevMode);
	if(pdn)
	    name = (WCHAR*)pdn + pdn->wDeviceOffset;
	else if(pdm)
	    name = pdm->dmDeviceName;
	PRINTDLG_SetUpPrinterListComboW(hDlg, comboID, name);
	if(pdm) GlobalUnlock(lppd->hDevMode);
	if(pdn) GlobalUnlock(lppd->hDevNames);

	/* Now find selected printer and update rest of dlg */
	/* ansi is ok here */
	name = HeapAlloc(GetProcessHeap(),0,256*sizeof(WCHAR));
	if (GetDlgItemTextW(hDlg, comboID, name, 255))
	    PRINTDLG_ChangePrinterW(hDlg, name, PrintStructures);
	HeapFree(GetProcessHeap(),0,name);
    } else {
	/* else use default printer */
	WCHAR name[200];
1492 1493
        DWORD dwBufLen = sizeof(name) / sizeof(WCHAR);
	BOOL ret = GetDefaultPrinterW(name, &dwBufLen);
1494 1495

	if (ret)
1496
	    PRINTDLG_ChangePrinterW(hDlg, name, PrintStructures);
1497 1498 1499 1500 1501 1502
	else
	    FIXME("No default printer found, expect problems!\n");
    }
    return TRUE;
}

1503 1504 1505
/***********************************************************************
 *                              PRINTDLG_WMCommand               [internal]
 */
1506 1507
static LRESULT PRINTDLG_WMCommandA(HWND hDlg, WPARAM wParam,
                                   LPARAM lParam, PRINT_PTRA* PrintStructures)
1508
{
1509
    LPPRINTDLGA lppd = PrintStructures->lpPrintDlg;
1510 1511
    UINT PrinterComboID = (lppd->Flags & PD_PRINTSETUP) ? cmb1 : cmb4;
    LPDEVMODEA lpdm = PrintStructures->lpDevMode;
1512

1513 1514
    switch (LOWORD(wParam))  {
    case IDOK:
1515
        TRACE(" OK button was hit\n");
1516
        if (!PRINTDLG_UpdatePrintDlgA(hDlg, PrintStructures)) {
1517
	    FIXME("Update printdlg was not successful!\n");
1518
	    return(FALSE);
1519
	}
1520 1521 1522 1523
	EndDialog(hDlg, TRUE);
	return(TRUE);

    case IDCANCEL:
1524
        TRACE(" CANCEL button was hit\n");
1525
        EndDialog(hDlg, FALSE);
1526 1527
	return(FALSE);

1528
     case pshHelp:
1529
        TRACE(" HELP button was hit\n");
1530
        SendMessageA(lppd->hwndOwner, PrintStructures->HelpMessageID,
1531 1532
        			(WPARAM) hDlg, (LPARAM) lppd);
        break;
1533

1534 1535
     case chx2:                         /* collate pages checkbox */
        if (IsDlgButtonChecked(hDlg, chx2) == BST_CHECKED)
1536
            SendDlgItemMessageA(hDlg, ico3, STM_SETIMAGE, IMAGE_ICON,
1537 1538
                                    (LPARAM)PrintStructures->hCollateIcon);
        else
1539
            SendDlgItemMessageA(hDlg, ico3, STM_SETIMAGE, IMAGE_ICON,
1540
                                    (LPARAM)PrintStructures->hNoCollateIcon);
1541
        break;
1542 1543
     case edt1:                         /* from page nr editbox */
     case edt2:                         /* to page nr editbox */
1544 1545 1546 1547 1548
        if (HIWORD(wParam)==EN_CHANGE) {
	    WORD nToPage;
	    WORD nFromPage;
	    nFromPage = GetDlgItemInt(hDlg, edt1, NULL, FALSE);
	    nToPage   = GetDlgItemInt(hDlg, edt2, NULL, FALSE);
1549
            if (nFromPage != lppd->nFromPage || nToPage != lppd->nToPage)
1550 1551
	        CheckRadioButton(hDlg, rad1, rad3, rad3);
	}
1552
        break;
1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563

    case edt3:
        if(HIWORD(wParam) == EN_CHANGE) {
	    INT copies = GetDlgItemInt(hDlg, edt3, NULL, FALSE);
	    if(copies <= 1)
	        EnableWindow(GetDlgItem(hDlg, chx2), FALSE);
	    else
	        EnableWindow(GetDlgItem(hDlg, chx2), TRUE);
	}
	break;

1564 1565 1566
     case psh2:                       /* Properties button */
       {
         HANDLE hPrinter;
1567 1568 1569 1570 1571 1572 1573
         char   PrinterName[256];

         GetDlgItemTextA(hDlg, PrinterComboID, PrinterName, 255);
         if (!OpenPrinterA(PrinterName, &hPrinter, NULL)) {
	     FIXME(" Call to OpenPrinter did not succeed!\n");
	     break;
	 }
1574
	 DocumentPropertiesA(hDlg, hPrinter, PrinterName,
1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585
			     PrintStructures->lpDevMode,
			     PrintStructures->lpDevMode,
			     DM_IN_BUFFER | DM_OUT_BUFFER | DM_IN_PROMPT);
	 ClosePrinter(hPrinter);
         break;
       }

    case rad1: /* Paperorientation */
        if (lppd->Flags & PD_PRINTSETUP)
        {
              lpdm->u1.s1.dmOrientation = DMORIENT_PORTRAIT;
1586
              SendDlgItemMessageA(hDlg, ico1, STM_SETIMAGE, IMAGE_ICON,
1587 1588 1589
                          (LPARAM)(PrintStructures->hPortraitIcon));
        }
        break;
1590

1591 1592 1593 1594
    case rad2: /* Paperorientation */
        if (lppd->Flags & PD_PRINTSETUP)
        {
              lpdm->u1.s1.dmOrientation = DMORIENT_LANDSCAPE;
1595
              SendDlgItemMessageA(hDlg, ico1, STM_SETIMAGE, IMAGE_ICON,
1596 1597 1598
                          (LPARAM)(PrintStructures->hLandscapeIcon));
        }
        break;
1599

1600
    case cmb1: /* Printer Combobox in PRINT SETUP, quality combobox in PRINT16 */
1601
	 if (PrinterComboID != LOWORD(wParam)) {
1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626
	     break;
	 }
	 /* FALLTHROUGH */
    case cmb4:                         /* Printer combobox */
         if (HIWORD(wParam)==CBN_SELCHANGE) {
	     char   PrinterName[256];
	     GetDlgItemTextA(hDlg, LOWORD(wParam), PrinterName, 255);
	     PRINTDLG_ChangePrinterA(hDlg, PrinterName, PrintStructures);
	 }
	 break;

    case cmb2: /* Papersize */
      {
	  DWORD Sel = SendDlgItemMessageA(hDlg, cmb2, CB_GETCURSEL, 0, 0);
	  if(Sel != CB_ERR)
	      lpdm->u1.s1.dmPaperSize = SendDlgItemMessageA(hDlg, cmb2,
							    CB_GETITEMDATA,
							    Sel, 0);
      }
      break;

    case cmb3: /* Bin */
      {
	  DWORD Sel = SendDlgItemMessageA(hDlg, cmb3, CB_GETCURSEL, 0, 0);
	  if(Sel != CB_ERR)
1627
	      lpdm->u1.s1.dmDefaultSource = SendDlgItemMessageA(hDlg, cmb3,
1628 1629 1630
							  CB_GETITEMDATA, Sel,
							  0);
      }
1631
      break;
1632 1633 1634 1635 1636 1637 1638 1639
    }
    if(lppd->Flags & PD_PRINTSETUP) {
        switch (LOWORD(wParam)) {
	case rad1:                         /* orientation */
	case rad2:
	    if (IsDlgButtonChecked(hDlg, rad1) == BST_CHECKED) {
	        if(lpdm->u1.s1.dmOrientation != DMORIENT_PORTRAIT) {
		    lpdm->u1.s1.dmOrientation = DMORIENT_PORTRAIT;
1640
                    SendDlgItemMessageA(hDlg, stc10, STM_SETIMAGE, IMAGE_ICON,
1641
					(LPARAM)PrintStructures->hPortraitIcon);
1642
                    SendDlgItemMessageA(hDlg, ico1, STM_SETIMAGE, IMAGE_ICON,
1643 1644 1645 1646 1647
					(LPARAM)PrintStructures->hPortraitIcon);
		}
	    } else {
	        if(lpdm->u1.s1.dmOrientation != DMORIENT_LANDSCAPE) {
	            lpdm->u1.s1.dmOrientation = DMORIENT_LANDSCAPE;
1648
                    SendDlgItemMessageA(hDlg, stc10, STM_SETIMAGE, IMAGE_ICON,
1649
					(LPARAM)PrintStructures->hLandscapeIcon);
1650
                    SendDlgItemMessageA(hDlg, ico1, STM_SETIMAGE, IMAGE_ICON,
1651 1652 1653 1654 1655 1656 1657
					(LPARAM)PrintStructures->hLandscapeIcon);
		}
	    }
	    break;
	}
    }
    return FALSE;
1658
}
1659

1660
static LRESULT PRINTDLG_WMCommandW(HWND hDlg, WPARAM wParam,
1661 1662
			LPARAM lParam, PRINT_PTRW* PrintStructures)
{
1663
    LPPRINTDLGW lppd = PrintStructures->lpPrintDlg;
1664 1665 1666 1667 1668 1669
    UINT PrinterComboID = (lppd->Flags & PD_PRINTSETUP) ? cmb1 : cmb4;
    LPDEVMODEW lpdm = PrintStructures->lpDevMode;

    switch (LOWORD(wParam))  {
    case IDOK:
        TRACE(" OK button was hit\n");
1670
        if (!PRINTDLG_UpdatePrintDlgW(hDlg, PrintStructures)) {
1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683
	    FIXME("Update printdlg was not successful!\n");
	    return(FALSE);
	}
	EndDialog(hDlg, TRUE);
	return(TRUE);

    case IDCANCEL:
        TRACE(" CANCEL button was hit\n");
        EndDialog(hDlg, FALSE);
	return(FALSE);

     case pshHelp:
        TRACE(" HELP button was hit\n");
1684
        SendMessageW(lppd->hwndOwner, PrintStructures->HelpMessageID,
1685 1686 1687 1688 1689
        			(WPARAM) hDlg, (LPARAM) lppd);
        break;

     case chx2:                         /* collate pages checkbox */
        if (IsDlgButtonChecked(hDlg, chx2) == BST_CHECKED)
1690
            SendDlgItemMessageW(hDlg, ico3, STM_SETIMAGE, IMAGE_ICON,
1691 1692
                                    (LPARAM)PrintStructures->hCollateIcon);
        else
1693
            SendDlgItemMessageW(hDlg, ico3, STM_SETIMAGE, IMAGE_ICON,
1694
                                    (LPARAM)PrintStructures->hNoCollateIcon);
1695
        break;
1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713
     case edt1:                         /* from page nr editbox */
     case edt2:                         /* to page nr editbox */
        if (HIWORD(wParam)==EN_CHANGE) {
	    WORD nToPage;
	    WORD nFromPage;
	    nFromPage = GetDlgItemInt(hDlg, edt1, NULL, FALSE);
	    nToPage   = GetDlgItemInt(hDlg, edt2, NULL, FALSE);
            if (nFromPage != lppd->nFromPage || nToPage != lppd->nToPage)
	        CheckRadioButton(hDlg, rad1, rad3, rad3);
	}
        break;

    case edt3:
        if(HIWORD(wParam) == EN_CHANGE) {
	    INT copies = GetDlgItemInt(hDlg, edt3, NULL, FALSE);
	    if(copies <= 1)
	        EnableWindow(GetDlgItem(hDlg, chx2), FALSE);
	    else
1714 1715 1716
                EnableWindow(GetDlgItem(hDlg, chx2), TRUE);
        }
        break;
1717 1718 1719 1720 1721

     case psh2:                       /* Properties button */
       {
         HANDLE hPrinter;
         WCHAR  PrinterName[256];
1722

1723
         if (!GetDlgItemTextW(hDlg, PrinterComboID, PrinterName, 255)) break;
1724
         if (!OpenPrinterW(PrinterName, &hPrinter, NULL)) {
1725
	     FIXME(" Call to OpenPrinter did not succeed!\n");
1726 1727
	     break;
	 }
1728
	 DocumentPropertiesW(hDlg, hPrinter, PrinterName,
1729 1730 1731 1732
			     PrintStructures->lpDevMode,
			     PrintStructures->lpDevMode,
			     DM_IN_BUFFER | DM_OUT_BUFFER | DM_IN_PROMPT);
	 ClosePrinter(hPrinter);
1733
         break;
1734
       }
1735

1736 1737
    case rad1: /* Paperorientation */
        if (lppd->Flags & PD_PRINTSETUP)
1738
        {
1739
              lpdm->u1.s1.dmOrientation = DMORIENT_PORTRAIT;
1740
              SendDlgItemMessageW(hDlg, ico1, STM_SETIMAGE, IMAGE_ICON,
1741 1742
                          (LPARAM)(PrintStructures->hPortraitIcon));
        }
1743
        break;
1744

1745 1746
    case rad2: /* Paperorientation */
        if (lppd->Flags & PD_PRINTSETUP)
1747
        {
1748
              lpdm->u1.s1.dmOrientation = DMORIENT_LANDSCAPE;
1749
              SendDlgItemMessageW(hDlg, ico1, STM_SETIMAGE, IMAGE_ICON,
1750 1751
                          (LPARAM)(PrintStructures->hLandscapeIcon));
        }
1752
        break;
1753

1754
    case cmb1: /* Printer Combobox in PRINT SETUP */
1755
	 /* FALLTHROUGH */
1756 1757
    case cmb4:                         /* Printer combobox */
         if (HIWORD(wParam)==CBN_SELCHANGE) {
1758 1759 1760
	     WCHAR   PrinterName[256];
	     GetDlgItemTextW(hDlg, LOWORD(wParam), PrinterName, 255);
	     PRINTDLG_ChangePrinterW(hDlg, PrinterName, PrintStructures);
1761 1762 1763 1764 1765
	 }
	 break;

    case cmb2: /* Papersize */
      {
1766
	  DWORD Sel = SendDlgItemMessageW(hDlg, cmb2, CB_GETCURSEL, 0, 0);
1767
	  if(Sel != CB_ERR)
1768
	      lpdm->u1.s1.dmPaperSize = SendDlgItemMessageW(hDlg, cmb2,
1769 1770 1771 1772 1773 1774 1775
							    CB_GETITEMDATA,
							    Sel, 0);
      }
      break;

    case cmb3: /* Bin */
      {
1776
	  DWORD Sel = SendDlgItemMessageW(hDlg, cmb3, CB_GETCURSEL, 0, 0);
1777
	  if(Sel != CB_ERR)
1778
	      lpdm->u1.s1.dmDefaultSource = SendDlgItemMessageW(hDlg, cmb3,
1779 1780 1781
							  CB_GETITEMDATA, Sel,
							  0);
      }
1782
      break;
1783
    }
1784 1785 1786 1787 1788 1789 1790
    if(lppd->Flags & PD_PRINTSETUP) {
        switch (LOWORD(wParam)) {
	case rad1:                         /* orientation */
	case rad2:
	    if (IsDlgButtonChecked(hDlg, rad1) == BST_CHECKED) {
	        if(lpdm->u1.s1.dmOrientation != DMORIENT_PORTRAIT) {
		    lpdm->u1.s1.dmOrientation = DMORIENT_PORTRAIT;
1791
                    SendDlgItemMessageW(hDlg, stc10, STM_SETIMAGE, IMAGE_ICON,
1792
					(LPARAM)PrintStructures->hPortraitIcon);
1793
                    SendDlgItemMessageW(hDlg, ico1, STM_SETIMAGE, IMAGE_ICON,
1794 1795 1796 1797 1798
					(LPARAM)PrintStructures->hPortraitIcon);
		}
	    } else {
	        if(lpdm->u1.s1.dmOrientation != DMORIENT_LANDSCAPE) {
	            lpdm->u1.s1.dmOrientation = DMORIENT_LANDSCAPE;
1799
                    SendDlgItemMessageW(hDlg, stc10, STM_SETIMAGE, IMAGE_ICON,
1800
					(LPARAM)PrintStructures->hLandscapeIcon);
1801
                    SendDlgItemMessageW(hDlg, ico1, STM_SETIMAGE, IMAGE_ICON,
1802 1803 1804 1805 1806 1807
					(LPARAM)PrintStructures->hLandscapeIcon);
		}
	    }
	    break;
	}
    }
1808
    return FALSE;
1809
}
1810

1811
/***********************************************************************
1812
 *           PrintDlgProcA			[internal]
1813
 */
1814 1815
static INT_PTR CALLBACK PrintDlgProcA(HWND hDlg, UINT uMsg, WPARAM wParam,
                                      LPARAM lParam)
1816
{
1817
    PRINT_PTRA* PrintStructures;
1818
    INT_PTR res = FALSE;
1819

1820
    if (uMsg!=WM_INITDIALOG) {
1821
        PrintStructures = GetPropW(hDlg, printdlg_prop);
1822 1823 1824 1825
	if (!PrintStructures)
	    return FALSE;
    } else {
        PrintStructures = (PRINT_PTRA*) lParam;
1826
        SetPropW(hDlg, printdlg_prop, PrintStructures);
1827 1828 1829 1830 1831
        if(!check_printer_setup(hDlg))
        {
            EndDialog(hDlg,FALSE);
            return FALSE;
        }
1832 1833
	res = PRINTDLG_WMInitDialog(hDlg, wParam, PrintStructures);

1834 1835 1836
	if(PrintStructures->lpPrintDlg->Flags & PD_ENABLEPRINTHOOK)
	    res = PrintStructures->lpPrintDlg->lpfnPrintHook(
		hDlg, uMsg, wParam, (LPARAM)PrintStructures->lpPrintDlg
1837
	    );
1838
	return res;
1839
    }
1840

1841 1842
    if(PrintStructures->lpPrintDlg->Flags & PD_ENABLEPRINTHOOK) {
        res = PrintStructures->lpPrintDlg->lpfnPrintHook(hDlg,uMsg,wParam,
1843 1844 1845 1846 1847 1848
							 lParam);
	if(res) return res;
    }

    switch (uMsg) {
    case WM_COMMAND:
1849 1850 1851 1852 1853 1854 1855 1856 1857 1858
        return PRINTDLG_WMCommandA(hDlg, wParam, lParam, PrintStructures);

    case WM_DESTROY:
	DestroyIcon(PrintStructures->hCollateIcon);
	DestroyIcon(PrintStructures->hNoCollateIcon);
        DestroyIcon(PrintStructures->hPortraitIcon);
        DestroyIcon(PrintStructures->hLandscapeIcon);
	if(PrintStructures->hwndUpDown)
	    DestroyWindow(PrintStructures->hwndUpDown);
        return FALSE;
1859
    }
1860 1861 1862
    return res;
}

1863 1864
static INT_PTR CALLBACK PrintDlgProcW(HWND hDlg, UINT uMsg, WPARAM wParam,
                                      LPARAM lParam)
1865 1866
{
    PRINT_PTRW* PrintStructures;
1867
    INT_PTR res = FALSE;
1868 1869

    if (uMsg!=WM_INITDIALOG) {
1870
        PrintStructures = GetPropW(hDlg, printdlg_prop);
1871 1872 1873 1874
	if (!PrintStructures)
	    return FALSE;
    } else {
        PrintStructures = (PRINT_PTRW*) lParam;
1875
        SetPropW(hDlg, printdlg_prop, PrintStructures);
1876 1877 1878 1879 1880
        if(!check_printer_setup(hDlg))
        {
            EndDialog(hDlg,FALSE);
            return FALSE;
        }
1881 1882
	res = PRINTDLG_WMInitDialogW(hDlg, wParam, PrintStructures);

1883 1884
	if(PrintStructures->lpPrintDlg->Flags & PD_ENABLEPRINTHOOK)
	    res = PrintStructures->lpPrintDlg->lpfnPrintHook(hDlg, uMsg, wParam, (LPARAM)PrintStructures->lpPrintDlg);
1885 1886
	return res;
    }
1887

1888 1889
    if(PrintStructures->lpPrintDlg->Flags & PD_ENABLEPRINTHOOK) {
        res = PrintStructures->lpPrintDlg->lpfnPrintHook(hDlg,uMsg,wParam, lParam);
1890 1891 1892 1893 1894 1895
	if(res) return res;
    }

    switch (uMsg) {
    case WM_COMMAND:
        return PRINTDLG_WMCommandW(hDlg, wParam, lParam, PrintStructures);
1896

1897 1898 1899
    case WM_DESTROY:
	DestroyIcon(PrintStructures->hCollateIcon);
	DestroyIcon(PrintStructures->hNoCollateIcon);
1900 1901 1902 1903
        DestroyIcon(PrintStructures->hPortraitIcon);
        DestroyIcon(PrintStructures->hLandscapeIcon);
	if(PrintStructures->hwndUpDown)
	    DestroyWindow(PrintStructures->hwndUpDown);
1904
        return FALSE;
1905
    }
1906 1907 1908 1909 1910 1911 1912 1913
    return res;
}

/************************************************************
 *
 *      PRINTDLG_GetDlgTemplate
 *
 */
1914
static HGLOBAL PRINTDLG_GetDlgTemplateA(const PRINTDLGA *lppd)
1915
{
1916 1917
    HRSRC hResInfo;
    HGLOBAL hDlgTmpl;
1918 1919

    if (lppd->Flags & PD_PRINTSETUP) {
1920
	if(lppd->Flags & PD_ENABLESETUPTEMPLATEHANDLE) {
1921
	    hDlgTmpl = lppd->hSetupTemplate;
1922
	} else if(lppd->Flags & PD_ENABLESETUPTEMPLATE) {
1923
	    hResInfo = FindResourceA(lppd->hInstance,
1924
				     lppd->lpSetupTemplateName, (LPSTR)RT_DIALOG);
1925 1926 1927
	    hDlgTmpl = LoadResource(lppd->hInstance, hResInfo);
	} else {
	    hResInfo = FindResourceA(COMDLG32_hInstance, "PRINT32_SETUP",
1928
				     (LPSTR)RT_DIALOG);
1929 1930 1931
	    hDlgTmpl = LoadResource(COMDLG32_hInstance, hResInfo);
	}
    } else {
1932
	if(lppd->Flags & PD_ENABLEPRINTTEMPLATEHANDLE) {
1933 1934 1935 1936
	    hDlgTmpl = lppd->hPrintTemplate;
	} else if(lppd->Flags & PD_ENABLEPRINTTEMPLATE) {
	    hResInfo = FindResourceA(lppd->hInstance,
				     lppd->lpPrintTemplateName,
1937
				     (LPSTR)RT_DIALOG);
1938 1939 1940
	    hDlgTmpl = LoadResource(lppd->hInstance, hResInfo);
	} else {
	    hResInfo = FindResourceA(COMDLG32_hInstance, "PRINT32",
1941
				     (LPSTR)RT_DIALOG);
1942 1943 1944 1945 1946
	    hDlgTmpl = LoadResource(COMDLG32_hInstance, hResInfo);
	}
    }
    return hDlgTmpl;
}
1947

1948
static HGLOBAL PRINTDLG_GetDlgTemplateW(const PRINTDLGW *lppd)
1949
{
1950 1951
    HRSRC hResInfo;
    HGLOBAL hDlgTmpl;
1952 1953
    static const WCHAR xpsetup[] = { 'P','R','I','N','T','3','2','_','S','E','T','U','P',0};
    static const WCHAR xprint[] = { 'P','R','I','N','T','3','2',0};
1954 1955 1956 1957

    if (lppd->Flags & PD_PRINTSETUP) {
	if(lppd->Flags & PD_ENABLESETUPTEMPLATEHANDLE) {
	    hDlgTmpl = lppd->hSetupTemplate;
1958
	} else if(lppd->Flags & PD_ENABLESETUPTEMPLATE) {
1959
	    hResInfo = FindResourceW(lppd->hInstance,
1960
				     lppd->lpSetupTemplateName, (LPWSTR)RT_DIALOG);
1961 1962
	    hDlgTmpl = LoadResource(lppd->hInstance, hResInfo);
	} else {
1963
	    hResInfo = FindResourceW(COMDLG32_hInstance, xpsetup, (LPWSTR)RT_DIALOG);
1964 1965 1966 1967 1968 1969 1970 1971
	    hDlgTmpl = LoadResource(COMDLG32_hInstance, hResInfo);
	}
    } else {
	if(lppd->Flags & PD_ENABLEPRINTTEMPLATEHANDLE) {
	    hDlgTmpl = lppd->hPrintTemplate;
	} else if(lppd->Flags & PD_ENABLEPRINTTEMPLATE) {
	    hResInfo = FindResourceW(lppd->hInstance,
				     lppd->lpPrintTemplateName,
1972
				     (LPWSTR)RT_DIALOG);
1973 1974
	    hDlgTmpl = LoadResource(lppd->hInstance, hResInfo);
	} else {
1975
	    hResInfo = FindResourceW(COMDLG32_hInstance, xprint, (LPWSTR)RT_DIALOG);
1976 1977 1978 1979 1980 1981
	    hDlgTmpl = LoadResource(COMDLG32_hInstance, hResInfo);
	}
    }
    return hDlgTmpl;
}

1982
/***********************************************************************
1983 1984 1985
 *
 *      PRINTDLG_CreateDC
 *
1986
 */
1987
static BOOL PRINTDLG_CreateDCA(LPPRINTDLGA lppd)
1988
{
1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005
    DEVNAMES *pdn = GlobalLock(lppd->hDevNames);
    DEVMODEA *pdm = GlobalLock(lppd->hDevMode);

    if(lppd->Flags & PD_RETURNDC) {
        lppd->hDC = CreateDCA((char*)pdn + pdn->wDriverOffset,
			      (char*)pdn + pdn->wDeviceOffset,
			      (char*)pdn + pdn->wOutputOffset,
			      pdm );
    } else if(lppd->Flags & PD_RETURNIC) {
        lppd->hDC = CreateICA((char*)pdn + pdn->wDriverOffset,
			      (char*)pdn + pdn->wDeviceOffset,
			      (char*)pdn + pdn->wOutputOffset,
			      pdm );
    }
    GlobalUnlock(lppd->hDevNames);
    GlobalUnlock(lppd->hDevMode);
    return lppd->hDC ? TRUE : FALSE;
2006
}
2007

2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028
static BOOL PRINTDLG_CreateDCW(LPPRINTDLGW lppd)
{
    DEVNAMES *pdn = GlobalLock(lppd->hDevNames);
    DEVMODEW *pdm = GlobalLock(lppd->hDevMode);

    if(lppd->Flags & PD_RETURNDC) {
        lppd->hDC = CreateDCW((WCHAR*)pdn + pdn->wDriverOffset,
			      (WCHAR*)pdn + pdn->wDeviceOffset,
			      (WCHAR*)pdn + pdn->wOutputOffset,
			      pdm );
    } else if(lppd->Flags & PD_RETURNIC) {
        lppd->hDC = CreateICW((WCHAR*)pdn + pdn->wDriverOffset,
			      (WCHAR*)pdn + pdn->wDeviceOffset,
			      (WCHAR*)pdn + pdn->wOutputOffset,
			      pdm );
    }
    GlobalUnlock(lppd->hDevNames);
    GlobalUnlock(lppd->hDevMode);
    return lppd->hDC ? TRUE : FALSE;
}

2029
/***********************************************************************
2030 2031
 *           PrintDlgA   (COMDLG32.@)
 *
2032
 *  Displays the PRINT dialog box, which enables the user to specify
2033
 *  specific properties of the print job.
2034 2035 2036 2037
 *  
 * PARAMS
 *  lppd  [IO] ptr to PRINTDLG32 struct
 * 
2038 2039 2040
 * RETURNS
 *  nonzero if the user pressed the OK button
 *  zero    if the user cancelled the window or an error occurred
2041
 *  
2042 2043 2044 2045 2046 2047
 * BUGS
 *  PrintDlg:
 *  * The Collate Icons do not display, even though they are in the code.
 *  * The Properties Button(s) should call DocumentPropertiesA().
 */

2048
BOOL WINAPI PrintDlgA(LPPRINTDLGA lppd)
2049 2050
{
    BOOL      bRet = FALSE;
2051 2052
    LPVOID    ptr;
    HINSTANCE hInst;
2053

2054 2055 2056 2057 2058 2059
    if (!lppd)
    {
        COMDLG32_SetCommDlgExtendedError(CDERR_INITIALIZATION);
        return FALSE;
    }

2060 2061
    if(TRACE_ON(commdlg)) {
        char flagstr[1000] = "";
2062
	const struct pd_flags *pflag = pd_flags;
2063 2064 2065 2066
	for( ; pflag->name; pflag++) {
	    if(lppd->Flags & pflag->flag)
	        strcat(flagstr, pflag->name);
	}
2067
	TRACE("(%p): hwndOwner = %p, hDevMode = %p, hDevNames = %p\n"
2068 2069
              "pp. %d-%d, min p %d, max p %d, copies %d, hinst %p\n"
              "flags %08x (%s)\n",
2070 2071 2072 2073 2074 2075 2076 2077
	      lppd, lppd->hwndOwner, lppd->hDevMode, lppd->hDevNames,
	      lppd->nFromPage, lppd->nToPage, lppd->nMinPage, lppd->nMaxPage,
	      lppd->nCopies, lppd->hInstance, lppd->Flags, flagstr);
    }

    if(lppd->lStructSize != sizeof(PRINTDLGA)) {
        WARN("structure size failure !!!\n");
	COMDLG32_SetCommDlgExtendedError(CDERR_STRUCTSIZE);
2078
	return FALSE;
2079 2080 2081 2082 2083 2084 2085 2086 2087 2088
    }

    if(lppd->Flags & PD_RETURNDEFAULT) {
        PRINTER_INFO_2A *pbuf;
	DRIVER_INFO_3A	*dbuf;
	HANDLE hprn;
	DWORD needed;

	if(lppd->hDevMode || lppd->hDevNames) {
	    WARN("hDevMode or hDevNames non-zero for PD_RETURNDEFAULT\n");
2089
	    COMDLG32_SetCommDlgExtendedError(PDERR_RETDEFFAILURE);
2090 2091 2092 2093
	    return FALSE;
	}
        if(!PRINTDLG_OpenDefaultPrinter(&hprn)) {
	    WARN("Can't find default printer\n");
2094
	    COMDLG32_SetCommDlgExtendedError(PDERR_NODEFAULTPRN);
2095 2096 2097 2098 2099 2100 2101 2102 2103 2104
	    return FALSE;
	}

	GetPrinterA(hprn, 2, NULL, 0, &needed);
	pbuf = HeapAlloc(GetProcessHeap(), 0, needed);
	GetPrinterA(hprn, 2, (LPBYTE)pbuf, needed, &needed);

	GetPrinterDriverA(hprn, NULL, 3, NULL, 0, &needed);
	dbuf = HeapAlloc(GetProcessHeap(),0,needed);
	if (!GetPrinterDriverA(hprn, NULL, 3, (LPBYTE)dbuf, needed, &needed)) {
2105 2106 2107 2108
	    ERR("GetPrinterDriverA failed, le %d, fix your config for printer %s!\n",
	        GetLastError(),pbuf->pPrinterName);
	    HeapFree(GetProcessHeap(), 0, dbuf);
	    HeapFree(GetProcessHeap(), 0, pbuf);
2109
	    COMDLG32_SetCommDlgExtendedError(PDERR_RETDEFFAILURE);
2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130
	    return FALSE;
	}
	ClosePrinter(hprn);

	PRINTDLG_CreateDevNames(&(lppd->hDevNames),
				  dbuf->pDriverPath,
				  pbuf->pPrinterName,
				  pbuf->pPortName);
	lppd->hDevMode = GlobalAlloc(GMEM_MOVEABLE, pbuf->pDevMode->dmSize +
				     pbuf->pDevMode->dmDriverExtra);
	ptr = GlobalLock(lppd->hDevMode);
	memcpy(ptr, pbuf->pDevMode, pbuf->pDevMode->dmSize +
	       pbuf->pDevMode->dmDriverExtra);
	GlobalUnlock(lppd->hDevMode);
	HeapFree(GetProcessHeap(), 0, pbuf);
	HeapFree(GetProcessHeap(), 0, dbuf);
	bRet = TRUE;
    } else {
	HGLOBAL hDlgTmpl;
	PRINT_PTRA *PrintStructures;

2131 2132
    /* load Dialog resources,
     * depending on Flags indicates Print32 or Print32_setup dialog
2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146
     */
	hDlgTmpl = PRINTDLG_GetDlgTemplateA(lppd);
	if (!hDlgTmpl) {
	    COMDLG32_SetCommDlgExtendedError(CDERR_LOADRESFAILURE);
	    return FALSE;
	}
	ptr = LockResource( hDlgTmpl );
	if (!ptr) {
	    COMDLG32_SetCommDlgExtendedError(CDERR_LOADRESFAILURE);
	    return FALSE;
	}

        PrintStructures = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY,
				    sizeof(PRINT_PTRA));
2147
	PrintStructures->lpPrintDlg = lppd;
2148 2149 2150 2151

	/* and create & process the dialog .
	 * -1 is failure, 0 is broken hwnd, everything else is ok.
	 */
2152 2153
        hInst = COMDLG32_hInstance;
	if (lppd->Flags & (PD_ENABLESETUPTEMPLATE | PD_ENABLEPRINTTEMPLATE)) hInst = lppd->hInstance;
2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189
	bRet = (0<DialogBoxIndirectParamA(hInst, ptr, lppd->hwndOwner,
					   PrintDlgProcA,
					   (LPARAM)PrintStructures));

	if(bRet) {
	    DEVMODEA *lpdm = PrintStructures->lpDevMode, *lpdmReturn;
	    PRINTER_INFO_2A *pi = PrintStructures->lpPrinterInfo;
	    DRIVER_INFO_3A *di = PrintStructures->lpDriverInfo;

	    if (lppd->hDevMode == 0) {
	        TRACE(" No hDevMode yet... Need to create my own\n");
		lppd->hDevMode = GlobalAlloc(GMEM_MOVEABLE,
					lpdm->dmSize + lpdm->dmDriverExtra);
	    } else {
		lppd->hDevMode = GlobalReAlloc(lppd->hDevMode,
					       lpdm->dmSize + lpdm->dmDriverExtra,
					       GMEM_MOVEABLE);
	    }
	    lpdmReturn = GlobalLock(lppd->hDevMode);
	    memcpy(lpdmReturn, lpdm, lpdm->dmSize + lpdm->dmDriverExtra);

	    PRINTDLG_CreateDevNames(&(lppd->hDevNames),
		    di->pDriverPath,
		    pi->pPrinterName,
		    pi->pPortName
	    );
	    GlobalUnlock(lppd->hDevMode);
	}
	HeapFree(GetProcessHeap(), 0, PrintStructures->lpDevMode);
	HeapFree(GetProcessHeap(), 0, PrintStructures->lpPrinterInfo);
	HeapFree(GetProcessHeap(), 0, PrintStructures->lpDriverInfo);
	HeapFree(GetProcessHeap(), 0, PrintStructures);
    }
    if(bRet && (lppd->Flags & PD_RETURNDC || lppd->Flags & PD_RETURNIC))
        bRet = PRINTDLG_CreateDCA(lppd);

2190 2191
    TRACE("exit! (%d)\n", bRet);
    return bRet;
2192 2193 2194 2195
}

/***********************************************************************
 *           PrintDlgW   (COMDLG32.@)
2196 2197
 *
 * See PrintDlgA.
2198
 */
2199
BOOL WINAPI PrintDlgW(LPPRINTDLGW lppd)
2200 2201
{
    BOOL      bRet = FALSE;
2202 2203 2204 2205 2206 2207 2208 2209
    LPVOID    ptr;
    HINSTANCE hInst;

    if (!lppd)
    {
        COMDLG32_SetCommDlgExtendedError(CDERR_INITIALIZATION);
        return FALSE;
    }
2210 2211 2212

    if(TRACE_ON(commdlg)) {
        char flagstr[1000] = "";
2213
	const struct pd_flags *pflag = pd_flags;
2214 2215 2216 2217
	for( ; pflag->name; pflag++) {
	    if(lppd->Flags & pflag->flag)
	        strcat(flagstr, pflag->name);
	}
2218
	TRACE("(%p): hwndOwner = %p, hDevMode = %p, hDevNames = %p\n"
2219 2220
              "pp. %d-%d, min p %d, max p %d, copies %d, hinst %p\n"
              "flags %08x (%s)\n",
2221 2222 2223 2224 2225
	      lppd, lppd->hwndOwner, lppd->hDevMode, lppd->hDevNames,
	      lppd->nFromPage, lppd->nToPage, lppd->nMinPage, lppd->nMaxPage,
	      lppd->nCopies, lppd->hInstance, lppd->Flags, flagstr);
    }

2226
    if(lppd->lStructSize != sizeof(PRINTDLGW)) {
2227 2228
        WARN("structure size failure !!!\n");
	COMDLG32_SetCommDlgExtendedError(CDERR_STRUCTSIZE);
2229
	return FALSE;
2230 2231 2232
    }

    if(lppd->Flags & PD_RETURNDEFAULT) {
2233 2234
        PRINTER_INFO_2W *pbuf;
	DRIVER_INFO_3W	*dbuf;
2235 2236 2237 2238 2239
	HANDLE hprn;
	DWORD needed;

	if(lppd->hDevMode || lppd->hDevNames) {
	    WARN("hDevMode or hDevNames non-zero for PD_RETURNDEFAULT\n");
2240
	    COMDLG32_SetCommDlgExtendedError(PDERR_RETDEFFAILURE);
2241
	    return FALSE;
2242 2243 2244
	}
        if(!PRINTDLG_OpenDefaultPrinter(&hprn)) {
	    WARN("Can't find default printer\n");
2245
	    COMDLG32_SetCommDlgExtendedError(PDERR_NODEFAULTPRN);
2246 2247 2248
	    return FALSE;
	}

2249
	GetPrinterW(hprn, 2, NULL, 0, &needed);
2250
	pbuf = HeapAlloc(GetProcessHeap(), 0, needed);
2251
	GetPrinterW(hprn, 2, (LPBYTE)pbuf, needed, &needed);
2252

2253
	GetPrinterDriverW(hprn, NULL, 3, NULL, 0, &needed);
2254
	dbuf = HeapAlloc(GetProcessHeap(),0,needed);
2255
	if (!GetPrinterDriverW(hprn, NULL, 3, (LPBYTE)dbuf, needed, &needed)) {
2256 2257 2258 2259
	    ERR("GetPrinterDriverA failed, le %d, fix your config for printer %s!\n",
	        GetLastError(),debugstr_w(pbuf->pPrinterName));
	    HeapFree(GetProcessHeap(), 0, dbuf);
	    HeapFree(GetProcessHeap(), 0, pbuf);
2260
	    COMDLG32_SetCommDlgExtendedError(PDERR_RETDEFFAILURE);
2261 2262
	    return FALSE;
	}
2263
	ClosePrinter(hprn);
2264

2265
	PRINTDLG_CreateDevNamesW(&(lppd->hDevNames),
2266 2267
				  dbuf->pDriverPath,
				  pbuf->pPrinterName,
2268 2269 2270 2271 2272 2273 2274 2275
				  pbuf->pPortName);
	lppd->hDevMode = GlobalAlloc(GMEM_MOVEABLE, pbuf->pDevMode->dmSize +
				     pbuf->pDevMode->dmDriverExtra);
	ptr = GlobalLock(lppd->hDevMode);
	memcpy(ptr, pbuf->pDevMode, pbuf->pDevMode->dmSize +
	       pbuf->pDevMode->dmDriverExtra);
	GlobalUnlock(lppd->hDevMode);
	HeapFree(GetProcessHeap(), 0, pbuf);
2276
	HeapFree(GetProcessHeap(), 0, dbuf);
2277 2278 2279
	bRet = TRUE;
    } else {
	HGLOBAL hDlgTmpl;
2280
	PRINT_PTRW *PrintStructures;
2281

2282 2283
    /* load Dialog resources,
     * depending on Flags indicates Print32 or Print32_setup dialog
2284
     */
2285
	hDlgTmpl = PRINTDLG_GetDlgTemplateW(lppd);
2286
	if (!hDlgTmpl) {
2287 2288 2289
	    COMDLG32_SetCommDlgExtendedError(CDERR_LOADRESFAILURE);
	    return FALSE;
	}
2290 2291 2292 2293 2294 2295
	ptr = LockResource( hDlgTmpl );
	if (!ptr) {
	    COMDLG32_SetCommDlgExtendedError(CDERR_LOADRESFAILURE);
	    return FALSE;
	}

2296
        PrintStructures = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY,
2297
				    sizeof(PRINT_PTRW));
2298
	PrintStructures->lpPrintDlg = lppd;
2299

2300 2301
	/* and create & process the dialog .
	 * -1 is failure, 0 is broken hwnd, everything else is ok.
2302
	 */
2303 2304
        hInst = COMDLG32_hInstance;
	if (lppd->Flags & (PD_ENABLESETUPTEMPLATE | PD_ENABLEPRINTTEMPLATE)) hInst = lppd->hInstance;
2305 2306
	bRet = (0<DialogBoxIndirectParamW(hInst, ptr, lppd->hwndOwner,
					   PrintDlgProcW,
2307
					   (LPARAM)PrintStructures));
2308 2309

	if(bRet) {
2310 2311 2312
	    DEVMODEW *lpdm = PrintStructures->lpDevMode, *lpdmReturn;
	    PRINTER_INFO_2W *pi = PrintStructures->lpPrinterInfo;
	    DRIVER_INFO_3W *di = PrintStructures->lpDriverInfo;
2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341

	    if (lppd->hDevMode == 0) {
	        TRACE(" No hDevMode yet... Need to create my own\n");
		lppd->hDevMode = GlobalAlloc(GMEM_MOVEABLE,
					lpdm->dmSize + lpdm->dmDriverExtra);
	    } else {
	        WORD locks;
		if((locks = (GlobalFlags(lppd->hDevMode) & GMEM_LOCKCOUNT))) {
		    WARN("hDevMode has %d locks on it. Unlocking it now\n", locks);
		    while(locks--) {
		        GlobalUnlock(lppd->hDevMode);
			TRACE("Now got %d locks\n", locks);
		    }
		}
		lppd->hDevMode = GlobalReAlloc(lppd->hDevMode,
					       lpdm->dmSize + lpdm->dmDriverExtra,
					       GMEM_MOVEABLE);
	    }
	    lpdmReturn = GlobalLock(lppd->hDevMode);
	    memcpy(lpdmReturn, lpdm, lpdm->dmSize + lpdm->dmDriverExtra);

	    if (lppd->hDevNames != 0) {
	        WORD locks;
		if((locks = (GlobalFlags(lppd->hDevNames) & GMEM_LOCKCOUNT))) {
		    WARN("hDevNames has %d locks on it. Unlocking it now\n", locks);
		    while(locks--)
		        GlobalUnlock(lppd->hDevNames);
		}
	    }
2342
	    PRINTDLG_CreateDevNamesW(&(lppd->hDevNames),
2343 2344 2345 2346
		    di->pDriverPath,
		    pi->pPrinterName,
		    pi->pPortName
	    );
2347 2348 2349 2350
	    GlobalUnlock(lppd->hDevMode);
	}
	HeapFree(GetProcessHeap(), 0, PrintStructures->lpDevMode);
	HeapFree(GetProcessHeap(), 0, PrintStructures->lpPrinterInfo);
2351
	HeapFree(GetProcessHeap(), 0, PrintStructures->lpDriverInfo);
2352 2353 2354
	HeapFree(GetProcessHeap(), 0, PrintStructures);
    }
    if(bRet && (lppd->Flags & PD_RETURNDC || lppd->Flags & PD_RETURNIC))
2355
        bRet = PRINTDLG_CreateDCW(lppd);
2356

2357 2358
    TRACE("exit! (%d)\n", bRet);
    return bRet;
2359 2360 2361 2362 2363
}

/***********************************************************************
 *
 *          PageSetupDlg
2364 2365
 * rad1 - portrait
 * rad2 - landscape
2366
 * cmb1 - printer select (not in standard dialog template)
2367 2368 2369 2370 2371 2372 2373
 * cmb2 - paper size
 * cmb3 - source (tray?)
 * edt4 - border left
 * edt5 - border top
 * edt6 - border right
 * edt7 - border bottom
 * psh3 - "Printer..."
2374
 */
2375

2376 2377
typedef struct
{
2378 2379 2380 2381 2382 2383 2384 2385
    BOOL unicode;
    union
    {
        LPPAGESETUPDLGA dlga;
        LPPAGESETUPDLGW dlgw;
    } u;
    HWND hDlg;                /* Page Setup dialog handle */
    RECT rtDrawRect;          /* Drawing rect for page */
2386
} pagesetup_data;
2387

2388 2389
static inline DWORD pagesetup_get_flags(const pagesetup_data *data)
{
2390
    return data->u.dlgw->Flags;
2391 2392
}

2393
static inline BOOL is_metric(const pagesetup_data *data)
2394
{
2395
    return pagesetup_get_flags(data) & PSD_INHUNDREDTHSOFMILLIMETERS;
2396 2397
}

2398
static inline LONG tenths_mm_to_size(const pagesetup_data *data, LONG size)
2399 2400 2401 2402 2403 2404 2405
{
    if (is_metric(data))
        return 10 * size;
    else
        return 10 * size * 100 / 254;
}

2406
static inline LONG thousandths_inch_to_size(const pagesetup_data *data, LONG size)
2407 2408 2409 2410 2411 2412 2413
{
    if (is_metric(data))
        return size * 254 / 100;
    else
        return size;
}

2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426
static WCHAR get_decimal_sep(void)
{
    static WCHAR sep;

    if(!sep)
    {
        WCHAR buf[2] = {'.',0};
        GetLocaleInfoW(LOCALE_USER_DEFAULT, LOCALE_SDECIMAL, buf, sizeof(buf) / sizeof(buf[0]));
        sep = buf[0];
    }
    return sep;
}

2427
static void size2str(const pagesetup_data *data, DWORD size, LPWSTR strout)
2428
{
2429
    WCHAR integer_fmt[] = {'%','d',0};
2430 2431
    WCHAR hundredths_fmt[] = {'%','d','%','c','%','0','2','d',0};
    WCHAR thousandths_fmt[] = {'%','d','%','c','%','0','3','d',0};
2432 2433

    /* FIXME use LOCALE_SDECIMAL when the edit parsing code can cope */
2434

2435
    if (is_metric(data))
2436 2437
    {
        if(size % 100)
2438
            wsprintfW(strout, hundredths_fmt, size / 100, get_decimal_sep(), size % 100);
2439 2440 2441
        else
            wsprintfW(strout, integer_fmt, size / 100);
    }
2442
    else
2443 2444
    {
        if(size % 1000)
2445
            wsprintfW(strout, thousandths_fmt, size / 1000, get_decimal_sep(), size % 1000);
2446 2447 2448 2449
        else
            wsprintfW(strout, integer_fmt, size / 1000);

    }
2450
}
2451

2452 2453 2454 2455 2456 2457 2458 2459
static inline BOOL is_default_metric(void)
{
    DWORD system;
    GetLocaleInfoW(LOCALE_USER_DEFAULT, LOCALE_IMEASURE | LOCALE_RETURN_NUMBER,
                   (LPWSTR)&system, sizeof(system));
    return system == 0;
}

2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486
/**********************************************
 *           rotate_rect
 * Cyclically permute the four members of rc
 * If sense is TRUE l -> t -> r -> b
 * otherwise        l <- t <- r <- b
 */
static inline void rotate_rect(RECT *rc, BOOL sense)
{
    INT tmp;
    if(sense)
    {
        tmp        = rc->bottom;
        rc->bottom = rc->right;
        rc->right  = rc->top;
        rc->top    = rc->left;
        rc->left   = tmp;
    }
    else
    {
        tmp        = rc->left;
        rc->left   = rc->top;
        rc->top    = rc->right;
        rc->right  = rc->bottom;
        rc->bottom = tmp;
    }
}

2487
static void pagesetup_set_orientation(pagesetup_data *data, WORD orient)
2488
{
2489
    DEVMODEW *dm = GlobalLock(data->u.dlgw->hDevMode);
2490 2491 2492

    assert(orient == DMORIENT_PORTRAIT || orient == DMORIENT_LANDSCAPE);

2493 2494 2495 2496 2497 2498 2499 2500
    if(data->unicode)
        dm->u1.s1.dmOrientation = orient;
    else
    {
        DEVMODEA *dmA = (DEVMODEA *)dm;
        dmA->u1.s1.dmOrientation = orient;
    }
    GlobalUnlock(data->u.dlgw->hDevMode);
2501 2502
}

2503
static WORD pagesetup_get_orientation(const pagesetup_data *data)
2504
{
2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515
    DEVMODEW *dm = GlobalLock(data->u.dlgw->hDevMode);
    WORD orient;

    if(data->unicode)
        orient = dm->u1.s1.dmOrientation;
    else
    {
        DEVMODEA *dmA = (DEVMODEA *)dm;
        orient = dmA->u1.s1.dmOrientation;
    }
    GlobalUnlock(data->u.dlgw->hDevMode);
2516 2517 2518
    return orient;
}

2519
static void pagesetup_set_papersize(pagesetup_data *data, WORD paper)
2520
{
2521 2522 2523 2524 2525 2526 2527 2528 2529 2530
    DEVMODEW *dm = GlobalLock(data->u.dlgw->hDevMode);

    if(data->unicode)
        dm->u1.s1.dmPaperSize = paper;
    else
    {
        DEVMODEA *dmA = (DEVMODEA *)dm;
        dmA->u1.s1.dmPaperSize = paper;
    }
    GlobalUnlock(data->u.dlgw->hDevMode);
2531 2532
}

2533
static WORD pagesetup_get_papersize(const pagesetup_data *data)
2534
{
2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545
    DEVMODEW *dm = GlobalLock(data->u.dlgw->hDevMode);
    WORD paper;

    if(data->unicode)
        paper = dm->u1.s1.dmPaperSize;
    else
    {
        DEVMODEA *dmA = (DEVMODEA *)dm;
        paper = dmA->u1.s1.dmPaperSize;
    }
    GlobalUnlock(data->u.dlgw->hDevMode);
2546 2547 2548
    return paper;
}

2549
static void pagesetup_set_defaultsource(pagesetup_data *data, WORD source)
2550
{
2551 2552 2553 2554 2555 2556 2557 2558 2559 2560
    DEVMODEW *dm = GlobalLock(data->u.dlgw->hDevMode);

    if(data->unicode)
        dm->u1.s1.dmDefaultSource = source;
    else
    {
        DEVMODEA *dmA = (DEVMODEA *)dm;
        dmA->u1.s1.dmDefaultSource = source;
    }
    GlobalUnlock(data->u.dlgw->hDevMode);
2561 2562
}

2563
typedef enum
2564
{
2565 2566 2567 2568
    devnames_driver_name,
    devnames_device_name,
    devnames_output_name
} devnames_name;
2569 2570


2571
static inline WORD get_devname_offset(const DEVNAMES *dn, devnames_name which)
2572
{
2573 2574 2575 2576 2577 2578 2579 2580
    switch(which)
    {
    case devnames_driver_name: return dn->wDriverOffset;
    case devnames_device_name: return dn->wDeviceOffset;
    case devnames_output_name: return dn->wOutputOffset;
    }
    ERR("Souldn't be here\n");
    return 0;
2581 2582
}

2583
static WCHAR *pagesetup_get_a_devname(const pagesetup_data *data, devnames_name which)
2584 2585 2586 2587
{
    DEVNAMES *dn;
    WCHAR *name;

2588 2589 2590 2591 2592 2593 2594 2595 2596 2597
    dn = GlobalLock(data->u.dlgw->hDevNames);
    if(data->unicode)
        name = strdupW((WCHAR *)dn + get_devname_offset(dn, which));
    else
    {
        int len = MultiByteToWideChar(CP_ACP, 0, (char*)dn + get_devname_offset(dn, which), -1, NULL, 0);
        name = HeapAlloc(GetProcessHeap(), 0, len * sizeof(WCHAR));
        MultiByteToWideChar(CP_ACP, 0, (char*)dn + get_devname_offset(dn, which), -1, name, len);
    }
    GlobalUnlock(data->u.dlgw->hDevNames);
2598 2599 2600
    return name;
}

2601
static WCHAR *pagesetup_get_drvname(const pagesetup_data *data)
2602
{
2603
    return pagesetup_get_a_devname(data, devnames_driver_name);
2604 2605
}

2606
static WCHAR *pagesetup_get_devname(const pagesetup_data *data)
2607
{
2608 2609
    return pagesetup_get_a_devname(data, devnames_device_name);
}
2610

2611 2612 2613
static WCHAR *pagesetup_get_portname(const pagesetup_data *data)
{
    return pagesetup_get_a_devname(data, devnames_output_name);
2614 2615
}

2616
static void pagesetup_release_a_devname(const pagesetup_data *data, WCHAR *name)
2617 2618 2619 2620
{
    HeapFree(GetProcessHeap(), 0, name);
}

2621
static void pagesetup_set_devnames(pagesetup_data *data, LPCWSTR drv, LPCWSTR devname, LPCWSTR port)
2622 2623 2624 2625 2626
{
    DEVNAMES *dn;
    WCHAR def[256];
    DWORD len = sizeof(DEVNAMES), drv_len, dev_len, port_len;

2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638
    if(data->unicode)
    {
        drv_len  = (strlenW(drv) + 1) * sizeof(WCHAR);
        dev_len  = (strlenW(devname) + 1) * sizeof(WCHAR);
        port_len = (strlenW(port) + 1) * sizeof(WCHAR);
    }
    else
    {
        drv_len = WideCharToMultiByte(CP_ACP, 0, drv, -1, NULL, 0, NULL, NULL);
        dev_len = WideCharToMultiByte(CP_ACP, 0, devname, -1, NULL, 0, NULL, NULL);
        port_len = WideCharToMultiByte(CP_ACP, 0, port, -1, NULL, 0, NULL, NULL);
    }
2639 2640
    len += drv_len + dev_len + port_len;

2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662
    if(data->u.dlgw->hDevNames)
        data->u.dlgw->hDevNames = GlobalReAlloc(data->u.dlgw->hDevNames, len, GMEM_MOVEABLE);
    else
        data->u.dlgw->hDevNames = GlobalAlloc(GMEM_MOVEABLE, len);

    dn = GlobalLock(data->u.dlgw->hDevNames);

    if(data->unicode)
    {
        WCHAR *ptr = (WCHAR *)(dn + 1);
        len = sizeof(DEVNAMES) / sizeof(WCHAR);
        dn->wDriverOffset = len;
        strcpyW(ptr, drv);
        ptr += drv_len / sizeof(WCHAR);
        len += drv_len / sizeof(WCHAR);
        dn->wDeviceOffset = len;
        strcpyW(ptr, devname);
        ptr += dev_len / sizeof(WCHAR);
        len += dev_len / sizeof(WCHAR);
        dn->wOutputOffset = len;
        strcpyW(ptr, port);
    }
2663
    else
2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677
    {
        char *ptr = (char *)(dn + 1);
        len = sizeof(DEVNAMES);
        dn->wDriverOffset = len;
        WideCharToMultiByte(CP_ACP, 0, drv, -1, ptr, drv_len, NULL, NULL);
        ptr += drv_len;
        len += drv_len;
        dn->wDeviceOffset = len;
        WideCharToMultiByte(CP_ACP, 0, devname, -1, ptr, dev_len, NULL, NULL);
        ptr += dev_len;
        len += dev_len;
        dn->wOutputOffset = len;
        WideCharToMultiByte(CP_ACP, 0, port, -1, ptr, port_len, NULL, NULL);
    }
2678 2679 2680 2681 2682 2683 2684

    dn->wDefault = 0;
    len = sizeof(def) / sizeof(def[0]);
    GetDefaultPrinterW(def, &len);
    if(!lstrcmpW(def, devname))
        dn->wDefault = 1;

2685
    GlobalUnlock(data->u.dlgw->hDevNames);
2686 2687
}

2688
static DEVMODEW *pagesetup_get_devmode(const pagesetup_data *data)
2689
{
2690 2691
    DEVMODEW *dm = GlobalLock(data->u.dlgw->hDevMode);
    DEVMODEW *ret;
2692

2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704
    if(data->unicode)
    {
        /* We make a copy even in the unicode case because the ptr
           may get passed back to us in pagesetup_set_devmode. */
        ret = HeapAlloc(GetProcessHeap(), 0, dm->dmSize + dm->dmDriverExtra);
        memcpy(ret, dm, dm->dmSize + dm->dmDriverExtra);
    }
    else
        ret = GdiConvertToDevmodeW((DEVMODEA *)dm);

    GlobalUnlock(data->u.dlgw->hDevMode);
    return ret;
2705 2706
}

2707
static void pagesetup_release_devmode(const pagesetup_data *data, DEVMODEW *dm)
2708 2709 2710 2711
{
    HeapFree(GetProcessHeap(), 0, dm);
}

2712
static void pagesetup_set_devmode(pagesetup_data *data, DEVMODEW *dm)
2713
{
2714 2715 2716
    DEVMODEA *dmA = NULL;
    void *src, *dst;
    DWORD size;
2717

2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728
    if(data->unicode)
    {
        size = dm->dmSize + dm->dmDriverExtra;
        src = dm;
    }
    else
    {
        dmA = convert_to_devmodeA(dm);
        size = dmA->dmSize + dmA->dmDriverExtra;
        src = dmA;
    }
2729

2730 2731 2732
    if(data->u.dlgw->hDevMode)
        data->u.dlgw->hDevMode = GlobalReAlloc(data->u.dlgw->hDevMode, size,
                                               GMEM_MOVEABLE);
2733
    else
2734 2735 2736 2737 2738 2739
        data->u.dlgw->hDevMode = GlobalAlloc(GMEM_MOVEABLE, size);

    dst = GlobalLock(data->u.dlgw->hDevMode);
    memcpy(dst, src, size);
    GlobalUnlock(data->u.dlgw->hDevMode);
    HeapFree(GetProcessHeap(), 0, dmA);
2740 2741
}

2742 2743
static inline POINT *pagesetup_get_papersize_pt(const pagesetup_data *data)
{
2744
    return &data->u.dlgw->ptPaperSize;
2745 2746
}

2747 2748
static inline RECT *pagesetup_get_margin_rect(const pagesetup_data *data)
{
2749
    return &data->u.dlgw->rtMargin;
2750 2751
}

2752 2753 2754 2755 2756 2757 2758 2759 2760 2761
typedef enum
{
    page_setup_hook,
    page_paint_hook
} hook_type;

static inline LPPAGESETUPHOOK pagesetup_get_hook(const pagesetup_data *data, hook_type which)
{
    switch(which)
    {
2762 2763
    case page_setup_hook: return data->u.dlgw->lpfnPageSetupHook;
    case page_paint_hook: return data->u.dlgw->lpfnPagePaintHook;
2764 2765 2766 2767
    }
    return NULL;
}

2768 2769 2770 2771
/* This should only be used in calls to hook procs so we return the ptr
   already cast to LPARAM */
static inline LPARAM pagesetup_get_dlg_struct(const pagesetup_data *data)
{
2772
    return (LPARAM)data->u.dlgw;
2773 2774
}

2775 2776 2777 2778 2779 2780 2781
static inline void swap_point(POINT *pt)
{
    LONG tmp = pt->x;
    pt->x = pt->y;
    pt->y = tmp;
}

2782
static BOOL pagesetup_update_papersize(pagesetup_data *data)
2783
{
2784 2785
    DEVMODEW *dm;
    LPWSTR devname, portname;
2786
    int i, num;
2787
    WORD *words = NULL, paperword;
2788 2789 2790
    POINT *points = NULL;
    BOOL retval = FALSE;

2791 2792 2793
    dm       = pagesetup_get_devmode(data);
    devname  = pagesetup_get_devname(data);
    portname = pagesetup_get_portname(data);
2794

2795
    num = DeviceCapabilitiesW(devname, portname, DC_PAPERS, NULL, dm);
2796 2797
    if (num <= 0)
    {
2798
        FIXME("No papernames found for %s/%s\n", debugstr_w(devname), debugstr_w(portname));
2799 2800 2801 2802 2803 2804
        goto end;
    }

    words = HeapAlloc(GetProcessHeap(), 0, num * sizeof(WORD));
    points = HeapAlloc(GetProcessHeap(), 0, num * sizeof(POINT));

2805
    if (num != DeviceCapabilitiesW(devname, portname, DC_PAPERS, (LPWSTR)words, dm))
2806 2807 2808 2809 2810
    {
        FIXME("Number of returned words is not %d\n", num);
        goto end;
    }

2811
    if (num != DeviceCapabilitiesW(devname, portname, DC_PAPERSIZE, (LPWSTR)points, dm))
2812
    {
2813
        FIXME("Number of returned sizes is not %d\n", num);
2814 2815 2816
        goto end;
    }

2817
    paperword = pagesetup_get_papersize(data);
2818

2819
    for (i = 0; i < num; i++)
2820
        if (words[i] == paperword)
2821 2822 2823 2824
            break;

    if (i == num)
    {
2825
        FIXME("Papersize %d not found in list?\n", paperword);
2826 2827 2828 2829
        goto end;
    }

    /* this is _10ths_ of a millimeter */
2830 2831
    pagesetup_get_papersize_pt(data)->x = tenths_mm_to_size(data, points[i].x);
    pagesetup_get_papersize_pt(data)->y = tenths_mm_to_size(data, points[i].y);
2832

2833
    if(pagesetup_get_orientation(data) == DMORIENT_LANDSCAPE)
2834 2835
        swap_point(pagesetup_get_papersize_pt(data));

2836 2837 2838 2839 2840
    retval = TRUE;

end:
    HeapFree(GetProcessHeap(), 0, words);
    HeapFree(GetProcessHeap(), 0, points);
2841 2842
    pagesetup_release_a_devname(data, portname);
    pagesetup_release_a_devname(data, devname);
2843
    pagesetup_release_devmode(data, dm);
2844

2845 2846
    return retval;
}
2847

2848
/**********************************************************************************************
2849
 * pagesetup_change_printer
2850 2851 2852 2853
 *
 * Redefines hDevMode and hDevNames HANDLES and initialises it.
 * 
 */
2854
static BOOL pagesetup_change_printer(LPWSTR name, pagesetup_data *data)
2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890
{
    HANDLE hprn;
    DWORD needed;
    PRINTER_INFO_2W *prn_info = NULL;
    DRIVER_INFO_3W *drv_info = NULL;
    DEVMODEW *dm = NULL;
    BOOL retval = FALSE;

    if(!OpenPrinterW(name, &hprn, NULL))
    {
        ERR("Can't open printer %s\n", debugstr_w(name));
        goto end;
    }

    GetPrinterW(hprn, 2, NULL, 0, &needed);
    prn_info = HeapAlloc(GetProcessHeap(), 0, needed);
    GetPrinterW(hprn, 2, (LPBYTE)prn_info, needed, &needed);
    GetPrinterDriverW(hprn, NULL, 3, NULL, 0, &needed);
    drv_info = HeapAlloc(GetProcessHeap(), 0, needed);
    if(!GetPrinterDriverW(hprn, NULL, 3, (LPBYTE)drv_info, needed, &needed))
    {
        ERR("GetPrinterDriverA failed for %s, fix your config!\n", debugstr_w(prn_info->pPrinterName));
        goto end;
    }
    ClosePrinter(hprn);

    needed = DocumentPropertiesW(0, 0, name, NULL, NULL, 0);
    if(needed == -1)
    {
        ERR("DocumentProperties fails on %s\n", debugstr_w(name));
        goto end;
    }

    dm = HeapAlloc(GetProcessHeap(), 0, needed);
    DocumentPropertiesW(0, 0, name, dm, NULL, DM_OUT_BUFFER);

2891 2892
    pagesetup_set_devmode(data, dm);
    pagesetup_set_devnames(data, drv_info->pDriverPath, prn_info->pPrinterName,
2893 2894 2895 2896 2897 2898 2899 2900
                           prn_info->pPortName);

    retval = TRUE;
end:
    HeapFree(GetProcessHeap(), 0, dm);
    HeapFree(GetProcessHeap(), 0, prn_info);
    HeapFree(GetProcessHeap(), 0, drv_info);
    return retval;
2901 2902 2903
}

/****************************************************************************************
2904
 *  pagesetup_init_combos
2905
 *
2906
 *  Fills Printers, Paper and Source combos
2907
 *
2908
 */
2909
static void pagesetup_init_combos(HWND hDlg, pagesetup_data *data)
2910
{
2911 2912
    DEVMODEW *dm;
    LPWSTR devname, portname;
2913

2914 2915 2916
    dm       = pagesetup_get_devmode(data);
    devname  = pagesetup_get_devname(data);
    portname = pagesetup_get_portname(data);
2917 2918 2919 2920 2921

    PRINTDLG_SetUpPrinterListComboW(hDlg, cmb1, devname);
    PRINTDLG_SetUpPaperComboBoxW(hDlg, cmb2, devname, portname, dm);
    PRINTDLG_SetUpPaperComboBoxW(hDlg, cmb3, devname, portname, dm);

2922 2923
    pagesetup_release_a_devname(data, portname);
    pagesetup_release_a_devname(data, devname);
2924
    pagesetup_release_devmode(data, dm);
2925 2926
}

2927 2928 2929 2930 2931 2932 2933 2934

/****************************************************************************************
 *  pagesetup_change_printer_dialog
 *
 *  Pops up another dialog that lets the user pick another printer.
 *
 *  For now we display the PrintDlg, this should display a striped down version of it.
 */
2935
static void pagesetup_change_printer_dialog(HWND hDlg, pagesetup_data *data)
2936 2937 2938 2939 2940 2941 2942 2943 2944 2945
{
    PRINTDLGW prnt;
    LPWSTR drvname, devname, portname;
    DEVMODEW *tmp_dm, *dm;

    memset(&prnt, 0, sizeof(prnt));
    prnt.lStructSize = sizeof(prnt);
    prnt.Flags     = 0;
    prnt.hwndOwner = hDlg;

2946 2947 2948
    drvname = pagesetup_get_drvname(data);
    devname = pagesetup_get_devname(data);
    portname = pagesetup_get_portname(data);
2949 2950
    prnt.hDevNames = 0;
    PRINTDLG_CreateDevNamesW(&prnt.hDevNames, drvname, devname, portname);
2951 2952 2953
    pagesetup_release_a_devname(data, portname);
    pagesetup_release_a_devname(data, devname);
    pagesetup_release_a_devname(data, drvname);
2954

2955
    tmp_dm = pagesetup_get_devmode(data);
2956 2957 2958 2959
    prnt.hDevMode = GlobalAlloc(GMEM_MOVEABLE, tmp_dm->dmSize + tmp_dm->dmDriverExtra);
    dm = GlobalLock(prnt.hDevMode);
    memcpy(dm, tmp_dm, tmp_dm->dmSize + tmp_dm->dmDriverExtra);
    GlobalUnlock(prnt.hDevMode);
2960
    pagesetup_release_devmode(data, tmp_dm);
2961 2962 2963 2964 2965 2966

    if (PrintDlgW(&prnt))
    {
        DEVMODEW *dm = GlobalLock(prnt.hDevMode);
        DEVNAMES *dn = GlobalLock(prnt.hDevNames);

2967
        pagesetup_set_devnames(data, (WCHAR*)dn + dn->wDriverOffset,
2968
                               (WCHAR*)dn + dn->wDeviceOffset, (WCHAR *)dn + dn->wOutputOffset);
2969
        pagesetup_set_devmode(data, dm);
2970 2971
        GlobalUnlock(prnt.hDevNames);
        GlobalUnlock(prnt.hDevMode);
2972
        pagesetup_init_combos(hDlg, data);
2973 2974 2975 2976 2977 2978 2979
    }

    GlobalFree(prnt.hDevMode);
    GlobalFree(prnt.hDevNames);

}

2980
/******************************************************************************************
2981
 * pagesetup_change_preview
2982
 *
2983
 * Changes paper preview size / position
2984 2985
 *
 */
2986
static void pagesetup_change_preview(const pagesetup_data *data)
2987 2988
{
    LONG width, height, x, y;
2989 2990 2991 2992 2993 2994
    RECT tmp;
    const int shadow = 4;

    if(pagesetup_get_orientation(data) == DMORIENT_LANDSCAPE)
    {
        width  = data->rtDrawRect.right - data->rtDrawRect.left;
2995
        height = pagesetup_get_papersize_pt(data)->y * width / pagesetup_get_papersize_pt(data)->x;
2996 2997 2998 2999
    }
    else
    {
        height = data->rtDrawRect.bottom - data->rtDrawRect.top;
3000
        width  = pagesetup_get_papersize_pt(data)->x * height / pagesetup_get_papersize_pt(data)->y;
3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014
    }
    x = (data->rtDrawRect.right + data->rtDrawRect.left - width) / 2;
    y = (data->rtDrawRect.bottom + data->rtDrawRect.top - height) / 2;
    TRACE("draw rect %s x=%d, y=%d, w=%d, h=%d\n",
          wine_dbgstr_rect(&data->rtDrawRect), x, y, width, height);

    MoveWindow(GetDlgItem(data->hDlg, rct2), x + width, y + shadow, shadow, height, FALSE);
    MoveWindow(GetDlgItem(data->hDlg, rct3), x + shadow, y + height, width, shadow, FALSE);
    MoveWindow(GetDlgItem(data->hDlg, rct1), x, y, width, height, FALSE);

    tmp = data->rtDrawRect;
    tmp.right  += shadow;
    tmp.bottom += shadow;
    InvalidateRect(data->hDlg, &tmp, TRUE);
3015 3016
}

3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028
static inline LONG *element_from_margin_id(RECT *rc, WORD id)
{
    switch(id)
    {
    case edt4: return &rc->left;
    case edt5: return &rc->top;
    case edt6: return &rc->right;
    case edt7: return &rc->bottom;
    }
    return NULL;
}

3029
static void update_margin_edits(HWND hDlg, const pagesetup_data *data, WORD id)
3030 3031
{
    WCHAR str[100];
3032
    WORD idx;
3033

3034 3035 3036 3037
    for(idx = edt4; idx <= edt7; idx++)
    {
        if(id == 0 || id == idx)
        {
3038
            size2str(data, *element_from_margin_id(pagesetup_get_margin_rect(data), idx), str);
3039 3040 3041
            SetDlgItemTextW(hDlg, idx, str);
        }
    }
3042 3043
}

3044
static void margin_edit_notification(HWND hDlg, const pagesetup_data *data, WORD msg, WORD id)
3045 3046 3047 3048 3049 3050 3051
{
    switch (msg)
    {
    case EN_CHANGE:
      {
        WCHAR buf[10];
        LONG val = 0;
3052
        LONG *value = element_from_margin_id(pagesetup_get_margin_rect(data), id);
3053 3054 3055 3056

        if (GetDlgItemTextW(hDlg, id, buf, sizeof(buf) / sizeof(buf[0])) != 0)
        {
            WCHAR *end;
3057
            WCHAR decimal = get_decimal_sep();
3058 3059 3060 3061

            val = strtolW(buf, &end, 10);
            if(end != buf || *end == decimal)
            {
3062
                int mult = is_metric(data) ? 100 : 1000;
3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082
                val *= mult;
                if(*end == decimal)
                {
                    while(mult > 1)
                    {
                        end++;
                        mult /= 10;
                        if(isdigitW(*end))
                            val += (*end - '0') * mult;
                        else
                            break;
                    }
                }
            }
        }
        *value = val;
        return;
      }

    case EN_KILLFOCUS:
3083
        update_margin_edits(hDlg, data, id);
3084 3085 3086 3087
        return;
    }
}

3088
static void set_margin_groupbox_title(HWND hDlg, const pagesetup_data *data)
3089 3090 3091
{
    WCHAR title[256];

3092
    if(LoadStringW(COMDLG32_hInstance, is_metric(data) ? PD32_MARGINS_IN_MILLIMETERS : PD32_MARGINS_IN_INCHES,
3093 3094 3095 3096
                   title, sizeof(title)/sizeof(title[0])))
        SetDlgItemTextW(hDlg, grp4, title);
}

3097
static void pagesetup_update_orientation_buttons(HWND hDlg, const pagesetup_data *data)
3098
{
3099
    if (pagesetup_get_orientation(data) == DMORIENT_LANDSCAPE)
3100 3101 3102 3103 3104
        CheckRadioButton(hDlg, rad1, rad2, rad2);
    else
        CheckRadioButton(hDlg, rad1, rad2, rad1);
}

3105 3106 3107 3108 3109
/****************************************************************************************
 *  pagesetup_printer_properties
 *
 *  Handle invocation of the 'Properties' button (not present in the default template).
 */
3110
static void pagesetup_printer_properties(HWND hDlg, pagesetup_data *data)
3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122
{
    HANDLE hprn;
    LPWSTR devname;
    DEVMODEW *dm;
    LRESULT count;
    int i;

    devname = pagesetup_get_devname(data);

    if (!OpenPrinterW(devname, &hprn, NULL))
    {
        FIXME("Call to OpenPrinter did not succeed!\n");
3123
        pagesetup_release_a_devname(data, devname);
3124 3125 3126 3127 3128 3129 3130
        return;
    }

    dm = pagesetup_get_devmode(data);
    DocumentPropertiesW(hDlg, hprn, devname, dm, dm, DM_IN_BUFFER | DM_OUT_BUFFER | DM_IN_PROMPT);
    pagesetup_set_devmode(data, dm);
    pagesetup_release_devmode(data, dm);
3131
    pagesetup_release_a_devname(data, devname);
3132 3133 3134 3135 3136 3137 3138
    ClosePrinter(hprn);

    /* Changing paper */
    pagesetup_update_papersize(data);
    pagesetup_update_orientation_buttons(hDlg, data);

    /* Changing paper preview */
3139
    pagesetup_change_preview(data);
3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155

    /* Selecting paper in combo */
    count = SendDlgItemMessageW(hDlg, cmb2, CB_GETCOUNT, 0, 0);
    if(count != CB_ERR)
    {
        WORD paperword = pagesetup_get_papersize(data);
        for(i = 0; i < count; i++)
        {
            if(SendDlgItemMessageW(hDlg, cmb2, CB_GETITEMDATA, i, 0) == paperword) {
                SendDlgItemMessageW(hDlg, cmb2, CB_SETCURSEL, i, 0);
                break;
            }
        }
    }
}

3156
/********************************************************************************
3157 3158
 * pagesetup_wm_command
 * process WM_COMMAND message for PageSetupDlg
3159 3160 3161 3162 3163 3164 3165 3166
 *
 * PARAMS
 *  hDlg 	[in] 	Main dialog HANDLE 
 *  wParam 	[in]	WM_COMMAND wParam
 *  lParam	[in]	WM_COMMAND lParam
 *  pda		[in/out] ptr to PageSetupDataA
 */

3167
static BOOL pagesetup_wm_command(HWND hDlg, WPARAM wParam, LPARAM lParam, pagesetup_data *data)
3168
{
3169 3170
    WORD msg = HIWORD(wParam);
    WORD id  = LOWORD(wParam);
3171

3172
    TRACE("loword (lparam) %d, wparam 0x%lx, lparam %08lx\n",
3173
	    LOWORD(lParam),wParam,lParam);
3174
    switch (id)  {
3175 3176 3177 3178 3179 3180 3181 3182
    case IDOK:
	EndDialog(hDlg, TRUE);
	return TRUE ;

    case IDCANCEL:
        EndDialog(hDlg, FALSE);
	return FALSE ;

3183
    case psh3: /* Printer... */
3184
        pagesetup_change_printer_dialog(hDlg, data);
3185
        return TRUE;
3186 3187 3188

    case rad1: /* Portrait */
    case rad2: /* Landscape */
3189 3190
        if((id == rad1 && pagesetup_get_orientation(data) == DMORIENT_LANDSCAPE) ||
           (id == rad2 && pagesetup_get_orientation(data) == DMORIENT_PORTRAIT))
3191
	{
3192 3193
            pagesetup_set_orientation(data, (id == rad1) ? DMORIENT_PORTRAIT : DMORIENT_LANDSCAPE);
            pagesetup_update_papersize(data);
3194
            rotate_rect(pagesetup_get_margin_rect(data), (id == rad2));
3195 3196
            update_margin_edits(hDlg, data, 0);
            pagesetup_change_preview(data);
3197 3198
	}
	break;
3199
    case cmb1: /* Printer combo */
3200 3201 3202 3203
        if(msg == CBN_SELCHANGE)
        {
            WCHAR name[256];
            GetDlgItemTextW(hDlg, id, name, sizeof(name) / sizeof(name[0]));
3204 3205
            pagesetup_change_printer(name, data);
            pagesetup_init_combos(hDlg, data);
3206 3207
        }
        break;
3208
    case cmb2: /* Paper combo */
3209 3210 3211 3212
        if(msg == CBN_SELCHANGE)
        {
            DWORD paperword = SendDlgItemMessageW(hDlg, cmb2, CB_GETITEMDATA,
                                                  SendDlgItemMessageW(hDlg, cmb2, CB_GETCURSEL, 0, 0), 0);
3213 3214
            if (paperword != CB_ERR)
            {
3215 3216 3217
                pagesetup_set_papersize(data, paperword);
                pagesetup_update_papersize(data);
                pagesetup_change_preview(data);
3218
	    } else
3219 3220 3221
                FIXME("could not get dialog text for papersize cmbbox?\n");
        }
        break;
3222 3223 3224
    case cmb3: /* Paper Source */
        if(msg == CBN_SELCHANGE)
        {
3225 3226
            WORD source = SendDlgItemMessageW(hDlg, cmb3, CB_GETITEMDATA,
                                              SendDlgItemMessageW(hDlg, cmb3, CB_GETCURSEL, 0, 0), 0);
3227
            pagesetup_set_defaultsource(data, source);
3228 3229
        }
        break;
3230
    case psh2: /* Printer Properties button */
3231
        pagesetup_printer_properties(hDlg, data);
3232
        break;
3233 3234 3235 3236
    case edt4:
    case edt5:
    case edt6:
    case edt7:
3237
        margin_edit_notification(hDlg, data, msg, id);
3238
        break;
3239
    }
3240
    InvalidateRect(GetDlgItem(hDlg, rct1), NULL, TRUE);
3241 3242 3243
    return FALSE;
}

3244
/***********************************************************************
3245
 *           default_page_paint_hook
3246 3247
 * Default hook paint procedure that receives WM_PSD_* messages from the dialog box 
 * whenever the sample page is redrawn.
3248 3249 3250
 */
static UINT_PTR default_page_paint_hook(HWND hwndDlg, UINT uMsg, WPARAM wParam, LPARAM lParam,
                                        const pagesetup_data *data)
3251 3252 3253 3254 3255 3256 3257 3258 3259
{
    LPRECT lprc = (LPRECT) lParam;
    HDC hdc = (HDC) wParam;
    HPEN hpen, holdpen;
    LOGFONTW lf;
    HFONT hfont, holdfont;
    INT oldbkmode;
    TRACE("uMsg: WM_USER+%d\n",uMsg-WM_USER);
    /* Call user paint hook if enable */
3260
    if (pagesetup_get_flags(data) & PSD_ENABLEPAGEPAINTHOOK)
3261
        if (pagesetup_get_hook(data, page_paint_hook)(hwndDlg, uMsg, wParam, lParam))
3262 3263 3264 3265 3266 3267 3268 3269 3270 3271 3272 3273 3274 3275 3276 3277 3278 3279 3280 3281 3282 3283 3284 3285 3286 3287 3288 3289 3290 3291 3292 3293 3294 3295 3296 3297 3298 3299 3300 3301 3302 3303 3304 3305 3306 3307 3308 3309 3310 3311 3312 3313 3314 3315 3316 3317 3318 3319 3320 3321 3322 3323 3324 3325 3326 3327 3328 3329 3330 3331 3332 3333 3334 3335 3336 3337 3338 3339 3340 3341 3342 3343 3344
            return TRUE;

    switch (uMsg) {
       /* LPPAGESETUPDLG in lParam */
       case WM_PSD_PAGESETUPDLG:
       /* Inform about the sample page rectangle */
       case WM_PSD_FULLPAGERECT:
       /* Inform about the margin rectangle */
       case WM_PSD_MINMARGINRECT:
            return FALSE;

        /* Draw dashed rectangle showing margins */
        case WM_PSD_MARGINRECT:
            hpen = CreatePen(PS_DASH, 1, GetSysColor(COLOR_3DSHADOW));
            holdpen = SelectObject(hdc, hpen);
            Rectangle(hdc, lprc->left, lprc->top, lprc->right, lprc->bottom);
            DeleteObject(SelectObject(hdc, holdpen));
            return TRUE;
        /* Draw the fake document */
        case WM_PSD_GREEKTEXTRECT:
            /* select a nice scalable font, because we want the text really small */
            SystemParametersInfoW(SPI_GETICONTITLELOGFONT, sizeof(lf), &lf, 0);
            lf.lfHeight = 6; /* value chosen based on visual effect */
            hfont = CreateFontIndirectW(&lf);
            holdfont = SelectObject(hdc, hfont);

            /* if text not loaded, then do so now */
            if (wszFakeDocumentText[0] == '\0')
                 LoadStringW(COMDLG32_hInstance,
                        IDS_FAKEDOCTEXT,
                        wszFakeDocumentText,
                        sizeof(wszFakeDocumentText)/sizeof(wszFakeDocumentText[0]));

            oldbkmode = SetBkMode(hdc, TRANSPARENT);
            DrawTextW(hdc, wszFakeDocumentText, -1, lprc, DT_TOP|DT_LEFT|DT_NOPREFIX|DT_WORDBREAK);
            SetBkMode(hdc, oldbkmode);

            DeleteObject(SelectObject(hdc, holdfont));
            return TRUE;

        /* Envelope stamp */
        case WM_PSD_ENVSTAMPRECT:
        /* Return address */
        case WM_PSD_YAFULLPAGERECT:
            FIXME("envelope/stamp is not implemented\n");
            return FALSE;
        default:
            FIXME("Unknown message %x\n",uMsg);
            return FALSE;
    }
    return TRUE;
}

/***********************************************************************
 *           PagePaintProc
 * The main paint procedure for the PageSetupDlg function.
 * The Page Setup dialog box includes an image of a sample page that shows how
 * the user's selections affect the appearance of the printed output.
 * The image consists of a rectangle that represents the selected paper
 * or envelope type, with a dotted-line rectangle representing
 * the current margins, and partial (Greek text) characters
 * to show how text looks on the printed page. 
 *
 * The following messages in the order sends to user hook procedure:
 *   WM_PSD_PAGESETUPDLG    Draw the contents of the sample page
 *   WM_PSD_FULLPAGERECT    Inform about the bounding rectangle
 *   WM_PSD_MINMARGINRECT   Inform about the margin rectangle (min margin?)
 *   WM_PSD_MARGINRECT      Draw the margin rectangle
 *   WM_PSD_GREEKTEXTRECT   Draw the Greek text inside the margin rectangle
 * If any of first three messages returns TRUE, painting done.
 *
 * PARAMS:
 *   hWnd   [in] Handle to the Page Setup dialog box
 *   uMsg   [in] Received message
 *
 * TODO:
 *   WM_PSD_ENVSTAMPRECT    Draw in the envelope-stamp rectangle (for envelopes only)
 *   WM_PSD_YAFULLPAGERECT  Draw the return address portion (for envelopes and other paper sizes)
 *
 * RETURNS:
 *   FALSE if all done correctly
 *
 */
3345 3346


3347
static LRESULT CALLBACK
3348
PRINTDLG_PagePaintProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
3349
{
3350 3351 3352 3353 3354
    PAINTSTRUCT ps;
    RECT rcClient, rcMargin;
    HPEN hpen, holdpen;
    HDC hdc;
    HBRUSH hbrush, holdbrush;
3355
    pagesetup_data *data;
3356
    int papersize=0, orientation=0; /* FIXME: set this values for user paint hook */
3357
    double scalx, scaly;
3358 3359 3360 3361 3362

    if (uMsg != WM_PAINT)
        return CallWindowProcA(lpfnStaticWndProc, hWnd, uMsg, wParam, lParam);

    /* Processing WM_PAINT message */
3363 3364
    data = GetPropW(hWnd, pagesetupdlg_prop);
    if (!data) {
3365 3366 3367
        WARN("__WINE_PAGESETUPDLGDATA prop not set?\n");
        return FALSE;
    }
3368 3369
    if (default_page_paint_hook(hWnd, WM_PSD_PAGESETUPDLG, MAKELONG(papersize, orientation),
                                pagesetup_get_dlg_struct(data), data))
3370
        return FALSE;
3371

3372 3373
    hdc = BeginPaint(hWnd, &ps);
    GetClientRect(hWnd, &rcClient);
3374
    
3375 3376
    scalx = rcClient.right  / (double)pagesetup_get_papersize_pt(data)->x;
    scaly = rcClient.bottom / (double)pagesetup_get_papersize_pt(data)->y;
3377
    rcMargin = rcClient;
3378

3379
    rcMargin.left   += pagesetup_get_margin_rect(data)->left   * scalx;
3380 3381
    rcMargin.top    += pagesetup_get_margin_rect(data)->top    * scaly;
    rcMargin.right  -= pagesetup_get_margin_rect(data)->right  * scalx;
3382
    rcMargin.bottom -= pagesetup_get_margin_rect(data)->bottom * scaly;
3383

3384 3385 3386 3387
    /* if the space is too small then we make sure to not draw anything */
    rcMargin.left = min(rcMargin.left, rcMargin.right);
    rcMargin.top = min(rcMargin.top, rcMargin.bottom);

3388 3389
    if (!default_page_paint_hook(hWnd, WM_PSD_FULLPAGERECT, (WPARAM)hdc, (LPARAM)&rcClient, data) &&
        !default_page_paint_hook(hWnd, WM_PSD_MINMARGINRECT, (WPARAM)hdc, (LPARAM)&rcMargin, data) )
3390
    {
3391 3392 3393 3394 3395 3396 3397
        /* fill background */
        hbrush = GetSysColorBrush(COLOR_3DHIGHLIGHT);
        FillRect(hdc, &rcClient, hbrush);
        holdbrush = SelectObject(hdc, hbrush);

        hpen = CreatePen(PS_SOLID, 1, GetSysColor(COLOR_3DSHADOW));
        holdpen = SelectObject(hdc, hpen);
3398
        
3399 3400 3401 3402 3403 3404 3405 3406 3407 3408 3409 3410 3411 3412 3413 3414 3415 3416 3417
        /* paint left edge */
        MoveToEx(hdc, rcClient.left, rcClient.top, NULL);
        LineTo(hdc, rcClient.left, rcClient.bottom-1);

        /* paint top edge */
        MoveToEx(hdc, rcClient.left, rcClient.top, NULL);
        LineTo(hdc, rcClient.right, rcClient.top);

        hpen = CreatePen(PS_SOLID, 1, GetSysColor(COLOR_3DDKSHADOW));
        DeleteObject(SelectObject(hdc, hpen));

        /* paint right edge */
        MoveToEx(hdc, rcClient.right-1, rcClient.top, NULL);
        LineTo(hdc, rcClient.right-1, rcClient.bottom);

        /* paint bottom edge */
        MoveToEx(hdc, rcClient.left, rcClient.bottom-1, NULL);
        LineTo(hdc, rcClient.right, rcClient.bottom-1);

3418 3419
        DeleteObject(SelectObject(hdc, holdpen));
        DeleteObject(SelectObject(hdc, holdbrush));
3420

3421
        default_page_paint_hook(hWnd, WM_PSD_MARGINRECT, (WPARAM)hdc, (LPARAM)&rcMargin, data);
3422 3423

        /* give text a bit of a space from the frame */
3424 3425 3426 3427 3428
        rcMargin.left += 2;
        rcMargin.top += 2;
        rcMargin.right -= 2;
        rcMargin.bottom -= 2;
        
3429
        /* if the space is too small then we make sure to not draw anything */
3430 3431
        rcMargin.left = min(rcMargin.left, rcMargin.right);
        rcMargin.top = min(rcMargin.top, rcMargin.bottom);
3432

3433
        default_page_paint_hook(hWnd, WM_PSD_GREEKTEXTRECT, (WPARAM)hdc, (LPARAM)&rcMargin, data);
3434
    }
3435 3436 3437

    EndPaint(hWnd, &ps);
    return FALSE;
3438 3439
}

3440 3441 3442 3443 3444 3445
/*******************************************************
 * The margin edit controls are subclassed to filter
 * anything other than numbers and the decimal separator.
 */
static LRESULT CALLBACK pagesetup_margin_editproc(HWND hwnd, UINT msg, WPARAM wparam, LPARAM lparam)
{
Andrew Talbot's avatar
Andrew Talbot committed
3446
    if (msg == WM_CHAR)
3447
    {
3448
        WCHAR decimal = get_decimal_sep();
3449 3450 3451 3452 3453 3454 3455 3456 3457 3458 3459 3460 3461 3462 3463 3464 3465 3466 3467 3468
        WCHAR wc = (WCHAR)wparam;
        if(!isdigitW(wc) && wc != decimal && wc != VK_BACK) return 0;
    }
    return CallWindowProcW(edit_wndproc, hwnd, msg, wparam, lparam);
}

static void subclass_margin_edits(HWND hDlg)
{
    int id;
    WNDPROC old_proc;

    for(id = edt4; id <= edt7; id++)
    {
        old_proc = (WNDPROC)SetWindowLongPtrW(GetDlgItem(hDlg, id),
                                              GWLP_WNDPROC,
                                              (ULONG_PTR)pagesetup_margin_editproc);
        InterlockedCompareExchangePointer((void**)&edit_wndproc, old_proc, NULL);
    }
}

3469
/***********************************************************************
3470 3471 3472
 *           pagesetup_dlg_proc
 *
 * Message handler for PageSetupDlg
3473
 */
3474
static INT_PTR CALLBACK pagesetup_dlg_proc(HWND hDlg, UINT uMsg, WPARAM wParam, LPARAM lParam)
3475
{
3476
    pagesetup_data *data;
3477
    INT_PTR		res = FALSE;
3478
    HWND 		hDrawWnd;
3479

3480
    if (uMsg == WM_INITDIALOG) { /*Init dialog*/
3481 3482 3483
        data = (pagesetup_data *)lParam;
        data->hDlg = hDlg;

3484
	hDrawWnd = GetDlgItem(hDlg, rct1); 
3485 3486 3487 3488 3489 3490
        TRACE("set property to %p\n", data);
        SetPropW(hDlg, pagesetupdlg_prop, data);
        SetPropW(hDrawWnd, pagesetupdlg_prop, data);
        GetWindowRect(hDrawWnd, &data->rtDrawRect); /* Calculating rect in client coordinates where paper draws */
        ScreenToClient(hDlg, (LPPOINT)&data->rtDrawRect);
        ScreenToClient(hDlg, (LPPOINT)(&data->rtDrawRect.right));
3491
        lpfnStaticWndProc = (WNDPROC)SetWindowLongPtrW(
3492
            hDrawWnd,
3493
            GWLP_WNDPROC,
3494
            (ULONG_PTR)PRINTDLG_PagePaintProc);
3495
	
3496
	/* FIXME: Paint hook. Must it be at begin of initialization or at end? */
3497
	res = TRUE;
3498
        if (pagesetup_get_flags(data) & PSD_ENABLEPAGESETUPHOOK)
3499
        {
3500 3501
            if (!pagesetup_get_hook(data, page_setup_hook)(hDlg, uMsg, wParam,
                                                           pagesetup_get_dlg_struct(data)))
3502 3503
		FIXME("Setup page hook failed?\n");
	}
3504

3505
	/* if printer button disabled */
3506
        if (pagesetup_get_flags(data) & PSD_DISABLEPRINTER)
3507
            EnableWindow(GetDlgItem(hDlg, psh3), FALSE);
3508
	/* if margin edit boxes disabled */
3509
        if (pagesetup_get_flags(data) & PSD_DISABLEMARGINS)
3510
        {
3511 3512 3513 3514
            EnableWindow(GetDlgItem(hDlg, edt4), FALSE);
            EnableWindow(GetDlgItem(hDlg, edt5), FALSE);
            EnableWindow(GetDlgItem(hDlg, edt6), FALSE);
            EnableWindow(GetDlgItem(hDlg, edt7), FALSE);
3515
	}
3516

3517
        /* Set orientation radiobuttons properly */
3518
        pagesetup_update_orientation_buttons(hDlg, data);
3519

3520
	/* if orientation disabled */
3521
        if (pagesetup_get_flags(data) & PSD_DISABLEORIENTATION)
3522
        {
3523 3524 3525
	    EnableWindow(GetDlgItem(hDlg,rad1),FALSE);
	    EnableWindow(GetDlgItem(hDlg,rad2),FALSE);
	}
3526

3527
	/* We fill them out enabled or not */
3528
        if (!(pagesetup_get_flags(data) & PSD_MARGINS))
3529
        {
3530
            /* default is 1 inch */
3531
            LONG size = thousandths_inch_to_size(data, 1000);
3532
            SetRect(pagesetup_get_margin_rect(data), size, size, size, size);
3533
        }
3534
        update_margin_edits(hDlg, data, 0);
3535
        subclass_margin_edits(hDlg);
3536
        set_margin_groupbox_title(hDlg, data);
3537

3538
	/* if paper disabled */
3539
        if (pagesetup_get_flags(data) & PSD_DISABLEPAPER)
3540
        {
3541 3542 3543
	    EnableWindow(GetDlgItem(hDlg,cmb2),FALSE);
	    EnableWindow(GetDlgItem(hDlg,cmb3),FALSE);
	}
3544

3545
	/* filling combos: printer, paper, source. selecting current printer (from DEVMODEA) */
3546 3547 3548
        pagesetup_init_combos(hDlg, data);
        pagesetup_update_papersize(data);
        pagesetup_set_defaultsource(data, DMBIN_FORMSOURCE); /* FIXME: This is the auto select bin. Is this correct? */
3549

3550
	/* Drawing paper prev */
3551
        pagesetup_change_preview(data);
3552 3553
	return TRUE;
    } else {
3554 3555 3556
        data = GetPropW(hDlg, pagesetupdlg_prop);
        if (!data)
        {
3557 3558 3559
	    WARN("__WINE_PAGESETUPDLGDATA prop not set?\n");
	    return FALSE;
	}
3560
        if (pagesetup_get_flags(data) & PSD_ENABLEPAGESETUPHOOK)
3561
        {
3562
            res = pagesetup_get_hook(data, page_setup_hook)(hDlg, uMsg, wParam, lParam);
3563 3564 3565 3566 3567
	    if (res) return res;
	}
    }
    switch (uMsg) {
    case WM_COMMAND:
3568
        return pagesetup_wm_command(hDlg, wParam, lParam, data);
3569 3570 3571 3572
    }
    return FALSE;
}

3573 3574 3575 3576
static WCHAR *get_default_printer(void)
{
    WCHAR *name = NULL;
    DWORD len = 0;
3577

3578 3579 3580 3581 3582
    GetDefaultPrinterW(NULL, &len);
    if(len)
    {
        name = HeapAlloc(GetProcessHeap(), 0, len * sizeof(WCHAR));
        GetDefaultPrinterW(name, &len);
3583
    }
3584 3585
    return name;
}
3586

3587 3588 3589 3590
static void pagesetup_dump_dlg_struct(pagesetup_data *data)
{
    if(TRACE_ON(commdlg))
    {
3591
        char flagstr[1000] = "";
3592
	const struct pd_flags *pflag = psd_flags;
3593 3594 3595 3596 3597 3598 3599 3600
        for( ; pflag->name; pflag++)
        {
            if(pagesetup_get_flags(data) & pflag->flag)
            {
                strcat(flagstr, pflag->name);
                strcat(flagstr, "|");
            }
        }
3601
        TRACE("%s: (%p): hwndOwner = %p, hDevMode = %p, hDevNames = %p\n"
3602
              "hinst %p, flags %08x (%s)\n",
3603 3604 3605
              data->unicode ? "unicode" : "ansi",
              data->u.dlgw, data->u.dlgw->hwndOwner, data->u.dlgw->hDevMode,
              data->u.dlgw->hDevNames, data->u.dlgw->hInstance,
3606
              pagesetup_get_flags(data), flagstr);
3607
    }
3608
}
3609

3610 3611 3612 3613 3614 3615 3616
static void *pagesetup_get_template(pagesetup_data *data)
{
    HRSRC res;
    HGLOBAL tmpl_handle;

    if(pagesetup_get_flags(data) & PSD_ENABLEPAGESETUPTEMPLATEHANDLE)
    {
3617
	tmpl_handle = data->u.dlgw->hPageSetupTemplate;
3618
    }
3619 3620
    else if(pagesetup_get_flags(data) & PSD_ENABLEPAGESETUPTEMPLATE)
    {
3621 3622 3623 3624 3625 3626 3627
        if(data->unicode)
            res = FindResourceW(data->u.dlgw->hInstance,
                                data->u.dlgw->lpPageSetupTemplateName, MAKEINTRESOURCEW(RT_DIALOG));
        else
            res = FindResourceA(data->u.dlga->hInstance,
                                data->u.dlga->lpPageSetupTemplateName, MAKEINTRESOURCEA(RT_DIALOG));
        tmpl_handle = LoadResource(data->u.dlgw->hInstance, res);
3628 3629 3630 3631 3632 3633 3634 3635 3636 3637 3638 3639 3640 3641
    }
    else
    {
        res = FindResourceW(COMDLG32_hInstance, MAKEINTRESOURCEW(PAGESETUPDLGORD),
                            MAKEINTRESOURCEW(RT_DIALOG));
        tmpl_handle = LoadResource(COMDLG32_hInstance, res);
    }
    return LockResource(tmpl_handle);
}

static BOOL pagesetup_common(pagesetup_data *data)
{
    BOOL ret;
    void *tmpl;
3642

3643 3644 3645 3646 3647 3648 3649 3650
    if(!pagesetup_get_dlg_struct(data))
    {
        COMDLG32_SetCommDlgExtendedError(CDERR_INITIALIZATION);
        return FALSE;
    }

    pagesetup_dump_dlg_struct(data);

3651
    if(data->u.dlgw->lStructSize != sizeof(PAGESETUPDLGW))
3652 3653 3654 3655 3656 3657 3658 3659 3660 3661 3662 3663 3664
    {
        COMDLG32_SetCommDlgExtendedError(CDERR_STRUCTSIZE);
        return FALSE;
    }

    if ((pagesetup_get_flags(data) & PSD_ENABLEPAGEPAINTHOOK) &&
        (pagesetup_get_hook(data, page_paint_hook) == NULL))
    {
        COMDLG32_SetCommDlgExtendedError(CDERR_NOHOOK);
        return FALSE;
    }

    if(!(pagesetup_get_flags(data) & (PSD_INTHOUSANDTHSOFINCHES | PSD_INHUNDREDTHSOFMILLIMETERS)))
3665
        data->u.dlgw->Flags |= is_default_metric() ?
3666 3667
            PSD_INHUNDREDTHSOFMILLIMETERS : PSD_INTHOUSANDTHSOFINCHES;

3668
    if (!data->u.dlgw->hDevMode || !data->u.dlgw->hDevNames)
3669
    {
3670 3671
        WCHAR *def = get_default_printer();
        if(!def)
3672
        {
3673 3674
            if (!(pagesetup_get_flags(data) & PSD_NOWARNING))
            {
3675 3676
                WCHAR errstr[256];
                LoadStringW(COMDLG32_hInstance, PD32_NO_DEFAULT_PRINTER, errstr, 255);
3677
                MessageBoxW(data->u.dlgw->hwndOwner, errstr, 0, MB_OK | MB_ICONERROR);
3678
            }
3679
            COMDLG32_SetCommDlgExtendedError(PDERR_NODEFAULTPRN);
3680 3681
            return FALSE;
        }
3682 3683
        pagesetup_change_printer(def, data);
        HeapFree(GetProcessHeap(), 0, def);
3684
    }
3685

3686 3687
    if (pagesetup_get_flags(data) & PSD_RETURNDEFAULT)
    {
3688
        pagesetup_update_papersize(data);
3689
        return TRUE;
3690
    }
3691

3692
    tmpl = pagesetup_get_template(data);
3693

3694 3695
    ret = DialogBoxIndirectParamW(data->u.dlgw->hInstance, tmpl,
                                  data->u.dlgw->hwndOwner,
3696 3697 3698
                                  pagesetup_dlg_proc, (LPARAM)data) > 0;
    return ret;
}
3699

3700 3701 3702 3703 3704 3705 3706 3707 3708 3709 3710 3711 3712 3713 3714 3715 3716 3717 3718 3719 3720 3721 3722
/***********************************************************************
 *            PageSetupDlgA  (COMDLG32.@)
 *
 *  Displays the PAGE SETUP dialog box, which enables the user to specify
 *  specific properties of a printed page such as
 *  size, source, orientation and the width of the page margins.
 *
 * PARAMS
 *  setupdlg [IO] PAGESETUPDLGA struct
 *
 * RETURNS
 *  TRUE    if the user pressed the OK button
 *  FALSE   if the user cancelled the window or an error occurred
 *
 * NOTES
 *    The values of hDevMode and hDevNames are filled on output and can be
 *    changed in PAGESETUPDLG when they are passed in PageSetupDlg.
 *
 */
BOOL WINAPI PageSetupDlgA(LPPAGESETUPDLGA setupdlg)
{
    pagesetup_data data;

3723 3724
    data.unicode = FALSE;
    data.u.dlga  = setupdlg;
3725 3726

    return pagesetup_common(&data);
3727
}
3728

3729
/***********************************************************************
3730
 *            PageSetupDlgW  (COMDLG32.@)
3731 3732
 *
 * See PageSetupDlgA.
3733
 */
3734 3735 3736
BOOL WINAPI PageSetupDlgW(LPPAGESETUPDLGW setupdlg)
{
    pagesetup_data data;
3737

3738 3739
    data.unicode = TRUE;
    data.u.dlgw  = setupdlg;
3740

3741
    return pagesetup_common(&data);
3742
}
3743

3744
/***********************************************************************
3745
 * PrintDlgExA (COMDLG32.@)
3746 3747 3748
 *
 * See PrintDlgExW.
 *
3749 3750 3751
 * BUGS
 *   Only a Stub
 *
3752
 */
3753
HRESULT WINAPI PrintDlgExA(LPPRINTDLGEXA lppd)
3754
{
3755 3756 3757 3758 3759 3760 3761 3762 3763 3764 3765

    FIXME("(%p) stub\n", lppd);
    if ((lppd == NULL) || (lppd->lStructSize != sizeof(PRINTDLGEXA))) {
        return E_INVALIDARG;
    }

    if (!IsWindow(lppd->hwndOwner)) {
        return E_HANDLE;
    }

    return E_NOTIMPL;
3766
}
3767

3768
/***********************************************************************
3769
 * PrintDlgExW (COMDLG32.@)
3770
 *
3771
 * Display the property sheet style PRINT dialog box
3772 3773 3774 3775 3776 3777 3778 3779 3780 3781 3782 3783 3784
 *  
 * PARAMS
 *  lppd  [IO] ptr to PRINTDLGEX struct
 * 
 * RETURNS
 *  Success: S_OK
 *  Failure: One of the following COM error codes:
 *    E_OUTOFMEMORY Insufficient memory.
 *    E_INVALIDARG  One or more arguments are invalid.
 *    E_POINTER     Invalid pointer.
 *    E_HANDLE      Invalid handle.
 *    E_FAIL        Unspecified error.
 *  
3785 3786 3787 3788 3789 3790
 * NOTES
 * This Dialog enables the user to specify specific properties of the print job.
 * The property sheet can also have additional application-specific and
 * driver-specific property pages.
 *
 * BUGS
3791
 *   Not fully implemented
3792
 *
3793
 */
3794
HRESULT WINAPI PrintDlgExW(LPPRINTDLGEXW lppd)
3795
{
3796 3797 3798 3799
    DWORD     ret = E_FAIL;
    LPVOID    ptr;

    FIXME("(%p) not fully implemented\n", lppd);
3800 3801 3802 3803 3804 3805 3806 3807 3808

    if ((lppd == NULL) || (lppd->lStructSize != sizeof(PRINTDLGEXW))) {
        return E_INVALIDARG;
    }

    if (!IsWindow(lppd->hwndOwner)) {
        return E_HANDLE;
    }

3809 3810 3811 3812 3813 3814 3815 3816 3817 3818 3819 3820 3821 3822 3823 3824 3825 3826 3827 3828 3829 3830 3831 3832 3833 3834 3835 3836 3837 3838 3839 3840 3841 3842 3843 3844 3845 3846 3847 3848 3849 3850 3851 3852 3853 3854 3855 3856 3857 3858 3859 3860 3861 3862 3863 3864 3865 3866 3867 3868 3869 3870 3871 3872 3873 3874 3875 3876 3877 3878 3879
    if (lppd->Flags & PD_RETURNDEFAULT) {
        PRINTER_INFO_2W *pbuf;
        DRIVER_INFO_2W  *dbuf;
        HANDLE hprn;
        DWORD needed = 1024;
        BOOL bRet;

        if (lppd->hDevMode || lppd->hDevNames) {
            WARN("hDevMode or hDevNames non-zero for PD_RETURNDEFAULT\n");
            COMDLG32_SetCommDlgExtendedError(PDERR_RETDEFFAILURE);
            return E_INVALIDARG;
        }
        if (!PRINTDLG_OpenDefaultPrinter(&hprn)) {
            WARN("Can't find default printer\n");
            COMDLG32_SetCommDlgExtendedError(PDERR_NODEFAULTPRN);
            return E_FAIL;
        }

        pbuf = HeapAlloc(GetProcessHeap(), 0, needed);
        bRet = GetPrinterW(hprn, 2, (LPBYTE)pbuf, needed, &needed);
        if (!bRet && (GetLastError() == ERROR_INSUFFICIENT_BUFFER)) {
            HeapFree(GetProcessHeap(), 0, pbuf);
            pbuf = HeapAlloc(GetProcessHeap(), 0, needed);
            bRet = GetPrinterW(hprn, 2, (LPBYTE)pbuf, needed, &needed);
        }
        if (!bRet) {
            HeapFree(GetProcessHeap(), 0, pbuf);
            ClosePrinter(hprn);
            return E_FAIL;
        }

        needed = 1024;
        dbuf = HeapAlloc(GetProcessHeap(), 0, needed);
        bRet = GetPrinterDriverW(hprn, NULL, 3, (LPBYTE)dbuf, needed, &needed);
        if (!bRet && (GetLastError() == ERROR_INSUFFICIENT_BUFFER)) {
            HeapFree(GetProcessHeap(), 0, dbuf);
            dbuf = HeapAlloc(GetProcessHeap(), 0, needed);
            bRet = GetPrinterDriverW(hprn, NULL, 3, (LPBYTE)dbuf, needed, &needed);
        }
        if (!bRet) {
            ERR("GetPrinterDriverW failed, last error %d, fix your config for printer %s!\n",
                GetLastError(), debugstr_w(pbuf->pPrinterName));
            HeapFree(GetProcessHeap(), 0, dbuf);
            HeapFree(GetProcessHeap(), 0, pbuf);
            COMDLG32_SetCommDlgExtendedError(PDERR_RETDEFFAILURE);
            ClosePrinter(hprn);
            return E_FAIL;
        }
        ClosePrinter(hprn);

        PRINTDLG_CreateDevNamesW(&(lppd->hDevNames),
                      dbuf->pDriverPath,
                      pbuf->pPrinterName,
                      pbuf->pPortName);
        lppd->hDevMode = GlobalAlloc(GMEM_MOVEABLE, pbuf->pDevMode->dmSize +
                         pbuf->pDevMode->dmDriverExtra);
        if (lppd->hDevMode) {
            ptr = GlobalLock(lppd->hDevMode);
            if (ptr) {
                memcpy(ptr, pbuf->pDevMode, pbuf->pDevMode->dmSize +
                    pbuf->pDevMode->dmDriverExtra);
                GlobalUnlock(lppd->hDevMode);
                ret = S_OK;
            }
        }
        HeapFree(GetProcessHeap(), 0, pbuf);
        HeapFree(GetProcessHeap(), 0, dbuf);

        return ret;
    }

3880
    return E_NOTIMPL;
3881
}