shell32: Don't add the directory name twice when recursing into subdirectories.
[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 #include "xdg.h"
46
47 WINE_DEFAULT_DEBUG_CHANNEL(shell);
48
49 #define IsAttrib(x, y)  ((INVALID_FILE_ATTRIBUTES != (x)) && ((x) & (y)))
50 #define IsAttribFile(x) (!((x) & FILE_ATTRIBUTE_DIRECTORY))
51 #define IsAttribDir(x)  IsAttrib(x, FILE_ATTRIBUTE_DIRECTORY)
52 #define IsDotDir(x)     ((x[0] == '.') && ((x[1] == 0) || ((x[1] == '.') && (x[2] == 0))))
53
54 #define FO_MASK         0xF
55
56 static const WCHAR wWildcardFile[] = {'*',0};
57 static const WCHAR wWildcardChars[] = {'*','?',0};
58
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         HINSTANCE hIconInstance;
72         UINT icon_resource_id;
73         UINT caption_resource_id, text_resource_id;
74 } SHELL_ConfirmIDstruc;
75
76 static BOOL SHELL_ConfirmIDs(int nKindOfDialog, SHELL_ConfirmIDstruc *ids)
77 {
78         ids->hIconInstance = shell32_hInstance;
79         switch (nKindOfDialog) {
80           case ASK_DELETE_FILE:
81             ids->icon_resource_id = IDI_SHELL_CONFIRM_DELETE;
82             ids->caption_resource_id  = IDS_DELETEITEM_CAPTION;
83             ids->text_resource_id  = IDS_DELETEITEM_TEXT;
84             return TRUE;
85           case ASK_DELETE_FOLDER:
86             ids->icon_resource_id = IDI_SHELL_CONFIRM_DELETE;
87             ids->caption_resource_id  = IDS_DELETEFOLDER_CAPTION;
88             ids->text_resource_id  = IDS_DELETEITEM_TEXT;
89             return TRUE;
90           case ASK_DELETE_MULTIPLE_ITEM:
91             ids->icon_resource_id = IDI_SHELL_CONFIRM_DELETE;
92             ids->caption_resource_id  = IDS_DELETEITEM_CAPTION;
93             ids->text_resource_id  = IDS_DELETEMULTIPLE_TEXT;
94             return TRUE;
95           case ASK_TRASH_FILE:
96             ids->icon_resource_id = IDI_SHELL_TRASH_FILE;
97             ids->caption_resource_id = IDS_DELETEITEM_CAPTION;
98             ids->text_resource_id = IDS_TRASHITEM_TEXT;
99             return TRUE;
100           case ASK_TRASH_FOLDER:
101             ids->icon_resource_id = IDI_SHELL_TRASH_FILE;
102             ids->caption_resource_id = IDS_DELETEFOLDER_CAPTION;
103             ids->text_resource_id = IDS_TRASHFOLDER_TEXT;
104             return TRUE;
105           case ASK_TRASH_MULTIPLE_ITEM:
106             ids->icon_resource_id = IDI_SHELL_TRASH_FILE;
107             ids->caption_resource_id = IDS_DELETEITEM_CAPTION;
108             ids->text_resource_id = IDS_TRASHMULTIPLE_TEXT;
109             return TRUE;
110           case ASK_CANT_TRASH_ITEM:
111             ids->icon_resource_id = IDI_SHELL_CONFIRM_DELETE;
112             ids->caption_resource_id  = IDS_DELETEITEM_CAPTION;
113             ids->text_resource_id  = IDS_CANTTRASH_TEXT;
114             return TRUE;
115           case ASK_DELETE_SELECTED:
116             ids->icon_resource_id = IDI_SHELL_CONFIRM_DELETE;
117             ids->caption_resource_id  = IDS_DELETEITEM_CAPTION;
118             ids->text_resource_id  = IDS_DELETESELECTED_TEXT;
119             return TRUE;
120           case ASK_OVERWRITE_FILE:
121             ids->hIconInstance = NULL;
122             ids->icon_resource_id = IDI_WARNING;
123             ids->caption_resource_id  = IDS_OVERWRITEFILE_CAPTION;
124             ids->text_resource_id  = IDS_OVERWRITEFILE_TEXT;
125             return TRUE;
126           default:
127             FIXME(" Unhandled nKindOfDialog %d stub\n", nKindOfDialog);
128         }
129         return FALSE;
130 }
131
132 BOOL SHELL_ConfirmDialogW(HWND hWnd, int nKindOfDialog, LPCWSTR szDir)
133 {
134         WCHAR szCaption[255], szText[255], szBuffer[MAX_PATH + 256];
135         SHELL_ConfirmIDstruc ids;
136         MSGBOXPARAMSW params;
137
138         if (!SHELL_ConfirmIDs(nKindOfDialog, &ids))
139           return FALSE;
140
141         LoadStringW(shell32_hInstance, ids.caption_resource_id, szCaption, sizeof(szCaption)/sizeof(WCHAR));
142         LoadStringW(shell32_hInstance, ids.text_resource_id, szText, sizeof(szText)/sizeof(WCHAR));
143
144         FormatMessageW(FORMAT_MESSAGE_FROM_STRING|FORMAT_MESSAGE_ARGUMENT_ARRAY,
145                        szText, 0, 0, szBuffer, sizeof(szBuffer), (va_list*)&szDir);
146
147         ZeroMemory(&params, sizeof(params));
148         params.cbSize = sizeof(MSGBOXPARAMSW);
149         params.hwndOwner = hWnd;
150         params.hInstance = ids.hIconInstance;
151         params.lpszText = szBuffer;
152         params.lpszCaption = szCaption;
153         params.lpszIcon = (LPWSTR)MAKEINTRESOURCE(ids.icon_resource_id);
154         params.dwStyle = MB_YESNO | MB_USERICON;
155
156         return (IDOK == MessageBoxIndirectW(&params));
157 }
158
159 static DWORD SHELL32_AnsiToUnicodeBuf(LPCSTR aPath, LPWSTR *wPath, DWORD minChars)
160 {
161         DWORD len = MultiByteToWideChar(CP_ACP, 0, aPath, -1, NULL, 0);
162
163         if (len < minChars)
164           len = minChars;
165
166         *wPath = HeapAlloc(GetProcessHeap(), 0, len * sizeof(WCHAR));
167         if (*wPath)
168         {
169           MultiByteToWideChar(CP_ACP, 0, aPath, -1, *wPath, len);
170           return NO_ERROR;
171         }
172         return E_OUTOFMEMORY;
173 }
174
175 static void SHELL32_FreeUnicodeBuf(LPWSTR wPath)
176 {
177         HeapFree(GetProcessHeap(), 0, wPath);
178 }
179
180 HRESULT WINAPI SHIsFileAvailableOffline(LPCWSTR path, LPDWORD status)
181 {
182     FIXME("(%s, %p) stub\n", debugstr_w(path), status);
183     return E_FAIL;
184 }
185
186 /**************************************************************************
187  * SHELL_DeleteDirectory()  [internal]
188  *
189  * Asks for confirmation when bShowUI is true and deletes the directory and
190  * all its subdirectories and files if necessary.
191  */
192 BOOL SHELL_DeleteDirectoryW(HWND hwnd, LPCWSTR pszDir, BOOL bShowUI)
193 {
194         BOOL    ret = TRUE;
195         HANDLE  hFind;
196         WIN32_FIND_DATAW wfd;
197         WCHAR   szTemp[MAX_PATH];
198
199         /* Make sure the directory exists before eventually prompting the user */
200         PathCombineW(szTemp, pszDir, wWildcardFile);
201         hFind = FindFirstFileW(szTemp, &wfd);
202         if (hFind == INVALID_HANDLE_VALUE)
203           return FALSE;
204
205         if (!bShowUI || (ret = SHELL_ConfirmDialogW(hwnd, ASK_DELETE_FOLDER, pszDir)))
206         {
207           do
208           {
209             LPWSTR lp = wfd.cAlternateFileName;
210             if (!lp[0])
211               lp = wfd.cFileName;
212             if (IsDotDir(lp))
213               continue;
214             PathCombineW(szTemp, pszDir, lp);
215             if (FILE_ATTRIBUTE_DIRECTORY & wfd.dwFileAttributes)
216               ret = SHELL_DeleteDirectoryW(hwnd, szTemp, FALSE);
217             else
218               ret = (SHNotifyDeleteFileW(szTemp) == ERROR_SUCCESS);
219           } while (ret && FindNextFileW(hFind, &wfd));
220         }
221         FindClose(hFind);
222         if (ret)
223           ret = (SHNotifyRemoveDirectoryW(pszDir) == ERROR_SUCCESS);
224         return ret;
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_SUCCESS &&
585               ret != ERROR_FILE_EXISTS &&
586               ret != ERROR_ALREADY_EXISTS &&
587               ret != ERROR_FILENAME_EXCED_RANGE)
588           {
589             WCHAR *pEnd, *pSlash, szTemp[MAX_PATH + 1];  /* extra for PathAddBackslash() */
590
591             lstrcpynW(szTemp, path, MAX_PATH);
592             pEnd = PathAddBackslashW(szTemp);
593             pSlash = szTemp + 3;
594
595             while (*pSlash)
596             {
597               while (*pSlash && *pSlash != '\\')
598                 pSlash = CharNextW(pSlash);
599
600               if (*pSlash)
601               {
602                 *pSlash = 0;    /* terminate path at separator */
603
604                 ret = SHNotifyCreateDirectoryW(szTemp, pSlash + 1 == pEnd ? sec : NULL);
605               }
606               *pSlash++ = '\\'; /* put the separator back */
607             }
608           }
609
610           if (ret && hWnd && (ERROR_CANCELLED != ret))
611           {
612             /* We failed and should show a dialog box */
613             FIXME("Show system error message, creating path %s, failed with error %d\n", debugstr_w(path), ret);
614             ret = ERROR_CANCELLED; /* Error has been already presented to user (not really yet!) */
615           }
616         }
617         return ret;
618 }
619
620 /*************************************************************************
621  * SHFindAttrW      [internal]
622  *
623  * Get the Attributes for a file or directory. The difference to GetAttributes()
624  * is that this function will also work for paths containing wildcard characters
625  * in its filename.
626
627  * PARAMS
628  *  path       [I]   path of directory or file to check
629  *  fileOnly   [I]   TRUE if only files should be found
630  *
631  * RETURNS
632  *  INVALID_FILE_ATTRIBUTES if the path does not exist, the actual attributes of
633  *  the first file or directory found otherwise
634  */
635 static DWORD SHFindAttrW(LPCWSTR pName, BOOL fileOnly)
636 {
637         WIN32_FIND_DATAW wfd;
638         BOOL b_FileMask = fileOnly && (NULL != StrPBrkW(pName, wWildcardChars));
639         DWORD dwAttr = INVALID_FILE_ATTRIBUTES;
640         HANDLE hFind = FindFirstFileW(pName, &wfd);
641
642         TRACE("%s %d\n", debugstr_w(pName), fileOnly);
643         if (INVALID_HANDLE_VALUE != hFind)
644         {
645           do
646           {
647             if (b_FileMask && IsAttribDir(wfd.dwFileAttributes))
648                continue;
649             dwAttr = wfd.dwFileAttributes;
650             break;
651           }
652           while (FindNextFileW(hFind, &wfd));
653           FindClose(hFind);
654         }
655         return dwAttr;
656 }
657
658 /*************************************************************************
659  *
660  * SHNameTranslate HelperFunction for SHFileOperationA
661  *
662  * Translates a list of 0 terminated ASCII strings into Unicode. If *wString
663  * is NULL, only the necessary size of the string is determined and returned,
664  * otherwise the ASCII strings are copied into it and the buffer is increased
665  * to point to the location after the final 0 termination char.
666  */
667 DWORD SHNameTranslate(LPWSTR* wString, LPCWSTR* pWToFrom, BOOL more)
668 {
669         DWORD size = 0, aSize = 0;
670         LPCSTR aString = (LPCSTR)*pWToFrom;
671
672         if (aString)
673         {
674           do
675           {
676             size = lstrlenA(aString) + 1;
677             aSize += size;
678             aString += size;
679           } while ((size != 1) && more);
680           /* The two sizes might be different in the case of multibyte chars */
681           size = MultiByteToWideChar(CP_ACP, 0, aString, aSize, *wString, 0);
682           if (*wString) /* only in the second loop */
683           {
684             MultiByteToWideChar(CP_ACP, 0, (LPCSTR)*pWToFrom, aSize, *wString, size);
685             *pWToFrom = *wString;
686             *wString += size;
687           }
688         }
689         return size;
690 }
691 /*************************************************************************
692  * SHFileOperationA          [SHELL32.@]
693  *
694  * Function to copy, move, delete and create one or more files with optional
695  * user prompts.
696  *
697  * PARAMS
698  *  lpFileOp   [I/O] pointer to a structure containing all the necessary information
699  *
700  * RETURNS
701  *  Success: ERROR_SUCCESS.
702  *  Failure: ERROR_CANCELLED.
703  *
704  * NOTES
705  *  exported by name
706  */
707 int WINAPI SHFileOperationA(LPSHFILEOPSTRUCTA lpFileOp)
708 {
709         SHFILEOPSTRUCTW nFileOp = *((LPSHFILEOPSTRUCTW)lpFileOp);
710         int retCode = 0;
711         DWORD size;
712         LPWSTR ForFree = NULL, /* we change wString in SHNameTranslate and can't use it for freeing */
713                wString = NULL; /* we change this in SHNameTranslate */
714
715         TRACE("\n");
716         if (FO_DELETE == (nFileOp.wFunc & FO_MASK))
717           nFileOp.pTo = NULL; /* we need a NULL or a valid pointer for translation */
718         if (!(nFileOp.fFlags & FOF_SIMPLEPROGRESS))
719           nFileOp.lpszProgressTitle = NULL; /* we need a NULL or a valid pointer for translation */
720         while (1) /* every loop calculate size, second translate also, if we have storage for this */
721         {
722           size = SHNameTranslate(&wString, &nFileOp.lpszProgressTitle, FALSE); /* no loop */
723           size += SHNameTranslate(&wString, &nFileOp.pFrom, TRUE); /* internal loop */
724           size += SHNameTranslate(&wString, &nFileOp.pTo, TRUE); /* internal loop */
725
726           if (ForFree)
727           {
728             retCode = SHFileOperationW(&nFileOp);
729             HeapFree(GetProcessHeap(), 0, ForFree); /* we cannot use wString, it was changed */
730             break;
731           }
732           else
733           {
734             wString = ForFree = HeapAlloc(GetProcessHeap(), 0, size * sizeof(WCHAR));
735             if (ForFree) continue;
736             retCode = ERROR_OUTOFMEMORY;
737             nFileOp.fAnyOperationsAborted = TRUE;
738             SetLastError(retCode);
739             return retCode;
740           }
741         }
742
743         lpFileOp->hNameMappings = nFileOp.hNameMappings;
744         lpFileOp->fAnyOperationsAborted = nFileOp.fAnyOperationsAborted;
745         return retCode;
746 }
747
748 #define ERROR_SHELL_INTERNAL_FILE_NOT_FOUND 1026
749
750 typedef struct
751 {
752     DWORD attributes;
753     LPWSTR szDirectory;
754     LPWSTR szFilename;
755     LPWSTR szFullPath;
756     BOOL bFromWildcard;
757     BOOL bFromRelative;
758     BOOL bExists;
759 } FILE_ENTRY;
760
761 typedef struct
762 {
763     FILE_ENTRY *feFiles;
764     DWORD num_alloc;
765     DWORD dwNumFiles;
766     BOOL bAnyFromWildcard;
767     BOOL bAnyDirectories;
768     BOOL bAnyDontExist;
769 } FILE_LIST;
770
771
772 static inline void grow_list(FILE_LIST *list)
773 {
774     FILE_ENTRY *new = HeapReAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, list->feFiles,
775                                   list->num_alloc * 2 * sizeof(*new) );
776     list->feFiles = new;
777     list->num_alloc *= 2;
778 }
779
780 /* adds a file to the FILE_ENTRY struct
781  */
782 static void add_file_to_entry(FILE_ENTRY *feFile, LPWSTR szFile)
783 {
784     DWORD dwLen = strlenW(szFile) + 1;
785     LPWSTR ptr;
786
787     feFile->szFullPath = HeapAlloc(GetProcessHeap(), 0, dwLen * sizeof(WCHAR));
788     strcpyW(feFile->szFullPath, szFile);
789
790     ptr = StrRChrW(szFile, NULL, '\\');
791     if (ptr)
792     {
793         dwLen = ptr - szFile + 1;
794         feFile->szDirectory = HeapAlloc(GetProcessHeap(), 0, dwLen * sizeof(WCHAR));
795         lstrcpynW(feFile->szDirectory, szFile, dwLen);
796
797         dwLen = strlenW(feFile->szFullPath) - dwLen + 1;
798         feFile->szFilename = HeapAlloc(GetProcessHeap(), 0, dwLen * sizeof(WCHAR));
799         strcpyW(feFile->szFilename, ptr + 1); /* skip over backslash */
800     }
801     feFile->bFromWildcard = FALSE;
802 }
803
804 static LPWSTR wildcard_to_file(LPWSTR szWildCard, LPWSTR szFileName)
805 {
806     LPWSTR szFullPath, ptr;
807     DWORD dwDirLen, dwFullLen;
808
809     ptr = StrRChrW(szWildCard, NULL, '\\');
810     dwDirLen = ptr - szWildCard + 1;
811
812     dwFullLen = dwDirLen + strlenW(szFileName) + 1;
813     szFullPath = HeapAlloc(GetProcessHeap(), 0, dwFullLen * sizeof(WCHAR));
814
815     lstrcpynW(szFullPath, szWildCard, dwDirLen + 1);
816     strcatW(szFullPath, szFileName);
817
818     return szFullPath;
819 }
820
821 static void parse_wildcard_files(FILE_LIST *flList, LPWSTR szFile, LPDWORD pdwListIndex)
822 {
823     WIN32_FIND_DATAW wfd;
824     HANDLE hFile = FindFirstFileW(szFile, &wfd);
825     FILE_ENTRY *file;
826     LPWSTR szFullPath;
827     BOOL res;
828
829     for (res = TRUE; res; res = FindNextFileW(hFile, &wfd))
830     {
831         if (IsDotDir(wfd.cFileName)) continue;
832         if (*pdwListIndex >= flList->num_alloc) grow_list( flList );
833         szFullPath = wildcard_to_file(szFile, wfd.cFileName);
834         file = &flList->feFiles[(*pdwListIndex)++];
835         add_file_to_entry(file, szFullPath);
836         file->bFromWildcard = TRUE;
837         file->attributes = wfd.dwFileAttributes;
838         if (IsAttribDir(file->attributes)) flList->bAnyDirectories = TRUE;
839         HeapFree(GetProcessHeap(), 0, szFullPath);
840     }
841
842     FindClose(hFile);
843 }
844
845 /* takes the null-separated file list and fills out the FILE_LIST */
846 static HRESULT parse_file_list(FILE_LIST *flList, LPCWSTR szFiles)
847 {
848     LPCWSTR ptr = szFiles;
849     WCHAR szCurFile[MAX_PATH];
850     DWORD i = 0, dwDirLen;
851
852     if (!szFiles)
853         return ERROR_INVALID_PARAMETER;
854
855     flList->bAnyFromWildcard = FALSE;
856     flList->bAnyDirectories = FALSE;
857     flList->bAnyDontExist = FALSE;
858     flList->num_alloc = 32;
859     flList->dwNumFiles = 0;
860
861     /* empty list */
862     if (!szFiles[0])
863         return ERROR_ACCESS_DENIED;
864         
865     flList->feFiles = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY,
866                                 flList->num_alloc * sizeof(FILE_ENTRY));
867
868     while (*ptr)
869     {
870         if (i >= flList->num_alloc) grow_list( flList );
871
872         /* change relative to absolute path */
873         if (PathIsRelativeW(ptr))
874         {
875             dwDirLen = GetCurrentDirectoryW(MAX_PATH, szCurFile) + 1;
876             PathCombineW(szCurFile, szCurFile, ptr);
877             flList->feFiles[i].bFromRelative = TRUE;
878         }
879         else
880         {
881             strcpyW(szCurFile, ptr);
882             flList->feFiles[i].bFromRelative = FALSE;
883         }
884
885         /* parse wildcard files if they are in the filename */
886         if (StrPBrkW(szCurFile, wWildcardChars))
887         {
888             parse_wildcard_files(flList, szCurFile, &i);
889             flList->bAnyFromWildcard = TRUE;
890             i--;
891         }
892         else
893         {
894             FILE_ENTRY *file = &flList->feFiles[i];
895             add_file_to_entry(file, szCurFile);
896             file->attributes = GetFileAttributesW( file->szFullPath );
897             file->bExists = (file->attributes != INVALID_FILE_ATTRIBUTES);
898             if (!file->bExists) flList->bAnyDontExist = TRUE;
899             if (IsAttribDir(file->attributes)) flList->bAnyDirectories = TRUE;
900         }
901
902         /* advance to the next string */
903         ptr += strlenW(ptr) + 1;
904         i++;
905     }
906     flList->dwNumFiles = i;
907
908     return S_OK;
909 }
910
911 /* free the FILE_LIST */
912 static void destroy_file_list(FILE_LIST *flList)
913 {
914     DWORD i;
915
916     if (!flList || !flList->feFiles)
917         return;
918
919     for (i = 0; i < flList->dwNumFiles; i++)
920     {
921         HeapFree(GetProcessHeap(), 0, flList->feFiles[i].szDirectory);
922         HeapFree(GetProcessHeap(), 0, flList->feFiles[i].szFilename);
923         HeapFree(GetProcessHeap(), 0, flList->feFiles[i].szFullPath);
924     }
925
926     HeapFree(GetProcessHeap(), 0, flList->feFiles);
927 }
928
929 static void copy_dir_to_dir(LPSHFILEOPSTRUCTW lpFileOp, FILE_ENTRY *feFrom, LPWSTR szDestPath)
930 {
931     WCHAR szFrom[MAX_PATH], szTo[MAX_PATH];
932     SHFILEOPSTRUCTW fileOp;
933
934     static const WCHAR wildCardFiles[] = {'*','.','*',0};
935
936     if (IsDotDir(feFrom->szFilename))
937         return;
938
939     if (PathFileExistsW(szDestPath))
940         PathCombineW(szTo, szDestPath, feFrom->szFilename);
941     else
942         strcpyW(szTo, szDestPath);
943
944     szTo[strlenW(szTo) + 1] = '\0';
945     SHNotifyCreateDirectoryW(szTo, NULL);
946
947     PathCombineW(szFrom, feFrom->szFullPath, wildCardFiles);
948     szFrom[strlenW(szFrom) + 1] = '\0';
949
950     memcpy(&fileOp, lpFileOp, sizeof(fileOp));
951     fileOp.pFrom = szFrom;
952     fileOp.pTo = szTo;
953     fileOp.fFlags &= ~FOF_MULTIDESTFILES; /* we know we're copying to one dir */
954
955     SHFileOperationW(&fileOp);
956 }
957
958 /* copy a file or directory to another directory */
959 static void copy_to_dir(LPSHFILEOPSTRUCTW lpFileOp, FILE_ENTRY *feFrom, FILE_ENTRY *feTo)
960 {
961     if (!PathFileExistsW(feTo->szFullPath))
962         SHNotifyCreateDirectoryW(feTo->szFullPath, NULL);
963
964     if (IsAttribFile(feFrom->attributes))
965     {
966         WCHAR szDestPath[MAX_PATH];
967
968         PathCombineW(szDestPath, feTo->szFullPath, feFrom->szFilename);
969         SHNotifyCopyFileW(feFrom->szFullPath, szDestPath, FALSE);
970     }
971     else if (!(lpFileOp->fFlags & FOF_FILESONLY && feFrom->bFromWildcard))
972         copy_dir_to_dir(lpFileOp, feFrom, feTo->szFullPath);
973 }
974
975 static void create_dest_dirs(LPWSTR szDestDir)
976 {
977     WCHAR dir[MAX_PATH];
978     LPWSTR ptr = StrChrW(szDestDir, '\\');
979
980     /* make sure all directories up to last one are created */
981     while (ptr && (ptr = StrChrW(ptr + 1, '\\')))
982     {
983         lstrcpynW(dir, szDestDir, ptr - szDestDir + 1);
984
985         if (!PathFileExistsW(dir))
986             SHNotifyCreateDirectoryW(dir, NULL);
987     }
988
989     /* create last directory */
990     if (!PathFileExistsW(szDestDir))
991         SHNotifyCreateDirectoryW(szDestDir, NULL);
992 }
993
994 /* the FO_COPY operation */
995 static HRESULT copy_files(LPSHFILEOPSTRUCTW lpFileOp, FILE_LIST *flFrom, FILE_LIST *flTo)
996 {
997     DWORD i;
998     FILE_ENTRY *entryToCopy;
999     FILE_ENTRY *fileDest = &flTo->feFiles[0];
1000     BOOL bCancelIfAnyDirectories = FALSE;
1001
1002     if (flFrom->bAnyDontExist)
1003         return ERROR_SHELL_INTERNAL_FILE_NOT_FOUND;
1004
1005     if (lpFileOp->fFlags & FOF_MULTIDESTFILES && flFrom->bAnyFromWildcard)
1006         return ERROR_CANCELLED;
1007
1008     if (!(lpFileOp->fFlags & FOF_MULTIDESTFILES) && flTo->dwNumFiles != 1)
1009         return ERROR_CANCELLED;
1010
1011     if (lpFileOp->fFlags & FOF_MULTIDESTFILES && flFrom->dwNumFiles != 1 &&
1012         flFrom->dwNumFiles != flTo->dwNumFiles)
1013     {
1014         return ERROR_CANCELLED;
1015     }
1016
1017     if (flFrom->dwNumFiles > 1 && flTo->dwNumFiles == 1 &&
1018         !PathFileExistsW(flTo->feFiles[0].szFullPath) &&
1019         IsAttribFile(fileDest->attributes))
1020     {
1021         bCancelIfAnyDirectories = TRUE;
1022     }
1023
1024     if (flFrom->dwNumFiles > 1 && flTo->dwNumFiles == 1 && fileDest->bFromRelative &&
1025         !PathFileExistsW(fileDest->szFullPath))
1026     {
1027         lpFileOp->fAnyOperationsAborted = TRUE;
1028         return ERROR_CANCELLED;
1029     }
1030
1031     if (!(lpFileOp->fFlags & FOF_MULTIDESTFILES) && flFrom->dwNumFiles != 1 &&
1032         PathFileExistsW(fileDest->szFullPath) &&
1033         IsAttribFile(fileDest->attributes))
1034     {
1035         return ERROR_CANCELLED;
1036     }
1037
1038     for (i = 0; i < flFrom->dwNumFiles; i++)
1039     {
1040         entryToCopy = &flFrom->feFiles[i];
1041
1042         if (lpFileOp->fFlags & FOF_MULTIDESTFILES)
1043             fileDest = &flTo->feFiles[i];
1044
1045         if (IsAttribDir(entryToCopy->attributes) &&
1046             !lstrcmpiW(entryToCopy->szFullPath, fileDest->szDirectory))
1047         {
1048             return ERROR_SUCCESS;
1049         }
1050
1051         if (IsAttribDir(entryToCopy->attributes) && bCancelIfAnyDirectories)
1052             return ERROR_CANCELLED;
1053
1054         create_dest_dirs(fileDest->szDirectory);
1055
1056         if (!lstrcmpiW(entryToCopy->szFullPath, fileDest->szFullPath))
1057         {
1058             if (IsAttribFile(entryToCopy->attributes))
1059                 return ERROR_NO_MORE_SEARCH_HANDLES;
1060             else
1061                 return ERROR_SUCCESS;
1062         }
1063
1064         if ((flFrom->dwNumFiles > 1 && flTo->dwNumFiles == 1) ||
1065             (flFrom->dwNumFiles == 1 && IsAttribDir(fileDest->attributes)))
1066         {
1067             copy_to_dir(lpFileOp, entryToCopy, fileDest);
1068         }
1069         else if (IsAttribDir(entryToCopy->attributes))
1070         {
1071             copy_dir_to_dir(lpFileOp, entryToCopy, fileDest->szFullPath);
1072         }
1073         else
1074         {
1075             if (SHNotifyCopyFileW(entryToCopy->szFullPath, fileDest->szFullPath, TRUE))
1076             {
1077                 lpFileOp->fAnyOperationsAborted = TRUE;
1078                 return ERROR_CANCELLED;
1079             }
1080         }
1081     }
1082
1083     return ERROR_SUCCESS;
1084 }
1085
1086 static BOOL confirm_delete_list(HWND hWnd, DWORD fFlags, BOOL fTrash, FILE_LIST *flFrom)
1087 {
1088     if (flFrom->dwNumFiles > 1)
1089     {
1090         WCHAR tmp[8];
1091         const WCHAR format[] = {'%','d',0};
1092
1093         wnsprintfW(tmp, sizeof(tmp)/sizeof(tmp[0]), format, flFrom->dwNumFiles);
1094         return SHELL_ConfirmDialogW(hWnd, (fTrash?ASK_TRASH_MULTIPLE_ITEM:ASK_DELETE_MULTIPLE_ITEM), tmp);
1095     }
1096     else
1097     {
1098         FILE_ENTRY *fileEntry = &flFrom->feFiles[0];
1099
1100         if (IsAttribFile(fileEntry->attributes))
1101             return SHELL_ConfirmDialogW(hWnd, (fTrash?ASK_TRASH_FILE:ASK_DELETE_FILE), fileEntry->szFullPath);
1102         else if (!(fFlags & FOF_FILESONLY && fileEntry->bFromWildcard))
1103             return SHELL_ConfirmDialogW(hWnd, (fTrash?ASK_TRASH_FOLDER:ASK_DELETE_FOLDER), fileEntry->szFullPath);
1104     }
1105     return TRUE;
1106 }
1107
1108 /* the FO_DELETE operation */
1109 static HRESULT delete_files(LPSHFILEOPSTRUCTW lpFileOp, FILE_LIST *flFrom)
1110 {
1111     FILE_ENTRY *fileEntry;
1112     DWORD i;
1113     BOOL bPathExists;
1114     BOOL bTrash;
1115
1116     if (!flFrom->dwNumFiles)
1117         return ERROR_SUCCESS;
1118
1119     /* Windows also checks only the first item */
1120     bTrash = (lpFileOp->fFlags & FOF_ALLOWUNDO)
1121         && TRASH_CanTrashFile(flFrom->feFiles[0].szFullPath);
1122
1123     if (!(lpFileOp->fFlags & FOF_NOCONFIRMATION) || (!bTrash && lpFileOp->fFlags & FOF_WANTNUKEWARNING))
1124         if (!confirm_delete_list(lpFileOp->hwnd, lpFileOp->fFlags, bTrash, flFrom))
1125         {
1126             lpFileOp->fAnyOperationsAborted = TRUE;
1127             return 0;
1128         }
1129
1130     for (i = 0; i < flFrom->dwNumFiles; i++)
1131     {
1132         bPathExists = TRUE;
1133         fileEntry = &flFrom->feFiles[i];
1134
1135         if (!IsAttribFile(fileEntry->attributes) &&
1136             (lpFileOp->fFlags & FOF_FILESONLY && fileEntry->bFromWildcard))
1137             continue;
1138
1139         if (bTrash)
1140         {
1141             BOOL bDelete;
1142             if (TRASH_TrashFile(fileEntry->szFullPath))
1143                 continue;
1144
1145             /* Note: Windows silently deletes the file in such a situation, we show a dialog */
1146             if (!(lpFileOp->fFlags & FOF_NOCONFIRMATION) || (lpFileOp->fFlags & FOF_WANTNUKEWARNING))
1147                 bDelete = SHELL_ConfirmDialogW(lpFileOp->hwnd, ASK_CANT_TRASH_ITEM, fileEntry->szFullPath);
1148             else
1149                 bDelete = TRUE;
1150
1151             if (!bDelete)
1152             {
1153                 lpFileOp->fAnyOperationsAborted = TRUE;
1154                 break;
1155             }
1156         }
1157         
1158         /* delete the file or directory */
1159         if (IsAttribFile(fileEntry->attributes))
1160             bPathExists = DeleteFileW(fileEntry->szFullPath);
1161         else
1162             bPathExists = SHELL_DeleteDirectoryW(lpFileOp->hwnd, fileEntry->szFullPath, FALSE);
1163
1164         if (!bPathExists)
1165             return ERROR_PATH_NOT_FOUND;
1166     }
1167
1168     return ERROR_SUCCESS;
1169 }
1170
1171 static void move_dir_to_dir(LPSHFILEOPSTRUCTW lpFileOp, FILE_ENTRY *feFrom, LPWSTR szDestPath)
1172 {
1173     WCHAR szFrom[MAX_PATH], szTo[MAX_PATH];
1174     SHFILEOPSTRUCTW fileOp;
1175
1176     static const WCHAR wildCardFiles[] = {'*','.','*',0};
1177
1178     if (IsDotDir(feFrom->szFilename))
1179         return;
1180
1181     SHNotifyCreateDirectoryW(szDestPath, NULL);
1182
1183     PathCombineW(szFrom, feFrom->szFullPath, wildCardFiles);
1184     szFrom[strlenW(szFrom) + 1] = '\0';
1185
1186     strcpyW(szTo, szDestPath);
1187     szTo[strlenW(szDestPath) + 1] = '\0';
1188
1189     memcpy(&fileOp, lpFileOp, sizeof(fileOp));
1190     fileOp.pFrom = szFrom;
1191     fileOp.pTo = szTo;
1192
1193     SHFileOperationW(&fileOp);
1194 }
1195
1196 /* moves a file or directory to another directory */
1197 static void move_to_dir(LPSHFILEOPSTRUCTW lpFileOp, FILE_ENTRY *feFrom, FILE_ENTRY *feTo)
1198 {
1199     WCHAR szDestPath[MAX_PATH];
1200
1201     PathCombineW(szDestPath, feTo->szFullPath, feFrom->szFilename);
1202
1203     if (IsAttribFile(feFrom->attributes))
1204         SHNotifyMoveFileW(feFrom->szFullPath, szDestPath);
1205     else if (!(lpFileOp->fFlags & FOF_FILESONLY && feFrom->bFromWildcard))
1206         move_dir_to_dir(lpFileOp, feFrom, szDestPath);
1207 }
1208
1209 /* the FO_MOVE operation */
1210 static HRESULT move_files(LPSHFILEOPSTRUCTW lpFileOp, FILE_LIST *flFrom, FILE_LIST *flTo)
1211 {
1212     DWORD i;
1213     FILE_ENTRY *entryToMove;
1214     FILE_ENTRY *fileDest;
1215
1216     if (!flFrom->dwNumFiles || !flTo->dwNumFiles)
1217         return ERROR_CANCELLED;
1218
1219     if (!(lpFileOp->fFlags & FOF_MULTIDESTFILES) &&
1220         flTo->dwNumFiles > 1 && flFrom->dwNumFiles > 1)
1221     {
1222         return ERROR_CANCELLED;
1223     }
1224
1225     if (!(lpFileOp->fFlags & FOF_MULTIDESTFILES) &&
1226         !flFrom->bAnyDirectories &&
1227         flFrom->dwNumFiles > flTo->dwNumFiles)
1228     {
1229         return ERROR_CANCELLED;
1230     }
1231
1232     if (!PathFileExistsW(flTo->feFiles[0].szDirectory))
1233         return ERROR_CANCELLED;
1234
1235     if ((lpFileOp->fFlags & FOF_MULTIDESTFILES) &&
1236         flFrom->dwNumFiles != flTo->dwNumFiles)
1237     {
1238         return ERROR_CANCELLED;
1239     }
1240
1241     fileDest = &flTo->feFiles[0];
1242     for (i = 0; i < flFrom->dwNumFiles; i++)
1243     {
1244         entryToMove = &flFrom->feFiles[i];
1245
1246         if (lpFileOp->fFlags & FOF_MULTIDESTFILES)
1247             fileDest = &flTo->feFiles[i];
1248
1249         if (!PathFileExistsW(fileDest->szDirectory))
1250             return ERROR_CANCELLED;
1251
1252         if (fileDest->bExists && IsAttribDir(fileDest->attributes))
1253             move_to_dir(lpFileOp, entryToMove, fileDest);
1254         else
1255             SHNotifyMoveFileW(entryToMove->szFullPath, fileDest->szFullPath);
1256     }
1257
1258     return ERROR_SUCCESS;
1259 }
1260
1261 /* the FO_RENAME files */
1262 static HRESULT rename_files(LPSHFILEOPSTRUCTW lpFileOp, FILE_LIST *flFrom, FILE_LIST *flTo)
1263 {
1264     FILE_ENTRY *feFrom;
1265     FILE_ENTRY *feTo;
1266
1267     if (flFrom->dwNumFiles != 1)
1268         return ERROR_GEN_FAILURE;
1269
1270     if (flTo->dwNumFiles != 1)
1271         return ERROR_CANCELLED;
1272
1273     feFrom = &flFrom->feFiles[0];
1274     feTo= &flTo->feFiles[0];
1275
1276     /* fail if destination doesn't exist */
1277     if (!feFrom->bExists)
1278         return ERROR_SHELL_INTERNAL_FILE_NOT_FOUND;
1279
1280     /* fail if destination already exists */
1281     if (feTo->bExists)
1282         return ERROR_ALREADY_EXISTS;
1283
1284     return SHNotifyMoveFileW(feFrom->szFullPath, feTo->szFullPath);
1285 }
1286
1287 /* alert the user if an unsupported flag is used */
1288 static void check_flags(FILEOP_FLAGS fFlags)
1289 {
1290     WORD wUnsupportedFlags = FOF_NO_CONNECTED_ELEMENTS |
1291         FOF_NOCOPYSECURITYATTRIBS | FOF_NORECURSEREPARSE |
1292         FOF_RENAMEONCOLLISION | FOF_WANTMAPPINGHANDLE;
1293
1294     if (fFlags & wUnsupportedFlags)
1295         FIXME("Unsupported flags: %04x\n", fFlags);
1296 }
1297
1298 /*************************************************************************
1299  * SHFileOperationW          [SHELL32.@]
1300  *
1301  * See SHFileOperationA
1302  */
1303 int WINAPI SHFileOperationW(LPSHFILEOPSTRUCTW lpFileOp)
1304 {
1305     FILE_LIST flFrom, flTo;
1306     int ret = 0;
1307
1308     if (!lpFileOp)
1309         return ERROR_INVALID_PARAMETER;
1310
1311     check_flags(lpFileOp->fFlags);
1312
1313     ZeroMemory(&flFrom, sizeof(FILE_LIST));
1314     ZeroMemory(&flTo, sizeof(FILE_LIST));
1315
1316     if ((ret = parse_file_list(&flFrom, lpFileOp->pFrom)))
1317         return ret;
1318
1319     if (lpFileOp->wFunc != FO_DELETE)
1320         parse_file_list(&flTo, lpFileOp->pTo);
1321
1322     switch (lpFileOp->wFunc)
1323     {
1324         case FO_COPY:
1325             ret = copy_files(lpFileOp, &flFrom, &flTo);
1326             break;
1327         case FO_DELETE:
1328             ret = delete_files(lpFileOp, &flFrom);
1329             break;
1330         case FO_MOVE:
1331             ret = move_files(lpFileOp, &flFrom, &flTo);
1332             break;
1333         case FO_RENAME:
1334             ret = rename_files(lpFileOp, &flFrom, &flTo);
1335             break;
1336         default:
1337             ret = ERROR_INVALID_PARAMETER;
1338             break;
1339     }
1340
1341     destroy_file_list(&flFrom);
1342
1343     if (lpFileOp->wFunc != FO_DELETE)
1344         destroy_file_list(&flTo);
1345
1346     if (ret == ERROR_CANCELLED)
1347         lpFileOp->fAnyOperationsAborted = TRUE;
1348     
1349     return ret;
1350 }
1351
1352 #define SHDSA_GetItemCount(hdsa) (*(int*)(hdsa))
1353
1354 /*************************************************************************
1355  * SHFreeNameMappings      [shell32.246]
1356  *
1357  * Free the mapping handle returned by SHFileoperation if FOF_WANTSMAPPINGHANDLE
1358  * was specified.
1359  *
1360  * PARAMS
1361  *  hNameMapping [I] handle to the name mappings used during renaming of files
1362  *
1363  * RETURNS
1364  *  Nothing
1365  */
1366 void WINAPI SHFreeNameMappings(HANDLE hNameMapping)
1367 {
1368         if (hNameMapping)
1369         {
1370           int i = SHDSA_GetItemCount((HDSA)hNameMapping) - 1;
1371
1372           for (; i>= 0; i--)
1373           {
1374             LPSHNAMEMAPPINGW lp = DSA_GetItemPtr((HDSA)hNameMapping, i);
1375
1376             SHFree(lp->pszOldPath);
1377             SHFree(lp->pszNewPath);
1378           }
1379           DSA_Destroy((HDSA)hNameMapping);
1380         }
1381 }
1382
1383 /*************************************************************************
1384  * SheGetDirA [SHELL32.@]
1385  *
1386  */
1387 HRESULT WINAPI SheGetDirA(LPSTR u, LPSTR v)
1388 {   FIXME("%p %p stub\n",u,v);
1389     return 0;
1390 }
1391
1392 /*************************************************************************
1393  * SheGetDirW [SHELL32.@]
1394  *
1395  */
1396 HRESULT WINAPI SheGetDirW(LPWSTR u, LPWSTR v)
1397 {       FIXME("%p %p stub\n",u,v);
1398         return 0;
1399 }
1400
1401 /*************************************************************************
1402  * SheChangeDirA [SHELL32.@]
1403  *
1404  */
1405 HRESULT WINAPI SheChangeDirA(LPSTR u)
1406 {   FIXME("(%s),stub\n",debugstr_a(u));
1407     return 0;
1408 }
1409
1410 /*************************************************************************
1411  * SheChangeDirW [SHELL32.@]
1412  *
1413  */
1414 HRESULT WINAPI SheChangeDirW(LPWSTR u)
1415 {       FIXME("(%s),stub\n",debugstr_w(u));
1416         return 0;
1417 }
1418
1419 /*************************************************************************
1420  * IsNetDrive                   [SHELL32.66]
1421  */
1422 BOOL WINAPI IsNetDrive(DWORD drive)
1423 {
1424         char root[4];
1425         strcpy(root, "A:\\");
1426         root[0] += (char)drive;
1427         return (GetDriveTypeA(root) == DRIVE_REMOTE);
1428 }
1429
1430
1431 /*************************************************************************
1432  * RealDriveType                [SHELL32.524]
1433  */
1434 INT WINAPI RealDriveType(INT drive, BOOL bQueryNet)
1435 {
1436     char root[] = "A:\\";
1437     root[0] += (char)drive;
1438     return GetDriveTypeA(root);
1439 }