shell32: Convert dll registration to the IRegistrar mechanism.
[wine] / dlls / shell32 / shellpath.c
1 /*
2  * Path Functions
3  *
4  * Copyright 1998, 1999, 2000 Juergen Schmied
5  * Copyright 2004 Juan Lang
6  *
7  * This library is free software; you can redistribute it and/or
8  * modify it under the terms of the GNU Lesser General Public
9  * License as published by the Free Software Foundation; either
10  * version 2.1 of the License, or (at your option) any later version.
11  *
12  * This library is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15  * Lesser General Public License for more details.
16  *
17  * You should have received a copy of the GNU Lesser General Public
18  * 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  * NOTES:
22  *
23  * Many of these functions are in SHLWAPI.DLL also
24  *
25  */
26
27 #define COBJMACROS
28
29 #include "config.h"
30 #include "wine/port.h"
31
32 #include <stdio.h>
33 #include <stdarg.h>
34 #include <string.h>
35 #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 #include "wingdi.h"
42 #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"
49 #include "pidl.h"
50 #include "wine/unicode.h"
51 #include "shlwapi.h"
52 #include "xdg.h"
53 #include "sddl.h"
54 #define INITGUID
55 #include "knownfolders.h"
56 #include "shobjidl.h"
57
58 WINE_DEFAULT_DEBUG_CHANNEL(shell);
59
60 static const BOOL is_win64 = sizeof(void *) > sizeof(int);
61
62 /*
63         ########## Combining and Constructing paths ##########
64 */
65
66 /*************************************************************************
67  * PathAppend           [SHELL32.36]
68  */
69 BOOL WINAPI PathAppendAW(
70         LPVOID lpszPath1,
71         LPCVOID lpszPath2)
72 {
73         if (SHELL_OsIsUnicode())
74           return PathAppendW(lpszPath1, lpszPath2);
75         return PathAppendA(lpszPath1, lpszPath2);
76 }
77
78 /*************************************************************************
79  * PathCombine   [SHELL32.37]
80  */
81 LPVOID WINAPI PathCombineAW(
82         LPVOID szDest,
83         LPCVOID lpszDir,
84         LPCVOID lpszFile)
85 {
86         if (SHELL_OsIsUnicode())
87           return PathCombineW( szDest, lpszDir, lpszFile );
88         return PathCombineA( szDest, lpszDir, lpszFile );
89 }
90
91 /*************************************************************************
92  * PathAddBackslash             [SHELL32.32]
93  */
94 LPVOID WINAPI PathAddBackslashAW(LPVOID lpszPath)
95 {
96         if(SHELL_OsIsUnicode())
97           return PathAddBackslashW(lpszPath);
98         return PathAddBackslashA(lpszPath);
99 }
100
101 /*************************************************************************
102  * PathBuildRoot                [SHELL32.30]
103  */
104 LPVOID WINAPI PathBuildRootAW(LPVOID lpszPath, int drive)
105 {
106         if(SHELL_OsIsUnicode())
107           return PathBuildRootW(lpszPath, drive);
108         return PathBuildRootA(lpszPath, drive);
109 }
110
111 /*
112         Extracting Component Parts
113 */
114
115 /*************************************************************************
116  * PathFindFileName     [SHELL32.34]
117  */
118 LPVOID WINAPI PathFindFileNameAW(LPCVOID lpszPath)
119 {
120         if(SHELL_OsIsUnicode())
121           return PathFindFileNameW(lpszPath);
122         return PathFindFileNameA(lpszPath);
123 }
124
125 /*************************************************************************
126  * PathFindExtension            [SHELL32.31]
127  */
128 LPVOID WINAPI PathFindExtensionAW(LPCVOID lpszPath)
129 {
130         if (SHELL_OsIsUnicode())
131           return PathFindExtensionW(lpszPath);
132         return PathFindExtensionA(lpszPath);
133
134 }
135
136 /*************************************************************************
137  * PathGetExtensionA            [internal]
138  *
139  * NOTES
140  *  exported by ordinal
141  *  return value points to the first char after the dot
142  */
143 static LPSTR PathGetExtensionA(LPCSTR lpszPath)
144 {
145         TRACE("(%s)\n",lpszPath);
146
147         lpszPath = PathFindExtensionA(lpszPath);
148         return (LPSTR)(*lpszPath?(lpszPath+1):lpszPath);
149 }
150
151 /*************************************************************************
152  * PathGetExtensionW            [internal]
153  */
154 static LPWSTR PathGetExtensionW(LPCWSTR lpszPath)
155 {
156         TRACE("(%s)\n",debugstr_w(lpszPath));
157
158         lpszPath = PathFindExtensionW(lpszPath);
159         return (LPWSTR)(*lpszPath?(lpszPath+1):lpszPath);
160 }
161
162 /*************************************************************************
163  * PathGetExtension             [SHELL32.158]
164  */
165 LPVOID WINAPI PathGetExtensionAW(LPCVOID lpszPath,DWORD void1, DWORD void2)
166 {
167         if (SHELL_OsIsUnicode())
168           return PathGetExtensionW(lpszPath);
169         return PathGetExtensionA(lpszPath);
170 }
171
172 /*************************************************************************
173  * PathGetArgs  [SHELL32.52]
174  */
175 LPVOID WINAPI PathGetArgsAW(LPVOID lpszPath)
176 {
177         if (SHELL_OsIsUnicode())
178           return PathGetArgsW(lpszPath);
179         return PathGetArgsA(lpszPath);
180 }
181
182 /*************************************************************************
183  * PathGetDriveNumber   [SHELL32.57]
184  */
185 int WINAPI PathGetDriveNumberAW(LPVOID lpszPath)
186 {
187         if (SHELL_OsIsUnicode())
188           return PathGetDriveNumberW(lpszPath);
189         return PathGetDriveNumberA(lpszPath);
190 }
191
192 /*************************************************************************
193  * PathRemoveFileSpec [SHELL32.35]
194  */
195 BOOL WINAPI PathRemoveFileSpecAW(LPVOID lpszPath)
196 {
197         if (SHELL_OsIsUnicode())
198           return PathRemoveFileSpecW(lpszPath);
199         return PathRemoveFileSpecA(lpszPath);
200 }
201
202 /*************************************************************************
203  * PathStripPath        [SHELL32.38]
204  */
205 void WINAPI PathStripPathAW(LPVOID lpszPath)
206 {
207         if (SHELL_OsIsUnicode())
208             PathStripPathW(lpszPath);
209         else
210             PathStripPathA(lpszPath);
211 }
212
213 /*************************************************************************
214  * PathStripToRoot      [SHELL32.50]
215  */
216 BOOL WINAPI PathStripToRootAW(LPVOID lpszPath)
217 {
218         if (SHELL_OsIsUnicode())
219           return PathStripToRootW(lpszPath);
220         return PathStripToRootA(lpszPath);
221 }
222
223 /*************************************************************************
224  * PathRemoveArgs       [SHELL32.251]
225  */
226 void WINAPI PathRemoveArgsAW(LPVOID lpszPath)
227 {
228         if (SHELL_OsIsUnicode())
229             PathRemoveArgsW(lpszPath);
230         else
231             PathRemoveArgsA(lpszPath);
232 }
233
234 /*************************************************************************
235  * PathRemoveExtension  [SHELL32.250]
236  */
237 void WINAPI PathRemoveExtensionAW(LPVOID lpszPath)
238 {
239         if (SHELL_OsIsUnicode())
240             PathRemoveExtensionW(lpszPath);
241         else
242             PathRemoveExtensionA(lpszPath);
243 }
244
245
246 /*
247         Path Manipulations
248 */
249
250 /*************************************************************************
251  * PathGetShortPathA [internal]
252  */
253 static void PathGetShortPathA(LPSTR pszPath)
254 {
255         CHAR path[MAX_PATH];
256
257         TRACE("%s\n", pszPath);
258
259         if (GetShortPathNameA(pszPath, path, MAX_PATH))
260         {
261           lstrcpyA(pszPath, path);
262         }
263 }
264
265 /*************************************************************************
266  * PathGetShortPathW [internal]
267  */
268 static void PathGetShortPathW(LPWSTR pszPath)
269 {
270         WCHAR path[MAX_PATH];
271
272         TRACE("%s\n", debugstr_w(pszPath));
273
274         if (GetShortPathNameW(pszPath, path, MAX_PATH))
275         {
276           lstrcpyW(pszPath, path);
277         }
278 }
279
280 /*************************************************************************
281  * PathGetShortPath [SHELL32.92]
282  */
283 VOID WINAPI PathGetShortPathAW(LPVOID pszPath)
284 {
285         if(SHELL_OsIsUnicode())
286           PathGetShortPathW(pszPath);
287         PathGetShortPathA(pszPath);
288 }
289
290 /*************************************************************************
291  * PathRemoveBlanks [SHELL32.33]
292  */
293 void WINAPI PathRemoveBlanksAW(LPVOID str)
294 {
295         if(SHELL_OsIsUnicode())
296             PathRemoveBlanksW(str);
297         else
298             PathRemoveBlanksA(str);
299 }
300
301 /*************************************************************************
302  * PathQuoteSpaces [SHELL32.55]
303  */
304 VOID WINAPI PathQuoteSpacesAW (LPVOID lpszPath)
305 {
306         if(SHELL_OsIsUnicode())
307             PathQuoteSpacesW(lpszPath);
308         else
309             PathQuoteSpacesA(lpszPath);
310 }
311
312 /*************************************************************************
313  * PathUnquoteSpaces [SHELL32.56]
314  */
315 VOID WINAPI PathUnquoteSpacesAW(LPVOID str)
316 {
317         if(SHELL_OsIsUnicode())
318           PathUnquoteSpacesW(str);
319         else
320           PathUnquoteSpacesA(str);
321 }
322
323 /*************************************************************************
324  * PathParseIconLocation        [SHELL32.249]
325  */
326 int WINAPI PathParseIconLocationAW (LPVOID lpszPath)
327 {
328         if(SHELL_OsIsUnicode())
329           return PathParseIconLocationW(lpszPath);
330         return PathParseIconLocationA(lpszPath);
331 }
332
333 /*
334         ########## Path Testing ##########
335 */
336 /*************************************************************************
337  * PathIsUNC            [SHELL32.39]
338  */
339 BOOL WINAPI PathIsUNCAW (LPCVOID lpszPath)
340 {
341         if (SHELL_OsIsUnicode())
342           return PathIsUNCW( lpszPath );
343         return PathIsUNCA( lpszPath );
344 }
345
346 /*************************************************************************
347  *  PathIsRelative      [SHELL32.40]
348  */
349 BOOL WINAPI PathIsRelativeAW (LPCVOID lpszPath)
350 {
351         if (SHELL_OsIsUnicode())
352           return PathIsRelativeW( lpszPath );
353         return PathIsRelativeA( lpszPath );
354 }
355
356 /*************************************************************************
357  * PathIsRoot           [SHELL32.29]
358  */
359 BOOL WINAPI PathIsRootAW(LPCVOID lpszPath)
360 {
361         if (SHELL_OsIsUnicode())
362           return PathIsRootW(lpszPath);
363         return PathIsRootA(lpszPath);
364 }
365
366 /*************************************************************************
367  *  PathIsExeA          [internal]
368  */
369 static BOOL PathIsExeA (LPCSTR lpszPath)
370 {
371         LPCSTR lpszExtension = PathGetExtensionA(lpszPath);
372         int i;
373         static const char * const lpszExtensions[] =
374             {"exe", "com", "pif", "cmd", "bat", "scf", "scr", NULL };
375
376         TRACE("path=%s\n",lpszPath);
377
378         for(i=0; lpszExtensions[i]; i++)
379           if (!lstrcmpiA(lpszExtension,lpszExtensions[i])) return TRUE;
380
381         return FALSE;
382 }
383
384 /*************************************************************************
385  *  PathIsExeW          [internal]
386  */
387 static BOOL PathIsExeW (LPCWSTR lpszPath)
388 {
389         LPCWSTR lpszExtension = PathGetExtensionW(lpszPath);
390         int i;
391         static const WCHAR lpszExtensions[][4] =
392             {{'e','x','e','\0'}, {'c','o','m','\0'}, {'p','i','f','\0'},
393              {'c','m','d','\0'}, {'b','a','t','\0'}, {'s','c','f','\0'},
394              {'s','c','r','\0'}, {'\0'} };
395
396         TRACE("path=%s\n",debugstr_w(lpszPath));
397
398         for(i=0; lpszExtensions[i][0]; i++)
399           if (!strcmpiW(lpszExtension,lpszExtensions[i])) return TRUE;
400
401         return FALSE;
402 }
403
404 /*************************************************************************
405  *  PathIsExe           [SHELL32.43]
406  */
407 BOOL WINAPI PathIsExeAW (LPCVOID path)
408 {
409         if (SHELL_OsIsUnicode())
410           return PathIsExeW (path);
411         return PathIsExeA(path);
412 }
413
414 /*************************************************************************
415  * PathIsDirectory      [SHELL32.159]
416  */
417 BOOL WINAPI PathIsDirectoryAW (LPCVOID lpszPath)
418 {
419         if (SHELL_OsIsUnicode())
420           return PathIsDirectoryW (lpszPath);
421         return PathIsDirectoryA (lpszPath);
422 }
423
424 /*************************************************************************
425  * PathFileExists       [SHELL32.45]
426  */
427 BOOL WINAPI PathFileExistsAW (LPCVOID lpszPath)
428 {
429         if (SHELL_OsIsUnicode())
430           return PathFileExistsW (lpszPath);
431         return PathFileExistsA (lpszPath);
432 }
433
434 /*************************************************************************
435  * PathMatchSpec        [SHELL32.46]
436  */
437 BOOL WINAPI PathMatchSpecAW(LPVOID name, LPVOID mask)
438 {
439         if (SHELL_OsIsUnicode())
440           return PathMatchSpecW( name, mask );
441         return PathMatchSpecA( name, mask );
442 }
443
444 /*************************************************************************
445  * PathIsSameRoot       [SHELL32.650]
446  */
447 BOOL WINAPI PathIsSameRootAW(LPCVOID lpszPath1, LPCVOID lpszPath2)
448 {
449         if (SHELL_OsIsUnicode())
450           return PathIsSameRootW(lpszPath1, lpszPath2);
451         return PathIsSameRootA(lpszPath1, lpszPath2);
452 }
453
454 /*************************************************************************
455  * IsLFNDriveA          [SHELL32.41]
456  */
457 BOOL WINAPI IsLFNDriveA(LPCSTR lpszPath)
458 {
459     DWORD       fnlen;
460
461     if (!GetVolumeInformationA(lpszPath, NULL, 0, NULL, &fnlen, NULL, NULL, 0))
462         return FALSE;
463     return fnlen > 12;
464 }
465
466 /*************************************************************************
467  * IsLFNDriveW          [SHELL32.42]
468  */
469 BOOL WINAPI IsLFNDriveW(LPCWSTR lpszPath)
470 {
471     DWORD       fnlen;
472
473     if (!GetVolumeInformationW(lpszPath, NULL, 0, NULL, &fnlen, NULL, NULL, 0))
474         return FALSE;
475     return fnlen > 12;
476 }
477
478 /*************************************************************************
479  * IsLFNDrive           [SHELL32.119]
480  */
481 BOOL WINAPI IsLFNDriveAW(LPCVOID lpszPath)
482 {
483         if (SHELL_OsIsUnicode())
484           return IsLFNDriveW(lpszPath);
485         return IsLFNDriveA(lpszPath);
486 }
487
488 /*
489         ########## Creating Something Unique ##########
490 */
491 /*************************************************************************
492  * PathMakeUniqueNameA  [internal]
493  */
494 static BOOL PathMakeUniqueNameA(
495         LPSTR lpszBuffer,
496         DWORD dwBuffSize,
497         LPCSTR lpszShortName,
498         LPCSTR lpszLongName,
499         LPCSTR lpszPathName)
500 {
501         FIXME("%p %u %s %s %s stub\n",
502          lpszBuffer, dwBuffSize, debugstr_a(lpszShortName),
503          debugstr_a(lpszLongName), debugstr_a(lpszPathName));
504         return TRUE;
505 }
506
507 /*************************************************************************
508  * PathMakeUniqueNameW  [internal]
509  */
510 static BOOL PathMakeUniqueNameW(
511         LPWSTR lpszBuffer,
512         DWORD dwBuffSize,
513         LPCWSTR lpszShortName,
514         LPCWSTR lpszLongName,
515         LPCWSTR lpszPathName)
516 {
517         FIXME("%p %u %s %s %s stub\n",
518          lpszBuffer, dwBuffSize, debugstr_w(lpszShortName),
519          debugstr_w(lpszLongName), debugstr_w(lpszPathName));
520         return TRUE;
521 }
522
523 /*************************************************************************
524  * PathMakeUniqueName   [SHELL32.47]
525  */
526 BOOL WINAPI PathMakeUniqueNameAW(
527         LPVOID lpszBuffer,
528         DWORD dwBuffSize,
529         LPCVOID lpszShortName,
530         LPCVOID lpszLongName,
531         LPCVOID lpszPathName)
532 {
533         if (SHELL_OsIsUnicode())
534           return PathMakeUniqueNameW(lpszBuffer,dwBuffSize, lpszShortName,lpszLongName,lpszPathName);
535         return PathMakeUniqueNameA(lpszBuffer,dwBuffSize, lpszShortName,lpszLongName,lpszPathName);
536 }
537
538 /*************************************************************************
539  * PathYetAnotherMakeUniqueName [SHELL32.75]
540  *
541  * NOTES
542  *     exported by ordinal
543  */
544 BOOL WINAPI PathYetAnotherMakeUniqueName(
545         LPWSTR lpszBuffer,
546         LPCWSTR lpszPathName,
547         LPCWSTR lpszShortName,
548         LPCWSTR lpszLongName)
549 {
550     FIXME("(%p, %s, %s ,%s):stub.\n",
551           lpszBuffer, debugstr_w(lpszPathName), debugstr_w(lpszShortName), debugstr_w(lpszLongName));
552     return TRUE;
553 }
554
555
556 /*
557         ########## cleaning and resolving paths ##########
558  */
559
560 /*************************************************************************
561  * PathFindOnPath       [SHELL32.145]
562  */
563 BOOL WINAPI PathFindOnPathAW(LPVOID sFile, LPCVOID *sOtherDirs)
564 {
565         if (SHELL_OsIsUnicode())
566           return PathFindOnPathW(sFile, (LPCWSTR *)sOtherDirs);
567         return PathFindOnPathA(sFile, (LPCSTR *)sOtherDirs);
568 }
569
570 /*************************************************************************
571  * PathCleanupSpec      [SHELL32.171]
572  *
573  * lpszFile is changed in place.
574  */
575 int WINAPI PathCleanupSpec( LPCWSTR lpszPathW, LPWSTR lpszFileW )
576 {
577     int i = 0;
578     DWORD rc = 0;
579     int length = 0;
580
581     if (SHELL_OsIsUnicode())
582     {
583         LPWSTR p = lpszFileW;
584
585         TRACE("Cleanup %s\n",debugstr_w(lpszFileW));
586
587         if (lpszPathW)
588             length = strlenW(lpszPathW);
589
590         while (*p)
591         {
592             int gct = PathGetCharTypeW(*p);
593             if (gct == GCT_INVALID || gct == GCT_WILD || gct == GCT_SEPARATOR)
594             {
595                 lpszFileW[i]='-';
596                 rc |= PCS_REPLACEDCHAR;
597             }
598             else
599                 lpszFileW[i]=*p;
600             i++;
601             p++;
602             if (length + i == MAX_PATH)
603             {
604                 rc |= PCS_FATAL | PCS_PATHTOOLONG;
605                 break;
606             }
607         }
608         lpszFileW[i]=0;
609     }
610     else
611     {
612         LPSTR lpszFileA = (LPSTR)lpszFileW;
613         LPCSTR lpszPathA = (LPCSTR)lpszPathW;
614         LPSTR p = lpszFileA;
615
616         TRACE("Cleanup %s\n",debugstr_a(lpszFileA));
617
618         if (lpszPathA)
619             length = strlen(lpszPathA);
620
621         while (*p)
622         {
623             int gct = PathGetCharTypeA(*p);
624             if (gct == GCT_INVALID || gct == GCT_WILD || gct == GCT_SEPARATOR)
625             {
626                 lpszFileA[i]='-';
627                 rc |= PCS_REPLACEDCHAR;
628             }
629             else
630                 lpszFileA[i]=*p;
631             i++;
632             p++;
633             if (length + i == MAX_PATH)
634             {
635                 rc |= PCS_FATAL | PCS_PATHTOOLONG;
636                 break;
637             }
638         }
639         lpszFileA[i]=0;
640     }
641     return rc;
642 }
643
644 /*************************************************************************
645  * PathQualifyA         [SHELL32]
646  */
647 static BOOL PathQualifyA(LPCSTR pszPath)
648 {
649         FIXME("%s\n",pszPath);
650         return 0;
651 }
652
653 /*************************************************************************
654  * PathQualifyW         [SHELL32]
655  */
656 static BOOL PathQualifyW(LPCWSTR pszPath)
657 {
658         FIXME("%s\n",debugstr_w(pszPath));
659         return 0;
660 }
661
662 /*************************************************************************
663  * PathQualify  [SHELL32.49]
664  */
665 BOOL WINAPI PathQualifyAW(LPCVOID pszPath)
666 {
667         if (SHELL_OsIsUnicode())
668           return PathQualifyW(pszPath);
669         return PathQualifyA(pszPath);
670 }
671
672 static BOOL PathResolveA(
673         LPSTR lpszPath,
674         LPCSTR *alpszPaths,
675         DWORD dwFlags)
676 {
677         FIXME("(%s,%p,0x%08x),stub!\n",
678           lpszPath, *alpszPaths, dwFlags);
679         return 0;
680 }
681
682 static BOOL PathResolveW(
683         LPWSTR lpszPath,
684         LPCWSTR *alpszPaths,
685         DWORD dwFlags)
686 {
687         FIXME("(%s,%p,0x%08x),stub!\n",
688           debugstr_w(lpszPath), debugstr_w(*alpszPaths), dwFlags);
689         return 0;
690 }
691
692 /*************************************************************************
693  * PathResolve [SHELL32.51]
694  */
695 BOOL WINAPI PathResolveAW(
696         LPVOID lpszPath,
697         LPCVOID *alpszPaths,
698         DWORD dwFlags)
699 {
700         if (SHELL_OsIsUnicode())
701           return PathResolveW(lpszPath, (LPCWSTR*)alpszPaths, dwFlags);
702         return PathResolveA(lpszPath, (LPCSTR*)alpszPaths, dwFlags);
703 }
704
705 /*************************************************************************
706 *       PathProcessCommandA
707 */
708 static LONG PathProcessCommandA (
709         LPCSTR lpszPath,
710         LPSTR lpszBuff,
711         DWORD dwBuffSize,
712         DWORD dwFlags)
713 {
714         FIXME("%s %p 0x%04x 0x%04x stub\n",
715         lpszPath, lpszBuff, dwBuffSize, dwFlags);
716         if(!lpszPath) return -1;
717         if(lpszBuff) strcpy(lpszBuff, lpszPath);
718         return strlen(lpszPath);
719 }
720
721 /*************************************************************************
722 *       PathProcessCommandW
723 */
724 static LONG PathProcessCommandW (
725         LPCWSTR lpszPath,
726         LPWSTR lpszBuff,
727         DWORD dwBuffSize,
728         DWORD dwFlags)
729 {
730         FIXME("(%s, %p, 0x%04x, 0x%04x) stub\n",
731         debugstr_w(lpszPath), lpszBuff, dwBuffSize, dwFlags);
732         if(!lpszPath) return -1;
733         if(lpszBuff) strcpyW(lpszBuff, lpszPath);
734         return strlenW(lpszPath);
735 }
736
737 /*************************************************************************
738 *       PathProcessCommand (SHELL32.653)
739 */
740 LONG WINAPI PathProcessCommandAW (
741         LPCVOID lpszPath,
742         LPVOID lpszBuff,
743         DWORD dwBuffSize,
744         DWORD dwFlags)
745 {
746         if (SHELL_OsIsUnicode())
747           return PathProcessCommandW(lpszPath, lpszBuff, dwBuffSize, dwFlags);
748         return PathProcessCommandA(lpszPath, lpszBuff, dwBuffSize, dwFlags);
749 }
750
751 /*
752         ########## special ##########
753 */
754
755 /*************************************************************************
756  * PathSetDlgItemPath (SHELL32.48)
757  */
758 VOID WINAPI PathSetDlgItemPathAW(HWND hDlg, int id, LPCVOID pszPath)
759 {
760         if (SHELL_OsIsUnicode())
761             PathSetDlgItemPathW(hDlg, id, pszPath);
762         else
763             PathSetDlgItemPathA(hDlg, id, pszPath);
764 }
765
766 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'};
767 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'};
768 static const WCHAR AppDataW[] = {'A','p','p','D','a','t','a','\0'};
769 static const WCHAR CacheW[] = {'C','a','c','h','e','\0'};
770 static const WCHAR CD_BurningW[] = {'C','D',' ','B','u','r','n','i','n','g','\0'};
771 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'};
772 static const WCHAR Common_AppDataW[] = {'C','o','m','m','o','n',' ','A','p','p','D','a','t','a','\0'};
773 static const WCHAR Common_DesktopW[] = {'C','o','m','m','o','n',' ','D','e','s','k','t','o','p','\0'};
774 static const WCHAR Common_DocumentsW[] = {'C','o','m','m','o','n',' ','D','o','c','u','m','e','n','t','s','\0'};
775 static const WCHAR Common_FavoritesW[] = {'C','o','m','m','o','n',' ','F','a','v','o','r','i','t','e','s','\0'};
776 static const WCHAR CommonFilesDirW[] = {'C','o','m','m','o','n','F','i','l','e','s','D','i','r','\0'};
777 static const WCHAR CommonFilesDirX86W[] = {'C','o','m','m','o','n','F','i','l','e','s','D','i','r',' ','(','x','8','6',')','\0'};
778 static const WCHAR CommonMusicW[] = {'C','o','m','m','o','n','M','u','s','i','c','\0'};
779 static const WCHAR CommonPicturesW[] = {'C','o','m','m','o','n','P','i','c','t','u','r','e','s','\0'};
780 static const WCHAR Common_ProgramsW[] = {'C','o','m','m','o','n',' ','P','r','o','g','r','a','m','s','\0'};
781 static const WCHAR Common_StartUpW[] = {'C','o','m','m','o','n',' ','S','t','a','r','t','U','p','\0'};
782 static const WCHAR Common_Start_MenuW[] = {'C','o','m','m','o','n',' ','S','t','a','r','t',' ','M','e','n','u','\0'};
783 static const WCHAR Common_TemplatesW[] = {'C','o','m','m','o','n',' ','T','e','m','p','l','a','t','e','s','\0'};
784 static const WCHAR CommonVideoW[] = {'C','o','m','m','o','n','V','i','d','e','o','\0'};
785 static const WCHAR ContactsW[] = {'C','o','n','t','a','c','t','s','\0'};
786 static const WCHAR CookiesW[] = {'C','o','o','k','i','e','s','\0'};
787 static const WCHAR DesktopW[] = {'D','e','s','k','t','o','p','\0'};
788 static const WCHAR FavoritesW[] = {'F','a','v','o','r','i','t','e','s','\0'};
789 static const WCHAR FontsW[] = {'F','o','n','t','s','\0'};
790 static const WCHAR HistoryW[] = {'H','i','s','t','o','r','y','\0'};
791 static const WCHAR Local_AppDataW[] = {'L','o','c','a','l',' ','A','p','p','D','a','t','a','\0'};
792 static const WCHAR My_MusicW[] = {'M','y',' ','M','u','s','i','c','\0'};
793 static const WCHAR My_PicturesW[] = {'M','y',' ','P','i','c','t','u','r','e','s','\0'};
794 static const WCHAR My_VideoW[] = {'M','y',' ','V','i','d','e','o','s','\0'};
795 static const WCHAR NetHoodW[] = {'N','e','t','H','o','o','d','\0'};
796 static const WCHAR PersonalW[] = {'P','e','r','s','o','n','a','l','\0'};
797 static const WCHAR PrintHoodW[] = {'P','r','i','n','t','H','o','o','d','\0'};
798 static const WCHAR ProgramFilesDirW[] = {'P','r','o','g','r','a','m','F','i','l','e','s','D','i','r','\0'};
799 static const WCHAR ProgramFilesDirX86W[] = {'P','r','o','g','r','a','m','F','i','l','e','s','D','i','r',' ','(','x','8','6',')','\0'};
800 static const WCHAR ProgramsW[] = {'P','r','o','g','r','a','m','s','\0'};
801 static const WCHAR RecentW[] = {'R','e','c','e','n','t','\0'};
802 static const WCHAR ResourcesW[] = {'R','e','s','o','u','r','c','e','s','\0'};
803 static const WCHAR SendToW[] = {'S','e','n','d','T','o','\0'};
804 static const WCHAR StartUpW[] = {'S','t','a','r','t','U','p','\0'};
805 static const WCHAR Start_MenuW[] = {'S','t','a','r','t',' ','M','e','n','u','\0'};
806 static const WCHAR TemplatesW[] = {'T','e','m','p','l','a','t','e','s','\0'};
807 static const WCHAR UsersW[] = {'U','s','e','r','s','\0'};
808 static const WCHAR UsersPublicW[] = {'U','s','e','r','s','\\','P','u','b','l','i','c','\0'};
809 static const WCHAR DefaultW[] = {'.','D','e','f','a','u','l','t','\0'};
810 static const WCHAR AllUsersProfileW[] = {'%','A','L','L','U','S','E','R','S','P','R','O','F','I','L','E','%','\0'};
811 static const WCHAR UserProfileW[] = {'%','U','S','E','R','P','R','O','F','I','L','E','%','\0'};
812 static const WCHAR SystemDriveW[] = {'%','S','y','s','t','e','m','D','r','i','v','e','%','\0'};
813 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};
814 static const WCHAR ProfilesDirectoryW[] = {'P','r','o','f','i','l','e','s','D','i','r','e','c','t','o','r','y',0};
815 static const WCHAR AllUsersProfileValueW[] = {'A','l','l','U','s','e','r','s','P','r','o','f','i','l','e','\0'};
816 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'};
817 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'};
818 static const WCHAR szDefaultProfileDirW[] = {'u','s','e','r','s',0};
819 static const WCHAR AllUsersW[] = {'P','u','b','l','i','c',0};
820
821 typedef enum _CSIDL_Type {
822     CSIDL_Type_User,
823     CSIDL_Type_AllUsers,
824     CSIDL_Type_CurrVer,
825     CSIDL_Type_Disallowed,
826     CSIDL_Type_NonExistent,
827     CSIDL_Type_WindowsPath,
828     CSIDL_Type_SystemPath,
829     CSIDL_Type_SystemX86Path,
830 } CSIDL_Type;
831
832 typedef struct
833 {
834     const KNOWNFOLDERID *id;
835     CSIDL_Type type;
836     LPCWSTR    szValueName;
837     LPCWSTR    szDefaultPath; /* fallback string or resource ID */
838 } CSIDL_DATA;
839
840 static const CSIDL_DATA CSIDL_Data[] =
841 {
842     { /* 0x00 - CSIDL_DESKTOP */
843         &FOLDERID_Desktop,
844         CSIDL_Type_User,
845         DesktopW,
846         MAKEINTRESOURCEW(IDS_DESKTOPDIRECTORY)
847     },
848     { /* 0x01 - CSIDL_INTERNET */
849         &FOLDERID_InternetFolder,
850         CSIDL_Type_Disallowed,
851         NULL,
852         NULL
853     },
854     { /* 0x02 - CSIDL_PROGRAMS */
855         &FOLDERID_Programs,
856         CSIDL_Type_User,
857         ProgramsW,
858         MAKEINTRESOURCEW(IDS_PROGRAMS)
859     },
860     { /* 0x03 - CSIDL_CONTROLS (.CPL files) */
861         &FOLDERID_ControlPanelFolder,
862         CSIDL_Type_SystemPath,
863         NULL,
864         NULL
865     },
866     { /* 0x04 - CSIDL_PRINTERS */
867         &FOLDERID_PrintersFolder,
868         CSIDL_Type_SystemPath,
869         NULL,
870         NULL
871     },
872     { /* 0x05 - CSIDL_PERSONAL */
873         &GUID_NULL,
874         CSIDL_Type_User,
875         PersonalW,
876         MAKEINTRESOURCEW(IDS_PERSONAL)
877     },
878     { /* 0x06 - CSIDL_FAVORITES */
879         &FOLDERID_Favorites,
880         CSIDL_Type_User,
881         FavoritesW,
882         MAKEINTRESOURCEW(IDS_FAVORITES)
883     },
884     { /* 0x07 - CSIDL_STARTUP */
885         &FOLDERID_Startup,
886         CSIDL_Type_User,
887         StartUpW,
888         MAKEINTRESOURCEW(IDS_STARTUP)
889     },
890     { /* 0x08 - CSIDL_RECENT */
891         &FOLDERID_Recent,
892         CSIDL_Type_User,
893         RecentW,
894         MAKEINTRESOURCEW(IDS_RECENT)
895     },
896     { /* 0x09 - CSIDL_SENDTO */
897         &FOLDERID_SendTo,
898         CSIDL_Type_User,
899         SendToW,
900         MAKEINTRESOURCEW(IDS_SENDTO)
901     },
902     { /* 0x0a - CSIDL_BITBUCKET - Recycle Bin */
903         &FOLDERID_RecycleBinFolder,
904         CSIDL_Type_Disallowed,
905         NULL,
906         NULL,
907     },
908     { /* 0x0b - CSIDL_STARTMENU */
909         &FOLDERID_StartMenu,
910         CSIDL_Type_User,
911         Start_MenuW,
912         MAKEINTRESOURCEW(IDS_STARTMENU)
913     },
914     { /* 0x0c - CSIDL_MYDOCUMENTS */
915         &GUID_NULL,
916         CSIDL_Type_Disallowed, /* matches WinXP--can't get its path */
917         NULL,
918         NULL
919     },
920     { /* 0x0d - CSIDL_MYMUSIC */
921         &FOLDERID_Music,
922         CSIDL_Type_User,
923         My_MusicW,
924         MAKEINTRESOURCEW(IDS_MYMUSIC)
925     },
926     { /* 0x0e - CSIDL_MYVIDEO */
927         &FOLDERID_Videos,
928         CSIDL_Type_User,
929         My_VideoW,
930         MAKEINTRESOURCEW(IDS_MYVIDEO)
931     },
932     { /* 0x0f - unassigned */
933         &GUID_NULL,
934         CSIDL_Type_Disallowed,
935         NULL,
936         NULL,
937     },
938     { /* 0x10 - CSIDL_DESKTOPDIRECTORY */
939         &FOLDERID_Desktop,
940         CSIDL_Type_User,
941         DesktopW,
942         MAKEINTRESOURCEW(IDS_DESKTOPDIRECTORY)
943     },
944     { /* 0x11 - CSIDL_DRIVES */
945         &FOLDERID_ComputerFolder,
946         CSIDL_Type_Disallowed,
947         NULL,
948         NULL,
949     },
950     { /* 0x12 - CSIDL_NETWORK */
951         &FOLDERID_NetworkFolder,
952         CSIDL_Type_Disallowed,
953         NULL,
954         NULL,
955     },
956     { /* 0x13 - CSIDL_NETHOOD */
957         &FOLDERID_NetHood,
958         CSIDL_Type_User,
959         NetHoodW,
960         MAKEINTRESOURCEW(IDS_NETHOOD)
961     },
962     { /* 0x14 - CSIDL_FONTS */
963         &FOLDERID_Fonts,
964         CSIDL_Type_WindowsPath,
965         FontsW,
966         FontsW
967     },
968     { /* 0x15 - CSIDL_TEMPLATES */
969         &FOLDERID_Templates,
970         CSIDL_Type_User,
971         TemplatesW,
972         MAKEINTRESOURCEW(IDS_TEMPLATES)
973     },
974     { /* 0x16 - CSIDL_COMMON_STARTMENU */
975         &FOLDERID_CommonStartMenu,
976         CSIDL_Type_AllUsers,
977         Common_Start_MenuW,
978         MAKEINTRESOURCEW(IDS_STARTMENU)
979     },
980     { /* 0x17 - CSIDL_COMMON_PROGRAMS */
981         &FOLDERID_CommonPrograms,
982         CSIDL_Type_AllUsers,
983         Common_ProgramsW,
984         MAKEINTRESOURCEW(IDS_PROGRAMS)
985     },
986     { /* 0x18 - CSIDL_COMMON_STARTUP */
987         &FOLDERID_CommonStartup,
988         CSIDL_Type_AllUsers,
989         Common_StartUpW,
990         MAKEINTRESOURCEW(IDS_STARTUP)
991     },
992     { /* 0x19 - CSIDL_COMMON_DESKTOPDIRECTORY */
993         &FOLDERID_PublicDesktop,
994         CSIDL_Type_AllUsers,
995         Common_DesktopW,
996         MAKEINTRESOURCEW(IDS_DESKTOPDIRECTORY)
997     },
998     { /* 0x1a - CSIDL_APPDATA */
999         &FOLDERID_RoamingAppData,
1000         CSIDL_Type_User,
1001         AppDataW,
1002         MAKEINTRESOURCEW(IDS_APPDATA)
1003     },
1004     { /* 0x1b - CSIDL_PRINTHOOD */
1005         &FOLDERID_PrintHood,
1006         CSIDL_Type_User,
1007         PrintHoodW,
1008         MAKEINTRESOURCEW(IDS_PRINTHOOD)
1009     },
1010     { /* 0x1c - CSIDL_LOCAL_APPDATA */
1011         &FOLDERID_LocalAppData,
1012         CSIDL_Type_User,
1013         Local_AppDataW,
1014         MAKEINTRESOURCEW(IDS_LOCAL_APPDATA)
1015     },
1016     { /* 0x1d - CSIDL_ALTSTARTUP */
1017         &GUID_NULL,
1018         CSIDL_Type_NonExistent,
1019         NULL,
1020         NULL
1021     },
1022     { /* 0x1e - CSIDL_COMMON_ALTSTARTUP */
1023         &GUID_NULL,
1024         CSIDL_Type_NonExistent,
1025         NULL,
1026         NULL
1027     },
1028     { /* 0x1f - CSIDL_COMMON_FAVORITES */
1029         &FOLDERID_Favorites,
1030         CSIDL_Type_AllUsers,
1031         Common_FavoritesW,
1032         MAKEINTRESOURCEW(IDS_FAVORITES)
1033     },
1034     { /* 0x20 - CSIDL_INTERNET_CACHE */
1035         &FOLDERID_InternetCache,
1036         CSIDL_Type_User,
1037         CacheW,
1038         MAKEINTRESOURCEW(IDS_INTERNET_CACHE)
1039     },
1040     { /* 0x21 - CSIDL_COOKIES */
1041         &FOLDERID_Cookies,
1042         CSIDL_Type_User,
1043         CookiesW,
1044         MAKEINTRESOURCEW(IDS_COOKIES)
1045     },
1046     { /* 0x22 - CSIDL_HISTORY */
1047         &FOLDERID_History,
1048         CSIDL_Type_User,
1049         HistoryW,
1050         MAKEINTRESOURCEW(IDS_HISTORY)
1051     },
1052     { /* 0x23 - CSIDL_COMMON_APPDATA */
1053         &FOLDERID_ProgramData,
1054         CSIDL_Type_AllUsers,
1055         Common_AppDataW,
1056         MAKEINTRESOURCEW(IDS_APPDATA)
1057     },
1058     { /* 0x24 - CSIDL_WINDOWS */
1059         &FOLDERID_Windows,
1060         CSIDL_Type_WindowsPath,
1061         NULL,
1062         NULL
1063     },
1064     { /* 0x25 - CSIDL_SYSTEM */
1065         &FOLDERID_System,
1066         CSIDL_Type_SystemPath,
1067         NULL,
1068         NULL
1069     },
1070     { /* 0x26 - CSIDL_PROGRAM_FILES */
1071         &FOLDERID_ProgramFiles,
1072         CSIDL_Type_CurrVer,
1073         ProgramFilesDirW,
1074         MAKEINTRESOURCEW(IDS_PROGRAM_FILES)
1075     },
1076     { /* 0x27 - CSIDL_MYPICTURES */
1077         &FOLDERID_Pictures,
1078         CSIDL_Type_User,
1079         My_PicturesW,
1080         MAKEINTRESOURCEW(IDS_MYPICTURES)
1081     },
1082     { /* 0x28 - CSIDL_PROFILE */
1083         &FOLDERID_Profile,
1084         CSIDL_Type_User,
1085         NULL,
1086         NULL
1087     },
1088     { /* 0x29 - CSIDL_SYSTEMX86 */
1089         &FOLDERID_SystemX86,
1090         CSIDL_Type_SystemX86Path,
1091         NULL,
1092         NULL
1093     },
1094     { /* 0x2a - CSIDL_PROGRAM_FILESX86 */
1095         &FOLDERID_ProgramFilesX86,
1096         CSIDL_Type_CurrVer,
1097         ProgramFilesDirX86W,
1098         MAKEINTRESOURCEW(IDS_PROGRAM_FILESX86)
1099     },
1100     { /* 0x2b - CSIDL_PROGRAM_FILES_COMMON */
1101         &FOLDERID_ProgramFilesCommon,
1102         CSIDL_Type_CurrVer,
1103         CommonFilesDirW,
1104         MAKEINTRESOURCEW(IDS_PROGRAM_FILES_COMMON)
1105     },
1106     { /* 0x2c - CSIDL_PROGRAM_FILES_COMMONX86 */
1107         &FOLDERID_ProgramFilesCommonX86,
1108         CSIDL_Type_CurrVer,
1109         CommonFilesDirX86W,
1110         MAKEINTRESOURCEW(IDS_PROGRAM_FILES_COMMONX86)
1111     },
1112     { /* 0x2d - CSIDL_COMMON_TEMPLATES */
1113         &FOLDERID_CommonTemplates,
1114         CSIDL_Type_AllUsers,
1115         Common_TemplatesW,
1116         MAKEINTRESOURCEW(IDS_TEMPLATES)
1117     },
1118     { /* 0x2e - CSIDL_COMMON_DOCUMENTS */
1119         &FOLDERID_PublicDocuments,
1120         CSIDL_Type_AllUsers,
1121         Common_DocumentsW,
1122         MAKEINTRESOURCEW(IDS_COMMON_DOCUMENTS)
1123     },
1124     { /* 0x2f - CSIDL_COMMON_ADMINTOOLS */
1125         &FOLDERID_CommonAdminTools,
1126         CSIDL_Type_AllUsers,
1127         Common_Administrative_ToolsW,
1128         MAKEINTRESOURCEW(IDS_ADMINTOOLS)
1129     },
1130     { /* 0x30 - CSIDL_ADMINTOOLS */
1131         &FOLDERID_AdminTools,
1132         CSIDL_Type_User,
1133         Administrative_ToolsW,
1134         MAKEINTRESOURCEW(IDS_ADMINTOOLS)
1135     },
1136     { /* 0x31 - CSIDL_CONNECTIONS */
1137         &FOLDERID_ConnectionsFolder,
1138         CSIDL_Type_Disallowed,
1139         NULL,
1140         NULL
1141     },
1142     { /* 0x32 - unassigned */
1143         &GUID_NULL,
1144         CSIDL_Type_Disallowed,
1145         NULL,
1146         NULL
1147     },
1148     { /* 0x33 - unassigned */
1149         &GUID_NULL,
1150         CSIDL_Type_Disallowed,
1151         NULL,
1152         NULL
1153     },
1154     { /* 0x34 - unassigned */
1155         &GUID_NULL,
1156         CSIDL_Type_Disallowed,
1157         NULL,
1158         NULL
1159     },
1160     { /* 0x35 - CSIDL_COMMON_MUSIC */
1161         &FOLDERID_PublicMusic,
1162         CSIDL_Type_AllUsers,
1163         CommonMusicW,
1164         MAKEINTRESOURCEW(IDS_COMMON_MUSIC)
1165     },
1166     { /* 0x36 - CSIDL_COMMON_PICTURES */
1167         &FOLDERID_PublicPictures,
1168         CSIDL_Type_AllUsers,
1169         CommonPicturesW,
1170         MAKEINTRESOURCEW(IDS_COMMON_PICTURES)
1171     },
1172     { /* 0x37 - CSIDL_COMMON_VIDEO */
1173         &FOLDERID_PublicVideos,
1174         CSIDL_Type_AllUsers,
1175         CommonVideoW,
1176         MAKEINTRESOURCEW(IDS_COMMON_VIDEO)
1177     },
1178     { /* 0x38 - CSIDL_RESOURCES */
1179         &FOLDERID_ResourceDir,
1180         CSIDL_Type_WindowsPath,
1181         NULL,
1182         ResourcesW
1183     },
1184     { /* 0x39 - CSIDL_RESOURCES_LOCALIZED */
1185         &FOLDERID_LocalizedResourcesDir,
1186         CSIDL_Type_NonExistent,
1187         NULL,
1188         NULL
1189     },
1190     { /* 0x3a - CSIDL_COMMON_OEM_LINKS */
1191         &FOLDERID_CommonOEMLinks,
1192         CSIDL_Type_AllUsers,
1193         NULL,
1194         MAKEINTRESOURCEW(IDS_COMMON_OEM_LINKS)
1195     },
1196     { /* 0x3b - CSIDL_CDBURN_AREA */
1197         &FOLDERID_CDBurning,
1198         CSIDL_Type_User,
1199         CD_BurningW,
1200         MAKEINTRESOURCEW(IDS_CDBURN_AREA)
1201     },
1202     { /* 0x3c unassigned */
1203         &GUID_NULL,
1204         CSIDL_Type_Disallowed,
1205         NULL,
1206         NULL
1207     },
1208     { /* 0x3d - CSIDL_COMPUTERSNEARME */
1209         &GUID_NULL,
1210         CSIDL_Type_Disallowed, /* FIXME */
1211         NULL,
1212         NULL
1213     },
1214     { /* 0x3e - CSIDL_PROFILES */
1215         &GUID_NULL,
1216         CSIDL_Type_Disallowed, /* oddly, this matches WinXP */
1217         NULL,
1218         NULL
1219     },
1220     { /* 0x3f */
1221         &FOLDERID_AddNewPrograms,
1222         CSIDL_Type_Disallowed,
1223         NULL,
1224         NULL
1225     },
1226     { /* 0x40 */
1227         &FOLDERID_AppUpdates,
1228         CSIDL_Type_Disallowed,
1229         NULL,
1230         NULL
1231     },
1232     { /* 0x41 */
1233         &FOLDERID_ChangeRemovePrograms,
1234         CSIDL_Type_Disallowed,
1235         NULL,
1236         NULL
1237     },
1238     { /* 0x42 */
1239         &FOLDERID_ConflictFolder,
1240         CSIDL_Type_Disallowed,
1241         NULL,
1242         NULL
1243     },
1244     { /* 0x43 */
1245         &FOLDERID_Contacts,
1246         CSIDL_Type_User,
1247         ContactsW,
1248         MAKEINTRESOURCEW(IDS_CONTACTS)
1249     },
1250     { /* 0x44 */
1251         &FOLDERID_DeviceMetadataStore,
1252         CSIDL_Type_Disallowed, /* FIXME */
1253         NULL,
1254         NULL
1255     },
1256     { /* 0x45 */
1257         &FOLDERID_Documents,
1258         CSIDL_Type_User,
1259         NULL,
1260         MAKEINTRESOURCEW(IDS_DOCUMENTS)
1261     },
1262     { /* 0x46 */
1263         &FOLDERID_DocumentsLibrary,
1264         CSIDL_Type_Disallowed, /* FIXME */
1265         NULL,
1266         NULL
1267     },
1268     { /* 0x47 */
1269         &FOLDERID_Downloads,
1270         CSIDL_Type_User,
1271         NULL,
1272         MAKEINTRESOURCEW(IDS_DOWNLOADS)
1273     },
1274     { /* 0x48 */
1275         &FOLDERID_Games,
1276         CSIDL_Type_Disallowed,
1277         NULL,
1278         NULL
1279     },
1280     { /* 0x49 */
1281         &FOLDERID_GameTasks,
1282         CSIDL_Type_Disallowed, /* FIXME */
1283         NULL,
1284         NULL
1285     },
1286     { /* 0x4a */
1287         &FOLDERID_HomeGroup,
1288         CSIDL_Type_Disallowed,
1289         NULL,
1290         NULL
1291     },
1292     { /* 0x4b */
1293         &FOLDERID_ImplicitAppShortcuts,
1294         CSIDL_Type_Disallowed, /* FIXME */
1295         NULL,
1296         NULL
1297     },
1298     { /* 0x4c */
1299         &FOLDERID_Libraries,
1300         CSIDL_Type_Disallowed, /* FIXME */
1301         NULL,
1302         NULL
1303     },
1304     { /* 0x4d */
1305         &FOLDERID_Links,
1306         CSIDL_Type_User,
1307         NULL,
1308         MAKEINTRESOURCEW(IDS_LINKS)
1309     },
1310     { /* 0x4e */
1311         &FOLDERID_LocalAppDataLow,
1312         CSIDL_Type_User,
1313         NULL,
1314         MAKEINTRESOURCEW(IDS_LOCAL_APPDATA_LOW)
1315     },
1316     { /* 0x4f */
1317         &FOLDERID_MusicLibrary,
1318         CSIDL_Type_Disallowed, /* FIXME */
1319         NULL,
1320         NULL
1321     },
1322     { /* 0x50 */
1323         &FOLDERID_OriginalImages,
1324         CSIDL_Type_Disallowed, /* FIXME */
1325         NULL,
1326         NULL
1327     },
1328     { /* 0x51 */
1329         &FOLDERID_PhotoAlbums,
1330         CSIDL_Type_User,
1331         NULL,
1332         MAKEINTRESOURCEW(IDS_PHOTO_ALBUMS)
1333     },
1334     { /* 0x52 */
1335         &FOLDERID_PicturesLibrary,
1336         CSIDL_Type_Disallowed, /* FIXME */
1337         NULL,
1338         NULL
1339     },
1340     { /* 0x53 */
1341         &FOLDERID_Playlists,
1342         CSIDL_Type_User,
1343         NULL,
1344         MAKEINTRESOURCEW(IDS_PLAYLISTS)
1345     },
1346     { /* 0x54 */
1347         &FOLDERID_ProgramFilesX64,
1348         CSIDL_Type_NonExistent,
1349         NULL,
1350         NULL
1351     },
1352     { /* 0x55 */
1353         &FOLDERID_ProgramFilesCommonX64,
1354         CSIDL_Type_NonExistent,
1355         NULL,
1356         NULL
1357     },
1358     { /* 0x56 */
1359         &FOLDERID_Public,
1360         CSIDL_Type_CurrVer, /* FIXME */
1361         NULL,
1362         UsersPublicW
1363     },
1364     { /* 0x57 */
1365         &FOLDERID_PublicDownloads,
1366         CSIDL_Type_AllUsers,
1367         NULL,
1368         MAKEINTRESOURCEW(IDS_PUBLIC_DOWNLOADS)
1369     },
1370     { /* 0x58 */
1371         &FOLDERID_PublicGameTasks,
1372         CSIDL_Type_AllUsers,
1373         NULL,
1374         MAKEINTRESOURCEW(IDS_PUBLIC_GAME_TASKS)
1375     },
1376     { /* 0x59 */
1377         &FOLDERID_PublicLibraries,
1378         CSIDL_Type_AllUsers,
1379         NULL,
1380         MAKEINTRESOURCEW(IDS_PUBLIC_LIBRARIES)
1381     },
1382     { /* 0x5a */
1383         &FOLDERID_PublicRingtones,
1384         CSIDL_Type_AllUsers,
1385         NULL,
1386         MAKEINTRESOURCEW(IDS_PUBLIC_RINGTONES)
1387     },
1388     { /* 0x5b */
1389         &FOLDERID_QuickLaunch,
1390         CSIDL_Type_Disallowed, /* FIXME */
1391         NULL,
1392         NULL
1393     },
1394     { /* 0x5c */
1395         &FOLDERID_RecordedTVLibrary,
1396         CSIDL_Type_Disallowed, /* FIXME */
1397         NULL,
1398         NULL
1399     },
1400     { /* 0x5d */
1401         &FOLDERID_Ringtones,
1402         CSIDL_Type_Disallowed, /* FIXME */
1403         NULL,
1404         NULL
1405     },
1406     { /* 0x5e */
1407         &FOLDERID_SampleMusic,
1408         CSIDL_Type_AllUsers,
1409         NULL,
1410         MAKEINTRESOURCEW(IDS_SAMPLE_MUSIC)
1411     },
1412     { /* 0x5f */
1413         &FOLDERID_SamplePictures,
1414         CSIDL_Type_AllUsers,
1415         NULL,
1416         MAKEINTRESOURCEW(IDS_SAMPLE_PICTURES)
1417     },
1418     { /* 0x60 */
1419         &FOLDERID_SamplePlaylists,
1420         CSIDL_Type_AllUsers,
1421         NULL,
1422         MAKEINTRESOURCEW(IDS_SAMPLE_PLAYLISTS)
1423     },
1424     { /* 0x61 */
1425         &FOLDERID_SampleVideos,
1426         CSIDL_Type_AllUsers,
1427         NULL,
1428         MAKEINTRESOURCEW(IDS_SAMPLE_VIDEOS)
1429     },
1430     { /* 0x62 */
1431         &FOLDERID_SavedGames,
1432         CSIDL_Type_User,
1433         NULL,
1434         MAKEINTRESOURCEW(IDS_SAVED_GAMES)
1435     },
1436     { /* 0x63 */
1437         &FOLDERID_SavedSearches,
1438         CSIDL_Type_User,
1439         NULL,
1440         MAKEINTRESOURCEW(IDS_SAVED_SEARCHES)
1441     },
1442     { /* 0x64 */
1443         &FOLDERID_SEARCH_CSC,
1444         CSIDL_Type_Disallowed,
1445         NULL,
1446         NULL
1447     },
1448     { /* 0x65 */
1449         &FOLDERID_SEARCH_MAPI,
1450         CSIDL_Type_Disallowed,
1451         NULL,
1452         NULL
1453     },
1454     { /* 0x66 */
1455         &FOLDERID_SearchHome,
1456         CSIDL_Type_Disallowed,
1457         NULL,
1458         NULL
1459     },
1460     { /* 0x67 */
1461         &FOLDERID_SidebarDefaultParts,
1462         CSIDL_Type_Disallowed, /* FIXME */
1463         NULL,
1464         NULL
1465     },
1466     { /* 0x68 */
1467         &FOLDERID_SidebarParts,
1468         CSIDL_Type_Disallowed, /* FIXME */
1469         NULL,
1470         NULL
1471     },
1472     { /* 0x69 */
1473         &FOLDERID_SyncManagerFolder,
1474         CSIDL_Type_Disallowed,
1475         NULL,
1476         NULL
1477     },
1478     { /* 0x6a */
1479         &FOLDERID_SyncResultsFolder,
1480         CSIDL_Type_Disallowed,
1481         NULL,
1482         NULL
1483     },
1484     { /* 0x6b */
1485         &FOLDERID_SyncSetupFolder,
1486         CSIDL_Type_Disallowed,
1487         NULL,
1488         NULL
1489     },
1490     { /* 0x6c */
1491         &FOLDERID_UserPinned,
1492         CSIDL_Type_Disallowed, /* FIXME */
1493         NULL,
1494         NULL
1495     },
1496     { /* 0x6d */
1497         &FOLDERID_UserProfiles,
1498         CSIDL_Type_CurrVer,
1499         UsersW,
1500         MAKEINTRESOURCEW(IDS_USER_PROFILES)
1501     },
1502     { /* 0x6e */
1503         &FOLDERID_UserProgramFiles,
1504         CSIDL_Type_Disallowed, /* FIXME */
1505         NULL,
1506         NULL
1507     },
1508     { /* 0x6f */
1509         &FOLDERID_UserProgramFilesCommon,
1510         CSIDL_Type_Disallowed, /* FIXME */
1511         NULL,
1512         NULL
1513     },
1514     { /* 0x70 */
1515         &FOLDERID_UsersFiles,
1516         CSIDL_Type_Disallowed,
1517         NULL,
1518         NULL
1519     },
1520     { /* 0x71 */
1521         &FOLDERID_UsersLibraries,
1522         CSIDL_Type_Disallowed,
1523         NULL,
1524         NULL
1525     },
1526     { /* 0x72 */
1527         &FOLDERID_VideosLibrary,
1528         CSIDL_Type_Disallowed, /* FIXME */
1529         NULL,
1530         NULL
1531     }
1532 };
1533
1534 static HRESULT _SHExpandEnvironmentStrings(LPCWSTR szSrc, LPWSTR szDest);
1535
1536 /* Gets the value named value from the registry key
1537  * rootKey\Software\Microsoft\Windows\CurrentVersion\Explorer\User Shell Folders
1538  * (or from rootKey\userPrefix\... if userPrefix is not NULL) into path, which
1539  * is assumed to be MAX_PATH WCHARs in length.
1540  * If it exists, expands the value and writes the expanded value to
1541  * rootKey\Software\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders
1542  * Returns successful error code if the value was retrieved from the registry,
1543  * and a failure otherwise.
1544  */
1545 static HRESULT _SHGetUserShellFolderPath(HKEY rootKey, LPCWSTR userPrefix,
1546  LPCWSTR value, LPWSTR path)
1547 {
1548     HRESULT hr;
1549     WCHAR shellFolderPath[MAX_PATH], userShellFolderPath[MAX_PATH];
1550     LPCWSTR pShellFolderPath, pUserShellFolderPath;
1551     DWORD dwType, dwPathLen = MAX_PATH;
1552     HKEY userShellFolderKey, shellFolderKey;
1553
1554     TRACE("%p,%s,%s,%p\n",rootKey, debugstr_w(userPrefix), debugstr_w(value),
1555      path);
1556
1557     if (userPrefix)
1558     {
1559         strcpyW(shellFolderPath, userPrefix);
1560         PathAddBackslashW(shellFolderPath);
1561         strcatW(shellFolderPath, szSHFolders);
1562         pShellFolderPath = shellFolderPath;
1563         strcpyW(userShellFolderPath, userPrefix);
1564         PathAddBackslashW(userShellFolderPath);
1565         strcatW(userShellFolderPath, szSHUserFolders);
1566         pUserShellFolderPath = userShellFolderPath;
1567     }
1568     else
1569     {
1570         pUserShellFolderPath = szSHUserFolders;
1571         pShellFolderPath = szSHFolders;
1572     }
1573
1574     if (RegCreateKeyW(rootKey, pShellFolderPath, &shellFolderKey))
1575     {
1576         TRACE("Failed to create %s\n", debugstr_w(pShellFolderPath));
1577         return E_FAIL;
1578     }
1579     if (RegCreateKeyW(rootKey, pUserShellFolderPath, &userShellFolderKey))
1580     {
1581         TRACE("Failed to create %s\n",
1582          debugstr_w(pUserShellFolderPath));
1583         RegCloseKey(shellFolderKey);
1584         return E_FAIL;
1585     }
1586
1587     if (!RegQueryValueExW(userShellFolderKey, value, NULL, &dwType,
1588      (LPBYTE)path, &dwPathLen) && (dwType == REG_EXPAND_SZ || dwType == REG_SZ))
1589     {
1590         LONG ret;
1591
1592         path[dwPathLen / sizeof(WCHAR)] = '\0';
1593         if (dwType == REG_EXPAND_SZ && path[0] == '%')
1594         {
1595             WCHAR szTemp[MAX_PATH];
1596
1597             _SHExpandEnvironmentStrings(path, szTemp);
1598             lstrcpynW(path, szTemp, MAX_PATH);
1599         }
1600         ret = RegSetValueExW(shellFolderKey, value, 0, REG_SZ, (LPBYTE)path,
1601          (strlenW(path) + 1) * sizeof(WCHAR));
1602         if (ret != ERROR_SUCCESS)
1603             hr = HRESULT_FROM_WIN32(ret);
1604         else
1605             hr = S_OK;
1606     }
1607     else
1608         hr = E_FAIL;
1609     RegCloseKey(shellFolderKey);
1610     RegCloseKey(userShellFolderKey);
1611     TRACE("returning 0x%08x\n", hr);
1612     return hr;
1613 }
1614
1615 /* Gets a 'semi-expanded' default value of the CSIDL with index folder into
1616  * pszPath, based on the entries in CSIDL_Data.  By semi-expanded, I mean:
1617  * - The entry's szDefaultPath may be either a string value or an integer
1618  *   resource identifier.  In the latter case, the string value of the resource
1619  *   is written.
1620  * - Depending on the entry's type, the path may begin with an (unexpanded)
1621  *   environment variable name.  The caller is responsible for expanding
1622  *   environment strings if so desired.
1623  *   The types that are prepended with environment variables are:
1624  *   CSIDL_Type_User:     %USERPROFILE%
1625  *   CSIDL_Type_AllUsers: %ALLUSERSPROFILE%
1626  *   CSIDL_Type_CurrVer:  %SystemDrive%
1627  *   (Others might make sense too, but as yet are unneeded.)
1628  */
1629 static HRESULT _SHGetDefaultValue(BYTE folder, LPWSTR pszPath)
1630 {
1631     HRESULT hr;
1632     WCHAR resourcePath[MAX_PATH];
1633     LPCWSTR pDefaultPath = NULL;
1634
1635     TRACE("0x%02x,%p\n", folder, pszPath);
1636
1637     if (folder >= sizeof(CSIDL_Data) / sizeof(CSIDL_Data[0]))
1638         return E_INVALIDARG;
1639     if (!pszPath)
1640         return E_INVALIDARG;
1641
1642     if (!is_win64)
1643     {
1644         BOOL is_wow64;
1645
1646         switch (folder)
1647         {
1648         case CSIDL_PROGRAM_FILES:
1649         case CSIDL_PROGRAM_FILESX86:
1650             IsWow64Process( GetCurrentProcess(), &is_wow64 );
1651             folder = is_wow64 ? CSIDL_PROGRAM_FILESX86 : CSIDL_PROGRAM_FILES;
1652             break;
1653         case CSIDL_PROGRAM_FILES_COMMON:
1654         case CSIDL_PROGRAM_FILES_COMMONX86:
1655             IsWow64Process( GetCurrentProcess(), &is_wow64 );
1656             folder = is_wow64 ? CSIDL_PROGRAM_FILES_COMMONX86 : CSIDL_PROGRAM_FILES_COMMON;
1657             break;
1658         }
1659     }
1660
1661     if (CSIDL_Data[folder].szDefaultPath &&
1662      IS_INTRESOURCE(CSIDL_Data[folder].szDefaultPath))
1663     {
1664         if (LoadStringW(shell32_hInstance,
1665          LOWORD(CSIDL_Data[folder].szDefaultPath), resourcePath, MAX_PATH))
1666         {
1667             hr = S_OK;
1668             pDefaultPath = resourcePath;
1669         }
1670         else
1671         {
1672             FIXME("(%d,%s), LoadString failed, missing translation?\n", folder,
1673              debugstr_w(pszPath));
1674             hr = E_FAIL;
1675         }
1676     }
1677     else
1678     {
1679         hr = S_OK;
1680         pDefaultPath = CSIDL_Data[folder].szDefaultPath;
1681     }
1682     if (SUCCEEDED(hr))
1683     {
1684         switch (CSIDL_Data[folder].type)
1685         {
1686             case CSIDL_Type_User:
1687                 strcpyW(pszPath, UserProfileW);
1688                 break;
1689             case CSIDL_Type_AllUsers:
1690                 strcpyW(pszPath, AllUsersProfileW);
1691                 break;
1692             case CSIDL_Type_CurrVer:
1693                 strcpyW(pszPath, SystemDriveW);
1694                 break;
1695             default:
1696                 ; /* no corresponding env. var, do nothing */
1697         }
1698         if (pDefaultPath)
1699         {
1700             PathAddBackslashW(pszPath);
1701             strcatW(pszPath, pDefaultPath);
1702         }
1703     }
1704     TRACE("returning 0x%08x\n", hr);
1705     return hr;
1706 }
1707
1708 /* Gets the (unexpanded) value of the folder with index folder into pszPath.
1709  * The folder's type is assumed to be CSIDL_Type_CurrVer.  Its default value
1710  * can be overridden in the HKLM\\szCurrentVersion key.
1711  * If dwFlags has SHGFP_TYPE_DEFAULT set or if the value isn't overridden in
1712  * the registry, uses _SHGetDefaultValue to get the value.
1713  */
1714 static HRESULT _SHGetCurrentVersionPath(DWORD dwFlags, BYTE folder,
1715  LPWSTR pszPath)
1716 {
1717     HRESULT hr;
1718
1719     TRACE("0x%08x,0x%02x,%p\n", dwFlags, folder, pszPath);
1720
1721     if (folder >= sizeof(CSIDL_Data) / sizeof(CSIDL_Data[0]))
1722         return E_INVALIDARG;
1723     if (CSIDL_Data[folder].type != CSIDL_Type_CurrVer)
1724         return E_INVALIDARG;
1725     if (!pszPath)
1726         return E_INVALIDARG;
1727
1728     if (dwFlags & SHGFP_TYPE_DEFAULT)
1729         hr = _SHGetDefaultValue(folder, pszPath);
1730     else
1731     {
1732         HKEY hKey;
1733
1734         if (RegCreateKeyW(HKEY_LOCAL_MACHINE, szCurrentVersion, &hKey))
1735             hr = E_FAIL;
1736         else
1737         {
1738             DWORD dwType, dwPathLen = MAX_PATH * sizeof(WCHAR);
1739
1740             if (RegQueryValueExW(hKey, CSIDL_Data[folder].szValueName, NULL,
1741              &dwType, (LPBYTE)pszPath, &dwPathLen) ||
1742              (dwType != REG_SZ && dwType != REG_EXPAND_SZ))
1743             {
1744                 hr = _SHGetDefaultValue(folder, pszPath);
1745                 dwType = REG_EXPAND_SZ;
1746                 switch (folder)
1747                 {
1748                 case CSIDL_PROGRAM_FILESX86:
1749                 case CSIDL_PROGRAM_FILES_COMMONX86:
1750                     /* these two should never be set on 32-bit setups */
1751                     if (!is_win64)
1752                     {
1753                         BOOL is_wow64;
1754                         IsWow64Process( GetCurrentProcess(), &is_wow64 );
1755                         if (!is_wow64) break;
1756                     }
1757                     /* fall through */
1758                 default:
1759                     RegSetValueExW(hKey, CSIDL_Data[folder].szValueName, 0, dwType,
1760                                    (LPBYTE)pszPath, (strlenW(pszPath)+1)*sizeof(WCHAR));
1761                 }
1762             }
1763             else
1764             {
1765                 pszPath[dwPathLen / sizeof(WCHAR)] = '\0';
1766                 hr = S_OK;
1767             }
1768             RegCloseKey(hKey);
1769         }
1770     }
1771     TRACE("returning 0x%08x (output path is %s)\n", hr, debugstr_w(pszPath));
1772     return hr;
1773 }
1774
1775 static LPWSTR _GetUserSidStringFromToken(HANDLE Token)
1776 {
1777     char InfoBuffer[64];
1778     PTOKEN_USER UserInfo;
1779     DWORD InfoSize;
1780     LPWSTR SidStr;
1781
1782     UserInfo = (PTOKEN_USER) InfoBuffer;
1783     if (! GetTokenInformation(Token, TokenUser, InfoBuffer, sizeof(InfoBuffer),
1784                               &InfoSize))
1785     {
1786         if (GetLastError() != ERROR_INSUFFICIENT_BUFFER)
1787             return NULL;
1788         UserInfo = HeapAlloc(GetProcessHeap(), 0, InfoSize);
1789         if (UserInfo == NULL)
1790             return NULL;
1791         if (! GetTokenInformation(Token, TokenUser, UserInfo, InfoSize,
1792                                   &InfoSize))
1793         {
1794             HeapFree(GetProcessHeap(), 0, UserInfo);
1795             return NULL;
1796         }
1797     }
1798
1799     if (! ConvertSidToStringSidW(UserInfo->User.Sid, &SidStr))
1800         SidStr = NULL;
1801
1802     if (UserInfo != (PTOKEN_USER) InfoBuffer)
1803         HeapFree(GetProcessHeap(), 0, UserInfo);
1804
1805     return SidStr;
1806 }
1807
1808 /* Gets the user's path (unexpanded) for the CSIDL with index folder:
1809  * If SHGFP_TYPE_DEFAULT is set, calls _SHGetDefaultValue for it.  Otherwise
1810  * calls _SHGetUserShellFolderPath for it.  Where it looks depends on hToken:
1811  * - if hToken is -1, looks in HKEY_USERS\.Default
1812  * - otherwise looks first in HKEY_CURRENT_USER, followed by HKEY_LOCAL_MACHINE
1813  *   if HKEY_CURRENT_USER doesn't contain any entries.  If both fail, finally
1814  *   calls _SHGetDefaultValue for it.
1815  */
1816 static HRESULT _SHGetUserProfilePath(HANDLE hToken, DWORD dwFlags, BYTE folder,
1817  LPWSTR pszPath)
1818 {
1819     HRESULT hr;
1820
1821     TRACE("%p,0x%08x,0x%02x,%p\n", hToken, dwFlags, folder, pszPath);
1822
1823     if (folder >= sizeof(CSIDL_Data) / sizeof(CSIDL_Data[0]))
1824         return E_INVALIDARG;
1825     if (CSIDL_Data[folder].type != CSIDL_Type_User)
1826         return E_INVALIDARG;
1827     if (!pszPath)
1828         return E_INVALIDARG;
1829
1830     if (dwFlags & SHGFP_TYPE_DEFAULT)
1831     {
1832         if (hToken != NULL && hToken != (HANDLE)-1)
1833         {
1834             FIXME("unsupported for user other than current or default\n");
1835             return E_FAIL;
1836         }
1837         hr = _SHGetDefaultValue(folder, pszPath);
1838     }
1839     else
1840     {
1841         LPCWSTR userPrefix = NULL;
1842         HKEY hRootKey;
1843
1844         if (hToken == (HANDLE)-1)
1845         {
1846             hRootKey = HKEY_USERS;
1847             userPrefix = DefaultW;
1848         }
1849         else if (hToken == NULL)
1850             hRootKey = HKEY_CURRENT_USER;
1851         else
1852         {
1853             hRootKey = HKEY_USERS;
1854             userPrefix = _GetUserSidStringFromToken(hToken);
1855             if (userPrefix == NULL)
1856             {
1857                 hr = E_FAIL;
1858                 goto error;
1859             }
1860         }
1861         hr = _SHGetUserShellFolderPath(hRootKey, userPrefix,
1862          CSIDL_Data[folder].szValueName, pszPath);
1863         if (FAILED(hr) && hRootKey != HKEY_LOCAL_MACHINE)
1864             hr = _SHGetUserShellFolderPath(HKEY_LOCAL_MACHINE, NULL,
1865              CSIDL_Data[folder].szValueName, pszPath);
1866         if (FAILED(hr))
1867             hr = _SHGetDefaultValue(folder, pszPath);
1868         if (userPrefix != NULL && userPrefix != DefaultW)
1869             LocalFree((HLOCAL) userPrefix);
1870     }
1871 error:
1872     TRACE("returning 0x%08x (output path is %s)\n", hr, debugstr_w(pszPath));
1873     return hr;
1874 }
1875
1876 /* Gets the (unexpanded) path for the CSIDL with index folder.  If dwFlags has
1877  * SHGFP_TYPE_DEFAULT set, calls _SHGetDefaultValue.  Otherwise calls
1878  * _SHGetUserShellFolderPath for it, looking only in HKEY_LOCAL_MACHINE.
1879  * If this fails, falls back to _SHGetDefaultValue.
1880  */
1881 static HRESULT _SHGetAllUsersProfilePath(DWORD dwFlags, BYTE folder,
1882  LPWSTR pszPath)
1883 {
1884     HRESULT hr;
1885
1886     TRACE("0x%08x,0x%02x,%p\n", dwFlags, folder, pszPath);
1887
1888     if (folder >= sizeof(CSIDL_Data) / sizeof(CSIDL_Data[0]))
1889         return E_INVALIDARG;
1890     if (CSIDL_Data[folder].type != CSIDL_Type_AllUsers)
1891         return E_INVALIDARG;
1892     if (!pszPath)
1893         return E_INVALIDARG;
1894
1895     if (dwFlags & SHGFP_TYPE_DEFAULT)
1896         hr = _SHGetDefaultValue(folder, pszPath);
1897     else
1898     {
1899         hr = _SHGetUserShellFolderPath(HKEY_LOCAL_MACHINE, NULL,
1900          CSIDL_Data[folder].szValueName, pszPath);
1901         if (FAILED(hr))
1902             hr = _SHGetDefaultValue(folder, pszPath);
1903     }
1904     TRACE("returning 0x%08x (output path is %s)\n", hr, debugstr_w(pszPath));
1905     return hr;
1906 }
1907
1908 static HRESULT _SHOpenProfilesKey(PHKEY pKey)
1909 {
1910     LONG lRet;
1911     DWORD disp;
1912
1913     lRet = RegCreateKeyExW(HKEY_LOCAL_MACHINE, ProfileListW, 0, NULL, 0,
1914      KEY_ALL_ACCESS, NULL, pKey, &disp);
1915     return HRESULT_FROM_WIN32(lRet);
1916 }
1917
1918 /* Reads the value named szValueName from the key profilesKey (assumed to be
1919  * opened by _SHOpenProfilesKey) into szValue, which is assumed to be MAX_PATH
1920  * WCHARs in length.  If it doesn't exist, returns szDefault (and saves
1921  * szDefault to the registry).
1922  */
1923 static HRESULT _SHGetProfilesValue(HKEY profilesKey, LPCWSTR szValueName,
1924  LPWSTR szValue, LPCWSTR szDefault)
1925 {
1926     HRESULT hr;
1927     DWORD type, dwPathLen = MAX_PATH * sizeof(WCHAR);
1928     LONG lRet;
1929
1930     TRACE("%p,%s,%p,%s\n", profilesKey, debugstr_w(szValueName), szValue,
1931      debugstr_w(szDefault));
1932     lRet = RegQueryValueExW(profilesKey, szValueName, NULL, &type,
1933      (LPBYTE)szValue, &dwPathLen);
1934     if (!lRet && (type == REG_SZ || type == REG_EXPAND_SZ) && dwPathLen
1935      && *szValue)
1936     {
1937         dwPathLen /= sizeof(WCHAR);
1938         szValue[dwPathLen] = '\0';
1939         hr = S_OK;
1940     }
1941     else
1942     {
1943         /* Missing or invalid value, set a default */
1944         lstrcpynW(szValue, szDefault, MAX_PATH);
1945         TRACE("Setting missing value %s to %s\n", debugstr_w(szValueName),
1946                                                   debugstr_w(szValue));
1947         lRet = RegSetValueExW(profilesKey, szValueName, 0, REG_EXPAND_SZ,
1948                               (LPBYTE)szValue,
1949                               (strlenW(szValue) + 1) * sizeof(WCHAR));
1950         if (lRet)
1951             hr = HRESULT_FROM_WIN32(lRet);
1952         else
1953             hr = S_OK;
1954     }
1955     TRACE("returning 0x%08x (output value is %s)\n", hr, debugstr_w(szValue));
1956     return hr;
1957 }
1958
1959 /* Attempts to expand environment variables from szSrc into szDest, which is
1960  * assumed to be MAX_PATH characters in length.  Before referring to the
1961  * environment, handles a few variables directly, because the environment
1962  * variables may not be set when this is called (as during Wine's installation
1963  * when default values are being written to the registry).
1964  * The directly handled environment variables, and their source, are:
1965  * - ALLUSERSPROFILE, USERPROFILE: reads from the registry
1966  * - SystemDrive: uses GetSystemDirectoryW and uses the drive portion of its
1967  *   path
1968  * If one of the directly handled environment variables is expanded, only
1969  * expands a single variable, and only in the beginning of szSrc.
1970  */
1971 static HRESULT _SHExpandEnvironmentStrings(LPCWSTR szSrc, LPWSTR szDest)
1972 {
1973     HRESULT hr;
1974     WCHAR szTemp[MAX_PATH], szProfilesPrefix[MAX_PATH] = { 0 };
1975     HKEY key = NULL;
1976
1977     TRACE("%s, %p\n", debugstr_w(szSrc), szDest);
1978
1979     if (!szSrc || !szDest) return E_INVALIDARG;
1980
1981     /* short-circuit if there's nothing to expand */
1982     if (szSrc[0] != '%')
1983     {
1984         strcpyW(szDest, szSrc);
1985         hr = S_OK;
1986         goto end;
1987     }
1988     /* Get the profile prefix, we'll probably be needing it */
1989     hr = _SHOpenProfilesKey(&key);
1990     if (SUCCEEDED(hr))
1991     {
1992         WCHAR def_val[MAX_PATH];
1993
1994         /* get the system drive */
1995         GetSystemDirectoryW(def_val, MAX_PATH);
1996         if (def_val[1] == ':') strcpyW( def_val + 3, szDefaultProfileDirW );
1997         else FIXME("non-drive system paths unsupported\n");
1998
1999         hr = _SHGetProfilesValue(key, ProfilesDirectoryW, szProfilesPrefix, def_val );
2000     }
2001
2002     *szDest = 0;
2003     strcpyW(szTemp, szSrc);
2004     while (SUCCEEDED(hr) && szTemp[0] == '%')
2005     {
2006         if (!strncmpiW(szTemp, AllUsersProfileW, strlenW(AllUsersProfileW)))
2007         {
2008             WCHAR szAllUsers[MAX_PATH];
2009
2010             strcpyW(szDest, szProfilesPrefix);
2011             hr = _SHGetProfilesValue(key, AllUsersProfileValueW,
2012              szAllUsers, AllUsersW);
2013             PathAppendW(szDest, szAllUsers);
2014             PathAppendW(szDest, szTemp + strlenW(AllUsersProfileW));
2015         }
2016         else if (!strncmpiW(szTemp, UserProfileW, strlenW(UserProfileW)))
2017         {
2018             WCHAR userName[MAX_PATH];
2019             DWORD userLen = MAX_PATH;
2020
2021             strcpyW(szDest, szProfilesPrefix);
2022             GetUserNameW(userName, &userLen);
2023             PathAppendW(szDest, userName);
2024             PathAppendW(szDest, szTemp + strlenW(UserProfileW));
2025         }
2026         else if (!strncmpiW(szTemp, SystemDriveW, strlenW(SystemDriveW)))
2027         {
2028             GetSystemDirectoryW(szDest, MAX_PATH);
2029             if (szDest[1] != ':')
2030             {
2031                 FIXME("non-drive system paths unsupported\n");
2032                 hr = E_FAIL;
2033             }
2034             else
2035             {
2036                 strcpyW(szDest + 3, szTemp + strlenW(SystemDriveW) + 1);
2037                 hr = S_OK;
2038             }
2039         }
2040         else
2041         {
2042             DWORD ret = ExpandEnvironmentStringsW(szSrc, szDest, MAX_PATH);
2043
2044             if (ret > MAX_PATH)
2045                 hr = HRESULT_FROM_WIN32(ERROR_INSUFFICIENT_BUFFER);
2046             else if (ret == 0)
2047                 hr = HRESULT_FROM_WIN32(GetLastError());
2048             else
2049                 hr = S_OK;
2050         }
2051         if (SUCCEEDED(hr) && szDest[0] == '%')
2052             strcpyW(szTemp, szDest);
2053         else
2054         {
2055             /* terminate loop */
2056             szTemp[0] = '\0';
2057         }
2058     }
2059 end:
2060     if (key)
2061         RegCloseKey(key);
2062     TRACE("returning 0x%08x (input was %s, output is %s)\n", hr,
2063      debugstr_w(szSrc), debugstr_w(szDest));
2064     return hr;
2065 }
2066
2067 /*************************************************************************
2068  * SHGetFolderPathW                     [SHELL32.@]
2069  *
2070  * Convert nFolder to path.  
2071  *
2072  * RETURNS
2073  *  Success: S_OK
2074  *  Failure: standard HRESULT error codes.
2075  *
2076  * NOTES
2077  * Most values can be overridden in either
2078  * HKCU\Software\Microsoft\Windows\CurrentVersion\Explorer\User Shell Folders
2079  * or in the same location in HKLM.
2080  * The "Shell Folders" registry key was used in NT4 and earlier systems.
2081  * Beginning with Windows 2000, the "User Shell Folders" key is used, so
2082  * changes made to it are made to the former key too.  This synchronization is
2083  * done on-demand: not until someone requests the value of one of these paths
2084  * (by calling one of the SHGet functions) is the value synchronized.
2085  * Furthermore, the HKCU paths take precedence over the HKLM paths.
2086  */
2087 HRESULT WINAPI SHGetFolderPathW(
2088         HWND hwndOwner,    /* [I] owner window */
2089         int nFolder,       /* [I] CSIDL identifying the folder */
2090         HANDLE hToken,     /* [I] access token */
2091         DWORD dwFlags,     /* [I] which path to return */
2092         LPWSTR pszPath)    /* [O] converted path */
2093 {
2094     HRESULT hr =  SHGetFolderPathAndSubDirW(hwndOwner, nFolder, hToken, dwFlags, NULL, pszPath);
2095     if(HRESULT_FROM_WIN32(ERROR_PATH_NOT_FOUND) == hr)
2096         hr = HRESULT_FROM_WIN32(ERROR_FILE_NOT_FOUND);
2097     return hr;
2098 }
2099
2100 HRESULT WINAPI SHGetFolderPathAndSubDirA(
2101         HWND hwndOwner,    /* [I] owner window */
2102         int nFolder,       /* [I] CSIDL identifying the folder */
2103         HANDLE hToken,     /* [I] access token */
2104         DWORD dwFlags,     /* [I] which path to return */
2105         LPCSTR pszSubPath, /* [I] sub directory of the specified folder */
2106         LPSTR pszPath)     /* [O] converted path */
2107 {
2108     int length;
2109     HRESULT hr = S_OK;
2110     LPWSTR pszSubPathW = NULL;
2111     LPWSTR pszPathW = NULL;
2112     TRACE("%08x,%08x,%s\n",nFolder, dwFlags, debugstr_w(pszSubPathW));
2113
2114     if(pszPath) {
2115         pszPathW = HeapAlloc(GetProcessHeap(), 0, MAX_PATH * sizeof(WCHAR));
2116         if(!pszPathW) {
2117             hr = HRESULT_FROM_WIN32(ERROR_NOT_ENOUGH_MEMORY);
2118             goto cleanup;
2119         }
2120     }
2121     TRACE("%08x,%08x,%s\n",nFolder, dwFlags, debugstr_w(pszSubPathW));
2122
2123     /* SHGetFolderPathAndSubDirW does not distinguish if pszSubPath isn't
2124      * set (null), or an empty string.therefore call it without the parameter set
2125      * if pszSubPath is an empty string
2126      */
2127     if (pszSubPath && pszSubPath[0]) {
2128         length = MultiByteToWideChar(CP_ACP, 0, pszSubPath, -1, NULL, 0);
2129         pszSubPathW = HeapAlloc(GetProcessHeap(), 0, length * sizeof(WCHAR));
2130         if(!pszSubPathW) {
2131             hr = HRESULT_FROM_WIN32(ERROR_NOT_ENOUGH_MEMORY);
2132             goto cleanup;
2133         }
2134         MultiByteToWideChar(CP_ACP, 0, pszSubPath, -1, pszSubPathW, length);
2135     }
2136
2137     hr = SHGetFolderPathAndSubDirW(hwndOwner, nFolder, hToken, dwFlags, pszSubPathW, pszPathW);
2138
2139     if (SUCCEEDED(hr) && pszPath)
2140         WideCharToMultiByte(CP_ACP, 0, pszPathW, -1, pszPath, MAX_PATH, NULL, NULL);
2141
2142 cleanup:
2143     HeapFree(GetProcessHeap(), 0, pszPathW);
2144     HeapFree(GetProcessHeap(), 0, pszSubPathW);
2145     return hr;
2146 }
2147
2148 /*************************************************************************
2149  * SHGetFolderPathAndSubDirW            [SHELL32.@]
2150  */
2151 HRESULT WINAPI SHGetFolderPathAndSubDirW(
2152         HWND hwndOwner,    /* [I] owner window */
2153         int nFolder,       /* [I] CSIDL identifying the folder */
2154         HANDLE hToken,     /* [I] access token */
2155         DWORD dwFlags,     /* [I] which path to return */
2156         LPCWSTR pszSubPath,/* [I] sub directory of the specified folder */
2157         LPWSTR pszPath)    /* [O] converted path */
2158 {
2159     HRESULT    hr;
2160     WCHAR      szBuildPath[MAX_PATH], szTemp[MAX_PATH];
2161     DWORD      folder = nFolder & CSIDL_FOLDER_MASK;
2162     CSIDL_Type type;
2163     int        ret;
2164     
2165     TRACE("%p,%p,nFolder=0x%04x,%s\n", hwndOwner,pszPath,nFolder,debugstr_w(pszSubPath));
2166
2167     /* Windows always NULL-terminates the resulting path regardless of success
2168      * or failure, so do so first
2169      */
2170     if (pszPath)
2171         *pszPath = '\0';
2172
2173     if (folder >= sizeof(CSIDL_Data) / sizeof(CSIDL_Data[0]))
2174         return E_INVALIDARG;
2175     if ((SHGFP_TYPE_CURRENT != dwFlags) && (SHGFP_TYPE_DEFAULT != dwFlags))
2176         return E_INVALIDARG;
2177     szTemp[0] = 0;
2178     type = CSIDL_Data[folder].type;
2179     switch (type)
2180     {
2181         case CSIDL_Type_Disallowed:
2182             hr = E_INVALIDARG;
2183             break;
2184         case CSIDL_Type_NonExistent:
2185             hr = S_FALSE;
2186             break;
2187         case CSIDL_Type_WindowsPath:
2188             GetWindowsDirectoryW(szTemp, MAX_PATH);
2189             if (CSIDL_Data[folder].szDefaultPath &&
2190              !IS_INTRESOURCE(CSIDL_Data[folder].szDefaultPath) &&
2191              *CSIDL_Data[folder].szDefaultPath)
2192             {
2193                 PathAddBackslashW(szTemp);
2194                 strcatW(szTemp, CSIDL_Data[folder].szDefaultPath);
2195             }
2196             hr = S_OK;
2197             break;
2198         case CSIDL_Type_SystemPath:
2199             GetSystemDirectoryW(szTemp, MAX_PATH);
2200             if (CSIDL_Data[folder].szDefaultPath &&
2201              !IS_INTRESOURCE(CSIDL_Data[folder].szDefaultPath) &&
2202              *CSIDL_Data[folder].szDefaultPath)
2203             {
2204                 PathAddBackslashW(szTemp);
2205                 strcatW(szTemp, CSIDL_Data[folder].szDefaultPath);
2206             }
2207             hr = S_OK;
2208             break;
2209         case CSIDL_Type_SystemX86Path:
2210             if (!GetSystemWow64DirectoryW(szTemp, MAX_PATH)) GetSystemDirectoryW(szTemp, MAX_PATH);
2211             if (CSIDL_Data[folder].szDefaultPath &&
2212              !IS_INTRESOURCE(CSIDL_Data[folder].szDefaultPath) &&
2213              *CSIDL_Data[folder].szDefaultPath)
2214             {
2215                 PathAddBackslashW(szTemp);
2216                 strcatW(szTemp, CSIDL_Data[folder].szDefaultPath);
2217             }
2218             hr = S_OK;
2219             break;
2220         case CSIDL_Type_CurrVer:
2221             hr = _SHGetCurrentVersionPath(dwFlags, folder, szTemp);
2222             break;
2223         case CSIDL_Type_User:
2224             hr = _SHGetUserProfilePath(hToken, dwFlags, folder, szTemp);
2225             break;
2226         case CSIDL_Type_AllUsers:
2227             hr = _SHGetAllUsersProfilePath(dwFlags, folder, szTemp);
2228             break;
2229         default:
2230             FIXME("bogus type %d, please fix\n", type);
2231             hr = E_INVALIDARG;
2232             break;
2233     }
2234
2235     /* Expand environment strings if necessary */
2236     if (*szTemp == '%')
2237         hr = _SHExpandEnvironmentStrings(szTemp, szBuildPath);
2238     else
2239         strcpyW(szBuildPath, szTemp);
2240
2241     if (FAILED(hr)) goto end;
2242
2243     if(pszSubPath) {
2244         /* make sure the new path does not exceed th bufferlength
2245          * rememebr to backslash and the termination */
2246         if(MAX_PATH < (lstrlenW(szBuildPath) + lstrlenW(pszSubPath) + 2)) {
2247             hr = HRESULT_FROM_WIN32(ERROR_FILENAME_EXCED_RANGE);
2248             goto end;
2249         }
2250         PathAppendW(szBuildPath, pszSubPath);
2251         PathRemoveBackslashW(szBuildPath);
2252     }
2253     /* Copy the path if it's available before we might return */
2254     if (SUCCEEDED(hr) && pszPath)
2255         strcpyW(pszPath, szBuildPath);
2256
2257     /* if we don't care about existing directories we are ready */
2258     if(nFolder & CSIDL_FLAG_DONT_VERIFY) goto end;
2259
2260     if (PathFileExistsW(szBuildPath)) goto end;
2261
2262     /* not existing but we are not allowed to create it.  The return value
2263      * is verified against shell32 version 6.0.
2264      */
2265     if (!(nFolder & CSIDL_FLAG_CREATE))
2266     {
2267         hr = HRESULT_FROM_WIN32(ERROR_PATH_NOT_FOUND);
2268         goto end;
2269     }
2270
2271     /* create directory/directories */
2272     ret = SHCreateDirectoryExW(hwndOwner, szBuildPath, NULL);
2273     if (ret && ret != ERROR_ALREADY_EXISTS)
2274     {
2275         ERR("Failed to create directory %s.\n", debugstr_w(szBuildPath));
2276         hr = E_FAIL;
2277         goto end;
2278     }
2279
2280     TRACE("Created missing system directory %s\n", debugstr_w(szBuildPath));
2281 end:
2282     TRACE("returning 0x%08x (final path is %s)\n", hr, debugstr_w(szBuildPath));
2283     return hr;
2284 }
2285
2286 /*************************************************************************
2287  * SHGetFolderPathA                     [SHELL32.@]
2288  *
2289  * See SHGetFolderPathW.
2290  */
2291 HRESULT WINAPI SHGetFolderPathA(
2292         HWND hwndOwner,
2293         int nFolder,
2294         HANDLE hToken,
2295         DWORD dwFlags,
2296         LPSTR pszPath)
2297 {
2298     WCHAR szTemp[MAX_PATH];
2299     HRESULT hr;
2300
2301     TRACE("%p,%p,nFolder=0x%04x\n",hwndOwner,pszPath,nFolder);
2302
2303     if (pszPath)
2304         *pszPath = '\0';
2305     hr = SHGetFolderPathW(hwndOwner, nFolder, hToken, dwFlags, szTemp);
2306     if (SUCCEEDED(hr) && pszPath)
2307         WideCharToMultiByte(CP_ACP, 0, szTemp, -1, pszPath, MAX_PATH, NULL,
2308          NULL);
2309
2310     return hr;
2311 }
2312
2313 /* For each folder in folders, if its value has not been set in the registry,
2314  * calls _SHGetUserProfilePath or _SHGetAllUsersProfilePath (depending on the
2315  * folder's type) to get the unexpanded value first.
2316  * Writes the unexpanded value to User Shell Folders, and queries it with
2317  * SHGetFolderPathW to force the creation of the directory if it doesn't
2318  * already exist.  SHGetFolderPathW also returns the expanded value, which
2319  * this then writes to Shell Folders.
2320  */
2321 static HRESULT _SHRegisterFolders(HKEY hRootKey, HANDLE hToken,
2322  LPCWSTR szUserShellFolderPath, LPCWSTR szShellFolderPath, const UINT folders[],
2323  UINT foldersLen)
2324 {
2325     UINT i;
2326     WCHAR path[MAX_PATH];
2327     HRESULT hr = S_OK;
2328     HKEY hUserKey = NULL, hKey = NULL;
2329     DWORD dwType, dwPathLen;
2330     LONG ret;
2331
2332     TRACE("%p,%p,%s,%p,%u\n", hRootKey, hToken,
2333      debugstr_w(szUserShellFolderPath), folders, foldersLen);
2334
2335     ret = RegCreateKeyW(hRootKey, szUserShellFolderPath, &hUserKey);
2336     if (ret)
2337         hr = HRESULT_FROM_WIN32(ret);
2338     else
2339     {
2340         ret = RegCreateKeyW(hRootKey, szShellFolderPath, &hKey);
2341         if (ret)
2342             hr = HRESULT_FROM_WIN32(ret);
2343     }
2344     for (i = 0; SUCCEEDED(hr) && i < foldersLen; i++)
2345     {
2346         dwPathLen = MAX_PATH * sizeof(WCHAR);
2347         if (RegQueryValueExW(hUserKey, CSIDL_Data[folders[i]].szValueName, NULL,
2348          &dwType, (LPBYTE)path, &dwPathLen) || (dwType != REG_SZ &&
2349          dwType != REG_EXPAND_SZ))
2350         {
2351             *path = '\0';
2352             if (CSIDL_Data[folders[i]].type == CSIDL_Type_User)
2353                 _SHGetUserProfilePath(hToken, SHGFP_TYPE_DEFAULT, folders[i],
2354                  path);
2355             else if (CSIDL_Data[folders[i]].type == CSIDL_Type_AllUsers)
2356                 _SHGetAllUsersProfilePath(SHGFP_TYPE_DEFAULT, folders[i], path);
2357             else if (CSIDL_Data[folders[i]].type == CSIDL_Type_WindowsPath)
2358             {
2359                 GetWindowsDirectoryW(path, MAX_PATH);
2360                 if (CSIDL_Data[folders[i]].szDefaultPath &&
2361                     !IS_INTRESOURCE(CSIDL_Data[folders[i]].szDefaultPath))
2362                 {
2363                     PathAddBackslashW(path);
2364                     strcatW(path, CSIDL_Data[folders[i]].szDefaultPath);
2365                 }
2366             }
2367             else
2368                 hr = E_FAIL;
2369             if (*path)
2370             {
2371                 ret = RegSetValueExW(hUserKey,
2372                  CSIDL_Data[folders[i]].szValueName, 0, REG_EXPAND_SZ,
2373                  (LPBYTE)path, (strlenW(path) + 1) * sizeof(WCHAR));
2374                 if (ret)
2375                     hr = HRESULT_FROM_WIN32(ret);
2376                 else
2377                 {
2378                     hr = SHGetFolderPathW(NULL, folders[i] | CSIDL_FLAG_CREATE,
2379                      hToken, SHGFP_TYPE_DEFAULT, path);
2380                     ret = RegSetValueExW(hKey,
2381                      CSIDL_Data[folders[i]].szValueName, 0, REG_SZ,
2382                      (LPBYTE)path, (strlenW(path) + 1) * sizeof(WCHAR));
2383                     if (ret)
2384                         hr = HRESULT_FROM_WIN32(ret);
2385                 }
2386             }
2387         }
2388     }
2389     if (hUserKey)
2390         RegCloseKey(hUserKey);
2391     if (hKey)
2392         RegCloseKey(hKey);
2393
2394     TRACE("returning 0x%08x\n", hr);
2395     return hr;
2396 }
2397
2398 static HRESULT _SHRegisterUserShellFolders(BOOL bDefault)
2399 {
2400     static const UINT folders[] = {
2401      CSIDL_PROGRAMS,
2402      CSIDL_PERSONAL,
2403      CSIDL_FAVORITES,
2404      CSIDL_APPDATA,
2405      CSIDL_STARTUP,
2406      CSIDL_RECENT,
2407      CSIDL_SENDTO,
2408      CSIDL_STARTMENU,
2409      CSIDL_MYMUSIC,
2410      CSIDL_MYVIDEO,
2411      CSIDL_DESKTOPDIRECTORY,
2412      CSIDL_NETHOOD,
2413      CSIDL_TEMPLATES,
2414      CSIDL_PRINTHOOD,
2415      CSIDL_LOCAL_APPDATA,
2416      CSIDL_INTERNET_CACHE,
2417      CSIDL_COOKIES,
2418      CSIDL_HISTORY,
2419      CSIDL_MYPICTURES,
2420      CSIDL_FONTS
2421     };
2422     WCHAR userShellFolderPath[MAX_PATH], shellFolderPath[MAX_PATH];
2423     LPCWSTR pUserShellFolderPath, pShellFolderPath;
2424     HRESULT hr = S_OK;
2425     HKEY hRootKey;
2426     HANDLE hToken;
2427
2428     TRACE("%s\n", bDefault ? "TRUE" : "FALSE");
2429     if (bDefault)
2430     {
2431         hToken = (HANDLE)-1;
2432         hRootKey = HKEY_USERS;
2433         strcpyW(userShellFolderPath, DefaultW);
2434         PathAddBackslashW(userShellFolderPath);
2435         strcatW(userShellFolderPath, szSHUserFolders);
2436         pUserShellFolderPath = userShellFolderPath;
2437         strcpyW(shellFolderPath, DefaultW);
2438         PathAddBackslashW(shellFolderPath);
2439         strcatW(shellFolderPath, szSHFolders);
2440         pShellFolderPath = shellFolderPath;
2441     }
2442     else
2443     {
2444         hToken = NULL;
2445         hRootKey = HKEY_CURRENT_USER;
2446         pUserShellFolderPath = szSHUserFolders;
2447         pShellFolderPath = szSHFolders;
2448     }
2449
2450     hr = _SHRegisterFolders(hRootKey, hToken, pUserShellFolderPath,
2451      pShellFolderPath, folders, sizeof(folders) / sizeof(folders[0]));
2452     TRACE("returning 0x%08x\n", hr);
2453     return hr;
2454 }
2455
2456 static HRESULT _SHRegisterCommonShellFolders(void)
2457 {
2458     static const UINT folders[] = {
2459      CSIDL_COMMON_STARTMENU,
2460      CSIDL_COMMON_PROGRAMS,
2461      CSIDL_COMMON_STARTUP,
2462      CSIDL_COMMON_DESKTOPDIRECTORY,
2463      CSIDL_COMMON_FAVORITES,
2464      CSIDL_COMMON_APPDATA,
2465      CSIDL_COMMON_TEMPLATES,
2466      CSIDL_COMMON_DOCUMENTS,
2467      CSIDL_COMMON_ADMINTOOLS,
2468      CSIDL_COMMON_MUSIC,
2469      CSIDL_COMMON_PICTURES,
2470      CSIDL_COMMON_VIDEO,
2471     };
2472     HRESULT hr;
2473
2474     TRACE("\n");
2475     hr = _SHRegisterFolders(HKEY_LOCAL_MACHINE, NULL, szSHUserFolders,
2476      szSHFolders, folders, sizeof(folders) / sizeof(folders[0]));
2477     TRACE("returning 0x%08x\n", hr);
2478     return hr;
2479 }
2480
2481 /******************************************************************************
2482  * _SHAppendToUnixPath  [Internal]
2483  *
2484  * Helper function for _SHCreateSymbolicLinks. Appends pwszSubPath (or the 
2485  * corresponding resource, if IS_INTRESOURCE) to the unix base path 'szBasePath' 
2486  * and replaces backslashes with slashes.
2487  *
2488  * PARAMS
2489  *  szBasePath  [IO] The unix base path, which will be appended to (CP_UNXICP).
2490  *  pwszSubPath [I]  Sub-path or resource id (use MAKEINTRESOURCEW).
2491  *
2492  * RETURNS
2493  *  Success: TRUE,
2494  *  Failure: FALSE
2495  */
2496 static inline BOOL _SHAppendToUnixPath(char *szBasePath, LPCWSTR pwszSubPath) {
2497     WCHAR wszSubPath[MAX_PATH];
2498     int cLen = strlen(szBasePath);
2499     char *pBackslash;
2500
2501     if (IS_INTRESOURCE(pwszSubPath)) {
2502         if (!LoadStringW(shell32_hInstance, LOWORD(pwszSubPath), wszSubPath, MAX_PATH)) {
2503             /* Fall back to hard coded defaults. */
2504             switch (LOWORD(pwszSubPath)) {
2505                 case IDS_PERSONAL:
2506                     lstrcpyW(wszSubPath, PersonalW);
2507                     break;
2508                 case IDS_MYMUSIC:
2509                     lstrcpyW(wszSubPath, My_MusicW);
2510                     break;
2511                 case IDS_MYPICTURES:
2512                     lstrcpyW(wszSubPath, My_PicturesW);
2513                     break;
2514                 case IDS_MYVIDEO:
2515                     lstrcpyW(wszSubPath, My_VideoW);
2516                     break;
2517                 default:
2518                     ERR("LoadString(%d) failed!\n", LOWORD(pwszSubPath));
2519                     return FALSE;
2520             }
2521         }
2522     } else {
2523         lstrcpyW(wszSubPath, pwszSubPath);
2524     }
2525  
2526     if (szBasePath[cLen-1] != '/') szBasePath[cLen++] = '/';
2527  
2528     if (!WideCharToMultiByte(CP_UNIXCP, 0, wszSubPath, -1, szBasePath + cLen,
2529                              FILENAME_MAX - cLen, NULL, NULL))
2530     {
2531         return FALSE;
2532     }
2533  
2534     pBackslash = szBasePath + cLen;
2535     while ((pBackslash = strchr(pBackslash, '\\'))) *pBackslash = '/';
2536  
2537     return TRUE;
2538 }
2539
2540 /******************************************************************************
2541  * _SHCreateSymbolicLinks  [Internal]
2542  * 
2543  * Sets up symbol links for various shell folders to point into the users home
2544  * directory. We do an educated guess about what the user would probably want:
2545  * - If there is a 'My Documents' directory in $HOME, the user probably wants
2546  *   wine's 'My Documents' to point there. Furthermore, we imply that the user
2547  *   is a Windows lover and has no problem with wine creating 'My Pictures',
2548  *   'My Music' and 'My Video' subfolders under '$HOME/My Documents', if those
2549  *   do not already exits. We put appropriate symbolic links in place for those,
2550  *   too.
2551  * - If there is no 'My Documents' directory in $HOME, we let 'My Documents'
2552  *   point directly to $HOME. We assume the user to be a unix hacker who does not
2553  *   want wine to create anything anywhere besides the .wine directory. So, if
2554  *   there already is a 'My Music' directory in $HOME, we symlink the 'My Music'
2555  *   shell folder to it. But if not, then we check XDG_MUSIC_DIR - "well known"
2556  *   directory, and try to link to that. If that fails, then we symlink to
2557  *   $HOME directly. The same holds fo 'My Pictures' and 'My Video'.
2558  * - The Desktop shell folder is symlinked to XDG_DESKTOP_DIR. If that does not
2559  *   exist, then we try '$HOME/Desktop'. If that does not exist, then we leave
2560  *   it alone.
2561  * ('My Music',... above in fact means LoadString(IDS_MYMUSIC))
2562  */
2563 static void _SHCreateSymbolicLinks(void)
2564 {
2565     UINT aidsMyStuff[] = { IDS_MYPICTURES, IDS_MYVIDEO, IDS_MYMUSIC }, i;
2566     int acsidlMyStuff[] = { CSIDL_MYPICTURES, CSIDL_MYVIDEO, CSIDL_MYMUSIC };
2567     static const char * const xdg_dirs[] = { "PICTURES", "VIDEOS", "MUSIC", "DESKTOP" };
2568     static const unsigned int num = sizeof(xdg_dirs) / sizeof(xdg_dirs[0]);
2569     WCHAR wszTempPath[MAX_PATH];
2570     char szPersonalTarget[FILENAME_MAX], *pszPersonal;
2571     char szMyStuffTarget[FILENAME_MAX], *pszMyStuff;
2572     char szDesktopTarget[FILENAME_MAX], *pszDesktop;
2573     struct stat statFolder;
2574     const char *pszHome;
2575     HRESULT hr;
2576     char ** xdg_results;
2577     char * xdg_desktop_dir;
2578
2579     /* Create all necessary profile sub-dirs up to 'My Documents' and get the unix path. */
2580     hr = SHGetFolderPathW(NULL, CSIDL_PERSONAL|CSIDL_FLAG_CREATE, NULL,
2581                           SHGFP_TYPE_DEFAULT, wszTempPath);
2582     if (FAILED(hr)) return;
2583     pszPersonal = wine_get_unix_file_name(wszTempPath);
2584     if (!pszPersonal) return;
2585
2586     hr = XDG_UserDirLookup(xdg_dirs, num, &xdg_results);
2587     if (FAILED(hr)) xdg_results = NULL;
2588
2589     pszHome = getenv("HOME");
2590     if (pszHome && !stat(pszHome, &statFolder) && S_ISDIR(statFolder.st_mode)) {
2591         strcpy(szPersonalTarget, pszHome);
2592         if (_SHAppendToUnixPath(szPersonalTarget, MAKEINTRESOURCEW(IDS_PERSONAL)) &&
2593             !stat(szPersonalTarget, &statFolder) && S_ISDIR(statFolder.st_mode))
2594         {
2595             /* '$HOME/My Documents' exists. Create 'My Pictures', 'My Videos' and 
2596              * 'My Music' subfolders or fail silently if they already exist. */
2597             for (i = 0; i < sizeof(aidsMyStuff)/sizeof(aidsMyStuff[0]); i++) {
2598                 strcpy(szMyStuffTarget, szPersonalTarget);
2599                 if (_SHAppendToUnixPath(szMyStuffTarget, MAKEINTRESOURCEW(aidsMyStuff[i])))
2600                     mkdir(szMyStuffTarget, 0777);
2601             }
2602         } 
2603         else
2604         {
2605             /* '$HOME/My Documents' doesn't exists, but '$HOME' does. */ 
2606             strcpy(szPersonalTarget, pszHome);
2607         }
2608
2609         /* Replace 'My Documents' directory with a symlink of fail silently if not empty. */
2610         rmdir(pszPersonal);
2611         symlink(szPersonalTarget, pszPersonal);
2612     }
2613     else
2614     {
2615         /* '$HOME' doesn't exist. Create 'My Pictures', 'My Videos' and 'My Music' subdirs
2616          * in '%USERPROFILE%\\My Documents' or fail silently if they already exist. */
2617         strcpy(szPersonalTarget, pszPersonal);
2618         for (i = 0; i < sizeof(aidsMyStuff)/sizeof(aidsMyStuff[0]); i++) {
2619             strcpy(szMyStuffTarget, szPersonalTarget);
2620             if (_SHAppendToUnixPath(szMyStuffTarget, MAKEINTRESOURCEW(aidsMyStuff[i])))
2621                 mkdir(szMyStuffTarget, 0777);
2622         }
2623     }
2624
2625     /* Create symbolic links for 'My Pictures', 'My Video' and 'My Music'. */
2626     for (i=0; i < sizeof(aidsMyStuff)/sizeof(aidsMyStuff[0]); i++) {
2627         /* Create the current 'My Whatever' folder and get it's unix path. */
2628         hr = SHGetFolderPathW(NULL, acsidlMyStuff[i]|CSIDL_FLAG_CREATE, NULL,
2629                               SHGFP_TYPE_DEFAULT, wszTempPath);
2630         if (FAILED(hr)) continue;
2631         pszMyStuff = wine_get_unix_file_name(wszTempPath);
2632         if (!pszMyStuff) continue;
2633         
2634         strcpy(szMyStuffTarget, szPersonalTarget);
2635         if (_SHAppendToUnixPath(szMyStuffTarget, MAKEINTRESOURCEW(aidsMyStuff[i])) &&
2636             !stat(szMyStuffTarget, &statFolder) && S_ISDIR(statFolder.st_mode))
2637         {
2638             /* If there's a 'My Whatever' directory where 'My Documents' links to, link to it. */
2639             rmdir(pszMyStuff);
2640             symlink(szMyStuffTarget, pszMyStuff);
2641         } 
2642         else
2643         {
2644             rmdir(pszMyStuff);
2645             if (xdg_results && xdg_results[i])
2646             {
2647                 /* the folder specified by XDG_XXX_DIR exists, link to it. */
2648                 symlink(xdg_results[i], pszMyStuff);
2649             }
2650             else
2651             {
2652                 /* Else link to where 'My Documents' itself links to. */
2653                 symlink(szPersonalTarget, pszMyStuff);
2654             }
2655         }
2656         HeapFree(GetProcessHeap(), 0, pszMyStuff);
2657     }
2658
2659     /* Last but not least, the Desktop folder */
2660     if (pszHome)
2661         strcpy(szDesktopTarget, pszHome);
2662     else
2663         strcpy(szDesktopTarget, pszPersonal);
2664     HeapFree(GetProcessHeap(), 0, pszPersonal);
2665
2666     xdg_desktop_dir = xdg_results ? xdg_results[num - 1] : NULL;
2667     if (xdg_desktop_dir ||
2668         (_SHAppendToUnixPath(szDesktopTarget, DesktopW) &&
2669         !stat(szDesktopTarget, &statFolder) && S_ISDIR(statFolder.st_mode)))
2670     {
2671         hr = SHGetFolderPathW(NULL, CSIDL_DESKTOPDIRECTORY|CSIDL_FLAG_CREATE, NULL,
2672                               SHGFP_TYPE_DEFAULT, wszTempPath);
2673         if (SUCCEEDED(hr) && (pszDesktop = wine_get_unix_file_name(wszTempPath))) 
2674         {
2675             rmdir(pszDesktop);
2676             if (xdg_desktop_dir)
2677                 symlink(xdg_desktop_dir, pszDesktop);
2678             else
2679                 symlink(szDesktopTarget, pszDesktop);
2680             HeapFree(GetProcessHeap(), 0, pszDesktop);
2681         }
2682     }
2683
2684     /* Free resources allocated by XDG_UserDirLookup() */
2685     if (xdg_results)
2686     {
2687         for (i = 0; i < num; i++)
2688             HeapFree(GetProcessHeap(), 0, xdg_results[i]);
2689         HeapFree(GetProcessHeap(), 0, xdg_results);
2690     }
2691 }
2692
2693 /******************************************************************************
2694  * create_extra_folders  [Internal]
2695  *
2696  * Create some extra folders that don't have a standard CSIDL definition.
2697  */
2698 static HRESULT create_extra_folders(void)
2699 {
2700     static const WCHAR environW[] = {'E','n','v','i','r','o','n','m','e','n','t',0};
2701     static const WCHAR TempW[]    = {'T','e','m','p',0};
2702     static const WCHAR TEMPW[]    = {'T','E','M','P',0};
2703     static const WCHAR TMPW[]     = {'T','M','P',0};
2704     WCHAR path[MAX_PATH+5];
2705     HRESULT hr;
2706     HKEY hkey;
2707     DWORD type, size, ret;
2708
2709     ret = RegCreateKeyW( HKEY_CURRENT_USER, environW, &hkey );
2710     if (ret) return HRESULT_FROM_WIN32( ret );
2711
2712     /* FIXME: should be under AppData, but we don't want spaces in the temp path */
2713     hr = SHGetFolderPathAndSubDirW( 0, CSIDL_PROFILE | CSIDL_FLAG_CREATE, NULL,
2714                                     SHGFP_TYPE_DEFAULT, TempW, path );
2715     if (SUCCEEDED(hr))
2716     {
2717         size = sizeof(path);
2718         if (RegQueryValueExW( hkey, TEMPW, NULL, &type, (LPBYTE)path, &size ))
2719             RegSetValueExW( hkey, TEMPW, 0, REG_SZ, (LPBYTE)path, (strlenW(path) + 1) * sizeof(WCHAR) );
2720         size = sizeof(path);
2721         if (RegQueryValueExW( hkey, TMPW, NULL, &type, (LPBYTE)path, &size ))
2722             RegSetValueExW( hkey, TMPW, 0, REG_SZ, (LPBYTE)path, (strlenW(path) + 1) * sizeof(WCHAR) );
2723     }
2724     RegCloseKey( hkey );
2725     return hr;
2726 }
2727
2728
2729 /******************************************************************************
2730  * set_folder_attributes
2731  *
2732  * Set the various folder attributes registry keys.
2733  */
2734 static HRESULT set_folder_attributes(void)
2735 {
2736     static const WCHAR clsidW[] = {'C','L','S','I','D','\\',0 };
2737     static const WCHAR shellfolderW[] = {'\\','S','h','e','l','l','F','o','l','d','e','r', 0 };
2738     static const WCHAR wfparsingW[] = {'W','a','n','t','s','F','O','R','P','A','R','S','I','N','G',0};
2739     static const WCHAR wfdisplayW[] = {'W','a','n','t','s','F','O','R','D','I','S','P','L','A','Y',0};
2740     static const WCHAR hideasdeleteW[] = {'H','i','d','e','A','s','D','e','l','e','t','e','P','e','r','U','s','e','r',0};
2741     static const WCHAR attributesW[] = {'A','t','t','r','i','b','u','t','e','s',0};
2742     static const WCHAR cfattributesW[] = {'C','a','l','l','F','o','r','A','t','t','r','i','b','u','t','e','s',0};
2743     static const WCHAR emptyW[] = {0};
2744
2745     static const struct
2746     {
2747         const CLSID *clsid;
2748         BOOL wfparsing : 1;
2749         BOOL wfdisplay : 1;
2750         BOOL hideasdel : 1;
2751         DWORD attr;
2752         DWORD call_for_attr;
2753     } folders[] =
2754     {
2755         { &CLSID_UnixFolder, TRUE, FALSE, FALSE },
2756         { &CLSID_UnixDosFolder, TRUE, FALSE, FALSE,
2757           SFGAO_FILESYSANCESTOR|SFGAO_FOLDER|SFGAO_HASSUBFOLDER, SFGAO_FILESYSTEM },
2758         { &CLSID_FolderShortcut, FALSE, FALSE, FALSE,
2759           SFGAO_FILESYSTEM|SFGAO_FOLDER|SFGAO_LINK,
2760           SFGAO_HASSUBFOLDER|SFGAO_FILESYSTEM|SFGAO_FOLDER|SFGAO_FILESYSANCESTOR },
2761         { &CLSID_MyDocuments, TRUE, FALSE, FALSE,
2762           SFGAO_FILESYSANCESTOR|SFGAO_FOLDER|SFGAO_HASSUBFOLDER, SFGAO_FILESYSTEM },
2763         { &CLSID_RecycleBin, FALSE, FALSE, FALSE,
2764           SFGAO_FOLDER|SFGAO_DROPTARGET|SFGAO_HASPROPSHEET },
2765         { &CLSID_ControlPanel, FALSE, TRUE, TRUE,
2766           SFGAO_FOLDER|SFGAO_HASSUBFOLDER }
2767     };
2768
2769     unsigned int i;
2770     WCHAR buffer[39 + (sizeof(clsidW) + sizeof(shellfolderW)) / sizeof(WCHAR)];
2771     LONG res;
2772     HKEY hkey;
2773
2774     for (i = 0; i < sizeof(folders)/sizeof(folders[0]); i++)
2775     {
2776         strcpyW( buffer, clsidW );
2777         StringFromGUID2( folders[i].clsid, buffer + strlenW(buffer), 39 );
2778         strcatW( buffer, shellfolderW );
2779         res = RegCreateKeyExW( HKEY_CLASSES_ROOT, buffer, 0, NULL, 0,
2780                                KEY_READ | KEY_WRITE, NULL, &hkey, NULL);
2781         if (res) return HRESULT_FROM_WIN32( res );
2782         if (folders[i].wfparsing)
2783             res = RegSetValueExW( hkey, wfparsingW, 0, REG_SZ, (const BYTE *)emptyW, sizeof(emptyW) );
2784         if (folders[i].wfdisplay)
2785             res = RegSetValueExW( hkey, wfdisplayW, 0, REG_SZ, (const BYTE *)emptyW, sizeof(emptyW) );
2786         if (folders[i].hideasdel)
2787             res = RegSetValueExW( hkey, hideasdeleteW, 0, REG_SZ, (const BYTE *)emptyW, sizeof(emptyW) );
2788         if (folders[i].attr)
2789             res = RegSetValueExW( hkey, attributesW, 0, REG_DWORD,
2790                                   (const BYTE *)&folders[i].attr, sizeof(DWORD));
2791         if (folders[i].call_for_attr)
2792             res = RegSetValueExW( hkey, cfattributesW, 0, REG_DWORD,
2793                                  (const BYTE *)&folders[i].call_for_attr, sizeof(DWORD));
2794         RegCloseKey( hkey );
2795     }
2796     return S_OK;
2797 }
2798
2799
2800 /* Register the default values in the registry, as some apps seem to depend
2801  * on their presence.  The set registered was taken from Windows XP.
2802  */
2803 HRESULT SHELL_RegisterShellFolders(void)
2804 {
2805     HRESULT hr;
2806
2807     /* Set up '$HOME' targeted symlinks for 'My Documents', 'My Pictures',
2808      * 'My Video', 'My Music' and 'Desktop' in advance, so that the
2809      * _SHRegister*ShellFolders() functions will find everything nice and clean
2810      * and thus will not attempt to create them in the profile directory. */
2811     _SHCreateSymbolicLinks();
2812     
2813     hr = _SHRegisterUserShellFolders(TRUE);
2814     if (SUCCEEDED(hr))
2815         hr = _SHRegisterUserShellFolders(FALSE);
2816     if (SUCCEEDED(hr))
2817         hr = _SHRegisterCommonShellFolders();
2818     if (SUCCEEDED(hr))
2819         hr = create_extra_folders();
2820     if (SUCCEEDED(hr))
2821         hr = set_folder_attributes();
2822     return hr;
2823 }
2824
2825 /*************************************************************************
2826  * SHGetSpecialFolderPathA [SHELL32.@]
2827  */
2828 BOOL WINAPI SHGetSpecialFolderPathA (
2829         HWND hwndOwner,
2830         LPSTR szPath,
2831         int nFolder,
2832         BOOL bCreate)
2833 {
2834         return (SHGetFolderPathA(
2835                 hwndOwner,
2836                 nFolder + (bCreate ? CSIDL_FLAG_CREATE : 0),
2837                 NULL,
2838                 0,
2839                 szPath)) == S_OK ? TRUE : FALSE;
2840 }
2841
2842 /*************************************************************************
2843  * SHGetSpecialFolderPathW
2844  */
2845 BOOL WINAPI SHGetSpecialFolderPathW (
2846         HWND hwndOwner,
2847         LPWSTR szPath,
2848         int nFolder,
2849         BOOL bCreate)
2850 {
2851         return (SHGetFolderPathW(
2852                 hwndOwner,
2853                 nFolder + (bCreate ? CSIDL_FLAG_CREATE : 0),
2854                 NULL,
2855                 0,
2856                 szPath)) == S_OK ? TRUE : FALSE;
2857 }
2858
2859 /*************************************************************************
2860  * SHGetSpecialFolderPath (SHELL32.175)
2861  */
2862 BOOL WINAPI SHGetSpecialFolderPathAW (
2863         HWND hwndOwner,
2864         LPVOID szPath,
2865         int nFolder,
2866         BOOL bCreate)
2867
2868 {
2869         if (SHELL_OsIsUnicode())
2870           return SHGetSpecialFolderPathW (hwndOwner, szPath, nFolder, bCreate);
2871         return SHGetSpecialFolderPathA (hwndOwner, szPath, nFolder, bCreate);
2872 }
2873
2874 /*************************************************************************
2875  * SHGetFolderLocation [SHELL32.@]
2876  *
2877  * Gets the folder locations from the registry and creates a pidl.
2878  *
2879  * PARAMS
2880  *   hwndOwner  [I]
2881  *   nFolder    [I] CSIDL_xxxxx
2882  *   hToken     [I] token representing user, or NULL for current user, or -1 for
2883  *                  default user
2884  *   dwReserved [I] must be zero
2885  *   ppidl      [O] PIDL of a special folder
2886  *
2887  * RETURNS
2888  *  Success: S_OK
2889  *  Failure: Standard OLE-defined error result, S_FALSE or E_INVALIDARG
2890  *
2891  * NOTES
2892  *  Creates missing reg keys and directories.
2893  *  Mostly forwards to SHGetFolderPathW, but a few values of nFolder return
2894  *  virtual folders that are handled here.
2895  */
2896 HRESULT WINAPI SHGetFolderLocation(
2897         HWND hwndOwner,
2898         int nFolder,
2899         HANDLE hToken,
2900         DWORD dwReserved,
2901         LPITEMIDLIST *ppidl)
2902 {
2903     HRESULT hr = E_INVALIDARG;
2904
2905     TRACE("%p 0x%08x %p 0x%08x %p\n",
2906      hwndOwner, nFolder, hToken, dwReserved, ppidl);
2907     
2908     if (!ppidl)
2909         return E_INVALIDARG;
2910     if (dwReserved)
2911         return E_INVALIDARG;
2912
2913     /* The virtual folders' locations are not user-dependent */
2914     *ppidl = NULL;
2915     switch (nFolder & CSIDL_FOLDER_MASK)
2916     {
2917         case CSIDL_DESKTOP:
2918             *ppidl = _ILCreateDesktop();
2919             break;
2920
2921         case CSIDL_PERSONAL:
2922             *ppidl = _ILCreateMyDocuments();
2923             break;
2924
2925         case CSIDL_INTERNET:
2926             *ppidl = _ILCreateIExplore();
2927             break;
2928
2929         case CSIDL_CONTROLS:
2930             *ppidl = _ILCreateControlPanel();
2931             break;
2932
2933         case CSIDL_PRINTERS:
2934             *ppidl = _ILCreatePrinters();
2935             break;
2936
2937         case CSIDL_BITBUCKET:
2938             *ppidl = _ILCreateBitBucket();
2939             break;
2940
2941         case CSIDL_DRIVES:
2942             *ppidl = _ILCreateMyComputer();
2943             break;
2944
2945         case CSIDL_NETWORK:
2946             *ppidl = _ILCreateNetwork();
2947             break;
2948
2949         default:
2950         {
2951             WCHAR szPath[MAX_PATH];
2952
2953             hr = SHGetFolderPathW(hwndOwner, nFolder, hToken,
2954              SHGFP_TYPE_CURRENT, szPath);
2955             if (SUCCEEDED(hr))
2956             {
2957                 DWORD attributes=0;
2958
2959                 TRACE("Value=%s\n", debugstr_w(szPath));
2960                 hr = SHILCreateFromPathW(szPath, ppidl, &attributes);
2961             }
2962             else if (hr == HRESULT_FROM_WIN32(ERROR_FILE_NOT_FOUND))
2963             {
2964                 /* unlike SHGetFolderPath, SHGetFolderLocation in shell32
2965                  * version 6.0 returns E_FAIL for nonexistent paths
2966                  */
2967                 hr = E_FAIL;
2968             }
2969         }
2970     }
2971     if(*ppidl)
2972         hr = NOERROR;
2973
2974     TRACE("-- (new pidl %p)\n",*ppidl);
2975     return hr;
2976 }
2977
2978 /*************************************************************************
2979  * SHGetSpecialFolderLocation           [SHELL32.@]
2980  *
2981  * NOTES
2982  *   In NT5, SHGetSpecialFolderLocation needs the <winntdir>/Recent
2983  *   directory.
2984  */
2985 HRESULT WINAPI SHGetSpecialFolderLocation(
2986         HWND hwndOwner,
2987         INT nFolder,
2988         LPITEMIDLIST * ppidl)
2989 {
2990     HRESULT hr = E_INVALIDARG;
2991
2992     TRACE("(%p,0x%x,%p)\n", hwndOwner,nFolder,ppidl);
2993
2994     if (!ppidl)
2995         return E_INVALIDARG;
2996
2997     hr = SHGetFolderLocation(hwndOwner, nFolder, NULL, 0, ppidl);
2998     return hr;
2999 }
3000
3001 static int csidl_from_id( const KNOWNFOLDERID *id )
3002 {
3003     int i;
3004     for (i = 0; i < sizeof(CSIDL_Data) / sizeof(CSIDL_Data[0]); i++)
3005         if (IsEqualGUID( CSIDL_Data[i].id, id )) return i;
3006     return -1;
3007 }
3008
3009 /*************************************************************************
3010  * SHGetKnownFolderPath           [SHELL32.@]
3011  */
3012 HRESULT WINAPI SHGetKnownFolderPath(REFKNOWNFOLDERID rfid, DWORD flags, HANDLE token, PWSTR *path)
3013 {
3014     HRESULT hr;
3015     WCHAR folder[MAX_PATH];
3016     int index = csidl_from_id( rfid );
3017
3018     TRACE("%s, 0x%08x, %p, %p\n", debugstr_guid(rfid), flags, token, path);
3019
3020     if (index < 0)
3021         return E_INVALIDARG;
3022
3023     if (flags & KF_FLAG_CREATE)
3024         index |= CSIDL_FLAG_CREATE;
3025
3026     if (flags & KF_FLAG_DONT_VERIFY)
3027         index |= CSIDL_FLAG_DONT_VERIFY;
3028
3029     if (flags & KF_FLAG_NO_ALIAS)
3030         index |= CSIDL_FLAG_NO_ALIAS;
3031
3032     if (flags & KF_FLAG_INIT)
3033         index |= CSIDL_FLAG_PER_USER_INIT;
3034
3035     if (flags & ~(KF_FLAG_CREATE|KF_FLAG_DONT_VERIFY|KF_FLAG_NO_ALIAS|KF_FLAG_INIT))
3036     {
3037         FIXME("flags 0x%08x not supported\n", flags);
3038         return E_INVALIDARG;
3039     }
3040
3041     hr = SHGetFolderPathW( NULL, index, token, 0, folder );
3042     if (SUCCEEDED(hr))
3043     {
3044         *path = CoTaskMemAlloc( (strlenW( folder ) + 1) * sizeof(WCHAR) );
3045         if (!*path)
3046             return E_OUTOFMEMORY;
3047         strcpyW( *path, folder );
3048     }
3049     return hr;
3050 }
3051
3052 /*************************************************************************
3053  * SHGetFolderPathEx           [SHELL32.@]
3054  */
3055 HRESULT WINAPI SHGetFolderPathEx(REFKNOWNFOLDERID rfid, DWORD flags, HANDLE token, LPWSTR path, DWORD len)
3056 {
3057     HRESULT hr;
3058     WCHAR *buffer;
3059
3060     TRACE("%s, 0x%08x, %p, %p, %u\n", debugstr_guid(rfid), flags, token, path, len);
3061
3062     if (!path || !len) return E_INVALIDARG;
3063
3064     hr = SHGetKnownFolderPath( rfid, flags, token, &buffer );
3065     if (SUCCEEDED( hr ))
3066     {
3067         if (strlenW( buffer ) + 1 > len)
3068         {
3069             CoTaskMemFree( buffer );
3070             return HRESULT_FROM_WIN32( ERROR_INSUFFICIENT_BUFFER );
3071         }
3072         strcpyW( path, buffer );
3073         CoTaskMemFree( buffer );
3074     }
3075     return hr;
3076 }
3077
3078 struct knownfolder
3079 {
3080     const struct IKnownFolderVtbl *vtbl;
3081     LONG refs;
3082     KNOWNFOLDERID id;
3083 };
3084
3085 static inline struct knownfolder *impl_from_IKnownFolder( IKnownFolder *iface )
3086 {
3087     return (struct knownfolder *)((char *)iface - FIELD_OFFSET( struct knownfolder, vtbl ));
3088 }
3089
3090 static ULONG WINAPI knownfolder_AddRef(
3091     IKnownFolder *iface )
3092 {
3093     struct knownfolder *knownfolder = impl_from_IKnownFolder( iface );
3094     return InterlockedIncrement( &knownfolder->refs );
3095 }
3096
3097 static ULONG WINAPI knownfolder_Release(
3098     IKnownFolder *iface )
3099 {
3100     struct knownfolder *knownfolder = impl_from_IKnownFolder( iface );
3101     LONG refs = InterlockedDecrement( &knownfolder->refs );
3102     if (!refs)
3103     {
3104         TRACE("destroying %p\n", knownfolder);
3105         HeapFree( GetProcessHeap(), 0, knownfolder );
3106     }
3107     return refs;
3108 }
3109
3110 static HRESULT WINAPI knownfolder_QueryInterface(
3111     IKnownFolder *iface,
3112     REFIID riid,
3113     void **ppv )
3114 {
3115     struct knownfolder *This = impl_from_IKnownFolder( iface );
3116
3117     TRACE("%p %s %p\n", This, debugstr_guid( riid ), ppv );
3118
3119     if ( IsEqualGUID( riid, &IID_IKnownFolder ) ||
3120          IsEqualGUID( riid, &IID_IUnknown ) )
3121     {
3122         *ppv = iface;
3123     }
3124     else
3125     {
3126         FIXME("interface %s not implemented\n", debugstr_guid(riid));
3127         return E_NOINTERFACE;
3128     }
3129     IKnownFolder_AddRef( iface );
3130     return S_OK;
3131 }
3132
3133 static HRESULT knowfolder_set_id(
3134     IKnownFolder *iface,
3135     const KNOWNFOLDERID *kfid)
3136 {
3137     struct knownfolder *knownfolder = impl_from_IKnownFolder( iface );
3138
3139     TRACE("%s\n", debugstr_guid(kfid));
3140
3141     knownfolder->id = *kfid;
3142     return S_OK;
3143 }
3144
3145 static HRESULT WINAPI knownfolder_GetId(
3146     IKnownFolder *iface,
3147     KNOWNFOLDERID *pkfid)
3148 {
3149     struct knownfolder *knownfolder = impl_from_IKnownFolder( iface );
3150
3151     TRACE("%p\n", pkfid);
3152
3153     *pkfid = knownfolder->id;
3154     return S_OK;
3155 }
3156
3157 static HRESULT WINAPI knownfolder_GetCategory(
3158     IKnownFolder *iface,
3159     KF_CATEGORY *pCategory)
3160 {
3161     FIXME("%p\n", pCategory);
3162     return E_NOTIMPL;
3163 }
3164
3165 static HRESULT WINAPI knownfolder_GetShellItem(
3166     IKnownFolder *iface,
3167     DWORD dwFlags,
3168     REFIID riid,
3169     void **ppv)
3170 {
3171     FIXME("0x%08x, %s, %p\n", dwFlags, debugstr_guid(riid), ppv);
3172     return E_NOTIMPL;
3173 }
3174
3175 static HRESULT WINAPI knownfolder_GetPath(
3176     IKnownFolder *iface,
3177     DWORD dwFlags,
3178     LPWSTR *ppszPath)
3179 {
3180     struct knownfolder *knownfolder = impl_from_IKnownFolder( iface );
3181
3182     TRACE("0x%08x, %p\n", dwFlags, ppszPath);
3183     return SHGetKnownFolderPath( &knownfolder->id, dwFlags, NULL, ppszPath );
3184 }
3185
3186 static HRESULT WINAPI knownfolder_SetPath(
3187     IKnownFolder *iface,
3188     DWORD dwFlags,
3189     LPCWSTR pszPath)
3190 {
3191     FIXME("0x%08x, %p\n", dwFlags, debugstr_w(pszPath));
3192     return E_NOTIMPL;
3193 }
3194
3195 static HRESULT WINAPI knownfolder_GetIDList(
3196     IKnownFolder *iface,
3197     DWORD dwFlags,
3198     PIDLIST_ABSOLUTE *ppidl)
3199 {
3200     FIXME("0x%08x, %p\n", dwFlags, ppidl);
3201     return E_NOTIMPL;
3202 }
3203
3204 static HRESULT WINAPI knownfolder_GetFolderType(
3205     IKnownFolder *iface,
3206     FOLDERTYPEID *pftid)
3207 {
3208     FIXME("%p\n", pftid);
3209     return E_NOTIMPL;
3210 }
3211
3212 static HRESULT WINAPI knownfolder_GetRedirectionCapabilities(
3213     IKnownFolder *iface,
3214     KF_REDIRECTION_CAPABILITIES *pCapabilities)
3215 {
3216     FIXME("%p\n", pCapabilities);
3217     return E_NOTIMPL;
3218 }
3219
3220 static HRESULT WINAPI knownfolder_GetFolderDefinition(
3221     IKnownFolder *iface,
3222     KNOWNFOLDER_DEFINITION *pKFD)
3223 {
3224     FIXME("%p\n", pKFD);
3225     return E_NOTIMPL;
3226 }
3227
3228 static const struct IKnownFolderVtbl knownfolder_vtbl =
3229 {
3230     knownfolder_QueryInterface,
3231     knownfolder_AddRef,
3232     knownfolder_Release,
3233     knownfolder_GetId,
3234     knownfolder_GetCategory,
3235     knownfolder_GetShellItem,
3236     knownfolder_GetPath,
3237     knownfolder_SetPath,
3238     knownfolder_GetIDList,
3239     knownfolder_GetFolderType,
3240     knownfolder_GetRedirectionCapabilities,
3241     knownfolder_GetFolderDefinition
3242 };
3243
3244 static HRESULT knownfolder_create( void **ppv )
3245 {
3246     struct knownfolder *kf;
3247
3248     kf = HeapAlloc( GetProcessHeap(), 0, sizeof(*kf) );
3249     if (!kf) return E_OUTOFMEMORY;
3250
3251     kf->vtbl = &knownfolder_vtbl;
3252     kf->refs = 1;
3253     memset( &kf->id, 0, sizeof(kf->id) );
3254
3255     *ppv = &kf->vtbl;
3256
3257     TRACE("returning iface %p\n", *ppv);
3258     return S_OK;
3259 }
3260
3261 struct foldermanager
3262 {
3263     const struct IKnownFolderManagerVtbl *vtbl;
3264     LONG refs;
3265     UINT num_ids;
3266     KNOWNFOLDERID *ids;
3267 };
3268
3269 static inline struct foldermanager *impl_from_IKnownFolderManager( IKnownFolderManager *iface )
3270 {
3271     return (struct foldermanager *)((char *)iface - FIELD_OFFSET( struct foldermanager, vtbl ));
3272 }
3273
3274 static ULONG WINAPI foldermanager_AddRef(
3275     IKnownFolderManager *iface )
3276 {
3277     struct foldermanager *foldermanager = impl_from_IKnownFolderManager( iface );
3278     return InterlockedIncrement( &foldermanager->refs );
3279 }
3280
3281 static ULONG WINAPI foldermanager_Release(
3282     IKnownFolderManager *iface )
3283 {
3284     struct foldermanager *foldermanager = impl_from_IKnownFolderManager( iface );
3285     LONG refs = InterlockedDecrement( &foldermanager->refs );
3286     if (!refs)
3287     {
3288         TRACE("destroying %p\n", foldermanager);
3289         HeapFree( GetProcessHeap(), 0, foldermanager->ids );
3290         HeapFree( GetProcessHeap(), 0, foldermanager );
3291     }
3292     return refs;
3293 }
3294
3295 static HRESULT WINAPI foldermanager_QueryInterface(
3296     IKnownFolderManager *iface,
3297     REFIID riid,
3298     void **ppv )
3299 {
3300     struct foldermanager *This = impl_from_IKnownFolderManager( iface );
3301
3302     TRACE("%p %s %p\n", This, debugstr_guid( riid ), ppv );
3303
3304     if ( IsEqualGUID( riid, &IID_IKnownFolderManager ) ||
3305          IsEqualGUID( riid, &IID_IUnknown ) )
3306     {
3307         *ppv = iface;
3308     }
3309     else
3310     {
3311         FIXME("interface %s not implemented\n", debugstr_guid(riid));
3312         return E_NOINTERFACE;
3313     }
3314     IKnownFolderManager_AddRef( iface );
3315     return S_OK;
3316 }
3317
3318 static HRESULT WINAPI foldermanager_FolderIdFromCsidl(
3319     IKnownFolderManager *iface,
3320     int nCsidl,
3321     KNOWNFOLDERID *pfid)
3322 {
3323     TRACE("%d, %p\n", nCsidl, pfid);
3324
3325     if (nCsidl >= sizeof(CSIDL_Data) / sizeof(CSIDL_Data[0]))
3326         return E_INVALIDARG;
3327     *pfid = *CSIDL_Data[nCsidl].id;
3328     return S_OK;
3329 }
3330
3331 static HRESULT WINAPI foldermanager_FolderIdToCsidl(
3332     IKnownFolderManager *iface,
3333     REFKNOWNFOLDERID rfid,
3334     int *pnCsidl)
3335 {
3336     int csidl;
3337
3338     TRACE("%s, %p\n", debugstr_guid(rfid), pnCsidl);
3339
3340     csidl = csidl_from_id( rfid );
3341     if (csidl == -1) return E_INVALIDARG;
3342     *pnCsidl = csidl;
3343     return S_OK;
3344 }
3345
3346 static HRESULT WINAPI foldermanager_GetFolderIds(
3347     IKnownFolderManager *iface,
3348     KNOWNFOLDERID **ppKFId,
3349     UINT *pCount)
3350 {
3351     struct foldermanager *fm = impl_from_IKnownFolderManager( iface );
3352
3353     TRACE("%p, %p\n", ppKFId, pCount);
3354
3355     *ppKFId = fm->ids;
3356     *pCount = fm->num_ids;
3357     return S_OK;
3358 }
3359
3360 static BOOL is_knownfolder( struct foldermanager *fm, const KNOWNFOLDERID *id )
3361 {
3362     UINT i;
3363
3364     for (i = 0; i < fm->num_ids; i++)
3365         if (IsEqualGUID( &fm->ids[i], id )) return TRUE;
3366
3367     return FALSE;
3368 }
3369
3370 static HRESULT WINAPI foldermanager_GetFolder(
3371     IKnownFolderManager *iface,
3372     REFKNOWNFOLDERID rfid,
3373     IKnownFolder **ppkf)
3374 {
3375     struct foldermanager *fm = impl_from_IKnownFolderManager( iface );
3376     HRESULT hr;
3377
3378     TRACE("%s, %p\n", debugstr_guid(rfid), ppkf);
3379
3380     if (!is_knownfolder( fm, rfid ))
3381     {
3382         WARN("unknown folder\n");
3383         return E_INVALIDARG;
3384     }
3385     hr = knownfolder_create( (void **)ppkf );
3386     if (SUCCEEDED( hr ))
3387         hr = knowfolder_set_id( *ppkf, rfid );
3388
3389     return hr;
3390 }
3391
3392 static HRESULT WINAPI foldermanager_GetFolderByName(
3393     IKnownFolderManager *iface,
3394     LPCWSTR pszCanonicalName,
3395     IKnownFolder **ppkf)
3396 {
3397     FIXME("%s, %p\n", debugstr_w(pszCanonicalName), ppkf);
3398     return E_NOTIMPL;
3399 }
3400
3401 static HRESULT WINAPI foldermanager_RegisterFolder(
3402     IKnownFolderManager *iface,
3403     REFKNOWNFOLDERID rfid,
3404     KNOWNFOLDER_DEFINITION const *pKFD)
3405 {
3406     FIXME("%p, %p\n", rfid, pKFD);
3407     return E_NOTIMPL;
3408 }
3409
3410 static HRESULT WINAPI foldermanager_UnregisterFolder(
3411     IKnownFolderManager *iface,
3412     REFKNOWNFOLDERID rfid)
3413 {
3414     FIXME("%p\n", rfid);
3415     return E_NOTIMPL;
3416 }
3417
3418 static HRESULT WINAPI foldermanager_FindFolderFromPath(
3419     IKnownFolderManager *iface,
3420     LPCWSTR pszPath,
3421     FFFP_MODE mode,
3422     IKnownFolder **ppkf)
3423 {
3424     FIXME("%s, 0x%08x, %p\n", debugstr_w(pszPath), mode, ppkf);
3425     return E_NOTIMPL;
3426 }
3427
3428 static HRESULT WINAPI foldermanager_FindFolderFromIDList(
3429     IKnownFolderManager *iface,
3430     PCIDLIST_ABSOLUTE pidl,
3431     IKnownFolder **ppkf)
3432 {
3433     FIXME("%p, %p\n", pidl, ppkf);
3434     return E_NOTIMPL;
3435 }
3436
3437 static HRESULT WINAPI foldermanager_Redirect(
3438     IKnownFolderManager *iface,
3439     REFKNOWNFOLDERID rfid,
3440     HWND hwnd,
3441     KF_REDIRECT_FLAGS flags,
3442     LPCWSTR pszTargetPath,
3443     UINT cFolders,
3444     KNOWNFOLDERID const *pExclusion,
3445     LPWSTR *ppszError)
3446 {
3447     FIXME("%p, %p, 0x%08x, %s, %u, %p, %p\n", rfid, hwnd, flags,
3448           debugstr_w(pszTargetPath), cFolders, pExclusion, ppszError);
3449     return E_NOTIMPL;
3450 }
3451
3452 static const struct IKnownFolderManagerVtbl foldermanager_vtbl =
3453 {
3454     foldermanager_QueryInterface,
3455     foldermanager_AddRef,
3456     foldermanager_Release,
3457     foldermanager_FolderIdFromCsidl,
3458     foldermanager_FolderIdToCsidl,
3459     foldermanager_GetFolderIds,
3460     foldermanager_GetFolder,
3461     foldermanager_GetFolderByName,
3462     foldermanager_RegisterFolder,
3463     foldermanager_UnregisterFolder,
3464     foldermanager_FindFolderFromPath,
3465     foldermanager_FindFolderFromIDList,
3466     foldermanager_Redirect
3467 };
3468
3469 static HRESULT foldermanager_create( void **ppv )
3470 {
3471     UINT i, j;
3472     struct foldermanager *fm;
3473
3474     fm = HeapAlloc( GetProcessHeap(), 0, sizeof(*fm) );
3475     if (!fm) return E_OUTOFMEMORY;
3476
3477     fm->vtbl = &foldermanager_vtbl;
3478     fm->refs = 1;
3479     fm->num_ids = 0;
3480
3481     for (i = 0; i < sizeof(CSIDL_Data) / sizeof(CSIDL_Data[0]); i++)
3482     {
3483         if (!IsEqualGUID( CSIDL_Data[i].id, &GUID_NULL )) fm->num_ids++;
3484     }
3485     fm->ids = HeapAlloc( GetProcessHeap(), 0, fm->num_ids * sizeof(KNOWNFOLDERID) );
3486     if (!fm->ids)
3487     {
3488         HeapFree( GetProcessHeap(), 0, fm );
3489         return E_OUTOFMEMORY;
3490     }
3491     for (i = j = 0; i < sizeof(CSIDL_Data) / sizeof(CSIDL_Data[0]); i++)
3492     {
3493         if (!IsEqualGUID( CSIDL_Data[i].id, &GUID_NULL ))
3494         {
3495             fm->ids[j] = *CSIDL_Data[i].id;
3496             j++;
3497         }
3498     }
3499     TRACE("found %u known folders\n", fm->num_ids);
3500     *ppv = &fm->vtbl;
3501
3502     TRACE("returning iface %p\n", *ppv);
3503     return S_OK;
3504 }
3505
3506 HRESULT WINAPI KnownFolderManager_Constructor( IUnknown *punk, REFIID riid, void **ppv )
3507 {
3508     TRACE("%p, %s, %p\n", punk, debugstr_guid(riid), ppv);
3509
3510     if (!ppv)
3511         return E_POINTER;
3512     if (punk)
3513         return CLASS_E_NOAGGREGATION;
3514
3515     return foldermanager_create( ppv );
3516 }