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/graphics.py ADDED
@@ -0,0 +1,1695 @@
1
+ """Zero-dependency sans-I/O ``SIXEL`` and Kitty ``APC G`` placement tracker."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import base64
6
+ import binascii
7
+ import collections
8
+ import collections.abc
9
+ import enum
10
+ import struct
11
+ import typing as t
12
+ import zlib
13
+ from dataclasses import dataclass
14
+
15
+ if t.TYPE_CHECKING:
16
+ from libvt.config import SixelErasePolicy
17
+
18
+ _PNG_SIGNATURE = b"\x89PNG\r\n\x1a\n"
19
+ _Z_BELOW_BG_THRESHOLD = -(1 << 30)
20
+ _MAX_UPLOAD_CHUNKS = 4_096
21
+ _MAX_UPLOAD_BYTES = 16_777_216
22
+ _MAX_ZLIB_INFLATE_BYTES = 16_777_216
23
+ _ZLIB_STEP_BYTES = 65_536
24
+ _MAX_MASK_CELLS = 16_384
25
+ _MAX_PARENT_DEPTH = 8
26
+
27
+
28
+ class GraphicsProtocol(enum.StrEnum):
29
+ """Terminal graphics protocol family."""
30
+
31
+ SIXEL = "sixel"
32
+ KITTY = "kitty"
33
+
34
+
35
+ class ZLayer(enum.StrEnum):
36
+ """Kitty graphics z-ordering plane relative to cell background and text."""
37
+
38
+ BELOW_BG = "below_bg"
39
+ BELOW_TEXT = "below_text"
40
+ ABOVE_TEXT = "above_text"
41
+
42
+
43
+ @dataclass(frozen=True, slots=True)
44
+ class ImageMeta:
45
+ """Stored sans-I/O image metadata without buffered pixel bitmaps.
46
+
47
+ Attributes
48
+ ----------
49
+ protocol : GraphicsProtocol
50
+ Originating graphics protocol (``SIXEL`` or ``KITTY``).
51
+ image_id : int
52
+ Protocol image identifier (auto-assigned positive integer for ``SIXEL``
53
+ or unnumbered Kitty uploads).
54
+ image_number : int
55
+ Optional Kitty ``I=`` non-unique image number (``0`` when unset).
56
+ width_px : int
57
+ Decoded or declared image width in pixels.
58
+ height_px : int
59
+ Decoded or declared image height in pixels.
60
+ format_code : int
61
+ Kitty ``f=`` pixel format (``8``, ``16``, ``24``, ``32``, or ``100``
62
+ PNG), or ``0`` for ``SIXEL``.
63
+ compressed : bool
64
+ ``True`` when transmitted with Kitty ``o=z`` zlib compression.
65
+ byte_len : int
66
+ Total encoded payload byte count observed across upload chunks.
67
+ """
68
+
69
+ protocol: GraphicsProtocol
70
+ image_id: int
71
+ image_number: int = 0
72
+ width_px: int = 0
73
+ height_px: int = 0
74
+ format_code: int = 32
75
+ compressed: bool = False
76
+ byte_len: int = 0
77
+
78
+
79
+ @dataclass(frozen=True, slots=True)
80
+ class ImagePlacement:
81
+ """Immutable snapshot of a ``SIXEL`` or Kitty image placement on a screen.
82
+
83
+ Attributes
84
+ ----------
85
+ protocol : GraphicsProtocol
86
+ Originating graphics protocol.
87
+ image_id : int
88
+ Referenced :attr:`ImageMeta.image_id`.
89
+ placement_id : int
90
+ Kitty ``p=`` placement identifier (``0`` when default/unnumbered).
91
+ abs_row : int
92
+ Monotonic absolute grid row anchor.
93
+ col : int
94
+ Zero-based starting column.
95
+ rows : int
96
+ Height in terminal cells.
97
+ cols : int
98
+ Width in terminal cells.
99
+ z_index : int
100
+ Signed 32-bit z-index (``0`` default).
101
+ virtual : bool
102
+ ``True`` for Kitty ``U=1`` Unicode-placeholder virtual placements.
103
+ parent_image_id : int
104
+ Parent image ID for Kitty ``P=`` relative placements (``0`` when none).
105
+ parent_placement_id : int
106
+ Parent placement ID for Kitty ``Q=`` relative placements.
107
+ source_x : int
108
+ Cropped source rectangle X origin in pixels.
109
+ source_y : int
110
+ Cropped source rectangle Y origin in pixels.
111
+ source_width : int
112
+ Cropped source rectangle width in pixels.
113
+ source_height : int
114
+ Cropped source rectangle height in pixels.
115
+ cell_offset_x : int
116
+ Sub-cell pixel X offset within the anchor cell.
117
+ cell_offset_y : int
118
+ Sub-cell pixel Y offset within the anchor cell.
119
+ visible_mask : int | None
120
+ Bitmask of ``rows * cols`` visible cells for ``SIXEL`` under
121
+ ``"cell_mask"`` erase policy (bit ``r * cols + c`` is ``1`` when
122
+ intact); ``None`` when all cells in ``(rows, cols)`` are intact.
123
+ """
124
+
125
+ protocol: GraphicsProtocol
126
+ image_id: int
127
+ placement_id: int
128
+ abs_row: int
129
+ col: int
130
+ rows: int
131
+ cols: int
132
+ z_index: int = 0
133
+ virtual: bool = False
134
+ parent_image_id: int = 0
135
+ parent_placement_id: int = 0
136
+ source_x: int = 0
137
+ source_y: int = 0
138
+ source_width: int = 0
139
+ source_height: int = 0
140
+ cell_offset_x: int = 0
141
+ cell_offset_y: int = 0
142
+ visible_mask: int | None = None
143
+
144
+ @property
145
+ def layer(self) -> ZLayer:
146
+ """Return rendering plane derived from :attr:`z_index`."""
147
+ if self.virtual:
148
+ return ZLayer.BELOW_TEXT
149
+ if self.z_index < _Z_BELOW_BG_THRESHOLD:
150
+ return ZLayer.BELOW_BG
151
+ if self.z_index < 0:
152
+ return ZLayer.BELOW_TEXT
153
+ return ZLayer.ABOVE_TEXT
154
+
155
+ def occupies_abs(self, abs_row: int, col: int) -> bool:
156
+ """Return ``True`` when absolute grid cell ``(abs_row, col)`` is covered.
157
+
158
+ Parameters
159
+ ----------
160
+ abs_row : int
161
+ Monotonic absolute row coordinate (for a viewport row ``0 <= r < rows``,
162
+ pass ``snap.scrolled_total + r``).
163
+ col : int
164
+ Zero-based column coordinate.
165
+
166
+ Returns
167
+ -------
168
+ bool
169
+ ``True`` when this non-virtual placement covers ``(abs_row, col)``
170
+ and its cell mask bit (if any) remains set; ``False`` for virtual
171
+ placements or uncovered cells.
172
+
173
+ Raises
174
+ ------
175
+ TypeError
176
+ When *abs_row* or *col* is not an :class:`int` (or is a :class:`bool`).
177
+ """
178
+ if isinstance(abs_row, bool) or not isinstance(abs_row, int):
179
+ msg = f"abs_row must be int, got {type(abs_row).__name__}"
180
+ raise TypeError(msg)
181
+ if isinstance(col, bool) or not isinstance(col, int):
182
+ msg = f"col must be int, got {type(col).__name__}"
183
+ raise TypeError(msg)
184
+ if self.virtual:
185
+ return False
186
+ if not (
187
+ self.abs_row <= abs_row < self.abs_row + self.rows
188
+ and self.col <= col < self.col + self.cols
189
+ ):
190
+ return False
191
+ if self.visible_mask is None:
192
+ return True
193
+ bit = (abs_row - self.abs_row) * self.cols + (col - self.col)
194
+ return bool((self.visible_mask >> bit) & 1)
195
+
196
+
197
+ def extract_png_dimensions(header_bytes: bytes) -> tuple[int, int] | None:
198
+ """Extract ``(width_px, height_px)`` from the first 24 bytes of a PNG stream.
199
+
200
+ Parameters
201
+ ----------
202
+ header_bytes : bytes
203
+ Leading uncompressed bytes of a PNG payload (at least 24 bytes).
204
+
205
+ Returns
206
+ -------
207
+ tuple[int, int] | None
208
+ ``(width_px, height_px)`` when the PNG signature and ``IHDR`` chunk
209
+ header are valid and positive, else ``None``.
210
+ """
211
+ if len(header_bytes) < 24 or header_bytes[:8] != _PNG_SIGNATURE:
212
+ return None
213
+ ihdr_len, chunk_type = struct.unpack(">I4s", header_bytes[8:16])
214
+ if chunk_type != b"IHDR" or ihdr_len < 13:
215
+ return None
216
+ width_px, height_px = struct.unpack(">II", header_bytes[16:24])
217
+ if width_px <= 0 or height_px <= 0:
218
+ return None
219
+ return width_px, height_px
220
+
221
+
222
+ def scan_sixel_geometry(
223
+ payload: bytes,
224
+ *,
225
+ max_dimension: int = 10_000,
226
+ ) -> tuple[int, int]:
227
+ """Compute ``(width_px, height_px)`` of a ``SIXEL`` payload in ``O(n)`` time.
228
+
229
+ Parameters
230
+ ----------
231
+ payload : bytes
232
+ Raw ``SIXEL`` data stream following ``DCS Ps... q``.
233
+ max_dimension : int
234
+ Upper bound applied to raster attributes and ``!Pn`` repeat counts.
235
+
236
+ Returns
237
+ -------
238
+ tuple[int, int]
239
+ Clamped ``(width_px, height_px)`` in pixels.
240
+ """
241
+ n = len(payload)
242
+ idx = 0
243
+ raster_w = 0
244
+ raster_h = 0
245
+ cur_x = 0
246
+ cur_y = 0
247
+ max_x = 0
248
+ max_y = 0
249
+
250
+ while idx < n:
251
+ b = payload[idx]
252
+ if 0x3F <= b <= 0x7E:
253
+ cur_x = min(max_dimension, cur_x + 1)
254
+ max_x = max(max_x, cur_x)
255
+ max_y = max(max_y, min(max_dimension, cur_y + 6))
256
+ idx += 1
257
+ elif b == 0x21: # '!' repeat introducer: !Pn<sixel>
258
+ idx += 1
259
+ rep = 0
260
+ has_digits = False
261
+ while idx < n and 0x30 <= payload[idx] <= 0x39:
262
+ has_digits = True
263
+ rep = min(max_dimension, rep * 10 + (payload[idx] - 0x30))
264
+ idx += 1
265
+ if idx < n and 0x3F <= payload[idx] <= 0x7E:
266
+ count = max(1, rep) if has_digits else 1
267
+ cur_x = min(max_dimension, cur_x + count)
268
+ max_x = max(max_x, cur_x)
269
+ max_y = max(max_y, min(max_dimension, cur_y + 6))
270
+ idx += 1
271
+ elif b == 0x22: # '"' raster attributes: "Pan;Pad;Ph;Pv
272
+ idx += 1
273
+ nums: list[int] = []
274
+ cur_num = 0
275
+ while idx < n and (0x30 <= payload[idx] <= 0x39 or payload[idx] == 0x3B):
276
+ if payload[idx] == 0x3B:
277
+ nums.append(cur_num)
278
+ cur_num = 0
279
+ else:
280
+ cur_num = min(max_dimension, cur_num * 10 + (payload[idx] - 0x30))
281
+ idx += 1
282
+ nums.append(cur_num)
283
+ if len(nums) >= 4:
284
+ raster_w = min(max_dimension, nums[2])
285
+ raster_h = min(max_dimension, nums[3])
286
+ elif b == 0x23: # '#' color introducer: #Pc or #Pc;Pu;Px;Py;Pz
287
+ idx += 1
288
+ while idx < n and (0x30 <= payload[idx] <= 0x39 or payload[idx] == 0x3B):
289
+ idx += 1
290
+ elif b == 0x24: # '$' graphics carriage return
291
+ cur_x = 0
292
+ idx += 1
293
+ elif b == 0x2D: # '-' graphics new line
294
+ cur_x = 0
295
+ cur_y = min(max_dimension, cur_y + 6)
296
+ idx += 1
297
+ else:
298
+ idx += 1
299
+
300
+ return min(max_dimension, max(raster_w, max_x)), min(
301
+ max_dimension, max(raster_h, max_y)
302
+ )
303
+
304
+
305
+ @dataclass(slots=True)
306
+ class _MutablePlacement:
307
+ protocol: GraphicsProtocol
308
+ image_id: int
309
+ placement_id: int
310
+ abs_row: int
311
+ col: int
312
+ rows: int
313
+ cols: int
314
+ z_index: int = 0
315
+ virtual: bool = False
316
+ parent_image_id: int = 0
317
+ parent_placement_id: int = 0
318
+ source_x: int = 0
319
+ source_y: int = 0
320
+ source_width: int = 0
321
+ source_height: int = 0
322
+ cell_offset_x: int = 0
323
+ cell_offset_y: int = 0
324
+ visible_mask: int | None = None
325
+
326
+ def freeze(self) -> ImagePlacement:
327
+ return ImagePlacement(
328
+ protocol=self.protocol,
329
+ image_id=self.image_id,
330
+ placement_id=self.placement_id,
331
+ abs_row=self.abs_row,
332
+ col=self.col,
333
+ rows=self.rows,
334
+ cols=self.cols,
335
+ z_index=self.z_index,
336
+ virtual=self.virtual,
337
+ parent_image_id=self.parent_image_id,
338
+ parent_placement_id=self.parent_placement_id,
339
+ source_x=self.source_x,
340
+ source_y=self.source_y,
341
+ source_width=self.source_width,
342
+ source_height=self.source_height,
343
+ cell_offset_x=self.cell_offset_x,
344
+ cell_offset_y=self.cell_offset_y,
345
+ visible_mask=self.visible_mask,
346
+ )
347
+
348
+
349
+ class _Decompressor(t.Protocol):
350
+ @property
351
+ def eof(self) -> bool: ...
352
+
353
+ @property
354
+ def unconsumed_tail(self) -> bytes: ...
355
+
356
+ def decompress(self, data: bytes, /, max_length: int = 0) -> bytes: ...
357
+
358
+ def flush(self, length: int = ..., /) -> bytes: ...
359
+
360
+
361
+ @dataclass(slots=True)
362
+ class _PendingKittyUpload:
363
+ control: dict[str, str]
364
+ b64_rem: bytes
365
+ header_buf: bytearray
366
+ decompressor: _Decompressor | None
367
+ inflate_cap: int
368
+ encoded_bytes: int
369
+ decoded_bytes: int
370
+ decompressed_bytes: int
371
+ chunks: int
372
+ failed_error: str | None = None
373
+
374
+
375
+ def _parse_int(control: dict[str, str], key: str, default: int = 0) -> int:
376
+ raw = control.get(key)
377
+ if raw is None or not raw:
378
+ return default
379
+ try:
380
+ return int(raw)
381
+ except ValueError:
382
+ return default
383
+
384
+
385
+ def _kitty_reply(
386
+ control: dict[str, str],
387
+ status: str,
388
+ *,
389
+ is_error: bool,
390
+ reply_image_id: int | None = None,
391
+ ) -> bytes | None:
392
+ quiet = _parse_int(control, "q", 0)
393
+ if quiet == 2 or (quiet == 1 and not is_error):
394
+ return None
395
+ client_id = _parse_int(control, "i", 0)
396
+ client_num = _parse_int(control, "I", 0)
397
+ if client_id <= 0 and client_num <= 0:
398
+ return None
399
+ img_id = reply_image_id if reply_image_id is not None else client_id
400
+ pid = _parse_int(control, "p", 0)
401
+ tokens: list[str] = []
402
+ if img_id > 0:
403
+ tokens.append(f"i={img_id}")
404
+ if client_num > 0:
405
+ tokens.append(f"I={client_num}")
406
+ if pid > 0:
407
+ tokens.append(f"p={pid}")
408
+ head = ",".join(tokens)
409
+ return f"\x1b_G{head};{status}\x1b\\".encode("ascii")
410
+
411
+
412
+ class GraphicsTracker:
413
+ """Per-screen sans-I/O ``SIXEL`` and Kitty ``APC G`` state machine.
414
+
415
+ Attributes
416
+ ----------
417
+ has_sixels : bool
418
+ ``True`` when at least one active or scrollback ``SIXEL`` placement is
419
+ present, gating cell-overwrite hooks in ``O(1)``.
420
+ revision : int
421
+ Monotonic counter incremented whenever stored placements change.
422
+ """
423
+
424
+ __slots__ = (
425
+ "_images",
426
+ "_max_dim",
427
+ "_max_images",
428
+ "_max_placements",
429
+ "_next_auto_id",
430
+ "_pending",
431
+ "_placements",
432
+ "has_sixels",
433
+ "revision",
434
+ )
435
+
436
+ def __init__(
437
+ self,
438
+ *,
439
+ max_images: int = 256,
440
+ max_placements: int = 1_024,
441
+ max_image_dimension: int = 10_000,
442
+ ) -> None:
443
+ self._max_images = max(1, max_images)
444
+ self._max_placements = max(1, max_placements)
445
+ self._max_dim = max(1, max_image_dimension)
446
+ self._images: collections.OrderedDict[int, ImageMeta] = (
447
+ collections.OrderedDict()
448
+ )
449
+ self._placements: list[_MutablePlacement] = []
450
+ self._pending: _PendingKittyUpload | None = None
451
+ self._next_auto_id: int = 0x8000_0001
452
+ self.has_sixels: bool = False
453
+ self.revision: int = 0
454
+
455
+ def _bump(self) -> None:
456
+ self.revision += 1
457
+ self.has_sixels = any(
458
+ p.protocol == GraphicsProtocol.SIXEL for p in self._placements
459
+ )
460
+
461
+ def clone(self) -> GraphicsTracker:
462
+ """Return an independent copy of this tracker."""
463
+ dup = GraphicsTracker(
464
+ max_images=self._max_images,
465
+ max_placements=self._max_placements,
466
+ max_image_dimension=self._max_dim,
467
+ )
468
+ dup._images = self._images.copy()
469
+ dup._placements = [
470
+ _MutablePlacement(
471
+ protocol=p.protocol,
472
+ image_id=p.image_id,
473
+ placement_id=p.placement_id,
474
+ abs_row=p.abs_row,
475
+ col=p.col,
476
+ rows=p.rows,
477
+ cols=p.cols,
478
+ z_index=p.z_index,
479
+ virtual=p.virtual,
480
+ parent_image_id=p.parent_image_id,
481
+ parent_placement_id=p.parent_placement_id,
482
+ source_x=p.source_x,
483
+ source_y=p.source_y,
484
+ source_width=p.source_width,
485
+ source_height=p.source_height,
486
+ cell_offset_x=p.cell_offset_x,
487
+ cell_offset_y=p.cell_offset_y,
488
+ visible_mask=p.visible_mask,
489
+ )
490
+ for p in self._placements
491
+ ]
492
+ dup._next_auto_id = self._next_auto_id
493
+ dup.has_sixels = self.has_sixels
494
+ dup.revision = self.revision
495
+ return dup
496
+
497
+ @property
498
+ def images(self) -> dict[int, ImageMeta]:
499
+ """Return shallow copy of stored :class:`ImageMeta` entries."""
500
+ return dict(self._images)
501
+
502
+ def snapshot_placements(self) -> tuple[ImagePlacement, ...]:
503
+ """Freeze stored placements into immutable :class:`ImagePlacement` records."""
504
+ if not self._placements:
505
+ return ()
506
+ return tuple(p.freeze() for p in self._placements)
507
+
508
+ def has_placement_on_row(self, row: int, scrolled_total: int) -> bool:
509
+ """Return ``True`` when any non-virtual placement covers viewport *row*."""
510
+ abs_y = scrolled_total + row
511
+ return any(
512
+ not p.virtual and p.abs_row <= abs_y < p.abs_row + p.rows
513
+ for p in self._placements
514
+ )
515
+
516
+ def _store_image(self, meta: ImageMeta) -> None:
517
+ had_placements = False
518
+ if meta.image_id in self._images:
519
+ self._images.move_to_end(meta.image_id)
520
+ before = len(self._placements)
521
+ self._placements = [
522
+ p for p in self._placements if p.image_id != meta.image_id
523
+ ]
524
+ had_placements = len(self._placements) != before
525
+ self._images[meta.image_id] = meta
526
+ evicted_any = False
527
+ while len(self._images) > self._max_images:
528
+ evicted_id, _ = self._images.popitem(last=False)
529
+ before = len(self._placements)
530
+ self._placements = [p for p in self._placements if p.image_id != evicted_id]
531
+ if len(self._placements) != before:
532
+ evicted_any = True
533
+ if had_placements or evicted_any:
534
+ self._prune_orphans()
535
+ self._bump()
536
+
537
+ def _append_placement(self, pl: _MutablePlacement) -> None:
538
+ if pl.protocol == GraphicsProtocol.KITTY and pl.placement_id > 0:
539
+ self._placements = [
540
+ p
541
+ for p in self._placements
542
+ if not (
543
+ p.protocol == GraphicsProtocol.KITTY
544
+ and p.image_id == pl.image_id
545
+ and p.placement_id == pl.placement_id
546
+ )
547
+ ]
548
+ self._placements.append(pl)
549
+ if len(self._placements) > self._max_placements:
550
+ del self._placements[: len(self._placements) - self._max_placements]
551
+ self._prune_orphans()
552
+ self._bump()
553
+
554
+ def reset(self) -> None:
555
+ """Clear all stored images, placements, and in-progress uploads."""
556
+ if self._images or self._placements or self._pending is not None:
557
+ self._images.clear()
558
+ self._placements.clear()
559
+ self._pending = None
560
+ self.has_sixels = False
561
+ self.revision += 1
562
+
563
+ def clear_active_screen(self, scrolled_total: int, screen_rows: int) -> None:
564
+ """Delete non-virtual placements intersecting the active viewport."""
565
+ if not self._placements:
566
+ return
567
+ top_abs = scrolled_total
568
+ bot_abs = scrolled_total + screen_rows
569
+ kept = [
570
+ p
571
+ for p in self._placements
572
+ if p.virtual or p.abs_row + p.rows <= top_abs or p.abs_row >= bot_abs
573
+ ]
574
+ if len(kept) != len(self._placements):
575
+ self._placements = kept
576
+ self._prune_orphans()
577
+ self._bump()
578
+
579
+ def clear_history(self, scrolled_total: int) -> None:
580
+ """Delete placements located completely inside scrollback (``ED 3``)."""
581
+ if not self._placements:
582
+ return
583
+ kept = [
584
+ p
585
+ for p in self._placements
586
+ if p.virtual or p.abs_row + p.rows > scrolled_total
587
+ ]
588
+ if len(kept) != len(self._placements):
589
+ self._placements = kept
590
+ self._prune_orphans()
591
+ self._bump()
592
+
593
+ def reap_evicted_history(self, min_retained_abs_row: int) -> None:
594
+ """Reap non-virtual placements scrolled past *min_retained_abs_row*."""
595
+ if not self._placements:
596
+ return
597
+ kept = [
598
+ p
599
+ for p in self._placements
600
+ if p.virtual or p.abs_row + p.rows > min_retained_abs_row
601
+ ]
602
+ if len(kept) != len(self._placements):
603
+ self._placements = kept
604
+ self._prune_orphans()
605
+ self._bump()
606
+
607
+ def on_non_reflow_resize(
608
+ self,
609
+ *,
610
+ top_drop_without_history: int,
611
+ new_rows: int,
612
+ new_cols: int,
613
+ scrolled_total: int,
614
+ ) -> None:
615
+ """Adjust placements when a non-reflow ``resize()`` drops or clips rows."""
616
+ if not self._placements:
617
+ return
618
+ changed = False
619
+ kept: list[_MutablePlacement] = []
620
+ max_abs = scrolled_total + new_rows
621
+ for p in self._placements:
622
+ if p.virtual:
623
+ kept.append(p)
624
+ continue
625
+ if top_drop_without_history > 0:
626
+ new_abs = p.abs_row - top_drop_without_history
627
+ if new_abs < scrolled_total:
628
+ clip_top = scrolled_total - new_abs
629
+ if clip_top >= p.rows:
630
+ changed = True
631
+ continue
632
+ keep_rows = p.rows - clip_top
633
+ if p.source_height > 0:
634
+ crop_px = (p.source_height * clip_top) // p.rows
635
+ p.source_y += crop_px
636
+ p.source_height = max(1, p.source_height - crop_px)
637
+ if (
638
+ p.visible_mask is not None
639
+ and keep_rows * p.cols <= _MAX_MASK_CELLS
640
+ ):
641
+ shifted = p.visible_mask >> (clip_top * p.cols)
642
+ p.visible_mask = shifted & ((1 << (keep_rows * p.cols)) - 1)
643
+ if p.visible_mask == 0:
644
+ changed = True
645
+ continue
646
+ p.rows = keep_rows
647
+ p.abs_row = scrolled_total
648
+ else:
649
+ p.abs_row = new_abs
650
+ changed = True
651
+ if p.abs_row + p.rows <= scrolled_total or p.abs_row >= max_abs:
652
+ changed = True
653
+ continue
654
+ if p.col >= new_cols:
655
+ changed = True
656
+ continue
657
+ kept.append(p)
658
+ if changed:
659
+ self._placements = kept
660
+ self._prune_orphans()
661
+ self._bump()
662
+
663
+ def erase_sixel_rect(
664
+ self,
665
+ *,
666
+ row: int,
667
+ col: int,
668
+ rows: int,
669
+ cols: int,
670
+ scrolled_total: int,
671
+ policy: SixelErasePolicy,
672
+ ) -> None:
673
+ """Clip or remove ``SIXEL`` placements intersected by a cell edit/erase."""
674
+ if not self.has_sixels or rows <= 0 or cols <= 0:
675
+ return
676
+ r0 = scrolled_total + row
677
+ r1 = r0 + rows
678
+ c0 = col
679
+ c1 = col + cols
680
+ changed = False
681
+ kept: list[_MutablePlacement] = []
682
+ for p in self._placements:
683
+ if p.protocol != GraphicsProtocol.SIXEL:
684
+ kept.append(p)
685
+ continue
686
+ pr0, pr1 = p.abs_row, p.abs_row + p.rows
687
+ pc0, pc1 = p.col, p.col + p.cols
688
+ if r1 <= pr0 or r0 >= pr1 or c1 <= pc0 or c0 >= pc1:
689
+ kept.append(p)
690
+ continue
691
+ if policy == "whole_image" or p.rows * p.cols > _MAX_MASK_CELLS:
692
+ changed = True
693
+ continue
694
+ prev_mask = p.visible_mask
695
+ if prev_mask is None:
696
+ prev_mask = (1 << (p.rows * p.cols)) - 1
697
+ mask = prev_mask
698
+ ir0 = max(r0, pr0) - pr0
699
+ ir1 = min(r1, pr1) - pr0
700
+ ic0 = max(c0, pc0) - pc0
701
+ ic1 = min(c1, pc1) - pc0
702
+ if ic0 == 0 and ic1 == p.cols:
703
+ span = (ir1 - ir0) * p.cols
704
+ mask &= ~(((1 << span) - 1) << (ir0 * p.cols))
705
+ else:
706
+ row_clear = ((1 << (ic1 - ic0)) - 1) << ic0
707
+ for rr in range(ir0, ir1):
708
+ mask &= ~(row_clear << (rr * p.cols))
709
+ if mask == 0:
710
+ changed = True
711
+ continue
712
+ if mask != prev_mask:
713
+ p.visible_mask = mask
714
+ changed = True
715
+ kept.append(p)
716
+ if changed:
717
+ self._placements = kept
718
+ self._bump()
719
+
720
+ def on_region_scroll(
721
+ self,
722
+ *,
723
+ top: int,
724
+ bottom: int,
725
+ left: int,
726
+ right: int,
727
+ delta_rows: int,
728
+ is_scroll: bool,
729
+ scrolled_total: int,
730
+ cell_height_px: int,
731
+ history_advanced: int = 0,
732
+ ) -> None:
733
+ """Adjust placements for bounded margin scroll or ``IL``/``DL``."""
734
+ if not self._placements or delta_rows == 0:
735
+ return
736
+ abs_top = scrolled_total + top
737
+ abs_bot = scrolled_total + bottom
738
+ changed = False
739
+ kept: list[_MutablePlacement] = []
740
+
741
+ for p in self._placements:
742
+ if p.virtual:
743
+ kept.append(p)
744
+ continue
745
+ p_top = p.abs_row
746
+ p_bot = p.abs_row + p.rows - 1
747
+ p_left = p.col
748
+ p_right = p.col + p.cols - 1
749
+
750
+ inside = (
751
+ p_top >= abs_top
752
+ and p_bot <= abs_bot
753
+ and p_left >= left
754
+ and p_right <= right
755
+ )
756
+
757
+ if p.protocol == GraphicsProtocol.KITTY or p.parent_image_id > 0:
758
+ if not is_scroll or not inside:
759
+ if history_advanced > 0 and p_top >= scrolled_total:
760
+ p.abs_row += history_advanced
761
+ changed = True
762
+ kept.append(p)
763
+ continue
764
+ new_top = p_top + delta_rows + history_advanced
765
+ new_bot = p_bot + delta_rows + history_advanced
766
+ eff_top = abs_top + history_advanced
767
+ eff_bot = abs_bot + history_advanced
768
+ clip_top = max(0, eff_top - new_top)
769
+ clip_bot = max(0, new_bot - eff_bot)
770
+ if clip_top + clip_bot >= p.rows:
771
+ changed = True
772
+ continue
773
+ if clip_top > 0:
774
+ crop_px = (
775
+ (p.source_height * clip_top) // p.rows
776
+ if p.rows > 0
777
+ else cell_height_px * clip_top
778
+ )
779
+ p.source_y += crop_px
780
+ p.source_height = max(0, p.source_height - crop_px)
781
+ p.rows -= clip_top
782
+ new_top = eff_top
783
+ if p.source_height <= 0 or p.rows <= 0:
784
+ changed = True
785
+ continue
786
+ if clip_bot > 0:
787
+ crop_px = (
788
+ (p.source_height * clip_bot) // p.rows
789
+ if p.rows > 0
790
+ else cell_height_px * clip_bot
791
+ )
792
+ p.source_height = max(0, p.source_height - crop_px)
793
+ p.rows -= clip_bot
794
+ if p.source_height <= 0 or p.rows <= 0:
795
+ changed = True
796
+ continue
797
+ p.abs_row = new_top
798
+ changed = True
799
+ kept.append(p)
800
+ else:
801
+ if (
802
+ p_bot < abs_top
803
+ or p_top > abs_bot
804
+ or p_right < left
805
+ or p_left > right
806
+ ):
807
+ if history_advanced > 0 and p_top > abs_bot:
808
+ p.abs_row += history_advanced
809
+ changed = True
810
+ kept.append(p)
811
+ continue
812
+ if not inside:
813
+ if history_advanced > 0 and p_top >= scrolled_total:
814
+ p.abs_row += history_advanced
815
+ changed = True
816
+ if p.rows * p.cols <= _MAX_MASK_CELLS:
817
+ prev_mask = (
818
+ (1 << (p.rows * p.cols)) - 1
819
+ if p.visible_mask is None
820
+ else p.visible_mask
821
+ )
822
+ ir0 = max(p_top, abs_top + history_advanced) - p.abs_row
823
+ ir1 = min(p_bot, abs_bot + history_advanced) - p.abs_row + 1
824
+ ic0 = max(p_left, left) - p_left
825
+ ic1 = min(p_right, right) - p_left + 1
826
+ if ir0 < ir1 and ic0 < ic1:
827
+ row_clear = ((1 << (ic1 - ic0)) - 1) << ic0
828
+ mask = prev_mask
829
+ for rr in range(ir0, ir1):
830
+ mask &= ~(row_clear << (rr * p.cols))
831
+ if mask == 0:
832
+ changed = True
833
+ continue
834
+ if mask != prev_mask:
835
+ p.visible_mask = mask
836
+ changed = True
837
+ kept.append(p)
838
+ continue
839
+
840
+ eff_top = abs_top + history_advanced
841
+ eff_bot = abs_bot + history_advanced
842
+ new_top = p_top + delta_rows + history_advanced
843
+ new_bot = p_bot + delta_rows + history_advanced
844
+ clip_top = max(0, eff_top - new_top)
845
+ clip_bot = max(0, new_bot - eff_bot)
846
+ if clip_top + clip_bot >= p.rows:
847
+ changed = True
848
+ continue
849
+ keep_rows = p.rows - clip_top - clip_bot
850
+ if (
851
+ p.visible_mask is not None
852
+ and (clip_top > 0 or clip_bot > 0)
853
+ and keep_rows * p.cols <= _MAX_MASK_CELLS
854
+ ):
855
+ shifted = p.visible_mask >> (clip_top * p.cols)
856
+ p.visible_mask = shifted & ((1 << (keep_rows * p.cols)) - 1)
857
+ if p.visible_mask == 0:
858
+ changed = True
859
+ continue
860
+ p.rows = keep_rows
861
+ p.abs_row = max(eff_top, new_top)
862
+ changed = True
863
+ kept.append(p)
864
+
865
+ if changed:
866
+ self._placements = kept
867
+ self._prune_orphans()
868
+ self._bump()
869
+
870
+ def prepare_sixel(
871
+ self,
872
+ payload: bytes,
873
+ *,
874
+ col: int,
875
+ screen_cols: int,
876
+ cell_width_px: int,
877
+ cell_height_px: int,
878
+ ) -> tuple[int, int, int, int] | None:
879
+ """Scan ``SIXEL`` geometry into ``(width_px, height_px, rows, cols)``."""
880
+ w_px, h_px = scan_sixel_geometry(payload, max_dimension=self._max_dim)
881
+ if w_px <= 0 or h_px <= 0:
882
+ return None
883
+ cw = max(1, cell_width_px)
884
+ ch = max(1, cell_height_px)
885
+ cols = min(max(1, screen_cols - col), max(1, (w_px + cw - 1) // cw))
886
+ rows = max(1, (h_px + ch - 1) // ch)
887
+ return w_px, h_px, rows, cols
888
+
889
+ def commit_sixel(
890
+ self,
891
+ *,
892
+ payload_len: int,
893
+ width_px: int,
894
+ height_px: int,
895
+ row: int,
896
+ col: int,
897
+ rows: int,
898
+ cols: int,
899
+ scrolled_total: int,
900
+ min_abs: int = 0,
901
+ ) -> None:
902
+ """Record a scanned ``SIXEL`` image and placement at post-scroll *row*."""
903
+ abs_r = scrolled_total + row
904
+ eff_rows = rows
905
+ eff_h_px = height_px
906
+ eff_src_y = 0
907
+ if abs_r < min_abs:
908
+ clip = min_abs - abs_r
909
+ if clip >= eff_rows:
910
+ return
911
+ if eff_h_px > 0 and eff_rows > 0:
912
+ crop_px = (eff_h_px * clip) // eff_rows
913
+ eff_src_y = crop_px
914
+ eff_h_px = max(1, eff_h_px - crop_px)
915
+ eff_rows -= clip
916
+ abs_r = min_abs
917
+ img_id = self._next_auto_id
918
+ self._next_auto_id += 1
919
+ meta = ImageMeta(
920
+ protocol=GraphicsProtocol.SIXEL,
921
+ image_id=img_id,
922
+ width_px=width_px,
923
+ height_px=height_px,
924
+ format_code=0,
925
+ byte_len=payload_len,
926
+ )
927
+ self._store_image(meta)
928
+ self._append_placement(
929
+ _MutablePlacement(
930
+ protocol=GraphicsProtocol.SIXEL,
931
+ image_id=img_id,
932
+ placement_id=0,
933
+ abs_row=max(0, abs_r),
934
+ col=col,
935
+ rows=eff_rows,
936
+ cols=cols,
937
+ source_y=eff_src_y,
938
+ source_width=width_px,
939
+ source_height=eff_h_px,
940
+ ),
941
+ )
942
+
943
+ def _drain_decompressor(self, up: _PendingKittyUpload, data: bytes) -> None:
944
+ dec = up.decompressor
945
+ if dec is None:
946
+ need = 24 - len(up.header_buf)
947
+ if need > 0:
948
+ up.header_buf.extend(data[:need])
949
+ return
950
+ buf = data
951
+ while buf and up.decompressed_bytes < up.inflate_cap:
952
+ step = min(_ZLIB_STEP_BYTES, up.inflate_cap - up.decompressed_bytes)
953
+ try:
954
+ out = dec.decompress(buf, step)
955
+ except zlib.error:
956
+ up.failed_error = "EINVAL:invalid zlib stream"
957
+ return
958
+ if not out and not dec.eof:
959
+ break
960
+ need = 24 - len(up.header_buf)
961
+ if need > 0:
962
+ up.header_buf.extend(out[:need])
963
+ up.decompressed_bytes += len(out)
964
+ buf = dec.unconsumed_tail
965
+ if dec.eof:
966
+ break
967
+
968
+ def _feed_upload_chunk(self, up: _PendingKittyUpload, payload: bytes) -> None:
969
+ if up.failed_error is not None:
970
+ return
971
+ if up.encoded_bytes + len(payload) > _MAX_UPLOAD_BYTES:
972
+ up.failed_error = "ENOMEM:upload exceeds byte limit"
973
+ return
974
+ cleaned = b"".join(payload.split())
975
+ if not cleaned:
976
+ return
977
+ up.encoded_bytes += len(cleaned)
978
+ combined = up.b64_rem + cleaned
979
+ rem_len = len(combined) % 4
980
+ if rem_len:
981
+ decode_part = combined[:-rem_len]
982
+ up.b64_rem = combined[-rem_len:]
983
+ else:
984
+ decode_part = combined
985
+ up.b64_rem = b""
986
+ if not decode_part:
987
+ return
988
+ try:
989
+ raw = base64.b64decode(decode_part, validate=True)
990
+ except binascii.Error:
991
+ up.failed_error = "EINVAL:invalid base64 payload"
992
+ return
993
+ up.decoded_bytes += len(raw)
994
+ self._drain_decompressor(up, raw)
995
+
996
+ def _finalize_upload(self, up: _PendingKittyUpload) -> None:
997
+ if up.failed_error is not None:
998
+ return
999
+ if up.b64_rem:
1000
+ padded = up.b64_rem + b"=" * ((4 - len(up.b64_rem)) % 4)
1001
+ try:
1002
+ raw = base64.b64decode(padded, validate=True)
1003
+ except binascii.Error:
1004
+ up.failed_error = "EINVAL:invalid base64 tail"
1005
+ return
1006
+ up.decoded_bytes += len(raw)
1007
+ self._drain_decompressor(up, raw)
1008
+ if up.failed_error is not None:
1009
+ return
1010
+ if up.decompressor is not None and up.decompressed_bytes < up.inflate_cap:
1011
+ try:
1012
+ tail = up.decompressor.flush(_ZLIB_STEP_BYTES)
1013
+ except zlib.error:
1014
+ up.failed_error = "EINVAL:invalid zlib stream"
1015
+ return
1016
+ need = 24 - len(up.header_buf)
1017
+ if need > 0:
1018
+ up.header_buf.extend(tail[:need])
1019
+ up.decompressed_bytes += len(tail)
1020
+ if not up.decompressor.eof and up.decompressed_bytes < up.inflate_cap:
1021
+ up.failed_error = "EINVAL:truncated zlib stream"
1022
+
1023
+ def handle_kitty(
1024
+ self,
1025
+ control: dict[str, str],
1026
+ payload: bytes,
1027
+ *,
1028
+ cursor_row: int,
1029
+ cursor_col: int,
1030
+ screen_rows: int,
1031
+ screen_cols: int,
1032
+ scrolled_total_getter: collections.abc.Callable[[], int] | None = None,
1033
+ scrolled_total: int = 0,
1034
+ cell_width_px: int = 8,
1035
+ cell_height_px: int = 16,
1036
+ min_row: int = 0,
1037
+ advance_cursor: collections.abc.Callable[[int, int], int] | None = None,
1038
+ ) -> bytes | None:
1039
+ """Process one Kitty ``APC G`` packet and return optional reply bytes.
1040
+
1041
+ Parameters
1042
+ ----------
1043
+ control : dict[str, str]
1044
+ Parsed ``key=value`` control header pairs.
1045
+ payload : bytes
1046
+ Base64 payload segment following ``;``.
1047
+ cursor_row : int
1048
+ Zero-based cursor row at packet arrival.
1049
+ cursor_col : int
1050
+ Zero-based cursor column at packet arrival.
1051
+ screen_rows : int
1052
+ Active screen height in rows.
1053
+ screen_cols : int
1054
+ Active screen width in columns.
1055
+ scrolled_total_getter : collections.abc.Callable[[], int] | None
1056
+ Optional callback returning live ``scrolled_total`` after
1057
+ *advance_cursor* runs.
1058
+ scrolled_total : int
1059
+ Fallback ``scrolled_total`` when *scrolled_total_getter* is ``None``.
1060
+ cell_width_px : int
1061
+ Nominal cell width in pixels.
1062
+ cell_height_px : int
1063
+ Nominal cell height in pixels.
1064
+ min_row : int
1065
+ Minimum viewport row ceiling when cursor scrolling does not advance
1066
+ scrollback (``0`` default, or active ``DECSTBM`` top margin).
1067
+ advance_cursor : collections.abc.Callable[[int, int], int] | None
1068
+ Callback invoked with ``(rows, cols)`` prior to committing a
1069
+ cursor-moving ``C=0`` placement, returning the post-scroll anchor
1070
+ row.
1071
+
1072
+ Returns
1073
+ -------
1074
+ bytes | None
1075
+ Sans-I/O ``APC G`` response packet, or ``None`` when silent.
1076
+ """
1077
+ explicit_action = control.get("a")
1078
+ more = _parse_int(control, "m", 0) == 1
1079
+ cur_scrolled = (
1080
+ scrolled_total_getter()
1081
+ if scrolled_total_getter is not None
1082
+ else scrolled_total
1083
+ )
1084
+
1085
+ if _parse_int(control, "i", 0) > 0 and _parse_int(control, "I", 0) > 0:
1086
+ self._pending = None
1087
+ return _kitty_reply(
1088
+ control, "EINVAL:cannot specify both i and I", is_error=True
1089
+ )
1090
+
1091
+ if explicit_action == "d":
1092
+ self._pending = None
1093
+ self._handle_kitty_delete(
1094
+ control,
1095
+ cursor_row=cursor_row,
1096
+ cursor_col=cursor_col,
1097
+ screen_rows=screen_rows,
1098
+ scrolled_total=cur_scrolled,
1099
+ )
1100
+ return None
1101
+
1102
+ if self._pending is not None:
1103
+ up = self._pending
1104
+ in_id = _parse_int(control, "i", 0)
1105
+ up_id = _parse_int(up.control, "i", 0)
1106
+ stale = (
1107
+ explicit_action in ("q", "p")
1108
+ or ("t" in control and control.get("t", "d") != "d")
1109
+ or (in_id > 0 and up_id > 0 and in_id != up_id)
1110
+ )
1111
+ if stale:
1112
+ self._pending = None
1113
+ elif explicit_action in (None, "t", "T"):
1114
+ if _parse_int(control, "q", 0) >= 1:
1115
+ up.control["q"] = control["q"]
1116
+ for k, v in control.items():
1117
+ if k not in ("m", "q"):
1118
+ up.control.setdefault(k, v)
1119
+ up.chunks += 1
1120
+ if up.chunks > _MAX_UPLOAD_CHUNKS:
1121
+ self._pending = None
1122
+ return _kitty_reply(
1123
+ up.control, "ENOMEM:too many chunks", is_error=True
1124
+ )
1125
+ self._feed_upload_chunk(up, payload)
1126
+ if more:
1127
+ return None
1128
+ self._pending = None
1129
+ self._finalize_upload(up)
1130
+ return self._complete_kitty_upload(
1131
+ up,
1132
+ cursor_row=cursor_row,
1133
+ cursor_col=cursor_col,
1134
+ screen_cols=screen_cols,
1135
+ scrolled_total_getter=scrolled_total_getter,
1136
+ scrolled_total=cur_scrolled,
1137
+ cell_width_px=cell_width_px,
1138
+ cell_height_px=cell_height_px,
1139
+ min_row=min_row,
1140
+ advance_cursor=advance_cursor,
1141
+ )
1142
+
1143
+ action = explicit_action or "t"
1144
+ if action in ("t", "T", "q"):
1145
+ if action == "q" and _parse_int(control, "i", 0) <= 0:
1146
+ if _parse_int(control, "I", 0) > 0:
1147
+ return _kitty_reply(
1148
+ control, "EINVAL:image ID required for query", is_error=True
1149
+ )
1150
+ return None
1151
+ medium = control.get("t", "d")
1152
+ if medium != "d":
1153
+ self._pending = None
1154
+ return _kitty_reply(
1155
+ control,
1156
+ f"EINVAL:unsupported transmission medium {medium!r}",
1157
+ is_error=True,
1158
+ )
1159
+ comp = control.get("o", "")
1160
+ if comp not in ("", "z"):
1161
+ return _kitty_reply(
1162
+ control,
1163
+ f"EINVAL:unsupported compression {comp!r}",
1164
+ is_error=True,
1165
+ )
1166
+ fmt = _parse_int(control, "f", 32)
1167
+ if fmt == 100:
1168
+ inflate_cap = _MAX_ZLIB_INFLATE_BYTES
1169
+ else:
1170
+ w_decl = min(self._max_dim + 1, max(0, _parse_int(control, "s", 0)))
1171
+ h_decl = min(self._max_dim + 1, max(0, _parse_int(control, "v", 0)))
1172
+ bpp = max(1, fmt // 8)
1173
+ inflate_cap = min(
1174
+ _MAX_ZLIB_INFLATE_BYTES, max(24, w_decl * h_decl * bpp)
1175
+ )
1176
+ up = _PendingKittyUpload(
1177
+ control=dict(control),
1178
+ b64_rem=b"",
1179
+ header_buf=bytearray(),
1180
+ decompressor=zlib.decompressobj() if comp == "z" else None,
1181
+ inflate_cap=inflate_cap,
1182
+ encoded_bytes=0,
1183
+ decoded_bytes=0,
1184
+ decompressed_bytes=0,
1185
+ chunks=1,
1186
+ )
1187
+ self._feed_upload_chunk(up, payload)
1188
+ if more:
1189
+ self._pending = up
1190
+ return None
1191
+ self._finalize_upload(up)
1192
+ return self._complete_kitty_upload(
1193
+ up,
1194
+ cursor_row=cursor_row,
1195
+ cursor_col=cursor_col,
1196
+ screen_cols=screen_cols,
1197
+ scrolled_total_getter=scrolled_total_getter,
1198
+ scrolled_total=cur_scrolled,
1199
+ cell_width_px=cell_width_px,
1200
+ cell_height_px=cell_height_px,
1201
+ min_row=min_row,
1202
+ advance_cursor=advance_cursor,
1203
+ )
1204
+
1205
+ if action == "p":
1206
+ return self._place_kitty_image(
1207
+ control,
1208
+ cursor_row=cursor_row,
1209
+ cursor_col=cursor_col,
1210
+ screen_cols=screen_cols,
1211
+ scrolled_total_getter=scrolled_total_getter,
1212
+ scrolled_total=cur_scrolled,
1213
+ cell_width_px=cell_width_px,
1214
+ cell_height_px=cell_height_px,
1215
+ min_row=min_row,
1216
+ advance_cursor=advance_cursor,
1217
+ )
1218
+
1219
+ return None
1220
+
1221
+ def _complete_kitty_upload(
1222
+ self,
1223
+ up: _PendingKittyUpload,
1224
+ *,
1225
+ cursor_row: int,
1226
+ cursor_col: int,
1227
+ screen_cols: int,
1228
+ scrolled_total_getter: collections.abc.Callable[[], int] | None,
1229
+ scrolled_total: int,
1230
+ cell_width_px: int,
1231
+ cell_height_px: int,
1232
+ min_row: int = 0,
1233
+ advance_cursor: collections.abc.Callable[[int, int], int] | None,
1234
+ ) -> bytes | None:
1235
+ ctrl = up.control
1236
+ if up.failed_error is not None:
1237
+ return _kitty_reply(ctrl, up.failed_error, is_error=True)
1238
+
1239
+ fmt = _parse_int(ctrl, "f", 32)
1240
+ if fmt == 100:
1241
+ dims = extract_png_dimensions(bytes(up.header_buf))
1242
+ if dims is None:
1243
+ return _kitty_reply(ctrl, "EINVAL:invalid PNG header", is_error=True)
1244
+ w_px, h_px = dims
1245
+ elif fmt in (8, 16, 24, 32):
1246
+ w_px = _parse_int(ctrl, "s", 0)
1247
+ h_px = _parse_int(ctrl, "v", 0)
1248
+ if w_px <= 0 or h_px <= 0:
1249
+ return _kitty_reply(
1250
+ ctrl, "EINVAL:missing raw s/v dimensions", is_error=True
1251
+ )
1252
+ if w_px > self._max_dim or h_px > self._max_dim:
1253
+ return _kitty_reply(
1254
+ ctrl, "EINVAL:image dimensions exceed limit", is_error=True
1255
+ )
1256
+ expected = w_px * h_px * (fmt // 8)
1257
+ if ctrl.get("o") == "z":
1258
+ req = min(expected, _MAX_ZLIB_INFLATE_BYTES)
1259
+ if up.decompressed_bytes < req:
1260
+ return _kitty_reply(
1261
+ ctrl, "EINVAL:truncated compressed payload", is_error=True
1262
+ )
1263
+ elif up.decoded_bytes < expected:
1264
+ return _kitty_reply(ctrl, "EINVAL:truncated raw payload", is_error=True)
1265
+ else:
1266
+ return _kitty_reply(
1267
+ ctrl, f"EINVAL:unsupported format f={fmt}", is_error=True
1268
+ )
1269
+
1270
+ if w_px > self._max_dim or h_px > self._max_dim:
1271
+ return _kitty_reply(
1272
+ ctrl, "EINVAL:image dimensions exceed limit", is_error=True
1273
+ )
1274
+
1275
+ action = ctrl.get("a", "t")
1276
+ if action == "q":
1277
+ return _kitty_reply(ctrl, "OK", is_error=False)
1278
+
1279
+ client_id = _parse_int(ctrl, "i", 0)
1280
+ client_num = _parse_int(ctrl, "I", 0)
1281
+ if client_id > 0:
1282
+ img_id = client_id
1283
+ else:
1284
+ img_id = self._next_auto_id
1285
+ self._next_auto_id += 1
1286
+ meta = ImageMeta(
1287
+ protocol=GraphicsProtocol.KITTY,
1288
+ image_id=img_id,
1289
+ image_number=client_num,
1290
+ width_px=w_px,
1291
+ height_px=h_px,
1292
+ format_code=fmt,
1293
+ compressed=ctrl.get("o") == "z",
1294
+ byte_len=up.encoded_bytes,
1295
+ )
1296
+ self._store_image(meta)
1297
+ reply_id = img_id if (client_id > 0 or client_num > 0) else None
1298
+ if action == "T":
1299
+ return self._place_kitty_image(
1300
+ ctrl,
1301
+ cursor_row=cursor_row,
1302
+ cursor_col=cursor_col,
1303
+ screen_cols=screen_cols,
1304
+ scrolled_total_getter=scrolled_total_getter,
1305
+ scrolled_total=scrolled_total,
1306
+ cell_width_px=cell_width_px,
1307
+ cell_height_px=cell_height_px,
1308
+ min_row=min_row,
1309
+ advance_cursor=advance_cursor,
1310
+ target_meta=meta,
1311
+ reply_image_id=reply_id,
1312
+ )
1313
+ return _kitty_reply(ctrl, "OK", is_error=False, reply_image_id=reply_id)
1314
+
1315
+ def _resolve_kitty_image(self, control: dict[str, str]) -> ImageMeta | None:
1316
+ img_id = _parse_int(control, "i", 0)
1317
+ if img_id > 0:
1318
+ return self._images.get(img_id)
1319
+ img_num = _parse_int(control, "I", 0)
1320
+ if img_num > 0:
1321
+ for meta in reversed(self._images.values()):
1322
+ if meta.image_number == img_num:
1323
+ return meta
1324
+ return None
1325
+
1326
+ def _find_parent_placement(
1327
+ self,
1328
+ parent_id: int,
1329
+ parent_pid: int,
1330
+ ) -> _MutablePlacement | None:
1331
+ for p in reversed(self._placements):
1332
+ if p.image_id == parent_id and (
1333
+ parent_pid == 0 or p.placement_id == parent_pid
1334
+ ):
1335
+ return p
1336
+ return None
1337
+
1338
+ def _validate_parent_chain(
1339
+ self,
1340
+ child_img_id: int,
1341
+ child_pid: int,
1342
+ parent: _MutablePlacement,
1343
+ ) -> str | None:
1344
+ if (
1345
+ child_img_id == parent.image_id
1346
+ and child_pid == parent.placement_id
1347
+ and (child_pid > 0 or parent.placement_id == 0)
1348
+ ):
1349
+ return "ECYCLE:self-parented placement"
1350
+ cur: _MutablePlacement | None = parent
1351
+ depth = 1
1352
+ while cur is not None and cur.parent_image_id > 0:
1353
+ if depth >= _MAX_PARENT_DEPTH:
1354
+ return "ETOODEEP:relative placement chain exceeds limit"
1355
+ if cur.parent_image_id == child_img_id and (
1356
+ cur.parent_placement_id in (0, child_pid)
1357
+ ):
1358
+ return "ECYCLE:cyclic relative placement"
1359
+ cur = self._find_parent_placement(
1360
+ cur.parent_image_id, cur.parent_placement_id
1361
+ )
1362
+ depth += 1
1363
+ return None
1364
+
1365
+ def _place_kitty_image(
1366
+ self,
1367
+ control: dict[str, str],
1368
+ *,
1369
+ cursor_row: int,
1370
+ cursor_col: int,
1371
+ screen_cols: int,
1372
+ scrolled_total_getter: collections.abc.Callable[[], int] | None,
1373
+ scrolled_total: int,
1374
+ cell_width_px: int,
1375
+ cell_height_px: int,
1376
+ min_row: int = 0,
1377
+ advance_cursor: collections.abc.Callable[[int, int], int] | None,
1378
+ target_meta: ImageMeta | None = None,
1379
+ reply_image_id: int | None = None,
1380
+ ) -> bytes | None:
1381
+ meta = (
1382
+ target_meta
1383
+ if target_meta is not None
1384
+ else self._resolve_kitty_image(control)
1385
+ )
1386
+ if meta is None:
1387
+ return _kitty_reply(control, "ENOENT:image not found", is_error=True)
1388
+
1389
+ virtual = _parse_int(control, "U", 0) == 1
1390
+ parent_id = _parse_int(control, "P", 0)
1391
+ parent_pid = _parse_int(control, "Q", 0)
1392
+ pid = _parse_int(control, "p", 0)
1393
+ if virtual and parent_id > 0:
1394
+ return _kitty_reply(
1395
+ control,
1396
+ "EINVAL:virtual placement cannot be relative",
1397
+ is_error=True,
1398
+ )
1399
+
1400
+ parent_pl: _MutablePlacement | None = None
1401
+ if parent_id > 0:
1402
+ if parent_id not in self._images:
1403
+ return _kitty_reply(
1404
+ control, "ENOPARENT:parent image not found", is_error=True
1405
+ )
1406
+ parent_pl = self._find_parent_placement(parent_id, parent_pid)
1407
+ if parent_pl is None or parent_pl.virtual:
1408
+ return _kitty_reply(
1409
+ control, "ENOPARENT:parent placement not found", is_error=True
1410
+ )
1411
+ chain_err = self._validate_parent_chain(meta.image_id, pid, parent_pl)
1412
+ if chain_err is not None:
1413
+ return _kitty_reply(control, chain_err, is_error=True)
1414
+
1415
+ cw = max(1, cell_width_px)
1416
+ ch = max(1, cell_height_px)
1417
+ src_x = min(meta.width_px, max(0, _parse_int(control, "x", 0)))
1418
+ src_y = min(meta.height_px, max(0, _parse_int(control, "y", 0)))
1419
+ req_w = max(0, _parse_int(control, "w", 0))
1420
+ req_h = max(0, _parse_int(control, "h", 0))
1421
+ src_w = (
1422
+ min(req_w, meta.width_px - src_x) if req_w > 0 else (meta.width_px - src_x)
1423
+ )
1424
+ src_h = (
1425
+ min(req_h, meta.height_px - src_y)
1426
+ if req_h > 0
1427
+ else (meta.height_px - src_y)
1428
+ )
1429
+ off_x = min(cw - 1, max(0, _parse_int(control, "X", 0)))
1430
+ off_y = min(ch - 1, max(0, _parse_int(control, "Y", 0)))
1431
+ req_c = max(0, _parse_int(control, "c", 0))
1432
+ req_r = max(0, _parse_int(control, "r", 0))
1433
+
1434
+ if req_c > 0 and req_r > 0:
1435
+ cols, rows = req_c, req_r
1436
+ elif req_c > 0:
1437
+ cols = req_c
1438
+ w_px = max(1, req_c * cw - off_x)
1439
+ h_px = max(1, (w_px * max(1, src_h) + max(1, src_w) - 1) // max(1, src_w))
1440
+ rows = max(1, (h_px + off_y + ch - 1) // ch)
1441
+ elif req_r > 0:
1442
+ rows = req_r
1443
+ h_px = max(1, req_r * ch - off_y)
1444
+ w_px = max(1, (h_px * max(1, src_w) + max(1, src_h) - 1) // max(1, src_h))
1445
+ cols = max(1, (w_px + off_x + cw - 1) // cw)
1446
+ else:
1447
+ cols = max(1, (max(1, src_w) + off_x + cw - 1) // cw)
1448
+ rows = max(1, (max(1, src_h) + off_y + ch - 1) // ch)
1449
+
1450
+ cols = min(max(1, screen_cols * 4), cols)
1451
+ rows = min(max(1, self._max_dim), rows)
1452
+ z_idx = _parse_int(control, "z", 0)
1453
+ move_cursor = (
1454
+ not virtual and parent_id == 0 and _parse_int(control, "C", 0) == 0
1455
+ )
1456
+
1457
+ eff_reply_id = (
1458
+ reply_image_id
1459
+ if target_meta is not None
1460
+ else (
1461
+ meta.image_id
1462
+ if (_parse_int(control, "i", 0) > 0 or _parse_int(control, "I", 0) > 0)
1463
+ else None
1464
+ )
1465
+ )
1466
+
1467
+ if parent_pl is not None:
1468
+ abs_r = parent_pl.abs_row + _parse_int(control, "V", 0)
1469
+ col_pos = max(
1470
+ 0, min(screen_cols - 1, parent_pl.col + _parse_int(control, "H", 0))
1471
+ )
1472
+ min_abs = 0
1473
+ else:
1474
+ anchor_r = cursor_row
1475
+ if move_cursor and advance_cursor is not None:
1476
+ anchor_r = advance_cursor(rows, cols)
1477
+ post_scrolled = (
1478
+ scrolled_total_getter()
1479
+ if scrolled_total_getter is not None
1480
+ else scrolled_total
1481
+ )
1482
+ abs_r = post_scrolled + anchor_r
1483
+ col_pos = cursor_col
1484
+ min_abs = (
1485
+ (post_scrolled + min_row) if post_scrolled == scrolled_total else 0
1486
+ )
1487
+
1488
+ if not virtual and abs_r < min_abs:
1489
+ clip_top = min_abs - abs_r
1490
+ if clip_top >= rows:
1491
+ return _kitty_reply(
1492
+ control, "OK", is_error=False, reply_image_id=eff_reply_id
1493
+ )
1494
+ if src_h > 0 and rows > 0:
1495
+ crop_px = (src_h * clip_top) // rows
1496
+ src_y += crop_px
1497
+ src_h = max(1, src_h - crop_px)
1498
+ rows -= clip_top
1499
+ abs_r = min_abs
1500
+
1501
+ self._append_placement(
1502
+ _MutablePlacement(
1503
+ protocol=GraphicsProtocol.KITTY,
1504
+ image_id=meta.image_id,
1505
+ placement_id=pid,
1506
+ abs_row=max(0, abs_r),
1507
+ col=col_pos,
1508
+ rows=rows,
1509
+ cols=cols,
1510
+ z_index=z_idx,
1511
+ virtual=virtual,
1512
+ parent_image_id=parent_id,
1513
+ parent_placement_id=parent_pid,
1514
+ source_x=src_x,
1515
+ source_y=src_y,
1516
+ source_width=src_w,
1517
+ source_height=src_h,
1518
+ cell_offset_x=off_x,
1519
+ cell_offset_y=off_y,
1520
+ ),
1521
+ )
1522
+ return _kitty_reply(control, "OK", is_error=False, reply_image_id=eff_reply_id)
1523
+
1524
+ def _prune_orphans(self, *, free_images: bool = False) -> None:
1525
+ if not self._placements:
1526
+ return
1527
+ children_by_key: dict[tuple[int, int], list[int]] = {}
1528
+ children_by_img: dict[int, list[int]] = {}
1529
+ reachable: list[bool] = [False] * len(self._placements)
1530
+ queue: collections.deque[int] = collections.deque()
1531
+
1532
+ for idx, p in enumerate(self._placements):
1533
+ if p.parent_image_id <= 0:
1534
+ reachable[idx] = True
1535
+ queue.append(idx)
1536
+ elif p.parent_placement_id > 0:
1537
+ children_by_key.setdefault(
1538
+ (p.parent_image_id, p.parent_placement_id), []
1539
+ ).append(idx)
1540
+ else:
1541
+ children_by_img.setdefault(p.parent_image_id, []).append(idx)
1542
+
1543
+ if len(queue) == len(self._placements):
1544
+ return
1545
+
1546
+ while queue:
1547
+ cur_idx = queue.popleft()
1548
+ cur_p = self._placements[cur_idx]
1549
+ for child_idx in children_by_key.get(
1550
+ (cur_p.image_id, cur_p.placement_id), ()
1551
+ ):
1552
+ if not reachable[child_idx]:
1553
+ reachable[child_idx] = True
1554
+ queue.append(child_idx)
1555
+ for child_idx in children_by_img.get(cur_p.image_id, ()):
1556
+ if not reachable[child_idx]:
1557
+ reachable[child_idx] = True
1558
+ queue.append(child_idx)
1559
+
1560
+ kept: list[_MutablePlacement] = []
1561
+ removed_ids: set[int] = set()
1562
+ for idx, p in enumerate(self._placements):
1563
+ if reachable[idx]:
1564
+ kept.append(p)
1565
+ else:
1566
+ removed_ids.add(p.image_id)
1567
+ self._placements = kept
1568
+ if free_images and removed_ids:
1569
+ still_used = {p.image_id for p in self._placements}
1570
+ for rid in removed_ids - still_used:
1571
+ self._images.pop(rid, None)
1572
+
1573
+ def _handle_kitty_delete(
1574
+ self,
1575
+ control: dict[str, str],
1576
+ *,
1577
+ cursor_row: int,
1578
+ cursor_col: int,
1579
+ screen_rows: int,
1580
+ scrolled_total: int,
1581
+ ) -> None:
1582
+ raw_sel = control.get("d", "a") or "a"
1583
+ sel = raw_sel[0]
1584
+ free_images = sel.isupper()
1585
+ kind = sel.lower()
1586
+ pid_filter = _parse_int(control, "p", 0)
1587
+ top_abs = scrolled_total
1588
+ bot_abs = scrolled_total + screen_rows
1589
+
1590
+ candidates: set[int] = set()
1591
+ kept: list[_MutablePlacement] = []
1592
+
1593
+ if kind == "a":
1594
+ for p in self._placements:
1595
+ if (
1596
+ p.virtual
1597
+ or p.parent_image_id > 0
1598
+ or p.abs_row + p.rows <= top_abs
1599
+ or p.abs_row >= bot_abs
1600
+ ):
1601
+ kept.append(p)
1602
+ else:
1603
+ candidates.add(p.image_id)
1604
+ elif kind in ("i", "n"):
1605
+ target = (
1606
+ _parse_int(control, "i", 0)
1607
+ if kind == "i"
1608
+ else (
1609
+ meta.image_id
1610
+ if (meta := self._resolve_kitty_image(control)) is not None
1611
+ else 0
1612
+ )
1613
+ )
1614
+ if target > 0 and pid_filter == 0:
1615
+ candidates.add(target)
1616
+ for p in self._placements:
1617
+ if p.image_id == target and (
1618
+ pid_filter == 0 or p.placement_id == pid_filter
1619
+ ):
1620
+ candidates.add(p.image_id)
1621
+ else:
1622
+ kept.append(p)
1623
+ elif kind == "r":
1624
+ lo = _parse_int(control, "x", 0)
1625
+ hi = _parse_int(control, "y", 0)
1626
+ for p in self._placements:
1627
+ if lo <= p.image_id <= hi:
1628
+ candidates.add(p.image_id)
1629
+ else:
1630
+ kept.append(p)
1631
+ if free_images:
1632
+ for img_id in [k for k in self._images if lo <= k <= hi]:
1633
+ candidates.add(img_id)
1634
+ elif kind in ("c", "p", "q", "x", "y", "z"):
1635
+ cell_c = cursor_col if kind == "c" else (_parse_int(control, "x", 0) - 1)
1636
+ cell_r = cursor_row if kind == "c" else (_parse_int(control, "y", 0) - 1)
1637
+ if kind in ("p", "q", "x") and cell_c < 0:
1638
+ return
1639
+ if kind in ("p", "q", "y") and not (0 <= cell_r < screen_rows):
1640
+ return
1641
+ abs_cell_r = scrolled_total + cell_r
1642
+ z_target = _parse_int(control, "z", 0)
1643
+ for p in self._placements:
1644
+ if p.virtual:
1645
+ kept.append(p)
1646
+ continue
1647
+ if kind == "z":
1648
+ match = p.z_index == z_target
1649
+ elif kind in ("c", "p"):
1650
+ match = (
1651
+ p.abs_row <= abs_cell_r < p.abs_row + p.rows
1652
+ and p.col <= cell_c < p.col + p.cols
1653
+ )
1654
+ elif kind == "q":
1655
+ match = (
1656
+ p.z_index == z_target
1657
+ and p.abs_row <= abs_cell_r < p.abs_row + p.rows
1658
+ and p.col <= cell_c < p.col + p.cols
1659
+ )
1660
+ elif kind == "x":
1661
+ match = (
1662
+ p.abs_row + p.rows > top_abs
1663
+ and p.abs_row < bot_abs
1664
+ and p.col <= cell_c < p.col + p.cols
1665
+ )
1666
+ else: # kind == "y"
1667
+ match = p.abs_row <= abs_cell_r < p.abs_row + p.rows
1668
+ if match:
1669
+ candidates.add(p.image_id)
1670
+ else:
1671
+ kept.append(p)
1672
+ else:
1673
+ return
1674
+
1675
+ changed = len(kept) != len(self._placements)
1676
+ self._placements = kept
1677
+ self._prune_orphans(free_images=free_images)
1678
+ if free_images and candidates:
1679
+ still_used = {p.image_id for p in self._placements}
1680
+ for cid in candidates - still_used:
1681
+ if self._images.pop(cid, None) is not None:
1682
+ changed = True
1683
+ if changed:
1684
+ self._bump()
1685
+
1686
+
1687
+ __all__ = [
1688
+ "GraphicsProtocol",
1689
+ "GraphicsTracker",
1690
+ "ImageMeta",
1691
+ "ImagePlacement",
1692
+ "ZLayer",
1693
+ "extract_png_dimensions",
1694
+ "scan_sixel_geometry",
1695
+ ]