Skip to content

Commit ae61d4f

Browse files
committed
Screen(fix[resize]): Preserve pending_wrap on resize (#4)
why: Unconditionally clearing pending_wrap on resize caused same-size resizes to overwrite the last column, widening with reflow to drop the right-margin advance, and dummy cursor cells to inject phantom blank rows on exact-fit shrinks. what: - Add reflow_on_resize to Profile (False on XTERM_PROFILE) and default Terminal.resize and PtySession.resize reflow=None to the profile - Return early from Screen.resize when dimensions do not change - Track logical eff_cur_col and cur_after_extra in _reflow_primary without dummy trailing cells - Preserve pending_wrap on non-reflow resizes when old_cur_col < cols and synchronize _saved_primary cursor state when resizing on ?1049h
1 parent 63e126a commit ae61d4f

5 files changed

Lines changed: 162 additions & 34 deletions

File tree

‎src/libvt/aio.py‎

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -394,7 +394,13 @@ def paste(self, text: str, /, *, sanitize: bool = False) -> None:
394394
"""Encode *text* as a :class:`PasteEvent` and write to the PTY."""
395395
self.send_event(PasteEvent(text=text, sanitize=sanitize))
396396

397-
def resize(self, *, rows: int, cols: int, reflow: bool = True) -> None:
397+
def resize(
398+
self,
399+
*,
400+
rows: int,
401+
cols: int,
402+
reflow: bool | None = None,
403+
) -> None:
398404
"""Update kernel ``TIOCSWINSZ`` and resize :attr:`terminal`."""
399405
import fcntl
400406
import termios

‎src/libvt/config.py‎

Lines changed: 9 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,7 @@ class ColorScheme(enum.IntEnum):
1313
LIGHT = 2
1414

1515

16-
@dataclass(frozen=True, slots=True)
16+
@dataclass(frozen=True, slots=True, kw_only=True)
1717
class Profile:
1818
r"""Terminal identity responses and compatibility switches.
1919
@@ -52,6 +52,10 @@ class Profile:
5252
tmux_window_rename : bool
5353
When ``True`` (``TMUX_PROFILE``), ``ESC k <name> ESC \`` is consumed as
5454
a window-rename control string rather than printed onto the grid.
55+
reflow_on_resize : bool
56+
Default reflow behavior for :meth:`~libvt.terminal.Terminal.resize`
57+
when ``reflow=None`` (``True`` on ``DEFAULT_PROFILE`` and
58+
``TMUX_PROFILE``, ``False`` on ``XTERM_PROFILE``).
5559
"""
5660

5761
name: str = "libvt"
@@ -68,12 +72,13 @@ class Profile:
6872
vs15_narrows_wide_emoji: bool = True
6973
vs16_always_wide: bool = False
7074
tmux_window_rename: bool = False
75+
reflow_on_resize: bool = True
7176

7277

7378
DEFAULT_OSC7_HOSTS: frozenset[str] = frozenset({"", "localhost"})
7479

7580

76-
@dataclass(frozen=True, slots=True)
81+
@dataclass(frozen=True, slots=True, kw_only=True)
7782
class Policy:
7883
r"""Default-deny host security and strictness policy.
7984
@@ -131,7 +136,7 @@ class Policy:
131136
strict: bool = False
132137

133138

134-
@dataclass(frozen=True, slots=True)
139+
@dataclass(frozen=True, slots=True, kw_only=True)
135140
class Limits:
136141
"""Resource ceilings protecting memory and CPU against hostile byte streams.
137142
@@ -189,6 +194,7 @@ class Limits:
189194
XTERM_PROFILE = Profile(
190195
name="xterm",
191196
osc_7501_capabilities="",
197+
reflow_on_resize=False,
192198
)
193199
TMUX_PROFILE = Profile(
194200
name="tmux",

‎src/libvt/screen.py‎

Lines changed: 51 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -800,11 +800,12 @@ def _reflow_primary(self, *, rows: int, cols: int) -> None:
800800

801801
combined = hist_thawed + self._rows[: last_active + 1]
802802
cur_abs_idx = hist_len + self._cur_row
803-
cur_col = self._cur_col
803+
eff_cur_col = self._cur_col + (1 if self._pending_wrap else 0)
804804

805805
new_all: list[_Row] = []
806806
new_cur_abs = 0
807807
new_cur_col = 0
808+
new_pending_wrap = False
808809
cursor_placed = False
809810

810811
idx = 0
@@ -816,83 +817,103 @@ def _reflow_primary(self, *, rows: int, cols: int) -> None:
816817
group_end = idx
817818
idx += 1
818819

819-
# Extract logical cells across [group_start .. group_end].
820-
cells: list[tuple[str, int, int, _CellExt | None, bool, bool]] = []
820+
if group_start <= cur_abs_idx < group_end and eff_cur_col >= len(
821+
combined[cur_abs_idx].chars
822+
):
823+
cur_abs_idx += 1
824+
eff_cur_col = 0
825+
826+
# Extract real logical cells across [group_start .. group_end].
827+
cells: list[tuple[str, int, int, _CellExt | None, int]] = []
828+
cur_after_extra: int | None = None
829+
carry_cur = False
821830
for r_i in range(group_start, group_end + 1):
822831
src = combined[r_i]
823832
is_last = r_i == group_end
824833
src_t_used = src.text_used if isinstance(src, _Row) else len(src.text)
825834
row_limit = len(src.chars) if not is_last else src_t_used
826-
limit = max(row_limit, cur_col + 1) if r_i == cur_abs_idx else row_limit
827-
for c_i in range(limit):
835+
if r_i == cur_abs_idx and eff_cur_col >= row_limit:
836+
cur_after_extra = eff_cur_col - row_limit
837+
for c_i in range(row_limit):
828838
word = src.attr_at(c_i)
829839
rb = raw_width_bits(word)
830-
is_cur = r_i == cur_abs_idx and c_i == cur_col
831-
is_dummy = is_last and c_i >= row_limit
840+
is_cur = r_i == cur_abs_idx and c_i == eff_cur_col
832841
if rb == int(WidthRole.SPACER_HEAD):
833842
if is_cur:
834-
cells.append((" ", 0, 1, None, True, True))
843+
carry_cur = True
835844
continue
836845
if rb == int(WidthRole.SPACER_TAIL):
837846
if is_cur and cells:
838-
p_ch, p_w, p_cw, p_ext, _, p_dum = cells[-1]
839-
cells[-1] = (p_ch, p_w, p_cw, p_ext, True, p_dum)
847+
p_ch, p_w, p_cw, p_ext, _ = cells[-1]
848+
cells[-1] = (p_ch, p_w, p_cw, p_ext, 1)
840849
continue
841850
cw = 2 if rb == int(WidthRole.WIDE) else 1
842851
base_word = word & _WIDTH_CLEAR_MASK
852+
cur_off = 0 if (is_cur or carry_cur) else -1
853+
carry_cur = False
843854
cells.append(
844855
(
845856
src.chars[c_i],
846857
base_word,
847858
cw,
848859
src.ext_at(c_i),
849-
is_cur,
850-
is_dummy,
860+
cur_off,
851861
)
852862
)
853863

854864
if not cells:
855865
empty_row = _Row(cols)
866+
new_all.append(empty_row)
856867
if group_start <= cur_abs_idx <= group_end and not cursor_placed:
857-
new_cur_abs = len(new_all)
858-
new_cur_col = 0
868+
extra = 0 if cur_after_extra is None else cur_after_extra
869+
new_cur_abs = len(new_all) - 1
870+
new_cur_col = min(cols - 1, extra)
871+
new_pending_wrap = False
859872
cursor_placed = True
860-
new_all.append(empty_row)
861873
continue
862874

863875
cur_out = _Row(cols)
864876
new_all.append(cur_out)
865877
out_col = 0
866-
for ch, base_w, cw, ce, is_cur, is_dummy in cells:
878+
for ch, base_w, cw, ce, cur_off in cells:
867879
eff_cw = cw
868880
eff_ch = ch
869881
if eff_cw == 2 and cols == 1:
870882
eff_ch = "\ufffd"
871883
eff_cw = 1
872884

873885
if out_col + eff_cw > cols:
874-
if not is_dummy and out_col < cols:
886+
if out_col < cols:
875887
cur_out.write_spacer_head(out_col, 0, None)
876-
if not is_dummy:
877-
cur_out.wrapped = True
888+
cur_out.wrapped = True
878889
cur_out = _Row(cols)
879890
new_all.append(cur_out)
880891
out_col = 0
881892

882-
if is_cur and not cursor_placed:
893+
if cur_off >= 0 and not cursor_placed:
883894
new_cur_abs = len(new_all) - 1
884-
new_cur_col = out_col
895+
new_cur_col = min(cols - 1, out_col + cur_off)
896+
new_pending_wrap = False
885897
cursor_placed = True
886898

887-
if is_dummy:
888-
out_col += eff_cw
889-
elif eff_cw == 2:
899+
if eff_cw == 2:
890900
cur_out.write_wide(out_col, eff_ch, base_w, ce)
891901
out_col += 2
892902
else:
893903
cur_out.write_narrow(out_col, eff_ch, base_w, ce)
894904
out_col += 1
895905

906+
if (cur_after_extra is not None or carry_cur) and not cursor_placed:
907+
extra = 0 if cur_after_extra is None else cur_after_extra
908+
new_cur_abs = len(new_all) - 1
909+
if extra == 0 and out_col == cols:
910+
new_cur_col = cols - 1
911+
new_pending_wrap = True
912+
else:
913+
new_cur_col = min(cols - 1, out_col + extra)
914+
new_pending_wrap = False
915+
cursor_placed = True
916+
896917
if not new_all:
897918
new_all.append(_Row(cols))
898919

@@ -911,7 +932,7 @@ def _reflow_primary(self, *, rows: int, cols: int) -> None:
911932
self._cols = cols
912933
self._cur_row = max(0, min(rows - 1, new_cur_abs - hist_cut))
913934
self._cur_col = max(0, min(cols - 1, new_cur_col))
914-
self._pending_wrap = False
935+
self._pending_wrap = new_pending_wrap
915936

916937
def resize(self, *, rows: int, cols: int, reflow: bool = True) -> None:
917938
"""Resize screen to ``(rows, cols)``, optionally reflowing soft wraps."""
@@ -920,9 +941,13 @@ def resize(self, *, rows: int, cols: int, reflow: bool = True) -> None:
920941
raise ValueError(msg)
921942

922943
old_cols = self._cols
944+
if rows == len(self._rows) and cols == old_cols:
945+
return
946+
923947
if reflow and cols != old_cols:
924948
self._reflow_primary(rows=rows, cols=cols)
925949
else:
950+
old_cur_col = self._cur_col
926951
if cols != old_cols:
927952
for r in self._rows:
928953
r.resize(cols)
@@ -948,7 +973,7 @@ def resize(self, *, rows: int, cols: int, reflow: bool = True) -> None:
948973

949974
self._cur_row = min(self._cur_row, rows - 1)
950975
self._cur_col = min(self._cur_col, cols - 1)
951-
self._pending_wrap = False
976+
self._pending_wrap = self._pending_wrap and old_cur_col < cols
952977

953978
self.scroll_region = ScrollRegion(
954979
top=0,

‎src/libvt/terminal.py‎

Lines changed: 26 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1080,11 +1080,33 @@ def _notify_erase(self, rect: Rect, cause: EraseCause) -> None:
10801080
),
10811081
)
10821082

1083-
def resize(self, *, rows: int, cols: int, reflow: bool = True) -> None:
1083+
def resize(
1084+
self,
1085+
*,
1086+
rows: int,
1087+
cols: int,
1088+
reflow: bool | None = None,
1089+
) -> None:
10841090
"""Resize terminal screens to ``(rows, cols)``."""
1091+
eff_reflow = self._profile.reflow_on_resize if reflow is None else reflow
10851092
self._before_mutate()
10861093
self._clear_cluster_anchor()
1087-
self._screens.resize(rows=rows, cols=cols, reflow=reflow)
1094+
self._screens.resize(rows=rows, cols=cols, reflow=eff_reflow)
1095+
if not self._modes.is_set(Mode.DECAWM):
1096+
self._screens.primary._pending_wrap = False
1097+
self._screens.alternate._pending_wrap = False
1098+
if self._screens.active_is_alt:
1099+
prim = self._screens.primary
1100+
self._saved_primary = _SavedCursor(
1101+
row=prim._cur_row,
1102+
col=prim._cur_col,
1103+
pending_wrap=prim._pending_wrap,
1104+
style=self._saved_primary.style,
1105+
decom=self._saved_primary.decom,
1106+
g_sets=self._saved_primary.g_sets,
1107+
gl=self._saved_primary.gl,
1108+
protected=self._saved_primary.protected,
1109+
)
10881110
self._generation += 1
10891111
if self._modes.is_set(Mode.IN_BAND_RESIZE):
10901112
self._emit_reply(f"\x1b[48;{rows};{cols};0;0t".encode("ascii"))
@@ -1337,7 +1359,7 @@ def _handle_print(self, text: str) -> None:
13371359
can_advance = scr._cur_row < scr.rows - 1 or (
13381360
scr._cur_row == bottom and left <= c_col <= right
13391361
)
1340-
if can_advance and min_col == 0 and max_col == scr.cols - 1:
1362+
if can_advance and min_col == 0 and c_col == scr.cols - 1:
13411363
scr._rows[scr._cur_row].wrapped = True
13421364
self._linefeed(scr)
13431365
self._set_cursor(scr, scr._cur_row, min_col, pending_wrap=False)
@@ -1554,7 +1576,7 @@ def _handle_print(self, text: str) -> None:
15541576
can_advance = c_row < scr.rows - 1 or (
15551577
c_row == bottom and left <= c_col <= right
15561578
)
1557-
if can_advance and min_col == 0 and max_col == scr.cols - 1:
1579+
if can_advance and min_col == 0 and c_col == scr.cols - 1:
15581580
scr._rows[c_row].wrapped = True
15591581
self._linefeed(scr)
15601582
self._set_cursor(scr, scr._cur_row, min_col, pending_wrap=False)

‎tests/test_pr2_review_fixes.py‎

Lines changed: 69 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,69 @@
1+
"""Regression tests for PR #2 architectural and terminal-profile review fixes."""
2+
3+
from __future__ import annotations
4+
5+
import libvt
6+
from libvt.config import XTERM_PROFILE
7+
8+
9+
def test_resize_preserves_pending_wrap_and_wide_glyphs() -> None:
10+
"""``resize()`` preserves ``pending_wrap``, wide cells, and profile reflow rules."""
11+
# Case 1a: same-size 4x2 -> 4x2 preserves pending_wrap and scroll_region.
12+
same = libvt.Terminal(rows=2, cols=4)
13+
same.feed(b"\x1b[1;2rABCD")
14+
assert same.cursor.pending_wrap is True
15+
same.resize(rows=2, cols=4)
16+
assert same.cursor.pending_wrap is True
17+
same.feed(b"E")
18+
assert same.lines == ("ABCD", "E")
19+
assert (same.cursor.row, same.cursor.col) == (1, 1)
20+
assert same.cursor.pending_wrap is False
21+
assert same[0].wrapped is True
22+
23+
# Case 1b (DEFAULT_PROFILE reflow=True): widen 4x2 -> 8x2 unwraps pending_wrap.
24+
widened = libvt.Terminal(rows=2, cols=4)
25+
widened.feed(b"ABCD")
26+
widened.resize(rows=2, cols=8)
27+
assert widened.cursor.col == 4
28+
assert widened.cursor.pending_wrap is False
29+
widened.feed(b"E")
30+
assert widened.lines == ("ABCDE", "")
31+
assert (widened.cursor.row, widened.cursor.col) == (0, 5)
32+
assert widened[0].wrapped is False
33+
34+
# Case 1b (XTERM_PROFILE reflow_on_resize=False): widen keeps col 3 + pending_wrap.
35+
xt = libvt.Terminal(rows=2, cols=4, profile=XTERM_PROFILE)
36+
xt.feed(b"ABCD")
37+
xt.resize(rows=2, cols=8)
38+
assert xt.cursor.col == 3
39+
assert xt.cursor.pending_wrap is True
40+
xt.feed(b"E")
41+
assert xt.lines == ("ABCD", "E")
42+
assert (xt.cursor.row, xt.cursor.col) == (1, 1)
43+
assert xt[0].wrapped is False
44+
45+
# Wide glyph ending at right margin ('AB界' on 4 cols) reflows cleanly on widen.
46+
wide = libvt.Terminal(rows=2, cols=4)
47+
wide.feed("AB界".encode())
48+
assert wide.cursor.pending_wrap is True
49+
wide.resize(rows=2, cols=8)
50+
wide.feed(b"E")
51+
assert wide.lines == ("AB界E", "")
52+
assert (wide.cursor.row, wide.cursor.col) == (0, 5)
53+
54+
# Exact-fit shrink 8x2 -> 4x2 after 'ABCD' produces no phantom blank row.
55+
shrink = libvt.Terminal(rows=2, cols=8, scrollback=10)
56+
shrink.feed(b"ABCD")
57+
assert (shrink.cursor.row, shrink.cursor.col) == (0, 4)
58+
shrink.resize(rows=2, cols=4)
59+
assert shrink.history == ()
60+
shrink.feed(b"E")
61+
assert shrink.lines == ("ABCD", "E")
62+
assert (shrink.cursor.row, shrink.cursor.col) == (1, 1)
63+
64+
# Resizing while inside ?1049h keeps primary saved cursor synchronized on ?1049l.
65+
alt_resize = libvt.Terminal(rows=2, cols=4)
66+
alt_resize.feed(b"ABCDabc\x1b[?1049h")
67+
alt_resize.resize(rows=2, cols=8)
68+
alt_resize.feed(b"\x1b[?1049lX")
69+
assert alt_resize[0].text == "ABCDabcX"

0 commit comments

Comments
 (0)