shell32: Fix incorrect use of the ScreenToClient function.
[wine/multimedia.git] / dlls / shell32 / shlfileop.c
blobf022faf478503dbd12fa0b5bafa5d4e2b3dde489
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 int width;
99 GetWindowRect(hButton, &r);
100 MapWindowPoints( 0, hDlg, (POINT *)&r, 2 );
101 width = r.right - r.left;
102 SetWindowPos(hButton, 0, *xPos - width, r.top - yOffset, 0, 0,
103 SWP_NOSIZE | SWP_NOZORDER | SWP_NOACTIVATE | SWP_NOREDRAW );
104 *xPos -= width + 5;
106 else
107 ShowWindow(hButton, SW_HIDE);
110 /* Note: we paint the text manually and don't use the static control to make
111 * sure the text has the same height as the one computed in WM_INITDIALOG
113 static INT_PTR ConfirmMsgBox_Paint(HWND hDlg)
115 PAINTSTRUCT ps;
116 HFONT hOldFont;
117 RECT r;
118 HDC hdc;
120 BeginPaint(hDlg, &ps);
121 hdc = ps.hdc;
123 GetClientRect(GetDlgItem(hDlg, IDD_MESSAGE), &r);
124 /* this will remap the rect to dialog coords */
125 MapWindowPoints(GetDlgItem(hDlg, IDD_MESSAGE), hDlg, (LPPOINT)&r, 2);
126 hOldFont = SelectObject(hdc, (HFONT)SendDlgItemMessageW(hDlg, IDD_MESSAGE, WM_GETFONT, 0, 0));
127 DrawTextW(hdc, GetPropW(hDlg, CONFIRM_MSG_PROP), -1, &r, DT_NOPREFIX | DT_PATH_ELLIPSIS | DT_WORDBREAK);
128 SelectObject(hdc, hOldFont);
129 EndPaint(hDlg, &ps);
130 return TRUE;
133 static INT_PTR ConfirmMsgBox_Init(HWND hDlg, LPARAM lParam)
135 struct confirm_msg_info *info = (struct confirm_msg_info *)lParam;
136 INT xPos, yOffset;
137 int width, height;
138 HFONT hOldFont;
139 HDC hdc;
140 RECT r;
142 SetWindowTextW(hDlg, info->lpszCaption);
143 ShowWindow(GetDlgItem(hDlg, IDD_MESSAGE), SW_HIDE);
144 SetPropW(hDlg, CONFIRM_MSG_PROP, info->lpszText);
145 SendDlgItemMessageW(hDlg, IDD_ICON, STM_SETICON, (WPARAM)info->hIcon, 0);
147 /* compute the text height and resize the dialog */
148 GetClientRect(GetDlgItem(hDlg, IDD_MESSAGE), &r);
149 hdc = GetDC(hDlg);
150 yOffset = r.bottom;
151 hOldFont = SelectObject(hdc, (HFONT)SendDlgItemMessageW(hDlg, IDD_MESSAGE, WM_GETFONT, 0, 0));
152 DrawTextW(hdc, info->lpszText, -1, &r, DT_NOPREFIX | DT_PATH_ELLIPSIS | DT_WORDBREAK | DT_CALCRECT);
153 SelectObject(hdc, hOldFont);
154 yOffset -= r.bottom;
155 yOffset = min(yOffset, 35); /* don't make the dialog too small */
156 ReleaseDC(hDlg, hdc);
158 GetClientRect(hDlg, &r);
159 xPos = r.right - 7;
160 GetWindowRect(hDlg, &r);
161 width = r.right - r.left;
162 height = r.bottom - r.top - yOffset;
163 MoveWindow(hDlg, (GetSystemMetrics(SM_CXSCREEN) - width)/2,
164 (GetSystemMetrics(SM_CYSCREEN) - height)/2, width, height, FALSE);
166 confirm_msg_move_button(hDlg, IDCANCEL, &xPos, yOffset, info->bYesToAll);
167 confirm_msg_move_button(hDlg, IDNO, &xPos, yOffset, TRUE);
168 confirm_msg_move_button(hDlg, IDD_YESTOALL, &xPos, yOffset, info->bYesToAll);
169 confirm_msg_move_button(hDlg, IDYES, &xPos, yOffset, TRUE);
170 return TRUE;
173 static INT_PTR CALLBACK ConfirmMsgBoxProc(HWND hDlg, UINT uMsg, WPARAM wParam, LPARAM lParam)
175 switch (uMsg)
177 case WM_INITDIALOG:
178 return ConfirmMsgBox_Init(hDlg, lParam);
179 case WM_PAINT:
180 return ConfirmMsgBox_Paint(hDlg);
181 case WM_COMMAND:
182 EndDialog(hDlg, wParam);
183 break;
184 case WM_CLOSE:
185 EndDialog(hDlg, IDCANCEL);
186 break;
188 return FALSE;
191 static int SHELL_ConfirmMsgBox(HWND hWnd, LPWSTR lpszText, LPWSTR lpszCaption, HICON hIcon, BOOL bYesToAll)
193 static const WCHAR wszTemplate[] = {'S','H','E','L','L','_','Y','E','S','T','O','A','L','L','_','M','S','G','B','O','X',0};
194 struct confirm_msg_info info;
196 info.lpszText = lpszText;
197 info.lpszCaption = lpszCaption;
198 info.hIcon = hIcon;
199 info.bYesToAll = bYesToAll;
200 return DialogBoxParamW(shell32_hInstance, wszTemplate, hWnd, ConfirmMsgBoxProc, (LPARAM)&info);
203 /* confirmation dialogs content */
204 typedef struct
206 HINSTANCE hIconInstance;
207 UINT icon_resource_id;
208 UINT caption_resource_id, text_resource_id;
209 } SHELL_ConfirmIDstruc;
211 static BOOL SHELL_ConfirmIDs(int nKindOfDialog, SHELL_ConfirmIDstruc *ids)
213 ids->hIconInstance = shell32_hInstance;
214 switch (nKindOfDialog) {
215 case ASK_DELETE_FILE:
216 ids->icon_resource_id = IDI_SHELL_CONFIRM_DELETE;
217 ids->caption_resource_id = IDS_DELETEITEM_CAPTION;
218 ids->text_resource_id = IDS_DELETEITEM_TEXT;
219 return TRUE;
220 case ASK_DELETE_FOLDER:
221 ids->icon_resource_id = IDI_SHELL_CONFIRM_DELETE;
222 ids->caption_resource_id = IDS_DELETEFOLDER_CAPTION;
223 ids->text_resource_id = IDS_DELETEITEM_TEXT;
224 return TRUE;
225 case ASK_DELETE_MULTIPLE_ITEM:
226 ids->icon_resource_id = IDI_SHELL_CONFIRM_DELETE;
227 ids->caption_resource_id = IDS_DELETEITEM_CAPTION;
228 ids->text_resource_id = IDS_DELETEMULTIPLE_TEXT;
229 return TRUE;
230 case ASK_TRASH_FILE:
231 ids->icon_resource_id = IDI_SHELL_TRASH_FILE;
232 ids->caption_resource_id = IDS_DELETEITEM_CAPTION;
233 ids->text_resource_id = IDS_TRASHITEM_TEXT;
234 return TRUE;
235 case ASK_TRASH_FOLDER:
236 ids->icon_resource_id = IDI_SHELL_TRASH_FILE;
237 ids->caption_resource_id = IDS_DELETEFOLDER_CAPTION;
238 ids->text_resource_id = IDS_TRASHFOLDER_TEXT;
239 return TRUE;
240 case ASK_TRASH_MULTIPLE_ITEM:
241 ids->icon_resource_id = IDI_SHELL_TRASH_FILE;
242 ids->caption_resource_id = IDS_DELETEITEM_CAPTION;
243 ids->text_resource_id = IDS_TRASHMULTIPLE_TEXT;
244 return TRUE;
245 case ASK_CANT_TRASH_ITEM:
246 ids->icon_resource_id = IDI_SHELL_CONFIRM_DELETE;
247 ids->caption_resource_id = IDS_DELETEITEM_CAPTION;
248 ids->text_resource_id = IDS_CANTTRASH_TEXT;
249 return TRUE;
250 case ASK_DELETE_SELECTED:
251 ids->icon_resource_id = IDI_SHELL_CONFIRM_DELETE;
252 ids->caption_resource_id = IDS_DELETEITEM_CAPTION;
253 ids->text_resource_id = IDS_DELETESELECTED_TEXT;
254 return TRUE;
255 case ASK_OVERWRITE_FILE:
256 ids->hIconInstance = NULL;
257 ids->icon_resource_id = IDI_WARNING;
258 ids->caption_resource_id = IDS_OVERWRITEFILE_CAPTION;
259 ids->text_resource_id = IDS_OVERWRITEFILE_TEXT;
260 return TRUE;
261 case ASK_OVERWRITE_FOLDER:
262 ids->hIconInstance = NULL;
263 ids->icon_resource_id = IDI_WARNING;
264 ids->caption_resource_id = IDS_OVERWRITEFILE_CAPTION;
265 ids->text_resource_id = IDS_OVERWRITEFOLDER_TEXT;
266 return TRUE;
267 default:
268 FIXME(" Unhandled nKindOfDialog %d stub\n", nKindOfDialog);
270 return FALSE;
273 static BOOL SHELL_ConfirmDialogW(HWND hWnd, int nKindOfDialog, LPCWSTR szDir, FILE_OPERATION *op)
275 WCHAR szCaption[255], szText[255], szBuffer[MAX_PATH + 256];
276 SHELL_ConfirmIDstruc ids;
277 DWORD_PTR args[1];
278 HICON hIcon;
279 int ret;
281 assert(nKindOfDialog >= 0 && nKindOfDialog < 32);
282 if (op && (op->dwYesToAllMask & (1 << nKindOfDialog)))
283 return TRUE;
285 if (!SHELL_ConfirmIDs(nKindOfDialog, &ids)) return FALSE;
287 LoadStringW(shell32_hInstance, ids.caption_resource_id, szCaption, sizeof(szCaption)/sizeof(WCHAR));
288 LoadStringW(shell32_hInstance, ids.text_resource_id, szText, sizeof(szText)/sizeof(WCHAR));
290 args[0] = (DWORD_PTR)szDir;
291 FormatMessageW(FORMAT_MESSAGE_FROM_STRING|FORMAT_MESSAGE_ARGUMENT_ARRAY,
292 szText, 0, 0, szBuffer, sizeof(szBuffer), (__ms_va_list*)args);
293 hIcon = LoadIconW(ids.hIconInstance, (LPWSTR)MAKEINTRESOURCE(ids.icon_resource_id));
295 ret = SHELL_ConfirmMsgBox(hWnd, szBuffer, szCaption, hIcon, op && op->bManyItems);
296 if (op) {
297 if (ret == IDD_YESTOALL) {
298 op->dwYesToAllMask |= (1 << nKindOfDialog);
299 ret = IDYES;
301 if (ret == IDCANCEL)
302 op->bCancelled = TRUE;
303 if (ret != IDYES)
304 op->req->fAnyOperationsAborted = TRUE;
306 return ret == IDYES;
309 BOOL SHELL_ConfirmYesNoW(HWND hWnd, int nKindOfDialog, LPCWSTR szDir)
311 return SHELL_ConfirmDialogW(hWnd, nKindOfDialog, szDir, NULL);
314 static DWORD SHELL32_AnsiToUnicodeBuf(LPCSTR aPath, LPWSTR *wPath, DWORD minChars)
316 DWORD len = MultiByteToWideChar(CP_ACP, 0, aPath, -1, NULL, 0);
318 if (len < minChars)
319 len = minChars;
321 *wPath = HeapAlloc(GetProcessHeap(), 0, len * sizeof(WCHAR));
322 if (*wPath)
324 MultiByteToWideChar(CP_ACP, 0, aPath, -1, *wPath, len);
325 return NO_ERROR;
327 return E_OUTOFMEMORY;
330 static void SHELL32_FreeUnicodeBuf(LPWSTR wPath)
332 HeapFree(GetProcessHeap(), 0, wPath);
335 HRESULT WINAPI SHIsFileAvailableOffline(LPCWSTR path, LPDWORD status)
337 FIXME("(%s, %p) stub\n", debugstr_w(path), status);
338 return E_FAIL;
341 /**************************************************************************
342 * SHELL_DeleteDirectory() [internal]
344 * Asks for confirmation when bShowUI is true and deletes the directory and
345 * all its subdirectories and files if necessary.
347 static BOOL SHELL_DeleteDirectoryW(HWND hwnd, LPCWSTR pszDir, BOOL bShowUI)
349 BOOL ret = TRUE;
350 HANDLE hFind;
351 WIN32_FIND_DATAW wfd;
352 WCHAR szTemp[MAX_PATH];
354 /* Make sure the directory exists before eventually prompting the user */
355 PathCombineW(szTemp, pszDir, wWildcardFile);
356 hFind = FindFirstFileW(szTemp, &wfd);
357 if (hFind == INVALID_HANDLE_VALUE)
358 return FALSE;
360 if (!bShowUI || (ret = SHELL_ConfirmDialogW(hwnd, ASK_DELETE_FOLDER, pszDir, NULL)))
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) == ERROR_SUCCESS);
371 } while (ret && FindNextFileW(hFind, &wfd));
373 FindClose(hFind);
374 if (ret)
375 ret = (SHNotifyRemoveDirectoryW(pszDir) == ERROR_SUCCESS);
376 return ret;
379 /**************************************************************************
380 * Win32CreateDirectory [SHELL32.93]
382 * Creates a directory. Also triggers a change notify if one exists.
384 * PARAMS
385 * path [I] path to directory to create
387 * RETURNS
388 * TRUE if successful, FALSE otherwise
390 * NOTES
391 * Verified on Win98 / IE 5 (SHELL32 4.72, March 1999 build) to be ANSI.
392 * This is Unicode on NT/2000
394 static DWORD SHNotifyCreateDirectoryA(LPCSTR path, LPSECURITY_ATTRIBUTES sec)
396 LPWSTR wPath;
397 DWORD retCode;
399 TRACE("(%s, %p)\n", debugstr_a(path), sec);
401 retCode = SHELL32_AnsiToUnicodeBuf(path, &wPath, 0);
402 if (!retCode)
404 retCode = SHNotifyCreateDirectoryW(wPath, sec);
405 SHELL32_FreeUnicodeBuf(wPath);
407 return retCode;
410 /**********************************************************************/
412 static DWORD SHNotifyCreateDirectoryW(LPCWSTR path, LPSECURITY_ATTRIBUTES sec)
414 TRACE("(%s, %p)\n", debugstr_w(path), sec);
416 if (CreateDirectoryW(path, sec))
418 SHChangeNotify(SHCNE_MKDIR, SHCNF_PATHW, path, NULL);
419 return ERROR_SUCCESS;
421 return GetLastError();
424 /**********************************************************************/
426 BOOL WINAPI Win32CreateDirectoryAW(LPCVOID path, LPSECURITY_ATTRIBUTES sec)
428 if (SHELL_OsIsUnicode())
429 return (SHNotifyCreateDirectoryW(path, sec) == ERROR_SUCCESS);
430 return (SHNotifyCreateDirectoryA(path, sec) == ERROR_SUCCESS);
433 /************************************************************************
434 * Win32RemoveDirectory [SHELL32.94]
436 * Deletes a directory. Also triggers a change notify if one exists.
438 * PARAMS
439 * path [I] path to directory to delete
441 * RETURNS
442 * TRUE if successful, FALSE otherwise
444 * NOTES
445 * Verified on Win98 / IE 5 (SHELL32 4.72, March 1999 build) to be ANSI.
446 * This is Unicode on NT/2000
448 static DWORD SHNotifyRemoveDirectoryA(LPCSTR path)
450 LPWSTR wPath;
451 DWORD retCode;
453 TRACE("(%s)\n", debugstr_a(path));
455 retCode = SHELL32_AnsiToUnicodeBuf(path, &wPath, 0);
456 if (!retCode)
458 retCode = SHNotifyRemoveDirectoryW(wPath);
459 SHELL32_FreeUnicodeBuf(wPath);
461 return retCode;
464 /***********************************************************************/
466 static DWORD SHNotifyRemoveDirectoryW(LPCWSTR path)
468 BOOL ret;
469 TRACE("(%s)\n", debugstr_w(path));
471 ret = RemoveDirectoryW(path);
472 if (!ret)
474 /* Directory may be write protected */
475 DWORD dwAttr = GetFileAttributesW(path);
476 if (IsAttrib(dwAttr, FILE_ATTRIBUTE_READONLY))
477 if (SetFileAttributesW(path, dwAttr & ~FILE_ATTRIBUTE_READONLY))
478 ret = RemoveDirectoryW(path);
480 if (ret)
482 SHChangeNotify(SHCNE_RMDIR, SHCNF_PATHW, path, NULL);
483 return ERROR_SUCCESS;
485 return GetLastError();
488 /***********************************************************************/
490 BOOL WINAPI Win32RemoveDirectoryAW(LPCVOID path)
492 if (SHELL_OsIsUnicode())
493 return (SHNotifyRemoveDirectoryW(path) == ERROR_SUCCESS);
494 return (SHNotifyRemoveDirectoryA(path) == ERROR_SUCCESS);
497 /************************************************************************
498 * Win32DeleteFile [SHELL32.164]
500 * Deletes a file. Also triggers a change notify if one exists.
502 * PARAMS
503 * path [I] path to file to delete
505 * RETURNS
506 * TRUE if successful, FALSE otherwise
508 * NOTES
509 * Verified on Win98 / IE 5 (SHELL32 4.72, March 1999 build) to be ANSI.
510 * This is Unicode on NT/2000
512 static DWORD SHNotifyDeleteFileA(LPCSTR path)
514 LPWSTR wPath;
515 DWORD retCode;
517 TRACE("(%s)\n", debugstr_a(path));
519 retCode = SHELL32_AnsiToUnicodeBuf(path, &wPath, 0);
520 if (!retCode)
522 retCode = SHNotifyDeleteFileW(wPath);
523 SHELL32_FreeUnicodeBuf(wPath);
525 return retCode;
528 /***********************************************************************/
530 static DWORD SHNotifyDeleteFileW(LPCWSTR path)
532 BOOL ret;
534 TRACE("(%s)\n", debugstr_w(path));
536 ret = DeleteFileW(path);
537 if (!ret)
539 /* File may be write protected or a system file */
540 DWORD dwAttr = GetFileAttributesW(path);
541 if (IsAttrib(dwAttr, FILE_ATTRIBUTE_READONLY | FILE_ATTRIBUTE_SYSTEM))
542 if (SetFileAttributesW(path, dwAttr & ~(FILE_ATTRIBUTE_READONLY | FILE_ATTRIBUTE_SYSTEM)))
543 ret = DeleteFileW(path);
545 if (ret)
547 SHChangeNotify(SHCNE_DELETE, SHCNF_PATHW, path, NULL);
548 return ERROR_SUCCESS;
550 return GetLastError();
553 /***********************************************************************/
555 DWORD WINAPI Win32DeleteFileAW(LPCVOID path)
557 if (SHELL_OsIsUnicode())
558 return (SHNotifyDeleteFileW(path) == ERROR_SUCCESS);
559 return (SHNotifyDeleteFileA(path) == ERROR_SUCCESS);
562 /************************************************************************
563 * SHNotifyMoveFile [internal]
565 * Moves a file. Also triggers a change notify if one exists.
567 * PARAMS
568 * src [I] path to source file to move
569 * dest [I] path to target file to move to
571 * RETURNS
572 * ERORR_SUCCESS if successful
574 static DWORD SHNotifyMoveFileW(LPCWSTR src, LPCWSTR dest)
576 BOOL ret;
578 TRACE("(%s %s)\n", debugstr_w(src), debugstr_w(dest));
580 ret = MoveFileExW(src, dest, MOVEFILE_REPLACE_EXISTING);
582 /* MOVEFILE_REPLACE_EXISTING fails with dirs, so try MoveFile */
583 if (!ret)
584 ret = MoveFileW(src, dest);
586 if (!ret)
588 DWORD dwAttr;
590 dwAttr = SHFindAttrW(dest, FALSE);
591 if (INVALID_FILE_ATTRIBUTES == dwAttr)
593 /* Source file may be write protected or a system file */
594 dwAttr = GetFileAttributesW(src);
595 if (IsAttrib(dwAttr, FILE_ATTRIBUTE_READONLY | FILE_ATTRIBUTE_SYSTEM))
596 if (SetFileAttributesW(src, dwAttr & ~(FILE_ATTRIBUTE_READONLY | FILE_ATTRIBUTE_SYSTEM)))
597 ret = MoveFileW(src, dest);
600 if (ret)
602 SHChangeNotify(SHCNE_RENAMEITEM, SHCNF_PATHW, src, dest);
603 return ERROR_SUCCESS;
605 return GetLastError();
608 /************************************************************************
609 * SHNotifyCopyFile [internal]
611 * Copies a file. Also triggers a change notify if one exists.
613 * PARAMS
614 * src [I] path to source file to move
615 * dest [I] path to target file to move to
616 * bFailIfExists [I] if TRUE, the target file will not be overwritten if
617 * a file with this name already exists
619 * RETURNS
620 * ERROR_SUCCESS if successful
622 static DWORD SHNotifyCopyFileW(LPCWSTR src, LPCWSTR dest, BOOL bFailIfExists)
624 BOOL ret;
625 DWORD attribs;
627 TRACE("(%s %s %s)\n", debugstr_w(src), debugstr_w(dest), bFailIfExists ? "failIfExists" : "");
629 /* Destination file may already exist with read only attribute */
630 attribs = GetFileAttributesW(dest);
631 if (IsAttrib(attribs, FILE_ATTRIBUTE_READONLY))
632 SetFileAttributesW(dest, attribs & ~FILE_ATTRIBUTE_READONLY);
634 ret = CopyFileW(src, dest, bFailIfExists);
635 if (ret)
637 SHChangeNotify(SHCNE_CREATE, SHCNF_PATHW, dest, NULL);
638 return ERROR_SUCCESS;
641 return GetLastError();
644 /*************************************************************************
645 * SHCreateDirectory [SHELL32.165]
647 * This function creates a file system folder whose fully qualified path is
648 * given by path. If one or more of the intermediate folders do not exist,
649 * they will be created as well.
651 * PARAMS
652 * hWnd [I]
653 * path [I] path of directory to create
655 * RETURNS
656 * ERROR_SUCCESS or one of the following values:
657 * ERROR_BAD_PATHNAME if the path is relative
658 * ERROR_FILE_EXISTS when a file with that name exists
659 * ERROR_PATH_NOT_FOUND can't find the path, probably invalid
660 * ERROR_INVALID_NAME if the path contains invalid chars
661 * ERROR_ALREADY_EXISTS when the directory already exists
662 * ERROR_FILENAME_EXCED_RANGE if the filename was to long to process
664 * NOTES
665 * exported by ordinal
666 * Win9x exports ANSI
667 * WinNT/2000 exports Unicode
669 DWORD WINAPI SHCreateDirectory(HWND hWnd, LPCVOID path)
671 if (SHELL_OsIsUnicode())
672 return SHCreateDirectoryExW(hWnd, path, NULL);
673 return SHCreateDirectoryExA(hWnd, path, NULL);
676 /*************************************************************************
677 * SHCreateDirectoryExA [SHELL32.@]
679 * This function creates a file system folder whose fully qualified path is
680 * given by path. If one or more of the intermediate folders do not exist,
681 * they will be created as well.
683 * PARAMS
684 * hWnd [I]
685 * path [I] path of directory to create
686 * sec [I] security attributes to use or NULL
688 * RETURNS
689 * ERROR_SUCCESS or one of the following values:
690 * ERROR_BAD_PATHNAME or ERROR_PATH_NOT_FOUND if the path is relative
691 * ERROR_INVALID_NAME if the path contains invalid chars
692 * ERROR_FILE_EXISTS when a file with that name exists
693 * ERROR_ALREADY_EXISTS when the directory already exists
694 * ERROR_FILENAME_EXCED_RANGE if the filename was to long to process
696 * FIXME: Not implemented yet;
697 * SHCreateDirectoryEx also verifies that the files in the directory will be visible
698 * if the path is a network path to deal with network drivers which might have a limited
699 * but unknown maximum path length. If not:
701 * If hWnd is set to a valid window handle, a message box is displayed warning
702 * the user that the files may not be accessible. If the user chooses not to
703 * proceed, the function returns ERROR_CANCELLED.
705 * If hWnd is set to NULL, no user interface is displayed and the function
706 * returns ERROR_CANCELLED.
708 int WINAPI SHCreateDirectoryExA(HWND hWnd, LPCSTR path, LPSECURITY_ATTRIBUTES sec)
710 LPWSTR wPath;
711 DWORD retCode;
713 TRACE("(%s, %p)\n", debugstr_a(path), sec);
715 retCode = SHELL32_AnsiToUnicodeBuf(path, &wPath, 0);
716 if (!retCode)
718 retCode = SHCreateDirectoryExW(hWnd, wPath, sec);
719 SHELL32_FreeUnicodeBuf(wPath);
721 return retCode;
724 /*************************************************************************
725 * SHCreateDirectoryExW [SHELL32.@]
727 * See SHCreateDirectoryExA.
729 int WINAPI SHCreateDirectoryExW(HWND hWnd, LPCWSTR path, LPSECURITY_ATTRIBUTES sec)
731 int ret = ERROR_BAD_PATHNAME;
732 TRACE("(%p, %s, %p)\n", hWnd, debugstr_w(path), sec);
734 if (PathIsRelativeW(path))
736 SetLastError(ret);
738 else
740 ret = SHNotifyCreateDirectoryW(path, sec);
741 /* Refuse to work on certain error codes before trying to create directories recursively */
742 if (ret != ERROR_SUCCESS &&
743 ret != ERROR_FILE_EXISTS &&
744 ret != ERROR_ALREADY_EXISTS &&
745 ret != ERROR_FILENAME_EXCED_RANGE)
747 WCHAR *pEnd, *pSlash, szTemp[MAX_PATH + 1]; /* extra for PathAddBackslash() */
749 lstrcpynW(szTemp, path, MAX_PATH);
750 pEnd = PathAddBackslashW(szTemp);
751 pSlash = szTemp + 3;
753 while (*pSlash)
755 while (*pSlash && *pSlash != '\\') pSlash++;
756 if (*pSlash)
758 *pSlash = 0; /* terminate path at separator */
760 ret = SHNotifyCreateDirectoryW(szTemp, pSlash + 1 == pEnd ? sec : NULL);
762 *pSlash++ = '\\'; /* put the separator back */
766 if (ret && hWnd && (ERROR_CANCELLED != ret))
768 /* We failed and should show a dialog box */
769 FIXME("Show system error message, creating path %s, failed with error %d\n", debugstr_w(path), ret);
770 ret = ERROR_CANCELLED; /* Error has been already presented to user (not really yet!) */
773 return ret;
776 /*************************************************************************
777 * SHFindAttrW [internal]
779 * Get the Attributes for a file or directory. The difference to GetAttributes()
780 * is that this function will also work for paths containing wildcard characters
781 * in its filename.
783 * PARAMS
784 * path [I] path of directory or file to check
785 * fileOnly [I] TRUE if only files should be found
787 * RETURNS
788 * INVALID_FILE_ATTRIBUTES if the path does not exist, the actual attributes of
789 * the first file or directory found otherwise
791 static DWORD SHFindAttrW(LPCWSTR pName, BOOL fileOnly)
793 WIN32_FIND_DATAW wfd;
794 BOOL b_FileMask = fileOnly && (NULL != StrPBrkW(pName, wWildcardChars));
795 DWORD dwAttr = INVALID_FILE_ATTRIBUTES;
796 HANDLE hFind = FindFirstFileW(pName, &wfd);
798 TRACE("%s %d\n", debugstr_w(pName), fileOnly);
799 if (INVALID_HANDLE_VALUE != hFind)
803 if (b_FileMask && IsAttribDir(wfd.dwFileAttributes))
804 continue;
805 dwAttr = wfd.dwFileAttributes;
806 break;
808 while (FindNextFileW(hFind, &wfd));
809 FindClose(hFind);
811 return dwAttr;
814 /*************************************************************************
816 * SHNameTranslate HelperFunction for SHFileOperationA
818 * Translates a list of 0 terminated ASCII strings into Unicode. If *wString
819 * is NULL, only the necessary size of the string is determined and returned,
820 * otherwise the ASCII strings are copied into it and the buffer is increased
821 * to point to the location after the final 0 termination char.
823 static DWORD SHNameTranslate(LPWSTR* wString, LPCWSTR* pWToFrom, BOOL more)
825 DWORD size = 0, aSize = 0;
826 LPCSTR aString = (LPCSTR)*pWToFrom;
828 if (aString)
832 size = lstrlenA(aString) + 1;
833 aSize += size;
834 aString += size;
835 } while ((size != 1) && more);
836 /* The two sizes might be different in the case of multibyte chars */
837 size = MultiByteToWideChar(CP_ACP, 0, (LPCSTR)*pWToFrom, aSize, *wString, 0);
838 if (*wString) /* only in the second loop */
840 MultiByteToWideChar(CP_ACP, 0, (LPCSTR)*pWToFrom, aSize, *wString, size);
841 *pWToFrom = *wString;
842 *wString += size;
845 return size;
847 /*************************************************************************
848 * SHFileOperationA [SHELL32.@]
850 * Function to copy, move, delete and create one or more files with optional
851 * user prompts.
853 * PARAMS
854 * lpFileOp [I/O] pointer to a structure containing all the necessary information
856 * RETURNS
857 * Success: ERROR_SUCCESS.
858 * Failure: ERROR_CANCELLED.
860 * NOTES
861 * exported by name
863 int WINAPI SHFileOperationA(LPSHFILEOPSTRUCTA lpFileOp)
865 SHFILEOPSTRUCTW nFileOp = *((LPSHFILEOPSTRUCTW)lpFileOp);
866 int retCode = 0;
867 DWORD size;
868 LPWSTR ForFree = NULL, /* we change wString in SHNameTranslate and can't use it for freeing */
869 wString = NULL; /* we change this in SHNameTranslate */
871 TRACE("\n");
872 if (FO_DELETE == (nFileOp.wFunc & FO_MASK))
873 nFileOp.pTo = NULL; /* we need a NULL or a valid pointer for translation */
874 if (!(nFileOp.fFlags & FOF_SIMPLEPROGRESS))
875 nFileOp.lpszProgressTitle = NULL; /* we need a NULL or a valid pointer for translation */
876 while (1) /* every loop calculate size, second translate also, if we have storage for this */
878 size = SHNameTranslate(&wString, &nFileOp.lpszProgressTitle, FALSE); /* no loop */
879 size += SHNameTranslate(&wString, &nFileOp.pFrom, TRUE); /* internal loop */
880 size += SHNameTranslate(&wString, &nFileOp.pTo, TRUE); /* internal loop */
882 if (ForFree)
884 retCode = SHFileOperationW(&nFileOp);
885 HeapFree(GetProcessHeap(), 0, ForFree); /* we cannot use wString, it was changed */
886 break;
888 else
890 wString = ForFree = HeapAlloc(GetProcessHeap(), 0, size * sizeof(WCHAR));
891 if (ForFree) continue;
892 retCode = ERROR_OUTOFMEMORY;
893 nFileOp.fAnyOperationsAborted = TRUE;
894 SetLastError(retCode);
895 return retCode;
899 lpFileOp->hNameMappings = nFileOp.hNameMappings;
900 lpFileOp->fAnyOperationsAborted = nFileOp.fAnyOperationsAborted;
901 return retCode;
904 #define ERROR_SHELL_INTERNAL_FILE_NOT_FOUND 1026
906 typedef struct
908 DWORD attributes;
909 LPWSTR szDirectory;
910 LPWSTR szFilename;
911 LPWSTR szFullPath;
912 BOOL bFromWildcard;
913 BOOL bFromRelative;
914 BOOL bExists;
915 } FILE_ENTRY;
917 typedef struct
919 FILE_ENTRY *feFiles;
920 DWORD num_alloc;
921 DWORD dwNumFiles;
922 BOOL bAnyFromWildcard;
923 BOOL bAnyDirectories;
924 BOOL bAnyDontExist;
925 } FILE_LIST;
928 static inline void grow_list(FILE_LIST *list)
930 FILE_ENTRY *new = HeapReAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, list->feFiles,
931 list->num_alloc * 2 * sizeof(*new) );
932 list->feFiles = new;
933 list->num_alloc *= 2;
936 /* adds a file to the FILE_ENTRY struct
938 static void add_file_to_entry(FILE_ENTRY *feFile, LPCWSTR szFile)
940 DWORD dwLen = lstrlenW(szFile) + 1;
941 LPCWSTR ptr;
943 feFile->szFullPath = HeapAlloc(GetProcessHeap(), 0, dwLen * sizeof(WCHAR));
944 lstrcpyW(feFile->szFullPath, szFile);
946 ptr = StrRChrW(szFile, NULL, '\\');
947 if (ptr)
949 dwLen = ptr - szFile + 1;
950 feFile->szDirectory = HeapAlloc(GetProcessHeap(), 0, dwLen * sizeof(WCHAR));
951 lstrcpynW(feFile->szDirectory, szFile, dwLen);
953 dwLen = lstrlenW(feFile->szFullPath) - dwLen + 1;
954 feFile->szFilename = HeapAlloc(GetProcessHeap(), 0, dwLen * sizeof(WCHAR));
955 lstrcpyW(feFile->szFilename, ptr + 1); /* skip over backslash */
957 feFile->bFromWildcard = FALSE;
960 static LPWSTR wildcard_to_file(LPCWSTR szWildCard, LPCWSTR szFileName)
962 LPCWSTR ptr;
963 LPWSTR szFullPath;
964 DWORD dwDirLen, dwFullLen;
966 ptr = StrRChrW(szWildCard, NULL, '\\');
967 dwDirLen = ptr - szWildCard + 1;
969 dwFullLen = dwDirLen + lstrlenW(szFileName) + 1;
970 szFullPath = HeapAlloc(GetProcessHeap(), 0, dwFullLen * sizeof(WCHAR));
972 lstrcpynW(szFullPath, szWildCard, dwDirLen + 1);
973 lstrcatW(szFullPath, szFileName);
975 return szFullPath;
978 static void parse_wildcard_files(FILE_LIST *flList, LPCWSTR szFile, LPDWORD pdwListIndex)
980 WIN32_FIND_DATAW wfd;
981 HANDLE hFile = FindFirstFileW(szFile, &wfd);
982 FILE_ENTRY *file;
983 LPWSTR szFullPath;
984 BOOL res;
986 if (hFile == INVALID_HANDLE_VALUE) return;
988 for (res = TRUE; res; res = FindNextFileW(hFile, &wfd))
990 if (IsDotDir(wfd.cFileName)) continue;
991 if (*pdwListIndex >= flList->num_alloc) grow_list( flList );
992 szFullPath = wildcard_to_file(szFile, wfd.cFileName);
993 file = &flList->feFiles[(*pdwListIndex)++];
994 add_file_to_entry(file, szFullPath);
995 file->bFromWildcard = TRUE;
996 file->attributes = wfd.dwFileAttributes;
997 if (IsAttribDir(file->attributes)) flList->bAnyDirectories = TRUE;
998 HeapFree(GetProcessHeap(), 0, szFullPath);
1001 FindClose(hFile);
1004 /* takes the null-separated file list and fills out the FILE_LIST */
1005 static HRESULT parse_file_list(FILE_LIST *flList, LPCWSTR szFiles)
1007 LPCWSTR ptr = szFiles;
1008 WCHAR szCurFile[MAX_PATH];
1009 DWORD i = 0;
1011 if (!szFiles)
1012 return ERROR_INVALID_PARAMETER;
1014 flList->bAnyFromWildcard = FALSE;
1015 flList->bAnyDirectories = FALSE;
1016 flList->bAnyDontExist = FALSE;
1017 flList->num_alloc = 32;
1018 flList->dwNumFiles = 0;
1020 /* empty list */
1021 if (!szFiles[0])
1022 return ERROR_ACCESS_DENIED;
1024 flList->feFiles = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY,
1025 flList->num_alloc * sizeof(FILE_ENTRY));
1027 while (*ptr)
1029 if (i >= flList->num_alloc) grow_list( flList );
1031 /* change relative to absolute path */
1032 if (PathIsRelativeW(ptr))
1034 GetCurrentDirectoryW(MAX_PATH, szCurFile);
1035 PathCombineW(szCurFile, szCurFile, ptr);
1036 flList->feFiles[i].bFromRelative = TRUE;
1038 else
1040 lstrcpyW(szCurFile, ptr);
1041 flList->feFiles[i].bFromRelative = FALSE;
1044 /* parse wildcard files if they are in the filename */
1045 if (StrPBrkW(szCurFile, wWildcardChars))
1047 parse_wildcard_files(flList, szCurFile, &i);
1048 flList->bAnyFromWildcard = TRUE;
1049 i--;
1051 else
1053 FILE_ENTRY *file = &flList->feFiles[i];
1054 add_file_to_entry(file, szCurFile);
1055 file->attributes = GetFileAttributesW( file->szFullPath );
1056 file->bExists = (file->attributes != INVALID_FILE_ATTRIBUTES);
1057 if (!file->bExists) flList->bAnyDontExist = TRUE;
1058 if (IsAttribDir(file->attributes)) flList->bAnyDirectories = TRUE;
1061 /* advance to the next string */
1062 ptr += lstrlenW(ptr) + 1;
1063 i++;
1065 flList->dwNumFiles = i;
1067 return S_OK;
1070 /* free the FILE_LIST */
1071 static void destroy_file_list(FILE_LIST *flList)
1073 DWORD i;
1075 if (!flList || !flList->feFiles)
1076 return;
1078 for (i = 0; i < flList->dwNumFiles; i++)
1080 HeapFree(GetProcessHeap(), 0, flList->feFiles[i].szDirectory);
1081 HeapFree(GetProcessHeap(), 0, flList->feFiles[i].szFilename);
1082 HeapFree(GetProcessHeap(), 0, flList->feFiles[i].szFullPath);
1085 HeapFree(GetProcessHeap(), 0, flList->feFiles);
1088 static void copy_dir_to_dir(FILE_OPERATION *op, const FILE_ENTRY *feFrom, LPCWSTR szDestPath)
1090 WCHAR szFrom[MAX_PATH], szTo[MAX_PATH];
1091 SHFILEOPSTRUCTW fileOp;
1093 static const WCHAR wildCardFiles[] = {'*','.','*',0};
1095 if (IsDotDir(feFrom->szFilename))
1096 return;
1098 if (PathFileExistsW(szDestPath))
1099 PathCombineW(szTo, szDestPath, feFrom->szFilename);
1100 else
1101 lstrcpyW(szTo, szDestPath);
1103 if (!(op->req->fFlags & FOF_NOCONFIRMATION) && PathFileExistsW(szTo)) {
1104 if (!SHELL_ConfirmDialogW(op->req->hwnd, ASK_OVERWRITE_FOLDER, feFrom->szFilename, op))
1106 /* Vista returns an ERROR_CANCELLED even if user pressed "No" */
1107 if (!op->bManyItems)
1108 op->bCancelled = TRUE;
1109 return;
1113 szTo[lstrlenW(szTo) + 1] = '\0';
1114 SHNotifyCreateDirectoryW(szTo, NULL);
1116 PathCombineW(szFrom, feFrom->szFullPath, wildCardFiles);
1117 szFrom[lstrlenW(szFrom) + 1] = '\0';
1119 fileOp = *op->req;
1120 fileOp.pFrom = szFrom;
1121 fileOp.pTo = szTo;
1122 fileOp.fFlags &= ~FOF_MULTIDESTFILES; /* we know we're copying to one dir */
1124 /* Don't ask the user about overwriting files when he accepted to overwrite the
1125 folder. FIXME: this is not exactly what Windows does - e.g. there would be
1126 an additional confirmation for a nested folder */
1127 fileOp.fFlags |= FOF_NOCONFIRMATION;
1129 SHFileOperationW(&fileOp);
1132 static BOOL copy_file_to_file(FILE_OPERATION *op, const WCHAR *szFrom, const WCHAR *szTo)
1134 if (!(op->req->fFlags & FOF_NOCONFIRMATION) && PathFileExistsW(szTo))
1136 if (!SHELL_ConfirmDialogW(op->req->hwnd, ASK_OVERWRITE_FILE, PathFindFileNameW(szTo), op))
1137 return 0;
1140 return SHNotifyCopyFileW(szFrom, szTo, FALSE) == 0;
1143 /* copy a file or directory to another directory */
1144 static void copy_to_dir(FILE_OPERATION *op, const FILE_ENTRY *feFrom, const FILE_ENTRY *feTo)
1146 if (!PathFileExistsW(feTo->szFullPath))
1147 SHNotifyCreateDirectoryW(feTo->szFullPath, NULL);
1149 if (IsAttribFile(feFrom->attributes))
1151 WCHAR szDestPath[MAX_PATH];
1153 PathCombineW(szDestPath, feTo->szFullPath, feFrom->szFilename);
1154 copy_file_to_file(op, feFrom->szFullPath, szDestPath);
1156 else if (!(op->req->fFlags & FOF_FILESONLY && feFrom->bFromWildcard))
1157 copy_dir_to_dir(op, feFrom, feTo->szFullPath);
1160 static void create_dest_dirs(LPCWSTR szDestDir)
1162 WCHAR dir[MAX_PATH];
1163 LPCWSTR ptr = StrChrW(szDestDir, '\\');
1165 /* make sure all directories up to last one are created */
1166 while (ptr && (ptr = StrChrW(ptr + 1, '\\')))
1168 lstrcpynW(dir, szDestDir, ptr - szDestDir + 1);
1170 if (!PathFileExistsW(dir))
1171 SHNotifyCreateDirectoryW(dir, NULL);
1174 /* create last directory */
1175 if (!PathFileExistsW(szDestDir))
1176 SHNotifyCreateDirectoryW(szDestDir, NULL);
1179 /* the FO_COPY operation */
1180 static HRESULT copy_files(FILE_OPERATION *op, const FILE_LIST *flFrom, FILE_LIST *flTo)
1182 DWORD i;
1183 const FILE_ENTRY *entryToCopy;
1184 const FILE_ENTRY *fileDest = &flTo->feFiles[0];
1186 if (flFrom->bAnyDontExist)
1187 return ERROR_SHELL_INTERNAL_FILE_NOT_FOUND;
1189 if (flTo->dwNumFiles == 0)
1191 /* If the destination is empty, SHFileOperation should use the current directory */
1192 WCHAR curdir[MAX_PATH+1];
1194 GetCurrentDirectoryW(MAX_PATH, curdir);
1195 curdir[lstrlenW(curdir)+1] = 0;
1197 destroy_file_list(flTo);
1198 ZeroMemory(flTo, sizeof(FILE_LIST));
1199 parse_file_list(flTo, curdir);
1200 fileDest = &flTo->feFiles[0];
1203 if (op->req->fFlags & FOF_MULTIDESTFILES)
1205 if (flFrom->bAnyFromWildcard)
1206 return ERROR_CANCELLED;
1208 if (flFrom->dwNumFiles != flTo->dwNumFiles)
1210 if (flFrom->dwNumFiles != 1 && !IsAttribDir(fileDest->attributes))
1211 return ERROR_CANCELLED;
1213 /* Free all but the first entry. */
1214 for (i = 1; i < flTo->dwNumFiles; i++)
1216 HeapFree(GetProcessHeap(), 0, flTo->feFiles[i].szDirectory);
1217 HeapFree(GetProcessHeap(), 0, flTo->feFiles[i].szFilename);
1218 HeapFree(GetProcessHeap(), 0, flTo->feFiles[i].szFullPath);
1221 flTo->dwNumFiles = 1;
1223 else if (IsAttribDir(fileDest->attributes))
1225 for (i = 1; i < flTo->dwNumFiles; i++)
1226 if (!IsAttribDir(flTo->feFiles[i].attributes) ||
1227 !IsAttribDir(flFrom->feFiles[i].attributes))
1229 return ERROR_CANCELLED;
1233 else if (flFrom->dwNumFiles != 1)
1235 if (flTo->dwNumFiles != 1 && !IsAttribDir(fileDest->attributes))
1236 return ERROR_CANCELLED;
1238 if (PathFileExistsW(fileDest->szFullPath) &&
1239 IsAttribFile(fileDest->attributes))
1241 return ERROR_CANCELLED;
1244 if (flTo->dwNumFiles == 1 && fileDest->bFromRelative &&
1245 !PathFileExistsW(fileDest->szFullPath))
1247 return ERROR_CANCELLED;
1251 for (i = 0; i < flFrom->dwNumFiles; i++)
1253 entryToCopy = &flFrom->feFiles[i];
1255 if ((op->req->fFlags & FOF_MULTIDESTFILES) &&
1256 flTo->dwNumFiles > 1)
1258 fileDest = &flTo->feFiles[i];
1261 if (IsAttribDir(entryToCopy->attributes) &&
1262 !lstrcmpiW(entryToCopy->szFullPath, fileDest->szDirectory))
1264 return ERROR_SUCCESS;
1267 create_dest_dirs(fileDest->szDirectory);
1269 if (!lstrcmpiW(entryToCopy->szFullPath, fileDest->szFullPath))
1271 if (IsAttribFile(entryToCopy->attributes))
1272 return ERROR_NO_MORE_SEARCH_HANDLES;
1273 else
1274 return ERROR_SUCCESS;
1277 if ((flFrom->dwNumFiles > 1 && flTo->dwNumFiles == 1) ||
1278 IsAttribDir(fileDest->attributes))
1280 copy_to_dir(op, entryToCopy, fileDest);
1282 else if (IsAttribDir(entryToCopy->attributes))
1284 copy_dir_to_dir(op, entryToCopy, fileDest->szFullPath);
1286 else
1288 if (!copy_file_to_file(op, entryToCopy->szFullPath, fileDest->szFullPath))
1290 op->req->fAnyOperationsAborted = TRUE;
1291 return ERROR_CANCELLED;
1295 /* Vista return code. XP would return e.g. ERROR_FILE_NOT_FOUND, ERROR_ALREADY_EXISTS */
1296 if (op->bCancelled)
1297 return ERROR_CANCELLED;
1300 /* Vista return code. On XP if the used pressed "No" for the last item,
1301 * ERROR_ARENA_TRASHED would be returned */
1302 return ERROR_SUCCESS;
1305 static BOOL confirm_delete_list(HWND hWnd, DWORD fFlags, BOOL fTrash, const FILE_LIST *flFrom)
1307 if (flFrom->dwNumFiles > 1)
1309 WCHAR tmp[8];
1310 const WCHAR format[] = {'%','d',0};
1312 wnsprintfW(tmp, sizeof(tmp)/sizeof(tmp[0]), format, flFrom->dwNumFiles);
1313 return SHELL_ConfirmDialogW(hWnd, (fTrash?ASK_TRASH_MULTIPLE_ITEM:ASK_DELETE_MULTIPLE_ITEM), tmp, NULL);
1315 else
1317 const FILE_ENTRY *fileEntry = &flFrom->feFiles[0];
1319 if (IsAttribFile(fileEntry->attributes))
1320 return SHELL_ConfirmDialogW(hWnd, (fTrash?ASK_TRASH_FILE:ASK_DELETE_FILE), fileEntry->szFullPath, NULL);
1321 else if (!(fFlags & FOF_FILESONLY && fileEntry->bFromWildcard))
1322 return SHELL_ConfirmDialogW(hWnd, (fTrash?ASK_TRASH_FOLDER:ASK_DELETE_FOLDER), fileEntry->szFullPath, NULL);
1324 return TRUE;
1327 /* the FO_DELETE operation */
1328 static HRESULT delete_files(LPSHFILEOPSTRUCTW lpFileOp, const FILE_LIST *flFrom)
1330 const FILE_ENTRY *fileEntry;
1331 DWORD i;
1332 BOOL bPathExists;
1333 BOOL bTrash;
1335 if (!flFrom->dwNumFiles)
1336 return ERROR_SUCCESS;
1338 /* Windows also checks only the first item */
1339 bTrash = (lpFileOp->fFlags & FOF_ALLOWUNDO)
1340 && TRASH_CanTrashFile(flFrom->feFiles[0].szFullPath);
1342 if (!(lpFileOp->fFlags & FOF_NOCONFIRMATION) || (!bTrash && lpFileOp->fFlags & FOF_WANTNUKEWARNING))
1343 if (!confirm_delete_list(lpFileOp->hwnd, lpFileOp->fFlags, bTrash, flFrom))
1345 lpFileOp->fAnyOperationsAborted = TRUE;
1346 return 0;
1349 for (i = 0; i < flFrom->dwNumFiles; i++)
1351 bPathExists = TRUE;
1352 fileEntry = &flFrom->feFiles[i];
1354 if (!IsAttribFile(fileEntry->attributes) &&
1355 (lpFileOp->fFlags & FOF_FILESONLY && fileEntry->bFromWildcard))
1356 continue;
1358 if (bTrash)
1360 BOOL bDelete;
1361 if (TRASH_TrashFile(fileEntry->szFullPath))
1362 continue;
1364 /* Note: Windows silently deletes the file in such a situation, we show a dialog */
1365 if (!(lpFileOp->fFlags & FOF_NOCONFIRMATION) || (lpFileOp->fFlags & FOF_WANTNUKEWARNING))
1366 bDelete = SHELL_ConfirmDialogW(lpFileOp->hwnd, ASK_CANT_TRASH_ITEM, fileEntry->szFullPath, NULL);
1367 else
1368 bDelete = TRUE;
1370 if (!bDelete)
1372 lpFileOp->fAnyOperationsAborted = TRUE;
1373 break;
1377 /* delete the file or directory */
1378 if (IsAttribFile(fileEntry->attributes))
1379 bPathExists = DeleteFileW(fileEntry->szFullPath);
1380 else
1381 bPathExists = SHELL_DeleteDirectoryW(lpFileOp->hwnd, fileEntry->szFullPath, FALSE);
1383 if (!bPathExists)
1384 return ERROR_PATH_NOT_FOUND;
1387 return ERROR_SUCCESS;
1390 static void move_dir_to_dir(LPSHFILEOPSTRUCTW lpFileOp, const FILE_ENTRY *feFrom, LPCWSTR szDestPath)
1392 WCHAR szFrom[MAX_PATH], szTo[MAX_PATH];
1393 SHFILEOPSTRUCTW fileOp;
1395 static const WCHAR wildCardFiles[] = {'*','.','*',0};
1397 if (IsDotDir(feFrom->szFilename))
1398 return;
1400 SHNotifyCreateDirectoryW(szDestPath, NULL);
1402 PathCombineW(szFrom, feFrom->szFullPath, wildCardFiles);
1403 szFrom[lstrlenW(szFrom) + 1] = '\0';
1405 lstrcpyW(szTo, szDestPath);
1406 szTo[lstrlenW(szDestPath) + 1] = '\0';
1408 fileOp = *lpFileOp;
1409 fileOp.pFrom = szFrom;
1410 fileOp.pTo = szTo;
1412 SHFileOperationW(&fileOp);
1415 /* moves a file or directory to another directory */
1416 static void move_to_dir(LPSHFILEOPSTRUCTW lpFileOp, const FILE_ENTRY *feFrom, const FILE_ENTRY *feTo)
1418 WCHAR szDestPath[MAX_PATH];
1420 PathCombineW(szDestPath, feTo->szFullPath, feFrom->szFilename);
1422 if (IsAttribFile(feFrom->attributes))
1423 SHNotifyMoveFileW(feFrom->szFullPath, szDestPath);
1424 else if (!(lpFileOp->fFlags & FOF_FILESONLY && feFrom->bFromWildcard))
1425 move_dir_to_dir(lpFileOp, feFrom, szDestPath);
1428 /* the FO_MOVE operation */
1429 static HRESULT move_files(LPSHFILEOPSTRUCTW lpFileOp, const FILE_LIST *flFrom, const FILE_LIST *flTo)
1431 DWORD i;
1432 const FILE_ENTRY *entryToMove;
1433 const FILE_ENTRY *fileDest;
1435 if (!flFrom->dwNumFiles || !flTo->dwNumFiles)
1436 return ERROR_CANCELLED;
1438 if (!(lpFileOp->fFlags & FOF_MULTIDESTFILES) &&
1439 flTo->dwNumFiles > 1 && flFrom->dwNumFiles > 1)
1441 return ERROR_CANCELLED;
1444 if (!(lpFileOp->fFlags & FOF_MULTIDESTFILES) &&
1445 !flFrom->bAnyDirectories &&
1446 flFrom->dwNumFiles > flTo->dwNumFiles)
1448 return ERROR_CANCELLED;
1451 if (!PathFileExistsW(flTo->feFiles[0].szDirectory))
1452 return ERROR_CANCELLED;
1454 if ((lpFileOp->fFlags & FOF_MULTIDESTFILES) &&
1455 flFrom->dwNumFiles != flTo->dwNumFiles)
1457 return ERROR_CANCELLED;
1460 fileDest = &flTo->feFiles[0];
1461 for (i = 0; i < flFrom->dwNumFiles; i++)
1463 entryToMove = &flFrom->feFiles[i];
1465 if (lpFileOp->fFlags & FOF_MULTIDESTFILES)
1466 fileDest = &flTo->feFiles[i];
1468 if (!PathFileExistsW(fileDest->szDirectory))
1469 return ERROR_CANCELLED;
1471 if (fileDest->bExists && IsAttribDir(fileDest->attributes))
1472 move_to_dir(lpFileOp, entryToMove, fileDest);
1473 else
1474 SHNotifyMoveFileW(entryToMove->szFullPath, fileDest->szFullPath);
1477 return ERROR_SUCCESS;
1480 /* the FO_RENAME files */
1481 static HRESULT rename_files(LPSHFILEOPSTRUCTW lpFileOp, const FILE_LIST *flFrom, const FILE_LIST *flTo)
1483 const FILE_ENTRY *feFrom;
1484 const FILE_ENTRY *feTo;
1486 if (flFrom->dwNumFiles != 1)
1487 return ERROR_GEN_FAILURE;
1489 if (flTo->dwNumFiles != 1)
1490 return ERROR_CANCELLED;
1492 feFrom = &flFrom->feFiles[0];
1493 feTo= &flTo->feFiles[0];
1495 /* fail if destination doesn't exist */
1496 if (!feFrom->bExists)
1497 return ERROR_SHELL_INTERNAL_FILE_NOT_FOUND;
1499 /* fail if destination already exists */
1500 if (feTo->bExists)
1501 return ERROR_ALREADY_EXISTS;
1503 return SHNotifyMoveFileW(feFrom->szFullPath, feTo->szFullPath);
1506 /* alert the user if an unsupported flag is used */
1507 static void check_flags(FILEOP_FLAGS fFlags)
1509 WORD wUnsupportedFlags = FOF_NO_CONNECTED_ELEMENTS |
1510 FOF_NOCOPYSECURITYATTRIBS | FOF_NORECURSEREPARSE |
1511 FOF_RENAMEONCOLLISION | FOF_WANTMAPPINGHANDLE;
1513 if (fFlags & wUnsupportedFlags)
1514 FIXME("Unsupported flags: %04x\n", fFlags);
1517 /*************************************************************************
1518 * SHFileOperationW [SHELL32.@]
1520 * See SHFileOperationA
1522 int WINAPI SHFileOperationW(LPSHFILEOPSTRUCTW lpFileOp)
1524 FILE_OPERATION op;
1525 FILE_LIST flFrom, flTo;
1526 int ret = 0;
1528 if (!lpFileOp)
1529 return ERROR_INVALID_PARAMETER;
1531 check_flags(lpFileOp->fFlags);
1533 ZeroMemory(&flFrom, sizeof(FILE_LIST));
1534 ZeroMemory(&flTo, sizeof(FILE_LIST));
1536 if ((ret = parse_file_list(&flFrom, lpFileOp->pFrom)))
1537 return ret;
1539 if (lpFileOp->wFunc != FO_DELETE)
1540 parse_file_list(&flTo, lpFileOp->pTo);
1542 ZeroMemory(&op, sizeof(op));
1543 op.req = lpFileOp;
1544 op.bManyItems = (flFrom.dwNumFiles > 1);
1546 switch (lpFileOp->wFunc)
1548 case FO_COPY:
1549 ret = copy_files(&op, &flFrom, &flTo);
1550 break;
1551 case FO_DELETE:
1552 ret = delete_files(lpFileOp, &flFrom);
1553 break;
1554 case FO_MOVE:
1555 ret = move_files(lpFileOp, &flFrom, &flTo);
1556 break;
1557 case FO_RENAME:
1558 ret = rename_files(lpFileOp, &flFrom, &flTo);
1559 break;
1560 default:
1561 ret = ERROR_INVALID_PARAMETER;
1562 break;
1565 destroy_file_list(&flFrom);
1567 if (lpFileOp->wFunc != FO_DELETE)
1568 destroy_file_list(&flTo);
1570 if (ret == ERROR_CANCELLED)
1571 lpFileOp->fAnyOperationsAborted = TRUE;
1573 return ret;
1576 #define SHDSA_GetItemCount(hdsa) (*(int*)(hdsa))
1578 /*************************************************************************
1579 * SHFreeNameMappings [shell32.246]
1581 * Free the mapping handle returned by SHFileOperation if FOF_WANTSMAPPINGHANDLE
1582 * was specified.
1584 * PARAMS
1585 * hNameMapping [I] handle to the name mappings used during renaming of files
1587 * RETURNS
1588 * Nothing
1590 void WINAPI SHFreeNameMappings(HANDLE hNameMapping)
1592 if (hNameMapping)
1594 int i = SHDSA_GetItemCount((HDSA)hNameMapping) - 1;
1596 for (; i>= 0; i--)
1598 LPSHNAMEMAPPINGW lp = DSA_GetItemPtr(hNameMapping, i);
1600 SHFree(lp->pszOldPath);
1601 SHFree(lp->pszNewPath);
1603 DSA_Destroy(hNameMapping);
1607 /*************************************************************************
1608 * SheGetDirA [SHELL32.@]
1610 * drive = 0: returns the current directory path
1611 * drive > 0: returns the current directory path of the specified drive
1612 * drive=1 -> A: drive=2 -> B: ...
1613 * returns 0 if successful
1615 DWORD WINAPI SheGetDirA(DWORD drive, LPSTR buffer)
1617 WCHAR org_path[MAX_PATH];
1618 DWORD ret;
1619 char drv_path[3];
1621 /* change current directory to the specified drive */
1622 if (drive) {
1623 strcpy(drv_path, "A:");
1624 drv_path[0] += (char)drive-1;
1626 GetCurrentDirectoryW(MAX_PATH, org_path);
1628 SetCurrentDirectoryA(drv_path);
1631 /* query current directory path of the specified drive */
1632 ret = GetCurrentDirectoryA(MAX_PATH, buffer);
1634 /* back to the original drive */
1635 if (drive)
1636 SetCurrentDirectoryW(org_path);
1638 if (!ret)
1639 return GetLastError();
1641 return 0;
1644 /*************************************************************************
1645 * SheGetDirW [SHELL32.@]
1647 * drive = 0: returns the current directory path
1648 * drive > 0: returns the current directory path of the specified drive
1649 * drive=1 -> A: drive=2 -> B: ...
1650 * returns 0 if successful
1652 DWORD WINAPI SheGetDirW(DWORD drive, LPWSTR buffer)
1654 WCHAR org_path[MAX_PATH];
1655 DWORD ret;
1656 char drv_path[3];
1658 /* change current directory to the specified drive */
1659 if (drive) {
1660 strcpy(drv_path, "A:");
1661 drv_path[0] += (char)drive-1;
1663 GetCurrentDirectoryW(MAX_PATH, org_path);
1665 SetCurrentDirectoryA(drv_path);
1668 /* query current directory path of the specified drive */
1669 ret = GetCurrentDirectoryW(MAX_PATH, buffer);
1671 /* back to the original drive */
1672 if (drive)
1673 SetCurrentDirectoryW(org_path);
1675 if (!ret)
1676 return GetLastError();
1678 return 0;
1681 /*************************************************************************
1682 * SheChangeDirA [SHELL32.@]
1684 * changes the current directory to the specified path
1685 * and returns 0 if successful
1687 DWORD WINAPI SheChangeDirA(LPSTR path)
1689 if (SetCurrentDirectoryA(path))
1690 return 0;
1691 else
1692 return GetLastError();
1695 /*************************************************************************
1696 * SheChangeDirW [SHELL32.@]
1698 * changes the current directory to the specified path
1699 * and returns 0 if successful
1701 DWORD WINAPI SheChangeDirW(LPWSTR path)
1703 if (SetCurrentDirectoryW(path))
1704 return 0;
1705 else
1706 return GetLastError();
1709 /*************************************************************************
1710 * IsNetDrive [SHELL32.66]
1712 BOOL WINAPI IsNetDrive(DWORD drive)
1714 char root[4];
1715 strcpy(root, "A:\\");
1716 root[0] += (char)drive;
1717 return (GetDriveTypeA(root) == DRIVE_REMOTE);
1721 /*************************************************************************
1722 * RealDriveType [SHELL32.524]
1724 INT WINAPI RealDriveType(INT drive, BOOL bQueryNet)
1726 char root[] = "A:\\";
1727 root[0] += (char)drive;
1728 return GetDriveTypeA(root);
1731 /***********************************************************************
1732 * SHPathPrepareForWriteA (SHELL32.@)
1734 HRESULT WINAPI SHPathPrepareForWriteA(HWND hwnd, IUnknown *modless, LPCSTR path, DWORD flags)
1736 WCHAR wpath[MAX_PATH];
1737 MultiByteToWideChar( CP_ACP, 0, path, -1, wpath, MAX_PATH);
1738 return SHPathPrepareForWriteW(hwnd, modless, wpath, flags);
1741 /***********************************************************************
1742 * SHPathPrepareForWriteW (SHELL32.@)
1744 HRESULT WINAPI SHPathPrepareForWriteW(HWND hwnd, IUnknown *modless, LPCWSTR path, DWORD flags)
1746 DWORD res;
1747 DWORD err;
1748 LPCWSTR realpath;
1749 int len;
1750 WCHAR* last_slash;
1751 WCHAR* temppath=NULL;
1753 TRACE("%p %p %s 0x%80x\n", hwnd, modless, debugstr_w(path), flags);
1755 if (flags & ~(SHPPFW_DIRCREATE|SHPPFW_ASKDIRCREATE|SHPPFW_IGNOREFILENAME))
1756 FIXME("unimplemented flags 0x%08x\n", flags);
1758 /* cut off filename if necessary */
1759 if (flags & SHPPFW_IGNOREFILENAME)
1761 last_slash = StrRChrW(path, NULL, '\\');
1762 if (last_slash == NULL)
1763 len = 1;
1764 else
1765 len = last_slash - path + 1;
1766 temppath = HeapAlloc(GetProcessHeap(), 0, len * sizeof(WCHAR));
1767 if (!temppath)
1768 return E_OUTOFMEMORY;
1769 StrCpyNW(temppath, path, len);
1770 realpath = temppath;
1772 else
1774 realpath = path;
1777 /* try to create the directory if asked to */
1778 if (flags & (SHPPFW_DIRCREATE|SHPPFW_ASKDIRCREATE))
1780 if (flags & SHPPFW_ASKDIRCREATE)
1781 FIXME("treating SHPPFW_ASKDIRCREATE as SHPPFW_DIRCREATE\n");
1783 SHCreateDirectoryExW(0, realpath, NULL);
1786 /* check if we can access the directory */
1787 res = GetFileAttributesW(realpath);
1789 HeapFree(GetProcessHeap(), 0, temppath);
1791 if (res == INVALID_FILE_ATTRIBUTES)
1793 err = GetLastError();
1794 if (err == ERROR_FILE_NOT_FOUND)
1795 return HRESULT_FROM_WIN32(ERROR_PATH_NOT_FOUND);
1796 return HRESULT_FROM_WIN32(err);
1798 else if (res & FILE_ATTRIBUTE_DIRECTORY)
1799 return S_OK;
1800 else
1801 return HRESULT_FROM_WIN32(ERROR_DIRECTORY);