wined3d: Resource size should always be non-zero in resource_init().
[wine.git] / dlls / shell32 / shlfileop.c
blob315f5a74531f4229fcb9cbbfafcb5db977b19ad9
1 /*
2 * SHFileOperation
4 * Copyright 2000 Juergen Schmied
5 * Copyright 2002 Andriy Palamarchuk
6 * Copyright 2004 Dietrich Teickner (from Odin)
7 * Copyright 2004 Rolf Kalbermatter
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.
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.
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
24 #include "config.h"
25 #include "wine/port.h"
27 #include <stdarg.h>
28 #include <string.h>
29 #include <ctype.h>
30 #include <assert.h>
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"
47 WINE_DEFAULT_DEBUG_CHANNEL(shell);
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))))
54 #define FO_MASK 0xF
56 #define DE_SAMEFILE 0x71
57 #define DE_DESTSAMETREE 0x7D
59 static const WCHAR wWildcardFile[] = {'*',0};
60 static const WCHAR wWildcardChars[] = {'*','?',0};
62 static DWORD SHNotifyCreateDirectoryA(LPCSTR path, LPSECURITY_ATTRIBUTES sec);
63 static DWORD SHNotifyCreateDirectoryW(LPCWSTR path, LPSECURITY_ATTRIBUTES sec);
64 static DWORD SHNotifyRemoveDirectoryA(LPCSTR path);
65 static DWORD SHNotifyRemoveDirectoryW(LPCWSTR path);
66 static DWORD SHNotifyDeleteFileA(LPCSTR path);
67 static DWORD SHNotifyDeleteFileW(LPCWSTR path);
68 static DWORD SHNotifyMoveFileW(LPCWSTR src, LPCWSTR dest);
69 static DWORD SHNotifyCopyFileW(LPCWSTR src, LPCWSTR dest, BOOL bFailIfExists);
70 static DWORD SHFindAttrW(LPCWSTR pName, BOOL fileOnly);
72 typedef struct
74 SHFILEOPSTRUCTW *req;
75 DWORD dwYesToAllMask;
76 BOOL bManyItems;
77 BOOL bCancelled;
78 } FILE_OPERATION;
80 /* Confirm dialogs with an optional "Yes To All" as used in file operations confirmations
82 static const WCHAR CONFIRM_MSG_PROP[] = {'W','I','N','E','_','C','O','N','F','I','R','M',0};
84 struct confirm_msg_info
86 LPWSTR lpszText;
87 LPWSTR lpszCaption;
88 HICON hIcon;
89 BOOL bYesToAll;
92 /* as some buttons may be hidden and the dialog height may change we may need
93 * to move the controls */
94 static void confirm_msg_move_button(HWND hDlg, INT iId, INT *xPos, INT yOffset, BOOL bShow)
96 HWND hButton = GetDlgItem(hDlg, iId);
97 RECT r;
99 if (bShow) {
100 int width;
102 GetWindowRect(hButton, &r);
103 MapWindowPoints( 0, hDlg, (POINT *)&r, 2 );
104 width = r.right - r.left;
105 SetWindowPos(hButton, 0, *xPos - width, r.top - yOffset, 0, 0,
106 SWP_NOSIZE | SWP_NOZORDER | SWP_NOACTIVATE | SWP_NOREDRAW );
107 *xPos -= width + 5;
109 else
110 ShowWindow(hButton, SW_HIDE);
113 /* Note: we paint the text manually and don't use the static control to make
114 * sure the text has the same height as the one computed in WM_INITDIALOG
116 static INT_PTR ConfirmMsgBox_Paint(HWND hDlg)
118 PAINTSTRUCT ps;
119 HFONT hOldFont;
120 RECT r;
121 HDC hdc;
123 BeginPaint(hDlg, &ps);
124 hdc = ps.hdc;
125 SetBkMode(hdc, TRANSPARENT);
127 GetClientRect(GetDlgItem(hDlg, IDD_MESSAGE), &r);
128 /* this will remap the rect to dialog coords */
129 MapWindowPoints(GetDlgItem(hDlg, IDD_MESSAGE), hDlg, (LPPOINT)&r, 2);
130 hOldFont = SelectObject(hdc, (HFONT)SendDlgItemMessageW(hDlg, IDD_MESSAGE, WM_GETFONT, 0, 0));
131 DrawTextW(hdc, GetPropW(hDlg, CONFIRM_MSG_PROP), -1, &r, DT_NOPREFIX | DT_PATH_ELLIPSIS | DT_WORDBREAK);
132 SelectObject(hdc, hOldFont);
133 EndPaint(hDlg, &ps);
134 return TRUE;
137 static INT_PTR ConfirmMsgBox_Init(HWND hDlg, LPARAM lParam)
139 struct confirm_msg_info *info = (struct confirm_msg_info *)lParam;
140 INT xPos, yOffset;
141 int width, height;
142 HFONT hOldFont;
143 HDC hdc;
144 RECT r;
146 SetWindowTextW(hDlg, info->lpszCaption);
147 ShowWindow(GetDlgItem(hDlg, IDD_MESSAGE), SW_HIDE);
148 SetPropW(hDlg, CONFIRM_MSG_PROP, info->lpszText);
149 SendDlgItemMessageW(hDlg, IDD_ICON, STM_SETICON, (WPARAM)info->hIcon, 0);
151 /* compute the text height and resize the dialog */
152 GetClientRect(GetDlgItem(hDlg, IDD_MESSAGE), &r);
153 hdc = GetDC(hDlg);
154 yOffset = r.bottom;
155 hOldFont = SelectObject(hdc, (HFONT)SendDlgItemMessageW(hDlg, IDD_MESSAGE, WM_GETFONT, 0, 0));
156 DrawTextW(hdc, info->lpszText, -1, &r, DT_NOPREFIX | DT_PATH_ELLIPSIS | DT_WORDBREAK | DT_CALCRECT);
157 SelectObject(hdc, hOldFont);
158 yOffset -= r.bottom;
159 yOffset = min(yOffset, 35); /* don't make the dialog too small */
160 ReleaseDC(hDlg, hdc);
162 GetClientRect(hDlg, &r);
163 xPos = r.right - 7;
164 GetWindowRect(hDlg, &r);
165 width = r.right - r.left;
166 height = r.bottom - r.top - yOffset;
167 MoveWindow(hDlg, (GetSystemMetrics(SM_CXSCREEN) - width)/2,
168 (GetSystemMetrics(SM_CYSCREEN) - height)/2, width, height, FALSE);
170 confirm_msg_move_button(hDlg, IDCANCEL, &xPos, yOffset, info->bYesToAll);
171 confirm_msg_move_button(hDlg, IDNO, &xPos, yOffset, TRUE);
172 confirm_msg_move_button(hDlg, IDD_YESTOALL, &xPos, yOffset, info->bYesToAll);
173 confirm_msg_move_button(hDlg, IDYES, &xPos, yOffset, TRUE);
174 return TRUE;
177 static INT_PTR CALLBACK ConfirmMsgBoxProc(HWND hDlg, UINT uMsg, WPARAM wParam, LPARAM lParam)
179 switch (uMsg)
181 case WM_INITDIALOG:
182 return ConfirmMsgBox_Init(hDlg, lParam);
183 case WM_PAINT:
184 return ConfirmMsgBox_Paint(hDlg);
185 case WM_COMMAND:
186 EndDialog(hDlg, wParam);
187 break;
188 case WM_CLOSE:
189 EndDialog(hDlg, IDCANCEL);
190 break;
192 return FALSE;
195 static int SHELL_ConfirmMsgBox(HWND hWnd, LPWSTR lpszText, LPWSTR lpszCaption, HICON hIcon, BOOL bYesToAll)
197 static const WCHAR wszTemplate[] = {'S','H','E','L','L','_','Y','E','S','T','O','A','L','L','_','M','S','G','B','O','X',0};
198 struct confirm_msg_info info;
200 info.lpszText = lpszText;
201 info.lpszCaption = lpszCaption;
202 info.hIcon = hIcon;
203 info.bYesToAll = bYesToAll;
204 return DialogBoxParamW(shell32_hInstance, wszTemplate, hWnd, ConfirmMsgBoxProc, (LPARAM)&info);
207 /* confirmation dialogs content */
208 typedef struct
210 HINSTANCE hIconInstance;
211 UINT icon_resource_id;
212 UINT caption_resource_id, text_resource_id;
213 } SHELL_ConfirmIDstruc;
215 static BOOL SHELL_ConfirmIDs(int nKindOfDialog, SHELL_ConfirmIDstruc *ids)
217 ids->hIconInstance = shell32_hInstance;
218 switch (nKindOfDialog) {
219 case ASK_DELETE_FILE:
220 ids->icon_resource_id = IDI_SHELL_CONFIRM_DELETE;
221 ids->caption_resource_id = IDS_DELETEITEM_CAPTION;
222 ids->text_resource_id = IDS_DELETEITEM_TEXT;
223 return TRUE;
224 case ASK_DELETE_FOLDER:
225 ids->icon_resource_id = IDI_SHELL_CONFIRM_DELETE;
226 ids->caption_resource_id = IDS_DELETEFOLDER_CAPTION;
227 ids->text_resource_id = IDS_DELETEITEM_TEXT;
228 return TRUE;
229 case ASK_DELETE_MULTIPLE_ITEM:
230 ids->icon_resource_id = IDI_SHELL_CONFIRM_DELETE;
231 ids->caption_resource_id = IDS_DELETEITEM_CAPTION;
232 ids->text_resource_id = IDS_DELETEMULTIPLE_TEXT;
233 return TRUE;
234 case ASK_TRASH_FILE:
235 ids->icon_resource_id = IDI_SHELL_TRASH_FILE;
236 ids->caption_resource_id = IDS_DELETEITEM_CAPTION;
237 ids->text_resource_id = IDS_TRASHITEM_TEXT;
238 return TRUE;
239 case ASK_TRASH_FOLDER:
240 ids->icon_resource_id = IDI_SHELL_TRASH_FILE;
241 ids->caption_resource_id = IDS_DELETEFOLDER_CAPTION;
242 ids->text_resource_id = IDS_TRASHFOLDER_TEXT;
243 return TRUE;
244 case ASK_TRASH_MULTIPLE_ITEM:
245 ids->icon_resource_id = IDI_SHELL_TRASH_FILE;
246 ids->caption_resource_id = IDS_DELETEITEM_CAPTION;
247 ids->text_resource_id = IDS_TRASHMULTIPLE_TEXT;
248 return TRUE;
249 case ASK_CANT_TRASH_ITEM:
250 ids->icon_resource_id = IDI_SHELL_CONFIRM_DELETE;
251 ids->caption_resource_id = IDS_DELETEITEM_CAPTION;
252 ids->text_resource_id = IDS_CANTTRASH_TEXT;
253 return TRUE;
254 case ASK_DELETE_SELECTED:
255 ids->icon_resource_id = IDI_SHELL_CONFIRM_DELETE;
256 ids->caption_resource_id = IDS_DELETEITEM_CAPTION;
257 ids->text_resource_id = IDS_DELETESELECTED_TEXT;
258 return TRUE;
259 case ASK_OVERWRITE_FILE:
260 ids->hIconInstance = NULL;
261 ids->icon_resource_id = IDI_WARNING;
262 ids->caption_resource_id = IDS_OVERWRITEFILE_CAPTION;
263 ids->text_resource_id = IDS_OVERWRITEFILE_TEXT;
264 return TRUE;
265 case ASK_OVERWRITE_FOLDER:
266 ids->hIconInstance = NULL;
267 ids->icon_resource_id = IDI_WARNING;
268 ids->caption_resource_id = IDS_OVERWRITEFILE_CAPTION;
269 ids->text_resource_id = IDS_OVERWRITEFOLDER_TEXT;
270 return TRUE;
271 default:
272 FIXME(" Unhandled nKindOfDialog %d stub\n", nKindOfDialog);
274 return FALSE;
277 static BOOL SHELL_ConfirmDialogW(HWND hWnd, int nKindOfDialog, LPCWSTR szDir, FILE_OPERATION *op)
279 WCHAR szCaption[255], szText[255], szBuffer[MAX_PATH + 256];
280 SHELL_ConfirmIDstruc ids;
281 DWORD_PTR args[1];
282 HICON hIcon;
283 int ret;
285 assert(nKindOfDialog >= 0 && nKindOfDialog < 32);
286 if (op && (op->dwYesToAllMask & (1 << nKindOfDialog)))
287 return TRUE;
289 if (!SHELL_ConfirmIDs(nKindOfDialog, &ids)) return FALSE;
291 LoadStringW(shell32_hInstance, ids.caption_resource_id, szCaption, sizeof(szCaption)/sizeof(WCHAR));
292 LoadStringW(shell32_hInstance, ids.text_resource_id, szText, sizeof(szText)/sizeof(WCHAR));
294 args[0] = (DWORD_PTR)szDir;
295 FormatMessageW(FORMAT_MESSAGE_FROM_STRING|FORMAT_MESSAGE_ARGUMENT_ARRAY,
296 szText, 0, 0, szBuffer, sizeof(szBuffer)/sizeof(szBuffer[0]), (__ms_va_list*)args);
297 hIcon = LoadIconW(ids.hIconInstance, (LPWSTR)MAKEINTRESOURCE(ids.icon_resource_id));
299 ret = SHELL_ConfirmMsgBox(hWnd, szBuffer, szCaption, hIcon, op && op->bManyItems);
300 if (op) {
301 if (ret == IDD_YESTOALL) {
302 op->dwYesToAllMask |= (1 << nKindOfDialog);
303 ret = IDYES;
305 if (ret == IDCANCEL)
306 op->bCancelled = TRUE;
307 if (ret != IDYES)
308 op->req->fAnyOperationsAborted = TRUE;
310 return ret == IDYES;
313 BOOL SHELL_ConfirmYesNoW(HWND hWnd, int nKindOfDialog, LPCWSTR szDir)
315 return SHELL_ConfirmDialogW(hWnd, nKindOfDialog, szDir, NULL);
318 static DWORD SHELL32_AnsiToUnicodeBuf(LPCSTR aPath, LPWSTR *wPath, DWORD minChars)
320 DWORD len = MultiByteToWideChar(CP_ACP, 0, aPath, -1, NULL, 0);
322 if (len < minChars)
323 len = minChars;
325 *wPath = heap_alloc(len * sizeof(WCHAR));
326 if (*wPath)
328 MultiByteToWideChar(CP_ACP, 0, aPath, -1, *wPath, len);
329 return NO_ERROR;
331 return E_OUTOFMEMORY;
334 HRESULT WINAPI SHIsFileAvailableOffline(LPCWSTR path, LPDWORD status)
336 FIXME("(%s, %p) stub\n", debugstr_w(path), status);
337 return E_FAIL;
340 /**************************************************************************
341 * SHELL_DeleteDirectory() [internal]
343 * Asks for confirmation when bShowUI is true and deletes the directory and
344 * all its subdirectories and files if necessary.
346 static DWORD SHELL_DeleteDirectoryW(HWND hwnd, LPCWSTR pszDir, BOOL bShowUI)
348 DWORD ret = 0;
349 HANDLE hFind;
350 WIN32_FIND_DATAW wfd;
351 WCHAR szTemp[MAX_PATH];
353 PathCombineW(szTemp, pszDir, wWildcardFile);
354 hFind = FindFirstFileW(szTemp, &wfd);
356 if (hFind != INVALID_HANDLE_VALUE) {
357 if (!bShowUI || SHELL_ConfirmDialogW(hwnd, ASK_DELETE_FOLDER, pszDir, NULL)) {
358 do {
359 if (IsDotDir(wfd.cFileName))
360 continue;
361 PathCombineW(szTemp, pszDir, wfd.cFileName);
362 if (FILE_ATTRIBUTE_DIRECTORY & wfd.dwFileAttributes)
363 ret = SHELL_DeleteDirectoryW(hwnd, szTemp, FALSE);
364 else
365 ret = SHNotifyDeleteFileW(szTemp);
366 } while (!ret && FindNextFileW(hFind, &wfd));
368 FindClose(hFind);
370 if (ret == ERROR_SUCCESS)
371 ret = SHNotifyRemoveDirectoryW(pszDir);
373 return ret == ERROR_PATH_NOT_FOUND ?
374 0x7C: /* DE_INVALIDFILES (legacy Windows error) */
375 ret;
378 /**************************************************************************
379 * Win32CreateDirectory [SHELL32.93]
381 * Creates a directory. Also triggers a change notify if one exists.
383 * PARAMS
384 * path [I] path to directory to create
386 * RETURNS
387 * TRUE if successful, FALSE otherwise
389 * NOTES
390 * Verified on Win98 / IE 5 (SHELL32 4.72, March 1999 build) to be ANSI.
391 * This is Unicode on NT/2000
393 static DWORD SHNotifyCreateDirectoryA(LPCSTR path, LPSECURITY_ATTRIBUTES sec)
395 LPWSTR wPath;
396 DWORD retCode;
398 TRACE("(%s, %p)\n", debugstr_a(path), sec);
400 retCode = SHELL32_AnsiToUnicodeBuf(path, &wPath, 0);
401 if (!retCode)
403 retCode = SHNotifyCreateDirectoryW(wPath, sec);
404 heap_free(wPath);
406 return retCode;
409 /**********************************************************************/
411 static DWORD SHNotifyCreateDirectoryW(LPCWSTR path, LPSECURITY_ATTRIBUTES sec)
413 TRACE("(%s, %p)\n", debugstr_w(path), sec);
415 if (CreateDirectoryW(path, sec))
417 SHChangeNotify(SHCNE_MKDIR, SHCNF_PATHW, path, NULL);
418 return ERROR_SUCCESS;
420 return GetLastError();
423 /**********************************************************************/
425 BOOL WINAPI Win32CreateDirectoryAW(LPCVOID path, LPSECURITY_ATTRIBUTES sec)
427 if (SHELL_OsIsUnicode())
428 return (SHNotifyCreateDirectoryW(path, sec) == ERROR_SUCCESS);
429 return (SHNotifyCreateDirectoryA(path, sec) == ERROR_SUCCESS);
432 /************************************************************************
433 * Win32RemoveDirectory [SHELL32.94]
435 * Deletes a directory. Also triggers a change notify if one exists.
437 * PARAMS
438 * path [I] path to directory to delete
440 * RETURNS
441 * TRUE if successful, FALSE otherwise
443 * NOTES
444 * Verified on Win98 / IE 5 (SHELL32 4.72, March 1999 build) to be ANSI.
445 * This is Unicode on NT/2000
447 static DWORD SHNotifyRemoveDirectoryA(LPCSTR path)
449 LPWSTR wPath;
450 DWORD retCode;
452 TRACE("(%s)\n", debugstr_a(path));
454 retCode = SHELL32_AnsiToUnicodeBuf(path, &wPath, 0);
455 if (!retCode)
457 retCode = SHNotifyRemoveDirectoryW(wPath);
458 heap_free(wPath);
460 return retCode;
463 /***********************************************************************/
465 static DWORD SHNotifyRemoveDirectoryW(LPCWSTR path)
467 BOOL ret;
468 TRACE("(%s)\n", debugstr_w(path));
470 ret = RemoveDirectoryW(path);
471 if (!ret)
473 /* Directory may be write protected */
474 DWORD dwAttr = GetFileAttributesW(path);
475 if (IsAttrib(dwAttr, FILE_ATTRIBUTE_READONLY))
476 if (SetFileAttributesW(path, dwAttr & ~FILE_ATTRIBUTE_READONLY))
477 ret = RemoveDirectoryW(path);
479 if (ret)
481 SHChangeNotify(SHCNE_RMDIR, SHCNF_PATHW, path, NULL);
482 return ERROR_SUCCESS;
484 return GetLastError();
487 /***********************************************************************/
489 BOOL WINAPI Win32RemoveDirectoryAW(LPCVOID path)
491 if (SHELL_OsIsUnicode())
492 return (SHNotifyRemoveDirectoryW(path) == ERROR_SUCCESS);
493 return (SHNotifyRemoveDirectoryA(path) == ERROR_SUCCESS);
496 /************************************************************************
497 * Win32DeleteFile [SHELL32.164]
499 * Deletes a file. Also triggers a change notify if one exists.
501 * PARAMS
502 * path [I] path to file to delete
504 * RETURNS
505 * TRUE if successful, FALSE otherwise
507 * NOTES
508 * Verified on Win98 / IE 5 (SHELL32 4.72, March 1999 build) to be ANSI.
509 * This is Unicode on NT/2000
511 static DWORD SHNotifyDeleteFileA(LPCSTR path)
513 LPWSTR wPath;
514 DWORD retCode;
516 TRACE("(%s)\n", debugstr_a(path));
518 retCode = SHELL32_AnsiToUnicodeBuf(path, &wPath, 0);
519 if (!retCode)
521 retCode = SHNotifyDeleteFileW(wPath);
522 heap_free(wPath);
524 return retCode;
527 /***********************************************************************/
529 static DWORD SHNotifyDeleteFileW(LPCWSTR path)
531 BOOL ret;
533 TRACE("(%s)\n", debugstr_w(path));
535 ret = DeleteFileW(path);
536 if (!ret)
538 /* File may be write protected or a system file */
539 DWORD dwAttr = GetFileAttributesW(path);
540 if (IsAttrib(dwAttr, FILE_ATTRIBUTE_READONLY | FILE_ATTRIBUTE_SYSTEM))
541 if (SetFileAttributesW(path, dwAttr & ~(FILE_ATTRIBUTE_READONLY | FILE_ATTRIBUTE_SYSTEM)))
542 ret = DeleteFileW(path);
544 if (ret)
546 SHChangeNotify(SHCNE_DELETE, SHCNF_PATHW, path, NULL);
547 return ERROR_SUCCESS;
549 return GetLastError();
552 /***********************************************************************/
554 DWORD WINAPI Win32DeleteFileAW(LPCVOID path)
556 if (SHELL_OsIsUnicode())
557 return (SHNotifyDeleteFileW(path) == ERROR_SUCCESS);
558 return (SHNotifyDeleteFileA(path) == ERROR_SUCCESS);
561 /************************************************************************
562 * SHNotifyMoveFile [internal]
564 * Moves a file. Also triggers a change notify if one exists.
566 * PARAMS
567 * src [I] path to source file to move
568 * dest [I] path to target file to move to
570 * RETURNS
571 * ERROR_SUCCESS if successful
573 static DWORD SHNotifyMoveFileW(LPCWSTR src, LPCWSTR dest)
575 BOOL ret;
577 TRACE("(%s %s)\n", debugstr_w(src), debugstr_w(dest));
579 ret = MoveFileExW(src, dest, MOVEFILE_REPLACE_EXISTING);
581 /* MOVEFILE_REPLACE_EXISTING fails with dirs, so try MoveFile */
582 if (!ret)
583 ret = MoveFileW(src, dest);
585 if (!ret)
587 DWORD dwAttr;
589 dwAttr = SHFindAttrW(dest, FALSE);
590 if (INVALID_FILE_ATTRIBUTES == dwAttr)
592 /* Source file may be write protected or a system file */
593 dwAttr = GetFileAttributesW(src);
594 if (IsAttrib(dwAttr, FILE_ATTRIBUTE_READONLY | FILE_ATTRIBUTE_SYSTEM))
595 if (SetFileAttributesW(src, dwAttr & ~(FILE_ATTRIBUTE_READONLY | FILE_ATTRIBUTE_SYSTEM)))
596 ret = MoveFileW(src, dest);
599 if (ret)
601 SHChangeNotify(SHCNE_RENAMEITEM, SHCNF_PATHW, src, dest);
602 return ERROR_SUCCESS;
604 return GetLastError();
607 /************************************************************************
608 * SHNotifyCopyFile [internal]
610 * Copies a file. Also triggers a change notify if one exists.
612 * PARAMS
613 * src [I] path to source file to move
614 * dest [I] path to target file to move to
615 * bFailIfExists [I] if TRUE, the target file will not be overwritten if
616 * a file with this name already exists
618 * RETURNS
619 * ERROR_SUCCESS if successful
621 static DWORD SHNotifyCopyFileW(LPCWSTR src, LPCWSTR dest, BOOL bFailIfExists)
623 BOOL ret;
624 DWORD attribs;
626 TRACE("(%s %s %s)\n", debugstr_w(src), debugstr_w(dest), bFailIfExists ? "failIfExists" : "");
628 /* Destination file may already exist with read only attribute */
629 attribs = GetFileAttributesW(dest);
630 if (IsAttrib(attribs, FILE_ATTRIBUTE_READONLY))
631 SetFileAttributesW(dest, attribs & ~FILE_ATTRIBUTE_READONLY);
633 ret = CopyFileW(src, dest, bFailIfExists);
634 if (ret)
636 SHChangeNotify(SHCNE_CREATE, SHCNF_PATHW, dest, NULL);
637 return ERROR_SUCCESS;
640 return GetLastError();
643 /*************************************************************************
644 * SHCreateDirectory [SHELL32.165]
646 * This function creates a file system folder whose fully qualified path is
647 * given by path. If one or more of the intermediate folders do not exist,
648 * they will be created as well.
650 * PARAMS
651 * hWnd [I]
652 * path [I] path of directory to create
654 * RETURNS
655 * ERROR_SUCCESS or one of the following values:
656 * ERROR_BAD_PATHNAME if the path is relative
657 * ERROR_FILE_EXISTS when a file with that name exists
658 * ERROR_PATH_NOT_FOUND can't find the path, probably invalid
659 * ERROR_INVALID_NAME if the path contains invalid chars
660 * ERROR_ALREADY_EXISTS when the directory already exists
661 * ERROR_FILENAME_EXCED_RANGE if the filename was too long to process
663 * NOTES
664 * exported by ordinal
665 * Win9x exports ANSI
666 * WinNT/2000 exports Unicode
668 DWORD WINAPI SHCreateDirectory(HWND hWnd, LPCVOID path)
670 if (SHELL_OsIsUnicode())
671 return SHCreateDirectoryExW(hWnd, path, NULL);
672 return SHCreateDirectoryExA(hWnd, path, NULL);
675 /*************************************************************************
676 * SHCreateDirectoryExA [SHELL32.@]
678 * This function creates a file system folder whose fully qualified path is
679 * given by path. If one or more of the intermediate folders do not exist,
680 * they will be created as well.
682 * PARAMS
683 * hWnd [I]
684 * path [I] path of directory to create
685 * sec [I] security attributes to use or NULL
687 * RETURNS
688 * ERROR_SUCCESS or one of the following values:
689 * ERROR_BAD_PATHNAME or ERROR_PATH_NOT_FOUND if the path is relative
690 * ERROR_INVALID_NAME if the path contains invalid chars
691 * ERROR_FILE_EXISTS when a file with that name exists
692 * ERROR_ALREADY_EXISTS when the directory already exists
693 * ERROR_FILENAME_EXCED_RANGE if the filename was too long to process
695 * FIXME: Not implemented yet;
696 * SHCreateDirectoryEx also verifies that the files in the directory will be visible
697 * if the path is a network path to deal with network drivers which might have a limited
698 * but unknown maximum path length. If not:
700 * If hWnd is set to a valid window handle, a message box is displayed warning
701 * the user that the files may not be accessible. If the user chooses not to
702 * proceed, the function returns ERROR_CANCELLED.
704 * If hWnd is set to NULL, no user interface is displayed and the function
705 * returns ERROR_CANCELLED.
707 int WINAPI SHCreateDirectoryExA(HWND hWnd, LPCSTR path, LPSECURITY_ATTRIBUTES sec)
709 LPWSTR wPath;
710 DWORD retCode;
712 TRACE("(%s, %p)\n", debugstr_a(path), sec);
714 retCode = SHELL32_AnsiToUnicodeBuf(path, &wPath, 0);
715 if (!retCode)
717 retCode = SHCreateDirectoryExW(hWnd, wPath, sec);
718 heap_free(wPath);
720 return retCode;
723 /*************************************************************************
724 * SHCreateDirectoryExW [SHELL32.@]
726 * See SHCreateDirectoryExA.
728 int WINAPI SHCreateDirectoryExW(HWND hWnd, LPCWSTR path, LPSECURITY_ATTRIBUTES sec)
730 int ret = ERROR_BAD_PATHNAME;
731 TRACE("(%p, %s, %p)\n", hWnd, debugstr_w(path), sec);
733 if (PathIsRelativeW(path))
735 SetLastError(ret);
737 else
739 ret = SHNotifyCreateDirectoryW(path, sec);
740 /* Refuse to work on certain error codes before trying to create directories recursively */
741 if (ret != ERROR_SUCCESS &&
742 ret != ERROR_FILE_EXISTS &&
743 ret != ERROR_ALREADY_EXISTS &&
744 ret != ERROR_FILENAME_EXCED_RANGE)
746 WCHAR *pEnd, *pSlash, szTemp[MAX_PATH + 1]; /* extra for PathAddBackslash() */
748 lstrcpynW(szTemp, path, MAX_PATH);
749 pEnd = PathAddBackslashW(szTemp);
750 pSlash = szTemp + 3;
752 while (*pSlash)
754 while (*pSlash && *pSlash != '\\') pSlash++;
755 if (*pSlash)
757 *pSlash = 0; /* terminate path at separator */
759 ret = SHNotifyCreateDirectoryW(szTemp, pSlash + 1 == pEnd ? sec : NULL);
761 *pSlash++ = '\\'; /* put the separator back */
765 if (ret && hWnd && (ERROR_CANCELLED != ret))
767 /* We failed and should show a dialog box */
768 FIXME("Show system error message, creating path %s, failed with error %d\n", debugstr_w(path), ret);
769 ret = ERROR_CANCELLED; /* Error has been already presented to user (not really yet!) */
772 return ret;
775 /*************************************************************************
776 * SHFindAttrW [internal]
778 * Get the Attributes for a file or directory. The difference to GetAttributes()
779 * is that this function will also work for paths containing wildcard characters
780 * in its filename.
782 * PARAMS
783 * path [I] path of directory or file to check
784 * fileOnly [I] TRUE if only files should be found
786 * RETURNS
787 * INVALID_FILE_ATTRIBUTES if the path does not exist, the actual attributes of
788 * the first file or directory found otherwise
790 static DWORD SHFindAttrW(LPCWSTR pName, BOOL fileOnly)
792 WIN32_FIND_DATAW wfd;
793 BOOL b_FileMask = fileOnly && (NULL != StrPBrkW(pName, wWildcardChars));
794 DWORD dwAttr = INVALID_FILE_ATTRIBUTES;
795 HANDLE hFind = FindFirstFileW(pName, &wfd);
797 TRACE("%s %d\n", debugstr_w(pName), fileOnly);
798 if (INVALID_HANDLE_VALUE != hFind)
802 if (b_FileMask && IsAttribDir(wfd.dwFileAttributes))
803 continue;
804 dwAttr = wfd.dwFileAttributes;
805 break;
807 while (FindNextFileW(hFind, &wfd));
808 FindClose(hFind);
810 return dwAttr;
813 /*************************************************************************
815 * SHNameTranslate HelperFunction for SHFileOperationA
817 * Translates a list of 0 terminated ASCII strings into Unicode. If *wString
818 * is NULL, only the necessary size of the string is determined and returned,
819 * otherwise the ASCII strings are copied into it and the buffer is increased
820 * to point to the location after the final 0 termination char.
822 static DWORD SHNameTranslate(LPWSTR* wString, LPCWSTR* pWToFrom, BOOL more)
824 DWORD size = 0, aSize = 0;
825 LPCSTR aString = (LPCSTR)*pWToFrom;
827 if (aString)
831 size = lstrlenA(aString) + 1;
832 aSize += size;
833 aString += size;
834 } while ((size != 1) && more);
835 /* The two sizes might be different in the case of multibyte chars */
836 size = MultiByteToWideChar(CP_ACP, 0, (LPCSTR)*pWToFrom, aSize, *wString, 0);
837 if (*wString) /* only in the second loop */
839 MultiByteToWideChar(CP_ACP, 0, (LPCSTR)*pWToFrom, aSize, *wString, size);
840 *pWToFrom = *wString;
841 *wString += size;
844 return size;
846 /*************************************************************************
847 * SHFileOperationA [SHELL32.@]
849 * Function to copy, move, delete and create one or more files with optional
850 * user prompts.
852 * PARAMS
853 * lpFileOp [I/O] pointer to a structure containing all the necessary information
855 * RETURNS
856 * Success: ERROR_SUCCESS.
857 * Failure: ERROR_CANCELLED.
859 * NOTES
860 * exported by name
862 int WINAPI SHFileOperationA(LPSHFILEOPSTRUCTA lpFileOp)
864 SHFILEOPSTRUCTW nFileOp = *((LPSHFILEOPSTRUCTW)lpFileOp);
865 int retCode = 0;
866 DWORD size;
867 LPWSTR ForFree = NULL, /* we change wString in SHNameTranslate and can't use it for freeing */
868 wString = NULL; /* we change this in SHNameTranslate */
870 TRACE("\n");
871 if (FO_DELETE == (nFileOp.wFunc & FO_MASK))
872 nFileOp.pTo = NULL; /* we need a NULL or a valid pointer for translation */
873 if (!(nFileOp.fFlags & FOF_SIMPLEPROGRESS))
874 nFileOp.lpszProgressTitle = NULL; /* we need a NULL or a valid pointer for translation */
875 while (1) /* every loop calculate size, second translate also, if we have storage for this */
877 size = SHNameTranslate(&wString, &nFileOp.lpszProgressTitle, FALSE); /* no loop */
878 size += SHNameTranslate(&wString, &nFileOp.pFrom, TRUE); /* internal loop */
879 size += SHNameTranslate(&wString, &nFileOp.pTo, TRUE); /* internal loop */
881 if (ForFree)
883 retCode = SHFileOperationW(&nFileOp);
884 heap_free(ForFree); /* we cannot use wString, it was changed */
885 break;
887 else
889 wString = ForFree = heap_alloc(size * sizeof(WCHAR));
890 if (ForFree) continue;
891 retCode = ERROR_OUTOFMEMORY;
892 nFileOp.fAnyOperationsAborted = TRUE;
893 return retCode;
897 lpFileOp->hNameMappings = nFileOp.hNameMappings;
898 lpFileOp->fAnyOperationsAborted = nFileOp.fAnyOperationsAborted;
899 return retCode;
902 #define ERROR_SHELL_INTERNAL_FILE_NOT_FOUND 1026
904 typedef struct
906 DWORD attributes;
907 LPWSTR szDirectory;
908 LPWSTR szFilename;
909 LPWSTR szFullPath;
910 BOOL bFromWildcard;
911 BOOL bFromRelative;
912 BOOL bExists;
913 } FILE_ENTRY;
915 typedef struct
917 FILE_ENTRY *feFiles;
918 DWORD num_alloc;
919 DWORD dwNumFiles;
920 BOOL bAnyFromWildcard;
921 BOOL bAnyDirectories;
922 BOOL bAnyDontExist;
923 } FILE_LIST;
926 static inline void grow_list(FILE_LIST *list)
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;
934 /* adds a file to the FILE_ENTRY struct
936 static void add_file_to_entry(FILE_ENTRY *feFile, LPCWSTR szFile)
938 DWORD dwLen = lstrlenW(szFile) + 1;
939 LPCWSTR ptr;
941 feFile->szFullPath = heap_alloc(dwLen * sizeof(WCHAR));
942 lstrcpyW(feFile->szFullPath, szFile);
944 ptr = StrRChrW(szFile, NULL, '\\');
945 if (ptr)
947 dwLen = ptr - szFile + 1;
948 feFile->szDirectory = heap_alloc(dwLen * sizeof(WCHAR));
949 lstrcpynW(feFile->szDirectory, szFile, dwLen);
951 dwLen = lstrlenW(feFile->szFullPath) - dwLen + 1;
952 feFile->szFilename = heap_alloc(dwLen * sizeof(WCHAR));
953 lstrcpyW(feFile->szFilename, ptr + 1); /* skip over backslash */
955 feFile->bFromWildcard = FALSE;
958 static LPWSTR wildcard_to_file(LPCWSTR szWildCard, LPCWSTR szFileName)
960 LPCWSTR ptr;
961 LPWSTR szFullPath;
962 DWORD dwDirLen, dwFullLen;
964 ptr = StrRChrW(szWildCard, NULL, '\\');
965 dwDirLen = ptr - szWildCard + 1;
967 dwFullLen = dwDirLen + lstrlenW(szFileName) + 1;
968 szFullPath = heap_alloc(dwFullLen * sizeof(WCHAR));
970 lstrcpynW(szFullPath, szWildCard, dwDirLen + 1);
971 lstrcatW(szFullPath, szFileName);
973 return szFullPath;
976 static void parse_wildcard_files(FILE_LIST *flList, LPCWSTR szFile, LPDWORD pdwListIndex)
978 WIN32_FIND_DATAW wfd;
979 HANDLE hFile = FindFirstFileW(szFile, &wfd);
980 FILE_ENTRY *file;
981 LPWSTR szFullPath;
982 BOOL res;
984 if (hFile == INVALID_HANDLE_VALUE) return;
986 for (res = TRUE; res; res = FindNextFileW(hFile, &wfd))
988 if (IsDotDir(wfd.cFileName)) continue;
989 if (*pdwListIndex >= flList->num_alloc) grow_list( flList );
990 szFullPath = wildcard_to_file(szFile, wfd.cFileName);
991 file = &flList->feFiles[(*pdwListIndex)++];
992 add_file_to_entry(file, szFullPath);
993 file->bFromWildcard = TRUE;
994 file->attributes = wfd.dwFileAttributes;
995 if (IsAttribDir(file->attributes)) flList->bAnyDirectories = TRUE;
996 heap_free(szFullPath);
999 FindClose(hFile);
1002 /* takes the null-separated file list and fills out the FILE_LIST */
1003 static HRESULT parse_file_list(FILE_LIST *flList, LPCWSTR szFiles)
1005 LPCWSTR ptr = szFiles;
1006 WCHAR szCurFile[MAX_PATH];
1007 DWORD i = 0;
1009 if (!szFiles)
1010 return ERROR_INVALID_PARAMETER;
1012 flList->bAnyFromWildcard = FALSE;
1013 flList->bAnyDirectories = FALSE;
1014 flList->bAnyDontExist = FALSE;
1015 flList->num_alloc = 32;
1016 flList->dwNumFiles = 0;
1018 /* empty list */
1019 if (!szFiles[0])
1020 return ERROR_ACCESS_DENIED;
1022 flList->feFiles = heap_alloc_zero(flList->num_alloc * sizeof(FILE_ENTRY));
1024 while (*ptr)
1026 if (i >= flList->num_alloc) grow_list( flList );
1028 /* change relative to absolute path */
1029 if (PathIsRelativeW(ptr))
1031 GetCurrentDirectoryW(MAX_PATH, szCurFile);
1032 PathCombineW(szCurFile, szCurFile, ptr);
1033 flList->feFiles[i].bFromRelative = TRUE;
1035 else
1037 lstrcpyW(szCurFile, ptr);
1038 flList->feFiles[i].bFromRelative = FALSE;
1041 /* parse wildcard files if they are in the filename */
1042 if (StrPBrkW(szCurFile, wWildcardChars))
1044 parse_wildcard_files(flList, szCurFile, &i);
1045 flList->bAnyFromWildcard = TRUE;
1046 i--;
1048 else
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;
1058 /* advance to the next string */
1059 ptr += lstrlenW(ptr) + 1;
1060 i++;
1062 flList->dwNumFiles = i;
1064 return S_OK;
1067 /* free the FILE_LIST */
1068 static void destroy_file_list(FILE_LIST *flList)
1070 DWORD i;
1072 if (!flList || !flList->feFiles)
1073 return;
1075 for (i = 0; i < flList->dwNumFiles; i++)
1077 heap_free(flList->feFiles[i].szDirectory);
1078 heap_free(flList->feFiles[i].szFilename);
1079 heap_free(flList->feFiles[i].szFullPath);
1082 heap_free(flList->feFiles);
1085 static void copy_dir_to_dir(FILE_OPERATION *op, const FILE_ENTRY *feFrom, LPCWSTR szDestPath)
1087 WCHAR szFrom[MAX_PATH], szTo[MAX_PATH];
1088 SHFILEOPSTRUCTW fileOp;
1090 static const WCHAR wildCardFiles[] = {'*','.','*',0};
1092 if (IsDotDir(feFrom->szFilename))
1093 return;
1095 if (PathFileExistsW(szDestPath))
1096 PathCombineW(szTo, szDestPath, feFrom->szFilename);
1097 else
1098 lstrcpyW(szTo, szDestPath);
1100 if (!(op->req->fFlags & FOF_NOCONFIRMATION) && PathFileExistsW(szTo)) {
1101 if (!SHELL_ConfirmDialogW(op->req->hwnd, ASK_OVERWRITE_FOLDER, feFrom->szFilename, op))
1103 /* Vista returns an ERROR_CANCELLED even if user pressed "No" */
1104 if (!op->bManyItems)
1105 op->bCancelled = TRUE;
1106 return;
1110 szTo[lstrlenW(szTo) + 1] = '\0';
1111 SHNotifyCreateDirectoryW(szTo, NULL);
1113 PathCombineW(szFrom, feFrom->szFullPath, wildCardFiles);
1114 szFrom[lstrlenW(szFrom) + 1] = '\0';
1116 fileOp = *op->req;
1117 fileOp.pFrom = szFrom;
1118 fileOp.pTo = szTo;
1119 fileOp.fFlags &= ~FOF_MULTIDESTFILES; /* we know we're copying to one dir */
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;
1126 SHFileOperationW(&fileOp);
1129 static BOOL copy_file_to_file(FILE_OPERATION *op, const WCHAR *szFrom, const WCHAR *szTo)
1131 if (!(op->req->fFlags & FOF_NOCONFIRMATION) && PathFileExistsW(szTo))
1133 if (!SHELL_ConfirmDialogW(op->req->hwnd, ASK_OVERWRITE_FILE, PathFindFileNameW(szTo), op))
1134 return FALSE;
1137 return SHNotifyCopyFileW(szFrom, szTo, FALSE) == 0;
1140 /* copy a file or directory to another directory */
1141 static void copy_to_dir(FILE_OPERATION *op, const FILE_ENTRY *feFrom, const FILE_ENTRY *feTo)
1143 if (!PathFileExistsW(feTo->szFullPath))
1144 SHNotifyCreateDirectoryW(feTo->szFullPath, NULL);
1146 if (IsAttribFile(feFrom->attributes))
1148 WCHAR szDestPath[MAX_PATH];
1150 PathCombineW(szDestPath, feTo->szFullPath, feFrom->szFilename);
1151 copy_file_to_file(op, feFrom->szFullPath, szDestPath);
1153 else if (!(op->req->fFlags & FOF_FILESONLY && feFrom->bFromWildcard))
1154 copy_dir_to_dir(op, feFrom, feTo->szFullPath);
1157 static void create_dest_dirs(LPCWSTR szDestDir)
1159 WCHAR dir[MAX_PATH];
1160 LPCWSTR ptr = StrChrW(szDestDir, '\\');
1162 /* make sure all directories up to last one are created */
1163 while (ptr && (ptr = StrChrW(ptr + 1, '\\')))
1165 lstrcpynW(dir, szDestDir, ptr - szDestDir + 1);
1167 if (!PathFileExistsW(dir))
1168 SHNotifyCreateDirectoryW(dir, NULL);
1171 /* create last directory */
1172 if (!PathFileExistsW(szDestDir))
1173 SHNotifyCreateDirectoryW(szDestDir, NULL);
1176 /* the FO_COPY operation */
1177 static int copy_files(FILE_OPERATION *op, const FILE_LIST *flFrom, FILE_LIST *flTo)
1179 DWORD i;
1180 const FILE_ENTRY *entryToCopy;
1181 const FILE_ENTRY *fileDest = &flTo->feFiles[0];
1183 if (flFrom->bAnyDontExist)
1184 return ERROR_SHELL_INTERNAL_FILE_NOT_FOUND;
1186 if (flTo->dwNumFiles == 0)
1188 /* If the destination is empty, SHFileOperation should use the current directory */
1189 WCHAR curdir[MAX_PATH+1];
1191 GetCurrentDirectoryW(MAX_PATH, curdir);
1192 curdir[lstrlenW(curdir)+1] = 0;
1194 destroy_file_list(flTo);
1195 ZeroMemory(flTo, sizeof(FILE_LIST));
1196 parse_file_list(flTo, curdir);
1197 fileDest = &flTo->feFiles[0];
1200 if (op->req->fFlags & FOF_MULTIDESTFILES)
1202 if (flFrom->bAnyFromWildcard)
1203 return ERROR_CANCELLED;
1205 if (flFrom->dwNumFiles != flTo->dwNumFiles)
1207 if (flFrom->dwNumFiles != 1 && !IsAttribDir(fileDest->attributes))
1208 return ERROR_CANCELLED;
1210 /* Free all but the first entry. */
1211 for (i = 1; i < flTo->dwNumFiles; i++)
1213 heap_free(flTo->feFiles[i].szDirectory);
1214 heap_free(flTo->feFiles[i].szFilename);
1215 heap_free(flTo->feFiles[i].szFullPath);
1218 flTo->dwNumFiles = 1;
1220 else if (IsAttribDir(fileDest->attributes))
1222 for (i = 1; i < flTo->dwNumFiles; i++)
1223 if (!IsAttribDir(flTo->feFiles[i].attributes) ||
1224 !IsAttribDir(flFrom->feFiles[i].attributes))
1226 return ERROR_CANCELLED;
1230 else if (flFrom->dwNumFiles != 1)
1232 if (flTo->dwNumFiles != 1 && !IsAttribDir(fileDest->attributes))
1233 return ERROR_CANCELLED;
1235 if (PathFileExistsW(fileDest->szFullPath) &&
1236 IsAttribFile(fileDest->attributes))
1238 return ERROR_CANCELLED;
1241 if (flTo->dwNumFiles == 1 && fileDest->bFromRelative &&
1242 !PathFileExistsW(fileDest->szFullPath))
1244 return ERROR_CANCELLED;
1248 for (i = 0; i < flFrom->dwNumFiles; i++)
1250 entryToCopy = &flFrom->feFiles[i];
1252 if ((op->req->fFlags & FOF_MULTIDESTFILES) &&
1253 flTo->dwNumFiles > 1)
1255 fileDest = &flTo->feFiles[i];
1258 if (IsAttribDir(entryToCopy->attributes) &&
1259 !lstrcmpiW(entryToCopy->szFullPath, fileDest->szDirectory))
1261 return ERROR_SUCCESS;
1264 create_dest_dirs(fileDest->szDirectory);
1266 if (!lstrcmpiW(entryToCopy->szFullPath, fileDest->szFullPath))
1268 if (IsAttribFile(entryToCopy->attributes))
1269 return ERROR_NO_MORE_SEARCH_HANDLES;
1270 else
1271 return ERROR_SUCCESS;
1274 if ((flFrom->dwNumFiles > 1 && flTo->dwNumFiles == 1) ||
1275 IsAttribDir(fileDest->attributes))
1277 copy_to_dir(op, entryToCopy, fileDest);
1279 else if (IsAttribDir(entryToCopy->attributes))
1281 copy_dir_to_dir(op, entryToCopy, fileDest->szFullPath);
1283 else
1285 if (!copy_file_to_file(op, entryToCopy->szFullPath, fileDest->szFullPath))
1287 op->req->fAnyOperationsAborted = TRUE;
1288 return ERROR_CANCELLED;
1292 /* Vista return code. XP would return e.g. ERROR_FILE_NOT_FOUND, ERROR_ALREADY_EXISTS */
1293 if (op->bCancelled)
1294 return ERROR_CANCELLED;
1297 /* Vista return code. On XP if the used pressed "No" for the last item,
1298 * ERROR_ARENA_TRASHED would be returned */
1299 return ERROR_SUCCESS;
1302 static BOOL confirm_delete_list(HWND hWnd, DWORD fFlags, BOOL fTrash, const FILE_LIST *flFrom)
1304 if (flFrom->dwNumFiles > 1)
1306 static const WCHAR format[] = {'%','d',0};
1307 WCHAR tmp[8];
1309 wnsprintfW(tmp, sizeof(tmp)/sizeof(tmp[0]), format, flFrom->dwNumFiles);
1310 return SHELL_ConfirmDialogW(hWnd, (fTrash?ASK_TRASH_MULTIPLE_ITEM:ASK_DELETE_MULTIPLE_ITEM), tmp, NULL);
1312 else
1314 const FILE_ENTRY *fileEntry = &flFrom->feFiles[0];
1316 if (IsAttribFile(fileEntry->attributes))
1317 return SHELL_ConfirmDialogW(hWnd, (fTrash?ASK_TRASH_FILE:ASK_DELETE_FILE), fileEntry->szFullPath, NULL);
1318 else if (!(fFlags & FOF_FILESONLY && fileEntry->bFromWildcard))
1319 return SHELL_ConfirmDialogW(hWnd, (fTrash?ASK_TRASH_FOLDER:ASK_DELETE_FOLDER), fileEntry->szFullPath, NULL);
1321 return TRUE;
1324 /* the FO_DELETE operation */
1325 static int delete_files(LPSHFILEOPSTRUCTW lpFileOp, const FILE_LIST *flFrom)
1327 const FILE_ENTRY *fileEntry;
1328 DWORD i;
1329 int ret;
1330 BOOL bTrash;
1332 if (!flFrom->dwNumFiles)
1333 return ERROR_SUCCESS;
1335 /* Windows also checks only the first item */
1336 bTrash = (lpFileOp->fFlags & FOF_ALLOWUNDO)
1337 && TRASH_CanTrashFile(flFrom->feFiles[0].szFullPath);
1339 if (!(lpFileOp->fFlags & FOF_NOCONFIRMATION) || (!bTrash && lpFileOp->fFlags & FOF_WANTNUKEWARNING))
1340 if (!confirm_delete_list(lpFileOp->hwnd, lpFileOp->fFlags, bTrash, flFrom))
1342 lpFileOp->fAnyOperationsAborted = TRUE;
1343 return 0;
1346 for (i = 0; i < flFrom->dwNumFiles; i++)
1348 fileEntry = &flFrom->feFiles[i];
1350 if (!IsAttribFile(fileEntry->attributes) &&
1351 (lpFileOp->fFlags & FOF_FILESONLY && fileEntry->bFromWildcard))
1352 continue;
1354 if (bTrash)
1356 BOOL bDelete;
1357 if (TRASH_TrashFile(fileEntry->szFullPath))
1358 continue;
1360 /* Note: Windows silently deletes the file in such a situation, we show a dialog */
1361 if (!(lpFileOp->fFlags & FOF_NOCONFIRMATION) || (lpFileOp->fFlags & FOF_WANTNUKEWARNING))
1362 bDelete = SHELL_ConfirmDialogW(lpFileOp->hwnd, ASK_CANT_TRASH_ITEM, fileEntry->szFullPath, NULL);
1363 else
1364 bDelete = TRUE;
1366 if (!bDelete)
1368 lpFileOp->fAnyOperationsAborted = TRUE;
1369 break;
1373 /* delete the file or directory */
1374 if (IsAttribFile(fileEntry->attributes))
1375 ret = DeleteFileW(fileEntry->szFullPath) ?
1376 ERROR_SUCCESS : GetLastError();
1377 else
1378 ret = SHELL_DeleteDirectoryW(lpFileOp->hwnd, fileEntry->szFullPath, FALSE);
1380 if (ret)
1381 return ret;
1384 return ERROR_SUCCESS;
1387 /* moves a file or directory to another directory */
1388 static void move_to_dir(LPSHFILEOPSTRUCTW lpFileOp, const FILE_ENTRY *feFrom, const FILE_ENTRY *feTo)
1390 WCHAR szDestPath[MAX_PATH];
1392 PathCombineW(szDestPath, feTo->szFullPath, feFrom->szFilename);
1393 SHNotifyMoveFileW(feFrom->szFullPath, szDestPath);
1396 /* the FO_MOVE operation */
1397 static int move_files(LPSHFILEOPSTRUCTW lpFileOp, const FILE_LIST *flFrom, const FILE_LIST *flTo)
1399 DWORD i;
1400 INT mismatched = 0;
1401 const FILE_ENTRY *entryToMove;
1402 const FILE_ENTRY *fileDest;
1404 if (!flFrom->dwNumFiles)
1405 return ERROR_SUCCESS;
1407 if (!flTo->dwNumFiles)
1408 return ERROR_FILE_NOT_FOUND;
1410 if (!(lpFileOp->fFlags & FOF_MULTIDESTFILES) &&
1411 flTo->dwNumFiles > 1 && flFrom->dwNumFiles > 1)
1413 return ERROR_CANCELLED;
1416 if (!(lpFileOp->fFlags & FOF_MULTIDESTFILES) &&
1417 !flFrom->bAnyDirectories &&
1418 flFrom->dwNumFiles > flTo->dwNumFiles)
1420 return ERROR_CANCELLED;
1423 if (!PathFileExistsW(flTo->feFiles[0].szDirectory))
1424 return ERROR_CANCELLED;
1426 if (lpFileOp->fFlags & FOF_MULTIDESTFILES)
1427 mismatched = flFrom->dwNumFiles - flTo->dwNumFiles;
1429 fileDest = &flTo->feFiles[0];
1430 for (i = 0; i < flFrom->dwNumFiles; i++)
1432 entryToMove = &flFrom->feFiles[i];
1434 if (!PathFileExistsW(fileDest->szDirectory))
1435 return ERROR_CANCELLED;
1437 if (lpFileOp->fFlags & FOF_MULTIDESTFILES)
1439 if (i >= flTo->dwNumFiles)
1440 break;
1441 fileDest = &flTo->feFiles[i];
1442 if (mismatched && !fileDest->bExists)
1444 create_dest_dirs(flTo->feFiles[i].szFullPath);
1445 flTo->feFiles[i].bExists = TRUE;
1446 flTo->feFiles[i].attributes = FILE_ATTRIBUTE_DIRECTORY;
1450 if (fileDest->bExists && IsAttribDir(fileDest->attributes))
1451 move_to_dir(lpFileOp, entryToMove, fileDest);
1452 else
1453 SHNotifyMoveFileW(entryToMove->szFullPath, fileDest->szFullPath);
1456 if (mismatched > 0)
1458 if (flFrom->bAnyDirectories)
1459 return DE_DESTSAMETREE;
1460 else
1461 return DE_SAMEFILE;
1464 return ERROR_SUCCESS;
1467 /* the FO_RENAME files */
1468 static int rename_files(LPSHFILEOPSTRUCTW lpFileOp, const FILE_LIST *flFrom, const FILE_LIST *flTo)
1470 const FILE_ENTRY *feFrom;
1471 const FILE_ENTRY *feTo;
1473 if (flFrom->dwNumFiles != 1)
1474 return ERROR_GEN_FAILURE;
1476 if (flTo->dwNumFiles != 1)
1477 return ERROR_CANCELLED;
1479 feFrom = &flFrom->feFiles[0];
1480 feTo= &flTo->feFiles[0];
1482 /* fail if destination doesn't exist */
1483 if (!feFrom->bExists)
1484 return ERROR_SHELL_INTERNAL_FILE_NOT_FOUND;
1486 /* fail if destination already exists */
1487 if (feTo->bExists)
1488 return ERROR_ALREADY_EXISTS;
1490 return SHNotifyMoveFileW(feFrom->szFullPath, feTo->szFullPath);
1493 /* alert the user if an unsupported flag is used */
1494 static void check_flags(FILEOP_FLAGS fFlags)
1496 WORD wUnsupportedFlags = FOF_NO_CONNECTED_ELEMENTS |
1497 FOF_NOCOPYSECURITYATTRIBS | FOF_NORECURSEREPARSE |
1498 FOF_RENAMEONCOLLISION | FOF_WANTMAPPINGHANDLE;
1500 if (fFlags & wUnsupportedFlags)
1501 FIXME("Unsupported flags: %04x\n", fFlags);
1504 /*************************************************************************
1505 * SHFileOperationW [SHELL32.@]
1507 * See SHFileOperationA
1509 int WINAPI SHFileOperationW(LPSHFILEOPSTRUCTW lpFileOp)
1511 FILE_OPERATION op;
1512 FILE_LIST flFrom, flTo;
1513 int ret = 0;
1515 if (!lpFileOp)
1516 return ERROR_INVALID_PARAMETER;
1518 check_flags(lpFileOp->fFlags);
1520 ZeroMemory(&flFrom, sizeof(FILE_LIST));
1521 ZeroMemory(&flTo, sizeof(FILE_LIST));
1523 if ((ret = parse_file_list(&flFrom, lpFileOp->pFrom)))
1524 return ret;
1526 if (lpFileOp->wFunc != FO_DELETE)
1527 parse_file_list(&flTo, lpFileOp->pTo);
1529 ZeroMemory(&op, sizeof(op));
1530 op.req = lpFileOp;
1531 op.bManyItems = (flFrom.dwNumFiles > 1);
1532 lpFileOp->fAnyOperationsAborted = FALSE;
1534 switch (lpFileOp->wFunc)
1536 case FO_COPY:
1537 ret = copy_files(&op, &flFrom, &flTo);
1538 break;
1539 case FO_DELETE:
1540 ret = delete_files(lpFileOp, &flFrom);
1541 break;
1542 case FO_MOVE:
1543 ret = move_files(lpFileOp, &flFrom, &flTo);
1544 break;
1545 case FO_RENAME:
1546 ret = rename_files(lpFileOp, &flFrom, &flTo);
1547 break;
1548 default:
1549 ret = ERROR_INVALID_PARAMETER;
1550 break;
1553 destroy_file_list(&flFrom);
1555 if (lpFileOp->wFunc != FO_DELETE)
1556 destroy_file_list(&flTo);
1558 if (ret == ERROR_CANCELLED)
1559 lpFileOp->fAnyOperationsAborted = TRUE;
1561 SetLastError(ERROR_SUCCESS);
1562 return ret;
1565 #define SHDSA_GetItemCount(hdsa) (*(int*)(hdsa))
1567 /*************************************************************************
1568 * SHFreeNameMappings [shell32.246]
1570 * Free the mapping handle returned by SHFileOperation if FOF_WANTSMAPPINGHANDLE
1571 * was specified.
1573 * PARAMS
1574 * hNameMapping [I] handle to the name mappings used during renaming of files
1576 * RETURNS
1577 * Nothing
1579 void WINAPI SHFreeNameMappings(HANDLE hNameMapping)
1581 if (hNameMapping)
1583 int i = SHDSA_GetItemCount((HDSA)hNameMapping) - 1;
1585 for (; i>= 0; i--)
1587 LPSHNAMEMAPPINGW lp = DSA_GetItemPtr(hNameMapping, i);
1589 SHFree(lp->pszOldPath);
1590 SHFree(lp->pszNewPath);
1592 DSA_Destroy(hNameMapping);
1596 /*************************************************************************
1597 * SheGetDirA [SHELL32.@]
1599 * drive = 0: returns the current directory path
1600 * drive > 0: returns the current directory path of the specified drive
1601 * drive=1 -> A: drive=2 -> B: ...
1602 * returns 0 if successful
1604 DWORD WINAPI SheGetDirA(DWORD drive, LPSTR buffer)
1606 WCHAR org_path[MAX_PATH];
1607 DWORD ret;
1608 char drv_path[3];
1610 /* change current directory to the specified drive */
1611 if (drive) {
1612 strcpy(drv_path, "A:");
1613 drv_path[0] += (char)drive-1;
1615 GetCurrentDirectoryW(MAX_PATH, org_path);
1617 SetCurrentDirectoryA(drv_path);
1620 /* query current directory path of the specified drive */
1621 ret = GetCurrentDirectoryA(MAX_PATH, buffer);
1623 /* back to the original drive */
1624 if (drive)
1625 SetCurrentDirectoryW(org_path);
1627 if (!ret)
1628 return GetLastError();
1630 return 0;
1633 /*************************************************************************
1634 * SheGetDirW [SHELL32.@]
1636 * drive = 0: returns the current directory path
1637 * drive > 0: returns the current directory path of the specified drive
1638 * drive=1 -> A: drive=2 -> B: ...
1639 * returns 0 if successful
1641 DWORD WINAPI SheGetDirW(DWORD drive, LPWSTR buffer)
1643 WCHAR org_path[MAX_PATH];
1644 DWORD ret;
1645 char drv_path[3];
1647 /* change current directory to the specified drive */
1648 if (drive) {
1649 strcpy(drv_path, "A:");
1650 drv_path[0] += (char)drive-1;
1652 GetCurrentDirectoryW(MAX_PATH, org_path);
1654 SetCurrentDirectoryA(drv_path);
1657 /* query current directory path of the specified drive */
1658 ret = GetCurrentDirectoryW(MAX_PATH, buffer);
1660 /* back to the original drive */
1661 if (drive)
1662 SetCurrentDirectoryW(org_path);
1664 if (!ret)
1665 return GetLastError();
1667 return 0;
1670 /*************************************************************************
1671 * SheChangeDirA [SHELL32.@]
1673 * changes the current directory to the specified path
1674 * and returns 0 if successful
1676 DWORD WINAPI SheChangeDirA(LPSTR path)
1678 if (SetCurrentDirectoryA(path))
1679 return 0;
1680 else
1681 return GetLastError();
1684 /*************************************************************************
1685 * SheChangeDirW [SHELL32.@]
1687 * changes the current directory to the specified path
1688 * and returns 0 if successful
1690 DWORD WINAPI SheChangeDirW(LPWSTR path)
1692 if (SetCurrentDirectoryW(path))
1693 return 0;
1694 else
1695 return GetLastError();
1698 /*************************************************************************
1699 * IsNetDrive [SHELL32.66]
1701 int WINAPI IsNetDrive(int drive)
1703 char root[4];
1704 strcpy(root, "A:\\");
1705 root[0] += (char)drive;
1706 return (GetDriveTypeA(root) == DRIVE_REMOTE);
1710 /*************************************************************************
1711 * RealDriveType [SHELL32.524]
1713 int WINAPI RealDriveType(int drive, BOOL bQueryNet)
1715 char root[] = "A:\\";
1716 root[0] += (char)drive;
1717 return GetDriveTypeA(root);
1720 /***********************************************************************
1721 * SHPathPrepareForWriteA (SHELL32.@)
1723 HRESULT WINAPI SHPathPrepareForWriteA(HWND hwnd, IUnknown *modless, LPCSTR path, DWORD flags)
1725 WCHAR wpath[MAX_PATH];
1726 MultiByteToWideChar( CP_ACP, 0, path, -1, wpath, MAX_PATH);
1727 return SHPathPrepareForWriteW(hwnd, modless, wpath, flags);
1730 /***********************************************************************
1731 * SHPathPrepareForWriteW (SHELL32.@)
1733 HRESULT WINAPI SHPathPrepareForWriteW(HWND hwnd, IUnknown *modless, LPCWSTR path, DWORD flags)
1735 DWORD res;
1736 DWORD err;
1737 LPCWSTR realpath;
1738 int len;
1739 WCHAR* last_slash;
1740 WCHAR* temppath=NULL;
1742 TRACE("%p %p %s 0x%08x\n", hwnd, modless, debugstr_w(path), flags);
1744 if (flags & ~(SHPPFW_DIRCREATE|SHPPFW_ASKDIRCREATE|SHPPFW_IGNOREFILENAME))
1745 FIXME("unimplemented flags 0x%08x\n", flags);
1747 /* cut off filename if necessary */
1748 if (flags & SHPPFW_IGNOREFILENAME)
1750 last_slash = StrRChrW(path, NULL, '\\');
1751 if (last_slash == NULL)
1752 len = 1;
1753 else
1754 len = last_slash - path + 1;
1755 temppath = heap_alloc(len * sizeof(WCHAR));
1756 if (!temppath)
1757 return E_OUTOFMEMORY;
1758 StrCpyNW(temppath, path, len);
1759 realpath = temppath;
1761 else
1763 realpath = path;
1766 /* try to create the directory if asked to */
1767 if (flags & (SHPPFW_DIRCREATE|SHPPFW_ASKDIRCREATE))
1769 if (flags & SHPPFW_ASKDIRCREATE)
1770 FIXME("treating SHPPFW_ASKDIRCREATE as SHPPFW_DIRCREATE\n");
1772 SHCreateDirectoryExW(0, realpath, NULL);
1775 /* check if we can access the directory */
1776 res = GetFileAttributesW(realpath);
1778 heap_free(temppath);
1780 if (res == INVALID_FILE_ATTRIBUTES)
1782 err = GetLastError();
1783 if (err == ERROR_FILE_NOT_FOUND)
1784 return HRESULT_FROM_WIN32(ERROR_PATH_NOT_FOUND);
1785 return HRESULT_FROM_WIN32(err);
1787 else if (res & FILE_ATTRIBUTE_DIRECTORY)
1788 return S_OK;
1789 else
1790 return HRESULT_FROM_WIN32(ERROR_DIRECTORY);