summaryrefslogtreecommitdiffstats
path: root/api/logic/FileSystem.cpp
blob: 1d8b290de03dea1b31f40fd494596043012d59f4 (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
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
// Licensed under the Apache-2.0 license. See README.md for details.

#include "FileSystem.h"

#include <QDir>
#include <QFile>
#include <QSaveFile>
#include <QFileInfo>
#include <QDebug>
#include <QUrl>
#include <QStandardPaths>
#include <QTextStream>

#if defined Q_OS_WIN32
    #include <windows.h>
    #include <string>
    #include <sys/utime.h>
    #include <winnls.h>
    #include <shobjidl.h>
    #include <objbase.h>
    #include <objidl.h>
    #include <shlguid.h>
    #include <shlobj.h>
#else
    #include <utime.h>
#endif

namespace FS {

void ensureExists(const QDir &dir)
{
    if (!QDir().mkpath(dir.absolutePath()))
    {
        throw FileSystemException("Unable to create folder " + dir.dirName() + " (" +
                                      dir.absolutePath() + ")");
    }
}

void write(const QString &filename, const QByteArray &data)
{
    ensureExists(QFileInfo(filename).dir());
    QSaveFile file(filename);
    if (!file.open(QSaveFile::WriteOnly))
    {
        throw FileSystemException("Couldn't open " + filename + " for writing: " +
                                  file.errorString());
    }
    if (data.size() != file.write(data))
    {
        throw FileSystemException("Error writing data to " + filename + ": " +
                                  file.errorString());
    }
    if (!file.commit())
    {
        throw FileSystemException("Error while committing data to " + filename + ": " +
                                  file.errorString());
    }
}

QByteArray read(const QString &filename)
{
    QFile file(filename);
    if (!file.open(QFile::ReadOnly))
    {
        throw FileSystemException("Unable to open " + filename + " for reading: " +
                                  file.errorString());
    }
    const qint64 size = file.size();
    QByteArray data(int(size), 0);
    const qint64 ret = file.read(data.data(), size);
    if (ret == -1 || ret != size)
    {
        throw FileSystemException("Error reading data from " + filename + ": " +
                                  file.errorString());
    }
    return data;
}

bool updateTimestamp(const QString& filename)
{
#ifdef Q_OS_WIN32
    std::wstring filename_utf_16 = filename.toStdWString();
    return (_wutime64(filename_utf_16.c_str(), nullptr) == 0);
#else
    QByteArray filenameBA = QFile::encodeName(filename);
    return (utime(filenameBA.data(), nullptr) == 0);
#endif
}

bool ensureFilePathExists(QString filenamepath)
{
    QFileInfo a(filenamepath);
    QDir dir;
    QString ensuredPath = a.path();
    bool success = dir.mkpath(ensuredPath);
    return success;
}

bool ensureFolderPathExists(QString foldernamepath)
{
    QFileInfo a(foldernamepath);
    QDir dir;
    QString ensuredPath = a.filePath();
    bool success = dir.mkpath(ensuredPath);
    return success;
}

bool copy::operator()(const QString &offset)
{
    //NOTE always deep copy on windows. the alternatives are too messy.
    #if defined Q_OS_WIN32
    m_followSymlinks = true;
    #endif

    auto src = PathCombine(m_src.absolutePath(), offset);
    auto dst = PathCombine(m_dst.absolutePath(), offset);

    QFileInfo currentSrc(src);
    if (!currentSrc.exists())
        return false;

    if(!m_followSymlinks && currentSrc.isSymLink())
    {
        qDebug() << "creating symlink" << src << " - " << dst;
        if (!ensureFilePathExists(dst))
        {
            qWarning() << "Cannot create path!";
            return false;
        }
        return QFile::link(currentSrc.symLinkTarget(), dst);
    }
    else if(currentSrc.isFile())
    {
        qDebug() << "copying file" << src << " - " << dst;
        if (!ensureFilePathExists(dst))
        {
            qWarning() << "Cannot create path!";
            return false;
        }
        return QFile::copy(src, dst);
    }
    else if(currentSrc.isDir())
    {
        qDebug() << "recursing" << offset;
        if (!ensureFolderPathExists(dst))
        {
            qWarning() << "Cannot create path!";
            return false;
        }
        QDir currentDir(src);
        for(auto & f : currentDir.entryList(QDir::Files | QDir::Dirs | QDir::NoDotAndDotDot | QDir::Hidden | QDir::System))
        {
            auto inner_offset = PathCombine(offset, f);
            // ignore and skip stuff that matches the blacklist.
            if(m_blacklist && m_blacklist->matches(inner_offset))
            {
                continue;
            }
            if(!operator()(inner_offset))
            {
                qWarning() << "Failed to copy" << inner_offset;
                return false;
            }
        }
    }
    else
    {
        qCritical() << "Copy ERROR: Unknown filesystem object:" << src;
        return false;
    }
    return true;
}

bool deletePath(QString path)
{
    bool OK = true;
    QDir dir(path);

    if (!dir.exists())
    {
        return OK;
    }
    auto allEntries = dir.entryInfoList(QDir::NoDotAndDotDot | QDir::System | QDir::Hidden |
                                        QDir::AllDirs | QDir::Files,
                                        QDir::DirsFirst);

    for(auto & info: allEntries)
    {
#if defined Q_OS_WIN32
        QString nativePath = QDir::toNativeSeparators(info.absoluteFilePath());
        auto wString = nativePath.toStdWString();
        DWORD dwAttrs = GetFileAttributesW(wString.c_str());
        // Windows: check for junctions, reparse points and other nasty things of that sort
        if(dwAttrs & FILE_ATTRIBUTE_REPARSE_POINT)
        {
            if (info.isFile())
            {
                OK &= QFile::remove(info.absoluteFilePath());
            }
            else if (info.isDir())
            {
                OK &= dir.rmdir(info.absoluteFilePath());
            }
        }
#else
        // We do not trust Qt with reparse points, but do trust it with unix symlinks.
        if(info.isSymLink())
        {
            OK &= QFile::remove(info.absoluteFilePath());
        }
#endif
        else if (info.isDir())
        {
            OK &= deletePath(info.absoluteFilePath());
        }
        else if (info.isFile())
        {
            OK &= QFile::remove(info.absoluteFilePath());
        }
        else
        {
            OK = false;
            qCritical() << "Delete ERROR: Unknown filesystem object:" << info.absoluteFilePath();
        }
    }
    OK &= dir.rmdir(dir.absolutePath());
    return OK;
}


QString PathCombine(const QString & path1, const QString & path2)
{
    if(!path1.size())
        return path2;
    if(!path2.size())
        return path1;
    return QDir::cleanPath(path1 + QDir::separator() + path2);
}

QString PathCombine(const QString & path1, const QString & path2, const QString & path3)
{
    return PathCombine(PathCombine(path1, path2), path3);
}

QString PathCombine(const QString & path1, const QString & path2, const QString & path3, const QString & path4)
{
    return PathCombine(PathCombine(path1, path2, path3), path4);
}

QString AbsolutePath(QString path)
{
    return QFileInfo(path).absolutePath();
}

QString ResolveExecutable(QString path)
{
    if (path.isEmpty())
    {
        return QString();
    }
    if(!path.contains('/'))
    {
        path = QStandardPaths::findExecutable(path);
    }
    QFileInfo pathInfo(path);
    if(!pathInfo.exists() || !pathInfo.isExecutable())
    {
        return QString();
    }
    return pathInfo.absoluteFilePath();
}

/**
 * Normalize path
 *
 * Any paths inside the current folder will be normalized to relative paths (to current)
 * Other paths will be made absolute
 */
QString NormalizePath(QString path)
{
    QDir a = QDir::currentPath();
    QString currentAbsolute = a.absolutePath();

    QDir b(path);
    QString newAbsolute = b.absolutePath();

    if (newAbsolute.startsWith(currentAbsolute))
    {
        return a.relativeFilePath(newAbsolute);
    }
    else
    {
        return newAbsolute;
    }
}

QString badFilenameChars = "\"\\/?<>:*|!";

QString RemoveInvalidFilenameChars(QString string, QChar replaceWith)
{
    for (int i = 0; i < string.length(); i++)
    {
        if (badFilenameChars.contains(string[i]))
        {
            string[i] = replaceWith;
        }
    }
    return string;
}

QString DirNameFromString(QString string, QString inDir)
{
    int num = 0;
    QString baseName = RemoveInvalidFilenameChars(string, '-');
    QString dirName;
    do
    {
        if(num == 0)
        {
            dirName = baseName;
        }
        else
        {
            dirName = baseName + QString::number(num);;
        }

        // If it's over 9000
        if (num > 9000)
            return "";
        num++;
    } while (QFileInfo(PathCombine(inDir, dirName)).exists());
    return dirName;
}

// Does the folder path contain any '!'? If yes, return true, otherwise false.
// (This is a problem for Java)
bool checkProblemticPathJava(QDir folder)
{
    QString pathfoldername = folder.absolutePath();
    return pathfoldername.contains("!", Qt::CaseInsensitive);
}

// Win32 crap
#if defined Q_OS_WIN

bool called_coinit = false;

HRESULT CreateLink(LPCSTR linkPath, LPCSTR targetPath, LPCSTR args)
{
    HRESULT hres;

    if (!called_coinit)
    {
        hres = CoInitialize(NULL);
        called_coinit = true;

        if (!SUCCEEDED(hres))
        {
            qWarning("Failed to initialize COM. Error 0x%08lX", hres);
            return hres;
        }
    }

    IShellLink *link;
    hres = CoCreateInstance(CLSID_ShellLink, NULL, CLSCTX_INPROC_SERVER, IID_IShellLink,
                            (LPVOID *)&link);

    if (SUCCEEDED(hres))
    {
        IPersistFile *persistFile;

        link->SetPath(targetPath);
        link->SetArguments(args);

        hres = link->QueryInterface(IID_IPersistFile, (LPVOID *)&persistFile);
        if (SUCCEEDED(hres))
        {
            WCHAR wstr[MAX_PATH];

            MultiByteToWideChar(CP_ACP, 0, linkPath, -1, wstr, MAX_PATH);

            hres = persistFile->Save(wstr, TRUE);
            persistFile->Release();
        }
        link->Release();
    }
    return hres;
}

#endif

QString getDesktopDir()
{
    return QStandardPaths::writableLocation(QStandardPaths::DesktopLocation);
}

// Cross-platform Shortcut creation
bool createShortCut(QString location, QString dest, QStringList args, QString name,
                          QString icon)
{
#if defined Q_OS_LINUX
    location = PathCombine(location, name + ".desktop");

    QFile f(location);
    f.open(QIODevice::WriteOnly | QIODevice::Text);
    QTextStream stream(&f);

    QString argstring;
    if (!args.empty())
        argstring = " '" + args.join("' '") + "'";

    stream << "[Desktop Entry]"
           << "\n";
    stream << "Type=Application"
           << "\n";
    stream << "TryExec=" << dest.toLocal8Bit() << "\n";
    stream << "Exec=" << dest.toLocal8Bit() << argstring.toLocal8Bit() << "\n";
    stream << "Name=" << name.toLocal8Bit() << "\n";
    stream << "Icon=" << icon.toLocal8Bit() << "\n";

    stream.flush();
    f.close();

    f.setPermissions(f.permissions() | QFileDevice::ExeOwner | QFileDevice::ExeGroup |
                     QFileDevice::ExeOther);

    return true;
#elif defined Q_OS_WIN
    // TODO: Fix
    //    QFile file(PathCombine(location, name + ".lnk"));
    //    WCHAR *file_w;
    //    WCHAR *dest_w;
    //    WCHAR *args_w;
    //    file.fileName().toWCharArray(file_w);
    //    dest.toWCharArray(dest_w);

    //    QString argStr;
    //    for (int i = 0; i < args.count(); i++)
    //    {
    //        argStr.append(args[i]);
    //        argStr.append(" ");
    //    }
    //    argStr.toWCharArray(args_w);

    //    return SUCCEEDED(CreateLink(file_w, dest_w, args_w));
    return false;
#else
    qWarning("Desktop Shortcuts not supported on your platform!");
    return false;
#endif
}
}