diff --git a/.github/workflows/docs.yml b/.github/workflows/docs.yml index c53950a..13dc99e 100644 --- a/.github/workflows/docs.yml +++ b/.github/workflows/docs.yml @@ -96,7 +96,7 @@ jobs: run: | aws cloudfront create-invalidation \ --distribution-id "${{ secrets.LIBVT_DOCS_DISTRIBUTION }}" \ - --paths "/index.html" "/objects.inv" "/searchindex.js" + --paths "/*" - name: Purge cache on Cloudflare if: env.BUILD_DOCS == 'true' && github.event_name == 'push' && github.ref == 'refs/heads/master' && vars.LIBVT_DOCS_DEPLOY == 'true' diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml index cdfe8e9..10a106d 100644 --- a/.github/workflows/tests.yml +++ b/.github/workflows/tests.yml @@ -9,6 +9,9 @@ on: jobs: test: runs-on: ubuntu-latest + permissions: + contents: read + timeout-minutes: 10 strategy: fail-fast: false matrix: @@ -35,11 +38,55 @@ jobs: - name: Tests (pytest) run: uv run pytest -m "" + test-macos: + runs-on: macos-latest + permissions: + contents: read + timeout-minutes: 10 + steps: + - uses: actions/checkout@v7 + - uses: astral-sh/setup-uv@v10.2.0 + with: + version-file: .tool-versions + enable-cache: true + - uses: actions/setup-python@v7 + with: + python-version: "3.14" + - name: Install dependencies + run: uv sync --all-groups + - name: Type check (ty) + run: uv run ty check --output-format github + - name: Tests (pytest + POSIX PTY) + run: uv run pytest -m "" + + test-windows: + runs-on: windows-latest + permissions: + contents: read + timeout-minutes: 10 + steps: + - uses: actions/checkout@v7 + - uses: astral-sh/setup-uv@v10.2.0 + with: + version-file: .tool-versions + enable-cache: true + - uses: actions/setup-python@v7 + with: + python-version: "3.14" + - name: Install dependencies + run: uv sync --all-groups + - name: Type check (ty) + run: uv run ty check --output-format github + - name: Tests (portable core + stream) + run: uv run pytest -m "" + release: runs-on: ubuntu-latest - needs: test + needs: [test, test-macos, test-windows] if: github.event_name == 'push' && startsWith(github.ref, 'refs/tags') + timeout-minutes: 10 permissions: + contents: read id-token: write attestations: write diff --git a/CHANGES b/CHANGES index 5c05c55..df01434 100644 --- a/CHANGES +++ b/CHANGES @@ -6,6 +6,177 @@ _Notes on the upcoming release will go here._ +### Breaking changes + +#### Cell-calibrated `MouseEvent.pixel_x` and `pixel_y` defaults (#26) + +{attr}`~libvt.input.MouseEvent.pixel_x` and +{attr}`~libvt.input.MouseEvent.pixel_y` now default to `None` +(`int | None = None`) instead of `0` so `?1016` SGR-Pixel encoding derives +cell-center pixel coordinates from `row`, `col`, and +{class}`~libvt.config.Profile` cell geometry unless explicit pixel coordinates +are supplied: + +```python +# Before +ev = MouseEvent(button=MouseButton.LEFT, action=MouseAction.PRESS, row=2, col=3) +assert (ev.pixel_x, ev.pixel_y) == (0, 0) + +# After +ev = MouseEvent(button=MouseButton.LEFT, action=MouseAction.PRESS, row=2, col=3) +assert (ev.pixel_x, ev.pixel_y) == (None, None) # encodes cell center (28, 40) +``` + +#### Scoped `CSI 5:3 m` overline decoding (#18) + +{func}`~libvt.parser.parse_sgr` and live {meth}`~libvt.terminal.Terminal.feed` +ignore `CSI 5:3 m` (`5` with colon subparameter `3`, neither enabling overline +nor blink), matching `tmux` and `Ghostty` input parsing, while +{func}`~libvt.tmux.decode_tmux_capture` continues decoding `tmux` +`grid_string_cells_code`'s `5:3m` overline serialization: + +```python +# Before +style = parse_sgr(CsiParams((5, 3), colon_mask=0b10)) # overline=True + +# After +style = parse_sgr(CsiParams((53,))) # standard SGR 53 overline +res = decode_tmux_capture(["\x1b[5:3mOV\x1b[0m"], rows=1, cols=4) +``` + +#### Opaque per-terminal sync watermarks (#22) + +{class}`~libvt.terminal.SyncToken` keeps its watermark state private, disallows +direct instantiation, and renders a compact `repr()`. Read snapshot state from +{attr}`~libvt.terminal.ScreenDelta.snapshot` rather than inspecting token +attributes directly: + +```python +# Before +cur = tok.cursor + +# After +delta = term.changes_since(tok) +cur = delta.snapshot.cursor +``` + +### What's new + +#### `OSC 4`/`12` queries, `XTMODKEYS`, `?1007`, and pixel `?1016` (#26) + +{class}`~libvt.terminal.Terminal` answers `OSC 4` / `OSC 104` 256-palette +overrides and queries, semicolon-chained `OSC 10`–`12` / `OSC 110`–`112` +foreground, background, and cursor color queries +({attr}`~libvt.config.Profile.cursor_rgb`), `DECRQM` across all ANSI and DEC +modes, `XTSMGRAPHICS` (`CSI ? Pi ; Pa ; Pv S` returning `\x1b[?{pi};3S`), and +`XTMODKEYS` (`CSI > 4 ; pv m` and `CSI ? 4 m` via +{attr}`~libvt.terminal.Terminal.modify_other_keys` and +{attr}`~libvt.screen.Screen.modify_other_keys`), while consuming `OSC 9`, +`OSC 99`, and `OSC 777` notifications silently. +{func}`~libvt.input.encode_input` and {meth}`~libvt.terminal.Terminal.encode` +encode `XTMODKEYS` levels `1` and `2`, default-enabled `?1007` +({attr}`~libvt.modes.Mode.ALTERNATE_SCROLL`) wheel-to-arrow presses on the +alternate screen, and cell-calibrated `?1016` +({attr}`~libvt.input.MouseEvent.pixel_x` / +{attr}`~libvt.input.MouseEvent.pixel_y`) mouse coordinates, while +{meth}`~libvt.terminal.Terminal.resize`, {func}`~libvt.aio.open_pty`, and +{meth}`~libvt.aio.PtySession.resize` report pixel dimensions in `?2048` and +`TIOCSWINSZ`. + +#### Chained `tmux` capture bundles and `-N -T -F` wide-wrap decoding (#18) + +{func}`~libvt.tmux.build_tmux_capture_command` and +{class}`~libvt.tmux.TmuxCaptureCommand` construct single-invocation `tmux` +command chains bracketing `capture-pane -S - -E - -e -p -N -T -F` (`-e -p -N +-T` + `-e -p -J` on `3.4`–`3.7`, `-e -p -N` + `-e -p -J` on `3.3a`) with +`display-message` metadata headers and footers so pane output cannot drift +mid-capture and trailing blank viewport lines survive line-splitting wrappers. +{func}`~libvt.tmux.decode_tmux_capture`, +{meth}`~libvt.terminal.Terminal.from_tmux_capture`, and +{meth}`~libvt.terminal.Snapshot.from_tmux_capture` accept `trim_trailing=True` +to preserve explicit trailing spaces and disambiguate `GRID_FLAG_PADDING` +wide-wrap spacers in a single pass. + +### Fixes + +#### `BCE` hyperlinks, `SU` scrollback, `DEL` UTF-8 flush, and profiles (#25) + +{class}`~libvt.terminal.Terminal` strips `OSC 8` hyperlinks from `BCE` blank +fills, pushes primary-screen `SU` (`CSI Ps S`) lines into scrollback when +unbounded horizontally, ignores non-`m` `CSI` sequences carrying `:` +subparameters while restricting {func}`~libvt.parser.parse_sgr` colons to +well-formed `4`/`38`/`48`/`58` groups, and flushes incomplete multi-byte UTF-8 +sequences on `0x7F` (`DEL`) in {class}`~libvt.parser.Parser`. `DECSLRM` partial +scrolls preserve wide glyphs wholly inside `[left, right]`, and +{class}`~libvt.terminal.Formatter` restores `IRM`, `DECOM`, `DECLRMM`, and +`DECSCUSR` after rendering cells while padding `wrapped=True` rows to `cols`. +{class}`~libvt.config.Profile` splits {data}`~libvt.config.DEFAULT_PROFILE` and +{data}`~libvt.config.XTERM_PROFILE` (VT510 `DECSTR` mode set, shared primary +`DECSC`/`?1049h` save slot with isolated alternate `DECSC` slot, and +`SS2`/`SS3` single-shift preservation) from {data}`~libvt.config.TMUX_PROFILE` +({attr}`~libvt.config.Profile.declrmm_enabled` `False` so `CSI 5;10 s` saves +the cursor, {attr}`~libvt.config.Profile.top_margin_scrolls_to_history` `True`, +and {attr}`~libvt.config.Profile.separate_alt_save_cursor` `True`). + +#### Buffered PTY writes, `?2026` EOF expiry, and frame-commit wakeups (#24) + +{class}`~libvt.aio.PtySession` queues synchronous +{meth}`~libvt.aio.PtySession.send`, {meth}`~libvt.aio.PtySession.paste`, and +terminal query auto-replies onto a single bounded FIFO drained via +`loop.add_writer` with {meth}`~libvt.aio.PtySession.drain` high-water +backpressure, keeping bracketed pastes atomic above kernel `TTYHOG` limits +while flushing `?2048` replies inside {meth}`~libvt.aio.PtySession.resize` and +closing `master_fd` inside non-awaiting `finally` guards. +{class}`~libvt.aio.AsyncTerminalStream` and {class}`~libvt.aio.PtySession` +drive {meth}`~libvt.aio.AsyncTerminalStream.wait_for` and +{meth}`~libvt.aio.PtySession.wait_for` from +{attr}`~libvt.terminal.Terminal.committed_generation` and expire unclosed +`?2026` holds on `EOF`, {meth}`~libvt.aio.AsyncTerminalStream.aclose`, and +{meth}`~libvt.aio.PtySession.aclose`. + +#### Bounded ASCII integer parsing and UTF-8 event accounting (#23) + +{class}`~libvt.parser.Parser`, {class}`~libvt.terminal.Terminal`, +{mod}`libvt.graphics`, {mod}`libvt.status`, and {mod}`libvt.tmux` parse numeric +parameters strictly from ASCII digits `0`–`9` with bounded accumulators +(`<= 65535` for `OSC` command codes, unsigned 32-bit Kitty `i=` / `I=` / `p=` / +`P=` / `Q=` identifiers, and signed 32-bit `OSC 133;D` exit codes), while +{meth}`~libvt.terminal.Terminal.feed` isolates malformed `OSC 7` / `OSC 9;9` +URIs and non-hex `OSC 10` / `OSC 11` color specs without raising `ValueError`. +Event retention limits charge UTF-8 payload bytes across every `Event` variant +in {mod}`libvt.events` under {attr}`~libvt.config.Limits.max_event_bytes`. + +#### Per-terminal sync isolation and horizontal-margin edits (#22) + +{meth}`~libvt.terminal.Terminal.sync_token` and +{meth}`~libvt.terminal.Terminal.changes_since` isolate row-mutation watermarks +per {class}`~libvt.terminal.Terminal` instance and report every cell, +soft-wrap, and direct {attr}`~libvt.terminal.Terminal.screen` mutation in +{attr}`~libvt.terminal.ScreenDelta.dirty_rows`, while `ICH` and `DCH` outside +`DECLRMM` horizontal margins leave soft-wrapped rows intact. + +#### Graphics retention, `DECSTBM` `SIXEL` masking, and streaming reflow (#21) + +{meth}`~libvt.graphics.GraphicsTracker.on_region_scroll` preserves `SIXEL` +visibility masks and scrollback-bound placements when `DECSTBM` top-zero +margins advance scrollback history. {meth}`~libvt.terminal.Terminal.resize` +and {meth}`~libvt.screen.Screen.resize` retain stored images and placements +across reflow and non-reflow resizes, stream unwrapped scrollback lines that +fit within `cols` in `O(1)` per row without reallocating history blocks, +preserve monotonic {attr}`~libvt.terminal.Snapshot.scrolled_total` +continuity, and remap {class}`~libvt.events.PromptZone` and cell-anchored +Kitty {class}`~libvt.graphics.ImagePlacement` `(abs_row, col)` pins. + +### Development + +#### macOS PTY and Windows portable-core CI (#3) + +GitHub Actions exercises Darwin {func}`~libvt.aio.open_pty` (`TIOCSCTTY`, +`TTYHOG` write queueing, and fast-exiting child drain) on `macos-latest` and +portable sans-I/O and {class}`~libvt.aio.AsyncTerminalStream` tests plus `ty` +checks on `windows-latest`, alongside the `Operating System :: Microsoft :: +Windows` classifier. + ## libvt 0.0.1a0 (2026-11-22) Initial pre-alpha release of `libvt`: a pure-Python, zero-dependency virtual diff --git a/MIGRATION b/MIGRATION index 6bd8f70..9b7439f 100644 --- a/MIGRATION +++ b/MIGRATION @@ -13,3 +13,59 @@ Migration and deprecation notes for `libvt` are recorded here; see _Detailed migration steps for the next version will be posted here._ + +### `MouseEvent.pixel_x` and `pixel_y` default to `None` (#26) + +{attr}`~libvt.input.MouseEvent.pixel_x` and +{attr}`~libvt.input.MouseEvent.pixel_y` now have type `int | None = None` so +`?1016` SGR-Pixel encoding derives cell-center coordinates when omitted; pass +`pixel_x=0, pixel_y=0` explicitly when origin `(0, 0)` pixels are intended: + +```python +# Before +ev = MouseEvent(button=MouseButton.LEFT, action=MouseAction.PRESS, row=2, col=3) + +# After (explicit origin pixels) +ev = MouseEvent( + button=MouseButton.LEFT, + action=MouseAction.PRESS, + row=2, + col=3, + pixel_x=0, + pixel_y=0, +) +``` + +### `CSI 5:3 m` overline scoped to `tmux` capture decoding (#18) + +{func}`~libvt.parser.parse_sgr` and live {meth}`~libvt.terminal.Terminal.feed` +no longer treat `CSI 5:3 m` as overline (or blink); emit standard `CSI 53 m` on +live VT streams and pass `tmux capture-pane -e` output through +{func}`~libvt.tmux.decode_tmux_capture` or +{meth}`~libvt.terminal.Terminal.from_tmux_capture`: + +```python +# Before +term.feed(b"\x1b[5:3moverline\x1b[0m") + +# After +term.feed(b"\x1b[53moverline\x1b[0m") +cap_term = Terminal.from_tmux_capture(["\x1b[5:3moverline\x1b[0m"]) +``` + +### Opaque `SyncToken` watermarks (#22) + +{class}`~libvt.terminal.SyncToken` no longer exposes internal watermark fields +or direct construction; obtain tokens from +{meth}`~libvt.terminal.Terminal.sync_token` or +{attr}`~libvt.terminal.ScreenDelta.token` and inspect terminal state via +{attr}`~libvt.terminal.ScreenDelta.snapshot`: + +```python +# Before +cur = tok.cursor + +# After +delta = term.changes_since(tok) +cur = delta.snapshot.cursor +``` diff --git a/docs/_static/css/libvt.css b/docs/_static/css/libvt.css new file mode 100644 index 0000000..c8f5384 --- /dev/null +++ b/docs/_static/css/libvt.css @@ -0,0 +1,17 @@ +/* Keep triple-quoted string literals (.sd) upright for box-drawing alignment. */ +.highlight .sd { + font-style: normal; +} + +/* Prevent unscoped light-theme italic rules from bleeding into dark Monokai. */ +@media not print { + body[data-theme="dark"] .highlight span:not(.ge):not(.ges) { + font-style: normal; + } +} + +@media not print and (prefers-color-scheme: dark) { + body:not([data-theme="light"]) .highlight span:not(.ge):not(.ges) { + font-style: normal; + } +} diff --git a/docs/api/aio.md b/docs/api/aio.md index d3951a4..61a2735 100644 --- a/docs/api/aio.md +++ b/docs/api/aio.md @@ -3,4 +3,10 @@ ```{eval-rst} .. automodule:: libvt.aio :members: + :no-private-members: + +.. py:type:: TtyMode + :canonical: typing.Literal["cooked", "cbreak", "raw"] + + Slave pseudo-terminal line discipline mode passed to :func:`open_pty`. ``` diff --git a/docs/api/config.md b/docs/api/config.md index 4a9fa7c..8a8256a 100644 --- a/docs/api/config.md +++ b/docs/api/config.md @@ -3,4 +3,19 @@ ```{eval-rst} .. automodule:: libvt.config :members: + :no-private-members: + :exclude-members: Charset, SixelErasePolicy + +.. py:type:: Charset + :module: libvt.config + :canonical: typing.Literal['B', '0', 'A'] + + Supported ``G0``–``G3`` character-set designators (US-ASCII, DEC Special, + UK). + +.. py:type:: SixelErasePolicy + :module: libvt.config + :canonical: typing.Literal['cell_mask', 'whole_image'] + + ``SIXEL`` cell-overwrite and rectangular-erase clipping policy. ``` diff --git a/docs/api/graphics.md b/docs/api/graphics.md index ebdb42a..6028cf1 100644 --- a/docs/api/graphics.md +++ b/docs/api/graphics.md @@ -3,4 +3,5 @@ ```{eval-rst} .. automodule:: libvt.graphics :members: + :no-private-members: ``` diff --git a/docs/api/index.md b/docs/api/index.md index 7bc9310..988e7ad 100644 --- a/docs/api/index.md +++ b/docs/api/index.md @@ -66,7 +66,7 @@ Zero-dependency `SIXEL` and Kitty `APC G` `ImageMeta` and `ImagePlacement`. :::{grid-item-card} `libvt.tmux` :link: tmux :link-type: doc -`decode_tmux_capture`, `TmuxPaneMetadata`, and `-CC` `%output` unescaping. +`build_tmux_capture_command`, `decode_tmux_capture`, and `-CC` unescaping. ::: :::: diff --git a/docs/api/input.md b/docs/api/input.md index d913a23..fc9906a 100644 --- a/docs/api/input.md +++ b/docs/api/input.md @@ -3,4 +3,13 @@ ```{eval-rst} .. automodule:: libvt.input :members: + :no-private-members: + :exclude-members: InputEvent + +.. py:type:: InputEvent + :module: libvt.input + :canonical: KeyEvent | MouseEvent | FocusEvent | PasteEvent + + Outbound input event union accepted by :func:`encode_input` and + :meth:`~libvt.terminal.Terminal.encode`. ``` diff --git a/docs/api/modes.md b/docs/api/modes.md index 22a8570..759c75d 100644 --- a/docs/api/modes.md +++ b/docs/api/modes.md @@ -3,4 +3,5 @@ ```{eval-rst} .. automodule:: libvt.modes :members: + :no-private-members: ``` diff --git a/docs/api/parser.md b/docs/api/parser.md index 4fa6010..6a882fb 100644 --- a/docs/api/parser.md +++ b/docs/api/parser.md @@ -3,4 +3,18 @@ ```{eval-rst} .. automodule:: libvt.parser :members: + :no-private-members: + :exclude-members: Action, ParserEncoding + +.. py:type:: ParserEncoding + :module: libvt.parser + :canonical: typing.Literal['utf-8', 'latin-1'] + + Wire input byte encoding accepted by :class:`Parser`. + +.. py:type:: Action + :module: libvt.parser + :canonical: Print | Execute | EscDispatch | CsiDispatch | OscDispatch | DcsDispatch | ApcDispatch + + Closed union of parser actions emitted by :meth:`Parser.feed`. ``` diff --git a/docs/api/screen.md b/docs/api/screen.md index e0c6234..c6f1569 100644 --- a/docs/api/screen.md +++ b/docs/api/screen.md @@ -3,4 +3,5 @@ ```{eval-rst} .. automodule:: libvt.screen :members: + :no-private-members: ``` diff --git a/docs/api/terminal.md b/docs/api/terminal.md index 0338642..47b0353 100644 --- a/docs/api/terminal.md +++ b/docs/api/terminal.md @@ -3,4 +3,13 @@ ```{eval-rst} .. automodule:: libvt.terminal :members: + :no-private-members: + :exclude-members: _state, SyncView + +.. py:type:: SyncView + :module: libvt.terminal + :canonical: typing.Literal['working', 'committed'] + + Buffer view selector for :meth:`Terminal.sync_token` and + :meth:`Terminal.changes_since`. ``` diff --git a/docs/api/tmux.md b/docs/api/tmux.md index c70d87d..352500a 100644 --- a/docs/api/tmux.md +++ b/docs/api/tmux.md @@ -3,4 +3,10 @@ ```{eval-rst} .. automodule:: libvt.tmux :members: + :no-private-members: + +.. py:type:: CaptureInput + :canonical: str | bytes | bytearray | collections.abc.Sequence[str] + + Accepted input payload shapes for ``tmux capture-pane`` decoders. ``` diff --git a/docs/conf.py b/docs/conf.py index a009574..12aaef0 100644 --- a/docs/conf.py +++ b/docs/conf.py @@ -47,6 +47,7 @@ ), }, html_favicon="_static/img/libvt.svg", + html_css_files=["css/libvt.css"], sphinx_font_preload=[ *DEFAULT_SPHINX_FONT_PRELOAD, ("IBM Plex Mono", 600, "normal"), @@ -60,4 +61,5 @@ "project/adr/_template.md", ], ) +conf.setdefault("autodoc_default_options", {})["private-members"] = False globals().update(conf) diff --git a/docs/history.md b/docs/history.md index a98ce00..a40c452 100644 --- a/docs/history.md +++ b/docs/history.md @@ -7,5 +7,5 @@ ``` ```{include} ../CHANGES - +:encoding: utf-8 ``` diff --git a/docs/migration.md b/docs/migration.md index 32199fe..c8f00d8 100644 --- a/docs/migration.md +++ b/docs/migration.md @@ -5,5 +5,5 @@ ``` ```{include} ../MIGRATION - +:encoding: utf-8 ``` diff --git a/docs/project/compatibility.md b/docs/project/compatibility.md index d3eb5eb..4918ce7 100644 --- a/docs/project/compatibility.md +++ b/docs/project/compatibility.md @@ -9,9 +9,9 @@ ## Platforms -| Platform | Status | -|----------|--------| -| Linux | Supported | -| macOS | Supported | -| WSL / WSL2 | Supported | -| Windows | Supported (sans-I/O core and `asyncio` stream adapter) | +| Platform | Scope | +|----------|-------| +| Linux | Full suite including {func}`~libvt.aio.open_pty` | +| macOS | Full suite including {func}`~libvt.aio.open_pty` | +| WSL / WSL2 | Full suite including {func}`~libvt.aio.open_pty` | +| Windows | Sans-I/O core, {class}`~libvt.aio.AsyncTerminalStream`, and `pytest` plugin | diff --git a/docs/topics/architecture.md b/docs/topics/architecture.md index 9ffc258..55c85f9 100644 --- a/docs/topics/architecture.md +++ b/docs/topics/architecture.md @@ -15,12 +15,13 @@ import only the machinery they need: primary-screen soft-wrap resize reflow. 3. **Sans-I/O terminal facade** ({mod}`libvt.terminal`, {mod}`libvt.status`, {mod}`libvt.input`, {mod}`libvt.codec`): - Coordinates dual primary/alternate screens, `Profile` / `Policy` / - `Limits`, `OSC 7501` status records, outbound replies, and input - encoding with zero system calls. + Coordinates dual primary/alternate screens, + {class}`~libvt.config.Profile` / {class}`~libvt.config.Policy` / + {class}`~libvt.config.Limits`, `OSC 7501` status records, outbound + replies, and input encoding with zero system calls. 4. **Transport and test edges** ({mod}`libvt.aio`, {mod}`libvt.testing`, {mod}`libvt.pytest_plugin`): Optional - `asyncio` stream/PTY runners and pytest diagnostics. + {mod}`asyncio` stream/PTY runners and pytest diagnostics. ## Configuration split diff --git a/docs/topics/index.md b/docs/topics/index.md index 639462b..dd7ebbb 100644 --- a/docs/topics/index.md +++ b/docs/topics/index.md @@ -17,7 +17,8 @@ Sans-I/O layering, lazy 64-bit viewport rows, RLE scrollback, and Unicode 17 clu :::{grid-item-card} Synchronized Output & `asyncio` :link: sync-and-asyncio :link-type: doc -DEC `?2026` copy-on-write holds, `feed_until`, `AsyncTerminalStream`, and `open_pty`. +DEC `?2026` copy-on-write holds, {meth}`~libvt.terminal.Terminal.feed_until`, +{class}`~libvt.aio.AsyncTerminalStream`, and {func}`~libvt.aio.open_pty`. ::: :::{grid-item-card} Protocols & Input Encoding diff --git a/docs/topics/migrating-from-pyte.md b/docs/topics/migrating-from-pyte.md index 19dedb0..7cabf1f 100644 --- a/docs/topics/migrating-from-pyte.md +++ b/docs/topics/migrating-from-pyte.md @@ -24,8 +24,8 @@ Unicode 17 grapheme clustering. ## Single byte-stream entry point -Instead of pairing a separate `ByteStream` with a `Screen` or -`HistoryScreen`, feed `bytes`, `bytearray`, or `memoryview` directly to +Instead of pairing a separate `pyte` stream with a screen object, feed +`bytes`, `bytearray`, or {class}`memoryview` directly to {meth}`libvt.Terminal.feed` (or UTF-8 strings via {meth}`libvt.Terminal.feed_str`): diff --git a/docs/topics/protocols-and-input.md b/docs/topics/protocols-and-input.md index 948d1f7..cfd53a4 100644 --- a/docs/topics/protocols-and-input.md +++ b/docs/topics/protocols-and-input.md @@ -22,14 +22,15 @@ fallback): ``` `OSC 7501 ; ?` capability queries answer whenever -`Policy.allow_program_status_query` is `True` (the default) and -`Profile.osc_7501_capabilities` is non-empty, independent of whether -`on_event` or `record_events=True` is attached. +{attr}`~libvt.config.Policy.allow_program_status_query` is `True` (the default) +and {attr}`~libvt.config.Profile.osc_7501_capabilities` is non-empty, +independent of whether `on_event` or `record_events=True` is attached. ## Semantic prompts (`OSC 133`) and queries -`OSC 133` prompt markers record monotonic `abs_row` indices across -scrollback eviction so stored prompt zones remain valid as output +`OSC 133` prompt markers record monotonic +{attr}`~libvt.events.PromptZone.abs_row` indices across scrollback eviction so +stored {attr}`~libvt.terminal.Terminal.prompt_zones` remain valid as output scrolls: ```python @@ -43,14 +44,19 @@ scrolls: {func}`~libvt.input.encode_input` and {meth}`~libvt.terminal.Terminal.encode` consult `DECCKM`, mouse modes (`?9`, `?1000`, `?1002`, `?1003`, `?1006`, -`?1016`), focus reporting (`?1004`), bracketed paste (`?2004`), and the -active screen's Kitty `CSI u` keyboard stack: +`?1007` {attr}`~libvt.modes.Mode.ALTERNATE_SCROLL`, and `?1016` pixel SGR), +focus reporting (`?1004`), bracketed paste (`?2004`), `XTMODKEYS` +(`CSI > 4 ; pv m` via {attr}`~libvt.terminal.Terminal.modify_other_keys`), and +the active screen's {class}`~libvt.input.KittyKeyboardStack`: ```python >>> term = libvt.Terminal(rows=4, cols=20) >>> term.feed(b"\x1b[?1h") >>> term.encode(libvt.KeyEvent.parse("up")) b'\x1bOA' +>>> term.feed(b"\x1b[>4;2m") +>>> term.encode(libvt.KeyEvent.parse("ctrl+;")) +b'\x1b[27;5;59~' ``` {func}`~libvt.input.encode_paste` fails closed with diff --git a/docs/topics/sync-and-asyncio.md b/docs/topics/sync-and-asyncio.md index 5454653..047f846 100644 --- a/docs/topics/sync-and-asyncio.md +++ b/docs/topics/sync-and-asyncio.md @@ -8,8 +8,9 @@ frames. ## Copy-on-write `?2026` holds and `feed_until` -While `term.synchronized` is `True`, {attr}`~libvt.terminal.Terminal.committed` -returns the pre-batch {class}`~libvt.terminal.Snapshot` while +While {attr}`~libvt.terminal.Terminal.synchronized` is `True`, +{attr}`~libvt.terminal.Terminal.committed` returns the pre-batch +{class}`~libvt.terminal.Snapshot` while {meth}`~libvt.terminal.Terminal.snapshot` reflects live in-progress mutations: @@ -28,7 +29,8 @@ mutations: ``` {meth}`~libvt.terminal.Terminal.feed_until` steps through concatenated -captures and stops cleanly at `?2026l` (`StopOn.SYNC_END`), `OSC 133` +captures and stops cleanly at `?2026l` +({attr}`StopOn.SYNC_END `), `OSC 133` prompt boundaries, or `OSC 7501` status transitions: ```python @@ -41,19 +43,35 @@ prompt boundaries, or `OSC 7501` status transitions: If an application crashes mid-frame without closing `?2026l`, {meth}`~libvt.terminal.Terminal.expire_synchronized_output` releases the -hold only when `sync_generation` still matches the stalled batch. +hold only when {attr}`~libvt.terminal.Terminal.sync_generation` still matches +the stalled batch. ## `AsyncTerminalStream` and `open_pty` -{mod}`libvt.aio` wraps sans-I/O terminals for `asyncio` readers/writers +{mod}`libvt.aio` wraps sans-I/O terminals for {mod}`asyncio` readers/writers and POSIX pseudo-terminals without adding background threads to the core: - {class}`~libvt.aio.AsyncTerminalStream` pumps an - `asyncio.StreamReader`, flushes {meth}`~libvt.terminal.Terminal.drain_replies` - to an optional writer, and coalesces `wait_for(...)` wakeups across - `?2026` batches up to `sync_timeout`. + {class}`asyncio.StreamReader`, flushes + {meth}`~libvt.terminal.Terminal.drain_replies` to an optional writer, wakes + {meth}`~libvt.aio.AsyncTerminalStream.wait_for` whenever + {attr}`~libvt.terminal.Terminal.committed_generation` advances (including + straddling `?2026l` … `?2026h` chunks), and expires unclosed `?2026` holds on + `EOF` and {meth}`~libvt.aio.AsyncTerminalStream.aclose`. - {func}`~libvt.aio.open_pty` spawns a child process attached to a - controlling `pty.openpty()` terminal (`TIOCSCTTY`, `TIOCSWINSZ`, - default `SIGPIPE`, and selectable `tty_mode`), forwards terminal query - replies, and calls + controlling {func}`pty.openpty` terminal (`TIOCSCTTY`, `TIOCSWINSZ`, + default `SIGPIPE`, and selectable `tty_mode`), queues outbound user input and + auto-replies on a bounded FIFO drained via `loop.add_writer` and + {meth}`~libvt.aio.PtySession.drain`, flushes `?2048` replies on + {meth}`~libvt.aio.PtySession.resize`, and calls {meth}`~libvt.terminal.Terminal.notify_process_exit` on teardown. + +## Concurrency and thread ownership + +Every method call and attribute read on a {class}`~libvt.terminal.Terminal` +instance (including capturing state via +{meth}`~libvt.terminal.Terminal.snapshot` or +{attr}`~libvt.terminal.Terminal.committed`) belongs to a single owning thread +or {mod}`asyncio` event loop unless externally synchronized. Returned +{class}`~libvt.terminal.Snapshot` values are immutable and safe to pass across +threads without locking. diff --git a/pyproject.toml b/pyproject.toml index 93db3d7..5da01ca 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -12,6 +12,7 @@ classifiers = [ "License :: OSI Approved :: MIT License", "Operating System :: POSIX", "Operating System :: MacOS :: MacOS X", + "Operating System :: Microsoft :: Windows", "Framework :: Pytest", "Intended Audience :: Developers", "Programming Language :: Python", diff --git a/src/libvt/__init__.py b/src/libvt/__init__.py index c4e28e2..c78c46a 100644 --- a/src/libvt/__init__.py +++ b/src/libvt/__init__.py @@ -137,9 +137,11 @@ TMUX_METADATA_FORMAT, CaptureCompleteness, CaptureInput, + TmuxCaptureCommand, TmuxCaptureResult, TmuxLineFlags, TmuxPaneMetadata, + build_tmux_capture_command, decode_tmux_capture, parse_flagged_line, unescape_tmux_control_output, @@ -241,6 +243,7 @@ "Terminal", "TerminalTimeoutError", "TitleChanged", + "TmuxCaptureCommand", "TmuxCaptureResult", "TmuxLineFlags", "TmuxPaneMetadata", @@ -263,6 +266,7 @@ "__title__", "__tracker__", "__version__", + "build_tmux_capture_command", "decode_tmux_capture", "display_width", "encode_input", diff --git a/src/libvt/_grid.py b/src/libvt/_grid.py index 263f546..d748276 100644 --- a/src/libvt/_grid.py +++ b/src/libvt/_grid.py @@ -39,21 +39,19 @@ _HISTORY_BLOCK_SIZE = 1 << _HISTORY_BLOCK_SHIFT _HISTORY_BLOCK_MASK = _HISTORY_BLOCK_SIZE - 1 -_GLOBAL_ROW_GEN: int = 0 +class _RowGenCounter: + """Per-screen-set monotonic row-mutation counter.""" -def bump_row_gen(row: _Row) -> int: - """Stamp *row* with the next strictly monotonic mutation generation.""" - global _GLOBAL_ROW_GEN - _GLOBAL_ROW_GEN += 1 - row.content_gen = _GLOBAL_ROW_GEN - row._frozen = None - return _GLOBAL_ROW_GEN + __slots__ = ("value",) + def __init__(self, initial: int = 0) -> None: + self.value: int = initial -def current_row_gen() -> int: - """Return the latest global row mutation generation without advancing it.""" - return _GLOBAL_ROW_GEN + def next(self) -> int: + """Advance and return the next strictly monotonic generation.""" + self.value += 1 + return self.value _COLOR_MASK = (1 << 25) - 1 @@ -243,7 +241,7 @@ def rstrip_text(self) -> str: def char_at(self, col: int) -> str: """Return cell string at *col*.""" - if col < 0 or col >= self.cols: + if col < 0: return " " if self.cells is not None: return self.cells[col] if col < len(self.cells) else " " @@ -273,16 +271,23 @@ def ext_at(self, col: int) -> _CellExt | None: return exts[idx][1] return None - def thaw(self, target_cols: int | None = None) -> _Row: + def thaw( + self, + target_cols: int | None = None, + *, + gen_counter: _RowGenCounter | None = None, + ) -> _Row: """Materialize a mutable :class:`_Row` from this sealed line.""" width = self.cols if target_cols is None else target_cols - row = _Row(width) - row.wrapped = self.wrapped + row = _Row(width, gen_counter=gen_counter) + row._wrapped = self.wrapped if width == self.cols else False limit = min(self.used, width) if limit == 0 and not self.runs: + row.stamp() return row for c in range(limit): - row.chars[c] = self.char_at(c) + row._chars[c] = self.char_at(c) + truncated_wide = False if self.runs: attrs = row._ensure_attrs() start = 0 @@ -291,50 +296,94 @@ def thaw(self, target_cols: int | None = None) -> _Row: for c in range(start, stop): attrs[c] = word if raw_width_bits(word) != 0: - row.has_wide = True + row._has_wide = True start = stop if start >= width: break if width > 0 and raw_width_bits(attrs[width - 1]) == int(WidthRole.WIDE): - row.chars[width - 1] = " " + row._chars[width - 1] = " " attrs[width - 1] &= _WIDTH_CLEAR_MASK + truncated_wide = True if self.exts: - row.ext = {c: ce for c, ce in self.exts if c < width} - row.used = limit - row.text_used = min( - len(self.cells) if self.cells is not None else len(self.text), width - ) + row._ext = {c: ce for c, ce in self.exts if c < width} + t_raw = len(self.cells) if self.cells is not None else len(self.text) + row._used = limit + row._text_used = min(t_raw, width - 1 if truncated_wide else width) + if ( + truncated_wide + and row._used == width + and row.attr_at(width - 1) == 0 + and row.ext_at(width - 1) is None + ): + row._used = max(row._text_used, width - 1) + if width != self.cols and 0 < self.cols <= width: + row.clear_spacer_head(self.cols - 1) + row.stamp() return row class _Row: - """Mutable viewport row with lazy 64-bit ``array('Q')`` promotion.""" + """Mutable viewport row guarded by write barriers on every cell/wrap edit.""" __slots__ = ( + "_attrs", + "_chars", + "_content_gen", + "_ext", "_frozen", + "_gen_counter", + "_has_wide", + "_text_used", + "_uniform_attr", + "_used", "_wrapped", - "attrs", - "chars", - "content_gen", - "ext", - "has_wide", - "text_used", - "uniform_attr", - "used", ) - def __init__(self, cols: int) -> None: - self.chars: list[str] = [" "] * cols - self.attrs: array.array[int] | None = None - self.uniform_attr: int = 0 - self.has_wide: bool = False - self.ext: dict[int, _CellExt] | None = None - self.used: int = 0 - self.text_used: int = 0 + def __init__( + self, + cols: int, + *, + gen_counter: _RowGenCounter | None = None, + ) -> None: + self._chars: list[str] = [" "] * cols + self._attrs: array.array[int] | None = None + self._uniform_attr: int = 0 + self._has_wide: bool = False + self._ext: dict[int, _CellExt] | None = None + self._used: int = 0 + self._text_used: int = 0 self._wrapped: bool = False - self.content_gen: int = 0 + self._gen_counter: _RowGenCounter = ( + _RowGenCounter() if gen_counter is None else gen_counter + ) + self._content_gen: int = 0 self._frozen: FrozenRow | None = None + @property + def cols(self) -> int: + """Return cell capacity of this row.""" + return len(self._chars) + + @property + def used(self) -> int: + """Return non-default cell high-water mark.""" + return self._used + + @property + def text_used(self) -> int: + """Return written-text column high-water mark.""" + return self._text_used + + @property + def has_wide(self) -> bool: + """Return ``True`` if this row may hold wide or spacer cells.""" + return self._has_wide + + @property + def content_gen(self) -> int: + """Return monotonic mutation stamp on this row's counter.""" + return self._content_gen + @property def wrapped(self) -> bool: """Return ``True`` when this row soft-wrapped onto the next line.""" @@ -344,28 +393,48 @@ def wrapped(self) -> bool: def wrapped(self, value: bool) -> None: if self._wrapped != value: self._wrapped = value - self._frozen = None + self.stamp() + + def stamp(self) -> int: + """Advance ``content_gen`` on the owning counter and clear ``_frozen``.""" + self._content_gen = self._gen_counter.next() + self._frozen = None + return self._content_gen + + def bind_counter(self, counter: _RowGenCounter, *, stamp: bool = True) -> None: + """Attach *counter* to this row and optionally stamp a fresh generation.""" + self._gen_counter = counter + if stamp: + self.stamp() def _ensure_attrs(self) -> array.array[int]: - if self.attrs is None: - self.attrs = array.array("Q", [self.uniform_attr]) * len(self.chars) - return self.attrs + if self._attrs is None: + self._attrs = array.array("Q", [self._uniform_attr]) * len(self._chars) + return self._attrs + + def char_at(self, col: int) -> str: + """Return grapheme string at *col*.""" + return self._chars[col] + + def slice_text(self, start: int, stop: int) -> str: + """Concatenate cell strings across ``[start, stop)``.""" + return "".join(self._chars[start:stop]) def attr_at(self, col: int) -> int: """Return 64-bit attribute word at *col*.""" - if self.attrs is None: - return self.uniform_attr - return self.attrs[col] + if self._attrs is None: + return self._uniform_attr + return self._attrs[col] def ext_at(self, col: int) -> _CellExt | None: """Return sparse :class:`_CellExt` at *col*, if any.""" - return self.ext.get(col) if self.ext is not None else None + return self._ext.get(col) if self._ext is not None else None def is_protected(self, col: int) -> bool: """Return ``True`` when cell *col* carries ``DECSCA`` protection.""" - if self.ext is None: + if self._ext is None: return False - ce = self.ext.get(col) + ce = self._ext.get(col) return bool(ce is not None and ce.protected) def reset_blank( @@ -375,23 +444,23 @@ def reset_blank( bce_ext: _CellExt | None = None, ) -> None: """Reset this row in place for zero-allocation scroll recycling.""" - if len(self.chars) != cols: - self.chars = [" "] * cols + if len(self._chars) != cols: + self._chars = [" "] * cols else: - self.chars[:] = [" "] * cols - self.attrs = None - self.uniform_attr = bce_word | (_HAS_EXT_BIT if bce_ext is not None else 0) - self.has_wide = False + self._chars[:] = [" "] * cols + self._attrs = None + self._uniform_attr = bce_word | (_HAS_EXT_BIT if bce_ext is not None else 0) + self._has_wide = False if bce_ext is not None: - self.ext = dict.fromkeys(range(cols), bce_ext) - self.used = cols + self._ext = dict.fromkeys(range(cols), bce_ext) + self._used = cols else: - if self.ext is not None: - self.ext.clear() - self.used = cols if bce_word != 0 else 0 - self.text_used = 0 + if self._ext is not None: + self._ext.clear() + self._used = cols if bce_word != 0 else 0 + self._text_used = 0 self._wrapped = False - bump_row_gen(self) + self.stamp() def _set_raw( self, @@ -404,57 +473,159 @@ def _set_raw( word = pen_word | (int(role) << _WIDTH_SHIFT) if cell_ext is not None: word |= _HAS_EXT_BIT - if self.ext is None: - self.ext = {col: cell_ext} + if self._ext is None: + self._ext = {col: cell_ext} else: - self.ext[col] = cell_ext - elif self.ext is not None: - self.ext.pop(col, None) + self._ext[col] = cell_ext + elif self._ext is not None: + self._ext.pop(col, None) if role != WidthRole.NARROW: - self.has_wide = True - self.chars[col] = ch - if self.attrs is None: - if word == self.uniform_attr: + self._has_wide = True + self._chars[col] = ch + if self._attrs is None: + if word == self._uniform_attr: return self._ensure_attrs()[col] = word else: - self.attrs[col] = word + self._attrs[col] = word def _heal_wide_boundary(self, col: int) -> None: """Clear both halves when an edit or margin boundary splits a wide glyph.""" - if not self.has_wide or self.attrs is None: + if not self._has_wide or self._attrs is None: return - cols = len(self.chars) + cols = len(self._chars) if col < 0 or col >= cols: return - role = raw_width_bits(self.attrs[col]) + role = raw_width_bits(self._attrs[col]) healed_pair_end = -1 if role == int(WidthRole.WIDE): - self.chars[col] = " " - self.attrs[col] &= _WIDTH_CLEAR_MASK + self._chars[col] = " " + self._attrs[col] &= _WIDTH_CLEAR_MASK healed_pair_end = col + 1 if col + 1 < cols: - self.chars[col + 1] = " " - self.attrs[col + 1] &= _WIDTH_CLEAR_MASK + self._chars[col + 1] = " " + self._attrs[col + 1] &= _WIDTH_CLEAR_MASK healed_pair_end = col + 2 elif role == int(WidthRole.SPACER_TAIL): - self.chars[col] = " " - self.attrs[col] &= _WIDTH_CLEAR_MASK + self._chars[col] = " " + self._attrs[col] &= _WIDTH_CLEAR_MASK healed_pair_end = col + 1 if col - 1 >= 0: - self.chars[col - 1] = " " - self.attrs[col - 1] &= _WIDTH_CLEAR_MASK + self._chars[col - 1] = " " + self._attrs[col - 1] &= _WIDTH_CLEAR_MASK if healed_pair_end != -1: - if self.text_used == healed_pair_end: - pair_lo = max(0, healed_pair_end - 2) - self.text_used = pair_lo - if ( - self.used == healed_pair_end - and self.attr_at(healed_pair_end - 1) == 0 - and self.ext_at(healed_pair_end - 1) is None + if self._text_used == healed_pair_end: + while self._text_used > 0 and self._chars[self._text_used - 1] == " ": + self._text_used -= 1 + while ( + self._used > self._text_used + and self._chars[self._used - 1] == " " + and self.attr_at(self._used - 1) == 0 + and self.ext_at(self._used - 1) is None + ): + self._used -= 1 + self._used = max(self._used, self._text_used) + self.stamp() + + def clear_spacer_head(self, col: int) -> bool: + """Clear ``SPACER_HEAD`` at *col* and tighten trailing default blanks.""" + if not self._has_wide or self._attrs is None: + return False + if not (0 <= col < len(self._chars)): + return False + if raw_width_bits(self._attrs[col]) != int(WidthRole.SPACER_HEAD): + return False + self._chars[col] = " " + self._attrs[col] &= _WIDTH_CLEAR_MASK + if self._text_used == col + 1: + self._text_used = col + while ( + self._text_used > 0 + and self._chars[self._text_used - 1] == " " + and self.attr_at(self._text_used - 1) == 0 + and self.ext_at(self._text_used - 1) is None + ): + self._text_used -= 1 + while ( + self._used > 0 + and self._chars[self._used - 1] == " " + and self.attr_at(self._used - 1) == 0 + and self.ext_at(self._used - 1) is None + ): + self._used -= 1 + self.stamp() + return True + + def trim_trailing_blanks(self) -> None: + """Trim unwrapped trailing space padding from ``text_used`` and ``used``.""" + orig_t = self._text_used + orig_u = self._used + while self._text_used > 0 and self._chars[self._text_used - 1] == " ": + self._text_used -= 1 + while ( + self._used > self._text_used + and self._chars[self._used - 1] == " " + and self.attr_at(self._used - 1) == 0 + and self.ext_at(self._used - 1) is None + ): + self._used -= 1 + if self._text_used != orig_t or self._used != orig_u: + self.stamp() + + def copy_region_from(self, src_row: _Row, left: int, right: int) -> None: + """Copy cells ``[left..right]`` from *src_row* during partial scroll.""" + if right == len(src_row._chars) - 1 and src_row.clear_spacer_head(right): + src_row.wrapped = False + if self._has_wide and self._attrs is not None: + if raw_width_bits(self._attrs[left]) == int(WidthRole.SPACER_TAIL): + self._heal_wide_boundary(left) + if raw_width_bits(self._attrs[right]) == int(WidthRole.WIDE): + self._heal_wide_boundary(right) + if src_row._has_wide and src_row._attrs is not None: + if raw_width_bits(src_row._attrs[left]) == int(WidthRole.SPACER_TAIL): + src_row._heal_wide_boundary(left) + if raw_width_bits(src_row._attrs[right]) == int(WidthRole.WIDE): + src_row._heal_wide_boundary(right) + for c in range(left, right + 1): + word = src_row.attr_at(c) + role = unpack_width_role(word) + ch = src_row._chars[c] + if role == WidthRole.SPACER_HEAD and not self._wrapped: + role = WidthRole.NARROW + ch = " " + base = word & _WIDTH_CLEAR_MASK + self._set_raw(c, ch, base, role, src_row.ext_at(c)) + limit = right + 1 + if self._text_used <= limit: + cand_t = ( + min(src_row._text_used, limit) + if src_row._text_used > left + else min(self._text_used, left) + ) + if src_row._text_used > limit: + floor_t = min(self._text_used, left) + while cand_t > floor_t and self._chars[cand_t - 1] == " ": + cand_t -= 1 + self._text_used = cand_t + if self._used <= limit: + cand_u = ( + min(src_row._used, limit) + if src_row._used > left + else min(self._used, left) + ) + floor_u = max(min(self._used, left), self._text_used) + if src_row._used > limit: + while ( + cand_u > floor_u + and self._chars[cand_u - 1] == " " + and self.attr_at(cand_u - 1) == 0 + and self.ext_at(cand_u - 1) is None ): - self.used = pair_lo - bump_row_gen(self) + cand_u -= 1 + self._used = max(cand_u, self._text_used) + else: + self._used = max(self._used, self._text_used) + self.stamp() def write_narrow( self, @@ -466,9 +637,9 @@ def write_narrow( """Write a 1-column glyph at *col*, healing any split wide cell.""" self._heal_wide_boundary(col) self._set_raw(col, ch, pen_word, WidthRole.NARROW, cell_ext) - self.used = max(self.used, col + 1) - self.text_used = max(self.text_used, col + 1) - bump_row_gen(self) + self._used = max(self._used, col + 1) + self._text_used = max(self._text_used, col + 1) + self.stamp() def write_spacer_head( self, @@ -479,9 +650,9 @@ def write_spacer_head( """Write ``WidthRole.SPACER_HEAD`` padding at right margin before wide wrap.""" self._heal_wide_boundary(col) self._set_raw(col, "", bce_word, WidthRole.SPACER_HEAD, bce_ext) - self.used = max(self.used, col + 1) - self.text_used = max(self.text_used, col + 1) - bump_row_gen(self) + self._used = max(self._used, col + 1) + self._text_used = max(self._text_used, col + 1) + self.stamp() def write_ascii_slice( self, @@ -493,40 +664,33 @@ def write_ascii_slice( """Fast-path bulk write of 1-column printable ASCII characters.""" n = len(text) end = col + n - if self.has_wide and self.attrs is not None: - self._heal_wide_boundary(col) - if end - 1 > col: + if self._has_wide and self._attrs is not None: + if raw_width_bits(self._attrs[col]) == int(WidthRole.SPACER_TAIL): + self._heal_wide_boundary(col) + if raw_width_bits(self._attrs[end - 1]) == int(WidthRole.WIDE): self._heal_wide_boundary(end - 1) - for idx in range(col, end): - if ( - raw_width_bits(self.attrs[idx]) == int(WidthRole.WIDE) - and idx + 1 >= end - and idx + 1 < len(self.chars) - ): - self.chars[idx + 1] = " " - self.attrs[idx + 1] &= _WIDTH_CLEAR_MASK - self.chars[col:end] = list(text) + self._chars[col:end] = list(text) word = pen_word | (_HAS_EXT_BIT if cell_ext is not None else 0) - if self.attrs is None: - if word != self.uniform_attr: + if self._attrs is None: + if word != self._uniform_attr: attrs = self._ensure_attrs() attrs[col:end] = array.array("Q", [word]) * n else: - self.attrs[col:end] = array.array("Q", [word]) * n + self._attrs[col:end] = array.array("Q", [word]) * n if cell_ext is not None: - if self.ext is None: - self.ext = {} + if self._ext is None: + self._ext = {} for idx in range(col, end): - self.ext[idx] = cell_ext - elif self.ext: + self._ext[idx] = cell_ext + elif self._ext: for idx in range(col, end): - self.ext.pop(idx, None) + self._ext.pop(idx, None) - self.used = max(self.used, end) - self.text_used = max(self.text_used, end) - bump_row_gen(self) + self._used = max(self._used, end) + self._text_used = max(self._text_used, end) + self.stamp() def write_wide( self, @@ -540,9 +704,9 @@ def write_wide( self._heal_wide_boundary(col + 1) self._set_raw(col, ch, pen_word, WidthRole.WIDE, cell_ext) self._set_raw(col + 1, "", pen_word, WidthRole.SPACER_TAIL, cell_ext) - self.used = max(self.used, col + 2) - self.text_used = max(self.text_used, col + 2) - bump_row_gen(self) + self._used = max(self._used, col + 2) + self._text_used = max(self._text_used, col + 2) + self.stamp() def append_grapheme( self, @@ -553,19 +717,19 @@ def append_grapheme( bce_word: int = 0, ) -> None: """Append zero-width or cluster-extending *ch* onto cell *col*.""" - cols = len(self.chars) + cols = len(self._chars) if col < 0 or col >= cols: return target = col if ( - self.has_wide - and self.attrs is not None - and raw_width_bits(self.attrs[col]) == int(WidthRole.SPACER_TAIL) + self._has_wide + and self._attrs is not None + and raw_width_bits(self._attrs[col]) == int(WidthRole.SPACER_TAIL) and col > 0 ): target = col - 1 - self.chars[target] = self.chars[target] + ch - cur_role = raw_width_bits(self.attrs[target]) if self.attrs is not None else 0 + self._chars[target] = self._chars[target] + ch + cur_role = raw_width_bits(self._attrs[target]) if self._attrs is not None else 0 if ( width_override == 2 and cur_role == int(WidthRole.NARROW) @@ -575,11 +739,11 @@ def append_grapheme( base_ext = self.ext_at(target) self._heal_wide_boundary(target + 1) self._set_raw( - target, self.chars[target], base_pen, WidthRole.WIDE, base_ext + target, self._chars[target], base_pen, WidthRole.WIDE, base_ext ) self._set_raw(target + 1, "", base_pen, WidthRole.SPACER_TAIL, base_ext) - self.used = max(self.used, target + 2) - self.text_used = max(self.text_used, target + 2) + self._used = max(self._used, target + 2) + self._text_used = max(self._text_used, target + 2) elif ( width_override == 1 and cur_role == int(WidthRole.WIDE) @@ -588,11 +752,11 @@ def append_grapheme( attrs = self._ensure_attrs() attrs[target] &= _WIDTH_CLEAR_MASK self._set_raw(target + 1, " ", bce_word, WidthRole.NARROW, None) - if self.text_used == target + 2: - self.text_used = target + 1 - if self.used == target + 2 and bce_word == 0: - self.used = target + 1 - bump_row_gen(self) + if self._text_used == target + 2: + self._text_used = target + 1 + if self._used == target + 2 and bce_word == 0: + self._used = target + 1 + self.stamp() def clear_range( self, @@ -604,70 +768,75 @@ def clear_range( selective: bool = False, ) -> None: """Erase cells in ``[start, end)`` using background color erase (*bce*).""" - cols = len(self.chars) + cols = len(self._chars) lo = max(0, start) hi = min(cols, end) if lo >= hi: return - if selective and self.ext: + if selective and self._ext: for c in range(lo, hi): if self.is_protected(c): continue self._heal_wide_boundary(c) self._set_raw(c, " ", bce_word, WidthRole.NARROW, bce_ext) if bce_word != 0 or bce_ext is not None: - self.used = max(self.used, hi) - elif hi >= self.used: + self._used = max(self._used, hi) + elif hi >= self._used: while ( - self.used > lo - and self.chars[self.used - 1] == " " - and self.attr_at(self.used - 1) == 0 - and self.ext_at(self.used - 1) is None + self._used > lo + and self._chars[self._used - 1] == " " + and self.attr_at(self._used - 1) == 0 + and self.ext_at(self._used - 1) is None + ): + self._used -= 1 + if hi >= self._text_used: + while self._text_used > lo and not self.is_protected( + self._text_used - 1 ): - self.used -= 1 - if hi >= self.text_used: - while self.text_used > lo and not self.is_protected(self.text_used - 1): - self.text_used -= 1 - bump_row_gen(self) + self._text_used -= 1 + self.stamp() return if lo == 0 and hi == cols: self.reset_blank(cols, bce_word, bce_ext) return - if self.has_wide: - self._heal_wide_boundary(lo) - self._heal_wide_boundary(hi - 1) + if self._has_wide and self._attrs is not None: + if raw_width_bits(self._attrs[lo]) == int(WidthRole.SPACER_TAIL): + self._heal_wide_boundary(lo) + if raw_width_bits(self._attrs[hi - 1]) == int(WidthRole.WIDE): + self._heal_wide_boundary(hi - 1) n = hi - lo - self.chars[lo:hi] = [" "] * n + self._chars[lo:hi] = [" "] * n word = bce_word | (_HAS_EXT_BIT if bce_ext is not None else 0) - if self.attrs is None: - if word != self.uniform_attr: + if self._attrs is None: + if word != self._uniform_attr: attrs = self._ensure_attrs() attrs[lo:hi] = array.array("Q", [word]) * n else: - self.attrs[lo:hi] = array.array("Q", [word]) * n + self._attrs[lo:hi] = array.array("Q", [word]) * n if bce_ext is not None: - if self.ext is None: - self.ext = {} + if self._ext is None: + self._ext = {} for c in range(lo, hi): - self.ext[c] = bce_ext - self.used = max(self.used, hi) + self._ext[c] = bce_ext + self._used = max(self._used, hi) else: - if self.ext: + if self._ext: for c in range(lo, hi): - self.ext.pop(c, None) + self._ext.pop(c, None) if bce_word != 0: - self.used = max(self.used, hi) - elif hi >= self.used: + self._used = max(self._used, hi) + elif hi >= self._used: # Clamp used to lo without erasing explicit spaces left of lo. - self.used = min(self.used, lo) - if hi >= self.text_used: - self.text_used = min(self.text_used, lo) - bump_row_gen(self) + self._used = min(self._used, lo) + if hi >= self._text_used: + self._text_used = min(self._text_used, lo) + self._used = max(self._used, self._text_used) + self.stamp() def insert_blanks( self, @@ -684,66 +853,65 @@ def insert_blanks( return shift = min(count, right - col + 1) - # Splitting a SPACER_TAIL at col orphans its WIDE head at col - 1. - if ( - self.has_wide - and self.attrs is not None - and raw_width_bits(self.attrs[col]) == int(WidthRole.SPACER_TAIL) - ): - if col > 0: - self.chars[col - 1] = " " - self.attrs[col - 1] &= _WIDTH_CLEAR_MASK - self.chars[col] = " " - self.attrs[col] &= _WIDTH_CLEAR_MASK - - # Discarding a WIDE head at right orphans its SPACER_TAIL at right + 1. - if ( - self.has_wide - and self.attrs is not None - and right + 1 < len(self.chars) - and raw_width_bits(self.attrs[right + 1]) == int(WidthRole.SPACER_TAIL) - ): - self.chars[right + 1] = " " - self.attrs[right + 1] &= _WIDTH_CLEAR_MASK + if self._has_wide and self._attrs is not None: + if raw_width_bits(self._attrs[col]) == int(WidthRole.SPACER_TAIL): + self._heal_wide_boundary(col) + if raw_width_bits(self._attrs[right]) == int(WidthRole.WIDE): + self._heal_wide_boundary(right) attrs = ( self._ensure_attrs() if ( - self.attrs is not None - or bce_word != self.uniform_attr + self._attrs is not None + or bce_word != self._uniform_attr or bce_ext is not None ) else None ) for dst in range(right, col + shift - 1, -1): src = dst - shift - self.chars[dst] = self.chars[src] + self._chars[dst] = self._chars[src] if attrs is not None: attrs[dst] = attrs[src] - if self.ext is not None: - if src in self.ext: - self.ext[dst] = self.ext[src] + if self._ext is not None: + if src in self._ext: + self._ext[dst] = self._ext[src] else: - self.ext.pop(dst, None) + self._ext.pop(dst, None) # Clear right when shifting pushes a WIDE head onto right without its tail. + cleared_right_head = False if ( - self.has_wide + self._has_wide and attrs is not None and raw_width_bits(attrs[right]) == int(WidthRole.WIDE) ): - self.chars[right] = " " + self._chars[right] = " " attrs[right] &= _WIDTH_CLEAR_MASK + cleared_right_head = True for c in range(col, col + shift): self._set_raw(c, " ", bce_word, WidthRole.NARROW, bce_ext) - if self.used <= right + 1 and ( - bce_word != 0 or bce_ext is not None or self.used > col + t_cap = right if cleared_right_head else right + 1 + if self._text_used <= right + 1 and self._text_used > col: + self._text_used = min(t_cap, self._text_used + shift) + if self._used <= right + 1 and ( + bce_word != 0 or bce_ext is not None or self._used > col ): - self.used = min(right + 1, max(self.used + shift, col + shift)) - if self.text_used <= right + 1 and self.text_used > col: - self.text_used = min(right + 1, self.text_used + shift) - bump_row_gen(self) + u_cap = ( + right + if ( + cleared_right_head + and self.attr_at(right) == 0 + and self.ext_at(right) is None + ) + else right + 1 + ) + self._used = max( + self._text_used, + min(u_cap, max(self._used + shift, col + shift)), + ) + self.stamp() def delete_cells( self, @@ -760,130 +928,146 @@ def delete_cells( return shift = min(count, right - col + 1) - if self.has_wide and self.attrs is not None: - # 1. Deleting SPACER_TAIL at col orphans WIDE head at col - 1. - if ( - raw_width_bits(self.attrs[col]) == int(WidthRole.SPACER_TAIL) - and col > 0 - ): - self.chars[col - 1] = " " - self.attrs[col - 1] &= _WIDTH_CLEAR_MASK - # First surviving cell at col + shift lost its WIDE head if SPACER_TAIL. - if col + shift <= right and raw_width_bits(self.attrs[col + shift]) == int( + if self._has_wide and self._attrs is not None: + if raw_width_bits(self._attrs[col]) == int(WidthRole.SPACER_TAIL): + self._heal_wide_boundary(col) + if col + shift <= right and raw_width_bits(self._attrs[col + shift]) == int( WidthRole.SPACER_TAIL ): - self.chars[col + shift] = " " - self.attrs[col + shift] &= _WIDTH_CLEAR_MASK - # Shifting WIDE head at right leftwards splits (right, right + 1). - if right + 1 < len(self.chars) and raw_width_bits( - self.attrs[right + 1] - ) == int(WidthRole.SPACER_TAIL): - self.chars[right] = " " - self.attrs[right] &= _WIDTH_CLEAR_MASK - self.chars[right + 1] = " " - self.attrs[right + 1] &= _WIDTH_CLEAR_MASK + self._heal_wide_boundary(col + shift) + if raw_width_bits(self._attrs[right]) == int(WidthRole.WIDE): + self._heal_wide_boundary(right) attrs = ( self._ensure_attrs() if ( - self.attrs is not None - or bce_word != self.uniform_attr + self._attrs is not None + or bce_word != self._uniform_attr or bce_ext is not None ) else None ) for dst in range(col, right - shift + 1): src = dst + shift - self.chars[dst] = self.chars[src] + self._chars[dst] = self._chars[src] if attrs is not None: attrs[dst] = attrs[src] - if self.ext is not None: - if src in self.ext: - self.ext[dst] = self.ext[src] + if self._ext is not None: + if src in self._ext: + self._ext[dst] = self._ext[src] else: - self.ext.pop(dst, None) + self._ext.pop(dst, None) for c in range(right - shift + 1, right + 1): self._set_raw(c, " ", bce_word, WidthRole.NARROW, bce_ext) - if self.used <= right + 1: + if self._used <= right + 1: if bce_word != 0 or bce_ext is not None: - self.used = max(self.used, right + 1) - elif self.used > col: - self.used = max(col, self.used - shift) - if self.text_used <= right + 1 and self.text_used > col: - self.text_used = max(col, self.text_used - shift) - bump_row_gen(self) + self._used = max(self._used, right + 1) + elif self._used > col: + self._used = max(col, self._used - shift) + if self._text_used <= right + 1 and self._text_used > col: + self._text_used = max(col, self._text_used - shift) + self._used = max(self._used, self._text_used) + self.stamp() def resize(self, cols: int) -> None: """Resize row in place to *cols* columns (non-reflow path).""" - cur = len(self.chars) + cur = len(self._chars) if cols == cur: return + self._wrapped = False if cols < cur: + healed_edge = False if ( cols > 0 - and self.has_wide - and self.attrs is not None - and raw_width_bits(self.attrs[cols - 1]) == int(WidthRole.WIDE) + and self._has_wide + and self._attrs is not None + and raw_width_bits(self._attrs[cols - 1]) + in (int(WidthRole.WIDE), int(WidthRole.SPACER_HEAD)) ): - self.chars[cols - 1] = " " - self.attrs[cols - 1] &= _WIDTH_CLEAR_MASK - del self.chars[cols:] - if self.attrs is not None: - del self.attrs[cols:] - self.used = min(self.used, cols) - self.text_used = min(self.text_used, cols) - if self.ext: - for k in [k for k in self.ext if k >= cols]: - del self.ext[k] + self._chars[cols - 1] = " " + self._attrs[cols - 1] &= _WIDTH_CLEAR_MASK + healed_edge = True + del self._chars[cols:] + if self._attrs is not None: + del self._attrs[cols:] + if self._ext: + for k in [k for k in self._ext if k >= cols]: + del self._ext[k] + t_lim = cols - 1 if healed_edge else cols + self._text_used = min(self._text_used, t_lim) + u_lim = ( + cols - 1 + if ( + healed_edge + and self.attr_at(cols - 1) == 0 + and self.ext_at(cols - 1) is None + ) + else cols + ) + self._used = max(self._text_used, min(self._used, u_lim)) else: + if cur > 0: + self.clear_spacer_head(cur - 1) pad = cols - cur - self.chars.extend([" "] * pad) - if self.attrs is not None: - self.attrs.extend([0] * pad) - elif self.uniform_attr != 0: - attrs = array.array("Q", [self.uniform_attr]) * cur + self._chars.extend([" "] * pad) + if self._attrs is not None: + self._attrs.extend([0] * pad) + elif self._uniform_attr != 0: + attrs = array.array("Q", [self._uniform_attr]) * cur attrs.extend([0] * pad) - self.attrs = attrs - bump_row_gen(self) + self._attrs = attrs + self.stamp() def clone(self) -> _Row: - """Return an independent copy of this row.""" + """Return an independent snapshot copy isolated from live counters.""" dup = _Row.__new__(_Row) - dup.chars = self.chars.copy() - dup.attrs = array.array("Q", self.attrs) if self.attrs is not None else None - dup.uniform_attr = self.uniform_attr - dup.has_wide = self.has_wide - dup.ext = self.ext.copy() if self.ext else None - dup.used = self.used - dup.text_used = self.text_used + dup._chars = self._chars.copy() + dup._attrs = array.array("Q", self._attrs) if self._attrs is not None else None + dup._uniform_attr = self._uniform_attr + dup._has_wide = self._has_wide + dup._ext = self._ext.copy() if self._ext else None + dup._used = self._used + dup._text_used = self._text_used dup._wrapped = self._wrapped - dup.content_gen = self.content_gen + dup._gen_counter = _RowGenCounter(self._content_gen) + dup._content_gen = self._content_gen dup._frozen = self._frozen return dup + def debug_fingerprint(self) -> tuple[object, ...]: + """Return complete structural state tuple for write-barrier verification.""" + return ( + self._wrapped, + tuple(self._chars), + tuple(self._attrs) if self._attrs is not None else self._uniform_attr, + tuple(sorted(self._ext.items())) if self._ext else (), + self._used, + self._text_used, + ) + def freeze(self) -> FrozenRow: """Seal this row into a compact run-length-encoded :class:`FrozenRow`.""" if self._frozen is not None: return self._frozen - cols = len(self.chars) - t_used = self.text_used - text = "".join(self.chars[:t_used]) + cols = len(self._chars) + t_used = self._text_used + text = "".join(self._chars[:t_used]) cells: tuple[str, ...] | None = None - if len(text) != t_used or "" in self.chars[:t_used]: - cells = tuple(self.chars[:t_used]) + if len(text) != t_used or "" in self._chars[:t_used]: + cells = tuple(self._chars[:t_used]) - u = min(cols, max(self.used, t_used)) + u = min(cols, max(self._used, t_used)) runs: tuple[tuple[int, int], ...] if u == 0: runs = () - elif self.attrs is None: - runs = () if self.uniform_attr == 0 else ((u, self.uniform_attr),) + elif self._attrs is None: + runs = () if self._uniform_attr == 0 else ((u, self._uniform_attr),) else: run_list: list[tuple[int, int]] = [] - cur_word = self.attrs[0] + cur_word = self._attrs[0] for c in range(1, u): - w = self.attrs[c] + w = self._attrs[c] if w != cur_word: run_list.append((c, cur_word)) cur_word = w @@ -891,7 +1075,7 @@ def freeze(self) -> FrozenRow: run_list.append((u, cur_word)) runs = tuple(run_list) - exts = tuple(sorted(self.ext.items())) if self.ext else () + exts = tuple(sorted(self._ext.items())) if self._ext else () fr = FrozenRow( text=text, cols=cols, @@ -905,7 +1089,7 @@ def freeze(self) -> FrozenRow: def rstrip_text(self) -> str: """Return row text up to ``text_used`` written columns.""" - return "".join(self.chars[: self.text_used]) + return "".join(self._chars[: self._text_used]) @dataclass(frozen=True, slots=True) @@ -1055,6 +1239,33 @@ def append(self, row: FrozenRow) -> bool: self._len += 1 return False + def replace_all(self, rows: collections.abc.Sequence[RowLike]) -> int: + """Replace buffer with trailing ``maxlen`` frozen rows; return evicted.""" + self.clear() + n = len(rows) + if self._maxlen <= 0 or n == 0: + return n + evicted = max(0, n - self._maxlen) + kept_len = n - evicted + full_blocks = kept_len >> _HISTORY_BLOCK_SHIFT + blocks: list[tuple[FrozenRow, ...]] = [] + pos = evicted + for _ in range(full_blocks): + nxt = pos + _HISTORY_BLOCK_SIZE + chunk = rows[pos:nxt] + blocks.append( + tuple(r if isinstance(r, FrozenRow) else r.freeze() for r in chunk) + ) + pos = nxt + self._blocks = blocks + self._tail = [ + r if isinstance(r, FrozenRow) else r.freeze() for r in rows[pos:n] + ] + self._head_offset = 0 + self._len = kept_len + self._snapshot = None + return evicted + def freeze(self) -> _FrozenHistory: """Capture an ``O(1)`` CoW :class:`_FrozenHistory` snapshot.""" if self._snapshot is not None: diff --git a/src/libvt/aio.py b/src/libvt/aio.py index 997a2f7..f4388b6 100644 --- a/src/libvt/aio.py +++ b/src/libvt/aio.py @@ -1,12 +1,14 @@ -"""Transport-only ``asyncio`` stream and POSIX PTY adapters over :class:`Terminal`.""" +"""``asyncio`` stream and POSIX PTY adapters over :class:`~libvt.terminal.Terminal`.""" from __future__ import annotations import asyncio +import collections import collections.abc import contextlib import dataclasses import errno +import math import os import signal import socket @@ -26,6 +28,7 @@ ) from libvt.exc import TerminalTimeoutError from libvt.input import InputEvent, KeyEvent, PasteEvent +from libvt.parser import _parse_ascii_uint from libvt.terminal import FlightRecorder, Snapshot, Terminal type TtyMode = t.Literal["cooked", "cbreak", "raw"] @@ -75,7 +78,8 @@ def _raise_exec_error(err_payload: bytes, cmd: str, default_errno: int) -> t.NoR stage, code_s, err_msg = parts else: stage, code_s, err_msg = "exec", "", body.decode("utf-8", "replace") - err_no = int(code_s) if code_s.isdigit() else default_errno + parsed_err = _parse_ascii_uint(code_s, max_val=65_535) + err_no = default_errno if parsed_err is None else parsed_err target = cmd if stage == "exec" else f"open_pty({stage})" raise OSError(err_no, err_msg or os.strerror(err_no), target) @@ -152,12 +156,78 @@ async def wait_closed(self) -> None: """Wait until writer close completes.""" +_PEER_EOF_ERRNOS = (errno.EIO, errno.EPIPE, errno.ENXIO) +_COALESCE_SLAB = 16_384 + + +def _validate_nonneg_seconds(value: float, name: str) -> None: + if ( + isinstance(value, bool) + or not isinstance(value, (int, float)) + or not math.isfinite(value) + or value < 0 + ): + msg = f"{name} must be a finite non-negative number, got {value!r}" + raise ValueError(msg) + + +def _validate_pty_dims(rows: int, cols: int) -> None: + if ( + isinstance(rows, bool) + or isinstance(cols, bool) + or not isinstance(rows, int) + or not isinstance(cols, int) + or not (1 <= rows <= 65_535) + or not (1 <= cols <= 65_535) + ): + msg = f"rows and cols must be integers in 1..65535, got ({rows!r}, {cols!r})" + raise ValueError(msg) + + +def _pack_winsize(rows: int, cols: int, profile: Profile) -> bytes: + xpixel = min(65_535, max(0, cols * profile.cell_width_px)) + ypixel = min(65_535, max(0, rows * profile.cell_height_px)) + return struct.pack("HHHH", rows, cols, xpixel, ypixel) + + +def _resolve_write_limits( + write_high_water: int | None, + max_write_buffer: int, +) -> tuple[int, int]: + if ( + isinstance(max_write_buffer, bool) + or not isinstance(max_write_buffer, int) + or max_write_buffer < 1 + ): + msg = f"max_write_buffer must be an int >= 1, got {max_write_buffer!r}" + raise ValueError(msg) + if write_high_water is None: + eff_hw = min(65_536, max_write_buffer) + else: + if ( + isinstance(write_high_water, bool) + or not isinstance(write_high_water, int) + or write_high_water < 0 + ): + msg = f"write_high_water must be >= 0, got {write_high_water!r}" + raise ValueError(msg) + if max_write_buffer < write_high_water: + msg = ( + "max_write_buffer must be >= write_high_water, " + f"got {max_write_buffer!r} < {write_high_water!r}" + ) + raise ValueError(msg) + eff_hw = write_high_water + return eff_hw, max_write_buffer + + class AsyncTerminalStream: """Drive a sans-I/O :class:`~libvt.terminal.Terminal` from ``asyncio`` streams. Coalesces frame wakeups across DEC mode ``?2026`` synchronized-output - batches (bounded by *sync_timeout* using generation-safe expiry) and - automatically flushes :meth:`~libvt.terminal.Terminal.drain_replies` when a + batches (bounded by *sync_timeout* using generation-safe expiry), expires + any active ``?2026`` hold on ``EOF`` and :meth:`aclose`, and automatically + flushes :meth:`~libvt.terminal.Terminal.drain_replies` when a ``StreamWriter`` is attached. """ @@ -172,6 +242,16 @@ def __init__( chunk_size: int = 4_096, sync_timeout: float = 1.0, ) -> None: + if ( + isinstance(chunk_size, bool) + or not isinstance(chunk_size, int) + or chunk_size < 1 + ): + msg = f"chunk_size must be >= 1, got {chunk_size!r}" + raise ValueError(msg) + if terminal is None: + _validate_pty_dims(rows, cols) + _validate_nonneg_seconds(sync_timeout, "sync_timeout") self.reader = reader self.writer = writer self.terminal = ( @@ -183,8 +263,12 @@ def __init__( self.sync_timeout = sync_timeout self._frame_event = asyncio.Event() self._eof = False + self._closed = False self._sync_started_at: float | None = None self._sync_gen_tracked: int | None = None + self._sync_timer_handle: asyncio.TimerHandle | None = None + self._sync_timer_gen: int | None = None + self._last_committed_gen: int = self.terminal.committed_generation self._task: asyncio.Task[None] | None = None @property @@ -192,37 +276,80 @@ def eof(self) -> bool: """Return ``True`` once ``reader`` reaches end-of-stream.""" return self._eof + def _cancel_sync_timer(self) -> None: + if self._sync_timer_handle is not None: + self._sync_timer_handle.cancel() + self._sync_timer_handle = None + self._sync_timer_gen = None + + def _on_sync_timeout(self) -> None: + self._sync_timer_handle = None + self._sync_timer_gen = None + self._update_sync_timer(time.monotonic()) + + def _mark_eof(self) -> None: + self._eof = True + self._cancel_sync_timer() + self.terminal.expire_synchronized_output() + self._sync_started_at = None + self._sync_gen_tracked = None + self._last_committed_gen = self.terminal.committed_generation + self._frame_event.set() + def _update_sync_timer(self, now: float) -> None: if self.terminal.synchronized: cur_gen = self.terminal.sync_generation if self._sync_gen_tracked != cur_gen or self._sync_started_at is None: self._sync_gen_tracked = cur_gen self._sync_started_at = now - elif ( + if ( now - self._sync_started_at >= self.sync_timeout and self.terminal.expire_synchronized_output(cur_gen) ): + self._cancel_sync_timer() self._sync_started_at = None self._sync_gen_tracked = None - self._frame_event.set() + elif ( + self._task is not None + and not self._task.done() + and self._sync_timer_gen != cur_gen + ): + self._cancel_sync_timer() + delay = max(0.0, self._sync_started_at + self.sync_timeout - now) + with contextlib.suppress(RuntimeError): + loop = asyncio.get_running_loop() + self._sync_timer_gen = cur_gen + self._sync_timer_handle = loop.call_later( + delay, + self._on_sync_timeout, + ) else: + self._cancel_sync_timer() self._sync_started_at = None self._sync_gen_tracked = None + cur_committed = self.terminal.committed_generation + if cur_committed != self._last_committed_gen: + self._last_committed_gen = cur_committed self._frame_event.set() async def pump_once(self) -> bool: - """Read and feed one chunk; return ``False`` on EOF.""" + """Read and feed one chunk; return ``False`` on EOF or after close.""" + if self._closed: + return False chunk = await self.reader.read(self.chunk_size) if not chunk: - self._eof = True - self._frame_event.set() + self._mark_eof() return False self.terminal.feed(chunk) replies = self.terminal.drain_replies() - if replies and self.writer is not None: - self.writer.write(replies) - await self.writer.drain() - self._update_sync_timer(time.monotonic()) + if self.reader.at_eof(): + self._mark_eof() + else: + self._update_sync_timer(time.monotonic()) + if replies and self.writer is not None and not self._closed: + with contextlib.suppress(BrokenPipeError, ConnectionResetError): + self.writer.write(replies) + await self.writer.drain() return True async def _pump_loop(self) -> None: @@ -230,25 +357,38 @@ async def _pump_loop(self) -> None: while await self.pump_once(): pass finally: + self._cancel_sync_timer() self._frame_event.set() def start(self) -> asyncio.Task[None]: """Start background stream pumping on the running event loop.""" if self._task is None or self._task.done(): + self._closed = False self._task = asyncio.create_task(self._pump_loop()) return self._task async def aclose(self) -> None: - """Cancel background pump task and close the writer if present.""" - if self._task is not None: - self._task.cancel() - with contextlib.suppress(asyncio.CancelledError): - await self._task + """Cancel background pump task, expire ``?2026`` holds, and close writer.""" + self._closed = True + self._cancel_sync_timer() + try: + if self._task is not None: + self._task.cancel() + with contextlib.suppress(asyncio.CancelledError): + await self._task + self._task = None + if self.writer is not None: + self.writer.close() + with contextlib.suppress(OSError): + await self.writer.wait_closed() + finally: self._task = None - if self.writer is not None: - self.writer.close() - with contextlib.suppress(OSError): - await self.writer.wait_closed() + self._cancel_sync_timer() + self.terminal.expire_synchronized_output() + self._sync_started_at = None + self._sync_gen_tracked = None + self._last_committed_gen = self.terminal.committed_generation + self._frame_event.set() async def __aenter__(self) -> t.Self: """Start background pumping when entering an ``async with`` block.""" @@ -271,7 +411,7 @@ async def wait_for( timeout: float = 2.0, attach_note: bool = True, ) -> Snapshot: - """Wait until *predicate* matches the committed :class:`Snapshot`. + """Wait until *predicate* matches :class:`~libvt.terminal.Snapshot`. Parameters ---------- @@ -293,9 +433,10 @@ async def wait_for( Raises ------ TerminalTimeoutError - If the stream reaches EOF before matching (``eof=True``) or - *timeout* expires (``eof=False``). + If the stream reaches EOF/close before matching or *timeout* + expires. """ + _validate_nonneg_seconds(timeout, "timeout") check = ( (lambda snap: predicate in snap.text) if isinstance(predicate, str) @@ -313,22 +454,26 @@ async def wait_for( now = time.monotonic() if self.terminal.synchronized: self._update_sync_timer(now) - snap = self.terminal.snapshot() if self._eof else self.terminal.committed + ended = self._eof or self._closed + snap = self.terminal.snapshot() if ended else self.terminal.committed if check(snap): return snap - if self._eof: + if ended: + reason = ( + "stream reached EOF before predicate matched" + if self._eof + else "stream closed before predicate matched" + ) raise _make_timeout_error( self.terminal, snap, - "stream reached EOF before predicate matched", - eof=True, + reason, + eof=self._eof, attach_note=attach_note, ) remaining = deadline - now if remaining <= 0: live = self.terminal.snapshot() - if check(live): - return live raise _make_timeout_error( self.terminal, live, @@ -362,7 +507,32 @@ async def wait_for( class PtySession: - """Async POSIX pseudo-terminal subprocess session backed by :class:`Terminal`.""" + """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. + + Attributes + ---------- + process : asyncio.subprocess.Process + Managed child process attached to the slave PTY. + terminal : Terminal + Live :class:`~libvt.terminal.Terminal` fed from ``master_fd``. + sync_timeout : float + Watchdog timeout in seconds before expiring stalled ``?2026`` frames. + write_high_water : int + High-water mark in bytes above which :meth:`drain` suspends. + max_write_buffer : int + Hard cap in bytes above which :meth:`send` raises :exc:`BufferError`. + """ + + process: asyncio.subprocess.Process + terminal: Terminal + sync_timeout: float + write_high_water: int + max_write_buffer: int def __init__( self, @@ -371,16 +541,55 @@ def __init__( process: asyncio.subprocess.Process, terminal: Terminal, sync_timeout: float = 1.0, + write_high_water: int | None = None, + max_write_buffer: int = 16_777_216, ) -> None: + """Initialize a :class:`PtySession` around an open non-blocking *master_fd*. + + Parameters + ---------- + master_fd : int + Non-blocking master pseudo-terminal file descriptor. + process : asyncio.subprocess.Process + Spawned child process bound to the slave PTY. + terminal : Terminal + Target :class:`~libvt.terminal.Terminal` instance. + sync_timeout : float + Watchdog timeout in seconds before expiring stalled ``?2026`` holds. + write_high_water : int | None + Outbound high-water mark in bytes (defaults to + ``min(65_536, max_write_buffer)``). + max_write_buffer : int + Maximum queued outbound bytes before raising :exc:`BufferError`. + """ + _validate_nonneg_seconds(sync_timeout, "sync_timeout") + eff_hw, eff_max = _resolve_write_limits(write_high_water, max_write_buffer) self._master_fd = master_fd self.process = process self.terminal = terminal self.sync_timeout = sync_timeout + self.write_high_water = eff_hw + self.max_write_buffer = eff_max self._frame_event = asyncio.Event() + self._drain_event = asyncio.Event() + self._drain_event.set() self._eof = False self._closed = False + self._fd_closed = False + self._reader_registered = False + self._writer_registered = False + self._write_closed = False + self._write_error: OSError | None = None + self._async_write_error: OSError | None = None + self._read_error: OSError | None = None + self._write_queue: collections.deque[bytearray] = collections.deque() + self._write_head_offset: int = 0 + self._write_buffered_bytes: int = 0 self._sync_started_at: float | None = None self._sync_gen_tracked: int | None = None + self._sync_timer_handle: asyncio.TimerHandle | None = None + self._sync_timer_gen: int | None = None + self._last_committed_gen: int = self.terminal.committed_generation self._loop: asyncio.AbstractEventLoop | None = None @property @@ -388,76 +597,283 @@ def eof(self) -> bool: """Return ``True`` once the PTY master reaches EOF.""" return self._eof + @property + def write_buffer_size(self) -> int: + """Return number of outbound bytes currently buffered for ``master_fd``.""" + return self._write_buffered_bytes + + def _cancel_sync_timer(self) -> None: + if self._sync_timer_handle is not None: + self._sync_timer_handle.cancel() + self._sync_timer_handle = None + self._sync_timer_gen = None + + def _on_sync_timeout(self) -> None: + self._sync_timer_handle = None + self._sync_timer_gen = None + self._sync_frame_wakeup(time.monotonic()) + + def _remove_reader(self) -> None: + if self._loop is not None and self._reader_registered: + self._reader_registered = False + with contextlib.suppress(Exception): + self._loop.remove_reader(self._master_fd) + + def _remove_writer(self) -> None: + if self._loop is not None and self._writer_registered: + self._writer_registered = False + with contextlib.suppress(Exception): + self._loop.remove_writer(self._master_fd) + + def _ensure_writer(self) -> None: + if self._writer_registered or self._closed or self._fd_closed: + return + loop = self._loop + if loop is None: + loop = asyncio.get_running_loop() + self._loop = loop + loop.add_writer(self._master_fd, self._on_writable) + self._writer_registered = True + + def _mark_eof(self) -> None: + self._eof = True + self._cancel_sync_timer() + self._remove_reader() + self.terminal.expire_synchronized_output() + self._sync_started_at = None + self._sync_gen_tracked = None + self._last_committed_gen = self.terminal.committed_generation + self._frame_event.set() + + def _sync_frame_wakeup(self, now: float) -> None: + if self.terminal.synchronized: + cur_gen = self.terminal.sync_generation + if self._sync_gen_tracked != cur_gen or self._sync_started_at is None: + self._sync_gen_tracked = cur_gen + self._sync_started_at = now + if ( + now - self._sync_started_at >= self.sync_timeout + and self.terminal.expire_synchronized_output(cur_gen) + ): + self._cancel_sync_timer() + self._sync_started_at = None + self._sync_gen_tracked = None + elif ( + self._loop is not None + and not self._closed + and not self._eof + and self._sync_timer_gen != cur_gen + ): + self._cancel_sync_timer() + delay = max(0.0, self._sync_started_at + self.sync_timeout - now) + with contextlib.suppress(RuntimeError): + self._sync_timer_gen = cur_gen + self._sync_timer_handle = self._loop.call_later( + delay, + self._on_sync_timeout, + ) + else: + self._cancel_sync_timer() + self._sync_started_at = None + self._sync_gen_tracked = None + cur_committed = self.terminal.committed_generation + if cur_committed != self._last_committed_gen: + self._last_committed_gen = cur_committed + self._frame_event.set() + + def _append_queued_bytes(self, mv: memoryview) -> None: + if ( + self._write_queue + and (len(self._write_queue) > 1 or self._write_head_offset == 0) + and len(self._write_queue[-1]) + len(mv) <= _COALESCE_SLAB + ): + self._write_queue[-1].extend(mv) + else: + self._write_queue.append(bytearray(mv)) + self._write_buffered_bytes += len(mv) + + def _enqueue_write( + self, + data: collections.abc.Buffer, + *, + is_reply: bool = False, + ) -> None: + with memoryview(data) as raw_mv, raw_mv.cast("B") as mv: + n_total = len(mv) + if n_total == 0: + return + if self._closed or self._fd_closed: + if is_reply: + return + raise OSError(errno.EBADF, "PTY session is closed") + if self._write_closed: + if is_reply: + return + if self._write_error is not None: + raise self._write_error + raise OSError(errno.EIO, "PTY master write end is closed") + if self._write_buffered_bytes + n_total > self.max_write_buffer: + if is_reply: + return + msg = ( + f"PTY write buffer exceeded {self.max_write_buffer} bytes; " + "await session.drain()" + ) + raise BufferError(msg) + + if not self._write_queue: + pos = 0 + while pos < n_total: + try: + with mv[pos:] as tail: + n = os.write(self._master_fd, tail) + except (BlockingIOError, InterruptedError): + break + except OSError as exc: + self._write_closed = True + self._write_error = exc + if is_reply: + self._async_write_error = exc + return + raise + if n <= 0: + break + pos += n + if pos >= n_total: + return + with mv[pos:] as rem: + self._write_queue.append(bytearray(rem)) + self._write_head_offset = 0 + self._write_buffered_bytes = len(rem) + else: + self._append_queued_bytes(mv) + + if self._write_buffered_bytes > 0: + if self._write_buffered_bytes > self.write_high_water: + self._drain_event.clear() + self._ensure_writer() + + def _on_writable(self) -> None: + if self._closed or self._fd_closed or not self._write_queue: + self._remove_writer() + self._drain_event.set() + return + while self._write_queue: + head = self._write_queue[0] + try: + with memoryview(head) as mv, mv[self._write_head_offset :] as tail: + n = os.write(self._master_fd, tail) + except (BlockingIOError, InterruptedError): + if self._write_buffered_bytes <= self.write_high_water: + self._drain_event.set() + return + except OSError as exc: + self._write_closed = True + self._write_error = exc + self._async_write_error = exc + self._write_queue.clear() + self._write_head_offset = 0 + self._write_buffered_bytes = 0 + self._remove_writer() + self._drain_event.set() + return + if n <= 0: + if self._write_buffered_bytes <= self.write_high_water: + self._drain_event.set() + return + self._write_head_offset += n + self._write_buffered_bytes -= n + if self._write_head_offset >= len(head): + self._write_queue.popleft() + self._write_head_offset = 0 + if self._write_buffered_bytes <= self.write_high_water: + self._drain_event.set() + self._remove_writer() + self._drain_event.set() + + async def drain(self) -> None: + """Pause while outbound buffered bytes exceed :attr:`write_high_water`.""" + if self._write_buffered_bytes <= self.write_high_water: + if self._write_buffered_bytes > 0: + self._ensure_writer() + await asyncio.sleep(0) + while ( + self._write_buffered_bytes > self.write_high_water + and not self._closed + and not self._fd_closed + and not self._write_closed + ): + self._ensure_writer() + await self._drain_event.wait() + if ( + self._async_write_error is not None + and self._async_write_error.errno not in _PEER_EOF_ERRNOS + and not self._closed + ): + raise self._async_write_error + def _drain_nonblocking_master(self) -> None: - """Consume any buffered non-blocking bytes from ``master_fd``.""" - if self._closed or self._eof: + """Consume buffered non-blocking bytes from ``master_fd`` on teardown.""" + if self._closed or self._fd_closed or self._eof: return - while True: + for _ in range(256): try: chunk = os.read(self._master_fd, 16_384) except (BlockingIOError, InterruptedError): - return + break except OSError as exc: - if exc.errno == errno.EIO: + if exc.errno in _PEER_EOF_ERRNOS: chunk = b"" else: - return + break if not chunk: self._eof = True - return + break self.terminal.feed(chunk) + self.terminal.drain_replies() def _on_readable(self) -> None: - if self._closed: + if self._closed or self._fd_closed: return try: chunk = os.read(self._master_fd, 16_384) except (BlockingIOError, InterruptedError): return except OSError as exc: - if exc.errno == errno.EIO: + if exc.errno in _PEER_EOF_ERRNOS: chunk = b"" else: - raise + self._read_error = exc + self._mark_eof() + return if not chunk: - self._eof = True - if self._loop is not None: - self._loop.remove_reader(self._master_fd) - self._frame_event.set() + self._mark_eof() return self.terminal.feed(chunk) replies = self.terminal.drain_replies() if replies: - with contextlib.suppress(OSError): - os.write(self._master_fd, replies) - now = time.monotonic() - if self.terminal.synchronized: - cur_gen = self.terminal.sync_generation - if self._sync_gen_tracked != cur_gen or self._sync_started_at is None: - self._sync_gen_tracked = cur_gen - self._sync_started_at = now - else: - self._sync_started_at = None - self._sync_gen_tracked = None - self._frame_event.set() + self._enqueue_write(replies, is_reply=True) + self._sync_frame_wakeup(time.monotonic()) - def send(self, data: bytes | str, /) -> None: - """Write raw *data* bytes (or UTF-8 string) to the PTY master.""" - raw = data.encode("utf-8") if isinstance(data, str) else data - os.write(self._master_fd, raw) + def send(self, data: collections.abc.Buffer | str, /) -> None: + """Enqueue raw *data* bytes (or UTF-8 string) onto the PTY write queue.""" + if isinstance(data, str): + self._enqueue_write(data.encode("utf-8")) + else: + self._enqueue_write(data) def send_event(self, event: InputEvent, /) -> None: - """Encode *event* via :meth:`Terminal.encode` and write to the PTY.""" + """Encode *event* via :meth:`~libvt.terminal.Terminal.encode` and enqueue.""" encoded = self.terminal.encode(event) if encoded: - os.write(self._master_fd, encoded) + self._enqueue_write(encoded) def send_key(self, chord: str, /) -> None: - """Parse *chord* (e.g. ``"ctrl+c"``, ``"enter"``) and send to the PTY.""" + """Parse *chord* (e.g. ``"ctrl+c"``, ``"enter"``) and enqueue for the PTY.""" self.send_event(KeyEvent.parse(chord)) def paste(self, text: str, /, *, sanitize: bool = False) -> None: - """Encode *text* as a :class:`PasteEvent` and write to the PTY.""" + """Encode *text* as an atomic :class:`~libvt.input.PasteEvent` on the queue.""" self.send_event(PasteEvent(text=text, sanitize=sanitize)) def resize( @@ -467,13 +883,23 @@ def resize( cols: int, reflow: bool | None = None, ) -> None: - """Update kernel ``TIOCSWINSZ`` and resize :attr:`terminal`.""" + """Update ``TIOCSWINSZ``, resize :attr:`terminal`, and flush ``?2048``.""" + if sys.platform == "win32": + msg = "PtySession.resize requires POSIX termios" + raise NotImplementedError(msg) + _validate_pty_dims(rows, cols) + if self._closed or self._fd_closed: + raise OSError(errno.EBADF, "PTY session is closed") import fcntl import termios - winsz = struct.pack("HHHH", rows, cols, 0, 0) + winsz = _pack_winsize(rows, cols, self.terminal.profile) fcntl.ioctl(self._master_fd, termios.TIOCSWINSZ, winsz) self.terminal.resize(rows=rows, cols=cols, reflow=reflow) + replies = self.terminal.drain_replies() + if replies: + self._enqueue_write(replies, is_reply=True) + self._sync_frame_wakeup(time.monotonic()) async def wait_for( self, @@ -482,7 +908,7 @@ async def wait_for( timeout: float = 2.0, attach_note: bool = True, ) -> Snapshot: - """Wait until *predicate* matches the committed :class:`Snapshot`. + """Wait until *predicate* matches :class:`~libvt.terminal.Snapshot`. Parameters ---------- @@ -504,9 +930,9 @@ async def wait_for( Raises ------ TerminalTimeoutError - If the PTY reaches EOF before matching (``eof=True``) or *timeout* - expires (``eof=False``). + If the PTY reaches EOF/close before matching or *timeout* expires. """ + _validate_nonneg_seconds(timeout, "timeout") check = ( (lambda snap: predicate in snap.text) if isinstance(predicate, str) @@ -514,31 +940,33 @@ async def wait_for( ) deadline = time.monotonic() + timeout while True: + if self._read_error is not None: + err = self._read_error + self._read_error = None + raise err now = time.monotonic() - if ( - self.terminal.synchronized - and self._sync_started_at is not None - and now - self._sync_started_at >= self.sync_timeout - ): - self.terminal.expire_synchronized_output(self._sync_gen_tracked) - self._sync_started_at = None - self._sync_gen_tracked = None - snap = self.terminal.snapshot() if self._eof else self.terminal.committed + if self.terminal.synchronized: + self._sync_frame_wakeup(now) + ended = self._eof or self._closed + snap = self.terminal.snapshot() if ended else self.terminal.committed if check(snap): return snap - if self._eof: + if ended: + reason = ( + "PTY reached EOF before predicate matched" + if self._eof + else "PTY session closed before predicate matched" + ) raise _make_timeout_error( self.terminal, snap, - "PTY reached EOF before predicate matched", - eof=True, + reason, + eof=self._eof, attach_note=attach_note, ) remaining = deadline - now if remaining <= 0: live = self.terminal.snapshot() - if check(live): - return live raise _make_timeout_error( self.terminal, live, @@ -561,35 +989,70 @@ async def wait_for( async def aclose(self) -> int: """Signal the owned process group, drain PTY output, and close master fd.""" - if self.process.returncode is None: - pid = self.process.pid - for sig, wait_s in ( - (signal.SIGHUP, 0.4), - (signal.SIGTERM, 0.4), - ): - if self.process.returncode is not None: - break - with contextlib.suppress(ProcessLookupError, PermissionError): - os.killpg(pid, sig) - with contextlib.suppress(TimeoutError): - await asyncio.wait_for(self.process.wait(), timeout=wait_s) + try: if self.process.returncode is None: - with contextlib.suppress(ProcessLookupError, PermissionError): - os.killpg(pid, signal.SIGKILL) + if sys.platform == "win32": + with contextlib.suppress(ProcessLookupError): + self.process.terminate() + with contextlib.suppress(TimeoutError): + await asyncio.wait_for(self.process.wait(), timeout=0.4) + if self.process.returncode is None: + with contextlib.suppress(ProcessLookupError): + self.process.kill() + await self.process.wait() + else: + pid = self.process.pid + for sig, wait_s in ( + (signal.SIGHUP, 0.4), + (signal.SIGTERM, 0.4), + ): + if self.process.returncode is not None: + break + with contextlib.suppress(ProcessLookupError, PermissionError): + os.killpg(pid, sig) + with contextlib.suppress(TimeoutError): + await asyncio.wait_for( + self.process.wait(), + timeout=wait_s, + ) + if self.process.returncode is None: + with contextlib.suppress(ProcessLookupError, PermissionError): + os.killpg(pid, signal.SIGKILL) + with contextlib.suppress(ProcessLookupError): + self.process.kill() + await self.process.wait() + except BaseException: + if self.process.returncode is None: + if sys.platform != "win32": + with contextlib.suppress(ProcessLookupError, PermissionError): + os.killpg(self.process.pid, signal.SIGKILL) with contextlib.suppress(ProcessLookupError): self.process.kill() await self.process.wait() - - if not self._closed: + raise + finally: + was_closed = self._closed + self._cancel_sync_timer() + self._remove_reader() + self._remove_writer() self._drain_nonblocking_master() self._closed = True - if self._loop is not None: - with contextlib.suppress(Exception): - self._loop.remove_reader(self._master_fd) - with contextlib.suppress(OSError): - os.close(self._master_fd) + self._write_queue.clear() + self._write_head_offset = 0 + self._write_buffered_bytes = 0 + self._drain_event.set() + if not self._fd_closed: + self._fd_closed = True + with contextlib.suppress(OSError): + os.close(self._master_fd) + self.terminal.expire_synchronized_output() + self._sync_started_at = None + self._sync_gen_tracked = None + if not was_closed: + self.terminal.notify_process_exit() + self._last_committed_gen = self.terminal.committed_generation + self._frame_event.set() - self.terminal.notify_process_exit() return self.process.returncode or 0 @@ -608,19 +1071,21 @@ async def open_pty( policy: Policy = DEFAULT_POLICY, limits: Limits = DEFAULT_LIMITS, sync_timeout: float = 1.0, + write_high_water: int | None = None, + max_write_buffer: int = 16_777_216, ) -> collections.abc.AsyncGenerator[PtySession]: - """Spawn *argv* with a controlling POSIX PTY driven by :class:`Terminal`. + """Spawn *argv* on a POSIX PTY driven by :class:`~libvt.terminal.Terminal`. Parameters ---------- argv : collections.abc.Sequence[str] Command and arguments executed via ``os.execvp``. rows : int - Initial PTY height in rows. + Initial PTY height in rows (``1..65535``). cols : int - Initial PTY width in columns. + Initial PTY width in columns (``1..65535``). scrollback : int - Primary-screen scrollback line capacity. + Primary-screen scrollback line capacity (``>= 0``). env : collections.abc.Mapping[str, str] | None Environment variables passed to the child process (defaults to ``os.environ`` with ``TERM=xterm-256color``). @@ -638,6 +1103,12 @@ async def open_pty( Parser and state resource ceilings. sync_timeout : float Watchdog timeout in seconds before expiring stalled ``?2026`` frames. + write_high_water : int | None + High-water mark in bytes for outbound PTY writes (defaults to + ``min(65_536, max_write_buffer)``). + max_write_buffer : int + Maximum outbound bytes queued before :meth:`PtySession.send` raises + :exc:`BufferError`. Yields ------ @@ -649,7 +1120,8 @@ async def open_pty( NotImplementedError On platforms lacking POSIX ``pty.openpty()`` (Windows). ValueError - If *argv* is empty or *tty_mode* is invalid. + If *argv*, dimensions, *tty_mode*, *sync_timeout*, or buffer sizes are + invalid. OSError If PTY allocation or ``execvp`` fails. """ @@ -659,9 +1131,19 @@ async def open_pty( if not argv: msg = "argv must not be empty" raise ValueError(msg) + _validate_pty_dims(rows, cols) + if ( + isinstance(scrollback, bool) + or not isinstance(scrollback, int) + or scrollback < 0 + ): + msg = f"scrollback must be an int >= 0, got {scrollback!r}" + raise ValueError(msg) if tty_mode not in ("cooked", "cbreak", "raw"): msg = f"unsupported tty_mode: {tty_mode!r}" raise ValueError(msg) + _validate_nonneg_seconds(sync_timeout, "sync_timeout") + eff_hw, eff_max = _resolve_write_limits(write_high_water, max_write_buffer) if python_executable is None: if getattr(sys, "frozen", False) or not sys.executable: @@ -684,12 +1166,13 @@ async def open_pty( err_r, err_w = os.pipe() slave_closed = False err_w_closed = False + master_handed_off = False proc: asyncio.subprocess.Process | None = None try: fcntl.ioctl( slave_fd, termios.TIOCSWINSZ, - struct.pack("HHHH", rows, cols, 0, 0), + _pack_winsize(rows, cols, profile), ) if tty_mode == "cbreak": tty.setcbreak(slave_fd) @@ -725,15 +1208,44 @@ async def open_pty( if err_payload != b"\x00": 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, + terminal=terminal, + sync_timeout=sync_timeout, + write_high_water=eff_hw, + max_write_buffer=eff_max, + ) + session._loop = loop + master_handed_off = True except BaseException: if proc is not None and proc.returncode is None: - with contextlib.suppress(ProcessLookupError, PermissionError): - os.killpg(proc.pid, signal.SIGKILL) + if sys.platform != "win32": + with contextlib.suppress(ProcessLookupError, PermissionError): + os.killpg(proc.pid, signal.SIGKILL) with contextlib.suppress(ProcessLookupError): proc.kill() await proc.wait() - with contextlib.suppress(OSError): - os.close(master_fd) raise finally: if not slave_closed: @@ -744,35 +1256,13 @@ async def open_pty( os.close(err_w) with contextlib.suppress(OSError): os.close(err_r) + if not master_handed_off: + with contextlib.suppress(OSError): + os.close(master_fd) - 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, - terminal=terminal, - sync_timeout=sync_timeout, - ) - session._loop = loop - loop.add_reader(master_fd, session._on_readable) try: + loop.add_reader(master_fd, session._on_readable) + session._reader_registered = True yield session finally: await session.aclose() diff --git a/src/libvt/codec.py b/src/libvt/codec.py index 237abf3..569e42b 100644 --- a/src/libvt/codec.py +++ b/src/libvt/codec.py @@ -106,7 +106,12 @@ class ExplainedSpan: 52: "OSC 52 (clipboard)", 66: "OSC 66 (text sizing)", 99: "OSC 99 (kitty notification)", + 104: "OSC 104 (reset palette)", + 110: "OSC 110 (reset fg color)", + 111: "OSC 111 (reset bg color)", + 112: "OSC 112 (reset cursor color)", 133: "OSC 133 (semantic prompt)", + 777: "OSC 777 (notification)", 3008: "OSC 3008 (context)", 5522: "OSC 5522 (mime clipboard)", 7501: "OSC 7501 (program status)", @@ -114,8 +119,10 @@ class ExplainedSpan: def _describe_mode(code: int, *, private: bool) -> str: - raw = (DEC_PRIVATE_MASK | code) if private else code prefix = "?" if private else "" + if not (0 <= code < DEC_PRIVATE_MASK): + return f"{prefix}{code}" + raw = (DEC_PRIVATE_MASK | code) if private else code try: name = Mode(raw).name except ValueError: diff --git a/src/libvt/config.py b/src/libvt/config.py index de514d5..1e00065 100644 --- a/src/libvt/config.py +++ b/src/libvt/config.py @@ -7,14 +7,44 @@ import typing as t from dataclasses import dataclass +#: Supported ``G0``..``G3`` character-set designators (US-ASCII, DEC Special, UK). type Charset = t.Literal["B", "0", "A"] + +#: ``SIXEL`` cell-overwrite and rectangular-erase clipping policy. type SixelErasePolicy = t.Literal["cell_mask", "whole_image"] _TMUX_VERSION_RE = re.compile( - r"^\s*(?:tmux\s+)?(?:next-)?(\d+)\.(\d+)(?:[a-z]|-rc\d*)?\s*$", + r"^\s*(?:tmux\s+)?(?:next-)?([0-9]{1,3})\.([0-9]{1,3})(?:[a-z]|-rc[0-9]{0,3})?\s*\Z", + re.ASCII, ) +def _parse_tmux_version(version: tuple[int, int] | str) -> tuple[int, int]: + """Parse ``version`` tuple or ``tmux -V`` string into ``(major, minor)``.""" + if isinstance(version, tuple): + if len(version) != 2 or any( + isinstance(v, bool) or not isinstance(v, int) or not (0 <= v <= 999) + for v in version + ): + msg = ( + f"invalid tmux version {repr(version)[:64]}; expected " + "(major, minor) ints in 0..999" + ) + raise ValueError(msg) + return version + if not isinstance(version, str): + msg = f"invalid tmux version type {type(version).__name__}" + raise TypeError(msg) + m = _TMUX_VERSION_RE.match(version) + if m is None: + msg = ( + f"invalid tmux version {version[:64]!r}; expected e.g. " + "'3.8a', 'next-3.9', or (3, 8)" + ) + raise ValueError(msg) + return int(m.group(1)), int(m.group(2)) + + class ColorScheme(enum.IntEnum): """``CSI ? 997 ; Ps n`` color-scheme values (``DEC ?2031`` / ``DSR ?996n``).""" @@ -46,6 +76,8 @@ class Profile: Default foreground 8-bit RGB reported for ``OSC 10 ; ?``. bg_rgb : tuple[int, int, int] Default background 8-bit RGB reported for ``OSC 11 ; ?``. + cursor_rgb : tuple[int, int, int] + Default cursor 8-bit RGB reported for ``OSC 12 ; ?``. pending_wrap_phantom_col : bool When ``True`` (``TMUX_PROFILE``), ``pending_wrap`` treats the cursor as occupying phantom column ``cols`` across ``EL``/``ED``, ``ECH``/``ICH``/ @@ -93,12 +125,29 @@ class Profile: ``CSI J`` with cursor at ``(0, 0)``) scrolls rows up to the last non-empty or image-bearing row into scrollback before clearing with ``BCE``, matching ``tmux``'s ``scroll-on-clear`` default. + declrmm_enabled : bool + When ``True`` (default), DEC mode ``?69`` (``DECLRMM``) enables + ``DECSLRM`` horizontal margins on ``CSI Pl ; Pr s``; when ``False`` + (``TMUX_PROFILE``), ``?69`` is unrecognized and any ``CSI ... s`` + executes ``SCOSC`` cursor save, matching ``tmux``'s ``input.c``. + top_margin_scrolls_to_history : bool + When ``True`` (``TMUX_PROFILE``), primary-screen full-width upward + scrolls (``LF``, ``IND``, ``NEL``, ``SU``) push ``DECSTBM``'s top row + into scrollback even when ``top > 0``, matching ``tmux``'s + ``grid_scroll_history_region``. + separate_alt_save_cursor : bool + When ``True`` (``TMUX_PROFILE``), ``DECSC`` / ``SCOSC`` uses an + independent cursor save slot rather than sharing primary-screen state + with ``?1049h`` / ``?1049l`` (and DEC ``?1048`` is unrecognized), + matching ``tmux``'s ``ictx->old_cx`` vs ``s->saved_cx``. cell_width_px : int - Nominal cell width in pixels used for ``CSI 14 t``, ``CSI 16 t``, and - ``SIXEL`` / Kitty cell-grid geometry (default ``8``). + Nominal cell width in pixels used for ``CSI 14 t``, ``CSI 16 t``, + ``?1016``, ``?2048``, ``TIOCSWINSZ``, and ``SIXEL`` / Kitty cell-grid + geometry (default ``8``). cell_height_px : int - Nominal cell height in pixels used for ``CSI 14 t``, ``CSI 16 t``, and - ``SIXEL`` / Kitty cell-grid geometry (default ``16``). + Nominal cell height in pixels used for ``CSI 14 t``, ``CSI 16 t``, + ``?1016``, ``?2048``, ``TIOCSWINSZ``, and ``SIXEL`` / Kitty cell-grid + geometry (default ``16``). sixel_erase_policy : SixelErasePolicy How text overwrites and cell erases affect ``SIXEL`` placements: ``"cell_mask"`` (default and ``tmux >= 3.9``) clears individual cells; @@ -116,6 +165,7 @@ class Profile: color_scheme: ColorScheme = ColorScheme.DARK fg_rgb: tuple[int, int, int] = (0xE5, 0xE5, 0xE5) bg_rgb: tuple[int, int, int] = (0x1E, 0x1E, 0x1E) + cursor_rgb: tuple[int, int, int] = (0xE5, 0xE5, 0xE5) pending_wrap_phantom_col: bool = False vs15_narrows_wide_emoji: bool = True vs16_always_wide: bool = False @@ -128,6 +178,9 @@ class Profile: default_g1_charset: Charset = "B" decstr_enabled: bool = True ed2_scrolls_primary_to_history: bool = False + declrmm_enabled: bool = True + top_margin_scrolls_to_history: bool = False + separate_alt_save_cursor: bool = False cell_width_px: int = 8 cell_height_px: int = 16 sixel_erase_policy: SixelErasePolicy = "cell_mask" @@ -152,17 +205,7 @@ def tmux(cls, version: tuple[int, int] | str = "3.8a") -> Profile: ValueError If *version* cannot be parsed as a ``tmux`` version identifier. """ - if isinstance(version, tuple): - major, minor = version - else: - m = _TMUX_VERSION_RE.match(version) - if m is None: - msg = ( - f"invalid tmux version {version!r}; expected e.g. " - "'3.8a', 'next-3.9', or (3, 8)" - ) - raise ValueError(msg) - major, minor = int(m.group(1)), int(m.group(2)) + major, minor = _parse_tmux_version(version) at_least_3_9 = (major, minor) >= (3, 9) return cls( name="tmux", @@ -176,6 +219,9 @@ def tmux(cls, version: tuple[int, int] | str = "3.8a") -> Profile: rep_wraps=at_least_3_9, decstr_enabled=False, ed2_scrolls_primary_to_history=True, + declrmm_enabled=False, + top_margin_scrolls_to_history=True, + separate_alt_save_cursor=True, sixel_erase_policy="cell_mask" if at_least_3_9 else "whole_image", ) @@ -190,6 +236,7 @@ def linux_console(cls) -> Profile: ) +#: Default ``OSC 7`` ``file://`` hostnames accepted in sans-I/O mode. DEFAULT_OSC7_HOSTS: frozenset[str] = frozenset({"", "localhost"}) @@ -209,8 +256,8 @@ class Policy: Emit :class:`~libvt.events.ClipboardWrite` events on ``OSC 52`` writes (default ``True``; no host clipboard is ever mutated by ``libvt``). allow_color_queries : bool - Permit ``OSC 10 ; ?``, ``OSC 11 ; ?``, and ``CSI ? 996 n`` palette and - color-scheme replies (default ``True``). + Permit ``OSC 4 ; c ; ?``, ``OSC 10 ; ?`` through ``OSC 12 ; ?``, and + ``CSI ? 996 n`` palette and color-scheme replies (default ``True``). allow_program_status_query : bool Permit ``OSC 7501 ; ?`` capability replies whenever ``profile.osc_7501_capabilities`` is non-empty (default ``True``). @@ -321,18 +368,31 @@ class Limits: max_image_dimension: int = 10_000 -DEFAULT_PROFILE = Profile() -XTERM_PROFILE = Profile( +#: Default modern VT500 / ``Ghostty``-aligned terminal profile. +DEFAULT_PROFILE: Profile = Profile() + +#: ``xterm`` compatibility profile (no resize reflow, alt-screen ``ED 3`` clear). +XTERM_PROFILE: Profile = Profile( name="xterm", osc_7501_capabilities="", reflow_on_resize=False, ed3_clears_scrollback_on_alt=True, ) -TMUX_PROFILE = Profile.tmux("3.8a") -LINUX_CONSOLE_PROFILE = Profile.linux_console() -DEFAULT_POLICY = Policy() -TMUX_CAPTURE_POLICY = Policy(allow_passthrough=False) -DEFAULT_LIMITS = Limits() + +#: ``tmux 3.8a`` inner-pane compatibility profile. +TMUX_PROFILE: Profile = Profile.tmux("3.8a") + +#: Linux virtual-console compatibility profile. +LINUX_CONSOLE_PROFILE: Profile = Profile.linux_console() + +#: Default host security and query policy. +DEFAULT_POLICY: Policy = Policy() + +#: Default policy for :func:`~libvt.tmux.decode_tmux_capture`. +TMUX_CAPTURE_POLICY: Policy = Policy(allow_passthrough=False) + +#: Default memory and sequence-size ceilings. +DEFAULT_LIMITS: Limits = Limits() __all__ = [ "DEFAULT_LIMITS", diff --git a/src/libvt/graphics.py b/src/libvt/graphics.py index 681f5fe..caa99aa 100644 --- a/src/libvt/graphics.py +++ b/src/libvt/graphics.py @@ -12,6 +12,8 @@ import zlib from dataclasses import dataclass +from libvt.parser import _parse_ascii_uint + if t.TYPE_CHECKING: from libvt.config import SixelErasePolicy @@ -346,6 +348,131 @@ def freeze(self) -> ImagePlacement: ) +def _trim_masked_sixel_rows(p: _MutablePlacement) -> bool: + """Trim completely zeroed leading or trailing ``SIXEL`` mask rows in place.""" + if p.protocol != GraphicsProtocol.SIXEL or p.visible_mask is None: + return False + if p.rows <= 0 or p.cols <= 0 or p.visible_mask <= 0: + p.rows = 0 + p.visible_mask = 0 + return True + cols = p.cols + mask = p.visible_mask + row_full = (1 << cols) - 1 + top_trim = 0 + while top_trim < p.rows and ((mask >> (top_trim * cols)) & row_full) == 0: + top_trim += 1 + bot_trim = 0 + while ( + top_trim + bot_trim < p.rows + and ((mask >> ((p.rows - 1 - bot_trim) * cols)) & row_full) == 0 + ): + bot_trim += 1 + if top_trim == 0 and bot_trim == 0: + if mask == (1 << (p.rows * cols)) - 1: + p.visible_mask = None + return True + return False + if top_trim + bot_trim >= p.rows: + p.rows = 0 + p.visible_mask = 0 + return True + if top_trim > 0: + if p.source_height > 0: + crop_top = (p.source_height * top_trim) // p.rows + p.source_y += crop_top + p.source_height = max(1, p.source_height - crop_top) + p.abs_row += top_trim + p.rows -= top_trim + mask >>= top_trim * cols + if bot_trim > 0: + if p.source_height > 0 and p.rows > 0: + crop_bot = (p.source_height * bot_trim) // p.rows + p.source_height = max(1, p.source_height - crop_bot) + p.rows -= bot_trim + mask &= (1 << (p.rows * cols)) - 1 + p.visible_mask = None if mask == (1 << (p.rows * cols)) - 1 else mask + return True + + +def _clip_placement_bounds( + p: _MutablePlacement, + *, + min_abs: int, + max_abs: int | None, + new_cols: int | None, +) -> tuple[bool, bool]: + """Clip *p* to ``[min_abs, max_abs)`` and *new_cols*; return ``(mutated, keep)``.""" + mutated = False + if p.rows <= 0 or p.cols <= 0: + return True, False + if new_cols is not None: + if p.col >= new_cols: + return True, False + if p.protocol == GraphicsProtocol.SIXEL and p.col + p.cols > new_cols: + keep_cols = new_cols - p.col + if keep_cols <= 0: + return True, False + old_cols = p.cols + if p.visible_mask is not None and p.rows * old_cols <= _MAX_MASK_CELLS: + row_keep = (1 << keep_cols) - 1 + new_mask = 0 + for rr in range(p.rows): + row_bits = (p.visible_mask >> (rr * old_cols)) & row_keep + new_mask |= row_bits << (rr * keep_cols) + if new_mask == 0: + return True, False + full_new = (1 << (p.rows * keep_cols)) - 1 + p.visible_mask = None if new_mask == full_new else new_mask + if p.source_width > 0: + p.source_width = max(1, (p.source_width * keep_cols) // old_cols) + p.cols = keep_cols + mutated = True + + if p.abs_row < min_abs: + clip_top = min_abs - p.abs_row + if clip_top >= p.rows: + return True, False + if p.source_height > 0: + crop_px = (p.source_height * clip_top) // p.rows + p.source_y += crop_px + p.source_height = max(1, p.source_height - crop_px) + keep_rows = p.rows - clip_top + if p.visible_mask is not None and p.rows * p.cols <= _MAX_MASK_CELLS: + shifted = p.visible_mask >> (clip_top * p.cols) + full_m = (1 << (keep_rows * p.cols)) - 1 + shifted &= full_m + if shifted == 0: + return True, False + p.visible_mask = None if shifted == full_m else shifted + p.rows = keep_rows + p.abs_row = min_abs + mutated = True + + if max_abs is not None and p.abs_row + p.rows > max_abs: + if p.abs_row >= max_abs: + return True, False + keep_rows = max_abs - p.abs_row + clip_bot = p.rows - keep_rows + if p.source_height > 0: + crop_px = (p.source_height * clip_bot) // p.rows + p.source_height = max(1, p.source_height - crop_px) + if p.visible_mask is not None and keep_rows * p.cols <= _MAX_MASK_CELLS: + full_m = (1 << (keep_rows * p.cols)) - 1 + masked = p.visible_mask & full_m + if masked == 0: + return True, False + p.visible_mask = None if masked == full_m else masked + p.rows = keep_rows + mutated = True + + if _trim_masked_sixel_rows(p): + mutated = True + if p.rows <= 0: + return True, False + return mutated, True + + class _Decompressor(t.Protocol): @property def eof(self) -> bool: ... @@ -372,14 +499,51 @@ class _PendingKittyUpload: failed_error: str | None = None +_KITTY_UINT32_MAX = 0xFFFF_FFFF +_KITTY_INT32_MIN = -2_147_483_648 +_KITTY_INT32_MAX = 2_147_483_647 + + +def _parse_uint32(control: dict[str, str], key: str, default: int = 0) -> int: + raw = control.get(key) + if raw is None or not raw: + return default + val = _parse_ascii_uint(raw, max_val=_KITTY_UINT32_MAX) + return default if val is None else val + + def _parse_int(control: dict[str, str], key: str, default: int = 0) -> int: raw = control.get(key) if raw is None or not raw: return default - try: - return int(raw) - except ValueError: + neg = False + start = 0 + first = raw[0] + if first == "-": + neg = True + start = 1 + elif first == "+": + start = 1 + if start >= len(raw): return default + limit = -_KITTY_INT32_MIN if neg else _KITTY_UINT32_MAX + acc = 0 + for idx in range(start, len(raw)): + code = ord(raw[idx]) + if not (0x30 <= code <= 0x39): + return default + if acc < limit: + acc = min(limit, acc * 10 + (code - 0x30)) + return -acc if neg else acc + + +def _valid_quiet(control: dict[str, str]) -> int: + raw = control.get("q") + if raw == "2": + return 2 + if raw == "1": + return 1 + return 0 def _kitty_reply( @@ -389,15 +553,15 @@ def _kitty_reply( is_error: bool, reply_image_id: int | None = None, ) -> bytes | None: - quiet = _parse_int(control, "q", 0) + quiet = _valid_quiet(control) if quiet == 2 or (quiet == 1 and not is_error): return None - client_id = _parse_int(control, "i", 0) - client_num = _parse_int(control, "I", 0) + client_id = _parse_uint32(control, "i", 0) + client_num = _parse_uint32(control, "I", 0) if client_id <= 0 and client_num <= 0: return None img_id = reply_image_id if reply_image_id is not None else client_id - pid = _parse_int(control, "p", 0) + pid = _parse_uint32(control, "p", 0) tokens: list[str] = [] if img_id > 0: tokens.append(f"i={img_id}") @@ -535,7 +699,9 @@ def _store_image(self, meta: ImageMeta) -> None: self._bump() def _append_placement(self, pl: _MutablePlacement) -> None: + replaced = False if pl.protocol == GraphicsProtocol.KITTY and pl.placement_id > 0: + before = len(self._placements) self._placements = [ p for p in self._placements @@ -545,9 +711,13 @@ def _append_placement(self, pl: _MutablePlacement) -> None: and p.placement_id == pl.placement_id ) ] + replaced = len(self._placements) != before self._placements.append(pl) + need_prune = replaced if len(self._placements) > self._max_placements: del self._placements[: len(self._placements) - self._max_placements] + need_prune = True + if need_prune: self._prune_orphans() self._bump() @@ -577,31 +747,134 @@ def clear_active_screen(self, scrolled_total: int, screen_rows: int) -> None: self._bump() def clear_history(self, scrolled_total: int) -> None: - """Delete placements located completely inside scrollback (``ED 3``).""" + """Clip or delete placements intersecting cleared scrollback (``ED 3``).""" + self.reap_evicted_history(scrolled_total) + + def reap_evicted_history(self, min_retained_abs_row: int) -> None: + """Clip or reap non-virtual placements scrolled past *min_retained_abs_row*.""" if not self._placements: return - kept = [ - p - for p in self._placements - if p.virtual or p.abs_row + p.rows > scrolled_total - ] - if len(kept) != len(self._placements): + changed = False + kept: list[_MutablePlacement] = [] + for p in self._placements: + if p.virtual: + kept.append(p) + continue + mutated, keep = _clip_placement_bounds( + p, + min_abs=min_retained_abs_row, + max_abs=None, + new_cols=None, + ) + if mutated: + changed = True + if keep: + kept.append(p) + else: + changed = True + if changed: self._placements = kept self._prune_orphans() self._bump() - def reap_evicted_history(self, min_retained_abs_row: int) -> None: - """Reap non-virtual placements scrolled past *min_retained_abs_row*.""" + def root_placement_pins(self) -> list[tuple[int, int, int]]: + """Return ``(index, abs_row, col)`` for non-virtual root placements.""" + return [ + (idx, p.abs_row, p.col) + for idx, p in enumerate(self._placements) + if not p.virtual and p.parent_image_id == 0 + ] + + def apply_reflow_pins( + self, + remapped_roots: collections.abc.Sequence[tuple[int, int, int]], + *, + new_cols: int, + min_retained_abs_row: int, + max_abs: int, + ) -> None: + """Apply reflowed ``(index, abs_row, col)`` pins and clip screen bounds.""" if not self._placements: return - kept = [ - p - for p in self._placements - if p.virtual or p.abs_row + p.rows > min_retained_abs_row + n_pl = len(self._placements) + old_coords: list[tuple[int, int]] = [ + (p.abs_row, p.col) for p in self._placements ] - if len(kept) != len(self._placements): + last_by_key: dict[tuple[int, int], int] = {} + last_by_img: dict[int, int] = {} + for idx, p in enumerate(self._placements): + if not p.virtual: + last_by_img[p.image_id] = idx + if p.placement_id > 0: + last_by_key[(p.image_id, p.placement_id)] = idx + + resolved: list[bool] = [ + p.virtual or p.parent_image_id <= 0 for p in self._placements + ] + changed = False + for idx, new_abs, new_col in remapped_roots: + p = self._placements[idx] + clamped_abs = max(0, new_abs) + clamped_col = max(0, min(new_cols - 1, new_col)) + if p.abs_row != clamped_abs or p.col != clamped_col: + p.abs_row = clamped_abs + p.col = clamped_col + changed = True + + def _resolve_child(idx: int, depth: int) -> None: + nonlocal changed + if resolved[idx] or depth > _MAX_PARENT_DEPTH: + resolved[idx] = True + return + p = self._placements[idx] + p_idx = ( + last_by_key.get((p.parent_image_id, p.parent_placement_id)) + if p.parent_placement_id > 0 + else last_by_img.get(p.parent_image_id) + ) + if p_idx is None or p_idx == idx: + resolved[idx] = True + return + if not resolved[p_idx]: + _resolve_child(p_idx, depth + 1) + parent_pl = self._placements[p_idx] + rel_v = old_coords[idx][0] - old_coords[p_idx][0] + rel_h = old_coords[idx][1] - old_coords[p_idx][1] + new_abs = max(0, parent_pl.abs_row + rel_v) + new_col = max(0, min(new_cols - 1, parent_pl.col + rel_h)) + if p.abs_row != new_abs or p.col != new_col: + p.abs_row = new_abs + p.col = new_col + changed = True + resolved[idx] = True + + for idx in range(n_pl): + if not resolved[idx]: + _resolve_child(idx, 0) + + kept: list[_MutablePlacement] = [] + dropped_any = False + for p in self._placements: + if p.virtual: + kept.append(p) + continue + mutated, keep = _clip_placement_bounds( + p, + min_abs=min_retained_abs_row, + max_abs=max_abs, + new_cols=new_cols, + ) + if mutated: + changed = True + if keep: + kept.append(p) + else: + changed = True + dropped_any = True + if dropped_any: self._placements = kept self._prune_orphans() + if changed: self._bump() def on_non_reflow_resize( @@ -611,53 +884,43 @@ def on_non_reflow_resize( new_rows: int, new_cols: int, scrolled_total: int, + min_retained_abs_row: int = 0, ) -> None: """Adjust placements when a non-reflow ``resize()`` drops or clips rows.""" if not self._placements: return changed = False kept: list[_MutablePlacement] = [] + dropped_any = False max_abs = scrolled_total + new_rows for p in self._placements: if p.virtual: kept.append(p) continue if top_drop_without_history > 0: - new_abs = p.abs_row - top_drop_without_history - if new_abs < scrolled_total: - clip_top = scrolled_total - new_abs - if clip_top >= p.rows: - changed = True - continue - keep_rows = p.rows - clip_top - if p.source_height > 0: - crop_px = (p.source_height * clip_top) // p.rows - p.source_y += crop_px - p.source_height = max(1, p.source_height - crop_px) - if ( - p.visible_mask is not None - and keep_rows * p.cols <= _MAX_MASK_CELLS - ): - shifted = p.visible_mask >> (clip_top * p.cols) - p.visible_mask = shifted & ((1 << (keep_rows * p.cols)) - 1) - if p.visible_mask == 0: - changed = True - continue - p.rows = keep_rows - p.abs_row = scrolled_total - else: - p.abs_row = new_abs + p.abs_row -= top_drop_without_history changed = True - if p.abs_row + p.rows <= scrolled_total or p.abs_row >= max_abs: + eff_min = max( + min_retained_abs_row, + scrolled_total if top_drop_without_history > 0 else 0, + ) + mutated, keep = _clip_placement_bounds( + p, + min_abs=eff_min, + max_abs=max_abs, + new_cols=new_cols, + ) + if mutated: changed = True - continue - if p.col >= new_cols: + if keep: + kept.append(p) + else: changed = True - continue - kept.append(p) - if changed: + dropped_any = True + if dropped_any: self._placements = kept self._prune_orphans() + if changed: self._bump() def erase_sixel_rect( @@ -711,10 +974,15 @@ def erase_sixel_rect( continue if mask != prev_mask: p.visible_mask = mask + _trim_masked_sixel_rows(p) changed = True + if p.rows <= 0: + continue kept.append(p) if changed: - self._placements = kept + if len(kept) != len(self._placements): + self._placements = kept + self._prune_orphans() self._bump() def on_region_scroll( @@ -747,6 +1015,70 @@ def on_region_scroll( p_left = p.col p_right = p.col + p.cols - 1 + if history_advanced > 0: + if top == 0: + if p_bot <= abs_bot: + kept.append(p) + continue + if p_top > abs_bot: + p.abs_row += history_advanced + changed = True + kept.append(p) + continue + else: + if p_bot < scrolled_total: + kept.append(p) + continue + if p_top < scrolled_total <= p_bot: + keep_hist_rows = scrolled_total - p_top + crop_bot = p.rows - keep_hist_rows + if ( + p.protocol == GraphicsProtocol.KITTY + or p.parent_image_id > 0 + ): + if p.source_height > 0 and p.rows > 0: + crop_px = (p.source_height * crop_bot) // p.rows + p.source_height = max(0, p.source_height - crop_px) + if p.source_height <= 0: + changed = True + continue + p.rows = keep_hist_rows + else: + if ( + p.visible_mask is not None + and keep_hist_rows * p.cols <= _MAX_MASK_CELLS + ): + p.visible_mask &= (1 << (keep_hist_rows * p.cols)) - 1 + if p.visible_mask == 0: + changed = True + continue + p.rows = keep_hist_rows + _trim_masked_sixel_rows(p) + if p.rows <= 0: + changed = True + continue + changed = True + kept.append(p) + continue + if p_top >= scrolled_total and p_bot < abs_top: + p.abs_row += history_advanced + changed = True + kept.append(p) + continue + if p_top >= abs_top and p_bot < abs_top + history_advanced: + p.abs_row -= top + changed = True + kept.append(p) + continue + if p_top >= abs_top + history_advanced and p_bot <= abs_bot: + kept.append(p) + continue + if p_top > abs_bot: + p.abs_row += history_advanced + changed = True + kept.append(p) + continue + inside = ( p_top >= abs_top and p_bot <= abs_bot @@ -810,7 +1142,8 @@ def on_region_scroll( kept.append(p) continue if not inside: - if history_advanced > 0 and p_top >= scrolled_total: + anchored_below = history_advanced > 0 and p_top >= scrolled_total + if anchored_below: p.abs_row += history_advanced changed = True if p.rows * p.cols <= _MAX_MASK_CELLS: @@ -819,8 +1152,12 @@ def on_region_scroll( if p.visible_mask is None else p.visible_mask ) - ir0 = max(p_top, abs_top + history_advanced) - p.abs_row - ir1 = min(p_bot, abs_bot + history_advanced) - p.abs_row + 1 + if history_advanced > 0 and not anchored_below: + ir0 = max(0, abs_bot + 1 - p_top) + ir1 = p.rows + else: + ir0 = max(p_top, abs_top) - p_top + ir1 = min(p_bot, abs_bot) - p_top + 1 ic0 = max(p_left, left) - p_left ic1 = min(p_right, right) - p_left + 1 if ir0 < ir1 and ic0 < ic1: @@ -833,7 +1170,10 @@ def on_region_scroll( continue if mask != prev_mask: p.visible_mask = mask + _trim_masked_sixel_rows(p) changed = True + if p.rows <= 0: + continue kept.append(p) continue @@ -1082,14 +1422,21 @@ def handle_kitty( else scrolled_total ) - if _parse_int(control, "i", 0) > 0 and _parse_int(control, "I", 0) > 0: - self._pending = None - return _kitty_reply( - control, "EINVAL:cannot specify both i and I", is_error=True - ) - if explicit_action == "d": self._pending = None + for id_key in ("i", "I", "p", "P", "Q"): + raw_id = control.get(id_key) + if ( + raw_id is not None + and raw_id != "" + and _parse_ascii_uint(raw_id, max_val=_KITTY_UINT32_MAX) is None + ): + return None + if ( + _parse_uint32(control, "i", 0) > 0 + and _parse_uint32(control, "I", 0) > 0 + ): + return None self._handle_kitty_delete( control, cursor_row=cursor_row, @@ -1099,23 +1446,63 @@ def handle_kitty( ) return None + reply_ctx = control if self._pending is not None: up = self._pending - in_id = _parse_int(control, "i", 0) - up_id = _parse_int(up.control, "i", 0) + raw_in_i = control.get("i") + in_i_valid = ( + _parse_ascii_uint(raw_in_i, max_val=_KITTY_UINT32_MAX) + if (raw_in_i is not None and raw_in_i != "") + else 0 + ) + up_id = _parse_uint32(up.control, "i", 0) stale = ( explicit_action in ("q", "p") or ("t" in control and control.get("t", "d") != "d") - or (in_id > 0 and up_id > 0 and in_id != up_id) + or ( + in_i_valid is not None + and in_i_valid > 0 + and up_id > 0 + and in_i_valid != up_id + ) ) if stale: self._pending = None elif explicit_action in (None, "t", "T"): - if _parse_int(control, "q", 0) >= 1: - up.control["q"] = control["q"] + merged_q = max(_valid_quiet(up.control), _valid_quiet(control)) + merged_ctrl = dict(up.control) for k, v in control.items(): if k not in ("m", "q"): - up.control.setdefault(k, v) + merged_ctrl.setdefault(k, v) + if merged_q > 0: + merged_ctrl["q"] = str(merged_q) + reply_ctx = merged_ctrl + + for id_key in ("i", "I", "p", "P", "Q"): + raw_id = control.get(id_key) + if ( + raw_id is not None + and raw_id != "" + and _parse_ascii_uint(raw_id, max_val=_KITTY_UINT32_MAX) is None + ): + self._pending = None + return _kitty_reply( + reply_ctx, + f"EINVAL:invalid uint32 {id_key}", + is_error=True, + ) + if ( + _parse_uint32(merged_ctrl, "i", 0) > 0 + and _parse_uint32(merged_ctrl, "I", 0) > 0 + ): + self._pending = None + return _kitty_reply( + reply_ctx, + "EINVAL:cannot specify both i and I", + is_error=True, + ) + + up.control = merged_ctrl up.chunks += 1 if up.chunks > _MAX_UPLOAD_CHUNKS: self._pending = None @@ -1140,10 +1527,30 @@ def handle_kitty( advance_cursor=advance_cursor, ) + for id_key in ("i", "I", "p", "P", "Q"): + raw_id = control.get(id_key) + if ( + raw_id is not None + and raw_id != "" + and _parse_ascii_uint(raw_id, max_val=_KITTY_UINT32_MAX) is None + ): + self._pending = None + return _kitty_reply( + reply_ctx, + f"EINVAL:invalid uint32 {id_key}", + is_error=True, + ) + + if _parse_uint32(control, "i", 0) > 0 and _parse_uint32(control, "I", 0) > 0: + self._pending = None + return _kitty_reply( + reply_ctx, "EINVAL:cannot specify both i and I", is_error=True + ) + action = explicit_action or "t" if action in ("t", "T", "q"): - if action == "q" and _parse_int(control, "i", 0) <= 0: - if _parse_int(control, "I", 0) > 0: + if action == "q" and _parse_uint32(control, "i", 0) <= 0: + if _parse_uint32(control, "I", 0) > 0: return _kitty_reply( control, "EINVAL:image ID required for query", is_error=True ) @@ -1153,14 +1560,14 @@ def handle_kitty( self._pending = None return _kitty_reply( control, - f"EINVAL:unsupported transmission medium {medium!r}", + f"EINVAL:unsupported transmission medium {medium!a}", is_error=True, ) comp = control.get("o", "") if comp not in ("", "z"): return _kitty_reply( control, - f"EINVAL:unsupported compression {comp!r}", + f"EINVAL:unsupported compression {comp!a}", is_error=True, ) fmt = _parse_int(control, "f", 32) @@ -1315,11 +1722,19 @@ def _complete_kitty_upload( def _resolve_kitty_image(self, control: dict[str, str]) -> ImageMeta | None: img_id = _parse_int(control, "i", 0) if img_id > 0: - return self._images.get(img_id) + meta = self._images.get(img_id) + return ( + meta + if meta is not None and meta.protocol == GraphicsProtocol.KITTY + else None + ) img_num = _parse_int(control, "I", 0) if img_num > 0: for meta in reversed(self._images.values()): - if meta.image_number == img_num: + if ( + meta.protocol == GraphicsProtocol.KITTY + and meta.image_number == img_num + ): return meta return None @@ -1329,8 +1744,10 @@ def _find_parent_placement( parent_pid: int, ) -> _MutablePlacement | None: for p in reversed(self._placements): - if p.image_id == parent_id and ( - parent_pid == 0 or p.placement_id == parent_pid + if ( + p.protocol == GraphicsProtocol.KITTY + and p.image_id == parent_id + and (parent_pid == 0 or p.placement_id == parent_pid) ): return p return None @@ -1399,7 +1816,8 @@ def _place_kitty_image( parent_pl: _MutablePlacement | None = None if parent_id > 0: - if parent_id not in self._images: + parent_meta = self._images.get(parent_id) + if parent_meta is None or parent_meta.protocol != GraphicsProtocol.KITTY: return _kitty_reply( control, "ENOPARENT:parent image not found", is_error=True ) @@ -1449,7 +1867,9 @@ def _place_kitty_image( cols = min(max(1, screen_cols * 4), cols) rows = min(max(1, self._max_dim), rows) - z_idx = _parse_int(control, "z", 0) + z_idx = max( + _KITTY_INT32_MIN, min(_KITTY_INT32_MAX, _parse_int(control, "z", 0)) + ) move_cursor = ( not virtual and parent_id == 0 and _parse_int(control, "C", 0) == 0 ) @@ -1459,16 +1879,25 @@ def _place_kitty_image( if target_meta is not None else ( meta.image_id - if (_parse_int(control, "i", 0) > 0 or _parse_int(control, "I", 0) > 0) + if ( + _parse_uint32(control, "i", 0) > 0 + or _parse_uint32(control, "I", 0) > 0 + ) else None ) ) if parent_pl is not None: - abs_r = parent_pl.abs_row + _parse_int(control, "V", 0) - col_pos = max( - 0, min(screen_cols - 1, parent_pl.col + _parse_int(control, "H", 0)) + rel_v = max( + -self._max_dim, + min(self._max_dim, _parse_int(control, "V", 0)), + ) + rel_h = max( + -self._max_dim, + min(self._max_dim, _parse_int(control, "H", 0)), ) + abs_r = parent_pl.abs_row + rel_v + col_pos = max(0, min(screen_cols - 1, parent_pl.col + rel_h)) min_abs = 0 else: anchor_r = cursor_row @@ -1482,7 +1911,9 @@ def _place_kitty_image( abs_r = post_scrolled + anchor_r col_pos = cursor_col min_abs = ( - (post_scrolled + min_row) if post_scrolled == scrolled_total else 0 + (post_scrolled + min_row) + if (min_row > 0 or post_scrolled == scrolled_total) + else 0 ) if not virtual and abs_r < min_abs: @@ -1532,7 +1963,8 @@ def _prune_orphans(self, *, free_images: bool = False) -> None: for idx, p in enumerate(self._placements): if p.parent_image_id <= 0: reachable[idx] = True - queue.append(idx) + if not p.virtual: + queue.append(idx) elif p.parent_placement_id > 0: children_by_key.setdefault( (p.parent_image_id, p.parent_placement_id), [] diff --git a/src/libvt/input.py b/src/libvt/input.py index 51d6f96..d80a7e4 100644 --- a/src/libvt/input.py +++ b/src/libvt/input.py @@ -178,10 +178,14 @@ class MouseEvent: Zero-based terminal column. modifiers : KeyMod Active keyboard modifiers during the mouse event. - pixel_x : int - Horizontal pixel coordinate for ``?1016`` SGR-Pixel mode. - pixel_y : int - Vertical pixel coordinate for ``?1016`` SGR-Pixel mode. + pixel_x : int | None + Explicit horizontal pixel coordinate for ``?1016`` SGR-Pixel mode + (clamped to ``>= 0``); ``None`` derives cell-center pixels from + ``col`` and ``cell_width_px``. + pixel_y : int | None + Explicit vertical pixel coordinate for ``?1016`` SGR-Pixel mode + (clamped to ``>= 0``); ``None`` derives cell-center pixels from + ``row`` and ``cell_height_px``. """ button: MouseButton @@ -189,8 +193,8 @@ class MouseEvent: row: int col: int modifiers: KeyMod = KeyMod.NONE - pixel_x: int = 0 - pixel_y: int = 0 + pixel_x: int | None = None + pixel_y: int | None = None @dataclass(frozen=True, slots=True) @@ -227,6 +231,8 @@ class PasteEvent: allow_unbracketed_newlines: bool = False +#: Outbound input event union accepted by :func:`encode_input` and +#: :meth:`~libvt.terminal.Terminal.encode`. type InputEvent = KeyEvent | MouseEvent | FocusEvent | PasteEvent _ARROW_CSI: dict[str, str] = { @@ -330,11 +336,20 @@ def encode_paste( return payload +def _is_ascii_alpha(k: str) -> bool: + return "a" <= k <= "z" or "A" <= k <= "Z" + + +def _has_legacy_c0_mapping(k: str) -> bool: + return _is_ascii_alpha(k) or k in (" ", "@", "[", "\\", "]", "^", "_", "/") + + def _encode_key( event: KeyEvent, *, modes: ModeState, kitty_flags: KittyKeyboardFlags, + modify_other_keys: int = 0, ) -> bytes: report_events = bool(kitty_flags & KittyKeyboardFlags.REPORT_EVENT_TYPES) if event.action == KeyAction.RELEASE and not report_events: @@ -378,6 +393,7 @@ def _encode_key( & (KittyKeyboardFlags.DISAMBIGUATE | KittyKeyboardFlags.REPORT_ALL_KEYS), ) report_all = bool(kitty_flags & KittyKeyboardFlags.REPORT_ALL_KEYS) + use_xtmod = kitty_flags == KittyKeyboardFlags.NONE and modify_other_keys in (1, 2) # Named C0 keys (escape, enter, tab, backspace) if k_low in _KITTY_SPECIAL_CP: @@ -393,6 +409,18 @@ def _encode_key( if mod_param == 1 and not ev_suffix: return f"\x1b[{cp}u".encode("ascii") return f"\x1b[{cp};{mod_param}{ev_suffix}u".encode("ascii") + if ( + use_xtmod + and event.modifiers != KeyMod.NONE + and ( + modify_other_keys == 2 + or not ( + (k_low == "tab" and event.modifiers == KeyMod.SHIFT) + or event.modifiers == KeyMod.ALT + ) + ) + ): + return f"\x1b[27;{mod_param};{cp}~".encode("ascii") if k_low == "tab" and (event.modifiers & KeyMod.SHIFT): return b"\x1b[Z" raw = bytes([cp]) @@ -414,12 +442,33 @@ def _encode_key( return f"\x1b[{base_cp}u".encode("ascii") return f"\x1b[{base_cp};{mp}{ev_suffix}u".encode("ascii") + if use_xtmod and event.modifiers != KeyMod.NONE: + mods = event.modifiers | (KeyMod.SHIFT if "A" <= k <= "Z" else KeyMod.NONE) + cp_out = ord(k.upper()) if ("a" <= k <= "z" and (mods & KeyMod.SHIFT)) else cp + if mods == KeyMod.SHIFT: + if cp_out == 0x20: + return b"\x1b[27;2;32~" + if modify_other_keys == 2 and 0x40 <= cp_out <= 0x7F: + return f"\x1b[27;2;{cp_out}~".encode("ascii") + else: + if modify_other_keys == 2: + return f"\x1b[27;{int(mods) + 1};{cp_out}~".encode("ascii") + legacy_ctrl = mods in (KeyMod.CTRL, KeyMod.CTRL | KeyMod.ALT) and ( + _has_legacy_c0_mapping(k) + ) + legacy_alt = (mods & ~(KeyMod.ALT | KeyMod.SHIFT)) == KeyMod.NONE and bool( + mods & KeyMod.ALT + ) + if not (legacy_ctrl or legacy_alt): + return f"\x1b[27;{int(mods) + 1};{cp_out}~".encode("ascii") + # Legacy xterm key encoding - out_char = k + out_char = ( + k.upper() if ("a" <= k <= "z" and (event.modifiers & KeyMod.SHIFT)) else k + ) if event.modifiers & KeyMod.CTRL: - low_cp = ord(k.lower()) - if 0x61 <= low_cp <= 0x7A: - raw = bytes([low_cp - 0x60]) + if _is_ascii_alpha(k): + raw = bytes([(ord(k) | 0x20) - 0x60]) elif k in (" ", "@"): raw = b"\x00" elif k == "[": @@ -442,13 +491,38 @@ def _encode_key( return raw -def _encode_mouse(event: MouseEvent, *, modes: ModeState) -> bytes: +def _encode_mouse( + event: MouseEvent, + *, + modes: ModeState, + active_is_alt: bool | None = None, + cell_width_px: int = 8, + cell_height_px: int = 16, +) -> bytes: any_event = modes.is_set(Mode.MOUSE_ANY_EVENT) btn_event = modes.is_set(Mode.MOUSE_BUTTON_EVENT) vt200 = modes.is_set(Mode.MOUSE_VT200) x10 = modes.is_set(Mode.MOUSE_X10) if not (any_event or btn_event or vt200 or x10): + eff_alt = ( + bool( + modes.is_set(Mode.ALT_SCREEN) + or modes.is_set(Mode.ALT_SCREEN_1047) + or modes.is_set(Mode.ALT_SCREEN_47) + ) + if active_is_alt is None + else active_is_alt + ) + if ( + eff_alt + and modes.is_set(Mode.ALTERNATE_SCROLL) + and event.action == MouseAction.PRESS + ): + if event.button == MouseButton.WHEEL_UP: + return b"\x1bOA" if modes.is_set(Mode.DECCKM) else b"\x1b[A" + if event.button == MouseButton.WHEEL_DOWN: + return b"\x1bOB" if modes.is_set(Mode.DECCKM) else b"\x1b[B" return b"" if ( event.action == MouseAction.MOVE @@ -474,12 +548,30 @@ def _encode_mouse(event: MouseEvent, *, modes: ModeState) -> bytes: code |= 16 if modes.is_set(Mode.MOUSE_SGR_PIXELS): - final = "m" if event.action == MouseAction.RELEASE else "M" - return f"\x1b[<{code};{event.pixel_x};{event.pixel_y}{final}".encode("ascii") + can_encode_px = (event.pixel_x is not None or cell_width_px > 0) and ( + event.pixel_y is not None or cell_height_px > 0 + ) + if can_encode_px: + cw = max(0, cell_width_px) + ch = max(0, cell_height_px) + px = ( + max(0, event.pixel_x) + if event.pixel_x is not None + else (max(0, event.col) * cw + cw // 2) + ) + py = ( + max(0, event.pixel_y) + if event.pixel_y is not None + else (max(0, event.row) * ch + ch // 2) + ) + final = "m" if event.action == MouseAction.RELEASE else "M" + return f"\x1b[<{code};{px};{py}{final}".encode("ascii") if modes.is_set(Mode.MOUSE_SGR): final = "m" if event.action == MouseAction.RELEASE else "M" - return f"\x1b[<{code};{event.col + 1};{event.row + 1}{final}".encode("ascii") + cx_sgr = max(0, event.col) + 1 + cy_sgr = max(0, event.row) + 1 + return f"\x1b[<{code};{cx_sgr};{cy_sgr}{final}".encode("ascii") # Classic X10 / VT200 byte-encoded coordinates (clamped to 223). wire_btn = 3 if event.action == MouseAction.RELEASE else code @@ -493,12 +585,58 @@ def encode_input( *, modes: ModeState, kitty_flags: KittyKeyboardFlags = KittyKeyboardFlags.NONE, + modify_other_keys: int = 0, + active_is_alt: bool | None = None, + cell_width_px: int = 8, + cell_height_px: int = 16, ) -> bytes: - """Encode *event* into outbound PTY bytes respecting active terminal *modes*.""" + """Encode *event* into outbound PTY bytes respecting active terminal *modes*. + + Parameters + ---------- + event : InputEvent + Keyboard, mouse, focus, or paste event to encode. + modes : ModeState + Active ANSI and DEC private modes. + kitty_flags : KittyKeyboardFlags + Active Kitty ``CSI u`` progressive-enhancement flags; when non-zero, + takes precedence over *modify_other_keys*. + modify_other_keys : int + ``xterm`` ``XTMODKEYS`` ``modifyOtherKeys`` level (``0``, ``1``, or + ``2``). + active_is_alt : bool | None + Whether the alternate screen buffer is active for ``?1007`` + (:attr:`~libvt.modes.Mode.ALTERNATE_SCROLL`). When ``None``, inferred + from ``?47`` / ``?1047`` / ``?1049`` in *modes*. + cell_width_px : int + Cell width in pixels used to derive default ``?1016`` horizontal pixel + coordinates (falls back to ``?1006`` / X10 when ``<= 0`` and + :attr:`MouseEvent.pixel_x` is ``None``). + cell_height_px : int + Cell height in pixels used to derive default ``?1016`` vertical pixel + coordinates (falls back to ``?1006`` / X10 when ``<= 0`` and + :attr:`MouseEvent.pixel_y` is ``None``). + + Returns + ------- + bytes + Encoded VT input sequence (``b""`` when suppressed by active modes). + """ if isinstance(event, KeyEvent): - return _encode_key(event, modes=modes, kitty_flags=kitty_flags) + return _encode_key( + event, + modes=modes, + kitty_flags=kitty_flags, + modify_other_keys=modify_other_keys, + ) if isinstance(event, MouseEvent): - return _encode_mouse(event, modes=modes) + return _encode_mouse( + event, + modes=modes, + active_is_alt=active_is_alt, + cell_width_px=cell_width_px, + cell_height_px=cell_height_px, + ) if isinstance(event, FocusEvent): if not modes.is_set(Mode.FOCUS_EVENT): return b"" diff --git a/src/libvt/modes.py b/src/libvt/modes.py index 6b214a6..722e3c1 100644 --- a/src/libvt/modes.py +++ b/src/libvt/modes.py @@ -2,6 +2,7 @@ from __future__ import annotations +import collections.abc import enum DEC_PRIVATE_MASK = 0x8000 @@ -27,6 +28,7 @@ class Mode(enum.IntEnum): MOUSE_ANY_EVENT = DEC_PRIVATE_MASK | 1003 FOCUS_EVENT = DEC_PRIVATE_MASK | 1004 MOUSE_SGR = DEC_PRIVATE_MASK | 1006 + ALTERNATE_SCROLL = DEC_PRIVATE_MASK | 1007 MOUSE_SGR_PIXELS = DEC_PRIVATE_MASK | 1016 ALT_SCREEN_1047 = DEC_PRIVATE_MASK | 1047 DECSC_1048 = DEC_PRIVATE_MASK | 1048 @@ -67,6 +69,7 @@ class DecrpmValue(enum.IntEnum): { Mode.DECAWM, Mode.DECTCEM, + Mode.ALTERNATE_SCROLL, Mode.GRAPHEME_CLUSTERING, }, ) @@ -77,12 +80,20 @@ class DecrpmValue(enum.IntEnum): class ModeState: """Mutable set of active ANSI and DEC private modes.""" - __slots__ = ("_enabled",) + __slots__ = ("_enabled", "_on_mutate", "_on_set_mode") - def __init__(self, enabled: set[Mode] | None = None) -> None: + def __init__( + self, + enabled: set[Mode] | None = None, + *, + on_mutate: collections.abc.Callable[[], None] | None = None, + on_set_mode: collections.abc.Callable[[Mode, bool], bool] | None = None, + ) -> None: self._enabled: set[Mode] = ( set(_DEFAULT_ENABLED_MODES) if enabled is None else set(enabled) ) + self._on_mutate = on_mutate + self._on_set_mode = on_set_mode def is_set(self, mode: Mode) -> bool: """Return ``True`` when *mode* is enabled.""" @@ -90,6 +101,13 @@ def is_set(self, mode: Mode) -> bool: def set_mode(self, mode: Mode, *, enabled: bool) -> None: """Enable or disable *mode*.""" + if self._on_set_mode is not None and self._on_set_mode(mode, enabled): + return + present = mode in self._enabled + if present == enabled: + return + if self._on_mutate is not None: + self._on_mutate() if enabled: self._enabled.add(mode) else: @@ -106,6 +124,11 @@ def sync_alt_screen( Exiting alternate screen via any of ``?47l``, ``?1047l``, or ``?1049l`` clears all three flags so ``DECRQM`` never reports a stale set bit. """ + target = {entered_via} if active_is_alt else set() + if (self._enabled & ALT_SCREEN_MODES) == target: + return + if self._on_mutate is not None: + self._on_mutate() self._enabled.difference_update(ALT_SCREEN_MODES) if active_is_alt: self._enabled.add(entered_via) @@ -118,6 +141,8 @@ def decrpm( active_is_alt: bool | None = None, ) -> DecrpmValue: """Return the ``DECRPM`` status value for raw mode number *code*.""" + if not (0 <= code < DEC_PRIVATE_MASK): + return DecrpmValue.NOT_RECOGNIZED raw = (DEC_PRIVATE_MASK | code) if private else code if raw not in _RECOGNIZED_MODES: return DecrpmValue.NOT_RECOGNIZED diff --git a/src/libvt/parser.py b/src/libvt/parser.py index d1a48b7..3574a16 100644 --- a/src/libvt/parser.py +++ b/src/libvt/parser.py @@ -40,6 +40,7 @@ _APC_STOP_RE = re.compile(rb"[\x18\x1a\x1b]") _APC_STOP_LATIN1_RE = re.compile(rb"[\x18\x1a\x1b\x80-\x9f]") +#: Wire input byte encoding accepted by :class:`Parser`. type ParserEncoding = t.Literal["utf-8", "latin-1"] @@ -74,6 +75,9 @@ class CsiParams: colon_mask : int Bitmask where bit ``i`` is ``1`` when ``values[i]`` was preceded by ``:`` (an ITU T.416 subparameter of the nearest preceding ``;`` slot). + When parameter slots overflow ``max_csi_params``, bit ``len(values)`` + marks a truncated ``:`` subparameter on ``values[-1]`` and bit + ``len(values) + 1`` marks a ``:`` subparameter in later dropped slots. omitted_mask : int Bitmask where bit ``i`` is ``1`` when slot ``i`` contained no digits. """ @@ -189,7 +193,8 @@ class OscDispatch: Attributes ---------- code : int - Numeric ``OSC`` command identifier (``-1`` when absent or non-numeric). + Numeric ``OSC`` command identifier in ``0..65535`` (``-1`` when absent, + non-ASCII, or above ``65535``). data : bytes Raw payload bytes following the first ``;`` (or the full body when no ``;`` is present). @@ -241,6 +246,7 @@ class ApcDispatch: data: bytes +#: Closed union of parser actions emitted by :meth:`Parser.feed`. type Action = ( Print | Execute @@ -336,54 +342,71 @@ def on_apc(self, data: bytes) -> None: def _parse_csi_param_bytes(raw: bytes, *, max_params: int) -> CsiParams: if not raw: return EMPTY_PARAMS + cap = max(0, max_params) vals: list[int] = [] colon_mask = 0 omitted_mask = 0 cur = 0 has_digit = False is_colon = False + overflow_idx = 0 for b in raw: if 0x30 <= b <= 0x39: cur = min(_PARAM_CLAMP, cur * 10 + (b - 0x30)) has_digit = True elif b in (0x3B, 0x3A): idx = len(vals) - if idx < max_params: + if idx < cap: vals.append(cur) if is_colon: colon_mask |= 1 << idx if not has_digit: omitted_mask |= 1 << idx + else: + if is_colon: + colon_mask |= 1 << (cap if overflow_idx == 0 else cap + 1) + overflow_idx += 1 cur = 0 has_digit = False is_colon = b == 0x3A idx = len(vals) - if idx < max_params: + if idx < cap: vals.append(cur) if is_colon: colon_mask |= 1 << idx if not has_digit: omitted_mask |= 1 << idx + elif is_colon: + colon_mask |= 1 << (cap if overflow_idx == 0 else cap + 1) return CsiParams(tuple(vals), colon_mask, omitted_mask) def _decode_extended_color( sub: tuple[int, ...], - flat_groups: list[tuple[int, ...]], + sub_omit: int, + flat_groups: list[tuple[tuple[int, ...], int]], group_idx: int, ) -> tuple[Color, int]: """Decode ``38`` / ``48`` / ``58`` color group into ``(color, consumed)``.""" if len(sub) >= 2: + if (sub_omit >> 1) & 1: + return None, 1 mode = sub[1] if mode == 5 and len(sub) >= 3: + if (sub_omit >> 2) & 1: + return None, 1 cidx = sub[2] if 0 <= cidx <= 255: return IndexedColor(cidx), 1 return None, 1 if mode == 2: if len(sub) >= 6: + if sub_omit & 0b111000: + return None, 1 r, g, b = sub[3], sub[4], sub[5] elif len(sub) == 5: + if sub_omit & 0b11100: + return None, 1 r, g, b = sub[2], sub[3], sub[4] else: return None, 1 @@ -394,22 +417,47 @@ def _decode_extended_color( if group_idx + 1 >= len(flat_groups): return None, 1 - mode = flat_groups[group_idx + 1][0] + mode = flat_groups[group_idx + 1][0][0] if mode == 5 and group_idx + 2 < len(flat_groups): - cidx = flat_groups[group_idx + 2][0] + cidx = flat_groups[group_idx + 2][0][0] if 0 <= cidx <= 255: return IndexedColor(cidx), 3 return None, 3 if mode == 2 and group_idx + 4 < len(flat_groups): - r = flat_groups[group_idx + 2][0] - g = flat_groups[group_idx + 3][0] - b = flat_groups[group_idx + 4][0] + r = flat_groups[group_idx + 2][0][0] + g = flat_groups[group_idx + 3][0][0] + b = flat_groups[group_idx + 4][0][0] if 0 <= r <= 255 and 0 <= g <= 255 and 0 <= b <= 255: return RgbColor(r, g, b), 5 return None, 5 return None, 2 +def _sgr_groups_with_omitted( + params: CsiParams, +) -> list[tuple[tuple[int, ...], int]]: + """Group ``params`` into ``(subparams, omitted_submask)`` tuples.""" + vals = params.values + if not vals: + return [] + c_mask = params.colon_mask + o_mask = params.omitted_mask + groups: list[tuple[list[int], int]] = [([vals[0]], o_mask & 1)] + for idx in range(1, len(vals)): + is_omit = (o_mask >> idx) & 1 + if (c_mask >> idx) & 1: + cur_list, cur_omit = groups[-1] + sub_pos = len(cur_list) + cur_list.append(vals[idx]) + if is_omit: + groups[-1] = (cur_list, cur_omit | (1 << sub_pos)) + else: + groups.append(([vals[idx]], is_omit)) + if (c_mask >> len(vals)) & 1: + groups.pop() + return [(tuple(g), go) for g, go in groups] + + _UL_MAP: dict[int, UnderlineStyle] = { 0: UnderlineStyle.NONE, 1: UnderlineStyle.SINGLE, @@ -450,13 +498,16 @@ def parse_sgr( strike = current.strikethrough overline = current.overline - groups = params.groups() + groups = _sgr_groups_with_omitted(params) idx = 0 total = len(groups) while idx < total: - grp = groups[idx] + grp, grp_omit = groups[idx] code = grp[0] - if code == 0 and len(grp) == 1: + if len(grp) > 1 and code not in (4, 38, 48, 58): + idx += 1 + continue + if code == 0: fg = None bg = None ul_color = None @@ -476,14 +527,12 @@ def parse_sgr( elif code == 3: italic = True elif code == 4: - sub_ul = grp[1] if len(grp) >= 2 else 1 - underline = _UL_MAP.get(sub_ul, UnderlineStyle.SINGLE) + if len(grp) == 1: + underline = UnderlineStyle.SINGLE + elif len(grp) == 2 and not ((grp_omit >> 1) & 1): + underline = _UL_MAP.get(grp[1], UnderlineStyle.SINGLE) elif code in (5, 6): - if code == 5 and len(grp) == 2 and grp[1] == 3: - # Work around tmux grid_string_cells_code encoding SGR 53 as 5:3m. - overline = True - else: - blink = True + blink = True elif code == 7: reverse = True elif code == 8: @@ -510,7 +559,7 @@ def parse_sgr( elif 30 <= code <= 37: fg = AnsiColor(code - 30) elif code == 38: - parsed_fg, step = _decode_extended_color(grp, groups, idx) + parsed_fg, step = _decode_extended_color(grp, grp_omit, groups, idx) if parsed_fg is not None: fg = parsed_fg idx += step @@ -520,7 +569,7 @@ def parse_sgr( elif 40 <= code <= 47: bg = AnsiColor(code - 40) elif code == 48: - parsed_bg, step = _decode_extended_color(grp, groups, idx) + parsed_bg, step = _decode_extended_color(grp, grp_omit, groups, idx) if parsed_bg is not None: bg = parsed_bg idx += step @@ -532,7 +581,7 @@ def parse_sgr( elif code == 55: overline = False elif code == 58: - parsed_ul, step = _decode_extended_color(grp, groups, idx) + parsed_ul, step = _decode_extended_color(grp, grp_omit, groups, idx) if parsed_ul is not None: ul_color = parsed_ul idx += step @@ -577,6 +626,7 @@ class Parser: "_csi_is_colon", "_csi_memo", "_csi_omitted_mask", + "_csi_overflow_idx", "_csi_prefix", "_csi_vals", "_dcs_final", @@ -623,6 +673,7 @@ def __init__( self._csi_vals: list[int] = [] self._csi_colon_mask: int = 0 self._csi_omitted_mask: int = 0 + self._csi_overflow_idx: int = 0 self._csi_cur: int = 0 self._csi_has_digit: bool = False self._csi_is_colon: bool = False @@ -664,6 +715,7 @@ def _reset_csi(self) -> None: self._csi_vals.clear() self._csi_colon_mask = 0 self._csi_omitted_mask = 0 + self._csi_overflow_idx: int = 0 self._csi_cur = 0 self._csi_has_digit = False self._csi_is_colon = False @@ -678,13 +730,20 @@ def _abort_string(self) -> None: self._reset_csi() def _push_param(self, *, next_is_colon: bool) -> None: + cap = max(0, self._limits.max_csi_params) idx = len(self._csi_vals) - if idx < self._limits.max_csi_params: + if idx < cap: self._csi_vals.append(self._csi_cur) if self._csi_is_colon: self._csi_colon_mask |= 1 << idx if not self._csi_has_digit: self._csi_omitted_mask |= 1 << idx + else: + if self._csi_is_colon: + self._csi_colon_mask |= 1 << ( + cap if self._csi_overflow_idx == 0 else cap + 1 + ) + self._csi_overflow_idx += 1 self._csi_cur = 0 self._csi_has_digit = False self._csi_is_colon = next_is_colon @@ -729,12 +788,9 @@ def _dispatch_osc(self, sink: ActionSink, terminator: bytes) -> None: self._abort_string() semi = raw.find(b";") if semi == -1: - code = int(raw) if raw.isdigit() else -1 - sink.on_osc(code, b"", terminator) + sink.on_osc(_parse_osc_code(raw), b"", terminator) else: - head = raw[:semi] - code = int(head) if head.isdigit() else -1 - sink.on_osc(code, raw[semi + 1 :], terminator) + sink.on_osc(_parse_osc_code(raw[:semi]), raw[semi + 1 :], terminator) def _dispatch_dcs(self, sink: ActionSink) -> None: if not self._str_overflow: @@ -879,7 +935,7 @@ def feed_to(self, data: collections.abc.Buffer, sink: ActionSink) -> None: self._intermediates.clear() self._state = ParserState.ESCAPE elif b == 0x7F: - pass + self._flush_incomplete_utf8(sink) else: self._flush_incomplete_utf8(sink) sink.on_execute(b) @@ -1189,6 +1245,71 @@ def feed_to(self, data: collections.abc.Buffer, sink: ActionSink) -> None: self._state = ParserState.DCS_IGNORE +def _parse_osc_code(buf: bytes) -> int: + """Parse ASCII digits ``0x30..0x39`` into ``0..65535``, or ``-1``.""" + if not buf: + return -1 + acc = 0 + for b in buf: + if not (0x30 <= b <= 0x39): + return -1 + acc = acc * 10 + (b - 0x30) + if acc > 65_535: + return -1 + return acc + + +def _parse_ascii_uint(raw: str, *, max_val: int) -> int | None: + """Parse non-empty ASCII digits ``0..9`` up to *max_val*, else ``None``.""" + if not raw: + return None + acc = 0 + for ch in raw: + code = ord(ch) + if not (0x30 <= code <= 0x39): + return None + acc = acc * 10 + (code - 0x30) + if acc > max_val: + return None + return acc + + +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: + return None + neg = False + start = 0 + first = raw[0] + if first == "-": + neg = True + start = 1 + elif first == "+": + start = 1 + if start >= len(raw): + return None + acc = 0 + if neg: + limit = -min_val + for idx in range(start, len(raw)): + code = ord(raw[idx]) + if not (0x30 <= code <= 0x39): + return None + acc = acc * 10 + (code - 0x30) + if acc > limit: + return None + val = -acc + return val if val <= max_val else None + for idx in range(start, len(raw)): + code = ord(raw[idx]) + if not (0x30 <= code <= 0x39): + return None + acc = acc * 10 + (code - 0x30) + if acc > max_val: + return None + return acc if acc >= min_val else None + + __all__ = [ "EMPTY_PARAMS", "Action", diff --git a/src/libvt/pytest_plugin.py b/src/libvt/pytest_plugin.py index 525943e..6b4abb9 100644 --- a/src/libvt/pytest_plugin.py +++ b/src/libvt/pytest_plugin.py @@ -55,6 +55,8 @@ def __call__( policy: Policy = ..., limits: Limits = ..., sync_timeout: float = 1.0, + write_high_water: int | None = None, + max_write_buffer: int = 16_777_216, ) -> contextlib.AbstractAsyncContextManager[PtySession]: """Open a POSIX PTY subprocess session.""" @@ -143,6 +145,8 @@ def _spawn( policy: Policy = DEFAULT_POLICY, limits: Limits = DEFAULT_LIMITS, sync_timeout: float = 1.0, + write_high_water: int | None = None, + max_write_buffer: int = 16_777_216, ) -> contextlib.AbstractAsyncContextManager[PtySession]: return open_pty( argv, @@ -157,6 +161,8 @@ def _spawn( policy=policy, limits=limits, sync_timeout=sync_timeout, + write_high_water=write_high_water, + max_write_buffer=max_write_buffer, ) return _spawn diff --git a/src/libvt/screen.py b/src/libvt/screen.py index 2d2b579..d6fea62 100644 --- a/src/libvt/screen.py +++ b/src/libvt/screen.py @@ -12,14 +12,14 @@ from libvt._grid import ( _EMPTY_FROZEN_HISTORY, - _WIDTH_CLEAR_MASK, + _PEN_BASE_MASK, FrozenRow, RowLike, _CellExt, _FrozenHistory, _HistoryBuffer, _Row, - bump_row_gen, + _RowGenCounter, raw_width_bits, unpack_style, unpack_width_role, @@ -165,7 +165,7 @@ class RowRun: def _materialize_cell(row: RowLike, col: int) -> Cell: - ch = row.chars[col] if isinstance(row, _Row) else row.char_at(col) + ch = row.char_at(col) word = row.attr_at(col) if word == 0 and ch == " ": return BLANK_CELL @@ -355,11 +355,7 @@ def __init__( self._row = row self._screen = screen self._row_idx = row_idx - total_cols = ( - screen.cols - if screen is not None - else (len(row.chars) if isinstance(row, _Row) else row.cols) - ) + total_cols = screen.cols if screen is not None else row.cols self._col_range = range(total_cols) if col_range is None else col_range def _current_row(self) -> RowLike: @@ -376,19 +372,18 @@ def wrapped(self) -> bool: def text(self) -> str: """Return right-trimmed rendered text for this row slice.""" row = self._current_row() - total_cols = len(row.chars) if isinstance(row, _Row) else row.cols - if self._col_range.start == 0 and self._col_range.stop == total_cols: - return row.rstrip_text() row_t_used = ( row.text_used if isinstance(row, _Row) else (len(row.cells) if row.cells is not None else len(row.text)) ) + if self._col_range.start == 0 and self._col_range.stop >= row_t_used: + return row.rstrip_text() limit = min(self._col_range.stop, row_t_used) if limit <= self._col_range.start: return "" if isinstance(row, _Row): - raw = "".join(row.chars[self._col_range.start : limit]) + raw = row.slice_text(self._col_range.start, limit) else: raw = "".join(row.char_at(c) for c in range(self._col_range.start, limit)) return raw.rstrip(" ") @@ -418,7 +413,7 @@ def runs(self) -> tuple[RowRun, ...]: ext = row.ext_at(c) st = unpack_style(word, ext) lnk = ext.hyperlink if ext is not None else None - ch = row.chars[c] if isinstance(row, _Row) else row.char_at(c) + ch = row.char_at(c) if st != cur_style or lnk != cur_link: out.append( RowRun( @@ -484,45 +479,73 @@ def __eq__(self, other: object) -> bool: r2 = other._current_row() if r1 is r2 and self._col_range == other._col_range: return True - c1 = len(r1.chars) if isinstance(r1, _Row) else r1.cols - c2 = len(r2.chars) if isinstance(r2, _Row) else r2.cols if ( - self._col_range.start == 0 - and self._col_range.stop == c1 - and other._col_range.start == 0 - and other._col_range.stop == c2 + self._col_range == other._col_range + and self._col_range.start == 0 + and self._col_range.step == 1 ): f1 = r1.freeze() if isinstance(r1, _Row) else r1 f2 = r2.freeze() if isinstance(r2, _Row) else r2 - return f1 == f2 + if self._col_range.stop >= max(f1.used, f2.used): + return _frozen_content_key(f1) == _frozen_content_key(f2) if r1.wrapped != r2.wrapped: return False return all(a == b for a, b in zip(self, other, strict=True)) -def _row_view_to_full_frozen(value: object) -> FrozenRow | None: +def _frozen_content_key( + fr: FrozenRow, +) -> tuple[ + bool, + str, + tuple[tuple[int, int], ...], + tuple[tuple[int, _CellExt], ...], + tuple[str, ...] | None, +]: + return ( + fr.wrapped, + fr.text, + fr.runs, + fr.exts, + fr.cells, + ) + + +def _row_view_to_full_frozen(value: object) -> tuple[int, FrozenRow] | None: if not isinstance(value, RowView): return None r = value._current_row() - cols = len(r.chars) if isinstance(r, _Row) else r.cols - if value._col_range.start == 0 and value._col_range.stop == cols: - return r.freeze() if isinstance(r, _Row) else r + fr = r.freeze() if isinstance(r, _Row) else r + v_cols = len(value._col_range) + if value._col_range.start == 0 and value._col_range.step == 1 and v_cols >= fr.used: + return v_cols, fr return None class _HistoryView(collections.abc.Sequence[RowView]): """Lazy ``O(1)`` immutable sequence view over scrollback :class:`RowView` lines.""" - __slots__ = ("_data", "_range") + __slots__ = ("_cols", "_data", "_range") def __init__( self, data: _FrozenHistory | None = None, index_range: range | None = None, + *, + cols: int | None = None, ) -> None: eff = _EMPTY_FROZEN_HISTORY if data is None else data self._data = eff self._range = range(len(eff)) if index_range is None else index_range + self._cols = cols + + def _eff_cols(self, fr: FrozenRow) -> int: + if self._cols is None: + return fr.cols + return max(self._cols, fr.used) + + def _wrap_row(self, fr: FrozenRow) -> RowView: + return RowView(fr, range(self._eff_cols(fr))) def __len__(self) -> int: """Return number of scrollback rows in this view.""" @@ -541,34 +564,65 @@ def __getitem__(self, index: slice) -> _HistoryView: ... def __getitem__(self, index: int | slice) -> RowView | _HistoryView: """Index one :class:`RowView` in ``O(1)`` or slice a sub-view.""" if isinstance(index, slice): - return _HistoryView(self._data, self._range[index]) + return _HistoryView(self._data, self._range[index], cols=self._cols) if isinstance(index, bool) or not isinstance(index, int): msg = f"history indices must be int or slice, got {type(index).__name__}" raise TypeError(msg) - return RowView(self._data.at(self._range[index])) + return self._wrap_row(self._data.at(self._range[index])) def __contains__(self, value: object) -> bool: """Return ``True`` when *value* matches a scrollback :class:`RowView`.""" if not isinstance(value, RowView): return False - target_fr = _row_view_to_full_frozen(value) - if target_fr is not None: - r = self._range - if r.start == 0 and r.stop == len(self._data) and r.step == 1: - return any(fr == target_fr for fr in self._data) + v_len = len(value) + if self._cols is not None and v_len < self._cols: + return False + full = _row_view_to_full_frozen(value) + r = self._range + if full is None: at = self._data.at - return any(at(idx) == target_fr for idx in r) - return any(item == value for item in self) + return any( + self._eff_cols(fr := at(idx)) == v_len and self._wrap_row(fr) == value + for idx in r + ) + v_cols, target_fr = full + target_key = _frozen_content_key(target_fr) + if r.start == 0 and r.stop == len(self._data) and r.step == 1: + return any( + self._eff_cols(fr) == v_cols and _frozen_content_key(fr) == target_key + for fr in self._data + ) + at = self._data.at + return any( + self._eff_cols(fr := at(idx)) == v_cols + and _frozen_content_key(fr) == target_key + for idx in r + ) def count(self, value: object) -> int: """Return count of scrollback rows equal to *value*.""" if not isinstance(value, RowView): return 0 - target_fr = _row_view_to_full_frozen(value) - if target_fr is not None: - at = self._data.at - return sum(1 for idx in self._range if at(idx) == target_fr) - return sum(1 for item in self if item == value) + v_len = len(value) + if self._cols is not None and v_len < self._cols: + return 0 + full = _row_view_to_full_frozen(value) + at = self._data.at + if full is None: + return sum( + 1 + for idx in self._range + if self._eff_cols(fr := at(idx)) == v_len + and self._wrap_row(fr) == value + ) + v_cols, target_fr = full + target_key = _frozen_content_key(target_fr) + return sum( + 1 + for idx in self._range + if self._eff_cols(fr := at(idx)) == v_cols + and _frozen_content_key(fr) == target_key + ) def index( self, @@ -578,17 +632,26 @@ def index( ) -> int: """Return first zero-based index of *value* in ``[start, stop)``.""" if isinstance(value, RowView): - sub_indices = range(len(self._range))[start:stop] - target_fr = _row_view_to_full_frozen(value) - at = self._data.at - if target_fr is not None: - for pos in sub_indices: - if at(self._range[pos]) == target_fr: - return pos - else: - for pos in sub_indices: - if RowView(at(self._range[pos])) == value: - return pos + v_len = len(value) + if self._cols is None or v_len >= self._cols: + sub_indices = range(len(self._range))[start:stop] + full = _row_view_to_full_frozen(value) + at = self._data.at + if full is None: + for pos in sub_indices: + fr = at(self._range[pos]) + if self._eff_cols(fr) == v_len and self._wrap_row(fr) == value: + return pos + else: + v_cols, target_fr = full + target_key = _frozen_content_key(target_fr) + for pos in sub_indices: + fr = at(self._range[pos]) + if ( + self._eff_cols(fr) == v_cols + and _frozen_content_key(fr) == target_key + ): + return pos msg = "RowView is not in history" raise ValueError(msg) @@ -599,30 +662,38 @@ def __iter__(self) -> collections.abc.Iterator[RowView]: return if r.start == 0 and r.stop == len(self._data) and r.step == 1: for fr in self._data: - yield RowView(fr) + yield self._wrap_row(fr) return at = self._data.at for idx in r: - yield RowView(at(idx)) + yield self._wrap_row(at(idx)) def __reversed__(self) -> collections.abc.Iterator[RowView]: """Yield :class:`RowView` items in reverse order.""" at = self._data.at for idx in reversed(self._range): - yield RowView(at(idx)) + yield self._wrap_row(at(idx)) def __eq__(self, other: object) -> bool: - """Compare two :class:`_HistoryView` instances by underlying frozen rows.""" + """Compare two :class:`_HistoryView` instances by view-width rows.""" if self is other: return True if not isinstance(other, _HistoryView): return NotImplemented if len(self._range) != len(other._range): return False - if self._data is other._data and self._range == other._range: + if not self._range: + return True + if ( + self._data is other._data + and self._range == other._range + and self._cols == other._cols + ): return True return all( - self._data.at(i) == other._data.at(j) + self._eff_cols(f1 := self._data.at(i)) + == other._eff_cols(f2 := other._data.at(j)) + and _frozen_content_key(f1) == _frozen_content_key(f2) for i, j in zip(self._range, other._range, strict=True) ) @@ -752,6 +823,7 @@ class Screen: "_cur_shape", "_cur_visible", "_evicted_total", + "_gen_counter", "_gfx", "_history", "_history_clear_at", @@ -760,11 +832,14 @@ class Screen: "_max_image_dimension", "_max_images", "_max_placements", + "_modify_other_keys", + "_on_mutate", "_pending_wrap", "_rows", "_scrolled_total", "_tabstops", "_tabstops_sorted", + "_top_margin_scrolls_to_history", "keyboard_stack", "scroll_region", ) @@ -781,18 +856,27 @@ def __init__( max_placements: int = 1_024, max_image_dimension: int = 10_000, is_alt: bool = False, + top_margin_scrolls_to_history: bool = False, + on_mutate: collections.abc.Callable[[bool], None] | None = None, ) -> None: if rows < 1 or cols < 1: msg = f"rows and cols must be >= 1, got ({rows}, {cols})" raise ValueError(msg) self._cols = cols - self._rows: list[_Row] = [_Row(cols) for _ in range(rows)] + self._gen_counter: _RowGenCounter = _RowGenCounter() + self._on_mutate = on_mutate + self._rows: list[_Row] = [ + _Row(cols, gen_counter=self._gen_counter) for _ in range(rows) + ] self._history: _HistoryBuffer = _HistoryBuffer(maxlen=max(0, scrollback)) self._scrolled_total: int = 0 self._evicted_total: int = 0 self._history_clear_at: int = 0 self._history_clear_seq: int = 0 self._is_alt: bool = is_alt + self._top_margin_scrolls_to_history: bool = ( + top_margin_scrolls_to_history and not is_alt + ) self._cell_height_px: int = max(1, cell_height_px) self._max_images: int = max_images self._max_placements: int = max_placements @@ -813,6 +897,12 @@ def __init__( self._tabstops: set[int] = set(range(8, cols, 8)) self._tabstops_sorted: list[int] = sorted(self._tabstops) self.keyboard_stack = KittyKeyboardStack(max_depth=keyboard_stack_depth) + self._modify_other_keys: int = 0 + + def _bind_counter(self, counter: _RowGenCounter) -> None: + self._gen_counter = counter + for r in self._rows: + r.bind_counter(counter, stamp=False) @property def rows(self) -> int: @@ -843,6 +933,8 @@ def cursor(self) -> Cursor: @cursor.setter def cursor(self, value: Cursor) -> None: + if self._on_mutate is not None: + self._on_mutate(False) self._cur_row = value.row self._cur_col = value.col self._cur_visible = value.visible @@ -853,13 +945,18 @@ def cursor(self, value: Cursor) -> None: @property def history(self) -> collections.abc.Sequence[RowView]: """Return ``O(1)`` immutable :class:`RowView` sequence over scrollback.""" - return _HistoryView(self._history.freeze()) + return _HistoryView(self._history.freeze(), cols=self._cols) @property def tabstops(self) -> tuple[int, ...]: """Return sorted horizontal tabstop columns.""" return tuple(self._tabstops_sorted) + @property + def modify_other_keys(self) -> int: + """Return ``XTMODKEYS`` ``modifyOtherKeys`` level (``0``, ``1``, or ``2``).""" + return self._modify_other_keys + def add_tabstop(self, col: int) -> None: """Set a horizontal tabstop at *col* (``HTS``).""" if 0 <= col < self._cols and col not in self._tabstops: @@ -879,6 +976,8 @@ def clear_all_tabstops(self) -> None: def clear_history(self) -> None: """Clear all sealed scrollback rows (``ED 3``).""" + if self._on_mutate is not None: + self._on_mutate(False) self._evicted_total += len(self._history) self._history.clear() self._history_clear_at = self._scrolled_total @@ -913,31 +1012,9 @@ def _append_history(self, frozen: FrozenRow) -> None: self._evicted_total += 1 def _clear_row_spacer_head(self, row_obj: _Row) -> bool: - if not row_obj.has_wide or row_obj.attrs is None: + if self._cols <= 0: return False - last = self._cols - 1 - if raw_width_bits(row_obj.attrs[last]) == int(WidthRole.SPACER_HEAD): - row_obj.chars[last] = " " - row_obj.attrs[last] &= _WIDTH_CLEAR_MASK - if row_obj.text_used == last + 1: - row_obj.text_used = last - while ( - row_obj.text_used > 0 - and row_obj.chars[row_obj.text_used - 1] == " " - and row_obj.attr_at(row_obj.text_used - 1) == 0 - and row_obj.ext_at(row_obj.text_used - 1) is None - ): - row_obj.text_used -= 1 - while ( - row_obj.used > 0 - and row_obj.chars[row_obj.used - 1] == " " - and row_obj.attr_at(row_obj.used - 1) == 0 - and row_obj.ext_at(row_obj.used - 1) is None - ): - row_obj.used -= 1 - bump_row_gen(row_obj) - return True - return False + return row_obj.clear_spacer_head(self._cols - 1) def heal_before_edit(self, row: int, col_start: int, col_end: int) -> None: """Repair cross-row ``SPACER_HEAD`` pairs before mutating cells.""" @@ -960,7 +1037,7 @@ def heal_wrapped_spacer_head(self, row: int) -> None: if row <= 0 or row > len(self._rows): return prev = self._rows[row - 1] - if not prev.has_wide or prev.attrs is None: + if not prev.has_wide: return if row == len(self._rows) or not prev.wrapped: if self._clear_row_spacer_head(prev): @@ -1017,7 +1094,6 @@ def scroll_up( right: int | None = None, save_history: bool = True, bce_word: int = 0, - bce_ext: _CellExt | None = None, is_line_op: bool = False, ) -> None: """Scroll region ``[top..bottom, left..right]`` upward by *count* lines.""" @@ -1026,22 +1102,25 @@ def scroll_up( r_col = (self._cols - 1) if right is None else right if count <= 0 or t_row > b_row: return + if self._on_mutate is not None: + self._on_mutate(False) shift = min(count, b_row - t_row + 1) full_width = left == 0 and r_col == self._cols - 1 full_screen = full_width and t_row == 0 and b_row == len(self._rows) - 1 if full_width: if t_row > 0: - if self._rows[t_row - 1].wrapped: - self._rows[t_row - 1].wrapped = False - bump_row_gen(self._rows[t_row - 1]) + self._rows[t_row - 1].wrapped = False self._clear_row_spacer_head(self._rows[t_row - 1]) if b_row < len(self._rows) - 1: - if self._rows[b_row].wrapped: - self._rows[b_row].wrapped = False - bump_row_gen(self._rows[b_row]) + self._rows[b_row].wrapped = False self._clear_row_spacer_head(self._rows[b_row]) - advances_abs = save_history and t_row == 0 and not self._is_alt + advances_abs = ( + save_history + and not self._is_alt + and (t_row == 0 or self._top_margin_scrolls_to_history) + ) + eff_count = count if full_screen else shift has_hist_cap = self._history.maxlen is not None and self._history.maxlen > 0 hist_adv = shift if (advances_abs and not full_screen) else 0 if self._gfx is not None and not (full_screen and advances_abs): @@ -1050,24 +1129,25 @@ def scroll_up( bottom=b_row, left=left, right=r_col, - delta_rows=-count, + delta_rows=-eff_count, is_scroll=not is_line_op, scrolled_total=self._scrolled_total, cell_height_px=self._cell_height_px, - history_advanced=( - count if (advances_abs and not full_screen) else 0 - ), + history_advanced=hist_adv, ) evicted = self._rows[t_row : t_row + shift] if advances_abs: + if t_row > 0 and evicted: + evicted[-1].wrapped = False + self._clear_row_spacer_head(evicted[-1]) if has_hist_cap: for row_ev in evicted: self._append_history(row_ev.freeze()) - extra = count - shift + extra = eff_count - shift if extra > 0: maxlen = self._history.maxlen or 0 blank_row = _Row(self._cols) - blank_row.reset_blank(self._cols, bce_word, bce_ext) + blank_row.reset_blank(self._cols, bce_word) blank_frozen = blank_row.freeze() skip_evict = max(0, extra - maxlen) if skip_evict > 0: @@ -1076,20 +1156,21 @@ def scroll_up( for _ in range(extra - skip_evict): self._append_history(blank_frozen) else: - self._evicted_total += count - self._scrolled_total += count + self._evicted_total += eff_count + self._scrolled_total += eff_count if self._gfx is not None: self._gfx.reap_evicted_history( self._scrolled_total - len(self._history), ) del self._rows[t_row : t_row + shift] for row_ev in evicted: - row_ev.reset_blank(self._cols, bce_word, bce_ext) + row_ev.reset_blank(self._cols, bce_word) self._rows[b_row - shift + 1 : b_row - shift + 1] = evicted if not (full_screen and advances_abs): + stamp_start = 0 if hist_adv > 0 else t_row stamp_end = len(self._rows) if hist_adv > 0 else (b_row + 1) - for idx_s in range(t_row, stamp_end): - bump_row_gen(self._rows[idx_s]) + for idx_s in range(stamp_start, stamp_end): + self._rows[idx_s].stamp() return if self._gfx is not None: @@ -1108,26 +1189,24 @@ def scroll_up( dst_row = self._rows[dst_r] dst_row.wrapped = False self._clear_row_spacer_head(dst_row) - if dst_r > 0 and left <= 1: - self._clear_row_spacer_head(self._rows[dst_r - 1]) - dst_row._heal_wide_boundary(left) - dst_row._heal_wide_boundary(r_col) - src_row._heal_wide_boundary(left) - src_row._heal_wide_boundary(r_col) - for c in range(left, r_col + 1): - word = src_row.attr_at(c) - role = unpack_width_role(word) - base = word & _WIDTH_CLEAR_MASK - dst_row._set_raw(c, src_row.chars[c], base, role, src_row.ext_at(c)) - _sync_partial_scroll_bounds(dst_row, src_row, left, r_col) - bump_row_gen(dst_row) + if ( + dst_r > 0 + and left <= 1 + and self._clear_row_spacer_head(self._rows[dst_r - 1]) + ): + self._rows[dst_r - 1].wrapped = False + dst_row.copy_region_from(src_row, left, r_col) for clr_r in range(b_row - shift + 1, b_row + 1): self._rows[clr_r].wrapped = False self._clear_row_spacer_head(self._rows[clr_r]) - if clr_r > 0 and left <= 1: - self._clear_row_spacer_head(self._rows[clr_r - 1]) - self._rows[clr_r].clear_range(left, r_col + 1, bce_word, bce_ext) + if ( + clr_r > 0 + and left <= 1 + and self._clear_row_spacer_head(self._rows[clr_r - 1]) + ): + self._rows[clr_r - 1].wrapped = False + self._rows[clr_r].clear_range(left, r_col + 1, bce_word, None) def scroll_down( self, @@ -1138,7 +1217,6 @@ def scroll_down( left: int = 0, right: int | None = None, bce_word: int = 0, - bce_ext: _CellExt | None = None, is_line_op: bool = False, ) -> None: """Scroll region ``[top..bottom, left..right]`` downward by *count* lines.""" @@ -1147,6 +1225,8 @@ def scroll_down( r_col = (self._cols - 1) if right is None else right if count <= 0 or t_row > b_row: return + if self._on_mutate is not None: + self._on_mutate(False) shift = min(count, b_row - t_row + 1) full_width = left == 0 and r_col == self._cols - 1 @@ -1164,22 +1244,17 @@ def scroll_down( if full_width: if t_row > 0: - if self._rows[t_row - 1].wrapped: - self._rows[t_row - 1].wrapped = False - bump_row_gen(self._rows[t_row - 1]) + self._rows[t_row - 1].wrapped = False self._clear_row_spacer_head(self._rows[t_row - 1]) recycled = self._rows[b_row - shift + 1 : b_row + 1] del self._rows[b_row - shift + 1 : b_row + 1] for row_ev in recycled: - row_ev.reset_blank(self._cols, bce_word, bce_ext) + row_ev.reset_blank(self._cols, bce_word) self._rows[t_row:t_row] = recycled - if b_row < len(self._rows) - 1: - if self._rows[b_row].wrapped: - self._rows[b_row].wrapped = False - bump_row_gen(self._rows[b_row]) - self._clear_row_spacer_head(self._rows[b_row]) + self._rows[b_row].wrapped = False + self._clear_row_spacer_head(self._rows[b_row]) for idx_s in range(t_row, b_row + 1): - bump_row_gen(self._rows[idx_s]) + self._rows[idx_s].stamp() return for dst_r in range(b_row, t_row + shift - 1, -1): @@ -1187,35 +1262,34 @@ def scroll_down( dst_row = self._rows[dst_r] dst_row.wrapped = False self._clear_row_spacer_head(dst_row) - if dst_r > 0 and left <= 1: - self._clear_row_spacer_head(self._rows[dst_r - 1]) - dst_row._heal_wide_boundary(left) - dst_row._heal_wide_boundary(r_col) - src_row._heal_wide_boundary(left) - src_row._heal_wide_boundary(r_col) - for c in range(left, r_col + 1): - word = src_row.attr_at(c) - role = unpack_width_role(word) - base = word & _WIDTH_CLEAR_MASK - dst_row._set_raw(c, src_row.chars[c], base, role, src_row.ext_at(c)) - _sync_partial_scroll_bounds(dst_row, src_row, left, r_col) - bump_row_gen(dst_row) + if ( + dst_r > 0 + and left <= 1 + and self._clear_row_spacer_head(self._rows[dst_r - 1]) + ): + self._rows[dst_r - 1].wrapped = False + dst_row.copy_region_from(src_row, left, r_col) for clr_r in range(t_row, t_row + shift): self._rows[clr_r].wrapped = False self._clear_row_spacer_head(self._rows[clr_r]) - if clr_r > 0 and left <= 1: - self._clear_row_spacer_head(self._rows[clr_r - 1]) - self._rows[clr_r].clear_range(left, r_col + 1, bce_word, bce_ext) + if ( + clr_r > 0 + and left <= 1 + and self._clear_row_spacer_head(self._rows[clr_r - 1]) + ): + self._rows[clr_r - 1].wrapped = False + self._rows[clr_r].clear_range(left, r_col + 1, bce_word, None) def push_scrollback_and_clear( self, bce_word: int = 0, - bce_ext: _CellExt | None = None, *, include_cursor_row: bool = True, ) -> None: """Push active lines up to last non-blank row into history.""" + if self._on_mutate is not None: + self._on_mutate(False) last_used = -1 for idx in range(len(self._rows) - 1, -1, -1): has_img = self._gfx is not None and self._gfx.has_placement_on_row( @@ -1230,6 +1304,8 @@ def push_scrollback_and_clear( last_used = idx break if last_used >= 0 and not self._is_alt: + self._rows[last_used].wrapped = False + self._clear_row_spacer_head(self._rows[last_used]) if self._history.maxlen is not None and self._history.maxlen > 0: for idx in range(last_used + 1): self._append_history(self._rows[idx].freeze()) @@ -1243,75 +1319,176 @@ def push_scrollback_and_clear( elif self._gfx is not None: self._gfx.clear_active_screen(self._scrolled_total, len(self._rows)) for r in self._rows: - r.reset_blank(self._cols, bce_word, bce_ext) + r.reset_blank(self._cols, bce_word) - def _reflow_primary(self, *, rows: int, cols: int) -> None: - hist_thawed = [fr.thaw() for fr in self._history] - hist_len = len(hist_thawed) + def _reflow_primary( + self, + *, + rows: int, + cols: int, + extra_pins: collections.abc.Sequence[tuple[int, int]] = (), + ) -> tuple[tuple[int, int], ...]: + hist_rows = list(self._history.freeze()) + hist_len = len(hist_rows) + old_first_abs = self._scrolled_total - hist_len - # Trim trailing unwritten blank rows strictly below the cursor. last_active = self._cur_row for r_idx in range(len(self._rows) - 1, self._cur_row, -1): if self._rows[r_idx].used > 0 or self._rows[r_idx].wrapped: last_active = r_idx break - combined = hist_thawed + self._rows[: last_active + 1] + total = hist_len + last_active + 1 cur_abs_idx = hist_len + self._cur_row eff_cur_col = self._cur_col + (1 if self._pending_wrap else 0) - new_all: list[_Row] = [] + gfx_roots = self._gfx.root_placement_pins() if self._gfx is not None else [] + n_extra = len(extra_pins) + all_pins: list[tuple[int, int]] = list(extra_pins) + for _, g_abs, g_col in gfx_roots: + all_pins.append((g_abs, g_col)) + + mapped_out: list[tuple[int, int] | None] = [None] * len(all_pins) + pins_by_row: dict[int, list[tuple[int, int]]] = {} + for p_idx, (p_abs, p_col) in enumerate(all_pins): + rel_in = p_abs - old_first_abs + if 0 <= rel_in < total: + pins_by_row.setdefault(rel_in, []).append((p_idx, p_col)) + + new_all: list[RowLike] = [] new_cur_abs = 0 new_cur_col = 0 new_pending_wrap = False cursor_placed = False idx = 0 - total = len(combined) while idx < total: + if idx < hist_len: + fr = hist_rows[idx] + if not fr.wrapped: + fr_t_cols = len(fr.cells) if fr.cells is not None else len(fr.text) + fr_used = ( + fr_t_cols + if (not fr.runs and not fr.exts) + else max( + fr_t_cols, + fr.runs[-1][0] if fr.runs else 0, + (fr.exts[-1][0] + 1) if fr.exts else 0, + ) + ) + if fr_used <= cols: + out_idx = len(new_all) + new_all.append(fr) + if pins_by_row: + row_ps = pins_by_row.get(idx) + if row_ps is not None: + for p_idx, p_col in row_ps: + mapped_out[p_idx] = ( + out_idx, + min(cols - 1, max(0, p_col)), + ) + idx += 1 + continue + group_start = idx - while idx + 1 < total and combined[idx].wrapped: + while idx + 1 < total: + cur_src = ( + hist_rows[idx] if idx < hist_len else self._rows[idx - hist_len] + ) + if not cur_src.wrapped: + break idx += 1 group_end = idx idx += 1 - if group_start <= cur_abs_idx < group_end and eff_cur_col >= len( - combined[cur_abs_idx].chars - ): - cur_abs_idx += 1 - eff_cur_col = 0 + if group_start <= cur_abs_idx < group_end: + cur_r_src = ( + hist_rows[cur_abs_idx] + if cur_abs_idx < hist_len + else self._rows[cur_abs_idx - hist_len] + ) + cur_r_cols = cur_r_src.cols + if eff_cur_col >= cur_r_cols: + cur_abs_idx += 1 + eff_cur_col = 0 - # Extract real logical cells across [group_start .. group_end]. cells: list[tuple[str, int, int, _CellExt | None, int]] = [] + cell_pins: dict[int, list[tuple[int, int]]] = {} + carried_pins: list[int] = [] + after_group_pins: list[tuple[int, int]] = [] cur_after_extra: int | None = None carry_cur = False + for r_i in range(group_start, group_end + 1): - src = combined[r_i] + src = hist_rows[r_i] if r_i < hist_len else self._rows[r_i - hist_len] is_last = r_i == group_end - src_t_used = src.text_used if isinstance(src, _Row) else len(src.text) - row_limit = len(src.chars) if not is_last else src_t_used + src_cols = src.cols + src_t_used = ( + src.text_used + if isinstance(src, _Row) + else (len(src.cells) if src.cells is not None else len(src.text)) + ) + row_limit = src_cols if not is_last else src_t_used if r_i == cur_abs_idx and eff_cur_col >= row_limit: cur_after_extra = eff_cur_col - row_limit + + row_ps = pins_by_row.get(r_i) + col_pins_map: dict[int, list[int]] | None = None + if row_ps is not None: + col_pins_map = {} + for p_idx, p_col in row_ps: + eff_pc = max(0, p_col) + if eff_pc >= row_limit: + if is_last: + after_group_pins.append((p_idx, eff_pc - row_limit)) + else: + carried_pins.append(p_idx) + else: + col_pins_map.setdefault(eff_pc, []).append(p_idx) + for c_i in range(row_limit): word = src.attr_at(c_i) rb = raw_width_bits(word) is_cur = r_i == cur_abs_idx and c_i == eff_cur_col + here_pins = ( + col_pins_map.get(c_i) if col_pins_map is not None else None + ) if rb == int(WidthRole.SPACER_HEAD): if is_cur: carry_cur = True + if here_pins: + carried_pins.extend(here_pins) continue if rb == int(WidthRole.SPACER_TAIL): if is_cur and cells: p_ch, p_w, p_cw, p_ext, _ = cells[-1] cells[-1] = (p_ch, p_w, p_cw, p_ext, 1) + if here_pins: + if cells: + prev_k = len(cells) - 1 + tgt = cell_pins.setdefault(prev_k, []) + for p_idx in here_pins: + tgt.append((p_idx, 1)) + else: + carried_pins.extend(here_pins) continue cw = 2 if rb == int(WidthRole.WIDE) else 1 - base_word = word & _WIDTH_CLEAR_MASK + base_word = word & _PEN_BASE_MASK cur_off = 0 if (is_cur or carry_cur) else -1 carry_cur = False + cell_k = len(cells) + if carried_pins or here_pins: + tgt = cell_pins.setdefault(cell_k, []) + for p_idx in carried_pins: + tgt.append((p_idx, 0)) + carried_pins.clear() + if here_pins: + for p_idx in here_pins: + tgt.append((p_idx, 0)) + ch_val = src.char_at(c_i) cells.append( ( - src.chars[c_i], + ch_val, base_word, cw, src.ext_at(c_i), @@ -1320,20 +1497,25 @@ def _reflow_primary(self, *, rows: int, cols: int) -> None: ) if not cells: - empty_row = _Row(cols) + empty_row = _Row(cols, gen_counter=self._gen_counter) new_all.append(empty_row) + out_idx = len(new_all) - 1 if group_start <= cur_abs_idx <= group_end and not cursor_placed: extra = 0 if cur_after_extra is None else cur_after_extra - new_cur_abs = len(new_all) - 1 + new_cur_abs = out_idx new_cur_col = min(cols - 1, extra) new_pending_wrap = False cursor_placed = True + for p_idx in carried_pins: + mapped_out[p_idx] = (out_idx, 0) + for p_idx, p_extra in after_group_pins: + mapped_out[p_idx] = (out_idx, min(cols - 1, p_extra)) continue - cur_out = _Row(cols) + cur_out = _Row(cols, gen_counter=self._gen_counter) new_all.append(cur_out) out_col = 0 - for ch, base_w, cw, ce, cur_off in cells: + for cell_k, (ch, base_w, cw, ce, cur_off) in enumerate(cells): eff_cw = cw eff_ch = ch if eff_cw == 2 and cols == 1: @@ -1344,16 +1526,25 @@ def _reflow_primary(self, *, rows: int, cols: int) -> None: if out_col < cols: cur_out.write_spacer_head(out_col, 0, None) cur_out.wrapped = True - cur_out = _Row(cols) + cur_out = _Row(cols, gen_counter=self._gen_counter) new_all.append(cur_out) out_col = 0 + out_idx = len(new_all) - 1 if cur_off >= 0 and not cursor_placed: - new_cur_abs = len(new_all) - 1 + new_cur_abs = out_idx new_cur_col = min(cols - 1, out_col + cur_off) new_pending_wrap = False cursor_placed = True + c_ps = cell_pins.get(cell_k) + if c_ps is not None: + for p_idx, p_off in c_ps: + mapped_out[p_idx] = ( + out_idx, + min(cols - 1, out_col + p_off), + ) + if eff_cw == 2: cur_out.write_wide(out_col, eff_ch, base_w, ce) out_col += 2 @@ -1361,9 +1552,18 @@ def _reflow_primary(self, *, rows: int, cols: int) -> None: cur_out.write_narrow(out_col, eff_ch, base_w, ce) out_col += 1 + last_out_idx = len(new_all) - 1 + for p_idx in carried_pins: + mapped_out[p_idx] = (last_out_idx, min(cols - 1, out_col)) + for p_idx, p_extra in after_group_pins: + mapped_out[p_idx] = ( + last_out_idx, + min(cols - 1, out_col + p_extra), + ) + if (cur_after_extra is not None or carry_cur) and not cursor_placed: extra = 0 if cur_after_extra is None else cur_after_extra - new_cur_abs = len(new_all) - 1 + new_cur_abs = last_out_idx if extra == 0 and out_col == cols: new_cur_col = cols - 1 new_pending_wrap = True @@ -1373,51 +1573,111 @@ def _reflow_primary(self, *, rows: int, cols: int) -> None: cursor_placed = True if not new_all: - new_all.append(_Row(cols)) + new_all.append(_Row(cols, gen_counter=self._gen_counter)) + + last_in_abs = old_first_abs + total - 1 + last_out_base = len(new_all) - 1 + for p_idx, (p_abs, p_col) in enumerate(all_pins): + if p_abs > last_in_abs: + mapped_out[p_idx] = ( + last_out_base + (p_abs - last_in_abs), + min(cols - 1, max(0, p_col)), + ) hist_cut = max(0, len(new_all) - rows) hist_cut = min(hist_cut, new_cur_abs) prev_scrolled = self._scrolled_total prev_evicted = self._evicted_total - self._history.clear() - self._evicted_total = 0 - if self._history.maxlen is not None and self._history.maxlen > 0: - for r_h in new_all[:hist_cut]: - self._append_history(r_h.freeze()) - hist_len = len(self._history) + evicted_in_reflow = self._history.replace_all(new_all[:hist_cut]) + new_hist_len = len(self._history) new_evicted = max( - prev_evicted + (hist_cut - hist_len), - prev_scrolled - hist_len, + prev_evicted + evicted_in_reflow, + prev_scrolled - new_hist_len, ) self._evicted_total = new_evicted - self._scrolled_total = new_evicted + hist_len + self._scrolled_total = new_evicted + new_hist_len - viewport = new_all[hist_cut : hist_cut + rows] + viewport: list[_Row] = [ + ( + r_v.thaw(cols, gen_counter=self._gen_counter) + if isinstance(r_v, FrozenRow) + else r_v + ) + for r_v in new_all[hist_cut : hist_cut + rows] + ] while len(viewport) < rows: - viewport.append(_Row(cols)) + viewport.append(_Row(cols, gen_counter=self._gen_counter)) for r_v in viewport: - bump_row_gen(r_v) + r_v.bind_counter(self._gen_counter) self._rows = viewport - if self._gfx is not None: - self._gfx.reset() self._cols = cols self._cur_row = max(0, min(rows - 1, new_cur_abs - hist_cut)) self._cur_col = max(0, min(cols - 1, new_cur_col)) self._pending_wrap = new_pending_wrap - def resize(self, *, rows: int, cols: int, reflow: bool = True) -> None: - """Resize screen to ``(rows, cols)``, optionally reflowing soft wraps.""" + if not all_pins: + if self._gfx is not None: + self._gfx.apply_reflow_pins( + (), + new_cols=cols, + min_retained_abs_row=self._evicted_total, + max_abs=self._scrolled_total + rows, + ) + return () + + final_pins: list[tuple[int, int]] = [] + new_first_abs = self._scrolled_total - hist_cut + for p_idx, (old_abs, old_col) in enumerate(all_pins): + m_pair = mapped_out[p_idx] + if m_pair is None: + if old_abs < old_first_abs: + mapped_abs = new_first_abs + (old_abs - old_first_abs) + else: + mapped_abs = old_abs + final_pins.append((mapped_abs, min(cols - 1, max(0, old_col)))) + else: + out_r, new_c = m_pair + final_pins.append((new_first_abs + out_r, new_c)) + + if self._gfx is not None: + remapped_gfx = [ + (gfx_idx, final_pins[n_extra + k][0], final_pins[n_extra + k][1]) + for k, (gfx_idx, _, _) in enumerate(gfx_roots) + ] + self._gfx.apply_reflow_pins( + remapped_gfx, + new_cols=cols, + min_retained_abs_row=self._evicted_total, + max_abs=self._scrolled_total + rows, + ) + + return tuple(final_pins[:n_extra]) + + def _resize_with_pins( + self, + *, + rows: int, + cols: int, + reflow: bool = True, + extra_pins: collections.abc.Sequence[tuple[int, int]] = (), + ) -> tuple[tuple[int, int], ...]: if rows < 1 or cols < 1: msg = f"rows and cols must be >= 1, got ({rows}, {cols})" raise ValueError(msg) old_cols = self._cols if rows == len(self._rows) and cols == old_cols: - return + return tuple(extra_pins) + if self._on_mutate is not None: + self._on_mutate(True) if reflow and cols != old_cols: - self._reflow_primary(rows=rows, cols=cols) + remapped = self._reflow_primary( + rows=rows, + cols=cols, + extra_pins=extra_pins, + ) else: old_cur_col = self._cur_col if cols != old_cols: @@ -1429,15 +1689,11 @@ def resize(self, *, rows: int, cols: int, reflow: bool = True) -> None: top_drop_no_hist = 0 if rows < cur_rows: drop_needed = cur_rows - rows - # Keep cursor visible by scrolling excess top rows into history first. top_excess = max(0, self._cur_row - (rows - 1)) top_drop = min(drop_needed, top_excess) if top_drop > 0: if not self._is_alt: - if ( - self._history.maxlen is not None - and self._history.maxlen > 0 - ): + if self._history.maxlen > 0: for r_ev in self._rows[:top_drop]: self._append_history(r_ev.freeze()) else: @@ -1454,7 +1710,10 @@ def resize(self, *, rows: int, cols: int, reflow: bool = True) -> None: if len(self._rows) > rows: del self._rows[rows:] elif rows > cur_rows: - self._rows.extend(_Row(cols) for _ in range(rows - cur_rows)) + self._rows.extend( + _Row(cols, gen_counter=self._gen_counter) + for _ in range(rows - cur_rows) + ) if self._gfx is not None: self._gfx.on_non_reflow_resize( @@ -1462,14 +1721,22 @@ def resize(self, *, rows: int, cols: int, reflow: bool = True) -> None: new_rows=rows, new_cols=cols, scrolled_total=self._scrolled_total, + min_retained_abs_row=self._evicted_total, ) for r_v in self._rows: - bump_row_gen(r_v) + r_v.bind_counter(self._gen_counter) self._cur_row = min(self._cur_row, rows - 1) self._cur_col = min(self._cur_col, cols - 1) self._pending_wrap = self._pending_wrap and old_cur_col < cols + remapped = ( + tuple( + (p_abs, min(cols - 1, max(0, p_col))) for p_abs, p_col in extra_pins + ) + if extra_pins + else () + ) self.scroll_region = ScrollRegion( top=0, @@ -1483,9 +1750,22 @@ def resize(self, *, rows: int, cols: int, reflow: bool = True) -> None: else: self._tabstops = {t for t in self._tabstops if t < cols} self._tabstops_sorted = sorted(self._tabstops) + return remapped + + def resize( + self, + *, + rows: int, + cols: int, + reflow: bool = True, + ) -> None: + """Resize screen to ``(rows, cols)``, optionally reflowing soft wraps.""" + self._resize_with_pins(rows=rows, cols=cols, reflow=reflow) def reset(self) -> None: """Clear all visible rows, margins, cursor, keyboard stack, and tabstops.""" + if self._on_mutate is not None: + self._on_mutate(True) rows = len(self._rows) for r in self._rows: r.reset_blank(self._cols) @@ -1504,48 +1784,15 @@ def reset(self) -> None: self._tabstops = set(range(8, self._cols, 8)) self._tabstops_sorted = sorted(self._tabstops) self.keyboard_stack.reset() + self._modify_other_keys = 0 if self._gfx is not None: self._gfx.reset() -def _sync_partial_scroll_bounds( - dst_row: _Row, - src_row: _Row, - left: int, - r_col: int, -) -> None: - limit = r_col + 1 - if dst_row.text_used <= limit: - cand_t = ( - min(src_row.text_used, limit) - if src_row.text_used > left - else min(dst_row.text_used, left) - ) - if src_row.text_used > limit: - floor_t = min(dst_row.text_used, left) - while cand_t > floor_t and dst_row.chars[cand_t - 1] == " ": - cand_t -= 1 - dst_row.text_used = cand_t - if dst_row.used <= limit: - cand_u = ( - min(src_row.used, limit) if src_row.used > left else min(dst_row.used, left) - ) - floor_u = max(min(dst_row.used, left), dst_row.text_used) - if src_row.used > limit: - while ( - cand_u > floor_u - and dst_row.chars[cand_u - 1] == " " - and dst_row.attr_at(cand_u - 1) == 0 - and dst_row.ext_at(cand_u - 1) is None - ): - cand_u -= 1 - dst_row.used = max(cand_u, dst_row.text_used) - - class ScreenSet: """Dual primary and alternate (``?1049``) screen pair.""" - __slots__ = ("active_is_alt", "alternate", "primary") + __slots__ = ("_active_is_alt", "_gen_counter", "_on_mutate", "alternate", "primary") def __init__( self, @@ -1558,7 +1805,12 @@ def __init__( max_images: int = 256, max_placements: int = 1_024, max_image_dimension: int = 10_000, + top_margin_scrolls_to_history: bool = False, + on_mutate: collections.abc.Callable[[bool], None] | None = None, ) -> None: + counter = _RowGenCounter() + self._gen_counter = counter + self._on_mutate = on_mutate self.primary = Screen( rows=rows, cols=cols, @@ -1568,7 +1820,10 @@ def __init__( max_images=max_images, max_placements=max_placements, max_image_dimension=max_image_dimension, + top_margin_scrolls_to_history=top_margin_scrolls_to_history, + on_mutate=on_mutate, ) + self.primary._bind_counter(counter) self.alternate = Screen( rows=rows, cols=cols, @@ -1579,18 +1834,58 @@ def __init__( max_placements=max_placements, max_image_dimension=max_image_dimension, is_alt=True, + on_mutate=on_mutate, ) - self.active_is_alt: bool = False + self.alternate._bind_counter(counter) + self._active_is_alt: bool = False + + @property + def active_is_alt(self) -> bool: + """Return ``True`` when the alternate screen is active.""" + return self._active_is_alt + + @active_is_alt.setter + def active_is_alt(self, value: bool) -> None: + if self._active_is_alt != value: + if self._on_mutate is not None: + self._on_mutate(True) + self._active_is_alt = value + + @property + def _row_gen(self) -> int: + return self._gen_counter.value @property def active(self) -> Screen: """Return the currently active :class:`Screen`.""" return self.alternate if self.active_is_alt else self.primary - def resize(self, *, rows: int, cols: int, reflow: bool = True) -> None: + def _resize_with_pins( + self, + *, + rows: int, + cols: int, + reflow: bool = True, + primary_pins: collections.abc.Sequence[tuple[int, int]] = (), + ) -> tuple[tuple[int, int], ...]: + remapped = self.primary._resize_with_pins( + rows=rows, + cols=cols, + reflow=reflow, + extra_pins=primary_pins, + ) + self.alternate._resize_with_pins(rows=rows, cols=cols, reflow=False) + return remapped + + def resize( + self, + *, + rows: int, + cols: int, + reflow: bool = True, + ) -> None: """Resize both screens (reflowing primary when *reflow* is ``True``).""" - self.primary.resize(rows=rows, cols=cols, reflow=reflow) - self.alternate.resize(rows=rows, cols=cols, reflow=False) + self._resize_with_pins(rows=rows, cols=cols, reflow=reflow) __all__ = [ diff --git a/src/libvt/status.py b/src/libvt/status.py index 24da82b..8bf53dd 100644 --- a/src/libvt/status.py +++ b/src/libvt/status.py @@ -8,6 +8,8 @@ import re from dataclasses import dataclass +from libvt.parser import _parse_ascii_uint + _APP_RE = re.compile(r"^[A-Za-z0-9_.+-]{1,32}$") _KEY_RE = re.compile(r"^[a-z]{1,16}$") _SEG_RE = re.compile(r"^[A-Za-z0-9_.-]+$") @@ -256,11 +258,8 @@ def apply_osc_7501(self, payload: bytes) -> tuple[bool, ProgramStatus | None]: progress: int | None = None if "progress" in fields: - raw_prog = fields["progress"] - if not raw_prog.isdigit(): - return False, self.most_urgent - prog_val = int(raw_prog) - if not 0 <= prog_val <= 100: + prog_val = _parse_ascii_uint(fields["progress"], max_val=100) + if prog_val is None: return False, self.most_urgent progress = prog_val diff --git a/src/libvt/terminal.py b/src/libvt/terminal.py index ab3bbe2..70e7e31 100644 --- a/src/libvt/terminal.py +++ b/src/libvt/terminal.py @@ -8,6 +8,7 @@ import collections.abc import enum import html +import itertools import os import re import types @@ -23,8 +24,6 @@ _CellExt, _FrozenHistory, _Row, - bump_row_gen, - current_row_gen, make_cell_ext, pack_pen_base, raw_width_bits, @@ -84,10 +83,19 @@ ALT_SCREEN_MODES, DEC_PRIVATE_MASK, TRANSIENT_SNAPSHOT_MODES, + DecrpmValue, Mode, ModeState, ) -from libvt.parser import CsiParams, Parser, ParserEncoding, ParserState, parse_sgr +from libvt.parser import ( + CsiParams, + Parser, + ParserEncoding, + ParserState, + _parse_ascii_int, + _parse_ascii_uint, + parse_sgr, +) from libvt.screen import ( Cell, Cursor, @@ -161,15 +169,33 @@ _STR_BODY_UTF8_RE = re.compile(rb"[^\x07\x18\x1a\x1b\x7f]+") _STR_BODY_LATIN1_RE = re.compile(rb"[^\x07\x18\x1a\x1b\x7f\x80-\x9f]+") -_NEXT_TERMINAL_ID: int = 0 + +class _TerminalIdAllocator: + """Fork-safe lazy per-PID random nonce paired with monotonic counter.""" + + __slots__ = ("_counter", "_nonce", "_pid") + + def __init__(self) -> None: + self._pid: int = -1 + self._nonce: int = 0 + self._counter = itertools.count(1).__next__ + + def alloc(self) -> int: + pid = os.getpid() + if pid != self._pid: + self._nonce = int.from_bytes(os.urandom(8), "big") + self._pid = pid + return (self._nonce << 32) | self._counter() + + +_TERMINAL_IDS = _TerminalIdAllocator() def _alloc_terminal_id() -> int: - global _NEXT_TERMINAL_ID - _NEXT_TERMINAL_ID += 1 - return _NEXT_TERMINAL_ID + return _TERMINAL_IDS.alloc() +#: Buffer view selector for :meth:`Terminal.sync_token` and incremental deltas. type SyncView = t.Literal["working", "committed"] @@ -184,45 +210,7 @@ class ResyncReason(enum.StrEnum): @dataclass(frozen=True, slots=True) -class SyncToken: - """Opaque monotonic watermark passed to :meth:`Terminal.changes_since`. - - Attributes - ---------- - terminal_id : int - Identity cookie of the originating :class:`Terminal`. - view : SyncView - Tracked view (``"committed"`` or ``"working"``). - epoch : int - Structural epoch incremented on ``resize()``, ``RIS``, and ``?1049`` - alternate-screen transitions. - revision : int - Monotonic row-content mutation watermark. - scrolled_total : int - Cumulative primary-screen lines scrolled into history. - evicted_total : int - Cumulative primary-screen history lines evicted by ``maxlen``. - history_clear_at : int - ``scrolled_total`` value at the most recent ``ED 3`` history clear. - history_clear_seq : int - Monotonic counter of ``ED 3`` history clears. - cursor : Cursor - Cursor state at watermark capture. - modes : frozenset[Mode] - Enabled terminal modes at watermark capture. - title : str - Window title at watermark capture. - cwd : str - Working directory at watermark capture. - cwd_uri : str - Raw ``OSC 7`` / ``OSC 9;9`` working directory URI at watermark capture. - aux_revision : int - Monotonic counter of prompt-zone, program-status, and window-metadata - updates. - graphics_revision : int - Monotonic graphics placement revision on the active screen. - """ - +class _SyncState: terminal_id: int view: SyncView epoch: int @@ -240,6 +228,70 @@ class SyncToken: graphics_revision: int = 0 +def _make_sync_token(state: _SyncState) -> SyncToken: + tok = object.__new__(SyncToken) + object.__setattr__(tok, "_state", state) + return tok + + +class SyncToken: + """Opaque per-:class:`Terminal` watermark passed to :meth:`Terminal.changes_since`. + + Compare tokens with ``==`` and store them in sets or dictionaries via + :func:`hash`; obtain instances from :meth:`Terminal.sync_token` or + :attr:`ScreenDelta.token`. + """ + + __slots__ = ("_state",) + _state: _SyncState + + def __new__(cls, *args: object, **kwargs: object) -> t.NoReturn: + """Disallow direct construction; call :meth:`Terminal.sync_token`.""" + msg = "SyncToken cannot be instantiated directly; call Terminal.sync_token()" + raise TypeError(msg) + + def __setattr__(self, name: str, value: object) -> t.NoReturn: + """Disallow attribute mutation on immutable tokens.""" + msg = f"cannot assign to attribute {name!r} on immutable SyncToken" + raise AttributeError(msg) + + def __delattr__(self, name: str) -> t.NoReturn: + """Disallow attribute deletion on immutable tokens.""" + msg = f"cannot delete attribute {name!r} on immutable SyncToken" + raise AttributeError(msg) + + def __eq__(self, other: object) -> bool: + """Return ``True`` when *other* captures the identical watermark state.""" + if self is other: + return True + if not isinstance(other, SyncToken): + return NotImplemented + return self._state == other._state + + def __hash__(self) -> int: + """Return hash of the captured watermark state.""" + return hash(self._state) + + def __repr__(self) -> str: + """Return compact opaque representation.""" + st = self._state + return f"SyncToken(view={st.view!r}, epoch={st.epoch}, revision={st.revision})" + + def __copy__(self) -> SyncToken: + """Return ``self`` (immutable value).""" + return self + + def __deepcopy__(self, memo: dict[int, object]) -> SyncToken: + """Return ``self`` (immutable value).""" + return self + + def __reduce__( + self, + ) -> tuple[collections.abc.Callable[[_SyncState], SyncToken], tuple[_SyncState]]: + """Serialize token state for :mod:`pickle`.""" + return (_make_sync_token, (self._state,)) + + @dataclass(frozen=True, slots=True) class ScreenDelta: """Multi-consumer incremental screen update from :meth:`Terminal.changes_since`. @@ -468,6 +520,8 @@ class _SavedCursor: Saved ``G0``..``G3`` character-set designations. gl : int Saved active locking-shift slot index (``0..3``). + single_shift : int | None + Saved pending single-shift slot (``2`` for ``SS2``, ``3`` for ``SS3``). protected : bool Saved ``DECSCA`` character-protection pen attribute. """ @@ -479,12 +533,71 @@ class _SavedCursor: decom: bool = False g_sets: tuple[Charset, Charset, Charset, Charset] = ("B", "B", "B", "B") gl: int = 0 + single_shift: int | None = None protected: bool = False +def _make_snapshot( + *, + rows: tuple[_Row, ...], + history: _FrozenHistory | collections.abc.Sequence[FrozenRow] = ( + _EMPTY_FROZEN_HISTORY + ), + cols: int, + cursor: Cursor, + title: str, + cwd: str, + cwd_uri: str = "", + modes: frozenset[Mode], + active_is_alt: bool, + prompt_zones: tuple[PromptZone, ...], + program_status: ProgramStatus | None, + program_statuses: collections.abc.Mapping[str, ProgramStatus], + generation: int, + images: collections.abc.Mapping[int, ImageMeta] | None = None, + placements: tuple[ImagePlacement, ...] = (), + scrolled_total: int | None = None, + evicted_total: int | None = None, +) -> Snapshot: + snap = object.__new__(Snapshot) + object.__setattr__(snap, "_frozen", False) + snap._rows = rows + hist_obj = _FrozenHistory.from_sequence(history) + snap._history = hist_obj + snap._cols = cols + eff_scrolled = ( + (0 if active_is_alt else len(hist_obj)) + if scrolled_total is None + else scrolled_total + ) + snap._scrolled_total = eff_scrolled + snap._evicted_total = ( + (0 if active_is_alt else max(0, eff_scrolled - len(hist_obj))) + if evicted_total is None + else evicted_total + ) + snap.cursor = cursor + snap.title = title + snap.cwd = cwd + snap.cwd_uri = cwd_uri + snap.modes = modes + snap.active_is_alt = active_is_alt + snap.prompt_zones = prompt_zones + snap.program_status = program_status + snap.program_statuses = types.MappingProxyType(dict(program_statuses)) + snap.generation = generation + snap.images = types.MappingProxyType(dict(images) if images is not None else {}) + snap.placements = placements + object.__setattr__(snap, "_frozen", True) + return snap + + class Snapshot: """Immutable point-in-time capture of terminal screen, history, and metadata. + Obtain instances via :meth:`Terminal.snapshot`, :attr:`Terminal.committed`, + or :meth:`Snapshot.from_tmux_capture`. + Attributes ---------- cursor : Cursor @@ -535,62 +648,29 @@ class Snapshot: "title", ) - def __init__( - self, - *, - rows: tuple[_Row, ...], - history: _FrozenHistory | collections.abc.Sequence[FrozenRow] = ( - _EMPTY_FROZEN_HISTORY - ), - cols: int, - cursor: Cursor, - title: str, - cwd: str, - cwd_uri: str = "", - modes: frozenset[Mode], - active_is_alt: bool, - prompt_zones: tuple[PromptZone, ...], - program_status: ProgramStatus | None, - program_statuses: collections.abc.Mapping[str, ProgramStatus], - generation: int, - images: collections.abc.Mapping[int, ImageMeta] | None = None, - placements: tuple[ImagePlacement, ...] = (), - scrolled_total: int | None = None, - evicted_total: int | None = None, - ) -> None: - object.__setattr__(self, "_frozen", False) - self._rows = rows - hist_obj = _FrozenHistory.from_sequence(history) - self._history: _FrozenHistory = hist_obj - self._cols = cols - eff_scrolled = ( - (0 if active_is_alt else len(hist_obj)) - if scrolled_total is None - else scrolled_total - ) - self._scrolled_total = eff_scrolled - self._evicted_total = ( - (0 if active_is_alt else max(0, eff_scrolled - len(hist_obj))) - if evicted_total is None - else evicted_total - ) - self.cursor = cursor - self.title = title - self.cwd = cwd - self.cwd_uri = cwd_uri - self.modes = modes - self.active_is_alt = active_is_alt - self.prompt_zones = prompt_zones - self.program_status = program_status - self.program_statuses: collections.abc.Mapping[str, ProgramStatus] = ( - types.MappingProxyType(dict(program_statuses)) - ) - self.generation = generation - self.images: collections.abc.Mapping[int, ImageMeta] = types.MappingProxyType( - dict(images) if images is not None else {} - ) - self.placements = placements - object.__setattr__(self, "_frozen", True) + _cols: int + _evicted_total: int + _frozen: bool + _history: _FrozenHistory + _rows: tuple[_Row, ...] + _scrolled_total: int + active_is_alt: bool + cursor: Cursor + cwd: str + cwd_uri: str + generation: int + images: collections.abc.Mapping[int, ImageMeta] + modes: frozenset[Mode] + placements: tuple[ImagePlacement, ...] + program_status: ProgramStatus | None + program_statuses: collections.abc.Mapping[str, ProgramStatus] + prompt_zones: tuple[PromptZone, ...] + title: str + + def __new__(cls, *args: object, **kwargs: object) -> t.NoReturn: + """Disallow direct construction; call :meth:`Terminal.snapshot`.""" + msg = "Snapshot cannot be instantiated directly; call Terminal.snapshot()" + raise TypeError(msg) def __setattr__(self, name: str, value: object) -> None: """Reject attribute mutation once snapshot initialization completes.""" @@ -609,14 +689,21 @@ def from_tmux_capture( cols: int = 80, scrollback: int | None = None, flagged: bool = False, + trim_trailing: bool = False, joined_capture: CaptureInput | None = None, saved_primary_capture: CaptureInput | None = None, saved_primary_flagged: bool | None = None, + saved_primary_trim_trailing: bool | None = None, + saved_primary_joined_capture: CaptureInput | None = None, + post_metadata: TmuxPaneMetadata | str | None = None, profile: Profile = TMUX_PROFILE, policy: Policy = TMUX_CAPTURE_POLICY, limits: Limits = DEFAULT_LIMITS, ) -> Snapshot: - """Decode ``tmux capture-pane`` output directly into a :class:`Snapshot`.""" + """Decode ``tmux capture-pane`` output directly into a :class:`Snapshot`. + + See :func:`~libvt.tmux.decode_tmux_capture` for parameter semantics. + """ from libvt.tmux import decode_tmux_capture return decode_tmux_capture( @@ -626,9 +713,13 @@ def from_tmux_capture( cols=cols, scrollback=scrollback, flagged=flagged, + trim_trailing=trim_trailing, joined_capture=joined_capture, saved_primary_capture=saved_primary_capture, saved_primary_flagged=saved_primary_flagged, + saved_primary_trim_trailing=saved_primary_trim_trailing, + saved_primary_joined_capture=saved_primary_joined_capture, + post_metadata=post_metadata, profile=profile, policy=policy, limits=limits, @@ -709,7 +800,8 @@ def at_abs(self, abs_row: int) -> RowView: msg = f"abs_row {abs_row} was evicted (earliest retained is {first_abs})" raise IndexError(msg) if abs_row < self._scrolled_total: - return RowView(self._history.at(abs_row - first_abs)) + fr = self._history.at(abs_row - first_abs) + return RowView(fr, range(max(self._cols, fr.used))) rel = abs_row - self._scrolled_total if rel < len(self._rows): return RowView(self._rows[rel]) @@ -719,7 +811,7 @@ def at_abs(self, abs_row: int) -> RowView: @property def history(self) -> collections.abc.Sequence[RowView]: """Return ``O(1)`` immutable :class:`RowView` sequence over scrollback rows.""" - return _HistoryView(self._history) + return _HistoryView(self._history, cols=self._cols) @property def lines(self) -> tuple[str, ...]: @@ -915,26 +1007,41 @@ def _render_vt(self, snapshot: Snapshot) -> str: export_modes = snapshot.modes - TRANSIENT_SNAPSHOT_MODES if not snapshot.active_is_alt: export_modes = export_modes - ALT_SCREEN_MODES - for mode in sorted(export_modes, key=int): - raw = int(mode) - if raw & DEC_PRIVATE_MASK: - code = raw & ~DEC_PRIVATE_MASK - if mode not in ( - Mode.DECAWM, - Mode.DECTCEM, - Mode.GRAPHEME_CLUSTERING, - ): - out.append(f"\x1b[?{code}h") - else: - out.append(f"\x1b[{raw}h") - if Mode.DECTCEM not in export_modes: - out.append("\x1b[?25l") + else: + for alt_mode in sorted(export_modes & ALT_SCREEN_MODES, key=int): + code = int(alt_mode) & ~DEC_PRIVATE_MASK + out.append(f"\x1b[?{code}h") + if Mode.GRAPHEME_CLUSTERING not in export_modes: + out.append("\x1b[?2027l") cur_style = DEFAULT_STYLE cur_link: Hyperlink | None = None + cols = snapshot.cols + n_rows = len(snapshot._rows) for r_idx, row in enumerate(snapshot._rows): + eff_wrapped = row.wrapped and r_idx + 1 < n_rows if r_idx > 0: - out.append("\r\n" if not snapshot._rows[r_idx - 1].wrapped else "") - limit = row.used if row.wrapped else row.text_used + prev_wrapped = snapshot._rows[r_idx - 1].wrapped + if not prev_wrapped: + out.append("\r\n") + elif not eff_wrapped and row.text_used == 0 and cols > 0: + if cur_link is not None: + out.append("\x1b]8;;\x1b\\") + cur_link = None + if cur_style != DEFAULT_STYLE: + out.append("\x1b[0m") + cur_style = DEFAULT_STYLE + out.append(f" \x1b[{r_idx + 1};1H\x1b[K") + if eff_wrapped: + has_spacer_head = ( + cols > 0 + and raw_width_bits(row.attr_at(cols - 1)) + == int(WidthRole.SPACER_HEAD) + and raw_width_bits(snapshot._rows[r_idx + 1].attr_at(0)) + == int(WidthRole.WIDE) + ) + limit = max(0, cols - 1) if has_spacer_head else cols + else: + limit = min(cols, row.text_used) for c in range(limit): word = row.attr_at(c) rb = raw_width_bits(word) @@ -953,11 +1060,11 @@ def _render_vt(self, snapshot: Snapshot) -> str: if style != cur_style: out.append(_style_to_sgr(style)) cur_style = style - out.append(row.chars[c]) - if not row.wrapped and row.used > limit: + out.append(row.char_at(c)) + if not eff_wrapped and row.used > limit: cur_col_pos = limit span_c = limit - row_used = min(snapshot.cols, row.used) + row_used = min(cols, row.used) while span_c < row_used: word = row.attr_at(span_c) ext = row.ext_at(span_c) @@ -987,7 +1094,7 @@ def _render_vt(self, snapshot: Snapshot) -> str: if style != cur_style: out.append(_style_to_sgr(style)) cur_style = style - if end_c == snapshot.cols: + if end_c == cols: out.append("\x1b[K") else: out.append(f"\x1b[{end_c - span_c}X") @@ -996,7 +1103,37 @@ def _render_vt(self, snapshot: Snapshot) -> str: out.append("\x1b]8;;\x1b\\") if cur_style != DEFAULT_STYLE: out.append("\x1b[0m") - out.append(f"\x1b[{snapshot.cursor.row + 1};{snapshot.cursor.col + 1}H") + for mode in sorted(export_modes - ALT_SCREEN_MODES, key=int): + raw = int(mode) + if raw & DEC_PRIVATE_MASK: + code = raw & ~DEC_PRIVATE_MASK + if mode not in ( + Mode.DECAWM, + Mode.DECTCEM, + Mode.ALTERNATE_SCROLL, + Mode.GRAPHEME_CLUSTERING, + ): + out.append(f"\x1b[?{code}h") + else: + out.append(f"\x1b[{raw}h") + if Mode.DECAWM not in export_modes: + out.append("\x1b[?7l") + if Mode.DECTCEM not in export_modes: + out.append("\x1b[?25l") + if Mode.ALTERNATE_SCROLL not in export_modes: + out.append("\x1b[?1007l") + cur = snapshot.cursor + if (cur.shape, cur.blinking) != (CursorShape.BLOCK, True): + decscusr_map: dict[tuple[CursorShape, bool], int] = { + (CursorShape.BLOCK, False): 2, + (CursorShape.UNDERLINE, True): 3, + (CursorShape.UNDERLINE, False): 4, + (CursorShape.BAR, True): 5, + (CursorShape.BAR, False): 6, + } + ps = decscusr_map.get((cur.shape, cur.blinking), 1) + out.append(f"\x1b[{ps} q") + out.append(f"\x1b[{cur.row + 1};{cur.col + 1}H") return "".join(out) def _render_html(self, snapshot: Snapshot) -> str: @@ -1117,25 +1254,107 @@ def on_window_rename(self, data: bytes) -> None: self._term._handle_window_rename(data) +def _utf8_len(text: str) -> int: + return len(text) if text.isascii() else len(text.encode("utf-8", "surrogatepass")) + + def _event_byte_cost(event: Event) -> int: if isinstance(event, Passthrough): return 64 + len(event.data) if isinstance(event, SixelGraphic): - return 64 + len(event.data.payload) + return 64 + len(event.data.payload) + len(event.data.params) * 8 if isinstance(event, KittyGraphic): - return 64 + len(event.command.payload) + ctrl_cost = sum( + 32 + _utf8_len(k) + _utf8_len(v) for k, v in event.command.control.items() + ) + return 64 + len(event.command.payload) + ctrl_cost if isinstance(event, ClipboardWrite): - return 64 + len(event.text) - return 64 + return 64 + _utf8_len(event.selection) + _utf8_len(event.text) + if isinstance(event, TitleChanged): + return 64 + _utf8_len(event.title) + if isinstance(event, WindowRenamed): + return 64 + _utf8_len(event.name) + if isinstance(event, WorkingDirectoryChanged): + return 64 + _utf8_len(event.uri) + _utf8_len(event.path) + if isinstance(event, ProgramStatusChanged): + cost = 64 + _utf8_len(event.task_id) + st = event.status + if st is not None: + cost += 64 + _utf8_len(st.id) + if st.app is not None: + cost += _utf8_len(st.app) + if st.effective_app is not None: + cost += _utf8_len(st.effective_app) + if st.title is not None: + cost += _utf8_len(st.title) + if st.msg is not None: + cost += _utf8_len(st.msg) + return cost + if isinstance(event, UnhandledSequence): + return 64 + _utf8_len(event.kind) + _utf8_len(event.summary) + if isinstance( + event, + ( + Bell, + PromptMark, + RenderHoldChanged, + ColorSchemeQueried, + InBandResize, + ScreenErased, + ), + ): + return 64 + t.assert_never(event) + + +def _parse_ascii_uint_bytes(raw: bytes, *, max_val: int) -> int | None: + if not raw: + return None + acc = 0 + for b in raw: + if not (0x30 <= b <= 0x39): + return None + acc = acc * 10 + (b - 0x30) + if acc > max_val: + return None + return acc + + +def _format_osc_rgb(rgb: tuple[int, int, int]) -> str: + r, g, b = rgb + return f"rgb:{r:02x}{r:02x}/{g:02x}{g:02x}/{b:02x}{b:02x}" + + +def _parse_ascii_hex(raw: str) -> int | None: + if not raw: + return None + acc = 0 + for ch in raw: + code = ord(ch) + if 0x30 <= code <= 0x39: + digit = code - 0x30 + elif 0x41 <= code <= 0x46: + digit = code - 0x41 + 10 + elif 0x61 <= code <= 0x66: + digit = code - 0x61 + 10 + else: + return None + acc = (acc << 4) | digit + return acc def _parse_osc_rgb(spec: bytes) -> tuple[int, int, int] | None: - text = spec.decode("ascii", errors="ignore").strip() + try: + text = spec.decode("ascii").strip() + except UnicodeDecodeError: + return None if text.startswith("#") and len(text) == 7: - try: - return (int(text[1:3], 16), int(text[3:5], 16), int(text[5:7], 16)) - except ValueError: + r = _parse_ascii_hex(text[1:3]) + g = _parse_ascii_hex(text[3:5]) + b = _parse_ascii_hex(text[5:7]) + if r is None or g is None or b is None: return None + return (r, g, b) if text.lower().startswith("rgb:"): parts = text[4:].split("/") if len(parts) != 3: @@ -1144,9 +1363,8 @@ def _parse_osc_rgb(spec: bytes) -> tuple[int, int, int] | None: for comp in parts: if not (1 <= len(comp) <= 4): return None - try: - raw = int(comp, 16) - except ValueError: + raw = _parse_ascii_hex(comp) + if raw is None: return None scale = (1 << (4 * len(comp))) - 1 vals.append((raw * 255) // scale) @@ -1171,7 +1389,14 @@ def _hex_encode(text: str) -> str: class Terminal: - """Sans-I/O virtual terminal emulator over a streaming VT500 parser.""" + """Sans-I/O virtual terminal emulator over a streaming VT500 parser. + + Every method call and attribute read on a :class:`Terminal` instance + (including capturing state via :meth:`snapshot` or :attr:`committed`) + belongs to a single owning thread or ``asyncio`` event loop unless + externally synchronized. Returned :class:`Snapshot` values are immutable + and safe to pass across threads without locking. + """ def __init__( self, @@ -1200,6 +1425,19 @@ def __init__( self._recorder = recorder self._events: collections.deque[Event] = collections.deque() self._event_bytes: int = 0 + self._terminal_id: int = _alloc_terminal_id() + self._generation: int = 0 + self._committed_generation: int = 0 + self._epoch: int = 0 + self._aux_revision: int = 0 + self._sync_generation: int = 0 + self._sync_hold_pending: bool = False + self._cached_snapshot: Snapshot | None = None + self._cached_row_gen: int = -1 + self._held_snapshot: Snapshot | None = None + self._held_sync_token: SyncToken | None = None + self._step_event: StopOn = StopOn.NONE + self._passthrough_depth: int = 0 self._screens = ScreenSet( rows=rows, cols=cols, @@ -1209,10 +1447,15 @@ def __init__( max_images=limits.max_images, max_placements=limits.max_placements, max_image_dimension=limits.max_image_dimension, + top_margin_scrolls_to_history=profile.top_margin_scrolls_to_history, + on_mutate=self._on_screen_mutate, + ) + self._modes = ModeState( + on_mutate=self._before_mutate, + on_set_mode=self._intercept_mode_set, ) - self._modes = ModeState() if newline_mode: - self._modes.set_mode(Mode.LNM, enabled=True) + self._modes._enabled.add(Mode.LNM) self._parser = Parser( encoding=encoding, tmux_window_rename=profile.tmux_window_rename, @@ -1238,6 +1481,8 @@ def __init__( self._single_shift: int | None = None self._saved_primary = _SavedCursor(g_sets=def_g) self._saved_alt = _SavedCursor(g_sets=def_g) + self._saved_decsc = _SavedCursor(g_sets=def_g) + self._has_alt_saved: bool = False self._last_printed: str = "" self._last_printed_pos: tuple[int, int] | None = None self._cluster_state: int = CLUSTER_NONE @@ -1247,6 +1492,8 @@ def __init__( self._window_name: str = "" self._fg_rgb: tuple[int, int, int] = profile.fg_rgb self._bg_rgb: tuple[int, int, int] = profile.bg_rgb + self._cursor_rgb: tuple[int, int, int] = profile.cursor_rgb + self._palette_overrides: dict[int, tuple[int, int, int]] = {} self._title_stack: list[str] = [] self._cwd: str = "" self._cwd_uri: str = "" @@ -1257,17 +1504,6 @@ def __init__( max_records=limits.max_status_records, ) self._replies = bytearray() - self._terminal_id: int = _alloc_terminal_id() - self._generation: int = 0 - self._epoch: int = 0 - self._aux_revision: int = 0 - self._sync_generation: int = 0 - self._sync_hold_pending: bool = False - self._cached_snapshot: Snapshot | None = None - self._held_snapshot: Snapshot | None = None - self._held_sync_token: SyncToken | None = None - self._step_event: StopOn = StopOn.NONE - self._passthrough_depth: int = 0 @classmethod def from_size( @@ -1299,14 +1535,21 @@ def from_tmux_capture( cols: int = 80, scrollback: int | None = None, flagged: bool = False, + trim_trailing: bool = False, joined_capture: CaptureInput | None = None, saved_primary_capture: CaptureInput | None = None, saved_primary_flagged: bool | None = None, + saved_primary_trim_trailing: bool | None = None, + saved_primary_joined_capture: CaptureInput | None = None, + post_metadata: TmuxPaneMetadata | str | None = None, profile: Profile = TMUX_PROFILE, policy: Policy = TMUX_CAPTURE_POLICY, limits: Limits = DEFAULT_LIMITS, ) -> Terminal: - """Reconstruct a live :class:`Terminal` from ``tmux capture-pane`` output.""" + """Reconstruct a live :class:`Terminal` from ``tmux capture-pane`` output. + + See :func:`~libvt.tmux.decode_tmux_capture` for parameter semantics. + """ from libvt.tmux import decode_tmux_capture return decode_tmux_capture( @@ -1316,9 +1559,13 @@ def from_tmux_capture( cols=cols, scrollback=scrollback, flagged=flagged, + trim_trailing=trim_trailing, joined_capture=joined_capture, saved_primary_capture=saved_primary_capture, saved_primary_flagged=saved_primary_flagged, + saved_primary_trim_trailing=saved_primary_trim_trailing, + saved_primary_joined_capture=saved_primary_joined_capture, + post_metadata=post_metadata, profile=profile, policy=policy, limits=limits, @@ -1409,6 +1656,11 @@ def kitty_keyboard_flags(self) -> KittyKeyboardFlags: """Return active screen's :class:`~libvt.input.KittyKeyboardFlags`.""" return self._screens.active.keyboard_stack.flags + @property + def modify_other_keys(self) -> int: + """Return active screen's ``XTMODKEYS`` ``modifyOtherKeys`` level.""" + return self._screens.active.modify_other_keys + @property def synchronized(self) -> bool: """Return ``True`` while DEC mode ``?2026`` synchronized output is active.""" @@ -1419,6 +1671,11 @@ def sync_generation(self) -> int: """Return monotonic ``?2026`` synchronized-update batch counter.""" return self._sync_generation + @property + def committed_generation(self) -> int: + """Return monotonic counter incremented whenever :attr:`committed` advances.""" + return self._committed_generation + @property def prompt_zones(self) -> tuple[PromptZone, ...]: """Return recorded primary-screen ``OSC 133`` semantic prompt zones.""" @@ -1482,7 +1739,7 @@ def _build_snapshot( if exclude_modes: modes = modes - exclude_modes active_alt = self._screens.active_is_alt - return Snapshot( + return _make_snapshot( rows=tuple(r.clone() for r in scr._rows), history=self._screens.primary._history.freeze(), cols=scr.cols, @@ -1514,22 +1771,24 @@ def _live_sync_token( if exclude_modes: modes = modes - exclude_modes gfx_rev = scr._gfx.revision if scr._gfx is not None else 0 - return SyncToken( - terminal_id=self._terminal_id, - view=view, - epoch=self._epoch, - revision=current_row_gen(), - scrolled_total=prim._scrolled_total, - evicted_total=prim._evicted_total, - history_clear_at=prim._history_clear_at, - history_clear_seq=prim._history_clear_seq, - cursor=scr.cursor, - modes=modes, - title=self._title, - cwd=self._cwd, - cwd_uri=self._cwd_uri, - aux_revision=self._aux_revision, - graphics_revision=gfx_rev, + return _make_sync_token( + _SyncState( + terminal_id=self._terminal_id, + view=view, + epoch=self._epoch, + revision=self._screens._row_gen, + scrolled_total=prim._scrolled_total, + evicted_total=prim._evicted_total, + history_clear_at=prim._history_clear_at, + history_clear_seq=prim._history_clear_seq, + cursor=scr.cursor, + modes=modes, + title=self._title, + cwd=self._cwd, + cwd_uri=self._cwd_uri, + aux_revision=self._aux_revision, + graphics_revision=gfx_rev, + ) ) def _ensure_sync_snapshot(self) -> None: @@ -1608,12 +1867,17 @@ def _full(reason: ResyncReason) -> ScreenDelta: if token is None: return _full(ResyncReason.INITIAL) - if token.terminal_id != self._terminal_id or token.view != view: + if not isinstance(token, SyncToken): + msg = f"token must be SyncToken or None, got {type(token).__name__}" + raise TypeError(msg) + cur_st = cur_tok._state + tok_st = token._state + if tok_st.terminal_id != self._terminal_id or tok_st.view != view: return _full(ResyncReason.TERMINAL_MISMATCH) - if token.epoch != cur_tok.epoch: + if tok_st.epoch != cur_st.epoch: return _full(ResyncReason.EPOCH_CHANGED) - if token == cur_tok: + if tok_st == cur_st: return ScreenDelta( token=cur_tok, from_token=token, @@ -1630,7 +1894,7 @@ def _full(reason: ResyncReason) -> ScreenDelta: snapshot=cur_snap, ) - hist_cleared = cur_tok.history_clear_seq != token.history_clear_seq + hist_cleared = cur_st.history_clear_seq != tok_st.history_clear_seq hist_len = len(cur_snap._history) zero_hist_cap = self._screens.primary._history.maxlen == 0 and hist_len == 0 new_hist: collections.abc.Sequence[RowView] @@ -1639,7 +1903,7 @@ def _full(reason: ResyncReason) -> ScreenDelta: new_hist = () evicted_cnt = 0 else: - post_clear = max(0, cur_tok.scrolled_total - cur_tok.history_clear_at) + post_clear = max(0, cur_st.scrolled_total - cur_st.history_clear_at) if post_clear > hist_len: return _full(ResyncReason.HISTORY_EVICTED) new_hist = ( @@ -1647,7 +1911,7 @@ def _full(reason: ResyncReason) -> ScreenDelta: ) evicted_cnt = 0 else: - added = max(0, cur_tok.scrolled_total - token.scrolled_total) + added = max(0, cur_st.scrolled_total - tok_st.scrolled_total) if zero_hist_cap: new_hist = () evicted_cnt = 0 @@ -1655,17 +1919,17 @@ def _full(reason: ResyncReason) -> ScreenDelta: if added > hist_len: return _full(ResyncReason.HISTORY_EVICTED) new_hist = cur_snap.history[hist_len - added :] if added > 0 else () - evicted_cnt = max(0, cur_tok.evicted_total - token.evicted_total) + evicted_cnt = max(0, cur_st.evicted_total - tok_st.evicted_total) v_scroll = ( 0 if cur_snap.active_is_alt - else max(0, cur_tok.scrolled_total - token.scrolled_total) + else max(0, cur_st.scrolled_total - tok_st.scrolled_total) ) dirty = tuple( idx for idx, r in enumerate(cur_snap._rows) - if r.content_gen > token.revision + if r.content_gen > tok_st.revision ) return ScreenDelta( token=cur_tok, @@ -1676,27 +1940,30 @@ def _full(reason: ResyncReason) -> ScreenDelta: new_history=new_hist, history_evicted=evicted_cnt, history_cleared=hist_cleared, - cursor_changed=cur_tok.cursor != token.cursor, - modes_changed=cur_tok.modes != token.modes, + cursor_changed=cur_st.cursor != tok_st.cursor, + modes_changed=cur_st.modes != tok_st.modes, metadata_changed=( - cur_tok.title != token.title - or cur_tok.cwd != token.cwd - or cur_tok.cwd_uri != token.cwd_uri - or cur_tok.aux_revision != token.aux_revision + cur_st.title != tok_st.title + or cur_st.cwd != tok_st.cwd + or cur_st.cwd_uri != tok_st.cwd_uri + or cur_st.aux_revision != tok_st.aux_revision ), - graphics_changed=cur_tok.graphics_revision != token.graphics_revision, + graphics_changed=cur_st.graphics_revision != tok_st.graphics_revision, snapshot=cur_snap, ) def snapshot(self) -> Snapshot: """Capture an immutable :class:`Snapshot` of live terminal state.""" + cur_row_gen = self._screens._row_gen if ( self._cached_snapshot is not None and self._cached_snapshot.generation == self._generation + and self._cached_row_gen == cur_row_gen ): return self._cached_snapshot snap = self._build_snapshot() self._cached_snapshot = snap + self._cached_row_gen = cur_row_gen return snap @t.overload @@ -1729,15 +1996,14 @@ def _emit_event(self, event: Event) -> None: max_ev = self._limits.max_events max_bytes = self._limits.max_event_bytes cost = _event_byte_cost(event) - if max_ev > 0 and max_bytes > 0: + if max_ev > 0 and max_bytes > 0 and cost <= max_bytes: while self._events and ( len(self._events) >= max_ev or self._event_bytes + cost > max_bytes ): dropped = self._events.popleft() self._event_bytes -= _event_byte_cost(dropped) - if cost <= max_bytes: - self._events.append(event) - self._event_bytes += cost + self._events.append(event) + self._event_bytes += cost if self._on_event is not None: self._on_event(event) @@ -1749,7 +2015,7 @@ def _unhandled(self, kind: str, summary: str) -> None: self._emit_event(UnhandledSequence(kind=kind, summary=summary)) def drain_events(self) -> tuple[Event, ...]: - """Return and clear buffered :data:`~libvt.events.Event` records.""" + """Return and clear buffered ``Event`` records from :mod:`libvt.events`.""" if not self._events: return () out = tuple(self._events) @@ -1771,6 +2037,10 @@ def encode(self, event: InputEvent, /) -> bytes: event, modes=self._modes, kitty_flags=self.kitty_keyboard_flags, + modify_other_keys=self.modify_other_keys, + active_is_alt=self._screens.active_is_alt, + cell_width_px=self._profile.cell_width_px, + cell_height_px=self._profile.cell_height_px, ) def expire_synchronized_output( @@ -1786,12 +2056,13 @@ def expire_synchronized_output( return False if sync_generation is not None and sync_generation != self._sync_generation: return False - self._modes.set_mode(Mode.SYNCHRONIZED_OUTPUT, enabled=False) + self._modes._enabled.discard(Mode.SYNCHRONIZED_OUTPUT) self._sync_hold_pending = False self._held_snapshot = None self._held_sync_token = None self._cached_snapshot = None self._generation += 1 + self._committed_generation += 1 self._emit_event( RenderHoldChanged( active=False, @@ -1833,10 +2104,9 @@ def _sync_pen_cache(self) -> None: ) def _bce_pair(self) -> tuple[int, _CellExt | None]: - if self._style.bg is None and self._hyperlink is None: + if self._style.bg is None: return 0, None - bce_style = Style(bg=self._style.bg) - return pack_pen_base(bce_style), make_cell_ext(bce_style, self._hyperlink) + return pack_pen_base(Style(bg=self._style.bg)), None def _notify_erase(self, rect: Rect, cause: EraseCause) -> None: if ( @@ -1860,10 +2130,46 @@ def resize( reflow: bool | None = None, ) -> None: """Resize terminal screens to ``(rows, cols)``.""" + if isinstance(rows, bool) or isinstance(cols, bool) or rows < 1 or cols < 1: + msg = f"rows and cols must be >= 1, got ({rows!r}, {cols!r})" + raise ValueError(msg) eff_reflow = self._profile.reflow_on_resize if reflow is None else reflow self._before_mutate() self._clear_cluster_anchor() - self._screens.resize(rows=rows, cols=cols, reflow=eff_reflow) + old_zones = tuple(self._prompt_zones) + zone_pins = tuple((z.abs_row, z.col) for z in old_zones) + remapped_pins = self._screens._resize_with_pins( + rows=rows, + cols=cols, + reflow=eff_reflow, + primary_pins=zone_pins, + ) + if old_zones and len(remapped_pins) == len(old_zones): + prim = self._screens.primary + min_z_abs = prim._evicted_total + max_z_abs = prim._scrolled_total + rows + changed_z = False + updated_z: list[PromptZone] = [] + for z, (new_abs, new_col) in zip(old_zones, remapped_pins, strict=True): + if new_abs < min_z_abs or new_abs >= max_z_abs: + changed_z = True + continue + if new_abs != z.abs_row or new_col != z.col: + updated_z.append( + PromptZone( + kind=z.kind, + abs_row=new_abs, + col=new_col, + exit_code=z.exit_code, + ) + ) + changed_z = True + else: + updated_z.append(z) + if changed_z: + self._prompt_zones.clear() + self._prompt_zones.extend(updated_z) + self._aux_revision += 1 if not self._modes.is_set(Mode.DECAWM): self._screens.primary._pending_wrap = False self._screens.alternate._pending_wrap = False @@ -1877,12 +2183,15 @@ def resize( decom=self._saved_primary.decom, g_sets=self._saved_primary.g_sets, gl=self._saved_primary.gl, + single_shift=self._saved_primary.single_shift, protected=self._saved_primary.protected, ) self._generation += 1 self._epoch += 1 if self._modes.is_set(Mode.IN_BAND_RESIZE): - self._emit_reply(f"\x1b[48;{rows};{cols};0;0t".encode("ascii")) + px_h = rows * max(0, self._profile.cell_height_px) + px_w = cols * max(0, self._profile.cell_width_px) + self._emit_reply(f"\x1b[48;{rows};{cols};{px_h};{px_w}t".encode("ascii")) self._emit_event(InBandResize(rows=rows, cols=cols)) def reset(self, *, soft: bool = False) -> None: @@ -1904,16 +2213,20 @@ def reset(self, *, soft: bool = False) -> None: self._gl = 0 self._single_shift = None was_sync = self.synchronized - was_alt = self._screens.active_is_alt - self._modes = ModeState() - if self._newline_mode: - self._modes.set_mode(Mode.LNM, enabled=True) - self._sync_hold_pending = False - self._held_snapshot = None - self._held_sync_token = None if soft: - if was_alt: - self._modes.sync_alt_screen(active_is_alt=True) + for mode_off in ( + Mode.IRM, + Mode.DECOM, + Mode.REVERSE_WRAP, + Mode.DECCKM, + Mode.DECLRMM, + ): + self._modes.set_mode(mode_off, enabled=False) + for mode_on in ( + Mode.DECAWM, + Mode.DECTCEM, + ): + self._modes.set_mode(mode_on, enabled=True) scr = self._screens.active scr.scroll_region = ScrollRegion( top=0, @@ -1921,10 +2234,29 @@ def reset(self, *, soft: bool = False) -> None: left=0, right=scr.cols - 1, ) - scr._cur_visible = True + self._screens.primary._cur_visible = True + self._screens.alternate._cur_visible = True + scr._cur_shape = CursorShape.BLOCK + scr._cur_blinking = True scr._pending_wrap = False - scr.keyboard_stack.reset() + scr._modify_other_keys = 0 + self._palette_overrides.clear() + if self._profile.separate_alt_save_cursor: + self._saved_decsc = _SavedCursor(g_sets=def_g) + elif self._screens.active_is_alt: + self._saved_alt = _SavedCursor(g_sets=def_g) + else: + self._saved_primary = _SavedCursor(g_sets=def_g) else: + self._modes = ModeState( + on_mutate=self._before_mutate, + on_set_mode=self._intercept_mode_set, + ) + if self._newline_mode: + self._modes._enabled.add(Mode.LNM) + self._sync_hold_pending = False + self._held_snapshot = None + self._held_sync_token = None self._epoch += 1 self._parser.reset() self._passthrough_parser = None @@ -1933,10 +2265,14 @@ def reset(self, *, soft: bool = False) -> None: self._screens.alternate.reset() self._saved_primary = _SavedCursor(g_sets=def_g) self._saved_alt = _SavedCursor(g_sets=def_g) + self._saved_decsc = _SavedCursor(g_sets=def_g) + self._has_alt_saved = False self._title = "" self._window_name = "" self._fg_rgb = self._profile.fg_rgb self._bg_rgb = self._profile.bg_rgb + self._cursor_rgb = self._profile.cursor_rgb + self._palette_overrides.clear() self._title_stack.clear() self._cwd = "" self._cwd_uri = "" @@ -1949,7 +2285,9 @@ def reset(self, *, soft: bool = False) -> None: ) self._cached_snapshot = None self._generation += 1 - if was_sync: + if (not soft and was_sync) or not self.synchronized: + self._committed_generation += 1 + if not soft and was_sync: self._emit_event( RenderHoldChanged( active=False, @@ -1957,9 +2295,61 @@ def reset(self, *, soft: bool = False) -> None: ), ) + def _on_screen_mutate(self, structural: bool) -> None: + self._before_mutate() + if structural: + self._epoch += 1 + + def _set_synchronized_output(self, enabled: bool) -> None: + was_set = self._modes.is_set(Mode.SYNCHRONIZED_OUTPUT) + if enabled == was_set: + return + self._invalidate_cache() + if enabled: + self._modes._enabled.add(Mode.SYNCHRONIZED_OUTPUT) + self._sync_generation += 1 + self._sync_hold_pending = True + self._held_snapshot = None + self._held_sync_token = None + self._step_event |= StopOn.SYNC_START + else: + self._modes._enabled.discard(Mode.SYNCHRONIZED_OUTPUT) + self._sync_hold_pending = False + self._held_snapshot = None + self._held_sync_token = None + self._committed_generation += 1 + self._step_event |= StopOn.SYNC_END + self._emit_event( + RenderHoldChanged( + active=enabled, + sync_generation=self._sync_generation, + ), + ) + + def _intercept_mode_set(self, mode: Mode, enabled: bool) -> bool: + if mode == Mode.SYNCHRONIZED_OUTPUT: + self._set_synchronized_output(enabled) + return True + if mode == Mode.DECLRMM and not self._profile.declrmm_enabled and enabled: + return True + if mode == Mode.DECSC_1048 and self._profile.separate_alt_save_cursor: + return True + if ( + mode == Mode.MOUSE_SGR_PIXELS + and enabled + and (self._profile.cell_width_px <= 0 or self._profile.cell_height_px <= 0) + ): + return True + if mode == Mode.DECTCEM: + self._screens.primary._cur_visible = enabled + self._screens.alternate._cur_visible = enabled + return False + def _before_mutate(self) -> None: if self._sync_hold_pending: self._ensure_sync_snapshot() + elif not self.synchronized: + self._committed_generation += 1 self._invalidate_cache() def feed_str(self, text: str, /) -> None: @@ -2077,23 +2467,42 @@ def _set_cursor( if clear_cluster: self._clear_cluster_anchor() - def _shift_prompt_zones_below( + def _remap_prompt_zones_on_scroll( self, prev_scrolled: int, + *, + top: int, bottom: int, - count: int, + rows: int, + hist_delta: int, ) -> None: - if not self._prompt_zones or count <= 0: + if not self._prompt_zones or hist_delta <= 0: return - cutoff = prev_scrolled + bottom + if top == 0 and bottom >= rows - 1: + return + abs_top = prev_scrolled + top + abs_bot = prev_scrolled + bottom changed = False updated: list[PromptZone] = [] for z in self._prompt_zones: - if z.abs_row > cutoff: + old_abs = z.abs_row + if top == 0: + new_abs = old_abs + hist_delta if old_abs > abs_bot else old_abs + elif old_abs < prev_scrolled: + new_abs = old_abs + elif old_abs < abs_top: + new_abs = old_abs + hist_delta + elif old_abs < abs_top + hist_delta: + new_abs = old_abs - top + elif old_abs <= abs_bot: + new_abs = old_abs + else: + new_abs = old_abs + hist_delta + if new_abs != old_abs: updated.append( PromptZone( kind=z.kind, - abs_row=z.abs_row + count, + abs_row=new_abs, col=z.col, exit_code=z.exit_code, ), @@ -2117,7 +2526,7 @@ def _linefeed(self, scr: Screen, *, carriage_return: bool = False) -> None: ) if scr._cur_row == bottom and left <= scr._cur_col <= right: prev_scrolled = scr._scrolled_total - bce_word, bce_ext = self._bce_pair() + bce_word, _ = self._bce_pair() save_hist = not self._screens.active_is_alt scr.scroll_up( 1, @@ -2127,17 +2536,16 @@ def _linefeed(self, scr: Screen, *, carriage_return: bool = False) -> None: right=right, save_history=save_hist, bce_word=bce_word, - bce_ext=bce_ext, ) hist_delta = scr._scrolled_total - prev_scrolled - if ( - hist_delta > 0 - and top == 0 - and bottom < scr.rows - 1 - and left == 0 - and right == scr.cols - 1 - ): - self._shift_prompt_zones_below(prev_scrolled, bottom, hist_delta) + if hist_delta > 0 and left == 0 and right == scr.cols - 1: + self._remap_prompt_zones_on_scroll( + prev_scrolled, + top=top, + bottom=bottom, + rows=scr.rows, + hist_delta=hist_delta, + ) self._notify_erase( Rect(bottom, left, 1, right - left + 1), EraseCause.SCROLL, @@ -2172,7 +2580,7 @@ def _advance_rows( self._set_cursor(scr, orig_row + to_bottom, final_col, pending_wrap=False) return orig_row prev_scrolled = scr._scrolled_total - bce_word, bce_ext = self._bce_pair() + bce_word, _ = self._bce_pair() save_hist = not self._screens.active_is_alt scr.scroll_up( scroll_cnt, @@ -2182,17 +2590,16 @@ def _advance_rows( right=right, save_history=save_hist, bce_word=bce_word, - bce_ext=bce_ext, ) hist_delta = scr._scrolled_total - prev_scrolled - if ( - hist_delta > 0 - and top == 0 - and bottom < scr.rows - 1 - and left == 0 - and right == scr.cols - 1 - ): - self._shift_prompt_zones_below(prev_scrolled, bottom, hist_delta) + if hist_delta > 0 and left == 0 and right == scr.cols - 1: + self._remap_prompt_zones_on_scroll( + prev_scrolled, + top=top, + bottom=bottom, + rows=scr.rows, + hist_delta=hist_delta, + ) erase_h = min(scroll_cnt, bottom - top + 1) self._notify_erase( Rect(bottom - erase_h + 1, left, erase_h, right - left + 1), @@ -2254,13 +2661,11 @@ def _write_slice_run( set_wrap = can_advance and min_col == 0 and c_col == scr.cols - 1 if set_wrap and prev_row == 0 and bottom == 0: scr._rows[0].wrapped = True - bump_row_gen(scr._rows[0]) self._linefeed(scr) if set_wrap and not (prev_row == 0 and bottom == 0): wrap_idx = prev_row - 1 if prev_row == bottom else prev_row if 0 <= wrap_idx < scr.rows: scr._rows[wrap_idx].wrapped = True - bump_row_gen(scr._rows[wrap_idx]) self._set_cursor(scr, scr._cur_row, min_col, pending_wrap=False) c_col = scr._cur_col avail = max_col - c_col + 1 @@ -2437,7 +2842,7 @@ def _handle_print(self, text: str) -> None: and eff_right - eff_left >= 1 ): prev_cluster_len = self._cluster_len - combined = row_obj.chars[pc] + ch + combined = row_obj.char_at(pc) + ch base_pen = row_obj.attr_at(pc) & _PEN_BASE_MASK base_ext = row_obj.ext_at(pc) bce_w, bce_e = self._bce_pair() @@ -2552,7 +2957,7 @@ def _handle_print(self, text: str) -> None: if pc == 0 and w_override == 1: scr.heal_wrapped_spacer_head(pr) self._cluster_len += 1 - self._last_printed = row_obj.chars[pc] + self._last_printed = row_obj.char_at(pc) if ( w_override == 2 and cur_role == int(WidthRole.NARROW) @@ -2620,13 +3025,11 @@ def _handle_print(self, text: str) -> None: set_wrap = can_advance and min_col == 0 and c_col == scr.cols - 1 if set_wrap and c_row == 0 and bottom == 0: scr._rows[0].wrapped = True - bump_row_gen(scr._rows[0]) self._linefeed(scr) if set_wrap and not (c_row == 0 and bottom == 0): wrap_idx = c_row - 1 if c_row == bottom else c_row if 0 <= wrap_idx < scr.rows: scr._rows[wrap_idx].wrapped = True - bump_row_gen(scr._rows[wrap_idx]) self._set_cursor(scr, scr._cur_row, min_col, pending_wrap=False) c_row = scr._cur_row c_col = scr._cur_col @@ -2805,9 +3208,9 @@ def _handle_execute(self, byte: int) -> None: elif byte == 0x0F: # SI -> G0 self._gl = 0 - def _save_cursor(self) -> None: + def _capture_saved_cursor(self) -> _SavedCursor: scr = self._screens.active - saved = _SavedCursor( + return _SavedCursor( row=scr._cur_row, col=scr._cur_col, pending_wrap=scr._pending_wrap, @@ -2820,24 +3223,26 @@ def _save_cursor(self) -> None: self._g_sets[3], ), gl=self._gl, + single_shift=self._single_shift, protected=self._protected, ) - if self._screens.active_is_alt: - self._saved_alt = saved - else: - self._saved_primary = saved - def _restore_cursor(self) -> None: + def _apply_saved_cursor( + self, + saved: _SavedCursor, + *, + restore_decom: bool = True, + ) -> None: self._before_mutate() scr = self._screens.active - saved = self._saved_alt if self._screens.active_is_alt else self._saved_primary self._style = saved.style self._protected = saved.protected self._sync_pen_cache() self._g_sets = list(saved.g_sets) self._gl = saved.gl - self._single_shift = None - self._modes.set_mode(Mode.DECOM, enabled=saved.decom) + self._single_shift = saved.single_shift + if restore_decom: + self._modes.set_mode(Mode.DECOM, enabled=saved.decom) restored_wrap = ( False if self._profile.pending_wrap_phantom_col else saved.pending_wrap ) @@ -2848,6 +3253,24 @@ def _restore_cursor(self) -> None: pending_wrap=restored_wrap, ) + def _save_cursor(self) -> None: + saved = self._capture_saved_cursor() + if self._profile.separate_alt_save_cursor: + self._saved_decsc = saved + elif self._screens.active_is_alt: + self._saved_alt = saved + else: + self._saved_primary = saved + + def _restore_cursor(self) -> None: + if self._profile.separate_alt_save_cursor: + saved = self._saved_decsc + else: + saved = ( + self._saved_alt if self._screens.active_is_alt else self._saved_primary + ) + self._apply_saved_cursor(saved) + def _handle_esc(self, intermediates: bytes, final: int) -> None: self._last_printed = "" scr = self._screens.active @@ -2867,7 +3290,7 @@ def _handle_esc(self, intermediates: bytes, final: int) -> None: top, bottom, left, right = self._effective_margins(scr) keep_wrap = self._profile.pending_wrap_phantom_col and scr._pending_wrap if scr._cur_row == top and left <= scr._cur_col <= right: - bce_w, bce_e = self._bce_pair() + bce_w, _ = self._bce_pair() scr.scroll_down( 1, top=top, @@ -2875,7 +3298,6 @@ def _handle_esc(self, intermediates: bytes, final: int) -> None: left=left, right=right, bce_word=bce_w, - bce_ext=bce_e, ) self._notify_erase( Rect(top, left, 1, right - left + 1), @@ -2926,57 +3348,82 @@ def _handle_esc(self, intermediates: bytes, final: int) -> None: self._unhandled("esc", f"ESC {inter_s}{chr(final)}") def _apply_mode(self, code: int, *, private: bool, enabled: bool) -> None: + if not (0 <= code < DEC_PRIVATE_MASK): + return raw = (DEC_PRIVATE_MASK | code) if private else code try: mode = Mode(raw) except ValueError: return - was_set = self._modes.is_set(mode) if mode == Mode.SYNCHRONIZED_OUTPUT: - if enabled == was_set: - return - self._invalidate_cache() - self._modes.set_mode(mode, enabled=enabled) - if enabled: - self._sync_generation += 1 - self._sync_hold_pending = True - self._held_snapshot = None - self._held_sync_token = None - self._step_event |= StopOn.SYNC_START - else: - self._sync_hold_pending = False - self._held_snapshot = None - self._held_sync_token = None - self._step_event |= StopOn.SYNC_END - self._emit_event( - RenderHoldChanged( - active=enabled, - sync_generation=self._sync_generation, - ), - ) + self._set_synchronized_output(enabled) + return + + if mode == Mode.DECLRMM and not self._profile.declrmm_enabled: + return + + if mode == Mode.DECSC_1048 and self._profile.separate_alt_save_cursor: + return + + if mode == Mode.MOUSE_SGR_PIXELS and ( + self._profile.cell_width_px <= 0 or self._profile.cell_height_px <= 0 + ): return if mode in ALT_SCREEN_MODES: self._before_mutate() self._clear_cluster_anchor() + def_g: tuple[Charset, Charset, Charset, Charset] = ( + "B", + self._profile.default_g1_charset, + "B", + "B", + ) + cur_vis = self._modes.is_set(Mode.DECTCEM) if enabled and not self._screens.active_is_alt: if mode == Mode.ALT_SCREEN: - self._save_cursor() + self._saved_primary = self._capture_saved_cursor() + self._has_alt_saved = True + self._single_shift = None self._screens.alternate.reset() + self._screens.alternate._cur_visible = cur_vis + self._saved_alt = _SavedCursor(g_sets=def_g) self._screens.active_is_alt = True self._epoch += 1 self._modes.sync_alt_screen(active_is_alt=True, entered_via=mode) + elif enabled and self._screens.active_is_alt: + if ( + mode == Mode.ALT_SCREEN + and not self._profile.separate_alt_save_cursor + ): + self._saved_alt = self._capture_saved_cursor() elif not enabled and self._screens.active_is_alt: if mode in (Mode.ALT_SCREEN_1047, Mode.ALT_SCREEN): self._screens.alternate.reset() + self._screens.alternate._cur_visible = cur_vis + self._saved_alt = _SavedCursor(g_sets=def_g) + self._single_shift = None + self._screens.primary._cur_visible = cur_vis self._screens.active_is_alt = False self._epoch += 1 self._modes.sync_alt_screen(active_is_alt=False) - if mode == Mode.ALT_SCREEN: - self._restore_cursor() + if mode == Mode.ALT_SCREEN and ( + not self._profile.separate_alt_save_cursor or self._has_alt_saved + ): + self._apply_saved_cursor( + self._saved_primary, + restore_decom=not self._profile.separate_alt_save_cursor, + ) elif not enabled: self._modes.sync_alt_screen(active_is_alt=False) + if mode == Mode.ALT_SCREEN and ( + not self._profile.separate_alt_save_cursor or self._has_alt_saved + ): + self._apply_saved_cursor( + self._saved_primary, + restore_decom=not self._profile.separate_alt_save_cursor, + ) return self._before_mutate() @@ -2984,7 +3431,8 @@ def _apply_mode(self, code: int, *, private: bool, enabled: bool) -> None: scr = self._screens.active if mode == Mode.DECTCEM: - scr._cur_visible = enabled + self._screens.primary._cur_visible = enabled + self._screens.alternate._cur_visible = enabled elif mode == Mode.DECOM: top, _, left, _ = self._effective_margins(scr) self._set_cursor( @@ -3044,7 +3492,6 @@ def _erase_display( if scroll_clear: scr.push_scrollback_and_clear( bce_w, - bce_e, include_cursor_row=False, ) self._notify_erase(Rect(0, 0, scr.rows, scr.cols), cause) @@ -3129,7 +3576,7 @@ def _erase_display( self._notify_erase(Rect(0, 0, scr.rows, scr.cols), cause) elif mode == 22 and not selective: if not self._screens.active_is_alt: - scr.push_scrollback_and_clear(bce_w, bce_e) + scr.push_scrollback_and_clear(bce_w) else: for r in range(scr.rows): scr._rows[r].clear_range(0, scr.cols, bce_w, bce_e) @@ -3228,6 +3675,10 @@ def _handle_csi( ) -> None: prev_printed = self._last_printed self._last_printed = "" + if params.colon_mask != 0 and not ( + prefix == 0 and not intermediates and final == ord("m") + ): + return scr = self._screens.active top, bottom, left, right = self._effective_margins(scr) @@ -3266,15 +3717,30 @@ def _handle_csi( # DECRQM: CSI ? Ps $ p or CSI Ps $ p if intermediates == b"$" and final == ord("p"): + if prefix not in (0, ord("?")) or len(params.values) > 1: + return private = prefix == ord("?") code = params.raw_or_default(0, 0) - pm = int( - self._modes.decrpm( - code, - private=private, - active_is_alt=self._screens.active_is_alt, - ), - ) + if private and ( + (code == 69 and not self._profile.declrmm_enabled) + or (code == 1048 and self._profile.separate_alt_save_cursor) + or ( + code == 1016 + and ( + self._profile.cell_width_px <= 0 + or self._profile.cell_height_px <= 0 + ) + ) + ): + pm = int(DecrpmValue.NOT_RECOGNIZED) + else: + pm = int( + self._modes.decrpm( + code, + private=private, + active_is_alt=self._screens.active_is_alt, + ), + ) q = "?" if private else "" self._emit_reply(f"\x1b[{q}{code};{pm}$y".encode("ascii")) return @@ -3352,11 +3818,48 @@ def _handle_csi( scheme = self._profile.color_scheme self._emit_reply(f"\x1b[?997;{int(scheme)}n".encode("ascii")) self._emit_event(ColorSchemeQueried(scheme=scheme)) + elif final == ord("m"): # XTQMODKEYS: CSI ? Pp m + if len(params.values) == 1 and params.raw_or_default(0, -1) == 4: + self._emit_reply( + f"\x1b[>4;{scr._modify_other_keys}m".encode("ascii"), + ) + elif final == ord("S") and 1 <= len(params.values) <= 4: # XTSMGRAPHICS + pi = params.raw_or_default(0, 0) + self._emit_reply(f"\x1b[?{pi};3S".encode("ascii")) return if prefix != 0: - if prefix == ord(">") and final in (ord("m"), ord("n")): - # XTMODKEYS: accept quietly + if prefix == ord(">") and final == ord("m"): + if not params.values: + if scr._modify_other_keys != 0: + self._before_mutate() + scr._modify_other_keys = 0 + elif len(params.values) <= 2: + pp = params.raw_or_default(0, 0) + if pp == 0 and len(params.values) == 1: + if scr._modify_other_keys != 0: + self._before_mutate() + scr._modify_other_keys = 0 + elif pp == 4: + pv = ( + params.raw_or_default(1, 0) + if len(params.values) == 2 + else 0 + ) + if pv in (0, 1, 2) and scr._modify_other_keys != pv: + self._before_mutate() + scr._modify_other_keys = pv + return + if prefix == ord(">") and final == ord("n"): + if ( + not params.values + or ( + len(params.values) == 1 + and params.raw_or_default(0, -1) in (0, 4) + ) + ) and scr._modify_other_keys != 0: + self._before_mutate() + scr._modify_other_keys = 0 return self._unhandled("csi", f"CSI {chr(prefix)}{chr(final)}") return @@ -3484,62 +3987,68 @@ def _handle_csi( if self._profile.pending_wrap_phantom_col and scr._pending_wrap: return self._before_mutate() - n = params.get(0, 1) - bce_w, bce_e = self._bce_pair() - scr.heal_before_edit(c_row, c_col, right + 1) - scr._rows[c_row].insert_blanks( - c_col, - n, - left=left, - right=right, - bce_word=bce_w, - bce_ext=bce_e, - ) - if scr._gfx is not None and scr._gfx.has_sixels and left <= c_col <= right: - scr._gfx.erase_sixel_rect( - row=c_row, - col=c_col, - rows=1, - cols=right - c_col + 1, - scrolled_total=scr._scrolled_total, - policy=self._profile.sixel_erase_policy, + if left <= c_col <= right: + n = params.get(0, 1) + bce_w, bce_e = self._bce_pair() + scr.heal_before_edit(c_row, c_col, right + 1) + scr._rows[c_row].insert_blanks( + c_col, + n, + left=left, + right=right, + bce_word=bce_w, + bce_ext=bce_e, ) + if scr._gfx is not None and scr._gfx.has_sixels: + scr._gfx.erase_sixel_rect( + row=c_row, + col=c_col, + rows=1, + cols=right - c_col + 1, + scrolled_total=scr._scrolled_total, + policy=self._profile.sixel_erase_policy, + ) self._set_cursor(scr, c_row, c_col, pending_wrap=False) elif ch_final == "P": # DCH if self._profile.pending_wrap_phantom_col and scr._pending_wrap: return self._before_mutate() - n = params.get(0, 1) - bce_w, bce_e = self._bce_pair() - scr.heal_before_edit(c_row, c_col, right + 1) - if c_col == 0 and left == 0 and c_row > 0 and scr._rows[c_row - 1].wrapped: - scr._rows[c_row - 1].wrapped = False - bump_row_gen(scr._rows[c_row - 1]) - scr._rows[c_row].delete_cells( - c_col, - n, - left=left, - right=right, - bce_word=bce_w, - bce_ext=bce_e, - ) - if right == scr.cols - 1: - scr._rows[c_row].wrapped = False - if scr._gfx is not None and scr._gfx.has_sixels and left <= c_col <= right: - scr._gfx.erase_sixel_rect( - row=c_row, - col=c_col, - rows=1, - cols=right - c_col + 1, - scrolled_total=scr._scrolled_total, - policy=self._profile.sixel_erase_policy, + if left <= c_col <= right: + n = params.get(0, 1) + bce_w, bce_e = self._bce_pair() + scr.heal_before_edit(c_row, c_col, right + 1) + if ( + c_col == 0 + and left == 0 + and c_row > 0 + and scr._rows[c_row - 1].wrapped + ): + scr._rows[c_row - 1].wrapped = False + scr._rows[c_row].delete_cells( + c_col, + n, + left=left, + right=right, + bce_word=bce_w, + bce_ext=bce_e, ) + if right == scr.cols - 1: + scr._rows[c_row].wrapped = False + if scr._gfx is not None and scr._gfx.has_sixels: + scr._gfx.erase_sixel_rect( + row=c_row, + col=c_col, + rows=1, + cols=right - c_col + 1, + scrolled_total=scr._scrolled_total, + policy=self._profile.sixel_erase_policy, + ) self._set_cursor(scr, c_row, c_col, pending_wrap=False) elif ch_final == "L": # IL if top <= c_row <= bottom and left <= c_col <= right: self._before_mutate() n = params.get(0, 1) - bce_w, bce_e = self._bce_pair() + bce_w, _ = self._bce_pair() keep_wrap = ( not self._profile.il_dl_resets_col and self._profile.pending_wrap_phantom_col @@ -3552,7 +4061,6 @@ def _handle_csi( left=left, right=right, bce_word=bce_w, - bce_ext=bce_e, is_line_op=True, ) self._notify_erase( @@ -3565,7 +4073,7 @@ def _handle_csi( if top <= c_row <= bottom and left <= c_col <= right: self._before_mutate() n = params.get(0, 1) - bce_w, bce_e = self._bce_pair() + bce_w, _ = self._bce_pair() keep_wrap = ( not self._profile.il_dl_resets_col and self._profile.pending_wrap_phantom_col @@ -3579,7 +4087,6 @@ def _handle_csi( right=right, save_history=False, bce_word=bce_w, - bce_ext=bce_e, is_line_op=True, ) self._notify_erase( @@ -3595,23 +4102,33 @@ def _handle_csi( self._set_cursor(scr, c_row, target_col, pending_wrap=keep_wrap) elif ch_final == "S": # SU self._before_mutate() - n = params.get(0, 1) - bce_w, bce_e = self._bce_pair() + region_h = bottom - top + 1 + n = min(params.get(0, 1), region_h) + prev_scrolled = scr._scrolled_total + bce_w, _ = self._bce_pair() scr.scroll_up( n, top=top, bottom=bottom, left=left, right=right, - save_history=False, + save_history=not self._screens.active_is_alt, bce_word=bce_w, - bce_ext=bce_e, ) + hist_delta = scr._scrolled_total - prev_scrolled + if hist_delta > 0 and left == 0 and right == scr.cols - 1: + self._remap_prompt_zones_on_scroll( + prev_scrolled, + top=top, + bottom=bottom, + rows=scr.rows, + hist_delta=hist_delta, + ) self._notify_erase( Rect( max(top, bottom - n + 1), left, - min(n, bottom - top + 1), + min(n, region_h), right - left + 1, ), EraseCause.SCROLL, @@ -3620,7 +4137,7 @@ def _handle_csi( elif ch_final == "T": # SD self._before_mutate() n = params.get(0, 1) - bce_w, bce_e = self._bce_pair() + bce_w, _ = self._bce_pair() scr.scroll_down( n, top=top, @@ -3628,7 +4145,6 @@ def _handle_csi( left=left, right=right, bce_word=bce_w, - bce_ext=bce_e, ) self._notify_erase( Rect(top, left, min(n, bottom - top + 1), right - left + 1), @@ -3673,25 +4189,26 @@ def _handle_csi( ) elif ch_final == "s": # DECSLRM (when ?69 set) or SCOSC if self._modes.is_set(Mode.DECLRMM): - l_arg = params.get(0, 1) - 1 - r_arg = params.get(1, scr.cols) - 1 - l_clamped = max(0, min(scr.cols - 1, l_arg)) - r_clamped = max(0, min(scr.cols - 1, r_arg)) - if l_clamped < r_clamped: - sr = scr.scroll_region - scr.scroll_region = ScrollRegion( - top=sr.top, - bottom=sr.bottom, - left=l_clamped, - right=r_clamped, - ) - decom = self._modes.is_set(Mode.DECOM) - self._set_cursor( - scr, - sr.top if decom else 0, - l_clamped if decom else 0, - ) - else: + if len(params.values) <= 2: + l_arg = params.get(0, 1) - 1 + r_arg = params.get(1, scr.cols) - 1 + l_clamped = max(0, min(scr.cols - 1, l_arg)) + r_clamped = max(0, min(scr.cols - 1, r_arg)) + if l_clamped < r_clamped: + sr = scr.scroll_region + scr.scroll_region = ScrollRegion( + top=sr.top, + bottom=sr.bottom, + left=l_clamped, + right=r_clamped, + ) + decom = self._modes.is_set(Mode.DECOM) + self._set_cursor( + scr, + sr.top if decom else 0, + l_clamped if decom else 0, + ) + elif not self._profile.declrmm_enabled or not params.values: self._save_cursor() elif ch_final == "u": # SCORC self._restore_cursor() @@ -3728,15 +4245,13 @@ def _handle_csi( if op == 18: # report text area size in chars self._emit_reply(f"\x1b[8;{scr.rows};{scr.cols}t".encode("ascii")) elif op == 14: # report text area size in pixels - px_h = scr.rows * self._profile.cell_height_px - px_w = scr.cols * self._profile.cell_width_px + px_h = scr.rows * max(0, self._profile.cell_height_px) + px_w = scr.cols * max(0, self._profile.cell_width_px) self._emit_reply(f"\x1b[4;{px_h};{px_w}t".encode("ascii")) elif op == 16: # report cell size in pixels - self._emit_reply( - f"\x1b[6;{self._profile.cell_height_px};{self._profile.cell_width_px}t".encode( - "ascii" - ), - ) + ch_px = max(0, self._profile.cell_height_px) + cw_px = max(0, self._profile.cell_width_px) + self._emit_reply(f"\x1b[6;{ch_px};{cw_px}t".encode("ascii")) elif op == 21 and self._policy.allow_title_report: safe_title = "".join( ch for ch in self._title if " " <= ch <= "~" and ch != "\\" @@ -3778,12 +4293,17 @@ def _update_cwd(self, raw_uri: str, *, from_osc7: bool = True) -> None: self._cwd = safe_uri self._emit_event(WorkingDirectoryChanged(uri=safe_uri, path=safe_uri)) return - parsed = urllib.parse.urlsplit(cleaned) + try: + parsed = urllib.parse.urlsplit(cleaned) + raw_host = urllib.parse.unquote(parsed.hostname or "").lower() + except ValueError: + self._cwd = "" + self._emit_event(WorkingDirectoryChanged(uri=safe_uri, path="")) + return if parsed.scheme.lower() != "file" or not parsed.path.startswith("/"): self._cwd = "" self._emit_event(WorkingDirectoryChanged(uri=safe_uri, path="")) return - raw_host = urllib.parse.unquote(parsed.hostname or "").lower() allowed_hosts = ( self._policy.osc7_hosts if self._policy.osc7_hosts is not None @@ -3794,7 +4314,10 @@ def _update_cwd(self, raw_uri: str, *, from_osc7: bool = True) -> None: self._cwd = "" self._emit_event(WorkingDirectoryChanged(uri=safe_uri, path="")) return - decoded_path = os.fsdecode(raw_path) + try: + decoded_path = os.fsdecode(raw_path) + except UnicodeDecodeError: + decoded_path = raw_path.decode("utf-8", errors="surrogateescape") if raw_host in allowed_hosts: self._cwd = decoded_path else: @@ -3818,6 +4341,45 @@ def _handle_osc(self, code: int, data: bytes, terminator: bytes) -> None: self._emit_event(TitleChanged(title=text)) elif code == 1: return + elif code == 4: + if not data: + return + pos = 0 + n_data = len(data) + while pos <= n_data: + semi1 = data.find(b";", pos) + if semi1 == -1: + break + pal_idx = _parse_ascii_uint_bytes(data[pos:semi1], max_val=255) + if pal_idx is None: + break + semi2 = data.find(b";", semi1 + 1) + if semi2 == -1: + spec_b = data[semi1 + 1 :] + pos = n_data + 1 + else: + spec_b = data[semi1 + 1 : semi2] + pos = semi2 + 1 + if spec_b == b"?": + if self._policy.allow_color_queries and ( + self._on_pty_write is not None + or len(self._replies) + 24 <= self._limits.max_reply_bytes + ): + rgb_val = self._palette_overrides.get(pal_idx) + if rgb_val is None: + rgb_val = _resolve_color_rgb( + IndexedColor(pal_idx), + (0, 0, 0), + ) + reply = (f"\x1b]4;{pal_idx};{_format_osc_rgb(rgb_val)}").encode( + "ascii" + ) + self._emit_reply(reply + out_term) + continue + parsed_pal = _parse_osc_rgb(spec_b) + if parsed_pal is None: + break + self._palette_overrides[pal_idx] = parsed_pal elif code == 7: self._update_cwd(data.decode("utf-8", errors="replace"), from_osc7=True) elif code == 8: @@ -3840,39 +4402,98 @@ def _handle_osc(self, code: int, data: bytes, terminator: bytes) -> None: elif code == 9: text = data.decode("utf-8", errors="replace") parts = text.split(";") - if len(parts) >= 2 and parts[0] == "4" and parts[1].isdigit(): - self._before_mutate() - sub = int(parts[1]) - prog = int(parts[2]) if len(parts) >= 3 and parts[2].isdigit() else None - changed, status = self._status_store.apply_osc_9_4(sub, prog) - if changed: - self._aux_revision += 1 - self._emit_event(ProgramStatusChanged(status=status, task_id="")) + if len(parts) >= 2 and parts[0] == "4": + sub = _parse_ascii_uint(parts[1], max_val=255) + if sub is not None: + self._before_mutate() + prog = ( + _parse_ascii_uint(parts[2], max_val=1_000) + if len(parts) >= 3 + else None + ) + changed, status = self._status_store.apply_osc_9_4(sub, prog) + if changed: + self._aux_revision += 1 + self._emit_event( + ProgramStatusChanged(status=status, task_id="") + ) elif len(parts) >= 2 and parts[0] == "9": self._update_cwd(";".join(parts[1:]), from_osc7=False) - elif code in (10, 11): - if data == b"?": - if self._policy.allow_color_queries: - r, g, b = self._fg_rgb if code == 10 else self._bg_rgb - reply = ( - f"\x1b]{code};rgb:{r:02x}{r:02x}/{g:02x}{g:02x}/{b:02x}{b:02x}" - ).encode("ascii") - self._emit_reply(reply + out_term) + elif code in (10, 11, 12): + if not data: return - parsed_rgb = _parse_osc_rgb(data) - if parsed_rgb is not None: - if code == 10: - self._fg_rgb = parsed_rgb + cur_code = code + pos = 0 + n_data = len(data) + while cur_code <= 12 and pos <= n_data: + semi = data.find(b";", pos) + if semi == -1: + spec_b = data[pos:] + pos = n_data + 1 + else: + spec_b = data[pos:semi] + pos = semi + 1 + if spec_b == b"?": + if self._policy.allow_color_queries and ( + self._on_pty_write is not None + or len(self._replies) + 23 <= self._limits.max_reply_bytes + ): + cur_rgb = ( + self._fg_rgb + if cur_code == 10 + else (self._bg_rgb if cur_code == 11 else self._cursor_rgb) + ) + reply = (f"\x1b]{cur_code};{_format_osc_rgb(cur_rgb)}").encode( + "ascii" + ) + self._emit_reply(reply + out_term) else: - self._bg_rgb = parsed_rgb - elif code == 12: + parsed_rgb = _parse_osc_rgb(spec_b) + if parsed_rgb is None: + break + if cur_code == 10: + self._fg_rgb = parsed_rgb + elif cur_code == 11: + self._bg_rgb = parsed_rgb + else: + self._cursor_rgb = parsed_rgb + cur_code += 1 + elif code in (99, 777): return + elif code == 104: + if not self._palette_overrides: + return + if not data: + self._palette_overrides.clear() + return + saw_nonempty = False + pos = 0 + n_data = len(data) + while pos <= n_data: + semi = data.find(b";", pos) + if semi == -1: + tok = data[pos:] + pos = n_data + 1 + else: + tok = data[pos:semi] + pos = semi + 1 + if not tok: + continue + saw_nonempty = True + pal_idx = _parse_ascii_uint_bytes(tok, max_val=255) + if pal_idx is not None: + self._palette_overrides.pop(pal_idx, None) + if not saw_nonempty: + self._palette_overrides.clear() elif code == 110: - self._fg_rgb = self._profile.fg_rgb + if not data: + self._fg_rgb = self._profile.fg_rgb elif code == 111: - self._bg_rgb = self._profile.bg_rgb + if not data: + self._bg_rgb = self._profile.bg_rgb elif code == 112: - return + if not data: + self._cursor_rgb = self._profile.cursor_rgb elif code == 52: semi = data.find(b";") if semi == -1: @@ -3899,12 +4520,12 @@ def _handle_osc(self, code: int, data: bytes, terminator: bytes) -> None: kind = PromptKind(raw_kind) exit_code: int | None = None is_continuation = any(p.strip() == "k=s" for p in parts[1:]) - if ( - kind == PromptKind.COMMAND_FINISHED - and len(parts) >= 2 - and parts[1].lstrip("-").isdigit() - ): - exit_code = int(parts[1]) + if kind == PromptKind.COMMAND_FINISHED and len(parts) >= 2: + exit_code = _parse_ascii_int( + parts[1], + min_val=-2_147_483_648, + max_val=2_147_483_647, + ) if not self._screens.active_is_alt: abs_r = self._screens.primary.scrolled_total + scr._cur_row zone = PromptZone( @@ -4076,11 +4697,14 @@ def _handle_dcs( else: post_r = self._advance_rows(scr, s_rows, final_col=0) eff_rows = min(s_rows, max(1, scr.rows - post_r)) - min_sixel_abs = ( - scr._scrolled_total + (top if in_margins else 0) - if scr._scrolled_total == pre_scrolled - else scr._scrolled_total - len(scr._history) - ) + if in_margins and top > 0: + min_sixel_abs = scr._scrolled_total + top + elif scr._scrolled_total == pre_scrolled: + min_sixel_abs = scr._scrolled_total + ( + top if in_margins else 0 + ) + else: + min_sixel_abs = scr._scrolled_total - len(scr._history) gfx.commit_sixel( payload_len=len(data), width_px=w_px, diff --git a/src/libvt/testing.py b/src/libvt/testing.py index 58656f3..e5b2f44 100644 --- a/src/libvt/testing.py +++ b/src/libvt/testing.py @@ -39,7 +39,7 @@ def _format_row_cells(snap: Snapshot, row_idx: int, width: int) -> str: parts.append(" ") cols_used += 1 break - parts.append(sanitize_terminal_text(row.chars[c])) + parts.append(sanitize_terminal_text(row.char_at(c))) cols_used += cell_w c += 1 if cols_used < width: diff --git a/src/libvt/tmux.py b/src/libvt/tmux.py index 4caea3d..86fbe29 100644 --- a/src/libvt/tmux.py +++ b/src/libvt/tmux.py @@ -6,9 +6,10 @@ import contextlib import enum import re +import secrets from dataclasses import dataclass -from libvt._grid import WidthRole, _Row, bump_row_gen, raw_width_bits +from libvt._grid import WidthRole, _Row, raw_width_bits from libvt.config import ( DEFAULT_LIMITS, TMUX_CAPTURE_POLICY, @@ -16,16 +17,19 @@ Limits, Policy, Profile, + _parse_tmux_version, ) from libvt.events import PromptKind, PromptZone from libvt.modes import DEC_PRIVATE_MASK, Mode -from libvt.parser import CsiParams, Parser +from libvt.parser import CsiParams, Parser, _parse_ascii_int, _parse_ascii_uint from libvt.screen import Screen, ScrollRegion from libvt.style import DEFAULT_STYLE from libvt.terminal import Snapshot, Terminal -type CaptureInput = str | bytes | collections.abc.Sequence[str] +#: Accepted input payload shapes for ``tmux capture-pane`` decoders. +type CaptureInput = str | bytes | bytearray | collections.abc.Sequence[str] +#: Format string passed to ``tmux display-message -p`` for pane metadata. TMUX_METADATA_FORMAT: str = ( "#{pane_width}\t#{pane_height}\t#{cursor_x}\t#{cursor_y}\t" "#{cursor_flag}\t#{alternate_on}\t#{alternate_saved_x}\t" @@ -38,9 +42,12 @@ "#{pane_current_path}\t#{pane_title}" ) -_FLAG_TOKEN_RE = re.compile(r"^(?:-|D?H?O?P?W?X?)$") +_FLAG_TOKEN_RE = re.compile(r"^(?:-|D?H?O?P?W?X?)\Z", re.ASCII) +_NONCE_RE = re.compile(r"^[0-9A-Za-z_-]{8,128}\Z", re.ASCII) _OCTAL_ESCAPE_RE = re.compile(rb"\\([0-3][0-7]{2})") _TMUX_UINT_MAX = 0xFFFF_FFFF +_TMUX_MAX_DIM = 10_000 +_TMUX_MAX_HISTORY = 1_000_000 _BASE_UNEXPOSED_FIELDS: frozenset[str] = frozenset( { @@ -58,12 +65,19 @@ class TmuxLineFlags(enum.IntFlag): """Per-line flags emitted by ``tmux capture-pane -F`` (``tmux >= 3.8``).""" + #: No per-line flags set (``-``). NONE = 0 + #: Pane exited / dead marker (``D``). DEAD = 1 + #: Line contains an ``OSC 8`` hyperlink (``H``). HYPERLINK = 2 + #: ``OSC 133;C`` command output start (``O``). START_OUTPUT = 4 + #: ``OSC 133;A`` shell prompt start (``P``). START_PROMPT = 8 + #: Line soft-wrapped onto the next grid row (``W``). WRAPPED = 16 + #: Line uses extended grid cell storage (``X``). EXTENDED = 32 @@ -135,26 +149,12 @@ def unescape_tmux_control_output(data: collections.abc.Buffer | str) -> bytes: def _opt_int(raw: str, default: int) -> int: - s = raw.strip() - if not s: - return default - try: - return int(s) - except ValueError: - return default + val = _parse_ascii_int(raw.strip(), min_val=-2_147_483_648, max_val=2_147_483_647) + return default if val is None else val def _opt_saved_coord(raw: str) -> int | None: - s = raw.strip() - if not s: - return None - try: - val = int(s) - except ValueError: - return None - if val < 0 or val >= _TMUX_UINT_MAX: - return None - return val + return _parse_ascii_uint(raw.strip(), max_val=_TMUX_UINT_MAX - 1) def _opt_bool(raw: str, *, default: bool = False) -> bool: @@ -284,8 +284,8 @@ def from_format_line(cls, line: str) -> TmuxPaneMetadata: parts = cleaned.split("\t", 26) if len(parts) < 27: parts.extend([""] * (27 - len(parts))) - cols = max(1, _opt_int(parts[0], 80)) - rows = max(1, _opt_int(parts[1], 24)) + cols = min(_TMUX_MAX_DIM, max(1, _opt_int(parts[0], 80))) + rows = min(_TMUX_MAX_DIM, max(1, _opt_int(parts[1], 24))) priv_raw = parts[19].strip() priv_modes: set[int] = set() @@ -295,8 +295,9 @@ def from_format_line(cls, line: str) -> TmuxPaneMetadata: elif priv_raw: for tok in priv_raw.split(","): p_str = tok.strip().lstrip("?") - if p_str.isdigit(): - priv_modes.add(int(p_str)) + p_val = _parse_ascii_uint(p_str, max_val=65_535) + if p_val is not None: + priv_modes.add(p_val) focus_on = 1004 in priv_modes tabs_raw = parts[20].strip() @@ -304,14 +305,15 @@ def from_format_line(cls, line: str) -> TmuxPaneMetadata: if tabs_raw: parsed_tabs: list[int] = [] for tok in tabs_raw.split(","): - t_str = tok.strip() - if t_str.isdigit(): - parsed_tabs.append(int(t_str)) + t_val = _parse_ascii_uint(tok.strip(), max_val=65_535) + if t_val is not None: + parsed_tabs.append(t_val) tabs = tuple(sorted(set(parsed_tabs))) gen_raw = parts[24].strip() - out_gen = int(gen_raw) if gen_raw.isdigit() else None + out_gen = _parse_ascii_uint(gen_raw, max_val=(1 << 64) - 1) sr_low_raw = parts[9].strip() - sr_lower = int(sr_low_raw) if sr_low_raw.isdigit() else (rows - 1) + sr_val = _parse_ascii_uint(sr_low_raw, max_val=65_535) + sr_lower = sr_val if sr_val is not None else (rows - 1) return cls( cols=cols, rows=rows, @@ -335,8 +337,8 @@ def from_format_line(cls, line: str) -> TmuxPaneMetadata: focus_events_flag=focus_on, private_modes=frozenset(priv_modes), pane_tabs=tabs, - history_size=_opt_int(parts[21], 0), - history_limit=max(0, _opt_int(parts[22], 2_000)), + history_size=max(0, min(_TMUX_MAX_HISTORY, _opt_int(parts[21], 0))), + history_limit=max(0, min(_TMUX_MAX_HISTORY, _opt_int(parts[22], 2_000))), synchronized=_opt_bool(parts[23]) or (2026 in priv_modes), output_generation=out_gen, cwd=parts[25], @@ -352,7 +354,7 @@ class CaptureCompleteness: ---------- exact_cells : bool ``True`` when cell glyphs, styles, and tab expansions were decoded from - ``-e -p -N`` output. + ``-e -p -N`` (or ``-e -p -N -T``) output. exact_wraps : bool ``True`` when soft-wrap flags came from ``-F`` or an exact ``-J`` companion capture. @@ -395,6 +397,72 @@ class TmuxCaptureResult: line_flags: tuple[TmuxLineFlags, ...] +def _rewrite_tmux_overline_sgr(params: CsiParams) -> CsiParams: + """Rewrite ``tmux`` ``grid_string_cells_code`` ``5:3`` SGR groups to ``53``.""" + if params.colon_mask == 0 or 5 not in params.values: + return params + vals = params.values + n = len(vals) + out_vals: list[int] = [] + out_colon = 0 + out_omitted = 0 + changed = False + idx = 0 + while idx < n: + g_end = idx + 1 + while g_end < n and ((params.colon_mask >> g_end) & 1): + g_end += 1 + g_len = g_end - idx + head = vals[idx] + head_omitted = bool((params.omitted_mask >> idx) & 1) + if g_len == 1 and not head_omitted and head in (38, 48, 58) and g_end < n: + nxt_end = g_end + 1 + while nxt_end < n and ((params.colon_mask >> nxt_end) & 1): + nxt_end += 1 + mode_val = vals[g_end] + extra_groups = 2 if mode_val == 5 else (4 if mode_val == 2 else 1) + skip_end = nxt_end + complete = True + for _ in range(extra_groups - 1): + if skip_end >= n: + complete = False + break + skip_end += 1 + while skip_end < n and ((params.colon_mask >> skip_end) & 1): + skip_end += 1 + if not complete: + skip_end = nxt_end + for k in range(idx, skip_end): + pos = len(out_vals) + out_vals.append(vals[k]) + if (params.colon_mask >> k) & 1: + out_colon |= 1 << pos + if (params.omitted_mask >> k) & 1: + out_omitted |= 1 << pos + idx = skip_end + continue + if ( + g_len == 2 + and not head_omitted + and head == 5 + and vals[idx + 1] == 3 + and not ((params.omitted_mask >> (idx + 1)) & 1) + ): + out_vals.append(53) + changed = True + idx = g_end + continue + for k in range(idx, g_end): + pos = len(out_vals) + out_vals.append(vals[k]) + if (params.colon_mask >> k) & 1: + out_colon |= 1 << pos + if (params.omitted_mask >> k) & 1: + out_omitted |= 1 << pos + idx = g_end + return CsiParams(tuple(out_vals), out_colon, out_omitted) if changed else params + + class _CaptureRowSink: r"""Internal parser sink expanding ``GRID_FLAG_TAB`` ``\t`` with active SGR.""" @@ -415,8 +483,9 @@ def on_print(self, text: str) -> None: def on_execute(self, byte: int) -> None: if byte == 0x09: - cur_col = self._scratch.screen._cur_col - mod_col = cur_col % self._cols if self._cols > 0 else cur_col + scr = self._scratch.screen + eff_col = 0 if scr._pending_wrap else scr._cur_col + mod_col = eff_col % self._cols if self._cols > 0 else eff_col nxt_mod = next( (t_col for t_col in self._tabstops if mod_col < t_col < self._cols), max(mod_col, self._cols - 1), @@ -428,7 +497,7 @@ def on_execute(self, byte: int) -> None: self._scratch._handle_execute(byte) def on_esc(self, intermediates: bytes, final: int) -> None: - self._scratch._handle_esc(intermediates, final) + return def on_csi( self, @@ -437,10 +506,17 @@ def on_csi( intermediates: bytes, final: int, ) -> None: - self._scratch._handle_csi(prefix, params, intermediates, final) + if prefix == 0 and not intermediates and final == 0x6D: + self._scratch._handle_csi( + prefix, + _rewrite_tmux_overline_sgr(params), + intermediates, + final, + ) def on_osc(self, code: int, data: bytes, terminator: bytes) -> None: - self._scratch._handle_osc(code, data, terminator) + if code == 8: + self._scratch._handle_osc(code, data, terminator) def on_dcs( self, @@ -450,10 +526,10 @@ def on_dcs( final: int, data: bytes, ) -> None: - self._scratch._handle_dcs(prefix, params, intermediates, final, data) + return def on_apc(self, data: bytes) -> None: - self._scratch._handle_apc(data) + return def _split_capture_lines(raw: CaptureInput) -> list[str]: @@ -466,30 +542,32 @@ def _split_capture_lines(raw: CaptureInput) -> list[str]: if isinstance(raw, (bytes, bytearray)) else raw ) - text = text.removesuffix("\n") + text = text.removesuffix("\n").removesuffix("\r") if not text: return [] - return text.split("\n") + return [ln.removesuffix("\r") for ln in text.split("\n")] def _row_trimmed_text_and_cols(row: _Row) -> tuple[str, int]: t_end = row.text_used - while t_end > 0 and row.chars[t_end - 1] == " ": + while t_end > 0 and row.char_at(t_end - 1) == " ": t_end -= 1 - return "".join(row.chars[:t_end]), t_end + return row.slice_text(0, t_end), t_end -def _decode_joined_lines( +def _infer_wraps_from_joined( + plain_rows: list[str], joined_raw: CaptureInput, *, stripped_trailing: int = 0, - max_physical_rows: int, + trim_trailing: bool = False, cols: int, tabstops: tuple[int, ...], profile: Profile, policy: Policy, limits: Limits, -) -> list[str]: +) -> tuple[list[bool], list[bool]] | None: + n = len(plain_rows) raw_lines = _split_capture_lines(joined_raw) if ( stripped_trailing > 0 @@ -497,102 +575,120 @@ def _decode_joined_lines( and not isinstance(joined_raw, (str, bytes, bytearray)) ): raw_lines.extend([""] * stripped_trailing) - if not raw_lines: - return [] - max_span = max(1, min(64, max_physical_rows - len(raw_lines) + 2)) - wide_cols = max(cols, cols * max_span) + if n == 0: + return ([], []) if not raw_lines else None + if not raw_lines or len(raw_lines) > n: + return None + + eff_cols = max(1, cols) + sb_cap = max(64, n + 4) + max_line_bytes = max(65_536, eff_cols * 64 * min(64, n - len(raw_lines) + 2)) scratch = Terminal( rows=1, - cols=wide_cols, - scrollback=0, + cols=eff_cols, + scrollback=sb_cap, profile=profile, policy=policy, limits=limits, ) - scratch.modes.set_mode(Mode.DECAWM, enabled=False) + scratch.modes.set_mode(Mode.DECAWM, enabled=True) scratch._g_sets = ["B", "0", "B", "B"] scratch._gl = 0 parser = Parser(limits=limits) - sink = _CaptureRowSink(scratch, cols, tabstops) - out: list[str] = [] + sink = _CaptureRowSink(scratch, eff_cols, tabstops) + segments: list[tuple[str, bool, bool]] = [] + for ln in raw_lines: + encoded = ln.encode("utf-8", errors="surrogateescape") + if len(encoded) > max_line_bytes: + return None + scratch.screen._history.clear() + scratch.screen._scrolled_total = 0 + scratch.screen._evicted_total = 0 row = scratch.screen._rows[0] - row.reset_blank(wide_cols) + row.reset_blank(eff_cols) + row.wrapped = False scratch._set_cursor(scratch.screen, 0, 0, pending_wrap=False) parser.reset() - parser.feed_to(ln.encode("utf-8", errors="surrogateescape"), sink) - txt, _ = _row_trimmed_text_and_cols(row) - out.append(txt) - return out - + mv = memoryview(encoded) + for off in range(0, len(mv), 4_096): + parser.feed_to(mv[off : off + 4_096], sink) + if ( + scratch.screen._evicted_total > 0 + or len(segments) + len(scratch.screen._history) + 1 > n + ): + return None + for h in scratch.screen._history: + raw_h = "".join(h.cells) if h.cells is not None else h.text + seg_txt = raw_h if trim_trailing else raw_h.rstrip(" ") + is_sp = cols > 0 and raw_width_bits(h.attr_at(cols - 1)) == int( + WidthRole.SPACER_HEAD + ) + segments.append((seg_txt, True, is_sp)) + cur_row = scratch.screen._rows[0] + tail_txt = ( + cur_row.slice_text(0, cur_row.text_used) + if trim_trailing + else _row_trimmed_text_and_cols(cur_row)[0] + ) + segments.append((tail_txt, False, False)) -def _infer_wraps_from_joined( - plain_rows: list[str], - row_used_cols: list[int], - joined_lines: list[str], - cols: int, -) -> tuple[list[bool], list[bool]] | None: - n = len(plain_rows) - if len(joined_lines) == n: - return [False] * n, [False] * n - if len(joined_lines) > n: + if len(segments) != n: return None - wraps = [False] * n - spacer_heads = [False] * n - r_idx = 0 - for j_line in joined_lines: - if r_idx >= n or not j_line.startswith(plain_rows[r_idx]): - return None - pos = len(plain_rows[r_idx]) - while r_idx + 1 < n and pos < len(j_line): - pad = max(0, cols - row_used_cols[r_idx]) - nxt = plain_rows[r_idx + 1] - matched_k = -1 - for k in range(pad, -1, -1): - if (k == 0 or j_line.startswith(" " * k, pos)) and j_line.startswith( - nxt, pos + k - ): - matched_k = k - break - if matched_k < 0: - break - wraps[r_idx] = True - spacer_heads[r_idx] = (pad - matched_k) == 1 - pos += matched_k + len(nxt) - r_idx += 1 - if pos != len(j_line): + for (seg_txt, _, _), plain in zip(segments, plain_rows, strict=True): + if seg_txt != plain: return None - r_idx += 1 - return (wraps, spacer_heads) if r_idx == n else None + return [s[1] for s in segments], [s[2] for s in segments] def _trim_unwrapped_row(row: _Row) -> None: - while row.text_used > 0 and row.chars[row.text_used - 1] == " ": - row.text_used -= 1 - while ( - row.used > row.text_used - and row.chars[row.used - 1] == " " - and row.attr_at(row.used - 1) == 0 - and row.ext_at(row.used - 1) is None - ): - row.used -= 1 - row._frozen = None + row.trim_trailing_blanks() -def _populate_screen_from_lines( - target: Screen, +def _apply_wide_spacer_heads( + decoded_rows: list[_Row], + *, + cols: int, + trim_trailing: bool, + inferred_spacers: list[bool] | None = None, + indices: collections.abc.Iterable[int] | None = None, +) -> None: + if cols <= 0 or len(decoded_rows) < 2: + return + scan = range(len(decoded_rows) - 1) if indices is None else indices + for i in scan: + cur_r = decoded_rows[i] + nxt_r = decoded_rows[i + 1] + if cur_r.wrapped and raw_width_bits(nxt_r.attr_at(0)) == int(WidthRole.WIDE): + if inferred_spacers is not None: + is_spacer = inferred_spacers[i] + elif trim_trailing: + is_spacer = cur_r.text_used == cols - 1 + else: + _, trimmed_cols = _row_trimmed_text_and_cols(cur_r) + is_spacer = trimmed_cols == cols - 1 + if is_spacer: + cur_r.write_spacer_head( + cols - 1, + cur_r.attr_at(cols - 1), + cur_r.ext_at(cols - 1), + ) + cur_r.wrapped = True + + +def _decode_capture_rows( raw_lines: list[str], *, - rows: int, cols: int, tabstops: tuple[int, ...], flagged: bool, + trim_trailing: bool = False, joined_capture: CaptureInput | None, stripped_trailing: int = 0, profile: Profile, policy: Policy, limits: Limits, -) -> tuple[tuple[TmuxLineFlags, ...], bool, list[PromptZone]]: +) -> tuple[list[_Row], list[TmuxLineFlags], bool]: flags_list: list[TmuxLineFlags] = [] bodies: list[str] = [] if flagged: @@ -634,23 +730,23 @@ def _populate_screen_from_lines( exact_wraps = flagged if flagged: row_wraps = [bool(fl & TmuxLineFlags.WRAPPED) for fl in flags_list] - elif joined_capture is not None and decoded_rows: - trimmed_pairs = [_row_trimmed_text_and_cols(r) for r in decoded_rows] - plain_texts = [pair[0] for pair in trimmed_pairs] - used_cols = [pair[1] for pair in trimmed_pairs] - decoded_joined = _decode_joined_lines( + elif joined_capture is not None: + plain_texts = ( + [r.slice_text(0, r.text_used) for r in decoded_rows] + if trim_trailing + else [_row_trimmed_text_and_cols(r)[0] for r in decoded_rows] + ) + inferred = _infer_wraps_from_joined( + plain_texts, joined_capture, stripped_trailing=stripped_trailing, - max_physical_rows=len(decoded_rows), + trim_trailing=trim_trailing, cols=cols, tabstops=tabstops, profile=profile, policy=policy, limits=limits, ) - inferred = _infer_wraps_from_joined( - plain_texts, used_cols, decoded_joined, cols - ) if inferred is not None: exact_wraps = True row_wraps, inferred_spacers = inferred @@ -661,30 +757,26 @@ def _populate_screen_from_lines( for idx, row_obj in enumerate(decoded_rows): row_obj.wrapped = row_wraps[idx] - if not row_wraps[idx]: + if not row_wraps[idx] and not trim_trailing: _trim_unwrapped_row(row_obj) - for i in range(len(decoded_rows) - 1): - cur_r = decoded_rows[i] - nxt_r = decoded_rows[i + 1] - if ( - cols > 0 - and cur_r.wrapped - and raw_width_bits(nxt_r.attr_at(0)) == int(WidthRole.WIDE) - ): - if inferred_spacers is not None: - is_spacer = inferred_spacers[i] - else: - _, trimmed_cols = _row_trimmed_text_and_cols(cur_r) - is_spacer = trimmed_cols == cols - 1 - if is_spacer: - cur_r.write_spacer_head( - cols - 1, - cur_r.attr_at(cols - 1), - cur_r.ext_at(cols - 1), - ) - cur_r.wrapped = True + _apply_wide_spacer_heads( + decoded_rows, + cols=cols, + trim_trailing=trim_trailing, + inferred_spacers=inferred_spacers, + ) + return decoded_rows, flags_list, exact_wraps + +def _install_rows_into_screen( + target: Screen, + decoded_rows: list[_Row], + flags_list: list[TmuxLineFlags], + *, + rows: int, + cols: int, +) -> list[PromptZone]: total = len(decoded_rows) hist_count = max(0, total - rows) target._history.clear() @@ -699,9 +791,9 @@ def _populate_screen_from_lines( view_rows = decoded_rows[hist_count : hist_count + rows] while len(view_rows) < rows: - view_rows.append(_Row(cols)) + view_rows.append(_Row(cols, gen_counter=target._gen_counter)) for r_v in view_rows: - bump_row_gen(r_v) + r_v.bind_counter(target._gen_counter) target._rows = view_rows zones: list[PromptZone] = [] @@ -723,7 +815,43 @@ def _populate_screen_from_lines( col=0, ), ) + return zones + +def _populate_screen_from_lines( + target: Screen, + raw_lines: list[str], + *, + rows: int, + cols: int, + tabstops: tuple[int, ...], + flagged: bool, + trim_trailing: bool = False, + joined_capture: CaptureInput | None, + stripped_trailing: int = 0, + profile: Profile, + policy: Policy, + limits: Limits, +) -> tuple[tuple[TmuxLineFlags, ...], bool, list[PromptZone]]: + decoded_rows, flags_list, exact_wraps = _decode_capture_rows( + raw_lines, + cols=cols, + tabstops=tabstops, + flagged=flagged, + trim_trailing=trim_trailing, + joined_capture=joined_capture, + stripped_trailing=stripped_trailing, + profile=profile, + policy=policy, + limits=limits, + ) + zones = _install_rows_into_screen( + target, + decoded_rows, + flags_list, + rows=rows, + cols=cols, + ) return tuple(flags_list), exact_wraps, zones @@ -735,9 +863,12 @@ def decode_tmux_capture( cols: int = 80, scrollback: int | None = None, flagged: bool = False, + trim_trailing: bool = False, joined_capture: CaptureInput | None = None, saved_primary_capture: CaptureInput | None = None, saved_primary_flagged: bool | None = None, + saved_primary_trim_trailing: bool | None = None, + saved_primary_joined_capture: CaptureInput | None = None, post_metadata: TmuxPaneMetadata | str | None = None, profile: Profile = TMUX_PROFILE, policy: Policy = TMUX_CAPTURE_POLICY, @@ -746,18 +877,21 @@ def decode_tmux_capture( r"""Reconstruct a :class:`~libvt.terminal.Terminal` from ``tmux capture-pane``. Handles bare ``SO``/``SI`` (``0x0e``/``0x0f``) ACS box-drawing runs without - polluting the reconstructed terminal's live ``G1`` charset, expands - ``GRID_FLAG_TAB`` ``\t`` cells against ``#{pane_tabs}`` while preserving - active SGR background/attributes, carries SGR across rows just like - ``tmux``'s ``grid_string_cells(&gc)``, reconstructs ``pending_wrap`` from - ``cursor_x >= pane_width``, and optionally populates backgrounded primary - history when ``alternate_on`` is active. + polluting the reconstructed terminal's live ``G1`` charset, decodes + ``tmux``'s ``CSI 5:3 m`` overline serialization strictly on the capture + scratch grid, expands ``GRID_FLAG_TAB`` ``\t`` cells against + ``#{pane_tabs}`` while preserving active SGR background/attributes, carries + SGR across rows just like ``tmux``'s ``grid_string_cells(&gc)``, + reconstructs ``pending_wrap`` from ``cursor_x >= pane_width``, and + optionally populates backgrounded primary history when ``alternate_on`` is + active. Parameters ---------- captured : CaptureInput - Output of ``tmux capture-pane -S - -E - -e -p -N [-F]`` as ``str``, - ``bytes``, or a line sequence (e.g. ``libtmux`` ``Pane.capture_pane``). + Output of ``tmux capture-pane -S - -E - -e -p -N [-T] [-F]`` as + ``str``, ``bytes``, or a line sequence (e.g. ``libtmux`` + ``Pane.capture_pane``). metadata : TmuxPaneMetadata | str | None Parsed :class:`TmuxPaneMetadata` or raw format line emitted by ``display-message -p TMUX_METADATA_FORMAT``; when ``None``, *rows*, @@ -771,16 +905,25 @@ def decode_tmux_capture( ``metadata.history_limit`` if *metadata* is provided, else ``2000``. flagged : bool ``True`` when *captured* includes ``capture-pane -F`` line prefixes. + trim_trailing : bool + ``True`` when *captured* used ``capture-pane -N -T`` (``tmux >= 3.4``) + to stop at ``gl->cellused`` without empty-cell padding. joined_capture : CaptureInput | None Optional ``capture-pane -S - -E - -e -p -J`` output used to infer soft wraps on ``tmux < 3.8`` when ``flagged=False``. saved_primary_capture : CaptureInput | None - Optional ``capture-pane -a -q -S - -E - -e -p -N [-F]`` output restoring - the backgrounded primary screen and scrollback when ``alternate_on`` is - ``True``. + Optional ``capture-pane -a -q -S - -E - -e -p -N [-T] [-F]`` output + restoring the backgrounded primary screen and scrollback when + ``alternate_on`` is ``True``. saved_primary_flagged : bool | None Whether *saved_primary_capture* carries ``-F`` prefixes (defaults to *flagged*). + saved_primary_trim_trailing : bool | None + Whether *saved_primary_capture* used ``-T`` (defaults to + *trim_trailing*). + saved_primary_joined_capture : CaptureInput | None + Optional ``capture-pane -a -q -S - -E - -e -p -J`` companion capture + for *saved_primary_capture* when ``saved_primary_flagged`` is ``False``. post_metadata : TmuxPaneMetadata | str | None Optional second metadata sample taken immediately after ``capture-pane`` to verify ``pane_output_generation`` stability. @@ -811,13 +954,14 @@ def decode_tmux_capture( else post_metadata ) - eff_rows = max(1, meta.rows) - eff_cols = max(1, meta.cols) - eff_scrollback = ( + eff_rows = min(_TMUX_MAX_DIM, max(1, meta.rows)) + eff_cols = min(_TMUX_MAX_DIM, max(1, meta.cols)) + raw_sb = ( scrollback if scrollback is not None else (meta.history_limit if metadata is not None else 2_000) ) + eff_scrollback = max(0, min(_TMUX_MAX_HISTORY, raw_sb)) tabstops = ( tuple(sorted({t for t in meta.pane_tabs if 0 < t < eff_cols})) if meta.pane_tabs is not None @@ -839,35 +983,108 @@ def decode_tmux_capture( raw_lines = _split_capture_lines(captured) stripped_trailing = 0 if ( - not meta.alternate_on - and metadata is not None + metadata is not None and not flagged and meta.history_size > 0 - and len(raw_lines) > meta.history_size + and len(raw_lines) >= meta.history_size and len(raw_lines) < meta.history_size + eff_rows ): stripped_trailing = meta.history_size + eff_rows - len(raw_lines) raw_lines.extend([""] * stripped_trailing) if meta.alternate_on: + all_rows, all_flags, exact_wraps = _decode_capture_rows( + raw_lines, + cols=eff_cols, + tabstops=tabstops, + flagged=flagged, + trim_trailing=trim_trailing, + joined_capture=joined_capture, + stripped_trailing=stripped_trailing, + profile=profile, + policy=policy, + limits=limits, + ) + alt_split = max(0, len(all_rows) - eff_rows) + prim_hist_rows = all_rows[:alt_split] + prim_hist_flags = all_flags[:alt_split] + alt_view_rows = all_rows[alt_split:] + alt_view_flags = all_flags[alt_split:] + if saved_primary_capture is not None: prim_lines = _split_capture_lines(saved_primary_capture) prim_flagged = ( flagged if saved_primary_flagged is None else saved_primary_flagged ) - _, _, prim_zones = _populate_screen_from_lines( - term.screens.primary, + prim_trim = ( + trim_trailing + if saved_primary_trim_trailing is None + else saved_primary_trim_trailing + ) + saved_rows, saved_flags, saved_exact = _decode_capture_rows( prim_lines, - rows=eff_rows, cols=eff_cols, tabstops=tabstops, flagged=prim_flagged, - joined_capture=None, + trim_trailing=prim_trim, + joined_capture=saved_primary_joined_capture, profile=profile, policy=policy, limits=limits, ) + exact_wraps = exact_wraps and saved_exact + if prim_hist_rows: + had_first_saved = bool(saved_rows) + if len(saved_rows) < eff_rows: + pad_n = eff_rows - len(saved_rows) + saved_rows = [ + *saved_rows, + *( + _Row( + eff_cols, gen_counter=term.screens.primary._gen_counter + ) + for _ in range(pad_n) + ), + ] + saved_flags = [*saved_flags, *([TmuxLineFlags.NONE] * pad_n)] + elif len(saved_rows) > eff_rows: + saved_rows = saved_rows[:eff_rows] + saved_flags = saved_flags[:eff_rows] + full_prim_rows = [*prim_hist_rows, *saved_rows] + full_prim_flags = [*prim_hist_flags, *saved_flags] + if had_first_saved: + _apply_wide_spacer_heads( + full_prim_rows, + cols=eff_cols, + trim_trailing=prim_trim, + indices=(len(prim_hist_rows) - 1,), + ) + else: + full_prim_rows = saved_rows + full_prim_flags = saved_flags + prim_zones = _install_rows_into_screen( + term.screens.primary, + full_prim_rows, + full_prim_flags, + rows=eff_rows, + cols=eff_cols, + ) + for z in prim_zones: + term._prompt_zones.append(z) + elif prim_hist_rows: + blank_prim_view = [ + _Row(eff_cols, gen_counter=term.screens.primary._gen_counter) + for _ in range(eff_rows) + ] + prim_zones = _install_rows_into_screen( + term.screens.primary, + [*prim_hist_rows, *blank_prim_view], + [*prim_hist_flags, *([TmuxLineFlags.NONE] * eff_rows)], + rows=eff_rows, + cols=eff_cols, + ) for z in prim_zones: term._prompt_zones.append(z) + has_saved_xy = ( meta.alternate_saved_x is not None or meta.alternate_saved_y is not None ) @@ -889,18 +1106,14 @@ def decode_tmux_capture( term.screens.active_is_alt = True entered_mode = Mode.ALT_SCREEN if has_saved_xy else Mode.ALT_SCREEN_1047 term.modes.sync_alt_screen(active_is_alt=True, entered_via=entered_mode) - line_flags, exact_wraps, _ = _populate_screen_from_lines( + _install_rows_into_screen( term.screens.alternate, - raw_lines[-eff_rows:], + alt_view_rows, + alt_view_flags, rows=eff_rows, cols=eff_cols, - tabstops=tabstops, - flagged=flagged, - joined_capture=joined_capture, - profile=profile, - policy=policy, - limits=limits, ) + line_flags = tuple(alt_view_flags) else: line_flags, exact_wraps, zones = _populate_screen_from_lines( term.screens.primary, @@ -909,6 +1122,7 @@ def decode_tmux_capture( cols=eff_cols, tabstops=tabstops, flagged=flagged, + trim_trailing=trim_trailing, joined_capture=joined_capture, stripped_trailing=stripped_trailing, profile=profile, @@ -943,7 +1157,12 @@ def decode_tmux_capture( term.modes.set_mode(Mode.MOUSE_SGR, enabled=meta.mouse_sgr_flag) term.modes.set_mode(Mode.FOCUS_EVENT, enabled=meta.focus_events_flag) for priv_code in meta.private_modes: - if priv_code not in (47, 1047, 1049, 2026): + if 0 <= priv_code < DEC_PRIVATE_MASK and priv_code not in ( + 47, + 1047, + 1049, + 2026, + ): raw_m = DEC_PRIVATE_MASK | priv_code with contextlib.suppress(ValueError): term.modes.set_mode(Mode(raw_m), enabled=True) @@ -969,9 +1188,11 @@ def decode_tmux_capture( term._generation += 1 term._cached_snapshot = None if meta.synchronized: - term.modes.set_mode(Mode.SYNCHRONIZED_OUTPUT, enabled=True) + term._modes._enabled.add(Mode.SYNCHRONIZED_OUTPUT) term._sync_generation = 1 term._sync_hold_pending = True + else: + term._committed_generation += 1 unexposed = set(_BASE_UNEXPOSED_FIELDS) if not exact_wraps: @@ -983,6 +1204,13 @@ def decode_tmux_capture( meta.output_generation is not None and post_meta is not None and post_meta.output_generation == meta.output_generation + and ( + post_meta.cols, + post_meta.rows, + post_meta.alternate_on, + post_meta.history_size, + ) + == (meta.cols, meta.rows, meta.alternate_on, meta.history_size) ) completeness = CaptureCompleteness( exact_cells=True, @@ -998,13 +1226,329 @@ def decode_tmux_capture( ) +@dataclass(frozen=True, slots=True) +class TmuxCaptureCommand: + """Sans-I/O chained ``tmux`` capture command specification and bundle parser. + + Attributes + ---------- + argv : tuple[str, ...] + Chained ``tmux`` subcommand arguments (``display-message`` + + ``capture-pane`` separated by ``";"``). Pass ``["tmux", *cmd.argv]`` to + :func:`subprocess.run` or ``server.cmd(cmd.argv[0], *cmd.argv[1:])`` in + ``libtmux``. + nonce : str + Boundary sentinel token bracketing each output section. + flagged : bool + ``True`` when ``capture-pane -F`` is included (``tmux >= 3.8``). + trim_trailing : bool + ``True`` when ``capture-pane -T`` is included (``tmux >= 3.4``). + has_joined : bool + ``True`` when companion ``capture-pane -J`` sections are included + (``tmux < 3.8``). + include_saved_primary : bool + ``True`` when ``capture-pane -a -q`` sections are included. + """ + + argv: tuple[str, ...] + nonce: str + flagged: bool + trim_trailing: bool + has_joined: bool + include_saved_primary: bool + + def parse( + self, + output: CaptureInput, + *, + scrollback: int | None = None, + profile: Profile = TMUX_PROFILE, + policy: Policy = TMUX_CAPTURE_POLICY, + limits: Limits = DEFAULT_LIMITS, + ) -> TmuxCaptureResult: + """Split chained ``tmux`` stdout and decode into a :class:`TmuxCaptureResult`. + + Parameters + ---------- + output : CaptureInput + Raw stdout ``str``/``bytes`` or line sequence (e.g. ``libtmux`` + ``tmux_cmd.stdout``) produced by executing :attr:`argv`. + scrollback : int | None + Explicit scrollback ceiling override. + profile : Profile + Compatibility profile for the reconstructed terminal. + policy : Policy + Security policy for the reconstructed terminal. + limits : Limits + Resource ceilings for the reconstructed terminal. + + Returns + ------- + TmuxCaptureResult + Decoded terminal, snapshot, completeness report, and line flags. + + Raises + ------ + ValueError + If *output* is missing expected nonce boundary markers. + """ + lines = _split_capture_lines(output) + pre_prefix = f"{self.nonce}:PRE:" + post_prefix = f"{self.nonce}:POST:" + if not lines or not lines[0].startswith(pre_prefix): + msg = "missing tmux capture bundle PRE header" + raise ValueError(msg) + + expected_markers: list[str] = [f"{self.nonce}:CAPTURE"] + if self.has_joined: + expected_markers.append(f"{self.nonce}:JOINED") + if self.include_saved_primary: + expected_markers.append(f"{self.nonce}:SAVED") + if self.has_joined: + expected_markers.append(f"{self.nonce}:SAVED_JOINED") + + marker_indices: dict[str, int] = {} + search_from = 1 + for marker in expected_markers: + found = -1 + for idx in range(search_from, len(lines)): + if lines[idx] == marker: + found = idx + break + if found < 0: + msg = f"missing tmux capture bundle marker: {marker}" + raise ValueError(msg) + marker_indices[marker] = found + search_from = found + 1 + + post_idx = -1 + for idx in range(len(lines) - 1, search_from - 1, -1): + if lines[idx].startswith(post_prefix): + post_idx = idx + break + if post_idx < 0: + msg = "missing tmux capture bundle POST footer" + raise ValueError(msg) + + cap_marker = f"{self.nonce}:CAPTURE" + cap_start = marker_indices[cap_marker] + pre_raw = "\n".join([lines[0][len(pre_prefix) :], *lines[1:cap_start]]) + post_raw = "\n".join( + [lines[post_idx][len(post_prefix) :], *lines[post_idx + 1 :]] + ) + pre_meta = TmuxPaneMetadata.from_format_line(pre_raw) + post_meta = TmuxPaneMetadata.from_format_line(post_raw) + + ordered_stops = [ + *(marker_indices[m] for m in expected_markers[1:]), + post_idx, + ] + cap_lines = lines[cap_start + 1 : ordered_stops[0]] + stop_cursor = 0 + joined_lines: list[str] | None = None + if self.has_joined: + j_idx = marker_indices[f"{self.nonce}:JOINED"] + stop_cursor += 1 + joined_lines = lines[j_idx + 1 : ordered_stops[stop_cursor]] + + saved_lines: list[str] | None = None + saved_joined_lines: list[str] | None = None + if self.include_saved_primary: + s_idx = marker_indices[f"{self.nonce}:SAVED"] + stop_cursor += 1 + raw_saved = lines[s_idx + 1 : ordered_stops[stop_cursor]] + if self.has_joined: + sj_idx = marker_indices[f"{self.nonce}:SAVED_JOINED"] + stop_cursor += 1 + raw_saved_j = lines[sj_idx + 1 : ordered_stops[stop_cursor]] + else: + raw_saved_j = None + if pre_meta.alternate_on and not (self.flagged and raw_saved == [""]): + saved_lines = raw_saved + saved_joined_lines = raw_saved_j + + return decode_tmux_capture( + cap_lines, + metadata=pre_meta, + post_metadata=post_meta, + scrollback=scrollback, + flagged=self.flagged, + trim_trailing=self.trim_trailing, + joined_capture=joined_lines, + saved_primary_capture=saved_lines, + saved_primary_flagged=self.flagged, + saved_primary_trim_trailing=self.trim_trailing, + saved_primary_joined_capture=saved_joined_lines, + profile=profile, + policy=policy, + limits=limits, + ) + + +def _escape_tmux_arg(value: str) -> str: + return f"{value[:-1]}\\;" if value.endswith(";") else value + + +def build_tmux_capture_command( + target: str | None = None, + *, + tmux_version: tuple[int, int] | str = "3.8a", + include_saved_primary: bool = True, + nonce: str | None = None, +) -> TmuxCaptureCommand: + """Build a single-invocation ``tmux`` command chaining metadata and capture. + + Chains ``display-message`` and ``capture-pane -S - -E - -e -p -N -T -F`` on + ``tmux >= 3.8`` (falling back to ``-e -p -N -T`` + ``-e -p -J`` on + ``3.4``-``3.7`` and ``-e -p -N`` + ``-e -p -J`` on ``3.3a``) inside one + atomic ``tmux`` command-queue batch so pane output cannot drift between + commands and trailing blank viewport rows are preserved ahead of the + closing ``POST`` footer. + + Parameters + ---------- + target : str | None + Optional ``tmux`` target pane (e.g. ``"%0"``); when ``None``, ``-t`` is + omitted so ``tmux`` targets the current pane. + tmux_version : tuple[int, int] | str + Target ``tmux`` version as ``(major, minor)`` or ``tmux -V`` string + (e.g. ``"3.8a"``, ``"3.6"``, ``"3.3a"``). + include_saved_primary : bool + Include ``capture-pane -a -q`` sections to restore backgrounded primary + history when ``alternate_on`` is active. + nonce : str | None + Explicit ASCII boundary token matching ``[0-9A-Za-z_-]{8,128}``; + generated via :func:`secrets.token_hex` when ``None``. + + Returns + ------- + TmuxCaptureCommand + Command specification with :attr:`~TmuxCaptureCommand.argv` and + :meth:`~TmuxCaptureCommand.parse`. + + Raises + ------ + ValueError + If *target*, *tmux_version*, or *nonce* is invalid. + """ + if target is not None and ( + not target or any(ch in target for ch in ("\x00", "\r", "\n")) + ): + msg = f"invalid tmux target {target[:64]!r}" + raise ValueError(msg) + eff_nonce = f"__LIBVT_CAP_{secrets.token_hex(16)}__" if nonce is None else nonce + if _NONCE_RE.match(eff_nonce) is None: + msg = ( + f"invalid tmux capture nonce {eff_nonce[:64]!r}; expected 8..128 " + "[0-9A-Za-z_-] characters" + ) + raise ValueError(msg) + + ver = _parse_tmux_version(tmux_version) + flagged = ver >= (3, 8) + trim_trailing = ver >= (3, 4) + has_joined = not flagged + t_args: tuple[str, ...] = ( + ("-t", _escape_tmux_arg(target)) if target is not None else () + ) + + cap_flags: list[str] = ["-S", "-", "-E", "-", "-e", "-p", "-N"] + if trim_trailing: + cap_flags.append("-T") + if flagged: + cap_flags.append("-F") + + joined_flags = ["-S", "-", "-E", "-", "-e", "-p", "-J"] + + argv: list[str] = [ + "display-message", + "-p", + *t_args, + f"{eff_nonce}:PRE:{TMUX_METADATA_FORMAT}", + ";", + "display-message", + "-p", + *t_args, + f"{eff_nonce}:CAPTURE", + ";", + "capture-pane", + *cap_flags, + *t_args, + ] + if has_joined: + argv.extend( + [ + ";", + "display-message", + "-p", + *t_args, + f"{eff_nonce}:JOINED", + ";", + "capture-pane", + *joined_flags, + *t_args, + ] + ) + if include_saved_primary: + argv.extend( + [ + ";", + "display-message", + "-p", + *t_args, + f"{eff_nonce}:SAVED", + ";", + "capture-pane", + "-a", + "-q", + *cap_flags, + *t_args, + ] + ) + if has_joined: + argv.extend( + [ + ";", + "display-message", + "-p", + *t_args, + f"{eff_nonce}:SAVED_JOINED", + ";", + "capture-pane", + "-a", + "-q", + *joined_flags, + *t_args, + ] + ) + argv.extend( + [ + ";", + "display-message", + "-p", + *t_args, + f"{eff_nonce}:POST:{TMUX_METADATA_FORMAT}", + ] + ) + return TmuxCaptureCommand( + argv=tuple(argv), + nonce=eff_nonce, + flagged=flagged, + trim_trailing=trim_trailing, + has_joined=has_joined, + include_saved_primary=include_saved_primary, + ) + + __all__ = [ "TMUX_METADATA_FORMAT", "CaptureCompleteness", "CaptureInput", + "TmuxCaptureCommand", "TmuxCaptureResult", "TmuxLineFlags", "TmuxPaneMetadata", + "build_tmux_capture_command", "decode_tmux_capture", "parse_flagged_line", "unescape_tmux_control_output", diff --git a/tests/test_aio.py b/tests/test_aio.py index 61e136c..83d84b9 100644 --- a/tests/test_aio.py +++ b/tests/test_aio.py @@ -3,13 +3,19 @@ from __future__ import annotations import asyncio +import errno +import importlib.util +import os +import pathlib import socket +import struct import sys +import typing as t import pytest import libvt -from libvt.aio import AsyncTerminalStream, open_pty +from libvt.aio import AsyncTerminalStream, _pack_winsize, open_pty from libvt.exc import TerminalTimeoutError from libvt.parser import ParserState @@ -110,11 +116,11 @@ async def test_open_pty_controlling_tty_signals_sigpipe_and_reap() -> None: " reply += ch\n" "print('DSR=' + repr(reply.decode('ascii', 'replace')), flush=True)\n" "while not winch:\n" - " signal.pause()\n" + " time.sleep(0.01)\n" "try:\n" " print('WINCH=1', flush=True)\n" " while True:\n" - " signal.pause()\n" + " time.sleep(0.05)\n" "except KeyboardInterrupt:\n" " print('SIGINT=1', flush=True)\n" ) @@ -134,3 +140,206 @@ async def test_open_pty_controlling_tty_signals_sigpipe_and_reap() -> None: pty_sess.send(b"\x03") await pty_sess.wait_for("SIGINT=1", timeout=3.0) assert pty_sess.terminal.program_statuses == {} + + # Fast-exiting child drains final PTY bytes cleanly across Linux EIO / Darwin EOF. + async with open_pty( + ( + sys.executable, + "-c", + "import sys; sys.stdout.write('FAST_EXIT_DRAIN_OK\\n'); sys.stdout.flush()", + ), + ) as fast_sess: + snap_fast = await fast_sess.wait_for("FAST_EXIT_DRAIN_OK", timeout=3.0) + assert "FAST_EXIT_DRAIN_OK" in snap_fast.text + + +async def test_stream_eof_aclose_and_straddling_sync_frame_wakeups() -> None: + """``AsyncTerminalStream`` expires ``?2026`` on EOF/aclose and wakes mid-chunk.""" + reader = asyncio.StreamReader() + stream = AsyncTerminalStream(reader, rows=3, cols=24, sync_timeout=10.0) + reader.feed_data(b"before\x1b[?2026hCRASH_REASON") + reader.feed_eof() + await stream.pump_once() + assert stream.terminal.synchronized is False + assert stream.terminal.committed.text == "beforeCRASH_REASON" + + aclose_r = asyncio.StreamReader() + aclose_s = AsyncTerminalStream(aclose_r, rows=2, cols=20, sync_timeout=10.0) + aclose_r.feed_data(b"init\x1b[?2026hHELD_ON_CLOSE") + await aclose_s.pump_once() + assert aclose_s.terminal.synchronized is True + await aclose_s.aclose() + assert aclose_s.terminal.synchronized is False + assert aclose_s.terminal.committed.text == "initHELD_ON_CLOSE" + + async with AsyncTerminalStream( + asyncio.StreamReader(), + rows=2, + cols=20, + sync_timeout=10.0, + ) as straddle: + waiter = asyncio.create_task(straddle.wait_for("FRAME_ONE", timeout=0.3)) + await asyncio.sleep(0) + straddle.reader.feed_data( + b"\x1b[?2026h\x1b[HFRAME_ONE\x1b[?2026l\x1b[?2026h\x1b[HFRAME_TWO" + ) + snap = await waiter + assert snap[0].text == "FRAME_ONE" + assert straddle.terminal.synchronized is True + with pytest.raises(TerminalTimeoutError): + await straddle.wait_for("FRAME_TWO", timeout=0.01) + assert straddle.terminal.synchronized is False + assert straddle.terminal.committed[0].text == "FRAME_TWO" + + async with AsyncTerminalStream( + asyncio.StreamReader(), + rows=2, + cols=20, + sync_timeout=0.02, + ) as timer_stream: + w2 = asyncio.create_task(timer_stream.wait_for("WEDGED", timeout=5.0)) + await asyncio.sleep(0) + timer_stream.reader.feed_data(b"\x1b[?2026hWEDGED") + snap_w2 = await asyncio.wait_for(w2, timeout=0.4) + assert snap_w2[0].text == "WEDGED" + + mode_term = libvt.Terminal(rows=2, cols=20) + mode_term.feed(b"BEFORE\x1b[?2026h\x1b[HAFTER") + mode_term.modes.set_mode(libvt.Mode.SYNCHRONIZED_OUTPUT, enabled=False) + mode_term.feed(b" NEW") + assert mode_term.synchronized is False + assert mode_term.committed.text == "AFTER NEW" + with pytest.raises(ValueError, match="finite"): + AsyncTerminalStream(asyncio.StreamReader(), sync_timeout=float("inf")) + + +async def test_aio_lazy_posix_imports_under_win32_simulation( + monkeypatch: pytest.MonkeyPatch, +) -> None: + """``libvt.aio`` imports cleanly when POSIX PTY modules are unavailable.""" + for mod_name in ("pty", "termios", "tty", "fcntl"): + monkeypatch.setitem(sys.modules, mod_name, None) + aio_path = pathlib.Path(libvt.__file__).resolve().parent / "aio.py" + spec = importlib.util.spec_from_file_location("_libvt_aio_win_check", aio_path) + assert spec is not None and spec.loader is not None + fresh_mod = importlib.util.module_from_spec(spec) + sys.modules["_libvt_aio_win_check"] = fresh_mod + try: + spec.loader.exec_module(fresh_mod) + r = asyncio.StreamReader() + s = fresh_mod.AsyncTerminalStream(r, rows=2, cols=10) + assert s.terminal.rows == 2 + monkeypatch.setattr(sys, "platform", "win32") + with pytest.raises(NotImplementedError, match="POSIX"): + async with fresh_mod.open_pty(("python",)): + pass + await asyncio.sleep(0) + finally: + sys.modules.pop("_libvt_aio_win_check", None) + + +@pytest.mark.skipif(sys.platform == "win32", reason="POSIX pty required") +async def test_pty_session_write_queue_paste_ordering_resize_and_cancel() -> None: + """``PtySession`` buffers pastes, orders replies, flushes ?2048, and closes.""" + child_code = ( + "import sys\n" + "sys.stdout.write('\\x1b[?2004h\\x1b[?2048hREADY\\n')\n" + "sys.stdout.flush()\n" + "buf = bytearray(sys.stdin.buffer.read(512))\n" + "sys.stdout.write('\\x1b[6n')\n" + "sys.stdout.flush()\n" + "target = 24576 + 12\n" + "while len(buf) < target:\n" + " chunk = sys.stdin.buffer.read(min(4096, target - len(buf)))\n" + " if not chunk: break\n" + " buf.extend(chunk)\n" + "while not (b'R' in buf[target:] and b't' in buf[target:]):\n" + " ch = sys.stdin.buffer.read(1)\n" + " if not ch: break\n" + " buf.extend(ch)\n" + "paste_ok = buf[:target] == (b'\\x1b[200~' + b'P' * 24576 + b'\\x1b[201~')\n" + "tail = bytes(buf[target:])\n" + "dsr_ok = b'R' in tail\n" + "rsz_ok = b'\\x1b[48;12;64;192;512t' in tail\n" + "import fcntl, struct, termios\n" + "ws = struct.unpack('HHHH', fcntl.ioctl(0, termios.TIOCGWINSZ, b'\\x00' * 8))\n" + "ws_ok = ws == (12, 64, 512, 192)\n" + "sys.stdout.write(\n" + " f'PASTE={paste_ok} DSR={dsr_ok} RSZ={rsz_ok} WS={ws_ok}'" + " + '\\x1b[?2026hTAIL_EOF'\n" + ")\n" + "sys.stdout.flush()\n" + ) + with pytest.raises(ValueError, match="rows and cols"): + async with open_pty((sys.executable, "-c", "pass"), rows=0): + pass + async with open_pty( + (sys.executable, "-u", "-c", child_code), + rows=6, + cols=50, + tty_mode="raw", + sync_timeout=10.0, + write_high_water=0, + ) as sess: + with pytest.raises(ValueError, match="rows and cols"): + sess.resize(rows=70_000, cols=50) + with pytest.raises(TypeError): + t.cast("t.Any", sess).send(12345) + await sess.wait_for("READY", timeout=3.0) + sess.paste("P" * 24_576) + sess.resize(rows=12, cols=64) + await sess.drain() + snap = await sess.wait_for("TAIL_EOF", timeout=3.0) + assert "PASTE=True" in snap.text + assert "DSR=True" in snap.text + assert "RSZ=True" in snap.text + assert "WS=True" in snap.text + assert sess.terminal.synchronized is False + packed_ws = _pack_winsize( + 1_000, + 1_000, + libvt.Profile(cell_width_px=100, cell_height_px=100), + ) + assert struct.unpack("HHHH", packed_ws) == (1_000, 1_000, 65_535, 65_535) + gen_after_close = sess.terminal.committed_generation + await sess.aclose() + assert sess.terminal.committed_generation == gen_after_close + + async with open_pty( + (sys.executable, "-c", "import time; time.sleep(5)"), + tty_mode="raw", + max_write_buffer=32_768, + ) as hw_sess: + hw_sess.send(b"x" * 16_384) + await asyncio.wait_for(hw_sess.drain(), timeout=0.2) + + # Verify master_fd closes even if CancelledError interrupts aclose()/open_pty. + ign_code = ( + "import signal, sys, time\n" + "signal.signal(signal.SIGHUP, signal.SIG_IGN)\n" + "signal.signal(signal.SIGTERM, signal.SIG_IGN)\n" + "sys.stdout.write('UP\\n')\n" + "sys.stdout.flush()\n" + "time.sleep(30)\n" + ) + captured_fd = -1 + + async def _run_and_hang_close() -> None: + nonlocal captured_fd + async with open_pty((sys.executable, "-u", "-c", ign_code)) as s2: + captured_fd = s2._master_fd + await s2.wait_for("UP", timeout=3.0) + await asyncio.sleep(10.0) + + t_cancel = asyncio.create_task(_run_and_hang_close()) + while captured_fd < 0: + await asyncio.sleep(0.01) + await asyncio.sleep(0.05) + t_cancel.cancel() + await asyncio.sleep(0.05) + t_cancel.cancel() + with pytest.raises(asyncio.CancelledError): + await t_cancel + with pytest.raises(OSError) as fd_exc: # noqa: PT011 + os.fstat(captured_fd) + assert fd_exc.value.errno == errno.EBADF diff --git a/tests/test_benchmark.py b/tests/test_benchmark.py index 5c06743..f999b10 100644 --- a/tests/test_benchmark.py +++ b/tests/test_benchmark.py @@ -4,6 +4,13 @@ import pathlib +import pytest + +if not (pathlib.Path(__file__).resolve().parent.parent / "scripts").is_dir(): + pytest.skip("repository scripts/ directory required", allow_module_level=True) + +pytest.importorskip("pydantic") + from scripts import bench_vt, benchmark diff --git a/tests/test_graphics.py b/tests/test_graphics.py index a5b252f..2d2e40e 100644 --- a/tests/test_graphics.py +++ b/tests/test_graphics.py @@ -146,6 +146,137 @@ def test_scroll_before_place_sixel_erase_policies_and_event_immutability() -> No assert (as_snap.placements[0].abs_row, as_snap.placements[0].rows) == (0, 3) assert as_snap.viewport_row(as_snap.placements[0].abs_row) == 0 + decstbm_sx = libvt.Terminal( + rows=6, cols=10, scrollback=10, profile=Profile.tmux("next-3.9") + ) + decstbm_sx.feed(b'\x1b[3;1H\x1bPq"1;1;20;64#0~\x1b\\\x1b[1;4r\x1b[4;1H\n\n') + ds_snap = decstbm_sx.snapshot() + assert len(ds_snap.placements) == 1 + assert ds_snap.placements[0].occupies_abs(ds_snap.scrolled_total + 4, 0) is True + assert ds_snap.placements[0].occupies_abs(ds_snap.scrolled_total + 2, 0) is False + + # Spanning scrollback + DECSTBM top==0 preserves viewport/history visibility. + span_sx = libvt.Terminal( + rows=6, cols=10, scrollback=10, profile=Profile.tmux("next-3.9") + ) + span_sx.feed(b'\x1b[1;4r\x1b[4;1H\x1bPq"1;1;16;80#0!16~\x1b\\\n') + span_snap = span_sx.snapshot() + assert span_snap.placements[0].occupies_abs(span_snap.scrolled_total - 1, 0) is True + assert span_snap.placements[0].occupies_abs(span_snap.scrolled_total, 0) is True + + # Placement inside DECSTBM 1;4r scrolls into scrollback instead of clipping. + hist_sx = libvt.Terminal( + rows=6, cols=10, scrollback=10, profile=Profile.tmux("next-3.9") + ) + hist_sx.feed( + b'\x1b[1;4r\x1b[1;1HROW0\r\nROW1\x1b[1;1H\x1bPq"1;1;16;32#0!16~\x1b\\\x1b[4;1H\n\n' + ) + assert len(hist_sx.snapshot().placements) == 1 + assert hist_sx.snapshot().placements[0].abs_row == 0 + + rz_gfx = libvt.Terminal(rows=6, cols=10, scrollback=10) + rz_gfx.feed(b'\x1b[2;4r\x1b[1;1H\x1bPq"1;1;20;20#0~\x1b\\') + rz_gfx.resize(rows=6, cols=12) + assert (rz_gfx.screen.scroll_region.top, rz_gfx.screen.scroll_region.bottom) == ( + 0, + 5, + ) + assert len(rz_gfx.snapshot().placements) == 1 + assert len(rz_gfx.snapshot().images) == 1 + rz_gfx.feed(b"\x1b[6;1H" + b"\n" * 6) + rz_gfx.resize(rows=8, cols=12) + assert len(rz_gfx.snapshot().placements) == 1 + + pin_term = libvt.Terminal(rows=4, cols=6, scrollback=10) + raw_1cell = base64.b64encode(b"\xff" * (8 * 16 * 3)) + pin_term.feed( + b"012345$" + b"\x1b]133;A\x07" + b"\x1b_Ga=T,f=24,s=8,v=16,i=42,p=1;" + raw_1cell + b"\x1b\\" + b"ok\x1b]133;B\x07" + ) + assert (pin_term.prompt_zones[0].abs_row, pin_term.prompt_zones[0].col) == (1, 1) + assert (pin_term.prompt_zones[1].abs_row, pin_term.prompt_zones[1].col) == (1, 4) + assert (pin_term.placements[0].abs_row, pin_term.placements[0].col) == (1, 1) + pin_term.resize(rows=4, cols=12) + pin_snap = pin_term.snapshot() + assert pin_snap[0].text == "012345$ ok" + assert (pin_snap.prompt_zones[0].abs_row, pin_snap.prompt_zones[0].col) == (0, 7) + assert (pin_snap.prompt_zones[1].abs_row, pin_snap.prompt_zones[1].col) == (0, 10) + assert (pin_snap.placements[0].abs_row, pin_snap.placements[0].col) == (0, 7) + + # Unnumbered relative children, out-of-order chains, and U=1 replacement. + rel_term = libvt.Terminal(rows=6, cols=6, scrollback=10) + rel_term.feed( + b"012345$" + b"\x1b_Ga=T,f=24,s=8,v=16,i=1,p=1;" + raw_1cell + b"\x1b\\" + b"\x1b_Ga=t,f=24,s=8,v=16,i=2;" + raw_1cell + b"\x1b\\" + b"\x1b_Ga=t,f=24,s=8,v=16,i=3;" + raw_1cell + b"\x1b\\" + b"\x1b_Ga=p,i=2,P=1,Q=1,H=1,V=0\x1b\\" + b"\x1b_Ga=p,i=2,P=1,Q=1,H=3,V=2\x1b\\" + b"\x1b_Ga=p,i=2,p=1,P=1,Q=1,H=1,V=1\x1b\\" + b"\x1b_Ga=p,i=3,p=1,P=2,Q=1,H=1,V=1\x1b\\" + b"\x1b_Ga=p,i=2,p=1,P=1,Q=1,H=1,V=1\x1b\\" + ) + rel_term.resize(rows=6, cols=12) + coords = { + (p.image_id, p.placement_id, p.abs_row, p.col) for p in rel_term.placements + } + assert coords == { + (1, 1, 0, 7), + (2, 0, 0, 8), + (2, 0, 2, 10), + (2, 1, 1, 8), + (3, 1, 2, 9), + } + rel_term.feed(b"\x1b_Ga=p,U=1,i=1,p=1\x1b\\") + assert [p.virtual for p in rel_term.placements] == [True] + + # Width shrink clips SIXEL cols/mask; height shrink clips bottom placements/zones. + shrink_sx = libvt.Terminal(rows=4, cols=10, profile=Profile.tmux("next-3.9")) + shrink_sx.feed(b'\x1bPq"1;1;48;16#0!48~\x1b\\') + shrink_sx.resize(rows=4, cols=3) + assert shrink_sx.placements[0].cols == 3 + shrink_sx.feed(b"\x1b[1;1H\x1b[2K") + assert shrink_sx.placements == () + + bot_crop = libvt.Terminal(rows=6, cols=10, scrollback=10) + bot_crop.feed( + b"\x1b[5;1H\x1b]133;A\x07" + b"\x1b_Ga=T,f=24,s=8,v=16,i=9,p=1,C=1;" + raw_1cell + b"\x1b\\\x1b[1;1H" + ) + bot_crop.resize(rows=2, cols=12) + assert bot_crop.placements == () + assert bot_crop.prompt_zones == () + + tall_evict = libvt.Terminal( + rows=4, cols=6, scrollback=2, profile=Profile.tmux("next-3.9") + ) + tall_evict.feed( + b'\x1b[1;1H\x1bPq"1;1;16;64#0!16~\x1b\\\x1b[1;1H0123456789AB\x1b[4;1H\n\n' + ) + tall_evict.resize(rows=4, cols=2) + te_snap = tall_evict.snapshot() + assert len(te_snap.placements) == 1 + assert te_snap.at_abs(te_snap.placements[0].abs_row) is not None + + # ED 3 clips straddling placements at scrolled_total; Kitty P= rejects SIXEL IDs. + ed3_sx = libvt.Terminal( + rows=4, cols=6, scrollback=2, profile=Profile.tmux("next-3.9") + ) + ed3_sx.feed(b'\x1b[1;1H\x1bPq"1;1;16;64#0!16~\x1b\\\x1b[4;1H\n\x1b[3J') + ed3_snap = ed3_sx.snapshot() + assert ed3_snap.placements[0].abs_row == ed3_snap.evicted_total + assert ed3_snap.placements[0].occupies_abs(0, 0) is False + assert ed3_snap.at_abs(ed3_snap.placements[0].abs_row) is not None + sx_auto_id = ed3_snap.placements[0].image_id + ed3_sx.feed( + b"\x1b_Ga=t,f=24,s=8,v=16,i=1;" + + raw_1cell + + f"\x1b\\\x1b_Ga=p,i=1,p=1,P={sx_auto_id},V=1\x1b\\".encode() + ) + assert b"ENOPARENT" in ed3_sx.drain_replies() + sixel_seq = b'\x1bP0;1;0q"1;1;16;32#0!16~-#0!16~-#0!16~-#0!16~-#0!16~\x1b\\' vt_sixel = libvt.Terminal(rows=6, cols=10, profile=Profile.tmux("next-3.9")) vt_sixel.feed(sixel_seq) diff --git a/tests/test_input.py b/tests/test_input.py index 5914609..3cf00c3 100644 --- a/tests/test_input.py +++ b/tests/test_input.py @@ -65,3 +65,152 @@ def test_paste_event_fail_closed_and_sanitizer() -> None: assert sanitized == b"\x1b[200~hi[20[201~1~\x1b[201~" assert Policy().allow_clipboard_read is False assert Policy().allow_passthrough is False + + +def test_xtmodkeys_alternate_scroll_1007_and_sgr_pixel_1016() -> None: + """``XTMODKEYS``, ``?1007`` wheel-to-arrow, and ``?1016`` pixel clamping.""" + term = libvt.Terminal(rows=4, cols=20) + term.feed(b"\x1b[?4m\x1b[>4;2m\x1b[?4m") + assert term.modify_other_keys == 2 + assert term.drain_replies() == b"\x1b[>4;0m\x1b[>4;2m" + + assert term.encode(KeyEvent.parse("a")) == b"a" + assert term.encode(KeyEvent.parse("A")) == b"A" + assert term.encode(KeyEvent.parse("shift+a")) == b"\x1b[27;2;65~" + assert term.encode(KeyEvent.parse("alt+a")) == b"\x1b[27;3;97~" + assert term.encode(KeyEvent.parse("alt+shift+a")) == b"\x1b[27;4;65~" + assert term.encode(KeyEvent.parse("ctrl+a")) == b"\x1b[27;5;97~" + assert term.encode(KeyEvent.parse("ctrl+shift+a")) == b"\x1b[27;6;65~" + assert term.encode(KeyEvent.parse("ctrl+;")) == b"\x1b[27;5;59~" + assert term.encode(KeyEvent.parse("shift+ ")) == b"\x1b[27;2;32~" + assert term.encode(KeyEvent.parse("shift+tab")) == b"\x1b[27;2;9~" + assert term.encode(KeyEvent.parse("shift+enter")) == b"\x1b[27;2;13~" + assert term.encode(KeyEvent.parse("ctrl+enter")) == b"\x1b[27;5;13~" + assert term.encode(KeyEvent.parse("ctrl+é")) == b"\x1b[27;5;233~" + assert term.encode(KeyEvent.parse("alt+é")) == b"\x1b[27;3;233~" + assert term.encode(KeyEvent.parse("ctrl+\u0130")) == b"\x1b[27;5;304~" + assert term.encode(KeyEvent.parse("ctrl+\u212a")) == b"\x1b[27;5;8490~" + + # Kitty keyboard protocol takes precedence over modifyOtherKeys while active. + term.feed(b"\x1b[>1u") + assert term.encode(KeyEvent.parse("ctrl+a")) == b"\x1b[97;5u" + assert term.encode(KeyEvent.parse("shift+a")) == b"A" + term.feed(b"\x1b[<1u") + + # Level 1 keeps C0/ESC for Ctrl+a / Alt+a / Shift+Tab while encoding ambiguous keys. + term.feed(b"\x1b[>4;1m") + assert term.modify_other_keys == 1 + assert term.encode(KeyEvent.parse("shift+a")) == b"A" + assert term.encode(KeyEvent.parse("alt+a")) == b"\x1ba" + assert term.encode(KeyEvent.parse("alt+shift+a")) == b"\x1bA" + assert term.encode(KeyEvent.parse("ctrl+a")) == b"\x01" + assert term.encode(KeyEvent.parse("shift+tab")) == b"\x1b[Z" + assert term.encode(KeyEvent.parse("ctrl+;")) == b"\x1b[27;5;59~" + assert term.encode(KeyEvent.parse("shift+enter")) == b"\x1b[27;2;13~" + assert term.encode(KeyEvent.parse("ctrl+é")) == b"\x1b[27;5;233~" + assert term.encode(KeyEvent.parse("alt+é")) == b"\x1b" + "é".encode() + assert term.encode(KeyEvent.parse("ctrl+\u0130")) == b"\x1b[27;5;304~" + assert term.encode(KeyEvent.parse("ctrl+\u212a")) == b"\x1b[27;5;8490~" + + # CSI > 4 m, CSI > m, CSI > 4 n, DECSTR, and RIS reset modify_other_keys to 0. + term.feed(b"\x1b[>4m") + assert term.modify_other_keys == 0 + assert term.encode(KeyEvent.parse("shift+a")) == b"A" + assert term.encode(KeyEvent.parse("alt+shift+a")) == b"\x1bA" + assert term.encode(KeyEvent.parse("ctrl+\u0130")) == "\u0130".encode() + assert term.encode(KeyEvent.parse("ctrl+\u212a")) == "\u212a".encode() + term.feed(b"\x1b[>4;2m\x1b[>m") + assert term.modify_other_keys == 0 + term.feed(b"\x1b[>4;2m\x1bc") + assert term.modify_other_keys == 0 + term.feed(b"\x1b[>4;2m\x1b[>4n\x1b[?4m\x1b[>4;2m\x1b[!p\x1b[?4m") + assert term.modify_other_keys == 0 + assert term.drain_replies() == b"\x1b[>4;0m\x1b[>4;0m" + + # ?1007 alternate scroll: default enabled on alt screen when mouse tracking is off. + wheel_up = MouseEvent( + button=MouseButton.WHEEL_UP, + action=MouseAction.PRESS, + row=1, + col=2, + ) + wheel_dn = MouseEvent( + button=MouseButton.WHEEL_DOWN, + action=MouseAction.PRESS, + row=1, + col=2, + ) + assert term.encode(wheel_up) == b"" + term.feed(b"\x1b[?1007$p\x1b[?1049h") + assert term.drain_replies() == b"\x1b[?1007;1$y" + assert term.encode(wheel_up) == b"\x1b[A" + assert term.encode(wheel_dn) == b"\x1b[B" + term.feed(b"\x1b[?1h") + assert term.encode(wheel_up) == b"\x1bOA" + term.feed(b"\x1b[?1007l") + assert term.encode(wheel_up) == b"" + term.feed(b"\x1b[?1007h\x1b[?1l\x1b[?1049l") + + # ?1016 SGR-Pixel mouse: derives default cell-center pixels & clamps negatives. + term.feed(b"\x1b[?1000;1016h") + auto_px = MouseEvent( + button=MouseButton.LEFT, + action=MouseAction.PRESS, + row=2, + col=3, + ) + assert term.encode(auto_px) == b"\x1b[<0;28;40M" + neg_px = MouseEvent( + button=MouseButton.LEFT, + action=MouseAction.PRESS, + row=0, + col=0, + pixel_x=-5, + pixel_y=-12, + ) + assert term.encode(neg_px) == b"\x1b[<0;0;0M" + exp_rel = MouseEvent( + button=MouseButton.RIGHT, + action=MouseAction.RELEASE, + row=0, + col=0, + pixel_x=10, + pixel_y=20, + ) + assert term.encode(exp_rel) == b"\x1b[<2;10;20m" + partial_x = MouseEvent( + button=MouseButton.LEFT, + action=MouseAction.PRESS, + row=2, + col=3, + pixel_x=10, + ) + partial_y = MouseEvent( + button=MouseButton.LEFT, + action=MouseAction.PRESS, + row=2, + col=3, + pixel_y=20, + ) + assert term.encode(partial_x) == b"\x1b[<0;10;40M" + assert term.encode(partial_y) == b"\x1b[<0;28;20M" + + # Standalone encode_input(..., active_is_alt=None) infers ?1049 from ModeState. + alt_modes = libvt.ModeState() + alt_modes.set_mode(libvt.Mode.ALT_SCREEN, enabled=True) + assert libvt.encode_input(wheel_up, modes=alt_modes) == b"\x1b[A" + + # Per-screen XTMODKEYS isolation across ?1049h and zero-pixel ?1016 gating. + strict_t = libvt.Terminal( + rows=4, + cols=10, + profile=libvt.Profile(cell_width_px=0, cell_height_px=0), + policy=Policy(strict=True), + ) + strict_t.feed(b"\x1b[>1;2m\x1b[>4;2m\x1b[?1049h") + assert strict_t.modify_other_keys == 0 + strict_t.feed(b"\x1b[>2n\x1b[?1049l") + assert strict_t.modify_other_keys == 2 + strict_t.feed(b"\x1b[?1016$p\x1b[?1000;1006;1016h") + assert strict_t.drain_replies() == b"\x1b[?1016;0$y" + assert strict_t.encode(auto_px) == b"\x1b[<0;4;3M" diff --git a/tests/test_libvt.py b/tests/test_libvt.py index cc5942e..fefd944 100644 --- a/tests/test_libvt.py +++ b/tests/test_libvt.py @@ -4,11 +4,14 @@ import dataclasses import importlib +import importlib.metadata import inspect +import pathlib import pkgutil import re import subprocess import sys +import tomllib import libvt @@ -77,3 +80,33 @@ def test_public_dataclass_attributes_documented() -> None: if not re.search(rf"^\s*{re.escape(fld.name)}\s*:", doc, re.MULTILINE): missing.append(f"{modinfo.name}.{cls_name}.{fld.name}") assert missing == [] + + +def test_cross_platform_classifiers_and_ci_workflows() -> None: + """Dist metadata, ``pyproject.toml``, and CI declare Linux, macOS, and Windows.""" + expected_os = { + "Operating System :: POSIX", + "Operating System :: MacOS :: MacOS X", + "Operating System :: Microsoft :: Windows", + } + dist_classifiers = set( + importlib.metadata.metadata("libvt").get_all("Classifier") or [], + ) + assert expected_os <= dist_classifiers + + repo_root = pathlib.Path(__file__).resolve().parent.parent + pyproject_path = repo_root / "pyproject.toml" + if pyproject_path.is_file(): + data = tomllib.loads(pyproject_path.read_text(encoding="utf-8")) + assert expected_os <= set(data["project"]["classifiers"]) + + if (repo_root / ".github").is_dir(): + tests_wf = repo_root / ".github" / "workflows" / "tests.yml" + docs_wf = repo_root / ".github" / "workflows" / "docs.yml" + assert tests_wf.is_file() + assert docs_wf.is_file() + tests_txt = tests_wf.read_text(encoding="utf-8") + docs_txt = docs_wf.read_text(encoding="utf-8") + assert "macos-latest" in tests_txt + assert "windows-latest" in tests_txt + assert '--paths "/*"' in docs_txt diff --git a/tests/test_parser.py b/tests/test_parser.py index 2cbf15a..ac1729a 100644 --- a/tests/test_parser.py +++ b/tests/test_parser.py @@ -2,6 +2,7 @@ from __future__ import annotations +import base64 import typing as t import pytest @@ -171,3 +172,128 @@ def test_string_esc_abort_dcs_del_bel_and_payload_limits() -> None: term.feed(b"\x1b]2;" + (b"x" * 64) + b"\x07clean") assert (term.title, term.text) == ("", "clean") assert any(isinstance(ev, libvt.UnhandledSequence) for ev in term.drain_events()) + + +def test_bounded_ascii_ints_and_utf8_event_byte_cost() -> None: + """Bounded ASCII int parsers never raise on >4300 digits or malformed URIs.""" + vt = libvt.Terminal( + rows=3, + cols=12, + limits=Limits(max_osc_bytes=16_384, max_event_bytes=512, max_events=4096), + record_events=True, + ) + vt.feed(b"\x1b]" + b"9" * 4_500 + b";x\x07") + assert Parser().feed(b"\x1b]65536;x\x07") == [OscDispatch(-1, b"x", b"\x07")] + vt.feed( + "\x1b]9;4;²;²\x07\x1b]133;D;--5\x07\x1b]133;D;²\x07".encode() + + b"\x1b]7501;state=working:progress=+50\x07" + + b"\x1b]7501;state=working:progress=101\x07" + + b"\x1b]7;file://[\x07\x1b]7;file://[bad]/tmp\x07" + + "\x1b]7;file://\uff03/tmp\x07".encode() + + b"\x1b]9;9;file://[\x07" + + b"\x1b]10;#-f-f-f\x07\x1b]10;rgb:-fff/-fff/-fff\x07\x1b]10;?\x07" + + b"\x1b]133;D;-42\x07" + ) + assert [z.exit_code for z in vt.prompt_zones] == [None, None, -42] + assert vt.program_status is None + assert b"-" not in vt.drain_replies() + + raw_px = base64.b64encode(b"\xff" * (8 * 16 * 3)) + vt.feed(b"\x1b_Ga=t,f=24,s=8,v=16,i=4294967295;" + raw_px + b"\x1b\\") + assert 4_294_967_295 in vt.images + vt.drain_replies() + vt.feed( + b"\x1b_Ga=t,f=24,s=8,v=16,i=4294967296;" + + raw_px + + b"\x1b\\" + + b"\x1b_Ga=p,i=" + + b"9" * 5_000 + + b"\x1b\\" + ) + assert 4_294_967_296 not in vt.images + vt.drain_replies() + + raw_2x2 = base64.b64encode(b"\xff" * 12) + vt.feed(b"\x1b_Ga=t,f=24,s=2,v=2,i=5,q=2,m=1;" + raw_2x2[:8] + b"\x1b\\") + vt.feed(b"\x1b_Gq=999999999999999,m=0;" + raw_2x2[8:] + b"\x1b\\") + assert vt.drain_replies() == b"" + + vt.feed(b"\x1b_Ga=t,f=24,s=2,v=2,i=6,m=1;" + raw_2x2[:8] + b"\x1b\\") + vt.feed(b"\x1b_GI=7,m=0;" + raw_2x2[8:] + b"\x1b\\") + assert 6 not in vt.images + assert b"EINVAL:cannot specify both i and I" in vt.drain_replies() + + vt.feed(b"\x1b_Ga=T,f=24,s=2,v=2,i=8,m=1;" + raw_2x2[:8] + b"\x1b\\") + vt.feed(b"\x1b_Gp=4294967296,m=0;" + raw_2x2[8:] + b"\x1b\\") + assert vt.drain_replies() == b"\x1b_Gi=8;EINVAL:invalid uint32 p\x1b\\" + + vt.feed("\x1b_Gi=9,t=é;\x1b\\".encode()) + assert b"EINVAL:unsupported transmission medium" in vt.drain_replies() + + vt.drain_events() + vt.feed(b"\x07\x07\x07") + vt.feed(b"\x1b]2;" + (b"x" * 600) + b"\x07") + assert len(vt.drain_events()) == 3 + + for i in range(20): + vt.feed_str(f"\x1b]2;{'🔥' * 30}-{i}\x07") + evs = vt.drain_events() + assert 1 <= len(evs) <= 3 + + +def test_parse_sgr_ignores_colon_5_3_outside_tmux_capture() -> None: + """Global ``parse_sgr`` and live ``Terminal`` ignore ``CSI 5:3 m``.""" + vt = libvt.Terminal(rows=2, cols=8) + vt.feed(b"\x1b[5:3mA\x1b[53mB\x1b[55;5mC") + assert (vt[0, 0].style.overline, vt[0, 0].style.blink) == (False, False) + assert (vt[0, 1].style.overline, vt[0, 1].style.blink) == (True, False) + assert (vt[0, 2].style.overline, vt[0, 2].style.blink) == (False, True) + + +def test_del_flushes_incomplete_utf8_and_colon_subparams_restricted() -> None: + """``0x7F`` flushes pending UTF-8; non-``m`` and non-``4/38/48/58`` colons drop.""" + for byte_wise in (False, True): + vt = libvt.Terminal(rows=3, cols=8) + payload = b"\xe2\x7f\x82\xac" + if byte_wise: + for idx in range(len(payload)): + vt.feed(payload[idx : idx + 1]) + else: + vt.feed(payload) + assert vt.lines[0] == "\ufffd\ufffd\ufffd" + + step_vt = libvt.Terminal(rows=2, cols=8) + res1 = step_vt.feed_until(b"\xe2", stop=libvt.StopOn.GROUND) + assert res1.stopped_on == libvt.StopOn.EOF + res2 = step_vt.feed_until(b"\x7f", stop=libvt.StopOn.GROUND) + assert res2.stopped_on == libvt.StopOn.GROUND + assert step_vt.lines[0] == "\ufffd" + + csi_vt = libvt.Terminal(rows=4, cols=8) + csi_vt.feed(b"\x1b[2;3HX\x1b[1:1H\x1b[2:2J\x1b[?25:0l\x1b[1:2;31:5;4:3;32mY") + assert (csi_vt.cursor.row, csi_vt.cursor.col, csi_vt.cursor.visible) == (1, 4, True) + assert csi_vt[1, 2].text == "X" + cell_y = csi_vt[1, 3] + assert cell_y.text == "Y" + assert cell_y.style.bold is False + assert cell_y.style.fg == libvt.AnsiColor.GREEN + assert cell_y.style.underline == libvt.UnderlineStyle.CURLY + + # Omitted colon subparams (4:m, 38:5:m, 38:2:10:20:m) and >2 underline + # subparams (4:3:9m) are ignored; >= max_csi_params colons still drop/truncate. + omitted_vt = libvt.Terminal(rows=2, cols=8) + omitted_vt.feed( + b"\x1b[4:3;31m\x1b[4:m\x1b[38:5:mA\x1b[0m\x1b[4:3:9mB\x1b[38:2:10:20:mC" + ) + assert omitted_vt[0, 0].style.underline == libvt.UnderlineStyle.CURLY + assert omitted_vt[0, 0].style.fg == libvt.AnsiColor.RED + assert omitted_vt[0, 1].style.underline == libvt.UnderlineStyle.NONE + assert omitted_vt[0, 2].style.fg is None + + assert hasattr(libvt.Parser(), "_csi_overflow_idx") + for slow_pad in (b"1;" * 31, b"00000001;" * 35): + over_vt = libvt.Terminal(rows=4, cols=8) + over_vt.feed(b"\x1b[3;4H\x1b[" + slow_pad + b"1:2H") + assert (over_vt.cursor.row, over_vt.cursor.col) == (2, 3) + over_vt.feed(b"\x1b[" + (b"0;" * 31) + b"1:2mZ") + assert over_vt[2, 3].style.bold is False diff --git a/tests/test_screen.py b/tests/test_screen.py index c63d90a..6528ab3 100644 --- a/tests/test_screen.py +++ b/tests/test_screen.py @@ -24,34 +24,29 @@ def _assert_grid_invariants(term: libvt.Terminal) -> None: assert 0 <= scr.cursor.row < scr.rows assert 0 <= scr.cursor.col < scr.cols for r_idx, raw_row in enumerate(scr._rows): - assert len(raw_row.chars) == scr.cols - assert 0 <= raw_row.used <= scr.cols - if raw_row.attrs is None: + assert raw_row.cols == scr.cols + assert 0 <= raw_row.text_used <= raw_row.used <= scr.cols + if not raw_row.has_wide: continue for c_idx in range(scr.cols): - role = WidthRole((raw_row.attrs[c_idx] >> 60) & 0b11) + role = WidthRole((raw_row.attr_at(c_idx) >> 60) & 0b11) if role == WidthRole.WIDE: assert c_idx + 1 < scr.cols, f"orphan WIDE at ({r_idx}, {c_idx})" - tail_role = WidthRole((raw_row.attrs[c_idx + 1] >> 60) & 0b11) + tail_role = WidthRole((raw_row.attr_at(c_idx + 1) >> 60) & 0b11) assert tail_role == WidthRole.SPACER_TAIL elif role == WidthRole.SPACER_TAIL: assert c_idx > 0, f"orphan SPACER_TAIL at ({r_idx}, 0)" - head_role = WidthRole((raw_row.attrs[c_idx - 1] >> 60) & 0b11) + head_role = WidthRole((raw_row.attr_at(c_idx - 1) >> 60) & 0b11) assert head_role == WidthRole.WIDE - elif ( - role == WidthRole.SPACER_HEAD - and not declrmm - and c_idx == scr.cols - 1 - and r_idx + 1 < scr.rows - and raw_row.wrapped - ): - next_row = scr._rows[r_idx + 1] - next_role = ( - WidthRole((next_row.attrs[0] >> 60) & 0b11) - if next_row.attrs is not None - else WidthRole.NARROW + elif role == WidthRole.SPACER_HEAD: + assert c_idx == scr.cols - 1, ( + f"interior SPACER_HEAD at ({r_idx}, {c_idx})" ) - assert next_role == WidthRole.WIDE + assert raw_row.wrapped, f"unwrapped SPACER_HEAD at ({r_idx}, {c_idx})" + if not declrmm and r_idx + 1 < scr.rows: + next_row = scr._rows[r_idx + 1] + next_role = WidthRole((next_row.attr_at(0) >> 60) & 0b11) + assert next_role == WidthRole.WIDE class ResizeCase(t.NamedTuple): @@ -181,7 +176,7 @@ def test_resize_soft_wrap_join_alt_crop_and_inband_2048() -> None: False, "hard", ) - assert term.drain_replies() == b"\x1b[48;4;20;0;0t" + assert term.drain_replies() == b"\x1b[48;4;20;64;160t" assert InBandResize(rows=4, cols=20) in term.drain_events() term.feed(b"\x1b[?1049h\x1b[H0123456789abcdefgh") @@ -333,10 +328,42 @@ def test_frozen_row_combining_wide_bce_and_256_block_cow_history() -> None: assert s_deep.history[-1].text == ( "line-50001" if step == 0 else f"tail-{step - 1:02d}" ) - assert time.perf_counter() - t0 < 0.05 + assert time.perf_counter() - t0 < 0.5 snap_b = deep.snapshot() assert snap_a._history.blocks[1] is snap_b._history.blocks[1] + unwrapped_fr = deep._screens.primary._history[10] + t_rz = time.perf_counter() + deep.resize(rows=2, cols=20) + assert time.perf_counter() - t_rz < 0.5 + assert deep._screens.primary._history[10].text == unwrapped_fr.text + assert deep._screens.primary._history[10].runs is unwrapped_fr.runs + + snap_rz = deep.snapshot() + first_abs = snap_rz.evicted_total + assert len(snap_rz.at_abs(first_abs)) == 20 + assert snap_rz.at_abs(first_abs) == snap_rz.history[0] + assert snap_rz.at_abs(first_abs) in snap_rz.history + assert snap_rz.history != snap_b.history + + t_20 = libvt.Terminal(rows=2, cols=20, scrollback=10) + t_10 = libvt.Terminal(rows=2, cols=10, scrollback=10) + for t_eq in (t_20, t_10): + t_eq.feed(b"hello\r\nrow1\r\nrow2") + t_10.resize(rows=2, cols=20) + assert t_10.snapshot().history == t_20.snapshot().history + + t_nr = libvt.Terminal(rows=2, cols=6, scrollback=10) + t_nr.feed_str("aaa中\r\nx\r\ny") + t_nr.resize(rows=2, cols=4, reflow=False) + nr_snap = t_nr.snapshot() + assert nr_snap.history[0].text == "aaa中" + assert nr_snap.history[0][3].width_role == libvt.WidthRole.WIDE + assert nr_snap.history[0][4].width_role == libvt.WidthRole.SPACER_TAIL + assert nr_snap.at_abs(0) == nr_snap.history[0] + assert nr_snap.at_abs(0) in nr_snap.history + assert nr_snap.history.index(nr_snap.at_abs(0)) == 0 + def test_seeded_grid_and_reflow_invariants() -> None: """Seeded property fuzzing preserves wide-spacer and cursor bounds.""" @@ -388,3 +415,34 @@ def test_seeded_grid_and_reflow_invariants() -> None: if trial % 4 == 0: term.resize(rows=rng.choice((3, 6, 9)), cols=rng.choice((5, 8, 14))) _assert_grid_invariants(term) + + +def test_decslrm_partial_scroll_preserves_interior_wide_glyphs() -> None: + """``DECSLRM`` partial scroll keeps wide glyphs wholly inside ``[left, right]``.""" + term = libvt.Terminal(rows=3, cols=8) + # Row 0: wide pairs straddling left=2 (cols 1..2) and right=5 (cols 5..6) + # Row 1: wide pairs wholly inside [2..5] at (2, 3) and (4, 5) + term.feed_str("A漢BB中C\r\n..日本ZZ") + term.feed(b"\x1b[?69h\x1b[3;6s\x1b[1;3H\x1b[S") + _assert_grid_invariants(term) + assert term.lines[0] == "A 日本 C" + assert term[0, 2].text == "日" + assert term[0, 2].width_role == WidthRole.WIDE + assert term[0, 3].width_role == WidthRole.SPACER_TAIL + assert term[0, 4].text == "本" + assert term[0, 4].width_role == WidthRole.WIDE + assert term[0, 5].width_role == WidthRole.SPACER_TAIL + assert term.lines[1] == ".. ZZ" + + # Scroll down (SD) also preserves wide glyphs at exact left/right boundaries. + term.feed(b"\x1b[T") + _assert_grid_invariants(term) + assert term.lines[0] == "A C" + assert term.lines[1] == "..日本ZZ" + assert term[1, 2].width_role == WidthRole.WIDE + assert term[1, 4].width_role == WidthRole.WIDE + + # Full-width scroll_down onto bottom row clears orphan SPACER_HEAD / wrapped. + sd_bot = libvt.Terminal(rows=3, cols=6) + sd_bot.feed(b"\x1b[2;1HGHIJK" + "漢".encode() + b"\x1b[1;1H\x1b[1T\x1b[3;1H\n") + _assert_grid_invariants(sd_bot) diff --git a/tests/test_terminal.py b/tests/test_terminal.py index 9154c25..ddcd80f 100644 --- a/tests/test_terminal.py +++ b/tests/test_terminal.py @@ -2,6 +2,10 @@ from __future__ import annotations +import copy +import dataclasses +import pickle +import random import time import typing as t @@ -403,3 +407,490 @@ def _step(tok: libvt.SyncToken | None) -> libvt.ScreenDelta: assert term.changes_since(stale_same_epoch).resync_reason == ( ResyncReason.HISTORY_EVICTED ) + + # SyncToken is opaque per Terminal; mutating another Terminal never bumps it. + other_term = libvt.Terminal(rows=2, cols=6) + tok_before_other = term.sync_token() + assert not dataclasses.is_dataclass(libvt.SyncToken) + assert not hasattr(tok_before_other, "terminal_id") + assert not hasattr(tok_before_other, "_terminal_id") + assert not hasattr(tok_before_other, "modes") + assert len(repr(tok_before_other)) < 80 + assert hash(tok_before_other) == hash(term.sync_token()) + assert copy.copy(tok_before_other) == tok_before_other + assert copy.deepcopy(tok_before_other) == tok_before_other + for proto in range(pickle.HIGHEST_PROTOCOL + 1): + roundtrip = pickle.loads(pickle.dumps(tok_before_other, protocol=proto)) + assert roundtrip == tok_before_other + assert ( + other_term.changes_since(roundtrip).resync_reason + == ResyncReason.TERMINAL_MISMATCH + ) + with pytest.raises(TypeError): + libvt.SyncToken() + with pytest.raises(AttributeError): + t.cast("t.Any", tok_before_other).extra = 1 + with pytest.raises(TypeError): + term.changes_since(t.cast("t.Any", "bad")) + other_term.feed_str("hello world") + assert term.sync_token() == tok_before_other + + # Direct Screen / ModeState mutators preserve ?2026 holds and replica sync. + direct_t = libvt.Terminal(rows=3, cols=6) + direct_t.feed(b"HELLO") + d0 = direct_t.changes_since(None) + dh: list[RowView] = [] + dv: list[RowView] = [] + d0.apply_rows(dh, dv) + direct_t.screen.reset() + d1 = direct_t.changes_since(d0.token) + d1.apply_rows(dh, dv) + direct_t.feed(b"\x1b[2;1HWORLD") + d2 = direct_t.changes_since(d1.token) + d2.apply_rows(dh, dv) + assert [r.text for r in dv] == list(d2.snapshot.lines) + + hold_t = libvt.Terminal(rows=2, cols=6) + hold_t.feed(b"SAFE\x1b[?2026h") + hold_t.screen.reset() + assert hold_t.committed.text == "SAFE" + + # DCH / ICH / SD / IL under DECLRMM & non-reflow resize preserve row invariants. + dch_lr = libvt.Terminal(rows=3, cols=6) + dch_lr.feed(b"ABCDEFG\x1b[?69h\x1b[3;6s\x1b[1;1H") + lr_tok = dch_lr.sync_token(view="working") + dch_lr.feed(b"\x1b[P\x1b[@") + lr_delta = dch_lr.changes_since(lr_tok, view="working") + assert dch_lr.snapshot()[0].wrapped is True + assert lr_delta.dirty_rows == () + + sd_lr = libvt.Terminal(rows=4, cols=6) + sd_lr.feed("ABCDE日12".encode() + b"\x1b[?69h\x1b[3;6s\x1b[1;1H\x1b[T\x1b[?69l") + assert sd_lr[1].wrapped is False + assert sd_lr[1, 5].width_role != libvt.WidthRole.SPACER_HEAD + + il_lr = libvt.Terminal(rows=3, cols=6) + il_lr.feed("ABCDE日1234".encode() + b"\x1b[?69h\x1b[2;5s\x1b[2;2H\x1b[L") + assert not (il_lr[0].wrapped and il_lr[0, 5].text == " ") + + ich_w = libvt.Terminal(rows=2, cols=6) + ich_w.feed("ABC日".encode() + b"\x1b[?69h\x1b[2;4s\x1b[1;2H\x1b[@") + ref_w = libvt.Terminal(rows=2, cols=6) + ref_w.feed(b"A BC") + assert ich_w.snapshot()[0].text == "A BC" + assert ich_w.snapshot()[0] == ref_w.snapshot()[0] + + alt_rz = libvt.Terminal(rows=3, cols=4) + alt_rz.feed(b"\x1b[?1049h" + "ABC日".encode()) + alt_rz.resize(rows=3, cols=6) + alt_rz.feed(b"\x1b[1;5HXY") + assert alt_rz[0, 3].width_role != libvt.WidthRole.SPACER_HEAD + assert alt_rz[0].text == "ABC XY" + + # Seeded replica & _Row write-barrier fingerprint fuzzer. + rng = random.Random(20261123) + fuzz_tokens: tuple[bytes, ...] = ( + b"ABCD", + "日本".encode(), + b"a\xcc\x81", + b"\r", + b"\n", + b"\x08", + b"\x1b[1;1H", + b"\x1b[2;3H", + b"\x1b[A", + b"\x1b[B", + b"\x1b[C", + b"\x1b[D", + b"\x1b[@", + b"\x1b[2@", + b"\x1b[P", + b"\x1b[2P", + b"\x1b[2X", + b"\x1b[K", + b"\x1b[1K", + b"\x1b[2K", + b"\x1b[J", + b"\x1b[2J", + b"\x1b[3J", + b"\x1b[L", + b"\x1b[M", + b"\x1b[S", + b"\x1b[T", + b"\x1b[1;3r", + b"\x1b[2;4r", + b"\x1b[r", + b"\x1b[?69h\x1b[3;5s", + b"\x1b[?69l", + b"\x1b[31;44m", + b"\x1b[0m", + b"\x1b[?1049h", + b"\x1b[?1049l", + b"\x1b[?2026h", + b"\x1b[?2026l", + ) + for trial in range(50): + ft = libvt.Terminal(rows=4, cols=6, scrollback=8) + w_tok = ft.sync_token(view="working") + c_tok2 = ft.sync_token(view="committed") + w_hist: list[RowView] = [] + w_view: list[RowView] = [ft.snapshot()[i] for i in range(4)] + c_hist: list[RowView] = [] + c_view: list[RowView] = [ft.committed[i] for i in range(4)] + prev_fps = [r.debug_fingerprint() for r in ft.screen._rows] + + for step_i in range(24): + if step_i == 12 and trial % 5 == 0: + ft.resize(rows=rng.choice((3, 5)), cols=rng.choice((5, 8))) + else: + ft.feed(rng.choice(fuzz_tokens)) + + cur_fps = [r.debug_fingerprint() for r in ft.screen._rows] + dw = ft.changes_since(w_tok, view="working") + if dw.resync_reason is ResyncReason.NONE and dw.viewport_scroll_up == 0: + changed_idx = tuple( + i for i in range(ft.rows) if cur_fps[i] != prev_fps[i] + ) + for ci in changed_idx: + assert ci in dw.dirty_rows + dw.apply_rows(w_hist, w_view) + ws = dw.snapshot + assert w_hist == list(ws.history) + assert w_view == [ws[i] for i in range(ws.rows)] + w_tok = dw.token + prev_fps = cur_fps + + dc = ft.changes_since(c_tok2, view="committed") + dc.apply_rows(c_hist, c_view) + cs = dc.snapshot + assert c_hist == list(cs.history) + assert c_view == [cs[i] for i in range(cs.rows)] + c_tok2 = dc.token + + +def test_bce_strips_hyperlink_su_history_and_vt_formatter_roundtrip() -> None: + """``BCE`` drops ``OSC 8``, ``SU`` scrolls to history, and ``VT`` round-trips.""" + bce_t = libvt.Terminal(rows=3, cols=8) + bce_t.feed( + b"\x1b]8;id=1;https://example.com\x07\x1b[42m" + b"AB\x1b[K\r\n" + b"CD\x1b[2X\r\n" + b"EF\x1b[1;1H\x1b[1;2r\x1b[1L\x1b[r\x1b]8;;\x07" + ) + assert bce_t[1, 0].hyperlink == libvt.Hyperlink(uri="https://example.com", id="1") + for r_i, c_i in ((0, 0), (0, 5), (1, 2), (1, 3)): + assert bce_t[r_i, c_i].style.bg == AnsiColor.GREEN + assert bce_t[r_i, c_i].hyperlink is None + + su_t = libvt.Terminal(rows=3, cols=8, scrollback=10) + su_t.feed(b"\x1b]133;A\x07rowA\r\nrowB\r\n\x1b]133;A\x07rowC\x1b[1;2r\x1b[1S") + su_snap = su_t.snapshot() + assert [r.text for r in su_snap.history] == ["rowA"] + assert su_snap.lines == ("rowB", "", "rowC") + assert [su_snap.at_abs(z.abs_row).text for z in su_snap.prompt_zones] == [ + "rowA", + "rowC", + ] + # Huge Ps in SU clamps to region height rather than flooding scrollback. + su_t.feed(b"\x1b[999S") + assert len(su_t.history) == 3 + + # Alt-screen SU and narrow-margin SU do not push to primary scrollback. + su_t.feed(b"\x1b[r\x1b[?1049hALT1\r\nALT2\x1b[1S\x1b[?1049l") + assert len(su_t.history) == 3 + + # Formatter(OutputFormat.VT) round-trips IRM / DECOM / DECLRMM / ?7l / ?25l / + # ?2027l / DECSCUSR and short wrapped=True rows from tmux -T. + src_t = libvt.Terminal.from_tmux_capture( + ["W ab", "- GH", "- "], + rows=3, + cols=6, + flagged=True, + trim_trailing=True, + profile=DEFAULT_PROFILE, + ) + assert src_t.screen._rows[0].used == 2 + src_t.feed( + b"\x1b[2;3H\x1b[42m\x1b[2X\x1b[0m" + b"\x1b[4h\x1b[?69h\x1b[2;5s\x1b[?6h\x1b[?7l\x1b[?25l\x1b[5 q\x1b[2;2H" + ) + snap = src_t.snapshot() + vt_out = snap.format(OutputFormat.VT) + dst_t = libvt.Terminal(rows=3, cols=6) + dst_t.feed_str(vt_out) + dst_snap = dst_t.snapshot() + assert dst_snap[0].wrapped is True + assert dst_snap[0, 0].text == "a" + assert dst_snap[0, 1].text == "b" + assert dst_snap[1].text == "GH" + assert dst_snap[1, 2].style.bg == AnsiColor.GREEN + assert dst_snap.modes == snap.modes + assert dst_snap.cursor == snap.cursor + + # ?2027l and ?25l across ?1049h round-trip through Formatter(OutputFormat.VT). + flag_t = libvt.Terminal(rows=2, cols=8) + flag_t.feed(b"\x1b[?25l\x1b[?1049h\x1b[?2027l" + "🇺🇸X".encode()) + flag_dst = libvt.Terminal(rows=2, cols=8) + flag_dst.feed_str(flag_t.snapshot().format(OutputFormat.VT)) + assert flag_dst.cursor.visible is False + assert (flag_dst[0, 1].text, flag_dst[0, 2].text) == ("🇸", "X") + + # Bottom-row wrapped=True from tmux capture preserves penultimate wrap & BCE. + s_bot1 = libvt.Snapshot.from_tmux_capture( + ["W abcdef", "W "], rows=2, cols=6, flagged=True, trim_trailing=True + ) + d_bot1 = libvt.Terminal(rows=2, cols=6) + d_bot1.feed_str(s_bot1.format(OutputFormat.VT)) + assert d_bot1[0].wrapped is True + + t_bot2 = libvt.Terminal.from_tmux_capture( + ["- abcdef", "W ab"], rows=2, cols=6, flagged=True, trim_trailing=True + ) + t_bot2.feed(b"\x1b[2;3H\x1b[42m\x1b[3X\x1b[0m") + d_bot2 = libvt.Terminal(rows=2, cols=6) + d_bot2.feed_str(t_bot2.snapshot().format(OutputFormat.VT)) + assert d_bot2[1, 2].style.bg == AnsiColor.GREEN + + +def test_profile_decstr_decsc_declrmm_and_top_margin_history() -> None: + """``DEFAULT`` vs ``TMUX_PROFILE`` split ``DECSTR``, ``DECSC``, and ``?69``.""" + # 1. DECSTR on DEFAULT / XTERM resets only VT510 soft-reset state. + for prof in (DEFAULT_PROFILE, libvt.XTERM_PROFILE): + dt = libvt.Terminal(rows=4, cols=8, profile=prof) + dt.feed( + b"\x1b[?1000h\x1b[?1006h\x1b[?2004h\x1b[>1u" + b"\x1b[4h\x1b[?7l\x1b[?25l\x1b[?69h\x1b[2;4r\x1b[2;6s\x1b[?6h" + b"\x1b[31m\x1b]8;;https://example.com\x07\x1b[5 q\x1b)0\x0e" + b"\x1b[2;2H\x1b7\x1b[!p" + ) + assert dt.modes.is_set(libvt.Mode.MOUSE_VT200) is True + assert dt.modes.is_set(libvt.Mode.MOUSE_SGR) is True + assert dt.modes.is_set(libvt.Mode.BRACKETED_PASTE) is True + assert int(dt.kitty_keyboard_flags) == 1 + assert dt.modes.is_set(libvt.Mode.IRM) is False + assert dt.modes.is_set(libvt.Mode.DECOM) is False + assert dt.modes.is_set(libvt.Mode.DECAWM) is True + assert dt.modes.is_set(libvt.Mode.DECTCEM) is True + assert dt.modes.is_set(libvt.Mode.DECLRMM) is False + assert dt.cursor.visible is True + assert (dt.cursor.shape, dt.cursor.blinking) == (libvt.CursorShape.BLOCK, True) + assert dt.screen.scroll_region == libvt.ScrollRegion(0, 3, 0, 7) + dt.feed(b"l\x1b8") + assert dt[dt.cursor.row, 0].style.fg is None + assert (dt.cursor.row, dt.cursor.col) == (0, 0) + + # 2. _single_shift saved/restored by DECSC; DEFAULT shares primary slot with ?1049h + # while alt screen keeps its own DECSC slot; CSI 5;10 s with ?69 off is ignored. + ss_t = libvt.Terminal(rows=4, cols=8, profile=DEFAULT_PROFILE) + ss_t.feed(b"\x1b*0\x1bN\x1b7\x1b[2;2Hll\x1b8ll") + assert (ss_t[1, 1].text, ss_t[1, 2].text) == ("┌", "l") + assert (ss_t[0, 0].text, ss_t[0, 1].text) == ("┌", "l") + + def_sc = libvt.Terminal(rows=4, cols=8, profile=DEFAULT_PROFILE) + def_sc.feed(b"\x1b[3;1H\x1b7\x1b[3;3H\x1b[5;10s\x1b8") + assert (def_sc.cursor.row, def_sc.cursor.col) == (2, 0) + def_sc.feed(b"\x1b[3;3H\x1b[?1049h\x1b[1;5H\x1b7\x1b[2;6H\x1b8\x1b[?1049l\x1b8") + assert (def_sc.cursor.row, def_sc.cursor.col) == (2, 2) + + # 3. TMUX_PROFILE: separate DECSC vs ?1049h slots, ?69/?1048 off, CSI 5;10 s saves. + tm_sc = libvt.Terminal(rows=4, cols=8, profile=TMUX_PROFILE) + tm_sc.feed( + b"\x1b[3;1H\x1b7\x1b[1;5H\x1b[?1048h\x1b[?1048$p\x1b[3;3H\x1b[?1049h\x1b[?1049l\x1b8" + ) + assert tm_sc.drain_replies() == b"\x1b[?1048;0$y" + assert (tm_sc.cursor.row, tm_sc.cursor.col) == (2, 0) + tm_sc.feed(b"\x1b[?69h\x1b[?69$p\x1b[2;5H\x1b[5;10s\x1b[4;7H\x1b[u") + assert tm_sc.modes.is_set(libvt.Mode.DECLRMM) is False + assert tm_sc.drain_replies() == b"\x1b[?69;0$y" + assert (tm_sc.cursor.row, tm_sc.cursor.col) == (1, 4) + + # Pending SS2 does not leak onto fresh alternate screen on ?1049h. + ss_alt = libvt.Terminal(rows=2, cols=8, profile=DEFAULT_PROFILE) + ss_alt.feed(b"\x1b*0\x1bN\x1b[?1049hl") + assert ss_alt[0, 0].text == "l" + + # 4. TMUX_PROFILE top > 0 DECSTBM scrollback + ScreenDelta + PromptZone + gfx. + tm_top = libvt.Terminal(rows=4, cols=8, scrollback=10, profile=TMUX_PROFILE) + tok = tm_top.sync_token() + rep_h: list[RowView] = [] + rep_v: list[RowView] = [tm_top.snapshot()[i] for i in range(4)] + tm_top.feed( + b"\x1b]133;A\x07HDR\r\n" + b"\x1b]133;A\x07R1\r\n" + b"R2\r\n" + b"\x1b]133;A\x07FTR" + b"\x1b[2;3r\x1b[3;1H\nNEW2" + ) + delta = tm_top.changes_since(tok) + delta.apply_rows(rep_h, rep_v) + snap_top = delta.snapshot + assert [r.text for r in snap_top.history] == ["R1"] + assert snap_top.lines == ("HDR", "R2", "NEW2", "FTR") + assert [r.text for r in rep_h] == ["R1"] + assert [r.text for r in rep_v] == ["HDR", "R2", "NEW2", "FTR"] + assert [snap_top.at_abs(z.abs_row).text for z in snap_top.prompt_zones] == [ + "HDR", + "R1", + "FTR", + ] + # DL inside top > 0 does not push to history. + tm_top.feed(b"\x1b[2;1H\x1b[M") + assert [r.text for r in tm_top.history] == ["R1"] + assert tm_top.lines == ("HDR", "NEW2", "", "FTR") + + # Wrapped row evicted from top > 0 DECSTBM or ED 2 does not glue onto viewport[0], + # and SIXEL inside top > 0 DECSTBM clips at top without covering HDR. + tm_wrap = libvt.Terminal(rows=4, cols=8, scrollback=10, profile=TMUX_PROFILE) + tm_wrap.feed(b"HEADER\r\n1234567890\r\nFOOTER\x1b[2;3r\x1b[3;1H\n") + assert tm_wrap.history[-1].wrapped is False + tm_wrap.resize(rows=4, cols=16, reflow=True) + assert tm_wrap.lines[0] == "HEADER" + + tm_sx = libvt.Terminal(rows=4, cols=8, scrollback=10, profile=TMUX_PROFILE) + tm_sx.feed( + b'HEADER\r\nR1\r\nR2\r\nFOOTER\x1b[2;3r\x1b[3;1H\x1bP0;1;0q"1;1;16;48#0!16~\x1b\\' + ) + sx_snap = tm_sx.snapshot() + assert sx_snap.placements[0].occupies_abs(sx_snap.scrolled_total, 0) is False + + # DEFAULT_PROFILE keeps top > 0 DECSTBM scrolls out of history. + def_top = libvt.Terminal(rows=4, cols=8, scrollback=10, profile=DEFAULT_PROFILE) + def_top.feed(b"HDR\r\nR1\r\nR2\r\nFTR\x1b[2;3r\x1b[3;1H\nNEW2") + assert list(def_top.history) == [] + assert def_top.lines == ("HDR", "R2", "NEW2", "FTR") + + +def test_osc_palette_dynamic_colors_decrqm_xtsmgraphics_and_notifications() -> None: + """``OSC 4/104/10-12/112``, ``DECRQM``, ``XTSMGRAPHICS``, and ``OSC 9/99/777``.""" + term = libvt.Terminal( + rows=4, + cols=10, + policy=Policy(strict=True), + record_events=True, + ) + # Default OSC 4 query + multi-pair set/query + selective/full OSC 104 reset. + term.feed(b"\x1b]4;1;?\x07") + assert term.drain_replies() == b"\x1b]4;1;rgb:cdcd/0000/0000\x07" + + term.feed(b"\x1b]4;1;#123456;2;rgb:aa/bb/cc;1;?;2;?\x1b\\") + assert term.drain_replies() == ( + b"\x1b]4;1;rgb:1212/3434/5656\x1b\\\x1b]4;2;rgb:aaaa/bbbb/cccc\x1b\\" + ) + term.feed(b"\x1b]104;1\x07\x1b]104;999\x07\x1b]4;1;?;2;?\x07") + assert term.drain_replies() == ( + b"\x1b]4;1;rgb:cdcd/0000/0000\x07\x1b]4;2;rgb:aaaa/bbbb/cccc\x07" + ) + + # Semicolon-chained OSC 10;?;?;? + OSC 12 / OSC 112 + DECSTR palette reset. + term.feed(b"\x1b]12;#abcdef\x07\x1b]10;?;?;?\x07") + assert term.drain_replies() == ( + b"\x1b]10;rgb:e5e5/e5e5/e5e5\x07" + b"\x1b]11;rgb:1e1e/1e1e/1e1e\x07" + b"\x1b]12;rgb:abab/cdcd/efef\x07" + ) + # DECSTR resets OSC 4 palette overrides while keeping OSC 10-12 dynamic colors. + term.feed(b"\x1b[!p\x1b]4;2;?\x07\x1b]12;?\x07") + assert term.drain_replies() == ( + b"\x1b]4;2;rgb:0000/cdcd/0000\x07\x1b]12;rgb:abab/cdcd/efef\x07" + ) + term.feed(b"\x1b]112;extra\x07\x1b]12;?\x07\x1b]112\x07\x1b]12;?\x07") + assert term.drain_replies() == ( + b"\x1b]12;rgb:abab/cdcd/efef\x07\x1b]12;rgb:e5e5/e5e5/e5e5\x07" + ) + + # DECRQM unknown modes return 0; XTSMGRAPHICS replies ?Pi;3S before DA1 sentinel. + term.feed( + b"\x1b[4$p\x1b[99$p\x1b[?2026$p\x1b[?9999$p" + b"\x1b[>1$p\x1b[?1;2$p" + b"\x1b[?1;1;0S\x1b[?2;3;800;600S\x1b[c" + ) + assert term.drain_replies() == ( + b"\x1b[4;2$y" + b"\x1b[99;0$y" + b"\x1b[?2026;2$y" + b"\x1b[?9999;0$y" + b"\x1b[?1;3S" + b"\x1b[?2;3S" + DEFAULT_PROFILE.da1 + ) + + # Policy(allow_color_queries=False) suppresses OSC 4 and OSC 10-12 replies. + no_color = libvt.Terminal(rows=2, cols=8, policy=Policy(allow_color_queries=False)) + no_color.feed(b"\x1b]4;1;?\x07\x1b]10;?;?;?\x07") + assert no_color.drain_replies() == b"" + + # Partial OSC 4 / 10-12 stops at first malformed pair; OSC 104 / 110 / RIS resets. + edge_t = libvt.Terminal( + rows=2, + cols=8, + profile=libvt.Profile(cursor_rgb=(1, 2, 3)), + limits=libvt.Limits(max_reply_bytes=64), + ) + edge_t.feed( + b"\x1b]4;1;#112233;bad;#445566;2;#778899\x07" + b"\x1b]4;2;#223344;3;notacolor;4;#778899\x07" + b"\x1b]4;+1;#999999;256;#999999\x07" + b"\x1b]4;1;?;2;?;3;?;4;?\x07" + ) + capped_rep = edge_t.drain_replies() + assert len(capped_rep) <= 64 + assert capped_rep.startswith( + b"\x1b]4;1;rgb:1111/2222/3333\x07\x1b]4;2;rgb:2222/3333/4444\x07" + ) + edge_t.feed(b"\x1b]4;3;?;4;?\x07") + assert edge_t.drain_replies() == ( + b"\x1b]4;3;rgb:cdcd/cdcd/0000\x07\x1b]4;4;rgb:0000/0000/eeee\x07" + ) + edge_t.feed(b"\x1b]104;;\x07\x1b]4;1;?\x07") + assert edge_t.drain_replies() == b"\x1b]4;1;rgb:cdcd/0000/0000\x07" + + # 2000-pair OSC 4 query flood respects max_reply_bytes without dropping sets. + flood = b"\x1b]4;" + b"1;?;" * 2_000 + b"5;#abcdef\x07" + edge_t.feed(flood) + assert len(edge_t.drain_replies()) <= 64 + edge_t.feed(b"\x1b]4;5;?\x07") + assert edge_t.drain_replies() == b"\x1b]4;5;rgb:abab/cdcd/efef\x07" + edge_t.feed(b"\x1b]104\x07\x1b]4;5;?\x07") + assert edge_t.drain_replies() == b"\x1b]4;5;rgb:cdcd/0000/cdcd\x07" + + # Chained OSC 10 set/query stops past 12 or on bad spec; OSC 110/111 & RIS reset. + edge_t2 = libvt.Terminal( + rows=2, cols=8, profile=libvt.Profile(cursor_rgb=(1, 2, 3)) + ) + edge_t2.feed(b"\x1b]10;#112233;bad;#778899\x07\x1b]10;?;?;?;?\x07") + assert edge_t2.drain_replies() == ( + b"\x1b]10;rgb:1111/2222/3333\x07" + b"\x1b]11;rgb:1e1e/1e1e/1e1e\x07" + b"\x1b]12;rgb:0101/0202/0303\x07" + ) + edge_t2.feed(b"\x1b]110;extra\x07\x1b]10;?\x07\x1b]110\x07\x1b]10;?\x07") + assert edge_t2.drain_replies() == ( + b"\x1b]10;rgb:1111/2222/3333\x07\x1b]10;rgb:e5e5/e5e5/e5e5\x07" + ) + edge_t2.feed(b"\x1b]10;#112233;#445566;#778899\x07\x1bc\x1b]12;?\x07") + assert edge_t2.drain_replies() == b"\x1b]12;rgb:0101/0202/0303\x07" + + # DEC_PRIVATE_MASK (32768) boundary: Ps >= 32768 never aliases DEC modes, + # and Formatter(OutputFormat.VT) round-trips ?1007l. + edge_t2.feed(b"\x1b[32769$p\x1b[33775$p\x1b[?32769$p\x1b[33817h\x1b[?1007l") + assert edge_t2.screens.active_is_alt is False + assert edge_t2.drain_replies() == b"\x1b[32769;0$y\x1b[33775;0$y\x1b[?32769;0$y" + vt_1007 = edge_t2.snapshot().format(libvt.OutputFormat.VT) + restored_1007 = libvt.Terminal(rows=2, cols=8) + restored_1007.feed(vt_1007.encode()) + assert restored_1007.modes.is_set(libvt.Mode.ALTERNATE_SCROLL) is False + edge_t2.feed(b"\x1b]7;file://localhost/%ff\x07") + assert edge_t2.cwd != "" + + # ?2048 resize reports pixel height and width from Profile cell dimensions. + term.feed(b"\x1b[?2048h") + term.resize(rows=10, cols=40) + assert term.drain_replies() == b"\x1b[48;10;40;160;320t" + + # OSC 9 (text), OSC 99, and OSC 777 consume silently under Policy(strict=True). + term.drain_events() + term.feed( + b"\x1b]9;Desktop alert\x07" + b"\x1b]99;i=1:d=0;Hello\x1b\\" + b"\x1b]777;notify;Build;Done\x07" + ) + assert term.drain_events() == () diff --git a/tests/test_tmux.py b/tests/test_tmux.py index 099e2c5..b0335a4 100644 --- a/tests/test_tmux.py +++ b/tests/test_tmux.py @@ -11,12 +11,14 @@ import libvt from libvt.modes import Mode -from libvt.style import AnsiColor +from libvt.style import AnsiColor, IndexedColor from libvt.tmux import ( TMUX_METADATA_FORMAT, TmuxLineFlags, TmuxPaneMetadata, + build_tmux_capture_command, decode_tmux_capture, + parse_flagged_line, unescape_tmux_control_output, ) @@ -307,3 +309,255 @@ def test_live_tmux_capture_pane_roundtrip() -> None: check=False, capture_output=True, ) + + +def test_capture_overline_scoping_ntf_wraps_and_command_bundle() -> None: + """``5:3`` is capture-only and ``-N -T -F`` / command bundles disambiguate wraps.""" + sgr_res = decode_tmux_capture( + ["\x1b[0;1;5:3;38;5;3mA\x1b[0;38:5:3mB"], + rows=1, + cols=4, + trim_trailing=True, + ) + assert sgr_res.terminal[0, 0].style.overline is True + assert sgr_res.terminal[0, 0].style.bold is True + assert sgr_res.terminal[0, 0].style.fg == IndexedColor(3) + assert sgr_res.terminal[0, 1].style.overline is False + assert sgr_res.terminal[0, 1].style.blink is False + assert sgr_res.terminal[0, 1].style.fg == IndexedColor(3) + sgr_res.terminal.feed(b"\x1b[0m\x1b[5:3mZ") + assert sgr_res.terminal[0, 0].style.overline is False + assert sgr_res.terminal[0, 0].style.blink is False + + trunc_rgb = decode_tmux_capture( + ["\x1b[38;2;1;5:3mA\x1b[999b\x1b[?1049h"], + rows=1, + cols=6, + ) + assert trunc_rgb.terminal[0, 0].style.bold is True + assert trunc_rgb.terminal[0, 0].style.overline is True + assert trunc_rgb.terminal[0].text == "A" + assert trunc_rgb.snapshot.active_is_alt is False + + meta4 = TmuxPaneMetadata(cols=4, rows=8) + ntf_term = libvt.Terminal.from_tmux_capture( + [ + "W abc", + "X 中文", + "W abc ", + "X 中文", + "W ab ", + "X 中文", + "- hi ", + "- ", + ], + metadata=meta4, + flagged=True, + trim_trailing=True, + ) + ntf_term.resize(rows=8, cols=8) + assert ntf_term.lines[:4] == ("abc中文", "abc 中文", "ab 中文", "hi ") + + trail_term = libvt.Terminal.from_tmux_capture( + ["- hi ", "- "], + metadata=TmuxPaneMetadata(cols=4, rows=2), + flagged=True, + trim_trailing=True, + ) + trail_term.resize(rows=2, cols=3) + assert (trail_term[0].text, trail_term[0].wrapped) == ("hi ", True) + + nt_joined = libvt.Terminal.from_tmux_capture( + ["abcdefghi", "中 X"], + metadata=TmuxPaneMetadata(cols=10, rows=2), + trim_trailing=True, + joined_capture=["abcdefghi中\tX"], + ) + nt_joined.resize(rows=2, cols=20) + assert nt_joined.lines == ("abcdefghi中 X", "") + + cmd_38 = build_tmux_capture_command("sess;", tmux_version="3.8a", nonce="NONCE_38") + assert "sess\\;" in cmd_38.argv + assert "-T" in cmd_38.argv + assert "-F" in cmd_38.argv + assert cmd_38.flagged is True + assert cmd_38.trim_trailing is True + assert cmd_38.has_joined is False + + cmd_36 = build_tmux_capture_command("%1", tmux_version="3.6", nonce="NONCE_36") + assert "-T" in cmd_36.argv + assert "-F" not in cmd_36.argv + assert "-J" in cmd_36.argv + assert cmd_36.flagged is False + assert cmd_36.trim_trailing is True + assert cmd_36.has_joined is True + + cmd_33 = build_tmux_capture_command("%1", tmux_version="3.3a", nonce="NONCE_33") + assert "-T" not in cmd_33.argv + assert cmd_33.trim_trailing is False + assert cmd_33.has_joined is True + + with pytest.raises(ValueError, match="nonce"): + build_tmux_capture_command("%0", nonce="bad#nonce") + with pytest.raises(ValueError, match="nonce"): + build_tmux_capture_command("%0", nonce="NONCE_38\n") + with pytest.raises(ValueError, match="target"): + build_tmux_capture_command("") + with pytest.raises(ValueError, match="invalid tmux capture-pane -F"): + parse_flagged_line("-\n rest") + with pytest.raises(ValueError, match="invalid tmux version"): + libvt.Profile.tmux((True, 8)) + with pytest.raises(ValueError, match="invalid tmux version"): + libvt.Profile.tmux("9999.0") + + clamped_meta = TmuxPaneMetadata.from_format_line("2147483647\t2147483647") + assert (clamped_meta.cols, clamped_meta.rows) == (10_000, 10_000) + + sp_wrap = decode_tmux_capture( + ["ABCD", " ", "XYZ "], + rows=3, + cols=4, + trim_trailing=False, + joined_capture=["ABCD ", "XYZ"], + ) + assert sp_wrap.completeness.exact_wraps is True + assert [sp_wrap.terminal[i].wrapped for i in range(3)] == [True, False, False] + sp_wrap.terminal.resize(rows=3, cols=8) + assert sp_wrap.terminal.lines == ("ABCD", "XYZ", "") + + empty_mid = decode_tmux_capture( + ["ABCD", "", "EF"], + rows=3, + cols=4, + trim_trailing=True, + joined_capture=["ABCD", "EF"], + ) + assert empty_mid.completeness.exact_wraps is False + assert [empty_mid.terminal[i].wrapped for i in range(3)] == [False, False, False] + + alt_short = decode_tmux_capture( + ["P H0", "P H1", "- ALT0", "- ALT1", "- ALT2"], + metadata=TmuxPaneMetadata(cols=4, rows=3, alternate_on=True, history_size=2), + scrollback=1, + flagged=True, + saved_primary_capture=["- P0"], + ) + assert [z.abs_row for z in alt_short.terminal._prompt_zones] == [1] + alt_short.terminal.feed(b"\x1b[?1049l") + assert [r.text for r in alt_short.terminal.history] == ["H1"] + assert alt_short.terminal.lines == ("P0", "", "") + + pre_line = ( + "4\t2\t0\t1\t1\t0\t4294967295\t4294967295\t0\t1\t" + "0\t0\t1\t0\t0\t0\t0\t0\t0\t\t\t0\t2000\t0\t9\t/tmp/dir\ninject\tt" + ) + bundle_out = ( + f"NONCE_38:PRE:{pre_line}\r\n" + "NONCE_38:CAPTURE\r\n" + "W abc\r\n" + "X 中文\r\n" + "NONCE_38:SAVED\r\n" + "\r\n" + f"NONCE_38:POST:{pre_line}\r\n" + ) + parsed_bundle = cmd_38.parse(bundle_out.encode("utf-8")) + assert parsed_bundle.completeness.exact_generation_bracket is True + parsed_bundle.terminal.resize(rows=2, cols=8) + assert parsed_bundle.terminal.lines == ("abc中文", "") + + spoof_pre = "24" + pre_line[1:] + spoof_bundle = ( + f"NONCE_36:PRE:{spoof_pre}\n" + "NONCE_36:CAPTURE\n" + "NONCE_36:POST:spoof\n" + "row2\n" + "NONCE_36:JOINED\n" + "NONCE_36:POST:spoof\n" + "row2\n" + "NONCE_36:SAVED\n" + "\n" + "NONCE_36:SAVED_JOINED\n" + "\n" + f"NONCE_36:POST:{spoof_pre}\n" + ) + spoof_res = cmd_36.parse(spoof_bundle) + assert spoof_res.completeness.exact_generation_bracket is True + assert spoof_res.completeness.exact_wraps is True + assert spoof_res.terminal.lines == ("NONCE_36:POST:spoof", "row2") + + +@pytest.mark.integration +@pytest.mark.skipif(shutil.which("tmux") is None, reason="tmux binary not installed") +def test_live_tmux_chained_bundle_overline_wraps_and_alt_screen() -> None: + """Live ``tmux`` chained command bundle preserves wraps, ``5:3``, and ``-a``.""" + sock = f"libvt-test-{zlib.crc32(b'tmux-bundle')}" + try: + ver_out = subprocess.run( + ["tmux", "-V"], + check=True, + capture_output=True, + text=True, + ).stdout.strip() + subprocess.run( + [ + "tmux", + "-L", + sock, + "-f", + "/dev/null", + "new-session", + "-d", + "-x", + "4", + "-y", + "5", + "sh", + "-c", + ( + "printf '\\033[53mOV\\033[0m\\r\\n" + "abc\\344\\270\\255\\346\\226\\207\\r\\n" + "abc \\344\\270\\255\\346\\226\\207\\r\\n" + "ab \\344\\270\\255\\346\\226\\207\\r\\n" + "\\033[?1049h\\033[HALT!'; sleep 30" + ), + ], + check=True, + ) + for _ in range(100): + chk = subprocess.run( + ["tmux", "-L", sock, "capture-pane", "-p"], + check=True, + capture_output=True, + text=True, + ) + if "ALT!" in chk.stdout: + break + time.sleep(0.01) + else: + pytest.fail("timed out waiting for tmux alt-screen output") + + cmd = build_tmux_capture_command("%0", tmux_version=ver_out) + raw_out = subprocess.run( + ["tmux", "-L", sock, *cmd.argv], + check=True, + capture_output=True, + text=True, + ).stdout + libtmux_lines = raw_out.split("\n") + while libtmux_lines and libtmux_lines[-1] == "": + libtmux_lines.pop() + + for payload in (raw_out, libtmux_lines): + res = cmd.parse(payload) + assert res.snapshot.active_is_alt is True + assert res.terminal[0].text == "ALT!" + res.terminal.feed(b"\x1b[?1049l") + assert res.terminal.history[0][0].style.overline is True + res.terminal.resize(rows=6, cols=8) + assert res.terminal.lines[:4] == ("OV", "abc中文", "abc 中文", "ab 中文") + finally: + subprocess.run( + ["tmux", "-L", sock, "kill-server"], + check=False, + capture_output=True, + )