-
-
Notifications
You must be signed in to change notification settings - Fork 195
Expand file tree
/
Copy pathmain.js
More file actions
1040 lines (933 loc) · 38.6 KB
/
Copy pathmain.js
File metadata and controls
1040 lines (933 loc) · 38.6 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
/*
* 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.
*
*/
/**
* Terminal Extension - Integrates a terminal panel into Phoenix Code.
* Only available in native (desktop) builds where node-pty is available.
*/
define(function (require, exports, module) {
if (!Phoenix.isNativeApp) {
return; // Terminal requires Node.js (node-pty)
}
const AppInit = require("utils/AppInit");
const CommandManager = require("command/CommandManager");
const WorkspaceManager = require("view/WorkspaceManager");
const ProjectManager = require("project/ProjectManager");
const ExtensionUtils = require("utils/ExtensionUtils");
const Metrics = require("utils/Metrics");
const NodeConnector = require("NodeConnector");
const Mustache = require("thirdparty/mustache/mustache");
const Dialogs = require("widgets/Dialogs");
const DefaultDialogs = require("widgets/DefaultDialogs");
const Strings = require("strings");
const StringUtils = require("utils/StringUtils");
const Menus = require("command/Menus");
const Commands = require("command/Commands");
const KeyBindingManager = require("command/KeyBindingManager");
const NotificationUI = require("widgets/NotificationUI");
const TerminalInstance = require("./TerminalInstance");
const ShellProfiles = require("./ShellProfiles");
const panelHTML = require("text!./terminal-panel.html");
// Load xterm.css (terminal panel styles are in src/styles/Extn-Terminal.less)
ExtensionUtils.loadStyleSheet(module, "../../thirdparty/xterm/xterm.css");
// Constants
const CMD_VIEW_TERMINAL = Commands.VIEW_TERMINAL;
const CMD_NEW_TERMINAL = "terminal.new";
const CMD_TERMINAL_COPY = "terminal.copy";
const CMD_TERMINAL_PASTE = "terminal.paste";
const CMD_TERMINAL_CLEAR = "terminal.clear";
const TERMINAL_CONTEXT_MENU_ID = "terminal-context-menu";
const PANEL_ID = "terminal-panel";
const PANEL_MIN_SIZE = 100;
// Shell process names — if the foreground process is one of these, no child is running
const SHELL_NAMES = new Set([
"bash", "zsh", "fish", "sh", "dash", "ksh", "csh", "tcsh",
"pwsh", "powershell", "cmd.exe", "nu", "elvish", "xonsh",
"login",
// Windows shell executables (returned with .exe suffix)
"bash.exe", "pwsh.exe", "powershell.exe", "nu.exe",
"fish.exe", "elvish.exe", "xonsh.exe", "wsl.exe"
]);
/**
* Check if a process name is a shell (handles full paths like /bin/bash)
*/
function _isShellProcess(processName) {
if (!processName) {
return true;
}
// Strip path and leading "-" for login shells (e.g. "-zsh")
const basename = processName.split("/").pop().split("\\").pop().replace(/^-/, "");
return SHELL_NAMES.has(basename);
}
// State
let panel = null;
let nodeConnector = null;
let terminalInstances = []; // All terminal instances
let activeTerminalId = null; // Currently visible terminal
let processInfo = {}; // id -> processName from PTY
let originalDefaultShellName = null; // System-detected default shell name
let _focusToastShown = false; // Show focus hint toast only once per session
let _clearHintShown = false; // Show clear buffer hint toast only once per session
let $panel, $contentArea, $shellDropdown, $flyoutList;
/**
* Create a new NodeConnector for terminal communication
*/
function _initNodeConnector() {
nodeConnector = NodeConnector.createNodeConnector("phoenix_terminal", exports);
}
/**
* Create the bottom panel
*/
function _createPanel() {
const templateVars = {
Strings: {
CMD_NEW_TERMINAL: "New Terminal",
TERMINAL_CLEAR: "Clear",
TERMINAL_KILL: "Kill",
CMD_HIDE_TERMINAL: "Close Panel"
}
};
$panel = $(Mustache.render(panelHTML, templateVars));
panel = WorkspaceManager.createBottomPanel(PANEL_ID, $panel, PANEL_MIN_SIZE, undefined, {iconSvg: "styles/images/panel-icon-terminal.svg"});
// Override focus() so Shift+Escape can transfer focus to the terminal
panel.focus = function () {
const active = _getActiveTerminal();
if (active) {
active.focus();
return true;
}
return false;
};
// Cache DOM references
$contentArea = $panel.find(".terminal-content-area");
$shellDropdown = $panel.find(".terminal-shell-dropdown");
$flyoutList = $panel.find(".terminal-flyout-list");
// Right-click context menu for terminal content area
$contentArea.on("contextmenu", function (e) {
e.preventDefault();
terminalContextMenu.open(e);
});
// "+" button creates a new terminal with the default shell
$panel.find(".terminal-flyout-new-btn").on("click", function (e) {
e.stopPropagation();
_createNewTerminal();
});
// Dropdown chevron button toggles shell selector
$panel.find(".terminal-flyout-dropdown-btn").on("click", _onDropdownButtonClick);
_setupPhoenixShortcuts();
// Refresh process info when the tab bar gains focus or mouse enters
$panel.find(".terminal-tab-bar").on("mouseenter", _refreshAllProcesses);
$panel.find(".terminal-tab-bar").on("focusin", _refreshAllProcesses);
// Listen for panel resize
WorkspaceManager.on("workspaceUpdateLayout", _handleResize);
// Focus terminal when the panel becomes visible
const PanelView = require("view/PanelView");
PanelView.on(PanelView.EVENT_PANEL_SHOWN, function (_event, panelId) {
if (panelId === PANEL_ID) {
_updateTabBarMode();
const active = _getActiveTerminal();
if (active) {
active.handleResize();
active.focus();
}
_showFocusHintToast();
Metrics.countEvent(Metrics.EVENT_TYPE.TERMINAL, "panel", "open");
}
});
// Listen for theme changes via MutationObserver on body class
const observer = new MutationObserver(function () {
_updateAllThemes();
});
observer.observe(document.body, {attributes: true, attributeFilter: ["class"]});
}
/**
* Populate the shell dropdown menu with checkmark on current default
*/
function _populateShellDropdown() {
const shells = ShellProfiles.getShells();
const defaultShell = ShellProfiles.getDefaultShell();
$shellDropdown.empty();
for (const shell of shells) {
const isSelected = defaultShell && defaultShell.name === shell.name;
const $check = $('<span class="shell-check"></span>');
if (isSelected) {
$check.append('<i class="fa-solid fa-check"></i>');
}
const $item = $('<div class="shell-option"></div>')
.attr("data-shell-name", shell.name)
.append($check)
.append($('<span></span>').text(shell.name));
$item.on("click", function () {
_hideShellDropdown();
ShellProfiles.setDefaultShell(shell.name);
_populateShellDropdown();
_updateNewTerminalButtonLabel();
// Metric: which shell the user picked from the dropdown
// (default-shell switch). _createNewTerminalWithShell below
// will also raise its own "new" metric for the spawn.
Metrics.countEvent(Metrics.EVENT_TYPE.TERMINAL, "pick",
_shellMetricLabel(shell.name));
_createNewTerminalWithShell(shell);
});
$shellDropdown.append($item);
}
}
/**
* Update the "+ New Terminal" button label.
* Shows "Terminal" when using the system default, or the shell name when user switched.
*/
function _updateNewTerminalButtonLabel() {
const defaultShell = ShellProfiles.getDefaultShell();
const isOriginal = defaultShell && defaultShell.name === originalDefaultShellName;
const label = !defaultShell || isOriginal ? "Terminal" : defaultShell.name;
$panel.find(".terminal-btn-label").text(label);
$panel.find(".terminal-flyout-new-btn").attr("title", label);
}
/**
* Show/hide the shell dropdown
*/
function _showShellDropdown() {
// Move dropdown out of the flyout and append to the terminal body
// so it isn't clipped by the tab bar's overflow: hidden.
// Position it above the actions row, aligned to the right.
const $body = $panel.find(".terminal-body");
const $actions = $panel.find(".terminal-flyout-actions");
const actionsRect = $actions[0].getBoundingClientRect();
const bodyRect = $body[0].getBoundingClientRect();
$shellDropdown.appendTo($body);
$shellDropdown.css({
position: "absolute",
bottom: (bodyRect.bottom - actionsRect.top) + "px",
right: "0",
left: "auto",
top: "auto"
});
$shellDropdown.removeClass("forced-hidden");
// Close on outside click
setTimeout(function () {
$(document).one("click", _hideShellDropdown);
}, 0);
}
function _hideShellDropdown() {
$shellDropdown.addClass("forced-hidden");
}
/**
* Handle dropdown chevron button click: toggle shell selector
*/
function _onDropdownButtonClick(e) {
e.stopPropagation();
if ($shellDropdown.hasClass("forced-hidden")) {
_populateShellDropdown();
_showShellDropdown();
} else {
_hideShellDropdown();
}
}
/**
* Create a new terminal with the default shell
*/
async function _createNewTerminal(cwdOverride) {
const shell = ShellProfiles.getDefaultShell();
return _createNewTerminalWithShell(shell, cwdOverride);
}
/**
* Convert a VFS path to a native platform path suitable for use as cwd.
* Strips trailing slashes (posix_spawnp can fail with them).
*/
function _toNativePath(vfsPath) {
let cwd = vfsPath;
const tauriPrefix = Phoenix.VFS.getTauriDir();
if (cwd.startsWith(tauriPrefix)) {
cwd = Phoenix.fs.getTauriPlatformPath(cwd);
}
if (cwd.length > 1 && (cwd.endsWith("/") || cwd.endsWith("\\"))) {
cwd = cwd.slice(0, -1);
}
return cwd;
}
/**
* Create a new terminal with a specific shell profile
* @param {Object} shell - Shell profile to use
* @param {string} [cwdOverride] - Optional VFS path to use as cwd instead of project root
*/
/**
* Map an OS shell name (e.g. "powershell.exe", "bash.exe") to a short
* family label so the metrics server's per-event length budget stays
* comfortable. Strips ".exe" and lower-cases; unknown shells fall
* through under "other" (with their lower-cased name shown only in
* the cap'd 8-char form).
*/
function _shellMetricLabel(shellName) {
if (!shellName) { return "unknown"; }
let n = String(shellName).toLowerCase();
if (n.endsWith(".exe")) { n = n.slice(0, -4); }
// pwsh & powershell are functionally the same family for the metric.
if (n === "powershell") { n = "pwsh"; }
// Cap so an unexpected long shell name can't blow the label cell.
if (n.length > 8) { n = n.slice(0, 8); }
return n || "unknown";
}
async function _createNewTerminalWithShell(shell, cwdOverride) {
if (!shell) {
console.error("Terminal: No shell available");
Metrics.countEvent(Metrics.EVENT_TYPE.TERMINAL, "new", "noShell");
return;
}
// Metric: a new terminal session was created, keyed by shell family.
Metrics.countEvent(Metrics.EVENT_TYPE.TERMINAL, "new",
_shellMetricLabel(shell.name));
// Get cwd: use override if provided, otherwise fall back to project root
let cwd;
if (cwdOverride) {
cwd = _toNativePath(cwdOverride);
} else {
const projectRoot = ProjectManager.getProjectRoot();
if (projectRoot) {
cwd = _toNativePath(projectRoot.fullPath);
}
}
// Create instance
const instance = new TerminalInstance(nodeConnector, shell, cwd);
// Set up callbacks
instance.onTitleChanged = _onTerminalTitleChanged;
instance.onProcessExit = _onTerminalProcessExit;
// Create xterm UI
instance.create($contentArea);
// Add to list
terminalInstances.push(instance);
// Tab-count bucket metric — raised only on tab creation so we
// can plot how many concurrent terminal tabs users keep open.
// Buckets: 1 → "one", 2..4 → "LTE4", 5..9 → "LTE9", 10+ → "GT10".
const count = terminalInstances.length;
const tabsBucket = count === 1 ? "one"
: count <= 4 ? "LTE4"
: count <= 9 ? "LTE9"
: "GT10";
Metrics.countEvent(Metrics.EVENT_TYPE.TERMINAL, "tabs", tabsBucket);
// Activate this terminal (also updates flyout)
_activateTerminal(instance.id);
// Show panel if hidden
if (!panel.isVisible()) {
panel.show();
}
// Fit the terminal now that the panel is visible so xterm
// has the correct dimensions before the PTY is spawned.
// Without this, xterm stays at default 80x24 while the PTY
// is created at the actual container size, causing a later
// _fit() to erase the prompt without a real resize/SIGWINCH.
try { instance.fitAddon.fit(); } catch (e) { /* not ready */ }
// Spawn PTY process
await instance.spawn();
}
/**
* Activate a terminal tab (show it, hide others)
*/
function _activateTerminal(id) {
activeTerminalId = id;
// Show/hide terminal containers
for (const inst of terminalInstances) {
if (inst.id === id) {
inst.show();
} else {
inst.hide();
}
}
_updateFlyout();
_refreshAllProcesses();
}
/**
* Close a terminal instance, confirming first if a child process is running
*/
async function _closeTerminal(id) {
const idx = terminalInstances.findIndex(t => t.id === id);
if (idx === -1) {
return;
}
const instance = terminalInstances[idx];
// Check for active child process before closing
if (instance.isAlive) {
try {
const result = await nodeConnector.execPeer("getTerminalProcess", {id});
const processName = result.process || "";
if (processName && !_isShellProcess(processName)) {
const message = StringUtils.format(
Strings.TERMINAL_CLOSE_CONFIRM_MSG, _escapeHtml(processName)
);
const dialog = Dialogs.showConfirmDialog(
Strings.TERMINAL_CLOSE_CONFIRM_TITLE, message
);
const buttonId = await dialog.getPromise();
if (buttonId !== Dialogs.DIALOG_BTN_OK) {
return;
}
}
} catch (e) {
// Terminal may already be dead; proceed with close
}
}
instance.dispose();
terminalInstances.splice(idx, 1);
delete processInfo[id];
Metrics.countEvent(Metrics.EVENT_TYPE.TERMINAL, "close", "user");
// If we closed the active terminal, activate another
if (activeTerminalId === id) {
if (terminalInstances.length > 0) {
const newActive = terminalInstances[Math.min(idx, terminalInstances.length - 1)];
_activateTerminal(newActive.id);
} else {
activeTerminalId = null;
}
}
// If no terminals left, hide the panel
if (terminalInstances.length === 0) {
panel.hide();
}
_updateFlyout();
}
/**
* Get the active terminal instance
*/
function _getActiveTerminal() {
return terminalInstances.find(t => t.id === activeTerminalId) || null;
}
/**
* Clear the active terminal
*/
function _clearActiveTerminal() {
const active = _getActiveTerminal();
if (active) {
active.clear();
}
}
/**
* Kill the active terminal's process
*/
function _killActiveTerminal() {
const active = _getActiveTerminal();
if (active && active.isAlive) {
nodeConnector.execPeer("killTerminal", {id: active.id}).catch((err) => {
console.error("Terminal: kill error:", err);
});
}
}
/**
* Handle terminal title change — also fetches and displays the foreground process.
* Clears the stale-title flag since the shell has provided its own title.
*/
function _onTerminalTitleChanged(id) {
const instance = terminalInstances.find(t => t.id === id);
if (instance) {
instance._titleStale = false;
}
_updateFlyout();
_updateTabProcess(id);
}
/**
* Fetch and display the foreground process for a terminal tab
*/
function _updateTabProcess(id) {
const instance = terminalInstances.find(t => t.id === id);
if (!instance || !instance.isAlive) {
return;
}
nodeConnector.execPeer("getTerminalProcess", {id}).then(function (result) {
const newProc = result.process || "";
if (processInfo[id] !== newProc) {
const oldProc = processInfo[id];
processInfo[id] = newProc;
// When a child process exits and the shell regains
// foreground, the child may have set a custom title
// via escape sequences. Some shells (e.g. zsh on
// macOS) don't emit a title reset, leaving inst.title
// stale. Mark it so _updateFlyout can fall back to
// the profile name. If the shell DOES emit a title
// change (e.g. bash on Linux), _onTerminalTitleChanged
// clears this flag immediately.
if (oldProc && !_isShellProcess(oldProc) && _isShellProcess(newProc)) {
instance._titleStale = true;
}
_updateFlyout();
}
}).catch(function () {
// Terminal may have been closed; ignore
});
}
/**
* Refresh process info for all alive terminals.
* Called on flyout hover so the tab bar is up-to-date when the user looks.
*/
function _refreshAllProcesses() {
for (const inst of terminalInstances) {
if (inst.isAlive) {
_updateTabProcess(inst.id);
}
}
}
/**
* Rebuild the flyout panel to reflect current tabs
*/
/**
* Extract the last directory name from a terminal title.
* Title format is typically "user@host: /path/to/dir" or "user@host: ~/path/to/dir".
*/
function _extractCwdBasename(title) {
const colonIdx = title.indexOf(": ");
const pathPart = colonIdx >= 0 ? title.slice(colonIdx + 2) : title;
const trimmed = pathPart.replace(/\/+$/, "");
const lastSlash = trimmed.lastIndexOf("/");
return lastSlash >= 0 ? trimmed.slice(lastSlash + 1) : trimmed;
}
function _updateFlyout() {
$flyoutList.empty();
for (const inst of terminalInstances) {
const proc = processInfo[inst.id] || "";
const basename = proc ? proc.split("/").pop().split("\\").pop() : "";
// Label: process basename; right side: cwd basename; tooltip: full title.
// If the title is stale (child set it and the shell didn't reset it),
// fall back to the shell profile name.
const label = basename || "Terminal";
const displayTitle = inst._titleStale ? inst.shellProfile.name : inst.title;
const cwdName = _extractCwdBasename(displayTitle);
const $item = $('<div class="terminal-flyout-item"></div>')
.attr("data-terminal-id", inst.id)
.attr("title", displayTitle)
.toggleClass("active", inst.id === activeTerminalId);
if (!inst.isAlive) {
$item.css("opacity", "0.6");
}
$item.append('<span class="terminal-flyout-close"><i class="fa-solid fa-xmark"></i></span>');
$item.append('<span class="terminal-flyout-icon"><i class="fa-solid fa-terminal"></i></span>');
$item.append($('<span class="terminal-flyout-title"></span>').text(label));
if (cwdName) {
$item.append($('<span class="terminal-flyout-cwd"></span>').text(cwdName));
}
$item.on("click", function (e) {
if (!$(e.target).closest(".terminal-flyout-close").length) {
_activateTerminal(inst.id);
}
});
$item.find(".terminal-flyout-close").on("click", function (e) {
e.stopPropagation();
_closeTerminal(inst.id);
});
$flyoutList.append($item);
}
}
/**
* Handle terminal process exit
*/
function _onTerminalProcessExit(id, exitCode) {
delete processInfo[id];
_updateFlyout();
// Metric: terminal process exited on its own (e.g. user typed
// "exit"). Distinct from "user" close above, which records the
// X-button / panel-driven close path. Exit code is bucketed
// ok/err so cardinality stays bounded.
Metrics.countEvent(Metrics.EVENT_TYPE.TERMINAL, "exit",
exitCode === 0 ? "ok" : "err");
}
/**
* Show the terminal panel. Creates a new terminal if none exist.
* If the panel is visible and the active terminal is focused and there
* are 2+ terminals, cycles to the next one. Otherwise just shows and
* focuses the active terminal.
*
* @param {Object} [options] - Optional settings
* @param {string} [options.shellCommand] - A shell command to execute in a new terminal.
* When provided, always creates a fresh terminal and types the command into it.
*/
async function _showTerminal(options) {
if (options && options.shellCommand) {
await _createNewTerminal();
const active = _getActiveTerminal();
if (active && active.isAlive) {
// Wait for the shell to output its prompt before sending the command.
await active.firstDataReceived;
nodeConnector.execPeer("writeTerminal", {
id: active.id,
data: options.shellCommand + "\r"
});
}
return;
}
if (terminalInstances.length === 0) {
await _createNewTerminal();
return;
}
const active = _getActiveTerminal();
const terminalHasFocus = active && active.$container &&
active.$container[0].contains(document.activeElement);
if (terminalInstances.length >= 2 && panel.isVisible() && terminalHasFocus) {
const activeIdx = terminalInstances.findIndex(t => t.id === activeTerminalId);
const nextIdx = (activeIdx + 1) % terminalInstances.length;
_activateTerminal(terminalInstances[nextIdx].id);
} else {
panel.show();
if (active) {
active.handleResize();
active.focus();
}
}
}
/**
* Update the expanded/collapsed tab bar class based on panel width
*/
function _updateTabBarMode() {
$panel.toggleClass("terminal-tabs-expanded", $panel.width() >= 840);
}
/**
* Handle workspace resize
*/
function _handleResize() {
_updateTabBarMode();
const active = _getActiveTerminal();
if (active) {
active.handleResize();
}
_refreshAllProcesses();
}
/**
* Set up keyboard shortcut routing so that when the terminal is focused,
* all keys go to the terminal except shortcuts bound to specific Phoenix
* commands (e.g. toggle terminal, keyboard nav overlay).
*/
function _setupPhoenixShortcuts() {
// Commands whose shortcuts should pass through to Phoenix
// even when the terminal is focused.
const PASSTHROUGH_COMMANDS = [
Commands.VIEW_TERMINAL,
Commands.CMD_KEYBOARD_NAV_UI_OVERLAY
];
// Build a set of shortcut strings, rebuilt when bindings change.
let passthroughShortcuts = new Set();
function rebuild() {
passthroughShortcuts = new Set();
for (const cmdId of PASSTHROUGH_COMMANDS) {
for (const binding of KeyBindingManager.getKeyBindings(cmdId)) {
if (binding.key) {
passthroughShortcuts.add(binding.key);
}
}
}
}
rebuild();
KeyBindingManager.on(KeyBindingManager.EVENT_KEY_BINDING_ADDED, rebuild);
KeyBindingManager.on(KeyBindingManager.EVENT_KEY_BINDING_REMOVED, rebuild);
KeyBindingManager.addGlobalKeydownHook(function (event, shortcut) {
if (event.type !== "keydown") {
return false;
}
const el = document.activeElement;
if (!el || !$contentArea[0].contains(el)) {
return false;
}
const ctrlOrMeta = event.ctrlKey || event.metaKey;
const key = event.key.toLowerCase();
// Ctrl+K (Cmd+K on mac): clear terminal scrollback
if (ctrlOrMeta && !event.shiftKey && key === "k") {
event.preventDefault();
_clearActiveTerminal();
return true;
}
// Show clear buffer hint on Ctrl+L
if (ctrlOrMeta && !event.shiftKey && key === "l") {
_showClearBufferHintToast();
}
// Let Phoenix handle shortcuts bound to passthrough commands
if (shortcut && passthroughShortcuts.has(shortcut)) {
return false;
}
// Block Phoenix from handling everything else — let xterm get it
return true;
});
}
/**
* Update all terminal themes (after editor theme change)
*/
function _updateAllThemes() {
for (const inst of terminalInstances) {
inst.updateTheme();
}
}
/**
* Show a one-time toast hint about Shift+Escape to switch focus
*/
function _showFocusHintToast() {
if (_focusToastShown) {
return;
}
_focusToastShown = true;
const shortcutKey = '<kbd>Shift+Esc</kbd>';
const message = StringUtils.format(Strings.TERMINAL_FOCUS_HINT, shortcutKey);
NotificationUI.showToastOn($contentArea[0], message, {
autoCloseTimeS: 5,
dismissOnClick: true
});
}
/**
* Show a one-time toast hint about Ctrl/Cmd+K to clear terminal buffer
*/
function _showClearBufferHintToast() {
if (_clearHintShown) {
return;
}
_clearHintShown = true;
const isMac = brackets.platform === "mac";
const shortcutKey = isMac ? '<kbd>Cmd+K</kbd>' : '<kbd>Ctrl+K</kbd>';
const message = StringUtils.format(Strings.TERMINAL_CLEAR_BUFFER_HINT, shortcutKey);
NotificationUI.showToastOn($contentArea[0], message, {
autoCloseTimeS: 5,
dismissOnClick: true
});
}
/**
* Escape HTML special characters
*/
function _escapeHtml(str) {
const div = document.createElement("div");
div.textContent = str;
return div.innerHTML;
}
/**
* Clean up all terminals (on app quit).
* Fire-and-forget — PTY kills are not awaited.
*/
function _disposeAll() {
for (const inst of terminalInstances) {
inst.dispose();
}
terminalInstances = [];
processInfo = {};
}
/**
* Async version: awaits all PTY kill commands so the
* caller can be sure the kill signals have been sent
* and acknowledged by the Node side.
*/
async function _disposeAllAsync() {
const killPromises = terminalInstances
.filter(function (inst) { return inst.isAlive && !inst._disposed; })
.map(function (inst) {
return nodeConnector.execPeer("killTerminal", {id: inst.id})
.catch(function () {});
});
_disposeAll();
await Promise.all(killPromises);
}
// Register commands
CommandManager.register("New Terminal", CMD_NEW_TERMINAL, _createNewTerminal, { supportsDesignMode: true });
CommandManager.register(Strings.CMD_VIEW_TERMINAL, CMD_VIEW_TERMINAL, _showTerminal, { supportsDesignMode: true });
CommandManager.register(Strings.CMD_OPEN_IN_INTEGRATED_TERMINAL,
Commands.NAVIGATE_OPEN_IN_INTEGRATED_TERMINAL, function () {
const entry = ProjectManager.getSelectedItem();
let cwdPath;
if (entry) {
cwdPath = entry.isDirectory ? entry.fullPath : entry.parentPath;
} else {
const projectRoot = ProjectManager.getProjectRoot();
cwdPath = projectRoot ? projectRoot.fullPath : undefined;
}
_createNewTerminal(cwdPath);
}, { supportsDesignMode: true });
// Terminal context menu commands
CommandManager.register(Strings.CMD_COPY, CMD_TERMINAL_COPY, function () {
const active = _getActiveTerminal();
if (active && active.terminal.hasSelection()) {
navigator.clipboard.writeText(active.terminal.getSelection());
active.focus();
}
});
CommandManager.register(Strings.CMD_PASTE, CMD_TERMINAL_PASTE, function () {
const active = _getActiveTerminal();
if (active && active.isAlive) {
active.focus();
Phoenix.app.clipboardReadText().then(function (text) {
if (text) {
nodeConnector.execPeer("writeTerminal", {id: active.id, data: text});
}
}).catch(function (err) {
console.error("Terminal paste failed:", err);
});
}
});
CommandManager.register(Strings.TERMINAL_CLEAR, CMD_TERMINAL_CLEAR, function () {
_clearActiveTerminal();
const active = _getActiveTerminal();
if (active) {
active.focus();
}
});
// Register terminal context menu
const terminalContextMenu = Menus.registerContextMenu(TERMINAL_CONTEXT_MENU_ID);
terminalContextMenu.addMenuItem(CMD_TERMINAL_COPY);
terminalContextMenu.addMenuItem(CMD_TERMINAL_PASTE);
terminalContextMenu.addMenuDivider();
terminalContextMenu.addMenuItem(CMD_TERMINAL_CLEAR);
// Enable/disable Copy based on terminal selection
terminalContextMenu.on(Menus.EVENT_BEFORE_CONTEXT_MENU_OPEN, function () {
const active = _getActiveTerminal();
const hasSelection = active && active.terminal.hasSelection();
CommandManager.get(CMD_TERMINAL_COPY).setEnabled(hasSelection);
CommandManager.get(CMD_TERMINAL_PASTE).setEnabled(active && active.isAlive);
CommandManager.get(CMD_TERMINAL_CLEAR).setEnabled(!!active);
});
function _createToolbarButton() {
const $btn = $("<a>")
.attr({
id: "terminal-toolbar-button",
href: "#",
title: Strings.CMD_VIEW_TERMINAL
})
.insertBefore("#app-drawer-button");
$btn.on("click", function () {
if (WorkspaceManager.isInDesignMode()) {
CommandManager.execute(Commands.VIEW_TOGGLE_DESIGN_MODE);
CommandManager.execute(CMD_VIEW_TERMINAL);
return;
}
if (panel && panel.isVisible()) {
panel.hide();
} else {
CommandManager.execute(CMD_VIEW_TERMINAL);
}
});
const PanelView = require("view/PanelView");
PanelView.on(PanelView.EVENT_PANEL_SHOWN, function (_event, panelId) {
$btn.toggleClass("selected-button", panelId === PANEL_ID);
});
PanelView.on(PanelView.EVENT_PANEL_HIDDEN, function (_event, panelId) {
if (panelId === PANEL_ID || panelId === WorkspaceManager.DEFAULT_PANEL_ID) {
$btn.removeClass("selected-button");
}
});
}
// Initialize on app ready
AppInit.appReady(function () {
if (Phoenix.isSpecRunnerWindow) {
return;
}
_initNodeConnector();
_createPanel();
_createToolbarButton();
// Gate user-initiated panel close (X button): confirm if needed, then
// dispose all terminals. Programmatic hide() just collapses the panel
// without disposing terminals.
panel.registerOnCloseRequestedHandler(async function () {
// Query all terminals in parallel to avoid sequential 2s waits on Windows
const aliveInstances = terminalInstances.filter(inst => inst.isAlive);
const results = await Promise.all(aliveInstances.map(function (inst) {
return nodeConnector.execPeer("getTerminalProcess", {id: inst.id})
.catch(function () { return {process: ""}; });
}));
const activeProcesses = [];
for (const result of results) {
if (result.process && !_isShellProcess(result.process)) {
activeProcesses.push(result.process);
}
}
let title, message, confirmText;
const count = terminalInstances.length;
const procCount = activeProcesses.length;
if (count === 1 && procCount > 0) {
// Single terminal with an active process
title = Strings.TERMINAL_CLOSE_SINGLE_TITLE;
message = Strings.TERMINAL_CLOSE_SINGLE_MSG;
confirmText = Strings.TERMINAL_CLOSE_SINGLE_BTN;
} else if (count > 1 && procCount === 0) {
// Multiple terminals, no active processes
title = Strings.TERMINAL_CLOSE_ALL_TITLE;
message = Strings.TERMINAL_CLOSE_ALL_MSG;
confirmText = Strings.TERMINAL_CLOSE_ALL_BTN;
} else if (count > 1 && procCount > 0) {
// Multiple terminals, some with active processes
title = Strings.TERMINAL_CLOSE_ALL_TITLE;
message = procCount === 1
? Strings.TERMINAL_CLOSE_ALL_MSG_PROCESS_ONE
: StringUtils.format(Strings.TERMINAL_CLOSE_ALL_MSG_PROCESS_MANY, procCount);
confirmText = Strings.TERMINAL_CLOSE_ALL_STOP_BTN;
} else {
// Single idle terminal — no confirmation needed
await _disposeAllAsync();
activeTerminalId = null;
_updateFlyout();
return true;
}
const buttons = [
{className: Dialogs.DIALOG_BTN_CLASS_NORMAL, id: Dialogs.DIALOG_BTN_CANCEL, text: Strings.CANCEL},
{className: Dialogs.DIALOG_BTN_CLASS_PRIMARY, id: Dialogs.DIALOG_BTN_OK, text: confirmText}
];
const dialog = Dialogs.showModalDialog(
DefaultDialogs.DIALOG_ID_INFO, title, message, buttons
);
const buttonId = await dialog.getPromise();
if (buttonId !== Dialogs.DIALOG_BTN_OK) {
return false;
}
// User confirmed — dispose everything
await _disposeAllAsync();
activeTerminalId = null;
_updateFlyout();
return true;
});
// Detect shells
ShellProfiles.init(nodeConnector).then(function () {
const shells = ShellProfiles.getShells();
const systemDefault = ShellProfiles.getDefaultShell();
originalDefaultShellName = systemDefault ? systemDefault.name : null;
if (shells.length <= 1) {
$panel.find(".terminal-flyout-dropdown-btn").addClass("forced-hidden");
}
_populateShellDropdown();
_updateNewTerminalButtonLabel();
});