diff --git a/CHANGES b/CHANGES index a9330d47..bb04a221 100644 --- a/CHANGES +++ b/CHANGES @@ -13,6 +13,13 @@ _Notes on the upcoming release will go here._ Pass `stop=StopOn.PROGRAM_STATUS` to `Terminal.feed_until()` to observe a status transition before processing the rest of a read. +#### Choose a PTY's initial encoding and retain its first events (#164) + +Pass `encoding="latin-1"` and `record_events=True` to +{func}`~libvt.aio.open_pty` to read a legacy program's first bytes and +retrieve its events. {meth}`~libvt.terminal.Terminal.from_size` and the +`vt_factory` and `vt_pty` fixtures accept the same settings. + ### Fixes #### Diagnose a bare PTY command (#165) diff --git a/docs/topics/sync-and-asyncio.md b/docs/topics/sync-and-asyncio.md index 755fbd63..c660396d 100644 --- a/docs/topics/sync-and-asyncio.md +++ b/docs/topics/sync-and-asyncio.md @@ -62,6 +62,26 @@ Pass the executable and its arguments as a sequence, for example `open_pty([sys.executable, "-i"])`. For an executable with no arguments, pass `open_pty([executable])`. +### Choose the startup encoding + +Pass `encoding="latin-1"` to {func}`~libvt.aio.open_pty` when the child +writes Latin-1. Pass `record_events=True` to retain events from its first +read. The `vt_pty` fixture accepts the same arguments. With an existing +stream, pass a configured {class}`~libvt.terminal.Terminal` to +{class}`~libvt.aio.AsyncTerminalStream`. + +```python +>>> import os +>>> from libvt import Terminal +>>> from libvt.events import Bell +>>> term = Terminal.from_size( +... os.terminal_size((8, 2)), encoding="latin-1", record_events=True +... ) +>>> term.feed(b"caf\xe9\x07") +>>> term[0].text, term.drain_events() == (Bell(),) +('café', True) +``` + ### Waiting for screen state {meth}`AsyncTerminalStream.wait_for() ` diff --git a/src/libvt/aio.py b/src/libvt/aio.py index 58bfbcfe..024d1078 100644 --- a/src/libvt/aio.py +++ b/src/libvt/aio.py @@ -34,7 +34,7 @@ MouseTracker, PasteEvent, ) -from libvt.parser import _byte_view, _parse_ascii_uint +from libvt.parser import ParserEncoding, _byte_view, _parse_ascii_uint from libvt.terminal import FlightRecorder, Snapshot, StopOn, Terminal type TtyMode = t.Literal["cooked", "cbreak", "raw"] @@ -2161,6 +2161,8 @@ async def open_pty( profile: Profile = DEFAULT_PROFILE, policy: Policy = DEFAULT_POLICY, limits: Limits = DEFAULT_LIMITS, + encoding: ParserEncoding = "utf-8", + record_events: bool = False, sync_timeout: float = 1.0, write_high_water: int | None = None, max_write_buffer: int = 16_777_216, @@ -2192,6 +2194,11 @@ async def open_pty( Host security and query policy. limits : Limits Parser and state resource ceilings. + encoding : ParserEncoding + Initial byte encoding for child output (``"utf-8"`` or ``"latin-1"``). + record_events : bool + Retain events from the first read for + ``session.terminal.drain_events()``. sync_timeout : float Watchdog timeout in seconds before expiring stalled ``?2026`` frames. write_high_water : int | None @@ -2213,8 +2220,8 @@ async def open_pty( TypeError If *argv* is a bare string. Use ``[executable]`` for one command. ValueError - If *argv*, dimensions, *tty_mode*, *sync_timeout*, or buffer sizes are - invalid. + If *argv*, dimensions, *tty_mode*, *encoding*, *sync_timeout*, or + buffer sizes are invalid. OSError If PTY allocation or ``execvp`` fails. """ @@ -2252,6 +2259,28 @@ async def open_pty( else: py_bin = os.fspath(python_executable) + eff_policy = policy + if policy.osc7_hosts is None: + fqdn = socket.gethostname().lower() + short = fqdn.partition(".")[0] + eff_policy = dataclasses.replace( + policy, + osc7_hosts=DEFAULT_OSC7_HOSTS | frozenset({fqdn, short}), + ) + + recorder = FlightRecorder(max_bytes=limits.max_recorder_bytes) + terminal = Terminal( + rows=rows, + cols=cols, + scrollback=scrollback, + profile=profile, + policy=eff_policy, + limits=limits, + encoding=encoding, + record_events=record_events, + recorder=recorder, + ) + import fcntl import pty import termios @@ -2307,25 +2336,6 @@ async def open_pty( await proc.wait() _raise_exec_error(err_payload, argv[0], errno.ENOEXEC) - eff_policy = policy - if policy.osc7_hosts is None: - fqdn = socket.gethostname().lower() - short = fqdn.partition(".")[0] - eff_policy = dataclasses.replace( - policy, - osc7_hosts=DEFAULT_OSC7_HOSTS | frozenset({fqdn, short}), - ) - - recorder = FlightRecorder(max_bytes=limits.max_recorder_bytes) - terminal = Terminal( - rows=rows, - cols=cols, - scrollback=scrollback, - profile=profile, - policy=eff_policy, - limits=limits, - recorder=recorder, - ) session = PtySession( master_fd=master_fd, process=proc, diff --git a/src/libvt/pytest_plugin.py b/src/libvt/pytest_plugin.py index d9e8b7e7..fe56d230 100644 --- a/src/libvt/pytest_plugin.py +++ b/src/libvt/pytest_plugin.py @@ -14,7 +14,7 @@ from libvt.aio import PtySession, TtyMode from libvt.config import Limits, Policy, Profile from libvt.events import Event - from libvt.parser import Parser + from libvt.parser import Parser, ParserEncoding from libvt.terminal import FlightRecorder, Terminal @@ -31,6 +31,7 @@ def __call__( policy: Policy = ..., limits: Limits = ..., on_event: collections.abc.Callable[[Event], None] | None = None, + encoding: ParserEncoding = "utf-8", record_events: bool = False, recorder: FlightRecorder | None = None, ) -> Terminal: @@ -54,6 +55,8 @@ def __call__( profile: Profile = ..., policy: Policy = ..., limits: Limits = ..., + encoding: ParserEncoding = "utf-8", + record_events: bool = False, sync_timeout: float = 1.0, write_high_water: int | None = None, max_write_buffer: int = 16_777_216, @@ -119,7 +122,7 @@ def vt_factory() -> TerminalFactory: TerminalFactory Keyword-configurable constructor accepting ``rows``, ``cols``, ``scrollback``, ``profile``, ``policy``, ``limits``, ``on_event``, - ``record_events``, and ``recorder``. + ``encoding``, ``record_events``, and ``recorder``. Examples -------- @@ -140,6 +143,7 @@ def _make( policy: Policy = DEFAULT_POLICY, limits: Limits = DEFAULT_LIMITS, on_event: collections.abc.Callable[[Event], None] | None = None, + encoding: ParserEncoding = "utf-8", record_events: bool = False, recorder: FlightRecorder | None = None, ) -> Terminal: @@ -151,6 +155,7 @@ def _make( policy=policy, limits=limits, on_event=on_event, + encoding=encoding, record_events=record_events, recorder=recorder, ) @@ -207,6 +212,8 @@ def _spawn( profile: Profile = DEFAULT_PROFILE, policy: Policy = DEFAULT_POLICY, limits: Limits = DEFAULT_LIMITS, + encoding: ParserEncoding = "utf-8", + record_events: bool = False, sync_timeout: float = 1.0, write_high_water: int | None = None, max_write_buffer: int = 16_777_216, @@ -223,6 +230,8 @@ def _spawn( profile=profile, policy=policy, limits=limits, + encoding=encoding, + record_events=record_events, sync_timeout=sync_timeout, write_high_water=write_high_water, max_write_buffer=max_write_buffer, diff --git a/src/libvt/terminal.py b/src/libvt/terminal.py index ce96b65f..34acf614 100644 --- a/src/libvt/terminal.py +++ b/src/libvt/terminal.py @@ -2353,6 +2353,8 @@ def from_size( profile: Profile = DEFAULT_PROFILE, policy: Policy = DEFAULT_POLICY, limits: Limits = DEFAULT_LIMITS, + encoding: ParserEncoding = "utf-8", + record_events: bool = False, ) -> Terminal: """Construct a :class:`Terminal` from :class:`os.terminal_size`.""" return cls( @@ -2362,6 +2364,8 @@ def from_size( profile=profile, policy=policy, limits=limits, + encoding=encoding, + record_events=record_events, ) @property diff --git a/tests/test_aio.py b/tests/test_aio.py index 672b5f4c..227dcb47 100644 --- a/tests/test_aio.py +++ b/tests/test_aio.py @@ -32,6 +32,7 @@ from libvt.input import MouseAction, MouseButton, MouseEvent from libvt.modes import Mode from libvt.parser import ParserState +from libvt.pytest_plugin import PtyFactory, TerminalFactory class _MemoryWriter: @@ -1575,3 +1576,72 @@ async def read(self, n: int = -1) -> bytes: await closing assert released.is_set() assert (writer.close_calls, writer.wait_calls) == (1, 1) + + +def test_size_and_factory_keep_the_initial_parser_settings( + vt_factory: TerminalFactory, +) -> None: + """Apply decoding and event recording before the first feed.""" + from libvt.events import Bell + + terminals = ( + libvt.Terminal.from_size( + os.terminal_size((6, 2)), encoding="latin-1", record_events=True + ), + vt_factory(rows=2, cols=6, encoding="latin-1", record_events=True), + ) + for terminal in terminals: + before = terminal.committed + terminal.feed(b"\x1b[32mcaf\xe9\x07") + snap = terminal.committed + assert (snap.lines, snap.cursor.col, snap[0].wrapped) == ( + ("café", ""), + 4, + False, + ) + assert [snap[0, col].style.fg for col in range(4)] == [2, 2, 2, 2] + assert terminal.drain_events() == (Bell(),) + assert before.lines == ("", "") + + +@pytest.mark.skipif(sys.platform == "win32", reason="POSIX terminal required") +async def test_pty_startup_keeps_the_first_byte_and_bell(vt_pty: PtyFactory) -> None: + """Read the first Latin-1 output from a child that exits immediately.""" + from libvt.events import Bell + + child = [sys.executable, "-c", r"import os; os.write(1, b'\x1b[32mcaf\xe9\x07')"] + for start in (open_pty, vt_pty): + async with start( + child, + rows=2, + cols=6, + tty_mode="raw", + encoding="latin-1", + record_events=True, + ) as session: + snap = await session.wait_for(lambda _: session.eof) + assert (snap.lines, snap.cursor.col, snap[0].wrapped) == ( + ("café", ""), + 4, + False, + ) + assert snap[0, 3].style.fg == 2 + assert session.terminal.drain_events() == (Bell(),) + + +@pytest.mark.skipif(sys.platform == "win32", reason="POSIX terminal required") +async def test_pty_validates_startup_options_before_openpty( + monkeypatch: pytest.MonkeyPatch, +) -> None: + """Validate serialized encoding settings before opening the PTY.""" + import json + import pty + + def unexpected_openpty() -> t.NoReturn: + pytest.fail("allocated a PTY before validating the startup encoding") + + monkeypatch.setattr(pty, "openpty", unexpected_openpty) + options = json.loads('{"encoding": "latin-2"}') + with pytest.raises(ValueError, match="unsupported parser encoding: 'latin-2'"): + async with open_pty([sys.executable, "-c", "pass"], **options): + pytest.fail("opened a PTY with an unsupported encoding")