vsview-graph 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.
vsview_graph/plugin.py ADDED
@@ -0,0 +1,509 @@
1
+ from __future__ import annotations
2
+
3
+ import base64
4
+ import threading
5
+ from functools import partial
6
+ from logging import getLogger
7
+ from pathlib import Path
8
+ from typing import Any, Literal, NamedTuple, assert_never, cast, override
9
+
10
+ import vsengine
11
+ import vsgraph
12
+ from jetpytools import fallback
13
+ from PySide6.QtCore import QUrl, QUrlQuery, Slot
14
+ from PySide6.QtGui import QCursor, QImage, QShowEvent
15
+ from PySide6.QtWidgets import QApplication, QFileDialog, QMenu, QVBoxLayout, QWidget
16
+
17
+ from vsview.api import PluginAPI, VideoOutputProxy, WidgetPluginBase, run_in_background, run_in_loop
18
+ from vsview.env import getenv_bool
19
+
20
+ from .analysis import enrich_cytoscape_payload
21
+ from .bridge import (
22
+ ExportFormat,
23
+ GraphOptionsPayload,
24
+ JsToPyCommand,
25
+ NodeCopyTarget,
26
+ NodeTimingUpdate,
27
+ OutputItem,
28
+ PyToJsCommand,
29
+ )
30
+ from .call import build_filter_call, build_node_report
31
+ from .constants import PLUGIN_DISPLAY_NAME, PLUGIN_IDENTIFIER
32
+ from .settings import GraphSettings, GraphShortcut
33
+ from .theme import extract_theme_tokens
34
+ from .web import GraphWebView
35
+
36
+ logger = getLogger(__name__)
37
+
38
+
39
+ class CachedGraph(NamedTuple):
40
+ graph: vsgraph.Graph[Any]
41
+ payload: dict[str, Any]
42
+
43
+
44
+ class GraphPlugin(WidgetPluginBase[GraphSettings, None]):
45
+ WEB_DIST_DIR = Path(__file__).parent / "web_dist"
46
+ INDEX_PATH = WEB_DIST_DIR / "index.html"
47
+
48
+ identifier = PLUGIN_IDENTIFIER
49
+ display_name = PLUGIN_DISPLAY_NAME
50
+
51
+ shortcuts = tuple(s.definition for s in GraphShortcut)
52
+
53
+ def __init__(self, parent: QWidget, api: PluginAPI) -> None:
54
+ super().__init__(parent, api)
55
+
56
+ self._selected_idx: int | None = None
57
+ self._is_dirty = False
58
+ self._selected_node_id: str | None = None
59
+
60
+ self._graph_cache = dict[int, CachedGraph]()
61
+ self._generation = 0
62
+ self._sent_key: tuple[int, int] | None = None
63
+ self._last_sent_timings = dict[str, int]()
64
+ self._load_lock = threading.RLock()
65
+
66
+ self._load_ready = False
67
+
68
+ self._sent_options = dict[str, Any]()
69
+ self._view_direction: Literal["TB", "LR"] | None = None
70
+ self._pending_png_path: str | None = None
71
+
72
+ layout = QVBoxLayout(self)
73
+ layout.setContentsMargins(0, 0, 0, 0)
74
+
75
+ self.view = GraphWebView(self)
76
+ layout.addWidget(self.view)
77
+ self.view.bridge.webReady.connect(self._on_web_ready)
78
+ self.view.bridge.commandReceived.connect(self._on_command_received)
79
+
80
+ self.context_menu = QMenu(self)
81
+ self.fit_act = self.context_menu.addAction("Fit to View")
82
+ self.fit_act.triggered.connect(self._on_fit_view_triggered)
83
+ self.reset_act = self.context_menu.addAction("Reset View")
84
+ self.reset_act.triggered.connect(self._on_reset_view_triggered)
85
+ self.reload_act = self.context_menu.addAction("Reload Graph")
86
+ self.reload_act.triggered.connect(self._on_reload_graph_triggered)
87
+
88
+ self.context_menu.addSeparator()
89
+
90
+ copy_menu = self.context_menu.addMenu("Copy Graph as")
91
+ copy_png_act = copy_menu.addAction("PNG Image")
92
+ copy_png_act.triggered.connect(self._on_copy_png_triggered)
93
+ copy_menu.addSeparator()
94
+
95
+ for fmt in ExportFormat:
96
+ act = copy_menu.addAction(fmt.label)
97
+ act.triggered.connect(partial(self._export_graph, fmt, clipboard=True))
98
+
99
+ save_menu = self.context_menu.addMenu("Save Graph as")
100
+ save_png_act = save_menu.addAction("PNG Image…")
101
+ save_png_act.triggered.connect(self._on_save_png_image)
102
+ save_menu.addSeparator()
103
+
104
+ for fmt in ExportFormat:
105
+ act = save_menu.addAction(f"{fmt.label}…")
106
+ act.triggered.connect(partial(self._export_graph, fmt, clipboard=False))
107
+
108
+ self.addActions([self.fit_act, self.reset_act, self.reload_act])
109
+
110
+ self.api.globalSettingsChanged.connect(self._sync_web_options)
111
+ self.api.globalSettingsChanged.connect(self._sync_keybindings)
112
+ self.api.register_on_destroy(self.on_destroy)
113
+
114
+ self.api.register_action(GraphShortcut.FIT.definition, self.fit_act)
115
+ self.api.register_action(GraphShortcut.RESET_VIEW.definition, self.reset_act)
116
+ self.api.register_action(GraphShortcut.RELOAD.definition, self.reload_act)
117
+
118
+ @property
119
+ def default_export_dir(self) -> Path:
120
+ return path.parent if (path := self.api.file_path) else Path.home()
121
+
122
+ @property
123
+ def default_export_stem(self) -> str:
124
+ return path.stem if (path := self.api.file_path) else "dependency-graph"
125
+
126
+ @property
127
+ def selected_output_index(self) -> int | None:
128
+ """The currently selected video output index, or None if following the active output."""
129
+ return self._selected_idx
130
+
131
+ @override
132
+ def showEvent(self, event: QShowEvent) -> None:
133
+ super().showEvent(event)
134
+ if self._is_dirty or (self._sent_key is None and self.view.bridge.is_ready):
135
+ self.view.sync_theme()
136
+ self.update_outputs()
137
+ self.update_graph(force_layout=True)
138
+
139
+ @override
140
+ def deleteLater(self) -> None:
141
+ self.view.deleteLater()
142
+ super().deleteLater()
143
+
144
+ @override
145
+ def on_current_voutput_changed(self, voutput: VideoOutputProxy, tab_index: int) -> None:
146
+ if not self._load_ready:
147
+ self._load_page()
148
+ self._load_ready = True
149
+
150
+ self.update_outputs()
151
+ if self._selected_idx is None:
152
+ self.update_graph(force_layout=False)
153
+
154
+ @override
155
+ def on_playback_stopped(self) -> None:
156
+ if self._is_dirty:
157
+ self.update_graph()
158
+
159
+ def on_destroy(self) -> None:
160
+ self._generation += 1
161
+ self._selected_idx = None
162
+ self._graph_cache.clear()
163
+ self._sent_key = None
164
+ self._last_sent_timings.clear()
165
+ self._is_dirty = False
166
+ self._selected_node_id = None
167
+
168
+ def select_output(self, index: int | None) -> None:
169
+ self._selected_idx = index if (index is not None and index >= 0) else None
170
+ self.update_outputs()
171
+ self.update_graph(force_layout=True)
172
+
173
+ @run_in_loop(return_future=False)
174
+ def update_outputs(self) -> None:
175
+ if not self.view.bridge.is_ready:
176
+ return
177
+
178
+ voutputs = self.api.voutputs
179
+ current_vs_index = self.api.current_voutput.vs_index
180
+ outputs = list[OutputItem]()
181
+
182
+ for v in voutputs:
183
+ # fmt:off
184
+ is_active = (
185
+ (self._selected_idx == v.vs_index)
186
+ or
187
+ (self._selected_idx is None and v.vs_index == current_vs_index)
188
+ )
189
+ # fmt:on
190
+ outputs.append({"index": v.vs_index, "name": v.vs_name, "isActive": is_active})
191
+
192
+ self.view.bridge.dispatch(
193
+ PyToJsCommand.SET_OUTPUTS,
194
+ {"outputs": outputs, "following": self._selected_idx is None},
195
+ )
196
+
197
+ @run_in_background(name="UpdateGraph")
198
+ def update_graph(self, *, force_layout: bool = False, refresh: bool = False) -> None:
199
+ if not self.view.bridge.is_ready:
200
+ return
201
+
202
+ if self.api.is_playing or (not force_layout and not vsengine.from_thread(self.isVisible).result()):
203
+ self._is_dirty = True
204
+ return
205
+
206
+ self._is_dirty = False
207
+
208
+ with self._load_lock:
209
+ generation = self._generation
210
+ key = self._current_output_key()
211
+
212
+ cached = self._load_graph(key, refresh=refresh)
213
+
214
+ if generation != self._generation:
215
+ return
216
+
217
+ if cached is None:
218
+ self.view.bridge.dispatch(
219
+ PyToJsCommand.SET_ERROR,
220
+ {"message": f"Failed to inspect the dependency graph of output {key}. See the log for details."},
221
+ )
222
+ return
223
+
224
+ node_ids = {n.id for n in cached.graph.nodes}
225
+ sent_key = (generation, key)
226
+ must_send_data = force_layout or sent_key != self._sent_key
227
+
228
+ timings = list[NodeTimingUpdate]()
229
+ timings_map = dict[str, int]()
230
+ for n in cached.graph.nodes:
231
+ timings.append(
232
+ {"id": n.id, "processing_time_ns": n.processing_time_ns, "processing_time_ms": n.processing_time_ms}
233
+ )
234
+ timings_map[n.id] = n.processing_time_ns
235
+
236
+ if must_send_data:
237
+ self._sent_key = sent_key
238
+
239
+ # Drop a selection that no longer exists in the new topology
240
+ if self._selected_node_id is not None and self._selected_node_id not in node_ids:
241
+ self._selected_node_id = None
242
+
243
+ self._last_sent_timings = timings_map
244
+ self.view.bridge.dispatch(PyToJsCommand.SET_DATA, cached.payload)
245
+
246
+ # A freshly loaded page has no selection of its own to restore after setData
247
+ if self._selected_node_id is not None:
248
+ self.view.bridge.dispatch(PyToJsCommand.SELECT_NODE, {"id": self._selected_node_id})
249
+ return
250
+
251
+ timings_changed = timings_map != self._last_sent_timings
252
+
253
+ # An explicit refresh always echoes the timings even when the values themselves did not change.
254
+ if not timings_changed and not refresh:
255
+ return
256
+
257
+ self._last_sent_timings = timings_map
258
+ self.view.bridge.dispatch(PyToJsCommand.UPDATE_TIMINGS, {"timings": timings})
259
+
260
+ @Slot()
261
+ def _on_web_ready(self) -> None:
262
+ self._sent_key = None
263
+ self._last_sent_timings.clear()
264
+ self._sent_options.clear()
265
+ self._view_direction = None
266
+ self._sync_web_options()
267
+ self._sync_keybindings()
268
+ self.view.sync_theme()
269
+ self.update_outputs()
270
+ self.update_graph(force_layout=True)
271
+
272
+ @Slot(str, dict)
273
+ def _on_command_received(self, command: JsToPyCommand, payload: dict[str, Any]) -> None:
274
+ match command:
275
+ case JsToPyCommand.RELOAD:
276
+ self._reload()
277
+ case JsToPyCommand.OUTPUT_SELECT:
278
+ self.select_output(payload.get("index"))
279
+ case JsToPyCommand.NODE_SELECT:
280
+ self._selected_node_id = payload["id"]
281
+ case JsToPyCommand.NODE_DESELECT:
282
+ self._selected_node_id = None
283
+ case JsToPyCommand.NODE_COPY:
284
+ self._copy_node_info(
285
+ str(payload["id"]), NodeCopyTarget(payload["target"]), int(payload.get("frameIdx", 0))
286
+ )
287
+ case JsToPyCommand.CONTEXT_MENU:
288
+ if (direction := payload.get("direction")) in ("TB", "LR"):
289
+ self._view_direction = direction
290
+ self.context_menu.exec(QCursor.pos())
291
+ case JsToPyCommand.EXPORT_GRAPH:
292
+ self._export_graph(ExportFormat(payload["format"]), clipboard=payload["clipboard"])
293
+ case JsToPyCommand.SAVE_IMAGE:
294
+ destination = payload.get("destination")
295
+ if destination == "clipboard":
296
+ self._copy_image(payload["dataBase64"])
297
+ elif destination == "file":
298
+ if (path := self._pending_png_path) is None:
299
+ logger.warning("Ignoring PNG image save that was not requested from the save dialog")
300
+ return
301
+ self._pending_png_path = None
302
+ self._save_image(path, payload["dataBase64"])
303
+ else:
304
+ logger.error("Malformed Payload")
305
+ case _:
306
+ assert_never(command)
307
+
308
+ @Slot()
309
+ def _on_fit_view_triggered(self) -> None:
310
+ self.view.bridge.dispatch(PyToJsCommand.FIT_VIEW)
311
+
312
+ @Slot()
313
+ def _on_reset_view_triggered(self) -> None:
314
+ self.view.bridge.dispatch(PyToJsCommand.RESET_VIEW)
315
+
316
+ @Slot()
317
+ def _on_reload_graph_triggered(self) -> None:
318
+ self._reload()
319
+
320
+ @Slot()
321
+ def _on_copy_png_triggered(self) -> None:
322
+ self.view.bridge.dispatch(PyToJsCommand.REQUEST_PNG_EXPORT, {"destination": "clipboard"})
323
+
324
+ @Slot()
325
+ def _on_save_png_image(self) -> None:
326
+ selected, _ = QFileDialog.getSaveFileName(
327
+ self,
328
+ "Save Graph Image",
329
+ str(self.default_export_dir / f"{self.default_export_stem}-graph.png"),
330
+ "PNG image (*.png)",
331
+ )
332
+ if not selected:
333
+ return
334
+
335
+ self._pending_png_path = selected
336
+ self.view.bridge.dispatch(PyToJsCommand.REQUEST_PNG_EXPORT, {"destination": "file"})
337
+
338
+ @Slot()
339
+ def _sync_web_options(self) -> None:
340
+ if not self.view.bridge.is_ready:
341
+ return
342
+
343
+ settings = self.settings.global_
344
+ options: GraphOptionsPayload = {
345
+ "direction": settings.direction,
346
+ "layout": settings.layout,
347
+ "rankSep": settings.rank_sep,
348
+ "nodeSep": settings.node_sep,
349
+ "heatmap": settings.heatmap_enabled,
350
+ "showTimings": settings.show_timings,
351
+ "timingUnit": settings.timing_unit,
352
+ "autoFitOnReload": settings.auto_fit_on_reload,
353
+ }
354
+
355
+ # globalSettingsChanged fires for every global save, including other plugins' settings.
356
+ # Re-sending unchanged values would revert view-only toggles made from the HUD.
357
+ changed = {key: value for key, value in options.items() if self._sent_options.get(key, ...) != value}
358
+ if not changed:
359
+ return
360
+
361
+ self._sent_options.update(changed)
362
+ if "direction" in changed:
363
+ self._view_direction = None
364
+ self.view.bridge.dispatch(PyToJsCommand.SET_OPTIONS, cast(GraphOptionsPayload, changed))
365
+
366
+ @Slot()
367
+ def _sync_keybindings(self) -> None:
368
+ if not self.view.bridge.is_ready:
369
+ return
370
+
371
+ rules = [
372
+ rule
373
+ for shortcut in GraphShortcut
374
+ if (rule := shortcut.to_rule(self.api.get_shortcut_key_sequence(shortcut.definition))) is not None
375
+ ]
376
+ self.view.bridge.dispatch(PyToJsCommand.SET_KEYBINDINGS, {"keybindings": rules})
377
+
378
+ @run_in_loop(return_future=False)
379
+ def _load_page(self) -> None:
380
+ tokens = extract_theme_tokens(self.palette())
381
+ query = QUrlQuery()
382
+ query.addQueryItem("windowColorRole", tokens["bg"])
383
+ query.addQueryItem("windowTextRole", tokens["textPrimary"])
384
+ query.addQueryItem("accentColor", tokens["accent"])
385
+
386
+ url = (
387
+ QUrl("http://localhost:5174")
388
+ if getenv_bool("VSVIEW_GRAPH_DEV")
389
+ else QUrl.fromLocalFile(GraphPlugin.INDEX_PATH)
390
+ )
391
+ url.setQuery(query)
392
+ self.view.load(url)
393
+
394
+ @run_in_background(name="CopyNodeInfo")
395
+ def _copy_node_info(self, node_id: str, target: NodeCopyTarget, frame_idx: int = 0) -> None:
396
+ if target == NodeCopyTarget.ID:
397
+ vsengine.from_thread(lambda: QApplication.clipboard().setText(node_id))
398
+ self.api.statusMessage.emit(f"Copied {target.description}")
399
+ return
400
+
401
+ if (cached := self._load_graph(self._current_output_key())) is None:
402
+ return
403
+
404
+ if (node := cached.graph.nodes_by_id.get(node_id)) is None:
405
+ logger.warning("Cannot copy %s: node '%s' not found in current graph.", target.description, node_id)
406
+ return
407
+
408
+ with self.api.vs_context():
409
+ match target:
410
+ case NodeCopyTarget.CALL:
411
+ text = build_filter_call(node, frame_idx)
412
+ case NodeCopyTarget.REPORT:
413
+ text = build_node_report(node, is_root=node.id == cached.graph.root_id)
414
+ case _:
415
+ assert_never(target)
416
+
417
+ vsengine.from_thread(lambda: QApplication.clipboard().setText(text))
418
+ self.api.statusMessage.emit(f"Copied {target.description}")
419
+
420
+ @run_in_background(name="ExportGraph")
421
+ def _export_graph(self, fmt: ExportFormat, clipboard: bool) -> None:
422
+ if (cached := self._load_graph(self._current_output_key())) is None:
423
+ return
424
+
425
+ direction = fallback(self._view_direction, self.settings.global_.direction)
426
+
427
+ with self.api.vs_context():
428
+ match fmt:
429
+ case ExportFormat.DOT:
430
+ text = cached.graph.to_dot(direction=direction)
431
+ case ExportFormat.MERMAID:
432
+ text = cached.graph.to_mermaid()
433
+ case ExportFormat.ASCII:
434
+ text = cached.graph.to_ascii()
435
+ case ExportFormat.JSON:
436
+ text = cached.graph.to_json(indent=2)
437
+ case _:
438
+ assert_never(fmt)
439
+
440
+ if clipboard:
441
+ vsengine.from_thread(lambda: QApplication.clipboard().setText(text))
442
+ self.api.statusMessage.emit(f"Copied dependency graph as {fmt.upper()}")
443
+ return
444
+
445
+ selected, _ = vsengine.from_thread(
446
+ QFileDialog.getSaveFileName,
447
+ self,
448
+ "Export Dependency Graph",
449
+ str(self.default_export_dir / f"{self.default_export_stem}-graph{fmt.suffix}"),
450
+ fmt.file_filter,
451
+ ).result()
452
+
453
+ if not selected:
454
+ return
455
+
456
+ Path(selected).write_text(text, encoding="utf-8")
457
+ self.api.statusMessage.emit(f"Saved dependency graph to {selected}")
458
+
459
+ def _reload(self) -> None:
460
+ self.update_outputs()
461
+ self.update_graph(refresh=True)
462
+
463
+ def _current_output_key(self) -> int:
464
+ return fallback(self._selected_idx, self.api.current_voutput.vs_index)
465
+
466
+ def _load_graph(self, key: int, *, refresh: bool = False) -> CachedGraph | None:
467
+ with self._load_lock:
468
+ if refresh:
469
+ self._graph_cache.pop(key, None)
470
+
471
+ if (cached := self._graph_cache.get(key)) is not None:
472
+ return cached
473
+
474
+ if (voutput := next((v for v in self.api.voutputs if v.vs_index == key), None)) is None:
475
+ logger.error("Failed to extract graph: output %d does not exist", key)
476
+ return None
477
+
478
+ generation = self._generation
479
+
480
+ with self.api.vs_context():
481
+ try:
482
+ graph = vsgraph.get_graph(voutput.vs_output.clip)
483
+ cached = CachedGraph(graph=graph, payload=enrich_cytoscape_payload(graph, graph.to_cytoscape()))
484
+ except Exception as e:
485
+ logger.error("Failed to extract graph from output %d: %s", key, e)
486
+ logger.debug("", exc_info=e)
487
+ return None
488
+
489
+ self._graph_cache[key] = cached
490
+ if generation != self._generation:
491
+ self._graph_cache.pop(key, None)
492
+
493
+ return cached
494
+
495
+ @run_in_background(name="CopyImage")
496
+ def _copy_image(self, data_base64: str) -> None:
497
+ encoded = data_base64.split(",", 1)[-1].strip()
498
+ image = QImage()
499
+ image.loadFromData(base64.b64decode(encoded, validate=True), "PNG")
500
+ vsengine.from_thread(lambda: QApplication.clipboard().setImage(image))
501
+ self.api.statusMessage.emit("Copied graph image to clipboard")
502
+ logger.info("Copied graph image to clipboard")
503
+
504
+ @run_in_background(name="SaveImage")
505
+ def _save_image(self, path: str, data_base64: str) -> None:
506
+ encoded = data_base64.split(",", 1)[-1].strip()
507
+ Path(path).write_bytes(base64.b64decode(encoded, validate=True))
508
+ self.api.statusMessage.emit(f"Saved graph image to {path}")
509
+ logger.info("Saved graph image to %s", path)
vsview_graph/py.typed ADDED
@@ -0,0 +1 @@
1
+
@@ -0,0 +1,164 @@
1
+ from __future__ import annotations
2
+
3
+ from enum import StrEnum
4
+ from typing import Annotated, Literal, Self, cast
5
+
6
+ from pydantic import BaseModel
7
+ from PySide6.QtCore import QKeyCombination, Qt
8
+ from PySide6.QtGui import QKeySequence
9
+
10
+ from vsview.api import ActionDefinition, Checkbox, Dropdown, Spin
11
+
12
+ from .bridge import KeybindingRule
13
+ from .constants import PLUGIN_IDENTIFIER
14
+
15
+
16
+ class GraphSettings(BaseModel):
17
+ direction: Annotated[
18
+ Literal["TB", "LR"],
19
+ Dropdown(
20
+ label="Layout Direction",
21
+ items=[("Top to Bottom (Vertical)", "TB"), ("Left to Right (Horizontal)", "LR")],
22
+ tooltip="Default layout orientation for the filter dependency graph.",
23
+ ),
24
+ ] = "TB"
25
+
26
+ layout: Annotated[
27
+ Literal["dagre", "breadthfirst", "concentric", "grid"],
28
+ Dropdown(
29
+ label="Layout Algorithm",
30
+ items=[
31
+ ("Dagre (Hierarchical)", "dagre"),
32
+ ("Breadth First", "breadthfirst"),
33
+ ("Concentric", "concentric"),
34
+ ("Grid", "grid"),
35
+ ],
36
+ tooltip=(
37
+ "Graph layout algorithm.\n"
38
+ "Dagre is the only one that honours the layout direction; the others ignore it."
39
+ ),
40
+ ),
41
+ ] = "dagre"
42
+
43
+ rank_sep: Annotated[
44
+ int,
45
+ Spin(
46
+ label="Rank Separation",
47
+ min=20,
48
+ max=200,
49
+ suffix=" px",
50
+ tooltip="Distance between dependency ranks in the Dagre layout.",
51
+ ),
52
+ ] = 60
53
+
54
+ node_sep: Annotated[
55
+ int,
56
+ Spin(
57
+ label="Node Separation",
58
+ min=10,
59
+ max=200,
60
+ suffix=" px",
61
+ tooltip="Distance between sibling nodes in the Dagre and Concentric layouts.",
62
+ ),
63
+ ] = 40
64
+
65
+ heatmap_enabled: Annotated[
66
+ bool,
67
+ Checkbox(
68
+ label="Profiling Heatmap",
69
+ text="Enable profiling heatmap by default",
70
+ tooltip="Highlight nodes using color gradations representing relative execution time.",
71
+ ),
72
+ ] = False
73
+
74
+ auto_fit_on_reload: Annotated[
75
+ bool,
76
+ Checkbox(
77
+ label="Auto-Fit Viewport",
78
+ text="Fit graph into viewport on reload",
79
+ tooltip="Automatically zoom and fit the entire graph into the viewport when topology reloads.",
80
+ ),
81
+ ] = True
82
+
83
+ show_timings: Annotated[
84
+ bool,
85
+ Checkbox(
86
+ label="Show Timings",
87
+ text="Display execution timings on nodes",
88
+ tooltip="Show execution timings on graph nodes and tooltips.",
89
+ ),
90
+ ] = True
91
+
92
+ timing_unit: Annotated[
93
+ Literal["auto", "ms", "ns"],
94
+ Dropdown(
95
+ label="Timing Unit",
96
+ items=[("Automatic", "auto"), ("Milliseconds (ms)", "ms"), ("Nanoseconds (ns)", "ns")],
97
+ tooltip="Display unit for filter processing timings.",
98
+ ),
99
+ ] = "auto"
100
+
101
+
102
+ # Qt PortableText key names that differ from DOM `KeyboardEvent.key` values.
103
+ QT_TO_DOM_KEYS = {
104
+ "Return": "Enter",
105
+ "Up": "ArrowUp",
106
+ "Down": "ArrowDown",
107
+ "Left": "ArrowLeft",
108
+ "Right": "ArrowRight",
109
+ "Space": " ",
110
+ "Esc": "Escape",
111
+ "Del": "Delete",
112
+ "Ins": "Insert",
113
+ "PgUp": "PageUp",
114
+ "PgDown": "PageDown",
115
+ "Print": "PrintScreen",
116
+ "Menu": "ContextMenu",
117
+ }
118
+
119
+
120
+ class GraphShortcut(StrEnum):
121
+ definition: ActionDefinition
122
+
123
+ FIT = "fit", "Fit Graph", "F"
124
+ RESET_VIEW = "reset_view", "Reset Zoom", "Ctrl+0"
125
+ TOGGLE_HEATMAP = "toggle_heatmap", "Toggle Heatmap", "H"
126
+ TOGGLE_PATTERNS = "toggle_patterns", "Toggle Edge Patterns", "P"
127
+ TOGGLE_OVERVIEW = "toggle_overview", "Toggle Overview Panel", "L"
128
+ RELOAD = "reload", "Reload Graph", "R"
129
+ FOCUS_SEARCH = "focus_search", "Focus Node Search", "/"
130
+ SELECT_ROOT = "select_root", "Select Root Node", "Home"
131
+ SELECT_DEEPEST_LEAF = "select_deepest_leaf", "Select Deepest Leaf", "End"
132
+ CENTER_SELECTED = "center_selected", "Center Selected Node", "Return"
133
+ NAVIGATE_UP = "navigate_up", "Navigate Up / Cycle Inward", "Up"
134
+ NAVIGATE_DOWN = "navigate_down", "Navigate Down / Cycle Outward", "Down"
135
+
136
+ def __new__(cls, value: str, label: str, default_key: str = "") -> Self:
137
+ obj = str.__new__(cls, value)
138
+ obj._value_ = value
139
+ obj.definition = ActionDefinition(f"{PLUGIN_IDENTIFIER}.{value}", label, default_key)
140
+ return obj
141
+
142
+ @property
143
+ def action_name(self) -> str:
144
+ """CamelCase identifier matching TypeScript KeybindingActions."""
145
+ parts = self.value.split("_")
146
+ return parts[0] + "".join(p.capitalize() for p in parts[1:])
147
+
148
+ def to_rule(self, key_sequence: QKeySequence) -> KeybindingRule | None:
149
+ """Convert a configured QKeySequence into a preconfigured payload for the TS frontend."""
150
+ if key_sequence.isEmpty():
151
+ return None
152
+
153
+ combo = cast(QKeyCombination, key_sequence[0]) # type: ignore[index]
154
+ mods = combo.keyboardModifiers()
155
+ key_text = QKeySequence(combo.key()).toString(QKeySequence.SequenceFormat.PortableText)
156
+
157
+ return {
158
+ "action": self.action_name,
159
+ "key": QT_TO_DOM_KEYS.get(key_text, key_text),
160
+ "ctrl": bool(mods & Qt.KeyboardModifier.ControlModifier),
161
+ "shift": bool(mods & Qt.KeyboardModifier.ShiftModifier),
162
+ "alt": bool(mods & Qt.KeyboardModifier.AltModifier),
163
+ "meta": bool(mods & Qt.KeyboardModifier.MetaModifier),
164
+ }