shell32: Update Bulgarian translation.
[wine] / dlls / shell32 / shlfileop.c
1 /*
2  * SHFileOperation
3  *
4  * Copyright 2000 Juergen Schmied
5  * Copyright 2002 Andriy Palamarchuk
6  * Copyright 2004 Dietrich Teickner (from Odin)
7  * Copyright 2004 Rolf Kalbermatter
8  *
9  * This library is free software; you can redistribute it and/or
10  * modify it under the terms of the GNU Lesser General Public
11  * License as published by the Free Software Foundation; either
12  * version 2.1 of the License, or (at your option) any later version.
13  *
14  * This library is distributed in the hope that it will be useful,
15  * but WITHOUT ANY WARRANTY; without even the implied warranty of
16  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
17  * Lesser General Public License for more details.
18  *
19  * You should have received a copy of the GNU Lesser General Public
20  * License along with this library; if not, write to the Free Software
21  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
22  */
23
24 #include "config.h"
25 #include "wine/port.h"
26
27 #include <stdarg.h>
28 #include <string.h>
29 #include <ctype.h>
30
31 #include "windef.h"
32 #include "winbase.h"
33 #include "winreg.h"
34 #include "shellapi.h"
35 #include "wingdi.h"
36 #include "winuser.h"
37 #include "shlobj.h"
38 #include "shresdef.h"
39 #define NO_SHLWAPI_STREAM
40 #include "shlwapi.h"
41 #include "shell32_main.h"
42 #include "undocshell.h"
43 #include "wine/unicode.h"
44 #include "wine/debug.h"
45
46 WINE_DEFAULT_DEBUG_CHANNEL(shell);
47
48 #define IsAttrib(x, y)  ((INVALID_FILE_ATTRIBUTES != (x)) && ((x) & (y)))
49 #define IsAttribFile(x) (!((x) & FILE_ATTRIBUTE_DIRECTORY))
50 #define IsAttribDir(x)  IsAttrib(x, FILE_ATTRIBUTE_DIRECTORY)
51 #define IsDotDir(x)     ((x[0] == '.') && ((x[1] == 0) || ((x[1] == '.') && (x[2] == 0))))
52
53 #define FO_MASK         0xF
54
55 static const WCHAR wWildcardFile[] = {'*',0};
56 static const WCHAR wWildcardChars[] = {'*','?',0};
57
58 static DWORD SHNotifyCreateDirectoryA(LPCSTR path, LPSECURITY_ATTRIBUTES sec);
59 static DWORD SHNotifyCreateDirectoryW(LPCWSTR path, LPSECURITY_ATTRIBUTES sec);
60 static DWORD SHNotifyRemoveDirectoryA(LPCSTR path);
61 static DWORD SHNotifyRemoveDirectoryW(LPCWSTR path);
62 static DWORD SHNotifyDeleteFileA(LPCSTR path);
63 static DWORD SHNotifyDeleteFileW(LPCWSTR path);
64 static DWORD SHNotifyMoveFileW(LPCWSTR src, LPCWSTR dest);
65 static DWORD SHNotifyCopyFileW(LPCWSTR src, LPCWSTR dest, BOOL bFailIfExists);
66 static DWORD SHFindAttrW(LPCWSTR pName, BOOL fileOnly);
67
68 typedef struct
69 {
70         HINSTANCE hIconInstance;
71         UINT icon_resource_id;
72         UINT caption_resource_id, text_resource_id;
73 } SHELL_ConfirmIDstruc;
74
75 static BOOL SHELL_ConfirmIDs(int nKindOfDialog, SHELL_ConfirmIDstruc *ids)
76 {
77         ids->hIconInstance = shell32_hInstance;
78         switch (nKindOfDialog) {
79           case ASK_DELETE_FILE:
80             ids->icon_resource_id = IDI_SHELL_CONFIRM_DELETE;
81             ids->caption_resource_id  = IDS_DELETEITEM_CAPTION;
82             ids->text_resource_id  = IDS_DELETEITEM_TEXT;
83             return TRUE;
84           case ASK_DELETE_FOLDER:
85             ids->icon_resource_id = IDI_SHELL_CONFIRM_DELETE;
86             ids->caption_resource_id  = IDS_DELETEFOLDER_CAPTION;
87             ids->text_resource_id  = IDS_DELETEITEM_TEXT;
88             return TRUE;
89           case ASK_DELETE_MULTIPLE_ITEM:
90             ids->icon_resource_id = IDI_SHELL_CONFIRM_DELETE;
91             ids->caption_resource_id  = IDS_DELETEITEM_CAPTION;
92             ids->text_resource_id  = IDS_DELETEMULTIPLE_TEXT;
93             return TRUE;
94           case ASK_DELETE_SELECTED:
95             ids->icon_resource_id = IDI_SHELL_CONFIRM_DELETE;
96             ids->caption_resource_id  = IDS_DELETEITEM_CAPTION;
97             ids->text_resource_id  = IDS_DELETESELECTED_TEXT;
98             return TRUE;
99           case ASK_OVERWRITE_FILE:
100             ids->hIconInstance = NULL;
101             ids->icon_resource_id = IDI_WARNING;
102             ids->caption_resource_id  = IDS_OVERWRITEFILE_CAPTION;
103             ids->text_resource_id  = IDS_OVERWRITEFILE_TEXT;
104             return TRUE;
105           default:
106             FIXME(" Unhandled nKindOfDialog %d stub\n", nKindOfDialog);
107         }
108         return FALSE;
109 }
110
111 BOOL SHELL_ConfirmDialogW(HWND hWnd, int nKindOfDialog, LPCWSTR szDir)
112 {
113         WCHAR szCaption[255], szText[255], szBuffer[MAX_PATH + 256];
114         SHELL_ConfirmIDstruc ids;
115         MSGBOXPARAMSW params;
116
117         if (!SHELL_ConfirmIDs(nKindOfDialog, &ids))
118           return FALSE;
119
120         LoadStringW(shell32_hInstance, ids.caption_resource_id, szCaption, sizeof(szCaption)/sizeof(WCHAR));
121         LoadStringW(shell32_hInstance, ids.text_resource_id, szText, sizeof(szText)/sizeof(WCHAR));
122
123         FormatMessageW(FORMAT_MESSAGE_FROM_STRING|FORMAT_MESSAGE_ARGUMENT_ARRAY,
124                        szText, 0, 0, szBuffer, sizeof(szBuffer), (va_list*)&szDir);
125
126         ZeroMemory(&params, sizeof(params));
127         params.cbSize = sizeof(MSGBOXPARAMSW);
128         params.hwndOwner = hWnd;
129         params.hInstance = ids.hIconInstance;
130         params.lpszText = szBuffer;
131         params.lpszCaption = szCaption;
132         params.lpszIcon = (LPWSTR)MAKEINTRESOURCE(ids.icon_resource_id);
133         params.dwStyle = MB_OKCANCEL | MB_USERICON;
134
135         return (IDOK == MessageBoxIndirectW(&params));
136 }
137
138 static DWORD SHELL32_AnsiToUnicodeBuf(LPCSTR aPath, LPWSTR *wPath, DWORD minChars)
139 {
140         DWORD len = MultiByteToWideChar(CP_ACP, 0, aPath, -1, NULL, 0);
141
142         if (len < minChars)
143           len = minChars;
144
145         *wPath = HeapAlloc(GetProcessHeap(), 0, len * sizeof(WCHAR));
146         if (*wPath)
147         {
148           MultiByteToWideChar(CP_ACP, 0, aPath, -1, *wPath, len);
149           return NO_ERROR;
150         }
151         return E_OUTOFMEMORY;
152 }
153
154 static void SHELL32_FreeUnicodeBuf(LPWSTR wPath)
155 {
156         HeapFree(GetProcessHeap(), 0, wPath);
157 }
158
159 HRESULT WINAPI SHIsFileAvailableOffline(LPCWSTR path, LPDWORD status)
160 {
161     FIXME("(%s, %p) stub\n", debugstr_w(path), status);
162     return E_FAIL;
163 }
164
165 /**************************************************************************
166  * SHELL_DeleteDirectory()  [internal]
167  *
168  * Asks for confirmation when bShowUI is true and deletes the directory and
169  * all its subdirectories and files if necessary.
170  */
171 BOOL SHELL_DeleteDirectoryW(HWND hwnd, LPCWSTR pszDir, BOOL bShowUI)
172 {
173         BOOL    ret = TRUE;
174         HANDLE  hFind;
175         WIN32_FIND_DATAW wfd;
176         WCHAR   szTemp[MAX_PATH];
177
178         /* Make sure the directory exists before eventually prompting the user */
179         PathCombineW(szTemp, pszDir, wWildcardFile);
180         hFind = FindFirstFileW(szTemp, &wfd);
181         if (hFind == INVALID_HANDLE_VALUE)
182           return FALSE;
183
184         if (!bShowUI || (ret = SHELL_ConfirmDialogW(hwnd, ASK_DELETE_FOLDER, pszDir)))
185         {
186           do
187           {
188             LPWSTR lp = wfd.cAlternateFileName;
189             if (!lp[0])
190               lp = wfd.cFileName;
191             if (IsDotDir(lp))
192               continue;
193             PathCombineW(szTemp, pszDir, lp);
194             if (FILE_ATTRIBUTE_DIRECTORY & wfd.dwFileAttributes)
195               ret = SHELL_DeleteDirectoryW(hwnd, szTemp, FALSE);
196             else
197               ret = (SHNotifyDeleteFileW(szTemp) == ERROR_SUCCESS);
198           } while (ret && FindNextFileW(hFind, &wfd));
199         }
200         FindClose(hFind);
201         if (ret)
202           ret = (SHNotifyRemoveDirectoryW(pszDir) == ERROR_SUCCESS);
203         return ret;
204 }
205
206 /**************************************************************************
207  * Win32CreateDirectory      [SHELL32.93]
208  *
209  * Creates a directory. Also triggers a change notify if one exists.
210  *
211  * PARAMS
212  *  path       [I]   path to directory to create
213  *
214  * RETURNS
215  *  TRUE if successful, FALSE otherwise
216  *
217  * NOTES
218  *  Verified on Win98 / IE 5 (SHELL32 4.72, March 1999 build) to be ANSI.
219  *  This is Unicode on NT/2000
220  */
221 static DWORD SHNotifyCreateDirectoryA(LPCSTR path, LPSECURITY_ATTRIBUTES sec)
222 {
223         LPWSTR wPath;
224         DWORD retCode;
225
226         TRACE("(%s, %p)\n", debugstr_a(path), sec);
227
228         retCode = SHELL32_AnsiToUnicodeBuf(path, &wPath, 0);
229         if (!retCode)
230         {
231           retCode = SHNotifyCreateDirectoryW(wPath, sec);
232           SHELL32_FreeUnicodeBuf(wPath);
233         }
234         return retCode;
235 }
236
237 /**********************************************************************/
238
239 static DWORD SHNotifyCreateDirectoryW(LPCWSTR path, LPSECURITY_ATTRIBUTES sec)
240 {
241         TRACE("(%s, %p)\n", debugstr_w(path), sec);
242
243         if (CreateDirectoryW(path, sec))
244         {
245           SHChangeNotify(SHCNE_MKDIR, SHCNF_PATHW, path, NULL);
246           return ERROR_SUCCESS;
247         }
248         return GetLastError();
249 }
250
251 /**********************************************************************/
252
253 BOOL WINAPI Win32CreateDirectoryAW(LPCVOID path, LPSECURITY_ATTRIBUTES sec)
254 {
255         if (SHELL_OsIsUnicode())
256           return (SHNotifyCreateDirectoryW(path, sec) == ERROR_SUCCESS);
257         return (SHNotifyCreateDirectoryA(path, sec) == ERROR_SUCCESS);
258 }
259
260 /************************************************************************
261  * Win32RemoveDirectory      [SHELL32.94]
262  *
263  * Deletes a directory. Also triggers a change notify if one exists.
264  *
265  * PARAMS
266  *  path       [I]   path to directory to delete
267  *
268  * RETURNS
269  *  TRUE if successful, FALSE otherwise
270  *
271  * NOTES
272  *  Verified on Win98 / IE 5 (SHELL32 4.72, March 1999 build) to be ANSI.
273  *  This is Unicode on NT/2000
274  */
275 static DWORD SHNotifyRemoveDirectoryA(LPCSTR path)
276 {
277         LPWSTR wPath;
278         DWORD retCode;
279
280         TRACE("(%s)\n", debugstr_a(path));
281
282         retCode = SHELL32_AnsiToUnicodeBuf(path, &wPath, 0);
283         if (!retCode)
284         {
285           retCode = SHNotifyRemoveDirectoryW(wPath);
286           SHELL32_FreeUnicodeBuf(wPath);
287         }
288         return retCode;
289 }
290
291 /***********************************************************************/
292
293 static DWORD SHNotifyRemoveDirectoryW(LPCWSTR path)
294 {
295         BOOL ret;
296         TRACE("(%s)\n", debugstr_w(path));
297
298         ret = RemoveDirectoryW(path);
299         if (!ret)
300         {
301           /* Directory may be write protected */
302           DWORD dwAttr = GetFileAttributesW(path);
303           if (IsAttrib(dwAttr, FILE_ATTRIBUTE_READONLY))
304             if (SetFileAttributesW(path, dwAttr & ~FILE_ATTRIBUTE_READONLY))
305               ret = RemoveDirectoryW(path);
306         }
307         if (ret)
308         {
309           SHChangeNotify(SHCNE_RMDIR, SHCNF_PATHW, path, NULL);
310           return ERROR_SUCCESS;
311         }
312         return GetLastError();
313 }
314
315 /***********************************************************************/
316
317 BOOL WINAPI Win32RemoveDirectoryAW(LPCVOID path)
318 {
319         if (SHELL_OsIsUnicode())
320           return (SHNotifyRemoveDirectoryW(path) == ERROR_SUCCESS);
321         return (SHNotifyRemoveDirectoryA(path) == ERROR_SUCCESS);
322 }
323
324 /************************************************************************
325  * Win32DeleteFile           [SHELL32.164]
326  *
327  * Deletes a file. Also triggers a change notify if one exists.
328  *
329  * PARAMS
330  *  path       [I]   path to file to delete
331  *
332  * RETURNS
333  *  TRUE if successful, FALSE otherwise
334  *
335  * NOTES
336  *  Verified on Win98 / IE 5 (SHELL32 4.72, March 1999 build) to be ANSI.
337  *  This is Unicode on NT/2000
338  */
339 static DWORD SHNotifyDeleteFileA(LPCSTR path)
340 {
341         LPWSTR wPath;
342         DWORD retCode;
343
344         TRACE("(%s)\n", debugstr_a(path));
345
346         retCode = SHELL32_AnsiToUnicodeBuf(path, &wPath, 0);
347         if (!retCode)
348         {
349           retCode = SHNotifyDeleteFileW(wPath);
350           SHELL32_FreeUnicodeBuf(wPath);
351         }
352         return retCode;
353 }
354
355 /***********************************************************************/
356
357 static DWORD SHNotifyDeleteFileW(LPCWSTR path)
358 {
359         BOOL ret;
360
361         TRACE("(%s)\n", debugstr_w(path));
362
363         ret = DeleteFileW(path);
364         if (!ret)
365         {
366           /* File may be write protected or a system file */
367           DWORD dwAttr = GetFileAttributesW(path);
368           if (IsAttrib(dwAttr, FILE_ATTRIBUTE_READONLY | FILE_ATTRIBUTE_SYSTEM))
369             if (SetFileAttributesW(path, dwAttr & ~(FILE_ATTRIBUTE_READONLY | FILE_ATTRIBUTE_SYSTEM)))
370               ret = DeleteFileW(path);
371         }
372         if (ret)
373         {
374           SHChangeNotify(SHCNE_DELETE, SHCNF_PATHW, path, NULL);
375           return ERROR_SUCCESS;
376         }
377         return GetLastError();
378 }
379
380 /***********************************************************************/
381
382 DWORD WINAPI Win32DeleteFileAW(LPCVOID path)
383 {
384         if (SHELL_OsIsUnicode())
385           return (SHNotifyDeleteFileW(path) == ERROR_SUCCESS);
386         return (SHNotifyDeleteFileA(path) == ERROR_SUCCESS);
387 }
388
389 /************************************************************************
390  * SHNotifyMoveFile          [internal]
391  *
392  * Moves a file. Also triggers a change notify if one exists.
393  *
394  * PARAMS
395  *  src        [I]   path to source file to move
396  *  dest       [I]   path to target file to move to
397  *
398  * RETURNS
399  *  ERORR_SUCCESS if successful
400  */
401 static DWORD SHNotifyMoveFileW(LPCWSTR src, LPCWSTR dest)
402 {
403         BOOL ret;
404
405         TRACE("(%s %s)\n", debugstr_w(src), debugstr_w(dest));
406
407         ret = MoveFileExW(src, dest, MOVEFILE_REPLACE_EXISTING);
408
409         /* MOVEFILE_REPLACE_EXISTING fails with dirs, so try MoveFile */
410         if (!ret)
411             ret = MoveFileW(src, dest);
412
413         if (!ret)
414         {
415           DWORD dwAttr;
416
417           dwAttr = SHFindAttrW(dest, FALSE);
418           if (INVALID_FILE_ATTRIBUTES == dwAttr)
419           {
420             /* Source file may be write protected or a system file */
421             dwAttr = GetFileAttributesW(src);
422             if (IsAttrib(dwAttr, FILE_ATTRIBUTE_READONLY | FILE_ATTRIBUTE_SYSTEM))
423               if (SetFileAttributesW(src, dwAttr & ~(FILE_ATTRIBUTE_READONLY | FILE_ATTRIBUTE_SYSTEM)))
424                 ret = MoveFileW(src, dest);
425           }
426         }
427         if (ret)
428         {
429           SHChangeNotify(SHCNE_RENAMEITEM, SHCNF_PATHW, src, dest);
430           return ERROR_SUCCESS;
431         }
432         return GetLastError();
433 }
434
435 /************************************************************************
436  * SHNotifyCopyFile          [internal]
437  *
438  * Copies a file. Also triggers a change notify if one exists.
439  *
440  * PARAMS
441  *  src           [I]   path to source file to move
442  *  dest          [I]   path to target file to move to
443  *  bFailIfExists [I]   if TRUE, the target file will not be overwritten if
444  *                      a file with this name already exists
445  *
446  * RETURNS
447  *  ERROR_SUCCESS if successful
448  */
449 static DWORD SHNotifyCopyFileW(LPCWSTR src, LPCWSTR dest, BOOL bFailIfExists)
450 {
451         BOOL ret;
452
453         TRACE("(%s %s %s)\n", debugstr_w(src), debugstr_w(dest), bFailIfExists ? "failIfExists" : "");
454
455         ret = CopyFileW(src, dest, bFailIfExists);
456         if (ret)
457         {
458           SHChangeNotify(SHCNE_CREATE, SHCNF_PATHW, dest, NULL);
459           return ERROR_SUCCESS;
460         }
461
462         return GetLastError();
463 }
464
465 /*************************************************************************
466  * SHCreateDirectory         [SHELL32.165]
467  *
468  * This function creates a file system folder whose fully qualified path is
469  * given by path. If one or more of the intermediate folders do not exist,
470  * they will be created as well.
471  *
472  * PARAMS
473  *  hWnd       [I]
474  *  path       [I]   path of directory to create
475  *
476  * RETURNS
477  *  ERRROR_SUCCESS or one of the following values:
478  *  ERROR_BAD_PATHNAME if the path is relative
479  *  ERROR_FILE_EXISTS when a file with that name exists
480  *  ERROR_PATH_NOT_FOUND can't find the path, probably invalid
481  *  ERROR_INVLID_NAME if the path contains invalid chars
482  *  ERROR_ALREADY_EXISTS when the directory already exists
483  *  ERROR_FILENAME_EXCED_RANGE if the filename was to long to process
484  *
485  * NOTES
486  *  exported by ordinal
487  *  Win9x exports ANSI
488  *  WinNT/2000 exports Unicode
489  */
490 DWORD WINAPI SHCreateDirectory(HWND hWnd, LPCVOID path)
491 {
492         if (SHELL_OsIsUnicode())
493           return SHCreateDirectoryExW(hWnd, path, NULL);
494         return SHCreateDirectoryExA(hWnd, path, NULL);
495 }
496
497 /*************************************************************************
498  * SHCreateDirectoryExA      [SHELL32.@]
499  *
500  * This function creates a file system folder whose fully qualified path is
501  * given by path. If one or more of the intermediate folders do not exist,
502  * they will be created as well.
503  *
504  * PARAMS
505  *  hWnd       [I]
506  *  path       [I]   path of directory to create
507  *  sec        [I]   security attributes to use or NULL
508  *
509  * RETURNS
510  *  ERRROR_SUCCESS or one of the following values:
511  *  ERROR_BAD_PATHNAME or ERROR_PATH_NOT_FOUND if the path is relative
512  *  ERROR_INVLID_NAME if the path contains invalid chars
513  *  ERROR_FILE_EXISTS when a file with that name exists
514  *  ERROR_ALREADY_EXISTS when the directory already exists
515  *  ERROR_FILENAME_EXCED_RANGE if the filename was to long to process
516  *
517  *  FIXME: Not implemented yet;
518  *  SHCreateDirectoryEx also verifies that the files in the directory will be visible
519  *  if the path is a network path to deal with network drivers which might have a limited
520  *  but unknown maximum path length. If not:
521  *
522  *  If hWnd is set to a valid window handle, a message box is displayed warning
523  *  the user that the files may not be accessible. If the user chooses not to
524  *  proceed, the function returns ERROR_CANCELLED.
525  *
526  *  If hWnd is set to NULL, no user interface is displayed and the function
527  *  returns ERROR_CANCELLED.
528  */
529 int WINAPI SHCreateDirectoryExA(HWND hWnd, LPCSTR path, LPSECURITY_ATTRIBUTES sec)
530 {
531         LPWSTR wPath;
532         DWORD retCode;
533
534         TRACE("(%s, %p)\n", debugstr_a(path), sec);
535
536         retCode = SHELL32_AnsiToUnicodeBuf(path, &wPath, 0);
537         if (!retCode)
538         {
539           retCode = SHCreateDirectoryExW(hWnd, wPath, sec);
540           SHELL32_FreeUnicodeBuf(wPath);
541         }
542         return retCode;
543 }
544
545 /*************************************************************************
546  * SHCreateDirectoryExW      [SHELL32.@]
547  *
548  * See SHCreateDirectoryExA.
549  */
550 int WINAPI SHCreateDirectoryExW(HWND hWnd, LPCWSTR path, LPSECURITY_ATTRIBUTES sec)
551 {
552         int ret = ERROR_BAD_PATHNAME;
553         TRACE("(%p, %s, %p)\n", hWnd, debugstr_w(path), sec);
554
555         if (PathIsRelativeW(path))
556         {
557           SetLastError(ret);
558         }
559         else
560         {
561           ret = SHNotifyCreateDirectoryW(path, sec);
562           /* Refuse to work on certain error codes before trying to create directories recursively */
563           if (ret != ERROR_SUCCESS &&
564               ret != ERROR_FILE_EXISTS &&
565               ret != ERROR_ALREADY_EXISTS &&
566               ret != ERROR_FILENAME_EXCED_RANGE)
567           {
568             WCHAR *pEnd, *pSlash, szTemp[MAX_PATH + 1];  /* extra for PathAddBackslash() */
569
570             lstrcpynW(szTemp, path, MAX_PATH);
571             pEnd = PathAddBackslashW(szTemp);
572             pSlash = szTemp + 3;
573
574             while (*pSlash)
575             {
576               while (*pSlash && *pSlash != '\\')
577                 pSlash = CharNextW(pSlash);
578
579               if (*pSlash)
580               {
581                 *pSlash = 0;    /* terminate path at separator */
582
583                 ret = SHNotifyCreateDirectoryW(szTemp, pSlash + 1 == pEnd ? sec : NULL);
584               }
585               *pSlash++ = '\\'; /* put the separator back */
586             }
587           }
588
589           if (ret && hWnd && (ERROR_CANCELLED != ret))
590           {
591             /* We failed and should show a dialog box */
592             FIXME("Show system error message, creating path %s, failed with error %d\n", debugstr_w(path), ret);
593             ret = ERROR_CANCELLED; /* Error has been already presented to user (not really yet!) */
594           }
595         }
596         return ret;
597 }
598
599 /*************************************************************************
600  * SHFindAttrW      [internal]
601  *
602  * Get the Attributes for a file or directory. The difference to GetAttributes()
603  * is that this function will also work for paths containing wildcard characters
604  * in its filename.
605
606  * PARAMS
607  *  path       [I]   path of directory or file to check
608  *  fileOnly   [I]   TRUE if only files should be found
609  *
610  * RETURNS
611  *  INVALID_FILE_ATTRIBUTES if the path does not exist, the actual attributes of
612  *  the first file or directory found otherwise
613  */
614 static DWORD SHFindAttrW(LPCWSTR pName, BOOL fileOnly)
615 {
616         WIN32_FIND_DATAW wfd;
617         BOOL b_FileMask = fileOnly && (NULL != StrPBrkW(pName, wWildcardChars));
618         DWORD dwAttr = INVALID_FILE_ATTRIBUTES;
619         HANDLE hFind = FindFirstFileW(pName, &wfd);
620
621         TRACE("%s %d\n", debugstr_w(pName), fileOnly);
622         if (INVALID_HANDLE_VALUE != hFind)
623         {
624           do
625           {
626             if (b_FileMask && IsAttribDir(wfd.dwFileAttributes))
627                continue;
628             dwAttr = wfd.dwFileAttributes;
629             break;
630           }
631           while (FindNextFileW(hFind, &wfd));
632           FindClose(hFind);
633         }
634         return dwAttr;
635 }
636
637 /*************************************************************************
638  *
639  * SHNameTranslate HelperFunction for SHFileOperationA
640  *
641  * Translates a list of 0 terminated ASCII strings into Unicode. If *wString
642  * is NULL, only the necessary size of the string is determined and returned,
643  * otherwise the ASCII strings are copied into it and the buffer is increased
644  * to point to the location after the final 0 termination char.
645  */
646 DWORD SHNameTranslate(LPWSTR* wString, LPCWSTR* pWToFrom, BOOL more)
647 {
648         DWORD size = 0, aSize = 0;
649         LPCSTR aString = (LPCSTR)*pWToFrom;
650
651         if (aString)
652         {
653           do
654           {
655             size = lstrlenA(aString) + 1;
656             aSize += size;
657             aString += size;
658           } while ((size != 1) && more);
659           /* The two sizes might be different in the case of multibyte chars */
660           size = MultiByteToWideChar(CP_ACP, 0, aString, aSize, *wString, 0);
661           if (*wString) /* only in the second loop */
662           {
663             MultiByteToWideChar(CP_ACP, 0, (LPCSTR)*pWToFrom, aSize, *wString, size);
664             *pWToFrom = *wString;
665             *wString += size;
666           }
667         }
668         return size;
669 }
670 /*************************************************************************
671  * SHFileOperationA          [SHELL32.@]
672  *
673  * Function to copy, move, delete and create one or more files with optional
674  * user prompts.
675  *
676  * PARAMS
677  *  lpFileOp   [I/O] pointer to a structure containing all the necessary information
678  *
679  * RETURNS
680  *  Success: ERROR_SUCCESS.
681  *  Failure: ERROR_CANCELLED.
682  *
683  * NOTES
684  *  exported by name
685  */
686 int WINAPI SHFileOperationA(LPSHFILEOPSTRUCTA lpFileOp)
687 {
688         SHFILEOPSTRUCTW nFileOp = *((LPSHFILEOPSTRUCTW)lpFileOp);
689         int retCode = 0;
690         DWORD size;
691         LPWSTR ForFree = NULL, /* we change wString in SHNameTranslate and can't use it for freeing */
692                wString = NULL; /* we change this in SHNameTranslate */
693
694         TRACE("\n");
695         if (FO_DELETE == (nFileOp.wFunc & FO_MASK))
696           nFileOp.pTo = NULL; /* we need a NULL or a valid pointer for translation */
697         if (!(nFileOp.fFlags & FOF_SIMPLEPROGRESS))
698           nFileOp.lpszProgressTitle = NULL; /* we need a NULL or a valid pointer for translation */
699         while (1) /* every loop calculate size, second translate also, if we have storage for this */
700         {
701           size = SHNameTranslate(&wString, &nFileOp.lpszProgressTitle, FALSE); /* no loop */
702           size += SHNameTranslate(&wString, &nFileOp.pFrom, TRUE); /* internal loop */
703           size += SHNameTranslate(&wString, &nFileOp.pTo, TRUE); /* internal loop */
704
705           if (ForFree)
706           {
707             retCode = SHFileOperationW(&nFileOp);
708             HeapFree(GetProcessHeap(), 0, ForFree); /* we cannot use wString, it was changed */
709             break;
710           }
711           else
712           {
713             wString = ForFree = HeapAlloc(GetProcessHeap(), 0, size * sizeof(WCHAR));
714             if (ForFree) continue;
715             retCode = ERROR_OUTOFMEMORY;
716             nFileOp.fAnyOperationsAborted = TRUE;
717             SetLastError(retCode);
718             return retCode;
719           }
720         }
721
722         lpFileOp->hNameMappings = nFileOp.hNameMappings;
723         lpFileOp->fAnyOperationsAborted = nFileOp.fAnyOperationsAborted;
724         return retCode;
725 }
726
727 #define ERROR_SHELL_INTERNAL_FILE_NOT_FOUND 1026
728
729 typedef struct
730 {
731     DWORD attributes;
732     LPWSTR szDirectory;
733     LPWSTR szFilename;
734     LPWSTR szFullPath;
735     BOOL bFromWildcard;
736     BOOL bFromRelative;
737     BOOL bExists;
738 } FILE_ENTRY;
739
740 typedef struct
741 {
742     FILE_ENTRY *feFiles;
743     DWORD num_alloc;
744     DWORD dwNumFiles;
745     BOOL bAnyFromWildcard;
746     BOOL bAnyDirectories;
747     BOOL bAnyDontExist;
748 } FILE_LIST;
749
750
751 static inline void grow_list(FILE_LIST *list)
752 {
753     FILE_ENTRY *new = HeapReAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, list->feFiles,
754                                   list->num_alloc * 2 * sizeof(*new) );
755     list->feFiles = new;
756     list->num_alloc *= 2;
757 }
758
759 /* adds a file to the FILE_ENTRY struct
760  */
761 static void add_file_to_entry(FILE_ENTRY *feFile, LPWSTR szFile)
762 {
763     DWORD dwLen = strlenW(szFile) + 1;
764     LPWSTR ptr;
765
766     feFile->szFullPath = HeapAlloc(GetProcessHeap(), 0, dwLen * sizeof(WCHAR));
767     strcpyW(feFile->szFullPath, szFile);
768
769     ptr = StrRChrW(szFile, NULL, '\\');
770     if (ptr)
771     {
772         dwLen = ptr - szFile + 1;
773         feFile->szDirectory = HeapAlloc(GetProcessHeap(), 0, dwLen * sizeof(WCHAR));
774         lstrcpynW(feFile->szDirectory, szFile, dwLen);
775
776         dwLen = strlenW(feFile->szFullPath) - dwLen + 1;
777         feFile->szFilename = HeapAlloc(GetProcessHeap(), 0, dwLen * sizeof(WCHAR));
778         strcpyW(feFile->szFilename, ptr + 1); /* skip over backslash */
779     }
780     feFile->bFromWildcard = FALSE;
781 }
782
783 static LPWSTR wildcard_to_file(LPWSTR szWildCard, LPWSTR szFileName)
784 {
785     LPWSTR szFullPath, ptr;
786     DWORD dwDirLen, dwFullLen;
787
788     ptr = StrRChrW(szWildCard, NULL, '\\');
789     dwDirLen = ptr - szWildCard + 1;
790
791     dwFullLen = dwDirLen + strlenW(szFileName) + 1;
792     szFullPath = HeapAlloc(GetProcessHeap(), 0, dwFullLen * sizeof(WCHAR));
793
794     lstrcpynW(szFullPath, szWildCard, dwDirLen + 1);
795     strcatW(szFullPath, szFileName);
796
797     return szFullPath;
798 }
799
800 static void parse_wildcard_files(FILE_LIST *flList, LPWSTR szFile, LPDWORD pdwListIndex)
801 {
802     WIN32_FIND_DATAW wfd;
803     HANDLE hFile = FindFirstFileW(szFile, &wfd);
804     FILE_ENTRY *file;
805     LPWSTR szFullPath;
806     BOOL res;
807
808     for (res = TRUE; res; res = FindNextFileW(hFile, &wfd))
809     {
810         if (IsDotDir(wfd.cFileName)) continue;
811         if (*pdwListIndex >= flList->num_alloc) grow_list( flList );
812         szFullPath = wildcard_to_file(szFile, wfd.cFileName);
813         file = &flList->feFiles[(*pdwListIndex)++];
814         add_file_to_entry(file, szFullPath);
815         file->bFromWildcard = TRUE;
816         file->attributes = wfd.dwFileAttributes;
817         if (IsAttribDir(file->attributes)) flList->bAnyDirectories = TRUE;
818         HeapFree(GetProcessHeap(), 0, szFullPath);
819     }
820
821     FindClose(hFile);
822 }
823
824 /* takes the null-separated file list and fills out the FILE_LIST */
825 static HRESULT parse_file_list(FILE_LIST *flList, LPCWSTR szFiles)
826 {
827     LPCWSTR ptr = szFiles;
828     WCHAR szCurFile[MAX_PATH];
829     DWORD i = 0, dwDirLen;
830
831     if (!szFiles)
832         return ERROR_INVALID_PARAMETER;
833
834     flList->bAnyFromWildcard = FALSE;
835     flList->bAnyDirectories = FALSE;
836     flList->bAnyDontExist = FALSE;
837     flList->num_alloc = 32;
838     flList->dwNumFiles = 0;
839
840     /* empty list */
841     if (!szFiles[0])
842         return ERROR_ACCESS_DENIED;
843         
844     flList->feFiles = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY,
845                                 flList->num_alloc * sizeof(FILE_ENTRY));
846
847     while (*ptr)
848     {
849         if (i >= flList->num_alloc) grow_list( flList );
850
851         /* change relative to absolute path */
852         if (PathIsRelativeW(ptr))
853         {
854             dwDirLen = GetCurrentDirectoryW(MAX_PATH, szCurFile) + 1;
855             PathCombineW(szCurFile, szCurFile, ptr);
856             flList->feFiles[i].bFromRelative = TRUE;
857         }
858         else
859         {
860             strcpyW(szCurFile, ptr);
861             flList->feFiles[i].bFromRelative = FALSE;
862         }
863
864         /* parse wildcard files if they are in the filename */
865         if (StrPBrkW(szCurFile, wWildcardChars))
866         {
867             parse_wildcard_files(flList, szCurFile, &i);
868             flList->bAnyFromWildcard = TRUE;
869             i--;
870         }
871         else
872         {
873             FILE_ENTRY *file = &flList->feFiles[i];
874             add_file_to_entry(file, szCurFile);
875             file->attributes = GetFileAttributesW( file->szFullPath );
876             file->bExists = (file->attributes != INVALID_FILE_ATTRIBUTES);
877             if (!file->bExists) flList->bAnyDontExist = TRUE;
878             if (IsAttribDir(file->attributes)) flList->bAnyDirectories = TRUE;
879         }
880
881         /* advance to the next string */
882         ptr += strlenW(ptr) + 1;
883         i++;
884     }
885     flList->dwNumFiles = i;
886
887     return S_OK;
888 }
889
890 /* free the FILE_LIST */
891 static void destroy_file_list(FILE_LIST *flList)
892 {
893     DWORD i;
894
895     if (!flList || !flList->feFiles)
896         return;
897
898     for (i = 0; i < flList->dwNumFiles; i++)
899     {
900         HeapFree(GetProcessHeap(), 0, flList->feFiles[i].szDirectory);
901         HeapFree(GetProcessHeap(), 0, flList->feFiles[i].szFilename);
902         HeapFree(GetProcessHeap(), 0, flList->feFiles[i].szFullPath);
903     }
904
905     HeapFree(GetProcessHeap(), 0, flList->feFiles);
906 }
907
908 static void copy_dir_to_dir(LPSHFILEOPSTRUCTW lpFileOp, FILE_ENTRY *feFrom, LPWSTR szDestPath)
909 {
910     WCHAR szFrom[MAX_PATH], szTo[MAX_PATH];
911     SHFILEOPSTRUCTW fileOp;
912
913     static const WCHAR wildCardFiles[] = {'*','.','*',0};
914
915     if (IsDotDir(feFrom->szFilename))
916         return;
917
918     if (PathFileExistsW(szDestPath))
919         PathCombineW(szTo, szDestPath, feFrom->szFilename);
920     else
921         strcpyW(szTo, szDestPath);
922
923     szTo[strlenW(szTo) + 1] = '\0';
924     SHNotifyCreateDirectoryW(szTo, NULL);
925
926     PathCombineW(szFrom, feFrom->szFullPath, wildCardFiles);
927     szFrom[strlenW(szFrom) + 1] = '\0';
928
929     memcpy(&fileOp, lpFileOp, sizeof(fileOp));
930     fileOp.pFrom = szFrom;
931     fileOp.pTo = szTo;
932     fileOp.fFlags &= ~FOF_MULTIDESTFILES; /* we know we're copying to one dir */
933
934     SHFileOperationW(&fileOp);
935 }
936
937 /* copy a file or directory to another directory */
938 static void copy_to_dir(LPSHFILEOPSTRUCTW lpFileOp, FILE_ENTRY *feFrom, FILE_ENTRY *feTo)
939 {
940     WCHAR szDestPath[MAX_PATH];
941
942     if (!PathFileExistsW(feTo->szFullPath))
943         SHNotifyCreateDirectoryW(feTo->szFullPath, NULL);
944
945     PathCombineW(szDestPath, feTo->szFullPath, feFrom->szFilename);
946
947     if (IsAttribFile(feFrom->attributes))
948         SHNotifyCopyFileW(feFrom->szFullPath, szDestPath, FALSE);
949     else if (!(lpFileOp->fFlags & FOF_FILESONLY && feFrom->bFromWildcard))
950         copy_dir_to_dir(lpFileOp, feFrom, szDestPath);
951 }
952
953 static void create_dest_dirs(LPWSTR szDestDir)
954 {
955     WCHAR dir[MAX_PATH];
956     LPWSTR ptr = StrChrW(szDestDir, '\\');
957
958     /* make sure all directories up to last one are created */
959     while (ptr && (ptr = StrChrW(ptr + 1, '\\')))
960     {
961         lstrcpynW(dir, szDestDir, ptr - szDestDir + 1);
962
963         if (!PathFileExistsW(dir))
964             SHNotifyCreateDirectoryW(dir, NULL);
965     }
966
967     /* create last directory */
968     if (!PathFileExistsW(szDestDir))
969         SHNotifyCreateDirectoryW(szDestDir, NULL);
970 }
971
972 /* the FO_COPY operation */
973 static HRESULT copy_files(LPSHFILEOPSTRUCTW lpFileOp, FILE_LIST *flFrom, FILE_LIST *flTo)
974 {
975     DWORD i;
976     FILE_ENTRY *entryToCopy;
977     FILE_ENTRY *fileDest = &flTo->feFiles[0];
978     BOOL bCancelIfAnyDirectories = FALSE;
979
980     if (flFrom->bAnyDontExist)
981         return ERROR_SHELL_INTERNAL_FILE_NOT_FOUND;
982
983     if (lpFileOp->fFlags & FOF_MULTIDESTFILES && flFrom->bAnyFromWildcard)
984         return ERROR_CANCELLED;
985
986     if (!(lpFileOp->fFlags & FOF_MULTIDESTFILES) && flTo->dwNumFiles != 1)
987         return ERROR_CANCELLED;
988
989     if (lpFileOp->fFlags & FOF_MULTIDESTFILES && flFrom->dwNumFiles != 1 &&
990         flFrom->dwNumFiles != flTo->dwNumFiles)
991     {
992         return ERROR_CANCELLED;
993     }
994
995     if (flFrom->dwNumFiles > 1 && flTo->dwNumFiles == 1 &&
996         !PathFileExistsW(flTo->feFiles[0].szFullPath) &&
997         IsAttribFile(fileDest->attributes))
998     {
999         bCancelIfAnyDirectories = TRUE;
1000     }
1001
1002     if (flFrom->dwNumFiles > 1 && flTo->dwNumFiles == 1 && fileDest->bFromRelative &&
1003         !PathFileExistsW(fileDest->szFullPath))
1004     {
1005         lpFileOp->fAnyOperationsAborted = TRUE;
1006         return ERROR_CANCELLED;
1007     }
1008
1009     if (!(lpFileOp->fFlags & FOF_MULTIDESTFILES) && flFrom->dwNumFiles != 1 &&
1010         PathFileExistsW(fileDest->szFullPath) &&
1011         IsAttribFile(fileDest->attributes))
1012     {
1013         return ERROR_CANCELLED;
1014     }
1015
1016     for (i = 0; i < flFrom->dwNumFiles; i++)
1017     {
1018         entryToCopy = &flFrom->feFiles[i];
1019
1020         if (lpFileOp->fFlags & FOF_MULTIDESTFILES)
1021             fileDest = &flTo->feFiles[i];
1022
1023         if (IsAttribDir(entryToCopy->attributes) &&
1024             !lstrcmpW(entryToCopy->szFullPath, fileDest->szDirectory))
1025         {
1026             return ERROR_SUCCESS;
1027         }
1028
1029         if (IsAttribDir(entryToCopy->attributes) && bCancelIfAnyDirectories)
1030             return ERROR_CANCELLED;
1031
1032         create_dest_dirs(fileDest->szDirectory);
1033
1034         if (!strcmpW(entryToCopy->szFullPath, fileDest->szFullPath))
1035         {
1036             if (IsAttribFile(entryToCopy->attributes))
1037                 return ERROR_NO_MORE_SEARCH_HANDLES;
1038             else
1039                 return ERROR_SUCCESS;
1040         }
1041
1042         if ((flFrom->dwNumFiles > 1 && flTo->dwNumFiles == 1) ||
1043             (flFrom->dwNumFiles == 1 && IsAttribDir(fileDest->attributes)))
1044         {
1045             copy_to_dir(lpFileOp, entryToCopy, fileDest);
1046         }
1047         else if (IsAttribDir(entryToCopy->attributes))
1048         {
1049             copy_dir_to_dir(lpFileOp, entryToCopy, fileDest->szFullPath);
1050         }
1051         else
1052         {
1053             if (SHNotifyCopyFileW(entryToCopy->szFullPath, fileDest->szFullPath, TRUE))
1054             {
1055                 lpFileOp->fAnyOperationsAborted = TRUE;
1056                 return ERROR_CANCELLED;
1057             }
1058         }
1059     }
1060
1061     return ERROR_SUCCESS;
1062 }
1063
1064 static BOOL confirm_delete_list(HWND hWnd, DWORD fFlags, FILE_LIST *flFrom)
1065 {
1066     if (flFrom->dwNumFiles > 1)
1067     {
1068         WCHAR tmp[8];
1069         const WCHAR format[] = {'%','d',0};
1070
1071         wnsprintfW(tmp, sizeof(tmp)/sizeof(tmp[0]), format, flFrom->dwNumFiles);
1072         return SHELL_ConfirmDialogW(hWnd, ASK_DELETE_MULTIPLE_ITEM, tmp);
1073     }
1074     else
1075     {
1076         FILE_ENTRY *fileEntry = &flFrom->feFiles[0];
1077
1078         if (IsAttribFile(fileEntry->attributes))
1079             return SHELL_ConfirmDialogW(hWnd, ASK_DELETE_FILE, fileEntry->szFullPath);
1080         else if (!(fFlags & FOF_FILESONLY && fileEntry->bFromWildcard))
1081             return SHELL_ConfirmDialogW(hWnd, ASK_DELETE_FOLDER, fileEntry->szFullPath);
1082     }
1083     return TRUE;
1084 }
1085
1086 /* the FO_DELETE operation */
1087 static HRESULT delete_files(LPSHFILEOPSTRUCTW lpFileOp, FILE_LIST *flFrom)
1088 {
1089     FILE_ENTRY *fileEntry;
1090     DWORD i;
1091     BOOL bPathExists;
1092
1093     if (!flFrom->dwNumFiles)
1094         return ERROR_SUCCESS;
1095
1096     if (!(lpFileOp->fFlags & FOF_NOCONFIRMATION) || (lpFileOp->fFlags & FOF_WANTNUKEWARNING))
1097         if (!confirm_delete_list(lpFileOp->hwnd, lpFileOp->fFlags, flFrom))
1098         {
1099             lpFileOp->fAnyOperationsAborted = TRUE;
1100             return 0;
1101         }
1102
1103     for (i = 0; i < flFrom->dwNumFiles; i++)
1104     {
1105         bPathExists = TRUE;
1106         fileEntry = &flFrom->feFiles[i];
1107
1108         /* delete the file or directory */
1109         if (IsAttribFile(fileEntry->attributes))
1110             bPathExists = DeleteFileW(fileEntry->szFullPath);
1111         else if (!(lpFileOp->fFlags & FOF_FILESONLY && fileEntry->bFromWildcard))
1112             bPathExists = SHELL_DeleteDirectoryW(lpFileOp->hwnd, fileEntry->szFullPath, FALSE);
1113
1114         if (!bPathExists)
1115             return ERROR_PATH_NOT_FOUND;
1116     }
1117
1118     return ERROR_SUCCESS;
1119 }
1120
1121 static void move_dir_to_dir(LPSHFILEOPSTRUCTW lpFileOp, FILE_ENTRY *feFrom, LPWSTR szDestPath)
1122 {
1123     WCHAR szFrom[MAX_PATH], szTo[MAX_PATH];
1124     SHFILEOPSTRUCTW fileOp;
1125
1126     static const WCHAR wildCardFiles[] = {'*','.','*',0};
1127
1128     if (IsDotDir(feFrom->szFilename))
1129         return;
1130
1131     SHNotifyCreateDirectoryW(szDestPath, NULL);
1132
1133     PathCombineW(szFrom, feFrom->szFullPath, wildCardFiles);
1134     szFrom[strlenW(szFrom) + 1] = '\0';
1135
1136     strcpyW(szTo, szDestPath);
1137     szTo[strlenW(szDestPath) + 1] = '\0';
1138
1139     memcpy(&fileOp, lpFileOp, sizeof(fileOp));
1140     fileOp.pFrom = szFrom;
1141     fileOp.pTo = szTo;
1142
1143     SHFileOperationW(&fileOp);
1144 }
1145
1146 /* moves a file or directory to another directory */
1147 static void move_to_dir(LPSHFILEOPSTRUCTW lpFileOp, FILE_ENTRY *feFrom, FILE_ENTRY *feTo)
1148 {
1149     WCHAR szDestPath[MAX_PATH];
1150
1151     PathCombineW(szDestPath, feTo->szFullPath, feFrom->szFilename);
1152
1153     if (IsAttribFile(feFrom->attributes))
1154         SHNotifyMoveFileW(feFrom->szFullPath, szDestPath);
1155     else if (!(lpFileOp->fFlags & FOF_FILESONLY && feFrom->bFromWildcard))
1156         move_dir_to_dir(lpFileOp, feFrom, szDestPath);
1157 }
1158
1159 /* the FO_MOVE operation */
1160 static HRESULT move_files(LPSHFILEOPSTRUCTW lpFileOp, FILE_LIST *flFrom, FILE_LIST *flTo)
1161 {
1162     DWORD i;
1163     FILE_ENTRY *entryToMove;
1164     FILE_ENTRY *fileDest;
1165
1166     if (!flFrom->dwNumFiles || !flTo->dwNumFiles)
1167         return ERROR_CANCELLED;
1168
1169     if (!(lpFileOp->fFlags & FOF_MULTIDESTFILES) &&
1170         flTo->dwNumFiles > 1 && flFrom->dwNumFiles > 1)
1171     {
1172         return ERROR_CANCELLED;
1173     }
1174
1175     if (!(lpFileOp->fFlags & FOF_MULTIDESTFILES) &&
1176         !flFrom->bAnyDirectories &&
1177         flFrom->dwNumFiles > flTo->dwNumFiles)
1178     {
1179         return ERROR_CANCELLED;
1180     }
1181
1182     if (!PathFileExistsW(flTo->feFiles[0].szDirectory))
1183         return ERROR_CANCELLED;
1184
1185     if ((lpFileOp->fFlags & FOF_MULTIDESTFILES) &&
1186         flFrom->dwNumFiles != flTo->dwNumFiles)
1187     {
1188         return ERROR_CANCELLED;
1189     }
1190
1191     fileDest = &flTo->feFiles[0];
1192     for (i = 0; i < flFrom->dwNumFiles; i++)
1193     {
1194         entryToMove = &flFrom->feFiles[i];
1195
1196         if (lpFileOp->fFlags & FOF_MULTIDESTFILES)
1197             fileDest = &flTo->feFiles[i];
1198
1199         if (!PathFileExistsW(fileDest->szDirectory))
1200             return ERROR_CANCELLED;
1201
1202         if (fileDest->bExists && IsAttribDir(fileDest->attributes))
1203             move_to_dir(lpFileOp, entryToMove, fileDest);
1204         else
1205             SHNotifyMoveFileW(entryToMove->szFullPath, fileDest->szFullPath);
1206     }
1207
1208     return ERROR_SUCCESS;
1209 }
1210
1211 /* the FO_RENAME files */
1212 static HRESULT rename_files(LPSHFILEOPSTRUCTW lpFileOp, FILE_LIST *flFrom, FILE_LIST *flTo)
1213 {
1214     FILE_ENTRY *feFrom;
1215     FILE_ENTRY *feTo;
1216
1217     if (flFrom->dwNumFiles != 1)
1218         return ERROR_GEN_FAILURE;
1219
1220     if (flTo->dwNumFiles != 1)
1221         return ERROR_CANCELLED;
1222
1223     feFrom = &flFrom->feFiles[0];
1224     feTo= &flTo->feFiles[0];
1225
1226     /* fail if destination doesn't exist */
1227     if (!feFrom->bExists)
1228         return ERROR_SHELL_INTERNAL_FILE_NOT_FOUND;
1229
1230     /* fail if destination already exists */
1231     if (feTo->bExists)
1232         return ERROR_ALREADY_EXISTS;
1233
1234     return SHNotifyMoveFileW(feFrom->szFullPath, feTo->szFullPath);
1235 }
1236
1237 /* alert the user if an unsupported flag is used */
1238 static void check_flags(FILEOP_FLAGS fFlags)
1239 {
1240     WORD wUnsupportedFlags = FOF_ALLOWUNDO | FOF_NO_CONNECTED_ELEMENTS |
1241         FOF_NOCOPYSECURITYATTRIBS | FOF_NORECURSEREPARSE |
1242         FOF_RENAMEONCOLLISION | FOF_WANTMAPPINGHANDLE;
1243
1244     if (fFlags & wUnsupportedFlags)
1245         FIXME("Unsupported flags: %04x\n", fFlags);
1246 }
1247
1248 /*************************************************************************
1249  * SHFileOperationW          [SHELL32.@]
1250  *
1251  * See SHFileOperationA
1252  */
1253 int WINAPI SHFileOperationW(LPSHFILEOPSTRUCTW lpFileOp)
1254 {
1255     FILE_LIST flFrom, flTo;
1256     int ret = 0;
1257
1258     if (!lpFileOp)
1259         return ERROR_INVALID_PARAMETER;
1260
1261     check_flags(lpFileOp->fFlags);
1262
1263     ZeroMemory(&flFrom, sizeof(FILE_LIST));
1264     ZeroMemory(&flTo, sizeof(FILE_LIST));
1265
1266     if ((ret = parse_file_list(&flFrom, lpFileOp->pFrom)))
1267         return ret;
1268
1269     if (lpFileOp->wFunc != FO_DELETE)
1270         parse_file_list(&flTo, lpFileOp->pTo);
1271
1272     switch (lpFileOp->wFunc)
1273     {
1274         case FO_COPY:
1275             ret = copy_files(lpFileOp, &flFrom, &flTo);
1276             break;
1277         case FO_DELETE:
1278             ret = delete_files(lpFileOp, &flFrom);
1279             break;
1280         case FO_MOVE:
1281             ret = move_files(lpFileOp, &flFrom, &flTo);
1282             break;
1283         case FO_RENAME:
1284             ret = rename_files(lpFileOp, &flFrom, &flTo);
1285             break;
1286         default:
1287             ret = ERROR_INVALID_PARAMETER;
1288             break;
1289     }
1290
1291     destroy_file_list(&flFrom);
1292
1293     if (lpFileOp->wFunc != FO_DELETE)
1294         destroy_file_list(&flTo);
1295
1296     if (ret == ERROR_CANCELLED)
1297         lpFileOp->fAnyOperationsAborted = TRUE;
1298     
1299     return ret;
1300 }
1301
1302 #define SHDSA_GetItemCount(hdsa) (*(int*)(hdsa))
1303
1304 /*************************************************************************
1305  * SHFreeNameMappings      [shell32.246]
1306  *
1307  * Free the mapping handle returned by SHFileoperation if FOF_WANTSMAPPINGHANDLE
1308  * was specified.
1309  *
1310  * PARAMS
1311  *  hNameMapping [I] handle to the name mappings used during renaming of files
1312  *
1313  * RETURNS
1314  *  Nothing
1315  */
1316 void WINAPI SHFreeNameMappings(HANDLE hNameMapping)
1317 {
1318         if (hNameMapping)
1319         {
1320           int i = SHDSA_GetItemCount((HDSA)hNameMapping) - 1;
1321
1322           for (; i>= 0; i--)
1323           {
1324             LPSHNAMEMAPPINGW lp = DSA_GetItemPtr((HDSA)hNameMapping, i);
1325
1326             SHFree(lp->pszOldPath);
1327             SHFree(lp->pszNewPath);
1328           }
1329           DSA_Destroy((HDSA)hNameMapping);
1330         }
1331 }
1332
1333 /*************************************************************************
1334  * SheGetDirA [SHELL32.@]
1335  *
1336  */
1337 HRESULT WINAPI SheGetDirA(LPSTR u, LPSTR v)
1338 {   FIXME("%p %p stub\n",u,v);
1339     return 0;
1340 }
1341
1342 /*************************************************************************
1343  * SheGetDirW [SHELL32.@]
1344  *
1345  */
1346 HRESULT WINAPI SheGetDirW(LPWSTR u, LPWSTR v)
1347 {       FIXME("%p %p stub\n",u,v);
1348         return 0;
1349 }
1350
1351 /*************************************************************************
1352  * SheChangeDirA [SHELL32.@]
1353  *
1354  */
1355 HRESULT WINAPI SheChangeDirA(LPSTR u)
1356 {   FIXME("(%s),stub\n",debugstr_a(u));
1357     return 0;
1358 }
1359
1360 /*************************************************************************
1361  * SheChangeDirW [SHELL32.@]
1362  *
1363  */
1364 HRESULT WINAPI SheChangeDirW(LPWSTR u)
1365 {       FIXME("(%s),stub\n",debugstr_w(u));
1366         return 0;
1367 }
1368
1369 /*************************************************************************
1370  * IsNetDrive                   [SHELL32.66]
1371  */
1372 BOOL WINAPI IsNetDrive(DWORD drive)
1373 {
1374         char root[4];
1375         strcpy(root, "A:\\");
1376         root[0] += (char)drive;
1377         return (GetDriveTypeA(root) == DRIVE_REMOTE);
1378 }
1379
1380
1381 /*************************************************************************
1382  * RealDriveType                [SHELL32.524]
1383  */
1384 INT WINAPI RealDriveType(INT drive, BOOL bQueryNet)
1385 {
1386     char root[] = "A:\\";
1387     root[0] += (char)drive;
1388     return GetDriveTypeA(root);
1389 }