feat: several terminal tabs per project, with a dropdown
A directory now has a TerminalWorkspace holding a list of tabs instead of a
single session. The status bar's left side became a dropdown: it shows the
active tab and its state ("终端 2 · 运行中") and lists the other tabs (the
active one checked) plus "新建终端". New tabs take the smallest free number,
so closing one frees its name.
Only the active tab keeps a socket: switching detaches the old tab and
attaches the new one, whose screen is replayed from the server snapshot; the
shell itself keeps running. The tab's model stays in memory, so switching
back is immediate.
The tab list (ids, labels, active one) is saved per connection and directory.
On the first open the server's sessions for the directory are reconciled with
it: saved labels and order are kept for sessions that still exist, sessions
opened elsewhere (web UI) are appended in creation order, and tabs whose
session is gone are dropped. Project-action command runners are not shown as
tabs. The 0.4.2 single-session value is read as one tab.
0.4.3 (403).
This commit is contained in:
1 parent
675d19d563
commit
a7bc380ac0
9 files changed
+717
-298
No files matched your search
+303
-94
@@ -1,6 +1,7 @@
|
||||
// The live terminal: the xterm model the view renders, and the socket that
|
||||
// carries its bytes. Kept on AppState so closing the panel (or switching
|
||||
// tabs) does not end the shell; reattaching replays the server's snapshot.
|
||||
// carries its bytes. A directory can hold several tabs; the workspace keeps
|
||||
// them and owns which one is attached, so closing the panel (or switching
|
||||
// tabs) does not end the shells — reattaching replays the server's snapshot.
|
||||
import 'dart:async';
|
||||
|
||||
import 'package:flutter/foundation.dart';
|
||||
@@ -8,11 +9,280 @@ import 'package:xterm/xterm.dart';
|
||||
|
||||
import 'api/terminal.dart';
|
||||
import 'state.dart';
|
||||
import 'storage.dart';
|
||||
|
||||
/// One terminal tab. [state] holds the model and the socket; the label is the
|
||||
/// local name ("终端 1") the dropdown shows.
|
||||
class TerminalTab {
|
||||
final TerminalSessionState state;
|
||||
String label;
|
||||
TerminalTab(this.state, this.label);
|
||||
}
|
||||
|
||||
/// A tab before its state exists: [id] is the server session when the tab is
|
||||
/// restored, null when it is about to be created.
|
||||
class TerminalTabPlan {
|
||||
final String? id;
|
||||
final String label;
|
||||
const TerminalTabPlan({this.id, required this.label});
|
||||
}
|
||||
|
||||
/// Every terminal tab of one working directory, and which one is showing.
|
||||
class TerminalWorkspace extends ChangeNotifier {
|
||||
final AppState app;
|
||||
final String directory;
|
||||
|
||||
final List<TerminalTab> tabs = [];
|
||||
int activeIndex = 0;
|
||||
bool _loaded = false;
|
||||
bool _disposed = false;
|
||||
|
||||
TerminalWorkspace(this.app, this.directory);
|
||||
|
||||
TerminalTab? get activeTab => tabs.isEmpty
|
||||
? null
|
||||
: tabs[activeIndex.clamp(0, tabs.length - 1)];
|
||||
|
||||
String get _connectionId => app.conn?.id ?? '';
|
||||
|
||||
/// Opens the workspace on first use: the saved tabs and the server's sessions
|
||||
/// for this directory are reconciled, then the active tab attaches. Later
|
||||
/// calls just make sure its socket is alive.
|
||||
Future<void> ensureOpen() async {
|
||||
if (_disposed) return;
|
||||
if (_loaded) {
|
||||
await activeTab?.state.ensureOpen();
|
||||
return;
|
||||
}
|
||||
_loaded = true;
|
||||
await _load();
|
||||
}
|
||||
|
||||
Future<void> _load() async {
|
||||
final saved = await _savedTabs();
|
||||
final server = await _serverTabs();
|
||||
final plans = planTabs(saved: saved?.tabs ?? const [], server: server);
|
||||
await _applyPlans(plans, activeId: saved?.activeId);
|
||||
await activeTab?.state.ensureOpen();
|
||||
}
|
||||
|
||||
/// Tabs to show, given what was saved locally and what the server holds for
|
||||
/// the directory. A saved tab whose session is gone is dropped; sessions
|
||||
/// from elsewhere (the web UI, another phone) become tabs of their own.
|
||||
static List<TerminalTabPlan> planTabs({
|
||||
required List<SavedTerminalTab> saved,
|
||||
required List<ServerTerminal>? server,
|
||||
}) {
|
||||
final plans = <TerminalTabPlan>[];
|
||||
String label() => freeLabel(plans.map((p) => p.label));
|
||||
if (server == null) {
|
||||
// The listing failed: trust what was saved, and let the attach path
|
||||
// report a dead id.
|
||||
for (final tab in saved) {
|
||||
plans.add(TerminalTabPlan(id: tab.id, label: tab.label));
|
||||
}
|
||||
if (plans.isEmpty) plans.add(TerminalTabPlan(label: freeLabel(const [])));
|
||||
return plans;
|
||||
}
|
||||
// Project-action command runners are PTYs too, but they are not the
|
||||
// person's terminal tabs.
|
||||
final sessions = [
|
||||
for (final s in server)
|
||||
if (s.interactive) s,
|
||||
];
|
||||
final byId = {for (final s in sessions) s.sessionId: s};
|
||||
final seen = <String>{};
|
||||
for (final tab in saved) {
|
||||
if (!byId.containsKey(tab.id) || !seen.add(tab.id)) continue;
|
||||
plans.add(TerminalTabPlan(id: tab.id, label: tab.label));
|
||||
}
|
||||
final rest = [
|
||||
for (final s in sessions)
|
||||
if (s.sessionId.isNotEmpty && !seen.contains(s.sessionId)) s,
|
||||
]..sort((a, b) => (a.createdAt ?? 0).compareTo(b.createdAt ?? 0));
|
||||
for (final session in rest) {
|
||||
if (!seen.add(session.sessionId)) continue;
|
||||
plans.add(TerminalTabPlan(id: session.sessionId, label: label()));
|
||||
}
|
||||
if (plans.isEmpty) plans.add(TerminalTabPlan(label: freeLabel(const [])));
|
||||
return plans;
|
||||
}
|
||||
|
||||
/// The first free "终端 N" among [labels], so closing a tab makes its number
|
||||
/// available again.
|
||||
static String freeLabel(Iterable<String> labels) {
|
||||
final used = <int>{};
|
||||
for (final label in labels) {
|
||||
final match = RegExp(r'^终端 (\d+)$').firstMatch(label.trim());
|
||||
if (match != null) used.add(int.parse(match.group(1)!));
|
||||
}
|
||||
var n = 1;
|
||||
while (used.contains(n)) {
|
||||
n++;
|
||||
}
|
||||
return '终端 $n';
|
||||
}
|
||||
|
||||
Future<SavedTerminalTabs?> _savedTabs() async {
|
||||
final connection = _connectionId;
|
||||
if (connection.isEmpty) return null;
|
||||
return app.storage.terminalTabs(connection, directory);
|
||||
}
|
||||
|
||||
/// The interactive terminals the server holds for this directory, or null
|
||||
/// when the listing failed (then the saved tabs are kept as they are).
|
||||
Future<List<ServerTerminal>?> _serverTabs() async {
|
||||
final client = app.client;
|
||||
if (client == null) return null;
|
||||
try {
|
||||
final all = await client.listTerminals(cwd: directory);
|
||||
return [
|
||||
for (final session in all)
|
||||
if (session.interactive) session,
|
||||
];
|
||||
} catch (_) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> _applyPlans(List<TerminalTabPlan> plans,
|
||||
{String? activeId}) async {
|
||||
final reuse = <String, TerminalTab>{};
|
||||
for (final tab in tabs) {
|
||||
final id = tab.state.sessionId;
|
||||
if (id != null) reuse[id] = tab;
|
||||
}
|
||||
final next = <TerminalTab>[];
|
||||
for (final plan in plans) {
|
||||
final existing = plan.id == null ? null : reuse[plan.id];
|
||||
final state = existing?.state ??
|
||||
TerminalSessionState(app, directory,
|
||||
onSessionIdChanged: _persistLater);
|
||||
if (plan.id != null) state.sessionId = plan.id;
|
||||
next.add(TerminalTab(state, plan.label));
|
||||
}
|
||||
for (final tab in tabs) {
|
||||
if (!next.any((entry) => entry.state == tab.state)) tab.state.dispose();
|
||||
}
|
||||
tabs
|
||||
..clear()
|
||||
..addAll(next);
|
||||
final match = activeId == null
|
||||
? -1
|
||||
: tabs.indexWhere((tab) => tab.state.sessionId == activeId);
|
||||
activeIndex = match >= 0 ? match : tabs.length - 1;
|
||||
notifyListeners();
|
||||
await _persist();
|
||||
}
|
||||
|
||||
void _persistLater() {
|
||||
unawaited(_persist());
|
||||
}
|
||||
|
||||
Future<void> _persist() async {
|
||||
final connection = _connectionId;
|
||||
if (connection.isEmpty || _disposed) return;
|
||||
final saved = [
|
||||
for (final tab in tabs)
|
||||
if (tab.state.sessionId case final id?)
|
||||
SavedTerminalTab(id, tab.label),
|
||||
];
|
||||
if (saved.isEmpty) {
|
||||
await app.storage.clearTerminalTabs(connection, directory);
|
||||
return;
|
||||
}
|
||||
await app.storage.saveTerminalTabs(connection, directory,
|
||||
SavedTerminalTabs(saved, activeTab?.state.sessionId));
|
||||
}
|
||||
|
||||
/// Switches tabs: the old one detaches (its shell stays on the server) and
|
||||
/// the new one attaches or is created.
|
||||
Future<void> select(int index) async {
|
||||
if (_disposed || tabs.isEmpty) return;
|
||||
index = index.clamp(0, tabs.length - 1);
|
||||
if (index == activeIndex) return;
|
||||
final previous = activeTab;
|
||||
activeIndex = index;
|
||||
notifyListeners();
|
||||
await previous?.state.detach();
|
||||
await activeTab?.state.ensureOpen();
|
||||
await _persist();
|
||||
}
|
||||
|
||||
/// Adds an empty tab and shows it; its shell is created on open.
|
||||
Future<void> addTab() async {
|
||||
if (_disposed) return;
|
||||
final previous = activeTab;
|
||||
final state = TerminalSessionState(app, directory,
|
||||
onSessionIdChanged: _persistLater);
|
||||
tabs.add(TerminalTab(state, freeLabel(tabs.map((tab) => tab.label))));
|
||||
activeIndex = tabs.length - 1;
|
||||
notifyListeners();
|
||||
await previous?.state.detach();
|
||||
await state.ensureOpen();
|
||||
await _persist();
|
||||
}
|
||||
|
||||
/// Closes the active tab on the server and in the list; when it was the last
|
||||
/// one, a fresh tab takes its place so the panel stays usable.
|
||||
Future<void> closeActive() async {
|
||||
if (_disposed || tabs.isEmpty) return;
|
||||
final closing = tabs.removeAt(activeIndex.clamp(0, tabs.length - 1));
|
||||
if (tabs.isEmpty) {
|
||||
final state = TerminalSessionState(app, directory,
|
||||
onSessionIdChanged: _persistLater);
|
||||
tabs.add(TerminalTab(state, freeLabel(const [])));
|
||||
activeIndex = 0;
|
||||
} else {
|
||||
activeIndex = activeIndex.clamp(0, tabs.length - 1);
|
||||
}
|
||||
notifyListeners();
|
||||
await closing.state.closeSession();
|
||||
closing.state.dispose();
|
||||
await activeTab?.state.ensureOpen();
|
||||
await _persist();
|
||||
}
|
||||
|
||||
/// Ends every shell and forgets the directory's tabs (an explicit
|
||||
/// disconnect, not the panel closing).
|
||||
Future<void> closeAll() async {
|
||||
final connection = _connectionId;
|
||||
for (final tab in List.of(tabs)) {
|
||||
await tab.state.closeSession();
|
||||
tab.state.dispose();
|
||||
}
|
||||
tabs.clear();
|
||||
_loaded = false;
|
||||
if (connection.isNotEmpty) {
|
||||
await app.storage.clearTerminalTabs(connection, directory);
|
||||
}
|
||||
notifyListeners();
|
||||
}
|
||||
|
||||
/// After the app returns from the background: the socket may be dead
|
||||
/// without having reported it.
|
||||
Future<void> reconnectIfNeeded() async {
|
||||
await activeTab?.state.reconnectIfNeeded();
|
||||
}
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
_disposed = true;
|
||||
for (final tab in tabs) {
|
||||
tab.state.dispose();
|
||||
}
|
||||
super.dispose();
|
||||
}
|
||||
}
|
||||
|
||||
class TerminalSessionState extends ChangeNotifier {
|
||||
final AppState app;
|
||||
final String directory;
|
||||
|
||||
/// Called when [sessionId] changes (created, replaced, cleared), so the
|
||||
/// workspace can save its tab list.
|
||||
final VoidCallback? onSessionIdChanged;
|
||||
|
||||
final Terminal model = Terminal(maxLines: 5000);
|
||||
|
||||
TerminalSocket? _socket;
|
||||
@@ -34,7 +304,7 @@ class TerminalSessionState extends ChangeNotifier {
|
||||
bool _disposed = false;
|
||||
bool _recovering = false;
|
||||
|
||||
TerminalSessionState(this.app, this.directory) {
|
||||
TerminalSessionState(this.app, this.directory, {this.onSessionIdChanged}) {
|
||||
model.onOutput = _onOutput;
|
||||
model.onResize = (cols, rows, _, __) {
|
||||
_cols = cols;
|
||||
@@ -43,6 +313,31 @@ class TerminalSessionState extends ChangeNotifier {
|
||||
};
|
||||
}
|
||||
|
||||
bool get isOpen => link == TerminalLinkState.open;
|
||||
bool get isRunning =>
|
||||
link == TerminalLinkState.open || link == TerminalLinkState.connecting;
|
||||
|
||||
/// Attaches to the tab's session, or creates one when the tab has none yet.
|
||||
Future<void> ensureOpen() async {
|
||||
if (_disposed) return;
|
||||
if (!_opened) {
|
||||
_opened = true;
|
||||
if (sessionId == null) {
|
||||
await _create();
|
||||
} else {
|
||||
await _attach();
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (_socket == null && link != TerminalLinkState.exited) await _attach();
|
||||
}
|
||||
|
||||
/// Drops the socket without ending the shell; [ensureOpen] attaches again.
|
||||
Future<void> detach() async {
|
||||
await _socket?.dispose();
|
||||
_socket = null;
|
||||
}
|
||||
|
||||
void toggleCtrl() {
|
||||
ctrl = !ctrl;
|
||||
notifyListeners();
|
||||
@@ -89,69 +384,6 @@ class TerminalSessionState extends ChangeNotifier {
|
||||
}
|
||||
}
|
||||
|
||||
bool get isOpen => link == TerminalLinkState.open;
|
||||
bool get isRunning =>
|
||||
link == TerminalLinkState.open || link == TerminalLinkState.connecting;
|
||||
|
||||
/// Opens the terminal on first use; later calls just make sure the socket is
|
||||
/// alive. Unless [fresh] is set, the previous session for this directory is
|
||||
/// picked up again when the server still holds it (the app may have been
|
||||
/// restarted since), so the same shell — and its history — comes back.
|
||||
Future<void> ensureOpen({bool fresh = false}) async {
|
||||
if (_disposed) return;
|
||||
if (_opened) {
|
||||
if (_socket == null && link != TerminalLinkState.exited) await _attach();
|
||||
return;
|
||||
}
|
||||
_opened = true;
|
||||
await _open(fresh: fresh);
|
||||
}
|
||||
|
||||
Future<void> _open({required bool fresh}) async {
|
||||
final client = app.client;
|
||||
if (client == null) return;
|
||||
_set(TerminalLinkState.creating);
|
||||
if (!fresh && await _restore()) return;
|
||||
await _create();
|
||||
}
|
||||
|
||||
/// The session this panel should reattach to: the one remembered for the
|
||||
/// directory while the server still lists it, else the newest running one,
|
||||
/// else the newest one. Null means the server holds nothing for this
|
||||
/// directory and a session has to be created.
|
||||
static String? restoreCandidate(
|
||||
String? saved, List<ServerTerminal> sessions) {
|
||||
if (sessions.isEmpty) return null;
|
||||
if (saved != null && sessions.any((s) => s.sessionId == saved)) {
|
||||
return saved;
|
||||
}
|
||||
final running = sessions.where((s) => s.status == 'running').toList();
|
||||
final pool = running.isNotEmpty ? running : sessions;
|
||||
pool.sort((a, b) => (b.createdAt ?? 0).compareTo(a.createdAt ?? 0));
|
||||
final id = pool.first.sessionId;
|
||||
return id.isEmpty ? null : id;
|
||||
}
|
||||
|
||||
Future<bool> _restore() async {
|
||||
final client = app.client;
|
||||
if (client == null) return false;
|
||||
final saved = await _savedId();
|
||||
final List<ServerTerminal> sessions;
|
||||
try {
|
||||
sessions = await client.listTerminals(cwd: directory);
|
||||
} catch (_) {
|
||||
// Let the create path report the failure; a listing error here should
|
||||
// not be what the status bar shows.
|
||||
return false;
|
||||
}
|
||||
final id = restoreCandidate(saved, sessions);
|
||||
if (_disposed || id == null) return false;
|
||||
sessionId = id;
|
||||
await _remember(id);
|
||||
await _attach();
|
||||
return true;
|
||||
}
|
||||
|
||||
Future<void> _create() async {
|
||||
final client = app.client;
|
||||
if (client == null) return;
|
||||
@@ -163,35 +395,13 @@ class TerminalSessionState extends ChangeNotifier {
|
||||
sessionId = info.sessionId;
|
||||
_cols = info.cols;
|
||||
_rows = info.rows;
|
||||
await _remember(info.sessionId);
|
||||
onSessionIdChanged?.call();
|
||||
await _attach();
|
||||
} catch (error) {
|
||||
_set(TerminalLinkState.error, detail: _message(error));
|
||||
}
|
||||
}
|
||||
|
||||
/// The connection a saved terminal id belongs to. A different saved server
|
||||
/// has its own ids, and adopting one across servers would point at nothing.
|
||||
String get _connectionId => app.conn?.id ?? '';
|
||||
|
||||
Future<String?> _savedId() async {
|
||||
final id = _connectionId;
|
||||
if (id.isEmpty) return null;
|
||||
return app.storage.terminalSession(id, directory);
|
||||
}
|
||||
|
||||
Future<void> _remember(String id) async {
|
||||
final connection = _connectionId;
|
||||
if (connection.isEmpty) return;
|
||||
await app.storage.saveTerminalSession(connection, directory, id);
|
||||
}
|
||||
|
||||
Future<void> _forget() async {
|
||||
final connection = _connectionId;
|
||||
if (connection.isEmpty) return;
|
||||
await app.storage.clearTerminalSession(connection, directory);
|
||||
}
|
||||
|
||||
Future<void> _attach() async {
|
||||
final client = app.client;
|
||||
final id = sessionId;
|
||||
@@ -305,8 +515,7 @@ class TerminalSessionState extends ChangeNotifier {
|
||||
if (_socket == null) await _attach();
|
||||
}
|
||||
|
||||
/// Ends the shell on the server and drops the socket; the next
|
||||
/// [ensureOpen] starts a fresh session.
|
||||
/// Ends the shell on the server and drops the socket.
|
||||
Future<void> closeSession() async {
|
||||
final client = app.client;
|
||||
final id = sessionId;
|
||||
@@ -314,7 +523,7 @@ class TerminalSessionState extends ChangeNotifier {
|
||||
_opened = false;
|
||||
link = TerminalLinkState.idle;
|
||||
detail = null;
|
||||
await _forget();
|
||||
onSessionIdChanged?.call();
|
||||
await _socket?.dispose();
|
||||
_socket = null;
|
||||
if (!_disposed) notifyListeners();
|
||||
@@ -326,13 +535,13 @@ class TerminalSessionState extends ChangeNotifier {
|
||||
}
|
||||
|
||||
/// Drops a session the server no longer has and opens another one in its
|
||||
/// place, so a stale remembered id does not leave the panel unusable.
|
||||
/// place, so a stale id does not leave the tab unusable.
|
||||
Future<void> _recoverMissing() async {
|
||||
if (_recovering || _disposed) return;
|
||||
_recovering = true;
|
||||
try {
|
||||
sessionId = null;
|
||||
await _forget();
|
||||
onSessionIdChanged?.call();
|
||||
await _socket?.dispose();
|
||||
_socket = null;
|
||||
if (_disposed) return;
|
||||
|
||||
Reference in new issue
Block a user