dlls: Fix va_list -> ms_va_list for variadic api calls
[wine/wine64.git] / dlls / shell32 / shlfileop.c
blob8191205524e1e06432eabdbecf152d0b136468a5
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 static const WCHAR wWildcardFile[] = {'*',0};
57 static const WCHAR wWildcardChars[] = {'*','?',0};
59 static DWORD SHNotifyCreateDirectoryA(LPCSTR path, LPSECURITY_ATTRIBUTES sec);
60 static DWORD SHNotifyCreateDirectoryW(LPCWSTR path, LPSECURITY_ATTRIBUTES sec);
61 static DWORD SHNotifyRemoveDirectoryA(LPCSTR path);
62 static DWORD SHNotifyRemoveDirectoryW(LPCWSTR path);
63 static DWORD SHNotifyDeleteFileA(LPCSTR path);
64 static DWORD SHNotifyDeleteFileW(LPCWSTR path);
65 static DWORD SHNotifyMoveFileW(LPCWSTR src, LPCWSTR dest);
66 static DWORD SHNotifyCopyFileW(LPCWSTR src, LPCWSTR dest, BOOL bFailIfExists);
67 static DWORD SHFindAttrW(LPCWSTR pName, BOOL fileOnly);
69 typedef struct
71 SHFILEOPSTRUCTW *req;
72 DWORD dwYesToAllMask;
73 BOOL bManyItems;
74 BOOL bCancelled;
75 } FILE_OPERATION;
77 /* Confirm dialogs with an optional "Yes To All" as used in file operations confirmations
79 static const WCHAR CONFIRM_MSG_PROP[] = {'W','I','N','E','_','C','O','N','F','I','R','M',0};
81 struct confirm_msg_info
83 LPWSTR lpszText;
84 LPWSTR lpszCaption;
85 HICON hIcon;
86 BOOL bYesToAll;
89 /* as some buttons may be hidden and the dialog height may change we may need
90 * to move the controls */
91 static void confirm_msg_move_button(HWND hDlg, INT iId, INT *xPos, INT yOffset, BOOL bShow)
93 HWND hButton = GetDlgItem(hDlg, iId);
94 RECT r;
96 if (bShow) {
97 POINT pt;
98 int width;
100 GetWindowRect(hButton, &r);
101 width = r.right - r.left;
102 pt.x = r.left;
103 pt.y = r.top;
104 ScreenToClient(hDlg, &pt);
105 MoveWindow(hButton, *xPos - width, pt.y - yOffset, width, r.bottom - r.top, FALSE);
106 *xPos -= width + 5;
108 else
109 ShowWindow(hButton, SW_HIDE);
112 /* Note: we paint the text manually and don't use the static control to make
113 * sure the text has the same height as the one computed in WM_INITDIALOG
115 static INT_PTR ConfirmMsgBox_Paint(HWND hDlg)
117 PAINTSTRUCT ps;
118 HFONT hOldFont;
119 RECT r;
120 HDC hdc;
122 BeginPaint(hDlg, &ps);
123 hdc = ps.hdc;
125 GetClientRect(GetDlgItem(hDlg, IDD_MESSAGE), &r);
126 /* this will remap the rect to dialog coords */
127 MapWindowPoints(GetDlgItem(hDlg, IDD_MESSAGE), hDlg, (LPPOINT)&r, 2);
128 hOldFont = SelectObject(hdc, (HFONT)SendDlgItemMessageW(hDlg, IDD_MESSAGE, WM_GETFONT, 0, 0));
129 DrawTextW(hdc, (LPWSTR)GetPropW(hDlg, CONFIRM_MSG_PROP), -1, &r, DT_NOPREFIX | DT_PATH_ELLIPSIS | DT_WORDBREAK);
130 SelectObject(hdc, hOldFont);
131 EndPaint(hDlg, &ps);
132 return TRUE;
135 static INT_PTR ConfirmMsgBox_Init(HWND hDlg, LPARAM lParam)
137 struct confirm_msg_info *info = (struct confirm_msg_info *)lParam;
138 INT xPos, yOffset;
139 int width, height;
140 HFONT hOldFont;
141 HDC hdc;
142 RECT r;
144 SetWindowTextW(hDlg, info->lpszCaption);
145 ShowWindow(GetDlgItem(hDlg, IDD_MESSAGE), SW_HIDE);
146 SetPropW(hDlg, CONFIRM_MSG_PROP, (HANDLE)info->lpszText);
147 SendDlgItemMessageW(hDlg, IDD_ICON, STM_SETICON, (WPARAM)info->hIcon, 0);
149 /* compute the text height and resize the dialog */
150 GetClientRect(GetDlgItem(hDlg, IDD_MESSAGE), &r);
151 hdc = GetDC(hDlg);
152 yOffset = r.bottom;
153 hOldFont = SelectObject(hdc, (HFONT)SendDlgItemMessageW(hDlg, IDD_MESSAGE, WM_GETFONT, 0, 0));
154 DrawTextW(hdc, info->lpszText, -1, &r, DT_NOPREFIX | DT_PATH_ELLIPSIS | DT_WORDBREAK | DT_CALCRECT);
155 SelectObject(hdc, hOldFont);
156 yOffset -= r.bottom;
157 yOffset = min(yOffset, 35); /* don't make the dialog too small */
158 ReleaseDC(hDlg, hdc);
160 GetClientRect(hDlg, &r);
161 xPos = r.right - 7;
162 GetWindowRect(hDlg, &r);
163 width = r.right - r.left;
164 height = r.bottom - r.top - yOffset;
165 MoveWindow(hDlg, (GetSystemMetrics(SM_CXSCREEN) - width)/2,
166 (GetSystemMetrics(SM_CYSCREEN) - height)/2, width, height, FALSE);
168 confirm_msg_move_button(hDlg, IDCANCEL, &xPos, yOffset, info->bYesToAll);
169 confirm_msg_move_button(hDlg, IDNO, &xPos, yOffset, TRUE);
170 confirm_msg_move_button(hDlg, IDD_YESTOALL, &xPos, yOffset, info->bYesToAll);
171 confirm_msg_move_button(hDlg, IDYES, &xPos, yOffset, TRUE);
172 return TRUE;
175 static INT_PTR CALLBACK ConfirmMsgBoxProc(HWND hDlg, UINT uMsg, WPARAM wParam, LPARAM lParam)
177 switch (uMsg)
179 case WM_INITDIALOG:
180 return ConfirmMsgBox_Init(hDlg, lParam);
181 case WM_PAINT:
182 return ConfirmMsgBox_Paint(hDlg);
183 case WM_COMMAND:
184 EndDialog(hDlg, wParam);
185 break;
186 case WM_CLOSE:
187 EndDialog(hDlg, IDCANCEL);
188 break;
190 return FALSE;
193 static int SHELL_ConfirmMsgBox(HWND hWnd, LPWSTR lpszText, LPWSTR lpszCaption, HICON hIcon, BOOL bYesToAll)
195 static const WCHAR wszTemplate[] = {'S','H','E','L','L','_','Y','E','S','T','O','A','L','L','_','M','S','G','B','O','X',0};
196 struct confirm_msg_info info;
198 info.lpszText = lpszText;
199 info.lpszCaption = lpszCaption;
200 info.hIcon = hIcon;
201 info.bYesToAll = bYesToAll;
202 return DialogBoxParamW(shell32_hInstance, wszTemplate, hWnd, ConfirmMsgBoxProc, (LPARAM)&info);
205 /* confirmation dialogs content */
206 typedef struct
208 HINSTANCE hIconInstance;
209 UINT icon_resource_id;
210 UINT caption_resource_id, text_resource_id;
211 } SHELL_ConfirmIDstruc;
213 static BOOL SHELL_ConfirmIDs(int nKindOfDialog, SHELL_ConfirmIDstruc *ids)
215 ids->hIconInstance = shell32_hInstance;
216 switch (nKindOfDialog) {
217 case ASK_DELETE_FILE:
218 ids->icon_resource_id = IDI_SHELL_CONFIRM_DELETE;
219 ids->caption_resource_id = IDS_DELETEITEM_CAPTION;
220 ids->text_resource_id = IDS_DELETEITEM_TEXT;
221 return TRUE;
222 case ASK_DELETE_FOLDER:
223 ids->icon_resource_id = IDI_SHELL_CONFIRM_DELETE;
224 ids->caption_resource_id = IDS_DELETEFOLDER_CAPTION;
225 ids->text_resource_id = IDS_DELETEITEM_TEXT;
226 return TRUE;
227 case ASK_DELETE_MULTIPLE_ITEM:
228 ids->icon_resource_id = IDI_SHELL_CONFIRM_DELETE;
229 ids->caption_resource_id = IDS_DELETEITEM_CAPTION;
230 ids->text_resource_id = IDS_DELETEMULTIPLE_TEXT;
231 return TRUE;
232 case ASK_TRASH_FILE:
233 ids->icon_resource_id = IDI_SHELL_TRASH_FILE;
234 ids->caption_resource_id = IDS_DELETEITEM_CAPTION;
235 ids->text_resource_id = IDS_TRASHITEM_TEXT;
236 return TRUE;
237 case ASK_TRASH_FOLDER:
238 ids->icon_resource_id = IDI_SHELL_TRASH_FILE;
239 ids->caption_resource_id = IDS_DELETEFOLDER_CAPTION;
240 ids->text_resource_id = IDS_TRASHFOLDER_TEXT;
241 return TRUE;
242 case ASK_TRASH_MULTIPLE_ITEM:
243 ids->icon_resource_id = IDI_SHELL_TRASH_FILE;
244 ids->caption_resource_id = IDS_DELETEITEM_CAPTION;
245 ids->text_resource_id = IDS_TRASHMULTIPLE_TEXT;
246 return TRUE;
247 case ASK_CANT_TRASH_ITEM:
248 ids->icon_resource_id = IDI_SHELL_CONFIRM_DELETE;
249 ids->caption_resource_id = IDS_DELETEITEM_CAPTION;
250 ids->text_resource_id = IDS_CANTTRASH_TEXT;
251 return TRUE;
252 case ASK_DELETE_SELECTED:
253 ids->icon_resource_id = IDI_SHELL_CONFIRM_DELETE;
254 ids->caption_resource_id = IDS_DELETEITEM_CAPTION;
255 ids->text_resource_id = IDS_DELETESELECTED_TEXT;
256 return TRUE;
257 case ASK_OVERWRITE_FILE:
258 ids->hIconInstance = NULL;
259 ids->icon_resource_id = IDI_WARNING;
260 ids->caption_resource_id = IDS_OVERWRITEFILE_CAPTION;
261 ids->text_resource_id = IDS_OVERWRITEFILE_TEXT;
262 return TRUE;
263 case ASK_OVERWRITE_FOLDER:
264 ids->hIconInstance = NULL;
265 ids->icon_resource_id = IDI_WARNING;
266 ids->caption_resource_id = IDS_OVERWRITEFILE_CAPTION;
267 ids->text_resource_id = IDS_OVERWRITEFOLDER_TEXT;
268 return TRUE;
269 default:
270 FIXME(" Unhandled nKindOfDialog %d stub\n", nKindOfDialog);
272 return FALSE;
275 static BOOL SHELL_ConfirmDialogW(HWND hWnd, int nKindOfDialog, LPCWSTR szDir, FILE_OPERATION *op)
277 WCHAR szCaption[255], szText[255], szBuffer[MAX_PATH + 256];
278 SHELL_ConfirmIDstruc ids;
279 DWORD_PTR args[1];
280 HICON hIcon;
281 int ret;
283 assert(nKindOfDialog >= 0 && nKindOfDialog < 32);
284 if (op && (op->dwYesToAllMask & (1 << nKindOfDialog)))
285 return TRUE;
287 if (!SHELL_ConfirmIDs(nKindOfDialog, &ids)) return FALSE;
289 LoadStringW(shell32_hInstance, ids.caption_resource_id, szCaption, sizeof(szCaption)/sizeof(WCHAR));
290 LoadStringW(shell32_hInstance, ids.text_resource_id, szText, sizeof(szText)/sizeof(WCHAR));
292 args[0] = (DWORD_PTR)szDir;
293 FormatMessageW(FORMAT_MESSAGE_FROM_STRING|FORMAT_MESSAGE_ARGUMENT_ARRAY,
294 szText, 0, 0, szBuffer, sizeof(szBuffer), (ms_va_list*)args);
295 hIcon = LoadIconW(ids.hIconInstance, (LPWSTR)MAKEINTRESOURCE(ids.icon_resource_id));
297 ret = SHELL_ConfirmMsgBox(hWnd, szBuffer, szCaption, hIcon, op && op->bManyItems);
298 if (op) {
299 if (ret == IDD_YESTOALL) {
300 op->dwYesToAllMask |= (1 << nKindOfDialog);
301 ret = IDYES;
303 if (ret == IDCANCEL)
304 op->bCancelled = TRUE;
305 if (ret != IDYES)
306 op->req->fAnyOperationsAborted = TRUE;
308 return ret == IDYES;
311 BOOL SHELL_ConfirmYesNoW(HWND hWnd, int nKindOfDialog, LPCWSTR szDir)
313 return SHELL_ConfirmDialogW(hWnd, nKindOfDialog, szDir, NULL);
316 static DWORD SHELL32_AnsiToUnicodeBuf(LPCSTR aPath, LPWSTR *wPath, DWORD minChars)
318 DWORD len = MultiByteToWideChar(CP_ACP, 0, aPath, -1, NULL, 0);
320 if (len < minChars)
321 len = minChars;
323 *wPath = HeapAlloc(GetProcessHeap(), 0, len * sizeof(WCHAR));
324 if (*wPath)
326 MultiByteToWideChar(CP_ACP, 0, aPath, -1, *wPath, len);
327 return NO_ERROR;
329 return E_OUTOFMEMORY;
332 static void SHELL32_FreeUnicodeBuf(LPWSTR wPath)
334 HeapFree(GetProcessHeap(), 0, wPath);
337 HRESULT WINAPI SHIsFileAvailableOffline(LPCWSTR path, LPDWORD status)
339 FIXME("(%s, %p) stub\n", debugstr_w(path), status);
340 return E_FAIL;
343 /**************************************************************************
344 * SHELL_DeleteDirectory() [internal]
346 * Asks for confirmation when bShowUI is true and deletes the directory and
347 * all its subdirectories and files if necessary.
349 static BOOL SHELL_DeleteDirectoryW(HWND hwnd, LPCWSTR pszDir, BOOL bShowUI)
351 BOOL ret = TRUE;
352 HANDLE hFind;
353 WIN32_FIND_DATAW wfd;
354 WCHAR szTemp[MAX_PATH];
356 /* Make sure the directory exists before eventually prompting the user */
357 PathCombineW(szTemp, pszDir, wWildcardFile);
358 hFind = FindFirstFileW(szTemp, &wfd);
359 if (hFind == INVALID_HANDLE_VALUE)
360 return FALSE;
362 if (!bShowUI || (ret = SHELL_ConfirmDialogW(hwnd, ASK_DELETE_FOLDER, pszDir, NULL)))
366 if (IsDotDir(wfd.cFileName))
367 continue;
368 PathCombineW(szTemp, pszDir, wfd.cFileName);
369 if (FILE_ATTRIBUTE_DIRECTORY & wfd.dwFileAttributes)
370 ret = SHELL_DeleteDirectoryW(hwnd, szTemp, FALSE);
371 else
372 ret = (SHNotifyDeleteFileW(szTemp) == ERROR_SUCCESS);
373 } while (ret && FindNextFileW(hFind, &wfd));
375 FindClose(hFind);
376 if (ret)
377 ret = (SHNotifyRemoveDirectoryW(pszDir) == ERROR_SUCCESS);
378 return ret;
381 /**************************************************************************
382 * Win32CreateDirectory [SHELL32.93]
384 * Creates a directory. Also triggers a change notify if one exists.
386 * PARAMS
387 * path [I] path to directory to create
389 * RETURNS
390 * TRUE if successful, FALSE otherwise
392 * NOTES
393 * Verified on Win98 / IE 5 (SHELL32 4.72, March 1999 build) to be ANSI.
394 * This is Unicode on NT/2000
396 static DWORD SHNotifyCreateDirectoryA(LPCSTR path, LPSECURITY_ATTRIBUTES sec)
398 LPWSTR wPath;
399 DWORD retCode;
401 TRACE("(%s, %p)\n", debugstr_a(path), sec);
403 retCode = SHELL32_AnsiToUnicodeBuf(path, &wPath, 0);
404 if (!retCode)
406 retCode = SHNotifyCreateDirectoryW(wPath, sec);
407 SHELL32_FreeUnicodeBuf(wPath);
409 return retCode;
412 /**********************************************************************/
414 static DWORD SHNotifyCreateDirectoryW(LPCWSTR path, LPSECURITY_ATTRIBUTES sec)
416 TRACE("(%s, %p)\n", debugstr_w(path), sec);
418 if (CreateDirectoryW(path, sec))
420 SHChangeNotify(SHCNE_MKDIR, SHCNF_PATHW, path, NULL);
421 return ERROR_SUCCESS;
423 return GetLastError();
426 /**********************************************************************/
428 BOOL WINAPI Win32CreateDirectoryAW(LPCVOID path, LPSECURITY_ATTRIBUTES sec)
430 if (SHELL_OsIsUnicode())
431 return (SHNotifyCreateDirectoryW(path, sec) == ERROR_SUCCESS);
432 return (SHNotifyCreateDirectoryA(path, sec) == ERROR_SUCCESS);
435 /************************************************************************
436 * Win32RemoveDirectory [SHELL32.94]
438 * Deletes a directory. Also triggers a change notify if one exists.
440 * PARAMS
441 * path [I] path to directory to delete
443 * RETURNS
444 * TRUE if successful, FALSE otherwise
446 * NOTES
447 * Verified on Win98 / IE 5 (SHELL32 4.72, March 1999 build) to be ANSI.
448 * This is Unicode on NT/2000
450 static DWORD SHNotifyRemoveDirectoryA(LPCSTR path)
452 LPWSTR wPath;
453 DWORD retCode;
455 TRACE("(%s)\n", debugstr_a(path));
457 retCode = SHELL32_AnsiToUnicodeBuf(path, &wPath, 0);
458 if (!retCode)
460 retCode = SHNotifyRemoveDirectoryW(wPath);
461 SHELL32_FreeUnicodeBuf(wPath);
463 return retCode;
466 /***********************************************************************/
468 static DWORD SHNotifyRemoveDirectoryW(LPCWSTR path)
470 BOOL ret;
471 TRACE("(%s)\n", debugstr_w(path));
473 ret = RemoveDirectoryW(path);
474 if (!ret)
476 /* Directory may be write protected */
477 DWORD dwAttr = GetFileAttributesW(path);
478 if (IsAttrib(dwAttr, FILE_ATTRIBUTE_READONLY))
479 if (SetFileAttributesW(path, dwAttr & ~FILE_ATTRIBUTE_READONLY))
480 ret = RemoveDirectoryW(path);
482 if (ret)
484 SHChangeNotify(SHCNE_RMDIR, SHCNF_PATHW, path, NULL);
485 return ERROR_SUCCESS;
487 return GetLastError();
490 /***********************************************************************/
492 BOOL WINAPI Win32RemoveDirectoryAW(LPCVOID path)
494 if (SHELL_OsIsUnicode())
495 return (SHNotifyRemoveDirectoryW(path) == ERROR_SUCCESS);
496 return (SHNotifyRemoveDirectoryA(path) == ERROR_SUCCESS);
499 /************************************************************************
500 * Win32DeleteFile [SHELL32.164]
502 * Deletes a file. Also triggers a change notify if one exists.
504 * PARAMS
505 * path [I] path to file to delete
507 * RETURNS
508 * TRUE if successful, FALSE otherwise
510 * NOTES
511 * Verified on Win98 / IE 5 (SHELL32 4.72, March 1999 build) to be ANSI.
512 * This is Unicode on NT/2000
514 static DWORD SHNotifyDeleteFileA(LPCSTR path)
516 LPWSTR wPath;
517 DWORD retCode;
519 TRACE("(%s)\n", debugstr_a(path));
521 retCode = SHELL32_AnsiToUnicodeBuf(path, &wPath, 0);
522 if (!retCode)
524 retCode = SHNotifyDeleteFileW(wPath);
525 SHELL32_FreeUnicodeBuf(wPath);
527 return retCode;
530 /***********************************************************************/
532 static DWORD SHNotifyDeleteFileW(LPCWSTR path)
534 BOOL ret;
536 TRACE("(%s)\n", debugstr_w(path));
538 ret = DeleteFileW(path);
539 if (!ret)
541 /* File may be write protected or a system file */
542 DWORD dwAttr = GetFileAttributesW(path);
543 if (IsAttrib(dwAttr, FILE_ATTRIBUTE_READONLY | FILE_ATTRIBUTE_SYSTEM))
544 if (SetFileAttributesW(path, dwAttr & ~(FILE_ATTRIBUTE_READONLY | FILE_ATTRIBUTE_SYSTEM)))
545 ret = DeleteFileW(path);
547 if (ret)
549 SHChangeNotify(SHCNE_DELETE, SHCNF_PATHW, path, NULL);
550 return ERROR_SUCCESS;
552 return GetLastError();
555 /***********************************************************************/
557 DWORD WINAPI Win32DeleteFileAW(LPCVOID path)
559 if (SHELL_OsIsUnicode())
560 return (SHNotifyDeleteFileW(path) == ERROR_SUCCESS);
561 return (SHNotifyDeleteFileA(path) == ERROR_SUCCESS);
564 /************************************************************************
565 * SHNotifyMoveFile [internal]
567 * Moves a file. Also triggers a change notify if one exists.
569 * PARAMS
570 * src [I] path to source file to move
571 * dest [I] path to target file to move to
573 * RETURNS
574 * ERORR_SUCCESS if successful
576 static DWORD SHNotifyMoveFileW(LPCWSTR src, LPCWSTR dest)
578 BOOL ret;
580 TRACE("(%s %s)\n", debugstr_w(src), debugstr_w(dest));
582 ret = MoveFileExW(src, dest, MOVEFILE_REPLACE_EXISTING);
584 /* MOVEFILE_REPLACE_EXISTING fails with dirs, so try MoveFile */
585 if (!ret)
586 ret = MoveFileW(src, dest);
588 if (!ret)
590 DWORD dwAttr;
592 dwAttr = SHFindAttrW(dest, FALSE);
593 if (INVALID_FILE_ATTRIBUTES == dwAttr)
595 /* Source file may be write protected or a system file */
596 dwAttr = GetFileAttributesW(src);
597 if (IsAttrib(dwAttr, FILE_ATTRIBUTE_READONLY | FILE_ATTRIBUTE_SYSTEM))
598 if (SetFileAttributesW(src, dwAttr & ~(FILE_ATTRIBUTE_READONLY | FILE_ATTRIBUTE_SYSTEM)))
599 ret = MoveFileW(src, dest);
602 if (ret)
604 SHChangeNotify(SHCNE_RENAMEITEM, SHCNF_PATHW, src, dest);
605 return ERROR_SUCCESS;
607 return GetLastError();
610 /************************************************************************
611 * SHNotifyCopyFile [internal]
613 * Copies a file. Also triggers a change notify if one exists.
615 * PARAMS
616 * src [I] path to source file to move
617 * dest [I] path to target file to move to
618 * bFailIfExists [I] if TRUE, the target file will not be overwritten if
619 * a file with this name already exists
621 * RETURNS
622 * ERROR_SUCCESS if successful
624 static DWORD SHNotifyCopyFileW(LPCWSTR src, LPCWSTR dest, BOOL bFailIfExists)
626 BOOL ret;
628 TRACE("(%s %s %s)\n", debugstr_w(src), debugstr_w(dest), bFailIfExists ? "failIfExists" : "");
630 ret = CopyFileW(src, dest, bFailIfExists);
631 if (ret)
633 SHChangeNotify(SHCNE_CREATE, SHCNF_PATHW, dest, NULL);
634 return ERROR_SUCCESS;
637 return GetLastError();
640 /*************************************************************************
641 * SHCreateDirectory [SHELL32.165]
643 * This function creates a file system folder whose fully qualified path is
644 * given by path. If one or more of the intermediate folders do not exist,
645 * they will be created as well.
647 * PARAMS
648 * hWnd [I]
649 * path [I] path of directory to create
651 * RETURNS
652 * ERROR_SUCCESS or one of the following values:
653 * ERROR_BAD_PATHNAME if the path is relative
654 * ERROR_FILE_EXISTS when a file with that name exists
655 * ERROR_PATH_NOT_FOUND can't find the path, probably invalid
656 * ERROR_INVALID_NAME if the path contains invalid chars
657 * ERROR_ALREADY_EXISTS when the directory already exists
658 * ERROR_FILENAME_EXCED_RANGE if the filename was to long to process
660 * NOTES
661 * exported by ordinal
662 * Win9x exports ANSI
663 * WinNT/2000 exports Unicode
665 DWORD WINAPI SHCreateDirectory(HWND hWnd, LPCVOID path)
667 if (SHELL_OsIsUnicode())
668 return SHCreateDirectoryExW(hWnd, path, NULL);
669 return SHCreateDirectoryExA(hWnd, path, NULL);
672 /*************************************************************************
673 * SHCreateDirectoryExA [SHELL32.@]
675 * This function creates a file system folder whose fully qualified path is
676 * given by path. If one or more of the intermediate folders do not exist,
677 * they will be created as well.
679 * PARAMS
680 * hWnd [I]
681 * path [I] path of directory to create
682 * sec [I] security attributes to use or NULL
684 * RETURNS
685 * ERROR_SUCCESS or one of the following values:
686 * ERROR_BAD_PATHNAME or ERROR_PATH_NOT_FOUND if the path is relative
687 * ERROR_INVALID_NAME if the path contains invalid chars
688 * ERROR_FILE_EXISTS when a file with that name exists
689 * ERROR_ALREADY_EXISTS when the directory already exists
690 * ERROR_FILENAME_EXCED_RANGE if the filename was to long to process
692 * FIXME: Not implemented yet;
693 * SHCreateDirectoryEx also verifies that the files in the directory will be visible
694 * if the path is a network path to deal with network drivers which might have a limited
695 * but unknown maximum path length. If not:
697 * If hWnd is set to a valid window handle, a message box is displayed warning
698 * the user that the files may not be accessible. If the user chooses not to
699 * proceed, the function returns ERROR_CANCELLED.
701 * If hWnd is set to NULL, no user interface is displayed and the function
702 * returns ERROR_CANCELLED.
704 int WINAPI SHCreateDirectoryExA(HWND hWnd, LPCSTR path, LPSECURITY_ATTRIBUTES sec)
706 LPWSTR wPath;
707 DWORD retCode;
709 TRACE("(%s, %p)\n", debugstr_a(path), sec);
711 retCode = SHELL32_AnsiToUnicodeBuf(path, &wPath, 0);
712 if (!retCode)
714 retCode = SHCreateDirectoryExW(hWnd, wPath, sec);
715 SHELL32_FreeUnicodeBuf(wPath);
717 return retCode;
720 /*************************************************************************
721 * SHCreateDirectoryExW [SHELL32.@]
723 * See SHCreateDirectoryExA.
725 int WINAPI SHCreateDirectoryExW(HWND hWnd, LPCWSTR path, LPSECURITY_ATTRIBUTES sec)
727 int ret = ERROR_BAD_PATHNAME;
728 TRACE("(%p, %s, %p)\n", hWnd, debugstr_w(path), sec);
730 if (PathIsRelativeW(path))
732 SetLastError(ret);
734 else
736 ret = SHNotifyCreateDirectoryW(path, sec);
737 /* Refuse to work on certain error codes before trying to create directories recursively */
738 if (ret != ERROR_SUCCESS &&
739 ret != ERROR_FILE_EXISTS &&
740 ret != ERROR_ALREADY_EXISTS &&
741 ret != ERROR_FILENAME_EXCED_RANGE)
743 WCHAR *pEnd, *pSlash, szTemp[MAX_PATH + 1]; /* extra for PathAddBackslash() */
745 lstrcpynW(szTemp, path, MAX_PATH);
746 pEnd = PathAddBackslashW(szTemp);
747 pSlash = szTemp + 3;
749 while (*pSlash)
751 while (*pSlash && *pSlash != '\\') pSlash++;
752 if (*pSlash)
754 *pSlash = 0; /* terminate path at separator */
756 ret = SHNotifyCreateDirectoryW(szTemp, pSlash + 1 == pEnd ? sec : NULL);
758 *pSlash++ = '\\'; /* put the separator back */
762 if (ret && hWnd && (ERROR_CANCELLED != ret))
764 /* We failed and should show a dialog box */
765 FIXME("Show system error message, creating path %s, failed with error %d\n", debugstr_w(path), ret);
766 ret = ERROR_CANCELLED; /* Error has been already presented to user (not really yet!) */
769 return ret;
772 /*************************************************************************
773 * SHFindAttrW [internal]
775 * Get the Attributes for a file or directory. The difference to GetAttributes()
776 * is that this function will also work for paths containing wildcard characters
777 * in its filename.
779 * PARAMS
780 * path [I] path of directory or file to check
781 * fileOnly [I] TRUE if only files should be found
783 * RETURNS
784 * INVALID_FILE_ATTRIBUTES if the path does not exist, the actual attributes of
785 * the first file or directory found otherwise
787 static DWORD SHFindAttrW(LPCWSTR pName, BOOL fileOnly)
789 WIN32_FIND_DATAW wfd;
790 BOOL b_FileMask = fileOnly && (NULL != StrPBrkW(pName, wWildcardChars));
791 DWORD dwAttr = INVALID_FILE_ATTRIBUTES;
792 HANDLE hFind = FindFirstFileW(pName, &wfd);
794 TRACE("%s %d\n", debugstr_w(pName), fileOnly);
795 if (INVALID_HANDLE_VALUE != hFind)
799 if (b_FileMask && IsAttribDir(wfd.dwFileAttributes))
800 continue;
801 dwAttr = wfd.dwFileAttributes;
802 break;
804 while (FindNextFileW(hFind, &wfd));
805 FindClose(hFind);
807 return dwAttr;
810 /*************************************************************************
812 * SHNameTranslate HelperFunction for SHFileOperationA
814 * Translates a list of 0 terminated ASCII strings into Unicode. If *wString
815 * is NULL, only the necessary size of the string is determined and returned,
816 * otherwise the ASCII strings are copied into it and the buffer is increased
817 * to point to the location after the final 0 termination char.
819 static DWORD SHNameTranslate(LPWSTR* wString, LPCWSTR* pWToFrom, BOOL more)
821 DWORD size = 0, aSize = 0;
822 LPCSTR aString = (LPCSTR)*pWToFrom;
824 if (aString)
828 size = lstrlenA(aString) + 1;
829 aSize += size;
830 aString += size;
831 } while ((size != 1) && more);
832 /* The two sizes might be different in the case of multibyte chars */
833 size = MultiByteToWideChar(CP_ACP, 0, (LPCSTR)*pWToFrom, aSize, *wString, 0);
834 if (*wString) /* only in the second loop */
836 MultiByteToWideChar(CP_ACP, 0, (LPCSTR)*pWToFrom, aSize, *wString, size);
837 *pWToFrom = *wString;
838 *wString += size;
841 return size;
843 /*************************************************************************
844 * SHFileOperationA [SHELL32.@]
846 * Function to copy, move, delete and create one or more files with optional
847 * user prompts.
849 * PARAMS
850 * lpFileOp [I/O] pointer to a structure containing all the necessary information
852 * RETURNS
853 * Success: ERROR_SUCCESS.
854 * Failure: ERROR_CANCELLED.
856 * NOTES
857 * exported by name
859 int WINAPI SHFileOperationA(LPSHFILEOPSTRUCTA lpFileOp)
861 SHFILEOPSTRUCTW nFileOp = *((LPSHFILEOPSTRUCTW)lpFileOp);
862 int retCode = 0;
863 DWORD size;
864 LPWSTR ForFree = NULL, /* we change wString in SHNameTranslate and can't use it for freeing */
865 wString = NULL; /* we change this in SHNameTranslate */
867 TRACE("\n");
868 if (FO_DELETE == (nFileOp.wFunc & FO_MASK))
869 nFileOp.pTo = NULL; /* we need a NULL or a valid pointer for translation */
870 if (!(nFileOp.fFlags & FOF_SIMPLEPROGRESS))
871 nFileOp.lpszProgressTitle = NULL; /* we need a NULL or a valid pointer for translation */
872 while (1) /* every loop calculate size, second translate also, if we have storage for this */
874 size = SHNameTranslate(&wString, &nFileOp.lpszProgressTitle, FALSE); /* no loop */
875 size += SHNameTranslate(&wString, &nFileOp.pFrom, TRUE); /* internal loop */
876 size += SHNameTranslate(&wString, &nFileOp.pTo, TRUE); /* internal loop */
878 if (ForFree)
880 retCode = SHFileOperationW(&nFileOp);
881 HeapFree(GetProcessHeap(), 0, ForFree); /* we cannot use wString, it was changed */
882 break;
884 else
886 wString = ForFree = HeapAlloc(GetProcessHeap(), 0, size * sizeof(WCHAR));
887 if (ForFree) continue;
888 retCode = ERROR_OUTOFMEMORY;
889 nFileOp.fAnyOperationsAborted = TRUE;
890 SetLastError(retCode);
891 return retCode;
895 lpFileOp->hNameMappings = nFileOp.hNameMappings;
896 lpFileOp->fAnyOperationsAborted = nFileOp.fAnyOperationsAborted;
897 return retCode;
900 #define ERROR_SHELL_INTERNAL_FILE_NOT_FOUND 1026
902 typedef struct
904 DWORD attributes;
905 LPWSTR szDirectory;
906 LPWSTR szFilename;
907 LPWSTR szFullPath;
908 BOOL bFromWildcard;
909 BOOL bFromRelative;
910 BOOL bExists;
911 } FILE_ENTRY;
913 typedef struct
915 FILE_ENTRY *feFiles;
916 DWORD num_alloc;
917 DWORD dwNumFiles;
918 BOOL bAnyFromWildcard;
919 BOOL bAnyDirectories;
920 BOOL bAnyDontExist;
921 } FILE_LIST;
924 static inline void grow_list(FILE_LIST *list)
926 FILE_ENTRY *new = HeapReAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, list->feFiles,
927 list->num_alloc * 2 * sizeof(*new) );
928 list->feFiles = new;
929 list->num_alloc *= 2;
932 /* adds a file to the FILE_ENTRY struct
934 static void add_file_to_entry(FILE_ENTRY *feFile, LPCWSTR szFile)
936 DWORD dwLen = lstrlenW(szFile) + 1;
937 LPCWSTR ptr;
939 feFile->szFullPath = HeapAlloc(GetProcessHeap(), 0, dwLen * sizeof(WCHAR));
940 lstrcpyW(feFile->szFullPath, szFile);
942 ptr = StrRChrW(szFile, NULL, '\\');
943 if (ptr)
945 dwLen = ptr - szFile + 1;
946 feFile->szDirectory = HeapAlloc(GetProcessHeap(), 0, dwLen * sizeof(WCHAR));
947 lstrcpynW(feFile->szDirectory, szFile, dwLen);
949 dwLen = lstrlenW(feFile->szFullPath) - dwLen + 1;
950 feFile->szFilename = HeapAlloc(GetProcessHeap(), 0, dwLen * sizeof(WCHAR));
951 lstrcpyW(feFile->szFilename, ptr + 1); /* skip over backslash */
953 feFile->bFromWildcard = FALSE;
956 static LPWSTR wildcard_to_file(LPCWSTR szWildCard, LPCWSTR szFileName)
958 LPCWSTR ptr;
959 LPWSTR szFullPath;
960 DWORD dwDirLen, dwFullLen;
962 ptr = StrRChrW(szWildCard, NULL, '\\');
963 dwDirLen = ptr - szWildCard + 1;
965 dwFullLen = dwDirLen + lstrlenW(szFileName) + 1;
966 szFullPath = HeapAlloc(GetProcessHeap(), 0, dwFullLen * sizeof(WCHAR));
968 lstrcpynW(szFullPath, szWildCard, dwDirLen + 1);
969 lstrcatW(szFullPath, szFileName);
971 return szFullPath;
974 static void parse_wildcard_files(FILE_LIST *flList, LPCWSTR szFile, LPDWORD pdwListIndex)
976 WIN32_FIND_DATAW wfd;
977 HANDLE hFile = FindFirstFileW(szFile, &wfd);
978 FILE_ENTRY *file;
979 LPWSTR szFullPath;
980 BOOL res;
982 if (hFile == INVALID_HANDLE_VALUE) return;
984 for (res = TRUE; res; res = FindNextFileW(hFile, &wfd))
986 if (IsDotDir(wfd.cFileName)) continue;
987 if (*pdwListIndex >= flList->num_alloc) grow_list( flList );
988 szFullPath = wildcard_to_file(szFile, wfd.cFileName);
989 file = &flList->feFiles[(*pdwListIndex)++];
990 add_file_to_entry(file, szFullPath);
991 file->bFromWildcard = TRUE;
992 file->attributes = wfd.dwFileAttributes;
993 if (IsAttribDir(file->attributes)) flList->bAnyDirectories = TRUE;
994 HeapFree(GetProcessHeap(), 0, szFullPath);
997 FindClose(hFile);
1000 /* takes the null-separated file list and fills out the FILE_LIST */
1001 static HRESULT parse_file_list(FILE_LIST *flList, LPCWSTR szFiles)
1003 LPCWSTR ptr = szFiles;
1004 WCHAR szCurFile[MAX_PATH];
1005 DWORD i = 0;
1007 if (!szFiles)
1008 return ERROR_INVALID_PARAMETER;
1010 flList->bAnyFromWildcard = FALSE;
1011 flList->bAnyDirectories = FALSE;
1012 flList->bAnyDontExist = FALSE;
1013 flList->num_alloc = 32;
1014 flList->dwNumFiles = 0;
1016 /* empty list */
1017 if (!szFiles[0])
1018 return ERROR_ACCESS_DENIED;
1020 flList->feFiles = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY,
1021 flList->num_alloc * sizeof(FILE_ENTRY));
1023 while (*ptr)
1025 if (i >= flList->num_alloc) grow_list( flList );
1027 /* change relative to absolute path */
1028 if (PathIsRelativeW(ptr))
1030 GetCurrentDirectoryW(MAX_PATH, szCurFile);
1031 PathCombineW(szCurFile, szCurFile, ptr);
1032 flList->feFiles[i].bFromRelative = TRUE;
1034 else
1036 lstrcpyW(szCurFile, ptr);
1037 flList->feFiles[i].bFromRelative = FALSE;
1040 /* parse wildcard files if they are in the filename */
1041 if (StrPBrkW(szCurFile, wWildcardChars))
1043 parse_wildcard_files(flList, szCurFile, &i);
1044 flList->bAnyFromWildcard = TRUE;
1045 i--;
1047 else
1049 FILE_ENTRY *file = &flList->feFiles[i];
1050 add_file_to_entry(file, szCurFile);
1051 file->attributes = GetFileAttributesW( file->szFullPath );
1052 file->bExists = (file->attributes != INVALID_FILE_ATTRIBUTES);
1053 if (!file->bExists) flList->bAnyDontExist = TRUE;
1054 if (IsAttribDir(file->attributes)) flList->bAnyDirectories = TRUE;
1057 /* advance to the next string */
1058 ptr += lstrlenW(ptr) + 1;
1059 i++;
1061 flList->dwNumFiles = i;
1063 return S_OK;
1066 /* free the FILE_LIST */
1067 static void destroy_file_list(FILE_LIST *flList)
1069 DWORD i;
1071 if (!flList || !flList->feFiles)
1072 return;
1074 for (i = 0; i < flList->dwNumFiles; i++)
1076 HeapFree(GetProcessHeap(), 0, flList->feFiles[i].szDirectory);
1077 HeapFree(GetProcessHeap(), 0, flList->feFiles[i].szFilename);
1078 HeapFree(GetProcessHeap(), 0, flList->feFiles[i].szFullPath);
1081 HeapFree(GetProcessHeap(), 0, flList->feFiles);
1084 static void copy_dir_to_dir(FILE_OPERATION *op, const FILE_ENTRY *feFrom, LPCWSTR szDestPath)
1086 WCHAR szFrom[MAX_PATH], szTo[MAX_PATH];
1087 SHFILEOPSTRUCTW fileOp;
1089 static const WCHAR wildCardFiles[] = {'*','.','*',0};
1091 if (IsDotDir(feFrom->szFilename))
1092 return;
1094 if (PathFileExistsW(szDestPath))
1095 PathCombineW(szTo, szDestPath, feFrom->szFilename);
1096 else
1097 lstrcpyW(szTo, szDestPath);
1099 if (!(op->req->fFlags & FOF_NOCONFIRMATION) && PathFileExistsW(szTo)) {
1100 if (!SHELL_ConfirmDialogW(op->req->hwnd, ASK_OVERWRITE_FOLDER, feFrom->szFilename, op))
1102 /* Vista returns an ERROR_CANCELLED even if user pressed "No" */
1103 if (!op->bManyItems)
1104 op->bCancelled = TRUE;
1105 return;
1109 szTo[lstrlenW(szTo) + 1] = '\0';
1110 SHNotifyCreateDirectoryW(szTo, NULL);
1112 PathCombineW(szFrom, feFrom->szFullPath, wildCardFiles);
1113 szFrom[lstrlenW(szFrom) + 1] = '\0';
1115 fileOp = *op->req;
1116 fileOp.pFrom = szFrom;
1117 fileOp.pTo = szTo;
1118 fileOp.fFlags &= ~FOF_MULTIDESTFILES; /* we know we're copying to one dir */
1120 /* Don't ask the user about overwriting files when he accepted to overwrite the
1121 folder. FIXME: this is not exactly what Windows does - e.g. there would be
1122 an additional confirmation for a nested folder */
1123 fileOp.fFlags |= FOF_NOCONFIRMATION;
1125 SHFileOperationW(&fileOp);
1128 static BOOL copy_file_to_file(FILE_OPERATION *op, const WCHAR *szFrom, const WCHAR *szTo)
1130 if (!(op->req->fFlags & FOF_NOCONFIRMATION) && PathFileExistsW(szTo))
1132 if (!SHELL_ConfirmDialogW(op->req->hwnd, ASK_OVERWRITE_FILE, PathFindFileNameW(szTo), op))
1133 return 0;
1136 return SHNotifyCopyFileW(szFrom, szTo, FALSE) == 0;
1139 /* copy a file or directory to another directory */
1140 static void copy_to_dir(FILE_OPERATION *op, const FILE_ENTRY *feFrom, const FILE_ENTRY *feTo)
1142 if (!PathFileExistsW(feTo->szFullPath))
1143 SHNotifyCreateDirectoryW(feTo->szFullPath, NULL);
1145 if (IsAttribFile(feFrom->attributes))
1147 WCHAR szDestPath[MAX_PATH];
1149 PathCombineW(szDestPath, feTo->szFullPath, feFrom->szFilename);
1150 copy_file_to_file(op, feFrom->szFullPath, szDestPath);
1152 else if (!(op->req->fFlags & FOF_FILESONLY && feFrom->bFromWildcard))
1153 copy_dir_to_dir(op, feFrom, feTo->szFullPath);
1156 static void create_dest_dirs(LPCWSTR szDestDir)
1158 WCHAR dir[MAX_PATH];
1159 LPCWSTR ptr = StrChrW(szDestDir, '\\');
1161 /* make sure all directories up to last one are created */
1162 while (ptr && (ptr = StrChrW(ptr + 1, '\\')))
1164 lstrcpynW(dir, szDestDir, ptr - szDestDir + 1);
1166 if (!PathFileExistsW(dir))
1167 SHNotifyCreateDirectoryW(dir, NULL);
1170 /* create last directory */
1171 if (!PathFileExistsW(szDestDir))
1172 SHNotifyCreateDirectoryW(szDestDir, NULL);
1175 /* the FO_COPY operation */
1176 static HRESULT copy_files(FILE_OPERATION *op, const FILE_LIST *flFrom, FILE_LIST *flTo)
1178 DWORD i;
1179 const FILE_ENTRY *entryToCopy;
1180 const FILE_ENTRY *fileDest = &flTo->feFiles[0];
1182 if (flFrom->bAnyDontExist)
1183 return ERROR_SHELL_INTERNAL_FILE_NOT_FOUND;
1185 if (op->req->fFlags & FOF_MULTIDESTFILES)
1187 if (flFrom->bAnyFromWildcard)
1188 return ERROR_CANCELLED;
1190 if (flFrom->dwNumFiles != flTo->dwNumFiles)
1192 if (flFrom->dwNumFiles != 1 && !IsAttribDir(fileDest->attributes))
1193 return ERROR_CANCELLED;
1195 flTo->dwNumFiles = 1;
1197 else if (IsAttribDir(fileDest->attributes))
1199 for (i = 1; i < flTo->dwNumFiles; i++)
1200 if (!IsAttribDir(flTo->feFiles[i].attributes) ||
1201 !IsAttribDir(flFrom->feFiles[i].attributes))
1203 return ERROR_CANCELLED;
1207 else if (flFrom->dwNumFiles != 1)
1209 if (flTo->dwNumFiles != 1 && !IsAttribDir(fileDest->attributes))
1210 return ERROR_CANCELLED;
1212 if (PathFileExistsW(fileDest->szFullPath) &&
1213 IsAttribFile(fileDest->attributes))
1215 return ERROR_CANCELLED;
1218 if (flTo->dwNumFiles == 1 && fileDest->bFromRelative &&
1219 !PathFileExistsW(fileDest->szFullPath))
1221 return ERROR_CANCELLED;
1225 for (i = 0; i < flFrom->dwNumFiles; i++)
1227 entryToCopy = &flFrom->feFiles[i];
1229 if ((op->req->fFlags & FOF_MULTIDESTFILES) &&
1230 flTo->dwNumFiles > 1)
1232 fileDest = &flTo->feFiles[i];
1235 if (IsAttribDir(entryToCopy->attributes) &&
1236 !lstrcmpiW(entryToCopy->szFullPath, fileDest->szDirectory))
1238 return ERROR_SUCCESS;
1241 create_dest_dirs(fileDest->szDirectory);
1243 if (!lstrcmpiW(entryToCopy->szFullPath, fileDest->szFullPath))
1245 if (IsAttribFile(entryToCopy->attributes))
1246 return ERROR_NO_MORE_SEARCH_HANDLES;
1247 else
1248 return ERROR_SUCCESS;
1251 if ((flFrom->dwNumFiles > 1 && flTo->dwNumFiles == 1) ||
1252 IsAttribDir(fileDest->attributes))
1254 copy_to_dir(op, entryToCopy, fileDest);
1256 else if (IsAttribDir(entryToCopy->attributes))
1258 copy_dir_to_dir(op, entryToCopy, fileDest->szFullPath);
1260 else
1262 if (!copy_file_to_file(op, entryToCopy->szFullPath, fileDest->szFullPath))
1264 op->req->fAnyOperationsAborted = TRUE;
1265 return ERROR_CANCELLED;
1269 /* Vista return code. XP would return e.g. ERROR_FILE_NOT_FOUND, ERROR_ALREADY_EXISTS */
1270 if (op->bCancelled)
1271 return ERROR_CANCELLED;
1274 /* Vista return code. On XP if the used pressed "No" for the last item,
1275 * ERROR_ARENA_TRASHED would be returned */
1276 return ERROR_SUCCESS;
1279 static BOOL confirm_delete_list(HWND hWnd, DWORD fFlags, BOOL fTrash, const FILE_LIST *flFrom)
1281 if (flFrom->dwNumFiles > 1)
1283 WCHAR tmp[8];
1284 const WCHAR format[] = {'%','d',0};
1286 wnsprintfW(tmp, sizeof(tmp)/sizeof(tmp[0]), format, flFrom->dwNumFiles);
1287 return SHELL_ConfirmDialogW(hWnd, (fTrash?ASK_TRASH_MULTIPLE_ITEM:ASK_DELETE_MULTIPLE_ITEM), tmp, NULL);
1289 else
1291 const FILE_ENTRY *fileEntry = &flFrom->feFiles[0];
1293 if (IsAttribFile(fileEntry->attributes))
1294 return SHELL_ConfirmDialogW(hWnd, (fTrash?ASK_TRASH_FILE:ASK_DELETE_FILE), fileEntry->szFullPath, NULL);
1295 else if (!(fFlags & FOF_FILESONLY && fileEntry->bFromWildcard))
1296 return SHELL_ConfirmDialogW(hWnd, (fTrash?ASK_TRASH_FOLDER:ASK_DELETE_FOLDER), fileEntry->szFullPath, NULL);
1298 return TRUE;
1301 /* the FO_DELETE operation */
1302 static HRESULT delete_files(LPSHFILEOPSTRUCTW lpFileOp, const FILE_LIST *flFrom)
1304 const FILE_ENTRY *fileEntry;
1305 DWORD i;
1306 BOOL bPathExists;
1307 BOOL bTrash;
1309 if (!flFrom->dwNumFiles)
1310 return ERROR_SUCCESS;
1312 /* Windows also checks only the first item */
1313 bTrash = (lpFileOp->fFlags & FOF_ALLOWUNDO)
1314 && TRASH_CanTrashFile(flFrom->feFiles[0].szFullPath);
1316 if (!(lpFileOp->fFlags & FOF_NOCONFIRMATION) || (!bTrash && lpFileOp->fFlags & FOF_WANTNUKEWARNING))
1317 if (!confirm_delete_list(lpFileOp->hwnd, lpFileOp->fFlags, bTrash, flFrom))
1319 lpFileOp->fAnyOperationsAborted = TRUE;
1320 return 0;
1323 for (i = 0; i < flFrom->dwNumFiles; i++)
1325 bPathExists = TRUE;
1326 fileEntry = &flFrom->feFiles[i];
1328 if (!IsAttribFile(fileEntry->attributes) &&
1329 (lpFileOp->fFlags & FOF_FILESONLY && fileEntry->bFromWildcard))
1330 continue;
1332 if (bTrash)
1334 BOOL bDelete;
1335 if (TRASH_TrashFile(fileEntry->szFullPath))
1336 continue;
1338 /* Note: Windows silently deletes the file in such a situation, we show a dialog */
1339 if (!(lpFileOp->fFlags & FOF_NOCONFIRMATION) || (lpFileOp->fFlags & FOF_WANTNUKEWARNING))
1340 bDelete = SHELL_ConfirmDialogW(lpFileOp->hwnd, ASK_CANT_TRASH_ITEM, fileEntry->szFullPath, NULL);
1341 else
1342 bDelete = TRUE;
1344 if (!bDelete)
1346 lpFileOp->fAnyOperationsAborted = TRUE;
1347 break;
1351 /* delete the file or directory */
1352 if (IsAttribFile(fileEntry->attributes))
1353 bPathExists = DeleteFileW(fileEntry->szFullPath);
1354 else
1355 bPathExists = SHELL_DeleteDirectoryW(lpFileOp->hwnd, fileEntry->szFullPath, FALSE);
1357 if (!bPathExists)
1358 return ERROR_PATH_NOT_FOUND;
1361 return ERROR_SUCCESS;
1364 static void move_dir_to_dir(LPSHFILEOPSTRUCTW lpFileOp, const FILE_ENTRY *feFrom, LPCWSTR szDestPath)
1366 WCHAR szFrom[MAX_PATH], szTo[MAX_PATH];
1367 SHFILEOPSTRUCTW fileOp;
1369 static const WCHAR wildCardFiles[] = {'*','.','*',0};
1371 if (IsDotDir(feFrom->szFilename))
1372 return;
1374 SHNotifyCreateDirectoryW(szDestPath, NULL);
1376 PathCombineW(szFrom, feFrom->szFullPath, wildCardFiles);
1377 szFrom[lstrlenW(szFrom) + 1] = '\0';
1379 lstrcpyW(szTo, szDestPath);
1380 szTo[lstrlenW(szDestPath) + 1] = '\0';
1382 fileOp = *lpFileOp;
1383 fileOp.pFrom = szFrom;
1384 fileOp.pTo = szTo;
1386 SHFileOperationW(&fileOp);
1389 /* moves a file or directory to another directory */
1390 static void move_to_dir(LPSHFILEOPSTRUCTW lpFileOp, const FILE_ENTRY *feFrom, const FILE_ENTRY *feTo)
1392 WCHAR szDestPath[MAX_PATH];
1394 PathCombineW(szDestPath, feTo->szFullPath, feFrom->szFilename);
1396 if (IsAttribFile(feFrom->attributes))
1397 SHNotifyMoveFileW(feFrom->szFullPath, szDestPath);
1398 else if (!(lpFileOp->fFlags & FOF_FILESONLY && feFrom->bFromWildcard))
1399 move_dir_to_dir(lpFileOp, feFrom, szDestPath);
1402 /* the FO_MOVE operation */
1403 static HRESULT move_files(LPSHFILEOPSTRUCTW lpFileOp, const FILE_LIST *flFrom, const FILE_LIST *flTo)
1405 DWORD i;
1406 const FILE_ENTRY *entryToMove;
1407 const FILE_ENTRY *fileDest;
1409 if (!flFrom->dwNumFiles || !flTo->dwNumFiles)
1410 return ERROR_CANCELLED;
1412 if (!(lpFileOp->fFlags & FOF_MULTIDESTFILES) &&
1413 flTo->dwNumFiles > 1 && flFrom->dwNumFiles > 1)
1415 return ERROR_CANCELLED;
1418 if (!(lpFileOp->fFlags & FOF_MULTIDESTFILES) &&
1419 !flFrom->bAnyDirectories &&
1420 flFrom->dwNumFiles > flTo->dwNumFiles)
1422 return ERROR_CANCELLED;
1425 if (!PathFileExistsW(flTo->feFiles[0].szDirectory))
1426 return ERROR_CANCELLED;
1428 if ((lpFileOp->fFlags & FOF_MULTIDESTFILES) &&
1429 flFrom->dwNumFiles != flTo->dwNumFiles)
1431 return ERROR_CANCELLED;
1434 fileDest = &flTo->feFiles[0];
1435 for (i = 0; i < flFrom->dwNumFiles; i++)
1437 entryToMove = &flFrom->feFiles[i];
1439 if (lpFileOp->fFlags & FOF_MULTIDESTFILES)
1440 fileDest = &flTo->feFiles[i];
1442 if (!PathFileExistsW(fileDest->szDirectory))
1443 return ERROR_CANCELLED;
1445 if (fileDest->bExists && IsAttribDir(fileDest->attributes))
1446 move_to_dir(lpFileOp, entryToMove, fileDest);
1447 else
1448 SHNotifyMoveFileW(entryToMove->szFullPath, fileDest->szFullPath);
1451 return ERROR_SUCCESS;
1454 /* the FO_RENAME files */
1455 static HRESULT rename_files(LPSHFILEOPSTRUCTW lpFileOp, const FILE_LIST *flFrom, const FILE_LIST *flTo)
1457 const FILE_ENTRY *feFrom;
1458 const FILE_ENTRY *feTo;
1460 if (flFrom->dwNumFiles != 1)
1461 return ERROR_GEN_FAILURE;
1463 if (flTo->dwNumFiles != 1)
1464 return ERROR_CANCELLED;
1466 feFrom = &flFrom->feFiles[0];
1467 feTo= &flTo->feFiles[0];
1469 /* fail if destination doesn't exist */
1470 if (!feFrom->bExists)
1471 return ERROR_SHELL_INTERNAL_FILE_NOT_FOUND;
1473 /* fail if destination already exists */
1474 if (feTo->bExists)
1475 return ERROR_ALREADY_EXISTS;
1477 return SHNotifyMoveFileW(feFrom->szFullPath, feTo->szFullPath);
1480 /* alert the user if an unsupported flag is used */
1481 static void check_flags(FILEOP_FLAGS fFlags)
1483 WORD wUnsupportedFlags = FOF_NO_CONNECTED_ELEMENTS |
1484 FOF_NOCOPYSECURITYATTRIBS | FOF_NORECURSEREPARSE |
1485 FOF_RENAMEONCOLLISION | FOF_WANTMAPPINGHANDLE;
1487 if (fFlags & wUnsupportedFlags)
1488 FIXME("Unsupported flags: %04x\n", fFlags);
1491 /*************************************************************************
1492 * SHFileOperationW [SHELL32.@]
1494 * See SHFileOperationA
1496 int WINAPI SHFileOperationW(LPSHFILEOPSTRUCTW lpFileOp)
1498 FILE_OPERATION op;
1499 FILE_LIST flFrom, flTo;
1500 int ret = 0;
1502 if (!lpFileOp)
1503 return ERROR_INVALID_PARAMETER;
1505 check_flags(lpFileOp->fFlags);
1507 ZeroMemory(&flFrom, sizeof(FILE_LIST));
1508 ZeroMemory(&flTo, sizeof(FILE_LIST));
1510 if ((ret = parse_file_list(&flFrom, lpFileOp->pFrom)))
1511 return ret;
1513 if (lpFileOp->wFunc != FO_DELETE)
1514 parse_file_list(&flTo, lpFileOp->pTo);
1516 ZeroMemory(&op, sizeof(op));
1517 op.req = lpFileOp;
1518 op.bManyItems = (flFrom.dwNumFiles > 1);
1520 switch (lpFileOp->wFunc)
1522 case FO_COPY:
1523 ret = copy_files(&op, &flFrom, &flTo);
1524 break;
1525 case FO_DELETE:
1526 ret = delete_files(lpFileOp, &flFrom);
1527 break;
1528 case FO_MOVE:
1529 ret = move_files(lpFileOp, &flFrom, &flTo);
1530 break;
1531 case FO_RENAME:
1532 ret = rename_files(lpFileOp, &flFrom, &flTo);
1533 break;
1534 default:
1535 ret = ERROR_INVALID_PARAMETER;
1536 break;
1539 destroy_file_list(&flFrom);
1541 if (lpFileOp->wFunc != FO_DELETE)
1542 destroy_file_list(&flTo);
1544 if (ret == ERROR_CANCELLED)
1545 lpFileOp->fAnyOperationsAborted = TRUE;
1547 return ret;
1550 #define SHDSA_GetItemCount(hdsa) (*(int*)(hdsa))
1552 /*************************************************************************
1553 * SHFreeNameMappings [shell32.246]
1555 * Free the mapping handle returned by SHFileOperation if FOF_WANTSMAPPINGHANDLE
1556 * was specified.
1558 * PARAMS
1559 * hNameMapping [I] handle to the name mappings used during renaming of files
1561 * RETURNS
1562 * Nothing
1564 void WINAPI SHFreeNameMappings(HANDLE hNameMapping)
1566 if (hNameMapping)
1568 int i = SHDSA_GetItemCount((HDSA)hNameMapping) - 1;
1570 for (; i>= 0; i--)
1572 LPSHNAMEMAPPINGW lp = DSA_GetItemPtr((HDSA)hNameMapping, i);
1574 SHFree(lp->pszOldPath);
1575 SHFree(lp->pszNewPath);
1577 DSA_Destroy((HDSA)hNameMapping);
1581 /*************************************************************************
1582 * SheGetDirA [SHELL32.@]
1584 * drive = 0: returns the current directory path
1585 * drive > 0: returns the current directory path of the specified drive
1586 * drive=1 -> A: drive=2 -> B: ...
1587 * returns 0 if successful
1589 DWORD WINAPI SheGetDirA(DWORD drive, LPSTR buffer)
1591 WCHAR org_path[MAX_PATH];
1592 DWORD ret;
1593 char drv_path[3];
1595 /* change current directory to the specified drive */
1596 if (drive) {
1597 strcpy(drv_path, "A:");
1598 drv_path[0] += (char)drive-1;
1600 GetCurrentDirectoryW(MAX_PATH, org_path);
1602 SetCurrentDirectoryA(drv_path);
1605 /* query current directory path of the specified drive */
1606 ret = GetCurrentDirectoryA(MAX_PATH, buffer);
1608 /* back to the original drive */
1609 if (drive)
1610 SetCurrentDirectoryW(org_path);
1612 if (!ret)
1613 return GetLastError();
1615 return 0;
1618 /*************************************************************************
1619 * SheGetDirW [SHELL32.@]
1621 * drive = 0: returns the current directory path
1622 * drive > 0: returns the current directory path of the specified drive
1623 * drive=1 -> A: drive=2 -> B: ...
1624 * returns 0 if successful
1626 DWORD WINAPI SheGetDirW(DWORD drive, LPWSTR buffer)
1628 WCHAR org_path[MAX_PATH];
1629 DWORD ret;
1630 char drv_path[3];
1632 /* change current directory to the specified drive */
1633 if (drive) {
1634 strcpy(drv_path, "A:");
1635 drv_path[0] += (char)drive-1;
1637 GetCurrentDirectoryW(MAX_PATH, org_path);
1639 SetCurrentDirectoryA(drv_path);
1642 /* query current directory path of the specified drive */
1643 ret = GetCurrentDirectoryW(MAX_PATH, buffer);
1645 /* back to the original drive */
1646 if (drive)
1647 SetCurrentDirectoryW(org_path);
1649 if (!ret)
1650 return GetLastError();
1652 return 0;
1655 /*************************************************************************
1656 * SheChangeDirA [SHELL32.@]
1658 * changes the current directory to the specified path
1659 * and returns 0 if successful
1661 DWORD WINAPI SheChangeDirA(LPSTR path)
1663 if (SetCurrentDirectoryA(path))
1664 return 0;
1665 else
1666 return GetLastError();
1669 /*************************************************************************
1670 * SheChangeDirW [SHELL32.@]
1672 * changes the current directory to the specified path
1673 * and returns 0 if successful
1675 DWORD WINAPI SheChangeDirW(LPWSTR path)
1677 if (SetCurrentDirectoryW(path))
1678 return 0;
1679 else
1680 return GetLastError();
1683 /*************************************************************************
1684 * IsNetDrive [SHELL32.66]
1686 BOOL WINAPI IsNetDrive(DWORD drive)
1688 char root[4];
1689 strcpy(root, "A:\\");
1690 root[0] += (char)drive;
1691 return (GetDriveTypeA(root) == DRIVE_REMOTE);
1695 /*************************************************************************
1696 * RealDriveType [SHELL32.524]
1698 INT WINAPI RealDriveType(INT drive, BOOL bQueryNet)
1700 char root[] = "A:\\";
1701 root[0] += (char)drive;
1702 return GetDriveTypeA(root);
1705 /***********************************************************************
1706 * SHPathPrepareForWriteA (SHELL32.@)
1708 HRESULT WINAPI SHPathPrepareForWriteA(HWND hwnd, IUnknown *modless, LPCSTR path, DWORD flags)
1710 WCHAR wpath[MAX_PATH];
1711 MultiByteToWideChar( CP_ACP, 0, path, -1, wpath, MAX_PATH);
1712 return SHPathPrepareForWriteW(hwnd, modless, wpath, flags);
1715 /***********************************************************************
1716 * SHPathPrepareForWriteW (SHELL32.@)
1718 HRESULT WINAPI SHPathPrepareForWriteW(HWND hwnd, IUnknown *modless, LPCWSTR path, DWORD flags)
1720 DWORD res;
1721 DWORD err;
1722 LPCWSTR realpath;
1723 int len;
1724 WCHAR* last_slash;
1725 WCHAR* temppath=NULL;
1727 TRACE("%p %p %s 0x%80x\n", hwnd, modless, debugstr_w(path), flags);
1729 if (flags & ~(SHPPFW_DIRCREATE|SHPPFW_ASKDIRCREATE|SHPPFW_IGNOREFILENAME))
1730 FIXME("unimplemented flags 0x%08x\n", flags);
1732 /* cut off filename if necessary */
1733 if (flags & SHPPFW_IGNOREFILENAME)
1735 last_slash = StrRChrW(path, NULL, '\\');
1736 if (last_slash == NULL)
1737 len = 1;
1738 else
1739 len = last_slash - path + 1;
1740 temppath = HeapAlloc(GetProcessHeap(), 0, len * sizeof(WCHAR));
1741 if (!temppath)
1742 return E_OUTOFMEMORY;
1743 StrCpyNW(temppath, path, len);
1744 realpath = temppath;
1746 else
1748 realpath = path;
1751 /* try to create the directory if asked to */
1752 if (flags & (SHPPFW_DIRCREATE|SHPPFW_ASKDIRCREATE))
1754 if (flags & SHPPFW_ASKDIRCREATE)
1755 FIXME("treating SHPPFW_ASKDIRCREATE as SHPPFW_DIRCREATE\n");
1757 SHCreateDirectoryExW(0, realpath, NULL);
1760 /* check if we can access the directory */
1761 res = GetFileAttributesW(realpath);
1763 HeapFree(GetProcessHeap(), 0, temppath);
1765 if (res == INVALID_FILE_ATTRIBUTES)
1767 err = GetLastError();
1768 if (err == ERROR_FILE_NOT_FOUND)
1769 return HRESULT_FROM_WIN32(ERROR_PATH_NOT_FOUND);
1770 return HRESULT_FROM_WIN32(err);
1772 else if (res & FILE_ATTRIBUTE_DIRECTORY)
1773 return S_OK;
1774 else
1775 return HRESULT_FROM_WIN32(ERROR_DIRECTORY);