pvl-dotview 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.
File without changes
@@ -0,0 +1,15 @@
1
+ """Entry point: ``python -m pvl_dotview`` or ``pvl-dotview`` script."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import sys
6
+
7
+ from .app import PvlDotApp
8
+
9
+
10
+ def main() -> None:
11
+ sys.exit(PvlDotApp().run())
12
+
13
+
14
+ if __name__ == "__main__":
15
+ main()
pvl_dotview/app.py ADDED
@@ -0,0 +1,54 @@
1
+ """PvlDotApp — application singleton owning the QApplication and window registry."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import contextlib
6
+ import sys
7
+ import traceback
8
+ from types import TracebackType
9
+
10
+ from PySide6.QtWidgets import QApplication, QMessageBox
11
+
12
+ from .window import PvlDotWindow
13
+
14
+
15
+ class PvlDotApp:
16
+ def __init__(self) -> None:
17
+ self._qapp = QApplication.instance() or QApplication(sys.argv)
18
+ self._windows: list[PvlDotWindow] = []
19
+ sys.excepthook = self._on_uncaught_exception
20
+ self.new_window()
21
+
22
+ def new_window(self) -> PvlDotWindow:
23
+ window = PvlDotWindow(self)
24
+ window.show()
25
+ self._windows.append(window)
26
+ return window
27
+
28
+ def remove_window(self, window: PvlDotWindow) -> None:
29
+ if window in self._windows:
30
+ self._windows.remove(window)
31
+
32
+ def run(self) -> int:
33
+ return self._qapp.exec()
34
+
35
+ def _on_uncaught_exception(
36
+ self,
37
+ exc_type: type[BaseException],
38
+ exc_value: BaseException,
39
+ exc_tb: TracebackType | None,
40
+ ) -> None:
41
+ # Always print to stderr so the trace lands in the terminal too.
42
+ sys.__excepthook__(exc_type, exc_value, exc_tb)
43
+ # Don't pop a dialog for KeyboardInterrupt — let it propagate cleanly.
44
+ if issubclass(exc_type, KeyboardInterrupt):
45
+ return
46
+ tb = "".join(traceback.format_exception(exc_type, exc_value, exc_tb))
47
+ parent = self._windows[0] if self._windows else None
48
+ # If the dialog itself fails, we've already printed to stderr.
49
+ with contextlib.suppress(Exception):
50
+ QMessageBox.critical(
51
+ parent,
52
+ "Unexpected error",
53
+ f"{exc_type.__name__}: {exc_value}\n\n{tb}",
54
+ )
@@ -0,0 +1,35 @@
1
+ """Render a DOT source string to SVG bytes via the graphviz `dot` binary."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import shutil
6
+ import subprocess
7
+
8
+
9
+ class GraphvizNotFoundError(RuntimeError):
10
+ """The `dot` binary is not on PATH."""
11
+
12
+
13
+ class GraphvizRenderError(RuntimeError):
14
+ """`dot` exited non-zero (DOT syntax error or other failure)."""
15
+
16
+
17
+ def render_dot_to_svg(dot_source: str) -> bytes:
18
+ """Invoke `dot -Tsvg` on the DOT source and return the SVG bytes."""
19
+ if not shutil.which("dot"):
20
+ raise GraphvizNotFoundError(
21
+ "Graphviz `dot` binary not found on PATH. "
22
+ "Install with `brew install graphviz` (macOS) or "
23
+ "`apt install graphviz` (Linux)."
24
+ )
25
+ try:
26
+ result = subprocess.run(
27
+ ["dot", "-Tsvg"],
28
+ input=dot_source.encode("utf-8"),
29
+ capture_output=True,
30
+ check=True,
31
+ )
32
+ except subprocess.CalledProcessError as exc:
33
+ stderr = exc.stderr.decode("utf-8", errors="replace").strip()
34
+ raise GraphvizRenderError(stderr or f"dot exited {exc.returncode}") from exc
35
+ return result.stdout
pvl_dotview/window.py ADDED
@@ -0,0 +1,262 @@
1
+ """PvlDotWindow — viewer window backed by QWebEngineView for browser-grade rendering."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import os
6
+ from collections.abc import Callable
7
+ from typing import TYPE_CHECKING, cast
8
+
9
+ from PySide6.QtCore import QChildEvent, QEvent, QObject
10
+ from PySide6.QtGui import (
11
+ QAction,
12
+ QCloseEvent,
13
+ QDragEnterEvent,
14
+ QDragMoveEvent,
15
+ QDropEvent,
16
+ QKeySequence,
17
+ )
18
+ from PySide6.QtWebEngineWidgets import QWebEngineView
19
+ from PySide6.QtWidgets import QMainWindow, QMessageBox, QWidget
20
+
21
+ from .renderer import GraphvizNotFoundError, GraphvizRenderError, render_dot_to_svg
22
+
23
+ if TYPE_CHECKING:
24
+ from .app import PvlDotApp
25
+
26
+
27
+ HTML_TEMPLATE = """<!DOCTYPE html>
28
+ <html>
29
+ <head>
30
+ <meta charset="utf-8">
31
+ <style>
32
+ html, body {
33
+ margin: 0; padding: 0; width: 100%; height: 100%;
34
+ overflow: hidden; background: #ffffff;
35
+ -webkit-user-select: none; user-select: none;
36
+ }
37
+ #viewport {
38
+ position: fixed; inset: 0; overflow: hidden;
39
+ cursor: grab;
40
+ }
41
+ #viewport.panning { cursor: grabbing; }
42
+ #content {
43
+ position: absolute; top: 0; left: 0;
44
+ transform-origin: 0 0;
45
+ will-change: transform;
46
+ }
47
+ #content svg { display: block; }
48
+ .placeholder {
49
+ display: flex; align-items: center; justify-content: center;
50
+ height: 100vh; padding: 0 24px;
51
+ font-family: -apple-system, BlinkMacSystemFont, "Helvetica Neue", sans-serif;
52
+ text-align: center; color: #888; font-size: 16px;
53
+ }
54
+ </style>
55
+ </head>
56
+ <body>
57
+ <div id="viewport"><div id="content">__CONTENT__</div></div>
58
+ <script>
59
+ (function(){
60
+ const viewport = document.getElementById('viewport');
61
+ const content = document.getElementById('content');
62
+
63
+ let scale = 1, tx = 0, ty = 0;
64
+ const ZOOM_BASE = 1.0015;
65
+ const ZOOM_MIN = 0.05;
66
+ const ZOOM_MAX = 50;
67
+
68
+ function applyTransform() {
69
+ content.style.transform = `translate(${tx}px, ${ty}px) scale(${scale})`;
70
+ }
71
+
72
+ function fitToViewport() {
73
+ const svg = content.querySelector('svg');
74
+ if (!svg) {
75
+ tx = 0; ty = 0; scale = 1;
76
+ applyTransform();
77
+ return;
78
+ }
79
+ let svgW = 0, svgH = 0;
80
+ if (svg.viewBox && svg.viewBox.baseVal && svg.viewBox.baseVal.width) {
81
+ svgW = svg.viewBox.baseVal.width;
82
+ svgH = svg.viewBox.baseVal.height;
83
+ } else if (svg.width && svg.width.baseVal) {
84
+ svgW = svg.width.baseVal.value;
85
+ svgH = svg.height.baseVal.value;
86
+ }
87
+ if (!svgW || !svgH) return;
88
+ svg.style.width = svgW + 'px';
89
+ svg.style.height = svgH + 'px';
90
+ const vw = viewport.clientWidth, vh = viewport.clientHeight;
91
+ scale = Math.min(vw / svgW, vh / svgH) * 0.95;
92
+ tx = (vw - svgW * scale) / 2;
93
+ ty = (vh - svgH * scale) / 2;
94
+ applyTransform();
95
+ }
96
+
97
+ viewport.addEventListener('wheel', (e) => {
98
+ e.preventDefault();
99
+ const delta = e.deltaY;
100
+ let factor = Math.pow(ZOOM_BASE, -delta);
101
+ let newScale = scale * factor;
102
+ if (newScale < ZOOM_MIN) { factor = ZOOM_MIN / scale; newScale = ZOOM_MIN; }
103
+ if (newScale > ZOOM_MAX) { factor = ZOOM_MAX / scale; newScale = ZOOM_MAX; }
104
+ const rect = viewport.getBoundingClientRect();
105
+ const cx = e.clientX - rect.left;
106
+ const cy = e.clientY - rect.top;
107
+ tx = cx - (cx - tx) * factor;
108
+ ty = cy - (cy - ty) * factor;
109
+ scale = newScale;
110
+ applyTransform();
111
+ }, { passive: false });
112
+
113
+ let panning = false, lastX = 0, lastY = 0;
114
+ viewport.addEventListener('mousedown', (e) => {
115
+ if (e.button !== 0) return;
116
+ panning = true;
117
+ lastX = e.clientX; lastY = e.clientY;
118
+ viewport.classList.add('panning');
119
+ e.preventDefault();
120
+ });
121
+ document.addEventListener('mousemove', (e) => {
122
+ if (!panning) return;
123
+ tx += e.clientX - lastX;
124
+ ty += e.clientY - lastY;
125
+ lastX = e.clientX; lastY = e.clientY;
126
+ applyTransform();
127
+ });
128
+ document.addEventListener('mouseup', () => {
129
+ if (!panning) return;
130
+ panning = false;
131
+ viewport.classList.remove('panning');
132
+ });
133
+
134
+ // Initial fit. setTimeout 0 lets the SVG layout settle first.
135
+ setTimeout(fitToViewport, 0);
136
+ window.addEventListener('load', fitToViewport);
137
+ })();
138
+ </script>
139
+ </body>
140
+ </html>
141
+ """
142
+
143
+
144
+ PLACEHOLDER_BODY = '<div class="placeholder">Drop a .dot file here</div>'
145
+
146
+
147
+ def _build_html(content: str) -> str:
148
+ return HTML_TEMPLATE.replace("__CONTENT__", content)
149
+
150
+
151
+ def _strip_svg_prologue(svg_text: str) -> str:
152
+ """Drop <?xml?> / <!DOCTYPE> for clean HTML embedding."""
153
+ idx = svg_text.find("<svg")
154
+ return svg_text[idx:] if idx >= 0 else svg_text
155
+
156
+
157
+ class _DropFilter(QObject):
158
+ """Intercept drag-drop events on the webview and any of its inner widgets.
159
+
160
+ QWebEngineView has internal Chromium widgets that consume drag-drop events;
161
+ a filter installed on the view and each of its children catches drops
162
+ regardless of which inner widget receives the OS event first.
163
+ """
164
+
165
+ def __init__(self, on_file_dropped: Callable[[str], None]) -> None:
166
+ super().__init__()
167
+ self._on_file_dropped = on_file_dropped
168
+
169
+ def eventFilter(self, obj: QObject, event: QEvent) -> bool: # noqa: N802
170
+ t = event.type()
171
+ if t == QEvent.Type.DragEnter:
172
+ ev = cast(QDragEnterEvent, event)
173
+ if ev.mimeData().hasUrls():
174
+ ev.acceptProposedAction()
175
+ return True
176
+ elif t == QEvent.Type.DragMove:
177
+ mv = cast(QDragMoveEvent, event)
178
+ if mv.mimeData().hasUrls():
179
+ mv.acceptProposedAction()
180
+ return True
181
+ elif t == QEvent.Type.Drop:
182
+ drop = cast(QDropEvent, event)
183
+ for url in drop.mimeData().urls():
184
+ path = url.toLocalFile()
185
+ if path:
186
+ self._on_file_dropped(path)
187
+ drop.acceptProposedAction()
188
+ return True
189
+ elif t == QEvent.Type.ChildAdded:
190
+ # A new internal widget was just attached — make sure it accepts
191
+ # drops and routes through this filter too.
192
+ child_ev = cast(QChildEvent, event)
193
+ child = child_ev.child()
194
+ if isinstance(child, QWidget):
195
+ child.setAcceptDrops(True)
196
+ child.installEventFilter(self)
197
+ return super().eventFilter(obj, event)
198
+
199
+
200
+ class PvlDotWindow(QMainWindow):
201
+ def __init__(self, app: PvlDotApp) -> None:
202
+ super().__init__()
203
+ self._app = app
204
+ self.setWindowTitle("pvl-dotview")
205
+ self.resize(900, 700)
206
+
207
+ self._view = QWebEngineView(self)
208
+ self.setCentralWidget(self._view)
209
+
210
+ self._drop_filter = _DropFilter(on_file_dropped=self._load)
211
+ self.setAcceptDrops(True)
212
+ self.installEventFilter(self._drop_filter)
213
+ self._view.setAcceptDrops(True)
214
+ self._view.installEventFilter(self._drop_filter)
215
+ for child in self._view.findChildren(QWidget):
216
+ child.setAcceptDrops(True)
217
+ child.installEventFilter(self._drop_filter)
218
+
219
+ self._show_placeholder()
220
+ self._install_shortcuts()
221
+
222
+ def _install_shortcuts(self) -> None:
223
+ new_action = QAction("New Window", self)
224
+ new_action.setShortcut(QKeySequence.StandardKey.New)
225
+ new_action.triggered.connect(self._app.new_window)
226
+ self.addAction(new_action)
227
+
228
+ def _show_placeholder(self) -> None:
229
+ self._view.setHtml(_build_html(PLACEHOLDER_BODY))
230
+
231
+ def _load(self, path: str) -> None:
232
+ filename = os.path.basename(path)
233
+ try:
234
+ with open(path) as f:
235
+ dot_source = f.read()
236
+ svg_body = _strip_svg_prologue(render_dot_to_svg(dot_source).decode("utf-8"))
237
+ except GraphvizNotFoundError as exc:
238
+ QMessageBox.warning(self, "Graphviz not installed", str(exc))
239
+ return
240
+ except GraphvizRenderError as exc:
241
+ QMessageBox.warning(self, "Cannot render DOT file", f"{filename}\n\n{exc}")
242
+ return
243
+ except OSError as exc:
244
+ QMessageBox.warning(self, "Cannot read file", f"{filename}\n\n{exc}")
245
+ return
246
+ except Exception as exc:
247
+ # Catch-all so unexpected failures (UnicodeDecodeError, MemoryError,
248
+ # anything from the subprocess layer we didn't anticipate) show a
249
+ # dialog and the app keeps running instead of crashing.
250
+ QMessageBox.warning(
251
+ self,
252
+ "Unexpected error loading file",
253
+ f"{filename}\n\n{type(exc).__name__}: {exc}",
254
+ )
255
+ return
256
+
257
+ self._view.setHtml(_build_html(svg_body))
258
+ self.setWindowTitle(f"pvl-dotview — {filename}")
259
+
260
+ def closeEvent(self, event: QCloseEvent) -> None: # noqa: N802
261
+ self._app.remove_window(self)
262
+ super().closeEvent(event)
@@ -0,0 +1,65 @@
1
+ Metadata-Version: 2.4
2
+ Name: pvl-dotview
3
+ Version: 0.1.0
4
+ Summary: Interactive Graphviz DOT file viewer with pan, zoom, and multi-window support.
5
+ Project-URL: Homepage, https://github.com/ParkviewLab/pvl-dotview
6
+ Project-URL: Source, https://github.com/ParkviewLab/pvl-dotview
7
+ Project-URL: Issues, https://github.com/ParkviewLab/pvl-dotview/issues
8
+ Author: GaryCoding, Claude Code
9
+ License-Expression: MIT
10
+ License-File: LICENSE
11
+ Keywords: diagram,dot,graphviz,gui,viewer,visualization
12
+ Classifier: Development Status :: 3 - Alpha
13
+ Classifier: Intended Audience :: Developers
14
+ Classifier: Operating System :: OS Independent
15
+ Classifier: Programming Language :: Python :: 3
16
+ Classifier: Programming Language :: Python :: 3.11
17
+ Classifier: Programming Language :: Python :: 3.12
18
+ Classifier: Programming Language :: Python :: 3.13
19
+ Classifier: Topic :: Scientific/Engineering :: Visualization
20
+ Requires-Python: >=3.11
21
+ Requires-Dist: pyside6>=6.7
22
+ Description-Content-Type: text/markdown
23
+
24
+ # pvl-dotview
25
+
26
+ Interactive Graphviz DOT file viewer. Drop a `.dot` file onto a blank window
27
+ and the graph is rendered as crisp, pannable, zoomable vector graphics
28
+ (via embedded Chromium / Qt WebEngine for browser-grade SVG fidelity). Open
29
+ additional windows with **⌘N** (macOS) or **Ctrl+N** (Linux/Windows).
30
+
31
+ ## Install
32
+
33
+ `pvl-dotview` shells out to the `dot` binary at runtime, so Graphviz must be
34
+ installed system-wide before running.
35
+
36
+ ### As a tool (recommended for end users)
37
+
38
+ ```bash
39
+ # macOS
40
+ brew install graphviz
41
+ uv tool install pvl-dotview
42
+
43
+ # Debian/Ubuntu
44
+ sudo apt install graphviz
45
+ uv tool install pvl-dotview
46
+ ```
47
+
48
+ Then run `pvl-dotview` from any terminal.
49
+
50
+ ### From a checkout (for development)
51
+
52
+ ```bash
53
+ brew install graphviz # or: apt install graphviz
54
+ uv sync
55
+ uv run pvl-dotview
56
+ ```
57
+
58
+ ## License
59
+
60
+ This project is released under the [MIT License](LICENSE).
61
+
62
+ Third-party components and their licenses are listed in [NOTICE](NOTICE):
63
+
64
+ - **PySide6** (LGPL-3.0) — used as a dynamically-linked dependency
65
+ - **Graphviz** (EPL-1.0, system dependency, invoked via the `dot` binary)
@@ -0,0 +1,10 @@
1
+ pvl_dotview/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
2
+ pvl_dotview/__main__.py,sha256=P3V8lQkoqUWOe67qWuOIsW_LmK9p-Pd4MjEKdqewg7c,242
3
+ pvl_dotview/app.py,sha256=qjLBdopila9dgdE-ZZTA4emjsFV3EspbZq6n0ke1slo,1776
4
+ pvl_dotview/renderer.py,sha256=I53NmSjxwXC6X61gjfiei3l9fbFWt8Qi8MPHun8SBnY,1128
5
+ pvl_dotview/window.py,sha256=gdMTaxn7TK3X27JQjEqbXgmItUEB9pP1w2LR43YfCI8,8678
6
+ pvl_dotview-0.1.0.dist-info/METADATA,sha256=dtDEJi46hRJn5Fqr3InkzMbfktQuKHVw3PTwoT6qxn0,2056
7
+ pvl_dotview-0.1.0.dist-info/WHEEL,sha256=QccIxa26bgl1E6uMy58deGWi-0aeIkkangHcxk2kWfw,87
8
+ pvl_dotview-0.1.0.dist-info/entry_points.txt,sha256=E7QkiLwb4OEaj1nz6i6uCnhoz0kuT-uWWFfkwjz5DEs,58
9
+ pvl_dotview-0.1.0.dist-info/licenses/LICENSE,sha256=26WCesJP98Lzoif2-upgDz-cPTelFImt-mngg6CcF2w,1080
10
+ pvl_dotview-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.29.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ pvl-dotview = pvl_dotview.__main__:main
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 GaryCoding, Claude Code
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.