-
Notifications
You must be signed in to change notification settings - Fork 964
Expand file tree
/
Copy pathterminal.js
More file actions
1007 lines (877 loc) · 24.8 KB
/
terminal.js
File metadata and controls
1007 lines (877 loc) · 24.8 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
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* Terminal Component using xtermjs
* Provides a pluggable and customizable terminal interface
*/
import { AttachAddon } from "@xterm/addon-attach";
import { FitAddon } from "@xterm/addon-fit";
import { ImageAddon } from "@xterm/addon-image";
import { SearchAddon } from "@xterm/addon-search";
import { Unicode11Addon } from "@xterm/addon-unicode11";
import { WebLinksAddon } from "@xterm/addon-web-links";
import { WebglAddon } from "@xterm/addon-webgl";
import { Terminal as Xterm } from "@xterm/xterm";
import toast from "components/toast";
import confirm from "dialogs/confirm";
import fonts from "lib/fonts";
import keyBindings from "lib/keyBindings";
import appSettings from "lib/settings";
import LigaturesAddon from "./ligatures";
import { getTerminalSettings } from "./terminalDefaults";
import TerminalThemeManager from "./terminalThemeManager";
import TerminalTouchSelection from "./terminalTouchSelection";
export default class TerminalComponent {
constructor(options = {}) {
// Get terminal settings from shared defaults
const terminalSettings = getTerminalSettings();
this.options = {
allowProposedApi: true,
scrollOnUserInput: true,
rows: options.rows || 24,
cols: options.cols || 80,
port: options.port || 8767,
fontSize: terminalSettings.fontSize,
fontFamily: terminalSettings.fontFamily,
fontWeight: terminalSettings.fontWeight,
theme: TerminalThemeManager.getTheme(terminalSettings.theme),
cursorBlink: terminalSettings.cursorBlink,
cursorStyle: terminalSettings.cursorStyle,
cursorInactiveStyle: terminalSettings.cursorInactiveStyle,
scrollback: terminalSettings.scrollback,
tabStopWidth: terminalSettings.tabStopWidth,
convertEol: terminalSettings.convertEol,
letterSpacing: terminalSettings.letterSpacing,
...options,
};
this.terminal = null;
this.fitAddon = null;
this.attachAddon = null;
this.unicode11Addon = null;
this.searchAddon = null;
this.webLinksAddon = null;
this.imageAddon = null;
this.ligaturesAddon = null;
this.container = null;
this.websocket = null;
this.pid = null;
this.isConnected = false;
this.serverMode = options.serverMode !== false; // Default true
this.touchSelection = null;
this.init();
}
init() {
this.terminal = new Xterm(this.options);
// Initialize addons
this.fitAddon = new FitAddon();
this.unicode11Addon = new Unicode11Addon();
this.searchAddon = new SearchAddon();
this.webLinksAddon = new WebLinksAddon(async (event, uri) => {
const linkOpenConfirm = await confirm(
"Terminal",
`Do you want to open ${uri} in browser?`,
);
if (linkOpenConfirm) {
system.openInBrowser(uri);
}
});
this.webglAddon = new WebglAddon();
// Load addons
this.terminal.loadAddon(this.fitAddon);
this.terminal.loadAddon(this.unicode11Addon);
this.terminal.loadAddon(this.searchAddon);
this.terminal.loadAddon(this.webLinksAddon);
// Load conditional addons based on settings
const terminalSettings = getTerminalSettings();
// Load image addon if enabled
if (terminalSettings.imageSupport) {
this.loadImageAddon();
}
// Load font if specified
this.loadTerminalFont();
// Set up terminal event handlers
this.setupEventHandlers();
}
setupEventHandlers() {
// terminal resize handling
this.setupResizeHandling();
// Handle terminal title changes
this.terminal.onTitleChange((title) => {
this.onTitleChange?.(title);
});
// Handle bell
this.terminal.onBell(() => {
this.onBell?.();
});
// Handle copy/paste keybindings
this.setupCopyPasteHandlers();
}
/**
* Setup resize handling for keyboard events and content preservation
*/
setupResizeHandling() {
let resizeTimeout = null;
let lastKnownScrollPosition = 0;
let isResizing = false;
let resizeCount = 0;
const RESIZE_DEBOUNCE = 100;
const MAX_RAPID_RESIZES = 3;
// Store original dimensions for comparison
let originalRows = this.terminal.rows;
let originalCols = this.terminal.cols;
this.terminal.onResize((size) => {
// Track resize events
resizeCount++;
isResizing = true;
// Store current scroll position before resize
if (this.terminal.buffer && this.terminal.buffer.active) {
lastKnownScrollPosition = this.terminal.buffer.active.viewportY;
}
// Clear any existing timeout
if (resizeTimeout) {
clearTimeout(resizeTimeout);
}
// Debounced resize handling
resizeTimeout = setTimeout(async () => {
try {
// Only proceed with server resize if dimensions actually changed significantly
const rowDiff = Math.abs(size.rows - originalRows);
const colDiff = Math.abs(size.cols - originalCols);
// If this is a minor resize (likely intermediate state), skip server update
if (rowDiff < 2 && colDiff < 2 && resizeCount > 1) {
console.log("Skipping minor resize to prevent instability");
isResizing = false;
resizeCount = 0;
return;
}
// Handle server resize
if (this.serverMode) {
await this.resizeTerminal(size.cols, size.rows);
}
// Handle keyboard resize cursor positioning
const heightRatio = size.rows / originalRows;
if (
heightRatio < 0.75 &&
this.terminal.buffer &&
this.terminal.buffer.active
) {
// Keyboard resize detected - ensure cursor is visible
const buffer = this.terminal.buffer.active;
const cursorY = buffer.cursorY;
const cursorViewportPos = buffer.baseY + cursorY;
const viewportTop = buffer.viewportY;
const viewportBottom = viewportTop + this.terminal.rows - 1;
if (
cursorViewportPos <= viewportTop + 1 ||
cursorViewportPos >= viewportBottom - 1
) {
const targetScroll = Math.max(
0,
Math.min(
buffer.length - this.terminal.rows,
cursorViewportPos - Math.floor(this.terminal.rows * 0.25),
),
);
this.terminal.scrollToLine(targetScroll);
}
} else {
// Regular resize - preserve scroll position
this.preserveViewportPosition(lastKnownScrollPosition);
}
// Update stored dimensions
originalRows = size.rows;
originalCols = size.cols;
// Mark resize as complete
isResizing = false;
resizeCount = 0;
// Notify touch selection if it exists
if (this.touchSelection) {
this.touchSelection.onTerminalResize(size);
}
} catch (error) {
console.error("Resize handling failed:", error);
isResizing = false;
resizeCount = 0;
}
}, RESIZE_DEBOUNCE);
});
// Also handle viewport changes for scroll position preservation
this.terminal.onData(() => {
// If we're not resizing and user types, everything is stable
if (!isResizing && this.terminal.buffer && this.terminal.buffer.active) {
lastKnownScrollPosition = this.terminal.buffer.active.viewportY;
}
});
}
/**
* Preserve viewport position during resize to prevent jumping
*/
preserveViewportPosition(targetScrollPosition) {
if (!this.terminal.buffer || !this.terminal.buffer.active) return;
const buffer = this.terminal.buffer.active;
const maxScroll = Math.max(0, buffer.length - this.terminal.rows);
// Ensure scroll position is within valid bounds
const safeScrollPosition = Math.min(targetScrollPosition, maxScroll);
// Only adjust if we have significant content and the position is different
if (
buffer.length > this.terminal.rows &&
Math.abs(buffer.viewportY - safeScrollPosition) > 2
) {
// Gradually adjust to prevent jarring movements
const steps = 3;
const diff = safeScrollPosition - buffer.viewportY;
const stepSize = Math.ceil(Math.abs(diff) / steps);
let currentStep = 0;
const adjustStep = () => {
if (currentStep >= steps) return;
const currentPos = buffer.viewportY;
const remaining = safeScrollPosition - currentPos;
const adjustment =
Math.sign(remaining) * Math.min(stepSize, Math.abs(remaining));
if (Math.abs(adjustment) >= 1) {
this.terminal.scrollLines(adjustment);
}
currentStep++;
if (currentStep < steps && Math.abs(remaining) > 1) {
setTimeout(adjustStep, 50);
}
};
setTimeout(adjustStep, 100);
}
}
/**
* Setup touch selection for mobile devices
*/
setupTouchSelection() {
// Only initialize touch selection on mobile devices
if (window.cordova && this.container) {
const terminalSettings = getTerminalSettings();
this.touchSelection = new TerminalTouchSelection(
this.terminal,
this.container,
{
tapHoldDuration:
terminalSettings.touchSelectionTapHoldDuration || 600,
moveThreshold: terminalSettings.touchSelectionMoveThreshold || 8,
handleSize: terminalSettings.touchSelectionHandleSize || 24,
hapticFeedback:
terminalSettings.touchSelectionHapticFeedback !== false,
showContextMenu:
terminalSettings.touchSelectionShowContextMenu !== false,
onFontSizeChange: (fontSize) => this.updateFontSize(fontSize),
},
);
}
}
/**
* Parse app keybindings into a format usable by the keyboard handler
*/
parseAppKeybindings() {
const parsedBindings = [];
Object.values(keyBindings).forEach((binding) => {
if (!binding.key) return;
// Skip editor-only keybindings in terminal
if (binding.editorOnly) return;
// Handle multiple key combinations separated by |
const keys = binding.key.split("|");
keys.forEach((keyCombo) => {
const parts = keyCombo.split("-");
const parsed = {
ctrl: false,
shift: false,
alt: false,
meta: false,
key: "",
};
parts.forEach((part) => {
const lowerPart = part.toLowerCase();
if (lowerPart === "ctrl") {
parsed.ctrl = true;
} else if (lowerPart === "shift") {
parsed.shift = true;
} else if (lowerPart === "alt") {
parsed.alt = true;
} else if (lowerPart === "meta" || lowerPart === "cmd") {
parsed.meta = true;
} else {
// This is the actual key
parsed.key = part;
}
});
if (parsed.key) {
parsedBindings.push(parsed);
}
});
});
return parsedBindings;
}
/**
* Setup copy/paste keyboard handlers
*/
setupCopyPasteHandlers() {
// Add keyboard event listener to terminal element
this.terminal.attachCustomKeyEventHandler((event) => {
// Check for Ctrl+Shift+C (copy)
if (event.ctrlKey && event.shiftKey && event.key === "C") {
event.preventDefault();
this.copySelection();
return false;
}
// Check for Ctrl+Shift+V (paste)
if (event.ctrlKey && event.shiftKey && event.key === "V") {
event.preventDefault();
this.pasteFromClipboard();
return false;
}
// Check for Ctrl+= or Ctrl++ (increase font size)
if (event.ctrlKey && (event.key === "+" || event.key === "=")) {
event.preventDefault();
this.increaseFontSize();
return false;
}
// Check for Ctrl+- (decrease font size)
if (event.ctrlKey && event.key === "-") {
event.preventDefault();
this.decreaseFontSize();
return false;
}
// Only intercept specific app-wide keybindings, let terminal handle the rest
if (event.ctrlKey || event.altKey || event.metaKey) {
// Skip modifier-only keys
if (["Control", "Alt", "Meta", "Shift"].includes(event.key)) {
return true;
}
// Get parsed app keybindings
const appKeybindings = this.parseAppKeybindings();
// Check if this is an app-specific keybinding
const isAppKeybinding = appKeybindings.some(
(binding) =>
binding.ctrl === event.ctrlKey &&
binding.shift === event.shiftKey &&
binding.alt === event.altKey &&
binding.meta === event.metaKey &&
binding.key === event.key,
);
if (isAppKeybinding) {
const appEvent = new KeyboardEvent("keydown", {
key: event.key,
ctrlKey: event.ctrlKey,
shiftKey: event.shiftKey,
altKey: event.altKey,
metaKey: event.metaKey,
bubbles: true,
cancelable: true,
});
// Dispatch to document so it gets picked up by the app's keyboard handler
document.dispatchEvent(appEvent);
// Return false to prevent terminal from processing this key
return false;
}
// For all other modifier combinations, let the terminal handle them
return true;
}
// Return true to allow normal processing for other keys
return true;
});
}
/**
* Copy selected text to clipboard
*/
copySelection() {
if (!this.terminal?.hasSelection()) return;
const selectedStr = this.terminal?.getSelection();
if (selectedStr && cordova?.plugins?.clipboard) {
cordova.plugins.clipboard.copy(selectedStr);
}
}
/**
* Paste text from clipboard
*/
pasteFromClipboard() {
if (cordova?.plugins?.clipboard) {
cordova.plugins.clipboard.paste((text) => {
this.terminal?.paste(text);
});
}
}
/**
* Create terminal container element
* @returns {HTMLElement} Container element
*/
createContainer() {
this.container = document.createElement("div");
this.container.className = "terminal-container";
this.container.style.cssText = `
width: 100%;
height: 100%;
position: relative;
background: ${this.options.theme.background};
overflow: hidden;
`;
return this.container;
}
/**
* Mount terminal to container
* @param {HTMLElement} container - Container element
*/
mount(container) {
if (!container) {
container = this.createContainer();
}
this.container = container;
// Apply terminal background color to container to match theme
this.container.style.background = this.options.theme.background;
try {
try {
this.terminal.loadAddon(this.webglAddon);
this.terminal.open(container);
} catch (error) {
console.error("Failed to load WebglAddon:", error);
this.webglAddon.dispose();
}
if (!this.terminal.element) {
// webgl loading failed for some reason, attach with DOM renderer
this.terminal.open(container);
}
const terminalSettings = getTerminalSettings();
// Load ligatures addon if enabled
if (terminalSettings.fontLigatures) {
this.loadLigaturesAddon();
}
// Wait for terminal to render then fit
setTimeout(() => {
this.fitAddon.fit();
this.terminal.focus();
// Initialize touch selection after terminal is mounted
this.setupTouchSelection();
}, 10);
} catch (error) {
console.error("Failed to mount terminal:", error);
}
return container;
}
/**
* Create new terminal session using global Terminal API
* @returns {Promise<string>} Terminal PID
*/
async createSession() {
if (!this.serverMode) {
throw new Error(
"Terminal is in local mode, cannot create server session",
);
}
try {
// Check if terminal is installed before starting AXS
if (!(await Terminal.isInstalled())) {
throw new Error(
"Terminal not installed. Please install terminal first.",
);
}
// Start AXS if not running
if (!(await Terminal.isAxsRunning())) {
await Terminal.startAxs(false, () => {}, console.error);
// Check if AXS started with interval polling
const maxRetries = 10;
let retries = 0;
while (retries < maxRetries) {
await new Promise((resolve) => setTimeout(resolve, 1000));
if (await Terminal.isAxsRunning()) {
break;
}
retries++;
}
// If AXS still not running after retries, throw error
if (!(await Terminal.isAxsRunning())) {
toast("Failed to start AXS server after multiple attempts");
//throw new Error("Failed to start AXS server after multiple attempts");
}
}
const requestBody = {
cols: this.terminal.cols,
rows: this.terminal.rows,
};
const response = await fetch(
`http://localhost:${this.options.port}/terminals`,
{
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify(requestBody),
},
);
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const data = await response.text();
this.pid = data.trim();
return this.pid;
} catch (error) {
console.error("Failed to create terminal session:", error);
throw error;
}
}
/**
* Connect to terminal session via WebSocket
* @param {string} pid - Terminal PID
*/
async connectToSession(pid) {
if (!this.serverMode) {
throw new Error(
"Terminal is in local mode, cannot connect to server session",
);
}
if (!pid) {
pid = await this.createSession();
}
this.pid = pid;
const wsUrl = `ws://localhost:${this.options.port}/terminals/${pid}`;
this.websocket = new WebSocket(wsUrl);
this.websocket.onopen = () => {
this.isConnected = true;
this.onConnect?.();
// Load attach addon after connection
this.attachAddon = new AttachAddon(this.websocket);
this.terminal.loadAddon(this.attachAddon);
this.terminal.unicode.activeVersion = "11";
// Focus terminal and ensure it's ready
this.terminal.focus();
this.fit();
};
this.websocket.onmessage = (event) => {
// Handle text messages (exit events)
if (typeof event.data === "string") {
try {
const message = JSON.parse(event.data);
if (message.type === "exit") {
this.onProcessExit?.(message.data);
return;
}
} catch (error) {
// Not a JSON message, let attachAddon handle it
}
}
// For binary data or non-exit text messages, let attachAddon handle them
};
this.websocket.onclose = (event) => {
this.isConnected = false;
this.onDisconnect?.();
};
this.websocket.onerror = (error) => {
console.error("WebSocket error:", error);
this.onError?.(error);
};
}
/**
* Resize terminal
* @param {number} cols - Number of columns
* @param {number} rows - Number of rows
*/
async resizeTerminal(cols, rows) {
if (!this.pid || !this.serverMode) return;
try {
await fetch(
`http://localhost:${this.options.port}/terminals/${this.pid}/resize`,
{
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({ cols, rows }),
},
);
} catch (error) {
console.error("Failed to resize terminal:", error);
}
}
/**
* Fit terminal to container
*/
fit() {
if (this.fitAddon) {
this.fitAddon.fit();
}
}
/**
* Write data to terminal
* @param {string} data - Data to write
*/
write(data) {
this.terminal.write(data);
}
/**
* Write line to terminal
* @param {string} data - Data to write
*/
writeln(data) {
this.terminal.writeln(data);
}
/**
* Clear terminal
*/
clear() {
this.terminal.clear();
}
/**
* Focus terminal
*/
focus() {
// Ensure cursor is visible before focusing to prevent half-visibility
if (this.terminal.buffer && this.terminal.buffer.active) {
const buffer = this.terminal.buffer.active;
const cursorY = buffer.cursorY;
const cursorViewportPos = buffer.baseY + cursorY;
const viewportTop = buffer.viewportY;
const viewportBottom = viewportTop + this.terminal.rows - 1;
// Check if cursor is fully visible (with margin to prevent half-visibility)
const isCursorFullyVisible =
cursorViewportPos >= viewportTop + 1 &&
cursorViewportPos <= viewportBottom - 2;
// If cursor is not fully visible, scroll to make it properly visible
if (!isCursorFullyVisible && buffer.length > this.terminal.rows) {
const targetScroll = Math.max(
0,
Math.min(
buffer.length - this.terminal.rows,
cursorViewportPos - Math.floor(this.terminal.rows * 0.25),
),
);
this.terminal.scrollToLine(targetScroll);
}
}
this.terminal.focus();
}
/**
* Blur terminal
*/
blur() {
this.terminal.blur();
}
/**
* Search in terminal
* @param {string} term - Search term
* @param {number} skip Number of search results to skip
* @param {boolean} backward Whether to search backward
*/
search(term, skip, backward) {
if (this.searchAddon) {
const searchOptions = {
regex: appSettings.value.search.regExp || false,
wholeWord: appSettings.value.search.wholeWord || false,
caseSensitive: appSettings.value.search.caseSensitive || false,
decorations: {
matchBorder: "#FFA500",
activeMatchBorder: "#FFFF00",
},
};
if (!term) {
return false;
}
if (backward) {
return this.searchAddon.findPrevious(term, searchOptions);
} else {
return this.searchAddon.findNext(term, searchOptions);
}
}
return false;
}
/**
* Update terminal theme
* @param {object|string} theme - Theme object or theme name
*/
updateTheme(theme) {
if (typeof theme === "string") {
theme = TerminalThemeManager.getTheme(theme);
}
this.options.theme = { ...this.options.theme, ...theme };
this.terminal.options.theme = this.options.theme;
}
/**
* Update terminal options
* @param {object} options - Options to update
*/
updateOptions(options) {
Object.keys(options).forEach((key) => {
if (key === "theme") {
this.updateTheme(options.theme);
} else {
this.terminal.options[key] = options[key];
this.options[key] = options[key];
}
});
}
/**
* Load image addon
*/
loadImageAddon() {
if (!this.imageAddon) {
try {
this.imageAddon = new ImageAddon();
this.terminal.loadAddon(this.imageAddon);
} catch (error) {
console.error("Failed to load ImageAddon:", error);
}
}
}
/**
* Dispose image addon
*/
disposeImageAddon() {
if (this.imageAddon) {
try {
this.imageAddon.dispose();
this.imageAddon = null;
} catch (error) {
console.error("Failed to dispose ImageAddon:", error);
}
}
}
/**
* Update image support setting
* @param {boolean} enabled - Whether to enable image support
*/
updateImageSupport(enabled) {
if (enabled) {
this.loadImageAddon();
} else {
this.disposeImageAddon();
}
}
/**
* Load ligatures addon
*/
loadLigaturesAddon() {
if (!this.ligaturesAddon) {
try {
this.ligaturesAddon = new LigaturesAddon();
this.terminal.loadAddon(this.ligaturesAddon);
} catch (error) {
console.error("Failed to load LigaturesAddon:", error);
}
}
}
/**
* Dispose ligatures addon
*/
disposeLigaturesAddon() {
if (this.ligaturesAddon) {
try {
this.ligaturesAddon.dispose();
this.ligaturesAddon = null;
} catch (error) {
console.error("Failed to dispose LigaturesAddon:", error);
}
}
}
/**
* Update font ligatures setting
* @param {boolean} enabled - Whether to enable font ligatures
*/
updateFontLigatures(enabled) {
if (enabled) {
this.loadLigaturesAddon();
} else {
this.disposeLigaturesAddon();
}
}
/**
* Load terminal font if it's not already loaded
*/
async loadTerminalFont() {
const fontFamily = this.options.fontFamily;
if (fontFamily && fonts.get(fontFamily)) {
try {
await fonts.loadFont(fontFamily);
} catch (error) {
console.warn(`Failed to load terminal font ${fontFamily}:`, error);
}
}
}
/**
* Increase terminal font size
*/
increaseFontSize() {
const currentSize = this.terminal.options.fontSize;
const newSize = Math.min(currentSize + 1, 24); // Max font size 24
this.updateFontSize(newSize);
}
/**
* Decrease terminal font size
*/
decreaseFontSize() {
const currentSize = this.terminal.options.fontSize;
const newSize = Math.max(currentSize - 1, 8); // Min font size 8
this.updateFontSize(newSize);
}
/**
* Update terminal font size and refresh display
*/
updateFontSize(fontSize) {
if (fontSize === this.terminal.options.fontSize) return;
this.terminal.options.fontSize = fontSize;
this.options.fontSize = fontSize;
// Update terminal settings properly
const currentSettings = appSettings.value.terminalSettings || {};
const updatedSettings = { ...currentSettings, fontSize };
appSettings.update({ terminalSettings: updatedSettings }, false);
// Refresh terminal display
this.terminal.refresh(0, this.terminal.rows - 1);
// Fit terminal to container after font size change to prevent empty space
setTimeout(() => {
if (this.fitAddon) {
this.fitAddon.fit();
}
}, 50);
// Update touch selection cell dimensions if it exists
if (this.touchSelection) {
setTimeout(() => {
this.touchSelection.updateCellDimensions();
}, 100);
}
}
/**
* Terminate terminal session
*/
async terminate() {
if (this.websocket) {
this.websocket.close();
}
if (this.pid && this.serverMode) {
try {
await fetch(
`http://localhost:${this.options.port}/terminals/${this.pid}/terminate`,
{
method: "POST",
},
);
} catch (error) {
console.error("Failed to terminate terminal:", error);
}
}
}
/**
* Dispose terminal
*/
dispose() {
this.terminate();
// Dispose touch selection
if (this.touchSelection) {
this.touchSelection.destroy();
this.touchSelection = null;
}
// Dispose addons
this.disposeImageAddon();
this.disposeLigaturesAddon();
if (this.terminal) {
this.terminal.dispose();
}
if (this.container) {
this.container.remove();
}
}
// Event handlers (can be overridden)