From 5cfb9e45832f402ee8cf2884708746e73d232dd2 Mon Sep 17 00:00:00 2001 From: Ryan James Date: Sat, 28 Nov 2026 17:01:55 -0700 Subject: [PATCH] Show diagrams from a terminal with draw() draw() with no filename raised TypeError: it passed format to graphviz.Digraph.view, which takes none. It now shows the diagram inline in terminals that support the kitty graphics protocol (kitty, Ghostty; not inside tmux or screen), at a resolution that matches the terminal's text and fits the window, and otherwise opens a temporary PDF in the system viewer. draw(filename, view=True) rendered a second time through view(), which overwrote the file it had just written with the DOT source and opened .svg.pdf. It now opens the file it wrote. --- CHANGELOG.md | 8 +++ docs/viz.rst | 9 ++- sofic/base.py | 7 ++- sofic/viz/_terminal.py | 67 ++++++++++++++++++++++ sofic/viz/graphviz.py | 29 +++++++--- tests/test_viz.py | 122 +++++++++++++++++++++++++++++++++++++++++ 6 files changed, 233 insertions(+), 9 deletions(-) create mode 100644 sofic/viz/_terminal.py diff --git a/CHANGELOG.md b/CHANGELOG.md index 2b607c3..d99ce86 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,14 @@ A second correctness review: every fix below was reproduced against a brute-force reference or a closed-form value and has a regression test. +### Drawing from a terminal + +- `draw()` with no filename shows the diagram: inline in terminals that support the kitty graphics protocol (kitty, + Ghostty; not inside tmux or screen), with its text matched to the terminal's and fit to the window, and otherwise + as a temporary PDF in the system viewer. It raised `TypeError`, passing `format` to `graphviz.Digraph.view`. +- `draw(filename, view=True)` opens the file it wrote. It overwrote that file with the DOT source and opened + `.svg.pdf`. + ### Truncated bidirectional machines - `generative_model` no longer reports lower bounds of a truncation as bounds on the process. When the reverse diff --git a/docs/viz.rst b/docs/viz.rst index 5b24979..449b7ba 100644 --- a/docs/viz.rst +++ b/docs/viz.rst @@ -21,13 +21,20 @@ installed (``pip install sofic[viz]`` plus the system ``graphviz`` binary): from sofic.examples import golden_mean eps = golden_mean(0.5) - eps.draw() # write / view a rendered diagram + eps.draw() # show the diagram (see below) + eps.draw("golden_mean") # write golden_mean.svg dot = eps.to_graphviz() # a graphviz.Digraph for further styling svg = sofic.viz.model_to_svg(eps) Models implement Jupyter display via ``_repr_mimebundle_``, so simply evaluating a model in a notebook shows its diagram when Graphviz is available. +From a terminal (IPython or the plain Python REPL), ``draw()`` with no filename +shows the diagram inline in terminals that support the `kitty graphics protocol +`__ (kitty, Ghostty), with +its text matched to the terminal's and fit to the window. Elsewhere, including +inside tmux or screen, it opens a temporary PDF in the system viewer. + By default, edges that share an emission (or an input/label symbol, on automata and shifts with no emissions) are drawn in the same colour. Pass ``color_by_emission=False`` to ``draw`` / ``to_graphviz`` / ``to_tikz`` for diff --git a/sofic/base.py b/sofic/base.py index 1fb1659..f57a0c4 100644 --- a/sofic/base.py +++ b/sofic/base.py @@ -168,7 +168,12 @@ def to_graphviz(self, **kwargs: Any) -> Any: return model_to_graphviz(self, **kwargs) def draw(self, filename: str | None = None, **kwargs: Any) -> str | None: - """Render this model with Graphviz.""" + """Render this model with Graphviz to ``filename``, or show it. + + Without ``filename`` the diagram appears inline in terminals that + support the kitty graphics protocol (kitty, Ghostty) and otherwise in + the system viewer; see :func:`sofic.viz.draw`. + """ from sofic.viz.graphviz import draw return draw(self, filename=filename, **kwargs) diff --git a/sofic/viz/_terminal.py b/sofic/viz/_terminal.py new file mode 100644 index 0000000..ef91275 --- /dev/null +++ b/sofic/viz/_terminal.py @@ -0,0 +1,67 @@ +"""Inline diagrams in terminals that support the kitty graphics protocol. + +The protocol is specified at https://sw.kovidgoyal.net/kitty/graphics-protocol/. +""" + +from __future__ import annotations + +import base64 +import math +import os +import struct +from typing import TextIO + +# Graphviz points per terminal row: 11pt node labels then come out about as tall as the terminal's text. +_POINTS_PER_ROW = 14 +# Largest base64 payload of one escape sequence. +_CHUNK = 4096 + + +def supports_kitty_graphics(stream: TextIO) -> bool: + """Whether ``stream`` is a kitty or Ghostty terminal outside tmux and screen. + + Multiplexers drop the protocol's escape sequences unless configured to pass them through. + """ + env = os.environ + if "TMUX" in env or "STY" in env or not stream.isatty(): + return False + return ( + env.get("TERM") in ("xterm-kitty", "xterm-ghostty") + or env.get("TERM_PROGRAM") == "ghostty" + or "KITTY_WINDOW_ID" in env + ) + + +def terminal_graph_attr(stream: TextIO) -> dict[str, str]: + """Graphviz ``dpi`` and ``size`` matching a diagram to the terminal's text and window. + + Empty when the terminal does not report its size in pixels. + """ + try: + import fcntl + import termios + + winsize = fcntl.ioctl(stream.fileno(), termios.TIOCGWINSZ, bytes(8)) + except (ImportError, OSError, ValueError): + return {} + rows, _, width, height = struct.unpack("4H", winsize) + if rows < 3 or not width or not height: + return {} + row = height / rows + dpi = round(72 * row / _POINTS_PER_ROW) + # Fit the window, leaving two rows for the prompt; Graphviz rounds pixel sizes up. + width_in = math.floor(1000 * width / dpi) / 1000 + height_in = math.floor(1000 * (height - 2 * row) / dpi) / 1000 + return {"dpi": str(dpi), "size": f"{width_in},{height_in}"} + + +def kitty_image(png: bytes) -> str: + """Escape sequences that display ``png`` at the cursor.""" + data = base64.standard_b64encode(png).decode("ascii") + chunks = [data[i : i + _CHUNK] for i in range(0, len(data), _CHUNK)] + parts = [] + for i, chunk in enumerate(chunks): + keys = "a=T,f=100,q=2," if i == 0 else "" # transmit and display a PNG, without replies + more = int(i < len(chunks) - 1) + parts.append(f"\x1b_G{keys}m={more};{chunk}\x1b\\") + return "".join(parts) diff --git a/sofic/viz/graphviz.py b/sofic/viz/graphviz.py index ad8dd29..ee1920f 100644 --- a/sofic/viz/graphviz.py +++ b/sofic/viz/graphviz.py @@ -2,13 +2,17 @@ from __future__ import annotations +import sys +import tempfile from collections.abc import Hashable +from pathlib import Path from typing import TYPE_CHECKING, Any from sofic.base import StateMachine from sofic.viz._context import VizContext, viz_context from sofic.viz._format import format_state from sofic.viz._names import node_names +from sofic.viz._terminal import kitty_image, supports_kitty_graphics, terminal_graph_attr if TYPE_CHECKING: import graphviz @@ -150,15 +154,26 @@ def draw( view: bool = False, **kwargs: Any, ) -> str | None: - """Render ``model`` to a file or open it in a viewer. + """Render ``model`` to a file, or show it. - Returns the output path when ``filename`` is given. + With ``filename``, write the diagram in ``format`` and return the output + path; ``view=True`` also opens it in the system viewer. + + Without ``filename``, show the diagram, also from a terminal (IPython or + the plain REPL): inline in terminals that support the `kitty graphics + protocol `__ (kitty, + Ghostty; not inside tmux or screen), with its text matched to the + terminal's and fit to the window, and otherwise as a temporary PDF in the + system viewer. ``format`` and ``view`` do not apply then. """ + if filename is None and supports_kitty_graphics(sys.stdout): + kwargs["graph_attr"] = {**terminal_graph_attr(sys.stdout), **(kwargs.get("graph_attr") or {})} + sys.stdout.write(kitty_image(model_to_png(model, **kwargs)) + "\n") + sys.stdout.flush() + return None dot = model_to_graphviz(model, **kwargs) if filename is None: - dot.view(format=format, cleanup=True) + directory = Path(tempfile.mkdtemp(prefix="sofic-")) + dot.render(outfile=directory / f"{dot.name}.pdf", cleanup=True, view=True) return None - path = dot.render(filename=filename, format=format, cleanup=True) - if view: - dot.view(filename=path, cleanup=True) - return path + return dot.render(filename=filename, format=format, cleanup=True, view=view) diff --git a/tests/test_viz.py b/tests/test_viz.py index 2b7e4d8..ef5b46b 100644 --- a/tests/test_viz.py +++ b/tests/test_viz.py @@ -2,6 +2,15 @@ from __future__ import annotations +import base64 +import io +import os +import re +import shutil +import struct +import sys +from pathlib import Path + import pytest from sofic.automata.dfa import DFA @@ -16,6 +25,7 @@ format_prob_rational, format_state, ) +from sofic.viz._terminal import kitty_image, supports_kitty_graphics, terminal_graph_attr from sofic.viz._tikz_format import format_state_tikz_node from sofic.viz.graphviz import model_to_graphviz from sofic.viz.tikz import model_to_tikz @@ -238,6 +248,118 @@ def test_draw_method(tmp_path): assert out.endswith(".svg") +class _Terminal(io.StringIO): + """A captured stream that reports being a terminal.""" + + def isatty(self) -> bool: + return True + + +def _terminal_env(monkeypatch, **env: str) -> None: + for name in ("TERM", "TERM_PROGRAM", "KITTY_WINDOW_ID", "TMUX", "STY"): + monkeypatch.delenv(name, raising=False) + for name, value in env.items(): + monkeypatch.setenv(name, value) + + +def _viewer(monkeypatch) -> list[str]: + """Record the files Graphviz would open in the system viewer, instead of opening them.""" + opened: list[str] = [] + monkeypatch.setattr(graphviz.Digraph, "_view", lambda _self, filepath, **_kwargs: opened.append(filepath)) + return opened + + +def test_draw_view_opens_the_written_file(tmp_path, monkeypatch): + opened = _viewer(monkeypatch) + out = _dfa().draw(filename=str(tmp_path / "dfa"), view=True) + assert opened == [out] + assert [path.name for path in tmp_path.iterdir()] == ["dfa.svg"] + assert "