250 lines
7.0 KiB
Dart
250 lines
7.0 KiB
Dart
import 'dart:async';
|
|
import 'dart:convert';
|
|
|
|
import 'package:flutter/foundation.dart';
|
|
|
|
import '../../core/api_gateway.dart';
|
|
import '../chat/shell/chat_shell_run.dart';
|
|
import '../chat/shell/chat_shell_terminal_session.dart';
|
|
import '../chat/shell/chat_shell_terminals.dart';
|
|
import 'terminal_info.dart';
|
|
import 'terminal_stream.dart';
|
|
|
|
/// One open machine terminal in the app: its record, the output held for
|
|
/// redraws, and the emulator session the panel, window and page draw (the
|
|
/// chat shell's own, so typing, links and colours behave the same).
|
|
///
|
|
/// It outlives every view: hiding the panel keeps it, and reconnecting
|
|
/// resumes its output from the last byte it holds.
|
|
class TerminalTab extends ChangeNotifier {
|
|
TerminalTab({
|
|
required this.machineId,
|
|
required this.machineName,
|
|
required this._gateway,
|
|
required this._info,
|
|
}) {
|
|
session = ChatShellTerminalSession(
|
|
_run(),
|
|
onInput: _input,
|
|
onResize: _resized,
|
|
);
|
|
session.terminal.onTitleChange = _titled;
|
|
}
|
|
|
|
final String machineId;
|
|
String machineName;
|
|
ApiGateway _gateway;
|
|
TerminalInfo _info;
|
|
late final ChatShellTerminalSession session;
|
|
final TerminalStream _stream = TerminalStream();
|
|
ChatShellInputPipe? _pipe;
|
|
Timer? _resize;
|
|
(int, int)? _sentSize;
|
|
String _oscTitle = '';
|
|
bool _disposed = false;
|
|
bool _reading = false;
|
|
bool _again = false;
|
|
|
|
/// False while the terminal's machine is not connected.
|
|
bool connected = true;
|
|
|
|
/// The last refusal of input, a resize or a read, in the server's words.
|
|
String? error;
|
|
|
|
String get key => terminalKey(machineId, _info.id);
|
|
TerminalInfo get info => _info;
|
|
ApiGateway get gateway => _gateway;
|
|
|
|
/// The window title the shell set (seen in its output or recorded by the
|
|
/// server), else the folder it started in.
|
|
String get title {
|
|
if (_oscTitle.isNotEmpty) return _oscTitle;
|
|
if (_info.title.isNotEmpty) return _info.title;
|
|
return terminalFolderLabel(_info.cwd);
|
|
}
|
|
|
|
ChatShellRun _run() => ChatShellRun(
|
|
id: _info.id,
|
|
command: title,
|
|
directory: _info.cwd,
|
|
status: _info.running ? 'running' : 'exited',
|
|
startedAt: _info.createdAt,
|
|
output: _stream.text,
|
|
outputStart: _stream.start,
|
|
outputEnd: _stream.end,
|
|
terminal: true,
|
|
cols: _info.cols,
|
|
rows: _info.rows,
|
|
);
|
|
|
|
/// The machine connected again (or for the first time): requests go
|
|
/// through [gateway] and the output resumes from the held end.
|
|
void attach(ApiGateway gateway, TerminalInfo info) {
|
|
_gateway = gateway;
|
|
connected = true;
|
|
_sentSize = null;
|
|
_update(info);
|
|
unawaited(resume());
|
|
}
|
|
|
|
void disconnected() {
|
|
connected = false;
|
|
_pipe = null;
|
|
_notify();
|
|
}
|
|
|
|
/// Reads what the server retains after the held end (all of it on a new
|
|
/// stream or after a gap) and subscribes this connection to the rest.
|
|
Future<void> resume() async {
|
|
if (_disposed) return;
|
|
if (_reading) {
|
|
_again = true;
|
|
return;
|
|
}
|
|
_reading = true;
|
|
try {
|
|
do {
|
|
_again = false;
|
|
final same = !_stream.empty && _info.stream == _stream.stream;
|
|
await _read(same ? _stream.end : null);
|
|
} while (_again && !_disposed);
|
|
error = null;
|
|
} catch (failure) {
|
|
error = '$failure';
|
|
} finally {
|
|
_reading = false;
|
|
_notify();
|
|
}
|
|
}
|
|
|
|
Future<void> _read(int? after) async {
|
|
final reply = await _gateway.call('terminal_output', {
|
|
'terminal_request': {'terminal_id': _info.id, 'after': ?after},
|
|
});
|
|
final record = reply['terminal'];
|
|
if (_disposed || record is! Map) return;
|
|
final info = TerminalInfo.fromJson(record);
|
|
_info = info;
|
|
if (after != null && info.stream != _stream.stream) {
|
|
// The server restarted since: its stream starts again at zero.
|
|
return _read(null);
|
|
}
|
|
final output = '${record['output'] ?? ''}';
|
|
final start = (record['output_start'] as num?)?.toInt() ?? 0;
|
|
if (after == null || start > _stream.end) {
|
|
_stream.reset(output, start, info.stream);
|
|
session.replay(_run());
|
|
} else {
|
|
_append(output, start, start + _byteLength(output));
|
|
}
|
|
if (!info.running) session.finish(_run());
|
|
}
|
|
|
|
/// One pushed `terminal_event` for this terminal.
|
|
void frame(Map event) {
|
|
final record = event['terminal'];
|
|
if (record is Map) {
|
|
_update(TerminalInfo.fromJson(record));
|
|
return;
|
|
}
|
|
final output = '${event['output'] ?? ''}';
|
|
final offset = (event['offset'] as num?)?.toInt() ?? 0;
|
|
final end = (event['end'] as num?)?.toInt() ?? 0;
|
|
_append(output, offset, end);
|
|
}
|
|
|
|
void _append(String output, int offset, int end) {
|
|
final before = _stream.end;
|
|
final fresh = _stream.add(output, offset, end);
|
|
if (fresh == null) {
|
|
// Frames were missed: read the retained tail again.
|
|
unawaited(resume());
|
|
return;
|
|
}
|
|
if (fresh.isNotEmpty) session.append(_run(), fresh, before, end);
|
|
}
|
|
|
|
void _update(TerminalInfo info) {
|
|
final ended = _info.running && !info.running;
|
|
// A lifecycle record carries no stream; keep the one the output has.
|
|
_info = info.stream.isEmpty ? info.withStream(_stream.stream) : info;
|
|
if (ended) {
|
|
_resize?.cancel();
|
|
_pipe = null;
|
|
session.finish(_run());
|
|
}
|
|
_notify();
|
|
}
|
|
|
|
void _titled(String title) {
|
|
if (title == _oscTitle) return;
|
|
_oscTitle = title.trim();
|
|
_notify();
|
|
}
|
|
|
|
void _input(String data) {
|
|
if (_disposed || !connected) return;
|
|
final id = _info.id;
|
|
final gateway = _gateway;
|
|
(_pipe ??= ChatShellInputPipe(
|
|
(data) => gateway.call('terminal_input', {
|
|
'terminal_request': {'terminal_id': id, 'data': data},
|
|
}),
|
|
(failure) {
|
|
error = '$failure';
|
|
_notify();
|
|
},
|
|
)).add(data);
|
|
}
|
|
|
|
void _resized(int cols, int rows) {
|
|
if (_disposed || !_info.running || !connected) return;
|
|
_resize?.cancel();
|
|
_resize = Timer(chatShellResizeDelay, () {
|
|
if (_sentSize == (cols, rows) || !connected) return;
|
|
_sentSize = (cols, rows);
|
|
_gateway
|
|
.call('terminal_resize', {
|
|
'terminal_request': {
|
|
'terminal_id': _info.id,
|
|
'cols': cols,
|
|
'rows': rows,
|
|
},
|
|
})
|
|
.catchError((Object failure) {
|
|
error = '$failure';
|
|
_notify();
|
|
return <String, dynamic>{};
|
|
});
|
|
});
|
|
}
|
|
|
|
void _notify() {
|
|
if (!_disposed) notifyListeners();
|
|
}
|
|
|
|
@override
|
|
void dispose() {
|
|
_disposed = true;
|
|
_resize?.cancel();
|
|
_pipe = null;
|
|
session.terminal.onTitleChange = null;
|
|
super.dispose();
|
|
}
|
|
}
|
|
|
|
String terminalKey(String machineId, String terminalId) =>
|
|
'$machineId/$terminalId';
|
|
|
|
/// The last folder of [cwd] ("~" for a home directory), for a tab title.
|
|
String terminalFolderLabel(String cwd) {
|
|
final parts = cwd.split('/').where((part) => part.isNotEmpty).toList();
|
|
if (parts.isEmpty) return '/';
|
|
if (parts.length == 2 && (parts[0] == 'Users' || parts[0] == 'home')) {
|
|
return '~';
|
|
}
|
|
return parts.last;
|
|
}
|
|
|
|
int _byteLength(String text) => utf8.encode(text).length;
|