add helper to run background task with progress

This commit is contained in:
Damien Elmes 2020-05-04 21:30:41 +10:00
parent 1233e9de12
commit f6931197d2
2 changed files with 22 additions and 4 deletions

View file

@ -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

View file

@ -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: