File: filesystem.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 (356 lines) | stat: -rw-r--r-- 11,043 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
348
349
350
351
352
353
354
355
356
/*
    SPDX-FileCopyrightText: 2000 Shie Erlich <krusader@users.sourceforge.net>
    SPDX-FileCopyrightText: 2000 Rafi Yanai <krusader@users.sourceforge.net>
    SPDX-FileCopyrightText: 2004-2022 Krusader Krew <https://krusader.org>

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

#include "filesystem.h"

#include <memory>

// QtCore
#include <QDebug>
#include <QDir>
#include <QList>
// QtWidgets
#include <qplatformdefs.h>

#include <KIO/JobUiDelegate>
#include <KLocalizedString>
#include <KSharedConfig>

#include "../JobMan/jobman.h"
#include "../JobMan/krjob.h"
#include "../defaults.h"
#include "../krglobal.h"
#include "fileitem.h"
#include "krpermhandler.h"

FileSystem::FileSystem()
    : DirListerInterface(nullptr)
    , _isRefreshing(false)
{
}

FileSystem::~FileSystem()
{
    clear(_fileItems);
    // please don't remove this line. This informs the view about deleting the file items.
    emit cleared();
}

QList<QUrl> FileSystem::getUrls(const QStringList &names) const
{
    QList<QUrl> urls;
    for (const QString &name : names) {
        urls.append(getUrl(name));
    }
    return urls;
}

FileItem *FileSystem::getFileItem(const QString &name) const
{
    return _fileItems.contains(name) ? _fileItems.value(name) : nullptr;
}

KIO::filesize_t FileSystem::totalSize() const
{
    KIO::filesize_t temp = 0;
    for (FileItem *item : _fileItems.values()) {
        if (!item->isDir() && item->getName() != "." && item->getName() != "..") {
            temp += item->getSize();
        }
    }

    return temp;
}

QUrl FileSystem::ensureTrailingSlash(const QUrl &url)
{
    if (url.path().endsWith('/')) {
        return url;
    }

    QUrl adjustedUrl(url);
    adjustedUrl.setPath(adjustedUrl.path() + '/');
    return adjustedUrl;
}

QUrl FileSystem::preferLocalUrl(const QUrl &url)
{
    if (url.isEmpty() || !url.scheme().isEmpty())
        return url;

    QUrl adjustedUrl = url;
    adjustedUrl.setScheme("file");
    return adjustedUrl;
}

bool FileSystem::scanOrRefresh(const QUrl &directory, bool onlyScan)
{
    qDebug() << "from current dir=" << _currentDirectory.toDisplayString() << "; to=" << directory.toDisplayString();
    if (_isRefreshing) {
        // NOTE: this does not happen (unless async)";
        return false;
    }

    // workaround for krarc: find out if transition to local fs is wanted and adjust URL manually
    QUrl url = directory;
    if (_currentDirectory.scheme() == "krarc" && url.scheme() == "krarc" && QDir(url.path()).exists()) {
        url.setScheme("file");
    }

    const bool dirChange = !url.isEmpty() && cleanUrl(url) != _currentDirectory;

    const QUrl toRefresh = dirChange ? url.adjusted(QUrl::NormalizePathSegments) : _currentDirectory;
    if (!toRefresh.isValid()) {
        emit error(i18n("Malformed URL:\n%1", toRefresh.toDisplayString()));
        return false;
    }

    _isRefreshing = true;

    FileItemDict tempFileItems(_fileItems); // old file items are still used during refresh
    _fileItems.clear();
    if (dirChange)
        // show an empty directory while loading the new one and clear selection
        emit cleared();

    const bool refreshed = refreshInternal(toRefresh, onlyScan);
    _isRefreshing = false;

    if (!refreshed) {
        // cleanup and abort
        if (!dirChange)
            emit cleared();
        clear(tempFileItems);
        return false;
    }

    emit scanDone(dirChange);

    clear(tempFileItems);

    updateFilesystemInfo();

    return true;
}

void FileSystem::deleteFiles(const QList<QUrl> &urls, bool moveToTrash)
{
    KrJob *krJob = KrJob::createDeleteJob(urls, moveToTrash);
    connect(krJob, &KrJob::started, this, [=](KIO::Job *job) {
        connectJobToSources(job, urls);
    });

    if (moveToTrash) {
        // update destination: the trash bin (in case a panel/tab is showing it)
        connect(krJob, &KrJob::started, this, [=](KIO::Job *job) {
            // Note: the "trash" protocol should always have only one "/" after the "scheme:" part
            connect(job, &KIO::Job::result, this, [=]() {
                emit fileSystemChanged(QUrl("trash:/"), false);
            });
        });
    }

    krJobMan->manageJob(krJob);
}

void FileSystem::connectJobToSources(KJob *job, const QList<QUrl> &urls)
{
    if (!urls.isEmpty()) {
        // TODO we assume that all files were in the same directory and only emit one signal for
        // the directory of the first file URL (all subdirectories of parent are notified)
        const QUrl url = urls.first().adjusted(QUrl::RemoveFilename);
        connect(job, &KIO::Job::result, this, [=]() {
            emit fileSystemChanged(url, true);
        });
    }
}

void FileSystem::connectJobToDestination(KJob *job, const QUrl &destination)
{
    connect(job, &KIO::Job::result, this, [=]() {
        emit fileSystemChanged(destination, false);
    });
    // (additional) direct refresh if on local fs because watcher is too slow
    const bool refresh = cleanUrl(destination) == _currentDirectory && isLocal();
    connect(job, &KIO::Job::result, this, [=](KJob *job) {
        slotJobResult(job, refresh);
    });
}

bool FileSystem::showHiddenFiles()
{
    const KConfigGroup gl(krConfig, "Look&Feel");
    return gl.readEntry("Show Hidden", _ShowHidden);
}

void FileSystem::addFileItem(FileItem *item)
{
    _fileItems.insert(item->getName(), item);
}

FileItem *FileSystem::createLocalFileItem(const QString &name, const QString &directory, bool virt)
{
    const QDir dir = QDir(directory);
    const QString path = dir.filePath(name);
    const QByteArray pathByteArray = path.toLocal8Bit();
    const QString fileItemName = virt ? path : name;
    const QUrl fileItemUrl = QUrl::fromLocalFile(path);

    // read file status; in case of error create a "broken" file item
    QT_STATBUF stat_p;
    memset(&stat_p, 0, sizeof(stat_p));
    if (QT_LSTAT(pathByteArray.data(), &stat_p) < 0)
        return FileItem::createBroken(fileItemName, fileItemUrl);

    const KIO::filesize_t size = stat_p.st_size;
    bool isDir = S_ISDIR(stat_p.st_mode);
    const bool isLink = S_ISLNK(stat_p.st_mode);

    // for links, read link destination and determine whether it's broken or not
    QString linkDestination;
    bool brokenLink = false;
    if (isLink) {
        linkDestination = readLinkSafely(pathByteArray.data());

        if (linkDestination.isNull()) {
            brokenLink = true;
        } else {
            const QFileInfo linkFile(dir, linkDestination);
            if (!linkFile.exists())
                brokenLink = true;
            else if (linkFile.isDir())
                isDir = true;
        }
    }

    // TODO use statx available in glibc >= 2.28 supporting creation time (btime) and more

    // create normal file item
    return new FileItem(fileItemName,
                        fileItemUrl,
                        isDir,
                        size,
                        stat_p.st_mode,
                        stat_p.st_mtime,
                        stat_p.st_ctime,
                        stat_p.st_atime,
                        -1,
                        stat_p.st_uid,
                        stat_p.st_gid,
                        QString(),
                        QString(),
                        isLink,
                        linkDestination,
                        brokenLink);
}

QString FileSystem::readLinkSafely(const char *path)
{
    // inspired by the areadlink_with_size function from gnulib, which is used for coreutils
    // idea: start with a small buffer and gradually increase it as we discover it wasn't enough

    QT_OFF_T bufferSize = 1024; // start with 1 KiB
    QT_OFF_T maxBufferSize = std::numeric_limits<QT_OFF_T>::max();

    while (true) {
        // try to read the link
        std::unique_ptr<char[]> buffer(new char[bufferSize]);
        auto nBytesRead = readlink(path, buffer.get(), bufferSize);

        // should never happen, asserted by the readlink
        if (nBytesRead > bufferSize) {
            return QString();
        }

        // read failure
        if (nBytesRead < 0) {
            qDebug() << "Failed to read the link " << path;
            return QString();
        }

        // read success
        if (nBytesRead < bufferSize || nBytesRead == maxBufferSize) {
            return QString::fromLocal8Bit(buffer.get(), static_cast<int>(nBytesRead));
        }

        // increase the buffer and retry again
        // bufferSize < maxBufferSize is implied from previous checks
        if (bufferSize <= maxBufferSize / 2) {
            bufferSize *= 2;
        } else {
            bufferSize = maxBufferSize;
        }
    }
}

FileItem *FileSystem::createFileItemFromKIO(const KIO::UDSEntry &entry, const QUrl &directory, bool virt)
{
    const KFileItem kfi(entry, directory, true, true);

    const QString name = kfi.name();
    // ignore un-needed entries
    if (name.isEmpty() || name == "." || name == "..") {
        return nullptr;
    }

    const QString localPath = kfi.localPath();
    const QUrl url = !localPath.isEmpty() ? QUrl::fromLocalFile(localPath) : kfi.url();
    const QString fname = virt ? url.toDisplayString() : name;

    // get file statistics...
    const time_t mtime = kfi.time(KFileItem::ModificationTime).toSecsSinceEpoch();
    const time_t atime = kfi.time(KFileItem::AccessTime).toSecsSinceEpoch();
    const mode_t mode = kfi.mode() | kfi.permissions();
    const QDateTime creationTime = kfi.time(KFileItem::CreationTime);
    const time_t btime = creationTime.isValid() ? creationTime.toSecsSinceEpoch() : (time_t)-1;

    // NOTE: we could get the mimetype (and file icon) from the kfileitem here but this is very
    // slow. Instead, the file item class has it's own (faster) way to determine the file type.

    // NOTE: "broken link" flag is always false, checking link destination existence is
    // considered to be too expensive
    return new FileItem(fname,
                        url,
                        kfi.isDir(),
                        kfi.size(),
                        mode,
                        mtime,
                        -1,
                        atime,
                        btime,
                        (uid_t)-1,
                        (gid_t)-1,
                        kfi.user(),
                        kfi.group(),
                        kfi.isLink(),
                        kfi.linkDest(),
                        false,
                        kfi.ACL().asString(),
                        kfi.defaultACL().asString());
}

void FileSystem::slotJobResult(KJob *job, bool refresh)
{
    if (job->error() && job->uiDelegate()) {
        // show errors for modifying operations as popup (works always)
        job->uiDelegate()->showErrorMessage();
    }

    if (refresh) {
        FileSystem::refresh();
    }
}

void FileSystem::clear(FileItemDict &fileItems)
{
    QHashIterator<QString, FileItem *> lit(fileItems);
    while (lit.hasNext()) {
        delete lit.next().value();
    }
    fileItems.clear();
}