Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
`<filename>.svg.pdf`.

### Truncated bidirectional machines

- `generative_model` no longer reports lower bounds of a truncation as bounds on the process. When the reverse
Expand Down
9 changes: 8 additions & 1 deletion docs/viz.rst
Original file line number Diff line number Diff line change
Expand Up @@ -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
<https://sw.kovidgoyal.net/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
Expand Down
7 changes: 6 additions & 1 deletion sofic/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
67 changes: 67 additions & 0 deletions sofic/viz/_terminal.py
Original file line number Diff line number Diff line change
@@ -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)
29 changes: 22 additions & 7 deletions sofic/viz/graphviz.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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 <https://sw.kovidgoyal.net/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)
122 changes: 122 additions & 0 deletions tests/test_viz.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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
Expand Down Expand Up @@ -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 "<svg" in Path(out).read_text(encoding="utf-8")


def test_draw_opens_a_pdf_outside_kitty_terminals(monkeypatch):
_terminal_env(monkeypatch, TERM="xterm-256color", TERM_PROGRAM="Apple_Terminal")
terminal = _Terminal()
monkeypatch.setattr(sys, "stdout", terminal)
opened = _viewer(monkeypatch)
assert _dfa().draw() is None
(path,) = map(Path, opened)
try:
assert path.name == "DFA.pdf"
assert path.read_bytes().startswith(b"%PDF")
finally:
shutil.rmtree(path.parent)
assert terminal.getvalue() == ""


def test_draw_shows_inline_in_kitty_terminals(monkeypatch):
_terminal_env(monkeypatch, TERM="xterm-ghostty")
terminal = _Terminal()
monkeypatch.setattr(sys, "stdout", terminal)
opened = _viewer(monkeypatch)
monkeypatch.setattr("sofic.viz.graphviz.terminal_graph_attr", lambda _stream: {"dpi": "192"})
assert _dfa().draw() is None
assert opened == []
out = terminal.getvalue()
assert out.startswith("\x1b_Ga=T,f=100,")
assert out.endswith("\x1b\\\n")
png = base64.b64decode("".join(re.findall(r";([^\x1b]*)\x1b\\", out)))
expected = model_to_graphviz(_dfa(), graph_attr={"dpi": "192"}).pipe(format="png")
assert png[:24] == expected[:24] # PNG signature and IHDR dimensions


@pytest.mark.parametrize(
("env", "tty", "expected"),
[
({"TERM": "xterm-ghostty"}, True, True),
({"TERM_PROGRAM": "ghostty"}, True, True),
({"TERM": "xterm-kitty"}, True, True),
({"KITTY_WINDOW_ID": "1"}, True, True),
({"TERM": "xterm-256color", "TERM_PROGRAM": "Apple_Terminal"}, True, False),
({"TERM": "xterm-ghostty", "TMUX": "/tmp/tmux-501/default,1,0"}, True, False),
({"TERM": "xterm-kitty", "STY": "1.ttys000.host"}, True, False),
({"TERM": "xterm-ghostty"}, False, False),
],
)
def test_supports_kitty_graphics(monkeypatch, env, tty, expected):
_terminal_env(monkeypatch, **env)
assert supports_kitty_graphics(_Terminal() if tty else io.StringIO()) is expected


def test_kitty_image_chunks_the_payload():
png = b"\x89PNG\r\n\x1a\n" + bytes(range(256)) * 30
out = kitty_image(png)
chunks = re.findall(r"\x1b_G([^;]*);([^\x1b]*)\x1b\\", out)
assert "".join(f"\x1b_G{keys};{data}\x1b\\" for keys, data in chunks) == out
assert [keys for keys, _ in chunks] == ["a=T,f=100,q=2,m=1", "m=1", "m=0"]
assert [len(data) for _, data in chunks[:-1]] == [4096, 4096]
assert base64.b64decode("".join(data for _, data in chunks)) == png


@pytest.mark.parametrize(
("pixels", "expected"),
[((1680, 1360), {"dpi": "175", "size": "9.6,7.382"}), ((0, 0), {})],
)
def test_terminal_graph_attr_reads_the_window_size(pixels, expected):
pty = pytest.importorskip("pty")
import fcntl
import termios

leader, follower = pty.openpty()
try:
# 40 rows of 34 pixels: 11pt labels at 175 dpi are 27 pixels tall
fcntl.ioctl(follower, termios.TIOCSWINSZ, struct.pack("4H", 40, 120, *pixels))
with os.fdopen(follower, "w", closefd=False) as stream:
assert terminal_graph_attr(stream) == expected
finally:
os.close(leader)
os.close(follower)


def test_terminal_graph_attr_needs_a_terminal():
assert terminal_graph_attr(io.StringIO()) == {}


def test_golden_mean_bidirectional_paper_style_dot():
bidir = golden_mean_bidirectional(0.5)
source = model_to_graphviz(bidir).source
Expand Down
Loading