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
6 changes: 6 additions & 0 deletions CHANGES
Original file line number Diff line number Diff line change
Expand Up @@ -100,6 +100,12 @@ protection, and the active SGR, OSC 8, and DECSCA pen. The formatter paints
stored glyphs in their recorded widths and preserves pending wrap where it
can reprint the captured margin glyph in place.

#### Read strided terminal input (#186)

Pass a sliced, reversed, or multidimensional `memoryview` to the parser,
terminal, recorder, explainer, PTY writes, or `tmux` control-mode helpers.
Each reads the logical bytes. Step offsets count those bytes.

### Documentation

#### Assert effective colors alongside screen goldens (#190)
Expand Down
4 changes: 2 additions & 2 deletions src/libvt/aio.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@
MouseTracker,
PasteEvent,
)
from libvt.parser import _parse_ascii_uint
from libvt.parser import _byte_view, _parse_ascii_uint
from libvt.terminal import FlightRecorder, Snapshot, Terminal

type TtyMode = t.Literal["cooked", "cbreak", "raw"]
Expand Down Expand Up @@ -1383,7 +1383,7 @@ def _enqueue_write(
*,
is_reply: bool = False,
) -> None:
with memoryview(data) as raw_mv, raw_mv.cast("B") as mv:
with _byte_view(data) as mv:
n_total = len(mv)
if n_total == 0:
return
Expand Down
23 changes: 13 additions & 10 deletions src/libvt/contrib/tmux/control.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,8 @@
import typing as t
from dataclasses import dataclass

from libvt.parser import _byte_view

if t.TYPE_CHECKING:
from libvt.config import Limits, Policy, Profile
from libvt.contrib.tmux.capture import TmuxCaptureResult
Expand Down Expand Up @@ -172,11 +174,11 @@ def unescape_tmux_control_output(data: collections.abc.Buffer | str) -> bytes:
>>> unescape_tmux_control_output(r"\033[32mok\033[0m\015\012")
b'\x1b[32mok\x1b[0m\r\n'
"""
raw = (
data.encode("utf-8", errors="surrogateescape")
if isinstance(data, str)
else bytes(memoryview(data).cast("B"))
)
if isinstance(data, str):
raw = data.encode("utf-8", errors="surrogateescape")
else:
with _byte_view(data) as mv:
raw = mv.tobytes()
if b"\\" not in raw:
return raw
return _OCTAL_ESCAPE_RE.sub(lambda m: bytes((int(m.group(1), 8),)), raw)
Expand Down Expand Up @@ -559,11 +561,12 @@ def feed(self, data: collections.abc.Buffer) -> list[TmuxControlEvent]:
>>> p.feed(b"%exit\n")
[TmuxExit(reason='')]
"""
buf: bytes | bytearray = (
data
if isinstance(data, (bytes, bytearray))
else bytes(memoryview(data).cast("B"))
)
buf: bytes | bytearray
if isinstance(data, (bytes, bytearray)):
buf = data
else:
with _byte_view(data) as mv:
buf = mv.tobytes()
events: list[TmuxControlEvent] = []
pos = 0
n = len(buf)
Expand Down
29 changes: 27 additions & 2 deletions src/libvt/parser.py
Original file line number Diff line number Diff line change
Expand Up @@ -908,14 +908,17 @@ def _cached_csi_params(self, pbytes: bytes) -> CsiParams:
return parsed

def feed(self, data: collections.abc.Buffer) -> list[Action]:
"""Feed *data* and return all completed :data:`Action` items."""
"""Parse the logical bytes of *data* and return completed :data:`Action` items.

A strided memoryview is read in its iteration order.
"""
sink = _ListSink()
self.feed_to(data, sink)
return sink.actions

def feed_to(self, data: collections.abc.Buffer, sink: ActionSink) -> None:
"""Feed *data* directly into *sink* without allocating action wrappers."""
mv = memoryview(data).cast("B")
mv = _byte_view(data)
n = len(mv)
pos = 0
max_osc = self._limits.max_osc_bytes
Expand Down Expand Up @@ -1326,6 +1329,28 @@ def _parse_ascii_uint(raw: str, *, max_val: int) -> int | None:
return acc


def _byte_view(data: collections.abc.Buffer) -> memoryview:
"""Return a fresh flat byte view in logical order, copying only strided data."""
view = memoryview(data)
if view.nbytes == 0:
view.release()
return memoryview(b"")
if view.c_contiguous:
if view.ndim == 1 and view.format == "B":
return view
strides = view.strides
if strides is None or 0 not in strides:
try:
return view.cast("B")
finally:
view.release()
try:
raw = view.tobytes()
finally:
view.release()
return memoryview(raw)


def _parse_ascii_int(raw: str, *, min_val: int, max_val: int) -> int | None:
"""Parse optional ``+``/``-`` plus ASCII digits within ``[min_val, max_val]``."""
if not raw:
Expand Down
7 changes: 4 additions & 3 deletions src/libvt/terminal.py
Original file line number Diff line number Diff line change
Expand Up @@ -106,6 +106,7 @@
Parser,
ParserEncoding,
ParserState,
_byte_view,
_parse_ascii_int,
_parse_ascii_uint,
parse_sgr,
Expand Down Expand Up @@ -547,7 +548,7 @@ def total_bytes(self) -> int:

def record(self, data: collections.abc.Buffer) -> None:
"""Append *data*, retaining at most ``max_bytes`` trailing bytes."""
mv = memoryview(data).cast("B")
mv = _byte_view(data)
n = len(mv)
if n == 0:
return
Expand Down Expand Up @@ -3808,7 +3809,7 @@ def feed(self, data: collections.abc.Buffer, /) -> None:
│line 2 │
└──────────┘
"""
mv = memoryview(data)
mv = _byte_view(data)
if not mv:
return
if self._recorder is not None:
Expand All @@ -3834,7 +3835,7 @@ def feed_until(
>>> step.stopped_on == StopOn.SYNC_END, term.committed.lines, buf[step.offset:]
(True, ('frame 1',), b'trailing')
"""
mv = memoryview(data).cast("B")
mv = _byte_view(data)
n = len(mv)
if offset < 0 or offset > n:
msg = f"offset {offset} out of range for buffer of length {n}"
Expand Down
82 changes: 82 additions & 0 deletions tests/test_aio.py
Original file line number Diff line number Diff line change
Expand Up @@ -504,3 +504,85 @@ def unexpected_open() -> tuple[int, int]:
with pytest.raises(ValueError, match="empty"):
async with open_pty([]):
pytest.fail("empty argv started a process")


async def test_stream_send_accepts_strided_and_empty_multidim_memoryviews() -> None:
"""``AsyncTerminalStream.send`` writes logical bytes for strided and empty views."""
writer = _MemoryWriter()
strided_buf = bytearray(b"A_B_C_D_")
two_d_buf = bytearray(b"IJKL")

async with AsyncTerminalStream(asyncio.StreamReader(), writer) as stream:
with (
memoryview(b"abcd") as empty_raw,
empty_raw.cast("B", shape=(2, 2)) as empty_cast,
empty_cast[:0] as empty_2d,
memoryview(strided_buf) as strided_raw,
strided_raw[::2] as strided,
memoryview(b"HGFE") as rev_raw,
rev_raw[::-1] as rev,
memoryview(two_d_buf) as two_d_raw,
two_d_raw.cast("B", shape=(2, 2)) as two_d,
):
stream.send(empty_2d)
stream.send(empty_2d)
stream.send(strided)
stream.send(rev)
stream.send(two_d)
await stream.drain()

strided_buf.append(0)
two_d_buf.append(0)
assert bytes(writer.buffer) == b"ABCDEFGHIJKL"


@pytest.mark.skipif(sys.platform == "win32", reason="POSIX pty required")
async def test_pty_session_send_accepts_strided_and_empty_multidim_memoryviews() -> (
None
):
"""``PtySession.send`` writes logical bytes and releases intermediate views."""
child_code = (
"import sys\n"
"sys.stdout.write('READY\\n')\n"
"sys.stdout.flush()\n"
"buf = bytearray()\n"
"while len(buf) < 12:\n"
" chunk = sys.stdin.buffer.read(12 - len(buf))\n"
" if not chunk:\n"
" break\n"
" buf.extend(chunk)\n"
"sys.stdout.write('GOT=' + buf.decode('ascii') + '\\n')\n"
"sys.stdout.flush()\n"
)
strided_buf = bytearray(b"A_B_C_D_")
two_d_buf = bytearray(b"IJKL")

async with open_pty(
(sys.executable, "-u", "-c", child_code),
rows=4,
cols=40,
tty_mode="raw",
) as sess:
await sess.wait_for("READY", timeout=3.0)
# Empty multi-D view twice verifies no shared singleton is released.
with (
memoryview(b"abcd") as empty_raw,
empty_raw.cast("B", shape=(2, 2)) as empty_cast,
empty_cast[:0] as empty_2d,
):
sess.send(empty_2d)
sess.send(empty_2d)
with memoryview(strided_buf) as strided_raw, strided_raw[::2] as strided:
sess.send(strided)
strided_buf.append(0)
with memoryview(b"HGFE") as rev_raw, rev_raw[::-1] as rev:
sess.send(rev)
with (
memoryview(two_d_buf) as two_d_raw,
two_d_raw.cast("B", shape=(2, 2)) as two_d,
):
sess.send(two_d)
two_d_buf.append(0)
await sess.drain()
snap = await sess.wait_for("GOT=ABCDEFGHIJKL", timeout=3.0)
assert "GOT=ABCDEFGHIJKL" in snap.text
70 changes: 70 additions & 0 deletions tests/test_codec.py
Original file line number Diff line number Diff line change
Expand Up @@ -114,3 +114,73 @@ def test_cli_rejects_geometry_before_opening_input(
assert not out
assert flag in err and "positive integer" in err and repr(value) in err
assert str(missing) not in err


@pytest.mark.parametrize("reverse", [False, True])
def test_strided_input_uses_logical_bytes_at_every_entry_point(reverse: bool) -> None:
"""Disassembly, recording, parsing and step offsets see the same bytes."""
from libvt import Terminal, render, strip
from libvt.parser import Parser
from libvt.terminal import FlightRecorder, StopOn

payload = b"\x1b[?2026h\x1b[32m" + "界Z".encode() + b"\x1b[?2026lEND"
backing = bytearray(len(payload) * 2)
backing[::2] = payload[::-1] if reverse else payload
view = memoryview(backing)[::2]
if reverse:
view = view[::-1]

assert Parser().feed(view) == Parser().feed(payload)
assert explain(view) == explain(payload)
assert strip(view) == strip(payload)
assert render(view, rows=2, cols=8) == render(payload, rows=2, cols=8)
recorder = FlightRecorder()
terminal = Terminal(rows=2, cols=8, recorder=recorder)
before = terminal.committed
prefix = terminal.feed_until(view, stop=StopOn.SYNC_END)
assert prefix.stopped_on == StopOn.SYNC_END
assert prefix.offset == len(payload) - 3
snap = terminal.committed
assert snap.lines == ("界Z", "")
assert (snap.cursor.row, snap.cursor.col, snap[0].wrapped) == (0, 3, False)
assert [snap[0, i].style.fg for i in range(4)] == [2, 2, 2, None]
terminal.feed(view[prefix.offset :])
assert recorder.tail() == payload
recorder.clear()
recorder.record(view)
assert recorder.tail() == payload
assert (before.lines, snap.lines, terminal.lines) == (
("", ""),
("界Z", ""),
("界ZEND", ""),
)


def test_buffer_shapes_keep_byte_offsets() -> None:
"""Flatten a multidimensional buffer and read a scalar as one byte."""
from libvt import Terminal
from libvt.terminal import FlightRecorder

recorder = FlightRecorder()
terminal = Terminal(rows=1, cols=8, recorder=recorder)
terminal.feed(memoryview(b"X").cast("B", ()))
step = terminal.feed_until(memoryview(b"1234").cast("B", (2, 2)), offset=1)
assert (step.offset, recorder.tail(), terminal.lines) == (4, b"X234", ("X234",))


def test_event_callback_can_release_its_input_view() -> None:
"""Retain the buffer export while a synchronous callback releases its view."""
from libvt import Terminal
from libvt.events import Bell, Event

view = memoryview(b"\x07READY")
seen: list[type[Event]] = []

def release(event: Event) -> None:
seen.append(type(event))
view.release()

terminal = Terminal(rows=1, cols=8, on_event=release)
terminal.feed(view)
assert seen == [Bell]
assert (terminal.lines, terminal.cursor.col) == (("READY",), 5)
Loading
Loading