libvt 0.0.1a0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
libvt/_grid.py ADDED
@@ -0,0 +1,1075 @@
1
+ """Two-tier row storage: lazy 64-bit packed viewport ``_Row`` and RLE ``FrozenRow``.
2
+
3
+ Bit layout of each 64-bit unsigned attribute word (``0`` == blank default cell):
4
+
5
+ - bits ``0..24`` (25b): foreground color (``0`` default, ``1..16`` ANSI,
6
+ ``256..511`` 256-palette index, ``(1 << 24) | 0xRRGGBB`` RGB)
7
+ - bits ``25..49`` (25b): background color
8
+ - bits ``50..56`` (7b): ``bold``, ``dim``, ``italic``, ``blink``, ``reverse``,
9
+ ``hidden``, ``strikethrough``
10
+ - bits ``57..59`` (3b): :class:`~libvt.style.UnderlineStyle`
11
+ - bits ``60..61`` (2b): :class:`~libvt._ucd.WidthRole`
12
+ - bit ``62`` (1b): ``overline``
13
+ - bit ``63`` (1b): ``HAS_EXT`` gating sparse :class:`_CellExt`
14
+ """
15
+
16
+ from __future__ import annotations
17
+
18
+ import array
19
+ import bisect
20
+ import collections.abc
21
+ import operator
22
+ import typing as t
23
+ from dataclasses import dataclass
24
+
25
+ from libvt._ucd import WidthRole
26
+ from libvt.style import (
27
+ DEFAULT_STYLE,
28
+ AnsiColor,
29
+ Color,
30
+ Hyperlink,
31
+ IndexedColor,
32
+ RgbColor,
33
+ Style,
34
+ UnderlineStyle,
35
+ )
36
+
37
+ _ITEM0 = operator.itemgetter(0)
38
+ _HISTORY_BLOCK_SHIFT = 8
39
+ _HISTORY_BLOCK_SIZE = 1 << _HISTORY_BLOCK_SHIFT
40
+ _HISTORY_BLOCK_MASK = _HISTORY_BLOCK_SIZE - 1
41
+
42
+ _GLOBAL_ROW_GEN: int = 0
43
+
44
+
45
+ def bump_row_gen(row: _Row) -> int:
46
+ """Stamp *row* with the next strictly monotonic mutation generation."""
47
+ global _GLOBAL_ROW_GEN
48
+ _GLOBAL_ROW_GEN += 1
49
+ row.content_gen = _GLOBAL_ROW_GEN
50
+ row._frozen = None
51
+ return _GLOBAL_ROW_GEN
52
+
53
+
54
+ def current_row_gen() -> int:
55
+ """Return the latest global row mutation generation without advancing it."""
56
+ return _GLOBAL_ROW_GEN
57
+
58
+
59
+ _COLOR_MASK = (1 << 25) - 1
60
+ _RGB_FLAG = 1 << 24
61
+ _IDX_BASE = 256
62
+
63
+ _BG_SHIFT = 25
64
+ _BOLD_BIT = 1 << 50
65
+ _DIM_BIT = 1 << 51
66
+ _ITALIC_BIT = 1 << 52
67
+ _BLINK_BIT = 1 << 53
68
+ _REVERSE_BIT = 1 << 54
69
+ _HIDDEN_BIT = 1 << 55
70
+ _STRIKE_BIT = 1 << 56
71
+ _UL_SHIFT = 57
72
+ _UL_MASK = 0b111
73
+ _WIDTH_SHIFT = 60
74
+ _WIDTH_MASK = 0b11
75
+ _WIDTH_CLEAR_MASK = ~(_WIDTH_MASK << _WIDTH_SHIFT) & ((1 << 64) - 1)
76
+ _OVERLINE_BIT = 1 << 62
77
+ _HAS_EXT_BIT = 1 << 63
78
+ _PEN_BASE_MASK = _WIDTH_CLEAR_MASK & ~_HAS_EXT_BIT
79
+ _PEN_BG_MASK = _COLOR_MASK << _BG_SHIFT
80
+
81
+
82
+ @dataclass(frozen=True, slots=True)
83
+ class _CellExt:
84
+ """Sparse per-cell metadata stored only when ``HAS_EXT`` is set.
85
+
86
+ Attributes
87
+ ----------
88
+ underline_color : Color
89
+ Explicit underline color (``SGR 58``), if any.
90
+ hyperlink : Hyperlink | None
91
+ Active ``OSC 8`` hyperlink, if any.
92
+ protected : bool
93
+ ``DECSCA`` character-protection flag respected by ``DECSED``/``DECSEL``.
94
+ """
95
+
96
+ underline_color: Color = None
97
+ hyperlink: Hyperlink | None = None
98
+ protected: bool = False
99
+
100
+
101
+ def _pack_color(color: Color) -> int:
102
+ if color is None:
103
+ return 0
104
+ if isinstance(color, AnsiColor):
105
+ return int(color) + 1
106
+ if isinstance(color, IndexedColor):
107
+ return _IDX_BASE + color.index
108
+ return _RGB_FLAG | (color.r << 16) | (color.g << 8) | color.b
109
+
110
+
111
+ def _unpack_color(bits: int) -> Color:
112
+ if bits == 0:
113
+ return None
114
+ if bits & _RGB_FLAG:
115
+ rgb = bits & 0xFFFFFF
116
+ return RgbColor((rgb >> 16) & 0xFF, (rgb >> 8) & 0xFF, rgb & 0xFF)
117
+ if bits >= _IDX_BASE:
118
+ return IndexedColor(bits - _IDX_BASE)
119
+ return AnsiColor(bits - 1)
120
+
121
+
122
+ def pack_pen_base(style: Style) -> int:
123
+ """Pack *style* into a 64-bit word (leaving ``WidthRole`` and ``HAS_EXT`` clear)."""
124
+ if style == DEFAULT_STYLE:
125
+ return 0
126
+ word = _pack_color(style.fg) | (_pack_color(style.bg) << _BG_SHIFT)
127
+ if style.bold:
128
+ word |= _BOLD_BIT
129
+ if style.dim:
130
+ word |= _DIM_BIT
131
+ if style.italic:
132
+ word |= _ITALIC_BIT
133
+ if style.blink:
134
+ word |= _BLINK_BIT
135
+ if style.reverse:
136
+ word |= _REVERSE_BIT
137
+ if style.hidden:
138
+ word |= _HIDDEN_BIT
139
+ if style.strikethrough:
140
+ word |= _STRIKE_BIT
141
+ if style.underline != UnderlineStyle.NONE:
142
+ word |= (int(style.underline) & _UL_MASK) << _UL_SHIFT
143
+ if style.overline:
144
+ word |= _OVERLINE_BIT
145
+ return word
146
+
147
+
148
+ def make_cell_ext(
149
+ style: Style,
150
+ hyperlink: Hyperlink | None,
151
+ *,
152
+ protected: bool = False,
153
+ ) -> _CellExt | None:
154
+ """Build sparse :class:`_CellExt` when needed, else return ``None``."""
155
+ if style.underline_color is None and hyperlink is None and not protected:
156
+ return None
157
+ return _CellExt(
158
+ underline_color=style.underline_color,
159
+ hyperlink=hyperlink,
160
+ protected=protected,
161
+ )
162
+
163
+
164
+ def unpack_style(word: int, ext: _CellExt | None) -> Style:
165
+ """Unpack a 64-bit cell attribute word and optional :class:`_CellExt`."""
166
+ style_bits = word & _WIDTH_CLEAR_MASK & ~_HAS_EXT_BIT
167
+ if style_bits == 0 and (ext is None or ext.underline_color is None):
168
+ return DEFAULT_STYLE
169
+ fg = _unpack_color(word & _COLOR_MASK)
170
+ bg = _unpack_color((word >> _BG_SHIFT) & _COLOR_MASK)
171
+ ul_raw = (word >> _UL_SHIFT) & _UL_MASK
172
+ ul_color = ext.underline_color if ext is not None else None
173
+ return Style(
174
+ fg=fg,
175
+ bg=bg,
176
+ underline_color=ul_color,
177
+ bold=bool(word & _BOLD_BIT),
178
+ dim=bool(word & _DIM_BIT),
179
+ italic=bool(word & _ITALIC_BIT),
180
+ underline=UnderlineStyle(ul_raw),
181
+ blink=bool(word & _BLINK_BIT),
182
+ reverse=bool(word & _REVERSE_BIT),
183
+ hidden=bool(word & _HIDDEN_BIT),
184
+ strikethrough=bool(word & _STRIKE_BIT),
185
+ overline=bool(word & _OVERLINE_BIT),
186
+ )
187
+
188
+
189
+ def unpack_width_role(word: int) -> WidthRole:
190
+ """Extract :class:`~libvt._ucd.WidthRole` from a 64-bit cell word."""
191
+ raw = (word >> _WIDTH_SHIFT) & _WIDTH_MASK
192
+ if raw == 0:
193
+ return WidthRole.NARROW
194
+ return WidthRole(raw)
195
+
196
+
197
+ def raw_width_bits(word: int) -> int:
198
+ """Extract raw 2-bit width role integer without constructing an Enum."""
199
+ return (word >> _WIDTH_SHIFT) & _WIDTH_MASK
200
+
201
+
202
+ @dataclass(frozen=True, slots=True)
203
+ class FrozenRow:
204
+ """Run-length-encoded immutable scrollback line.
205
+
206
+ Attributes
207
+ ----------
208
+ text : str
209
+ Right-trimmed rendered row text.
210
+ cols : int
211
+ Column count when the row was sealed.
212
+ runs : tuple[tuple[int, int], ...]
213
+ ``(end_col, attr_u64)`` run-length spans; ``()`` when all cells carry
214
+ attribute word ``0``.
215
+ exts : tuple[tuple[int, _CellExt], ...]
216
+ Sorted ``(col, _CellExt)`` sparse metadata pairs.
217
+ cells : tuple[str, ...] | None
218
+ Per-column cell strings up to ``used`` when the row contains wide
219
+ spacers or multi-codepoint clusters; ``None`` when ``text`` maps 1:1
220
+ to narrow columns ``0..len(text) - 1``.
221
+ wrapped : bool
222
+ ``True`` when the row soft-wrapped onto the next row under ``DECAWM``.
223
+ """
224
+
225
+ text: str
226
+ cols: int
227
+ runs: tuple[tuple[int, int], ...] = ()
228
+ exts: tuple[tuple[int, _CellExt], ...] = ()
229
+ cells: tuple[str, ...] | None = None
230
+ wrapped: bool = False
231
+
232
+ @property
233
+ def used(self) -> int:
234
+ """Return count of written columns in this sealed row."""
235
+ text_cols = len(self.cells) if self.cells is not None else len(self.text)
236
+ run_end = self.runs[-1][0] if self.runs else 0
237
+ ext_end = (self.exts[-1][0] + 1) if self.exts else 0
238
+ return max(text_cols, run_end, ext_end)
239
+
240
+ def rstrip_text(self) -> str:
241
+ """Return right-trimmed row text."""
242
+ return self.text
243
+
244
+ def char_at(self, col: int) -> str:
245
+ """Return cell string at *col*."""
246
+ if col < 0 or col >= self.cols:
247
+ return " "
248
+ if self.cells is not None:
249
+ return self.cells[col] if col < len(self.cells) else " "
250
+ return self.text[col] if col < len(self.text) else " "
251
+
252
+ def attr_at(self, col: int) -> int:
253
+ """Return packed 64-bit attribute word at *col*."""
254
+ runs = self.runs
255
+ if not runs or col < 0:
256
+ return 0
257
+ if len(runs) == 1:
258
+ end_col, word = runs[0]
259
+ return word if col < end_col else 0
260
+ idx = bisect.bisect_right(runs, col, key=_ITEM0)
261
+ return runs[idx][1] if idx < len(runs) else 0
262
+
263
+ def ext_at(self, col: int) -> _CellExt | None:
264
+ """Return sparse :class:`_CellExt` at *col*, if any."""
265
+ exts = self.exts
266
+ if not exts or col < 0:
267
+ return None
268
+ if len(exts) == 1:
269
+ ext_col, ce = exts[0]
270
+ return ce if ext_col == col else None
271
+ idx = bisect.bisect_right(exts, col, key=_ITEM0) - 1
272
+ if idx >= 0 and exts[idx][0] == col:
273
+ return exts[idx][1]
274
+ return None
275
+
276
+ def thaw(self, target_cols: int | None = None) -> _Row:
277
+ """Materialize a mutable :class:`_Row` from this sealed line."""
278
+ width = self.cols if target_cols is None else target_cols
279
+ row = _Row(width)
280
+ row.wrapped = self.wrapped
281
+ limit = min(self.used, width)
282
+ if limit == 0 and not self.runs:
283
+ return row
284
+ for c in range(limit):
285
+ row.chars[c] = self.char_at(c)
286
+ if self.runs:
287
+ attrs = row._ensure_attrs()
288
+ start = 0
289
+ for end_col, word in self.runs:
290
+ stop = min(end_col, width)
291
+ for c in range(start, stop):
292
+ attrs[c] = word
293
+ if raw_width_bits(word) != 0:
294
+ row.has_wide = True
295
+ start = stop
296
+ if start >= width:
297
+ break
298
+ if width > 0 and raw_width_bits(attrs[width - 1]) == int(WidthRole.WIDE):
299
+ row.chars[width - 1] = " "
300
+ attrs[width - 1] &= _WIDTH_CLEAR_MASK
301
+ if self.exts:
302
+ row.ext = {c: ce for c, ce in self.exts if c < width}
303
+ row.used = limit
304
+ row.text_used = min(
305
+ len(self.cells) if self.cells is not None else len(self.text), width
306
+ )
307
+ return row
308
+
309
+
310
+ class _Row:
311
+ """Mutable viewport row with lazy 64-bit ``array('Q')`` promotion."""
312
+
313
+ __slots__ = (
314
+ "_frozen",
315
+ "_wrapped",
316
+ "attrs",
317
+ "chars",
318
+ "content_gen",
319
+ "ext",
320
+ "has_wide",
321
+ "text_used",
322
+ "uniform_attr",
323
+ "used",
324
+ )
325
+
326
+ def __init__(self, cols: int) -> None:
327
+ self.chars: list[str] = [" "] * cols
328
+ self.attrs: array.array[int] | None = None
329
+ self.uniform_attr: int = 0
330
+ self.has_wide: bool = False
331
+ self.ext: dict[int, _CellExt] | None = None
332
+ self.used: int = 0
333
+ self.text_used: int = 0
334
+ self._wrapped: bool = False
335
+ self.content_gen: int = 0
336
+ self._frozen: FrozenRow | None = None
337
+
338
+ @property
339
+ def wrapped(self) -> bool:
340
+ """Return ``True`` when this row soft-wrapped onto the next line."""
341
+ return self._wrapped
342
+
343
+ @wrapped.setter
344
+ def wrapped(self, value: bool) -> None:
345
+ if self._wrapped != value:
346
+ self._wrapped = value
347
+ self._frozen = None
348
+
349
+ def _ensure_attrs(self) -> array.array[int]:
350
+ if self.attrs is None:
351
+ self.attrs = array.array("Q", [self.uniform_attr]) * len(self.chars)
352
+ return self.attrs
353
+
354
+ def attr_at(self, col: int) -> int:
355
+ """Return 64-bit attribute word at *col*."""
356
+ if self.attrs is None:
357
+ return self.uniform_attr
358
+ return self.attrs[col]
359
+
360
+ def ext_at(self, col: int) -> _CellExt | None:
361
+ """Return sparse :class:`_CellExt` at *col*, if any."""
362
+ return self.ext.get(col) if self.ext is not None else None
363
+
364
+ def is_protected(self, col: int) -> bool:
365
+ """Return ``True`` when cell *col* carries ``DECSCA`` protection."""
366
+ if self.ext is None:
367
+ return False
368
+ ce = self.ext.get(col)
369
+ return bool(ce is not None and ce.protected)
370
+
371
+ def reset_blank(
372
+ self,
373
+ cols: int,
374
+ bce_word: int = 0,
375
+ bce_ext: _CellExt | None = None,
376
+ ) -> None:
377
+ """Reset this row in place for zero-allocation scroll recycling."""
378
+ if len(self.chars) != cols:
379
+ self.chars = [" "] * cols
380
+ else:
381
+ self.chars[:] = [" "] * cols
382
+ self.attrs = None
383
+ self.uniform_attr = bce_word | (_HAS_EXT_BIT if bce_ext is not None else 0)
384
+ self.has_wide = False
385
+ if bce_ext is not None:
386
+ self.ext = dict.fromkeys(range(cols), bce_ext)
387
+ self.used = cols
388
+ else:
389
+ if self.ext is not None:
390
+ self.ext.clear()
391
+ self.used = cols if bce_word != 0 else 0
392
+ self.text_used = 0
393
+ self._wrapped = False
394
+ bump_row_gen(self)
395
+
396
+ def _set_raw(
397
+ self,
398
+ col: int,
399
+ ch: str,
400
+ pen_word: int,
401
+ role: WidthRole,
402
+ cell_ext: _CellExt | None,
403
+ ) -> None:
404
+ word = pen_word | (int(role) << _WIDTH_SHIFT)
405
+ if cell_ext is not None:
406
+ word |= _HAS_EXT_BIT
407
+ if self.ext is None:
408
+ self.ext = {col: cell_ext}
409
+ else:
410
+ self.ext[col] = cell_ext
411
+ elif self.ext is not None:
412
+ self.ext.pop(col, None)
413
+ if role != WidthRole.NARROW:
414
+ self.has_wide = True
415
+ self.chars[col] = ch
416
+ if self.attrs is None:
417
+ if word == self.uniform_attr:
418
+ return
419
+ self._ensure_attrs()[col] = word
420
+ else:
421
+ self.attrs[col] = word
422
+
423
+ def _heal_wide_boundary(self, col: int) -> None:
424
+ """Clear both halves when an edit or margin boundary splits a wide glyph."""
425
+ if not self.has_wide or self.attrs is None:
426
+ return
427
+ cols = len(self.chars)
428
+ if col < 0 or col >= cols:
429
+ return
430
+ role = raw_width_bits(self.attrs[col])
431
+ healed_pair_end = -1
432
+ if role == int(WidthRole.WIDE):
433
+ self.chars[col] = " "
434
+ self.attrs[col] &= _WIDTH_CLEAR_MASK
435
+ healed_pair_end = col + 1
436
+ if col + 1 < cols:
437
+ self.chars[col + 1] = " "
438
+ self.attrs[col + 1] &= _WIDTH_CLEAR_MASK
439
+ healed_pair_end = col + 2
440
+ elif role == int(WidthRole.SPACER_TAIL):
441
+ self.chars[col] = " "
442
+ self.attrs[col] &= _WIDTH_CLEAR_MASK
443
+ healed_pair_end = col + 1
444
+ if col - 1 >= 0:
445
+ self.chars[col - 1] = " "
446
+ self.attrs[col - 1] &= _WIDTH_CLEAR_MASK
447
+ if healed_pair_end != -1:
448
+ if self.text_used == healed_pair_end:
449
+ pair_lo = max(0, healed_pair_end - 2)
450
+ self.text_used = pair_lo
451
+ if (
452
+ self.used == healed_pair_end
453
+ and self.attr_at(healed_pair_end - 1) == 0
454
+ and self.ext_at(healed_pair_end - 1) is None
455
+ ):
456
+ self.used = pair_lo
457
+ bump_row_gen(self)
458
+
459
+ def write_narrow(
460
+ self,
461
+ col: int,
462
+ ch: str,
463
+ pen_word: int,
464
+ cell_ext: _CellExt | None,
465
+ ) -> None:
466
+ """Write a 1-column glyph at *col*, healing any split wide cell."""
467
+ self._heal_wide_boundary(col)
468
+ self._set_raw(col, ch, pen_word, WidthRole.NARROW, cell_ext)
469
+ self.used = max(self.used, col + 1)
470
+ self.text_used = max(self.text_used, col + 1)
471
+ bump_row_gen(self)
472
+
473
+ def write_spacer_head(
474
+ self,
475
+ col: int,
476
+ bce_word: int,
477
+ bce_ext: _CellExt | None,
478
+ ) -> None:
479
+ """Write ``WidthRole.SPACER_HEAD`` padding at right margin before wide wrap."""
480
+ self._heal_wide_boundary(col)
481
+ self._set_raw(col, "", bce_word, WidthRole.SPACER_HEAD, bce_ext)
482
+ self.used = max(self.used, col + 1)
483
+ self.text_used = max(self.text_used, col + 1)
484
+ bump_row_gen(self)
485
+
486
+ def write_ascii_slice(
487
+ self,
488
+ col: int,
489
+ text: str,
490
+ pen_word: int,
491
+ cell_ext: _CellExt | None,
492
+ ) -> None:
493
+ """Fast-path bulk write of 1-column printable ASCII characters."""
494
+ n = len(text)
495
+ end = col + n
496
+ if self.has_wide and self.attrs is not None:
497
+ self._heal_wide_boundary(col)
498
+ if end - 1 > col:
499
+ self._heal_wide_boundary(end - 1)
500
+ for idx in range(col, end):
501
+ if (
502
+ raw_width_bits(self.attrs[idx]) == int(WidthRole.WIDE)
503
+ and idx + 1 >= end
504
+ and idx + 1 < len(self.chars)
505
+ ):
506
+ self.chars[idx + 1] = " "
507
+ self.attrs[idx + 1] &= _WIDTH_CLEAR_MASK
508
+
509
+ self.chars[col:end] = list(text)
510
+ word = pen_word | (_HAS_EXT_BIT if cell_ext is not None else 0)
511
+ if self.attrs is None:
512
+ if word != self.uniform_attr:
513
+ attrs = self._ensure_attrs()
514
+ attrs[col:end] = array.array("Q", [word]) * n
515
+ else:
516
+ self.attrs[col:end] = array.array("Q", [word]) * n
517
+
518
+ if cell_ext is not None:
519
+ if self.ext is None:
520
+ self.ext = {}
521
+ for idx in range(col, end):
522
+ self.ext[idx] = cell_ext
523
+ elif self.ext:
524
+ for idx in range(col, end):
525
+ self.ext.pop(idx, None)
526
+
527
+ self.used = max(self.used, end)
528
+ self.text_used = max(self.text_used, end)
529
+ bump_row_gen(self)
530
+
531
+ def write_wide(
532
+ self,
533
+ col: int,
534
+ ch: str,
535
+ pen_word: int,
536
+ cell_ext: _CellExt | None,
537
+ ) -> None:
538
+ """Write a 2-column glyph across ``col`` and ``col + 1``."""
539
+ self._heal_wide_boundary(col)
540
+ self._heal_wide_boundary(col + 1)
541
+ self._set_raw(col, ch, pen_word, WidthRole.WIDE, cell_ext)
542
+ self._set_raw(col + 1, "", pen_word, WidthRole.SPACER_TAIL, cell_ext)
543
+ self.used = max(self.used, col + 2)
544
+ self.text_used = max(self.text_used, col + 2)
545
+ bump_row_gen(self)
546
+
547
+ def append_grapheme(
548
+ self,
549
+ col: int,
550
+ ch: str,
551
+ *,
552
+ width_override: int,
553
+ bce_word: int = 0,
554
+ ) -> None:
555
+ """Append zero-width or cluster-extending *ch* onto cell *col*."""
556
+ cols = len(self.chars)
557
+ if col < 0 or col >= cols:
558
+ return
559
+ target = col
560
+ if (
561
+ self.has_wide
562
+ and self.attrs is not None
563
+ and raw_width_bits(self.attrs[col]) == int(WidthRole.SPACER_TAIL)
564
+ and col > 0
565
+ ):
566
+ target = col - 1
567
+ self.chars[target] = self.chars[target] + ch
568
+ cur_role = raw_width_bits(self.attrs[target]) if self.attrs is not None else 0
569
+ if (
570
+ width_override == 2
571
+ and cur_role == int(WidthRole.NARROW)
572
+ and target + 1 < cols
573
+ ):
574
+ base_pen = self.attr_at(target) & _PEN_BASE_MASK
575
+ base_ext = self.ext_at(target)
576
+ self._heal_wide_boundary(target + 1)
577
+ self._set_raw(
578
+ target, self.chars[target], base_pen, WidthRole.WIDE, base_ext
579
+ )
580
+ self._set_raw(target + 1, "", base_pen, WidthRole.SPACER_TAIL, base_ext)
581
+ self.used = max(self.used, target + 2)
582
+ self.text_used = max(self.text_used, target + 2)
583
+ elif (
584
+ width_override == 1
585
+ and cur_role == int(WidthRole.WIDE)
586
+ and target + 1 < cols
587
+ ):
588
+ attrs = self._ensure_attrs()
589
+ attrs[target] &= _WIDTH_CLEAR_MASK
590
+ self._set_raw(target + 1, " ", bce_word, WidthRole.NARROW, None)
591
+ if self.text_used == target + 2:
592
+ self.text_used = target + 1
593
+ if self.used == target + 2 and bce_word == 0:
594
+ self.used = target + 1
595
+ bump_row_gen(self)
596
+
597
+ def clear_range(
598
+ self,
599
+ start: int,
600
+ end: int,
601
+ bce_word: int,
602
+ bce_ext: _CellExt | None,
603
+ *,
604
+ selective: bool = False,
605
+ ) -> None:
606
+ """Erase cells in ``[start, end)`` using background color erase (*bce*)."""
607
+ cols = len(self.chars)
608
+ lo = max(0, start)
609
+ hi = min(cols, end)
610
+ if lo >= hi:
611
+ return
612
+
613
+ if selective and self.ext:
614
+ for c in range(lo, hi):
615
+ if self.is_protected(c):
616
+ continue
617
+ self._heal_wide_boundary(c)
618
+ self._set_raw(c, " ", bce_word, WidthRole.NARROW, bce_ext)
619
+ if bce_word != 0 or bce_ext is not None:
620
+ self.used = max(self.used, hi)
621
+ elif hi >= self.used:
622
+ while (
623
+ self.used > lo
624
+ and self.chars[self.used - 1] == " "
625
+ and self.attr_at(self.used - 1) == 0
626
+ and self.ext_at(self.used - 1) is None
627
+ ):
628
+ self.used -= 1
629
+ if hi >= self.text_used:
630
+ while self.text_used > lo and not self.is_protected(self.text_used - 1):
631
+ self.text_used -= 1
632
+ bump_row_gen(self)
633
+ return
634
+
635
+ if lo == 0 and hi == cols:
636
+ self.reset_blank(cols, bce_word, bce_ext)
637
+ return
638
+
639
+ if self.has_wide:
640
+ self._heal_wide_boundary(lo)
641
+ self._heal_wide_boundary(hi - 1)
642
+
643
+ n = hi - lo
644
+ self.chars[lo:hi] = [" "] * n
645
+ word = bce_word | (_HAS_EXT_BIT if bce_ext is not None else 0)
646
+ if self.attrs is None:
647
+ if word != self.uniform_attr:
648
+ attrs = self._ensure_attrs()
649
+ attrs[lo:hi] = array.array("Q", [word]) * n
650
+ else:
651
+ self.attrs[lo:hi] = array.array("Q", [word]) * n
652
+
653
+ if bce_ext is not None:
654
+ if self.ext is None:
655
+ self.ext = {}
656
+ for c in range(lo, hi):
657
+ self.ext[c] = bce_ext
658
+ self.used = max(self.used, hi)
659
+ else:
660
+ if self.ext:
661
+ for c in range(lo, hi):
662
+ self.ext.pop(c, None)
663
+ if bce_word != 0:
664
+ self.used = max(self.used, hi)
665
+ elif hi >= self.used:
666
+ # Clamp used to lo without erasing explicit spaces left of lo.
667
+ self.used = min(self.used, lo)
668
+ if hi >= self.text_used:
669
+ self.text_used = min(self.text_used, lo)
670
+ bump_row_gen(self)
671
+
672
+ def insert_blanks(
673
+ self,
674
+ col: int,
675
+ count: int,
676
+ *,
677
+ left: int,
678
+ right: int,
679
+ bce_word: int,
680
+ bce_ext: _CellExt | None = None,
681
+ ) -> None:
682
+ """Insert *count* blank cells at *col* within ``[left, right]`` (``ICH``)."""
683
+ if not (left <= col <= right) or count <= 0:
684
+ return
685
+ shift = min(count, right - col + 1)
686
+
687
+ # Splitting a SPACER_TAIL at col orphans its WIDE head at col - 1.
688
+ if (
689
+ self.has_wide
690
+ and self.attrs is not None
691
+ and raw_width_bits(self.attrs[col]) == int(WidthRole.SPACER_TAIL)
692
+ ):
693
+ if col > 0:
694
+ self.chars[col - 1] = " "
695
+ self.attrs[col - 1] &= _WIDTH_CLEAR_MASK
696
+ self.chars[col] = " "
697
+ self.attrs[col] &= _WIDTH_CLEAR_MASK
698
+
699
+ # Discarding a WIDE head at right orphans its SPACER_TAIL at right + 1.
700
+ if (
701
+ self.has_wide
702
+ and self.attrs is not None
703
+ and right + 1 < len(self.chars)
704
+ and raw_width_bits(self.attrs[right + 1]) == int(WidthRole.SPACER_TAIL)
705
+ ):
706
+ self.chars[right + 1] = " "
707
+ self.attrs[right + 1] &= _WIDTH_CLEAR_MASK
708
+
709
+ attrs = (
710
+ self._ensure_attrs()
711
+ if (
712
+ self.attrs is not None
713
+ or bce_word != self.uniform_attr
714
+ or bce_ext is not None
715
+ )
716
+ else None
717
+ )
718
+ for dst in range(right, col + shift - 1, -1):
719
+ src = dst - shift
720
+ self.chars[dst] = self.chars[src]
721
+ if attrs is not None:
722
+ attrs[dst] = attrs[src]
723
+ if self.ext is not None:
724
+ if src in self.ext:
725
+ self.ext[dst] = self.ext[src]
726
+ else:
727
+ self.ext.pop(dst, None)
728
+
729
+ # Clear right when shifting pushes a WIDE head onto right without its tail.
730
+ if (
731
+ self.has_wide
732
+ and attrs is not None
733
+ and raw_width_bits(attrs[right]) == int(WidthRole.WIDE)
734
+ ):
735
+ self.chars[right] = " "
736
+ attrs[right] &= _WIDTH_CLEAR_MASK
737
+
738
+ for c in range(col, col + shift):
739
+ self._set_raw(c, " ", bce_word, WidthRole.NARROW, bce_ext)
740
+ if self.used <= right + 1 and (
741
+ bce_word != 0 or bce_ext is not None or self.used > col
742
+ ):
743
+ self.used = min(right + 1, max(self.used + shift, col + shift))
744
+ if self.text_used <= right + 1 and self.text_used > col:
745
+ self.text_used = min(right + 1, self.text_used + shift)
746
+ bump_row_gen(self)
747
+
748
+ def delete_cells(
749
+ self,
750
+ col: int,
751
+ count: int,
752
+ *,
753
+ left: int,
754
+ right: int,
755
+ bce_word: int,
756
+ bce_ext: _CellExt | None = None,
757
+ ) -> None:
758
+ """Delete *count* cells at *col* within ``[left, right]`` (``DCH``)."""
759
+ if not (left <= col <= right) or count <= 0:
760
+ return
761
+ shift = min(count, right - col + 1)
762
+
763
+ if self.has_wide and self.attrs is not None:
764
+ # 1. Deleting SPACER_TAIL at col orphans WIDE head at col - 1.
765
+ if (
766
+ raw_width_bits(self.attrs[col]) == int(WidthRole.SPACER_TAIL)
767
+ and col > 0
768
+ ):
769
+ self.chars[col - 1] = " "
770
+ self.attrs[col - 1] &= _WIDTH_CLEAR_MASK
771
+ # First surviving cell at col + shift lost its WIDE head if SPACER_TAIL.
772
+ if col + shift <= right and raw_width_bits(self.attrs[col + shift]) == int(
773
+ WidthRole.SPACER_TAIL
774
+ ):
775
+ self.chars[col + shift] = " "
776
+ self.attrs[col + shift] &= _WIDTH_CLEAR_MASK
777
+ # Shifting WIDE head at right leftwards splits (right, right + 1).
778
+ if right + 1 < len(self.chars) and raw_width_bits(
779
+ self.attrs[right + 1]
780
+ ) == int(WidthRole.SPACER_TAIL):
781
+ self.chars[right] = " "
782
+ self.attrs[right] &= _WIDTH_CLEAR_MASK
783
+ self.chars[right + 1] = " "
784
+ self.attrs[right + 1] &= _WIDTH_CLEAR_MASK
785
+
786
+ attrs = (
787
+ self._ensure_attrs()
788
+ if (
789
+ self.attrs is not None
790
+ or bce_word != self.uniform_attr
791
+ or bce_ext is not None
792
+ )
793
+ else None
794
+ )
795
+ for dst in range(col, right - shift + 1):
796
+ src = dst + shift
797
+ self.chars[dst] = self.chars[src]
798
+ if attrs is not None:
799
+ attrs[dst] = attrs[src]
800
+ if self.ext is not None:
801
+ if src in self.ext:
802
+ self.ext[dst] = self.ext[src]
803
+ else:
804
+ self.ext.pop(dst, None)
805
+
806
+ for c in range(right - shift + 1, right + 1):
807
+ self._set_raw(c, " ", bce_word, WidthRole.NARROW, bce_ext)
808
+ if self.used <= right + 1:
809
+ if bce_word != 0 or bce_ext is not None:
810
+ self.used = max(self.used, right + 1)
811
+ elif self.used > col:
812
+ self.used = max(col, self.used - shift)
813
+ if self.text_used <= right + 1 and self.text_used > col:
814
+ self.text_used = max(col, self.text_used - shift)
815
+ bump_row_gen(self)
816
+
817
+ def resize(self, cols: int) -> None:
818
+ """Resize row in place to *cols* columns (non-reflow path)."""
819
+ cur = len(self.chars)
820
+ if cols == cur:
821
+ return
822
+ if cols < cur:
823
+ if (
824
+ cols > 0
825
+ and self.has_wide
826
+ and self.attrs is not None
827
+ and raw_width_bits(self.attrs[cols - 1]) == int(WidthRole.WIDE)
828
+ ):
829
+ self.chars[cols - 1] = " "
830
+ self.attrs[cols - 1] &= _WIDTH_CLEAR_MASK
831
+ del self.chars[cols:]
832
+ if self.attrs is not None:
833
+ del self.attrs[cols:]
834
+ self.used = min(self.used, cols)
835
+ self.text_used = min(self.text_used, cols)
836
+ if self.ext:
837
+ for k in [k for k in self.ext if k >= cols]:
838
+ del self.ext[k]
839
+ else:
840
+ pad = cols - cur
841
+ self.chars.extend([" "] * pad)
842
+ if self.attrs is not None:
843
+ self.attrs.extend([0] * pad)
844
+ elif self.uniform_attr != 0:
845
+ attrs = array.array("Q", [self.uniform_attr]) * cur
846
+ attrs.extend([0] * pad)
847
+ self.attrs = attrs
848
+ bump_row_gen(self)
849
+
850
+ def clone(self) -> _Row:
851
+ """Return an independent copy of this row."""
852
+ dup = _Row.__new__(_Row)
853
+ dup.chars = self.chars.copy()
854
+ dup.attrs = array.array("Q", self.attrs) if self.attrs is not None else None
855
+ dup.uniform_attr = self.uniform_attr
856
+ dup.has_wide = self.has_wide
857
+ dup.ext = self.ext.copy() if self.ext else None
858
+ dup.used = self.used
859
+ dup.text_used = self.text_used
860
+ dup._wrapped = self._wrapped
861
+ dup.content_gen = self.content_gen
862
+ dup._frozen = self._frozen
863
+ return dup
864
+
865
+ def freeze(self) -> FrozenRow:
866
+ """Seal this row into a compact run-length-encoded :class:`FrozenRow`."""
867
+ if self._frozen is not None:
868
+ return self._frozen
869
+ cols = len(self.chars)
870
+ t_used = self.text_used
871
+ text = "".join(self.chars[:t_used])
872
+ cells: tuple[str, ...] | None = None
873
+ if len(text) != t_used or "" in self.chars[:t_used]:
874
+ cells = tuple(self.chars[:t_used])
875
+
876
+ u = min(cols, max(self.used, t_used))
877
+ runs: tuple[tuple[int, int], ...]
878
+ if u == 0:
879
+ runs = ()
880
+ elif self.attrs is None:
881
+ runs = () if self.uniform_attr == 0 else ((u, self.uniform_attr),)
882
+ else:
883
+ run_list: list[tuple[int, int]] = []
884
+ cur_word = self.attrs[0]
885
+ for c in range(1, u):
886
+ w = self.attrs[c]
887
+ if w != cur_word:
888
+ run_list.append((c, cur_word))
889
+ cur_word = w
890
+ if cur_word != 0:
891
+ run_list.append((u, cur_word))
892
+ runs = tuple(run_list)
893
+
894
+ exts = tuple(sorted(self.ext.items())) if self.ext else ()
895
+ fr = FrozenRow(
896
+ text=text,
897
+ cols=cols,
898
+ runs=runs,
899
+ exts=exts,
900
+ cells=cells,
901
+ wrapped=self._wrapped,
902
+ )
903
+ self._frozen = fr
904
+ return fr
905
+
906
+ def rstrip_text(self) -> str:
907
+ """Return row text up to ``text_used`` written columns."""
908
+ return "".join(self.chars[: self.text_used])
909
+
910
+
911
+ @dataclass(frozen=True, slots=True)
912
+ class _FrozenHistory(collections.abc.Sequence[FrozenRow]):
913
+ """Immutable 256-row copy-on-write block snapshot of sealed scrollback."""
914
+
915
+ blocks: tuple[tuple[FrozenRow, ...], ...] = ()
916
+ tail: tuple[FrozenRow, ...] = ()
917
+ head_offset: int = 0
918
+ length: int = 0
919
+
920
+ @classmethod
921
+ def from_sequence(
922
+ cls,
923
+ rows: collections.abc.Sequence[FrozenRow],
924
+ ) -> _FrozenHistory:
925
+ """Pack an arbitrary :class:`FrozenRow` sequence into 256-row blocks."""
926
+ if isinstance(rows, _FrozenHistory):
927
+ return rows
928
+ n = len(rows)
929
+ if n == 0:
930
+ return _EMPTY_FROZEN_HISTORY
931
+ full_blocks = n >> _HISTORY_BLOCK_SHIFT
932
+ blocks = tuple(
933
+ tuple(rows[i << _HISTORY_BLOCK_SHIFT : (i + 1) << _HISTORY_BLOCK_SHIFT])
934
+ for i in range(full_blocks)
935
+ )
936
+ tail = tuple(rows[full_blocks << _HISTORY_BLOCK_SHIFT :])
937
+ return cls(blocks=blocks, tail=tail, head_offset=0, length=n)
938
+
939
+ def __len__(self) -> int:
940
+ return self.length
941
+
942
+ def at(self, index: int) -> FrozenRow:
943
+ """Return :class:`FrozenRow` at normalized ``0 <= index < length``."""
944
+ raw = self.head_offset + index
945
+ b_idx = raw >> _HISTORY_BLOCK_SHIFT
946
+ off = raw & _HISTORY_BLOCK_MASK
947
+ if b_idx < len(self.blocks):
948
+ return self.blocks[b_idx][off]
949
+ return self.tail[off]
950
+
951
+ @t.overload
952
+ def __getitem__(self, index: int) -> FrozenRow: ...
953
+
954
+ @t.overload
955
+ def __getitem__(self, index: slice) -> tuple[FrozenRow, ...]: ...
956
+
957
+ def __getitem__(
958
+ self,
959
+ index: int | slice,
960
+ ) -> FrozenRow | tuple[FrozenRow, ...]:
961
+ if isinstance(index, slice):
962
+ start, stop, step = index.indices(self.length)
963
+ return tuple(self.at(i) for i in range(start, stop, step))
964
+ if isinstance(index, bool) or not isinstance(index, int):
965
+ msg = f"history indices must be int or slice, got {type(index).__name__}"
966
+ raise TypeError(msg)
967
+ norm = index + self.length if index < 0 else index
968
+ if norm < 0 or norm >= self.length:
969
+ msg = f"history index {index} out of range for size {self.length}"
970
+ raise IndexError(msg)
971
+ return self.at(norm)
972
+
973
+ def __iter__(self) -> collections.abc.Iterator[FrozenRow]:
974
+ if self.length == 0:
975
+ return
976
+ if not self.blocks:
977
+ yield from self.tail[self.head_offset : self.head_offset + self.length]
978
+ return
979
+ yield from self.blocks[0][self.head_offset :]
980
+ for blk in self.blocks[1:]:
981
+ yield from blk
982
+ yield from self.tail
983
+
984
+
985
+ _EMPTY_FROZEN_HISTORY = _FrozenHistory()
986
+
987
+
988
+ class _HistoryBuffer:
989
+ """Bounded 256-row block scrollback buffer with ``O(1)`` CoW snapshots."""
990
+
991
+ __slots__ = ("_blocks", "_head_offset", "_len", "_maxlen", "_snapshot", "_tail")
992
+
993
+ def __init__(self, *, maxlen: int) -> None:
994
+ self._maxlen: int = max(0, maxlen)
995
+ self._blocks: list[tuple[FrozenRow, ...]] = []
996
+ self._tail: list[FrozenRow] = []
997
+ self._head_offset: int = 0
998
+ self._len: int = 0
999
+ self._snapshot: _FrozenHistory | None = _EMPTY_FROZEN_HISTORY
1000
+
1001
+ @property
1002
+ def maxlen(self) -> int:
1003
+ """Return scrollback line capacity (``0`` when disabled)."""
1004
+ return self._maxlen
1005
+
1006
+ def __len__(self) -> int:
1007
+ return self._len
1008
+
1009
+ def __bool__(self) -> bool:
1010
+ return self._len > 0
1011
+
1012
+ def __getitem__(self, index: int) -> FrozenRow:
1013
+ if isinstance(index, bool) or not isinstance(index, int):
1014
+ msg = f"history index must be int, got {type(index).__name__}"
1015
+ raise TypeError(msg)
1016
+ norm = index + self._len if index < 0 else index
1017
+ if norm < 0 or norm >= self._len:
1018
+ msg = f"history index {index} out of range for size {self._len}"
1019
+ raise IndexError(msg)
1020
+ raw = self._head_offset + norm
1021
+ b_idx = raw >> _HISTORY_BLOCK_SHIFT
1022
+ off = raw & _HISTORY_BLOCK_MASK
1023
+ if b_idx < len(self._blocks):
1024
+ return self._blocks[b_idx][off]
1025
+ return self._tail[off]
1026
+
1027
+ def __iter__(self) -> collections.abc.Iterator[FrozenRow]:
1028
+ return iter(self.freeze())
1029
+
1030
+ def clear(self) -> None:
1031
+ """Discard all stored scrollback blocks."""
1032
+ if self._len == 0:
1033
+ return
1034
+ self._blocks.clear()
1035
+ self._tail = []
1036
+ self._head_offset = 0
1037
+ self._len = 0
1038
+ self._snapshot = _EMPTY_FROZEN_HISTORY
1039
+
1040
+ def append(self, row: FrozenRow) -> bool:
1041
+ """Append *row*, returning ``True`` when the oldest row was evicted."""
1042
+ if self._maxlen <= 0:
1043
+ return False
1044
+ self._snapshot = None
1045
+ self._tail.append(row)
1046
+ if len(self._tail) == _HISTORY_BLOCK_SIZE:
1047
+ self._blocks.append(tuple(self._tail))
1048
+ self._tail = []
1049
+ if self._len == self._maxlen:
1050
+ self._head_offset += 1
1051
+ if self._head_offset == _HISTORY_BLOCK_SIZE:
1052
+ del self._blocks[0]
1053
+ self._head_offset = 0
1054
+ return True
1055
+ self._len += 1
1056
+ return False
1057
+
1058
+ def freeze(self) -> _FrozenHistory:
1059
+ """Capture an ``O(1)`` CoW :class:`_FrozenHistory` snapshot."""
1060
+ if self._snapshot is not None:
1061
+ return self._snapshot
1062
+ if self._len == 0:
1063
+ self._snapshot = _EMPTY_FROZEN_HISTORY
1064
+ return _EMPTY_FROZEN_HISTORY
1065
+ snap = _FrozenHistory(
1066
+ blocks=tuple(self._blocks),
1067
+ tail=tuple(self._tail),
1068
+ head_offset=self._head_offset,
1069
+ length=self._len,
1070
+ )
1071
+ self._snapshot = snap
1072
+ return snap
1073
+
1074
+
1075
+ type RowLike = _Row | FrozenRow