diff options
Diffstat (limited to 'filecopier.cpp')
-rw-r--r-- | filecopier.cpp | 66 |
1 files changed, 66 insertions, 0 deletions
diff --git a/filecopier.cpp b/filecopier.cpp new file mode 100644 index 0000000..3475b74 --- /dev/null +++ b/filecopier.cpp @@ -0,0 +1,66 @@ +#include <QMutexLocker> +#include <QFile> + +#include "filecopier.h" + +FileCopier::FileCopier(QObject *parent) : QThread(parent), mCancel(false){} + +void FileCopier::addJob(const QString &source, const QString &dest){ + QMutexLocker l(&mAddJobMutex); + if(!mJobs.contains(source)){ + mJobs[source] = dest; + } +} + +QHash<QString, QString> FileCopier::jobs(){ + QMutexLocker l(&mAddJobMutex); + return mJobs; +} + +void FileCopier::run(){ + int bufsize = 16 * 1024 * 1024; + char *buf = new char[bufsize]; + mCancel = false; + while(!mJobs.isEmpty()){ + mAddJobMutex.lock(); + auto first = mJobs.constBegin(); + auto source = first.key(); + auto dest = first.value(); + mJobs.remove(source); + mAddJobMutex.unlock(); + QFile sFile(source); + QFile dFile(dest); + bool openSource = sFile.open(QIODevice::ReadOnly); + bool openDest = dFile.open(QIODevice::WriteOnly); + if(!openSource || !openDest){ + emit success(false, source); + goto cleanup; + } + emit newFile(source, sFile.size()); + int read = 0; + qint64 total = 0; + while(!sFile.atEnd()){ + mCancelMutex.lock(); + bool cancel = mCancel; + mCancelMutex.unlock(); + if(cancel){ + QFile::remove(dest); + emit success(false, source); + goto cleanup; + } + read = sFile.read(buf, bufsize); + dFile.write(buf, read); + total += read; + emit bytesRead(total); + } + emit success(true, source); + } + + cleanup: + delete buf; +} + +void FileCopier::cancel(){ + QMutexLocker l(&mCancelMutex); + mCancel = true; +} |