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