dpnet/tests: Add a trailing '\n' to some ok() calls.
[wine.git] / dlls / shell32 / shlfileop.c
blob62d788088b0fcca05f8c8ae8dea9b3090bc3f16e
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;
126 GetClientRect(GetDlgItem(hDlg, IDD_MESSAGE), &r);
127 /* this will remap the rect to dialog coords */
128 MapWindowPoints(GetDlgItem(hDlg, IDD_MESSAGE), hDlg, (LPPOINT)&r, 2);
129 hOldFont = SelectObject(hdc, (HFONT)SendDlgItemMessageW(hDlg, IDD_MESSAGE, WM_GETFONT, 0, 0));
130 DrawTextW(hdc, GetPropW(hDlg, CONFIRM_MSG_PROP), -1, &r, DT_NOPREFIX | DT_PATH_ELLIPSIS | DT_WORDBREAK);
131 SelectObject(hdc, hOldFont);
132 EndPaint(hDlg, &ps);
133 return TRUE;
136 static INT_PTR ConfirmMsgBox_Init(HWND hDlg, LPARAM lParam)
138 struct confirm_msg_info *info = (struct confirm_msg_info *)lParam;
139 INT xPos, yOffset;
140 int width, height;
141 HFONT hOldFont;
142 HDC hdc;
143 RECT r;
145 SetWindowTextW(hDlg, info->lpszCaption);
146 ShowWindow(GetDlgItem(hDlg, IDD_MESSAGE), SW_HIDE);
147 SetPropW(hDlg, CONFIRM_MSG_PROP, info->lpszText);
148 SendDlgItemMessageW(hDlg, IDD_ICON, STM_SETICON, (WPARAM)info->hIcon, 0);
150 /* compute the text height and resize the dialog */
151 GetClientRect(GetDlgItem(hDlg, IDD_MESSAGE), &r);
152 hdc = GetDC(hDlg);
153 yOffset = r.bottom;
154 hOldFont = SelectObject(hdc, (HFONT)SendDlgItemMessageW(hDlg, IDD_MESSAGE, WM_GETFONT, 0, 0));
155 DrawTextW(hdc, info->lpszText, -1, &r, DT_NOPREFIX | DT_PATH_ELLIPSIS | DT_WORDBREAK | DT_CALCRECT);
156 SelectObject(hdc, hOldFont);
157 yOffset -= r.bottom;
158 yOffset = min(yOffset, 35); /* don't make the dialog too small */
159 ReleaseDC(hDlg, hdc);
161 GetClientRect(hDlg, &r);
162 xPos = r.right - 7;
163 GetWindowRect(hDlg, &r);
164 width = r.right - r.left;
165 height = r.bottom - r.top - yOffset;
166 MoveWindow(hDlg, (GetSystemMetrics(SM_CXSCREEN) - width)/2,
167 (GetSystemMetrics(SM_CYSCREEN) - height)/2, width, height, FALSE);
169 confirm_msg_move_button(hDlg, IDCANCEL, &xPos, yOffset, info->bYesToAll);
170 confirm_msg_move_button(hDlg, IDNO, &xPos, yOffset, TRUE);
171 confirm_msg_move_button(hDlg, IDD_YESTOALL, &xPos, yOffset, info->bYesToAll);
172 confirm_msg_move_button(hDlg, IDYES, &xPos, yOffset, TRUE);
173 return TRUE;
176 static INT_PTR CALLBACK ConfirmMsgBoxProc(HWND hDlg, UINT uMsg, WPARAM wParam, LPARAM lParam)
178 switch (uMsg)
180 case WM_INITDIALOG:
181 return ConfirmMsgBox_Init(hDlg, lParam);
182 case WM_PAINT:
183 return ConfirmMsgBox_Paint(hDlg);
184 case WM_COMMAND:
185 EndDialog(hDlg, wParam);
186 break;
187 case WM_CLOSE:
188 EndDialog(hDlg, IDCANCEL);
189 break;
191 return FALSE;
194 static int SHELL_ConfirmMsgBox(HWND hWnd, LPWSTR lpszText, LPWSTR lpszCaption, HICON hIcon, BOOL bYesToAll)
196 static const WCHAR wszTemplate[] = {'S','H','E','L','L','_','Y','E','S','T','O','A','L','L','_','M','S','G','B','O','X',0};
197 struct confirm_msg_info info;
199 info.lpszText = lpszText;
200 info.lpszCaption = lpszCaption;
201 info.hIcon = hIcon;
202 info.bYesToAll = bYesToAll;
203 return DialogBoxParamW(shell32_hInstance, wszTemplate, hWnd, ConfirmMsgBoxProc, (LPARAM)&info);
206 /* confirmation dialogs content */
207 typedef struct
209 HINSTANCE hIconInstance;
210 UINT icon_resource_id;
211 UINT caption_resource_id, text_resource_id;
212 } SHELL_ConfirmIDstruc;
214 static BOOL SHELL_ConfirmIDs(int nKindOfDialog, SHELL_ConfirmIDstruc *ids)
216 ids->hIconInstance = shell32_hInstance;
217 switch (nKindOfDialog) {
218 case ASK_DELETE_FILE:
219 ids->icon_resource_id = IDI_SHELL_CONFIRM_DELETE;
220 ids->caption_resource_id = IDS_DELETEITEM_CAPTION;
221 ids->text_resource_id = IDS_DELETEITEM_TEXT;
222 return TRUE;
223 case ASK_DELETE_FOLDER:
224 ids->icon_resource_id = IDI_SHELL_CONFIRM_DELETE;
225 ids->caption_resource_id = IDS_DELETEFOLDER_CAPTION;
226 ids->text_resource_id = IDS_DELETEITEM_TEXT;
227 return TRUE;
228 case ASK_DELETE_MULTIPLE_ITEM:
229 ids->icon_resource_id = IDI_SHELL_CONFIRM_DELETE;
230 ids->caption_resource_id = IDS_DELETEITEM_CAPTION;
231 ids->text_resource_id = IDS_DELETEMULTIPLE_TEXT;
232 return TRUE;
233 case ASK_TRASH_FILE:
234 ids->icon_resource_id = IDI_SHELL_TRASH_FILE;
235 ids->caption_resource_id = IDS_DELETEITEM_CAPTION;
236 ids->text_resource_id = IDS_TRASHITEM_TEXT;
237 return TRUE;
238 case ASK_TRASH_FOLDER:
239 ids->icon_resource_id = IDI_SHELL_TRASH_FILE;
240 ids->caption_resource_id = IDS_DELETEFOLDER_CAPTION;
241 ids->text_resource_id = IDS_TRASHFOLDER_TEXT;
242 return TRUE;
243 case ASK_TRASH_MULTIPLE_ITEM:
244 ids->icon_resource_id = IDI_SHELL_TRASH_FILE;
245 ids->caption_resource_id = IDS_DELETEITEM_CAPTION;
246 ids->text_resource_id = IDS_TRASHMULTIPLE_TEXT;
247 return TRUE;
248 case ASK_CANT_TRASH_ITEM:
249 ids->icon_resource_id = IDI_SHELL_CONFIRM_DELETE;
250 ids->caption_resource_id = IDS_DELETEITEM_CAPTION;
251 ids->text_resource_id = IDS_CANTTRASH_TEXT;
252 return TRUE;
253 case ASK_DELETE_SELECTED:
254 ids->icon_resource_id = IDI_SHELL_CONFIRM_DELETE;
255 ids->caption_resource_id = IDS_DELETEITEM_CAPTION;
256 ids->text_resource_id = IDS_DELETESELECTED_TEXT;
257 return TRUE;
258 case ASK_OVERWRITE_FILE:
259 ids->hIconInstance = NULL;
260 ids->icon_resource_id = IDI_WARNING;
261 ids->caption_resource_id = IDS_OVERWRITEFILE_CAPTION;
262 ids->text_resource_id = IDS_OVERWRITEFILE_TEXT;
263 return TRUE;
264 case ASK_OVERWRITE_FOLDER:
265 ids->hIconInstance = NULL;
266 ids->icon_resource_id = IDI_WARNING;
267 ids->caption_resource_id = IDS_OVERWRITEFILE_CAPTION;
268 ids->text_resource_id = IDS_OVERWRITEFOLDER_TEXT;
269 return TRUE;
270 default:
271 FIXME(" Unhandled nKindOfDialog %d stub\n", nKindOfDialog);
273 return FALSE;
276 static BOOL SHELL_ConfirmDialogW(HWND hWnd, int nKindOfDialog, LPCWSTR szDir, FILE_OPERATION *op)
278 WCHAR szCaption[255], szText[255], szBuffer[MAX_PATH + 256];
279 SHELL_ConfirmIDstruc ids;
280 DWORD_PTR args[1];
281 HICON hIcon;
282 int ret;
284 assert(nKindOfDialog >= 0 && nKindOfDialog < 32);
285 if (op && (op->dwYesToAllMask & (1 << nKindOfDialog)))
286 return TRUE;
288 if (!SHELL_ConfirmIDs(nKindOfDialog, &ids)) return FALSE;
290 LoadStringW(shell32_hInstance, ids.caption_resource_id, szCaption, sizeof(szCaption)/sizeof(WCHAR));
291 LoadStringW(shell32_hInstance, ids.text_resource_id, szText, sizeof(szText)/sizeof(WCHAR));
293 args[0] = (DWORD_PTR)szDir;
294 FormatMessageW(FORMAT_MESSAGE_FROM_STRING|FORMAT_MESSAGE_ARGUMENT_ARRAY,
295 szText, 0, 0, szBuffer, sizeof(szBuffer), (__ms_va_list*)args);
296 hIcon = LoadIconW(ids.hIconInstance, (LPWSTR)MAKEINTRESOURCE(ids.icon_resource_id));
298 ret = SHELL_ConfirmMsgBox(hWnd, szBuffer, szCaption, hIcon, op && op->bManyItems);
299 if (op) {
300 if (ret == IDD_YESTOALL) {
301 op->dwYesToAllMask |= (1 << nKindOfDialog);
302 ret = IDYES;
304 if (ret == IDCANCEL)
305 op->bCancelled = TRUE;
306 if (ret != IDYES)
307 op->req->fAnyOperationsAborted = TRUE;
309 return ret == IDYES;
312 BOOL SHELL_ConfirmYesNoW(HWND hWnd, int nKindOfDialog, LPCWSTR szDir)
314 return SHELL_ConfirmDialogW(hWnd, nKindOfDialog, szDir, NULL);
317 static DWORD SHELL32_AnsiToUnicodeBuf(LPCSTR aPath, LPWSTR *wPath, DWORD minChars)
319 DWORD len = MultiByteToWideChar(CP_ACP, 0, aPath, -1, NULL, 0);
321 if (len < minChars)
322 len = minChars;
324 *wPath = HeapAlloc(GetProcessHeap(), 0, len * sizeof(WCHAR));
325 if (*wPath)
327 MultiByteToWideChar(CP_ACP, 0, aPath, -1, *wPath, len);
328 return NO_ERROR;
330 return E_OUTOFMEMORY;
333 static void SHELL32_FreeUnicodeBuf(LPWSTR wPath)
335 HeapFree(GetProcessHeap(), 0, wPath);
338 HRESULT WINAPI SHIsFileAvailableOffline(LPCWSTR path, LPDWORD status)
340 FIXME("(%s, %p) stub\n", debugstr_w(path), status);
341 return E_FAIL;
344 /**************************************************************************
345 * SHELL_DeleteDirectory() [internal]
347 * Asks for confirmation when bShowUI is true and deletes the directory and
348 * all its subdirectories and files if necessary.
350 static DWORD SHELL_DeleteDirectoryW(HWND hwnd, LPCWSTR pszDir, BOOL bShowUI)
352 DWORD ret = 0;
353 HANDLE hFind;
354 WIN32_FIND_DATAW wfd;
355 WCHAR szTemp[MAX_PATH];
357 PathCombineW(szTemp, pszDir, wWildcardFile);
358 hFind = FindFirstFileW(szTemp, &wfd);
360 if (hFind != INVALID_HANDLE_VALUE) {
361 if (!bShowUI || SHELL_ConfirmDialogW(hwnd, ASK_DELETE_FOLDER, pszDir, NULL)) {
362 do {
363 if (IsDotDir(wfd.cFileName))
364 continue;
365 PathCombineW(szTemp, pszDir, wfd.cFileName);
366 if (FILE_ATTRIBUTE_DIRECTORY & wfd.dwFileAttributes)
367 ret = SHELL_DeleteDirectoryW(hwnd, szTemp, FALSE);
368 else
369 ret = SHNotifyDeleteFileW(szTemp);
370 } while (!ret && FindNextFileW(hFind, &wfd));
372 FindClose(hFind);
374 if (ret == ERROR_SUCCESS)
375 ret = SHNotifyRemoveDirectoryW(pszDir);
377 return ret == ERROR_PATH_NOT_FOUND ?
378 0x7C: /* DE_INVALIDFILES (legacy Windows error) */
379 ret;
382 /**************************************************************************
383 * Win32CreateDirectory [SHELL32.93]
385 * Creates a directory. Also triggers a change notify if one exists.
387 * PARAMS
388 * path [I] path to directory to create
390 * RETURNS
391 * TRUE if successful, FALSE otherwise
393 * NOTES
394 * Verified on Win98 / IE 5 (SHELL32 4.72, March 1999 build) to be ANSI.
395 * This is Unicode on NT/2000
397 static DWORD SHNotifyCreateDirectoryA(LPCSTR path, LPSECURITY_ATTRIBUTES sec)
399 LPWSTR wPath;
400 DWORD retCode;
402 TRACE("(%s, %p)\n", debugstr_a(path), sec);
404 retCode = SHELL32_AnsiToUnicodeBuf(path, &wPath, 0);
405 if (!retCode)
407 retCode = SHNotifyCreateDirectoryW(wPath, sec);
408 SHELL32_FreeUnicodeBuf(wPath);
410 return retCode;
413 /**********************************************************************/
415 static DWORD SHNotifyCreateDirectoryW(LPCWSTR path, LPSECURITY_ATTRIBUTES sec)
417 TRACE("(%s, %p)\n", debugstr_w(path), sec);
419 if (CreateDirectoryW(path, sec))
421 SHChangeNotify(SHCNE_MKDIR, SHCNF_PATHW, path, NULL);
422 return ERROR_SUCCESS;
424 return GetLastError();
427 /**********************************************************************/
429 BOOL WINAPI Win32CreateDirectoryAW(LPCVOID path, LPSECURITY_ATTRIBUTES sec)
431 if (SHELL_OsIsUnicode())
432 return (SHNotifyCreateDirectoryW(path, sec) == ERROR_SUCCESS);
433 return (SHNotifyCreateDirectoryA(path, sec) == ERROR_SUCCESS);
436 /************************************************************************
437 * Win32RemoveDirectory [SHELL32.94]
439 * Deletes a directory. Also triggers a change notify if one exists.
441 * PARAMS
442 * path [I] path to directory to delete
444 * RETURNS
445 * TRUE if successful, FALSE otherwise
447 * NOTES
448 * Verified on Win98 / IE 5 (SHELL32 4.72, March 1999 build) to be ANSI.
449 * This is Unicode on NT/2000
451 static DWORD SHNotifyRemoveDirectoryA(LPCSTR path)
453 LPWSTR wPath;
454 DWORD retCode;
456 TRACE("(%s)\n", debugstr_a(path));
458 retCode = SHELL32_AnsiToUnicodeBuf(path, &wPath, 0);
459 if (!retCode)
461 retCode = SHNotifyRemoveDirectoryW(wPath);
462 SHELL32_FreeUnicodeBuf(wPath);
464 return retCode;
467 /***********************************************************************/
469 static DWORD SHNotifyRemoveDirectoryW(LPCWSTR path)
471 BOOL ret;
472 TRACE("(%s)\n", debugstr_w(path));
474 ret = RemoveDirectoryW(path);
475 if (!ret)
477 /* Directory may be write protected */
478 DWORD dwAttr = GetFileAttributesW(path);
479 if (IsAttrib(dwAttr, FILE_ATTRIBUTE_READONLY))
480 if (SetFileAttributesW(path, dwAttr & ~FILE_ATTRIBUTE_READONLY))
481 ret = RemoveDirectoryW(path);
483 if (ret)
485 SHChangeNotify(SHCNE_RMDIR, SHCNF_PATHW, path, NULL);
486 return ERROR_SUCCESS;
488 return GetLastError();
491 /***********************************************************************/
493 BOOL WINAPI Win32RemoveDirectoryAW(LPCVOID path)
495 if (SHELL_OsIsUnicode())
496 return (SHNotifyRemoveDirectoryW(path) == ERROR_SUCCESS);
497 return (SHNotifyRemoveDirectoryA(path) == ERROR_SUCCESS);
500 /************************************************************************
501 * Win32DeleteFile [SHELL32.164]
503 * Deletes a file. Also triggers a change notify if one exists.
505 * PARAMS
506 * path [I] path to file to delete
508 * RETURNS
509 * TRUE if successful, FALSE otherwise
511 * NOTES
512 * Verified on Win98 / IE 5 (SHELL32 4.72, March 1999 build) to be ANSI.
513 * This is Unicode on NT/2000
515 static DWORD SHNotifyDeleteFileA(LPCSTR path)
517 LPWSTR wPath;
518 DWORD retCode;
520 TRACE("(%s)\n", debugstr_a(path));
522 retCode = SHELL32_AnsiToUnicodeBuf(path, &wPath, 0);
523 if (!retCode)
525 retCode = SHNotifyDeleteFileW(wPath);
526 SHELL32_FreeUnicodeBuf(wPath);
528 return retCode;
531 /***********************************************************************/
533 static DWORD SHNotifyDeleteFileW(LPCWSTR path)
535 BOOL ret;
537 TRACE("(%s)\n", debugstr_w(path));
539 ret = DeleteFileW(path);
540 if (!ret)
542 /* File may be write protected or a system file */
543 DWORD dwAttr = GetFileAttributesW(path);
544 if (IsAttrib(dwAttr, FILE_ATTRIBUTE_READONLY | FILE_ATTRIBUTE_SYSTEM))
545 if (SetFileAttributesW(path, dwAttr & ~(FILE_ATTRIBUTE_READONLY | FILE_ATTRIBUTE_SYSTEM)))
546 ret = DeleteFileW(path);
548 if (ret)
550 SHChangeNotify(SHCNE_DELETE, SHCNF_PATHW, path, NULL);
551 return ERROR_SUCCESS;
553 return GetLastError();
556 /***********************************************************************/
558 DWORD WINAPI Win32DeleteFileAW(LPCVOID path)
560 if (SHELL_OsIsUnicode())
561 return (SHNotifyDeleteFileW(path) == ERROR_SUCCESS);
562 return (SHNotifyDeleteFileA(path) == ERROR_SUCCESS);
565 /************************************************************************
566 * SHNotifyMoveFile [internal]
568 * Moves a file. Also triggers a change notify if one exists.
570 * PARAMS
571 * src [I] path to source file to move
572 * dest [I] path to target file to move to
574 * RETURNS
575 * ERORR_SUCCESS if successful
577 static DWORD SHNotifyMoveFileW(LPCWSTR src, LPCWSTR dest)
579 BOOL ret;
581 TRACE("(%s %s)\n", debugstr_w(src), debugstr_w(dest));
583 ret = MoveFileExW(src, dest, MOVEFILE_REPLACE_EXISTING);
585 /* MOVEFILE_REPLACE_EXISTING fails with dirs, so try MoveFile */
586 if (!ret)
587 ret = MoveFileW(src, dest);
589 if (!ret)
591 DWORD dwAttr;
593 dwAttr = SHFindAttrW(dest, FALSE);
594 if (INVALID_FILE_ATTRIBUTES == dwAttr)
596 /* Source file may be write protected or a system file */
597 dwAttr = GetFileAttributesW(src);
598 if (IsAttrib(dwAttr, FILE_ATTRIBUTE_READONLY | FILE_ATTRIBUTE_SYSTEM))
599 if (SetFileAttributesW(src, dwAttr & ~(FILE_ATTRIBUTE_READONLY | FILE_ATTRIBUTE_SYSTEM)))
600 ret = MoveFileW(src, dest);
603 if (ret)
605 SHChangeNotify(SHCNE_RENAMEITEM, SHCNF_PATHW, src, dest);
606 return ERROR_SUCCESS;
608 return GetLastError();
611 /************************************************************************
612 * SHNotifyCopyFile [internal]
614 * Copies a file. Also triggers a change notify if one exists.
616 * PARAMS
617 * src [I] path to source file to move
618 * dest [I] path to target file to move to
619 * bFailIfExists [I] if TRUE, the target file will not be overwritten if
620 * a file with this name already exists
622 * RETURNS
623 * ERROR_SUCCESS if successful
625 static DWORD SHNotifyCopyFileW(LPCWSTR src, LPCWSTR dest, BOOL bFailIfExists)
627 BOOL ret;
628 DWORD attribs;
630 TRACE("(%s %s %s)\n", debugstr_w(src), debugstr_w(dest), bFailIfExists ? "failIfExists" : "");
632 /* Destination file may already exist with read only attribute */
633 attribs = GetFileAttributesW(dest);
634 if (IsAttrib(attribs, FILE_ATTRIBUTE_READONLY))
635 SetFileAttributesW(dest, attribs & ~FILE_ATTRIBUTE_READONLY);
637 ret = CopyFileW(src, dest, bFailIfExists);
638 if (ret)
640 SHChangeNotify(SHCNE_CREATE, SHCNF_PATHW, dest, NULL);
641 return ERROR_SUCCESS;
644 return GetLastError();
647 /*************************************************************************
648 * SHCreateDirectory [SHELL32.165]
650 * This function creates a file system folder whose fully qualified path is
651 * given by path. If one or more of the intermediate folders do not exist,
652 * they will be created as well.
654 * PARAMS
655 * hWnd [I]
656 * path [I] path of directory to create
658 * RETURNS
659 * ERROR_SUCCESS or one of the following values:
660 * ERROR_BAD_PATHNAME if the path is relative
661 * ERROR_FILE_EXISTS when a file with that name exists
662 * ERROR_PATH_NOT_FOUND can't find the path, probably invalid
663 * ERROR_INVALID_NAME if the path contains invalid chars
664 * ERROR_ALREADY_EXISTS when the directory already exists
665 * ERROR_FILENAME_EXCED_RANGE if the filename was to long to process
667 * NOTES
668 * exported by ordinal
669 * Win9x exports ANSI
670 * WinNT/2000 exports Unicode
672 DWORD WINAPI SHCreateDirectory(HWND hWnd, LPCVOID path)
674 if (SHELL_OsIsUnicode())
675 return SHCreateDirectoryExW(hWnd, path, NULL);
676 return SHCreateDirectoryExA(hWnd, path, NULL);
679 /*************************************************************************
680 * SHCreateDirectoryExA [SHELL32.@]
682 * This function creates a file system folder whose fully qualified path is
683 * given by path. If one or more of the intermediate folders do not exist,
684 * they will be created as well.
686 * PARAMS
687 * hWnd [I]
688 * path [I] path of directory to create
689 * sec [I] security attributes to use or NULL
691 * RETURNS
692 * ERROR_SUCCESS or one of the following values:
693 * ERROR_BAD_PATHNAME or ERROR_PATH_NOT_FOUND if the path is relative
694 * ERROR_INVALID_NAME if the path contains invalid chars
695 * ERROR_FILE_EXISTS when a file with that name exists
696 * ERROR_ALREADY_EXISTS when the directory already exists
697 * ERROR_FILENAME_EXCED_RANGE if the filename was to long to process
699 * FIXME: Not implemented yet;
700 * SHCreateDirectoryEx also verifies that the files in the directory will be visible
701 * if the path is a network path to deal with network drivers which might have a limited
702 * but unknown maximum path length. If not:
704 * If hWnd is set to a valid window handle, a message box is displayed warning
705 * the user that the files may not be accessible. If the user chooses not to
706 * proceed, the function returns ERROR_CANCELLED.
708 * If hWnd is set to NULL, no user interface is displayed and the function
709 * returns ERROR_CANCELLED.
711 int WINAPI SHCreateDirectoryExA(HWND hWnd, LPCSTR path, LPSECURITY_ATTRIBUTES sec)
713 LPWSTR wPath;
714 DWORD retCode;
716 TRACE("(%s, %p)\n", debugstr_a(path), sec);
718 retCode = SHELL32_AnsiToUnicodeBuf(path, &wPath, 0);
719 if (!retCode)
721 retCode = SHCreateDirectoryExW(hWnd, wPath, sec);
722 SHELL32_FreeUnicodeBuf(wPath);
724 return retCode;
727 /*************************************************************************
728 * SHCreateDirectoryExW [SHELL32.@]
730 * See SHCreateDirectoryExA.
732 int WINAPI SHCreateDirectoryExW(HWND hWnd, LPCWSTR path, LPSECURITY_ATTRIBUTES sec)
734 int ret = ERROR_BAD_PATHNAME;
735 TRACE("(%p, %s, %p)\n", hWnd, debugstr_w(path), sec);
737 if (PathIsRelativeW(path))
739 SetLastError(ret);
741 else
743 ret = SHNotifyCreateDirectoryW(path, sec);
744 /* Refuse to work on certain error codes before trying to create directories recursively */
745 if (ret != ERROR_SUCCESS &&
746 ret != ERROR_FILE_EXISTS &&
747 ret != ERROR_ALREADY_EXISTS &&
748 ret != ERROR_FILENAME_EXCED_RANGE)
750 WCHAR *pEnd, *pSlash, szTemp[MAX_PATH + 1]; /* extra for PathAddBackslash() */
752 lstrcpynW(szTemp, path, MAX_PATH);
753 pEnd = PathAddBackslashW(szTemp);
754 pSlash = szTemp + 3;
756 while (*pSlash)
758 while (*pSlash && *pSlash != '\\') pSlash++;
759 if (*pSlash)
761 *pSlash = 0; /* terminate path at separator */
763 ret = SHNotifyCreateDirectoryW(szTemp, pSlash + 1 == pEnd ? sec : NULL);
765 *pSlash++ = '\\'; /* put the separator back */
769 if (ret && hWnd && (ERROR_CANCELLED != ret))
771 /* We failed and should show a dialog box */
772 FIXME("Show system error message, creating path %s, failed with error %d\n", debugstr_w(path), ret);
773 ret = ERROR_CANCELLED; /* Error has been already presented to user (not really yet!) */
776 return ret;
779 /*************************************************************************
780 * SHFindAttrW [internal]
782 * Get the Attributes for a file or directory. The difference to GetAttributes()
783 * is that this function will also work for paths containing wildcard characters
784 * in its filename.
786 * PARAMS
787 * path [I] path of directory or file to check
788 * fileOnly [I] TRUE if only files should be found
790 * RETURNS
791 * INVALID_FILE_ATTRIBUTES if the path does not exist, the actual attributes of
792 * the first file or directory found otherwise
794 static DWORD SHFindAttrW(LPCWSTR pName, BOOL fileOnly)
796 WIN32_FIND_DATAW wfd;
797 BOOL b_FileMask = fileOnly && (NULL != StrPBrkW(pName, wWildcardChars));
798 DWORD dwAttr = INVALID_FILE_ATTRIBUTES;
799 HANDLE hFind = FindFirstFileW(pName, &wfd);
801 TRACE("%s %d\n", debugstr_w(pName), fileOnly);
802 if (INVALID_HANDLE_VALUE != hFind)
806 if (b_FileMask && IsAttribDir(wfd.dwFileAttributes))
807 continue;
808 dwAttr = wfd.dwFileAttributes;
809 break;
811 while (FindNextFileW(hFind, &wfd));
812 FindClose(hFind);
814 return dwAttr;
817 /*************************************************************************
819 * SHNameTranslate HelperFunction for SHFileOperationA
821 * Translates a list of 0 terminated ASCII strings into Unicode. If *wString
822 * is NULL, only the necessary size of the string is determined and returned,
823 * otherwise the ASCII strings are copied into it and the buffer is increased
824 * to point to the location after the final 0 termination char.
826 static DWORD SHNameTranslate(LPWSTR* wString, LPCWSTR* pWToFrom, BOOL more)
828 DWORD size = 0, aSize = 0;
829 LPCSTR aString = (LPCSTR)*pWToFrom;
831 if (aString)
835 size = lstrlenA(aString) + 1;
836 aSize += size;
837 aString += size;
838 } while ((size != 1) && more);
839 /* The two sizes might be different in the case of multibyte chars */
840 size = MultiByteToWideChar(CP_ACP, 0, (LPCSTR)*pWToFrom, aSize, *wString, 0);
841 if (*wString) /* only in the second loop */
843 MultiByteToWideChar(CP_ACP, 0, (LPCSTR)*pWToFrom, aSize, *wString, size);
844 *pWToFrom = *wString;
845 *wString += size;
848 return size;
850 /*************************************************************************
851 * SHFileOperationA [SHELL32.@]
853 * Function to copy, move, delete and create one or more files with optional
854 * user prompts.
856 * PARAMS
857 * lpFileOp [I/O] pointer to a structure containing all the necessary information
859 * RETURNS
860 * Success: ERROR_SUCCESS.
861 * Failure: ERROR_CANCELLED.
863 * NOTES
864 * exported by name
866 int WINAPI SHFileOperationA(LPSHFILEOPSTRUCTA lpFileOp)
868 SHFILEOPSTRUCTW nFileOp = *((LPSHFILEOPSTRUCTW)lpFileOp);
869 int retCode = 0;
870 DWORD size;
871 LPWSTR ForFree = NULL, /* we change wString in SHNameTranslate and can't use it for freeing */
872 wString = NULL; /* we change this in SHNameTranslate */
874 TRACE("\n");
875 if (FO_DELETE == (nFileOp.wFunc & FO_MASK))
876 nFileOp.pTo = NULL; /* we need a NULL or a valid pointer for translation */
877 if (!(nFileOp.fFlags & FOF_SIMPLEPROGRESS))
878 nFileOp.lpszProgressTitle = NULL; /* we need a NULL or a valid pointer for translation */
879 while (1) /* every loop calculate size, second translate also, if we have storage for this */
881 size = SHNameTranslate(&wString, &nFileOp.lpszProgressTitle, FALSE); /* no loop */
882 size += SHNameTranslate(&wString, &nFileOp.pFrom, TRUE); /* internal loop */
883 size += SHNameTranslate(&wString, &nFileOp.pTo, TRUE); /* internal loop */
885 if (ForFree)
887 retCode = SHFileOperationW(&nFileOp);
888 HeapFree(GetProcessHeap(), 0, ForFree); /* we cannot use wString, it was changed */
889 break;
891 else
893 wString = ForFree = HeapAlloc(GetProcessHeap(), 0, size * sizeof(WCHAR));
894 if (ForFree) continue;
895 retCode = ERROR_OUTOFMEMORY;
896 nFileOp.fAnyOperationsAborted = TRUE;
897 SetLastError(retCode);
898 return retCode;
902 lpFileOp->hNameMappings = nFileOp.hNameMappings;
903 lpFileOp->fAnyOperationsAborted = nFileOp.fAnyOperationsAborted;
904 return retCode;
907 #define ERROR_SHELL_INTERNAL_FILE_NOT_FOUND 1026
909 typedef struct
911 DWORD attributes;
912 LPWSTR szDirectory;
913 LPWSTR szFilename;
914 LPWSTR szFullPath;
915 BOOL bFromWildcard;
916 BOOL bFromRelative;
917 BOOL bExists;
918 } FILE_ENTRY;
920 typedef struct
922 FILE_ENTRY *feFiles;
923 DWORD num_alloc;
924 DWORD dwNumFiles;
925 BOOL bAnyFromWildcard;
926 BOOL bAnyDirectories;
927 BOOL bAnyDontExist;
928 } FILE_LIST;
931 static inline void grow_list(FILE_LIST *list)
933 FILE_ENTRY *new = HeapReAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, list->feFiles,
934 list->num_alloc * 2 * sizeof(*new) );
935 list->feFiles = new;
936 list->num_alloc *= 2;
939 /* adds a file to the FILE_ENTRY struct
941 static void add_file_to_entry(FILE_ENTRY *feFile, LPCWSTR szFile)
943 DWORD dwLen = lstrlenW(szFile) + 1;
944 LPCWSTR ptr;
946 feFile->szFullPath = HeapAlloc(GetProcessHeap(), 0, dwLen * sizeof(WCHAR));
947 lstrcpyW(feFile->szFullPath, szFile);
949 ptr = StrRChrW(szFile, NULL, '\\');
950 if (ptr)
952 dwLen = ptr - szFile + 1;
953 feFile->szDirectory = HeapAlloc(GetProcessHeap(), 0, dwLen * sizeof(WCHAR));
954 lstrcpynW(feFile->szDirectory, szFile, dwLen);
956 dwLen = lstrlenW(feFile->szFullPath) - dwLen + 1;
957 feFile->szFilename = HeapAlloc(GetProcessHeap(), 0, dwLen * sizeof(WCHAR));
958 lstrcpyW(feFile->szFilename, ptr + 1); /* skip over backslash */
960 feFile->bFromWildcard = FALSE;
963 static LPWSTR wildcard_to_file(LPCWSTR szWildCard, LPCWSTR szFileName)
965 LPCWSTR ptr;
966 LPWSTR szFullPath;
967 DWORD dwDirLen, dwFullLen;
969 ptr = StrRChrW(szWildCard, NULL, '\\');
970 dwDirLen = ptr - szWildCard + 1;
972 dwFullLen = dwDirLen + lstrlenW(szFileName) + 1;
973 szFullPath = HeapAlloc(GetProcessHeap(), 0, dwFullLen * sizeof(WCHAR));
975 lstrcpynW(szFullPath, szWildCard, dwDirLen + 1);
976 lstrcatW(szFullPath, szFileName);
978 return szFullPath;
981 static void parse_wildcard_files(FILE_LIST *flList, LPCWSTR szFile, LPDWORD pdwListIndex)
983 WIN32_FIND_DATAW wfd;
984 HANDLE hFile = FindFirstFileW(szFile, &wfd);
985 FILE_ENTRY *file;
986 LPWSTR szFullPath;
987 BOOL res;
989 if (hFile == INVALID_HANDLE_VALUE) return;
991 for (res = TRUE; res; res = FindNextFileW(hFile, &wfd))
993 if (IsDotDir(wfd.cFileName)) continue;
994 if (*pdwListIndex >= flList->num_alloc) grow_list( flList );
995 szFullPath = wildcard_to_file(szFile, wfd.cFileName);
996 file = &flList->feFiles[(*pdwListIndex)++];
997 add_file_to_entry(file, szFullPath);
998 file->bFromWildcard = TRUE;
999 file->attributes = wfd.dwFileAttributes;
1000 if (IsAttribDir(file->attributes)) flList->bAnyDirectories = TRUE;
1001 HeapFree(GetProcessHeap(), 0, szFullPath);
1004 FindClose(hFile);
1007 /* takes the null-separated file list and fills out the FILE_LIST */
1008 static HRESULT parse_file_list(FILE_LIST *flList, LPCWSTR szFiles)
1010 LPCWSTR ptr = szFiles;
1011 WCHAR szCurFile[MAX_PATH];
1012 DWORD i = 0;
1014 if (!szFiles)
1015 return ERROR_INVALID_PARAMETER;
1017 flList->bAnyFromWildcard = FALSE;
1018 flList->bAnyDirectories = FALSE;
1019 flList->bAnyDontExist = FALSE;
1020 flList->num_alloc = 32;
1021 flList->dwNumFiles = 0;
1023 /* empty list */
1024 if (!szFiles[0])
1025 return ERROR_ACCESS_DENIED;
1027 flList->feFiles = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY,
1028 flList->num_alloc * sizeof(FILE_ENTRY));
1030 while (*ptr)
1032 if (i >= flList->num_alloc) grow_list( flList );
1034 /* change relative to absolute path */
1035 if (PathIsRelativeW(ptr))
1037 GetCurrentDirectoryW(MAX_PATH, szCurFile);
1038 PathCombineW(szCurFile, szCurFile, ptr);
1039 flList->feFiles[i].bFromRelative = TRUE;
1041 else
1043 lstrcpyW(szCurFile, ptr);
1044 flList->feFiles[i].bFromRelative = FALSE;
1047 /* parse wildcard files if they are in the filename */
1048 if (StrPBrkW(szCurFile, wWildcardChars))
1050 parse_wildcard_files(flList, szCurFile, &i);
1051 flList->bAnyFromWildcard = TRUE;
1052 i--;
1054 else
1056 FILE_ENTRY *file = &flList->feFiles[i];
1057 add_file_to_entry(file, szCurFile);
1058 file->attributes = GetFileAttributesW( file->szFullPath );
1059 file->bExists = (file->attributes != INVALID_FILE_ATTRIBUTES);
1060 if (!file->bExists) flList->bAnyDontExist = TRUE;
1061 if (IsAttribDir(file->attributes)) flList->bAnyDirectories = TRUE;
1064 /* advance to the next string */
1065 ptr += lstrlenW(ptr) + 1;
1066 i++;
1068 flList->dwNumFiles = i;
1070 return S_OK;
1073 /* free the FILE_LIST */
1074 static void destroy_file_list(FILE_LIST *flList)
1076 DWORD i;
1078 if (!flList || !flList->feFiles)
1079 return;
1081 for (i = 0; i < flList->dwNumFiles; i++)
1083 HeapFree(GetProcessHeap(), 0, flList->feFiles[i].szDirectory);
1084 HeapFree(GetProcessHeap(), 0, flList->feFiles[i].szFilename);
1085 HeapFree(GetProcessHeap(), 0, flList->feFiles[i].szFullPath);
1088 HeapFree(GetProcessHeap(), 0, flList->feFiles);
1091 static void copy_dir_to_dir(FILE_OPERATION *op, const FILE_ENTRY *feFrom, LPCWSTR szDestPath)
1093 WCHAR szFrom[MAX_PATH], szTo[MAX_PATH];
1094 SHFILEOPSTRUCTW fileOp;
1096 static const WCHAR wildCardFiles[] = {'*','.','*',0};
1098 if (IsDotDir(feFrom->szFilename))
1099 return;
1101 if (PathFileExistsW(szDestPath))
1102 PathCombineW(szTo, szDestPath, feFrom->szFilename);
1103 else
1104 lstrcpyW(szTo, szDestPath);
1106 if (!(op->req->fFlags & FOF_NOCONFIRMATION) && PathFileExistsW(szTo)) {
1107 if (!SHELL_ConfirmDialogW(op->req->hwnd, ASK_OVERWRITE_FOLDER, feFrom->szFilename, op))
1109 /* Vista returns an ERROR_CANCELLED even if user pressed "No" */
1110 if (!op->bManyItems)
1111 op->bCancelled = TRUE;
1112 return;
1116 szTo[lstrlenW(szTo) + 1] = '\0';
1117 SHNotifyCreateDirectoryW(szTo, NULL);
1119 PathCombineW(szFrom, feFrom->szFullPath, wildCardFiles);
1120 szFrom[lstrlenW(szFrom) + 1] = '\0';
1122 fileOp = *op->req;
1123 fileOp.pFrom = szFrom;
1124 fileOp.pTo = szTo;
1125 fileOp.fFlags &= ~FOF_MULTIDESTFILES; /* we know we're copying to one dir */
1127 /* Don't ask the user about overwriting files when he accepted to overwrite the
1128 folder. FIXME: this is not exactly what Windows does - e.g. there would be
1129 an additional confirmation for a nested folder */
1130 fileOp.fFlags |= FOF_NOCONFIRMATION;
1132 SHFileOperationW(&fileOp);
1135 static BOOL copy_file_to_file(FILE_OPERATION *op, const WCHAR *szFrom, const WCHAR *szTo)
1137 if (!(op->req->fFlags & FOF_NOCONFIRMATION) && PathFileExistsW(szTo))
1139 if (!SHELL_ConfirmDialogW(op->req->hwnd, ASK_OVERWRITE_FILE, PathFindFileNameW(szTo), op))
1140 return FALSE;
1143 return SHNotifyCopyFileW(szFrom, szTo, FALSE) == 0;
1146 /* copy a file or directory to another directory */
1147 static void copy_to_dir(FILE_OPERATION *op, const FILE_ENTRY *feFrom, const FILE_ENTRY *feTo)
1149 if (!PathFileExistsW(feTo->szFullPath))
1150 SHNotifyCreateDirectoryW(feTo->szFullPath, NULL);
1152 if (IsAttribFile(feFrom->attributes))
1154 WCHAR szDestPath[MAX_PATH];
1156 PathCombineW(szDestPath, feTo->szFullPath, feFrom->szFilename);
1157 copy_file_to_file(op, feFrom->szFullPath, szDestPath);
1159 else if (!(op->req->fFlags & FOF_FILESONLY && feFrom->bFromWildcard))
1160 copy_dir_to_dir(op, feFrom, feTo->szFullPath);
1163 static void create_dest_dirs(LPCWSTR szDestDir)
1165 WCHAR dir[MAX_PATH];
1166 LPCWSTR ptr = StrChrW(szDestDir, '\\');
1168 /* make sure all directories up to last one are created */
1169 while (ptr && (ptr = StrChrW(ptr + 1, '\\')))
1171 lstrcpynW(dir, szDestDir, ptr - szDestDir + 1);
1173 if (!PathFileExistsW(dir))
1174 SHNotifyCreateDirectoryW(dir, NULL);
1177 /* create last directory */
1178 if (!PathFileExistsW(szDestDir))
1179 SHNotifyCreateDirectoryW(szDestDir, NULL);
1182 /* the FO_COPY operation */
1183 static DWORD copy_files(FILE_OPERATION *op, const FILE_LIST *flFrom, FILE_LIST *flTo)
1185 DWORD i;
1186 const FILE_ENTRY *entryToCopy;
1187 const FILE_ENTRY *fileDest = &flTo->feFiles[0];
1189 if (flFrom->bAnyDontExist)
1190 return ERROR_SHELL_INTERNAL_FILE_NOT_FOUND;
1192 if (flTo->dwNumFiles == 0)
1194 /* If the destination is empty, SHFileOperation should use the current directory */
1195 WCHAR curdir[MAX_PATH+1];
1197 GetCurrentDirectoryW(MAX_PATH, curdir);
1198 curdir[lstrlenW(curdir)+1] = 0;
1200 destroy_file_list(flTo);
1201 ZeroMemory(flTo, sizeof(FILE_LIST));
1202 parse_file_list(flTo, curdir);
1203 fileDest = &flTo->feFiles[0];
1206 if (op->req->fFlags & FOF_MULTIDESTFILES)
1208 if (flFrom->bAnyFromWildcard)
1209 return ERROR_CANCELLED;
1211 if (flFrom->dwNumFiles != flTo->dwNumFiles)
1213 if (flFrom->dwNumFiles != 1 && !IsAttribDir(fileDest->attributes))
1214 return ERROR_CANCELLED;
1216 /* Free all but the first entry. */
1217 for (i = 1; i < flTo->dwNumFiles; i++)
1219 HeapFree(GetProcessHeap(), 0, flTo->feFiles[i].szDirectory);
1220 HeapFree(GetProcessHeap(), 0, flTo->feFiles[i].szFilename);
1221 HeapFree(GetProcessHeap(), 0, flTo->feFiles[i].szFullPath);
1224 flTo->dwNumFiles = 1;
1226 else if (IsAttribDir(fileDest->attributes))
1228 for (i = 1; i < flTo->dwNumFiles; i++)
1229 if (!IsAttribDir(flTo->feFiles[i].attributes) ||
1230 !IsAttribDir(flFrom->feFiles[i].attributes))
1232 return ERROR_CANCELLED;
1236 else if (flFrom->dwNumFiles != 1)
1238 if (flTo->dwNumFiles != 1 && !IsAttribDir(fileDest->attributes))
1239 return ERROR_CANCELLED;
1241 if (PathFileExistsW(fileDest->szFullPath) &&
1242 IsAttribFile(fileDest->attributes))
1244 return ERROR_CANCELLED;
1247 if (flTo->dwNumFiles == 1 && fileDest->bFromRelative &&
1248 !PathFileExistsW(fileDest->szFullPath))
1250 return ERROR_CANCELLED;
1254 for (i = 0; i < flFrom->dwNumFiles; i++)
1256 entryToCopy = &flFrom->feFiles[i];
1258 if ((op->req->fFlags & FOF_MULTIDESTFILES) &&
1259 flTo->dwNumFiles > 1)
1261 fileDest = &flTo->feFiles[i];
1264 if (IsAttribDir(entryToCopy->attributes) &&
1265 !lstrcmpiW(entryToCopy->szFullPath, fileDest->szDirectory))
1267 return ERROR_SUCCESS;
1270 create_dest_dirs(fileDest->szDirectory);
1272 if (!lstrcmpiW(entryToCopy->szFullPath, fileDest->szFullPath))
1274 if (IsAttribFile(entryToCopy->attributes))
1275 return ERROR_NO_MORE_SEARCH_HANDLES;
1276 else
1277 return ERROR_SUCCESS;
1280 if ((flFrom->dwNumFiles > 1 && flTo->dwNumFiles == 1) ||
1281 IsAttribDir(fileDest->attributes))
1283 copy_to_dir(op, entryToCopy, fileDest);
1285 else if (IsAttribDir(entryToCopy->attributes))
1287 copy_dir_to_dir(op, entryToCopy, fileDest->szFullPath);
1289 else
1291 if (!copy_file_to_file(op, entryToCopy->szFullPath, fileDest->szFullPath))
1293 op->req->fAnyOperationsAborted = TRUE;
1294 return ERROR_CANCELLED;
1298 /* Vista return code. XP would return e.g. ERROR_FILE_NOT_FOUND, ERROR_ALREADY_EXISTS */
1299 if (op->bCancelled)
1300 return ERROR_CANCELLED;
1303 /* Vista return code. On XP if the used pressed "No" for the last item,
1304 * ERROR_ARENA_TRASHED would be returned */
1305 return ERROR_SUCCESS;
1308 static BOOL confirm_delete_list(HWND hWnd, DWORD fFlags, BOOL fTrash, const FILE_LIST *flFrom)
1310 if (flFrom->dwNumFiles > 1)
1312 WCHAR tmp[8];
1313 const WCHAR format[] = {'%','d',0};
1315 wnsprintfW(tmp, sizeof(tmp)/sizeof(tmp[0]), format, flFrom->dwNumFiles);
1316 return SHELL_ConfirmDialogW(hWnd, (fTrash?ASK_TRASH_MULTIPLE_ITEM:ASK_DELETE_MULTIPLE_ITEM), tmp, NULL);
1318 else
1320 const FILE_ENTRY *fileEntry = &flFrom->feFiles[0];
1322 if (IsAttribFile(fileEntry->attributes))
1323 return SHELL_ConfirmDialogW(hWnd, (fTrash?ASK_TRASH_FILE:ASK_DELETE_FILE), fileEntry->szFullPath, NULL);
1324 else if (!(fFlags & FOF_FILESONLY && fileEntry->bFromWildcard))
1325 return SHELL_ConfirmDialogW(hWnd, (fTrash?ASK_TRASH_FOLDER:ASK_DELETE_FOLDER), fileEntry->szFullPath, NULL);
1327 return TRUE;
1330 /* the FO_DELETE operation */
1331 static DWORD delete_files(LPSHFILEOPSTRUCTW lpFileOp, const FILE_LIST *flFrom)
1333 const FILE_ENTRY *fileEntry;
1334 DWORD i, ret;
1335 BOOL bTrash;
1337 if (!flFrom->dwNumFiles)
1338 return ERROR_SUCCESS;
1340 /* Windows also checks only the first item */
1341 bTrash = (lpFileOp->fFlags & FOF_ALLOWUNDO)
1342 && TRASH_CanTrashFile(flFrom->feFiles[0].szFullPath);
1344 if (!(lpFileOp->fFlags & FOF_NOCONFIRMATION) || (!bTrash && lpFileOp->fFlags & FOF_WANTNUKEWARNING))
1345 if (!confirm_delete_list(lpFileOp->hwnd, lpFileOp->fFlags, bTrash, flFrom))
1347 lpFileOp->fAnyOperationsAborted = TRUE;
1348 return 0;
1351 for (i = 0; i < flFrom->dwNumFiles; i++)
1353 fileEntry = &flFrom->feFiles[i];
1355 if (!IsAttribFile(fileEntry->attributes) &&
1356 (lpFileOp->fFlags & FOF_FILESONLY && fileEntry->bFromWildcard))
1357 continue;
1359 if (bTrash)
1361 BOOL bDelete;
1362 if (TRASH_TrashFile(fileEntry->szFullPath))
1363 continue;
1365 /* Note: Windows silently deletes the file in such a situation, we show a dialog */
1366 if (!(lpFileOp->fFlags & FOF_NOCONFIRMATION) || (lpFileOp->fFlags & FOF_WANTNUKEWARNING))
1367 bDelete = SHELL_ConfirmDialogW(lpFileOp->hwnd, ASK_CANT_TRASH_ITEM, fileEntry->szFullPath, NULL);
1368 else
1369 bDelete = TRUE;
1371 if (!bDelete)
1373 lpFileOp->fAnyOperationsAborted = TRUE;
1374 break;
1378 /* delete the file or directory */
1379 if (IsAttribFile(fileEntry->attributes))
1380 ret = DeleteFileW(fileEntry->szFullPath) ?
1381 ERROR_SUCCESS : GetLastError();
1382 else
1383 ret = SHELL_DeleteDirectoryW(lpFileOp->hwnd, fileEntry->szFullPath, FALSE);
1385 if (ret)
1386 return ret;
1389 return ERROR_SUCCESS;
1392 static void move_dir_to_dir(LPSHFILEOPSTRUCTW lpFileOp, const FILE_ENTRY *feFrom, LPCWSTR szDestPath)
1394 WCHAR szFrom[MAX_PATH], szTo[MAX_PATH];
1395 SHFILEOPSTRUCTW fileOp;
1397 static const WCHAR wildCardFiles[] = {'*','.','*',0};
1399 if (IsDotDir(feFrom->szFilename))
1400 return;
1402 SHNotifyCreateDirectoryW(szDestPath, NULL);
1404 PathCombineW(szFrom, feFrom->szFullPath, wildCardFiles);
1405 szFrom[lstrlenW(szFrom) + 1] = '\0';
1407 lstrcpyW(szTo, szDestPath);
1408 szTo[lstrlenW(szDestPath) + 1] = '\0';
1410 fileOp = *lpFileOp;
1411 fileOp.pFrom = szFrom;
1412 fileOp.pTo = szTo;
1414 SHFileOperationW(&fileOp);
1417 /* moves a file or directory to another directory */
1418 static void move_to_dir(LPSHFILEOPSTRUCTW lpFileOp, const FILE_ENTRY *feFrom, const FILE_ENTRY *feTo)
1420 WCHAR szDestPath[MAX_PATH];
1422 PathCombineW(szDestPath, feTo->szFullPath, feFrom->szFilename);
1424 if (IsAttribFile(feFrom->attributes))
1425 SHNotifyMoveFileW(feFrom->szFullPath, szDestPath);
1426 else if (!(lpFileOp->fFlags & FOF_FILESONLY && feFrom->bFromWildcard))
1427 move_dir_to_dir(lpFileOp, feFrom, szDestPath);
1430 /* the FO_MOVE operation */
1431 static DWORD move_files(LPSHFILEOPSTRUCTW lpFileOp, const FILE_LIST *flFrom, const FILE_LIST *flTo)
1433 DWORD i;
1434 INT mismatched = 0;
1435 const FILE_ENTRY *entryToMove;
1436 const FILE_ENTRY *fileDest;
1438 if (!flFrom->dwNumFiles)
1439 return ERROR_SUCCESS;
1441 if (!flTo->dwNumFiles)
1442 return ERROR_FILE_NOT_FOUND;
1444 if (!(lpFileOp->fFlags & FOF_MULTIDESTFILES) &&
1445 flTo->dwNumFiles > 1 && flFrom->dwNumFiles > 1)
1447 return ERROR_CANCELLED;
1450 if (!(lpFileOp->fFlags & FOF_MULTIDESTFILES) &&
1451 !flFrom->bAnyDirectories &&
1452 flFrom->dwNumFiles > flTo->dwNumFiles)
1454 return ERROR_CANCELLED;
1457 if (!PathFileExistsW(flTo->feFiles[0].szDirectory))
1458 return ERROR_CANCELLED;
1460 if (lpFileOp->fFlags & FOF_MULTIDESTFILES)
1461 mismatched = flFrom->dwNumFiles - flTo->dwNumFiles;
1463 fileDest = &flTo->feFiles[0];
1464 for (i = 0; i < flFrom->dwNumFiles; i++)
1466 entryToMove = &flFrom->feFiles[i];
1468 if (!PathFileExistsW(fileDest->szDirectory))
1469 return ERROR_CANCELLED;
1471 if (lpFileOp->fFlags & FOF_MULTIDESTFILES)
1473 if (i >= flTo->dwNumFiles)
1474 break;
1475 fileDest = &flTo->feFiles[i];
1476 if (mismatched && !fileDest->bExists)
1478 create_dest_dirs(flTo->feFiles[i].szFullPath);
1479 flTo->feFiles[i].bExists = TRUE;
1480 flTo->feFiles[i].attributes = FILE_ATTRIBUTE_DIRECTORY;
1484 if (fileDest->bExists && IsAttribDir(fileDest->attributes))
1485 move_to_dir(lpFileOp, entryToMove, fileDest);
1486 else
1487 SHNotifyMoveFileW(entryToMove->szFullPath, fileDest->szFullPath);
1490 if (mismatched > 0)
1492 if (flFrom->bAnyDirectories)
1493 return DE_DESTSAMETREE;
1494 else
1495 return DE_SAMEFILE;
1498 return ERROR_SUCCESS;
1501 /* the FO_RENAME files */
1502 static DWORD rename_files(LPSHFILEOPSTRUCTW lpFileOp, const FILE_LIST *flFrom, const FILE_LIST *flTo)
1504 const FILE_ENTRY *feFrom;
1505 const FILE_ENTRY *feTo;
1507 if (flFrom->dwNumFiles != 1)
1508 return ERROR_GEN_FAILURE;
1510 if (flTo->dwNumFiles != 1)
1511 return ERROR_CANCELLED;
1513 feFrom = &flFrom->feFiles[0];
1514 feTo= &flTo->feFiles[0];
1516 /* fail if destination doesn't exist */
1517 if (!feFrom->bExists)
1518 return ERROR_SHELL_INTERNAL_FILE_NOT_FOUND;
1520 /* fail if destination already exists */
1521 if (feTo->bExists)
1522 return ERROR_ALREADY_EXISTS;
1524 return SHNotifyMoveFileW(feFrom->szFullPath, feTo->szFullPath);
1527 /* alert the user if an unsupported flag is used */
1528 static void check_flags(FILEOP_FLAGS fFlags)
1530 WORD wUnsupportedFlags = FOF_NO_CONNECTED_ELEMENTS |
1531 FOF_NOCOPYSECURITYATTRIBS | FOF_NORECURSEREPARSE |
1532 FOF_RENAMEONCOLLISION | FOF_WANTMAPPINGHANDLE;
1534 if (fFlags & wUnsupportedFlags)
1535 FIXME("Unsupported flags: %04x\n", fFlags);
1538 /*************************************************************************
1539 * SHFileOperationW [SHELL32.@]
1541 * See SHFileOperationA
1543 int WINAPI SHFileOperationW(LPSHFILEOPSTRUCTW lpFileOp)
1545 FILE_OPERATION op;
1546 FILE_LIST flFrom, flTo;
1547 int ret = 0;
1549 if (!lpFileOp)
1550 return ERROR_INVALID_PARAMETER;
1552 check_flags(lpFileOp->fFlags);
1554 ZeroMemory(&flFrom, sizeof(FILE_LIST));
1555 ZeroMemory(&flTo, sizeof(FILE_LIST));
1557 if ((ret = parse_file_list(&flFrom, lpFileOp->pFrom)))
1558 return ret;
1560 if (lpFileOp->wFunc != FO_DELETE)
1561 parse_file_list(&flTo, lpFileOp->pTo);
1563 ZeroMemory(&op, sizeof(op));
1564 op.req = lpFileOp;
1565 op.bManyItems = (flFrom.dwNumFiles > 1);
1566 lpFileOp->fAnyOperationsAborted = FALSE;
1568 switch (lpFileOp->wFunc)
1570 case FO_COPY:
1571 ret = copy_files(&op, &flFrom, &flTo);
1572 break;
1573 case FO_DELETE:
1574 ret = delete_files(lpFileOp, &flFrom);
1575 break;
1576 case FO_MOVE:
1577 ret = move_files(lpFileOp, &flFrom, &flTo);
1578 break;
1579 case FO_RENAME:
1580 ret = rename_files(lpFileOp, &flFrom, &flTo);
1581 break;
1582 default:
1583 ret = ERROR_INVALID_PARAMETER;
1584 break;
1587 destroy_file_list(&flFrom);
1589 if (lpFileOp->wFunc != FO_DELETE)
1590 destroy_file_list(&flTo);
1592 if (ret == ERROR_CANCELLED)
1593 lpFileOp->fAnyOperationsAborted = TRUE;
1595 return ret;
1598 #define SHDSA_GetItemCount(hdsa) (*(int*)(hdsa))
1600 /*************************************************************************
1601 * SHFreeNameMappings [shell32.246]
1603 * Free the mapping handle returned by SHFileOperation if FOF_WANTSMAPPINGHANDLE
1604 * was specified.
1606 * PARAMS
1607 * hNameMapping [I] handle to the name mappings used during renaming of files
1609 * RETURNS
1610 * Nothing
1612 void WINAPI SHFreeNameMappings(HANDLE hNameMapping)
1614 if (hNameMapping)
1616 int i = SHDSA_GetItemCount((HDSA)hNameMapping) - 1;
1618 for (; i>= 0; i--)
1620 LPSHNAMEMAPPINGW lp = DSA_GetItemPtr(hNameMapping, i);
1622 SHFree(lp->pszOldPath);
1623 SHFree(lp->pszNewPath);
1625 DSA_Destroy(hNameMapping);
1629 /*************************************************************************
1630 * SheGetDirA [SHELL32.@]
1632 * drive = 0: returns the current directory path
1633 * drive > 0: returns the current directory path of the specified drive
1634 * drive=1 -> A: drive=2 -> B: ...
1635 * returns 0 if successful
1637 DWORD WINAPI SheGetDirA(DWORD drive, LPSTR buffer)
1639 WCHAR org_path[MAX_PATH];
1640 DWORD ret;
1641 char drv_path[3];
1643 /* change current directory to the specified drive */
1644 if (drive) {
1645 strcpy(drv_path, "A:");
1646 drv_path[0] += (char)drive-1;
1648 GetCurrentDirectoryW(MAX_PATH, org_path);
1650 SetCurrentDirectoryA(drv_path);
1653 /* query current directory path of the specified drive */
1654 ret = GetCurrentDirectoryA(MAX_PATH, buffer);
1656 /* back to the original drive */
1657 if (drive)
1658 SetCurrentDirectoryW(org_path);
1660 if (!ret)
1661 return GetLastError();
1663 return 0;
1666 /*************************************************************************
1667 * SheGetDirW [SHELL32.@]
1669 * drive = 0: returns the current directory path
1670 * drive > 0: returns the current directory path of the specified drive
1671 * drive=1 -> A: drive=2 -> B: ...
1672 * returns 0 if successful
1674 DWORD WINAPI SheGetDirW(DWORD drive, LPWSTR buffer)
1676 WCHAR org_path[MAX_PATH];
1677 DWORD ret;
1678 char drv_path[3];
1680 /* change current directory to the specified drive */
1681 if (drive) {
1682 strcpy(drv_path, "A:");
1683 drv_path[0] += (char)drive-1;
1685 GetCurrentDirectoryW(MAX_PATH, org_path);
1687 SetCurrentDirectoryA(drv_path);
1690 /* query current directory path of the specified drive */
1691 ret = GetCurrentDirectoryW(MAX_PATH, buffer);
1693 /* back to the original drive */
1694 if (drive)
1695 SetCurrentDirectoryW(org_path);
1697 if (!ret)
1698 return GetLastError();
1700 return 0;
1703 /*************************************************************************
1704 * SheChangeDirA [SHELL32.@]
1706 * changes the current directory to the specified path
1707 * and returns 0 if successful
1709 DWORD WINAPI SheChangeDirA(LPSTR path)
1711 if (SetCurrentDirectoryA(path))
1712 return 0;
1713 else
1714 return GetLastError();
1717 /*************************************************************************
1718 * SheChangeDirW [SHELL32.@]
1720 * changes the current directory to the specified path
1721 * and returns 0 if successful
1723 DWORD WINAPI SheChangeDirW(LPWSTR path)
1725 if (SetCurrentDirectoryW(path))
1726 return 0;
1727 else
1728 return GetLastError();
1731 /*************************************************************************
1732 * IsNetDrive [SHELL32.66]
1734 int WINAPI IsNetDrive(int drive)
1736 char root[4];
1737 strcpy(root, "A:\\");
1738 root[0] += (char)drive;
1739 return (GetDriveTypeA(root) == DRIVE_REMOTE);
1743 /*************************************************************************
1744 * RealDriveType [SHELL32.524]
1746 int WINAPI RealDriveType(int drive, BOOL bQueryNet)
1748 char root[] = "A:\\";
1749 root[0] += (char)drive;
1750 return GetDriveTypeA(root);
1753 /***********************************************************************
1754 * SHPathPrepareForWriteA (SHELL32.@)
1756 HRESULT WINAPI SHPathPrepareForWriteA(HWND hwnd, IUnknown *modless, LPCSTR path, DWORD flags)
1758 WCHAR wpath[MAX_PATH];
1759 MultiByteToWideChar( CP_ACP, 0, path, -1, wpath, MAX_PATH);
1760 return SHPathPrepareForWriteW(hwnd, modless, wpath, flags);
1763 /***********************************************************************
1764 * SHPathPrepareForWriteW (SHELL32.@)
1766 HRESULT WINAPI SHPathPrepareForWriteW(HWND hwnd, IUnknown *modless, LPCWSTR path, DWORD flags)
1768 DWORD res;
1769 DWORD err;
1770 LPCWSTR realpath;
1771 int len;
1772 WCHAR* last_slash;
1773 WCHAR* temppath=NULL;
1775 TRACE("%p %p %s 0x%80x\n", hwnd, modless, debugstr_w(path), flags);
1777 if (flags & ~(SHPPFW_DIRCREATE|SHPPFW_ASKDIRCREATE|SHPPFW_IGNOREFILENAME))
1778 FIXME("unimplemented flags 0x%08x\n", flags);
1780 /* cut off filename if necessary */
1781 if (flags & SHPPFW_IGNOREFILENAME)
1783 last_slash = StrRChrW(path, NULL, '\\');
1784 if (last_slash == NULL)
1785 len = 1;
1786 else
1787 len = last_slash - path + 1;
1788 temppath = HeapAlloc(GetProcessHeap(), 0, len * sizeof(WCHAR));
1789 if (!temppath)
1790 return E_OUTOFMEMORY;
1791 StrCpyNW(temppath, path, len);
1792 realpath = temppath;
1794 else
1796 realpath = path;
1799 /* try to create the directory if asked to */
1800 if (flags & (SHPPFW_DIRCREATE|SHPPFW_ASKDIRCREATE))
1802 if (flags & SHPPFW_ASKDIRCREATE)
1803 FIXME("treating SHPPFW_ASKDIRCREATE as SHPPFW_DIRCREATE\n");
1805 SHCreateDirectoryExW(0, realpath, NULL);
1808 /* check if we can access the directory */
1809 res = GetFileAttributesW(realpath);
1811 HeapFree(GetProcessHeap(), 0, temppath);
1813 if (res == INVALID_FILE_ATTRIBUTES)
1815 err = GetLastError();
1816 if (err == ERROR_FILE_NOT_FOUND)
1817 return HRESULT_FROM_WIN32(ERROR_PATH_NOT_FOUND);
1818 return HRESULT_FROM_WIN32(err);
1820 else if (res & FILE_ATTRIBUTE_DIRECTORY)
1821 return S_OK;
1822 else
1823 return HRESULT_FROM_WIN32(ERROR_DIRECTORY);