-
-
Notifications
You must be signed in to change notification settings - Fork 195
Expand file tree
/
Copy pathTerminalInstance.js
More file actions
453 lines (404 loc) · 15.9 KB
/
Copy pathTerminalInstance.js
File metadata and controls
453 lines (404 loc) · 15.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
/*
* GNU AGPL-3.0 License
*
* Copyright (c) 2021 - present core.ai . All rights reserved.
*
* This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License
* for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see https://opensource.org/licenses/AGPL-3.0.
*
*/
/**
* TerminalInstance - manages a single xterm.js terminal instance and its
* connection to a PTY process via NodeConnector.
*/
define(function (require, exports, module) {
// xterm.js and addons (loaded as AMD modules from thirdparty)
const xtermModule = require("thirdparty/xterm/xterm");
const FitAddonModule = require("thirdparty/xterm/addon-fit");
const WebLinksAddonModule = require("thirdparty/xterm/addon-web-links");
const SearchAddonModule = require("thirdparty/xterm/addon-search");
const WebglAddonModule = require("thirdparty/xterm/addon-webgl");
const Terminal = xtermModule.Terminal;
const FitAddon = FitAddonModule.FitAddon;
const WebLinksAddon = WebLinksAddonModule.WebLinksAddon;
const SearchAddon = SearchAddonModule.SearchAddon;
const WebglAddon = WebglAddonModule.WebglAddon;
let _nextId = 0;
/**
* Read terminal theme colors from CSS variables
* @returns {Object} xterm.js theme object
*/
function _getThemeFromCSS() {
const panelEl = document.querySelector('.terminal-panel-container') || document.documentElement;
const style = getComputedStyle(panelEl);
function v(name) {
return style.getPropertyValue(name).trim() || undefined;
}
return {
background: v("--terminal-background"),
foreground: v("--terminal-foreground"),
cursor: v("--terminal-cursor"),
cursorAccent: v("--terminal-background"),
selectionBackground: v("--terminal-selection"),
selectionForeground: undefined,
black: v("--terminal-ansi-black"),
red: v("--terminal-ansi-red"),
green: v("--terminal-ansi-green"),
yellow: v("--terminal-ansi-yellow"),
blue: v("--terminal-ansi-blue"),
magenta: v("--terminal-ansi-magenta"),
cyan: v("--terminal-ansi-cyan"),
white: v("--terminal-ansi-white"),
brightBlack: v("--terminal-ansi-bright-black"),
brightRed: v("--terminal-ansi-bright-red"),
brightGreen: v("--terminal-ansi-bright-green"),
brightYellow: v("--terminal-ansi-bright-yellow"),
brightBlue: v("--terminal-ansi-bright-blue"),
brightMagenta: v("--terminal-ansi-bright-magenta"),
brightCyan: v("--terminal-ansi-bright-cyan"),
brightWhite: v("--terminal-ansi-bright-white")
};
}
/**
* Create a new TerminalInstance
* @param {Object} nodeConnector - NodeConnector for communication
* @param {Object} shellProfile - Shell profile {name, path, args}
* @param {string} cwd - Working directory
* @constructor
*/
function TerminalInstance(nodeConnector, shellProfile, cwd) {
this.id = "term_" + (++_nextId);
this.nodeConnector = nodeConnector;
this.shellProfile = shellProfile;
this.cwd = cwd;
this.title = shellProfile.name;
this.pid = null;
this.isAlive = false;
this.terminal = null;
this.fitAddon = null;
this.searchAddon = null;
this.$container = null;
this._resizeTimeout = null;
this._disposed = false;
this._webglAddon = null;
this._lastDpr = null;
// Promise that resolves when the shell sends its first output (prompt ready)
this._firstDataResolve = null;
this.firstDataReceived = new Promise(function (resolve) {
this._firstDataResolve = resolve;
}.bind(this));
// Bound event handlers for cleanup
this._onTerminalData = this._onTerminalData.bind(this);
this._onTerminalExit = this._onTerminalExit.bind(this);
}
/**
* Create the xterm.js terminal and attach it to the DOM
* @param {jQuery} $parentContainer - The container to attach the terminal to
*/
TerminalInstance.prototype.create = function ($parentContainer) {
// Create DOM container
this.$container = $('<div class="terminal-instance-container" data-terminal-id="' + this.id + '"></div>');
$parentContainer.append(this.$container);
// Create xterm.js instance
this.terminal = new Terminal({
theme: _getThemeFromCSS(),
fontFamily: "'Menlo', 'DejaVu Sans Mono', 'Consolas', 'Lucida Console', monospace",
fontSize: 13,
lineHeight: 1.2,
cursorBlink: true,
cursorStyle: "block",
scrollback: 10000,
allowProposedApi: true
});
// Load addons
this.fitAddon = new FitAddon();
this.searchAddon = new SearchAddon();
this.terminal.loadAddon(this.fitAddon);
this.terminal.loadAddon(new WebLinksAddon(function (_event, uri) {
Phoenix.app.openURLInDefaultBrowser(uri);
}));
this.terminal.loadAddon(this.searchAddon);
// Open terminal in DOM
this.terminal.open(this.$container[0]);
// Load WebGL renderer for better performance
this._loadWebGLAddon();
// Fit to container
this._fit();
// Set up custom key handler to intercept editor shortcuts
this.terminal.attachCustomKeyEventHandler(this._customKeyHandler.bind(this));
// Wire input: terminal -> PTY
this.terminal.onData((data) => {
if (this.isAlive) {
this.nodeConnector.execPeer("writeTerminal", {id: this.id, data}).catch((err) => {
console.error("Terminal: write error:", err);
});
}
});
// Wire resize: terminal -> PTY
this.terminal.onResize(({cols, rows}) => {
if (this.isAlive) {
this.nodeConnector.execPeer("resizeTerminal", {id: this.id, cols, rows}).catch((err) => {
console.error("Terminal: resize error:", err);
});
}
});
// Listen for title changes from xterm
this.terminal.onTitleChange((newTitle) => {
if (newTitle) {
this.title = newTitle;
if (this.onTitleChanged) {
this.onTitleChanged(this.id, newTitle);
}
}
});
// Listen for NodeConnector events
this.nodeConnector.on("terminalData", this._onTerminalData);
this.nodeConnector.on("terminalExit", this._onTerminalExit);
};
/**
* Spawn the PTY process on the Node side
*/
TerminalInstance.prototype.spawn = async function () {
const dims = this.fitAddon.proposeDimensions();
try {
const result = await this.nodeConnector.execPeer("createTerminal", {
id: this.id,
shell: this.shellProfile.path,
args: this.shellProfile.args || [],
cwd: this.cwd,
cols: dims ? dims.cols : 80,
rows: dims ? dims.rows : 24
});
this.pid = result.pid;
this.isAlive = true;
} catch (err) {
console.error("Terminal: Failed to spawn PTY:", err);
this.terminal.write("\r\n\x1b[31mFailed to start terminal: " + err.message + "\x1b[0m\r\n");
}
};
/**
* Handle data from PTY (NodeConnector event)
*/
TerminalInstance.prototype._onTerminalData = function (_event, eventData) {
if (eventData.id === this.id && this.terminal) {
this.terminal.write(eventData.data);
if (this._firstDataResolve) {
this._firstDataResolve();
this._firstDataResolve = null;
}
}
};
/**
* Handle PTY exit (NodeConnector event)
*/
TerminalInstance.prototype._onTerminalExit = function (_event, eventData) {
if (eventData.id === this.id) {
this.isAlive = false;
if (this.terminal) {
this.terminal.write("\r\n\x1b[90m[Process exited with code " + eventData.exitCode + "]\x1b[0m\r\n");
}
if (this.onProcessExit) {
this.onProcessExit(this.id, eventData.exitCode);
}
}
};
/**
* Custom key event handler - intercept editor shortcuts and clipboard keys
* Returns true to allow xterm to handle, false to prevent
*/
TerminalInstance.prototype._customKeyHandler = function (event) {
// Only intercept keydown events
if (event.type !== "keydown") {
return true;
}
const ctrlOrMeta = event.ctrlKey || event.metaKey;
// Shift+Escape should focus the active editor
if (event.shiftKey && event.key === "Escape") {
return false;
}
// Ctrl+C with a selection should copy to clipboard, not send SIGINT
if (ctrlOrMeta && !event.shiftKey && event.key.toLowerCase() === "c" && this.terminal.hasSelection()) {
return false;
}
return true; // Let xterm handle it
};
/**
* Load (or reload) the WebGL renderer addon, recording the current DPR
* so we can detect changes later and recreate the addon at the correct
* resolution (e.g. after a zoom change).
*/
TerminalInstance.prototype._loadWebGLAddon = function () {
try {
this._webglAddon = new WebglAddon();
this.terminal.loadAddon(this._webglAddon);
this._lastDpr = window.devicePixelRatio;
} catch (e) {
console.warn("Terminal: WebglAddon failed to load, using default renderer:", e);
this._webglAddon = null;
}
};
/**
* Fit the terminal to its container.
*
* Before reflowing, the prompt area is cleared so that stale wrapped
* text does not survive the reflow as a "ghost" line. xterm.js
* defaults to reflowCursorLine: false, meaning the cursor row is
* excluded from reflow. When the terminal widens, a multi-line
* wrapped prompt cannot merge back into one line; the first part
* remains as a visible ghost. By erasing the prompt region first
* (walking up through isWrapped lines), the reflow has nothing
* stale to preserve, and readline's SIGWINCH redraw writes a
* clean prompt at the new width.
*/
TerminalInstance.prototype._fit = function () {
if (!this.fitAddon || !this.$container || !this.$container.is(":visible")) {
return;
}
// When the effective DPR changes (e.g. after a webview zoom change),
// clear the glyph texture atlas so the WebGL renderer rebuilds it at
// the new resolution. The subsequent fit() will resize the canvas.
const currentDpr = window.devicePixelRatio;
if (this._lastDpr !== null && this._lastDpr !== currentDpr) {
this._lastDpr = currentDpr;
this.terminal.clearTextureAtlas();
}
try {
// Only clear the prompt region when dimensions are actually
// changing — i.e. a real reflow will happen. When dimensions
// are unchanged (e.g. tab switch, panel re-focus) clearing
// would erase the prompt without a subsequent SIGWINCH to
// make the shell redraw it.
if (this.terminal && this.isAlive) {
const proposed = this.fitAddon.proposeDimensions();
const dimensionsChanged = proposed &&
(proposed.cols !== this.terminal.cols || proposed.rows !== this.terminal.rows);
if (dimensionsChanged) {
const buf = this.terminal.buffer.active;
let promptStart = buf.cursorY;
// Walk upward through wrapped lines to find prompt start
while (promptStart > 0) {
const line = buf.getLine(buf.baseY + promptStart);
if (!line || !line.isWrapped) {
break;
}
promptStart--;
}
// Erase from prompt start to end of screen, then fit
// once the erase has been applied to the buffer.
this.terminal.write(
"\x1b[" + (promptStart + 1) + ";1H\x1b[J",
() => {
try {
this.fitAddon.fit();
} catch (e) {
// Container might not be visible yet
}
}
);
return;
}
}
this.fitAddon.fit();
} catch (e) {
// Container might not be visible yet
}
};
/**
* Handle container resize — debounced so that only the final size
* triggers a reflow + PTY resize. This avoids garbled prompts from
* intermediate SIGWINCH signals during continuous drag-resizing.
*/
TerminalInstance.prototype.handleResize = function () {
clearTimeout(this._resizeTimeout);
this._resizeTimeout = setTimeout(() => {
this._fit();
}, 300);
};
/**
* Show this terminal (make its container visible)
*/
TerminalInstance.prototype.show = function () {
if (this.$container) {
this.$container.addClass("active");
this._fit();
this.terminal.focus();
}
};
/**
* Hide this terminal
*/
TerminalInstance.prototype.hide = function () {
if (this.$container) {
this.$container.removeClass("active");
}
};
/**
* Focus the terminal
*/
TerminalInstance.prototype.focus = function () {
if (this.terminal) {
this.terminal.focus();
}
};
/**
* Clear the terminal screen
*/
TerminalInstance.prototype.clear = function () {
if (this.terminal) {
this.terminal.clear();
}
};
/**
* Update the terminal theme (e.g., after theme change)
*/
TerminalInstance.prototype.updateTheme = function () {
if (this.terminal) {
this.terminal.options.theme = _getThemeFromCSS();
}
};
/**
* Kill the PTY process and dispose of the terminal
*/
TerminalInstance.prototype.dispose = function () {
if (this._disposed) {
return;
}
this._disposed = true;
// Remove event listeners
this.nodeConnector.off("terminalData", this._onTerminalData);
this.nodeConnector.off("terminalExit", this._onTerminalExit);
// Kill PTY
if (this.isAlive) {
this.nodeConnector.execPeer("killTerminal", {id: this.id}).catch((err) => {
console.error("Terminal: kill error:", err);
});
this.isAlive = false;
}
// Dispose xterm
clearTimeout(this._resizeTimeout);
if (this._webglAddon) {
this._webglAddon.dispose();
this._webglAddon = null;
}
if (this.terminal) {
this.terminal.dispose();
this.terminal = null;
}
// Remove DOM
if (this.$container) {
this.$container.remove();
this.$container = null;
}
};
module.exports = TerminalInstance;
});