shell32: Replace numeric literals with the proper constant.
[wine] / dlls / shell32 / shfldr_unixfs.c
1 /*
2  * UNIXFS - Shell namespace extension for the unix filesystem
3  *
4  * Copyright (C) 2005 Michael Jung
5  *
6  * This library is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU Lesser General Public
8  * License as published by the Free Software Foundation; either
9  * version 2.1 of the License, or (at your option) any later version.
10  *
11  * This library is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14  * Lesser General Public License for more details.
15  *
16  * You should have received a copy of the GNU Lesser General Public
17  * License along with this library; if not, write to the Free Software
18  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
19  */
20
21 /*
22  * As you know, windows and unix do have a different philosophy with regard to
23  * the question of how a filesystem should be laid out. While we unix geeks
24  * learned to love the 'one-tree-rooted-at-/' approach, windows has in fact
25  * a whole forest of filesystem trees, each of which is typically identified by
26  * a drive letter.
27  *
28  * We would like wine to integrate as smoothly as possible (that is without
29  * sacrificing win32 compatibility) into the unix environment. For the
30  * filesystem question, this means we really would like those windows
31  * applications to work with unix path- and file-names. Unfortunately, this
32  * seems to be impossible in general. Therefore we have those symbolic links
33  * in wine's 'dosdevices' directory, which are used to simulate drives
34  * to keep windows applications happy. And as a consequence, we have those
35  * drive letters show up now and then in GUI applications running under wine,
36  * which gets the unix hardcore fans all angry, shouting at us @#!&$%* wine
37  * hackers that we are seducing the big companies not to port their applications
38  * to unix.
39  *
40  * DOS paths do appear at various places in GUI applications. Sometimes, they
41  * show up in the title bar of an application's window. They tend to accumulate
42  * in the most-recently-used section of the file-menu. And I've even seen some
43  * in a configuration dialog's edit control. In those examples, wine can't do a
44  * lot about this, since path-names can't be told appart from ordinary strings
45  * here. That's different in the file dialogs, though.
46  *
47  * With the introduction of the 'shell' in win32, Microsoft established an 
48  * abstraction layer on top of the filesystem, called the shell namespace (I was
49  * told that Gnome's virtual filesystem is conceptually similar). In the shell
50  * namespace, one doesn't use ascii- or unicode-strings to uniquely identify
51  * objects. Instead Microsoft introduced item-identifier-lists (The c type is 
52  * called ITEMIDLIST) as an abstraction of path-names. As you probably would
53  * have guessed, an item-identifier-list is a list of item-identifiers (whose
54  * c type's funny name is SHITEMID), which are opaque binary objects. This means
55  * that no application (apart from Microsoft Office) should make any assumptions
56  * on the internal structure of these SHITEMIDs. 
57  *
58  * Since the user prefers to be presented the good-old DOS file-names instead of 
59  * binary ITEMIDLISTs, a translation method between string-based file-names and
60  * ITEMIDLISTs was established. At the core of this are the COM-Interface
61  * IShellFolder and especially it's methods ParseDisplayName and 
62  * GetDisplayNameOf. Basically, you give a DOS-path (let's say C:\windows) to
63  * ParseDisplayName and get a SHITEMID similar to <Desktop|My Computer|C:|windows|>.
64  * Since it's opaque, you can't see the 'C', the 'windows' and the other stuff.
65  * You can only figure out that the ITEMIDLIST is composed of four SHITEMIDS.
66  * The file dialog applies IShellFolder's BindToObject method to bind to each of
67  * those four objects (Desktop, My Computer, C: and windows. All of them have to 
68  * implement the IShellFolder interface.) and asks them how they would like to be 
69  * displayed (basically their icon and the string displayed). If the file dialog 
70  * asks <Desktop|My Computer|C:|windows> which sub-objects it contains (via 
71  * EnumObjects) it gets a list of opaque SHITEMIDs, which can be concatenated to 
72  * <Desktop|...|windows> to build a new ITEMIDLIST and browse, for instance, 
73  * into <system32>. This means the file dialog browses the shell namespace by 
74  * identifying objects via ITEMIDLISTs. Once the user has selected a location to 
75  * save his valuable file, the file dialog calls IShellFolder's GetDisplayNameOf
76  * method to translate the ITEMIDLIST back to a DOS filename.
77  * 
78  * It seems that one intention of the shell namespace concept was to make it 
79  * possible to have objects in the namespace, which don't have any counterpart 
80  * in the filesystem. The 'My Computer' shell folder object is one instance
81  * which comes to mind (Go try to save a file into 'My Computer' on windows.)
82  * So, to make matters a little more complex, before the file dialog asks a
83  * shell namespace object for it's DOS path, it asks if it actually has one.
84  * This is done via the IShellFolder::GetAttributesOf method, which sets the
85  * SFGAO_FILESYSTEM if - and only if - it has.
86  *
87  * The two things, described in the previous two paragraphs, are what unixfs is
88  * based on. So basically, if UnixDosFolder's ParseDisplayName method is called 
89  * with a 'c:\windows' path-name, it doesn't return an 
90  * <Desktop|My Computer|C:|windows|> ITEMIDLIST. Instead, it uses 
91  * shell32's wine_get_unix_path_name and the _posix_ (which means not the win32) 
92  * fileio api's to figure out that c: is mapped to - let's say - 
93  * /home/mjung/.wine/drive_c and then constructs a 
94  * <Desktop|/|home|mjung|.wine|drive_c> ITEMIDLIST. Which is what the file 
95  * dialog uses to display the folder and file objects, which is why you see a 
96  * unix path. When the user has found a nice place for his file and hits the
97  * save button, the ITEMIDLIST of the selected folder object is passed to 
98  * GetDisplayNameOf, which returns a _DOS_ path name 
99  * (like H:\home_of_my_new_file out of <|Desktop|/|home|mjung|home_of_my_new_file|>).
100  * Unixfs basically mounts your dos devices together in order to construct
101  * a copy of your unix filesystem structure.
102  *
103  * But what if none of the symbolic links in 'dosdevices' points to '/', you 
104  * might ask ("And I don't want wine have access to my complete hard drive, you 
105  * *%&1#!"). No problem, as I stated above, unixfs uses the _posix_ apis to 
106  * construct the ITEMIDLISTs. Folders, which aren't accessible via a drive letter,
107  * don't have the SFGAO_FILESYSTEM flag set. So the file dialogs should'nt allow
108  * the user to select such a folder for file storage (And if it does anyhow, it 
109  * will not be able to return a valid path, since there is none). Think of those 
110  * folders as a hierarchy of 'My Computer'-like folders, which happen to be a 
111  * shadow of your unix filesystem tree. And since all of this stuff doesn't 
112  * change anything at all in wine's fileio api's, windows applications will have 
113  * no more access rights as they had before. 
114  *
115  * To sum it all up, you can still savely run wine with you root account (Just
116  * kidding, don't do it.)
117  *
118  * If you are now standing in front of your computer, shouting hotly 
119  * "I am not convinced, Mr. Rumsfeld^H^H^H^H^H^H^H^H^H^H^H^H", fire up regedit
120  * and delete HKEY_LOCAL_MACHINE\Software\Microsoft\Windows\CurrentVersion\
121  * Explorer\Desktop\Namespace\{9D20AAE8-0625-44B0-9CA7-71889C2254D9} and you 
122  * will be back in the pre-unixfs days.
123  */
124
125 #include "config.h"
126 #include "wine/port.h"
127
128 #include <stdio.h>
129 #include <stdarg.h>
130 #include <limits.h>
131 #include <dirent.h>
132 #include <stdlib.h>
133 #ifdef HAVE_UNISTD_H
134 # include <unistd.h>
135 #endif
136 #ifdef HAVE_SYS_STAT_H
137 # include <sys/stat.h>
138 #endif
139 #ifdef HAVE_PWD_H
140 # include <pwd.h>
141 #endif
142 #include <grp.h>
143 #include <limits.h>
144
145 #define COBJMACROS
146 #define NONAMELESSUNION
147 #define NONAMELESSSTRUCT
148
149 #include "windef.h"
150 #include "winbase.h"
151 #include "winuser.h"
152 #include "objbase.h"
153 #include "winreg.h"
154 #include "shlwapi.h"
155 #include "winternl.h"
156 #include "wine/debug.h"
157
158 #include "shell32_main.h"
159 #include "shellfolder.h"
160 #include "shfldr.h"
161 #include "shresdef.h"
162 #include "pidl.h"
163
164 WINE_DEFAULT_DEBUG_CHANNEL(shell);
165
166 #define ADJUST_THIS(c,m,p) ((c*)(((long)p)-(long)&(((c*)0)->lp##m##Vtbl)))
167 #define STATIC_CAST(i,p) ((i*)&p->lp##i##Vtbl)
168
169 #define LEN_SHITEMID_FIXED_PART ((USHORT) \
170     ( sizeof(USHORT)      /* SHITEMID's cb field. */ \
171     + sizeof(PIDLTYPE)    /* PIDLDATA's type field. */ \
172     + sizeof(FileStruct)  /* Well, the FileStruct. */ \
173     - sizeof(char)        /* One char too much in FileStruct. */ \
174     + sizeof(FileStructW) /* You name it. */ \
175     - sizeof(WCHAR)       /* One WCHAR too much in FileStructW. */ \
176     + sizeof(WORD) ))     /* Offset of FileStructW field in PIDL. */
177
178 #define PATHMODE_UNIX 0
179 #define PATHMODE_DOS  1
180
181 /* UnixFolder object layout and typedef.
182  */
183 typedef struct _UnixFolder {
184     const IShellFolder2Vtbl       *lpIShellFolder2Vtbl;
185     const IPersistFolder3Vtbl     *lpIPersistFolder3Vtbl;
186     const IPersistPropertyBagVtbl *lpIPersistPropertyBagVtbl;
187     const IDropTargetVtbl         *lpIDropTargetVtbl;
188     const ISFHelperVtbl           *lpISFHelperVtbl;
189     LONG         m_cRef;
190     CHAR         *m_pszPath;     /* Target path of the shell folder (CP_UNIXCP) */
191     LPITEMIDLIST m_pidlLocation; /* Location in the shell namespace */
192     DWORD        m_dwPathMode;
193     DWORD        m_dwAttributes;
194     const CLSID  *m_pCLSID;
195     DWORD        m_dwDropEffectsMask;
196 } UnixFolder;
197
198 /* Will hold the registered clipboard format identifier for ITEMIDLISTS. */
199 static UINT cfShellIDList = 0;
200
201 /******************************************************************************
202  * UNIXFS_is_rooted_at_desktop [Internal]
203  *
204  * Checks if the unixfs namespace extension is rooted at desktop level.
205  *
206  * RETURNS
207  *  TRUE, if unixfs is rooted at desktop level
208  *  FALSE, if not.
209  */
210 BOOL UNIXFS_is_rooted_at_desktop(void) {
211     HKEY hKey;
212     WCHAR wszRootedAtDesktop[69 + CHARS_IN_GUID] = { 
213         'S','o','f','t','w','a','r','e','\\','M','i','c','r','o','s','o','f','t','\\',
214         'W','i','n','d','o','w','s','\\','C','u','r','r','e','n','t','V','e','r','s','i','o','n','\\',
215         'E','x','p','l','o','r','e','r','\\','D','e','s','k','t','o','p','\\',
216         'N','a','m','e','S','p','a','c','e','\\',0 }; 
217
218     if (StringFromGUID2(&CLSID_UnixDosFolder, wszRootedAtDesktop + 69, CHARS_IN_GUID) &&
219         RegOpenKeyExW(HKEY_LOCAL_MACHINE, wszRootedAtDesktop, 0, KEY_READ, &hKey) == ERROR_SUCCESS) 
220     {
221         RegCloseKey(hKey);
222         return TRUE;
223     }
224     return FALSE;
225 }
226
227 /******************************************************************************
228  * UNIXFS_filename_from_shitemid [Internal]
229  *
230  *  Get CP_UNIXCP encoded filename corresponding to the first item of a pidl
231  * 
232  * PARAMS
233  *  pidl           [I] A simple SHITEMID
234  *  pszPathElement [O] Filename in CP_UNIXCP encoding will be stored here
235  *
236  * RETURNS
237  *  Success: Number of bytes necessary to store the CP_UNIXCP encoded filename 
238  *   _without_ the terminating NUL.
239  *  Failure: 0
240  *  
241  * NOTES
242  *  Size of the buffer at pszPathElement has to be FILENAME_MAX. pszPathElement
243  *  may be NULL, if you are only interested in the return value. 
244  */
245 static int UNIXFS_filename_from_shitemid(LPCITEMIDLIST pidl, char* pszPathElement) {
246     FileStructW *pFileStructW = _ILGetFileStructW(pidl);
247     int cLen = 0;
248
249     if (pFileStructW) {
250         cLen = WideCharToMultiByte(CP_UNIXCP, 0, pFileStructW->wszName, -1, pszPathElement,
251             pszPathElement ? FILENAME_MAX : 0, 0, 0);
252     } else {
253         /* There might be pidls slipping in from shfldr_fs.c, which don't contain the
254          * FileStructW field. In this case, we have to convert from CP_ACP to CP_UNIXCP. */
255         char *pszText = _ILGetTextPointer(pidl);
256         WCHAR *pwszPathElement = NULL;
257         int cWideChars;
258     
259         cWideChars = MultiByteToWideChar(CP_ACP, 0, pszText, -1, NULL, 0);
260         if (!cWideChars) goto cleanup;
261
262         pwszPathElement = SHAlloc(cWideChars * sizeof(WCHAR));
263         if (!pwszPathElement) goto cleanup;
264     
265         cWideChars = MultiByteToWideChar(CP_ACP, 0, pszText, -1, pwszPathElement, cWideChars);
266         if (!cWideChars) goto cleanup; 
267
268         cLen = WideCharToMultiByte(CP_UNIXCP, 0, pwszPathElement, -1, pszPathElement, 
269             pszPathElement ? FILENAME_MAX : 0, 0, 0);
270
271     cleanup:
272         SHFree(pwszPathElement);
273     }
274         
275     if (cLen) cLen--; /* Don't count terminating NUL! */
276     return cLen;
277 }
278
279 /******************************************************************************
280  * UNIXFS_shitemid_len_from_filename [Internal]
281  *
282  * Computes the necessary length of a pidl to hold a path element
283  *
284  * PARAMS
285  *  szPathElement    [I] The path element string in CP_UNIXCP encoding.
286  *  ppszPathElement  [O] Path element string in CP_ACP encoding.
287  *  ppwszPathElement [O] Path element string as WCHAR string.
288  *
289  * RETURNS
290  *  Success: Length in bytes of a SHITEMID representing szPathElement
291  *  Failure: 0
292  * 
293  * NOTES
294  *  Provide NULL values if not interested in pp(w)szPathElement. Otherwise
295  *  caller is responsible to free ppszPathElement and ppwszPathElement with
296  *  SHFree.
297  */
298 static USHORT UNIXFS_shitemid_len_from_filename(
299     const char *szPathElement, char **ppszPathElement, WCHAR **ppwszPathElement) 
300 {
301     USHORT cbPidlLen = 0;
302     WCHAR *pwszPathElement = NULL;
303     char *pszPathElement = NULL;
304     int cWideChars, cChars;
305
306     /* There and Back Again: A Hobbit's Holiday. CP_UNIXCP might be some ANSI
307      * codepage or it might be a real multi-byte encoding like utf-8. There is no
308      * other way to figure out the length of the corresponding WCHAR and CP_ACP 
309      * strings without actually doing the full CP_UNIXCP -> WCHAR -> CP_ACP cycle. */
310     
311     cWideChars = MultiByteToWideChar(CP_UNIXCP, 0, szPathElement, -1, NULL, 0);
312     if (!cWideChars) goto cleanup;
313
314     pwszPathElement = SHAlloc(cWideChars * sizeof(WCHAR));
315     if (!pwszPathElement) goto cleanup;
316
317     cWideChars = MultiByteToWideChar(CP_UNIXCP, 0, szPathElement, -1, pwszPathElement, cWideChars);
318     if (!cWideChars) goto cleanup; 
319
320     cChars = WideCharToMultiByte(CP_ACP, 0, pwszPathElement, -1, NULL, 0, 0, 0);
321     if (!cChars) goto cleanup;
322
323     pszPathElement = SHAlloc(cChars);
324     if (!pszPathElement) goto cleanup;
325
326     cChars = WideCharToMultiByte(CP_ACP, 0, pwszPathElement, -1, pszPathElement, cChars, 0, 0);
327     if (!cChars) goto cleanup;
328
329     /* (cChars & 0x1) is for the potential alignment byte */
330     cbPidlLen = LEN_SHITEMID_FIXED_PART + cChars + (cChars & 0x1) + cWideChars * sizeof(WCHAR);
331     
332 cleanup:
333     if (cbPidlLen && ppszPathElement) 
334         *ppszPathElement = pszPathElement;
335     else 
336         SHFree(pszPathElement);
337
338     if (cbPidlLen && ppwszPathElement)
339         *ppwszPathElement = pwszPathElement;
340     else
341         SHFree(pwszPathElement);
342
343     return cbPidlLen;
344 }
345
346 /******************************************************************************
347  * UNIXFS_is_pidl_of_type [Internal]
348  *
349  * Checks for the first SHITEMID of an ITEMIDLIST if it passes a filter.
350  *
351  * PARAMS
352  *  pIDL    [I] The ITEMIDLIST to be checked.
353  *  fFilter [I] Shell condition flags, which specify the filter.
354  *
355  * RETURNS
356  *  TRUE, if pIDL is accepted by fFilter
357  *  FALSE, otherwise
358  */
359 static inline BOOL UNIXFS_is_pidl_of_type(LPITEMIDLIST pIDL, SHCONTF fFilter) {
360     LPPIDLDATA pIDLData = _ILGetDataPointer(pIDL);
361     if (!(fFilter & SHCONTF_INCLUDEHIDDEN) && pIDLData && 
362         (pIDLData->u.file.uFileAttribs & FILE_ATTRIBUTE_HIDDEN)) 
363     {
364         return FALSE;
365     }
366     if (_ILIsFolder(pIDL) && (fFilter & SHCONTF_FOLDERS)) return TRUE;
367     if (_ILIsValue(pIDL) && (fFilter & SHCONTF_NONFOLDERS)) return TRUE;
368     return FALSE;
369 }
370
371 /******************************************************************************
372  * UNIXFS_is_dos_device [Internal]
373  *
374  * Determines if a unix directory corresponds to any dos device.
375  *
376  * PARAMS
377  *  statPath [I] The stat struct of the directory, as returned by stat(2).
378  *
379  * RETURNS
380  *  TRUE, if statPath corresponds to any dos drive letter
381  *  FALSE, otherwise
382  */
383 static BOOL UNIXFS_is_dos_device(const struct stat *statPath) {
384     struct stat statDrive;
385     char *pszDrivePath;
386     DWORD dwDriveMap;
387     WCHAR wszDosDevice[4] = { 'A', ':', '\\', 0 };
388
389     for (dwDriveMap = GetLogicalDrives(); dwDriveMap; dwDriveMap >>= 1, wszDosDevice[0]++) {
390         if (!(dwDriveMap & 0x1)) continue;
391         pszDrivePath = wine_get_unix_file_name(wszDosDevice);
392         if (pszDrivePath && !stat(pszDrivePath, &statDrive)) {
393             HeapFree(GetProcessHeap(), 0, pszDrivePath);
394             if ((statPath->st_dev == statDrive.st_dev) && (statPath->st_ino == statDrive.st_ino))
395                 return TRUE;
396         }
397     }
398     return FALSE;
399 }
400
401 /******************************************************************************
402  * UNIXFS_get_unix_path [Internal]
403  *
404  * Convert an absolute dos path to an absolute unix path.
405  * Evaluate "/.", "/.." and the symbolic links in $WINEPREFIX/dosdevices.
406  *
407  * PARAMS
408  *  pszDosPath       [I] An absolute dos path
409  *  pszCanonicalPath [O] Buffer of length FILENAME_MAX. Will receive the canonical path.
410  *
411  * RETURNS
412  *  Success, TRUE
413  *  Failure, FALSE - Path not existent, too long, insufficient rights, to many symlinks
414  */
415 static BOOL UNIXFS_get_unix_path(LPCWSTR pszDosPath, char *pszCanonicalPath)
416 {
417     char *pPathTail, *pElement, *pCanonicalTail, szPath[FILENAME_MAX], *pszUnixPath;
418     WCHAR wszDrive[] = { '?', ':', '\\', 0 };
419     int cDriveSymlinkLen;
420     
421     TRACE("(pszDosPath=%s, pszCanonicalPath=%p)\n", debugstr_w(pszDosPath), pszCanonicalPath);
422
423     if (!pszDosPath || pszDosPath[1] != ':')
424         return FALSE;
425
426     /* Get the canonicalized unix path corresponding to the drive letter. */
427     wszDrive[0] = pszDosPath[0];
428     pszUnixPath = wine_get_unix_file_name(wszDrive);
429     if (!pszUnixPath) return FALSE;
430     cDriveSymlinkLen = strlen(pszUnixPath);
431     pElement = realpath(pszUnixPath, szPath);
432     HeapFree(GetProcessHeap(), 0, pszUnixPath);
433     if (!pElement) return FALSE;
434     if (szPath[strlen(szPath)-1] != '/') strcat(szPath, "/");
435
436     /* Append the part relative to the drive symbolic link target. */
437     pszUnixPath = wine_get_unix_file_name(pszDosPath);
438     if (!pszUnixPath) return FALSE;
439     strcat(szPath, pszUnixPath + cDriveSymlinkLen);
440     HeapFree(GetProcessHeap(), 0, pszUnixPath);
441     
442     /* pCanonicalTail always points to the end of the canonical path constructed
443      * thus far. pPathTail points to the still to be processed part of the input
444      * path. pElement points to the path element currently investigated.
445      */
446     *pszCanonicalPath = '\0';
447     pCanonicalTail = pszCanonicalPath;
448     pPathTail = szPath;
449
450     do {
451         char cTemp;
452             
453         pElement = pPathTail;
454         pPathTail = strchr(pPathTail+1, '/');
455         if (!pPathTail) /* Last path element may not be terminated by '/'. */ 
456             pPathTail = pElement + strlen(pElement);
457         /* Temporarily terminate the current path element. Will be restored later. */
458         cTemp = *pPathTail;
459         *pPathTail = '\0';
460
461         /* Skip "/." path elements */
462         if (!strcmp("/.", pElement)) {
463             *pPathTail = cTemp;
464         } else if (!strcmp("/..", pElement)) {
465             /* Remove last element in canonical path for "/.." elements, then skip. */
466             char *pTemp = strrchr(pszCanonicalPath, '/');
467             if (pTemp)
468                 pCanonicalTail = pTemp;
469             *pCanonicalTail = '\0';
470             *pPathTail = cTemp;
471         } else {
472             /* Directory or file. Copy to canonical path */
473             if (pCanonicalTail - pszCanonicalPath + pPathTail - pElement + 1 > FILENAME_MAX)
474                 return FALSE;
475                 
476             memcpy(pCanonicalTail, pElement, pPathTail - pElement + 1);
477             pCanonicalTail += pPathTail - pElement;
478             *pPathTail = cTemp;
479         }
480     } while (pPathTail[0] == '/');
481    
482     TRACE("--> %s\n", debugstr_a(pszCanonicalPath));
483     
484     return TRUE;
485 }
486
487 /******************************************************************************
488  * UNIXFS_seconds_since_1970_to_dos_date_time [Internal]
489  *
490  * Convert unix time to FAT time
491  *
492  * PARAMS 
493  *  ss1970 [I] Unix time (seconds since 1970)
494  *  pDate  [O] Corresponding FAT date
495  *  pTime  [O] Corresponding FAT time
496  */
497 static inline void UNIXFS_seconds_since_1970_to_dos_date_time(
498     time_t ss1970, LPWORD pDate, LPWORD pTime)
499 {
500     LARGE_INTEGER time;
501     FILETIME fileTime;
502
503     RtlSecondsSince1970ToTime( ss1970, &time );
504     fileTime.dwLowDateTime = time.u.LowPart;
505     fileTime.dwHighDateTime = time.u.HighPart;
506     FileTimeToDosDateTime(&fileTime, pDate, pTime);
507 }
508
509 /******************************************************************************
510  * UNIXFS_build_shitemid [Internal]
511  *
512  * Constructs a new SHITEMID for the last component of path 'pszUnixPath' into 
513  * buffer 'pIDL'.
514  *
515  * PARAMS
516  *  pszUnixPath [I] An absolute path. The SHITEMID will be build for the last component.
517  *  pIDL        [O] SHITEMID will be constructed here.
518  *
519  * RETURNS
520  *  Success: A pointer to the terminating '\0' character of path.
521  *  Failure: NULL
522  *
523  * NOTES
524  *  Minimum size of pIDL is SHITEMID_LEN_FROM_NAME_LEN(strlen(last_component_of_path)).
525  *  If what you need is a PIDLLIST with a single SHITEMID, don't forget to append
526  *  a 0 USHORT value.
527  */
528 static char* UNIXFS_build_shitemid(char *pszUnixPath, void *pIDL) {
529     LPPIDLDATA pIDLData;
530     struct stat fileStat;
531     char *pszComponentU, *pszComponentA;
532     WCHAR *pwszComponentW;
533     int cComponentULen, cComponentALen;
534     USHORT cbLen;
535     FileStructW *pFileStructW;
536     WORD uOffsetW, *pOffsetW;
537
538     TRACE("(pszUnixPath=%s, pIDL=%p)\n", debugstr_a(pszUnixPath), pIDL);
539
540     /* We are only interested in regular files and directories. */
541     if (stat(pszUnixPath, &fileStat)) return NULL;
542     if (!S_ISDIR(fileStat.st_mode) && !S_ISREG(fileStat.st_mode)) return NULL;
543     
544     /* Compute the SHITEMID's length and wipe it. */
545     pszComponentU = strrchr(pszUnixPath, '/') + 1;
546     cComponentULen = strlen(pszComponentU);
547     cbLen = UNIXFS_shitemid_len_from_filename(pszComponentU, &pszComponentA, &pwszComponentW);
548     if (!cbLen) return NULL;
549     memset(pIDL, 0, cbLen);
550     ((LPSHITEMID)pIDL)->cb = cbLen;
551     
552     /* Set shell32's standard SHITEMID data fields. */
553     pIDLData = _ILGetDataPointer((LPCITEMIDLIST)pIDL);
554     pIDLData->type = S_ISDIR(fileStat.st_mode) ? PT_FOLDER : PT_VALUE;
555     pIDLData->u.file.dwFileSize = (DWORD)fileStat.st_size;
556     UNIXFS_seconds_since_1970_to_dos_date_time(fileStat.st_mtime, &pIDLData->u.file.uFileDate, 
557         &pIDLData->u.file.uFileTime);
558     pIDLData->u.file.uFileAttribs = 0;
559     if (S_ISDIR(fileStat.st_mode)) pIDLData->u.file.uFileAttribs |= FILE_ATTRIBUTE_DIRECTORY;
560     if (pszComponentU[0] == '.') pIDLData->u.file.uFileAttribs |=  FILE_ATTRIBUTE_HIDDEN;
561     cComponentALen = lstrlenA(pszComponentA) + 1;
562     memcpy(pIDLData->u.file.szNames, pszComponentA, cComponentALen);
563     
564     pFileStructW = (FileStructW*)(pIDLData->u.file.szNames + cComponentALen + (cComponentALen & 0x1));
565     uOffsetW = (WORD)(((LPBYTE)pFileStructW) - ((LPBYTE)pIDL));
566     pFileStructW->cbLen = cbLen - uOffsetW;
567     UNIXFS_seconds_since_1970_to_dos_date_time(fileStat.st_mtime, &pFileStructW->uCreationDate, 
568         &pFileStructW->uCreationTime);
569     UNIXFS_seconds_since_1970_to_dos_date_time(fileStat.st_atime, &pFileStructW->uLastAccessDate,
570         &pFileStructW->uLastAccessTime);
571     lstrcpyW(pFileStructW->wszName, pwszComponentW);
572
573     pOffsetW = (WORD*)(((LPBYTE)pIDL) + cbLen - sizeof(WORD));
574     *pOffsetW = uOffsetW;
575     
576     SHFree(pszComponentA);
577     SHFree(pwszComponentW);
578     
579     return pszComponentU + cComponentULen;
580 }
581
582 /******************************************************************************
583  * UNIXFS_path_to_pidl [Internal]
584  *
585  * PARAMS
586  *  pUnixFolder [I] If path is relative, pUnixFolder represents the base path
587  *  path        [I] An absolute unix or dos path or a path relativ to pUnixFolder
588  *  ppidl       [O] The corresponding ITEMIDLIST. Release with SHFree/ILFree
589  *  
590  * RETURNS
591  *  Success: TRUE
592  *  Failure: FALSE, invalid params or out of memory
593  *
594  * NOTES
595  *  pUnixFolder also carries the information if the path is expected to be unix or dos.
596  */
597 static BOOL UNIXFS_path_to_pidl(UnixFolder *pUnixFolder, const WCHAR *path, LPITEMIDLIST *ppidl) {
598     LPITEMIDLIST pidl;
599     int cPidlLen, cPathLen;
600     char *pSlash, *pNextSlash, szCompletePath[FILENAME_MAX], *pNextPathElement, *pszAPath;
601     WCHAR *pwszPath;
602
603     TRACE("pUnixFolder=%p, path=%s, ppidl=%p\n", pUnixFolder, debugstr_w(path), ppidl);
604    
605     if (!ppidl || !path)
606         return FALSE;
607
608     /* Build an absolute path and let pNextPathElement point to the interesting 
609      * relative sub-path. We need the absolute path to call 'stat', but the pidl
610      * will only contain the relative part.
611      */
612     if ((pUnixFolder->m_dwPathMode == PATHMODE_DOS) && (path[1] == ':')) 
613     {
614         /* Absolute dos path. Convert to unix */
615         if (!UNIXFS_get_unix_path(path, szCompletePath))
616             return FALSE;
617         pNextPathElement = szCompletePath;
618     } 
619     else if ((pUnixFolder->m_dwPathMode == PATHMODE_UNIX) && (path[0] == '/')) 
620     {
621         /* Absolute unix path. Just convert to ANSI. */
622         WideCharToMultiByte(CP_UNIXCP, 0, path, -1, szCompletePath, FILENAME_MAX, NULL, NULL); 
623         pNextPathElement = szCompletePath;
624     } 
625     else 
626     {
627         /* Relative dos or unix path. Concat with this folder's path */
628         int cBasePathLen = strlen(pUnixFolder->m_pszPath);
629         memcpy(szCompletePath, pUnixFolder->m_pszPath, cBasePathLen);
630         WideCharToMultiByte(CP_UNIXCP, 0, path, -1, szCompletePath + cBasePathLen, 
631                             FILENAME_MAX - cBasePathLen, NULL, NULL);
632         pNextPathElement = szCompletePath + cBasePathLen - 1;
633         
634         /* If in dos mode, replace '\' with '/' */
635         if (pUnixFolder->m_dwPathMode == PATHMODE_DOS) {
636             char *pBackslash = strchr(pNextPathElement, '\\');
637             while (pBackslash) {
638                 *pBackslash = '/';
639                 pBackslash = strchr(pBackslash, '\\');
640             }
641         }
642     }
643
644     /* Special case for the root folder. */
645     if (!strcmp(szCompletePath, "/")) {
646         *ppidl = pidl = (LPITEMIDLIST)SHAlloc(sizeof(USHORT));
647         if (!pidl) return FALSE;
648         pidl->mkid.cb = 0; /* Terminate the ITEMIDLIST */
649         return TRUE;
650     }
651     
652     /* Remove trailing slash, if present */
653     cPathLen = strlen(szCompletePath);
654     if (szCompletePath[cPathLen-1] == '/') 
655         szCompletePath[cPathLen-1] = '\0';
656
657     if ((szCompletePath[0] != '/') || (pNextPathElement[0] != '/')) {
658         ERR("szCompletePath: %s, pNextPathElment: %s\n", szCompletePath, pNextPathElement);
659         return FALSE;
660     }
661     
662     /* At this point, we have an absolute unix path in szCompletePath 
663      * and the relative portion of it in pNextPathElement. Both starting with '/'
664      * and _not_ terminated by a '/'. */
665     TRACE("complete path: %s, relative path: %s\n", szCompletePath, pNextPathElement);
666     
667     /* Convert to CP_ACP and WCHAR */
668     if (!UNIXFS_shitemid_len_from_filename(pNextPathElement, &pszAPath, &pwszPath))
669         return 0;
670
671     /* Compute the length of the complete ITEMIDLIST */
672     cPidlLen = 0;
673     pSlash = pszAPath;
674     while (pSlash) {
675         pNextSlash = strchr(pSlash+1, '/');
676         cPidlLen += LEN_SHITEMID_FIXED_PART + /* Fixed part length plus potential alignment byte. */
677             (pNextSlash ? (pNextSlash - pSlash) & 0x1 : lstrlenA(pSlash) & 0x1); 
678         pSlash = pNextSlash;
679     }
680
681     /* The USHORT is for the ITEMIDLIST terminator. The NUL terminators for the sub-path-strings
682      * are accounted for by the '/' separators, which are not stored in the SHITEMIDs. Above we
683      * have ensured that the number of '/'s exactly matches the number of sub-path-strings. */
684     cPidlLen += lstrlenA(pszAPath) + lstrlenW(pwszPath) * sizeof(WCHAR) + sizeof(USHORT);
685
686     SHFree(pszAPath);
687     SHFree(pwszPath);
688
689     *ppidl = pidl = (LPITEMIDLIST)SHAlloc(cPidlLen);
690     if (!pidl) return FALSE;
691
692     /* Concatenate the SHITEMIDs of the sub-directories. */
693     while (*pNextPathElement) {
694         pSlash = strchr(pNextPathElement+1, '/');
695         if (pSlash) *pSlash = '\0';
696         pNextPathElement = UNIXFS_build_shitemid(szCompletePath, pidl);
697         if (pSlash) *pSlash = '/';
698             
699         if (!pNextPathElement) {
700             SHFree(*ppidl);
701             *ppidl = NULL;
702             return FALSE;
703         }
704         pidl = ILGetNext(pidl);
705     }
706     pidl->mkid.cb = 0; /* Terminate the ITEMIDLIST */
707
708     if ((char *)pidl-(char *)*ppidl+sizeof(USHORT) != cPidlLen) /* We've corrupted the heap :( */ 
709         ERR("Computed length of pidl incorrect. Please report.\n");
710     
711     return TRUE;
712 }
713
714 /******************************************************************************
715  * UNIXFS_initialize_target_folder [Internal]
716  *
717  *  Initialize the m_pszPath member of an UnixFolder, given an absolute unix
718  *  base path and a relative ITEMIDLIST. Leave the m_pidlLocation member, which
719  *  specifies the location in the shell namespace alone. 
720  * 
721  * PARAMS
722  *  This          [IO] The UnixFolder, whose target path is to be initialized
723  *  szBasePath    [I]  The absolute base path
724  *  pidlSubFolder [I]  Relative part of the path, given as an ITEMIDLIST
725  *  dwAttributes  [I]  Attributes to add to the Folders m_dwAttributes member 
726  *                     (Used to pass the SFGAO_FILESYSTEM flag down the path)
727  * RETURNS
728  *  Success: S_OK,
729  *  Failure: E_FAIL
730  */
731 static HRESULT UNIXFS_initialize_target_folder(UnixFolder *This, const char *szBasePath,
732     LPCITEMIDLIST pidlSubFolder, DWORD dwAttributes)
733 {
734     LPCITEMIDLIST current = pidlSubFolder;
735     DWORD dwPathLen = strlen(szBasePath)+1;
736     struct stat statPrefix;
737     char *pNextDir;
738         
739     /* Determine the path's length bytes */
740     while (current && current->mkid.cb) {
741         dwPathLen += UNIXFS_filename_from_shitemid(current, NULL) + 1; /* For the '/' */
742         current = ILGetNext(current);
743     };
744
745     /* Build the path and compute the attributes*/
746     This->m_dwAttributes = 
747             dwAttributes|SFGAO_FOLDER|SFGAO_HASSUBFOLDER|SFGAO_FILESYSANCESTOR|SFGAO_CANRENAME;
748     This->m_pszPath = pNextDir = SHAlloc(dwPathLen);
749     if (!This->m_pszPath) {
750         WARN("SHAlloc failed!\n");
751         return E_FAIL;
752     }
753     current = pidlSubFolder;
754     strcpy(pNextDir, szBasePath);
755     pNextDir += strlen(szBasePath);
756     if (This->m_dwPathMode == PATHMODE_UNIX || IsEqualCLSID(&CLSID_MyDocuments, This->m_pCLSID))
757         This->m_dwAttributes |= SFGAO_FILESYSTEM;
758     if (!(This->m_dwAttributes & SFGAO_FILESYSTEM)) {
759         *pNextDir = '\0';
760         if (!stat(This->m_pszPath, &statPrefix) && UNIXFS_is_dos_device(&statPrefix))
761             This->m_dwAttributes |= SFGAO_FILESYSTEM;
762     }
763     while (current && current->mkid.cb) {
764         pNextDir += UNIXFS_filename_from_shitemid(current, pNextDir);
765         if (!(This->m_dwAttributes & SFGAO_FILESYSTEM)) {
766             *pNextDir = '\0';
767             if (!stat(This->m_pszPath, &statPrefix) && UNIXFS_is_dos_device(&statPrefix))
768                 This->m_dwAttributes |= SFGAO_FILESYSTEM;
769         }
770         *pNextDir++ = '/';
771         current = ILGetNext(current);
772     }
773     *pNextDir='\0';
774  
775     return S_OK;
776 }
777
778 /******************************************************************************
779  * UnixFolder
780  *
781  * Class whose heap based instances represent unix filesystem directories.
782  */
783
784 static void UnixFolder_Destroy(UnixFolder *pUnixFolder) {
785     TRACE("(pUnixFolder=%p)\n", pUnixFolder);
786     
787     SHFree(pUnixFolder->m_pszPath);
788     ILFree(pUnixFolder->m_pidlLocation);
789     SHFree(pUnixFolder);
790 }
791
792 static HRESULT WINAPI UnixFolder_IShellFolder2_QueryInterface(IShellFolder2 *iface, REFIID riid, 
793     void **ppv) 
794 {
795     UnixFolder *This = ADJUST_THIS(UnixFolder, IShellFolder2, iface);
796         
797     TRACE("(iface=%p, riid=%p, ppv=%p)\n", iface, riid, ppv);
798     
799     if (!ppv) return E_INVALIDARG;
800     
801     if (IsEqualIID(&IID_IUnknown, riid) || IsEqualIID(&IID_IShellFolder, riid) || 
802         IsEqualIID(&IID_IShellFolder2, riid)) 
803     {
804         *ppv = STATIC_CAST(IShellFolder2, This);
805     } else if (IsEqualIID(&IID_IPersistFolder3, riid) || IsEqualIID(&IID_IPersistFolder2, riid) || 
806                IsEqualIID(&IID_IPersistFolder, riid) || IsEqualIID(&IID_IPersist, riid)) 
807     {
808         *ppv = STATIC_CAST(IPersistFolder3, This);
809     } else if (IsEqualIID(&IID_IPersistPropertyBag, riid)) {
810         *ppv = STATIC_CAST(IPersistPropertyBag, This);
811     } else if (IsEqualIID(&IID_ISFHelper, riid)) {
812         *ppv = STATIC_CAST(ISFHelper, This);
813     } else if (IsEqualIID(&IID_IDropTarget, riid)) {
814         *ppv = STATIC_CAST(IDropTarget, This);
815         if (!cfShellIDList) 
816             cfShellIDList = RegisterClipboardFormatA(CFSTR_SHELLIDLIST);
817     } else {
818         *ppv = NULL;
819         return E_NOINTERFACE;
820     }
821
822     IUnknown_AddRef((IUnknown*)*ppv);
823     return S_OK;
824 }
825
826 static ULONG WINAPI UnixFolder_IShellFolder2_AddRef(IShellFolder2 *iface) {
827     UnixFolder *This = ADJUST_THIS(UnixFolder, IShellFolder2, iface);
828
829     TRACE("(iface=%p)\n", iface);
830
831     return InterlockedIncrement(&This->m_cRef);
832 }
833
834 static ULONG WINAPI UnixFolder_IShellFolder2_Release(IShellFolder2 *iface) {
835     UnixFolder *This = ADJUST_THIS(UnixFolder, IShellFolder2, iface);
836     ULONG cRef;
837     
838     TRACE("(iface=%p)\n", iface);
839
840     cRef = InterlockedDecrement(&This->m_cRef);
841     
842     if (!cRef) 
843         UnixFolder_Destroy(This);
844
845     return cRef;
846 }
847
848 static HRESULT WINAPI UnixFolder_IShellFolder2_ParseDisplayName(IShellFolder2* iface, HWND hwndOwner, 
849     LPBC pbcReserved, LPOLESTR lpszDisplayName, ULONG* pchEaten, LPITEMIDLIST* ppidl, 
850     ULONG* pdwAttributes)
851 {
852     UnixFolder *This = ADJUST_THIS(UnixFolder, IShellFolder2, iface);
853     BOOL result;
854
855     TRACE("(iface=%p, hwndOwner=%p, pbcReserved=%p, lpszDisplayName=%s, pchEaten=%p, ppidl=%p, "
856           "pdwAttributes=%p) stub\n", iface, hwndOwner, pbcReserved, debugstr_w(lpszDisplayName), 
857           pchEaten, ppidl, pdwAttributes);
858
859     result = UNIXFS_path_to_pidl(This, lpszDisplayName, ppidl);
860     if (result && pdwAttributes && *pdwAttributes)
861     {
862         IShellFolder *pParentSF;
863         LPCITEMIDLIST pidlLast;
864         LPITEMIDLIST pidlComplete = ILCombine(This->m_pidlLocation, *ppidl);
865         HRESULT hr;
866         
867         hr = SHBindToParent(pidlComplete, &IID_IShellFolder, (LPVOID*)&pParentSF, &pidlLast);
868         if (FAILED(hr)) {
869             FIXME("SHBindToParent failed! hr = %08x\n", hr);
870             ILFree(pidlComplete);
871             return E_FAIL;
872         }
873         IShellFolder_GetAttributesOf(pParentSF, 1, &pidlLast, pdwAttributes);
874         IShellFolder_Release(pParentSF);
875         ILFree(pidlComplete);
876     }
877
878     if (!result) TRACE("FAILED!\n");
879     return result ? S_OK : E_FAIL;
880 }
881
882 static IUnknown *UnixSubFolderIterator_Constructor(UnixFolder *pUnixFolder, SHCONTF fFilter);
883
884 static HRESULT WINAPI UnixFolder_IShellFolder2_EnumObjects(IShellFolder2* iface, HWND hwndOwner, 
885     SHCONTF grfFlags, IEnumIDList** ppEnumIDList)
886 {
887     UnixFolder *This = ADJUST_THIS(UnixFolder, IShellFolder2, iface);
888     IUnknown *newIterator;
889     HRESULT hr;
890     
891     TRACE("(iface=%p, hwndOwner=%p, grfFlags=%08x, ppEnumIDList=%p)\n", 
892             iface, hwndOwner, grfFlags, ppEnumIDList);
893
894     if (!This->m_pszPath) {
895         WARN("EnumObjects called on uninitialized UnixFolder-object!\n");
896         return E_UNEXPECTED;
897     }
898
899     newIterator = UnixSubFolderIterator_Constructor(This, grfFlags);
900     hr = IUnknown_QueryInterface(newIterator, &IID_IEnumIDList, (void**)ppEnumIDList);
901     IUnknown_Release(newIterator);
902     
903     return hr;
904 }
905
906 static HRESULT CreateUnixFolder(IUnknown *pUnkOuter, REFIID riid, LPVOID *ppv, const CLSID *pCLSID);
907
908 static HRESULT WINAPI UnixFolder_IShellFolder2_BindToObject(IShellFolder2* iface, LPCITEMIDLIST pidl,
909     LPBC pbcReserved, REFIID riid, void** ppvOut)
910 {
911     UnixFolder *This = ADJUST_THIS(UnixFolder, IShellFolder2, iface);
912     IPersistFolder3 *persistFolder;
913     HRESULT hr;
914     const CLSID *clsidChild;
915         
916     TRACE("(iface=%p, pidl=%p, pbcReserver=%p, riid=%p, ppvOut=%p)\n", 
917             iface, pidl, pbcReserved, riid, ppvOut);
918
919     if (!pidl || !pidl->mkid.cb)
920         return E_INVALIDARG;
921    
922     if (IsEqualCLSID(This->m_pCLSID, &CLSID_FolderShortcut)) {
923         /* Children of FolderShortcuts are ShellFSFolders on Windows. 
924          * Unixfs' counterpart is UnixDosFolder. */
925         clsidChild = &CLSID_UnixDosFolder;    
926     } else {
927         clsidChild = This->m_pCLSID;
928     }
929     
930     hr = CreateUnixFolder(NULL, &IID_IPersistFolder3, (void**)&persistFolder, clsidChild);
931     if (!SUCCEEDED(hr)) return hr;
932     hr = IPersistFolder_QueryInterface(persistFolder, riid, (void**)ppvOut);
933    
934     if (SUCCEEDED(hr)) {
935         UnixFolder *subfolder = ADJUST_THIS(UnixFolder, IPersistFolder3, persistFolder);
936         subfolder->m_pidlLocation = ILCombine(This->m_pidlLocation, pidl);
937         hr = UNIXFS_initialize_target_folder(subfolder, This->m_pszPath, pidl,
938                                              This->m_dwAttributes & SFGAO_FILESYSTEM);
939     } 
940
941     IPersistFolder3_Release(persistFolder);
942     
943     return hr;
944 }
945
946 static HRESULT WINAPI UnixFolder_IShellFolder2_BindToStorage(IShellFolder2* This, LPCITEMIDLIST pidl, 
947     LPBC pbcReserved, REFIID riid, void** ppvObj)
948 {
949     FIXME("stub\n");
950     return E_NOTIMPL;
951 }
952
953 static HRESULT WINAPI UnixFolder_IShellFolder2_CompareIDs(IShellFolder2* iface, LPARAM lParam, 
954     LPCITEMIDLIST pidl1, LPCITEMIDLIST pidl2)
955 {
956     BOOL isEmpty1, isEmpty2;
957     HRESULT hr = E_FAIL;
958     LPITEMIDLIST firstpidl;
959     IShellFolder2 *psf;
960     int compare;
961
962     TRACE("(iface=%p, lParam=%ld, pidl1=%p, pidl2=%p)\n", iface, lParam, pidl1, pidl2);
963     
964     isEmpty1 = !pidl1 || !pidl1->mkid.cb;
965     isEmpty2 = !pidl2 || !pidl2->mkid.cb;
966
967     if (isEmpty1 && isEmpty2) 
968         return MAKE_HRESULT(SEVERITY_SUCCESS, 0, 0);
969     else if (isEmpty1)
970         return MAKE_HRESULT(SEVERITY_SUCCESS, 0, (WORD)-1);
971     else if (isEmpty2)
972         return MAKE_HRESULT(SEVERITY_SUCCESS, 0, (WORD)1);
973
974     if (_ILIsFolder(pidl1) && !_ILIsFolder(pidl2)) 
975         return MAKE_HRESULT(SEVERITY_SUCCESS, 0, (WORD)-1);
976     if (!_ILIsFolder(pidl1) && _ILIsFolder(pidl2))
977         return MAKE_HRESULT(SEVERITY_SUCCESS, 0, (WORD)1);
978
979     compare = CompareStringA(LOCALE_USER_DEFAULT, NORM_IGNORECASE, 
980                              _ILGetTextPointer(pidl1), -1,
981                              _ILGetTextPointer(pidl2), -1);
982     
983     if ((compare == CSTR_LESS_THAN) || (compare == CSTR_GREATER_THAN)) 
984         return MAKE_HRESULT(SEVERITY_SUCCESS, 0, (WORD)((compare == CSTR_LESS_THAN)?-1:1));
985
986     if (pidl1->mkid.cb < pidl2->mkid.cb)
987         return MAKE_HRESULT(SEVERITY_SUCCESS, 0, (WORD)-1);
988     else if (pidl1->mkid.cb > pidl2->mkid.cb)
989         return MAKE_HRESULT(SEVERITY_SUCCESS, 0, (WORD)1);
990
991     firstpidl = ILCloneFirst(pidl1);
992     pidl1 = ILGetNext(pidl1);
993     pidl2 = ILGetNext(pidl2);
994     
995     hr = IShellFolder2_BindToObject(iface, firstpidl, NULL, &IID_IShellFolder, (LPVOID*)&psf);
996     if (SUCCEEDED(hr)) {
997         hr = IShellFolder_CompareIDs(psf, lParam, pidl1, pidl2);
998         IShellFolder2_Release(psf);
999     }
1000
1001     ILFree(firstpidl);
1002     return hr;
1003 }
1004
1005 static HRESULT WINAPI UnixFolder_IShellFolder2_CreateViewObject(IShellFolder2* iface, HWND hwndOwner,
1006     REFIID riid, void** ppv)
1007 {
1008     HRESULT hr = E_INVALIDARG;
1009         
1010     TRACE("(iface=%p, hwndOwner=%p, riid=%p, ppv=%p) stub\n", iface, hwndOwner, riid, ppv);
1011     
1012     if (!ppv) return E_INVALIDARG;
1013     *ppv = NULL;
1014     
1015     if (IsEqualIID(&IID_IShellView, riid)) {
1016         LPSHELLVIEW pShellView;
1017         
1018         pShellView = IShellView_Constructor((IShellFolder*)iface);
1019         if (pShellView) {
1020             hr = IShellView_QueryInterface(pShellView, riid, ppv);
1021             IShellView_Release(pShellView);
1022         }
1023     } else if (IsEqualIID(&IID_IDropTarget, riid)) {
1024         hr = IShellFolder2_QueryInterface(iface, &IID_IDropTarget, ppv);
1025     }
1026     
1027     return hr;
1028 }
1029
1030 static HRESULT WINAPI UnixFolder_IShellFolder2_GetAttributesOf(IShellFolder2* iface, UINT cidl, 
1031     LPCITEMIDLIST* apidl, SFGAOF* rgfInOut)
1032 {
1033     UnixFolder *This = ADJUST_THIS(UnixFolder, IShellFolder2, iface);
1034     HRESULT hr = S_OK;
1035         
1036     TRACE("(iface=%p, cidl=%u, apidl=%p, rgfInOut=%p)\n", iface, cidl, apidl, rgfInOut);
1037  
1038     if (!rgfInOut || (cidl && !apidl)) 
1039         return E_INVALIDARG;
1040     
1041     if (cidl == 0) {
1042         *rgfInOut &= This->m_dwAttributes;
1043     } else {
1044         char szAbsolutePath[FILENAME_MAX], *pszRelativePath;
1045         UINT i;
1046
1047         *rgfInOut = SFGAO_CANCOPY|SFGAO_CANMOVE|SFGAO_CANLINK|SFGAO_CANRENAME|SFGAO_CANDELETE|
1048                     SFGAO_HASPROPSHEET|SFGAO_DROPTARGET|SFGAO_FILESYSTEM;
1049         lstrcpyA(szAbsolutePath, This->m_pszPath);
1050         pszRelativePath = szAbsolutePath + lstrlenA(szAbsolutePath);
1051         for (i=0; i<cidl; i++) {
1052             if (!(This->m_dwAttributes & SFGAO_FILESYSTEM)) {
1053                 struct stat fileStat;
1054                 if (!UNIXFS_filename_from_shitemid(apidl[i], pszRelativePath)) 
1055                     return E_INVALIDARG;
1056                 if (stat(szAbsolutePath, &fileStat) || !UNIXFS_is_dos_device(&fileStat))
1057                     *rgfInOut &= ~SFGAO_FILESYSTEM;
1058             }
1059             if (_ILIsFolder(apidl[i])) 
1060                 *rgfInOut |= SFGAO_FOLDER|SFGAO_HASSUBFOLDER|SFGAO_FILESYSANCESTOR;
1061         }
1062     }
1063     
1064     return hr;
1065 }
1066
1067 static HRESULT WINAPI UnixFolder_IShellFolder2_GetUIObjectOf(IShellFolder2* iface, HWND hwndOwner, 
1068     UINT cidl, LPCITEMIDLIST* apidl, REFIID riid, UINT* prgfInOut, void** ppvOut)
1069 {
1070     UnixFolder *This = ADJUST_THIS(UnixFolder, IShellFolder2, iface);
1071     UINT i;
1072     
1073     TRACE("(iface=%p, hwndOwner=%p, cidl=%d, apidl=%p, riid=%s, prgfInOut=%p, ppv=%p)\n",
1074         iface, hwndOwner, cidl, apidl, debugstr_guid(riid), prgfInOut, ppvOut);
1075
1076     if (!cidl || !apidl || !riid || !ppvOut) 
1077         return E_INVALIDARG;
1078
1079     for (i=0; i<cidl; i++) 
1080         if (!apidl[i]) 
1081             return E_INVALIDARG;
1082     
1083     if (IsEqualIID(&IID_IContextMenu, riid)) {
1084         *ppvOut = ISvItemCm_Constructor((IShellFolder*)iface, This->m_pidlLocation, apidl, cidl);
1085         return S_OK;
1086     } else if (IsEqualIID(&IID_IDataObject, riid)) {
1087         *ppvOut = IDataObject_Constructor(hwndOwner, This->m_pidlLocation, apidl, cidl);
1088         return S_OK;
1089     } else if (IsEqualIID(&IID_IExtractIconA, riid)) {
1090         LPITEMIDLIST pidl;
1091         if (cidl != 1) return E_INVALIDARG;
1092         pidl = ILCombine(This->m_pidlLocation, apidl[0]);
1093         *ppvOut = (LPVOID)IExtractIconA_Constructor(pidl);
1094         SHFree(pidl);
1095         return S_OK;
1096     } else if (IsEqualIID(&IID_IExtractIconW, riid)) {
1097         LPITEMIDLIST pidl;
1098         if (cidl != 1) return E_INVALIDARG;
1099         pidl = ILCombine(This->m_pidlLocation, apidl[0]);
1100         *ppvOut = (LPVOID)IExtractIconW_Constructor(pidl);
1101         SHFree(pidl);
1102         return S_OK;
1103     } else if (IsEqualIID(&IID_IDropTarget, riid)) {
1104         if (cidl != 1) return E_INVALIDARG;
1105         return IShellFolder2_BindToObject(iface, apidl[0], NULL, &IID_IDropTarget, ppvOut);
1106     } else if (IsEqualIID(&IID_IShellLinkW, riid)) {
1107         FIXME("IShellLinkW\n");
1108         return E_FAIL;
1109     } else if (IsEqualIID(&IID_IShellLinkA, riid)) {
1110         FIXME("IShellLinkA\n");
1111         return E_FAIL;
1112     } else {
1113         FIXME("Unknown interface %s in GetUIObjectOf\n", debugstr_guid(riid));
1114         return E_NOINTERFACE;
1115     }
1116 }
1117
1118 static HRESULT WINAPI UnixFolder_IShellFolder2_GetDisplayNameOf(IShellFolder2* iface, 
1119     LPCITEMIDLIST pidl, SHGDNF uFlags, STRRET* lpName)
1120 {
1121     UnixFolder *This = ADJUST_THIS(UnixFolder, IShellFolder2, iface);
1122     HRESULT hr = S_OK;    
1123
1124     TRACE("(iface=%p, pidl=%p, uFlags=%x, lpName=%p)\n", iface, pidl, uFlags, lpName);
1125     
1126     if ((GET_SHGDN_FOR(uFlags) & SHGDN_FORPARSING) &&
1127         (GET_SHGDN_RELATION(uFlags) != SHGDN_INFOLDER))
1128     {
1129         if (!pidl || !pidl->mkid.cb) {
1130             lpName->uType = STRRET_WSTR;
1131             if (This->m_dwPathMode == PATHMODE_UNIX) {
1132                 UINT len = MultiByteToWideChar(CP_UNIXCP, 0, This->m_pszPath, -1, NULL, 0);
1133                 lpName->u.pOleStr = SHAlloc(len * sizeof(WCHAR));
1134                 if (!lpName->u.pOleStr) return HRESULT_FROM_WIN32(GetLastError());
1135                 MultiByteToWideChar(CP_UNIXCP, 0, This->m_pszPath, -1, lpName->u.pOleStr, len);
1136             } else {
1137                 LPWSTR pwszDosFileName = wine_get_dos_file_name(This->m_pszPath);
1138                 if (!pwszDosFileName) return HRESULT_FROM_WIN32(GetLastError());
1139                 lpName->u.pOleStr = SHAlloc((lstrlenW(pwszDosFileName) + 1) * sizeof(WCHAR));
1140                 if (!lpName->u.pOleStr) return HRESULT_FROM_WIN32(GetLastError());
1141                 lstrcpyW(lpName->u.pOleStr, pwszDosFileName);
1142                 PathRemoveBackslashW(lpName->u.pOleStr);
1143                 HeapFree(GetProcessHeap(), 0, pwszDosFileName);
1144             }
1145         } else {
1146             IShellFolder *pSubFolder;
1147             SHITEMID emptyIDL = { 0, { 0 } };
1148
1149             hr = IShellFolder_BindToObject(iface, pidl, NULL, &IID_IShellFolder, (void**)&pSubFolder);
1150             if (!SUCCEEDED(hr)) return hr;
1151        
1152             hr = IShellFolder_GetDisplayNameOf(pSubFolder, (LPITEMIDLIST)&emptyIDL, uFlags, lpName);
1153             IShellFolder_Release(pSubFolder);
1154         }
1155     } else {
1156         WCHAR wszFileName[MAX_PATH];
1157         if (!_ILSimpleGetTextW(pidl, wszFileName, MAX_PATH)) return E_INVALIDARG;
1158         lpName->uType = STRRET_WSTR;
1159         lpName->u.pOleStr = SHAlloc((lstrlenW(wszFileName)+1)*sizeof(WCHAR));
1160         if (!lpName->u.pOleStr) return HRESULT_FROM_WIN32(GetLastError());
1161         lstrcpyW(lpName->u.pOleStr, wszFileName);
1162         if (!(GET_SHGDN_FOR(uFlags) & SHGDN_FORPARSING) && This->m_dwPathMode == PATHMODE_DOS && 
1163             !_ILIsFolder(pidl) && wszFileName[0] != '.' && SHELL_FS_HideExtension(wszFileName))
1164         {
1165             PathRemoveExtensionW(lpName->u.pOleStr);
1166         }
1167     }
1168
1169     TRACE("--> %s\n", debugstr_w(lpName->u.pOleStr));
1170     
1171     return hr;
1172 }
1173
1174 static HRESULT WINAPI UnixFolder_IShellFolder2_SetNameOf(IShellFolder2* iface, HWND hwnd, 
1175     LPCITEMIDLIST pidl, LPCOLESTR lpcwszName, SHGDNF uFlags, LPITEMIDLIST* ppidlOut)
1176 {
1177     UnixFolder *This = ADJUST_THIS(UnixFolder, IShellFolder2, iface);
1178
1179     static const WCHAR awcInvalidChars[] = { '\\', '/', ':', '*', '?', '"', '<', '>', '|' };
1180     char szSrc[FILENAME_MAX], szDest[FILENAME_MAX];
1181     WCHAR wszSrcRelative[MAX_PATH];
1182     int cBasePathLen = lstrlenA(This->m_pszPath), i;
1183     struct stat statDest;
1184     LPITEMIDLIST pidlSrc, pidlDest, pidlRelativeDest;
1185     LPOLESTR lpwszName;
1186     HRESULT hr;
1187    
1188     TRACE("(iface=%p, hwnd=%p, pidl=%p, lpcwszName=%s, uFlags=0x%08x, ppidlOut=%p)\n",
1189           iface, hwnd, pidl, debugstr_w(lpcwszName), uFlags, ppidlOut); 
1190
1191     /* prepare to fail */
1192     if (ppidlOut)
1193         *ppidlOut = NULL;
1194     
1195     /* pidl has to contain a single non-empty SHITEMID */
1196     if (_ILIsDesktop(pidl) || !_ILIsPidlSimple(pidl) || !_ILGetTextPointer(pidl))
1197         return E_INVALIDARG;
1198  
1199     /* check for invalid characters in lpcwszName. */
1200     for (i=0; i < sizeof(awcInvalidChars)/sizeof(*awcInvalidChars); i++)
1201         if (StrChrW(lpcwszName, awcInvalidChars[i]))
1202             return HRESULT_FROM_WIN32(ERROR_CANCELLED);
1203
1204     /* build source path */
1205     memcpy(szSrc, This->m_pszPath, cBasePathLen);
1206     UNIXFS_filename_from_shitemid(pidl, szSrc + cBasePathLen);
1207
1208     /* build destination path */
1209     memcpy(szDest, This->m_pszPath, cBasePathLen);
1210     WideCharToMultiByte(CP_UNIXCP, 0, lpcwszName, -1, szDest+cBasePathLen, 
1211                         FILENAME_MAX-cBasePathLen, NULL, NULL);
1212
1213     /* If the filename's extension is hidden to the user, we have to append it. */
1214     if (!(uFlags & SHGDN_FORPARSING) && 
1215         _ILSimpleGetTextW(pidl, wszSrcRelative, MAX_PATH) && 
1216         SHELL_FS_HideExtension(wszSrcRelative))
1217     {
1218         WCHAR *pwszExt = PathFindExtensionW(wszSrcRelative);
1219         int cLenDest = strlen(szDest);
1220         WideCharToMultiByte(CP_UNIXCP, 0, pwszExt, -1, szDest + cLenDest, 
1221             FILENAME_MAX - cLenDest, NULL, NULL);
1222     }
1223
1224     TRACE("src=%s dest=%s\n", szSrc, szDest);
1225
1226     /* Fail, if destination does already exist */
1227     if (!stat(szDest, &statDest)) 
1228         return E_FAIL;
1229
1230     /* Rename the file */
1231     if (rename(szSrc, szDest)) 
1232         return E_FAIL;
1233     
1234     /* Build a pidl for the path of the renamed file */
1235     lpwszName = SHAlloc((lstrlenW(lpcwszName)+1)*sizeof(WCHAR)); /* due to const correctness. */
1236     lstrcpyW(lpwszName, lpcwszName);
1237     hr = IShellFolder2_ParseDisplayName(iface, NULL, NULL, lpwszName, NULL, &pidlRelativeDest, NULL);
1238     SHFree(lpwszName);
1239     if (FAILED(hr)) {
1240         rename(szDest, szSrc); /* Undo the renaming */
1241         return E_FAIL;
1242     }
1243     pidlDest = ILCombine(This->m_pidlLocation, pidlRelativeDest);
1244     ILFree(pidlRelativeDest);
1245     pidlSrc = ILCombine(This->m_pidlLocation, pidl);
1246     
1247     /* Inform the shell */
1248     if (_ILIsFolder(ILFindLastID(pidlDest))) 
1249         SHChangeNotify(SHCNE_RENAMEFOLDER, SHCNF_IDLIST, pidlSrc, pidlDest);
1250     else 
1251         SHChangeNotify(SHCNE_RENAMEITEM, SHCNF_IDLIST, pidlSrc, pidlDest);
1252     
1253     if (ppidlOut) 
1254         *ppidlOut = ILClone(ILFindLastID(pidlDest));
1255         
1256     ILFree(pidlSrc);
1257     ILFree(pidlDest);
1258     
1259     return S_OK;
1260 }
1261
1262 static HRESULT WINAPI UnixFolder_IShellFolder2_EnumSearches(IShellFolder2* iface, 
1263     IEnumExtraSearch **ppEnum) 
1264 {
1265     FIXME("stub\n");
1266     return E_NOTIMPL;
1267 }
1268
1269 static HRESULT WINAPI UnixFolder_IShellFolder2_GetDefaultColumn(IShellFolder2* iface, 
1270     DWORD dwReserved, ULONG *pSort, ULONG *pDisplay) 
1271 {
1272     FIXME("stub\n");
1273     return E_NOTIMPL;
1274 }
1275
1276 static HRESULT WINAPI UnixFolder_IShellFolder2_GetDefaultColumnState(IShellFolder2* iface, 
1277     UINT iColumn, SHCOLSTATEF *pcsFlags)
1278 {
1279     FIXME("stub\n");
1280     return E_NOTIMPL;
1281 }
1282
1283 static HRESULT WINAPI UnixFolder_IShellFolder2_GetDefaultSearchGUID(IShellFolder2* iface, 
1284     GUID *pguid)
1285 {
1286     FIXME("stub\n");
1287     return E_NOTIMPL;
1288 }
1289
1290 static HRESULT WINAPI UnixFolder_IShellFolder2_GetDetailsEx(IShellFolder2* iface, 
1291     LPCITEMIDLIST pidl, const SHCOLUMNID *pscid, VARIANT *pv)
1292 {
1293     FIXME("stub\n");
1294     return E_NOTIMPL;
1295 }
1296
1297 #define SHELLVIEWCOLUMNS 7 
1298
1299 static HRESULT WINAPI UnixFolder_IShellFolder2_GetDetailsOf(IShellFolder2* iface, 
1300     LPCITEMIDLIST pidl, UINT iColumn, SHELLDETAILS *psd)
1301 {
1302     UnixFolder *This = ADJUST_THIS(UnixFolder, IShellFolder2, iface);
1303     HRESULT hr = E_FAIL;
1304     struct passwd *pPasswd;
1305     struct group *pGroup;
1306     static const shvheader SFHeader[SHELLVIEWCOLUMNS] = {
1307         {IDS_SHV_COLUMN1,  SHCOLSTATE_TYPE_STR  | SHCOLSTATE_ONBYDEFAULT, LVCFMT_RIGHT, 15},
1308         {IDS_SHV_COLUMN2,  SHCOLSTATE_TYPE_STR  | SHCOLSTATE_ONBYDEFAULT, LVCFMT_RIGHT, 10},
1309         {IDS_SHV_COLUMN3,  SHCOLSTATE_TYPE_STR  | SHCOLSTATE_ONBYDEFAULT, LVCFMT_RIGHT, 10},
1310         {IDS_SHV_COLUMN4,  SHCOLSTATE_TYPE_DATE | SHCOLSTATE_ONBYDEFAULT, LVCFMT_RIGHT, 12},
1311         {IDS_SHV_COLUMN5,  SHCOLSTATE_TYPE_STR  | SHCOLSTATE_ONBYDEFAULT, LVCFMT_RIGHT, 9},
1312         {IDS_SHV_COLUMN10, SHCOLSTATE_TYPE_STR  | SHCOLSTATE_ONBYDEFAULT, LVCFMT_RIGHT, 7},
1313         {IDS_SHV_COLUMN11, SHCOLSTATE_TYPE_STR  | SHCOLSTATE_ONBYDEFAULT, LVCFMT_RIGHT, 7}
1314     };
1315
1316     TRACE("(iface=%p, pidl=%p, iColumn=%d, psd=%p) stub\n", iface, pidl, iColumn, psd);
1317     
1318     if (!psd || iColumn >= SHELLVIEWCOLUMNS)
1319         return E_INVALIDARG;
1320
1321     if (!pidl) {
1322         psd->fmt = SFHeader[iColumn].fmt;
1323         psd->cxChar = SFHeader[iColumn].cxChar;
1324         psd->str.uType = STRRET_CSTR;
1325         LoadStringA(shell32_hInstance, SFHeader[iColumn].colnameid, psd->str.u.cStr, MAX_PATH);
1326         return S_OK;
1327     } else {
1328         struct stat statItem;
1329         if (iColumn == 4 || iColumn == 5 || iColumn == 6) {
1330             char szPath[FILENAME_MAX];
1331             strcpy(szPath, This->m_pszPath);
1332             if (!UNIXFS_filename_from_shitemid(pidl, szPath + strlen(szPath)))
1333                 return E_INVALIDARG;
1334             if (stat(szPath, &statItem)) 
1335                 return E_INVALIDARG;
1336         }
1337         psd->str.u.cStr[0] = '\0';
1338         psd->str.uType = STRRET_CSTR;
1339         switch (iColumn) {
1340             case 0:
1341                 hr = IShellFolder2_GetDisplayNameOf(iface, pidl, SHGDN_NORMAL|SHGDN_INFOLDER, &psd->str);
1342                 break;
1343             case 1:
1344                 _ILGetFileSize(pidl, psd->str.u.cStr, MAX_PATH);
1345                 break;
1346             case 2:
1347                 _ILGetFileType (pidl, psd->str.u.cStr, MAX_PATH);
1348                 break;
1349             case 3:
1350                 _ILGetFileDate(pidl, psd->str.u.cStr, MAX_PATH);
1351                 break;
1352             case 4:
1353                 psd->str.u.cStr[0] = S_ISDIR(statItem.st_mode) ? 'd' : '-';
1354                 psd->str.u.cStr[1] = (statItem.st_mode & S_IRUSR) ? 'r' : '-';
1355                 psd->str.u.cStr[2] = (statItem.st_mode & S_IWUSR) ? 'w' : '-';
1356                 psd->str.u.cStr[3] = (statItem.st_mode & S_IXUSR) ? 'x' : '-';
1357                 psd->str.u.cStr[4] = (statItem.st_mode & S_IRGRP) ? 'r' : '-';
1358                 psd->str.u.cStr[5] = (statItem.st_mode & S_IWGRP) ? 'w' : '-';
1359                 psd->str.u.cStr[6] = (statItem.st_mode & S_IXGRP) ? 'x' : '-';
1360                 psd->str.u.cStr[7] = (statItem.st_mode & S_IROTH) ? 'r' : '-';
1361                 psd->str.u.cStr[8] = (statItem.st_mode & S_IWOTH) ? 'w' : '-';
1362                 psd->str.u.cStr[9] = (statItem.st_mode & S_IXOTH) ? 'x' : '-';
1363                 psd->str.u.cStr[10] = '\0';
1364                 break;
1365             case 5:
1366                 pPasswd = getpwuid(statItem.st_uid);
1367                 if (pPasswd) strcpy(psd->str.u.cStr, pPasswd->pw_name);
1368                 break;
1369             case 6:
1370                 pGroup = getgrgid(statItem.st_gid);
1371                 if (pGroup) strcpy(psd->str.u.cStr, pGroup->gr_name);
1372                 break;
1373         }
1374     }
1375     
1376     return hr;
1377 }
1378
1379 static HRESULT WINAPI UnixFolder_IShellFolder2_MapColumnToSCID(IShellFolder2* iface, UINT iColumn,
1380     SHCOLUMNID *pscid) 
1381 {
1382     FIXME("stub\n");
1383     return E_NOTIMPL;
1384 }
1385
1386 /* VTable for UnixFolder's IShellFolder2 interface.
1387  */
1388 static const IShellFolder2Vtbl UnixFolder_IShellFolder2_Vtbl = {
1389     UnixFolder_IShellFolder2_QueryInterface,
1390     UnixFolder_IShellFolder2_AddRef,
1391     UnixFolder_IShellFolder2_Release,
1392     UnixFolder_IShellFolder2_ParseDisplayName,
1393     UnixFolder_IShellFolder2_EnumObjects,
1394     UnixFolder_IShellFolder2_BindToObject,
1395     UnixFolder_IShellFolder2_BindToStorage,
1396     UnixFolder_IShellFolder2_CompareIDs,
1397     UnixFolder_IShellFolder2_CreateViewObject,
1398     UnixFolder_IShellFolder2_GetAttributesOf,
1399     UnixFolder_IShellFolder2_GetUIObjectOf,
1400     UnixFolder_IShellFolder2_GetDisplayNameOf,
1401     UnixFolder_IShellFolder2_SetNameOf,
1402     UnixFolder_IShellFolder2_GetDefaultSearchGUID,
1403     UnixFolder_IShellFolder2_EnumSearches,
1404     UnixFolder_IShellFolder2_GetDefaultColumn,
1405     UnixFolder_IShellFolder2_GetDefaultColumnState,
1406     UnixFolder_IShellFolder2_GetDetailsEx,
1407     UnixFolder_IShellFolder2_GetDetailsOf,
1408     UnixFolder_IShellFolder2_MapColumnToSCID
1409 };
1410
1411 static HRESULT WINAPI UnixFolder_IPersistFolder3_QueryInterface(IPersistFolder3* iface, REFIID riid, 
1412     void** ppvObject)
1413 {
1414     return UnixFolder_IShellFolder2_QueryInterface(
1415         STATIC_CAST(IShellFolder2, ADJUST_THIS(UnixFolder, IPersistFolder3, iface)), riid, ppvObject);
1416 }
1417
1418 static ULONG WINAPI UnixFolder_IPersistFolder3_AddRef(IPersistFolder3* iface)
1419 {
1420     return UnixFolder_IShellFolder2_AddRef(
1421         STATIC_CAST(IShellFolder2, ADJUST_THIS(UnixFolder, IPersistFolder3, iface)));
1422 }
1423
1424 static ULONG WINAPI UnixFolder_IPersistFolder3_Release(IPersistFolder3* iface)
1425 {
1426     return UnixFolder_IShellFolder2_Release(
1427         STATIC_CAST(IShellFolder2, ADJUST_THIS(UnixFolder, IPersistFolder3, iface)));
1428 }
1429
1430 static HRESULT WINAPI UnixFolder_IPersistFolder3_GetClassID(IPersistFolder3* iface, CLSID* pClassID)
1431 {    
1432     UnixFolder *This = ADJUST_THIS(UnixFolder, IPersistFolder3, iface);
1433     
1434     TRACE("(iface=%p, pClassId=%p)\n", iface, pClassID);
1435     
1436     if (!pClassID)
1437         return E_INVALIDARG;
1438
1439     memcpy(pClassID, This->m_pCLSID, sizeof(CLSID));
1440     return S_OK;
1441 }
1442
1443 static HRESULT WINAPI UnixFolder_IPersistFolder3_Initialize(IPersistFolder3* iface, LPCITEMIDLIST pidl)
1444 {
1445     UnixFolder *This = ADJUST_THIS(UnixFolder, IPersistFolder3, iface);
1446     LPCITEMIDLIST current = pidl;
1447     char szBasePath[FILENAME_MAX] = "/";
1448     
1449     TRACE("(iface=%p, pidl=%p)\n", iface, pidl);
1450
1451     /* Find the UnixFolderClass root */
1452     while (current->mkid.cb) {
1453         if ((_ILIsDrive(current) && IsEqualCLSID(This->m_pCLSID, &CLSID_ShellFSFolder)) ||
1454             (_ILIsSpecialFolder(current) && IsEqualCLSID(This->m_pCLSID, _ILGetGUIDPointer(current))))
1455         {
1456             break;
1457         }
1458         current = ILGetNext(current);
1459     }
1460
1461     if (current && current->mkid.cb) {
1462         if (_ILIsDrive(current)) {
1463             WCHAR wszDrive[4] = { '?', ':', '\\', 0 };
1464             wszDrive[0] = (WCHAR)*_ILGetTextPointer(current);
1465             if (!UNIXFS_get_unix_path(wszDrive, szBasePath))
1466                 return E_FAIL;
1467         } else if (IsEqualIID(&CLSID_MyDocuments, _ILGetGUIDPointer(current))) {
1468             WCHAR wszMyDocumentsPath[MAX_PATH];
1469             if (!SHGetSpecialFolderPathW(0, wszMyDocumentsPath, CSIDL_PERSONAL, FALSE))
1470                 return E_FAIL;
1471             PathAddBackslashW(wszMyDocumentsPath);
1472             if (!UNIXFS_get_unix_path(wszMyDocumentsPath, szBasePath))
1473                 return E_FAIL;
1474         } 
1475         current = ILGetNext(current);
1476     } else if (_ILIsDesktop(pidl) || _ILIsValue(pidl) || _ILIsFolder(pidl)) {
1477         /* Path rooted at Desktop */
1478         WCHAR wszDesktopPath[MAX_PATH];
1479         if (!SHGetSpecialFolderPathW(0, wszDesktopPath, CSIDL_DESKTOPDIRECTORY, FALSE)) 
1480             return E_FAIL;
1481         PathAddBackslashW(wszDesktopPath);
1482         if (!UNIXFS_get_unix_path(wszDesktopPath, szBasePath))
1483             return E_FAIL;
1484         current = pidl;
1485     } else if (IsEqualCLSID(This->m_pCLSID, &CLSID_FolderShortcut)) {
1486         /* FolderShortcuts' Initialize method only sets the ITEMIDLIST, which
1487          * specifies the location in the shell namespace, but leaves the
1488          * target folder (m_pszPath) alone. See unit tests in tests/shlfolder.c */
1489         This->m_pidlLocation = ILClone(pidl);
1490         return S_OK;
1491     } else {
1492         ERR("Unknown pidl type!\n");
1493         pdump(pidl);
1494         return E_INVALIDARG;
1495     }
1496   
1497     This->m_pidlLocation = ILClone(pidl);
1498     return UNIXFS_initialize_target_folder(This, szBasePath, current, 0); 
1499 }
1500
1501 static HRESULT WINAPI UnixFolder_IPersistFolder3_GetCurFolder(IPersistFolder3* iface, LPITEMIDLIST* ppidl)
1502 {
1503     UnixFolder *This = ADJUST_THIS(UnixFolder, IPersistFolder3, iface);
1504     
1505     TRACE ("(iface=%p, ppidl=%p)\n", iface, ppidl);
1506
1507     if (!ppidl)
1508         return E_POINTER;
1509     *ppidl = ILClone (This->m_pidlLocation);
1510     return S_OK;
1511 }
1512
1513 static HRESULT WINAPI UnixFolder_IPersistFolder3_InitializeEx(IPersistFolder3 *iface, IBindCtx *pbc, 
1514     LPCITEMIDLIST pidlRoot, const PERSIST_FOLDER_TARGET_INFO *ppfti)
1515 {
1516     UnixFolder *This = ADJUST_THIS(UnixFolder, IPersistFolder3, iface);
1517     WCHAR wszTargetDosPath[MAX_PATH];
1518     char szTargetPath[FILENAME_MAX] = "";
1519     
1520     TRACE("(iface=%p, pbc=%p, pidlRoot=%p, ppfti=%p)\n", iface, pbc, pidlRoot, ppfti);
1521
1522     /* If no PERSIST_FOLDER_TARGET_INFO is given InitializeEx is equivalent to Initialize. */
1523     if (!ppfti) 
1524         return IPersistFolder3_Initialize(iface, pidlRoot);
1525
1526     if (ppfti->csidl != -1) {
1527         if (FAILED(SHGetFolderPathW(0, ppfti->csidl, NULL, 0, wszTargetDosPath)) ||
1528             !UNIXFS_get_unix_path(wszTargetDosPath, szTargetPath))
1529         {
1530             return E_FAIL;
1531         }
1532     } else if (*ppfti->szTargetParsingName) {
1533         lstrcpyW(wszTargetDosPath, ppfti->szTargetParsingName);
1534         PathAddBackslashW(wszTargetDosPath);
1535         if (!UNIXFS_get_unix_path(wszTargetDosPath, szTargetPath)) {
1536             return E_FAIL;
1537         }
1538     } else if (ppfti->pidlTargetFolder) {
1539         if (!SHGetPathFromIDListW(ppfti->pidlTargetFolder, wszTargetDosPath) ||
1540             !UNIXFS_get_unix_path(wszTargetDosPath, szTargetPath))
1541         {
1542             return E_FAIL;
1543         }
1544     } else {
1545         return E_FAIL;
1546     }
1547
1548     This->m_pszPath = SHAlloc(lstrlenA(szTargetPath)+1);
1549     if (!This->m_pszPath) 
1550         return E_FAIL;
1551     lstrcpyA(This->m_pszPath, szTargetPath);
1552     This->m_pidlLocation = ILClone(pidlRoot);
1553     This->m_dwAttributes = (ppfti->dwAttributes != -1) ? ppfti->dwAttributes :
1554         (SFGAO_FOLDER|SFGAO_HASSUBFOLDER|SFGAO_FILESYSANCESTOR|SFGAO_CANRENAME|SFGAO_FILESYSTEM);
1555
1556     return S_OK;
1557 }
1558
1559 static HRESULT WINAPI UnixFolder_IPersistFolder3_GetFolderTargetInfo(IPersistFolder3 *iface, 
1560     PERSIST_FOLDER_TARGET_INFO *ppfti)
1561 {
1562     FIXME("(iface=%p, ppfti=%p) stub\n", iface, ppfti);
1563     return E_NOTIMPL;
1564 }
1565
1566 /* VTable for UnixFolder's IPersistFolder interface.
1567  */
1568 static const IPersistFolder3Vtbl UnixFolder_IPersistFolder3_Vtbl = {
1569     UnixFolder_IPersistFolder3_QueryInterface,
1570     UnixFolder_IPersistFolder3_AddRef,
1571     UnixFolder_IPersistFolder3_Release,
1572     UnixFolder_IPersistFolder3_GetClassID,
1573     UnixFolder_IPersistFolder3_Initialize,
1574     UnixFolder_IPersistFolder3_GetCurFolder,
1575     UnixFolder_IPersistFolder3_InitializeEx,
1576     UnixFolder_IPersistFolder3_GetFolderTargetInfo
1577 };
1578
1579 static HRESULT WINAPI UnixFolder_IPersistPropertyBag_QueryInterface(IPersistPropertyBag* iface,
1580     REFIID riid, void** ppv)
1581 {
1582     return UnixFolder_IShellFolder2_QueryInterface(
1583         STATIC_CAST(IShellFolder2, ADJUST_THIS(UnixFolder, IPersistPropertyBag, iface)), riid, ppv);
1584 }
1585
1586 static ULONG WINAPI UnixFolder_IPersistPropertyBag_AddRef(IPersistPropertyBag* iface)
1587 {
1588     return UnixFolder_IShellFolder2_AddRef(
1589         STATIC_CAST(IShellFolder2, ADJUST_THIS(UnixFolder, IPersistPropertyBag, iface)));
1590 }
1591
1592 static ULONG WINAPI UnixFolder_IPersistPropertyBag_Release(IPersistPropertyBag* iface)
1593 {
1594     return UnixFolder_IShellFolder2_Release(
1595         STATIC_CAST(IShellFolder2, ADJUST_THIS(UnixFolder, IPersistPropertyBag, iface)));
1596 }
1597
1598 static HRESULT WINAPI UnixFolder_IPersistPropertyBag_GetClassID(IPersistPropertyBag* iface, 
1599     CLSID* pClassID)
1600 {
1601     return UnixFolder_IPersistFolder3_GetClassID(
1602         STATIC_CAST(IPersistFolder3, ADJUST_THIS(UnixFolder, IPersistPropertyBag, iface)), pClassID);
1603 }
1604
1605 static HRESULT WINAPI UnixFolder_IPersistPropertyBag_InitNew(IPersistPropertyBag* iface)
1606 {
1607     FIXME("() stub\n");
1608     return E_NOTIMPL;
1609 }
1610
1611 static HRESULT WINAPI UnixFolder_IPersistPropertyBag_Load(IPersistPropertyBag *iface, 
1612     IPropertyBag *pPropertyBag, IErrorLog *pErrorLog)
1613 {
1614      UnixFolder *This = ADJUST_THIS(UnixFolder, IPersistPropertyBag, iface);
1615      static const WCHAR wszTarget[] = { 'T','a','r','g','e','t', 0 }, wszNull[] = { 0 };
1616      PERSIST_FOLDER_TARGET_INFO pftiTarget;
1617      VARIANT var;
1618      HRESULT hr;
1619      
1620      TRACE("(iface=%p, pPropertyBag=%p, pErrorLog=%p)\n", iface, pPropertyBag, pErrorLog);
1621  
1622      if (!pPropertyBag)
1623          return E_POINTER;
1624  
1625      /* Get 'Target' property from the property bag. */
1626      V_VT(&var) = VT_BSTR;
1627      hr = IPropertyBag_Read(pPropertyBag, wszTarget, &var, NULL);
1628      if (FAILED(hr)) 
1629          return E_FAIL;
1630      lstrcpyW(pftiTarget.szTargetParsingName, V_BSTR(&var));
1631      SysFreeString(V_BSTR(&var));
1632  
1633      pftiTarget.pidlTargetFolder = NULL;
1634      lstrcpyW(pftiTarget.szNetworkProvider, wszNull);
1635      pftiTarget.dwAttributes = -1;
1636      pftiTarget.csidl = -1;
1637  
1638      return UnixFolder_IPersistFolder3_InitializeEx(
1639                  STATIC_CAST(IPersistFolder3, This), NULL, NULL, &pftiTarget);
1640 }
1641
1642 static HRESULT WINAPI UnixFolder_IPersistPropertyBag_Save(IPersistPropertyBag *iface,
1643     IPropertyBag *pPropertyBag, BOOL fClearDirty, BOOL fSaveAllProperties)
1644 {
1645     FIXME("() stub\n");
1646     return E_NOTIMPL;
1647 }
1648
1649 /* VTable for UnixFolder's IPersistPropertyBag interface.
1650  */
1651 static const IPersistPropertyBagVtbl UnixFolder_IPersistPropertyBag_Vtbl = {
1652     UnixFolder_IPersistPropertyBag_QueryInterface,
1653     UnixFolder_IPersistPropertyBag_AddRef,
1654     UnixFolder_IPersistPropertyBag_Release,
1655     UnixFolder_IPersistPropertyBag_GetClassID,
1656     UnixFolder_IPersistPropertyBag_InitNew,
1657     UnixFolder_IPersistPropertyBag_Load,
1658     UnixFolder_IPersistPropertyBag_Save
1659 };
1660
1661 static HRESULT WINAPI UnixFolder_ISFHelper_QueryInterface(ISFHelper* iface, REFIID riid, 
1662     void** ppvObject)
1663 {
1664     return UnixFolder_IShellFolder2_QueryInterface(
1665         STATIC_CAST(IShellFolder2, ADJUST_THIS(UnixFolder, ISFHelper, iface)), riid, ppvObject);
1666 }
1667
1668 static ULONG WINAPI UnixFolder_ISFHelper_AddRef(ISFHelper* iface)
1669 {
1670     return UnixFolder_IShellFolder2_AddRef(
1671         STATIC_CAST(IShellFolder2, ADJUST_THIS(UnixFolder, ISFHelper, iface)));
1672 }
1673
1674 static ULONG WINAPI UnixFolder_ISFHelper_Release(ISFHelper* iface)
1675 {
1676     return UnixFolder_IShellFolder2_Release(
1677         STATIC_CAST(IShellFolder2, ADJUST_THIS(UnixFolder, ISFHelper, iface)));
1678 }
1679
1680 static HRESULT WINAPI UnixFolder_ISFHelper_GetUniqueName(ISFHelper* iface, LPWSTR pwszName, UINT uLen)
1681 {
1682     UnixFolder *This = ADJUST_THIS(UnixFolder, ISFHelper, iface);
1683     IEnumIDList *pEnum;
1684     HRESULT hr;
1685     LPITEMIDLIST pidlElem;
1686     DWORD dwFetched;
1687     int i;
1688     static const WCHAR wszNewFolder[] = { 'N','e','w',' ','F','o','l','d','e','r', 0 };
1689     static const WCHAR wszFormat[] = { '%','s',' ','%','d',0 };
1690
1691     TRACE("(iface=%p, pwszName=%p, uLen=%u)\n", iface, pwszName, uLen);
1692     
1693     if (uLen < sizeof(wszNewFolder)/sizeof(WCHAR)+3)
1694         return E_INVALIDARG;
1695
1696     hr = IShellFolder2_EnumObjects(STATIC_CAST(IShellFolder2, This), 0,
1697                                    SHCONTF_FOLDERS|SHCONTF_NONFOLDERS|SHCONTF_INCLUDEHIDDEN, &pEnum);
1698     if (SUCCEEDED(hr)) {
1699         lstrcpynW(pwszName, wszNewFolder, uLen);
1700         IEnumIDList_Reset(pEnum);
1701         i = 2;
1702         while ((IEnumIDList_Next(pEnum, 1, &pidlElem, &dwFetched) == S_OK) && (dwFetched == 1)) {
1703             WCHAR wszTemp[MAX_PATH];
1704             _ILSimpleGetTextW(pidlElem, wszTemp, MAX_PATH);
1705             if (!lstrcmpiW(wszTemp, pwszName)) {
1706                 IEnumIDList_Reset(pEnum);
1707                 snprintfW(pwszName, uLen, wszFormat, wszNewFolder, i++);
1708                 if (i > 99) {
1709                     hr = E_FAIL;
1710                     break;
1711                 }
1712             }
1713         }
1714         IEnumIDList_Release(pEnum);
1715     }
1716     return hr;
1717 }
1718
1719 static HRESULT WINAPI UnixFolder_ISFHelper_AddFolder(ISFHelper* iface, HWND hwnd, LPCWSTR pwszName, 
1720     LPITEMIDLIST* ppidlOut)
1721 {
1722     UnixFolder *This = ADJUST_THIS(UnixFolder, ISFHelper, iface);
1723     char szNewDir[FILENAME_MAX];
1724     int cBaseLen;
1725
1726     TRACE("(iface=%p, hwnd=%p, pwszName=%s, ppidlOut=%p)\n", 
1727             iface, hwnd, debugstr_w(pwszName), ppidlOut);
1728
1729     if (ppidlOut)
1730         *ppidlOut = NULL;
1731
1732     if (!This->m_pszPath || !(This->m_dwAttributes & SFGAO_FILESYSTEM))
1733         return E_FAIL;
1734     
1735     lstrcpynA(szNewDir, This->m_pszPath, FILENAME_MAX);
1736     cBaseLen = lstrlenA(szNewDir);
1737     WideCharToMultiByte(CP_UNIXCP, 0, pwszName, -1, szNewDir+cBaseLen, FILENAME_MAX-cBaseLen, 0, 0);
1738    
1739     if (mkdir(szNewDir, 0755)) {
1740         char szMessage[256 + FILENAME_MAX];
1741         char szCaption[256];
1742
1743         LoadStringA(shell32_hInstance, IDS_CREATEFOLDER_DENIED, szCaption, sizeof(szCaption));
1744         sprintf(szMessage, szCaption, szNewDir);
1745         LoadStringA(shell32_hInstance, IDS_CREATEFOLDER_CAPTION, szCaption, sizeof(szCaption));
1746         MessageBoxA(hwnd, szMessage, szCaption, MB_OK | MB_ICONEXCLAMATION);
1747
1748         return E_FAIL;
1749     } else {
1750         LPITEMIDLIST pidlRelative;
1751
1752         /* Inform the shell */
1753         if (UNIXFS_path_to_pidl(This, pwszName, &pidlRelative)) {
1754             LPITEMIDLIST pidlAbsolute = ILCombine(This->m_pidlLocation, pidlRelative);
1755             if (ppidlOut)
1756                 *ppidlOut = pidlRelative;
1757             else
1758                 ILFree(pidlRelative);
1759             SHChangeNotify(SHCNE_MKDIR, SHCNF_IDLIST, pidlAbsolute, NULL);
1760             ILFree(pidlAbsolute);
1761         } else return E_FAIL;
1762         return S_OK;
1763     }
1764 }
1765
1766 /*
1767  * Delete specified files by converting the path to DOS paths and calling
1768  * SHFileOperationW. If an error occurs it returns an error code. If the paths can't
1769  * be converted, S_FALSE is returned. In such situation DeleteItems will try to delete
1770  * the files using syscalls
1771  */
1772 static HRESULT UNIXFS_delete_with_shfileop(UnixFolder *This, UINT cidl, LPCITEMIDLIST *apidl)
1773 {
1774     char szAbsolute[FILENAME_MAX], *pszRelative;
1775     LPWSTR wszPathsList, wszListPos;
1776     SHFILEOPSTRUCTW op;
1777     HRESULT ret;
1778     int i;
1779     
1780     lstrcpyA(szAbsolute, This->m_pszPath);
1781     pszRelative = szAbsolute + lstrlenA(szAbsolute);
1782     
1783     wszListPos = wszPathsList = HeapAlloc(GetProcessHeap(), 0, cidl*MAX_PATH*sizeof(WCHAR)+1);
1784     if (wszPathsList == NULL)
1785         return E_OUTOFMEMORY;
1786     for (i=0; i<cidl; i++) {
1787         LPWSTR wszDosPath;
1788         
1789         if (!_ILIsFolder(apidl[i]) && !_ILIsValue(apidl[i]))
1790             continue;
1791         if (!UNIXFS_filename_from_shitemid(apidl[i], pszRelative))
1792         {
1793             HeapFree(GetProcessHeap(), 0, wszPathsList);
1794             return E_INVALIDARG;
1795         }
1796         wszDosPath = wine_get_dos_file_name(szAbsolute);
1797         if (wszDosPath == NULL || lstrlenW(wszDosPath) >= MAX_PATH)
1798         {
1799             HeapFree(GetProcessHeap(), 0, wszPathsList);
1800             HeapFree(GetProcessHeap(), 0, wszDosPath);
1801             return S_FALSE;
1802         }
1803         lstrcpyW(wszListPos, wszDosPath);
1804         wszListPos += lstrlenW(wszListPos)+1;
1805         HeapFree(GetProcessHeap(), 0, wszDosPath);
1806     }
1807     *wszListPos = 0;
1808     
1809     ZeroMemory(&op, sizeof(op));
1810     op.hwnd = GetActiveWindow();
1811     op.wFunc = FO_DELETE;
1812     op.pFrom = wszPathsList;
1813     op.fFlags = FOF_ALLOWUNDO;
1814     if (!SHFileOperationW(&op))
1815     {
1816         WARN("SHFileOperationW failed\n");
1817         ret = E_FAIL;
1818     }
1819     else
1820         ret = S_OK;
1821
1822     HeapFree(GetProcessHeap(), 0, wszPathsList);
1823     return ret;
1824 }
1825
1826 static HRESULT UNIXFS_delete_with_syscalls(UnixFolder *This, UINT cidl, LPCITEMIDLIST *apidl)
1827 {
1828     char szAbsolute[FILENAME_MAX], *pszRelative;
1829     static const WCHAR empty[] = {0};
1830     int i;
1831     
1832     if (!SHELL_ConfirmDialogW(GetActiveWindow(), ASK_DELETE_SELECTED, empty))
1833         return S_OK;
1834     
1835     lstrcpyA(szAbsolute, This->m_pszPath);
1836     pszRelative = szAbsolute + lstrlenA(szAbsolute);
1837     
1838     for (i=0; i<cidl; i++) {
1839         if (!UNIXFS_filename_from_shitemid(apidl[i], pszRelative))
1840             return E_INVALIDARG;
1841         if (_ILIsFolder(apidl[i])) {
1842             if (rmdir(szAbsolute))
1843                 return E_FAIL;
1844         } else if (_ILIsValue(apidl[i])) {
1845             if (unlink(szAbsolute))
1846                 return E_FAIL;
1847         }
1848     }
1849     return S_OK;
1850 }
1851
1852 static HRESULT WINAPI UnixFolder_ISFHelper_DeleteItems(ISFHelper* iface, UINT cidl, 
1853     LPCITEMIDLIST* apidl)
1854 {
1855     UnixFolder *This = ADJUST_THIS(UnixFolder, ISFHelper, iface);
1856     char szAbsolute[FILENAME_MAX], *pszRelative;
1857     LPITEMIDLIST pidlAbsolute;
1858     HRESULT hr = S_OK;
1859     UINT i;
1860     struct stat st;
1861     
1862     TRACE("(iface=%p, cidl=%d, apidl=%p)\n", iface, cidl, apidl);
1863
1864     hr = UNIXFS_delete_with_shfileop(This, cidl, apidl);
1865     if (hr == S_FALSE)
1866         hr = UNIXFS_delete_with_syscalls(This, cidl, apidl);
1867
1868     lstrcpyA(szAbsolute, This->m_pszPath);
1869     pszRelative = szAbsolute + lstrlenA(szAbsolute);
1870     
1871     /* we need to manually send the notifies if the files doesn't exist */
1872     for (i=0; i<cidl; i++) {
1873         if (!UNIXFS_filename_from_shitemid(apidl[i], pszRelative))
1874             continue;
1875         pidlAbsolute = ILCombine(This->m_pidlLocation, apidl[i]);
1876         if (stat(szAbsolute, &st))
1877         {
1878             if (_ILIsFolder(apidl[i])) {
1879                 SHChangeNotify(SHCNE_RMDIR, SHCNF_IDLIST, pidlAbsolute, NULL);
1880             } else if (_ILIsValue(apidl[i])) {
1881                 SHChangeNotify(SHCNE_DELETE, SHCNF_IDLIST, pidlAbsolute, NULL);
1882             }
1883         }
1884         ILFree(pidlAbsolute);
1885     }
1886         
1887     return hr;
1888 }
1889
1890 static HRESULT WINAPI UnixFolder_ISFHelper_CopyItems(ISFHelper* iface, IShellFolder *psfFrom, 
1891     UINT cidl, LPCITEMIDLIST *apidl)
1892 {
1893     UnixFolder *This = ADJUST_THIS(UnixFolder, ISFHelper, iface);
1894     DWORD dwAttributes;
1895     UINT i;
1896     HRESULT hr;
1897     char szAbsoluteDst[FILENAME_MAX], *pszRelativeDst;
1898     
1899     TRACE("(iface=%p, psfFrom=%p, cidl=%d, apidl=%p): semi-stub\n", iface, psfFrom, cidl, apidl);
1900
1901     if (!psfFrom || !cidl || !apidl)
1902         return E_INVALIDARG;
1903
1904     /* All source items have to be filesystem items. */
1905     dwAttributes = SFGAO_FILESYSTEM;
1906     hr = IShellFolder_GetAttributesOf(psfFrom, cidl, apidl, &dwAttributes);
1907     if (FAILED(hr) || !(dwAttributes & SFGAO_FILESYSTEM)) 
1908         return E_INVALIDARG;
1909
1910     lstrcpyA(szAbsoluteDst, This->m_pszPath);
1911     pszRelativeDst = szAbsoluteDst + strlen(szAbsoluteDst);
1912     
1913     for (i=0; i<cidl; i++) {
1914         WCHAR wszSrc[MAX_PATH];
1915         char szSrc[FILENAME_MAX];
1916         STRRET strret;
1917
1918         /* Build the unix path of the current source item. */
1919         if (FAILED(IShellFolder_GetDisplayNameOf(psfFrom, apidl[i], SHGDN_FORPARSING, &strret)))
1920             return E_FAIL;
1921         if (FAILED(StrRetToBufW(&strret, apidl[i], wszSrc, MAX_PATH)))
1922             return E_FAIL;
1923         if (!UNIXFS_get_unix_path(wszSrc, szSrc)) 
1924             return E_FAIL;
1925
1926         /* Build the unix path of the current destination item */
1927         UNIXFS_filename_from_shitemid(apidl[i], pszRelativeDst);
1928
1929         FIXME("Would copy %s to %s. Not yet implemented.\n", szSrc, szAbsoluteDst);
1930     }
1931     return S_OK;
1932 }
1933
1934 /* VTable for UnixFolder's ISFHelper interface
1935  */
1936 static const ISFHelperVtbl UnixFolder_ISFHelper_Vtbl = {
1937     UnixFolder_ISFHelper_QueryInterface,
1938     UnixFolder_ISFHelper_AddRef,
1939     UnixFolder_ISFHelper_Release,
1940     UnixFolder_ISFHelper_GetUniqueName,
1941     UnixFolder_ISFHelper_AddFolder,
1942     UnixFolder_ISFHelper_DeleteItems,
1943     UnixFolder_ISFHelper_CopyItems
1944 };
1945
1946 static HRESULT WINAPI UnixFolder_IDropTarget_QueryInterface(IDropTarget* iface, REFIID riid, 
1947     void** ppvObject)
1948 {
1949     return UnixFolder_IShellFolder2_QueryInterface(
1950         STATIC_CAST(IShellFolder2, ADJUST_THIS(UnixFolder, IDropTarget, iface)), riid, ppvObject);
1951 }
1952
1953 static ULONG WINAPI UnixFolder_IDropTarget_AddRef(IDropTarget* iface)
1954 {
1955     return UnixFolder_IShellFolder2_AddRef(
1956         STATIC_CAST(IShellFolder2, ADJUST_THIS(UnixFolder, IDropTarget, iface)));
1957 }
1958
1959 static ULONG WINAPI UnixFolder_IDropTarget_Release(IDropTarget* iface)
1960 {
1961     return UnixFolder_IShellFolder2_Release(
1962         STATIC_CAST(IShellFolder2, ADJUST_THIS(UnixFolder, IDropTarget, iface)));
1963 }
1964
1965 #define HIDA_GetPIDLFolder(pida) (LPCITEMIDLIST)(((LPBYTE)pida)+(pida)->aoffset[0])
1966 #define HIDA_GetPIDLItem(pida, i) (LPCITEMIDLIST)(((LPBYTE)pida)+(pida)->aoffset[i+1])
1967
1968 static HRESULT WINAPI UnixFolder_IDropTarget_DragEnter(IDropTarget *iface, IDataObject *pDataObject,
1969     DWORD dwKeyState, POINTL pt, DWORD *pdwEffect)
1970 {
1971     UnixFolder *This = ADJUST_THIS(UnixFolder, IDropTarget, iface);
1972     FORMATETC format;
1973     STGMEDIUM medium; 
1974         
1975     TRACE("(iface=%p, pDataObject=%p, dwKeyState=%08x, pt={.x=%d, .y=%d}, pdwEffect=%p)\n",
1976         iface, pDataObject, dwKeyState, pt.x, pt.y, pdwEffect);
1977
1978     if (!pdwEffect || !pDataObject)
1979         return E_INVALIDARG;
1980   
1981     /* Compute a mask of supported drop-effects for this shellfolder object and the given data 
1982      * object. Dropping is only supported on folders, which represent filesystem locations. One
1983      * can't drop on file objects. And the 'move' drop effect is only supported, if the source
1984      * folder is not identical to the target folder. */
1985     This->m_dwDropEffectsMask = DROPEFFECT_NONE;
1986     InitFormatEtc(format, cfShellIDList, TYMED_HGLOBAL);
1987     if ((This->m_dwAttributes & SFGAO_FILESYSTEM) && /* Only drop to filesystem folders */
1988         _ILIsFolder(ILFindLastID(This->m_pidlLocation)) && /* Only drop to folders, not to files */
1989         SUCCEEDED(IDataObject_GetData(pDataObject, &format, &medium))) /* Only ShellIDList format */
1990     {
1991         LPIDA pidaShellIDList = GlobalLock(medium.u.hGlobal);
1992         This->m_dwDropEffectsMask |= DROPEFFECT_COPY|DROPEFFECT_LINK;
1993
1994         if (pidaShellIDList) { /* Files can only be moved between two different folders */
1995             if (!ILIsEqual(HIDA_GetPIDLFolder(pidaShellIDList), This->m_pidlLocation))
1996                 This->m_dwDropEffectsMask |= DROPEFFECT_MOVE;
1997             GlobalUnlock(medium.u.hGlobal);
1998         }
1999     }
2000
2001     *pdwEffect = KeyStateToDropEffect(dwKeyState) & This->m_dwDropEffectsMask;
2002     
2003     return S_OK;
2004 }
2005
2006 static HRESULT WINAPI UnixFolder_IDropTarget_DragOver(IDropTarget *iface, DWORD dwKeyState, 
2007     POINTL pt, DWORD *pdwEffect)
2008 {
2009     UnixFolder *This = ADJUST_THIS(UnixFolder, IDropTarget, iface);
2010     
2011     TRACE("(iface=%p, dwKeyState=%08x, pt={.x=%d, .y=%d}, pdwEffect=%p)\n", iface, dwKeyState, 
2012         pt.x, pt.y, pdwEffect);
2013
2014     if (!pdwEffect)
2015         return E_INVALIDARG;
2016
2017     *pdwEffect = KeyStateToDropEffect(dwKeyState) & This->m_dwDropEffectsMask;
2018     
2019     return S_OK;
2020 }
2021
2022 static HRESULT WINAPI UnixFolder_IDropTarget_DragLeave(IDropTarget *iface) {
2023     UnixFolder *This = ADJUST_THIS(UnixFolder, IDropTarget, iface);
2024     
2025     TRACE("(iface=%p)\n", iface);
2026  
2027     This->m_dwDropEffectsMask = DROPEFFECT_NONE;
2028     
2029     return S_OK;
2030 }
2031
2032 static HRESULT WINAPI UnixFolder_IDropTarget_Drop(IDropTarget *iface, IDataObject *pDataObject,
2033     DWORD dwKeyState, POINTL pt, DWORD *pdwEffect)
2034 {
2035     UnixFolder *This = ADJUST_THIS(UnixFolder, IDropTarget, iface);
2036     FORMATETC format;
2037     STGMEDIUM medium; 
2038     HRESULT hr;
2039
2040     TRACE("(iface=%p, pDataObject=%p, dwKeyState=%d, pt={.x=%d, .y=%d}, pdwEffect=%p) semi-stub\n",
2041         iface, pDataObject, dwKeyState, pt.x, pt.y, pdwEffect);
2042
2043     InitFormatEtc(format, cfShellIDList, TYMED_HGLOBAL);
2044     hr = IDataObject_GetData(pDataObject, &format, &medium);
2045     if (!SUCCEEDED(hr)) 
2046         return hr;
2047
2048     if (medium.tymed == TYMED_HGLOBAL) {
2049         IShellFolder *psfSourceFolder, *psfDesktopFolder;
2050         LPIDA pidaShellIDList = GlobalLock(medium.u.hGlobal);
2051         STRRET strret;
2052         UINT i;
2053     
2054         if (!pidaShellIDList) 
2055             return HRESULT_FROM_WIN32(GetLastError());
2056         
2057         hr = SHGetDesktopFolder(&psfDesktopFolder);
2058         if (FAILED(hr)) {
2059             GlobalUnlock(medium.u.hGlobal);
2060             return hr;
2061         }
2062
2063         hr = IShellFolder_BindToObject(psfDesktopFolder, HIDA_GetPIDLFolder(pidaShellIDList), NULL, 
2064                                        &IID_IShellFolder, (LPVOID*)&psfSourceFolder);
2065         IShellFolder_Release(psfDesktopFolder);
2066         if (FAILED(hr)) {
2067             GlobalUnlock(medium.u.hGlobal);
2068             return hr;
2069         }
2070
2071         for (i = 0; i < pidaShellIDList->cidl; i++) {
2072             WCHAR wszSourcePath[MAX_PATH];
2073
2074             hr = IShellFolder_GetDisplayNameOf(psfSourceFolder, HIDA_GetPIDLItem(pidaShellIDList, i),
2075                                                SHGDN_FORPARSING, &strret);
2076             if (FAILED(hr)) 
2077                 break;
2078
2079             hr = StrRetToBufW(&strret, NULL, wszSourcePath, MAX_PATH);
2080             if (FAILED(hr)) 
2081                 break;
2082
2083             switch (*pdwEffect) {
2084                 case DROPEFFECT_MOVE:
2085                     FIXME("Move %s to %s!\n", debugstr_w(wszSourcePath), This->m_pszPath);
2086                     break;
2087                 case DROPEFFECT_COPY:
2088                     FIXME("Copy %s to %s!\n", debugstr_w(wszSourcePath), This->m_pszPath);
2089                     break;
2090                 case DROPEFFECT_LINK:
2091                     FIXME("Link %s from %s!\n", debugstr_w(wszSourcePath), This->m_pszPath);
2092                     break;
2093             }
2094         }
2095     
2096         IShellFolder_Release(psfSourceFolder);
2097         GlobalUnlock(medium.u.hGlobal);
2098         return hr;
2099     }
2100  
2101     return E_NOTIMPL;
2102 }
2103
2104 /* VTable for UnixFolder's IDropTarget interface
2105  */
2106 static const IDropTargetVtbl UnixFolder_IDropTarget_Vtbl = {
2107     UnixFolder_IDropTarget_QueryInterface,
2108     UnixFolder_IDropTarget_AddRef,
2109     UnixFolder_IDropTarget_Release,
2110     UnixFolder_IDropTarget_DragEnter,
2111     UnixFolder_IDropTarget_DragOver,
2112     UnixFolder_IDropTarget_DragLeave,
2113     UnixFolder_IDropTarget_Drop
2114 };
2115
2116 /******************************************************************************
2117  * Unix[Dos]Folder_Constructor [Internal]
2118  *
2119  * PARAMS
2120  *  pUnkOuter [I] Outer class for aggregation. Currently ignored.
2121  *  riid      [I] Interface asked for by the client.
2122  *  ppv       [O] Pointer to an riid interface to the UnixFolder object.
2123  *
2124  * NOTES
2125  *  Those are the only functions exported from shfldr_unixfs.c. They are called from
2126  *  shellole.c's default class factory and thus have to exhibit a LPFNCREATEINSTANCE
2127  *  compatible signature.
2128  *
2129  *  The UnixDosFolder_Constructor sets the dwPathMode member to PATHMODE_DOS. This
2130  *  means that paths are converted from dos to unix and back at the interfaces.
2131  */
2132 static HRESULT CreateUnixFolder(IUnknown *pUnkOuter, REFIID riid, LPVOID *ppv, const CLSID *pCLSID) 
2133 {
2134     HRESULT hr = E_FAIL;
2135     UnixFolder *pUnixFolder = SHAlloc((ULONG)sizeof(UnixFolder));
2136    
2137     if (pUnkOuter) {
2138         FIXME("Aggregation not yet implemented!\n");
2139         return CLASS_E_NOAGGREGATION;
2140     }
2141     
2142     if(pUnixFolder) {
2143         pUnixFolder->lpIShellFolder2Vtbl = &UnixFolder_IShellFolder2_Vtbl;
2144         pUnixFolder->lpIPersistFolder3Vtbl = &UnixFolder_IPersistFolder3_Vtbl;
2145         pUnixFolder->lpIPersistPropertyBagVtbl = &UnixFolder_IPersistPropertyBag_Vtbl;
2146         pUnixFolder->lpISFHelperVtbl = &UnixFolder_ISFHelper_Vtbl;
2147         pUnixFolder->lpIDropTargetVtbl = &UnixFolder_IDropTarget_Vtbl;
2148         pUnixFolder->m_cRef = 0;
2149         pUnixFolder->m_pszPath = NULL;
2150         pUnixFolder->m_pidlLocation = NULL;
2151         pUnixFolder->m_dwPathMode = IsEqualCLSID(&CLSID_UnixFolder, pCLSID) ? PATHMODE_UNIX : PATHMODE_DOS;
2152         pUnixFolder->m_dwAttributes = 0;
2153         pUnixFolder->m_pCLSID = pCLSID;
2154         pUnixFolder->m_dwDropEffectsMask = DROPEFFECT_NONE;
2155
2156         UnixFolder_IShellFolder2_AddRef(STATIC_CAST(IShellFolder2, pUnixFolder));
2157         hr = UnixFolder_IShellFolder2_QueryInterface(STATIC_CAST(IShellFolder2, pUnixFolder), riid, ppv);
2158         UnixFolder_IShellFolder2_Release(STATIC_CAST(IShellFolder2, pUnixFolder));
2159     }
2160     return hr;
2161 }
2162
2163 HRESULT WINAPI UnixFolder_Constructor(IUnknown *pUnkOuter, REFIID riid, LPVOID *ppv) {
2164     TRACE("(pUnkOuter=%p, riid=%p, ppv=%p)\n", pUnkOuter, riid, ppv);
2165     return CreateUnixFolder(pUnkOuter, riid, ppv, &CLSID_UnixFolder);
2166 }
2167
2168 HRESULT WINAPI UnixDosFolder_Constructor(IUnknown *pUnkOuter, REFIID riid, LPVOID *ppv) {
2169     TRACE("(pUnkOuter=%p, riid=%p, ppv=%p)\n", pUnkOuter, riid, ppv);
2170     return CreateUnixFolder(pUnkOuter, riid, ppv, &CLSID_UnixDosFolder);
2171 }
2172
2173 HRESULT WINAPI FolderShortcut_Constructor(IUnknown *pUnkOuter, REFIID riid, LPVOID *ppv) {
2174     TRACE("(pUnkOuter=%p, riid=%p, ppv=%p)\n", pUnkOuter, riid, ppv);
2175     return CreateUnixFolder(pUnkOuter, riid, ppv, &CLSID_FolderShortcut);
2176 }
2177
2178 HRESULT WINAPI MyDocuments_Constructor(IUnknown *pUnkOuter, REFIID riid, LPVOID *ppv) {
2179     TRACE("(pUnkOuter=%p, riid=%p, ppv=%p)\n", pUnkOuter, riid, ppv);
2180     return CreateUnixFolder(pUnkOuter, riid, ppv, &CLSID_MyDocuments);
2181 }
2182
2183 HRESULT WINAPI ShellFSFolder_Constructor(IUnknown *pUnkOuter, REFIID riid, LPVOID *ppv) {
2184     TRACE("(pUnkOuter=%p, riid=%p, ppv=%p)\n", pUnkOuter, riid, ppv);
2185     return CreateUnixFolder(pUnkOuter, riid, ppv, &CLSID_ShellFSFolder);
2186 }
2187
2188 /******************************************************************************
2189  * UnixSubFolderIterator
2190  *
2191  * Class whose heap based objects represent iterators over the sub-directories
2192  * of a given UnixFolder object. 
2193  */
2194
2195 /* UnixSubFolderIterator object layout and typedef.
2196  */
2197 typedef struct _UnixSubFolderIterator {
2198     const IEnumIDListVtbl *lpIEnumIDListVtbl;
2199     LONG m_cRef;
2200     SHCONTF m_fFilter;
2201     DIR *m_dirFolder;
2202     char m_szFolder[FILENAME_MAX];
2203 } UnixSubFolderIterator;
2204
2205 static void UnixSubFolderIterator_Destroy(UnixSubFolderIterator *iterator) {
2206     TRACE("(iterator=%p)\n", iterator);
2207
2208     if (iterator->m_dirFolder)
2209         closedir(iterator->m_dirFolder);
2210     SHFree(iterator);
2211 }
2212
2213 static HRESULT WINAPI UnixSubFolderIterator_IEnumIDList_QueryInterface(IEnumIDList* iface, 
2214     REFIID riid, void** ppv)
2215 {
2216     TRACE("(iface=%p, riid=%p, ppv=%p)\n", iface, riid, ppv);
2217     
2218     if (!ppv) return E_INVALIDARG;
2219     
2220     if (IsEqualIID(&IID_IUnknown, riid) || IsEqualIID(&IID_IEnumIDList, riid)) {
2221         *ppv = iface;
2222     } else {
2223         *ppv = NULL;
2224         return E_NOINTERFACE;
2225     }
2226
2227     IEnumIDList_AddRef(iface);
2228     return S_OK;
2229 }
2230                             
2231 static ULONG WINAPI UnixSubFolderIterator_IEnumIDList_AddRef(IEnumIDList* iface)
2232 {
2233     UnixSubFolderIterator *This = ADJUST_THIS(UnixSubFolderIterator, IEnumIDList, iface);
2234
2235     TRACE("(iface=%p)\n", iface);
2236    
2237     return InterlockedIncrement(&This->m_cRef);
2238 }
2239
2240 static ULONG WINAPI UnixSubFolderIterator_IEnumIDList_Release(IEnumIDList* iface)
2241 {
2242     UnixSubFolderIterator *This = ADJUST_THIS(UnixSubFolderIterator, IEnumIDList, iface);
2243     ULONG cRef;
2244     
2245     TRACE("(iface=%p)\n", iface);
2246
2247     cRef = InterlockedDecrement(&This->m_cRef);
2248     
2249     if (!cRef) 
2250         UnixSubFolderIterator_Destroy(This);
2251
2252     return cRef;
2253 }
2254
2255 static HRESULT WINAPI UnixSubFolderIterator_IEnumIDList_Next(IEnumIDList* iface, ULONG celt, 
2256     LPITEMIDLIST* rgelt, ULONG* pceltFetched)
2257 {
2258     UnixSubFolderIterator *This = ADJUST_THIS(UnixSubFolderIterator, IEnumIDList, iface);
2259     ULONG i = 0;
2260
2261     /* This->m_dirFolder will be NULL if the user doesn't have access rights for the dir. */
2262     if (This->m_dirFolder) {
2263         char *pszRelativePath = This->m_szFolder + lstrlenA(This->m_szFolder);
2264         struct dirent *pDirEntry;
2265
2266         while (i < celt) {
2267             pDirEntry = readdir(This->m_dirFolder);
2268             if (!pDirEntry) break; /* No more entries */
2269             if (!strcmp(pDirEntry->d_name, ".") || !strcmp(pDirEntry->d_name, "..")) continue;
2270
2271             /* Temporarily build absolute path in This->m_szFolder. Then construct a pidl
2272              * and see if it passes the filter. 
2273              */
2274             lstrcpyA(pszRelativePath, pDirEntry->d_name);
2275             rgelt[i] = (LPITEMIDLIST)SHAlloc(
2276                 UNIXFS_shitemid_len_from_filename(pszRelativePath, NULL, NULL)+sizeof(USHORT));
2277             if (!UNIXFS_build_shitemid(This->m_szFolder, rgelt[i]) ||
2278                 !UNIXFS_is_pidl_of_type(rgelt[i], This->m_fFilter)) 
2279             {
2280                 SHFree(rgelt[i]);
2281                 continue;
2282             }
2283             memset(((PBYTE)rgelt[i])+rgelt[i]->mkid.cb, 0, sizeof(USHORT));
2284             i++;
2285         }
2286         *pszRelativePath = '\0'; /* Restore the original path in This->m_szFolder. */
2287     }
2288     
2289     if (pceltFetched)
2290         *pceltFetched = i;
2291
2292     return (i == 0) ? S_FALSE : S_OK;
2293 }
2294     
2295 static HRESULT WINAPI UnixSubFolderIterator_IEnumIDList_Skip(IEnumIDList* iface, ULONG celt)
2296 {
2297     LPITEMIDLIST *apidl;
2298     ULONG cFetched;
2299     HRESULT hr;
2300     
2301     TRACE("(iface=%p, celt=%d)\n", iface, celt);
2302
2303     /* Call IEnumIDList::Next and delete the resulting pidls. */
2304     apidl = (LPITEMIDLIST*)SHAlloc(celt * sizeof(LPITEMIDLIST));
2305     hr = IEnumIDList_Next(iface, celt, apidl, &cFetched);
2306     if (SUCCEEDED(hr))
2307         while (cFetched--) 
2308             SHFree(apidl[cFetched]);
2309     SHFree(apidl);
2310
2311     return hr;
2312 }
2313
2314 static HRESULT WINAPI UnixSubFolderIterator_IEnumIDList_Reset(IEnumIDList* iface)
2315 {
2316     UnixSubFolderIterator *This = ADJUST_THIS(UnixSubFolderIterator, IEnumIDList, iface);
2317         
2318     TRACE("(iface=%p)\n", iface);
2319
2320     if (This->m_dirFolder)
2321         rewinddir(This->m_dirFolder);
2322     
2323     return S_OK;
2324 }
2325
2326 static HRESULT WINAPI UnixSubFolderIterator_IEnumIDList_Clone(IEnumIDList* This, 
2327     IEnumIDList** ppenum)
2328 {
2329     FIXME("stub\n");
2330     return E_NOTIMPL;
2331 }
2332
2333 /* VTable for UnixSubFolderIterator's IEnumIDList interface.
2334  */
2335 static const IEnumIDListVtbl UnixSubFolderIterator_IEnumIDList_Vtbl = {
2336     UnixSubFolderIterator_IEnumIDList_QueryInterface,
2337     UnixSubFolderIterator_IEnumIDList_AddRef,
2338     UnixSubFolderIterator_IEnumIDList_Release,
2339     UnixSubFolderIterator_IEnumIDList_Next,
2340     UnixSubFolderIterator_IEnumIDList_Skip,
2341     UnixSubFolderIterator_IEnumIDList_Reset,
2342     UnixSubFolderIterator_IEnumIDList_Clone
2343 };
2344
2345 static IUnknown *UnixSubFolderIterator_Constructor(UnixFolder *pUnixFolder, SHCONTF fFilter) {
2346     UnixSubFolderIterator *iterator;
2347
2348     TRACE("(pUnixFolder=%p)\n", pUnixFolder);
2349     
2350     iterator = SHAlloc((ULONG)sizeof(UnixSubFolderIterator));
2351     iterator->lpIEnumIDListVtbl = &UnixSubFolderIterator_IEnumIDList_Vtbl;
2352     iterator->m_cRef = 0;
2353     iterator->m_fFilter = fFilter;
2354     iterator->m_dirFolder = opendir(pUnixFolder->m_pszPath);
2355     lstrcpyA(iterator->m_szFolder, pUnixFolder->m_pszPath);
2356
2357     UnixSubFolderIterator_IEnumIDList_AddRef((IEnumIDList*)iterator);
2358     
2359     return (IUnknown*)iterator;
2360 }