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.
taskgraph/ui/scene.py ADDED
@@ -0,0 +1,426 @@
1
+ from __future__ import annotations
2
+
3
+ import json
4
+ from collections import defaultdict, deque
5
+
6
+ from qtpy.QtCore import QPointF, QRectF, Qt, Signal
7
+ from qtpy.QtGui import QColor, QPainter, QPen
8
+ from qtpy.QtWidgets import QApplication, QGraphicsScene, QGraphicsView
9
+
10
+ from taskgraph.core.model import Backdrop, Connection, Graph
11
+ from taskgraph.core.registry import create_node
12
+ from taskgraph.ui.items import BackdropItem, ConnectionItem, NodeItem, PortItem
13
+
14
+ CLIPBOARD_MIME = "application/x-taskgraph-nodes"
15
+
16
+
17
+ class GraphScene(QGraphicsScene):
18
+ node_selected = Signal(object)
19
+ graph_changed = Signal()
20
+
21
+ def __init__(self, graph: Graph | None = None, parent=None):
22
+ super().__init__(parent)
23
+ self.setSceneRect(-5000, -5000, 10000, 10000)
24
+ self.graph = graph or Graph()
25
+ self.backdrop_items: dict[str, BackdropItem] = {}
26
+ self.node_items: dict[str, NodeItem] = {}
27
+ self.connection_items: list[ConnectionItem] = []
28
+ self._drag_item: ConnectionItem | None = None
29
+ self._drag_port: PortItem | None = None
30
+ self._paste_offset = 0
31
+ self.execution_states: dict[str, str] = {}
32
+ self.selectionChanged.connect(self._selection_changed)
33
+ self.rebuild()
34
+
35
+ def rebuild(self) -> None:
36
+ self.clear()
37
+ self.backdrop_items.clear()
38
+ self.node_items.clear()
39
+ self.connection_items.clear()
40
+ for backdrop in self.graph.backdrops.values():
41
+ item = BackdropItem(self, backdrop)
42
+ item.setPos(QPointF(*backdrop.position))
43
+ self.addItem(item)
44
+ self.backdrop_items[backdrop.id] = item
45
+ for node in self.graph.nodes.values():
46
+ item = NodeItem(self, node)
47
+ item.setPos(QPointF(*self.graph.positions.get(node.id, (0, 0))))
48
+ self.addItem(item)
49
+ self.node_items[node.id] = item
50
+ for connection in self.graph.connections:
51
+ item = ConnectionItem(self, connection)
52
+ self.addItem(item)
53
+ self.connection_items.append(item)
54
+
55
+ def set_graph(self, graph: Graph) -> None:
56
+ self.graph = graph
57
+ self.rebuild()
58
+ self.graph_changed.emit()
59
+
60
+ def add_process_node(self, node, position: QPointF) -> NodeItem:
61
+ self.graph.add_node(node, (position.x(), position.y()))
62
+ item = NodeItem(self, node)
63
+ item.setPos(position)
64
+ self.addItem(item)
65
+ self.node_items[node.id] = item
66
+ item.setSelected(True)
67
+ self.graph_changed.emit()
68
+ return item
69
+
70
+ def add_backdrop(self, position: QPointF) -> BackdropItem:
71
+ backdrop = Backdrop(position=(position.x(), position.y()))
72
+ self.graph.add_backdrop(backdrop)
73
+ item = BackdropItem(self, backdrop)
74
+ item.setPos(position)
75
+ self.addItem(item)
76
+ self.backdrop_items[backdrop.id] = item
77
+ self.clearSelection()
78
+ item.setSelected(True)
79
+ self.graph_changed.emit()
80
+ return item
81
+
82
+ def node_moved(self, item: NodeItem) -> None:
83
+ pos = item.pos()
84
+ self.graph.positions[item.node.id] = (pos.x(), pos.y())
85
+ for edge in self.connection_items:
86
+ if edge.connection and item.node.id in (edge.connection.source_node, edge.connection.target_node):
87
+ edge.refresh()
88
+ self.graph_changed.emit()
89
+
90
+ def begin_connection(self, port: PortItem) -> None:
91
+ self.cancel_connection()
92
+ self._drag_port = port
93
+ self._drag_item = ConnectionItem(self)
94
+ self.addItem(self._drag_item)
95
+ self._drag_item.set_points(port.scenePos(), port.scenePos())
96
+
97
+ def update_connection(self, position: QPointF) -> None:
98
+ if not self._drag_item or not self._drag_port:
99
+ return
100
+ if self._drag_port.is_output:
101
+ self._drag_item.set_points(self._drag_port.scenePos(), position)
102
+ else:
103
+ self._drag_item.set_points(position, self._drag_port.scenePos())
104
+
105
+ def finish_connection(self, position: QPointF) -> None:
106
+ start = self._drag_port
107
+ targets = [item for item in self.items(position) if isinstance(item, PortItem)]
108
+ target = next((port for port in targets if port is not start), None)
109
+ self.cancel_connection()
110
+ if not start or not target or start.is_output == target.is_output:
111
+ return
112
+ source, destination = (start, target) if start.is_output else (target, start)
113
+ if source.node_item is destination.node_item:
114
+ return
115
+ if source.connection_kind != destination.connection_kind:
116
+ return
117
+ if (
118
+ source.connection_kind == "attribute"
119
+ and
120
+ source.spec.data_type != "any"
121
+ and destination.spec.data_type != "any"
122
+ and source.spec.data_type != destination.spec.data_type
123
+ ):
124
+ return
125
+ connection = Connection(
126
+ source.node_item.node.id, source.spec.name,
127
+ destination.node_item.node.id, destination.spec.name,
128
+ source.connection_kind,
129
+ )
130
+ self.graph.connect(connection)
131
+ self.rebuild()
132
+ self.graph_changed.emit()
133
+
134
+ def cancel_connection(self) -> None:
135
+ if self._drag_item and self._drag_item.scene():
136
+ self.removeItem(self._drag_item)
137
+ self._drag_item = None
138
+ self._drag_port = None
139
+
140
+ def delete_selected(self) -> None:
141
+ selected = list(self.selectedItems())
142
+ edges = {item.connection for item in selected if isinstance(item, ConnectionItem) and item.connection}
143
+ node_ids = {item.node.id for item in selected if isinstance(item, NodeItem)}
144
+ backdrop_ids = {
145
+ item.backdrop.id for item in selected
146
+ if isinstance(item, BackdropItem)
147
+ }
148
+ if edges:
149
+ self.graph.connections = [edge for edge in self.graph.connections if edge not in edges]
150
+ for node_id in node_ids:
151
+ self.graph.remove_node(node_id)
152
+ for backdrop_id in backdrop_ids:
153
+ self.graph.remove_backdrop(backdrop_id)
154
+ if selected:
155
+ self.rebuild()
156
+ self.node_selected.emit(None)
157
+ self.graph_changed.emit()
158
+
159
+ def toggle_selected_disabled(self) -> None:
160
+ nodes = [item for item in self.selectedItems() if isinstance(item, NodeItem)]
161
+ if not nodes:
162
+ return
163
+ disable = not all(item.node.disabled for item in nodes)
164
+ for item in nodes:
165
+ item.node.disabled = disable
166
+ item.update()
167
+ self.graph_changed.emit()
168
+
169
+ def copy_selected(self) -> bool:
170
+ selected_ids = {
171
+ item.node.id for item in self.selectedItems()
172
+ if isinstance(item, NodeItem)
173
+ }
174
+ if not selected_ids:
175
+ return False
176
+ nodes = []
177
+ for node_id in selected_ids:
178
+ node = self.graph.nodes[node_id]
179
+ nodes.append({
180
+ **node.to_dict(),
181
+ "position": list(self.graph.positions.get(node_id, (0, 0))),
182
+ })
183
+ connections = [
184
+ edge.to_dict() for edge in self.graph.connections
185
+ if edge.source_node in selected_ids and edge.target_node in selected_ids
186
+ ]
187
+ payload = json.dumps({
188
+ "format": "taskgraph/nodes",
189
+ "version": 1,
190
+ "nodes": nodes,
191
+ "connections": connections,
192
+ })
193
+ # Replace the clipboard data while also exposing readable JSON for
194
+ # inspection and interoperability.
195
+ from qtpy.QtCore import QMimeData
196
+ new_mime = QMimeData()
197
+ new_mime.setData(CLIPBOARD_MIME, payload.encode("utf-8"))
198
+ new_mime.setText(payload)
199
+ QApplication.clipboard().setMimeData(new_mime)
200
+ self._paste_offset = 0
201
+ return True
202
+
203
+ def paste_clipboard(self) -> list[NodeItem]:
204
+ mime = QApplication.clipboard().mimeData()
205
+ raw = bytes(mime.data(CLIPBOARD_MIME)) if mime.hasFormat(CLIPBOARD_MIME) else b""
206
+ if not raw:
207
+ return []
208
+ try:
209
+ data = json.loads(raw.decode("utf-8"))
210
+ if data.get("format") != "taskgraph/nodes" or data.get("version") != 1:
211
+ return []
212
+ self._paste_offset += 32
213
+ id_map = {}
214
+ created_ids = []
215
+ self.clearSelection()
216
+ for item in data.get("nodes", []):
217
+ node = create_node(
218
+ item["type"], values=item.get("values"),
219
+ disabled=item.get("disabled", False),
220
+ name=item.get("name"),
221
+ )
222
+ id_map[item["id"]] = node.id
223
+ created_ids.append(node.id)
224
+ x, y = item.get("position", (0, 0))
225
+ self.add_process_node(
226
+ node, QPointF(x + self._paste_offset, y + self._paste_offset)
227
+ )
228
+ for item in data.get("connections", []):
229
+ source = id_map.get(item["source_node"])
230
+ target = id_map.get(item["target_node"])
231
+ if source and target:
232
+ self.graph.connect(Connection(
233
+ source, item["source_port"], target, item["target_port"],
234
+ item.get("kind", "attribute"),
235
+ ))
236
+ self.rebuild()
237
+ for node_id in created_ids:
238
+ replacement = self.node_items.get(node_id)
239
+ if replacement:
240
+ replacement.setSelected(True)
241
+ self.graph_changed.emit()
242
+ return [self.node_items[node_id] for node_id in created_ids]
243
+ except (KeyError, TypeError, ValueError, json.JSONDecodeError):
244
+ return []
245
+
246
+ def _selection_changed(self) -> None:
247
+ selected = self.selectedItems()
248
+ editable = next(
249
+ (item.node for item in selected if isinstance(item, NodeItem)),
250
+ None,
251
+ )
252
+ if editable is None:
253
+ editable = next(
254
+ (
255
+ item.backdrop for item in selected
256
+ if isinstance(item, BackdropItem)
257
+ ),
258
+ None,
259
+ )
260
+ self.node_selected.emit(editable)
261
+
262
+ def refresh_nodes(self) -> None:
263
+ for item in self.node_items.values():
264
+ item.update()
265
+ for item in self.backdrop_items.values():
266
+ item.refresh_geometry()
267
+
268
+ def reset_execution_states(self) -> None:
269
+ self.execution_states.clear()
270
+ self.refresh_nodes()
271
+
272
+ def set_execution_state(self, node_id: str, state: str) -> None:
273
+ self.execution_states[node_id] = state
274
+ item = self.node_items.get(node_id)
275
+ if item:
276
+ item.update()
277
+
278
+ def auto_arrange(self) -> None:
279
+ """Lay out the dependency graph from left to right in execution layers."""
280
+ if not self.graph.nodes:
281
+ return
282
+ indegree = {node_id: 0 for node_id in self.graph.nodes}
283
+ downstream = defaultdict(list)
284
+ for edge in self.graph.connections:
285
+ if (
286
+ edge.kind == "dependency"
287
+ and edge.source_node in indegree
288
+ and edge.target_node in indegree
289
+ ):
290
+ indegree[edge.target_node] += 1
291
+ downstream[edge.source_node].append(edge.target_node)
292
+
293
+ levels = {node_id: 0 for node_id, degree in indegree.items() if degree == 0}
294
+ queue = deque(sorted(
295
+ levels,
296
+ key=lambda node_id: (
297
+ self.graph.positions.get(node_id, (0, 0))[1],
298
+ self.graph.nodes[node_id].display_name.lower(),
299
+ ),
300
+ ))
301
+ while queue:
302
+ node_id = queue.popleft()
303
+ for target in downstream[node_id]:
304
+ levels[target] = max(levels.get(target, 0), levels[node_id] + 1)
305
+ indegree[target] -= 1
306
+ if indegree[target] == 0:
307
+ queue.append(target)
308
+
309
+ # Cyclic nodes cannot be topologically layered. Keep the operation
310
+ # useful by placing them together in a final column.
311
+ if len(levels) != len(self.graph.nodes):
312
+ last_level = max(levels.values(), default=-1) + 1
313
+ for node_id in self.graph.nodes:
314
+ levels.setdefault(node_id, last_level)
315
+
316
+ columns = defaultdict(list)
317
+ for node_id, level in levels.items():
318
+ columns[level].append(node_id)
319
+ max_rows = max(len(nodes) for nodes in columns.values())
320
+ horizontal_spacing = 300.0
321
+ vertical_spacing = 160.0
322
+ for level in sorted(columns):
323
+ nodes = sorted(
324
+ columns[level],
325
+ key=lambda node_id: (
326
+ self.graph.positions.get(node_id, (0, 0))[1],
327
+ self.graph.nodes[node_id].display_name.lower(),
328
+ ),
329
+ )
330
+ vertical_offset = (max_rows - len(nodes)) * vertical_spacing / 2
331
+ for row, node_id in enumerate(nodes):
332
+ position = QPointF(
333
+ level * horizontal_spacing,
334
+ vertical_offset + row * vertical_spacing,
335
+ )
336
+ self.graph.positions[node_id] = (position.x(), position.y())
337
+ self.node_items[node_id].setPos(position)
338
+
339
+ for connection in self.connection_items:
340
+ connection.refresh()
341
+ self.graph_changed.emit()
342
+
343
+
344
+ class GraphView(QGraphicsView):
345
+ node_type_dropped = Signal(str, QPointF)
346
+
347
+ def __init__(self, scene: GraphScene, parent=None):
348
+ super().__init__(scene, parent)
349
+ self.setRenderHints(QPainter.Antialiasing | QPainter.TextAntialiasing)
350
+ self.setViewportUpdateMode(QGraphicsView.BoundingRectViewportUpdate)
351
+ self.setDragMode(QGraphicsView.RubberBandDrag)
352
+ self.setTransformationAnchor(QGraphicsView.AnchorUnderMouse)
353
+ self.setAcceptDrops(True)
354
+ self.setBackgroundBrush(QColor("#1a1f24"))
355
+ self._panning = False
356
+ self._pan_start = None
357
+
358
+ def drawBackground(self, painter: QPainter, rect: QRectF) -> None:
359
+ painter.fillRect(rect, QColor("#1a1f24"))
360
+ left = int(rect.left()) - int(rect.left()) % 24
361
+ top = int(rect.top()) - int(rect.top()) % 24
362
+ painter.setPen(QPen(QColor("#242b31"), 1))
363
+ x = left
364
+ while x < rect.right():
365
+ painter.drawLine(x, rect.top(), x, rect.bottom())
366
+ x += 24
367
+ y = top
368
+ while y < rect.bottom():
369
+ painter.drawLine(rect.left(), y, rect.right(), y)
370
+ y += 24
371
+ painter.setPen(QPen(QColor("#2c353d"), 1))
372
+ x = left - left % 120
373
+ while x < rect.right():
374
+ painter.drawLine(x, rect.top(), x, rect.bottom())
375
+ x += 120
376
+ y = top - top % 120
377
+ while y < rect.bottom():
378
+ painter.drawLine(rect.left(), y, rect.right(), y)
379
+ y += 120
380
+
381
+ def wheelEvent(self, event) -> None:
382
+ factor = 1.18 if event.angleDelta().y() > 0 else 1 / 1.18
383
+ current = self.transform().m11()
384
+ if 0.2 < current * factor < 4.0:
385
+ self.scale(factor, factor)
386
+
387
+ def mousePressEvent(self, event) -> None:
388
+ if event.button() == Qt.MiddleButton:
389
+ self._panning = True
390
+ self._pan_start = event.position()
391
+ self.setCursor(Qt.ClosedHandCursor)
392
+ event.accept()
393
+ return
394
+ super().mousePressEvent(event)
395
+
396
+ def mouseMoveEvent(self, event) -> None:
397
+ if self._panning:
398
+ delta = event.position() - self._pan_start
399
+ self._pan_start = event.position()
400
+ self.horizontalScrollBar().setValue(self.horizontalScrollBar().value() - int(delta.x()))
401
+ self.verticalScrollBar().setValue(self.verticalScrollBar().value() - int(delta.y()))
402
+ event.accept()
403
+ return
404
+ super().mouseMoveEvent(event)
405
+
406
+ def mouseReleaseEvent(self, event) -> None:
407
+ if event.button() == Qt.MiddleButton:
408
+ self._panning = False
409
+ self.setCursor(Qt.ArrowCursor)
410
+ event.accept()
411
+ return
412
+ super().mouseReleaseEvent(event)
413
+
414
+ def dragEnterEvent(self, event) -> None:
415
+ if event.mimeData().hasFormat("application/x-taskgraph-node"):
416
+ event.acceptProposedAction()
417
+ else:
418
+ super().dragEnterEvent(event)
419
+
420
+ def dragMoveEvent(self, event) -> None:
421
+ event.acceptProposedAction()
422
+
423
+ def dropEvent(self, event) -> None:
424
+ type_id = bytes(event.mimeData().data("application/x-taskgraph-node")).decode()
425
+ self.node_type_dropped.emit(type_id, self.mapToScene(event.position().toPoint()))
426
+ event.acceptProposedAction()
taskgraph/ui/theme.py ADDED
@@ -0,0 +1,30 @@
1
+ APP_STYLESHEET = """
2
+ QWidget { background: #171b20; color: #d5dbe3; font-size: 12px; }
3
+ QMainWindow, QDockWidget { background: #12161a; }
4
+ QToolBar { background: #11151a; border: 0; spacing: 6px; padding: 6px; }
5
+ QToolButton, QPushButton {
6
+ background: #26313b; border: 1px solid #394957; border-radius: 4px;
7
+ padding: 6px 10px;
8
+ }
9
+ QToolButton:hover, QPushButton:hover { background: #31404d; }
10
+ QToolButton:pressed, QPushButton:pressed { background: #177f8e; }
11
+ QLineEdit, QSpinBox, QDoubleSpinBox, QComboBox {
12
+ background: #10151a; border: 1px solid #36434e; border-radius: 3px;
13
+ padding: 5px; selection-background-color: #168c9c;
14
+ }
15
+ QTextEdit#notesEditor {
16
+ background: #10151a; border: 1px solid #36434e; border-radius: 3px;
17
+ padding: 7px; selection-background-color: #168c9c;
18
+ }
19
+ QTreeWidget, QListWidget, QPlainTextEdit {
20
+ background: #11161b; border: 0; alternate-background-color: #151b21;
21
+ }
22
+ QTreeWidget::item { padding: 4px; }
23
+ QTreeWidget::item:selected, QListWidget::item:selected { background: #176b78; }
24
+ QHeaderView::section { background: #202830; border: 0; padding: 5px; }
25
+ QDockWidget::title { background: #202830; padding: 7px; }
26
+ QSplitter::handle { background: #0f1216; }
27
+ QStatusBar { background: #11151a; }
28
+ QScrollBar { background: #12171c; width: 10px; height: 10px; }
29
+ QScrollBar::handle { background: #3b4853; border-radius: 5px; min-height: 22px; }
30
+ """