@gjermundgaraba/clankermux 0.4.1 → 0.5.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.
@@ -5,7 +5,7 @@
5
5
  * Imported as `@gjermundgaraba/clankermux/worker`, so a worker typechecked
6
6
  * without the DOM library does not see the page's types.
7
7
  */
8
- import { type CellPoint, type Frame, type KeyInput } from "../engine/index.ts";
8
+ import { type CellPoint, type PackedFrame, type KeyInput } from "../engine/index.ts";
9
9
  import { type ErrorCode, type ErrorMessage, type Event, type Exit, type Peer, type Profile, type Session, type Size } from "../proto/index.ts";
10
10
  import { type ErrorKind } from "./connection.ts";
11
11
  /** Why the link to the session ended. `closed`: the connection closed
@@ -57,6 +57,8 @@ export interface MountInit {
57
57
  viewport: Size;
58
58
  profile: Profile;
59
59
  active: boolean;
60
+ /** Whether the document is visible, independently of focus. */
61
+ visible: boolean;
60
62
  readOnly: boolean;
61
63
  ackOnFocus: boolean;
62
64
  }
@@ -155,6 +157,17 @@ export type ToWorker = {
155
157
  mount: number;
156
158
  focused: boolean;
157
159
  }
160
+ /** Visibility is independent of focus: visible, unfocused pages still paint. */
161
+ | {
162
+ type: "visibility";
163
+ mount: number;
164
+ visible: boolean;
165
+ }
166
+ /** The page painted its one outstanding frame, or discarded it while hidden. */
167
+ | {
168
+ type: "painted";
169
+ mount: number;
170
+ }
158
171
  /** The page lost its drawing: send the whole screen again. */
159
172
  | {
160
173
  type: "repaint";
@@ -206,7 +219,7 @@ export type ToPage =
206
219
  } | {
207
220
  type: "frame";
208
221
  mount: number;
209
- frame: Frame;
222
+ frame: PackedFrame;
210
223
  } | {
211
224
  type: "clipboard";
212
225
  mount: number;
@@ -223,7 +236,7 @@ export type ToPage =
223
236
  };
224
237
  /** The worker's end of the page's messages: `self` in a dedicated worker. */
225
238
  export interface WorkerPort {
226
- postMessage(message: ToPage): void;
239
+ postMessage(message: ToPage, options?: StructuredSerializeOptions): void;
227
240
  onmessage: ((e: MessageEvent<ToWorker>) => void) | null;
228
241
  }
229
242
  /** Serves a page's `connect` on `port`: the worker module the page starts
@@ -26,6 +26,18 @@ const BACKOFF_MAX_MS = 5000;
26
26
  const PERMANENT = new Set(["no_such_session", "engine_mismatch", "invalid_request"]);
27
27
  /** The records `ack` marks seen. */
28
28
  const ACKED = new Set(["done", "error"]);
29
+ /** Delays before trying again, doubling up to the maximum. */
30
+ class Backoff {
31
+ ms = BACKOFF_MIN_MS;
32
+ next() {
33
+ const delay = this.ms;
34
+ this.ms = Math.min(this.ms * 2, BACKOFF_MAX_MS);
35
+ return delay;
36
+ }
37
+ reset() {
38
+ this.ms = BACKOFF_MIN_MS;
39
+ }
40
+ }
29
41
  /** A WebSocket as the client's message transport. */
30
42
  class SocketTransport {
31
43
  socket;
@@ -79,16 +91,14 @@ class Hub {
79
91
  client = "clankermux-web";
80
92
  conn;
81
93
  /** The connection-level link, as a terminal mounted now first sees it:
82
- * `connecting`, `connected` (to no session), or `ended` for good. */
94
+ * `connecting`, `connected` (to no session), or `ended` for good, with
95
+ * the server's refusal or error, when an `attach` connects again. */
83
96
  state = { state: "connecting", attempt: 1 };
84
97
  /** The latest connection-level status text, for a terminal mounted later. */
85
98
  statusText = "connecting";
86
99
  /** Connection attempts since a server last answered. */
87
100
  attempt = 0;
88
- backoff = BACKOFF_MIN_MS;
89
- /** The connection ended for good with the server's refusal or error;
90
- * an `attach` connects again. */
91
- refused = false;
101
+ backoff = new Backoff();
92
102
  /** Frame channels, shared by the terminals of the one connection. */
93
103
  channel = 0;
94
104
  mounts = new Map();
@@ -115,11 +125,6 @@ class Hub {
115
125
  this.post({ type: "ready" });
116
126
  await this.connect();
117
127
  }
118
- delay() {
119
- const delay = this.backoff;
120
- this.backoff = Math.min(this.backoff * 2, BACKOFF_MAX_MS);
121
- return delay;
122
- }
123
128
  /** A connection-level change, to the page and every terminal. A
124
129
  * retrying end leaves the connection `connecting` meanwhile. */
125
130
  linkAll(link) {
@@ -139,7 +144,6 @@ class Hub {
139
144
  }
140
145
  /** The connection ended for good with `err`. */
141
146
  refuse(err) {
142
- this.refused = true;
143
147
  this.statusAll(err instanceof Error ? err.message : String(err));
144
148
  this.linkAll(endedWith(err, false));
145
149
  }
@@ -156,11 +160,11 @@ class Hub {
156
160
  this.refuse(err);
157
161
  return;
158
162
  }
159
- setTimeout(() => void this.connect(), this.delay());
163
+ setTimeout(() => void this.connect(), this.backoff.next());
160
164
  return;
161
165
  }
162
166
  this.attempt = 0;
163
- this.backoff = BACKOFF_MIN_MS;
167
+ this.backoff.reset();
164
168
  this.conn = conn;
165
169
  conn.onEnd = (err) => {
166
170
  if (this.conn !== conn)
@@ -171,7 +175,7 @@ class Hub {
171
175
  }
172
176
  else {
173
177
  this.linkAll({ state: "ended", reason: "closed", retry: true });
174
- setTimeout(() => void this.connect(), this.delay());
178
+ setTimeout(() => void this.connect(), this.backoff.next());
175
179
  }
176
180
  };
177
181
  conn.onEvent = (event) => this.event(event);
@@ -300,7 +304,7 @@ class Hub {
300
304
  const mount = new Mount(this, id, init);
301
305
  this.mounts.set(id, mount);
302
306
  mount.status(this.statusText);
303
- if (this.refused)
307
+ if (this.state.state === "ended")
304
308
  this.reattach(mount);
305
309
  else if (this.live())
306
310
  mount.connected();
@@ -315,8 +319,7 @@ class Hub {
315
319
  * otherwise opens `mount`'s session, or leaves it to the connection
316
320
  * coming up. */
317
321
  reattach(mount) {
318
- if (this.refused) {
319
- this.refused = false;
322
+ if (this.state.state === "ended") {
320
323
  this.attempt = 0;
321
324
  void this.connect();
322
325
  }
@@ -342,6 +345,7 @@ class Mount {
342
345
  profile;
343
346
  /** The page is in use; only then are its size and profile reported. */
344
347
  active;
348
+ visible;
345
349
  readOnly;
346
350
  ackOnFocus;
347
351
  /** The terminal has the keyboard and its window the focus. */
@@ -361,8 +365,11 @@ class Mount {
361
365
  writes = Promise.resolve();
362
366
  clipboard = new Osc52Scanner();
363
367
  paintTimer;
368
+ paintPending = false;
369
+ frameInFlight = false;
370
+ fullNext = false;
364
371
  /** Re-attaches after a failure; reset by a screen. */
365
- backoff = BACKOFF_MIN_MS;
372
+ backoff = new Backoff();
366
373
  reopenTimer;
367
374
  disposed = false;
368
375
  constructor(hub, id, init) {
@@ -372,14 +379,15 @@ class Mount {
372
379
  this.viewport = init.viewport;
373
380
  this.profile = init.profile;
374
381
  this.active = init.active;
382
+ this.visible = init.visible;
375
383
  this.readOnly = init.readOnly;
376
384
  this.ackOnFocus = init.ackOnFocus;
377
385
  this.render = new RenderState(hub.engine);
378
386
  this.gesture = new SelectionGesture(hub.engine);
379
387
  }
380
- post(message) {
388
+ post(message, options) {
381
389
  if (!this.disposed)
382
- this.hub.post(message);
390
+ this.hub.post(message, options);
383
391
  }
384
392
  link(link) {
385
393
  this.post({ type: "link", mount: this.id, link });
@@ -387,11 +395,6 @@ class Mount {
387
395
  status(text) {
388
396
  this.post({ type: "status", mount: this.id, text });
389
397
  }
390
- delay() {
391
- const delay = this.backoff;
392
- this.backoff = Math.min(this.backoff * 2, BACKOFF_MAX_MS);
393
- return delay;
394
- }
395
398
  /** The hub's connection is up: attach the session, if there is one. */
396
399
  connected() {
397
400
  if (this.session !== undefined) {
@@ -422,42 +425,37 @@ class Mount {
422
425
  ...(this.active && { viewport: this.viewport, profile: this.profile }),
423
426
  ...(resume && { resume }),
424
427
  };
425
- try {
426
- conn.open(channel, open, (frame) => {
427
- if (this.attachment !== attachment)
428
- return;
429
- let actions;
430
- try {
431
- actions = attachment.handle(frame);
432
- }
433
- catch (err) {
434
- // A lost place in the stream: CLOSE and OPEN again, afresh. Any
435
- // other fault would only repeat.
436
- this.status(String(err));
437
- const desync = err instanceof ClientError && err.kind === "desync";
438
- this.link(endedWith(err, desync));
439
- if (desync)
440
- this.reopen();
441
- else
442
- this.giveUp();
443
- return;
444
- }
445
- if (frame.header.type === FrameType.Attached && actions.length === 0) {
446
- // Resumed: the terminal shows the stream already, and an exit
447
- // still to come arrives as EXITED. A snapshot's screen comes
448
- // later, as an action.
449
- if (attachment.resume()) {
450
- this.status("resumed");
451
- this.link({ state: "connected", session: attachment.session });
452
- }
428
+ conn.open(channel, open, (frame) => {
429
+ if (this.attachment !== attachment)
430
+ return;
431
+ let actions;
432
+ try {
433
+ actions = attachment.handle(frame);
434
+ }
435
+ catch (err) {
436
+ // A lost place in the stream: CLOSE and OPEN again, afresh. Any
437
+ // other fault would only repeat.
438
+ this.status(String(err));
439
+ const desync = err instanceof ClientError && err.kind === "desync";
440
+ this.link(endedWith(err, desync));
441
+ if (desync)
442
+ this.reopen();
443
+ else
444
+ this.giveUp();
445
+ return;
446
+ }
447
+ if (frame.header.type === FrameType.Attached && actions.length === 0) {
448
+ // Resumed: the terminal shows the stream already, and an exit
449
+ // still to come arrives as EXITED. A snapshot's screen comes
450
+ // later, as an action.
451
+ if (attachment.resume()) {
452
+ this.status("resumed");
453
+ this.link({ state: "connected", session: attachment.session });
453
454
  }
454
- for (const action of actions)
455
- this.apply(action);
456
- });
457
- }
458
- catch (err) {
459
- this.status(String(err));
460
- }
455
+ }
456
+ for (const action of actions)
457
+ this.apply(action);
458
+ });
461
459
  }
462
460
  /** The screen of `session` is shown: `connected`, and at once `ended
463
461
  * exited` when its program has exited already. */
@@ -479,12 +477,12 @@ class Mount {
479
477
  this.reopenTimer = undefined;
480
478
  if (this.session !== undefined && !this.attachment)
481
479
  this.open();
482
- }, this.delay());
480
+ }, this.backoff.next());
483
481
  }
484
482
  apply(action) {
485
483
  switch (action.type) {
486
484
  case "screen": {
487
- this.backoff = BACKOFF_MIN_MS;
485
+ this.backoff.reset();
488
486
  this.forgetSelection();
489
487
  this.clipboard.reset();
490
488
  this.applyProfile(this.attachment?.term());
@@ -502,6 +500,9 @@ class Mount {
502
500
  break;
503
501
  }
504
502
  case "output":
503
+ // Selection state must reach the page even while painting is paused.
504
+ if (this.selected && !this.attachment?.term()?.selected)
505
+ this.unselected();
505
506
  for (const write of this.clipboard.feed(action.bytes)) {
506
507
  // Only the clipboard selection; primary and secondary have no
507
508
  // browser equivalent.
@@ -509,7 +510,9 @@ class Mount {
509
510
  this.post({ type: "clipboard", mount: this.id, text: write.text });
510
511
  }
511
512
  }
512
- this.paintTimer ??= setTimeout(() => this.paint(), PAINT_MS);
513
+ this.paintPending = true;
514
+ if (this.visible && !this.frameInFlight)
515
+ this.paintTimer ??= setTimeout(() => this.paint(), PAINT_MS);
513
516
  break;
514
517
  case "resized":
515
518
  // Another client's size, while this page kept its focus (the user
@@ -576,41 +579,65 @@ class Mount {
576
579
  }
577
580
  }
578
581
  repaint() {
579
- const term = this.attachment?.term();
580
- if (!term)
581
- return;
582
- // Switching the render state to a fresh terminal makes the next
583
- // update full; so does a resize. A full repaint of the same terminal
584
- // comes from a clean render state.
585
- this.render.free();
586
- this.render = new RenderState(this.hub.engine);
582
+ this.fullNext = true;
587
583
  this.paint();
588
584
  }
585
+ visibility(visible) {
586
+ if (this.visible === visible)
587
+ return;
588
+ this.visible = visible;
589
+ if (visible)
590
+ this.repaint();
591
+ else if (this.paintTimer !== undefined) {
592
+ clearTimeout(this.paintTimer);
593
+ this.paintTimer = undefined;
594
+ }
595
+ }
596
+ painted() {
597
+ if (!this.frameInFlight)
598
+ return;
599
+ this.frameInFlight = false;
600
+ if (this.paintPending)
601
+ this.paint();
602
+ }
589
603
  paint() {
590
604
  if (this.paintTimer !== undefined) {
591
605
  clearTimeout(this.paintTimer);
592
606
  this.paintTimer = undefined;
593
607
  }
608
+ this.paintPending = true;
594
609
  const term = this.attachment?.term();
595
- if (!term || this.disposed)
610
+ if (!term || this.disposed || !this.visible || this.frameInFlight)
596
611
  return;
597
- this.post({ type: "frame", mount: this.id, frame: this.render.update(term) });
612
+ if (this.fullNext) {
613
+ this.render.free();
614
+ this.render = new RenderState(this.hub.engine);
615
+ this.fullNext = false;
616
+ }
617
+ const frame = this.render.updatePacked(term);
618
+ // Clean only the captured rows. While this frame is in flight, no
619
+ // extraction runs, so subsequent changes accumulate in the engine.
598
620
  this.render.clean();
621
+ this.paintPending = false;
622
+ this.frameInFlight = true;
623
+ this.post({ type: "frame", mount: this.id, frame }, { transfer: frame.lines.map((row) => row.cells.data.buffer) });
599
624
  // A switch to the alternate screen or a full reset took the selection.
600
625
  if (this.selected && !term.selected)
601
626
  this.unselected();
602
627
  }
603
628
  /** The mouse: a press clears the selection, or selects a word or a line
604
629
  * at once; a drag selects; the release copies what is selected. */
605
- select(action, at, time, copy) {
630
+ select(message) {
631
+ const { at, time } = message;
606
632
  const term = this.attachment?.term();
607
633
  if (!term) {
608
634
  // Nothing to select: the page's copy waits for the answer even so.
609
- if (copy !== undefined)
610
- this.post({ type: "selection", mount: this.id, text: undefined, copy });
635
+ if (message.action === "release") {
636
+ this.post({ type: "selection", mount: this.id, text: undefined, copy: message.copy });
637
+ }
611
638
  return;
612
639
  }
613
- switch (action) {
640
+ switch (message.action) {
614
641
  case "press":
615
642
  this.claim();
616
643
  if (this.selected)
@@ -629,7 +656,7 @@ class Mount {
629
656
  // (trimmed to nothing) are no text to copy.
630
657
  const text = term.selectionText() || undefined;
631
658
  this.selected = text !== undefined;
632
- this.post({ type: "selection", mount: this.id, text, ...(copy !== undefined ? { copy } : {}) });
659
+ this.post({ type: "selection", mount: this.id, text, copy: message.copy });
633
660
  break;
634
661
  }
635
662
  }
@@ -666,14 +693,8 @@ class Mount {
666
693
  const conn = this.hub.conn;
667
694
  if (conn) {
668
695
  conn.release(this.channel);
669
- if (!this.attachment.closed()) {
670
- try {
671
- conn.send(FrameType.Close, this.channel, new Uint8Array());
672
- }
673
- catch {
674
- // The connection is gone; nothing to close.
675
- }
676
- }
696
+ if (!this.attachment.closed())
697
+ conn.send(FrameType.Close, this.channel, new Uint8Array());
677
698
  }
678
699
  this.attachment.free();
679
700
  this.attachment = undefined;
@@ -722,7 +743,7 @@ class Mount {
722
743
  return;
723
744
  }
724
745
  this.claim();
725
- this.live();
746
+ this.backToLive();
726
747
  this.unselect();
727
748
  // Each request's base64 fits the control body with room for the rest,
728
749
  // and its bytes fit the input queue (at least one byte, so the loop
@@ -794,14 +815,14 @@ class Mount {
794
815
  if (!term || term.alternate)
795
816
  return;
796
817
  if (rows === "live")
797
- this.live();
818
+ this.backToLive();
798
819
  else if (rows !== 0) {
799
820
  term.scroll(rows);
800
821
  this.paint();
801
822
  }
802
823
  }
803
824
  /** Back to the live screen before input, as any terminal does. */
804
- live() {
825
+ backToLive() {
805
826
  const term = this.attachment?.term();
806
827
  if (!term)
807
828
  return;
@@ -841,12 +862,7 @@ class Mount {
841
862
  }
842
863
  report() {
843
864
  this.reclaim = false;
844
- try {
845
- this.hub.conn?.sendJson(FrameType.Viewport, this.channel, { ...this.viewport, profile: this.profile });
846
- }
847
- catch {
848
- // Reported through onEnd.
849
- }
865
+ this.hub.conn?.sendJson(FrameType.Viewport, this.channel, { ...this.viewport, profile: this.profile });
850
866
  }
851
867
  /** Input from the page in use: its size again if another client took it. */
852
868
  claim() {
@@ -893,29 +909,27 @@ function describe(exit) {
893
909
  /** Serves a page's `connect` on `port`: the worker module the page starts
894
910
  * calls `runWorker(self)`. */
895
911
  export function runWorker(port) {
896
- const hub = new Hub((message) => port.postMessage(message));
912
+ const hub = new Hub((message, options) => port.postMessage(message, options));
897
913
  port.onmessage = (e) => {
898
914
  const message = e.data;
899
- if (message.type === "init") {
900
- void hub.init(message);
901
- return;
902
- }
903
- if (message.type === "request") {
904
- void hub.request(message.id, message.method, message.params);
905
- return;
906
- }
907
- if (message.type === "cancel") {
908
- hub.cancel(message.id);
909
- return;
910
- }
911
- if (message.type === "mount") {
912
- const { type: _, mount, ...init } = message;
913
- hub.mount(mount, init);
914
- return;
915
- }
916
- if (message.type === "unmount") {
917
- hub.unmount(message.mount);
918
- return;
915
+ switch (message.type) {
916
+ case "init":
917
+ void hub.init(message);
918
+ return;
919
+ case "request":
920
+ void hub.request(message.id, message.method, message.params);
921
+ return;
922
+ case "cancel":
923
+ hub.cancel(message.id);
924
+ return;
925
+ case "mount": {
926
+ const { type: _, mount, ...init } = message;
927
+ hub.mount(mount, init);
928
+ return;
929
+ }
930
+ case "unmount":
931
+ hub.unmount(message.mount);
932
+ return;
919
933
  }
920
934
  const mount = hub.mounts.get(message.mount);
921
935
  if (!mount)
@@ -937,7 +951,7 @@ export function runWorker(port) {
937
951
  mount.text(message.text);
938
952
  break;
939
953
  case "select":
940
- mount.select(message.action, message.at, message.time, message.action === "release" ? message.copy : undefined);
954
+ mount.select(message);
941
955
  break;
942
956
  case "wheel":
943
957
  mount.wheel(message.rows);
@@ -951,6 +965,12 @@ export function runWorker(port) {
951
965
  case "focus":
952
966
  mount.focus(message.focused);
953
967
  break;
968
+ case "visibility":
969
+ mount.visibility(message.visible);
970
+ break;
971
+ case "painted":
972
+ mount.painted();
973
+ break;
954
974
  case "repaint":
955
975
  mount.repaint();
956
976
  break;
@@ -1,4 +1,4 @@
1
- import { EngineError, Terminal } from "./index.js";
1
+ import { Terminal } from "./index.js";
2
2
  /** Bytes before the first record: the 8-byte magic and the u16 version. */
3
3
  const ENVELOPE_LEN = 10;
4
4
  /** Bytes in a record header: tag u16, payload length u32, CRC32C u32. */
@@ -101,15 +101,11 @@ export class Decoder {
101
101
  const end = stepEnd(this.source, this.consumed, this.filled);
102
102
  if (end === undefined)
103
103
  throw new Error("next page not buffered");
104
- const code = this.engine.call("ghostty_snapshot_decoder_next", this.decoder);
104
+ const page = this.engine.present("ghostty_snapshot_decoder_next", this.decoder);
105
105
  this.consumed = end;
106
- if (code === this.engine.result.NO_VALUE) {
106
+ if (!page)
107
107
  this.complete = true;
108
- return false;
109
- }
110
- if (code !== this.engine.result.SUCCESS)
111
- throw new EngineError("ghostty_snapshot_decoder_next", code);
112
- return true;
108
+ return page;
113
109
  }
114
110
  terminal() {
115
111
  return this.term;
@@ -2,7 +2,7 @@ export { Decoder, readyEnd } from "./decoder.ts";
2
2
  export { KeyEncoder, isText, keyName } from "./keys.ts";
3
3
  export type { KeyInput } from "./keys.ts";
4
4
  export { FLAG, NO_COLOR, RenderState } from "./render.ts";
5
- export type { Cell, Frame, FrameRow } from "./render.ts";
5
+ export type { Cell, Frame, FrameRow, PackedCells, PackedFrame } from "./render.ts";
6
6
  export { ENGINE } from "./pin.ts";
7
7
  export { SelectionGesture } from "./selection.ts";
8
8
  export type { CellPoint } from "./selection.ts";
@@ -33,6 +33,8 @@ export declare class EngineError extends Error {
33
33
  export declare class Engine {
34
34
  private readonly exports;
35
35
  private readonly types;
36
+ private memoryView;
37
+ private dataView;
36
38
  /** The `GhosttyResult` members the wrapper branches on. */
37
39
  readonly result: {
38
40
  SUCCESS: number;
@@ -42,12 +44,15 @@ export declare class Engine {
42
44
  };
43
45
  private constructor();
44
46
  static load(wasm: BufferSource): Promise<Engine>;
45
- /** The current linear memory; reacquired on every access because it may grow. */
47
+ /** Cached views are valid only until wasm grows its linear memory. */
46
48
  get memory(): Uint8Array;
47
49
  get view(): DataView;
48
50
  call(name: string, ...args: number[]): number;
49
51
  /** Calls a function returning GhosttyResult and throws on failure. */
50
52
  check(name: string, ...args: number[]): void;
53
+ /** Calls a function returning GhosttyResult: true for a value, false
54
+ * for `NO_VALUE`; throws on failure. */
55
+ present(name: string, ...args: number[]): boolean;
51
56
  alloc(len: number): number;
52
57
  free(ptr: number, len: number): void;
53
58
  /** Runs `f` with `bytes` copied into wasm memory, or with a null