@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.
@@ -16,6 +16,8 @@ export class EngineError extends Error {
16
16
  export class Engine {
17
17
  exports;
18
18
  types;
19
+ memoryView;
20
+ dataView;
19
21
  /** The `GhosttyResult` members the wrapper branches on. */
20
22
  result;
21
23
  constructor(exports) {
@@ -34,12 +36,18 @@ export class Engine {
34
36
  const { instance } = await WebAssembly.instantiate(wasm, {});
35
37
  return new Engine(instance.exports);
36
38
  }
37
- /** The current linear memory; reacquired on every access because it may grow. */
39
+ /** Cached views are valid only until wasm grows its linear memory. */
38
40
  get memory() {
39
- return new Uint8Array(this.exports.memory.buffer);
41
+ const buffer = this.exports.memory.buffer;
42
+ if (this.memoryView?.buffer !== buffer)
43
+ this.memoryView = new Uint8Array(buffer);
44
+ return this.memoryView;
40
45
  }
41
46
  get view() {
42
- return new DataView(this.exports.memory.buffer);
47
+ const buffer = this.exports.memory.buffer;
48
+ if (this.dataView?.buffer !== buffer)
49
+ this.dataView = new DataView(buffer);
50
+ return this.dataView;
43
51
  }
44
52
  call(name, ...args) {
45
53
  const fn = this.exports[name];
@@ -53,6 +61,16 @@ export class Engine {
53
61
  if (code !== this.result.SUCCESS)
54
62
  throw new EngineError(name, code);
55
63
  }
64
+ /** Calls a function returning GhosttyResult: true for a value, false
65
+ * for `NO_VALUE`; throws on failure. */
66
+ present(name, ...args) {
67
+ const code = this.call(name, ...args);
68
+ if (code === this.result.NO_VALUE)
69
+ return false;
70
+ if (code !== this.result.SUCCESS)
71
+ throw new EngineError(name, code);
72
+ return true;
73
+ }
56
74
  alloc(len) {
57
75
  const ptr = this.call("ghostty_wasm_alloc", len);
58
76
  if (ptr === 0)
@@ -190,6 +208,12 @@ export class Engine {
190
208
  }
191
209
  /** Reads a bit field of a 64-bit packed value at `ptr`. */
192
210
  readBits(ptr, field) {
211
+ const bit = field.lsb % 32;
212
+ if (bit + field.width <= 32) {
213
+ const word = this.view.getUint32(ptr + 4 * Math.floor(field.lsb / 32), true) >>> bit;
214
+ // A 32-bit mask would be signed; preserve the unsigned full word.
215
+ return field.width === 32 ? word : word & (2 ** field.width - 1);
216
+ }
193
217
  const value = this.view.getBigUint64(ptr, true);
194
218
  return Number((value >> BigInt(field.lsb)) & ((1n << BigInt(field.width)) - 1n));
195
219
  }
@@ -349,14 +373,9 @@ export class Terminal {
349
373
  }
350
374
  get title() {
351
375
  const size = this.engine.sizeOf("GhosttyString");
352
- return this.engine.scratch(size, (out) => {
353
- const code = this.engine.call("ghostty_terminal_get", this.handle, this.engine.enumValue("GhosttyTerminalData", "TITLE"), out);
354
- if (code === this.engine.result.NO_VALUE)
355
- return "";
356
- if (code !== this.engine.result.SUCCESS)
357
- throw new EngineError("ghostty_terminal_get", code);
358
- return this.engine.readString(out);
359
- });
376
+ return this.engine.scratch(size, (out) => this.engine.present("ghostty_terminal_get", this.handle, this.engine.enumValue("GhosttyTerminalData", "TITLE"), out)
377
+ ? this.engine.readString(out)
378
+ : "");
360
379
  }
361
380
  /** An untracked `GhosttyGridRef` to the viewport cell at `at`, valid
362
381
  * until the terminal changes. */
@@ -401,11 +420,8 @@ export class Terminal {
401
420
  e.view.setUint32(out, 0, true);
402
421
  e.view.setUint32(out + 4, 0, true);
403
422
  // 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)
423
+ if (!e.present("ghostty_terminal_selection_format_alloc", this.handle, 0, optionsPtr, out, out + 4))
406
424
  return undefined;
407
- if (code !== e.result.SUCCESS)
408
- throw new EngineError("ghostty_terminal_selection_format_alloc", code);
409
425
  const ptr = e.view.getUint32(out, true);
410
426
  const len = e.view.getUint32(out + 4, true);
411
427
  try {
@@ -422,12 +438,7 @@ export class Terminal {
422
438
  const size = e.sizeOf("GhosttySelection");
423
439
  return e.scratch(size, (out) => {
424
440
  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;
441
+ return e.present("ghostty_terminal_get", this.handle, e.enumValue("GhosttyTerminalData", "SELECTION"), out);
431
442
  });
432
443
  }
433
444
  /** Whether DEC private mode `number` is set. */
@@ -29,13 +29,13 @@ export interface Cell {
29
29
  /** `GhosttyRenderStateCursorVisualStyle` by name. */
30
30
  declare const CURSOR_STYLES: readonly ["bar", "block", "underline", "block_hollow"];
31
31
  type CursorStyle = (typeof CURSOR_STYLES)[number];
32
- export interface FrameRow {
32
+ export interface FrameRow<Cells = Cell[]> {
33
33
  y: number;
34
- cells: Cell[];
34
+ cells: Cells;
35
35
  /** The selected cells of the row, first and last inclusive. */
36
36
  selection?: [number, number];
37
37
  }
38
- export interface Frame {
38
+ export interface Frame<Cells = Cell[]> {
39
39
  cols: number;
40
40
  rows: number;
41
41
  /** Every row is included and the renderer should clear first. */
@@ -51,11 +51,22 @@ export interface Frame {
51
51
  color: number;
52
52
  } | undefined;
53
53
  /** The rows that changed, or every row when `full`. */
54
- lines: FrameRow[];
54
+ lines: FrameRow<Cells>[];
55
55
  /** Where the viewport is in the history: scrolled back when it ends
56
56
  * above the last row (`offset + len < total`). */
57
57
  scrollbar: Scrollbar;
58
58
  }
59
+ /** Four signed words per cell: text code, foreground, background, style.
60
+ * Text is a Unicode scalar (0 for blank), or -(grapheme index + 1).
61
+ * Style holds flags in its low 16 bits and underline in its high 16. */
62
+ export declare const PACKED_STRIDE = 4;
63
+ export interface PackedCells {
64
+ data: Int32Array<ArrayBuffer>;
65
+ /** Only multi-codepoint cells need strings; these are cloned on transfer. */
66
+ graphemes: string[];
67
+ }
68
+ export type PackedFrame = Frame<PackedCells>;
69
+ export declare function packedText(cells: PackedCells, x: number): string;
59
70
  /**
60
71
  * The engine's render state: updated from a terminal, read into a
61
72
  * [`Frame`] of the rows that changed, then cleaned.
@@ -74,12 +85,16 @@ export declare class RenderState {
74
85
  constructor(engine: Engine);
75
86
  /** Captures the terminal and returns the rows that changed since the last `clean`. */
76
87
  update(term: Terminal): Frame;
88
+ /** Captures transferable cell buffers without allocating Cell objects.
89
+ * Each row owns its buffer so the renderer can retain rows independently. */
90
+ updatePacked(term: Terminal): PackedFrame;
91
+ private frame;
77
92
  /** The row's selected cells, or undefined when the selection misses it. */
78
93
  private rowSelection;
79
94
  private readRow;
80
95
  private color;
81
96
  private graphemes;
82
- /** Marks the frame as drawn. */
97
+ /** Clears the captured dirty rows; later terminal writes remain dirty. */
83
98
  clean(): void;
84
99
  free(): void;
85
100
  }
@@ -1,3 +1,4 @@
1
+ import { EngineError } from "./index.js";
1
2
  /** Style flag bits of a [`Cell`]. */
2
3
  export const FLAG = {
3
4
  BOLD: 1,
@@ -17,6 +18,14 @@ export const FLAG = {
17
18
  export const NO_COLOR = -1;
18
19
  /** `GhosttyRenderStateCursorVisualStyle` by name. */
19
20
  const CURSOR_STYLES = ["bar", "block", "underline", "block_hollow"];
21
+ /** Four signed words per cell: text code, foreground, background, style.
22
+ * Text is a Unicode scalar (0 for blank), or -(grapheme index + 1).
23
+ * Style holds flags in its low 16 bits and underline in its high 16. */
24
+ export const PACKED_STRIDE = 4;
25
+ export function packedText(cells, x) {
26
+ const code = cells.data[x * PACKED_STRIDE];
27
+ return code < 0 ? cells.graphemes[-code - 1] : code === 0 ? "" : String.fromCodePoint(code);
28
+ }
20
29
  /**
21
30
  * The engine's render state: updated from a terminal, read into a
22
31
  * [`Frame`] of the rows that changed, then cleaned.
@@ -67,6 +76,31 @@ export class RenderState {
67
76
  }
68
77
  /** Captures the terminal and returns the rows that changed since the last `clean`. */
69
78
  update(term) {
79
+ return this.frame(term, (cols) => {
80
+ const cells = [];
81
+ this.readRow(cols, (codepoint, text, fg, bg, flags, underline) => {
82
+ cells.push({ text: codepoint ? String.fromCodePoint(codepoint) : text, fg, bg, flags, underline });
83
+ });
84
+ return cells;
85
+ });
86
+ }
87
+ /** Captures transferable cell buffers without allocating Cell objects.
88
+ * Each row owns its buffer so the renderer can retain rows independently. */
89
+ updatePacked(term) {
90
+ return this.frame(term, (cols) => {
91
+ const data = new Int32Array(cols * PACKED_STRIDE);
92
+ const graphemes = [];
93
+ let at = 0;
94
+ this.readRow(cols, (codepoint, text, fg, bg, flags, underline) => {
95
+ data[at++] = text === "" ? codepoint : -graphemes.push(text);
96
+ data[at++] = fg;
97
+ data[at++] = bg;
98
+ data[at++] = flags | (underline << 16);
99
+ });
100
+ return { data: data.subarray(0, at), graphemes };
101
+ });
102
+ }
103
+ frame(term, readRow) {
70
104
  const e = this.engine;
71
105
  e.check("ghostty_render_state_update", this.state, term.handle);
72
106
  // Read with the update: the render state does not keep the scroll position.
@@ -112,7 +146,7 @@ export class RenderState {
112
146
  e.check("ghostty_render_state_get", this.state, this.keys.data["ROW_ITERATOR"], out);
113
147
  while (e.call("ghostty_render_state_row_iterator_next_dirty", this.iterator, out + 4)) {
114
148
  const y = e.view.getUint16(out + 4, true);
115
- const row = { y, cells: this.readRow(cols) };
149
+ const row = { y, cells: readRow(cols) };
116
150
  const selection = this.rowSelection();
117
151
  if (selection)
118
152
  row.selection = selection;
@@ -127,23 +161,20 @@ export class RenderState {
127
161
  const size = e.sizeOf("GhosttyRenderStateRowSelection");
128
162
  return e.scratch(size, (out) => {
129
163
  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)
164
+ if (!e.present("ghostty_render_state_row_get", this.iterator, this.keys.row["SELECTION"], out))
132
165
  return undefined;
133
- if (code !== e.result.SUCCESS)
134
- throw new Error(`row selection: ${code}`);
135
166
  const field = (key) => e.field("GhosttyRenderStateRowSelection", out, key);
136
167
  return [field("start_x"), field("end_x")];
137
168
  });
138
169
  }
139
- readRow(cols) {
170
+ readRow(cols, write) {
140
171
  const e = this.engine;
141
172
  e.scratch(4, (out) => {
142
173
  e.view.setUint32(out, this.cells, true);
143
174
  e.check("ghostty_render_state_row_get", this.iterator, this.keys.row["CELLS"], out);
144
175
  });
145
176
  const styleSize = e.sizeOf("GhosttyStyle");
146
- const cells = [];
177
+ let count = 0;
147
178
  // Scratch: raw cell (8), colour (3, padded to 8), the 8-aligned style,
148
179
  // a UTF-8 buffer struct and its bytes.
149
180
  const utf8Cap = 64;
@@ -153,15 +184,14 @@ export class RenderState {
153
184
  const style = scratch + 16;
154
185
  const buffer = style + styleSize;
155
186
  const utf8 = buffer + e.sizeOf("GhosttyBuffer");
156
- while (e.call("ghostty_render_state_row_cells_next", this.cells) && cells.length < cols) {
187
+ while (e.call("ghostty_render_state_row_cells_next", this.cells) && count < cols) {
157
188
  e.check("ghostty_render_state_row_cells_get", this.cells, this.keys.cell["RAW"], raw);
158
189
  const tag = e.readBits(raw, this.cell.tag);
159
190
  const wide = e.readBits(raw, this.cell.wide);
191
+ let codepoint = 0;
160
192
  let text = "";
161
193
  if (tag === this.tags.codepoint) {
162
- const cp = e.readBits(raw, this.cell.codepoint);
163
- if (cp !== 0)
164
- text = String.fromCodePoint(cp);
194
+ codepoint = e.readBits(raw, this.cell.codepoint);
165
195
  }
166
196
  else if (tag === this.tags.grapheme) {
167
197
  text = this.graphemes(buffer, utf8, utf8Cap);
@@ -197,10 +227,10 @@ export class RenderState {
197
227
  flags |= FLAG.OVERLINE;
198
228
  underline = e.field("GhosttyStyle", style, "underline");
199
229
  }
200
- cells.push({ text, fg, bg, flags, underline });
230
+ write(codepoint, text, fg, bg, flags, underline);
231
+ count++;
201
232
  }
202
233
  });
203
- return cells;
204
234
  }
205
235
  color(key, out) {
206
236
  const e = this.engine;
@@ -208,7 +238,7 @@ export class RenderState {
208
238
  if (code === e.result.INVALID_VALUE)
209
239
  return NO_COLOR;
210
240
  if (code !== e.result.SUCCESS)
211
- throw new Error(`cell colour: ${code}`);
241
+ throw new EngineError("ghostty_render_state_row_cells_get", code);
212
242
  return e.readRgb(out);
213
243
  }
214
244
  graphemes(buffer, utf8, cap) {
@@ -222,7 +252,7 @@ export class RenderState {
222
252
  return new TextDecoder().decode(e.memory.slice(utf8, utf8 + len));
223
253
  }
224
254
  if (code !== e.result.OUT_OF_SPACE)
225
- throw new Error(`cell graphemes: ${code}`);
255
+ throw new EngineError("ghostty_render_state_row_cells_get", code);
226
256
  // The buffer struct reports the needed length; retry through it.
227
257
  const needed = e.field("GhosttyBuffer", buffer, "len");
228
258
  return new TextDecoder().decode(e.growing("ghostty_render_state_row_cells_get", needed, (big, bigCap, len) => {
@@ -233,7 +263,7 @@ export class RenderState {
233
263
  return again;
234
264
  }));
235
265
  }
236
- /** Marks the frame as drawn. */
266
+ /** Clears the captured dirty rows; later terminal writes remain dirty. */
237
267
  clean() {
238
268
  this.engine.check("ghostty_render_state_clean", this.state);
239
269
  }
@@ -85,11 +85,8 @@ export class SelectionGesture {
85
85
  return e.scratch(size, (out) => {
86
86
  e.memory.fill(0, out, out + size);
87
87
  e.view.setUint32(out, size, true);
88
- const code = e.call("ghostty_selection_gesture_event", this.gesture, term.handle, event, out);
89
- if (code === e.result.NO_VALUE)
88
+ if (!e.present("ghostty_selection_gesture_event", this.gesture, term.handle, event, out))
90
89
  return undefined;
91
- if (code !== e.result.SUCCESS)
92
- throw new Error(`selection gesture: ${code}`);
93
90
  return e.memory.slice(out, out + size);
94
91
  });
95
92
  }