shell32: Draw text on message boxes without background.
[wine.git] / dlls / shell32 / shlfileop.c
blob8d4160d90c59421fe2a4eb7e49a4c0fcb7a9b98a
1 /*
2 * SHFileOperation
4 * Copyright 2000 Juergen Schmied
5 * Copyright 2002 Andriy Palamarchuk
6 * Copyright 2004 Dietrich Teickner (from Odin)
7 * Copyright 2004 Rolf Kalbermatter
9 * This library is free software; you can redistribute it and/or
10 * modify it under the terms of the GNU Lesser General Public
11 * License as published by the Free Software Foundation; either
12 * version 2.1 of the License, or (at your option) any later version.
14 * This library is distributed in the hope that it will be useful,
15 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
17 * Lesser General Public License for more details.
19 * You should have received a copy of the GNU Lesser General Public
20 * License along with this library; if not, write to the Free Software
21 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
24 #include "config.h"
25 #include "wine/port.h"
27 #include <stdarg.h>
28 #include <string.h>
29 #include <ctype.h>
30 #include <assert.h>
32 #include "windef.h"
33 #include "winbase.h"
34 #include "winreg.h"
35 #include "shellapi.h"
36 #include "wingdi.h"
37 #include "winuser.h"
38 #include "shlobj.h"
39 #include "shresdef.h"
40 #define NO_SHLWAPI_STREAM
41 #include "shlwapi.h"
42 #include "shell32_main.h"
43 #include "undocshell.h"
44 #include "wine/debug.h"
45 #include "xdg.h"
47 WINE_DEFAULT_DEBUG_CHANNEL(shell);
49 #define IsAttrib(x, y) ((INVALID_FILE_ATTRIBUTES != (x)) && ((x) & (y)))
50 #define IsAttribFile(x) (!((x) & FILE_ATTRIBUTE_DIRECTORY))
51 #define IsAttribDir(x) IsAttrib(x, FILE_ATTRIBUTE_DIRECTORY)
52 #define IsDotDir(x) ((x[0] == '.') && ((x[1] == 0) || ((x[1] == '.') && (x[2] == 0))))
54 #define FO_MASK 0xF
56 #define DE_SAMEFILE 0x71
57 #define DE_DESTSAMETREE 0x7D
59 static const WCHAR wWildcardFile[] = {'*',0};
60 static const WCHAR wWildcardChars[] = {'*','?',0};
62 static DWORD SHNotifyCreateDirectoryA(LPCSTR path, LPSECURITY_ATTRIBUTES sec);
63 static DWORD SHNotifyCreateDirectoryW(LPCWSTR path, LPSECURITY_ATTRIBUTES sec);
64 static DWORD SHNotifyRemoveDirectoryA(LPCSTR path);
65 static DWORD SHNotifyRemoveDirectoryW(LPCWSTR path);
66 static DWORD SHNotifyDeleteFileA(LPCSTR path);
67 static DWORD SHNotifyDeleteFileW(LPCWSTR path);
68 static DWORD SHNotifyMoveFileW(LPCWSTR src, LPCWSTR dest);
69 static DWORD SHNotifyCopyFileW(LPCWSTR src, LPCWSTR dest, BOOL bFailIfExists);
70 static DWORD SHFindAttrW(LPCWSTR pName, BOOL fileOnly);
72 typedef struct
74 SHFILEOPSTRUCTW *req;
75 DWORD dwYesToAllMask;
76 BOOL bManyItems;
77 BOOL bCancelled;
78 } FILE_OPERATION;
80 /* Confirm dialogs with an optional "Yes To All" as used in file operations confirmations
82 static const WCHAR CONFIRM_MSG_PROP[] = {'W','I','N','E','_','C','O','N','F','I','R','M',0};
84 struct confirm_msg_info
86 LPWSTR lpszText;
87 LPWSTR lpszCaption;
88 HICON hIcon;
89 BOOL bYesToAll;
92 /* as some buttons may be hidden and the dialog height may change we may need
93 * to move the controls */
94 static void confirm_msg_move_button(HWND hDlg, INT iId, INT *xPos, INT yOffset, BOOL bShow)
96 HWND hButton = GetDlgItem(hDlg, iId);
97 RECT r;
99 if (bShow) {
100 int width;
102 GetWindowRect(hButton, &r);
103 MapWindowPoints( 0, hDlg, (POINT *)&r, 2 );
104 width = r.right - r.left;
105 SetWindowPos(hButton, 0, *xPos - width, r.top - yOffset, 0, 0,
106 SWP_NOSIZE | SWP_NOZORDER | SWP_NOACTIVATE | SWP_NOREDRAW );
107 *xPos -= width + 5;
109 else
110 ShowWindow(hButton, SW_HIDE);
113 /* Note: we paint the text manually and don't use the static control to make
114 * sure the text has the same height as the one computed in WM_INITDIALOG
116 static INT_PTR ConfirmMsgBox_Paint(HWND hDlg)
118 PAINTSTRUCT ps;
119 HFONT hOldFont;
120 RECT r;
121 HDC hdc;
123 BeginPaint(hDlg, &ps);
124 hdc = ps.hdc;
125 SetBkMode(hdc, TRANSPARENT);
127 GetClientRect(GetDlgItem(hDlg, IDD_MESSAGE), &r);
128 /* this will remap the rect to dialog coords */
129 MapWindowPoints(GetDlgItem(hDlg, IDD_MESSAGE), hDlg, (LPPOINT)&r, 2);
130 hOldFont = SelectObject(hdc, (HFONT)SendDlgItemMessageW(hDlg, IDD_MESSAGE, WM_GETFONT, 0, 0));
131 DrawTextW(hdc, GetPropW(hDlg, CONFIRM_MSG_PROP), -1, &r, DT_NOPREFIX | DT_PATH_ELLIPSIS | DT_WORDBREAK);
132 SelectObject(hdc, hOldFont);
133 EndPaint(hDlg, &ps);
134 return TRUE;
137 static INT_PTR ConfirmMsgBox_Init(HWND hDlg, LPARAM lParam)
139 struct confirm_msg_info *info = (struct confirm_msg_info *)lParam;
140 INT xPos, yOffset;
141 int width, height;
142 HFONT hOldFont;
143 HDC hdc;
144 RECT r;
146 SetWindowTextW(hDlg, info->lpszCaption);
147 ShowWindow(GetDlgItem(hDlg, IDD_MESSAGE), SW_HIDE);
148 SetPropW(hDlg, CONFIRM_MSG_PROP, info->lpszText);
149 SendDlgItemMessageW(hDlg, IDD_ICON, STM_SETICON, (WPARAM)info->hIcon, 0);
151 /* compute the text height and resize the dialog */
152 GetClientRect(GetDlgItem(hDlg, IDD_MESSAGE), &r);
153 hdc = GetDC(hDlg);
154 yOffset = r.bottom;
155 hOldFont = SelectObject(hdc, (HFONT)SendDlgItemMessageW(hDlg, IDD_MESSAGE, WM_GETFONT, 0, 0));
156 DrawTextW(hdc, info->lpszText, -1, &r, DT_NOPREFIX | DT_PATH_ELLIPSIS | DT_WORDBREAK | DT_CALCRECT);
157 SelectObject(hdc, hOldFont);
158 yOffset -= r.bottom;
159 yOffset = min(yOffset, 35); /* don't make the dialog too small */
160 ReleaseDC(hDlg, hdc);
162 GetClientRect(hDlg, &r);
163 xPos = r.right - 7;
164 GetWindowRect(hDlg, &r);
165 width = r.right - r.left;
166 height = r.bottom - r.top - yOffset;
167 MoveWindow(hDlg, (GetSystemMetrics(SM_CXSCREEN) - width)/2,
168 (GetSystemMetrics(SM_CYSCREEN) - height)/2, width, height, FALSE);
170 confirm_msg_move_button(hDlg, IDCANCEL, &xPos, yOffset, info->bYesToAll);
171 confirm_msg_move_button(hDlg, IDNO, &xPos, yOffset, TRUE);
172 confirm_msg_move_button(hDlg, IDD_YESTOALL, &xPos, yOffset, info->bYesToAll);
173 confirm_msg_move_button(hDlg, IDYES, &xPos, yOffset, TRUE);
174 return TRUE;
177 static INT_PTR CALLBACK ConfirmMsgBoxProc(HWND hDlg, UINT uMsg, WPARAM wParam, LPARAM lParam)
179 switch (uMsg)
181 case WM_INITDIALOG:
182 return ConfirmMsgBox_Init(hDlg, lParam);
183 case WM_PAINT:
184 return ConfirmMsgBox_Paint(hDlg);
185 case WM_COMMAND:
186 EndDialog(hDlg, wParam);
187 break;
188 case WM_CLOSE:
189 EndDialog(hDlg, IDCANCEL);
190 break;
192 return FALSE;
195 static int SHELL_ConfirmMsgBox(HWND hWnd, LPWSTR lpszText, LPWSTR lpszCaption, HICON hIcon, BOOL bYesToAll)
197 static const WCHAR wszTemplate[] = {'S','H','E','L','L','_','Y','E','S','T','O','A','L','L','_','M','S','G','B','O','X',0};
198 struct confirm_msg_info info;
200 info.lpszText = lpszText;
201 info.lpszCaption = lpszCaption;
202 info.hIcon = hIcon;
203 info.bYesToAll = bYesToAll;
204 return DialogBoxParamW(shell32_hInstance, wszTemplate, hWnd, ConfirmMsgBoxProc, (LPARAM)&info);
207 /* confirmation dialogs content */
208 typedef struct
210 HINSTANCE hIconInstance;
211 UINT icon_resource_id;
212 UINT caption_resource_id, text_resource_id;
213 } SHELL_ConfirmIDstruc;
215 static BOOL SHELL_ConfirmIDs(int nKindOfDialog, SHELL_ConfirmIDstruc *ids)
217 ids->hIconInstance = shell32_hInstance;
218 switch (nKindOfDialog) {
219 case ASK_DELETE_FILE:
220 ids->icon_resource_id = IDI_SHELL_CONFIRM_DELETE;
221 ids->caption_resource_id = IDS_DELETEITEM_CAPTION;
222 ids->text_resource_id = IDS_DELETEITEM_TEXT;
223 return TRUE;
224 case ASK_DELETE_FOLDER:
225 ids->icon_resource_id = IDI_SHELL_CONFIRM_DELETE;
226 ids->caption_resource_id = IDS_DELETEFOLDER_CAPTION;
227 ids->text_resource_id = IDS_DELETEITEM_TEXT;
228 return TRUE;
229 case ASK_DELETE_MULTIPLE_ITEM:
230 ids->icon_resource_id = IDI_SHELL_CONFIRM_DELETE;
231 ids->caption_resource_id = IDS_DELETEITEM_CAPTION;
232 ids->text_resource_id = IDS_DELETEMULTIPLE_TEXT;
233 return TRUE;
234 case ASK_TRASH_FILE:
235 ids->icon_resource_id = IDI_SHELL_TRASH_FILE;
236 ids->caption_resource_id = IDS_DELETEITEM_CAPTION;
237 ids->text_resource_id = IDS_TRASHITEM_TEXT;
238 return TRUE;
239 case ASK_TRASH_FOLDER:
240 ids->icon_resource_id = IDI_SHELL_TRASH_FILE;
241 ids->caption_resource_id = IDS_DELETEFOLDER_CAPTION;
242 ids->text_resource_id = IDS_TRASHFOLDER_TEXT;
243 return TRUE;
244 case ASK_TRASH_MULTIPLE_ITEM:
245 ids->icon_resource_id = IDI_SHELL_TRASH_FILE;
246 ids->caption_resource_id = IDS_DELETEITEM_CAPTION;
247 ids->text_resource_id = IDS_TRASHMULTIPLE_TEXT;
248 return TRUE;
249 case ASK_CANT_TRASH_ITEM:
250 ids->icon_resource_id = IDI_SHELL_CONFIRM_DELETE;
251 ids->caption_resource_id = IDS_DELETEITEM_CAPTION;
252 ids->text_resource_id = IDS_CANTTRASH_TEXT;
253 return TRUE;
254 case ASK_DELETE_SELECTED:
255 ids->icon_resource_id = IDI_SHELL_CONFIRM_DELETE;
256 ids->caption_resource_id = IDS_DELETEITEM_CAPTION;
257 ids->text_resource_id = IDS_DELETESELECTED_TEXT;
258 return TRUE;
259 case ASK_OVERWRITE_FILE:
260 ids->hIconInstance = NULL;
261 ids->icon_resource_id = IDI_WARNING;
262 ids->caption_resource_id = IDS_OVERWRITEFILE_CAPTION;
263 ids->text_resource_id = IDS_OVERWRITEFILE_TEXT;
264 return TRUE;
265 case ASK_OVERWRITE_FOLDER:
266 ids->hIconInstance = NULL;
267 ids->icon_resource_id = IDI_WARNING;
268 ids->caption_resource_id = IDS_OVERWRITEFILE_CAPTION;
269 ids->text_resource_id = IDS_OVERWRITEFOLDER_TEXT;
270 return TRUE;
271 default:
272 FIXME(" Unhandled nKindOfDialog %d stub\n", nKindOfDialog);
274 return FALSE;
277 static BOOL SHELL_ConfirmDialogW(HWND hWnd, int nKindOfDialog, LPCWSTR szDir, FILE_OPERATION *op)
279 WCHAR szCaption[255], szText[255], szBuffer[MAX_PATH + 256];
280 SHELL_ConfirmIDstruc ids;
281 DWORD_PTR args[1];
282 HICON hIcon;
283 int ret;
285 assert(nKindOfDialog >= 0 && nKindOfDialog < 32);
286 if (op && (op->dwYesToAllMask & (1 << nKindOfDialog)))
287 return TRUE;
289 if (!SHELL_ConfirmIDs(nKindOfDialog, &ids)) return FALSE;
291 LoadStringW(shell32_hInstance, ids.caption_resource_id, szCaption, sizeof(szCaption)/sizeof(WCHAR));
292 LoadStringW(shell32_hInstance, ids.text_resource_id, szText, sizeof(szText)/sizeof(WCHAR));
294 args[0] = (DWORD_PTR)szDir;
295 FormatMessageW(FORMAT_MESSAGE_FROM_STRING|FORMAT_MESSAGE_ARGUMENT_ARRAY,
296 szText, 0, 0, szBuffer, sizeof(szBuffer)/sizeof(szBuffer[0]), (__ms_va_list*)args);
297 hIcon = LoadIconW(ids.hIconInstance, (LPWSTR)MAKEINTRESOURCE(ids.icon_resource_id));
299 ret = SHELL_ConfirmMsgBox(hWnd, szBuffer, szCaption, hIcon, op && op->bManyItems);
300 if (op) {
301 if (ret == IDD_YESTOALL) {
302 op->dwYesToAllMask |= (1 << nKindOfDialog);
303 ret = IDYES;
305 if (ret == IDCANCEL)
306 op->bCancelled = TRUE;
307 if (ret != IDYES)
308 op->req->fAnyOperationsAborted = TRUE;
310 return ret == IDYES;
313 BOOL SHELL_ConfirmYesNoW(HWND hWnd, int nKindOfDialog, LPCWSTR szDir)
315 return SHELL_ConfirmDialogW(hWnd, nKindOfDialog, szDir, NULL);
318 static DWORD SHELL32_AnsiToUnicodeBuf(LPCSTR aPath, LPWSTR *wPath, DWORD minChars)
320 DWORD len = MultiByteToWideChar(CP_ACP, 0, aPath, -1, NULL, 0);
322 if (len < minChars)
323 len = minChars;
325 *wPath = HeapAlloc(GetProcessHeap(), 0, len * sizeof(WCHAR));
326 if (*wPath)
328 MultiByteToWideChar(CP_ACP, 0, aPath, -1, *wPath, len);
329 return NO_ERROR;
331 return E_OUTOFMEMORY;
334 static void SHELL32_FreeUnicodeBuf(LPWSTR wPath)
336 HeapFree(GetProcessHeap(), 0, wPath);
339 HRESULT WINAPI SHIsFileAvailableOffline(LPCWSTR path, LPDWORD status)
341 FIXME("(%s, %p) stub\n", debugstr_w(path), status);
342 return E_FAIL;
345 /**************************************************************************
346 * SHELL_DeleteDirectory() [internal]
348 * Asks for confirmation when bShowUI is true and deletes the directory and
349 * all its subdirectories and files if necessary.
351 static DWORD SHELL_DeleteDirectoryW(HWND hwnd, LPCWSTR pszDir, BOOL bShowUI)
353 DWORD ret = 0;
354 HANDLE hFind;
355 WIN32_FIND_DATAW wfd;
356 WCHAR szTemp[MAX_PATH];
358 PathCombineW(szTemp, pszDir, wWildcardFile);
359 hFind = FindFirstFileW(szTemp, &wfd);
361 if (hFind != INVALID_HANDLE_VALUE) {
362 if (!bShowUI || SHELL_ConfirmDialogW(hwnd, ASK_DELETE_FOLDER, pszDir, NULL)) {
363 do {
364 if (IsDotDir(wfd.cFileName))
365 continue;
366 PathCombineW(szTemp, pszDir, wfd.cFileName);
367 if (FILE_ATTRIBUTE_DIRECTORY & wfd.dwFileAttributes)
368 ret = SHELL_DeleteDirectoryW(hwnd, szTemp, FALSE);
369 else
370 ret = SHNotifyDeleteFileW(szTemp);
371 } while (!ret && FindNextFileW(hFind, &wfd));
373 FindClose(hFind);
375 if (ret == ERROR_SUCCESS)
376 ret = SHNotifyRemoveDirectoryW(pszDir);
378 return ret == ERROR_PATH_NOT_FOUND ?
379 0x7C: /* DE_INVALIDFILES (legacy Windows error) */
380 ret;
383 /**************************************************************************
384 * Win32CreateDirectory [SHELL32.93]
386 * Creates a directory. Also triggers a change notify if one exists.
388 * PARAMS
389 * path [I] path to directory to create
391 * RETURNS
392 * TRUE if successful, FALSE otherwise
394 * NOTES
395 * Verified on Win98 / IE 5 (SHELL32 4.72, March 1999 build) to be ANSI.
396 * This is Unicode on NT/2000
398 static DWORD SHNotifyCreateDirectoryA(LPCSTR path, LPSECURITY_ATTRIBUTES sec)
400 LPWSTR wPath;
401 DWORD retCode;
403 TRACE("(%s, %p)\n", debugstr_a(path), sec);
405 retCode = SHELL32_AnsiToUnicodeBuf(path, &wPath, 0);
406 if (!retCode)
408 retCode = SHNotifyCreateDirectoryW(wPath, sec);
409 SHELL32_FreeUnicodeBuf(wPath);
411 return retCode;
414 /**********************************************************************/
416 static DWORD SHNotifyCreateDirectoryW(LPCWSTR path, LPSECURITY_ATTRIBUTES sec)
418 TRACE("(%s, %p)\n", debugstr_w(path), sec);
420 if (CreateDirectoryW(path, sec))
422 SHChangeNotify(SHCNE_MKDIR, SHCNF_PATHW, path, NULL);
423 return ERROR_SUCCESS;
425 return GetLastError();
428 /**********************************************************************/
430 BOOL WINAPI Win32CreateDirectoryAW(LPCVOID path, LPSECURITY_ATTRIBUTES sec)
432 if (SHELL_OsIsUnicode())
433 return (SHNotifyCreateDirectoryW(path, sec) == ERROR_SUCCESS);
434 return (SHNotifyCreateDirectoryA(path, sec) == ERROR_SUCCESS);
437 /************************************************************************
438 * Win32RemoveDirectory [SHELL32.94]
440 * Deletes a directory. Also triggers a change notify if one exists.
442 * PARAMS
443 * path [I] path to directory to delete
445 * RETURNS
446 * TRUE if successful, FALSE otherwise
448 * NOTES
449 * Verified on Win98 / IE 5 (SHELL32 4.72, March 1999 build) to be ANSI.
450 * This is Unicode on NT/2000
452 static DWORD SHNotifyRemoveDirectoryA(LPCSTR path)
454 LPWSTR wPath;
455 DWORD retCode;
457 TRACE("(%s)\n", debugstr_a(path));
459 retCode = SHELL32_AnsiToUnicodeBuf(path, &wPath, 0);
460 if (!retCode)
462 retCode = SHNotifyRemoveDirectoryW(wPath);
463 SHELL32_FreeUnicodeBuf(wPath);
465 return retCode;
468 /***********************************************************************/
470 static DWORD SHNotifyRemoveDirectoryW(LPCWSTR path)
472 BOOL ret;
473 TRACE("(%s)\n", debugstr_w(path));
475 ret = RemoveDirectoryW(path);
476 if (!ret)
478 /* Directory may be write protected */
479 DWORD dwAttr = GetFileAttributesW(path);
480 if (IsAttrib(dwAttr, FILE_ATTRIBUTE_READONLY))
481 if (SetFileAttributesW(path, dwAttr & ~FILE_ATTRIBUTE_READONLY))
482 ret = RemoveDirectoryW(path);
484 if (ret)
486 SHChangeNotify(SHCNE_RMDIR, SHCNF_PATHW, path, NULL);
487 return ERROR_SUCCESS;
489 return GetLastError();
492 /***********************************************************************/
494 BOOL WINAPI Win32RemoveDirectoryAW(LPCVOID path)
496 if (SHELL_OsIsUnicode())
497 return (SHNotifyRemoveDirectoryW(path) == ERROR_SUCCESS);
498 return (SHNotifyRemoveDirectoryA(path) == ERROR_SUCCESS);
501 /************************************************************************
502 * Win32DeleteFile [SHELL32.164]
504 * Deletes a file. Also triggers a change notify if one exists.
506 * PARAMS
507 * path [I] path to file to delete
509 * RETURNS
510 * TRUE if successful, FALSE otherwise
512 * NOTES
513 * Verified on Win98 / IE 5 (SHELL32 4.72, March 1999 build) to be ANSI.
514 * This is Unicode on NT/2000
516 static DWORD SHNotifyDeleteFileA(LPCSTR path)
518 LPWSTR wPath;
519 DWORD retCode;
521 TRACE("(%s)\n", debugstr_a(path));
523 retCode = SHELL32_AnsiToUnicodeBuf(path, &wPath, 0);
524 if (!retCode)
526 retCode = SHNotifyDeleteFileW(wPath);
527 SHELL32_FreeUnicodeBuf(wPath);
529 return retCode;
532 /***********************************************************************/
534 static DWORD SHNotifyDeleteFileW(LPCWSTR path)
536 BOOL ret;
538 TRACE("(%s)\n", debugstr_w(path));
540 ret = DeleteFileW(path);
541 if (!ret)
543 /* File may be write protected or a system file */
544 DWORD dwAttr = GetFileAttributesW(path);
545 if (IsAttrib(dwAttr, FILE_ATTRIBUTE_READONLY | FILE_ATTRIBUTE_SYSTEM))
546 if (SetFileAttributesW(path, dwAttr & ~(FILE_ATTRIBUTE_READONLY | FILE_ATTRIBUTE_SYSTEM)))
547 ret = DeleteFileW(path);
549 if (ret)
551 SHChangeNotify(SHCNE_DELETE, SHCNF_PATHW, path, NULL);
552 return ERROR_SUCCESS;
554 return GetLastError();
557 /***********************************************************************/
559 DWORD WINAPI Win32DeleteFileAW(LPCVOID path)
561 if (SHELL_OsIsUnicode())
562 return (SHNotifyDeleteFileW(path) == ERROR_SUCCESS);
563 return (SHNotifyDeleteFileA(path) == ERROR_SUCCESS);
566 /************************************************************************
567 * SHNotifyMoveFile [internal]
569 * Moves a file. Also triggers a change notify if one exists.
571 * PARAMS
572 * src [I] path to source file to move
573 * dest [I] path to target file to move to
575 * RETURNS
576 * ERROR_SUCCESS if successful
578 static DWORD SHNotifyMoveFileW(LPCWSTR src, LPCWSTR dest)
580 BOOL ret;
582 TRACE("(%s %s)\n", debugstr_w(src), debugstr_w(dest));
584 ret = MoveFileExW(src, dest, MOVEFILE_REPLACE_EXISTING);
586 /* MOVEFILE_REPLACE_EXISTING fails with dirs, so try MoveFile */
587 if (!ret)
588 ret = MoveFileW(src, dest);
590 if (!ret)
592 DWORD dwAttr;
594 dwAttr = SHFindAttrW(dest, FALSE);
595 if (INVALID_FILE_ATTRIBUTES == dwAttr)
597 /* Source file may be write protected or a system file */
598 dwAttr = GetFileAttributesW(src);
599 if (IsAttrib(dwAttr, FILE_ATTRIBUTE_READONLY | FILE_ATTRIBUTE_SYSTEM))
600 if (SetFileAttributesW(src, dwAttr & ~(FILE_ATTRIBUTE_READONLY | FILE_ATTRIBUTE_SYSTEM)))
601 ret = MoveFileW(src, dest);
604 if (ret)
606 SHChangeNotify(SHCNE_RENAMEITEM, SHCNF_PATHW, src, dest);
607 return ERROR_SUCCESS;
609 return GetLastError();
612 /************************************************************************
613 * SHNotifyCopyFile [internal]
615 * Copies a file. Also triggers a change notify if one exists.
617 * PARAMS
618 * src [I] path to source file to move
619 * dest [I] path to target file to move to
620 * bFailIfExists [I] if TRUE, the target file will not be overwritten if
621 * a file with this name already exists
623 * RETURNS
624 * ERROR_SUCCESS if successful
626 static DWORD SHNotifyCopyFileW(LPCWSTR src, LPCWSTR dest, BOOL bFailIfExists)
628 BOOL ret;
629 DWORD attribs;
631 TRACE("(%s %s %s)\n", debugstr_w(src), debugstr_w(dest), bFailIfExists ? "failIfExists" : "");
633 /* Destination file may already exist with read only attribute */
634 attribs = GetFileAttributesW(dest);
635 if (IsAttrib(attribs, FILE_ATTRIBUTE_READONLY))
636 SetFileAttributesW(dest, attribs & ~FILE_ATTRIBUTE_READONLY);
638 ret = CopyFileW(src, dest, bFailIfExists);
639 if (ret)
641 SHChangeNotify(SHCNE_CREATE, SHCNF_PATHW, dest, NULL);
642 return ERROR_SUCCESS;
645 return GetLastError();
648 /*************************************************************************
649 * SHCreateDirectory [SHELL32.165]
651 * This function creates a file system folder whose fully qualified path is
652 * given by path. If one or more of the intermediate folders do not exist,
653 * they will be created as well.
655 * PARAMS
656 * hWnd [I]
657 * path [I] path of directory to create
659 * RETURNS
660 * ERROR_SUCCESS or one of the following values:
661 * ERROR_BAD_PATHNAME if the path is relative
662 * ERROR_FILE_EXISTS when a file with that name exists
663 * ERROR_PATH_NOT_FOUND can't find the path, probably invalid
664 * ERROR_INVALID_NAME if the path contains invalid chars
665 * ERROR_ALREADY_EXISTS when the directory already exists
666 * ERROR_FILENAME_EXCED_RANGE if the filename was too long to process
668 * NOTES
669 * exported by ordinal
670 * Win9x exports ANSI
671 * WinNT/2000 exports Unicode
673 DWORD WINAPI SHCreateDirectory(HWND hWnd, LPCVOID path)
675 if (SHELL_OsIsUnicode())
676 return SHCreateDirectoryExW(hWnd, path, NULL);
677 return SHCreateDirectoryExA(hWnd, path, NULL);
680 /*************************************************************************
681 * SHCreateDirectoryExA [SHELL32.@]
683 * This function creates a file system folder whose fully qualified path is
684 * given by path. If one or more of the intermediate folders do not exist,
685 * they will be created as well.
687 * PARAMS
688 * hWnd [I]
689 * path [I] path of directory to create
690 * sec [I] security attributes to use or NULL
692 * RETURNS
693 * ERROR_SUCCESS or one of the following values:
694 * ERROR_BAD_PATHNAME or ERROR_PATH_NOT_FOUND if the path is relative
695 * ERROR_INVALID_NAME if the path contains invalid chars
696 * ERROR_FILE_EXISTS when a file with that name exists
697 * ERROR_ALREADY_EXISTS when the directory already exists
698 * ERROR_FILENAME_EXCED_RANGE if the filename was too long to process
700 * FIXME: Not implemented yet;
701 * SHCreateDirectoryEx also verifies that the files in the directory will be visible
702 * if the path is a network path to deal with network drivers which might have a limited
703 * but unknown maximum path length. If not:
705 * If hWnd is set to a valid window handle, a message box is displayed warning
706 * the user that the files may not be accessible. If the user chooses not to
707 * proceed, the function returns ERROR_CANCELLED.
709 * If hWnd is set to NULL, no user interface is displayed and the function
710 * returns ERROR_CANCELLED.
712 int WINAPI SHCreateDirectoryExA(HWND hWnd, LPCSTR path, LPSECURITY_ATTRIBUTES sec)
714 LPWSTR wPath;
715 DWORD retCode;
717 TRACE("(%s, %p)\n", debugstr_a(path), sec);
719 retCode = SHELL32_AnsiToUnicodeBuf(path, &wPath, 0);
720 if (!retCode)
722 retCode = SHCreateDirectoryExW(hWnd, wPath, sec);
723 SHELL32_FreeUnicodeBuf(wPath);
725 return retCode;
728 /*************************************************************************
729 * SHCreateDirectoryExW [SHELL32.@]
731 * See SHCreateDirectoryExA.
733 int WINAPI SHCreateDirectoryExW(HWND hWnd, LPCWSTR path, LPSECURITY_ATTRIBUTES sec)
735 int ret = ERROR_BAD_PATHNAME;
736 TRACE("(%p, %s, %p)\n", hWnd, debugstr_w(path), sec);
738 if (PathIsRelativeW(path))
740 SetLastError(ret);
742 else
744 ret = SHNotifyCreateDirectoryW(path, sec);
745 /* Refuse to work on certain error codes before trying to create directories recursively */
746 if (ret != ERROR_SUCCESS &&
747 ret != ERROR_FILE_EXISTS &&
748 ret != ERROR_ALREADY_EXISTS &&
749 ret != ERROR_FILENAME_EXCED_RANGE)
751 WCHAR *pEnd, *pSlash, szTemp[MAX_PATH + 1]; /* extra for PathAddBackslash() */
753 lstrcpynW(szTemp, path, MAX_PATH);
754 pEnd = PathAddBackslashW(szTemp);
755 pSlash = szTemp + 3;
757 while (*pSlash)
759 while (*pSlash && *pSlash != '\\') pSlash++;
760 if (*pSlash)
762 *pSlash = 0; /* terminate path at separator */
764 ret = SHNotifyCreateDirectoryW(szTemp, pSlash + 1 == pEnd ? sec : NULL);
766 *pSlash++ = '\\'; /* put the separator back */
770 if (ret && hWnd && (ERROR_CANCELLED != ret))
772 /* We failed and should show a dialog box */
773 FIXME("Show system error message, creating path %s, failed with error %d\n", debugstr_w(path), ret);
774 ret = ERROR_CANCELLED; /* Error has been already presented to user (not really yet!) */
777 return ret;
780 /*************************************************************************
781 * SHFindAttrW [internal]
783 * Get the Attributes for a file or directory. The difference to GetAttributes()
784 * is that this function will also work for paths containing wildcard characters
785 * in its filename.
787 * PARAMS
788 * path [I] path of directory or file to check
789 * fileOnly [I] TRUE if only files should be found
791 * RETURNS
792 * INVALID_FILE_ATTRIBUTES if the path does not exist, the actual attributes of
793 * the first file or directory found otherwise
795 static DWORD SHFindAttrW(LPCWSTR pName, BOOL fileOnly)
797 WIN32_FIND_DATAW wfd;
798 BOOL b_FileMask = fileOnly && (NULL != StrPBrkW(pName, wWildcardChars));
799 DWORD dwAttr = INVALID_FILE_ATTRIBUTES;
800 HANDLE hFind = FindFirstFileW(pName, &wfd);
802 TRACE("%s %d\n", debugstr_w(pName), fileOnly);
803 if (INVALID_HANDLE_VALUE != hFind)
807 if (b_FileMask && IsAttribDir(wfd.dwFileAttributes))
808 continue;
809 dwAttr = wfd.dwFileAttributes;
810 break;
812 while (FindNextFileW(hFind, &wfd));
813 FindClose(hFind);
815 return dwAttr;
818 /*************************************************************************
820 * SHNameTranslate HelperFunction for SHFileOperationA
822 * Translates a list of 0 terminated ASCII strings into Unicode. If *wString
823 * is NULL, only the necessary size of the string is determined and returned,
824 * otherwise the ASCII strings are copied into it and the buffer is increased
825 * to point to the location after the final 0 termination char.
827 static DWORD SHNameTranslate(LPWSTR* wString, LPCWSTR* pWToFrom, BOOL more)
829 DWORD size = 0, aSize = 0;
830 LPCSTR aString = (LPCSTR)*pWToFrom;
832 if (aString)
836 size = lstrlenA(aString) + 1;
837 aSize += size;
838 aString += size;
839 } while ((size != 1) && more);
840 /* The two sizes might be different in the case of multibyte chars */
841 size = MultiByteToWideChar(CP_ACP, 0, (LPCSTR)*pWToFrom, aSize, *wString, 0);
842 if (*wString) /* only in the second loop */
844 MultiByteToWideChar(CP_ACP, 0, (LPCSTR)*pWToFrom, aSize, *wString, size);
845 *pWToFrom = *wString;
846 *wString += size;
849 return size;
851 /*************************************************************************
852 * SHFileOperationA [SHELL32.@]
854 * Function to copy, move, delete and create one or more files with optional
855 * user prompts.
857 * PARAMS
858 * lpFileOp [I/O] pointer to a structure containing all the necessary information
860 * RETURNS
861 * Success: ERROR_SUCCESS.
862 * Failure: ERROR_CANCELLED.
864 * NOTES
865 * exported by name
867 int WINAPI SHFileOperationA(LPSHFILEOPSTRUCTA lpFileOp)
869 SHFILEOPSTRUCTW nFileOp = *((LPSHFILEOPSTRUCTW)lpFileOp);
870 int retCode = 0;
871 DWORD size;
872 LPWSTR ForFree = NULL, /* we change wString in SHNameTranslate and can't use it for freeing */
873 wString = NULL; /* we change this in SHNameTranslate */
875 TRACE("\n");
876 if (FO_DELETE == (nFileOp.wFunc & FO_MASK))
877 nFileOp.pTo = NULL; /* we need a NULL or a valid pointer for translation */
878 if (!(nFileOp.fFlags & FOF_SIMPLEPROGRESS))
879 nFileOp.lpszProgressTitle = NULL; /* we need a NULL or a valid pointer for translation */
880 while (1) /* every loop calculate size, second translate also, if we have storage for this */
882 size = SHNameTranslate(&wString, &nFileOp.lpszProgressTitle, FALSE); /* no loop */
883 size += SHNameTranslate(&wString, &nFileOp.pFrom, TRUE); /* internal loop */
884 size += SHNameTranslate(&wString, &nFileOp.pTo, TRUE); /* internal loop */
886 if (ForFree)
888 retCode = SHFileOperationW(&nFileOp);
889 HeapFree(GetProcessHeap(), 0, ForFree); /* we cannot use wString, it was changed */
890 break;
892 else
894 wString = ForFree = HeapAlloc(GetProcessHeap(), 0, size * sizeof(WCHAR));
895 if (ForFree) continue;
896 retCode = ERROR_OUTOFMEMORY;
897 nFileOp.fAnyOperationsAborted = TRUE;
898 return retCode;
902 lpFileOp->hNameMappings = nFileOp.hNameMappings;
903 lpFileOp->fAnyOperationsAborted = nFileOp.fAnyOperationsAborted;
904 return retCode;
907 #define ERROR_SHELL_INTERNAL_FILE_NOT_FOUND 1026
909 typedef struct
911 DWORD attributes;
912 LPWSTR szDirectory;
913 LPWSTR szFilename;
914 LPWSTR szFullPath;
915 BOOL bFromWildcard;
916 BOOL bFromRelative;
917 BOOL bExists;
918 } FILE_ENTRY;
920 typedef struct
922 FILE_ENTRY *feFiles;
923 DWORD num_alloc;
924 DWORD dwNumFiles;
925 BOOL bAnyFromWildcard;
926 BOOL bAnyDirectories;
927 BOOL bAnyDontExist;
928 } FILE_LIST;
931 static inline void grow_list(FILE_LIST *list)
933 FILE_ENTRY *new = HeapReAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, list->feFiles,
934 list->num_alloc * 2 * sizeof(*new) );
935 list->feFiles = new;
936 list->num_alloc *= 2;
939 /* adds a file to the FILE_ENTRY struct
941 static void add_file_to_entry(FILE_ENTRY *feFile, LPCWSTR szFile)
943 DWORD dwLen = lstrlenW(szFile) + 1;
944 LPCWSTR ptr;
946 feFile->szFullPath = HeapAlloc(GetProcessHeap(), 0, dwLen * sizeof(WCHAR));
947 lstrcpyW(feFile->szFullPath, szFile);
949 ptr = StrRChrW(szFile, NULL, '\\');
950 if (ptr)
952 dwLen = ptr - szFile + 1;
953 feFile->szDirectory = HeapAlloc(GetProcessHeap(), 0, dwLen * sizeof(WCHAR));
954 lstrcpynW(feFile->szDirectory, szFile, dwLen);
956 dwLen = lstrlenW(feFile->szFullPath) - dwLen + 1;
957 feFile->szFilename = HeapAlloc(GetProcessHeap(), 0, dwLen * sizeof(WCHAR));
958 lstrcpyW(feFile->szFilename, ptr + 1); /* skip over backslash */
960 feFile->bFromWildcard = FALSE;
963 static LPWSTR wildcard_to_file(LPCWSTR szWildCard, LPCWSTR szFileName)
965 LPCWSTR ptr;
966 LPWSTR szFullPath;
967 DWORD dwDirLen, dwFullLen;
969 ptr = StrRChrW(szWildCard, NULL, '\\');
970 dwDirLen = ptr - szWildCard + 1;
972 dwFullLen = dwDirLen + lstrlenW(szFileName) + 1;
973 szFullPath = HeapAlloc(GetProcessHeap(), 0, dwFullLen * sizeof(WCHAR));
975 lstrcpynW(szFullPath, szWildCard, dwDirLen + 1);
976 lstrcatW(szFullPath, szFileName);
978 return szFullPath;
981 static void parse_wildcard_files(FILE_LIST *flList, LPCWSTR szFile, LPDWORD pdwListIndex)
983 WIN32_FIND_DATAW wfd;
984 HANDLE hFile = FindFirstFileW(szFile, &wfd);
985 FILE_ENTRY *file;
986 LPWSTR szFullPath;
987 BOOL res;
989 if (hFile == INVALID_HANDLE_VALUE) return;
991 for (res = TRUE; res; res = FindNextFileW(hFile, &wfd))
993 if (IsDotDir(wfd.cFileName)) continue;
994 if (*pdwListIndex >= flList->num_alloc) grow_list( flList );
995 szFullPath = wildcard_to_file(szFile, wfd.cFileName);
996 file = &flList->feFiles[(*pdwListIndex)++];
997 add_file_to_entry(file, szFullPath);
998 file->bFromWildcard = TRUE;
999 file->attributes = wfd.dwFileAttributes;
1000 if (IsAttribDir(file->attributes)) flList->bAnyDirectories = TRUE;
1001 HeapFree(GetProcessHeap(), 0, szFullPath);
1004 FindClose(hFile);
1007 /* takes the null-separated file list and fills out the FILE_LIST */
1008 static HRESULT parse_file_list(FILE_LIST *flList, LPCWSTR szFiles)
1010 LPCWSTR ptr = szFiles;
1011 WCHAR szCurFile[MAX_PATH];
1012 DWORD i = 0;
1014 if (!szFiles)
1015 return ERROR_INVALID_PARAMETER;
1017 flList->bAnyFromWildcard = FALSE;
1018 flList->bAnyDirectories = FALSE;
1019 flList->bAnyDontExist = FALSE;
1020 flList->num_alloc = 32;
1021 flList->dwNumFiles = 0;
1023 /* empty list */
1024 if (!szFiles[0])
1025 return ERROR_ACCESS_DENIED;
1027 flList->feFiles = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY,
1028 flList->num_alloc * sizeof(FILE_ENTRY));
1030 while (*ptr)
1032 if (i >= flList->num_alloc) grow_list( flList );
1034 /* change relative to absolute path */
1035 if (PathIsRelativeW(ptr))
1037 GetCurrentDirectoryW(MAX_PATH, szCurFile);
1038 PathCombineW(szCurFile, szCurFile, ptr);
1039 flList->feFiles[i].bFromRelative = TRUE;
1041 else
1043 lstrcpyW(szCurFile, ptr);
1044 flList->feFiles[i].bFromRelative = FALSE;
1047 /* parse wildcard files if they are in the filename */
1048 if (StrPBrkW(szCurFile, wWildcardChars))
1050 parse_wildcard_files(flList, szCurFile, &i);
1051 flList->bAnyFromWildcard = TRUE;
1052 i--;
1054 else
1056 FILE_ENTRY *file = &flList->feFiles[i];
1057 add_file_to_entry(file, szCurFile);
1058 file->attributes = GetFileAttributesW( file->szFullPath );
1059 file->bExists = (file->attributes != INVALID_FILE_ATTRIBUTES);
1060 if (!file->bExists) flList->bAnyDontExist = TRUE;
1061 if (IsAttribDir(file->attributes)) flList->bAnyDirectories = TRUE;
1064 /* advance to the next string */
1065 ptr += lstrlenW(ptr) + 1;
1066 i++;
1068 flList->dwNumFiles = i;
1070 return S_OK;
1073 /* free the FILE_LIST */
1074 static void destroy_file_list(FILE_LIST *flList)
1076 DWORD i;
1078 if (!flList || !flList->feFiles)
1079 return;
1081 for (i = 0; i < flList->dwNumFiles; i++)
1083 HeapFree(GetProcessHeap(), 0, flList->feFiles[i].szDirectory);
1084 HeapFree(GetProcessHeap(), 0, flList->feFiles[i].szFilename);
1085 HeapFree(GetProcessHeap(), 0, flList->feFiles[i].szFullPath);
1088 HeapFree(GetProcessHeap(), 0, flList->feFiles);
1091 static void copy_dir_to_dir(FILE_OPERATION *op, const FILE_ENTRY *feFrom, LPCWSTR szDestPath)
1093 WCHAR szFrom[MAX_PATH], szTo[MAX_PATH];
1094 SHFILEOPSTRUCTW fileOp;
1096 static const WCHAR wildCardFiles[] = {'*','.','*',0};
1098 if (IsDotDir(feFrom->szFilename))
1099 return;
1101 if (PathFileExistsW(szDestPath))
1102 PathCombineW(szTo, szDestPath, feFrom->szFilename);
1103 else
1104 lstrcpyW(szTo, szDestPath);
1106 if (!(op->req->fFlags & FOF_NOCONFIRMATION) && PathFileExistsW(szTo)) {
1107 if (!SHELL_ConfirmDialogW(op->req->hwnd, ASK_OVERWRITE_FOLDER, feFrom->szFilename, op))
1109 /* Vista returns an ERROR_CANCELLED even if user pressed "No" */
1110 if (!op->bManyItems)
1111 op->bCancelled = TRUE;
1112 return;
1116 szTo[lstrlenW(szTo) + 1] = '\0';
1117 SHNotifyCreateDirectoryW(szTo, NULL);
1119 PathCombineW(szFrom, feFrom->szFullPath, wildCardFiles);
1120 szFrom[lstrlenW(szFrom) + 1] = '\0';
1122 fileOp = *op->req;
1123 fileOp.pFrom = szFrom;
1124 fileOp.pTo = szTo;
1125 fileOp.fFlags &= ~FOF_MULTIDESTFILES; /* we know we're copying to one dir */
1127 /* Don't ask the user about overwriting files when he accepted to overwrite the
1128 folder. FIXME: this is not exactly what Windows does - e.g. there would be
1129 an additional confirmation for a nested folder */
1130 fileOp.fFlags |= FOF_NOCONFIRMATION;
1132 SHFileOperationW(&fileOp);
1135 static BOOL copy_file_to_file(FILE_OPERATION *op, const WCHAR *szFrom, const WCHAR *szTo)
1137 if (!(op->req->fFlags & FOF_NOCONFIRMATION) && PathFileExistsW(szTo))
1139 if (!SHELL_ConfirmDialogW(op->req->hwnd, ASK_OVERWRITE_FILE, PathFindFileNameW(szTo), op))
1140 return FALSE;
1143 return SHNotifyCopyFileW(szFrom, szTo, FALSE) == 0;
1146 /* copy a file or directory to another directory */
1147 static void copy_to_dir(FILE_OPERATION *op, const FILE_ENTRY *feFrom, const FILE_ENTRY *feTo)
1149 if (!PathFileExistsW(feTo->szFullPath))
1150 SHNotifyCreateDirectoryW(feTo->szFullPath, NULL);
1152 if (IsAttribFile(feFrom->attributes))
1154 WCHAR szDestPath[MAX_PATH];
1156 PathCombineW(szDestPath, feTo->szFullPath, feFrom->szFilename);
1157 copy_file_to_file(op, feFrom->szFullPath, szDestPath);
1159 else if (!(op->req->fFlags & FOF_FILESONLY && feFrom->bFromWildcard))
1160 copy_dir_to_dir(op, feFrom, feTo->szFullPath);
1163 static void create_dest_dirs(LPCWSTR szDestDir)
1165 WCHAR dir[MAX_PATH];
1166 LPCWSTR ptr = StrChrW(szDestDir, '\\');
1168 /* make sure all directories up to last one are created */
1169 while (ptr && (ptr = StrChrW(ptr + 1, '\\')))
1171 lstrcpynW(dir, szDestDir, ptr - szDestDir + 1);
1173 if (!PathFileExistsW(dir))
1174 SHNotifyCreateDirectoryW(dir, NULL);
1177 /* create last directory */
1178 if (!PathFileExistsW(szDestDir))
1179 SHNotifyCreateDirectoryW(szDestDir, NULL);
1182 /* the FO_COPY operation */
1183 static int copy_files(FILE_OPERATION *op, const FILE_LIST *flFrom, FILE_LIST *flTo)
1185 DWORD i;
1186 const FILE_ENTRY *entryToCopy;
1187 const FILE_ENTRY *fileDest = &flTo->feFiles[0];
1189 if (flFrom->bAnyDontExist)
1190 return ERROR_SHELL_INTERNAL_FILE_NOT_FOUND;
1192 if (flTo->dwNumFiles == 0)
1194 /* If the destination is empty, SHFileOperation should use the current directory */
1195 WCHAR curdir[MAX_PATH+1];
1197 GetCurrentDirectoryW(MAX_PATH, curdir);
1198 curdir[lstrlenW(curdir)+1] = 0;
1200 destroy_file_list(flTo);
1201 ZeroMemory(flTo, sizeof(FILE_LIST));
1202 parse_file_list(flTo, curdir);
1203 fileDest = &flTo->feFiles[0];
1206 if (op->req->fFlags & FOF_MULTIDESTFILES)
1208 if (flFrom->bAnyFromWildcard)
1209 return ERROR_CANCELLED;
1211 if (flFrom->dwNumFiles != flTo->dwNumFiles)
1213 if (flFrom->dwNumFiles != 1 && !IsAttribDir(fileDest->attributes))
1214 return ERROR_CANCELLED;
1216 /* Free all but the first entry. */
1217 for (i = 1; i < flTo->dwNumFiles; i++)
1219 HeapFree(GetProcessHeap(), 0, flTo->feFiles[i].szDirectory);
1220 HeapFree(GetProcessHeap(), 0, flTo->feFiles[i].szFilename);
1221 HeapFree(GetProcessHeap(), 0, flTo->feFiles[i].szFullPath);
1224 flTo->dwNumFiles = 1;
1226 else if (IsAttribDir(fileDest->attributes))
1228 for (i = 1; i < flTo->dwNumFiles; i++)
1229 if (!IsAttribDir(flTo->feFiles[i].attributes) ||
1230 !IsAttribDir(flFrom->feFiles[i].attributes))
1232 return ERROR_CANCELLED;
1236 else if (flFrom->dwNumFiles != 1)
1238 if (flTo->dwNumFiles != 1 && !IsAttribDir(fileDest->attributes))
1239 return ERROR_CANCELLED;
1241 if (PathFileExistsW(fileDest->szFullPath) &&
1242 IsAttribFile(fileDest->attributes))
1244 return ERROR_CANCELLED;
1247 if (flTo->dwNumFiles == 1 && fileDest->bFromRelative &&
1248 !PathFileExistsW(fileDest->szFullPath))
1250 return ERROR_CANCELLED;
1254 for (i = 0; i < flFrom->dwNumFiles; i++)
1256 entryToCopy = &flFrom->feFiles[i];
1258 if ((op->req->fFlags & FOF_MULTIDESTFILES) &&
1259 flTo->dwNumFiles > 1)
1261 fileDest = &flTo->feFiles[i];
1264 if (IsAttribDir(entryToCopy->attributes) &&
1265 !lstrcmpiW(entryToCopy->szFullPath, fileDest->szDirectory))
1267 return ERROR_SUCCESS;
1270 create_dest_dirs(fileDest->szDirectory);
1272 if (!lstrcmpiW(entryToCopy->szFullPath, fileDest->szFullPath))
1274 if (IsAttribFile(entryToCopy->attributes))
1275 return ERROR_NO_MORE_SEARCH_HANDLES;
1276 else
1277 return ERROR_SUCCESS;
1280 if ((flFrom->dwNumFiles > 1 && flTo->dwNumFiles == 1) ||
1281 IsAttribDir(fileDest->attributes))
1283 copy_to_dir(op, entryToCopy, fileDest);
1285 else if (IsAttribDir(entryToCopy->attributes))
1287 copy_dir_to_dir(op, entryToCopy, fileDest->szFullPath);
1289 else
1291 if (!copy_file_to_file(op, entryToCopy->szFullPath, fileDest->szFullPath))
1293 op->req->fAnyOperationsAborted = TRUE;
1294 return ERROR_CANCELLED;
1298 /* Vista return code. XP would return e.g. ERROR_FILE_NOT_FOUND, ERROR_ALREADY_EXISTS */
1299 if (op->bCancelled)
1300 return ERROR_CANCELLED;
1303 /* Vista return code. On XP if the used pressed "No" for the last item,
1304 * ERROR_ARENA_TRASHED would be returned */
1305 return ERROR_SUCCESS;
1308 static BOOL confirm_delete_list(HWND hWnd, DWORD fFlags, BOOL fTrash, const FILE_LIST *flFrom)
1310 if (flFrom->dwNumFiles > 1)
1312 WCHAR tmp[8];
1313 const WCHAR format[] = {'%','d',0};
1315 wnsprintfW(tmp, sizeof(tmp)/sizeof(tmp[0]), format, flFrom->dwNumFiles);
1316 return SHELL_ConfirmDialogW(hWnd, (fTrash?ASK_TRASH_MULTIPLE_ITEM:ASK_DELETE_MULTIPLE_ITEM), tmp, NULL);
1318 else
1320 const FILE_ENTRY *fileEntry = &flFrom->feFiles[0];
1322 if (IsAttribFile(fileEntry->attributes))
1323 return SHELL_ConfirmDialogW(hWnd, (fTrash?ASK_TRASH_FILE:ASK_DELETE_FILE), fileEntry->szFullPath, NULL);
1324 else if (!(fFlags & FOF_FILESONLY && fileEntry->bFromWildcard))
1325 return SHELL_ConfirmDialogW(hWnd, (fTrash?ASK_TRASH_FOLDER:ASK_DELETE_FOLDER), fileEntry->szFullPath, NULL);
1327 return TRUE;
1330 /* the FO_DELETE operation */
1331 static int delete_files(LPSHFILEOPSTRUCTW lpFileOp, const FILE_LIST *flFrom)
1333 const FILE_ENTRY *fileEntry;
1334 DWORD i;
1335 int ret;
1336 BOOL bTrash;
1338 if (!flFrom->dwNumFiles)
1339 return ERROR_SUCCESS;
1341 /* Windows also checks only the first item */
1342 bTrash = (lpFileOp->fFlags & FOF_ALLOWUNDO)
1343 && TRASH_CanTrashFile(flFrom->feFiles[0].szFullPath);
1345 if (!(lpFileOp->fFlags & FOF_NOCONFIRMATION) || (!bTrash && lpFileOp->fFlags & FOF_WANTNUKEWARNING))
1346 if (!confirm_delete_list(lpFileOp->hwnd, lpFileOp->fFlags, bTrash, flFrom))
1348 lpFileOp->fAnyOperationsAborted = TRUE;
1349 return 0;
1352 for (i = 0; i < flFrom->dwNumFiles; i++)
1354 fileEntry = &flFrom->feFiles[i];
1356 if (!IsAttribFile(fileEntry->attributes) &&
1357 (lpFileOp->fFlags & FOF_FILESONLY && fileEntry->bFromWildcard))
1358 continue;
1360 if (bTrash)
1362 BOOL bDelete;
1363 if (TRASH_TrashFile(fileEntry->szFullPath))
1364 continue;
1366 /* Note: Windows silently deletes the file in such a situation, we show a dialog */
1367 if (!(lpFileOp->fFlags & FOF_NOCONFIRMATION) || (lpFileOp->fFlags & FOF_WANTNUKEWARNING))
1368 bDelete = SHELL_ConfirmDialogW(lpFileOp->hwnd, ASK_CANT_TRASH_ITEM, fileEntry->szFullPath, NULL);
1369 else
1370 bDelete = TRUE;
1372 if (!bDelete)
1374 lpFileOp->fAnyOperationsAborted = TRUE;
1375 break;
1379 /* delete the file or directory */
1380 if (IsAttribFile(fileEntry->attributes))
1381 ret = DeleteFileW(fileEntry->szFullPath) ?
1382 ERROR_SUCCESS : GetLastError();
1383 else
1384 ret = SHELL_DeleteDirectoryW(lpFileOp->hwnd, fileEntry->szFullPath, FALSE);
1386 if (ret)
1387 return ret;
1390 return ERROR_SUCCESS;
1393 /* moves a file or directory to another directory */
1394 static void move_to_dir(LPSHFILEOPSTRUCTW lpFileOp, const FILE_ENTRY *feFrom, const FILE_ENTRY *feTo)
1396 WCHAR szDestPath[MAX_PATH];
1398 PathCombineW(szDestPath, feTo->szFullPath, feFrom->szFilename);
1399 SHNotifyMoveFileW(feFrom->szFullPath, szDestPath);
1402 /* the FO_MOVE operation */
1403 static int move_files(LPSHFILEOPSTRUCTW lpFileOp, const FILE_LIST *flFrom, const FILE_LIST *flTo)
1405 DWORD i;
1406 INT mismatched = 0;
1407 const FILE_ENTRY *entryToMove;
1408 const FILE_ENTRY *fileDest;
1410 if (!flFrom->dwNumFiles)
1411 return ERROR_SUCCESS;
1413 if (!flTo->dwNumFiles)
1414 return ERROR_FILE_NOT_FOUND;
1416 if (!(lpFileOp->fFlags & FOF_MULTIDESTFILES) &&
1417 flTo->dwNumFiles > 1 && flFrom->dwNumFiles > 1)
1419 return ERROR_CANCELLED;
1422 if (!(lpFileOp->fFlags & FOF_MULTIDESTFILES) &&
1423 !flFrom->bAnyDirectories &&
1424 flFrom->dwNumFiles > flTo->dwNumFiles)
1426 return ERROR_CANCELLED;
1429 if (!PathFileExistsW(flTo->feFiles[0].szDirectory))
1430 return ERROR_CANCELLED;
1432 if (lpFileOp->fFlags & FOF_MULTIDESTFILES)
1433 mismatched = flFrom->dwNumFiles - flTo->dwNumFiles;
1435 fileDest = &flTo->feFiles[0];
1436 for (i = 0; i < flFrom->dwNumFiles; i++)
1438 entryToMove = &flFrom->feFiles[i];
1440 if (!PathFileExistsW(fileDest->szDirectory))
1441 return ERROR_CANCELLED;
1443 if (lpFileOp->fFlags & FOF_MULTIDESTFILES)
1445 if (i >= flTo->dwNumFiles)
1446 break;
1447 fileDest = &flTo->feFiles[i];
1448 if (mismatched && !fileDest->bExists)
1450 create_dest_dirs(flTo->feFiles[i].szFullPath);
1451 flTo->feFiles[i].bExists = TRUE;
1452 flTo->feFiles[i].attributes = FILE_ATTRIBUTE_DIRECTORY;
1456 if (fileDest->bExists && IsAttribDir(fileDest->attributes))
1457 move_to_dir(lpFileOp, entryToMove, fileDest);
1458 else
1459 SHNotifyMoveFileW(entryToMove->szFullPath, fileDest->szFullPath);
1462 if (mismatched > 0)
1464 if (flFrom->bAnyDirectories)
1465 return DE_DESTSAMETREE;
1466 else
1467 return DE_SAMEFILE;
1470 return ERROR_SUCCESS;
1473 /* the FO_RENAME files */
1474 static int rename_files(LPSHFILEOPSTRUCTW lpFileOp, const FILE_LIST *flFrom, const FILE_LIST *flTo)
1476 const FILE_ENTRY *feFrom;
1477 const FILE_ENTRY *feTo;
1479 if (flFrom->dwNumFiles != 1)
1480 return ERROR_GEN_FAILURE;
1482 if (flTo->dwNumFiles != 1)
1483 return ERROR_CANCELLED;
1485 feFrom = &flFrom->feFiles[0];
1486 feTo= &flTo->feFiles[0];
1488 /* fail if destination doesn't exist */
1489 if (!feFrom->bExists)
1490 return ERROR_SHELL_INTERNAL_FILE_NOT_FOUND;
1492 /* fail if destination already exists */
1493 if (feTo->bExists)
1494 return ERROR_ALREADY_EXISTS;
1496 return SHNotifyMoveFileW(feFrom->szFullPath, feTo->szFullPath);
1499 /* alert the user if an unsupported flag is used */
1500 static void check_flags(FILEOP_FLAGS fFlags)
1502 WORD wUnsupportedFlags = FOF_NO_CONNECTED_ELEMENTS |
1503 FOF_NOCOPYSECURITYATTRIBS | FOF_NORECURSEREPARSE |
1504 FOF_RENAMEONCOLLISION | FOF_WANTMAPPINGHANDLE;
1506 if (fFlags & wUnsupportedFlags)
1507 FIXME("Unsupported flags: %04x\n", fFlags);
1510 /*************************************************************************
1511 * SHFileOperationW [SHELL32.@]
1513 * See SHFileOperationA
1515 int WINAPI SHFileOperationW(LPSHFILEOPSTRUCTW lpFileOp)
1517 FILE_OPERATION op;
1518 FILE_LIST flFrom, flTo;
1519 int ret = 0;
1521 if (!lpFileOp)
1522 return ERROR_INVALID_PARAMETER;
1524 check_flags(lpFileOp->fFlags);
1526 ZeroMemory(&flFrom, sizeof(FILE_LIST));
1527 ZeroMemory(&flTo, sizeof(FILE_LIST));
1529 if ((ret = parse_file_list(&flFrom, lpFileOp->pFrom)))
1530 return ret;
1532 if (lpFileOp->wFunc != FO_DELETE)
1533 parse_file_list(&flTo, lpFileOp->pTo);
1535 ZeroMemory(&op, sizeof(op));
1536 op.req = lpFileOp;
1537 op.bManyItems = (flFrom.dwNumFiles > 1);
1538 lpFileOp->fAnyOperationsAborted = FALSE;
1540 switch (lpFileOp->wFunc)
1542 case FO_COPY:
1543 ret = copy_files(&op, &flFrom, &flTo);
1544 break;
1545 case FO_DELETE:
1546 ret = delete_files(lpFileOp, &flFrom);
1547 break;
1548 case FO_MOVE:
1549 ret = move_files(lpFileOp, &flFrom, &flTo);
1550 break;
1551 case FO_RENAME:
1552 ret = rename_files(lpFileOp, &flFrom, &flTo);
1553 break;
1554 default:
1555 ret = ERROR_INVALID_PARAMETER;
1556 break;
1559 destroy_file_list(&flFrom);
1561 if (lpFileOp->wFunc != FO_DELETE)
1562 destroy_file_list(&flTo);
1564 if (ret == ERROR_CANCELLED)
1565 lpFileOp->fAnyOperationsAborted = TRUE;
1567 SetLastError(ERROR_SUCCESS);
1568 return ret;
1571 #define SHDSA_GetItemCount(hdsa) (*(int*)(hdsa))
1573 /*************************************************************************
1574 * SHFreeNameMappings [shell32.246]
1576 * Free the mapping handle returned by SHFileOperation if FOF_WANTSMAPPINGHANDLE
1577 * was specified.
1579 * PARAMS
1580 * hNameMapping [I] handle to the name mappings used during renaming of files
1582 * RETURNS
1583 * Nothing
1585 void WINAPI SHFreeNameMappings(HANDLE hNameMapping)
1587 if (hNameMapping)
1589 int i = SHDSA_GetItemCount((HDSA)hNameMapping) - 1;
1591 for (; i>= 0; i--)
1593 LPSHNAMEMAPPINGW lp = DSA_GetItemPtr(hNameMapping, i);
1595 SHFree(lp->pszOldPath);
1596 SHFree(lp->pszNewPath);
1598 DSA_Destroy(hNameMapping);
1602 /*************************************************************************
1603 * SheGetDirA [SHELL32.@]
1605 * drive = 0: returns the current directory path
1606 * drive > 0: returns the current directory path of the specified drive
1607 * drive=1 -> A: drive=2 -> B: ...
1608 * returns 0 if successful
1610 DWORD WINAPI SheGetDirA(DWORD drive, LPSTR buffer)
1612 WCHAR org_path[MAX_PATH];
1613 DWORD ret;
1614 char drv_path[3];
1616 /* change current directory to the specified drive */
1617 if (drive) {
1618 strcpy(drv_path, "A:");
1619 drv_path[0] += (char)drive-1;
1621 GetCurrentDirectoryW(MAX_PATH, org_path);
1623 SetCurrentDirectoryA(drv_path);
1626 /* query current directory path of the specified drive */
1627 ret = GetCurrentDirectoryA(MAX_PATH, buffer);
1629 /* back to the original drive */
1630 if (drive)
1631 SetCurrentDirectoryW(org_path);
1633 if (!ret)
1634 return GetLastError();
1636 return 0;
1639 /*************************************************************************
1640 * SheGetDirW [SHELL32.@]
1642 * drive = 0: returns the current directory path
1643 * drive > 0: returns the current directory path of the specified drive
1644 * drive=1 -> A: drive=2 -> B: ...
1645 * returns 0 if successful
1647 DWORD WINAPI SheGetDirW(DWORD drive, LPWSTR buffer)
1649 WCHAR org_path[MAX_PATH];
1650 DWORD ret;
1651 char drv_path[3];
1653 /* change current directory to the specified drive */
1654 if (drive) {
1655 strcpy(drv_path, "A:");
1656 drv_path[0] += (char)drive-1;
1658 GetCurrentDirectoryW(MAX_PATH, org_path);
1660 SetCurrentDirectoryA(drv_path);
1663 /* query current directory path of the specified drive */
1664 ret = GetCurrentDirectoryW(MAX_PATH, buffer);
1666 /* back to the original drive */
1667 if (drive)
1668 SetCurrentDirectoryW(org_path);
1670 if (!ret)
1671 return GetLastError();
1673 return 0;
1676 /*************************************************************************
1677 * SheChangeDirA [SHELL32.@]
1679 * changes the current directory to the specified path
1680 * and returns 0 if successful
1682 DWORD WINAPI SheChangeDirA(LPSTR path)
1684 if (SetCurrentDirectoryA(path))
1685 return 0;
1686 else
1687 return GetLastError();
1690 /*************************************************************************
1691 * SheChangeDirW [SHELL32.@]
1693 * changes the current directory to the specified path
1694 * and returns 0 if successful
1696 DWORD WINAPI SheChangeDirW(LPWSTR path)
1698 if (SetCurrentDirectoryW(path))
1699 return 0;
1700 else
1701 return GetLastError();
1704 /*************************************************************************
1705 * IsNetDrive [SHELL32.66]
1707 int WINAPI IsNetDrive(int drive)
1709 char root[4];
1710 strcpy(root, "A:\\");
1711 root[0] += (char)drive;
1712 return (GetDriveTypeA(root) == DRIVE_REMOTE);
1716 /*************************************************************************
1717 * RealDriveType [SHELL32.524]
1719 int WINAPI RealDriveType(int drive, BOOL bQueryNet)
1721 char root[] = "A:\\";
1722 root[0] += (char)drive;
1723 return GetDriveTypeA(root);
1726 /***********************************************************************
1727 * SHPathPrepareForWriteA (SHELL32.@)
1729 HRESULT WINAPI SHPathPrepareForWriteA(HWND hwnd, IUnknown *modless, LPCSTR path, DWORD flags)
1731 WCHAR wpath[MAX_PATH];
1732 MultiByteToWideChar( CP_ACP, 0, path, -1, wpath, MAX_PATH);
1733 return SHPathPrepareForWriteW(hwnd, modless, wpath, flags);
1736 /***********************************************************************
1737 * SHPathPrepareForWriteW (SHELL32.@)
1739 HRESULT WINAPI SHPathPrepareForWriteW(HWND hwnd, IUnknown *modless, LPCWSTR path, DWORD flags)
1741 DWORD res;
1742 DWORD err;
1743 LPCWSTR realpath;
1744 int len;
1745 WCHAR* last_slash;
1746 WCHAR* temppath=NULL;
1748 TRACE("%p %p %s 0x%08x\n", hwnd, modless, debugstr_w(path), flags);
1750 if (flags & ~(SHPPFW_DIRCREATE|SHPPFW_ASKDIRCREATE|SHPPFW_IGNOREFILENAME))
1751 FIXME("unimplemented flags 0x%08x\n", flags);
1753 /* cut off filename if necessary */
1754 if (flags & SHPPFW_IGNOREFILENAME)
1756 last_slash = StrRChrW(path, NULL, '\\');
1757 if (last_slash == NULL)
1758 len = 1;
1759 else
1760 len = last_slash - path + 1;
1761 temppath = HeapAlloc(GetProcessHeap(), 0, len * sizeof(WCHAR));
1762 if (!temppath)
1763 return E_OUTOFMEMORY;
1764 StrCpyNW(temppath, path, len);
1765 realpath = temppath;
1767 else
1769 realpath = path;
1772 /* try to create the directory if asked to */
1773 if (flags & (SHPPFW_DIRCREATE|SHPPFW_ASKDIRCREATE))
1775 if (flags & SHPPFW_ASKDIRCREATE)
1776 FIXME("treating SHPPFW_ASKDIRCREATE as SHPPFW_DIRCREATE\n");
1778 SHCreateDirectoryExW(0, realpath, NULL);
1781 /* check if we can access the directory */
1782 res = GetFileAttributesW(realpath);
1784 HeapFree(GetProcessHeap(), 0, temppath);
1786 if (res == INVALID_FILE_ATTRIBUTES)
1788 err = GetLastError();
1789 if (err == ERROR_FILE_NOT_FOUND)
1790 return HRESULT_FROM_WIN32(ERROR_PATH_NOT_FOUND);
1791 return HRESULT_FROM_WIN32(err);
1793 else if (res & FILE_ATTRIBUTE_DIRECTORY)
1794 return S_OK;
1795 else
1796 return HRESULT_FROM_WIN32(ERROR_DIRECTORY);