@gjermundgaraba/clankermux 0.1.0 → 0.2.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.
@@ -4,11 +4,19 @@
4
4
  * reports input. Imported as `@gjermundgaraba/clankermux/worker`, so a worker
5
5
  * typechecked without the DOM library does not see the page's types.
6
6
  */
7
- import { ENGINE, Engine, KeyEncoder, RenderState } from "../engine/index.js";
7
+ import { ENGINE, Engine, KeyEncoder, RenderState, SelectionGesture, } from "../engine/index.js";
8
8
  import { FrameType, } from "../proto/index.js";
9
9
  import { Attachment } from "./attachment.js";
10
10
  import { ClientError, Connection, hello } from "./connection.js";
11
11
  import { Osc52Scanner } from "./osc52.js";
12
+ /** The keys that, with Shift, scroll the history: by pages, or to its
13
+ * top or bottom. */
14
+ const SCROLL_KEYS = {
15
+ PageUp: -1,
16
+ PageDown: 1,
17
+ Home: "top",
18
+ End: "bottom",
19
+ };
12
20
  /** Coalescing window for paints. */
13
21
  const PAINT_MS = 16;
14
22
  const BACKOFF_MIN_MS = 250;
@@ -49,9 +57,17 @@ class Client {
49
57
  engine;
50
58
  render;
51
59
  keys;
60
+ gesture;
61
+ /** The page holds a selection's text. */
62
+ selected = false;
52
63
  url = "";
53
64
  viewport;
54
65
  profile;
66
+ /** The page is in use; only then are its size and profile reported. */
67
+ active = false;
68
+ /** Another client resized the session while this page was in use: its
69
+ * next input reports its size again. */
70
+ reclaim = false;
55
71
  conn;
56
72
  attachment;
57
73
  channel = 0;
@@ -69,6 +85,21 @@ class Client {
69
85
  /** Shared by reconnects and re-attaches after a failure; reset by a screen. */
70
86
  backoff = BACKOFF_MIN_MS;
71
87
  reopenTimer;
88
+ /** Connection attempts since a server last answered. */
89
+ attempt = 0;
90
+ /** The connection ended for good with the server's refusal or error;
91
+ * `attach` connects again. */
92
+ refused = false;
93
+ link(link) {
94
+ this.post({ type: "link", link });
95
+ }
96
+ /** The link ended with `error`: the server's, else the client's own. */
97
+ endedWith(err, retry) {
98
+ const server = err instanceof ClientError ? err.server : undefined;
99
+ this.link(server
100
+ ? { state: "ended", reason: linkEnd(server.code), code: server.code, message: server.message, retry }
101
+ : { state: "ended", reason: "error", message: err instanceof Error ? err.message : String(err), retry });
102
+ }
72
103
  delay() {
73
104
  const delay = this.backoff;
74
105
  this.backoff = Math.min(this.backoff * 2, BACKOFF_MAX_MS);
@@ -78,16 +109,26 @@ class Client {
78
109
  this.url = message.url;
79
110
  this.viewport = message.viewport;
80
111
  this.profile = message.profile;
112
+ this.active = message.active;
81
113
  this.session = message.session;
82
114
  this.post({ type: "status", text: "loading engine" });
83
- const wasm = await (await fetch(message.wasm)).arrayBuffer();
84
- this.engine = await Engine.load(wasm);
115
+ try {
116
+ const wasm = await (await fetch(message.wasm)).arrayBuffer();
117
+ this.engine = await Engine.load(wasm);
118
+ }
119
+ catch (err) {
120
+ this.post({ type: "status", text: `cannot load the engine: ${err}` });
121
+ this.endedWith(err, false);
122
+ return;
123
+ }
85
124
  this.render = new RenderState(this.engine);
86
125
  this.keys = new KeyEncoder(this.engine);
126
+ this.gesture = new SelectionGesture(this.engine);
87
127
  await this.connect();
88
128
  }
89
129
  async connect() {
90
130
  this.post({ type: "status", text: this.attachment ? "reconnecting" : "connecting" });
131
+ this.link({ state: "connecting", attempt: ++this.attempt });
91
132
  let conn;
92
133
  try {
93
134
  conn = await Connection.connect(await SocketTransport.connect(this.url), hello("clankermux-web", ENGINE));
@@ -96,11 +137,14 @@ class Client {
96
137
  // A server that answers and refuses is not retried; a lost one is.
97
138
  if (err instanceof ClientError && (err.kind === "server" || err.kind === "protocol")) {
98
139
  this.post({ type: "status", text: err.message });
140
+ this.refused = true;
141
+ this.endedWith(err, false);
99
142
  return;
100
143
  }
101
144
  setTimeout(() => void this.connect(), this.delay());
102
145
  return;
103
146
  }
147
+ this.attempt = 0;
104
148
  this.conn = conn;
105
149
  conn.onEnd = (err) => {
106
150
  if (this.conn !== conn)
@@ -108,8 +152,11 @@ class Client {
108
152
  this.conn = undefined;
109
153
  if (err.kind === "server") {
110
154
  this.post({ type: "status", text: err.message });
155
+ this.refused = true;
156
+ this.endedWith(err, false);
111
157
  }
112
158
  else {
159
+ this.link({ state: "ended", reason: "closed", retry: true });
113
160
  setTimeout(() => void this.connect(), this.delay());
114
161
  }
115
162
  };
@@ -129,13 +176,24 @@ class Client {
129
176
  }
130
177
  catch (err) {
131
178
  this.post({ type: "status", text: String(err) });
179
+ // A lost connection is reported through onEnd, which ran first; a
180
+ // refused subscription ends this one for good.
181
+ if (this.conn === conn) {
182
+ this.conn = undefined;
183
+ conn.close();
184
+ this.refused = true;
185
+ this.endedWith(err, false);
186
+ }
132
187
  return;
133
188
  }
134
189
  this.postSessions();
135
- if (this.session !== undefined)
190
+ if (this.session !== undefined) {
136
191
  this.open();
137
- else
192
+ }
193
+ else {
138
194
  this.post({ type: "status", text: "no session" });
195
+ this.link({ state: "connected", session: undefined });
196
+ }
139
197
  }
140
198
  event(event) {
141
199
  switch (event.event) {
@@ -163,10 +221,10 @@ class Client {
163
221
  const attachment = this.attachment;
164
222
  attachment.openOn(conn.welcome);
165
223
  const channel = ++this.channel;
224
+ // An OPEN with a viewport or profile is a report applied at once.
166
225
  const open = {
167
226
  session: this.session,
168
- viewport: this.viewport,
169
- profile: this.profile,
227
+ ...(this.active && { viewport: this.viewport, profile: this.profile }),
170
228
  resume: attachment.resume(),
171
229
  };
172
230
  try {
@@ -181,7 +239,9 @@ class Client {
181
239
  // A lost place in the stream: CLOSE and OPEN again, afresh. Any
182
240
  // other fault would only repeat.
183
241
  this.post({ type: "status", text: String(err) });
184
- if (err instanceof ClientError && err.kind === "desync")
242
+ const desync = err instanceof ClientError && err.kind === "desync";
243
+ this.endedWith(err, desync);
244
+ if (desync)
185
245
  this.reopen();
186
246
  else
187
247
  this.giveUp();
@@ -189,6 +249,11 @@ class Client {
189
249
  }
190
250
  if (frame.header.type === FrameType.Attached && actions.length === 0) {
191
251
  this.post({ type: "status", text: "attached" });
252
+ // Resumed: the terminal shows the stream already, and an exit
253
+ // still to come arrives as EXITED. A snapshot's screen comes
254
+ // later, as an action.
255
+ if (attachment.resume())
256
+ this.link({ state: "connected", session: attachment.session });
192
257
  }
193
258
  for (const action of actions)
194
259
  this.apply(action);
@@ -198,6 +263,14 @@ class Client {
198
263
  this.post({ type: "status", text: String(err) });
199
264
  }
200
265
  }
266
+ /** The screen of `session` is shown: `connected`, and at once `ended
267
+ * exited` when its program has exited already. */
268
+ attached(session) {
269
+ this.link({ state: "connected", session });
270
+ if (session?.status === "exited") {
271
+ this.link({ state: "ended", reason: "exited", ...(session.exit && { exit: session.exit }), retry: false });
272
+ }
273
+ }
201
274
  /** Detaches for good: a reconnect does not try the session again. */
202
275
  giveUp() {
203
276
  this.detach();
@@ -217,6 +290,7 @@ class Client {
217
290
  switch (action.type) {
218
291
  case "screen": {
219
292
  this.backoff = BACKOFF_MIN_MS;
293
+ this.forgetSelection();
220
294
  this.clipboard.reset();
221
295
  this.applyProfile(this.attachment?.term());
222
296
  this.paint();
@@ -227,6 +301,7 @@ class Client {
227
301
  ? `exited: ${describe(session.exit)}`
228
302
  : "attached";
229
303
  this.post({ type: "status", text });
304
+ this.attached(session);
230
305
  break;
231
306
  }
232
307
  case "output":
@@ -239,31 +314,47 @@ class Client {
239
314
  this.paintTimer ??= setTimeout(() => this.paint(), PAINT_MS);
240
315
  break;
241
316
  case "resized":
317
+ // Another client's size, while this page kept its focus (the user
318
+ // went to another machine): taken back at this page's next input.
319
+ if (this.active && (action.cols !== this.viewport.cols || action.rows !== this.viewport.rows)) {
320
+ this.reclaim = true;
321
+ }
242
322
  this.paint();
243
323
  break;
244
324
  case "exited":
245
325
  this.paint();
246
326
  this.post({ type: "status", text: `exited: ${describe(action.exit)}` });
327
+ this.link({ state: "ended", reason: "exited", exit: action.exit, retry: false });
247
328
  break;
248
329
  case "gap":
249
330
  this.clipboard.reset();
331
+ this.forgetSelection();
250
332
  this.post({ type: "status", text: "resynchronising" });
251
333
  break;
252
334
  case "closed":
253
335
  this.post({ type: "status", text: `closed: ${action.reason}` });
336
+ // `stopping` is followed by the connection's close, and the
337
+ // reconnect attaches again; a removed session is gone for good.
338
+ this.link({ state: "ended", reason: action.reason, retry: action.reason === "stopping" });
339
+ if (action.reason === "removed")
340
+ this.giveUp();
254
341
  break;
255
- case "error":
342
+ case "error": {
256
343
  this.post({ type: "status", text: `${action.error.code}: ${action.error.message}` });
257
344
  // An error ended the attachment: attach again after a backoff
258
345
  // (`too_slow`, a snapshot that could not be taken), unless a new
259
346
  // OPEN would fail the same way.
260
- if (this.attachment?.closed()) {
261
- if (PERMANENT.has(action.error.code))
262
- this.giveUp();
263
- else
264
- this.reopen();
265
- }
347
+ if (!this.attachment?.closed())
348
+ break;
349
+ const { code, message } = action.error;
350
+ const retry = !PERMANENT.has(code);
351
+ this.link({ state: "ended", reason: linkEnd(code), code, message, retry });
352
+ if (retry)
353
+ this.reopen();
354
+ else
355
+ this.giveUp();
266
356
  break;
357
+ }
267
358
  }
268
359
  }
269
360
  /** The page's colours on the local terminal, as the server has them on
@@ -301,6 +392,60 @@ class Client {
301
392
  return;
302
393
  this.post({ type: "frame", frame: this.render.update(term) });
303
394
  this.render.clean();
395
+ // A switch to the alternate screen or a full reset took the selection.
396
+ if (this.selected && !term.selected)
397
+ this.unselected();
398
+ }
399
+ /** The mouse: a press clears the selection, or selects a word or a line
400
+ * at once; a drag selects; the release copies what is selected. */
401
+ select(action, at, time) {
402
+ const term = this.attachment?.term();
403
+ if (!term)
404
+ return;
405
+ switch (action) {
406
+ case "press":
407
+ this.claim();
408
+ if (this.selected)
409
+ this.unselected();
410
+ term.select(this.gesture.press(term, at, time));
411
+ break;
412
+ case "drag": {
413
+ const selection = this.gesture.drag(term, at);
414
+ if (selection)
415
+ term.select(selection);
416
+ break;
417
+ }
418
+ case "release": {
419
+ this.gesture.release(term, at);
420
+ // Answered either way: the page's copy waits for it. Blanks only
421
+ // (trimmed to nothing) are no text to copy.
422
+ const text = term.selectionText() || undefined;
423
+ this.selected = text !== undefined;
424
+ this.post({ type: "selection", text, copy: true });
425
+ break;
426
+ }
427
+ }
428
+ this.paint();
429
+ }
430
+ /** Input clears the selection. */
431
+ unselect() {
432
+ const term = this.attachment?.term();
433
+ if (!term?.selected)
434
+ return;
435
+ term.select(undefined);
436
+ this.paint();
437
+ if (this.selected)
438
+ this.unselected();
439
+ }
440
+ unselected() {
441
+ this.selected = false;
442
+ this.post({ type: "selection", text: undefined, copy: false });
443
+ }
444
+ /** The terminal goes, and its selection and the gesture's anchor with it. */
445
+ forgetSelection(term) {
446
+ this.gesture.forget(term);
447
+ if (this.selected)
448
+ this.unselected();
304
449
  }
305
450
  /** Closes the current attachment's channel and forgets it. An
306
451
  * attachment the server ended needs no CLOSE; one whose stream ended
@@ -308,6 +453,8 @@ class Client {
308
453
  detach() {
309
454
  if (!this.attachment)
310
455
  return;
456
+ // Still alive: the gesture's anchor is released in it.
457
+ this.forgetSelection(this.attachment.term());
311
458
  if (this.conn) {
312
459
  this.conn.release(this.channel);
313
460
  if (!this.attachment.closed()) {
@@ -322,24 +469,67 @@ class Client {
322
469
  this.attachment.free();
323
470
  this.attachment = undefined;
324
471
  }
472
+ /** Attaches `session`; after the server refused or ended the
473
+ * connection, connects again first. */
325
474
  attach(session) {
326
475
  this.detach();
327
476
  this.writes = Promise.resolve();
328
477
  this.session = session;
329
478
  this.postSessions();
330
- this.open();
479
+ if (this.refused) {
480
+ this.refused = false;
481
+ this.attempt = 0;
482
+ void this.connect();
483
+ }
484
+ else {
485
+ this.open();
486
+ }
331
487
  }
332
- async create() {
488
+ /** Creates a session at the current size and attaches it; `on_exit`
489
+ * only when given, so the server's default holds otherwise. */
490
+ async create(id, onExit) {
333
491
  const conn = this.conn;
334
492
  if (!conn)
335
- return;
493
+ return this.fail(id, new ClientError("closed", "not connected"));
494
+ const params = { cols: this.viewport.cols, rows: this.viewport.rows };
495
+ if (onExit !== undefined)
496
+ params.on_exit = onExit;
497
+ let session;
336
498
  try {
337
- const session = await conn.call("create", { cols: this.viewport.cols, rows: this.viewport.rows });
338
- this.attach(session.id);
499
+ session = await conn.call("create", params);
339
500
  }
340
501
  catch (err) {
341
502
  this.post({ type: "status", text: String(err) });
503
+ return this.fail(id, err);
342
504
  }
505
+ this.attach(session.id);
506
+ this.post({ type: "done", id, session });
507
+ }
508
+ /** `end` (SIGHUP) or `remove` for the session attached or being
509
+ * attached. `not_running` from `end` is success: there is nothing left
510
+ * to end. */
511
+ async request(id, method) {
512
+ const conn = this.conn;
513
+ const session = this.session;
514
+ if (!conn)
515
+ return this.fail(id, new ClientError("closed", "not connected"));
516
+ if (session === undefined)
517
+ return this.fail(id, new Error("no session is attached"));
518
+ try {
519
+ await conn.call(method, { session });
520
+ }
521
+ catch (err) {
522
+ if (!(method === "end" && err instanceof ClientError && err.server?.code === "not_running")) {
523
+ return this.fail(id, err);
524
+ }
525
+ }
526
+ this.post({ type: "done", id });
527
+ }
528
+ fail(id, err) {
529
+ const error = err instanceof ClientError
530
+ ? { kind: err.kind, message: err.message, ...(err.server && { server: err.server }) }
531
+ : { message: err instanceof Error ? err.message : String(err) };
532
+ this.post({ type: "done", id, error });
343
533
  }
344
534
  /** Input for the session, dropped unless attached on a live connection.
345
535
  * Keys go as INPUT; a paste goes as `write` requests, each answered
@@ -353,6 +543,9 @@ class Client {
353
543
  const channel = this.channel;
354
544
  if (bytes.length === 0 || !conn || !attachment || attachment.ended() || session === undefined)
355
545
  return;
546
+ this.claim();
547
+ this.live();
548
+ this.unselect();
356
549
  // Each request's base64 fits the control body with room for the rest,
357
550
  // and its bytes fit the input queue (at least one byte, so the loop
358
551
  // moves on an absurd limit).
@@ -382,29 +575,97 @@ class Client {
382
575
  const term = this.attachment?.term();
383
576
  if (!term)
384
577
  return;
578
+ // Shift+PageUp, PageDown, Home and End scroll the history, press and
579
+ // release; on the alternate screen, which has none, they are keys.
580
+ const scroll = SCROLL_KEYS[input.code];
581
+ if (scroll && input.shift && !input.ctrl && !input.alt && !input.meta && !term.alternate) {
582
+ if (input.action === "release")
583
+ return;
584
+ term.scroll(typeof scroll === "number" ? scroll * term.rows : scroll);
585
+ this.paint();
586
+ return;
587
+ }
385
588
  this.input(this.keys.encode(term, input), false);
386
589
  }
590
+ /** The wheel. On the alternate screen, with alternate scroll (mode
591
+ * 1007, on by default), it is the arrow keys, as a full-screen program
592
+ * such as `less` expects; without it, nothing. */
593
+ scroll(rows) {
594
+ const term = this.attachment?.term();
595
+ if (!term || rows === 0)
596
+ return;
597
+ this.claim();
598
+ if (!term.alternate) {
599
+ term.scroll(rows);
600
+ this.paint();
601
+ return;
602
+ }
603
+ if (!term.mode(1007))
604
+ return;
605
+ const code = rows < 0 ? "ArrowUp" : "ArrowDown";
606
+ const arrow = this.keys.encode(term, { code, key: code, action: "press", shift: false, ctrl: false, alt: false, meta: false });
607
+ const bytes = new Uint8Array(arrow.length * Math.abs(rows));
608
+ for (let i = 0; i < Math.abs(rows); i++)
609
+ bytes.set(arrow, i * arrow.length);
610
+ this.input(bytes, false);
611
+ }
612
+ /** Back to the live screen before input, as any terminal does. */
613
+ live() {
614
+ const term = this.attachment?.term();
615
+ if (!term)
616
+ return;
617
+ const { total, offset, len } = term.scrollbar;
618
+ if (offset + len >= total)
619
+ return;
620
+ term.scroll("bottom");
621
+ this.paint();
622
+ }
623
+ /** Text no key sent, as UTF-8: a composition's, the emoji picker's. */
624
+ text(text) {
625
+ if (!this.attachment?.term())
626
+ return;
627
+ this.input(new TextEncoder().encode(text), false);
628
+ }
387
629
  paste(text) {
388
630
  const term = this.attachment?.term();
389
631
  if (!term)
390
632
  return;
391
633
  this.input(this.engine.encodePaste(text, term.mode(2004)), true);
392
634
  }
393
- setViewport(size, profile) {
635
+ /** Keeps the page's size (for `create`) and colours (for the local
636
+ * terminal), and reports them to the session while the page is active.
637
+ * A report repeats the last one when the page becomes active again, so
638
+ * the session takes its size back from another client. */
639
+ setViewport(size, profile, active) {
394
640
  this.viewport = size;
395
641
  this.profile = profile;
642
+ this.active = active;
396
643
  const attachment = this.attachment;
397
644
  if (!this.conn || !attachment || attachment.ended())
398
645
  return;
399
646
  this.applyProfile(attachment.term());
400
647
  this.paint();
648
+ if (active)
649
+ this.report();
650
+ }
651
+ report() {
652
+ this.reclaim = false;
401
653
  try {
402
- this.conn.sendJson(FrameType.Viewport, this.channel, { ...size, profile });
654
+ this.conn?.sendJson(FrameType.Viewport, this.channel, { ...this.viewport, profile: this.profile });
403
655
  }
404
656
  catch {
405
657
  // Reported through onEnd.
406
658
  }
407
659
  }
660
+ /** Input from the page in use: its size again if another client took it. */
661
+ claim() {
662
+ if (this.reclaim && this.active && this.attachment && !this.attachment.ended())
663
+ this.report();
664
+ }
665
+ }
666
+ /** The reason an error code ends the link with. */
667
+ function linkEnd(code) {
668
+ return code === "no_such_session" || code === "engine_mismatch" ? code : "error";
408
669
  }
409
670
  function describe(exit) {
410
671
  return "code" in exit ? `code ${exit.code}` : `signal ${exit.signal}`;
@@ -423,7 +684,11 @@ export function runWorker(port) {
423
684
  client.attach(message.session);
424
685
  break;
425
686
  case "create":
426
- void client.create();
687
+ void client.create(message.id, message.onExit);
688
+ break;
689
+ case "end":
690
+ case "remove":
691
+ void client.request(message.id, message.type);
427
692
  break;
428
693
  case "key":
429
694
  client.key(message.input);
@@ -431,8 +696,17 @@ export function runWorker(port) {
431
696
  case "paste":
432
697
  client.paste(message.text);
433
698
  break;
699
+ case "text":
700
+ client.text(message.text);
701
+ break;
702
+ case "select":
703
+ client.select(message.action, message.at, message.time);
704
+ break;
705
+ case "scroll":
706
+ client.scroll(message.rows);
707
+ break;
434
708
  case "viewport":
435
- client.setViewport(message.size, message.profile);
709
+ client.setViewport(message.size, message.profile, message.active);
436
710
  break;
437
711
  case "repaint":
438
712
  client.repaint();
@@ -4,10 +4,21 @@ export type { KeyInput } from "./keys.ts";
4
4
  export { FLAG, NO_COLOR, RenderState } from "./render.ts";
5
5
  export type { Cell, Frame, FrameRow } from "./render.ts";
6
6
  export { ENGINE } from "./pin.ts";
7
+ export { SelectionGesture } from "./selection.ts";
8
+ export type { CellPoint } from "./selection.ts";
7
9
  /** Struct fields to set: numbers, or the fields of a nested struct. */
8
10
  type Packed = {
9
11
  [field: string]: number | Packed;
10
12
  };
13
+ /** The viewport's place in the screen's rows, history included. */
14
+ export interface Scrollbar {
15
+ /** Rows of the screen, history and the active area. */
16
+ total: number;
17
+ /** The viewport's first row. */
18
+ offset: number;
19
+ /** The viewport's rows. */
20
+ len: number;
21
+ }
11
22
  /** Position and width of a bit field, from the manifest. */
12
23
  export interface BitField {
13
24
  lsb: number;
@@ -95,7 +106,30 @@ export declare class Terminal {
95
106
  get cols(): number;
96
107
  get rows(): number;
97
108
  get scrollbackRows(): number;
109
+ /** Whether the alternate screen (full-screen programs) is active; it
110
+ * has no history to scroll. */
111
+ get alternate(): boolean;
112
+ get scrollbar(): Scrollbar;
113
+ /** Moves the viewport `rows` rows (up when negative) through the
114
+ * history, or to its top or the live screen at its bottom. Output does
115
+ * not move a viewport scrolled into the history. */
116
+ scroll(to: number | "top" | "bottom"): void;
98
117
  get title(): string;
118
+ /** An untracked `GhosttyGridRef` to the viewport cell at `at`, valid
119
+ * until the terminal changes. */
120
+ gridRef(at: {
121
+ x: number;
122
+ y: number;
123
+ }): Uint8Array;
124
+ /** Installs `selection` (a `GhosttySelection`) as the terminal's, which
125
+ * the terminal then tracks through output, scrolling and resizes, or
126
+ * clears it. */
127
+ select(selection: Uint8Array | undefined): void;
128
+ /** The selection's text: soft-wrapped lines joined, trailing blanks
129
+ * trimmed, as Ghostty copies it; undefined with no selection. */
130
+ selectionText(): string | undefined;
131
+ /** Whether the active screen has a selection. */
132
+ get selected(): boolean;
99
133
  /** Whether DEC private mode `number` is set. */
100
134
  mode(number: number): boolean;
101
135
  /** No cell size in pixels: `RESIZED` carries none. */