wined3d: Handle 3D textures in wined3d_device_copy_sub_resource_region().
[wine.git] / dlls / shell32 / shlfileop.c
blob02e7a1ba386f3d9c6ea8f7a0070af32de691eb8c
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, ARRAY_SIZE(szCaption));
292 LoadStringW(shell32_hInstance, ids.text_resource_id, szText, ARRAY_SIZE(szText));
294 args[0] = (DWORD_PTR)szDir;
295 FormatMessageW(FORMAT_MESSAGE_FROM_STRING|FORMAT_MESSAGE_ARGUMENT_ARRAY,
296 szText, 0, 0, szBuffer, ARRAY_SIZE(szBuffer), (__ms_va_list*)args);
298 hIcon = LoadIconW(ids.hIconInstance, (LPWSTR)MAKEINTRESOURCE(ids.icon_resource_id));
300 ret = SHELL_ConfirmMsgBox(hWnd, szBuffer, szCaption, hIcon, op && op->bManyItems);
301 if (op) {
302 if (ret == IDD_YESTOALL) {
303 op->dwYesToAllMask |= (1 << nKindOfDialog);
304 ret = IDYES;
306 if (ret == IDCANCEL)
307 op->bCancelled = TRUE;
308 if (ret != IDYES)
309 op->req->fAnyOperationsAborted = TRUE;
311 return ret == IDYES;
314 BOOL SHELL_ConfirmYesNoW(HWND hWnd, int nKindOfDialog, LPCWSTR szDir)
316 return SHELL_ConfirmDialogW(hWnd, nKindOfDialog, szDir, NULL);
319 static DWORD SHELL32_AnsiToUnicodeBuf(LPCSTR aPath, LPWSTR *wPath, DWORD minChars)
321 DWORD len = MultiByteToWideChar(CP_ACP, 0, aPath, -1, NULL, 0);
323 if (len < minChars)
324 len = minChars;
326 *wPath = heap_alloc(len * sizeof(WCHAR));
327 if (*wPath)
329 MultiByteToWideChar(CP_ACP, 0, aPath, -1, *wPath, len);
330 return NO_ERROR;
332 return E_OUTOFMEMORY;
335 HRESULT WINAPI SHIsFileAvailableOffline(LPCWSTR path, LPDWORD status)
337 FIXME("(%s, %p) stub\n", debugstr_w(path), status);
338 return E_FAIL;
341 /**************************************************************************
342 * SHELL_DeleteDirectory() [internal]
344 * Asks for confirmation when bShowUI is true and deletes the directory and
345 * all its subdirectories and files if necessary.
347 static DWORD SHELL_DeleteDirectoryW(HWND hwnd, LPCWSTR pszDir, BOOL bShowUI)
349 DWORD ret = 0;
350 HANDLE hFind;
351 WIN32_FIND_DATAW wfd;
352 WCHAR szTemp[MAX_PATH];
354 PathCombineW(szTemp, pszDir, wWildcardFile);
355 hFind = FindFirstFileW(szTemp, &wfd);
357 if (hFind != INVALID_HANDLE_VALUE) {
358 if (!bShowUI || SHELL_ConfirmDialogW(hwnd, ASK_DELETE_FOLDER, pszDir, NULL)) {
359 do {
360 if (IsDotDir(wfd.cFileName))
361 continue;
362 PathCombineW(szTemp, pszDir, wfd.cFileName);
363 if (FILE_ATTRIBUTE_DIRECTORY & wfd.dwFileAttributes)
364 ret = SHELL_DeleteDirectoryW(hwnd, szTemp, FALSE);
365 else
366 ret = SHNotifyDeleteFileW(szTemp);
367 } while (!ret && FindNextFileW(hFind, &wfd));
369 FindClose(hFind);
371 if (ret == ERROR_SUCCESS)
372 ret = SHNotifyRemoveDirectoryW(pszDir);
374 return ret == ERROR_PATH_NOT_FOUND ?
375 0x7C: /* DE_INVALIDFILES (legacy Windows error) */
376 ret;
379 /**************************************************************************
380 * Win32CreateDirectory [SHELL32.93]
382 * Creates a directory. Also triggers a change notify if one exists.
384 * PARAMS
385 * path [I] path to directory to create
387 * RETURNS
388 * TRUE if successful, FALSE otherwise
390 * NOTES
391 * Verified on Win98 / IE 5 (SHELL32 4.72, March 1999 build) to be ANSI.
392 * This is Unicode on NT/2000
394 static DWORD SHNotifyCreateDirectoryA(LPCSTR path, LPSECURITY_ATTRIBUTES sec)
396 LPWSTR wPath;
397 DWORD retCode;
399 TRACE("(%s, %p)\n", debugstr_a(path), sec);
401 retCode = SHELL32_AnsiToUnicodeBuf(path, &wPath, 0);
402 if (!retCode)
404 retCode = SHNotifyCreateDirectoryW(wPath, sec);
405 heap_free(wPath);
407 return retCode;
410 /**********************************************************************/
412 static DWORD SHNotifyCreateDirectoryW(LPCWSTR path, LPSECURITY_ATTRIBUTES sec)
414 TRACE("(%s, %p)\n", debugstr_w(path), sec);
416 if (CreateDirectoryW(path, sec))
418 SHChangeNotify(SHCNE_MKDIR, SHCNF_PATHW, path, NULL);
419 return ERROR_SUCCESS;
421 return GetLastError();
424 /**********************************************************************/
426 BOOL WINAPI Win32CreateDirectoryAW(LPCVOID path, LPSECURITY_ATTRIBUTES sec)
428 if (SHELL_OsIsUnicode())
429 return (SHNotifyCreateDirectoryW(path, sec) == ERROR_SUCCESS);
430 return (SHNotifyCreateDirectoryA(path, sec) == ERROR_SUCCESS);
433 /************************************************************************
434 * Win32RemoveDirectory [SHELL32.94]
436 * Deletes a directory. Also triggers a change notify if one exists.
438 * PARAMS
439 * path [I] path to directory to delete
441 * RETURNS
442 * TRUE if successful, FALSE otherwise
444 * NOTES
445 * Verified on Win98 / IE 5 (SHELL32 4.72, March 1999 build) to be ANSI.
446 * This is Unicode on NT/2000
448 static DWORD SHNotifyRemoveDirectoryA(LPCSTR path)
450 LPWSTR wPath;
451 DWORD retCode;
453 TRACE("(%s)\n", debugstr_a(path));
455 retCode = SHELL32_AnsiToUnicodeBuf(path, &wPath, 0);
456 if (!retCode)
458 retCode = SHNotifyRemoveDirectoryW(wPath);
459 heap_free(wPath);
461 return retCode;
464 /***********************************************************************/
466 static DWORD SHNotifyRemoveDirectoryW(LPCWSTR path)
468 BOOL ret;
469 TRACE("(%s)\n", debugstr_w(path));
471 ret = RemoveDirectoryW(path);
472 if (!ret)
474 /* Directory may be write protected */
475 DWORD dwAttr = GetFileAttributesW(path);
476 if (IsAttrib(dwAttr, FILE_ATTRIBUTE_READONLY))
477 if (SetFileAttributesW(path, dwAttr & ~FILE_ATTRIBUTE_READONLY))
478 ret = RemoveDirectoryW(path);
480 if (ret)
482 SHChangeNotify(SHCNE_RMDIR, SHCNF_PATHW, path, NULL);
483 return ERROR_SUCCESS;
485 return GetLastError();
488 /***********************************************************************/
490 BOOL WINAPI Win32RemoveDirectoryAW(LPCVOID path)
492 if (SHELL_OsIsUnicode())
493 return (SHNotifyRemoveDirectoryW(path) == ERROR_SUCCESS);
494 return (SHNotifyRemoveDirectoryA(path) == ERROR_SUCCESS);
497 /************************************************************************
498 * Win32DeleteFile [SHELL32.164]
500 * Deletes a file. Also triggers a change notify if one exists.
502 * PARAMS
503 * path [I] path to file to delete
505 * RETURNS
506 * TRUE if successful, FALSE otherwise
508 * NOTES
509 * Verified on Win98 / IE 5 (SHELL32 4.72, March 1999 build) to be ANSI.
510 * This is Unicode on NT/2000
512 static DWORD SHNotifyDeleteFileA(LPCSTR path)
514 LPWSTR wPath;
515 DWORD retCode;
517 TRACE("(%s)\n", debugstr_a(path));
519 retCode = SHELL32_AnsiToUnicodeBuf(path, &wPath, 0);
520 if (!retCode)
522 retCode = SHNotifyDeleteFileW(wPath);
523 heap_free(wPath);
525 return retCode;
528 /***********************************************************************/
530 static DWORD SHNotifyDeleteFileW(LPCWSTR path)
532 BOOL ret;
534 TRACE("(%s)\n", debugstr_w(path));
536 ret = DeleteFileW(path);
537 if (!ret)
539 /* File may be write protected or a system file */
540 DWORD dwAttr = GetFileAttributesW(path);
541 if (IsAttrib(dwAttr, FILE_ATTRIBUTE_READONLY | FILE_ATTRIBUTE_SYSTEM))
542 if (SetFileAttributesW(path, dwAttr & ~(FILE_ATTRIBUTE_READONLY | FILE_ATTRIBUTE_SYSTEM)))
543 ret = DeleteFileW(path);
545 if (ret)
547 SHChangeNotify(SHCNE_DELETE, SHCNF_PATHW, path, NULL);
548 return ERROR_SUCCESS;
550 return GetLastError();
553 /***********************************************************************/
555 DWORD WINAPI Win32DeleteFileAW(LPCVOID path)
557 if (SHELL_OsIsUnicode())
558 return (SHNotifyDeleteFileW(path) == ERROR_SUCCESS);
559 return (SHNotifyDeleteFileA(path) == ERROR_SUCCESS);
562 /************************************************************************
563 * SHNotifyMoveFile [internal]
565 * Moves a file. Also triggers a change notify if one exists.
567 * PARAMS
568 * src [I] path to source file to move
569 * dest [I] path to target file to move to
571 * RETURNS
572 * ERROR_SUCCESS if successful
574 static DWORD SHNotifyMoveFileW(LPCWSTR src, LPCWSTR dest)
576 BOOL ret;
578 TRACE("(%s %s)\n", debugstr_w(src), debugstr_w(dest));
580 ret = MoveFileExW(src, dest, MOVEFILE_REPLACE_EXISTING);
582 /* MOVEFILE_REPLACE_EXISTING fails with dirs, so try MoveFile */
583 if (!ret)
584 ret = MoveFileW(src, dest);
586 if (!ret)
588 DWORD dwAttr;
590 dwAttr = SHFindAttrW(dest, FALSE);
591 if (INVALID_FILE_ATTRIBUTES == dwAttr)
593 /* Source file may be write protected or a system file */
594 dwAttr = GetFileAttributesW(src);
595 if (IsAttrib(dwAttr, FILE_ATTRIBUTE_READONLY | FILE_ATTRIBUTE_SYSTEM))
596 if (SetFileAttributesW(src, dwAttr & ~(FILE_ATTRIBUTE_READONLY | FILE_ATTRIBUTE_SYSTEM)))
597 ret = MoveFileW(src, dest);
600 if (ret)
602 SHChangeNotify(SHCNE_RENAMEITEM, SHCNF_PATHW, src, dest);
603 return ERROR_SUCCESS;
605 return GetLastError();
608 /************************************************************************
609 * SHNotifyCopyFile [internal]
611 * Copies a file. Also triggers a change notify if one exists.
613 * PARAMS
614 * src [I] path to source file to move
615 * dest [I] path to target file to move to
616 * bFailIfExists [I] if TRUE, the target file will not be overwritten if
617 * a file with this name already exists
619 * RETURNS
620 * ERROR_SUCCESS if successful
622 static DWORD SHNotifyCopyFileW(LPCWSTR src, LPCWSTR dest, BOOL bFailIfExists)
624 BOOL ret;
625 DWORD attribs;
627 TRACE("(%s %s %s)\n", debugstr_w(src), debugstr_w(dest), bFailIfExists ? "failIfExists" : "");
629 /* Destination file may already exist with read only attribute */
630 attribs = GetFileAttributesW(dest);
631 if (IsAttrib(attribs, FILE_ATTRIBUTE_READONLY))
632 SetFileAttributesW(dest, attribs & ~FILE_ATTRIBUTE_READONLY);
634 ret = CopyFileW(src, dest, bFailIfExists);
635 if (ret)
637 SHChangeNotify(SHCNE_CREATE, SHCNF_PATHW, dest, NULL);
638 return ERROR_SUCCESS;
641 return GetLastError();
644 /*************************************************************************
645 * SHCreateDirectory [SHELL32.165]
647 * This function creates a file system folder whose fully qualified path is
648 * given by path. If one or more of the intermediate folders do not exist,
649 * they will be created as well.
651 * PARAMS
652 * hWnd [I]
653 * path [I] path of directory to create
655 * RETURNS
656 * ERROR_SUCCESS or one of the following values:
657 * ERROR_BAD_PATHNAME if the path is relative
658 * ERROR_FILE_EXISTS when a file with that name exists
659 * ERROR_PATH_NOT_FOUND can't find the path, probably invalid
660 * ERROR_INVALID_NAME if the path contains invalid chars
661 * ERROR_ALREADY_EXISTS when the directory already exists
662 * ERROR_FILENAME_EXCED_RANGE if the filename was too long to process
664 * NOTES
665 * exported by ordinal
666 * Win9x exports ANSI
667 * WinNT/2000 exports Unicode
669 DWORD WINAPI SHCreateDirectory(HWND hWnd, LPCVOID path)
671 if (SHELL_OsIsUnicode())
672 return SHCreateDirectoryExW(hWnd, path, NULL);
673 return SHCreateDirectoryExA(hWnd, path, NULL);
676 /*************************************************************************
677 * SHCreateDirectoryExA [SHELL32.@]
679 * This function creates a file system folder whose fully qualified path is
680 * given by path. If one or more of the intermediate folders do not exist,
681 * they will be created as well.
683 * PARAMS
684 * hWnd [I]
685 * path [I] path of directory to create
686 * sec [I] security attributes to use or NULL
688 * RETURNS
689 * ERROR_SUCCESS or one of the following values:
690 * ERROR_BAD_PATHNAME or ERROR_PATH_NOT_FOUND if the path is relative
691 * ERROR_INVALID_NAME if the path contains invalid chars
692 * ERROR_FILE_EXISTS when a file with that name exists
693 * ERROR_ALREADY_EXISTS when the directory already exists
694 * ERROR_FILENAME_EXCED_RANGE if the filename was too long to process
696 * FIXME: Not implemented yet;
697 * SHCreateDirectoryEx also verifies that the files in the directory will be visible
698 * if the path is a network path to deal with network drivers which might have a limited
699 * but unknown maximum path length. If not:
701 * If hWnd is set to a valid window handle, a message box is displayed warning
702 * the user that the files may not be accessible. If the user chooses not to
703 * proceed, the function returns ERROR_CANCELLED.
705 * If hWnd is set to NULL, no user interface is displayed and the function
706 * returns ERROR_CANCELLED.
708 int WINAPI SHCreateDirectoryExA(HWND hWnd, LPCSTR path, LPSECURITY_ATTRIBUTES sec)
710 LPWSTR wPath;
711 DWORD retCode;
713 TRACE("(%s, %p)\n", debugstr_a(path), sec);
715 retCode = SHELL32_AnsiToUnicodeBuf(path, &wPath, 0);
716 if (!retCode)
718 retCode = SHCreateDirectoryExW(hWnd, wPath, sec);
719 heap_free(wPath);
721 return retCode;
724 /*************************************************************************
725 * SHCreateDirectoryExW [SHELL32.@]
727 * See SHCreateDirectoryExA.
729 int WINAPI SHCreateDirectoryExW(HWND hWnd, LPCWSTR path, LPSECURITY_ATTRIBUTES sec)
731 int ret = ERROR_BAD_PATHNAME;
732 TRACE("(%p, %s, %p)\n", hWnd, debugstr_w(path), sec);
734 if (PathIsRelativeW(path))
736 SetLastError(ret);
738 else
740 ret = SHNotifyCreateDirectoryW(path, sec);
741 /* Refuse to work on certain error codes before trying to create directories recursively */
742 if (ret != ERROR_SUCCESS &&
743 ret != ERROR_FILE_EXISTS &&
744 ret != ERROR_ALREADY_EXISTS &&
745 ret != ERROR_FILENAME_EXCED_RANGE)
747 WCHAR *pEnd, *pSlash, szTemp[MAX_PATH + 1]; /* extra for PathAddBackslash() */
749 lstrcpynW(szTemp, path, MAX_PATH);
750 pEnd = PathAddBackslashW(szTemp);
751 pSlash = szTemp + 3;
753 while (*pSlash)
755 while (*pSlash && *pSlash != '\\') pSlash++;
756 if (*pSlash)
758 *pSlash = 0; /* terminate path at separator */
760 ret = SHNotifyCreateDirectoryW(szTemp, pSlash + 1 == pEnd ? sec : NULL);
762 *pSlash++ = '\\'; /* put the separator back */
766 if (ret && hWnd && (ERROR_CANCELLED != ret))
768 /* We failed and should show a dialog box */
769 FIXME("Show system error message, creating path %s, failed with error %d\n", debugstr_w(path), ret);
770 ret = ERROR_CANCELLED; /* Error has been already presented to user (not really yet!) */
773 return ret;
776 /*************************************************************************
777 * SHFindAttrW [internal]
779 * Get the Attributes for a file or directory. The difference to GetAttributes()
780 * is that this function will also work for paths containing wildcard characters
781 * in its filename.
783 * PARAMS
784 * path [I] path of directory or file to check
785 * fileOnly [I] TRUE if only files should be found
787 * RETURNS
788 * INVALID_FILE_ATTRIBUTES if the path does not exist, the actual attributes of
789 * the first file or directory found otherwise
791 static DWORD SHFindAttrW(LPCWSTR pName, BOOL fileOnly)
793 WIN32_FIND_DATAW wfd;
794 BOOL b_FileMask = fileOnly && (NULL != StrPBrkW(pName, wWildcardChars));
795 DWORD dwAttr = INVALID_FILE_ATTRIBUTES;
796 HANDLE hFind = FindFirstFileW(pName, &wfd);
798 TRACE("%s %d\n", debugstr_w(pName), fileOnly);
799 if (INVALID_HANDLE_VALUE != hFind)
803 if (b_FileMask && IsAttribDir(wfd.dwFileAttributes))
804 continue;
805 dwAttr = wfd.dwFileAttributes;
806 break;
808 while (FindNextFileW(hFind, &wfd));
809 FindClose(hFind);
811 return dwAttr;
814 /*************************************************************************
816 * SHNameTranslate HelperFunction for SHFileOperationA
818 * Translates a list of 0 terminated ASCII strings into Unicode. If *wString
819 * is NULL, only the necessary size of the string is determined and returned,
820 * otherwise the ASCII strings are copied into it and the buffer is increased
821 * to point to the location after the final 0 termination char.
823 static DWORD SHNameTranslate(LPWSTR* wString, LPCWSTR* pWToFrom, BOOL more)
825 DWORD size = 0, aSize = 0;
826 LPCSTR aString = (LPCSTR)*pWToFrom;
828 if (aString)
832 size = lstrlenA(aString) + 1;
833 aSize += size;
834 aString += size;
835 } while ((size != 1) && more);
836 /* The two sizes might be different in the case of multibyte chars */
837 size = MultiByteToWideChar(CP_ACP, 0, (LPCSTR)*pWToFrom, aSize, *wString, 0);
838 if (*wString) /* only in the second loop */
840 MultiByteToWideChar(CP_ACP, 0, (LPCSTR)*pWToFrom, aSize, *wString, size);
841 *pWToFrom = *wString;
842 *wString += size;
845 return size;
847 /*************************************************************************
848 * SHFileOperationA [SHELL32.@]
850 * Function to copy, move, delete and create one or more files with optional
851 * user prompts.
853 * PARAMS
854 * lpFileOp [I/O] pointer to a structure containing all the necessary information
856 * RETURNS
857 * Success: ERROR_SUCCESS.
858 * Failure: ERROR_CANCELLED.
860 * NOTES
861 * exported by name
863 int WINAPI SHFileOperationA(LPSHFILEOPSTRUCTA lpFileOp)
865 SHFILEOPSTRUCTW nFileOp = *((LPSHFILEOPSTRUCTW)lpFileOp);
866 int retCode = 0;
867 DWORD size;
868 LPWSTR ForFree = NULL, /* we change wString in SHNameTranslate and can't use it for freeing */
869 wString = NULL; /* we change this in SHNameTranslate */
871 TRACE("\n");
872 if (FO_DELETE == (nFileOp.wFunc & FO_MASK))
873 nFileOp.pTo = NULL; /* we need a NULL or a valid pointer for translation */
874 if (!(nFileOp.fFlags & FOF_SIMPLEPROGRESS))
875 nFileOp.lpszProgressTitle = NULL; /* we need a NULL or a valid pointer for translation */
876 while (1) /* every loop calculate size, second translate also, if we have storage for this */
878 size = SHNameTranslate(&wString, &nFileOp.lpszProgressTitle, FALSE); /* no loop */
879 size += SHNameTranslate(&wString, &nFileOp.pFrom, TRUE); /* internal loop */
880 size += SHNameTranslate(&wString, &nFileOp.pTo, TRUE); /* internal loop */
882 if (ForFree)
884 retCode = SHFileOperationW(&nFileOp);
885 heap_free(ForFree); /* we cannot use wString, it was changed */
886 break;
888 else
890 wString = ForFree = heap_alloc(size * sizeof(WCHAR));
891 if (ForFree) continue;
892 retCode = ERROR_OUTOFMEMORY;
893 nFileOp.fAnyOperationsAborted = TRUE;
894 return retCode;
898 lpFileOp->hNameMappings = nFileOp.hNameMappings;
899 lpFileOp->fAnyOperationsAborted = nFileOp.fAnyOperationsAborted;
900 return retCode;
903 #define ERROR_SHELL_INTERNAL_FILE_NOT_FOUND 1026
905 typedef struct
907 DWORD attributes;
908 LPWSTR szDirectory;
909 LPWSTR szFilename;
910 LPWSTR szFullPath;
911 BOOL bFromWildcard;
912 BOOL bFromRelative;
913 BOOL bExists;
914 } FILE_ENTRY;
916 typedef struct
918 FILE_ENTRY *feFiles;
919 DWORD num_alloc;
920 DWORD dwNumFiles;
921 BOOL bAnyFromWildcard;
922 BOOL bAnyDirectories;
923 BOOL bAnyDontExist;
924 } FILE_LIST;
927 static inline void grow_list(FILE_LIST *list)
929 FILE_ENTRY *new = HeapReAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, list->feFiles,
930 list->num_alloc * 2 * sizeof(*new) );
931 list->feFiles = new;
932 list->num_alloc *= 2;
935 /* adds a file to the FILE_ENTRY struct
937 static void add_file_to_entry(FILE_ENTRY *feFile, LPCWSTR szFile)
939 DWORD dwLen = lstrlenW(szFile) + 1;
940 LPCWSTR ptr;
942 feFile->szFullPath = heap_alloc(dwLen * sizeof(WCHAR));
943 lstrcpyW(feFile->szFullPath, szFile);
945 ptr = StrRChrW(szFile, NULL, '\\');
946 if (ptr)
948 dwLen = ptr - szFile + 1;
949 feFile->szDirectory = heap_alloc(dwLen * sizeof(WCHAR));
950 lstrcpynW(feFile->szDirectory, szFile, dwLen);
952 dwLen = lstrlenW(feFile->szFullPath) - dwLen + 1;
953 feFile->szFilename = heap_alloc(dwLen * sizeof(WCHAR));
954 lstrcpyW(feFile->szFilename, ptr + 1); /* skip over backslash */
956 feFile->bFromWildcard = FALSE;
959 static LPWSTR wildcard_to_file(LPCWSTR szWildCard, LPCWSTR szFileName)
961 LPCWSTR ptr;
962 LPWSTR szFullPath;
963 DWORD dwDirLen, dwFullLen;
965 ptr = StrRChrW(szWildCard, NULL, '\\');
966 dwDirLen = ptr - szWildCard + 1;
968 dwFullLen = dwDirLen + lstrlenW(szFileName) + 1;
969 szFullPath = heap_alloc(dwFullLen * sizeof(WCHAR));
971 lstrcpynW(szFullPath, szWildCard, dwDirLen + 1);
972 lstrcatW(szFullPath, szFileName);
974 return szFullPath;
977 static void parse_wildcard_files(FILE_LIST *flList, LPCWSTR szFile, LPDWORD pdwListIndex)
979 WIN32_FIND_DATAW wfd;
980 HANDLE hFile = FindFirstFileW(szFile, &wfd);
981 FILE_ENTRY *file;
982 LPWSTR szFullPath;
983 BOOL res;
985 if (hFile == INVALID_HANDLE_VALUE) return;
987 for (res = TRUE; res; res = FindNextFileW(hFile, &wfd))
989 if (IsDotDir(wfd.cFileName)) continue;
990 if (*pdwListIndex >= flList->num_alloc) grow_list( flList );
991 szFullPath = wildcard_to_file(szFile, wfd.cFileName);
992 file = &flList->feFiles[(*pdwListIndex)++];
993 add_file_to_entry(file, szFullPath);
994 file->bFromWildcard = TRUE;
995 file->attributes = wfd.dwFileAttributes;
996 if (IsAttribDir(file->attributes)) flList->bAnyDirectories = TRUE;
997 heap_free(szFullPath);
1000 FindClose(hFile);
1003 /* takes the null-separated file list and fills out the FILE_LIST */
1004 static HRESULT parse_file_list(FILE_LIST *flList, LPCWSTR szFiles)
1006 LPCWSTR ptr = szFiles;
1007 WCHAR szCurFile[MAX_PATH];
1008 DWORD i = 0;
1010 if (!szFiles)
1011 return ERROR_INVALID_PARAMETER;
1013 flList->bAnyFromWildcard = FALSE;
1014 flList->bAnyDirectories = FALSE;
1015 flList->bAnyDontExist = FALSE;
1016 flList->num_alloc = 32;
1017 flList->dwNumFiles = 0;
1019 /* empty list */
1020 if (!szFiles[0])
1021 return ERROR_ACCESS_DENIED;
1023 flList->feFiles = heap_alloc_zero(flList->num_alloc * sizeof(FILE_ENTRY));
1025 while (*ptr)
1027 if (i >= flList->num_alloc) grow_list( flList );
1029 /* change relative to absolute path */
1030 if (PathIsRelativeW(ptr))
1032 GetCurrentDirectoryW(MAX_PATH, szCurFile);
1033 PathCombineW(szCurFile, szCurFile, ptr);
1034 flList->feFiles[i].bFromRelative = TRUE;
1036 else
1038 lstrcpyW(szCurFile, ptr);
1039 flList->feFiles[i].bFromRelative = FALSE;
1042 /* parse wildcard files if they are in the filename */
1043 if (StrPBrkW(szCurFile, wWildcardChars))
1045 parse_wildcard_files(flList, szCurFile, &i);
1046 flList->bAnyFromWildcard = TRUE;
1047 i--;
1049 else
1051 FILE_ENTRY *file = &flList->feFiles[i];
1052 add_file_to_entry(file, szCurFile);
1053 file->attributes = GetFileAttributesW( file->szFullPath );
1054 file->bExists = (file->attributes != INVALID_FILE_ATTRIBUTES);
1055 if (!file->bExists) flList->bAnyDontExist = TRUE;
1056 if (IsAttribDir(file->attributes)) flList->bAnyDirectories = TRUE;
1059 /* advance to the next string */
1060 ptr += lstrlenW(ptr) + 1;
1061 i++;
1063 flList->dwNumFiles = i;
1065 return S_OK;
1068 /* free the FILE_LIST */
1069 static void destroy_file_list(FILE_LIST *flList)
1071 DWORD i;
1073 if (!flList || !flList->feFiles)
1074 return;
1076 for (i = 0; i < flList->dwNumFiles; i++)
1078 heap_free(flList->feFiles[i].szDirectory);
1079 heap_free(flList->feFiles[i].szFilename);
1080 heap_free(flList->feFiles[i].szFullPath);
1083 heap_free(flList->feFiles);
1086 static void copy_dir_to_dir(FILE_OPERATION *op, const FILE_ENTRY *feFrom, LPCWSTR szDestPath)
1088 WCHAR szFrom[MAX_PATH], szTo[MAX_PATH];
1089 SHFILEOPSTRUCTW fileOp;
1091 static const WCHAR wildCardFiles[] = {'*','.','*',0};
1093 if (IsDotDir(feFrom->szFilename))
1094 return;
1096 if (PathFileExistsW(szDestPath))
1097 PathCombineW(szTo, szDestPath, feFrom->szFilename);
1098 else
1099 lstrcpyW(szTo, szDestPath);
1101 if (!(op->req->fFlags & FOF_NOCONFIRMATION) && PathFileExistsW(szTo)) {
1102 if (!SHELL_ConfirmDialogW(op->req->hwnd, ASK_OVERWRITE_FOLDER, feFrom->szFilename, op))
1104 /* Vista returns an ERROR_CANCELLED even if user pressed "No" */
1105 if (!op->bManyItems)
1106 op->bCancelled = TRUE;
1107 return;
1111 szTo[lstrlenW(szTo) + 1] = '\0';
1112 SHNotifyCreateDirectoryW(szTo, NULL);
1114 PathCombineW(szFrom, feFrom->szFullPath, wildCardFiles);
1115 szFrom[lstrlenW(szFrom) + 1] = '\0';
1117 fileOp = *op->req;
1118 fileOp.pFrom = szFrom;
1119 fileOp.pTo = szTo;
1120 fileOp.fFlags &= ~FOF_MULTIDESTFILES; /* we know we're copying to one dir */
1122 /* Don't ask the user about overwriting files when he accepted to overwrite the
1123 folder. FIXME: this is not exactly what Windows does - e.g. there would be
1124 an additional confirmation for a nested folder */
1125 fileOp.fFlags |= FOF_NOCONFIRMATION;
1127 SHFileOperationW(&fileOp);
1130 static BOOL copy_file_to_file(FILE_OPERATION *op, const WCHAR *szFrom, const WCHAR *szTo)
1132 if (!(op->req->fFlags & FOF_NOCONFIRMATION) && PathFileExistsW(szTo))
1134 if (!SHELL_ConfirmDialogW(op->req->hwnd, ASK_OVERWRITE_FILE, PathFindFileNameW(szTo), op))
1135 return FALSE;
1138 return SHNotifyCopyFileW(szFrom, szTo, FALSE) == 0;
1141 /* copy a file or directory to another directory */
1142 static void copy_to_dir(FILE_OPERATION *op, const FILE_ENTRY *feFrom, const FILE_ENTRY *feTo)
1144 if (!PathFileExistsW(feTo->szFullPath))
1145 SHNotifyCreateDirectoryW(feTo->szFullPath, NULL);
1147 if (IsAttribFile(feFrom->attributes))
1149 WCHAR szDestPath[MAX_PATH];
1151 PathCombineW(szDestPath, feTo->szFullPath, feFrom->szFilename);
1152 copy_file_to_file(op, feFrom->szFullPath, szDestPath);
1154 else if (!(op->req->fFlags & FOF_FILESONLY && feFrom->bFromWildcard))
1155 copy_dir_to_dir(op, feFrom, feTo->szFullPath);
1158 static void create_dest_dirs(LPCWSTR szDestDir)
1160 WCHAR dir[MAX_PATH];
1161 LPCWSTR ptr = StrChrW(szDestDir, '\\');
1163 /* make sure all directories up to last one are created */
1164 while (ptr && (ptr = StrChrW(ptr + 1, '\\')))
1166 lstrcpynW(dir, szDestDir, ptr - szDestDir + 1);
1168 if (!PathFileExistsW(dir))
1169 SHNotifyCreateDirectoryW(dir, NULL);
1172 /* create last directory */
1173 if (!PathFileExistsW(szDestDir))
1174 SHNotifyCreateDirectoryW(szDestDir, NULL);
1177 /* the FO_COPY operation */
1178 static int copy_files(FILE_OPERATION *op, const FILE_LIST *flFrom, FILE_LIST *flTo)
1180 DWORD i;
1181 const FILE_ENTRY *entryToCopy;
1182 const FILE_ENTRY *fileDest = &flTo->feFiles[0];
1184 if (flFrom->bAnyDontExist)
1185 return ERROR_SHELL_INTERNAL_FILE_NOT_FOUND;
1187 if (flTo->dwNumFiles == 0)
1189 /* If the destination is empty, SHFileOperation should use the current directory */
1190 WCHAR curdir[MAX_PATH+1];
1192 GetCurrentDirectoryW(MAX_PATH, curdir);
1193 curdir[lstrlenW(curdir)+1] = 0;
1195 destroy_file_list(flTo);
1196 ZeroMemory(flTo, sizeof(FILE_LIST));
1197 parse_file_list(flTo, curdir);
1198 fileDest = &flTo->feFiles[0];
1201 if (op->req->fFlags & FOF_MULTIDESTFILES)
1203 if (flFrom->bAnyFromWildcard)
1204 return ERROR_CANCELLED;
1206 if (flFrom->dwNumFiles != flTo->dwNumFiles)
1208 if (flFrom->dwNumFiles != 1 && !IsAttribDir(fileDest->attributes))
1209 return ERROR_CANCELLED;
1211 /* Free all but the first entry. */
1212 for (i = 1; i < flTo->dwNumFiles; i++)
1214 heap_free(flTo->feFiles[i].szDirectory);
1215 heap_free(flTo->feFiles[i].szFilename);
1216 heap_free(flTo->feFiles[i].szFullPath);
1219 flTo->dwNumFiles = 1;
1221 else if (IsAttribDir(fileDest->attributes))
1223 for (i = 1; i < flTo->dwNumFiles; i++)
1224 if (!IsAttribDir(flTo->feFiles[i].attributes) ||
1225 !IsAttribDir(flFrom->feFiles[i].attributes))
1227 return ERROR_CANCELLED;
1231 else if (flFrom->dwNumFiles != 1)
1233 if (flTo->dwNumFiles != 1 && !IsAttribDir(fileDest->attributes))
1234 return ERROR_CANCELLED;
1236 if (PathFileExistsW(fileDest->szFullPath) &&
1237 IsAttribFile(fileDest->attributes))
1239 return ERROR_CANCELLED;
1242 if (flTo->dwNumFiles == 1 && fileDest->bFromRelative &&
1243 !PathFileExistsW(fileDest->szFullPath))
1245 return ERROR_CANCELLED;
1249 for (i = 0; i < flFrom->dwNumFiles; i++)
1251 entryToCopy = &flFrom->feFiles[i];
1253 if ((op->req->fFlags & FOF_MULTIDESTFILES) &&
1254 flTo->dwNumFiles > 1)
1256 fileDest = &flTo->feFiles[i];
1259 if (IsAttribDir(entryToCopy->attributes) &&
1260 !lstrcmpiW(entryToCopy->szFullPath, fileDest->szDirectory))
1262 return ERROR_SUCCESS;
1265 create_dest_dirs(fileDest->szDirectory);
1267 if (!lstrcmpiW(entryToCopy->szFullPath, fileDest->szFullPath))
1269 if (IsAttribFile(entryToCopy->attributes))
1270 return ERROR_NO_MORE_SEARCH_HANDLES;
1271 else
1272 return ERROR_SUCCESS;
1275 if ((flFrom->dwNumFiles > 1 && flTo->dwNumFiles == 1) ||
1276 IsAttribDir(fileDest->attributes))
1278 copy_to_dir(op, entryToCopy, fileDest);
1280 else if (IsAttribDir(entryToCopy->attributes))
1282 copy_dir_to_dir(op, entryToCopy, fileDest->szFullPath);
1284 else
1286 if (!copy_file_to_file(op, entryToCopy->szFullPath, fileDest->szFullPath))
1288 op->req->fAnyOperationsAborted = TRUE;
1289 return ERROR_CANCELLED;
1293 /* Vista return code. XP would return e.g. ERROR_FILE_NOT_FOUND, ERROR_ALREADY_EXISTS */
1294 if (op->bCancelled)
1295 return ERROR_CANCELLED;
1298 /* Vista return code. On XP if the used pressed "No" for the last item,
1299 * ERROR_ARENA_TRASHED would be returned */
1300 return ERROR_SUCCESS;
1303 static BOOL confirm_delete_list(HWND hWnd, DWORD fFlags, BOOL fTrash, const FILE_LIST *flFrom)
1305 if (flFrom->dwNumFiles > 1)
1307 static const WCHAR format[] = {'%','d',0};
1308 WCHAR tmp[8];
1310 wnsprintfW(tmp, sizeof(tmp)/sizeof(tmp[0]), format, flFrom->dwNumFiles);
1311 return SHELL_ConfirmDialogW(hWnd, (fTrash?ASK_TRASH_MULTIPLE_ITEM:ASK_DELETE_MULTIPLE_ITEM), tmp, NULL);
1313 else
1315 const FILE_ENTRY *fileEntry = &flFrom->feFiles[0];
1317 if (IsAttribFile(fileEntry->attributes))
1318 return SHELL_ConfirmDialogW(hWnd, (fTrash?ASK_TRASH_FILE:ASK_DELETE_FILE), fileEntry->szFullPath, NULL);
1319 else if (!(fFlags & FOF_FILESONLY && fileEntry->bFromWildcard))
1320 return SHELL_ConfirmDialogW(hWnd, (fTrash?ASK_TRASH_FOLDER:ASK_DELETE_FOLDER), fileEntry->szFullPath, NULL);
1322 return TRUE;
1325 /* the FO_DELETE operation */
1326 static int delete_files(LPSHFILEOPSTRUCTW lpFileOp, const FILE_LIST *flFrom)
1328 const FILE_ENTRY *fileEntry;
1329 DWORD i;
1330 int ret;
1331 BOOL bTrash;
1333 if (!flFrom->dwNumFiles)
1334 return ERROR_SUCCESS;
1336 /* Windows also checks only the first item */
1337 bTrash = (lpFileOp->fFlags & FOF_ALLOWUNDO)
1338 && TRASH_CanTrashFile(flFrom->feFiles[0].szFullPath);
1340 if (!(lpFileOp->fFlags & FOF_NOCONFIRMATION) || (!bTrash && lpFileOp->fFlags & FOF_WANTNUKEWARNING))
1341 if (!confirm_delete_list(lpFileOp->hwnd, lpFileOp->fFlags, bTrash, flFrom))
1343 lpFileOp->fAnyOperationsAborted = TRUE;
1344 return 0;
1347 for (i = 0; i < flFrom->dwNumFiles; i++)
1349 fileEntry = &flFrom->feFiles[i];
1351 if (!IsAttribFile(fileEntry->attributes) &&
1352 (lpFileOp->fFlags & FOF_FILESONLY && fileEntry->bFromWildcard))
1353 continue;
1355 if (bTrash)
1357 BOOL bDelete;
1358 if (TRASH_TrashFile(fileEntry->szFullPath))
1359 continue;
1361 /* Note: Windows silently deletes the file in such a situation, we show a dialog */
1362 if (!(lpFileOp->fFlags & FOF_NOCONFIRMATION) || (lpFileOp->fFlags & FOF_WANTNUKEWARNING))
1363 bDelete = SHELL_ConfirmDialogW(lpFileOp->hwnd, ASK_CANT_TRASH_ITEM, fileEntry->szFullPath, NULL);
1364 else
1365 bDelete = TRUE;
1367 if (!bDelete)
1369 lpFileOp->fAnyOperationsAborted = TRUE;
1370 break;
1374 /* delete the file or directory */
1375 if (IsAttribFile(fileEntry->attributes))
1376 ret = DeleteFileW(fileEntry->szFullPath) ?
1377 ERROR_SUCCESS : GetLastError();
1378 else
1379 ret = SHELL_DeleteDirectoryW(lpFileOp->hwnd, fileEntry->szFullPath, FALSE);
1381 if (ret)
1382 return ret;
1385 return ERROR_SUCCESS;
1388 /* moves a file or directory to another directory */
1389 static void move_to_dir(LPSHFILEOPSTRUCTW lpFileOp, const FILE_ENTRY *feFrom, const FILE_ENTRY *feTo)
1391 WCHAR szDestPath[MAX_PATH];
1393 PathCombineW(szDestPath, feTo->szFullPath, feFrom->szFilename);
1394 SHNotifyMoveFileW(feFrom->szFullPath, szDestPath);
1397 /* the FO_MOVE operation */
1398 static int move_files(LPSHFILEOPSTRUCTW lpFileOp, const FILE_LIST *flFrom, const FILE_LIST *flTo)
1400 DWORD i;
1401 INT mismatched = 0;
1402 const FILE_ENTRY *entryToMove;
1403 const FILE_ENTRY *fileDest;
1405 if (!flFrom->dwNumFiles)
1406 return ERROR_SUCCESS;
1408 if (!flTo->dwNumFiles)
1409 return ERROR_FILE_NOT_FOUND;
1411 if (!(lpFileOp->fFlags & FOF_MULTIDESTFILES) &&
1412 flTo->dwNumFiles > 1 && flFrom->dwNumFiles > 1)
1414 return ERROR_CANCELLED;
1417 if (!(lpFileOp->fFlags & FOF_MULTIDESTFILES) &&
1418 !flFrom->bAnyDirectories &&
1419 flFrom->dwNumFiles > flTo->dwNumFiles)
1421 return ERROR_CANCELLED;
1424 if (!PathFileExistsW(flTo->feFiles[0].szDirectory))
1425 return ERROR_CANCELLED;
1427 if (lpFileOp->fFlags & FOF_MULTIDESTFILES)
1428 mismatched = flFrom->dwNumFiles - flTo->dwNumFiles;
1430 fileDest = &flTo->feFiles[0];
1431 for (i = 0; i < flFrom->dwNumFiles; i++)
1433 entryToMove = &flFrom->feFiles[i];
1435 if (!PathFileExistsW(fileDest->szDirectory))
1436 return ERROR_CANCELLED;
1438 if (lpFileOp->fFlags & FOF_MULTIDESTFILES)
1440 if (i >= flTo->dwNumFiles)
1441 break;
1442 fileDest = &flTo->feFiles[i];
1443 if (mismatched && !fileDest->bExists)
1445 create_dest_dirs(flTo->feFiles[i].szFullPath);
1446 flTo->feFiles[i].bExists = TRUE;
1447 flTo->feFiles[i].attributes = FILE_ATTRIBUTE_DIRECTORY;
1451 if (fileDest->bExists && IsAttribDir(fileDest->attributes))
1452 move_to_dir(lpFileOp, entryToMove, fileDest);
1453 else
1454 SHNotifyMoveFileW(entryToMove->szFullPath, fileDest->szFullPath);
1457 if (mismatched > 0)
1459 if (flFrom->bAnyDirectories)
1460 return DE_DESTSAMETREE;
1461 else
1462 return DE_SAMEFILE;
1465 return ERROR_SUCCESS;
1468 /* the FO_RENAME files */
1469 static int rename_files(LPSHFILEOPSTRUCTW lpFileOp, const FILE_LIST *flFrom, const FILE_LIST *flTo)
1471 const FILE_ENTRY *feFrom;
1472 const FILE_ENTRY *feTo;
1474 if (flFrom->dwNumFiles != 1)
1475 return ERROR_GEN_FAILURE;
1477 if (flTo->dwNumFiles != 1)
1478 return ERROR_CANCELLED;
1480 feFrom = &flFrom->feFiles[0];
1481 feTo= &flTo->feFiles[0];
1483 /* fail if destination doesn't exist */
1484 if (!feFrom->bExists)
1485 return ERROR_SHELL_INTERNAL_FILE_NOT_FOUND;
1487 /* fail if destination already exists */
1488 if (feTo->bExists)
1489 return ERROR_ALREADY_EXISTS;
1491 return SHNotifyMoveFileW(feFrom->szFullPath, feTo->szFullPath);
1494 /* alert the user if an unsupported flag is used */
1495 static void check_flags(FILEOP_FLAGS fFlags)
1497 WORD wUnsupportedFlags = FOF_NO_CONNECTED_ELEMENTS |
1498 FOF_NOCOPYSECURITYATTRIBS | FOF_NORECURSEREPARSE |
1499 FOF_RENAMEONCOLLISION | FOF_WANTMAPPINGHANDLE;
1501 if (fFlags & wUnsupportedFlags)
1502 FIXME("Unsupported flags: %04x\n", fFlags);
1505 /*************************************************************************
1506 * SHFileOperationW [SHELL32.@]
1508 * See SHFileOperationA
1510 int WINAPI SHFileOperationW(LPSHFILEOPSTRUCTW lpFileOp)
1512 FILE_OPERATION op;
1513 FILE_LIST flFrom, flTo;
1514 int ret = 0;
1516 if (!lpFileOp)
1517 return ERROR_INVALID_PARAMETER;
1519 check_flags(lpFileOp->fFlags);
1521 ZeroMemory(&flFrom, sizeof(FILE_LIST));
1522 ZeroMemory(&flTo, sizeof(FILE_LIST));
1524 if ((ret = parse_file_list(&flFrom, lpFileOp->pFrom)))
1525 return ret;
1527 if (lpFileOp->wFunc != FO_DELETE)
1528 parse_file_list(&flTo, lpFileOp->pTo);
1530 ZeroMemory(&op, sizeof(op));
1531 op.req = lpFileOp;
1532 op.bManyItems = (flFrom.dwNumFiles > 1);
1533 lpFileOp->fAnyOperationsAborted = FALSE;
1535 switch (lpFileOp->wFunc)
1537 case FO_COPY:
1538 ret = copy_files(&op, &flFrom, &flTo);
1539 break;
1540 case FO_DELETE:
1541 ret = delete_files(lpFileOp, &flFrom);
1542 break;
1543 case FO_MOVE:
1544 ret = move_files(lpFileOp, &flFrom, &flTo);
1545 break;
1546 case FO_RENAME:
1547 ret = rename_files(lpFileOp, &flFrom, &flTo);
1548 break;
1549 default:
1550 ret = ERROR_INVALID_PARAMETER;
1551 break;
1554 destroy_file_list(&flFrom);
1556 if (lpFileOp->wFunc != FO_DELETE)
1557 destroy_file_list(&flTo);
1559 if (ret == ERROR_CANCELLED)
1560 lpFileOp->fAnyOperationsAborted = TRUE;
1562 SetLastError(ERROR_SUCCESS);
1563 return ret;
1566 #define SHDSA_GetItemCount(hdsa) (*(int*)(hdsa))
1568 /*************************************************************************
1569 * SHFreeNameMappings [shell32.246]
1571 * Free the mapping handle returned by SHFileOperation if FOF_WANTSMAPPINGHANDLE
1572 * was specified.
1574 * PARAMS
1575 * hNameMapping [I] handle to the name mappings used during renaming of files
1577 * RETURNS
1578 * Nothing
1580 void WINAPI SHFreeNameMappings(HANDLE hNameMapping)
1582 if (hNameMapping)
1584 int i = SHDSA_GetItemCount((HDSA)hNameMapping) - 1;
1586 for (; i>= 0; i--)
1588 LPSHNAMEMAPPINGW lp = DSA_GetItemPtr(hNameMapping, i);
1590 SHFree(lp->pszOldPath);
1591 SHFree(lp->pszNewPath);
1593 DSA_Destroy(hNameMapping);
1597 /*************************************************************************
1598 * SheGetDirA [SHELL32.@]
1600 * drive = 0: returns the current directory path
1601 * drive > 0: returns the current directory path of the specified drive
1602 * drive=1 -> A: drive=2 -> B: ...
1603 * returns 0 if successful
1605 DWORD WINAPI SheGetDirA(DWORD drive, LPSTR buffer)
1607 WCHAR org_path[MAX_PATH];
1608 DWORD ret;
1609 char drv_path[3];
1611 /* change current directory to the specified drive */
1612 if (drive) {
1613 strcpy(drv_path, "A:");
1614 drv_path[0] += (char)drive-1;
1616 GetCurrentDirectoryW(MAX_PATH, org_path);
1618 SetCurrentDirectoryA(drv_path);
1621 /* query current directory path of the specified drive */
1622 ret = GetCurrentDirectoryA(MAX_PATH, buffer);
1624 /* back to the original drive */
1625 if (drive)
1626 SetCurrentDirectoryW(org_path);
1628 if (!ret)
1629 return GetLastError();
1631 return 0;
1634 /*************************************************************************
1635 * SheGetDirW [SHELL32.@]
1637 * drive = 0: returns the current directory path
1638 * drive > 0: returns the current directory path of the specified drive
1639 * drive=1 -> A: drive=2 -> B: ...
1640 * returns 0 if successful
1642 DWORD WINAPI SheGetDirW(DWORD drive, LPWSTR buffer)
1644 WCHAR org_path[MAX_PATH];
1645 DWORD ret;
1646 char drv_path[3];
1648 /* change current directory to the specified drive */
1649 if (drive) {
1650 strcpy(drv_path, "A:");
1651 drv_path[0] += (char)drive-1;
1653 GetCurrentDirectoryW(MAX_PATH, org_path);
1655 SetCurrentDirectoryA(drv_path);
1658 /* query current directory path of the specified drive */
1659 ret = GetCurrentDirectoryW(MAX_PATH, buffer);
1661 /* back to the original drive */
1662 if (drive)
1663 SetCurrentDirectoryW(org_path);
1665 if (!ret)
1666 return GetLastError();
1668 return 0;
1671 /*************************************************************************
1672 * SheChangeDirA [SHELL32.@]
1674 * changes the current directory to the specified path
1675 * and returns 0 if successful
1677 DWORD WINAPI SheChangeDirA(LPSTR path)
1679 if (SetCurrentDirectoryA(path))
1680 return 0;
1681 else
1682 return GetLastError();
1685 /*************************************************************************
1686 * SheChangeDirW [SHELL32.@]
1688 * changes the current directory to the specified path
1689 * and returns 0 if successful
1691 DWORD WINAPI SheChangeDirW(LPWSTR path)
1693 if (SetCurrentDirectoryW(path))
1694 return 0;
1695 else
1696 return GetLastError();
1699 /*************************************************************************
1700 * IsNetDrive [SHELL32.66]
1702 int WINAPI IsNetDrive(int drive)
1704 char root[4];
1705 strcpy(root, "A:\\");
1706 root[0] += (char)drive;
1707 return (GetDriveTypeA(root) == DRIVE_REMOTE);
1711 /*************************************************************************
1712 * RealDriveType [SHELL32.524]
1714 int WINAPI RealDriveType(int drive, BOOL bQueryNet)
1716 char root[] = "A:\\";
1717 root[0] += (char)drive;
1718 return GetDriveTypeA(root);
1721 /***********************************************************************
1722 * SHPathPrepareForWriteA (SHELL32.@)
1724 HRESULT WINAPI SHPathPrepareForWriteA(HWND hwnd, IUnknown *modless, LPCSTR path, DWORD flags)
1726 WCHAR wpath[MAX_PATH];
1727 MultiByteToWideChar( CP_ACP, 0, path, -1, wpath, MAX_PATH);
1728 return SHPathPrepareForWriteW(hwnd, modless, wpath, flags);
1731 /***********************************************************************
1732 * SHPathPrepareForWriteW (SHELL32.@)
1734 HRESULT WINAPI SHPathPrepareForWriteW(HWND hwnd, IUnknown *modless, LPCWSTR path, DWORD flags)
1736 DWORD res;
1737 DWORD err;
1738 LPCWSTR realpath;
1739 int len;
1740 WCHAR* last_slash;
1741 WCHAR* temppath=NULL;
1743 TRACE("%p %p %s 0x%08x\n", hwnd, modless, debugstr_w(path), flags);
1745 if (flags & ~(SHPPFW_DIRCREATE|SHPPFW_ASKDIRCREATE|SHPPFW_IGNOREFILENAME))
1746 FIXME("unimplemented flags 0x%08x\n", flags);
1748 /* cut off filename if necessary */
1749 if (flags & SHPPFW_IGNOREFILENAME)
1751 last_slash = StrRChrW(path, NULL, '\\');
1752 if (last_slash == NULL)
1753 len = 1;
1754 else
1755 len = last_slash - path + 1;
1756 temppath = heap_alloc(len * sizeof(WCHAR));
1757 if (!temppath)
1758 return E_OUTOFMEMORY;
1759 StrCpyNW(temppath, path, len);
1760 realpath = temppath;
1762 else
1764 realpath = path;
1767 /* try to create the directory if asked to */
1768 if (flags & (SHPPFW_DIRCREATE|SHPPFW_ASKDIRCREATE))
1770 if (flags & SHPPFW_ASKDIRCREATE)
1771 FIXME("treating SHPPFW_ASKDIRCREATE as SHPPFW_DIRCREATE\n");
1773 SHCreateDirectoryExW(0, realpath, NULL);
1776 /* check if we can access the directory */
1777 res = GetFileAttributesW(realpath);
1779 heap_free(temppath);
1781 if (res == INVALID_FILE_ATTRIBUTES)
1783 err = GetLastError();
1784 if (err == ERROR_FILE_NOT_FOUND)
1785 return HRESULT_FROM_WIN32(ERROR_PATH_NOT_FOUND);
1786 return HRESULT_FROM_WIN32(err);
1788 else if (res & FILE_ATTRIBUTE_DIRECTORY)
1789 return S_OK;
1790 else
1791 return HRESULT_FROM_WIN32(ERROR_DIRECTORY);