printdlg.c 130 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 32

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

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

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

48
WINE_DEFAULT_DEBUG_CHANNEL(commdlg);
49

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

54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85
/* 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;

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

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

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

151

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

164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210
/***********************************************************************
 * 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;
}


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

257 258 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

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

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

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

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

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

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

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

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

481 482
    p = strrchr( DeviceDriverName, '\\' );
    if (p) DeviceDriverName = p + 1;
483

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

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

496 497
    pDevNamesSpace = GlobalLock(*hmem);
    lpDevNames = (LPDEVNAMES) pDevNamesSpace;
498

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

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

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

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

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

528 529
    p = strrchrW( DeviceDriverName, '\\' );
    if (p) DeviceDriverName = p + 1;
530

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

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

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

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

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


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


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

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

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

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

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

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

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

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

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

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

705 706
	    if (nFromPage < lppd->nMinPage || nFromPage > lppd->nMaxPage ||
		nToPage < lppd->nMinPage || nToPage > lppd->nMaxPage) {
707 708
	        WCHAR resourcestr[256];
		WCHAR resultstr[256];
709
                DWORD_PTR args[2];
710
		LoadStringW(COMDLG32_hInstance, PD32_INVALID_PAGE_RANGE,
711
			    resourcestr, 255);
712 713 714 715 716 717
                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);
718
		LoadStringW(COMDLG32_hInstance, PD32_PRINT_TITLE,
719
			    resourcestr, 255);
720
		MessageBoxW(hDlg, resultstr, resourcestr,
721 722 723 724 725
			    MB_OK | MB_ICONWARNING);
		return FALSE;
	    }
	    lppd->nFromPage = nFromPage;
	    lppd->nToPage   = nToPage;
726
	    lppd->Flags |= PD_PAGENUMS;
727
	}
728 729
	else
	    lppd->Flags &= ~PD_PAGENUMS;
730

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

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

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

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

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

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

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

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

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

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

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

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

855 856
    /* 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 */
857
    Sel = 0;
858
    old_Sel = NrOfEntries;
859 860 861
    for (i = 0; i < NrOfEntries; i++) {
        if(SendDlgItemMessageA(hDlg, nIDComboBox, CB_GETITEMDATA, i, 0) ==
	   oldWord) {
862
	    old_Sel = i;
863 864
	    break;
	}
865 866
        if(SendDlgItemMessageA(hDlg, nIDComboBox, CB_GETITEMDATA, i, 0) == newWord)
	    Sel = i;
867
    }
868 869 870 871 872 873 874 875 876 877 878 879 880

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

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

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

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

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

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

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

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

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

935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952
    NrOfEntries = DeviceCapabilitiesW(PrinterName, PortName,
                                      fwCapability_Names, NULL, dm);
    if (NrOfEntries == 0)
         WARN("no Name Entries found!\n");
    else if (NrOfEntries < 0)
         return FALSE;

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

    Names = HeapAlloc(GetProcessHeap(),0, NrOfEntries*sizeof(WCHAR)*NamesSize);
    Words = HeapAlloc(GetProcessHeap(),0, NrOfEntries*sizeof(WORD));
    NrOfEntries = DeviceCapabilitiesW(PrinterName, PortName,
                                      fwCapability_Names, Names, dm);
    NrOfEntries = DeviceCapabilitiesW(PrinterName, PortName,
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) {
1496 1497 1498 1499
        ERR("no icon in resourcefile\n");
	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 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613
    if(PrintStructures->hCollateIcon == 0 ||
       PrintStructures->hNoCollateIcon == 0 ||
       PrintStructures->hPortraitIcon == 0 ||
       PrintStructures->hLandscapeIcon == 0) {
        ERR("no icon in resourcefile\n");
	COMDLG32_SetCommDlgExtendedError(CDERR_LOADRESFAILURE);
	EndDialog(hDlg, FALSE);
    }

    /*
     * if lppd->Flags PD_SHOWHELP is specified, a HELPMESGSTRING message
     * must be registered and the Help button must be shown.
     */
    if (lppd->Flags & PD_SHOWHELP) {
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 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809
	 }
	 break;

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

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

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

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

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

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

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

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

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

1937
    case cmb1: /* Printer Combobox in PRINT SETUP */
1938
	 /* FALLTHROUGH */
1939 1940
    case cmb4:                         /* Printer combobox */
         if (HIWORD(wParam)==CBN_SELCHANGE) {
1941 1942 1943 1944 1945 1946
	     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);
1947
	     PRINTDLG_ChangePrinterW(hDlg, PrinterName, PrintStructures);
1948
	     HeapFree(GetProcessHeap(),0,PrinterName);
1949 1950 1951 1952 1953
	 }
	 break;

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

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

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

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

2022 2023 2024
	if(PrintStructures->lpPrintDlg->Flags & PD_ENABLEPRINTHOOK)
	    res = PrintStructures->lpPrintDlg->lpfnPrintHook(
		hDlg, uMsg, wParam, (LPARAM)PrintStructures->lpPrintDlg
2025
	    );
2026
	return res;
2027
    }
2028

2029 2030
    if(PrintStructures->lpPrintDlg->Flags & PD_ENABLEPRINTHOOK) {
        res = PrintStructures->lpPrintDlg->lpfnPrintHook(hDlg,uMsg,wParam,
2031 2032 2033 2034 2035 2036
							 lParam);
	if(res) return res;
    }

    switch (uMsg) {
    case WM_COMMAND:
2037
        return PRINTDLG_WMCommandA(hDlg, wParam, PrintStructures);
2038 2039 2040 2041 2042 2043 2044 2045 2046

    case WM_DESTROY:
	DestroyIcon(PrintStructures->hCollateIcon);
	DestroyIcon(PrintStructures->hNoCollateIcon);
        DestroyIcon(PrintStructures->hPortraitIcon);
        DestroyIcon(PrintStructures->hLandscapeIcon);
	if(PrintStructures->hwndUpDown)
	    DestroyWindow(PrintStructures->hwndUpDown);
        return FALSE;
2047
    }
2048 2049 2050
    return res;
}

2051 2052
static INT_PTR CALLBACK PrintDlgProcW(HWND hDlg, UINT uMsg, WPARAM wParam,
                                      LPARAM lParam)
2053 2054
{
    PRINT_PTRW* PrintStructures;
2055
    INT_PTR res = FALSE;
2056 2057

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

2071 2072
	if(PrintStructures->lpPrintDlg->Flags & PD_ENABLEPRINTHOOK)
	    res = PrintStructures->lpPrintDlg->lpfnPrintHook(hDlg, uMsg, wParam, (LPARAM)PrintStructures->lpPrintDlg);
2073 2074
	return res;
    }
2075

2076 2077
    if(PrintStructures->lpPrintDlg->Flags & PD_ENABLEPRINTHOOK) {
        res = PrintStructures->lpPrintDlg->lpfnPrintHook(hDlg,uMsg,wParam, lParam);
2078 2079 2080 2081 2082
	if(res) return res;
    }

    switch (uMsg) {
    case WM_COMMAND:
2083
        return PRINTDLG_WMCommandW(hDlg, wParam, PrintStructures);
2084

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

/************************************************************
 *
 *      PRINTDLG_GetDlgTemplate
 *
 */
2102
static HGLOBAL PRINTDLG_GetDlgTemplateA(const PRINTDLGA *lppd)
2103
{
2104 2105
    HRSRC hResInfo;
    HGLOBAL hDlgTmpl;
2106 2107

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

2136
static HGLOBAL PRINTDLG_GetDlgTemplateW(const PRINTDLGW *lppd)
2137
{
2138 2139
    HRSRC hResInfo;
    HGLOBAL hDlgTmpl;
2140 2141
    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};
2142 2143 2144 2145

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

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

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

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

2236
BOOL WINAPI PrintDlgA(LPPRINTDLGA lppd)
2237 2238
{
    BOOL      bRet = FALSE;
2239 2240
    LPVOID    ptr;
    HINSTANCE hInst;
2241

2242 2243 2244 2245 2246 2247
    if (!lppd)
    {
        COMDLG32_SetCommDlgExtendedError(CDERR_INITIALIZATION);
        return FALSE;
    }

2248 2249
    if(TRACE_ON(commdlg)) {
        char flagstr[1000] = "";
2250
	const struct pd_flags *pflag = pd_flags;
2251 2252 2253 2254
	for( ; pflag->name; pflag++) {
	    if(lppd->Flags & pflag->flag)
	        strcat(flagstr, pflag->name);
	}
2255
	TRACE("(%p): hwndOwner = %p, hDevMode = %p, hDevNames = %p\n"
2256 2257
              "pp. %d-%d, min p %d, max p %d, copies %d, hinst %p\n"
              "flags %08x (%s)\n",
2258 2259 2260 2261 2262 2263 2264 2265
	      lppd, lppd->hwndOwner, lppd->hDevMode, lppd->hDevNames,
	      lppd->nFromPage, lppd->nToPage, lppd->nMinPage, lppd->nMaxPage,
	      lppd->nCopies, lppd->hInstance, lppd->Flags, flagstr);
    }

    if(lppd->lStructSize != sizeof(PRINTDLGA)) {
        WARN("structure size failure !!!\n");
	COMDLG32_SetCommDlgExtendedError(CDERR_STRUCTSIZE);
2266
	return FALSE;
2267 2268 2269 2270 2271 2272 2273 2274 2275 2276
    }

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

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

	/* and create & process the dialog .
	 * -1 is failure, 0 is broken hwnd, everything else is ok.
	 */
2340 2341
        hInst = COMDLG32_hInstance;
	if (lppd->Flags & (PD_ENABLESETUPTEMPLATE | PD_ENABLEPRINTTEMPLATE)) hInst = lppd->hInstance;
2342 2343 2344 2345 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
	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);

2378 2379
    TRACE("exit! (%d)\n", bRet);
    return bRet;
2380 2381 2382 2383
}

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

    if (!lppd)
    {
        COMDLG32_SetCommDlgExtendedError(CDERR_INITIALIZATION);
        return FALSE;
    }
2398 2399 2400

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

2414
    if(lppd->lStructSize != sizeof(PRINTDLGW)) {
2415 2416
        WARN("structure size failure !!!\n");
	COMDLG32_SetCommDlgExtendedError(CDERR_STRUCTSIZE);
2417
	return FALSE;
2418 2419 2420
    }

    if(lppd->Flags & PD_RETURNDEFAULT) {
2421 2422
        PRINTER_INFO_2W *pbuf;
	DRIVER_INFO_3W	*dbuf;
2423 2424 2425 2426 2427
	HANDLE hprn;
	DWORD needed;

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

2437
	GetPrinterW(hprn, 2, NULL, 0, &needed);
2438
	pbuf = HeapAlloc(GetProcessHeap(), 0, needed);
2439
	GetPrinterW(hprn, 2, (LPBYTE)pbuf, needed, &needed);
2440

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

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

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

2484
        PrintStructures = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY,
2485
				    sizeof(PRINT_PTRW));
2486
	PrintStructures->lpPrintDlg = lppd;
2487

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

	if(bRet) {
2498 2499 2500
	    DEVMODEW *lpdm = PrintStructures->lpDevMode, *lpdmReturn;
	    PRINTER_INFO_2W *pi = PrintStructures->lpPrinterInfo;
	    DRIVER_INFO_3W *di = PrintStructures->lpDriverInfo;
2501 2502 2503 2504 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

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

2545 2546
    TRACE("exit! (%d)\n", bRet);
    return bRet;
2547 2548 2549 2550 2551
}

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

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

2576 2577
static inline DWORD pagesetup_get_flags(const pagesetup_data *data)
{
2578
    return data->u.dlgw->Flags;
2579 2580
}

2581
static inline BOOL is_metric(const pagesetup_data *data)
2582
{
2583
    return pagesetup_get_flags(data) & PSD_INHUNDREDTHSOFMILLIMETERS;
2584 2585
}

2586
static inline LONG tenths_mm_to_size(const pagesetup_data *data, LONG size)
2587 2588 2589 2590 2591 2592 2593
{
    if (is_metric(data))
        return 10 * size;
    else
        return 10 * size * 100 / 254;
}

2594
static inline LONG thousandths_inch_to_size(const pagesetup_data *data, LONG size)
2595 2596 2597 2598 2599 2600 2601
{
    if (is_metric(data))
        return size * 254 / 100;
    else
        return size;
}

2602 2603 2604 2605 2606 2607
static WCHAR get_decimal_sep(void)
{
    static WCHAR sep;

    if(!sep)
    {
2608
        WCHAR buf[] = {'.', 0};
2609 2610 2611 2612 2613 2614
        GetLocaleInfoW(LOCALE_USER_DEFAULT, LOCALE_SDECIMAL, buf, sizeof(buf) / sizeof(buf[0]));
        sep = buf[0];
    }
    return sep;
}

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

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

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

    }
2638
}
2639

2640 2641 2642 2643 2644 2645 2646 2647
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;
}

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

2675
static void pagesetup_set_orientation(pagesetup_data *data, WORD orient)
2676
{
2677
    DEVMODEW *dm = GlobalLock(data->u.dlgw->hDevMode);
2678 2679 2680

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

2681 2682 2683 2684 2685 2686 2687 2688
    if(data->unicode)
        dm->u1.s1.dmOrientation = orient;
    else
    {
        DEVMODEA *dmA = (DEVMODEA *)dm;
        dmA->u1.s1.dmOrientation = orient;
    }
    GlobalUnlock(data->u.dlgw->hDevMode);
2689 2690
}

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

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

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

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

2751
typedef enum
2752
{
2753 2754 2755 2756
    devnames_driver_name,
    devnames_device_name,
    devnames_output_name
} devnames_name;
2757 2758


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

2771
static WCHAR *pagesetup_get_a_devname(const pagesetup_data *data, devnames_name which)
2772 2773 2774 2775
{
    DEVNAMES *dn;
    WCHAR *name;

2776 2777 2778 2779 2780 2781 2782 2783 2784 2785
    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);
2786 2787 2788
    return name;
}

2789
static WCHAR *pagesetup_get_drvname(const pagesetup_data *data)
2790
{
2791
    return pagesetup_get_a_devname(data, devnames_driver_name);
2792 2793
}

2794
static WCHAR *pagesetup_get_devname(const pagesetup_data *data)
2795
{
2796 2797
    return pagesetup_get_a_devname(data, devnames_device_name);
}
2798

2799 2800 2801
static WCHAR *pagesetup_get_portname(const pagesetup_data *data)
{
    return pagesetup_get_a_devname(data, devnames_output_name);
2802 2803
}

2804
static void pagesetup_release_a_devname(const pagesetup_data *data, WCHAR *name)
2805 2806 2807 2808
{
    HeapFree(GetProcessHeap(), 0, name);
}

2809
static void pagesetup_set_devnames(pagesetup_data *data, LPCWSTR drv, LPCWSTR devname, LPCWSTR port)
2810 2811 2812 2813 2814
{
    DEVNAMES *dn;
    WCHAR def[256];
    DWORD len = sizeof(DEVNAMES), drv_len, dev_len, port_len;

2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826
    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);
    }
2827 2828
    len += drv_len + dev_len + port_len;

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

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

2873
    GlobalUnlock(data->u.dlgw->hDevNames);
2874 2875
}

2876
static DEVMODEW *pagesetup_get_devmode(const pagesetup_data *data)
2877
{
2878 2879
    DEVMODEW *dm = GlobalLock(data->u.dlgw->hDevMode);
    DEVMODEW *ret;
2880

2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892
    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;
2893 2894
}

2895
static void pagesetup_release_devmode(const pagesetup_data *data, DEVMODEW *dm)
2896 2897 2898 2899
{
    HeapFree(GetProcessHeap(), 0, dm);
}

2900
static void pagesetup_set_devmode(pagesetup_data *data, DEVMODEW *dm)
2901
{
2902 2903 2904
    DEVMODEA *dmA = NULL;
    void *src, *dst;
    DWORD size;
2905

2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916
    if(data->unicode)
    {
        size = dm->dmSize + dm->dmDriverExtra;
        src = dm;
    }
    else
    {
        dmA = convert_to_devmodeA(dm);
        size = dmA->dmSize + dmA->dmDriverExtra;
        src = dmA;
    }
2917

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

2930 2931
static inline POINT *pagesetup_get_papersize_pt(const pagesetup_data *data)
{
2932
    return &data->u.dlgw->ptPaperSize;
2933 2934
}

2935 2936
static inline RECT *pagesetup_get_margin_rect(const pagesetup_data *data)
{
2937
    return &data->u.dlgw->rtMargin;
2938 2939
}

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

2956 2957 2958 2959
/* 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)
{
2960
    return (LPARAM)data->u.dlgw;
2961 2962
}

2963 2964 2965 2966 2967 2968 2969
static inline void swap_point(POINT *pt)
{
    LONG tmp = pt->x;
    pt->x = pt->y;
    pt->y = tmp;
}

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

2979 2980 2981
    dm       = pagesetup_get_devmode(data);
    devname  = pagesetup_get_devname(data);
    portname = pagesetup_get_portname(data);
2982

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

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

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

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

3005
    paperword = pagesetup_get_papersize(data);
3006

3007
    for (i = 0; i < num; i++)
3008
        if (words[i] == paperword)
3009 3010 3011 3012
            break;

    if (i == num)
    {
3013
        FIXME("Papersize %d not found in list?\n", paperword);
3014 3015 3016 3017
        goto end;
    }

    /* this is _10ths_ of a millimeter */
3018 3019
    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);
3020

3021
    if(pagesetup_get_orientation(data) == DMORIENT_LANDSCAPE)
3022 3023
        swap_point(pagesetup_get_papersize_pt(data));

3024 3025 3026 3027 3028
    retval = TRUE;

end:
    HeapFree(GetProcessHeap(), 0, words);
    HeapFree(GetProcessHeap(), 0, points);
3029 3030
    pagesetup_release_a_devname(data, portname);
    pagesetup_release_a_devname(data, devname);
3031
    pagesetup_release_devmode(data, dm);
3032

3033 3034
    return retval;
}
3035

3036
/**********************************************************************************************
3037
 * pagesetup_change_printer
3038 3039 3040 3041
 *
 * Redefines hDevMode and hDevNames HANDLES and initialises it.
 * 
 */
3042
static BOOL pagesetup_change_printer(LPWSTR name, pagesetup_data *data)
3043 3044 3045 3046 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
{
    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);

3079 3080
    pagesetup_set_devmode(data, dm);
    pagesetup_set_devnames(data, drv_info->pDriverPath, prn_info->pPrinterName,
3081 3082 3083 3084 3085 3086 3087 3088
                           prn_info->pPortName);

    retval = TRUE;
end:
    HeapFree(GetProcessHeap(), 0, dm);
    HeapFree(GetProcessHeap(), 0, prn_info);
    HeapFree(GetProcessHeap(), 0, drv_info);
    return retval;
3089 3090 3091
}

/****************************************************************************************
3092
 *  pagesetup_init_combos
3093
 *
3094
 *  Fills Printers, Paper and Source combos
3095
 *
3096
 */
3097
static void pagesetup_init_combos(HWND hDlg, pagesetup_data *data)
3098
{
3099 3100
    DEVMODEW *dm;
    LPWSTR devname, portname;
3101

3102 3103 3104
    dm       = pagesetup_get_devmode(data);
    devname  = pagesetup_get_devname(data);
    portname = pagesetup_get_portname(data);
3105 3106 3107 3108 3109

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

3110 3111
    pagesetup_release_a_devname(data, portname);
    pagesetup_release_a_devname(data, devname);
3112
    pagesetup_release_devmode(data, dm);
3113 3114
}

3115 3116 3117 3118 3119 3120 3121 3122

/****************************************************************************************
 *  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.
 */
3123
static void pagesetup_change_printer_dialog(HWND hDlg, pagesetup_data *data)
3124 3125 3126 3127 3128 3129 3130 3131 3132 3133
{
    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;

3134 3135 3136
    drvname = pagesetup_get_drvname(data);
    devname = pagesetup_get_devname(data);
    portname = pagesetup_get_portname(data);
3137 3138
    prnt.hDevNames = 0;
    PRINTDLG_CreateDevNamesW(&prnt.hDevNames, drvname, devname, portname);
3139 3140 3141
    pagesetup_release_a_devname(data, portname);
    pagesetup_release_a_devname(data, devname);
    pagesetup_release_a_devname(data, drvname);
3142

3143
    tmp_dm = pagesetup_get_devmode(data);
3144 3145 3146 3147
    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);
3148
    pagesetup_release_devmode(data, tmp_dm);
3149 3150 3151 3152 3153 3154

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

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

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

}

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

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

3205 3206 3207 3208 3209 3210 3211 3212 3213 3214 3215 3216
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;
}

3217
static void update_margin_edits(HWND hDlg, const pagesetup_data *data, WORD id)
3218 3219
{
    WCHAR str[100];
3220
    WORD idx;
3221

3222 3223 3224 3225
    for(idx = edt4; idx <= edt7; idx++)
    {
        if(id == 0 || id == idx)
        {
3226
            size2str(data, *element_from_margin_id(pagesetup_get_margin_rect(data), idx), str);
3227 3228 3229
            SetDlgItemTextW(hDlg, idx, str);
        }
    }
3230 3231
}

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

        if (GetDlgItemTextW(hDlg, id, buf, sizeof(buf) / sizeof(buf[0])) != 0)
        {
            WCHAR *end;
3245
            WCHAR decimal = get_decimal_sep();
3246 3247 3248 3249

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

3276
static void set_margin_groupbox_title(HWND hDlg, const pagesetup_data *data)
3277 3278 3279
{
    WCHAR title[256];

3280
    if(LoadStringW(COMDLG32_hInstance, is_metric(data) ? PD32_MARGINS_IN_MILLIMETERS : PD32_MARGINS_IN_INCHES,
3281 3282 3283 3284
                   title, sizeof(title)/sizeof(title[0])))
        SetDlgItemTextW(hDlg, grp4, title);
}

3285
static void pagesetup_update_orientation_buttons(HWND hDlg, const pagesetup_data *data)
3286
{
3287
    if (pagesetup_get_orientation(data) == DMORIENT_LANDSCAPE)
3288 3289 3290 3291 3292
        CheckRadioButton(hDlg, rad1, rad2, rad2);
    else
        CheckRadioButton(hDlg, rad1, rad2, rad1);
}

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

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

    /* Changing paper preview */
3327
    pagesetup_change_preview(data);
3328 3329 3330 3331 3332 3333 3334 3335 3336 3337 3338 3339 3340 3341 3342 3343

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

3344
/********************************************************************************
3345 3346
 * pagesetup_wm_command
 * process WM_COMMAND message for PageSetupDlg
3347 3348 3349 3350 3351 3352 3353 3354
 *
 * PARAMS
 *  hDlg 	[in] 	Main dialog HANDLE 
 *  wParam 	[in]	WM_COMMAND wParam
 *  lParam	[in]	WM_COMMAND lParam
 *  pda		[in/out] ptr to PageSetupDataA
 */

3355
static BOOL pagesetup_wm_command(HWND hDlg, WPARAM wParam, LPARAM lParam, pagesetup_data *data)
3356
{
3357 3358
    WORD msg = HIWORD(wParam);
    WORD id  = LOWORD(wParam);
3359

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

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

3371
    case psh3: /* Printer... */
3372
        pagesetup_change_printer_dialog(hDlg, data);
3373
        return TRUE;
3374 3375 3376

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

3436
/***********************************************************************
3437
 *           default_page_paint_hook
3438 3439
 * Default hook paint procedure that receives WM_PSD_* messages from the dialog box 
 * whenever the sample page is redrawn.
3440 3441 3442
 */
static UINT_PTR default_page_paint_hook(HWND hwndDlg, UINT uMsg, WPARAM wParam, LPARAM lParam,
                                        const pagesetup_data *data)
3443 3444 3445 3446 3447 3448 3449 3450 3451
{
    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 */
3452
    if (pagesetup_get_flags(data) & PSD_ENABLEPAGEPAINTHOOK)
3453
        if (pagesetup_get_hook(data, page_paint_hook)(hwndDlg, uMsg, wParam, lParam))
3454 3455 3456 3457 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
            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
 *
 */
3537 3538


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

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

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

3564 3565
    hdc = BeginPaint(hWnd, &ps);
    GetClientRect(hWnd, &rcClient);
3566
    
3567 3568
    scalx = rcClient.right  / (double)pagesetup_get_papersize_pt(data)->x;
    scaly = rcClient.bottom / (double)pagesetup_get_papersize_pt(data)->y;
3569
    rcMargin = rcClient;
3570

3571
    rcMargin.left   += pagesetup_get_margin_rect(data)->left   * scalx;
3572 3573
    rcMargin.top    += pagesetup_get_margin_rect(data)->top    * scaly;
    rcMargin.right  -= pagesetup_get_margin_rect(data)->right  * scalx;
3574
    rcMargin.bottom -= pagesetup_get_margin_rect(data)->bottom * scaly;
3575

3576 3577 3578 3579
    /* 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);

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

3610 3611
        DeleteObject(SelectObject(hdc, holdpen));
        DeleteObject(SelectObject(hdc, holdbrush));
3612

3613
        default_page_paint_hook(hWnd, WM_PSD_MARGINRECT, (WPARAM)hdc, (LPARAM)&rcMargin, data);
3614 3615

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

3625
        default_page_paint_hook(hWnd, WM_PSD_GREEKTEXTRECT, (WPARAM)hdc, (LPARAM)&rcMargin, data);
3626
    }
3627 3628 3629

    EndPaint(hWnd, &ps);
    return FALSE;
3630 3631
}

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

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

3672
    if (uMsg == WM_INITDIALOG) { /*Init dialog*/
3673 3674 3675
        data = (pagesetup_data *)lParam;
        data->hDlg = hDlg;

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

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

3708
        /* Set orientation radiobuttons properly */
3709
        pagesetup_update_orientation_buttons(hDlg, data);
3710

3711
	/* if orientation disabled */
3712
        if (pagesetup_get_flags(data) & PSD_DISABLEORIENTATION)
3713
        {
3714 3715 3716
	    EnableWindow(GetDlgItem(hDlg,rad1),FALSE);
	    EnableWindow(GetDlgItem(hDlg,rad2),FALSE);
	}
3717

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

3729
	/* if paper disabled */
3730
        if (pagesetup_get_flags(data) & PSD_DISABLEPAPER)
3731
        {
3732 3733 3734
	    EnableWindow(GetDlgItem(hDlg,cmb2),FALSE);
	    EnableWindow(GetDlgItem(hDlg,cmb3),FALSE);
	}
3735

3736
	/* filling combos: printer, paper, source. selecting current printer (from DEVMODEA) */
3737 3738 3739
        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? */
3740

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

3764 3765 3766 3767
static WCHAR *get_default_printer(void)
{
    WCHAR *name = NULL;
    DWORD len = 0;
3768

3769 3770 3771 3772 3773
    GetDefaultPrinterW(NULL, &len);
    if(len)
    {
        name = HeapAlloc(GetProcessHeap(), 0, len * sizeof(WCHAR));
        GetDefaultPrinterW(name, &len);
3774
    }
3775 3776
    return name;
}
3777

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

3801 3802 3803 3804 3805 3806 3807
static void *pagesetup_get_template(pagesetup_data *data)
{
    HRSRC res;
    HGLOBAL tmpl_handle;

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

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

3834 3835 3836 3837 3838 3839 3840 3841
    if(!pagesetup_get_dlg_struct(data))
    {
        COMDLG32_SetCommDlgExtendedError(CDERR_INITIALIZATION);
        return FALSE;
    }

    pagesetup_dump_dlg_struct(data);

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

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

3877 3878
    if (pagesetup_get_flags(data) & PSD_RETURNDEFAULT)
    {
3879
        pagesetup_update_papersize(data);
3880
        return TRUE;
3881
    }
3882

3883
    tmpl = pagesetup_get_template(data);
3884

3885 3886
    ret = DialogBoxIndirectParamW(data->u.dlgw->hInstance, tmpl,
                                  data->u.dlgw->hwndOwner,
3887 3888 3889
                                  pagesetup_dlg_proc, (LPARAM)data) > 0;
    return ret;
}
3890

3891 3892 3893 3894 3895 3896 3897 3898 3899 3900 3901 3902 3903 3904 3905 3906 3907 3908 3909 3910 3911 3912 3913
/***********************************************************************
 *            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;

3914 3915
    data.unicode = FALSE;
    data.u.dlga  = setupdlg;
3916 3917

    return pagesetup_common(&data);
3918
}
3919

3920
/***********************************************************************
3921
 *            PageSetupDlgW  (COMDLG32.@)
3922 3923
 *
 * See PageSetupDlgA.
3924
 */
3925 3926 3927
BOOL WINAPI PageSetupDlgW(LPPAGESETUPDLGW setupdlg)
{
    pagesetup_data data;
3928

3929 3930
    data.unicode = TRUE;
    data.u.dlgw  = setupdlg;
3931

3932
    return pagesetup_common(&data);
3933
}
3934

3935
/***********************************************************************
3936
 * PrintDlgExA (COMDLG32.@)
3937 3938 3939
 *
 * See PrintDlgExW.
 *
3940 3941 3942
 * BUGS
 *   Only a Stub
 *
3943
 */
3944
HRESULT WINAPI PrintDlgExA(LPPRINTDLGEXA lppd)
3945
{
3946 3947 3948 3949 3950
    PRINTER_INFO_2A *pbuf;
    DRIVER_INFO_3A *dbuf;
    DEVMODEA *dm;
    HRESULT hr = S_OK;
    HANDLE hprn;
3951

3952
    if ((lppd == NULL) || (lppd->lStructSize != sizeof(PRINTDLGEXA)))
3953 3954
        return E_INVALIDARG;

3955
    if (!IsWindow(lppd->hwndOwner))
3956
        return E_HANDLE;
3957

3958 3959 3960 3961 3962 3963 3964 3965 3966 3967 3968 3969 3970 3971
    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;
    }

3972 3973 3974 3975 3976 3977 3978 3979 3980 3981 3982 3983 3984 3985 3986
    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;
        }

3987 3988
        pbuf = get_printer_infoA(hprn);
        if (!pbuf)
3989 3990 3991 3992 3993
        {
            ClosePrinter(hprn);
            return E_FAIL;
        }

3994 3995
        dbuf = get_driver_infoA(hprn);
        if (!dbuf)
3996 3997 3998 3999 4000 4001
        {
            HeapFree(GetProcessHeap(), 0, pbuf);
            COMDLG32_SetCommDlgExtendedError(PDERR_RETDEFFAILURE);
            ClosePrinter(hprn);
            return E_FAIL;
        }
4002 4003 4004 4005 4006 4007
        dm = pbuf->pDevMode;
    }
    else
    {
        FIXME("(%p) dialog not implemented\n", lppd);
        return E_NOTIMPL;
4008

4009 4010
    }

4011 4012 4013 4014 4015 4016 4017
    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);
4018 4019 4020 4021 4022 4023 4024 4025 4026 4027 4028 4029 4030
    if (!hr && lppd->hDevMode) {
        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
4031 4032 4033 4034 4035 4036
        hr = E_FAIL;

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

    return hr;
4037
}
4038

4039
/***********************************************************************
4040
 * PrintDlgExW (COMDLG32.@)
4041
 *
4042
 * Display the property sheet style PRINT dialog box
4043 4044 4045 4046 4047 4048 4049 4050 4051 4052 4053 4054 4055
 *  
 * 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.
 *  
4056 4057 4058 4059 4060 4061
 * 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
4062
 *   Not fully implemented
4063
 *
4064
 */
4065
HRESULT WINAPI PrintDlgExW(LPPRINTDLGEXW lppd)
4066
{
4067 4068 4069 4070 4071
    PRINTER_INFO_2W *pbuf;
    DRIVER_INFO_3W *dbuf;
    DEVMODEW *dm;
    HRESULT hr = S_OK;
    HANDLE hprn;
4072 4073 4074 4075 4076 4077 4078 4079 4080

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

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

4081 4082 4083 4084 4085 4086 4087 4088 4089 4090 4091 4092 4093 4094
    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;
    }

4095 4096 4097 4098 4099 4100 4101 4102 4103 4104 4105 4106 4107
    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;
        }

4108 4109 4110
        pbuf = get_printer_infoW(hprn);
        if (!pbuf)
        {
4111 4112 4113 4114
            ClosePrinter(hprn);
            return E_FAIL;
        }

4115 4116 4117
        dbuf = get_driver_infoW(hprn);
        if (!dbuf)
        {
4118 4119 4120 4121 4122
            HeapFree(GetProcessHeap(), 0, pbuf);
            COMDLG32_SetCommDlgExtendedError(PDERR_RETDEFFAILURE);
            ClosePrinter(hprn);
            return E_FAIL;
        }
4123 4124 4125 4126 4127 4128
        dm = pbuf->pDevMode;
    }
    else
    {
        FIXME("(%p) dialog not implemented\n", lppd);
        return E_NOTIMPL;
4129 4130 4131

    }

4132 4133 4134 4135 4136 4137 4138
    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);
4139 4140 4141 4142 4143 4144 4145 4146 4147 4148 4149 4150 4151
    if (!hr && lppd->hDevMode) {
        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
4152 4153 4154 4155 4156 4157
        hr = E_FAIL;

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

    return hr;
4158
}