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