File: virtualfilesystem.cpp

package info (click to toggle)
krusader 2%3A2.9.0-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 25,448 kB
  • sloc: cpp: 56,112; ansic: 1,187; xml: 811; sh: 23; makefile: 3
file content (347 lines) | stat: -rw-r--r-- 10,833 bytes parent folder | download
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
/*
    SPDX-FileCopyrightText: 2003 Shie Erlich <erlich@users.sourceforge.net>
    SPDX-FileCopyrightText: 2003 Rafi Yanai <yanai@users.sourceforge.net>
    SPDX-FileCopyrightText: 2004-2022 Krusader Krew <https://krusader.org>

    SPDX-License-Identifier: GPL-2.0-or-later
*/

#include "virtualfilesystem.h"

// QtCore
#include <QDir>
#include <QEventLoop>
#include <QUrl>
// QtWidgets
#include <QApplication>

#include <KFileItem>
#include <KIO/CopyJob>
#include <KIO/DeleteJob>
#include <KIO/DirectorySizeJob>
#include <KIO/StatJob>
#include <KLocalizedString>
#include <KMessageBox>
#include <KUrlMimeData>

#include "../defaults.h"
#include "../krglobal.h"
#include "../krservices.h"
#include "fileitem.h"

#define VIRTUALFILESYSTEM_DB "virtualfilesystem.db"

QHash<QString, QList<QUrl> *> VirtualFileSystem::_virtFilesystemDict;
QHash<QString, QString> VirtualFileSystem::_metaInfoDict;

VirtualFileSystem::VirtualFileSystem()
{
    if (_virtFilesystemDict.isEmpty()) {
        restore();
    }

    _type = FS_VIRTUAL;
}

void VirtualFileSystem::copyFiles(const QList<QUrl> &urls,
                                  const QUrl &destination,
                                  KIO::CopyJob::CopyMode /*mode*/,
                                  bool /*showProgressInfo*/,
                                  JobMan::StartMode /*startMode*/)
{
    const QString dir = QDir(destination.path()).absolutePath().remove('/');

    if (dir.isEmpty()) {
        showError(
            i18n("You cannot copy files directly to the 'virt:/' folder.\n"
                 "You can create a sub folder and copy your files into it."));
        return;
    }

    if (!_virtFilesystemDict.contains(dir)) {
        mkDirInternal(dir);
    }

    QList<QUrl> *urlList = _virtFilesystemDict[dir];
    for (const QUrl &fileUrl : urls) {
        if (!urlList->contains(fileUrl)) {
            urlList->push_back(fileUrl);
        }
    }

    emit fileSystemChanged(QUrl("virt:///" + dir), false); // may call refresh()
}

void VirtualFileSystem::dropFiles(const QUrl &destination, QDropEvent *event, QWidget *)
{
    const QList<QUrl> &urls = KUrlMimeData::urlsFromMimeData(event->mimeData());
    // dropping on virtual filesystem is always copy operation
    copyFiles(urls, destination);
}

void VirtualFileSystem::addFiles(const QList<QUrl> &fileUrls, KIO::CopyJob::CopyMode /*mode*/, const QString &dir)
{
    QUrl destination(_currentDirectory);
    if (!dir.isEmpty()) {
        destination.setPath(QDir::cleanPath(destination.path() + '/' + dir));
    }
    copyFiles(fileUrls, destination);
}

void VirtualFileSystem::remove(const QStringList &fileNames)
{
    const QString parentDir = currentDir();
    if (parentDir == "/") { // remove virtual directory
        for (const QString &filename : fileNames) {
            _virtFilesystemDict["/"]->removeAll(QUrl(QStringLiteral("virt:/") + filename));
            delete _virtFilesystemDict[filename];
            _virtFilesystemDict.remove(filename);
            _metaInfoDict.remove(filename);
        }
    } else {
        // remove the URLs from the collection
        for (const QString &name : fileNames) {
            if (_virtFilesystemDict.find(parentDir) != _virtFilesystemDict.end()) {
                QList<QUrl> *urlList = _virtFilesystemDict[parentDir];
                urlList->removeAll(getUrl(name));
            }
        }
    }

    emit fileSystemChanged(currentDirectory(), true); // will call refresh()
}

QUrl VirtualFileSystem::getUrl(const QString &name) const
{
    FileItem *item = getFileItem(name);
    if (!item) {
        return QUrl(); // not found
    }

    return item->getUrl();
}

void VirtualFileSystem::mkDir(const QString &name)
{
    if (currentDir() != "/") {
        showError(i18n("Creating new folders is allowed only in the 'virt:/' folder."));
        return;
    }

    mkDirInternal(name);

    emit fileSystemChanged(currentDirectory(), false); // will call refresh()
}

void VirtualFileSystem::rename(const QString &fileName, const QString &newName)
{
    FileItem *item = getFileItem(fileName);
    if (!item)
        return; // not found

    if (currentDir() == "/") { // rename virtual directory
        _virtFilesystemDict["/"]->append(QUrl(QStringLiteral("virt:/") + newName));
        _virtFilesystemDict["/"]->removeAll(QUrl(QStringLiteral("virt:/") + fileName));
        _virtFilesystemDict.insert(newName, _virtFilesystemDict.take(fileName));
        refresh();
        return;
    }

    // newName can be a (local) path or a full url
    QUrl dest(newName);
    if (dest.scheme().isEmpty())
        dest.setScheme("file");

    // add the new url to the list
    // the list is refreshed, only existing files remain -
    // so we don't have to worry if the job was successful
    _virtFilesystemDict[currentDir()]->append(dest);

    KIO::Job *job = KIO::moveAs(item->getUrl(), dest, KIO::HideProgressInfo);
    connect(job, &KIO::Job::result, this, [=](KJob *job) {
        slotJobResult(job, false);
    });
    connect(job, &KIO::Job::result, this, [=]() {
        emit fileSystemChanged(currentDirectory(), false);
    });
}

bool VirtualFileSystem::canMoveToTrash(const QStringList &fileNames) const
{
    if (isRoot())
        return false;

    for (const QString &fileName : fileNames) {
        if (!getUrl(fileName).isLocalFile()) {
            return false;
        }
    }
    return true;
}

void VirtualFileSystem::setMetaInformation(const QString &info)
{
    _metaInfoDict[currentDir()] = info;
}

// ==== protected ====

bool VirtualFileSystem::refreshInternal(const QUrl &directory, bool onlyScan)
{
    _currentDirectory = cleanUrl(directory);
    _currentDirectory.setHost("");
    // remove invalid subdirectories
    _currentDirectory.setPath('/' + _currentDirectory.path().remove('/'));

    if (!_virtFilesystemDict.contains(currentDir())) {
        if (onlyScan) {
            return false; // virtual dir does not exist
        } else {
            // Silently creating non-existing directories here. The search and locate tools
            // expect this. And the user can enter some directory and it will be created.
            mkDirInternal(currentDir());
            save();
            // infinite loop possible
            // emit fileSystemChanged(currentDirectory());
            return true;
        }
    }

    QList<QUrl> *urlList = _virtFilesystemDict[currentDir()];

    if (!onlyScan) {
        const QString metaInfo = _metaInfoDict[currentDir()];
        emit fileSystemInfoChanged(metaInfo.isEmpty() ? i18n("Virtual filesystem") : metaInfo, "", 0, 0);
    }

    QMutableListIterator<QUrl> it(*urlList);
    while (it.hasNext()) {
        const QUrl url = it.next();
        FileItem *item = createFileItem(url);
        if (!item) { // remove URL from the list for a file that no longer exists
            it.remove();
        } else {
            addFileItem(item);
        }
    }

    save();
    return true;
}

// ==== private ====

void VirtualFileSystem::mkDirInternal(const QString &name)
{
    // clean path, consistent with currentDir()
    QString dirName = name;
    dirName = dirName.remove('/');
    if (dirName.isEmpty())
        dirName = '/';

    _virtFilesystemDict.insert(dirName, new QList<QUrl>());
    _virtFilesystemDict["/"]->append(QUrl(QStringLiteral("virt:/") + dirName));
}

void VirtualFileSystem::save()
{
    KConfig *db = &VirtualFileSystem::getVirtDB();
    db->deleteGroup("virt_db");
    KConfigGroup group(db, "virt_db");

    QHashIterator<QString, QList<QUrl> *> it(_virtFilesystemDict);
    while (it.hasNext()) {
        it.next();
        QList<QUrl> *urlList = it.value();

        QList<QUrl>::iterator url;
        QStringList entry;
        for (url = urlList->begin(); url != urlList->end(); ++url) {
            entry.append((*url).toDisplayString());
        }
        // KDE 4.0 workaround: 'Item_' prefix is added as KConfig fails on 1 char names (such as /)
        group.writeEntry("Item_" + it.key(), entry);
        group.writeEntry("MetaInfo_" + it.key(), _metaInfoDict[it.key()]);
    }

    db->sync();
}

void VirtualFileSystem::restore()
{
    KConfig *db = &VirtualFileSystem::getVirtDB();
    const KConfigGroup dbGrp(db, "virt_db");

    const QMap<QString, QString> map = db->entryMap("virt_db");
    QMapIterator<QString, QString> it(map);
    while (it.hasNext()) {
        it.next();

        // KDE 4.0 workaround: check and remove 'Item_' prefix
        if (!it.key().startsWith(QLatin1String("Item_")))
            continue;
        const QString key = it.key().mid(5);

        const QList<QUrl> urlList = KrServices::toUrlList(dbGrp.readEntry(it.key(), QStringList()));
        _virtFilesystemDict.insert(key, new QList<QUrl>(urlList));
        _metaInfoDict.insert(key, dbGrp.readEntry("MetaInfo_" + key, QString()));
    }

    if (!_virtFilesystemDict["/"]) { // insert root element if missing for some reason
        _virtFilesystemDict.insert("/", new QList<QUrl>());
    }
}

FileItem *VirtualFileSystem::createFileItem(const QUrl &url)
{
    if (url.scheme() == "virt") { // return a virtual directory in root
        QString path = url.path().mid(1);
        if (path.isEmpty())
            path = '/';
        return FileItem::createVirtualDir(path, url);
    }

    const QUrl directory = url.adjusted(QUrl::RemoveFilename);

    if (url.isLocalFile()) {
        QFileInfo file(url.path());
        return file.exists() ? FileSystem::createLocalFileItem(url.fileName(), directory.path(), true) : nullptr;
    }

    KIO::StatJob *statJob = KIO::stat(url, KIO::HideProgressInfo);
    connect(statJob, &KIO::Job::result, this, &VirtualFileSystem::slotStatResult);

    // ugly: we have to wait here until the stat job is finished
    QEventLoop eventLoop;
    connect(statJob, &KJob::finished, &eventLoop, &QEventLoop::quit);
    eventLoop.exec(); // blocking until quit()

    if (_fileEntry.count() == 0) {
        return nullptr; // stat job failed
    }

    if (!_fileEntry.contains(KIO::UDSEntry::UDS_MODIFICATION_TIME)) {
        // TODO this also happens for FTP directories
        return nullptr; // file not found
    }

    return FileSystem::createFileItemFromKIO(_fileEntry, directory, true);
}

KConfig &VirtualFileSystem::getVirtDB()
{
    // virtualfilesystem_db = new KConfig("data",VIRTUALFILESYSTEM_DB,KConfig::NoGlobals);
    static KConfig db(VIRTUALFILESYSTEM_DB, KConfig::CascadeConfig, QStandardPaths::AppDataLocation);
    return db;
}

void VirtualFileSystem::slotStatResult(KJob *job)
{
    _fileEntry = job->error() ? KIO::UDSEntry() : dynamic_cast<KIO::StatJob *>(job)->statResult();
}

void VirtualFileSystem::showError(const QString &error)
{
    QWidget *window = QApplication::activeWindow();
    KMessageBox::error(window, error); // window can be null, is allowed
}