diff --git a/src/contentmanager.cpp b/src/contentmanager.cpp index 158f2cd..1caa68c 100644 --- a/src/contentmanager.cpp +++ b/src/contentmanager.cpp @@ -130,12 +130,36 @@ ContentManager::ContentManager(Library* library, kiwix::Downloader* downloader, setCategories(); setLanguages(); - m_downloadUpdateTimer.start(1000); - connect(&m_downloadUpdateTimer, &QTimer::timeout, - this, &ContentManager::updateDownloads); - connect(this, &ContentManager::downloadUpdated, this, &ContentManager::updateDownload); + + if ( mp_downloader ) { + startDownloadUpdaterThread(); + } +} + +void ContentManager::startDownloadUpdaterThread() +{ + // so that DownloadInfo can be copied across threads + qRegisterMetaType("DownloadInfo"); + + mp_downloadUpdaterThread = QThread::create([=]() { + while ( mp_downloadUpdaterThread != nullptr ) { + updateDownloads(); + QThread::msleep(1000); + } + }); + mp_downloadUpdaterThread->start(); +} + +ContentManager::~ContentManager() +{ + if ( mp_downloadUpdaterThread ) + { + QThread* t = mp_downloadUpdaterThread; + mp_downloadUpdaterThread = nullptr; // tell the thread to terminate + t->wait(); + } } void ContentManager::updateModel() diff --git a/src/contentmanager.h b/src/contentmanager.h index e27d88b..5023a5b 100644 --- a/src/contentmanager.h +++ b/src/contentmanager.h @@ -22,7 +22,7 @@ public: // types public: // functions explicit ContentManager(Library* library, kiwix::Downloader *downloader, QObject *parent = nullptr); - virtual ~ContentManager() {} + virtual ~ContentManager(); ContentManagerView* getView() { return mp_view; } void setLocal(bool local); @@ -84,6 +84,7 @@ private: // functions // the remote or local library (in that order). const kiwix::Book& getRemoteOrLocalBook(const QString &id); + void startDownloadUpdaterThread(); std::string startDownload(const kiwix::Book& book); void removeDownload(QString bookId); void downloadStarted(const kiwix::Book& book, const std::string& downloadId); @@ -96,7 +97,7 @@ private: // data kiwix::LibraryPtr mp_remoteLibrary; kiwix::Downloader* mp_downloader; ContentManagerModel::Downloads m_downloads; - QTimer m_downloadUpdateTimer; + QThread* mp_downloadUpdaterThread = nullptr; OpdsRequestManager m_remoteLibraryManager; ContentManagerView* mp_view; bool m_local = true;