@m4ike1/ion-tui 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 (196) hide show
  1. package/README.md +114 -0
  2. package/dist/alt-screen-search.d.ts +46 -0
  3. package/dist/alt-screen-search.d.ts.map +1 -0
  4. package/dist/alt-screen-search.js +282 -0
  5. package/dist/alt-screen-search.js.map +1 -0
  6. package/dist/autocomplete.d.ts +75 -0
  7. package/dist/autocomplete.d.ts.map +1 -0
  8. package/dist/autocomplete.js +749 -0
  9. package/dist/autocomplete.js.map +1 -0
  10. package/dist/components/alt-screen-flash.d.ts +13 -0
  11. package/dist/components/alt-screen-flash.d.ts.map +1 -0
  12. package/dist/components/alt-screen-flash.js +37 -0
  13. package/dist/components/alt-screen-flash.js.map +1 -0
  14. package/dist/components/box.d.ts +24 -0
  15. package/dist/components/box.d.ts.map +1 -0
  16. package/dist/components/box.js +133 -0
  17. package/dist/components/box.js.map +1 -0
  18. package/dist/components/cancellable-loader.d.ts +22 -0
  19. package/dist/components/cancellable-loader.d.ts.map +1 -0
  20. package/dist/components/cancellable-loader.js +35 -0
  21. package/dist/components/cancellable-loader.js.map +1 -0
  22. package/dist/components/editor.d.ts +266 -0
  23. package/dist/components/editor.d.ts.map +1 -0
  24. package/dist/components/editor.js +2087 -0
  25. package/dist/components/editor.js.map +1 -0
  26. package/dist/components/h-stack.d.ts +7 -0
  27. package/dist/components/h-stack.d.ts.map +1 -0
  28. package/dist/components/h-stack.js +43 -0
  29. package/dist/components/h-stack.js.map +1 -0
  30. package/dist/components/image.d.ts +28 -0
  31. package/dist/components/image.d.ts.map +1 -0
  32. package/dist/components/image.js +90 -0
  33. package/dist/components/image.js.map +1 -0
  34. package/dist/components/input.d.ts +48 -0
  35. package/dist/components/input.d.ts.map +1 -0
  36. package/dist/components/input.js +417 -0
  37. package/dist/components/input.js.map +1 -0
  38. package/dist/components/loader.d.ts +33 -0
  39. package/dist/components/loader.d.ts.map +1 -0
  40. package/dist/components/loader.js +76 -0
  41. package/dist/components/loader.js.map +1 -0
  42. package/dist/components/markdown.d.ts +103 -0
  43. package/dist/components/markdown.d.ts.map +1 -0
  44. package/dist/components/markdown.js +858 -0
  45. package/dist/components/markdown.js.map +1 -0
  46. package/dist/components/mouse-region.d.ts +12 -0
  47. package/dist/components/mouse-region.d.ts.map +1 -0
  48. package/dist/components/mouse-region.js +21 -0
  49. package/dist/components/mouse-region.js.map +1 -0
  50. package/dist/components/scroll-view.d.ts +68 -0
  51. package/dist/components/scroll-view.d.ts.map +1 -0
  52. package/dist/components/scroll-view.js +199 -0
  53. package/dist/components/scroll-view.js.map +1 -0
  54. package/dist/components/select-list.d.ts +53 -0
  55. package/dist/components/select-list.d.ts.map +1 -0
  56. package/dist/components/select-list.js +206 -0
  57. package/dist/components/select-list.js.map +1 -0
  58. package/dist/components/settings-list.d.ts +60 -0
  59. package/dist/components/settings-list.d.ts.map +1 -0
  60. package/dist/components/settings-list.js +252 -0
  61. package/dist/components/settings-list.js.map +1 -0
  62. package/dist/components/spacer.d.ts +12 -0
  63. package/dist/components/spacer.d.ts.map +1 -0
  64. package/dist/components/spacer.js +23 -0
  65. package/dist/components/spacer.js.map +1 -0
  66. package/dist/components/stack.d.ts +32 -0
  67. package/dist/components/stack.d.ts.map +1 -0
  68. package/dist/components/stack.js +111 -0
  69. package/dist/components/stack.js.map +1 -0
  70. package/dist/components/text.d.ts +19 -0
  71. package/dist/components/text.d.ts.map +1 -0
  72. package/dist/components/text.js +90 -0
  73. package/dist/components/text.js.map +1 -0
  74. package/dist/components/truncated-text.d.ts +13 -0
  75. package/dist/components/truncated-text.d.ts.map +1 -0
  76. package/dist/components/truncated-text.js +51 -0
  77. package/dist/components/truncated-text.js.map +1 -0
  78. package/dist/components/v-stack.d.ts +8 -0
  79. package/dist/components/v-stack.d.ts.map +1 -0
  80. package/dist/components/v-stack.js +26 -0
  81. package/dist/components/v-stack.js.map +1 -0
  82. package/dist/components/virtual-list.d.ts +51 -0
  83. package/dist/components/virtual-list.d.ts.map +1 -0
  84. package/dist/components/virtual-list.js +170 -0
  85. package/dist/components/virtual-list.js.map +1 -0
  86. package/dist/editor-component.d.ts +39 -0
  87. package/dist/editor-component.d.ts.map +1 -0
  88. package/dist/editor-component.js +2 -0
  89. package/dist/editor-component.js.map +1 -0
  90. package/dist/fuzzy.d.ts +16 -0
  91. package/dist/fuzzy.d.ts.map +1 -0
  92. package/dist/fuzzy.js +110 -0
  93. package/dist/fuzzy.js.map +1 -0
  94. package/dist/index.d.ts +34 -0
  95. package/dist/index.d.ts.map +1 -0
  96. package/dist/index.js +46 -0
  97. package/dist/index.js.map +1 -0
  98. package/dist/keybindings.d.ts +366 -0
  99. package/dist/keybindings.d.ts.map +1 -0
  100. package/dist/keybindings.js +331 -0
  101. package/dist/keybindings.js.map +1 -0
  102. package/dist/keys.d.ts +184 -0
  103. package/dist/keys.d.ts.map +1 -0
  104. package/dist/keys.js +1174 -0
  105. package/dist/keys.js.map +1 -0
  106. package/dist/kill-ring.d.ts +28 -0
  107. package/dist/kill-ring.d.ts.map +1 -0
  108. package/dist/kill-ring.js +44 -0
  109. package/dist/kill-ring.js.map +1 -0
  110. package/dist/latex.d.ts +10 -0
  111. package/dist/latex.d.ts.map +1 -0
  112. package/dist/latex.js +1285 -0
  113. package/dist/latex.js.map +1 -0
  114. package/dist/layout-node.d.ts +59 -0
  115. package/dist/layout-node.d.ts.map +1 -0
  116. package/dist/layout-node.js +12 -0
  117. package/dist/layout-node.js.map +1 -0
  118. package/dist/layout.d.ts +42 -0
  119. package/dist/layout.d.ts.map +1 -0
  120. package/dist/layout.js +404 -0
  121. package/dist/layout.js.map +1 -0
  122. package/dist/native-modifiers.d.ts +4 -0
  123. package/dist/native-modifiers.d.ts.map +1 -0
  124. package/dist/native-modifiers.js +13 -0
  125. package/dist/native-modifiers.js.map +1 -0
  126. package/dist/native-module-path.d.ts +7 -0
  127. package/dist/native-module-path.d.ts.map +1 -0
  128. package/dist/native-module-path.js +19 -0
  129. package/dist/native-module-path.js.map +1 -0
  130. package/dist/native-platform.d.ts +18 -0
  131. package/dist/native-platform.d.ts.map +1 -0
  132. package/dist/native-platform.js +42 -0
  133. package/dist/native-platform.js.map +1 -0
  134. package/dist/pty-host.d.ts +224 -0
  135. package/dist/pty-host.d.ts.map +1 -0
  136. package/dist/pty-host.js +347 -0
  137. package/dist/pty-host.js.map +1 -0
  138. package/dist/stdin-buffer.d.ts +56 -0
  139. package/dist/stdin-buffer.d.ts.map +1 -0
  140. package/dist/stdin-buffer.js +366 -0
  141. package/dist/stdin-buffer.js.map +1 -0
  142. package/dist/terminal-colors.d.ts +10 -0
  143. package/dist/terminal-colors.d.ts.map +1 -0
  144. package/dist/terminal-colors.js +59 -0
  145. package/dist/terminal-colors.js.map +1 -0
  146. package/dist/terminal-image.d.ts +118 -0
  147. package/dist/terminal-image.d.ts.map +1 -0
  148. package/dist/terminal-image.js +550 -0
  149. package/dist/terminal-image.js.map +1 -0
  150. package/dist/terminal.d.ts +123 -0
  151. package/dist/terminal.d.ts.map +1 -0
  152. package/dist/terminal.js +442 -0
  153. package/dist/terminal.js.map +1 -0
  154. package/dist/tui-alt-screen.d.ts +165 -0
  155. package/dist/tui-alt-screen.d.ts.map +1 -0
  156. package/dist/tui-alt-screen.js +1515 -0
  157. package/dist/tui-alt-screen.js.map +1 -0
  158. package/dist/tui-main-screen.d.ts +39 -0
  159. package/dist/tui-main-screen.d.ts.map +1 -0
  160. package/dist/tui-main-screen.js +594 -0
  161. package/dist/tui-main-screen.js.map +1 -0
  162. package/dist/tui.d.ts +431 -0
  163. package/dist/tui.d.ts.map +1 -0
  164. package/dist/tui.js +1142 -0
  165. package/dist/tui.js.map +1 -0
  166. package/dist/undo-stack.d.ts +17 -0
  167. package/dist/undo-stack.d.ts.map +1 -0
  168. package/dist/undo-stack.js +25 -0
  169. package/dist/undo-stack.js.map +1 -0
  170. package/dist/utils.d.ts +98 -0
  171. package/dist/utils.d.ts.map +1 -0
  172. package/dist/utils.js +1200 -0
  173. package/dist/utils.js.map +1 -0
  174. package/dist/word-navigation.d.ts +25 -0
  175. package/dist/word-navigation.d.ts.map +1 -0
  176. package/dist/word-navigation.js +96 -0
  177. package/dist/word-navigation.js.map +1 -0
  178. package/native/clipboard.h +170 -0
  179. package/native/darwin/README.md +22 -0
  180. package/native/darwin/build.sh +69 -0
  181. package/native/darwin/prebuilds/darwin-arm64/darwin-platform.node +0 -0
  182. package/native/darwin/prebuilds/darwin-x64/darwin-platform.node +0 -0
  183. package/native/darwin/src/darwin-platform.m +93 -0
  184. package/native/linux/README.md +23 -0
  185. package/native/linux/build.sh +65 -0
  186. package/native/linux/prebuilds/linux-arm64/linux-platform-x11.node +0 -0
  187. package/native/linux/prebuilds/linux-x64/linux-platform-x11.node +0 -0
  188. package/native/linux/src/clipboard-worker.h +70 -0
  189. package/native/linux/src/linux-platform-x11.c +274 -0
  190. package/native/napi.h +89 -0
  191. package/native/win32/README.md +31 -0
  192. package/native/win32/build.mjs +232 -0
  193. package/native/win32/prebuilds/win32-arm64/win32-platform.node +0 -0
  194. package/native/win32/prebuilds/win32-x64/win32-platform.node +0 -0
  195. package/native/win32/src/win32-platform.c +241 -0
  196. package/package.json +62 -0
@@ -0,0 +1,1515 @@
1
+ import { AltScreenSearchComponent, AltScreenSearchIndex, getAltScreenSearchMatchKey, } from "./alt-screen-search.js";
2
+ import { AltScreenFlashContainer } from "./components/alt-screen-flash.js";
3
+ import { ScrollView } from "./components/scroll-view.js";
4
+ import { getKeybindings } from "./keybindings.js";
5
+ import { isKeyRelease } from "./keys.js";
6
+ import { getLayoutBoxesAt, getScrollbarGeometry, getScrollViewBox, getScrollViewsAt, renderLayoutFrame, } from "./layout.js";
7
+ import { getLayoutNode } from "./layout-node.js";
8
+ import { deleteAllKittyImages, deleteAllKittyPlacements, deleteKittyImage, getCapabilities, getKittyImagePlacement, isImageLine, setCapabilities, } from "./terminal-image.js";
9
+ import { Container, CURSOR_MARKER, compositeTuiLine, dispatchMouseEvent, retargetMouseEvent, TuiBase, VIEWPORT_TUI, } from "./tui.js";
10
+ import { extractAnsiCode, getGraphemeCellRange, getOsc8LinkAtColumn, getWordSegmenter, sliceByColumn, stripTerminalSequences, truncateToWidth, visibleWidth, } from "./utils.js";
11
+ const ENTER_ALT_SCREEN = "\x1b[?1049h";
12
+ const EXIT_ALT_SCREEN = "\x1b[?1049l";
13
+ const DISABLE_AUTOWRAP = "\x1b[?7l";
14
+ const ENABLE_AUTOWRAP = "\x1b[?7h";
15
+ const ENABLE_BUTTON_MOTION_MOUSE = "\x1b[?1000h\x1b[?1002h\x1b[?1004h\x1b[?1006h";
16
+ const ENABLE_ALL_MOTION_MOUSE = "\x1b[?1000h\x1b[?1002h\x1b[?1003h\x1b[?1004h\x1b[?1006h";
17
+ const DISABLE_MOUSE = "\x1b[?1006l\x1b[?1004l\x1b[?1003l\x1b[?1002l\x1b[?1000l";
18
+ const FOCUS_IN = "\x1b[I";
19
+ const FOCUS_OUT = "\x1b[O";
20
+ const BEGIN_SYNCHRONIZED_OUTPUT = "\x1b[?2026h";
21
+ const END_SYNCHRONIZED_OUTPUT = "\x1b[?2026l";
22
+ const OSC133_ZONE_PREFIX = /^(?:\x1b\]133;[ABC](?:\x07|\x1b\\))+/;
23
+ const OSC133_PROMPT_START = /^\x1b\]133;A(?:\x07|\x1b\\)/;
24
+ const PAGE_SCROLL_OVERLAP = 4;
25
+ const ALT_WHEEL_SCROLL_MULTIPLIER = 5;
26
+ const MAX_CACHED_OFFSCREEN_KITTY_IMAGES = 16;
27
+ const MAX_CACHED_OFFSCREEN_KITTY_TRANSMISSION_BYTES = 32 * 1024 * 1024;
28
+ const MAX_CACHED_OFFSCREEN_KITTY_DECODED_BYTES = 64 * 1024 * 1024;
29
+ const DOUBLE_CLICK_INTERVAL_MS = 500;
30
+ // Regular mode delegates double-click selection to the terminal emulator. Fullscreen owns mouse selection,
31
+ // so mirror common terminal word-selection behavior by keeping paths and kebab-case tokens whole.
32
+ const TERMINAL_WORD_SELECTION_JOINERS = new Set(["/", "-"]);
33
+ const wordSegmenter = getWordSegmenter();
34
+ /** Alternate-screen TUI with a scrollable, application-owned viewport. */
35
+ export class TuiAltScreen extends TuiBase {
36
+ mode = "fullscreen";
37
+ [VIEWPORT_TUI] = true;
38
+ previousScreen = [];
39
+ lastDocument = [];
40
+ previousScreenWidth = 0;
41
+ previousScreenHeight = 0;
42
+ layoutRoot;
43
+ currentLayout;
44
+ implicitDocument;
45
+ implicitScrollView;
46
+ flashes;
47
+ altScreenActive = false;
48
+ imageProtocol = null;
49
+ savedCapabilities;
50
+ uploadedKittyImages = new Map();
51
+ selectionAnchor;
52
+ selectionFocus;
53
+ selectionGranularity = "character";
54
+ selectionInitialRange;
55
+ lastClick;
56
+ selectionDragPointer;
57
+ selectionAutoScrollDirection = 0;
58
+ selectionAutoScrollTimer;
59
+ selectionPressActive = false;
60
+ scrollbarDrag;
61
+ scrollbarHover;
62
+ scrollToEndIndicatorRect;
63
+ activeSearch;
64
+ pressedUrl;
65
+ selectionDragged = false;
66
+ mouseCapture;
67
+ mousePressTarget;
68
+ mousePressPoint;
69
+ mousePressMoved = false;
70
+ lastComponentClick;
71
+ wheelScrollLines;
72
+ mouseEnabled;
73
+ searchMatchStyle;
74
+ searchCurrentMatchStyle;
75
+ searchNavigationButtonStyle;
76
+ scrollToEndIndicator;
77
+ openUrl;
78
+ onRightClickPaste;
79
+ copyOnSelect;
80
+ copySelection;
81
+ constructor(terminal, showHardwareCursor, logDirectory, options = {}) {
82
+ super(terminal, showHardwareCursor, logDirectory);
83
+ this.implicitDocument = {
84
+ render: (width) => super.render(width),
85
+ handleMouse: (event) => super.handleMouse(event),
86
+ invalidate: () => {
87
+ for (const child of this.children)
88
+ child.invalidate();
89
+ },
90
+ };
91
+ this.implicitScrollView = new ScrollView(this.implicitDocument, { follow: "end", primary: true });
92
+ this.flashes = new AltScreenFlashContainer(() => this.requestRender());
93
+ this.wheelScrollLines = Math.max(1, Math.floor(options.wheelScrollLines ?? 1));
94
+ this.mouseEnabled = options.mouse ?? true;
95
+ this.searchMatchStyle = options.searchMatchStyle ?? ((text) => `\x1b[4m${text}\x1b[24m`);
96
+ this.searchCurrentMatchStyle = options.searchCurrentMatchStyle ?? ((text) => `\x1b[1;7m${text}\x1b[22;27m`);
97
+ this.searchNavigationButtonStyle = options.searchNavigationButtonStyle ?? ((text) => text);
98
+ this.scrollToEndIndicator = options.scrollToEndIndicator;
99
+ this.openUrl = options.openUrl;
100
+ this.onRightClickPaste = options.onRightClickPaste;
101
+ this.copyOnSelect = options.copyOnSelect ?? true;
102
+ this.copySelection = options.copySelection;
103
+ this.addInputListener((data) => this.handleViewportInput(data));
104
+ }
105
+ get viewportTop() {
106
+ return this.getPrimaryScrollView().scrollTop;
107
+ }
108
+ get isFollowingOutput() {
109
+ return this.getPrimaryScrollView().isFollowingEnd;
110
+ }
111
+ getCopyOnSelect() {
112
+ return this.copyOnSelect;
113
+ }
114
+ setCopyOnSelect(enabled) {
115
+ this.copyOnSelect = enabled;
116
+ }
117
+ /** Whether the fullscreen viewport has a non-empty active text selection. */
118
+ hasActiveSelection() {
119
+ return this.getActiveSelectionText() !== undefined;
120
+ }
121
+ /** Copy the active fullscreen text selection, if any, using the configured selection clipboard path. */
122
+ async copyActiveSelectionToClipboard() {
123
+ const text = this.getActiveSelectionText();
124
+ if (!text)
125
+ return false;
126
+ return this.copyTextToClipboard(text);
127
+ }
128
+ setLayoutRoot(component) {
129
+ if (this.layoutRoot === component)
130
+ return;
131
+ this.layoutRoot = component;
132
+ this.currentLayout = undefined;
133
+ this.requestRender();
134
+ }
135
+ render(width) {
136
+ return this.layoutRoot?.render(width) ?? super.render(width);
137
+ }
138
+ getMountedRoots() {
139
+ return this.layoutRoot ? [this.layoutRoot] : this.children;
140
+ }
141
+ getPrimaryScrollView() {
142
+ return this.currentLayout?.primaryScrollView ?? this.implicitScrollView;
143
+ }
144
+ beforeTerminalStart() {
145
+ this.stopSelectionAutoScroll();
146
+ this.selectionPressActive = false;
147
+ this.stopScrollbarHover();
148
+ this.stopScrollbarDrag();
149
+ this.flashes.dispose();
150
+ this.altScreenActive = true;
151
+ const capabilities = getCapabilities();
152
+ this.imageProtocol = capabilities.images;
153
+ this.uploadedKittyImages.clear();
154
+ if (capabilities.images === "iterm2") {
155
+ this.savedCapabilities = capabilities;
156
+ setCapabilities({ ...capabilities, images: null });
157
+ this.invalidate();
158
+ }
159
+ this.lastDocument = [];
160
+ this.selectionAnchor = undefined;
161
+ this.selectionFocus = undefined;
162
+ this.selectionGranularity = "character";
163
+ this.selectionInitialRange = undefined;
164
+ this.lastClick = undefined;
165
+ this.pressedUrl = undefined;
166
+ this.selectionDragged = false;
167
+ this.clearComponentMouseGesture();
168
+ this.lastComponentClick = undefined;
169
+ this.resetRenderState();
170
+ const term = process.env.TERM?.toLowerCase() ?? "";
171
+ // Multiplexers can lag when every pointer movement is forwarded. Button-motion
172
+ // tracking preserves clicks, wheel events, selections, and scrollbar dragging.
173
+ const mouseSequence = process.env.TMUX !== undefined ||
174
+ process.env.ZELLIJ !== undefined ||
175
+ process.env.STY !== undefined ||
176
+ term.startsWith("tmux") ||
177
+ term.startsWith("screen")
178
+ ? ENABLE_BUTTON_MOTION_MOUSE
179
+ : ENABLE_ALL_MOTION_MOUSE;
180
+ this.terminal.write(`${ENTER_ALT_SCREEN}${DISABLE_AUTOWRAP}${this.mouseEnabled ? mouseSequence : ""}\x1b[2J\x1b[H\x1b[?25l`);
181
+ }
182
+ beforeTerminalStop(_options) {
183
+ this.closeSearch();
184
+ this.stopSelectionAutoScroll();
185
+ this.selectionPressActive = false;
186
+ this.stopScrollbarHover();
187
+ this.stopScrollbarDrag();
188
+ this.clearComponentMouseGesture();
189
+ this.flashes.dispose();
190
+ if (!this.altScreenActive)
191
+ return;
192
+ this.terminal.write(`${BEGIN_SYNCHRONIZED_OUTPUT}${this.deleteKittyImages()}${this.mouseEnabled ? DISABLE_MOUSE : ""}${ENABLE_AUTOWRAP}${END_SYNCHRONIZED_OUTPUT}`);
193
+ this.uploadedKittyImages.clear();
194
+ }
195
+ afterTerminalStop(options) {
196
+ if (!this.altScreenActive)
197
+ return;
198
+ this.altScreenActive = false;
199
+ if (options.preserveScreen) {
200
+ this.terminal.write(`${BEGIN_SYNCHRONIZED_OUTPUT}${EXIT_ALT_SCREEN}\x1b[?25h${END_SYNCHRONIZED_OUTPUT}`);
201
+ }
202
+ else {
203
+ const width = Math.max(1, this.terminal.columns);
204
+ const documentLines = this.render(width).map((line) => line.replace(OSC133_ZONE_PREFIX, ""));
205
+ this.lastDocument = this.applyLineResets(documentLines.map((line) => line.replaceAll(CURSOR_MARKER, ""))).map((line) => (isImageLine(line) || visibleWidth(line) <= width ? line : sliceByColumn(line, 0, width, true)));
206
+ let buffer = `${BEGIN_SYNCHRONIZED_OUTPUT}${EXIT_ALT_SCREEN}${DISABLE_AUTOWRAP}`;
207
+ for (let row = 0; row < this.lastDocument.length; row++) {
208
+ if (row > 0)
209
+ buffer += "\r\n";
210
+ buffer += `\r\x1b[2K${this.lastDocument[row] ?? ""}`;
211
+ }
212
+ buffer += `\x1b[0m${ENABLE_AUTOWRAP}\r\n\x1b[?25h${END_SYNCHRONIZED_OUTPUT}`;
213
+ this.terminal.write(buffer);
214
+ }
215
+ if (this.savedCapabilities) {
216
+ setCapabilities(this.savedCapabilities);
217
+ this.savedCapabilities = undefined;
218
+ }
219
+ }
220
+ deleteKittyImages() {
221
+ return this.imageProtocol === "kitty" ? deleteAllKittyImages() : "";
222
+ }
223
+ prepareKittyScreen(screen) {
224
+ const visibleImageIds = new Set();
225
+ const lines = screen.map((line) => {
226
+ const placement = getKittyImagePlacement(line);
227
+ if (!placement)
228
+ return line;
229
+ visibleImageIds.add(placement.imageId);
230
+ const cachedImage = this.uploadedKittyImages.get(placement.imageId);
231
+ const nextCachedImage = {
232
+ transmissionGeneration: placement.transmissionGeneration,
233
+ transmissionBytes: placement.transmissionBytes,
234
+ estimatedDecodedBytes: placement.estimatedDecodedBytes,
235
+ };
236
+ if (cachedImage)
237
+ this.uploadedKittyImages.delete(placement.imageId);
238
+ this.uploadedKittyImages.set(placement.imageId, nextCachedImage);
239
+ return cachedImage?.transmissionGeneration === placement.transmissionGeneration
240
+ ? placement.replacementLine
241
+ : line;
242
+ });
243
+ let cachedOffscreenImageCount = 0;
244
+ let cachedOffscreenTransmissionBytes = 0;
245
+ let cachedOffscreenDecodedBytes = 0;
246
+ for (const [imageId, cachedImage] of this.uploadedKittyImages) {
247
+ if (visibleImageIds.has(imageId))
248
+ continue;
249
+ cachedOffscreenImageCount += 1;
250
+ cachedOffscreenTransmissionBytes += cachedImage.transmissionBytes;
251
+ cachedOffscreenDecodedBytes += cachedImage.estimatedDecodedBytes;
252
+ }
253
+ let evictedImageDeletion = "";
254
+ for (const [imageId, cachedImage] of this.uploadedKittyImages) {
255
+ if (cachedOffscreenImageCount <= MAX_CACHED_OFFSCREEN_KITTY_IMAGES &&
256
+ cachedOffscreenTransmissionBytes <= MAX_CACHED_OFFSCREEN_KITTY_TRANSMISSION_BYTES &&
257
+ cachedOffscreenDecodedBytes <= MAX_CACHED_OFFSCREEN_KITTY_DECODED_BYTES) {
258
+ break;
259
+ }
260
+ if (visibleImageIds.has(imageId))
261
+ continue;
262
+ evictedImageDeletion += deleteKittyImage(imageId);
263
+ this.uploadedKittyImages.delete(imageId);
264
+ cachedOffscreenImageCount -= 1;
265
+ cachedOffscreenTransmissionBytes -= cachedImage.transmissionBytes;
266
+ cachedOffscreenDecodedBytes -= cachedImage.estimatedDecodedBytes;
267
+ }
268
+ return { lines, evictedImageDeletion };
269
+ }
270
+ resetRenderState() {
271
+ this.previousScreen = [];
272
+ this.previousScreenWidth = 0;
273
+ this.previousScreenHeight = 0;
274
+ this.currentLayout = undefined;
275
+ }
276
+ scrollBy(lines) {
277
+ this.getPrimaryScrollView().scrollBy(lines);
278
+ this.requestRender();
279
+ }
280
+ scrollToTop() {
281
+ this.getPrimaryScrollView().scrollToStart();
282
+ this.requestRender();
283
+ }
284
+ scrollToBottom() {
285
+ this.getPrimaryScrollView().scrollToEnd();
286
+ this.requestRender();
287
+ }
288
+ scrollToPrompt(direction) {
289
+ if (!this.currentLayout)
290
+ return;
291
+ const scrollView = this.getPrimaryScrollView();
292
+ const lines = getScrollViewBox(this.currentLayout, scrollView)?.scrollContentLines;
293
+ if (!lines)
294
+ return;
295
+ for (let row = scrollView.scrollTop + direction; row >= 0 && row < lines.length; row += direction) {
296
+ if (!OSC133_PROMPT_START.test(lines[row] ?? ""))
297
+ continue;
298
+ scrollView.scrollTo(row);
299
+ this.requestRender();
300
+ return;
301
+ }
302
+ }
303
+ toggleSearch() {
304
+ if (this.activeSearch) {
305
+ this.closeSearch();
306
+ return;
307
+ }
308
+ const component = new AltScreenSearchComponent((query) => this.updateSearchQuery(query), this.searchNavigationButtonStyle);
309
+ const search = {
310
+ component,
311
+ index: new AltScreenSearchIndex(),
312
+ query: "",
313
+ matches: [],
314
+ selectedIndex: -1,
315
+ anchorRow: this.getPrimaryScrollView().scrollTop,
316
+ selectionMode: "query",
317
+ };
318
+ this.activeSearch = search;
319
+ search.overlay = this.showOverlay(component, {
320
+ anchor: "top-right",
321
+ width: "40%",
322
+ minWidth: 32,
323
+ margin: 1,
324
+ });
325
+ }
326
+ closeSearch() {
327
+ const search = this.activeSearch;
328
+ if (!search)
329
+ return;
330
+ this.activeSearch = undefined;
331
+ search.overlay?.hide();
332
+ this.requestRender();
333
+ }
334
+ /**
335
+ * Fullscreen Escape order: focused autocomplete first (base), then
336
+ * transcript search when it is the topmost capturing layer, then the base
337
+ * overlay-forwarding rule. A dialog above the search owns the press.
338
+ */
339
+ dismissInnermostLayer(data) {
340
+ if (super.dismissInnermostLayer(data))
341
+ return true;
342
+ const search = this.activeSearch;
343
+ if (search &&
344
+ this.getTopmostVisibleCapturingOverlay() === search.component &&
345
+ getKeybindings().matches(data, "tui.altScreen.searchClose")) {
346
+ this.closeSearch();
347
+ return true;
348
+ }
349
+ return false;
350
+ }
351
+ updateSearchQuery(query) {
352
+ const search = this.activeSearch;
353
+ if (!search || query === search.query)
354
+ return;
355
+ const selected = search.matches[search.selectedIndex];
356
+ search.anchorRow = selected?.segments[0]?.row ?? this.getPrimaryScrollView().scrollTop;
357
+ search.query = query;
358
+ search.selectionMode = "query";
359
+ search.component.setResult(-1, 0);
360
+ this.requestRender();
361
+ }
362
+ navigateSearch(direction) {
363
+ const search = this.activeSearch;
364
+ if (!search?.query)
365
+ return;
366
+ search.selectionMode = direction < 0 ? "previous" : "next";
367
+ this.requestRender();
368
+ }
369
+ getSearchNavigationDirectionAt(x, y) {
370
+ const search = this.activeSearch;
371
+ const bounds = search?.overlay?.getBounds();
372
+ if (!search || !bounds)
373
+ return undefined;
374
+ if (x < bounds.col || x >= bounds.col + bounds.width || y < bounds.row || y >= bounds.row + bounds.height) {
375
+ return undefined;
376
+ }
377
+ return search.component.getNavigationDirectionAt(y - bounds.row, x - bounds.col);
378
+ }
379
+ handleSearchMouseEvent(event) {
380
+ const search = this.activeSearch;
381
+ if (!search)
382
+ return false;
383
+ const direction = this.getSearchNavigationDirectionAt(event.x, event.y);
384
+ if (search.component.setHoveredNavigationDirection(direction))
385
+ this.requestRender();
386
+ if (direction === undefined || event.release || (event.button & 32) !== 0 || (event.button & 3) !== 0) {
387
+ return false;
388
+ }
389
+ this.navigateSearch(direction);
390
+ return true;
391
+ }
392
+ refreshSearch(layout) {
393
+ const search = this.activeSearch;
394
+ if (!search)
395
+ return false;
396
+ const scrollView = layout.primaryScrollView ?? this.implicitScrollView;
397
+ const box = getScrollViewBox(layout, scrollView);
398
+ const lines = box?.scrollContentLines;
399
+ if (!lines || !search.query.trim()) {
400
+ search.matches = [];
401
+ search.selectedIndex = -1;
402
+ search.selectedKey = undefined;
403
+ search.selectionMode = "retain";
404
+ search.component.setResult(-1, 0);
405
+ return false;
406
+ }
407
+ const shouldRevealSelection = search.selectionMode !== "retain";
408
+ const result = search.index.search(lines, search.query);
409
+ const matches = result.matches;
410
+ search.matches = matches;
411
+ if (!result.changed && search.selectionMode === "retain")
412
+ return false;
413
+ const exactIndex = result.changed
414
+ ? search.selectedKey
415
+ ? matches.findIndex((match) => getAltScreenSearchMatchKey(match) === search.selectedKey)
416
+ : -1
417
+ : search.selectedIndex;
418
+ let selectedIndex = -1;
419
+ if (matches.length > 0) {
420
+ if (search.selectionMode === "query") {
421
+ let low = 0;
422
+ let high = matches.length;
423
+ while (low < high) {
424
+ const middle = low + Math.floor((high - low) / 2);
425
+ if ((matches[middle].segments[0]?.row ?? 0) < search.anchorRow)
426
+ low = middle + 1;
427
+ else
428
+ high = middle;
429
+ }
430
+ selectedIndex = low < matches.length ? low : 0;
431
+ }
432
+ else if (search.selectionMode === "next") {
433
+ const baseIndex = exactIndex >= 0 ? exactIndex : Math.min(search.selectedIndex, matches.length - 1);
434
+ selectedIndex = baseIndex < 0 ? 0 : (baseIndex + 1) % matches.length;
435
+ }
436
+ else if (search.selectionMode === "previous") {
437
+ const baseIndex = exactIndex >= 0 ? exactIndex : Math.min(search.selectedIndex, matches.length - 1);
438
+ selectedIndex = baseIndex < 0 ? matches.length - 1 : (baseIndex - 1 + matches.length) % matches.length;
439
+ }
440
+ else {
441
+ selectedIndex =
442
+ exactIndex >= 0 ? exactIndex : Math.min(Math.max(0, search.selectedIndex), matches.length - 1);
443
+ }
444
+ }
445
+ search.selectedIndex = selectedIndex;
446
+ search.selectedKey = selectedIndex >= 0 ? getAltScreenSearchMatchKey(matches[selectedIndex]) : undefined;
447
+ search.selectionMode = "retain";
448
+ search.component.setResult(selectedIndex, matches.length);
449
+ if (!shouldRevealSelection)
450
+ return false;
451
+ const selected = matches[selectedIndex];
452
+ const firstSegment = selected?.segments[0];
453
+ const lastSegment = selected?.segments[selected.segments.length - 1];
454
+ if (!box || !firstSegment || !lastSegment || scrollView.viewportHeight <= 0)
455
+ return false;
456
+ const before = scrollView.scrollTop;
457
+ const visibleBottom = before + scrollView.viewportHeight - 1;
458
+ let target = before;
459
+ if (firstSegment.row < before || lastSegment.row > visibleBottom) {
460
+ target = firstSegment.row - Math.floor(scrollView.viewportHeight / 3);
461
+ }
462
+ scrollView.scrollTo(target, { disableFollow: true });
463
+ return scrollView.scrollTop !== before;
464
+ }
465
+ /** Show a transient message in the alternate-screen flash stack. */
466
+ flash(message, durationMs) {
467
+ this.flashes.flash(message, durationMs);
468
+ }
469
+ shouldDeferViewportInputToOverlay() {
470
+ return this.isOverlayFocused() && this.activeSearch?.overlay?.isFocused() !== true;
471
+ }
472
+ clearComponentMouseGesture() {
473
+ this.mouseCapture = undefined;
474
+ this.mousePressTarget = undefined;
475
+ this.mousePressPoint = undefined;
476
+ this.mousePressMoved = false;
477
+ }
478
+ handleViewportInput(data) {
479
+ if (data === FOCUS_OUT) {
480
+ const hadActiveSelection = this.selectionPressActive;
481
+ const hadNonEmptyActiveSelection = hadActiveSelection && this.getSelectionBounds() !== undefined;
482
+ this.selectionPressActive = false;
483
+ this.stopSelectionAutoScroll();
484
+ this.stopScrollbarHover();
485
+ if (this.activeSearch?.component.setHoveredNavigationDirection(undefined))
486
+ this.requestRender();
487
+ this.stopScrollbarDrag();
488
+ this.pressedUrl = undefined;
489
+ this.selectionDragged = false;
490
+ this.clearComponentMouseGesture();
491
+ this.lastComponentClick = undefined;
492
+ if (hadActiveSelection) {
493
+ this.selectionAnchor = undefined;
494
+ this.selectionFocus = undefined;
495
+ this.selectionGranularity = "character";
496
+ this.selectionInitialRange = undefined;
497
+ if (hadNonEmptyActiveSelection)
498
+ this.requestRender();
499
+ }
500
+ this.lastClick = undefined;
501
+ return { consume: true };
502
+ }
503
+ if (data === FOCUS_IN)
504
+ return { consume: true };
505
+ const wheelEvent = this.parseWheelEvent(data);
506
+ if (wheelEvent) {
507
+ const event = this.createMouseEvent("wheel", wheelEvent.button, wheelEvent.x, wheelEvent.y, {
508
+ wheelDelta: wheelEvent.direction * this.getWheelScrollLines(wheelEvent.button),
509
+ });
510
+ const overlay = this.dispatchMouseToOverlay(event);
511
+ const result = overlay.result ?? (overlay.hit ? undefined : this.dispatchMouseToLayout(event));
512
+ if (result) {
513
+ if (this.applyMouseDispatchResult(event, result))
514
+ this.requestRender();
515
+ return { consume: true };
516
+ }
517
+ if (this.shouldDeferViewportInputToOverlay())
518
+ return undefined;
519
+ this.routeWheel(wheelEvent);
520
+ return { consume: true };
521
+ }
522
+ const mouseEvent = this.parseSgrMouseEvent(data);
523
+ if (mouseEvent) {
524
+ this.handleMouseEvent(mouseEvent);
525
+ return { consume: true };
526
+ }
527
+ if (this.isMouseSequence(data))
528
+ return { consume: true };
529
+ const keybindings = getKeybindings();
530
+ const isRelease = isKeyRelease(data);
531
+ if (keybindings.matches(data, "tui.altScreen.search")) {
532
+ if (!isRelease)
533
+ this.toggleSearch();
534
+ return { consume: true };
535
+ }
536
+ if (this.activeSearch?.overlay?.isFocused()) {
537
+ if (keybindings.matches(data, "tui.altScreen.searchNext")) {
538
+ if (!isRelease)
539
+ this.navigateSearch(1);
540
+ return { consume: true };
541
+ }
542
+ if (keybindings.matches(data, "tui.altScreen.searchPrevious")) {
543
+ if (!isRelease)
544
+ this.navigateSearch(-1);
545
+ return { consume: true };
546
+ }
547
+ if (keybindings.matches(data, "tui.altScreen.searchClose")) {
548
+ if (!isRelease)
549
+ this.closeSearch();
550
+ return { consume: true };
551
+ }
552
+ }
553
+ if (this.shouldDeferViewportInputToOverlay())
554
+ return undefined;
555
+ if (keybindings.matches(data, "tui.altScreen.pageUp")) {
556
+ if (!isRelease) {
557
+ this.scrollBy(-Math.max(1, this.getPrimaryScrollView().viewportHeight - PAGE_SCROLL_OVERLAP));
558
+ }
559
+ return { consume: true };
560
+ }
561
+ if (keybindings.matches(data, "tui.altScreen.pageDown")) {
562
+ if (!isRelease) {
563
+ this.scrollBy(Math.max(1, this.getPrimaryScrollView().viewportHeight - PAGE_SCROLL_OVERLAP));
564
+ }
565
+ return { consume: true };
566
+ }
567
+ if (keybindings.matches(data, "tui.altScreen.halfPageUp")) {
568
+ if (!isRelease)
569
+ this.scrollBy(-Math.max(1, Math.floor(this.getPrimaryScrollView().viewportHeight / 2)));
570
+ return { consume: true };
571
+ }
572
+ if (keybindings.matches(data, "tui.altScreen.halfPageDown")) {
573
+ if (!isRelease)
574
+ this.scrollBy(Math.max(1, Math.floor(this.getPrimaryScrollView().viewportHeight / 2)));
575
+ return { consume: true };
576
+ }
577
+ if (keybindings.matches(data, "tui.altScreen.lineUp")) {
578
+ if (!isRelease)
579
+ this.scrollBy(-1);
580
+ return { consume: true };
581
+ }
582
+ if (keybindings.matches(data, "tui.altScreen.lineDown")) {
583
+ if (!isRelease)
584
+ this.scrollBy(1);
585
+ return { consume: true };
586
+ }
587
+ if (keybindings.matches(data, "tui.altScreen.previousPrompt")) {
588
+ if (!isRelease)
589
+ this.scrollToPrompt(-1);
590
+ return { consume: true };
591
+ }
592
+ if (keybindings.matches(data, "tui.altScreen.nextPrompt")) {
593
+ if (!isRelease)
594
+ this.scrollToPrompt(1);
595
+ return { consume: true };
596
+ }
597
+ if (keybindings.matches(data, "tui.altScreen.top")) {
598
+ if (!isRelease)
599
+ this.scrollToTop();
600
+ return { consume: true };
601
+ }
602
+ if (keybindings.matches(data, "tui.altScreen.bottom")) {
603
+ if (!isRelease)
604
+ this.scrollToBottom();
605
+ return { consume: true };
606
+ }
607
+ return undefined;
608
+ }
609
+ decodeMouseButton(button) {
610
+ switch (button & 3) {
611
+ case 0:
612
+ return "left";
613
+ case 1:
614
+ return "middle";
615
+ case 2:
616
+ return "right";
617
+ default:
618
+ return "none";
619
+ }
620
+ }
621
+ createMouseEvent(type, button, x, y, extra = {}) {
622
+ return {
623
+ type,
624
+ button: type === "wheel" ? "none" : this.decodeMouseButton(button),
625
+ x,
626
+ y,
627
+ screenX: x,
628
+ screenY: y,
629
+ width: Math.max(1, this.terminal.columns),
630
+ height: Math.max(1, this.terminal.rows),
631
+ shift: (button & 4) !== 0,
632
+ alt: (button & 8) !== 0,
633
+ ctrl: (button & 16) !== 0,
634
+ ...(extra.wheelDelta === undefined ? {} : { wheelDelta: extra.wheelDelta }),
635
+ ...(extra.clickCount === undefined ? {} : { clickCount: extra.clickCount }),
636
+ };
637
+ }
638
+ dispatchMouseToLayout(event) {
639
+ if (!this.currentLayout)
640
+ return undefined;
641
+ const visited = new Set();
642
+ const boxes = getLayoutBoxesAt(this.currentLayout, event.screenX, event.screenY);
643
+ for (const box of boxes) {
644
+ if (visited.has(box.component))
645
+ continue;
646
+ if (getLayoutNode(box.component) && box.component.handleMouse === Container.prototype.handleMouse)
647
+ continue;
648
+ visited.add(box.component);
649
+ const result = dispatchMouseEvent(box.component, {
650
+ ...event,
651
+ x: event.screenX - box.rect.x,
652
+ y: event.screenY - box.rect.y,
653
+ width: box.rect.width,
654
+ height: box.rect.height,
655
+ });
656
+ if (result)
657
+ return result;
658
+ }
659
+ return undefined;
660
+ }
661
+ applyMouseDispatchResult(event, result) {
662
+ const focusTarget = this.resolveMouseFocusTarget(result.focusTarget ?? result.target.component);
663
+ const focusChanged = result.focus === true && this.getFocusedComponent() !== focusTarget;
664
+ // A capturing overlay owns keyboard focus until it closes: background
665
+ // mouse gestures must not steal focus out of the modal layer, or keys
666
+ // would leak to the editor beneath the dialog (single focus owner).
667
+ const stealsModalFocus = result.focus === true &&
668
+ this.isFocusInVisibleOverlay(true) &&
669
+ !this.isComponentInVisibleOverlay(focusTarget, true);
670
+ if (result.focus && !stealsModalFocus)
671
+ this.setFocus(focusTarget, { reason: "mouse" });
672
+ if (result.capture)
673
+ this.mouseCapture = result.target;
674
+ return (result.render ??
675
+ (focusChanged ||
676
+ event.type === "press" ||
677
+ event.type === "click" ||
678
+ event.type === "drag" ||
679
+ event.type === "wheel"));
680
+ }
681
+ dispatchMouseToTarget(event, target) {
682
+ return dispatchMouseEvent(target.component, retargetMouseEvent(event, target));
683
+ }
684
+ getComponentClickCount(target, x, y) {
685
+ const now = Date.now();
686
+ const previous = this.lastComponentClick;
687
+ const count = previous &&
688
+ now - previous.timestamp <= DOUBLE_CLICK_INTERVAL_MS &&
689
+ previous.component === target.component &&
690
+ previous.x === x &&
691
+ previous.y === y
692
+ ? (previous.count % 3) + 1
693
+ : 1;
694
+ this.lastComponentClick = { timestamp: now, count, component: target.component, x, y };
695
+ return count;
696
+ }
697
+ clearTextSelection() {
698
+ this.stopSelectionAutoScroll();
699
+ this.selectionPressActive = false;
700
+ this.selectionAnchor = undefined;
701
+ this.selectionFocus = undefined;
702
+ this.selectionGranularity = "character";
703
+ this.selectionInitialRange = undefined;
704
+ this.pressedUrl = undefined;
705
+ this.selectionDragged = false;
706
+ }
707
+ handleMouseEvent(raw) {
708
+ const isMotion = (raw.button & 32) !== 0;
709
+ const type = raw.release
710
+ ? "release"
711
+ : isMotion
712
+ ? this.decodeMouseButton(raw.button) === "none"
713
+ ? "move"
714
+ : "drag"
715
+ : "press";
716
+ const event = this.createMouseEvent(type, raw.button, raw.x, raw.y);
717
+ if (this.mouseCapture || this.mousePressTarget) {
718
+ const target = this.mouseCapture ?? this.mousePressTarget;
719
+ if (this.mousePressPoint && (raw.x !== this.mousePressPoint.x || raw.y !== this.mousePressPoint.y)) {
720
+ this.mousePressMoved = true;
721
+ this.lastComponentClick = undefined;
722
+ }
723
+ let render = false;
724
+ const targetResult = this.dispatchMouseToTarget(event, target);
725
+ if (targetResult)
726
+ render = this.applyMouseDispatchResult(event, targetResult);
727
+ if (raw.release) {
728
+ if (!this.mousePressMoved && this.mousePressPoint?.x === raw.x && this.mousePressPoint.y === raw.y) {
729
+ const clickEvent = this.createMouseEvent("click", raw.button, raw.x, raw.y, {
730
+ clickCount: this.getComponentClickCount(target, raw.x, raw.y),
731
+ });
732
+ const clickResult = this.dispatchMouseToTarget(clickEvent, target);
733
+ if (clickResult)
734
+ render = this.applyMouseDispatchResult(clickEvent, clickResult) || render;
735
+ }
736
+ this.clearComponentMouseGesture();
737
+ }
738
+ if (render)
739
+ this.requestRender();
740
+ return;
741
+ }
742
+ if (this.handleSearchMouseEvent(raw))
743
+ return;
744
+ const overlay = this.dispatchMouseToOverlay(event);
745
+ if (!overlay.hit) {
746
+ if (this.handleScrollToEndIndicatorMouseEvent(raw))
747
+ return;
748
+ const scrollbarHandled = this.handleScrollbarMouseEvent(raw);
749
+ if (!this.scrollbarDrag)
750
+ this.updateScrollbarHover(raw.x, raw.y);
751
+ if (scrollbarHandled)
752
+ return;
753
+ }
754
+ else {
755
+ this.stopScrollbarHover();
756
+ }
757
+ const result = overlay.result ?? (overlay.hit ? undefined : this.dispatchMouseToLayout(event));
758
+ if (result) {
759
+ const render = this.applyMouseDispatchResult(event, result);
760
+ if (type === "press") {
761
+ this.clearTextSelection();
762
+ this.mousePressTarget = result.target;
763
+ this.mousePressPoint = { x: raw.x, y: raw.y };
764
+ this.mousePressMoved = false;
765
+ }
766
+ if (render)
767
+ this.requestRender();
768
+ return;
769
+ }
770
+ if (this.handleRightClickPaste(raw))
771
+ return;
772
+ this.handleSelectionMouseEvent(raw);
773
+ }
774
+ parseWheelEvent(data) {
775
+ const sgr = /^\x1b\[<(\d+);(\d+);(\d+)[Mm]$/.exec(data);
776
+ if (sgr) {
777
+ const button = Number.parseInt(sgr[1], 10);
778
+ if ((button & 64) === 0)
779
+ return undefined;
780
+ const direction = button & 3;
781
+ if (direction !== 0 && direction !== 1)
782
+ return undefined;
783
+ return {
784
+ direction: direction === 0 ? -1 : 1,
785
+ x: Number.parseInt(sgr[2], 10) - 1,
786
+ y: Number.parseInt(sgr[3], 10) - 1,
787
+ button,
788
+ };
789
+ }
790
+ if (data.length === 6 && data.startsWith("\x1b[M")) {
791
+ const button = data.charCodeAt(3) - 32;
792
+ if ((button & 64) === 0)
793
+ return undefined;
794
+ const direction = button & 3;
795
+ if (direction !== 0 && direction !== 1)
796
+ return undefined;
797
+ return {
798
+ direction: direction === 0 ? -1 : 1,
799
+ x: data.charCodeAt(4) - 33,
800
+ y: data.charCodeAt(5) - 33,
801
+ button,
802
+ };
803
+ }
804
+ return undefined;
805
+ }
806
+ getWheelScrollLines(button) {
807
+ // SGR mouse button codes use bit 3 (value 8) for the Alt modifier.
808
+ return (button & 8) !== 0 ? this.wheelScrollLines * ALT_WHEEL_SCROLL_MULTIPLIER : this.wheelScrollLines;
809
+ }
810
+ routeWheel(event) {
811
+ let remaining = event.direction * this.getWheelScrollLines(event.button);
812
+ const seen = new Set();
813
+ for (const scrollView of this.currentLayout ? getScrollViewsAt(this.currentLayout, event.x, event.y) : []) {
814
+ seen.add(scrollView);
815
+ remaining = scrollView.scrollBy(remaining);
816
+ if (remaining === 0 || scrollView.overscroll === "contain")
817
+ break;
818
+ }
819
+ const primary = this.getPrimaryScrollView();
820
+ if (remaining !== 0 && !seen.has(primary))
821
+ primary.scrollBy(remaining);
822
+ this.updateScrollbarHover(event.x, event.y);
823
+ this.requestRender();
824
+ }
825
+ parseSgrMouseEvent(data) {
826
+ const match = /^\x1b\[<(\d+);(\d+);(\d+)([Mm])$/.exec(data);
827
+ if (!match)
828
+ return undefined;
829
+ return {
830
+ button: Number.parseInt(match[1], 10),
831
+ x: Number.parseInt(match[2], 10) - 1,
832
+ y: Number.parseInt(match[3], 10) - 1,
833
+ release: match[4] === "m",
834
+ };
835
+ }
836
+ handleRightClickPaste(event) {
837
+ if (!this.onRightClickPaste ||
838
+ process.platform !== "win32" ||
839
+ process.env.TERM_PROGRAM?.toLowerCase() === "vscode" ||
840
+ event.release ||
841
+ event.button !== 2) {
842
+ return false;
843
+ }
844
+ try {
845
+ this.onRightClickPaste();
846
+ }
847
+ catch {
848
+ // Clipboard paste is best-effort.
849
+ }
850
+ return true;
851
+ }
852
+ handleScrollToEndIndicatorMouseEvent(event) {
853
+ const rect = this.scrollToEndIndicatorRect;
854
+ if (!rect || event.release || (event.button & 32) !== 0 || (event.button & 3) !== 0)
855
+ return false;
856
+ if (event.y !== rect.row || event.x < rect.column || event.x >= rect.column + rect.width)
857
+ return false;
858
+ this.scrollToBottom();
859
+ return true;
860
+ }
861
+ getScrollbarTargetAt(x, y, includeHiddenAuto = false) {
862
+ if (this.hasOverlay() || !this.currentLayout)
863
+ return undefined;
864
+ for (const scrollView of getScrollViewsAt(this.currentLayout, x, y)) {
865
+ const box = getScrollViewBox(this.currentLayout, scrollView);
866
+ const geometry = box ? getScrollbarGeometry(box, includeHiddenAuto) : undefined;
867
+ if (geometry &&
868
+ x === geometry.column &&
869
+ y >= geometry.trackTop &&
870
+ y < geometry.trackTop + geometry.trackHeight) {
871
+ return { scrollView, geometry };
872
+ }
873
+ }
874
+ return undefined;
875
+ }
876
+ setScrollbarHover(scrollView) {
877
+ if (scrollView === this.scrollbarHover)
878
+ return;
879
+ this.scrollbarHover?.setScrollbarActive(false);
880
+ this.scrollbarHover = scrollView;
881
+ this.scrollbarHover?.setScrollbarActive(true);
882
+ }
883
+ updateScrollbarHover(x, y) {
884
+ this.setScrollbarHover(this.getScrollbarTargetAt(x, y, true)?.scrollView);
885
+ }
886
+ stopScrollbarHover() {
887
+ this.setScrollbarHover(undefined);
888
+ }
889
+ scrollScrollbarToPointer(scrollView, geometry, pointerY, grabOffset) {
890
+ const maxThumbOffset = geometry.trackHeight - geometry.thumbHeight;
891
+ const thumbOffset = Math.max(0, Math.min(maxThumbOffset, pointerY - geometry.trackTop - grabOffset));
892
+ const scrollTop = maxThumbOffset === 0 ? 0 : Math.round((thumbOffset / maxThumbOffset) * geometry.maxScrollTop);
893
+ scrollView.scrollTo(scrollTop);
894
+ }
895
+ handleScrollbarMouseEvent(event) {
896
+ if (this.scrollbarDrag) {
897
+ if (event.release) {
898
+ this.stopScrollbarDrag();
899
+ return true;
900
+ }
901
+ const box = this.currentLayout
902
+ ? getScrollViewBox(this.currentLayout, this.scrollbarDrag.scrollView)
903
+ : undefined;
904
+ const geometry = box ? getScrollbarGeometry(box) : undefined;
905
+ if (geometry) {
906
+ this.scrollScrollbarToPointer(this.scrollbarDrag.scrollView, geometry, event.y, this.scrollbarDrag.grabOffset);
907
+ }
908
+ return true;
909
+ }
910
+ if (event.release || (event.button & 32) !== 0 || (event.button & 3) !== 0)
911
+ return false;
912
+ const target = this.getScrollbarTargetAt(event.x, event.y);
913
+ if (!target)
914
+ return false;
915
+ this.stopSelectionAutoScroll();
916
+ this.selectionPressActive = false;
917
+ this.selectionAnchor = undefined;
918
+ this.selectionFocus = undefined;
919
+ this.selectionGranularity = "character";
920
+ this.selectionInitialRange = undefined;
921
+ this.lastClick = undefined;
922
+ this.pressedUrl = undefined;
923
+ this.selectionDragged = false;
924
+ this.setScrollbarHover(target.scrollView);
925
+ const onThumb = event.y >= target.geometry.thumbTop && event.y < target.geometry.thumbTop + target.geometry.thumbHeight;
926
+ const grabOffset = onThumb ? event.y - target.geometry.thumbTop : Math.floor(target.geometry.thumbHeight / 2);
927
+ if (!onThumb)
928
+ this.scrollScrollbarToPointer(target.scrollView, target.geometry, event.y, grabOffset);
929
+ this.scrollbarDrag = {
930
+ scrollView: target.scrollView,
931
+ grabOffset,
932
+ };
933
+ return true;
934
+ }
935
+ stopScrollbarDrag() {
936
+ this.scrollbarDrag = undefined;
937
+ }
938
+ getScrollSelectionPoint(scrollView, x, y) {
939
+ if (!this.currentLayout)
940
+ return undefined;
941
+ const box = getScrollViewBox(this.currentLayout, scrollView);
942
+ if (!box || box.rect.height <= 0 || box.clip.height <= 0)
943
+ return undefined;
944
+ const visibleTop = Math.max(0, box.rect.y, box.clip.y);
945
+ const visibleBottom = Math.min(this.terminal.rows - 1, box.rect.y + box.rect.height - 1, box.clip.y + box.clip.height - 1);
946
+ if (visibleBottom < visibleTop)
947
+ return undefined;
948
+ const pointerRow = Math.max(visibleTop, Math.min(visibleBottom, y));
949
+ const maxContentRow = Math.max(0, (box.scrollContentLines?.length ?? 1) - 1);
950
+ return {
951
+ row: Math.max(0, Math.min(maxContentRow, scrollView.scrollTop + pointerRow - box.rect.y)),
952
+ col: Math.max(0, Math.min(box.rect.width - 1, x - box.rect.x)),
953
+ scrollView,
954
+ };
955
+ }
956
+ getSelectionPoint(event, scrollView) {
957
+ if (scrollView) {
958
+ const point = this.getScrollSelectionPoint(scrollView, event.x, event.y);
959
+ if (point)
960
+ return point;
961
+ }
962
+ return {
963
+ row: Math.max(0, Math.min(this.terminal.rows - 1, event.y)),
964
+ col: Math.max(0, Math.min(this.terminal.columns - 1, event.x)),
965
+ };
966
+ }
967
+ getSelectionSourceLine(point) {
968
+ if (point.scrollView && this.currentLayout) {
969
+ const lines = getScrollViewBox(this.currentLayout, point.scrollView)?.scrollContentLines;
970
+ if (lines)
971
+ return lines[point.row] ?? "";
972
+ }
973
+ return this.previousScreen[point.row] ?? "";
974
+ }
975
+ getWordSelection(point) {
976
+ const line = stripTerminalSequences(this.getSelectionSourceLine(point));
977
+ const segments = [];
978
+ let start = 0;
979
+ for (const segment of wordSegmenter.segment(line)) {
980
+ const end = start + visibleWidth(segment.segment);
981
+ const joiner = TERMINAL_WORD_SELECTION_JOINERS.has(segment.segment);
982
+ segments.push({ start, end, selectable: segment.isWordLike === true || joiner, joiner });
983
+ start = end;
984
+ }
985
+ const clickedSegmentIndex = segments.findIndex((segment) => point.col >= segment.start && point.col < segment.end);
986
+ if (clickedSegmentIndex < 0)
987
+ return undefined;
988
+ const canJoin = (left, right) => left.selectable && right.selectable && (left.joiner || right.joiner);
989
+ let selectionStart = segments[clickedSegmentIndex].start;
990
+ let selectionEnd = segments[clickedSegmentIndex].end;
991
+ for (let index = clickedSegmentIndex; index > 0 && canJoin(segments[index - 1], segments[index]); index--) {
992
+ selectionStart = segments[index - 1].start;
993
+ }
994
+ for (let index = clickedSegmentIndex; index < segments.length - 1 && canJoin(segments[index], segments[index + 1]); index++) {
995
+ selectionEnd = segments[index + 1].end;
996
+ }
997
+ return {
998
+ start: { ...point, col: selectionStart },
999
+ end: { ...point, col: selectionEnd, boundary: true },
1000
+ };
1001
+ }
1002
+ getLineSelection(point) {
1003
+ return {
1004
+ start: { ...point, col: 0 },
1005
+ end: { ...point, col: visibleWidth(this.getSelectionSourceLine(point)), boundary: true },
1006
+ };
1007
+ }
1008
+ updateSelectionFocus(point) {
1009
+ if (this.selectionGranularity === "character" || !this.selectionInitialRange) {
1010
+ this.selectionFocus = point;
1011
+ return;
1012
+ }
1013
+ const range = this.selectionGranularity === "word" ? this.getWordSelection(point) : this.getLineSelection(point);
1014
+ if (!range)
1015
+ return;
1016
+ const initial = this.selectionInitialRange;
1017
+ const targetBeforeInitial = range.start.row < initial.start.row ||
1018
+ (range.start.row === initial.start.row && range.start.col < initial.start.col);
1019
+ if (targetBeforeInitial) {
1020
+ this.selectionAnchor = initial.end;
1021
+ this.selectionFocus = range.start;
1022
+ }
1023
+ else {
1024
+ this.selectionAnchor = initial.start;
1025
+ this.selectionFocus = range.end;
1026
+ }
1027
+ }
1028
+ getClickCount(point, word) {
1029
+ const now = Date.now();
1030
+ const previous = this.lastClick;
1031
+ const count = word &&
1032
+ previous &&
1033
+ now - previous.timestamp <= DOUBLE_CLICK_INTERVAL_MS &&
1034
+ previous.row === point.row &&
1035
+ previous.scrollView === point.scrollView &&
1036
+ previous.wordStart === word.start.col &&
1037
+ previous.wordEnd === word.end.col
1038
+ ? (previous.count % 3) + 1
1039
+ : 1;
1040
+ this.lastClick = word
1041
+ ? {
1042
+ timestamp: now,
1043
+ count,
1044
+ row: point.row,
1045
+ scrollView: point.scrollView,
1046
+ wordStart: word.start.col,
1047
+ wordEnd: word.end.col,
1048
+ }
1049
+ : undefined;
1050
+ return count;
1051
+ }
1052
+ updateSelectionAutoScroll(event) {
1053
+ const scrollView = this.selectionAnchor?.scrollView;
1054
+ if (!scrollView || !this.currentLayout) {
1055
+ this.stopSelectionAutoScroll();
1056
+ return;
1057
+ }
1058
+ const box = getScrollViewBox(this.currentLayout, scrollView);
1059
+ if (!box || box.rect.height <= 0 || box.clip.height <= 0) {
1060
+ this.stopSelectionAutoScroll();
1061
+ return;
1062
+ }
1063
+ const visibleTop = Math.max(0, box.rect.y, box.clip.y);
1064
+ const visibleBottom = Math.min(this.terminal.rows - 1, box.rect.y + box.rect.height - 1, box.clip.y + box.clip.height - 1);
1065
+ this.selectionDragPointer = { x: event.x, y: event.y };
1066
+ this.selectionAutoScrollDirection = event.y <= visibleTop ? -1 : event.y >= visibleBottom ? 1 : 0;
1067
+ if (this.selectionAutoScrollDirection === 0) {
1068
+ this.stopSelectionAutoScroll();
1069
+ return;
1070
+ }
1071
+ if (this.selectionAutoScrollTimer)
1072
+ return;
1073
+ this.selectionAutoScrollTimer = setInterval(() => this.autoScrollSelection(), 50);
1074
+ this.selectionAutoScrollTimer.unref();
1075
+ }
1076
+ autoScrollSelection() {
1077
+ const scrollView = this.selectionAnchor?.scrollView;
1078
+ const pointer = this.selectionDragPointer;
1079
+ const direction = this.selectionAutoScrollDirection;
1080
+ if (!scrollView || !pointer || direction === 0) {
1081
+ this.stopSelectionAutoScroll();
1082
+ return;
1083
+ }
1084
+ const remaining = scrollView.scrollBy(direction);
1085
+ if (remaining === direction) {
1086
+ this.stopSelectionAutoScroll();
1087
+ return;
1088
+ }
1089
+ const point = this.getScrollSelectionPoint(scrollView, pointer.x, pointer.y);
1090
+ if (point)
1091
+ this.updateSelectionFocus(point);
1092
+ this.requestRender();
1093
+ }
1094
+ stopSelectionAutoScroll() {
1095
+ if (this.selectionAutoScrollTimer) {
1096
+ clearInterval(this.selectionAutoScrollTimer);
1097
+ this.selectionAutoScrollTimer = undefined;
1098
+ }
1099
+ this.selectionAutoScrollDirection = 0;
1100
+ this.selectionDragPointer = undefined;
1101
+ }
1102
+ handleSelectionMouseEvent(event) {
1103
+ const button = event.button & 3;
1104
+ if (button !== 0 && !(event.release && button === 3))
1105
+ return;
1106
+ const anchorScrollView = this.selectionAnchor?.scrollView;
1107
+ const point = this.getSelectionPoint(event, anchorScrollView);
1108
+ if (event.release) {
1109
+ if (!this.selectionPressActive)
1110
+ return;
1111
+ this.selectionPressActive = false;
1112
+ this.stopSelectionAutoScroll();
1113
+ if (!this.selectionAnchor)
1114
+ return;
1115
+ this.updateSelectionFocus(point);
1116
+ const isClick = !this.selectionDragged &&
1117
+ this.selectionAnchor.scrollView === point.scrollView &&
1118
+ this.selectionAnchor.row === point.row &&
1119
+ this.selectionAnchor.col === point.col;
1120
+ const clickedUrl = isClick ? this.pressedUrl : undefined;
1121
+ this.pressedUrl = undefined;
1122
+ if (clickedUrl && this.openUrl) {
1123
+ this.selectionAnchor = undefined;
1124
+ this.selectionFocus = undefined;
1125
+ try {
1126
+ this.openUrl(clickedUrl);
1127
+ }
1128
+ catch {
1129
+ // URL activation is best-effort.
1130
+ }
1131
+ this.requestRender();
1132
+ return;
1133
+ }
1134
+ if (isClick) {
1135
+ const clickEvent = this.createMouseEvent("click", event.button, event.x, event.y, {
1136
+ clickCount: this.lastClick?.count ?? 1,
1137
+ });
1138
+ const overlay = this.dispatchMouseToOverlay(clickEvent);
1139
+ const result = overlay.result ?? (overlay.hit ? undefined : this.dispatchMouseToLayout(clickEvent));
1140
+ if (result) {
1141
+ const render = this.applyMouseDispatchResult(clickEvent, result);
1142
+ this.clearTextSelection();
1143
+ if (render)
1144
+ this.requestRender();
1145
+ return;
1146
+ }
1147
+ }
1148
+ if (this.copyOnSelect)
1149
+ void this.copySelectionToClipboard();
1150
+ this.requestRender();
1151
+ return;
1152
+ }
1153
+ if ((event.button & 32) !== 0) {
1154
+ if (!this.selectionPressActive || !this.selectionAnchor)
1155
+ return;
1156
+ this.selectionDragged = true;
1157
+ this.lastClick = undefined;
1158
+ this.pressedUrl = undefined;
1159
+ this.updateSelectionFocus(point);
1160
+ this.updateSelectionAutoScroll(event);
1161
+ this.requestRender();
1162
+ return;
1163
+ }
1164
+ this.stopSelectionAutoScroll();
1165
+ this.selectionPressActive = true;
1166
+ const scrollView = !this.hasOverlay() && this.currentLayout
1167
+ ? getScrollViewsAt(this.currentLayout, event.x, event.y)[0]
1168
+ : undefined;
1169
+ const anchor = this.getSelectionPoint(event, scrollView);
1170
+ const word = this.getWordSelection(anchor);
1171
+ const clickCount = this.getClickCount(anchor, word);
1172
+ const range = clickCount === 2 ? word : clickCount === 3 ? this.getLineSelection(anchor) : undefined;
1173
+ this.selectionGranularity = range ? (clickCount === 2 ? "word" : "line") : "character";
1174
+ this.selectionInitialRange = range;
1175
+ this.selectionAnchor = range?.start ?? anchor;
1176
+ this.selectionFocus = range?.end ?? anchor;
1177
+ this.selectionDragged = false;
1178
+ this.pressedUrl = range
1179
+ ? undefined
1180
+ : getOsc8LinkAtColumn(this.previousScreen[Math.max(0, Math.min(this.terminal.rows - 1, event.y))] ?? "", Math.max(0, Math.min(this.terminal.columns - 1, event.x)));
1181
+ this.requestRender();
1182
+ }
1183
+ getSelectionBounds() {
1184
+ if (!this.selectionAnchor || !this.selectionFocus)
1185
+ return undefined;
1186
+ if (this.selectionAnchor.scrollView !== this.selectionFocus.scrollView)
1187
+ return undefined;
1188
+ const anchorBeforeFocus = this.selectionAnchor.row < this.selectionFocus.row ||
1189
+ (this.selectionAnchor.row === this.selectionFocus.row && this.selectionAnchor.col < this.selectionFocus.col);
1190
+ if (this.selectionAnchor.row === this.selectionFocus.row &&
1191
+ this.selectionAnchor.col === this.selectionFocus.col) {
1192
+ return undefined;
1193
+ }
1194
+ return anchorBeforeFocus
1195
+ ? { start: this.selectionAnchor, end: this.selectionFocus }
1196
+ : { start: this.selectionFocus, end: this.selectionAnchor };
1197
+ }
1198
+ getSelectionColumns(line, row, selection, minColumn = 0, maxColumn = visibleWidth(line)) {
1199
+ const lineWidth = visibleWidth(line);
1200
+ let start = Math.max(0, minColumn);
1201
+ let end = Math.min(lineWidth, maxColumn);
1202
+ if (row === selection.start.row) {
1203
+ start = getGraphemeCellRange(line, selection.start.col)?.start ?? Math.min(selection.start.col, lineWidth);
1204
+ }
1205
+ if (row === selection.end.row) {
1206
+ end = selection.end.boundary
1207
+ ? Math.min(selection.end.col, lineWidth)
1208
+ : (getGraphemeCellRange(line, selection.end.col)?.end ?? Math.min(selection.end.col + 1, lineWidth));
1209
+ }
1210
+ return { start: Math.max(minColumn, start), end: Math.min(maxColumn, end) };
1211
+ }
1212
+ getActiveSelectionText() {
1213
+ const selection = this.getSelectionBounds();
1214
+ if (!selection)
1215
+ return undefined;
1216
+ let sourceLines = this.previousScreen;
1217
+ if (selection.start.scrollView) {
1218
+ if (!this.currentLayout)
1219
+ return undefined;
1220
+ const box = getScrollViewBox(this.currentLayout, selection.start.scrollView);
1221
+ if (!box?.scrollContentLines)
1222
+ return undefined;
1223
+ sourceLines = box.scrollContentLines;
1224
+ }
1225
+ const lines = [];
1226
+ for (let row = selection.start.row; row <= selection.end.row; row++) {
1227
+ const line = sourceLines[row] ?? "";
1228
+ const columns = this.getSelectionColumns(line, row, selection);
1229
+ lines.push(stripTerminalSequences(sliceByColumn(line, columns.start, Math.max(0, columns.end - columns.start), true)).trimEnd());
1230
+ }
1231
+ const text = lines.join("\n");
1232
+ return text.length === 0 ? undefined : text;
1233
+ }
1234
+ async copySelectionToClipboard() {
1235
+ const text = this.getActiveSelectionText();
1236
+ if (!text)
1237
+ return false;
1238
+ return this.copyTextToClipboard(text);
1239
+ }
1240
+ async copyTextToClipboard(text) {
1241
+ // Prefer an injected clipboard implementation (native clipboard + platform tools with a
1242
+ // verified success path) when the host app provides one. A bare OSC 52 write can show
1243
+ // "Copied!" while leaving the system clipboard untouched (e.g. macOS Terminal.app, tmux
1244
+ // without OSC 52 clipboard passthrough), so only report success when it actually copies.
1245
+ if (this.copySelection) {
1246
+ const ok = await this.copySelection(text);
1247
+ this.flash(ok ? "Copied!" : "Copy failed");
1248
+ return ok;
1249
+ }
1250
+ this.terminal.write(`\x1b]52;c;${Buffer.from(text).toString("base64")}\x07`);
1251
+ this.flash("Copied!");
1252
+ return true;
1253
+ }
1254
+ applySearchTextHighlight(text, current) {
1255
+ const style = current ? this.searchCurrentMatchStyle : this.searchMatchStyle;
1256
+ let result = "";
1257
+ let plainStart = 0;
1258
+ let index = 0;
1259
+ while (index < text.length) {
1260
+ const ansi = extractAnsiCode(text, index);
1261
+ if (!ansi) {
1262
+ index += 1;
1263
+ continue;
1264
+ }
1265
+ if (index > plainStart)
1266
+ result += style(text.slice(plainStart, index));
1267
+ result += ansi.code;
1268
+ index += ansi.length;
1269
+ plainStart = index;
1270
+ }
1271
+ if (plainStart < text.length)
1272
+ result += style(text.slice(plainStart));
1273
+ return result;
1274
+ }
1275
+ applySearchHighlights(screen, layout) {
1276
+ const search = this.activeSearch;
1277
+ if (!search || search.selectedIndex < 0 || search.matches.length === 0)
1278
+ return screen;
1279
+ const scrollView = layout.primaryScrollView ?? this.implicitScrollView;
1280
+ const box = getScrollViewBox(layout, scrollView);
1281
+ if (!box)
1282
+ return screen;
1283
+ const rangesByRow = new Map();
1284
+ const scrollbarColumn = getScrollbarGeometry(box)?.column;
1285
+ const minRow = Math.max(0, box.rect.y, box.clip.y);
1286
+ const maxRow = Math.min(screen.length, box.rect.y + box.rect.height, box.clip.y + box.clip.height);
1287
+ const minColumn = Math.max(0, box.rect.x, box.clip.x);
1288
+ const maxColumn = Math.min(this.terminal.columns, box.rect.x + box.rect.width, box.clip.x + box.clip.width, scrollbarColumn ?? Number.POSITIVE_INFINITY);
1289
+ const minContentRow = scrollView.scrollTop + minRow - box.rect.y;
1290
+ const maxContentRow = scrollView.scrollTop + maxRow - box.rect.y - 1;
1291
+ let low = 0;
1292
+ let high = search.matches.length;
1293
+ while (low < high) {
1294
+ const middle = low + Math.floor((high - low) / 2);
1295
+ const match = search.matches[middle];
1296
+ const lastRow = match.segments[match.segments.length - 1]?.row ?? -1;
1297
+ if (lastRow < minContentRow)
1298
+ low = middle + 1;
1299
+ else
1300
+ high = middle;
1301
+ }
1302
+ for (let matchIndex = low; matchIndex < search.matches.length; matchIndex++) {
1303
+ const match = search.matches[matchIndex];
1304
+ if ((match.segments[0]?.row ?? 0) > maxContentRow)
1305
+ break;
1306
+ for (const segment of match.segments) {
1307
+ const row = box.rect.y + segment.row - scrollView.scrollTop;
1308
+ if (row < minRow || row >= maxRow)
1309
+ continue;
1310
+ const startCol = Math.max(minColumn, box.rect.x + segment.startCol);
1311
+ const endCol = Math.min(maxColumn, box.rect.x + segment.endCol);
1312
+ if (endCol <= startCol)
1313
+ continue;
1314
+ const ranges = rangesByRow.get(row) ?? [];
1315
+ ranges.push({ startCol, endCol, current: matchIndex === search.selectedIndex });
1316
+ rangesByRow.set(row, ranges);
1317
+ }
1318
+ }
1319
+ const result = [...screen];
1320
+ for (const [row, ranges] of rangesByRow) {
1321
+ let line = result[row] ?? "";
1322
+ if (isImageLine(line))
1323
+ continue;
1324
+ const lineWidth = visibleWidth(line);
1325
+ for (const range of ranges.sort((a, b) => b.startCol - a.startCol)) {
1326
+ const startCol = Math.min(range.startCol, lineWidth);
1327
+ const endCol = Math.min(range.endCol, lineWidth);
1328
+ if (endCol <= startCol)
1329
+ continue;
1330
+ const before = sliceByColumn(line, 0, startCol, true);
1331
+ const highlighted = sliceByColumn(line, startCol, endCol - startCol, true);
1332
+ const after = sliceByColumn(line, endCol, Math.max(0, lineWidth - endCol), true);
1333
+ line = `${before}${this.applySearchTextHighlight(highlighted, range.current)}${after}`;
1334
+ }
1335
+ result[row] = line;
1336
+ }
1337
+ return result;
1338
+ }
1339
+ applySelectionHighlight(text) {
1340
+ let result = "\x1b[7m";
1341
+ let index = 0;
1342
+ while (index < text.length) {
1343
+ const ansi = extractAnsiCode(text, index);
1344
+ if (!ansi) {
1345
+ result += text[index];
1346
+ index += 1;
1347
+ continue;
1348
+ }
1349
+ result += ansi.code;
1350
+ if (ansi.code.endsWith("m"))
1351
+ result += "\x1b[7m";
1352
+ index += ansi.length;
1353
+ }
1354
+ return `${result}\x1b[27m`;
1355
+ }
1356
+ applySelection(screen, layout = this.currentLayout) {
1357
+ const selection = this.getSelectionBounds();
1358
+ if (!selection)
1359
+ return screen;
1360
+ let screenSelection = selection;
1361
+ let minRow = 0;
1362
+ let maxRow = screen.length - 1;
1363
+ let minColumn = 0;
1364
+ let maxColumn = this.terminal.columns;
1365
+ if (selection.start.scrollView) {
1366
+ if (!layout)
1367
+ return screen;
1368
+ const box = getScrollViewBox(layout, selection.start.scrollView);
1369
+ if (!box)
1370
+ return screen;
1371
+ minRow = Math.max(0, box.rect.y, box.clip.y);
1372
+ maxRow = Math.min(screen.length - 1, box.rect.y + box.rect.height - 1, box.clip.y + box.clip.height - 1);
1373
+ minColumn = Math.max(0, box.rect.x, box.clip.x);
1374
+ maxColumn = Math.min(this.terminal.columns, box.rect.x + box.rect.width, box.clip.x + box.clip.width);
1375
+ screenSelection = {
1376
+ start: {
1377
+ ...selection.start,
1378
+ row: box.rect.y + selection.start.row - selection.start.scrollView.scrollTop,
1379
+ col: box.rect.x + selection.start.col,
1380
+ },
1381
+ end: {
1382
+ ...selection.end,
1383
+ row: box.rect.y + selection.end.row - selection.start.scrollView.scrollTop,
1384
+ col: box.rect.x + selection.end.col,
1385
+ },
1386
+ };
1387
+ }
1388
+ return screen.map((line, row) => {
1389
+ if (row < minRow ||
1390
+ row > maxRow ||
1391
+ row < screenSelection.start.row ||
1392
+ row > screenSelection.end.row ||
1393
+ isImageLine(line)) {
1394
+ return line;
1395
+ }
1396
+ const lineWidth = visibleWidth(line);
1397
+ const columns = this.getSelectionColumns(line, row, screenSelection, minColumn, maxColumn);
1398
+ if (columns.end <= columns.start)
1399
+ return line;
1400
+ const before = sliceByColumn(line, 0, columns.start, true);
1401
+ const selected = sliceByColumn(line, columns.start, columns.end - columns.start, true);
1402
+ const after = sliceByColumn(line, columns.end, Math.max(0, lineWidth - columns.end), true);
1403
+ return `${before}${this.applySelectionHighlight(selected)}${after}`;
1404
+ });
1405
+ }
1406
+ isMouseSequence(data) {
1407
+ return /^\x1b\[<\d+;\d+;\d+[Mm]$/.test(data) || (data.length === 6 && data.startsWith("\x1b[M"));
1408
+ }
1409
+ compositeScrollToEndIndicator(screen, layout, width) {
1410
+ this.scrollToEndIndicatorRect = undefined;
1411
+ const scrollView = layout.primaryScrollView ?? this.implicitScrollView;
1412
+ if (!this.scrollToEndIndicator || !scrollView.followEnd || scrollView.isFollowingEnd)
1413
+ return screen;
1414
+ const box = getScrollViewBox(layout, scrollView);
1415
+ const clip = box?.clip;
1416
+ if (!clip || clip.width <= 0 || clip.height <= 0)
1417
+ return screen;
1418
+ const row = clip.y + clip.height - 1;
1419
+ if (row >= screen.length || isImageLine(screen[row] ?? ""))
1420
+ return screen;
1421
+ const scrollbarColumn = box ? getScrollbarGeometry(box)?.column : undefined;
1422
+ const availableWidth = Math.max(0, (scrollbarColumn ?? clip.x + clip.width) - clip.x);
1423
+ const text = truncateToWidth(this.scrollToEndIndicator(), availableWidth, "");
1424
+ const textWidth = visibleWidth(text);
1425
+ if (textWidth === 0)
1426
+ return screen;
1427
+ const column = clip.x + Math.floor((availableWidth - textWidth) / 2);
1428
+ const result = [...screen];
1429
+ result[row] = compositeTuiLine(result[row] ?? "", text, column, textWidth, width);
1430
+ this.scrollToEndIndicatorRect = { row, column, width: textWidth };
1431
+ return result;
1432
+ }
1433
+ compositeFlashes(screen, width, height) {
1434
+ const flashLines = this.flashes.render(width).slice(-height);
1435
+ if (flashLines.length === 0)
1436
+ return screen;
1437
+ const result = [...screen];
1438
+ while (result.length < height)
1439
+ result.push("");
1440
+ for (let row = 0; row < flashLines.length; row++) {
1441
+ const line = flashLines[row];
1442
+ const flashWidth = visibleWidth(line);
1443
+ if (flashWidth === 0)
1444
+ continue;
1445
+ result[row] = compositeTuiLine(result[row] ?? "", line, width - flashWidth, flashWidth, width);
1446
+ }
1447
+ return result;
1448
+ }
1449
+ doRender() {
1450
+ if (this.stopped || !this.altScreenActive)
1451
+ return;
1452
+ const width = Math.max(1, this.terminal.columns);
1453
+ const height = Math.max(1, this.terminal.rows);
1454
+ const root = this.layoutRoot ?? this.implicitScrollView;
1455
+ let nextLayout = renderLayoutFrame(root, width, height, () => this.requestRender());
1456
+ if (this.refreshSearch(nextLayout)) {
1457
+ nextLayout = renderLayoutFrame(root, width, height, () => this.requestRender());
1458
+ }
1459
+ let screen = nextLayout.lines.map((line) => line.replace(OSC133_ZONE_PREFIX, ""));
1460
+ screen = this.applySearchHighlights(screen, nextLayout);
1461
+ screen = this.compositeScrollToEndIndicator(screen, nextLayout, width);
1462
+ screen = this.compositeOverlays(screen, width, height);
1463
+ if (screen.length > height)
1464
+ screen = screen.slice(screen.length - height);
1465
+ screen = this.applySelection(screen, nextLayout);
1466
+ screen = this.compositeFlashes(screen, width, height);
1467
+ const cursorPos = this.extractCursorPosition(screen, height);
1468
+ screen = this.applyLineResets(screen).map((line) => {
1469
+ if (isImageLine(line) || visibleWidth(line) <= width)
1470
+ return line;
1471
+ return sliceByColumn(line, 0, width, true);
1472
+ });
1473
+ const fullRedraw = this.previousScreen.length === 0 || this.previousScreenWidth !== width || this.previousScreenHeight !== height;
1474
+ const imagesNeedRedraw = screen.some((line, row) => line !== this.previousScreen[row] && (isImageLine(line) || isImageLine(this.previousScreen[row] ?? "")));
1475
+ const redrawImages = fullRedraw || imagesNeedRedraw;
1476
+ const hadUploadedKittyImages = this.uploadedKittyImages.size > 0;
1477
+ const preparedKittyScreen = redrawImages && this.imageProtocol === "kitty"
1478
+ ? this.prepareKittyScreen(screen)
1479
+ : { lines: screen, evictedImageDeletion: "" };
1480
+ let buffer = BEGIN_SYNCHRONIZED_OUTPUT;
1481
+ if (fullRedraw) {
1482
+ this.fullRedrawCount += 1;
1483
+ const clearImages = this.imageProtocol === "kitty" && hadUploadedKittyImages
1484
+ ? deleteAllKittyPlacements()
1485
+ : this.deleteKittyImages();
1486
+ buffer += `${clearImages}\x1b[2J`;
1487
+ }
1488
+ else if (imagesNeedRedraw) {
1489
+ if (this.imageProtocol === "iterm2")
1490
+ buffer += "\x1b[2J";
1491
+ else if (this.imageProtocol === "kitty")
1492
+ buffer += deleteAllKittyPlacements();
1493
+ }
1494
+ buffer += preparedKittyScreen.evictedImageDeletion;
1495
+ for (let row = 0; row < height; row++) {
1496
+ if (!fullRedraw && !imagesNeedRedraw && screen[row] === this.previousScreen[row])
1497
+ continue;
1498
+ buffer += `\x1b[${row + 1};1H\x1b[2K${preparedKittyScreen.lines[row] ?? ""}`;
1499
+ }
1500
+ if (cursorPos) {
1501
+ buffer += `\x1b[${cursorPos.row + 1};${Math.min(width, cursorPos.col) + 1}H`;
1502
+ buffer += this.getShowHardwareCursor() ? "\x1b[?25h" : "\x1b[?25l";
1503
+ }
1504
+ else {
1505
+ buffer += "\x1b[?25l";
1506
+ }
1507
+ buffer += END_SYNCHRONIZED_OUTPUT;
1508
+ this.terminal.write(buffer);
1509
+ this.previousScreen = screen;
1510
+ this.previousScreenWidth = width;
1511
+ this.previousScreenHeight = height;
1512
+ this.currentLayout = nextLayout;
1513
+ }
1514
+ }
1515
+ //# sourceMappingURL=tui-alt-screen.js.map