File: fileoperation.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 (447 lines) | stat: -rw-r--r-- 14,813 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
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
/*
 * Copyright (C) 2012 - 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 "fileoperation.h"
#include "fileoperationdialog.h"
#include <QTimer>
#include <QElapsedTimer>
#include <QMessageBox>
#include <QDebug>

#include "core/deletejob.h"
#include "core/trashjob.h"
#include "core/untrashjob.h"
#include "core/filetransferjob.h"
#include "core/filechangeattrjob.h"
#include "utilities.h"

namespace Fm {

#define SHOW_DLG_DELAY  1000

FileOperation::FileOperation(Type type, Fm::FilePathList srcPaths, QObject* parent):
    QObject(parent),
    type_{type},
    job_{nullptr},
    dlg_{nullptr},
    srcPaths_{std::move(srcPaths)},
    uiTimer_(nullptr),
    elapsedTimer_(nullptr),
    lastElapsed_(0),
    updateRemainingTime_(true),
    autoDestroy_(true) {

    switch(type_) {
    case Copy:
        job_ = new FileTransferJob(srcPaths_, FileTransferJob::Mode::COPY);
        break;
    case Move:
        job_ = new FileTransferJob(srcPaths_, FileTransferJob::Mode::MOVE);
        break;
    case Link:
        job_ = new FileTransferJob(srcPaths_, FileTransferJob::Mode::LINK);
        break;
    case Delete:
        job_ = new Fm::DeleteJob(srcPaths_);
        break;
    case Trash:
        job_ = new Fm::TrashJob(srcPaths_);
        break;
    case UnTrash:
        job_ = new Fm::UntrashJob(srcPaths_);
        break;
    case ChangeAttr:
        job_ = new Fm::FileChangeAttrJob(srcPaths_);
        break;
    default:
        break;
    }

    if(job_) {
        // automatically delete the job object when it's finished.
        job_->setAutoDelete(true);

        // new C++ jobs
        connect(job_, &Fm::Job::finished, this, &Fm::FileOperation::onJobFinish);
        connect(job_, &Fm::Job::cancelled, this, &Fm::FileOperation::onJobCancalled);
        connect(job_, &Fm::Job::error, this, &Fm::FileOperation::onJobError, Qt::BlockingQueuedConnection);
        connect(job_, &Fm::FileOperationJob::fileExists, this, &Fm::FileOperation::onJobFileExists, Qt::BlockingQueuedConnection);

        // we block the job deliberately until we prepare to start (initiailize the timer) so we can calculate elapsed time correctly.
        connect(job_, &Fm::FileOperationJob::preparedToRun, this, &Fm::FileOperation::onJobPrepared, Qt::BlockingQueuedConnection);
    }
}

void FileOperation::disconnectJob() {
    if(job_) {
        disconnect(job_, &Fm::Job::finished, this, &Fm::FileOperation::onJobFinish);
        disconnect(job_, &Fm::Job::cancelled, this, &Fm::FileOperation::onJobCancalled);
        disconnect(job_, &Fm::Job::error, this, &Fm::FileOperation::onJobError);
        disconnect(job_, &Fm::FileOperationJob::fileExists, this, &Fm::FileOperation::onJobFileExists);
        disconnect(job_, &Fm::FileOperationJob::preparedToRun, this, &Fm::FileOperation::onJobPrepared);
    }
}

FileOperation::~FileOperation() {
    if(uiTimer_) {
        uiTimer_->stop();
        delete uiTimer_;
        uiTimer_ = nullptr;
    }
    if(elapsedTimer_) {
        delete elapsedTimer_;
        elapsedTimer_ = nullptr;
    }
}

void FileOperation::setDestination(Fm::FilePath dest) {
    destPath_ = std::move(dest);
    switch(type_) {
    case Copy:
    case Move:
    case Link:
        if(job_) {
            static_cast<FileTransferJob*>(job_)->setDestDirPath(destPath_);
        }
        break;
    default:
        break;
    }
}

void FileOperation::setDestFiles(FilePathList destFiles) {
    switch(type_) {
    case Copy:
    case Move:
    case Link:
        if(job_) {
            static_cast<FileTransferJob*>(job_)->setDestPaths(std::move(destFiles));
        }
        break;
    default:
        break;
    }
}

void FileOperation::setChmod(mode_t newMode, mode_t newModeMask) {
    if(job_) {
        auto job = static_cast<FileChangeAttrJob*>(job_);
        job->setFileModeEnabled(true);
        job->setFileMode(newMode, newModeMask);
    }
}

void FileOperation::setChown(uid_t uid, gid_t gid) {
    if(job_) {
        auto job = static_cast<FileChangeAttrJob*>(job_);
        if(uid != INVALID_UID) {
            job->setOwnerEnabled(true);
            job->setOwner(uid);
        }
        if(gid != INVALID_GID) {
            job->setGroupEnabled(true);
            job->setGroup(gid);
        }
    }
}

void FileOperation::setRecursiveChattr(bool recursive) {
    if(job_) {
        auto job = static_cast<FileChangeAttrJob*>(job_);
        job->setRecursive(recursive);
    }
}

bool FileOperation::run() {
    delete uiTimer_;
    // run the job
    uiTimer_ = new QTimer();
    uiTimer_->start(SHOW_DLG_DELAY);
    connect(uiTimer_, &QTimer::timeout, this, &FileOperation::onUiTimeout);

    if(job_) {
        job_->runAsync();
        return true;
    }
    return false;
}

void FileOperation::cancel() {
    if(job_) {
        job_->cancel();
    }
}

void FileOperation::onUiTimeout() {
    if(dlg_) {
        // estimate remaining time based on past history
        if(job_) {
            Fm::FilePath curFilePath = job_->currentFile();
            // update progress bar
            double finishedRatio = job_->progress();
            if(finishedRatio > 0.0 && updateRemainingTime_) {
                dlg_->setPercent(int(finishedRatio * 100));

                std::uint64_t totalSize, totalCount, finishedSize, finishedCount;
                job_->totalAmount(totalSize, totalCount);
                job_->finishedAmount(finishedSize, finishedCount);

                // only show data transferred if the job progress can be calculated by file size.
                // for jobs not related to data transfer (for example: change attr, delete,...), hide the UI
                if(job_->calcProgressUsingSize()) {
                    dlg_->setDataTransferred(finishedSize, totalSize);
                }
                else {
                    dlg_->setFilesProcessed(finishedCount, totalCount);
                }

                double remainRatio = 1.0 - finishedRatio;
                gint64 remaining = elapsedTime() * (remainRatio / finishedRatio) / 1000;
                // qDebug("etime: %llu, finished: %lf, remain:%lf, remaining secs: %llu",
                //        elapsedTime(), finishedRatio, remainRatio, remaining);
                dlg_->setRemainingTime(remaining);
            }
            // update currently processed file
            if(curFilePath_ != curFilePath) {
                curFilePath_ = std::move(curFilePath);
                // FIXME: make this cleaner
                curFile = QString::fromUtf8(curFilePath_.toString().get());
                dlg_->setCurFile(curFile);
            }
        }
        // this timeout slot is called every 0.5 second.
        // by adding this flag, we can update remaining time every 1 second.
        updateRemainingTime_ = !updateRemainingTime_;
    }
    else {
        showDialog();
    }
}

void FileOperation::showDialog() {
    if(!dlg_) {
        dlg_ = new FileOperationDialog(this);
        dlg_->setSourceFiles(srcPaths_);

        if(destPath_) {
            dlg_->setDestPath(destPath_);
        }

        if(curFile.isEmpty()) {
            dlg_->setPrepared();
            dlg_->setCurFile(curFile);
        }
        uiTimer_->setInterval(500); // change the interval of the timer
        // now the timer is used to update current file display
        dlg_->show();
    }
}

void FileOperation::onJobFileExists(const FileInfo& src, const FileInfo& dest, Fm::FileOperationJob::FileExistsAction& response, FilePath& newDest) {
    pauseElapsedTimer();
    showDialog();
    response = dlg_->askRename(src, dest, newDest);
    resumeElapsedTimer();
}

void FileOperation::onJobCancalled() {
    qDebug("file operation is cancelled!");
}

void FileOperation::onJobError(const GErrorPtr& err, Fm::Job::ErrorSeverity severity, Fm::Job::ErrorAction& response) {
    pauseElapsedTimer();
    showDialog();
    response = Fm::Job::ErrorAction(dlg_->error(err.get(), severity));
    resumeElapsedTimer();
}

void FileOperation::onJobPrepared() {
    if(!elapsedTimer_) {
        elapsedTimer_ = new QElapsedTimer();
        elapsedTimer_->start();
    }
    if(dlg_) {
        dlg_->setPrepared();
    }
}

void FileOperation::onJobFinish() {
    disconnectJob();

    if(uiTimer_) {
        uiTimer_->stop();
        delete uiTimer_;
        uiTimer_ = nullptr;
    }

    if(dlg_) {
        dlg_->done(QDialog::Accepted);
        delete dlg_;
        dlg_ = nullptr;
    }
    Q_EMIT finished();

    bool tryReload = true;

    // special handling for trash job
    if(type_ == Trash && !job_->isCancelled()) {
        auto trashJob = static_cast<Fm::TrashJob*>(job_);
        /* some files cannot be trashed because underlying filesystems don't support it. */
        auto unsupportedFiles = trashJob->unsupportedFiles();
        if(!unsupportedFiles.empty()) { /* delete them instead */
            /* parent object is not destroyed before this */
            QWidget* pWidget = qobject_cast<QWidget*>(parent());
            if(QMessageBox::question(pWidget ? pWidget->window() : nullptr,
                                     tr("Error"),
                                     tr("Some files cannot be moved to trash can because "
                                        "the underlying file systems don't support this operation.\n"
                                        "Do you want to delete them instead?")) == QMessageBox::Yes) {
                deleteFiles(std::move(unsupportedFiles), false);
            }
            tryReload = false;
        }
    }

    // reload the containing folder if it is in use but does not have a file monitor
    if(tryReload) {
        if(!srcPaths_.empty() && (type_ == Trash || type_ == Delete || type_ == Move)) {
            auto parent_path = srcPaths_[0].parent();
            if(parent_path != destPath_) { // otherwise, it will be done below
                auto folder = Fm::Folder::findByPath(parent_path);
                if(folder && folder->isValid() && folder->isLoaded() && !folder->hasFileMonitor()) {
                    folder->reload();
                }
            }
        }
        if(destPath_) {
            auto folder = Fm::Folder::findByPath(destPath_);
            if(folder && folder->isValid() && folder->isLoaded() && !folder->hasFileMonitor()) {
                folder->reload();
            }
        }
    }

    if(autoDestroy_) {
        delete this;
    }
}

// static
FileOperation* FileOperation::copyFiles(Fm::FilePathList srcFiles, Fm::FilePath dest, QWidget* parent) {
    FileOperation* op = new FileOperation(FileOperation::Copy, std::move(srcFiles), parent);
    op->setDestination(dest);
    op->run();
    return op;
}

//static
FileOperation *FileOperation::copyFiles(FilePathList srcFiles, FilePathList destFiles, QWidget *parent) {
    qDebug("copy: %s -> %s", srcFiles[0].toString().get(), destFiles[0].toString().get());
    FileOperation* op = new FileOperation(FileOperation::Copy, std::move(srcFiles), parent);
    op->setDestFiles(std::move(destFiles));
    op->run();
    return op;
}

// static
FileOperation* FileOperation::moveFiles(Fm::FilePathList srcFiles, Fm::FilePath dest, QWidget* parent) {
    FileOperation* op = new FileOperation(FileOperation::Move, std::move(srcFiles), parent);
    op->setDestination(dest);
    op->run();
    return op;
}

//static
FileOperation *FileOperation::moveFiles(FilePathList srcFiles, FilePathList destFiles, QWidget *parent) {
    FileOperation* op = new FileOperation(FileOperation::Move, std::move(srcFiles), parent);
    op->setDestFiles(std::move(destFiles));
    op->run();
    return op;
}

//static
FileOperation* FileOperation::symlinkFiles(Fm::FilePathList srcFiles, Fm::FilePath dest, QWidget* parent) {
    FileOperation* op = new FileOperation(FileOperation::Link, std::move(srcFiles), parent);
    op->setDestination(dest);
    op->run();
    return op;
}

//static
FileOperation *FileOperation::symlinkFiles(FilePathList srcFiles, FilePathList destFiles, QWidget *parent) {
    FileOperation* op = new FileOperation(FileOperation::Link, std::move(srcFiles), parent);
    op->setDestFiles(std::move(destFiles));
    op->run();
    return op;
}

//static
FileOperation* FileOperation::deleteFiles(Fm::FilePathList srcFiles, bool prompt, QWidget* parent) {
    if(prompt) {
        int result = QMessageBox::warning(parent ? parent->window() : nullptr,
                                          tr("Confirm"),
                                          tr("Do you want to delete the selected files?"),
                                          QMessageBox::Yes | QMessageBox::No,
                                          QMessageBox::No);
        if(result != QMessageBox::Yes) {
            return nullptr;
        }
    }

    FileOperation* op = new FileOperation(FileOperation::Delete, std::move(srcFiles), parent);
    op->run();
    return op;
}

//static
FileOperation* FileOperation::trashFiles(Fm::FilePathList srcFiles, bool prompt, QWidget* parent) {
    if(prompt) {
        int result = QMessageBox::warning(parent ? parent->window() : nullptr,
                                          tr("Confirm"),
                                          tr("Do you want to move the selected files to trash can?"),
                                          QMessageBox::Yes | QMessageBox::No,
                                          QMessageBox::No);
        if(result != QMessageBox::Yes) {
            return nullptr;
        }
    }

    FileOperation* op = new FileOperation(FileOperation::Trash, std::move(srcFiles), parent);
    op->run();
    return op;
}

//static
FileOperation* FileOperation::unTrashFiles(Fm::FilePathList srcFiles, QWidget* parent) {
    FileOperation* op = new FileOperation(FileOperation::UnTrash, std::move(srcFiles), parent);
    op->run();
    return op;
}

// static
FileOperation* FileOperation::changeAttrFiles(Fm::FilePathList srcFiles, QWidget* parent) {
    //TODO
    FileOperation* op = new FileOperation(FileOperation::ChangeAttr, std::move(srcFiles), parent);
    op->run();
    return op;
}


} // namespace Fm