[SHELL32]
[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
535 TRACE("(%s %s %s)\n", debugstr_w(src), debugstr_w(dest), bFailIfExists ? "failIfExists" : "");
536
537 ret = CopyFileW(src, dest, bFailIfExists);
538 if (ret)
539 {
540 SHChangeNotify(SHCNE_CREATE, SHCNF_PATHW, dest, NULL);
541 return ERROR_SUCCESS;
542 }
543
544 return GetLastError();
545 }
546
547 /*************************************************************************
548 * SHCreateDirectory [SHELL32.165]
549 *
550 * This function creates a file system folder whose fully qualified path is
551 * given by path. If one or more of the intermediate folders do not exist,
552 * they will be created as well.
553 *
554 * PARAMS
555 * hWnd [I]
556 * path [I] path of directory to create
557 *
558 * RETURNS
559 * ERROR_SUCCESS or one of the following values:
560 * ERROR_BAD_PATHNAME if the path is relative
561 * ERROR_FILE_EXISTS when a file with that name exists
562 * ERROR_PATH_NOT_FOUND can't find the path, probably invalid
563 * ERROR_INVALID_NAME if the path contains invalid chars
564 * ERROR_ALREADY_EXISTS when the directory already exists
565 * ERROR_FILENAME_EXCED_RANGE if the filename was to long to process
566 *
567 * NOTES
568 * exported by ordinal
569 * Win9x exports ANSI
570 * WinNT/2000 exports Unicode
571 */
572 DWORD WINAPI SHCreateDirectory(HWND hWnd, LPCWSTR path)
573 {
574 return SHCreateDirectoryExW(hWnd, path, NULL);
575 }
576
577 /*************************************************************************
578 * SHCreateDirectoryExA [SHELL32.@]
579 *
580 * This function creates a file system folder whose fully qualified path is
581 * given by path. If one or more of the intermediate folders do not exist,
582 * they will be created as well.
583 *
584 * PARAMS
585 * hWnd [I]
586 * path [I] path of directory to create
587 * sec [I] security attributes to use or NULL
588 *
589 * RETURNS
590 * ERROR_SUCCESS or one of the following values:
591 * ERROR_BAD_PATHNAME or ERROR_PATH_NOT_FOUND if the path is relative
592 * ERROR_INVALID_NAME if the path contains invalid chars
593 * ERROR_FILE_EXISTS when a file with that name exists
594 * ERROR_ALREADY_EXISTS when the directory already exists
595 * ERROR_FILENAME_EXCED_RANGE if the filename was to long to process
596 *
597 * FIXME: Not implemented yet;
598 * SHCreateDirectoryEx also verifies that the files in the directory will be visible
599 * if the path is a network path to deal with network drivers which might have a limited
600 * but unknown maximum path length. If not:
601 *
602 * If hWnd is set to a valid window handle, a message box is displayed warning
603 * the user that the files may not be accessible. If the user chooses not to
604 * proceed, the function returns ERROR_CANCELLED.
605 *
606 * If hWnd is set to NULL, no user interface is displayed and the function
607 * returns ERROR_CANCELLED.
608 */
609 int WINAPI SHCreateDirectoryExA(HWND hWnd, LPCSTR path, LPSECURITY_ATTRIBUTES sec)
610 {
611 LPWSTR wPath;
612 DWORD retCode;
613
614 TRACE("(%s, %p)\n", debugstr_a(path), sec);
615
616 retCode = SHELL32_AnsiToUnicodeBuf(path, &wPath, 0);
617 if (!retCode)
618 {
619 retCode = SHCreateDirectoryExW(hWnd, wPath, sec);
620 SHELL32_FreeUnicodeBuf(wPath);
621 }
622 return retCode;
623 }
624
625 /*************************************************************************
626 * SHCreateDirectoryExW [SHELL32.@]
627 *
628 * See SHCreateDirectoryExA.
629 */
630 int WINAPI SHCreateDirectoryExW(HWND hWnd, LPCWSTR path, LPSECURITY_ATTRIBUTES sec)
631 {
632 int ret = ERROR_BAD_PATHNAME;
633 TRACE("(%p, %s, %p)\n", hWnd, debugstr_w(path), sec);
634
635 if (PathIsRelativeW(path))
636 {
637 SetLastError(ret);
638 }
639 else
640 {
641 ret = SHNotifyCreateDirectoryW(path, sec);
642 /* Refuse to work on certain error codes before trying to create directories recursively */
643 if (ret != ERROR_SUCCESS &&
644 ret != ERROR_FILE_EXISTS &&
645 ret != ERROR_ALREADY_EXISTS &&
646 ret != ERROR_FILENAME_EXCED_RANGE)
647 {
648 WCHAR *pEnd, *pSlash, szTemp[MAX_PATH + 1]; /* extra for PathAddBackslash() */
649
650 lstrcpynW(szTemp, path, MAX_PATH);
651 pEnd = PathAddBackslashW(szTemp);
652 pSlash = szTemp + 3;
653
654 while (*pSlash)
655 {
656 while (*pSlash && *pSlash != '\\') pSlash++;
657 if (*pSlash)
658 {
659 *pSlash = 0; /* terminate path at separator */
660
661 ret = SHNotifyCreateDirectoryW(szTemp, pSlash + 1 == pEnd ? sec : NULL);
662 }
663 *pSlash++ = '\\'; /* put the separator back */
664 }
665 }
666
667 if (ret && hWnd && (ERROR_CANCELLED != ret))
668 {
669 /* We failed and should show a dialog box */
670 FIXME("Show system error message, creating path %s, failed with error %d\n", debugstr_w(path), ret);
671 ret = ERROR_CANCELLED; /* Error has been already presented to user (not really yet!) */
672 }
673 }
674 return ret;
675 }
676
677 /*************************************************************************
678 * SHFindAttrW [internal]
679 *
680 * Get the Attributes for a file or directory. The difference to GetAttributes()
681 * is that this function will also work for paths containing wildcard characters
682 * in its filename.
683
684 * PARAMS
685 * path [I] path of directory or file to check
686 * fileOnly [I] TRUE if only files should be found
687 *
688 * RETURNS
689 * INVALID_FILE_ATTRIBUTES if the path does not exist, the actual attributes of
690 * the first file or directory found otherwise
691 */
692 static DWORD SHFindAttrW(LPCWSTR pName, BOOL fileOnly)
693 {
694 WIN32_FIND_DATAW wfd;
695 BOOL b_FileMask = fileOnly && (NULL != StrPBrkW(pName, wWildcardChars));
696 DWORD dwAttr = INVALID_FILE_ATTRIBUTES;
697 HANDLE hFind = FindFirstFileW(pName, &wfd);
698
699 TRACE("%s %d\n", debugstr_w(pName), fileOnly);
700 if (INVALID_HANDLE_VALUE != hFind)
701 {
702 do
703 {
704 if (b_FileMask && IsAttribDir(wfd.dwFileAttributes))
705 continue;
706 dwAttr = wfd.dwFileAttributes;
707 break;
708 }
709 while (FindNextFileW(hFind, &wfd));
710 FindClose(hFind);
711 }
712 return dwAttr;
713 }
714
715 /*************************************************************************
716 *
717 * SHNameTranslate HelperFunction for SHFileOperationA
718 *
719 * Translates a list of 0 terminated ASCII strings into Unicode. If *wString
720 * is NULL, only the necessary size of the string is determined and returned,
721 * otherwise the ASCII strings are copied into it and the buffer is increased
722 * to point to the location after the final 0 termination char.
723 */
724 static DWORD SHNameTranslate(LPWSTR* wString, LPCWSTR* pWToFrom, BOOL more)
725 {
726 DWORD size = 0, aSize = 0;
727 LPCSTR aString = (LPCSTR)*pWToFrom;
728
729 if (aString)
730 {
731 do
732 {
733 size = lstrlenA(aString) + 1;
734 aSize += size;
735 aString += size;
736 } while ((size != 1) && more);
737 /* The two sizes might be different in the case of multibyte chars */
738 size = MultiByteToWideChar(CP_ACP, 0, (LPCSTR)*pWToFrom, aSize, *wString, 0);
739 if (*wString) /* only in the second loop */
740 {
741 MultiByteToWideChar(CP_ACP, 0, (LPCSTR)*pWToFrom, aSize, *wString, size);
742 *pWToFrom = *wString;
743 *wString += size;
744 }
745 }
746 return size;
747 }
748 /*************************************************************************
749 * SHFileOperationA [SHELL32.@]
750 *
751 * Function to copy, move, delete and create one or more files with optional
752 * user prompts.
753 *
754 * PARAMS
755 * lpFileOp [I/O] pointer to a structure containing all the necessary information
756 *
757 * RETURNS
758 * Success: ERROR_SUCCESS.
759 * Failure: ERROR_CANCELLED.
760 *
761 * NOTES
762 * exported by name
763 */
764 int WINAPI SHFileOperationA(LPSHFILEOPSTRUCTA lpFileOp)
765 {
766 SHFILEOPSTRUCTW nFileOp = *((LPSHFILEOPSTRUCTW)lpFileOp);
767 int retCode = 0;
768 DWORD size;
769 LPWSTR ForFree = NULL, /* we change wString in SHNameTranslate and can't use it for freeing */
770 wString = NULL; /* we change this in SHNameTranslate */
771
772 TRACE("\n");
773 if (FO_DELETE == (nFileOp.wFunc & FO_MASK))
774 nFileOp.pTo = NULL; /* we need a NULL or a valid pointer for translation */
775 if (!(nFileOp.fFlags & FOF_SIMPLEPROGRESS))
776 nFileOp.lpszProgressTitle = NULL; /* we need a NULL or a valid pointer for translation */
777 while (1) /* every loop calculate size, second translate also, if we have storage for this */
778 {
779 size = SHNameTranslate(&wString, &nFileOp.lpszProgressTitle, FALSE); /* no loop */
780 size += SHNameTranslate(&wString, &nFileOp.pFrom, TRUE); /* internal loop */
781 size += SHNameTranslate(&wString, &nFileOp.pTo, TRUE); /* internal loop */
782
783 if (ForFree)
784 {
785 retCode = SHFileOperationW(&nFileOp);
786 HeapFree(GetProcessHeap(), 0, ForFree); /* we cannot use wString, it was changed */
787 break;
788 }
789 else
790 {
791 wString = ForFree = HeapAlloc(GetProcessHeap(), 0, size * sizeof(WCHAR));
792 if (ForFree) continue;
793 retCode = ERROR_OUTOFMEMORY;
794 nFileOp.fAnyOperationsAborted = TRUE;
795 SetLastError(retCode);
796 return retCode;
797 }
798 }
799
800 lpFileOp->hNameMappings = nFileOp.hNameMappings;
801 lpFileOp->fAnyOperationsAborted = nFileOp.fAnyOperationsAborted;
802 return retCode;
803 }
804
805 #define ERROR_SHELL_INTERNAL_FILE_NOT_FOUND 1026
806
807 typedef struct
808 {
809 DWORD attributes;
810 LPWSTR szDirectory;
811 LPWSTR szFilename;
812 LPWSTR szFullPath;
813 BOOL bFromWildcard;
814 BOOL bFromRelative;
815 BOOL bExists;
816 } FILE_ENTRY;
817
818 typedef struct
819 {
820 FILE_ENTRY *feFiles;
821 DWORD num_alloc;
822 DWORD dwNumFiles;
823 BOOL bAnyFromWildcard;
824 BOOL bAnyDirectories;
825 BOOL bAnyDontExist;
826 } FILE_LIST;
827
828
829 static void __inline grow_list(FILE_LIST *list)
830 {
831 FILE_ENTRY *new = HeapReAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, list->feFiles,
832 list->num_alloc * 2 * sizeof(*new) );
833 list->feFiles = new;
834 list->num_alloc *= 2;
835 }
836
837 /* adds a file to the FILE_ENTRY struct
838 */
839 static void add_file_to_entry(FILE_ENTRY *feFile, LPCWSTR szFile)
840 {
841 DWORD dwLen = lstrlenW(szFile) + 1;
842 LPCWSTR ptr;
843
844 feFile->szFullPath = HeapAlloc(GetProcessHeap(), 0, dwLen * sizeof(WCHAR));
845 lstrcpyW(feFile->szFullPath, szFile);
846
847 ptr = StrRChrW(szFile, NULL, '\\');
848 if (ptr)
849 {
850 dwLen = ptr - szFile + 1;
851 feFile->szDirectory = HeapAlloc(GetProcessHeap(), 0, dwLen * sizeof(WCHAR));
852 lstrcpynW(feFile->szDirectory, szFile, dwLen);
853
854 dwLen = lstrlenW(feFile->szFullPath) - dwLen + 1;
855 feFile->szFilename = HeapAlloc(GetProcessHeap(), 0, dwLen * sizeof(WCHAR));
856 lstrcpyW(feFile->szFilename, ptr + 1); /* skip over backslash */
857 }
858 feFile->bFromWildcard = FALSE;
859 }
860
861 static LPWSTR wildcard_to_file(LPCWSTR szWildCard, LPCWSTR szFileName)
862 {
863 LPCWSTR ptr;
864 LPWSTR szFullPath;
865 DWORD dwDirLen, dwFullLen;
866
867 ptr = StrRChrW(szWildCard, NULL, '\\');
868 dwDirLen = ptr - szWildCard + 1;
869
870 dwFullLen = dwDirLen + lstrlenW(szFileName) + 1;
871 szFullPath = HeapAlloc(GetProcessHeap(), 0, dwFullLen * sizeof(WCHAR));
872
873 lstrcpynW(szFullPath, szWildCard, dwDirLen + 1);
874 lstrcatW(szFullPath, szFileName);
875
876 return szFullPath;
877 }
878
879 static void parse_wildcard_files(FILE_LIST *flList, LPCWSTR szFile, LPDWORD pdwListIndex)
880 {
881 WIN32_FIND_DATAW wfd;
882 HANDLE hFile = FindFirstFileW(szFile, &wfd);
883 FILE_ENTRY *file;
884 LPWSTR szFullPath;
885 BOOL res;
886
887 if (hFile == INVALID_HANDLE_VALUE) return;
888
889 for (res = TRUE; res; res = FindNextFileW(hFile, &wfd))
890 {
891 if (IsDotDir(wfd.cFileName)) continue;
892 if (*pdwListIndex >= flList->num_alloc) grow_list( flList );
893 szFullPath = wildcard_to_file(szFile, wfd.cFileName);
894 file = &flList->feFiles[(*pdwListIndex)++];
895 add_file_to_entry(file, szFullPath);
896 file->bFromWildcard = TRUE;
897 file->attributes = wfd.dwFileAttributes;
898 if (IsAttribDir(file->attributes)) flList->bAnyDirectories = TRUE;
899 HeapFree(GetProcessHeap(), 0, szFullPath);
900 }
901
902 FindClose(hFile);
903 }
904
905 /* takes the null-separated file list and fills out the FILE_LIST */
906 static HRESULT parse_file_list(FILE_LIST *flList, LPCWSTR szFiles)
907 {
908 LPCWSTR ptr = szFiles;
909 WCHAR szCurFile[MAX_PATH];
910 DWORD i = 0;
911
912 if (!szFiles)
913 return ERROR_INVALID_PARAMETER;
914
915 flList->bAnyFromWildcard = FALSE;
916 flList->bAnyDirectories = FALSE;
917 flList->bAnyDontExist = FALSE;
918 flList->num_alloc = 32;
919 flList->dwNumFiles = 0;
920
921 /* empty list */
922 if (!szFiles[0])
923 return ERROR_ACCESS_DENIED;
924
925 flList->feFiles = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY,
926 flList->num_alloc * sizeof(FILE_ENTRY));
927
928 while (*ptr)
929 {
930 if (i >= flList->num_alloc) grow_list( flList );
931
932 /* change relative to absolute path */
933 if (PathIsRelativeW(ptr))
934 {
935 GetCurrentDirectoryW(MAX_PATH, szCurFile);
936 PathCombineW(szCurFile, szCurFile, ptr);
937 flList->feFiles[i].bFromRelative = TRUE;
938 }
939 else
940 {
941 lstrcpyW(szCurFile, ptr);
942 flList->feFiles[i].bFromRelative = FALSE;
943 }
944
945 /* parse wildcard files if they are in the filename */
946 if (StrPBrkW(szCurFile, wWildcardChars))
947 {
948 parse_wildcard_files(flList, szCurFile, &i);
949 flList->bAnyFromWildcard = TRUE;
950 i--;
951 }
952 else
953 {
954 FILE_ENTRY *file = &flList->feFiles[i];
955 add_file_to_entry(file, szCurFile);
956 file->attributes = GetFileAttributesW( file->szFullPath );
957 file->bExists = (file->attributes != INVALID_FILE_ATTRIBUTES);
958 if (!file->bExists) flList->bAnyDontExist = TRUE;
959 if (IsAttribDir(file->attributes)) flList->bAnyDirectories = TRUE;
960 }
961
962 /* advance to the next string */
963 ptr += lstrlenW(ptr) + 1;
964 i++;
965 }
966 flList->dwNumFiles = i;
967
968 return S_OK;
969 }
970
971 /* free the FILE_LIST */
972 static void destroy_file_list(FILE_LIST *flList)
973 {
974 DWORD i;
975
976 if (!flList || !flList->feFiles)
977 return;
978
979 for (i = 0; i < flList->dwNumFiles; i++)
980 {
981 HeapFree(GetProcessHeap(), 0, flList->feFiles[i].szDirectory);
982 HeapFree(GetProcessHeap(), 0, flList->feFiles[i].szFilename);
983 HeapFree(GetProcessHeap(), 0, flList->feFiles[i].szFullPath);
984 }
985
986 HeapFree(GetProcessHeap(), 0, flList->feFiles);
987 }
988
989 static void copy_dir_to_dir(FILE_OPERATION *op, const FILE_ENTRY *feFrom, LPCWSTR szDestPath)
990 {
991 WCHAR szFrom[MAX_PATH], szTo[MAX_PATH];
992 SHFILEOPSTRUCTW fileOp;
993
994 static const WCHAR wildCardFiles[] = {'*','.','*',0};
995
996 if (IsDotDir(feFrom->szFilename))
997 return;
998
999 if (PathFileExistsW(szDestPath))
1000 PathCombineW(szTo, szDestPath, feFrom->szFilename);
1001 else
1002 lstrcpyW(szTo, szDestPath);
1003
1004 if (!(op->req->fFlags & FOF_NOCONFIRMATION) && PathFileExistsW(szTo)) {
1005 if (!SHELL_ConfirmDialogW(op->req->hwnd, ASK_OVERWRITE_FOLDER, feFrom->szFilename, op))
1006 {
1007 /* Vista returns an ERROR_CANCELLED even if user pressed "No" */
1008 if (!op->bManyItems)
1009 op->bCancelled = TRUE;
1010 return;
1011 }
1012 }
1013
1014 szTo[lstrlenW(szTo) + 1] = '\0';
1015 SHNotifyCreateDirectoryW(szTo, NULL);
1016
1017 PathCombineW(szFrom, feFrom->szFullPath, wildCardFiles);
1018 szFrom[lstrlenW(szFrom) + 1] = '\0';
1019
1020 fileOp = *op->req;
1021 fileOp.pFrom = szFrom;
1022 fileOp.pTo = szTo;
1023 fileOp.fFlags &= ~FOF_MULTIDESTFILES; /* we know we're copying to one dir */
1024
1025 /* Don't ask the user about overwriting files when he accepted to overwrite the
1026 folder. FIXME: this is not exactly what Windows does - e.g. there would be
1027 an additional confirmation for a nested folder */
1028 fileOp.fFlags |= FOF_NOCONFIRMATION;
1029
1030 SHFileOperationW(&fileOp);
1031 }
1032
1033 static BOOL copy_file_to_file(FILE_OPERATION *op, const WCHAR *szFrom, const WCHAR *szTo)
1034 {
1035 if (!(op->req->fFlags & FOF_NOCONFIRMATION) && PathFileExistsW(szTo))
1036 {
1037 if (!SHELL_ConfirmDialogW(op->req->hwnd, ASK_OVERWRITE_FILE, PathFindFileNameW(szTo), op))
1038 return 0;
1039 }
1040
1041 return SHNotifyCopyFileW(szFrom, szTo, FALSE) == 0;
1042 }
1043
1044 /* copy a file or directory to another directory */
1045 static void copy_to_dir(FILE_OPERATION *op, const FILE_ENTRY *feFrom, const FILE_ENTRY *feTo)
1046 {
1047 if (!PathFileExistsW(feTo->szFullPath))
1048 SHNotifyCreateDirectoryW(feTo->szFullPath, NULL);
1049
1050 if (IsAttribFile(feFrom->attributes))
1051 {
1052 WCHAR szDestPath[MAX_PATH];
1053
1054 PathCombineW(szDestPath, feTo->szFullPath, feFrom->szFilename);
1055 copy_file_to_file(op, feFrom->szFullPath, szDestPath);
1056 }
1057 else if (!(op->req->fFlags & FOF_FILESONLY && feFrom->bFromWildcard))
1058 copy_dir_to_dir(op, feFrom, feTo->szFullPath);
1059 }
1060
1061 static void create_dest_dirs(LPCWSTR szDestDir)
1062 {
1063 WCHAR dir[MAX_PATH];
1064 LPCWSTR ptr = StrChrW(szDestDir, '\\');
1065
1066 /* make sure all directories up to last one are created */
1067 while (ptr && (ptr = StrChrW(ptr + 1, '\\')))
1068 {
1069 lstrcpynW(dir, szDestDir, ptr - szDestDir + 1);
1070
1071 if (!PathFileExistsW(dir))
1072 SHNotifyCreateDirectoryW(dir, NULL);
1073 }
1074
1075 /* create last directory */
1076 if (!PathFileExistsW(szDestDir))
1077 SHNotifyCreateDirectoryW(szDestDir, NULL);
1078 }
1079
1080 /* the FO_COPY operation */
1081 static HRESULT copy_files(FILE_OPERATION *op, const FILE_LIST *flFrom, FILE_LIST *flTo)
1082 {
1083 DWORD i;
1084 const FILE_ENTRY *entryToCopy;
1085 const FILE_ENTRY *fileDest = &flTo->feFiles[0];
1086
1087 if (flFrom->bAnyDontExist)
1088 return ERROR_SHELL_INTERNAL_FILE_NOT_FOUND;
1089
1090 if (flTo->dwNumFiles == 0)
1091 {
1092 /* If the destination is empty, SHFileOperation should use the current directory */
1093 WCHAR curdir[MAX_PATH+1];
1094
1095 GetCurrentDirectoryW(MAX_PATH, curdir);
1096 curdir[lstrlenW(curdir)+1] = 0;
1097
1098 destroy_file_list(flTo);
1099 ZeroMemory(flTo, sizeof(FILE_LIST));
1100 parse_file_list(flTo, curdir);
1101 fileDest = &flTo->feFiles[0];
1102 }
1103
1104 if (op->req->fFlags & FOF_MULTIDESTFILES)
1105 {
1106 if (flFrom->bAnyFromWildcard)
1107 return ERROR_CANCELLED;
1108
1109 if (flFrom->dwNumFiles != flTo->dwNumFiles)
1110 {
1111 if (flFrom->dwNumFiles != 1 && !IsAttribDir(fileDest->attributes))
1112 return ERROR_CANCELLED;
1113
1114 /* Free all but the first entry. */
1115 for (i = 1; i < flTo->dwNumFiles; i++)
1116 {
1117 HeapFree(GetProcessHeap(), 0, flTo->feFiles[i].szDirectory);
1118 HeapFree(GetProcessHeap(), 0, flTo->feFiles[i].szFilename);
1119 HeapFree(GetProcessHeap(), 0, flTo->feFiles[i].szFullPath);
1120 }
1121
1122 flTo->dwNumFiles = 1;
1123 }
1124 else if (IsAttribDir(fileDest->attributes))
1125 {
1126 for (i = 1; i < flTo->dwNumFiles; i++)
1127 if (!IsAttribDir(flTo->feFiles[i].attributes) ||
1128 !IsAttribDir(flFrom->feFiles[i].attributes))
1129 {
1130 return ERROR_CANCELLED;
1131 }
1132 }
1133 }
1134 else if (flFrom->dwNumFiles != 1)
1135 {
1136 if (flTo->dwNumFiles != 1 && !IsAttribDir(fileDest->attributes))
1137 return ERROR_CANCELLED;
1138
1139 if (PathFileExistsW(fileDest->szFullPath) &&
1140 IsAttribFile(fileDest->attributes))
1141 {
1142 return ERROR_CANCELLED;
1143 }
1144
1145 if (flTo->dwNumFiles == 1 && fileDest->bFromRelative &&
1146 !PathFileExistsW(fileDest->szFullPath))
1147 {
1148 return ERROR_CANCELLED;
1149 }
1150 }
1151
1152 for (i = 0; i < flFrom->dwNumFiles; i++)
1153 {
1154 entryToCopy = &flFrom->feFiles[i];
1155
1156 if ((op->req->fFlags & FOF_MULTIDESTFILES) &&
1157 flTo->dwNumFiles > 1)
1158 {
1159 fileDest = &flTo->feFiles[i];
1160 }
1161
1162 if (IsAttribDir(entryToCopy->attributes) &&
1163 !lstrcmpiW(entryToCopy->szFullPath, fileDest->szDirectory))
1164 {
1165 return ERROR_SUCCESS;
1166 }
1167
1168 create_dest_dirs(fileDest->szDirectory);
1169
1170 if (!lstrcmpiW(entryToCopy->szFullPath, fileDest->szFullPath))
1171 {
1172 if (IsAttribFile(entryToCopy->attributes))
1173 return ERROR_NO_MORE_SEARCH_HANDLES;
1174 else
1175 return ERROR_SUCCESS;
1176 }
1177
1178 if ((flFrom->dwNumFiles > 1 && flTo->dwNumFiles == 1) ||
1179 IsAttribDir(fileDest->attributes))
1180 {
1181 copy_to_dir(op, entryToCopy, fileDest);
1182 }
1183 else if (IsAttribDir(entryToCopy->attributes))
1184 {
1185 copy_dir_to_dir(op, entryToCopy, fileDest->szFullPath);
1186 }
1187 else
1188 {
1189 if (!copy_file_to_file(op, entryToCopy->szFullPath, fileDest->szFullPath))
1190 {
1191 op->req->fAnyOperationsAborted = TRUE;
1192 return ERROR_CANCELLED;
1193 }
1194 }
1195
1196 /* Vista return code. XP would return e.g. ERROR_FILE_NOT_FOUND, ERROR_ALREADY_EXISTS */
1197 if (op->bCancelled)
1198 return ERROR_CANCELLED;
1199 }
1200
1201 /* Vista return code. On XP if the used pressed "No" for the last item,
1202 * ERROR_ARENA_TRASHED would be returned */
1203 return ERROR_SUCCESS;
1204 }
1205
1206 static BOOL confirm_delete_list(HWND hWnd, DWORD fFlags, BOOL fTrash, const FILE_LIST *flFrom)
1207 {
1208 if (flFrom->dwNumFiles > 1)
1209 {
1210 WCHAR tmp[8];
1211 const WCHAR format[] = {'%','d',0};
1212
1213 wnsprintfW(tmp, sizeof(tmp)/sizeof(tmp[0]), format, flFrom->dwNumFiles);
1214 return SHELL_ConfirmDialogW(hWnd, (fTrash?ASK_TRASH_MULTIPLE_ITEM:ASK_DELETE_MULTIPLE_ITEM), tmp, NULL);
1215 }
1216 else
1217 {
1218 const FILE_ENTRY *fileEntry = &flFrom->feFiles[0];
1219
1220 if (IsAttribFile(fileEntry->attributes))
1221 return SHELL_ConfirmDialogW(hWnd, (fTrash?ASK_TRASH_FILE:ASK_DELETE_FILE), fileEntry->szFullPath, NULL);
1222 else if (!(fFlags & FOF_FILESONLY && fileEntry->bFromWildcard))
1223 return SHELL_ConfirmDialogW(hWnd, (fTrash?ASK_TRASH_FOLDER:ASK_DELETE_FOLDER), fileEntry->szFullPath, NULL);
1224 }
1225 return TRUE;
1226 }
1227
1228 /* the FO_DELETE operation */
1229 static HRESULT delete_files(LPSHFILEOPSTRUCTW lpFileOp, const FILE_LIST *flFrom)
1230 {
1231 const FILE_ENTRY *fileEntry;
1232 DWORD i;
1233 BOOL bPathExists;
1234 BOOL bTrash;
1235
1236 if (!flFrom->dwNumFiles)
1237 return ERROR_SUCCESS;
1238
1239 /* Windows also checks only the first item */
1240 bTrash = (lpFileOp->fFlags & FOF_ALLOWUNDO)
1241 && TRASH_CanTrashFile(flFrom->feFiles[0].szFullPath);
1242
1243 if (!(lpFileOp->fFlags & FOF_NOCONFIRMATION) || (!bTrash && lpFileOp->fFlags & FOF_WANTNUKEWARNING))
1244 if (!confirm_delete_list(lpFileOp->hwnd, lpFileOp->fFlags, bTrash, flFrom))
1245 {
1246 lpFileOp->fAnyOperationsAborted = TRUE;
1247 return 0;
1248 }
1249
1250 for (i = 0; i < flFrom->dwNumFiles; i++)
1251 {
1252 bPathExists = TRUE;
1253 fileEntry = &flFrom->feFiles[i];
1254
1255 if (!IsAttribFile(fileEntry->attributes) &&
1256 (lpFileOp->fFlags & FOF_FILESONLY && fileEntry->bFromWildcard))
1257 continue;
1258
1259 if (bTrash)
1260 {
1261 BOOL bDelete;
1262 if (TRASH_TrashFile(fileEntry->szFullPath))
1263 continue;
1264
1265 /* Note: Windows silently deletes the file in such a situation, we show a dialog */
1266 if (!(lpFileOp->fFlags & FOF_NOCONFIRMATION) || (lpFileOp->fFlags & FOF_WANTNUKEWARNING))
1267 bDelete = SHELL_ConfirmDialogW(lpFileOp->hwnd, ASK_CANT_TRASH_ITEM, fileEntry->szFullPath, NULL);
1268 else
1269 bDelete = TRUE;
1270
1271 if (!bDelete)
1272 {
1273 lpFileOp->fAnyOperationsAborted = TRUE;
1274 break;
1275 }
1276 }
1277
1278 /* delete the file or directory */
1279 if (IsAttribFile(fileEntry->attributes))
1280 bPathExists = DeleteFileW(fileEntry->szFullPath);
1281 else
1282 bPathExists = SHELL_DeleteDirectoryW(lpFileOp->hwnd, fileEntry->szFullPath, FALSE);
1283
1284 if (!bPathExists)
1285 return ERROR_PATH_NOT_FOUND;
1286 }
1287
1288 return ERROR_SUCCESS;
1289 }
1290
1291 static void move_dir_to_dir(LPSHFILEOPSTRUCTW lpFileOp, const FILE_ENTRY *feFrom, LPCWSTR szDestPath)
1292 {
1293 WCHAR szFrom[MAX_PATH], szTo[MAX_PATH];
1294 SHFILEOPSTRUCTW fileOp;
1295
1296 static const WCHAR wildCardFiles[] = {'*','.','*',0};
1297
1298 if (IsDotDir(feFrom->szFilename))
1299 return;
1300
1301 SHNotifyCreateDirectoryW(szDestPath, NULL);
1302
1303 PathCombineW(szFrom, feFrom->szFullPath, wildCardFiles);
1304 szFrom[lstrlenW(szFrom) + 1] = '\0';
1305
1306 lstrcpyW(szTo, szDestPath);
1307 szTo[lstrlenW(szDestPath) + 1] = '\0';
1308
1309 fileOp = *lpFileOp;
1310 fileOp.pFrom = szFrom;
1311 fileOp.pTo = szTo;
1312
1313 SHFileOperationW(&fileOp);
1314 }
1315
1316 /* moves a file or directory to another directory */
1317 static void move_to_dir(LPSHFILEOPSTRUCTW lpFileOp, const FILE_ENTRY *feFrom, const FILE_ENTRY *feTo)
1318 {
1319 WCHAR szDestPath[MAX_PATH];
1320
1321 PathCombineW(szDestPath, feTo->szFullPath, feFrom->szFilename);
1322
1323 if (IsAttribFile(feFrom->attributes))
1324 SHNotifyMoveFileW(feFrom->szFullPath, szDestPath);
1325 else if (!(lpFileOp->fFlags & FOF_FILESONLY && feFrom->bFromWildcard))
1326 move_dir_to_dir(lpFileOp, feFrom, szDestPath);
1327 }
1328
1329 /* the FO_MOVE operation */
1330 static HRESULT move_files(LPSHFILEOPSTRUCTW lpFileOp, const FILE_LIST *flFrom, const FILE_LIST *flTo)
1331 {
1332 DWORD i;
1333 const FILE_ENTRY *entryToMove;
1334 const FILE_ENTRY *fileDest;
1335
1336 if (!flFrom->dwNumFiles || !flTo->dwNumFiles)
1337 return ERROR_CANCELLED;
1338
1339 if (!(lpFileOp->fFlags & FOF_MULTIDESTFILES) &&
1340 flTo->dwNumFiles > 1 && flFrom->dwNumFiles > 1)
1341 {
1342 return ERROR_CANCELLED;
1343 }
1344
1345 if (!(lpFileOp->fFlags & FOF_MULTIDESTFILES) &&
1346 !flFrom->bAnyDirectories &&
1347 flFrom->dwNumFiles > flTo->dwNumFiles)
1348 {
1349 return ERROR_CANCELLED;
1350 }
1351
1352 if (!PathFileExistsW(flTo->feFiles[0].szDirectory))
1353 return ERROR_CANCELLED;
1354
1355 if ((lpFileOp->fFlags & FOF_MULTIDESTFILES) &&
1356 flFrom->dwNumFiles != flTo->dwNumFiles)
1357 {
1358 return ERROR_CANCELLED;
1359 }
1360
1361 fileDest = &flTo->feFiles[0];
1362 for (i = 0; i < flFrom->dwNumFiles; i++)
1363 {
1364 entryToMove = &flFrom->feFiles[i];
1365
1366 if (lpFileOp->fFlags & FOF_MULTIDESTFILES)
1367 fileDest = &flTo->feFiles[i];
1368
1369 if (!PathFileExistsW(fileDest->szDirectory))
1370 return ERROR_CANCELLED;
1371
1372 if (fileDest->bExists && IsAttribDir(fileDest->attributes))
1373 move_to_dir(lpFileOp, entryToMove, fileDest);
1374 else
1375 SHNotifyMoveFileW(entryToMove->szFullPath, fileDest->szFullPath);
1376 }
1377
1378 return ERROR_SUCCESS;
1379 }
1380
1381 /* the FO_RENAME files */
1382 static HRESULT rename_files(LPSHFILEOPSTRUCTW lpFileOp, const FILE_LIST *flFrom, const FILE_LIST *flTo)
1383 {
1384 const FILE_ENTRY *feFrom;
1385 const FILE_ENTRY *feTo;
1386
1387 if (flFrom->dwNumFiles != 1)
1388 return ERROR_GEN_FAILURE;
1389
1390 if (flTo->dwNumFiles != 1)
1391 return ERROR_CANCELLED;
1392
1393 feFrom = &flFrom->feFiles[0];
1394 feTo= &flTo->feFiles[0];
1395
1396 /* fail if destination doesn't exist */
1397 if (!feFrom->bExists)
1398 return ERROR_SHELL_INTERNAL_FILE_NOT_FOUND;
1399
1400 /* fail if destination already exists */
1401 if (feTo->bExists)
1402 return ERROR_ALREADY_EXISTS;
1403
1404 return SHNotifyMoveFileW(feFrom->szFullPath, feTo->szFullPath);
1405 }
1406
1407 /* alert the user if an unsupported flag is used */
1408 static void check_flags(FILEOP_FLAGS fFlags)
1409 {
1410 WORD wUnsupportedFlags = FOF_NO_CONNECTED_ELEMENTS |
1411 FOF_NOCOPYSECURITYATTRIBS | FOF_NORECURSEREPARSE |
1412 FOF_RENAMEONCOLLISION | FOF_WANTMAPPINGHANDLE;
1413
1414 if (fFlags & wUnsupportedFlags)
1415 FIXME("Unsupported flags: %04x\n", fFlags);
1416 }
1417
1418 /*************************************************************************
1419 * SHFileOperationW [SHELL32.@]
1420 *
1421 * See SHFileOperationA
1422 */
1423 int WINAPI SHFileOperationW(LPSHFILEOPSTRUCTW lpFileOp)
1424 {
1425 FILE_OPERATION op;
1426 FILE_LIST flFrom, flTo;
1427 int ret = 0;
1428
1429 if (!lpFileOp)
1430 return ERROR_INVALID_PARAMETER;
1431
1432 check_flags(lpFileOp->fFlags);
1433
1434 ZeroMemory(&flFrom, sizeof(FILE_LIST));
1435 ZeroMemory(&flTo, sizeof(FILE_LIST));
1436
1437 if ((ret = parse_file_list(&flFrom, lpFileOp->pFrom)))
1438 return ret;
1439
1440 if (lpFileOp->wFunc != FO_DELETE)
1441 parse_file_list(&flTo, lpFileOp->pTo);
1442
1443 ZeroMemory(&op, sizeof(op));
1444 op.req = lpFileOp;
1445 op.bManyItems = (flFrom.dwNumFiles > 1);
1446
1447 switch (lpFileOp->wFunc)
1448 {
1449 case FO_COPY:
1450 ret = copy_files(&op, &flFrom, &flTo);
1451 break;
1452 case FO_DELETE:
1453 ret = delete_files(lpFileOp, &flFrom);
1454 break;
1455 case FO_MOVE:
1456 ret = move_files(lpFileOp, &flFrom, &flTo);
1457 break;
1458 case FO_RENAME:
1459 ret = rename_files(lpFileOp, &flFrom, &flTo);
1460 break;
1461 default:
1462 ret = ERROR_INVALID_PARAMETER;
1463 break;
1464 }
1465
1466 destroy_file_list(&flFrom);
1467
1468 if (lpFileOp->wFunc != FO_DELETE)
1469 destroy_file_list(&flTo);
1470
1471 if (ret == ERROR_CANCELLED)
1472 lpFileOp->fAnyOperationsAborted = TRUE;
1473
1474 return ret;
1475 }
1476
1477 #define SHDSA_GetItemCount(hdsa) (*(int*)(hdsa))
1478
1479 /*************************************************************************
1480 * SHFreeNameMappings [shell32.246]
1481 *
1482 * Free the mapping handle returned by SHFileoperation if FOF_WANTSMAPPINGHANDLE
1483 * was specified.
1484 *
1485 * PARAMS
1486 * hNameMapping [I] handle to the name mappings used during renaming of files
1487 *
1488 * RETURNS
1489 * Nothing
1490 */
1491 void WINAPI SHFreeNameMappings(HANDLE hNameMapping)
1492 {
1493 if (hNameMapping)
1494 {
1495 int i = SHDSA_GetItemCount((HDSA)hNameMapping) - 1;
1496
1497 for (; i>= 0; i--)
1498 {
1499 LPSHNAMEMAPPINGW lp = DSA_GetItemPtr((HDSA)hNameMapping, i);
1500
1501 SHFree(lp->pszOldPath);
1502 SHFree(lp->pszNewPath);
1503 }
1504 DSA_Destroy((HDSA)hNameMapping);
1505 }
1506 }
1507
1508 /*************************************************************************
1509 * SheGetDirA [SHELL32.@]
1510 *
1511 * drive = 0: returns the current directory path
1512 * drive > 0: returns the current directory path of the specified drive
1513 * drive=1 -> A: drive=2 -> B: ...
1514 * returns 0 if successful
1515 */
1516 DWORD WINAPI SheGetDirA(DWORD drive, LPSTR buffer)
1517 {
1518 WCHAR org_path[MAX_PATH];
1519 DWORD ret;
1520 char drv_path[3];
1521
1522 /* change current directory to the specified drive */
1523 if (drive) {
1524 strcpy(drv_path, "A:");
1525 drv_path[0] += (char)drive-1;
1526
1527 GetCurrentDirectoryW(MAX_PATH, org_path);
1528
1529 SetCurrentDirectoryA(drv_path);
1530 }
1531
1532 /* query current directory path of the specified drive */
1533 ret = GetCurrentDirectoryA(MAX_PATH, buffer);
1534
1535 /* back to the original drive */
1536 if (drive)
1537 SetCurrentDirectoryW(org_path);
1538
1539 if (!ret)
1540 return GetLastError();
1541
1542 return 0;
1543 }
1544
1545 /*************************************************************************
1546 * SheGetDirW [SHELL32.@]
1547 *
1548 * drive = 0: returns the current directory path
1549 * drive > 0: returns the current directory path of the specified drive
1550 * drive=1 -> A: drive=2 -> B: ...
1551 * returns 0 if successful
1552 */
1553 DWORD WINAPI SheGetDirW(DWORD drive, LPWSTR buffer)
1554 {
1555 WCHAR org_path[MAX_PATH];
1556 DWORD ret;
1557 char drv_path[3];
1558
1559 /* change current directory to the specified drive */
1560 if (drive) {
1561 strcpy(drv_path, "A:");
1562 drv_path[0] += (char)drive-1;
1563
1564 GetCurrentDirectoryW(MAX_PATH, org_path);
1565
1566 SetCurrentDirectoryA(drv_path);
1567 }
1568
1569 /* query current directory path of the specified drive */
1570 ret = GetCurrentDirectoryW(MAX_PATH, buffer);
1571
1572 /* back to the original drive */
1573 if (drive)
1574 SetCurrentDirectoryW(org_path);
1575
1576 if (!ret)
1577 return GetLastError();
1578
1579 return 0;
1580 }
1581
1582 /*************************************************************************
1583 * SheChangeDirA [SHELL32.@]
1584 *
1585 * changes the current directory to the specified path
1586 * and returns 0 if successful
1587 */
1588 DWORD WINAPI SheChangeDirA(LPSTR path)
1589 {
1590 if (SetCurrentDirectoryA(path))
1591 return 0;
1592 else
1593 return GetLastError();
1594 }
1595
1596 /*************************************************************************
1597 * SheChangeDirW [SHELL32.@]
1598 *
1599 * changes the current directory to the specified path
1600 * and returns 0 if successful
1601 */
1602 DWORD WINAPI SheChangeDirW(LPWSTR path)
1603 {
1604 if (SetCurrentDirectoryW(path))
1605 return 0;
1606 else
1607 return GetLastError();
1608 }
1609
1610 /*************************************************************************
1611 * IsNetDrive [SHELL32.66]
1612 */
1613 BOOL WINAPI IsNetDrive(DWORD drive)
1614 {
1615 char root[4];
1616 strcpy(root, "A:\\");
1617 root[0] += (char)drive;
1618 return (GetDriveTypeA(root) == DRIVE_REMOTE);
1619 }
1620
1621
1622 /*************************************************************************
1623 * RealDriveType [SHELL32.524]
1624 */
1625 INT WINAPI RealDriveType(INT drive, BOOL bQueryNet)
1626 {
1627 char root[] = "A:\\";
1628 root[0] += (char)drive;
1629 return GetDriveTypeA(root);
1630 }
1631
1632 /***********************************************************************
1633 * SHPathPrepareForWriteW (SHELL32.@)
1634 */
1635 HRESULT WINAPI SHPathPrepareForWriteW(HWND hwnd, IUnknown *modless, LPCWSTR path, DWORD flags)
1636 {
1637 HRESULT res;
1638 DWORD err;
1639 LPCWSTR realpath;
1640 int len;
1641 WCHAR* last_slash;
1642 WCHAR* temppath=NULL;
1643
1644 TRACE("%p %p %s 0x%80x\n", hwnd, modless, debugstr_w(path), flags);
1645
1646 if (flags & ~(SHPPFW_DIRCREATE|SHPPFW_ASKDIRCREATE|SHPPFW_IGNOREFILENAME))
1647 FIXME("unimplemented flags 0x%08x\n", flags);
1648
1649 /* cut off filename if necessary */
1650 if (flags & SHPPFW_IGNOREFILENAME)
1651 {
1652 last_slash = StrRChrW(path, NULL, '\\');
1653 if (last_slash == NULL)
1654 len = 1;
1655 else
1656 len = last_slash - path + 1;
1657 temppath = HeapAlloc(GetProcessHeap(), 0, len * sizeof(WCHAR));
1658 if (!temppath)
1659 return E_OUTOFMEMORY;
1660 StrCpyNW(temppath, path, len);
1661 realpath = temppath;
1662 }
1663 else
1664 {
1665 realpath = path;
1666 }
1667
1668 /* try to create the directory if asked to */
1669 if (flags & (SHPPFW_DIRCREATE|SHPPFW_ASKDIRCREATE))
1670 {
1671 if (flags & SHPPFW_ASKDIRCREATE)
1672 FIXME("treating SHPPFW_ASKDIRCREATE as SHPPFW_DIRCREATE\n");
1673
1674 SHCreateDirectoryExW(0, realpath, NULL);
1675 }
1676
1677 /* check if we can access the directory */
1678 res = GetFileAttributesW(realpath);
1679
1680 HeapFree(GetProcessHeap(), 0, temppath);
1681
1682 if (res == INVALID_FILE_ATTRIBUTES)
1683 {
1684 err = GetLastError();
1685 if (err == ERROR_FILE_NOT_FOUND)
1686 return HRESULT_FROM_WIN32(ERROR_PATH_NOT_FOUND);
1687 return HRESULT_FROM_WIN32(err);
1688 }
1689 else if (res & FILE_ATTRIBUTE_DIRECTORY)
1690 return S_OK;
1691 else
1692 return HRESULT_FROM_WIN32(ERROR_DIRECTORY);
1693 }
1694
1695 /***********************************************************************
1696 * SHPathPrepareForWriteA (SHELL32.@)
1697 */
1698 HRESULT WINAPI SHPathPrepareForWriteA(HWND hwnd, IUnknown *modless, LPCSTR path, DWORD flags)
1699 {
1700 WCHAR wpath[MAX_PATH];
1701 MultiByteToWideChar( CP_ACP, 0, path, -1, wpath, MAX_PATH);
1702 return SHPathPrepareForWriteW(hwnd, modless, wpath, flags);
1703 }