summaryrefslogtreecommitdiffstats
path: root/copyworker.cpp
blob: 0fbc8026d7b8d48006a1147ed1ecc6a5bb53ba44 (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
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
/*
  This program is free software; you can redistribute it and/or
  modify it under the terms of the GNU General Public License
  as published by the Free Software Foundation; either version
  2 of the License, or (at your option) any later version.
*/

#include <QFile>
#include <QFileInfo>
#include <QMutexLocker>

#include "copyworker.h"

CopyWorker::CopyWorker(QObject *parent) : QThread(parent), mMax(0) {}

void CopyWorker::enqueue(const QString &source, const QString &destination){
    QMutexLocker l(&mSourceMx);
    QPair<QString, QString> x = qMakePair<QString, QString>(source, destination);
    if(!mFiles.contains(x)){
        QFileInfo fi(source);
        mFiles.append(x);
        qint64 size = fi.size();
        mMax += size / 1024 / 1024;
    }
}

void CopyWorker::appendData(const QString &source, const QVariant &data){
    QList<QVariant> v = mData[source];
    v << data;
    mData.insert(source, v);
}

void CopyWorker::clear(){
    if(isRunning()){
        return;
    }
    QMutexLocker l(&mSourceMx);
    mFiles.clear();
    mMax = 0;
}

void CopyWorker::run(){
    qint64 total = 0;
    for(int i = 0; i < mFiles.size(); ++i){
        QPair<QString, QString> p = mFiles.at(i);
        QFileInfo cur(p.first);
        if(!cur.exists()){
            QString e = QString(tr("%1 has gone away from under us!")).arg(cur.fileName());
            emit error(e);
            return;
        }
        QFileInfo destFi(p.second);
        if(destFi.exists()){
            QString e = QString(tr("%1 already exists!")).arg(destFi.absoluteFilePath());
            emit error(e);
            return;
        }
        QFile sourceQF(p.first);
        QFile destQF(p.second);
        bool openSource = sourceQF.open(QIODevice::ReadOnly);
        bool openDest = destQF.open(QIODevice::WriteOnly);
        if(!openSource || !openDest){
            QString e = QString(tr("Failed to open source or destination on %1!")).arg(cur.fileName());
            emit error(e);
            return;
        }
        char *buf = new char[32768];
        qint64 len = 0;
        emit file(cur.fileName());
        while(!sourceQF.atEnd()){
            len = sourceQF.read(buf, 32768);
            destQF.write(buf, len);
            total += len;
            qint64 cur = total / 1024 / 1024;
            emit bytesRead(cur);
        }
        delete buf;
    }
    QString s = QString(tr("Done copying %1 file(s)")).arg(QString::number(mFiles.size()));
    emit success(s);
}