@amritk/nish-aarch64-linux 0.45.1 → 0.47.0

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.
package/std/term.ts CHANGED
@@ -316,6 +316,8 @@ const TERM_ESC: i32 = 27
316
316
 
317
317
  /** The space a blank cell holds. */
318
318
  const TERM_SPACE: i32 = 32
319
+ /** The largest `i32`, where a column count stops rather than wraps. */
320
+ const TERM_I32_MAX: i32 = 2147483647
319
321
 
320
322
  /** DEL, the first byte past printable ASCII. */
321
323
  const TERM_DELETE: i32 = 127
@@ -369,9 +371,6 @@ const TERM_STYLE_UNKNOWN: i32 = -2
369
371
  */
370
372
  const TERM_CELL_BYTES: i32 = 64
371
373
 
372
- /** The most cells a side of a `Screen` has; a terminal reports up to 65,535. */
373
- const TERM_MAX_SIDE: i32 = 4096
374
-
375
374
  /** The most cells a `Screen` has, so its `flush` buffer stays at 64 MiB. */
376
375
  const TERM_MAX_CELLS: i32 = 1048576
377
376
 
@@ -393,6 +392,90 @@ const TERM_REPLACEMENT: i32 = 65533
393
392
  /** Whether a string here is UTF-8 bytes (natively) rather than UTF-16 units (under Node). */
394
393
  const termNativeStrings = (): boolean => toI32("▀".length) === 3
395
394
 
395
+ /** A side of a `Screen`: `v` held to 0–4,096 cells; a terminal reports up to 65,535. */
396
+ const termSide = (v: i32): integer<0, 4096> => {
397
+ if (v <= 0) {
398
+ return 0
399
+ }
400
+ if (v >= 4096) {
401
+ return 4096
402
+ }
403
+ return v
404
+ }
405
+
406
+ /** The rows of a `Screen` `w` columns wide: `h`, or fewer when `w * h` would pass `TERM_MAX_CELLS`. */
407
+ const termFitRows = (w: integer<0, 4096>, h: integer<0, 4096>): integer<0, 4096> => {
408
+ if (w <= 0) {
409
+ return h
410
+ }
411
+ const most: i32 = (TERM_MAX_CELLS / w) | 0
412
+ if (h <= most) {
413
+ return h
414
+ }
415
+ return termSide(most)
416
+ }
417
+
418
+ /** The cells of a `Screen` `w` by `h`, which `termFitRows` has kept within `TERM_MAX_CELLS`. */
419
+ const termCellCount = (w: integer<0, 4096>, h: integer<0, 4096>): integer<0, 1048576> => termCellLimit(w * h)
420
+
421
+ /**
422
+ * `n` cells of `value`. Built by `push` rather than `new Array<i32>(n)`, whose
423
+ * length check the declared range of `n` does not reach. A `resize` at the
424
+ * 1,048,576-cell cap, with its flush room, takes about 0.1 s, twice what
425
+ * `new Array` took.
426
+ */
427
+ const termCells = (n: integer<0, 1048576>, value: i32): i32[] => {
428
+ const cells: i32[] = []
429
+ for (let i: i32 = 0; i < n; i++) {
430
+ cells.push(value)
431
+ }
432
+ return cells
433
+ }
434
+
435
+ /** The zeroed room a flush of `cells` cells writes into: `TERM_CELL_BYTES` per cell and once more. */
436
+ const termFlushRoom = (cells: integer<0, 1048576>): u8[] => {
437
+ const room: u8[] = []
438
+ for (let i: i32 = 0; i <= cells; i++) {
439
+ for (let k: i32 = 0; k < TERM_CELL_BYTES; k++) {
440
+ room.push(0)
441
+ }
442
+ }
443
+ return room
444
+ }
445
+
446
+ /** `n` held to the cells a `Screen` can have, 0 to `TERM_MAX_CELLS`. */
447
+ const termCellLimit = (n: i32): integer<0, 1048576> => {
448
+ if (n <= 0) {
449
+ return 0
450
+ }
451
+ if (n >= 1048576) {
452
+ return 1048576
453
+ }
454
+ return n
455
+ }
456
+
457
+ /**
458
+ * Where cell `x`, `y` of a `w`-wide, `h`-high grid sits in a buffer of `len`
459
+ * slots, row by row, or -1 when it is off the grid or past the buffer's end.
460
+ */
461
+ const termGridAt = (x: i32, y: i32, w: i32, h: i32, len: i32): i32 => {
462
+ if (x < 0 || y < 0 || x >= w || y >= h) {
463
+ return -1
464
+ }
465
+ const at: i64 = toI64(y) * toI64(w) + toI64(x)
466
+ if (at >= toI64(len)) {
467
+ return -1
468
+ }
469
+ return toI32(at)
470
+ }
471
+
472
+ /** The length of the shortest of four of a `Screen`'s buffers. */
473
+ const termShortest = (a: i32[], b: i32[], c: i32[], d: i32[]): i32 => {
474
+ const ab: i32 = toI32(a.length) < toI32(b.length) ? toI32(a.length) : toI32(b.length)
475
+ const cd: i32 = toI32(c.length) < toI32(d.length) ? toI32(c.length) : toI32(d.length)
476
+ return ab < cd ? ab : cd
477
+ }
478
+
396
479
  /** `v` held to `lo`–`hi`. */
397
480
  const termClamp = (v: i32, lo: i32, hi: i32): i32 => {
398
481
  if (v < lo) {
@@ -432,18 +515,41 @@ export const rgb = (r: i32, g: i32, b: i32): i32 =>
432
515
  (termClamp(r, 0, 255) << 16) | (termClamp(g, 0, 255) << 8) | termClamp(b, 0, 255)
433
516
 
434
517
  /** The index of the 6×6×6 colour cube's level (0–5) nearest one component in 0–255. */
435
- const termCubeLevel = (v: i32): i32 => {
518
+ const termCubeLevel = (v: i32): integer<0, 5> => {
436
519
  if (v < 48) {
437
520
  return 0
438
521
  }
439
522
  if (v < 115) {
440
523
  return 1
441
524
  }
442
- return ((v - 35) / 40) | 0
525
+ if (v < 155) {
526
+ return 2
527
+ }
528
+ if (v < 195) {
529
+ return 3
530
+ }
531
+ if (v < 235) {
532
+ return 4
533
+ }
534
+ return 5
443
535
  }
444
536
 
445
537
  /** The component value of cube level `q`: 0, 95, 135, 175, 215 or 255. */
446
- const termCubeValue = (q: i32): i32 => (q === 0 ? 0 : q * 40 + 55)
538
+ const termCubeValue = (q: i32): f64 => (q === 0 ? 0 : toF64(q) * 40 + 55)
539
+
540
+ /**
541
+ * The grey ramp entry (232–255) for a mean component in 0–255: grey `k` is
542
+ * `10k + 8`, and the mean picks the highest one whose midpoint below it does
543
+ * not pass the mean.
544
+ */
545
+ const termGreyIndex = (average: i32): i32 => {
546
+ for (let step: i32 = 0; step < 23; step++) {
547
+ if (average < step * 10 + 13) {
548
+ return step + 232
549
+ }
550
+ }
551
+ return 255
552
+ }
447
553
 
448
554
  /**
449
555
  * The 256-colour palette entry nearest a colour: one of the 6×6×6 cube (16–231)
@@ -459,22 +565,22 @@ export const paletteIndex = (colour: i32): i32 => {
459
565
  const r: i32 = (colour >> 16) & 255
460
566
  const g: i32 = (colour >> 8) & 255
461
567
  const b: i32 = colour & 255
462
- const qr: i32 = termCubeLevel(r)
463
- const qg: i32 = termCubeLevel(g)
464
- const qb: i32 = termCubeLevel(b)
568
+ const qr = termCubeLevel(r)
569
+ const qg = termCubeLevel(g)
570
+ const qb = termCubeLevel(b)
465
571
  const cube: i32 = qr * 36 + qg * 6 + qb + 16
466
- const dr: i32 = r - termCubeValue(qr)
467
- const dg: i32 = g - termCubeValue(qg)
468
- const db: i32 = b - termCubeValue(qb)
469
- const cubeDistance: i32 = dr * dr + dg * dg + db * db
470
- const average: i32 = ((r + g + b) / 3) | 0
471
- const step: i32 = average > 238 ? 23 : termClamp(((average - 3) / 10) | 0, 0, 23)
472
- const grey: i32 = step * 10 + 8
473
- const gr: i32 = r - grey
474
- const gg: i32 = g - grey
475
- const gb: i32 = b - grey
476
- const greyDistance: i32 = gr * gr + gg * gg + gb * gb
477
- return greyDistance < cubeDistance ? step + 232 : cube
572
+ // The distances are squared in f64: each term is under 2^16, exact there.
573
+ const dr: f64 = toF64(r) - termCubeValue(qr)
574
+ const dg: f64 = toF64(g) - termCubeValue(qg)
575
+ const db: f64 = toF64(b) - termCubeValue(qb)
576
+ const cubeDistance: f64 = dr * dr + dg * dg + db * db
577
+ const greyIndex: i32 = termGreyIndex(((r + g + b) / 3) | 0)
578
+ const grey: f64 = (toF64(greyIndex) - 232) * 10 + 8
579
+ const gr: f64 = toF64(r) - grey
580
+ const gg: f64 = toF64(g) - grey
581
+ const gb: f64 = toF64(b) - grey
582
+ const greyDistance: f64 = gr * gr + gg * gg + gb * gb
583
+ return greyDistance < cubeDistance ? greyIndex : cube
478
584
  }
479
585
 
480
586
  /**
@@ -528,7 +634,9 @@ export const resetStyle = (): string => "\x1b[0m"
528
634
  * @param y The row, from 0 at the top.
529
635
  * @returns The escape sequence, to `write`.
530
636
  */
531
- export const moveCursor = (x: i32, y: i32): string => `\x1b[${y + 1};${x + 1}H`
637
+ export const moveCursor = (x: i32, y: i32): string =>
638
+ // The sequence counts from 1, which is past `i32` for a side of 2,147,483,647, so the sum is `i64`.
639
+ `\x1b[${toI64(y) + toI64(1)};${toI64(x) + toI64(1)}H`
532
640
 
533
641
  /**
534
642
  * Begin a synchronized update (DEC mode 2026): a terminal that knows the mode
@@ -547,55 +655,59 @@ export const beginSync = (): string => "\x1b[?2026h"
547
655
  export const endSync = (): string => "\x1b[?2026l"
548
656
 
549
657
  /**
550
- * The code point of the character that starts at unit `i` of `s`: UTF-8 bytes
551
- * natively, UTF-16 units under Node. A unit that cannot start one is U+FFFD.
658
+ * The character that starts at unit `i` of `s`, which has `n` units: UTF-8
659
+ * bytes natively, UTF-16 units under Node. The result is its code point shifted
660
+ * left 3, or-ed with the units it takes (1–4), so a caller walks `s` in place.
661
+ * A unit that cannot start a character, or a lead whose continuation is cut
662
+ * short, is one U+FFFD of one unit, and the next unit is read afresh.
552
663
  */
553
- const termCodePointAt = (s: string, i: i32, n: i32): i32 => {
664
+ const termCodePointStep = (s: string, i: i32, n: i32): i32 => {
665
+ if (i < 0 || i >= n) {
666
+ return (TERM_REPLACEMENT << 3) | 1
667
+ }
554
668
  const c: i32 = toI32(s.charCodeAt(i))
669
+ let j: i32 = i
670
+ if (j < TERM_I32_MAX) {
671
+ j = j + 1
672
+ }
555
673
  if (!termNativeStrings()) {
556
- if (c >= 55296 && c < 56320 && i + 1 < n) {
557
- const lo: i32 = toI32(s.charCodeAt(i + 1))
674
+ if (c >= 55296 && c < 56320 && j < n) {
675
+ const lo: i32 = toI32(s.charCodeAt(j))
558
676
  if (lo >= 56320 && lo < 57344) {
559
- return ((c - 55296) << 10) + (lo - 56320) + 65536
677
+ return (((c & 1023) * 1024 + (lo & 1023) + 65536) << 3) | 2
560
678
  }
561
679
  }
562
- return c
680
+ return (c << 3) | 1
563
681
  }
564
- const width: i32 = termCodePointUnits(s, i, n)
565
682
  if (c < 128) {
566
- return c
567
- }
568
- if (width === 1) {
569
- return TERM_REPLACEMENT
683
+ return (c << 3) | 1
570
684
  }
685
+ const width: i32 = c >= 248 ? 1 : termLeadWidth(c)
571
686
  let cp: i32 = termLeadBits(c, width)
572
- for (let k: i32 = 1; k < width; k++) {
573
- cp = (cp << 6) | (toI32(s.charCodeAt(i + k)) & 63)
574
- }
575
- return cp
576
- }
577
-
578
- /** How many units of `s` the character at `i` takes: 1–4 bytes natively, 1 or 2 units under Node. */
579
- const termCodePointUnits = (s: string, i: i32, n: i32): i32 => {
580
- const c: i32 = toI32(s.charCodeAt(i))
581
- if (!termNativeStrings()) {
582
- if (c >= 55296 && c < 56320 && i + 1 < n) {
583
- const lo: i32 = toI32(s.charCodeAt(i + 1))
584
- return lo >= 56320 && lo < 57344 ? 2 : 1
687
+ let read: i32 = 1
688
+ let k: i32 = j
689
+ while (read < width && k < n) {
690
+ const next: i32 = toI32(s.charCodeAt(k))
691
+ if (next < 128 || next >= 192) {
692
+ break
585
693
  }
586
- return 1
694
+ cp = (cp << 6) | (next & 63)
695
+ read = read + 1
696
+ k = k + 1
587
697
  }
588
- const width: i32 = c >= 248 ? 1 : termLeadWidth(c)
589
- if (width === 1 || i + width > n) {
590
- return 1
698
+ if (width > 1 && read === width) {
699
+ return (cp << 3) | width
591
700
  }
592
- for (let k: i32 = 1; k < width; k++) {
593
- const next: i32 = toI32(s.charCodeAt(i + k))
594
- if (next < 128 || next >= 192) {
595
- return 1
596
- }
701
+ return (TERM_REPLACEMENT << 3) | 1
702
+ }
703
+
704
+ /** The unit after the character at `i`, which `step` (from `termCodePointStep`) says takes `step & 7` units; at most `n`. */
705
+ const termStepOn = (i: i32, step: i32, n: i32): i32 => {
706
+ if (i < 0 || i > 2147483640) {
707
+ return n
597
708
  }
598
- return width
709
+ const next: i32 = i + (step & 7)
710
+ return next < n ? next : n
599
711
  }
600
712
 
601
713
  /**
@@ -604,28 +716,38 @@ const termCodePointUnits = (s: string, i: i32, n: i32): i32 => {
604
716
  * sends the same bytes back out.
605
717
  */
606
718
  const termBytesText = (bytes: u8[], n: i32): string => {
719
+ // Every caller passes at most `bytes.length`: a whole buffer, or a screen's `outLen`, which `put` keeps within `out`.
720
+ const held: i32 = toI32(bytes.length)
721
+ let end: i32 = n
722
+ if (end > held) {
723
+ end = held
724
+ }
725
+ if (end < 0) {
726
+ end = 0
727
+ }
607
728
  if (termNativeStrings()) {
608
- return String.fromBytes(bytes, 0, n)
729
+ return String.fromBytes(bytes, 0, end)
609
730
  }
610
731
  const pieces: string[] = []
611
- let run: i32 = 0
612
732
  let i: i32 = 0
613
- while (i < n) {
614
- if (!(i >= 0 && i < toI32(bytes.length))) {
615
- panic("nish/term: a byte count past the end of its buffer")
616
- }
733
+ while (i >= 0 && i < end && i < toI32(bytes.length)) {
617
734
  const c: i32 = toI32(bytes[i])
735
+ i = i + 1
618
736
  if (c < 128) {
619
- i = i + 1
737
+ pieces.push(String.fromCharCode(c))
620
738
  continue
621
739
  }
622
- if (run < i) {
623
- pieces.push(String.fromBytes(bytes, run, i))
624
- }
625
740
  const width: i32 = termLeadWidth(c)
626
741
  let cp: i32 = width === 1 ? TERM_REPLACEMENT : termLeadBits(c, width)
627
- for (let k: i32 = 1; k < width && i + k < n; k++) {
628
- cp = (cp << 6) | (toI32(bytes[i + k]) & 63)
742
+ // A character cut off at `end` takes the bytes that are there.
743
+ let left: i32 = 0
744
+ if (width > 1) {
745
+ left = width - 1
746
+ }
747
+ while (left > 0 && i >= 0 && i < end && i < toI32(bytes.length)) {
748
+ cp = (cp << 6) | (toI32(bytes[i]) & 63)
749
+ i = i + 1
750
+ left = left - 1
629
751
  }
630
752
  if (cp >= 65536) {
631
753
  const v: i32 = cp - 65536
@@ -633,11 +755,6 @@ const termBytesText = (bytes: u8[], n: i32): string => {
633
755
  } else {
634
756
  pieces.push(String.fromCharCode(cp))
635
757
  }
636
- i = i + width
637
- run = i
638
- }
639
- if (run < n) {
640
- pieces.push(String.fromBytes(bytes, run, n))
641
758
  }
642
759
  return pieces.join("")
643
760
  }
@@ -710,25 +827,22 @@ export class Screen {
710
827
  * @param height The new rows.
711
828
  */
712
829
  resize(width: i32, height: i32): void {
713
- this.width = termClamp(width, 0, TERM_MAX_SIDE)
714
- this.height = termClamp(height, 0, TERM_MAX_SIDE)
715
- if (this.width * this.height > TERM_MAX_CELLS) {
716
- this.height = (TERM_MAX_CELLS / this.width) | 0
717
- }
718
- const cells: i32 = this.width * this.height
719
- this.glyphs = new Array<i32>(cells)
720
- this.fgs = new Array<i32>(cells)
721
- this.bgs = new Array<i32>(cells)
722
- this.attrs = new Array<i32>(cells)
723
- this.sentGlyphs = new Array<i32>(cells)
724
- this.sentFgs = new Array<i32>(cells)
725
- this.sentBgs = new Array<i32>(cells)
726
- this.sentAttrs = new Array<i32>(cells)
830
+ const w = termSide(width)
831
+ const h = termFitRows(w, termSide(height))
832
+ const cells = termCellCount(w, h)
833
+ this.width = w
834
+ this.height = h
835
+ this.glyphs = termCells(cells, TERM_SPACE)
836
+ this.fgs = termCells(cells, COLOR_DEFAULT)
837
+ this.bgs = termCells(cells, COLOR_DEFAULT)
838
+ this.attrs = termCells(cells, ATTR_NONE)
839
+ this.sentGlyphs = termCells(cells, TERM_UNSENT)
840
+ this.sentFgs = termCells(cells, COLOR_DEFAULT)
841
+ this.sentBgs = termCells(cells, COLOR_DEFAULT)
842
+ this.sentAttrs = termCells(cells, ATTR_NONE)
727
843
  // Sized here rather than in `flush`, so a flush stores nothing into the
728
844
  // screen and a frame loop around it can take its string back every pass.
729
- this.out = new Array<u8>(cells * TERM_CELL_BYTES + TERM_CELL_BYTES)
730
- this.clear(COLOR_DEFAULT)
731
- this.invalidate()
845
+ this.out = termFlushRoom(cells)
732
846
  }
733
847
 
734
848
  /**
@@ -765,17 +879,23 @@ export class Screen {
765
879
  * has an attribute it cannot write.
766
880
  */
767
881
  set(x: i32, y: i32, glyph: i32, fg: i32, bg: i32, attrs: i32): void {
768
- if (x < 0 || y < 0 || x >= this.width || y >= this.height) {
769
- return
770
- }
771
- const i: i32 = y * this.width + x
772
- if (!(i >= 0 && i < toI32(this.glyphs.length))) {
773
- return
882
+ const glyphs: i32[] = this.glyphs
883
+ const fgs: i32[] = this.fgs
884
+ const bgs: i32[] = this.bgs
885
+ const kept: i32[] = this.attrs
886
+ const i: i32 = termGridAt(x, y, this.width, this.height, toI32(glyphs.length))
887
+ if (
888
+ i >= 0 &&
889
+ i < toI32(glyphs.length) &&
890
+ i < toI32(fgs.length) &&
891
+ i < toI32(bgs.length) &&
892
+ i < toI32(kept.length)
893
+ ) {
894
+ glyphs[i] = glyph
895
+ fgs[i] = fg
896
+ bgs[i] = bg
897
+ kept[i] = attrs & (ATTR_BOLD | ATTR_INVERSE)
774
898
  }
775
- this.glyphs[i] = glyph
776
- this.fgs[i] = fg
777
- this.bgs[i] = bg
778
- this.attrs[i] = attrs & (ATTR_BOLD | ATTR_INVERSE)
779
899
  }
780
900
 
781
901
  /**
@@ -787,16 +907,18 @@ export class Screen {
787
907
  * @param fg The characters' colour.
788
908
  * @param bg The colour behind them.
789
909
  * @param attrs `ATTR_BOLD` and `ATTR_INVERSE` bits, as `set` takes them.
790
- * @returns The column after the last character, `x` plus the characters in `s`, whether or not they were clipped.
910
+ * @returns The column after the last character, `x` plus the characters in `s`, whether or not they were clipped;
911
+ * held at 2,147,483,647 rather than wrapping.
791
912
  */
792
913
  text(x: i32, y: i32, s: string, fg: i32, bg: i32, attrs: i32): i32 {
793
914
  const n: i32 = toI32(s.length)
794
915
  let column: i32 = x
795
916
  let i: i32 = 0
796
917
  while (i < n) {
797
- this.set(column, y, termCodePointAt(s, i, n), fg, bg, attrs)
798
- i = i + termCodePointUnits(s, i, n)
799
- column = column + 1
918
+ const step: i32 = termCodePointStep(s, i, n)
919
+ this.set(column, y, step >> 3, fg, bg, attrs)
920
+ i = termStepOn(i, step, n)
921
+ column = column < TERM_I32_MAX ? column + 1 : column
800
922
  }
801
923
  return column
802
924
  }
@@ -809,28 +931,31 @@ export class Screen {
809
931
  * @returns The code point drawn there, or -1 off the screen.
810
932
  */
811
933
  glyphAt(x: i32, y: i32): i32 {
812
- if (x < 0 || y < 0 || x >= this.width || y >= this.height) {
813
- return -1
934
+ const glyphs: i32[] = this.glyphs
935
+ const i: i32 = termGridAt(x, y, this.width, this.height, toI32(glyphs.length))
936
+ if (i >= 0 && i < toI32(glyphs.length)) {
937
+ return glyphs[i]
814
938
  }
815
- return this.glyphs[y * this.width + x]
939
+ return -1
816
940
  }
817
941
 
818
- /** Append one byte to the flush in progress; `flush` has reserved the room. */
942
+ /** Append one byte to the flush in progress; `flush` has made the room, so none is dropped. */
819
943
  private put(b: i32): void {
820
- this.out[this.outLen] = toU8(b)
821
- this.outLen = this.outLen + 1
944
+ const out: u8[] = this.out
945
+ const at: i32 = this.outLen
946
+ if (at >= 0 && at < toI32(out.length)) {
947
+ out[at] = toU8(b)
948
+ this.outLen = at + 1
949
+ }
822
950
  }
823
951
 
824
- /** Append `v`, at least 0, in decimal: the three digits a colour channel has without recursing. */
952
+ /** Append `v`, at least 0, in decimal; a negative `v` appends nothing. */
825
953
  private putDecimal(v: i32): void {
826
- if (v >= 100) {
827
- if (v >= 1000) {
828
- this.putDecimal((v / 1000) | 0)
829
- }
830
- this.put((((v / 100) | 0) % 10) + TERM_DIGIT_0)
954
+ if (v < 0) {
955
+ return
831
956
  }
832
957
  if (v >= 10) {
833
- this.put((((v / 10) | 0) % 10) + TERM_DIGIT_0)
958
+ this.putDecimal((v / 10) | 0)
834
959
  }
835
960
  this.put((v % 10) + TERM_DIGIT_0)
836
961
  }
@@ -869,13 +994,38 @@ export class Screen {
869
994
  }
870
995
  }
871
996
 
872
- /** Append the SGR parameters for colour `key` (an RGB or a palette index) on base 30 (foreground) or 40. */
873
- private putColour(base: i32, key: i32): void {
997
+ /**
998
+ * Append `v + 1`, `v` at least 0, in decimal, carrying digit by digit so that
999
+ * `v + 1` is never formed; a negative `v` appends nothing.
1000
+ */
1001
+ private putDecimalAfter(v: i32): void {
1002
+ if (v < 0) {
1003
+ return
1004
+ }
1005
+ const rest: i32 = (v / 10) | 0
1006
+ const digit: i32 = v % 10
1007
+ if (digit === 9) {
1008
+ this.putDecimalAfter(rest)
1009
+ this.put(TERM_DIGIT_0)
1010
+ return
1011
+ }
1012
+ if (rest > 0) {
1013
+ this.putDecimal(rest)
1014
+ }
1015
+ this.put(TERM_DIGIT_0 + digit + 1)
1016
+ }
1017
+
1018
+ /**
1019
+ * Append the SGR parameters for colour `key` (an RGB or a palette index),
1020
+ * on base `tens` decimal 30 (foreground) or 40 (background).
1021
+ */
1022
+ private putColour(tens: i32, key: i32): void {
1023
+ this.put(tens === TERM_SGR_FOREGROUND ? TERM_DIGIT_0 + 3 : TERM_DIGIT_0 + 4)
874
1024
  if (key < 0) {
875
- this.putDecimal(base + 9)
1025
+ this.put(TERM_DIGIT_0 + 9)
876
1026
  return
877
1027
  }
878
- this.putDecimal(base + 8)
1028
+ this.put(TERM_DIGIT_0 + 8)
879
1029
  if (this.palette256) {
880
1030
  this.put(TERM_SEMICOLON)
881
1031
  this.put(TERM_DIGIT_0 + 5)
@@ -921,7 +1071,6 @@ export class Screen {
921
1071
  */
922
1072
  flush(): string {
923
1073
  const w: i32 = this.width
924
- const cells: i32 = toI32(this.glyphs.length)
925
1074
  this.outLen = 0
926
1075
  const glyphs: i32[] = this.glyphs
927
1076
  const fgs: i32[] = this.fgs
@@ -931,20 +1080,18 @@ export class Screen {
931
1080
  const sentFgs: i32[] = this.sentFgs
932
1081
  const sentBgs: i32[] = this.sentBgs
933
1082
  const sentAttrs: i32[] = this.sentAttrs
934
- if (
935
- !(
936
- toI32(fgs.length) === cells &&
937
- toI32(bgs.length) === cells &&
938
- toI32(attrs.length) === cells &&
939
- toI32(sentGlyphs.length) === cells &&
940
- toI32(sentFgs.length) === cells &&
941
- toI32(sentBgs.length) === cells &&
942
- toI32(sentAttrs.length) === cells &&
943
- toI32(this.out.length) >= cells * TERM_CELL_BYTES + TERM_CELL_BYTES
944
- )
945
- ) {
946
- panic("nish/term: a Screen's buffers disagree on its size")
947
- }
1083
+ // `resize` gives every buffer `width * height` cells and `out` room for
1084
+ // them. A caller that pushed to or shortened a buffer (they are public)
1085
+ // has its flush cover the cells all of them hold, never past that room,
1086
+ // so a flush allocates nothing; a screen with no columns places no cells.
1087
+ if (w <= 0) {
1088
+ return ""
1089
+ }
1090
+ const drawn: i32 = termShortest(glyphs, fgs, bgs, attrs)
1091
+ const sent: i32 = termShortest(sentGlyphs, sentFgs, sentBgs, sentAttrs)
1092
+ const room = termCellLimit(((toI32(this.out.length) - TERM_CELL_BYTES) / TERM_CELL_BYTES) | 0)
1093
+ const held: i32 = sent < drawn ? sent : drawn
1094
+ const cells = termCellLimit(room < held ? room : held)
948
1095
  if (this.sync) {
949
1096
  this.putSyncMode(TERM_FINAL_SET)
950
1097
  }
@@ -952,8 +1099,9 @@ export class Screen {
952
1099
  let styleFg: i32 = TERM_STYLE_UNKNOWN
953
1100
  let styleBg: i32 = TERM_STYLE_UNKNOWN
954
1101
  let styleAttrs: i32 = TERM_STYLE_UNKNOWN
955
- let cursorRow: i32 = -1
956
- let cursorCol: i32 = -1
1102
+ // The cell the cursor is at, or -1 when that is not known: after the last
1103
+ // column of a row, where terminals differ on whether it wrapped.
1104
+ let cursor: i32 = -1
957
1105
  for (
958
1106
  let i: i32 = 0;
959
1107
  i < cells &&
@@ -975,13 +1123,17 @@ export class Screen {
975
1123
  continue
976
1124
  }
977
1125
  const row: i32 = (i / w) | 0
978
- const col: i32 = i - row * w
1126
+ const col: i32 = i % w
979
1127
  const fgKey: i32 = this.colourKey(fg)
980
1128
  const bgKey: i32 = this.colourKey(bg)
981
- if (cursorRow !== row || cursorCol !== col) {
982
- const gap: i32 = col - cursorCol
1129
+ if (cursor !== i) {
1130
+ // How far along this row the cursor is behind the cell, or 0 when it is on another row.
1131
+ let gap: i32 = 0
1132
+ if (cursor >= 0 && cursor < i && ((cursor / w) | 0) === row) {
1133
+ gap = i - cursor
1134
+ }
983
1135
  let bridged: boolean = false
984
- if (cursorRow === row && gap > 0 && gap <= TERM_BRIDGE) {
1136
+ if (gap > 0 && gap <= TERM_BRIDGE) {
985
1137
  bridged = true
986
1138
  for (let k: i32 = i - gap; k < i; k++) {
987
1139
  if (
@@ -1006,7 +1158,7 @@ export class Screen {
1006
1158
  if (!bridged) {
1007
1159
  this.put(TERM_ESC)
1008
1160
  this.put(TERM_BRACKET)
1009
- if (cursorRow === row && gap > 0) {
1161
+ if (gap > 0) {
1010
1162
  if (gap > 1) {
1011
1163
  this.putDecimal(gap)
1012
1164
  }
@@ -1014,9 +1166,9 @@ export class Screen {
1014
1166
  } else if (row === 0 && col === 0) {
1015
1167
  this.put(TERM_FINAL_POSITION)
1016
1168
  } else {
1017
- this.putDecimal(row + 1)
1169
+ this.putDecimalAfter(row)
1018
1170
  this.put(TERM_SEMICOLON)
1019
- this.putDecimal(col + 1)
1171
+ this.putDecimalAfter(col)
1020
1172
  this.put(TERM_FINAL_POSITION)
1021
1173
  }
1022
1174
  }
@@ -1069,11 +1221,7 @@ export class Screen {
1069
1221
  sentFgs[i] = fg
1070
1222
  sentBgs[i] = bg
1071
1223
  sentAttrs[i] = at
1072
- cursorRow = row
1073
- cursorCol = col + 1
1074
- if (cursorCol >= w) {
1075
- cursorRow = -1
1076
- }
1224
+ cursor = col < w - 1 ? i + 1 : -1
1077
1225
  }
1078
1226
  if (
1079
1227
  styleAttrs !== TERM_STYLE_UNKNOWN &&
@@ -1117,11 +1265,20 @@ export class Canvas {
1117
1265
  * @param screen The screen it draws on, two pixels to a cell, one above the other.
1118
1266
  */
1119
1267
  constructor(screen: Screen) {
1268
+ // `resize` holds the screen's sides to 0–4,096; a caller that set them
1269
+ // past that gets a canvas of the held sides, as many pixels as fit.
1270
+ const w = termSide(screen.width)
1271
+ const rows = termFitRows(w, termSide(screen.height))
1120
1272
  this.screen = screen
1121
- this.width = screen.width
1122
- this.height = screen.height * 2
1123
- this.pixels = new Array<i32>(this.width * this.height)
1124
- this.pixels.fill(COLOR_DEFAULT)
1273
+ this.width = w
1274
+ this.height = rows * 2
1275
+ const cells = termCellCount(w, rows)
1276
+ // Two pixels a cell, in two passes: `2 * cells` is past `termCells`'s range.
1277
+ const pixels: i32[] = termCells(cells, COLOR_DEFAULT)
1278
+ for (let i: i32 = 0; i < cells; i++) {
1279
+ pixels.push(COLOR_DEFAULT)
1280
+ }
1281
+ this.pixels = pixels
1125
1282
  }
1126
1283
 
1127
1284
  /**
@@ -1150,7 +1307,12 @@ export class Canvas {
1150
1307
  if (x < 0 || y < 0 || x >= this.width || y >= this.height) {
1151
1308
  return COLOR_DEFAULT
1152
1309
  }
1153
- return this.pixels[y * this.width + x]
1310
+ const pixels: i32[] = this.pixels
1311
+ const at: i32 = termGridAt(x, y, this.width, this.height, toI32(pixels.length))
1312
+ if (at >= 0 && at < toI32(pixels.length)) {
1313
+ return pixels[at]
1314
+ }
1315
+ return COLOR_DEFAULT
1154
1316
  }
1155
1317
 
1156
1318
  /**
@@ -1164,7 +1326,11 @@ export class Canvas {
1164
1326
  if (x < 0 || y < 0 || x >= this.width || y >= this.height) {
1165
1327
  return
1166
1328
  }
1167
- this.pixels[y * this.width + x] = colour
1329
+ const pixels: i32[] = this.pixels
1330
+ const at: i32 = termGridAt(x, y, this.width, this.height, toI32(pixels.length))
1331
+ if (at >= 0 && at < toI32(pixels.length)) {
1332
+ pixels[at] = colour
1333
+ }
1168
1334
  this.paintCell(x, y >> 1)
1169
1335
  }
1170
1336
 
@@ -1180,14 +1346,32 @@ export class Canvas {
1180
1346
  fillRect(x: i32, y: i32, w: i32, h: i32, colour: i32): void {
1181
1347
  const left: i32 = x < 0 ? 0 : x
1182
1348
  const top: i32 = y < 0 ? 0 : y
1183
- const right: i32 = x + w > this.width ? this.width : x + w
1184
- const bottom: i32 = y + h > this.height ? this.height : y + h
1349
+ // The far edges in i64, where `x + w` cannot wrap, then held to 0 and the canvas's sides.
1350
+ const r: i64 = toI64(x) + toI64(w)
1351
+ const b: i64 = toI64(y) + toI64(h)
1352
+ let right: i32 = 0
1353
+ if (r > toI64(this.width)) {
1354
+ right = this.width
1355
+ } else if (r > toI64(0)) {
1356
+ right = toI32(r)
1357
+ }
1358
+ let bottom: i32 = 0
1359
+ if (b > toI64(this.height)) {
1360
+ bottom = this.height
1361
+ } else if (b > toI64(0)) {
1362
+ bottom = toI32(b)
1363
+ }
1364
+ const pixels: i32[] = this.pixels
1185
1365
  for (let py: i32 = top; py < bottom; py++) {
1186
1366
  for (let px: i32 = left; px < right; px++) {
1187
- this.pixels[py * this.width + px] = colour
1367
+ const at: i32 = termGridAt(px, py, this.width, this.height, toI32(pixels.length))
1368
+ if (at >= 0 && at < toI32(pixels.length)) {
1369
+ pixels[at] = colour
1370
+ }
1188
1371
  }
1189
1372
  }
1190
- for (let row: i32 = top >> 1; row < (bottom + 1) >> 1; row++) {
1373
+ const end: i32 = (bottom >> 1) + (bottom & 1)
1374
+ for (let row: i32 = top >> 1; row < end; row++) {
1191
1375
  for (let col: i32 = left; col < right; col++) {
1192
1376
  this.paintCell(col, row)
1193
1377
  }
@@ -1220,13 +1404,31 @@ export class Canvas {
1220
1404
  return
1221
1405
  }
1222
1406
  const twice: f64 = 2.0 * err
1407
+ // The walk never steps past an end, so a coordinate at its end stays.
1223
1408
  if (twice >= dy) {
1224
- err = err + dy
1225
- x = x + sx
1409
+ if (x < x1) {
1410
+ err = err + dy
1411
+ x = x + 1
1412
+ } else {
1413
+ // `~(~x + 1)` is `x - 1`; `~x < ~x1` (that is, `x1 < x`) proves `~x + 1` does not wrap.
1414
+ const nx: i32 = ~x
1415
+ if (nx < ~x1) {
1416
+ err = err + dy
1417
+ x = ~(nx + 1)
1418
+ }
1419
+ }
1226
1420
  }
1227
1421
  if (twice <= dx) {
1228
- err = err + dx
1229
- y = y + sy
1422
+ if (y < y1) {
1423
+ err = err + dx
1424
+ y = y + 1
1425
+ } else {
1426
+ const ny: i32 = ~y
1427
+ if (ny < ~y1) {
1428
+ err = err + dx
1429
+ y = ~(ny + 1)
1430
+ }
1431
+ }
1230
1432
  }
1231
1433
  // The walk only moves away from an edge it has passed, so no later point is on the canvas.
1232
1434
  if (
@@ -1256,22 +1458,39 @@ export class Canvas {
1256
1458
  let column: i32 = col
1257
1459
  let i: i32 = 0
1258
1460
  while (i < n) {
1259
- const top: i32 = this.pixel(column, row * 2)
1260
- const bg: i32 = top >= 0 ? top : this.pixel(column, row * 2 + 1)
1261
- this.screen.set(column, row, termCodePointAt(s, i, n), fg, bg, ATTR_NONE)
1262
- i = i + termCodePointUnits(s, i, n)
1263
- column = column + 1
1461
+ const step: i32 = termCodePointStep(s, i, n)
1462
+ i = termStepOn(i, step, n)
1463
+ const top: i32 = this.upper(column, row)
1464
+ const bg: i32 = top >= 0 ? top : this.lower(column, row)
1465
+ this.screen.set(column, row, step >> 3, fg, bg, ATTR_NONE)
1466
+ column = column < TERM_I32_MAX ? column + 1 : column
1264
1467
  }
1265
1468
  return column
1266
1469
  }
1267
1470
 
1471
+ /** The top pixel of cell `col`, `row`, or `COLOR_DEFAULT` off the canvas. */
1472
+ private upper(col: i32, row: i32): i32 {
1473
+ if (row < 0 || row > 1073741822) {
1474
+ return COLOR_DEFAULT
1475
+ }
1476
+ return this.pixel(col, row * 2)
1477
+ }
1478
+
1479
+ /** The bottom pixel of cell `col`, `row`, or `COLOR_DEFAULT` off the canvas. */
1480
+ private lower(col: i32, row: i32): i32 {
1481
+ if (row < 0 || row > 1073741822) {
1482
+ return COLOR_DEFAULT
1483
+ }
1484
+ return this.pixel(col, row * 2 + 1)
1485
+ }
1486
+
1268
1487
  /**
1269
1488
  * Redraw the screen cell at `col`, `row` from its two pixels.
1270
1489
  * @internal Called by `drawHalfBlocks` in term-pixels.ts.
1271
1490
  */
1272
1491
  paintCell(col: i32, row: i32): void {
1273
- const top: i32 = this.pixel(col, row * 2)
1274
- const bottom: i32 = this.pixel(col, row * 2 + 1)
1492
+ const top: i32 = this.upper(col, row)
1493
+ const bottom: i32 = this.lower(col, row)
1275
1494
  if (top < 0 && bottom < 0) {
1276
1495
  this.screen.set(col, row, TERM_SPACE, COLOR_DEFAULT, COLOR_DEFAULT, ATTR_NONE)
1277
1496
  } else if (top < 0) {
@@ -1530,15 +1749,13 @@ export class KeyDecoder {
1530
1749
 
1531
1750
  /** The held bytes followed by `bytes[0, count)`. */
1532
1751
  private merged(bytes: u8[], count: i32): u8[] {
1533
- const held: i32 = toI32(this.pending.length)
1534
- const n: i32 = termClamp(count, 0, toI32(bytes.length))
1535
- const work: u8[] = new Array<u8>(held + n)
1752
+ const work: u8[] = []
1536
1753
  const pending: u8[] = this.pending
1537
- for (let k: i32 = 0; k < toI32(pending.length) && k < toI32(work.length); k++) {
1538
- work[k] = pending[k]
1754
+ for (let k: i32 = 0; k < toI32(pending.length); k++) {
1755
+ work.push(pending[k])
1539
1756
  }
1540
- for (let k: i32 = 0; k < n && k < toI32(bytes.length); k++) {
1541
- work[held + k] = bytes[k]
1757
+ for (let k: i32 = 0; k < count && k < toI32(bytes.length); k++) {
1758
+ work.push(bytes[k])
1542
1759
  }
1543
1760
  return work
1544
1761
  }
@@ -1546,10 +1763,12 @@ export class KeyDecoder {
1546
1763
  /** Hold `work` from `used` on; when `restart` is set, the held bytes count as arriving at `nowMs`. */
1547
1764
  private keep(work: u8[], used: i32, restart: boolean, nowMs: f64): void {
1548
1765
  const rest: u8[] = []
1549
- for (let k: i32 = used; k < toI32(work.length); k++) {
1550
- if (!(k >= 0)) {
1551
- panic("nish/term: the key decoder used more bytes than it was given")
1552
- }
1766
+ // The decoders count `used` up from 0; were one ever below, every byte would be held, none lost.
1767
+ let from: i32 = 0
1768
+ if (used > 0) {
1769
+ from = used
1770
+ }
1771
+ for (let k: i32 = from; k < toI32(work.length); k++) {
1553
1772
  rest.push(work[k])
1554
1773
  }
1555
1774
  if (toI32(rest.length) > 0 && restart) {
@@ -1589,18 +1808,13 @@ export class KeyState {
1589
1808
  /** The latest send time of an answered query that `delivered` was given: everything the terminal generated before it has arrived. */
1590
1809
  watermarkMs: f64
1591
1810
  /**
1592
- * The keys down, each as `termKeyId` names it.
1811
+ * The keys down, each as `termKeyId` names it. A release replaces the array
1812
+ * rather than shifting it, so read it afresh rather than keep it.
1593
1813
  * @internal Used by `Terminal` in term-io.ts.
1594
1814
  */
1595
1815
  downKeys: i32[]
1596
- /** When each key down last pressed or repeated. */
1597
- private downSince: f64[]
1598
- /** Whether each key down has repeated. */
1599
- private downRepeated: boolean[]
1600
- /** The code each key down last came with, which its synthesized release carries. */
1601
- private downCodes: i32[]
1602
- /** The `MOD_` bits each key down last came with, which its synthesized release carries. */
1603
- private downMods: i32[]
1816
+ /** Each key down, in the order they went down, as `downKeys` lists their names. */
1817
+ private held: TermHeldKey[]
1604
1818
  /**
1605
1819
  * Whether releases are made up from silence; false from the first real release, or when the caller knows kitty flag 2 is on.
1606
1820
  */
@@ -1619,10 +1833,7 @@ export class KeyState {
1619
1833
  this.watermarked = false
1620
1834
  this.quitOnCtrlC = true
1621
1835
  this.downKeys = []
1622
- this.downSince = []
1623
- this.downRepeated = []
1624
- this.downCodes = []
1625
- this.downMods = []
1836
+ this.held = []
1626
1837
  }
1627
1838
 
1628
1839
  /**
@@ -1635,7 +1846,7 @@ export class KeyState {
1635
1846
  * @returns True from the key's press until its release, real or synthetic, or a loss of focus.
1636
1847
  */
1637
1848
  isDown(key: i32, code: i32): boolean {
1638
- return this.find(termKeyId(key, code)) >= 0
1849
+ return this.find(termKeyId(key, code)) !== null
1639
1850
  }
1640
1851
 
1641
1852
  /**
@@ -1659,9 +1870,8 @@ export class KeyState {
1659
1870
  for (let k: i32 = 0; k < toI32(events.length); k++) {
1660
1871
  const e: TermEvent = events[k]
1661
1872
  if (e.type === EVENT_FOCUS && !e.gained) {
1662
- const first: i32 = 0
1663
- while (toI32(this.downKeys.length) > 0) {
1664
- this.release(first, out)
1873
+ for (const h of this.held) {
1874
+ this.release(h, out)
1665
1875
  }
1666
1876
  } else if (e.type === EVENT_KEY && this.quitOnCtrlC && termIsCtrlC(e)) {
1667
1877
  if (e.action === ACTION_PRESS) {
@@ -1723,13 +1933,10 @@ export class KeyState {
1723
1933
  return out
1724
1934
  }
1725
1935
  const clock: f64 = this.watermarked ? this.watermarkMs : nowMs
1726
- let k: i32 = 0
1727
- while (k < toI32(this.downKeys.length)) {
1728
- const gap: f64 = this.downRepeated[k] ? this.releaseGapMs : this.firstRepeatMs
1729
- if (clock - this.downSince[k] >= gap && !termNamesKey(batch, this.downKeys[k])) {
1730
- this.release(k, out)
1731
- } else {
1732
- k = k + 1
1936
+ for (const h of this.held) {
1937
+ const gap: f64 = h.repeated ? this.releaseGapMs : this.firstRepeatMs
1938
+ if (clock - h.since >= gap && !termNamesKey(batch, h.id)) {
1939
+ this.release(h, out)
1733
1940
  }
1734
1941
  }
1735
1942
  return out
@@ -1737,77 +1944,93 @@ export class KeyState {
1737
1944
 
1738
1945
  /** Record key event `e` at `nowMs`; false for a release of a key not down, which `apply` drops. */
1739
1946
  private press(e: TermEvent, nowMs: f64): boolean {
1740
- const at: i32 = this.find(termKeyId(e.key, e.code))
1947
+ const id: i32 = termKeyId(e.key, e.code)
1948
+ const at: TermHeldKey | null = this.find(id)
1741
1949
  if (e.action === ACTION_RELEASE) {
1742
1950
  this.releasesAreSynthetic = false
1743
- if (at < 0) {
1951
+ if (at === null) {
1744
1952
  return false
1745
1953
  }
1746
1954
  this.remove(at)
1747
1955
  return true
1748
1956
  }
1749
1957
  const known: boolean = termFinite(nowMs)
1750
- if (at < 0) {
1958
+ if (at === null) {
1751
1959
  let since: f64 = known ? nowMs : toF64(0)
1752
1960
  if (!known && this.watermarked) {
1753
1961
  since = this.watermarkMs
1754
1962
  }
1755
- this.downKeys.push(termKeyId(e.key, e.code))
1756
- this.downSince.push(since)
1757
- this.downRepeated.push(false)
1758
- this.downCodes.push(e.code)
1759
- this.downMods.push(e.modifiers)
1963
+ this.held.push(new TermHeldKey(id, since, e.code, e.modifiers))
1964
+ this.downKeys.push(id)
1760
1965
  return true
1761
1966
  }
1762
1967
  if (known) {
1763
- this.downSince[at] = nowMs
1968
+ at.since = nowMs
1764
1969
  }
1765
- this.downRepeated[at] = true
1766
- this.downCodes[at] = e.code
1767
- this.downMods[at] = e.modifiers
1970
+ at.repeated = true
1971
+ at.code = e.code
1972
+ at.modifiers = e.modifiers
1768
1973
  if (this.releasesAreSynthetic) {
1769
1974
  e.action = ACTION_REPEAT
1770
1975
  }
1771
1976
  return true
1772
1977
  }
1773
1978
 
1774
- /** Let key `at` go, appending its release to `out`. */
1775
- private release(at: i32, out: TermEvent[]): void {
1776
- const id: i32 = this.downKeys[at]
1979
+ /** Let key `h` go, appending its release to `out`. */
1980
+ private release(h: TermHeldKey, out: TermEvent[]): void {
1777
1981
  const e: TermEvent = new TermEvent(EVENT_KEY)
1778
- e.key = id >> 21
1779
- e.code = this.downCodes[at]
1780
- e.modifiers = this.downMods[at]
1982
+ e.key = h.id >> 21
1983
+ e.code = h.code
1984
+ e.modifiers = h.modifiers
1781
1985
  e.action = ACTION_RELEASE
1782
1986
  out.push(e)
1783
- this.remove(at)
1987
+ this.remove(h)
1784
1988
  }
1785
1989
 
1786
- /** Where key `id` is in `downKeys`, or -1. */
1787
- private find(id: i32): i32 {
1788
- for (let k: i32 = 0; k < toI32(this.downKeys.length); k++) {
1789
- if (this.downKeys[k] === id) {
1790
- return k
1990
+ /** The key named `id` among those down, or null. */
1991
+ private find(id: i32): TermHeldKey | null {
1992
+ for (const h of this.held) {
1993
+ if (h.id === id) {
1994
+ return h
1791
1995
  }
1792
1996
  }
1793
- return -1
1997
+ return null
1794
1998
  }
1795
1999
 
1796
- /** Drop key `at`, keeping the others in order. */
1797
- private remove(at: i32): void {
1798
- const last: i32 = toI32(this.downKeys.length) - 1
1799
- for (let k: i32 = at; k < last; k++) {
1800
- this.downKeys[k] = this.downKeys[k + 1]
1801
- this.downSince[k] = this.downSince[k + 1]
1802
- this.downRepeated[k] = this.downRepeated[k + 1]
1803
- this.downCodes[k] = this.downCodes[k + 1]
1804
- this.downMods[k] = this.downMods[k + 1]
2000
+ /** Drop key `gone`, keeping the others in order, and `downKeys` with them. */
2001
+ private remove(gone: TermHeldKey): void {
2002
+ const held: TermHeldKey[] = []
2003
+ const ids: i32[] = []
2004
+ for (const h of this.held) {
2005
+ if (h !== gone) {
2006
+ held.push(h)
2007
+ ids.push(h.id)
2008
+ }
1805
2009
  }
1806
- this.downKeys.pop()
1807
- this.downSince.pop()
1808
- this.downRepeated.pop()
1809
- this.downCodes.pop()
1810
- this.downMods.pop()
2010
+ this.held = held
2011
+ this.downKeys = ids
2012
+ }
2013
+ }
2014
+
2015
+ /** A key `KeyState` holds down: its name, as `termKeyId` makes it, and what its synthesized release carries. */
2016
+ class TermHeldKey {
2017
+ /** When the key last pressed or repeated. */
2018
+ since: f64
2019
+ /** The key's name, as `termKeyId` makes it. */
2020
+ id: i32
2021
+ /** The code the key last came with. */
2022
+ code: i32
2023
+ /** The `MOD_` bits the key last came with. */
2024
+ modifiers: i32
2025
+ /** Whether the key has repeated. */
2026
+ repeated: boolean
2027
+
2028
+ constructor(id: i32, since: f64, code: i32, modifiers: i32) {
2029
+ this.id = id
2030
+ this.since = since
2031
+ this.repeated = false
2032
+ this.code = code
2033
+ this.modifiers = modifiers
1811
2034
  }
1812
2035
  }
1813
2036
 
@@ -1942,13 +2165,12 @@ const termAsciiKind = (b: i32): i32 => {
1942
2165
  */
1943
2166
  const termDecodeKeys = (bytes: u8[], last: boolean, events: KeyEvent[]): i32 => {
1944
2167
  let i: i32 = 0
1945
- while (i < toI32(bytes.length)) {
1946
- if (!(i >= 0)) {
1947
- panic("nish/term: the key decoder stepped back")
1948
- }
2168
+ // `i` only moves forward, a byte at a time or past what `bytes` holds, so it stays from 0 to the length.
2169
+ while (i >= 0 && i < toI32(bytes.length)) {
1949
2170
  const b: i32 = toI32(bytes[i])
1950
2171
  if (b === TERM_ESC) {
1951
- if (i + 1 >= toI32(bytes.length)) {
2172
+ const second: i32 = i + 1
2173
+ if (second >= toI32(bytes.length)) {
1952
2174
  if (!last) {
1953
2175
  return i
1954
2176
  }
@@ -1956,16 +2178,24 @@ const termDecodeKeys = (bytes: u8[], last: boolean, events: KeyEvent[]): i32 =>
1956
2178
  i = i + 1
1957
2179
  continue
1958
2180
  }
1959
- const next: i32 = toI32(bytes[i + 1])
2181
+ const next: i32 = toI32(bytes[second])
1960
2182
  if (next === 91) {
1961
- let j: i32 = i + 2
1962
- const stop: i32 = j + TERM_MAX_CSI_PARAMS + 1
1963
- while (j < toI32(bytes.length) && j < stop && toI32(bytes[j]) >= 32 && toI32(bytes[j]) < 64) {
2183
+ let j: i32 = second + 1
2184
+ let run: i32 = 0
2185
+ // 33 is `TERM_MAX_CSI_PARAMS + 1`, spelled out so the bounds walk reads it.
2186
+ while (
2187
+ run < 33 &&
2188
+ j >= 0 &&
2189
+ j < toI32(bytes.length) &&
2190
+ toI32(bytes[j]) >= 32 &&
2191
+ toI32(bytes[j]) < 64
2192
+ ) {
1964
2193
  j = j + 1
2194
+ run = run + 1
1965
2195
  }
1966
2196
  // A run past the cap is no key a terminal sends: give the ESC up now
1967
2197
  // rather than hold, and copy on every `feed`, what follows.
1968
- if (j === stop) {
2198
+ if (run > TERM_MAX_CSI_PARAMS) {
1969
2199
  events.push(new KeyEvent(KEY_ESCAPE, b))
1970
2200
  i = i + 1
1971
2201
  continue
@@ -1989,7 +2219,8 @@ const termDecodeKeys = (bytes: u8[], last: boolean, events: KeyEvent[]): i32 =>
1989
2219
  continue
1990
2220
  }
1991
2221
  if (next === 79) {
1992
- if (i + 2 >= toI32(bytes.length)) {
2222
+ const at: i32 = second + 1
2223
+ if (at >= toI32(bytes.length)) {
1993
2224
  if (!last) {
1994
2225
  return i
1995
2226
  }
@@ -1997,10 +2228,10 @@ const termDecodeKeys = (bytes: u8[], last: boolean, events: KeyEvent[]): i32 =>
1997
2228
  i = i + 1
1998
2229
  continue
1999
2230
  }
2000
- const final: i32 = toI32(bytes[i + 2])
2231
+ const final: i32 = toI32(bytes[at])
2001
2232
  if (final >= 64 && final < 127) {
2002
2233
  events.push(new KeyEvent(termArrowKind(final), final))
2003
- i = i + 3
2234
+ i = at + 1
2004
2235
  } else {
2005
2236
  events.push(new KeyEvent(KEY_ESCAPE, b))
2006
2237
  i = i + 1
@@ -2021,7 +2252,11 @@ const termDecodeKeys = (bytes: u8[], last: boolean, events: KeyEvent[]): i32 =>
2021
2252
  return i
2022
2253
  }
2023
2254
  events.push(new KeyEvent(KEY_CHAR, char >> 3))
2024
- i = i + (char & 7)
2255
+ // `termUtf8At` used `char & 7` bytes, all of them in `bytes`.
2256
+ const used: i32 = char & 7
2257
+ for (let k: i32 = 0; k < used && i < toI32(bytes.length); k++) {
2258
+ i = i + 1
2259
+ }
2025
2260
  }
2026
2261
  return toI32(bytes.length)
2027
2262
  }
@@ -2042,26 +2277,34 @@ const termUtf8At = (bytes: u8[], i: i32, last: boolean): i32 => {
2042
2277
  return (TERM_REPLACEMENT << 3) | 1
2043
2278
  }
2044
2279
  let cp: i32 = termLeadBits(b, width)
2045
- let good: i32 = 0
2046
- let stopped: boolean = false
2047
- for (let k: i32 = 1; k < width && !stopped; k++) {
2048
- if (i + k >= toI32(bytes.length)) {
2049
- stopped = true
2050
- } else {
2051
- const c: i32 = toI32(bytes[i + k])
2052
- if (c < 128 || c >= 192) {
2053
- stopped = true
2054
- } else {
2055
- cp = (cp << 6) | (c & 63)
2056
- good = good + 1
2057
- }
2280
+ let left: i32 = 0
2281
+ if (width > 1) {
2282
+ left = width - 1
2283
+ }
2284
+ // The lead byte and the good ones after it; a lead asks for at most 3 more.
2285
+ let used: i32 = 1
2286
+ let at: i32 = i
2287
+ let ended: boolean = false
2288
+ while (left > 0 && used < 4 && at >= 0 && at < toI32(bytes.length)) {
2289
+ const next: i32 = at + 1
2290
+ if (next >= toI32(bytes.length)) {
2291
+ ended = true
2292
+ break
2058
2293
  }
2294
+ const c: i32 = toI32(bytes[next])
2295
+ if (c < 128 || c >= 192) {
2296
+ break
2297
+ }
2298
+ cp = (cp << 6) | (c & 63)
2299
+ used = used + 1
2300
+ left = left - 1
2301
+ at = next
2059
2302
  }
2060
- if (good < width - 1) {
2061
- if (!last && i + 1 + good >= toI32(bytes.length)) {
2303
+ if (left > 0) {
2304
+ if (!last && ended) {
2062
2305
  return -1
2063
2306
  }
2064
- return (TERM_REPLACEMENT << 3) | (1 + good)
2307
+ return (TERM_REPLACEMENT << 3) | used
2065
2308
  }
2066
2309
  let least: i32 = 65536
2067
2310
  if (width === 2) {
@@ -2094,6 +2337,21 @@ const termAction = (raw: i32): i32 => {
2094
2337
  return raw === 3 ? ACTION_RELEASE : ACTION_PRESS
2095
2338
  }
2096
2339
 
2340
+ /**
2341
+ * `value`, a parameter being read (-1 before its first digit), with the digit
2342
+ * byte `c` appended. Past eight digits a number is no parameter a terminal
2343
+ * sends; it stops growing.
2344
+ */
2345
+ const termAddDigit = (value: i32, c: integer<0, 255>): i32 => {
2346
+ if (value < 0) {
2347
+ return c - TERM_DIGIT_0
2348
+ }
2349
+ if (value < 10000000) {
2350
+ return value * 10 + (c - TERM_DIGIT_0)
2351
+ }
2352
+ return value
2353
+ }
2354
+
2097
2355
  /**
2098
2356
  * Field `field`, sub-field `sub` of the parameters `bytes[from, to)`, where
2099
2357
  * `;` separates fields and `:` sub-fields (ECMA-48 § 5.4.2; the kitty
@@ -2103,20 +2361,27 @@ const termCsiField = (bytes: u8[], from: i32, to: i32, field: i32, sub: i32): i3
2103
2361
  let f: i32 = 0
2104
2362
  let s: i32 = 0
2105
2363
  let value: i32 = -1
2106
- for (let k: i32 = from; k < to && k < toI32(bytes.length); k++) {
2364
+ let start: i32 = from
2365
+ if (start < 0) {
2366
+ start = 0
2367
+ }
2368
+ for (let k: i32 = start; k < to && k < toI32(bytes.length); k++) {
2107
2369
  const c: i32 = toI32(bytes[k])
2108
2370
  if (c === TERM_SEMICOLON) {
2371
+ // Past the field asked for, nothing later can change the answer.
2372
+ if (f >= field) {
2373
+ return value
2374
+ }
2109
2375
  f = f + 1
2110
2376
  s = 0
2111
2377
  } else if (c === 58) {
2112
- s = s + 1
2113
- } else if (c >= TERM_DIGIT_0 && c < TERM_DIGIT_0 + 10 && f === field && s === sub) {
2114
- // Past eight digits a number is no parameter a terminal sends; it stops growing.
2115
- if (value < 0) {
2116
- value = c - TERM_DIGIT_0
2117
- } else if (value < 10000000) {
2118
- value = value * 10 + (c - TERM_DIGIT_0)
2378
+ if (s < sub) {
2379
+ s = s + 1
2380
+ } else if (f === field) {
2381
+ return value
2119
2382
  }
2383
+ } else if (c >= TERM_DIGIT_0 && c < TERM_DIGIT_0 + 10 && f === field && s === sub) {
2384
+ value = termAddDigit(value, c)
2120
2385
  }
2121
2386
  }
2122
2387
  return value
@@ -2128,23 +2393,75 @@ const termCsiParams = (bytes: u8[], from: i32, to: i32): i32[] => {
2128
2393
  if (from >= to) {
2129
2394
  return params
2130
2395
  }
2131
- let fields: i32 = 1
2132
- for (let k: i32 = from; k < to && k < toI32(bytes.length); k++) {
2133
- if (toI32(bytes[k]) === TERM_SEMICOLON) {
2134
- fields = fields + 1
2135
- }
2396
+ // `value` is -1 until a digit of the field's first sub-field arrives; `first` is false past its `:`.
2397
+ let value: i32 = -1
2398
+ let first: boolean = true
2399
+ let start: i32 = from
2400
+ if (start < 0) {
2401
+ start = 0
2136
2402
  }
2137
- for (let f: i32 = 0; f < fields; f++) {
2138
- const v: i32 = termCsiField(bytes, from, to, f, 0)
2139
- params.push(v < 0 ? 0 : v)
2403
+ for (let k: i32 = start; k < to && k < toI32(bytes.length); k++) {
2404
+ const c: i32 = toI32(bytes[k])
2405
+ if (c === TERM_SEMICOLON) {
2406
+ params.push(value < 0 ? 0 : value)
2407
+ value = -1
2408
+ first = true
2409
+ } else if (c === 58) {
2410
+ first = false
2411
+ } else if (first && c >= TERM_DIGIT_0 && c < TERM_DIGIT_0 + 10) {
2412
+ value = termAddDigit(value, c)
2413
+ }
2140
2414
  }
2415
+ params.push(value < 0 ? 0 : value)
2141
2416
  return params
2142
2417
  }
2143
2418
 
2419
+ /**
2420
+ * The text of a kitty key report: the code points of the third field of the
2421
+ * parameters `bytes[from, to)`, one per `:` sub-field, up to the first omitted
2422
+ * one (kitty keyboard protocol, "Text as code points").
2423
+ */
2424
+ const termKittyText = (bytes: u8[], from: i32, to: i32): string => {
2425
+ const text: u8[] = []
2426
+ let f: i32 = 0
2427
+ let value: i32 = -1
2428
+ let stopped: boolean = false
2429
+ let start: i32 = from
2430
+ if (start < 0) {
2431
+ start = 0
2432
+ }
2433
+ for (let k: i32 = start; k < to && k < toI32(bytes.length); k++) {
2434
+ const c: i32 = toI32(bytes[k])
2435
+ if (c === TERM_SEMICOLON) {
2436
+ if (f >= 2) {
2437
+ break
2438
+ }
2439
+ f = f + 1
2440
+ } else if (c === 58 && f === 2) {
2441
+ if (value < 0) {
2442
+ stopped = true
2443
+ break
2444
+ }
2445
+ termPushUtf8(text, value)
2446
+ value = -1
2447
+ } else if (c >= TERM_DIGIT_0 && c < TERM_DIGIT_0 + 10 && f === 2) {
2448
+ value = termAddDigit(value, c)
2449
+ }
2450
+ }
2451
+ if (!stopped && value >= 0) {
2452
+ termPushUtf8(text, value)
2453
+ }
2454
+ return termBytesText(text, toI32(text.length))
2455
+ }
2456
+
2144
2457
  /** The string of UTF-8 `bytes[from, to)`, as `termBytesText` makes one. */
2145
2458
  const termBytesRange = (bytes: u8[], from: i32, to: i32): string => {
2146
2459
  const part: u8[] = []
2147
- for (let k: i32 = from; k < to && k < toI32(bytes.length); k++) {
2460
+ let start: i32 = from
2461
+ if (start < 0) {
2462
+ start = 0
2463
+ }
2464
+ for (let k: i32 = start; k < to && k < toI32(bytes.length); k++) {
2148
2465
  part.push(bytes[k])
2149
2466
  }
2150
2467
  return termBytesText(part, toI32(part.length))
@@ -2229,8 +2546,11 @@ const termTildeKind = (n: i32): i32 => {
2229
2546
  if (n >= 17 && n <= 21) {
2230
2547
  return KEY_F6 + (n - 17)
2231
2548
  }
2232
- if (n === 23 || n === 24) {
2233
- return KEY_F11 + (n - 23)
2549
+ if (n === 23) {
2550
+ return KEY_F11
2551
+ }
2552
+ if (n === 24) {
2553
+ return KEY_F12
2234
2554
  }
2235
2555
  return KEY_UNKNOWN
2236
2556
  }
@@ -2307,18 +2627,26 @@ const termPasteEndByte = (k: i32): i32 => {
2307
2627
  const termDecodePaste = (d: KeyDecoder, bytes: u8[], i: i32, last: boolean, events: TermEvent[]): i32 => {
2308
2628
  const n: i32 = toI32(bytes.length)
2309
2629
  let k: i32 = i
2630
+ // Where decoding resumes past a whole terminator, or -1 while there is none.
2631
+ let resume: i32 = -1
2310
2632
  while (k >= 0 && k < toI32(bytes.length)) {
2311
2633
  let m: i32 = 0
2312
- while (m < 6 && k + m < n && toI32(bytes[k + m]) === termPasteEndByte(m)) {
2634
+ let at: i32 = k
2635
+ while (m < 6 && at >= 0 && at < toI32(bytes.length) && toI32(bytes[at]) === termPasteEndByte(m)) {
2313
2636
  m = m + 1
2637
+ at = at + 1
2314
2638
  }
2315
- if (m === 6 || (m > 0 && k + m === n && !last)) {
2639
+ if (m === 6) {
2640
+ resume = at
2641
+ break
2642
+ }
2643
+ if (m > 0 && at >= n && !last) {
2316
2644
  break
2317
2645
  }
2318
2646
  d.pasteBytes.push(bytes[k])
2319
2647
  k = k + 1
2320
2648
  }
2321
- if (k >= n || k + 6 > n) {
2649
+ if (resume < 0) {
2322
2650
  return k
2323
2651
  }
2324
2652
  const e: TermEvent = new TermEvent(EVENT_PASTE)
@@ -2326,7 +2654,15 @@ const termDecodePaste = (d: KeyDecoder, bytes: u8[], i: i32, last: boolean, even
2326
2654
  events.push(e)
2327
2655
  d.pasting = false
2328
2656
  d.pasteBytes = []
2329
- return k + 6
2657
+ return resume
2658
+ }
2659
+
2660
+ /** A coordinate `v` that counts from 1, made to count from 0; an omitted or 0 one is 0. */
2661
+ const termFromOne = (v: i32): i32 => {
2662
+ if (v > 0) {
2663
+ return v - 1
2664
+ }
2665
+ return 0
2330
2666
  }
2331
2667
 
2332
2668
  /**
@@ -2338,8 +2674,8 @@ const termDecodePaste = (d: KeyDecoder, bytes: u8[], i: i32, last: boolean, even
2338
2674
  */
2339
2675
  const termMouseEvent = (d: KeyDecoder, bytes: u8[], from: i32, to: i32, final: i32): TermEvent => {
2340
2676
  const b: i32 = termCsiField(bytes, from, to, 0, 0)
2341
- const x: i32 = termClamp(termCsiField(bytes, from, to, 1, 0) - 1, 0, 2147483646)
2342
- const y: i32 = termClamp(termCsiField(bytes, from, to, 2, 0) - 1, 0, 2147483646)
2677
+ const x: i32 = termFromOne(termCsiField(bytes, from, to, 1, 0))
2678
+ const y: i32 = termFromOne(termCsiField(bytes, from, to, 2, 0))
2343
2679
  const e: TermEvent = new TermEvent(EVENT_MOUSE)
2344
2680
  const bits: i32 = b < 0 ? 3 : b
2345
2681
  const none: i32 = 0
@@ -2367,8 +2703,16 @@ const termMouseEvent = (d: KeyDecoder, bytes: u8[], from: i32, to: i32, final: i
2367
2703
  }
2368
2704
  e.px = x
2369
2705
  e.py = y
2370
- e.x = d.cellWidthPx > 0 ? (x / d.cellWidthPx) | 0 : -1
2371
- e.y = d.cellHeightPx > 0 ? (y / d.cellHeightPx) | 0 : -1
2706
+ const w: i32 = d.cellWidthPx
2707
+ const h: i32 = d.cellHeightPx
2708
+ e.x = -1
2709
+ e.y = -1
2710
+ if (w > 0) {
2711
+ e.x = (x / w) | 0
2712
+ }
2713
+ if (h > 0) {
2714
+ e.y = (y / h) | 0
2715
+ }
2372
2716
  return e
2373
2717
  }
2374
2718
 
@@ -2419,8 +2763,9 @@ const termCsiEvent = (
2419
2763
  // but a final no key uses (xterm ctlseqs, "Functions using CSI").
2420
2764
  const cpr: boolean = final === 82 && d.cprOutstanding > 0
2421
2765
  if (prefix !== 0 || intermediate !== 0 || final === 110 || final === 116 || cpr) {
2422
- if (cpr) {
2423
- d.cprOutstanding = d.cprOutstanding - 1
2766
+ const outstanding: i32 = d.cprOutstanding
2767
+ if (cpr && outstanding > 0) {
2768
+ d.cprOutstanding = outstanding - 1
2424
2769
  }
2425
2770
  events.push(termReplyEvent(TERM_BRACKET, prefix, termCsiParams(bytes, from, to), intermediate, final, ""))
2426
2771
  return
@@ -2445,11 +2790,7 @@ const termCsiEvent = (
2445
2790
  const code: i32 = final === 117 ? first : termCsiField(bytes, from, to, 2, 0)
2446
2791
  const e: TermEvent = termKeyEvent(termKittyKind(code), code < 0 ? final : code, mods, action)
2447
2792
  if (final === 117) {
2448
- const text: u8[] = []
2449
- for (let s: i32 = 0; termCsiField(bytes, from, to, 2, s) >= 0; s++) {
2450
- termPushUtf8(text, termCsiField(bytes, from, to, 2, s))
2451
- }
2452
- e.text = termBytesText(text, toI32(text.length))
2793
+ e.text = termKittyText(bytes, from, to)
2453
2794
  }
2454
2795
  events.push(e)
2455
2796
  return
@@ -2468,107 +2809,125 @@ const termCsiEvent = (
2468
2809
  }
2469
2810
 
2470
2811
  /**
2471
- * Decode the control sequence at `bytes[i]` (`ESC [`) into `events` and answer
2472
- * where decoding resumes, or -1 when it is unfinished at the end and `last`
2473
- * is not set. Parameter and intermediate bytes run 32–63 and a final byte
2474
- * 64–126 (ECMA-48 § 5.4); a sequence broken off by another byte is an ESC
2475
- * key, and the bytes after it keys of their own, as `feed` has it.
2812
+ * Decode the control sequence whose `[` is `bytes[open]`, just after its ESC,
2813
+ * into `events` and answer where decoding resumes, or -1 when it is
2814
+ * unfinished at the end and `last` is not set. Parameter and intermediate
2815
+ * bytes run 32–63 and a final byte 64–126 (ECMA-48 § 5.4); a sequence broken
2816
+ * off by another byte is an ESC key, and the bytes after it keys of their
2817
+ * own, as `feed` has it.
2476
2818
  */
2477
- const termDecodeCsi = (d: KeyDecoder, bytes: u8[], i: i32, last: boolean, events: TermEvent[]): i32 => {
2819
+ const termDecodeCsi = (d: KeyDecoder, bytes: u8[], open: i32, last: boolean, events: TermEvent[]): i32 => {
2478
2820
  const n: i32 = toI32(bytes.length)
2479
- let j: i32 = i + 2
2480
- while (j < n && toI32(bytes[j]) >= 32 && toI32(bytes[j]) < 64) {
2821
+ // `j` steps past the `[` (91, no parameter byte) and then the parameter run.
2822
+ let j: i32 = open
2823
+ while (j >= 0 && j < n && (j === open || (toI32(bytes[j]) >= 32 && toI32(bytes[j]) < 64))) {
2481
2824
  j = j + 1
2482
2825
  }
2483
- if (j >= n && !last) {
2484
- return -1
2826
+ if (j < 0 || j >= toI32(bytes.length)) {
2827
+ if (!last) {
2828
+ return -1
2829
+ }
2830
+ events.push(termKeyEvent(KEY_ESCAPE, TERM_ESC, 0, ACTION_PRESS))
2831
+ return open
2485
2832
  }
2486
- const final: i32 = j < n ? toI32(bytes[j]) : 0
2833
+ const final: i32 = toI32(bytes[j])
2487
2834
  if (!(final >= 64 && final < 127)) {
2488
2835
  events.push(termKeyEvent(KEY_ESCAPE, TERM_ESC, 0, ACTION_PRESS))
2489
- return i + 1
2836
+ return open
2837
+ }
2838
+ let from: i32 = open
2839
+ if (from < j) {
2840
+ from = from + 1
2490
2841
  }
2491
2842
  // The Linux console's F1–F5, `ESC [ [ A` to `ESC [ [ E` (console_codes(4)).
2492
- if (final === TERM_BRACKET && j === i + 2) {
2493
- if (j + 1 >= n && !last) {
2843
+ if (final === TERM_BRACKET && from === j) {
2844
+ const key: i32 = j + 1
2845
+ if (key >= n && !last) {
2494
2846
  return -1
2495
2847
  }
2496
- const f: i32 = j + 1 < n ? toI32(bytes[j + 1]) : 0
2497
- if (f >= 65 && f <= 69) {
2848
+ const f: i32 = termByte(bytes, key)
2849
+ if (key < n && f >= 65 && f <= 69) {
2498
2850
  events.push(termKeyEvent(KEY_F1 + (f - 65), f, 0, ACTION_PRESS))
2499
- return j + 2
2851
+ return key + 1
2500
2852
  }
2501
2853
  }
2502
- let from: i32 = i + 2
2503
2854
  let prefix: i32 = 0
2504
- if (from < j && toI32(bytes[from]) >= 60) {
2505
- prefix = toI32(bytes[from])
2855
+ if (from < j && termByte(bytes, from) >= 60) {
2856
+ prefix = termByte(bytes, from)
2506
2857
  from = from + 1
2507
2858
  }
2508
2859
  let to: i32 = from
2509
2860
  while (to < j && termByte(bytes, to) >= TERM_DIGIT_0) {
2510
2861
  to = to + 1
2511
2862
  }
2512
- termCsiEvent(d, bytes, from, to, prefix, to < j ? toI32(bytes[j - 1]) : 0, final, events)
2863
+ let intermediate: i32 = 0
2864
+ if (to < j) {
2865
+ const back: i32 = j - 1
2866
+ intermediate = termByte(bytes, back)
2867
+ }
2868
+ termCsiEvent(d, bytes, from, to, prefix, intermediate, final, events)
2513
2869
  return j + 1
2514
2870
  }
2515
2871
 
2516
2872
  /**
2517
- * Decode the control string at `bytes[i]` — DCS `ESC P`, APC `ESC _`, OSC
2518
- * `ESC ]`, PM `ESC ^` or SOS `ESC X` — into one `EVENT_REPLY`, and answer
2519
- * where decoding resumes. It ends at ST, `ESC \`, or BEL (ECMA-48 § 8.3.143;
2520
- * xterm ctlseqs, "Operating System Commands"). Unfinished at the end it is -1
2521
- * unless `last`, when it is dropped; an ESC inside that starts no ST breaks
2522
- * it off, and decoding resumes at that ESC. A DCS reads as a CSI does then
2523
- * carries its data in `text`: XTVERSION `ESC P > | name ST`, DECRQSS
2524
- * `ESC P 1 $ r … ST`. An APC's first byte is its `reply` (kitty graphics
2525
- * `ESC _ G … ST`); an OSC's number is its one param and the rest its text.
2873
+ * Decode the control string whose introducer is `bytes[open]`, just after its
2874
+ * ESC — DCS `P`, APC `_`, OSC `]`, PM `^` or SOS `X` — into one `EVENT_REPLY`,
2875
+ * and answer where decoding resumes. It ends at ST, `ESC \`, or BEL (ECMA-48
2876
+ * § 8.3.143; xterm ctlseqs, "Operating System Commands"). Unfinished at the
2877
+ * end it is -1 unless `last`, when it is dropped; an ESC inside that starts
2878
+ * no ST breaks it off, and decoding resumes at that ESC. A DCS reads as a CSI
2879
+ * does then carries its data in `text`: XTVERSION `ESC P > | name ST`,
2880
+ * DECRQSS `ESC P 1 $ r … ST`. An APC's first byte is its `reply` (kitty
2881
+ * graphics `ESC _ G … ST`); an OSC's number is its one param and the rest its
2882
+ * text.
2526
2883
  */
2527
- const termDecodeString = (bytes: u8[], i: i32, last: boolean, events: TermEvent[]): i32 => {
2884
+ const termDecodeString = (bytes: u8[], open: i32, last: boolean, events: TermEvent[]): i32 => {
2528
2885
  const n: i32 = toI32(bytes.length)
2529
- const introducer: i32 = toI32(bytes[i + 1])
2530
- let end: i32 = i + 2
2531
- while (end < n && toI32(bytes[end]) !== 7 && toI32(bytes[end]) !== TERM_ESC) {
2886
+ const introducer: i32 = termByte(bytes, open)
2887
+ // The introducer is neither BEL nor ESC, so the walk starts on it.
2888
+ let end: i32 = open
2889
+ while (end >= 0 && end < toI32(bytes.length) && toI32(bytes[end]) !== 7 && toI32(bytes[end]) !== TERM_ESC) {
2532
2890
  end = end + 1
2533
2891
  }
2534
- if (end + (end < n && toI32(bytes[end]) === TERM_ESC ? 1 : 0) >= n) {
2892
+ if (end < 0 || end >= toI32(bytes.length)) {
2535
2893
  return last ? n : -1
2536
2894
  }
2537
2895
  let resume: i32 = end + 1
2538
2896
  if (toI32(bytes[end]) === TERM_ESC) {
2539
- if (toI32(bytes[end + 1]) !== 92) {
2897
+ const after: i32 = end + 1
2898
+ if (after >= n) {
2899
+ return last ? n : -1
2900
+ }
2901
+ if (termByte(bytes, after) !== 92) {
2540
2902
  return end
2541
2903
  }
2542
- resume = end + 2
2904
+ resume = after + 1
2905
+ }
2906
+ let start: i32 = open
2907
+ if (start < end) {
2908
+ start = start + 1
2543
2909
  }
2544
- const start: i32 = i + 2
2545
2910
  if (introducer === 95) {
2546
- events.push(
2547
- termReplyEvent(
2548
- introducer,
2549
- 0,
2550
- [],
2551
- 0,
2552
- start < end ? toI32(bytes[start]) : 0,
2553
- termBytesRange(bytes, start + 1, end)
2554
- )
2555
- )
2911
+ let reply: i32 = 0
2912
+ let text: i32 = start
2913
+ if (start < end) {
2914
+ reply = termByte(bytes, start)
2915
+ text = start + 1
2916
+ }
2917
+ events.push(termReplyEvent(introducer, 0, [], 0, reply, termBytesRange(bytes, text, end)))
2556
2918
  return resume
2557
2919
  }
2558
2920
  if (introducer === 93) {
2559
2921
  let semi: i32 = start
2560
- while (semi < end && toI32(bytes[semi]) !== TERM_SEMICOLON) {
2922
+ while (semi < end && termByte(bytes, semi) !== TERM_SEMICOLON) {
2561
2923
  semi = semi + 1
2562
2924
  }
2925
+ let text: i32 = semi
2926
+ if (semi < end) {
2927
+ text = semi + 1
2928
+ }
2563
2929
  events.push(
2564
- termReplyEvent(
2565
- introducer,
2566
- 0,
2567
- termCsiParams(bytes, start, semi),
2568
- 0,
2569
- 0,
2570
- termBytesRange(bytes, semi + 1, end)
2571
- )
2930
+ termReplyEvent(introducer, 0, termCsiParams(bytes, start, semi), 0, 0, termBytesRange(bytes, text, end))
2572
2931
  )
2573
2932
  return resume
2574
2933
  }
@@ -2583,15 +2942,24 @@ const termDecodeString = (bytes: u8[], i: i32, last: boolean, events: TermEvent[
2583
2942
  from = from + 1
2584
2943
  }
2585
2944
  let to: i32 = from
2586
- while (to < end && toI32(bytes[to]) >= TERM_DIGIT_0 && toI32(bytes[to]) < 64) {
2945
+ while (to < end && termByte(bytes, to) >= TERM_DIGIT_0 && termByte(bytes, to) < 64) {
2587
2946
  to = to + 1
2588
2947
  }
2589
2948
  let f: i32 = to
2590
- while (f < end && toI32(bytes[f]) >= 32 && toI32(bytes[f]) < TERM_DIGIT_0) {
2949
+ while (f < end && termByte(bytes, f) >= 32 && termByte(bytes, f) < TERM_DIGIT_0) {
2591
2950
  f = f + 1
2592
2951
  }
2593
- const intermediate: i32 = f > to ? toI32(bytes[f - 1]) : 0
2594
- const final: i32 = f < end ? toI32(bytes[f]) : 0
2952
+ let intermediate: i32 = 0
2953
+ if (f > to) {
2954
+ const back: i32 = f - 1
2955
+ intermediate = termByte(bytes, back)
2956
+ }
2957
+ let final: i32 = 0
2958
+ let text: i32 = f
2959
+ if (f < end) {
2960
+ final = toI32(bytes[f])
2961
+ text = f + 1
2962
+ }
2595
2963
  events.push(
2596
2964
  termReplyEvent(
2597
2965
  introducer,
@@ -2599,7 +2967,7 @@ const termDecodeString = (bytes: u8[], i: i32, last: boolean, events: TermEvent[
2599
2967
  termCsiParams(bytes, from, to),
2600
2968
  intermediate,
2601
2969
  final,
2602
- termBytesRange(bytes, f + 1, end)
2970
+ termBytesRange(bytes, text, end)
2603
2971
  )
2604
2972
  )
2605
2973
  return resume
@@ -2620,47 +2988,49 @@ const termOpensString = (b: i32): boolean => b === 80 || b === 88 || b === 93 ||
2620
2988
  const termDecodeEvents = (d: KeyDecoder, bytes: u8[], last: boolean, events: TermEvent[]): i32 => {
2621
2989
  const n: i32 = toI32(bytes.length)
2622
2990
  let i: i32 = 0
2623
- while (i < toI32(bytes.length)) {
2624
- if (!(i >= 0)) {
2625
- panic("nish/term: the event decoder stepped back")
2626
- }
2627
- let next: i32 = i + 1
2991
+ // Every step answers a `next` past `i`, so `i` only moves forward from 0.
2992
+ while (i >= 0 && i < toI32(bytes.length)) {
2993
+ const second: i32 = i + 1
2994
+ let next: i32 = second
2628
2995
  const b: i32 = toI32(bytes[i])
2629
2996
  if (d.pasting) {
2630
2997
  next = termDecodePaste(d, bytes, i, last, events)
2631
2998
  if (next < n && d.pasting) {
2632
2999
  return next
2633
3000
  }
2634
- } else if (b === TERM_ESC && i + 1 >= n) {
2635
- if (!last) {
2636
- return i
2637
- }
2638
- events.push(termKeyEvent(KEY_ESCAPE, b, 0, ACTION_PRESS))
2639
3001
  } else if (b === TERM_ESC) {
2640
- const after: i32 = termByte(bytes, i + 1)
2641
- if (after === TERM_BRACKET) {
2642
- next = termDecodeCsi(d, bytes, i, last, events)
2643
- } else if (termOpensString(after)) {
2644
- next = termDecodeString(bytes, i, last, events)
2645
- } else if (after === 79 && i + 2 >= n && !last) {
2646
- next = -1
2647
- } else if (after === 79 && termByte(bytes, i + 2) >= 64 && termByte(bytes, i + 2) < 127) {
2648
- // SS3 `ESC O X`: the arrows, Home, End and F1–F4 in application
2649
- // mode, and keypad Enter `ESC O M` (xterm ctlseqs, "PC-Style Function Keys").
2650
- const f: i32 = termByte(bytes, i + 2)
2651
- events.push(
2652
- termKeyEvent(f === 77 ? KEY_ENTER : termLetterKind(f), f === 77 ? 13 : f, 0, ACTION_PRESS)
2653
- )
2654
- next = i + 3
2655
- } else if (after !== TERM_ESC && after !== 79 && after < 128) {
2656
- // Alt held with a key sends ESC before it (xterm's metaSendsEscape).
2657
- events.push(termKeyEvent(termAsciiKind(after), after, MOD_ALT, ACTION_PRESS))
2658
- next = i + 2
2659
- } else {
3002
+ if (second >= n) {
3003
+ if (!last) {
3004
+ return i
3005
+ }
2660
3006
  events.push(termKeyEvent(KEY_ESCAPE, b, 0, ACTION_PRESS))
2661
- }
2662
- if (next < 0) {
2663
- return i
3007
+ } else {
3008
+ const after: i32 = termByte(bytes, second)
3009
+ const third: i32 = second + 1
3010
+ const f: i32 = termByte(bytes, third)
3011
+ if (after === TERM_BRACKET) {
3012
+ next = termDecodeCsi(d, bytes, second, last, events)
3013
+ } else if (termOpensString(after)) {
3014
+ next = termDecodeString(bytes, second, last, events)
3015
+ } else if (after === 79 && third >= n && !last) {
3016
+ next = -1
3017
+ } else if (after === 79 && third < n && f >= 64 && f < 127) {
3018
+ // SS3 `ESC O X`: the arrows, Home, End and F1–F4 in application
3019
+ // mode, and keypad Enter `ESC O M` (xterm ctlseqs, "PC-Style Function Keys").
3020
+ events.push(
3021
+ termKeyEvent(f === 77 ? KEY_ENTER : termLetterKind(f), f === 77 ? 13 : f, 0, ACTION_PRESS)
3022
+ )
3023
+ next = third + 1
3024
+ } else if (after !== TERM_ESC && after !== 79 && after < 128) {
3025
+ // Alt held with a key sends ESC before it (xterm's metaSendsEscape).
3026
+ events.push(termKeyEvent(termAsciiKind(after), after, MOD_ALT, ACTION_PRESS))
3027
+ next = third
3028
+ } else {
3029
+ events.push(termKeyEvent(KEY_ESCAPE, b, 0, ACTION_PRESS))
3030
+ }
3031
+ if (next < 0) {
3032
+ return i
3033
+ }
2664
3034
  }
2665
3035
  } else if (b < 128) {
2666
3036
  events.push(termKeyEvent(termAsciiKind(b), b, 0, ACTION_PRESS))
@@ -2670,7 +3040,13 @@ const termDecodeEvents = (d: KeyDecoder, bytes: u8[], last: boolean, events: Ter
2670
3040
  return i
2671
3041
  }
2672
3042
  events.push(termKeyEvent(KEY_CHAR, char >> 3, 0, ACTION_PRESS))
2673
- next = i + (char & 7)
3043
+ // `char & 7` bytes make the character, each one in `bytes`.
3044
+ const used: i32 = char & 7
3045
+ let at: i32 = i
3046
+ for (let k: i32 = 0; k < used && at < n; k++) {
3047
+ at = at + 1
3048
+ }
3049
+ next = at
2674
3050
  }
2675
3051
  i = next
2676
3052
  }