printdlg.c 135 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
 * Copyright 2010 Vitaly Perov
9 10 11 12 13 14 15 16 17 18 19 20 21
 *
 * 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
22
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
23 24 25
 */
#include <ctype.h>
#include <stdlib.h>
26
#include <stdarg.h>
27
#include <stdio.h>
28
#include <string.h>
29
#include <assert.h>
30

31
#define COBJMACROS
32 33
#define NONAMELESSUNION
#define NONAMELESSSTRUCT
34
#include "windef.h"
35
#include "winbase.h"
36
#include "wingdi.h"
37
#include "winuser.h"
38 39
#include "winspool.h"
#include "winerror.h"
40 41
#include "objbase.h"
#include "commdlg.h"
42

43
#include "wine/unicode.h"
44 45
#include "wine/debug.h"

46
#include "dlgs.h"
47
#include "cderr.h"
48
#include "cdlg.h"
49

50
WINE_DEFAULT_DEBUG_CHANNEL(commdlg);
51

52 53 54
/* Yes these constants are the same, but we're just copying win98 */
#define UPDOWN_ID 0x270f
#define MAX_COPIES 9999
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 85 86 87
/* 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;

88
/* Debugging info */
89 90 91 92 93 94
struct pd_flags
{
  DWORD  flag;
  LPCSTR name;
};

95
static const struct pd_flags psd_flags[] = {
96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114
  {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}
};

115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139
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}
};
140 141
/* address of wndproc for subclassed Static control */
static WNDPROC lpfnStaticWndProc;
142
static WNDPROC edit_wndproc;
143 144
/* the text of the fake document to render for the Page Setup dialog */
static WCHAR wszFakeDocumentText[1024];
145 146 147 148
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 };
149 150 151
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 };
152

153

154 155 156 157 158 159 160 161 162 163 164 165
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;
}

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 203 204 205 206 207 208 209 210 211 212
/***********************************************************************
 * get_driver_info [internal]
 *
 * get DRIVER_INFO_3W for the current printer handle,
 * alloc the buffer, when needed
 */
static DRIVER_INFO_3W * get_driver_infoW(HANDLE hprn)
{
    DRIVER_INFO_3W *di3 = NULL;
    DWORD needed = 0;
    BOOL res;

    res = GetPrinterDriverW(hprn, NULL, 3, NULL, 0, &needed);
    if (!res && (GetLastError() == ERROR_INSUFFICIENT_BUFFER)) {
        di3 = HeapAlloc(GetProcessHeap(), 0, needed);
        res = GetPrinterDriverW(hprn, NULL, 3, (LPBYTE)di3, needed, &needed);
    }

    if (res)
        return di3;

    TRACE("GetPrinterDriverW failed with %u\n", GetLastError());
    HeapFree(GetProcessHeap(), 0, di3);
    return NULL;
}

static DRIVER_INFO_3A * get_driver_infoA(HANDLE hprn)
{
    DRIVER_INFO_3A *di3 = NULL;
    DWORD needed = 0;
    BOOL res;

    res = GetPrinterDriverA(hprn, NULL, 3, NULL, 0, &needed);
    if (!res && (GetLastError() == ERROR_INSUFFICIENT_BUFFER)) {
        di3 = HeapAlloc(GetProcessHeap(), 0, needed);
        res = GetPrinterDriverA(hprn, NULL, 3, (LPBYTE)di3, needed, &needed);
    }

    if (res)
        return di3;

    TRACE("GetPrinterDriverA failed with %u\n", GetLastError());
    HeapFree(GetProcessHeap(), 0, di3);
    return NULL;
}


213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258
/***********************************************************************
 * get_printer_info [internal]
 *
 * get PRINTER_INFO_2W for the current printer handle,
 * alloc the buffer, when needed
 */
static PRINTER_INFO_2W * get_printer_infoW(HANDLE hprn)
{
    PRINTER_INFO_2W *pi2 = NULL;
    DWORD needed = 0;
    BOOL res;

    res = GetPrinterW(hprn, 2, NULL, 0, &needed);
    if (!res && (GetLastError() == ERROR_INSUFFICIENT_BUFFER)) {
        pi2 = HeapAlloc(GetProcessHeap(), 0, needed);
        res = GetPrinterW(hprn, 2, (LPBYTE)pi2, needed, &needed);
    }

    if (res)
        return pi2;

    TRACE("GetPrinterW failed with %u\n", GetLastError());
    HeapFree(GetProcessHeap(), 0, pi2);
    return NULL;
}

static PRINTER_INFO_2A * get_printer_infoA(HANDLE hprn)
{
    PRINTER_INFO_2A *pi2 = NULL;
    DWORD needed = 0;
    BOOL res;

    res = GetPrinterA(hprn, 2, NULL, 0, &needed);
    if (!res && (GetLastError() == ERROR_INSUFFICIENT_BUFFER)) {
        pi2 = HeapAlloc(GetProcessHeap(), 0, needed);
        res = GetPrinterA(hprn, 2, (LPBYTE)pi2, needed, &needed);
    }

    if (res)
        return pi2;

    TRACE("GetPrinterA failed with %u\n", GetLastError());
    HeapFree(GetProcessHeap(), 0, pi2);
    return NULL;
}

259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320

/***********************************************************************
 * update_devmode_handle [internal]
 *
 * update a devmode handle for the given DEVMODE, alloc the buffer, when needed
 */
static HGLOBAL update_devmode_handleW(HGLOBAL hdm, DEVMODEW *dm)
{
    SIZE_T size = GlobalSize(hdm);
    LPVOID ptr;

    /* Increase / alloc the global memory block, when needed */
    if ((dm->dmSize + dm->dmDriverExtra) > size) {
        if (hdm)
            hdm = GlobalReAlloc(hdm, dm->dmSize + dm->dmDriverExtra, 0);
        else
            hdm = GlobalAlloc(GMEM_MOVEABLE, dm->dmSize + dm->dmDriverExtra);
    }

    if (hdm) {
        ptr = GlobalLock(hdm);
        if (ptr) {
            memcpy(ptr, dm, dm->dmSize + dm->dmDriverExtra);
            GlobalUnlock(hdm);
        }
        else
        {
            GlobalFree(hdm);
            hdm = NULL;
        }
    }
    return hdm;
}

static HGLOBAL update_devmode_handleA(HGLOBAL hdm, DEVMODEA *dm)
{
    SIZE_T size = GlobalSize(hdm);
    LPVOID ptr;

    /* Increase / alloc the global memory block, when needed */
    if ((dm->dmSize + dm->dmDriverExtra) > size) {
        if (hdm)
            hdm = GlobalReAlloc(hdm, dm->dmSize + dm->dmDriverExtra, 0);
        else
            hdm = GlobalAlloc(GMEM_MOVEABLE, dm->dmSize + dm->dmDriverExtra);
    }

    if (hdm) {
        ptr = GlobalLock(hdm);
        if (ptr) {
            memcpy(ptr, dm, dm->dmSize + dm->dmDriverExtra);
            GlobalUnlock(hdm);
        }
        else
        {
            GlobalFree(hdm);
            hdm = NULL;
        }
    }
    return hdm;
}

321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360
/***********************************************************
 * 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;
}

361
/***********************************************************************
362
 *    PRINTDLG_OpenDefaultPrinter
363
 *
364 365
 * Returns a winspool printer handle to the default printer in *hprn
 * Caller must call ClosePrinter on the handle
366
 *
367
 * Returns TRUE on success else FALSE
368
 */
369
static BOOL PRINTDLG_OpenDefaultPrinter(HANDLE *hprn)
370
{
371 372
    WCHAR buf[260];
    DWORD dwBufLen = sizeof(buf) / sizeof(buf[0]);
373
    BOOL res;
374
    if(!GetDefaultPrinterW(buf, &dwBufLen))
375
        return FALSE;
376
    res = OpenPrinterW(buf, hprn, NULL);
377
    if (!res)
378
        WARN("Could not open printer %s\n", debugstr_w(buf));
379
    return res;
380
}
381

382 383 384 385 386 387 388 389 390 391 392 393 394
/***********************************************************************
 *    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.
 */
395
static INT PRINTDLG_SetUpPrinterListComboA(HWND hDlg, UINT id, LPCSTR name)
396 397 398 399 400 401
{
    DWORD needed, num;
    INT i;
    LPPRINTER_INFO_2A pi;
    EnumPrintersA(PRINTER_ENUM_LOCAL, NULL, 2, NULL, 0, &needed, &num);
    pi = HeapAlloc(GetProcessHeap(), 0, needed);
402
    EnumPrintersA(PRINTER_ENUM_LOCAL, NULL, 2, (LPBYTE)pi, needed, &needed,
403 404
		  &num);

405 406
    SendDlgItemMessageA(hDlg, id, CB_RESETCONTENT, 0, 0);
    
407 408 409
    for(i = 0; i < num; i++) {
        SendDlgItemMessageA(hDlg, id, CB_ADDSTRING, 0,
			    (LPARAM)pi[i].pPrinterName );
410
    }
411 412 413 414 415 416
    HeapFree(GetProcessHeap(), 0, pi);
    if(!name ||
       (i = SendDlgItemMessageA(hDlg, id, CB_FINDSTRINGEXACT, -1,
				(LPARAM)name)) == CB_ERR) {

        char buf[260];
417
        DWORD dwBufLen = sizeof(buf);
418 419 420
        if (name != NULL)
            WARN("Can't find %s in printer list so trying to find default\n",
	        debugstr_a(name));
421
	if(!GetDefaultPrinterA(buf, &dwBufLen))
422 423 424
	    return num;
	i = SendDlgItemMessageA(hDlg, id, CB_FINDSTRINGEXACT, -1, (LPARAM)buf);
	if(i == CB_ERR)
425
	    FIXME("Can't find default printer in printer list\n");
426
    }
427 428
    SendDlgItemMessageA(hDlg, id, CB_SETCURSEL, i, 0);
    return num;
429 430
}

431 432 433 434 435 436 437
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);
438
    EnumPrintersW(PRINTER_ENUM_LOCAL, NULL, 2, (LPBYTE)pi, needed, &needed,
439 440 441 442 443 444 445 446 447 448
		  &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) {
449 450
        WCHAR buf[260];
        DWORD dwBufLen = sizeof(buf)/sizeof(buf[0]);
451 452 453
        if (name != NULL)
            WARN("Can't find %s in printer list so trying to find default\n",
	        debugstr_w(name));
454
	if(!GetDefaultPrinterW(buf, &dwBufLen))
455
	    return num;
456
	i = SendDlgItemMessageW(hDlg, id, CB_FINDSTRINGEXACT, -1, (LPARAM)buf);
457
	if(i == CB_ERR)
458
	    TRACE("Can't find default printer in printer list\n");
459 460 461 462 463
    }
    SendDlgItemMessageW(hDlg, id, CB_SETCURSEL, i, 0);
    return num;
}

464
/***********************************************************************
465
 *             PRINTDLG_CreateDevNames          [internal]
466 467
 *
 *
468
 *   creates a DevNames structure.
469
 *
470
 *  (NB. when we handle unicode the offsets will be in wchars).
471
 */
472 473
static BOOL PRINTDLG_CreateDevNames(HGLOBAL *hmem, const char* DeviceDriverName,
				    const char* DeviceName, const char* OutputPort)
474
{
475 476 477 478 479
    long size;
    char*   pDevNamesSpace;
    char*   pTempPtr;
    LPDEVNAMES lpDevNames;
    char buf[260];
480
    DWORD dwBufLen = sizeof(buf);
481
    const char *p;
482

483 484
    p = strrchr( DeviceDriverName, '\\' );
    if (p) DeviceDriverName = p + 1;
485

486 487 488 489
    size = strlen(DeviceDriverName) + 1
            + strlen(DeviceName) + 1
            + strlen(OutputPort) + 1
            + sizeof(DEVNAMES);
490

491 492
    if(*hmem)
        *hmem = GlobalReAlloc(*hmem, size, GMEM_MOVEABLE);
493
    else
494 495
        *hmem = GlobalAlloc(GMEM_MOVEABLE, size);
    if (*hmem == 0)
496
        return FALSE;
497

498 499
    pDevNamesSpace = GlobalLock(*hmem);
    lpDevNames = (LPDEVNAMES) pDevNamesSpace;
500

501 502 503
    pTempPtr = pDevNamesSpace + sizeof(DEVNAMES);
    strcpy(pTempPtr, DeviceDriverName);
    lpDevNames->wDriverOffset = pTempPtr - pDevNamesSpace;
504

505 506 507
    pTempPtr += strlen(DeviceDriverName) + 1;
    strcpy(pTempPtr, DeviceName);
    lpDevNames->wDeviceOffset = pTempPtr - pDevNamesSpace;
508

509 510 511 512
    pTempPtr += strlen(DeviceName) + 1;
    strcpy(pTempPtr, OutputPort);
    lpDevNames->wOutputOffset = pTempPtr - pDevNamesSpace;

513
    GetDefaultPrinterA(buf, &dwBufLen);
514 515 516 517
    lpDevNames->wDefault = (strcmp(buf, DeviceName) == 0) ? 1 : 0;
    GlobalUnlock(*hmem);
    return TRUE;
}
518

519
static BOOL PRINTDLG_CreateDevNamesW(HGLOBAL *hmem, LPCWSTR DeviceDriverName,
520 521 522 523 524 525 526
				    LPCWSTR DeviceName, LPCWSTR OutputPort)
{
    long size;
    LPWSTR   pDevNamesSpace;
    LPWSTR   pTempPtr;
    LPDEVNAMES lpDevNames;
    WCHAR bufW[260];
527
    DWORD dwBufLen = sizeof(bufW) / sizeof(WCHAR);
528
    const WCHAR *p;
529

530 531
    p = strrchrW( DeviceDriverName, '\\' );
    if (p) DeviceDriverName = p + 1;
532

533 534 535 536
    size = sizeof(WCHAR)*lstrlenW(DeviceDriverName) + 2
            + sizeof(WCHAR)*lstrlenW(DeviceName) + 2
            + sizeof(WCHAR)*lstrlenW(OutputPort) + 2
            + sizeof(DEVNAMES);
537

538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554
    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;
555

556 557 558 559
    pTempPtr += lstrlenW(DeviceName) + 1;
    lstrcpyW(pTempPtr, OutputPort);
    lpDevNames->wOutputOffset = pTempPtr - pDevNamesSpace;

560
    GetDefaultPrinterW(bufW, &dwBufLen);
561 562 563 564 565
    lpDevNames->wDefault = (lstrcmpW(bufW, DeviceName) == 0) ? 1 : 0;
    GlobalUnlock(*hmem);
    return TRUE;
}

566
/***********************************************************************
567 568 569
 *             PRINTDLG_UpdatePrintDlg          [internal]
 *
 *
Francois Gouget's avatar
Francois Gouget committed
570
 *   updates the PrintDlg structure for return values.
571
 *
572 573
 * RETURNS
 *   FALSE if user is not allowed to close (i.e. wrong nTo or nFrom values)
Francois Gouget's avatar
Francois Gouget committed
574
 *   TRUE  if successful.
575
 */
576
static BOOL PRINTDLG_UpdatePrintDlgA(HWND hDlg,
577
				    PRINT_PTRA* PrintStructures)
578
{
579
    LPPRINTDLGA       lppd = PrintStructures->lpPrintDlg;
580 581 582 583
    PDEVMODEA         lpdm = PrintStructures->lpDevMode;
    LPPRINTER_INFO_2A pi = PrintStructures->lpPrinterInfo;


584 585 586 587
    if(!lpdm) {
	FIXME("No lpdm ptr?\n");
	return FALSE;
    }
588 589 590 591 592 593 594 595 596


    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;
597
            BOOL translated;
598
	    nFromPage = GetDlgItemInt(hDlg, edt1, NULL, FALSE);
599 600 601 602 603
	    nToPage   = GetDlgItemInt(hDlg, edt2, &translated, FALSE);

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

604 605
	    if (nFromPage < lppd->nMinPage || nFromPage > lppd->nMaxPage ||
		nToPage < lppd->nMinPage || nToPage > lppd->nMaxPage) {
606 607 608 609 610 611
	        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);
612 613 614 615
		return FALSE;
	    }
	    lppd->nFromPage = nFromPage;
	    lppd->nToPage   = nToPage;
616
	    lppd->Flags |= PD_PAGENUMS;
617
	}
618 619
	else
	    lppd->Flags &= ~PD_PAGENUMS;
620

621 622 623 624 625
        if (IsDlgButtonChecked(hDlg, rad2) == BST_CHECKED) /* Selection */
            lppd->Flags |= PD_SELECTION;
        else
            lppd->Flags &= ~PD_SELECTION;

626
	if (IsDlgButtonChecked(hDlg, chx1) == BST_CHECKED) {/* Print to file */
627
	    static char file[] = "FILE:";
628
	    lppd->Flags |= PD_PRINTTOFILE;
629
	    pi->pPortName = file;
630
	}
631

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

636 637 638 639 640 641 642 643 644 645
	/* 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)
646
	        lpdm->dmCollate =
647 648
		  (IsDlgButtonChecked(hDlg, chx2) == BST_CHECKED);
	    if (lpdm->dmFields & DM_COPIES)
649
	        lpdm->u1.s1.dmCopies = GetDlgItemInt(hDlg, edt3, NULL, FALSE);
650
	} else {
651
            /* Application is responsible for multiple copies */
652 653 654 655 656
	    if (IsDlgButtonChecked(hDlg, chx2) == BST_CHECKED)
	        lppd->Flags |= PD_COLLATE;
            else
               lppd->Flags &= ~PD_COLLATE;
            lppd->nCopies = GetDlgItemInt(hDlg, edt3, NULL, FALSE);
657 658
            /* multiple copies already included in the document. Driver must print only one copy */
            lpdm->u1.s1.dmCopies = 1;
659
	}
660 661 662 663 664 665 666 667 668 669 670 671 672 673 674

	/* 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);
	    }
	}
675 676
    }
    return TRUE;
677 678
}

679
static BOOL PRINTDLG_UpdatePrintDlgW(HWND hDlg,
680 681
				    PRINT_PTRW* PrintStructures)
{
682
    LPPRINTDLGW       lppd = PrintStructures->lpPrintDlg;
683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699
    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;
700
            BOOL translated;
701
	    nFromPage = GetDlgItemInt(hDlg, edt1, NULL, FALSE);
702 703 704 705 706
	    nToPage   = GetDlgItemInt(hDlg, edt2, &translated, FALSE);

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

707 708
	    if (nFromPage < lppd->nMinPage || nFromPage > lppd->nMaxPage ||
		nToPage < lppd->nMinPage || nToPage > lppd->nMaxPage) {
709 710
	        WCHAR resourcestr[256];
		WCHAR resultstr[256];
711
                DWORD_PTR args[2];
712
		LoadStringW(COMDLG32_hInstance, PD32_INVALID_PAGE_RANGE,
713
			    resourcestr, 255);
714 715 716 717 718 719
                args[0] = lppd->nMinPage;
                args[1] = lppd->nMaxPage;
                FormatMessageW(FORMAT_MESSAGE_FROM_STRING|FORMAT_MESSAGE_ARGUMENT_ARRAY,
                               resourcestr, 0, 0, resultstr,
                               sizeof(resultstr)/sizeof(*resultstr),
                               (__ms_va_list*)args);
720
		LoadStringW(COMDLG32_hInstance, PD32_PRINT_TITLE,
721
			    resourcestr, 255);
722
		MessageBoxW(hDlg, resultstr, resourcestr,
723 724 725 726 727
			    MB_OK | MB_ICONWARNING);
		return FALSE;
	    }
	    lppd->nFromPage = nFromPage;
	    lppd->nToPage   = nToPage;
728
	    lppd->Flags |= PD_PAGENUMS;
729
	}
730 731
	else
	    lppd->Flags &= ~PD_PAGENUMS;
732

733 734 735 736 737
        if (IsDlgButtonChecked(hDlg, rad2) == BST_CHECKED) /* Selection */
            lppd->Flags |= PD_SELECTION;
        else
            lppd->Flags &= ~PD_SELECTION;

738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757
	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)
758
	        lpdm->dmCollate =
759 760
		  (IsDlgButtonChecked(hDlg, chx2) == BST_CHECKED);
	    if (lpdm->dmFields & DM_COPIES)
761
	        lpdm->u1.s1.dmCopies = GetDlgItemInt(hDlg, edt3, NULL, FALSE);
762 763 764 765 766 767 768 769 770 771 772
	} 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;
}

773 774
/************************************************************************
 * PRINTDLG_SetUpPaperComboBox
775
 *
776 777 778
 * 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.
779
 */
780
static BOOL PRINTDLG_SetUpPaperComboBoxA(HWND hDlg,
781
					int   nIDComboBox,
782
					char* PrinterName,
783 784
					char* PortName,
					LPDEVMODEA dm)
785 786
{
    int     i;
787
    int     NrOfEntries;
788
    char*   Names;
789
    WORD*   Words;
790 791
    DWORD   Sel, old_Sel;
    WORD    oldWord = 0, newWord = 0; /* DMPAPER_ and DMBIN_ start at 1 */
792 793 794
    int     NamesSize;
    int     fwCapability_Names;
    int     fwCapability_Words;
795

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

798
    /* query the dialog box for the current selected value */
799 800
    Sel = SendDlgItemMessageA(hDlg, nIDComboBox, CB_GETCURSEL, 0, 0);
    if(Sel != CB_ERR) {
801 802 803 804 805 806
        /* 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);
807 808 809
        if(oldWord >= DMPAPER_USER) /* DMPAPER_USER == DMBIN_USER */
            oldWord = 0; /* There's no point in trying to keep custom
                            paper / bin sizes across printers */
810
    }
811

812 813 814
    if (dm)
        newWord = (nIDComboBox == cmb2) ? dm->u1.s1.dmPaperSize : dm->u1.s1.dmDefaultSource;

815
    if (nIDComboBox == cmb2) {
816 817 818
         NamesSize          = 64;
         fwCapability_Names = DC_PAPERNAMES;
         fwCapability_Words = DC_PAPERS;
819
    } else {
820 821 822 823
         nIDComboBox        = cmb3;
         NamesSize          = 24;
         fwCapability_Names = DC_BINNAMES;
         fwCapability_Words = DC_BINS;
824
    }
825

826
    NrOfEntries = DeviceCapabilitiesA(PrinterName, PortName,
827
                                      fwCapability_Names, NULL, dm);
828
    if (NrOfEntries == 0)
829
         WARN("no Name Entries found!\n");
830 831
    else if (NrOfEntries < 0)
         return FALSE;
832 833 834 835 836 837 838

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

839
    Names = HeapAlloc(GetProcessHeap(),0, NrOfEntries*sizeof(char)*NamesSize);
840
    Words = HeapAlloc(GetProcessHeap(),0, NrOfEntries*sizeof(WORD));
841
    DeviceCapabilitiesA(PrinterName, PortName, fwCapability_Names, Names, dm);
842 843 844
    NrOfEntries = DeviceCapabilitiesA(PrinterName, PortName,
				      fwCapability_Words, (LPSTR)Words, dm);

845 846
    /* reset any current content in the combobox */
    SendDlgItemMessageA(hDlg, nIDComboBox, CB_RESETCONTENT, 0, 0);
847

848
    /* store new content */
849 850 851
    for (i = 0; i < NrOfEntries; i++) {
        DWORD pos = SendDlgItemMessageA(hDlg, nIDComboBox, CB_ADDSTRING, 0,
					(LPARAM)(&Names[i*NamesSize]) );
852
	SendDlgItemMessageA(hDlg, nIDComboBox, CB_SETITEMDATA, pos,
853 854
			    Words[i]);
    }
855

856 857
    /* Look for old selection or the new default.
       Can't do this is previous loop since item order will change as more items are added */
858
    Sel = 0;
859
    old_Sel = NrOfEntries;
860 861 862
    for (i = 0; i < NrOfEntries; i++) {
        if(SendDlgItemMessageA(hDlg, nIDComboBox, CB_GETITEMDATA, i, 0) ==
	   oldWord) {
863
	    old_Sel = i;
864 865
	    break;
	}
866 867
        if(SendDlgItemMessageA(hDlg, nIDComboBox, CB_GETITEMDATA, i, 0) == newWord)
	    Sel = i;
868
    }
869 870 871 872 873 874 875 876 877 878 879 880 881

    if(old_Sel < NrOfEntries)
    {
        if (dm)
        {
            if(nIDComboBox == cmb2)
                dm->u1.s1.dmPaperSize = oldWord;
            else
                dm->u1.s1.dmDefaultSource = oldWord;
        }
        Sel = old_Sel;
    }

882
    SendDlgItemMessageA(hDlg, nIDComboBox, CB_SETCURSEL, Sel, 0);
883

884 885 886 887
    HeapFree(GetProcessHeap(),0,Words);
    HeapFree(GetProcessHeap(),0,Names);
    return TRUE;
}
888

889 890
static BOOL PRINTDLG_SetUpPaperComboBoxW(HWND hDlg,
					int   nIDComboBox,
891 892
					const WCHAR* PrinterName,
					const WCHAR* PortName,
893
					LPDEVMODEW dm)
894
{
895 896 897 898
    int     i;
    int     NrOfEntries;
    WCHAR*  Names;
    WORD*   Words;
899 900
    DWORD   Sel, old_Sel;
    WORD    oldWord = 0, newWord = 0; /* DMPAPER_ and DMBIN_ start at 1 */
901 902 903
    int     NamesSize;
    int     fwCapability_Names;
    int     fwCapability_Words;
904

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

907
    /* query the dialog box for the current selected value */
908
    Sel = SendDlgItemMessageW(hDlg, nIDComboBox, CB_GETCURSEL, 0, 0);
909 910 911 912 913
    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.
         */
914
        oldWord = SendDlgItemMessageW(hDlg, nIDComboBox, CB_GETITEMDATA,
915
                                      Sel, 0);
916 917 918 919

        if(oldWord >= DMPAPER_USER) /* DMPAPER_USER == DMBIN_USER */
            oldWord = 0; /* There's no point in trying to keep custom
                            paper / bin sizes across printers */
920
    }
921

922 923 924
    if (dm)
        newWord = (nIDComboBox == cmb2) ? dm->u1.s1.dmPaperSize : dm->u1.s1.dmDefaultSource;

925 926 927 928 929 930 931 932 933 934
    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;
    }
935

936 937 938 939 940 941 942 943 944 945 946 947 948 949 950
    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));
951
    DeviceCapabilitiesW(PrinterName, PortName, fwCapability_Names, Names, dm);
952
    NrOfEntries = DeviceCapabilitiesW(PrinterName, PortName,
953
                                      fwCapability_Words, Words, dm);
954 955

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

958 959 960 961
    /* store new content */
    for (i = 0; i < NrOfEntries; i++) {
        DWORD pos = SendDlgItemMessageW(hDlg, nIDComboBox, CB_ADDSTRING, 0,
					(LPARAM)(&Names[i*NamesSize]) );
962
	SendDlgItemMessageW(hDlg, nIDComboBox, CB_SETITEMDATA, pos,
963 964 965
			    Words[i]);
    }

966 967
    /* Look for old selection or the new default.
       Can't do this is previous loop since item order will change as more items are added */
968
    Sel = 0;
969
    old_Sel = NrOfEntries;
970
    for (i = 0; i < NrOfEntries; i++) {
971
        if(SendDlgItemMessageW(hDlg, nIDComboBox, CB_GETITEMDATA, i, 0) ==
972
	   oldWord) {
973
	    old_Sel = i;
974 975
	    break;
	}
976 977
        if(SendDlgItemMessageA(hDlg, nIDComboBox, CB_GETITEMDATA, i, 0) == newWord)
            Sel = i;
978
    }
979 980 981 982 983 984 985 986 987 988 989 990 991

    if(old_Sel < NrOfEntries)
    {
        if (dm)
        {
            if(nIDComboBox == cmb2)
                dm->u1.s1.dmPaperSize = oldWord;
            else
                dm->u1.s1.dmDefaultSource = oldWord;
        }
        Sel = old_Sel;
    }

992
    SendDlgItemMessageW(hDlg, nIDComboBox, CB_SETCURSEL, Sel, 0);
993 994 995 996 997 998 999 1000 1001 1002

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


/***********************************************************************
 *               PRINTDLG_UpdatePrinterInfoTexts               [internal]
 */
1003
static void PRINTDLG_UpdatePrinterInfoTextsA(HWND hDlg, const PRINTER_INFO_2A *pi)
1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014
{
    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)) {
1015
	    LoadStringA(COMDLG32_hInstance, PD32_PRINTER_STATUS_PAUSED+i,
1016 1017 1018 1019 1020
			ResourceString, 255);
	    strcat(StatusMsg,ResourceString);
        }
    }
    /* append "ready" */
1021
    /* FIXME: status==ready must only be appended if really so.
1022
              but how to detect? */
1023
    LoadStringA(COMDLG32_hInstance, PD32_PRINTER_STATUS_READY,
1024 1025
		ResourceString, 255);
    strcat(StatusMsg,ResourceString);
1026
    SetDlgItemTextA(hDlg, stc12, StatusMsg);
1027 1028

    /* set all other printer info texts */
1029 1030
    SetDlgItemTextA(hDlg, stc11, pi->pDriverName);
    
1031
    if (pi->pLocation != NULL && pi->pLocation[0] != '\0')
1032
        SetDlgItemTextA(hDlg, stc14, pi->pLocation);
1033
    else
1034 1035
        SetDlgItemTextA(hDlg, stc14, pi->pPortName);
    SetDlgItemTextA(hDlg, stc13, pi->pComment ? pi->pComment : "");
1036 1037 1038
    return;
}

1039
static void PRINTDLG_UpdatePrinterInfoTextsW(HWND hDlg, const PRINTER_INFO_2W *pi)
1040 1041 1042
{
    WCHAR   StatusMsg[256];
    WCHAR   ResourceString[256];
1043
    static const WCHAR emptyW[] = {0};
1044 1045 1046 1047 1048 1049 1050 1051
    int    i;

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

    /* add all status messages */
    for (i = 0; i < 25; i++) {
        if (pi->Status & (1<<i)) {
1052
	    LoadStringW(COMDLG32_hInstance, PD32_PRINTER_STATUS_PAUSED+i,
1053 1054 1055 1056 1057
			ResourceString, 255);
	    lstrcatW(StatusMsg,ResourceString);
        }
    }
    /* append "ready" */
1058
    /* FIXME: status==ready must only be appended if really so.
1059
              but how to detect? */
1060
    LoadStringW(COMDLG32_hInstance, PD32_PRINTER_STATUS_READY,
1061 1062
		ResourceString, 255);
    lstrcatW(StatusMsg,ResourceString);
1063
    SetDlgItemTextW(hDlg, stc12, StatusMsg);
1064 1065

    /* set all other printer info texts */
1066
    SetDlgItemTextW(hDlg, stc11, pi->pDriverName);
1067
    if (pi->pLocation != NULL && pi->pLocation[0] != '\0')
1068
        SetDlgItemTextW(hDlg, stc14, pi->pLocation);
1069
    else
1070 1071
        SetDlgItemTextW(hDlg, stc14, pi->pPortName);
    SetDlgItemTextW(hDlg, stc13, pi->pComment ? pi->pComment : emptyW);
1072 1073
}

1074

1075 1076 1077 1078
/*******************************************************************
 *
 *                 PRINTDLG_ChangePrinter
 *
1079
 */
1080
static BOOL PRINTDLG_ChangePrinterA(HWND hDlg, char *name, PRINT_PTRA *PrintStructures)
1081
{
1082
    LPPRINTDLGA lppd = PrintStructures->lpPrintDlg;
1083 1084 1085 1086 1087
    LPDEVMODEA lpdm = NULL;
    LONG dmSize;
    DWORD needed;
    HANDLE hprn;

1088 1089
    HeapFree(GetProcessHeap(),0, PrintStructures->lpPrinterInfo);
    HeapFree(GetProcessHeap(),0, PrintStructures->lpDriverInfo);
1090 1091 1092 1093 1094 1095 1096 1097
    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);
1098 1099 1100 1101 1102 1103 1104
    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;
    }
1105
    ClosePrinter(hprn);
1106

1107
    PRINTDLG_UpdatePrinterInfoTextsA(hDlg, PrintStructures->lpPrinterInfo);
1108

1109 1110
    HeapFree(GetProcessHeap(), 0, PrintStructures->lpDevMode);
    PrintStructures->lpDevMode = NULL;
1111

1112 1113 1114 1115
    dmSize = DocumentPropertiesA(0, 0, name, NULL, NULL, 0);
    if(dmSize == -1) {
        ERR("DocumentProperties fails on %s\n", debugstr_a(name));
	return FALSE;
1116
    }
1117 1118 1119 1120
    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
1121 1122
			  !lstrcmpA( (LPSTR) lpdm->dmDeviceName,
				     (LPSTR) PrintStructures->lpDevMode->dmDeviceName)) {
1123 1124 1125
      /* Supplied devicemode matches current printer so try to use it */
        DocumentPropertiesA(0, 0, name, PrintStructures->lpDevMode, lpdm,
			    DM_OUT_BUFFER | DM_IN_BUFFER);
1126
    }
1127 1128 1129 1130 1131 1132
    if(lpdm)
        GlobalUnlock(lppd->hDevMode);

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

    if(!(lppd->Flags & PD_PRINTSETUP)) {
1133 1134 1135 1136 1137 1138
	/* 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);

1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154
	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);
	}
1155 1156

	/* Collate pages
1157 1158 1159 1160
	 *
	 * FIXME: The ico3 is not displayed for some reason. I don't know why.
	 */
	if (lppd->Flags & PD_COLLATE) {
1161
            SendDlgItemMessageA(hDlg, ico3, STM_SETIMAGE, IMAGE_ICON,
1162 1163 1164
				(LPARAM)PrintStructures->hCollateIcon);
	    CheckDlgButton(hDlg, chx2, 1);
	} else {
1165
            SendDlgItemMessageA(hDlg, ico3, STM_SETIMAGE, IMAGE_ICON,
1166 1167 1168
				(LPARAM)PrintStructures->hNoCollateIcon);
	    CheckDlgButton(hDlg, chx2, 0);
	}
1169

1170 1171 1172
	if (lppd->Flags & PD_USEDEVMODECOPIESANDCOLLATE) {
	  /* if printer doesn't support it: no Collate */
	    if (!(lpdm->dmFields & DM_COLLATE)) {
1173 1174
	        EnableWindow(GetDlgItem(hDlg, chx2), FALSE);
		EnableWindow(GetDlgItem(hDlg, ico3), FALSE);
1175 1176
	    }
	}
1177

1178
	/* nCopies */
1179 1180 1181 1182 1183
	{
	  INT copies;
	  if (lppd->hDevMode == 0)
	      copies = lppd->nCopies;
	  else
1184
	      copies = lpdm->u1.s1.dmCopies;
1185 1186 1187 1188
	  if(copies == 0) copies = 1;
	  else if(copies < 0) copies = MAX_COPIES;
	  SetDlgItemInt(hDlg, edt3, copies, FALSE);
	}
1189 1190 1191 1192

	if (lppd->Flags & PD_USEDEVMODECOPIESANDCOLLATE) {
	  /* if printer doesn't support it: no nCopies */
	    if (!(lpdm->dmFields & DM_COPIES)) {
1193 1194
	        EnableWindow(GetDlgItem(hDlg, edt3), FALSE);
		EnableWindow(GetDlgItem(hDlg, stc5), FALSE);
1195
	    }
1196
	}
1197

1198 1199 1200
	/* print to file */
	CheckDlgButton(hDlg, chx1, (lppd->Flags & PD_PRINTTOFILE) ? 1 : 0);
	if (lppd->Flags & PD_DISABLEPRINTTOFILE)
1201
            EnableWindow(GetDlgItem(hDlg, chx1), FALSE);
1202 1203 1204
	if (lppd->Flags & PD_HIDEPRINTTOFILE)
            ShowWindow(GetDlgItem(hDlg, chx1), SW_HIDE);

1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216
	/* 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];
1217
		DWORD i;
1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259
		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);
	    }
	}
1260
    } else { /* PD_PRINTSETUP */
1261 1262
      BOOL bPortrait = (lpdm->u1.s1.dmOrientation == DMORIENT_PORTRAIT);

1263 1264 1265 1266 1267 1268 1269 1270 1271
      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);
1272
      SendDlgItemMessageA(hDlg, ico1, STM_SETIMAGE, IMAGE_ICON,
1273 1274
                          (LPARAM)(bPortrait ? PrintStructures->hPortraitIcon :
                                   PrintStructures->hLandscapeIcon));
1275

1276 1277 1278 1279 1280
    }

    /* help button */
    if ((lppd->Flags & PD_SHOWHELP)==0) {
        /* hide if PD_SHOWHELP not specified */
1281
        ShowWindow(GetDlgItem(hDlg, pshHelp), SW_HIDE);
1282 1283 1284 1285 1286 1287 1288
    }
    return TRUE;
}

static BOOL PRINTDLG_ChangePrinterW(HWND hDlg, WCHAR *name,
				   PRINT_PTRW *PrintStructures)
{
1289
    LPPRINTDLGW lppd = PrintStructures->lpPrintDlg;
1290 1291 1292 1293 1294
    LPDEVMODEW lpdm = NULL;
    LONG dmSize;
    DWORD needed;
    HANDLE hprn;

1295 1296
    HeapFree(GetProcessHeap(),0, PrintStructures->lpPrinterInfo);
    HeapFree(GetProcessHeap(),0, PrintStructures->lpDriverInfo);
1297 1298 1299 1300 1301
    if(!OpenPrinterW(name, &hprn, NULL)) {
        ERR("Can't open printer %s\n", debugstr_w(name));
	return FALSE;
    }
    GetPrinterW(hprn, 2, NULL, 0, &needed);
1302
    PrintStructures->lpPrinterInfo = HeapAlloc(GetProcessHeap(),0,needed);
1303 1304 1305
    GetPrinterW(hprn, 2, (LPBYTE)PrintStructures->lpPrinterInfo, needed,
		&needed);
    GetPrinterDriverW(hprn, NULL, 3, NULL, 0, &needed);
1306
    PrintStructures->lpDriverInfo = HeapAlloc(GetProcessHeap(),0,needed);
1307 1308 1309 1310 1311 1312 1313 1314 1315
    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);

1316 1317
    HeapFree(GetProcessHeap(), 0, PrintStructures->lpDevMode);
    PrintStructures->lpDevMode = NULL;
1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339

    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)) {
1340 1341 1342 1343 1344 1345
	/* 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);

1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361
	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);
	}
1362 1363

	/* Collate pages
1364 1365 1366 1367
	 *
	 * FIXME: The ico3 is not displayed for some reason. I don't know why.
	 */
	if (lppd->Flags & PD_COLLATE) {
1368
            SendDlgItemMessageW(hDlg, ico3, STM_SETIMAGE, IMAGE_ICON,
1369 1370 1371
				(LPARAM)PrintStructures->hCollateIcon);
	    CheckDlgButton(hDlg, chx2, 1);
	} else {
1372
            SendDlgItemMessageW(hDlg, ico3, STM_SETIMAGE, IMAGE_ICON,
1373 1374 1375 1376 1377 1378 1379
				(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)) {
1380 1381
	        EnableWindow(GetDlgItem(hDlg, chx2), FALSE);
		EnableWindow(GetDlgItem(hDlg, ico3), FALSE);
1382 1383 1384 1385 1386 1387 1388 1389 1390
	    }
	}

	/* nCopies */
	{
	  INT copies;
	  if (lppd->hDevMode == 0)
	      copies = lppd->nCopies;
	  else
1391
	      copies = lpdm->u1.s1.dmCopies;
1392 1393 1394 1395 1396 1397 1398 1399
	  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)) {
1400 1401
	        EnableWindow(GetDlgItem(hDlg, edt3), FALSE);
		EnableWindow(GetDlgItem(hDlg, stc5), FALSE);
1402 1403 1404 1405 1406 1407
	    }
	}

	/* print to file */
	CheckDlgButton(hDlg, chx1, (lppd->Flags & PD_PRINTTOFILE) ? 1 : 0);
	if (lppd->Flags & PD_DISABLEPRINTTOFILE)
1408
            EnableWindow(GetDlgItem(hDlg, chx1), FALSE);
1409 1410 1411 1412 1413 1414 1415
	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,
1416 1417 1418
				  PrintStructures->lpPrinterInfo->pPrinterName,
				  PrintStructures->lpPrinterInfo->pPortName,
				  lpdm);
1419
      PRINTDLG_SetUpPaperComboBoxW(hDlg, cmb3,
1420 1421 1422
				  PrintStructures->lpPrinterInfo->pPrinterName,
				  PrintStructures->lpPrinterInfo->pPortName,
				  lpdm);
1423
      CheckRadioButton(hDlg, rad1, rad2, bPortrait ? rad1: rad2);
1424
      SendDlgItemMessageW(hDlg, ico1, STM_SETIMAGE, IMAGE_ICON,
1425 1426
                          (LPARAM)(bPortrait ? PrintStructures->hPortraitIcon :
                                   PrintStructures->hLandscapeIcon));
1427

Alexandre Julliard's avatar
Alexandre Julliard committed
1428 1429
    }

1430 1431 1432
    /* help button */
    if ((lppd->Flags & PD_SHOWHELP)==0) {
        /* hide if PD_SHOWHELP not specified */
1433
        ShowWindow(GetDlgItem(hDlg, pshHelp), SW_HIDE);
1434 1435
    }
    return TRUE;
1436
}
1437

1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456
 /***********************************************************************
 *           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);
1457
          MessageBoxW(hDlg, resultstr, resourcestr,MB_OK | MB_ICONWARNING);
1458 1459 1460 1461
          return FALSE;
    }
}

1462
/***********************************************************************
1463
 *           PRINTDLG_WMInitDialog                      [internal]
1464
 */
1465
static LRESULT PRINTDLG_WMInitDialog(HWND hDlg,
1466
				     PRINT_PTRA* PrintStructures)
1467
{
1468
    LPPRINTDLGA lppd = PrintStructures->lpPrintDlg;
1469 1470 1471 1472
    DEVNAMES *pdn;
    DEVMODEA *pdm;
    char *name = NULL;
    UINT comboID = (lppd->Flags & PD_PRINTSETUP) ? cmb1 : cmb4;
1473

1474
    /* load Collate ICONs */
1475
    /* We load these with LoadImage because they are not a standard
1476
       size and we don't want them rescaled */
1477
    PrintStructures->hCollateIcon =
1478
      LoadImageA(COMDLG32_hInstance, "PD32_COLLATE", IMAGE_ICON, 0, 0, 0);
1479
    PrintStructures->hNoCollateIcon =
1480
      LoadImageA(COMDLG32_hInstance, "PD32_NOCOLLATE", IMAGE_ICON, 0, 0, 0);
1481 1482 1483 1484 1485 1486 1487

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

1488
    /* display the collate/no_collate icon */
1489
    SendDlgItemMessageA(hDlg, ico3, STM_SETIMAGE, IMAGE_ICON,
1490 1491
                        (LPARAM)PrintStructures->hNoCollateIcon);

1492
    if(PrintStructures->hCollateIcon == 0 ||
1493 1494 1495
       PrintStructures->hNoCollateIcon == 0 ||
       PrintStructures->hPortraitIcon == 0 ||
       PrintStructures->hLandscapeIcon == 0) {
Andrey Gusev's avatar
Andrey Gusev committed
1496
        ERR("no icon in resource file\n");
1497 1498 1499
	COMDLG32_SetCommDlgExtendedError(CDERR_LOADRESFAILURE);
	EndDialog(hDlg, FALSE);
    }
1500

1501 1502 1503 1504 1505
    /*
     * 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) {
1506
        if((PrintStructures->HelpMessageID =
1507
	    RegisterWindowMessageA(HELPMSGSTRINGA)) == 0) {
1508 1509 1510 1511 1512
	    COMDLG32_SetCommDlgExtendedError(CDERR_REGISTERMSGFAIL);
	    return FALSE;
	}
    } else
        PrintStructures->HelpMessageID = 0;
1513

1514 1515 1516 1517 1518 1519 1520 1521 1522
    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);
    }

1523
    /* FIXME: I allow more freedom than either Win95 or WinNT,
1524
     *        which do not agree on what errors should be thrown or not
1525 1526 1527 1528
     *        in case nToPage or nFromPage is out-of-range.
     */
    if (lppd->nMaxPage < lppd->nMinPage)
    	lppd->nMaxPage = lppd->nMinPage;
1529 1530
    if (lppd->nMinPage == lppd->nMaxPage)
    	lppd->Flags |= PD_NOPAGENUMS;
1531 1532 1533 1534 1535 1536 1537 1538
    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;
1539

1540 1541
    /* if we have the combo box, fill it */
    if (GetDlgItem(hDlg,comboID)) {
1542
	/* Fill Combobox
1543 1544 1545 1546 1547 1548
	 */
	pdn = GlobalLock(lppd->hDevNames);
	pdm = GlobalLock(lppd->hDevMode);
	if(pdn)
	    name = (char*)pdn + pdn->wDeviceOffset;
	else if(pdm)
1549
	    name = (char*)pdm->dmDeviceName;
1550
	PRINTDLG_SetUpPrinterListComboA(hDlg, comboID, name);
1551 1552 1553 1554 1555 1556
	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))
1557
	    PRINTDLG_ChangePrinterA(hDlg, name, PrintStructures);
1558 1559 1560 1561
	HeapFree(GetProcessHeap(),0,name);
    } else {
	/* else use default printer */
	char name[200];
1562 1563
        DWORD dwBufLen = sizeof(name);
	BOOL ret = GetDefaultPrinterA(name, &dwBufLen);
1564 1565 1566 1567 1568 1569 1570 1571 1572

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

1573
static LRESULT PRINTDLG_WMInitDialogW(HWND hDlg,
1574 1575
				     PRINT_PTRW* PrintStructures)
{
1576
    LPPRINTDLGW lppd = PrintStructures->lpPrintDlg;
1577 1578 1579 1580 1581 1582 1583 1584 1585
    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 =
1586
      LoadImageW(COMDLG32_hInstance, pd32_collateW, IMAGE_ICON, 0, 0, 0);
1587
    PrintStructures->hNoCollateIcon =
1588
      LoadImageW(COMDLG32_hInstance, pd32_nocollateW, IMAGE_ICON, 0, 0, 0);
1589 1590 1591

    /* These can be done with LoadIcon */
    PrintStructures->hPortraitIcon =
1592
      LoadIconW(COMDLG32_hInstance, pd32_portraitW);
1593
    PrintStructures->hLandscapeIcon =
1594
      LoadIconW(COMDLG32_hInstance, pd32_landscapeW);
1595

1596
    /* display the collate/no_collate icon */
1597
    SendDlgItemMessageW(hDlg, ico3, STM_SETIMAGE, IMAGE_ICON,
1598 1599
                        (LPARAM)PrintStructures->hNoCollateIcon);

1600 1601 1602 1603
    if(PrintStructures->hCollateIcon == 0 ||
       PrintStructures->hNoCollateIcon == 0 ||
       PrintStructures->hPortraitIcon == 0 ||
       PrintStructures->hLandscapeIcon == 0) {
Andrey Gusev's avatar
Andrey Gusev committed
1604
        ERR("no icon in resource file\n");
1605 1606 1607 1608 1609 1610 1611 1612 1613
	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) {
1614
        if((PrintStructures->HelpMessageID =
1615
	    RegisterWindowMessageW(HELPMSGSTRINGW)) == 0) {
1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636
	    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;
1637 1638
    if (lppd->nMinPage == lppd->nMaxPage)
    	lppd->Flags |= PD_NOPAGENUMS;
1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649
    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)) {
1650
	/* Fill Combobox
1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670
	 */
	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];
1671 1672
        DWORD dwBufLen = sizeof(name) / sizeof(WCHAR);
	BOOL ret = GetDefaultPrinterW(name, &dwBufLen);
1673 1674

	if (ret)
1675
	    PRINTDLG_ChangePrinterW(hDlg, name, PrintStructures);
1676 1677 1678 1679 1680 1681
	else
	    FIXME("No default printer found, expect problems!\n");
    }
    return TRUE;
}

1682 1683 1684
/***********************************************************************
 *                              PRINTDLG_WMCommand               [internal]
 */
1685
static LRESULT PRINTDLG_WMCommandA(HWND hDlg, WPARAM wParam,
1686
                                   PRINT_PTRA* PrintStructures)
1687
{
1688
    LPPRINTDLGA lppd = PrintStructures->lpPrintDlg;
1689 1690
    UINT PrinterComboID = (lppd->Flags & PD_PRINTSETUP) ? cmb1 : cmb4;
    LPDEVMODEA lpdm = PrintStructures->lpDevMode;
1691

1692 1693
    switch (LOWORD(wParam))  {
    case IDOK:
1694
        TRACE(" OK button was hit\n");
1695
        if (!PRINTDLG_UpdatePrintDlgA(hDlg, PrintStructures)) {
1696
	    FIXME("Update printdlg was not successful!\n");
1697
	    return(FALSE);
1698
	}
1699 1700 1701 1702
	EndDialog(hDlg, TRUE);
	return(TRUE);

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

1707
     case pshHelp:
1708
        TRACE(" HELP button was hit\n");
1709
        SendMessageA(lppd->hwndOwner, PrintStructures->HelpMessageID,
1710 1711
        			(WPARAM) hDlg, (LPARAM) lppd);
        break;
1712

1713 1714
     case chx2:                         /* collate pages checkbox */
        if (IsDlgButtonChecked(hDlg, chx2) == BST_CHECKED)
1715
            SendDlgItemMessageA(hDlg, ico3, STM_SETIMAGE, IMAGE_ICON,
1716 1717
                                    (LPARAM)PrintStructures->hCollateIcon);
        else
1718
            SendDlgItemMessageA(hDlg, ico3, STM_SETIMAGE, IMAGE_ICON,
1719
                                    (LPARAM)PrintStructures->hNoCollateIcon);
1720
        break;
1721 1722
     case edt1:                         /* from page nr editbox */
     case edt2:                         /* to page nr editbox */
1723 1724 1725 1726 1727
        if (HIWORD(wParam)==EN_CHANGE) {
	    WORD nToPage;
	    WORD nFromPage;
	    nFromPage = GetDlgItemInt(hDlg, edt1, NULL, FALSE);
	    nToPage   = GetDlgItemInt(hDlg, edt2, NULL, FALSE);
1728
            if (nFromPage != lppd->nFromPage || nToPage != lppd->nToPage)
1729 1730
	        CheckRadioButton(hDlg, rad1, rad3, rad3);
	}
1731
        break;
1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742

    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;

1743 1744 1745
     case psh2:                       /* Properties button */
       {
         HANDLE hPrinter;
1746 1747 1748 1749 1750 1751 1752
         char   PrinterName[256];

         GetDlgItemTextA(hDlg, PrinterComboID, PrinterName, 255);
         if (!OpenPrinterA(PrinterName, &hPrinter, NULL)) {
	     FIXME(" Call to OpenPrinter did not succeed!\n");
	     break;
	 }
1753
	 DocumentPropertiesA(hDlg, hPrinter, PrinterName,
1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764
			     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;
1765
              SendDlgItemMessageA(hDlg, ico1, STM_SETIMAGE, IMAGE_ICON,
1766 1767 1768
                          (LPARAM)(PrintStructures->hPortraitIcon));
        }
        break;
1769

1770 1771 1772 1773
    case rad2: /* Paperorientation */
        if (lppd->Flags & PD_PRINTSETUP)
        {
              lpdm->u1.s1.dmOrientation = DMORIENT_LANDSCAPE;
1774
              SendDlgItemMessageA(hDlg, ico1, STM_SETIMAGE, IMAGE_ICON,
1775 1776 1777
                          (LPARAM)(PrintStructures->hLandscapeIcon));
        }
        break;
1778

1779
    case cmb1: /* Printer Combobox in PRINT SETUP, quality combobox in PRINT16 */
1780
	 if (PrinterComboID != LOWORD(wParam)) {
1781 1782 1783 1784 1785
	     break;
	 }
	 /* FALLTHROUGH */
    case cmb4:                         /* Printer combobox */
         if (HIWORD(wParam)==CBN_SELCHANGE) {
1786 1787 1788 1789 1790
	     char   *PrinterName;
	     INT index = SendDlgItemMessageW(hDlg, LOWORD(wParam), CB_GETCURSEL, 0, 0);
	     INT length = SendDlgItemMessageW(hDlg, LOWORD(wParam), CB_GETLBTEXTLEN, index, 0);
	     PrinterName = HeapAlloc(GetProcessHeap(),0,length+1);
	     SendDlgItemMessageA(hDlg, LOWORD(wParam), CB_GETLBTEXT, index, (LPARAM)PrinterName);
1791
	     PRINTDLG_ChangePrinterA(hDlg, PrinterName, PrintStructures);
1792
	     HeapFree(GetProcessHeap(),0,PrinterName);
1793 1794 1795 1796 1797 1798
	 }
	 break;

    case cmb2: /* Papersize */
      {
	  DWORD Sel = SendDlgItemMessageA(hDlg, cmb2, CB_GETCURSEL, 0, 0);
1799
	  if(Sel != CB_ERR) {
1800 1801 1802
	      lpdm->u1.s1.dmPaperSize = SendDlgItemMessageA(hDlg, cmb2,
							    CB_GETITEMDATA,
							    Sel, 0);
1803 1804
	      GetDlgItemTextA(hDlg, cmb2, (char *)lpdm->dmFormName, CCHFORMNAME);
	  }
1805 1806 1807 1808 1809 1810 1811
      }
      break;

    case cmb3: /* Bin */
      {
	  DWORD Sel = SendDlgItemMessageA(hDlg, cmb3, CB_GETCURSEL, 0, 0);
	  if(Sel != CB_ERR)
1812
	      lpdm->u1.s1.dmDefaultSource = SendDlgItemMessageA(hDlg, cmb3,
1813 1814 1815
							  CB_GETITEMDATA, Sel,
							  0);
      }
1816
      break;
1817 1818 1819 1820 1821 1822 1823 1824
    }
    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;
1825
                    SendDlgItemMessageA(hDlg, stc10, STM_SETIMAGE, IMAGE_ICON,
1826
					(LPARAM)PrintStructures->hPortraitIcon);
1827
                    SendDlgItemMessageA(hDlg, ico1, STM_SETIMAGE, IMAGE_ICON,
1828 1829 1830 1831 1832
					(LPARAM)PrintStructures->hPortraitIcon);
		}
	    } else {
	        if(lpdm->u1.s1.dmOrientation != DMORIENT_LANDSCAPE) {
	            lpdm->u1.s1.dmOrientation = DMORIENT_LANDSCAPE;
1833
                    SendDlgItemMessageA(hDlg, stc10, STM_SETIMAGE, IMAGE_ICON,
1834
					(LPARAM)PrintStructures->hLandscapeIcon);
1835
                    SendDlgItemMessageA(hDlg, ico1, STM_SETIMAGE, IMAGE_ICON,
1836 1837 1838 1839 1840 1841 1842
					(LPARAM)PrintStructures->hLandscapeIcon);
		}
	    }
	    break;
	}
    }
    return FALSE;
1843
}
1844

1845
static LRESULT PRINTDLG_WMCommandW(HWND hDlg, WPARAM wParam,
1846
			           PRINT_PTRW* PrintStructures)
1847
{
1848
    LPPRINTDLGW lppd = PrintStructures->lpPrintDlg;
1849 1850 1851 1852 1853 1854
    UINT PrinterComboID = (lppd->Flags & PD_PRINTSETUP) ? cmb1 : cmb4;
    LPDEVMODEW lpdm = PrintStructures->lpDevMode;

    switch (LOWORD(wParam))  {
    case IDOK:
        TRACE(" OK button was hit\n");
1855
        if (!PRINTDLG_UpdatePrintDlgW(hDlg, PrintStructures)) {
1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868
	    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");
1869
        SendMessageW(lppd->hwndOwner, PrintStructures->HelpMessageID,
1870 1871 1872 1873 1874
        			(WPARAM) hDlg, (LPARAM) lppd);
        break;

     case chx2:                         /* collate pages checkbox */
        if (IsDlgButtonChecked(hDlg, chx2) == BST_CHECKED)
1875
            SendDlgItemMessageW(hDlg, ico3, STM_SETIMAGE, IMAGE_ICON,
1876 1877
                                    (LPARAM)PrintStructures->hCollateIcon);
        else
1878
            SendDlgItemMessageW(hDlg, ico3, STM_SETIMAGE, IMAGE_ICON,
1879
                                    (LPARAM)PrintStructures->hNoCollateIcon);
1880
        break;
1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898
     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
1899 1900 1901
                EnableWindow(GetDlgItem(hDlg, chx2), TRUE);
        }
        break;
1902 1903 1904 1905 1906

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

1908
         if (!GetDlgItemTextW(hDlg, PrinterComboID, PrinterName, 255)) break;
1909
         if (!OpenPrinterW(PrinterName, &hPrinter, NULL)) {
1910
	     FIXME(" Call to OpenPrinter did not succeed!\n");
1911 1912
	     break;
	 }
1913
	 DocumentPropertiesW(hDlg, hPrinter, PrinterName,
1914 1915 1916 1917
			     PrintStructures->lpDevMode,
			     PrintStructures->lpDevMode,
			     DM_IN_BUFFER | DM_OUT_BUFFER | DM_IN_PROMPT);
	 ClosePrinter(hPrinter);
1918
         break;
1919
       }
1920

1921 1922
    case rad1: /* Paperorientation */
        if (lppd->Flags & PD_PRINTSETUP)
1923
        {
1924
              lpdm->u1.s1.dmOrientation = DMORIENT_PORTRAIT;
1925
              SendDlgItemMessageW(hDlg, ico1, STM_SETIMAGE, IMAGE_ICON,
1926 1927
                          (LPARAM)(PrintStructures->hPortraitIcon));
        }
1928
        break;
1929

1930 1931
    case rad2: /* Paperorientation */
        if (lppd->Flags & PD_PRINTSETUP)
1932
        {
1933
              lpdm->u1.s1.dmOrientation = DMORIENT_LANDSCAPE;
1934
              SendDlgItemMessageW(hDlg, ico1, STM_SETIMAGE, IMAGE_ICON,
1935 1936
                          (LPARAM)(PrintStructures->hLandscapeIcon));
        }
1937
        break;
1938

1939
    case cmb1: /* Printer Combobox in PRINT SETUP */
1940
	 /* FALLTHROUGH */
1941 1942
    case cmb4:                         /* Printer combobox */
         if (HIWORD(wParam)==CBN_SELCHANGE) {
1943 1944 1945 1946 1947 1948
	     WCHAR *PrinterName;
	     INT index = SendDlgItemMessageW(hDlg, LOWORD(wParam), CB_GETCURSEL, 0, 0);
	     INT length = SendDlgItemMessageW(hDlg, LOWORD(wParam), CB_GETLBTEXTLEN, index, 0);

	     PrinterName = HeapAlloc(GetProcessHeap(),0,sizeof(WCHAR)*(length+1));
	     SendDlgItemMessageW(hDlg, LOWORD(wParam), CB_GETLBTEXT, index, (LPARAM)PrinterName);
1949
	     PRINTDLG_ChangePrinterW(hDlg, PrinterName, PrintStructures);
1950
	     HeapFree(GetProcessHeap(),0,PrinterName);
1951 1952 1953 1954 1955
	 }
	 break;

    case cmb2: /* Papersize */
      {
1956
	  DWORD Sel = SendDlgItemMessageW(hDlg, cmb2, CB_GETCURSEL, 0, 0);
1957
	  if(Sel != CB_ERR) {
1958
	      lpdm->u1.s1.dmPaperSize = SendDlgItemMessageW(hDlg, cmb2,
1959 1960
							    CB_GETITEMDATA,
							    Sel, 0);
1961 1962
	      GetDlgItemTextW(hDlg, cmb2, lpdm->dmFormName, CCHFORMNAME);
	  }
1963 1964 1965 1966 1967
      }
      break;

    case cmb3: /* Bin */
      {
1968
	  DWORD Sel = SendDlgItemMessageW(hDlg, cmb3, CB_GETCURSEL, 0, 0);
1969
	  if(Sel != CB_ERR)
1970
	      lpdm->u1.s1.dmDefaultSource = SendDlgItemMessageW(hDlg, cmb3,
1971 1972 1973
							  CB_GETITEMDATA, Sel,
							  0);
      }
1974
      break;
1975
    }
1976 1977 1978 1979 1980 1981 1982
    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;
1983
                    SendDlgItemMessageW(hDlg, stc10, STM_SETIMAGE, IMAGE_ICON,
1984
					(LPARAM)PrintStructures->hPortraitIcon);
1985
                    SendDlgItemMessageW(hDlg, ico1, STM_SETIMAGE, IMAGE_ICON,
1986 1987 1988 1989 1990
					(LPARAM)PrintStructures->hPortraitIcon);
		}
	    } else {
	        if(lpdm->u1.s1.dmOrientation != DMORIENT_LANDSCAPE) {
	            lpdm->u1.s1.dmOrientation = DMORIENT_LANDSCAPE;
1991
                    SendDlgItemMessageW(hDlg, stc10, STM_SETIMAGE, IMAGE_ICON,
1992
					(LPARAM)PrintStructures->hLandscapeIcon);
1993
                    SendDlgItemMessageW(hDlg, ico1, STM_SETIMAGE, IMAGE_ICON,
1994 1995 1996 1997 1998 1999
					(LPARAM)PrintStructures->hLandscapeIcon);
		}
	    }
	    break;
	}
    }
2000
    return FALSE;
2001
}
2002

2003
/***********************************************************************
2004
 *           PrintDlgProcA			[internal]
2005
 */
2006 2007
static INT_PTR CALLBACK PrintDlgProcA(HWND hDlg, UINT uMsg, WPARAM wParam,
                                      LPARAM lParam)
2008
{
2009
    PRINT_PTRA* PrintStructures;
2010
    INT_PTR res = FALSE;
2011

2012
    if (uMsg!=WM_INITDIALOG) {
2013
        PrintStructures = GetPropW(hDlg, printdlg_prop);
2014 2015 2016 2017
	if (!PrintStructures)
	    return FALSE;
    } else {
        PrintStructures = (PRINT_PTRA*) lParam;
2018
        SetPropW(hDlg, printdlg_prop, PrintStructures);
2019 2020 2021 2022 2023
        if(!check_printer_setup(hDlg))
        {
            EndDialog(hDlg,FALSE);
            return FALSE;
        }
2024
	res = PRINTDLG_WMInitDialog(hDlg, PrintStructures);
2025

2026 2027 2028
	if(PrintStructures->lpPrintDlg->Flags & PD_ENABLEPRINTHOOK)
	    res = PrintStructures->lpPrintDlg->lpfnPrintHook(
		hDlg, uMsg, wParam, (LPARAM)PrintStructures->lpPrintDlg
2029
	    );
2030
	return res;
2031
    }
2032

2033 2034
    if(PrintStructures->lpPrintDlg->Flags & PD_ENABLEPRINTHOOK) {
        res = PrintStructures->lpPrintDlg->lpfnPrintHook(hDlg,uMsg,wParam,
2035 2036 2037 2038 2039 2040
							 lParam);
	if(res) return res;
    }

    switch (uMsg) {
    case WM_COMMAND:
2041
        return PRINTDLG_WMCommandA(hDlg, wParam, PrintStructures);
2042 2043 2044 2045 2046 2047 2048 2049 2050

    case WM_DESTROY:
	DestroyIcon(PrintStructures->hCollateIcon);
	DestroyIcon(PrintStructures->hNoCollateIcon);
        DestroyIcon(PrintStructures->hPortraitIcon);
        DestroyIcon(PrintStructures->hLandscapeIcon);
	if(PrintStructures->hwndUpDown)
	    DestroyWindow(PrintStructures->hwndUpDown);
        return FALSE;
2051
    }
2052 2053 2054
    return res;
}

2055 2056
static INT_PTR CALLBACK PrintDlgProcW(HWND hDlg, UINT uMsg, WPARAM wParam,
                                      LPARAM lParam)
2057 2058
{
    PRINT_PTRW* PrintStructures;
2059
    INT_PTR res = FALSE;
2060 2061

    if (uMsg!=WM_INITDIALOG) {
2062
        PrintStructures = GetPropW(hDlg, printdlg_prop);
2063 2064 2065 2066
	if (!PrintStructures)
	    return FALSE;
    } else {
        PrintStructures = (PRINT_PTRW*) lParam;
2067
        SetPropW(hDlg, printdlg_prop, PrintStructures);
2068 2069 2070 2071 2072
        if(!check_printer_setup(hDlg))
        {
            EndDialog(hDlg,FALSE);
            return FALSE;
        }
2073
	res = PRINTDLG_WMInitDialogW(hDlg, PrintStructures);
2074

2075 2076
	if(PrintStructures->lpPrintDlg->Flags & PD_ENABLEPRINTHOOK)
	    res = PrintStructures->lpPrintDlg->lpfnPrintHook(hDlg, uMsg, wParam, (LPARAM)PrintStructures->lpPrintDlg);
2077 2078
	return res;
    }
2079

2080 2081
    if(PrintStructures->lpPrintDlg->Flags & PD_ENABLEPRINTHOOK) {
        res = PrintStructures->lpPrintDlg->lpfnPrintHook(hDlg,uMsg,wParam, lParam);
2082 2083 2084 2085 2086
	if(res) return res;
    }

    switch (uMsg) {
    case WM_COMMAND:
2087
        return PRINTDLG_WMCommandW(hDlg, wParam, PrintStructures);
2088

2089 2090 2091
    case WM_DESTROY:
	DestroyIcon(PrintStructures->hCollateIcon);
	DestroyIcon(PrintStructures->hNoCollateIcon);
2092 2093 2094 2095
        DestroyIcon(PrintStructures->hPortraitIcon);
        DestroyIcon(PrintStructures->hLandscapeIcon);
	if(PrintStructures->hwndUpDown)
	    DestroyWindow(PrintStructures->hwndUpDown);
2096
        return FALSE;
2097
    }
2098 2099 2100 2101 2102 2103 2104 2105
    return res;
}

/************************************************************
 *
 *      PRINTDLG_GetDlgTemplate
 *
 */
2106
static HGLOBAL PRINTDLG_GetDlgTemplateA(const PRINTDLGA *lppd)
2107
{
2108 2109
    HRSRC hResInfo;
    HGLOBAL hDlgTmpl;
2110 2111

    if (lppd->Flags & PD_PRINTSETUP) {
2112
	if(lppd->Flags & PD_ENABLESETUPTEMPLATEHANDLE) {
2113
	    hDlgTmpl = lppd->hSetupTemplate;
2114
	} else if(lppd->Flags & PD_ENABLESETUPTEMPLATE) {
2115
	    hResInfo = FindResourceA(lppd->hInstance,
2116
				     lppd->lpSetupTemplateName, (LPSTR)RT_DIALOG);
2117 2118 2119
	    hDlgTmpl = LoadResource(lppd->hInstance, hResInfo);
	} else {
	    hResInfo = FindResourceA(COMDLG32_hInstance, "PRINT32_SETUP",
2120
				     (LPSTR)RT_DIALOG);
2121 2122 2123
	    hDlgTmpl = LoadResource(COMDLG32_hInstance, hResInfo);
	}
    } else {
2124
	if(lppd->Flags & PD_ENABLEPRINTTEMPLATEHANDLE) {
2125 2126 2127 2128
	    hDlgTmpl = lppd->hPrintTemplate;
	} else if(lppd->Flags & PD_ENABLEPRINTTEMPLATE) {
	    hResInfo = FindResourceA(lppd->hInstance,
				     lppd->lpPrintTemplateName,
2129
				     (LPSTR)RT_DIALOG);
2130 2131 2132
	    hDlgTmpl = LoadResource(lppd->hInstance, hResInfo);
	} else {
	    hResInfo = FindResourceA(COMDLG32_hInstance, "PRINT32",
2133
				     (LPSTR)RT_DIALOG);
2134 2135 2136 2137 2138
	    hDlgTmpl = LoadResource(COMDLG32_hInstance, hResInfo);
	}
    }
    return hDlgTmpl;
}
2139

2140
static HGLOBAL PRINTDLG_GetDlgTemplateW(const PRINTDLGW *lppd)
2141
{
2142 2143
    HRSRC hResInfo;
    HGLOBAL hDlgTmpl;
2144 2145
    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};
2146 2147 2148 2149

    if (lppd->Flags & PD_PRINTSETUP) {
	if(lppd->Flags & PD_ENABLESETUPTEMPLATEHANDLE) {
	    hDlgTmpl = lppd->hSetupTemplate;
2150
	} else if(lppd->Flags & PD_ENABLESETUPTEMPLATE) {
2151
	    hResInfo = FindResourceW(lppd->hInstance,
2152
				     lppd->lpSetupTemplateName, (LPWSTR)RT_DIALOG);
2153 2154
	    hDlgTmpl = LoadResource(lppd->hInstance, hResInfo);
	} else {
2155
	    hResInfo = FindResourceW(COMDLG32_hInstance, xpsetup, (LPWSTR)RT_DIALOG);
2156 2157 2158 2159 2160 2161 2162 2163
	    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,
2164
				     (LPWSTR)RT_DIALOG);
2165 2166
	    hDlgTmpl = LoadResource(lppd->hInstance, hResInfo);
	} else {
2167
	    hResInfo = FindResourceW(COMDLG32_hInstance, xprint, (LPWSTR)RT_DIALOG);
2168 2169 2170 2171 2172 2173
	    hDlgTmpl = LoadResource(COMDLG32_hInstance, hResInfo);
	}
    }
    return hDlgTmpl;
}

2174
/***********************************************************************
2175 2176 2177
 *
 *      PRINTDLG_CreateDC
 *
2178
 */
2179
static BOOL PRINTDLG_CreateDCA(LPPRINTDLGA lppd)
2180
{
2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196
    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);
2197
    return lppd->hDC != NULL;
2198
}
2199

2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217
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);
2218
    return lppd->hDC != NULL;
2219 2220
}

2221
/***********************************************************************
2222 2223
 *           PrintDlgA   (COMDLG32.@)
 *
2224
 *  Displays the PRINT dialog box, which enables the user to specify
2225
 *  specific properties of the print job.
2226 2227 2228 2229
 *  
 * PARAMS
 *  lppd  [IO] ptr to PRINTDLG32 struct
 * 
2230 2231 2232
 * RETURNS
 *  nonzero if the user pressed the OK button
 *  zero    if the user cancelled the window or an error occurred
2233
 *  
2234 2235 2236 2237 2238 2239
 * BUGS
 *  PrintDlg:
 *  * The Collate Icons do not display, even though they are in the code.
 *  * The Properties Button(s) should call DocumentPropertiesA().
 */

2240
BOOL WINAPI PrintDlgA(LPPRINTDLGA lppd)
2241 2242
{
    BOOL      bRet = FALSE;
2243 2244
    LPVOID    ptr;
    HINSTANCE hInst;
2245

2246 2247 2248 2249 2250 2251
    if (!lppd)
    {
        COMDLG32_SetCommDlgExtendedError(CDERR_INITIALIZATION);
        return FALSE;
    }

2252 2253
    if(TRACE_ON(commdlg)) {
        char flagstr[1000] = "";
2254
	const struct pd_flags *pflag = pd_flags;
2255 2256 2257 2258
	for( ; pflag->name; pflag++) {
	    if(lppd->Flags & pflag->flag)
	        strcat(flagstr, pflag->name);
	}
2259
	TRACE("(%p): hwndOwner = %p, hDevMode = %p, hDevNames = %p\n"
2260 2261
              "pp. %d-%d, min p %d, max p %d, copies %d, hinst %p\n"
              "flags %08x (%s)\n",
2262 2263 2264 2265 2266 2267
	      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)) {
Andrey Gusev's avatar
Andrey Gusev committed
2268
        WARN("structure size failure!!!\n");
2269
	COMDLG32_SetCommDlgExtendedError(CDERR_STRUCTSIZE);
2270
	return FALSE;
2271 2272 2273 2274 2275 2276 2277 2278 2279 2280
    }

    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");
2281
	    COMDLG32_SetCommDlgExtendedError(PDERR_RETDEFFAILURE);
2282 2283 2284 2285
	    return FALSE;
	}
        if(!PRINTDLG_OpenDefaultPrinter(&hprn)) {
	    WARN("Can't find default printer\n");
2286
	    COMDLG32_SetCommDlgExtendedError(PDERR_NODEFAULTPRN);
2287 2288 2289 2290 2291 2292 2293 2294 2295 2296
	    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)) {
2297 2298 2299 2300
	    ERR("GetPrinterDriverA failed, le %d, fix your config for printer %s!\n",
	        GetLastError(),pbuf->pPrinterName);
	    HeapFree(GetProcessHeap(), 0, dbuf);
	    HeapFree(GetProcessHeap(), 0, pbuf);
2301
	    COMDLG32_SetCommDlgExtendedError(PDERR_RETDEFFAILURE);
2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322
	    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;

2323 2324
    /* load Dialog resources,
     * depending on Flags indicates Print32 or Print32_setup dialog
2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338
     */
	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));
2339
	PrintStructures->lpPrintDlg = lppd;
2340 2341 2342 2343

	/* and create & process the dialog .
	 * -1 is failure, 0 is broken hwnd, everything else is ok.
	 */
2344 2345
        hInst = COMDLG32_hInstance;
	if (lppd->Flags & (PD_ENABLESETUPTEMPLATE | PD_ENABLEPRINTTEMPLATE)) hInst = lppd->hInstance;
2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381
	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);

2382 2383
    TRACE("exit! (%d)\n", bRet);
    return bRet;
2384 2385 2386 2387
}

/***********************************************************************
 *           PrintDlgW   (COMDLG32.@)
2388 2389
 *
 * See PrintDlgA.
2390
 */
2391
BOOL WINAPI PrintDlgW(LPPRINTDLGW lppd)
2392 2393
{
    BOOL      bRet = FALSE;
2394 2395 2396 2397 2398 2399 2400 2401
    LPVOID    ptr;
    HINSTANCE hInst;

    if (!lppd)
    {
        COMDLG32_SetCommDlgExtendedError(CDERR_INITIALIZATION);
        return FALSE;
    }
2402 2403 2404

    if(TRACE_ON(commdlg)) {
        char flagstr[1000] = "";
2405
	const struct pd_flags *pflag = pd_flags;
2406 2407 2408 2409
	for( ; pflag->name; pflag++) {
	    if(lppd->Flags & pflag->flag)
	        strcat(flagstr, pflag->name);
	}
2410
	TRACE("(%p): hwndOwner = %p, hDevMode = %p, hDevNames = %p\n"
2411 2412
              "pp. %d-%d, min p %d, max p %d, copies %d, hinst %p\n"
              "flags %08x (%s)\n",
2413 2414 2415 2416 2417
	      lppd, lppd->hwndOwner, lppd->hDevMode, lppd->hDevNames,
	      lppd->nFromPage, lppd->nToPage, lppd->nMinPage, lppd->nMaxPage,
	      lppd->nCopies, lppd->hInstance, lppd->Flags, flagstr);
    }

2418
    if(lppd->lStructSize != sizeof(PRINTDLGW)) {
Andrey Gusev's avatar
Andrey Gusev committed
2419
        WARN("structure size failure!!!\n");
2420
	COMDLG32_SetCommDlgExtendedError(CDERR_STRUCTSIZE);
2421
	return FALSE;
2422 2423 2424
    }

    if(lppd->Flags & PD_RETURNDEFAULT) {
2425 2426
        PRINTER_INFO_2W *pbuf;
	DRIVER_INFO_3W	*dbuf;
2427 2428 2429 2430 2431
	HANDLE hprn;
	DWORD needed;

	if(lppd->hDevMode || lppd->hDevNames) {
	    WARN("hDevMode or hDevNames non-zero for PD_RETURNDEFAULT\n");
2432
	    COMDLG32_SetCommDlgExtendedError(PDERR_RETDEFFAILURE);
2433
	    return FALSE;
2434 2435 2436
	}
        if(!PRINTDLG_OpenDefaultPrinter(&hprn)) {
	    WARN("Can't find default printer\n");
2437
	    COMDLG32_SetCommDlgExtendedError(PDERR_NODEFAULTPRN);
2438 2439 2440
	    return FALSE;
	}

2441
	GetPrinterW(hprn, 2, NULL, 0, &needed);
2442
	pbuf = HeapAlloc(GetProcessHeap(), 0, needed);
2443
	GetPrinterW(hprn, 2, (LPBYTE)pbuf, needed, &needed);
2444

2445
	GetPrinterDriverW(hprn, NULL, 3, NULL, 0, &needed);
2446
	dbuf = HeapAlloc(GetProcessHeap(),0,needed);
2447
	if (!GetPrinterDriverW(hprn, NULL, 3, (LPBYTE)dbuf, needed, &needed)) {
2448 2449 2450 2451
	    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);
2452
	    COMDLG32_SetCommDlgExtendedError(PDERR_RETDEFFAILURE);
2453 2454
	    return FALSE;
	}
2455
	ClosePrinter(hprn);
2456

2457
	PRINTDLG_CreateDevNamesW(&(lppd->hDevNames),
2458 2459
				  dbuf->pDriverPath,
				  pbuf->pPrinterName,
2460 2461 2462 2463 2464 2465 2466 2467
				  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);
2468
	HeapFree(GetProcessHeap(), 0, dbuf);
2469 2470 2471
	bRet = TRUE;
    } else {
	HGLOBAL hDlgTmpl;
2472
	PRINT_PTRW *PrintStructures;
2473

2474 2475
    /* load Dialog resources,
     * depending on Flags indicates Print32 or Print32_setup dialog
2476
     */
2477
	hDlgTmpl = PRINTDLG_GetDlgTemplateW(lppd);
2478
	if (!hDlgTmpl) {
2479 2480 2481
	    COMDLG32_SetCommDlgExtendedError(CDERR_LOADRESFAILURE);
	    return FALSE;
	}
2482 2483 2484 2485 2486 2487
	ptr = LockResource( hDlgTmpl );
	if (!ptr) {
	    COMDLG32_SetCommDlgExtendedError(CDERR_LOADRESFAILURE);
	    return FALSE;
	}

2488
        PrintStructures = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY,
2489
				    sizeof(PRINT_PTRW));
2490
	PrintStructures->lpPrintDlg = lppd;
2491

2492 2493
	/* and create & process the dialog .
	 * -1 is failure, 0 is broken hwnd, everything else is ok.
2494
	 */
2495 2496
        hInst = COMDLG32_hInstance;
	if (lppd->Flags & (PD_ENABLESETUPTEMPLATE | PD_ENABLEPRINTTEMPLATE)) hInst = lppd->hInstance;
2497 2498
	bRet = (0<DialogBoxIndirectParamW(hInst, ptr, lppd->hwndOwner,
					   PrintDlgProcW,
2499
					   (LPARAM)PrintStructures));
2500 2501

	if(bRet) {
2502 2503 2504
	    DEVMODEW *lpdm = PrintStructures->lpDevMode, *lpdmReturn;
	    PRINTER_INFO_2W *pi = PrintStructures->lpPrinterInfo;
	    DRIVER_INFO_3W *di = PrintStructures->lpDriverInfo;
2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533

	    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);
		}
	    }
2534
	    PRINTDLG_CreateDevNamesW(&(lppd->hDevNames),
2535 2536 2537 2538
		    di->pDriverPath,
		    pi->pPrinterName,
		    pi->pPortName
	    );
2539 2540 2541 2542
	    GlobalUnlock(lppd->hDevMode);
	}
	HeapFree(GetProcessHeap(), 0, PrintStructures->lpDevMode);
	HeapFree(GetProcessHeap(), 0, PrintStructures->lpPrinterInfo);
2543
	HeapFree(GetProcessHeap(), 0, PrintStructures->lpDriverInfo);
2544 2545 2546
	HeapFree(GetProcessHeap(), 0, PrintStructures);
    }
    if(bRet && (lppd->Flags & PD_RETURNDC || lppd->Flags & PD_RETURNIC))
2547
        bRet = PRINTDLG_CreateDCW(lppd);
2548

2549 2550
    TRACE("exit! (%d)\n", bRet);
    return bRet;
2551 2552 2553 2554 2555
}

/***********************************************************************
 *
 *          PageSetupDlg
2556 2557
 * rad1 - portrait
 * rad2 - landscape
2558
 * cmb1 - printer select (not in standard dialog template)
2559 2560 2561 2562 2563 2564 2565
 * cmb2 - paper size
 * cmb3 - source (tray?)
 * edt4 - border left
 * edt5 - border top
 * edt6 - border right
 * edt7 - border bottom
 * psh3 - "Printer..."
2566
 */
2567

2568 2569
typedef struct
{
2570 2571 2572 2573 2574 2575 2576 2577
    BOOL unicode;
    union
    {
        LPPAGESETUPDLGA dlga;
        LPPAGESETUPDLGW dlgw;
    } u;
    HWND hDlg;                /* Page Setup dialog handle */
    RECT rtDrawRect;          /* Drawing rect for page */
2578
} pagesetup_data;
2579

2580 2581
static inline DWORD pagesetup_get_flags(const pagesetup_data *data)
{
2582
    return data->u.dlgw->Flags;
2583 2584
}

2585
static inline BOOL is_metric(const pagesetup_data *data)
2586
{
2587
    return pagesetup_get_flags(data) & PSD_INHUNDREDTHSOFMILLIMETERS;
2588 2589
}

2590
static inline LONG tenths_mm_to_size(const pagesetup_data *data, LONG size)
2591 2592 2593 2594 2595 2596 2597
{
    if (is_metric(data))
        return 10 * size;
    else
        return 10 * size * 100 / 254;
}

2598
static inline LONG thousandths_inch_to_size(const pagesetup_data *data, LONG size)
2599 2600 2601 2602 2603 2604 2605
{
    if (is_metric(data))
        return size * 254 / 100;
    else
        return size;
}

2606 2607 2608 2609 2610 2611
static WCHAR get_decimal_sep(void)
{
    static WCHAR sep;

    if(!sep)
    {
2612
        WCHAR buf[] = {'.', 0};
2613 2614 2615 2616 2617 2618
        GetLocaleInfoW(LOCALE_USER_DEFAULT, LOCALE_SDECIMAL, buf, sizeof(buf) / sizeof(buf[0]));
        sep = buf[0];
    }
    return sep;
}

2619
static void size2str(const pagesetup_data *data, DWORD size, LPWSTR strout)
2620
{
2621
    WCHAR integer_fmt[] = {'%','d',0};
2622 2623
    WCHAR hundredths_fmt[] = {'%','d','%','c','%','0','2','d',0};
    WCHAR thousandths_fmt[] = {'%','d','%','c','%','0','3','d',0};
2624 2625

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

2627
    if (is_metric(data))
2628 2629
    {
        if(size % 100)
2630
            wsprintfW(strout, hundredths_fmt, size / 100, get_decimal_sep(), size % 100);
2631 2632 2633
        else
            wsprintfW(strout, integer_fmt, size / 100);
    }
2634
    else
2635 2636
    {
        if(size % 1000)
2637
            wsprintfW(strout, thousandths_fmt, size / 1000, get_decimal_sep(), size % 1000);
2638 2639 2640 2641
        else
            wsprintfW(strout, integer_fmt, size / 1000);

    }
2642
}
2643

2644 2645 2646 2647 2648 2649 2650 2651
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;
}

2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678
/**********************************************
 *           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;
    }
}

2679
static void pagesetup_set_orientation(pagesetup_data *data, WORD orient)
2680
{
2681
    DEVMODEW *dm = GlobalLock(data->u.dlgw->hDevMode);
2682 2683 2684

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

2685 2686 2687 2688 2689 2690 2691 2692
    if(data->unicode)
        dm->u1.s1.dmOrientation = orient;
    else
    {
        DEVMODEA *dmA = (DEVMODEA *)dm;
        dmA->u1.s1.dmOrientation = orient;
    }
    GlobalUnlock(data->u.dlgw->hDevMode);
2693 2694
}

2695
static WORD pagesetup_get_orientation(const pagesetup_data *data)
2696
{
2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707
    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);
2708 2709 2710
    return orient;
}

2711
static void pagesetup_set_papersize(pagesetup_data *data, WORD paper)
2712
{
2713 2714 2715 2716 2717 2718 2719 2720 2721 2722
    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);
2723 2724
}

2725
static WORD pagesetup_get_papersize(const pagesetup_data *data)
2726
{
2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737
    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);
2738 2739 2740
    return paper;
}

2741
static void pagesetup_set_defaultsource(pagesetup_data *data, WORD source)
2742
{
2743 2744 2745 2746 2747 2748 2749 2750 2751 2752
    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);
2753 2754
}

2755
typedef enum
2756
{
2757 2758 2759 2760
    devnames_driver_name,
    devnames_device_name,
    devnames_output_name
} devnames_name;
2761 2762


2763
static inline WORD get_devname_offset(const DEVNAMES *dn, devnames_name which)
2764
{
2765 2766 2767 2768 2769 2770
    switch(which)
    {
    case devnames_driver_name: return dn->wDriverOffset;
    case devnames_device_name: return dn->wDeviceOffset;
    case devnames_output_name: return dn->wOutputOffset;
    }
2771
    ERR("Shouldn't be here\n");
2772
    return 0;
2773 2774
}

2775
static WCHAR *pagesetup_get_a_devname(const pagesetup_data *data, devnames_name which)
2776 2777 2778 2779
{
    DEVNAMES *dn;
    WCHAR *name;

2780 2781 2782 2783 2784 2785 2786 2787 2788 2789
    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);
2790 2791 2792
    return name;
}

2793
static WCHAR *pagesetup_get_drvname(const pagesetup_data *data)
2794
{
2795
    return pagesetup_get_a_devname(data, devnames_driver_name);
2796 2797
}

2798
static WCHAR *pagesetup_get_devname(const pagesetup_data *data)
2799
{
2800 2801
    return pagesetup_get_a_devname(data, devnames_device_name);
}
2802

2803 2804 2805
static WCHAR *pagesetup_get_portname(const pagesetup_data *data)
{
    return pagesetup_get_a_devname(data, devnames_output_name);
2806 2807
}

2808
static void pagesetup_release_a_devname(const pagesetup_data *data, WCHAR *name)
2809 2810 2811 2812
{
    HeapFree(GetProcessHeap(), 0, name);
}

2813
static void pagesetup_set_devnames(pagesetup_data *data, LPCWSTR drv, LPCWSTR devname, LPCWSTR port)
2814 2815 2816 2817 2818
{
    DEVNAMES *dn;
    WCHAR def[256];
    DWORD len = sizeof(DEVNAMES), drv_len, dev_len, port_len;

2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830
    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);
    }
2831 2832
    len += drv_len + dev_len + port_len;

2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854
    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);
    }
2855
    else
2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869
    {
        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);
    }
2870 2871 2872 2873 2874 2875 2876

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

2877
    GlobalUnlock(data->u.dlgw->hDevNames);
2878 2879
}

2880
static DEVMODEW *pagesetup_get_devmode(const pagesetup_data *data)
2881
{
2882 2883
    DEVMODEW *dm = GlobalLock(data->u.dlgw->hDevMode);
    DEVMODEW *ret;
2884

2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896
    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;
2897 2898
}

2899
static void pagesetup_release_devmode(const pagesetup_data *data, DEVMODEW *dm)
2900 2901 2902 2903
{
    HeapFree(GetProcessHeap(), 0, dm);
}

2904
static void pagesetup_set_devmode(pagesetup_data *data, DEVMODEW *dm)
2905
{
2906 2907 2908
    DEVMODEA *dmA = NULL;
    void *src, *dst;
    DWORD size;
2909

2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920
    if(data->unicode)
    {
        size = dm->dmSize + dm->dmDriverExtra;
        src = dm;
    }
    else
    {
        dmA = convert_to_devmodeA(dm);
        size = dmA->dmSize + dmA->dmDriverExtra;
        src = dmA;
    }
2921

2922 2923 2924
    if(data->u.dlgw->hDevMode)
        data->u.dlgw->hDevMode = GlobalReAlloc(data->u.dlgw->hDevMode, size,
                                               GMEM_MOVEABLE);
2925
    else
2926 2927 2928 2929 2930 2931
        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);
2932 2933
}

2934 2935
static inline POINT *pagesetup_get_papersize_pt(const pagesetup_data *data)
{
2936
    return &data->u.dlgw->ptPaperSize;
2937 2938
}

2939 2940
static inline RECT *pagesetup_get_margin_rect(const pagesetup_data *data)
{
2941
    return &data->u.dlgw->rtMargin;
2942 2943
}

2944 2945 2946 2947 2948 2949 2950 2951 2952 2953
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)
    {
2954 2955
    case page_setup_hook: return data->u.dlgw->lpfnPageSetupHook;
    case page_paint_hook: return data->u.dlgw->lpfnPagePaintHook;
2956 2957 2958 2959
    }
    return NULL;
}

2960 2961 2962 2963
/* 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)
{
2964
    return (LPARAM)data->u.dlgw;
2965 2966
}

2967 2968 2969 2970 2971 2972 2973
static inline void swap_point(POINT *pt)
{
    LONG tmp = pt->x;
    pt->x = pt->y;
    pt->y = tmp;
}

2974
static BOOL pagesetup_update_papersize(pagesetup_data *data)
2975
{
2976 2977
    DEVMODEW *dm;
    LPWSTR devname, portname;
2978
    int i, num;
2979
    WORD *words = NULL, paperword;
2980 2981 2982
    POINT *points = NULL;
    BOOL retval = FALSE;

2983 2984 2985
    dm       = pagesetup_get_devmode(data);
    devname  = pagesetup_get_devname(data);
    portname = pagesetup_get_portname(data);
2986

2987
    num = DeviceCapabilitiesW(devname, portname, DC_PAPERS, NULL, dm);
2988 2989
    if (num <= 0)
    {
2990
        FIXME("No papernames found for %s/%s\n", debugstr_w(devname), debugstr_w(portname));
2991 2992 2993 2994 2995 2996
        goto end;
    }

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

2997
    if (num != DeviceCapabilitiesW(devname, portname, DC_PAPERS, (LPWSTR)words, dm))
2998 2999 3000 3001 3002
    {
        FIXME("Number of returned words is not %d\n", num);
        goto end;
    }

3003
    if (num != DeviceCapabilitiesW(devname, portname, DC_PAPERSIZE, (LPWSTR)points, dm))
3004
    {
3005
        FIXME("Number of returned sizes is not %d\n", num);
3006 3007 3008
        goto end;
    }

3009
    paperword = pagesetup_get_papersize(data);
3010

3011
    for (i = 0; i < num; i++)
3012
        if (words[i] == paperword)
3013 3014 3015 3016
            break;

    if (i == num)
    {
3017
        FIXME("Papersize %d not found in list?\n", paperword);
3018 3019 3020 3021
        goto end;
    }

    /* this is _10ths_ of a millimeter */
3022 3023
    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);
3024

3025
    if(pagesetup_get_orientation(data) == DMORIENT_LANDSCAPE)
3026 3027
        swap_point(pagesetup_get_papersize_pt(data));

3028 3029 3030 3031 3032
    retval = TRUE;

end:
    HeapFree(GetProcessHeap(), 0, words);
    HeapFree(GetProcessHeap(), 0, points);
3033 3034
    pagesetup_release_a_devname(data, portname);
    pagesetup_release_a_devname(data, devname);
3035
    pagesetup_release_devmode(data, dm);
3036

3037 3038
    return retval;
}
3039

3040
/**********************************************************************************************
3041
 * pagesetup_change_printer
3042 3043 3044 3045
 *
 * Redefines hDevMode and hDevNames HANDLES and initialises it.
 * 
 */
3046
static BOOL pagesetup_change_printer(LPWSTR name, pagesetup_data *data)
3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082
{
    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);

3083 3084
    pagesetup_set_devmode(data, dm);
    pagesetup_set_devnames(data, drv_info->pDriverPath, prn_info->pPrinterName,
3085 3086 3087 3088 3089 3090 3091 3092
                           prn_info->pPortName);

    retval = TRUE;
end:
    HeapFree(GetProcessHeap(), 0, dm);
    HeapFree(GetProcessHeap(), 0, prn_info);
    HeapFree(GetProcessHeap(), 0, drv_info);
    return retval;
3093 3094 3095
}

/****************************************************************************************
3096
 *  pagesetup_init_combos
3097
 *
3098
 *  Fills Printers, Paper and Source combos
3099
 *
3100
 */
3101
static void pagesetup_init_combos(HWND hDlg, pagesetup_data *data)
3102
{
3103 3104
    DEVMODEW *dm;
    LPWSTR devname, portname;
3105

3106 3107 3108
    dm       = pagesetup_get_devmode(data);
    devname  = pagesetup_get_devname(data);
    portname = pagesetup_get_portname(data);
3109 3110 3111 3112 3113

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

3114 3115
    pagesetup_release_a_devname(data, portname);
    pagesetup_release_a_devname(data, devname);
3116
    pagesetup_release_devmode(data, dm);
3117 3118
}

3119 3120 3121 3122 3123 3124 3125 3126

/****************************************************************************************
 *  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.
 */
3127
static void pagesetup_change_printer_dialog(HWND hDlg, pagesetup_data *data)
3128 3129 3130 3131 3132 3133 3134 3135 3136 3137
{
    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;

3138 3139 3140
    drvname = pagesetup_get_drvname(data);
    devname = pagesetup_get_devname(data);
    portname = pagesetup_get_portname(data);
3141 3142
    prnt.hDevNames = 0;
    PRINTDLG_CreateDevNamesW(&prnt.hDevNames, drvname, devname, portname);
3143 3144 3145
    pagesetup_release_a_devname(data, portname);
    pagesetup_release_a_devname(data, devname);
    pagesetup_release_a_devname(data, drvname);
3146

3147
    tmp_dm = pagesetup_get_devmode(data);
3148 3149 3150 3151
    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);
3152
    pagesetup_release_devmode(data, tmp_dm);
3153 3154 3155 3156 3157 3158

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

3159
        pagesetup_set_devnames(data, (WCHAR*)dn + dn->wDriverOffset,
3160
                               (WCHAR*)dn + dn->wDeviceOffset, (WCHAR *)dn + dn->wOutputOffset);
3161
        pagesetup_set_devmode(data, dm);
3162 3163
        GlobalUnlock(prnt.hDevNames);
        GlobalUnlock(prnt.hDevMode);
3164
        pagesetup_init_combos(hDlg, data);
3165 3166 3167 3168 3169 3170 3171
    }

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

}

3172
/******************************************************************************************
3173
 * pagesetup_change_preview
3174
 *
3175
 * Changes paper preview size / position
3176 3177
 *
 */
3178
static void pagesetup_change_preview(const pagesetup_data *data)
3179 3180
{
    LONG width, height, x, y;
3181 3182 3183 3184 3185 3186
    RECT tmp;
    const int shadow = 4;

    if(pagesetup_get_orientation(data) == DMORIENT_LANDSCAPE)
    {
        width  = data->rtDrawRect.right - data->rtDrawRect.left;
3187
        height = pagesetup_get_papersize_pt(data)->y * width / pagesetup_get_papersize_pt(data)->x;
3188 3189 3190 3191
    }
    else
    {
        height = data->rtDrawRect.bottom - data->rtDrawRect.top;
3192
        width  = pagesetup_get_papersize_pt(data)->x * height / pagesetup_get_papersize_pt(data)->y;
3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206
    }
    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);
3207 3208
}

3209 3210 3211 3212 3213 3214 3215 3216 3217 3218 3219 3220
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;
}

3221
static void update_margin_edits(HWND hDlg, const pagesetup_data *data, WORD id)
3222 3223
{
    WCHAR str[100];
3224
    WORD idx;
3225

3226 3227 3228 3229
    for(idx = edt4; idx <= edt7; idx++)
    {
        if(id == 0 || id == idx)
        {
3230
            size2str(data, *element_from_margin_id(pagesetup_get_margin_rect(data), idx), str);
3231 3232 3233
            SetDlgItemTextW(hDlg, idx, str);
        }
    }
3234 3235
}

3236
static void margin_edit_notification(HWND hDlg, const pagesetup_data *data, WORD msg, WORD id)
3237 3238 3239 3240 3241 3242 3243
{
    switch (msg)
    {
    case EN_CHANGE:
      {
        WCHAR buf[10];
        LONG val = 0;
3244
        LONG *value = element_from_margin_id(pagesetup_get_margin_rect(data), id);
3245 3246 3247 3248

        if (GetDlgItemTextW(hDlg, id, buf, sizeof(buf) / sizeof(buf[0])) != 0)
        {
            WCHAR *end;
3249
            WCHAR decimal = get_decimal_sep();
3250 3251 3252 3253

            val = strtolW(buf, &end, 10);
            if(end != buf || *end == decimal)
            {
3254
                int mult = is_metric(data) ? 100 : 1000;
3255 3256 3257 3258 3259 3260 3261 3262 3263 3264 3265 3266 3267 3268 3269 3270 3271 3272 3273 3274
                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:
3275
        update_margin_edits(hDlg, data, id);
3276 3277 3278 3279
        return;
    }
}

3280
static void set_margin_groupbox_title(HWND hDlg, const pagesetup_data *data)
3281 3282 3283
{
    WCHAR title[256];

3284
    if(LoadStringW(COMDLG32_hInstance, is_metric(data) ? PD32_MARGINS_IN_MILLIMETERS : PD32_MARGINS_IN_INCHES,
3285 3286 3287 3288
                   title, sizeof(title)/sizeof(title[0])))
        SetDlgItemTextW(hDlg, grp4, title);
}

3289
static void pagesetup_update_orientation_buttons(HWND hDlg, const pagesetup_data *data)
3290
{
3291
    if (pagesetup_get_orientation(data) == DMORIENT_LANDSCAPE)
3292 3293 3294 3295 3296
        CheckRadioButton(hDlg, rad1, rad2, rad2);
    else
        CheckRadioButton(hDlg, rad1, rad2, rad1);
}

3297 3298 3299 3300 3301
/****************************************************************************************
 *  pagesetup_printer_properties
 *
 *  Handle invocation of the 'Properties' button (not present in the default template).
 */
3302
static void pagesetup_printer_properties(HWND hDlg, pagesetup_data *data)
3303 3304 3305 3306 3307 3308 3309 3310 3311 3312 3313 3314
{
    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");
3315
        pagesetup_release_a_devname(data, devname);
3316 3317 3318 3319 3320 3321 3322
        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);
3323
    pagesetup_release_a_devname(data, devname);
3324 3325 3326 3327 3328 3329 3330
    ClosePrinter(hprn);

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

    /* Changing paper preview */
3331
    pagesetup_change_preview(data);
3332 3333 3334 3335 3336 3337 3338 3339 3340 3341 3342 3343 3344 3345 3346 3347

    /* 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;
            }
        }
    }
}

3348
/********************************************************************************
3349 3350
 * pagesetup_wm_command
 * process WM_COMMAND message for PageSetupDlg
3351 3352 3353 3354 3355 3356 3357 3358
 *
 * PARAMS
 *  hDlg 	[in] 	Main dialog HANDLE 
 *  wParam 	[in]	WM_COMMAND wParam
 *  lParam	[in]	WM_COMMAND lParam
 *  pda		[in/out] ptr to PageSetupDataA
 */

3359
static BOOL pagesetup_wm_command(HWND hDlg, WPARAM wParam, LPARAM lParam, pagesetup_data *data)
3360
{
3361 3362
    WORD msg = HIWORD(wParam);
    WORD id  = LOWORD(wParam);
3363

3364
    TRACE("loword (lparam) %d, wparam 0x%lx, lparam %08lx\n",
3365
	    LOWORD(lParam),wParam,lParam);
3366
    switch (id)  {
3367 3368 3369 3370 3371 3372 3373 3374
    case IDOK:
	EndDialog(hDlg, TRUE);
	return TRUE ;

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

3375
    case psh3: /* Printer... */
3376
        pagesetup_change_printer_dialog(hDlg, data);
3377
        return TRUE;
3378 3379 3380

    case rad1: /* Portrait */
    case rad2: /* Landscape */
3381 3382
        if((id == rad1 && pagesetup_get_orientation(data) == DMORIENT_LANDSCAPE) ||
           (id == rad2 && pagesetup_get_orientation(data) == DMORIENT_PORTRAIT))
3383
	{
3384 3385
            pagesetup_set_orientation(data, (id == rad1) ? DMORIENT_PORTRAIT : DMORIENT_LANDSCAPE);
            pagesetup_update_papersize(data);
3386
            rotate_rect(pagesetup_get_margin_rect(data), (id == rad2));
3387 3388
            update_margin_edits(hDlg, data, 0);
            pagesetup_change_preview(data);
3389 3390
	}
	break;
3391
    case cmb1: /* Printer combo */
3392 3393
        if(msg == CBN_SELCHANGE)
        {
3394 3395 3396 3397 3398
            WCHAR *name;
            INT index = SendDlgItemMessageW(hDlg, id, CB_GETCURSEL, 0, 0);
            INT length = SendDlgItemMessageW(hDlg, id, CB_GETLBTEXTLEN, index, 0);
            name = HeapAlloc(GetProcessHeap(),0,sizeof(WCHAR)*(length+1));
            SendDlgItemMessageW(hDlg, id, CB_GETLBTEXT, index, (LPARAM)name);
3399 3400
            pagesetup_change_printer(name, data);
            pagesetup_init_combos(hDlg, data);
3401
            HeapFree(GetProcessHeap(),0,name);
3402 3403
        }
        break;
3404
    case cmb2: /* Paper combo */
3405 3406 3407 3408
        if(msg == CBN_SELCHANGE)
        {
            DWORD paperword = SendDlgItemMessageW(hDlg, cmb2, CB_GETITEMDATA,
                                                  SendDlgItemMessageW(hDlg, cmb2, CB_GETCURSEL, 0, 0), 0);
3409 3410
            if (paperword != CB_ERR)
            {
3411 3412 3413
                pagesetup_set_papersize(data, paperword);
                pagesetup_update_papersize(data);
                pagesetup_change_preview(data);
3414
	    } else
3415 3416 3417
                FIXME("could not get dialog text for papersize cmbbox?\n");
        }
        break;
3418 3419 3420
    case cmb3: /* Paper Source */
        if(msg == CBN_SELCHANGE)
        {
3421 3422
            WORD source = SendDlgItemMessageW(hDlg, cmb3, CB_GETITEMDATA,
                                              SendDlgItemMessageW(hDlg, cmb3, CB_GETCURSEL, 0, 0), 0);
3423
            pagesetup_set_defaultsource(data, source);
3424 3425
        }
        break;
3426
    case psh2: /* Printer Properties button */
3427
        pagesetup_printer_properties(hDlg, data);
3428
        break;
3429 3430 3431 3432
    case edt4:
    case edt5:
    case edt6:
    case edt7:
3433
        margin_edit_notification(hDlg, data, msg, id);
3434
        break;
3435
    }
3436
    InvalidateRect(GetDlgItem(hDlg, rct1), NULL, TRUE);
3437 3438 3439
    return FALSE;
}

3440
/***********************************************************************
3441
 *           default_page_paint_hook
3442 3443
 * Default hook paint procedure that receives WM_PSD_* messages from the dialog box 
 * whenever the sample page is redrawn.
3444 3445 3446
 */
static UINT_PTR default_page_paint_hook(HWND hwndDlg, UINT uMsg, WPARAM wParam, LPARAM lParam,
                                        const pagesetup_data *data)
3447 3448 3449 3450 3451 3452 3453 3454 3455
{
    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 */
3456
    if (pagesetup_get_flags(data) & PSD_ENABLEPAGEPAINTHOOK)
3457
        if (pagesetup_get_hook(data, page_paint_hook)(hwndDlg, uMsg, wParam, lParam))
3458 3459 3460 3461 3462 3463 3464 3465 3466 3467 3468 3469 3470 3471 3472 3473 3474 3475 3476 3477 3478 3479 3480 3481 3482 3483 3484 3485 3486 3487 3488 3489 3490 3491 3492 3493 3494 3495 3496 3497 3498 3499 3500 3501 3502 3503 3504 3505 3506 3507 3508 3509 3510 3511 3512 3513 3514 3515 3516 3517 3518 3519 3520 3521 3522 3523 3524 3525 3526 3527 3528 3529 3530 3531 3532 3533 3534 3535 3536 3537 3538 3539 3540
            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
 *
 */
3541 3542


3543
static LRESULT CALLBACK
3544
PRINTDLG_PagePaintProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
3545
{
3546 3547 3548 3549 3550
    PAINTSTRUCT ps;
    RECT rcClient, rcMargin;
    HPEN hpen, holdpen;
    HDC hdc;
    HBRUSH hbrush, holdbrush;
3551
    pagesetup_data *data;
3552
    int papersize=0, orientation=0; /* FIXME: set these values for the user paint hook */
3553
    double scalx, scaly;
3554 3555 3556 3557 3558

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

    /* Processing WM_PAINT message */
3559 3560
    data = GetPropW(hWnd, pagesetupdlg_prop);
    if (!data) {
3561 3562 3563
        WARN("__WINE_PAGESETUPDLGDATA prop not set?\n");
        return FALSE;
    }
3564 3565
    if (default_page_paint_hook(hWnd, WM_PSD_PAGESETUPDLG, MAKELONG(papersize, orientation),
                                pagesetup_get_dlg_struct(data), data))
3566
        return FALSE;
3567

3568 3569
    hdc = BeginPaint(hWnd, &ps);
    GetClientRect(hWnd, &rcClient);
3570
    
3571 3572
    scalx = rcClient.right  / (double)pagesetup_get_papersize_pt(data)->x;
    scaly = rcClient.bottom / (double)pagesetup_get_papersize_pt(data)->y;
3573
    rcMargin = rcClient;
3574

3575
    rcMargin.left   += pagesetup_get_margin_rect(data)->left   * scalx;
3576 3577
    rcMargin.top    += pagesetup_get_margin_rect(data)->top    * scaly;
    rcMargin.right  -= pagesetup_get_margin_rect(data)->right  * scalx;
3578
    rcMargin.bottom -= pagesetup_get_margin_rect(data)->bottom * scaly;
3579

3580 3581 3582 3583
    /* 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);

3584 3585
    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) )
3586
    {
3587 3588 3589 3590 3591 3592 3593
        /* 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);
3594
        
3595 3596 3597 3598 3599 3600 3601 3602 3603 3604 3605 3606 3607 3608 3609 3610 3611 3612 3613
        /* 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);

3614 3615
        DeleteObject(SelectObject(hdc, holdpen));
        DeleteObject(SelectObject(hdc, holdbrush));
3616

3617
        default_page_paint_hook(hWnd, WM_PSD_MARGINRECT, (WPARAM)hdc, (LPARAM)&rcMargin, data);
3618 3619

        /* give text a bit of a space from the frame */
3620 3621 3622 3623 3624
        rcMargin.left += 2;
        rcMargin.top += 2;
        rcMargin.right -= 2;
        rcMargin.bottom -= 2;
        
3625
        /* if the space is too small then we make sure to not draw anything */
3626 3627
        rcMargin.left = min(rcMargin.left, rcMargin.right);
        rcMargin.top = min(rcMargin.top, rcMargin.bottom);
3628

3629
        default_page_paint_hook(hWnd, WM_PSD_GREEKTEXTRECT, (WPARAM)hdc, (LPARAM)&rcMargin, data);
3630
    }
3631 3632 3633

    EndPaint(hWnd, &ps);
    return FALSE;
3634 3635
}

3636 3637 3638 3639 3640 3641
/*******************************************************
 * 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
3642
    if (msg == WM_CHAR)
3643
    {
3644
        WCHAR decimal = get_decimal_sep();
3645 3646 3647 3648 3649 3650 3651 3652 3653 3654 3655 3656 3657 3658 3659 3660 3661 3662 3663 3664
        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);
    }
}

3665
/***********************************************************************
3666 3667 3668
 *           pagesetup_dlg_proc
 *
 * Message handler for PageSetupDlg
3669
 */
3670
static INT_PTR CALLBACK pagesetup_dlg_proc(HWND hDlg, UINT uMsg, WPARAM wParam, LPARAM lParam)
3671
{
3672
    pagesetup_data *data;
3673
    INT_PTR		res = FALSE;
3674
    HWND 		hDrawWnd;
3675

3676
    if (uMsg == WM_INITDIALOG) { /*Init dialog*/
3677 3678 3679
        data = (pagesetup_data *)lParam;
        data->hDlg = hDlg;

3680
	hDrawWnd = GetDlgItem(hDlg, rct1); 
3681 3682 3683 3684
        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 */
3685
        MapWindowPoints( 0, hDlg, (LPPOINT)&data->rtDrawRect, 2 );
3686
        lpfnStaticWndProc = (WNDPROC)SetWindowLongPtrW(
3687
            hDrawWnd,
3688
            GWLP_WNDPROC,
3689
            (ULONG_PTR)PRINTDLG_PagePaintProc);
3690
	
3691
	/* FIXME: Paint hook. Must it be at begin of initialization or at end? */
3692
	res = TRUE;
3693
        if (pagesetup_get_flags(data) & PSD_ENABLEPAGESETUPHOOK)
3694
        {
3695 3696
            if (!pagesetup_get_hook(data, page_setup_hook)(hDlg, uMsg, wParam,
                                                           pagesetup_get_dlg_struct(data)))
3697 3698
		FIXME("Setup page hook failed?\n");
	}
3699

3700
	/* if printer button disabled */
3701
        if (pagesetup_get_flags(data) & PSD_DISABLEPRINTER)
3702
            EnableWindow(GetDlgItem(hDlg, psh3), FALSE);
3703
	/* if margin edit boxes disabled */
3704
        if (pagesetup_get_flags(data) & PSD_DISABLEMARGINS)
3705
        {
3706 3707 3708 3709
            EnableWindow(GetDlgItem(hDlg, edt4), FALSE);
            EnableWindow(GetDlgItem(hDlg, edt5), FALSE);
            EnableWindow(GetDlgItem(hDlg, edt6), FALSE);
            EnableWindow(GetDlgItem(hDlg, edt7), FALSE);
3710
	}
3711

3712
        /* Set orientation radiobuttons properly */
3713
        pagesetup_update_orientation_buttons(hDlg, data);
3714

3715
	/* if orientation disabled */
3716
        if (pagesetup_get_flags(data) & PSD_DISABLEORIENTATION)
3717
        {
3718 3719 3720
	    EnableWindow(GetDlgItem(hDlg,rad1),FALSE);
	    EnableWindow(GetDlgItem(hDlg,rad2),FALSE);
	}
3721

3722
	/* We fill them out enabled or not */
3723
        if (!(pagesetup_get_flags(data) & PSD_MARGINS))
3724
        {
3725
            /* default is 1 inch */
3726
            LONG size = thousandths_inch_to_size(data, 1000);
3727
            SetRect(pagesetup_get_margin_rect(data), size, size, size, size);
3728
        }
3729
        update_margin_edits(hDlg, data, 0);
3730
        subclass_margin_edits(hDlg);
3731
        set_margin_groupbox_title(hDlg, data);
3732

3733
	/* if paper disabled */
3734
        if (pagesetup_get_flags(data) & PSD_DISABLEPAPER)
3735
        {
3736 3737 3738
	    EnableWindow(GetDlgItem(hDlg,cmb2),FALSE);
	    EnableWindow(GetDlgItem(hDlg,cmb3),FALSE);
	}
3739

3740
	/* filling combos: printer, paper, source. selecting current printer (from DEVMODEA) */
3741 3742 3743
        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? */
3744

3745
	/* Drawing paper prev */
3746
        pagesetup_change_preview(data);
3747 3748
	return TRUE;
    } else {
3749 3750 3751
        data = GetPropW(hDlg, pagesetupdlg_prop);
        if (!data)
        {
3752 3753 3754
	    WARN("__WINE_PAGESETUPDLGDATA prop not set?\n");
	    return FALSE;
	}
3755
        if (pagesetup_get_flags(data) & PSD_ENABLEPAGESETUPHOOK)
3756
        {
3757
            res = pagesetup_get_hook(data, page_setup_hook)(hDlg, uMsg, wParam, lParam);
3758 3759 3760 3761 3762
	    if (res) return res;
	}
    }
    switch (uMsg) {
    case WM_COMMAND:
3763
        return pagesetup_wm_command(hDlg, wParam, lParam, data);
3764 3765 3766 3767
    }
    return FALSE;
}

3768 3769 3770 3771
static WCHAR *get_default_printer(void)
{
    WCHAR *name = NULL;
    DWORD len = 0;
3772

3773 3774 3775 3776 3777
    GetDefaultPrinterW(NULL, &len);
    if(len)
    {
        name = HeapAlloc(GetProcessHeap(), 0, len * sizeof(WCHAR));
        GetDefaultPrinterW(name, &len);
3778
    }
3779 3780
    return name;
}
3781

3782
static void pagesetup_dump_dlg_struct(const pagesetup_data *data)
3783 3784 3785
{
    if(TRACE_ON(commdlg))
    {
3786
        char flagstr[1000] = "";
3787
	const struct pd_flags *pflag = psd_flags;
3788 3789 3790 3791 3792 3793 3794 3795
        for( ; pflag->name; pflag++)
        {
            if(pagesetup_get_flags(data) & pflag->flag)
            {
                strcat(flagstr, pflag->name);
                strcat(flagstr, "|");
            }
        }
3796
        TRACE("%s: (%p): hwndOwner = %p, hDevMode = %p, hDevNames = %p\n"
3797
              "hinst %p, flags %08x (%s)\n",
3798 3799 3800
              data->unicode ? "unicode" : "ansi",
              data->u.dlgw, data->u.dlgw->hwndOwner, data->u.dlgw->hDevMode,
              data->u.dlgw->hDevNames, data->u.dlgw->hInstance,
3801
              pagesetup_get_flags(data), flagstr);
3802
    }
3803
}
3804

3805 3806 3807 3808 3809 3810 3811
static void *pagesetup_get_template(pagesetup_data *data)
{
    HRSRC res;
    HGLOBAL tmpl_handle;

    if(pagesetup_get_flags(data) & PSD_ENABLEPAGESETUPTEMPLATEHANDLE)
    {
3812
	tmpl_handle = data->u.dlgw->hPageSetupTemplate;
3813
    }
3814 3815
    else if(pagesetup_get_flags(data) & PSD_ENABLEPAGESETUPTEMPLATE)
    {
3816 3817
        if(data->unicode)
            res = FindResourceW(data->u.dlgw->hInstance,
3818
                                data->u.dlgw->lpPageSetupTemplateName, (LPWSTR)RT_DIALOG);
3819 3820
        else
            res = FindResourceA(data->u.dlga->hInstance,
3821
                                data->u.dlga->lpPageSetupTemplateName, (LPSTR)RT_DIALOG);
3822
        tmpl_handle = LoadResource(data->u.dlgw->hInstance, res);
3823 3824 3825 3826
    }
    else
    {
        res = FindResourceW(COMDLG32_hInstance, MAKEINTRESOURCEW(PAGESETUPDLGORD),
3827
                            (LPWSTR)RT_DIALOG);
3828 3829 3830 3831 3832 3833 3834 3835 3836
        tmpl_handle = LoadResource(COMDLG32_hInstance, res);
    }
    return LockResource(tmpl_handle);
}

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

3838 3839 3840 3841 3842 3843 3844 3845
    if(!pagesetup_get_dlg_struct(data))
    {
        COMDLG32_SetCommDlgExtendedError(CDERR_INITIALIZATION);
        return FALSE;
    }

    pagesetup_dump_dlg_struct(data);

3846
    if(data->u.dlgw->lStructSize != sizeof(PAGESETUPDLGW))
3847 3848 3849 3850 3851 3852 3853 3854 3855 3856 3857 3858 3859
    {
        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)))
3860
        data->u.dlgw->Flags |= is_default_metric() ?
3861 3862
            PSD_INHUNDREDTHSOFMILLIMETERS : PSD_INTHOUSANDTHSOFINCHES;

3863
    if (!data->u.dlgw->hDevMode || !data->u.dlgw->hDevNames)
3864
    {
3865 3866
        WCHAR *def = get_default_printer();
        if(!def)
3867
        {
3868 3869
            if (!(pagesetup_get_flags(data) & PSD_NOWARNING))
            {
3870 3871
                WCHAR errstr[256];
                LoadStringW(COMDLG32_hInstance, PD32_NO_DEFAULT_PRINTER, errstr, 255);
3872
                MessageBoxW(data->u.dlgw->hwndOwner, errstr, 0, MB_OK | MB_ICONERROR);
3873
            }
3874
            COMDLG32_SetCommDlgExtendedError(PDERR_NODEFAULTPRN);
3875 3876
            return FALSE;
        }
3877 3878
        pagesetup_change_printer(def, data);
        HeapFree(GetProcessHeap(), 0, def);
3879
    }
3880

3881 3882
    if (pagesetup_get_flags(data) & PSD_RETURNDEFAULT)
    {
3883
        pagesetup_update_papersize(data);
3884
        return TRUE;
3885
    }
3886

3887
    tmpl = pagesetup_get_template(data);
3888

3889 3890
    ret = DialogBoxIndirectParamW(data->u.dlgw->hInstance, tmpl,
                                  data->u.dlgw->hwndOwner,
3891 3892 3893
                                  pagesetup_dlg_proc, (LPARAM)data) > 0;
    return ret;
}
3894

3895 3896 3897 3898 3899 3900 3901 3902 3903 3904 3905 3906 3907 3908 3909 3910 3911 3912 3913 3914 3915 3916 3917
/***********************************************************************
 *            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;

3918 3919
    data.unicode = FALSE;
    data.u.dlga  = setupdlg;
3920 3921

    return pagesetup_common(&data);
3922
}
3923

3924
/***********************************************************************
3925
 *            PageSetupDlgW  (COMDLG32.@)
3926 3927
 *
 * See PageSetupDlgA.
3928
 */
3929 3930 3931
BOOL WINAPI PageSetupDlgW(LPPAGESETUPDLGW setupdlg)
{
    pagesetup_data data;
3932

3933 3934
    data.unicode = TRUE;
    data.u.dlgw  = setupdlg;
3935

3936
    return pagesetup_common(&data);
3937
}
3938

3939 3940 3941 3942 3943 3944 3945 3946 3947 3948 3949 3950 3951 3952 3953 3954 3955 3956 3957 3958 3959 3960 3961 3962 3963 3964 3965 3966 3967 3968 3969 3970 3971 3972 3973 3974 3975 3976 3977 3978 3979 3980 3981 3982 3983 3984 3985 3986 3987 3988 3989 3990 3991
static void pdlgex_to_pdlg(const PRINTDLGEXW *pdlgex, PRINTDLGW *pdlg)
{
    pdlg->lStructSize = sizeof(*pdlg);
    pdlg->hwndOwner = pdlgex->hwndOwner;
    pdlg->hDevMode = pdlgex->hDevMode;
    pdlg->hDevNames = pdlgex->hDevNames;
    pdlg->hDC = pdlgex->hDC;
    pdlg->Flags = pdlgex->Flags;
    if ((pdlgex->Flags & PD_NOPAGENUMS) || !pdlgex->nPageRanges || !pdlgex->lpPageRanges)
    {
        pdlg->nFromPage = 0;
        pdlg->nToPage = 65534;
    }
    else
    {
        pdlg->nFromPage = pdlgex->lpPageRanges[0].nFromPage;
        pdlg->nToPage = pdlgex->lpPageRanges[0].nToPage;
    }
    pdlg->nMinPage = pdlgex->nMinPage;
    pdlg->nMaxPage = pdlgex->nMaxPage;
    pdlg->nCopies = pdlgex->nCopies;
    pdlg->hInstance = pdlgex->hInstance;
    pdlg->lCustData = 0;
    pdlg->lpfnPrintHook = NULL;
    pdlg->lpfnSetupHook = NULL;
    pdlg->lpPrintTemplateName = pdlgex->lpPrintTemplateName;
    pdlg->lpSetupTemplateName = NULL;
    pdlg->hPrintTemplate = NULL;
    pdlg->hSetupTemplate = NULL;
}

/* Only copy fields that are supposed to be changed. */
static void pdlg_to_pdlgex(const PRINTDLGW *pdlg, PRINTDLGEXW *pdlgex)
{
    pdlgex->hDevMode = pdlg->hDevMode;
    pdlgex->hDevNames = pdlg->hDevNames;
    pdlgex->hDC = pdlg->hDC;
    if (!(pdlgex->Flags & PD_NOPAGENUMS) && pdlgex->nPageRanges && pdlgex->lpPageRanges)
    {
        pdlgex->lpPageRanges[0].nFromPage = pdlg->nFromPage;
        pdlgex->lpPageRanges[0].nToPage = pdlg->nToPage;
    }
    pdlgex->nMinPage = pdlg->nMinPage;
    pdlgex->nMaxPage = pdlg->nMaxPage;
    pdlgex->nCopies = pdlg->nCopies;
}

struct callback_data
{
    IPrintDialogCallback *callback;
    IObjectWithSite *object;
};

3992
static UINT_PTR CALLBACK pdlgex_hook_proc(HWND hwnd, UINT msg, WPARAM wp, LPARAM lp)
3993 3994 3995 3996 3997 3998
{
    if (msg == WM_INITDIALOG)
    {
        PRINTDLGW *pd = (PRINTDLGW *)lp;
        struct callback_data *cb = (struct callback_data *)pd->lCustData;

3999 4000 4001 4002 4003
        if (cb->callback)
        {
            cb->callback->lpVtbl->SelectionChange(cb->callback);
            cb->callback->lpVtbl->InitDone(cb->callback);
        }
4004 4005 4006 4007 4008 4009 4010 4011 4012 4013 4014 4015
    }
    else
    {
/* FIXME: store interface pointer somewhere in window properties and call it
        HRESULT hres;
        cb->callback->lpVtbl->HandleMessage(cb->callback, hwnd, msg, wp, lp, &hres);
*/
    }

    return 0;
}

4016
/***********************************************************************
4017
 * PrintDlgExA (COMDLG32.@)
4018 4019 4020
 *
 * See PrintDlgExW.
 *
4021 4022 4023
 * BUGS
 *   Only a Stub
 *
4024
 */
4025
HRESULT WINAPI PrintDlgExA(LPPRINTDLGEXA lppd)
4026
{
4027 4028 4029 4030 4031
    PRINTER_INFO_2A *pbuf;
    DRIVER_INFO_3A *dbuf;
    DEVMODEA *dm;
    HRESULT hr = S_OK;
    HANDLE hprn;
4032

4033
    if ((lppd == NULL) || (lppd->lStructSize != sizeof(PRINTDLGEXA)))
4034 4035
        return E_INVALIDARG;

4036
    if (!IsWindow(lppd->hwndOwner))
4037
        return E_HANDLE;
4038

4039 4040 4041 4042 4043 4044 4045 4046 4047 4048 4049 4050 4051 4052
    if (lppd->nStartPage != START_PAGE_GENERAL)
    {
        if (!lppd->nPropertyPages)
            return E_INVALIDARG;

        FIXME("custom property sheets (%d at %p) not supported\n", lppd->nPropertyPages, lppd->lphPropertyPages);
    }

    /* Use PD_NOPAGENUMS or set nMaxPageRanges and lpPageRanges */
    if (!(lppd->Flags & PD_NOPAGENUMS) && (!lppd->nMaxPageRanges || !lppd->lpPageRanges))
    {
        return E_INVALIDARG;
    }

4053 4054 4055 4056 4057 4058 4059 4060 4061 4062 4063 4064 4065 4066 4067
    if (lppd->Flags & PD_RETURNDEFAULT)
    {
        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;
        }

4068 4069
        pbuf = get_printer_infoA(hprn);
        if (!pbuf)
4070 4071 4072 4073 4074
        {
            ClosePrinter(hprn);
            return E_FAIL;
        }

4075 4076
        dbuf = get_driver_infoA(hprn);
        if (!dbuf)
4077 4078 4079 4080 4081 4082
        {
            HeapFree(GetProcessHeap(), 0, pbuf);
            COMDLG32_SetCommDlgExtendedError(PDERR_RETDEFFAILURE);
            ClosePrinter(hprn);
            return E_FAIL;
        }
4083 4084 4085 4086
        dm = pbuf->pDevMode;
    }
    else
    {
4087 4088 4089 4090 4091 4092 4093 4094 4095 4096 4097 4098 4099 4100 4101 4102 4103 4104 4105 4106 4107 4108 4109 4110 4111 4112 4113 4114 4115 4116 4117
        PRINTDLGA pdlg;
        struct callback_data cb_data = { 0 };

        FIXME("(%p) semi-stub\n", lppd);

        if (lppd->lpCallback)
        {
            IUnknown_QueryInterface((IUnknown *)lppd->lpCallback, &IID_IPrintDialogCallback, (void **)&cb_data.callback);
            IUnknown_QueryInterface((IUnknown *)lppd->lpCallback, &IID_IObjectWithSite, (void **)&cb_data.object);
        }

        /*
         * PRINTDLGEXA/W and PRINTDLGA/W layout is the same for A and W variants.
         */
        pdlgex_to_pdlg((const PRINTDLGEXW *)lppd, (PRINTDLGW *)&pdlg);
        pdlg.Flags |= PD_ENABLEPRINTHOOK;
        pdlg.lpfnPrintHook = pdlgex_hook_proc;
        pdlg.lCustData = (LPARAM)&cb_data;

        if (PrintDlgA(&pdlg))
        {
            pdlg_to_pdlgex((const PRINTDLGW *)&pdlg, (PRINTDLGEXW *)lppd);
            lppd->dwResultAction = PD_RESULT_PRINT;
        }
        else
            lppd->dwResultAction = PD_RESULT_CANCEL;

        if (cb_data.callback)
            cb_data.callback->lpVtbl->Release(cb_data.callback);
        if (cb_data.object)
            cb_data.object->lpVtbl->Release(cb_data.object);
4118

4119
        return S_OK;
4120 4121
    }

4122 4123 4124 4125 4126 4127 4128
    ClosePrinter(hprn);

    PRINTDLG_CreateDevNames(&(lppd->hDevNames), dbuf->pDriverPath, pbuf->pPrinterName, pbuf->pPortName);
    if (!lppd->hDevNames)
        hr = E_FAIL;

    lppd->hDevMode = update_devmode_handleA(lppd->hDevMode, dm);
4129
    if (hr == S_OK && lppd->hDevMode) {
4130 4131 4132 4133 4134 4135 4136 4137 4138 4139 4140 4141
        if (lppd->Flags & PD_RETURNDC) {
            lppd->hDC = CreateDCA(dbuf->pDriverPath, pbuf->pPrinterName, pbuf->pPortName, dm);
            if (!lppd->hDC)
                hr = E_FAIL;
        }
        else if (lppd->Flags & PD_RETURNIC) {
            lppd->hDC = CreateICA(dbuf->pDriverPath, pbuf->pPrinterName, pbuf->pPortName, dm);
            if (!lppd->hDC)
                hr = E_FAIL;
        }
    }
    else
4142 4143 4144 4145 4146 4147
        hr = E_FAIL;

    HeapFree(GetProcessHeap(), 0, pbuf);
    HeapFree(GetProcessHeap(), 0, dbuf);

    return hr;
4148
}
4149

4150
/***********************************************************************
4151
 * PrintDlgExW (COMDLG32.@)
4152
 *
4153
 * Display the property sheet style PRINT dialog box
4154 4155 4156 4157 4158 4159 4160 4161 4162 4163 4164 4165 4166
 *  
 * 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.
 *  
4167 4168 4169 4170 4171 4172
 * 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
4173
 *   Not fully implemented
4174
 *
4175
 */
4176
HRESULT WINAPI PrintDlgExW(LPPRINTDLGEXW lppd)
4177
{
4178 4179 4180 4181 4182
    PRINTER_INFO_2W *pbuf;
    DRIVER_INFO_3W *dbuf;
    DEVMODEW *dm;
    HRESULT hr = S_OK;
    HANDLE hprn;
4183 4184 4185 4186 4187 4188 4189 4190 4191

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

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

4192 4193 4194 4195 4196 4197 4198 4199 4200 4201 4202 4203 4204 4205
    if (lppd->nStartPage != START_PAGE_GENERAL)
    {
        if (!lppd->nPropertyPages)
            return E_INVALIDARG;

        FIXME("custom property sheets (%d at %p) not supported\n", lppd->nPropertyPages, lppd->lphPropertyPages);
    }

    /* Use PD_NOPAGENUMS or set nMaxPageRanges and lpPageRanges */
    if (!(lppd->Flags & PD_NOPAGENUMS) && (!lppd->nMaxPageRanges || !lppd->lpPageRanges))
    {
        return E_INVALIDARG;
    }

4206 4207 4208 4209 4210 4211 4212 4213 4214 4215 4216 4217 4218
    if (lppd->Flags & PD_RETURNDEFAULT) {

        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;
        }

4219 4220 4221
        pbuf = get_printer_infoW(hprn);
        if (!pbuf)
        {
4222 4223 4224 4225
            ClosePrinter(hprn);
            return E_FAIL;
        }

4226 4227 4228
        dbuf = get_driver_infoW(hprn);
        if (!dbuf)
        {
4229 4230 4231 4232 4233
            HeapFree(GetProcessHeap(), 0, pbuf);
            COMDLG32_SetCommDlgExtendedError(PDERR_RETDEFFAILURE);
            ClosePrinter(hprn);
            return E_FAIL;
        }
4234 4235 4236 4237
        dm = pbuf->pDevMode;
    }
    else
    {
4238 4239 4240 4241 4242 4243 4244 4245 4246 4247 4248 4249 4250 4251 4252 4253 4254 4255 4256 4257 4258 4259 4260 4261 4262 4263 4264 4265
        PRINTDLGW pdlg;
        struct callback_data cb_data = { 0 };

        FIXME("(%p) semi-stub\n", lppd);

        if (lppd->lpCallback)
        {
            IUnknown_QueryInterface((IUnknown *)lppd->lpCallback, &IID_IPrintDialogCallback, (void **)&cb_data.callback);
            IUnknown_QueryInterface((IUnknown *)lppd->lpCallback, &IID_IObjectWithSite, (void **)&cb_data.object);
        }

        pdlgex_to_pdlg(lppd, &pdlg);
        pdlg.Flags |= PD_ENABLEPRINTHOOK;
        pdlg.lpfnPrintHook = pdlgex_hook_proc;
        pdlg.lCustData = (LPARAM)&cb_data;

        if (PrintDlgW(&pdlg))
        {
            pdlg_to_pdlgex(&pdlg, lppd);
            lppd->dwResultAction = PD_RESULT_PRINT;
        }
        else
            lppd->dwResultAction = PD_RESULT_CANCEL;

        if (cb_data.callback)
            cb_data.callback->lpVtbl->Release(cb_data.callback);
        if (cb_data.object)
            cb_data.object->lpVtbl->Release(cb_data.object);
4266

4267
        return S_OK;
4268 4269
    }

4270 4271 4272 4273 4274 4275 4276
    ClosePrinter(hprn);

    PRINTDLG_CreateDevNamesW(&(lppd->hDevNames), dbuf->pDriverPath, pbuf->pPrinterName, pbuf->pPortName);
    if (!lppd->hDevNames)
        hr = E_FAIL;

    lppd->hDevMode = update_devmode_handleW(lppd->hDevMode, dm);
4277
    if (hr == S_OK && lppd->hDevMode) {
4278 4279 4280 4281 4282 4283 4284 4285 4286 4287 4288 4289
        if (lppd->Flags & PD_RETURNDC) {
            lppd->hDC = CreateDCW(dbuf->pDriverPath, pbuf->pPrinterName, pbuf->pPortName, dm);
            if (!lppd->hDC)
                hr = E_FAIL;
        }
        else if (lppd->Flags & PD_RETURNIC) {
            lppd->hDC = CreateICW(dbuf->pDriverPath, pbuf->pPrinterName, pbuf->pPortName, dm);
            if (!lppd->hDC)
                hr = E_FAIL;
        }
    }
    else
4290 4291 4292 4293 4294 4295
        hr = E_FAIL;

    HeapFree(GetProcessHeap(), 0, pbuf);
    HeapFree(GetProcessHeap(), 0, dbuf);

    return hr;
4296
}