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