kernel32: Handle the SECURITY_* flags passed into CreateFileW by filling out the...
[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/debug.h"
44 #include "xdg.h"
45
46 WINE_DEFAULT_DEBUG_CHANNEL(shell);
47
48 #define IsAttrib(x, y)  ((INVALID_FILE_ATTRIBUTES != (x)) && ((x) & (y)))
49 #define IsAttribFile(x) (!((x) & FILE_ATTRIBUTE_DIRECTORY))
50 #define IsAttribDir(x)  IsAttrib(x, FILE_ATTRIBUTE_DIRECTORY)
51 #define IsDotDir(x)     ((x[0] == '.') && ((x[1] == 0) || ((x[1] == '.') && (x[2] == 0))))
52
53 #define FO_MASK         0xF
54
55 static const WCHAR wWildcardFile[] = {'*',0};
56 static const WCHAR wWildcardChars[] = {'*','?',0};
57
58 static DWORD SHNotifyCreateDirectoryA(LPCSTR path, LPSECURITY_ATTRIBUTES sec);
59 static DWORD SHNotifyCreateDirectoryW(LPCWSTR path, LPSECURITY_ATTRIBUTES sec);
60 static DWORD SHNotifyRemoveDirectoryA(LPCSTR path);
61 static DWORD SHNotifyRemoveDirectoryW(LPCWSTR path);
62 static DWORD SHNotifyDeleteFileA(LPCSTR path);
63 static DWORD SHNotifyDeleteFileW(LPCWSTR path);
64 static DWORD SHNotifyMoveFileW(LPCWSTR src, LPCWSTR dest);
65 static DWORD SHNotifyCopyFileW(LPCWSTR src, LPCWSTR dest, BOOL bFailIfExists);
66 static DWORD SHFindAttrW(LPCWSTR pName, BOOL fileOnly);
67
68 typedef struct
69 {
70         HINSTANCE hIconInstance;
71         UINT icon_resource_id;
72         UINT caption_resource_id, text_resource_id;
73 } SHELL_ConfirmIDstruc;
74
75 static BOOL SHELL_ConfirmIDs(int nKindOfDialog, SHELL_ConfirmIDstruc *ids)
76 {
77         ids->hIconInstance = shell32_hInstance;
78         switch (nKindOfDialog) {
79           case ASK_DELETE_FILE:
80             ids->icon_resource_id = IDI_SHELL_CONFIRM_DELETE;
81             ids->caption_resource_id  = IDS_DELETEITEM_CAPTION;
82             ids->text_resource_id  = IDS_DELETEITEM_TEXT;
83             return TRUE;
84           case ASK_DELETE_FOLDER:
85             ids->icon_resource_id = IDI_SHELL_CONFIRM_DELETE;
86             ids->caption_resource_id  = IDS_DELETEFOLDER_CAPTION;
87             ids->text_resource_id  = IDS_DELETEITEM_TEXT;
88             return TRUE;
89           case ASK_DELETE_MULTIPLE_ITEM:
90             ids->icon_resource_id = IDI_SHELL_CONFIRM_DELETE;
91             ids->caption_resource_id  = IDS_DELETEITEM_CAPTION;
92             ids->text_resource_id  = IDS_DELETEMULTIPLE_TEXT;
93             return TRUE;
94           case ASK_TRASH_FILE:
95             ids->icon_resource_id = IDI_SHELL_TRASH_FILE;
96             ids->caption_resource_id = IDS_DELETEITEM_CAPTION;
97             ids->text_resource_id = IDS_TRASHITEM_TEXT;
98             return TRUE;
99           case ASK_TRASH_FOLDER:
100             ids->icon_resource_id = IDI_SHELL_TRASH_FILE;
101             ids->caption_resource_id = IDS_DELETEFOLDER_CAPTION;
102             ids->text_resource_id = IDS_TRASHFOLDER_TEXT;
103             return TRUE;
104           case ASK_TRASH_MULTIPLE_ITEM:
105             ids->icon_resource_id = IDI_SHELL_TRASH_FILE;
106             ids->caption_resource_id = IDS_DELETEITEM_CAPTION;
107             ids->text_resource_id = IDS_TRASHMULTIPLE_TEXT;
108             return TRUE;
109           case ASK_CANT_TRASH_ITEM:
110             ids->icon_resource_id = IDI_SHELL_CONFIRM_DELETE;
111             ids->caption_resource_id  = IDS_DELETEITEM_CAPTION;
112             ids->text_resource_id  = IDS_CANTTRASH_TEXT;
113             return TRUE;
114           case ASK_DELETE_SELECTED:
115             ids->icon_resource_id = IDI_SHELL_CONFIRM_DELETE;
116             ids->caption_resource_id  = IDS_DELETEITEM_CAPTION;
117             ids->text_resource_id  = IDS_DELETESELECTED_TEXT;
118             return TRUE;
119           case ASK_OVERWRITE_FILE:
120             ids->hIconInstance = NULL;
121             ids->icon_resource_id = IDI_WARNING;
122             ids->caption_resource_id  = IDS_OVERWRITEFILE_CAPTION;
123             ids->text_resource_id  = IDS_OVERWRITEFILE_TEXT;
124             return TRUE;
125           default:
126             FIXME(" Unhandled nKindOfDialog %d stub\n", nKindOfDialog);
127         }
128         return FALSE;
129 }
130
131 BOOL SHELL_ConfirmDialogW(HWND hWnd, int nKindOfDialog, LPCWSTR szDir)
132 {
133         WCHAR szCaption[255], szText[255], szBuffer[MAX_PATH + 256];
134         SHELL_ConfirmIDstruc ids;
135         MSGBOXPARAMSW params;
136         DWORD_PTR args[1];
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         args[0] = (DWORD_PTR)szDir;
145         FormatMessageW(FORMAT_MESSAGE_FROM_STRING|FORMAT_MESSAGE_ARGUMENT_ARRAY,
146                        szText, 0, 0, szBuffer, sizeof(szBuffer), (va_list*)args);
147
148         ZeroMemory(&params, sizeof(params));
149         params.cbSize = sizeof(MSGBOXPARAMSW);
150         params.hwndOwner = hWnd;
151         params.hInstance = ids.hIconInstance;
152         params.lpszText = szBuffer;
153         params.lpszCaption = szCaption;
154         params.lpszIcon = (LPWSTR)MAKEINTRESOURCE(ids.icon_resource_id);
155         params.dwStyle = MB_YESNO | MB_USERICON;
156
157         return (IDYES == MessageBoxIndirectW(&params));
158 }
159
160 static DWORD SHELL32_AnsiToUnicodeBuf(LPCSTR aPath, LPWSTR *wPath, DWORD minChars)
161 {
162         DWORD len = MultiByteToWideChar(CP_ACP, 0, aPath, -1, NULL, 0);
163
164         if (len < minChars)
165           len = minChars;
166
167         *wPath = HeapAlloc(GetProcessHeap(), 0, len * sizeof(WCHAR));
168         if (*wPath)
169         {
170           MultiByteToWideChar(CP_ACP, 0, aPath, -1, *wPath, len);
171           return NO_ERROR;
172         }
173         return E_OUTOFMEMORY;
174 }
175
176 static void SHELL32_FreeUnicodeBuf(LPWSTR wPath)
177 {
178         HeapFree(GetProcessHeap(), 0, wPath);
179 }
180
181 HRESULT WINAPI SHIsFileAvailableOffline(LPCWSTR path, LPDWORD status)
182 {
183     FIXME("(%s, %p) stub\n", debugstr_w(path), status);
184     return E_FAIL;
185 }
186
187 /**************************************************************************
188  * SHELL_DeleteDirectory()  [internal]
189  *
190  * Asks for confirmation when bShowUI is true and deletes the directory and
191  * all its subdirectories and files if necessary.
192  */
193 BOOL SHELL_DeleteDirectoryW(HWND hwnd, LPCWSTR pszDir, BOOL bShowUI)
194 {
195         BOOL    ret = TRUE;
196         HANDLE  hFind;
197         WIN32_FIND_DATAW wfd;
198         WCHAR   szTemp[MAX_PATH];
199
200         /* Make sure the directory exists before eventually prompting the user */
201         PathCombineW(szTemp, pszDir, wWildcardFile);
202         hFind = FindFirstFileW(szTemp, &wfd);
203         if (hFind == INVALID_HANDLE_VALUE)
204           return FALSE;
205
206         if (!bShowUI || (ret = SHELL_ConfirmDialogW(hwnd, ASK_DELETE_FOLDER, pszDir)))
207         {
208           do
209           {
210             if (IsDotDir(wfd.cFileName))
211               continue;
212             PathCombineW(szTemp, pszDir, wfd.cFileName);
213             if (FILE_ATTRIBUTE_DIRECTORY & wfd.dwFileAttributes)
214               ret = SHELL_DeleteDirectoryW(hwnd, szTemp, FALSE);
215             else
216               ret = (SHNotifyDeleteFileW(szTemp) == ERROR_SUCCESS);
217           } while (ret && FindNextFileW(hFind, &wfd));
218         }
219         FindClose(hFind);
220         if (ret)
221           ret = (SHNotifyRemoveDirectoryW(pszDir) == ERROR_SUCCESS);
222         return ret;
223 }
224
225 /**************************************************************************
226  * Win32CreateDirectory      [SHELL32.93]
227  *
228  * Creates a directory. Also triggers a change notify if one exists.
229  *
230  * PARAMS
231  *  path       [I]   path to directory to create
232  *
233  * RETURNS
234  *  TRUE if successful, FALSE otherwise
235  *
236  * NOTES
237  *  Verified on Win98 / IE 5 (SHELL32 4.72, March 1999 build) to be ANSI.
238  *  This is Unicode on NT/2000
239  */
240 static DWORD SHNotifyCreateDirectoryA(LPCSTR path, LPSECURITY_ATTRIBUTES sec)
241 {
242         LPWSTR wPath;
243         DWORD retCode;
244
245         TRACE("(%s, %p)\n", debugstr_a(path), sec);
246
247         retCode = SHELL32_AnsiToUnicodeBuf(path, &wPath, 0);
248         if (!retCode)
249         {
250           retCode = SHNotifyCreateDirectoryW(wPath, sec);
251           SHELL32_FreeUnicodeBuf(wPath);
252         }
253         return retCode;
254 }
255
256 /**********************************************************************/
257
258 static DWORD SHNotifyCreateDirectoryW(LPCWSTR path, LPSECURITY_ATTRIBUTES sec)
259 {
260         TRACE("(%s, %p)\n", debugstr_w(path), sec);
261
262         if (CreateDirectoryW(path, sec))
263         {
264           SHChangeNotify(SHCNE_MKDIR, SHCNF_PATHW, path, NULL);
265           return ERROR_SUCCESS;
266         }
267         return GetLastError();
268 }
269
270 /**********************************************************************/
271
272 BOOL WINAPI Win32CreateDirectoryAW(LPCVOID path, LPSECURITY_ATTRIBUTES sec)
273 {
274         if (SHELL_OsIsUnicode())
275           return (SHNotifyCreateDirectoryW(path, sec) == ERROR_SUCCESS);
276         return (SHNotifyCreateDirectoryA(path, sec) == ERROR_SUCCESS);
277 }
278
279 /************************************************************************
280  * Win32RemoveDirectory      [SHELL32.94]
281  *
282  * Deletes a directory. Also triggers a change notify if one exists.
283  *
284  * PARAMS
285  *  path       [I]   path to directory to delete
286  *
287  * RETURNS
288  *  TRUE if successful, FALSE otherwise
289  *
290  * NOTES
291  *  Verified on Win98 / IE 5 (SHELL32 4.72, March 1999 build) to be ANSI.
292  *  This is Unicode on NT/2000
293  */
294 static DWORD SHNotifyRemoveDirectoryA(LPCSTR path)
295 {
296         LPWSTR wPath;
297         DWORD retCode;
298
299         TRACE("(%s)\n", debugstr_a(path));
300
301         retCode = SHELL32_AnsiToUnicodeBuf(path, &wPath, 0);
302         if (!retCode)
303         {
304           retCode = SHNotifyRemoveDirectoryW(wPath);
305           SHELL32_FreeUnicodeBuf(wPath);
306         }
307         return retCode;
308 }
309
310 /***********************************************************************/
311
312 static DWORD SHNotifyRemoveDirectoryW(LPCWSTR path)
313 {
314         BOOL ret;
315         TRACE("(%s)\n", debugstr_w(path));
316
317         ret = RemoveDirectoryW(path);
318         if (!ret)
319         {
320           /* Directory may be write protected */
321           DWORD dwAttr = GetFileAttributesW(path);
322           if (IsAttrib(dwAttr, FILE_ATTRIBUTE_READONLY))
323             if (SetFileAttributesW(path, dwAttr & ~FILE_ATTRIBUTE_READONLY))
324               ret = RemoveDirectoryW(path);
325         }
326         if (ret)
327         {
328           SHChangeNotify(SHCNE_RMDIR, SHCNF_PATHW, path, NULL);
329           return ERROR_SUCCESS;
330         }
331         return GetLastError();
332 }
333
334 /***********************************************************************/
335
336 BOOL WINAPI Win32RemoveDirectoryAW(LPCVOID path)
337 {
338         if (SHELL_OsIsUnicode())
339           return (SHNotifyRemoveDirectoryW(path) == ERROR_SUCCESS);
340         return (SHNotifyRemoveDirectoryA(path) == ERROR_SUCCESS);
341 }
342
343 /************************************************************************
344  * Win32DeleteFile           [SHELL32.164]
345  *
346  * Deletes a file. Also triggers a change notify if one exists.
347  *
348  * PARAMS
349  *  path       [I]   path to file to delete
350  *
351  * RETURNS
352  *  TRUE if successful, FALSE otherwise
353  *
354  * NOTES
355  *  Verified on Win98 / IE 5 (SHELL32 4.72, March 1999 build) to be ANSI.
356  *  This is Unicode on NT/2000
357  */
358 static DWORD SHNotifyDeleteFileA(LPCSTR path)
359 {
360         LPWSTR wPath;
361         DWORD retCode;
362
363         TRACE("(%s)\n", debugstr_a(path));
364
365         retCode = SHELL32_AnsiToUnicodeBuf(path, &wPath, 0);
366         if (!retCode)
367         {
368           retCode = SHNotifyDeleteFileW(wPath);
369           SHELL32_FreeUnicodeBuf(wPath);
370         }
371         return retCode;
372 }
373
374 /***********************************************************************/
375
376 static DWORD SHNotifyDeleteFileW(LPCWSTR path)
377 {
378         BOOL ret;
379
380         TRACE("(%s)\n", debugstr_w(path));
381
382         ret = DeleteFileW(path);
383         if (!ret)
384         {
385           /* File may be write protected or a system file */
386           DWORD dwAttr = GetFileAttributesW(path);
387           if (IsAttrib(dwAttr, FILE_ATTRIBUTE_READONLY | FILE_ATTRIBUTE_SYSTEM))
388             if (SetFileAttributesW(path, dwAttr & ~(FILE_ATTRIBUTE_READONLY | FILE_ATTRIBUTE_SYSTEM)))
389               ret = DeleteFileW(path);
390         }
391         if (ret)
392         {
393           SHChangeNotify(SHCNE_DELETE, SHCNF_PATHW, path, NULL);
394           return ERROR_SUCCESS;
395         }
396         return GetLastError();
397 }
398
399 /***********************************************************************/
400
401 DWORD WINAPI Win32DeleteFileAW(LPCVOID path)
402 {
403         if (SHELL_OsIsUnicode())
404           return (SHNotifyDeleteFileW(path) == ERROR_SUCCESS);
405         return (SHNotifyDeleteFileA(path) == ERROR_SUCCESS);
406 }
407
408 /************************************************************************
409  * SHNotifyMoveFile          [internal]
410  *
411  * Moves a file. Also triggers a change notify if one exists.
412  *
413  * PARAMS
414  *  src        [I]   path to source file to move
415  *  dest       [I]   path to target file to move to
416  *
417  * RETURNS
418  *  ERORR_SUCCESS if successful
419  */
420 static DWORD SHNotifyMoveFileW(LPCWSTR src, LPCWSTR dest)
421 {
422         BOOL ret;
423
424         TRACE("(%s %s)\n", debugstr_w(src), debugstr_w(dest));
425
426         ret = MoveFileExW(src, dest, MOVEFILE_REPLACE_EXISTING);
427
428         /* MOVEFILE_REPLACE_EXISTING fails with dirs, so try MoveFile */
429         if (!ret)
430             ret = MoveFileW(src, dest);
431
432         if (!ret)
433         {
434           DWORD dwAttr;
435
436           dwAttr = SHFindAttrW(dest, FALSE);
437           if (INVALID_FILE_ATTRIBUTES == dwAttr)
438           {
439             /* Source file may be write protected or a system file */
440             dwAttr = GetFileAttributesW(src);
441             if (IsAttrib(dwAttr, FILE_ATTRIBUTE_READONLY | FILE_ATTRIBUTE_SYSTEM))
442               if (SetFileAttributesW(src, dwAttr & ~(FILE_ATTRIBUTE_READONLY | FILE_ATTRIBUTE_SYSTEM)))
443                 ret = MoveFileW(src, dest);
444           }
445         }
446         if (ret)
447         {
448           SHChangeNotify(SHCNE_RENAMEITEM, SHCNF_PATHW, src, dest);
449           return ERROR_SUCCESS;
450         }
451         return GetLastError();
452 }
453
454 /************************************************************************
455  * SHNotifyCopyFile          [internal]
456  *
457  * Copies a file. Also triggers a change notify if one exists.
458  *
459  * PARAMS
460  *  src           [I]   path to source file to move
461  *  dest          [I]   path to target file to move to
462  *  bFailIfExists [I]   if TRUE, the target file will not be overwritten if
463  *                      a file with this name already exists
464  *
465  * RETURNS
466  *  ERROR_SUCCESS if successful
467  */
468 static DWORD SHNotifyCopyFileW(LPCWSTR src, LPCWSTR dest, BOOL bFailIfExists)
469 {
470         BOOL ret;
471
472         TRACE("(%s %s %s)\n", debugstr_w(src), debugstr_w(dest), bFailIfExists ? "failIfExists" : "");
473
474         ret = CopyFileW(src, dest, bFailIfExists);
475         if (ret)
476         {
477           SHChangeNotify(SHCNE_CREATE, SHCNF_PATHW, dest, NULL);
478           return ERROR_SUCCESS;
479         }
480
481         return GetLastError();
482 }
483
484 /*************************************************************************
485  * SHCreateDirectory         [SHELL32.165]
486  *
487  * This function creates a file system folder whose fully qualified path is
488  * given by path. If one or more of the intermediate folders do not exist,
489  * they will be created as well.
490  *
491  * PARAMS
492  *  hWnd       [I]
493  *  path       [I]   path of directory to create
494  *
495  * RETURNS
496  *  ERRROR_SUCCESS or one of the following values:
497  *  ERROR_BAD_PATHNAME if the path is relative
498  *  ERROR_FILE_EXISTS when a file with that name exists
499  *  ERROR_PATH_NOT_FOUND can't find the path, probably invalid
500  *  ERROR_INVLID_NAME if the path contains invalid chars
501  *  ERROR_ALREADY_EXISTS when the directory already exists
502  *  ERROR_FILENAME_EXCED_RANGE if the filename was to long to process
503  *
504  * NOTES
505  *  exported by ordinal
506  *  Win9x exports ANSI
507  *  WinNT/2000 exports Unicode
508  */
509 DWORD WINAPI SHCreateDirectory(HWND hWnd, LPCVOID path)
510 {
511         if (SHELL_OsIsUnicode())
512           return SHCreateDirectoryExW(hWnd, path, NULL);
513         return SHCreateDirectoryExA(hWnd, path, NULL);
514 }
515
516 /*************************************************************************
517  * SHCreateDirectoryExA      [SHELL32.@]
518  *
519  * This function creates a file system folder whose fully qualified path is
520  * given by path. If one or more of the intermediate folders do not exist,
521  * they will be created as well.
522  *
523  * PARAMS
524  *  hWnd       [I]
525  *  path       [I]   path of directory to create
526  *  sec        [I]   security attributes to use or NULL
527  *
528  * RETURNS
529  *  ERRROR_SUCCESS or one of the following values:
530  *  ERROR_BAD_PATHNAME or ERROR_PATH_NOT_FOUND if the path is relative
531  *  ERROR_INVLID_NAME if the path contains invalid chars
532  *  ERROR_FILE_EXISTS when a file with that name exists
533  *  ERROR_ALREADY_EXISTS when the directory already exists
534  *  ERROR_FILENAME_EXCED_RANGE if the filename was to long to process
535  *
536  *  FIXME: Not implemented yet;
537  *  SHCreateDirectoryEx also verifies that the files in the directory will be visible
538  *  if the path is a network path to deal with network drivers which might have a limited
539  *  but unknown maximum path length. If not:
540  *
541  *  If hWnd is set to a valid window handle, a message box is displayed warning
542  *  the user that the files may not be accessible. If the user chooses not to
543  *  proceed, the function returns ERROR_CANCELLED.
544  *
545  *  If hWnd is set to NULL, no user interface is displayed and the function
546  *  returns ERROR_CANCELLED.
547  */
548 int WINAPI SHCreateDirectoryExA(HWND hWnd, LPCSTR path, LPSECURITY_ATTRIBUTES sec)
549 {
550         LPWSTR wPath;
551         DWORD retCode;
552
553         TRACE("(%s, %p)\n", debugstr_a(path), sec);
554
555         retCode = SHELL32_AnsiToUnicodeBuf(path, &wPath, 0);
556         if (!retCode)
557         {
558           retCode = SHCreateDirectoryExW(hWnd, wPath, sec);
559           SHELL32_FreeUnicodeBuf(wPath);
560         }
561         return retCode;
562 }
563
564 /*************************************************************************
565  * SHCreateDirectoryExW      [SHELL32.@]
566  *
567  * See SHCreateDirectoryExA.
568  */
569 int WINAPI SHCreateDirectoryExW(HWND hWnd, LPCWSTR path, LPSECURITY_ATTRIBUTES sec)
570 {
571         int ret = ERROR_BAD_PATHNAME;
572         TRACE("(%p, %s, %p)\n", hWnd, debugstr_w(path), sec);
573
574         if (PathIsRelativeW(path))
575         {
576           SetLastError(ret);
577         }
578         else
579         {
580           ret = SHNotifyCreateDirectoryW(path, sec);
581           /* Refuse to work on certain error codes before trying to create directories recursively */
582           if (ret != ERROR_SUCCESS &&
583               ret != ERROR_FILE_EXISTS &&
584               ret != ERROR_ALREADY_EXISTS &&
585               ret != ERROR_FILENAME_EXCED_RANGE)
586           {
587             WCHAR *pEnd, *pSlash, szTemp[MAX_PATH + 1];  /* extra for PathAddBackslash() */
588
589             lstrcpynW(szTemp, path, MAX_PATH);
590             pEnd = PathAddBackslashW(szTemp);
591             pSlash = szTemp + 3;
592
593             while (*pSlash)
594             {
595               while (*pSlash && *pSlash != '\\')
596                 pSlash = CharNextW(pSlash);
597
598               if (*pSlash)
599               {
600                 *pSlash = 0;    /* terminate path at separator */
601
602                 ret = SHNotifyCreateDirectoryW(szTemp, pSlash + 1 == pEnd ? sec : NULL);
603               }
604               *pSlash++ = '\\'; /* put the separator back */
605             }
606           }
607
608           if (ret && hWnd && (ERROR_CANCELLED != ret))
609           {
610             /* We failed and should show a dialog box */
611             FIXME("Show system error message, creating path %s, failed with error %d\n", debugstr_w(path), ret);
612             ret = ERROR_CANCELLED; /* Error has been already presented to user (not really yet!) */
613           }
614         }
615         return ret;
616 }
617
618 /*************************************************************************
619  * SHFindAttrW      [internal]
620  *
621  * Get the Attributes for a file or directory. The difference to GetAttributes()
622  * is that this function will also work for paths containing wildcard characters
623  * in its filename.
624
625  * PARAMS
626  *  path       [I]   path of directory or file to check
627  *  fileOnly   [I]   TRUE if only files should be found
628  *
629  * RETURNS
630  *  INVALID_FILE_ATTRIBUTES if the path does not exist, the actual attributes of
631  *  the first file or directory found otherwise
632  */
633 static DWORD SHFindAttrW(LPCWSTR pName, BOOL fileOnly)
634 {
635         WIN32_FIND_DATAW wfd;
636         BOOL b_FileMask = fileOnly && (NULL != StrPBrkW(pName, wWildcardChars));
637         DWORD dwAttr = INVALID_FILE_ATTRIBUTES;
638         HANDLE hFind = FindFirstFileW(pName, &wfd);
639
640         TRACE("%s %d\n", debugstr_w(pName), fileOnly);
641         if (INVALID_HANDLE_VALUE != hFind)
642         {
643           do
644           {
645             if (b_FileMask && IsAttribDir(wfd.dwFileAttributes))
646                continue;
647             dwAttr = wfd.dwFileAttributes;
648             break;
649           }
650           while (FindNextFileW(hFind, &wfd));
651           FindClose(hFind);
652         }
653         return dwAttr;
654 }
655
656 /*************************************************************************
657  *
658  * SHNameTranslate HelperFunction for SHFileOperationA
659  *
660  * Translates a list of 0 terminated ASCII strings into Unicode. If *wString
661  * is NULL, only the necessary size of the string is determined and returned,
662  * otherwise the ASCII strings are copied into it and the buffer is increased
663  * to point to the location after the final 0 termination char.
664  */
665 DWORD SHNameTranslate(LPWSTR* wString, LPCWSTR* pWToFrom, BOOL more)
666 {
667         DWORD size = 0, aSize = 0;
668         LPCSTR aString = (LPCSTR)*pWToFrom;
669
670         if (aString)
671         {
672           do
673           {
674             size = lstrlenA(aString) + 1;
675             aSize += size;
676             aString += size;
677           } while ((size != 1) && more);
678           /* The two sizes might be different in the case of multibyte chars */
679           size = MultiByteToWideChar(CP_ACP, 0, aString, aSize, *wString, 0);
680           if (*wString) /* only in the second loop */
681           {
682             MultiByteToWideChar(CP_ACP, 0, (LPCSTR)*pWToFrom, aSize, *wString, size);
683             *pWToFrom = *wString;
684             *wString += size;
685           }
686         }
687         return size;
688 }
689 /*************************************************************************
690  * SHFileOperationA          [SHELL32.@]
691  *
692  * Function to copy, move, delete and create one or more files with optional
693  * user prompts.
694  *
695  * PARAMS
696  *  lpFileOp   [I/O] pointer to a structure containing all the necessary information
697  *
698  * RETURNS
699  *  Success: ERROR_SUCCESS.
700  *  Failure: ERROR_CANCELLED.
701  *
702  * NOTES
703  *  exported by name
704  */
705 int WINAPI SHFileOperationA(LPSHFILEOPSTRUCTA lpFileOp)
706 {
707         SHFILEOPSTRUCTW nFileOp = *((LPSHFILEOPSTRUCTW)lpFileOp);
708         int retCode = 0;
709         DWORD size;
710         LPWSTR ForFree = NULL, /* we change wString in SHNameTranslate and can't use it for freeing */
711                wString = NULL; /* we change this in SHNameTranslate */
712
713         TRACE("\n");
714         if (FO_DELETE == (nFileOp.wFunc & FO_MASK))
715           nFileOp.pTo = NULL; /* we need a NULL or a valid pointer for translation */
716         if (!(nFileOp.fFlags & FOF_SIMPLEPROGRESS))
717           nFileOp.lpszProgressTitle = NULL; /* we need a NULL or a valid pointer for translation */
718         while (1) /* every loop calculate size, second translate also, if we have storage for this */
719         {
720           size = SHNameTranslate(&wString, &nFileOp.lpszProgressTitle, FALSE); /* no loop */
721           size += SHNameTranslate(&wString, &nFileOp.pFrom, TRUE); /* internal loop */
722           size += SHNameTranslate(&wString, &nFileOp.pTo, TRUE); /* internal loop */
723
724           if (ForFree)
725           {
726             retCode = SHFileOperationW(&nFileOp);
727             HeapFree(GetProcessHeap(), 0, ForFree); /* we cannot use wString, it was changed */
728             break;
729           }
730           else
731           {
732             wString = ForFree = HeapAlloc(GetProcessHeap(), 0, size * sizeof(WCHAR));
733             if (ForFree) continue;
734             retCode = ERROR_OUTOFMEMORY;
735             nFileOp.fAnyOperationsAborted = TRUE;
736             SetLastError(retCode);
737             return retCode;
738           }
739         }
740
741         lpFileOp->hNameMappings = nFileOp.hNameMappings;
742         lpFileOp->fAnyOperationsAborted = nFileOp.fAnyOperationsAborted;
743         return retCode;
744 }
745
746 #define ERROR_SHELL_INTERNAL_FILE_NOT_FOUND 1026
747
748 typedef struct
749 {
750     DWORD attributes;
751     LPWSTR szDirectory;
752     LPWSTR szFilename;
753     LPWSTR szFullPath;
754     BOOL bFromWildcard;
755     BOOL bFromRelative;
756     BOOL bExists;
757 } FILE_ENTRY;
758
759 typedef struct
760 {
761     FILE_ENTRY *feFiles;
762     DWORD num_alloc;
763     DWORD dwNumFiles;
764     BOOL bAnyFromWildcard;
765     BOOL bAnyDirectories;
766     BOOL bAnyDontExist;
767 } FILE_LIST;
768
769
770 static inline void grow_list(FILE_LIST *list)
771 {
772     FILE_ENTRY *new = HeapReAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, list->feFiles,
773                                   list->num_alloc * 2 * sizeof(*new) );
774     list->feFiles = new;
775     list->num_alloc *= 2;
776 }
777
778 /* adds a file to the FILE_ENTRY struct
779  */
780 static void add_file_to_entry(FILE_ENTRY *feFile, LPWSTR szFile)
781 {
782     DWORD dwLen = lstrlenW(szFile) + 1;
783     LPWSTR ptr;
784
785     feFile->szFullPath = HeapAlloc(GetProcessHeap(), 0, dwLen * sizeof(WCHAR));
786     lstrcpyW(feFile->szFullPath, szFile);
787
788     ptr = StrRChrW(szFile, NULL, '\\');
789     if (ptr)
790     {
791         dwLen = ptr - szFile + 1;
792         feFile->szDirectory = HeapAlloc(GetProcessHeap(), 0, dwLen * sizeof(WCHAR));
793         lstrcpynW(feFile->szDirectory, szFile, dwLen);
794
795         dwLen = lstrlenW(feFile->szFullPath) - dwLen + 1;
796         feFile->szFilename = HeapAlloc(GetProcessHeap(), 0, dwLen * sizeof(WCHAR));
797         lstrcpyW(feFile->szFilename, ptr + 1); /* skip over backslash */
798     }
799     feFile->bFromWildcard = FALSE;
800 }
801
802 static LPWSTR wildcard_to_file(LPWSTR szWildCard, LPWSTR szFileName)
803 {
804     LPWSTR szFullPath, ptr;
805     DWORD dwDirLen, dwFullLen;
806
807     ptr = StrRChrW(szWildCard, NULL, '\\');
808     dwDirLen = ptr - szWildCard + 1;
809
810     dwFullLen = dwDirLen + lstrlenW(szFileName) + 1;
811     szFullPath = HeapAlloc(GetProcessHeap(), 0, dwFullLen * sizeof(WCHAR));
812
813     lstrcpynW(szFullPath, szWildCard, dwDirLen + 1);
814     lstrcatW(szFullPath, szFileName);
815
816     return szFullPath;
817 }
818
819 static void parse_wildcard_files(FILE_LIST *flList, LPWSTR szFile, LPDWORD pdwListIndex)
820 {
821     WIN32_FIND_DATAW wfd;
822     HANDLE hFile = FindFirstFileW(szFile, &wfd);
823     FILE_ENTRY *file;
824     LPWSTR szFullPath;
825     BOOL res;
826
827     if (hFile == INVALID_HANDLE_VALUE) return;
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             lstrcpyW(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 += lstrlenW(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         lstrcpyW(szTo, szDestPath);
943
944     szTo[lstrlenW(szTo) + 1] = '\0';
945     SHNotifyCreateDirectoryW(szTo, NULL);
946
947     PathCombineW(szFrom, feFrom->szFullPath, wildCardFiles);
948     szFrom[lstrlenW(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[lstrlenW(szFrom) + 1] = '\0';
1185
1186     lstrcpyW(szTo, szDestPath);
1187     szTo[lstrlenW(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 }