summaryrefslogtreecommitdiff
path: root/lib/recycler.cpp
blob: 11ed77f751ab430ca850df4850a084e69ffbde11 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
// **************************************************************************
// * This file is part of the FreeFileSync project. It is distributed under *
// * GNU General Public License: http://www.gnu.org/licenses/gpl.html       *
// * Copyright (C) ZenJu (zhnmju123 AT gmx DOT de) - All Rights Reserved    *
// **************************************************************************

#include "recycler.h"
#include <stdexcept>
#include <iterator>
#include <zen/file_handling.h>

#ifdef FFS_WIN
#include <algorithm>
#include <functional>
#include <vector>
#include <boost/thread/once.hpp>
#include <zen/dll.h>
#include <zen/win.h> //includes "windows.h"
#include <zen/assert_static.h>
#include <zen/win_ver.h>
#include <zen/long_path_prefix.h>
#include "IFileOperation/file_op.h"

#elif defined FFS_LINUX
#include <sys/stat.h>
#include <giomm/file.h>
#endif

using namespace zen;


namespace
{
#ifdef FFS_WIN
/*
Performance test: delete 1000 files
------------------------------------
SHFileOperation - single file     33s
SHFileOperation - multiple files  2,1s
IFileOperation  - single file     33s
IFileOperation  - multiple files  2,1s

=> SHFileOperation and IFileOperation have nearly IDENTICAL performance characteristics!

Nevertheless, let's use IFileOperation for better error reporting!
*/

void moveToWindowsRecycler(const std::vector<Zstring>& filesToDelete)  //throw FileError
{
    if (filesToDelete.empty())
        return;

    static bool useIFileOperation = false;
    static boost::once_flag once = BOOST_ONCE_INIT; //caveat: function scope static initialization is not thread-safe in VS 2010!
    boost::call_once(once, []() { useIFileOperation = vistaOrLater(); });

    if (useIFileOperation) //new recycle bin usage: available since Vista
    {
        std::vector<const wchar_t*> fileNames;
        std::transform(filesToDelete.begin(), filesToDelete.end(),
                       std::back_inserter(fileNames), std::mem_fun_ref(&Zstring::c_str));

        using namespace fileop;
        const DllFun<MoveToRecycleBinFct> moveToRecycler(getDllName(), moveToRecycleBinFctName);
        const DllFun<GetLastErrorFct>     getLastError  (getDllName(), getLastErrorFctName);

        if (!moveToRecycler || !getLastError)
            throw FileError(_("Error moving to Recycle Bin:") + L"\n\"" + fileNames[0] + L"\"" + //report first file only... better than nothing
                            L"\n\n" + _("Could not load a required DLL:") + L" \"" + getDllName() + L"\"");

        //#warning moving long file paths to recycler does not work! clarify!
        //        std::vector<Zstring> temp;
        //        std::transform(filesToDelete.begin(), filesToDelete.end(),
        //                       std::back_inserter(temp), std::ptr_fun(zen::removeLongPathPrefix)); //::IFileOperation() can't handle \\?\-prefix!

        if (!moveToRecycler(&fileNames[0], //array must not be empty
                            fileNames.size()))
        {
            wchar_t errorMessage[2000];
            getLastError(errorMessage, 2000);
            throw FileError(_("Error moving to Recycle Bin:") + L"\n\"" + fileNames[0] + L"\"" + //report first file only... better than nothing
                            L"\n\n" + L"(" + errorMessage + L")");
        }
    }
    else //regular recycle bin usage: available since XP
    {
        Zstring filenameDoubleNull;
        for (std::vector<Zstring>::const_iterator i = filesToDelete.begin(); i != filesToDelete.end(); ++i)
        {
            //#warning moving long file paths to recycler does not work! clarify!
            //filenameDoubleNull += removeLongPathPrefix(*i); //::SHFileOperation() can't handle \\?\-prefix!
            //You should use fully-qualified path names with this function. Using it with relative path names is not thread safe.
            filenameDoubleNull += *i; //::SHFileOperation() can't handle \\?\-prefix!
            filenameDoubleNull += L'\0';
        }

        SHFILEOPSTRUCT fileOp = {};
        fileOp.hwnd   = NULL;
        fileOp.wFunc  = FO_DELETE;
        fileOp.pFrom  = filenameDoubleNull.c_str();
        fileOp.pTo    = NULL;
        fileOp.fFlags = FOF_ALLOWUNDO | FOF_NOCONFIRMATION | FOF_SILENT | FOF_NOERRORUI;
        fileOp.fAnyOperationsAborted = false;
        fileOp.hNameMappings         = NULL;
        fileOp.lpszProgressTitle     = NULL;

        if (::SHFileOperation(&fileOp) != 0 || fileOp.fAnyOperationsAborted)
        {
            throw FileError(_("Error moving to Recycle Bin:") + L"\n\"" + filenameDoubleNull + L"\""); //report first file only... better than nothing
        }
    }
}
#endif
}


bool zen::moveToRecycleBin(const Zstring& filename)  //throw FileError
{
    if (!somethingExists(filename))
        return false; //neither file nor any other object with that name existing: no error situation, manual deletion relies on it!

#ifdef FFS_WIN
    //::SetFileAttributes(applyLongPathPrefix(filename).c_str(), FILE_ATTRIBUTE_NORMAL);
    //both SHFileOperation and IFileOperation are not able to delete a folder named "System Volume Information" with normal attributes but shamelessly report success

    std::vector<Zstring> fileNames;
    fileNames.push_back(filename);
    ::moveToWindowsRecycler(fileNames);  //throw FileError

#elif defined FFS_LINUX
    Glib::RefPtr<Gio::File> fileObj = Gio::File::create_for_path(filename.c_str()); //never fails
    try
    {
        if (!fileObj->trash())
            throw FileError(_("Error moving to Recycle Bin:") + L"\n\"" + filename + L"\"" +
                            L"\n\n" + L"(unknown error)");
    }
    catch (const Glib::Error& errorObj)
    {
        //implement same behavior as in Windows: if recycler is not existing, delete permanently
        if (errorObj.code() == G_IO_ERROR_NOT_SUPPORTED)
        {
            struct stat fileInfo = {};
            if (::lstat(filename.c_str(), &fileInfo) != 0)
                return false;

            if (S_ISLNK(fileInfo.st_mode) || S_ISREG(fileInfo.st_mode))
                removeFile(filename); //throw FileError
            else if (S_ISDIR(fileInfo.st_mode))
                removeDirectory(filename); //throw FileError
            return true;
        }

        //assemble error message
        const std::wstring errorMessage = L"Glib Error Code " + toString<std::wstring>(errorObj.code()) + /* L", " +
                                          g_quark_to_string(errorObj.domain()) + */ L": " + utf8CvrtTo<std::wstring>(errorObj.what());

        throw FileError(_("Error moving to Recycle Bin:") + L"\n\"" + filename + L"\"" +
                        L"\n\n" + L"(" + errorMessage + L")");
    }
#endif
    return true;
}


#ifdef FFS_WIN
zen::StatusRecycler zen::recycleBinStatus(const Zstring& pathName)
{
    std::vector<wchar_t> buffer(MAX_PATH + 1);
    if (::GetVolumePathName(applyLongPathPrefix(pathName).c_str(), //__in   LPCTSTR lpszFileName,
                            &buffer[0],                            //__out  LPTSTR lpszVolumePathName,
                            static_cast<DWORD>(buffer.size())))    //__in   DWORD cchBufferLength
    {
        Zstring rootPath = &buffer[0];
        if (!endsWith(rootPath, FILE_NAME_SEPARATOR)) //a trailing backslash is required
            rootPath += FILE_NAME_SEPARATOR;

        SHQUERYRBINFO recInfo = {};
        recInfo.cbSize = sizeof(recInfo);
        HRESULT rv = ::SHQueryRecycleBin(rootPath.c_str(), //__in_opt  LPCTSTR pszRootPath,
                                         &recInfo);        //__inout   LPSHQUERYRBINFO pSHQueryRBInfo
        return rv == S_OK ? STATUS_REC_EXISTS : STATUS_REC_MISSING;
    }
    return STATUS_REC_UNKNOWN;
}
#elif defined FFS_LINUX
/*
We really need access to a similar function to check whether a directory supports trashing and emit a warning if it does not!

The following function looks perfect, alas it is restricted to local files and to the implementation of GIO only:

    gboolean _g_local_file_has_trash_dir(const char* dirname, dev_t dir_dev);
    See: http://www.netmite.com/android/mydroid/2.0/external/bluetooth/glib/gio/glocalfileinfo.h

    Just checking for "G_FILE_ATTRIBUTE_ACCESS_CAN_TRASH" is not correct, since we find in
    http://www.netmite.com/android/mydroid/2.0/external/bluetooth/glib/gio/glocalfileinfo.c

            g_file_info_set_attribute_boolean (info, G_FILE_ATTRIBUTE_ACCESS_CAN_TRASH,
                                           writable && parent_info->has_trash_dir);

    => We're NOT interested in whether the specified folder can be trashed, but whether it supports thrashing its child elements! (Only support, not actual write access!)
    This renders G_FILE_ATTRIBUTE_ACCESS_CAN_TRASH useless for this purpose.
*/
#endif
bgstack15