summaryrefslogtreecommitdiffstats
path: root/filecopier.cpp
blob: 6256be143a4de5cbe2f6191e3b92ae95745c5cd1 (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
#include <QMutexLocker>
#include <QFile>

#include "filecopier.h"

FileCopier::FileCopier(QObject *parent) : QThread(parent), mCancel(false), mTotal(0), mCopied(0){}

void FileCopier::addJob(const QString &source, const QString &dest){
    QMutexLocker l(&mAddJobMutex);
    if(!mJobs.contains(source)){
        mJobs[source] = dest;
        ++mTotal;
    }
}

void FileCopier::run(){
    mCancel = false;
    mCopied = 0;
    while(!mJobs.isEmpty()){
        mAddJobMutex.lock();
        auto first = mJobs.constBegin();
        auto source = first.key();
        auto dest = first.value();
        mJobs.remove(source);
        mAddJobMutex.unlock();
        QString msg = QString(tr("Copy: %1 (%2/%3)")).arg(source).arg(QString::number(mCopied + 1)).arg(QString::number(mTotal));
        emit message(msg);
        QFile sFile(source);
        if(sFile.copy(dest)){
            ++mCopied;
            QString msg = QString(tr("Copied file %1/%2").arg(QString::number(mCopied)).arg(QString::number(mTotal)));
            emit message(msg);
        }else{
            QString msg = QString(tr("Failed to copy %1: %2").arg(source).arg(sFile.errorString()));
            emit message(msg);
        }
        QMutexLocker l(&mCancelMutex);
        if(mCancel){
            break;
        }
    }
    mCancel = false;
    mTotal = 0;
    mJobs.clear();
}

void FileCopier::cancel(){
    QMutexLocker l(&mCancelMutex);
    emit message(tr("Canceling copy jobs. Please wait..."));
    mCancel = true;
}