cutter/src/common/AsyncTask.h

82 lines
1.5 KiB
C
Raw Normal View History

2018-05-26 16:21:23 +00:00
#ifndef ASYNCTASK_H
#define ASYNCTASK_H
#include "core/CutterCommon.h"
2018-05-26 16:21:23 +00:00
#include <QRunnable>
#include <QThreadPool>
2018-05-26 18:09:20 +00:00
#include <QMutex>
2018-05-27 14:51:01 +00:00
#include <QElapsedTimer>
2018-05-28 14:19:04 +00:00
#include <QSharedPointer>
#include <QList>
2018-05-26 18:09:20 +00:00
class AsyncTaskManager;
2018-05-26 16:21:23 +00:00
class CUTTER_EXPORT AsyncTask : public QObject, public QRunnable
2018-05-26 16:21:23 +00:00
{
Q_OBJECT
2018-05-26 18:09:20 +00:00
friend class AsyncTaskManager;
2018-05-26 16:21:23 +00:00
public:
2018-05-28 14:19:04 +00:00
using Ptr = QSharedPointer<AsyncTask>;
AsyncTask();
2018-05-26 18:09:20 +00:00
~AsyncTask();
2018-05-26 16:21:23 +00:00
void run() override final;
2018-05-26 18:09:20 +00:00
void wait();
bool wait(int timeout);
virtual void interrupt();
bool isInterrupted() { return interrupted; }
bool isRunning() { return running; }
2018-05-26 18:49:57 +00:00
const QString &getLog() { return logBuffer; }
2018-05-27 14:51:01 +00:00
const QElapsedTimer &getTimer() { return timer; }
qint64 getElapsedTime() { return timer.isValid() ? timer.elapsed() : 0; }
2018-05-27 14:51:01 +00:00
virtual QString getTitle() { return QString(); }
2018-05-26 18:49:57 +00:00
2018-05-26 18:09:20 +00:00
protected:
2018-05-26 16:21:23 +00:00
virtual void runTask() =0;
2018-05-26 18:49:57 +00:00
void log(QString s);
2018-05-26 16:21:23 +00:00
signals:
void finished();
2018-05-26 18:49:57 +00:00
void logChanged(const QString &log);
2018-05-26 18:09:20 +00:00
private:
bool running;
bool interrupted;
QMutex runningMutex;
2018-05-27 14:51:01 +00:00
QElapsedTimer timer;
2018-05-26 18:49:57 +00:00
QString logBuffer;
2018-05-26 18:09:20 +00:00
void prepareRun();
2018-05-26 16:21:23 +00:00
};
class AsyncTaskManager : public QObject
{
Q_OBJECT
private:
QThreadPool *threadPool;
2018-05-28 14:19:04 +00:00
QList<AsyncTask::Ptr> tasks;
2018-05-26 16:21:23 +00:00
public:
explicit AsyncTaskManager(QObject *parent = nullptr);
~AsyncTaskManager();
2018-05-28 14:19:04 +00:00
void start(AsyncTask::Ptr task);
bool getTasksRunning();
signals:
void tasksChanged();
2018-05-26 16:21:23 +00:00
};
#endif //ASYNCTASK_H