info.c 281 KB
Newer Older
1
/*
2
 * WINSPOOL functions
3
 *
4 5
 * Copyright 1996 John Harvey
 * Copyright 1998 Andreas Mohr
6 7
 * Copyright 1999 Klaas van Gend
 * Copyright 1999, 2000 Huw D M Davies
8
 * Copyright 2001 Marcus Meissner
9
 * Copyright 2005-2010 Detlef Riekenberg
10
 * Copyright 2010 Vitaly Perov
11 12 13 14 15 16 17 18 19 20 21 22 23
 *
 * 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
24
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
25 26
 */

27
#include "config.h"
28
#include "wine/port.h"
29

30
#include <stdarg.h>
31
#include <stdio.h>
32 33 34
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
35
#include <stddef.h>
36
#include <errno.h>
37 38 39
#ifdef HAVE_SYS_WAIT_H
#include <sys/wait.h>
#endif
40 41 42
#ifdef HAVE_UNISTD_H
# include <unistd.h>
#endif
43
#include <signal.h>
44
#ifdef HAVE_CUPS_CUPS_H
45 46
# include <cups/cups.h>
#endif
47 48 49
#ifdef HAVE_CUPS_PPD_H
# include <cups/ppd.h>
#endif
50

51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106
#ifdef HAVE_APPLICATIONSERVICES_APPLICATIONSERVICES_H
#define GetCurrentProcess GetCurrentProcess_Mac
#define GetCurrentThread GetCurrentThread_Mac
#define LoadResource LoadResource_Mac
#define AnimatePalette AnimatePalette_Mac
#define EqualRgn EqualRgn_Mac
#define FillRgn FillRgn_Mac
#define FrameRgn FrameRgn_Mac
#define GetPixel GetPixel_Mac
#define InvertRgn InvertRgn_Mac
#define LineTo LineTo_Mac
#define OffsetRgn OffsetRgn_Mac
#define PaintRgn PaintRgn_Mac
#define Polygon Polygon_Mac
#define ResizePalette ResizePalette_Mac
#define SetRectRgn SetRectRgn_Mac
#define EqualRect EqualRect_Mac
#define FillRect FillRect_Mac
#define FrameRect FrameRect_Mac
#define GetCursor GetCursor_Mac
#define InvertRect InvertRect_Mac
#define OffsetRect OffsetRect_Mac
#define PtInRect PtInRect_Mac
#define SetCursor SetCursor_Mac
#define SetRect SetRect_Mac
#define ShowCursor ShowCursor_Mac
#define UnionRect UnionRect_Mac
#include <ApplicationServices/ApplicationServices.h>
#undef GetCurrentProcess
#undef GetCurrentThread
#undef LoadResource
#undef AnimatePalette
#undef EqualRgn
#undef FillRgn
#undef FrameRgn
#undef GetPixel
#undef InvertRgn
#undef LineTo
#undef OffsetRgn
#undef PaintRgn
#undef Polygon
#undef ResizePalette
#undef SetRectRgn
#undef EqualRect
#undef FillRect
#undef FrameRect
#undef GetCursor
#undef InvertRect
#undef OffsetRect
#undef PtInRect
#undef SetCursor
#undef SetRect
#undef ShowCursor
#undef UnionRect
#endif

107 108 109
#define NONAMELESSSTRUCT
#define NONAMELESSUNION

110
#include "windef.h"
111
#include "winbase.h"
112
#include "winuser.h"
113 114
#include "winerror.h"
#include "winreg.h"
115 116
#include "wingdi.h"
#include "winspool.h"
117
#include "winternl.h"
118
#include "wine/windef16.h"
119
#include "wine/unicode.h"
120
#include "wine/debug.h"
121
#include "wine/list.h"
122
#include "wine/heap.h"
123
#include "winnls.h"
124

125
#include "ddk/winsplp.h"
126 127
#include "wspool.h"

128
WINE_DEFAULT_DEBUG_CHANNEL(winspool);
129

130 131
/* ############################### */

132 133 134 135 136
static CRITICAL_SECTION printer_handles_cs;
static CRITICAL_SECTION_DEBUG printer_handles_cs_debug = 
{
    0, 0, &printer_handles_cs,
    { &printer_handles_cs_debug.ProcessLocksList, &printer_handles_cs_debug.ProcessLocksList },
137
      0, 0, { (DWORD_PTR)(__FILE__ ": printer_handles_cs") }
138 139 140
};
static CRITICAL_SECTION printer_handles_cs = { &printer_handles_cs_debug, -1, 0, 0, 0, 0 };

141 142
/* ############################### */

143 144 145 146 147
typedef struct {
    DWORD job_id;
    HANDLE hf;
} started_doc_t;

148
typedef struct {
149
    struct list jobs;
150
    LONG ref;
151
} jobqueue_t;
152 153 154

typedef struct {
    LPWSTR name;
155
    LPWSTR printername;
156
    HANDLE backend_printer;
157
    jobqueue_t *queue;
158
    started_doc_t *doc;
159
    DEVMODEW *devmode;
160 161
} opened_printer_t;

162 163 164 165
typedef struct {
    struct list entry;
    DWORD job_id;
    WCHAR *filename;
166
    WCHAR *portname;
167
    WCHAR *document_title;
168
    WCHAR *printer_name;
169
    LPDEVMODEW devmode;
170 171
} job_t;

172 173 174 175

typedef struct {
    LPCWSTR  envname;
    LPCWSTR  subdir;
176 177 178
    DWORD    driverversion;
    LPCWSTR  versionregpath;
    LPCWSTR  versionsubdir;
179 180 181 182
} printenv_t;

/* ############################### */

183
static opened_printer_t **printer_handles;
184
static UINT nb_printer_handles;
Kevin Koltzau's avatar
Kevin Koltzau committed
185
static LONG next_job_id = 1;
186

187
static DWORD (WINAPI *GDI_CallDeviceCapabilities16)( LPCSTR lpszDevice, LPCSTR lpszPort,
188 189
                                                     WORD fwCapability, LPSTR lpszOutput,
                                                     LPDEVMODEA lpdm );
190
static INT (WINAPI *GDI_CallExtDeviceMode16)( HWND hwnd, LPDEVMODEA lpdmOutput,
191 192 193 194
                                              LPSTR lpszDevice, LPSTR lpszPort,
                                              LPDEVMODEA lpdmInput, LPSTR lpszProfile,
                                              DWORD fwMode );

195 196 197 198 199
static const WCHAR DriversW[] = { 'S','y','s','t','e','m','\\',
                                  'C','u', 'r','r','e','n','t','C','o','n','t','r','o','l','S','e','t','\\',
                                  'c','o','n','t','r','o','l','\\',
                                  'P','r','i','n','t','\\',
                                  'E','n','v','i','r','o','n','m','e','n','t','s','\\',
200
                                  '%','s','\\','D','r','i','v','e','r','s','%','s',0 };
201

202 203 204 205 206 207
static const WCHAR PrintersW[] = {'S','y','s','t','e','m','\\',
                                  'C','u', 'r','r','e','n','t','C','o','n','t','r','o','l','S','e','t','\\',
                                  'C','o','n','t','r','o','l','\\',
                                  'P','r','i','n','t','\\',
                                  'P','r','i','n','t','e','r','s',0};

208 209 210 211 212 213 214 215 216 217 218 219
static const WCHAR user_default_reg_key[] = { 'S','o','f','t','w','a','r','e','\\',
                                              'M','i','c','r','o','s','o','f','t','\\',
                                              'W','i','n','d','o','w','s',' ','N','T','\\',
                                              'C','u','r','r','e','n','t','V','e','r','s','i','o','n','\\',
                                              'W','i','n','d','o','w','s',0};

static const WCHAR user_printers_reg_key[] = { 'S','o','f','t','w','a','r','e','\\',
                                               'M','i','c','r','o','s','o','f','t','\\',
                                               'W','i','n','d','o','w','s',' ','N','T','\\',
                                               'C','u','r','r','e','n','t','V','e','r','s','i','o','n','\\',
                                               'D','e','v','i','c','e','s',0};

220 221 222 223 224 225
static const WCHAR WinNT_CV_PrinterPortsW[] = { 'S','o','f','t','w','a','r','e','\\',
                                                'M','i','c','r','o','s','o','f','t','\\',
                                                'W','i','n','d','o','w','s',' ','N','T','\\',
                                                'C','u','r','r','e','n','t','V','e','r','s','i','o','n','\\',
                                                'P','r','i','n','t','e','r','P','o','r','t','s',0};

226
static       WCHAR envname_win40W[] = {'W','i','n','d','o','w','s',' ','4','.','0',0};
227
static const WCHAR envname_x64W[] =   {'W','i','n','d','o','w','s',' ','x','6','4',0};
228
static       WCHAR envname_x86W[] =   {'W','i','n','d','o','w','s',' ','N','T',' ','x','8','6',0};
229
static const WCHAR subdir_win40W[] = {'w','i','n','4','0',0};
230
static const WCHAR subdir_x64W[] =   {'x','6','4',0};
231
static const WCHAR subdir_x86W[] =   {'w','3','2','x','8','6',0};
232 233
static const WCHAR Version0_RegPathW[] = {'\\','V','e','r','s','i','o','n','-','0',0};
static const WCHAR Version0_SubdirW[] = {'\\','0',0};
234 235
static const WCHAR Version3_RegPathW[] = {'\\','V','e','r','s','i','o','n','-','3',0};
static const WCHAR Version3_SubdirW[] = {'\\','3',0};
236

237
static const WCHAR AttributesW[] = {'A','t','t','r','i','b','u','t','e','s',0};
238
static const WCHAR backslashW[] = {'\\',0};
239
static const WCHAR Configuration_FileW[] = {'C','o','n','f','i','g','u','r','a','t',
240
				      'i','o','n',' ','F','i','l','e',0};
241 242
static const WCHAR DatatypeW[] = {'D','a','t','a','t','y','p','e',0};
static const WCHAR Data_FileW[] = {'D','a','t','a',' ','F','i','l','e',0};
243
static const WCHAR Default_DevModeW[] = {'D','e','f','a','u','l','t',' ','D','e','v','M','o','d','e',0};
244
static const WCHAR Default_PriorityW[] = {'D','e','f','a','u','l','t',' ','P','r','i','o','r','i','t','y',0};
245
static const WCHAR Dependent_FilesW[] = {'D','e','p','e','n','d','e','n','t',' ','F','i','l','e','s',0};
246
static const WCHAR DescriptionW[] = {'D','e','s','c','r','i','p','t','i','o','n',0};
247
static const WCHAR dnsTimeoutW[] = {'d','n','s','T','i','m','e','o','u','t',0};
248
static const WCHAR DriverW[] = {'D','r','i','v','e','r',0};
249
static const WCHAR HardwareIDW[] = {'H','a','r','d','w','a','r','e','I','D',0};
250 251
static const WCHAR Help_FileW[] = {'H','e','l','p',' ','F','i','l','e',0};
static const WCHAR LocationW[] = {'L','o','c','a','t','i','o','n',0};
252
static const WCHAR ManufacturerW[] = {'M','a','n','u','f','a','c','t','u','r','e','r',0};
253 254
static const WCHAR MonitorW[] = {'M','o','n','i','t','o','r',0};
static const WCHAR NameW[] = {'N','a','m','e',0};
255
static const WCHAR ObjectGUIDW[] = {'O','b','j','e','c','t','G','U','I','D',0};
256
static const WCHAR OEM_UrlW[] = {'O','E','M',' ','U','r','l',0};
257 258
static const WCHAR ParametersW[] = {'P','a','r','a','m','e','t','e','r','s',0};
static const WCHAR PortW[] = {'P','o','r','t',0};
259 260 261 262
static const WCHAR Previous_NamesW[] = {'P','r','e','v','i','o','u','s',' ','N','a','m','e','s',0};
static const WCHAR Print_ProcessorW[] = {'P','r','i','n','t',' ','P','r','o','c','e','s','s','o','r',0};
static const WCHAR Printer_DriverW[] = {'P','r','i','n','t','e','r',' ','D','r','i','v','e','r',0};
static const WCHAR PrinterDriverDataW[] = {'P','r','i','n','t','e','r','D','r','i','v','e','r','D','a','t','a',0};
263
static const WCHAR PriorityW[] = {'P','r','i','o','r','i','t','y',0};
264 265
static const WCHAR ProviderW[] = {'P','r','o','v','i','d','e','r',0};
static const WCHAR Separator_FileW[] = {'S','e','p','a','r','a','t','o','r',' ','F','i','l','e',0};
266
static const WCHAR Share_NameW[] = {'S','h','a','r','e',' ','N','a','m','e',0};
267 268
static const WCHAR StartTimeW[] = {'S','t','a','r','t','T','i','m','e',0};
static const WCHAR StatusW[] = {'S','t','a','t','u','s',0};
269
static const WCHAR txTimeoutW[] = {'t','x','T','i','m','e','o','u','t',0};
270
static const WCHAR UntilTimeW[] = {'U','n','t','i','l','T','i','m','e',0};
271
static       WCHAR WinPrintW[] = {'W','i','n','P','r','i','n','t',0};
272 273
static const WCHAR deviceW[]  = {'d','e','v','i','c','e',0};
static const WCHAR windowsW[] = {'w','i','n','d','o','w','s',0};
274 275 276
static       WCHAR rawW[] = {'R','A','W',0};
static       WCHAR driver_9x[] = {'w','i','n','e','p','s','1','6','.','d','r','v',0};
static       WCHAR driver_nt[] = {'w','i','n','e','p','s','.','d','r','v',0};
277 278
static const WCHAR timeout_15_45[] = {',','1','5',',','4','5',0};
static const WCHAR commaW[] = {',',0};
279
static       WCHAR emptyStringW[] = {0};
280 281

static const WCHAR May_Delete_Value[] = {'W','i','n','e','M','a','y','D','e','l','e','t','e','M','e',0};
282

283 284 285 286
static const WCHAR CUPS_Port[] = {'C','U','P','S',':',0};
static const WCHAR FILE_Port[] = {'F','I','L','E',':',0};
static const WCHAR LPR_Port[] = {'L','P','R',':',0};

287 288 289
static const WCHAR default_doc_title[] = {'L','o','c','a','l',' ','D','o','w','n','l','e','v','e','l',' ',
                                          'D','o','c','u','m','e','n','t',0};

290 291 292
static const WCHAR PPD_Overrides[] = {'P','P','D',' ','O','v','e','r','r','i','d','e','s',0};
static const WCHAR DefaultPageSize[] = {'D','e','f','a','u','l','t','P','a','g','e','S','i','z','e',0};

293 294 295 296
static const DWORD di_sizeof[] = {0, sizeof(DRIVER_INFO_1W), sizeof(DRIVER_INFO_2W),
                                     sizeof(DRIVER_INFO_3W), sizeof(DRIVER_INFO_4W),
                                     sizeof(DRIVER_INFO_5W), sizeof(DRIVER_INFO_6W),
                                  0, sizeof(DRIVER_INFO_8W)};
297

298 299 300 301 302 303 304

static const DWORD pi_sizeof[] = {0, sizeof(PRINTER_INFO_1W), sizeof(PRINTER_INFO_2W),
                                     sizeof(PRINTER_INFO_3),  sizeof(PRINTER_INFO_4W),
                                     sizeof(PRINTER_INFO_5W), sizeof(PRINTER_INFO_6),
                                     sizeof(PRINTER_INFO_7W), sizeof(PRINTER_INFO_8W),
                                     sizeof(PRINTER_INFO_9W)};

305 306 307 308 309 310
static const printenv_t env_x64 = {envname_x64W, subdir_x64W, 3, Version3_RegPathW, Version3_SubdirW};
static const printenv_t env_x86 = {envname_x86W, subdir_x86W, 3, Version3_RegPathW, Version3_SubdirW};
static const printenv_t env_win40 = {envname_win40W, subdir_win40W, 0, Version0_RegPathW, Version0_SubdirW};

static const printenv_t * const all_printenv[] = {&env_x86, &env_x64, &env_win40};

311 312 313 314 315 316 317 318 319 320 321
/******************************************************************
 *  validate the user-supplied printing-environment [internal]
 *
 * PARAMS
 *  env  [I] PTR to Environment-String or NULL
 *
 * RETURNS
 *  Failure:  NULL
 *  Success:  PTR to printenv_t
 *
 * NOTES
322
 *  An empty string is handled the same way as NULL.
323
 *  SetLastError(ERROR_INVALID_ENVIRONMENT) is called on Failure
324 325 326 327 328 329 330 331 332
 *  
 */

static const  printenv_t * validate_envW(LPCWSTR env)
{
    const printenv_t *result = NULL;
    unsigned int i;

    TRACE("testing %s\n", debugstr_w(env));
333
    if (env && env[0])
334
    {
335
        for (i = 0; i < ARRAY_SIZE(all_printenv); i++)
336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359
        {
            if (lstrcmpiW(env, all_printenv[i]->envname) == 0)
            {
                result = all_printenv[i];
                break;
            }
        }

        if (result == NULL) {
            FIXME("unsupported Environment: %s\n", debugstr_w(env));
            SetLastError(ERROR_INVALID_ENVIRONMENT);
        }
        /* on win9x, only "Windows 4.0" is allowed, but we ignore this */
    }
    else
    {
        result = (GetVersion() & 0x80000000) ? &env_win40 : &env_x86;
    }
    TRACE("using %p: %s\n", result, debugstr_w(result ? result->envname : NULL));

    return result;
}


360 361 362 363 364 365 366 367 368 369 370 371 372 373
/* RtlCreateUnicodeStringFromAsciiz will return an empty string in the buffer
   if passed a NULL string. This returns NULLs to the result. 
*/
static inline PWSTR asciitounicode( UNICODE_STRING * usBufferPtr, LPCSTR src )
{
    if ( (src) )
    {
        RtlCreateUnicodeStringFromAsciiz(usBufferPtr, src);
        return usBufferPtr->Buffer;
    }
    usBufferPtr->Buffer = NULL; /* so that RtlFreeUnicodeString won't barf */
    return NULL;
}
            
374
static LPWSTR strdupW(LPCWSTR p)
375 376 377 378 379 380 381 382 383 384 385
{
    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;
}

386 387 388 389 390 391 392 393 394 395 396 397
static LPSTR strdupWtoA( LPCWSTR str )
{
    LPSTR ret;
    INT len;

    if (!str) return NULL;
    len = WideCharToMultiByte( CP_ACP, 0, str, -1, NULL, 0, NULL, NULL );
    ret = HeapAlloc( GetProcessHeap(), 0, len );
    if(ret) WideCharToMultiByte( CP_ACP, 0, str, -1, ret, len, NULL, NULL );
    return ret;
}

398 399 400 401 402 403 404 405 406 407
static DEVMODEW *dup_devmode( const DEVMODEW *dm )
{
    DEVMODEW *ret;

    if (!dm) return NULL;
    ret = HeapAlloc( GetProcessHeap(), 0, dm->dmSize + dm->dmDriverExtra );
    if (ret) memcpy( ret, dm, dm->dmSize + dm->dmDriverExtra );
    return ret;
}

408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446
/***********************************************************
 * DEVMODEdupWtoA
 * Creates an ansi copy of supplied devmode
 */
static DEVMODEA *DEVMODEdupWtoA( const DEVMODEW *dmW )
{
    LPDEVMODEA dmA;
    DWORD size;

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

    dmA = HeapAlloc( GetProcessHeap(), HEAP_ZERO_MEMORY, 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;
}

447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501
static void packed_string_WtoA( WCHAR *strW )
{
    DWORD len = strlenW( strW ), size = (len + 1) * sizeof(WCHAR), ret;
    char *str;

    if (!len) return;
    str = heap_alloc( size );
    ret = WideCharToMultiByte( CP_ACP, 0, strW, len, str, size - 1, NULL, NULL );
    memcpy( strW, str, ret );
    memset( (BYTE *)strW + ret, 0, size - ret );
    heap_free( str );
}

/*********************************************************************
 *                 packed_struct_WtoA
 *
 * Convert a packed struct from W to A overwriting the unicode strings
 * with their ansi equivalents.
 */
static void packed_struct_WtoA( BYTE *data, const DWORD *string_info )
{
    WCHAR *strW;

    string_info++; /* sizeof */
    while (*string_info != ~0u)
    {
        strW = *(WCHAR **)(data + *string_info);
        if (strW) packed_string_WtoA( strW );
        string_info++;
    }
}

static inline const DWORD *form_string_info( DWORD level )
{
    static const DWORD info_1[] =
    {
        sizeof( FORM_INFO_1W ),
        FIELD_OFFSET( FORM_INFO_1W, pName ),
        ~0u
    };
    static const DWORD info_2[] =
    {
        sizeof( FORM_INFO_2W ),
        FIELD_OFFSET( FORM_INFO_2W, pName ),
        FIELD_OFFSET( FORM_INFO_2W, pMuiDll ),
        FIELD_OFFSET( FORM_INFO_2W, pDisplayName ),
        ~0u
    };

    if (level == 1) return info_1;
    if (level == 2) return info_2;

    SetLastError( ERROR_INVALID_LEVEL );
    return NULL;
}
502

503 504 505 506 507 508 509 510 511
/******************************************************************
 * verify, that the filename is a local file
 *
 */
static inline BOOL is_local_file(LPWSTR name)
{
    return (name[0] && (name[1] == ':') && (name[2] == '\\'));
}

512 513
/* ################################ */

514 515 516 517 518 519 520 521 522 523 524 525
static int multi_sz_lenA(const char *str)
{
    const char *ptr = str;
    if(!str) return 0;
    do
    {
        ptr += lstrlenA(ptr) + 1;
    } while(*ptr);

    return ptr - str + 1;
}

526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555
/*****************************************************************************
 *    get_dword_from_reg
 *
 * Return DWORD associated with name from hkey.
 */
static DWORD get_dword_from_reg( HKEY hkey, const WCHAR *name )
{
    DWORD sz = sizeof(DWORD), type, value = 0;
    LONG ret;

    ret = RegQueryValueExW( hkey, name, 0, &type, (LPBYTE)&value, &sz );

    if (ret != ERROR_SUCCESS)
    {
        WARN( "Got ret = %d on name %s\n", ret, debugstr_w(name) );
        return 0;
    }
    if (type != REG_DWORD)
    {
        ERR( "Got type %d\n", type );
        return 0;
    }
    return value;
}

static inline DWORD set_reg_DWORD( HKEY hkey, const WCHAR *keyname, const DWORD value )
{
    return RegSetValueExW( hkey, keyname, 0, REG_DWORD, (const BYTE*)&value, sizeof(value) );
}

556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584
/******************************************************************
 *  get_opened_printer
 *  Get the pointer to the opened printer referred by the handle
 */
static opened_printer_t *get_opened_printer(HANDLE hprn)
{
    UINT_PTR idx = (UINT_PTR)hprn;
    opened_printer_t *ret = NULL;

    EnterCriticalSection(&printer_handles_cs);

    if ((idx > 0) && (idx <= nb_printer_handles)) {
        ret = printer_handles[idx - 1];
    }
    LeaveCriticalSection(&printer_handles_cs);
    return ret;
}

/******************************************************************
 *  get_opened_printer_name
 *  Get the pointer to the opened printer name referred by the handle
 */
static LPCWSTR get_opened_printer_name(HANDLE hprn)
{
    opened_printer_t *printer = get_opened_printer(hprn);
    if(!printer) return NULL;
    return printer->name;
}

585 586 587 588 589 590 591
static HANDLE get_backend_handle( HANDLE hprn )
{
    opened_printer_t *printer = get_opened_printer( hprn );
    if (!printer) return NULL;
    return printer->backend_printer;
}

592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618
static DWORD open_printer_reg_key( const WCHAR *name, HKEY *key )
{
    HKEY printers;
    DWORD err;

    *key = NULL;
    err = RegCreateKeyW( HKEY_LOCAL_MACHINE, PrintersW, &printers );
    if (err) return err;

    err = RegOpenKeyW( printers, name, key );
    if (err) err = ERROR_INVALID_PRINTER_NAME;
    RegCloseKey( printers );
    return err;
}

/******************************************************************
 *  WINSPOOL_GetOpenedPrinterRegKey
 *
 */
static DWORD WINSPOOL_GetOpenedPrinterRegKey(HANDLE hPrinter, HKEY *phkey)
{
    LPCWSTR name = get_opened_printer_name(hPrinter);

    if(!name) return ERROR_INVALID_HANDLE;
    return open_printer_reg_key( name, phkey );
}

619 620 621 622 623 624 625 626 627 628
static void set_default_printer(const char *devname, const char *name)
{
    char *buf = HeapAlloc(GetProcessHeap(), 0, strlen(name)+strlen(devname)+strlen(",WINEPS.DRV,LPR:")+1);
    HKEY hkey;

    sprintf(buf, "%s,WINEPS.DRV,LPR:%s", devname, name);
    if (!RegCreateKeyW(HKEY_CURRENT_USER, user_default_reg_key, &hkey))
    {
        RegSetValueExA(hkey, "Device", 0, REG_SZ, (BYTE *)buf, strlen(buf) + 1);
        RegCloseKey(hkey);
629
    }
630
    HeapFree(GetProcessHeap(), 0, buf);
631
}
632

633
static BOOL add_printer_driver(const WCHAR *name, WCHAR *ppd)
634
{
635
    DRIVER_INFO_3W di3;
636 637
    unsigned int i;
    BOOL res;
638 639 640

    ZeroMemory(&di3, sizeof(DRIVER_INFO_3W));
    di3.cVersion         = 3;
641
    di3.pName            = (WCHAR*)name;
642
    di3.pDriverPath      = driver_nt;
643
    di3.pDataFile        = ppd;
644 645 646
    di3.pConfigFile      = driver_nt;
    di3.pDefaultDataType = rawW;

647
    for (i = 0; i < ARRAY_SIZE(all_printenv); i++)
648
    {
649 650
        di3.pEnvironment = (WCHAR *) all_printenv[i]->envname;
        if (all_printenv[i]->envname == envname_win40W)
651
        {
652 653 654 655 656 657 658
            /* We use wineps16.drv as driver for 16 bit */
            di3.pDriverPath      = driver_9x;
            di3.pConfigFile      = driver_9x;
        }
        res = AddPrinterDriverExW( NULL, 3, (LPBYTE)&di3, APD_COPY_NEW_FILES | APD_COPY_FROM_DIRECTORY );
        TRACE("got %d and %d for %s (%s)\n", res, GetLastError(), debugstr_w(name), debugstr_w(di3.pEnvironment));

659
        if (!res && (GetLastError() != ERROR_PRINTER_DRIVER_ALREADY_INSTALLED))
660 661 662 663
        {
            ERR("failed with %u for %s (%s) %s\n", GetLastError(), debugstr_w(name),
                debugstr_w(di3.pEnvironment), debugstr_w(di3.pDriverPath));
                return FALSE;
664
        }
665
    }
666 667

    return TRUE;
668 669
}

670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712
static inline char *expand_env_string( char *str, DWORD type )
{
    if (type == REG_EXPAND_SZ)
    {
        char *tmp;
        DWORD needed = ExpandEnvironmentStringsA( str, NULL, 0 );
        tmp = HeapAlloc( GetProcessHeap(), 0, needed );
        if (tmp)
        {
            ExpandEnvironmentStringsA( str, tmp, needed );
            HeapFree( GetProcessHeap(), 0, str );
            return tmp;
        }
    }
    return str;
}

static char *get_fallback_ppd_name( const char *printer_name )
{
    static const WCHAR ppds_key[] = {'S','o','f','t','w','a','r','e','\\','W','i','n','e','\\',
                                     'P','r','i','n','t','i','n','g','\\','P','P','D',' ','F','i','l','e','s',0};
    HKEY hkey;
    DWORD needed, type;
    char *ret = NULL;

    if (RegOpenKeyW( HKEY_CURRENT_USER, ppds_key, &hkey ) == ERROR_SUCCESS )
    {
        const char *value_name = NULL;

        if (RegQueryValueExA( hkey, printer_name, 0, NULL, NULL, &needed ) == ERROR_SUCCESS)
            value_name = printer_name;
        else if (RegQueryValueExA( hkey, "generic", 0, NULL, NULL, &needed ) == ERROR_SUCCESS)
            value_name = "generic";

        if (value_name)
        {
            ret = HeapAlloc( GetProcessHeap(), 0, needed );
            if (!ret) return NULL;
            RegQueryValueExA( hkey, value_name, 0, &type, (BYTE *)ret, &needed );
        }
        RegCloseKey( hkey );
        if (ret) return expand_env_string( ret, type );
    }
713
    return NULL;
714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738
}

static BOOL copy_file( const char *src, const char *dst )
{
    int fds[2] = {-1, -1}, num;
    char buf[1024];
    BOOL ret = FALSE;

    fds[0] = open( src, O_RDONLY );
    fds[1] = open( dst, O_CREAT | O_TRUNC | O_WRONLY, 0666 );
    if (fds[0] == -1 || fds[1] == -1) goto fail;

    while ((num = read( fds[0], buf, sizeof(buf) )) != 0)
    {
        if (num == -1) goto fail;
        if (write( fds[1], buf, num ) != num) goto fail;
    }
    ret = TRUE;

fail:
    if (fds[1] != -1) close( fds[1] );
    if (fds[0] != -1) close( fds[0] );
    return ret;
}

739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761
static BOOL get_internal_fallback_ppd( const WCHAR *ppd )
{
    static const WCHAR typeW[] = {'P','P','D','F','I','L','E',0};

    char *ptr, *end;
    DWORD size, written;
    HANDLE file;
    BOOL ret;
    HRSRC res = FindResourceW( WINSPOOL_hInstance, MAKEINTRESOURCEW(1), typeW );

    if (!res || !(ptr = LoadResource( WINSPOOL_hInstance, res ))) return FALSE;
    size = SizeofResource( WINSPOOL_hInstance, res );
    end = memchr( ptr, 0, size );  /* resource file may contain additional nulls */
    if (end) size = end - ptr;
    file = CreateFileW( ppd, GENERIC_WRITE, FILE_SHARE_READ, NULL, CREATE_ALWAYS, 0, 0 );
    if (file == INVALID_HANDLE_VALUE) return FALSE;
    ret = WriteFile( file, ptr, size, &written, NULL ) && written == size;
    CloseHandle( file );
    if (ret) TRACE( "using internal fallback for %s\n", debugstr_w( ppd ));
    else DeleteFileW( ppd );
    return ret;
}

762 763
static BOOL get_fallback_ppd( const char *printer_name, const WCHAR *ppd )
{
764
    char *dst, *src = get_fallback_ppd_name( printer_name );
765 766
    BOOL ret = FALSE;

767 768
    if (!src) return get_internal_fallback_ppd( ppd );

769 770
    TRACE( "(%s %s) found %s\n", debugstr_a(printer_name), debugstr_w(ppd), debugstr_a(src) );

771
    if (!(dst = wine_get_unix_file_name( ppd ))) goto fail;
772 773 774 775 776 777 778 779 780 781 782 783 784 785 786

    if (symlink( src, dst ) == -1)
        if (errno != ENOSYS || !copy_file( src, dst ))
            goto fail;

    ret = TRUE;
fail:
    HeapFree( GetProcessHeap(), 0, dst );
    HeapFree( GetProcessHeap(), 0, src );
    return ret;
}

static WCHAR *get_ppd_filename( const WCHAR *dir, const WCHAR *file_name )
{
    static const WCHAR dot_ppd[] = {'.','p','p','d',0};
787 788 789 790
    static const WCHAR invalid_chars[] = {'*','?','<','>','|','"','/','\\',0};
    int dir_len = strlenW( dir ), file_len = strlenW( file_name );
    int len = (dir_len + file_len + ARRAY_SIZE( dot_ppd )) * sizeof(WCHAR);
    WCHAR *ppd = HeapAlloc( GetProcessHeap(), 0, len ), *p;
791 792

    if (!ppd) return NULL;
793 794 795 796 797 798
    memcpy( ppd, dir, dir_len * sizeof(WCHAR) );
    memcpy( ppd + dir_len, file_name, file_len * sizeof(WCHAR) );
    memcpy( ppd + dir_len + file_len, dot_ppd, sizeof(dot_ppd) );

    p = ppd + dir_len;
    while ((p = strpbrkW( p, invalid_chars ))) *p++ = '_';
799 800 801 802 803 804 805 806 807 808 809

    return ppd;
}

static WCHAR *get_ppd_dir( void )
{
    static const WCHAR wine_ppds[] = {'w','i','n','e','_','p','p','d','s','\\',0};
    DWORD len;
    WCHAR *dir, tmp_path[MAX_PATH];
    BOOL res;

810
    len = GetTempPathW( ARRAY_SIZE( tmp_path ), tmp_path );
811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833
    if (!len) return NULL;
    dir = HeapAlloc( GetProcessHeap(), 0, len * sizeof(WCHAR) + sizeof(wine_ppds) ) ;
    if (!dir) return NULL;

    memcpy( dir, tmp_path, len * sizeof(WCHAR) );
    memcpy( dir + len, wine_ppds, sizeof(wine_ppds) );
    res = CreateDirectoryW( dir, NULL );
    if (!res && GetLastError() != ERROR_ALREADY_EXISTS)
    {
        HeapFree( GetProcessHeap(), 0, dir );
        dir = NULL;
    }
    TRACE( "ppd temporary dir: %s\n", debugstr_w(dir) );
    return dir;
}

static void unlink_ppd( const WCHAR *ppd )
{
    char *unix_name = wine_get_unix_file_name( ppd );
    unlink( unix_name );
    HeapFree( GetProcessHeap(), 0, unix_name );
}

834
#ifdef SONAME_LIBCUPS
835

836 837
static void *cupshandle;

838
#define CUPS_FUNCS \
839
    DO_FUNC(cupsAddOption); \
840
    DO_FUNC(cupsFreeDests); \
841
    DO_FUNC(cupsFreeOptions); \
842
    DO_FUNC(cupsGetDests); \
843
    DO_FUNC(cupsGetOption); \
844
    DO_FUNC(cupsParseOptions); \
845
    DO_FUNC(cupsPrintFile)
846
#define CUPS_OPT_FUNCS \
847
    DO_FUNC(cupsGetNamedDest); \
848
    DO_FUNC(cupsGetPPD); \
849 850
    DO_FUNC(cupsGetPPD3); \
    DO_FUNC(cupsLastErrorString)
851 852 853 854

#define DO_FUNC(f) static typeof(f) *p##f
CUPS_FUNCS;
#undef DO_FUNC
855
static cups_dest_t * (*pcupsGetNamedDest)(http_t *, const char *, const char *);
856
static const char *  (*pcupsGetPPD)(const char *);
857
static http_status_t (*pcupsGetPPD3)(http_t *, const char *, time_t *, char *, size_t);
858
static const char *  (*pcupsLastErrorString)(void);
859 860 861 862 863 864 865 866 867

static http_status_t cupsGetPPD3_wrapper( http_t *http, const char *name,
                                          time_t *modtime, char *buffer,
                                          size_t bufsize )
{
    const char *ppd;

    if (pcupsGetPPD3) return pcupsGetPPD3( http, name, modtime, buffer, bufsize );

868 869
    if (!pcupsGetPPD) return HTTP_NOT_FOUND;

870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899
    TRACE( "No cupsGetPPD3 implementation, so calling cupsGetPPD\n" );

    *modtime = 0;
    ppd = pcupsGetPPD( name );

    TRACE( "cupsGetPPD returns %s\n", debugstr_a(ppd) );

    if (!ppd) return HTTP_NOT_FOUND;

    if (rename( ppd, buffer ) == -1)
    {
        BOOL res = copy_file( ppd, buffer );
        unlink( ppd );
        if (!res) return HTTP_NOT_FOUND;
    }
    return HTTP_OK;
}

static BOOL get_cups_ppd( const char *printer_name, const WCHAR *ppd )
{
    time_t modtime = 0;
    http_status_t http_status;
    char *unix_name = wine_get_unix_file_name( ppd );

    TRACE( "(%s, %s)\n", debugstr_a(printer_name), debugstr_w(ppd) );

    if (!unix_name) return FALSE;

    http_status = cupsGetPPD3_wrapper( 0, printer_name, &modtime,
                                       unix_name, strlen( unix_name ) + 1 );
900 901

    if (http_status != HTTP_OK) unlink( unix_name );
902 903 904 905
    HeapFree( GetProcessHeap(), 0, unix_name );

    if (http_status == HTTP_OK) return TRUE;

906 907
    TRACE( "failed to get ppd for printer %s from cups (status %d), calling fallback\n",
           debugstr_a(printer_name), http_status );
908 909 910
    return get_fallback_ppd( printer_name, ppd );
}

911 912 913 914 915 916 917 918 919 920 921 922 923 924 925
static WCHAR *get_cups_option( const char *name, int num_options, cups_option_t *options )
{
    const char *value;
    WCHAR *ret;
    int len;

    value = pcupsGetOption( name, num_options, options );
    if (!value) return NULL;

    len = MultiByteToWideChar( CP_UNIXCP, 0, value, -1, NULL, 0 );
    ret = HeapAlloc( GetProcessHeap(), 0, len * sizeof(WCHAR) );
    if (ret) MultiByteToWideChar( CP_UNIXCP, 0, value, -1, ret, len );

    return ret;
}
926

927 928 929 930 931 932 933 934 935 936 937 938 939 940
static cups_ptype_t get_cups_printer_type( const cups_dest_t *dest )
{
    WCHAR *type = get_cups_option( "printer-type", dest->num_options, dest->options ), *end;
    cups_ptype_t ret = 0;

    if (type && *type)
    {
        ret = (cups_ptype_t)strtoulW( type, &end, 10 );
        if (*end) ret = 0;
    }
    HeapFree( GetProcessHeap(), 0, type );
    return ret;
}

941 942
static void load_cups(void)
{
943
    cupshandle = dlopen( SONAME_LIBCUPS, RTLD_NOW );
944 945 946 947 948
    if (!cupshandle) return;

    TRACE("%p: %s loaded\n", cupshandle, SONAME_LIBCUPS);

#define DO_FUNC(x) \
949
    p##x = dlsym( cupshandle, #x ); \
950 951 952 953 954 955 956 957
    if (!p##x) \
    { \
        ERR("failed to load symbol %s\n", #x); \
        cupshandle = NULL; \
        return; \
    }
    CUPS_FUNCS;
#undef DO_FUNC
958
#define DO_FUNC(x) p##x = dlsym( cupshandle, #x )
959 960 961 962
    CUPS_OPT_FUNCS;
#undef DO_FUNC
}

963 964
static BOOL CUPS_LoadPrinters(void)
{
965
    int	                  i, nrofdests;
966
    BOOL                  hadprinter = FALSE, haddefault = FALSE;
967
    cups_dest_t          *dests;
968
    PRINTER_INFO_2W       pi2;
969
    WCHAR *port, *ppd_dir = NULL, *ppd;
970
    HKEY hkeyPrinter, hkeyPrinters;
971
    WCHAR   nameW[MAX_PATH];
972
    HANDLE  added_printer;
973
    cups_ptype_t printer_type;
974

975
    if (!cupshandle) return FALSE;
976

977
    if(RegCreateKeyW(HKEY_LOCAL_MACHINE, PrintersW, &hkeyPrinters) !=
978 979 980 981
       ERROR_SUCCESS) {
        ERR("Can't create Printers key\n");
	return FALSE;
    }
982

983 984
    nrofdests = pcupsGetDests(&dests);
    TRACE("Found %d CUPS %s:\n", nrofdests, (nrofdests == 1) ? "printer" : "printers");
985
    for (i=0;i<nrofdests;i++) {
986
        MultiByteToWideChar(CP_UNIXCP, 0, dests[i].name, -1, nameW, ARRAY_SIZE(nameW));
987 988 989 990 991 992 993 994 995
        printer_type = get_cups_printer_type( dests + i );

        TRACE( "Printer %d: %s. printer_type %x\n", i, debugstr_w(nameW), printer_type );

        if (printer_type & 0x2000000 /* CUPS_PRINTER_SCANNER */)
        {
            TRACE( "skipping scanner-only device\n" );
            continue;
        }
996

997 998 999
        port = HeapAlloc(GetProcessHeap(), 0, sizeof(CUPS_Port) + lstrlenW(nameW) * sizeof(WCHAR));
        lstrcpyW(port, CUPS_Port);
        lstrcatW(port, nameW);
1000

1001
        if(RegOpenKeyW(hkeyPrinters, nameW, &hkeyPrinter) == ERROR_SUCCESS) {
1002
            DWORD status = get_dword_from_reg( hkeyPrinter, StatusW );
1003 1004 1005
            /* Printer already in registry, delete the tag added in WINSPOOL_LoadSystemPrinters
               and continue */
            TRACE("Printer already exists\n");
1006 1007
            /* overwrite old LPR:* port */
            RegSetValueExW(hkeyPrinter, PortW, 0, REG_SZ, (LPBYTE)port, (lstrlenW(port) + 1) * sizeof(WCHAR));
1008
            RegDeleteValueW(hkeyPrinter, May_Delete_Value);
1009 1010
            /* flag that the PPD file should be checked for an update */
            set_reg_DWORD( hkeyPrinter, StatusW, status | PRINTER_STATUS_DRIVER_UPDATE_NEEDED );
1011 1012
            RegCloseKey(hkeyPrinter);
        } else {
1013
            BOOL added_driver = FALSE;
1014

1015 1016 1017 1018 1019
            if (!ppd_dir && !(ppd_dir = get_ppd_dir()))
            {
                HeapFree( GetProcessHeap(), 0, port );
                break;
            }
1020 1021 1022 1023 1024 1025 1026
            ppd = get_ppd_filename( ppd_dir, nameW );
            if (get_cups_ppd( dests[i].name, ppd ))
            {
                added_driver = add_printer_driver( nameW, ppd );
                unlink_ppd( ppd );
            }
            HeapFree( GetProcessHeap(), 0, ppd );
1027 1028 1029 1030 1031
            if (!added_driver)
            {
                HeapFree( GetProcessHeap(), 0, port );
                continue;
            }
1032

1033 1034 1035 1036 1037
            memset(&pi2, 0, sizeof(PRINTER_INFO_2W));
            pi2.pPrinterName    = nameW;
            pi2.pDatatype       = rawW;
            pi2.pPrintProcessor = WinPrintW;
            pi2.pDriverName     = nameW;
1038
            pi2.pComment        = get_cups_option( "printer-info", dests[i].num_options, dests[i].options );
1039
            pi2.pLocation       = get_cups_option( "printer-location", dests[i].num_options, dests[i].options );
1040 1041 1042 1043 1044
            pi2.pPortName       = port;
            pi2.pParameters     = emptyStringW;
            pi2.pShareName      = emptyStringW;
            pi2.pSepFile        = emptyStringW;

1045 1046 1047 1048
            added_printer = AddPrinterW( NULL, 2, (LPBYTE)&pi2 );
            if (added_printer) ClosePrinter( added_printer );
            else if (GetLastError() != ERROR_PRINTER_ALREADY_EXISTS)
                ERR( "printer '%s' not added by AddPrinter (error %d)\n", debugstr_w(nameW), GetLastError() );
1049 1050

            HeapFree( GetProcessHeap(), 0, pi2.pComment );
1051
            HeapFree( GetProcessHeap(), 0, pi2.pLocation );
1052
        }
1053
        HeapFree( GetProcessHeap(), 0, port );
1054 1055

        hadprinter = TRUE;
1056
        if (dests[i].is_default) {
1057
            SetDefaultPrinterW(nameW);
1058 1059
            haddefault = TRUE;
        }
1060
    }
1061 1062 1063 1064 1065 1066 1067

    if (ppd_dir)
    {
        RemoveDirectoryW( ppd_dir );
        HeapFree( GetProcessHeap(), 0, ppd_dir );
    }

1068
    if (hadprinter && !haddefault) {
1069
        MultiByteToWideChar(CP_UNIXCP, 0, dests[0].name, -1, nameW, ARRAY_SIZE(nameW));
1070 1071
        SetDefaultPrinterW(nameW);
    }
1072
    pcupsFreeDests(nrofdests, dests);
1073
    RegCloseKey(hkeyPrinters);
1074
    return TRUE;
1075
}
1076

1077 1078 1079
#endif

static char *get_queue_name( HANDLE printer, BOOL *cups )
1080
{
1081
    WCHAR *port, *name = NULL;
1082 1083 1084 1085
    DWORD err, needed, type;
    char *ret = NULL;
    HKEY key;

1086 1087
    *cups = FALSE;

1088 1089 1090
    err = WINSPOOL_GetOpenedPrinterRegKey( printer, &key );
    if (err) return NULL;
    err = RegQueryValueExW( key, PortW, 0, &type, NULL, &needed );
1091
    if (err) goto end;
1092 1093 1094
    port = HeapAlloc( GetProcessHeap(), 0, needed );
    if (!port) goto end;
    RegQueryValueExW( key, PortW, 0, &type, (BYTE*)port, &needed );
1095

1096
    if (!strncmpW( port, CUPS_Port, ARRAY_SIZE( CUPS_Port ) -1 ))
1097
    {
1098
        name = port + ARRAY_SIZE( CUPS_Port ) - 1;
1099 1100
        *cups = TRUE;
    }
1101 1102
    else if (!strncmpW( port, LPR_Port, ARRAY_SIZE( LPR_Port ) -1 ))
        name = port + ARRAY_SIZE( LPR_Port ) - 1;
1103
    if (name)
1104 1105 1106 1107 1108 1109 1110 1111 1112 1113
    {
        needed = WideCharToMultiByte( CP_UNIXCP, 0, name, -1, NULL, 0, NULL, NULL );
        ret = HeapAlloc( GetProcessHeap(), 0, needed );
        if(ret) WideCharToMultiByte( CP_UNIXCP, 0, name, -1, ret, needed, NULL, NULL );
    }
    HeapFree( GetProcessHeap(), 0, port );
end:
    RegCloseKey( key );
    return ret;
}
1114

1115

1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159
static void set_ppd_overrides( HANDLE printer )
{
    WCHAR *wstr = NULL;
    int size = 0;
#ifdef HAVE_APPLICATIONSERVICES_APPLICATIONSERVICES_H
    OSStatus status;
    PMPrintSession session = NULL;
    PMPageFormat format = NULL;
    PMPaper paper;
    CFStringRef paper_name;
    CFRange range;

    status = PMCreateSession( &session );
    if (status) goto end;

    status = PMCreatePageFormat( &format );
    if (status) goto end;

    status = PMSessionDefaultPageFormat( session, format );
    if (status) goto end;

    status = PMGetPageFormatPaper( format, &paper );
    if (status) goto end;

    status = PMPaperGetPPDPaperName( paper, &paper_name );
    if (status) goto end;

    range.location = 0;
    range.length = CFStringGetLength( paper_name );
    size = (range.length + 1) * sizeof(WCHAR);

    wstr = HeapAlloc( GetProcessHeap(), 0, size );
    CFStringGetCharacters( paper_name, range, (UniChar*)wstr );
    wstr[range.length] = 0;

end:
    if (format) PMRelease( format );
    if (session) PMRelease( session );
#endif

    SetPrinterDataExW( printer, PPD_Overrides, DefaultPageSize, REG_SZ, (BYTE*)wstr, size );
    HeapFree( GetProcessHeap(), 0, wstr );
}

1160 1161
static BOOL update_driver( HANDLE printer )
{
1162
    BOOL ret, is_cups;
1163 1164
    const WCHAR *name = get_opened_printer_name( printer );
    WCHAR *ppd_dir, *ppd;
1165
    char *queue_name;
1166 1167

    if (!name) return FALSE;
1168 1169
    queue_name = get_queue_name( printer, &is_cups );
    if (!queue_name) return FALSE;
1170

1171 1172 1173 1174 1175
    if (!(ppd_dir = get_ppd_dir()))
    {
        HeapFree( GetProcessHeap(), 0, queue_name );
        return FALSE;
    }
1176
    ppd = get_ppd_filename( ppd_dir, name );
1177 1178 1179 1180 1181 1182 1183 1184 1185

#ifdef SONAME_LIBCUPS
    if (is_cups)
        ret = get_cups_ppd( queue_name, ppd );
    else
#endif
        ret = get_fallback_ppd( queue_name, ppd );

    if (ret)
1186 1187 1188 1189 1190 1191 1192
    {
        TRACE( "updating driver %s\n", debugstr_w( name ) );
        ret = add_printer_driver( name, ppd );
        unlink_ppd( ppd );
    }
    HeapFree( GetProcessHeap(), 0, ppd_dir );
    HeapFree( GetProcessHeap(), 0, ppd );
1193
    HeapFree( GetProcessHeap(), 0, queue_name );
1194

1195 1196
    set_ppd_overrides( printer );

1197 1198 1199
    /* call into the driver to update the devmode */
    DocumentPropertiesW( 0, printer, NULL, NULL, NULL, 0 );

1200 1201 1202
    return ret;
}

1203 1204
static BOOL PRINTCAP_ParseEntry( const char *pent, BOOL isfirst )
{
1205
    PRINTER_INFO_2A	pinfo2a;
1206 1207
    const char	*r;
    size_t		name_len;
1208 1209
    char		*e,*s,*name,*prettyname,*devname;
    BOOL		ret = FALSE, set_default = FALSE;
1210
    char *port = NULL, *env_default;
1211 1212
    HKEY hkeyPrinter, hkeyPrinters = NULL;
    WCHAR devnameW[MAX_PATH], *ppd_dir = NULL, *ppd;
1213
    HANDLE added_printer;
1214

1215
    while (isspace(*pent)) pent++;
1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226
    r = strchr(pent,':');
    if (r)
        name_len = r - pent;
    else
        name_len = strlen(pent);
    name = HeapAlloc(GetProcessHeap(), 0, name_len + 1);
    memcpy(name, pent, name_len);
    name[name_len] = '\0';
    if (r)
        pent = r;
    else
1227 1228 1229 1230 1231 1232 1233
        pent = "";

    TRACE("name=%s entry=%s\n",name, pent);

    if(ispunct(*name)) { /* a tc entry, not a real printer */
        TRACE("skipping tc entry\n");
        goto end;
1234
    }
1235 1236 1237 1238

    if(strstr(pent,":server")) { /* server only version so skip */
        TRACE("skipping server entry\n");
        goto end;
1239 1240
    }

1241
    /* Determine whether this is a postscript printer. */
1242

1243 1244
    ret = TRUE;
    env_default = getenv("PRINTER");
1245 1246
    prettyname = name;
    /* Get longest name, usually the one at the right for later display. */
1247 1248 1249 1250 1251
    while((s=strchr(prettyname,'|'))) {
        *s = '\0';
        e = s;
        while(isspace(*--e)) *e = '\0';
        TRACE("\t%s\n", debugstr_a(prettyname));
1252
        if(env_default && !_strnicmp(prettyname, env_default, -1)) set_default = TRUE;
1253 1254 1255 1256 1257 1258
        for(prettyname = s+1; isspace(*prettyname); prettyname++)
            ;
    }
    e = prettyname + strlen(prettyname);
    while(isspace(*--e)) *e = '\0';
    TRACE("\t%s\n", debugstr_a(prettyname));
1259
    if(env_default && !_strnicmp(prettyname, env_default, -1)) set_default = TRUE;
1260 1261 1262 1263 1264 1265

    /* prettyname must fit into the dmDeviceName member of DEVMODE struct,
     * if it is too long, we use it as comment below. */
    devname = prettyname;
    if (strlen(devname)>=CCHDEVICENAME-1)
	 devname = name;
1266 1267 1268 1269
    if (strlen(devname)>=CCHDEVICENAME-1) {
        ret = FALSE;
        goto end;
    }
1270

1271 1272 1273
    port = HeapAlloc(GetProcessHeap(),0,strlen("LPR:")+strlen(name)+1);
    sprintf(port,"LPR:%s",name);

1274
    if(RegCreateKeyW(HKEY_LOCAL_MACHINE, PrintersW, &hkeyPrinters) !=
1275 1276 1277 1278 1279
       ERROR_SUCCESS) {
        ERR("Can't create Printers key\n");
	ret = FALSE;
        goto end;
    }
1280

1281
    MultiByteToWideChar(CP_ACP, 0, devname, -1, devnameW, ARRAY_SIZE(devnameW));
1282

1283
    if(RegOpenKeyA(hkeyPrinters, devname, &hkeyPrinter) == ERROR_SUCCESS) {
1284
        DWORD status = get_dword_from_reg( hkeyPrinter, StatusW );
1285 1286 1287 1288
        /* Printer already in registry, delete the tag added in WINSPOOL_LoadSystemPrinters
           and continue */
        TRACE("Printer already exists\n");
        RegDeleteValueW(hkeyPrinter, May_Delete_Value);
1289 1290
        /* flag that the PPD file should be checked for an update */
        set_reg_DWORD( hkeyPrinter, StatusW, status | PRINTER_STATUS_DRIVER_UPDATE_NEEDED );
1291 1292
        RegCloseKey(hkeyPrinter);
    } else {
1293 1294 1295 1296 1297 1298
        static CHAR data_type[]   = "RAW",
                    print_proc[]  = "WinPrint",
                    comment[]     = "WINEPS Printer using LPR",
                    params[]      = "<parameters?>",
                    share_name[]  = "<share name?>",
                    sep_file[]    = "<sep file?>";
1299
        BOOL added_driver = FALSE;
1300

1301
        if (!ppd_dir && !(ppd_dir = get_ppd_dir())) goto end;
1302 1303 1304 1305 1306 1307 1308 1309
        ppd = get_ppd_filename( ppd_dir, devnameW );
        if (get_fallback_ppd( devname, ppd ))
        {
            added_driver = add_printer_driver( devnameW, ppd );
            unlink_ppd( ppd );
        }
        HeapFree( GetProcessHeap(), 0, ppd );
        if (!added_driver) goto end;
1310

1311
        memset(&pinfo2a,0,sizeof(pinfo2a));
1312 1313 1314
        pinfo2a.pPrinterName    = devname;
        pinfo2a.pDatatype       = data_type;
        pinfo2a.pPrintProcessor = print_proc;
1315
        pinfo2a.pDriverName     = devname;
1316 1317 1318 1319 1320 1321
        pinfo2a.pComment        = comment;
        pinfo2a.pLocation       = prettyname;
        pinfo2a.pPortName       = port;
        pinfo2a.pParameters     = params;
        pinfo2a.pShareName      = share_name;
        pinfo2a.pSepFile        = sep_file;
1322

1323 1324 1325 1326
        added_printer = AddPrinterA( NULL, 2, (LPBYTE)&pinfo2a );
        if (added_printer) ClosePrinter( added_printer );
        else if (GetLastError() != ERROR_PRINTER_ALREADY_EXISTS)
            ERR( "printer '%s' not added by AddPrinter (error %d)\n", debugstr_a(name), GetLastError() );
1327
    }
1328 1329

    if (isfirst || set_default)
1330
        set_default_printer(devname, name);
1331 1332

 end:
1333 1334 1335 1336 1337 1338
    if (hkeyPrinters) RegCloseKey( hkeyPrinters );
    if (ppd_dir)
    {
        RemoveDirectoryW( ppd_dir );
        HeapFree( GetProcessHeap(), 0, ppd_dir );
    }
1339
    HeapFree(GetProcessHeap(), 0, port);
1340 1341
    HeapFree(GetProcessHeap(), 0, name);
    return ret;
1342 1343 1344 1345
}

static BOOL
PRINTCAP_LoadPrinters(void) {
1346
    BOOL		hadprinter = FALSE;
1347 1348
    char		buf[200];
    FILE		*f;
1349 1350
    char *pent = NULL;
    BOOL had_bash = FALSE;
1351 1352 1353 1354 1355

    f = fopen("/etc/printcap","r");
    if (!f)
	return FALSE;

1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390
    while(fgets(buf,sizeof(buf),f)) {
        char *start, *end;

        end=strchr(buf,'\n');
        if (end) *end='\0';
    
        start = buf;
        while(isspace(*start)) start++;
        if(*start == '#' || *start == '\0')
            continue;

        if(pent && !had_bash && *start != ':' && *start != '|') { /* start of new entry, parse the previous one */
	    hadprinter |= PRINTCAP_ParseEntry(pent,!hadprinter);
            HeapFree(GetProcessHeap(),0,pent);
            pent = NULL;
        }

        if (end && *--end == '\\') {
            *end = '\0';
            had_bash = TRUE;
        } else
            had_bash = FALSE;

        if (pent) {
            pent=HeapReAlloc(GetProcessHeap(),0,pent,strlen(pent)+strlen(start)+1);
            strcat(pent,start);
        } else {
            pent=HeapAlloc(GetProcessHeap(),0,strlen(start)+1);
            strcpy(pent,start);
        }

    }
    if(pent) {
        hadprinter |= PRINTCAP_ParseEntry(pent,!hadprinter);
        HeapFree(GetProcessHeap(),0,pent);
1391 1392 1393 1394 1395
    }
    fclose(f);
    return hadprinter;
}

1396
static inline DWORD set_reg_szW(HKEY hkey, const WCHAR *keyname, const WCHAR *value)
1397
{
1398
    if (value)
Eric Pouech's avatar
Eric Pouech committed
1399
        return RegSetValueExW(hkey, keyname, 0, REG_SZ, (const BYTE*)value,
1400
                              (lstrlenW(value) + 1) * sizeof(WCHAR));
1401 1402
    else
        return ERROR_FILE_NOT_FOUND;
1403 1404
}

1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424
static inline DWORD set_reg_devmode( HKEY key, const WCHAR *name, const DEVMODEW *dm )
{
    DEVMODEA *dmA = DEVMODEdupWtoA( dm );
    DWORD ret = ERROR_FILE_NOT_FOUND;

    /* FIXME: Write DEVMODEA not DEVMODEW into reg.  This is what win9x does
       and we support these drivers.  NT writes DEVMODEW so somehow
       we'll need to distinguish between these when we support NT
       drivers */

    if (dmA)
    {
        ret = RegSetValueExW( key, name, 0, REG_BINARY,
                              (LPBYTE)dmA, dmA->dmSize + dmA->dmDriverExtra );
        HeapFree( GetProcessHeap(), 0, dmA );
    }

    return ret;
}

1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449
/******************************************************************
 * get_servername_from_name  (internal)
 *
 * for an external server, a copy of the serverpart from the full name is returned
 *
 */
static LPWSTR get_servername_from_name(LPCWSTR name)
{
    LPWSTR  server;
    LPWSTR  ptr;
    WCHAR   buffer[MAX_PATH];
    DWORD   len;

    if (name == NULL) return NULL;
    if ((name[0] != '\\') || (name[1] != '\\')) return NULL;

    server = strdupW(&name[2]);     /* skip over both backslash */
    if (server == NULL) return NULL;

    /* strip '\' and the printername */
    ptr = strchrW(server, '\\');
    if (ptr) ptr[0] = '\0';

    TRACE("found %s\n", debugstr_w(server));

1450
    len = ARRAY_SIZE(buffer);
1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473
    if (GetComputerNameW(buffer, &len)) {
        if (lstrcmpW(buffer, server) == 0) {
            /* The requested Servername is our computername */
            HeapFree(GetProcessHeap(), 0, server);
            return NULL;
        }
    }
    return server;
}

/******************************************************************
 * get_basename_from_name  (internal)
 *
 * skip over the serverpart from the full name
 *
 */
static LPCWSTR get_basename_from_name(LPCWSTR name)
{
    if (name == NULL)  return NULL;
    if ((name[0] == '\\') && (name[1] == '\\')) {
        /* skip over the servername and search for the following '\'  */
        name = strchrW(&name[2], '\\');
        if ((name) && (name[1])) {
1474 1475
            /* found a separator ('\') followed by a name:
               skip over the separator and return the rest */
1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486
            name++;
        }
        else
        {
            /* no basename present (we found only a servername) */
            return NULL;
        }
    }
    return name;
}

1487 1488 1489 1490 1491
static void free_printer_entry( opened_printer_t *printer )
{
    /* the queue is shared, so don't free that here */
    HeapFree( GetProcessHeap(), 0, printer->printername );
    HeapFree( GetProcessHeap(), 0, printer->name );
1492
    HeapFree( GetProcessHeap(), 0, printer->devmode );
1493 1494 1495
    HeapFree( GetProcessHeap(), 0, printer );
}

1496
/******************************************************************
1497
 *  get_opened_printer_entry
1498
 *  Get the first place empty in the opened printer table
1499 1500 1501
 *
 * ToDo:
 *  - pDefault is ignored
1502
 */
1503
static HANDLE get_opened_printer_entry(LPWSTR name, LPPRINTER_DEFAULTSW pDefault)
1504
{
Kevin Koltzau's avatar
Kevin Koltzau committed
1505
    UINT_PTR handle = nb_printer_handles, i;
1506
    jobqueue_t *queue = NULL;
1507
    opened_printer_t *printer = NULL;
1508 1509 1510
    LPWSTR  servername;
    LPCWSTR printername;

1511 1512
    if ((backend == NULL)  && !load_backend()) return NULL;

1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528
    servername = get_servername_from_name(name);
    if (servername) {
        FIXME("server %s not supported\n", debugstr_w(servername));
        HeapFree(GetProcessHeap(), 0, servername);
        SetLastError(ERROR_INVALID_PRINTER_NAME);
        return NULL;
    }

    printername = get_basename_from_name(name);
    if (name != printername) TRACE("converted %s to %s\n", debugstr_w(name), debugstr_w(printername));

    /* an empty printername is invalid */
    if (printername && (!printername[0])) {
        SetLastError(ERROR_INVALID_PARAMETER);
        return NULL;
    }
1529

1530
    EnterCriticalSection(&printer_handles_cs);
1531

1532 1533 1534 1535 1536 1537 1538
    for (i = 0; i < nb_printer_handles; i++)
    {
        if (!printer_handles[i])
        {
            if(handle == nb_printer_handles)
                handle = i;
        }
1539 1540 1541 1542 1543
        else
        {
            if(!queue && (name) && !lstrcmpW(name, printer_handles[i]->name))
                queue = printer_handles[i]->queue;
        }
1544
    }
1545

1546 1547 1548 1549 1550 1551
    if (handle >= nb_printer_handles)
    {
        opened_printer_t **new_array;
        if (printer_handles)
            new_array = HeapReAlloc( GetProcessHeap(), HEAP_ZERO_MEMORY, printer_handles,
                                     (nb_printer_handles + 16) * sizeof(*new_array) );
1552
        else
1553 1554 1555 1556 1557 1558 1559 1560 1561 1562
            new_array = HeapAlloc( GetProcessHeap(), HEAP_ZERO_MEMORY,
                                   (nb_printer_handles + 16) * sizeof(*new_array) );

        if (!new_array)
        {
            handle = 0;
            goto end;
        }
        printer_handles = new_array;
        nb_printer_handles += 16;
1563 1564
    }

1565
    if (!(printer = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*printer))))
1566
    {
1567 1568
        handle = 0;
        goto end;
1569
    }
1570

1571 1572 1573 1574 1575
    /* get a printer handle from the backend */
    if (! backend->fpOpenPrinter(name, &printer->backend_printer, pDefault)) {
        handle = 0;
        goto end;
    }
1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586

    /* clone the base name. This is NULL for the printserver */
    printer->printername = strdupW(printername);

    /* clone the full name */
    printer->name = strdupW(name);
    if (name && (!printer->name)) {
        handle = 0;
        goto end;
    }

1587 1588 1589
    if (pDefault && pDefault->pDevMode)
        printer->devmode = dup_devmode( pDefault->pDevMode );

1590 1591 1592 1593 1594
    if(queue)
        printer->queue = queue;
    else
    {
        printer->queue = HeapAlloc(GetProcessHeap(), 0, sizeof(*queue));
1595 1596 1597 1598
        if (!printer->queue) {
            handle = 0;
            goto end;
        }
1599 1600 1601 1602
        list_init(&printer->queue->jobs);
        printer->queue->ref = 0;
    }
    InterlockedIncrement(&printer->queue->ref);
1603

1604
    printer_handles[handle] = printer;
1605 1606 1607
    handle++;
end:
    LeaveCriticalSection(&printer_handles_cs);
1608 1609
    if (!handle && printer) {
        if (!queue) HeapFree(GetProcessHeap(), 0, printer->queue);
1610
        free_printer_entry( printer );
1611
    }
1612 1613

    return (HANDLE)handle;
1614 1615
}

1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630
static void old_printer_check( BOOL delete_phase )
{
    PRINTER_INFO_5W* pi;
    DWORD needed, type, num, delete, i, size;
    const DWORD one = 1;
    HKEY key;
    HANDLE hprn;

    EnumPrintersW( PRINTER_ENUM_LOCAL, NULL, 5, NULL, 0, &needed, &num );
    if (GetLastError() != ERROR_INSUFFICIENT_BUFFER) return;

    pi = HeapAlloc( GetProcessHeap(), 0, needed );
    EnumPrintersW( PRINTER_ENUM_LOCAL, NULL, 5, (LPBYTE)pi, needed, &needed, &num );
    for (i = 0; i < num; i++)
    {
1631 1632
        if (!pi[i].pPortName) continue;

1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664
        if (strncmpW( pi[i].pPortName, CUPS_Port, strlenW(CUPS_Port) ) &&
            strncmpW( pi[i].pPortName, LPR_Port, strlenW(LPR_Port) ))
            continue;

        if (open_printer_reg_key( pi[i].pPrinterName, &key )) continue;

        if (!delete_phase)
        {
            RegSetValueExW( key, May_Delete_Value, 0, REG_DWORD, (LPBYTE)&one, sizeof(one) );
            RegCloseKey( key );
        }
        else
        {
            delete = 0;
            size = sizeof( delete );
            RegQueryValueExW( key, May_Delete_Value, NULL, &type, (LPBYTE)&delete, &size );
            RegCloseKey( key );
            if (delete)
            {
                TRACE( "Deleting old printer %s\n", debugstr_w(pi[i].pPrinterName) );
                if (OpenPrinterW( pi[i].pPrinterName, &hprn, NULL ))
                {
                    DeletePrinter( hprn );
                    ClosePrinter( hprn );
                }
                DeletePrinterDriverExW( NULL, NULL, pi[i].pPrinterName, 0, 0 );
            }
        }
    }
    HeapFree(GetProcessHeap(), 0, pi);
}

1665 1666
static const WCHAR winspool_mutex_name[] = {'_','_','W','I','N','E','_','W','I','N','S','P','O','O','L','_',
                                            'M','U','T','E','X','_','_','\0'};
1667
static HANDLE init_mutex;
1668

1669 1670 1671 1672 1673 1674
void WINSPOOL_LoadSystemPrinters(void)
{
    HKEY                hkey, hkeyPrinters;
    DWORD               needed, num, i;
    WCHAR               PrinterName[256];
    BOOL                done = FALSE;
1675

1676 1677 1678 1679
#ifdef SONAME_LIBCUPS
    load_cups();
#endif

1680
    /* FIXME: The init code should be moved to spoolsv.exe */
1681 1682
    init_mutex = CreateMutexW( NULL, TRUE, winspool_mutex_name );
    if (!init_mutex)
1683 1684 1685 1686 1687 1688
    {
        ERR( "Failed to create mutex\n" );
        return;
    }
    if (GetLastError() == ERROR_ALREADY_EXISTS)
    {
1689 1690
        WaitForSingleObject( init_mutex, INFINITE );
        ReleaseMutex( init_mutex );
1691 1692 1693
        TRACE( "Init already done\n" );
        return;
    }
1694 1695 1696 1697 1698

    /* This ensures that all printer entries have a valid Name value.  If causes
       problems later if they don't.  If one is found to be missed we create one
       and set it equal to the name of the key */
    if(RegCreateKeyW(HKEY_LOCAL_MACHINE, PrintersW, &hkeyPrinters) == ERROR_SUCCESS) {
1699
        if(RegQueryInfoKeyW(hkeyPrinters, NULL, NULL, NULL, &num, NULL, NULL,
1700 1701
                            NULL, NULL, NULL, NULL, NULL) == ERROR_SUCCESS) {
            for(i = 0; i < num; i++) {
1702
                if(RegEnumKeyW(hkeyPrinters, i, PrinterName, ARRAY_SIZE(PrinterName)) == ERROR_SUCCESS) {
1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714
                    if(RegOpenKeyW(hkeyPrinters, PrinterName, &hkey) == ERROR_SUCCESS) {
                        if(RegQueryValueExW(hkey, NameW, 0, 0, 0, &needed) == ERROR_FILE_NOT_FOUND) {
                            set_reg_szW(hkey, NameW, PrinterName);
                        }
                        RegCloseKey(hkey);
                    }
                }
            }
        }
        RegCloseKey(hkeyPrinters);
    }

1715
    old_printer_check( FALSE );
1716

1717
#ifdef SONAME_LIBCUPS
1718 1719 1720
    done = CUPS_LoadPrinters();
#endif

1721 1722
    if(!done) /* If we have any CUPS based printers, skip looking for printcap printers */
        PRINTCAP_LoadPrinters();
1723

1724
    old_printer_check( TRUE );
1725

1726
    ReleaseMutex( init_mutex );
1727 1728 1729
    return;
}

1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741
/******************************************************************
 *                  get_job
 *
 *  Get the pointer to the specified job.
 *  Should hold the printer_handles_cs before calling.
 */
static job_t *get_job(HANDLE hprn, DWORD JobId)
{
    opened_printer_t *printer = get_opened_printer(hprn);
    job_t *job;

    if(!printer) return NULL;
1742
    LIST_FOR_EACH_ENTRY(job, &printer->queue->jobs, job_t, entry)
1743 1744 1745 1746 1747 1748 1749
    {
        if(job->job_id == JobId)
            return job;
    }
    return NULL;
}

1750 1751 1752 1753 1754 1755
/***********************************************************
 *      DEVMODEcpyAtoW
 */
static LPDEVMODEW DEVMODEcpyAtoW(DEVMODEW *dmW, const DEVMODEA *dmA)
{
    BOOL Formname;
Eric Pouech's avatar
Eric Pouech committed
1756
    ptrdiff_t off_formname = (const char *)dmA->dmFormName - (const char *)dmA;
1757 1758 1759 1760
    DWORD size;

    Formname = (dmA->dmSize > off_formname);
    size = dmA->dmSize + CCHDEVICENAME + (Formname ? CCHFORMNAME : 0);
Mike McCormack's avatar
Mike McCormack committed
1761 1762
    MultiByteToWideChar(CP_ACP, 0, (LPCSTR)dmA->dmDeviceName, -1,
                        dmW->dmDeviceName, CCHDEVICENAME);
1763 1764 1765 1766 1767 1768
    if(!Formname) {
      memcpy(&dmW->dmSpecVersion, &dmA->dmSpecVersion,
	     dmA->dmSize - CCHDEVICENAME);
    } else {
      memcpy(&dmW->dmSpecVersion, &dmA->dmSpecVersion,
	     off_formname - CCHDEVICENAME);
Mike McCormack's avatar
Mike McCormack committed
1769 1770
      MultiByteToWideChar(CP_ACP, 0, (LPCSTR)dmA->dmFormName, -1,
                          dmW->dmFormName, CCHFORMNAME);
1771 1772 1773 1774
      memcpy(&dmW->dmLogPixels, &dmA->dmLogPixels, dmA->dmSize -
	     (off_formname + CCHFORMNAME));
    }
    dmW->dmSize = size;
Eric Pouech's avatar
Eric Pouech committed
1775
    memcpy((char *)dmW + dmW->dmSize, (const char *)dmA + dmA->dmSize,
1776 1777 1778 1779
	   dmA->dmDriverExtra);
    return dmW;
}

1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987
/******************************************************************
 * convert_printerinfo_W_to_A [internal]
 *
 */
static void convert_printerinfo_W_to_A(LPBYTE out, LPBYTE pPrintersW,
                                       DWORD level, DWORD outlen, DWORD numentries)
{
    DWORD id = 0;
    LPSTR ptr;
    INT len;

    TRACE("(%p, %p, %d, %u, %u)\n", out, pPrintersW, level, outlen, numentries);

    len = pi_sizeof[level] * numentries;
    ptr = (LPSTR) out + len;
    outlen -= len;

    /* copy the numbers of all PRINTER_INFO_* first */
    memcpy(out, pPrintersW, len);

    while (id < numentries) {
        switch (level) {
            case 1:
                {
                    PRINTER_INFO_1W * piW = (PRINTER_INFO_1W *) pPrintersW;
                    PRINTER_INFO_1A * piA = (PRINTER_INFO_1A *) out;

                    TRACE("(%u) #%u: %s\n", level, id, debugstr_w(piW->pName));
                    if (piW->pDescription) {
                        piA->pDescription = ptr;
                        len = WideCharToMultiByte(CP_ACP, 0, piW->pDescription, -1,
                                                  ptr, outlen, NULL, NULL);
                        ptr += len;
                        outlen -= len;
                    }
                    if (piW->pName) {
                        piA->pName = ptr;
                        len = WideCharToMultiByte(CP_ACP, 0, piW->pName, -1,
                                                  ptr, outlen, NULL, NULL);
                        ptr += len;
                        outlen -= len;
                    }
                    if (piW->pComment) {
                        piA->pComment = ptr;
                        len = WideCharToMultiByte(CP_ACP, 0, piW->pComment, -1,
                                                  ptr, outlen, NULL, NULL);
                        ptr += len;
                        outlen -= len;
                    }
                    break;
                }

            case 2:
                {
                    PRINTER_INFO_2W * piW = (PRINTER_INFO_2W *) pPrintersW;
                    PRINTER_INFO_2A * piA = (PRINTER_INFO_2A *) out;
                    LPDEVMODEA dmA;

                    TRACE("(%u) #%u: %s\n", level, id, debugstr_w(piW->pPrinterName));
                    if (piW->pServerName) {
                        piA->pServerName = ptr;
                        len = WideCharToMultiByte(CP_ACP, 0, piW->pServerName, -1,
                                                  ptr, outlen, NULL, NULL);
                        ptr += len;
                        outlen -= len;
                    }
                    if (piW->pPrinterName) {
                        piA->pPrinterName = ptr;
                        len = WideCharToMultiByte(CP_ACP, 0, piW->pPrinterName, -1,
                                                  ptr, outlen, NULL, NULL);
                        ptr += len;
                        outlen -= len;
                    }
                    if (piW->pShareName) {
                        piA->pShareName = ptr;
                        len = WideCharToMultiByte(CP_ACP, 0, piW->pShareName, -1,
                                                  ptr, outlen, NULL, NULL);
                        ptr += len;
                        outlen -= len;
                    }
                    if (piW->pPortName) {
                        piA->pPortName = ptr;
                        len = WideCharToMultiByte(CP_ACP, 0, piW->pPortName, -1,
                                                  ptr, outlen, NULL, NULL);
                        ptr += len;
                        outlen -= len;
                    }
                    if (piW->pDriverName) {
                        piA->pDriverName = ptr;
                        len = WideCharToMultiByte(CP_ACP, 0, piW->pDriverName, -1,
                                                  ptr, outlen, NULL, NULL);
                        ptr += len;
                        outlen -= len;
                    }
                    if (piW->pComment) {
                        piA->pComment = ptr;
                        len = WideCharToMultiByte(CP_ACP, 0, piW->pComment, -1,
                                                  ptr, outlen, NULL, NULL);
                        ptr += len;
                        outlen -= len;
                    }
                    if (piW->pLocation) {
                        piA->pLocation = ptr;
                        len = WideCharToMultiByte(CP_ACP, 0, piW->pLocation, -1,
                                                  ptr, outlen, NULL, NULL);
                        ptr += len;
                        outlen -= len;
                    }

                    dmA = DEVMODEdupWtoA(piW->pDevMode);
                    if (dmA) {
                        /* align DEVMODEA to a DWORD boundary */
                        len = (4 - ( (DWORD_PTR) ptr & 3)) & 3;
                        ptr += len;
                        outlen -= len;

                        piA->pDevMode = (LPDEVMODEA) ptr;
                        len = dmA->dmSize + dmA->dmDriverExtra;
                        memcpy(ptr, dmA, len);
                        HeapFree(GetProcessHeap(), 0, dmA);

                        ptr += len;
                        outlen -= len;
                    }

                    if (piW->pSepFile) {
                        piA->pSepFile = ptr;
                        len = WideCharToMultiByte(CP_ACP, 0, piW->pSepFile, -1,
                                                  ptr, outlen, NULL, NULL);
                        ptr += len;
                        outlen -= len;
                    }
                    if (piW->pPrintProcessor) {
                        piA->pPrintProcessor = ptr;
                        len = WideCharToMultiByte(CP_ACP, 0, piW->pPrintProcessor, -1,
                                                  ptr, outlen, NULL, NULL);
                        ptr += len;
                        outlen -= len;
                    }
                    if (piW->pDatatype) {
                        piA->pDatatype = ptr;
                        len = WideCharToMultiByte(CP_ACP, 0, piW->pDatatype, -1,
                                                  ptr, outlen, NULL, NULL);
                        ptr += len;
                        outlen -= len;
                    }
                    if (piW->pParameters) {
                        piA->pParameters = ptr;
                        len = WideCharToMultiByte(CP_ACP, 0, piW->pParameters, -1,
                                                  ptr, outlen, NULL, NULL);
                        ptr += len;
                        outlen -= len;
                    }
                    if (piW->pSecurityDescriptor) {
                        piA->pSecurityDescriptor = NULL;
                        FIXME("pSecurityDescriptor ignored: %s\n", debugstr_w(piW->pPrinterName));
                    }
                    break;
                }

            case 4:
                {
                    PRINTER_INFO_4W * piW = (PRINTER_INFO_4W *) pPrintersW;
                    PRINTER_INFO_4A * piA = (PRINTER_INFO_4A *) out;

                    TRACE("(%u) #%u: %s\n", level, id, debugstr_w(piW->pPrinterName));

                    if (piW->pPrinterName) {
                        piA->pPrinterName = ptr;
                        len = WideCharToMultiByte(CP_ACP, 0, piW->pPrinterName, -1,
                                                  ptr, outlen, NULL, NULL);
                        ptr += len;
                        outlen -= len;
                    }
                    if (piW->pServerName) {
                        piA->pServerName = ptr;
                        len = WideCharToMultiByte(CP_ACP, 0, piW->pServerName, -1,
                                                  ptr, outlen, NULL, NULL);
                        ptr += len;
                        outlen -= len;
                    }
                    break;
                }

            case 5:
                {
                    PRINTER_INFO_5W * piW = (PRINTER_INFO_5W *) pPrintersW;
                    PRINTER_INFO_5A * piA = (PRINTER_INFO_5A *) out;

                    TRACE("(%u) #%u: %s\n", level, id, debugstr_w(piW->pPrinterName));

                    if (piW->pPrinterName) {
                        piA->pPrinterName = ptr;
                        len = WideCharToMultiByte(CP_ACP, 0, piW->pPrinterName, -1,
                                                  ptr, outlen, NULL, NULL);
                        ptr += len;
                        outlen -= len;
                    }
                    if (piW->pPortName) {
                        piA->pPortName = ptr;
                        len = WideCharToMultiByte(CP_ACP, 0, piW->pPortName, -1,
                                                  ptr, outlen, NULL, NULL);
                        ptr += len;
                        outlen -= len;
                    }
                    break;
                }

1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006
            case 6:  /* 6A and 6W are the same structure */
                break;

            case 7:
                {
                    PRINTER_INFO_7W * piW = (PRINTER_INFO_7W *) pPrintersW;
                    PRINTER_INFO_7A * piA = (PRINTER_INFO_7A *) out;

                    TRACE("(%u) #%u\n", level, id);
                    if (piW->pszObjectGUID) {
                        piA->pszObjectGUID = ptr;
                        len = WideCharToMultiByte(CP_ACP, 0, piW->pszObjectGUID, -1,
                                                  ptr, outlen, NULL, NULL);
                        ptr += len;
                        outlen -= len;
                    }
                    break;
                }

2007
            case 8:
2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033
            case 9:
                {
                    PRINTER_INFO_9W * piW = (PRINTER_INFO_9W *) pPrintersW;
                    PRINTER_INFO_9A * piA = (PRINTER_INFO_9A *) out;
                    LPDEVMODEA dmA;

                    TRACE("(%u) #%u\n", level, id);
                    dmA = DEVMODEdupWtoA(piW->pDevMode);
                    if (dmA) {
                        /* align DEVMODEA to a DWORD boundary */
                        len = (4 - ( (DWORD_PTR) ptr & 3)) & 3;
                        ptr += len;
                        outlen -= len;

                        piA->pDevMode = (LPDEVMODEA) ptr;
                        len = dmA->dmSize + dmA->dmDriverExtra;
                        memcpy(ptr, dmA, len);
                        HeapFree(GetProcessHeap(), 0, dmA);

                        ptr += len;
                        outlen -= len;
                    }

                    break;
                }

2034 2035 2036 2037 2038 2039 2040 2041 2042
            default:
                FIXME("for level %u\n", level);
        }
        pPrintersW += pi_sizeof[level];
        out += pi_sizeof[level];
        id++;
    }
}

2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224
/******************************************************************
 * convert_driverinfo_W_to_A [internal]
 *
 */
static void convert_driverinfo_W_to_A(LPBYTE out, LPBYTE pDriversW,
                                       DWORD level, DWORD outlen, DWORD numentries)
{
    DWORD id = 0;
    LPSTR ptr;
    INT len;

    TRACE("(%p, %p, %d, %u, %u)\n", out, pDriversW, level, outlen, numentries);

    len = di_sizeof[level] * numentries;
    ptr = (LPSTR) out + len;
    outlen -= len;

    /* copy the numbers of all PRINTER_INFO_* first */
    memcpy(out, pDriversW, len);

#define COPY_STRING(fld) \
                    { if (diW->fld){ \
                        diA->fld = ptr; \
                        len = WideCharToMultiByte(CP_ACP, 0, diW->fld, -1, ptr, outlen, NULL, NULL);\
                        ptr += len; outlen -= len;\
                    }}
#define COPY_MULTIZ_STRING(fld) \
                    { LPWSTR p = diW->fld; if (p){ \
                        diA->fld = ptr; \
                        do {\
                        len = WideCharToMultiByte(CP_ACP, 0, p, -1, ptr, outlen, NULL, NULL);\
                        ptr += len; outlen -= len; p += len;\
                        }\
                        while(len > 1 && outlen > 0); \
                    }}

    while (id < numentries)
    {
        switch (level)
        {
            case 1:
                {
                    DRIVER_INFO_1W * diW = (DRIVER_INFO_1W *) pDriversW;
                    DRIVER_INFO_1A * diA = (DRIVER_INFO_1A *) out;

                    TRACE("(%u) #%u: %s\n", level, id, debugstr_w(diW->pName));

                    COPY_STRING(pName);
                    break;
                }
            case 2:
                {
                    DRIVER_INFO_2W * diW = (DRIVER_INFO_2W *) pDriversW;
                    DRIVER_INFO_2A * diA = (DRIVER_INFO_2A *) out;

                    TRACE("(%u) #%u: %s\n", level, id, debugstr_w(diW->pName));

                    COPY_STRING(pName);
                    COPY_STRING(pEnvironment);
                    COPY_STRING(pDriverPath);
                    COPY_STRING(pDataFile);
                    COPY_STRING(pConfigFile);
                    break;
                }
            case 3:
                {
                    DRIVER_INFO_3W * diW = (DRIVER_INFO_3W *) pDriversW;
                    DRIVER_INFO_3A * diA = (DRIVER_INFO_3A *) out;

                    TRACE("(%u) #%u: %s\n", level, id, debugstr_w(diW->pName));

                    COPY_STRING(pName);
                    COPY_STRING(pEnvironment);
                    COPY_STRING(pDriverPath);
                    COPY_STRING(pDataFile);
                    COPY_STRING(pConfigFile);
                    COPY_STRING(pHelpFile);
                    COPY_MULTIZ_STRING(pDependentFiles);
                    COPY_STRING(pMonitorName);
                    COPY_STRING(pDefaultDataType);
                    break;
                }
            case 4:
                {
                    DRIVER_INFO_4W * diW = (DRIVER_INFO_4W *) pDriversW;
                    DRIVER_INFO_4A * diA = (DRIVER_INFO_4A *) out;

                    TRACE("(%u) #%u: %s\n", level, id, debugstr_w(diW->pName));

                    COPY_STRING(pName);
                    COPY_STRING(pEnvironment);
                    COPY_STRING(pDriverPath);
                    COPY_STRING(pDataFile);
                    COPY_STRING(pConfigFile);
                    COPY_STRING(pHelpFile);
                    COPY_MULTIZ_STRING(pDependentFiles);
                    COPY_STRING(pMonitorName);
                    COPY_STRING(pDefaultDataType);
                    COPY_MULTIZ_STRING(pszzPreviousNames);
                    break;
                }
            case 5:
                {
                    DRIVER_INFO_5W * diW = (DRIVER_INFO_5W *) pDriversW;
                    DRIVER_INFO_5A * diA = (DRIVER_INFO_5A *) out;

                    TRACE("(%u) #%u: %s\n", level, id, debugstr_w(diW->pName));

                    COPY_STRING(pName);
                    COPY_STRING(pEnvironment);
                    COPY_STRING(pDriverPath);
                    COPY_STRING(pDataFile);
                    COPY_STRING(pConfigFile);
                    break;
                }
            case 6:
                {
                    DRIVER_INFO_6W * diW = (DRIVER_INFO_6W *) pDriversW;
                    DRIVER_INFO_6A * diA = (DRIVER_INFO_6A *) out;

                    TRACE("(%u) #%u: %s\n", level, id, debugstr_w(diW->pName));

                    COPY_STRING(pName);
                    COPY_STRING(pEnvironment);
                    COPY_STRING(pDriverPath);
                    COPY_STRING(pDataFile);
                    COPY_STRING(pConfigFile);
                    COPY_STRING(pHelpFile);
                    COPY_MULTIZ_STRING(pDependentFiles);
                    COPY_STRING(pMonitorName);
                    COPY_STRING(pDefaultDataType);
                    COPY_MULTIZ_STRING(pszzPreviousNames);
                    COPY_STRING(pszMfgName);
                    COPY_STRING(pszOEMUrl);
                    COPY_STRING(pszHardwareID);
                    COPY_STRING(pszProvider);
                    break;
                }
            case 8:
                {
                    DRIVER_INFO_8W * diW = (DRIVER_INFO_8W *) pDriversW;
                    DRIVER_INFO_8A * diA = (DRIVER_INFO_8A *) out;

                    TRACE("(%u) #%u: %s\n", level, id, debugstr_w(diW->pName));

                    COPY_STRING(pName);
                    COPY_STRING(pEnvironment);
                    COPY_STRING(pDriverPath);
                    COPY_STRING(pDataFile);
                    COPY_STRING(pConfigFile);
                    COPY_STRING(pHelpFile);
                    COPY_MULTIZ_STRING(pDependentFiles);
                    COPY_STRING(pMonitorName);
                    COPY_STRING(pDefaultDataType);
                    COPY_MULTIZ_STRING(pszzPreviousNames);
                    COPY_STRING(pszMfgName);
                    COPY_STRING(pszOEMUrl);
                    COPY_STRING(pszHardwareID);
                    COPY_STRING(pszProvider);
                    COPY_STRING(pszPrintProcessor);
                    COPY_STRING(pszVendorSetup);
                    COPY_MULTIZ_STRING(pszzColorProfiles);
                    COPY_STRING(pszInfPath);
                    COPY_MULTIZ_STRING(pszzCoreDriverDependencies);
                    break;
                }


            default:
                FIXME("for level %u\n", level);
        }

        pDriversW += di_sizeof[level];
        out += di_sizeof[level];
        id++;

    }
#undef COPY_STRING
#undef COPY_MULTIZ_STRING
}


2225
/***********************************************************
2226
 *             printer_info_AtoW
2227
 */
2228
static void *printer_info_AtoW( const void *data, DWORD level )
2229
{
2230
    void *ret;
2231 2232
    UNICODE_STRING usBuffer;

2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280
    if (!data) return NULL;

    if (level < 1 || level > 9) return NULL;

    ret = HeapAlloc( GetProcessHeap(), 0, pi_sizeof[level] );
    if (!ret) return NULL;

    memcpy( ret, data, pi_sizeof[level] ); /* copy everything first */

    switch (level)
    {
    case 2:
    {
        const PRINTER_INFO_2A *piA = (const PRINTER_INFO_2A *)data;
        PRINTER_INFO_2W *piW = (PRINTER_INFO_2W *)ret;

        piW->pServerName = asciitounicode( &usBuffer, piA->pServerName );
        piW->pPrinterName = asciitounicode( &usBuffer, piA->pPrinterName );
        piW->pShareName = asciitounicode( &usBuffer, piA->pShareName );
        piW->pPortName = asciitounicode( &usBuffer, piA->pPortName );
        piW->pDriverName = asciitounicode( &usBuffer, piA->pDriverName );
        piW->pComment = asciitounicode( &usBuffer, piA->pComment );
        piW->pLocation = asciitounicode( &usBuffer, piA->pLocation );
        piW->pDevMode = piA->pDevMode ? GdiConvertToDevmodeW( piA->pDevMode ) : NULL;
        piW->pSepFile = asciitounicode( &usBuffer, piA->pSepFile );
        piW->pPrintProcessor = asciitounicode( &usBuffer, piA->pPrintProcessor );
        piW->pDatatype = asciitounicode( &usBuffer, piA->pDatatype );
        piW->pParameters = asciitounicode( &usBuffer, piA->pParameters );
        break;
    }

    case 8:
    case 9:
    {
        const PRINTER_INFO_9A *piA = (const PRINTER_INFO_9A *)data;
        PRINTER_INFO_9W *piW = (PRINTER_INFO_9W *)ret;

        piW->pDevMode = piA->pDevMode ? GdiConvertToDevmodeW( piA->pDevMode ) : NULL;
        break;
    }

    default:
        FIXME( "Unhandled level %d\n", level );
        HeapFree( GetProcessHeap(), 0, ret );
        return NULL;
    }

    return ret;
2281 2282 2283
}

/***********************************************************
2284
 *       free_printer_info
2285
 */
2286
static void free_printer_info( void *data, DWORD level )
2287
{
2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324
    if (!data) return;

    switch (level)
    {
    case 2:
    {
        PRINTER_INFO_2W *piW = (PRINTER_INFO_2W *)data;

        HeapFree( GetProcessHeap(), 0, piW->pServerName );
        HeapFree( GetProcessHeap(), 0, piW->pPrinterName );
        HeapFree( GetProcessHeap(), 0, piW->pShareName );
        HeapFree( GetProcessHeap(), 0, piW->pPortName );
        HeapFree( GetProcessHeap(), 0, piW->pDriverName );
        HeapFree( GetProcessHeap(), 0, piW->pComment );
        HeapFree( GetProcessHeap(), 0, piW->pLocation );
        HeapFree( GetProcessHeap(), 0, piW->pDevMode );
        HeapFree( GetProcessHeap(), 0, piW->pSepFile );
        HeapFree( GetProcessHeap(), 0, piW->pPrintProcessor );
        HeapFree( GetProcessHeap(), 0, piW->pDatatype );
        HeapFree( GetProcessHeap(), 0, piW->pParameters );
        break;
    }

    case 8:
    case 9:
    {
        PRINTER_INFO_9W *piW = (PRINTER_INFO_9W *)data;

        HeapFree( GetProcessHeap(), 0, piW->pDevMode );
        break;
    }

    default:
        FIXME( "Unhandled level %d\n", level );
    }

    HeapFree( GetProcessHeap(), 0, data );
2325 2326 2327
    return;
}

2328
/******************************************************************
Patrik Stridvall's avatar
Patrik Stridvall committed
2329 2330
 *              DeviceCapabilities     [WINSPOOL.@]
 *              DeviceCapabilitiesA    [WINSPOOL.@]
2331 2332
 *
 */
Andreas Mohr's avatar
Andreas Mohr committed
2333
INT WINAPI DeviceCapabilitiesA(LPCSTR pDevice,LPCSTR pPort, WORD cap,
2334 2335
			       LPSTR pOutput, LPDEVMODEA lpdm)
{
2336
    INT ret;
2337

2338 2339
    TRACE("%s,%s,%u,%p,%p\n", debugstr_a(pDevice), debugstr_a(pPort), cap, pOutput, lpdm);

2340 2341 2342 2343 2344 2345
    if (!GDI_CallDeviceCapabilities16)
    {
        GDI_CallDeviceCapabilities16 = (void*)GetProcAddress( GetModuleHandleA("gdi32"),
                                                              (LPCSTR)104 );
        if (!GDI_CallDeviceCapabilities16) return -1;
    }
Andreas Mohr's avatar
Andreas Mohr committed
2346
    ret = GDI_CallDeviceCapabilities16(pDevice, pPort, cap, pOutput, lpdm);
2347 2348 2349 2350

    /* If DC_PAPERSIZE map POINT16s to POINTs */
    if(ret != -1 && cap == DC_PAPERSIZE && pOutput) {
        POINT16 *tmp = HeapAlloc( GetProcessHeap(), 0, ret * sizeof(POINT16) );
2351
        POINT *pt = (POINT *)pOutput;
2352 2353
	INT i;
	memcpy(tmp, pOutput, ret * sizeof(POINT16));
2354 2355 2356 2357 2358
	for(i = 0; i < ret; i++, pt++)
        {
            pt->x = tmp[i].x;
            pt->y = tmp[i].y;
        }
2359 2360 2361
	HeapFree( GetProcessHeap(), 0, tmp );
    }
    return ret;
2362 2363 2364 2365
}


/*****************************************************************************
2366
 *          DeviceCapabilitiesW        [WINSPOOL.@]
2367 2368 2369
 *
 * Call DeviceCapabilitiesA since we later call 16bit stuff anyway
 *
2370 2371 2372 2373 2374
 */
INT WINAPI DeviceCapabilitiesW(LPCWSTR pDevice, LPCWSTR pPort,
			       WORD fwCapability, LPWSTR pOutput,
			       const DEVMODEW *pDevMode)
{
2375
    LPDEVMODEA dmA = DEVMODEdupWtoA(pDevMode);
2376 2377
    LPSTR pDeviceA = strdupWtoA(pDevice);
    LPSTR pPortA = strdupWtoA(pPort);
2378 2379
    INT ret;

2380 2381
    TRACE("%s,%s,%u,%p,%p\n", debugstr_w(pDevice), debugstr_w(pPort), fwCapability, pOutput, pDevMode);

2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415
    if(pOutput && (fwCapability == DC_BINNAMES ||
		   fwCapability == DC_FILEDEPENDENCIES ||
		   fwCapability == DC_PAPERNAMES)) {
      /* These need A -> W translation */
        INT size = 0, i;
	LPSTR pOutputA;
        ret = DeviceCapabilitiesA(pDeviceA, pPortA, fwCapability, NULL,
				  dmA);
	if(ret == -1)
	    return ret;
	switch(fwCapability) {
	case DC_BINNAMES:
	    size = 24;
	    break;
	case DC_PAPERNAMES:
	case DC_FILEDEPENDENCIES:
	    size = 64;
	    break;
	}
	pOutputA = HeapAlloc(GetProcessHeap(), 0, size * ret);
	ret = DeviceCapabilitiesA(pDeviceA, pPortA, fwCapability, pOutputA,
				  dmA);
	for(i = 0; i < ret; i++)
	    MultiByteToWideChar(CP_ACP, 0, pOutputA + (i * size), -1,
				pOutput + (i * size), size);
	HeapFree(GetProcessHeap(), 0, pOutputA);
    } else {
        ret = DeviceCapabilitiesA(pDeviceA, pPortA, fwCapability,
				  (LPSTR)pOutput, dmA);
    }
    HeapFree(GetProcessHeap(),0,pPortA);
    HeapFree(GetProcessHeap(),0,pDeviceA);
    HeapFree(GetProcessHeap(),0,dmA);
    return ret;
2416 2417 2418
}

/******************************************************************
2419
 *              DocumentPropertiesA   [WINSPOOL.@]
2420
 *
2421
 * FIXME: implement DocumentPropertiesA via DocumentPropertiesW, not vice versa
2422 2423 2424 2425 2426
 */
LONG WINAPI DocumentPropertiesA(HWND hWnd,HANDLE hPrinter,
                                LPSTR pDeviceName, LPDEVMODEA pDevModeOutput,
				LPDEVMODEA pDevModeInput,DWORD fMode )
{
2427
    LPSTR lpName = pDeviceName, dupname = NULL;
2428
    static CHAR port[] = "LPT1:";
2429
    LONG ret;
2430

2431
    TRACE("(%p,%p,%s,%p,%p,%d)\n",
2432 2433 2434
	hWnd,hPrinter,pDeviceName,pDevModeOutput,pDevModeInput,fMode
    );

2435
    if(!pDeviceName || !*pDeviceName) {
2436
        LPCWSTR lpNameW = get_opened_printer_name(hPrinter);
2437 2438
        if(!lpNameW) {
		ERR("no name from hPrinter?\n");
2439
                SetLastError(ERROR_INVALID_HANDLE);
2440 2441
		return -1;
	}
2442
	lpName = dupname = strdupWtoA(lpNameW);
2443 2444
    }

2445 2446 2447 2448
    if (!GDI_CallExtDeviceMode16)
    {
        GDI_CallExtDeviceMode16 = (void*)GetProcAddress( GetModuleHandleA("gdi32"),
                                                         (LPCSTR)102 );
2449 2450
        if (!GDI_CallExtDeviceMode16) {
		ERR("No CallExtDeviceMode16?\n");
2451 2452
		ret = -1;
		goto end;
2453
	}
2454
    }
2455
    ret = GDI_CallExtDeviceMode16(hWnd, pDevModeOutput, lpName, port,
2456
				  pDevModeInput, NULL, fMode);
2457

2458 2459
end:
    HeapFree(GetProcessHeap(), 0, dupname);
2460
    return ret;
2461 2462 2463 2464
}


/*****************************************************************************
2465
 *          DocumentPropertiesW (WINSPOOL.@)
2466 2467
 *
 * FIXME: implement DocumentPropertiesA via DocumentPropertiesW, not vice versa
2468 2469
 */
LONG WINAPI DocumentPropertiesW(HWND hWnd, HANDLE hPrinter,
2470 2471 2472
				LPWSTR pDeviceName,
				LPDEVMODEW pDevModeOutput,
				LPDEVMODEW pDevModeInput, DWORD fMode)
2473
{
2474

2475
    LPSTR pDeviceNameA = strdupWtoA(pDeviceName);
2476
    LPDEVMODEA pDevModeInputA;
2477 2478 2479
    LPDEVMODEA pDevModeOutputA = NULL;
    LONG ret;

2480
    TRACE("(%p,%p,%s,%p,%p,%d)\n",
2481 2482
          hWnd,hPrinter,debugstr_w(pDeviceName),pDevModeOutput,pDevModeInput,
	  fMode);
2483 2484 2485 2486 2487
    if(pDevModeOutput) {
        ret = DocumentPropertiesA(hWnd, hPrinter, pDeviceNameA, NULL, NULL, 0);
	if(ret < 0) return ret;
	pDevModeOutputA = HeapAlloc(GetProcessHeap(), 0, ret);
    }
2488
    pDevModeInputA = (fMode & DM_IN_BUFFER) ? DEVMODEdupWtoA(pDevModeInput) : NULL;
2489 2490 2491 2492 2493 2494 2495 2496 2497
    ret = DocumentPropertiesA(hWnd, hPrinter, pDeviceNameA, pDevModeOutputA,
			      pDevModeInputA, fMode);
    if(pDevModeOutput) {
        DEVMODEcpyAtoW(pDevModeOutput, pDevModeOutputA);
	HeapFree(GetProcessHeap(),0,pDevModeOutputA);
    }
    if(fMode == 0 && ret > 0)
        ret += (CCHDEVICENAME + CCHFORMNAME);
    HeapFree(GetProcessHeap(),0,pDevModeInputA);
2498
    HeapFree(GetProcessHeap(),0,pDeviceNameA);
2499
    return ret;
2500 2501
}

2502 2503 2504 2505 2506 2507
/*****************************************************************************
 *          IsValidDevmodeA            [WINSPOOL.@]
 *
 * Validate a DEVMODE structure and fix errors if possible.
 *
 */
2508
BOOL WINAPI IsValidDevmodeA(PDEVMODEA pDevMode, SIZE_T size)
2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523
{
    FIXME("(%p,%ld): stub\n", pDevMode, size);

    if(!pDevMode)
        return FALSE;

    return TRUE;
}

/*****************************************************************************
 *          IsValidDevmodeW            [WINSPOOL.@]
 *
 * Validate a DEVMODE structure and fix errors if possible.
 *
 */
2524
BOOL WINAPI IsValidDevmodeW(PDEVMODEW dm, SIZE_T size)
2525
{
2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572
    static const struct
    {
        DWORD flag;
        SIZE_T size;
    } map[] =
    {
#define F_SIZE(field) FIELD_OFFSET(DEVMODEW, field) + sizeof(dm->field)
        { DM_ORIENTATION, F_SIZE(u1.s1.dmOrientation) },
        { DM_PAPERSIZE, F_SIZE(u1.s1.dmPaperSize) },
        { DM_PAPERLENGTH, F_SIZE(u1.s1.dmPaperLength) },
        { DM_PAPERWIDTH, F_SIZE(u1.s1.dmPaperWidth) },
        { DM_SCALE, F_SIZE(u1.s1.dmScale) },
        { DM_COPIES, F_SIZE(u1.s1.dmCopies) },
        { DM_DEFAULTSOURCE, F_SIZE(u1.s1.dmDefaultSource) },
        { DM_PRINTQUALITY, F_SIZE(u1.s1.dmPrintQuality) },
        { DM_POSITION, F_SIZE(u1.s2.dmPosition) },
        { DM_DISPLAYORIENTATION, F_SIZE(u1.s2.dmDisplayOrientation) },
        { DM_DISPLAYFIXEDOUTPUT, F_SIZE(u1.s2.dmDisplayFixedOutput) },
        { DM_COLOR, F_SIZE(dmColor) },
        { DM_DUPLEX, F_SIZE(dmDuplex) },
        { DM_YRESOLUTION, F_SIZE(dmYResolution) },
        { DM_TTOPTION, F_SIZE(dmTTOption) },
        { DM_COLLATE, F_SIZE(dmCollate) },
        { DM_FORMNAME, F_SIZE(dmFormName) },
        { DM_LOGPIXELS, F_SIZE(dmLogPixels) },
        { DM_BITSPERPEL, F_SIZE(dmBitsPerPel) },
        { DM_PELSWIDTH, F_SIZE(dmPelsWidth) },
        { DM_PELSHEIGHT, F_SIZE(dmPelsHeight) },
        { DM_DISPLAYFLAGS, F_SIZE(u2.dmDisplayFlags) },
        { DM_NUP, F_SIZE(u2.dmNup) },
        { DM_DISPLAYFREQUENCY, F_SIZE(dmDisplayFrequency) },
        { DM_ICMMETHOD, F_SIZE(dmICMMethod) },
        { DM_ICMINTENT, F_SIZE(dmICMIntent) },
        { DM_MEDIATYPE, F_SIZE(dmMediaType) },
        { DM_DITHERTYPE, F_SIZE(dmDitherType) },
        { DM_PANNINGWIDTH, F_SIZE(dmPanningWidth) },
        { DM_PANNINGHEIGHT, F_SIZE(dmPanningHeight) }
#undef F_SIZE
    };
    int i;

    if (!dm) return FALSE;
    if (size < FIELD_OFFSET(DEVMODEW, dmFields) + sizeof(dm->dmFields)) return FALSE;

    for (i = 0; i < ARRAY_SIZE(map); i++)
        if ((dm->dmFields & map[i].flag) && size < map[i].size)
            return FALSE;
2573 2574 2575 2576

    return TRUE;
}

2577
/******************************************************************
2578
 *              OpenPrinterA        [WINSPOOL.@]
2579
 *
2580 2581
 * See OpenPrinterW.
 *
2582 2583
 */
BOOL WINAPI OpenPrinterA(LPSTR lpPrinterName,HANDLE *phPrinter,
2584
			 LPPRINTER_DEFAULTSA pDefault)
2585
{
2586 2587
    UNICODE_STRING lpPrinterNameW;
    UNICODE_STRING usBuffer;
2588
    PRINTER_DEFAULTSW DefaultW, *pDefaultW = NULL;
2589
    PWSTR pwstrPrinterNameW;
2590
    BOOL ret;
2591

2592 2593
    TRACE("%s,%p,%p\n", debugstr_a(lpPrinterName), phPrinter, pDefault);

2594
    pwstrPrinterNameW = asciitounicode(&lpPrinterNameW,lpPrinterName);
2595

2596
    if(pDefault) {
2597
        DefaultW.pDatatype = asciitounicode(&usBuffer,pDefault->pDatatype);
2598
	DefaultW.pDevMode = pDefault->pDevMode ? GdiConvertToDevmodeW(pDefault->pDevMode) : NULL;
2599 2600 2601
	DefaultW.DesiredAccess = pDefault->DesiredAccess;
	pDefaultW = &DefaultW;
    }
2602
    ret = OpenPrinterW(pwstrPrinterNameW, phPrinter, pDefaultW);
2603
    if(pDefault) {
2604
        RtlFreeUnicodeString(&usBuffer);
2605 2606
	HeapFree(GetProcessHeap(), 0, DefaultW.pDevMode);
    }
2607
    RtlFreeUnicodeString(&lpPrinterNameW);
2608 2609 2610 2611
    return ret;
}

/******************************************************************
2612
 *              OpenPrinterW        [WINSPOOL.@]
2613
 *
2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634
 * Open a Printer / Printserver or a Printer-Object
 *
 * PARAMS
 *  lpPrinterName [I] Name of Printserver, Printer, or Printer-Object
 *  phPrinter     [O] The resulting Handle is stored here
 *  pDefault      [I] PTR to Default Printer Settings or NULL
 *
 * RETURNS
 *  Success: TRUE
 *  Failure: FALSE
 *
 * NOTES
 *  lpPrinterName is one of:
 *|  Printserver (NT only): "Servername" or NULL for the local Printserver
 *|  Printer: "PrinterName"
 *|  Printer-Object: "PrinterName,Job xxx"
 *|  XcvMonitor: "Servername,XcvMonitor MonitorName"
 *|  XcvPort: "Servername,XcvPort PortName"
 *
 * BUGS
 *|  Printer-Object not supported
2635
 *|  pDefaults is ignored
2636
 *
2637
 */
2638
BOOL WINAPI OpenPrinterW(LPWSTR lpPrinterName,HANDLE *phPrinter, LPPRINTER_DEFAULTSW pDefault)
2639
{
2640
    HKEY key;
2641

2642
    TRACE("(%s, %p, %p)\n", debugstr_w(lpPrinterName), phPrinter, pDefault);
2643

2644 2645 2646 2647
    if(!phPrinter) {
        /* NT: FALSE with ERROR_INVALID_PARAMETER, 9x: TRUE */
        SetLastError(ERROR_INVALID_PARAMETER);
        return FALSE;
2648
    }
2649

2650 2651
    /* Get the unique handle of the printer or Printserver */
    *phPrinter = get_opened_printer_entry(lpPrinterName, pDefault);
2652

2653
    if (*phPrinter && WINSPOOL_GetOpenedPrinterRegKey( *phPrinter, &key ) == ERROR_SUCCESS)
2654 2655 2656 2657
    {
        DWORD deleting = 0, size = sizeof( deleting ), type;
        DWORD status;
        RegQueryValueExW( key, May_Delete_Value, NULL, &type, (LPBYTE)&deleting, &size );
2658
        WaitForSingleObject( init_mutex, INFINITE );
2659
        status = get_dword_from_reg( key, StatusW );
2660 2661
        set_reg_DWORD( key, StatusW, status & ~PRINTER_STATUS_DRIVER_UPDATE_NEEDED );
        ReleaseMutex( init_mutex );
2662 2663 2664 2665 2666
        if (!deleting && (status & PRINTER_STATUS_DRIVER_UPDATE_NEEDED))
            update_driver( *phPrinter );
        RegCloseKey( key );
    }

2667
    TRACE("returning %d with %u and %p\n", *phPrinter != NULL, GetLastError(), *phPrinter);
2668
    return (*phPrinter != 0);
2669 2670 2671
}

/******************************************************************
2672
 *              AddMonitorA        [WINSPOOL.@]
2673
 *
2674 2675
 * See AddMonitorW.
 *
2676
 */
2677
BOOL WINAPI AddMonitorA(LPSTR pName, DWORD Level, LPBYTE pMonitors)
2678
{
2679 2680 2681 2682 2683 2684 2685
    LPWSTR  nameW = NULL;
    INT     len;
    BOOL    res;
    LPMONITOR_INFO_2A mi2a;
    MONITOR_INFO_2W mi2w;

    mi2a = (LPMONITOR_INFO_2A) pMonitors;
2686 2687 2688 2689
    TRACE("(%s, %d, %p) :  %s %s %s\n", debugstr_a(pName), Level, pMonitors,
          debugstr_a(mi2a ? mi2a->pName : NULL),
          debugstr_a(mi2a ? mi2a->pEnvironment : NULL),
          debugstr_a(mi2a ? mi2a->pDLLName : NULL));
2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731

    if  (Level != 2) {
        SetLastError(ERROR_INVALID_LEVEL);
        return FALSE;
    }

    /* XP: unchanged, win9x: ERROR_INVALID_ENVIRONMENT */
    if (mi2a == NULL) {
        return FALSE;
    }

    if (pName) {
        len = MultiByteToWideChar(CP_ACP, 0, pName, -1, NULL, 0);
        nameW = HeapAlloc(GetProcessHeap(), 0, len * sizeof(WCHAR));
        MultiByteToWideChar(CP_ACP, 0, pName, -1, nameW, len);
    }

    memset(&mi2w, 0, sizeof(MONITOR_INFO_2W));
    if (mi2a->pName) {
        len = MultiByteToWideChar(CP_ACP, 0, mi2a->pName, -1, NULL, 0);
        mi2w.pName = HeapAlloc(GetProcessHeap(), 0, len * sizeof(WCHAR));
        MultiByteToWideChar(CP_ACP, 0, mi2a->pName, -1, mi2w.pName, len);
    }
    if (mi2a->pEnvironment) {
        len = MultiByteToWideChar(CP_ACP, 0, mi2a->pEnvironment, -1, NULL, 0);
        mi2w.pEnvironment = HeapAlloc(GetProcessHeap(), 0, len * sizeof(WCHAR));
        MultiByteToWideChar(CP_ACP, 0, mi2a->pEnvironment, -1, mi2w.pEnvironment, len);
    }
    if (mi2a->pDLLName) {
        len = MultiByteToWideChar(CP_ACP, 0, mi2a->pDLLName, -1, NULL, 0);
        mi2w.pDLLName = HeapAlloc(GetProcessHeap(), 0, len * sizeof(WCHAR));
        MultiByteToWideChar(CP_ACP, 0, mi2a->pDLLName, -1, mi2w.pDLLName, len);
    }

    res = AddMonitorW(nameW, Level, (LPBYTE) &mi2w);

    HeapFree(GetProcessHeap(), 0, mi2w.pName); 
    HeapFree(GetProcessHeap(), 0, mi2w.pEnvironment); 
    HeapFree(GetProcessHeap(), 0, mi2w.pDLLName); 

    HeapFree(GetProcessHeap(), 0, nameW); 
    return (res);
2732 2733 2734 2735
}

/******************************************************************************
 *              AddMonitorW        [WINSPOOL.@]
2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750
 *
 * Install a Printmonitor
 *
 * PARAMS
 *  pName       [I] Servername or NULL (local Computer)
 *  Level       [I] Structure-Level (Must be 2)
 *  pMonitors   [I] PTR to MONITOR_INFO_2
 *
 * RETURNS
 *  Success: TRUE
 *  Failure: FALSE
 *
 * NOTES
 *  All Files for the Monitor must already be copied to %winsysdir% ("%SystemRoot%\system32")
 *
2751 2752 2753
 */
BOOL WINAPI AddMonitorW(LPWSTR pName, DWORD Level, LPBYTE pMonitors)
{
2754 2755 2756
    LPMONITOR_INFO_2W mi2w;

    mi2w = (LPMONITOR_INFO_2W) pMonitors;
2757 2758 2759 2760
    TRACE("(%s, %d, %p) :  %s %s %s\n", debugstr_w(pName), Level, pMonitors,
          debugstr_w(mi2w ? mi2w->pName : NULL),
          debugstr_w(mi2w ? mi2w->pEnvironment : NULL),
          debugstr_w(mi2w ? mi2w->pDLLName : NULL));
2761

2762 2763
    if ((backend == NULL)  && !load_backend()) return FALSE;

2764 2765 2766 2767 2768 2769 2770 2771 2772 2773
    if (Level != 2) {
        SetLastError(ERROR_INVALID_LEVEL);
        return FALSE;
    }

    /* XP: unchanged, win9x: ERROR_INVALID_ENVIRONMENT */
    if (mi2w == NULL) {
        return FALSE;
    }

2774
    return backend->fpAddMonitor(pName, Level, pMonitors);
2775 2776 2777
}

/******************************************************************
2778
 *              DeletePrinterDriverA        [WINSPOOL.@]
2779 2780
 *
 */
2781
BOOL WINAPI DeletePrinterDriverA (LPSTR pName, LPSTR pEnvironment, LPSTR pDriverName)
2782
{
2783
    return DeletePrinterDriverExA(pName, pEnvironment, pDriverName, 0, 0);
2784 2785
}

2786 2787 2788 2789
/******************************************************************
 *              DeletePrinterDriverW        [WINSPOOL.@]
 *
 */
2790
BOOL WINAPI DeletePrinterDriverW (LPWSTR pName, LPWSTR pEnvironment, LPWSTR pDriverName)
2791
{
2792
    return DeletePrinterDriverExW(pName, pEnvironment, pDriverName, 0, 0);
2793
}
2794 2795

/******************************************************************
2796
 *              DeleteMonitorA        [WINSPOOL.@]
2797
 *
2798 2799
 * See DeleteMonitorW.
 *
2800
 */
2801
BOOL WINAPI DeleteMonitorA (LPSTR pName, LPSTR pEnvironment, LPSTR pMonitorName)
2802
{
2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831
    LPWSTR  nameW = NULL;
    LPWSTR  EnvironmentW = NULL;
    LPWSTR  MonitorNameW = NULL;
    BOOL    res;
    INT     len;

    if (pName) {
        len = MultiByteToWideChar(CP_ACP, 0, pName, -1, NULL, 0);
        nameW = HeapAlloc(GetProcessHeap(), 0, len * sizeof(WCHAR));
        MultiByteToWideChar(CP_ACP, 0, pName, -1, nameW, len);
    }

    if (pEnvironment) {
        len = MultiByteToWideChar(CP_ACP, 0, pEnvironment, -1, NULL, 0);
        EnvironmentW = HeapAlloc(GetProcessHeap(), 0, len * sizeof(WCHAR));
        MultiByteToWideChar(CP_ACP, 0, pEnvironment, -1, EnvironmentW, len);
    }
    if (pMonitorName) {
        len = MultiByteToWideChar(CP_ACP, 0, pMonitorName, -1, NULL, 0);
        MonitorNameW = HeapAlloc(GetProcessHeap(), 0, len * sizeof(WCHAR));
        MultiByteToWideChar(CP_ACP, 0, pMonitorName, -1, MonitorNameW, len);
    }

    res = DeleteMonitorW(nameW, EnvironmentW, MonitorNameW);

    HeapFree(GetProcessHeap(), 0, MonitorNameW); 
    HeapFree(GetProcessHeap(), 0, EnvironmentW);
    HeapFree(GetProcessHeap(), 0, nameW); 
    return (res);
2832 2833
}

2834 2835 2836
/******************************************************************
 *              DeleteMonitorW        [WINSPOOL.@]
 *
2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847
 * Delete a specific Printmonitor from a Printing-Environment
 *
 * PARAMS
 *  pName        [I] Servername or NULL (local Computer)
 *  pEnvironment [I] Printing-Environment of the Monitor or NULL (Default)
 *  pMonitorName [I] Name of the Monitor, that should be deleted
 *
 * RETURNS
 *  Success: TRUE
 *  Failure: FALSE
 *
2848 2849
 * NOTES
 *  pEnvironment is ignored in Windows for the local Computer.
2850
 *
2851
 */
2852
BOOL WINAPI DeleteMonitorW(LPWSTR pName, LPWSTR pEnvironment, LPWSTR pMonitorName)
2853
{
2854 2855 2856 2857

    TRACE("(%s, %s, %s)\n",debugstr_w(pName),debugstr_w(pEnvironment),
           debugstr_w(pMonitorName));

2858
    if ((backend == NULL)  && !load_backend()) return FALSE;
2859

2860
    return backend->fpDeleteMonitor(pName, pEnvironment, pMonitorName);
2861
}
2862

2863

2864
/******************************************************************
2865
 *              DeletePortA        [WINSPOOL.@]
2866
 *
2867 2868
 * See DeletePortW.
 *
2869
 */
2870
BOOL WINAPI DeletePortA (LPSTR pName, HWND hWnd, LPSTR pPortName)
2871
{
2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896
    LPWSTR  nameW = NULL;
    LPWSTR  portW = NULL;
    INT     len;
    DWORD   res;

    TRACE("(%s, %p, %s)\n", debugstr_a(pName), hWnd, debugstr_a(pPortName));

    /* convert servername to unicode */
    if (pName) {
        len = MultiByteToWideChar(CP_ACP, 0, pName, -1, NULL, 0);
        nameW = HeapAlloc(GetProcessHeap(), 0, len * sizeof(WCHAR));
        MultiByteToWideChar(CP_ACP, 0, pName, -1, nameW, len);
    }

    /* convert portname to unicode */
    if (pPortName) {
        len = MultiByteToWideChar(CP_ACP, 0, pPortName, -1, NULL, 0);
        portW = HeapAlloc(GetProcessHeap(), 0, len * sizeof(WCHAR));
        MultiByteToWideChar(CP_ACP, 0, pPortName, -1, portW, len);
    }

    res = DeletePortW(nameW, hWnd, portW);
    HeapFree(GetProcessHeap(), 0, nameW);
    HeapFree(GetProcessHeap(), 0, portW);
    return res;
2897 2898
}

2899 2900 2901
/******************************************************************
 *              DeletePortW        [WINSPOOL.@]
 *
2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912
 * Delete a specific Port
 *
 * PARAMS
 *  pName     [I] Servername or NULL (local Computer)
 *  hWnd      [I] Handle to parent Window for the Dialog-Box
 *  pPortName [I] Name of the Port, that should be deleted
 *
 * RETURNS
 *  Success: TRUE
 *  Failure: FALSE
 *
2913
 */
2914
BOOL WINAPI DeletePortW (LPWSTR pName, HWND hWnd, LPWSTR pPortName)
2915
{
2916 2917
    TRACE("(%s, %p, %s)\n", debugstr_w(pName), hWnd, debugstr_w(pPortName));

2918
    if ((backend == NULL)  && !load_backend()) return FALSE;
2919 2920 2921 2922 2923 2924

    if (!pPortName) {
        SetLastError(RPC_X_NULL_REF_POINTER);
        return FALSE;
    }

2925
    return backend->fpDeletePort(pName, hWnd, pPortName);
2926 2927
}

2928
/******************************************************************************
2929
 *    WritePrinter  [WINSPOOL.@]
2930
 */
2931 2932 2933 2934
BOOL WINAPI WritePrinter(HANDLE hPrinter, LPVOID pBuf, DWORD cbBuf, LPDWORD pcWritten)
{
    opened_printer_t *printer;
    BOOL ret = FALSE;
2935

2936
    TRACE("(%p, %p, %d, %p)\n", hPrinter, pBuf, cbBuf, pcWritten);
2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955

    EnterCriticalSection(&printer_handles_cs);
    printer = get_opened_printer(hPrinter);
    if(!printer)
    {
        SetLastError(ERROR_INVALID_HANDLE);
        goto end;
    }

    if(!printer->doc)
    {
        SetLastError(ERROR_SPL_NO_STARTDOC);
        goto end;
    }

    ret = WriteFile(printer->doc->hf, pBuf, cbBuf, pcWritten, NULL);
end:
    LeaveCriticalSection(&printer_handles_cs);
    return ret;
2956 2957 2958
}

/*****************************************************************************
2959
 *          AddFormA  [WINSPOOL.@]
2960 2961 2962
 */
BOOL WINAPI AddFormA(HANDLE hPrinter, DWORD Level, LPBYTE pForm)
{
2963
    FIXME("(%p,%d,%p): stub\n", hPrinter, Level, pForm);
2964
    return TRUE;
2965 2966 2967
}

/*****************************************************************************
2968
 *          AddFormW  [WINSPOOL.@]
2969
 */
2970
BOOL WINAPI AddFormW( HANDLE printer, DWORD level, BYTE *form )
2971
{
2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982
    HANDLE handle = get_backend_handle( printer );

    TRACE( "(%p, %d, %p)\n", printer, level, form );

    if (!handle)
    {
        SetLastError( ERROR_INVALID_HANDLE );
        return FALSE;
    }

    return backend->fpAddForm( handle, level, form );
2983 2984 2985
}

/*****************************************************************************
2986
 *          AddJobA  [WINSPOOL.@]
2987
 */
2988
BOOL WINAPI AddJobA(HANDLE hPrinter, DWORD Level, LPBYTE pData, DWORD cbBuf, LPDWORD pcbNeeded)
2989
{
2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015
    BOOL ret;
    BYTE buf[MAX_PATH * sizeof(WCHAR) + sizeof(ADDJOB_INFO_1W)];
    DWORD needed;

    if(Level != 1) {
        SetLastError(ERROR_INVALID_LEVEL);
        return FALSE;
    }

    ret = AddJobW(hPrinter, Level, buf, sizeof(buf), &needed);

    if(ret) {
        ADDJOB_INFO_1W *addjobW = (ADDJOB_INFO_1W*)buf;
        DWORD len = WideCharToMultiByte(CP_ACP, 0, addjobW->Path, -1, NULL, 0, NULL, NULL);
        *pcbNeeded = len + sizeof(ADDJOB_INFO_1A);
        if(*pcbNeeded > cbBuf) {
            SetLastError(ERROR_INSUFFICIENT_BUFFER);
            ret = FALSE;
        } else {
            ADDJOB_INFO_1A *addjobA = (ADDJOB_INFO_1A*)pData;
            addjobA->JobId = addjobW->JobId;
            addjobA->Path = (char *)(addjobA + 1);
            WideCharToMultiByte(CP_ACP, 0, addjobW->Path, -1, addjobA->Path, len, NULL, NULL);
        }
    }
    return ret;
3016 3017 3018
}

/*****************************************************************************
3019
 *          AddJobW  [WINSPOOL.@]
3020
 */
3021
BOOL WINAPI AddJobW(HANDLE hPrinter, DWORD Level, LPBYTE pData, DWORD cbBuf, LPDWORD pcbNeeded)
3022
{
3023 3024 3025 3026 3027 3028 3029 3030 3031
    opened_printer_t *printer;
    job_t *job;
    BOOL ret = FALSE;
    static const WCHAR spool_path[] = {'s','p','o','o','l','\\','P','R','I','N','T','E','R','S','\\',0};
    static const WCHAR fmtW[] = {'%','s','%','0','5','d','.','S','P','L',0};
    WCHAR path[MAX_PATH], filename[MAX_PATH];
    DWORD len;
    ADDJOB_INFO_1W *addjob;

3032
    TRACE("(%p,%d,%p,%d,%p)\n", hPrinter, Level, pData, cbBuf, pcbNeeded);
3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053
    
    EnterCriticalSection(&printer_handles_cs);

    printer = get_opened_printer(hPrinter);

    if(!printer) {
        SetLastError(ERROR_INVALID_HANDLE);
        goto end;
    }

    if(Level != 1) {
        SetLastError(ERROR_INVALID_LEVEL);
        goto end;
    }

    job = HeapAlloc(GetProcessHeap(), 0, sizeof(*job));
    if(!job)
        goto end;

    job->job_id = InterlockedIncrement(&next_job_id);

3054
    len = GetSystemDirectoryW(path, ARRAY_SIZE(path));
3055 3056 3057 3058 3059 3060 3061 3062
    if(path[len - 1] != '\\')
        path[len++] = '\\';
    memcpy(path + len, spool_path, sizeof(spool_path));    
    sprintfW(filename, fmtW, path, job->job_id);

    len = strlenW(filename);
    job->filename = HeapAlloc(GetProcessHeap(), 0, (len + 1) * sizeof(WCHAR));
    memcpy(job->filename, filename, (len + 1) * sizeof(WCHAR));
3063
    job->portname = NULL;
3064
    job->document_title = strdupW(default_doc_title);
3065
    job->printer_name = strdupW(printer->name);
3066
    job->devmode = dup_devmode( printer->devmode );
3067
    list_add_tail(&printer->queue->jobs, &job->entry);
3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081

    *pcbNeeded = (len + 1) * sizeof(WCHAR) + sizeof(*addjob);
    if(*pcbNeeded <= cbBuf) {
        addjob = (ADDJOB_INFO_1W*)pData;
        addjob->JobId = job->job_id;
        addjob->Path = (WCHAR *)(addjob + 1);
        memcpy(addjob->Path, filename, (len + 1) * sizeof(WCHAR));
        ret = TRUE;
    } else 
        SetLastError(ERROR_INSUFFICIENT_BUFFER);

end:
    LeaveCriticalSection(&printer_handles_cs);
    return ret;
3082 3083
}

3084 3085
/*****************************************************************************
 *          GetPrintProcessorDirectoryA  [WINSPOOL.@]
3086 3087 3088 3089 3090 3091
 *
 * Return the PATH for the Print-Processors
 *
 * See GetPrintProcessorDirectoryW.
 *
 *
3092
 */
Alexandre Julliard's avatar
Alexandre Julliard committed
3093
BOOL WINAPI GetPrintProcessorDirectoryA(LPSTR server, LPSTR env,
3094
                                        DWORD level,  LPBYTE Info,
3095
                                        DWORD cbBuf,  LPDWORD pcbNeeded)
3096
{
3097 3098 3099 3100 3101
    LPWSTR  serverW = NULL;
    LPWSTR  envW = NULL;
    BOOL    ret;
    INT     len;

3102
    TRACE("(%s, %s, %d, %p, %d, %p)\n", debugstr_a(server), 
3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127
          debugstr_a(env), level, Info, cbBuf, pcbNeeded);
 

    if (server) {
        len = MultiByteToWideChar(CP_ACP, 0, server, -1, NULL, 0);
        serverW = HeapAlloc(GetProcessHeap(), 0, len * sizeof(WCHAR));
        MultiByteToWideChar(CP_ACP, 0, server, -1, serverW, len);
    }

    if (env) {
        len = MultiByteToWideChar(CP_ACP, 0, env, -1, NULL, 0);
        envW = HeapAlloc(GetProcessHeap(), 0, len * sizeof(WCHAR));
        MultiByteToWideChar(CP_ACP, 0, env, -1, envW, len);
    }

    /* NT requires the buffersize from GetPrintProcessorDirectoryW also
       for GetPrintProcessorDirectoryA and WC2MB is done in-place.
     */
    ret = GetPrintProcessorDirectoryW(serverW, envW, level, Info, 
                                      cbBuf, pcbNeeded);

    if (ret) ret = WideCharToMultiByte(CP_ACP, 0, (LPWSTR)Info, -1, (LPSTR)Info,
                                       cbBuf, NULL, NULL) > 0;


3128
    TRACE(" required: 0x%x/%d\n", pcbNeeded ? *pcbNeeded : 0, pcbNeeded ? *pcbNeeded : 0);
3129 3130 3131
    HeapFree(GetProcessHeap(), 0, envW);
    HeapFree(GetProcessHeap(), 0, serverW);
    return ret;
3132 3133 3134 3135
}

/*****************************************************************************
 *          GetPrintProcessorDirectoryW  [WINSPOOL.@]
3136 3137 3138 3139 3140 3141 3142 3143 3144
 *
 * Return the PATH for the Print-Processors
 *
 * PARAMS
 *   server     [I] Servername (NT only) or NULL (local Computer)
 *   env        [I] Printing-Environment (see below) or NULL (Default)
 *   level      [I] Structure-Level (must be 1)
 *   Info       [O] PTR to Buffer that receives the Result
 *   cbBuf      [I] Size of Buffer at "Info"
3145
 *   pcbNeeded  [O] PTR to DWORD that receives the size in Bytes used / 
3146 3147 3148
 *                  required for the Buffer at "Info"
 *
 * RETURNS
3149 3150
 *   Success: TRUE  and in pcbNeeded the Bytes used in Info
 *   Failure: FALSE and in pcbNeeded the Bytes required for Info,
3151 3152
 *   if cbBuf is too small
 * 
3153
 *   Native Values returned in Info on Success:
3154 3155 3156 3157 3158 3159 3160
 *|  NT(Windows NT x86):  "%winsysdir%\\spool\\PRTPROCS\\w32x86" 
 *|  NT(Windows 4.0):     "%winsysdir%\\spool\\PRTPROCS\\win40" 
 *|  win9x(Windows 4.0):  "%winsysdir%" 
 *
 *   "%winsysdir%" is the Value from GetSystemDirectoryW()
 *
 * BUGS
3161
 *  Only NULL or "" is supported for server
3162
 *
3163 3164 3165
 */
BOOL WINAPI GetPrintProcessorDirectoryW(LPWSTR server, LPWSTR env,
                                        DWORD level,  LPBYTE Info,
3166
                                        DWORD cbBuf,  LPDWORD pcbNeeded)
3167
{
3168

3169 3170
    TRACE("(%s, %s, %d, %p, %d, %p)\n", debugstr_w(server), debugstr_w(env), level,
                                        Info, cbBuf, pcbNeeded);
3171

3172
    if ((backend == NULL)  && !load_backend()) return FALSE;
3173

3174 3175
    if (level != 1) {
        /* (Level != 1) is ignored in win9x */
3176 3177 3178 3179
        SetLastError(ERROR_INVALID_LEVEL);
        return FALSE;
    }

3180 3181
    if (pcbNeeded == NULL) {
        /* (pcbNeeded == NULL) is ignored in win9x */
3182 3183 3184
        SetLastError(RPC_X_NULL_REF_POINTER);
        return FALSE;
    }
3185 3186

    return backend->fpGetPrintProcessorDirectory(server, env, level, Info, cbBuf, pcbNeeded);
3187 3188
}

3189 3190 3191 3192 3193 3194 3195 3196
/*****************************************************************************
 *          WINSPOOL_OpenDriverReg [internal]
 *
 * opens the registry for the printer drivers depending on the given input
 * variable pEnvironment
 *
 * RETURNS:
 *    the opened hkey on success
3197
 *    NULL on error
3198
 */
3199
static HKEY WINSPOOL_OpenDriverReg( LPCVOID pEnvironment)
3200
{   
3201 3202 3203
    HKEY  retval = NULL;
    LPWSTR buffer;
    const printenv_t * env;
3204

3205
    TRACE("(%s)\n", debugstr_w(pEnvironment));
3206

3207
    env = validate_envW(pEnvironment);
3208 3209 3210 3211 3212 3213 3214 3215 3216 3217
    if (!env) return NULL;

    buffer = HeapAlloc( GetProcessHeap(), 0,
                (strlenW(DriversW) + strlenW(env->envname) + 
                 strlenW(env->versionregpath) + 1) * sizeof(WCHAR));
    if(buffer) {
        wsprintfW(buffer, DriversW, env->envname, env->versionregpath);
        RegCreateKeyW(HKEY_LOCAL_MACHINE, buffer, &retval);
        HeapFree(GetProcessHeap(), 0, buffer);
    }
3218 3219 3220
    return retval;
}

3221 3222 3223 3224 3225 3226 3227 3228 3229 3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245 3246 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 3257 3258
/*****************************************************************************
 * set_devices_and_printerports [internal]
 *
 * set the [Devices] and [PrinterPorts] entries for a printer.
 *
 */
static void set_devices_and_printerports(PRINTER_INFO_2W *pi)
{
    DWORD portlen = lstrlenW(pi->pPortName) * sizeof(WCHAR);
    WCHAR *devline;
    HKEY  hkey;

    TRACE("(%p) %s\n", pi, debugstr_w(pi->pPrinterName));

    /* FIXME: the driver must change to "winspool" */
    devline = HeapAlloc(GetProcessHeap(), 0, sizeof(driver_nt) + portlen + sizeof(timeout_15_45));
    if (devline) {
        lstrcpyW(devline, driver_nt);
        lstrcatW(devline, commaW);
        lstrcatW(devline, pi->pPortName);

        TRACE("using %s\n", debugstr_w(devline));
        if (!RegCreateKeyW(HKEY_CURRENT_USER, user_printers_reg_key, &hkey)) {
            RegSetValueExW(hkey, pi->pPrinterName, 0, REG_SZ, (LPBYTE)devline,
                            (lstrlenW(devline) + 1) * sizeof(WCHAR));
            RegCloseKey(hkey);
        }

        lstrcatW(devline, timeout_15_45);
        if (!RegCreateKeyW(HKEY_CURRENT_USER, WinNT_CV_PrinterPortsW, &hkey)) {
            RegSetValueExW(hkey, pi->pPrinterName, 0, REG_SZ, (LPBYTE)devline,
                            (lstrlenW(devline) + 1) * sizeof(WCHAR));
            RegCloseKey(hkey);
        }
        HeapFree(GetProcessHeap(), 0, devline);
    }
}

3259
/*****************************************************************************
3260
 *          AddPrinterW  [WINSPOOL.@]
3261
 */
3262
HANDLE WINAPI AddPrinterW(LPWSTR pName, DWORD Level, LPBYTE pPrinter)
3263
{
3264
    PRINTER_INFO_2W *pi = (PRINTER_INFO_2W *) pPrinter;
3265
    LPDEVMODEW dm;
3266 3267
    HANDLE retval;
    HKEY hkeyPrinter, hkeyPrinters, hkeyDriver, hkeyDrivers;
3268
    LONG size;
3269

3270
    TRACE("(%s,%d,%p)\n", debugstr_w(pName), Level, pPrinter);
3271

3272
    if(pName && *pName) {
3273
        ERR("pName = %s - unsupported\n", debugstr_w(pName));
3274 3275 3276 3277
	SetLastError(ERROR_INVALID_PARAMETER);
	return 0;
    }
    if(Level != 2) {
3278
        ERR("Level = %d, unsupported!\n", Level);
3279 3280 3281 3282 3283 3284 3285
	SetLastError(ERROR_INVALID_LEVEL);
	return 0;
    }
    if(!pPrinter) {
        SetLastError(ERROR_INVALID_PARAMETER);
	return 0;
    }
3286
    if(RegCreateKeyW(HKEY_LOCAL_MACHINE, PrintersW, &hkeyPrinters) !=
3287 3288 3289 3290
       ERROR_SUCCESS) {
        ERR("Can't create Printers key\n");
	return 0;
    }
3291
    if(!RegOpenKeyW(hkeyPrinters, pi->pPrinterName, &hkeyPrinter)) {
3292
	if (!RegQueryValueW(hkeyPrinter, AttributesW, NULL, NULL)) {
3293 3294 3295 3296 3297
	    SetLastError(ERROR_PRINTER_ALREADY_EXISTS);
	    RegCloseKey(hkeyPrinter);
	    RegCloseKey(hkeyPrinters);
	    return 0;
	}
3298 3299
	RegCloseKey(hkeyPrinter);
    }
3300
    hkeyDrivers = WINSPOOL_OpenDriverReg(NULL);
3301
    if(!hkeyDrivers) {
3302 3303 3304 3305
        ERR("Can't create Drivers key\n");
	RegCloseKey(hkeyPrinters);
	return 0;
    }
3306
    if(RegOpenKeyW(hkeyDrivers, pi->pDriverName, &hkeyDriver) !=
3307
       ERROR_SUCCESS) {
3308
        WARN("Can't find driver %s\n", debugstr_w(pi->pDriverName));
3309 3310 3311 3312 3313 3314 3315
	RegCloseKey(hkeyPrinters);
	RegCloseKey(hkeyDrivers);
	SetLastError(ERROR_UNKNOWN_PRINTER_DRIVER);
	return 0;
    }
    RegCloseKey(hkeyDriver);
    RegCloseKey(hkeyDrivers);
3316 3317

    if(lstrcmpiW(pi->pPrintProcessor, WinPrintW)) {  /* FIXME */
3318
        FIXME("Can't find processor %s\n", debugstr_w(pi->pPrintProcessor));
3319 3320 3321 3322
	SetLastError(ERROR_UNKNOWN_PRINTPROCESSOR);
	RegCloseKey(hkeyPrinters);
	return 0;
    }
3323

3324 3325 3326 3327 3328 3329 3330
    if(RegCreateKeyW(hkeyPrinters, pi->pPrinterName, &hkeyPrinter) !=
       ERROR_SUCCESS) {
        FIXME("Can't create printer %s\n", debugstr_w(pi->pPrinterName));
	SetLastError(ERROR_INVALID_PRINTER_NAME);
	RegCloseKey(hkeyPrinters);
	return 0;
    }
3331 3332

    set_devices_and_printerports(pi);
3333

3334
    set_reg_DWORD(hkeyPrinter, AttributesW, pi->Attributes);
3335
    set_reg_szW(hkeyPrinter, DatatypeW, pi->pDatatype);
3336
    set_reg_DWORD(hkeyPrinter, Default_PriorityW, pi->DefaultPriority);
3337 3338 3339 3340 3341 3342 3343 3344 3345 3346 3347 3348 3349 3350 3351
    set_reg_szW(hkeyPrinter, DescriptionW, pi->pComment);
    set_reg_DWORD(hkeyPrinter, dnsTimeoutW, 0);
    set_reg_szW(hkeyPrinter, LocationW, pi->pLocation);
    set_reg_szW(hkeyPrinter, NameW, pi->pPrinterName);
    set_reg_szW(hkeyPrinter, ParametersW, pi->pParameters);
    set_reg_szW(hkeyPrinter, PortW, pi->pPortName);
    set_reg_szW(hkeyPrinter, Print_ProcessorW, pi->pPrintProcessor);
    set_reg_szW(hkeyPrinter, Printer_DriverW, pi->pDriverName);
    set_reg_DWORD(hkeyPrinter, PriorityW, pi->Priority);
    set_reg_szW(hkeyPrinter, Separator_FileW, pi->pSepFile);
    set_reg_szW(hkeyPrinter, Share_NameW, pi->pShareName);
    set_reg_DWORD(hkeyPrinter, StartTimeW, pi->StartTime);
    set_reg_DWORD(hkeyPrinter, StatusW, pi->Status);
    set_reg_DWORD(hkeyPrinter, txTimeoutW, 0);
    set_reg_DWORD(hkeyPrinter, UntilTimeW, pi->UntilTime);
3352

3353
    size = DocumentPropertiesW(0, 0, pi->pPrinterName, NULL, NULL, 0);
3354

3355 3356
    if (size < 0)
    {
3357
        FIXME("DocumentPropertiesW on printer %s fails\n", debugstr_w(pi->pPrinterName));
3358
        size = sizeof(DEVMODEW);
3359
    }
3360
    if(pi->pDevMode)
3361
        dm = pi->pDevMode;
3362
    else
3363
    {
3364 3365 3366
        dm = HeapAlloc( GetProcessHeap(), HEAP_ZERO_MEMORY, size );
        dm->dmSize = size;
        if (DocumentPropertiesW(0, 0, pi->pPrinterName, dm, NULL, DM_OUT_BUFFER) < 0)
3367
        {
3368
            WARN("DocumentPropertiesW on printer %s failed!\n", debugstr_w(pi->pPrinterName));
3369 3370
            HeapFree( GetProcessHeap(), 0, dm );
            dm = NULL;
3371
        }
3372 3373
        else
        {
3374
            /* set devmode to printer name */
3375
            lstrcpynW( dm->dmDeviceName, pi->pPrinterName, CCHDEVICENAME );
3376
        }
3377 3378
    }

3379
    set_reg_devmode( hkeyPrinter, Default_DevModeW, dm );
3380 3381
    if (!pi->pDevMode) HeapFree( GetProcessHeap(), 0, dm );

3382 3383
    RegCloseKey(hkeyPrinter);
    RegCloseKey(hkeyPrinters);
3384
    if(!OpenPrinterW(pi->pPrinterName, &retval, NULL)) {
3385 3386 3387 3388
        ERR("OpenPrinter failing\n");
	return 0;
    }
    return retval;
3389 3390 3391
}

/*****************************************************************************
3392
 *          AddPrinterA  [WINSPOOL.@]
3393
 */
3394
HANDLE WINAPI AddPrinterA(LPSTR pName, DWORD Level, LPBYTE pPrinter)
3395
{
3396
    UNICODE_STRING pNameW;
3397
    PWSTR pwstrNameW;
3398 3399 3400 3401
    PRINTER_INFO_2W *piW;
    PRINTER_INFO_2A *piA = (PRINTER_INFO_2A*)pPrinter;
    HANDLE ret;

3402
    TRACE("(%s, %d, %p)\n", debugstr_a(pName), Level, pPrinter);
3403
    if(Level != 2) {
3404
        ERR("Level = %d, unsupported!\n", Level);
3405 3406 3407
	SetLastError(ERROR_INVALID_LEVEL);
	return 0;
    }
3408
    pwstrNameW = asciitounicode(&pNameW,pName);
3409
    piW = printer_info_AtoW( piA, Level );
3410

3411
    ret = AddPrinterW(pwstrNameW, Level, (LPBYTE)piW);
3412

3413
    free_printer_info( piW, Level );
3414
    RtlFreeUnicodeString(&pNameW);
3415
    return ret;
3416 3417 3418 3419
}


/*****************************************************************************
3420
 *          ClosePrinter  [WINSPOOL.@]
3421 3422 3423
 */
BOOL WINAPI ClosePrinter(HANDLE hPrinter)
{
Kevin Koltzau's avatar
Kevin Koltzau committed
3424
    UINT_PTR i = (UINT_PTR)hPrinter;
3425
    opened_printer_t *printer = NULL;
3426

3427
    TRACE("(%p)\n", hPrinter);
3428

3429 3430 3431 3432 3433
    EnterCriticalSection(&printer_handles_cs);

    if ((i > 0) && (i <= nb_printer_handles))
        printer = printer_handles[i - 1];

3434

3435 3436
    if(printer)
    {
3437
        struct list *cursor, *cursor2;
3438

3439
        TRACE("closing %s (doc: %p)\n", debugstr_w(printer->name), printer->doc);
3440

3441 3442 3443
        if(printer->doc)
            EndDocPrinter(hPrinter);

3444
        if(InterlockedDecrement(&printer->queue->ref) == 0)
3445
        {
3446 3447 3448 3449 3450 3451
            LIST_FOR_EACH_SAFE(cursor, cursor2, &printer->queue->jobs)
            {
                job_t *job = LIST_ENTRY(cursor, job_t, entry);
                ScheduleJob(hPrinter, job->job_id);
            }
            HeapFree(GetProcessHeap(), 0, printer->queue);
3452
        }
3453

3454 3455 3456 3457
        if (printer->backend_printer) {
            backend->fpClosePrinter(printer->backend_printer);
        }

3458
        free_printer_entry( printer );
3459
        printer_handles[i - 1] = NULL;
3460 3461
        LeaveCriticalSection(&printer_handles_cs);
        return TRUE;
3462
    }
3463

3464
    LeaveCriticalSection(&printer_handles_cs);
3465 3466
    SetLastError(ERROR_INVALID_HANDLE);
    return FALSE;
3467 3468 3469
}

/*****************************************************************************
3470
 *          DeleteFormA  [WINSPOOL.@]
3471 3472 3473
 */
BOOL WINAPI DeleteFormA(HANDLE hPrinter, LPSTR pFormName)
{
3474
    FIXME("(%p,%s): stub\n", hPrinter, pFormName);
3475
    return TRUE;
3476 3477 3478
}

/*****************************************************************************
3479
 *          DeleteFormW  [WINSPOOL.@]
3480
 */
3481
BOOL WINAPI DeleteFormW( HANDLE printer, WCHAR *name )
3482
{
3483 3484 3485 3486 3487 3488 3489 3490 3491 3492 3493
    HANDLE handle = get_backend_handle( printer );

    TRACE( "(%p, %s)\n", printer, debugstr_w( name ) );

    if (!handle)
    {
        SetLastError( ERROR_INVALID_HANDLE );
        return FALSE;
    }

    return backend->fpDeleteForm( handle, name );
3494
}
3495

3496
/*****************************************************************************
3497
 *          DeletePrinter  [WINSPOOL.@]
3498 3499 3500
 */
BOOL WINAPI DeletePrinter(HANDLE hPrinter)
{
3501
    LPCWSTR lpNameW = get_opened_printer_name(hPrinter);
3502
    HKEY hkeyPrinters, hkey;
3503
    WCHAR def[MAX_PATH];
3504
    DWORD size = ARRAY_SIZE(def);
3505

3506 3507 3508 3509
    if(!lpNameW) {
        SetLastError(ERROR_INVALID_HANDLE);
        return FALSE;
    }
3510
    if(RegOpenKeyW(HKEY_LOCAL_MACHINE, PrintersW, &hkeyPrinters) == ERROR_SUCCESS) {
3511
        RegDeleteTreeW(hkeyPrinters, lpNameW);
3512
        RegCloseKey(hkeyPrinters);
3513
    }
3514

3515 3516 3517 3518
    if(RegCreateKeyW(HKEY_CURRENT_USER, user_printers_reg_key, &hkey) == ERROR_SUCCESS) {
        RegDeleteValueW(hkey, lpNameW);
        RegCloseKey(hkey);
    }
3519 3520 3521 3522 3523

    if(RegCreateKeyW(HKEY_CURRENT_USER, WinNT_CV_PrinterPortsW, &hkey) == ERROR_SUCCESS) {
        RegDeleteValueW(hkey, lpNameW);
        RegCloseKey(hkey);
    }
3524 3525 3526 3527 3528 3529 3530 3531 3532 3533 3534

    if (GetDefaultPrinterW( def, &size ) && !strcmpW( def, lpNameW ))
    {
        if (!RegCreateKeyW( HKEY_CURRENT_USER, user_default_reg_key, &hkey ))
        {
            RegDeleteValueW( hkey, deviceW );
            RegCloseKey( hkey );
        }
        SetDefaultPrinterW( NULL );
    }

3535
    return TRUE;
3536 3537 3538
}

/*****************************************************************************
3539
 *          SetPrinterA  [WINSPOOL.@]
3540
 */
3541
BOOL WINAPI SetPrinterA( HANDLE printer, DWORD level, LPBYTE data, DWORD command )
3542
{
3543 3544 3545 3546 3547 3548 3549 3550 3551 3552 3553 3554 3555 3556
    BYTE *dataW = data;
    BOOL ret;

    if (level != 0)
    {
        dataW = printer_info_AtoW( data, level );
        if (!dataW) return FALSE;
    }

    ret = SetPrinterW( printer, level, dataW, command );

    if (dataW != data) free_printer_info( dataW, level );

    return ret;
3557 3558
}

3559 3560 3561 3562 3563 3564 3565 3566 3567 3568 3569 3570 3571 3572 3573 3574 3575
static void set_printer_2( HKEY key, const PRINTER_INFO_2W *pi )
{
    set_reg_szW( key, NameW, pi->pPrinterName );
    set_reg_szW( key, Share_NameW, pi->pShareName );
    set_reg_szW( key, PortW, pi->pPortName );
    set_reg_szW( key, Printer_DriverW, pi->pDriverName );
    set_reg_szW( key, DescriptionW, pi->pComment );
    set_reg_szW( key, LocationW, pi->pLocation );

    if (pi->pDevMode)
        set_reg_devmode( key, Default_DevModeW, pi->pDevMode );

    set_reg_szW( key, Separator_FileW, pi->pSepFile );
    set_reg_szW( key, Print_ProcessorW, pi->pPrintProcessor );
    set_reg_szW( key, DatatypeW, pi->pDatatype );
    set_reg_szW( key, ParametersW, pi->pParameters );

3576 3577 3578 3579 3580
    set_reg_DWORD( key, AttributesW, pi->Attributes );
    set_reg_DWORD( key, PriorityW, pi->Priority );
    set_reg_DWORD( key, Default_PriorityW, pi->DefaultPriority );
    set_reg_DWORD( key, StartTimeW, pi->StartTime );
    set_reg_DWORD( key, UntilTimeW, pi->UntilTime );
3581 3582
}

3583 3584 3585 3586 3587 3588 3589 3590 3591 3592 3593 3594 3595 3596 3597 3598 3599 3600 3601 3602 3603 3604 3605 3606 3607
static BOOL set_printer_9( HKEY key, const PRINTER_INFO_9W *pi )
{
    if (!pi->pDevMode) return FALSE;

    set_reg_devmode( key, Default_DevModeW, pi->pDevMode );
    return TRUE;
}

/******************************************************************************
 *    SetPrinterW  [WINSPOOL.@]
 */
BOOL WINAPI SetPrinterW( HANDLE printer, DWORD level, LPBYTE data, DWORD command )
{
    HKEY key;
    BOOL ret = FALSE;

    TRACE( "(%p, %d, %p, %d)\n", printer, level, data, command );

    if (command != 0) FIXME( "Ignoring command %d\n", command );

    if (WINSPOOL_GetOpenedPrinterRegKey( printer, &key ))
        return FALSE;

    switch (level)
    {
3608 3609 3610 3611 3612 3613 3614 3615
    case 2:
    {
        PRINTER_INFO_2W *pi2 = (PRINTER_INFO_2W *)data;
        set_printer_2( key, pi2 );
        ret = TRUE;
        break;
    }

3616 3617 3618 3619
    case 8:
        /* 8 is the global default printer info and 9 already sets it instead of the per-user one */
        /* still, PRINTER_INFO_8W is the same as PRINTER_INFO_9W */
        /* fall through */
3620 3621 3622 3623 3624 3625 3626 3627 3628 3629 3630 3631 3632 3633 3634 3635
    case 9:
    {
        PRINTER_INFO_9W *pi = (PRINTER_INFO_9W *)data;
        ret = set_printer_9( key, pi );
        break;
    }

    default:
        FIXME( "Unimplemented level %d\n", level );
        SetLastError( ERROR_INVALID_LEVEL );
    }

    RegCloseKey( key );
    return ret;
}

3636
/*****************************************************************************
3637
 *          SetJobA  [WINSPOOL.@]
3638 3639
 */
BOOL WINAPI SetJobA(HANDLE hPrinter, DWORD JobId, DWORD Level,
3640
                    LPBYTE pJob, DWORD Command)
3641
{
Huw Davies's avatar
Huw Davies committed
3642 3643 3644 3645
    BOOL ret;
    LPBYTE JobW;
    UNICODE_STRING usBuffer;

3646
    TRACE("(%p, %d, %d, %p, %d)\n",hPrinter, JobId, Level, pJob, Command);
Huw Davies's avatar
Huw Davies committed
3647 3648 3649 3650 3651 3652 3653 3654 3655 3656 3657 3658 3659 3660 3661 3662 3663 3664 3665 3666 3667 3668 3669 3670 3671 3672 3673 3674 3675 3676 3677 3678 3679 3680 3681 3682 3683 3684 3685 3686 3687 3688 3689 3690 3691 3692 3693 3694 3695 3696 3697 3698 3699 3700 3701 3702 3703 3704 3705 3706 3707 3708 3709 3710 3711 3712 3713 3714 3715 3716 3717 3718 3719 3720 3721 3722 3723 3724 3725 3726 3727 3728 3729 3730 3731 3732

    /* JobId, pPrinterName, pMachineName, pDriverName, Size, Submitted, Time and TotalPages
       are all ignored by SetJob, so we don't bother copying them */
    switch(Level)
    {
    case 0:
        JobW = NULL;
        break;
    case 1:
      {
        JOB_INFO_1W *info1W = HeapAlloc(GetProcessHeap(), 0, sizeof(*info1W));
        JOB_INFO_1A *info1A = (JOB_INFO_1A*)pJob;

        JobW = (LPBYTE)info1W;
        info1W->pUserName = asciitounicode(&usBuffer, info1A->pUserName);
        info1W->pDocument = asciitounicode(&usBuffer, info1A->pDocument);
        info1W->pDatatype = asciitounicode(&usBuffer, info1A->pDatatype);
        info1W->pStatus = asciitounicode(&usBuffer, info1A->pStatus);
        info1W->Status = info1A->Status;
        info1W->Priority = info1A->Priority;
        info1W->Position = info1A->Position;
        info1W->PagesPrinted = info1A->PagesPrinted;
        break;
      }
    case 2:
      {
        JOB_INFO_2W *info2W = HeapAlloc(GetProcessHeap(), 0, sizeof(*info2W));
        JOB_INFO_2A *info2A = (JOB_INFO_2A*)pJob;

        JobW = (LPBYTE)info2W;
        info2W->pUserName = asciitounicode(&usBuffer, info2A->pUserName);
        info2W->pDocument = asciitounicode(&usBuffer, info2A->pDocument);
        info2W->pNotifyName = asciitounicode(&usBuffer, info2A->pNotifyName);
        info2W->pDatatype = asciitounicode(&usBuffer, info2A->pDatatype);
        info2W->pPrintProcessor = asciitounicode(&usBuffer, info2A->pPrintProcessor);
        info2W->pParameters = asciitounicode(&usBuffer, info2A->pParameters);
        info2W->pDevMode = info2A->pDevMode ? GdiConvertToDevmodeW(info2A->pDevMode) : NULL;
        info2W->pStatus = asciitounicode(&usBuffer, info2A->pStatus);
        info2W->pSecurityDescriptor = info2A->pSecurityDescriptor;
        info2W->Status = info2A->Status;
        info2W->Priority = info2A->Priority;
        info2W->Position = info2A->Position;
        info2W->StartTime = info2A->StartTime;
        info2W->UntilTime = info2A->UntilTime;
        info2W->PagesPrinted = info2A->PagesPrinted;
        break;
      }
    case 3:
        JobW = HeapAlloc(GetProcessHeap(), 0, sizeof(JOB_INFO_3));
        memcpy(JobW, pJob, sizeof(JOB_INFO_3));
        break;
    default:
        SetLastError(ERROR_INVALID_LEVEL);
        return FALSE;
    }

    ret = SetJobW(hPrinter, JobId, Level, JobW, Command);

    switch(Level)
    {
    case 1:
      {
        JOB_INFO_1W *info1W = (JOB_INFO_1W*)JobW;
        HeapFree(GetProcessHeap(), 0, info1W->pUserName);
        HeapFree(GetProcessHeap(), 0, info1W->pDocument); 
        HeapFree(GetProcessHeap(), 0, info1W->pDatatype);
        HeapFree(GetProcessHeap(), 0, info1W->pStatus);
        break;
      }
    case 2:
      {
        JOB_INFO_2W *info2W = (JOB_INFO_2W*)JobW;
        HeapFree(GetProcessHeap(), 0, info2W->pUserName);
        HeapFree(GetProcessHeap(), 0, info2W->pDocument); 
        HeapFree(GetProcessHeap(), 0, info2W->pNotifyName);
        HeapFree(GetProcessHeap(), 0, info2W->pDatatype);
        HeapFree(GetProcessHeap(), 0, info2W->pPrintProcessor);
        HeapFree(GetProcessHeap(), 0, info2W->pParameters);
        HeapFree(GetProcessHeap(), 0, info2W->pDevMode);
        HeapFree(GetProcessHeap(), 0, info2W->pStatus);
        break;
      }
    }
    HeapFree(GetProcessHeap(), 0, JobW);

    return ret;
3733 3734 3735
}

/*****************************************************************************
3736
 *          SetJobW  [WINSPOOL.@]
3737 3738
 */
BOOL WINAPI SetJobW(HANDLE hPrinter, DWORD JobId, DWORD Level,
3739
                    LPBYTE pJob, DWORD Command)
3740
{
3741 3742 3743
    BOOL ret = FALSE;
    job_t *job;

3744
    TRACE("(%p, %d, %d, %p, %d)\n", hPrinter, JobId, Level, pJob, Command);
3745 3746 3747 3748 3749 3750 3751 3752 3753 3754 3755 3756 3757 3758 3759 3760 3761 3762 3763 3764 3765 3766 3767
    FIXME("Ignoring everything other than document title\n");

    EnterCriticalSection(&printer_handles_cs);
    job = get_job(hPrinter, JobId);
    if(!job)
        goto end;

    switch(Level)
    {
    case 0:
        break;
    case 1:
      {
        JOB_INFO_1W *info1 = (JOB_INFO_1W*)pJob;
        HeapFree(GetProcessHeap(), 0, job->document_title);
        job->document_title = strdupW(info1->pDocument);
        break;
      }
    case 2:
      {
        JOB_INFO_2W *info2 = (JOB_INFO_2W*)pJob;
        HeapFree(GetProcessHeap(), 0, job->document_title);
        job->document_title = strdupW(info2->pDocument);
3768
        HeapFree(GetProcessHeap(), 0, job->devmode);
3769
        job->devmode = dup_devmode( info2->pDevMode );
3770 3771 3772 3773 3774 3775 3776 3777 3778 3779 3780 3781
        break;
      }
    case 3:
        break;
    default:
        SetLastError(ERROR_INVALID_LEVEL);
        goto end;
    }
    ret = TRUE;
end:
    LeaveCriticalSection(&printer_handles_cs);
    return ret;
3782 3783
}

3784 3785 3786 3787 3788
/*****************************************************************************
 *          EndDocPrinter  [WINSPOOL.@]
 */
BOOL WINAPI EndDocPrinter(HANDLE hPrinter)
{
3789 3790 3791 3792 3793 3794 3795 3796 3797 3798 3799 3800 3801 3802 3803 3804 3805 3806 3807 3808 3809 3810 3811 3812 3813 3814 3815
    opened_printer_t *printer;
    BOOL ret = FALSE;
    TRACE("(%p)\n", hPrinter);

    EnterCriticalSection(&printer_handles_cs);

    printer = get_opened_printer(hPrinter);
    if(!printer)
    {
        SetLastError(ERROR_INVALID_HANDLE);
        goto end;
    }

    if(!printer->doc)    
    {
        SetLastError(ERROR_SPL_NO_STARTDOC);
        goto end;
    }

    CloseHandle(printer->doc->hf);
    ScheduleJob(hPrinter, printer->doc->job_id);
    HeapFree(GetProcessHeap(), 0, printer->doc);
    printer->doc = NULL;
    ret = TRUE;
end:
    LeaveCriticalSection(&printer_handles_cs);
    return ret;
3816 3817 3818 3819 3820 3821 3822
}

/*****************************************************************************
 *          EndPagePrinter  [WINSPOOL.@]
 */
BOOL WINAPI EndPagePrinter(HANDLE hPrinter)
{
3823 3824
    FIXME("(%p): stub\n", hPrinter);
    return TRUE;
3825 3826 3827 3828 3829 3830 3831
}

/*****************************************************************************
 *          StartDocPrinterA  [WINSPOOL.@]
 */
DWORD WINAPI StartDocPrinterA(HANDLE hPrinter, DWORD Level, LPBYTE pDocInfo)
{
3832 3833 3834 3835 3836 3837 3838 3839 3840 3841 3842 3843 3844 3845 3846 3847 3848 3849 3850 3851 3852 3853 3854 3855 3856 3857 3858 3859 3860 3861 3862 3863 3864
    UNICODE_STRING usBuffer;
    DOC_INFO_2W doc2W;
    DOC_INFO_2A *doc2 = (DOC_INFO_2A*)pDocInfo;
    DWORD ret;

    /* DOC_INFO_1, 2 and 3 all have the strings in the same place with either two (DOC_INFO_2)
       or one (DOC_INFO_3) extra DWORDs */

    switch(Level) {
    case 2:
        doc2W.JobId = doc2->JobId;
        /* fall through */
    case 3:
        doc2W.dwMode = doc2->dwMode;
        /* fall through */
    case 1:
        doc2W.pDocName = asciitounicode(&usBuffer, doc2->pDocName);
        doc2W.pOutputFile = asciitounicode(&usBuffer, doc2->pOutputFile);
        doc2W.pDatatype = asciitounicode(&usBuffer, doc2->pDatatype);
        break;

    default:
        SetLastError(ERROR_INVALID_LEVEL);
        return FALSE;
    }

    ret = StartDocPrinterW(hPrinter, Level, (LPBYTE)&doc2W);

    HeapFree(GetProcessHeap(), 0, doc2W.pDatatype);
    HeapFree(GetProcessHeap(), 0, doc2W.pOutputFile);
    HeapFree(GetProcessHeap(), 0, doc2W.pDocName);

    return ret;
3865 3866 3867 3868 3869 3870 3871
}

/*****************************************************************************
 *          StartDocPrinterW  [WINSPOOL.@]
 */
DWORD WINAPI StartDocPrinterW(HANDLE hPrinter, DWORD Level, LPBYTE pDocInfo)
{
3872
    DOC_INFO_2W *doc = (DOC_INFO_2W *)pDocInfo;
3873 3874 3875
    opened_printer_t *printer;
    BYTE addjob_buf[MAX_PATH * sizeof(WCHAR) + sizeof(ADDJOB_INFO_1W)];
    ADDJOB_INFO_1W *addjob = (ADDJOB_INFO_1W*) addjob_buf;
3876
    JOB_INFO_1W job_info;
3877 3878 3879
    DWORD needed, ret = 0;
    HANDLE hf;
    WCHAR *filename;
3880
    job_t *job;
3881

3882
    TRACE("(hPrinter = %p, Level = %d, pDocInfo = %p {pDocName = %s, pOutputFile = %s, pDatatype = %s}):\n",
3883 3884
          hPrinter, Level, doc, debugstr_w(doc->pDocName), debugstr_w(doc->pOutputFile),
          debugstr_w(doc->pDatatype));
3885 3886 3887 3888 3889 3890 3891 3892 3893 3894 3895 3896 3897 3898 3899 3900 3901 3902 3903 3904 3905 3906 3907 3908 3909 3910

    if(Level < 1 || Level > 3)
    {
        SetLastError(ERROR_INVALID_LEVEL);
        return 0;
    }

    EnterCriticalSection(&printer_handles_cs);
    printer = get_opened_printer(hPrinter);
    if(!printer)
    {
        SetLastError(ERROR_INVALID_HANDLE);
        goto end;
    }

    if(printer->doc)
    {
        SetLastError(ERROR_INVALID_PRINTER_STATE);
        goto end;
    }

    /* Even if we're printing to a file we still add a print job, we'll
       just ignore the spool file name */

    if(!AddJobW(hPrinter, 1, addjob_buf, sizeof(addjob_buf), &needed))
    {
3911
        ERR("AddJob failed gle %u\n", GetLastError());
3912 3913 3914
        goto end;
    }

3915 3916
    /* use pOutputFile only, when it is a real filename */
    if ((doc->pOutputFile) && is_local_file(doc->pOutputFile))
3917 3918 3919 3920 3921 3922 3923 3924
        filename = doc->pOutputFile;
    else
        filename = addjob->Path;

    hf = CreateFileW(filename, GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
    if(hf == INVALID_HANDLE_VALUE)
        goto end;

3925 3926 3927
    memset(&job_info, 0, sizeof(job_info));
    job_info.pDocument = doc->pDocName;
    SetJobW(hPrinter, addjob->JobId, 1, (LPBYTE)&job_info, 0);
3928 3929 3930 3931

    printer->doc = HeapAlloc(GetProcessHeap(), 0, sizeof(*printer->doc));
    printer->doc->hf = hf;
    ret = printer->doc->job_id = addjob->JobId;
3932 3933 3934
    job = get_job(hPrinter, ret);
    job->portname = strdupW(doc->pOutputFile);

3935 3936 3937 3938
end:
    LeaveCriticalSection(&printer_handles_cs);

    return ret;
3939 3940 3941 3942 3943 3944 3945
}

/*****************************************************************************
 *          StartPagePrinter  [WINSPOOL.@]
 */
BOOL WINAPI StartPagePrinter(HANDLE hPrinter)
{
3946 3947
    FIXME("(%p): stub\n", hPrinter);
    return TRUE;
3948 3949
}

3950
/*****************************************************************************
3951
 *          GetFormA  [WINSPOOL.@]
3952
 */
3953
BOOL WINAPI GetFormA( HANDLE printer, char *name, DWORD level, BYTE *form, DWORD size, DWORD *needed )
3954
{
3955 3956 3957 3958 3959 3960 3961 3962 3963 3964 3965 3966 3967
    UNICODE_STRING nameW;
    const DWORD *string_info = form_string_info( level );
    BOOL ret;

    if (!string_info) return FALSE;

    asciitounicode( &nameW, name );

    ret = GetFormW( printer, nameW.Buffer, level, form, size, needed );
    if (ret) packed_struct_WtoA( form, string_info );

    RtlFreeUnicodeString( &nameW );
    return ret;
3968 3969 3970
}

/*****************************************************************************
3971
 *          GetFormW  [WINSPOOL.@]
3972
 */
3973
BOOL WINAPI GetFormW( HANDLE printer, WCHAR *name, DWORD level, BYTE *form, DWORD size, DWORD *needed )
3974
{
3975 3976 3977 3978 3979 3980 3981 3982 3983 3984 3985
    HANDLE handle = get_backend_handle( printer );

    TRACE( "(%p, %s, %d, %p, %d, %p)\n", printer, debugstr_w( name ), level, form, size, needed );

    if (!handle)
    {
        SetLastError( ERROR_INVALID_HANDLE );
        return FALSE;
    }

    return backend->fpGetForm( handle, name, level, form, size, needed );
3986 3987 3988
}

/*****************************************************************************
3989
 *          SetFormA  [WINSPOOL.@]
3990 3991 3992 3993
 */
BOOL WINAPI SetFormA(HANDLE hPrinter, LPSTR pFormName, DWORD Level,
                        LPBYTE pForm)
{
3994
    FIXME("(%p,%s,%d,%p): stub\n",hPrinter,pFormName,Level,pForm);
3995 3996 3997 3998
    return FALSE;
}

/*****************************************************************************
3999
 *          SetFormW  [WINSPOOL.@]
4000
 */
4001
BOOL WINAPI SetFormW( HANDLE printer, WCHAR *name, DWORD level, BYTE *form )
4002
{
4003 4004 4005 4006 4007 4008 4009 4010 4011 4012 4013
    HANDLE handle = get_backend_handle( printer );

    TRACE( "(%p, %s, %d, %p)\n", printer, debugstr_w( name ), level, form );

    if (!handle)
    {
        SetLastError( ERROR_INVALID_HANDLE );
        return FALSE;
    }

    return backend->fpSetForm( handle, name, level, form );
4014 4015 4016
}

/*****************************************************************************
4017
 *          ReadPrinter  [WINSPOOL.@]
4018 4019 4020 4021
 */
BOOL WINAPI ReadPrinter(HANDLE hPrinter, LPVOID pBuf, DWORD cbBuf,
                           LPDWORD pNoBytesRead)
{
4022
    FIXME("(%p,%p,%d,%p): stub\n",hPrinter,pBuf,cbBuf,pNoBytesRead);
4023 4024 4025 4026
    return FALSE;
}

/*****************************************************************************
4027
 *          ResetPrinterA  [WINSPOOL.@]
4028 4029 4030
 */
BOOL WINAPI ResetPrinterA(HANDLE hPrinter, LPPRINTER_DEFAULTSA pDefault)
{
4031
    FIXME("(%p, %p): stub\n", hPrinter, pDefault);
4032 4033 4034 4035
    return FALSE;
}

/*****************************************************************************
4036
 *          ResetPrinterW  [WINSPOOL.@]
4037 4038 4039
 */
BOOL WINAPI ResetPrinterW(HANDLE hPrinter, LPPRINTER_DEFAULTSW pDefault)
{
4040
    FIXME("(%p, %p): stub\n", hPrinter, pDefault);
4041 4042 4043
    return FALSE;
}

4044 4045 4046 4047 4048 4049 4050 4051 4052 4053 4054
/*****************************************************************************
 * get_filename_from_reg [internal]
 *
 * Get ValueName from hkey storing result in out
 * when the Value in the registry has only a filename, use driverdir as prefix
 * outlen is space left in out
 * String is stored either as unicode or ascii
 *
 */

static BOOL get_filename_from_reg(HKEY hkey, LPCWSTR driverdir, DWORD dirlen, LPCWSTR ValueName,
4055
                                  LPBYTE out, DWORD outlen, LPDWORD needed)
4056 4057 4058 4059 4060 4061 4062 4063 4064 4065 4066 4067 4068 4069 4070 4071 4072 4073 4074 4075 4076 4077 4078 4079 4080 4081 4082 4083 4084 4085 4086 4087 4088 4089 4090 4091 4092 4093
{
    WCHAR   filename[MAX_PATH];
    DWORD   size;
    DWORD   type;
    LONG    ret;
    LPWSTR  buffer = filename;
    LPWSTR  ptr;

    *needed = 0;
    size = sizeof(filename);
    buffer[0] = '\0';
    ret = RegQueryValueExW(hkey, ValueName, NULL, &type, (LPBYTE) buffer, &size);
    if (ret == ERROR_MORE_DATA) {
        TRACE("need dynamic buffer: %u\n", size);
        buffer = HeapAlloc(GetProcessHeap(), 0, size);
        if (!buffer) {
            /* No Memory is bad */
            return FALSE;
        }
        buffer[0] = '\0';
        ret = RegQueryValueExW(hkey, ValueName, NULL, &type, (LPBYTE) buffer, &size);
    }

    if ((ret != ERROR_SUCCESS) || (!buffer[0])) {
        if (buffer != filename) HeapFree(GetProcessHeap(), 0, buffer);
        return FALSE;
    }

    ptr = buffer;
    while (ptr) {
        /* do we have a full path ? */
        ret = (((buffer[0] == '\\') && (buffer[1] == '\\')) ||
                (buffer[0] && (buffer[1] == ':') && (buffer[2] == '\\')) );

        if (!ret) {
            /* we must build the full Path */
            *needed += dirlen;
            if ((out) && (outlen > dirlen)) {
4094
                lstrcpyW((LPWSTR)out, driverdir);
4095 4096 4097 4098 4099 4100 4101 4102
                out += dirlen;
                outlen -= dirlen;
            }
            else
                out = NULL;
        }

        /* write the filename */
4103 4104 4105 4106 4107
        size = (lstrlenW(ptr) + 1) * sizeof(WCHAR);
        if ((out) && (outlen >= size)) {
            lstrcpyW((LPWSTR)out, ptr);
            out += size;
            outlen -= size;
4108 4109
        }
        else
4110
            out = NULL;
4111 4112 4113 4114 4115 4116 4117 4118 4119
        *needed += size;
        ptr +=  lstrlenW(ptr)+1;
        if ((type != REG_MULTI_SZ) || (!ptr[0]))  ptr = NULL;
    }

    if (buffer != filename) HeapFree(GetProcessHeap(), 0, buffer);

    /* write the multisz-termination */
    if (type == REG_MULTI_SZ) {
4120
        size = sizeof(WCHAR);
4121 4122 4123 4124 4125 4126 4127 4128 4129

        *needed += size;
        if (out && (outlen >= size)) {
            memset (out, 0, size);
        }
    }
    return TRUE;
}

4130
/*****************************************************************************
4131
 *    WINSPOOL_GetStringFromReg
4132
 *
4133
 * Get ValueName from hkey storing result in ptr.  buflen is space left in ptr
4134
 * String is stored as unicode.
4135
 */
4136
static BOOL WINSPOOL_GetStringFromReg(HKEY hkey, LPCWSTR ValueName, LPBYTE ptr,
4137
				      DWORD buflen, DWORD *needed)
4138 4139 4140 4141
{
    DWORD sz = buflen, type;
    LONG ret;

4142
    ret = RegQueryValueExW(hkey, ValueName, 0, &type, ptr, &sz);
4143
    if(ret != ERROR_SUCCESS && ret != ERROR_MORE_DATA) {
4144
        WARN("Got ret = %d\n", ret);
4145 4146 4147
	*needed = 0;
	return FALSE;
    }
4148
    /* add space for terminating '\0' */
4149
    sz += sizeof(WCHAR);
4150
    *needed = sz;
4151 4152

    if (ptr)
4153
        TRACE("%s: %s\n", debugstr_w(ValueName), debugstr_w((LPCWSTR)ptr));
4154

4155 4156 4157
    return TRUE;
}

4158 4159 4160 4161
/*****************************************************************************
 *    WINSPOOL_GetDefaultDevMode
 *
 * Get a default DevMode values for wineps.
4162 4163 4164 4165 4166 4167 4168 4169 4170 4171 4172 4173 4174 4175
 */
static void WINSPOOL_GetDefaultDevMode(LPBYTE ptr, DWORD buflen, DWORD *needed)
{
    static const WCHAR winepsW[] = { 'w','i','n','e','p','s','.','d','r','v',0 };

    if (buflen >= sizeof(DEVMODEW))
    {
        DEVMODEW *dm = (DEVMODEW *)ptr;

        /* the driver will update registry with real values */
        memset(dm, 0, sizeof(*dm));
        dm->dmSize = sizeof(*dm);
        lstrcpyW(dm->dmDeviceName, winepsW);
    }
4176
    *needed = sizeof(DEVMODEW);
4177 4178
}

4179 4180 4181 4182 4183
/*****************************************************************************
 *    WINSPOOL_GetDevModeFromReg
 *
 * Get ValueName from hkey storing result in ptr.  buflen is space left in ptr
 * DevMode is stored either as unicode or ascii.
4184
 */
4185 4186
static BOOL WINSPOOL_GetDevModeFromReg(HKEY hkey, LPCWSTR ValueName,
				       LPBYTE ptr,
4187
				       DWORD buflen, DWORD *needed)
4188 4189 4190
{
    DWORD sz = buflen, type;
    LONG ret;
4191

4192
    if (ptr && buflen>=sizeof(DEVMODEA)) memset(ptr, 0, sizeof(DEVMODEA));
4193
    ret = RegQueryValueExW(hkey, ValueName, 0, &type, ptr, &sz);
4194 4195 4196
    if ((ret != ERROR_SUCCESS && ret != ERROR_MORE_DATA)) sz = 0;
    if (sz < sizeof(DEVMODEA))
    {
4197
        TRACE("corrupted registry for %s ( size %d)\n",debugstr_w(ValueName),sz);
4198
	return FALSE;
4199
    }
4200 4201 4202
    /* ensures that dmSize is not erratically bogus if registry is invalid */
    if (ptr && ((DEVMODEA*)ptr)->dmSize < sizeof(DEVMODEA))
        ((DEVMODEA*)ptr)->dmSize = sizeof(DEVMODEA);
4203
    sz += (CCHDEVICENAME + CCHFORMNAME);
4204
    if (ptr && (buflen >= sz)) {
4205 4206 4207
        DEVMODEW *dmW = GdiConvertToDevmodeW((DEVMODEA*)ptr);
        memcpy(ptr, dmW, sz);
        HeapFree(GetProcessHeap(),0,dmW);
4208
    }
4209 4210 4211 4212
    *needed = sz;
    return TRUE;
}

4213 4214 4215
/*********************************************************************
 *    WINSPOOL_GetPrinter_1
 *
4216
 * Fills out a PRINTER_INFO_1W struct storing the strings in buf.
4217 4218
 */
static BOOL WINSPOOL_GetPrinter_1(HKEY hkeyPrinter, PRINTER_INFO_1W *pi1,
4219
				  LPBYTE buf, DWORD cbBuf, LPDWORD pcbNeeded)
4220 4221 4222 4223 4224 4225 4226
{
    DWORD size, left = cbBuf;
    BOOL space = (cbBuf > 0);
    LPBYTE ptr = buf;

    *pcbNeeded = 0;

4227
    if(WINSPOOL_GetStringFromReg(hkeyPrinter, NameW, ptr, left, &size)) {
4228 4229 4230 4231 4232 4233 4234 4235 4236 4237
        if(space && size <= left) {
	    pi1->pName = (LPWSTR)ptr;
	    ptr += size;
	    left -= size;
	} else
	    space = FALSE;
	*pcbNeeded += size;
    }

    /* FIXME: pDescription should be something like "Name,Driver_Name,". */
4238
    if(WINSPOOL_GetStringFromReg(hkeyPrinter, NameW, ptr, left, &size)) {
4239 4240 4241 4242 4243 4244 4245 4246 4247
        if(space && size <= left) {
	    pi1->pDescription = (LPWSTR)ptr;
	    ptr += size;
	    left -= size;
	} else
	    space = FALSE;
	*pcbNeeded += size;
    }

4248
    if(WINSPOOL_GetStringFromReg(hkeyPrinter, DescriptionW, ptr, left, &size)) {
4249 4250 4251 4252 4253 4254 4255 4256 4257 4258 4259 4260 4261 4262 4263 4264
        if(space && size <= left) {
	    pi1->pComment = (LPWSTR)ptr;
	    ptr += size;
	    left -= size;
	} else
	    space = FALSE;
	*pcbNeeded += size;
    }

    if(pi1) pi1->Flags = PRINTER_ENUM_ICON8; /* We're a printer */

    if(!space && pi1) /* zero out pi1 if we can't completely fill buf */
        memset(pi1, 0, sizeof(*pi1));

    return space;
}
4265
/*********************************************************************
4266
 *    WINSPOOL_GetPrinter_2
4267
 *
4268
 * Fills out a PRINTER_INFO_2W struct storing the strings in buf.
4269
 */
4270
static BOOL WINSPOOL_GetPrinter_2(HKEY hkeyPrinter, PRINTER_INFO_2W *pi2,
4271
				  LPBYTE buf, DWORD cbBuf, LPDWORD pcbNeeded)
4272 4273 4274 4275 4276 4277 4278
{
    DWORD size, left = cbBuf;
    BOOL space = (cbBuf > 0);
    LPBYTE ptr = buf;

    *pcbNeeded = 0;

4279
    if(WINSPOOL_GetStringFromReg(hkeyPrinter, NameW, ptr, left, &size)) {
4280 4281 4282 4283 4284 4285 4286 4287
        if(space && size <= left) {
	    pi2->pPrinterName = (LPWSTR)ptr;
	    ptr += size;
	    left -= size;
	} else
	    space = FALSE;
	*pcbNeeded += size;
    }
4288
    if(WINSPOOL_GetStringFromReg(hkeyPrinter, Share_NameW, ptr, left, &size)) {
4289 4290 4291 4292 4293 4294 4295 4296
        if(space && size <= left) {
	    pi2->pShareName = (LPWSTR)ptr;
	    ptr += size;
	    left -= size;
	} else
	    space = FALSE;
	*pcbNeeded += size;
    }
4297
    if(WINSPOOL_GetStringFromReg(hkeyPrinter, PortW, ptr, left, &size)) {
4298 4299 4300 4301 4302 4303 4304 4305
        if(space && size <= left) {
	    pi2->pPortName = (LPWSTR)ptr;
	    ptr += size;
	    left -= size;
	} else
	    space = FALSE;
	*pcbNeeded += size;
    }
4306
    if(WINSPOOL_GetStringFromReg(hkeyPrinter, Printer_DriverW, ptr, left, &size)) {
4307 4308 4309 4310 4311 4312 4313 4314
        if(space && size <= left) {
	    pi2->pDriverName = (LPWSTR)ptr;
	    ptr += size;
	    left -= size;
	} else
	    space = FALSE;
	*pcbNeeded += size;
    }
4315
    if(WINSPOOL_GetStringFromReg(hkeyPrinter, DescriptionW, ptr, left, &size)) {
4316 4317 4318 4319 4320 4321 4322 4323
        if(space && size <= left) {
	    pi2->pComment = (LPWSTR)ptr;
	    ptr += size;
	    left -= size;
	} else
	    space = FALSE;
	*pcbNeeded += size;
    }
4324
    if(WINSPOOL_GetStringFromReg(hkeyPrinter, LocationW, ptr, left, &size)) {
4325 4326 4327 4328 4329 4330 4331 4332
        if(space && size <= left) {
	    pi2->pLocation = (LPWSTR)ptr;
	    ptr += size;
	    left -= size;
	} else
	    space = FALSE;
	*pcbNeeded += size;
    }
4333
    if(WINSPOOL_GetDevModeFromReg(hkeyPrinter, Default_DevModeW, ptr, left, &size)) {
4334 4335 4336 4337 4338 4339 4340 4341
        if(space && size <= left) {
	    pi2->pDevMode = (LPDEVMODEW)ptr;
	    ptr += size;
	    left -= size;
	} else
	    space = FALSE;
	*pcbNeeded += size;
    }
4342 4343
    else
    {
4344
	WINSPOOL_GetDefaultDevMode(ptr, left, &size);
4345 4346 4347 4348 4349 4350 4351 4352
        if(space && size <= left) {
	    pi2->pDevMode = (LPDEVMODEW)ptr;
	    ptr += size;
	    left -= size;
	} else
	    space = FALSE;
	*pcbNeeded += size;
    }
4353
    if(WINSPOOL_GetStringFromReg(hkeyPrinter, Separator_FileW, ptr, left, &size)) {
4354 4355 4356 4357 4358 4359 4360 4361
        if(space && size <= left) {
            pi2->pSepFile = (LPWSTR)ptr;
	    ptr += size;
	    left -= size;
	} else
	    space = FALSE;
	*pcbNeeded += size;
    }
4362
    if(WINSPOOL_GetStringFromReg(hkeyPrinter, Print_ProcessorW, ptr, left, &size)) {
4363 4364 4365 4366 4367 4368 4369 4370
        if(space && size <= left) {
	    pi2->pPrintProcessor = (LPWSTR)ptr;
	    ptr += size;
	    left -= size;
	} else
	    space = FALSE;
	*pcbNeeded += size;
    }
4371
    if(WINSPOOL_GetStringFromReg(hkeyPrinter, DatatypeW, ptr, left, &size)) {
4372 4373 4374 4375 4376 4377 4378 4379
        if(space && size <= left) {
	    pi2->pDatatype = (LPWSTR)ptr;
	    ptr += size;
	    left -= size;
	} else
	    space = FALSE;
	*pcbNeeded += size;
    }
4380
    if(WINSPOOL_GetStringFromReg(hkeyPrinter, ParametersW, ptr, left, &size)) {
4381 4382 4383 4384 4385 4386 4387 4388 4389
        if(space && size <= left) {
	    pi2->pParameters = (LPWSTR)ptr;
	    ptr += size;
	    left -= size;
	} else
	    space = FALSE;
	*pcbNeeded += size;
    }
    if(pi2) {
4390 4391 4392 4393 4394
        pi2->Attributes = get_dword_from_reg( hkeyPrinter, AttributesW );
        pi2->Priority = get_dword_from_reg( hkeyPrinter, PriorityW );
        pi2->DefaultPriority = get_dword_from_reg( hkeyPrinter, Default_PriorityW );
        pi2->StartTime = get_dword_from_reg( hkeyPrinter, StartTimeW );
        pi2->UntilTime = get_dword_from_reg( hkeyPrinter, UntilTimeW );
4395
    }
4396 4397 4398 4399 4400 4401 4402 4403

    if(!space && pi2) /* zero out pi2 if we can't completely fill buf */
        memset(pi2, 0, sizeof(*pi2));

    return space;
}

/*********************************************************************
4404
 *    WINSPOOL_GetPrinter_4
4405
 *
4406
 * Fills out a PRINTER_INFO_4 struct storing the strings in buf.
4407
 */
4408
static BOOL WINSPOOL_GetPrinter_4(HKEY hkeyPrinter, PRINTER_INFO_4W *pi4,
4409
				  LPBYTE buf, DWORD cbBuf, LPDWORD pcbNeeded)
4410 4411 4412 4413 4414 4415 4416
{
    DWORD size, left = cbBuf;
    BOOL space = (cbBuf > 0);
    LPBYTE ptr = buf;

    *pcbNeeded = 0;

4417
    if(WINSPOOL_GetStringFromReg(hkeyPrinter, NameW, ptr, left, &size)) {
4418 4419 4420 4421 4422 4423 4424 4425 4426
        if(space && size <= left) {
	    pi4->pPrinterName = (LPWSTR)ptr;
	    ptr += size;
	    left -= size;
	} else
	    space = FALSE;
	*pcbNeeded += size;
    }
    if(pi4) {
4427
        pi4->Attributes = get_dword_from_reg( hkeyPrinter, AttributesW );
4428
    }
4429 4430 4431 4432 4433 4434 4435 4436

    if(!space && pi4) /* zero out pi4 if we can't completely fill buf */
        memset(pi4, 0, sizeof(*pi4));

    return space;
}

/*********************************************************************
4437
 *    WINSPOOL_GetPrinter_5
4438
 *
4439
 * Fills out a PRINTER_INFO_5 struct storing the strings in buf.
4440
 */
4441
static BOOL WINSPOOL_GetPrinter_5(HKEY hkeyPrinter, PRINTER_INFO_5W *pi5,
4442
				  LPBYTE buf, DWORD cbBuf, LPDWORD pcbNeeded)
4443 4444 4445 4446 4447 4448 4449
{
    DWORD size, left = cbBuf;
    BOOL space = (cbBuf > 0);
    LPBYTE ptr = buf;

    *pcbNeeded = 0;

4450
    if(WINSPOOL_GetStringFromReg(hkeyPrinter, NameW, ptr, left, &size)) {
4451 4452 4453 4454 4455 4456 4457 4458
        if(space && size <= left) {
	    pi5->pPrinterName = (LPWSTR)ptr;
	    ptr += size;
	    left -= size;
	} else
	    space = FALSE;
	*pcbNeeded += size;
    }
4459
    if(WINSPOOL_GetStringFromReg(hkeyPrinter, PortW, ptr, left, &size)) {
4460 4461 4462 4463 4464 4465 4466 4467 4468
        if(space && size <= left) {
	    pi5->pPortName = (LPWSTR)ptr;
	    ptr += size;
	    left -= size;
	} else
	    space = FALSE;
	*pcbNeeded += size;
    }
    if(pi5) {
4469 4470 4471
        pi5->Attributes = get_dword_from_reg( hkeyPrinter, AttributesW );
        pi5->DeviceNotSelectedTimeout = get_dword_from_reg( hkeyPrinter, dnsTimeoutW );
        pi5->TransmissionRetryTimeout = get_dword_from_reg( hkeyPrinter, txTimeoutW );
4472
    }
4473 4474 4475 4476 4477 4478

    if(!space && pi5) /* zero out pi5 if we can't completely fill buf */
        memset(pi5, 0, sizeof(*pi5));

    return space;
}
4479

4480 4481 4482 4483 4484 4485
/*********************************************************************
 *    WINSPOOL_GetPrinter_7
 *
 * Fills out a PRINTER_INFO_7 struct storing the strings in buf.
 */
static BOOL WINSPOOL_GetPrinter_7(HKEY hkeyPrinter, PRINTER_INFO_7W *pi7, LPBYTE buf,
4486
                                  DWORD cbBuf, LPDWORD pcbNeeded)
4487 4488 4489 4490 4491 4492 4493
{
    DWORD size, left = cbBuf;
    BOOL space = (cbBuf > 0);
    LPBYTE ptr = buf;

    *pcbNeeded = 0;

4494
    if (! WINSPOOL_GetStringFromReg(hkeyPrinter, ObjectGUIDW, ptr, left, &size))
4495
    {
4496 4497
        ptr = NULL;
        size = sizeof(pi7->pszObjectGUID);
4498
    }
4499 4500 4501 4502 4503 4504 4505
    if (space && size <= left) {
        pi7->pszObjectGUID = (LPWSTR)ptr;
        ptr += size;
        left -= size;
    } else
        space = FALSE;
    *pcbNeeded += size;
4506 4507 4508 4509 4510 4511 4512 4513 4514 4515 4516
    if (pi7) {
        /* We do not have a Directory Service */
        pi7->dwAction = DSPRINT_UNPUBLISH;
    }

    if (!space && pi7) /* zero out pi7 if we can't completely fill buf */
        memset(pi7, 0, sizeof(*pi7));

    return space;
}

4517 4518 4519
/*********************************************************************
 *    WINSPOOL_GetPrinter_9
 *
4520
 * Fills out a PRINTER_INFO_9AW struct storing the strings in buf.
4521 4522
 */
static BOOL WINSPOOL_GetPrinter_9(HKEY hkeyPrinter, PRINTER_INFO_9W *pi9, LPBYTE buf,
4523
                                  DWORD cbBuf, LPDWORD pcbNeeded)
4524 4525 4526 4527 4528 4529
{
    DWORD size;
    BOOL space = (cbBuf > 0);

    *pcbNeeded = 0;

4530
    if(WINSPOOL_GetDevModeFromReg(hkeyPrinter, Default_DevModeW, buf, cbBuf, &size)) {
4531 4532 4533 4534 4535 4536 4537 4538
        if(space && size <= cbBuf) {
            pi9->pDevMode = (LPDEVMODEW)buf;
        } else
            space = FALSE;
        *pcbNeeded += size;
    }
    else
    {
4539
        WINSPOOL_GetDefaultDevMode(buf, cbBuf, &size);
4540 4541 4542 4543 4544 4545 4546 4547 4548 4549 4550 4551 4552
        if(space && size <= cbBuf) {
            pi9->pDevMode = (LPDEVMODEW)buf;
        } else
            space = FALSE;
        *pcbNeeded += size;
    }

    if(!space && pi9) /* zero out pi9 if we can't completely fill buf */
        memset(pi9, 0, sizeof(*pi9));

    return space;
}

4553
/*****************************************************************************
4554
 *          GetPrinterW  [WINSPOOL.@]
4555
 */
4556 4557
BOOL WINAPI GetPrinterW(HANDLE hPrinter, DWORD Level, LPBYTE pPrinter,
			DWORD cbBuf, LPDWORD pcbNeeded)
4558
{
4559
    DWORD size, needed = 0, err;
4560
    LPBYTE ptr = NULL;
4561
    HKEY hkeyPrinter;
4562 4563
    BOOL ret;

4564
    TRACE("(%p,%d,%p,%d,%p)\n",hPrinter,Level,pPrinter,cbBuf, pcbNeeded);
4565

4566 4567
    err = WINSPOOL_GetOpenedPrinterRegKey( hPrinter, &hkeyPrinter );
    if (err)
4568
    {
4569 4570
        SetLastError( err );
        return FALSE;
4571
    }
4572

4573
    switch(Level) {
4574 4575 4576 4577 4578 4579 4580 4581 4582 4583 4584 4585 4586 4587 4588 4589 4590 4591
    case 1:
      {
        PRINTER_INFO_1W *pi1 = (PRINTER_INFO_1W *)pPrinter;

        size = sizeof(PRINTER_INFO_1W);
        if (size <= cbBuf) {
            ptr = pPrinter + size;
            cbBuf -= size;
            memset(pPrinter, 0, size);
        } else {
            pi1 = NULL;
            cbBuf = 0;
        }
        ret = WINSPOOL_GetPrinter_1(hkeyPrinter, pi1, ptr, cbBuf, &needed);
        needed += size;
        break;
      }

4592 4593
    case 2:
      {
4594
        PRINTER_INFO_2W *pi2 = (PRINTER_INFO_2W *)pPrinter;
4595

4596
        size = sizeof(PRINTER_INFO_2W);
4597 4598 4599 4600
	if(size <= cbBuf) {
	    ptr = pPrinter + size;
	    cbBuf -= size;
	    memset(pPrinter, 0, size);
4601 4602
	} else {
	    pi2 = NULL;
4603
	    cbBuf = 0;
4604
	}
4605
	ret = WINSPOOL_GetPrinter_2(hkeyPrinter, pi2, ptr, cbBuf, &needed);
4606
	needed += size;
4607 4608
	break;
      }
4609

4610 4611
    case 4:
      {
4612
	PRINTER_INFO_4W *pi4 = (PRINTER_INFO_4W *)pPrinter;
4613

4614
        size = sizeof(PRINTER_INFO_4W);
4615 4616 4617 4618 4619 4620
	if(size <= cbBuf) {
	    ptr = pPrinter + size;
	    cbBuf -= size;
	    memset(pPrinter, 0, size);
	} else {
	    pi4 = NULL;
4621
	    cbBuf = 0;
4622
	}
4623
	ret = WINSPOOL_GetPrinter_4(hkeyPrinter, pi4, ptr, cbBuf, &needed);
4624 4625 4626
	needed += size;
	break;
      }
4627 4628


4629 4630
    case 5:
      {
4631
        PRINTER_INFO_5W *pi5 = (PRINTER_INFO_5W *)pPrinter;
4632

4633
        size = sizeof(PRINTER_INFO_5W);
4634 4635 4636 4637
	if(size <= cbBuf) {
	    ptr = pPrinter + size;
	    cbBuf -= size;
	    memset(pPrinter, 0, size);
4638 4639
	} else {
	    pi5 = NULL;
4640
	    cbBuf = 0;
4641
	}
4642

4643
	ret = WINSPOOL_GetPrinter_5(hkeyPrinter, pi5, ptr, cbBuf, &needed);
4644 4645 4646 4647
	needed += size;
	break;
      }

4648 4649 4650 4651 4652 4653 4654 4655

    case 6:
      {
        PRINTER_INFO_6 *pi6 = (PRINTER_INFO_6 *) pPrinter;

        size = sizeof(PRINTER_INFO_6);
        if (size <= cbBuf) {
            /* FIXME: We do not update the status yet */
4656
            pi6->dwStatus = get_dword_from_reg( hkeyPrinter, StatusW );
4657 4658 4659 4660 4661 4662 4663 4664 4665 4666 4667 4668 4669 4670 4671 4672 4673 4674 4675 4676 4677 4678 4679
            ret = TRUE;
        } else {
            ret = FALSE;
        }

        needed += size;
        break;
      }

    case 7:
      {
        PRINTER_INFO_7W *pi7 = (PRINTER_INFO_7W *) pPrinter;

        size = sizeof(PRINTER_INFO_7W);
        if (size <= cbBuf) {
            ptr = pPrinter + size;
            cbBuf -= size;
            memset(pPrinter, 0, size);
        } else {
            pi7 = NULL;
            cbBuf = 0;
        }

4680
        ret = WINSPOOL_GetPrinter_7(hkeyPrinter, pi7, ptr, cbBuf, &needed);
4681 4682 4683 4684 4685
        needed += size;
        break;
      }


4686 4687 4688 4689
    case 8:
        /* 8 is the global default printer info and 9 already gets it instead of the per-user one */
        /* still, PRINTER_INFO_8W is the same as PRINTER_INFO_9W */
        /* fall through */
4690 4691 4692 4693 4694 4695 4696 4697 4698 4699 4700 4701 4702 4703
    case 9:
      {
        PRINTER_INFO_9W *pi9 = (PRINTER_INFO_9W *)pPrinter;

        size = sizeof(PRINTER_INFO_9W);
        if(size <= cbBuf) {
            ptr = pPrinter + size;
            cbBuf -= size;
            memset(pPrinter, 0, size);
        } else {
            pi9 = NULL;
            cbBuf = 0;
        }

4704
        ret = WINSPOOL_GetPrinter_9(hkeyPrinter, pi9, ptr, cbBuf, &needed);
4705 4706 4707 4708 4709
        needed += size;
        break;
      }


4710
    default:
4711
        FIXME("Unimplemented level %d\n", Level);
4712 4713
        SetLastError(ERROR_INVALID_LEVEL);
	RegCloseKey(hkeyPrinter);
4714 4715 4716
	return FALSE;
    }

4717 4718
    RegCloseKey(hkeyPrinter);

4719
    TRACE("returning %d needed = %d\n", ret, needed);
4720
    if(pcbNeeded) *pcbNeeded = needed;
4721 4722 4723
    if(!ret)
        SetLastError(ERROR_INSUFFICIENT_BUFFER);
    return ret;
4724 4725
}

4726
/*****************************************************************************
4727
 *          GetPrinterA  [WINSPOOL.@]
4728 4729
 */
BOOL WINAPI GetPrinterA(HANDLE hPrinter, DWORD Level, LPBYTE pPrinter,
4730 4731
                    DWORD cbBuf, LPDWORD pcbNeeded)
{
4732 4733 4734 4735 4736 4737 4738 4739 4740 4741 4742 4743
    BOOL ret;
    LPBYTE buf = NULL;

    if (cbBuf)
        buf = HeapAlloc(GetProcessHeap(), 0, cbBuf);

    ret = GetPrinterW(hPrinter, Level, buf, cbBuf, pcbNeeded);
    if (ret)
        convert_printerinfo_W_to_A(pPrinter, buf, Level, cbBuf, 1);
    HeapFree(GetProcessHeap(), 0, buf);

    return ret;
4744 4745
}

4746
/*****************************************************************************
4747
 *          WINSPOOL_EnumPrintersW
4748
 *
4749
 *    Implementation of EnumPrintersW
4750
 */
4751
static BOOL WINSPOOL_EnumPrintersW(DWORD dwType, LPWSTR lpszName,
4752 4753
				  DWORD dwLevel, LPBYTE lpbPrinters,
				  DWORD cbBuf, LPDWORD lpdwNeeded,
4754
				  LPDWORD lpdwReturned)
4755 4756 4757

{
    HKEY hkeyPrinters, hkeyPrinter;
4758
    WCHAR PrinterName[255];
4759 4760 4761 4762 4763 4764 4765 4766
    DWORD needed = 0, number = 0;
    DWORD used, i, left;
    PBYTE pi, buf;

    if(lpbPrinters)
        memset(lpbPrinters, 0, cbBuf);
    if(lpdwReturned)
        *lpdwReturned = 0;
4767 4768 4769 4770 4771 4772
    if(lpdwNeeded)
        *lpdwNeeded = 0;

    /* PRINTER_ENUM_DEFAULT is only supported under win9x, we behave like NT */
    if(dwType == PRINTER_ENUM_DEFAULT)
	return TRUE;
4773

4774
    if (dwType & PRINTER_ENUM_CONNECTIONS) {
4775 4776 4777 4778 4779 4780 4781
        TRACE("ignoring PRINTER_ENUM_CONNECTIONS\n");
        dwType &= ~PRINTER_ENUM_CONNECTIONS; /* we don't handle that */
        if (!dwType) {
            FIXME("We don't handle PRINTER_ENUM_CONNECTIONS\n");
            return TRUE;
        }

4782 4783
    }

4784
    if (!((dwType & PRINTER_ENUM_LOCAL) || (dwType & PRINTER_ENUM_NAME))) {
4785
        FIXME("dwType = %08x\n", dwType);
4786 4787 4788 4789
	SetLastError(ERROR_INVALID_FLAGS);
	return FALSE;
    }

4790
    if(RegCreateKeyW(HKEY_LOCAL_MACHINE, PrintersW, &hkeyPrinters) !=
4791 4792 4793 4794
       ERROR_SUCCESS) {
        ERR("Can't create Printers key\n");
	return FALSE;
    }
4795

4796 4797 4798 4799 4800 4801
    if(RegQueryInfoKeyA(hkeyPrinters, NULL, NULL, NULL, &number, NULL, NULL,
			NULL, NULL, NULL, NULL, NULL) != ERROR_SUCCESS) {
        RegCloseKey(hkeyPrinters);
	ERR("Can't query Printers key\n");
	return FALSE;
    }
4802
    TRACE("Found %d printers\n", number);
4803 4804 4805

    switch(dwLevel) {
    case 1:
4806 4807
        used = number * sizeof(PRINTER_INFO_1W);
        break;
4808
    case 2:
4809
        used = number * sizeof(PRINTER_INFO_2W);
4810 4811
	break;
    case 4:
4812
        used = number * sizeof(PRINTER_INFO_4W);
4813 4814
	break;
    case 5:
4815
        used = number * sizeof(PRINTER_INFO_5W);
4816 4817 4818 4819 4820 4821 4822 4823 4824 4825
	break;

    default:
        SetLastError(ERROR_INVALID_LEVEL);
	RegCloseKey(hkeyPrinters);
	return FALSE;
    }
    pi = (used <= cbBuf) ? lpbPrinters : NULL;

    for(i = 0; i < number; i++) {
4826
        if(RegEnumKeyW(hkeyPrinters, i, PrinterName, ARRAY_SIZE(PrinterName)) != ERROR_SUCCESS) {
4827
	    ERR("Can't enum key number %d\n", i);
4828 4829 4830
	    RegCloseKey(hkeyPrinters);
	    return FALSE;
	}
4831
	TRACE("Printer %d is %s\n", i, debugstr_w(PrinterName));
4832
	if(RegOpenKeyW(hkeyPrinters, PrinterName, &hkeyPrinter) !=
4833
	   ERROR_SUCCESS) {
4834
	    ERR("Can't open key %s\n", debugstr_w(PrinterName));
4835 4836 4837 4838 4839 4840 4841 4842 4843 4844 4845 4846 4847
	    RegCloseKey(hkeyPrinters);
	    return FALSE;
	}

	if(cbBuf > used) {
	    buf = lpbPrinters + used;
	    left = cbBuf - used;
	} else {
	    buf = NULL;
	    left = 0;
	}

	switch(dwLevel) {
4848 4849
	case 1:
	    WINSPOOL_GetPrinter_1(hkeyPrinter, (PRINTER_INFO_1W *)pi, buf,
4850
				  left, &needed);
4851 4852 4853
	    used += needed;
	    if(pi) pi += sizeof(PRINTER_INFO_1W);
	    break;
4854
	case 2:
4855
	    WINSPOOL_GetPrinter_2(hkeyPrinter, (PRINTER_INFO_2W *)pi, buf,
4856
				  left, &needed);
4857
	    used += needed;
4858
	    if(pi) pi += sizeof(PRINTER_INFO_2W);
4859 4860
	    break;
	case 4:
4861
	    WINSPOOL_GetPrinter_4(hkeyPrinter, (PRINTER_INFO_4W *)pi, buf,
4862
				  left, &needed);
4863
	    used += needed;
4864
	    if(pi) pi += sizeof(PRINTER_INFO_4W);
4865 4866
	    break;
	case 5:
4867
	    WINSPOOL_GetPrinter_5(hkeyPrinter, (PRINTER_INFO_5W *)pi, buf,
4868
				  left, &needed);
4869
	    used += needed;
4870
	    if(pi) pi += sizeof(PRINTER_INFO_5W);
4871 4872 4873 4874 4875 4876 4877 4878 4879 4880 4881 4882 4883
	    break;
	default:
	    ERR("Shouldn't be here!\n");
	    RegCloseKey(hkeyPrinter);
	    RegCloseKey(hkeyPrinters);
	    return FALSE;
	}
	RegCloseKey(hkeyPrinter);
    }
    RegCloseKey(hkeyPrinters);

    if(lpdwNeeded)
        *lpdwNeeded = used;
4884

4885 4886 4887 4888 4889 4890 4891
    if(used > cbBuf) {
        if(lpbPrinters)
	    memset(lpbPrinters, 0, cbBuf);
	SetLastError(ERROR_INSUFFICIENT_BUFFER);
	return FALSE;
    }
    if(lpdwReturned)
4892
        *lpdwReturned = number;
4893 4894 4895 4896
    SetLastError(ERROR_SUCCESS);
    return TRUE;
}

4897

4898
/******************************************************************
4899
 *              EnumPrintersW        [WINSPOOL.@]
4900
 *
4901 4902 4903 4904 4905 4906
 *    Enumerates the available printers, print servers and print
 *    providers, depending on the specified flags, name and level.
 *
 * RETURNS:
 *
 *    If level is set to 1:
4907 4908
 *      Returns an array of PRINTER_INFO_1 data structures in the
 *      lpbPrinters buffer.
4909 4910 4911
 *
 *    If level is set to 2:
 *		Possible flags: PRINTER_ENUM_CONNECTIONS, PRINTER_ENUM_LOCAL.
4912 4913
 *      Returns an array of PRINTER_INFO_2 data structures in the
 *      lpbPrinters buffer. Note that according to MSDN also an
4914 4915 4916 4917 4918 4919
 *      OpenPrinter should be performed on every remote printer.
 *
 *    If level is set to 4 (officially WinNT only):
 *		Possible flags: PRINTER_ENUM_CONNECTIONS, PRINTER_ENUM_LOCAL.
 *      Fast: Only the registry is queried to retrieve printer names,
 *      no connection to the driver is made.
4920
 *      Returns an array of PRINTER_INFO_4 data structures in the
4921 4922 4923 4924 4925
 *      lpbPrinters buffer.
 *
 *    If level is set to 5 (officially WinNT4/Win9x only):
 *      Fast: Only the registry is queried to retrieve printer names,
 *      no connection to the driver is made.
4926
 *      Returns an array of PRINTER_INFO_5 data structures in the
4927 4928 4929
 *      lpbPrinters buffer.
 *
 *    If level set to 3 or 6+:
4930
 *	    returns zero (failure!)
4931
 *
4932
 *    Returns nonzero (TRUE) on success, or zero on failure, use GetLastError
4933 4934 4935 4936 4937 4938
 *    for information.
 *
 * BUGS:
 *    - Only PRINTER_ENUM_LOCAL and PRINTER_ENUM_NAME are implemented.
 *    - Only levels 2, 4 and 5 are implemented at the moment.
 *    - 16-bit printer drivers are not enumerated.
4939 4940
 *    - Returned amount of bytes used/needed does not match the real Windoze
 *      implementation (as in this implementation, all strings are part
4941 4942 4943 4944 4945 4946 4947 4948
 *      of the buffer, whereas Win32 keeps them somewhere else)
 *    - At level 2, EnumPrinters should also call OpenPrinter for remote printers.
 *
 * NOTE:
 *    - In a regular Wine installation, no registry settings for printers
 *      exist, which makes this function return an empty list.
 */
BOOL  WINAPI EnumPrintersW(
4949 4950 4951 4952 4953 4954 4955
		DWORD dwType,        /* [in] Types of print objects to enumerate */
                LPWSTR lpszName,     /* [in] name of objects to enumerate */
	        DWORD dwLevel,       /* [in] type of printer info structure */
                LPBYTE lpbPrinters,  /* [out] buffer which receives info */
		DWORD cbBuf,         /* [in] max size of buffer in bytes */
		LPDWORD lpdwNeeded,  /* [out] pointer to var: # bytes used/needed */
		LPDWORD lpdwReturned /* [out] number of entries returned */
4956 4957
		)
{
4958 4959
    return WINSPOOL_EnumPrintersW(dwType, lpszName, dwLevel, lpbPrinters, cbBuf,
				 lpdwNeeded, lpdwReturned);
4960 4961 4962
}

/******************************************************************
4963 4964 4965
 * EnumPrintersA    [WINSPOOL.@]
 *
 * See EnumPrintersW
4966
 *
4967
 */
4968 4969
BOOL WINAPI EnumPrintersA(DWORD flags, LPSTR pName, DWORD level, LPBYTE pPrinters,
                          DWORD cbBuf, LPDWORD pcbNeeded, LPDWORD pcReturned)
4970
{
4971 4972 4973 4974 4975 4976 4977 4978 4979
    BOOL ret;
    UNICODE_STRING pNameU;
    LPWSTR pNameW;
    LPBYTE pPrintersW;

    TRACE("(0x%x, %s, %u, %p, %d, %p, %p)\n", flags, debugstr_a(pName), level,
                                              pPrinters, cbBuf, pcbNeeded, pcReturned);

    pNameW = asciitounicode(&pNameU, pName);
4980

4981 4982 4983 4984 4985 4986 4987 4988 4989 4990 4991
    /* Request a buffer with a size, that is big enough for EnumPrintersW.
       MS Office need this */
    pPrintersW = (pPrinters && cbBuf) ? HeapAlloc(GetProcessHeap(), 0, cbBuf) : NULL;

    ret = EnumPrintersW(flags, pNameW, level, pPrintersW, cbBuf, pcbNeeded, pcReturned);

    RtlFreeUnicodeString(&pNameU);
    if (ret) {
        convert_printerinfo_W_to_A(pPrinters, pPrintersW, level, *pcbNeeded, *pcReturned);
    }
    HeapFree(GetProcessHeap(), 0, pPrintersW);
4992
    return ret;
4993 4994
}

4995 4996 4997 4998 4999 5000 5001 5002 5003 5004 5005 5006
/*****************************************************************************
 *          WINSPOOL_GetDriverInfoFromReg [internal]
 *
 *    Enters the information from the registry into the DRIVER_INFO struct
 *
 * RETURNS
 *    zero if the printer driver does not exist in the registry
 *    (only if Level > 1) otherwise nonzero
 */
static BOOL WINSPOOL_GetDriverInfoFromReg(
                            HKEY    hkeyDrivers,
                            LPWSTR  DriverName,
5007
                            const printenv_t * env,
5008 5009 5010 5011
                            DWORD   Level,
                            LPBYTE  ptr,            /* DRIVER_INFO */
                            LPBYTE  pDriverStrings, /* strings buffer */
                            DWORD   cbBuf,          /* size of string buffer */
5012
                            LPDWORD pcbNeeded)      /* space needed for str. */
5013 5014
{
    DWORD  size, tmp;
5015
    HKEY   hkeyDriver;
5016 5017
    WCHAR  driverdir[MAX_PATH];
    DWORD  dirlen;
5018
    LPBYTE strPtr = pDriverStrings;
5019
    LPDRIVER_INFO_8W di = (LPDRIVER_INFO_8W) ptr;
5020

5021
    TRACE("(%p, %s, %p, %d, %p, %p, %d)\n", hkeyDrivers,
5022
          debugstr_w(DriverName), env,
5023
          Level, di, pDriverStrings, cbBuf);
5024

5025 5026
    if (di) ZeroMemory(di, di_sizeof[Level]);

5027 5028 5029
    *pcbNeeded = (lstrlenW(DriverName) + 1) * sizeof(WCHAR);
    if (*pcbNeeded <= cbBuf)
       strcpyW((LPWSTR)strPtr, DriverName);
5030 5031 5032 5033

    /* pName for level 1 has a different offset! */
    if (Level == 1) {
       if (di) ((LPDRIVER_INFO_1W) di)->pName = (LPWSTR) strPtr;
5034 5035 5036
       return TRUE;
    }

5037 5038 5039 5040 5041 5042 5043
    /* .cVersion and .pName for level > 1 */
    if (di) {
        di->cVersion = env->driverversion;
        di->pName = (LPWSTR) strPtr;
        strPtr = (pDriverStrings) ? (pDriverStrings + (*pcbNeeded)) : NULL;
    }

5044 5045 5046 5047 5048 5049 5050 5051 5052 5053
    /* Reserve Space for the largest subdir and a Backslash*/
    size = sizeof(driverdir) - sizeof(Version3_SubdirW) - sizeof(WCHAR);
    if (!GetPrinterDriverDirectoryW(NULL, (LPWSTR) env->envname, 1, (LPBYTE) driverdir, size, &size)) {
        /* Should never Fail */
        return FALSE;
    }
    lstrcatW(driverdir, env->versionsubdir);
    lstrcatW(driverdir, backslashW);

    /* dirlen must not include the terminating zero */
5054
    dirlen = lstrlenW(driverdir) * sizeof(WCHAR);
5055

5056
    if (!DriverName[0] || RegOpenKeyW(hkeyDrivers, DriverName, &hkeyDriver) != ERROR_SUCCESS) {
5057
        ERR("Can't find driver %s in registry\n", debugstr_w(DriverName));
5058 5059 5060 5061
        SetLastError(ERROR_UNKNOWN_PRINTER_DRIVER); /* ? */
        return FALSE;
    }

5062
    /* pEnvironment */
5063
    size = (lstrlenW(env->envname) + 1) * sizeof(WCHAR);
5064

5065
    *pcbNeeded += size;
5066
    if (*pcbNeeded <= cbBuf) {
5067
        lstrcpyW((LPWSTR)strPtr, env->envname);
5068
        if (di) di->pEnvironment = (LPWSTR)strPtr;
5069 5070 5071
        strPtr = (pDriverStrings) ? (pDriverStrings + (*pcbNeeded)) : NULL;
    }

5072 5073
    /* .pDriverPath is the Graphics rendering engine.
        The full Path is required to avoid a crash in some apps */
5074
    if (get_filename_from_reg(hkeyDriver, driverdir, dirlen, DriverW, strPtr, 0, &size)) {
5075
        *pcbNeeded += size;
5076
        if (*pcbNeeded <= cbBuf)
5077
            get_filename_from_reg(hkeyDriver, driverdir, dirlen, DriverW, strPtr, size, &tmp);
5078 5079

        if (di) di->pDriverPath = (LPWSTR)strPtr;
5080 5081 5082
        strPtr = (pDriverStrings) ? (pDriverStrings + (*pcbNeeded)) : NULL;
    }

5083
    /* .pDataFile: For postscript-drivers, this is the ppd-file */
5084
    if (get_filename_from_reg(hkeyDriver, driverdir, dirlen, Data_FileW, strPtr, 0, &size)) {
5085
        *pcbNeeded += size;
5086
        if (*pcbNeeded <= cbBuf)
5087
            get_filename_from_reg(hkeyDriver, driverdir, dirlen, Data_FileW, strPtr, size, &size);
5088 5089

        if (di) di->pDataFile = (LPWSTR)strPtr;
5090 5091 5092
        strPtr = (pDriverStrings) ? pDriverStrings + (*pcbNeeded) : NULL;
    }

5093
    /* .pConfigFile is the Driver user Interface */
5094
    if (get_filename_from_reg(hkeyDriver, driverdir, dirlen, Configuration_FileW, strPtr, 0, &size)) {
5095
        *pcbNeeded += size;
5096
        if (*pcbNeeded <= cbBuf)
5097
            get_filename_from_reg(hkeyDriver, driverdir, dirlen, Configuration_FileW, strPtr, size, &size);
5098 5099

        if (di) di->pConfigFile = (LPWSTR)strPtr;
5100 5101 5102
        strPtr = (pDriverStrings) ? pDriverStrings + (*pcbNeeded) : NULL;
    }

5103
    if (Level == 2 ) {
5104
        RegCloseKey(hkeyDriver);
5105
        TRACE("buffer space %d required %d\n", cbBuf, *pcbNeeded);
5106 5107 5108
        return TRUE;
    }

5109 5110 5111 5112 5113 5114 5115
    if (Level == 5 ) {
        RegCloseKey(hkeyDriver);
        FIXME("level 5: incomplete\n");
        return TRUE;
    }

    /* .pHelpFile */
5116
    if (get_filename_from_reg(hkeyDriver, driverdir, dirlen, Help_FileW, strPtr, 0, &size)) {
5117
        *pcbNeeded += size;
5118
        if (*pcbNeeded <= cbBuf)
5119
            get_filename_from_reg(hkeyDriver, driverdir, dirlen, Help_FileW, strPtr, size, &size);
5120 5121

        if (di) di->pHelpFile = (LPWSTR)strPtr;
5122 5123 5124
        strPtr = (pDriverStrings) ? pDriverStrings + (*pcbNeeded) : NULL;
    }

5125
    /* .pDependentFiles */
5126
    if (get_filename_from_reg(hkeyDriver, driverdir, dirlen, Dependent_FilesW, strPtr, 0, &size)) {
5127
        *pcbNeeded += size;
5128
        if (*pcbNeeded <= cbBuf)
5129
            get_filename_from_reg(hkeyDriver, driverdir, dirlen, Dependent_FilesW, strPtr, size, &size);
5130 5131

        if (di) di->pDependentFiles = (LPWSTR)strPtr;
5132 5133
        strPtr = (pDriverStrings) ? pDriverStrings + (*pcbNeeded) : NULL;
    }
5134
    else if (GetVersion() & 0x80000000) {
5135
        /* PowerPoint XP expects that pDependentFiles is always valid on win9x */
5136
        size = 2 * sizeof(WCHAR);
5137 5138 5139 5140 5141 5142
        *pcbNeeded += size;
        if ((*pcbNeeded <= cbBuf) && strPtr) ZeroMemory(strPtr, size);

        if (di) di->pDependentFiles = (LPWSTR)strPtr;
        strPtr = (pDriverStrings) ? pDriverStrings + (*pcbNeeded) : NULL;
    }
5143

5144
    /* .pMonitorName is the optional Language Monitor */
5145
    if (WINSPOOL_GetStringFromReg(hkeyDriver, MonitorW, strPtr, 0, &size)) {
5146
        *pcbNeeded += size;
5147
        if (*pcbNeeded <= cbBuf)
5148
            WINSPOOL_GetStringFromReg(hkeyDriver, MonitorW, strPtr, size, &size);
5149 5150

        if (di) di->pMonitorName = (LPWSTR)strPtr;
5151 5152 5153
        strPtr = (pDriverStrings) ? pDriverStrings + (*pcbNeeded) : NULL;
    }

5154
    /* .pDefaultDataType */
5155
    if (WINSPOOL_GetStringFromReg(hkeyDriver, DatatypeW, strPtr, 0, &size)) {
5156 5157
        *pcbNeeded += size;
        if(*pcbNeeded <= cbBuf)
5158
            WINSPOOL_GetStringFromReg(hkeyDriver, DatatypeW, strPtr, size, &size);
5159 5160

        if (di) di->pDefaultDataType = (LPWSTR)strPtr;
5161 5162 5163
        strPtr = (pDriverStrings) ? pDriverStrings + (*pcbNeeded) : NULL;
    }

5164 5165 5166 5167 5168 5169 5170
    if (Level == 3 ) {
        RegCloseKey(hkeyDriver);
        TRACE("buffer space %d required %d\n", cbBuf, *pcbNeeded);
        return TRUE;
    }

    /* .pszzPreviousNames */
5171
    if (WINSPOOL_GetStringFromReg(hkeyDriver, Previous_NamesW, strPtr, 0, &size)) {
5172 5173
        *pcbNeeded += size;
        if(*pcbNeeded <= cbBuf)
5174
            WINSPOOL_GetStringFromReg(hkeyDriver, Previous_NamesW, strPtr, size, &size);
5175 5176 5177 5178 5179 5180 5181 5182 5183 5184 5185 5186 5187 5188 5189

        if (di) di->pszzPreviousNames = (LPWSTR)strPtr;
        strPtr = (pDriverStrings) ? pDriverStrings + (*pcbNeeded) : NULL;
    }

    if (Level == 4 ) {
        RegCloseKey(hkeyDriver);
        TRACE("buffer space %d required %d\n", cbBuf, *pcbNeeded);
        return TRUE;
    }

    /* support is missing, but not important enough for a FIXME */
    TRACE("%s: DriverDate + DriverVersion not supported\n", debugstr_w(DriverName));

    /* .pszMfgName */
5190
    if (WINSPOOL_GetStringFromReg(hkeyDriver, ManufacturerW, strPtr, 0, &size)) {
5191 5192
        *pcbNeeded += size;
        if(*pcbNeeded <= cbBuf)
5193
            WINSPOOL_GetStringFromReg(hkeyDriver, ManufacturerW, strPtr, size, &size);
5194 5195 5196 5197 5198 5199

        if (di) di->pszMfgName = (LPWSTR)strPtr;
        strPtr = (pDriverStrings) ? pDriverStrings + (*pcbNeeded) : NULL;
    }

    /* .pszOEMUrl */
5200
    if (WINSPOOL_GetStringFromReg(hkeyDriver, OEM_UrlW, strPtr, 0, &size)) {
5201 5202
        *pcbNeeded += size;
        if(*pcbNeeded <= cbBuf)
5203
            WINSPOOL_GetStringFromReg(hkeyDriver, OEM_UrlW, strPtr, size, &size);
5204 5205 5206 5207 5208 5209

        if (di) di->pszOEMUrl = (LPWSTR)strPtr;
        strPtr = (pDriverStrings) ? pDriverStrings + (*pcbNeeded) : NULL;
    }

    /* .pszHardwareID */
5210
    if (WINSPOOL_GetStringFromReg(hkeyDriver, HardwareIDW, strPtr, 0, &size)) {
5211 5212
        *pcbNeeded += size;
        if(*pcbNeeded <= cbBuf)
5213
            WINSPOOL_GetStringFromReg(hkeyDriver, HardwareIDW, strPtr, size, &size);
5214 5215 5216 5217 5218 5219

        if (di) di->pszHardwareID = (LPWSTR)strPtr;
        strPtr = (pDriverStrings) ? pDriverStrings + (*pcbNeeded) : NULL;
    }

    /* .pszProvider */
5220
    if (WINSPOOL_GetStringFromReg(hkeyDriver, ProviderW, strPtr, 0, &size)) {
5221 5222
        *pcbNeeded += size;
        if(*pcbNeeded <= cbBuf)
5223
            WINSPOOL_GetStringFromReg(hkeyDriver, ProviderW, strPtr, size, &size);
5224 5225 5226 5227 5228 5229 5230 5231 5232 5233 5234 5235 5236

        if (di) di->pszProvider = (LPWSTR)strPtr;
        strPtr = (pDriverStrings) ? pDriverStrings + (*pcbNeeded) : NULL;
    }

    if (Level == 6 ) {
        RegCloseKey(hkeyDriver);
        return TRUE;
    }

    /* support is missing, but not important enough for a FIXME */
    TRACE("level 8: incomplete\n");

5237
    TRACE("buffer space %d required %d\n", cbBuf, *pcbNeeded);
5238 5239 5240
    RegCloseKey(hkeyDriver);
    return TRUE;
}
5241

5242
/*****************************************************************************
5243
 *          GetPrinterDriverW  [WINSPOOL.@]
5244
 */
5245 5246 5247
BOOL WINAPI GetPrinterDriverW(HANDLE hPrinter, LPWSTR pEnvironment,
                                  DWORD Level, LPBYTE pDriverInfo,
                                  DWORD cbBuf, LPDWORD pcbNeeded)
5248
{
5249
    LPCWSTR name;
5250
    WCHAR DriverName[100];
5251
    DWORD ret, type, size, needed = 0;
5252
    LPBYTE ptr = NULL;
5253
    HKEY hkeyPrinter, hkeyDrivers;
5254
    const printenv_t * env;
5255

5256
    TRACE("(%p,%s,%d,%p,%d,%p)\n",hPrinter,debugstr_w(pEnvironment),
5257
	  Level,pDriverInfo,cbBuf, pcbNeeded);
5258

5259 5260
    if (cbBuf > 0)
        ZeroMemory(pDriverInfo, cbBuf);
5261

5262 5263 5264 5265
    if (!(name = get_opened_printer_name(hPrinter))) {
        SetLastError(ERROR_INVALID_HANDLE);
        return FALSE;
    }
5266

5267
    if (Level < 1 || Level == 7 || Level > 8) {
5268
        SetLastError(ERROR_INVALID_LEVEL);
5269
        return FALSE;
5270
    }
5271 5272 5273 5274

    env = validate_envW(pEnvironment);
    if (!env) return FALSE;     /* SetLastError() is in validate_envW */

5275 5276 5277 5278 5279 5280
    ret = open_printer_reg_key( name, &hkeyPrinter );
    if (ret)
    {
        ERR( "Can't find opened printer %s in registry\n", debugstr_w(name) );
        SetLastError( ret );
        return FALSE;
5281
    }
5282

5283
    size = sizeof(DriverName);
5284
    DriverName[0] = 0;
5285 5286
    ret = RegQueryValueExW(hkeyPrinter, Printer_DriverW, 0, &type,
			   (LPBYTE)DriverName, &size);
5287 5288
    RegCloseKey(hkeyPrinter);
    if(ret != ERROR_SUCCESS) {
5289
        ERR("Can't get DriverName for printer %s\n", debugstr_w(name));
5290 5291
	return FALSE;
    }
5292

5293
    hkeyDrivers = WINSPOOL_OpenDriverReg(pEnvironment);
5294
    if(!hkeyDrivers) {
5295 5296 5297 5298
        ERR("Can't create Drivers key\n");
	return FALSE;
    }

5299 5300
    size = di_sizeof[Level];
    if ((size <= cbBuf) && pDriverInfo)
5301 5302
        ptr = pDriverInfo + size;

5303
    if(!WINSPOOL_GetDriverInfoFromReg(hkeyDrivers, DriverName,
5304
                         env, Level, pDriverInfo, ptr,
5305
                         (cbBuf < size) ? 0 : cbBuf - size,
5306
                         &needed)) {
5307 5308
            RegCloseKey(hkeyDrivers);
            return FALSE;
5309
    }
5310

5311 5312
    RegCloseKey(hkeyDrivers);

5313
    if(pcbNeeded) *pcbNeeded = size + needed;
5314
    TRACE("buffer space %d required %d\n", cbBuf, size + needed);
5315
    if(cbBuf >= size + needed) return TRUE;
5316
    SetLastError(ERROR_INSUFFICIENT_BUFFER);
5317 5318 5319
    return FALSE;
}

5320
/*****************************************************************************
5321
 *          GetPrinterDriverA  [WINSPOOL.@]
5322 5323 5324 5325 5326 5327
 */
BOOL WINAPI GetPrinterDriverA(HANDLE hPrinter, LPSTR pEnvironment,
			      DWORD Level, LPBYTE pDriverInfo,
			      DWORD cbBuf, LPDWORD pcbNeeded)
{
    BOOL ret;
5328
    UNICODE_STRING pEnvW;
5329
    PWSTR pwstrEnvW;
5330 5331 5332
    LPBYTE buf = NULL;

    if (cbBuf)
5333 5334
    {
        ZeroMemory(pDriverInfo, cbBuf);
5335
        buf = HeapAlloc(GetProcessHeap(), 0, cbBuf);
5336 5337
    }

5338
    pwstrEnvW = asciitounicode(&pEnvW, pEnvironment);
5339 5340 5341 5342 5343 5344 5345
    ret = GetPrinterDriverW(hPrinter, pwstrEnvW, Level, buf,
				    cbBuf, pcbNeeded);
    if (ret)
        convert_driverinfo_W_to_A(pDriverInfo, buf, Level, cbBuf, 1);

    HeapFree(GetProcessHeap(), 0, buf);

5346
    RtlFreeUnicodeString(&pEnvW);
5347 5348
    return ret;
}
5349 5350

/*****************************************************************************
5351
 *       GetPrinterDriverDirectoryW  [WINSPOOL.@]
5352 5353 5354 5355 5356 5357 5358 5359 5360 5361 5362 5363 5364 5365 5366
 *
 * Return the PATH for the Printer-Drivers (UNICODE)
 *
 * PARAMS
 *   pName            [I] Servername (NT only) or NULL (local Computer)
 *   pEnvironment     [I] Printing-Environment (see below) or NULL (Default)
 *   Level            [I] Structure-Level (must be 1)
 *   pDriverDirectory [O] PTR to Buffer that receives the Result
 *   cbBuf            [I] Size of Buffer at pDriverDirectory
 *   pcbNeeded        [O] PTR to DWORD that receives the size in Bytes used / 
 *                        required for pDriverDirectory
 *
 * RETURNS
 *   Success: TRUE  and in pcbNeeded the Bytes used in pDriverDirectory
 *   Failure: FALSE and in pcbNeeded the Bytes required for pDriverDirectory,
5367
 *   if cbBuf is too small
5368 5369 5370 5371 5372 5373 5374 5375 5376
 * 
 *   Native Values returned in pDriverDirectory on Success:
 *|  NT(Windows NT x86):  "%winsysdir%\\spool\\DRIVERS\\w32x86" 
 *|  NT(Windows 4.0):     "%winsysdir%\\spool\\DRIVERS\\win40" 
 *|  win9x(Windows 4.0):  "%winsysdir%" 
 *
 *   "%winsysdir%" is the Value from GetSystemDirectoryW()
 *
 * FIXME
5377
 *-  Only NULL or "" is supported for pName
5378
 *
5379
 */
5380
BOOL WINAPI GetPrinterDriverDirectoryW(LPWSTR pName, LPWSTR pEnvironment,
5381 5382 5383
				       DWORD Level, LPBYTE pDriverDirectory,
				       DWORD cbBuf, LPDWORD pcbNeeded)
{
5384
    TRACE("(%s, %s, %d, %p, %d, %p)\n", debugstr_w(pName), 
5385
          debugstr_w(pEnvironment), Level, pDriverDirectory, cbBuf, pcbNeeded);
5386

5387
    if ((backend == NULL)  && !load_backend()) return FALSE;
5388

5389 5390
    if (Level != 1) {
        /* (Level != 1) is ignored in win9x */
5391 5392
        SetLastError(ERROR_INVALID_LEVEL);
        return FALSE;
5393
    }
5394 5395
    if (pcbNeeded == NULL) {
        /* (pcbNeeded == NULL) is ignored in win9x */
5396 5397
        SetLastError(RPC_X_NULL_REF_POINTER);
        return FALSE;
5398
    }
5399 5400 5401 5402

    return backend->fpGetPrinterDriverDirectory(pName, pEnvironment, Level,
                                                pDriverDirectory, cbBuf, pcbNeeded);

5403 5404 5405 5406
}


/*****************************************************************************
5407
 *       GetPrinterDriverDirectoryA  [WINSPOOL.@]
5408 5409 5410 5411 5412 5413 5414 5415
 *
 * Return the PATH for the Printer-Drivers (ANSI)
 *
 * See GetPrinterDriverDirectoryW.
 *
 * NOTES
 * On NT, pDriverDirectory need the same Size as the Unicode-Version
 *
5416
 */
5417
BOOL WINAPI GetPrinterDriverDirectoryA(LPSTR pName, LPSTR pEnvironment,
5418 5419 5420
				       DWORD Level, LPBYTE pDriverDirectory,
				       DWORD cbBuf, LPDWORD pcbNeeded)
{
5421
    UNICODE_STRING nameW, environmentW;
5422
    BOOL ret;
5423 5424 5425 5426
    DWORD pcbNeededW;
    INT len = cbBuf * sizeof(WCHAR)/sizeof(CHAR);
    WCHAR *driverDirectoryW = NULL;

5427
    TRACE("(%s, %s, %d, %p, %d, %p)\n", debugstr_a(pName), 
5428 5429
          debugstr_a(pEnvironment), Level, pDriverDirectory, cbBuf, pcbNeeded);
 
5430 5431 5432 5433 5434 5435 5436 5437 5438 5439
    if (len) driverDirectoryW = HeapAlloc( GetProcessHeap(), 0, len );

    if(pName) RtlCreateUnicodeStringFromAsciiz(&nameW, pName);
    else nameW.Buffer = NULL;
    if(pEnvironment) RtlCreateUnicodeStringFromAsciiz(&environmentW, pEnvironment);
    else environmentW.Buffer = NULL;

    ret = GetPrinterDriverDirectoryW( nameW.Buffer, environmentW.Buffer, Level,
				      (LPBYTE)driverDirectoryW, len, &pcbNeededW );
    if (ret) {
5440
        DWORD needed;
5441
        needed =  WideCharToMultiByte( CP_ACP, 0, driverDirectoryW, -1, 
Mike McCormack's avatar
Mike McCormack committed
5442
                                   (LPSTR)pDriverDirectory, cbBuf, NULL, NULL);
5443
        if(pcbNeeded)
5444
            *pcbNeeded = needed;
5445
        ret = needed <= cbBuf;
5446
    } else 
5447
        if(pcbNeeded) *pcbNeeded = pcbNeededW * sizeof(CHAR)/sizeof(WCHAR);
5448

5449
    TRACE("required: 0x%x/%d\n", pcbNeeded ? *pcbNeeded : 0, pcbNeeded ? *pcbNeeded : 0);
5450

5451
    HeapFree( GetProcessHeap(), 0, driverDirectoryW );
5452 5453
    RtlFreeUnicodeString(&environmentW);
    RtlFreeUnicodeString(&nameW);
5454 5455 5456 5457

    return ret;
}

5458
/*****************************************************************************
5459
 *          AddPrinterDriverA  [WINSPOOL.@]
5460 5461 5462
 *
 * See AddPrinterDriverW.
 *
5463
 */
5464
BOOL WINAPI AddPrinterDriverA(LPSTR pName, DWORD level, LPBYTE pDriverInfo)
5465
{
5466 5467
    TRACE("(%s, %d, %p)\n", debugstr_a(pName), level, pDriverInfo);
    return AddPrinterDriverExA(pName, level, pDriverInfo, APD_COPY_NEW_FILES);
5468
}
5469

5470 5471 5472 5473 5474 5475 5476 5477 5478 5479 5480 5481 5482 5483
/******************************************************************************
 *  AddPrinterDriverW (WINSPOOL.@)
 *
 * Install a Printer Driver
 *
 * PARAMS
 *  pName           [I] Servername or NULL (local Computer)
 *  level           [I] Level for the supplied DRIVER_INFO_*W struct
 *  pDriverInfo     [I] PTR to DRIVER_INFO_*W struct with the Driver Parameter
 *
 * RESULTS
 *  Success: TRUE
 *  Failure: FALSE
 *
5484
 */
5485
BOOL WINAPI AddPrinterDriverW(LPWSTR pName, DWORD level, LPBYTE pDriverInfo)
5486
{
5487 5488
    TRACE("(%s, %d, %p)\n", debugstr_w(pName), level, pDriverInfo);
    return AddPrinterDriverExW(pName, level, pDriverInfo, APD_COPY_NEW_FILES);
5489 5490
}

5491 5492 5493 5494 5495 5496
/*****************************************************************************
 *          AddPrintProcessorA  [WINSPOOL.@]
 */
BOOL WINAPI AddPrintProcessorA(LPSTR pName, LPSTR pEnvironment, LPSTR pPathName,
                               LPSTR pPrintProcessorName)
{
5497 5498 5499 5500
    UNICODE_STRING NameW, EnvW, PathW, ProcessorW;
    BOOL ret;

    TRACE("(%s,%s,%s,%s)\n", debugstr_a(pName), debugstr_a(pEnvironment),
5501
          debugstr_a(pPathName), debugstr_a(pPrintProcessorName));
5502 5503 5504 5505 5506 5507 5508 5509 5510 5511 5512 5513 5514 5515

    asciitounicode(&NameW, pName);
    asciitounicode(&EnvW, pEnvironment);
    asciitounicode(&PathW, pPathName);
    asciitounicode(&ProcessorW, pPrintProcessorName);

    ret = AddPrintProcessorW(NameW.Buffer, EnvW.Buffer, PathW.Buffer, ProcessorW.Buffer);

    RtlFreeUnicodeString(&ProcessorW);
    RtlFreeUnicodeString(&PathW);
    RtlFreeUnicodeString(&EnvW);
    RtlFreeUnicodeString(&NameW);

    return ret;
5516 5517 5518 5519 5520 5521 5522 5523 5524 5525
}

/*****************************************************************************
 *          AddPrintProcessorW  [WINSPOOL.@]
 */
BOOL WINAPI AddPrintProcessorW(LPWSTR pName, LPWSTR pEnvironment, LPWSTR pPathName,
                               LPWSTR pPrintProcessorName)
{
    FIXME("(%s,%s,%s,%s): stub\n", debugstr_w(pName), debugstr_w(pEnvironment),
          debugstr_w(pPathName), debugstr_w(pPrintProcessorName));
5526
    return TRUE;
5527 5528 5529 5530 5531 5532 5533
}

/*****************************************************************************
 *          AddPrintProvidorA  [WINSPOOL.@]
 */
BOOL WINAPI AddPrintProvidorA(LPSTR pName, DWORD Level, LPBYTE pProviderInfo)
{
5534
    FIXME("(%s,0x%08x,%p): stub\n", debugstr_a(pName), Level, pProviderInfo);
5535 5536 5537 5538 5539 5540 5541 5542
    return FALSE;
}

/*****************************************************************************
 *          AddPrintProvidorW  [WINSPOOL.@]
 */
BOOL WINAPI AddPrintProvidorW(LPWSTR pName, DWORD Level, LPBYTE pProviderInfo)
{
5543
    FIXME("(%s,0x%08x,%p): stub\n", debugstr_w(pName), Level, pProviderInfo);
5544 5545 5546 5547 5548 5549 5550 5551 5552 5553 5554 5555 5556 5557 5558 5559 5560 5561 5562 5563 5564 5565 5566 5567
    return FALSE;
}

/*****************************************************************************
 *          AdvancedDocumentPropertiesA  [WINSPOOL.@]
 */
LONG WINAPI AdvancedDocumentPropertiesA(HWND hWnd, HANDLE hPrinter, LPSTR pDeviceName,
                                        PDEVMODEA pDevModeOutput, PDEVMODEA pDevModeInput)
{
    FIXME("(%p,%p,%s,%p,%p): stub\n", hWnd, hPrinter, debugstr_a(pDeviceName),
          pDevModeOutput, pDevModeInput);
    return 0;
}

/*****************************************************************************
 *          AdvancedDocumentPropertiesW  [WINSPOOL.@]
 */
LONG WINAPI AdvancedDocumentPropertiesW(HWND hWnd, HANDLE hPrinter, LPWSTR pDeviceName,
                                        PDEVMODEW pDevModeOutput, PDEVMODEW pDevModeInput)
{
    FIXME("(%p,%p,%s,%p,%p): stub\n", hWnd, hPrinter, debugstr_w(pDeviceName),
          pDevModeOutput, pDevModeInput);
    return 0;
}
5568 5569

/*****************************************************************************
5570
 *          PrinterProperties  [WINSPOOL.@]
5571 5572 5573
 *
 *     Displays a dialog to set the properties of the printer.
 *
5574
 * RETURNS
5575
 *     nonzero on success or zero on failure
5576 5577 5578 5579
 *
 * BUGS
 *	   implemented as stub only
 */
5580 5581
BOOL WINAPI PrinterProperties(HWND hWnd,      /* [in] handle to parent window */
                              HANDLE hPrinter /* [in] handle to printer object */
5582
){
5583
    FIXME("(%p,%p): stub\n", hWnd, hPrinter);
5584 5585 5586 5587
    SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
    return FALSE;
}

Huw D M Davies's avatar
Huw D M Davies committed
5588
/*****************************************************************************
5589
 *          EnumJobsA [WINSPOOL.@]
Huw D M Davies's avatar
Huw D M Davies committed
5590 5591 5592 5593 5594 5595
 *
 */
BOOL WINAPI EnumJobsA(HANDLE hPrinter, DWORD FirstJob, DWORD NoJobs,
		      DWORD Level, LPBYTE pJob, DWORD cbBuf, LPDWORD pcbNeeded,
		      LPDWORD pcReturned)
{
5596
    FIXME("(%p,first=%d,no=%d,level=%d,job=%p,cb=%d,%p,%p), stub!\n",
5597 5598
	hPrinter, FirstJob, NoJobs, Level, pJob, cbBuf, pcbNeeded, pcReturned
    );
Huw D M Davies's avatar
Huw D M Davies committed
5599 5600
    if(pcbNeeded) *pcbNeeded = 0;
    if(pcReturned) *pcReturned = 0;
5601
    return FALSE;
Huw D M Davies's avatar
Huw D M Davies committed
5602 5603
}

5604

Huw D M Davies's avatar
Huw D M Davies committed
5605
/*****************************************************************************
5606
 *          EnumJobsW [WINSPOOL.@]
Huw D M Davies's avatar
Huw D M Davies committed
5607 5608 5609 5610 5611 5612
 *
 */
BOOL WINAPI EnumJobsW(HANDLE hPrinter, DWORD FirstJob, DWORD NoJobs,
		      DWORD Level, LPBYTE pJob, DWORD cbBuf, LPDWORD pcbNeeded,
		      LPDWORD pcReturned)
{
5613
    FIXME("(%p,first=%d,no=%d,level=%d,job=%p,cb=%d,%p,%p), stub!\n",
5614 5615
	hPrinter, FirstJob, NoJobs, Level, pJob, cbBuf, pcbNeeded, pcReturned
    );
Huw D M Davies's avatar
Huw D M Davies committed
5616 5617
    if(pcbNeeded) *pcbNeeded = 0;
    if(pcReturned) *pcReturned = 0;
5618
    return FALSE;
Huw D M Davies's avatar
Huw D M Davies committed
5619
}
5620 5621 5622 5623

/*****************************************************************************
 *          WINSPOOL_EnumPrinterDrivers [internal]
 *
5624
 *    Delivers information about all printer drivers installed on the
5625 5626 5627
 *    localhost or a given server
 *
 * RETURNS
5628
 *    nonzero on success or zero on failure. If the buffer for the returned
5629 5630 5631 5632 5633
 *    information is too small the function will return an error
 *
 * BUGS
 *    - only implemented for localhost, foreign hosts will return an error
 */
5634
static BOOL WINSPOOL_EnumPrinterDrivers(LPWSTR pName, LPCWSTR pEnvironment,
5635
                                        DWORD Level, LPBYTE pDriverInfo,
5636
                                        DWORD driver_index,
5637
                                        DWORD cbBuf, LPDWORD pcbNeeded,
5638
                                        LPDWORD pcFound, DWORD data_offset)
5639 5640

{   HKEY  hkeyDrivers;
5641
    DWORD i, size = 0;
5642
    const printenv_t * env;
5643

5644
    TRACE("%s,%s,%d,%p,%d,%d,%d\n",
5645
          debugstr_w(pName), debugstr_w(pEnvironment),
5646
          Level, pDriverInfo, driver_index, cbBuf, data_offset);
5647

5648 5649 5650
    env = validate_envW(pEnvironment);
    if (!env) return FALSE;     /* SetLastError() is in validate_envW */

5651
    *pcFound = 0;
5652

5653
    hkeyDrivers = WINSPOOL_OpenDriverReg(pEnvironment);
5654
    if(!hkeyDrivers) {
5655 5656 5657 5658
        ERR("Can't open Drivers key\n");
        return FALSE;
    }

5659
    if(RegQueryInfoKeyA(hkeyDrivers, NULL, NULL, NULL, pcFound, NULL, NULL,
5660 5661 5662 5663 5664
                        NULL, NULL, NULL, NULL, NULL) != ERROR_SUCCESS) {
        RegCloseKey(hkeyDrivers);
        ERR("Can't query Drivers key\n");
        return FALSE;
    }
5665
    TRACE("Found %d Drivers\n", *pcFound);
5666 5667 5668 5669

    /* get size of single struct
     * unicode and ascii structure have the same size
     */
5670
    size = di_sizeof[Level];
5671

5672 5673 5674 5675 5676 5677 5678 5679 5680
    if (data_offset == 0)
        data_offset = size * (*pcFound);
    *pcbNeeded = data_offset;

    for( i = 0; i < *pcFound; i++) {
        WCHAR DriverNameW[255];
        PBYTE table_ptr = NULL;
        PBYTE data_ptr = NULL;
        DWORD needed = 0;
5681

5682
        if(RegEnumKeyW(hkeyDrivers, i, DriverNameW, ARRAY_SIZE(DriverNameW)) != ERROR_SUCCESS) {
5683
            ERR("Can't enum key number %d\n", i);
5684 5685 5686
            RegCloseKey(hkeyDrivers);
            return FALSE;
        }
5687 5688 5689 5690 5691 5692

        if (pDriverInfo && ((driver_index + i + 1) * size) <= cbBuf)
            table_ptr = pDriverInfo + (driver_index + i) * size;
        if (pDriverInfo && *pcbNeeded <= cbBuf)
            data_ptr = pDriverInfo + *pcbNeeded;

5693
        if(!WINSPOOL_GetDriverInfoFromReg(hkeyDrivers, DriverNameW,
5694
                         env, Level, table_ptr, data_ptr,
5695
                         (cbBuf < *pcbNeeded) ? 0 : cbBuf - *pcbNeeded,
5696
                         &needed)) {
5697 5698 5699
            RegCloseKey(hkeyDrivers);
            return FALSE;
        }
5700

5701
        *pcbNeeded += needed;
5702 5703 5704 5705 5706 5707 5708 5709 5710 5711 5712 5713 5714
    }

    RegCloseKey(hkeyDrivers);

    if(cbBuf < *pcbNeeded){
        SetLastError(ERROR_INSUFFICIENT_BUFFER);
        return FALSE;
    }

    return TRUE;
}

/*****************************************************************************
5715
 *          EnumPrinterDriversW  [WINSPOOL.@]
5716 5717 5718 5719 5720 5721 5722
 *
 *    see function EnumPrinterDrivers for RETURNS, BUGS
 */
BOOL WINAPI EnumPrinterDriversW(LPWSTR pName, LPWSTR pEnvironment, DWORD Level,
                                LPBYTE pDriverInfo, DWORD cbBuf,
                                LPDWORD pcbNeeded, LPDWORD pcReturned)
{
5723
    static const WCHAR allW[] = {'a','l','l',0};
5724 5725 5726 5727 5728 5729 5730 5731
    BOOL ret;
    DWORD found;

    if ((pcbNeeded == NULL) || (pcReturned == NULL))
    {
        SetLastError(RPC_X_NULL_REF_POINTER);
        return FALSE;
    }
5732

5733 5734 5735 5736 5737 5738 5739 5740 5741 5742 5743 5744 5745 5746 5747 5748 5749
    /* check for local drivers */
    if((pName) && (pName[0])) {
        FIXME("remote drivers (%s) not supported!\n", debugstr_w(pName));
        SetLastError(ERROR_ACCESS_DENIED);
        return FALSE;
    }

    /* check input parameter */
    if ((Level < 1) || (Level == 7) || (Level > 8)) {
        SetLastError(ERROR_INVALID_LEVEL);
        return FALSE;
    }

    if(pDriverInfo && cbBuf > 0)
        memset( pDriverInfo, 0, cbBuf);

    /* Exception:  pull all printers */
5750 5751
    if (pEnvironment && !strcmpW(pEnvironment, allW))
    {
5752 5753 5754 5755 5756 5757
        DWORD i, needed, bufsize = cbBuf;
        DWORD total_found = 0;
        DWORD data_offset;

        /* Precompute the overall total; we need this to know
           where pointers end and data begins (i.e. data_offset) */
5758
        for (i = 0; i < ARRAY_SIZE(all_printenv); i++)
5759 5760 5761 5762 5763 5764 5765 5766 5767
        {
            needed = found = 0;
            ret = WINSPOOL_EnumPrinterDrivers(pName, all_printenv[i]->envname, Level,
                                              NULL, 0, 0, &needed, &found, 0);
            if (!ret && GetLastError() != ERROR_INSUFFICIENT_BUFFER) return FALSE;
            total_found += found;
        }

        data_offset = di_sizeof[Level] * total_found;
5768

5769 5770 5771
        *pcReturned = 0;
        *pcbNeeded = 0;
        total_found = 0;
5772
        for (i = 0; i < ARRAY_SIZE(all_printenv); i++)
5773
        {
5774
            needed = found = 0;
5775
            ret = WINSPOOL_EnumPrinterDrivers(pName, all_printenv[i]->envname, Level,
5776
                                              pDriverInfo, total_found, bufsize, &needed, &found, data_offset);
5777 5778
            if (!ret && GetLastError() != ERROR_INSUFFICIENT_BUFFER) return FALSE;
            else if (ret)
5779 5780 5781 5782
                *pcReturned += found;
            *pcbNeeded = needed;
            data_offset = needed;
            total_found += found;
5783 5784 5785
        }
        return ret;
    }
5786 5787 5788 5789 5790 5791 5792 5793

    /* Normal behavior */
    ret = WINSPOOL_EnumPrinterDrivers(pName, pEnvironment, Level, pDriverInfo,
                                       0, cbBuf, pcbNeeded, &found, 0);
    if (ret)
        *pcReturned = found;

    return ret;
5794 5795 5796
}

/*****************************************************************************
5797
 *          EnumPrinterDriversA  [WINSPOOL.@]
5798 5799 5800 5801 5802 5803
 *
 *    see function EnumPrinterDrivers for RETURNS, BUGS
 */
BOOL WINAPI EnumPrinterDriversA(LPSTR pName, LPSTR pEnvironment, DWORD Level,
                                LPBYTE pDriverInfo, DWORD cbBuf,
                                LPDWORD pcbNeeded, LPDWORD pcReturned)
5804 5805
{
    BOOL ret;
5806
    UNICODE_STRING pNameW, pEnvironmentW;
5807
    PWSTR pwstrNameW, pwstrEnvironmentW;
5808 5809 5810 5811
    LPBYTE buf = NULL;

    if (cbBuf)
        buf = HeapAlloc(GetProcessHeap(), 0, cbBuf);
5812

5813 5814
    pwstrNameW = asciitounicode(&pNameW, pName);
    pwstrEnvironmentW = asciitounicode(&pEnvironmentW, pEnvironment);
5815

5816 5817 5818 5819 5820 5821
    ret = EnumPrinterDriversW(pwstrNameW, pwstrEnvironmentW, Level,
                                buf, cbBuf, pcbNeeded, pcReturned);
    if (ret)
        convert_driverinfo_W_to_A(pDriverInfo, buf, Level, cbBuf, *pcReturned);

    HeapFree(GetProcessHeap(), 0, buf);
5822

5823 5824
    RtlFreeUnicodeString(&pNameW);
    RtlFreeUnicodeString(&pEnvironmentW);
5825 5826 5827

    return ret;
}
5828 5829

/******************************************************************************
5830
 *		EnumPortsA   (WINSPOOL.@)
5831 5832 5833
 *
 * See EnumPortsW.
 *
5834
 */
5835 5836
BOOL WINAPI EnumPortsA( LPSTR pName, DWORD Level, LPBYTE pPorts, DWORD cbBuf,
                        LPDWORD pcbNeeded, LPDWORD pcReturned)
5837
{
5838 5839 5840 5841 5842 5843
    BOOL    res;
    LPBYTE  bufferW = NULL;
    LPWSTR  nameW = NULL;
    DWORD   needed = 0;
    DWORD   numentries = 0;
    INT     len;
5844

5845 5846
    TRACE("(%s, %d, %p, %d, %p, %p)\n", debugstr_a(pName), Level, pPorts,
          cbBuf, pcbNeeded, pcReturned);
5847

5848 5849 5850 5851 5852
    /* convert servername to unicode */
    if (pName) {
        len = MultiByteToWideChar(CP_ACP, 0, pName, -1, NULL, 0);
        nameW = HeapAlloc(GetProcessHeap(), 0, len * sizeof(WCHAR));
        MultiByteToWideChar(CP_ACP, 0, pName, -1, nameW, len);
5853
    }
5854 5855 5856 5857
    /* alloc (userbuffersize*sizeof(WCHAR) and try to enum the Ports */
    needed = cbBuf * sizeof(WCHAR);    
    if (needed) bufferW = HeapAlloc(GetProcessHeap(), 0, needed);
    res = EnumPortsW(nameW, Level, bufferW, needed, pcbNeeded, pcReturned);
5858

5859 5860 5861 5862 5863
    if(!res && (GetLastError() == ERROR_INSUFFICIENT_BUFFER)) {
        if (pcbNeeded) needed = *pcbNeeded;
        /* HeapReAlloc return NULL, when bufferW was NULL */
        bufferW = (bufferW) ? HeapReAlloc(GetProcessHeap(), 0, bufferW, needed) :
                              HeapAlloc(GetProcessHeap(), 0, needed);
5864

5865 5866
        /* Try again with the large Buffer */
        res = EnumPortsW(nameW, Level, bufferW, needed, pcbNeeded, pcReturned);
5867
    }
5868 5869
    needed = pcbNeeded ? *pcbNeeded : 0;
    numentries = pcReturned ? *pcReturned : 0;
Mike McCormack's avatar
Mike McCormack committed
5870

5871 5872 5873 5874 5875
    /*
       W2k require the buffersize from EnumPortsW also for EnumPortsA.
       We use the smaller Ansi-Size to avoid conflicts with fixed Buffers of old Apps.
     */
    if (res) {
5876
        /* EnumPortsW collected all Data. Parse them to calculate ANSI-Size */
5877 5878 5879 5880 5881 5882 5883 5884 5885 5886 5887 5888 5889 5890 5891 5892 5893 5894 5895 5896 5897 5898 5899 5900 5901 5902 5903 5904 5905
        DWORD   entrysize = 0;
        DWORD   index;
        LPSTR   ptr;
        LPPORT_INFO_2W pi2w;
        LPPORT_INFO_2A pi2a;

        needed = 0;
        entrysize = (Level == 1) ? sizeof(PORT_INFO_1A) : sizeof(PORT_INFO_2A);

        /* First pass: calculate the size for all Entries */
        pi2w = (LPPORT_INFO_2W) bufferW;
        pi2a = (LPPORT_INFO_2A) pPorts;
        index = 0;
        while (index < numentries) {
            index++;
            needed += entrysize;    /* PORT_INFO_?A */
            TRACE("%p: parsing #%d (%s)\n", pi2w, index, debugstr_w(pi2w->pPortName));

            needed += WideCharToMultiByte(CP_ACP, 0, pi2w->pPortName, -1,
                                            NULL, 0, NULL, NULL);
            if (Level > 1) {
                needed += WideCharToMultiByte(CP_ACP, 0, pi2w->pMonitorName, -1,
                                                NULL, 0, NULL, NULL);
                needed += WideCharToMultiByte(CP_ACP, 0, pi2w->pDescription, -1,
                                                NULL, 0, NULL, NULL);
            }
            /* use LPBYTE with entrysize to avoid double code (PORT_INFO_1 + PORT_INFO_2) */
            pi2w = (LPPORT_INFO_2W) (((LPBYTE)pi2w) + entrysize);
            pi2a = (LPPORT_INFO_2A) (((LPBYTE)pi2a) + entrysize);
Mike McCormack's avatar
Mike McCormack committed
5906
        }
5907

5908 5909 5910 5911 5912 5913 5914 5915 5916 5917 5918 5919 5920 5921 5922 5923 5924 5925 5926 5927 5928 5929 5930 5931 5932 5933 5934 5935 5936 5937 5938 5939 5940 5941 5942 5943 5944
        /* check for errors and quit on failure */
        if (cbBuf < needed) {
            SetLastError(ERROR_INSUFFICIENT_BUFFER);
            res = FALSE;
            goto cleanup;
        }
        len = entrysize * numentries;       /* room for all PORT_INFO_?A */
        ptr = (LPSTR) &pPorts[len];         /* room for strings */
        cbBuf -= len ;                      /* free Bytes in the user-Buffer */
        pi2w = (LPPORT_INFO_2W) bufferW;
        pi2a = (LPPORT_INFO_2A) pPorts;
        index = 0;
        /* Second Pass: Fill the User Buffer (if we have one) */
        while ((index < numentries) && pPorts) {
            index++;
            TRACE("%p: writing PORT_INFO_%dA #%d\n", pi2a, Level, index);
            pi2a->pPortName = ptr;
            len = WideCharToMultiByte(CP_ACP, 0, pi2w->pPortName, -1,
                                            ptr, cbBuf , NULL, NULL);
            ptr += len;
            cbBuf -= len;
            if (Level > 1) {
                pi2a->pMonitorName = ptr;
                len = WideCharToMultiByte(CP_ACP, 0, pi2w->pMonitorName, -1,
                                            ptr, cbBuf, NULL, NULL);
                ptr += len;
                cbBuf -= len;

                pi2a->pDescription = ptr;
                len = WideCharToMultiByte(CP_ACP, 0, pi2w->pDescription, -1,
                                            ptr, cbBuf, NULL, NULL);
                ptr += len;
                cbBuf -= len;

                pi2a->fPortType = pi2w->fPortType;
                pi2a->Reserved = 0;              /* documented: "must be zero" */
                
5945
            }
5946 5947 5948
            /* use LPBYTE with entrysize to avoid double code (PORT_INFO_1 + PORT_INFO_2) */
            pi2w = (LPPORT_INFO_2W) (((LPBYTE)pi2w) + entrysize);
            pi2a = (LPPORT_INFO_2A) (((LPBYTE)pi2a) + entrysize);
Mike McCormack's avatar
Mike McCormack committed
5949
        }
5950 5951
    }

5952 5953 5954
cleanup:
    if (pcbNeeded)  *pcbNeeded = needed;
    if (pcReturned) *pcReturned = (res) ? numentries : 0;
5955

5956 5957
    HeapFree(GetProcessHeap(), 0, nameW);
    HeapFree(GetProcessHeap(), 0, bufferW);
5958

5959 5960 5961 5962
    TRACE("returning %d with %d (%d byte for %d of %d entries)\n", 
            (res), GetLastError(), needed, (res)? numentries : 0, numentries);

    return (res);
5963

5964
}
5965

5966 5967
/******************************************************************************
 *      EnumPortsW   (WINSPOOL.@)
5968 5969 5970 5971
 *
 * Enumerate available Ports
 *
 * PARAMS
5972 5973 5974 5975 5976 5977
 *  pName      [I] Servername or NULL (local Computer)
 *  Level      [I] Structure-Level (1 or 2)
 *  pPorts     [O] PTR to Buffer that receives the Result
 *  cbBuf      [I] Size of Buffer at pPorts
 *  pcbNeeded  [O] PTR to DWORD that receives the size in Bytes used / required for pPorts
 *  pcReturned [O] PTR to DWORD that receives the number of Ports in pPorts
5978 5979 5980
 *
 * RETURNS
 *  Success: TRUE
5981
 *  Failure: FALSE and in pcbNeeded the Bytes required for pPorts, if cbBuf is too small
5982
 *
5983
 */
5984
BOOL WINAPI EnumPortsW(LPWSTR pName, DWORD Level, LPBYTE pPorts, DWORD cbBuf, LPDWORD pcbNeeded, LPDWORD pcReturned)
5985
{
5986 5987 5988 5989

    TRACE("(%s, %d, %p, %d, %p, %p)\n", debugstr_w(pName), Level, pPorts,
          cbBuf, pcbNeeded, pcReturned);

5990
    if ((backend == NULL)  && !load_backend()) return FALSE;
5991 5992 5993 5994 5995

    /* Level is not checked in win9x */
    if (!Level || (Level > 2)) {
        WARN("level (%d) is ignored in win9x\n", Level);
        SetLastError(ERROR_INVALID_LEVEL);
5996
        return FALSE;
5997
    }
5998
    if (!pcbNeeded || (!pPorts && (cbBuf > 0))) {
5999
        SetLastError(RPC_X_NULL_REF_POINTER);
6000
        return FALSE;
6001 6002
    }

6003
    return backend->fpEnumPorts(pName, Level, pPorts, cbBuf, pcbNeeded, pcReturned);
6004
}
6005

6006
/******************************************************************************
6007 6008 6009 6010 6011
 *		GetDefaultPrinterW   (WINSPOOL.@)
 *
 * FIXME
 *	This function must read the value from data 'device' of key
 *	HCU\\Software\\Microsoft\\Windows NT\\CurrentVersion\\Windows
6012
 */
6013
BOOL WINAPI GetDefaultPrinterW(LPWSTR name, LPDWORD namesize)
6014
{
6015 6016 6017
    BOOL  retval = TRUE;
    DWORD insize, len;
    WCHAR *buffer, *ptr;
6018

6019 6020 6021 6022 6023
    if (!namesize)
    {
        SetLastError(ERROR_INVALID_PARAMETER);
        return FALSE;
    }
6024

6025 6026
    /* make the buffer big enough for the stuff from the profile/registry,
     * the content must fit into the local buffer to compute the correct
6027
     * size even if the extern buffer is too small or not given.
6028 6029 6030 6031
     * (20 for ,driver,port) */
    insize = *namesize;
    len = max(100, (insize + 20));
    buffer = HeapAlloc( GetProcessHeap(), 0, len * sizeof(WCHAR));
6032

6033 6034 6035 6036 6037 6038 6039 6040 6041 6042 6043 6044 6045 6046
    if (!GetProfileStringW(windowsW, deviceW, emptyStringW, buffer, len))
    {
        SetLastError (ERROR_FILE_NOT_FOUND);
        retval = FALSE;
        goto end;
    }
    TRACE("%s\n", debugstr_w(buffer));

    if ((ptr = strchrW(buffer, ',')) == NULL)
    {
        SetLastError(ERROR_INVALID_NAME);
        retval = FALSE;
        goto end;
    }
6047

6048 6049 6050 6051 6052 6053 6054 6055 6056 6057 6058
    *ptr = 0;
    *namesize = strlenW(buffer) + 1;
    if(!name || (*namesize > insize))
    {
        SetLastError(ERROR_INSUFFICIENT_BUFFER);
        retval = FALSE;
        goto end;
    }
    strcpyW(name, buffer);

end:
6059
    HeapFree( GetProcessHeap(), 0, buffer);
6060
    return retval;
6061 6062 6063 6064
}


/******************************************************************************
6065
 *		GetDefaultPrinterA   (WINSPOOL.@)
6066
 */
6067
BOOL WINAPI GetDefaultPrinterA(LPSTR name, LPDWORD namesize)
6068
{
6069 6070 6071 6072 6073 6074 6075 6076 6077 6078 6079 6080 6081 6082 6083 6084 6085 6086 6087 6088 6089 6090 6091 6092 6093 6094 6095
    BOOL  retval = TRUE;
    DWORD insize = 0;
    WCHAR *bufferW = NULL;

    if (!namesize)
    {
        SetLastError(ERROR_INVALID_PARAMETER);
        return FALSE;
    }

    if(name && *namesize) {
	insize = *namesize;
	bufferW = HeapAlloc( GetProcessHeap(), 0, insize * sizeof(WCHAR));
    }

    if(!GetDefaultPrinterW( bufferW, namesize)) {
	retval = FALSE;
	goto end;
    }

    *namesize = WideCharToMultiByte(CP_ACP, 0, bufferW, -1, name, insize,
                                    NULL, NULL);
    if (!*namesize)
    {
        *namesize = WideCharToMultiByte(CP_ACP, 0, bufferW, -1, NULL, 0, NULL, NULL);
        retval = FALSE;
    }
6096
    TRACE("0x%08x/0x%08x:%s\n", *namesize, insize, debugstr_w(bufferW));
6097 6098

end:
6099
    HeapFree( GetProcessHeap(), 0, bufferW);
6100
    return retval;
6101 6102 6103
}


6104 6105 6106 6107 6108 6109 6110 6111 6112 6113 6114 6115 6116 6117 6118 6119 6120 6121 6122 6123 6124
/******************************************************************************
 *		SetDefaultPrinterW   (WINSPOOL.204)
 *
 * Set the Name of the Default Printer
 *
 * PARAMS
 *  pszPrinter [I] Name of the Printer or NULL
 *
 * RETURNS
 *  Success:    True
 *  Failure:    FALSE
 *
 * NOTES
 *  When the Parameter is NULL or points to an Empty String and
 *  a Default Printer was already present, then this Function changes nothing.
 *  Without a Default Printer and NULL (or an Empty String) as Parameter,
 *  the First enumerated local Printer is used.
 *
 */
BOOL WINAPI SetDefaultPrinterW(LPCWSTR pszPrinter)
{
6125 6126 6127 6128 6129 6130
    WCHAR   default_printer[MAX_PATH];
    LPWSTR  buffer = NULL;
    HKEY    hreg;
    DWORD   size;
    DWORD   namelen;
    LONG    lres;
6131 6132

    TRACE("(%s)\n", debugstr_w(pszPrinter));
6133
    if ((pszPrinter == NULL) || (pszPrinter[0] == '\0')) {
6134

6135
        default_printer[0] = '\0';
6136
        size = ARRAY_SIZE(default_printer);
6137 6138 6139 6140 6141 6142 6143 6144 6145 6146

        /* if we have a default Printer, do nothing. */
        if (GetDefaultPrinterW(default_printer, &size))
            return TRUE;

        pszPrinter = NULL;
        /* we have no default Printer: search local Printers and use the first */
        if (!RegOpenKeyExW(HKEY_LOCAL_MACHINE, PrintersW, 0, KEY_READ, &hreg)) {

            default_printer[0] = '\0';
6147
            size = ARRAY_SIZE(default_printer);
6148 6149 6150 6151 6152 6153 6154 6155 6156 6157 6158 6159 6160 6161 6162 6163 6164 6165 6166 6167 6168 6169 6170 6171 6172 6173 6174 6175 6176 6177 6178 6179 6180 6181 6182
            if (!RegEnumKeyExW(hreg, 0, default_printer, &size, NULL, NULL, NULL, NULL)) {

                pszPrinter = default_printer;
                TRACE("using %s\n", debugstr_w(pszPrinter));
            }
            RegCloseKey(hreg);
        }

        if (pszPrinter == NULL) {
            TRACE("no local printer found\n");
            SetLastError(ERROR_FILE_NOT_FOUND);
            return FALSE;
        }
    }

    /* "pszPrinter" is never empty or NULL here. */
    namelen = lstrlenW(pszPrinter);
    size = namelen + (MAX_PATH * 2) + 3; /* printer,driver,port and a 0 */
    buffer = HeapAlloc(GetProcessHeap(), 0, size * sizeof(WCHAR));
    if (!buffer ||
        (RegOpenKeyExW(HKEY_CURRENT_USER, user_printers_reg_key, 0, KEY_READ, &hreg) != ERROR_SUCCESS)) {
        HeapFree(GetProcessHeap(), 0, buffer);
        SetLastError(ERROR_FILE_NOT_FOUND);
        return FALSE;
    }

    /* read the devices entry for the printer (driver,port) to build the string for the
       default device entry (printer,driver,port) */
    memcpy(buffer, pszPrinter, namelen * sizeof(WCHAR));
    buffer[namelen] = ',';
    namelen++; /* move index to the start of the driver */

    size = ((MAX_PATH * 2) + 2) * sizeof(WCHAR); /* driver,port and a 0 */
    lres = RegQueryValueExW(hreg, pszPrinter, NULL, NULL, (LPBYTE) (&buffer[namelen]), &size);
    if (!lres) {
6183
        HKEY hdev;
6184

6185
        if (!RegCreateKeyW(HKEY_CURRENT_USER, user_default_reg_key, &hdev))
6186
        {
6187 6188
            RegSetValueExW(hdev, deviceW, 0, REG_SZ, (BYTE *)buffer, (lstrlenW(buffer) + 1) * sizeof(WCHAR));
            RegCloseKey(hdev);
6189 6190 6191 6192 6193 6194 6195 6196 6197 6198 6199 6200 6201
        }
    }
    else
    {
        if (lres != ERROR_FILE_NOT_FOUND)
            FIXME("RegQueryValueExW failed with %d for %s\n", lres, debugstr_w(pszPrinter));

        SetLastError(ERROR_INVALID_PRINTER_NAME);
    }

    RegCloseKey(hreg);
    HeapFree(GetProcessHeap(), 0, buffer);
    return (lres == ERROR_SUCCESS);
6202 6203 6204 6205 6206 6207 6208 6209 6210 6211
}

/******************************************************************************
 *		SetDefaultPrinterA   (WINSPOOL.202)
 *
 * See SetDefaultPrinterW.
 *
 */
BOOL WINAPI SetDefaultPrinterA(LPCSTR pszPrinter)
{
6212 6213
    LPWSTR  bufferW = NULL;
    BOOL    res;
6214 6215

    TRACE("(%s)\n", debugstr_a(pszPrinter));
6216 6217 6218 6219 6220 6221 6222 6223
    if(pszPrinter) {
        INT len = MultiByteToWideChar(CP_ACP, 0, pszPrinter, -1, NULL, 0);
        bufferW = HeapAlloc(GetProcessHeap(), 0, len * sizeof(WCHAR));
        if (bufferW) MultiByteToWideChar(CP_ACP, 0, pszPrinter, -1, bufferW, len);
    }
    res = SetDefaultPrinterW(bufferW);
    HeapFree(GetProcessHeap(), 0, bufferW);
    return res;
6224 6225
}

6226
/******************************************************************************
6227
 *		SetPrinterDataExA   (WINSPOOL.@)
6228
 */
6229 6230
DWORD WINAPI SetPrinterDataExA(HANDLE hPrinter, LPCSTR pKeyName,
			       LPCSTR pValueName, DWORD Type,
6231 6232 6233 6234 6235
			       LPBYTE pData, DWORD cbData)
{
    HKEY hkeyPrinter, hkeySubkey;
    DWORD ret;

6236
    TRACE("(%p, %s, %s %08x, %p, %08x)\n", hPrinter, debugstr_a(pKeyName),
6237 6238 6239 6240 6241 6242 6243 6244 6245 6246 6247 6248 6249 6250 6251 6252 6253 6254 6255
	  debugstr_a(pValueName), Type, pData, cbData);

    if((ret = WINSPOOL_GetOpenedPrinterRegKey(hPrinter, &hkeyPrinter))
       != ERROR_SUCCESS)
        return ret;

    if((ret = RegCreateKeyA(hkeyPrinter, pKeyName, &hkeySubkey))
       != ERROR_SUCCESS) {
        ERR("Can't create subkey %s\n", debugstr_a(pKeyName));
	RegCloseKey(hkeyPrinter);
	return ret;
    }
    ret = RegSetValueExA(hkeySubkey, pValueName, 0, Type, pData, cbData);
    RegCloseKey(hkeySubkey);
    RegCloseKey(hkeyPrinter);
    return ret;
}

/******************************************************************************
6256
 *		SetPrinterDataExW   (WINSPOOL.@)
6257
 */
6258 6259
DWORD WINAPI SetPrinterDataExW(HANDLE hPrinter, LPCWSTR pKeyName,
			       LPCWSTR pValueName, DWORD Type,
6260 6261 6262 6263 6264
			       LPBYTE pData, DWORD cbData)
{
    HKEY hkeyPrinter, hkeySubkey;
    DWORD ret;

6265
    TRACE("(%p, %s, %s %08x, %p, %08x)\n", hPrinter, debugstr_w(pKeyName),
6266 6267 6268 6269 6270 6271 6272 6273 6274 6275 6276 6277 6278 6279 6280 6281 6282 6283 6284
	  debugstr_w(pValueName), Type, pData, cbData);

    if((ret = WINSPOOL_GetOpenedPrinterRegKey(hPrinter, &hkeyPrinter))
       != ERROR_SUCCESS)
        return ret;

    if((ret = RegCreateKeyW(hkeyPrinter, pKeyName, &hkeySubkey))
       != ERROR_SUCCESS) {
        ERR("Can't create subkey %s\n", debugstr_w(pKeyName));
	RegCloseKey(hkeyPrinter);
	return ret;
    }
    ret = RegSetValueExW(hkeySubkey, pValueName, 0, Type, pData, cbData);
    RegCloseKey(hkeySubkey);
    RegCloseKey(hkeyPrinter);
    return ret;
}

/******************************************************************************
6285
 *		SetPrinterDataA   (WINSPOOL.@)
6286 6287 6288 6289 6290 6291 6292 6293 6294
 */
DWORD WINAPI SetPrinterDataA(HANDLE hPrinter, LPSTR pValueName, DWORD Type,
			       LPBYTE pData, DWORD cbData)
{
    return SetPrinterDataExA(hPrinter, "PrinterDriverData", pValueName, Type,
			     pData, cbData);
}

/******************************************************************************
6295
 *		SetPrinterDataW   (WINSPOOL.@)
6296 6297 6298 6299 6300 6301 6302 6303 6304
 */
DWORD WINAPI SetPrinterDataW(HANDLE hPrinter, LPWSTR pValueName, DWORD Type,
			     LPBYTE pData, DWORD cbData)
{
    return SetPrinterDataExW(hPrinter, PrinterDriverDataW, pValueName, Type,
			     pData, cbData);
}

/******************************************************************************
6305
 *		GetPrinterDataExA   (WINSPOOL.@)
6306
 */
6307 6308
DWORD WINAPI GetPrinterDataExA(HANDLE hPrinter, LPCSTR pKeyName,
			       LPCSTR pValueName, LPDWORD pType,
6309 6310
			       LPBYTE pData, DWORD nSize, LPDWORD pcbNeeded)
{
6311 6312
    opened_printer_t *printer;
    HKEY hkeyPrinters, hkeyPrinter = 0, hkeySubkey = 0;
6313 6314
    DWORD ret;

6315 6316
    TRACE("(%p, %s, %s, %p, %p, %u, %p)\n", hPrinter, debugstr_a(pKeyName),
            debugstr_a(pValueName), pType, pData, nSize, pcbNeeded);
6317

6318 6319
    printer = get_opened_printer(hPrinter);
    if(!printer) return ERROR_INVALID_HANDLE;
6320

6321 6322 6323
    ret = RegOpenKeyW(HKEY_LOCAL_MACHINE, PrintersW, &hkeyPrinters);
    if (ret) return ret;

6324 6325
    TRACE("printer->name: %s\n", debugstr_w(printer->name));

6326 6327 6328 6329 6330 6331 6332 6333 6334 6335 6336 6337 6338
    if (printer->name) {

        ret = RegOpenKeyW(hkeyPrinters, printer->name, &hkeyPrinter);
        if (ret) {
            RegCloseKey(hkeyPrinters);
            return ret;
        }
        if((ret = RegOpenKeyA(hkeyPrinter, pKeyName, &hkeySubkey)) != ERROR_SUCCESS) {
            WARN("Can't open subkey %s: %d\n", debugstr_a(pKeyName), ret);
            RegCloseKey(hkeyPrinter);
            RegCloseKey(hkeyPrinters);
            return ret;
        }
6339 6340
    }
    *pcbNeeded = nSize;
6341 6342 6343
    ret = RegQueryValueExA(printer->name ? hkeySubkey : hkeyPrinters, pValueName,
                          0, pType, pData, pcbNeeded);

6344 6345
    if (!ret && !pData) ret = ERROR_MORE_DATA;

6346 6347
    RegCloseKey(hkeySubkey);
    RegCloseKey(hkeyPrinter);
6348
    RegCloseKey(hkeyPrinters);
6349 6350

    TRACE("--> %d\n", ret);
6351 6352 6353 6354
    return ret;
}

/******************************************************************************
6355
 *		GetPrinterDataExW   (WINSPOOL.@)
6356
 */
6357 6358
DWORD WINAPI GetPrinterDataExW(HANDLE hPrinter, LPCWSTR pKeyName,
			       LPCWSTR pValueName, LPDWORD pType,
6359 6360
			       LPBYTE pData, DWORD nSize, LPDWORD pcbNeeded)
{
6361 6362
    opened_printer_t *printer;
    HKEY hkeyPrinters, hkeyPrinter = 0, hkeySubkey = 0;
6363 6364
    DWORD ret;

6365 6366
    TRACE("(%p, %s, %s, %p, %p, %u, %p)\n", hPrinter, debugstr_w(pKeyName),
            debugstr_w(pValueName), pType, pData, nSize, pcbNeeded);
6367

6368 6369
    printer = get_opened_printer(hPrinter);
    if(!printer) return ERROR_INVALID_HANDLE;
6370

6371 6372 6373
    ret = RegOpenKeyW(HKEY_LOCAL_MACHINE, PrintersW, &hkeyPrinters);
    if (ret) return ret;

6374 6375
    TRACE("printer->name: %s\n", debugstr_w(printer->name));

6376 6377 6378 6379 6380 6381 6382 6383 6384 6385 6386 6387 6388
    if (printer->name) {

        ret = RegOpenKeyW(hkeyPrinters, printer->name, &hkeyPrinter);
        if (ret) {
            RegCloseKey(hkeyPrinters);
            return ret;
        }
        if((ret = RegOpenKeyW(hkeyPrinter, pKeyName, &hkeySubkey)) != ERROR_SUCCESS) {
            WARN("Can't open subkey %s: %d\n", debugstr_w(pKeyName), ret);
            RegCloseKey(hkeyPrinter);
            RegCloseKey(hkeyPrinters);
            return ret;
        }
6389 6390
    }
    *pcbNeeded = nSize;
6391 6392 6393
    ret = RegQueryValueExW(printer->name ? hkeySubkey : hkeyPrinters, pValueName,
                          0, pType, pData, pcbNeeded);

6394 6395
    if (!ret && !pData) ret = ERROR_MORE_DATA;

6396 6397
    RegCloseKey(hkeySubkey);
    RegCloseKey(hkeyPrinter);
6398
    RegCloseKey(hkeyPrinters);
6399 6400

    TRACE("--> %d\n", ret);
6401 6402 6403 6404
    return ret;
}

/******************************************************************************
6405
 *		GetPrinterDataA   (WINSPOOL.@)
6406 6407 6408 6409 6410 6411 6412 6413 6414
 */
DWORD WINAPI GetPrinterDataA(HANDLE hPrinter, LPSTR pValueName, LPDWORD pType,
			     LPBYTE pData, DWORD nSize, LPDWORD pcbNeeded)
{
    return GetPrinterDataExA(hPrinter, "PrinterDriverData", pValueName, pType,
			     pData, nSize, pcbNeeded);
}

/******************************************************************************
6415
 *		GetPrinterDataW   (WINSPOOL.@)
6416 6417 6418 6419 6420 6421 6422
 */
DWORD WINAPI GetPrinterDataW(HANDLE hPrinter, LPWSTR pValueName, LPDWORD pType,
			     LPBYTE pData, DWORD nSize, LPDWORD pcbNeeded)
{
    return GetPrinterDataExW(hPrinter, PrinterDriverDataW, pValueName, pType,
			     pData, nSize, pcbNeeded);
}
6423 6424

/*******************************************************************************
6425
 *		EnumPrinterDataExW	[WINSPOOL.@]
6426 6427 6428 6429 6430 6431 6432 6433 6434 6435 6436 6437 6438 6439
 */
DWORD WINAPI EnumPrinterDataExW(HANDLE hPrinter, LPCWSTR pKeyName,
				LPBYTE pEnumValues, DWORD cbEnumValues,
				LPDWORD pcbEnumValues, LPDWORD pnEnumValues)
{
    HKEY		    hkPrinter, hkSubKey;
    DWORD		    r, ret, dwIndex, cValues, cbMaxValueNameLen,
			    cbValueNameLen, cbMaxValueLen, cbValueLen,
			    cbBufSize, dwType;
    LPWSTR		    lpValueName;
    HANDLE		    hHeap;
    PBYTE		    lpValue;
    PPRINTER_ENUM_VALUESW   ppev;

6440
    TRACE ("%p %s\n", hPrinter, debugstr_w (pKeyName));
6441 6442 6443 6444 6445 6446 6447

    if (pKeyName == NULL || *pKeyName == 0)
	return ERROR_INVALID_PARAMETER;

    ret = WINSPOOL_GetOpenedPrinterRegKey (hPrinter, &hkPrinter);
    if (ret != ERROR_SUCCESS)
    {
6448
	TRACE ("WINSPOOL_GetOpenedPrinterRegKey (%p) returned %i\n",
6449 6450 6451 6452 6453 6454 6455 6456 6457
		hPrinter, ret);
	return ret;
    }

    ret = RegOpenKeyExW (hkPrinter, pKeyName, 0, KEY_READ, &hkSubKey);
    if (ret != ERROR_SUCCESS)
    {
	r = RegCloseKey (hkPrinter);
	if (r != ERROR_SUCCESS)
6458 6459
	    WARN ("RegCloseKey returned %i\n", r);
	TRACE ("RegOpenKeyExW (%p, %s) returned %i\n", hPrinter,
6460 6461 6462 6463 6464 6465 6466
		debugstr_w (pKeyName), ret);
	return ret;
    }

    ret = RegCloseKey (hkPrinter);
    if (ret != ERROR_SUCCESS)
    {
6467
	ERR ("RegCloseKey returned %i\n", ret);
6468 6469
	r = RegCloseKey (hkSubKey);
	if (r != ERROR_SUCCESS)
6470
	    WARN ("RegCloseKey returned %i\n", r);
6471 6472 6473 6474 6475 6476 6477 6478 6479
	return ret;
    }

    ret = RegQueryInfoKeyW (hkSubKey, NULL, NULL, NULL, NULL, NULL, NULL,
	    &cValues, &cbMaxValueNameLen, &cbMaxValueLen, NULL, NULL);
    if (ret != ERROR_SUCCESS)
    {
	r = RegCloseKey (hkSubKey);
	if (r != ERROR_SUCCESS)
6480 6481
	    WARN ("RegCloseKey returned %i\n", r);
	TRACE ("RegQueryInfoKeyW (%p) returned %i\n", hkSubKey, ret);
6482 6483 6484
	return ret;
    }

6485 6486
    TRACE ("RegQueryInfoKeyW returned cValues = %i, cbMaxValueNameLen = %i, "
	    "cbMaxValueLen = %i\n", cValues, cbMaxValueNameLen, cbMaxValueLen);
6487 6488 6489 6490 6491

    if (cValues == 0)			/* empty key */
    {
	r = RegCloseKey (hkSubKey);
	if (r != ERROR_SUCCESS)
6492
	    WARN ("RegCloseKey returned %i\n", r);
6493 6494 6495 6496 6497 6498 6499
	*pcbEnumValues = *pnEnumValues = 0;
	return ERROR_SUCCESS;
    }

    ++cbMaxValueNameLen;			/* allow for trailing '\0' */

    hHeap = GetProcessHeap ();
6500
    if (hHeap == NULL)
6501 6502 6503 6504
    {
	ERR ("GetProcessHeap failed\n");
	r = RegCloseKey (hkSubKey);
	if (r != ERROR_SUCCESS)
6505
	    WARN ("RegCloseKey returned %i\n", r);
6506 6507 6508 6509 6510 6511
	return ERROR_OUTOFMEMORY;
    }

    lpValueName = HeapAlloc (hHeap, 0, cbMaxValueNameLen * sizeof (WCHAR));
    if (lpValueName == NULL)
    {
6512
	ERR ("Failed to allocate %i WCHARs from process heap\n", cbMaxValueNameLen);
6513 6514
	r = RegCloseKey (hkSubKey);
	if (r != ERROR_SUCCESS)
6515
	    WARN ("RegCloseKey returned %i\n", r);
6516 6517 6518 6519 6520 6521
	return ERROR_OUTOFMEMORY;
    }

    lpValue = HeapAlloc (hHeap, 0, cbMaxValueLen);
    if (lpValue == NULL)
    {
6522
	ERR ("Failed to allocate %i bytes from process heap\n", cbMaxValueLen);
6523
	if (HeapFree (hHeap, 0, lpValueName) == 0)
6524
	    WARN ("HeapFree failed with code %i\n", GetLastError ());
6525 6526
	r = RegCloseKey (hkSubKey);
	if (r != ERROR_SUCCESS)
6527
	    WARN ("RegCloseKey returned %i\n", r);
6528 6529 6530 6531 6532 6533 6534
	return ERROR_OUTOFMEMORY;
    }

    TRACE ("pass 1: calculating buffer required for all names and values\n");

    cbBufSize = cValues * sizeof (PRINTER_ENUM_VALUESW);

6535
    TRACE ("%i bytes required for %i headers\n", cbBufSize, cValues);
6536 6537 6538 6539 6540 6541 6542 6543 6544

    for (dwIndex = 0; dwIndex < cValues; ++dwIndex)
    {
	cbValueNameLen = cbMaxValueNameLen; cbValueLen = cbMaxValueLen;
	ret = RegEnumValueW (hkSubKey, dwIndex, lpValueName, &cbValueNameLen,
		NULL, NULL, lpValue, &cbValueLen);
	if (ret != ERROR_SUCCESS)
	{
	    if (HeapFree (hHeap, 0, lpValue) == 0)
6545
		WARN ("HeapFree failed with code %i\n", GetLastError ());
6546
	    if (HeapFree (hHeap, 0, lpValueName) == 0)
6547
		WARN ("HeapFree failed with code %i\n", GetLastError ());
6548 6549
	    r = RegCloseKey (hkSubKey);
	    if (r != ERROR_SUCCESS)
6550 6551
		WARN ("RegCloseKey returned %i\n", r);
	    TRACE ("RegEnumValueW (%i) returned %i\n", dwIndex, ret);
6552 6553 6554
	    return ret;
	}

6555
	TRACE ("%s [%i]: name needs %i WCHARs, data needs %i bytes\n",
6556
		debugstr_w (lpValueName), dwIndex,
6557
		cbValueNameLen + 1, cbValueLen);
6558 6559 6560 6561 6562

	cbBufSize += (cbValueNameLen + 1) * sizeof (WCHAR);
	cbBufSize += cbValueLen;
    }

6563
    TRACE ("%i bytes required for all %i values\n", cbBufSize, cValues);
6564 6565 6566 6567 6568 6569 6570

    *pcbEnumValues = cbBufSize;
    *pnEnumValues = cValues;

    if (cbEnumValues < cbBufSize)	/* buffer too small */
    {
	if (HeapFree (hHeap, 0, lpValue) == 0)
6571
	    WARN ("HeapFree failed with code %i\n", GetLastError ());
6572
	if (HeapFree (hHeap, 0, lpValueName) == 0)
6573
	    WARN ("HeapFree failed with code %i\n", GetLastError ());
6574 6575
	r = RegCloseKey (hkSubKey);
	if (r != ERROR_SUCCESS)
6576 6577
	    WARN ("RegCloseKey returned %i\n", r);
	TRACE ("%i byte buffer is not large enough\n", cbEnumValues);
6578 6579 6580 6581 6582 6583 6584 6585 6586 6587 6588 6589 6590 6591 6592 6593
	return ERROR_MORE_DATA;
    }

    TRACE ("pass 2: copying all names and values to buffer\n");

    ppev = (PPRINTER_ENUM_VALUESW) pEnumValues;		/* array of structs */
    pEnumValues += cValues * sizeof (PRINTER_ENUM_VALUESW);

    for (dwIndex = 0; dwIndex < cValues; ++dwIndex)
    {
	cbValueNameLen = cbMaxValueNameLen; cbValueLen = cbMaxValueLen;
	ret = RegEnumValueW (hkSubKey, dwIndex, lpValueName, &cbValueNameLen,
		NULL, &dwType, lpValue, &cbValueLen);
	if (ret != ERROR_SUCCESS)
	{
	    if (HeapFree (hHeap, 0, lpValue) == 0)
6594
		WARN ("HeapFree failed with code %i\n", GetLastError ());
6595
	    if (HeapFree (hHeap, 0, lpValueName) == 0)
6596
		WARN ("HeapFree failed with code %i\n", GetLastError ());
6597 6598
	    r = RegCloseKey (hkSubKey);
	    if (r != ERROR_SUCCESS)
6599 6600
		WARN ("RegCloseKey returned %i\n", r);
	    TRACE ("RegEnumValueW (%i) returned %i\n", dwIndex, ret);
6601 6602 6603 6604 6605 6606 6607 6608 6609 6610 6611 6612 6613 6614 6615 6616 6617 6618 6619
	    return ret;
	}

	cbValueNameLen = (cbValueNameLen + 1) * sizeof (WCHAR);
	memcpy (pEnumValues, lpValueName, cbValueNameLen);
	ppev[dwIndex].pValueName = (LPWSTR) pEnumValues;
	pEnumValues += cbValueNameLen;

	/* return # of *bytes* (including trailing \0), not # of chars */
	ppev[dwIndex].cbValueName = cbValueNameLen;

	ppev[dwIndex].dwType = dwType;

	memcpy (pEnumValues, lpValue, cbValueLen);
	ppev[dwIndex].pData = pEnumValues;
	pEnumValues += cbValueLen;

	ppev[dwIndex].cbData = cbValueLen;

6620
	TRACE ("%s [%i]: copied name (%i bytes) and data (%i bytes)\n",
6621 6622 6623 6624 6625 6626
		debugstr_w (lpValueName), dwIndex, cbValueNameLen, cbValueLen);
    }

    if (HeapFree (hHeap, 0, lpValue) == 0)
    {
	ret = GetLastError ();
6627
	ERR ("HeapFree failed with code %i\n", ret);
6628
	if (HeapFree (hHeap, 0, lpValueName) == 0)
6629
	    WARN ("HeapFree failed with code %i\n", GetLastError ());
6630 6631
	r = RegCloseKey (hkSubKey);
	if (r != ERROR_SUCCESS)
6632
	    WARN ("RegCloseKey returned %i\n", r);
6633 6634 6635 6636 6637 6638
	return ret;
    }

    if (HeapFree (hHeap, 0, lpValueName) == 0)
    {
	ret = GetLastError ();
6639
	ERR ("HeapFree failed with code %i\n", ret);
6640 6641
	r = RegCloseKey (hkSubKey);
	if (r != ERROR_SUCCESS)
6642
	    WARN ("RegCloseKey returned %i\n", r);
6643 6644 6645 6646 6647 6648
	return ret;
    }

    ret = RegCloseKey (hkSubKey);
    if (ret != ERROR_SUCCESS)
    {
6649
	ERR ("RegCloseKey returned %i\n", ret);
6650 6651 6652 6653 6654 6655 6656
	return ret;
    }

    return ERROR_SUCCESS;
}

/*******************************************************************************
6657
 *		EnumPrinterDataExA	[WINSPOOL.@]
6658 6659 6660 6661 6662 6663 6664 6665 6666 6667 6668 6669 6670 6671 6672 6673
 *
 * This functions returns value names and REG_SZ, REG_EXPAND_SZ, and
 * REG_MULTI_SZ values as ASCII strings in Unicode-sized buffers.  This is
 * what Windows 2000 SP1 does.
 *
 */
DWORD WINAPI EnumPrinterDataExA(HANDLE hPrinter, LPCSTR pKeyName,
				LPBYTE pEnumValues, DWORD cbEnumValues,
				LPDWORD pcbEnumValues, LPDWORD pnEnumValues)
{
    INT	    len;
    LPWSTR  pKeyNameW;
    DWORD   ret, dwIndex, dwBufSize;
    HANDLE  hHeap;
    LPSTR   pBuffer;

6674
    TRACE ("%p %s\n", hPrinter, pKeyName);
6675 6676 6677 6678 6679 6680 6681 6682

    if (pKeyName == NULL || *pKeyName == 0)
	return ERROR_INVALID_PARAMETER;

    len = MultiByteToWideChar (CP_ACP, 0, pKeyName, -1, NULL, 0);
    if (len == 0)
    {
	ret = GetLastError ();
6683
	ERR ("MultiByteToWideChar failed with code %i\n", ret);
6684 6685 6686 6687
	return ret;
    }

    hHeap = GetProcessHeap ();
6688
    if (hHeap == NULL)
6689 6690 6691 6692 6693 6694 6695 6696
    {
	ERR ("GetProcessHeap failed\n");
	return ERROR_OUTOFMEMORY;
    }

    pKeyNameW = HeapAlloc (hHeap, 0, len * sizeof (WCHAR));
    if (pKeyNameW == NULL)
    {
6697
	ERR ("Failed to allocate %i bytes from process heap\n",
6698
             (LONG)(len * sizeof (WCHAR)));
6699 6700 6701 6702 6703 6704
	return ERROR_OUTOFMEMORY;
    }

    if (MultiByteToWideChar (CP_ACP, 0, pKeyName, -1, pKeyNameW, len) == 0)
    {
	ret = GetLastError ();
6705
	ERR ("MultiByteToWideChar failed with code %i\n", ret);
6706
	if (HeapFree (hHeap, 0, pKeyNameW) == 0)
6707
	    WARN ("HeapFree failed with code %i\n", GetLastError ());
6708 6709 6710 6711 6712 6713 6714 6715
	return ret;
    }

    ret = EnumPrinterDataExW (hPrinter, pKeyNameW, pEnumValues, cbEnumValues,
	    pcbEnumValues, pnEnumValues);
    if (ret != ERROR_SUCCESS)
    {
	if (HeapFree (hHeap, 0, pKeyNameW) == 0)
6716 6717
	    WARN ("HeapFree failed with code %i\n", GetLastError ());
	TRACE ("EnumPrinterDataExW returned %i\n", ret);
6718 6719 6720 6721 6722 6723
	return ret;
    }

    if (HeapFree (hHeap, 0, pKeyNameW) == 0)
    {
	ret = GetLastError ();
6724
	ERR ("HeapFree failed with code %i\n", ret);
6725
	return ret;
6726
    }
6727 6728 6729 6730 6731 6732 6733 6734 6735 6736 6737 6738 6739 6740 6741 6742 6743 6744

    if (*pnEnumValues == 0)	/* empty key */
	return ERROR_SUCCESS;

    dwBufSize = 0;
    for (dwIndex = 0; dwIndex < *pnEnumValues; ++dwIndex)
    {
	PPRINTER_ENUM_VALUESW ppev =
		&((PPRINTER_ENUM_VALUESW) pEnumValues)[dwIndex];

	if (dwBufSize < ppev->cbValueName)
	    dwBufSize = ppev->cbValueName;

	if (dwBufSize < ppev->cbData && (ppev->dwType == REG_SZ ||
		ppev->dwType == REG_EXPAND_SZ || ppev->dwType == REG_MULTI_SZ))
	    dwBufSize = ppev->cbData;
    }

6745
    TRACE ("Largest Unicode name or value is %i bytes\n", dwBufSize);
6746 6747 6748 6749

    pBuffer = HeapAlloc (hHeap, 0, dwBufSize);
    if (pBuffer == NULL)
    {
6750
	ERR ("Failed to allocate %i bytes from process heap\n", dwBufSize);
6751 6752 6753 6754 6755 6756 6757 6758 6759 6760 6761 6762 6763 6764
	return ERROR_OUTOFMEMORY;
    }

    for (dwIndex = 0; dwIndex < *pnEnumValues; ++dwIndex)
    {
	PPRINTER_ENUM_VALUESW ppev =
		&((PPRINTER_ENUM_VALUESW) pEnumValues)[dwIndex];

	len = WideCharToMultiByte (CP_ACP, 0, ppev->pValueName,
		ppev->cbValueName / sizeof (WCHAR), pBuffer, dwBufSize, NULL,
		NULL);
	if (len == 0)
	{
	    ret = GetLastError ();
6765
	    ERR ("WideCharToMultiByte failed with code %i\n", ret);
6766
	    if (HeapFree (hHeap, 0, pBuffer) == 0)
6767
		WARN ("HeapFree failed with code %i\n", GetLastError ());
6768 6769 6770 6771 6772 6773 6774 6775 6776 6777 6778 6779 6780 6781 6782 6783
	    return ret;
	}

	memcpy (ppev->pValueName, pBuffer, len);

	TRACE ("Converted '%s' from Unicode to ASCII\n", pBuffer);

	if (ppev->dwType != REG_SZ && ppev->dwType != REG_EXPAND_SZ &&
		ppev->dwType != REG_MULTI_SZ)
	    continue;

	len = WideCharToMultiByte (CP_ACP, 0, (LPWSTR) ppev->pData,
		ppev->cbData / sizeof (WCHAR), pBuffer, dwBufSize, NULL, NULL);
	if (len == 0)
	{
	    ret = GetLastError ();
6784
	    ERR ("WideCharToMultiByte failed with code %i\n", ret);
6785
	    if (HeapFree (hHeap, 0, pBuffer) == 0)
6786
		WARN ("HeapFree failed with code %i\n", GetLastError ());
6787 6788 6789 6790 6791 6792 6793 6794 6795 6796 6797 6798
	    return ret;
	}

	memcpy (ppev->pData, pBuffer, len);

	TRACE ("Converted '%s' from Unicode to ASCII\n", pBuffer);
	TRACE ("  (only first string of REG_MULTI_SZ printed)\n");
    }

    if (HeapFree (hHeap, 0, pBuffer) == 0)
    {
	ret = GetLastError ();
6799
	ERR ("HeapFree failed with code %i\n", ret);
6800 6801 6802 6803 6804
	return ret;
    }

    return ERROR_SUCCESS;
}
Aric Stewart's avatar
Aric Stewart committed
6805

6806 6807 6808 6809 6810 6811 6812 6813 6814
/******************************************************************************
 *      AbortPrinter (WINSPOOL.@)
 */
BOOL WINAPI AbortPrinter( HANDLE hPrinter )
{
    FIXME("(%p), stub!\n", hPrinter);
    return TRUE;
}

Aric Stewart's avatar
Aric Stewart committed
6815 6816
/******************************************************************************
 *		AddPortA (WINSPOOL.@)
6817 6818 6819
 *
 * See AddPortW.
 *
Aric Stewart's avatar
Aric Stewart committed
6820
 */
6821
BOOL WINAPI AddPortA(LPSTR pName, HWND hWnd, LPSTR pMonitorName)
Aric Stewart's avatar
Aric Stewart committed
6822
{
6823 6824 6825 6826 6827 6828 6829 6830 6831 6832 6833 6834 6835 6836 6837 6838 6839 6840 6841 6842 6843 6844
    LPWSTR  nameW = NULL;
    LPWSTR  monitorW = NULL;
    DWORD   len;
    BOOL    res;

    TRACE("(%s, %p, %s)\n",debugstr_a(pName), hWnd, debugstr_a(pMonitorName));

    if (pName) {
        len = MultiByteToWideChar(CP_ACP, 0, pName, -1, NULL, 0);
        nameW = HeapAlloc(GetProcessHeap(), 0, len * sizeof(WCHAR));
        MultiByteToWideChar(CP_ACP, 0, pName, -1, nameW, len);
    }

    if (pMonitorName) {
        len = MultiByteToWideChar(CP_ACP, 0, pMonitorName, -1, NULL, 0);
        monitorW = HeapAlloc(GetProcessHeap(), 0, len * sizeof(WCHAR));
        MultiByteToWideChar(CP_ACP, 0, pMonitorName, -1, monitorW, len);
    }
    res = AddPortW(nameW, hWnd, monitorW);
    HeapFree(GetProcessHeap(), 0, nameW);
    HeapFree(GetProcessHeap(), 0, monitorW);
    return res;
6845 6846 6847 6848
}

/******************************************************************************
 *      AddPortW (WINSPOOL.@)
6849 6850 6851 6852 6853 6854 6855 6856 6857 6858 6859 6860
 *
 * Add a Port for a specific Monitor
 *
 * PARAMS
 *  pName        [I] Servername or NULL (local Computer)
 *  hWnd         [I] Handle to parent Window for the Dialog-Box
 *  pMonitorName [I] Name of the Monitor that manage the Port
 *
 * RETURNS
 *  Success: TRUE
 *  Failure: FALSE
 *
6861 6862 6863
 */
BOOL WINAPI AddPortW(LPWSTR pName, HWND hWnd, LPWSTR pMonitorName)
{
6864 6865
    TRACE("(%s, %p, %s)\n", debugstr_w(pName), hWnd, debugstr_w(pMonitorName));

6866
    if ((backend == NULL)  && !load_backend()) return FALSE;
6867 6868 6869 6870 6871 6872

    if (!pMonitorName) {
        SetLastError(RPC_X_NULL_REF_POINTER);
        return FALSE;
    }

6873
    return backend->fpAddPort(pName, hWnd, pMonitorName);
Aric Stewart's avatar
Aric Stewart committed
6874
}
6875

6876 6877 6878
/******************************************************************************
 *             AddPortExA (WINSPOOL.@)
 *
6879 6880
 * See AddPortExW.
 *
6881
 */
6882
BOOL WINAPI AddPortExA(LPSTR pName, DWORD level, LPBYTE pBuffer, LPSTR pMonitorName)
6883
{
6884 6885 6886 6887 6888 6889 6890 6891 6892 6893 6894 6895 6896 6897 6898 6899 6900 6901 6902 6903 6904 6905 6906 6907 6908 6909 6910 6911 6912 6913 6914 6915 6916 6917 6918 6919 6920 6921 6922 6923 6924 6925 6926 6927 6928 6929 6930 6931 6932 6933 6934 6935 6936 6937 6938 6939 6940 6941 6942 6943 6944 6945 6946 6947 6948 6949 6950
    PORT_INFO_2W   pi2W;
    PORT_INFO_2A * pi2A;
    LPWSTR  nameW = NULL;
    LPWSTR  monitorW = NULL;
    DWORD   len;
    BOOL    res;

    pi2A = (PORT_INFO_2A *) pBuffer;

    TRACE("(%s, %d, %p, %s): %s\n", debugstr_a(pName), level, pBuffer,
            debugstr_a(pMonitorName), debugstr_a(pi2A ? pi2A->pPortName : NULL));

    if ((level < 1) || (level > 2)) {
        SetLastError(ERROR_INVALID_LEVEL);
        return FALSE;
    }

    if (!pi2A) {
        SetLastError(ERROR_INVALID_PARAMETER);
        return FALSE;
    }

    if (pName) {
        len = MultiByteToWideChar(CP_ACP, 0, pName, -1, NULL, 0);
        nameW = HeapAlloc(GetProcessHeap(), 0, len * sizeof(WCHAR));
        MultiByteToWideChar(CP_ACP, 0, pName, -1, nameW, len);
    }

    if (pMonitorName) {
        len = MultiByteToWideChar(CP_ACP, 0, pMonitorName, -1, NULL, 0);
        monitorW = HeapAlloc(GetProcessHeap(), 0, len * sizeof(WCHAR));
        MultiByteToWideChar(CP_ACP, 0, pMonitorName, -1, monitorW, len);
    }

    ZeroMemory(&pi2W, sizeof(PORT_INFO_2W));

    if (pi2A->pPortName) {
        len = MultiByteToWideChar(CP_ACP, 0, pi2A->pPortName, -1, NULL, 0);
        pi2W.pPortName = HeapAlloc(GetProcessHeap(), 0, len * sizeof(WCHAR));
        MultiByteToWideChar(CP_ACP, 0, pi2A->pPortName, -1, pi2W.pPortName, len);
    }

    if (level > 1) {
        if (pi2A->pMonitorName) {
            len = MultiByteToWideChar(CP_ACP, 0, pi2A->pMonitorName, -1, NULL, 0);
            pi2W.pMonitorName = HeapAlloc(GetProcessHeap(), 0, len * sizeof(WCHAR));
            MultiByteToWideChar(CP_ACP, 0, pi2A->pMonitorName, -1, pi2W.pMonitorName, len);
        }

        if (pi2A->pDescription) {
            len = MultiByteToWideChar(CP_ACP, 0, pi2A->pDescription, -1, NULL, 0);
            pi2W.pDescription = HeapAlloc(GetProcessHeap(), 0, len * sizeof(WCHAR));
            MultiByteToWideChar(CP_ACP, 0, pi2A->pDescription, -1, pi2W.pDescription, len);
        }
        pi2W.fPortType = pi2A->fPortType;
        pi2W.Reserved = pi2A->Reserved;
    }

    res = AddPortExW(nameW, level, (LPBYTE) &pi2W, monitorW);

    HeapFree(GetProcessHeap(), 0, nameW);
    HeapFree(GetProcessHeap(), 0, monitorW);
    HeapFree(GetProcessHeap(), 0, pi2W.pPortName);
    HeapFree(GetProcessHeap(), 0, pi2W.pMonitorName);
    HeapFree(GetProcessHeap(), 0, pi2W.pDescription);
    return res;

6951 6952 6953 6954 6955
}

/******************************************************************************
 *             AddPortExW (WINSPOOL.@)
 *
6956 6957 6958 6959
 * Add a Port for a specific Monitor, without presenting a user interface
 *
 * PARAMS
 *  pName         [I] Servername or NULL (local Computer)
6960 6961 6962
 *  level         [I] Structure-Level (1 or 2) for pBuffer
 *  pBuffer       [I] PTR to: PORT_INFO_1 or PORT_INFO_2
 *  pMonitorName  [I] Name of the Monitor that manage the Port
6963 6964 6965 6966 6967
 *
 * RETURNS
 *  Success: TRUE
 *  Failure: FALSE
 *
6968
 */
6969
BOOL WINAPI AddPortExW(LPWSTR pName, DWORD level, LPBYTE pBuffer, LPWSTR pMonitorName)
6970
{
6971 6972 6973 6974 6975 6976 6977 6978 6979
    PORT_INFO_2W * pi2;

    pi2 = (PORT_INFO_2W *) pBuffer;

    TRACE("(%s, %d, %p, %s): %s %s %s\n", debugstr_w(pName), level, pBuffer,
            debugstr_w(pMonitorName), debugstr_w(pi2 ? pi2->pPortName : NULL),
            debugstr_w(((level > 1) && pi2) ? pi2->pMonitorName : NULL),
            debugstr_w(((level > 1) && pi2) ? pi2->pDescription : NULL));

6980
    if ((backend == NULL)  && !load_backend()) return FALSE;
6981

6982
    if ((!pi2) || (!pMonitorName) || (!pMonitorName[0])) {
6983 6984 6985 6986
        SetLastError(ERROR_INVALID_PARAMETER);
        return FALSE;
    }

6987
    return backend->fpAddPortEx(pName, level, pBuffer, pMonitorName);
6988 6989 6990 6991 6992 6993 6994 6995 6996 6997 6998 6999 7000 7001 7002 7003 7004 7005 7006 7007
}

/******************************************************************************
 *      AddPrinterConnectionA (WINSPOOL.@)
 */
BOOL WINAPI AddPrinterConnectionA( LPSTR pName )
{
    FIXME("%s\n", debugstr_a(pName));
    return FALSE;
}

/******************************************************************************
 *      AddPrinterConnectionW (WINSPOOL.@)
 */
BOOL WINAPI AddPrinterConnectionW( LPWSTR pName )
{
    FIXME("%s\n", debugstr_w(pName));
    return FALSE;
}

7008
/******************************************************************************
7009 7010 7011 7012 7013 7014 7015 7016 7017 7018 7019 7020 7021 7022
 *  AddPrinterDriverExW (WINSPOOL.@)
 *
 * Install a Printer Driver with the Option to upgrade / downgrade the Files
 *
 * PARAMS
 *  pName           [I] Servername or NULL (local Computer)
 *  level           [I] Level for the supplied DRIVER_INFO_*W struct
 *  pDriverInfo     [I] PTR to DRIVER_INFO_*W struct with the Driver Parameter
 *  dwFileCopyFlags [I] How to Copy / Upgrade / Downgrade the needed Files
 *
 * RESULTS
 *  Success: TRUE
 *  Failure: FALSE
 *
7023
 */
7024
BOOL WINAPI AddPrinterDriverExW( LPWSTR pName, DWORD level, LPBYTE pDriverInfo, DWORD dwFileCopyFlags)
7025
{
7026 7027
    TRACE("(%s, %d, %p, 0x%x)\n", debugstr_w(pName), level, pDriverInfo, dwFileCopyFlags);

7028 7029
    if ((backend == NULL)  && !load_backend()) return FALSE;

7030 7031 7032 7033 7034 7035 7036 7037 7038 7039
    if (level < 2 || level == 5 || level == 7 || level > 8) {
        SetLastError(ERROR_INVALID_LEVEL);
        return FALSE;
    }

    if (!pDriverInfo) {
        SetLastError(ERROR_INVALID_PARAMETER);
        return FALSE;
    }

7040
    return backend->fpAddPrinterDriverEx(pName, level, pDriverInfo, dwFileCopyFlags);
7041 7042 7043
}

/******************************************************************************
7044 7045 7046 7047
 *  AddPrinterDriverExA (WINSPOOL.@)
 *
 * See AddPrinterDriverExW.
 *
7048
 */
7049
BOOL WINAPI AddPrinterDriverExA(LPSTR pName, DWORD Level, LPBYTE pDriverInfo, DWORD dwFileCopyFlags)
7050
{
7051 7052 7053 7054 7055
    DRIVER_INFO_8A  *diA;
    DRIVER_INFO_8W   diW;
    LPWSTR  nameW = NULL;
    DWORD   lenA;
    DWORD   len;
7056
    BOOL    res = FALSE;
7057

7058 7059
    TRACE("(%s, %d, %p, 0x%x)\n", debugstr_a(pName), Level, pDriverInfo, dwFileCopyFlags);

7060 7061 7062 7063 7064 7065 7066 7067 7068 7069 7070 7071 7072 7073 7074 7075 7076 7077 7078 7079 7080 7081 7082
    diA = (DRIVER_INFO_8A  *) pDriverInfo;
    ZeroMemory(&diW, sizeof(diW));

    if (Level < 2 || Level == 5 || Level == 7 || Level > 8) {
        SetLastError(ERROR_INVALID_LEVEL);
        return FALSE;
    }

    if (diA == NULL) {
        SetLastError(ERROR_INVALID_PARAMETER);
        return FALSE;
    }

    /* convert servername to unicode */
    if (pName) {
        len = MultiByteToWideChar(CP_ACP, 0, pName, -1, NULL, 0);
        nameW = HeapAlloc(GetProcessHeap(), 0, len * sizeof(WCHAR));
        MultiByteToWideChar(CP_ACP, 0, pName, -1, nameW, len);
    }

    /* common fields */
    diW.cVersion = diA->cVersion;

7083 7084 7085 7086 7087
    if (diA->pName) {
        len = MultiByteToWideChar(CP_ACP, 0, diA->pName, -1, NULL, 0);
        diW.pName = HeapAlloc(GetProcessHeap(), 0, len * sizeof(WCHAR));
        MultiByteToWideChar(CP_ACP, 0, diA->pName, -1, diW.pName, len);
    }
7088

7089 7090 7091 7092 7093
    if (diA->pEnvironment) {
        len = MultiByteToWideChar(CP_ACP, 0, diA->pEnvironment, -1, NULL, 0);
        diW.pEnvironment = HeapAlloc(GetProcessHeap(), 0, len * sizeof(WCHAR));
        MultiByteToWideChar(CP_ACP, 0, diA->pEnvironment, -1, diW.pEnvironment, len);
    }
7094

7095 7096 7097 7098 7099
    if (diA->pDriverPath) {
        len = MultiByteToWideChar(CP_ACP, 0, diA->pDriverPath, -1, NULL, 0);
        diW.pDriverPath = HeapAlloc(GetProcessHeap(), 0, len * sizeof(WCHAR));
        MultiByteToWideChar(CP_ACP, 0, diA->pDriverPath, -1, diW.pDriverPath, len);
    }
7100

7101 7102 7103 7104 7105
    if (diA->pDataFile) {
        len = MultiByteToWideChar(CP_ACP, 0, diA->pDataFile, -1, NULL, 0);
        diW.pDataFile = HeapAlloc(GetProcessHeap(), 0, len * sizeof(WCHAR));
        MultiByteToWideChar(CP_ACP, 0, diA->pDataFile, -1, diW.pDataFile, len);
    }
7106

7107 7108 7109 7110 7111
    if (diA->pConfigFile) {
        len = MultiByteToWideChar(CP_ACP, 0, diA->pConfigFile, -1, NULL, 0);
        diW.pConfigFile = HeapAlloc(GetProcessHeap(), 0, len * sizeof(WCHAR));
        MultiByteToWideChar(CP_ACP, 0, diA->pConfigFile, -1, diW.pConfigFile, len);
    }
7112

7113 7114 7115 7116 7117 7118
    if ((Level > 2) && diA->pHelpFile) {
        len = MultiByteToWideChar(CP_ACP, 0, diA->pHelpFile, -1, NULL, 0);
        diW.pHelpFile = HeapAlloc(GetProcessHeap(), 0, len * sizeof(WCHAR));
        MultiByteToWideChar(CP_ACP, 0, diA->pHelpFile, -1, diW.pHelpFile, len);
    }

7119
    if ((Level > 2) && diA->pDependentFiles) {
7120 7121 7122 7123
        lenA = multi_sz_lenA(diA->pDependentFiles);
        len = MultiByteToWideChar(CP_ACP, 0, diA->pDependentFiles, lenA, NULL, 0);
        diW.pDependentFiles = HeapAlloc(GetProcessHeap(), 0, len * sizeof(WCHAR));
        MultiByteToWideChar(CP_ACP, 0, diA->pDependentFiles, lenA, diW.pDependentFiles, len);
7124
    }
7125

7126
    if ((Level > 2) && diA->pMonitorName) {
7127 7128 7129 7130 7131
        len = MultiByteToWideChar(CP_ACP, 0, diA->pMonitorName, -1, NULL, 0);
        diW.pMonitorName = HeapAlloc(GetProcessHeap(), 0, len * sizeof(WCHAR));
        MultiByteToWideChar(CP_ACP, 0, diA->pMonitorName, -1, diW.pMonitorName, len);
    }

7132
    if ((Level > 2) && diA->pDefaultDataType) {
7133 7134 7135
        len = MultiByteToWideChar(CP_ACP, 0, diA->pDefaultDataType, -1, NULL, 0);
        diW.pDefaultDataType = HeapAlloc(GetProcessHeap(), 0, len * sizeof(WCHAR));
        MultiByteToWideChar(CP_ACP, 0, diA->pDefaultDataType, -1, diW.pDefaultDataType, len);
7136
    }
7137

7138
    if ((Level > 3) && diA->pszzPreviousNames) {
7139 7140 7141 7142 7143 7144
        lenA = multi_sz_lenA(diA->pszzPreviousNames);
        len = MultiByteToWideChar(CP_ACP, 0, diA->pszzPreviousNames, lenA, NULL, 0);
        diW.pszzPreviousNames = HeapAlloc(GetProcessHeap(), 0, len * sizeof(WCHAR));
        MultiByteToWideChar(CP_ACP, 0, diA->pszzPreviousNames, lenA, diW.pszzPreviousNames, len);
    }

7145 7146 7147 7148 7149
    if (Level > 5) {
        diW.ftDriverDate = diA->ftDriverDate;
        diW.dwlDriverVersion = diA->dwlDriverVersion;
    }

7150
    if ((Level > 5) && diA->pszMfgName) {
7151 7152 7153
        len = MultiByteToWideChar(CP_ACP, 0, diA->pszMfgName, -1, NULL, 0);
        diW.pszMfgName = HeapAlloc(GetProcessHeap(), 0, len * sizeof(WCHAR));
        MultiByteToWideChar(CP_ACP, 0, diA->pszMfgName, -1, diW.pszMfgName, len);
7154
    }
7155

7156
    if ((Level > 5) && diA->pszOEMUrl) {
7157 7158 7159
        len = MultiByteToWideChar(CP_ACP, 0, diA->pszOEMUrl, -1, NULL, 0);
        diW.pszOEMUrl = HeapAlloc(GetProcessHeap(), 0, len * sizeof(WCHAR));
        MultiByteToWideChar(CP_ACP, 0, diA->pszOEMUrl, -1, diW.pszOEMUrl, len);
7160
    }
7161

7162
    if ((Level > 5) && diA->pszHardwareID) {
7163 7164 7165
        len = MultiByteToWideChar(CP_ACP, 0, diA->pszHardwareID, -1, NULL, 0);
        diW.pszHardwareID = HeapAlloc(GetProcessHeap(), 0, len * sizeof(WCHAR));
        MultiByteToWideChar(CP_ACP, 0, diA->pszHardwareID, -1, diW.pszHardwareID, len);
7166
    }
7167

7168
    if ((Level > 5) && diA->pszProvider) {
7169 7170 7171 7172 7173
        len = MultiByteToWideChar(CP_ACP, 0, diA->pszProvider, -1, NULL, 0);
        diW.pszProvider = HeapAlloc(GetProcessHeap(), 0, len * sizeof(WCHAR));
        MultiByteToWideChar(CP_ACP, 0, diA->pszProvider, -1, diW.pszProvider, len);
    }

7174 7175 7176 7177 7178 7179 7180 7181 7182 7183 7184 7185 7186 7187 7188 7189 7190 7191 7192 7193 7194 7195 7196 7197 7198 7199 7200 7201 7202 7203 7204 7205
    if ((Level > 7) && diA->pszPrintProcessor) {
        len = MultiByteToWideChar(CP_ACP, 0, diA->pszPrintProcessor, -1, NULL, 0);
        diW.pszPrintProcessor = HeapAlloc(GetProcessHeap(), 0, len * sizeof(WCHAR));
        MultiByteToWideChar(CP_ACP, 0, diA->pszPrintProcessor, -1, diW.pszPrintProcessor, len);
    }

    if ((Level > 7) && diA->pszVendorSetup) {
        len = MultiByteToWideChar(CP_ACP, 0, diA->pszVendorSetup, -1, NULL, 0);
        diW.pszVendorSetup = HeapAlloc(GetProcessHeap(), 0, len * sizeof(WCHAR));
        MultiByteToWideChar(CP_ACP, 0, diA->pszVendorSetup, -1, diW.pszVendorSetup, len);
    }

    if ((Level > 7) && diA->pszzColorProfiles) {
        lenA = multi_sz_lenA(diA->pszzColorProfiles);
        len = MultiByteToWideChar(CP_ACP, 0, diA->pszzColorProfiles, lenA, NULL, 0);
        diW.pszzColorProfiles = HeapAlloc(GetProcessHeap(), 0, len * sizeof(WCHAR));
        MultiByteToWideChar(CP_ACP, 0, diA->pszzColorProfiles, lenA, diW.pszzColorProfiles, len);
    }

    if ((Level > 7) && diA->pszInfPath) {
        len = MultiByteToWideChar(CP_ACP, 0, diA->pszInfPath, -1, NULL, 0);
        diW.pszInfPath = HeapAlloc(GetProcessHeap(), 0, len * sizeof(WCHAR));
        MultiByteToWideChar(CP_ACP, 0, diA->pszInfPath, -1, diW.pszInfPath, len);
    }

    if ((Level > 7) && diA->pszzCoreDriverDependencies) {
        lenA = multi_sz_lenA(diA->pszzCoreDriverDependencies);
        len = MultiByteToWideChar(CP_ACP, 0, diA->pszzCoreDriverDependencies, lenA, NULL, 0);
        diW.pszzCoreDriverDependencies = HeapAlloc(GetProcessHeap(), 0, len * sizeof(WCHAR));
        MultiByteToWideChar(CP_ACP, 0, diA->pszzCoreDriverDependencies, lenA, diW.pszzCoreDriverDependencies, len);
    }

7206
    if (Level > 7) {
7207 7208 7209
        diW.dwPrinterDriverAttributes = diA->dwPrinterDriverAttributes;
        diW.ftMinInboxDriverVerDate = diA->ftMinInboxDriverVerDate;
        diW.dwlMinInboxDriverVerVersion = diA->dwlMinInboxDriverVerVersion;
7210 7211 7212 7213 7214 7215 7216 7217 7218 7219
    }

    res = AddPrinterDriverExW(nameW, Level, (LPBYTE) &diW, dwFileCopyFlags);
    TRACE("got %u with %u\n", res, GetLastError());
    HeapFree(GetProcessHeap(), 0, nameW);
    HeapFree(GetProcessHeap(), 0, diW.pName);
    HeapFree(GetProcessHeap(), 0, diW.pEnvironment);
    HeapFree(GetProcessHeap(), 0, diW.pDriverPath);
    HeapFree(GetProcessHeap(), 0, diW.pDataFile);
    HeapFree(GetProcessHeap(), 0, diW.pConfigFile);
7220
    HeapFree(GetProcessHeap(), 0, diW.pHelpFile);
7221 7222 7223 7224 7225 7226 7227 7228
    HeapFree(GetProcessHeap(), 0, diW.pDependentFiles);
    HeapFree(GetProcessHeap(), 0, diW.pMonitorName);
    HeapFree(GetProcessHeap(), 0, diW.pDefaultDataType);
    HeapFree(GetProcessHeap(), 0, diW.pszzPreviousNames);
    HeapFree(GetProcessHeap(), 0, diW.pszMfgName);
    HeapFree(GetProcessHeap(), 0, diW.pszOEMUrl);
    HeapFree(GetProcessHeap(), 0, diW.pszHardwareID);
    HeapFree(GetProcessHeap(), 0, diW.pszProvider);
7229 7230 7231 7232 7233
    HeapFree(GetProcessHeap(), 0, diW.pszPrintProcessor);
    HeapFree(GetProcessHeap(), 0, diW.pszVendorSetup);
    HeapFree(GetProcessHeap(), 0, diW.pszzColorProfiles);
    HeapFree(GetProcessHeap(), 0, diW.pszInfPath);
    HeapFree(GetProcessHeap(), 0, diW.pszzCoreDriverDependencies);
7234 7235 7236

    TRACE("=> %u with %u\n", res, GetLastError());
    return res;
7237 7238
}

7239 7240
/******************************************************************************
 *      ConfigurePortA (WINSPOOL.@)
7241 7242 7243
 *
 * See ConfigurePortW.
 *
7244 7245 7246
 */
BOOL WINAPI ConfigurePortA(LPSTR pName, HWND hWnd, LPSTR pPortName)
{
7247 7248 7249 7250 7251 7252 7253 7254 7255 7256 7257 7258 7259 7260 7261 7262 7263 7264 7265 7266 7267 7268 7269 7270 7271
    LPWSTR  nameW = NULL;
    LPWSTR  portW = NULL;
    INT     len;
    DWORD   res;

    TRACE("(%s, %p, %s)\n", debugstr_a(pName), hWnd, debugstr_a(pPortName));

    /* convert servername to unicode */
    if (pName) {
        len = MultiByteToWideChar(CP_ACP, 0, pName, -1, NULL, 0);
        nameW = HeapAlloc(GetProcessHeap(), 0, len * sizeof(WCHAR));
        MultiByteToWideChar(CP_ACP, 0, pName, -1, nameW, len);
    }

    /* convert portname to unicode */
    if (pPortName) {
        len = MultiByteToWideChar(CP_ACP, 0, pPortName, -1, NULL, 0);
        portW = HeapAlloc(GetProcessHeap(), 0, len * sizeof(WCHAR));
        MultiByteToWideChar(CP_ACP, 0, pPortName, -1, portW, len);
    }

    res = ConfigurePortW(nameW, hWnd, portW);
    HeapFree(GetProcessHeap(), 0, nameW);
    HeapFree(GetProcessHeap(), 0, portW);
    return res;
7272 7273 7274 7275
}

/******************************************************************************
 *      ConfigurePortW (WINSPOOL.@)
7276 7277 7278 7279 7280 7281 7282 7283 7284 7285 7286 7287
 *
 * Display the Configuration-Dialog for a specific Port
 *
 * PARAMS
 *  pName     [I] Servername or NULL (local Computer)
 *  hWnd      [I] Handle to parent Window for the Dialog-Box
 *  pPortName [I] Name of the Port, that should be configured
 *
 * RETURNS
 *  Success: TRUE
 *  Failure: FALSE
 *
7288 7289 7290
 */
BOOL WINAPI ConfigurePortW(LPWSTR pName, HWND hWnd, LPWSTR pPortName)
{
7291 7292 7293

    TRACE("(%s, %p, %s)\n", debugstr_w(pName), hWnd, debugstr_w(pPortName));

7294
    if ((backend == NULL)  && !load_backend()) return FALSE;
7295 7296 7297 7298 7299 7300

    if (!pPortName) {
        SetLastError(RPC_X_NULL_REF_POINTER);
        return FALSE;
    }

7301
    return backend->fpConfigurePort(pName, hWnd, pPortName);
7302 7303
}

7304 7305 7306 7307 7308
/******************************************************************************
 *      ConnectToPrinterDlg (WINSPOOL.@)
 */
HANDLE WINAPI ConnectToPrinterDlg( HWND hWnd, DWORD Flags )
{
7309
    FIXME("%p %x\n", hWnd, Flags);
7310 7311 7312 7313 7314 7315 7316 7317 7318 7319 7320 7321 7322 7323 7324 7325 7326 7327 7328 7329 7330
    return NULL;
}

/******************************************************************************
 *      DeletePrinterConnectionA (WINSPOOL.@)
 */
BOOL WINAPI DeletePrinterConnectionA( LPSTR pName )
{
    FIXME("%s\n", debugstr_a(pName));
    return TRUE;
}

/******************************************************************************
 *      DeletePrinterConnectionW (WINSPOOL.@)
 */
BOOL WINAPI DeletePrinterConnectionW( LPWSTR pName )
{
    FIXME("%s\n", debugstr_w(pName));
    return TRUE;
}

7331 7332 7333 7334 7335 7336
/******************************************************************************
 *		DeletePrinterDriverExW (WINSPOOL.@)
 */
BOOL WINAPI DeletePrinterDriverExW( LPWSTR pName, LPWSTR pEnvironment,
    LPWSTR pDriverName, DWORD dwDeleteFlag, DWORD dwVersionFlag)
{
7337 7338 7339 7340
    HKEY hkey_drivers;
    BOOL ret = FALSE;

    TRACE("%s %s %s %x %x\n", debugstr_w(pName), debugstr_w(pEnvironment),
7341
          debugstr_w(pDriverName), dwDeleteFlag, dwVersionFlag);
7342 7343 7344 7345 7346 7347 7348 7349 7350 7351 7352 7353 7354 7355 7356

    if(pName && pName[0])
    {
        FIXME("pName = %s - unsupported\n", debugstr_w(pName));
        SetLastError(ERROR_INVALID_PARAMETER);
        return FALSE;
    }

    if(dwDeleteFlag)
    {
        FIXME("dwDeleteFlag = %x - unsupported\n", dwDeleteFlag);
        SetLastError(ERROR_INVALID_PARAMETER);
        return FALSE;
    }

7357
    hkey_drivers = WINSPOOL_OpenDriverReg(pEnvironment);
7358 7359 7360 7361 7362 7363 7364

    if(!hkey_drivers)
    {
        ERR("Can't open drivers key\n");
        return FALSE;
    }

7365
    if(RegDeleteTreeW(hkey_drivers, pDriverName) == ERROR_SUCCESS)
7366 7367 7368 7369 7370
        ret = TRUE;

    RegCloseKey(hkey_drivers);

    return ret;
7371 7372 7373 7374 7375 7376 7377 7378
}

/******************************************************************************
 *		DeletePrinterDriverExA (WINSPOOL.@)
 */
BOOL WINAPI DeletePrinterDriverExA( LPSTR pName, LPSTR pEnvironment,
    LPSTR pDriverName, DWORD dwDeleteFlag, DWORD dwVersionFlag)
{
7379 7380 7381 7382 7383 7384 7385 7386 7387 7388 7389 7390 7391 7392
    UNICODE_STRING NameW, EnvW, DriverW;
    BOOL ret;

    asciitounicode(&NameW, pName);
    asciitounicode(&EnvW, pEnvironment);
    asciitounicode(&DriverW, pDriverName);

    ret = DeletePrinterDriverExW(NameW.Buffer, EnvW.Buffer, DriverW.Buffer, dwDeleteFlag, dwVersionFlag);

    RtlFreeUnicodeString(&DriverW);
    RtlFreeUnicodeString(&EnvW);
    RtlFreeUnicodeString(&NameW);

    return ret;
7393 7394 7395 7396 7397 7398 7399 7400 7401 7402 7403 7404 7405 7406 7407 7408 7409 7410 7411 7412 7413 7414 7415 7416
}

/******************************************************************************
 *		DeletePrinterDataExW (WINSPOOL.@)
 */
DWORD WINAPI DeletePrinterDataExW( HANDLE hPrinter, LPCWSTR pKeyName,
                                  LPCWSTR pValueName)
{
    FIXME("%p %s %s\n", hPrinter, 
          debugstr_w(pKeyName), debugstr_w(pValueName));
    return ERROR_INVALID_PARAMETER;
}

/******************************************************************************
 *		DeletePrinterDataExA (WINSPOOL.@)
 */
DWORD WINAPI DeletePrinterDataExA( HANDLE hPrinter, LPCSTR pKeyName,
                                  LPCSTR pValueName)
{
    FIXME("%p %s %s\n", hPrinter, 
          debugstr_a(pKeyName), debugstr_a(pValueName));
    return ERROR_INVALID_PARAMETER;
}

7417 7418 7419 7420 7421 7422 7423 7424 7425 7426 7427 7428 7429 7430 7431 7432 7433 7434 7435 7436 7437 7438 7439 7440 7441 7442 7443 7444 7445 7446 7447 7448 7449 7450 7451 7452 7453 7454 7455 7456
/******************************************************************************
 *      DeletePrintProcessorA (WINSPOOL.@)
 */
BOOL WINAPI DeletePrintProcessorA(LPSTR pName, LPSTR pEnvironment, LPSTR pPrintProcessorName)
{
    FIXME("%s %s %s\n", debugstr_a(pName), debugstr_a(pEnvironment),
          debugstr_a(pPrintProcessorName));
    return TRUE;
}

/******************************************************************************
 *      DeletePrintProcessorW (WINSPOOL.@)
 */
BOOL WINAPI DeletePrintProcessorW(LPWSTR pName, LPWSTR pEnvironment, LPWSTR pPrintProcessorName)
{
    FIXME("%s %s %s\n", debugstr_w(pName), debugstr_w(pEnvironment),
          debugstr_w(pPrintProcessorName));
    return TRUE;
}

/******************************************************************************
 *      DeletePrintProvidorA (WINSPOOL.@)
 */
BOOL WINAPI DeletePrintProvidorA(LPSTR pName, LPSTR pEnvironment, LPSTR pPrintProviderName)
{
    FIXME("%s %s %s\n", debugstr_a(pName), debugstr_a(pEnvironment),
          debugstr_a(pPrintProviderName));
    return TRUE;
}

/******************************************************************************
 *      DeletePrintProvidorW (WINSPOOL.@)
 */
BOOL WINAPI DeletePrintProvidorW(LPWSTR pName, LPWSTR pEnvironment, LPWSTR pPrintProviderName)
{
    FIXME("%s %s %s\n", debugstr_w(pName), debugstr_w(pEnvironment),
          debugstr_w(pPrintProviderName));
    return TRUE;
}

7457 7458 7459
/******************************************************************************
 *      EnumFormsA (WINSPOOL.@)
 */
7460
BOOL WINAPI EnumFormsA( HANDLE printer, DWORD level, BYTE *form, DWORD size, DWORD *needed, DWORD *count )
7461
{
7462 7463 7464 7465 7466 7467 7468 7469 7470 7471 7472 7473
    const DWORD *string_info = form_string_info( level );
    BOOL ret;
    DWORD i;

    if (!string_info) return FALSE;

    ret = EnumFormsW( printer, level, form, size, needed, count );
    if (ret)
        for (i = 0; i < *count; i++)
            packed_struct_WtoA( form + i * string_info[0], string_info );

    return ret;
7474 7475 7476 7477 7478
}

/******************************************************************************
 *      EnumFormsW (WINSPOOL.@)
 */
7479
BOOL WINAPI EnumFormsW( HANDLE printer, DWORD level, BYTE *form, DWORD size, DWORD *needed, DWORD *count )
7480
{
7481 7482 7483 7484 7485 7486 7487 7488 7489 7490
    HANDLE handle = get_backend_handle( printer );

    TRACE( "(%p, %d, %p, %d, %p, %p)\n", printer, level, form, size, needed, count );

    if (!handle)
    {
        SetLastError( ERROR_INVALID_HANDLE );
        return FALSE;
    }

7491 7492 7493 7494 7495 7496 7497 7498 7499 7500 7501 7502
    if (!needed || !count)
    {
        SetLastError( RPC_X_NULL_REF_POINTER );
        return FALSE;
    }

    if (!form && size)
    {
        SetLastError( ERROR_INVALID_USER_BUFFER );
        return FALSE;
    }

7503
    return backend->fpEnumForms( handle, level, form, size, needed, count );
7504 7505
}

7506 7507 7508
/*****************************************************************************
 *          EnumMonitorsA [WINSPOOL.@]
 *
7509 7510
 * See EnumMonitorsW.
 *
7511 7512 7513 7514
 */
BOOL WINAPI EnumMonitorsA(LPSTR pName, DWORD Level, LPBYTE pMonitors,
                          DWORD cbBuf, LPDWORD pcbNeeded, LPDWORD pcReturned)
{
7515 7516 7517 7518 7519 7520 7521
    BOOL    res;
    LPBYTE  bufferW = NULL;
    LPWSTR  nameW = NULL;
    DWORD   needed = 0;
    DWORD   numentries = 0;
    INT     len;

7522
    TRACE("(%s, %d, %p, %d, %p, %p)\n", debugstr_a(pName), Level, pMonitors,
7523
          cbBuf, pcbNeeded, pcReturned);
7524 7525 7526 7527 7528 7529 7530 7531 7532 7533 7534 7535 7536 7537 7538 7539 7540 7541 7542 7543 7544 7545 7546 7547 7548 7549 7550 7551

    /* convert servername to unicode */
    if (pName) {
        len = MultiByteToWideChar(CP_ACP, 0, pName, -1, NULL, 0);
        nameW = HeapAlloc(GetProcessHeap(), 0, len * sizeof(WCHAR));
        MultiByteToWideChar(CP_ACP, 0, pName, -1, nameW, len);
    }
    /* alloc (userbuffersize*sizeof(WCHAR) and try to enum the monitors */
    needed = cbBuf * sizeof(WCHAR);    
    if (needed) bufferW = HeapAlloc(GetProcessHeap(), 0, needed);
    res = EnumMonitorsW(nameW, Level, bufferW, needed, pcbNeeded, pcReturned);

    if(!res && (GetLastError() == ERROR_INSUFFICIENT_BUFFER)) {
        if (pcbNeeded) needed = *pcbNeeded;
        /* HeapReAlloc return NULL, when bufferW was NULL */
        bufferW = (bufferW) ? HeapReAlloc(GetProcessHeap(), 0, bufferW, needed) :
                              HeapAlloc(GetProcessHeap(), 0, needed);

        /* Try again with the large Buffer */
        res = EnumMonitorsW(nameW, Level, bufferW, needed, pcbNeeded, pcReturned);
    }
    numentries = pcReturned ? *pcReturned : 0;
    needed = 0;
    /*
       W2k require the buffersize from EnumMonitorsW also for EnumMonitorsA.
       We use the smaller Ansi-Size to avoid conflicts with fixed Buffers of old Apps.
     */
    if (res) {
7552
        /* EnumMonitorsW collected all Data. Parse them to calculate ANSI-Size */
7553 7554 7555 7556 7557 7558 7559 7560 7561 7562 7563 7564 7565 7566 7567 7568
        DWORD   entrysize = 0;
        DWORD   index;
        LPSTR   ptr;
        LPMONITOR_INFO_2W mi2w;
        LPMONITOR_INFO_2A mi2a;

        /* MONITOR_INFO_*W and MONITOR_INFO_*A have the same size */
        entrysize = (Level == 1) ? sizeof(MONITOR_INFO_1A) : sizeof(MONITOR_INFO_2A);

        /* First pass: calculate the size for all Entries */
        mi2w = (LPMONITOR_INFO_2W) bufferW;
        mi2a = (LPMONITOR_INFO_2A) pMonitors;
        index = 0;
        while (index < numentries) {
            index++;
            needed += entrysize;    /* MONITOR_INFO_?A */
7569
            TRACE("%p: parsing #%d (%s)\n", mi2w, index, debugstr_w(mi2w->pName));
7570 7571 7572 7573 7574 7575 7576 7577 7578 7579 7580 7581 7582 7583 7584 7585 7586 7587 7588 7589 7590 7591 7592 7593 7594 7595 7596 7597 7598

            needed += WideCharToMultiByte(CP_ACP, 0, mi2w->pName, -1,
                                            NULL, 0, NULL, NULL);
            if (Level > 1) {
                needed += WideCharToMultiByte(CP_ACP, 0, mi2w->pEnvironment, -1,
                                                NULL, 0, NULL, NULL);
                needed += WideCharToMultiByte(CP_ACP, 0, mi2w->pDLLName, -1,
                                                NULL, 0, NULL, NULL);
            }
            /* use LPBYTE with entrysize to avoid double code (MONITOR_INFO_1 + MONITOR_INFO_2) */
            mi2w = (LPMONITOR_INFO_2W) (((LPBYTE)mi2w) + entrysize);
            mi2a = (LPMONITOR_INFO_2A) (((LPBYTE)mi2a) + entrysize);
        }

        /* check for errors and quit on failure */
        if (cbBuf < needed) {
            SetLastError(ERROR_INSUFFICIENT_BUFFER);
            res = FALSE;
            goto emA_cleanup;
        }
        len = entrysize * numentries;       /* room for all MONITOR_INFO_?A */
        ptr = (LPSTR) &pMonitors[len];      /* room for strings */
        cbBuf -= len ;                      /* free Bytes in the user-Buffer */
        mi2w = (LPMONITOR_INFO_2W) bufferW;
        mi2a = (LPMONITOR_INFO_2A) pMonitors;
        index = 0;
        /* Second Pass: Fill the User Buffer (if we have one) */
        while ((index < numentries) && pMonitors) {
            index++;
7599
            TRACE("%p: writing MONITOR_INFO_%dA #%d\n", mi2a, Level, index);
7600 7601 7602 7603 7604 7605 7606 7607 7608 7609 7610 7611 7612 7613 7614 7615 7616 7617 7618 7619 7620 7621 7622 7623 7624 7625 7626 7627 7628 7629
            mi2a->pName = ptr;
            len = WideCharToMultiByte(CP_ACP, 0, mi2w->pName, -1,
                                            ptr, cbBuf , NULL, NULL);
            ptr += len;
            cbBuf -= len;
            if (Level > 1) {
                mi2a->pEnvironment = ptr;
                len = WideCharToMultiByte(CP_ACP, 0, mi2w->pEnvironment, -1,
                                            ptr, cbBuf, NULL, NULL);
                ptr += len;
                cbBuf -= len;

                mi2a->pDLLName = ptr;
                len = WideCharToMultiByte(CP_ACP, 0, mi2w->pDLLName, -1,
                                            ptr, cbBuf, NULL, NULL);
                ptr += len;
                cbBuf -= len;
            }
            /* use LPBYTE with entrysize to avoid double code (MONITOR_INFO_1 + MONITOR_INFO_2) */
            mi2w = (LPMONITOR_INFO_2W) (((LPBYTE)mi2w) + entrysize);
            mi2a = (LPMONITOR_INFO_2A) (((LPBYTE)mi2a) + entrysize);
        }
    }
emA_cleanup:
    if (pcbNeeded)  *pcbNeeded = needed;
    if (pcReturned) *pcReturned = (res) ? numentries : 0;

    HeapFree(GetProcessHeap(), 0, nameW);
    HeapFree(GetProcessHeap(), 0, bufferW);

7630
    TRACE("returning %d with %d (%d byte for %d entries)\n", 
7631 7632 7633 7634
            (res), GetLastError(), needed, numentries);

    return (res);

7635 7636 7637 7638 7639
}

/*****************************************************************************
 *          EnumMonitorsW [WINSPOOL.@]
 *
7640
 * Enumerate available Port-Monitors
7641 7642 7643 7644 7645 7646 7647 7648 7649 7650 7651
 *
 * PARAMS
 *  pName       [I] Servername or NULL (local Computer)
 *  Level       [I] Structure-Level (1:Win9x+NT or 2:NT only)
 *  pMonitors   [O] PTR to Buffer that receives the Result
 *  cbBuf       [I] Size of Buffer at pMonitors
 *  pcbNeeded   [O] PTR to DWORD that receives the size in Bytes used / required for pMonitors
 *  pcReturned  [O] PTR to DWORD that receives the number of Monitors in pMonitors
 *
 * RETURNS
 *  Success: TRUE
7652
 *  Failure: FALSE and in pcbNeeded the Bytes required for buffer, if cbBuf is too small
7653
 *
7654 7655 7656 7657
 */
BOOL WINAPI EnumMonitorsW(LPWSTR pName, DWORD Level, LPBYTE pMonitors,
                          DWORD cbBuf, LPDWORD pcbNeeded, LPDWORD pcReturned)
{
7658

7659
    TRACE("(%s, %d, %p, %d, %p, %p)\n", debugstr_w(pName), Level, pMonitors,
7660
          cbBuf, pcbNeeded, pcReturned);
7661

7662
    if ((backend == NULL)  && !load_backend()) return FALSE;
7663

7664
    if (!pcbNeeded || !pcReturned || (!pMonitors && (cbBuf > 0))) {
7665
        SetLastError(RPC_X_NULL_REF_POINTER);
7666
        return FALSE;
7667 7668
    }

7669
    return backend->fpEnumMonitors(pName, Level, pMonitors, cbBuf, pcbNeeded, pcReturned);
7670 7671
}

7672 7673 7674 7675 7676 7677 7678 7679 7680 7681 7682 7683 7684 7685 7686 7687 7688 7689 7690 7691
/******************************************************************************
 * SpoolerInit (WINSPOOL.@)
 *
 * Initialize the Spooler
 *
 * RETURNS
 *  Success: TRUE
 *  Failure: FALSE
 *
 * NOTES
 *  The function fails on windows, when the spooler service is not running
 *
 */
BOOL WINAPI SpoolerInit(void)
{

    if ((backend == NULL)  && !load_backend()) return FALSE;
    return TRUE;
}

7692 7693 7694
/******************************************************************************
 *		XcvDataW (WINSPOOL.@)
 *
7695 7696 7697 7698 7699 7700 7701 7702 7703 7704 7705 7706 7707 7708 7709 7710 7711 7712 7713 7714 7715 7716 7717 7718 7719 7720 7721 7722 7723 7724
 * Execute commands in the Printmonitor DLL
 *
 * PARAMS
 *  hXcv            [i] Handle from OpenPrinter (with XcvMonitor or XcvPort)
 *  pszDataName     [i] Name of the command to execute
 *  pInputData      [i] Buffer for extra Input Data (needed only for some commands)
 *  cbInputData     [i] Size in Bytes of Buffer at pInputData
 *  pOutputData     [o] Buffer to receive additional Data (needed only for some commands)
 *  cbOutputData    [i] Size in Bytes of Buffer at pOutputData
 *  pcbOutputNeeded [o] PTR to receive the minimal Size in Bytes of the Buffer at pOutputData
 *  pdwStatus       [o] PTR to receive the win32 error code from the Printmonitor DLL
 *
 * RETURNS
 *  Success: TRUE
 *  Failure: FALSE
 *
 * NOTES
 *  Returning "TRUE" does mean, that the Printmonitor DLL was called successful.
 *  The execution of the command can still fail (check pdwStatus for ERROR_SUCCESS).
 *
 *  Minimal List of commands, that a Printmonitor DLL should support:
 *
 *| "MonitorUI" : Return the Name of the Userinterface-DLL as WSTR in pOutputData
 *| "AddPort"   : Add a Port
 *| "DeletePort": Delete a Port
 *
 *  Many Printmonitors support additional commands. Examples for localspl.dll:
 *  "GetDefaultCommConfig", "SetDefaultCommConfig",
 *  "GetTransmissionRetryTimeout", "ConfigureLPTPortCommandOK"
 *
7725 7726 7727 7728 7729
 */
BOOL WINAPI XcvDataW( HANDLE hXcv, LPCWSTR pszDataName, PBYTE pInputData,
    DWORD cbInputData, PBYTE pOutputData, DWORD cbOutputData,
    PDWORD pcbOutputNeeded, PDWORD pdwStatus)
{
7730 7731 7732
    opened_printer_t *printer;

    TRACE("(%p, %s, %p, %d, %p, %d, %p, %p)\n", hXcv, debugstr_w(pszDataName),
7733 7734
          pInputData, cbInputData, pOutputData,
          cbOutputData, pcbOutputNeeded, pdwStatus);
7735

7736 7737
    if ((backend == NULL)  && !load_backend()) return FALSE;

7738
    printer = get_opened_printer(hXcv);
7739
    if (!printer || (!printer->backend_printer)) {
7740 7741 7742 7743
        SetLastError(ERROR_INVALID_HANDLE);
        return FALSE;
    }

7744 7745 7746 7747 7748 7749 7750 7751 7752 7753 7754 7755
    if (!pcbOutputNeeded) {
        SetLastError(ERROR_INVALID_PARAMETER);
        return FALSE;
    }

    if (!pszDataName || !pdwStatus || (!pOutputData && (cbOutputData > 0))) {
        SetLastError(RPC_X_NULL_REF_POINTER);
        return FALSE;
    }

    *pcbOutputNeeded = 0;

7756 7757
    return backend->fpXcvData(printer->backend_printer, pszDataName, pInputData,
                    cbInputData, pOutputData, cbOutputData, pcbOutputNeeded, pdwStatus);
7758

7759
}
7760

7761 7762 7763 7764 7765 7766 7767 7768
/*****************************************************************************
 *          EnumPrinterDataA [WINSPOOL.@]
 *
 */
DWORD WINAPI EnumPrinterDataA( HANDLE hPrinter, DWORD dwIndex, LPSTR pValueName,
    DWORD cbValueName, LPDWORD pcbValueName, LPDWORD pType, LPBYTE pData,
    DWORD cbData, LPDWORD pcbData )
{
7769
    FIXME("%p %x %p %x %p %p %p %x %p\n", hPrinter, dwIndex, pValueName,
7770 7771 7772 7773 7774 7775 7776 7777 7778 7779 7780 7781
          cbValueName, pcbValueName, pType, pData, cbData, pcbData);
    return ERROR_NO_MORE_ITEMS;
}

/*****************************************************************************
 *          EnumPrinterDataW [WINSPOOL.@]
 *
 */
DWORD WINAPI EnumPrinterDataW( HANDLE hPrinter, DWORD dwIndex, LPWSTR pValueName,
    DWORD cbValueName, LPDWORD pcbValueName, LPDWORD pType, LPBYTE pData,
    DWORD cbData, LPDWORD pcbData )
{
7782
    FIXME("%p %x %p %x %p %p %p %x %p\n", hPrinter, dwIndex, pValueName,
7783 7784 7785 7786
          cbValueName, pcbValueName, pType, pData, cbData, pcbData);
    return ERROR_NO_MORE_ITEMS;
}

7787 7788 7789 7790 7791 7792 7793 7794 7795 7796 7797 7798 7799 7800 7801 7802 7803 7804 7805 7806
/*****************************************************************************
 *          EnumPrinterKeyA [WINSPOOL.@]
 *
 */
DWORD WINAPI EnumPrinterKeyA(HANDLE printer, const CHAR *key, CHAR *subkey, DWORD size, DWORD *needed)
{
    FIXME("%p %s %p %x %p\n", printer, debugstr_a(key), subkey, size, needed);
    return ERROR_CALL_NOT_IMPLEMENTED;
}

/*****************************************************************************
 *          EnumPrinterKeyW [WINSPOOL.@]
 *
 */
DWORD WINAPI EnumPrinterKeyW(HANDLE printer, const WCHAR *key, WCHAR *subkey, DWORD size, DWORD *needed)
{
    FIXME("%p %s %p %x %p\n", printer, debugstr_w(key), subkey, size, needed);
    return ERROR_CALL_NOT_IMPLEMENTED;
}

7807 7808 7809 7810 7811 7812 7813 7814
/*****************************************************************************
 *          EnumPrintProcessorDatatypesA [WINSPOOL.@]
 *
 */
BOOL WINAPI EnumPrintProcessorDatatypesA(LPSTR pName, LPSTR pPrintProcessorName,
                                         DWORD Level, LPBYTE pDatatypes, DWORD cbBuf,
                                         LPDWORD pcbNeeded, LPDWORD pcReturned)
{
7815
    FIXME("Stub: %s %s %d %p %d %p %p\n", debugstr_a(pName),
7816 7817 7818 7819 7820 7821 7822 7823 7824 7825 7826 7827 7828
          debugstr_a(pPrintProcessorName), Level, pDatatypes, cbBuf,
          pcbNeeded, pcReturned);
    return FALSE;
}

/*****************************************************************************
 *          EnumPrintProcessorDatatypesW [WINSPOOL.@]
 *
 */
BOOL WINAPI EnumPrintProcessorDatatypesW(LPWSTR pName, LPWSTR pPrintProcessorName,
                                         DWORD Level, LPBYTE pDatatypes, DWORD cbBuf,
                                         LPDWORD pcbNeeded, LPDWORD pcReturned)
{
7829
    FIXME("Stub: %s %s %d %p %d %p %p\n", debugstr_w(pName),
7830 7831 7832 7833
          debugstr_w(pPrintProcessorName), Level, pDatatypes, cbBuf,
          pcbNeeded, pcReturned);
    return FALSE;
}
7834 7835 7836 7837

/*****************************************************************************
 *          EnumPrintProcessorsA [WINSPOOL.@]
 *
7838 7839
 * See EnumPrintProcessorsW.
 *
7840 7841
 */
BOOL WINAPI EnumPrintProcessorsA(LPSTR pName, LPSTR pEnvironment, DWORD Level, 
7842
                            LPBYTE pPPInfo, DWORD cbBuf, LPDWORD pcbNeeded, LPDWORD pcReturned)
7843
{
7844 7845 7846 7847 7848 7849 7850 7851 7852 7853 7854 7855 7856 7857 7858 7859 7860 7861 7862 7863 7864 7865 7866 7867 7868 7869 7870 7871 7872 7873 7874 7875 7876 7877 7878 7879 7880 7881 7882 7883 7884 7885 7886 7887 7888 7889 7890 7891 7892 7893 7894 7895 7896 7897 7898 7899 7900 7901 7902 7903 7904 7905 7906 7907 7908 7909 7910 7911 7912 7913 7914 7915 7916 7917 7918 7919 7920 7921 7922 7923 7924 7925 7926 7927 7928 7929 7930 7931 7932 7933 7934 7935 7936 7937 7938 7939 7940 7941 7942 7943 7944 7945 7946
    BOOL    res;
    LPBYTE  bufferW = NULL;
    LPWSTR  nameW = NULL;
    LPWSTR  envW = NULL;
    DWORD   needed = 0;
    DWORD   numentries = 0;
    INT     len;

    TRACE("(%s, %s, %d, %p, %d, %p, %p)\n", debugstr_a(pName), debugstr_a(pEnvironment),
                Level, pPPInfo, cbBuf, pcbNeeded, pcReturned);

    /* convert names to unicode */
    if (pName) {
        len = MultiByteToWideChar(CP_ACP, 0, pName, -1, NULL, 0);
        nameW = HeapAlloc(GetProcessHeap(), 0, len * sizeof(WCHAR));
        MultiByteToWideChar(CP_ACP, 0, pName, -1, nameW, len);
    }
    if (pEnvironment) {
        len = MultiByteToWideChar(CP_ACP, 0, pEnvironment, -1, NULL, 0);
        envW = HeapAlloc(GetProcessHeap(), 0, len * sizeof(WCHAR));
        MultiByteToWideChar(CP_ACP, 0, pEnvironment, -1, envW, len);
    }

    /* alloc (userbuffersize*sizeof(WCHAR) and try to enum the monitors */
    needed = cbBuf * sizeof(WCHAR);
    if (needed) bufferW = HeapAlloc(GetProcessHeap(), 0, needed);
    res = EnumPrintProcessorsW(nameW, envW, Level, bufferW, needed, pcbNeeded, pcReturned);

    if(!res && (GetLastError() == ERROR_INSUFFICIENT_BUFFER)) {
        if (pcbNeeded) needed = *pcbNeeded;
        /* HeapReAlloc return NULL, when bufferW was NULL */
        bufferW = (bufferW) ? HeapReAlloc(GetProcessHeap(), 0, bufferW, needed) :
                              HeapAlloc(GetProcessHeap(), 0, needed);

        /* Try again with the large Buffer */
        res = EnumPrintProcessorsW(nameW, envW, Level, bufferW, needed, pcbNeeded, pcReturned);
    }
    numentries = pcReturned ? *pcReturned : 0;
    needed = 0;

    if (res) {
        /* EnumPrintProcessorsW collected all Data. Parse them to calculate ANSI-Size */
        DWORD   index;
        LPSTR   ptr;
        PPRINTPROCESSOR_INFO_1W ppiw;
        PPRINTPROCESSOR_INFO_1A ppia;

        /* First pass: calculate the size for all Entries */
        ppiw = (PPRINTPROCESSOR_INFO_1W) bufferW;
        ppia = (PPRINTPROCESSOR_INFO_1A) pPPInfo;
        index = 0;
        while (index < numentries) {
            index++;
            needed += sizeof(PRINTPROCESSOR_INFO_1A);
            TRACE("%p: parsing #%d (%s)\n", ppiw, index, debugstr_w(ppiw->pName));

            needed += WideCharToMultiByte(CP_ACP, 0, ppiw->pName, -1,
                                            NULL, 0, NULL, NULL);

            ppiw = (PPRINTPROCESSOR_INFO_1W) (((LPBYTE)ppiw) + sizeof(PRINTPROCESSOR_INFO_1W));
            ppia = (PPRINTPROCESSOR_INFO_1A) (((LPBYTE)ppia) + sizeof(PRINTPROCESSOR_INFO_1A));
        }

        /* check for errors and quit on failure */
        if (cbBuf < needed) {
            SetLastError(ERROR_INSUFFICIENT_BUFFER);
            res = FALSE;
            goto epp_cleanup;
        }

        len = numentries * sizeof(PRINTPROCESSOR_INFO_1A); /* room for structs */
        ptr = (LPSTR) &pPPInfo[len];        /* start of strings */
        cbBuf -= len ;                      /* free Bytes in the user-Buffer */
        ppiw = (PPRINTPROCESSOR_INFO_1W) bufferW;
        ppia = (PPRINTPROCESSOR_INFO_1A) pPPInfo;
        index = 0;
        /* Second Pass: Fill the User Buffer (if we have one) */
        while ((index < numentries) && pPPInfo) {
            index++;
            TRACE("%p: writing PRINTPROCESSOR_INFO_1A #%d\n", ppia, index);
            ppia->pName = ptr;
            len = WideCharToMultiByte(CP_ACP, 0, ppiw->pName, -1,
                                            ptr, cbBuf , NULL, NULL);
            ptr += len;
            cbBuf -= len;

            ppiw = (PPRINTPROCESSOR_INFO_1W) (((LPBYTE)ppiw) + sizeof(PRINTPROCESSOR_INFO_1W));
            ppia = (PPRINTPROCESSOR_INFO_1A) (((LPBYTE)ppia) + sizeof(PRINTPROCESSOR_INFO_1A));

        }
    }
epp_cleanup:
    if (pcbNeeded)  *pcbNeeded = needed;
    if (pcReturned) *pcReturned = (res) ? numentries : 0;

    HeapFree(GetProcessHeap(), 0, nameW);
    HeapFree(GetProcessHeap(), 0, envW);
    HeapFree(GetProcessHeap(), 0, bufferW);

    TRACE("returning %d with %d (%d byte for %d entries)\n",
            (res), GetLastError(), needed, numentries);

    return (res);
7947 7948 7949 7950 7951
}

/*****************************************************************************
 *          EnumPrintProcessorsW [WINSPOOL.@]
 *
7952 7953 7954 7955 7956 7957 7958
 * Enumerate available Print Processors
 *
 * PARAMS
 *  pName        [I] Servername or NULL (local Computer)
 *  pEnvironment [I] Printing-Environment or NULL (Default)
 *  Level        [I] Structure-Level (Only 1 is allowed)
 *  pPPInfo      [O] PTR to Buffer that receives the Result
7959
 *  cbBuf        [I] Size of Buffer at pPPInfo
7960 7961 7962 7963 7964 7965 7966
 *  pcbNeeded    [O] PTR to DWORD that receives the size in Bytes used / required for pPPInfo
 *  pcReturned   [O] PTR to DWORD that receives the number of Print Processors in pPPInfo
 *
 * RETURNS
 *  Success: TRUE
 *  Failure: FALSE and in pcbNeeded the Bytes required for pPPInfo, if cbBuf is too small
 *
7967 7968
 */
BOOL WINAPI EnumPrintProcessorsW(LPWSTR pName, LPWSTR pEnvironment, DWORD Level,
7969
                            LPBYTE pPPInfo, DWORD cbBuf, LPDWORD pcbNeeded, LPDWORD pcReturned)
7970
{
7971 7972 7973 7974 7975 7976 7977 7978 7979 7980 7981 7982 7983 7984 7985 7986 7987 7988

    TRACE("(%s, %s, %d, %p, %d, %p, %p)\n", debugstr_w(pName), debugstr_w(pEnvironment),
                                Level, pPPInfo, cbBuf, pcbNeeded, pcReturned);

    if ((backend == NULL)  && !load_backend()) return FALSE;

    if (!pcbNeeded || !pcReturned) {
        SetLastError(RPC_X_NULL_REF_POINTER);
        return FALSE;
    }

    if (!pPPInfo && (cbBuf > 0)) {
        SetLastError(ERROR_INVALID_USER_BUFFER);
        return FALSE;
    }

    return backend->fpEnumPrintProcessors(pName, pEnvironment, Level, pPPInfo,
                                          cbBuf, pcbNeeded, pcReturned);
7989
}
7990

7991 7992 7993 7994 7995 7996 7997 7998
/*****************************************************************************
 *          ExtDeviceMode [WINSPOOL.@]
 *
 */
LONG WINAPI ExtDeviceMode( HWND hWnd, HANDLE hInst, LPDEVMODEA pDevModeOutput,
    LPSTR pDeviceName, LPSTR pPort, LPDEVMODEA pDevModeInput, LPSTR pProfile,
    DWORD fMode)
{
7999
    FIXME("Stub: %p %p %p %s %s %p %s %x\n", hWnd, hInst, pDevModeOutput,
8000 8001 8002 8003 8004 8005 8006 8007 8008 8009 8010 8011 8012 8013 8014 8015 8016 8017 8018 8019 8020 8021
          debugstr_a(pDeviceName), debugstr_a(pPort), pDevModeInput,
          debugstr_a(pProfile), fMode);
    return -1;
}

/*****************************************************************************
 *          FindClosePrinterChangeNotification [WINSPOOL.@]
 *
 */
BOOL WINAPI FindClosePrinterChangeNotification( HANDLE hChange )
{
    FIXME("Stub: %p\n", hChange);
    return TRUE;
}

/*****************************************************************************
 *          FindFirstPrinterChangeNotification [WINSPOOL.@]
 *
 */
HANDLE WINAPI FindFirstPrinterChangeNotification( HANDLE hPrinter,
    DWORD fdwFlags, DWORD fdwOptions, LPVOID pPrinterNotifyOptions )
{
8022
    FIXME("Stub: %p %x %x %p\n",
8023 8024 8025 8026 8027 8028 8029 8030 8031 8032 8033 8034 8035 8036 8037 8038 8039 8040 8041 8042 8043 8044 8045 8046 8047 8048
          hPrinter, fdwFlags, fdwOptions, pPrinterNotifyOptions);
    return INVALID_HANDLE_VALUE;
}

/*****************************************************************************
 *          FindNextPrinterChangeNotification [WINSPOOL.@]
 *
 */
BOOL WINAPI FindNextPrinterChangeNotification( HANDLE hChange, PDWORD pdwChange,
    LPVOID pPrinterNotifyOptions, LPVOID *ppPrinterNotifyInfo )
{
    FIXME("Stub: %p %p %p %p\n",
          hChange, pdwChange, pPrinterNotifyOptions, ppPrinterNotifyInfo);
    return FALSE;
}

/*****************************************************************************
 *          FreePrinterNotifyInfo [WINSPOOL.@]
 *
 */
BOOL WINAPI FreePrinterNotifyInfo( PPRINTER_NOTIFY_INFO pPrinterNotifyInfo )
{
    FIXME("Stub: %p\n", pPrinterNotifyInfo);
    return TRUE;
}

8049 8050 8051 8052 8053 8054 8055 8056 8057 8058 8059 8060 8061 8062 8063 8064 8065 8066 8067 8068 8069 8070 8071 8072 8073 8074 8075 8076 8077
/*****************************************************************************
 *          string_to_buf
 *
 * Copies a unicode string into a buffer.  The buffer will either contain unicode or
 * ansi depending on the unicode parameter.
 */
static BOOL string_to_buf(LPCWSTR str, LPBYTE ptr, DWORD cb, DWORD *size, BOOL unicode)
{
    if(!str)
    {
        *size = 0;
        return TRUE;
    }

    if(unicode)
    {
        *size = (strlenW(str) + 1) * sizeof(WCHAR);
        if(*size <= cb)
        {
            memcpy(ptr, str, *size);
            return TRUE;
        }
        return FALSE;
    }
    else
    {
        *size = WideCharToMultiByte(CP_ACP, 0, str, -1, NULL, 0, NULL, NULL);
        if(*size <= cb)
        {
Mike McCormack's avatar
Mike McCormack committed
8078
            WideCharToMultiByte(CP_ACP, 0, str, -1, (LPSTR)ptr, *size, NULL, NULL);
8079 8080 8081 8082 8083 8084 8085 8086 8087 8088 8089 8090 8091 8092 8093 8094 8095 8096 8097 8098 8099 8100 8101 8102 8103 8104 8105 8106 8107 8108 8109 8110 8111 8112
            return TRUE;
        }
        return FALSE;
    }
}

/*****************************************************************************
 *          get_job_info_1
 */
static BOOL get_job_info_1(job_t *job, JOB_INFO_1W *ji1, LPBYTE buf, DWORD cbBuf,
                           LPDWORD pcbNeeded, BOOL unicode)
{
    DWORD size, left = cbBuf;
    BOOL space = (cbBuf > 0);
    LPBYTE ptr = buf;

    *pcbNeeded = 0;

    if(space)
    {
        ji1->JobId = job->job_id;
    }

    string_to_buf(job->document_title, ptr, left, &size, unicode);
    if(space && size <= left)
    {
        ji1->pDocument = (LPWSTR)ptr;
        ptr += size;
        left -= size;
    }
    else
        space = FALSE;
    *pcbNeeded += size;

8113 8114 8115 8116 8117 8118 8119 8120 8121 8122 8123 8124 8125 8126
    if (job->printer_name)
    {
        string_to_buf(job->printer_name, ptr, left, &size, unicode);
        if(space && size <= left)
        {
            ji1->pPrinterName = (LPWSTR)ptr;
            ptr += size;
            left -= size;
        }
        else
            space = FALSE;
        *pcbNeeded += size;
    }

8127 8128 8129 8130 8131 8132 8133 8134 8135 8136
    return space;
}

/*****************************************************************************
 *          get_job_info_2
 */
static BOOL get_job_info_2(job_t *job, JOB_INFO_2W *ji2, LPBYTE buf, DWORD cbBuf,
                           LPDWORD pcbNeeded, BOOL unicode)
{
    DWORD size, left = cbBuf;
8137
    DWORD shift;
8138 8139
    BOOL space = (cbBuf > 0);
    LPBYTE ptr = buf;
8140
    LPDEVMODEA  dmA = NULL;
8141
    LPDEVMODEW  devmode;
8142 8143 8144 8145 8146 8147 8148 8149 8150 8151 8152 8153 8154 8155 8156 8157 8158 8159 8160

    *pcbNeeded = 0;

    if(space)
    {
        ji2->JobId = job->job_id;
    }

    string_to_buf(job->document_title, ptr, left, &size, unicode);
    if(space && size <= left)
    {
        ji2->pDocument = (LPWSTR)ptr;
        ptr += size;
        left -= size;
    }
    else
        space = FALSE;
    *pcbNeeded += size;

8161 8162 8163 8164 8165 8166 8167 8168 8169 8170 8171 8172 8173 8174
    if (job->printer_name)
    {
        string_to_buf(job->printer_name, ptr, left, &size, unicode);
        if(space && size <= left)
        {
            ji2->pPrinterName = (LPWSTR)ptr;
            ptr += size;
            left -= size;
        }
        else
            space = FALSE;
        *pcbNeeded += size;
    }

8175 8176 8177 8178 8179 8180 8181 8182 8183 8184 8185 8186 8187 8188 8189 8190 8191 8192 8193
    if (job->devmode)
    {
        if (!unicode)
        {
            dmA = DEVMODEdupWtoA(job->devmode);
            devmode = (LPDEVMODEW) dmA;
            if (dmA) size = dmA->dmSize + dmA->dmDriverExtra;
        }
        else
        {
            devmode = job->devmode;
            size = devmode->dmSize + devmode->dmDriverExtra;
        }

        if (!devmode)
             FIXME("Can't convert DEVMODE W to A\n");
        else
        {
            /* align DEVMODE to a DWORD boundary */
8194
            shift = (4 - (*pcbNeeded & 3)) & 3;
8195 8196 8197 8198 8199 8200 8201 8202
            size += shift;

            if (size <= left)
            {
                ptr += shift;
                memcpy(ptr, devmode, size-shift);
                ji2->pDevMode = (LPDEVMODEW)ptr;
                if (!unicode) HeapFree(GetProcessHeap(), 0, dmA);
8203
                ptr += size-shift;
8204 8205 8206 8207 8208 8209 8210 8211
                left -= size;
            }
            else
                space = FALSE;
            *pcbNeeded +=size;
        }
    }

8212 8213 8214 8215 8216 8217 8218 8219 8220 8221 8222 8223 8224 8225
    return space;
}

/*****************************************************************************
 *          get_job_info
 */
static BOOL get_job_info(HANDLE hPrinter, DWORD JobId, DWORD Level, LPBYTE pJob,
                         DWORD cbBuf, LPDWORD pcbNeeded, BOOL unicode)
{
    BOOL ret = FALSE;
    DWORD needed = 0, size;
    job_t *job;
    LPBYTE ptr = pJob;

8226
    TRACE("%p %d %d %p %d %p\n", hPrinter, JobId, Level, pJob, cbBuf, pcbNeeded);
8227 8228 8229 8230 8231 8232 8233 8234 8235 8236 8237 8238 8239 8240 8241 8242 8243 8244 8245 8246 8247 8248 8249 8250 8251 8252 8253 8254 8255 8256 8257 8258 8259 8260 8261 8262 8263 8264 8265 8266 8267 8268 8269 8270 8271 8272 8273 8274 8275 8276 8277 8278 8279 8280 8281 8282 8283 8284 8285 8286

    EnterCriticalSection(&printer_handles_cs);
    job = get_job(hPrinter, JobId);
    if(!job)
        goto end;

    switch(Level)
    {
    case 1:
        size = sizeof(JOB_INFO_1W);
        if(cbBuf >= size)
        {
            cbBuf -= size;
            ptr += size;
            memset(pJob, 0, size);
        }
        else
            cbBuf = 0;
        ret = get_job_info_1(job, (JOB_INFO_1W *)pJob, ptr, cbBuf, &needed, unicode);
        needed += size;
        break;

    case 2:
        size = sizeof(JOB_INFO_2W);
        if(cbBuf >= size)
        {
            cbBuf -= size;
            ptr += size;
            memset(pJob, 0, size);
        }
        else
            cbBuf = 0;
        ret = get_job_info_2(job, (JOB_INFO_2W *)pJob, ptr, cbBuf, &needed, unicode);
        needed += size;
        break;

    case 3:
        size = sizeof(JOB_INFO_3);
        if(cbBuf >= size)
        {
            cbBuf -= size;
            memset(pJob, 0, size);
            ret = TRUE;
        }
        else
            cbBuf = 0;
        needed = size;
        break;

    default:
        SetLastError(ERROR_INVALID_LEVEL);
        goto end;
    }
    if(pcbNeeded)
        *pcbNeeded = needed;
end:
    LeaveCriticalSection(&printer_handles_cs);
    return ret;
}

8287 8288 8289 8290 8291
/*****************************************************************************
 *          GetJobA [WINSPOOL.@]
 *
 */
BOOL WINAPI GetJobA(HANDLE hPrinter, DWORD JobId, DWORD Level, LPBYTE pJob,
8292
                    DWORD cbBuf, LPDWORD pcbNeeded)
8293
{
8294
    return get_job_info(hPrinter, JobId, Level, pJob, cbBuf, pcbNeeded, FALSE);
8295 8296 8297 8298 8299 8300 8301
}

/*****************************************************************************
 *          GetJobW [WINSPOOL.@]
 *
 */
BOOL WINAPI GetJobW(HANDLE hPrinter, DWORD JobId, DWORD Level, LPBYTE pJob,
8302
                    DWORD cbBuf, LPDWORD pcbNeeded)
8303
{
8304
    return get_job_info(hPrinter, JobId, Level, pJob, cbBuf, pcbNeeded, TRUE);
8305
}
8306

8307
/*****************************************************************************
8308
 *          schedule_pipe
8309
 */
8310
static BOOL schedule_pipe(LPCWSTR cmd, LPCWSTR filename)
8311
{
8312 8313
#ifdef HAVE_FORK
    char *unixname, *cmdA;
8314
    DWORD len;
8315 8316 8317
    int fds[2] = {-1, -1}, file_fd = -1, no_read;
    BOOL ret = FALSE;
    char buf[1024];
8318 8319
    pid_t pid, wret;
    int status;
8320 8321 8322 8323

    if(!(unixname = wine_get_unix_file_name(filename)))
        return FALSE;

8324 8325 8326
    len = WideCharToMultiByte(CP_UNIXCP, 0, cmd, -1, NULL, 0, NULL, NULL);
    cmdA = HeapAlloc(GetProcessHeap(), 0, len);
    WideCharToMultiByte(CP_UNIXCP, 0, cmd, -1, cmdA, len, NULL, NULL);
8327

8328
    TRACE("printing with: %s\n", cmdA);
8329

8330 8331
    if((file_fd = open(unixname, O_RDONLY)) == -1)
        goto end;
8332

8333 8334 8335 8336 8337 8338
    if (pipe(fds))
    {
        ERR("pipe() failed!\n");
        goto end;
    }

8339
    if ((pid = fork()) == 0)
8340 8341 8342 8343 8344 8345 8346 8347 8348 8349 8350
    {
        close(0);
        dup2(fds[0], 0);
        close(fds[1]);

        /* reset signals that we previously set to SIG_IGN */
        signal(SIGPIPE, SIG_DFL);

        execl("/bin/sh", "/bin/sh", "-c", cmdA, NULL);
        _exit(1);
    }
8351 8352 8353 8354 8355
    else if (pid == -1)
    {
        ERR("fork() failed!\n");
        goto end;
    }
8356

8357 8358
    close(fds[0]);
    fds[0] = -1;
8359 8360 8361
    while((no_read = read(file_fd, buf, sizeof(buf))) > 0)
        write(fds[1], buf, no_read);

8362 8363 8364 8365 8366 8367 8368 8369 8370 8371 8372 8373 8374 8375 8376 8377 8378 8379
    close(fds[1]);
    fds[1] = -1;

    /* reap child */
    do {
        wret = waitpid(pid, &status, 0);
    } while (wret < 0 && errno == EINTR);
    if (wret < 0)
    {
        ERR("waitpid() failed!\n");
        goto end;
    }
    if (!WIFEXITED(status) || WEXITSTATUS(status))
    {
        ERR("child process failed! %d\n", status);
        goto end;
    }

8380 8381 8382 8383 8384 8385 8386 8387
    ret = TRUE;

end:
    if(file_fd != -1) close(file_fd);
    if(fds[0] != -1) close(fds[0]);
    if(fds[1] != -1) close(fds[1]);

    HeapFree(GetProcessHeap(), 0, cmdA);
8388
    HeapFree(GetProcessHeap(), 0, unixname);
8389 8390 8391 8392 8393 8394 8395 8396 8397 8398 8399
    return ret;
#else
    return FALSE;
#endif
}

/*****************************************************************************
 *          schedule_lpr
 */
static BOOL schedule_lpr(LPCWSTR printer_name, LPCWSTR filename)
{
8400
    static const WCHAR fmtW[] = {'l','p','r',' ','-','P','\'','%','s','\'',0};
8401 8402 8403 8404 8405 8406 8407 8408 8409 8410
    WCHAR *cmd;
    BOOL r;

    cmd = HeapAlloc(GetProcessHeap(), 0, strlenW(printer_name) * sizeof(WCHAR) + sizeof(fmtW));
    sprintfW(cmd, fmtW, printer_name);

    r = schedule_pipe(cmd, filename);

    HeapFree(GetProcessHeap(), 0, cmd);
    return r;
8411 8412
}

8413 8414 8415 8416 8417 8418 8419 8420 8421 8422 8423 8424 8425 8426 8427 8428 8429 8430 8431 8432 8433 8434 8435 8436 8437 8438 8439 8440 8441
#ifdef SONAME_LIBCUPS
/*****************************************************************************
 *          get_cups_jobs_ticket_options
 *
 * Explicitly set CUPS options based on any %cupsJobTicket lines.
 * The CUPS scheduler only looks for these in Print-File requests, and since
 * cupsPrintFile uses Create-Job / Send-Document, the ticket lines don't get
 * parsed.
 */
static int get_cups_job_ticket_options( const char *file, int num_options, cups_option_t **options )
{
    FILE *fp = fopen( file, "r" );
    char buf[257]; /* DSC max of 256 + '\0' */
    const char *ps_adobe = "%!PS-Adobe-";
    const char *cups_job = "%cupsJobTicket:";

    if (!fp) return num_options;
    if (!fgets( buf, sizeof(buf), fp )) goto end;
    if (strncmp( buf, ps_adobe, strlen( ps_adobe ) )) goto end;
    while (fgets( buf, sizeof(buf), fp ))
    {
        if (strncmp( buf, cups_job, strlen( cups_job ) )) break;
        num_options = pcupsParseOptions( buf + strlen( cups_job ), num_options, options );
    }

end:
    fclose( fp );
    return num_options;
}
8442 8443 8444 8445 8446 8447 8448 8449 8450 8451 8452 8453 8454 8455 8456 8457 8458 8459 8460 8461 8462

static int get_cups_default_options( const char *printer, int num_options, cups_option_t **options )
{
    cups_dest_t *dest;
    int i;

    if (!pcupsGetNamedDest) return num_options;

    dest = pcupsGetNamedDest( NULL, printer, NULL );
    if (!dest) return num_options;

    for (i = 0; i < dest->num_options; i++)
    {
        if (!pcupsGetOption( dest->options[i].name, num_options, *options ))
            num_options = pcupsAddOption( dest->options[i].name, dest->options[i].value,
                                          num_options, options );
    }

    pcupsFreeDests( 1, dest );
    return num_options;
}
8463 8464
#endif

8465 8466 8467
/*****************************************************************************
 *          schedule_cups
 */
8468
static BOOL schedule_cups(LPCWSTR printer_name, LPCWSTR filename, LPCWSTR document_title)
8469
{
8470
#ifdef SONAME_LIBCUPS
8471 8472
    if(pcupsPrintFile)
    {
8473
        char *unixname, *queue, *unix_doc_title;
8474 8475
        DWORD len;
        BOOL ret;
8476 8477
        int num_options = 0, i;
        cups_option_t *options = NULL;
8478 8479 8480 8481

        if(!(unixname = wine_get_unix_file_name(filename)))
            return FALSE;

8482
        len = WideCharToMultiByte(CP_UNIXCP, 0, printer_name, -1, NULL, 0, NULL, NULL);
8483
        queue = HeapAlloc(GetProcessHeap(), 0, len);
8484
        WideCharToMultiByte(CP_UNIXCP, 0, printer_name, -1, queue, len, NULL, NULL);
8485

8486 8487 8488
        len = WideCharToMultiByte(CP_UNIXCP, 0, document_title, -1, NULL, 0, NULL, NULL);
        unix_doc_title = HeapAlloc(GetProcessHeap(), 0, len);
        WideCharToMultiByte(CP_UNIXCP, 0, document_title, -1, unix_doc_title, len, NULL, NULL);
8489

8490
        num_options = get_cups_job_ticket_options( unixname, num_options, &options );
8491
        num_options = get_cups_default_options( queue, num_options, &options );
8492 8493 8494 8495 8496 8497

        TRACE( "printing via cups with options:\n" );
        for (i = 0; i < num_options; i++)
            TRACE( "\t%d: %s = %s\n", i, options[i].name, options[i].value );

        ret = pcupsPrintFile( queue, unixname, unix_doc_title, num_options, options );
8498 8499
        if (ret == 0 && pcupsLastErrorString)
            WARN("cupsPrintFile failed with error %s\n", debugstr_a(pcupsLastErrorString()));
8500 8501 8502

        pcupsFreeOptions( num_options, options );

8503
        HeapFree(GetProcessHeap(), 0, unix_doc_title);
8504 8505 8506 8507 8508 8509 8510 8511 8512 8513 8514
        HeapFree(GetProcessHeap(), 0, queue);
        HeapFree(GetProcessHeap(), 0, unixname);
        return ret;
    }
    else
#endif
    {
        return schedule_lpr(printer_name, filename);
    }
}

8515
static INT_PTR CALLBACK file_dlg_proc(HWND hwnd, UINT msg, WPARAM wparam, LPARAM lparam)
8516 8517 8518 8519 8520 8521 8522 8523 8524 8525 8526 8527 8528 8529 8530
{
    LPWSTR filename;

    switch(msg)
    {
    case WM_INITDIALOG:
        SetWindowLongPtrW(hwnd, DWLP_USER, lparam);
        return TRUE;

    case WM_COMMAND:
        if(HIWORD(wparam) == BN_CLICKED)
        {
            if(LOWORD(wparam) == IDOK)
            {
                HANDLE hf;
8531
                DWORD len = SendDlgItemMessageW(hwnd, EDITBOX, WM_GETTEXTLENGTH, 0, 0);
8532 8533 8534 8535
                LPWSTR *output;

                filename = HeapAlloc(GetProcessHeap(), 0, (len + 1) * sizeof(WCHAR));
                GetDlgItemTextW(hwnd, EDITBOX, filename, len + 1);
8536

8537 8538 8539 8540 8541
                if(GetFileAttributesW(filename) != INVALID_FILE_ATTRIBUTES)
                {
                    WCHAR caption[200], message[200];
                    int mb_ret;

8542 8543
                    LoadStringW(WINSPOOL_hInstance, IDS_CAPTION, caption, ARRAY_SIZE(caption));
                    LoadStringW(WINSPOOL_hInstance, IDS_FILE_EXISTS, message, ARRAY_SIZE(message));
8544 8545 8546 8547 8548 8549 8550 8551 8552 8553 8554 8555
                    mb_ret = MessageBoxW(hwnd, message, caption, MB_OKCANCEL | MB_ICONEXCLAMATION);
                    if(mb_ret == IDCANCEL)
                    {
                        HeapFree(GetProcessHeap(), 0, filename);
                        return TRUE;
                    }
                }
                hf = CreateFileW(filename, GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
                if(hf == INVALID_HANDLE_VALUE)
                {
                    WCHAR caption[200], message[200];

8556 8557
                    LoadStringW(WINSPOOL_hInstance, IDS_CAPTION, caption, ARRAY_SIZE(caption));
                    LoadStringW(WINSPOOL_hInstance, IDS_CANNOT_OPEN, message, ARRAY_SIZE(message));
8558 8559 8560 8561 8562 8563 8564 8565 8566 8567 8568 8569 8570 8571 8572 8573 8574 8575 8576 8577 8578 8579
                    MessageBoxW(hwnd, message, caption, MB_OK | MB_ICONEXCLAMATION);
                    HeapFree(GetProcessHeap(), 0, filename);
                    return TRUE;
                }
                CloseHandle(hf);
                DeleteFileW(filename);
                output = (LPWSTR *)GetWindowLongPtrW(hwnd, DWLP_USER);
                *output = filename;
                EndDialog(hwnd, IDOK);
                return TRUE;
            }
            if(LOWORD(wparam) == IDCANCEL)
            {
                EndDialog(hwnd, IDCANCEL);
                return TRUE;
            }
        }
        return FALSE;
    }
    return FALSE;
}

8580 8581 8582 8583 8584 8585 8586 8587 8588
/*****************************************************************************
 *          get_filename
 */
static BOOL get_filename(LPWSTR *filename)
{
    return DialogBoxParamW(WINSPOOL_hInstance, MAKEINTRESOURCEW(FILENAME_DIALOG), GetForegroundWindow(),
                           file_dlg_proc, (LPARAM)filename) == IDOK;
}

8589 8590 8591 8592 8593 8594 8595
/*****************************************************************************
 *          schedule_file
 */
static BOOL schedule_file(LPCWSTR filename)
{
    LPWSTR output = NULL;

8596
    if(get_filename(&output))
8597
    {
8598
        BOOL r;
8599
        TRACE("copy to %s\n", debugstr_w(output));
8600
        r = CopyFileW(filename, output, FALSE);
8601
        HeapFree(GetProcessHeap(), 0, output);
8602
        return r;
8603 8604 8605
    }
    return FALSE;
}
8606 8607 8608 8609 8610 8611 8612 8613 8614 8615 8616 8617 8618 8619 8620

/*****************************************************************************
 *          schedule_unixfile
 */
static BOOL schedule_unixfile(LPCWSTR output, LPCWSTR filename)
{
    int in_fd, out_fd, no_read;
    char buf[1024];
    BOOL ret = FALSE;
    char *unixname, *outputA;
    DWORD len;

    if(!(unixname = wine_get_unix_file_name(filename)))
        return FALSE;

8621
    len = WideCharToMultiByte(CP_UNIXCP, 0, output, -1, NULL, 0, NULL, NULL);
8622
    outputA = HeapAlloc(GetProcessHeap(), 0, len);
8623
    WideCharToMultiByte(CP_UNIXCP, 0, output, -1, outputA, len, NULL, NULL);
8624 8625 8626 8627 8628 8629
    
    out_fd = open(outputA, O_CREAT | O_TRUNC | O_WRONLY, 0666);
    in_fd = open(unixname, O_RDONLY);
    if(out_fd == -1 || in_fd == -1)
        goto end;

8630
    while((no_read = read(in_fd, buf, sizeof(buf))) > 0)
8631 8632 8633 8634 8635 8636 8637 8638 8639 8640 8641
        write(out_fd, buf, no_read);

    ret = TRUE;
end:
    if(in_fd != -1) close(in_fd);
    if(out_fd != -1) close(out_fd);
    HeapFree(GetProcessHeap(), 0, outputA);
    HeapFree(GetProcessHeap(), 0, unixname);
    return ret;
}

8642 8643 8644 8645 8646 8647
/*****************************************************************************
 *          ScheduleJob [WINSPOOL.@]
 *
 */
BOOL WINAPI ScheduleJob( HANDLE hPrinter, DWORD dwJobID )
{
8648 8649 8650 8651
    opened_printer_t *printer;
    BOOL ret = FALSE;
    struct list *cursor, *cursor2;

8652
    TRACE("(%p, %x)\n", hPrinter, dwJobID);
8653 8654 8655 8656 8657
    EnterCriticalSection(&printer_handles_cs);
    printer = get_opened_printer(hPrinter);
    if(!printer)
        goto end;

8658
    LIST_FOR_EACH_SAFE(cursor, cursor2, &printer->queue->jobs)
8659 8660 8661 8662 8663 8664 8665 8666 8667
    {
        job_t *job = LIST_ENTRY(cursor, job_t, entry);
        HANDLE hf;

        if(job->job_id != dwJobID) continue;

        hf = CreateFileW(job->filename, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, 0, NULL);
        if(hf != INVALID_HANDLE_VALUE)
        {
8668 8669
            PRINTER_INFO_5W *pi5 = NULL;
            LPWSTR portname = job->portname;
8670
            DWORD needed;
8671 8672 8673 8674
            HKEY hkey;
            WCHAR output[1024];
            static const WCHAR spooler_key[] = {'S','o','f','t','w','a','r','e','\\','W','i','n','e','\\',
                                                'P','r','i','n','t','i','n','g','\\','S','p','o','o','l','e','r',0};
8675

8676 8677 8678 8679 8680 8681 8682
            if (!portname)
            {
                GetPrinterW(hPrinter, 5, NULL, 0, &needed);
                pi5 = HeapAlloc(GetProcessHeap(), 0, needed);
                GetPrinterW(hPrinter, 5, (LPBYTE)pi5, needed, &needed);
                portname = pi5->pPortName;
            }
8683
            TRACE("need to schedule job %d filename %s to port %s\n", job->job_id, debugstr_w(job->filename),
8684
                  debugstr_w(portname));
8685
            
8686 8687 8688 8689 8690 8691
            output[0] = 0;

            /* @@ Wine registry key: HKCU\Software\Wine\Printing\Spooler */
            if(RegOpenKeyW(HKEY_CURRENT_USER, spooler_key, &hkey) == ERROR_SUCCESS)
            {
                DWORD type, count = sizeof(output);
8692
                RegQueryValueExW(hkey, portname, NULL, &type, (LPBYTE)output, &count);
8693 8694 8695 8696
                RegCloseKey(hkey);
            }
            if(output[0] == '|')
            {
8697
                ret = schedule_pipe(output + 1, job->filename);
8698 8699 8700
            }
            else if(output[0])
            {
8701
                ret = schedule_unixfile(output, job->filename);
8702
            }
8703
            else if(!strncmpW(portname, LPR_Port, strlenW(LPR_Port)))
8704
            {
8705
                ret = schedule_lpr(portname + strlenW(LPR_Port), job->filename);
8706
            }
8707
            else if(!strncmpW(portname, CUPS_Port, strlenW(CUPS_Port)))
8708
            {
8709
                ret = schedule_cups(portname + strlenW(CUPS_Port), job->filename, job->document_title);
8710
            }
8711
            else if(!strncmpW(portname, FILE_Port, strlenW(FILE_Port)))
8712
            {
8713
                ret = schedule_file(job->filename);
8714
            }
8715 8716 8717 8718 8719
            else if(isalpha(portname[0]) && portname[1] == ':')
            {
                TRACE("copying to %s\n", debugstr_w(portname));
                ret = CopyFileW(job->filename, portname, FALSE);
            }
8720 8721
            else
            {
8722
                FIXME("can't schedule to port %s\n", debugstr_w(portname));
8723 8724
            }
            HeapFree(GetProcessHeap(), 0, pi5);
8725 8726 8727 8728
            CloseHandle(hf);
            DeleteFileW(job->filename);
        }
        list_remove(cursor);
8729
        HeapFree(GetProcessHeap(), 0, job->document_title);
8730
        HeapFree(GetProcessHeap(), 0, job->printer_name);
8731
        HeapFree(GetProcessHeap(), 0, job->portname);
8732
        HeapFree(GetProcessHeap(), 0, job->filename);
8733
        HeapFree(GetProcessHeap(), 0, job->devmode);
8734 8735 8736 8737 8738 8739
        HeapFree(GetProcessHeap(), 0, job);
        break;
    }
end:
    LeaveCriticalSection(&printer_handles_cs);
    return ret;
8740
}
8741 8742 8743 8744

/*****************************************************************************
 *          StartDocDlgA [WINSPOOL.@]
 */
8745
LPSTR WINAPI StartDocDlgA( HANDLE hPrinter, DOCINFOA *doc )
8746 8747
{
    UNICODE_STRING usBuffer;
8748
    DOCINFOW docW = { 0 };
8749
    LPWSTR retW;
8750
    LPWSTR docnameW = NULL, outputW = NULL, datatypeW = NULL;
8751 8752 8753
    LPSTR ret = NULL;

    docW.cbSize = sizeof(docW);
8754 8755 8756
    if (doc->lpszDocName)
    {
        docnameW = asciitounicode(&usBuffer, doc->lpszDocName);
8757
        if (!(docW.lpszDocName = docnameW)) goto failed;
8758 8759 8760 8761
    }
    if (doc->lpszOutput)
    {
        outputW = asciitounicode(&usBuffer, doc->lpszOutput);
8762
        if (!(docW.lpszOutput = outputW)) goto failed;
8763 8764 8765 8766
    }
    if (doc->lpszDatatype)
    {
        datatypeW = asciitounicode(&usBuffer, doc->lpszDatatype);
8767
        if (!(docW.lpszDatatype = datatypeW)) goto failed;
8768
    }
8769 8770 8771 8772 8773 8774 8775 8776 8777 8778 8779 8780
    docW.fwType = doc->fwType;

    retW = StartDocDlgW(hPrinter, &docW);

    if(retW)
    {
        DWORD len = WideCharToMultiByte(CP_ACP, 0, retW, -1, NULL, 0, NULL, NULL);
        ret = HeapAlloc(GetProcessHeap(), 0, len);
        WideCharToMultiByte(CP_ACP, 0, retW, -1, ret, len, NULL, NULL);
        HeapFree(GetProcessHeap(), 0, retW);
    }

8781
failed:
8782 8783 8784
    HeapFree(GetProcessHeap(), 0, datatypeW);
    HeapFree(GetProcessHeap(), 0, outputW);
    HeapFree(GetProcessHeap(), 0, docnameW);
8785 8786 8787 8788 8789 8790 8791 8792 8793 8794 8795 8796 8797 8798 8799 8800 8801 8802 8803 8804 8805 8806 8807 8808 8809 8810 8811 8812 8813 8814 8815 8816 8817 8818 8819 8820 8821

    return ret;
}

/*****************************************************************************
 *          StartDocDlgW [WINSPOOL.@]
 *
 * Undocumented: Apparently used by gdi32:StartDocW() to popup the file dialog
 * when lpszOutput is "FILE:" or if lpszOutput is NULL and the default printer
 * port is "FILE:". Also returns the full path if passed a relative path.
 *
 * The caller should free the returned string from the process heap.
 */
LPWSTR WINAPI StartDocDlgW( HANDLE hPrinter, DOCINFOW *doc )
{
    LPWSTR ret = NULL;
    DWORD len, attr;

    if(doc->lpszOutput == NULL) /* Check whether default port is FILE: */
    {
        PRINTER_INFO_5W *pi5;
        GetPrinterW(hPrinter, 5, NULL, 0, &len);
        if(GetLastError() != ERROR_INSUFFICIENT_BUFFER)
            return NULL;
        pi5 = HeapAlloc(GetProcessHeap(), 0, len);
        GetPrinterW(hPrinter, 5, (LPBYTE)pi5, len, &len);
        if(!pi5->pPortName || strcmpW(pi5->pPortName, FILE_Port))
        {
            HeapFree(GetProcessHeap(), 0, pi5);
            return NULL;
        }
        HeapFree(GetProcessHeap(), 0, pi5);
    }

    if(doc->lpszOutput == NULL || !strcmpW(doc->lpszOutput, FILE_Port))
    {
        LPWSTR name;
8822 8823

        if (get_filename(&name))
8824 8825 8826 8827 8828 8829 8830 8831 8832 8833 8834 8835 8836 8837 8838 8839 8840 8841 8842 8843 8844 8845 8846 8847 8848 8849 8850
        {
            if(!(len = GetFullPathNameW(name, 0, NULL, NULL)))
            {
                HeapFree(GetProcessHeap(), 0, name);
                return NULL;
            }
            ret = HeapAlloc(GetProcessHeap(), 0, len * sizeof(WCHAR));
            GetFullPathNameW(name, len, ret, NULL);
            HeapFree(GetProcessHeap(), 0, name);
        }
        return ret;
    }

    if(!(len = GetFullPathNameW(doc->lpszOutput, 0, NULL, NULL)))
        return NULL;

    ret = HeapAlloc(GetProcessHeap(), 0, len * sizeof(WCHAR));
    GetFullPathNameW(doc->lpszOutput, len, ret, NULL);
        
    attr = GetFileAttributesW(ret);
    if(attr != INVALID_FILE_ATTRIBUTES && (attr & FILE_ATTRIBUTE_DIRECTORY))
    {
        HeapFree(GetProcessHeap(), 0, ret);
        ret = NULL;
    }
    return ret;
}
8851 8852 8853 8854 8855 8856 8857 8858 8859 8860 8861 8862 8863 8864 8865 8866 8867 8868 8869 8870 8871 8872

/*****************************************************************************
 *          UploadPrinterDriverPackageA [WINSPOOL.@]
 */
HRESULT WINAPI UploadPrinterDriverPackageA( LPCSTR server, LPCSTR path, LPCSTR env,
                                            DWORD flags, HWND hwnd, LPSTR dst, PULONG dstlen )
{
    FIXME("%s, %s, %s, %x, %p, %p, %p\n", debugstr_a(server), debugstr_a(path), debugstr_a(env),
          flags, hwnd, dst, dstlen);
    return E_NOTIMPL;
}

/*****************************************************************************
 *          UploadPrinterDriverPackageW [WINSPOOL.@]
 */
HRESULT WINAPI UploadPrinterDriverPackageW( LPCWSTR server, LPCWSTR path, LPCWSTR env,
                                            DWORD flags, HWND hwnd, LPWSTR dst, PULONG dstlen )
{
    FIXME("%s, %s, %s, %x, %p, %p, %p\n", debugstr_w(server), debugstr_w(path), debugstr_w(env),
          flags, hwnd, dst, dstlen);
    return E_NOTIMPL;
}
8873 8874 8875 8876 8877 8878 8879 8880 8881 8882 8883 8884 8885 8886 8887 8888 8889 8890 8891 8892 8893 8894 8895 8896 8897 8898 8899 8900 8901

/*****************************************************************************
 *          PerfOpen [WINSPOOL.@]
 */
DWORD WINAPI PerfOpen(LPWSTR context)
{
    FIXME("%s: stub\n", debugstr_w(context));
    return ERROR_SUCCESS;
}

/*****************************************************************************
 *          PerfClose [WINSPOOL.@]
 */
DWORD WINAPI PerfClose(void)
{
    FIXME("stub\n");
    return ERROR_SUCCESS;
}

/*****************************************************************************
 *          PerfCollect [WINSPOOL.@]
 */
DWORD WINAPI PerfCollect(LPWSTR query, LPVOID *data, LPDWORD size, LPDWORD obj_count)
{
    FIXME("%s, %p, %p, %p: stub\n", debugstr_w(query), data, size, obj_count);
    *size = 0;
    *obj_count = 0;
    return ERROR_SUCCESS;
}