koode-taskgraph 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.
@@ -0,0 +1,208 @@
1
+ from __future__ import annotations
2
+
3
+ from hashlib import sha256
4
+ from importlib.util import module_from_spec, spec_from_file_location
5
+ from pathlib import Path
6
+ import inspect
7
+ import sys
8
+ from types import ModuleType
9
+ from typing import Callable
10
+
11
+ from qtpy.QtCore import QPointF, Qt
12
+ from qtpy.QtGui import QAction, QKeySequence
13
+ from qtpy.QtWidgets import QDockWidget, QWidget
14
+
15
+ from taskgraph.core.model import Backdrop, Connection, ProcessNode
16
+ from taskgraph.core.registry import create_node
17
+
18
+ PLUGIN_ENTRYPOINT = "register_taskgraph_plugin"
19
+ _LOADED_GUI_PLUGINS: dict[Path, ModuleType] = {}
20
+
21
+
22
+ class TaskGraphPluginApi:
23
+ """Small GUI-facing API for external TaskGraph plugins."""
24
+
25
+ def __init__(self, window, plugin_path: Path):
26
+ self.window = window
27
+ self.plugin_path = plugin_path
28
+
29
+ @property
30
+ def scene(self):
31
+ return self.window.scene
32
+
33
+ @property
34
+ def graph(self):
35
+ return self.window.scene.graph
36
+
37
+ @property
38
+ def console(self):
39
+ return self.window.console
40
+
41
+ def add_menu_action(
42
+ self,
43
+ menu: str,
44
+ text: str,
45
+ callback: Callable,
46
+ shortcut: str | QKeySequence | None = None,
47
+ ) -> QAction:
48
+ action = QAction(text, self.window)
49
+ if shortcut:
50
+ action.setShortcut(QKeySequence(shortcut))
51
+ self.window.addAction(action)
52
+ action.triggered.connect(
53
+ lambda checked=False: self._trigger_callback(callback, checked)
54
+ )
55
+ qt_menu = self.window.menu_for_plugin(menu)
56
+ qt_menu.addAction(action)
57
+ self.window.plugin_actions.append(action)
58
+ return action
59
+
60
+ def add_dock(
61
+ self,
62
+ title: str,
63
+ widget: QWidget,
64
+ area: Qt.DockWidgetArea = Qt.RightDockWidgetArea,
65
+ ) -> QDockWidget:
66
+ dock = self.window.add_plugin_dock(title, widget, area)
67
+ return dock
68
+
69
+ def create_node(
70
+ self,
71
+ type_id: str,
72
+ values: dict | None = None,
73
+ name: str | None = None,
74
+ position: tuple[float, float] = (0, 0),
75
+ disabled: bool = False,
76
+ ) -> ProcessNode:
77
+ node = create_node(
78
+ type_id,
79
+ values=values,
80
+ disabled=disabled,
81
+ name=name,
82
+ )
83
+ self.scene.add_process_node(node, QPointF(position[0], position[1]))
84
+ return node
85
+
86
+ def connect_dependency(
87
+ self,
88
+ source: ProcessNode | str,
89
+ target: ProcessNode | str,
90
+ ) -> Connection:
91
+ source_node = self._node(source)
92
+ target_node = self._node(target)
93
+ connection = Connection(
94
+ source_node.id,
95
+ source_node.dependency_output.name,
96
+ target_node.id,
97
+ target_node.dependency_input.name,
98
+ "dependency",
99
+ )
100
+ self._add_connection(connection)
101
+ return connection
102
+
103
+ def connect_attribute(
104
+ self,
105
+ source: ProcessNode | str,
106
+ source_port: str,
107
+ target: ProcessNode | str,
108
+ target_port: str,
109
+ ) -> Connection:
110
+ source_node = self._node(source)
111
+ target_node = self._node(target)
112
+ connection = Connection(
113
+ source_node.id,
114
+ source_port,
115
+ target_node.id,
116
+ target_port,
117
+ "attribute",
118
+ )
119
+ self._add_connection(connection)
120
+ return connection
121
+
122
+ def add_backdrop(
123
+ self,
124
+ title: str = "Notes",
125
+ note: str = "",
126
+ color: str = "#168c9c",
127
+ position: tuple[float, float] = (0, 0),
128
+ size: tuple[float, float] = (480, 300),
129
+ ) -> Backdrop:
130
+ backdrop = Backdrop(
131
+ title=title,
132
+ note=note,
133
+ color=color,
134
+ position=position,
135
+ size=size,
136
+ )
137
+ self.graph.add_backdrop(backdrop)
138
+ self.scene.rebuild()
139
+ self.scene.graph_changed.emit()
140
+ return backdrop
141
+
142
+ def _add_connection(self, connection: Connection) -> None:
143
+ self.graph.connect(connection)
144
+ self.scene.rebuild()
145
+ self.scene.graph_changed.emit()
146
+
147
+ def _node(self, node: ProcessNode | str) -> ProcessNode:
148
+ if isinstance(node, ProcessNode):
149
+ return node
150
+ return self.graph.nodes[node]
151
+
152
+ def _trigger_callback(self, callback: Callable, checked: bool) -> None:
153
+ signature = inspect.signature(callback)
154
+ if len(signature.parameters) == 0:
155
+ callback()
156
+ else:
157
+ callback(checked)
158
+
159
+
160
+ def load_gui_plugin_directory(directory: str | Path, window) -> list[Path]:
161
+ """Load GUI plugins from a directory and call register_taskgraph_plugin(api)."""
162
+ location = Path(directory).expanduser().resolve()
163
+ if not location.is_dir():
164
+ raise ValueError(f"GUI plugin location does not exist: {location}")
165
+
166
+ loaded = []
167
+ for path in sorted(location.glob("*.py")):
168
+ if path.name.startswith("_") or path in _LOADED_GUI_PLUGINS:
169
+ continue
170
+ module = _load_plugin_module(path, location)
171
+ entrypoint = getattr(module, PLUGIN_ENTRYPOINT, None)
172
+ if entrypoint is None:
173
+ continue
174
+ if not callable(entrypoint):
175
+ raise TypeError(f"{path} defines non-callable {PLUGIN_ENTRYPOINT}")
176
+ try:
177
+ entrypoint(TaskGraphPluginApi(window, path))
178
+ except Exception:
179
+ _LOADED_GUI_PLUGINS.pop(path, None)
180
+ sys.modules.pop(module.__name__, None)
181
+ raise
182
+ _LOADED_GUI_PLUGINS[path] = module
183
+ loaded.append(path)
184
+ return loaded
185
+
186
+
187
+ def _load_plugin_module(path: Path, location: Path) -> ModuleType:
188
+ module_name = (
189
+ "_taskgraph_gui_plugin_"
190
+ + sha256(str(path).encode("utf-8")).hexdigest()[:20]
191
+ )
192
+ spec = spec_from_file_location(module_name, path)
193
+ if not spec or not spec.loader:
194
+ raise ImportError(f"Could not load GUI plugin module: {path}")
195
+ module = module_from_spec(spec)
196
+ sys.modules[module_name] = module
197
+ sys.path.insert(0, str(location))
198
+ try:
199
+ spec.loader.exec_module(module)
200
+ except Exception:
201
+ sys.modules.pop(module_name, None)
202
+ raise
203
+ finally:
204
+ try:
205
+ sys.path.remove(str(location))
206
+ except ValueError:
207
+ pass
208
+ return module
@@ -0,0 +1,165 @@
1
+ from __future__ import annotations
2
+
3
+ from qtpy.QtCore import Signal
4
+ from qtpy.QtGui import QColor
5
+ from qtpy.QtWidgets import (
6
+ QCheckBox, QComboBox, QDoubleSpinBox, QFormLayout, QLabel,
7
+ QLineEdit, QScrollArea, QSizePolicy, QSpinBox, QTextEdit, QWidget,
8
+ )
9
+
10
+ from taskgraph.core.model import Backdrop
11
+
12
+
13
+ class PropertyEditor(QScrollArea):
14
+ property_changed = Signal()
15
+
16
+ def __init__(self, parent=None):
17
+ super().__init__(parent)
18
+ self.setWidgetResizable(True)
19
+ self.setMinimumWidth(250)
20
+ self._node = None
21
+ self._body = QWidget()
22
+ self._layout = QFormLayout(self._body)
23
+ self._layout.setContentsMargins(12, 12, 12, 12)
24
+ self.setWidget(self._body)
25
+ self.set_node(None)
26
+
27
+ def _clear(self) -> None:
28
+ while self._layout.count():
29
+ item = self._layout.takeAt(0)
30
+ if item.widget():
31
+ item.widget().deleteLater()
32
+
33
+ def set_node(self, node) -> None:
34
+ self._node = node
35
+ self._clear()
36
+ if node is None:
37
+ self._layout.addRow(
38
+ QLabel("Select a node or backdrop to edit its properties.")
39
+ )
40
+ return
41
+ if isinstance(node, Backdrop):
42
+ self._set_backdrop(node)
43
+ return
44
+ title = QLabel(f"<b>{node.title}</b><br><small>{node.type_id}</small>")
45
+ self._layout.addRow(title)
46
+ name_editor = QLineEdit(node.name or "")
47
+ name_editor.setPlaceholderText(node.title)
48
+ name_editor.editingFinished.connect(
49
+ lambda editor=name_editor: self._set_name(editor.text())
50
+ )
51
+ self._layout.addRow("Node Name", name_editor)
52
+ for spec in node.properties:
53
+ widget = self._make_editor(spec, node.values.get(spec.name))
54
+ self._layout.addRow(spec.label, widget)
55
+
56
+ def _set_backdrop(self, backdrop: Backdrop) -> None:
57
+ self._layout.addRow(QLabel("<b>Backdrop</b><br><small>Graph notes</small>"))
58
+ title = QLineEdit(backdrop.title)
59
+ title.editingFinished.connect(
60
+ lambda editor=title: self._set_backdrop_value(
61
+ "title", editor.text().strip() or "Notes"
62
+ )
63
+ )
64
+ self._layout.addRow("Title", title)
65
+
66
+ notes = QTextEdit(backdrop.note)
67
+ notes.setObjectName("notesEditor")
68
+ notes.setAcceptRichText(False)
69
+ notes.setLineWrapMode(QTextEdit.WidgetWidth)
70
+ notes.setMinimumHeight(140)
71
+ notes.setMaximumHeight(220)
72
+ notes.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Fixed)
73
+ notes.textChanged.connect(
74
+ lambda editor=notes: self._set_backdrop_value(
75
+ "note", editor.toPlainText()
76
+ )
77
+ )
78
+ # A widget-only QFormLayout row spans both columns, giving multiline
79
+ # notes the full width of the Properties panel.
80
+ self._layout.addRow(QLabel("Notes"))
81
+ self._layout.addRow(notes)
82
+
83
+ color = QLineEdit(backdrop.color)
84
+ color.editingFinished.connect(
85
+ lambda editor=color: self._set_backdrop_color(editor.text())
86
+ )
87
+ self._layout.addRow("Color", color)
88
+
89
+ width = QSpinBox()
90
+ width.setRange(200, 3000)
91
+ width.setValue(int(backdrop.size[0]))
92
+ width.valueChanged.connect(
93
+ lambda value: self._set_backdrop_size(width=value)
94
+ )
95
+ self._layout.addRow("Width", width)
96
+
97
+ height = QSpinBox()
98
+ height.setRange(120, 3000)
99
+ height.setValue(int(backdrop.size[1]))
100
+ height.valueChanged.connect(
101
+ lambda value: self._set_backdrop_size(height=value)
102
+ )
103
+ self._layout.addRow("Height", height)
104
+
105
+ def _make_editor(self, spec, value):
106
+ if spec.kind == "bool":
107
+ widget = QCheckBox()
108
+ widget.setChecked(bool(value))
109
+ widget.toggled.connect(lambda checked, s=spec: self._set(s.name, checked))
110
+ elif spec.kind == "int":
111
+ widget = QSpinBox()
112
+ widget.setRange(int(spec.minimum if spec.minimum is not None else -1_000_000),
113
+ int(spec.maximum if spec.maximum is not None else 1_000_000))
114
+ widget.setValue(int(value or 0))
115
+ widget.valueChanged.connect(lambda number, s=spec: self._set(s.name, number))
116
+ elif spec.kind == "float":
117
+ widget = QDoubleSpinBox()
118
+ widget.setDecimals(4)
119
+ widget.setRange(spec.minimum if spec.minimum is not None else -1e12,
120
+ spec.maximum if spec.maximum is not None else 1e12)
121
+ widget.setValue(float(value or 0))
122
+ widget.valueChanged.connect(lambda number, s=spec: self._set(s.name, number))
123
+ elif spec.kind == "choice":
124
+ widget = QComboBox()
125
+ widget.addItems([str(choice) for choice in spec.choices])
126
+ if value in spec.choices:
127
+ widget.setCurrentIndex(spec.choices.index(value))
128
+ widget.currentIndexChanged.connect(
129
+ lambda index, s=spec: self._set(s.name, s.choices[index])
130
+ )
131
+ else:
132
+ widget = QLineEdit("" if value is None else str(value))
133
+ widget.editingFinished.connect(lambda w=widget, s=spec: self._set(s.name, w.text()))
134
+ return widget
135
+
136
+ def _set(self, name, value) -> None:
137
+ if self._node:
138
+ self._node.values[name] = value
139
+ self.property_changed.emit()
140
+
141
+ def _set_name(self, value: str) -> None:
142
+ if self._node:
143
+ self._node.name = value.strip() or None
144
+ self.property_changed.emit()
145
+
146
+ def _set_backdrop_value(self, name: str, value) -> None:
147
+ if isinstance(self._node, Backdrop):
148
+ setattr(self._node, name, value)
149
+ self.property_changed.emit()
150
+
151
+ def _set_backdrop_color(self, value: str) -> None:
152
+ if isinstance(self._node, Backdrop) and QColor(value).isValid():
153
+ self._node.color = value
154
+ self.property_changed.emit()
155
+
156
+ def _set_backdrop_size(
157
+ self, width: int | None = None, height: int | None = None
158
+ ) -> None:
159
+ if isinstance(self._node, Backdrop):
160
+ current_width, current_height = self._node.size
161
+ self._node.size = (
162
+ width if width is not None else current_width,
163
+ height if height is not None else current_height,
164
+ )
165
+ self.property_changed.emit()