@bigpixelrocket/uiok 0.0.0-stage → 0.1.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.
Files changed (280) hide show
  1. package/CHANGELOG.md +38 -0
  2. package/LICENSE +21 -0
  3. package/NOTICE +569 -0
  4. package/README.md +44 -2
  5. package/dist/VisuallyHidden.d.ts +13 -0
  6. package/dist/VisuallyHidden.js +13 -0
  7. package/dist/activity/ActivityBar.d.ts +29 -0
  8. package/dist/activity/ActivityBar.js +21 -0
  9. package/dist/activity/activity.css +43 -0
  10. package/dist/activity/index.d.ts +2 -0
  11. package/dist/activity/index.js +2 -0
  12. package/dist/button/Button.d.ts +26 -0
  13. package/dist/button/Button.js +14 -0
  14. package/dist/button/IconButton.d.ts +18 -0
  15. package/dist/button/IconButton.js +14 -0
  16. package/dist/button/button.css +95 -0
  17. package/dist/button/index.d.ts +3 -0
  18. package/dist/button/index.js +3 -0
  19. package/dist/charts/Drawing.d.ts +27 -0
  20. package/dist/charts/Drawing.js +117 -0
  21. package/dist/charts/Drawing.logic.d.ts +2 -0
  22. package/dist/charts/Drawing.logic.js +22 -0
  23. package/dist/charts/Line.logic.d.ts +33 -0
  24. package/dist/charts/Line.logic.js +72 -0
  25. package/dist/charts/LineChart.d.ts +34 -0
  26. package/dist/charts/LineChart.js +100 -0
  27. package/dist/charts/Pie.logic.d.ts +16 -0
  28. package/dist/charts/Pie.logic.js +28 -0
  29. package/dist/charts/PieChart.d.ts +20 -0
  30. package/dist/charts/PieChart.js +16 -0
  31. package/dist/charts/ResultChart.d.ts +47 -0
  32. package/dist/charts/ResultChart.js +175 -0
  33. package/dist/charts/ResultChart.logic.d.ts +42 -0
  34. package/dist/charts/ResultChart.logic.js +165 -0
  35. package/dist/charts/Scatter.logic.d.ts +55 -0
  36. package/dist/charts/Scatter.logic.js +134 -0
  37. package/dist/charts/ScatterChart.d.ts +36 -0
  38. package/dist/charts/ScatterChart.js +99 -0
  39. package/dist/charts/charts.css +310 -0
  40. package/dist/charts/index.d.ts +14 -0
  41. package/dist/charts/index.js +11 -0
  42. package/dist/charts/seriesColour.d.ts +2 -0
  43. package/dist/charts/seriesColour.js +8 -0
  44. package/dist/clock/index.d.ts +2 -0
  45. package/dist/clock/index.js +2 -0
  46. package/dist/clock/useClock.d.ts +14 -0
  47. package/dist/clock/useClock.js +57 -0
  48. package/dist/datetime/DateTimePicker.d.ts +50 -0
  49. package/dist/datetime/DateTimePicker.js +98 -0
  50. package/dist/datetime/DateTimePicker.logic.d.ts +59 -0
  51. package/dist/datetime/DateTimePicker.logic.js +103 -0
  52. package/dist/datetime/datetime.css +115 -0
  53. package/dist/datetime/index.d.ts +7 -0
  54. package/dist/datetime/index.js +7 -0
  55. package/dist/dialog/ConfirmDialog.d.ts +73 -0
  56. package/dist/dialog/ConfirmDialog.js +30 -0
  57. package/dist/dialog/DialogLegend.d.ts +21 -0
  58. package/dist/dialog/DialogLegend.js +28 -0
  59. package/dist/dialog/DialogLegend.logic.d.ts +145 -0
  60. package/dist/dialog/DialogLegend.logic.js +71 -0
  61. package/dist/dialog/ModalDialog.d.ts +101 -0
  62. package/dist/dialog/ModalDialog.js +184 -0
  63. package/dist/dialog/dialog.css +283 -0
  64. package/dist/dialog/index.d.ts +8 -0
  65. package/dist/dialog/index.js +8 -0
  66. package/dist/filter/FilterEscape.d.ts +16 -0
  67. package/dist/filter/FilterEscape.js +15 -0
  68. package/dist/filter/FilterIcon.d.ts +8 -0
  69. package/dist/filter/FilterIcon.js +11 -0
  70. package/dist/filter/filter.css +42 -0
  71. package/dist/filter/index.d.ts +3 -0
  72. package/dist/filter/index.js +3 -0
  73. package/dist/grid/DataGrid.d.ts +149 -0
  74. package/dist/grid/DataGrid.js +373 -0
  75. package/dist/grid/DataGrid.logic.d.ts +57 -0
  76. package/dist/grid/DataGrid.logic.js +121 -0
  77. package/dist/grid/grid.css +206 -0
  78. package/dist/grid/index.d.ts +7 -0
  79. package/dist/grid/index.js +7 -0
  80. package/dist/index.d.ts +32 -0
  81. package/dist/index.js +32 -0
  82. package/dist/keyboard/BrowserKeys.d.ts +15 -0
  83. package/dist/keyboard/BrowserKeys.js +28 -0
  84. package/dist/keyboard/KeyChord.logic.d.ts +25 -0
  85. package/dist/keyboard/KeyChord.logic.js +50 -0
  86. package/dist/keyboard/Keyboard.logic.d.ts +84 -0
  87. package/dist/keyboard/Keyboard.logic.js +137 -0
  88. package/dist/keyboard/OverlayWatch.d.ts +28 -0
  89. package/dist/keyboard/OverlayWatch.js +119 -0
  90. package/dist/keyboard/PageSelectAll.d.ts +14 -0
  91. package/dist/keyboard/PageSelectAll.js +22 -0
  92. package/dist/keyboard/index.d.ts +9 -0
  93. package/dist/keyboard/index.js +9 -0
  94. package/dist/keychord/KeyChord.d.ts +16 -0
  95. package/dist/keychord/KeyChord.js +55 -0
  96. package/dist/keychord/index.d.ts +2 -0
  97. package/dist/keychord/index.js +2 -0
  98. package/dist/keychord/keychord.css +41 -0
  99. package/dist/labels/UiokLabels.d.ts +41 -0
  100. package/dist/labels/UiokLabels.js +31 -0
  101. package/dist/labels/UiokProvider.d.ts +44 -0
  102. package/dist/labels/UiokProvider.js +54 -0
  103. package/dist/labels/charts.d.ts +34 -0
  104. package/dist/labels/charts.js +15 -0
  105. package/dist/labels/dateTime.d.ts +32 -0
  106. package/dist/labels/dateTime.js +14 -0
  107. package/dist/labels/dialog.d.ts +18 -0
  108. package/dist/labels/dialog.js +6 -0
  109. package/dist/labels/index.d.ts +13 -0
  110. package/dist/labels/index.js +13 -0
  111. package/dist/labels/keys.d.ts +28 -0
  112. package/dist/labels/keys.js +53 -0
  113. package/dist/labels/legend.d.ts +21 -0
  114. package/dist/labels/legend.js +7 -0
  115. package/dist/labels/listing.d.ts +16 -0
  116. package/dist/labels/listing.js +8 -0
  117. package/dist/labels/pager.d.ts +32 -0
  118. package/dist/labels/pager.js +20 -0
  119. package/dist/labels/palette.d.ts +17 -0
  120. package/dist/labels/palette.js +6 -0
  121. package/dist/labels/selectAll.d.ts +15 -0
  122. package/dist/labels/selectAll.js +6 -0
  123. package/dist/labels/terminal.d.ts +25 -0
  124. package/dist/labels/terminal.js +9 -0
  125. package/dist/legend/KeyLegend.logic.d.ts +84 -0
  126. package/dist/legend/KeyLegend.logic.js +109 -0
  127. package/dist/legend/KeyLegendStrip.d.ts +36 -0
  128. package/dist/legend/KeyLegendStrip.js +82 -0
  129. package/dist/legend/index.d.ts +3 -0
  130. package/dist/legend/index.js +3 -0
  131. package/dist/legend/legend.css +148 -0
  132. package/dist/listing/CurrentDot.d.ts +15 -0
  133. package/dist/listing/CurrentDot.js +13 -0
  134. package/dist/listing/Listing.d.ts +230 -0
  135. package/dist/listing/Listing.js +265 -0
  136. package/dist/listing/PathParts.logic.d.ts +17 -0
  137. package/dist/listing/PathParts.logic.js +18 -0
  138. package/dist/listing/index.d.ts +10 -0
  139. package/dist/listing/index.js +10 -0
  140. package/dist/listing/listing.css +867 -0
  141. package/dist/menu/MenuQuery.logic.d.ts +69 -0
  142. package/dist/menu/MenuQuery.logic.js +75 -0
  143. package/dist/menu/fuzzyMatch.d.ts +31 -0
  144. package/dist/menu/fuzzyMatch.js +296 -0
  145. package/dist/menu/index.d.ts +9 -0
  146. package/dist/menu/index.js +9 -0
  147. package/dist/menu/menu.css +203 -0
  148. package/dist/menu/useBellBeat.d.ts +8 -0
  149. package/dist/menu/useBellBeat.js +26 -0
  150. package/dist/namecut/NameCut.d.ts +22 -0
  151. package/dist/namecut/NameCut.js +28 -0
  152. package/dist/namecut/NameCut.logic.d.ts +51 -0
  153. package/dist/namecut/NameCut.logic.js +120 -0
  154. package/dist/namecut/index.d.ts +3 -0
  155. package/dist/namecut/index.js +3 -0
  156. package/dist/namecut/namecut.css +67 -0
  157. package/dist/pager/Pager.d.ts +37 -0
  158. package/dist/pager/Pager.js +38 -0
  159. package/dist/pager/Pager.logic.d.ts +13 -0
  160. package/dist/pager/Pager.logic.js +63 -0
  161. package/dist/pager/index.d.ts +7 -0
  162. package/dist/pager/index.js +7 -0
  163. package/dist/pager/pager.css +62 -0
  164. package/dist/palette/Palette.d.ts +79 -0
  165. package/dist/palette/Palette.js +60 -0
  166. package/dist/palette/index.d.ts +6 -0
  167. package/dist/palette/index.js +6 -0
  168. package/dist/palette/palette.css +159 -0
  169. package/dist/pane/PaneActions.d.ts +104 -0
  170. package/dist/pane/PaneActions.js +62 -0
  171. package/dist/pane/PaneFrame.d.ts +51 -0
  172. package/dist/pane/PaneFrame.js +28 -0
  173. package/dist/pane/PaneKeys.d.ts +41 -0
  174. package/dist/pane/PaneKeys.js +104 -0
  175. package/dist/pane/PaneKeys.logic.d.ts +95 -0
  176. package/dist/pane/PaneKeys.logic.js +109 -0
  177. package/dist/pane/index.d.ts +11 -0
  178. package/dist/pane/index.js +11 -0
  179. package/dist/pane/usePaneKeys.d.ts +141 -0
  180. package/dist/pane/usePaneKeys.js +313 -0
  181. package/dist/run/RunHeader.d.ts +50 -0
  182. package/dist/run/RunHeader.js +31 -0
  183. package/dist/run/RunProgress.logic.d.ts +29 -0
  184. package/dist/run/RunProgress.logic.js +34 -0
  185. package/dist/run/index.d.ts +3 -0
  186. package/dist/run/index.js +3 -0
  187. package/dist/run/run.css +190 -0
  188. package/dist/segmented/SegmentedChoice.d.ts +22 -0
  189. package/dist/segmented/SegmentedChoice.js +31 -0
  190. package/dist/segmented/index.d.ts +2 -0
  191. package/dist/segmented/index.js +2 -0
  192. package/dist/segmented/segmented.css +49 -0
  193. package/dist/selectall/CheckRange.logic.d.ts +8 -0
  194. package/dist/selectall/CheckRange.logic.js +23 -0
  195. package/dist/selectall/SelectAllBar.d.ts +25 -0
  196. package/dist/selectall/SelectAllBar.js +24 -0
  197. package/dist/selectall/index.d.ts +7 -0
  198. package/dist/selectall/index.js +7 -0
  199. package/dist/selectall/selectall.css +31 -0
  200. package/dist/store/KeepUnchanged.logic.d.ts +19 -0
  201. package/dist/store/KeepUnchanged.logic.js +33 -0
  202. package/dist/store/SameProps.d.ts +15 -0
  203. package/dist/store/SameProps.js +46 -0
  204. package/dist/store/ValueStore.d.ts +17 -0
  205. package/dist/store/ValueStore.js +23 -0
  206. package/dist/store/index.d.ts +8 -0
  207. package/dist/store/index.js +8 -0
  208. package/dist/store/useStableHandlers.d.ts +13 -0
  209. package/dist/store/useStableHandlers.js +22 -0
  210. package/dist/styles.css +85 -0
  211. package/dist/tabs/PageTabs.d.ts +38 -0
  212. package/dist/tabs/PageTabs.js +33 -0
  213. package/dist/tabs/index.d.ts +2 -0
  214. package/dist/tabs/index.js +2 -0
  215. package/dist/tabs/tabs.css +64 -0
  216. package/dist/terminal/Terminal.d.ts +104 -0
  217. package/dist/terminal/Terminal.js +309 -0
  218. package/dist/terminal/Terminal.logic.d.ts +66 -0
  219. package/dist/terminal/Terminal.logic.js +156 -0
  220. package/dist/terminal/TerminalMenu.d.ts +36 -0
  221. package/dist/terminal/TerminalMenu.js +87 -0
  222. package/dist/terminal/TerminalMenu.logic.d.ts +78 -0
  223. package/dist/terminal/TerminalMenu.logic.js +68 -0
  224. package/dist/terminal/TerminalScrollback.d.ts +10 -0
  225. package/dist/terminal/TerminalScrollback.js +11 -0
  226. package/dist/terminal/ghostty/LICENSE +21 -0
  227. package/dist/terminal/ghostty/core.d.ts +315 -0
  228. package/dist/terminal/ghostty/core.js +1189 -0
  229. package/dist/terminal/ghostty/fallbackColors.d.ts +12 -0
  230. package/dist/terminal/ghostty/fallbackColors.js +23 -0
  231. package/dist/terminal/ghostty/fonts/LICENSE +21 -0
  232. package/dist/terminal/ghostty/fonts/SymbolsNerdFontMono-Regular.woff2 +0 -0
  233. package/dist/terminal/ghostty/keyCodes.logic.d.ts +20 -0
  234. package/dist/terminal/ghostty/keyCodes.logic.js +249 -0
  235. package/dist/terminal/ghostty/links.logic.d.ts +39 -0
  236. package/dist/terminal/ghostty/links.logic.js +84 -0
  237. package/dist/terminal/ghostty/renderer.d.ts +98 -0
  238. package/dist/terminal/ghostty/renderer.js +481 -0
  239. package/dist/terminal/ghostty/runtime.d.ts +126 -0
  240. package/dist/terminal/ghostty/runtime.js +346 -0
  241. package/dist/terminal/ghostty/spriteGlyphs.logic.d.ts +64 -0
  242. package/dist/terminal/ghostty/spriteGlyphs.logic.js +546 -0
  243. package/dist/terminal/ghostty/surface.d.ts +285 -0
  244. package/dist/terminal/ghostty/surface.js +1565 -0
  245. package/dist/terminal/ghostty/surface.logic.d.ts +181 -0
  246. package/dist/terminal/ghostty/surface.logic.js +392 -0
  247. package/dist/terminal/ghostty/vendor/LICENSE +21 -0
  248. package/dist/terminal/ghostty/vendor/ghostty-effects.wasm +0 -0
  249. package/dist/terminal/ghostty/vendor/ghostty-vt.wasm +0 -0
  250. package/dist/terminal/index.d.ts +12 -0
  251. package/dist/terminal/index.js +12 -0
  252. package/dist/terminal/terminal.css +169 -0
  253. package/dist/text/MarkedText.d.ts +14 -0
  254. package/dist/text/MarkedText.js +11 -0
  255. package/dist/text/highlightSegments.d.ts +13 -0
  256. package/dist/text/highlightSegments.js +29 -0
  257. package/dist/text/index.d.ts +3 -0
  258. package/dist/text/index.js +3 -0
  259. package/dist/text/text.css +11 -0
  260. package/dist/themes/attributes.d.ts +21 -0
  261. package/dist/themes/attributes.js +41 -0
  262. package/dist/themes/catalog.d.ts +125 -0
  263. package/dist/themes/catalog.js +940 -0
  264. package/dist/themes/color.d.ts +29 -0
  265. package/dist/themes/color.js +52 -0
  266. package/dist/themes/ids.d.ts +139 -0
  267. package/dist/themes/ids.js +59 -0
  268. package/dist/themes/index.d.ts +12 -0
  269. package/dist/themes/index.js +12 -0
  270. package/dist/themes/themes.generated.css +1830 -0
  271. package/dist/themes/tokens.d.ts +189 -0
  272. package/dist/themes/tokens.js +462 -0
  273. package/dist/tooltip/Tooltip.d.ts +21 -0
  274. package/dist/tooltip/Tooltip.js +105 -0
  275. package/dist/tooltip/Tooltip.logic.d.ts +49 -0
  276. package/dist/tooltip/Tooltip.logic.js +50 -0
  277. package/dist/tooltip/index.d.ts +3 -0
  278. package/dist/tooltip/index.js +3 -0
  279. package/dist/tooltip/tooltip.css +45 -0
  280. package/package.json +91 -4
@@ -0,0 +1,1189 @@
1
+ /**
2
+ * One terminal's libghostty-vt handles: VT parsing, render snapshots, key,
3
+ * paste, and mouse encoding, selection, and scrollback, translated from the C
4
+ * ABI into plain values. Every handle is freed by `dispose`.
5
+ */
6
+ import { ghosttyConsumedMods, ghosttyKeyForCode, ghosttyUnshiftedCodepoint } from './keyCodes.logic.js';
7
+ import { GhosttyRuntime, loadGhosttyRuntime } from './runtime.js';
8
+ import { ENGINE_DEFAULT_BACKGROUND, ENGINE_DEFAULT_FOREGROUND } from './fallbackColors.js';
9
+ /**
10
+ * How many terminals one page's shared engine memory is budgeted for: sixteen
11
+ * interactive terminals and one read-only log. Every terminal on a page
12
+ * shares one WebAssembly memory, which wasm32 caps at 4 GiB, so each
13
+ * terminal's history ceiling is a share of it.
14
+ */
15
+ export const GHOSTTY_BUDGETED_TERMINALS = 17;
16
+ const GHOSTTY_SUCCESS = 0;
17
+ const GHOSTTY_OUT_OF_SPACE = -3;
18
+ /**
19
+ * The most memory one terminal's history may take. Every terminal in a
20
+ * window shares one WebAssembly memory, which wasm32 caps at 4 GiB; at this
21
+ * ceiling a full page (`GHOSTTY_BUDGETED_TERMINALS` terminals) holds at most 3 GiB of history, leaving the rest for screens and
22
+ * parsing. It binds only at the largest length on very wide grids (50,000
23
+ * lines past about 445 columns), where a terminal keeps fewer lines instead
24
+ * of exhausting the shared memory.
25
+ */
26
+ const SCROLLBACK_MAX_BYTES = Math.floor((3 * 1024 ** 3) / GHOSTTY_BUDGETED_TERMINALS);
27
+ /**
28
+ * The bytes a standard page of the engine's grid holds for row headers and
29
+ * cells (Ghostty `fb13fa9`, wasm32: a 448 KiB page less its style, grapheme,
30
+ * string, and hyperlink tables). `runtimeAbi.test.ts` pins it, through
31
+ * `ghosttyPageRows`, against the engine's own pages.
32
+ */
33
+ const PAGE_GRID_BYTES = 436_784;
34
+ /** Bytes of a row header (`Row`) and of a cell (`Cell`) in the engine's grid. */
35
+ const PAGE_ROW_BYTES = 8;
36
+ const PAGE_CELL_BYTES = 8;
37
+ /** The alignment of a page's cell array, which follows its row headers. */
38
+ const PAGE_CELLS_ALIGN = 64;
39
+ /** The rows of a page too wide for a standard one, which the engine sizes up instead. */
40
+ const PAGE_STANDARD_ROWS = 215;
41
+ /** `GHOSTTY_TERMINAL_OPT_COLOR_PALETTE`: the default 256-color palette, as `GhosttyColorRgb[256]`. */
42
+ const OPTION_COLOR_PALETTE = 14;
43
+ /** Entries in the palette the option takes. */
44
+ const GHOSTTY_PALETTE_SIZE = 256;
45
+ /** `GHOSTTY_TERMINAL_OPT_SCROLLBACK_MAX_BYTES`: the history's byte budget, as `size_t*`. */
46
+ const OPTION_SCROLLBACK_MAX_BYTES = 27;
47
+ /** `GHOSTTY_TERMINAL_OPT_SCROLLBACK_MAX_LINES`: the history's physical row limit, as `size_t*`. */
48
+ const OPTION_SCROLLBACK_MAX_LINES = 28;
49
+ /** `GHOSTTY_TERMINAL_OPT_MODE`: sets a mode's current value, as `GhosttyTerminalModeConfig*`. */
50
+ const OPTION_MODE = 34;
51
+ /** `GHOSTTY_TERMINAL_DATA_MODE`: reads a mode's current value into a `GhosttyTerminalModeConfig`. */
52
+ const DATA_MODE = 37;
53
+ /** The DEC private modes the adapter reads or sets (`GhosttyMode` without the ANSI bit). */
54
+ const DEC_MODE = {
55
+ cursorKeys: 1,
56
+ anyEventMouse: 1003,
57
+ bracketedPaste: 2004,
58
+ synchronizedOutput: 2026,
59
+ colorSchemeReport: 2031
60
+ };
61
+ /** wasm32's `size_t`, the width of every written-length out-parameter. */
62
+ const USIZE_BYTES = 4;
63
+ /**
64
+ * The unsolicited reports a program that enabled DEC mode 2031 receives when
65
+ * the scheme changes; they are byte for byte the engine's own `CSI ? 996 n`
66
+ * answers.
67
+ */
68
+ const COLOR_SCHEME_REPORT = {
69
+ dark: '\x1b[?997;1n',
70
+ light: '\x1b[?997;2n'
71
+ };
72
+ const RENDER_DATA = {
73
+ cols: 1,
74
+ rows: 2,
75
+ dirty: 3,
76
+ rowIterator: 4,
77
+ background: 5,
78
+ foreground: 6,
79
+ cursor: 7,
80
+ cursorHasValue: 8,
81
+ cursorStyle: 10,
82
+ cursorVisible: 11,
83
+ cursorBlinking: 12,
84
+ cursorInViewport: 14,
85
+ cursorX: 15,
86
+ cursorY: 16
87
+ };
88
+ const ROW_DATA = {
89
+ dirty: 1,
90
+ raw: 2,
91
+ cells: 3
92
+ };
93
+ const CELL_DATA = {
94
+ raw: 1,
95
+ style: 2,
96
+ graphemesLength: 3,
97
+ graphemes: 4,
98
+ background: 5,
99
+ foreground: 6,
100
+ selected: 7
101
+ };
102
+ /** The `GhosttyStyle` fields a drawn cell reads; `underline` is an `i32`, the rest single bytes. */
103
+ const STYLE_FLAGS = [
104
+ 'inverse',
105
+ 'faint',
106
+ 'bold',
107
+ 'italic',
108
+ 'invisible',
109
+ 'strikethrough',
110
+ 'overline',
111
+ 'underline'
112
+ ];
113
+ /** Colors kept as shared objects before the table is dropped wholesale. */
114
+ const COLOR_TABLE_LIMIT = 4096;
115
+ const RAW_CELL_DATA = {
116
+ wide: 3
117
+ };
118
+ /** Ghostty's cell width classes: a wide glyph's second column is its spacer tail. */
119
+ export const GHOSTTY_CELL_WIDE = {
120
+ narrow: 0,
121
+ wide: 1,
122
+ spacerTail: 2,
123
+ spacerHead: 3
124
+ };
125
+ const decoder = new TextDecoder();
126
+ const encoder = new TextEncoder();
127
+ let keyboardLayoutMapPromise;
128
+ /** The browser's keyboard layout map, read once per page; undefined where the API is missing. */
129
+ function loadGhosttyKeyboardLayoutMap() {
130
+ if (keyboardLayoutMapPromise)
131
+ return keyboardLayoutMapPromise;
132
+ const browserNavigator = globalThis.navigator;
133
+ const keyboard = browserNavigator?.keyboard;
134
+ const promise = keyboard?.getLayoutMap().catch(() => undefined) ?? Promise.resolve(undefined);
135
+ keyboardLayoutMapPromise = promise;
136
+ return promise;
137
+ }
138
+ function blend(foreground, background) {
139
+ const channel = (front, back) => Math.floor((front * 155 + back * 100) / 255);
140
+ return {
141
+ r: channel(foreground.r, background.r),
142
+ g: channel(foreground.g, background.g),
143
+ b: channel(foreground.b, background.b)
144
+ };
145
+ }
146
+ /** A little-endian 32-bit value at `offset`, unsigned. */
147
+ function readU32(heap, offset) {
148
+ return ((heap[offset] |
149
+ (heap[offset + 1] << 8) |
150
+ (heap[offset + 2] << 16) |
151
+ (heap[offset + 3] << 24)) >>>
152
+ 0);
153
+ }
154
+ /**
155
+ * A row read from the engine. Its plain text is only wanted for links,
156
+ * selection, and tests, so it is joined on first use rather than per frame.
157
+ */
158
+ class SnapshotRow {
159
+ cells;
160
+ isWrapContinuation;
161
+ wrapsToNext;
162
+ joinedText;
163
+ constructor(cells, isWrapContinuation, wrapsToNext) {
164
+ this.cells = cells;
165
+ this.isWrapContinuation = isWrapContinuation;
166
+ this.wrapsToNext = wrapsToNext;
167
+ }
168
+ get text() {
169
+ this.joinedText ??= this.cells
170
+ .map((cell) => cell.text || ' ')
171
+ .join('')
172
+ .trimEnd();
173
+ return this.joinedText;
174
+ }
175
+ }
176
+ function sameColor(left, right) {
177
+ return left.r === right.r && left.g === right.g && left.b === right.b;
178
+ }
179
+ /**
180
+ * A cell's codepoints as a string, converted in bounded chunks: JavaScript
181
+ * engines cap spread-call arguments, and a cell's cluster is only as short as
182
+ * the engine keeps it (64 combining marks since Ghostty `fb13fa9`; earlier
183
+ * revisions kept hundreds of thousands). Exported for `core.test.ts`, which
184
+ * feeds it clusters too large to build through a terminal.
185
+ */
186
+ export function ghosttyCellText(codepointView, graphemeLength) {
187
+ if (graphemeLength === 1)
188
+ return String.fromCodePoint(codepointView.getUint32(0, true));
189
+ const CHUNK_SIZE = 4_096;
190
+ let text = '';
191
+ for (let start = 0; start < graphemeLength; start += CHUNK_SIZE) {
192
+ const count = Math.min(CHUNK_SIZE, graphemeLength - start);
193
+ const codes = new Array(count);
194
+ for (let index = 0; index < count; index += 1) {
195
+ codes[index] = codepointView.getUint32((start + index) * 4, true);
196
+ }
197
+ text += String.fromCodePoint(...codes);
198
+ }
199
+ return text;
200
+ }
201
+ /**
202
+ * The rows one page of the engine's history holds at `cols` columns: as many
203
+ * as fit their headers, then their cells on a cache-line boundary, in a
204
+ * standard page's grid (`Capacity.adjust` in Ghostty's `page.zig`). A grid
205
+ * too wide for one standard row gets a larger page of 215 rows.
206
+ */
207
+ export function ghosttyPageRows(cols) {
208
+ const fits = (rows) => Math.ceil((rows * PAGE_ROW_BYTES) / PAGE_CELLS_ALIGN) * PAGE_CELLS_ALIGN +
209
+ rows * cols * PAGE_CELL_BYTES <=
210
+ PAGE_GRID_BYTES;
211
+ let rows = Math.floor(PAGE_GRID_BYTES / (PAGE_ROW_BYTES + PAGE_CELL_BYTES * cols));
212
+ while (rows > 0 && !fits(rows))
213
+ rows -= 1;
214
+ return rows > 0 ? rows : PAGE_STANDARD_ROWS;
215
+ }
216
+ /**
217
+ * The engine's line limit (`GHOSTTY_TERMINAL_OPT_SCROLLBACK_MAX_LINES`) that
218
+ * keeps at least `lines` rows of history at `cols` columns. The engine drops
219
+ * the oldest history a whole page at a time, so under a limit of N it keeps
220
+ * at most N rows and as few as N less one page; one page more than `lines`
221
+ * keeps at least `lines` and at most a page beyond them.
222
+ */
223
+ function ghosttyScrollbackLimit(lines, cols) {
224
+ return lines + ghosttyPageRows(cols);
225
+ }
226
+ /** A grid dimension as the engine takes it: whole cells, 1 to 65,535. */
227
+ function gridCount(cells) {
228
+ return Math.max(1, Math.min(65_535, cells));
229
+ }
230
+ /** A libghostty-vt terminal: create with `GhosttyTerminalCore.create`, release with `dispose`. */
231
+ export class GhosttyTerminalCore {
232
+ runtime;
233
+ terminalSlot = 0;
234
+ terminal = 0;
235
+ renderStateSlot = 0;
236
+ renderState = 0;
237
+ rowIteratorSlot = 0;
238
+ rowCellsSlot = 0;
239
+ keyEncoderSlot = 0;
240
+ keyEncoder = 0;
241
+ keyEventSlot = 0;
242
+ keyEvent = 0;
243
+ mouseEncoderSlot = 0;
244
+ mouseEncoder = 0;
245
+ mouseEventSlot = 0;
246
+ mouseEvent = 0;
247
+ effectsId = 0;
248
+ effects = null;
249
+ onBell;
250
+ /** Whether the bell rang during the write in progress, which reports it once it returns. */
251
+ bellRang = false;
252
+ /** The scheme the theme's background reads as, which `CSI ? 996 n` reports. */
253
+ colorScheme = 'dark';
254
+ scratch = 0;
255
+ graphemes = 0;
256
+ graphemeCapacity = 0;
257
+ style = 0;
258
+ /** A zeroed `GhosttyStyle` with its size set, copied over `style` before each cell's read. */
259
+ styleTemplate = new Uint8Array(0);
260
+ /** Byte offsets of the `GhosttyStyle` fields a cell reads. */
261
+ styleOffsets = null;
262
+ cellsNext = null;
263
+ cellsGet = null;
264
+ /** One object per color a snapshot reads, so a cell's colors allocate nothing. */
265
+ colors = new Map();
266
+ scrollbar = 0;
267
+ rows = [];
268
+ /** The rows of history kept above the screen, and the grid width the engine's limit is set for. */
269
+ scrollbackLines = 0;
270
+ gridCols = 0;
271
+ disposed = false;
272
+ keyboardLayoutMap;
273
+ constructor(runtime) {
274
+ this.runtime = runtime;
275
+ void loadGhosttyKeyboardLayoutMap().then((layoutMap) => {
276
+ if (!this.disposed)
277
+ this.keyboardLayoutMap = layoutMap;
278
+ });
279
+ }
280
+ /**
281
+ * Loads the shared runtime and allocates a terminal that keeps at least
282
+ * `scrollbackLines` rows of history above its screen at any width (see
283
+ * `setScrollbackLines`); `onPtyData` receives the terminal's replies, and
284
+ * `onBell` hears of the bell once per `write` in which the program rang it.
285
+ */
286
+ static async create(cols, rows, cellWidth, cellHeight, theme, scrollbackLines, onPtyData, onBell) {
287
+ const core = new GhosttyTerminalCore(await loadGhosttyRuntime());
288
+ core.onBell = onBell;
289
+ try {
290
+ core.initialize(cols, rows, cellWidth, cellHeight, theme, scrollbackLines, onPtyData);
291
+ return core;
292
+ }
293
+ catch (error) {
294
+ core.dispose();
295
+ throw error;
296
+ }
297
+ }
298
+ initialize(cols, rows, cellWidth, cellHeight, theme, scrollbackLines, onPtyData) {
299
+ this.terminalSlot = this.runtime.allocOpaque();
300
+ this.assertSuccess('ghostty_terminal_new', this.runtime.call('ghostty_terminal_new', 0, this.terminalSlot, cols, rows));
301
+ this.terminal = this.runtime.readPointer(this.terminalSlot);
302
+ // The byte budget is only the shared memory's ceiling; the line limit,
303
+ // which follows the grid's width, decides how much history is kept.
304
+ this.setSizeOption(OPTION_SCROLLBACK_MAX_BYTES, SCROLLBACK_MAX_BYTES, 'scrollback bytes');
305
+ this.gridCols = gridCount(cols);
306
+ this.scrollbackLines = scrollbackLines;
307
+ this.applyScrollbackLimit(this.gridCols);
308
+ this.applyDefaultCursorBlink();
309
+ // The bell is only noted here: the callback runs inside the engine's
310
+ // parse, which must not be entered again, so `write` reports it after.
311
+ this.effects = {
312
+ writePty: onPtyData,
313
+ bell: () => {
314
+ this.bellRang = true;
315
+ },
316
+ colorScheme: () => this.colorScheme
317
+ };
318
+ this.effectsId = this.runtime.attachEffects(this.terminal, this.effects);
319
+ this.renderStateSlot = this.runtime.allocOpaque();
320
+ this.assertSuccess('ghostty_render_state_new', this.runtime.call('ghostty_render_state_new', 0, this.renderStateSlot));
321
+ this.renderState = this.runtime.readPointer(this.renderStateSlot);
322
+ this.rowIteratorSlot = this.runtime.allocOpaque();
323
+ this.assertSuccess('ghostty_render_state_row_iterator_new', this.runtime.call('ghostty_render_state_row_iterator_new', 0, this.rowIteratorSlot));
324
+ this.rowCellsSlot = this.runtime.allocOpaque();
325
+ this.assertSuccess('ghostty_render_state_row_cells_new', this.runtime.call('ghostty_render_state_row_cells_new', 0, this.rowCellsSlot));
326
+ this.keyEncoderSlot = this.runtime.allocOpaque();
327
+ this.assertSuccess('ghostty_key_encoder_new', this.runtime.call('ghostty_key_encoder_new', 0, this.keyEncoderSlot));
328
+ this.keyEncoder = this.runtime.readPointer(this.keyEncoderSlot);
329
+ this.keyEventSlot = this.runtime.allocOpaque();
330
+ this.assertSuccess('ghostty_key_event_new', this.runtime.call('ghostty_key_event_new', 0, this.keyEventSlot));
331
+ this.keyEvent = this.runtime.readPointer(this.keyEventSlot);
332
+ this.mouseEncoderSlot = this.runtime.allocOpaque();
333
+ this.assertSuccess('ghostty_mouse_encoder_new', this.runtime.call('ghostty_mouse_encoder_new', 0, this.mouseEncoderSlot));
334
+ this.mouseEncoder = this.runtime.readPointer(this.mouseEncoderSlot);
335
+ this.mouseEventSlot = this.runtime.allocOpaque();
336
+ this.assertSuccess('ghostty_mouse_event_new', this.runtime.call('ghostty_mouse_event_new', 0, this.mouseEventSlot));
337
+ this.mouseEvent = this.runtime.readPointer(this.mouseEventSlot);
338
+ this.scratch = this.runtime.alloc(16);
339
+ const styleSize = this.runtime.layout('GhosttyStyle').size;
340
+ this.style = this.runtime.alloc(styleSize);
341
+ this.runtime.setField(this.style, 'GhosttyStyle', 'size', styleSize);
342
+ this.styleTemplate = this.runtime.bytes(this.style, styleSize).slice();
343
+ const styleFields = this.runtime.layout('GhosttyStyle').fields;
344
+ this.styleOffsets = Object.fromEntries(STYLE_FLAGS.map((flag) => [flag, styleFields[flag].offset]));
345
+ this.cellsNext = this.runtime.exportedFunction('ghostty_render_state_row_cells_next');
346
+ this.cellsGet = this.runtime.exportedFunction('ghostty_render_state_row_cells_get');
347
+ this.scrollbar = this.runtime.alloc(this.runtime.layout('GhosttyTerminalScrollbar').size);
348
+ this.setTheme(theme);
349
+ this.resize(cols, rows, cellWidth, cellHeight);
350
+ }
351
+ /**
352
+ * Parses output from the program, then tells `onBell` if the program rang
353
+ * the bell in it, however many times. With `onSynchronizedOutputEnd`, a write
354
+ * that starts inside a synchronized update (DEC 2026) calls it as soon as
355
+ * that update ends, before any later byte can open the next one, so each
356
+ * update can be given its own paint deadline.
357
+ */
358
+ write(data, onSynchronizedOutputEnd) {
359
+ this.ensureActive();
360
+ const bytes = typeof data === 'string' ? encoder.encode(data) : data;
361
+ if (bytes.length === 0)
362
+ return;
363
+ const pointer = this.runtime.alloc(bytes.length);
364
+ this.runtime.bytes(pointer, bytes.length).set(bytes);
365
+ // Feeding the open update one escape at a time is enough to see where it
366
+ // ends: Ghostty keeps its parser state across calls, so a sequence split
367
+ // here still parses whole. Once it ends, the rest goes in one call.
368
+ let synchronized = onSynchronizedOutputEnd !== undefined && this.isSynchronizedOutput();
369
+ let rang;
370
+ try {
371
+ for (let start = 0; start < bytes.length;) {
372
+ const nextEscape = synchronized ? bytes.indexOf(0x1b, start + 1) : -1;
373
+ const end = nextEscape === -1 ? bytes.length : nextEscape;
374
+ this.runtime.call('ghostty_terminal_vt_write', this.terminal, pointer + start, end - start);
375
+ start = end;
376
+ if (synchronized && !this.isSynchronizedOutput()) {
377
+ synchronized = false;
378
+ onSynchronizedOutputEnd?.();
379
+ }
380
+ }
381
+ }
382
+ finally {
383
+ this.runtime.free(pointer, bytes.length);
384
+ rang = this.bellRang;
385
+ this.bellRang = false;
386
+ }
387
+ if (rang)
388
+ this.onBell?.();
389
+ }
390
+ /**
391
+ * Resets every mode, the screen, and scrollback, then replays `data`
392
+ * without answering its queries or ringing its bells.
393
+ */
394
+ resetAndWrite(data) {
395
+ this.ensureActive();
396
+ // RIS keeps the embedder's defaults (colors and the cursor's blink).
397
+ this.runtime.call('ghostty_terminal_reset', this.terminal);
398
+ this.rows = [];
399
+ if (data.length === 0)
400
+ return;
401
+ const effects = this.effects;
402
+ if (this.effectsId !== 0) {
403
+ this.runtime.detachEffects(this.terminal, this.effectsId);
404
+ this.effectsId = 0;
405
+ }
406
+ try {
407
+ this.write(data);
408
+ }
409
+ finally {
410
+ if (effects !== null && !this.disposed) {
411
+ this.effectsId = this.runtime.attachEffects(this.terminal, effects);
412
+ }
413
+ }
414
+ }
415
+ /**
416
+ * Resizes the grid in cells; the pixel cell size feeds pixel-based reports.
417
+ * The line limit follows the new width, since a page holds fewer rows the
418
+ * wider it is.
419
+ */
420
+ resize(cols, rows, cellWidth, cellHeight) {
421
+ this.ensureActive();
422
+ const nextCols = gridCount(cols);
423
+ // The engine prunes to its limit during the reflow, while its pages
424
+ // change from one width's to the other's; a limit with room for a page at
425
+ // either width keeps every line the chosen length does through it.
426
+ if (nextCols !== this.gridCols) {
427
+ this.applyScrollbackLimit(ghosttyPageRows(this.gridCols) > ghosttyPageRows(nextCols) ? this.gridCols : nextCols);
428
+ }
429
+ this.assertSuccess('ghostty_terminal_resize', this.runtime.call('ghostty_terminal_resize', this.terminal, nextCols, gridCount(rows), Math.max(1, Math.round(cellWidth)), Math.max(1, Math.round(cellHeight))));
430
+ if (nextCols !== this.gridCols) {
431
+ this.gridCols = nextCols;
432
+ this.applyScrollbackLimit(nextCols);
433
+ }
434
+ }
435
+ /**
436
+ * Keeps at least `lines` rows of history above the screen from now on, and
437
+ * at most one page more. A shorter length drops the oldest history at once.
438
+ */
439
+ setScrollbackLines(lines) {
440
+ this.ensureActive();
441
+ if (lines === this.scrollbackLines)
442
+ return;
443
+ this.scrollbackLines = lines;
444
+ this.applyScrollbackLimit(this.gridCols);
445
+ }
446
+ /** Sets the engine's line limit for the chosen length at `cols` columns. */
447
+ applyScrollbackLimit(cols) {
448
+ this.setSizeOption(OPTION_SCROLLBACK_MAX_LINES, ghosttyScrollbackLimit(this.scrollbackLines, cols), 'scrollback lines');
449
+ }
450
+ /** Sets a terminal option that takes a `size_t*`. */
451
+ setSizeOption(option, value, name) {
452
+ const pointer = this.runtime.alloc(USIZE_BYTES);
453
+ this.runtime.view(pointer, USIZE_BYTES).setUint32(0, value, true);
454
+ const result = this.runtime.call('ghostty_terminal_set', this.terminal, option, pointer);
455
+ this.runtime.free(pointer, USIZE_BYTES);
456
+ this.assertSuccess(`ghostty_terminal_set(${name})`, result);
457
+ }
458
+ /**
459
+ * Ghostty's built-in default cursor is steady, while a macOS terminal's
460
+ * cursor blinks. Option 23 is the embedder's
461
+ * default blink, which is the state a session starts in and returns to on
462
+ * DECSCUSR reset (CSI 0 q), so programs that ask for a specific cursor
463
+ * through DECSCUSR or DEC mode 12 still win.
464
+ */
465
+ applyDefaultCursorBlink() {
466
+ const blink = this.runtime.alloc(1);
467
+ this.runtime.bytes(blink, 1)[0] = 1;
468
+ this.runtime.call('ghostty_terminal_set', this.terminal, 23, blink);
469
+ this.runtime.free(blink, 1);
470
+ }
471
+ /**
472
+ * Sets the default colors; colors a program set through OSC sequences stay
473
+ * in force. The background decides the scheme `CSI ? 996 n` reports, light
474
+ * where Ghostty's perceived luminance exceeds one half, and a change of
475
+ * scheme is reported to a program that enabled DEC mode 2031.
476
+ */
477
+ setTheme(theme) {
478
+ this.ensureActive();
479
+ const color = this.runtime.alloc(3);
480
+ for (const [option, value] of [
481
+ [11, theme.foreground],
482
+ [12, theme.background],
483
+ [13, theme.cursor]
484
+ ]) {
485
+ this.runtime.bytes(color, 3).set([value.r, value.g, value.b]);
486
+ this.runtime.call('ghostty_terminal_set', this.terminal, option, color);
487
+ }
488
+ this.runtime.bytes(color, 3).set([theme.background.r, theme.background.g, theme.background.b]);
489
+ const scheme = this.runtime.call('ghostty_color_perceived_luminance', color) > 0.5 ? 'light' : 'dark';
490
+ this.runtime.free(color, 3);
491
+ if (scheme !== this.colorScheme) {
492
+ this.colorScheme = scheme;
493
+ if (this.effects !== null &&
494
+ this.effectsId !== 0 &&
495
+ this.getMode(DEC_MODE.colorSchemeReport)) {
496
+ this.effects.writePty(COLOR_SCHEME_REPORT[scheme]);
497
+ }
498
+ }
499
+ if (theme.palette === undefined)
500
+ return;
501
+ if (theme.palette.length !== GHOSTTY_PALETTE_SIZE) {
502
+ throw new Error(`A terminal palette needs ${GHOSTTY_PALETTE_SIZE} colors`);
503
+ }
504
+ const size = GHOSTTY_PALETTE_SIZE * 3;
505
+ const palette = this.runtime.alloc(size);
506
+ const bytes = this.runtime.bytes(palette, size);
507
+ theme.palette.forEach((entry, index) => bytes.set([entry.r, entry.g, entry.b], index * 3));
508
+ this.runtime.call('ghostty_terminal_set', this.terminal, OPTION_COLOR_PALETTE, palette);
509
+ this.runtime.free(palette, size);
510
+ }
511
+ /**
512
+ * Erases the scrollback and the rows above the cursor, moving the cursor's
513
+ * row to the top: Terminal.app's Clear to Start. The alternate screen (a
514
+ * full-screen program) is left alone. The erase runs through the VT parser,
515
+ * so it assumes the program is idle between sequences, as a prompt is.
516
+ */
517
+ clearToStart() {
518
+ this.ensureActive();
519
+ if (this.isAlternateScreen())
520
+ return;
521
+ this.runtime.bytes(this.scratch, 2).fill(0);
522
+ const row = this.runtime.call('ghostty_terminal_get', this.terminal, 4, this.scratch) === GHOSTTY_SUCCESS
523
+ ? this.runtime.view(this.scratch, 2).getUint16(0, true)
524
+ : 0;
525
+ // SU scrolls the region without feeding scrollback; ED 3 then drops the history.
526
+ this.write(`${row > 0 ? `\x1b[${row}S\x1b[${row}A` : ''}\x1b[3J`);
527
+ }
528
+ /** Scrolls the viewport through scrollback by whole rows. */
529
+ scroll(deltaRows) {
530
+ this.ensureActive();
531
+ const layout = this.runtime.layout('GhosttyTerminalScrollViewport');
532
+ const scroll = this.runtime.alloc(layout.size);
533
+ this.runtime.setField(scroll, 'GhosttyTerminalScrollViewport', 'tag', 2);
534
+ const value = layout.fields.value;
535
+ this.runtime.view(scroll + value.offset, value.size).setInt32(0, deltaRows, true);
536
+ this.runtime.call('ghostty_terminal_scroll_viewport', this.terminal, scroll);
537
+ this.runtime.free(scroll, layout.size);
538
+ }
539
+ /** Returns the viewport to the live screen. */
540
+ scrollToBottom() {
541
+ this.ensureActive();
542
+ const layout = this.runtime.layout('GhosttyTerminalScrollViewport');
543
+ const scroll = this.runtime.alloc(layout.size);
544
+ this.runtime.setField(scroll, 'GhosttyTerminalScrollViewport', 'tag', 1);
545
+ this.runtime.call('ghostty_terminal_scroll_viewport', this.terminal, scroll);
546
+ this.runtime.free(scroll, layout.size);
547
+ }
548
+ /** Whether the viewport shows the live screen rather than scrollback. */
549
+ isViewportActive() {
550
+ this.ensureActive();
551
+ this.runtime.bytes(this.scratch, 1)[0] = 0;
552
+ return (this.runtime.call('ghostty_terminal_get', this.terminal, 32, this.scratch) ===
553
+ GHOSTTY_SUCCESS && this.runtime.bytes(this.scratch, 1)[0] !== 0);
554
+ }
555
+ /** The scrollback position, or null when Ghostty cannot report it. */
556
+ scrollbarState() {
557
+ this.ensureActive();
558
+ const layout = this.runtime.layout('GhosttyTerminalScrollbar');
559
+ this.runtime.bytes(this.scrollbar, layout.size).fill(0);
560
+ if (this.runtime.call('ghostty_terminal_get', this.terminal, 9, this.scrollbar) !==
561
+ GHOSTTY_SUCCESS) {
562
+ return null;
563
+ }
564
+ return {
565
+ total: this.runtime.readField(this.scrollbar, 'GhosttyTerminalScrollbar', 'total'),
566
+ offset: this.runtime.readField(this.scrollbar, 'GhosttyTerminalScrollbar', 'offset'),
567
+ len: this.runtime.readField(this.scrollbar, 'GhosttyTerminalScrollbar', 'len')
568
+ };
569
+ }
570
+ /** Whether the program asked for mouse reports. */
571
+ isMouseTracking() {
572
+ this.ensureActive();
573
+ this.runtime.bytes(this.scratch, 1)[0] = 0;
574
+ return (this.runtime.call('ghostty_terminal_get', this.terminal, 11, this.scratch) ===
575
+ GHOSTTY_SUCCESS && this.runtime.bytes(this.scratch, 1)[0] !== 0);
576
+ }
577
+ /** Whether the program asked for motion reports without a pressed button (DEC 1003). */
578
+ isMouseAnyEventTracking() {
579
+ this.ensureActive();
580
+ return this.getMode(DEC_MODE.anyEventMouse);
581
+ }
582
+ /** Whether the program has a synchronized update open (DEC 2026): its frame is still being drawn. */
583
+ isSynchronizedOutput() {
584
+ this.ensureActive();
585
+ return this.getMode(DEC_MODE.synchronizedOutput);
586
+ }
587
+ /** Ends an open synchronized update, as a program that never closes one would have. */
588
+ endSynchronizedOutput() {
589
+ this.ensureActive();
590
+ this.writeModeConfig(DEC_MODE.synchronizedOutput, false);
591
+ this.assertSuccess('ghostty_terminal_set(mode)', this.runtime.call('ghostty_terminal_set', this.terminal, OPTION_MODE, this.scratch));
592
+ }
593
+ /** Whether a full-screen program switched to the alternate screen. */
594
+ isAlternateScreen() {
595
+ this.ensureActive();
596
+ this.runtime.bytes(this.scratch, 4).fill(0);
597
+ return (this.runtime.call('ghostty_terminal_get', this.terminal, 6, this.scratch) ===
598
+ GHOSTTY_SUCCESS && this.runtime.view(this.scratch, 4).getUint32(0, true) === 1);
599
+ }
600
+ /** Whether cursor keys send application sequences (DECCKM). */
601
+ isApplicationCursorKeys() {
602
+ this.ensureActive();
603
+ return this.getMode(DEC_MODE.cursorKeys);
604
+ }
605
+ /** Encodes a key event under the terminal's current keyboard modes; empty when it sends nothing. */
606
+ encodeKey(event, action = 'press') {
607
+ this.ensureActive();
608
+ this.runtime.call('ghostty_key_encoder_setopt_from_terminal', this.keyEncoder, this.terminal);
609
+ this.runtime.call('ghostty_key_event_set_action', this.keyEvent, action === 'release' ? 0 : event.repeat ? 2 : 1);
610
+ this.runtime.call('ghostty_key_event_set_key', this.keyEvent, ghosttyKeyForCode(event.code));
611
+ const mods = (event.shiftKey ? 1 : 0) |
612
+ (event.ctrlKey ? 1 << 1 : 0) |
613
+ (event.altKey ? 1 << 2 : 0) |
614
+ (event.metaKey ? 1 << 3 : 0) |
615
+ (event.getModifierState('CapsLock') ? 1 << 4 : 0) |
616
+ (event.getModifierState('NumLock') ? 1 << 5 : 0);
617
+ this.runtime.call('ghostty_key_event_set_mods', this.keyEvent, mods);
618
+ this.runtime.call('ghostty_key_event_set_consumed_mods', this.keyEvent, ghosttyConsumedMods(event));
619
+ this.runtime.call('ghostty_key_event_set_composing', this.keyEvent, event.isComposing ? 1 : 0);
620
+ this.runtime.call('ghostty_key_event_set_unshifted_codepoint', this.keyEvent, ghosttyUnshiftedCodepoint(event, this.keyboardLayoutMap));
621
+ const text = event.key.length === 1 ? event.key : '';
622
+ const textBytes = encoder.encode(text);
623
+ const textPointer = textBytes.length === 0 ? 0 : this.runtime.alloc(textBytes.length);
624
+ if (textPointer !== 0)
625
+ this.runtime.bytes(textPointer, textBytes.length).set(textBytes);
626
+ this.runtime.call('ghostty_key_event_set_utf8', this.keyEvent, textPointer, textBytes.length);
627
+ const written = this.runtime.alloc(USIZE_BYTES);
628
+ const encoded = this.encodeOutput(written, (output, outputSize) => this.runtime.call('ghostty_key_encoder_encode', this.keyEncoder, this.keyEvent, output, outputSize, written));
629
+ this.runtime.free(written, USIZE_BYTES);
630
+ if (textPointer !== 0)
631
+ this.runtime.free(textPointer, textBytes.length);
632
+ return encoded;
633
+ }
634
+ /** Encodes pasted text, bracketed when the program enabled bracketed paste (mode 2004). */
635
+ encodePaste(data) {
636
+ this.ensureActive();
637
+ const input = encoder.encode(data);
638
+ if (input.length === 0)
639
+ return '';
640
+ const inputPointer = this.runtime.alloc(input.length);
641
+ this.runtime.bytes(inputPointer, input.length).set(input);
642
+ const bracketed = this.getMode(DEC_MODE.bracketedPaste);
643
+ const written = this.runtime.alloc(USIZE_BYTES);
644
+ let encoded = '';
645
+ const sizeResult = this.runtime.call('ghostty_paste_encode', inputPointer, input.length, bracketed ? 1 : 0, 0, 0, written);
646
+ const outputSize = this.runtime.view(written, 4).getUint32(0, true);
647
+ if (sizeResult === GHOSTTY_OUT_OF_SPACE && outputSize > 0) {
648
+ const output = this.runtime.alloc(outputSize);
649
+ const result = this.runtime.call('ghostty_paste_encode', inputPointer, input.length, bracketed ? 1 : 0, output, outputSize, written);
650
+ const outputLength = this.runtime.view(written, 4).getUint32(0, true);
651
+ encoded =
652
+ result === GHOSTTY_SUCCESS ? decoder.decode(this.runtime.bytes(output, outputLength)) : '';
653
+ this.runtime.free(output, outputSize);
654
+ }
655
+ this.runtime.free(written, USIZE_BYTES);
656
+ this.runtime.free(inputPointer, input.length);
657
+ return encoded;
658
+ }
659
+ /** Encodes a pointer event under the program's mouse modes; empty when it sends nothing. */
660
+ encodeMouse(input) {
661
+ this.ensureActive();
662
+ this.runtime.call('ghostty_mouse_encoder_setopt_from_terminal', this.mouseEncoder, this.terminal);
663
+ const sizeLayout = this.runtime.layout('GhosttyMouseEncoderSize');
664
+ const size = this.runtime.alloc(sizeLayout.size);
665
+ for (const [field, value] of [
666
+ ['size', sizeLayout.size],
667
+ ['screen_width', input.screenWidth],
668
+ ['screen_height', input.screenHeight],
669
+ ['cell_width', input.cellWidth],
670
+ ['cell_height', input.cellHeight],
671
+ ['padding_top', input.paddingTop],
672
+ ['padding_bottom', input.paddingBottom],
673
+ ['padding_right', input.paddingRight],
674
+ ['padding_left', input.paddingLeft]
675
+ ]) {
676
+ this.runtime.setField(size, 'GhosttyMouseEncoderSize', field, Math.max(0, Math.round(value)));
677
+ }
678
+ this.runtime.call('ghostty_mouse_encoder_setopt', this.mouseEncoder, 2, size);
679
+ this.runtime.free(size, sizeLayout.size);
680
+ this.runtime.bytes(this.scratch, 1)[0] = input.anyButtonPressed ? 1 : 0;
681
+ this.runtime.call('ghostty_mouse_encoder_setopt', this.mouseEncoder, 3, this.scratch);
682
+ this.runtime.bytes(this.scratch, 1)[0] = 1;
683
+ this.runtime.call('ghostty_mouse_encoder_setopt', this.mouseEncoder, 4, this.scratch);
684
+ this.runtime.call('ghostty_mouse_event_set_action', this.mouseEvent, input.action === 'press' ? 0 : input.action === 'release' ? 1 : 2);
685
+ if (input.button === null) {
686
+ this.runtime.call('ghostty_mouse_event_clear_button', this.mouseEvent);
687
+ }
688
+ else {
689
+ this.runtime.call('ghostty_mouse_event_set_button', this.mouseEvent, input.button);
690
+ }
691
+ this.runtime.call('ghostty_mouse_event_set_mods', this.mouseEvent, input.mods);
692
+ const positionLayout = this.runtime.layout('GhosttyMousePosition');
693
+ const position = this.runtime.alloc(positionLayout.size);
694
+ const positionView = this.runtime.view(position, positionLayout.size);
695
+ positionView.setFloat32(positionLayout.fields.x.offset, input.x, true);
696
+ positionView.setFloat32(positionLayout.fields.y.offset, input.y, true);
697
+ this.runtime.call('ghostty_mouse_event_set_position', this.mouseEvent, position);
698
+ this.runtime.free(position, positionLayout.size);
699
+ const written = this.runtime.alloc(USIZE_BYTES);
700
+ const encoded = this.encodeOutput(written, (output, outputSize) => this.runtime.call('ghostty_mouse_encoder_encode', this.mouseEncoder, this.mouseEvent, output, outputSize, written));
701
+ this.runtime.free(written, USIZE_BYTES);
702
+ return encoded;
703
+ }
704
+ /** Selects the cells between two grid points. */
705
+ setSelection(anchor, end) {
706
+ this.ensureActive();
707
+ const selectionLayout = this.runtime.layout('GhosttySelection');
708
+ const gridRefSize = this.runtime.layout('GhosttyGridRef').size;
709
+ const selection = this.runtime.alloc(selectionLayout.size);
710
+ let start = 0;
711
+ let endRef = 0;
712
+ try {
713
+ this.runtime.setField(selection, 'GhosttySelection', 'size', selectionLayout.size);
714
+ start = this.gridRef(anchor.x, anchor.y, anchor.tag ?? 1);
715
+ endRef = this.gridRef(end.x, end.y, end.tag ?? 1);
716
+ const startField = selectionLayout.fields.start;
717
+ const endField = selectionLayout.fields.end;
718
+ this.runtime
719
+ .bytes(selection + startField.offset, startField.size)
720
+ .set(this.runtime.bytes(start, startField.size));
721
+ this.runtime
722
+ .bytes(selection + endField.offset, endField.size)
723
+ .set(this.runtime.bytes(endRef, endField.size));
724
+ this.runtime.call('ghostty_terminal_set', this.terminal, 21, selection);
725
+ }
726
+ finally {
727
+ this.runtime.free(start, gridRefSize);
728
+ this.runtime.free(endRef, gridRefSize);
729
+ this.runtime.free(selection, selectionLayout.size);
730
+ }
731
+ }
732
+ /** Selects the word at a viewport cell. */
733
+ selectWord(col, row) {
734
+ return this.selectAt('GhosttyTerminalSelectWordOptions', 'ghostty_terminal_select_word', col, row);
735
+ }
736
+ /** Selects the line at a viewport cell. */
737
+ selectLine(col, row) {
738
+ return this.selectAt('GhosttyTerminalSelectLineOptions', 'ghostty_terminal_select_line', col, row);
739
+ }
740
+ /** The OSC 8 hyperlink at a viewport cell, if any. */
741
+ hyperlinkAt(col, row) {
742
+ this.ensureActive();
743
+ const ref = this.gridRef(col, row);
744
+ const written = this.runtime.alloc(USIZE_BYTES);
745
+ const sizeResult = this.runtime.call('ghostty_grid_ref_hyperlink_uri', ref, 0, 0, written);
746
+ const outputSize = this.runtime.view(written, 4).getUint32(0, true);
747
+ let hyperlink = null;
748
+ if (sizeResult === GHOSTTY_OUT_OF_SPACE && outputSize > 0) {
749
+ const output = this.runtime.alloc(outputSize);
750
+ const result = this.runtime.call('ghostty_grid_ref_hyperlink_uri', ref, output, outputSize, written);
751
+ const outputLength = this.runtime.view(written, 4).getUint32(0, true);
752
+ if (result === GHOSTTY_SUCCESS && outputLength > 0) {
753
+ hyperlink = decoder.decode(this.runtime.bytes(output, outputLength));
754
+ }
755
+ this.runtime.free(output, outputSize);
756
+ }
757
+ this.runtime.free(written, USIZE_BYTES);
758
+ this.runtime.free(ref, this.runtime.layout('GhosttyGridRef').size);
759
+ return hyperlink;
760
+ }
761
+ /** Removes the selection. */
762
+ clearSelection() {
763
+ this.ensureActive();
764
+ this.runtime.call('ghostty_terminal_set', this.terminal, 21, 0);
765
+ }
766
+ /** Reads the viewport, re-reading only the rows Ghostty marked dirty since the last call. */
767
+ snapshot() {
768
+ this.ensureActive();
769
+ this.assertSuccess('ghostty_render_state_update', this.runtime.call('ghostty_render_state_update', this.renderState, this.terminal));
770
+ const cols = this.getU16(RENDER_DATA.cols);
771
+ const rowCount = this.getU16(RENDER_DATA.rows);
772
+ const dirty = this.getU32(RENDER_DATA.dirty);
773
+ const foreground = this.getColor(RENDER_DATA.foreground, ENGINE_DEFAULT_FOREGROUND);
774
+ const background = this.getColor(RENDER_DATA.background, ENGINE_DEFAULT_BACKGROUND);
775
+ const cursorHasValue = this.getBool(RENDER_DATA.cursorHasValue);
776
+ const cursor = cursorHasValue ? this.getColor(RENDER_DATA.cursor, foreground) : foreground;
777
+ const cursorInViewport = this.getBool(RENDER_DATA.cursorInViewport);
778
+ const cursorVisible = this.getBool(RENDER_DATA.cursorVisible) && cursorInViewport;
779
+ const cursorX = cursorInViewport ? this.getU16(RENDER_DATA.cursorX) : -1;
780
+ const cursorY = cursorInViewport ? this.getU16(RENDER_DATA.cursorY) : -1;
781
+ if (this.rows.length !== rowCount || this.rows.some((row) => row.cells.length !== cols)) {
782
+ this.rows = Array.from({ length: rowCount }, () => ({
783
+ cells: Array.from({ length: cols }, () => this.emptyCell(foreground, background)),
784
+ text: '',
785
+ isWrapContinuation: false,
786
+ wrapsToNext: false
787
+ }));
788
+ }
789
+ const dirtyRows = new Set();
790
+ if (dirty !== 0) {
791
+ this.assertSuccess('ghostty_render_state_get(row iterator)', this.runtime.call('ghostty_render_state_get', this.renderState, RENDER_DATA.rowIterator, this.rowIteratorSlot));
792
+ const iterator = this.runtime.readPointer(this.rowIteratorSlot);
793
+ let rowIndex = 0;
794
+ while (rowIndex < rowCount &&
795
+ this.runtime.call('ghostty_render_state_row_iterator_next', iterator) !== 0) {
796
+ const rowDirty = dirty === 2 || this.getRowBool(iterator, ROW_DATA.dirty);
797
+ if (rowDirty) {
798
+ this.rows[rowIndex] = this.readRow(iterator, cols, foreground, background);
799
+ dirtyRows.add(rowIndex);
800
+ this.runtime.bytes(this.scratch, 1)[0] = 0;
801
+ this.runtime.call('ghostty_render_state_row_set', iterator, 0, this.scratch);
802
+ }
803
+ rowIndex += 1;
804
+ }
805
+ this.runtime.view(this.scratch, 4).setUint32(0, 0, true);
806
+ this.runtime.call('ghostty_render_state_set', this.renderState, 0, this.scratch);
807
+ }
808
+ return {
809
+ cols,
810
+ rows: rowCount,
811
+ foreground,
812
+ background,
813
+ cursor,
814
+ cursorX,
815
+ cursorY,
816
+ cursorVisible,
817
+ cursorBlinking: this.getBool(RENDER_DATA.cursorBlinking),
818
+ cursorStyle: this.getU32(RENDER_DATA.cursorStyle),
819
+ dirtyRows,
820
+ rowData: this.rows
821
+ };
822
+ }
823
+ /** The selection as plain text with Ghostty's copy semantics (soft wraps joined, trailing blanks trimmed). */
824
+ selectionText() {
825
+ this.ensureActive();
826
+ // Plain text (`emit` 0) of the terminal's own selection (`selection` null).
827
+ const optionsName = 'GhosttyTerminalSelectionFormatOptions';
828
+ const optionsSize = this.runtime.layout(optionsName).size;
829
+ const options = this.runtime.alloc(optionsSize);
830
+ this.runtime.setField(options, optionsName, 'size', optionsSize);
831
+ this.runtime.setField(options, optionsName, 'unwrap', 1);
832
+ this.runtime.setField(options, optionsName, 'trim', 1);
833
+ const written = this.runtime.alloc(USIZE_BYTES);
834
+ const sizeResult = this.runtime.call('ghostty_terminal_selection_format_buf', this.terminal, options, 0, 0, written);
835
+ const outputSize = this.runtime.view(written, 4).getUint32(0, true);
836
+ let text = '';
837
+ if (sizeResult === GHOSTTY_OUT_OF_SPACE && outputSize > 0) {
838
+ const output = this.runtime.alloc(outputSize);
839
+ const result = this.runtime.call('ghostty_terminal_selection_format_buf', this.terminal, options, output, outputSize, written);
840
+ const outputLength = this.runtime.view(written, 4).getUint32(0, true);
841
+ if (result === GHOSTTY_SUCCESS) {
842
+ text = decoder.decode(this.runtime.bytes(output, outputLength));
843
+ }
844
+ this.runtime.free(output, outputSize);
845
+ }
846
+ this.runtime.free(written, USIZE_BYTES);
847
+ this.runtime.free(options, optionsSize);
848
+ return text;
849
+ }
850
+ /** Converts a viewport cell to screen coordinates. */
851
+ viewportPointToScreen(col, row) {
852
+ return this.convertPoint(col, row, 1, 2);
853
+ }
854
+ convertPoint(col, row, fromTag, toTag) {
855
+ this.ensureActive();
856
+ const ref = this.gridRef(col, row, fromTag);
857
+ const point = this.pointFromGridRef(ref, toTag);
858
+ this.runtime.free(ref, this.runtime.layout('GhosttyGridRef').size);
859
+ return point;
860
+ }
861
+ /** Frees every handle and allocation; the core is unusable afterwards. */
862
+ dispose() {
863
+ if (this.disposed)
864
+ return;
865
+ this.disposed = true;
866
+ if (this.mouseEvent)
867
+ this.runtime.call('ghostty_mouse_event_free', this.mouseEvent);
868
+ if (this.mouseEncoder)
869
+ this.runtime.call('ghostty_mouse_encoder_free', this.mouseEncoder);
870
+ if (this.keyEvent)
871
+ this.runtime.call('ghostty_key_event_free', this.keyEvent);
872
+ if (this.keyEncoder)
873
+ this.runtime.call('ghostty_key_encoder_free', this.keyEncoder);
874
+ if (this.rowCellsSlot) {
875
+ const cells = this.runtime.readPointer(this.rowCellsSlot);
876
+ if (cells)
877
+ this.runtime.call('ghostty_render_state_row_cells_free', cells);
878
+ }
879
+ if (this.rowIteratorSlot) {
880
+ const iterator = this.runtime.readPointer(this.rowIteratorSlot);
881
+ if (iterator)
882
+ this.runtime.call('ghostty_render_state_row_iterator_free', iterator);
883
+ }
884
+ if (this.renderState)
885
+ this.runtime.call('ghostty_render_state_free', this.renderState);
886
+ if (this.terminal) {
887
+ if (this.effectsId)
888
+ this.runtime.detachEffects(this.terminal, this.effectsId);
889
+ this.runtime.call('ghostty_terminal_free', this.terminal);
890
+ }
891
+ if (this.style)
892
+ this.runtime.free(this.style, this.runtime.layout('GhosttyStyle').size);
893
+ if (this.scrollbar) {
894
+ this.runtime.free(this.scrollbar, this.runtime.layout('GhosttyTerminalScrollbar').size);
895
+ }
896
+ if (this.scratch)
897
+ this.runtime.free(this.scratch, 16);
898
+ if (this.graphemes)
899
+ this.runtime.free(this.graphemes, this.graphemeCapacity);
900
+ for (const slot of [
901
+ this.mouseEventSlot,
902
+ this.mouseEncoderSlot,
903
+ this.keyEventSlot,
904
+ this.keyEncoderSlot,
905
+ this.rowCellsSlot,
906
+ this.rowIteratorSlot,
907
+ this.renderStateSlot,
908
+ this.terminalSlot
909
+ ]) {
910
+ this.runtime.freeOpaque(slot);
911
+ }
912
+ }
913
+ encodeOutput(written, encode) {
914
+ const sizeResult = encode(0, 0);
915
+ const outputSize = this.runtime.view(written, 4).getUint32(0, true);
916
+ if (sizeResult === GHOSTTY_SUCCESS && outputSize === 0)
917
+ return '';
918
+ if (sizeResult !== GHOSTTY_OUT_OF_SPACE || outputSize === 0)
919
+ return '';
920
+ const output = this.runtime.alloc(outputSize);
921
+ const result = encode(output, outputSize);
922
+ const outputLength = this.runtime.view(written, 4).getUint32(0, true);
923
+ const encoded = result === GHOSTTY_SUCCESS ? decoder.decode(this.runtime.bytes(output, outputLength)) : '';
924
+ this.runtime.free(output, outputSize);
925
+ return encoded;
926
+ }
927
+ readRow(iterator, cols, defaultForeground, defaultBackground) {
928
+ this.assertSuccess('ghostty_render_state_row_get(raw)', this.runtime.call('ghostty_render_state_row_get', iterator, ROW_DATA.raw, this.scratch));
929
+ const rawRow = this.runtime.view(this.scratch, 8).getBigUint64(0, true);
930
+ this.runtime.bytes(this.scratch + 8, 1)[0] = 0;
931
+ this.assertSuccess('ghostty_row_get(wrap continuation)', this.runtime.call('ghostty_row_get', rawRow, 2, this.scratch + 8));
932
+ const isWrapContinuation = this.runtime.bytes(this.scratch + 8, 1)[0] !== 0;
933
+ this.runtime.bytes(this.scratch + 8, 1)[0] = 0;
934
+ this.assertSuccess('ghostty_row_get(wrap)', this.runtime.call('ghostty_row_get', rawRow, 1, this.scratch + 8));
935
+ const wrapsToNext = this.runtime.bytes(this.scratch + 8, 1)[0] !== 0;
936
+ this.assertSuccess('ghostty_render_state_row_get(cells)', this.runtime.call('ghostty_render_state_row_get', iterator, ROW_DATA.cells, this.rowCellsSlot));
937
+ const cellsIterator = this.runtime.readPointer(this.rowCellsSlot);
938
+ const cellsNext = this.cellsNext;
939
+ const cellsGet = this.cellsGet;
940
+ const offsets = this.styleOffsets;
941
+ const style = this.style;
942
+ const scratch = this.scratch;
943
+ const cells = [];
944
+ // Values are read straight from one view of module memory rather than a
945
+ // fresh typed array per value; the view is fetched again after every
946
+ // call, since any of them could grow memory.
947
+ while (cells.length < cols && cellsNext(cellsIterator) !== 0) {
948
+ let foreground = this.readCellColor(cellsIterator, CELL_DATA.foreground, defaultForeground);
949
+ let background = this.readCellColor(cellsIterator, CELL_DATA.background, defaultBackground);
950
+ this.runtime.heapBytes().set(this.styleTemplate, style);
951
+ cellsGet(cellsIterator, CELL_DATA.style, style);
952
+ let heap = this.runtime.heapBytes();
953
+ heap.fill(0, scratch, scratch + 4);
954
+ const graphemeLength = cellsGet(cellsIterator, CELL_DATA.graphemesLength, scratch) === GHOSTTY_SUCCESS
955
+ ? readU32(this.runtime.heapBytes(), scratch)
956
+ : 0;
957
+ let text = '';
958
+ if (graphemeLength > 0) {
959
+ const bufferSize = graphemeLength * 4;
960
+ if (bufferSize > this.graphemeCapacity) {
961
+ const capacity = Math.max(bufferSize, this.graphemeCapacity * 2);
962
+ const buffer = this.runtime.alloc(capacity);
963
+ this.runtime.free(this.graphemes, this.graphemeCapacity);
964
+ this.graphemes = buffer;
965
+ this.graphemeCapacity = capacity;
966
+ }
967
+ if (cellsGet(cellsIterator, CELL_DATA.graphemes, this.graphemes) === GHOSTTY_SUCCESS) {
968
+ // A lone codepoint, nearly every cell, is read in place; a cluster
969
+ // goes through a DataView, which takes the codepoints as
970
+ // little-endian whatever the buffer's alignment.
971
+ text =
972
+ graphemeLength === 1
973
+ ? String.fromCodePoint(readU32(this.runtime.heapBytes(), this.graphemes))
974
+ : ghosttyCellText(this.runtime.view(this.graphemes, bufferSize), graphemeLength);
975
+ }
976
+ }
977
+ let wide = 0;
978
+ if (text.length === 0 && cells.at(-1)?.text.length) {
979
+ this.assertSuccess('ghostty_render_state_row_cells_get(raw)', this.runtime.call('ghostty_render_state_row_cells_get', cellsIterator, CELL_DATA.raw, this.scratch));
980
+ const rawCell = this.runtime.view(this.scratch, 8).getBigUint64(0, true);
981
+ this.runtime.view(this.scratch + 8, 4).setUint32(0, 0, true);
982
+ this.assertSuccess('ghostty_cell_get(wide)', this.runtime.call('ghostty_cell_get', rawCell, RAW_CELL_DATA.wide, this.scratch + 8));
983
+ wide = this.runtime.view(this.scratch + 8, 4).getUint32(0, true);
984
+ }
985
+ this.runtime.heapBytes()[scratch] = 0;
986
+ const selected = cellsGet(cellsIterator, CELL_DATA.selected, scratch) === GHOSTTY_SUCCESS &&
987
+ this.runtime.heapBytes()[scratch] !== 0;
988
+ // Read the style after allocation and ABI calls, which can grow WASM memory.
989
+ heap = this.runtime.heapBytes();
990
+ if (heap[style + offsets.inverse] !== 0) {
991
+ [foreground, background] = [background, foreground];
992
+ }
993
+ if (heap[style + offsets.faint] !== 0) {
994
+ foreground = blend(foreground, background);
995
+ }
996
+ cells.push({
997
+ text,
998
+ wide,
999
+ foreground,
1000
+ background,
1001
+ bold: heap[style + offsets.bold] !== 0,
1002
+ italic: heap[style + offsets.italic] !== 0,
1003
+ invisible: heap[style + offsets.invisible] !== 0,
1004
+ strikethrough: heap[style + offsets.strikethrough] !== 0,
1005
+ overline: heap[style + offsets.overline] !== 0,
1006
+ underline: readU32(heap, style + offsets.underline) !== 0,
1007
+ selected
1008
+ });
1009
+ }
1010
+ while (cells.length < cols)
1011
+ cells.push(this.emptyCell(defaultForeground, defaultBackground));
1012
+ return new SnapshotRow(cells, isWrapContinuation, wrapsToNext);
1013
+ }
1014
+ /** A cell's color, or `fallback` when the cell has none of its own. */
1015
+ readCellColor(iterator, data, fallback) {
1016
+ if (this.cellsGet(iterator, data, this.scratch) !== GHOSTTY_SUCCESS)
1017
+ return fallback;
1018
+ const heap = this.runtime.heapBytes();
1019
+ const r = heap[this.scratch];
1020
+ const g = heap[this.scratch + 1];
1021
+ const b = heap[this.scratch + 2];
1022
+ const key = (r << 16) | (g << 8) | b;
1023
+ let color = this.colors.get(key);
1024
+ if (color === undefined) {
1025
+ if (this.colors.size >= COLOR_TABLE_LIMIT)
1026
+ this.colors.clear();
1027
+ color = { r, g, b };
1028
+ this.colors.set(key, color);
1029
+ }
1030
+ return color;
1031
+ }
1032
+ gridRef(col, row, tag = 1) {
1033
+ const pointLayout = this.runtime.layout('GhosttyPoint');
1034
+ const point = this.runtime.alloc(pointLayout.size);
1035
+ this.runtime.setField(point, 'GhosttyPoint', 'tag', tag);
1036
+ const pointValue = pointLayout.fields.value;
1037
+ const valueOffset = pointValue.offset;
1038
+ const view = this.runtime.view(point + valueOffset, pointValue.size);
1039
+ view.setUint16(0, Math.max(0, col), true);
1040
+ view.setUint32(4, Math.max(0, row), true);
1041
+ const gridRefSize = this.runtime.layout('GhosttyGridRef').size;
1042
+ const gridRef = this.runtime.alloc(gridRefSize);
1043
+ this.runtime.setField(gridRef, 'GhosttyGridRef', 'size', gridRefSize);
1044
+ const result = this.runtime.call('ghostty_terminal_grid_ref', this.terminal, point, gridRef);
1045
+ this.runtime.free(point, pointLayout.size);
1046
+ if (result !== GHOSTTY_SUCCESS) {
1047
+ this.runtime.free(gridRef, gridRefSize);
1048
+ this.assertSuccess('ghostty_terminal_grid_ref', result);
1049
+ }
1050
+ return gridRef;
1051
+ }
1052
+ selectAt(optionsName, operation, col, row) {
1053
+ this.ensureActive();
1054
+ const optionsLayout = this.runtime.layout(optionsName);
1055
+ const selectionLayout = this.runtime.layout('GhosttySelection');
1056
+ const options = this.runtime.alloc(optionsLayout.size);
1057
+ let ref = 0;
1058
+ let selection = 0;
1059
+ let range = null;
1060
+ try {
1061
+ this.runtime.setField(options, optionsName, 'size', optionsLayout.size);
1062
+ ref = this.gridRef(col, row);
1063
+ const refField = optionsLayout.fields.ref;
1064
+ this.runtime
1065
+ .bytes(options + refField.offset, refField.size)
1066
+ .set(this.runtime.bytes(ref, refField.size));
1067
+ selection = this.runtime.alloc(selectionLayout.size);
1068
+ this.runtime.setField(selection, 'GhosttySelection', 'size', selectionLayout.size);
1069
+ const result = this.runtime.call(operation, this.terminal, options, selection);
1070
+ if (result === GHOSTTY_SUCCESS) {
1071
+ const start = selection + selectionLayout.fields.start.offset;
1072
+ const end = selection + selectionLayout.fields.end.offset;
1073
+ const viewportStart = this.pointFromGridRef(start, 1);
1074
+ const viewportEnd = this.pointFromGridRef(end, 1);
1075
+ const screenStart = this.pointFromGridRef(start, 2);
1076
+ const screenEnd = this.pointFromGridRef(end, 2);
1077
+ if (viewportStart && viewportEnd && screenStart && screenEnd) {
1078
+ range = {
1079
+ viewport: { start: viewportStart, end: viewportEnd },
1080
+ screen: { start: screenStart, end: screenEnd }
1081
+ };
1082
+ }
1083
+ this.runtime.call('ghostty_terminal_set', this.terminal, 21, selection);
1084
+ }
1085
+ }
1086
+ finally {
1087
+ this.runtime.free(selection, selectionLayout.size);
1088
+ this.runtime.free(ref, this.runtime.layout('GhosttyGridRef').size);
1089
+ this.runtime.free(options, optionsLayout.size);
1090
+ }
1091
+ return range;
1092
+ }
1093
+ pointFromGridRef(ref, tag) {
1094
+ const coordinateLayout = this.runtime.layout('GhosttyPointCoordinate');
1095
+ const coordinate = this.runtime.alloc(coordinateLayout.size);
1096
+ const result = this.runtime.call('ghostty_terminal_point_from_grid_ref', this.terminal, ref, tag, coordinate);
1097
+ const point = result === GHOSTTY_SUCCESS
1098
+ ? {
1099
+ x: this.runtime.readField(coordinate, 'GhosttyPointCoordinate', 'x'),
1100
+ y: this.runtime.readField(coordinate, 'GhosttyPointCoordinate', 'y')
1101
+ }
1102
+ : null;
1103
+ this.runtime.free(coordinate, coordinateLayout.size);
1104
+ return point;
1105
+ }
1106
+ /** Whether a DEC private mode is set. */
1107
+ getMode(mode) {
1108
+ this.writeModeConfig(mode, false);
1109
+ return (this.runtime.call('ghostty_terminal_get', this.terminal, DATA_MODE, this.scratch) ===
1110
+ GHOSTTY_SUCCESS &&
1111
+ this.runtime.readField(this.scratch, 'GhosttyTerminalModeConfig', 'value') !== 0);
1112
+ }
1113
+ /** Fills the scratch buffer with a `GhosttyTerminalModeConfig` for a DEC private mode. */
1114
+ writeModeConfig(mode, value) {
1115
+ this.runtime.setField(this.scratch, 'GhosttyTerminalModeConfig', 'mode', mode);
1116
+ this.runtime.setField(this.scratch, 'GhosttyTerminalModeConfig', 'value', value ? 1 : 0);
1117
+ }
1118
+ getU16(data) {
1119
+ this.runtime.bytes(this.scratch, 2).fill(0);
1120
+ this.assertSuccess('ghostty_render_state_get', this.runtime.call('ghostty_render_state_get', this.renderState, data, this.scratch));
1121
+ return this.runtime.view(this.scratch, 2).getUint16(0, true);
1122
+ }
1123
+ getU32(data) {
1124
+ this.runtime.bytes(this.scratch, 4).fill(0);
1125
+ this.assertSuccess('ghostty_render_state_get', this.runtime.call('ghostty_render_state_get', this.renderState, data, this.scratch));
1126
+ return this.runtime.view(this.scratch, 4).getUint32(0, true);
1127
+ }
1128
+ getBool(data) {
1129
+ this.runtime.bytes(this.scratch, 1)[0] = 0;
1130
+ this.assertSuccess('ghostty_render_state_get', this.runtime.call('ghostty_render_state_get', this.renderState, data, this.scratch));
1131
+ return this.runtime.bytes(this.scratch, 1)[0] !== 0;
1132
+ }
1133
+ getColor(data, fallback) {
1134
+ this.runtime.bytes(this.scratch, 3).fill(0);
1135
+ const result = this.runtime.call('ghostty_render_state_get', this.renderState, data, this.scratch);
1136
+ return result === GHOSTTY_SUCCESS ? this.readColor(this.scratch) : fallback;
1137
+ }
1138
+ getRowBool(iterator, data) {
1139
+ this.runtime.bytes(this.scratch, 1)[0] = 0;
1140
+ return (this.runtime.call('ghostty_render_state_row_get', iterator, data, this.scratch) ===
1141
+ GHOSTTY_SUCCESS && this.runtime.bytes(this.scratch, 1)[0] !== 0);
1142
+ }
1143
+ getCellU32(iterator, data) {
1144
+ this.runtime.bytes(this.scratch, 4).fill(0);
1145
+ const result = this.runtime.call('ghostty_render_state_row_cells_get', iterator, data, this.scratch);
1146
+ return result === GHOSTTY_SUCCESS ? this.runtime.view(this.scratch, 4).getUint32(0, true) : 0;
1147
+ }
1148
+ getCellBool(iterator, data) {
1149
+ this.runtime.bytes(this.scratch, 1)[0] = 0;
1150
+ return (this.runtime.call('ghostty_render_state_row_cells_get', iterator, data, this.scratch) ===
1151
+ GHOSTTY_SUCCESS && this.runtime.bytes(this.scratch, 1)[0] !== 0);
1152
+ }
1153
+ getCellColor(iterator, data, fallback) {
1154
+ this.runtime.bytes(this.scratch, 3).fill(0);
1155
+ const result = this.runtime.call('ghostty_render_state_row_cells_get', iterator, data, this.scratch);
1156
+ return result === GHOSTTY_SUCCESS ? this.readColor(this.scratch) : fallback;
1157
+ }
1158
+ readColor(pointer) {
1159
+ const bytes = this.runtime.bytes(pointer, 3);
1160
+ return { r: bytes[0] ?? 0, g: bytes[1] ?? 0, b: bytes[2] ?? 0 };
1161
+ }
1162
+ emptyCell(foreground, background) {
1163
+ return {
1164
+ text: '',
1165
+ wide: 0,
1166
+ foreground,
1167
+ background,
1168
+ bold: false,
1169
+ italic: false,
1170
+ invisible: false,
1171
+ strikethrough: false,
1172
+ overline: false,
1173
+ underline: false,
1174
+ selected: false
1175
+ };
1176
+ }
1177
+ assertSuccess(operation, result) {
1178
+ if (result !== GHOSTTY_SUCCESS)
1179
+ throw new Error(`${operation} failed with result ${result}`);
1180
+ }
1181
+ ensureActive() {
1182
+ if (this.disposed)
1183
+ throw new Error('libghostty-vt terminal has been disposed');
1184
+ }
1185
+ }
1186
+ /** Whether two colors are the same. */
1187
+ export function ghosttyColorsEqual(left, right) {
1188
+ return sameColor(left, right);
1189
+ }