File: utilities.cpp

package info (click to toggle)
libfm-qt 0.14.1-9
  • links: PTS, VCS
  • area: main
  • in suites: buster
  • size: 4,124 kB
  • sloc: cpp: 20,397; ansic: 5,719; xml: 35; makefile: 11
file content (388 lines) | stat: -rw-r--r-- 12,757 bytes parent folder | download | duplicates (2)
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
/*
 * Copyright (C) 2013 - 2015  Hong Jen Yee (PCMan) <pcman.tw@gmail.com>
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
 *
 */

#include "utilities.h"
#include "utilities_p.h"
#include <QApplication>
#include <QClipboard>
#include <QMimeData>
#include <QUrl>
#include <QList>
#include <QStringBuilder>
#include <QMessageBox>
#include "fileoperation.h"
#include <QEventLoop>

#include <pwd.h>
#include <grp.h>
#include <stdlib.h>
#include <glib.h>

namespace Fm {

Fm::FilePathList pathListFromUriList(const char* uriList) {
    Fm::FilePathList pathList;
    char** uris = g_strsplit_set(uriList, "\r\n", -1);
    for(char** uri = uris; *uri; ++uri) {
        if(**uri != '\0') {
            pathList.push_back(Fm::FilePath::fromUri(*uri));
        }
    }
    g_strfreev(uris);
    return pathList;
}

QByteArray pathListToUriList(const Fm::FilePathList& paths) {
    QByteArray uriList;
    for(auto& path: paths) {
        uriList += path.uri().get();
        uriList += "\r\n";
    }
    return uriList;
}

Fm::FilePathList pathListFromQUrls(QList<QUrl> urls) {
    Fm::FilePathList pathList;
    for(auto it = urls.cbegin(); it != urls.cend(); ++it) {
        auto path = Fm::FilePath::fromUri(it->toString().toUtf8().constData());
        pathList.push_back(std::move(path));
    }
    return pathList;
}

std::pair<Fm::FilePathList, bool> parseClipboardData(const QMimeData& data) {
    bool isCut = false;
    Fm::FilePathList paths;

    if(data.hasFormat("x-special/gnome-copied-files")) {
        // Gnome, LXDE, and XFCE
        QByteArray gnomeData = data.data("x-special/gnome-copied-files");
        char* pdata = gnomeData.data();
        char* eol = strchr(pdata, '\n');

        if(eol) {
            *eol = '\0';
            isCut = (strcmp(pdata, "cut") == 0 ? true : false);
            paths = pathListFromUriList(eol + 1);
        }
    }

    if(paths.empty() && data.hasUrls()) {
        // The KDE way
        paths = Fm::pathListFromQUrls(data.urls());
        QByteArray cut = data.data(QStringLiteral("application/x-kde-cutselection"));
        if(!cut.isEmpty() && QChar::fromLatin1(cut.at(0)) == QLatin1Char('1')) {
            isCut = true;
        }
    }

    return std::make_pair(paths, isCut);
}

void pasteFilesFromClipboard(const Fm::FilePath& destPath, QWidget* parent) {
    QClipboard* clipboard = QApplication::clipboard();
    const QMimeData* data = clipboard->mimeData();
    Fm::FilePathList paths;
    bool isCut = false;

    std::tie(paths, isCut) = parseClipboardData(*data);

    if(!paths.empty()) {
        if(isCut) {
            FileOperation::moveFiles(paths, destPath, parent);
            clipboard->clear(QClipboard::Clipboard);
        }
        else {
            FileOperation::copyFiles(paths, destPath, parent);
        }
    }
}

void copyFilesToClipboard(const Fm::FilePathList& files) {
    QClipboard* clipboard = QApplication::clipboard();
    QMimeData* data = new QMimeData();
    QByteArray ba;
    auto urilist = pathListToUriList(files);

    // Add current pid to trace cut/copy operations to current app
    data->setData(QStringLiteral("text/x-libfmqt-pid"), ba.setNum(QCoreApplication::applicationPid()));
    // Gnome, LXDE, and XFCE
    // Note: the standard text/urilist format uses CRLF for line breaks, but gnome format uses LF only
    data->setData("x-special/gnome-copied-files", QByteArray("copy\n") + urilist.replace("\r\n", "\n"));
    // The KDE way
    data->setData("text/uri-list", urilist);
    // data->setData(QStringLiteral("application/x-kde-cutselection"), QByteArrayLiteral("0"));
    clipboard->setMimeData(data);
}

void cutFilesToClipboard(const Fm::FilePathList& files) {
    QClipboard* clipboard = QApplication::clipboard();
    QMimeData* data = new QMimeData();
    QByteArray ba;
    auto urilist = pathListToUriList(files);

    // Add current pid to trace cut/copy operations to current app
    data->setData(QStringLiteral("text/x-libfmqt-pid"), ba.setNum(QCoreApplication::applicationPid()));
    // Gnome, LXDE, and XFCE
    // Note: the standard text/urilist format uses CRLF for line breaks, but gnome format uses LF only
    data->setData("x-special/gnome-copied-files", QByteArray("cut\n") + urilist.replace("\r\n", "\n"));
    // The KDE way
    data->setData("text/uri-list", urilist);
    data->setData(QStringLiteral("application/x-kde-cutselection"), QByteArrayLiteral("1"));
    clipboard->setMimeData(data);
}

bool isCurrentPidClipboardData(const QMimeData& data) {
    QByteArray clip_pid = data.data(QStringLiteral("text/x-libfmqt-pid"));
    QByteArray curr_pid;
    curr_pid.setNum(QCoreApplication::applicationPid());

    return !clip_pid.isEmpty() && clip_pid == curr_pid;
}

bool changeFileName(const Fm::FilePath& filePath, const QString& newName, QWidget* parent, bool showMessage) {
    auto parent_path = filePath.parent();
    auto dest = parent_path.child(newName.toLocal8Bit().constData());
    Fm::GErrorPtr err;
    if(!g_file_move(filePath.gfile().get(), dest.gfile().get(),
                    GFileCopyFlags(G_FILE_COPY_ALL_METADATA |
                                   G_FILE_COPY_NO_FALLBACK_FOR_MOVE |
                                   G_FILE_COPY_NOFOLLOW_SYMLINKS),
                    nullptr, /* make this cancellable later. */
                    nullptr, nullptr, &err)) {
        if (showMessage){
            QMessageBox::critical(parent ? parent->window() : nullptr, QObject::tr("Error"), err.message());
        }
        return false;
    }

    // reload the containing folder if it is in use but does not have a file monitor
    auto folder = Fm::Folder::findByPath(parent_path);
    if(folder && folder->isValid() && folder->isLoaded() && !folder->hasFileMonitor()) {
        folder->reload();
    }

    return true;
}

bool renameFile(std::shared_ptr<const Fm::FileInfo> file, QWidget* parent) {
    FilenameDialog dlg(parent ? parent->window() : nullptr);
    dlg.setWindowTitle(QObject::tr("Rename File"));
    dlg.setLabelText(QObject::tr("Please enter a new name:"));
    // FIXME: what's the best way to handle non-UTF8 filename encoding here?
    auto old_name = QString::fromStdString(file->name());
    dlg.setTextValue(old_name);

    if(file->isDir()) { // select filename extension for directories
        dlg.setSelectExtension(true);
    }

    if(dlg.exec() != QDialog::Accepted) {
        return false; // stop multiple renaming
    }

    QString new_name = dlg.textValue();
    if(new_name == old_name) {
        return true; // let multiple renaming continue
    }
    changeFileName(file->path(), new_name, parent);
    return true;
}

// templateFile is a file path used as a template of the new file.
void createFileOrFolder(CreateFileType type, FilePath parentDir, const TemplateItem* templ, QWidget* parent) {
    QString defaultNewName;
    QString prompt;
    QString dialogTitle = type == CreateNewFolder ? QObject::tr("Create Folder")
                          : QObject::tr("Create File");

    switch(type) {
    case CreateNewTextFile:
        prompt = QObject::tr("Please enter a new file name:");
        defaultNewName = QObject::tr("New text file");
        break;

    case CreateNewFolder:
        prompt = QObject::tr("Please enter a new folder name:");
        defaultNewName = QObject::tr("New folder");
        break;

    case CreateWithTemplate: {
        auto mime = templ->mimeType();
        prompt = QObject::tr("Enter a name for the new %1:").arg(mime->desc());
        defaultNewName = QString::fromStdString(templ->name());
    }
    break;
    }

_retry:
    // ask the user to input a file name
    bool ok;
    QString new_name = QInputDialog::getText(parent ? parent->window() : nullptr,
                       dialogTitle,
                       prompt,
                       QLineEdit::Normal,
                       defaultNewName,
                       &ok);

    if(!ok) {
        return;
    }

    auto dest = parentDir.child(new_name.toLocal8Bit().data());
    Fm::GErrorPtr err;
    switch(type) {
    case CreateNewTextFile: {
        Fm::GFileOutputStreamPtr f{g_file_create(dest.gfile().get(), G_FILE_CREATE_NONE, nullptr, &err), false};
        if(f) {
            g_output_stream_close(G_OUTPUT_STREAM(f.get()), nullptr, nullptr);
        }
        break;
    }
    case CreateNewFolder:
        g_file_make_directory(dest.gfile().get(), nullptr, &err);
        break;
    case CreateWithTemplate:
        // copy the template file to its destination
        FileOperation::copyFile(templ->filePath(), dest, parent);
        break;
    }
    if(err) {
        if(err.domain() == G_IO_ERROR && err.code() == G_IO_ERROR_EXISTS) {
            err.reset();
            goto _retry;
        }

        QMessageBox::critical(parent ? parent->window() : nullptr, QObject::tr("Error"), err.message());
    }
    else { // reload the containing folder if it is in use but does not have a file monitor
        auto folder = Fm::Folder::findByPath(parentDir);
        if(folder && folder->isValid() && folder->isLoaded() && !folder->hasFileMonitor()) {
            folder->reload();
        }
    }
}

uid_t uidFromName(QString name) {
    uid_t ret;
    if(name.isEmpty()) {
        return INVALID_UID;
    }
    if(name.at(0).digitValue() != -1) {
        ret = uid_t(name.toUInt());
    }
    else {
        struct passwd* pw = getpwnam(name.toLatin1());
        // FIXME: use getpwnam_r instead later to make it reentrant
        ret = pw ? pw->pw_uid : INVALID_UID;
    }

    return ret;
}

QString uidToName(uid_t uid) {
    QString ret;
    struct passwd* pw = getpwuid(uid);

    if(pw) {
        ret = pw->pw_name;
    }
    else {
        ret = QString::number(uid);
    }

    return ret;
}

gid_t gidFromName(QString name) {
    gid_t ret;
    if(name.isEmpty()) {
        return INVALID_GID;
    }
    if(name.at(0).digitValue() != -1) {
        ret = gid_t(name.toUInt());
    }
    else {
        // FIXME: use getgrnam_r instead later to make it reentrant
        struct group* grp = getgrnam(name.toLatin1());
        ret = grp ? grp->gr_gid : INVALID_GID;
    }

    return ret;
}

QString gidToName(gid_t gid) {
    QString ret;
    struct group* grp = getgrgid(gid);

    if(grp) {
        ret = grp->gr_name;
    }
    else {
        ret = QString::number(gid);
    }

    return ret;
}

int execModelessDialog(QDialog* dlg) {
    // FIXME: this does much less than QDialog::exec(). Will this work flawlessly?
    QEventLoop loop;
    QObject::connect(dlg, &QDialog::finished, &loop, &QEventLoop::quit);
    // DialogExec does not seem to be documented in the Qt API doc?
    // However, in the source code of QDialog::exec(), it's used so let's use it too.
    dlg->show();
    (void)loop.exec(QEventLoop::DialogExec);
    return dlg->result();
}

// check if GVFS can support this uri scheme (lower case)
// NOTE: this does not work reliably due to some problems in gio/gvfs and causes bug lxqt/lxqt#512
// https://github.com/lxqt/lxqt/issues/512
// Use uriExists() whenever possible.
bool isUriSchemeSupported(const char* uriScheme) {
    const gchar* const* schemes = g_vfs_get_supported_uri_schemes(g_vfs_get_default());
    if(Q_UNLIKELY(schemes == nullptr)) {
        return false;
    }
    for(const gchar * const* scheme = schemes; *scheme; ++scheme)
        if(strcmp(uriScheme, *scheme) == 0) {
            return true;
        }
    return false;
}

// check if the URI exists.
// NOTE: this is a blocking call possibly involving I/O.
// So it's better to use it in limited cases, like checking trash:// or computer://.
// Avoid calling this on a slow filesystem.
// Checking "network:///" is very slow, for example.
bool uriExists(const char* uri) {
    GFile* gf = g_file_new_for_uri(uri);
    bool ret = (bool)g_file_query_exists(gf, nullptr);
    g_object_unref(gf);
    return ret;
}

QString formatFileSize(uint64_t size, bool useSI) {
    Fm::CStrPtr str{g_format_size_full(size, useSI ? G_FORMAT_SIZE_DEFAULT : G_FORMAT_SIZE_IEC_UNITS)};
    return QString(str.get());
}

} // namespace Fm