File indexing completed on 2025-01-05 04:37:24

0001 /*
0002     SPDX-FileCopyrightText: 2009 Joris Guisson <joris.guisson@gmail.com>
0003 
0004     SPDX-License-Identifier: GPL-2.0-or-later
0005 */
0006 #include "jobqueue.h"
0007 #include "job.h"
0008 #include "torrentcontrol.h"
0009 #include <util/log.h>
0010 
0011 namespace bt
0012 {
0013 JobQueue::JobQueue(bt::TorrentControl *parent)
0014     : QObject(parent)
0015     , tc(parent)
0016     , restart(false)
0017 {
0018 }
0019 
0020 JobQueue::~JobQueue()
0021 {
0022     killAll();
0023 }
0024 
0025 void JobQueue::enqueue(Job *job)
0026 {
0027     queue.append(job);
0028     if (queue.count() == 1)
0029         startNextJob();
0030 }
0031 
0032 bool JobQueue::runningJobs() const
0033 {
0034     return queue.count() > 0;
0035 }
0036 
0037 Job *JobQueue::currentJob()
0038 {
0039     return queue.isEmpty() ? nullptr : queue.front();
0040 }
0041 
0042 void JobQueue::startNextJob()
0043 {
0044     if (queue.isEmpty())
0045         return;
0046 
0047     Job *j = queue.front();
0048     connect(j, &Job::result, this, &JobQueue::jobDone);
0049     if (j->stopTorrent() && tc->getStats().running) {
0050         // stop the torrent if the job requires it
0051         tc->pause();
0052         restart = true;
0053     }
0054     j->start();
0055 }
0056 
0057 void JobQueue::jobDone(KJob *job)
0058 {
0059     if (queue.isEmpty() || queue.front() != job)
0060         return;
0061 
0062     // remove the job and start the next
0063     queue.pop_front();
0064     if (!queue.isEmpty()) {
0065         startNextJob();
0066     } else {
0067         if (restart) {
0068             tc->unpause();
0069             tc->allJobsDone();
0070             restart = false;
0071         } else
0072             tc->allJobsDone();
0073     }
0074 }
0075 
0076 void JobQueue::killAll()
0077 {
0078     if (queue.isEmpty())
0079         return;
0080 
0081     queue.front()->kill();
0082     qDeleteAll(queue);
0083     queue.clear();
0084 }
0085 
0086 }