File indexing completed on 2024-12-01 12:29:48

0001 /*
0002  * BluezQt - Asynchronous Bluez wrapper library
0003  *
0004  * SPDX-FileCopyrightText: 2014 Alejandro Fiestas Olivares <afiestas@kde.org>
0005  * SPDX-FileCopyrightText: 2014 David Rosca <nowrep@gmail.com>
0006  *
0007  * SPDX-License-Identifier: LGPL-2.1-only OR LGPL-3.0-only OR LicenseRef-KDE-Accepted-LGPL
0008  */
0009 
0010 #include "job.h"
0011 #include "job_p.h"
0012 
0013 #include <QEventLoop>
0014 
0015 namespace BluezQt
0016 {
0017 JobPrivate::JobPrivate()
0018 {
0019     eventLoop = nullptr;
0020     error = Job::NoError;
0021     running = false;
0022     finished = false;
0023     killed = false;
0024 }
0025 
0026 Job::Job(QObject *parent)
0027     : QObject(parent)
0028     , d_ptr(new JobPrivate)
0029 {
0030     d_ptr->q_ptr = this;
0031 }
0032 
0033 Job::~Job()
0034 {
0035     delete d_ptr;
0036 }
0037 
0038 void Job::start()
0039 {
0040     d_func()->running = true;
0041     QMetaObject::invokeMethod(this, "doStart", Qt::QueuedConnection);
0042 }
0043 
0044 void Job::kill()
0045 {
0046     Q_D(Job);
0047     Q_ASSERT(!d->eventLoop);
0048 
0049     d->running = false;
0050     d->finished = true;
0051     d->killed = true;
0052     deleteLater();
0053 }
0054 
0055 void Job::emitResult()
0056 {
0057     Q_D(Job);
0058 
0059     if (d->killed) {
0060         return;
0061     }
0062 
0063     if (d->eventLoop) {
0064         d->eventLoop->quit();
0065     }
0066 
0067     d->running = false;
0068     d->finished = true;
0069     doEmitResult();
0070     deleteLater();
0071 }
0072 
0073 int Job::error() const
0074 {
0075     return d_func()->error;
0076 }
0077 
0078 QString Job::errorText() const
0079 {
0080     return d_func()->errorText;
0081 }
0082 
0083 bool Job::isRunning() const
0084 {
0085     return d_func()->running;
0086 }
0087 
0088 bool Job::isFinished() const
0089 {
0090     return d_func()->finished;
0091 }
0092 
0093 void Job::setError(int errorCode)
0094 {
0095     d_func()->error = errorCode;
0096 }
0097 
0098 void Job::setErrorText(const QString &errorText)
0099 {
0100     d_func()->errorText = errorText;
0101 }
0102 
0103 bool Job::exec()
0104 {
0105     Q_D(Job);
0106 
0107     Q_ASSERT(!d->eventLoop);
0108 
0109     QEventLoop loop(this);
0110     d->eventLoop = &loop;
0111 
0112     start();
0113     d->eventLoop->exec(QEventLoop::ExcludeUserInputEvents);
0114     d->running = false;
0115     d->finished = true;
0116 
0117     return d->error == NoError;
0118 }
0119 
0120 } // namespace BluezQt
0121 
0122 #include "moc_job.cpp"