@gjermundgaraba/clankermux 0.1.1 → 0.3.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,7 +4,7 @@
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 { type Frame, type KeyInput } from "../engine/index.ts";
7
+ import { type CellPoint, type Frame, type KeyInput } from "../engine/index.ts";
8
8
  import { type ErrorCode, type ErrorMessage, type Exit, type OnExit, type Profile, type Session, type Size } from "../proto/index.ts";
9
9
  import { type ErrorKind } from "./connection.ts";
10
10
  /** Why the link to the session ended. `closed`: the connection closed
@@ -50,12 +50,15 @@ export interface Failure {
50
50
  server?: ErrorMessage;
51
51
  }
52
52
  /** Messages from the page to the worker. */
53
- export type ToWorker = {
53
+ export type ToWorker =
54
+ /** `active`: the user is looking at the page (below). */
55
+ {
54
56
  type: "init";
55
57
  wasm: string;
56
58
  url: string;
57
59
  viewport: Size;
58
60
  profile: Profile;
61
+ active: boolean;
59
62
  session: string | undefined;
60
63
  } | {
61
64
  type: "attach";
@@ -78,10 +81,33 @@ export type ToWorker = {
78
81
  } | {
79
82
  type: "paste";
80
83
  text: string;
81
- } | {
84
+ }
85
+ /** The mouse on the canvas, `at` in cells of the viewport, fractions
86
+ * included; `time` in ms, for double and triple clicks. */
87
+ | {
88
+ type: "select";
89
+ action: "press" | "drag" | "release";
90
+ at: CellPoint;
91
+ time: number;
92
+ }
93
+ /** Text as typed, which no key sent: a composition's, the emoji picker's. */
94
+ | {
95
+ type: "text";
96
+ text: string;
97
+ }
98
+ /** The wheel: `rows` through the history, up when negative. */
99
+ | {
100
+ type: "scroll";
101
+ rows: number;
102
+ }
103
+ /** The page's size and profile. Only an `active` page, one the user is
104
+ * looking at, reports them to the session: the server applies the
105
+ * latest report, so the session takes the size of the page in use. */
106
+ | {
82
107
  type: "viewport";
83
108
  size: Size;
84
109
  profile: Profile;
110
+ active: boolean;
85
111
  }
86
112
  /** The page lost its drawing: send the whole screen again. */
87
113
  | {
@@ -109,6 +135,13 @@ export type ToPage = {
109
135
  } | {
110
136
  type: "clipboard";
111
137
  text: string;
138
+ }
139
+ /** The selection's text, or undefined once there is none; `copy`: the
140
+ * answer to a release, so the text (if any) goes to the clipboard. */
141
+ | {
142
+ type: "selection";
143
+ text: string | undefined;
144
+ copy: boolean;
112
145
  };
113
146
  /** The worker's end of the page's messages: `self` in a dedicated worker. */
114
147
  export interface WorkerPort {
@@ -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,16 +57,24 @@ 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;
58
74
  /** The session attached or being attached. */
59
75
  session;
60
76
  sessions = new Map();
61
- /** Input in order: a paste goes as `write` requests, and keys typed
77
+ /** Input in order: a paste goes as `send` requests, and keys typed
62
78
  * meanwhile wait behind it. `attach` starts a fresh chain; input queued
63
79
  * for an attachment that is gone is dropped, but a paste under way
64
80
  * finishes (cut short, it would leave the program inside a bracketed
@@ -93,6 +109,7 @@ class Client {
93
109
  this.url = message.url;
94
110
  this.viewport = message.viewport;
95
111
  this.profile = message.profile;
112
+ this.active = message.active;
96
113
  this.session = message.session;
97
114
  this.post({ type: "status", text: "loading engine" });
98
115
  try {
@@ -106,6 +123,7 @@ class Client {
106
123
  }
107
124
  this.render = new RenderState(this.engine);
108
125
  this.keys = new KeyEncoder(this.engine);
126
+ this.gesture = new SelectionGesture(this.engine);
109
127
  await this.connect();
110
128
  }
111
129
  async connect() {
@@ -203,10 +221,10 @@ class Client {
203
221
  const attachment = this.attachment;
204
222
  attachment.openOn(conn.welcome);
205
223
  const channel = ++this.channel;
224
+ // An OPEN with a viewport or profile is a report applied at once.
206
225
  const open = {
207
226
  session: this.session,
208
- viewport: this.viewport,
209
- profile: this.profile,
227
+ ...(this.active && { viewport: this.viewport, profile: this.profile }),
210
228
  resume: attachment.resume(),
211
229
  };
212
230
  try {
@@ -272,6 +290,7 @@ class Client {
272
290
  switch (action.type) {
273
291
  case "screen": {
274
292
  this.backoff = BACKOFF_MIN_MS;
293
+ this.forgetSelection();
275
294
  this.clipboard.reset();
276
295
  this.applyProfile(this.attachment?.term());
277
296
  this.paint();
@@ -295,6 +314,11 @@ class Client {
295
314
  this.paintTimer ??= setTimeout(() => this.paint(), PAINT_MS);
296
315
  break;
297
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
+ }
298
322
  this.paint();
299
323
  break;
300
324
  case "exited":
@@ -304,6 +328,7 @@ class Client {
304
328
  break;
305
329
  case "gap":
306
330
  this.clipboard.reset();
331
+ this.forgetSelection();
307
332
  this.post({ type: "status", text: "resynchronising" });
308
333
  break;
309
334
  case "closed":
@@ -367,6 +392,60 @@ class Client {
367
392
  return;
368
393
  this.post({ type: "frame", frame: this.render.update(term) });
369
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();
370
449
  }
371
450
  /** Closes the current attachment's channel and forgets it. An
372
451
  * attachment the server ended needs no CLOSE; one whose stream ended
@@ -374,6 +453,8 @@ class Client {
374
453
  detach() {
375
454
  if (!this.attachment)
376
455
  return;
456
+ // Still alive: the gesture's anchor is released in it.
457
+ this.forgetSelection(this.attachment.term());
377
458
  if (this.conn) {
378
459
  this.conn.release(this.channel);
379
460
  if (!this.attachment.closed()) {
@@ -451,7 +532,7 @@ class Client {
451
532
  this.post({ type: "done", id, error });
452
533
  }
453
534
  /** Input for the session, dropped unless attached on a live connection.
454
- * Keys go as INPUT; a paste goes as `write` requests, each answered
535
+ * Keys go as INPUT; a paste goes as `send` requests, each answered
455
536
  * once the PTY took it, since INPUT frames are not acknowledged and a
456
537
  * paste would overflow the input queue. This tab's input is sent in
457
538
  * order, so none of it lands inside a paste. */
@@ -462,6 +543,9 @@ class Client {
462
543
  const channel = this.channel;
463
544
  if (bytes.length === 0 || !conn || !attachment || attachment.ended() || session === undefined)
464
545
  return;
546
+ this.claim();
547
+ this.live();
548
+ this.unselect();
465
549
  // Each request's base64 fits the control body with room for the rest,
466
550
  // and its bytes fit the input queue (at least one byte, so the loop
467
551
  // moves on an absurd limit).
@@ -476,7 +560,7 @@ class Client {
476
560
  return;
477
561
  }
478
562
  for (let at = 0; at < bytes.length; at += chunk) {
479
- await conn.call("write", { session, data: base64(bytes.subarray(at, at + chunk)) });
563
+ await conn.call("send", { session, data: base64(bytes.subarray(at, at + chunk)) });
480
564
  }
481
565
  }
482
566
  catch (err) {
@@ -491,29 +575,93 @@ class Client {
491
575
  const term = this.attachment?.term();
492
576
  if (!term)
493
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
+ }
494
588
  this.input(this.keys.encode(term, input), false);
495
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
+ }
496
629
  paste(text) {
497
630
  const term = this.attachment?.term();
498
631
  if (!term)
499
632
  return;
500
633
  this.input(this.engine.encodePaste(text, term.mode(2004)), true);
501
634
  }
502
- 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) {
503
640
  this.viewport = size;
504
641
  this.profile = profile;
642
+ this.active = active;
505
643
  const attachment = this.attachment;
506
644
  if (!this.conn || !attachment || attachment.ended())
507
645
  return;
508
646
  this.applyProfile(attachment.term());
509
647
  this.paint();
648
+ if (active)
649
+ this.report();
650
+ }
651
+ report() {
652
+ this.reclaim = false;
510
653
  try {
511
- this.conn.sendJson(FrameType.Viewport, this.channel, { ...size, profile });
654
+ this.conn?.sendJson(FrameType.Viewport, this.channel, { ...this.viewport, profile: this.profile });
512
655
  }
513
656
  catch {
514
657
  // Reported through onEnd.
515
658
  }
516
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
+ }
517
665
  }
518
666
  /** The reason an error code ends the link with. */
519
667
  function linkEnd(code) {
@@ -548,8 +696,17 @@ export function runWorker(port) {
548
696
  case "paste":
549
697
  client.paste(message.text);
550
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;
551
708
  case "viewport":
552
- client.setViewport(message.size, message.profile);
709
+ client.setViewport(message.size, message.profile, message.active);
553
710
  break;
554
711
  case "repaint":
555
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. */
@@ -2,6 +2,7 @@ export { Decoder, readyEnd } from "./decoder.js";
2
2
  export { KeyEncoder, isText, keyName } from "./keys.js";
3
3
  export { FLAG, NO_COLOR, RenderState } from "./render.js";
4
4
  export { ENGINE } from "./pin.js";
5
+ export { SelectionGesture } from "./selection.js";
5
6
  export class EngineError extends Error {
6
7
  call;
7
8
  code;
@@ -317,6 +318,35 @@ export class Terminal {
317
318
  get scrollbackRows() {
318
319
  return this.get("SCROLLBACK_ROWS", 4);
319
320
  }
321
+ /** Whether the alternate screen (full-screen programs) is active; it
322
+ * has no history to scroll. */
323
+ get alternate() {
324
+ return this.get("ACTIVE_SCREEN", 4) === this.engine.enumValue("GhosttyTerminalScreen", "ALTERNATE");
325
+ }
326
+ get scrollbar() {
327
+ const e = this.engine;
328
+ return e.scratch(e.sizeOf("GhosttyTerminalScrollbar"), (out) => {
329
+ e.check("ghostty_terminal_get", this.handle, e.enumValue("GhosttyTerminalData", "SCROLLBAR"), out);
330
+ const u64 = (key) => Number(e.view.getBigUint64(out + e.offsetOf("GhosttyTerminalScrollbar", key), true));
331
+ return { total: u64("total"), offset: u64("offset"), len: u64("len") };
332
+ });
333
+ }
334
+ /** Moves the viewport `rows` rows (up when negative) through the
335
+ * history, or to its top or the live screen at its bottom. Output does
336
+ * not move a viewport scrolled into the history. */
337
+ scroll(to) {
338
+ const e = this.engine;
339
+ const size = e.sizeOf("GhosttyTerminalScrollViewport");
340
+ e.scratch(size, (ptr) => {
341
+ e.memory.fill(0, ptr, ptr + size);
342
+ const tag = typeof to === "number" ? "DELTA" : to.toUpperCase();
343
+ e.view.setInt32(ptr + e.offsetOf("GhosttyTerminalScrollViewport", "tag"), e.enumValue("GhosttyTerminalScrollViewportTag", tag), true);
344
+ if (typeof to === "number")
345
+ e.view.setInt32(ptr + e.offsetOf("GhosttyTerminalScrollViewport", "value"), to, true);
346
+ // The tagged union is passed by value, which the wasm ABI passes by address.
347
+ e.call("ghostty_terminal_scroll_viewport", this.handle, ptr);
348
+ });
349
+ }
320
350
  get title() {
321
351
  const size = this.engine.sizeOf("GhosttyString");
322
352
  return this.engine.scratch(size, (out) => {
@@ -328,6 +358,78 @@ export class Terminal {
328
358
  return this.engine.readString(out);
329
359
  });
330
360
  }
361
+ /** An untracked `GhosttyGridRef` to the viewport cell at `at`, valid
362
+ * until the terminal changes. */
363
+ gridRef(at) {
364
+ const e = this.engine;
365
+ const point = e.sizeOf("GhosttyPoint");
366
+ const ref = e.sizeOf("GhosttyGridRef");
367
+ const x = Math.min(Math.max(0, Math.floor(at.x)), this.cols - 1);
368
+ const y = Math.min(Math.max(0, Math.floor(at.y)), this.rows - 1);
369
+ return e.scratch(point + ref, (ptr) => {
370
+ e.memory.fill(0, ptr, ptr + point + ref);
371
+ e.view.setInt32(ptr + e.offsetOf("GhosttyPoint", "tag"), e.enumValue("GhosttyPointTag", "VIEWPORT"), true);
372
+ const coordinate = ptr + e.offsetOf("GhosttyPoint", "value");
373
+ e.view.setUint16(coordinate + e.offsetOf("GhosttyPointCoordinate", "x"), x, true);
374
+ e.view.setUint32(coordinate + e.offsetOf("GhosttyPointCoordinate", "y"), y, true);
375
+ e.view.setUint32(ptr + point, ref, true);
376
+ // The point is passed by value, which the wasm ABI passes by address.
377
+ e.check("ghostty_terminal_grid_ref", this.handle, ptr, ptr + point);
378
+ return e.memory.slice(ptr + point, ptr + point + ref);
379
+ });
380
+ }
381
+ /** Installs `selection` (a `GhosttySelection`) as the terminal's, which
382
+ * the terminal then tracks through output, scrolling and resizes, or
383
+ * clears it. */
384
+ select(selection) {
385
+ const option = this.engine.enumValue("GhosttyTerminalOption", "SELECTION");
386
+ if (!selection)
387
+ this.engine.check("ghostty_terminal_set", this.handle, option, 0);
388
+ else
389
+ this.engine.withBytes(selection, (ptr) => this.engine.check("ghostty_terminal_set", this.handle, option, ptr));
390
+ }
391
+ /** The selection's text: soft-wrapped lines joined, trailing blanks
392
+ * trimmed, as Ghostty copies it; undefined with no selection. */
393
+ selectionText() {
394
+ const e = this.engine;
395
+ const options = e.pack("GhosttyTerminalSelectionFormatOptions", {
396
+ emit: e.enumValue("GhosttyFormatterFormat", "PLAIN"),
397
+ unwrap: 1,
398
+ trim: 1,
399
+ });
400
+ return e.withBytes(options, (optionsPtr) => e.scratch(8, (out) => {
401
+ e.view.setUint32(out, 0, true);
402
+ e.view.setUint32(out + 4, 0, true);
403
+ // The options are passed by value, which the wasm ABI passes by address.
404
+ const code = e.call("ghostty_terminal_selection_format_alloc", this.handle, 0, optionsPtr, out, out + 4);
405
+ if (code === e.result.NO_VALUE)
406
+ return undefined;
407
+ if (code !== e.result.SUCCESS)
408
+ throw new EngineError("ghostty_terminal_selection_format_alloc", code);
409
+ const ptr = e.view.getUint32(out, true);
410
+ const len = e.view.getUint32(out + 4, true);
411
+ try {
412
+ return new TextDecoder().decode(e.memory.slice(ptr, ptr + len));
413
+ }
414
+ finally {
415
+ e.call("ghostty_free", 0, ptr, len);
416
+ }
417
+ }));
418
+ }
419
+ /** Whether the active screen has a selection. */
420
+ get selected() {
421
+ const e = this.engine;
422
+ const size = e.sizeOf("GhosttySelection");
423
+ return e.scratch(size, (out) => {
424
+ e.view.setUint32(out, size, true);
425
+ const code = e.call("ghostty_terminal_get", this.handle, e.enumValue("GhosttyTerminalData", "SELECTION"), out);
426
+ if (code === e.result.NO_VALUE)
427
+ return false;
428
+ if (code !== e.result.SUCCESS)
429
+ throw new EngineError("ghostty_terminal_get", code);
430
+ return true;
431
+ });
432
+ }
331
433
  /** Whether DEC private mode `number` is set. */
332
434
  mode(number) {
333
435
  const config = this.engine.pack("GhosttyTerminalModeConfig", { mode: number });
@@ -1,4 +1,4 @@
1
- import { type Engine, type Terminal } from "./index.ts";
1
+ import { type Engine, type Scrollbar, type Terminal } from "./index.ts";
2
2
  /** Style flag bits of a [`Cell`]. */
3
3
  export declare const FLAG: {
4
4
  readonly BOLD: 1;
@@ -32,6 +32,8 @@ type CursorStyle = (typeof CURSOR_STYLES)[number];
32
32
  export interface FrameRow {
33
33
  y: number;
34
34
  cells: Cell[];
35
+ /** The selected cells of the row, first and last inclusive. */
36
+ selection?: [number, number];
35
37
  }
36
38
  export interface Frame {
37
39
  cols: number;
@@ -50,6 +52,9 @@ export interface Frame {
50
52
  } | undefined;
51
53
  /** The rows that changed, or every row when `full`. */
52
54
  lines: FrameRow[];
55
+ /** Where the viewport is in the history: scrolled back when it ends
56
+ * above the last row (`offset + len < total`). */
57
+ scrollbar: Scrollbar;
53
58
  }
54
59
  /**
55
60
  * The engine's render state: updated from a terminal, read into a
@@ -69,6 +74,8 @@ export declare class RenderState {
69
74
  constructor(engine: Engine);
70
75
  /** Captures the terminal and returns the rows that changed since the last `clean`. */
71
76
  update(term: Terminal): Frame;
77
+ /** The row's selected cells, or undefined when the selection misses it. */
78
+ private rowSelection;
72
79
  private readRow;
73
80
  private color;
74
81
  private graphemes;
@@ -40,7 +40,7 @@ export class RenderState {
40
40
  const values = (name, members) => Object.fromEntries(members.map((m) => [m, engine.enumValue(name, m)]));
41
41
  this.keys = {
42
42
  data: values("GhosttyRenderStateData", ["COLS", "ROWS", "DIRTY", "ROW_ITERATOR", "COLORS", "CURSOR"]),
43
- row: values("GhosttyRenderStateRowData", ["CELLS"]),
43
+ row: values("GhosttyRenderStateRowData", ["CELLS", "SELECTION"]),
44
44
  cell: values("GhosttyRenderStateRowCellsData", [
45
45
  "RAW",
46
46
  "STYLE",
@@ -69,6 +69,8 @@ export class RenderState {
69
69
  update(term) {
70
70
  const e = this.engine;
71
71
  e.check("ghostty_render_state_update", this.state, term.handle);
72
+ // Read with the update: the render state does not keep the scroll position.
73
+ const scrollbar = term.scrollbar;
72
74
  const u16 = (key) => e.scratch(4, (out) => {
73
75
  e.check("ghostty_render_state_get", this.state, key, out);
74
76
  return e.view.getUint16(out, true);
@@ -110,10 +112,29 @@ export class RenderState {
110
112
  e.check("ghostty_render_state_get", this.state, this.keys.data["ROW_ITERATOR"], out);
111
113
  while (e.call("ghostty_render_state_row_iterator_next_dirty", this.iterator, out + 4)) {
112
114
  const y = e.view.getUint16(out + 4, true);
113
- lines.push({ y, cells: this.readRow(cols) });
115
+ const row = { y, cells: this.readRow(cols) };
116
+ const selection = this.rowSelection();
117
+ if (selection)
118
+ row.selection = selection;
119
+ lines.push(row);
114
120
  }
115
121
  });
116
- return { cols, rows, full, background, foreground, cursor, lines };
122
+ return { cols, rows, full, background, foreground, cursor, lines, scrollbar };
123
+ }
124
+ /** The row's selected cells, or undefined when the selection misses it. */
125
+ rowSelection() {
126
+ const e = this.engine;
127
+ const size = e.sizeOf("GhosttyRenderStateRowSelection");
128
+ return e.scratch(size, (out) => {
129
+ e.view.setUint32(out, size, true);
130
+ const code = e.call("ghostty_render_state_row_get", this.iterator, this.keys.row["SELECTION"], out);
131
+ if (code === e.result.NO_VALUE)
132
+ return undefined;
133
+ if (code !== e.result.SUCCESS)
134
+ throw new Error(`row selection: ${code}`);
135
+ const field = (key) => e.field("GhosttyRenderStateRowSelection", out, key);
136
+ return [field("start_x"), field("end_x")];
137
+ });
117
138
  }
118
139
  readRow(cols) {
119
140
  const e = this.engine;
@@ -0,0 +1,39 @@
1
+ import type { Engine, Terminal } from "./index.ts";
2
+ /** A point in the viewport in cells, fractions included: the pointer's
3
+ * place within its cell decides which cells a drag covers. */
4
+ export interface CellPoint {
5
+ x: number;
6
+ y: number;
7
+ }
8
+ /**
9
+ * Mouse selection through the engine's gesture: a press, then drags, then
10
+ * a release. A single press selects nothing; a drag selects from it by
11
+ * cells, a double press a word and a triple press a line, dragging by
12
+ * words or lines. The gesture tracks its anchor in the terminal, so
13
+ * output between press and drag does not move it.
14
+ */
15
+ export declare class SelectionGesture {
16
+ readonly engine: Engine;
17
+ private gesture;
18
+ private readonly events;
19
+ /** The terminal the gesture tracks its anchor in. */
20
+ private term;
21
+ constructor(engine: Engine);
22
+ /** Presses at `at` (`time` in ms); the selection to install, or
23
+ * undefined for none (a single press). */
24
+ press(term: Terminal, at: CellPoint, time: number): Uint8Array | undefined;
25
+ /** Drags to `at`; the selection from the press, or undefined when the
26
+ * pointer has not left the pressed cell. */
27
+ drag(term: Terminal, at: CellPoint): Uint8Array | undefined;
28
+ release(term: Terminal, at: CellPoint): void;
29
+ /** Starts afresh, for a terminal freed or about to be: `term` when it
30
+ * is still alive, to release the tracked anchor in it, else none. The
31
+ * caller says so, since a new terminal may have the handle of a freed
32
+ * one. */
33
+ forget(term?: Terminal): void;
34
+ /** A gesture is in one terminal. */
35
+ private follow;
36
+ private set;
37
+ private apply;
38
+ free(): void;
39
+ }