shellpath.c 121 KB
Newer Older
1 2 3
/*
 * Path Functions
 *
4
 * Copyright 1998, 1999, 2000 Juergen Schmied
5
 * Copyright 2004 Juan Lang
6 7 8 9 10 11 12 13 14 15 16 17 18
 *
 * 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
19
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
20 21 22 23
 *
 * NOTES:
 *
 * Many of these functions are in SHLWAPI.DLL also
24 25
 *
 */
26

27 28
#define COBJMACROS

29 30 31
#include "config.h"
#include "wine/port.h"

32
#include <stdio.h>
33
#include <stdarg.h>
34 35
#include <string.h>
#include <ctype.h>
36
#include "wine/debug.h"
37
#include "windef.h"
38
#include "winbase.h"
39
#include "winnls.h"
40
#include "winreg.h"
41 42
#include "wingdi.h"
#include "winuser.h"
43 44

#include "shlobj.h"
45
#include "shtypes.h"
46
#include "shresdef.h"
47
#include "shell32_main.h"
48
#include "undocshell.h"
Juan Lang's avatar
Juan Lang committed
49
#include "pidl.h"
50
#include "wine/unicode.h"
51
#include "shlwapi.h"
52
#include "xdg.h"
53
#include "sddl.h"
54
#include "knownfolders.h"
55
#include "initguid.h"
56
#include "shobjidl.h"
57

58
WINE_DEFAULT_DEBUG_CHANNEL(shell);
59

60 61
static const BOOL is_win64 = sizeof(void *) > sizeof(int);

62
/*
Juergen Schmied's avatar
Juergen Schmied committed
63
	########## Combining and Constructing paths ##########
64
*/
Alexandre Julliard's avatar
Alexandre Julliard committed
65

66
/*************************************************************************
Patrik Stridvall's avatar
Patrik Stridvall committed
67
 * PathAppend		[SHELL32.36]
68
 */
Juergen Schmied's avatar
Juergen Schmied committed
69
BOOL WINAPI PathAppendAW(
70 71 72
	LPVOID lpszPath1,
	LPCVOID lpszPath2)
{
73
	if (SHELL_OsIsUnicode())
74 75 76 77
	  return PathAppendW(lpszPath1, lpszPath2);
	return PathAppendA(lpszPath1, lpszPath2);
}

78
/*************************************************************************
Patrik Stridvall's avatar
Patrik Stridvall committed
79
 * PathCombine	 [SHELL32.37]
80
 */
81 82 83
LPVOID WINAPI PathCombineAW(
	LPVOID szDest,
	LPCVOID lpszDir,
84
	LPCVOID lpszFile)
85
{
86
	if (SHELL_OsIsUnicode())
87 88
	  return PathCombineW( szDest, lpszDir, lpszFile );
	return PathCombineA( szDest, lpszDir, lpszFile );
89 90
}

91
/*************************************************************************
Patrik Stridvall's avatar
Patrik Stridvall committed
92
 * PathAddBackslash		[SHELL32.32]
93 94 95
 */
LPVOID WINAPI PathAddBackslashAW(LPVOID lpszPath)
{
96
	if(SHELL_OsIsUnicode())
97 98 99 100 101
	  return PathAddBackslashW(lpszPath);
	return PathAddBackslashA(lpszPath);
}

/*************************************************************************
Patrik Stridvall's avatar
Patrik Stridvall committed
102
 * PathBuildRoot		[SHELL32.30]
103 104 105
 */
LPVOID WINAPI PathBuildRootAW(LPVOID lpszPath, int drive)
{
106
	if(SHELL_OsIsUnicode())
107 108 109 110 111 112 113 114 115
	  return PathBuildRootW(lpszPath, drive);
	return PathBuildRootA(lpszPath, drive);
}

/*
	Extracting Component Parts
*/

/*************************************************************************
Patrik Stridvall's avatar
Patrik Stridvall committed
116
 * PathFindFileName	[SHELL32.34]
117 118 119
 */
LPVOID WINAPI PathFindFileNameAW(LPCVOID lpszPath)
{
120
	if(SHELL_OsIsUnicode())
121 122 123 124
	  return PathFindFileNameW(lpszPath);
	return PathFindFileNameA(lpszPath);
}

125
/*************************************************************************
Patrik Stridvall's avatar
Patrik Stridvall committed
126
 * PathFindExtension		[SHELL32.31]
127
 */
128
LPVOID WINAPI PathFindExtensionAW(LPCVOID lpszPath)
129
{
130
	if (SHELL_OsIsUnicode())
131 132 133 134 135
	  return PathFindExtensionW(lpszPath);
	return PathFindExtensionA(lpszPath);

}

136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161
/*************************************************************************
 * PathGetExtensionA		[internal]
 *
 * NOTES
 *  exported by ordinal
 *  return value points to the first char after the dot
 */
static LPSTR PathGetExtensionA(LPCSTR lpszPath)
{
	TRACE("(%s)\n",lpszPath);

	lpszPath = PathFindExtensionA(lpszPath);
	return (LPSTR)(*lpszPath?(lpszPath+1):lpszPath);
}

/*************************************************************************
 * PathGetExtensionW		[internal]
 */
static LPWSTR PathGetExtensionW(LPCWSTR lpszPath)
{
	TRACE("(%s)\n",debugstr_w(lpszPath));

	lpszPath = PathFindExtensionW(lpszPath);
	return (LPWSTR)(*lpszPath?(lpszPath+1):lpszPath);
}

162
/*************************************************************************
Patrik Stridvall's avatar
Patrik Stridvall committed
163
 * PathGetExtension		[SHELL32.158]
164
 */
165
LPVOID WINAPI PathGetExtensionAW(LPCVOID lpszPath,DWORD void1, DWORD void2)
166
{
167
	if (SHELL_OsIsUnicode())
168 169
	  return PathGetExtensionW(lpszPath);
	return PathGetExtensionA(lpszPath);
170
}
171 172

/*************************************************************************
Patrik Stridvall's avatar
Patrik Stridvall committed
173
 * PathGetArgs	[SHELL32.52]
174
 */
175
LPVOID WINAPI PathGetArgsAW(LPVOID lpszPath)
176
{
177
	if (SHELL_OsIsUnicode())
178 179
	  return PathGetArgsW(lpszPath);
	return PathGetArgsA(lpszPath);
180 181
}

182
/*************************************************************************
183
 * PathGetDriveNumber	[SHELL32.57]
184
 */
185
int WINAPI PathGetDriveNumberAW(LPVOID lpszPath)
186
{
187
	if (SHELL_OsIsUnicode())
188 189
	  return PathGetDriveNumberW(lpszPath);
	return PathGetDriveNumberA(lpszPath);
190
}
191

192
/*************************************************************************
193
 * PathRemoveFileSpec [SHELL32.35]
194
 */
195
BOOL WINAPI PathRemoveFileSpecAW(LPVOID lpszPath)
196
{
197
	if (SHELL_OsIsUnicode())
198 199
	  return PathRemoveFileSpecW(lpszPath);
	return PathRemoveFileSpecA(lpszPath);
200
}
201 202

/*************************************************************************
Patrik Stridvall's avatar
Patrik Stridvall committed
203
 * PathStripPath	[SHELL32.38]
204
 */
205
void WINAPI PathStripPathAW(LPVOID lpszPath)
206
{
207
	if (SHELL_OsIsUnicode())
208 209 210
            PathStripPathW(lpszPath);
        else
            PathStripPathA(lpszPath);
211
}
212 213

/*************************************************************************
Patrik Stridvall's avatar
Patrik Stridvall committed
214
 * PathStripToRoot	[SHELL32.50]
215
 */
216
BOOL WINAPI PathStripToRootAW(LPVOID lpszPath)
217
{
218
	if (SHELL_OsIsUnicode())
219 220
	  return PathStripToRootW(lpszPath);
	return PathStripToRootA(lpszPath);
221
}
222

223
/*************************************************************************
Patrik Stridvall's avatar
Patrik Stridvall committed
224
 * PathRemoveArgs	[SHELL32.251]
225
 */
226
void WINAPI PathRemoveArgsAW(LPVOID lpszPath)
227
{
228
	if (SHELL_OsIsUnicode())
229 230 231
            PathRemoveArgsW(lpszPath);
        else
            PathRemoveArgsA(lpszPath);
232
}
233 234

/*************************************************************************
Patrik Stridvall's avatar
Patrik Stridvall committed
235
 * PathRemoveExtension	[SHELL32.250]
236
 */
237
void WINAPI PathRemoveExtensionAW(LPVOID lpszPath)
238
{
239
	if (SHELL_OsIsUnicode())
240 241 242
            PathRemoveExtensionW(lpszPath);
        else
            PathRemoveExtensionA(lpszPath);
243
}
244 245


246 247 248
/*
	Path Manipulations
*/
249 250

/*************************************************************************
251
 * PathGetShortPathA [internal]
252
 */
253
static void PathGetShortPathA(LPSTR pszPath)
254
{
255 256 257 258 259 260 261 262
	CHAR path[MAX_PATH];

	TRACE("%s\n", pszPath);

	if (GetShortPathNameA(pszPath, path, MAX_PATH))
	{
	  lstrcpyA(pszPath, path);
	}
263 264 265
}

/*************************************************************************
266
 * PathGetShortPathW [internal]
267
 */
268
static void PathGetShortPathW(LPWSTR pszPath)
269
{
270 271 272 273 274 275 276 277
	WCHAR path[MAX_PATH];

	TRACE("%s\n", debugstr_w(pszPath));

	if (GetShortPathNameW(pszPath, path, MAX_PATH))
	{
	  lstrcpyW(pszPath, path);
	}
278
}
279 280

/*************************************************************************
Patrik Stridvall's avatar
Patrik Stridvall committed
281
 * PathGetShortPath [SHELL32.92]
282
 */
283
VOID WINAPI PathGetShortPathAW(LPVOID pszPath)
284
{
285
	if(SHELL_OsIsUnicode())
286 287
	  PathGetShortPathW(pszPath);
	PathGetShortPathA(pszPath);
288
}
289 290

/*************************************************************************
Patrik Stridvall's avatar
Patrik Stridvall committed
291
 * PathRemoveBlanks [SHELL32.33]
292
 */
293
void WINAPI PathRemoveBlanksAW(LPVOID str)
Juergen Schmied's avatar
Juergen Schmied committed
294
{
295
	if(SHELL_OsIsUnicode())
296 297 298
            PathRemoveBlanksW(str);
        else
            PathRemoveBlanksA(str);
299 300
}

Juergen Schmied's avatar
Juergen Schmied committed
301
/*************************************************************************
Patrik Stridvall's avatar
Patrik Stridvall committed
302
 * PathQuoteSpaces [SHELL32.55]
Juergen Schmied's avatar
Juergen Schmied committed
303
 */
304
VOID WINAPI PathQuoteSpacesAW (LPVOID lpszPath)
Juergen Schmied's avatar
Juergen Schmied committed
305
{
306
	if(SHELL_OsIsUnicode())
307 308 309
            PathQuoteSpacesW(lpszPath);
        else
            PathQuoteSpacesA(lpszPath);
Juergen Schmied's avatar
Juergen Schmied committed
310 311 312
}

/*************************************************************************
Patrik Stridvall's avatar
Patrik Stridvall committed
313
 * PathUnquoteSpaces [SHELL32.56]
Juergen Schmied's avatar
Juergen Schmied committed
314
 */
315
VOID WINAPI PathUnquoteSpacesAW(LPVOID str)
Juergen Schmied's avatar
Juergen Schmied committed
316
{
317
	if(SHELL_OsIsUnicode())
318 319 320
	  PathUnquoteSpacesW(str);
	else
	  PathUnquoteSpacesA(str);
Juergen Schmied's avatar
Juergen Schmied committed
321 322 323
}

/*************************************************************************
Patrik Stridvall's avatar
Patrik Stridvall committed
324
 * PathParseIconLocation	[SHELL32.249]
Juergen Schmied's avatar
Juergen Schmied committed
325
 */
326
int WINAPI PathParseIconLocationAW (LPVOID lpszPath)
Juergen Schmied's avatar
Juergen Schmied committed
327
{
328
	if(SHELL_OsIsUnicode())
329 330
	  return PathParseIconLocationW(lpszPath);
	return PathParseIconLocationA(lpszPath);
Juergen Schmied's avatar
Juergen Schmied committed
331 332
}

333 334 335
/*
	########## Path Testing ##########
*/
Juergen Schmied's avatar
Juergen Schmied committed
336
/*************************************************************************
Patrik Stridvall's avatar
Patrik Stridvall committed
337
 * PathIsUNC		[SHELL32.39]
Juergen Schmied's avatar
Juergen Schmied committed
338
 */
339
BOOL WINAPI PathIsUNCAW (LPCVOID lpszPath)
Juergen Schmied's avatar
Juergen Schmied committed
340
{
341
	if (SHELL_OsIsUnicode())
342
	  return PathIsUNCW( lpszPath );
343
	return PathIsUNCA( lpszPath );
Juergen Schmied's avatar
Juergen Schmied committed
344 345 346
}

/*************************************************************************
Patrik Stridvall's avatar
Patrik Stridvall committed
347
 *  PathIsRelative	[SHELL32.40]
Juergen Schmied's avatar
Juergen Schmied committed
348
 */
349
BOOL WINAPI PathIsRelativeAW (LPCVOID lpszPath)
Juergen Schmied's avatar
Juergen Schmied committed
350
{
351
	if (SHELL_OsIsUnicode())
352
	  return PathIsRelativeW( lpszPath );
353
	return PathIsRelativeA( lpszPath );
Juergen Schmied's avatar
Juergen Schmied committed
354 355 356
}

/*************************************************************************
Patrik Stridvall's avatar
Patrik Stridvall committed
357
 * PathIsRoot		[SHELL32.29]
Juergen Schmied's avatar
Juergen Schmied committed
358
 */
359
BOOL WINAPI PathIsRootAW(LPCVOID lpszPath)
Juergen Schmied's avatar
Juergen Schmied committed
360
{
361
	if (SHELL_OsIsUnicode())
362 363
	  return PathIsRootW(lpszPath);
	return PathIsRootA(lpszPath);
Juergen Schmied's avatar
Juergen Schmied committed
364 365
}

366 367 368 369 370 371
/*************************************************************************
 *  PathIsExeA		[internal]
 */
static BOOL PathIsExeA (LPCSTR lpszPath)
{
	LPCSTR lpszExtension = PathGetExtensionA(lpszPath);
372 373 374
        int i;
        static const char * const lpszExtensions[] =
            {"exe", "com", "pif", "cmd", "bat", "scf", "scr", NULL };
375

376 377 378
	TRACE("path=%s\n",lpszPath);

	for(i=0; lpszExtensions[i]; i++)
379
	  if (!lstrcmpiA(lpszExtension,lpszExtensions[i])) return TRUE;
380

381 382 383 384 385 386 387 388 389
	return FALSE;
}

/*************************************************************************
 *  PathIsExeW		[internal]
 */
static BOOL PathIsExeW (LPCWSTR lpszPath)
{
	LPCWSTR lpszExtension = PathGetExtensionW(lpszPath);
390 391 392 393 394
        int i;
        static const WCHAR lpszExtensions[][4] =
            {{'e','x','e','\0'}, {'c','o','m','\0'}, {'p','i','f','\0'},
             {'c','m','d','\0'}, {'b','a','t','\0'}, {'s','c','f','\0'},
             {'s','c','r','\0'}, {'\0'} };
395

396 397
	TRACE("path=%s\n",debugstr_w(lpszPath));

398
	for(i=0; lpszExtensions[i][0]; i++)
399
	  if (!strcmpiW(lpszExtension,lpszExtensions[i])) return TRUE;
400

401 402 403
	return FALSE;
}

Juergen Schmied's avatar
Juergen Schmied committed
404
/*************************************************************************
Patrik Stridvall's avatar
Patrik Stridvall committed
405
 *  PathIsExe		[SHELL32.43]
Juergen Schmied's avatar
Juergen Schmied committed
406
 */
407
BOOL WINAPI PathIsExeAW (LPCVOID path)
Juergen Schmied's avatar
Juergen Schmied committed
408
{
409
	if (SHELL_OsIsUnicode())
410 411
	  return PathIsExeW (path);
	return PathIsExeA(path);
Juergen Schmied's avatar
Juergen Schmied committed
412 413 414
}

/*************************************************************************
Patrik Stridvall's avatar
Patrik Stridvall committed
415
 * PathIsDirectory	[SHELL32.159]
Juergen Schmied's avatar
Juergen Schmied committed
416
 */
417
BOOL WINAPI PathIsDirectoryAW (LPCVOID lpszPath)
Juergen Schmied's avatar
Juergen Schmied committed
418
{
419
	if (SHELL_OsIsUnicode())
420 421
	  return PathIsDirectoryW (lpszPath);
	return PathIsDirectoryA (lpszPath);
Juergen Schmied's avatar
Juergen Schmied committed
422 423 424
}

/*************************************************************************
Patrik Stridvall's avatar
Patrik Stridvall committed
425
 * PathFileExists	[SHELL32.45]
426
 */
427
BOOL WINAPI PathFileExistsAW (LPCVOID lpszPath)
Juergen Schmied's avatar
Juergen Schmied committed
428
{
429
	if (SHELL_OsIsUnicode())
430 431
	  return PathFileExistsW (lpszPath);
	return PathFileExistsA (lpszPath);
Juergen Schmied's avatar
Juergen Schmied committed
432 433 434
}

/*************************************************************************
Patrik Stridvall's avatar
Patrik Stridvall committed
435
 * PathMatchSpec	[SHELL32.46]
Juergen Schmied's avatar
Juergen Schmied committed
436
 */
437
BOOL WINAPI PathMatchSpecAW(LPVOID name, LPVOID mask)
Juergen Schmied's avatar
Juergen Schmied committed
438
{
439
	if (SHELL_OsIsUnicode())
440 441
	  return PathMatchSpecW( name, mask );
	return PathMatchSpecA( name, mask );
Juergen Schmied's avatar
Juergen Schmied committed
442 443 444
}

/*************************************************************************
Patrik Stridvall's avatar
Patrik Stridvall committed
445
 * PathIsSameRoot	[SHELL32.650]
Juergen Schmied's avatar
Juergen Schmied committed
446
 */
447
BOOL WINAPI PathIsSameRootAW(LPCVOID lpszPath1, LPCVOID lpszPath2)
Juergen Schmied's avatar
Juergen Schmied committed
448
{
449
	if (SHELL_OsIsUnicode())
450 451
	  return PathIsSameRootW(lpszPath1, lpszPath2);
	return PathIsSameRootA(lpszPath1, lpszPath2);
Juergen Schmied's avatar
Juergen Schmied committed
452 453 454
}

/*************************************************************************
455
 * IsLFNDriveA		[SHELL32.41]
Juergen Schmied's avatar
Juergen Schmied committed
456
 */
457
BOOL WINAPI IsLFNDriveA(LPCSTR lpszPath)
Juergen Schmied's avatar
Juergen Schmied committed
458
{
459 460
    DWORD	fnlen;

461 462 463 464 465 466 467 468 469 470 471 472 473
    if (!GetVolumeInformationA(lpszPath, NULL, 0, NULL, &fnlen, NULL, NULL, 0))
	return FALSE;
    return fnlen > 12;
}

/*************************************************************************
 * IsLFNDriveW		[SHELL32.42]
 */
BOOL WINAPI IsLFNDriveW(LPCWSTR lpszPath)
{
    DWORD	fnlen;

    if (!GetVolumeInformationW(lpszPath, NULL, 0, NULL, &fnlen, NULL, NULL, 0))
Juergen Schmied's avatar
Juergen Schmied committed
474
	return FALSE;
475
    return fnlen > 12;
Juergen Schmied's avatar
Juergen Schmied committed
476 477
}

478 479 480 481 482 483 484 485 486 487
/*************************************************************************
 * IsLFNDrive		[SHELL32.119]
 */
BOOL WINAPI IsLFNDriveAW(LPCVOID lpszPath)
{
	if (SHELL_OsIsUnicode())
	  return IsLFNDriveW(lpszPath);
	return IsLFNDriveA(lpszPath);
}

488
/*
Juergen Schmied's avatar
Juergen Schmied committed
489
	########## Creating Something Unique ##########
490
*/
491
/*************************************************************************
492
 * PathMakeUniqueNameA	[internal]
493
 */
494
static BOOL PathMakeUniqueNameA(
495
	LPSTR lpszBuffer,
496
	DWORD dwBuffSize,
497 498 499 500
	LPCSTR lpszShortName,
	LPCSTR lpszLongName,
	LPCSTR lpszPathName)
{
501
	FIXME("%p %u %s %s %s stub\n",
502 503 504
	 lpszBuffer, dwBuffSize, debugstr_a(lpszShortName),
	 debugstr_a(lpszLongName), debugstr_a(lpszPathName));
	return TRUE;
505 506
}

507
/*************************************************************************
508
 * PathMakeUniqueNameW	[internal]
509
 */
510
static BOOL PathMakeUniqueNameW(
511
	LPWSTR lpszBuffer,
512
	DWORD dwBuffSize,
513 514 515 516
	LPCWSTR lpszShortName,
	LPCWSTR lpszLongName,
	LPCWSTR lpszPathName)
{
517
	FIXME("%p %u %s %s %s stub\n",
518 519 520
	 lpszBuffer, dwBuffSize, debugstr_w(lpszShortName),
	 debugstr_w(lpszLongName), debugstr_w(lpszPathName));
	return TRUE;
521 522 523
}

/*************************************************************************
Patrik Stridvall's avatar
Patrik Stridvall committed
524
 * PathMakeUniqueName	[SHELL32.47]
525
 */
526 527
BOOL WINAPI PathMakeUniqueNameAW(
	LPVOID lpszBuffer,
528
	DWORD dwBuffSize,
529 530 531
	LPCVOID lpszShortName,
	LPCVOID lpszLongName,
	LPCVOID lpszPathName)
532
{
533
	if (SHELL_OsIsUnicode())
534 535
	  return PathMakeUniqueNameW(lpszBuffer,dwBuffSize, lpszShortName,lpszLongName,lpszPathName);
	return PathMakeUniqueNameA(lpszBuffer,dwBuffSize, lpszShortName,lpszLongName,lpszPathName);
536 537
}

538
/*************************************************************************
Patrik Stridvall's avatar
Patrik Stridvall committed
539
 * PathYetAnotherMakeUniqueName [SHELL32.75]
540
 *
541 542 543
 * NOTES
 *     exported by ordinal
 */
544 545 546 547 548
BOOL WINAPI PathYetAnotherMakeUniqueName(
	LPWSTR lpszBuffer,
	LPCWSTR lpszPathName,
	LPCWSTR lpszShortName,
	LPCWSTR lpszLongName)
549
{
550 551
    FIXME("(%p, %s, %s ,%s):stub.\n",
          lpszBuffer, debugstr_w(lpszPathName), debugstr_w(lpszShortName), debugstr_w(lpszLongName));
552 553 554 555
    return TRUE;
}


556
/*
Juergen Schmied's avatar
Juergen Schmied committed
557
	########## cleaning and resolving paths ##########
558
 */
559 560

/*************************************************************************
Patrik Stridvall's avatar
Patrik Stridvall committed
561
 * PathFindOnPath	[SHELL32.145]
562
 */
563
BOOL WINAPI PathFindOnPathAW(LPVOID sFile, LPCVOID *sOtherDirs)
564
{
565
	if (SHELL_OsIsUnicode())
566 567
	  return PathFindOnPathW(sFile, (LPCWSTR *)sOtherDirs);
	return PathFindOnPathA(sFile, (LPCSTR *)sOtherDirs);
568 569
}

570
/*************************************************************************
Patrik Stridvall's avatar
Patrik Stridvall committed
571
 * PathCleanupSpec	[SHELL32.171]
572 573
 *
 * lpszFile is changed in place.
574
 */
575
int WINAPI PathCleanupSpec( LPCWSTR lpszPathW, LPWSTR lpszFileW )
576
{
577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612
    int i = 0;
    DWORD rc = 0;
    int length = 0;

    if (SHELL_OsIsUnicode())
    {
        LPWSTR p = lpszFileW;

        TRACE("Cleanup %s\n",debugstr_w(lpszFileW));

        if (lpszPathW)
            length = strlenW(lpszPathW);

        while (*p)
        {
            int gct = PathGetCharTypeW(*p);
            if (gct == GCT_INVALID || gct == GCT_WILD || gct == GCT_SEPARATOR)
            {
                lpszFileW[i]='-';
                rc |= PCS_REPLACEDCHAR;
            }
            else
                lpszFileW[i]=*p;
            i++;
            p++;
            if (length + i == MAX_PATH)
            {
                rc |= PCS_FATAL | PCS_PATHTOOLONG;
                break;
            }
        }
        lpszFileW[i]=0;
    }
    else
    {
        LPSTR lpszFileA = (LPSTR)lpszFileW;
613
        LPCSTR lpszPathA = (LPCSTR)lpszPathW;
614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641
        LPSTR p = lpszFileA;

        TRACE("Cleanup %s\n",debugstr_a(lpszFileA));

        if (lpszPathA)
            length = strlen(lpszPathA);

        while (*p)
        {
            int gct = PathGetCharTypeA(*p);
            if (gct == GCT_INVALID || gct == GCT_WILD || gct == GCT_SEPARATOR)
            {
                lpszFileA[i]='-';
                rc |= PCS_REPLACEDCHAR;
            }
            else
                lpszFileA[i]=*p;
            i++;
            p++;
            if (length + i == MAX_PATH)
            {
                rc |= PCS_FATAL | PCS_PATHTOOLONG;
                break;
            }
        }
        lpszFileA[i]=0;
    }
    return rc;
642 643
}

644
/*************************************************************************
645
 * PathQualifyA		[SHELL32]
646
 */
647
static BOOL PathQualifyA(LPCSTR pszPath)
648 649
{
	FIXME("%s\n",pszPath);
650 651 652 653
	return 0;
}

/*************************************************************************
654 655
 * PathQualifyW		[SHELL32]
 */
656
static BOOL PathQualifyW(LPCWSTR pszPath)
657 658 659 660 661 662
{
	FIXME("%s\n",debugstr_w(pszPath));
	return 0;
}

/*************************************************************************
Patrik Stridvall's avatar
Patrik Stridvall committed
663
 * PathQualify	[SHELL32.49]
664
 */
665
BOOL WINAPI PathQualifyAW(LPCVOID pszPath)
666
{
667
	if (SHELL_OsIsUnicode())
668 669 670 671
	  return PathQualifyW(pszPath);
	return PathQualifyA(pszPath);
}

672
static BOOL PathResolveA(LPSTR path, LPCSTR *paths, DWORD flags)
673
{
674 675
    FIXME("(%s,%p,0x%08x),stub!\n", debugstr_a(path), paths, flags);
    return FALSE;
676 677
}

678
static BOOL PathResolveW(LPWSTR path, LPCWSTR *paths, DWORD flags)
679
{
680 681
    FIXME("(%s,%p,0x%08x),stub!\n", debugstr_w(path), paths, flags);
    return FALSE;
682 683 684
}

/*************************************************************************
Patrik Stridvall's avatar
Patrik Stridvall committed
685
 * PathResolve [SHELL32.51]
686
 */
687
BOOL WINAPI PathResolveAW(LPVOID path, LPCVOID *paths, DWORD flags)
688
{
689 690 691 692
    if (SHELL_OsIsUnicode())
        return PathResolveW(path, (LPCWSTR*)paths, flags);
    else
        return PathResolveA(path, (LPCSTR*)paths, flags);
693 694 695
}

/*************************************************************************
696
*	PathProcessCommandA
697
*/
698
static LONG PathProcessCommandA (
699 700 701 702
	LPCSTR lpszPath,
	LPSTR lpszBuff,
	DWORD dwBuffSize,
	DWORD dwFlags)
Juergen Schmied's avatar
Juergen Schmied committed
703
{
704
	FIXME("%s %p 0x%04x 0x%04x stub\n",
705
	lpszPath, lpszBuff, dwBuffSize, dwFlags);
706 707 708
	if(!lpszPath) return -1;
	if(lpszBuff) strcpy(lpszBuff, lpszPath);
	return strlen(lpszPath);
Juergen Schmied's avatar
Juergen Schmied committed
709 710
}

711 712 713
/*************************************************************************
*	PathProcessCommandW
*/
714
static LONG PathProcessCommandW (
715 716 717 718
	LPCWSTR lpszPath,
	LPWSTR lpszBuff,
	DWORD dwBuffSize,
	DWORD dwFlags)
Juergen Schmied's avatar
Juergen Schmied committed
719
{
720
	FIXME("(%s, %p, 0x%04x, 0x%04x) stub\n",
721
	debugstr_w(lpszPath), lpszBuff, dwBuffSize, dwFlags);
722 723 724
	if(!lpszPath) return -1;
	if(lpszBuff) strcpyW(lpszBuff, lpszPath);
	return strlenW(lpszPath);
725
}
726

727
/*************************************************************************
Patrik Stridvall's avatar
Patrik Stridvall committed
728
*	PathProcessCommand (SHELL32.653)
729
*/
730
LONG WINAPI PathProcessCommandAW (
731 732 733 734
	LPCVOID lpszPath,
	LPVOID lpszBuff,
	DWORD dwBuffSize,
	DWORD dwFlags)
Juergen Schmied's avatar
Juergen Schmied committed
735
{
736
	if (SHELL_OsIsUnicode())
737 738 739 740 741
	  return PathProcessCommandW(lpszPath, lpszBuff, dwBuffSize, dwFlags);
	return PathProcessCommandA(lpszPath, lpszBuff, dwBuffSize, dwFlags);
}

/*
Juergen Schmied's avatar
Juergen Schmied committed
742
	########## special ##########
743 744 745
*/

/*************************************************************************
Patrik Stridvall's avatar
Patrik Stridvall committed
746
 * PathSetDlgItemPath (SHELL32.48)
747
 */
748
VOID WINAPI PathSetDlgItemPathAW(HWND hDlg, int id, LPCVOID pszPath)
749 750 751 752 753
{
	if (SHELL_OsIsUnicode())
            PathSetDlgItemPathW(hDlg, id, pszPath);
        else
            PathSetDlgItemPathA(hDlg, id, pszPath);
Juergen Schmied's avatar
Juergen Schmied committed
754 755
}

756
static const WCHAR szCurrentVersion[] = {'S','o','f','t','w','a','r','e','\\','M','i','c','r','o','s','o','f','t','\\','W','i','n','d','o','w','s','\\','C','u','r','r','e','n','t','V','e','r','s','i','o','n','\0'};
757 758
static const WCHAR Administrative_ToolsW[] = {'A','d','m','i','n','i','s','t','r','a','t','i','v','e',' ','T','o','o','l','s','\0'};
static const WCHAR AppDataW[] = {'A','p','p','D','a','t','a','\0'};
759 760
static const WCHAR AppData_LocalLowW[] = {'A','p','p','D','a','t','a','\\','L','o','c','a','l','L','o','w','\0'};
static const WCHAR Application_DataW[] = {'A','p','p','l','i','c','a','t','i','o','n',' ','D','a','t','a','\0'};
761 762 763 764 765 766
static const WCHAR CacheW[] = {'C','a','c','h','e','\0'};
static const WCHAR CD_BurningW[] = {'C','D',' ','B','u','r','n','i','n','g','\0'};
static const WCHAR Common_Administrative_ToolsW[] = {'C','o','m','m','o','n',' ','A','d','m','i','n','i','s','t','r','a','t','i','v','e',' ','T','o','o','l','s','\0'};
static const WCHAR Common_AppDataW[] = {'C','o','m','m','o','n',' ','A','p','p','D','a','t','a','\0'};
static const WCHAR Common_DesktopW[] = {'C','o','m','m','o','n',' ','D','e','s','k','t','o','p','\0'};
static const WCHAR Common_DocumentsW[] = {'C','o','m','m','o','n',' ','D','o','c','u','m','e','n','t','s','\0'};
767
static const WCHAR Common_FavoritesW[] = {'C','o','m','m','o','n',' ','F','a','v','o','r','i','t','e','s','\0'};
768
static const WCHAR CommonFilesDirW[] = {'C','o','m','m','o','n','F','i','l','e','s','D','i','r','\0'};
769
static const WCHAR CommonFilesDirX86W[] = {'C','o','m','m','o','n','F','i','l','e','s','D','i','r',' ','(','x','8','6',')','\0'};
770 771 772 773 774 775 776
static const WCHAR CommonMusicW[] = {'C','o','m','m','o','n','M','u','s','i','c','\0'};
static const WCHAR CommonPicturesW[] = {'C','o','m','m','o','n','P','i','c','t','u','r','e','s','\0'};
static const WCHAR Common_ProgramsW[] = {'C','o','m','m','o','n',' ','P','r','o','g','r','a','m','s','\0'};
static const WCHAR Common_StartUpW[] = {'C','o','m','m','o','n',' ','S','t','a','r','t','U','p','\0'};
static const WCHAR Common_Start_MenuW[] = {'C','o','m','m','o','n',' ','S','t','a','r','t',' ','M','e','n','u','\0'};
static const WCHAR Common_TemplatesW[] = {'C','o','m','m','o','n',' ','T','e','m','p','l','a','t','e','s','\0'};
static const WCHAR CommonVideoW[] = {'C','o','m','m','o','n','V','i','d','e','o','\0'};
777
static const WCHAR ContactsW[] = {'C','o','n','t','a','c','t','s','\0'};
778 779
static const WCHAR CookiesW[] = {'C','o','o','k','i','e','s','\0'};
static const WCHAR DesktopW[] = {'D','e','s','k','t','o','p','\0'};
780 781
static const WCHAR DocumentsW[] = {'D','o','c','u','m','e','n','t','s','\0'};
static const WCHAR DownloadsW[] = {'D','o','w','n','l','o','a','d','s','\0'};
782 783 784
static const WCHAR FavoritesW[] = {'F','a','v','o','r','i','t','e','s','\0'};
static const WCHAR FontsW[] = {'F','o','n','t','s','\0'};
static const WCHAR HistoryW[] = {'H','i','s','t','o','r','y','\0'};
785
static const WCHAR LinksW[] = {'L','i','n','k','s','\0'};
786
static const WCHAR Local_AppDataW[] = {'L','o','c','a','l',' ','A','p','p','D','a','t','a','\0'};
787 788 789 790 791 792 793 794 795 796 797 798
static const WCHAR Local_Settings_Application_DataW[] = {'L','o','c','a','l',' ','S','e','t','t','i','n','g','s','\\','A','p','p','l','i','c','a','t','i','o','n',' ','D','a','t','a','\0'};
static const WCHAR Local_Settings_CD_BurningW[] = {'L','o','c','a','l',' ','S','e','t','t','i','n','g','s','\\','A','p','p','l','i','c','a','t','i','o','n',' ','D','a','t','a','\\','M','i','c','r','o','s','o','f','t','\\','C','D',' ','B','u','r','n','i','n','g','\0'};
static const WCHAR Local_Settings_HistoryW[] = {'L','o','c','a','l',' ','S','e','t','t','i','n','g','s','\\','H','i','s','t','o','r','y','\0'};
static const WCHAR Local_Settings_Temporary_Internet_FilesW[] = {'L','o','c','a','l',' ','S','e','t','t','i','n','g','s','\\','T','e','m','p','o','r','a','r','y',' ','I','n','t','e','r','n','e','t',' ','F','i','l','e','s','\0'};
static const WCHAR Microsoft_Windows_GameExplorerW[] = {'M','i','c','r','o','s','o','f','t','\\','W','i','n','d','o','w','s','\\','G','a','m','e','E','x','p','l','o','r','e','r','\0'};
static const WCHAR Microsoft_Windows_LibrariesW[] = {'M','i','c','r','o','s','o','f','t','\\','W','i','n','d','o','w','s','\\','L','i','b','r','a','r','i','e','s','\0'};
static const WCHAR Microsoft_Windows_RingtonesW[] = {'M','i','c','r','o','s','o','f','t','\\','W','i','n','d','o','w','s','\\','R','i','n','g','t','o','n','e','s','\0'};
static const WCHAR MusicW[] = {'M','u','s','i','c','\0'};
static const WCHAR Music_PlaylistsW[] = {'M','u','s','i','c','\\','P','l','a','y','l','i','s','t','s','\0'};
static const WCHAR Music_Sample_MusicW[] = {'M','u','s','i','c','\\','S','a','m','p','l','e',' ','M','u','s','i','c','\0'};
static const WCHAR Music_Sample_PlaylistsW[] = {'M','u','s','i','c','\\','S','a','m','p','l','e',' ','P','l','a','y','l','i','s','t','s','\0'};
static const WCHAR My_DocumentsW[] = {'M','y',' ','D','o','c','u','m','e','n','t','s','\0'};
799 800
static const WCHAR My_MusicW[] = {'M','y',' ','M','u','s','i','c','\0'};
static const WCHAR My_PicturesW[] = {'M','y',' ','P','i','c','t','u','r','e','s','\0'};
801
static const WCHAR My_VideosW[] = {'M','y',' ','V','i','d','e','o','s','\0'};
802
static const WCHAR NetHoodW[] = {'N','e','t','H','o','o','d','\0'};
803
static const WCHAR OEM_LinksW[] = {'O','E','M',' ','L','i','n','k','s','\0'};
804
static const WCHAR PersonalW[] = {'P','e','r','s','o','n','a','l','\0'};
805 806 807
static const WCHAR PicturesW[] = {'P','i','c','t','u','r','e','s','\0'};
static const WCHAR Pictures_Sample_PicturesW[] = {'P','i','c','t','u','r','e','s','\\','S','a','m','p','l','e',' ','P','i','c','t','u','r','e','s','\0'};
static const WCHAR Pictures_Slide_ShowsW[] = {'P','i','c','t','u','r','e','s','\\','S','l','i','d','e',' ','S','h','o','w','s','\0'};
808
static const WCHAR PrintHoodW[] = {'P','r','i','n','t','H','o','o','d','\0'};
809 810 811 812
static const WCHAR Program_FilesW[] = {'P','r','o','g','r','a','m',' ','F','i','l','e','s','\0'};
static const WCHAR Program_Files_Common_FilesW[] = {'P','r','o','g','r','a','m',' ','F','i','l','e','s','\\','C','o','m','m','o','n',' ','F','i','l','e','s','\0'};
static const WCHAR Program_Files_x86W[] = {'P','r','o','g','r','a','m',' ','F','i','l','e','s',' ','(','x','8','6',')','\0'};
static const WCHAR Program_Files_x86_Common_FilesW[] = {'P','r','o','g','r','a','m',' ','F','i','l','e','s',' ','(','x','8','6',')','\\','C','o','m','m','o','n',' ','F','i','l','e','s','\0'};
813
static const WCHAR ProgramFilesDirW[] = {'P','r','o','g','r','a','m','F','i','l','e','s','D','i','r','\0'};
814
static const WCHAR ProgramFilesDirX86W[] = {'P','r','o','g','r','a','m','F','i','l','e','s','D','i','r',' ','(','x','8','6',')','\0'};
815
static const WCHAR ProgramsW[] = {'P','r','o','g','r','a','m','s','\0'};
816 817
static const WCHAR RecentW[] = {'R','e','c','e','n','t','\0'};
static const WCHAR ResourcesW[] = {'R','e','s','o','u','r','c','e','s','\0'};
818 819
static const WCHAR Saved_GamesW[] = {'S','a','v','e','d',' ','G','a','m','e','s','\0'};
static const WCHAR SearchesW[] = {'S','e','a','r','c','h','e','s','\0'};
820 821 822
static const WCHAR SendToW[] = {'S','e','n','d','T','o','\0'};
static const WCHAR StartUpW[] = {'S','t','a','r','t','U','p','\0'};
static const WCHAR Start_MenuW[] = {'S','t','a','r','t',' ','M','e','n','u','\0'};
823 824 825
static const WCHAR Start_Menu_ProgramsW[] = {'S','t','a','r','t',' ','M','e','n','u','\\','P','r','o','g','r','a','m','s','\0'};
static const WCHAR Start_Menu_Admin_ToolsW[] = {'S','t','a','r','t',' ','M','e','n','u','\\','P','r','o','g','r','a','m','s','\\','A','d','m','i','n','i','s','t','r','a','t','i','v','e',' ','T','o','o','l','s','\0'};
static const WCHAR Start_Menu_StartupW[] = {'S','t','a','r','t',' ','M','e','n','u','\\','P','r','o','g','r','a','m','s','\\','S','t','a','r','t','U','p','\0'};
826
static const WCHAR TemplatesW[] = {'T','e','m','p','l','a','t','e','s','\0'};
827 828
static const WCHAR UsersW[] = {'U','s','e','r','s','\0'};
static const WCHAR UsersPublicW[] = {'U','s','e','r','s','\\','P','u','b','l','i','c','\0'};
829 830
static const WCHAR VideosW[] = {'V','i','d','e','o','s','\0'};
static const WCHAR Videos_Sample_VideosW[] = {'V','i','d','e','o','s','\\','S','a','m','p','l','e',' ','V','i','d','e','o','s','\0'};
831 832 833 834 835 836 837 838 839
static const WCHAR DefaultW[] = {'.','D','e','f','a','u','l','t','\0'};
static const WCHAR AllUsersProfileW[] = {'%','A','L','L','U','S','E','R','S','P','R','O','F','I','L','E','%','\0'};
static const WCHAR UserProfileW[] = {'%','U','S','E','R','P','R','O','F','I','L','E','%','\0'};
static const WCHAR SystemDriveW[] = {'%','S','y','s','t','e','m','D','r','i','v','e','%','\0'};
static const WCHAR ProfileListW[] = {'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','o','f','i','l','e','L','i','s','t',0};
static const WCHAR ProfilesDirectoryW[] = {'P','r','o','f','i','l','e','s','D','i','r','e','c','t','o','r','y',0};
static const WCHAR AllUsersProfileValueW[] = {'A','l','l','U','s','e','r','s','P','r','o','f','i','l','e','\0'};
static const WCHAR szSHFolders[] = {'S','o','f','t','w','a','r','e','\\','M','i','c','r','o','s','o','f','t','\\','W','i','n','d','o','w','s','\\','C','u','r','r','e','n','t','V','e','r','s','i','o','n','\\','E','x','p','l','o','r','e','r','\\','S','h','e','l','l',' ','F','o','l','d','e','r','s','\0'};
static const WCHAR szSHUserFolders[] = {'S','o','f','t','w','a','r','e','\\','M','i','c','r','o','s','o','f','t','\\','W','i','n','d','o','w','s','\\','C','u','r','r','e','n','t','V','e','r','s','i','o','n','\\','E','x','p','l','o','r','e','r','\\','U','s','e','r',' ','S','h','e','l','l',' ','F','o','l','d','e','r','s','\0'};
840
static const WCHAR szDefaultProfileDirW[] = {'u','s','e','r','s',0};
841
static const WCHAR szKnownFolderDescriptions[] = {'S','o','f','t','w','a','r','e','\\','M','i','c','r','o','s','o','f','t','\\','W','i','n','d','o','w','s','\\','C','u','r','r','e','n','t','V','e','r','s','i','o','n','\\','E','x','p','l','o','r','e','r','\\','F','o','l','d','e','r','D','e','s','c','r','i','p','t','i','o','n','s','\0'};
842
static const WCHAR szKnownFolderRedirections[] = {'S','o','f','t','w','a','r','e','\\','M','i','c','r','o','s','o','f','t','\\','W','i','n','d','o','w','s','\\','C','u','r','r','e','n','t','V','e','r','s','i','o','n','\\','E','x','p','l','o','r','e','r','\\','U','s','e','r',' ','S','h','e','l','l',' ','F','o','l','d','e','r','s',0};
843
static const WCHAR AllUsersW[] = {'P','u','b','l','i','c',0};
844 845 846 847 848 849 850 851 852

typedef enum _CSIDL_Type {
    CSIDL_Type_User,
    CSIDL_Type_AllUsers,
    CSIDL_Type_CurrVer,
    CSIDL_Type_Disallowed,
    CSIDL_Type_NonExistent,
    CSIDL_Type_WindowsPath,
    CSIDL_Type_SystemPath,
853
    CSIDL_Type_SystemX86Path,
854
} CSIDL_Type;
855

856 857
typedef struct
{
858
    const KNOWNFOLDERID *id;
859 860 861
    CSIDL_Type type;
    LPCWSTR    szValueName;
    LPCWSTR    szDefaultPath; /* fallback string or resource ID */
862 863 864 865
} CSIDL_DATA;

static const CSIDL_DATA CSIDL_Data[] =
{
866
    { /* 0x00 - CSIDL_DESKTOP */
867
        &FOLDERID_Desktop,
868 869 870
        CSIDL_Type_User,
        DesktopW,
        MAKEINTRESOURCEW(IDS_DESKTOPDIRECTORY)
871
    },
872
    { /* 0x01 - CSIDL_INTERNET */
873
        &FOLDERID_InternetFolder,
874 875 876
        CSIDL_Type_Disallowed,
        NULL,
        NULL
877
    },
878
    { /* 0x02 - CSIDL_PROGRAMS */
879
        &FOLDERID_Programs,
880 881
        CSIDL_Type_User,
        ProgramsW,
882
        Start_Menu_ProgramsW
883
    },
884
    { /* 0x03 - CSIDL_CONTROLS (.CPL files) */
885
        &FOLDERID_ControlPanelFolder,
886 887 888
        CSIDL_Type_SystemPath,
        NULL,
        NULL
889
    },
890
    { /* 0x04 - CSIDL_PRINTERS */
891
        &FOLDERID_PrintersFolder,
892 893 894
        CSIDL_Type_SystemPath,
        NULL,
        NULL
895
    },
896
    { /* 0x05 - CSIDL_PERSONAL */
897
        &FOLDERID_Documents,
898 899 900
        CSIDL_Type_User,
        PersonalW,
        MAKEINTRESOURCEW(IDS_PERSONAL)
901
    },
902
    { /* 0x06 - CSIDL_FAVORITES */
903
        &FOLDERID_Favorites,
904 905
        CSIDL_Type_User,
        FavoritesW,
906
        FavoritesW
907
    },
908
    { /* 0x07 - CSIDL_STARTUP */
909
        &FOLDERID_Startup,
910 911
        CSIDL_Type_User,
        StartUpW,
912
        Start_Menu_StartupW
913
    },
914
    { /* 0x08 - CSIDL_RECENT */
915
        &FOLDERID_Recent,
916 917
        CSIDL_Type_User,
        RecentW,
918
        RecentW
919
    },
920
    { /* 0x09 - CSIDL_SENDTO */
921
        &FOLDERID_SendTo,
922 923
        CSIDL_Type_User,
        SendToW,
924
        SendToW
925
    },
926
    { /* 0x0a - CSIDL_BITBUCKET - Recycle Bin */
927
        &FOLDERID_RecycleBinFolder,
928 929 930
        CSIDL_Type_Disallowed,
        NULL,
        NULL,
931
    },
932
    { /* 0x0b - CSIDL_STARTMENU */
933
        &FOLDERID_StartMenu,
934 935
        CSIDL_Type_User,
        Start_MenuW,
936
        Start_MenuW
937
    },
938
    { /* 0x0c - CSIDL_MYDOCUMENTS */
939
        &GUID_NULL,
940 941 942
        CSIDL_Type_Disallowed, /* matches WinXP--can't get its path */
        NULL,
        NULL
943
    },
944
    { /* 0x0d - CSIDL_MYMUSIC */
945
        &FOLDERID_Music,
946 947 948
        CSIDL_Type_User,
        My_MusicW,
        MAKEINTRESOURCEW(IDS_MYMUSIC)
949
    },
950
    { /* 0x0e - CSIDL_MYVIDEO */
951
        &FOLDERID_Videos,
952
        CSIDL_Type_User,
953 954
        My_VideosW,
        MAKEINTRESOURCEW(IDS_MYVIDEOS)
955
    },
956
    { /* 0x0f - unassigned */
957
        &GUID_NULL,
958 959 960
        CSIDL_Type_Disallowed,
        NULL,
        NULL,
961
    },
962
    { /* 0x10 - CSIDL_DESKTOPDIRECTORY */
963
        &FOLDERID_Desktop,
964 965 966
        CSIDL_Type_User,
        DesktopW,
        MAKEINTRESOURCEW(IDS_DESKTOPDIRECTORY)
967
    },
968
    { /* 0x11 - CSIDL_DRIVES */
969
        &FOLDERID_ComputerFolder,
970 971 972
        CSIDL_Type_Disallowed,
        NULL,
        NULL,
973
    },
974
    { /* 0x12 - CSIDL_NETWORK */
975
        &FOLDERID_NetworkFolder,
976 977 978
        CSIDL_Type_Disallowed,
        NULL,
        NULL,
979
    },
980
    { /* 0x13 - CSIDL_NETHOOD */
981
        &FOLDERID_NetHood,
982 983
        CSIDL_Type_User,
        NetHoodW,
984
        NetHoodW
985
    },
986
    { /* 0x14 - CSIDL_FONTS */
987
        &FOLDERID_Fonts,
988
        CSIDL_Type_WindowsPath,
989
        FontsW,
990
        FontsW
991
    },
992
    { /* 0x15 - CSIDL_TEMPLATES */
993
        &FOLDERID_Templates,
994 995
        CSIDL_Type_User,
        TemplatesW,
996
        TemplatesW
997
    },
998
    { /* 0x16 - CSIDL_COMMON_STARTMENU */
999
        &FOLDERID_CommonStartMenu,
1000 1001
        CSIDL_Type_AllUsers,
        Common_Start_MenuW,
1002
        Start_MenuW
1003
    },
1004
    { /* 0x17 - CSIDL_COMMON_PROGRAMS */
1005
        &FOLDERID_CommonPrograms,
1006 1007
        CSIDL_Type_AllUsers,
        Common_ProgramsW,
1008
        Start_Menu_ProgramsW
1009
    },
1010
    { /* 0x18 - CSIDL_COMMON_STARTUP */
1011
        &FOLDERID_CommonStartup,
1012
        CSIDL_Type_AllUsers,
1013
        Common_StartUpW,
1014
        Start_Menu_StartupW
1015
    },
1016
    { /* 0x19 - CSIDL_COMMON_DESKTOPDIRECTORY */
1017
        &FOLDERID_PublicDesktop,
1018 1019
        CSIDL_Type_AllUsers,
        Common_DesktopW,
1020
        MAKEINTRESOURCEW(IDS_DESKTOPDIRECTORY)
1021
    },
1022
    { /* 0x1a - CSIDL_APPDATA */
1023
        &FOLDERID_RoamingAppData,
1024 1025
        CSIDL_Type_User,
        AppDataW,
1026
        Application_DataW
1027
    },
1028
    { /* 0x1b - CSIDL_PRINTHOOD */
1029
        &FOLDERID_PrintHood,
1030 1031
        CSIDL_Type_User,
        PrintHoodW,
1032
        PrintHoodW
1033
    },
1034
    { /* 0x1c - CSIDL_LOCAL_APPDATA */
1035
        &FOLDERID_LocalAppData,
1036 1037
        CSIDL_Type_User,
        Local_AppDataW,
1038
        Local_Settings_Application_DataW
1039
    },
1040
    { /* 0x1d - CSIDL_ALTSTARTUP */
1041
        &GUID_NULL,
1042 1043 1044
        CSIDL_Type_NonExistent,
        NULL,
        NULL
1045
    },
1046
    { /* 0x1e - CSIDL_COMMON_ALTSTARTUP */
1047
        &GUID_NULL,
1048 1049 1050
        CSIDL_Type_NonExistent,
        NULL,
        NULL
1051
    },
1052
    { /* 0x1f - CSIDL_COMMON_FAVORITES */
1053
        &FOLDERID_Favorites,
1054
        CSIDL_Type_AllUsers,
1055
        Common_FavoritesW,
1056
        FavoritesW
1057
    },
1058
    { /* 0x20 - CSIDL_INTERNET_CACHE */
1059
        &FOLDERID_InternetCache,
1060 1061
        CSIDL_Type_User,
        CacheW,
1062
        Local_Settings_Temporary_Internet_FilesW
1063
    },
1064
    { /* 0x21 - CSIDL_COOKIES */
1065
        &FOLDERID_Cookies,
1066 1067
        CSIDL_Type_User,
        CookiesW,
1068
        CookiesW
1069
    },
1070
    { /* 0x22 - CSIDL_HISTORY */
1071
        &FOLDERID_History,
1072 1073
        CSIDL_Type_User,
        HistoryW,
1074
        Local_Settings_HistoryW
1075
    },
1076
    { /* 0x23 - CSIDL_COMMON_APPDATA */
1077
        &FOLDERID_ProgramData,
1078 1079
        CSIDL_Type_AllUsers,
        Common_AppDataW,
1080
        Application_DataW
1081
    },
1082
    { /* 0x24 - CSIDL_WINDOWS */
1083
        &FOLDERID_Windows,
1084 1085 1086
        CSIDL_Type_WindowsPath,
        NULL,
        NULL
1087
    },
1088
    { /* 0x25 - CSIDL_SYSTEM */
1089
        &FOLDERID_System,
1090 1091 1092
        CSIDL_Type_SystemPath,
        NULL,
        NULL
1093
    },
1094
    { /* 0x26 - CSIDL_PROGRAM_FILES */
1095
        &FOLDERID_ProgramFiles,
1096 1097
        CSIDL_Type_CurrVer,
        ProgramFilesDirW,
1098
        Program_FilesW
1099
    },
1100
    { /* 0x27 - CSIDL_MYPICTURES */
1101
        &FOLDERID_Pictures,
1102 1103 1104
        CSIDL_Type_User,
        My_PicturesW,
        MAKEINTRESOURCEW(IDS_MYPICTURES)
1105
    },
1106
    { /* 0x28 - CSIDL_PROFILE */
1107
        &FOLDERID_Profile,
1108 1109 1110
        CSIDL_Type_User,
        NULL,
        NULL
1111
    },
1112
    { /* 0x29 - CSIDL_SYSTEMX86 */
1113
        &FOLDERID_SystemX86,
1114
        CSIDL_Type_SystemX86Path,
1115 1116
        NULL,
        NULL
1117
    },
1118
    { /* 0x2a - CSIDL_PROGRAM_FILESX86 */
1119
        &FOLDERID_ProgramFilesX86,
1120 1121
        CSIDL_Type_CurrVer,
        ProgramFilesDirX86W,
1122
        Program_Files_x86W
1123
    },
1124
    { /* 0x2b - CSIDL_PROGRAM_FILES_COMMON */
1125
        &FOLDERID_ProgramFilesCommon,
1126 1127
        CSIDL_Type_CurrVer,
        CommonFilesDirW,
1128
        Program_Files_Common_FilesW
1129
    },
1130
    { /* 0x2c - CSIDL_PROGRAM_FILES_COMMONX86 */
1131
        &FOLDERID_ProgramFilesCommonX86,
1132 1133
        CSIDL_Type_CurrVer,
        CommonFilesDirX86W,
1134
        Program_Files_x86_Common_FilesW
1135
    },
1136
    { /* 0x2d - CSIDL_COMMON_TEMPLATES */
1137
        &FOLDERID_CommonTemplates,
1138 1139
        CSIDL_Type_AllUsers,
        Common_TemplatesW,
1140
        TemplatesW
1141
    },
1142
    { /* 0x2e - CSIDL_COMMON_DOCUMENTS */
1143
        &FOLDERID_PublicDocuments,
1144 1145
        CSIDL_Type_AllUsers,
        Common_DocumentsW,
1146
        DocumentsW
1147
    },
1148
    { /* 0x2f - CSIDL_COMMON_ADMINTOOLS */
1149
        &FOLDERID_CommonAdminTools,
1150 1151
        CSIDL_Type_AllUsers,
        Common_Administrative_ToolsW,
1152
        Start_Menu_Admin_ToolsW
1153
    },
1154
    { /* 0x30 - CSIDL_ADMINTOOLS */
1155
        &FOLDERID_AdminTools,
1156 1157
        CSIDL_Type_User,
        Administrative_ToolsW,
1158
        Start_Menu_Admin_ToolsW
1159
    },
1160
    { /* 0x31 - CSIDL_CONNECTIONS */
1161
        &FOLDERID_ConnectionsFolder,
1162 1163 1164
        CSIDL_Type_Disallowed,
        NULL,
        NULL
1165
    },
1166
    { /* 0x32 - unassigned */
1167
        &GUID_NULL,
1168 1169 1170
        CSIDL_Type_Disallowed,
        NULL,
        NULL
1171
    },
1172
    { /* 0x33 - unassigned */
1173
        &GUID_NULL,
1174 1175 1176
        CSIDL_Type_Disallowed,
        NULL,
        NULL
1177
    },
1178
    { /* 0x34 - unassigned */
1179
        &GUID_NULL,
1180 1181 1182
        CSIDL_Type_Disallowed,
        NULL,
        NULL
1183
    },
1184
    { /* 0x35 - CSIDL_COMMON_MUSIC */
1185
        &FOLDERID_PublicMusic,
1186 1187
        CSIDL_Type_AllUsers,
        CommonMusicW,
1188
        MusicW
1189
    },
1190
    { /* 0x36 - CSIDL_COMMON_PICTURES */
1191
        &FOLDERID_PublicPictures,
1192 1193
        CSIDL_Type_AllUsers,
        CommonPicturesW,
1194
        PicturesW
1195
    },
1196
    { /* 0x37 - CSIDL_COMMON_VIDEO */
1197
        &FOLDERID_PublicVideos,
1198 1199
        CSIDL_Type_AllUsers,
        CommonVideoW,
1200
        VideosW
1201
    },
1202
    { /* 0x38 - CSIDL_RESOURCES */
1203
        &FOLDERID_ResourceDir,
1204 1205 1206
        CSIDL_Type_WindowsPath,
        NULL,
        ResourcesW
1207
    },
1208
    { /* 0x39 - CSIDL_RESOURCES_LOCALIZED */
1209
        &FOLDERID_LocalizedResourcesDir,
1210 1211 1212
        CSIDL_Type_NonExistent,
        NULL,
        NULL
1213
    },
1214
    { /* 0x3a - CSIDL_COMMON_OEM_LINKS */
1215 1216
        &FOLDERID_CommonOEMLinks,
        CSIDL_Type_AllUsers,
1217
        NULL,
1218
        OEM_LinksW
1219
    },
1220
    { /* 0x3b - CSIDL_CDBURN_AREA */
1221
        &FOLDERID_CDBurning,
1222 1223
        CSIDL_Type_User,
        CD_BurningW,
1224
        Local_Settings_CD_BurningW
1225
    },
1226
    { /* 0x3c unassigned */
1227
        &GUID_NULL,
1228 1229 1230
        CSIDL_Type_Disallowed,
        NULL,
        NULL
1231
    },
1232
    { /* 0x3d - CSIDL_COMPUTERSNEARME */
1233
        &GUID_NULL,
1234 1235 1236
        CSIDL_Type_Disallowed, /* FIXME */
        NULL,
        NULL
1237
    },
1238
    { /* 0x3e - CSIDL_PROFILES */
1239
        &GUID_NULL,
1240 1241 1242
        CSIDL_Type_Disallowed, /* oddly, this matches WinXP */
        NULL,
        NULL
1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271
    },
    { /* 0x3f */
        &FOLDERID_AddNewPrograms,
        CSIDL_Type_Disallowed,
        NULL,
        NULL
    },
    { /* 0x40 */
        &FOLDERID_AppUpdates,
        CSIDL_Type_Disallowed,
        NULL,
        NULL
    },
    { /* 0x41 */
        &FOLDERID_ChangeRemovePrograms,
        CSIDL_Type_Disallowed,
        NULL,
        NULL
    },
    { /* 0x42 */
        &FOLDERID_ConflictFolder,
        CSIDL_Type_Disallowed,
        NULL,
        NULL
    },
    { /* 0x43 */
        &FOLDERID_Contacts,
        CSIDL_Type_User,
        ContactsW,
1272
        ContactsW
1273 1274 1275 1276 1277 1278 1279 1280
    },
    { /* 0x44 */
        &FOLDERID_DeviceMetadataStore,
        CSIDL_Type_Disallowed, /* FIXME */
        NULL,
        NULL
    },
    { /* 0x45 */
1281
        &GUID_NULL,
1282 1283
        CSIDL_Type_User,
        NULL,
1284
        DocumentsW
1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295
    },
    { /* 0x46 */
        &FOLDERID_DocumentsLibrary,
        CSIDL_Type_Disallowed, /* FIXME */
        NULL,
        NULL
    },
    { /* 0x47 */
        &FOLDERID_Downloads,
        CSIDL_Type_User,
        NULL,
1296
        DownloadsW
1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331
    },
    { /* 0x48 */
        &FOLDERID_Games,
        CSIDL_Type_Disallowed,
        NULL,
        NULL
    },
    { /* 0x49 */
        &FOLDERID_GameTasks,
        CSIDL_Type_Disallowed, /* FIXME */
        NULL,
        NULL
    },
    { /* 0x4a */
        &FOLDERID_HomeGroup,
        CSIDL_Type_Disallowed,
        NULL,
        NULL
    },
    { /* 0x4b */
        &FOLDERID_ImplicitAppShortcuts,
        CSIDL_Type_Disallowed, /* FIXME */
        NULL,
        NULL
    },
    { /* 0x4c */
        &FOLDERID_Libraries,
        CSIDL_Type_Disallowed, /* FIXME */
        NULL,
        NULL
    },
    { /* 0x4d */
        &FOLDERID_Links,
        CSIDL_Type_User,
        NULL,
1332
        LinksW
1333 1334 1335
    },
    { /* 0x4e */
        &FOLDERID_LocalAppDataLow,
1336
        CSIDL_Type_User,
1337
        NULL,
1338
        AppData_LocalLowW
1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355
    },
    { /* 0x4f */
        &FOLDERID_MusicLibrary,
        CSIDL_Type_Disallowed, /* FIXME */
        NULL,
        NULL
    },
    { /* 0x50 */
        &FOLDERID_OriginalImages,
        CSIDL_Type_Disallowed, /* FIXME */
        NULL,
        NULL
    },
    { /* 0x51 */
        &FOLDERID_PhotoAlbums,
        CSIDL_Type_User,
        NULL,
1356
        Pictures_Slide_ShowsW
1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367
    },
    { /* 0x52 */
        &FOLDERID_PicturesLibrary,
        CSIDL_Type_Disallowed, /* FIXME */
        NULL,
        NULL
    },
    { /* 0x53 */
        &FOLDERID_Playlists,
        CSIDL_Type_User,
        NULL,
1368
        Music_PlaylistsW
1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391
    },
    { /* 0x54 */
        &FOLDERID_ProgramFilesX64,
        CSIDL_Type_NonExistent,
        NULL,
        NULL
    },
    { /* 0x55 */
        &FOLDERID_ProgramFilesCommonX64,
        CSIDL_Type_NonExistent,
        NULL,
        NULL
    },
    { /* 0x56 */
        &FOLDERID_Public,
        CSIDL_Type_CurrVer, /* FIXME */
        NULL,
        UsersPublicW
    },
    { /* 0x57 */
        &FOLDERID_PublicDownloads,
        CSIDL_Type_AllUsers,
        NULL,
1392
        DownloadsW
1393 1394 1395 1396 1397
    },
    { /* 0x58 */
        &FOLDERID_PublicGameTasks,
        CSIDL_Type_AllUsers,
        NULL,
1398
        Microsoft_Windows_GameExplorerW
1399 1400 1401 1402 1403
    },
    { /* 0x59 */
        &FOLDERID_PublicLibraries,
        CSIDL_Type_AllUsers,
        NULL,
1404
        Microsoft_Windows_LibrariesW
1405 1406 1407 1408 1409
    },
    { /* 0x5a */
        &FOLDERID_PublicRingtones,
        CSIDL_Type_AllUsers,
        NULL,
1410
        Microsoft_Windows_RingtonesW
1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433
    },
    { /* 0x5b */
        &FOLDERID_QuickLaunch,
        CSIDL_Type_Disallowed, /* FIXME */
        NULL,
        NULL
    },
    { /* 0x5c */
        &FOLDERID_RecordedTVLibrary,
        CSIDL_Type_Disallowed, /* FIXME */
        NULL,
        NULL
    },
    { /* 0x5d */
        &FOLDERID_Ringtones,
        CSIDL_Type_Disallowed, /* FIXME */
        NULL,
        NULL
    },
    { /* 0x5e */
        &FOLDERID_SampleMusic,
        CSIDL_Type_AllUsers,
        NULL,
1434
        Music_Sample_MusicW
1435 1436 1437 1438 1439
    },
    { /* 0x5f */
        &FOLDERID_SamplePictures,
        CSIDL_Type_AllUsers,
        NULL,
1440
        Pictures_Sample_PicturesW
1441 1442 1443 1444 1445
    },
    { /* 0x60 */
        &FOLDERID_SamplePlaylists,
        CSIDL_Type_AllUsers,
        NULL,
1446
        Music_Sample_PlaylistsW
1447 1448 1449 1450 1451
    },
    { /* 0x61 */
        &FOLDERID_SampleVideos,
        CSIDL_Type_AllUsers,
        NULL,
1452
        Videos_Sample_VideosW
1453 1454 1455 1456 1457
    },
    { /* 0x62 */
        &FOLDERID_SavedGames,
        CSIDL_Type_User,
        NULL,
1458
        Saved_GamesW
1459 1460 1461 1462 1463
    },
    { /* 0x63 */
        &FOLDERID_SavedSearches,
        CSIDL_Type_User,
        NULL,
1464
        SearchesW
1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523
    },
    { /* 0x64 */
        &FOLDERID_SEARCH_CSC,
        CSIDL_Type_Disallowed,
        NULL,
        NULL
    },
    { /* 0x65 */
        &FOLDERID_SEARCH_MAPI,
        CSIDL_Type_Disallowed,
        NULL,
        NULL
    },
    { /* 0x66 */
        &FOLDERID_SearchHome,
        CSIDL_Type_Disallowed,
        NULL,
        NULL
    },
    { /* 0x67 */
        &FOLDERID_SidebarDefaultParts,
        CSIDL_Type_Disallowed, /* FIXME */
        NULL,
        NULL
    },
    { /* 0x68 */
        &FOLDERID_SidebarParts,
        CSIDL_Type_Disallowed, /* FIXME */
        NULL,
        NULL
    },
    { /* 0x69 */
        &FOLDERID_SyncManagerFolder,
        CSIDL_Type_Disallowed,
        NULL,
        NULL
    },
    { /* 0x6a */
        &FOLDERID_SyncResultsFolder,
        CSIDL_Type_Disallowed,
        NULL,
        NULL
    },
    { /* 0x6b */
        &FOLDERID_SyncSetupFolder,
        CSIDL_Type_Disallowed,
        NULL,
        NULL
    },
    { /* 0x6c */
        &FOLDERID_UserPinned,
        CSIDL_Type_Disallowed, /* FIXME */
        NULL,
        NULL
    },
    { /* 0x6d */
        &FOLDERID_UserProfiles,
        CSIDL_Type_CurrVer,
        UsersW,
1524
        UsersW
1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554
    },
    { /* 0x6e */
        &FOLDERID_UserProgramFiles,
        CSIDL_Type_Disallowed, /* FIXME */
        NULL,
        NULL
    },
    { /* 0x6f */
        &FOLDERID_UserProgramFilesCommon,
        CSIDL_Type_Disallowed, /* FIXME */
        NULL,
        NULL
    },
    { /* 0x70 */
        &FOLDERID_UsersFiles,
        CSIDL_Type_Disallowed,
        NULL,
        NULL
    },
    { /* 0x71 */
        &FOLDERID_UsersLibraries,
        CSIDL_Type_Disallowed,
        NULL,
        NULL
    },
    { /* 0x72 */
        &FOLDERID_VideosLibrary,
        CSIDL_Type_Disallowed, /* FIXME */
        NULL,
        NULL
1555 1556 1557
    }
};

1558
static HRESULT _SHExpandEnvironmentStrings(LPCWSTR szSrc, LPWSTR szDest);
1559

1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570
/* Gets the value named value from the registry key
 * rootKey\Software\Microsoft\Windows\CurrentVersion\Explorer\User Shell Folders
 * (or from rootKey\userPrefix\... if userPrefix is not NULL) into path, which
 * is assumed to be MAX_PATH WCHARs in length.
 * If it exists, expands the value and writes the expanded value to
 * rootKey\Software\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders
 * Returns successful error code if the value was retrieved from the registry,
 * and a failure otherwise.
 */
static HRESULT _SHGetUserShellFolderPath(HKEY rootKey, LPCWSTR userPrefix,
 LPCWSTR value, LPWSTR path)
1571
{
1572 1573 1574
    HRESULT hr;
    WCHAR shellFolderPath[MAX_PATH], userShellFolderPath[MAX_PATH];
    LPCWSTR pShellFolderPath, pUserShellFolderPath;
1575
    DWORD dwType, dwPathLen = MAX_PATH;
1576
    HKEY userShellFolderKey, shellFolderKey;
1577

1578 1579
    TRACE("%p,%s,%s,%p\n",rootKey, debugstr_w(userPrefix), debugstr_w(value),
     path);
1580

1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596
    if (userPrefix)
    {
        strcpyW(shellFolderPath, userPrefix);
        PathAddBackslashW(shellFolderPath);
        strcatW(shellFolderPath, szSHFolders);
        pShellFolderPath = shellFolderPath;
        strcpyW(userShellFolderPath, userPrefix);
        PathAddBackslashW(userShellFolderPath);
        strcatW(userShellFolderPath, szSHUserFolders);
        pUserShellFolderPath = userShellFolderPath;
    }
    else
    {
        pUserShellFolderPath = szSHUserFolders;
        pShellFolderPath = szSHFolders;
    }
Juan Lang's avatar
Juan Lang committed
1597

1598
    if (RegCreateKeyW(rootKey, pShellFolderPath, &shellFolderKey))
1599 1600 1601 1602
    {
        TRACE("Failed to create %s\n", debugstr_w(pShellFolderPath));
        return E_FAIL;
    }
1603
    if (RegCreateKeyW(rootKey, pUserShellFolderPath, &userShellFolderKey))
1604 1605 1606 1607 1608 1609
    {
        TRACE("Failed to create %s\n",
         debugstr_w(pUserShellFolderPath));
        RegCloseKey(shellFolderKey);
        return E_FAIL;
    }
1610

1611 1612 1613
    if (!RegQueryValueExW(userShellFolderKey, value, NULL, &dwType,
     (LPBYTE)path, &dwPathLen) && (dwType == REG_EXPAND_SZ || dwType == REG_SZ))
    {
1614 1615
        LONG ret;

1616
        path[dwPathLen / sizeof(WCHAR)] = '\0';
1617
        if (dwType == REG_EXPAND_SZ && path[0] == '%')
1618 1619
        {
            WCHAR szTemp[MAX_PATH];
1620

1621
            _SHExpandEnvironmentStrings(path, szTemp);
1622
            lstrcpynW(path, szTemp, MAX_PATH);
1623
        }
1624
        ret = RegSetValueExW(shellFolderKey, value, 0, REG_SZ, (LPBYTE)path,
1625
         (strlenW(path) + 1) * sizeof(WCHAR));
1626 1627 1628 1629
        if (ret != ERROR_SUCCESS)
            hr = HRESULT_FROM_WIN32(ret);
        else
            hr = S_OK;
1630 1631 1632 1633 1634
    }
    else
        hr = E_FAIL;
    RegCloseKey(shellFolderKey);
    RegCloseKey(userShellFolderKey);
1635
    TRACE("returning 0x%08x\n", hr);
1636 1637
    return hr;
}
1638

1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656
/* Gets a 'semi-expanded' default value of the CSIDL with index folder into
 * pszPath, based on the entries in CSIDL_Data.  By semi-expanded, I mean:
 * - The entry's szDefaultPath may be either a string value or an integer
 *   resource identifier.  In the latter case, the string value of the resource
 *   is written.
 * - Depending on the entry's type, the path may begin with an (unexpanded)
 *   environment variable name.  The caller is responsible for expanding
 *   environment strings if so desired.
 *   The types that are prepended with environment variables are:
 *   CSIDL_Type_User:     %USERPROFILE%
 *   CSIDL_Type_AllUsers: %ALLUSERSPROFILE%
 *   CSIDL_Type_CurrVer:  %SystemDrive%
 *   (Others might make sense too, but as yet are unneeded.)
 */
static HRESULT _SHGetDefaultValue(BYTE folder, LPWSTR pszPath)
{
    HRESULT hr;
    WCHAR resourcePath[MAX_PATH];
1657
    LPCWSTR pDefaultPath = NULL;
Juergen Schmied's avatar
Juergen Schmied committed
1658

1659
    TRACE("0x%02x,%p\n", folder, pszPath);
Juergen Schmied's avatar
Juergen Schmied committed
1660

1661 1662 1663 1664
    if (folder >= sizeof(CSIDL_Data) / sizeof(CSIDL_Data[0]))
        return E_INVALIDARG;
    if (!pszPath)
        return E_INVALIDARG;
Juergen Schmied's avatar
Juergen Schmied committed
1665

1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684
    if (!is_win64)
    {
        BOOL is_wow64;

        switch (folder)
        {
        case CSIDL_PROGRAM_FILES:
        case CSIDL_PROGRAM_FILESX86:
            IsWow64Process( GetCurrentProcess(), &is_wow64 );
            folder = is_wow64 ? CSIDL_PROGRAM_FILESX86 : CSIDL_PROGRAM_FILES;
            break;
        case CSIDL_PROGRAM_FILES_COMMON:
        case CSIDL_PROGRAM_FILES_COMMONX86:
            IsWow64Process( GetCurrentProcess(), &is_wow64 );
            folder = is_wow64 ? CSIDL_PROGRAM_FILES_COMMONX86 : CSIDL_PROGRAM_FILES_COMMON;
            break;
        }
    }

1685 1686 1687 1688
    if (CSIDL_Data[folder].szDefaultPath &&
     IS_INTRESOURCE(CSIDL_Data[folder].szDefaultPath))
    {
        if (LoadStringW(shell32_hInstance,
Kevin Koltzau's avatar
Kevin Koltzau committed
1689
         LOWORD(CSIDL_Data[folder].szDefaultPath), resourcePath, MAX_PATH))
1690 1691 1692 1693 1694 1695
        {
            hr = S_OK;
            pDefaultPath = resourcePath;
        }
        else
        {
1696 1697
            FIXME("(%d,%s), LoadString failed, missing translation?\n", folder,
             debugstr_w(pszPath));
1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727
            hr = E_FAIL;
        }
    }
    else
    {
        hr = S_OK;
        pDefaultPath = CSIDL_Data[folder].szDefaultPath;
    }
    if (SUCCEEDED(hr))
    {
        switch (CSIDL_Data[folder].type)
        {
            case CSIDL_Type_User:
                strcpyW(pszPath, UserProfileW);
                break;
            case CSIDL_Type_AllUsers:
                strcpyW(pszPath, AllUsersProfileW);
                break;
            case CSIDL_Type_CurrVer:
                strcpyW(pszPath, SystemDriveW);
                break;
            default:
                ; /* no corresponding env. var, do nothing */
        }
        if (pDefaultPath)
        {
            PathAddBackslashW(pszPath);
            strcatW(pszPath, pDefaultPath);
        }
    }
1728
    TRACE("returning 0x%08x\n", hr);
1729 1730
    return hr;
}
1731

1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742
/* Gets the (unexpanded) value of the folder with index folder into pszPath.
 * The folder's type is assumed to be CSIDL_Type_CurrVer.  Its default value
 * can be overridden in the HKLM\\szCurrentVersion key.
 * If dwFlags has SHGFP_TYPE_DEFAULT set or if the value isn't overridden in
 * the registry, uses _SHGetDefaultValue to get the value.
 */
static HRESULT _SHGetCurrentVersionPath(DWORD dwFlags, BYTE folder,
 LPWSTR pszPath)
{
    HRESULT hr;

1743
    TRACE("0x%08x,0x%02x,%p\n", dwFlags, folder, pszPath);
1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757

    if (folder >= sizeof(CSIDL_Data) / sizeof(CSIDL_Data[0]))
        return E_INVALIDARG;
    if (CSIDL_Data[folder].type != CSIDL_Type_CurrVer)
        return E_INVALIDARG;
    if (!pszPath)
        return E_INVALIDARG;

    if (dwFlags & SHGFP_TYPE_DEFAULT)
        hr = _SHGetDefaultValue(folder, pszPath);
    else
    {
        HKEY hKey;

1758
        if (RegCreateKeyW(HKEY_LOCAL_MACHINE, szCurrentVersion, &hKey))
1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769
            hr = E_FAIL;
        else
        {
            DWORD dwType, dwPathLen = MAX_PATH * sizeof(WCHAR);

            if (RegQueryValueExW(hKey, CSIDL_Data[folder].szValueName, NULL,
             &dwType, (LPBYTE)pszPath, &dwPathLen) ||
             (dwType != REG_SZ && dwType != REG_EXPAND_SZ))
            {
                hr = _SHGetDefaultValue(folder, pszPath);
                dwType = REG_EXPAND_SZ;
1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785
                switch (folder)
                {
                case CSIDL_PROGRAM_FILESX86:
                case CSIDL_PROGRAM_FILES_COMMONX86:
                    /* these two should never be set on 32-bit setups */
                    if (!is_win64)
                    {
                        BOOL is_wow64;
                        IsWow64Process( GetCurrentProcess(), &is_wow64 );
                        if (!is_wow64) break;
                    }
                    /* fall through */
                default:
                    RegSetValueExW(hKey, CSIDL_Data[folder].szValueName, 0, dwType,
                                   (LPBYTE)pszPath, (strlenW(pszPath)+1)*sizeof(WCHAR));
                }
1786 1787 1788 1789 1790 1791 1792 1793 1794
            }
            else
            {
                pszPath[dwPathLen / sizeof(WCHAR)] = '\0';
                hr = S_OK;
            }
            RegCloseKey(hKey);
        }
    }
1795
    TRACE("returning 0x%08x (output path is %s)\n", hr, debugstr_w(pszPath));
1796 1797 1798
    return hr;
}

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
static LPWSTR _GetUserSidStringFromToken(HANDLE Token)
{
    char InfoBuffer[64];
    PTOKEN_USER UserInfo;
    DWORD InfoSize;
    LPWSTR SidStr;

    UserInfo = (PTOKEN_USER) InfoBuffer;
    if (! GetTokenInformation(Token, TokenUser, InfoBuffer, sizeof(InfoBuffer),
                              &InfoSize))
    {
        if (GetLastError() != ERROR_INSUFFICIENT_BUFFER)
            return NULL;
        UserInfo = HeapAlloc(GetProcessHeap(), 0, InfoSize);
        if (UserInfo == NULL)
            return NULL;
        if (! GetTokenInformation(Token, TokenUser, UserInfo, InfoSize,
                                  &InfoSize))
        {
            HeapFree(GetProcessHeap(), 0, UserInfo);
            return NULL;
        }
    }

    if (! ConvertSidToStringSidW(UserInfo->User.Sid, &SidStr))
        SidStr = NULL;

    if (UserInfo != (PTOKEN_USER) InfoBuffer)
        HeapFree(GetProcessHeap(), 0, UserInfo);

    return SidStr;
}

1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844
/* Gets the user's path (unexpanded) for the CSIDL with index folder:
 * If SHGFP_TYPE_DEFAULT is set, calls _SHGetDefaultValue for it.  Otherwise
 * calls _SHGetUserShellFolderPath for it.  Where it looks depends on hToken:
 * - if hToken is -1, looks in HKEY_USERS\.Default
 * - otherwise looks first in HKEY_CURRENT_USER, followed by HKEY_LOCAL_MACHINE
 *   if HKEY_CURRENT_USER doesn't contain any entries.  If both fail, finally
 *   calls _SHGetDefaultValue for it.
 */
static HRESULT _SHGetUserProfilePath(HANDLE hToken, DWORD dwFlags, BYTE folder,
 LPWSTR pszPath)
{
    HRESULT hr;

1845
    TRACE("%p,0x%08x,0x%02x,%p\n", hToken, dwFlags, folder, pszPath);
1846 1847 1848 1849 1850 1851 1852 1853 1854

    if (folder >= sizeof(CSIDL_Data) / sizeof(CSIDL_Data[0]))
        return E_INVALIDARG;
    if (CSIDL_Data[folder].type != CSIDL_Type_User)
        return E_INVALIDARG;
    if (!pszPath)
        return E_INVALIDARG;

    if (dwFlags & SHGFP_TYPE_DEFAULT)
1855 1856 1857 1858 1859 1860
    {
        if (hToken != NULL && hToken != (HANDLE)-1)
        {
            FIXME("unsupported for user other than current or default\n");
            return E_FAIL;
        }
1861
        hr = _SHGetDefaultValue(folder, pszPath);
1862
    }
1863 1864 1865 1866 1867 1868 1869 1870 1871 1872
    else
    {
        LPCWSTR userPrefix = NULL;
        HKEY hRootKey;

        if (hToken == (HANDLE)-1)
        {
            hRootKey = HKEY_USERS;
            userPrefix = DefaultW;
        }
1873
        else if (hToken == NULL)
1874
            hRootKey = HKEY_CURRENT_USER;
1875 1876 1877 1878 1879 1880 1881 1882 1883 1884
        else
        {
            hRootKey = HKEY_USERS;
            userPrefix = _GetUserSidStringFromToken(hToken);
            if (userPrefix == NULL)
            {
                hr = E_FAIL;
                goto error;
            }
        }
1885 1886 1887 1888 1889 1890 1891
        hr = _SHGetUserShellFolderPath(hRootKey, userPrefix,
         CSIDL_Data[folder].szValueName, pszPath);
        if (FAILED(hr) && hRootKey != HKEY_LOCAL_MACHINE)
            hr = _SHGetUserShellFolderPath(HKEY_LOCAL_MACHINE, NULL,
             CSIDL_Data[folder].szValueName, pszPath);
        if (FAILED(hr))
            hr = _SHGetDefaultValue(folder, pszPath);
1892 1893
        if (userPrefix != NULL && userPrefix != DefaultW)
            LocalFree((HLOCAL) userPrefix);
1894
    }
1895
error:
1896
    TRACE("returning 0x%08x (output path is %s)\n", hr, debugstr_w(pszPath));
1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909
    return hr;
}

/* Gets the (unexpanded) path for the CSIDL with index folder.  If dwFlags has
 * SHGFP_TYPE_DEFAULT set, calls _SHGetDefaultValue.  Otherwise calls
 * _SHGetUserShellFolderPath for it, looking only in HKEY_LOCAL_MACHINE.
 * If this fails, falls back to _SHGetDefaultValue.
 */
static HRESULT _SHGetAllUsersProfilePath(DWORD dwFlags, BYTE folder,
 LPWSTR pszPath)
{
    HRESULT hr;

1910
    TRACE("0x%08x,0x%02x,%p\n", dwFlags, folder, pszPath);
1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927

    if (folder >= sizeof(CSIDL_Data) / sizeof(CSIDL_Data[0]))
        return E_INVALIDARG;
    if (CSIDL_Data[folder].type != CSIDL_Type_AllUsers)
        return E_INVALIDARG;
    if (!pszPath)
        return E_INVALIDARG;

    if (dwFlags & SHGFP_TYPE_DEFAULT)
        hr = _SHGetDefaultValue(folder, pszPath);
    else
    {
        hr = _SHGetUserShellFolderPath(HKEY_LOCAL_MACHINE, NULL,
         CSIDL_Data[folder].szValueName, pszPath);
        if (FAILED(hr))
            hr = _SHGetDefaultValue(folder, pszPath);
    }
1928
    TRACE("returning 0x%08x (output path is %s)\n", hr, debugstr_w(pszPath));
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
    return hr;
}

static HRESULT _SHOpenProfilesKey(PHKEY pKey)
{
    LONG lRet;
    DWORD disp;

    lRet = RegCreateKeyExW(HKEY_LOCAL_MACHINE, ProfileListW, 0, NULL, 0,
     KEY_ALL_ACCESS, NULL, pKey, &disp);
    return HRESULT_FROM_WIN32(lRet);
}

/* Reads the value named szValueName from the key profilesKey (assumed to be
 * opened by _SHOpenProfilesKey) into szValue, which is assumed to be MAX_PATH
 * WCHARs in length.  If it doesn't exist, returns szDefault (and saves
 * szDefault to the registry).
 */
static HRESULT _SHGetProfilesValue(HKEY profilesKey, LPCWSTR szValueName,
 LPWSTR szValue, LPCWSTR szDefault)
{
    HRESULT hr;
    DWORD type, dwPathLen = MAX_PATH * sizeof(WCHAR);
    LONG lRet;

    TRACE("%p,%s,%p,%s\n", profilesKey, debugstr_w(szValueName), szValue,
     debugstr_w(szDefault));
    lRet = RegQueryValueExW(profilesKey, szValueName, NULL, &type,
     (LPBYTE)szValue, &dwPathLen);
    if (!lRet && (type == REG_SZ || type == REG_EXPAND_SZ) && dwPathLen
     && *szValue)
    {
        dwPathLen /= sizeof(WCHAR);
        szValue[dwPathLen] = '\0';
        hr = S_OK;
    }
    else
    {
        /* Missing or invalid value, set a default */
1968
        lstrcpynW(szValue, szDefault, MAX_PATH);
1969
        TRACE("Setting missing value %s to %s\n", debugstr_w(szValueName),
1970
                                                  debugstr_w(szValue));
1971
        lRet = RegSetValueExW(profilesKey, szValueName, 0, REG_EXPAND_SZ,
1972 1973
                              (LPBYTE)szValue,
                              (strlenW(szValue) + 1) * sizeof(WCHAR));
1974 1975 1976 1977 1978
        if (lRet)
            hr = HRESULT_FROM_WIN32(lRet);
        else
            hr = S_OK;
    }
1979
    TRACE("returning 0x%08x (output value is %s)\n", hr, debugstr_w(szValue));
1980 1981 1982
    return hr;
}

1983 1984 1985 1986 1987 1988
/* Attempts to expand environment variables from szSrc into szDest, which is
 * assumed to be MAX_PATH characters in length.  Before referring to the
 * environment, handles a few variables directly, because the environment
 * variables may not be set when this is called (as during Wine's installation
 * when default values are being written to the registry).
 * The directly handled environment variables, and their source, are:
1989 1990 1991
 * - ALLUSERSPROFILE, USERPROFILE: reads from the registry
 * - SystemDrive: uses GetSystemDirectoryW and uses the drive portion of its
 *   path
1992 1993
 * If one of the directly handled environment variables is expanded, only
 * expands a single variable, and only in the beginning of szSrc.
1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004
 */
static HRESULT _SHExpandEnvironmentStrings(LPCWSTR szSrc, LPWSTR szDest)
{
    HRESULT hr;
    WCHAR szTemp[MAX_PATH], szProfilesPrefix[MAX_PATH] = { 0 };
    HKEY key = NULL;

    TRACE("%s, %p\n", debugstr_w(szSrc), szDest);

    if (!szSrc || !szDest) return E_INVALIDARG;

2005 2006 2007 2008 2009 2010 2011
    /* short-circuit if there's nothing to expand */
    if (szSrc[0] != '%')
    {
        strcpyW(szDest, szSrc);
        hr = S_OK;
        goto end;
    }
2012 2013 2014 2015
    /* Get the profile prefix, we'll probably be needing it */
    hr = _SHOpenProfilesKey(&key);
    if (SUCCEEDED(hr))
    {
2016 2017 2018 2019 2020 2021
        WCHAR def_val[MAX_PATH];

        /* get the system drive */
        GetSystemDirectoryW(def_val, MAX_PATH);
        if (def_val[1] == ':') strcpyW( def_val + 3, szDefaultProfileDirW );
        else FIXME("non-drive system paths unsupported\n");
2022

2023
        hr = _SHGetProfilesValue(key, ProfilesDirectoryW, szProfilesPrefix, def_val );
2024 2025 2026 2027 2028 2029 2030 2031 2032
    }

    *szDest = 0;
    strcpyW(szTemp, szSrc);
    while (SUCCEEDED(hr) && szTemp[0] == '%')
    {
        if (!strncmpiW(szTemp, AllUsersProfileW, strlenW(AllUsersProfileW)))
        {
            WCHAR szAllUsers[MAX_PATH];
2033

2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065
            strcpyW(szDest, szProfilesPrefix);
            hr = _SHGetProfilesValue(key, AllUsersProfileValueW,
             szAllUsers, AllUsersW);
            PathAppendW(szDest, szAllUsers);
            PathAppendW(szDest, szTemp + strlenW(AllUsersProfileW));
        }
        else if (!strncmpiW(szTemp, UserProfileW, strlenW(UserProfileW)))
        {
            WCHAR userName[MAX_PATH];
            DWORD userLen = MAX_PATH;

            strcpyW(szDest, szProfilesPrefix);
            GetUserNameW(userName, &userLen);
            PathAppendW(szDest, userName);
            PathAppendW(szDest, szTemp + strlenW(UserProfileW));
        }
        else if (!strncmpiW(szTemp, SystemDriveW, strlenW(SystemDriveW)))
        {
            GetSystemDirectoryW(szDest, MAX_PATH);
            if (szDest[1] != ':')
            {
                FIXME("non-drive system paths unsupported\n");
                hr = E_FAIL;
            }
            else
            {
                strcpyW(szDest + 3, szTemp + strlenW(SystemDriveW) + 1);
                hr = S_OK;
            }
        }
        else
        {
2066 2067 2068 2069 2070 2071 2072 2073
            DWORD ret = ExpandEnvironmentStringsW(szSrc, szDest, MAX_PATH);

            if (ret > MAX_PATH)
                hr = HRESULT_FROM_WIN32(ERROR_INSUFFICIENT_BUFFER);
            else if (ret == 0)
                hr = HRESULT_FROM_WIN32(GetLastError());
            else
                hr = S_OK;
2074 2075 2076 2077 2078 2079 2080 2081 2082
        }
        if (SUCCEEDED(hr) && szDest[0] == '%')
            strcpyW(szTemp, szDest);
        else
        {
            /* terminate loop */
            szTemp[0] = '\0';
        }
    }
2083
end:
2084 2085
    if (key)
        RegCloseKey(key);
2086
    TRACE("returning 0x%08x (input was %s, output is %s)\n", hr,
2087 2088 2089 2090 2091 2092 2093
     debugstr_w(szSrc), debugstr_w(szDest));
    return hr;
}

/*************************************************************************
 * SHGetFolderPathW			[SHELL32.@]
 *
2094 2095 2096 2097 2098 2099
 * Convert nFolder to path.  
 *
 * RETURNS
 *  Success: S_OK
 *  Failure: standard HRESULT error codes.
 *
2100
 * NOTES
2101
 * Most values can be overridden in either
2102 2103 2104 2105 2106 2107 2108
 * HKCU\Software\Microsoft\Windows\CurrentVersion\Explorer\User Shell Folders
 * or in the same location in HKLM.
 * The "Shell Folders" registry key was used in NT4 and earlier systems.
 * Beginning with Windows 2000, the "User Shell Folders" key is used, so
 * changes made to it are made to the former key too.  This synchronization is
 * done on-demand: not until someone requests the value of one of these paths
 * (by calling one of the SHGet functions) is the value synchronized.
2109
 * Furthermore, the HKCU paths take precedence over the HKLM paths.
2110
 */
2111
HRESULT WINAPI SHGetFolderPathW(
2112
	HWND hwndOwner,    /* [I] owner window */
2113
	int nFolder,       /* [I] CSIDL identifying the folder */
2114 2115 2116
	HANDLE hToken,     /* [I] access token */
	DWORD dwFlags,     /* [I] which path to return */
	LPWSTR pszPath)    /* [O] converted path */
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
{
    HRESULT hr =  SHGetFolderPathAndSubDirW(hwndOwner, nFolder, hToken, dwFlags, NULL, pszPath);
    if(HRESULT_FROM_WIN32(ERROR_PATH_NOT_FOUND) == hr)
        hr = HRESULT_FROM_WIN32(ERROR_FILE_NOT_FOUND);
    return hr;
}

HRESULT WINAPI SHGetFolderPathAndSubDirA(
	HWND hwndOwner,    /* [I] owner window */
	int nFolder,       /* [I] CSIDL identifying the folder */
	HANDLE hToken,     /* [I] access token */
	DWORD dwFlags,     /* [I] which path to return */
	LPCSTR pszSubPath, /* [I] sub directory of the specified folder */
	LPSTR pszPath)     /* [O] converted path */
{
    int length;
    HRESULT hr = S_OK;
    LPWSTR pszSubPathW = NULL;
    LPWSTR pszPathW = NULL;
    TRACE("%08x,%08x,%s\n",nFolder, dwFlags, debugstr_w(pszSubPathW));

    if(pszPath) {
        pszPathW = HeapAlloc(GetProcessHeap(), 0, MAX_PATH * sizeof(WCHAR));
        if(!pszPathW) {
            hr = HRESULT_FROM_WIN32(ERROR_NOT_ENOUGH_MEMORY);
            goto cleanup;
        }
    }
    TRACE("%08x,%08x,%s\n",nFolder, dwFlags, debugstr_w(pszSubPathW));

    /* SHGetFolderPathAndSubDirW does not distinguish if pszSubPath isn't
     * set (null), or an empty string.therefore call it without the parameter set
     * if pszSubPath is an empty string
     */
    if (pszSubPath && pszSubPath[0]) {
        length = MultiByteToWideChar(CP_ACP, 0, pszSubPath, -1, NULL, 0);
        pszSubPathW = HeapAlloc(GetProcessHeap(), 0, length * sizeof(WCHAR));
        if(!pszSubPathW) {
            hr = HRESULT_FROM_WIN32(ERROR_NOT_ENOUGH_MEMORY);
            goto cleanup;
        }
        MultiByteToWideChar(CP_ACP, 0, pszSubPath, -1, pszSubPathW, length);
    }

    hr = SHGetFolderPathAndSubDirW(hwndOwner, nFolder, hToken, dwFlags, pszSubPathW, pszPathW);

    if (SUCCEEDED(hr) && pszPath)
        WideCharToMultiByte(CP_ACP, 0, pszPathW, -1, pszPath, MAX_PATH, NULL, NULL);

cleanup:
    HeapFree(GetProcessHeap(), 0, pszPathW);
    HeapFree(GetProcessHeap(), 0, pszSubPathW);
    return hr;
}

2172 2173 2174
/*************************************************************************
 * SHGetFolderPathAndSubDirW		[SHELL32.@]
 */
2175 2176 2177 2178 2179 2180 2181
HRESULT WINAPI SHGetFolderPathAndSubDirW(
	HWND hwndOwner,    /* [I] owner window */
	int nFolder,       /* [I] CSIDL identifying the folder */
	HANDLE hToken,     /* [I] access token */
	DWORD dwFlags,     /* [I] which path to return */
	LPCWSTR pszSubPath,/* [I] sub directory of the specified folder */
	LPWSTR pszPath)    /* [O] converted path */
2182 2183 2184 2185 2186
{
    HRESULT    hr;
    WCHAR      szBuildPath[MAX_PATH], szTemp[MAX_PATH];
    DWORD      folder = nFolder & CSIDL_FOLDER_MASK;
    CSIDL_Type type;
2187 2188
    int        ret;
    
2189
    TRACE("%p,%p,nFolder=0x%04x,%s\n", hwndOwner,pszPath,nFolder,debugstr_w(pszSubPath));
2190 2191 2192 2193 2194 2195

    /* Windows always NULL-terminates the resulting path regardless of success
     * or failure, so do so first
     */
    if (pszPath)
        *pszPath = '\0';
2196

2197 2198
    if (folder >= sizeof(CSIDL_Data) / sizeof(CSIDL_Data[0]))
        return E_INVALIDARG;
2199 2200
    if ((SHGFP_TYPE_CURRENT != dwFlags) && (SHGFP_TYPE_DEFAULT != dwFlags))
        return E_INVALIDARG;
2201
    szTemp[0] = 0;
2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232
    type = CSIDL_Data[folder].type;
    switch (type)
    {
        case CSIDL_Type_Disallowed:
            hr = E_INVALIDARG;
            break;
        case CSIDL_Type_NonExistent:
            hr = S_FALSE;
            break;
        case CSIDL_Type_WindowsPath:
            GetWindowsDirectoryW(szTemp, MAX_PATH);
            if (CSIDL_Data[folder].szDefaultPath &&
             !IS_INTRESOURCE(CSIDL_Data[folder].szDefaultPath) &&
             *CSIDL_Data[folder].szDefaultPath)
            {
                PathAddBackslashW(szTemp);
                strcatW(szTemp, CSIDL_Data[folder].szDefaultPath);
            }
            hr = S_OK;
            break;
        case CSIDL_Type_SystemPath:
            GetSystemDirectoryW(szTemp, MAX_PATH);
            if (CSIDL_Data[folder].szDefaultPath &&
             !IS_INTRESOURCE(CSIDL_Data[folder].szDefaultPath) &&
             *CSIDL_Data[folder].szDefaultPath)
            {
                PathAddBackslashW(szTemp);
                strcatW(szTemp, CSIDL_Data[folder].szDefaultPath);
            }
            hr = S_OK;
            break;
2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243
        case CSIDL_Type_SystemX86Path:
            if (!GetSystemWow64DirectoryW(szTemp, MAX_PATH)) GetSystemDirectoryW(szTemp, MAX_PATH);
            if (CSIDL_Data[folder].szDefaultPath &&
             !IS_INTRESOURCE(CSIDL_Data[folder].szDefaultPath) &&
             *CSIDL_Data[folder].szDefaultPath)
            {
                PathAddBackslashW(szTemp);
                strcatW(szTemp, CSIDL_Data[folder].szDefaultPath);
            }
            hr = S_OK;
            break;
2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255
        case CSIDL_Type_CurrVer:
            hr = _SHGetCurrentVersionPath(dwFlags, folder, szTemp);
            break;
        case CSIDL_Type_User:
            hr = _SHGetUserProfilePath(hToken, dwFlags, folder, szTemp);
            break;
        case CSIDL_Type_AllUsers:
            hr = _SHGetAllUsersProfilePath(dwFlags, folder, szTemp);
            break;
        default:
            FIXME("bogus type %d, please fix\n", type);
            hr = E_INVALIDARG;
2256
            break;
2257 2258 2259 2260 2261 2262 2263
    }

    /* Expand environment strings if necessary */
    if (*szTemp == '%')
        hr = _SHExpandEnvironmentStrings(szTemp, szBuildPath);
    else
        strcpyW(szBuildPath, szTemp);
2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276

    if (FAILED(hr)) goto end;

    if(pszSubPath) {
        /* make sure the new path does not exceed th bufferlength
         * rememebr to backslash and the termination */
        if(MAX_PATH < (lstrlenW(szBuildPath) + lstrlenW(pszSubPath) + 2)) {
            hr = HRESULT_FROM_WIN32(ERROR_FILENAME_EXCED_RANGE);
            goto end;
        }
        PathAppendW(szBuildPath, pszSubPath);
        PathRemoveBackslashW(szBuildPath);
    }
2277
    /* Copy the path if it's available before we might return */
2278
    if (SUCCEEDED(hr) && pszPath)
2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290
        strcpyW(pszPath, szBuildPath);

    /* if we don't care about existing directories we are ready */
    if(nFolder & CSIDL_FLAG_DONT_VERIFY) goto end;

    if (PathFileExistsW(szBuildPath)) goto end;

    /* not existing but we are not allowed to create it.  The return value
     * is verified against shell32 version 6.0.
     */
    if (!(nFolder & CSIDL_FLAG_CREATE))
    {
2291
        hr = HRESULT_FROM_WIN32(ERROR_PATH_NOT_FOUND);
2292 2293 2294 2295
        goto end;
    }

    /* create directory/directories */
2296 2297
    ret = SHCreateDirectoryExW(hwndOwner, szBuildPath, NULL);
    if (ret && ret != ERROR_ALREADY_EXISTS)
2298
    {
2299
        ERR("Failed to create directory %s.\n", debugstr_w(szBuildPath));
2300 2301
        hr = E_FAIL;
        goto end;
2302 2303
    }

2304
    TRACE("Created missing system directory %s\n", debugstr_w(szBuildPath));
2305
end:
2306
    TRACE("returning 0x%08x (final path is %s)\n", hr, debugstr_w(szBuildPath));
2307
    return hr;
2308
}
2309 2310

/*************************************************************************
2311
 * SHGetFolderPathA			[SHELL32.@]
2312 2313
 *
 * See SHGetFolderPathW.
2314
 */
2315
HRESULT WINAPI SHGetFolderPathA(
2316
	HWND hwndOwner,
2317
	int nFolder,
2318 2319 2320
	HANDLE hToken,
	DWORD dwFlags,
	LPSTR pszPath)
2321
{
Juan Lang's avatar
Juan Lang committed
2322 2323
    WCHAR szTemp[MAX_PATH];
    HRESULT hr;
2324

2325
    TRACE("%p,%p,nFolder=0x%04x\n",hwndOwner,pszPath,nFolder);
2326

2327 2328 2329 2330
    if (pszPath)
        *pszPath = '\0';
    hr = SHGetFolderPathW(hwndOwner, nFolder, hToken, dwFlags, szTemp);
    if (SUCCEEDED(hr) && pszPath)
Juan Lang's avatar
Juan Lang committed
2331 2332
        WideCharToMultiByte(CP_ACP, 0, szTemp, -1, pszPath, MAX_PATH, NULL,
         NULL);
2333

2334 2335 2336 2337
    return hr;
}

/* For each folder in folders, if its value has not been set in the registry,
2338
 * calls _SHGetUserProfilePath or _SHGetAllUsersProfilePath (depending on the
2339
 * folder's type) to get the unexpanded value first.
2340 2341 2342 2343
 * Writes the unexpanded value to User Shell Folders, and queries it with
 * SHGetFolderPathW to force the creation of the directory if it doesn't
 * already exist.  SHGetFolderPathW also returns the expanded value, which
 * this then writes to Shell Folders.
2344 2345
 */
static HRESULT _SHRegisterFolders(HKEY hRootKey, HANDLE hToken,
2346 2347
 LPCWSTR szUserShellFolderPath, LPCWSTR szShellFolderPath, const UINT folders[],
 UINT foldersLen)
2348 2349 2350 2351
{
    UINT i;
    WCHAR path[MAX_PATH];
    HRESULT hr = S_OK;
2352
    HKEY hUserKey = NULL, hKey = NULL;
2353
    DWORD dwType, dwPathLen;
2354 2355 2356 2357 2358
    LONG ret;

    TRACE("%p,%p,%s,%p,%u\n", hRootKey, hToken,
     debugstr_w(szUserShellFolderPath), folders, foldersLen);

2359
    ret = RegCreateKeyW(hRootKey, szUserShellFolderPath, &hUserKey);
2360 2361
    if (ret)
        hr = HRESULT_FROM_WIN32(ret);
2362 2363
    else
    {
2364
        ret = RegCreateKeyW(hRootKey, szShellFolderPath, &hKey);
2365 2366 2367
        if (ret)
            hr = HRESULT_FROM_WIN32(ret);
    }
2368 2369 2370
    for (i = 0; SUCCEEDED(hr) && i < foldersLen; i++)
    {
        dwPathLen = MAX_PATH * sizeof(WCHAR);
2371
        if (RegQueryValueExW(hUserKey, CSIDL_Data[folders[i]].szValueName, NULL,
2372 2373 2374 2375 2376 2377 2378 2379 2380
         &dwType, (LPBYTE)path, &dwPathLen) || (dwType != REG_SZ &&
         dwType != REG_EXPAND_SZ))
        {
            *path = '\0';
            if (CSIDL_Data[folders[i]].type == CSIDL_Type_User)
                _SHGetUserProfilePath(hToken, SHGFP_TYPE_DEFAULT, folders[i],
                 path);
            else if (CSIDL_Data[folders[i]].type == CSIDL_Type_AllUsers)
                _SHGetAllUsersProfilePath(SHGFP_TYPE_DEFAULT, folders[i], path);
2381
            else if (CSIDL_Data[folders[i]].type == CSIDL_Type_WindowsPath)
2382
            {
2383
                GetWindowsDirectoryW(path, MAX_PATH);
2384 2385 2386 2387 2388 2389 2390
                if (CSIDL_Data[folders[i]].szDefaultPath &&
                    !IS_INTRESOURCE(CSIDL_Data[folders[i]].szDefaultPath))
                {
                    PathAddBackslashW(path);
                    strcatW(path, CSIDL_Data[folders[i]].szDefaultPath);
                }
            }
2391 2392 2393 2394
            else
                hr = E_FAIL;
            if (*path)
            {
2395 2396 2397
                ret = RegSetValueExW(hUserKey,
                 CSIDL_Data[folders[i]].szValueName, 0, REG_EXPAND_SZ,
                 (LPBYTE)path, (strlenW(path) + 1) * sizeof(WCHAR));
2398 2399 2400
                if (ret)
                    hr = HRESULT_FROM_WIN32(ret);
                else
2401
                {
2402
                    hr = SHGetFolderPathW(NULL, folders[i] | CSIDL_FLAG_CREATE,
2403 2404 2405 2406 2407 2408 2409
                     hToken, SHGFP_TYPE_DEFAULT, path);
                    ret = RegSetValueExW(hKey,
                     CSIDL_Data[folders[i]].szValueName, 0, REG_SZ,
                     (LPBYTE)path, (strlenW(path) + 1) * sizeof(WCHAR));
                    if (ret)
                        hr = HRESULT_FROM_WIN32(ret);
                }
2410 2411 2412
            }
        }
    }
2413 2414
    if (hUserKey)
        RegCloseKey(hUserKey);
2415 2416 2417
    if (hKey)
        RegCloseKey(hKey);

2418
    TRACE("returning 0x%08x\n", hr);
2419 2420 2421 2422 2423 2424 2425 2426 2427
    return hr;
}

static HRESULT _SHRegisterUserShellFolders(BOOL bDefault)
{
    static const UINT folders[] = {
     CSIDL_PROGRAMS,
     CSIDL_PERSONAL,
     CSIDL_FAVORITES,
2428
     CSIDL_APPDATA,
2429 2430 2431 2432
     CSIDL_STARTUP,
     CSIDL_RECENT,
     CSIDL_SENDTO,
     CSIDL_STARTMENU,
2433 2434
     CSIDL_MYMUSIC,
     CSIDL_MYVIDEO,
2435 2436 2437 2438
     CSIDL_DESKTOPDIRECTORY,
     CSIDL_NETHOOD,
     CSIDL_TEMPLATES,
     CSIDL_PRINTHOOD,
2439 2440
     CSIDL_LOCAL_APPDATA,
     CSIDL_INTERNET_CACHE,
2441 2442
     CSIDL_COOKIES,
     CSIDL_HISTORY,
2443 2444
     CSIDL_MYPICTURES,
     CSIDL_FONTS
2445
    };
2446 2447
    WCHAR userShellFolderPath[MAX_PATH], shellFolderPath[MAX_PATH];
    LPCWSTR pUserShellFolderPath, pShellFolderPath;
2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460
    HRESULT hr = S_OK;
    HKEY hRootKey;
    HANDLE hToken;

    TRACE("%s\n", bDefault ? "TRUE" : "FALSE");
    if (bDefault)
    {
        hToken = (HANDLE)-1;
        hRootKey = HKEY_USERS;
        strcpyW(userShellFolderPath, DefaultW);
        PathAddBackslashW(userShellFolderPath);
        strcatW(userShellFolderPath, szSHUserFolders);
        pUserShellFolderPath = userShellFolderPath;
2461 2462 2463 2464
        strcpyW(shellFolderPath, DefaultW);
        PathAddBackslashW(shellFolderPath);
        strcatW(shellFolderPath, szSHFolders);
        pShellFolderPath = shellFolderPath;
2465 2466 2467 2468 2469 2470
    }
    else
    {
        hToken = NULL;
        hRootKey = HKEY_CURRENT_USER;
        pUserShellFolderPath = szSHUserFolders;
2471
        pShellFolderPath = szSHFolders;
2472 2473 2474
    }

    hr = _SHRegisterFolders(hRootKey, hToken, pUserShellFolderPath,
2475
     pShellFolderPath, folders, sizeof(folders) / sizeof(folders[0]));
2476
    TRACE("returning 0x%08x\n", hr);
2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490
    return hr;
}

static HRESULT _SHRegisterCommonShellFolders(void)
{
    static const UINT folders[] = {
     CSIDL_COMMON_STARTMENU,
     CSIDL_COMMON_PROGRAMS,
     CSIDL_COMMON_STARTUP,
     CSIDL_COMMON_DESKTOPDIRECTORY,
     CSIDL_COMMON_FAVORITES,
     CSIDL_COMMON_APPDATA,
     CSIDL_COMMON_TEMPLATES,
     CSIDL_COMMON_DOCUMENTS,
2491 2492 2493 2494
     CSIDL_COMMON_ADMINTOOLS,
     CSIDL_COMMON_MUSIC,
     CSIDL_COMMON_PICTURES,
     CSIDL_COMMON_VIDEO,
2495 2496 2497 2498 2499
    };
    HRESULT hr;

    TRACE("\n");
    hr = _SHRegisterFolders(HKEY_LOCAL_MACHINE, NULL, szSHUserFolders,
2500
     szSHFolders, folders, sizeof(folders) / sizeof(folders[0]));
2501
    TRACE("returning 0x%08x\n", hr);
2502 2503
    return hr;
}
Juan Lang's avatar
Juan Lang committed
2504

2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537
/******************************************************************************
 * _SHAppendToUnixPath  [Internal]
 *
 * Helper function for _SHCreateSymbolicLinks. Appends pwszSubPath (or the 
 * corresponding resource, if IS_INTRESOURCE) to the unix base path 'szBasePath' 
 * and replaces backslashes with slashes.
 *
 * PARAMS
 *  szBasePath  [IO] The unix base path, which will be appended to (CP_UNXICP).
 *  pwszSubPath [I]  Sub-path or resource id (use MAKEINTRESOURCEW).
 *
 * RETURNS
 *  Success: TRUE,
 *  Failure: FALSE
 */
static inline BOOL _SHAppendToUnixPath(char *szBasePath, LPCWSTR pwszSubPath) {
    WCHAR wszSubPath[MAX_PATH];
    int cLen = strlen(szBasePath);
    char *pBackslash;

    if (IS_INTRESOURCE(pwszSubPath)) {
        if (!LoadStringW(shell32_hInstance, LOWORD(pwszSubPath), wszSubPath, MAX_PATH)) {
            /* Fall back to hard coded defaults. */
            switch (LOWORD(pwszSubPath)) {
                case IDS_PERSONAL:
                    lstrcpyW(wszSubPath, PersonalW);
                    break;
                case IDS_MYMUSIC:
                    lstrcpyW(wszSubPath, My_MusicW);
                    break;
                case IDS_MYPICTURES:
                    lstrcpyW(wszSubPath, My_PicturesW);
                    break;
2538 2539
                case IDS_MYVIDEOS:
                    lstrcpyW(wszSubPath, My_VideosW);
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
                    break;
                default:
                    ERR("LoadString(%d) failed!\n", LOWORD(pwszSubPath));
                    return FALSE;
            }
        }
    } else {
        lstrcpyW(wszSubPath, pwszSubPath);
    }
 
    if (szBasePath[cLen-1] != '/') szBasePath[cLen++] = '/';
 
    if (!WideCharToMultiByte(CP_UNIXCP, 0, wszSubPath, -1, szBasePath + cLen,
                             FILENAME_MAX - cLen, NULL, NULL))
    {
        return FALSE;
    }
 
    pBackslash = szBasePath + cLen;
    while ((pBackslash = strchr(pBackslash, '\\'))) *pBackslash = '/';
 
    return TRUE;
}

/******************************************************************************
 * _SHCreateSymbolicLinks  [Internal]
 * 
 * Sets up symbol links for various shell folders to point into the users home
 * directory. We do an educated guess about what the user would probably want:
 * - If there is a 'My Documents' directory in $HOME, the user probably wants
 *   wine's 'My Documents' to point there. Furthermore, we imply that the user
 *   is a Windows lover and has no problem with wine creating 'My Pictures',
2572
 *   'My Music' and 'My Videos' subfolders under '$HOME/My Documents', if those
2573 2574 2575 2576 2577 2578
 *   do not already exits. We put appropriate symbolic links in place for those,
 *   too.
 * - If there is no 'My Documents' directory in $HOME, we let 'My Documents'
 *   point directly to $HOME. We assume the user to be a unix hacker who does not
 *   want wine to create anything anywhere besides the .wine directory. So, if
 *   there already is a 'My Music' directory in $HOME, we symlink the 'My Music'
2579 2580
 *   shell folder to it. But if not, then we check XDG_MUSIC_DIR - "well known"
 *   directory, and try to link to that. If that fails, then we symlink to
2581
 *   $HOME directly. The same holds fo 'My Pictures' and 'My Videos'.
2582 2583 2584
 * - The Desktop shell folder is symlinked to XDG_DESKTOP_DIR. If that does not
 *   exist, then we try '$HOME/Desktop'. If that does not exist, then we leave
 *   it alone.
2585 2586
 * ('My Music',... above in fact means LoadString(IDS_MYMUSIC))
 */
2587
static void _SHCreateSymbolicLinks(void)
2588
{
2589
    UINT aidsMyStuff[] = { IDS_MYPICTURES, IDS_MYVIDEOS, IDS_MYMUSIC }, i;
2590
    int acsidlMyStuff[] = { CSIDL_MYPICTURES, CSIDL_MYVIDEO, CSIDL_MYMUSIC };
2591 2592
    static const char * const xdg_dirs[] = { "PICTURES", "VIDEOS", "MUSIC", "DESKTOP" };
    static const unsigned int num = sizeof(xdg_dirs) / sizeof(xdg_dirs[0]);
2593 2594 2595 2596 2597 2598 2599
    WCHAR wszTempPath[MAX_PATH];
    char szPersonalTarget[FILENAME_MAX], *pszPersonal;
    char szMyStuffTarget[FILENAME_MAX], *pszMyStuff;
    char szDesktopTarget[FILENAME_MAX], *pszDesktop;
    struct stat statFolder;
    const char *pszHome;
    HRESULT hr;
2600
    char ** xdg_results;
2601
    char * xdg_desktop_dir;
2602 2603 2604 2605 2606 2607 2608 2609

    /* Create all necessary profile sub-dirs up to 'My Documents' and get the unix path. */
    hr = SHGetFolderPathW(NULL, CSIDL_PERSONAL|CSIDL_FLAG_CREATE, NULL,
                          SHGFP_TYPE_DEFAULT, wszTempPath);
    if (FAILED(hr)) return;
    pszPersonal = wine_get_unix_file_name(wszTempPath);
    if (!pszPersonal) return;

2610 2611
    hr = XDG_UserDirLookup(xdg_dirs, num, &xdg_results);
    if (FAILED(hr)) xdg_results = NULL;
2612

2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623
    pszHome = getenv("HOME");
    if (pszHome && !stat(pszHome, &statFolder) && S_ISDIR(statFolder.st_mode)) {
        strcpy(szPersonalTarget, pszHome);
        if (_SHAppendToUnixPath(szPersonalTarget, MAKEINTRESOURCEW(IDS_PERSONAL)) &&
            !stat(szPersonalTarget, &statFolder) && S_ISDIR(statFolder.st_mode))
        {
            /* '$HOME/My Documents' exists. Create 'My Pictures', 'My Videos' and 
             * 'My Music' subfolders or fail silently if they already exist. */
            for (i = 0; i < sizeof(aidsMyStuff)/sizeof(aidsMyStuff[0]); i++) {
                strcpy(szMyStuffTarget, szPersonalTarget);
                if (_SHAppendToUnixPath(szMyStuffTarget, MAKEINTRESOURCEW(aidsMyStuff[i])))
2624
                    mkdir(szMyStuffTarget, 0777);
2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644
            }
        } 
        else
        {
            /* '$HOME/My Documents' doesn't exists, but '$HOME' does. */ 
            strcpy(szPersonalTarget, pszHome);
        }

        /* Replace 'My Documents' directory with a symlink of fail silently if not empty. */
        rmdir(pszPersonal);
        symlink(szPersonalTarget, pszPersonal);
    }
    else
    {
        /* '$HOME' doesn't exist. Create 'My Pictures', 'My Videos' and 'My Music' subdirs
         * in '%USERPROFILE%\\My Documents' or fail silently if they already exist. */
        strcpy(szPersonalTarget, pszPersonal);
        for (i = 0; i < sizeof(aidsMyStuff)/sizeof(aidsMyStuff[0]); i++) {
            strcpy(szMyStuffTarget, szPersonalTarget);
            if (_SHAppendToUnixPath(szMyStuffTarget, MAKEINTRESOURCEW(aidsMyStuff[i])))
2645
                mkdir(szMyStuffTarget, 0777);
2646 2647 2648
        }
    }

2649
    /* Create symbolic links for 'My Pictures', 'My Videos' and 'My Music'. */
2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668
    for (i=0; i < sizeof(aidsMyStuff)/sizeof(aidsMyStuff[0]); i++) {
        /* Create the current 'My Whatever' folder and get it's unix path. */
        hr = SHGetFolderPathW(NULL, acsidlMyStuff[i]|CSIDL_FLAG_CREATE, NULL,
                              SHGFP_TYPE_DEFAULT, wszTempPath);
        if (FAILED(hr)) continue;
        pszMyStuff = wine_get_unix_file_name(wszTempPath);
        if (!pszMyStuff) continue;
        
        strcpy(szMyStuffTarget, szPersonalTarget);
        if (_SHAppendToUnixPath(szMyStuffTarget, MAKEINTRESOURCEW(aidsMyStuff[i])) &&
            !stat(szMyStuffTarget, &statFolder) && S_ISDIR(statFolder.st_mode))
        {
            /* If there's a 'My Whatever' directory where 'My Documents' links to, link to it. */
            rmdir(pszMyStuff);
            symlink(szMyStuffTarget, pszMyStuff);
        } 
        else
        {
            rmdir(pszMyStuff);
2669 2670 2671 2672 2673 2674 2675 2676 2677 2678
            if (xdg_results && xdg_results[i])
            {
                /* the folder specified by XDG_XXX_DIR exists, link to it. */
                symlink(xdg_results[i], pszMyStuff);
            }
            else
            {
                /* Else link to where 'My Documents' itself links to. */
                symlink(szPersonalTarget, pszMyStuff);
            }
2679 2680 2681 2682 2683
        }
        HeapFree(GetProcessHeap(), 0, pszMyStuff);
    }

    /* Last but not least, the Desktop folder */
2684 2685 2686 2687 2688 2689
    if (pszHome)
        strcpy(szDesktopTarget, pszHome);
    else
        strcpy(szDesktopTarget, pszPersonal);
    HeapFree(GetProcessHeap(), 0, pszPersonal);

2690 2691 2692 2693
    xdg_desktop_dir = xdg_results ? xdg_results[num - 1] : NULL;
    if (xdg_desktop_dir ||
        (_SHAppendToUnixPath(szDesktopTarget, DesktopW) &&
        !stat(szDesktopTarget, &statFolder) && S_ISDIR(statFolder.st_mode)))
2694 2695 2696 2697 2698 2699
    {
        hr = SHGetFolderPathW(NULL, CSIDL_DESKTOPDIRECTORY|CSIDL_FLAG_CREATE, NULL,
                              SHGFP_TYPE_DEFAULT, wszTempPath);
        if (SUCCEEDED(hr) && (pszDesktop = wine_get_unix_file_name(wszTempPath))) 
        {
            rmdir(pszDesktop);
2700 2701 2702 2703
            if (xdg_desktop_dir)
                symlink(xdg_desktop_dir, pszDesktop);
            else
                symlink(szDesktopTarget, pszDesktop);
2704 2705 2706
            HeapFree(GetProcessHeap(), 0, pszDesktop);
        }
    }
2707 2708 2709 2710 2711 2712 2713 2714

    /* Free resources allocated by XDG_UserDirLookup() */
    if (xdg_results)
    {
        for (i = 0; i < num; i++)
            HeapFree(GetProcessHeap(), 0, xdg_results[i]);
        HeapFree(GetProcessHeap(), 0, xdg_results);
    }
2715 2716
}

2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752
/******************************************************************************
 * create_extra_folders  [Internal]
 *
 * Create some extra folders that don't have a standard CSIDL definition.
 */
static HRESULT create_extra_folders(void)
{
    static const WCHAR environW[] = {'E','n','v','i','r','o','n','m','e','n','t',0};
    static const WCHAR TempW[]    = {'T','e','m','p',0};
    static const WCHAR TEMPW[]    = {'T','E','M','P',0};
    static const WCHAR TMPW[]     = {'T','M','P',0};
    WCHAR path[MAX_PATH+5];
    HRESULT hr;
    HKEY hkey;
    DWORD type, size, ret;

    ret = RegCreateKeyW( HKEY_CURRENT_USER, environW, &hkey );
    if (ret) return HRESULT_FROM_WIN32( ret );

    /* FIXME: should be under AppData, but we don't want spaces in the temp path */
    hr = SHGetFolderPathAndSubDirW( 0, CSIDL_PROFILE | CSIDL_FLAG_CREATE, NULL,
                                    SHGFP_TYPE_DEFAULT, TempW, path );
    if (SUCCEEDED(hr))
    {
        size = sizeof(path);
        if (RegQueryValueExW( hkey, TEMPW, NULL, &type, (LPBYTE)path, &size ))
            RegSetValueExW( hkey, TEMPW, 0, REG_SZ, (LPBYTE)path, (strlenW(path) + 1) * sizeof(WCHAR) );
        size = sizeof(path);
        if (RegQueryValueExW( hkey, TMPW, NULL, &type, (LPBYTE)path, &size ))
            RegSetValueExW( hkey, TMPW, 0, REG_SZ, (LPBYTE)path, (strlenW(path) + 1) * sizeof(WCHAR) );
    }
    RegCloseKey( hkey );
    return hr;
}


2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823
/******************************************************************************
 * set_folder_attributes
 *
 * Set the various folder attributes registry keys.
 */
static HRESULT set_folder_attributes(void)
{
    static const WCHAR clsidW[] = {'C','L','S','I','D','\\',0 };
    static const WCHAR shellfolderW[] = {'\\','S','h','e','l','l','F','o','l','d','e','r', 0 };
    static const WCHAR wfparsingW[] = {'W','a','n','t','s','F','O','R','P','A','R','S','I','N','G',0};
    static const WCHAR wfdisplayW[] = {'W','a','n','t','s','F','O','R','D','I','S','P','L','A','Y',0};
    static const WCHAR hideasdeleteW[] = {'H','i','d','e','A','s','D','e','l','e','t','e','P','e','r','U','s','e','r',0};
    static const WCHAR attributesW[] = {'A','t','t','r','i','b','u','t','e','s',0};
    static const WCHAR cfattributesW[] = {'C','a','l','l','F','o','r','A','t','t','r','i','b','u','t','e','s',0};
    static const WCHAR emptyW[] = {0};

    static const struct
    {
        const CLSID *clsid;
        BOOL wfparsing : 1;
        BOOL wfdisplay : 1;
        BOOL hideasdel : 1;
        DWORD attr;
        DWORD call_for_attr;
    } folders[] =
    {
        { &CLSID_UnixFolder, TRUE, FALSE, FALSE },
        { &CLSID_UnixDosFolder, TRUE, FALSE, FALSE,
          SFGAO_FILESYSANCESTOR|SFGAO_FOLDER|SFGAO_HASSUBFOLDER, SFGAO_FILESYSTEM },
        { &CLSID_FolderShortcut, FALSE, FALSE, FALSE,
          SFGAO_FILESYSTEM|SFGAO_FOLDER|SFGAO_LINK,
          SFGAO_HASSUBFOLDER|SFGAO_FILESYSTEM|SFGAO_FOLDER|SFGAO_FILESYSANCESTOR },
        { &CLSID_MyDocuments, TRUE, FALSE, FALSE,
          SFGAO_FILESYSANCESTOR|SFGAO_FOLDER|SFGAO_HASSUBFOLDER, SFGAO_FILESYSTEM },
        { &CLSID_RecycleBin, FALSE, FALSE, FALSE,
          SFGAO_FOLDER|SFGAO_DROPTARGET|SFGAO_HASPROPSHEET },
        { &CLSID_ControlPanel, FALSE, TRUE, TRUE,
          SFGAO_FOLDER|SFGAO_HASSUBFOLDER }
    };

    unsigned int i;
    WCHAR buffer[39 + (sizeof(clsidW) + sizeof(shellfolderW)) / sizeof(WCHAR)];
    LONG res;
    HKEY hkey;

    for (i = 0; i < sizeof(folders)/sizeof(folders[0]); i++)
    {
        strcpyW( buffer, clsidW );
        StringFromGUID2( folders[i].clsid, buffer + strlenW(buffer), 39 );
        strcatW( buffer, shellfolderW );
        res = RegCreateKeyExW( HKEY_CLASSES_ROOT, buffer, 0, NULL, 0,
                               KEY_READ | KEY_WRITE, NULL, &hkey, NULL);
        if (res) return HRESULT_FROM_WIN32( res );
        if (folders[i].wfparsing)
            res = RegSetValueExW( hkey, wfparsingW, 0, REG_SZ, (const BYTE *)emptyW, sizeof(emptyW) );
        if (folders[i].wfdisplay)
            res = RegSetValueExW( hkey, wfdisplayW, 0, REG_SZ, (const BYTE *)emptyW, sizeof(emptyW) );
        if (folders[i].hideasdel)
            res = RegSetValueExW( hkey, hideasdeleteW, 0, REG_SZ, (const BYTE *)emptyW, sizeof(emptyW) );
        if (folders[i].attr)
            res = RegSetValueExW( hkey, attributesW, 0, REG_DWORD,
                                  (const BYTE *)&folders[i].attr, sizeof(DWORD));
        if (folders[i].call_for_attr)
            res = RegSetValueExW( hkey, cfattributesW, 0, REG_DWORD,
                                 (const BYTE *)&folders[i].call_for_attr, sizeof(DWORD));
        RegCloseKey( hkey );
    }
    return S_OK;
}


2824 2825 2826 2827 2828
/* Register the default values in the registry, as some apps seem to depend
 * on their presence.  The set registered was taken from Windows XP.
 */
HRESULT SHELL_RegisterShellFolders(void)
{
2829
    HRESULT hr;
2830

2831
    /* Set up '$HOME' targeted symlinks for 'My Documents', 'My Pictures',
2832
     * 'My Videos', 'My Music' and 'Desktop' in advance, so that the
2833 2834 2835 2836 2837
     * _SHRegister*ShellFolders() functions will find everything nice and clean
     * and thus will not attempt to create them in the profile directory. */
    _SHCreateSymbolicLinks();
    
    hr = _SHRegisterUserShellFolders(TRUE);
2838 2839 2840 2841
    if (SUCCEEDED(hr))
        hr = _SHRegisterUserShellFolders(FALSE);
    if (SUCCEEDED(hr))
        hr = _SHRegisterCommonShellFolders();
2842 2843
    if (SUCCEEDED(hr))
        hr = create_extra_folders();
2844 2845
    if (SUCCEEDED(hr))
        hr = set_folder_attributes();
Juan Lang's avatar
Juan Lang committed
2846
    return hr;
2847
}
2848 2849

/*************************************************************************
2850
 * SHGetSpecialFolderPathA [SHELL32.@]
2851
 */
2852
BOOL WINAPI SHGetSpecialFolderPathA (
2853
	HWND hwndOwner,
2854
	LPSTR szPath,
2855
	int nFolder,
2856 2857
	BOOL bCreate)
{
2858 2859
	return (SHGetFolderPathA(
		hwndOwner,
2860
		nFolder + (bCreate ? CSIDL_FLAG_CREATE : 0),
2861 2862 2863
		NULL,
		0,
		szPath)) == S_OK ? TRUE : FALSE;
2864
}
Jim Aston's avatar
Jim Aston committed
2865

Juergen Schmied's avatar
Juergen Schmied committed
2866
/*************************************************************************
2867
 * SHGetSpecialFolderPathW
Juergen Schmied's avatar
Juergen Schmied committed
2868
 */
2869
BOOL WINAPI SHGetSpecialFolderPathW (
Juergen Schmied's avatar
Juergen Schmied committed
2870
	HWND hwndOwner,
2871
	LPWSTR szPath,
2872
	int nFolder,
2873
	BOOL bCreate)
Juergen Schmied's avatar
Juergen Schmied committed
2874
{
2875
	return (SHGetFolderPathW(
Juergen Schmied's avatar
Juergen Schmied committed
2876
		hwndOwner,
2877
		nFolder + (bCreate ? CSIDL_FLAG_CREATE : 0),
2878 2879 2880
		NULL,
		0,
		szPath)) == S_OK ? TRUE : FALSE;
Juergen Schmied's avatar
Juergen Schmied committed
2881 2882 2883
}

/*************************************************************************
2884
 * SHGetSpecialFolderPath (SHELL32.175)
Juergen Schmied's avatar
Juergen Schmied committed
2885
 */
2886
BOOL WINAPI SHGetSpecialFolderPathAW (
Juergen Schmied's avatar
Juergen Schmied committed
2887
	HWND hwndOwner,
2888
	LPVOID szPath,
2889
	int nFolder,
2890 2891
	BOOL bCreate)

Juergen Schmied's avatar
Juergen Schmied committed
2892
{
2893
	if (SHELL_OsIsUnicode())
2894 2895
	  return SHGetSpecialFolderPathW (hwndOwner, szPath, nFolder, bCreate);
	return SHGetSpecialFolderPathA (hwndOwner, szPath, nFolder, bCreate);
Juergen Schmied's avatar
Juergen Schmied committed
2896
}
Juan Lang's avatar
Juan Lang committed
2897 2898

/*************************************************************************
2899
 * SHGetFolderLocation [SHELL32.@]
Juan Lang's avatar
Juan Lang committed
2900
 *
2901
 * Gets the folder locations from the registry and creates a pidl.
Juan Lang's avatar
Juan Lang committed
2902 2903
 *
 * PARAMS
2904 2905 2906 2907 2908 2909
 *   hwndOwner  [I]
 *   nFolder    [I] CSIDL_xxxxx
 *   hToken     [I] token representing user, or NULL for current user, or -1 for
 *                  default user
 *   dwReserved [I] must be zero
 *   ppidl      [O] PIDL of a special folder
Juan Lang's avatar
Juan Lang committed
2910
 *
2911 2912 2913 2914
 * RETURNS
 *  Success: S_OK
 *  Failure: Standard OLE-defined error result, S_FALSE or E_INVALIDARG
 *
Juan Lang's avatar
Juan Lang committed
2915
 * NOTES
2916 2917 2918
 *  Creates missing reg keys and directories.
 *  Mostly forwards to SHGetFolderPathW, but a few values of nFolder return
 *  virtual folders that are handled here.
Juan Lang's avatar
Juan Lang committed
2919
 */
2920
HRESULT WINAPI SHGetFolderLocation(
Juan Lang's avatar
Juan Lang committed
2921
	HWND hwndOwner,
2922 2923 2924 2925
	int nFolder,
	HANDLE hToken,
	DWORD dwReserved,
	LPITEMIDLIST *ppidl)
Juan Lang's avatar
Juan Lang committed
2926 2927 2928
{
    HRESULT hr = E_INVALIDARG;

2929
    TRACE("%p 0x%08x %p 0x%08x %p\n",
2930 2931
     hwndOwner, nFolder, hToken, dwReserved, ppidl);
    
Juan Lang's avatar
Juan Lang committed
2932 2933
    if (!ppidl)
        return E_INVALIDARG;
2934 2935
    if (dwReserved)
        return E_INVALIDARG;
Juan Lang's avatar
Juan Lang committed
2936

2937
    /* The virtual folders' locations are not user-dependent */
Juan Lang's avatar
Juan Lang committed
2938
    *ppidl = NULL;
2939
    switch (nFolder & CSIDL_FOLDER_MASK)
Juan Lang's avatar
Juan Lang committed
2940 2941 2942 2943 2944
    {
        case CSIDL_DESKTOP:
            *ppidl = _ILCreateDesktop();
            break;

2945 2946 2947 2948
        case CSIDL_PERSONAL:
            *ppidl = _ILCreateMyDocuments();
            break;

Juan Lang's avatar
Juan Lang committed
2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976
        case CSIDL_INTERNET:
            *ppidl = _ILCreateIExplore();
            break;

        case CSIDL_CONTROLS:
            *ppidl = _ILCreateControlPanel();
            break;

        case CSIDL_PRINTERS:
            *ppidl = _ILCreatePrinters();
            break;

        case CSIDL_BITBUCKET:
            *ppidl = _ILCreateBitBucket();
            break;

        case CSIDL_DRIVES:
            *ppidl = _ILCreateMyComputer();
            break;

        case CSIDL_NETWORK:
            *ppidl = _ILCreateNetwork();
            break;

        default:
        {
            WCHAR szPath[MAX_PATH];

2977 2978 2979
            hr = SHGetFolderPathW(hwndOwner, nFolder, hToken,
             SHGFP_TYPE_CURRENT, szPath);
            if (SUCCEEDED(hr))
Juan Lang's avatar
Juan Lang committed
2980 2981 2982 2983 2984 2985
            {
                DWORD attributes=0;

                TRACE("Value=%s\n", debugstr_w(szPath));
                hr = SHILCreateFromPathW(szPath, ppidl, &attributes);
            }
2986 2987 2988
            else if (hr == HRESULT_FROM_WIN32(ERROR_FILE_NOT_FOUND))
            {
                /* unlike SHGetFolderPath, SHGetFolderLocation in shell32
2989
                 * version 6.0 returns E_FAIL for nonexistent paths
2990 2991 2992
                 */
                hr = E_FAIL;
            }
Juan Lang's avatar
Juan Lang committed
2993 2994 2995
        }
    }
    if(*ppidl)
2996
        hr = S_OK;
Juan Lang's avatar
Juan Lang committed
2997 2998 2999 3000 3001 3002

    TRACE("-- (new pidl %p)\n",*ppidl);
    return hr;
}

/*************************************************************************
3003
 * SHGetSpecialFolderLocation		[SHELL32.@]
Juan Lang's avatar
Juan Lang committed
3004 3005
 *
 * NOTES
3006 3007
 *   In NT5, SHGetSpecialFolderLocation needs the <winntdir>/Recent
 *   directory.
Juan Lang's avatar
Juan Lang committed
3008
 */
3009 3010 3011 3012
HRESULT WINAPI SHGetSpecialFolderLocation(
	HWND hwndOwner,
	INT nFolder,
	LPITEMIDLIST * ppidl)
Juan Lang's avatar
Juan Lang committed
3013
{
3014 3015 3016
    HRESULT hr = E_INVALIDARG;

    TRACE("(%p,0x%x,%p)\n", hwndOwner,nFolder,ppidl);
Juan Lang's avatar
Juan Lang committed
3017 3018 3019 3020

    if (!ppidl)
        return E_INVALIDARG;

3021
    hr = SHGetFolderLocation(hwndOwner, nFolder, NULL, 0, ppidl);
Juan Lang's avatar
Juan Lang committed
3022 3023
    return hr;
}
3024

3025 3026 3027 3028 3029 3030 3031 3032
static int csidl_from_id( const KNOWNFOLDERID *id )
{
    int i;
    for (i = 0; i < sizeof(CSIDL_Data) / sizeof(CSIDL_Data[0]); i++)
        if (IsEqualGUID( CSIDL_Data[i].id, id )) return i;
    return -1;
}

3033 3034 3035 3036 3037
/*************************************************************************
 * SHGetKnownFolderPath           [SHELL32.@]
 */
HRESULT WINAPI SHGetKnownFolderPath(REFKNOWNFOLDERID rfid, DWORD flags, HANDLE token, PWSTR *path)
{
3038 3039 3040 3041 3042 3043
    HRESULT hr;
    WCHAR folder[MAX_PATH];
    int index = csidl_from_id( rfid );

    TRACE("%s, 0x%08x, %p, %p\n", debugstr_guid(rfid), flags, token, path);

3044 3045
    *path = NULL;

3046
    if (index < 0)
3047
        return HRESULT_FROM_WIN32( ERROR_FILE_NOT_FOUND );
3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075

    if (flags & KF_FLAG_CREATE)
        index |= CSIDL_FLAG_CREATE;

    if (flags & KF_FLAG_DONT_VERIFY)
        index |= CSIDL_FLAG_DONT_VERIFY;

    if (flags & KF_FLAG_NO_ALIAS)
        index |= CSIDL_FLAG_NO_ALIAS;

    if (flags & KF_FLAG_INIT)
        index |= CSIDL_FLAG_PER_USER_INIT;

    if (flags & ~(KF_FLAG_CREATE|KF_FLAG_DONT_VERIFY|KF_FLAG_NO_ALIAS|KF_FLAG_INIT))
    {
        FIXME("flags 0x%08x not supported\n", flags);
        return E_INVALIDARG;
    }

    hr = SHGetFolderPathW( NULL, index, token, 0, folder );
    if (SUCCEEDED(hr))
    {
        *path = CoTaskMemAlloc( (strlenW( folder ) + 1) * sizeof(WCHAR) );
        if (!*path)
            return E_OUTOFMEMORY;
        strcpyW( *path, folder );
    }
    return hr;
3076
}
3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102

/*************************************************************************
 * SHGetFolderPathEx           [SHELL32.@]
 */
HRESULT WINAPI SHGetFolderPathEx(REFKNOWNFOLDERID rfid, DWORD flags, HANDLE token, LPWSTR path, DWORD len)
{
    HRESULT hr;
    WCHAR *buffer;

    TRACE("%s, 0x%08x, %p, %p, %u\n", debugstr_guid(rfid), flags, token, path, len);

    if (!path || !len) return E_INVALIDARG;

    hr = SHGetKnownFolderPath( rfid, flags, token, &buffer );
    if (SUCCEEDED( hr ))
    {
        if (strlenW( buffer ) + 1 > len)
        {
            CoTaskMemFree( buffer );
            return HRESULT_FROM_WIN32( ERROR_INSUFFICIENT_BUFFER );
        }
        strcpyW( path, buffer );
        CoTaskMemFree( buffer );
    }
    return hr;
}
3103

3104 3105 3106
/* constant values used by known folder functions */
static const WCHAR szCategory[] = {'C','a','t','e','g','o','r','y',0};
static const WCHAR szName[] = {'N','a','m','e',0};
3107
static const WCHAR szRelativePath[] = {'R','e','l','a','t','i','v','e','P','a','t','h',0};
3108
static const WCHAR szParentFolder[] = {'P','a','r','e','n','t','F','o','l','d','e','r',0};
3109 3110 3111 3112 3113 3114

/*
 * Internal function to convert known folder identifier to path of registry key
 * associated with known folder.
 *
 * Parameters:
3115 3116
 *  rfid            [I] pointer to known folder identifier (may be NULL)
 *  lpStringGuid    [I] string with known folder identifier (used when rfid is NULL)
3117 3118 3119
 *  lpPath          [O] place to store string address. String should be
 *                      later freed using HeapFree(GetProcessHeap(),0, ... )
 */
3120 3121 3122 3123
static HRESULT get_known_folder_registry_path(
    REFKNOWNFOLDERID rfid,
    LPWSTR lpStringGuid,
    LPWSTR *lpPath)
3124 3125 3126 3127 3128 3129
{
    static const WCHAR sBackslash[] = {'\\',0};
    HRESULT hr = S_OK;
    int length;
    WCHAR sGuid[50];

3130
    TRACE("(%s, %s, %p)\n", debugstr_guid(rfid), debugstr_w(lpStringGuid), lpPath);
3131

3132 3133 3134 3135
    if(rfid)
        StringFromGUID2(rfid, sGuid, sizeof(sGuid)/sizeof(sGuid[0]));
    else
        lstrcpyW(sGuid, lpStringGuid);
3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151

    length = lstrlenW(szKnownFolderDescriptions)+51;
    *lpPath = HeapAlloc(GetProcessHeap(), 0, length*sizeof(WCHAR));
    if(!(*lpPath))
        hr = E_OUTOFMEMORY;

    if(SUCCEEDED(hr))
    {
        lstrcpyW(*lpPath, szKnownFolderDescriptions);
        lstrcatW(*lpPath, sBackslash);
        lstrcatW(*lpPath, sGuid);
    }

    return hr;
}

3152 3153 3154 3155 3156 3157 3158 3159 3160 3161
/*
 * Internal function to get place where folder redirection information are stored.
 *
 * Parameters:
 *  rfid            [I] pointer to known folder identifier (may be NULL)
 *  rootKey         [O] root key where the redirection information are stored
 *                      It can be HKLM for COMMON folders, and HKCU for PERUSER folders.
 *                      However, besides root key, path is always that same, and is stored
 *                      as "szKnownFolderRedirections" constant
 */
3162
static HRESULT get_known_folder_redirection_place(
3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199
    REFKNOWNFOLDERID rfid,
    HKEY *rootKey)
{
    HRESULT hr;
    LPWSTR lpRegistryPath = NULL;
    KF_CATEGORY category;
    DWORD dwSize;

    /* first, get known folder's category */
    hr = get_known_folder_registry_path(rfid, NULL, &lpRegistryPath);

    if(SUCCEEDED(hr))
    {
        dwSize = sizeof(category);
        hr = HRESULT_FROM_WIN32(RegGetValueW(HKEY_LOCAL_MACHINE, lpRegistryPath, szCategory, RRF_RT_DWORD, NULL, &category, &dwSize));
    }

    if(SUCCEEDED(hr))
    {
        if(category == KF_CATEGORY_COMMON)
        {
            *rootKey = HKEY_LOCAL_MACHINE;
            hr = S_OK;
        }
        else if(category == KF_CATEGORY_PERUSER)
        {
            *rootKey = HKEY_CURRENT_USER;
            hr = S_OK;
        }
        else
            hr = E_FAIL;
    }

    HeapFree(GetProcessHeap(), 0, lpRegistryPath);
    return hr;
}

3200 3201
static HRESULT get_known_folder_path_by_id(REFKNOWNFOLDERID folderId, LPWSTR lpRegistryPath, DWORD dwFlags, LPWSTR *ppszPath);

3202 3203 3204 3205 3206 3207 3208 3209 3210
static HRESULT get_known_folder_category(
    LPWSTR registryPath,
    KF_CATEGORY* pCategory)
{
    DWORD dwSize = sizeof(DWORD);
    DWORD dwType;
    return HRESULT_FROM_WIN32(RegGetValueW(HKEY_LOCAL_MACHINE, registryPath, szCategory, RRF_RT_DWORD, &dwType, pCategory, &dwSize));
}

3211
static HRESULT redirect_known_folder(
3212 3213 3214 3215 3216 3217 3218 3219 3220 3221 3222
    REFKNOWNFOLDERID rfid,
    HWND hwnd,
    KF_REDIRECT_FLAGS flags,
    LPCWSTR pszTargetPath,
    UINT cFolders,
    KNOWNFOLDERID const *pExclusion,
    LPWSTR *ppszError)
{
    HRESULT hr;
    HKEY rootKey = HKEY_LOCAL_MACHINE, hKey;
    WCHAR sGuid[39];
3223
    LPWSTR lpRegistryPath = NULL, lpSrcPath = NULL;
3224 3225
    TRACE("(%s, %p, 0x%08x, %s, %d, %p, %p)\n", debugstr_guid(rfid), hwnd, flags, debugstr_w(pszTargetPath), cFolders, pExclusion, ppszError);

3226 3227
    if (ppszError) *ppszError = NULL;

3228 3229 3230 3231 3232 3233 3234
    hr = get_known_folder_registry_path(rfid, NULL, &lpRegistryPath);

    if(SUCCEEDED(hr))
        hr = get_known_folder_path_by_id(rfid, lpRegistryPath, 0, &lpSrcPath);

    HeapFree(GetProcessHeap(), 0, lpRegistryPath);

3235
    /* get path to redirection storage */
3236 3237
    if(SUCCEEDED(hr))
        hr = get_known_folder_redirection_place(rfid, &rootKey);
3238 3239 3240 3241 3242 3243 3244 3245 3246 3247 3248 3249 3250 3251

    /* write redirection information */
    if(SUCCEEDED(hr))
        hr = HRESULT_FROM_WIN32(RegCreateKeyExW(rootKey, szKnownFolderRedirections, 0, NULL, 0, KEY_WRITE, NULL, &hKey, NULL));

    if(SUCCEEDED(hr))
    {
        StringFromGUID2(rfid, sGuid, sizeof(sGuid)/sizeof(sGuid[0]));

        hr = HRESULT_FROM_WIN32(RegSetValueExW(hKey, sGuid, 0, REG_SZ, (LPBYTE)pszTargetPath, (lstrlenW(pszTargetPath)+1)*sizeof(WCHAR)));

        RegCloseKey(hKey);
    }

3252 3253 3254 3255 3256 3257 3258 3259 3260 3261 3262 3263 3264 3265 3266 3267 3268 3269
    /* make sure destination path exists */
    SHCreateDirectory(NULL, pszTargetPath);

    /* copy content if required */
    if(SUCCEEDED(hr) && (flags & KF_REDIRECT_COPY_CONTENTS) )
    {
        static const WCHAR sWildcard[] = {'\\','*',0};
        WCHAR srcPath[MAX_PATH+1], dstPath[MAX_PATH+1];
        SHFILEOPSTRUCTW fileOp;

        ZeroMemory(srcPath, sizeof(srcPath));
        lstrcpyW(srcPath, lpSrcPath);
        lstrcatW(srcPath, sWildcard);

        ZeroMemory(dstPath, sizeof(dstPath));
        lstrcpyW(dstPath, pszTargetPath);

        ZeroMemory(&fileOp, sizeof(fileOp));
3270 3271 3272 3273 3274 3275

        if(flags & KF_REDIRECT_DEL_SOURCE_CONTENTS)
            fileOp.wFunc = FO_MOVE;
        else
            fileOp.wFunc = FO_COPY;

3276 3277 3278 3279 3280
        fileOp.pFrom = srcPath;
        fileOp.pTo = dstPath;
        fileOp.fFlags = FOF_NO_UI;

        hr = (SHFileOperationW(&fileOp)==0 ? S_OK : E_FAIL);
3281 3282 3283 3284 3285 3286 3287 3288 3289 3290 3291 3292 3293

        if(flags & KF_REDIRECT_DEL_SOURCE_CONTENTS)
        {
            ZeroMemory(srcPath, sizeof(srcPath));
            lstrcpyW(srcPath, lpSrcPath);

            ZeroMemory(&fileOp, sizeof(fileOp));
            fileOp.wFunc = FO_DELETE;
            fileOp.pFrom = srcPath;
            fileOp.fFlags = FOF_NO_UI;

            hr = (SHFileOperationW(&fileOp)==0 ? S_OK : E_FAIL);
        }
3294 3295 3296 3297
    }

    CoTaskMemFree(lpSrcPath);

3298 3299 3300 3301
    return hr;
}


3302 3303
struct knownfolder
{
3304
    IKnownFolder IKnownFolder_iface;
3305 3306
    LONG refs;
    KNOWNFOLDERID id;
3307
    LPWSTR registryPath;
3308 3309 3310 3311
};

static inline struct knownfolder *impl_from_IKnownFolder( IKnownFolder *iface )
{
3312
    return CONTAINING_RECORD( iface, struct knownfolder, IKnownFolder_iface );
3313 3314 3315 3316 3317 3318 3319 3320 3321 3322 3323 3324 3325 3326 3327 3328 3329
}

static ULONG WINAPI knownfolder_AddRef(
    IKnownFolder *iface )
{
    struct knownfolder *knownfolder = impl_from_IKnownFolder( iface );
    return InterlockedIncrement( &knownfolder->refs );
}

static ULONG WINAPI knownfolder_Release(
    IKnownFolder *iface )
{
    struct knownfolder *knownfolder = impl_from_IKnownFolder( iface );
    LONG refs = InterlockedDecrement( &knownfolder->refs );
    if (!refs)
    {
        TRACE("destroying %p\n", knownfolder);
3330
        HeapFree( GetProcessHeap(), 0, knownfolder->registryPath);
3331 3332 3333 3334 3335 3336 3337 3338 3339 3340 3341 3342 3343 3344 3345 3346 3347 3348 3349 3350 3351 3352 3353 3354 3355 3356 3357 3358
        HeapFree( GetProcessHeap(), 0, knownfolder );
    }
    return refs;
}

static HRESULT WINAPI knownfolder_QueryInterface(
    IKnownFolder *iface,
    REFIID riid,
    void **ppv )
{
    struct knownfolder *This = impl_from_IKnownFolder( iface );

    TRACE("%p %s %p\n", This, debugstr_guid( riid ), ppv );

    if ( IsEqualGUID( riid, &IID_IKnownFolder ) ||
         IsEqualGUID( riid, &IID_IUnknown ) )
    {
        *ppv = iface;
    }
    else
    {
        FIXME("interface %s not implemented\n", debugstr_guid(riid));
        return E_NOINTERFACE;
    }
    IKnownFolder_AddRef( iface );
    return S_OK;
}

Mariusz Pluciński's avatar
Mariusz Pluciński committed
3359
static HRESULT knownfolder_set_id(
3360
    struct knownfolder *knownfolder,
3361 3362
    const KNOWNFOLDERID *kfid)
{
3363 3364
    HKEY hKey;
    HRESULT hr;
3365 3366 3367 3368

    TRACE("%s\n", debugstr_guid(kfid));

    knownfolder->id = *kfid;
3369 3370

    /* check is it registry-registered folder */
3371
    hr = get_known_folder_registry_path(kfid, NULL, &knownfolder->registryPath);
3372 3373 3374 3375 3376 3377 3378 3379 3380 3381 3382 3383 3384 3385 3386 3387 3388
    if(SUCCEEDED(hr))
        hr = HRESULT_FROM_WIN32(RegOpenKeyExW(HKEY_LOCAL_MACHINE, knownfolder->registryPath, 0, 0, &hKey));

    if(SUCCEEDED(hr))
    {
        hr = S_OK;
        RegCloseKey(hKey);
    }
    else
    {
        /* This known folder is not registered. To mark it, we set registryPath to NULL */
        HeapFree(GetProcessHeap(), 0, knownfolder->registryPath);
        knownfolder->registryPath = NULL;
        hr = S_OK;
    }

    return hr;
3389 3390 3391 3392 3393 3394 3395 3396 3397 3398 3399 3400 3401 3402 3403 3404 3405 3406
}

static HRESULT WINAPI knownfolder_GetId(
    IKnownFolder *iface,
    KNOWNFOLDERID *pkfid)
{
    struct knownfolder *knownfolder = impl_from_IKnownFolder( iface );

    TRACE("%p\n", pkfid);

    *pkfid = knownfolder->id;
    return S_OK;
}

static HRESULT WINAPI knownfolder_GetCategory(
    IKnownFolder *iface,
    KF_CATEGORY *pCategory)
{
3407 3408 3409 3410 3411
    struct knownfolder *knownfolder = impl_from_IKnownFolder(iface);
    HRESULT hr = S_OK;

    TRACE("%p, %p\n", knownfolder, pCategory);

3412
    /* we cannot get a category for a folder which is not registered */
3413 3414 3415 3416
    if(!knownfolder->registryPath)
        hr = E_FAIL;

    if(SUCCEEDED(hr))
3417
        hr = get_known_folder_category(knownfolder->registryPath, pCategory);
3418 3419

    return hr;
3420 3421 3422 3423 3424 3425 3426 3427 3428 3429 3430 3431
}

static HRESULT WINAPI knownfolder_GetShellItem(
    IKnownFolder *iface,
    DWORD dwFlags,
    REFIID riid,
    void **ppv)
{
    FIXME("0x%08x, %s, %p\n", dwFlags, debugstr_guid(riid), ppv);
    return E_NOTIMPL;
}

3432
static HRESULT get_known_folder_path(
3433
    LPWSTR sFolderId,
3434 3435 3436 3437 3438 3439 3440 3441
    LPWSTR registryPath,
    LPWSTR *ppszPath)
{
    static const WCHAR sBackslash[] = {'\\',0};
    HRESULT hr;
    DWORD dwSize, dwType;
    WCHAR path[MAX_PATH] = {0};
    WCHAR parentGuid[39];
3442
    KF_CATEGORY category;
3443
    LPWSTR parentRegistryPath, parentPath;
3444
    HKEY hRedirectionRootKey = NULL;
3445 3446

    TRACE("(%s, %p)\n", debugstr_w(registryPath), ppszPath);
3447
    *ppszPath = NULL;
3448 3449 3450 3451 3452 3453 3454 3455 3456

    /* check if folder has parent */
    dwSize = sizeof(parentGuid);
    hr = HRESULT_FROM_WIN32(RegGetValueW(HKEY_LOCAL_MACHINE, registryPath, szParentFolder, RRF_RT_REG_SZ, &dwType, parentGuid, &dwSize));
    if(hr == HRESULT_FROM_WIN32(ERROR_FILE_NOT_FOUND)) hr = S_FALSE;

    if(hr == S_OK)
    {
        /* get parent's known folder path (recursive) */
3457
        hr = get_known_folder_registry_path(NULL, parentGuid, &parentRegistryPath);
3458
        if(FAILED(hr)) return hr;
3459

3460
        hr = get_known_folder_path(parentGuid, parentRegistryPath, &parentPath);
3461
        if(FAILED(hr)) {
3462 3463 3464
            HeapFree(GetProcessHeap(), 0, parentRegistryPath);
            return hr;
        }
3465 3466 3467 3468 3469 3470 3471 3472

        lstrcatW(path, parentPath);
        lstrcatW(path, sBackslash);

        HeapFree(GetProcessHeap(), 0, parentRegistryPath);
        HeapFree(GetProcessHeap(), 0, parentPath);
    }

3473
    /* check, if folder was redirected */
3474
    if(SUCCEEDED(hr))
3475
        hr = HRESULT_FROM_WIN32(RegGetValueW(HKEY_LOCAL_MACHINE, registryPath, szCategory, RRF_RT_REG_DWORD, NULL, &category, &dwSize));
3476 3477 3478

    if(SUCCEEDED(hr))
    {
3479 3480 3481 3482
        if(category == KF_CATEGORY_COMMON)
            hRedirectionRootKey = HKEY_LOCAL_MACHINE;
        else if(category == KF_CATEGORY_PERUSER)
            hRedirectionRootKey = HKEY_CURRENT_USER;
3483

3484 3485 3486 3487 3488 3489 3490 3491 3492 3493 3494 3495 3496 3497 3498 3499 3500 3501 3502 3503 3504 3505 3506 3507 3508 3509 3510 3511 3512 3513 3514 3515 3516 3517
        if(hRedirectionRootKey)
        {
            hr = HRESULT_FROM_WIN32(RegGetValueW(hRedirectionRootKey, szKnownFolderRedirections, sFolderId, RRF_RT_REG_SZ, NULL, NULL, &dwSize));

            if(SUCCEEDED(hr))
            {
                *ppszPath = CoTaskMemAlloc(dwSize+(lstrlenW(path)+1)*sizeof(WCHAR));
                if(!*ppszPath) hr = E_OUTOFMEMORY;
            }

            if(SUCCEEDED(hr))
            {
                lstrcpyW(*ppszPath, path);
                hr = HRESULT_FROM_WIN32(RegGetValueW(hRedirectionRootKey, szKnownFolderRedirections, sFolderId, RRF_RT_REG_SZ, NULL, *ppszPath + lstrlenW(path), &dwSize));
            }
        }

        if(!*ppszPath)
        {
            /* no redirection, use previous way - read the relative path from folder definition */
            hr = HRESULT_FROM_WIN32(RegGetValueW(HKEY_LOCAL_MACHINE, registryPath, szRelativePath, RRF_RT_REG_SZ, &dwType, NULL, &dwSize));

            if(SUCCEEDED(hr))
            {
                *ppszPath = CoTaskMemAlloc(dwSize+(lstrlenW(path)+1)*sizeof(WCHAR));
                if(!*ppszPath) hr = E_OUTOFMEMORY;
            }

            if(SUCCEEDED(hr))
            {
                lstrcpyW(*ppszPath, path);
                hr = HRESULT_FROM_WIN32(RegGetValueW(HKEY_LOCAL_MACHINE, registryPath, szRelativePath, RRF_RT_REG_SZ, &dwType, *ppszPath + lstrlenW(path), &dwSize));
            }
        }
3518 3519 3520 3521 3522 3523
    }

    TRACE("returning path: %s\n", debugstr_w(*ppszPath));
    return hr;
}

3524 3525 3526
static HRESULT get_known_folder_path_by_id(
    REFKNOWNFOLDERID folderId,
    LPWSTR lpRegistryPath,
3527 3528 3529
    DWORD dwFlags,
    LPWSTR *ppszPath)
{
3530
    HRESULT hr;
3531
    WCHAR sGuid[39];
3532
    DWORD dwAttributes;
3533

3534
    TRACE("(%s, %s, 0x%08x, %p)\n", debugstr_guid(folderId), debugstr_w(lpRegistryPath), dwFlags, ppszPath);
3535 3536

    /* if this is registry-registered known folder, get path from registry */
3537
    if(lpRegistryPath)
3538
    {
3539
        StringFromGUID2(folderId, sGuid, sizeof(sGuid)/sizeof(sGuid[0]));
3540

3541
        hr = get_known_folder_path(sGuid, lpRegistryPath, ppszPath);
3542 3543 3544
    }
    /* in other case, use older way */
    else
3545
        hr = SHGetKnownFolderPath( folderId, dwFlags, NULL, ppszPath );
3546

3547 3548
    if (FAILED(hr)) return hr;

3549 3550 3551 3552 3553 3554 3555 3556 3557 3558
    /* check if known folder really exists */
    dwAttributes = GetFileAttributesW(*ppszPath);
    if(dwAttributes == INVALID_FILE_ATTRIBUTES || !(dwAttributes & FILE_ATTRIBUTE_DIRECTORY) )
    {
        TRACE("directory %s not found\n", debugstr_w(*ppszPath));
        CoTaskMemFree(*ppszPath);
        *ppszPath = NULL;
        hr = HRESULT_FROM_WIN32(ERROR_FILE_NOT_FOUND);
    }

3559
    return hr;
3560 3561
}

3562 3563 3564 3565 3566 3567 3568 3569 3570 3571 3572
static HRESULT WINAPI knownfolder_GetPath(
    IKnownFolder *iface,
    DWORD dwFlags,
    LPWSTR *ppszPath)
{
    struct knownfolder *knownfolder = impl_from_IKnownFolder( iface );
    TRACE("(%p, 0x%08x, %p)\n", knownfolder, dwFlags, ppszPath);

    return get_known_folder_path_by_id(&knownfolder->id, knownfolder->registryPath, dwFlags, ppszPath);
}

3573 3574 3575 3576 3577
static HRESULT WINAPI knownfolder_SetPath(
    IKnownFolder *iface,
    DWORD dwFlags,
    LPCWSTR pszPath)
{
3578 3579 3580
    struct knownfolder *knownfolder = impl_from_IKnownFolder( iface );
    HRESULT hr = S_OK;

3581
    TRACE("(%p, 0x%08x, %s)\n", knownfolder, dwFlags, debugstr_w(pszPath));
3582 3583 3584 3585 3586 3587

    /* check if the known folder is registered */
    if(!knownfolder->registryPath)
        hr = E_FAIL;

    if(SUCCEEDED(hr))
3588
        hr = redirect_known_folder(&knownfolder->id, NULL, 0, pszPath, 0, NULL, NULL);
3589 3590

    return hr;
3591 3592 3593 3594 3595 3596 3597 3598 3599 3600 3601 3602 3603 3604 3605 3606 3607 3608 3609 3610 3611 3612 3613 3614 3615 3616 3617 3618 3619 3620 3621
}

static HRESULT WINAPI knownfolder_GetIDList(
    IKnownFolder *iface,
    DWORD dwFlags,
    PIDLIST_ABSOLUTE *ppidl)
{
    FIXME("0x%08x, %p\n", dwFlags, ppidl);
    return E_NOTIMPL;
}

static HRESULT WINAPI knownfolder_GetFolderType(
    IKnownFolder *iface,
    FOLDERTYPEID *pftid)
{
    FIXME("%p\n", pftid);
    return E_NOTIMPL;
}

static HRESULT WINAPI knownfolder_GetRedirectionCapabilities(
    IKnownFolder *iface,
    KF_REDIRECTION_CAPABILITIES *pCapabilities)
{
    FIXME("%p\n", pCapabilities);
    return E_NOTIMPL;
}

static HRESULT WINAPI knownfolder_GetFolderDefinition(
    IKnownFolder *iface,
    KNOWNFOLDER_DEFINITION *pKFD)
{
3622 3623 3624 3625 3626 3627 3628 3629 3630 3631 3632 3633 3634 3635 3636 3637 3638 3639 3640 3641 3642 3643 3644 3645
    struct knownfolder *knownfolder = impl_from_IKnownFolder( iface );
    HRESULT hr;
    DWORD dwSize;
    TRACE("(%p, %p)\n", knownfolder, pKFD);

    if(!pKFD) return E_INVALIDARG;

    ZeroMemory(pKFD, sizeof(*pKFD));

    hr = get_known_folder_category(knownfolder->registryPath, &pKFD->category);

    if(SUCCEEDED(hr))
        hr = HRESULT_FROM_WIN32(RegGetValueW(HKEY_LOCAL_MACHINE, knownfolder->registryPath, szName, RRF_RT_REG_SZ, NULL, NULL, &dwSize));

    if(SUCCEEDED(hr))
    {
        pKFD->pszName = CoTaskMemAlloc(dwSize);
        if(!pKFD->pszName) hr = E_OUTOFMEMORY;
    }

    if(SUCCEEDED(hr))
        hr = HRESULT_FROM_WIN32(RegGetValueW(HKEY_LOCAL_MACHINE, knownfolder->registryPath, szName, RRF_RT_REG_SZ, NULL, pKFD->pszName, &dwSize));

    return hr;
3646 3647 3648 3649 3650 3651 3652 3653 3654 3655 3656 3657 3658 3659 3660 3661 3662 3663
}

static const struct IKnownFolderVtbl knownfolder_vtbl =
{
    knownfolder_QueryInterface,
    knownfolder_AddRef,
    knownfolder_Release,
    knownfolder_GetId,
    knownfolder_GetCategory,
    knownfolder_GetShellItem,
    knownfolder_GetPath,
    knownfolder_SetPath,
    knownfolder_GetIDList,
    knownfolder_GetFolderType,
    knownfolder_GetRedirectionCapabilities,
    knownfolder_GetFolderDefinition
};

3664
static HRESULT knownfolder_create( struct knownfolder **knownfolder )
3665 3666 3667 3668 3669 3670
{
    struct knownfolder *kf;

    kf = HeapAlloc( GetProcessHeap(), 0, sizeof(*kf) );
    if (!kf) return E_OUTOFMEMORY;

3671
    kf->IKnownFolder_iface.lpVtbl = &knownfolder_vtbl;
3672 3673
    kf->refs = 1;
    memset( &kf->id, 0, sizeof(kf->id) );
3674
    kf->registryPath = NULL;
3675

3676
    *knownfolder = kf;
3677

3678
    TRACE("returning iface %p\n", &kf->IKnownFolder_iface);
3679 3680 3681 3682 3683
    return S_OK;
}

struct foldermanager
{
3684
    IKnownFolderManager IKnownFolderManager_iface;
3685 3686 3687 3688 3689 3690 3691
    LONG refs;
    UINT num_ids;
    KNOWNFOLDERID *ids;
};

static inline struct foldermanager *impl_from_IKnownFolderManager( IKnownFolderManager *iface )
{
3692
    return CONTAINING_RECORD( iface, struct foldermanager, IKnownFolderManager_iface );
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 3733 3734 3735 3736 3737 3738 3739 3740 3741 3742 3743 3744 3745 3746 3747 3748 3749 3750 3751 3752 3753 3754 3755 3756 3757 3758 3759 3760 3761 3762 3763 3764 3765 3766 3767 3768 3769 3770 3771 3772 3773 3774 3775 3776 3777 3778 3779 3780 3781 3782 3783
}

static ULONG WINAPI foldermanager_AddRef(
    IKnownFolderManager *iface )
{
    struct foldermanager *foldermanager = impl_from_IKnownFolderManager( iface );
    return InterlockedIncrement( &foldermanager->refs );
}

static ULONG WINAPI foldermanager_Release(
    IKnownFolderManager *iface )
{
    struct foldermanager *foldermanager = impl_from_IKnownFolderManager( iface );
    LONG refs = InterlockedDecrement( &foldermanager->refs );
    if (!refs)
    {
        TRACE("destroying %p\n", foldermanager);
        HeapFree( GetProcessHeap(), 0, foldermanager->ids );
        HeapFree( GetProcessHeap(), 0, foldermanager );
    }
    return refs;
}

static HRESULT WINAPI foldermanager_QueryInterface(
    IKnownFolderManager *iface,
    REFIID riid,
    void **ppv )
{
    struct foldermanager *This = impl_from_IKnownFolderManager( iface );

    TRACE("%p %s %p\n", This, debugstr_guid( riid ), ppv );

    if ( IsEqualGUID( riid, &IID_IKnownFolderManager ) ||
         IsEqualGUID( riid, &IID_IUnknown ) )
    {
        *ppv = iface;
    }
    else
    {
        FIXME("interface %s not implemented\n", debugstr_guid(riid));
        return E_NOINTERFACE;
    }
    IKnownFolderManager_AddRef( iface );
    return S_OK;
}

static HRESULT WINAPI foldermanager_FolderIdFromCsidl(
    IKnownFolderManager *iface,
    int nCsidl,
    KNOWNFOLDERID *pfid)
{
    TRACE("%d, %p\n", nCsidl, pfid);

    if (nCsidl >= sizeof(CSIDL_Data) / sizeof(CSIDL_Data[0]))
        return E_INVALIDARG;
    *pfid = *CSIDL_Data[nCsidl].id;
    return S_OK;
}

static HRESULT WINAPI foldermanager_FolderIdToCsidl(
    IKnownFolderManager *iface,
    REFKNOWNFOLDERID rfid,
    int *pnCsidl)
{
    int csidl;

    TRACE("%s, %p\n", debugstr_guid(rfid), pnCsidl);

    csidl = csidl_from_id( rfid );
    if (csidl == -1) return E_INVALIDARG;
    *pnCsidl = csidl;
    return S_OK;
}

static HRESULT WINAPI foldermanager_GetFolderIds(
    IKnownFolderManager *iface,
    KNOWNFOLDERID **ppKFId,
    UINT *pCount)
{
    struct foldermanager *fm = impl_from_IKnownFolderManager( iface );

    TRACE("%p, %p\n", ppKFId, pCount);

    *ppKFId = fm->ids;
    *pCount = fm->num_ids;
    return S_OK;
}

static BOOL is_knownfolder( struct foldermanager *fm, const KNOWNFOLDERID *id )
{
    UINT i;
3784 3785 3786
    HRESULT hr;
    LPWSTR registryPath = NULL;
    HKEY hKey;
3787

3788
    /* TODO: move all entries from "CSIDL_Data" static array to registry known folder descriptions */
3789 3790 3791
    for (i = 0; i < fm->num_ids; i++)
        if (IsEqualGUID( &fm->ids[i], id )) return TRUE;

3792
    hr = get_known_folder_registry_path(id, NULL, &registryPath);
3793 3794 3795 3796 3797 3798 3799 3800 3801 3802
    if(SUCCEEDED(hr))
        hr = HRESULT_FROM_WIN32(RegOpenKeyExW(HKEY_LOCAL_MACHINE, registryPath, 0, 0, &hKey));

    if(SUCCEEDED(hr))
    {
        hr = S_OK;
        RegCloseKey(hKey);
    }

    return hr == S_OK;
3803 3804 3805 3806 3807 3808 3809 3810
}

static HRESULT WINAPI foldermanager_GetFolder(
    IKnownFolderManager *iface,
    REFKNOWNFOLDERID rfid,
    IKnownFolder **ppkf)
{
    struct foldermanager *fm = impl_from_IKnownFolderManager( iface );
3811
    struct knownfolder *kf;
3812 3813 3814 3815 3816 3817 3818 3819 3820
    HRESULT hr;

    TRACE("%s, %p\n", debugstr_guid(rfid), ppkf);

    if (!is_knownfolder( fm, rfid ))
    {
        WARN("unknown folder\n");
        return E_INVALIDARG;
    }
3821
    hr = knownfolder_create( &kf );
3822
    if (SUCCEEDED( hr ))
3823 3824 3825 3826 3827 3828
    {
        hr = knownfolder_set_id( kf, rfid );
        *ppkf = &kf->IKnownFolder_iface;
    }
    else
        *ppkf = NULL;
3829 3830 3831 3832 3833 3834 3835 3836 3837 3838 3839 3840 3841 3842 3843 3844 3845 3846

    return hr;
}

static HRESULT WINAPI foldermanager_GetFolderByName(
    IKnownFolderManager *iface,
    LPCWSTR pszCanonicalName,
    IKnownFolder **ppkf)
{
    FIXME("%s, %p\n", debugstr_w(pszCanonicalName), ppkf);
    return E_NOTIMPL;
}

static HRESULT WINAPI foldermanager_RegisterFolder(
    IKnownFolderManager *iface,
    REFKNOWNFOLDERID rfid,
    KNOWNFOLDER_DEFINITION const *pKFD)
{
3847 3848 3849 3850 3851 3852
    HRESULT hr;
    HKEY hKey = NULL;
    DWORD dwDisp;
    LPWSTR registryPath = NULL;
    TRACE("(%p, %s, %p)\n", iface, debugstr_guid(rfid), pKFD);

3853
    hr = get_known_folder_registry_path(rfid, NULL, &registryPath);
3854 3855 3856 3857 3858 3859 3860 3861 3862 3863 3864 3865 3866 3867 3868 3869
    TRACE("registry path: %s\n", debugstr_w(registryPath));

    if(SUCCEEDED(hr))
        hr = HRESULT_FROM_WIN32(RegCreateKeyExW(HKEY_LOCAL_MACHINE, registryPath, 0, NULL, 0, KEY_WRITE, 0, &hKey, &dwDisp));

    if(SUCCEEDED(hr))
    {
        if(dwDisp == REG_OPENED_EXISTING_KEY)
            hr = E_FAIL;

        if(SUCCEEDED(hr))
            hr = HRESULT_FROM_WIN32(RegSetValueExW(hKey, szCategory, 0, REG_DWORD, (LPBYTE)&pKFD->category, sizeof(pKFD->category)));

        if(SUCCEEDED(hr))
            hr = HRESULT_FROM_WIN32(RegSetValueExW(hKey, szName, 0, REG_SZ, (LPBYTE)pKFD->pszName, (lstrlenW(pKFD->pszName)+1)*sizeof(WCHAR) ));

3870 3871 3872 3873 3874 3875 3876 3877 3878
        if(SUCCEEDED(hr) && !IsEqualGUID(&pKFD->fidParent, &GUID_NULL))
        {
            WCHAR sParentGuid[39];
            StringFromGUID2(&pKFD->fidParent, sParentGuid, sizeof(sParentGuid)/sizeof(sParentGuid[0]));

            /* this known folder has parent folder */
            hr = HRESULT_FROM_WIN32(RegSetValueExW(hKey, szParentFolder, 0, REG_SZ, (LPBYTE)sParentGuid, sizeof(sParentGuid)));
        }

3879
        if(SUCCEEDED(hr) && pKFD->category != KF_CATEGORY_VIRTUAL)
3880 3881 3882 3883 3884 3885 3886
        {
            if(!pKFD->pszRelativePath)
                hr = E_INVALIDARG;

            if(SUCCEEDED(hr))
                hr = HRESULT_FROM_WIN32(RegSetValueExW(hKey, szRelativePath, 0, REG_SZ, (LPBYTE)pKFD->pszRelativePath, (lstrlenW(pKFD->pszRelativePath)+1)*sizeof(WCHAR) ));
        }
3887

3888
        RegCloseKey(hKey);
3889 3890 3891

        if(FAILED(hr))
            SHDeleteKeyW(HKEY_LOCAL_MACHINE, registryPath);
3892 3893 3894 3895
    }

    HeapFree(GetProcessHeap(), 0, registryPath);
    return hr;
3896 3897 3898 3899 3900 3901
}

static HRESULT WINAPI foldermanager_UnregisterFolder(
    IKnownFolderManager *iface,
    REFKNOWNFOLDERID rfid)
{
3902 3903 3904 3905
    HRESULT hr;
    LPWSTR registryPath = NULL;
    TRACE("(%p, %s)\n", iface, debugstr_guid(rfid));

3906
    hr = get_known_folder_registry_path(rfid, NULL, &registryPath);
3907 3908

    if(SUCCEEDED(hr))
3909
        hr = HRESULT_FROM_WIN32(SHDeleteKeyW(HKEY_LOCAL_MACHINE, registryPath));
3910 3911 3912

    HeapFree(GetProcessHeap(), 0, registryPath);
    return hr;
3913 3914 3915 3916 3917 3918 3919 3920 3921 3922 3923 3924 3925 3926 3927 3928 3929 3930 3931 3932 3933 3934 3935 3936 3937 3938 3939 3940 3941 3942 3943
}

static HRESULT WINAPI foldermanager_FindFolderFromPath(
    IKnownFolderManager *iface,
    LPCWSTR pszPath,
    FFFP_MODE mode,
    IKnownFolder **ppkf)
{
    FIXME("%s, 0x%08x, %p\n", debugstr_w(pszPath), mode, ppkf);
    return E_NOTIMPL;
}

static HRESULT WINAPI foldermanager_FindFolderFromIDList(
    IKnownFolderManager *iface,
    PCIDLIST_ABSOLUTE pidl,
    IKnownFolder **ppkf)
{
    FIXME("%p, %p\n", pidl, ppkf);
    return E_NOTIMPL;
}

static HRESULT WINAPI foldermanager_Redirect(
    IKnownFolderManager *iface,
    REFKNOWNFOLDERID rfid,
    HWND hwnd,
    KF_REDIRECT_FLAGS flags,
    LPCWSTR pszTargetPath,
    UINT cFolders,
    KNOWNFOLDERID const *pExclusion,
    LPWSTR *ppszError)
{
3944
    return redirect_known_folder(rfid, hwnd, flags, pszTargetPath, cFolders, pExclusion, ppszError);
3945 3946 3947 3948 3949 3950 3951 3952 3953 3954 3955 3956 3957 3958 3959 3960 3961 3962 3963 3964 3965 3966 3967 3968 3969 3970 3971
}

static const struct IKnownFolderManagerVtbl foldermanager_vtbl =
{
    foldermanager_QueryInterface,
    foldermanager_AddRef,
    foldermanager_Release,
    foldermanager_FolderIdFromCsidl,
    foldermanager_FolderIdToCsidl,
    foldermanager_GetFolderIds,
    foldermanager_GetFolder,
    foldermanager_GetFolderByName,
    foldermanager_RegisterFolder,
    foldermanager_UnregisterFolder,
    foldermanager_FindFolderFromPath,
    foldermanager_FindFolderFromIDList,
    foldermanager_Redirect
};

static HRESULT foldermanager_create( void **ppv )
{
    UINT i, j;
    struct foldermanager *fm;

    fm = HeapAlloc( GetProcessHeap(), 0, sizeof(*fm) );
    if (!fm) return E_OUTOFMEMORY;

3972
    fm->IKnownFolderManager_iface.lpVtbl = &foldermanager_vtbl;
3973 3974 3975 3976 3977 3978 3979 3980 3981 3982 3983 3984 3985 3986 3987 3988 3989 3990 3991 3992 3993 3994
    fm->refs = 1;
    fm->num_ids = 0;

    for (i = 0; i < sizeof(CSIDL_Data) / sizeof(CSIDL_Data[0]); i++)
    {
        if (!IsEqualGUID( CSIDL_Data[i].id, &GUID_NULL )) fm->num_ids++;
    }
    fm->ids = HeapAlloc( GetProcessHeap(), 0, fm->num_ids * sizeof(KNOWNFOLDERID) );
    if (!fm->ids)
    {
        HeapFree( GetProcessHeap(), 0, fm );
        return E_OUTOFMEMORY;
    }
    for (i = j = 0; i < sizeof(CSIDL_Data) / sizeof(CSIDL_Data[0]); i++)
    {
        if (!IsEqualGUID( CSIDL_Data[i].id, &GUID_NULL ))
        {
            fm->ids[j] = *CSIDL_Data[i].id;
            j++;
        }
    }
    TRACE("found %u known folders\n", fm->num_ids);
3995
    *ppv = &fm->IKnownFolderManager_iface;
3996 3997 3998 3999 4000 4001 4002 4003 4004 4005 4006 4007 4008 4009 4010 4011

    TRACE("returning iface %p\n", *ppv);
    return S_OK;
}

HRESULT WINAPI KnownFolderManager_Constructor( IUnknown *punk, REFIID riid, void **ppv )
{
    TRACE("%p, %s, %p\n", punk, debugstr_guid(riid), ppv);

    if (!ppv)
        return E_POINTER;
    if (punk)
        return CLASS_E_NOAGGREGATION;

    return foldermanager_create( ppv );
}