po: Updated Polish translation.
[wine.git] / dlls / shell32 / shlfileop.c
blob3c1806606af667877d2bb20366692265941c8320
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)/sizeof(szBuffer[0]), (__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 * ERROR_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 too 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 too 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 return retCode;
901 lpFileOp->hNameMappings = nFileOp.hNameMappings;
902 lpFileOp->fAnyOperationsAborted = nFileOp.fAnyOperationsAborted;
903 return retCode;
906 #define ERROR_SHELL_INTERNAL_FILE_NOT_FOUND 1026
908 typedef struct
910 DWORD attributes;
911 LPWSTR szDirectory;
912 LPWSTR szFilename;
913 LPWSTR szFullPath;
914 BOOL bFromWildcard;
915 BOOL bFromRelative;
916 BOOL bExists;
917 } FILE_ENTRY;
919 typedef struct
921 FILE_ENTRY *feFiles;
922 DWORD num_alloc;
923 DWORD dwNumFiles;
924 BOOL bAnyFromWildcard;
925 BOOL bAnyDirectories;
926 BOOL bAnyDontExist;
927 } FILE_LIST;
930 static inline void grow_list(FILE_LIST *list)
932 FILE_ENTRY *new = HeapReAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, list->feFiles,
933 list->num_alloc * 2 * sizeof(*new) );
934 list->feFiles = new;
935 list->num_alloc *= 2;
938 /* adds a file to the FILE_ENTRY struct
940 static void add_file_to_entry(FILE_ENTRY *feFile, LPCWSTR szFile)
942 DWORD dwLen = lstrlenW(szFile) + 1;
943 LPCWSTR ptr;
945 feFile->szFullPath = HeapAlloc(GetProcessHeap(), 0, dwLen * sizeof(WCHAR));
946 lstrcpyW(feFile->szFullPath, szFile);
948 ptr = StrRChrW(szFile, NULL, '\\');
949 if (ptr)
951 dwLen = ptr - szFile + 1;
952 feFile->szDirectory = HeapAlloc(GetProcessHeap(), 0, dwLen * sizeof(WCHAR));
953 lstrcpynW(feFile->szDirectory, szFile, dwLen);
955 dwLen = lstrlenW(feFile->szFullPath) - dwLen + 1;
956 feFile->szFilename = HeapAlloc(GetProcessHeap(), 0, dwLen * sizeof(WCHAR));
957 lstrcpyW(feFile->szFilename, ptr + 1); /* skip over backslash */
959 feFile->bFromWildcard = FALSE;
962 static LPWSTR wildcard_to_file(LPCWSTR szWildCard, LPCWSTR szFileName)
964 LPCWSTR ptr;
965 LPWSTR szFullPath;
966 DWORD dwDirLen, dwFullLen;
968 ptr = StrRChrW(szWildCard, NULL, '\\');
969 dwDirLen = ptr - szWildCard + 1;
971 dwFullLen = dwDirLen + lstrlenW(szFileName) + 1;
972 szFullPath = HeapAlloc(GetProcessHeap(), 0, dwFullLen * sizeof(WCHAR));
974 lstrcpynW(szFullPath, szWildCard, dwDirLen + 1);
975 lstrcatW(szFullPath, szFileName);
977 return szFullPath;
980 static void parse_wildcard_files(FILE_LIST *flList, LPCWSTR szFile, LPDWORD pdwListIndex)
982 WIN32_FIND_DATAW wfd;
983 HANDLE hFile = FindFirstFileW(szFile, &wfd);
984 FILE_ENTRY *file;
985 LPWSTR szFullPath;
986 BOOL res;
988 if (hFile == INVALID_HANDLE_VALUE) return;
990 for (res = TRUE; res; res = FindNextFileW(hFile, &wfd))
992 if (IsDotDir(wfd.cFileName)) continue;
993 if (*pdwListIndex >= flList->num_alloc) grow_list( flList );
994 szFullPath = wildcard_to_file(szFile, wfd.cFileName);
995 file = &flList->feFiles[(*pdwListIndex)++];
996 add_file_to_entry(file, szFullPath);
997 file->bFromWildcard = TRUE;
998 file->attributes = wfd.dwFileAttributes;
999 if (IsAttribDir(file->attributes)) flList->bAnyDirectories = TRUE;
1000 HeapFree(GetProcessHeap(), 0, szFullPath);
1003 FindClose(hFile);
1006 /* takes the null-separated file list and fills out the FILE_LIST */
1007 static HRESULT parse_file_list(FILE_LIST *flList, LPCWSTR szFiles)
1009 LPCWSTR ptr = szFiles;
1010 WCHAR szCurFile[MAX_PATH];
1011 DWORD i = 0;
1013 if (!szFiles)
1014 return ERROR_INVALID_PARAMETER;
1016 flList->bAnyFromWildcard = FALSE;
1017 flList->bAnyDirectories = FALSE;
1018 flList->bAnyDontExist = FALSE;
1019 flList->num_alloc = 32;
1020 flList->dwNumFiles = 0;
1022 /* empty list */
1023 if (!szFiles[0])
1024 return ERROR_ACCESS_DENIED;
1026 flList->feFiles = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY,
1027 flList->num_alloc * sizeof(FILE_ENTRY));
1029 while (*ptr)
1031 if (i >= flList->num_alloc) grow_list( flList );
1033 /* change relative to absolute path */
1034 if (PathIsRelativeW(ptr))
1036 GetCurrentDirectoryW(MAX_PATH, szCurFile);
1037 PathCombineW(szCurFile, szCurFile, ptr);
1038 flList->feFiles[i].bFromRelative = TRUE;
1040 else
1042 lstrcpyW(szCurFile, ptr);
1043 flList->feFiles[i].bFromRelative = FALSE;
1046 /* parse wildcard files if they are in the filename */
1047 if (StrPBrkW(szCurFile, wWildcardChars))
1049 parse_wildcard_files(flList, szCurFile, &i);
1050 flList->bAnyFromWildcard = TRUE;
1051 i--;
1053 else
1055 FILE_ENTRY *file = &flList->feFiles[i];
1056 add_file_to_entry(file, szCurFile);
1057 file->attributes = GetFileAttributesW( file->szFullPath );
1058 file->bExists = (file->attributes != INVALID_FILE_ATTRIBUTES);
1059 if (!file->bExists) flList->bAnyDontExist = TRUE;
1060 if (IsAttribDir(file->attributes)) flList->bAnyDirectories = TRUE;
1063 /* advance to the next string */
1064 ptr += lstrlenW(ptr) + 1;
1065 i++;
1067 flList->dwNumFiles = i;
1069 return S_OK;
1072 /* free the FILE_LIST */
1073 static void destroy_file_list(FILE_LIST *flList)
1075 DWORD i;
1077 if (!flList || !flList->feFiles)
1078 return;
1080 for (i = 0; i < flList->dwNumFiles; i++)
1082 HeapFree(GetProcessHeap(), 0, flList->feFiles[i].szDirectory);
1083 HeapFree(GetProcessHeap(), 0, flList->feFiles[i].szFilename);
1084 HeapFree(GetProcessHeap(), 0, flList->feFiles[i].szFullPath);
1087 HeapFree(GetProcessHeap(), 0, flList->feFiles);
1090 static void copy_dir_to_dir(FILE_OPERATION *op, const FILE_ENTRY *feFrom, LPCWSTR szDestPath)
1092 WCHAR szFrom[MAX_PATH], szTo[MAX_PATH];
1093 SHFILEOPSTRUCTW fileOp;
1095 static const WCHAR wildCardFiles[] = {'*','.','*',0};
1097 if (IsDotDir(feFrom->szFilename))
1098 return;
1100 if (PathFileExistsW(szDestPath))
1101 PathCombineW(szTo, szDestPath, feFrom->szFilename);
1102 else
1103 lstrcpyW(szTo, szDestPath);
1105 if (!(op->req->fFlags & FOF_NOCONFIRMATION) && PathFileExistsW(szTo)) {
1106 if (!SHELL_ConfirmDialogW(op->req->hwnd, ASK_OVERWRITE_FOLDER, feFrom->szFilename, op))
1108 /* Vista returns an ERROR_CANCELLED even if user pressed "No" */
1109 if (!op->bManyItems)
1110 op->bCancelled = TRUE;
1111 return;
1115 szTo[lstrlenW(szTo) + 1] = '\0';
1116 SHNotifyCreateDirectoryW(szTo, NULL);
1118 PathCombineW(szFrom, feFrom->szFullPath, wildCardFiles);
1119 szFrom[lstrlenW(szFrom) + 1] = '\0';
1121 fileOp = *op->req;
1122 fileOp.pFrom = szFrom;
1123 fileOp.pTo = szTo;
1124 fileOp.fFlags &= ~FOF_MULTIDESTFILES; /* we know we're copying to one dir */
1126 /* Don't ask the user about overwriting files when he accepted to overwrite the
1127 folder. FIXME: this is not exactly what Windows does - e.g. there would be
1128 an additional confirmation for a nested folder */
1129 fileOp.fFlags |= FOF_NOCONFIRMATION;
1131 SHFileOperationW(&fileOp);
1134 static BOOL copy_file_to_file(FILE_OPERATION *op, const WCHAR *szFrom, const WCHAR *szTo)
1136 if (!(op->req->fFlags & FOF_NOCONFIRMATION) && PathFileExistsW(szTo))
1138 if (!SHELL_ConfirmDialogW(op->req->hwnd, ASK_OVERWRITE_FILE, PathFindFileNameW(szTo), op))
1139 return FALSE;
1142 return SHNotifyCopyFileW(szFrom, szTo, FALSE) == 0;
1145 /* copy a file or directory to another directory */
1146 static void copy_to_dir(FILE_OPERATION *op, const FILE_ENTRY *feFrom, const FILE_ENTRY *feTo)
1148 if (!PathFileExistsW(feTo->szFullPath))
1149 SHNotifyCreateDirectoryW(feTo->szFullPath, NULL);
1151 if (IsAttribFile(feFrom->attributes))
1153 WCHAR szDestPath[MAX_PATH];
1155 PathCombineW(szDestPath, feTo->szFullPath, feFrom->szFilename);
1156 copy_file_to_file(op, feFrom->szFullPath, szDestPath);
1158 else if (!(op->req->fFlags & FOF_FILESONLY && feFrom->bFromWildcard))
1159 copy_dir_to_dir(op, feFrom, feTo->szFullPath);
1162 static void create_dest_dirs(LPCWSTR szDestDir)
1164 WCHAR dir[MAX_PATH];
1165 LPCWSTR ptr = StrChrW(szDestDir, '\\');
1167 /* make sure all directories up to last one are created */
1168 while (ptr && (ptr = StrChrW(ptr + 1, '\\')))
1170 lstrcpynW(dir, szDestDir, ptr - szDestDir + 1);
1172 if (!PathFileExistsW(dir))
1173 SHNotifyCreateDirectoryW(dir, NULL);
1176 /* create last directory */
1177 if (!PathFileExistsW(szDestDir))
1178 SHNotifyCreateDirectoryW(szDestDir, NULL);
1181 /* the FO_COPY operation */
1182 static int copy_files(FILE_OPERATION *op, const FILE_LIST *flFrom, FILE_LIST *flTo)
1184 DWORD i;
1185 const FILE_ENTRY *entryToCopy;
1186 const FILE_ENTRY *fileDest = &flTo->feFiles[0];
1188 if (flFrom->bAnyDontExist)
1189 return ERROR_SHELL_INTERNAL_FILE_NOT_FOUND;
1191 if (flTo->dwNumFiles == 0)
1193 /* If the destination is empty, SHFileOperation should use the current directory */
1194 WCHAR curdir[MAX_PATH+1];
1196 GetCurrentDirectoryW(MAX_PATH, curdir);
1197 curdir[lstrlenW(curdir)+1] = 0;
1199 destroy_file_list(flTo);
1200 ZeroMemory(flTo, sizeof(FILE_LIST));
1201 parse_file_list(flTo, curdir);
1202 fileDest = &flTo->feFiles[0];
1205 if (op->req->fFlags & FOF_MULTIDESTFILES)
1207 if (flFrom->bAnyFromWildcard)
1208 return ERROR_CANCELLED;
1210 if (flFrom->dwNumFiles != flTo->dwNumFiles)
1212 if (flFrom->dwNumFiles != 1 && !IsAttribDir(fileDest->attributes))
1213 return ERROR_CANCELLED;
1215 /* Free all but the first entry. */
1216 for (i = 1; i < flTo->dwNumFiles; i++)
1218 HeapFree(GetProcessHeap(), 0, flTo->feFiles[i].szDirectory);
1219 HeapFree(GetProcessHeap(), 0, flTo->feFiles[i].szFilename);
1220 HeapFree(GetProcessHeap(), 0, flTo->feFiles[i].szFullPath);
1223 flTo->dwNumFiles = 1;
1225 else if (IsAttribDir(fileDest->attributes))
1227 for (i = 1; i < flTo->dwNumFiles; i++)
1228 if (!IsAttribDir(flTo->feFiles[i].attributes) ||
1229 !IsAttribDir(flFrom->feFiles[i].attributes))
1231 return ERROR_CANCELLED;
1235 else if (flFrom->dwNumFiles != 1)
1237 if (flTo->dwNumFiles != 1 && !IsAttribDir(fileDest->attributes))
1238 return ERROR_CANCELLED;
1240 if (PathFileExistsW(fileDest->szFullPath) &&
1241 IsAttribFile(fileDest->attributes))
1243 return ERROR_CANCELLED;
1246 if (flTo->dwNumFiles == 1 && fileDest->bFromRelative &&
1247 !PathFileExistsW(fileDest->szFullPath))
1249 return ERROR_CANCELLED;
1253 for (i = 0; i < flFrom->dwNumFiles; i++)
1255 entryToCopy = &flFrom->feFiles[i];
1257 if ((op->req->fFlags & FOF_MULTIDESTFILES) &&
1258 flTo->dwNumFiles > 1)
1260 fileDest = &flTo->feFiles[i];
1263 if (IsAttribDir(entryToCopy->attributes) &&
1264 !lstrcmpiW(entryToCopy->szFullPath, fileDest->szDirectory))
1266 return ERROR_SUCCESS;
1269 create_dest_dirs(fileDest->szDirectory);
1271 if (!lstrcmpiW(entryToCopy->szFullPath, fileDest->szFullPath))
1273 if (IsAttribFile(entryToCopy->attributes))
1274 return ERROR_NO_MORE_SEARCH_HANDLES;
1275 else
1276 return ERROR_SUCCESS;
1279 if ((flFrom->dwNumFiles > 1 && flTo->dwNumFiles == 1) ||
1280 IsAttribDir(fileDest->attributes))
1282 copy_to_dir(op, entryToCopy, fileDest);
1284 else if (IsAttribDir(entryToCopy->attributes))
1286 copy_dir_to_dir(op, entryToCopy, fileDest->szFullPath);
1288 else
1290 if (!copy_file_to_file(op, entryToCopy->szFullPath, fileDest->szFullPath))
1292 op->req->fAnyOperationsAborted = TRUE;
1293 return ERROR_CANCELLED;
1297 /* Vista return code. XP would return e.g. ERROR_FILE_NOT_FOUND, ERROR_ALREADY_EXISTS */
1298 if (op->bCancelled)
1299 return ERROR_CANCELLED;
1302 /* Vista return code. On XP if the used pressed "No" for the last item,
1303 * ERROR_ARENA_TRASHED would be returned */
1304 return ERROR_SUCCESS;
1307 static BOOL confirm_delete_list(HWND hWnd, DWORD fFlags, BOOL fTrash, const FILE_LIST *flFrom)
1309 if (flFrom->dwNumFiles > 1)
1311 WCHAR tmp[8];
1312 const WCHAR format[] = {'%','d',0};
1314 wnsprintfW(tmp, sizeof(tmp)/sizeof(tmp[0]), format, flFrom->dwNumFiles);
1315 return SHELL_ConfirmDialogW(hWnd, (fTrash?ASK_TRASH_MULTIPLE_ITEM:ASK_DELETE_MULTIPLE_ITEM), tmp, NULL);
1317 else
1319 const FILE_ENTRY *fileEntry = &flFrom->feFiles[0];
1321 if (IsAttribFile(fileEntry->attributes))
1322 return SHELL_ConfirmDialogW(hWnd, (fTrash?ASK_TRASH_FILE:ASK_DELETE_FILE), fileEntry->szFullPath, NULL);
1323 else if (!(fFlags & FOF_FILESONLY && fileEntry->bFromWildcard))
1324 return SHELL_ConfirmDialogW(hWnd, (fTrash?ASK_TRASH_FOLDER:ASK_DELETE_FOLDER), fileEntry->szFullPath, NULL);
1326 return TRUE;
1329 /* the FO_DELETE operation */
1330 static int delete_files(LPSHFILEOPSTRUCTW lpFileOp, const FILE_LIST *flFrom)
1332 const FILE_ENTRY *fileEntry;
1333 DWORD i;
1334 int 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 /* moves a file or directory to another directory */
1393 static void move_to_dir(LPSHFILEOPSTRUCTW lpFileOp, const FILE_ENTRY *feFrom, const FILE_ENTRY *feTo)
1395 WCHAR szDestPath[MAX_PATH];
1397 PathCombineW(szDestPath, feTo->szFullPath, feFrom->szFilename);
1398 SHNotifyMoveFileW(feFrom->szFullPath, szDestPath);
1401 /* the FO_MOVE operation */
1402 static int move_files(LPSHFILEOPSTRUCTW lpFileOp, const FILE_LIST *flFrom, const FILE_LIST *flTo)
1404 DWORD i;
1405 INT mismatched = 0;
1406 const FILE_ENTRY *entryToMove;
1407 const FILE_ENTRY *fileDest;
1409 if (!flFrom->dwNumFiles)
1410 return ERROR_SUCCESS;
1412 if (!flTo->dwNumFiles)
1413 return ERROR_FILE_NOT_FOUND;
1415 if (!(lpFileOp->fFlags & FOF_MULTIDESTFILES) &&
1416 flTo->dwNumFiles > 1 && flFrom->dwNumFiles > 1)
1418 return ERROR_CANCELLED;
1421 if (!(lpFileOp->fFlags & FOF_MULTIDESTFILES) &&
1422 !flFrom->bAnyDirectories &&
1423 flFrom->dwNumFiles > flTo->dwNumFiles)
1425 return ERROR_CANCELLED;
1428 if (!PathFileExistsW(flTo->feFiles[0].szDirectory))
1429 return ERROR_CANCELLED;
1431 if (lpFileOp->fFlags & FOF_MULTIDESTFILES)
1432 mismatched = flFrom->dwNumFiles - flTo->dwNumFiles;
1434 fileDest = &flTo->feFiles[0];
1435 for (i = 0; i < flFrom->dwNumFiles; i++)
1437 entryToMove = &flFrom->feFiles[i];
1439 if (!PathFileExistsW(fileDest->szDirectory))
1440 return ERROR_CANCELLED;
1442 if (lpFileOp->fFlags & FOF_MULTIDESTFILES)
1444 if (i >= flTo->dwNumFiles)
1445 break;
1446 fileDest = &flTo->feFiles[i];
1447 if (mismatched && !fileDest->bExists)
1449 create_dest_dirs(flTo->feFiles[i].szFullPath);
1450 flTo->feFiles[i].bExists = TRUE;
1451 flTo->feFiles[i].attributes = FILE_ATTRIBUTE_DIRECTORY;
1455 if (fileDest->bExists && IsAttribDir(fileDest->attributes))
1456 move_to_dir(lpFileOp, entryToMove, fileDest);
1457 else
1458 SHNotifyMoveFileW(entryToMove->szFullPath, fileDest->szFullPath);
1461 if (mismatched > 0)
1463 if (flFrom->bAnyDirectories)
1464 return DE_DESTSAMETREE;
1465 else
1466 return DE_SAMEFILE;
1469 return ERROR_SUCCESS;
1472 /* the FO_RENAME files */
1473 static int rename_files(LPSHFILEOPSTRUCTW lpFileOp, const FILE_LIST *flFrom, const FILE_LIST *flTo)
1475 const FILE_ENTRY *feFrom;
1476 const FILE_ENTRY *feTo;
1478 if (flFrom->dwNumFiles != 1)
1479 return ERROR_GEN_FAILURE;
1481 if (flTo->dwNumFiles != 1)
1482 return ERROR_CANCELLED;
1484 feFrom = &flFrom->feFiles[0];
1485 feTo= &flTo->feFiles[0];
1487 /* fail if destination doesn't exist */
1488 if (!feFrom->bExists)
1489 return ERROR_SHELL_INTERNAL_FILE_NOT_FOUND;
1491 /* fail if destination already exists */
1492 if (feTo->bExists)
1493 return ERROR_ALREADY_EXISTS;
1495 return SHNotifyMoveFileW(feFrom->szFullPath, feTo->szFullPath);
1498 /* alert the user if an unsupported flag is used */
1499 static void check_flags(FILEOP_FLAGS fFlags)
1501 WORD wUnsupportedFlags = FOF_NO_CONNECTED_ELEMENTS |
1502 FOF_NOCOPYSECURITYATTRIBS | FOF_NORECURSEREPARSE |
1503 FOF_RENAMEONCOLLISION | FOF_WANTMAPPINGHANDLE;
1505 if (fFlags & wUnsupportedFlags)
1506 FIXME("Unsupported flags: %04x\n", fFlags);
1509 /*************************************************************************
1510 * SHFileOperationW [SHELL32.@]
1512 * See SHFileOperationA
1514 int WINAPI SHFileOperationW(LPSHFILEOPSTRUCTW lpFileOp)
1516 FILE_OPERATION op;
1517 FILE_LIST flFrom, flTo;
1518 int ret = 0;
1520 if (!lpFileOp)
1521 return ERROR_INVALID_PARAMETER;
1523 check_flags(lpFileOp->fFlags);
1525 ZeroMemory(&flFrom, sizeof(FILE_LIST));
1526 ZeroMemory(&flTo, sizeof(FILE_LIST));
1528 if ((ret = parse_file_list(&flFrom, lpFileOp->pFrom)))
1529 return ret;
1531 if (lpFileOp->wFunc != FO_DELETE)
1532 parse_file_list(&flTo, lpFileOp->pTo);
1534 ZeroMemory(&op, sizeof(op));
1535 op.req = lpFileOp;
1536 op.bManyItems = (flFrom.dwNumFiles > 1);
1537 lpFileOp->fAnyOperationsAborted = FALSE;
1539 switch (lpFileOp->wFunc)
1541 case FO_COPY:
1542 ret = copy_files(&op, &flFrom, &flTo);
1543 break;
1544 case FO_DELETE:
1545 ret = delete_files(lpFileOp, &flFrom);
1546 break;
1547 case FO_MOVE:
1548 ret = move_files(lpFileOp, &flFrom, &flTo);
1549 break;
1550 case FO_RENAME:
1551 ret = rename_files(lpFileOp, &flFrom, &flTo);
1552 break;
1553 default:
1554 ret = ERROR_INVALID_PARAMETER;
1555 break;
1558 destroy_file_list(&flFrom);
1560 if (lpFileOp->wFunc != FO_DELETE)
1561 destroy_file_list(&flTo);
1563 if (ret == ERROR_CANCELLED)
1564 lpFileOp->fAnyOperationsAborted = TRUE;
1566 SetLastError(ERROR_SUCCESS);
1567 return ret;
1570 #define SHDSA_GetItemCount(hdsa) (*(int*)(hdsa))
1572 /*************************************************************************
1573 * SHFreeNameMappings [shell32.246]
1575 * Free the mapping handle returned by SHFileOperation if FOF_WANTSMAPPINGHANDLE
1576 * was specified.
1578 * PARAMS
1579 * hNameMapping [I] handle to the name mappings used during renaming of files
1581 * RETURNS
1582 * Nothing
1584 void WINAPI SHFreeNameMappings(HANDLE hNameMapping)
1586 if (hNameMapping)
1588 int i = SHDSA_GetItemCount((HDSA)hNameMapping) - 1;
1590 for (; i>= 0; i--)
1592 LPSHNAMEMAPPINGW lp = DSA_GetItemPtr(hNameMapping, i);
1594 SHFree(lp->pszOldPath);
1595 SHFree(lp->pszNewPath);
1597 DSA_Destroy(hNameMapping);
1601 /*************************************************************************
1602 * SheGetDirA [SHELL32.@]
1604 * drive = 0: returns the current directory path
1605 * drive > 0: returns the current directory path of the specified drive
1606 * drive=1 -> A: drive=2 -> B: ...
1607 * returns 0 if successful
1609 DWORD WINAPI SheGetDirA(DWORD drive, LPSTR buffer)
1611 WCHAR org_path[MAX_PATH];
1612 DWORD ret;
1613 char drv_path[3];
1615 /* change current directory to the specified drive */
1616 if (drive) {
1617 strcpy(drv_path, "A:");
1618 drv_path[0] += (char)drive-1;
1620 GetCurrentDirectoryW(MAX_PATH, org_path);
1622 SetCurrentDirectoryA(drv_path);
1625 /* query current directory path of the specified drive */
1626 ret = GetCurrentDirectoryA(MAX_PATH, buffer);
1628 /* back to the original drive */
1629 if (drive)
1630 SetCurrentDirectoryW(org_path);
1632 if (!ret)
1633 return GetLastError();
1635 return 0;
1638 /*************************************************************************
1639 * SheGetDirW [SHELL32.@]
1641 * drive = 0: returns the current directory path
1642 * drive > 0: returns the current directory path of the specified drive
1643 * drive=1 -> A: drive=2 -> B: ...
1644 * returns 0 if successful
1646 DWORD WINAPI SheGetDirW(DWORD drive, LPWSTR buffer)
1648 WCHAR org_path[MAX_PATH];
1649 DWORD ret;
1650 char drv_path[3];
1652 /* change current directory to the specified drive */
1653 if (drive) {
1654 strcpy(drv_path, "A:");
1655 drv_path[0] += (char)drive-1;
1657 GetCurrentDirectoryW(MAX_PATH, org_path);
1659 SetCurrentDirectoryA(drv_path);
1662 /* query current directory path of the specified drive */
1663 ret = GetCurrentDirectoryW(MAX_PATH, buffer);
1665 /* back to the original drive */
1666 if (drive)
1667 SetCurrentDirectoryW(org_path);
1669 if (!ret)
1670 return GetLastError();
1672 return 0;
1675 /*************************************************************************
1676 * SheChangeDirA [SHELL32.@]
1678 * changes the current directory to the specified path
1679 * and returns 0 if successful
1681 DWORD WINAPI SheChangeDirA(LPSTR path)
1683 if (SetCurrentDirectoryA(path))
1684 return 0;
1685 else
1686 return GetLastError();
1689 /*************************************************************************
1690 * SheChangeDirW [SHELL32.@]
1692 * changes the current directory to the specified path
1693 * and returns 0 if successful
1695 DWORD WINAPI SheChangeDirW(LPWSTR path)
1697 if (SetCurrentDirectoryW(path))
1698 return 0;
1699 else
1700 return GetLastError();
1703 /*************************************************************************
1704 * IsNetDrive [SHELL32.66]
1706 int WINAPI IsNetDrive(int drive)
1708 char root[4];
1709 strcpy(root, "A:\\");
1710 root[0] += (char)drive;
1711 return (GetDriveTypeA(root) == DRIVE_REMOTE);
1715 /*************************************************************************
1716 * RealDriveType [SHELL32.524]
1718 int WINAPI RealDriveType(int drive, BOOL bQueryNet)
1720 char root[] = "A:\\";
1721 root[0] += (char)drive;
1722 return GetDriveTypeA(root);
1725 /***********************************************************************
1726 * SHPathPrepareForWriteA (SHELL32.@)
1728 HRESULT WINAPI SHPathPrepareForWriteA(HWND hwnd, IUnknown *modless, LPCSTR path, DWORD flags)
1730 WCHAR wpath[MAX_PATH];
1731 MultiByteToWideChar( CP_ACP, 0, path, -1, wpath, MAX_PATH);
1732 return SHPathPrepareForWriteW(hwnd, modless, wpath, flags);
1735 /***********************************************************************
1736 * SHPathPrepareForWriteW (SHELL32.@)
1738 HRESULT WINAPI SHPathPrepareForWriteW(HWND hwnd, IUnknown *modless, LPCWSTR path, DWORD flags)
1740 DWORD res;
1741 DWORD err;
1742 LPCWSTR realpath;
1743 int len;
1744 WCHAR* last_slash;
1745 WCHAR* temppath=NULL;
1747 TRACE("%p %p %s 0x%08x\n", hwnd, modless, debugstr_w(path), flags);
1749 if (flags & ~(SHPPFW_DIRCREATE|SHPPFW_ASKDIRCREATE|SHPPFW_IGNOREFILENAME))
1750 FIXME("unimplemented flags 0x%08x\n", flags);
1752 /* cut off filename if necessary */
1753 if (flags & SHPPFW_IGNOREFILENAME)
1755 last_slash = StrRChrW(path, NULL, '\\');
1756 if (last_slash == NULL)
1757 len = 1;
1758 else
1759 len = last_slash - path + 1;
1760 temppath = HeapAlloc(GetProcessHeap(), 0, len * sizeof(WCHAR));
1761 if (!temppath)
1762 return E_OUTOFMEMORY;
1763 StrCpyNW(temppath, path, len);
1764 realpath = temppath;
1766 else
1768 realpath = path;
1771 /* try to create the directory if asked to */
1772 if (flags & (SHPPFW_DIRCREATE|SHPPFW_ASKDIRCREATE))
1774 if (flags & SHPPFW_ASKDIRCREATE)
1775 FIXME("treating SHPPFW_ASKDIRCREATE as SHPPFW_DIRCREATE\n");
1777 SHCreateDirectoryExW(0, realpath, NULL);
1780 /* check if we can access the directory */
1781 res = GetFileAttributesW(realpath);
1783 HeapFree(GetProcessHeap(), 0, temppath);
1785 if (res == INVALID_FILE_ATTRIBUTES)
1787 err = GetLastError();
1788 if (err == ERROR_FILE_NOT_FOUND)
1789 return HRESULT_FROM_WIN32(ERROR_PATH_NOT_FOUND);
1790 return HRESULT_FROM_WIN32(err);
1792 else if (res & FILE_ATTRIBUTE_DIRECTORY)
1793 return S_OK;
1794 else
1795 return HRESULT_FROM_WIN32(ERROR_DIRECTORY);