dinput: SetActionMap setting the device buffer.
[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 szKnownFolderDescriptions[] = {'S','o','f','t','w','a','r','e','\\','M','i','c','r','o','s','o','f','t','\\','W','i','n','d','o','w','s','\\','C','u','r','r','e','n','t','V','e','r','s','i','o','n','\\','E','x','p','l','o','r','e','r','\\','F','o','l','d','e','r','D','e','s','c','r','i','p','t','i','o','n','s','\0'};
820 static const WCHAR AllUsersW[] = {'P','u','b','l','i','c',0};
821
822 typedef enum _CSIDL_Type {
823     CSIDL_Type_User,
824     CSIDL_Type_AllUsers,
825     CSIDL_Type_CurrVer,
826     CSIDL_Type_Disallowed,
827     CSIDL_Type_NonExistent,
828     CSIDL_Type_WindowsPath,
829     CSIDL_Type_SystemPath,
830     CSIDL_Type_SystemX86Path,
831 } CSIDL_Type;
832
833 typedef struct
834 {
835     const KNOWNFOLDERID *id;
836     CSIDL_Type type;
837     LPCWSTR    szValueName;
838     LPCWSTR    szDefaultPath; /* fallback string or resource ID */
839 } CSIDL_DATA;
840
841 static const CSIDL_DATA CSIDL_Data[] =
842 {
843     { /* 0x00 - CSIDL_DESKTOP */
844         &FOLDERID_Desktop,
845         CSIDL_Type_User,
846         DesktopW,
847         MAKEINTRESOURCEW(IDS_DESKTOPDIRECTORY)
848     },
849     { /* 0x01 - CSIDL_INTERNET */
850         &FOLDERID_InternetFolder,
851         CSIDL_Type_Disallowed,
852         NULL,
853         NULL
854     },
855     { /* 0x02 - CSIDL_PROGRAMS */
856         &FOLDERID_Programs,
857         CSIDL_Type_User,
858         ProgramsW,
859         MAKEINTRESOURCEW(IDS_PROGRAMS)
860     },
861     { /* 0x03 - CSIDL_CONTROLS (.CPL files) */
862         &FOLDERID_ControlPanelFolder,
863         CSIDL_Type_SystemPath,
864         NULL,
865         NULL
866     },
867     { /* 0x04 - CSIDL_PRINTERS */
868         &FOLDERID_PrintersFolder,
869         CSIDL_Type_SystemPath,
870         NULL,
871         NULL
872     },
873     { /* 0x05 - CSIDL_PERSONAL */
874         &GUID_NULL,
875         CSIDL_Type_User,
876         PersonalW,
877         MAKEINTRESOURCEW(IDS_PERSONAL)
878     },
879     { /* 0x06 - CSIDL_FAVORITES */
880         &FOLDERID_Favorites,
881         CSIDL_Type_User,
882         FavoritesW,
883         MAKEINTRESOURCEW(IDS_FAVORITES)
884     },
885     { /* 0x07 - CSIDL_STARTUP */
886         &FOLDERID_Startup,
887         CSIDL_Type_User,
888         StartUpW,
889         MAKEINTRESOURCEW(IDS_STARTUP)
890     },
891     { /* 0x08 - CSIDL_RECENT */
892         &FOLDERID_Recent,
893         CSIDL_Type_User,
894         RecentW,
895         MAKEINTRESOURCEW(IDS_RECENT)
896     },
897     { /* 0x09 - CSIDL_SENDTO */
898         &FOLDERID_SendTo,
899         CSIDL_Type_User,
900         SendToW,
901         MAKEINTRESOURCEW(IDS_SENDTO)
902     },
903     { /* 0x0a - CSIDL_BITBUCKET - Recycle Bin */
904         &FOLDERID_RecycleBinFolder,
905         CSIDL_Type_Disallowed,
906         NULL,
907         NULL,
908     },
909     { /* 0x0b - CSIDL_STARTMENU */
910         &FOLDERID_StartMenu,
911         CSIDL_Type_User,
912         Start_MenuW,
913         MAKEINTRESOURCEW(IDS_STARTMENU)
914     },
915     { /* 0x0c - CSIDL_MYDOCUMENTS */
916         &GUID_NULL,
917         CSIDL_Type_Disallowed, /* matches WinXP--can't get its path */
918         NULL,
919         NULL
920     },
921     { /* 0x0d - CSIDL_MYMUSIC */
922         &FOLDERID_Music,
923         CSIDL_Type_User,
924         My_MusicW,
925         MAKEINTRESOURCEW(IDS_MYMUSIC)
926     },
927     { /* 0x0e - CSIDL_MYVIDEO */
928         &FOLDERID_Videos,
929         CSIDL_Type_User,
930         My_VideoW,
931         MAKEINTRESOURCEW(IDS_MYVIDEO)
932     },
933     { /* 0x0f - unassigned */
934         &GUID_NULL,
935         CSIDL_Type_Disallowed,
936         NULL,
937         NULL,
938     },
939     { /* 0x10 - CSIDL_DESKTOPDIRECTORY */
940         &FOLDERID_Desktop,
941         CSIDL_Type_User,
942         DesktopW,
943         MAKEINTRESOURCEW(IDS_DESKTOPDIRECTORY)
944     },
945     { /* 0x11 - CSIDL_DRIVES */
946         &FOLDERID_ComputerFolder,
947         CSIDL_Type_Disallowed,
948         NULL,
949         NULL,
950     },
951     { /* 0x12 - CSIDL_NETWORK */
952         &FOLDERID_NetworkFolder,
953         CSIDL_Type_Disallowed,
954         NULL,
955         NULL,
956     },
957     { /* 0x13 - CSIDL_NETHOOD */
958         &FOLDERID_NetHood,
959         CSIDL_Type_User,
960         NetHoodW,
961         MAKEINTRESOURCEW(IDS_NETHOOD)
962     },
963     { /* 0x14 - CSIDL_FONTS */
964         &FOLDERID_Fonts,
965         CSIDL_Type_WindowsPath,
966         FontsW,
967         FontsW
968     },
969     { /* 0x15 - CSIDL_TEMPLATES */
970         &FOLDERID_Templates,
971         CSIDL_Type_User,
972         TemplatesW,
973         MAKEINTRESOURCEW(IDS_TEMPLATES)
974     },
975     { /* 0x16 - CSIDL_COMMON_STARTMENU */
976         &FOLDERID_CommonStartMenu,
977         CSIDL_Type_AllUsers,
978         Common_Start_MenuW,
979         MAKEINTRESOURCEW(IDS_STARTMENU)
980     },
981     { /* 0x17 - CSIDL_COMMON_PROGRAMS */
982         &FOLDERID_CommonPrograms,
983         CSIDL_Type_AllUsers,
984         Common_ProgramsW,
985         MAKEINTRESOURCEW(IDS_PROGRAMS)
986     },
987     { /* 0x18 - CSIDL_COMMON_STARTUP */
988         &FOLDERID_CommonStartup,
989         CSIDL_Type_AllUsers,
990         Common_StartUpW,
991         MAKEINTRESOURCEW(IDS_STARTUP)
992     },
993     { /* 0x19 - CSIDL_COMMON_DESKTOPDIRECTORY */
994         &FOLDERID_PublicDesktop,
995         CSIDL_Type_AllUsers,
996         Common_DesktopW,
997         MAKEINTRESOURCEW(IDS_DESKTOPDIRECTORY)
998     },
999     { /* 0x1a - CSIDL_APPDATA */
1000         &FOLDERID_RoamingAppData,
1001         CSIDL_Type_User,
1002         AppDataW,
1003         MAKEINTRESOURCEW(IDS_APPDATA)
1004     },
1005     { /* 0x1b - CSIDL_PRINTHOOD */
1006         &FOLDERID_PrintHood,
1007         CSIDL_Type_User,
1008         PrintHoodW,
1009         MAKEINTRESOURCEW(IDS_PRINTHOOD)
1010     },
1011     { /* 0x1c - CSIDL_LOCAL_APPDATA */
1012         &FOLDERID_LocalAppData,
1013         CSIDL_Type_User,
1014         Local_AppDataW,
1015         MAKEINTRESOURCEW(IDS_LOCAL_APPDATA)
1016     },
1017     { /* 0x1d - CSIDL_ALTSTARTUP */
1018         &GUID_NULL,
1019         CSIDL_Type_NonExistent,
1020         NULL,
1021         NULL
1022     },
1023     { /* 0x1e - CSIDL_COMMON_ALTSTARTUP */
1024         &GUID_NULL,
1025         CSIDL_Type_NonExistent,
1026         NULL,
1027         NULL
1028     },
1029     { /* 0x1f - CSIDL_COMMON_FAVORITES */
1030         &FOLDERID_Favorites,
1031         CSIDL_Type_AllUsers,
1032         Common_FavoritesW,
1033         MAKEINTRESOURCEW(IDS_FAVORITES)
1034     },
1035     { /* 0x20 - CSIDL_INTERNET_CACHE */
1036         &FOLDERID_InternetCache,
1037         CSIDL_Type_User,
1038         CacheW,
1039         MAKEINTRESOURCEW(IDS_INTERNET_CACHE)
1040     },
1041     { /* 0x21 - CSIDL_COOKIES */
1042         &FOLDERID_Cookies,
1043         CSIDL_Type_User,
1044         CookiesW,
1045         MAKEINTRESOURCEW(IDS_COOKIES)
1046     },
1047     { /* 0x22 - CSIDL_HISTORY */
1048         &FOLDERID_History,
1049         CSIDL_Type_User,
1050         HistoryW,
1051         MAKEINTRESOURCEW(IDS_HISTORY)
1052     },
1053     { /* 0x23 - CSIDL_COMMON_APPDATA */
1054         &FOLDERID_ProgramData,
1055         CSIDL_Type_AllUsers,
1056         Common_AppDataW,
1057         MAKEINTRESOURCEW(IDS_APPDATA)
1058     },
1059     { /* 0x24 - CSIDL_WINDOWS */
1060         &FOLDERID_Windows,
1061         CSIDL_Type_WindowsPath,
1062         NULL,
1063         NULL
1064     },
1065     { /* 0x25 - CSIDL_SYSTEM */
1066         &FOLDERID_System,
1067         CSIDL_Type_SystemPath,
1068         NULL,
1069         NULL
1070     },
1071     { /* 0x26 - CSIDL_PROGRAM_FILES */
1072         &FOLDERID_ProgramFiles,
1073         CSIDL_Type_CurrVer,
1074         ProgramFilesDirW,
1075         MAKEINTRESOURCEW(IDS_PROGRAM_FILES)
1076     },
1077     { /* 0x27 - CSIDL_MYPICTURES */
1078         &FOLDERID_Pictures,
1079         CSIDL_Type_User,
1080         My_PicturesW,
1081         MAKEINTRESOURCEW(IDS_MYPICTURES)
1082     },
1083     { /* 0x28 - CSIDL_PROFILE */
1084         &FOLDERID_Profile,
1085         CSIDL_Type_User,
1086         NULL,
1087         NULL
1088     },
1089     { /* 0x29 - CSIDL_SYSTEMX86 */
1090         &FOLDERID_SystemX86,
1091         CSIDL_Type_SystemX86Path,
1092         NULL,
1093         NULL
1094     },
1095     { /* 0x2a - CSIDL_PROGRAM_FILESX86 */
1096         &FOLDERID_ProgramFilesX86,
1097         CSIDL_Type_CurrVer,
1098         ProgramFilesDirX86W,
1099         MAKEINTRESOURCEW(IDS_PROGRAM_FILESX86)
1100     },
1101     { /* 0x2b - CSIDL_PROGRAM_FILES_COMMON */
1102         &FOLDERID_ProgramFilesCommon,
1103         CSIDL_Type_CurrVer,
1104         CommonFilesDirW,
1105         MAKEINTRESOURCEW(IDS_PROGRAM_FILES_COMMON)
1106     },
1107     { /* 0x2c - CSIDL_PROGRAM_FILES_COMMONX86 */
1108         &FOLDERID_ProgramFilesCommonX86,
1109         CSIDL_Type_CurrVer,
1110         CommonFilesDirX86W,
1111         MAKEINTRESOURCEW(IDS_PROGRAM_FILES_COMMONX86)
1112     },
1113     { /* 0x2d - CSIDL_COMMON_TEMPLATES */
1114         &FOLDERID_CommonTemplates,
1115         CSIDL_Type_AllUsers,
1116         Common_TemplatesW,
1117         MAKEINTRESOURCEW(IDS_TEMPLATES)
1118     },
1119     { /* 0x2e - CSIDL_COMMON_DOCUMENTS */
1120         &FOLDERID_PublicDocuments,
1121         CSIDL_Type_AllUsers,
1122         Common_DocumentsW,
1123         MAKEINTRESOURCEW(IDS_COMMON_DOCUMENTS)
1124     },
1125     { /* 0x2f - CSIDL_COMMON_ADMINTOOLS */
1126         &FOLDERID_CommonAdminTools,
1127         CSIDL_Type_AllUsers,
1128         Common_Administrative_ToolsW,
1129         MAKEINTRESOURCEW(IDS_ADMINTOOLS)
1130     },
1131     { /* 0x30 - CSIDL_ADMINTOOLS */
1132         &FOLDERID_AdminTools,
1133         CSIDL_Type_User,
1134         Administrative_ToolsW,
1135         MAKEINTRESOURCEW(IDS_ADMINTOOLS)
1136     },
1137     { /* 0x31 - CSIDL_CONNECTIONS */
1138         &FOLDERID_ConnectionsFolder,
1139         CSIDL_Type_Disallowed,
1140         NULL,
1141         NULL
1142     },
1143     { /* 0x32 - unassigned */
1144         &GUID_NULL,
1145         CSIDL_Type_Disallowed,
1146         NULL,
1147         NULL
1148     },
1149     { /* 0x33 - unassigned */
1150         &GUID_NULL,
1151         CSIDL_Type_Disallowed,
1152         NULL,
1153         NULL
1154     },
1155     { /* 0x34 - unassigned */
1156         &GUID_NULL,
1157         CSIDL_Type_Disallowed,
1158         NULL,
1159         NULL
1160     },
1161     { /* 0x35 - CSIDL_COMMON_MUSIC */
1162         &FOLDERID_PublicMusic,
1163         CSIDL_Type_AllUsers,
1164         CommonMusicW,
1165         MAKEINTRESOURCEW(IDS_COMMON_MUSIC)
1166     },
1167     { /* 0x36 - CSIDL_COMMON_PICTURES */
1168         &FOLDERID_PublicPictures,
1169         CSIDL_Type_AllUsers,
1170         CommonPicturesW,
1171         MAKEINTRESOURCEW(IDS_COMMON_PICTURES)
1172     },
1173     { /* 0x37 - CSIDL_COMMON_VIDEO */
1174         &FOLDERID_PublicVideos,
1175         CSIDL_Type_AllUsers,
1176         CommonVideoW,
1177         MAKEINTRESOURCEW(IDS_COMMON_VIDEO)
1178     },
1179     { /* 0x38 - CSIDL_RESOURCES */
1180         &FOLDERID_ResourceDir,
1181         CSIDL_Type_WindowsPath,
1182         NULL,
1183         ResourcesW
1184     },
1185     { /* 0x39 - CSIDL_RESOURCES_LOCALIZED */
1186         &FOLDERID_LocalizedResourcesDir,
1187         CSIDL_Type_NonExistent,
1188         NULL,
1189         NULL
1190     },
1191     { /* 0x3a - CSIDL_COMMON_OEM_LINKS */
1192         &FOLDERID_CommonOEMLinks,
1193         CSIDL_Type_AllUsers,
1194         NULL,
1195         MAKEINTRESOURCEW(IDS_COMMON_OEM_LINKS)
1196     },
1197     { /* 0x3b - CSIDL_CDBURN_AREA */
1198         &FOLDERID_CDBurning,
1199         CSIDL_Type_User,
1200         CD_BurningW,
1201         MAKEINTRESOURCEW(IDS_CDBURN_AREA)
1202     },
1203     { /* 0x3c unassigned */
1204         &GUID_NULL,
1205         CSIDL_Type_Disallowed,
1206         NULL,
1207         NULL
1208     },
1209     { /* 0x3d - CSIDL_COMPUTERSNEARME */
1210         &GUID_NULL,
1211         CSIDL_Type_Disallowed, /* FIXME */
1212         NULL,
1213         NULL
1214     },
1215     { /* 0x3e - CSIDL_PROFILES */
1216         &GUID_NULL,
1217         CSIDL_Type_Disallowed, /* oddly, this matches WinXP */
1218         NULL,
1219         NULL
1220     },
1221     { /* 0x3f */
1222         &FOLDERID_AddNewPrograms,
1223         CSIDL_Type_Disallowed,
1224         NULL,
1225         NULL
1226     },
1227     { /* 0x40 */
1228         &FOLDERID_AppUpdates,
1229         CSIDL_Type_Disallowed,
1230         NULL,
1231         NULL
1232     },
1233     { /* 0x41 */
1234         &FOLDERID_ChangeRemovePrograms,
1235         CSIDL_Type_Disallowed,
1236         NULL,
1237         NULL
1238     },
1239     { /* 0x42 */
1240         &FOLDERID_ConflictFolder,
1241         CSIDL_Type_Disallowed,
1242         NULL,
1243         NULL
1244     },
1245     { /* 0x43 */
1246         &FOLDERID_Contacts,
1247         CSIDL_Type_User,
1248         ContactsW,
1249         MAKEINTRESOURCEW(IDS_CONTACTS)
1250     },
1251     { /* 0x44 */
1252         &FOLDERID_DeviceMetadataStore,
1253         CSIDL_Type_Disallowed, /* FIXME */
1254         NULL,
1255         NULL
1256     },
1257     { /* 0x45 */
1258         &FOLDERID_Documents,
1259         CSIDL_Type_User,
1260         NULL,
1261         MAKEINTRESOURCEW(IDS_DOCUMENTS)
1262     },
1263     { /* 0x46 */
1264         &FOLDERID_DocumentsLibrary,
1265         CSIDL_Type_Disallowed, /* FIXME */
1266         NULL,
1267         NULL
1268     },
1269     { /* 0x47 */
1270         &FOLDERID_Downloads,
1271         CSIDL_Type_User,
1272         NULL,
1273         MAKEINTRESOURCEW(IDS_DOWNLOADS)
1274     },
1275     { /* 0x48 */
1276         &FOLDERID_Games,
1277         CSIDL_Type_Disallowed,
1278         NULL,
1279         NULL
1280     },
1281     { /* 0x49 */
1282         &FOLDERID_GameTasks,
1283         CSIDL_Type_Disallowed, /* FIXME */
1284         NULL,
1285         NULL
1286     },
1287     { /* 0x4a */
1288         &FOLDERID_HomeGroup,
1289         CSIDL_Type_Disallowed,
1290         NULL,
1291         NULL
1292     },
1293     { /* 0x4b */
1294         &FOLDERID_ImplicitAppShortcuts,
1295         CSIDL_Type_Disallowed, /* FIXME */
1296         NULL,
1297         NULL
1298     },
1299     { /* 0x4c */
1300         &FOLDERID_Libraries,
1301         CSIDL_Type_Disallowed, /* FIXME */
1302         NULL,
1303         NULL
1304     },
1305     { /* 0x4d */
1306         &FOLDERID_Links,
1307         CSIDL_Type_User,
1308         NULL,
1309         MAKEINTRESOURCEW(IDS_LINKS)
1310     },
1311     { /* 0x4e */
1312         &FOLDERID_LocalAppDataLow,
1313         CSIDL_Type_User,
1314         NULL,
1315         MAKEINTRESOURCEW(IDS_LOCAL_APPDATA_LOW)
1316     },
1317     { /* 0x4f */
1318         &FOLDERID_MusicLibrary,
1319         CSIDL_Type_Disallowed, /* FIXME */
1320         NULL,
1321         NULL
1322     },
1323     { /* 0x50 */
1324         &FOLDERID_OriginalImages,
1325         CSIDL_Type_Disallowed, /* FIXME */
1326         NULL,
1327         NULL
1328     },
1329     { /* 0x51 */
1330         &FOLDERID_PhotoAlbums,
1331         CSIDL_Type_User,
1332         NULL,
1333         MAKEINTRESOURCEW(IDS_PHOTO_ALBUMS)
1334     },
1335     { /* 0x52 */
1336         &FOLDERID_PicturesLibrary,
1337         CSIDL_Type_Disallowed, /* FIXME */
1338         NULL,
1339         NULL
1340     },
1341     { /* 0x53 */
1342         &FOLDERID_Playlists,
1343         CSIDL_Type_User,
1344         NULL,
1345         MAKEINTRESOURCEW(IDS_PLAYLISTS)
1346     },
1347     { /* 0x54 */
1348         &FOLDERID_ProgramFilesX64,
1349         CSIDL_Type_NonExistent,
1350         NULL,
1351         NULL
1352     },
1353     { /* 0x55 */
1354         &FOLDERID_ProgramFilesCommonX64,
1355         CSIDL_Type_NonExistent,
1356         NULL,
1357         NULL
1358     },
1359     { /* 0x56 */
1360         &FOLDERID_Public,
1361         CSIDL_Type_CurrVer, /* FIXME */
1362         NULL,
1363         UsersPublicW
1364     },
1365     { /* 0x57 */
1366         &FOLDERID_PublicDownloads,
1367         CSIDL_Type_AllUsers,
1368         NULL,
1369         MAKEINTRESOURCEW(IDS_PUBLIC_DOWNLOADS)
1370     },
1371     { /* 0x58 */
1372         &FOLDERID_PublicGameTasks,
1373         CSIDL_Type_AllUsers,
1374         NULL,
1375         MAKEINTRESOURCEW(IDS_PUBLIC_GAME_TASKS)
1376     },
1377     { /* 0x59 */
1378         &FOLDERID_PublicLibraries,
1379         CSIDL_Type_AllUsers,
1380         NULL,
1381         MAKEINTRESOURCEW(IDS_PUBLIC_LIBRARIES)
1382     },
1383     { /* 0x5a */
1384         &FOLDERID_PublicRingtones,
1385         CSIDL_Type_AllUsers,
1386         NULL,
1387         MAKEINTRESOURCEW(IDS_PUBLIC_RINGTONES)
1388     },
1389     { /* 0x5b */
1390         &FOLDERID_QuickLaunch,
1391         CSIDL_Type_Disallowed, /* FIXME */
1392         NULL,
1393         NULL
1394     },
1395     { /* 0x5c */
1396         &FOLDERID_RecordedTVLibrary,
1397         CSIDL_Type_Disallowed, /* FIXME */
1398         NULL,
1399         NULL
1400     },
1401     { /* 0x5d */
1402         &FOLDERID_Ringtones,
1403         CSIDL_Type_Disallowed, /* FIXME */
1404         NULL,
1405         NULL
1406     },
1407     { /* 0x5e */
1408         &FOLDERID_SampleMusic,
1409         CSIDL_Type_AllUsers,
1410         NULL,
1411         MAKEINTRESOURCEW(IDS_SAMPLE_MUSIC)
1412     },
1413     { /* 0x5f */
1414         &FOLDERID_SamplePictures,
1415         CSIDL_Type_AllUsers,
1416         NULL,
1417         MAKEINTRESOURCEW(IDS_SAMPLE_PICTURES)
1418     },
1419     { /* 0x60 */
1420         &FOLDERID_SamplePlaylists,
1421         CSIDL_Type_AllUsers,
1422         NULL,
1423         MAKEINTRESOURCEW(IDS_SAMPLE_PLAYLISTS)
1424     },
1425     { /* 0x61 */
1426         &FOLDERID_SampleVideos,
1427         CSIDL_Type_AllUsers,
1428         NULL,
1429         MAKEINTRESOURCEW(IDS_SAMPLE_VIDEOS)
1430     },
1431     { /* 0x62 */
1432         &FOLDERID_SavedGames,
1433         CSIDL_Type_User,
1434         NULL,
1435         MAKEINTRESOURCEW(IDS_SAVED_GAMES)
1436     },
1437     { /* 0x63 */
1438         &FOLDERID_SavedSearches,
1439         CSIDL_Type_User,
1440         NULL,
1441         MAKEINTRESOURCEW(IDS_SAVED_SEARCHES)
1442     },
1443     { /* 0x64 */
1444         &FOLDERID_SEARCH_CSC,
1445         CSIDL_Type_Disallowed,
1446         NULL,
1447         NULL
1448     },
1449     { /* 0x65 */
1450         &FOLDERID_SEARCH_MAPI,
1451         CSIDL_Type_Disallowed,
1452         NULL,
1453         NULL
1454     },
1455     { /* 0x66 */
1456         &FOLDERID_SearchHome,
1457         CSIDL_Type_Disallowed,
1458         NULL,
1459         NULL
1460     },
1461     { /* 0x67 */
1462         &FOLDERID_SidebarDefaultParts,
1463         CSIDL_Type_Disallowed, /* FIXME */
1464         NULL,
1465         NULL
1466     },
1467     { /* 0x68 */
1468         &FOLDERID_SidebarParts,
1469         CSIDL_Type_Disallowed, /* FIXME */
1470         NULL,
1471         NULL
1472     },
1473     { /* 0x69 */
1474         &FOLDERID_SyncManagerFolder,
1475         CSIDL_Type_Disallowed,
1476         NULL,
1477         NULL
1478     },
1479     { /* 0x6a */
1480         &FOLDERID_SyncResultsFolder,
1481         CSIDL_Type_Disallowed,
1482         NULL,
1483         NULL
1484     },
1485     { /* 0x6b */
1486         &FOLDERID_SyncSetupFolder,
1487         CSIDL_Type_Disallowed,
1488         NULL,
1489         NULL
1490     },
1491     { /* 0x6c */
1492         &FOLDERID_UserPinned,
1493         CSIDL_Type_Disallowed, /* FIXME */
1494         NULL,
1495         NULL
1496     },
1497     { /* 0x6d */
1498         &FOLDERID_UserProfiles,
1499         CSIDL_Type_CurrVer,
1500         UsersW,
1501         MAKEINTRESOURCEW(IDS_USER_PROFILES)
1502     },
1503     { /* 0x6e */
1504         &FOLDERID_UserProgramFiles,
1505         CSIDL_Type_Disallowed, /* FIXME */
1506         NULL,
1507         NULL
1508     },
1509     { /* 0x6f */
1510         &FOLDERID_UserProgramFilesCommon,
1511         CSIDL_Type_Disallowed, /* FIXME */
1512         NULL,
1513         NULL
1514     },
1515     { /* 0x70 */
1516         &FOLDERID_UsersFiles,
1517         CSIDL_Type_Disallowed,
1518         NULL,
1519         NULL
1520     },
1521     { /* 0x71 */
1522         &FOLDERID_UsersLibraries,
1523         CSIDL_Type_Disallowed,
1524         NULL,
1525         NULL
1526     },
1527     { /* 0x72 */
1528         &FOLDERID_VideosLibrary,
1529         CSIDL_Type_Disallowed, /* FIXME */
1530         NULL,
1531         NULL
1532     }
1533 };
1534
1535 static HRESULT _SHExpandEnvironmentStrings(LPCWSTR szSrc, LPWSTR szDest);
1536
1537 /* Gets the value named value from the registry key
1538  * rootKey\Software\Microsoft\Windows\CurrentVersion\Explorer\User Shell Folders
1539  * (or from rootKey\userPrefix\... if userPrefix is not NULL) into path, which
1540  * is assumed to be MAX_PATH WCHARs in length.
1541  * If it exists, expands the value and writes the expanded value to
1542  * rootKey\Software\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders
1543  * Returns successful error code if the value was retrieved from the registry,
1544  * and a failure otherwise.
1545  */
1546 static HRESULT _SHGetUserShellFolderPath(HKEY rootKey, LPCWSTR userPrefix,
1547  LPCWSTR value, LPWSTR path)
1548 {
1549     HRESULT hr;
1550     WCHAR shellFolderPath[MAX_PATH], userShellFolderPath[MAX_PATH];
1551     LPCWSTR pShellFolderPath, pUserShellFolderPath;
1552     DWORD dwType, dwPathLen = MAX_PATH;
1553     HKEY userShellFolderKey, shellFolderKey;
1554
1555     TRACE("%p,%s,%s,%p\n",rootKey, debugstr_w(userPrefix), debugstr_w(value),
1556      path);
1557
1558     if (userPrefix)
1559     {
1560         strcpyW(shellFolderPath, userPrefix);
1561         PathAddBackslashW(shellFolderPath);
1562         strcatW(shellFolderPath, szSHFolders);
1563         pShellFolderPath = shellFolderPath;
1564         strcpyW(userShellFolderPath, userPrefix);
1565         PathAddBackslashW(userShellFolderPath);
1566         strcatW(userShellFolderPath, szSHUserFolders);
1567         pUserShellFolderPath = userShellFolderPath;
1568     }
1569     else
1570     {
1571         pUserShellFolderPath = szSHUserFolders;
1572         pShellFolderPath = szSHFolders;
1573     }
1574
1575     if (RegCreateKeyW(rootKey, pShellFolderPath, &shellFolderKey))
1576     {
1577         TRACE("Failed to create %s\n", debugstr_w(pShellFolderPath));
1578         return E_FAIL;
1579     }
1580     if (RegCreateKeyW(rootKey, pUserShellFolderPath, &userShellFolderKey))
1581     {
1582         TRACE("Failed to create %s\n",
1583          debugstr_w(pUserShellFolderPath));
1584         RegCloseKey(shellFolderKey);
1585         return E_FAIL;
1586     }
1587
1588     if (!RegQueryValueExW(userShellFolderKey, value, NULL, &dwType,
1589      (LPBYTE)path, &dwPathLen) && (dwType == REG_EXPAND_SZ || dwType == REG_SZ))
1590     {
1591         LONG ret;
1592
1593         path[dwPathLen / sizeof(WCHAR)] = '\0';
1594         if (dwType == REG_EXPAND_SZ && path[0] == '%')
1595         {
1596             WCHAR szTemp[MAX_PATH];
1597
1598             _SHExpandEnvironmentStrings(path, szTemp);
1599             lstrcpynW(path, szTemp, MAX_PATH);
1600         }
1601         ret = RegSetValueExW(shellFolderKey, value, 0, REG_SZ, (LPBYTE)path,
1602          (strlenW(path) + 1) * sizeof(WCHAR));
1603         if (ret != ERROR_SUCCESS)
1604             hr = HRESULT_FROM_WIN32(ret);
1605         else
1606             hr = S_OK;
1607     }
1608     else
1609         hr = E_FAIL;
1610     RegCloseKey(shellFolderKey);
1611     RegCloseKey(userShellFolderKey);
1612     TRACE("returning 0x%08x\n", hr);
1613     return hr;
1614 }
1615
1616 /* Gets a 'semi-expanded' default value of the CSIDL with index folder into
1617  * pszPath, based on the entries in CSIDL_Data.  By semi-expanded, I mean:
1618  * - The entry's szDefaultPath may be either a string value or an integer
1619  *   resource identifier.  In the latter case, the string value of the resource
1620  *   is written.
1621  * - Depending on the entry's type, the path may begin with an (unexpanded)
1622  *   environment variable name.  The caller is responsible for expanding
1623  *   environment strings if so desired.
1624  *   The types that are prepended with environment variables are:
1625  *   CSIDL_Type_User:     %USERPROFILE%
1626  *   CSIDL_Type_AllUsers: %ALLUSERSPROFILE%
1627  *   CSIDL_Type_CurrVer:  %SystemDrive%
1628  *   (Others might make sense too, but as yet are unneeded.)
1629  */
1630 static HRESULT _SHGetDefaultValue(BYTE folder, LPWSTR pszPath)
1631 {
1632     HRESULT hr;
1633     WCHAR resourcePath[MAX_PATH];
1634     LPCWSTR pDefaultPath = NULL;
1635
1636     TRACE("0x%02x,%p\n", folder, pszPath);
1637
1638     if (folder >= sizeof(CSIDL_Data) / sizeof(CSIDL_Data[0]))
1639         return E_INVALIDARG;
1640     if (!pszPath)
1641         return E_INVALIDARG;
1642
1643     if (!is_win64)
1644     {
1645         BOOL is_wow64;
1646
1647         switch (folder)
1648         {
1649         case CSIDL_PROGRAM_FILES:
1650         case CSIDL_PROGRAM_FILESX86:
1651             IsWow64Process( GetCurrentProcess(), &is_wow64 );
1652             folder = is_wow64 ? CSIDL_PROGRAM_FILESX86 : CSIDL_PROGRAM_FILES;
1653             break;
1654         case CSIDL_PROGRAM_FILES_COMMON:
1655         case CSIDL_PROGRAM_FILES_COMMONX86:
1656             IsWow64Process( GetCurrentProcess(), &is_wow64 );
1657             folder = is_wow64 ? CSIDL_PROGRAM_FILES_COMMONX86 : CSIDL_PROGRAM_FILES_COMMON;
1658             break;
1659         }
1660     }
1661
1662     if (CSIDL_Data[folder].szDefaultPath &&
1663      IS_INTRESOURCE(CSIDL_Data[folder].szDefaultPath))
1664     {
1665         if (LoadStringW(shell32_hInstance,
1666          LOWORD(CSIDL_Data[folder].szDefaultPath), resourcePath, MAX_PATH))
1667         {
1668             hr = S_OK;
1669             pDefaultPath = resourcePath;
1670         }
1671         else
1672         {
1673             FIXME("(%d,%s), LoadString failed, missing translation?\n", folder,
1674              debugstr_w(pszPath));
1675             hr = E_FAIL;
1676         }
1677     }
1678     else
1679     {
1680         hr = S_OK;
1681         pDefaultPath = CSIDL_Data[folder].szDefaultPath;
1682     }
1683     if (SUCCEEDED(hr))
1684     {
1685         switch (CSIDL_Data[folder].type)
1686         {
1687             case CSIDL_Type_User:
1688                 strcpyW(pszPath, UserProfileW);
1689                 break;
1690             case CSIDL_Type_AllUsers:
1691                 strcpyW(pszPath, AllUsersProfileW);
1692                 break;
1693             case CSIDL_Type_CurrVer:
1694                 strcpyW(pszPath, SystemDriveW);
1695                 break;
1696             default:
1697                 ; /* no corresponding env. var, do nothing */
1698         }
1699         if (pDefaultPath)
1700         {
1701             PathAddBackslashW(pszPath);
1702             strcatW(pszPath, pDefaultPath);
1703         }
1704     }
1705     TRACE("returning 0x%08x\n", hr);
1706     return hr;
1707 }
1708
1709 /* Gets the (unexpanded) value of the folder with index folder into pszPath.
1710  * The folder's type is assumed to be CSIDL_Type_CurrVer.  Its default value
1711  * can be overridden in the HKLM\\szCurrentVersion key.
1712  * If dwFlags has SHGFP_TYPE_DEFAULT set or if the value isn't overridden in
1713  * the registry, uses _SHGetDefaultValue to get the value.
1714  */
1715 static HRESULT _SHGetCurrentVersionPath(DWORD dwFlags, BYTE folder,
1716  LPWSTR pszPath)
1717 {
1718     HRESULT hr;
1719
1720     TRACE("0x%08x,0x%02x,%p\n", dwFlags, folder, pszPath);
1721
1722     if (folder >= sizeof(CSIDL_Data) / sizeof(CSIDL_Data[0]))
1723         return E_INVALIDARG;
1724     if (CSIDL_Data[folder].type != CSIDL_Type_CurrVer)
1725         return E_INVALIDARG;
1726     if (!pszPath)
1727         return E_INVALIDARG;
1728
1729     if (dwFlags & SHGFP_TYPE_DEFAULT)
1730         hr = _SHGetDefaultValue(folder, pszPath);
1731     else
1732     {
1733         HKEY hKey;
1734
1735         if (RegCreateKeyW(HKEY_LOCAL_MACHINE, szCurrentVersion, &hKey))
1736             hr = E_FAIL;
1737         else
1738         {
1739             DWORD dwType, dwPathLen = MAX_PATH * sizeof(WCHAR);
1740
1741             if (RegQueryValueExW(hKey, CSIDL_Data[folder].szValueName, NULL,
1742              &dwType, (LPBYTE)pszPath, &dwPathLen) ||
1743              (dwType != REG_SZ && dwType != REG_EXPAND_SZ))
1744             {
1745                 hr = _SHGetDefaultValue(folder, pszPath);
1746                 dwType = REG_EXPAND_SZ;
1747                 switch (folder)
1748                 {
1749                 case CSIDL_PROGRAM_FILESX86:
1750                 case CSIDL_PROGRAM_FILES_COMMONX86:
1751                     /* these two should never be set on 32-bit setups */
1752                     if (!is_win64)
1753                     {
1754                         BOOL is_wow64;
1755                         IsWow64Process( GetCurrentProcess(), &is_wow64 );
1756                         if (!is_wow64) break;
1757                     }
1758                     /* fall through */
1759                 default:
1760                     RegSetValueExW(hKey, CSIDL_Data[folder].szValueName, 0, dwType,
1761                                    (LPBYTE)pszPath, (strlenW(pszPath)+1)*sizeof(WCHAR));
1762                 }
1763             }
1764             else
1765             {
1766                 pszPath[dwPathLen / sizeof(WCHAR)] = '\0';
1767                 hr = S_OK;
1768             }
1769             RegCloseKey(hKey);
1770         }
1771     }
1772     TRACE("returning 0x%08x (output path is %s)\n", hr, debugstr_w(pszPath));
1773     return hr;
1774 }
1775
1776 static LPWSTR _GetUserSidStringFromToken(HANDLE Token)
1777 {
1778     char InfoBuffer[64];
1779     PTOKEN_USER UserInfo;
1780     DWORD InfoSize;
1781     LPWSTR SidStr;
1782
1783     UserInfo = (PTOKEN_USER) InfoBuffer;
1784     if (! GetTokenInformation(Token, TokenUser, InfoBuffer, sizeof(InfoBuffer),
1785                               &InfoSize))
1786     {
1787         if (GetLastError() != ERROR_INSUFFICIENT_BUFFER)
1788             return NULL;
1789         UserInfo = HeapAlloc(GetProcessHeap(), 0, InfoSize);
1790         if (UserInfo == NULL)
1791             return NULL;
1792         if (! GetTokenInformation(Token, TokenUser, UserInfo, InfoSize,
1793                                   &InfoSize))
1794         {
1795             HeapFree(GetProcessHeap(), 0, UserInfo);
1796             return NULL;
1797         }
1798     }
1799
1800     if (! ConvertSidToStringSidW(UserInfo->User.Sid, &SidStr))
1801         SidStr = NULL;
1802
1803     if (UserInfo != (PTOKEN_USER) InfoBuffer)
1804         HeapFree(GetProcessHeap(), 0, UserInfo);
1805
1806     return SidStr;
1807 }
1808
1809 /* Gets the user's path (unexpanded) for the CSIDL with index folder:
1810  * If SHGFP_TYPE_DEFAULT is set, calls _SHGetDefaultValue for it.  Otherwise
1811  * calls _SHGetUserShellFolderPath for it.  Where it looks depends on hToken:
1812  * - if hToken is -1, looks in HKEY_USERS\.Default
1813  * - otherwise looks first in HKEY_CURRENT_USER, followed by HKEY_LOCAL_MACHINE
1814  *   if HKEY_CURRENT_USER doesn't contain any entries.  If both fail, finally
1815  *   calls _SHGetDefaultValue for it.
1816  */
1817 static HRESULT _SHGetUserProfilePath(HANDLE hToken, DWORD dwFlags, BYTE folder,
1818  LPWSTR pszPath)
1819 {
1820     HRESULT hr;
1821
1822     TRACE("%p,0x%08x,0x%02x,%p\n", hToken, dwFlags, folder, pszPath);
1823
1824     if (folder >= sizeof(CSIDL_Data) / sizeof(CSIDL_Data[0]))
1825         return E_INVALIDARG;
1826     if (CSIDL_Data[folder].type != CSIDL_Type_User)
1827         return E_INVALIDARG;
1828     if (!pszPath)
1829         return E_INVALIDARG;
1830
1831     if (dwFlags & SHGFP_TYPE_DEFAULT)
1832     {
1833         if (hToken != NULL && hToken != (HANDLE)-1)
1834         {
1835             FIXME("unsupported for user other than current or default\n");
1836             return E_FAIL;
1837         }
1838         hr = _SHGetDefaultValue(folder, pszPath);
1839     }
1840     else
1841     {
1842         LPCWSTR userPrefix = NULL;
1843         HKEY hRootKey;
1844
1845         if (hToken == (HANDLE)-1)
1846         {
1847             hRootKey = HKEY_USERS;
1848             userPrefix = DefaultW;
1849         }
1850         else if (hToken == NULL)
1851             hRootKey = HKEY_CURRENT_USER;
1852         else
1853         {
1854             hRootKey = HKEY_USERS;
1855             userPrefix = _GetUserSidStringFromToken(hToken);
1856             if (userPrefix == NULL)
1857             {
1858                 hr = E_FAIL;
1859                 goto error;
1860             }
1861         }
1862         hr = _SHGetUserShellFolderPath(hRootKey, userPrefix,
1863          CSIDL_Data[folder].szValueName, pszPath);
1864         if (FAILED(hr) && hRootKey != HKEY_LOCAL_MACHINE)
1865             hr = _SHGetUserShellFolderPath(HKEY_LOCAL_MACHINE, NULL,
1866              CSIDL_Data[folder].szValueName, pszPath);
1867         if (FAILED(hr))
1868             hr = _SHGetDefaultValue(folder, pszPath);
1869         if (userPrefix != NULL && userPrefix != DefaultW)
1870             LocalFree((HLOCAL) userPrefix);
1871     }
1872 error:
1873     TRACE("returning 0x%08x (output path is %s)\n", hr, debugstr_w(pszPath));
1874     return hr;
1875 }
1876
1877 /* Gets the (unexpanded) path for the CSIDL with index folder.  If dwFlags has
1878  * SHGFP_TYPE_DEFAULT set, calls _SHGetDefaultValue.  Otherwise calls
1879  * _SHGetUserShellFolderPath for it, looking only in HKEY_LOCAL_MACHINE.
1880  * If this fails, falls back to _SHGetDefaultValue.
1881  */
1882 static HRESULT _SHGetAllUsersProfilePath(DWORD dwFlags, BYTE folder,
1883  LPWSTR pszPath)
1884 {
1885     HRESULT hr;
1886
1887     TRACE("0x%08x,0x%02x,%p\n", dwFlags, folder, pszPath);
1888
1889     if (folder >= sizeof(CSIDL_Data) / sizeof(CSIDL_Data[0]))
1890         return E_INVALIDARG;
1891     if (CSIDL_Data[folder].type != CSIDL_Type_AllUsers)
1892         return E_INVALIDARG;
1893     if (!pszPath)
1894         return E_INVALIDARG;
1895
1896     if (dwFlags & SHGFP_TYPE_DEFAULT)
1897         hr = _SHGetDefaultValue(folder, pszPath);
1898     else
1899     {
1900         hr = _SHGetUserShellFolderPath(HKEY_LOCAL_MACHINE, NULL,
1901          CSIDL_Data[folder].szValueName, pszPath);
1902         if (FAILED(hr))
1903             hr = _SHGetDefaultValue(folder, pszPath);
1904     }
1905     TRACE("returning 0x%08x (output path is %s)\n", hr, debugstr_w(pszPath));
1906     return hr;
1907 }
1908
1909 static HRESULT _SHOpenProfilesKey(PHKEY pKey)
1910 {
1911     LONG lRet;
1912     DWORD disp;
1913
1914     lRet = RegCreateKeyExW(HKEY_LOCAL_MACHINE, ProfileListW, 0, NULL, 0,
1915      KEY_ALL_ACCESS, NULL, pKey, &disp);
1916     return HRESULT_FROM_WIN32(lRet);
1917 }
1918
1919 /* Reads the value named szValueName from the key profilesKey (assumed to be
1920  * opened by _SHOpenProfilesKey) into szValue, which is assumed to be MAX_PATH
1921  * WCHARs in length.  If it doesn't exist, returns szDefault (and saves
1922  * szDefault to the registry).
1923  */
1924 static HRESULT _SHGetProfilesValue(HKEY profilesKey, LPCWSTR szValueName,
1925  LPWSTR szValue, LPCWSTR szDefault)
1926 {
1927     HRESULT hr;
1928     DWORD type, dwPathLen = MAX_PATH * sizeof(WCHAR);
1929     LONG lRet;
1930
1931     TRACE("%p,%s,%p,%s\n", profilesKey, debugstr_w(szValueName), szValue,
1932      debugstr_w(szDefault));
1933     lRet = RegQueryValueExW(profilesKey, szValueName, NULL, &type,
1934      (LPBYTE)szValue, &dwPathLen);
1935     if (!lRet && (type == REG_SZ || type == REG_EXPAND_SZ) && dwPathLen
1936      && *szValue)
1937     {
1938         dwPathLen /= sizeof(WCHAR);
1939         szValue[dwPathLen] = '\0';
1940         hr = S_OK;
1941     }
1942     else
1943     {
1944         /* Missing or invalid value, set a default */
1945         lstrcpynW(szValue, szDefault, MAX_PATH);
1946         TRACE("Setting missing value %s to %s\n", debugstr_w(szValueName),
1947                                                   debugstr_w(szValue));
1948         lRet = RegSetValueExW(profilesKey, szValueName, 0, REG_EXPAND_SZ,
1949                               (LPBYTE)szValue,
1950                               (strlenW(szValue) + 1) * sizeof(WCHAR));
1951         if (lRet)
1952             hr = HRESULT_FROM_WIN32(lRet);
1953         else
1954             hr = S_OK;
1955     }
1956     TRACE("returning 0x%08x (output value is %s)\n", hr, debugstr_w(szValue));
1957     return hr;
1958 }
1959
1960 /* Attempts to expand environment variables from szSrc into szDest, which is
1961  * assumed to be MAX_PATH characters in length.  Before referring to the
1962  * environment, handles a few variables directly, because the environment
1963  * variables may not be set when this is called (as during Wine's installation
1964  * when default values are being written to the registry).
1965  * The directly handled environment variables, and their source, are:
1966  * - ALLUSERSPROFILE, USERPROFILE: reads from the registry
1967  * - SystemDrive: uses GetSystemDirectoryW and uses the drive portion of its
1968  *   path
1969  * If one of the directly handled environment variables is expanded, only
1970  * expands a single variable, and only in the beginning of szSrc.
1971  */
1972 static HRESULT _SHExpandEnvironmentStrings(LPCWSTR szSrc, LPWSTR szDest)
1973 {
1974     HRESULT hr;
1975     WCHAR szTemp[MAX_PATH], szProfilesPrefix[MAX_PATH] = { 0 };
1976     HKEY key = NULL;
1977
1978     TRACE("%s, %p\n", debugstr_w(szSrc), szDest);
1979
1980     if (!szSrc || !szDest) return E_INVALIDARG;
1981
1982     /* short-circuit if there's nothing to expand */
1983     if (szSrc[0] != '%')
1984     {
1985         strcpyW(szDest, szSrc);
1986         hr = S_OK;
1987         goto end;
1988     }
1989     /* Get the profile prefix, we'll probably be needing it */
1990     hr = _SHOpenProfilesKey(&key);
1991     if (SUCCEEDED(hr))
1992     {
1993         WCHAR def_val[MAX_PATH];
1994
1995         /* get the system drive */
1996         GetSystemDirectoryW(def_val, MAX_PATH);
1997         if (def_val[1] == ':') strcpyW( def_val + 3, szDefaultProfileDirW );
1998         else FIXME("non-drive system paths unsupported\n");
1999
2000         hr = _SHGetProfilesValue(key, ProfilesDirectoryW, szProfilesPrefix, def_val );
2001     }
2002
2003     *szDest = 0;
2004     strcpyW(szTemp, szSrc);
2005     while (SUCCEEDED(hr) && szTemp[0] == '%')
2006     {
2007         if (!strncmpiW(szTemp, AllUsersProfileW, strlenW(AllUsersProfileW)))
2008         {
2009             WCHAR szAllUsers[MAX_PATH];
2010
2011             strcpyW(szDest, szProfilesPrefix);
2012             hr = _SHGetProfilesValue(key, AllUsersProfileValueW,
2013              szAllUsers, AllUsersW);
2014             PathAppendW(szDest, szAllUsers);
2015             PathAppendW(szDest, szTemp + strlenW(AllUsersProfileW));
2016         }
2017         else if (!strncmpiW(szTemp, UserProfileW, strlenW(UserProfileW)))
2018         {
2019             WCHAR userName[MAX_PATH];
2020             DWORD userLen = MAX_PATH;
2021
2022             strcpyW(szDest, szProfilesPrefix);
2023             GetUserNameW(userName, &userLen);
2024             PathAppendW(szDest, userName);
2025             PathAppendW(szDest, szTemp + strlenW(UserProfileW));
2026         }
2027         else if (!strncmpiW(szTemp, SystemDriveW, strlenW(SystemDriveW)))
2028         {
2029             GetSystemDirectoryW(szDest, MAX_PATH);
2030             if (szDest[1] != ':')
2031             {
2032                 FIXME("non-drive system paths unsupported\n");
2033                 hr = E_FAIL;
2034             }
2035             else
2036             {
2037                 strcpyW(szDest + 3, szTemp + strlenW(SystemDriveW) + 1);
2038                 hr = S_OK;
2039             }
2040         }
2041         else
2042         {
2043             DWORD ret = ExpandEnvironmentStringsW(szSrc, szDest, MAX_PATH);
2044
2045             if (ret > MAX_PATH)
2046                 hr = HRESULT_FROM_WIN32(ERROR_INSUFFICIENT_BUFFER);
2047             else if (ret == 0)
2048                 hr = HRESULT_FROM_WIN32(GetLastError());
2049             else
2050                 hr = S_OK;
2051         }
2052         if (SUCCEEDED(hr) && szDest[0] == '%')
2053             strcpyW(szTemp, szDest);
2054         else
2055         {
2056             /* terminate loop */
2057             szTemp[0] = '\0';
2058         }
2059     }
2060 end:
2061     if (key)
2062         RegCloseKey(key);
2063     TRACE("returning 0x%08x (input was %s, output is %s)\n", hr,
2064      debugstr_w(szSrc), debugstr_w(szDest));
2065     return hr;
2066 }
2067
2068 /*************************************************************************
2069  * SHGetFolderPathW                     [SHELL32.@]
2070  *
2071  * Convert nFolder to path.  
2072  *
2073  * RETURNS
2074  *  Success: S_OK
2075  *  Failure: standard HRESULT error codes.
2076  *
2077  * NOTES
2078  * Most values can be overridden in either
2079  * HKCU\Software\Microsoft\Windows\CurrentVersion\Explorer\User Shell Folders
2080  * or in the same location in HKLM.
2081  * The "Shell Folders" registry key was used in NT4 and earlier systems.
2082  * Beginning with Windows 2000, the "User Shell Folders" key is used, so
2083  * changes made to it are made to the former key too.  This synchronization is
2084  * done on-demand: not until someone requests the value of one of these paths
2085  * (by calling one of the SHGet functions) is the value synchronized.
2086  * Furthermore, the HKCU paths take precedence over the HKLM paths.
2087  */
2088 HRESULT WINAPI SHGetFolderPathW(
2089         HWND hwndOwner,    /* [I] owner window */
2090         int nFolder,       /* [I] CSIDL identifying the folder */
2091         HANDLE hToken,     /* [I] access token */
2092         DWORD dwFlags,     /* [I] which path to return */
2093         LPWSTR pszPath)    /* [O] converted path */
2094 {
2095     HRESULT hr =  SHGetFolderPathAndSubDirW(hwndOwner, nFolder, hToken, dwFlags, NULL, pszPath);
2096     if(HRESULT_FROM_WIN32(ERROR_PATH_NOT_FOUND) == hr)
2097         hr = HRESULT_FROM_WIN32(ERROR_FILE_NOT_FOUND);
2098     return hr;
2099 }
2100
2101 HRESULT WINAPI SHGetFolderPathAndSubDirA(
2102         HWND hwndOwner,    /* [I] owner window */
2103         int nFolder,       /* [I] CSIDL identifying the folder */
2104         HANDLE hToken,     /* [I] access token */
2105         DWORD dwFlags,     /* [I] which path to return */
2106         LPCSTR pszSubPath, /* [I] sub directory of the specified folder */
2107         LPSTR pszPath)     /* [O] converted path */
2108 {
2109     int length;
2110     HRESULT hr = S_OK;
2111     LPWSTR pszSubPathW = NULL;
2112     LPWSTR pszPathW = NULL;
2113     TRACE("%08x,%08x,%s\n",nFolder, dwFlags, debugstr_w(pszSubPathW));
2114
2115     if(pszPath) {
2116         pszPathW = HeapAlloc(GetProcessHeap(), 0, MAX_PATH * sizeof(WCHAR));
2117         if(!pszPathW) {
2118             hr = HRESULT_FROM_WIN32(ERROR_NOT_ENOUGH_MEMORY);
2119             goto cleanup;
2120         }
2121     }
2122     TRACE("%08x,%08x,%s\n",nFolder, dwFlags, debugstr_w(pszSubPathW));
2123
2124     /* SHGetFolderPathAndSubDirW does not distinguish if pszSubPath isn't
2125      * set (null), or an empty string.therefore call it without the parameter set
2126      * if pszSubPath is an empty string
2127      */
2128     if (pszSubPath && pszSubPath[0]) {
2129         length = MultiByteToWideChar(CP_ACP, 0, pszSubPath, -1, NULL, 0);
2130         pszSubPathW = HeapAlloc(GetProcessHeap(), 0, length * sizeof(WCHAR));
2131         if(!pszSubPathW) {
2132             hr = HRESULT_FROM_WIN32(ERROR_NOT_ENOUGH_MEMORY);
2133             goto cleanup;
2134         }
2135         MultiByteToWideChar(CP_ACP, 0, pszSubPath, -1, pszSubPathW, length);
2136     }
2137
2138     hr = SHGetFolderPathAndSubDirW(hwndOwner, nFolder, hToken, dwFlags, pszSubPathW, pszPathW);
2139
2140     if (SUCCEEDED(hr) && pszPath)
2141         WideCharToMultiByte(CP_ACP, 0, pszPathW, -1, pszPath, MAX_PATH, NULL, NULL);
2142
2143 cleanup:
2144     HeapFree(GetProcessHeap(), 0, pszPathW);
2145     HeapFree(GetProcessHeap(), 0, pszSubPathW);
2146     return hr;
2147 }
2148
2149 /*************************************************************************
2150  * SHGetFolderPathAndSubDirW            [SHELL32.@]
2151  */
2152 HRESULT WINAPI SHGetFolderPathAndSubDirW(
2153         HWND hwndOwner,    /* [I] owner window */
2154         int nFolder,       /* [I] CSIDL identifying the folder */
2155         HANDLE hToken,     /* [I] access token */
2156         DWORD dwFlags,     /* [I] which path to return */
2157         LPCWSTR pszSubPath,/* [I] sub directory of the specified folder */
2158         LPWSTR pszPath)    /* [O] converted path */
2159 {
2160     HRESULT    hr;
2161     WCHAR      szBuildPath[MAX_PATH], szTemp[MAX_PATH];
2162     DWORD      folder = nFolder & CSIDL_FOLDER_MASK;
2163     CSIDL_Type type;
2164     int        ret;
2165     
2166     TRACE("%p,%p,nFolder=0x%04x,%s\n", hwndOwner,pszPath,nFolder,debugstr_w(pszSubPath));
2167
2168     /* Windows always NULL-terminates the resulting path regardless of success
2169      * or failure, so do so first
2170      */
2171     if (pszPath)
2172         *pszPath = '\0';
2173
2174     if (folder >= sizeof(CSIDL_Data) / sizeof(CSIDL_Data[0]))
2175         return E_INVALIDARG;
2176     if ((SHGFP_TYPE_CURRENT != dwFlags) && (SHGFP_TYPE_DEFAULT != dwFlags))
2177         return E_INVALIDARG;
2178     szTemp[0] = 0;
2179     type = CSIDL_Data[folder].type;
2180     switch (type)
2181     {
2182         case CSIDL_Type_Disallowed:
2183             hr = E_INVALIDARG;
2184             break;
2185         case CSIDL_Type_NonExistent:
2186             hr = S_FALSE;
2187             break;
2188         case CSIDL_Type_WindowsPath:
2189             GetWindowsDirectoryW(szTemp, MAX_PATH);
2190             if (CSIDL_Data[folder].szDefaultPath &&
2191              !IS_INTRESOURCE(CSIDL_Data[folder].szDefaultPath) &&
2192              *CSIDL_Data[folder].szDefaultPath)
2193             {
2194                 PathAddBackslashW(szTemp);
2195                 strcatW(szTemp, CSIDL_Data[folder].szDefaultPath);
2196             }
2197             hr = S_OK;
2198             break;
2199         case CSIDL_Type_SystemPath:
2200             GetSystemDirectoryW(szTemp, MAX_PATH);
2201             if (CSIDL_Data[folder].szDefaultPath &&
2202              !IS_INTRESOURCE(CSIDL_Data[folder].szDefaultPath) &&
2203              *CSIDL_Data[folder].szDefaultPath)
2204             {
2205                 PathAddBackslashW(szTemp);
2206                 strcatW(szTemp, CSIDL_Data[folder].szDefaultPath);
2207             }
2208             hr = S_OK;
2209             break;
2210         case CSIDL_Type_SystemX86Path:
2211             if (!GetSystemWow64DirectoryW(szTemp, MAX_PATH)) GetSystemDirectoryW(szTemp, MAX_PATH);
2212             if (CSIDL_Data[folder].szDefaultPath &&
2213              !IS_INTRESOURCE(CSIDL_Data[folder].szDefaultPath) &&
2214              *CSIDL_Data[folder].szDefaultPath)
2215             {
2216                 PathAddBackslashW(szTemp);
2217                 strcatW(szTemp, CSIDL_Data[folder].szDefaultPath);
2218             }
2219             hr = S_OK;
2220             break;
2221         case CSIDL_Type_CurrVer:
2222             hr = _SHGetCurrentVersionPath(dwFlags, folder, szTemp);
2223             break;
2224         case CSIDL_Type_User:
2225             hr = _SHGetUserProfilePath(hToken, dwFlags, folder, szTemp);
2226             break;
2227         case CSIDL_Type_AllUsers:
2228             hr = _SHGetAllUsersProfilePath(dwFlags, folder, szTemp);
2229             break;
2230         default:
2231             FIXME("bogus type %d, please fix\n", type);
2232             hr = E_INVALIDARG;
2233             break;
2234     }
2235
2236     /* Expand environment strings if necessary */
2237     if (*szTemp == '%')
2238         hr = _SHExpandEnvironmentStrings(szTemp, szBuildPath);
2239     else
2240         strcpyW(szBuildPath, szTemp);
2241
2242     if (FAILED(hr)) goto end;
2243
2244     if(pszSubPath) {
2245         /* make sure the new path does not exceed th bufferlength
2246          * rememebr to backslash and the termination */
2247         if(MAX_PATH < (lstrlenW(szBuildPath) + lstrlenW(pszSubPath) + 2)) {
2248             hr = HRESULT_FROM_WIN32(ERROR_FILENAME_EXCED_RANGE);
2249             goto end;
2250         }
2251         PathAppendW(szBuildPath, pszSubPath);
2252         PathRemoveBackslashW(szBuildPath);
2253     }
2254     /* Copy the path if it's available before we might return */
2255     if (SUCCEEDED(hr) && pszPath)
2256         strcpyW(pszPath, szBuildPath);
2257
2258     /* if we don't care about existing directories we are ready */
2259     if(nFolder & CSIDL_FLAG_DONT_VERIFY) goto end;
2260
2261     if (PathFileExistsW(szBuildPath)) goto end;
2262
2263     /* not existing but we are not allowed to create it.  The return value
2264      * is verified against shell32 version 6.0.
2265      */
2266     if (!(nFolder & CSIDL_FLAG_CREATE))
2267     {
2268         hr = HRESULT_FROM_WIN32(ERROR_PATH_NOT_FOUND);
2269         goto end;
2270     }
2271
2272     /* create directory/directories */
2273     ret = SHCreateDirectoryExW(hwndOwner, szBuildPath, NULL);
2274     if (ret && ret != ERROR_ALREADY_EXISTS)
2275     {
2276         ERR("Failed to create directory %s.\n", debugstr_w(szBuildPath));
2277         hr = E_FAIL;
2278         goto end;
2279     }
2280
2281     TRACE("Created missing system directory %s\n", debugstr_w(szBuildPath));
2282 end:
2283     TRACE("returning 0x%08x (final path is %s)\n", hr, debugstr_w(szBuildPath));
2284     return hr;
2285 }
2286
2287 /*************************************************************************
2288  * SHGetFolderPathA                     [SHELL32.@]
2289  *
2290  * See SHGetFolderPathW.
2291  */
2292 HRESULT WINAPI SHGetFolderPathA(
2293         HWND hwndOwner,
2294         int nFolder,
2295         HANDLE hToken,
2296         DWORD dwFlags,
2297         LPSTR pszPath)
2298 {
2299     WCHAR szTemp[MAX_PATH];
2300     HRESULT hr;
2301
2302     TRACE("%p,%p,nFolder=0x%04x\n",hwndOwner,pszPath,nFolder);
2303
2304     if (pszPath)
2305         *pszPath = '\0';
2306     hr = SHGetFolderPathW(hwndOwner, nFolder, hToken, dwFlags, szTemp);
2307     if (SUCCEEDED(hr) && pszPath)
2308         WideCharToMultiByte(CP_ACP, 0, szTemp, -1, pszPath, MAX_PATH, NULL,
2309          NULL);
2310
2311     return hr;
2312 }
2313
2314 /* For each folder in folders, if its value has not been set in the registry,
2315  * calls _SHGetUserProfilePath or _SHGetAllUsersProfilePath (depending on the
2316  * folder's type) to get the unexpanded value first.
2317  * Writes the unexpanded value to User Shell Folders, and queries it with
2318  * SHGetFolderPathW to force the creation of the directory if it doesn't
2319  * already exist.  SHGetFolderPathW also returns the expanded value, which
2320  * this then writes to Shell Folders.
2321  */
2322 static HRESULT _SHRegisterFolders(HKEY hRootKey, HANDLE hToken,
2323  LPCWSTR szUserShellFolderPath, LPCWSTR szShellFolderPath, const UINT folders[],
2324  UINT foldersLen)
2325 {
2326     UINT i;
2327     WCHAR path[MAX_PATH];
2328     HRESULT hr = S_OK;
2329     HKEY hUserKey = NULL, hKey = NULL;
2330     DWORD dwType, dwPathLen;
2331     LONG ret;
2332
2333     TRACE("%p,%p,%s,%p,%u\n", hRootKey, hToken,
2334      debugstr_w(szUserShellFolderPath), folders, foldersLen);
2335
2336     ret = RegCreateKeyW(hRootKey, szUserShellFolderPath, &hUserKey);
2337     if (ret)
2338         hr = HRESULT_FROM_WIN32(ret);
2339     else
2340     {
2341         ret = RegCreateKeyW(hRootKey, szShellFolderPath, &hKey);
2342         if (ret)
2343             hr = HRESULT_FROM_WIN32(ret);
2344     }
2345     for (i = 0; SUCCEEDED(hr) && i < foldersLen; i++)
2346     {
2347         dwPathLen = MAX_PATH * sizeof(WCHAR);
2348         if (RegQueryValueExW(hUserKey, CSIDL_Data[folders[i]].szValueName, NULL,
2349          &dwType, (LPBYTE)path, &dwPathLen) || (dwType != REG_SZ &&
2350          dwType != REG_EXPAND_SZ))
2351         {
2352             *path = '\0';
2353             if (CSIDL_Data[folders[i]].type == CSIDL_Type_User)
2354                 _SHGetUserProfilePath(hToken, SHGFP_TYPE_DEFAULT, folders[i],
2355                  path);
2356             else if (CSIDL_Data[folders[i]].type == CSIDL_Type_AllUsers)
2357                 _SHGetAllUsersProfilePath(SHGFP_TYPE_DEFAULT, folders[i], path);
2358             else if (CSIDL_Data[folders[i]].type == CSIDL_Type_WindowsPath)
2359             {
2360                 GetWindowsDirectoryW(path, MAX_PATH);
2361                 if (CSIDL_Data[folders[i]].szDefaultPath &&
2362                     !IS_INTRESOURCE(CSIDL_Data[folders[i]].szDefaultPath))
2363                 {
2364                     PathAddBackslashW(path);
2365                     strcatW(path, CSIDL_Data[folders[i]].szDefaultPath);
2366                 }
2367             }
2368             else
2369                 hr = E_FAIL;
2370             if (*path)
2371             {
2372                 ret = RegSetValueExW(hUserKey,
2373                  CSIDL_Data[folders[i]].szValueName, 0, REG_EXPAND_SZ,
2374                  (LPBYTE)path, (strlenW(path) + 1) * sizeof(WCHAR));
2375                 if (ret)
2376                     hr = HRESULT_FROM_WIN32(ret);
2377                 else
2378                 {
2379                     hr = SHGetFolderPathW(NULL, folders[i] | CSIDL_FLAG_CREATE,
2380                      hToken, SHGFP_TYPE_DEFAULT, path);
2381                     ret = RegSetValueExW(hKey,
2382                      CSIDL_Data[folders[i]].szValueName, 0, REG_SZ,
2383                      (LPBYTE)path, (strlenW(path) + 1) * sizeof(WCHAR));
2384                     if (ret)
2385                         hr = HRESULT_FROM_WIN32(ret);
2386                 }
2387             }
2388         }
2389     }
2390     if (hUserKey)
2391         RegCloseKey(hUserKey);
2392     if (hKey)
2393         RegCloseKey(hKey);
2394
2395     TRACE("returning 0x%08x\n", hr);
2396     return hr;
2397 }
2398
2399 static HRESULT _SHRegisterUserShellFolders(BOOL bDefault)
2400 {
2401     static const UINT folders[] = {
2402      CSIDL_PROGRAMS,
2403      CSIDL_PERSONAL,
2404      CSIDL_FAVORITES,
2405      CSIDL_APPDATA,
2406      CSIDL_STARTUP,
2407      CSIDL_RECENT,
2408      CSIDL_SENDTO,
2409      CSIDL_STARTMENU,
2410      CSIDL_MYMUSIC,
2411      CSIDL_MYVIDEO,
2412      CSIDL_DESKTOPDIRECTORY,
2413      CSIDL_NETHOOD,
2414      CSIDL_TEMPLATES,
2415      CSIDL_PRINTHOOD,
2416      CSIDL_LOCAL_APPDATA,
2417      CSIDL_INTERNET_CACHE,
2418      CSIDL_COOKIES,
2419      CSIDL_HISTORY,
2420      CSIDL_MYPICTURES,
2421      CSIDL_FONTS
2422     };
2423     WCHAR userShellFolderPath[MAX_PATH], shellFolderPath[MAX_PATH];
2424     LPCWSTR pUserShellFolderPath, pShellFolderPath;
2425     HRESULT hr = S_OK;
2426     HKEY hRootKey;
2427     HANDLE hToken;
2428
2429     TRACE("%s\n", bDefault ? "TRUE" : "FALSE");
2430     if (bDefault)
2431     {
2432         hToken = (HANDLE)-1;
2433         hRootKey = HKEY_USERS;
2434         strcpyW(userShellFolderPath, DefaultW);
2435         PathAddBackslashW(userShellFolderPath);
2436         strcatW(userShellFolderPath, szSHUserFolders);
2437         pUserShellFolderPath = userShellFolderPath;
2438         strcpyW(shellFolderPath, DefaultW);
2439         PathAddBackslashW(shellFolderPath);
2440         strcatW(shellFolderPath, szSHFolders);
2441         pShellFolderPath = shellFolderPath;
2442     }
2443     else
2444     {
2445         hToken = NULL;
2446         hRootKey = HKEY_CURRENT_USER;
2447         pUserShellFolderPath = szSHUserFolders;
2448         pShellFolderPath = szSHFolders;
2449     }
2450
2451     hr = _SHRegisterFolders(hRootKey, hToken, pUserShellFolderPath,
2452      pShellFolderPath, folders, sizeof(folders) / sizeof(folders[0]));
2453     TRACE("returning 0x%08x\n", hr);
2454     return hr;
2455 }
2456
2457 static HRESULT _SHRegisterCommonShellFolders(void)
2458 {
2459     static const UINT folders[] = {
2460      CSIDL_COMMON_STARTMENU,
2461      CSIDL_COMMON_PROGRAMS,
2462      CSIDL_COMMON_STARTUP,
2463      CSIDL_COMMON_DESKTOPDIRECTORY,
2464      CSIDL_COMMON_FAVORITES,
2465      CSIDL_COMMON_APPDATA,
2466      CSIDL_COMMON_TEMPLATES,
2467      CSIDL_COMMON_DOCUMENTS,
2468      CSIDL_COMMON_ADMINTOOLS,
2469      CSIDL_COMMON_MUSIC,
2470      CSIDL_COMMON_PICTURES,
2471      CSIDL_COMMON_VIDEO,
2472     };
2473     HRESULT hr;
2474
2475     TRACE("\n");
2476     hr = _SHRegisterFolders(HKEY_LOCAL_MACHINE, NULL, szSHUserFolders,
2477      szSHFolders, folders, sizeof(folders) / sizeof(folders[0]));
2478     TRACE("returning 0x%08x\n", hr);
2479     return hr;
2480 }
2481
2482 /******************************************************************************
2483  * _SHAppendToUnixPath  [Internal]
2484  *
2485  * Helper function for _SHCreateSymbolicLinks. Appends pwszSubPath (or the 
2486  * corresponding resource, if IS_INTRESOURCE) to the unix base path 'szBasePath' 
2487  * and replaces backslashes with slashes.
2488  *
2489  * PARAMS
2490  *  szBasePath  [IO] The unix base path, which will be appended to (CP_UNXICP).
2491  *  pwszSubPath [I]  Sub-path or resource id (use MAKEINTRESOURCEW).
2492  *
2493  * RETURNS
2494  *  Success: TRUE,
2495  *  Failure: FALSE
2496  */
2497 static inline BOOL _SHAppendToUnixPath(char *szBasePath, LPCWSTR pwszSubPath) {
2498     WCHAR wszSubPath[MAX_PATH];
2499     int cLen = strlen(szBasePath);
2500     char *pBackslash;
2501
2502     if (IS_INTRESOURCE(pwszSubPath)) {
2503         if (!LoadStringW(shell32_hInstance, LOWORD(pwszSubPath), wszSubPath, MAX_PATH)) {
2504             /* Fall back to hard coded defaults. */
2505             switch (LOWORD(pwszSubPath)) {
2506                 case IDS_PERSONAL:
2507                     lstrcpyW(wszSubPath, PersonalW);
2508                     break;
2509                 case IDS_MYMUSIC:
2510                     lstrcpyW(wszSubPath, My_MusicW);
2511                     break;
2512                 case IDS_MYPICTURES:
2513                     lstrcpyW(wszSubPath, My_PicturesW);
2514                     break;
2515                 case IDS_MYVIDEO:
2516                     lstrcpyW(wszSubPath, My_VideoW);
2517                     break;
2518                 default:
2519                     ERR("LoadString(%d) failed!\n", LOWORD(pwszSubPath));
2520                     return FALSE;
2521             }
2522         }
2523     } else {
2524         lstrcpyW(wszSubPath, pwszSubPath);
2525     }
2526  
2527     if (szBasePath[cLen-1] != '/') szBasePath[cLen++] = '/';
2528  
2529     if (!WideCharToMultiByte(CP_UNIXCP, 0, wszSubPath, -1, szBasePath + cLen,
2530                              FILENAME_MAX - cLen, NULL, NULL))
2531     {
2532         return FALSE;
2533     }
2534  
2535     pBackslash = szBasePath + cLen;
2536     while ((pBackslash = strchr(pBackslash, '\\'))) *pBackslash = '/';
2537  
2538     return TRUE;
2539 }
2540
2541 /******************************************************************************
2542  * _SHCreateSymbolicLinks  [Internal]
2543  * 
2544  * Sets up symbol links for various shell folders to point into the users home
2545  * directory. We do an educated guess about what the user would probably want:
2546  * - If there is a 'My Documents' directory in $HOME, the user probably wants
2547  *   wine's 'My Documents' to point there. Furthermore, we imply that the user
2548  *   is a Windows lover and has no problem with wine creating 'My Pictures',
2549  *   'My Music' and 'My Video' subfolders under '$HOME/My Documents', if those
2550  *   do not already exits. We put appropriate symbolic links in place for those,
2551  *   too.
2552  * - If there is no 'My Documents' directory in $HOME, we let 'My Documents'
2553  *   point directly to $HOME. We assume the user to be a unix hacker who does not
2554  *   want wine to create anything anywhere besides the .wine directory. So, if
2555  *   there already is a 'My Music' directory in $HOME, we symlink the 'My Music'
2556  *   shell folder to it. But if not, then we check XDG_MUSIC_DIR - "well known"
2557  *   directory, and try to link to that. If that fails, then we symlink to
2558  *   $HOME directly. The same holds fo 'My Pictures' and 'My Video'.
2559  * - The Desktop shell folder is symlinked to XDG_DESKTOP_DIR. If that does not
2560  *   exist, then we try '$HOME/Desktop'. If that does not exist, then we leave
2561  *   it alone.
2562  * ('My Music',... above in fact means LoadString(IDS_MYMUSIC))
2563  */
2564 static void _SHCreateSymbolicLinks(void)
2565 {
2566     UINT aidsMyStuff[] = { IDS_MYPICTURES, IDS_MYVIDEO, IDS_MYMUSIC }, i;
2567     int acsidlMyStuff[] = { CSIDL_MYPICTURES, CSIDL_MYVIDEO, CSIDL_MYMUSIC };
2568     static const char * const xdg_dirs[] = { "PICTURES", "VIDEOS", "MUSIC", "DESKTOP" };
2569     static const unsigned int num = sizeof(xdg_dirs) / sizeof(xdg_dirs[0]);
2570     WCHAR wszTempPath[MAX_PATH];
2571     char szPersonalTarget[FILENAME_MAX], *pszPersonal;
2572     char szMyStuffTarget[FILENAME_MAX], *pszMyStuff;
2573     char szDesktopTarget[FILENAME_MAX], *pszDesktop;
2574     struct stat statFolder;
2575     const char *pszHome;
2576     HRESULT hr;
2577     char ** xdg_results;
2578     char * xdg_desktop_dir;
2579
2580     /* Create all necessary profile sub-dirs up to 'My Documents' and get the unix path. */
2581     hr = SHGetFolderPathW(NULL, CSIDL_PERSONAL|CSIDL_FLAG_CREATE, NULL,
2582                           SHGFP_TYPE_DEFAULT, wszTempPath);
2583     if (FAILED(hr)) return;
2584     pszPersonal = wine_get_unix_file_name(wszTempPath);
2585     if (!pszPersonal) return;
2586
2587     hr = XDG_UserDirLookup(xdg_dirs, num, &xdg_results);
2588     if (FAILED(hr)) xdg_results = NULL;
2589
2590     pszHome = getenv("HOME");
2591     if (pszHome && !stat(pszHome, &statFolder) && S_ISDIR(statFolder.st_mode)) {
2592         strcpy(szPersonalTarget, pszHome);
2593         if (_SHAppendToUnixPath(szPersonalTarget, MAKEINTRESOURCEW(IDS_PERSONAL)) &&
2594             !stat(szPersonalTarget, &statFolder) && S_ISDIR(statFolder.st_mode))
2595         {
2596             /* '$HOME/My Documents' exists. Create 'My Pictures', 'My Videos' and 
2597              * 'My Music' subfolders or fail silently if they already exist. */
2598             for (i = 0; i < sizeof(aidsMyStuff)/sizeof(aidsMyStuff[0]); i++) {
2599                 strcpy(szMyStuffTarget, szPersonalTarget);
2600                 if (_SHAppendToUnixPath(szMyStuffTarget, MAKEINTRESOURCEW(aidsMyStuff[i])))
2601                     mkdir(szMyStuffTarget, 0777);
2602             }
2603         } 
2604         else
2605         {
2606             /* '$HOME/My Documents' doesn't exists, but '$HOME' does. */ 
2607             strcpy(szPersonalTarget, pszHome);
2608         }
2609
2610         /* Replace 'My Documents' directory with a symlink of fail silently if not empty. */
2611         rmdir(pszPersonal);
2612         symlink(szPersonalTarget, pszPersonal);
2613     }
2614     else
2615     {
2616         /* '$HOME' doesn't exist. Create 'My Pictures', 'My Videos' and 'My Music' subdirs
2617          * in '%USERPROFILE%\\My Documents' or fail silently if they already exist. */
2618         strcpy(szPersonalTarget, pszPersonal);
2619         for (i = 0; i < sizeof(aidsMyStuff)/sizeof(aidsMyStuff[0]); i++) {
2620             strcpy(szMyStuffTarget, szPersonalTarget);
2621             if (_SHAppendToUnixPath(szMyStuffTarget, MAKEINTRESOURCEW(aidsMyStuff[i])))
2622                 mkdir(szMyStuffTarget, 0777);
2623         }
2624     }
2625
2626     /* Create symbolic links for 'My Pictures', 'My Video' and 'My Music'. */
2627     for (i=0; i < sizeof(aidsMyStuff)/sizeof(aidsMyStuff[0]); i++) {
2628         /* Create the current 'My Whatever' folder and get it's unix path. */
2629         hr = SHGetFolderPathW(NULL, acsidlMyStuff[i]|CSIDL_FLAG_CREATE, NULL,
2630                               SHGFP_TYPE_DEFAULT, wszTempPath);
2631         if (FAILED(hr)) continue;
2632         pszMyStuff = wine_get_unix_file_name(wszTempPath);
2633         if (!pszMyStuff) continue;
2634         
2635         strcpy(szMyStuffTarget, szPersonalTarget);
2636         if (_SHAppendToUnixPath(szMyStuffTarget, MAKEINTRESOURCEW(aidsMyStuff[i])) &&
2637             !stat(szMyStuffTarget, &statFolder) && S_ISDIR(statFolder.st_mode))
2638         {
2639             /* If there's a 'My Whatever' directory where 'My Documents' links to, link to it. */
2640             rmdir(pszMyStuff);
2641             symlink(szMyStuffTarget, pszMyStuff);
2642         } 
2643         else
2644         {
2645             rmdir(pszMyStuff);
2646             if (xdg_results && xdg_results[i])
2647             {
2648                 /* the folder specified by XDG_XXX_DIR exists, link to it. */
2649                 symlink(xdg_results[i], pszMyStuff);
2650             }
2651             else
2652             {
2653                 /* Else link to where 'My Documents' itself links to. */
2654                 symlink(szPersonalTarget, pszMyStuff);
2655             }
2656         }
2657         HeapFree(GetProcessHeap(), 0, pszMyStuff);
2658     }
2659
2660     /* Last but not least, the Desktop folder */
2661     if (pszHome)
2662         strcpy(szDesktopTarget, pszHome);
2663     else
2664         strcpy(szDesktopTarget, pszPersonal);
2665     HeapFree(GetProcessHeap(), 0, pszPersonal);
2666
2667     xdg_desktop_dir = xdg_results ? xdg_results[num - 1] : NULL;
2668     if (xdg_desktop_dir ||
2669         (_SHAppendToUnixPath(szDesktopTarget, DesktopW) &&
2670         !stat(szDesktopTarget, &statFolder) && S_ISDIR(statFolder.st_mode)))
2671     {
2672         hr = SHGetFolderPathW(NULL, CSIDL_DESKTOPDIRECTORY|CSIDL_FLAG_CREATE, NULL,
2673                               SHGFP_TYPE_DEFAULT, wszTempPath);
2674         if (SUCCEEDED(hr) && (pszDesktop = wine_get_unix_file_name(wszTempPath))) 
2675         {
2676             rmdir(pszDesktop);
2677             if (xdg_desktop_dir)
2678                 symlink(xdg_desktop_dir, pszDesktop);
2679             else
2680                 symlink(szDesktopTarget, pszDesktop);
2681             HeapFree(GetProcessHeap(), 0, pszDesktop);
2682         }
2683     }
2684
2685     /* Free resources allocated by XDG_UserDirLookup() */
2686     if (xdg_results)
2687     {
2688         for (i = 0; i < num; i++)
2689             HeapFree(GetProcessHeap(), 0, xdg_results[i]);
2690         HeapFree(GetProcessHeap(), 0, xdg_results);
2691     }
2692 }
2693
2694 /******************************************************************************
2695  * create_extra_folders  [Internal]
2696  *
2697  * Create some extra folders that don't have a standard CSIDL definition.
2698  */
2699 static HRESULT create_extra_folders(void)
2700 {
2701     static const WCHAR environW[] = {'E','n','v','i','r','o','n','m','e','n','t',0};
2702     static const WCHAR TempW[]    = {'T','e','m','p',0};
2703     static const WCHAR TEMPW[]    = {'T','E','M','P',0};
2704     static const WCHAR TMPW[]     = {'T','M','P',0};
2705     WCHAR path[MAX_PATH+5];
2706     HRESULT hr;
2707     HKEY hkey;
2708     DWORD type, size, ret;
2709
2710     ret = RegCreateKeyW( HKEY_CURRENT_USER, environW, &hkey );
2711     if (ret) return HRESULT_FROM_WIN32( ret );
2712
2713     /* FIXME: should be under AppData, but we don't want spaces in the temp path */
2714     hr = SHGetFolderPathAndSubDirW( 0, CSIDL_PROFILE | CSIDL_FLAG_CREATE, NULL,
2715                                     SHGFP_TYPE_DEFAULT, TempW, path );
2716     if (SUCCEEDED(hr))
2717     {
2718         size = sizeof(path);
2719         if (RegQueryValueExW( hkey, TEMPW, NULL, &type, (LPBYTE)path, &size ))
2720             RegSetValueExW( hkey, TEMPW, 0, REG_SZ, (LPBYTE)path, (strlenW(path) + 1) * sizeof(WCHAR) );
2721         size = sizeof(path);
2722         if (RegQueryValueExW( hkey, TMPW, NULL, &type, (LPBYTE)path, &size ))
2723             RegSetValueExW( hkey, TMPW, 0, REG_SZ, (LPBYTE)path, (strlenW(path) + 1) * sizeof(WCHAR) );
2724     }
2725     RegCloseKey( hkey );
2726     return hr;
2727 }
2728
2729
2730 /******************************************************************************
2731  * set_folder_attributes
2732  *
2733  * Set the various folder attributes registry keys.
2734  */
2735 static HRESULT set_folder_attributes(void)
2736 {
2737     static const WCHAR clsidW[] = {'C','L','S','I','D','\\',0 };
2738     static const WCHAR shellfolderW[] = {'\\','S','h','e','l','l','F','o','l','d','e','r', 0 };
2739     static const WCHAR wfparsingW[] = {'W','a','n','t','s','F','O','R','P','A','R','S','I','N','G',0};
2740     static const WCHAR wfdisplayW[] = {'W','a','n','t','s','F','O','R','D','I','S','P','L','A','Y',0};
2741     static const WCHAR hideasdeleteW[] = {'H','i','d','e','A','s','D','e','l','e','t','e','P','e','r','U','s','e','r',0};
2742     static const WCHAR attributesW[] = {'A','t','t','r','i','b','u','t','e','s',0};
2743     static const WCHAR cfattributesW[] = {'C','a','l','l','F','o','r','A','t','t','r','i','b','u','t','e','s',0};
2744     static const WCHAR emptyW[] = {0};
2745
2746     static const struct
2747     {
2748         const CLSID *clsid;
2749         BOOL wfparsing : 1;
2750         BOOL wfdisplay : 1;
2751         BOOL hideasdel : 1;
2752         DWORD attr;
2753         DWORD call_for_attr;
2754     } folders[] =
2755     {
2756         { &CLSID_UnixFolder, TRUE, FALSE, FALSE },
2757         { &CLSID_UnixDosFolder, TRUE, FALSE, FALSE,
2758           SFGAO_FILESYSANCESTOR|SFGAO_FOLDER|SFGAO_HASSUBFOLDER, SFGAO_FILESYSTEM },
2759         { &CLSID_FolderShortcut, FALSE, FALSE, FALSE,
2760           SFGAO_FILESYSTEM|SFGAO_FOLDER|SFGAO_LINK,
2761           SFGAO_HASSUBFOLDER|SFGAO_FILESYSTEM|SFGAO_FOLDER|SFGAO_FILESYSANCESTOR },
2762         { &CLSID_MyDocuments, TRUE, FALSE, FALSE,
2763           SFGAO_FILESYSANCESTOR|SFGAO_FOLDER|SFGAO_HASSUBFOLDER, SFGAO_FILESYSTEM },
2764         { &CLSID_RecycleBin, FALSE, FALSE, FALSE,
2765           SFGAO_FOLDER|SFGAO_DROPTARGET|SFGAO_HASPROPSHEET },
2766         { &CLSID_ControlPanel, FALSE, TRUE, TRUE,
2767           SFGAO_FOLDER|SFGAO_HASSUBFOLDER }
2768     };
2769
2770     unsigned int i;
2771     WCHAR buffer[39 + (sizeof(clsidW) + sizeof(shellfolderW)) / sizeof(WCHAR)];
2772     LONG res;
2773     HKEY hkey;
2774
2775     for (i = 0; i < sizeof(folders)/sizeof(folders[0]); i++)
2776     {
2777         strcpyW( buffer, clsidW );
2778         StringFromGUID2( folders[i].clsid, buffer + strlenW(buffer), 39 );
2779         strcatW( buffer, shellfolderW );
2780         res = RegCreateKeyExW( HKEY_CLASSES_ROOT, buffer, 0, NULL, 0,
2781                                KEY_READ | KEY_WRITE, NULL, &hkey, NULL);
2782         if (res) return HRESULT_FROM_WIN32( res );
2783         if (folders[i].wfparsing)
2784             res = RegSetValueExW( hkey, wfparsingW, 0, REG_SZ, (const BYTE *)emptyW, sizeof(emptyW) );
2785         if (folders[i].wfdisplay)
2786             res = RegSetValueExW( hkey, wfdisplayW, 0, REG_SZ, (const BYTE *)emptyW, sizeof(emptyW) );
2787         if (folders[i].hideasdel)
2788             res = RegSetValueExW( hkey, hideasdeleteW, 0, REG_SZ, (const BYTE *)emptyW, sizeof(emptyW) );
2789         if (folders[i].attr)
2790             res = RegSetValueExW( hkey, attributesW, 0, REG_DWORD,
2791                                   (const BYTE *)&folders[i].attr, sizeof(DWORD));
2792         if (folders[i].call_for_attr)
2793             res = RegSetValueExW( hkey, cfattributesW, 0, REG_DWORD,
2794                                  (const BYTE *)&folders[i].call_for_attr, sizeof(DWORD));
2795         RegCloseKey( hkey );
2796     }
2797     return S_OK;
2798 }
2799
2800
2801 /* Register the default values in the registry, as some apps seem to depend
2802  * on their presence.  The set registered was taken from Windows XP.
2803  */
2804 HRESULT SHELL_RegisterShellFolders(void)
2805 {
2806     HRESULT hr;
2807
2808     /* Set up '$HOME' targeted symlinks for 'My Documents', 'My Pictures',
2809      * 'My Video', 'My Music' and 'Desktop' in advance, so that the
2810      * _SHRegister*ShellFolders() functions will find everything nice and clean
2811      * and thus will not attempt to create them in the profile directory. */
2812     _SHCreateSymbolicLinks();
2813     
2814     hr = _SHRegisterUserShellFolders(TRUE);
2815     if (SUCCEEDED(hr))
2816         hr = _SHRegisterUserShellFolders(FALSE);
2817     if (SUCCEEDED(hr))
2818         hr = _SHRegisterCommonShellFolders();
2819     if (SUCCEEDED(hr))
2820         hr = create_extra_folders();
2821     if (SUCCEEDED(hr))
2822         hr = set_folder_attributes();
2823     return hr;
2824 }
2825
2826 /*************************************************************************
2827  * SHGetSpecialFolderPathA [SHELL32.@]
2828  */
2829 BOOL WINAPI SHGetSpecialFolderPathA (
2830         HWND hwndOwner,
2831         LPSTR szPath,
2832         int nFolder,
2833         BOOL bCreate)
2834 {
2835         return (SHGetFolderPathA(
2836                 hwndOwner,
2837                 nFolder + (bCreate ? CSIDL_FLAG_CREATE : 0),
2838                 NULL,
2839                 0,
2840                 szPath)) == S_OK ? TRUE : FALSE;
2841 }
2842
2843 /*************************************************************************
2844  * SHGetSpecialFolderPathW
2845  */
2846 BOOL WINAPI SHGetSpecialFolderPathW (
2847         HWND hwndOwner,
2848         LPWSTR szPath,
2849         int nFolder,
2850         BOOL bCreate)
2851 {
2852         return (SHGetFolderPathW(
2853                 hwndOwner,
2854                 nFolder + (bCreate ? CSIDL_FLAG_CREATE : 0),
2855                 NULL,
2856                 0,
2857                 szPath)) == S_OK ? TRUE : FALSE;
2858 }
2859
2860 /*************************************************************************
2861  * SHGetSpecialFolderPath (SHELL32.175)
2862  */
2863 BOOL WINAPI SHGetSpecialFolderPathAW (
2864         HWND hwndOwner,
2865         LPVOID szPath,
2866         int nFolder,
2867         BOOL bCreate)
2868
2869 {
2870         if (SHELL_OsIsUnicode())
2871           return SHGetSpecialFolderPathW (hwndOwner, szPath, nFolder, bCreate);
2872         return SHGetSpecialFolderPathA (hwndOwner, szPath, nFolder, bCreate);
2873 }
2874
2875 /*************************************************************************
2876  * SHGetFolderLocation [SHELL32.@]
2877  *
2878  * Gets the folder locations from the registry and creates a pidl.
2879  *
2880  * PARAMS
2881  *   hwndOwner  [I]
2882  *   nFolder    [I] CSIDL_xxxxx
2883  *   hToken     [I] token representing user, or NULL for current user, or -1 for
2884  *                  default user
2885  *   dwReserved [I] must be zero
2886  *   ppidl      [O] PIDL of a special folder
2887  *
2888  * RETURNS
2889  *  Success: S_OK
2890  *  Failure: Standard OLE-defined error result, S_FALSE or E_INVALIDARG
2891  *
2892  * NOTES
2893  *  Creates missing reg keys and directories.
2894  *  Mostly forwards to SHGetFolderPathW, but a few values of nFolder return
2895  *  virtual folders that are handled here.
2896  */
2897 HRESULT WINAPI SHGetFolderLocation(
2898         HWND hwndOwner,
2899         int nFolder,
2900         HANDLE hToken,
2901         DWORD dwReserved,
2902         LPITEMIDLIST *ppidl)
2903 {
2904     HRESULT hr = E_INVALIDARG;
2905
2906     TRACE("%p 0x%08x %p 0x%08x %p\n",
2907      hwndOwner, nFolder, hToken, dwReserved, ppidl);
2908     
2909     if (!ppidl)
2910         return E_INVALIDARG;
2911     if (dwReserved)
2912         return E_INVALIDARG;
2913
2914     /* The virtual folders' locations are not user-dependent */
2915     *ppidl = NULL;
2916     switch (nFolder & CSIDL_FOLDER_MASK)
2917     {
2918         case CSIDL_DESKTOP:
2919             *ppidl = _ILCreateDesktop();
2920             break;
2921
2922         case CSIDL_PERSONAL:
2923             *ppidl = _ILCreateMyDocuments();
2924             break;
2925
2926         case CSIDL_INTERNET:
2927             *ppidl = _ILCreateIExplore();
2928             break;
2929
2930         case CSIDL_CONTROLS:
2931             *ppidl = _ILCreateControlPanel();
2932             break;
2933
2934         case CSIDL_PRINTERS:
2935             *ppidl = _ILCreatePrinters();
2936             break;
2937
2938         case CSIDL_BITBUCKET:
2939             *ppidl = _ILCreateBitBucket();
2940             break;
2941
2942         case CSIDL_DRIVES:
2943             *ppidl = _ILCreateMyComputer();
2944             break;
2945
2946         case CSIDL_NETWORK:
2947             *ppidl = _ILCreateNetwork();
2948             break;
2949
2950         default:
2951         {
2952             WCHAR szPath[MAX_PATH];
2953
2954             hr = SHGetFolderPathW(hwndOwner, nFolder, hToken,
2955              SHGFP_TYPE_CURRENT, szPath);
2956             if (SUCCEEDED(hr))
2957             {
2958                 DWORD attributes=0;
2959
2960                 TRACE("Value=%s\n", debugstr_w(szPath));
2961                 hr = SHILCreateFromPathW(szPath, ppidl, &attributes);
2962             }
2963             else if (hr == HRESULT_FROM_WIN32(ERROR_FILE_NOT_FOUND))
2964             {
2965                 /* unlike SHGetFolderPath, SHGetFolderLocation in shell32
2966                  * version 6.0 returns E_FAIL for nonexistent paths
2967                  */
2968                 hr = E_FAIL;
2969             }
2970         }
2971     }
2972     if(*ppidl)
2973         hr = NOERROR;
2974
2975     TRACE("-- (new pidl %p)\n",*ppidl);
2976     return hr;
2977 }
2978
2979 /*************************************************************************
2980  * SHGetSpecialFolderLocation           [SHELL32.@]
2981  *
2982  * NOTES
2983  *   In NT5, SHGetSpecialFolderLocation needs the <winntdir>/Recent
2984  *   directory.
2985  */
2986 HRESULT WINAPI SHGetSpecialFolderLocation(
2987         HWND hwndOwner,
2988         INT nFolder,
2989         LPITEMIDLIST * ppidl)
2990 {
2991     HRESULT hr = E_INVALIDARG;
2992
2993     TRACE("(%p,0x%x,%p)\n", hwndOwner,nFolder,ppidl);
2994
2995     if (!ppidl)
2996         return E_INVALIDARG;
2997
2998     hr = SHGetFolderLocation(hwndOwner, nFolder, NULL, 0, ppidl);
2999     return hr;
3000 }
3001
3002 static int csidl_from_id( const KNOWNFOLDERID *id )
3003 {
3004     int i;
3005     for (i = 0; i < sizeof(CSIDL_Data) / sizeof(CSIDL_Data[0]); i++)
3006         if (IsEqualGUID( CSIDL_Data[i].id, id )) return i;
3007     return -1;
3008 }
3009
3010 /*************************************************************************
3011  * SHGetKnownFolderPath           [SHELL32.@]
3012  */
3013 HRESULT WINAPI SHGetKnownFolderPath(REFKNOWNFOLDERID rfid, DWORD flags, HANDLE token, PWSTR *path)
3014 {
3015     HRESULT hr;
3016     WCHAR folder[MAX_PATH];
3017     int index = csidl_from_id( rfid );
3018
3019     TRACE("%s, 0x%08x, %p, %p\n", debugstr_guid(rfid), flags, token, path);
3020
3021     if (index < 0)
3022         return E_INVALIDARG;
3023
3024     if (flags & KF_FLAG_CREATE)
3025         index |= CSIDL_FLAG_CREATE;
3026
3027     if (flags & KF_FLAG_DONT_VERIFY)
3028         index |= CSIDL_FLAG_DONT_VERIFY;
3029
3030     if (flags & KF_FLAG_NO_ALIAS)
3031         index |= CSIDL_FLAG_NO_ALIAS;
3032
3033     if (flags & KF_FLAG_INIT)
3034         index |= CSIDL_FLAG_PER_USER_INIT;
3035
3036     if (flags & ~(KF_FLAG_CREATE|KF_FLAG_DONT_VERIFY|KF_FLAG_NO_ALIAS|KF_FLAG_INIT))
3037     {
3038         FIXME("flags 0x%08x not supported\n", flags);
3039         return E_INVALIDARG;
3040     }
3041
3042     hr = SHGetFolderPathW( NULL, index, token, 0, folder );
3043     if (SUCCEEDED(hr))
3044     {
3045         *path = CoTaskMemAlloc( (strlenW( folder ) + 1) * sizeof(WCHAR) );
3046         if (!*path)
3047             return E_OUTOFMEMORY;
3048         strcpyW( *path, folder );
3049     }
3050     return hr;
3051 }
3052
3053 /*************************************************************************
3054  * SHGetFolderPathEx           [SHELL32.@]
3055  */
3056 HRESULT WINAPI SHGetFolderPathEx(REFKNOWNFOLDERID rfid, DWORD flags, HANDLE token, LPWSTR path, DWORD len)
3057 {
3058     HRESULT hr;
3059     WCHAR *buffer;
3060
3061     TRACE("%s, 0x%08x, %p, %p, %u\n", debugstr_guid(rfid), flags, token, path, len);
3062
3063     if (!path || !len) return E_INVALIDARG;
3064
3065     hr = SHGetKnownFolderPath( rfid, flags, token, &buffer );
3066     if (SUCCEEDED( hr ))
3067     {
3068         if (strlenW( buffer ) + 1 > len)
3069         {
3070             CoTaskMemFree( buffer );
3071             return HRESULT_FROM_WIN32( ERROR_INSUFFICIENT_BUFFER );
3072         }
3073         strcpyW( path, buffer );
3074         CoTaskMemFree( buffer );
3075     }
3076     return hr;
3077 }
3078
3079 /* constant values used by known folder functions */
3080 static const WCHAR szCategory[] = {'C','a','t','e','g','o','r','y',0};
3081 static const WCHAR szName[] = {'N','a','m','e',0};
3082 static const WCHAR szRelativePath[] = {'R','e','l','a','t','i','v','e','P','a','t','h',0};
3083
3084 /*
3085  * Internal function to convert known folder identifier to path of registry key
3086  * associated with known folder.
3087  *
3088  * Parameters:
3089  *  rfid            [I] pointer to known folder identifier
3090  *  lpPath          [O] place to store string address. String should be
3091  *                      later freed using HeapFree(GetProcessHeap(),0, ... )
3092  */
3093 static HRESULT get_known_folder_registry_path(REFKNOWNFOLDERID rfid, LPWSTR *lpPath)
3094 {
3095     static const WCHAR sBackslash[] = {'\\',0};
3096     HRESULT hr = S_OK;
3097     int length;
3098     WCHAR sGuid[50];
3099
3100     TRACE("(%s, %p)\n", debugstr_guid(rfid), lpPath);
3101
3102     StringFromGUID2(rfid, sGuid, sizeof(sGuid)/sizeof(sGuid[0]));
3103
3104     length = lstrlenW(szKnownFolderDescriptions)+51;
3105     *lpPath = HeapAlloc(GetProcessHeap(), 0, length*sizeof(WCHAR));
3106     if(!(*lpPath))
3107         hr = E_OUTOFMEMORY;
3108
3109     if(SUCCEEDED(hr))
3110     {
3111         lstrcpyW(*lpPath, szKnownFolderDescriptions);
3112         lstrcatW(*lpPath, sBackslash);
3113         lstrcatW(*lpPath, sGuid);
3114     }
3115
3116     return hr;
3117 }
3118
3119 struct knownfolder
3120 {
3121     const struct IKnownFolderVtbl *vtbl;
3122     LONG refs;
3123     KNOWNFOLDERID id;
3124     LPWSTR registryPath;
3125 };
3126
3127 static inline struct knownfolder *impl_from_IKnownFolder( IKnownFolder *iface )
3128 {
3129     return (struct knownfolder *)((char *)iface - FIELD_OFFSET( struct knownfolder, vtbl ));
3130 }
3131
3132 static ULONG WINAPI knownfolder_AddRef(
3133     IKnownFolder *iface )
3134 {
3135     struct knownfolder *knownfolder = impl_from_IKnownFolder( iface );
3136     return InterlockedIncrement( &knownfolder->refs );
3137 }
3138
3139 static ULONG WINAPI knownfolder_Release(
3140     IKnownFolder *iface )
3141 {
3142     struct knownfolder *knownfolder = impl_from_IKnownFolder( iface );
3143     LONG refs = InterlockedDecrement( &knownfolder->refs );
3144     if (!refs)
3145     {
3146         TRACE("destroying %p\n", knownfolder);
3147         HeapFree( GetProcessHeap(), 0, knownfolder->registryPath);
3148         HeapFree( GetProcessHeap(), 0, knownfolder );
3149     }
3150     return refs;
3151 }
3152
3153 static HRESULT WINAPI knownfolder_QueryInterface(
3154     IKnownFolder *iface,
3155     REFIID riid,
3156     void **ppv )
3157 {
3158     struct knownfolder *This = impl_from_IKnownFolder( iface );
3159
3160     TRACE("%p %s %p\n", This, debugstr_guid( riid ), ppv );
3161
3162     if ( IsEqualGUID( riid, &IID_IKnownFolder ) ||
3163          IsEqualGUID( riid, &IID_IUnknown ) )
3164     {
3165         *ppv = iface;
3166     }
3167     else
3168     {
3169         FIXME("interface %s not implemented\n", debugstr_guid(riid));
3170         return E_NOINTERFACE;
3171     }
3172     IKnownFolder_AddRef( iface );
3173     return S_OK;
3174 }
3175
3176 static HRESULT knownfolder_set_id(
3177     IKnownFolder *iface,
3178     const KNOWNFOLDERID *kfid)
3179 {
3180     struct knownfolder *knownfolder = impl_from_IKnownFolder( iface );
3181     HKEY hKey;
3182     HRESULT hr;
3183
3184     TRACE("%s\n", debugstr_guid(kfid));
3185
3186     knownfolder->id = *kfid;
3187
3188     /* check is it registry-registered folder */
3189     hr = get_known_folder_registry_path(kfid, &knownfolder->registryPath);
3190     if(SUCCEEDED(hr))
3191         hr = HRESULT_FROM_WIN32(RegOpenKeyExW(HKEY_LOCAL_MACHINE, knownfolder->registryPath, 0, 0, &hKey));
3192
3193     if(SUCCEEDED(hr))
3194     {
3195         hr = S_OK;
3196         RegCloseKey(hKey);
3197     }
3198     else
3199     {
3200         /* This known folder is not registered. To mark it, we set registryPath to NULL */
3201         HeapFree(GetProcessHeap(), 0, knownfolder->registryPath);
3202         knownfolder->registryPath = NULL;
3203         hr = S_OK;
3204     }
3205
3206     return hr;
3207 }
3208
3209 static HRESULT WINAPI knownfolder_GetId(
3210     IKnownFolder *iface,
3211     KNOWNFOLDERID *pkfid)
3212 {
3213     struct knownfolder *knownfolder = impl_from_IKnownFolder( iface );
3214
3215     TRACE("%p\n", pkfid);
3216
3217     *pkfid = knownfolder->id;
3218     return S_OK;
3219 }
3220
3221 static HRESULT WINAPI knownfolder_GetCategory(
3222     IKnownFolder *iface,
3223     KF_CATEGORY *pCategory)
3224 {
3225     struct knownfolder *knownfolder = impl_from_IKnownFolder(iface);
3226     HRESULT hr = S_OK;
3227     DWORD dwSize, dwType;
3228
3229     TRACE("%p, %p\n", knownfolder, pCategory);
3230
3231     /* we cannot get a category for a folder which is not registered */
3232     if(!knownfolder->registryPath)
3233         hr = E_FAIL;
3234
3235     if(SUCCEEDED(hr))
3236         hr = HRESULT_FROM_WIN32(RegGetValueW(HKEY_LOCAL_MACHINE, knownfolder->registryPath, szCategory, RRF_RT_DWORD, &dwType, pCategory, &dwSize));
3237
3238     return hr;
3239 }
3240
3241 static HRESULT WINAPI knownfolder_GetShellItem(
3242     IKnownFolder *iface,
3243     DWORD dwFlags,
3244     REFIID riid,
3245     void **ppv)
3246 {
3247     FIXME("0x%08x, %s, %p\n", dwFlags, debugstr_guid(riid), ppv);
3248     return E_NOTIMPL;
3249 }
3250
3251 static HRESULT WINAPI knownfolder_GetPath(
3252     IKnownFolder *iface,
3253     DWORD dwFlags,
3254     LPWSTR *ppszPath)
3255 {
3256     struct knownfolder *knownfolder = impl_from_IKnownFolder( iface );
3257     DWORD dwSize, dwType;
3258     HRESULT hr;
3259
3260     TRACE("(%p, 0x%08x, %p)\n", knownfolder, dwFlags, ppszPath);
3261
3262     /* if this is registry-registered known folder, get path from registry */
3263     if(knownfolder->registryPath)
3264     {
3265         hr = HRESULT_FROM_WIN32(RegGetValueW(HKEY_LOCAL_MACHINE, knownfolder->registryPath, szRelativePath, RRF_RT_REG_SZ, &dwType, NULL, &dwSize));
3266
3267         if(SUCCEEDED(hr))
3268         {
3269             *ppszPath = CoTaskMemAlloc(dwSize);
3270             if(!*ppszPath) hr = E_OUTOFMEMORY;
3271         }
3272
3273         if(SUCCEEDED(hr))
3274             hr = HRESULT_FROM_WIN32(RegGetValueW(HKEY_LOCAL_MACHINE, knownfolder->registryPath, szRelativePath, RRF_RT_REG_SZ, &dwType, *ppszPath, &dwSize));
3275     }
3276     /* in other case, use older way */
3277     else
3278         hr = SHGetKnownFolderPath( &knownfolder->id, dwFlags, NULL, ppszPath );
3279
3280     return hr;
3281 }
3282
3283 static HRESULT WINAPI knownfolder_SetPath(
3284     IKnownFolder *iface,
3285     DWORD dwFlags,
3286     LPCWSTR pszPath)
3287 {
3288     struct knownfolder *knownfolder = impl_from_IKnownFolder( iface );
3289     HRESULT hr = S_OK;
3290     HKEY hKey;
3291     WCHAR szPath[MAX_PATH];
3292
3293     TRACE("(%p, 0x%08x, %p)\n", knownfolder, dwFlags, debugstr_w(pszPath));
3294
3295     /* check if the known folder is registered */
3296     if(!knownfolder->registryPath)
3297         hr = E_FAIL;
3298
3299     if(SUCCEEDED(hr))
3300     {
3301         if(dwFlags & KF_FLAG_DONT_UNEXPAND)
3302             lstrcpyW(szPath, pszPath);
3303         else
3304             hr = ( ExpandEnvironmentStringsW(pszPath, szPath, sizeof(szPath)/sizeof(szPath[0]))!=0 ? S_OK : HRESULT_FROM_WIN32(GetLastError()));
3305     }
3306
3307     if(SUCCEEDED(hr))
3308         hr = HRESULT_FROM_WIN32(RegOpenKeyExW(HKEY_LOCAL_MACHINE, knownfolder->registryPath, 0, KEY_SET_VALUE, &hKey));
3309
3310     if(SUCCEEDED(hr))
3311     {
3312         hr = HRESULT_FROM_WIN32(RegSetValueExW(hKey, szRelativePath, 0, REG_SZ, (LPBYTE)pszPath, (lstrlenW(pszPath)+1)*sizeof(WCHAR)));
3313
3314         RegCloseKey(hKey);
3315     }
3316
3317     return hr;
3318 }
3319
3320 static HRESULT WINAPI knownfolder_GetIDList(
3321     IKnownFolder *iface,
3322     DWORD dwFlags,
3323     PIDLIST_ABSOLUTE *ppidl)
3324 {
3325     FIXME("0x%08x, %p\n", dwFlags, ppidl);
3326     return E_NOTIMPL;
3327 }
3328
3329 static HRESULT WINAPI knownfolder_GetFolderType(
3330     IKnownFolder *iface,
3331     FOLDERTYPEID *pftid)
3332 {
3333     FIXME("%p\n", pftid);
3334     return E_NOTIMPL;
3335 }
3336
3337 static HRESULT WINAPI knownfolder_GetRedirectionCapabilities(
3338     IKnownFolder *iface,
3339     KF_REDIRECTION_CAPABILITIES *pCapabilities)
3340 {
3341     FIXME("%p\n", pCapabilities);
3342     return E_NOTIMPL;
3343 }
3344
3345 static HRESULT WINAPI knownfolder_GetFolderDefinition(
3346     IKnownFolder *iface,
3347     KNOWNFOLDER_DEFINITION *pKFD)
3348 {
3349     FIXME("%p\n", pKFD);
3350     return E_NOTIMPL;
3351 }
3352
3353 static const struct IKnownFolderVtbl knownfolder_vtbl =
3354 {
3355     knownfolder_QueryInterface,
3356     knownfolder_AddRef,
3357     knownfolder_Release,
3358     knownfolder_GetId,
3359     knownfolder_GetCategory,
3360     knownfolder_GetShellItem,
3361     knownfolder_GetPath,
3362     knownfolder_SetPath,
3363     knownfolder_GetIDList,
3364     knownfolder_GetFolderType,
3365     knownfolder_GetRedirectionCapabilities,
3366     knownfolder_GetFolderDefinition
3367 };
3368
3369 static HRESULT knownfolder_create( void **ppv )
3370 {
3371     struct knownfolder *kf;
3372
3373     kf = HeapAlloc( GetProcessHeap(), 0, sizeof(*kf) );
3374     if (!kf) return E_OUTOFMEMORY;
3375
3376     kf->vtbl = &knownfolder_vtbl;
3377     kf->refs = 1;
3378     memset( &kf->id, 0, sizeof(kf->id) );
3379     kf->registryPath = NULL;
3380
3381     *ppv = &kf->vtbl;
3382
3383     TRACE("returning iface %p\n", *ppv);
3384     return S_OK;
3385 }
3386
3387 struct foldermanager
3388 {
3389     const struct IKnownFolderManagerVtbl *vtbl;
3390     LONG refs;
3391     UINT num_ids;
3392     KNOWNFOLDERID *ids;
3393 };
3394
3395 static inline struct foldermanager *impl_from_IKnownFolderManager( IKnownFolderManager *iface )
3396 {
3397     return (struct foldermanager *)((char *)iface - FIELD_OFFSET( struct foldermanager, vtbl ));
3398 }
3399
3400 static ULONG WINAPI foldermanager_AddRef(
3401     IKnownFolderManager *iface )
3402 {
3403     struct foldermanager *foldermanager = impl_from_IKnownFolderManager( iface );
3404     return InterlockedIncrement( &foldermanager->refs );
3405 }
3406
3407 static ULONG WINAPI foldermanager_Release(
3408     IKnownFolderManager *iface )
3409 {
3410     struct foldermanager *foldermanager = impl_from_IKnownFolderManager( iface );
3411     LONG refs = InterlockedDecrement( &foldermanager->refs );
3412     if (!refs)
3413     {
3414         TRACE("destroying %p\n", foldermanager);
3415         HeapFree( GetProcessHeap(), 0, foldermanager->ids );
3416         HeapFree( GetProcessHeap(), 0, foldermanager );
3417     }
3418     return refs;
3419 }
3420
3421 static HRESULT WINAPI foldermanager_QueryInterface(
3422     IKnownFolderManager *iface,
3423     REFIID riid,
3424     void **ppv )
3425 {
3426     struct foldermanager *This = impl_from_IKnownFolderManager( iface );
3427
3428     TRACE("%p %s %p\n", This, debugstr_guid( riid ), ppv );
3429
3430     if ( IsEqualGUID( riid, &IID_IKnownFolderManager ) ||
3431          IsEqualGUID( riid, &IID_IUnknown ) )
3432     {
3433         *ppv = iface;
3434     }
3435     else
3436     {
3437         FIXME("interface %s not implemented\n", debugstr_guid(riid));
3438         return E_NOINTERFACE;
3439     }
3440     IKnownFolderManager_AddRef( iface );
3441     return S_OK;
3442 }
3443
3444 static HRESULT WINAPI foldermanager_FolderIdFromCsidl(
3445     IKnownFolderManager *iface,
3446     int nCsidl,
3447     KNOWNFOLDERID *pfid)
3448 {
3449     TRACE("%d, %p\n", nCsidl, pfid);
3450
3451     if (nCsidl >= sizeof(CSIDL_Data) / sizeof(CSIDL_Data[0]))
3452         return E_INVALIDARG;
3453     *pfid = *CSIDL_Data[nCsidl].id;
3454     return S_OK;
3455 }
3456
3457 static HRESULT WINAPI foldermanager_FolderIdToCsidl(
3458     IKnownFolderManager *iface,
3459     REFKNOWNFOLDERID rfid,
3460     int *pnCsidl)
3461 {
3462     int csidl;
3463
3464     TRACE("%s, %p\n", debugstr_guid(rfid), pnCsidl);
3465
3466     csidl = csidl_from_id( rfid );
3467     if (csidl == -1) return E_INVALIDARG;
3468     *pnCsidl = csidl;
3469     return S_OK;
3470 }
3471
3472 static HRESULT WINAPI foldermanager_GetFolderIds(
3473     IKnownFolderManager *iface,
3474     KNOWNFOLDERID **ppKFId,
3475     UINT *pCount)
3476 {
3477     struct foldermanager *fm = impl_from_IKnownFolderManager( iface );
3478
3479     TRACE("%p, %p\n", ppKFId, pCount);
3480
3481     *ppKFId = fm->ids;
3482     *pCount = fm->num_ids;
3483     return S_OK;
3484 }
3485
3486 static BOOL is_knownfolder( struct foldermanager *fm, const KNOWNFOLDERID *id )
3487 {
3488     UINT i;
3489     HRESULT hr;
3490     LPWSTR registryPath = NULL;
3491     HKEY hKey;
3492
3493     /* TODO: move all entries from "CSIDL_Data" static array to registry known folder descriptions */
3494     for (i = 0; i < fm->num_ids; i++)
3495         if (IsEqualGUID( &fm->ids[i], id )) return TRUE;
3496
3497     hr = get_known_folder_registry_path(id, &registryPath);
3498     if(SUCCEEDED(hr))
3499         hr = HRESULT_FROM_WIN32(RegOpenKeyExW(HKEY_LOCAL_MACHINE, registryPath, 0, 0, &hKey));
3500
3501     if(SUCCEEDED(hr))
3502     {
3503         hr = S_OK;
3504         RegCloseKey(hKey);
3505     }
3506
3507     return hr == S_OK;
3508 }
3509
3510 static HRESULT WINAPI foldermanager_GetFolder(
3511     IKnownFolderManager *iface,
3512     REFKNOWNFOLDERID rfid,
3513     IKnownFolder **ppkf)
3514 {
3515     struct foldermanager *fm = impl_from_IKnownFolderManager( iface );
3516     HRESULT hr;
3517
3518     TRACE("%s, %p\n", debugstr_guid(rfid), ppkf);
3519
3520     if (!is_knownfolder( fm, rfid ))
3521     {
3522         WARN("unknown folder\n");
3523         return E_INVALIDARG;
3524     }
3525     hr = knownfolder_create( (void **)ppkf );
3526     if (SUCCEEDED( hr ))
3527         hr = knownfolder_set_id( *ppkf, rfid );
3528
3529     return hr;
3530 }
3531
3532 static HRESULT WINAPI foldermanager_GetFolderByName(
3533     IKnownFolderManager *iface,
3534     LPCWSTR pszCanonicalName,
3535     IKnownFolder **ppkf)
3536 {
3537     FIXME("%s, %p\n", debugstr_w(pszCanonicalName), ppkf);
3538     return E_NOTIMPL;
3539 }
3540
3541 static HRESULT WINAPI foldermanager_RegisterFolder(
3542     IKnownFolderManager *iface,
3543     REFKNOWNFOLDERID rfid,
3544     KNOWNFOLDER_DEFINITION const *pKFD)
3545 {
3546     HRESULT hr;
3547     HKEY hKey = NULL;
3548     DWORD dwDisp;
3549     LPWSTR registryPath = NULL;
3550     TRACE("(%p, %s, %p)\n", iface, debugstr_guid(rfid), pKFD);
3551
3552     hr = get_known_folder_registry_path(rfid, &registryPath);
3553     TRACE("registry path: %s\n", debugstr_w(registryPath));
3554
3555     if(SUCCEEDED(hr))
3556         hr = HRESULT_FROM_WIN32(RegCreateKeyExW(HKEY_LOCAL_MACHINE, registryPath, 0, NULL, 0, KEY_WRITE, 0, &hKey, &dwDisp));
3557
3558     if(SUCCEEDED(hr))
3559     {
3560         if(dwDisp == REG_OPENED_EXISTING_KEY)
3561             hr = E_FAIL;
3562
3563         if(SUCCEEDED(hr))
3564             hr = HRESULT_FROM_WIN32(RegSetValueExW(hKey, szCategory, 0, REG_DWORD, (LPBYTE)&pKFD->category, sizeof(pKFD->category)));
3565
3566         if(SUCCEEDED(hr))
3567             hr = HRESULT_FROM_WIN32(RegSetValueExW(hKey, szName, 0, REG_SZ, (LPBYTE)pKFD->pszName, (lstrlenW(pKFD->pszName)+1)*sizeof(WCHAR) ));
3568
3569         if(SUCCEEDED(hr) && pKFD->category != KF_CATEGORY_VIRTUAL)
3570             hr = HRESULT_FROM_WIN32(RegSetValueExW(hKey, szRelativePath, 0, REG_SZ, (LPBYTE)pKFD->pszRelativePath, (lstrlenW(pKFD->pszRelativePath)+1)*sizeof(WCHAR) ));
3571
3572         RegCloseKey(hKey);
3573     }
3574
3575     HeapFree(GetProcessHeap(), 0, registryPath);
3576     return hr;
3577 }
3578
3579 static HRESULT WINAPI foldermanager_UnregisterFolder(
3580     IKnownFolderManager *iface,
3581     REFKNOWNFOLDERID rfid)
3582 {
3583     HRESULT hr;
3584     LPWSTR registryPath = NULL;
3585     TRACE("(%p, %s)\n", iface, debugstr_guid(rfid));
3586
3587     hr = get_known_folder_registry_path(rfid, &registryPath);
3588
3589     if(SUCCEEDED(hr))
3590         hr = HRESULT_FROM_WIN32(RegDeleteKeyW(HKEY_LOCAL_MACHINE, registryPath));
3591
3592     HeapFree(GetProcessHeap(), 0, registryPath);
3593     return hr;
3594 }
3595
3596 static HRESULT WINAPI foldermanager_FindFolderFromPath(
3597     IKnownFolderManager *iface,
3598     LPCWSTR pszPath,
3599     FFFP_MODE mode,
3600     IKnownFolder **ppkf)
3601 {
3602     FIXME("%s, 0x%08x, %p\n", debugstr_w(pszPath), mode, ppkf);
3603     return E_NOTIMPL;
3604 }
3605
3606 static HRESULT WINAPI foldermanager_FindFolderFromIDList(
3607     IKnownFolderManager *iface,
3608     PCIDLIST_ABSOLUTE pidl,
3609     IKnownFolder **ppkf)
3610 {
3611     FIXME("%p, %p\n", pidl, ppkf);
3612     return E_NOTIMPL;
3613 }
3614
3615 static HRESULT WINAPI foldermanager_Redirect(
3616     IKnownFolderManager *iface,
3617     REFKNOWNFOLDERID rfid,
3618     HWND hwnd,
3619     KF_REDIRECT_FLAGS flags,
3620     LPCWSTR pszTargetPath,
3621     UINT cFolders,
3622     KNOWNFOLDERID const *pExclusion,
3623     LPWSTR *ppszError)
3624 {
3625     FIXME("%p, %p, 0x%08x, %s, %u, %p, %p\n", rfid, hwnd, flags,
3626           debugstr_w(pszTargetPath), cFolders, pExclusion, ppszError);
3627     return E_NOTIMPL;
3628 }
3629
3630 static const struct IKnownFolderManagerVtbl foldermanager_vtbl =
3631 {
3632     foldermanager_QueryInterface,
3633     foldermanager_AddRef,
3634     foldermanager_Release,
3635     foldermanager_FolderIdFromCsidl,
3636     foldermanager_FolderIdToCsidl,
3637     foldermanager_GetFolderIds,
3638     foldermanager_GetFolder,
3639     foldermanager_GetFolderByName,
3640     foldermanager_RegisterFolder,
3641     foldermanager_UnregisterFolder,
3642     foldermanager_FindFolderFromPath,
3643     foldermanager_FindFolderFromIDList,
3644     foldermanager_Redirect
3645 };
3646
3647 static HRESULT foldermanager_create( void **ppv )
3648 {
3649     UINT i, j;
3650     struct foldermanager *fm;
3651
3652     fm = HeapAlloc( GetProcessHeap(), 0, sizeof(*fm) );
3653     if (!fm) return E_OUTOFMEMORY;
3654
3655     fm->vtbl = &foldermanager_vtbl;
3656     fm->refs = 1;
3657     fm->num_ids = 0;
3658
3659     for (i = 0; i < sizeof(CSIDL_Data) / sizeof(CSIDL_Data[0]); i++)
3660     {
3661         if (!IsEqualGUID( CSIDL_Data[i].id, &GUID_NULL )) fm->num_ids++;
3662     }
3663     fm->ids = HeapAlloc( GetProcessHeap(), 0, fm->num_ids * sizeof(KNOWNFOLDERID) );
3664     if (!fm->ids)
3665     {
3666         HeapFree( GetProcessHeap(), 0, fm );
3667         return E_OUTOFMEMORY;
3668     }
3669     for (i = j = 0; i < sizeof(CSIDL_Data) / sizeof(CSIDL_Data[0]); i++)
3670     {
3671         if (!IsEqualGUID( CSIDL_Data[i].id, &GUID_NULL ))
3672         {
3673             fm->ids[j] = *CSIDL_Data[i].id;
3674             j++;
3675         }
3676     }
3677     TRACE("found %u known folders\n", fm->num_ids);
3678     *ppv = &fm->vtbl;
3679
3680     TRACE("returning iface %p\n", *ppv);
3681     return S_OK;
3682 }
3683
3684 HRESULT WINAPI KnownFolderManager_Constructor( IUnknown *punk, REFIID riid, void **ppv )
3685 {
3686     TRACE("%p, %s, %p\n", punk, debugstr_guid(riid), ppv);
3687
3688     if (!ppv)
3689         return E_POINTER;
3690     if (punk)
3691         return CLASS_E_NOAGGREGATION;
3692
3693     return foldermanager_create( ppv );
3694 }