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