Merge from amd64-branch:
[reactos.git] / reactos / dll / win32 / shell32 / shlfileop.c
1 /*
2 * SHFileOperation
3 *
4 * Copyright 2000 Juergen Schmied
5 * Copyright 2002 Andriy Palamarchuk
6 * Copyright 2004 Dietrich Teickner (from Odin)
7 * Copyright 2004 Rolf Kalbermatter
8 *
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.
13 *
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.
18 *
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
22 */
23
24 //#define NO_SHLWAPI_STREAM
25 #include <precomp.h>
26
27
28 WINE_DEFAULT_DEBUG_CHANNEL(shell);
29
30 #define IsAttrib(x, y) ((INVALID_FILE_ATTRIBUTES != (x)) && ((x) & (y)))
31 #define IsAttribFile(x) (!((x) & FILE_ATTRIBUTE_DIRECTORY))
32 #define IsAttribDir(x) IsAttrib(x, FILE_ATTRIBUTE_DIRECTORY)
33 #define IsDotDir(x) ((x[0] == '.') && ((x[1] == 0) || ((x[1] == '.') && (x[2] == 0))))
34
35 #define FO_MASK 0xF
36
37 static const WCHAR wWildcardFile[] = {'*',0};
38 static const WCHAR wWildcardChars[] = {'*','?',0};
39
40 static DWORD SHNotifyCreateDirectoryW(LPCWSTR path, LPSECURITY_ATTRIBUTES sec);
41 static DWORD SHNotifyRemoveDirectoryW(LPCWSTR path);
42 static DWORD SHNotifyDeleteFileW(LPCWSTR path);
43 static DWORD SHNotifyMoveFileW(LPCWSTR src, LPCWSTR dest);
44 static DWORD SHNotifyCopyFileW(LPCWSTR src, LPCWSTR dest, BOOL bFailIfExists);
45 static DWORD SHFindAttrW(LPCWSTR pName, BOOL fileOnly);
46
47 typedef struct
48 {
49 SHFILEOPSTRUCTW *req;
50 DWORD dwYesToAllMask;
51 BOOL bManyItems;
52 BOOL bCancelled;
53 } FILE_OPERATION;
54
55 /* Confirm dialogs with an optional "Yes To All" as used in file operations confirmations
56 */
57 static const WCHAR CONFIRM_MSG_PROP[] = {'W','I','N','E','_','C','O','N','F','I','R','M',0};
58
59 struct confirm_msg_info
60 {
61 LPWSTR lpszText;
62 LPWSTR lpszCaption;
63 HICON hIcon;
64 BOOL bYesToAll;
65 };
66
67 /* as some buttons may be hidden and the dialog height may change we may need
68 * to move the controls */
69 static void confirm_msg_move_button(HWND hDlg, INT iId, INT *xPos, INT yOffset, BOOL bShow)
70 {
71 HWND hButton = GetDlgItem(hDlg, iId);
72 RECT r;
73
74 if (bShow) {
75 POINT pt;
76 int width;
77
78 GetWindowRect(hButton, &r);
79 width = r.right - r.left;
80 pt.x = r.left;
81 pt.y = r.top;
82 ScreenToClient(hDlg, &pt);
83 MoveWindow(hButton, *xPos - width, pt.y - yOffset, width, r.bottom - r.top, FALSE);
84 *xPos -= width + 5;
85 }
86 else
87 ShowWindow(hButton, SW_HIDE);
88 }
89
90 /* Note: we paint the text manually and don't use the static control to make
91 * sure the text has the same height as the one computed in WM_INITDIALOG
92 */
93 static INT_PTR ConfirmMsgBox_Paint(HWND hDlg)
94 {
95 PAINTSTRUCT ps;
96 HFONT hOldFont;
97 RECT r;
98 HDC hdc;
99
100 BeginPaint(hDlg, &ps);
101 hdc = ps.hdc;
102
103 GetClientRect(GetDlgItem(hDlg, IDD_MESSAGE), &r);
104 /* this will remap the rect to dialog coords */
105 MapWindowPoints(GetDlgItem(hDlg, IDD_MESSAGE), hDlg, (LPPOINT)&r, 2);
106 hOldFont = SelectObject(hdc, (HFONT)SendDlgItemMessageW(hDlg, IDD_MESSAGE, WM_GETFONT, 0, 0));
107 DrawTextW(hdc, GetPropW(hDlg, CONFIRM_MSG_PROP), -1, &r, DT_NOPREFIX | DT_PATH_ELLIPSIS | DT_WORDBREAK);
108 SelectObject(hdc, hOldFont);
109 EndPaint(hDlg, &ps);
110 return TRUE;
111 }
112
113 static INT_PTR ConfirmMsgBox_Init(HWND hDlg, LPARAM lParam)
114 {
115 struct confirm_msg_info *info = (struct confirm_msg_info *)lParam;
116 INT xPos, yOffset;
117 int width, height;
118 HFONT hOldFont;
119 HDC hdc;
120 RECT r;
121
122 SetWindowTextW(hDlg, info->lpszCaption);
123 ShowWindow(GetDlgItem(hDlg, IDD_MESSAGE), SW_HIDE);
124 SetPropW(hDlg, CONFIRM_MSG_PROP, info->lpszText);
125 SendDlgItemMessageW(hDlg, IDD_ICON, STM_SETICON, (WPARAM)info->hIcon, 0);
126
127 /* compute the text height and resize the dialog */
128 GetClientRect(GetDlgItem(hDlg, IDD_MESSAGE), &r);
129 hdc = GetDC(hDlg);
130 yOffset = r.bottom;
131 hOldFont = SelectObject(hdc, (HFONT)SendDlgItemMessageW(hDlg, IDD_MESSAGE, WM_GETFONT, 0, 0));
132 DrawTextW(hdc, info->lpszText, -1, &r, DT_NOPREFIX | DT_PATH_ELLIPSIS | DT_WORDBREAK | DT_CALCRECT);
133 SelectObject(hdc, hOldFont);
134 yOffset -= r.bottom;
135 yOffset = min(yOffset, 35); /* don't make the dialog too small */
136 ReleaseDC(hDlg, hdc);
137
138 GetClientRect(hDlg, &r);
139 xPos = r.right - 7;
140 GetWindowRect(hDlg, &r);
141 width = r.right - r.left;
142 height = r.bottom - r.top - yOffset;
143 MoveWindow(hDlg, (GetSystemMetrics(SM_CXSCREEN) - width)/2,
144 (GetSystemMetrics(SM_CYSCREEN) - height)/2, width, height, FALSE);
145
146 confirm_msg_move_button(hDlg, IDCANCEL, &xPos, yOffset, info->bYesToAll);
147 confirm_msg_move_button(hDlg, IDNO, &xPos, yOffset, TRUE);
148 confirm_msg_move_button(hDlg, IDD_YESTOALL, &xPos, yOffset, info->bYesToAll);
149 confirm_msg_move_button(hDlg, IDYES, &xPos, yOffset, TRUE);
150 return TRUE;
151 }
152
153 static INT_PTR CALLBACK ConfirmMsgBoxProc(HWND hDlg, UINT uMsg, WPARAM wParam, LPARAM lParam)
154 {
155 switch (uMsg)
156 {
157 case WM_INITDIALOG:
158 return ConfirmMsgBox_Init(hDlg, lParam);
159 case WM_PAINT:
160 return ConfirmMsgBox_Paint(hDlg);
161 case WM_COMMAND:
162 EndDialog(hDlg, wParam);
163 break;
164 case WM_CLOSE:
165 EndDialog(hDlg, IDCANCEL);
166 break;
167 }
168 return FALSE;
169 }
170
171 int SHELL_ConfirmMsgBox(HWND hWnd, LPWSTR lpszText, LPWSTR lpszCaption, HICON hIcon, BOOL bYesToAll)
172 {
173 static const WCHAR wszTemplate[] = {'S','H','E','L','L','_','Y','E','S','T','O','A','L','L','_','M','S','G','B','O','X',0};
174 struct confirm_msg_info info;
175
176 info.lpszText = lpszText;
177 info.lpszCaption = lpszCaption;
178 info.hIcon = hIcon;
179 info.bYesToAll = bYesToAll;
180 return DialogBoxParamW(shell32_hInstance, wszTemplate, hWnd, ConfirmMsgBoxProc, (LPARAM)&info);
181 }
182
183 /* confirmation dialogs content */
184 typedef struct
185 {
186 HINSTANCE hIconInstance;
187 UINT icon_resource_id;
188 UINT caption_resource_id, text_resource_id;
189 } SHELL_ConfirmIDstruc;
190
191 static BOOL SHELL_ConfirmIDs(int nKindOfDialog, SHELL_ConfirmIDstruc *ids)
192 {
193 ids->hIconInstance = shell32_hInstance;
194 switch (nKindOfDialog) {
195 case ASK_DELETE_FILE:
196 ids->icon_resource_id = IDI_SHELL_CONFIRM_DELETE;
197 ids->caption_resource_id = IDS_DELETEITEM_CAPTION;
198 ids->text_resource_id = IDS_DELETEITEM_TEXT;
199 return TRUE;
200 case ASK_DELETE_FOLDER:
201 ids->icon_resource_id = IDI_SHELL_CONFIRM_DELETE;
202 ids->caption_resource_id = IDS_DELETEFOLDER_CAPTION;
203 ids->text_resource_id = IDS_DELETEITEM_TEXT;
204 return TRUE;
205 case ASK_DELETE_MULTIPLE_ITEM:
206 ids->icon_resource_id = IDI_SHELL_CONFIRM_DELETE;
207 ids->caption_resource_id = IDS_DELETEITEM_CAPTION;
208 ids->text_resource_id = IDS_DELETEMULTIPLE_TEXT;
209 return TRUE;
210 case ASK_TRASH_FILE:
211 ids->icon_resource_id = IDI_SHELL_TRASH_FILE;
212 ids->caption_resource_id = IDS_DELETEITEM_CAPTION;
213 ids->text_resource_id = IDS_TRASHITEM_TEXT;
214 return TRUE;
215 case ASK_TRASH_FOLDER:
216 ids->icon_resource_id = IDI_SHELL_TRASH_FILE;
217 ids->caption_resource_id = IDS_DELETEFOLDER_CAPTION;
218 ids->text_resource_id = IDS_TRASHFOLDER_TEXT;
219 return TRUE;
220 case ASK_TRASH_MULTIPLE_ITEM:
221 ids->icon_resource_id = IDI_SHELL_TRASH_FILE;
222 ids->caption_resource_id = IDS_DELETEITEM_CAPTION;
223 ids->text_resource_id = IDS_TRASHMULTIPLE_TEXT;
224 return TRUE;
225 case ASK_CANT_TRASH_ITEM:
226 ids->icon_resource_id = IDI_SHELL_CONFIRM_DELETE;
227 ids->caption_resource_id = IDS_DELETEITEM_CAPTION;
228 ids->text_resource_id = IDS_CANTTRASH_TEXT;
229 return TRUE;
230 case ASK_DELETE_SELECTED:
231 ids->icon_resource_id = IDI_SHELL_CONFIRM_DELETE;
232 ids->caption_resource_id = IDS_DELETEITEM_CAPTION;
233 ids->text_resource_id = IDS_DELETESELECTED_TEXT;
234 return TRUE;
235 case ASK_OVERWRITE_FILE:
236 ids->hIconInstance = NULL;
237 ids->icon_resource_id = IDI_SHELL_CONFIRM_DELETE;
238 ids->caption_resource_id = IDS_OVERWRITEFILE_CAPTION;
239 ids->text_resource_id = IDS_OVERWRITEFILE_TEXT;
240 return TRUE;
241 case ASK_OVERWRITE_FOLDER:
242 ids->hIconInstance = NULL;
243 ids->icon_resource_id = IDI_SHELL_CONFIRM_DELETE;
244 ids->caption_resource_id = IDS_OVERWRITEFILE_CAPTION;
245 ids->text_resource_id = IDS_OVERWRITEFOLDER_TEXT;
246 return TRUE;
247 default:
248 FIXME(" Unhandled nKindOfDialog %d stub\n", nKindOfDialog);
249 }
250 return FALSE;
251 }
252
253 static BOOL SHELL_ConfirmDialogW(HWND hWnd, int nKindOfDialog, LPCWSTR szDir, FILE_OPERATION *op)
254 {
255 WCHAR szCaption[255], szText[255], szBuffer[MAX_PATH + 256];
256 SHELL_ConfirmIDstruc ids;
257 DWORD_PTR args[1];
258 HICON hIcon;
259 int ret;
260
261 assert(nKindOfDialog >= 0 && nKindOfDialog < 32);
262 if (op && (op->dwYesToAllMask & (1 << nKindOfDialog)))
263 return TRUE;
264
265 if (!SHELL_ConfirmIDs(nKindOfDialog, &ids)) return FALSE;
266
267 LoadStringW(shell32_hInstance, ids.caption_resource_id, szCaption, sizeof(szCaption)/sizeof(WCHAR));
268 LoadStringW(shell32_hInstance, ids.text_resource_id, szText, sizeof(szText)/sizeof(WCHAR));
269
270 args[0] = (DWORD_PTR)szDir;
271 FormatMessageW(FORMAT_MESSAGE_FROM_STRING|FORMAT_MESSAGE_ARGUMENT_ARRAY,
272 szText, 0, 0, szBuffer, sizeof(szBuffer), (va_list*)args);
273 hIcon = LoadIconW(ids.hIconInstance, (LPWSTR)MAKEINTRESOURCE(ids.icon_resource_id));
274
275 ret = SHELL_ConfirmMsgBox(hWnd, szBuffer, szCaption, hIcon, op && op->bManyItems);
276 if (op) {
277 if (ret == IDD_YESTOALL) {
278 op->dwYesToAllMask |= (1 << nKindOfDialog);
279 ret = IDYES;
280 }
281 if (ret == IDCANCEL)
282 op->bCancelled = TRUE;
283 if (ret != IDYES)
284 op->req->fAnyOperationsAborted = TRUE;
285 }
286 return ret == IDYES;
287 }
288
289 BOOL SHELL_ConfirmYesNoW(HWND hWnd, int nKindOfDialog, LPCWSTR szDir)
290 {
291 return SHELL_ConfirmDialogW(hWnd, nKindOfDialog, szDir, NULL);
292 }
293
294 static DWORD SHELL32_AnsiToUnicodeBuf(LPCSTR aPath, LPWSTR *wPath, DWORD minChars)
295 {
296 DWORD len = MultiByteToWideChar(CP_ACP, 0, aPath, -1, NULL, 0);
297
298 if (len < minChars)
299 len = minChars;
300
301 *wPath = HeapAlloc(GetProcessHeap(), 0, len * sizeof(WCHAR));
302 if (*wPath)
303 {
304 MultiByteToWideChar(CP_ACP, 0, aPath, -1, *wPath, len);
305 return NO_ERROR;
306 }
307 return E_OUTOFMEMORY;
308 }
309
310 static void SHELL32_FreeUnicodeBuf(LPWSTR wPath)
311 {
312 HeapFree(GetProcessHeap(), 0, wPath);
313 }
314
315 HRESULT WINAPI SHIsFileAvailableOffline(LPCWSTR path, LPDWORD status)
316 {
317 FIXME("(%s, %p) stub\n", debugstr_w(path), status);
318 return E_FAIL;
319 }
320
321 /**************************************************************************
322 * SHELL_DeleteDirectory() [internal]
323 *
324 * Asks for confirmation when bShowUI is true and deletes the directory and
325 * all its subdirectories and files if necessary.
326 */
327 BOOL SHELL_DeleteDirectoryW(HWND hwnd, LPCWSTR pszDir, BOOL bShowUI)
328 {
329 BOOL ret = TRUE;
330 HANDLE hFind;
331 WIN32_FIND_DATAW wfd;
332 WCHAR szTemp[MAX_PATH];
333
334 /* Make sure the directory exists before eventually prompting the user */
335 PathCombineW(szTemp, pszDir, wWildcardFile);
336 hFind = FindFirstFileW(szTemp, &wfd);
337 if (hFind == INVALID_HANDLE_VALUE)
338 return FALSE;
339
340 if (!bShowUI || (ret = SHELL_ConfirmDialogW(hwnd, ASK_DELETE_FOLDER, pszDir, NULL)))
341 {
342 do
343 {
344 if (IsDotDir(wfd.cFileName))
345 continue;
346 PathCombineW(szTemp, pszDir, wfd.cFileName);
347 if (FILE_ATTRIBUTE_DIRECTORY & wfd.dwFileAttributes)
348 ret = SHELL_DeleteDirectoryW(hwnd, szTemp, FALSE);
349 else
350 ret = (SHNotifyDeleteFileW(szTemp) == ERROR_SUCCESS);
351 } while (ret && FindNextFileW(hFind, &wfd));
352 }
353 FindClose(hFind);
354 if (ret)
355 ret = (SHNotifyRemoveDirectoryW(pszDir) == ERROR_SUCCESS);
356 return ret;
357 }
358
359 /**************************************************************************
360 * Win32CreateDirectory [SHELL32.93]
361 *
362 * Creates a directory. Also triggers a change notify if one exists.
363 *
364 * PARAMS
365 * path [I] path to directory to create
366 *
367 * RETURNS
368 * TRUE if successful, FALSE otherwise
369 */
370
371 static DWORD SHNotifyCreateDirectoryW(LPCWSTR path, LPSECURITY_ATTRIBUTES sec)
372 {
373 TRACE("(%s, %p)\n", debugstr_w(path), sec);
374
375 if (CreateDirectoryW(path, sec))
376 {
377 SHChangeNotify(SHCNE_MKDIR, SHCNF_PATHW, path, NULL);
378 return ERROR_SUCCESS;
379 }
380 return GetLastError();
381 }
382
383 /**********************************************************************/
384
385 BOOL WINAPI Win32CreateDirectoryW(LPCWSTR path, LPSECURITY_ATTRIBUTES sec)
386 {
387 return (SHNotifyCreateDirectoryW(path, sec) == ERROR_SUCCESS);
388 }
389
390 /************************************************************************
391 * Win32RemoveDirectory [SHELL32.94]
392 *
393 * Deletes a directory. Also triggers a change notify if one exists.
394 *
395 * PARAMS
396 * path [I] path to directory to delete
397 *
398 * RETURNS
399 * TRUE if successful, FALSE otherwise
400 */
401 static DWORD SHNotifyRemoveDirectoryW(LPCWSTR path)
402 {
403 BOOL ret;
404 TRACE("(%s)\n", debugstr_w(path));
405
406 ret = RemoveDirectoryW(path);
407 if (!ret)
408 {
409 /* Directory may be write protected */
410 DWORD dwAttr = GetFileAttributesW(path);
411 if (IsAttrib(dwAttr, FILE_ATTRIBUTE_READONLY))
412 if (SetFileAttributesW(path, dwAttr & ~FILE_ATTRIBUTE_READONLY))
413 ret = RemoveDirectoryW(path);
414 }
415 if (ret)
416 {
417 SHChangeNotify(SHCNE_RMDIR, SHCNF_PATHW, path, NULL);
418 return ERROR_SUCCESS;
419 }
420 return GetLastError();
421 }
422
423 /***********************************************************************/
424
425 BOOL WINAPI Win32RemoveDirectoryW(LPCWSTR path)
426 {
427 return (SHNotifyRemoveDirectoryW(path) == ERROR_SUCCESS);
428 }
429
430 /************************************************************************
431 * Win32DeleteFile [SHELL32.164]
432 *
433 * Deletes a file. Also triggers a change notify if one exists.
434 *
435 * PARAMS
436 * path [I] path to file to delete
437 *
438 * RETURNS
439 * TRUE if successful, FALSE otherwise
440 */
441 static DWORD SHNotifyDeleteFileW(LPCWSTR path)
442 {
443 BOOL ret;
444
445 TRACE("(%s)\n", debugstr_w(path));
446
447 ret = DeleteFileW(path);
448 if (!ret)
449 {
450 /* File may be write protected or a system file */
451 DWORD dwAttr = GetFileAttributesW(path);
452 if (IsAttrib(dwAttr, FILE_ATTRIBUTE_READONLY | FILE_ATTRIBUTE_SYSTEM))
453 if (SetFileAttributesW(path, dwAttr & ~(FILE_ATTRIBUTE_READONLY | FILE_ATTRIBUTE_SYSTEM)))
454 ret = DeleteFileW(path);
455 }
456 if (ret)
457 {
458 SHChangeNotify(SHCNE_DELETE, SHCNF_PATHW, path, NULL);
459 return ERROR_SUCCESS;
460 }
461 return GetLastError();
462 }
463
464 /***********************************************************************/
465
466 DWORD WINAPI Win32DeleteFileW(LPCWSTR path)
467 {
468 return (SHNotifyDeleteFileW(path) == ERROR_SUCCESS);
469 }
470
471 /************************************************************************
472 * SHNotifyMoveFile [internal]
473 *
474 * Moves a file. Also triggers a change notify if one exists.
475 *
476 * PARAMS
477 * src [I] path to source file to move
478 * dest [I] path to target file to move to
479 *
480 * RETURNS
481 * ERORR_SUCCESS if successful
482 */
483 static DWORD SHNotifyMoveFileW(LPCWSTR src, LPCWSTR dest)
484 {
485 BOOL ret;
486
487 TRACE("(%s %s)\n", debugstr_w(src), debugstr_w(dest));
488
489 ret = MoveFileExW(src, dest, MOVEFILE_REPLACE_EXISTING);
490
491 /* MOVEFILE_REPLACE_EXISTING fails with dirs, so try MoveFile */
492 if (!ret)
493 ret = MoveFileW(src, dest);
494
495 if (!ret)
496 {
497 DWORD dwAttr;
498
499 dwAttr = SHFindAttrW(dest, FALSE);
500 if (INVALID_FILE_ATTRIBUTES == dwAttr)
501 {
502 /* Source file may be write protected or a system file */
503 dwAttr = GetFileAttributesW(src);
504 if (IsAttrib(dwAttr, FILE_ATTRIBUTE_READONLY | FILE_ATTRIBUTE_SYSTEM))
505 if (SetFileAttributesW(src, dwAttr & ~(FILE_ATTRIBUTE_READONLY | FILE_ATTRIBUTE_SYSTEM)))
506 ret = MoveFileW(src, dest);
507 }
508 }
509 if (ret)
510 {
511 SHChangeNotify(SHCNE_RENAMEITEM, SHCNF_PATHW, src, dest);
512 return ERROR_SUCCESS;
513 }
514 return GetLastError();
515 }
516
517 /************************************************************************
518 * SHNotifyCopyFile [internal]
519 *
520 * Copies a file. Also triggers a change notify if one exists.
521 *
522 * PARAMS
523 * src [I] path to source file to move
524 * dest [I] path to target file to move to
525 * bFailIfExists [I] if TRUE, the target file will not be overwritten if
526 * a file with this name already exists
527 *
528 * RETURNS
529 * ERROR_SUCCESS if successful
530 */
531 static DWORD SHNotifyCopyFileW(LPCWSTR src, LPCWSTR dest, BOOL bFailIfExists)
532 {
533 BOOL ret;
534 DWORD attribs;
535
536 TRACE("(%s %s %s)\n", debugstr_w(src), debugstr_w(dest), bFailIfExists ? "failIfExists" : "");
537
538 /* Destination file may already exist with read only attribute */
539 attribs = GetFileAttributesW(dest);
540 if (IsAttrib(attribs, FILE_ATTRIBUTE_READONLY))
541 SetFileAttributesW(dest, attribs & ~FILE_ATTRIBUTE_READONLY);
542
543 ret = CopyFileW(src, dest, bFailIfExists);
544 if (ret)
545 {
546 SHChangeNotify(SHCNE_CREATE, SHCNF_PATHW, dest, NULL);
547 return ERROR_SUCCESS;
548 }
549
550 return GetLastError();
551 }
552
553 /*************************************************************************
554 * SHCreateDirectory [SHELL32.165]
555 *
556 * This function creates a file system folder whose fully qualified path is
557 * given by path. If one or more of the intermediate folders do not exist,
558 * they will be created as well.
559 *
560 * PARAMS
561 * hWnd [I]
562 * path [I] path of directory to create
563 *
564 * RETURNS
565 * ERROR_SUCCESS or one of the following values:
566 * ERROR_BAD_PATHNAME if the path is relative
567 * ERROR_FILE_EXISTS when a file with that name exists
568 * ERROR_PATH_NOT_FOUND can't find the path, probably invalid
569 * ERROR_INVALID_NAME if the path contains invalid chars
570 * ERROR_ALREADY_EXISTS when the directory already exists
571 * ERROR_FILENAME_EXCED_RANGE if the filename was to long to process
572 *
573 * NOTES
574 * exported by ordinal
575 * Win9x exports ANSI
576 * WinNT/2000 exports Unicode
577 */
578 DWORD WINAPI SHCreateDirectory(HWND hWnd, LPCWSTR path)
579 {
580 return SHCreateDirectoryExW(hWnd, path, NULL);
581 }
582
583 /*************************************************************************
584 * SHCreateDirectoryExA [SHELL32.@]
585 *
586 * This function creates a file system folder whose fully qualified path is
587 * given by path. If one or more of the intermediate folders do not exist,
588 * they will be created as well.
589 *
590 * PARAMS
591 * hWnd [I]
592 * path [I] path of directory to create
593 * sec [I] security attributes to use or NULL
594 *
595 * RETURNS
596 * ERROR_SUCCESS or one of the following values:
597 * ERROR_BAD_PATHNAME or ERROR_PATH_NOT_FOUND if the path is relative
598 * ERROR_INVALID_NAME if the path contains invalid chars
599 * ERROR_FILE_EXISTS when a file with that name exists
600 * ERROR_ALREADY_EXISTS when the directory already exists
601 * ERROR_FILENAME_EXCED_RANGE if the filename was to long to process
602 *
603 * FIXME: Not implemented yet;
604 * SHCreateDirectoryEx also verifies that the files in the directory will be visible
605 * if the path is a network path to deal with network drivers which might have a limited
606 * but unknown maximum path length. If not:
607 *
608 * If hWnd is set to a valid window handle, a message box is displayed warning
609 * the user that the files may not be accessible. If the user chooses not to
610 * proceed, the function returns ERROR_CANCELLED.
611 *
612 * If hWnd is set to NULL, no user interface is displayed and the function
613 * returns ERROR_CANCELLED.
614 */
615 int WINAPI SHCreateDirectoryExA(HWND hWnd, LPCSTR path, LPSECURITY_ATTRIBUTES sec)
616 {
617 LPWSTR wPath;
618 DWORD retCode;
619
620 TRACE("(%s, %p)\n", debugstr_a(path), sec);
621
622 retCode = SHELL32_AnsiToUnicodeBuf(path, &wPath, 0);
623 if (!retCode)
624 {
625 retCode = SHCreateDirectoryExW(hWnd, wPath, sec);
626 SHELL32_FreeUnicodeBuf(wPath);
627 }
628 return retCode;
629 }
630
631 /*************************************************************************
632 * SHCreateDirectoryExW [SHELL32.@]
633 *
634 * See SHCreateDirectoryExA.
635 */
636 int WINAPI SHCreateDirectoryExW(HWND hWnd, LPCWSTR path, LPSECURITY_ATTRIBUTES sec)
637 {
638 int ret = ERROR_BAD_PATHNAME;
639 TRACE("(%p, %s, %p)\n", hWnd, debugstr_w(path), sec);
640
641 if (PathIsRelativeW(path))
642 {
643 SetLastError(ret);
644 }
645 else
646 {
647 ret = SHNotifyCreateDirectoryW(path, sec);
648 /* Refuse to work on certain error codes before trying to create directories recursively */
649 if (ret != ERROR_SUCCESS &&
650 ret != ERROR_FILE_EXISTS &&
651 ret != ERROR_ALREADY_EXISTS &&
652 ret != ERROR_FILENAME_EXCED_RANGE)
653 {
654 WCHAR *pEnd, *pSlash, szTemp[MAX_PATH + 1]; /* extra for PathAddBackslash() */
655
656 lstrcpynW(szTemp, path, MAX_PATH);
657 pEnd = PathAddBackslashW(szTemp);
658 pSlash = szTemp + 3;
659
660 while (*pSlash)
661 {
662 while (*pSlash && *pSlash != '\\') pSlash++;
663 if (*pSlash)
664 {
665 *pSlash = 0; /* terminate path at separator */
666
667 ret = SHNotifyCreateDirectoryW(szTemp, pSlash + 1 == pEnd ? sec : NULL);
668 }
669 *pSlash++ = '\\'; /* put the separator back */
670 }
671 }
672
673 if (ret && hWnd && (ERROR_CANCELLED != ret))
674 {
675 /* We failed and should show a dialog box */
676 FIXME("Show system error message, creating path %s, failed with error %d\n", debugstr_w(path), ret);
677 ret = ERROR_CANCELLED; /* Error has been already presented to user (not really yet!) */
678 }
679 }
680 return ret;
681 }
682
683 /*************************************************************************
684 * SHFindAttrW [internal]
685 *
686 * Get the Attributes for a file or directory. The difference to GetAttributes()
687 * is that this function will also work for paths containing wildcard characters
688 * in its filename.
689
690 * PARAMS
691 * path [I] path of directory or file to check
692 * fileOnly [I] TRUE if only files should be found
693 *
694 * RETURNS
695 * INVALID_FILE_ATTRIBUTES if the path does not exist, the actual attributes of
696 * the first file or directory found otherwise
697 */
698 static DWORD SHFindAttrW(LPCWSTR pName, BOOL fileOnly)
699 {
700 WIN32_FIND_DATAW wfd;
701 BOOL b_FileMask = fileOnly && (NULL != StrPBrkW(pName, wWildcardChars));
702 DWORD dwAttr = INVALID_FILE_ATTRIBUTES;
703 HANDLE hFind = FindFirstFileW(pName, &wfd);
704
705 TRACE("%s %d\n", debugstr_w(pName), fileOnly);
706 if (INVALID_HANDLE_VALUE != hFind)
707 {
708 do
709 {
710 if (b_FileMask && IsAttribDir(wfd.dwFileAttributes))
711 continue;
712 dwAttr = wfd.dwFileAttributes;
713 break;
714 }
715 while (FindNextFileW(hFind, &wfd));
716 FindClose(hFind);
717 }
718 return dwAttr;
719 }
720
721 /*************************************************************************
722 *
723 * SHNameTranslate HelperFunction for SHFileOperationA
724 *
725 * Translates a list of 0 terminated ASCII strings into Unicode. If *wString
726 * is NULL, only the necessary size of the string is determined and returned,
727 * otherwise the ASCII strings are copied into it and the buffer is increased
728 * to point to the location after the final 0 termination char.
729 */
730 static DWORD SHNameTranslate(LPWSTR* wString, LPCWSTR* pWToFrom, BOOL more)
731 {
732 DWORD size = 0, aSize = 0;
733 LPCSTR aString = (LPCSTR)*pWToFrom;
734
735 if (aString)
736 {
737 do
738 {
739 size = lstrlenA(aString) + 1;
740 aSize += size;
741 aString += size;
742 } while ((size != 1) && more);
743 /* The two sizes might be different in the case of multibyte chars */
744 size = MultiByteToWideChar(CP_ACP, 0, (LPCSTR)*pWToFrom, aSize, *wString, 0);
745 if (*wString) /* only in the second loop */
746 {
747 MultiByteToWideChar(CP_ACP, 0, (LPCSTR)*pWToFrom, aSize, *wString, size);
748 *pWToFrom = *wString;
749 *wString += size;
750 }
751 }
752 return size;
753 }
754 /*************************************************************************
755 * SHFileOperationA [SHELL32.@]
756 *
757 * Function to copy, move, delete and create one or more files with optional
758 * user prompts.
759 *
760 * PARAMS
761 * lpFileOp [I/O] pointer to a structure containing all the necessary information
762 *
763 * RETURNS
764 * Success: ERROR_SUCCESS.
765 * Failure: ERROR_CANCELLED.
766 *
767 * NOTES
768 * exported by name
769 */
770 int WINAPI SHFileOperationA(LPSHFILEOPSTRUCTA lpFileOp)
771 {
772 SHFILEOPSTRUCTW nFileOp = *((LPSHFILEOPSTRUCTW)lpFileOp);
773 int retCode = 0;
774 DWORD size;
775 LPWSTR ForFree = NULL, /* we change wString in SHNameTranslate and can't use it for freeing */
776 wString = NULL; /* we change this in SHNameTranslate */
777
778 TRACE("\n");
779 if (FO_DELETE == (nFileOp.wFunc & FO_MASK))
780 nFileOp.pTo = NULL; /* we need a NULL or a valid pointer for translation */
781 if (!(nFileOp.fFlags & FOF_SIMPLEPROGRESS))
782 nFileOp.lpszProgressTitle = NULL; /* we need a NULL or a valid pointer for translation */
783 while (1) /* every loop calculate size, second translate also, if we have storage for this */
784 {
785 size = SHNameTranslate(&wString, &nFileOp.lpszProgressTitle, FALSE); /* no loop */
786 size += SHNameTranslate(&wString, &nFileOp.pFrom, TRUE); /* internal loop */
787 size += SHNameTranslate(&wString, &nFileOp.pTo, TRUE); /* internal loop */
788
789 if (ForFree)
790 {
791 retCode = SHFileOperationW(&nFileOp);
792 HeapFree(GetProcessHeap(), 0, ForFree); /* we cannot use wString, it was changed */
793 break;
794 }
795 else
796 {
797 wString = ForFree = HeapAlloc(GetProcessHeap(), 0, size * sizeof(WCHAR));
798 if (ForFree) continue;
799 retCode = ERROR_OUTOFMEMORY;
800 nFileOp.fAnyOperationsAborted = TRUE;
801 SetLastError(retCode);
802 return retCode;
803 }
804 }
805
806 lpFileOp->hNameMappings = nFileOp.hNameMappings;
807 lpFileOp->fAnyOperationsAborted = nFileOp.fAnyOperationsAborted;
808 return retCode;
809 }
810
811 #define ERROR_SHELL_INTERNAL_FILE_NOT_FOUND 1026
812
813 typedef struct
814 {
815 DWORD attributes;
816 LPWSTR szDirectory;
817 LPWSTR szFilename;
818 LPWSTR szFullPath;
819 BOOL bFromWildcard;
820 BOOL bFromRelative;
821 BOOL bExists;
822 } FILE_ENTRY;
823
824 typedef struct
825 {
826 FILE_ENTRY *feFiles;
827 DWORD num_alloc;
828 DWORD dwNumFiles;
829 BOOL bAnyFromWildcard;
830 BOOL bAnyDirectories;
831 BOOL bAnyDontExist;
832 } FILE_LIST;
833
834
835 static void __inline grow_list(FILE_LIST *list)
836 {
837 FILE_ENTRY *new = HeapReAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, list->feFiles,
838 list->num_alloc * 2 * sizeof(*new) );
839 list->feFiles = new;
840 list->num_alloc *= 2;
841 }
842
843 /* adds a file to the FILE_ENTRY struct
844 */
845 static void add_file_to_entry(FILE_ENTRY *feFile, LPCWSTR szFile)
846 {
847 DWORD dwLen = lstrlenW(szFile) + 1;
848 LPCWSTR ptr;
849
850 feFile->szFullPath = HeapAlloc(GetProcessHeap(), 0, dwLen * sizeof(WCHAR));
851 lstrcpyW(feFile->szFullPath, szFile);
852
853 ptr = StrRChrW(szFile, NULL, '\\');
854 if (ptr)
855 {
856 dwLen = ptr - szFile + 1;
857 feFile->szDirectory = HeapAlloc(GetProcessHeap(), 0, dwLen * sizeof(WCHAR));
858 lstrcpynW(feFile->szDirectory, szFile, dwLen);
859
860 dwLen = lstrlenW(feFile->szFullPath) - dwLen + 1;
861 feFile->szFilename = HeapAlloc(GetProcessHeap(), 0, dwLen * sizeof(WCHAR));
862 lstrcpyW(feFile->szFilename, ptr + 1); /* skip over backslash */
863 }
864 feFile->bFromWildcard = FALSE;
865 }
866
867 static LPWSTR wildcard_to_file(LPCWSTR szWildCard, LPCWSTR szFileName)
868 {
869 LPCWSTR ptr;
870 LPWSTR szFullPath;
871 DWORD dwDirLen, dwFullLen;
872
873 ptr = StrRChrW(szWildCard, NULL, '\\');
874 dwDirLen = ptr - szWildCard + 1;
875
876 dwFullLen = dwDirLen + lstrlenW(szFileName) + 1;
877 szFullPath = HeapAlloc(GetProcessHeap(), 0, dwFullLen * sizeof(WCHAR));
878
879 lstrcpynW(szFullPath, szWildCard, dwDirLen + 1);
880 lstrcatW(szFullPath, szFileName);
881
882 return szFullPath;
883 }
884
885 static void parse_wildcard_files(FILE_LIST *flList, LPCWSTR szFile, LPDWORD pdwListIndex)
886 {
887 WIN32_FIND_DATAW wfd;
888 HANDLE hFile = FindFirstFileW(szFile, &wfd);
889 FILE_ENTRY *file;
890 LPWSTR szFullPath;
891 BOOL res;
892
893 if (hFile == INVALID_HANDLE_VALUE) return;
894
895 for (res = TRUE; res; res = FindNextFileW(hFile, &wfd))
896 {
897 if (IsDotDir(wfd.cFileName)) continue;
898 if (*pdwListIndex >= flList->num_alloc) grow_list( flList );
899 szFullPath = wildcard_to_file(szFile, wfd.cFileName);
900 file = &flList->feFiles[(*pdwListIndex)++];
901 add_file_to_entry(file, szFullPath);
902 file->bFromWildcard = TRUE;
903 file->attributes = wfd.dwFileAttributes;
904 if (IsAttribDir(file->attributes)) flList->bAnyDirectories = TRUE;
905 HeapFree(GetProcessHeap(), 0, szFullPath);
906 }
907
908 FindClose(hFile);
909 }
910
911 /* takes the null-separated file list and fills out the FILE_LIST */
912 static HRESULT parse_file_list(FILE_LIST *flList, LPCWSTR szFiles)
913 {
914 LPCWSTR ptr = szFiles;
915 WCHAR szCurFile[MAX_PATH];
916 DWORD i = 0;
917
918 if (!szFiles)
919 return ERROR_INVALID_PARAMETER;
920
921 flList->bAnyFromWildcard = FALSE;
922 flList->bAnyDirectories = FALSE;
923 flList->bAnyDontExist = FALSE;
924 flList->num_alloc = 32;
925 flList->dwNumFiles = 0;
926
927 /* empty list */
928 if (!szFiles[0])
929 return ERROR_ACCESS_DENIED;
930
931 flList->feFiles = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY,
932 flList->num_alloc * sizeof(FILE_ENTRY));
933
934 while (*ptr)
935 {
936 if (i >= flList->num_alloc) grow_list( flList );
937
938 /* change relative to absolute path */
939 if (PathIsRelativeW(ptr))
940 {
941 GetCurrentDirectoryW(MAX_PATH, szCurFile);
942 PathCombineW(szCurFile, szCurFile, ptr);
943 flList->feFiles[i].bFromRelative = TRUE;
944 }
945 else
946 {
947 lstrcpyW(szCurFile, ptr);
948 flList->feFiles[i].bFromRelative = FALSE;
949 }
950
951 /* parse wildcard files if they are in the filename */
952 if (StrPBrkW(szCurFile, wWildcardChars))
953 {
954 parse_wildcard_files(flList, szCurFile, &i);
955 flList->bAnyFromWildcard = TRUE;
956 i--;
957 }
958 else
959 {
960 FILE_ENTRY *file = &flList->feFiles[i];
961 add_file_to_entry(file, szCurFile);
962 file->attributes = GetFileAttributesW( file->szFullPath );
963 file->bExists = (file->attributes != INVALID_FILE_ATTRIBUTES);
964 if (!file->bExists) flList->bAnyDontExist = TRUE;
965 if (IsAttribDir(file->attributes)) flList->bAnyDirectories = TRUE;
966 }
967
968 /* advance to the next string */
969 ptr += lstrlenW(ptr) + 1;
970 i++;
971 }
972 flList->dwNumFiles = i;
973
974 return S_OK;
975 }
976
977 /* free the FILE_LIST */
978 static void destroy_file_list(FILE_LIST *flList)
979 {
980 DWORD i;
981
982 if (!flList || !flList->feFiles)
983 return;
984
985 for (i = 0; i < flList->dwNumFiles; i++)
986 {
987 HeapFree(GetProcessHeap(), 0, flList->feFiles[i].szDirectory);
988 HeapFree(GetProcessHeap(), 0, flList->feFiles[i].szFilename);
989 HeapFree(GetProcessHeap(), 0, flList->feFiles[i].szFullPath);
990 }
991
992 HeapFree(GetProcessHeap(), 0, flList->feFiles);
993 }
994
995 static void copy_dir_to_dir(FILE_OPERATION *op, const FILE_ENTRY *feFrom, LPCWSTR szDestPath)
996 {
997 WCHAR szFrom[MAX_PATH], szTo[MAX_PATH];
998 SHFILEOPSTRUCTW fileOp;
999
1000 static const WCHAR wildCardFiles[] = {'*','.','*',0};
1001
1002 if (IsDotDir(feFrom->szFilename))
1003 return;
1004
1005 if (PathFileExistsW(szDestPath))
1006 PathCombineW(szTo, szDestPath, feFrom->szFilename);
1007 else
1008 lstrcpyW(szTo, szDestPath);
1009
1010 if (!(op->req->fFlags & FOF_NOCONFIRMATION) && PathFileExistsW(szTo)) {
1011 if (!SHELL_ConfirmDialogW(op->req->hwnd, ASK_OVERWRITE_FOLDER, feFrom->szFilename, op))
1012 {
1013 /* Vista returns an ERROR_CANCELLED even if user pressed "No" */
1014 if (!op->bManyItems)
1015 op->bCancelled = TRUE;
1016 return;
1017 }
1018 }
1019
1020 szTo[lstrlenW(szTo) + 1] = '\0';
1021 SHNotifyCreateDirectoryW(szTo, NULL);
1022
1023 PathCombineW(szFrom, feFrom->szFullPath, wildCardFiles);
1024 szFrom[lstrlenW(szFrom) + 1] = '\0';
1025
1026 fileOp = *op->req;
1027 fileOp.pFrom = szFrom;
1028 fileOp.pTo = szTo;
1029 fileOp.fFlags &= ~FOF_MULTIDESTFILES; /* we know we're copying to one dir */
1030
1031 /* Don't ask the user about overwriting files when he accepted to overwrite the
1032 folder. FIXME: this is not exactly what Windows does - e.g. there would be
1033 an additional confirmation for a nested folder */
1034 fileOp.fFlags |= FOF_NOCONFIRMATION;
1035
1036 SHFileOperationW(&fileOp);
1037 }
1038
1039 static BOOL copy_file_to_file(FILE_OPERATION *op, const WCHAR *szFrom, const WCHAR *szTo)
1040 {
1041 if (!(op->req->fFlags & FOF_NOCONFIRMATION) && PathFileExistsW(szTo))
1042 {
1043 if (!SHELL_ConfirmDialogW(op->req->hwnd, ASK_OVERWRITE_FILE, PathFindFileNameW(szTo), op))
1044 return 0;
1045 }
1046
1047 return SHNotifyCopyFileW(szFrom, szTo, FALSE) == 0;
1048 }
1049
1050 /* copy a file or directory to another directory */
1051 static void copy_to_dir(FILE_OPERATION *op, const FILE_ENTRY *feFrom, const FILE_ENTRY *feTo)
1052 {
1053 if (!PathFileExistsW(feTo->szFullPath))
1054 SHNotifyCreateDirectoryW(feTo->szFullPath, NULL);
1055
1056 if (IsAttribFile(feFrom->attributes))
1057 {
1058 WCHAR szDestPath[MAX_PATH];
1059
1060 PathCombineW(szDestPath, feTo->szFullPath, feFrom->szFilename);
1061 copy_file_to_file(op, feFrom->szFullPath, szDestPath);
1062 }
1063 else if (!(op->req->fFlags & FOF_FILESONLY && feFrom->bFromWildcard))
1064 copy_dir_to_dir(op, feFrom, feTo->szFullPath);
1065 }
1066
1067 static void create_dest_dirs(LPCWSTR szDestDir)
1068 {
1069 WCHAR dir[MAX_PATH];
1070 LPCWSTR ptr = StrChrW(szDestDir, '\\');
1071
1072 /* make sure all directories up to last one are created */
1073 while (ptr && (ptr = StrChrW(ptr + 1, '\\')))
1074 {
1075 lstrcpynW(dir, szDestDir, ptr - szDestDir + 1);
1076
1077 if (!PathFileExistsW(dir))
1078 SHNotifyCreateDirectoryW(dir, NULL);
1079 }
1080
1081 /* create last directory */
1082 if (!PathFileExistsW(szDestDir))
1083 SHNotifyCreateDirectoryW(szDestDir, NULL);
1084 }
1085
1086 /* the FO_COPY operation */
1087 static HRESULT copy_files(FILE_OPERATION *op, const FILE_LIST *flFrom, FILE_LIST *flTo)
1088 {
1089 DWORD i;
1090 const FILE_ENTRY *entryToCopy;
1091 const FILE_ENTRY *fileDest = &flTo->feFiles[0];
1092
1093 if (flFrom->bAnyDontExist)
1094 return ERROR_SHELL_INTERNAL_FILE_NOT_FOUND;
1095
1096 if (flTo->dwNumFiles == 0)
1097 {
1098 /* If the destination is empty, SHFileOperation should use the current directory */
1099 WCHAR curdir[MAX_PATH+1];
1100
1101 GetCurrentDirectoryW(MAX_PATH, curdir);
1102 curdir[lstrlenW(curdir)+1] = 0;
1103
1104 destroy_file_list(flTo);
1105 ZeroMemory(flTo, sizeof(FILE_LIST));
1106 parse_file_list(flTo, curdir);
1107 fileDest = &flTo->feFiles[0];
1108 }
1109
1110 if (op->req->fFlags & FOF_MULTIDESTFILES)
1111 {
1112 if (flFrom->bAnyFromWildcard)
1113 return ERROR_CANCELLED;
1114
1115 if (flFrom->dwNumFiles != flTo->dwNumFiles)
1116 {
1117 if (flFrom->dwNumFiles != 1 && !IsAttribDir(fileDest->attributes))
1118 return ERROR_CANCELLED;
1119
1120 /* Free all but the first entry. */
1121 for (i = 1; i < flTo->dwNumFiles; i++)
1122 {
1123 HeapFree(GetProcessHeap(), 0, flTo->feFiles[i].szDirectory);
1124 HeapFree(GetProcessHeap(), 0, flTo->feFiles[i].szFilename);
1125 HeapFree(GetProcessHeap(), 0, flTo->feFiles[i].szFullPath);
1126 }
1127
1128 flTo->dwNumFiles = 1;
1129 }
1130 else if (IsAttribDir(fileDest->attributes))
1131 {
1132 for (i = 1; i < flTo->dwNumFiles; i++)
1133 if (!IsAttribDir(flTo->feFiles[i].attributes) ||
1134 !IsAttribDir(flFrom->feFiles[i].attributes))
1135 {
1136 return ERROR_CANCELLED;
1137 }
1138 }
1139 }
1140 else if (flFrom->dwNumFiles != 1)
1141 {
1142 if (flTo->dwNumFiles != 1 && !IsAttribDir(fileDest->attributes))
1143 return ERROR_CANCELLED;
1144
1145 if (PathFileExistsW(fileDest->szFullPath) &&
1146 IsAttribFile(fileDest->attributes))
1147 {
1148 return ERROR_CANCELLED;
1149 }
1150
1151 if (flTo->dwNumFiles == 1 && fileDest->bFromRelative &&
1152 !PathFileExistsW(fileDest->szFullPath))
1153 {
1154 return ERROR_CANCELLED;
1155 }
1156 }
1157
1158 for (i = 0; i < flFrom->dwNumFiles; i++)
1159 {
1160 entryToCopy = &flFrom->feFiles[i];
1161
1162 if ((op->req->fFlags & FOF_MULTIDESTFILES) &&
1163 flTo->dwNumFiles > 1)
1164 {
1165 fileDest = &flTo->feFiles[i];
1166 }
1167
1168 if (IsAttribDir(entryToCopy->attributes) &&
1169 !lstrcmpiW(entryToCopy->szFullPath, fileDest->szDirectory))
1170 {
1171 return ERROR_SUCCESS;
1172 }
1173
1174 create_dest_dirs(fileDest->szDirectory);
1175
1176 if (!lstrcmpiW(entryToCopy->szFullPath, fileDest->szFullPath))
1177 {
1178 if (IsAttribFile(entryToCopy->attributes))
1179 return ERROR_NO_MORE_SEARCH_HANDLES;
1180 else
1181 return ERROR_SUCCESS;
1182 }
1183
1184 if ((flFrom->dwNumFiles > 1 && flTo->dwNumFiles == 1) ||
1185 IsAttribDir(fileDest->attributes))
1186 {
1187 copy_to_dir(op, entryToCopy, fileDest);
1188 }
1189 else if (IsAttribDir(entryToCopy->attributes))
1190 {
1191 copy_dir_to_dir(op, entryToCopy, fileDest->szFullPath);
1192 }
1193 else
1194 {
1195 if (!copy_file_to_file(op, entryToCopy->szFullPath, fileDest->szFullPath))
1196 {
1197 op->req->fAnyOperationsAborted = TRUE;
1198 return ERROR_CANCELLED;
1199 }
1200 }
1201
1202 /* Vista return code. XP would return e.g. ERROR_FILE_NOT_FOUND, ERROR_ALREADY_EXISTS */
1203 if (op->bCancelled)
1204 return ERROR_CANCELLED;
1205 }
1206
1207 /* Vista return code. On XP if the used pressed "No" for the last item,
1208 * ERROR_ARENA_TRASHED would be returned */
1209 return ERROR_SUCCESS;
1210 }
1211
1212 static BOOL confirm_delete_list(HWND hWnd, DWORD fFlags, BOOL fTrash, const FILE_LIST *flFrom)
1213 {
1214 if (flFrom->dwNumFiles > 1)
1215 {
1216 WCHAR tmp[8];
1217 const WCHAR format[] = {'%','d',0};
1218
1219 wnsprintfW(tmp, sizeof(tmp)/sizeof(tmp[0]), format, flFrom->dwNumFiles);
1220 return SHELL_ConfirmDialogW(hWnd, (fTrash?ASK_TRASH_MULTIPLE_ITEM:ASK_DELETE_MULTIPLE_ITEM), tmp, NULL);
1221 }
1222 else
1223 {
1224 const FILE_ENTRY *fileEntry = &flFrom->feFiles[0];
1225
1226 if (IsAttribFile(fileEntry->attributes))
1227 return SHELL_ConfirmDialogW(hWnd, (fTrash?ASK_TRASH_FILE:ASK_DELETE_FILE), fileEntry->szFullPath, NULL);
1228 else if (!(fFlags & FOF_FILESONLY && fileEntry->bFromWildcard))
1229 return SHELL_ConfirmDialogW(hWnd, (fTrash?ASK_TRASH_FOLDER:ASK_DELETE_FOLDER), fileEntry->szFullPath, NULL);
1230 }
1231 return TRUE;
1232 }
1233
1234 /* the FO_DELETE operation */
1235 static HRESULT delete_files(LPSHFILEOPSTRUCTW lpFileOp, const FILE_LIST *flFrom)
1236 {
1237 const FILE_ENTRY *fileEntry;
1238 DWORD i;
1239 BOOL bPathExists;
1240 BOOL bTrash;
1241
1242 if (!flFrom->dwNumFiles)
1243 return ERROR_SUCCESS;
1244
1245 /* Windows also checks only the first item */
1246 bTrash = (lpFileOp->fFlags & FOF_ALLOWUNDO)
1247 && TRASH_CanTrashFile(flFrom->feFiles[0].szFullPath);
1248
1249 if (!(lpFileOp->fFlags & FOF_NOCONFIRMATION) || (!bTrash && lpFileOp->fFlags & FOF_WANTNUKEWARNING))
1250 if (!confirm_delete_list(lpFileOp->hwnd, lpFileOp->fFlags, bTrash, flFrom))
1251 {
1252 lpFileOp->fAnyOperationsAborted = TRUE;
1253 return 0;
1254 }
1255
1256 for (i = 0; i < flFrom->dwNumFiles; i++)
1257 {
1258 bPathExists = TRUE;
1259 fileEntry = &flFrom->feFiles[i];
1260
1261 if (!IsAttribFile(fileEntry->attributes) &&
1262 (lpFileOp->fFlags & FOF_FILESONLY && fileEntry->bFromWildcard))
1263 continue;
1264
1265 if (bTrash)
1266 {
1267 BOOL bDelete;
1268 if (TRASH_TrashFile(fileEntry->szFullPath))
1269 continue;
1270
1271 /* Note: Windows silently deletes the file in such a situation, we show a dialog */
1272 if (!(lpFileOp->fFlags & FOF_NOCONFIRMATION) || (lpFileOp->fFlags & FOF_WANTNUKEWARNING))
1273 bDelete = SHELL_ConfirmDialogW(lpFileOp->hwnd, ASK_CANT_TRASH_ITEM, fileEntry->szFullPath, NULL);
1274 else
1275 bDelete = TRUE;
1276
1277 if (!bDelete)
1278 {
1279 lpFileOp->fAnyOperationsAborted = TRUE;
1280 break;
1281 }
1282 }
1283
1284 /* delete the file or directory */
1285 if (IsAttribFile(fileEntry->attributes))
1286 bPathExists = DeleteFileW(fileEntry->szFullPath);
1287 else
1288 bPathExists = SHELL_DeleteDirectoryW(lpFileOp->hwnd, fileEntry->szFullPath, FALSE);
1289
1290 if (!bPathExists)
1291 return ERROR_PATH_NOT_FOUND;
1292 }
1293
1294 return ERROR_SUCCESS;
1295 }
1296
1297 static void move_dir_to_dir(LPSHFILEOPSTRUCTW lpFileOp, const FILE_ENTRY *feFrom, LPCWSTR szDestPath)
1298 {
1299 WCHAR szFrom[MAX_PATH], szTo[MAX_PATH];
1300 SHFILEOPSTRUCTW fileOp;
1301
1302 static const WCHAR wildCardFiles[] = {'*','.','*',0};
1303
1304 if (IsDotDir(feFrom->szFilename))
1305 return;
1306
1307 SHNotifyCreateDirectoryW(szDestPath, NULL);
1308
1309 PathCombineW(szFrom, feFrom->szFullPath, wildCardFiles);
1310 szFrom[lstrlenW(szFrom) + 1] = '\0';
1311
1312 lstrcpyW(szTo, szDestPath);
1313 szTo[lstrlenW(szDestPath) + 1] = '\0';
1314
1315 fileOp = *lpFileOp;
1316 fileOp.pFrom = szFrom;
1317 fileOp.pTo = szTo;
1318
1319 SHFileOperationW(&fileOp);
1320 }
1321
1322 /* moves a file or directory to another directory */
1323 static void move_to_dir(LPSHFILEOPSTRUCTW lpFileOp, const FILE_ENTRY *feFrom, const FILE_ENTRY *feTo)
1324 {
1325 WCHAR szDestPath[MAX_PATH];
1326
1327 PathCombineW(szDestPath, feTo->szFullPath, feFrom->szFilename);
1328
1329 if (IsAttribFile(feFrom->attributes))
1330 SHNotifyMoveFileW(feFrom->szFullPath, szDestPath);
1331 else if (!(lpFileOp->fFlags & FOF_FILESONLY && feFrom->bFromWildcard))
1332 move_dir_to_dir(lpFileOp, feFrom, szDestPath);
1333 }
1334
1335 /* the FO_MOVE operation */
1336 static HRESULT move_files(LPSHFILEOPSTRUCTW lpFileOp, const FILE_LIST *flFrom, const FILE_LIST *flTo)
1337 {
1338 DWORD i;
1339 const FILE_ENTRY *entryToMove;
1340 const FILE_ENTRY *fileDest;
1341
1342 if (!flFrom->dwNumFiles || !flTo->dwNumFiles)
1343 return ERROR_CANCELLED;
1344
1345 if (!(lpFileOp->fFlags & FOF_MULTIDESTFILES) &&
1346 flTo->dwNumFiles > 1 && flFrom->dwNumFiles > 1)
1347 {
1348 return ERROR_CANCELLED;
1349 }
1350
1351 if (!(lpFileOp->fFlags & FOF_MULTIDESTFILES) &&
1352 !flFrom->bAnyDirectories &&
1353 flFrom->dwNumFiles > flTo->dwNumFiles)
1354 {
1355 return ERROR_CANCELLED;
1356 }
1357
1358 if (!PathFileExistsW(flTo->feFiles[0].szDirectory))
1359 return ERROR_CANCELLED;
1360
1361 if ((lpFileOp->fFlags & FOF_MULTIDESTFILES) &&
1362 flFrom->dwNumFiles != flTo->dwNumFiles)
1363 {
1364 return ERROR_CANCELLED;
1365 }
1366
1367 fileDest = &flTo->feFiles[0];
1368 for (i = 0; i < flFrom->dwNumFiles; i++)
1369 {
1370 entryToMove = &flFrom->feFiles[i];
1371
1372 if (lpFileOp->fFlags & FOF_MULTIDESTFILES)
1373 fileDest = &flTo->feFiles[i];
1374
1375 if (!PathFileExistsW(fileDest->szDirectory))
1376 return ERROR_CANCELLED;
1377
1378 if (fileDest->bExists && IsAttribDir(fileDest->attributes))
1379 move_to_dir(lpFileOp, entryToMove, fileDest);
1380 else
1381 SHNotifyMoveFileW(entryToMove->szFullPath, fileDest->szFullPath);
1382 }
1383
1384 return ERROR_SUCCESS;
1385 }
1386
1387 /* the FO_RENAME files */
1388 static HRESULT rename_files(LPSHFILEOPSTRUCTW lpFileOp, const FILE_LIST *flFrom, const FILE_LIST *flTo)
1389 {
1390 const FILE_ENTRY *feFrom;
1391 const FILE_ENTRY *feTo;
1392
1393 if (flFrom->dwNumFiles != 1)
1394 return ERROR_GEN_FAILURE;
1395
1396 if (flTo->dwNumFiles != 1)
1397 return ERROR_CANCELLED;
1398
1399 feFrom = &flFrom->feFiles[0];
1400 feTo= &flTo->feFiles[0];
1401
1402 /* fail if destination doesn't exist */
1403 if (!feFrom->bExists)
1404 return ERROR_SHELL_INTERNAL_FILE_NOT_FOUND;
1405
1406 /* fail if destination already exists */
1407 if (feTo->bExists)
1408 return ERROR_ALREADY_EXISTS;
1409
1410 return SHNotifyMoveFileW(feFrom->szFullPath, feTo->szFullPath);
1411 }
1412
1413 /* alert the user if an unsupported flag is used */
1414 static void check_flags(FILEOP_FLAGS fFlags)
1415 {
1416 WORD wUnsupportedFlags = FOF_NO_CONNECTED_ELEMENTS |
1417 FOF_NOCOPYSECURITYATTRIBS | FOF_NORECURSEREPARSE |
1418 FOF_RENAMEONCOLLISION | FOF_WANTMAPPINGHANDLE;
1419
1420 if (fFlags & wUnsupportedFlags)
1421 FIXME("Unsupported flags: %04x\n", fFlags);
1422 }
1423
1424 /*************************************************************************
1425 * SHFileOperationW [SHELL32.@]
1426 *
1427 * See SHFileOperationA
1428 */
1429 int WINAPI SHFileOperationW(LPSHFILEOPSTRUCTW lpFileOp)
1430 {
1431 FILE_OPERATION op;
1432 FILE_LIST flFrom, flTo;
1433 int ret = 0;
1434
1435 if (!lpFileOp)
1436 return ERROR_INVALID_PARAMETER;
1437
1438 check_flags(lpFileOp->fFlags);
1439
1440 ZeroMemory(&flFrom, sizeof(FILE_LIST));
1441 ZeroMemory(&flTo, sizeof(FILE_LIST));
1442
1443 if ((ret = parse_file_list(&flFrom, lpFileOp->pFrom)))
1444 return ret;
1445
1446 if (lpFileOp->wFunc != FO_DELETE)
1447 parse_file_list(&flTo, lpFileOp->pTo);
1448
1449 ZeroMemory(&op, sizeof(op));
1450 op.req = lpFileOp;
1451 op.bManyItems = (flFrom.dwNumFiles > 1);
1452
1453 switch (lpFileOp->wFunc)
1454 {
1455 case FO_COPY:
1456 ret = copy_files(&op, &flFrom, &flTo);
1457 break;
1458 case FO_DELETE:
1459 ret = delete_files(lpFileOp, &flFrom);
1460 break;
1461 case FO_MOVE:
1462 ret = move_files(lpFileOp, &flFrom, &flTo);
1463 break;
1464 case FO_RENAME:
1465 ret = rename_files(lpFileOp, &flFrom, &flTo);
1466 break;
1467 default:
1468 ret = ERROR_INVALID_PARAMETER;
1469 break;
1470 }
1471
1472 destroy_file_list(&flFrom);
1473
1474 if (lpFileOp->wFunc != FO_DELETE)
1475 destroy_file_list(&flTo);
1476
1477 if (ret == ERROR_CANCELLED)
1478 lpFileOp->fAnyOperationsAborted = TRUE;
1479
1480 return ret;
1481 }
1482
1483 #define SHDSA_GetItemCount(hdsa) (*(int*)(hdsa))
1484
1485 /*************************************************************************
1486 * SHFreeNameMappings [shell32.246]
1487 *
1488 * Free the mapping handle returned by SHFileOperation if FOF_WANTSMAPPINGHANDLE
1489 * was specified.
1490 *
1491 * PARAMS
1492 * hNameMapping [I] handle to the name mappings used during renaming of files
1493 *
1494 * RETURNS
1495 * Nothing
1496 */
1497 void WINAPI SHFreeNameMappings(HANDLE hNameMapping)
1498 {
1499 if (hNameMapping)
1500 {
1501 int i = SHDSA_GetItemCount((HDSA)hNameMapping) - 1;
1502
1503 for (; i>= 0; i--)
1504 {
1505 LPSHNAMEMAPPINGW lp = DSA_GetItemPtr(hNameMapping, i);
1506
1507 SHFree(lp->pszOldPath);
1508 SHFree(lp->pszNewPath);
1509 }
1510 DSA_Destroy(hNameMapping);
1511 }
1512 }
1513
1514 /*************************************************************************
1515 * SheGetDirA [SHELL32.@]
1516 *
1517 * drive = 0: returns the current directory path
1518 * drive > 0: returns the current directory path of the specified drive
1519 * drive=1 -> A: drive=2 -> B: ...
1520 * returns 0 if successful
1521 */
1522 DWORD WINAPI SheGetDirA(DWORD drive, LPSTR buffer)
1523 {
1524 WCHAR org_path[MAX_PATH];
1525 DWORD ret;
1526 char drv_path[3];
1527
1528 /* change current directory to the specified drive */
1529 if (drive) {
1530 strcpy(drv_path, "A:");
1531 drv_path[0] += (char)drive-1;
1532
1533 GetCurrentDirectoryW(MAX_PATH, org_path);
1534
1535 SetCurrentDirectoryA(drv_path);
1536 }
1537
1538 /* query current directory path of the specified drive */
1539 ret = GetCurrentDirectoryA(MAX_PATH, buffer);
1540
1541 /* back to the original drive */
1542 if (drive)
1543 SetCurrentDirectoryW(org_path);
1544
1545 if (!ret)
1546 return GetLastError();
1547
1548 return 0;
1549 }
1550
1551 /*************************************************************************
1552 * SheGetDirW [SHELL32.@]
1553 *
1554 * drive = 0: returns the current directory path
1555 * drive > 0: returns the current directory path of the specified drive
1556 * drive=1 -> A: drive=2 -> B: ...
1557 * returns 0 if successful
1558 */
1559 DWORD WINAPI SheGetDirW(DWORD drive, LPWSTR buffer)
1560 {
1561 WCHAR org_path[MAX_PATH];
1562 DWORD ret;
1563 char drv_path[3];
1564
1565 /* change current directory to the specified drive */
1566 if (drive) {
1567 strcpy(drv_path, "A:");
1568 drv_path[0] += (char)drive-1;
1569
1570 GetCurrentDirectoryW(MAX_PATH, org_path);
1571
1572 SetCurrentDirectoryA(drv_path);
1573 }
1574
1575 /* query current directory path of the specified drive */
1576 ret = GetCurrentDirectoryW(MAX_PATH, buffer);
1577
1578 /* back to the original drive */
1579 if (drive)
1580 SetCurrentDirectoryW(org_path);
1581
1582 if (!ret)
1583 return GetLastError();
1584
1585 return 0;
1586 }
1587
1588 /*************************************************************************
1589 * SheChangeDirA [SHELL32.@]
1590 *
1591 * changes the current directory to the specified path
1592 * and returns 0 if successful
1593 */
1594 DWORD WINAPI SheChangeDirA(LPSTR path)
1595 {
1596 if (SetCurrentDirectoryA(path))
1597 return 0;
1598 else
1599 return GetLastError();
1600 }
1601
1602 /*************************************************************************
1603 * SheChangeDirW [SHELL32.@]
1604 *
1605 * changes the current directory to the specified path
1606 * and returns 0 if successful
1607 */
1608 DWORD WINAPI SheChangeDirW(LPWSTR path)
1609 {
1610 if (SetCurrentDirectoryW(path))
1611 return 0;
1612 else
1613 return GetLastError();
1614 }
1615
1616 /*************************************************************************
1617 * IsNetDrive [SHELL32.66]
1618 */
1619 BOOL WINAPI IsNetDrive(DWORD drive)
1620 {
1621 char root[4];
1622 strcpy(root, "A:\\");
1623 root[0] += (char)drive;
1624 return (GetDriveTypeA(root) == DRIVE_REMOTE);
1625 }
1626
1627
1628 /*************************************************************************
1629 * RealDriveType [SHELL32.524]
1630 */
1631 INT WINAPI RealDriveType(INT drive, BOOL bQueryNet)
1632 {
1633 char root[] = "A:\\";
1634 root[0] += (char)drive;
1635 return GetDriveTypeA(root);
1636 }
1637
1638 /***********************************************************************
1639 * SHPathPrepareForWriteW (SHELL32.@)
1640 */
1641 HRESULT WINAPI SHPathPrepareForWriteW(HWND hwnd, IUnknown *modless, LPCWSTR path, DWORD flags)
1642 {
1643 HRESULT res;
1644 DWORD err;
1645 LPCWSTR realpath;
1646 int len;
1647 WCHAR* last_slash;
1648 WCHAR* temppath=NULL;
1649
1650 TRACE("%p %p %s 0x%80x\n", hwnd, modless, debugstr_w(path), flags);
1651
1652 if (flags & ~(SHPPFW_DIRCREATE|SHPPFW_ASKDIRCREATE|SHPPFW_IGNOREFILENAME))
1653 FIXME("unimplemented flags 0x%08x\n", flags);
1654
1655 /* cut off filename if necessary */
1656 if (flags & SHPPFW_IGNOREFILENAME)
1657 {
1658 last_slash = StrRChrW(path, NULL, '\\');
1659 if (last_slash == NULL)
1660 len = 1;
1661 else
1662 len = last_slash - path + 1;
1663 temppath = HeapAlloc(GetProcessHeap(), 0, len * sizeof(WCHAR));
1664 if (!temppath)
1665 return E_OUTOFMEMORY;
1666 StrCpyNW(temppath, path, len);
1667 realpath = temppath;
1668 }
1669 else
1670 {
1671 realpath = path;
1672 }
1673
1674 /* try to create the directory if asked to */
1675 if (flags & (SHPPFW_DIRCREATE|SHPPFW_ASKDIRCREATE))
1676 {
1677 if (flags & SHPPFW_ASKDIRCREATE)
1678 FIXME("treating SHPPFW_ASKDIRCREATE as SHPPFW_DIRCREATE\n");
1679
1680 SHCreateDirectoryExW(0, realpath, NULL);
1681 }
1682
1683 /* check if we can access the directory */
1684 res = GetFileAttributesW(realpath);
1685
1686 HeapFree(GetProcessHeap(), 0, temppath);
1687
1688 if (res == INVALID_FILE_ATTRIBUTES)
1689 {
1690 err = GetLastError();
1691 if (err == ERROR_FILE_NOT_FOUND)
1692 return HRESULT_FROM_WIN32(ERROR_PATH_NOT_FOUND);
1693 return HRESULT_FROM_WIN32(err);
1694 }
1695 else if (res & FILE_ATTRIBUTE_DIRECTORY)
1696 return S_OK;
1697 else
1698 return HRESULT_FROM_WIN32(ERROR_DIRECTORY);
1699 }
1700
1701 /***********************************************************************
1702 * SHPathPrepareForWriteA (SHELL32.@)
1703 */
1704 HRESULT WINAPI SHPathPrepareForWriteA(HWND hwnd, IUnknown *modless, LPCSTR path, DWORD flags)
1705 {
1706 WCHAR wpath[MAX_PATH];
1707 MultiByteToWideChar( CP_ACP, 0, path, -1, wpath, MAX_PATH);
1708 return SHPathPrepareForWriteW(hwnd, modless, wpath, flags);
1709 }