From f6931197d273cf61b74ce57f3011b67849d14a8a Mon Sep 17 00:00:00 2001 From: Damien Elmes Date: Mon, 4 May 2020 21:30:41 +1000 Subject: [PATCH] add helper to run background task with progress --- qt/aqt/main.py | 2 +- qt/aqt/taskman.py | 24 +++++++++++++++++++++--- 2 files changed, 22 insertions(+), 4 deletions(-) diff --git a/qt/aqt/main.py b/qt/aqt/main.py index 9c5958af7..bb4fa0df0 100644 --- a/qt/aqt/main.py +++ b/qt/aqt/main.py @@ -89,7 +89,7 @@ class AnkiQt(QMainWindow): self.state = "startup" self.opts = opts self.col: Optional[_Collection] = None - self.taskman = TaskManager() + self.taskman = TaskManager(self) self.media_syncer = MediaSyncer(self) aqt.mw = self self.app = app diff --git a/qt/aqt/taskman.py b/qt/aqt/taskman.py index 44718a04d..a7b48ec35 100644 --- a/qt/aqt/taskman.py +++ b/qt/aqt/taskman.py @@ -5,14 +5,17 @@ Helper for running tasks on background threads. """ +from __future__ import annotations + from concurrent.futures import Future from concurrent.futures.thread import ThreadPoolExecutor from threading import Lock -from typing import Any, Callable, Dict, List, Optional +from typing import Any, Callable, Dict, List, Optional, Union from PyQt5.QtCore import QObject, pyqtSignal -from aqt.qt import qconnect +import aqt +from aqt.qt import QWidget, qconnect Closure = Callable[[], None] @@ -20,8 +23,9 @@ Closure = Callable[[], None] class TaskManager(QObject): _closures_pending = pyqtSignal() - def __init__(self) -> None: + def __init__(self, mw: aqt.AnkiQt) -> None: QObject.__init__(self) + self.mw = mw.weakref() self._executor = ThreadPoolExecutor() self._closures: List[Closure] = [] self._closures_lock = Lock() @@ -57,6 +61,20 @@ class TaskManager(QObject): return fut + def with_progress( + self, + task: Callable, + on_done: Optional[Callable[[Future], None]] = None, + parent: Optional[QWidget] = None, + ): + self.mw.progress.start(parent=parent) + + def wrapped_done(fut): + self.mw.progress.finish() + on_done(fut) + + self.run_in_background(task, wrapped_done) + def _on_closures_pending(self): """Run any pending closures. This runs in the main thread.""" with self._closures_lock: