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
12 changes: 12 additions & 0 deletions CHANGES
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,18 @@ _Notes on the upcoming release will go here._

### What's new

#### Submit mode-aware lines with `send_line()` (#121)

{class}`~libvt.aio.AsyncSession`, {class}`~libvt.aio.AsyncTerminalStream`,
{class}`~libvt.aio.PtySession`, and
{class}`~libvt.contrib.subprocess.TerminalProcess` now provide
{meth}`~libvt.aio.PtySession.send_line` to submit a single line honoring
DEC `?2004` bracketed paste and active keyboard encoding modes as one atomic
outbound write. Embedded `\r` and `\n` raise
{exc}`~libvt.exc.UnsafePasteError` unless `sanitize=True`, empty text sends
only `Enter`, and a full outbound buffer raises {exc}`BufferError` without
queuing partial bytes.

#### Extended function keys and modifier-only keys (#129)

{class}`~libvt.input.KeyEvent` and {func}`~libvt.input.encode_input` now accept
Expand Down
3 changes: 1 addition & 2 deletions docs/api/contrib/subprocess.md
Original file line number Diff line number Diff line change
Expand Up @@ -18,8 +18,7 @@ resizes the viewport.
... with sp.open_terminal(command, vt=sp.VT(rows=6, cols=40)) as child:
... _ = child.wait_for("Ready", timeout=8)
... child.resize(rows=8, cols=48)
... child.paste("pear")
... child.send_key("enter")
... child.send_line("pear")
... status = child.wait(timeout=8)
... final = child.wait_eof(timeout=8)
... assert (status, final.snapshot.lines[2]) == (0, "Result: raep")
Expand Down
15 changes: 12 additions & 3 deletions docs/topics/sync-and-asyncio.md
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,7 @@ into a terminal and drives outbound input over an optional writer.
{class}`~libvt.aio.PtySession` (Linux, macOS, and BSD; raises
{exc}`NotImplementedError` on Windows). Both satisfy the structural
{class}`~libvt.aio.AsyncSession` protocol (`terminal`, `eof`, `send`,
`send_event`, `send_key`, `paste`, `drain`, `wait_for`, `aclose`).
`send_event`, `send_key`, `paste`, `send_line`, `drain`, `wait_for`, `aclose`).

Pass the executable and its arguments as a sequence, for example
`open_pty([sys.executable, "-i"])`. For an executable with no arguments,
Expand Down Expand Up @@ -131,14 +131,23 @@ Both {class}`~libvt.aio.AsyncTerminalStream` and {class}`~libvt.aio.PtySession`
queue outbound {meth}`~libvt.aio.PtySession.send`,
{meth}`~libvt.aio.PtySession.send_event`,
{meth}`~libvt.aio.PtySession.send_key`, {meth}`~libvt.aio.PtySession.paste`,
and automatic query replies onto a single bounded FIFO queue (`StreamWriter`
background flusher on {class}`~libvt.aio.AsyncTerminalStream`, paired with
{meth}`~libvt.aio.PtySession.send_line`, and automatic query replies onto a
single bounded FIFO queue (`StreamWriter` background flusher on
{class}`~libvt.aio.AsyncTerminalStream`, paired with
{meth}`~libvt.aio.AsyncTerminalStream.write_eof` for half-close; `add_writer` on
{class}`~libvt.aio.PtySession`). Call `await session.drain()`
({meth}`~libvt.aio.AsyncTerminalStream.drain` /
{meth}`~libvt.aio.PtySession.drain`) to flush or apply backpressure; exceeding
`max_write_buffer` raises {exc}`BufferError`.

Use {meth}`~libvt.aio.PtySession.send_line` for line-oriented prompts. It
wraps non-empty payloads in `?2004` brackets when active (sending only `Enter`
when empty or sanitized to empty), appends the active mode's `Enter` key,
rejects embedded `\r` / `\n` and unsafe controls with
{exc}`~libvt.exc.UnsafePasteError` unless `sanitize=True`, and enqueues the
entire line atomically so a full buffer raises {exc}`BufferError` without
queuing partial bytes.

Await a stream's `drain()` before closing to flush its queue. A PTY drain
waits until buffered bytes drop to `write_high_water` or below. Use
`write_high_water=0` to wait for its entire queue. If a concurrent
Expand Down
77 changes: 77 additions & 0 deletions src/libvt/aio/_core.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,9 @@
MouseEvent,
MouseTracker,
PasteEvent,
_encode_line_payload,
)
from libvt.modes import Mode
from libvt.recorder import find_flight_recorder
from libvt.snapshot import Snapshot
from libvt.terminal import StopOn, Terminal
Expand Down Expand Up @@ -114,6 +116,9 @@ def send_key(self, chord: str, /) -> None:
def paste(self, text: str, /, *, sanitize: bool = False) -> None:
"""Encode *text* as an atomic :class:`~libvt.input.PasteEvent` frame."""

def send_line(self, text: str, /, *, sanitize: bool = False) -> None:
"""Encode *text* as one line followed by Enter and enqueue atomically."""

async def drain(self) -> None:
"""Pause while outbound buffered bytes exceed ``write_high_water``."""

Expand Down Expand Up @@ -642,6 +647,78 @@ def paste(self, text: str, /, *, sanitize: bool = False) -> None:
"""
self.send_event(PasteEvent(text=text, sanitize=sanitize))

def send_line(self, text: str, /, *, sanitize: bool = False) -> None:
r"""Encode *text* as a single line followed by Enter and enqueue atomically.

Respects DEC bracketed paste mode ``?2004`` and active keyboard encoding
modes (such as Kitty ``REPORT_ALL_KEYS`` for Enter), enqueueing the line
text and Enter as one atomic outbound write so the payload and Enter
either fit together or fail together with :exc:`BufferError`.

Embedded ``\r`` and ``\n`` are always rejected when *sanitize* is
``False``, even when ``?2004`` is active. When *text* is empty (or
becomes empty after sanitization), only the encoded Enter key is sent.

Parameters
----------
text : str
Single-line text to submit.
sanitize : bool
When ``False`` (default), raise :exc:`~libvt.exc.UnsafePasteError`
on embedded line breaks or disallowed control/escape characters;
when ``True``, strip them before encoding.

Raises
------
UnsafePasteError
If *sanitize* is ``False`` and *text* contains ``\r``, ``\n``, or
other disallowed control/escape characters.
RuntimeError
If no outbound writer is attached.
OSError
If the outbound transport is closed or half-closed.
BufferError
If buffered outbound bytes plus the combined line and Enter would
exceed :attr:`max_write_buffer`; no partial bytes are queued.

Examples
--------
>>> import asyncio
>>> from libvt.aio import AsyncTerminalStream
>>> class _MemWriter:
... def __init__(self) -> None:
... self.buf = bytearray()
... def write(self, data: bytes, /) -> None:
... self.buf.extend(data)
... async def drain(self) -> None:
... pass
... def close(self) -> None:
... pass
... async def wait_closed(self) -> None:
... pass
>>> async def _demo() -> tuple[bytes, bytes]:
... w = _MemWriter()
... async with AsyncTerminalStream(asyncio.StreamReader(), w) as s:
... s.send_line("pear")
... await s.drain()
... plain = bytes(w.buf)
... w.buf.clear()
... s.terminal.feed(b"\x1b[?2004h")
... s.send_line("pear")
... await s.drain()
... bracketed = bytes(w.buf)
... return plain, bracketed
>>> asyncio.run(_demo())
(b'pear\r', b'\x1b[200~pear\x1b[201~\r')
"""
paste_bytes = _encode_line_payload(
text,
bracketed=self.terminal.modes.is_set(Mode.BRACKETED_PASTE),
sanitize=sanitize,
)
enter_bytes = self.terminal.encode(KeyEvent("enter"))
self._enqueue_outbound(paste_bytes + enter_bytes)

def _cancel_sync_timer(self) -> None:
if self._sync_timer_handle is not None:
self._sync_timer_handle.cancel()
Expand Down
6 changes: 3 additions & 3 deletions src/libvt/aio/_pty.py
Original file line number Diff line number Diff line change
Expand Up @@ -213,9 +213,9 @@ class PtySession(_SessionCore):
"""Async POSIX PTY subprocess session over :class:`~libvt.terminal.Terminal`.

Outbound bytes from :meth:`send`, :meth:`send_event`, :meth:`send_key`,
:meth:`paste`, and synchronous terminal query auto-replies share a single
bounded FIFO queue drained via ``loop.add_writer``, paired with
:meth:`drain` for high-water backpressure.
:meth:`paste`, :meth:`send_line`, and synchronous terminal query
auto-replies share a single bounded FIFO queue drained via
``loop.add_writer``, paired with :meth:`drain` for high-water backpressure.

Attributes
----------
Expand Down
7 changes: 4 additions & 3 deletions src/libvt/aio/_stream.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,9 +32,10 @@ class AsyncTerminalStream(_SessionCore):
Coalesces frame wakeups across DEC mode ``?2026`` synchronized-output
batches (bounded by *sync_timeout* using generation-safe expiry), expires
any active ``?2026`` hold on ``EOF`` and :meth:`aclose`, and queues outbound
:meth:`send`, :meth:`send_event`, :meth:`send_key`, :meth:`paste`, and
automatic query replies onto a non-blocking single-FIFO writer queue so
inbound reads never block on outbound backpressure.
:meth:`send`, :meth:`send_event`, :meth:`send_key`, :meth:`paste`,
:meth:`send_line`, and automatic query replies onto a non-blocking
single-FIFO writer queue so inbound reads never block on outbound
backpressure.
"""

_eof_wait_reason: t.ClassVar[str] = "stream reached EOF before predicate matched"
Expand Down
21 changes: 21 additions & 0 deletions src/libvt/contrib/subprocess.py
Original file line number Diff line number Diff line change
Expand Up @@ -647,6 +647,27 @@ def paste(self, text: str, /, *, sanitize: bool = False) -> None:
"""
self._call(lambda: self._attachment.io.paste(text, sanitize=sanitize))

def send_line(self, text: str, /, *, sanitize: bool = False) -> None:
r"""Queue single-line *text* and Enter atomically for active terminal modes.

Respects DEC bracketed paste ``?2004`` and active keyboard modes while
rejecting embedded ``\r`` / ``\n`` and unsafe controls unless
*sanitize* is ``True``. Empty (or sanitized-empty) input sends only the
encoded Enter key.

Raises
------
libvt.exc.UnsafePasteError
If *text* contains line breaks or unsafe controls and *sanitize* is
false.
BufferError
If the outbound write queue cannot fit the full line and Enter;
call :meth:`drain`. No partial bytes are queued.
ValueError
If the handle is closed.
"""
self._call(lambda: self._attachment.io.send_line(text, sanitize=sanitize))

def drain(self, timeout: float | None = None) -> None:
"""Wait until queued outbound input bytes are written to the terminal.

Expand Down
92 changes: 61 additions & 31 deletions src/libvt/input.py
Original file line number Diff line number Diff line change
Expand Up @@ -607,19 +607,21 @@ def filter_event(
return event


def _is_disallowed_paste_cp(cp: int, *, allow_newlines: bool) -> bool:
if cp == 0x1B or cp == 0x7F or 0x80 <= cp <= 0x9F or cp == 0:
return True
if cp < 0x20:
if cp == 0x09:
return False
return not (allow_newlines and cp in (0x0A, 0x0D))
return False


def is_safe_paste(text: str, *, bracketed: bool = True) -> bool:
"""Return ``True`` when *text* contains no escape or injection control bytes."""
for ch in text:
cp = ord(ch)
if cp == 0x1B or cp == 0x7F or 0x80 <= cp <= 0x9F or cp == 0:
return False
if cp < 0x20:
if ch == "\t":
continue
if bracketed and ch in ("\n", "\r"):
continue
return False
return True
return not any(
_is_disallowed_paste_cp(ord(ch), allow_newlines=bracketed) for ch in text
)


def encode_paste(
Expand All @@ -637,38 +639,66 @@ def encode_paste(
:exc:`~libvt.exc.UnsafePasteError`. Pass ``sanitize=True`` to remove
disallowed characters instead.
"""
allow_newlines = bracketed or allow_unbracketed_newlines
if sanitize:
cleaned: list[str] = []
for ch in text:
cp = ord(ch)
if cp == 0x1B or cp == 0x7F or 0x80 <= cp <= 0x9F or cp == 0:
continue
if cp < 0x20:
if ch == "\t" or (
(bracketed or allow_unbracketed_newlines) and ch in ("\n", "\r")
):
cleaned.append(ch)
continue
cleaned.append(ch)
payload = "".join(cleaned).encode("utf-8")
payload = "".join(
ch
for ch in text
if not _is_disallowed_paste_cp(ord(ch), allow_newlines=allow_newlines)
).encode("utf-8")
else:
for ch in text:
cp = ord(ch)
if not _is_disallowed_paste_cp(cp, allow_newlines=allow_newlines):
continue
if cp == 0x1B or cp == 0x7F or 0x80 <= cp <= 0x9F or cp == 0:
msg = f"paste contains unsafe control/escape codepoint U+{cp:04X}"
raise UnsafePasteError(msg)
if cp < 0x20:
if ch == "\t":
continue
if (bracketed or allow_unbracketed_newlines) and ch in ("\n", "\r"):
continue
msg = (
f"paste contains newline/control U+{cp:04X} while bracketed "
f"paste (?2004) is {'enabled' if bracketed else 'disabled'}"
)
raise UnsafePasteError(msg)
payload = text.encode("utf-8")

if bracketed:
return b"\x1b[200~" + payload + b"\x1b[201~"
return payload


def _encode_line_payload(
text: str,
*,
bracketed: bool,
sanitize: bool = False,
) -> bytes:
"""Encode single-line text without embedded line breaks for ``send_line()``."""
if sanitize:
payload = "".join(
ch
for ch in text
if not _is_disallowed_paste_cp(ord(ch), allow_newlines=False)
).encode("utf-8")
else:
for ch in text:
cp = ord(ch)
if not _is_disallowed_paste_cp(cp, allow_newlines=False):
continue
if cp in (0x0A, 0x0D):
msg = (
f"paste contains newline/control U+{cp:04X} while bracketed "
f"paste (?2004) is {'enabled' if bracketed else 'disabled'}"
f"line contains embedded line break U+{cp:04X}; "
"strip line breaks or pass sanitize=True"
)
raise UnsafePasteError(msg)
if cp == 0x1B or cp == 0x7F or 0x80 <= cp <= 0x9F or cp == 0:
msg = f"line contains unsafe control/escape codepoint U+{cp:04X}"
raise UnsafePasteError(msg)
msg = f"line contains disallowed control codepoint U+{cp:04X}"
raise UnsafePasteError(msg)
payload = text.encode("utf-8")

if not payload:
return b""
if bracketed:
return b"\x1b[200~" + payload + b"\x1b[201~"
return payload
Expand Down
Loading
Loading