tqm 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- tqm/__init__.py +44 -0
- tqm/_core/logger.py +123 -0
- tqm/_core/queue.py +150 -0
- tqm/_core/settings.py +117 -0
- tqm/_core/shutdown.py +60 -0
- tqm/_core/task.py +112 -0
- tqm/_core/task_actions.py +29 -0
- tqm/_core/task_base.py +160 -0
- tqm/_core/task_builder.py +380 -0
- tqm/_core/task_callbacks.py +38 -0
- tqm/_core/task_executor.py +470 -0
- tqm/_core/task_options.py +24 -0
- tqm/_core/task_predicate.py +88 -0
- tqm/_core/task_runner.py +110 -0
- tqm/_core/task_state.py +212 -0
- tqm/_core/threadpool_interface.py +38 -0
- tqm/_main.py +172 -0
- tqm/_resources_rc.py +14737 -0
- tqm/_ui/context_menu.py +78 -0
- tqm/_ui/debug_widget.py +208 -0
- tqm/_ui/font_loader.py +37 -0
- tqm/_ui/mixins/multi_select_mixin.py +85 -0
- tqm/_ui/mixins/view_mixin.py +182 -0
- tqm/_ui/progress_bar_delegate.py +178 -0
- tqm/_ui/tab_logs.py +121 -0
- tqm/_ui/task_item.py +25 -0
- tqm/_ui/toolbar.py +124 -0
- tqm/_ui/ui_controller.py +270 -0
- tqm/_ui/ui_view_model.py +281 -0
- tqm/demo/__init__.py +5 -0
- tqm/demo/demo.py +313 -0
- tqm/exceptions.py +26 -0
- tqm/theme/style.qss +80 -0
- tqm/typings.py +9 -0
- tqm/utils/__init__.py +11 -0
- tqm/utils/extract_fn_name.py +27 -0
- tqm/utils/open_file.py +42 -0
- tqm/utils/random_color.py +56 -0
- tqm/utils/thread_info.py +21 -0
- tqm/version.py +1 -0
- tqm/widgets/__init__.py +9 -0
- tqm/widgets/frame.py +15 -0
- tqm/widgets/help_widget.py +86 -0
- tqm/widgets/tool_button.py +11 -0
- tqm-0.1.0.dist-info/LICENSE.md +21 -0
- tqm-0.1.0.dist-info/METADATA +219 -0
- tqm-0.1.0.dist-info/RECORD +49 -0
- tqm-0.1.0.dist-info/WHEEL +4 -0
- tqm-0.1.0.dist-info/entry_points.txt +4 -0
tqm/__init__.py
ADDED
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Queue Task Manager: PySide2 parallel task queuing and execution framework.
|
|
3
|
+
"""
|
|
4
|
+
|
|
5
|
+
from __future__ import annotations
|
|
6
|
+
|
|
7
|
+
from .version import __version__
|
|
8
|
+
|
|
9
|
+
from ._core import logger
|
|
10
|
+
from ._core.logger import write_log
|
|
11
|
+
try:
|
|
12
|
+
from . import _resources_rc
|
|
13
|
+
except ImportError:
|
|
14
|
+
import warnings
|
|
15
|
+
warnings.warn(
|
|
16
|
+
"Resource file '_resources_rc.py' not found. "
|
|
17
|
+
'Some UI resources may not be available. '
|
|
18
|
+
'If you are developing, ensure resources are compiled and available in the package.',
|
|
19
|
+
)
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
from ._main import TQManager
|
|
23
|
+
from . import exceptions
|
|
24
|
+
from ._core.task import TaskExecutable, TaskGroup, TaskUnit
|
|
25
|
+
from ._core.task_builder import TaskBuilder, TaskGroupBuilder
|
|
26
|
+
from ._core.task_executor import TaskExecutor
|
|
27
|
+
from ._core.task_actions import TaskActionVisibility
|
|
28
|
+
from .widgets.help_widget import about
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
__all__ = [
|
|
32
|
+
'write_log',
|
|
33
|
+
'exceptions',
|
|
34
|
+
'TaskExecutable',
|
|
35
|
+
'TaskUnit',
|
|
36
|
+
'TaskGroup',
|
|
37
|
+
'TaskBuilder',
|
|
38
|
+
'TaskGroupBuilder',
|
|
39
|
+
'TaskActionVisibility',
|
|
40
|
+
'TQManager',
|
|
41
|
+
'TaskExecutor',
|
|
42
|
+
'about',
|
|
43
|
+
'__version__',
|
|
44
|
+
]
|
tqm/_core/logger.py
ADDED
|
@@ -0,0 +1,123 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import os
|
|
4
|
+
import sys
|
|
5
|
+
import logging
|
|
6
|
+
from typing import TYPE_CHECKING, TextIO, Optional
|
|
7
|
+
from pathlib import Path
|
|
8
|
+
from logging.handlers import TimedRotatingFileHandler
|
|
9
|
+
|
|
10
|
+
from PySide2.QtCore import Qt, Signal, QObject
|
|
11
|
+
|
|
12
|
+
if TYPE_CHECKING:
|
|
13
|
+
from .._ui.tab_logs import TasksLog
|
|
14
|
+
|
|
15
|
+
USER_LEVEL = 25
|
|
16
|
+
logging.addLevelName(USER_LEVEL, 'USER')
|
|
17
|
+
|
|
18
|
+
LOG_FILE_FORMAT = logging.Formatter(' - '.join([
|
|
19
|
+
'%(asctime)s',
|
|
20
|
+
'%(levelname)-8s',
|
|
21
|
+
'%(threadName)s ID:%(thread)-15d',
|
|
22
|
+
'%(message)s'
|
|
23
|
+
]), '%Y-%m-%d %H:%M:%S')
|
|
24
|
+
|
|
25
|
+
LOG_WIDGET_FORMAT = logging.Formatter(' - '.join([
|
|
26
|
+
'%(asctime)s',
|
|
27
|
+
'%(levelname)-8s',
|
|
28
|
+
'%(threadName)s ID:%(thread)-15d',
|
|
29
|
+
'%(message)s'
|
|
30
|
+
]), '%H:%M:%S')
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
class TqmLogger(logging.Logger):
|
|
34
|
+
def __init__(self, name: str = 'tqm') -> None:
|
|
35
|
+
super().__init__(name)
|
|
36
|
+
self.setLevel(logging.DEBUG)
|
|
37
|
+
self._widget = logging.NullHandler()
|
|
38
|
+
|
|
39
|
+
@property
|
|
40
|
+
def widget(self) -> logging.Handler:
|
|
41
|
+
return self._widget
|
|
42
|
+
|
|
43
|
+
@widget.setter
|
|
44
|
+
def widget(self, handler: logging.Handler) -> None:
|
|
45
|
+
self._widget = handler
|
|
46
|
+
self.addHandler(self._widget)
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
class HandlerSignal(QObject):
|
|
50
|
+
log_message = Signal(str, str, str)
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
class WidgetLogHandler(logging.Handler):
|
|
54
|
+
|
|
55
|
+
def __init__(self, widget: TasksLog, debug: bool = False) -> None:
|
|
56
|
+
super().__init__()
|
|
57
|
+
self.set_name('widget_handler')
|
|
58
|
+
self.setLevel(logging.DEBUG if debug else logging.INFO)
|
|
59
|
+
self.setFormatter(LOG_WIDGET_FORMAT)
|
|
60
|
+
|
|
61
|
+
self._widget = widget
|
|
62
|
+
self._signal = HandlerSignal()
|
|
63
|
+
self._signal.log_message.connect(self._widget.log, Qt.QueuedConnection)
|
|
64
|
+
|
|
65
|
+
def emit(self, record: logging.LogRecord) -> None:
|
|
66
|
+
self._signal.log_message.emit(
|
|
67
|
+
self.format(record) + '\n',
|
|
68
|
+
record.levelname.upper(),
|
|
69
|
+
str(record.thread)
|
|
70
|
+
)
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
def log_file_handler(config_path: Path) -> TimedRotatingFileHandler:
|
|
74
|
+
tqm_log_dir = config_path / 'logs'
|
|
75
|
+
tqm_log_dir.mkdir(parents=True, exist_ok=True)
|
|
76
|
+
|
|
77
|
+
handler = TimedRotatingFileHandler(
|
|
78
|
+
filename=tqm_log_dir / 'tqm.log',
|
|
79
|
+
when='midnight',
|
|
80
|
+
backupCount=7
|
|
81
|
+
)
|
|
82
|
+
|
|
83
|
+
handler.setLevel(logging.DEBUG)
|
|
84
|
+
handler.set_name('file_handler')
|
|
85
|
+
handler.setFormatter(LOG_FILE_FORMAT)
|
|
86
|
+
|
|
87
|
+
return handler
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
def _console_handler() -> logging.StreamHandler[TextIO]:
|
|
91
|
+
handler = logging.StreamHandler(sys.stdout)
|
|
92
|
+
handler.setLevel(logging.DEBUG)
|
|
93
|
+
handler.set_name('console_handler')
|
|
94
|
+
handler.setFormatter(LOG_WIDGET_FORMAT)
|
|
95
|
+
return handler
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
def write_log(msg: str, *, stream: Optional[TextIO] = None) -> None:
|
|
99
|
+
"""Write a log level USER message to the logger.
|
|
100
|
+
|
|
101
|
+
Args:
|
|
102
|
+
msg (str): The message to log.
|
|
103
|
+
stream (Optional[TextIO], optional): The stream to write to. Defaults to None.
|
|
104
|
+
|
|
105
|
+
```
|
|
106
|
+
write_log('Hello, World!')
|
|
107
|
+
write_log('Hello, World!', stream=sys.stdout)
|
|
108
|
+
```
|
|
109
|
+
|
|
110
|
+
"""
|
|
111
|
+
if stream:
|
|
112
|
+
try:
|
|
113
|
+
stream.write(msg + '\n')
|
|
114
|
+
stream.flush()
|
|
115
|
+
except Exception as e:
|
|
116
|
+
LOGGER.error('Invalid stream: %s', e)
|
|
117
|
+
|
|
118
|
+
LOGGER.log(USER_LEVEL, msg)
|
|
119
|
+
|
|
120
|
+
|
|
121
|
+
LOGGER = TqmLogger()
|
|
122
|
+
if os.getenv('TQM_DEBUG') == '1':
|
|
123
|
+
LOGGER.addHandler(_console_handler())
|
tqm/_core/queue.py
ADDED
|
@@ -0,0 +1,150 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import heapq
|
|
4
|
+
from uuid import UUID
|
|
5
|
+
from typing import Dict, List, Iterator
|
|
6
|
+
|
|
7
|
+
from tqm._core.task import TaskGroup, TaskExecutable
|
|
8
|
+
from tqm._core.task_base import TaskBase
|
|
9
|
+
from tqm._core.task_runner import TaskRunner, GroupRunner
|
|
10
|
+
|
|
11
|
+
from .task import TaskUnit
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
class DeferredTaskNotFound(Exception):
|
|
15
|
+
pass
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
class TaskNotFoundError(Exception):
|
|
19
|
+
pass
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
class TasksQueue:
|
|
23
|
+
"""Simple heap-based priority queue for tasks.
|
|
24
|
+
|
|
25
|
+
The class also includes a deferred queue for tasks that are not ready to be
|
|
26
|
+
executed. The deferred queue is a simple dictionary with the task id as the
|
|
27
|
+
key and the task as the value.
|
|
28
|
+
|
|
29
|
+
"""
|
|
30
|
+
|
|
31
|
+
DeferredTaskNotFound = DeferredTaskNotFound
|
|
32
|
+
TaskNotFound = TaskNotFoundError
|
|
33
|
+
|
|
34
|
+
def __init__(self) -> None:
|
|
35
|
+
self.heap: List[TaskUnit] = []
|
|
36
|
+
self.deferred: Dict[UUID, TaskUnit] = {}
|
|
37
|
+
|
|
38
|
+
def is_empty(self) -> bool:
|
|
39
|
+
"""Return True if the queue is empty."""
|
|
40
|
+
return not bool(self.heap)
|
|
41
|
+
|
|
42
|
+
def peek(self) -> TaskUnit:
|
|
43
|
+
"""Return the task with the highest priority in the queue."""
|
|
44
|
+
if not self.is_empty():
|
|
45
|
+
return self.heap[0]
|
|
46
|
+
raise IndexError('Queue is empty')
|
|
47
|
+
|
|
48
|
+
def size(self) -> int:
|
|
49
|
+
"""Return the number of tasks in the main queue (heap)."""
|
|
50
|
+
return len(self.heap)
|
|
51
|
+
|
|
52
|
+
def size_deferred(self) -> int:
|
|
53
|
+
return len(self.deferred)
|
|
54
|
+
|
|
55
|
+
def enqueue(self, task: TaskUnit) -> None:
|
|
56
|
+
"""Push a task into the queue."""
|
|
57
|
+
heapq.heappush(self.heap, task)
|
|
58
|
+
|
|
59
|
+
def dequeue(self) -> TaskUnit:
|
|
60
|
+
"""Pop the task with the highest priority from the queue."""
|
|
61
|
+
if not self.is_empty():
|
|
62
|
+
return heapq.heappop(self.heap)
|
|
63
|
+
raise IndexError('Queue is empty')
|
|
64
|
+
|
|
65
|
+
def suspend(self, task: TaskUnit) -> None:
|
|
66
|
+
"""Defer a task to be executed later."""
|
|
67
|
+
self.deferred[task.id] = task
|
|
68
|
+
|
|
69
|
+
def is_task_deferred(self, task: TaskUnit) -> bool:
|
|
70
|
+
"""Check if task is in the deferred queue."""
|
|
71
|
+
return task.id in self.deferred
|
|
72
|
+
|
|
73
|
+
def remove_from_deferred(self, task: TaskUnit) -> TaskUnit:
|
|
74
|
+
"""Remove a task from the deferred queue.
|
|
75
|
+
|
|
76
|
+
Raises:
|
|
77
|
+
TasksQueueDeferredItemNotFound: If the task is not found in the deferred queue.
|
|
78
|
+
"""
|
|
79
|
+
try:
|
|
80
|
+
self.deferred.pop(task.id)
|
|
81
|
+
except (ValueError, KeyError) as e:
|
|
82
|
+
raise DeferredTaskNotFound(
|
|
83
|
+
f'Item {task.name} not found in deferred queue'
|
|
84
|
+
) from e
|
|
85
|
+
return task
|
|
86
|
+
|
|
87
|
+
def main_to_deferred(self, task: TaskUnit) -> None:
|
|
88
|
+
"""Transfer a task from the main queue to the deferred queue."""
|
|
89
|
+
self.remove_from_queue(task)
|
|
90
|
+
self.suspend(task)
|
|
91
|
+
|
|
92
|
+
def promote_to_main(self, task: TaskUnit) -> None:
|
|
93
|
+
"""Transfer a task from the deferred queue to the main queue."""
|
|
94
|
+
self.remove_from_deferred(task)
|
|
95
|
+
self.enqueue(task)
|
|
96
|
+
|
|
97
|
+
def remove_from_queue(self, task: TaskUnit) -> TaskUnit:
|
|
98
|
+
"""Remove a task from the queue.
|
|
99
|
+
|
|
100
|
+
Raises:
|
|
101
|
+
TaskNotFoundError: If the task is not found in the queue.
|
|
102
|
+
"""
|
|
103
|
+
try:
|
|
104
|
+
self.heap.remove(task)
|
|
105
|
+
except ValueError as e:
|
|
106
|
+
raise TaskNotFoundError(f'Item {task.name} not found in queue') from e
|
|
107
|
+
|
|
108
|
+
heapq.heapify(self.heap)
|
|
109
|
+
return task
|
|
110
|
+
|
|
111
|
+
def clear(self) -> None:
|
|
112
|
+
"""Clear the queue and deferred queue."""
|
|
113
|
+
self.heap.clear()
|
|
114
|
+
self.deferred.clear()
|
|
115
|
+
|
|
116
|
+
def remove_task(self, task: TaskUnit) -> None:
|
|
117
|
+
"""Delete a task from the queue or deferred queue.
|
|
118
|
+
|
|
119
|
+
Raises:
|
|
120
|
+
TaskNotFoundError: If the task is not found in the queue or deferred queue.
|
|
121
|
+
"""
|
|
122
|
+
try:
|
|
123
|
+
self.remove_from_queue(task)
|
|
124
|
+
except self.TaskNotFound:
|
|
125
|
+
try:
|
|
126
|
+
self.remove_from_deferred(task)
|
|
127
|
+
except self.DeferredTaskNotFound as e:
|
|
128
|
+
raise self.TaskNotFound from e
|
|
129
|
+
|
|
130
|
+
def __iter__(self) -> Iterator[TaskBase[TaskExecutable, TaskRunner] | TaskBase[TaskGroup, GroupRunner]]:
|
|
131
|
+
return iter([*self.heap, *self.deferred.values()])
|
|
132
|
+
|
|
133
|
+
def __contains__(self, task: TaskUnit) -> bool:
|
|
134
|
+
"""
|
|
135
|
+
Check if a given task is present in the queue.
|
|
136
|
+
|
|
137
|
+
NOTE: debug only. not optimize for fast lookup
|
|
138
|
+
|
|
139
|
+
Args:
|
|
140
|
+
task (TqmTaskUnit): The task to check for presence in the queue.
|
|
141
|
+
|
|
142
|
+
Returns:
|
|
143
|
+
bool: True if the task is found in the deferred list or the heap,
|
|
144
|
+
otherwise False.
|
|
145
|
+
"""
|
|
146
|
+
|
|
147
|
+
return (
|
|
148
|
+
True if task.id in self.deferred
|
|
149
|
+
else any(t == task for t in self.heap)
|
|
150
|
+
)
|
tqm/_core/settings.py
ADDED
|
@@ -0,0 +1,117 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import os
|
|
4
|
+
import sys
|
|
5
|
+
import json
|
|
6
|
+
from typing import Any, Dict, Literal, Optional, Generator
|
|
7
|
+
from pathlib import Path
|
|
8
|
+
from contextlib import contextmanager
|
|
9
|
+
from dataclasses import field, asdict, dataclass
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
def get_config_path(app_name: str) -> Path:
|
|
13
|
+
"""
|
|
14
|
+
Get the config directory path for the application.
|
|
15
|
+
|
|
16
|
+
Args:
|
|
17
|
+
app_name (str): The name of the application
|
|
18
|
+
|
|
19
|
+
Returns:
|
|
20
|
+
Path: The config directory path for the application.
|
|
21
|
+
"""
|
|
22
|
+
home = Path.home()
|
|
23
|
+
|
|
24
|
+
if sys.platform == 'win32':
|
|
25
|
+
env = os.getenv('LOCALAPPDATA')
|
|
26
|
+
path = (
|
|
27
|
+
Path(env) / 'tqm' / app_name
|
|
28
|
+
if env
|
|
29
|
+
else home / 'AppData' / 'Local' / 'tqm' / app_name
|
|
30
|
+
)
|
|
31
|
+
else:
|
|
32
|
+
env = os.environ.get('XDG_CONFIG_HOME')
|
|
33
|
+
path = (
|
|
34
|
+
Path(env) / 'tqm' / app_name
|
|
35
|
+
if env
|
|
36
|
+
else home / '.config' / 'tqm' / app_name
|
|
37
|
+
)
|
|
38
|
+
|
|
39
|
+
os.environ['TQM_CONFIG_PATH'] = str(path)
|
|
40
|
+
os.environ['TQM_SETTINGS_PATH'] = str(path / 'settings.json')
|
|
41
|
+
|
|
42
|
+
return path
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def get_qss_path(config_path: Path) -> Path:
|
|
46
|
+
"""Returns the style qss path.
|
|
47
|
+
|
|
48
|
+
Uses the environment variable `TQM_QSS_PATH` if set.
|
|
49
|
+
|
|
50
|
+
"""
|
|
51
|
+
env = os.getenv('TQM_QSS_PATH')
|
|
52
|
+
if env:
|
|
53
|
+
return Path(env)
|
|
54
|
+
|
|
55
|
+
user_qss = config_path / 'style.qss'
|
|
56
|
+
base_qss = Path(__file__).parent.parent / 'theme' / 'style.qss'
|
|
57
|
+
|
|
58
|
+
if not user_qss.exists():
|
|
59
|
+
user_qss.write_text(base_qss.read_text())
|
|
60
|
+
|
|
61
|
+
return user_qss
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
class _SingletonMeta(type):
|
|
65
|
+
_instance = None
|
|
66
|
+
|
|
67
|
+
def __call__(cls, *args: Any, **kwargs: Any) -> Any:
|
|
68
|
+
if not cls._instance:
|
|
69
|
+
instance = super().__call__(*args, **kwargs)
|
|
70
|
+
cls._instance = instance
|
|
71
|
+
return cls._instance
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
@dataclass
|
|
75
|
+
class Settings(metaclass=_SingletonMeta):
|
|
76
|
+
max_workers: int = 20
|
|
77
|
+
enable_debug: bool = False
|
|
78
|
+
wrap_lines: bool = True
|
|
79
|
+
view: Dict[str, Any] = field(default_factory=dict[str, Any], repr=False)
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
@contextmanager
|
|
83
|
+
def open_settings(
|
|
84
|
+
mode: Literal['r', 'w'] = 'r',
|
|
85
|
+
*, json_file_path: Optional[Path] = None
|
|
86
|
+
) -> Generator[Settings, Any, None]:
|
|
87
|
+
"""Open settings context manager.
|
|
88
|
+
|
|
89
|
+
```
|
|
90
|
+
with open_settings(mode='r') as s:
|
|
91
|
+
s.save_to_db = True
|
|
92
|
+
s.focus_tab_on_error = False
|
|
93
|
+
```
|
|
94
|
+
"""
|
|
95
|
+
if json_file_path is None:
|
|
96
|
+
json_file_path = Path(os.environ['TQM_SETTINGS_PATH'])
|
|
97
|
+
|
|
98
|
+
try:
|
|
99
|
+
with json_file_path.open() as f:
|
|
100
|
+
settings = Settings(**json.load(f))
|
|
101
|
+
|
|
102
|
+
except FileNotFoundError:
|
|
103
|
+
settings = Settings()
|
|
104
|
+
with json_file_path.open('w') as f:
|
|
105
|
+
json.dump(asdict(settings), f, indent=4)
|
|
106
|
+
|
|
107
|
+
except Exception as e:
|
|
108
|
+
print('[tqm error]: Invalid settings file. Resetting settings.', e)
|
|
109
|
+
settings = Settings()
|
|
110
|
+
|
|
111
|
+
yield settings
|
|
112
|
+
|
|
113
|
+
if mode != 'w':
|
|
114
|
+
return
|
|
115
|
+
|
|
116
|
+
with json_file_path.open('w') as f:
|
|
117
|
+
json.dump(asdict(settings), f, indent=4)
|
tqm/_core/shutdown.py
ADDED
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
"""Shutdown tasks for the task runner.
|
|
2
|
+
|
|
3
|
+
This module contains the shutdown tasks for the task runner. The shutdown tasks
|
|
4
|
+
will wait (blocking the main thread) for all tasks to complete before shutting down
|
|
5
|
+
the workers.
|
|
6
|
+
|
|
7
|
+
"""
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
from typing import Optional
|
|
11
|
+
|
|
12
|
+
from PySide2.QtCore import Signal, QObject, QThread, QEventLoop
|
|
13
|
+
from PySide2.QtWidgets import QProgressDialog
|
|
14
|
+
|
|
15
|
+
from .threadpool_interface import ThreadPoolInterface
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
class ShutdownWorker(QObject):
|
|
19
|
+
finished = Signal()
|
|
20
|
+
|
|
21
|
+
def __init__(self, threadpool: ThreadPoolInterface) -> None:
|
|
22
|
+
super().__init__()
|
|
23
|
+
self.threadPool = threadpool
|
|
24
|
+
|
|
25
|
+
def run(self) -> None:
|
|
26
|
+
self.threadPool.waitForDone()
|
|
27
|
+
self.finished.emit()
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
class ShutdownThread(QObject):
|
|
31
|
+
def __init__(self, threadpool: ThreadPoolInterface) -> None:
|
|
32
|
+
super().__init__()
|
|
33
|
+
|
|
34
|
+
self.threadPool = threadpool
|
|
35
|
+
self.progressDialog: Optional[QProgressDialog] = None
|
|
36
|
+
|
|
37
|
+
def run(self) -> None:
|
|
38
|
+
self.shutdownThread = QThread()
|
|
39
|
+
self.shutdownWorker = ShutdownWorker(self.threadPool)
|
|
40
|
+
|
|
41
|
+
self.shutdownWorker.moveToThread(self.shutdownThread)
|
|
42
|
+
self.shutdownWorker.finished.connect(self.onShutdownComplete)
|
|
43
|
+
|
|
44
|
+
self.shutdownThread.started.connect(self.shutdownWorker.run)
|
|
45
|
+
|
|
46
|
+
self.progressDialog = QProgressDialog('Shutting down, please wait...', '', 0, 0)
|
|
47
|
+
self.progressDialog.setCancelButton(None)
|
|
48
|
+
self.progressDialog.setModal(True)
|
|
49
|
+
self.progressDialog.show()
|
|
50
|
+
|
|
51
|
+
self.shutdownThread.start()
|
|
52
|
+
event_loop = QEventLoop()
|
|
53
|
+
self.shutdownThread.finished.connect(event_loop.quit)
|
|
54
|
+
event_loop.exec_()
|
|
55
|
+
|
|
56
|
+
def onShutdownComplete(self) -> None:
|
|
57
|
+
self.shutdownThread.quit()
|
|
58
|
+
self.shutdownThread.wait()
|
|
59
|
+
if self.progressDialog:
|
|
60
|
+
self.progressDialog.accept()
|
tqm/_core/task.py
ADDED
|
@@ -0,0 +1,112 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
from typing import Any, Set, Dict, Union, Callable, Optional
|
|
4
|
+
from dataclasses import field, dataclass
|
|
5
|
+
|
|
6
|
+
from ..utils import extract_fn_name
|
|
7
|
+
from .logger import LOGGER
|
|
8
|
+
from .task_base import TaskBase
|
|
9
|
+
from .task_runner import TaskRunner, GroupRunner
|
|
10
|
+
|
|
11
|
+
TaskUnit = Union[
|
|
12
|
+
TaskBase['TaskExecutable', TaskRunner],
|
|
13
|
+
TaskBase['TaskGroup', GroupRunner]
|
|
14
|
+
]
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
@dataclass
|
|
18
|
+
class TaskExecutable(TaskBase['TaskExecutable', TaskRunner]):
|
|
19
|
+
execute: Callable[..., Any] = lambda: None
|
|
20
|
+
group: Optional[TaskGroup] = None
|
|
21
|
+
runner: TaskRunner = field(init=False)
|
|
22
|
+
|
|
23
|
+
def __post_init__(self) -> None:
|
|
24
|
+
super().__post_init__(suffix='Task')
|
|
25
|
+
LOGGER.debug('TaskExecutable created: %s', str(self))
|
|
26
|
+
self.runner = TaskRunner(self)
|
|
27
|
+
|
|
28
|
+
def __hash__(self) -> int:
|
|
29
|
+
return hash(self.id)
|
|
30
|
+
|
|
31
|
+
def reset(self, comment: str = '', reset_attempts: bool = False) -> None:
|
|
32
|
+
super().reset(comment, reset_attempts)
|
|
33
|
+
self.runner = TaskRunner(self)
|
|
34
|
+
|
|
35
|
+
def delete(self, comment: str = '') -> None:
|
|
36
|
+
if self.group:
|
|
37
|
+
self.group.tasks.remove(self)
|
|
38
|
+
return super().delete(comment)
|
|
39
|
+
|
|
40
|
+
def emit_progress(self, value: float) -> None:
|
|
41
|
+
self.runner.signals.task_progress_updated.emit(value)
|
|
42
|
+
|
|
43
|
+
def inspect(self) -> Dict[str, Any]:
|
|
44
|
+
data = super().inspect()
|
|
45
|
+
data['execute'] = extract_fn_name(self.execute)
|
|
46
|
+
data['group'] = str(self.group) or ''
|
|
47
|
+
return data
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
@dataclass
|
|
51
|
+
class TaskGroup(TaskBase['TaskGroup', GroupRunner]):
|
|
52
|
+
tasks: Set[TaskExecutable] = field(init=False, default_factory=set[TaskExecutable])
|
|
53
|
+
runner: GroupRunner = field(init=False)
|
|
54
|
+
|
|
55
|
+
def __post_init__(self) -> None:
|
|
56
|
+
super().__post_init__(suffix='Group')
|
|
57
|
+
LOGGER.debug('Task Group Created: %s', str(self))
|
|
58
|
+
self.runner = GroupRunner(self)
|
|
59
|
+
|
|
60
|
+
def __hash__(self) -> int:
|
|
61
|
+
return hash(self.id)
|
|
62
|
+
|
|
63
|
+
def reset(self, comment: str = '', reset_attempts: bool = False) -> None:
|
|
64
|
+
super().reset(comment, reset_attempts)
|
|
65
|
+
self.runner = GroupRunner(self)
|
|
66
|
+
|
|
67
|
+
def add_tasks(self, *tasks: TaskExecutable) -> None:
|
|
68
|
+
for task in tasks:
|
|
69
|
+
self.tasks.add(task)
|
|
70
|
+
task.group = self
|
|
71
|
+
|
|
72
|
+
def add_event(
|
|
73
|
+
self,
|
|
74
|
+
execute: Callable[[TaskExecutable], Any],
|
|
75
|
+
*,
|
|
76
|
+
show_progress: bool = False,
|
|
77
|
+
label: str = '',
|
|
78
|
+
comment: str = ''
|
|
79
|
+
) -> TaskExecutable:
|
|
80
|
+
"""Add a simple task to the queue.
|
|
81
|
+
|
|
82
|
+
Args:
|
|
83
|
+
execute (Callable[..., Any]): The event to be executed. The first argument is the task itself.
|
|
84
|
+
progress (bool): If the task should show a progress.
|
|
85
|
+
label (Optional[str], optional): The label of the task. If not provided,
|
|
86
|
+
a default label will be generated.
|
|
87
|
+
details (Optional[str], optional): Comment of the task. Defaults to ''.
|
|
88
|
+
|
|
89
|
+
```
|
|
90
|
+
add_event(
|
|
91
|
+
execute=lambda task: print(task.name),
|
|
92
|
+
progress=True,
|
|
93
|
+
label='My task',
|
|
94
|
+
comment='Comment of the task'
|
|
95
|
+
)
|
|
96
|
+
```
|
|
97
|
+
"""
|
|
98
|
+
# XXX: find a better way to avoid circular dependency
|
|
99
|
+
from .task_builder import TaskBuilder
|
|
100
|
+
task = (
|
|
101
|
+
TaskBuilder(name=label)
|
|
102
|
+
.with_event(execute, show_progress=show_progress)
|
|
103
|
+
.with_comment(comment)
|
|
104
|
+
.build()
|
|
105
|
+
)
|
|
106
|
+
self.add_tasks(task)
|
|
107
|
+
return task
|
|
108
|
+
|
|
109
|
+
def inspect(self) -> Dict[str, Any]:
|
|
110
|
+
data = super().inspect()
|
|
111
|
+
data['tasks'] = [str(task) for task in self.tasks]
|
|
112
|
+
return data
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
from enum import Enum, auto
|
|
4
|
+
from typing import Any, Dict, Generic, TypeVar, Callable
|
|
5
|
+
from dataclasses import dataclass
|
|
6
|
+
|
|
7
|
+
from ..utils import extract_fn_name
|
|
8
|
+
|
|
9
|
+
T = TypeVar('T')
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
class TaskActionVisibility(Enum):
|
|
13
|
+
ON_COMPLETED = auto()
|
|
14
|
+
ON_FAILED = auto()
|
|
15
|
+
ALWAYS = auto()
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
@dataclass(frozen=True)
|
|
19
|
+
class TaskAction(Generic[T]):
|
|
20
|
+
name: str
|
|
21
|
+
action: Callable[[T], Any]
|
|
22
|
+
visibility: TaskActionVisibility = TaskActionVisibility.ON_COMPLETED
|
|
23
|
+
|
|
24
|
+
def inspect(self) -> Dict[str, str]:
|
|
25
|
+
return {
|
|
26
|
+
'name': self.name,
|
|
27
|
+
'action': extract_fn_name(self.action),
|
|
28
|
+
'visibility': self.visibility.name,
|
|
29
|
+
}
|