Add the app's terminal surface: bottom panel, floating window and full-screen page
This commit is contained in:
@@ -0,0 +1,57 @@
|
||||
import 'package:flutter/widgets.dart';
|
||||
|
||||
import '../core/api_gateway.dart';
|
||||
import '../core/servers/chat/chat_server_pool.dart';
|
||||
import '../features/terminal/terminal_hub.dart';
|
||||
import '../features/terminal/terminal_layout.dart';
|
||||
import '../features/terminal/terminal_machines.dart';
|
||||
import '../features/terminal/terminal_surface.dart';
|
||||
import '../features/terminal/terminal_toggle_button.dart';
|
||||
|
||||
/// The app's machine terminals: one hub over every connected machine (the
|
||||
/// chat pool's, else the app's own server), kept for the app's lifetime so
|
||||
/// shells and their output survive navigation and hidden panels.
|
||||
class AppTerminals {
|
||||
AppTerminals({
|
||||
required ChatServerPool? pool,
|
||||
required Listenable connection,
|
||||
required bool Function() connected,
|
||||
required ApiGateway gateway,
|
||||
required String machineId,
|
||||
required String machineName,
|
||||
required this.layout,
|
||||
}) : machines = pool != null
|
||||
? PoolTerminalMachines(pool)
|
||||
: SingleTerminalMachines(
|
||||
connection: connection,
|
||||
connected: connected,
|
||||
machine: TerminalMachine(
|
||||
id: machineId,
|
||||
name: machineName,
|
||||
gateway: gateway,
|
||||
),
|
||||
) {
|
||||
hub = TerminalHub(machines);
|
||||
}
|
||||
|
||||
final ValueNotifier<List<TerminalMachine>> machines;
|
||||
final TerminalLayout layout;
|
||||
late final TerminalHub hub;
|
||||
|
||||
/// [shell] with the terminal panel, window or page around it.
|
||||
Widget surround(Widget shell, {required bool cupertino}) => TerminalSurface(
|
||||
hub: hub,
|
||||
layout: layout,
|
||||
cupertino: cupertino,
|
||||
child: shell,
|
||||
);
|
||||
|
||||
/// The bar button showing or hiding the terminal.
|
||||
Widget toggle({required bool cupertino}) =>
|
||||
TerminalToggleButton(layout: layout, cupertino: cupertino);
|
||||
|
||||
void dispose() {
|
||||
hub.dispose();
|
||||
machines.dispose();
|
||||
}
|
||||
}
|
||||
@@ -1,3 +1,4 @@
|
||||
import '../features/terminal/terminal_layout.dart';
|
||||
import '../core/session/server_session.dart';
|
||||
import '../ui/scale/ui_scale.dart';
|
||||
import 'package:flutter/foundation.dart';
|
||||
@@ -60,6 +61,7 @@ Future<void> runPipelinesApp({
|
||||
// not hold the first frame, and applies when it lands.
|
||||
final animationSpeed = AnimationSpeedController.instance.restore();
|
||||
final uiScale = UiScaleController.instance.restore();
|
||||
final terminalLayout = TerminalLayout.instance.restore();
|
||||
final quickSwitchAnimation = QuickSwitchAnimationController.instance
|
||||
.restore();
|
||||
final font = AppFontController.instance.restore(wait: appFontStartupWait);
|
||||
@@ -68,6 +70,7 @@ Future<void> runPipelinesApp({
|
||||
await font;
|
||||
await animationSpeed;
|
||||
await uiScale;
|
||||
await terminalLayout;
|
||||
await quickSwitchAnimation;
|
||||
final server = await resolveLaunchServer(
|
||||
base: base,
|
||||
|
||||
@@ -32,6 +32,8 @@ import '../features/updates/launch_update_dialog.dart';
|
||||
import '../features/updates/web_release.dart';
|
||||
import '../features/settings/server_connections.dart';
|
||||
import 'app.dart';
|
||||
import 'app_terminals.dart';
|
||||
import '../features/terminal/terminal_layout.dart';
|
||||
import 'app_route.dart';
|
||||
import 'app_router.dart';
|
||||
import 'app_session.dart';
|
||||
@@ -82,9 +84,13 @@ class PipelinesApp extends StatefulWidget {
|
||||
this.androidInstaller = downloadAndInstall,
|
||||
this.webRefresher = refreshWebPage,
|
||||
this.tabLocationsStore,
|
||||
this.terminalLayout,
|
||||
});
|
||||
|
||||
final TabLocationsStore? tabLocationsStore;
|
||||
|
||||
/// The terminal surface's saved layout; null is the device's own.
|
||||
final TerminalLayout? terminalLayout;
|
||||
final ServerEndpoint server;
|
||||
final PipelinesClient? client;
|
||||
final bool? cupertino;
|
||||
@@ -195,6 +201,7 @@ class _PipelinesAppState extends State<PipelinesApp>
|
||||
},
|
||||
);
|
||||
NotificationServiceHandoff? _deliveryHandoff;
|
||||
late final AppTerminals _terminals;
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
@@ -213,6 +220,18 @@ class _PipelinesAppState extends State<PipelinesApp>
|
||||
serverId: widget.serverId,
|
||||
);
|
||||
bindServerIdentity(_session.gateway, widget.serverId);
|
||||
_terminals = AppTerminals(
|
||||
pool: widget.chatPool,
|
||||
connection: _session,
|
||||
connected: () => _session.connected,
|
||||
gateway: _session.gateway,
|
||||
machineId: widget.serverId ?? 'server',
|
||||
machineName:
|
||||
widget.servers?.catalog.active?.name ??
|
||||
widget.server.uri?.host ??
|
||||
'This server',
|
||||
layout: widget.terminalLayout ?? TerminalLayout.instance,
|
||||
);
|
||||
_ownsProvider = widget.routeInformationProvider == null;
|
||||
_provider =
|
||||
widget.routeInformationProvider ??
|
||||
@@ -421,6 +440,7 @@ class _PipelinesAppState extends State<PipelinesApp>
|
||||
if (_ownsProvider) {
|
||||
(_provider as PlatformRouteInformationProvider).dispose();
|
||||
}
|
||||
_terminals.dispose();
|
||||
_session.dispose();
|
||||
super.dispose();
|
||||
}
|
||||
@@ -697,7 +717,8 @@ class _PipelinesAppState extends State<PipelinesApp>
|
||||
Widget _buildShell(BuildContext context, AppRoute route) =>
|
||||
ValueListenableBuilder<int>(
|
||||
valueListenable: _attentionCount,
|
||||
builder: (context, count, _) => _shellFor(route, count),
|
||||
builder: (context, count, _) =>
|
||||
_terminals.surround(_shellFor(route, count), cupertino: _cupertino),
|
||||
);
|
||||
|
||||
Widget _shellFor(AppRoute route, int attentionCount) {
|
||||
@@ -715,6 +736,7 @@ class _PipelinesAppState extends State<PipelinesApp>
|
||||
final runsRoute = tab(AppDestination.runs);
|
||||
final chatRoute = tab(AppDestination.chat);
|
||||
return AdaptiveShell(
|
||||
barActions: [_terminals.toggle(cupertino: _cupertino)],
|
||||
attentionCount: attentionCount,
|
||||
cupertino: _cupertino,
|
||||
destination: _destinationOf(route.kind),
|
||||
@@ -803,6 +825,7 @@ class _PipelinesAppState extends State<PipelinesApp>
|
||||
// Settings is a page of the Pipelines tab (its bar's gear), not a
|
||||
// tab; the shell shows it with Back to Pipelines.
|
||||
AppDestination.settings: (_) => SettingsScreen(
|
||||
terminalLayout: _terminals.layout,
|
||||
navigationScope: _navigationScope,
|
||||
client: _session.client,
|
||||
// A phone signs in at the web login; a browser has its own.
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import '../../terminal/terminal_open_action.dart';
|
||||
import 'dart:async';
|
||||
|
||||
import 'package:flutter/cupertino.dart';
|
||||
@@ -1407,6 +1408,15 @@ class _ChatThreadViewState extends State<ChatThreadView> {
|
||||
?widget.sidebarControl,
|
||||
...widget.paneControls,
|
||||
chatShellRunMenuAction(onPressed: _runShellFromMenu),
|
||||
?terminalOpenMenuAction(
|
||||
context,
|
||||
gateway: widget.gateway,
|
||||
directory: directory,
|
||||
onRefused: (refusal) => _showCommandNotice(
|
||||
"Couldn't open a terminal: $refusal",
|
||||
failed: true,
|
||||
),
|
||||
),
|
||||
],
|
||||
controls: [
|
||||
if (hasModel)
|
||||
|
||||
@@ -14,6 +14,8 @@ import 'files_upload_notice.dart';
|
||||
import 'files_viewer.dart';
|
||||
import 'files_header.dart';
|
||||
import '../../../ui/layout/app_overflow_menu.dart';
|
||||
import '../../terminal/terminal_open_action.dart';
|
||||
import '../../terminal/terminal_scope.dart';
|
||||
|
||||
const double filesPanelMinWidth = 280;
|
||||
const double filesPanelMaxWidth = 420;
|
||||
@@ -23,8 +25,9 @@ double filesPanelWidth(double available) => (available * filesPanelFraction)
|
||||
.clamp(filesPanelMinWidth, filesPanelMaxWidth);
|
||||
|
||||
/// The actions of an entry's row or tile menu. Open and Download are for
|
||||
/// files; Rename, Move and Delete apply to files and folders alike.
|
||||
enum FileAction { open, download, rename, move, delete }
|
||||
/// files, Open in terminal for folders (where the app has a terminal);
|
||||
/// Rename, Move and Delete apply to files and folders alike.
|
||||
enum FileAction { open, download, terminal, rename, move, delete }
|
||||
|
||||
class FilesPanel extends StatefulWidget {
|
||||
const FilesPanel({
|
||||
@@ -180,6 +183,12 @@ class _FilesPanelState extends State<FilesPanel> {
|
||||
endpoint: _endpoint,
|
||||
entry: entry,
|
||||
),
|
||||
// A refusal shows in the terminal the surface opens.
|
||||
FileAction.terminal => openInTerminal(
|
||||
context,
|
||||
controller.gateway,
|
||||
entry.path,
|
||||
),
|
||||
FileAction.rename => renameEntry(context, controller, entry),
|
||||
FileAction.move => moveEntry(context, controller, entry),
|
||||
FileAction.delete => deleteEntry(context, controller, entry),
|
||||
@@ -189,6 +198,11 @@ class _FilesPanelState extends State<FilesPanel> {
|
||||
AppMenuAction(value: FileAction.open, label: 'Open'),
|
||||
AppMenuAction(value: FileAction.download, label: 'Download'),
|
||||
],
|
||||
if (entry.isDir && TerminalScope.maybeOf(context) != null)
|
||||
const AppMenuAction(
|
||||
value: FileAction.terminal,
|
||||
label: terminalOpenActionLabel,
|
||||
),
|
||||
const AppMenuAction(value: FileAction.rename, label: 'Rename…'),
|
||||
const AppMenuAction(value: FileAction.move, label: 'Move…'),
|
||||
const AppMenuAction(
|
||||
|
||||
@@ -28,7 +28,7 @@ class ChatShellTerminals {
|
||||
final void Function(String runId, Object error) onError;
|
||||
|
||||
final Map<String, ChatShellTerminalSession> _sessions = {};
|
||||
final Map<String, _InputPipe> _inputs = {};
|
||||
final Map<String, ChatShellInputPipe> _inputs = {};
|
||||
final Map<String, Timer> _resizes = {};
|
||||
final Map<String, (int, int)> _sentSizes = {};
|
||||
bool _disposed = false;
|
||||
@@ -66,7 +66,7 @@ class ChatShellTerminals {
|
||||
_inputs
|
||||
.putIfAbsent(
|
||||
runId,
|
||||
() => _InputPipe(
|
||||
() => ChatShellInputPipe(
|
||||
(data) => _repository.input(_sessionId, runId, data),
|
||||
(error) => onError(runId, error),
|
||||
),
|
||||
@@ -98,11 +98,12 @@ class ChatShellTerminals {
|
||||
}
|
||||
}
|
||||
|
||||
/// One run's typed input on its way to the server, in order: what arrives
|
||||
/// One terminal's typed input on its way to the server (a chat run's or a
|
||||
/// machine terminal's), in order: what arrives
|
||||
/// while a request is in flight goes in the next one. Nothing is kept once
|
||||
/// sent, and a refusal discards what was waiting rather than retyping it.
|
||||
class _InputPipe {
|
||||
_InputPipe(this._send, this._failed);
|
||||
class ChatShellInputPipe {
|
||||
ChatShellInputPipe(this._send, this._failed);
|
||||
|
||||
final Future<void> Function(String data) _send;
|
||||
final void Function(Object error) _failed;
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
import '../terminal/terminal_layout.dart';
|
||||
import 'settings_terminal_section.dart';
|
||||
import '../../ui/adaptive/segmented_bar.dart';
|
||||
import 'dart:async';
|
||||
|
||||
@@ -66,12 +68,17 @@ class SettingsScreen extends StatefulWidget {
|
||||
this.deliveryServiceController,
|
||||
this.fonts,
|
||||
this.animationSpeed,
|
||||
this.terminalLayout,
|
||||
});
|
||||
|
||||
/// The device's interface font; defaults to the app's shared controller.
|
||||
final AppFontController? fonts;
|
||||
final AnimationSpeedController? animationSpeed;
|
||||
|
||||
/// The terminal surface's layout (its mode is chosen here); null is the
|
||||
/// device's own.
|
||||
final TerminalLayout? terminalLayout;
|
||||
|
||||
/// Android background delivery; hidden when absent or unsupported.
|
||||
final NotificationServiceBridge? deliveryService;
|
||||
final NotificationServiceController? deliveryServiceController;
|
||||
|
||||
@@ -0,0 +1,85 @@
|
||||
import 'package:flutter/cupertino.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
import '../terminal/terminal_layout.dart';
|
||||
import 'settings_group.dart';
|
||||
import 'settings_theme.dart';
|
||||
|
||||
/// Appearance → Terminal: whether the terminal docks at the bottom of the
|
||||
/// window or floats over it (Ctrl+` shows and hides it either way).
|
||||
class SettingsTerminalSection extends StatelessWidget {
|
||||
const SettingsTerminalSection({super.key, required this.layout});
|
||||
|
||||
final TerminalLayout layout;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) => ListenableBuilder(
|
||||
listenable: layout,
|
||||
builder: (context, _) {
|
||||
final cupertino = usesCupertinoControls(context);
|
||||
final Widget choice = cupertino
|
||||
? CupertinoSlidingSegmentedControl<TerminalMode>(
|
||||
groupValue: layout.mode,
|
||||
children: {
|
||||
for (final mode in TerminalMode.values)
|
||||
mode: Padding(
|
||||
key: ValueKey('settings-terminal-${mode.name}'),
|
||||
padding: const EdgeInsets.symmetric(horizontal: 8),
|
||||
child: Text(mode.label),
|
||||
),
|
||||
},
|
||||
onValueChanged: (mode) {
|
||||
if (mode != null) layout.setMode(mode);
|
||||
},
|
||||
)
|
||||
: SegmentedButton<TerminalMode>(
|
||||
segments: [
|
||||
for (final mode in TerminalMode.values)
|
||||
ButtonSegment(
|
||||
value: mode,
|
||||
label: Text(
|
||||
mode.label,
|
||||
key: ValueKey('settings-terminal-${mode.name}'),
|
||||
),
|
||||
icon: Icon(
|
||||
mode == TerminalMode.panel
|
||||
? Icons.vertical_split_outlined
|
||||
: Icons.picture_in_picture_alt_outlined,
|
||||
),
|
||||
),
|
||||
],
|
||||
selected: {layout.mode},
|
||||
onSelectionChanged: (modes) => layout.setMode(modes.first),
|
||||
);
|
||||
return SettingsGroup(
|
||||
title: 'Terminal',
|
||||
footer: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||
children: [
|
||||
const Text(
|
||||
'Saved on this device. Ctrl+` shows or hides the terminal; on '
|
||||
'a narrow window it opens full screen. Shells keep running '
|
||||
'while it is hidden.',
|
||||
),
|
||||
if (layout.saveFailed)
|
||||
Text(
|
||||
'Could not save; applies until reload.',
|
||||
style: TextStyle(color: settingsErrorColor(context)),
|
||||
),
|
||||
],
|
||||
),
|
||||
children: [
|
||||
SettingsGroupItem(
|
||||
child: Semantics(
|
||||
label: 'Terminal placement',
|
||||
child: Align(
|
||||
alignment: AlignmentDirectional.centerStart,
|
||||
child: choice,
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
);
|
||||
},
|
||||
);
|
||||
}
|
||||
@@ -14,6 +14,9 @@ extension _SettingsTopicPages on _SettingsScreenState {
|
||||
SettingsFontSection(
|
||||
controller: widget.fonts ?? AppFontController.instance,
|
||||
),
|
||||
SettingsTerminalSection(
|
||||
layout: widget.terminalLayout ?? TerminalLayout.instance,
|
||||
),
|
||||
],
|
||||
),
|
||||
SettingsTopic.connection: (_) => SettingsPageBody(
|
||||
|
||||
@@ -0,0 +1,126 @@
|
||||
import 'dart:async';
|
||||
|
||||
import 'package:flutter/cupertino.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
import '../chat/shell/chat_shell_terminal_keys.dart';
|
||||
import '../chat/shell/chat_shell_terminal_view.dart';
|
||||
import 'terminal_hub.dart';
|
||||
import 'terminal_tab.dart';
|
||||
|
||||
/// The selected terminal: its emulator (focused when shown), what the
|
||||
/// operator should know about it (ended, machine offline, ends with the
|
||||
/// server) and, with [keys], the touch key toolbar.
|
||||
class TerminalBody extends StatelessWidget {
|
||||
const TerminalBody({
|
||||
super.key,
|
||||
required this.hub,
|
||||
required this.cupertino,
|
||||
this.keys = false,
|
||||
});
|
||||
|
||||
final TerminalHub hub;
|
||||
final bool cupertino;
|
||||
final bool keys;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final tab = hub.selected;
|
||||
if (tab == null) return _empty(context);
|
||||
final notes = <String>[
|
||||
if (!tab.connected)
|
||||
'${tab.machineName} is not connected; the terminal resumes when it is.'
|
||||
else if (!tab.info.running)
|
||||
tab.info.endedText
|
||||
else if (!tab.info.persistent)
|
||||
'This shell ends if the server on ${tab.machineName} restarts '
|
||||
'(tmux is not installed there).',
|
||||
?tab.error,
|
||||
?hub.error,
|
||||
];
|
||||
return Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||
children: [
|
||||
Expanded(
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.fromLTRB(8, 0, 8, 8),
|
||||
child: ChatShellTerminalView(
|
||||
key: ValueKey('terminal-view-${tab.key}'),
|
||||
session: tab.session,
|
||||
cupertino: cupertino,
|
||||
fill: true,
|
||||
autofocus: true,
|
||||
),
|
||||
),
|
||||
),
|
||||
for (final note in notes)
|
||||
Padding(
|
||||
padding: const EdgeInsets.fromLTRB(12, 0, 12, 8),
|
||||
child: Text(note, style: _noteStyle(context)),
|
||||
),
|
||||
if (keys && tab.session.live && tab.connected)
|
||||
Padding(
|
||||
padding: const EdgeInsets.fromLTRB(8, 0, 8, 8),
|
||||
child: ChatShellTerminalKeys(
|
||||
session: tab.session,
|
||||
cupertino: cupertino,
|
||||
field: chatShellTouchFirst(),
|
||||
),
|
||||
),
|
||||
if (!tab.info.running && tab.connected) _closeEnded(tab),
|
||||
],
|
||||
);
|
||||
}
|
||||
|
||||
TextStyle? _noteStyle(BuildContext context) => cupertino
|
||||
? CupertinoTheme.of(context).textTheme.textStyle.copyWith(
|
||||
color: CupertinoColors.secondaryLabel.resolveFrom(context),
|
||||
)
|
||||
: Theme.of(context).textTheme.bodySmall?.copyWith(
|
||||
color: Theme.of(context).colorScheme.onSurfaceVariant,
|
||||
);
|
||||
|
||||
Widget _closeEnded(TerminalTab tab) {
|
||||
void close() => unawaited(hub.close(tab));
|
||||
return Padding(
|
||||
padding: const EdgeInsets.fromLTRB(8, 0, 8, 8),
|
||||
child: Align(
|
||||
alignment: AlignmentDirectional.centerStart,
|
||||
child: cupertino
|
||||
? CupertinoButton(onPressed: close, child: const Text('Close tab'))
|
||||
: TextButton(onPressed: close, child: const Text('Close tab')),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Widget _empty(BuildContext context) {
|
||||
final machines = hub.connected;
|
||||
final text = machines.isEmpty
|
||||
? 'No machine is connected.'
|
||||
: 'No terminals are open.';
|
||||
void open() => unawaited(hub.open());
|
||||
return Center(
|
||||
child: Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
Text(text, style: _noteStyle(context)),
|
||||
if (hub.error case final error?)
|
||||
Padding(
|
||||
padding: const EdgeInsets.all(8),
|
||||
child: Text(error, style: _noteStyle(context)),
|
||||
),
|
||||
if (machines.isNotEmpty)
|
||||
cupertino
|
||||
? CupertinoButton(
|
||||
onPressed: open,
|
||||
child: const Text('New terminal'),
|
||||
)
|
||||
: FilledButton.tonal(
|
||||
onPressed: open,
|
||||
child: const Text('New terminal'),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,226 @@
|
||||
import 'dart:async';
|
||||
|
||||
import 'package:flutter/cupertino.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
import 'terminal_body.dart';
|
||||
import 'terminal_hub.dart';
|
||||
import 'terminal_layout.dart';
|
||||
import 'terminal_tab_strip.dart';
|
||||
|
||||
/// Margin a maximised window keeps from the edges of the app.
|
||||
const double terminalFloatMargin = 8;
|
||||
|
||||
/// [rect] moved and shrunk to fit inside [bounds], at least the minimum
|
||||
/// window size where the bounds allow it.
|
||||
Rect fitTerminalFloat(Rect rect, Size bounds) {
|
||||
final width = rect.width
|
||||
.clamp(terminalFloatMinSize.width, double.infinity)
|
||||
.clamp(0.0, bounds.width);
|
||||
final height = rect.height
|
||||
.clamp(terminalFloatMinSize.height, double.infinity)
|
||||
.clamp(0.0, bounds.height);
|
||||
final left = rect.left.clamp(0.0, bounds.width - width);
|
||||
final top = rect.top.clamp(0.0, bounds.height - height);
|
||||
return Rect.fromLTWH(left, top, width, height);
|
||||
}
|
||||
|
||||
/// The terminal as a window over the app: moved by its title bar, resized
|
||||
/// from its lower right corner, minimised to its title bar or maximised to
|
||||
/// the app. Its frame is kept in [layout].
|
||||
class TerminalFloat extends StatelessWidget {
|
||||
const TerminalFloat({
|
||||
super.key,
|
||||
required this.hub,
|
||||
required this.layout,
|
||||
required this.cupertino,
|
||||
required this.bounds,
|
||||
});
|
||||
|
||||
final TerminalHub hub;
|
||||
final TerminalLayout layout;
|
||||
final bool cupertino;
|
||||
final Size bounds;
|
||||
|
||||
/// Where the window is drawn now.
|
||||
Rect get frame => layout.maximized
|
||||
? (Offset.zero & bounds).deflate(terminalFloatMargin)
|
||||
: fitTerminalFloat(layout.floatRect, bounds);
|
||||
|
||||
void _move(Offset delta) {
|
||||
if (layout.maximized) return;
|
||||
layout.setFloatRect(frame.shift(delta), save: false);
|
||||
}
|
||||
|
||||
void _resize(Offset delta) {
|
||||
final rect = frame;
|
||||
layout.setFloatRect(
|
||||
fitTerminalFloat(
|
||||
Rect.fromLTWH(
|
||||
rect.left,
|
||||
rect.top,
|
||||
rect.width + delta.dx,
|
||||
rect.height + delta.dy,
|
||||
),
|
||||
bounds,
|
||||
),
|
||||
save: false,
|
||||
);
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final rect = frame;
|
||||
final title = _titleBar(context);
|
||||
final Widget window;
|
||||
if (layout.minimized) {
|
||||
window = SizedBox(width: rect.width, child: title);
|
||||
} else {
|
||||
window = SizedBox.fromSize(
|
||||
size: rect.size,
|
||||
child: Stack(
|
||||
children: [
|
||||
Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||
children: [
|
||||
title,
|
||||
TerminalTabStrip(
|
||||
hub: hub,
|
||||
layout: layout,
|
||||
cupertino: cupertino,
|
||||
),
|
||||
Expanded(
|
||||
child: TerminalBody(hub: hub, cupertino: cupertino),
|
||||
),
|
||||
],
|
||||
),
|
||||
if (!layout.maximized)
|
||||
PositionedDirectional(end: 0, bottom: 0, child: _corner()),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
return Positioned(
|
||||
left: rect.left,
|
||||
top: rect.top,
|
||||
child: Semantics(
|
||||
container: true,
|
||||
label: 'Terminal window',
|
||||
child: _chrome(context, window),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Widget _chrome(BuildContext context, Widget child) {
|
||||
if (!cupertino) {
|
||||
return Material(
|
||||
elevation: 8,
|
||||
clipBehavior: Clip.antiAlias,
|
||||
borderRadius: BorderRadius.circular(12),
|
||||
color: Theme.of(context).colorScheme.surfaceContainer,
|
||||
child: child,
|
||||
);
|
||||
}
|
||||
return DecoratedBox(
|
||||
decoration: BoxDecoration(
|
||||
color: CupertinoColors.secondarySystemBackground.resolveFrom(context),
|
||||
borderRadius: BorderRadius.circular(12),
|
||||
border: Border.all(
|
||||
color: CupertinoColors.separator.resolveFrom(context),
|
||||
),
|
||||
boxShadow: const [BoxShadow(blurRadius: 16, color: Color(0x33000000))],
|
||||
),
|
||||
child: ClipRRect(
|
||||
borderRadius: BorderRadius.circular(12),
|
||||
child: Material(type: MaterialType.transparency, child: child),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Widget _titleBar(BuildContext context) {
|
||||
final label = Text(
|
||||
hub.selected?.title ?? 'Terminal',
|
||||
maxLines: 1,
|
||||
overflow: TextOverflow.ellipsis,
|
||||
style: cupertino
|
||||
? CupertinoTheme.of(context).textTheme.navTitleTextStyle
|
||||
: Theme.of(context).textTheme.titleSmall,
|
||||
);
|
||||
final drag = MouseRegion(
|
||||
cursor: layout.maximized
|
||||
? SystemMouseCursors.basic
|
||||
: SystemMouseCursors.move,
|
||||
child: GestureDetector(
|
||||
key: const ValueKey('terminal-float-title'),
|
||||
behavior: HitTestBehavior.opaque,
|
||||
onPanUpdate: (details) => _move(details.delta),
|
||||
onPanEnd: (_) => unawaited(layout.save()),
|
||||
onDoubleTap: () => layout.setMaximized(!layout.maximized),
|
||||
child: Padding(
|
||||
padding: const EdgeInsetsDirectional.only(start: 12),
|
||||
child: Align(
|
||||
alignment: AlignmentDirectional.centerStart,
|
||||
child: label,
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
return Row(
|
||||
children: [
|
||||
Expanded(child: drag),
|
||||
_button(
|
||||
layout.minimized ? 'Restore' : 'Minimise',
|
||||
layout.minimized ? Icons.expand_less : Icons.minimize,
|
||||
layout.minimized ? CupertinoIcons.chevron_up : CupertinoIcons.minus,
|
||||
() => layout.setMinimized(!layout.minimized),
|
||||
),
|
||||
_button(
|
||||
layout.maximized ? 'Restore size' : 'Maximise',
|
||||
layout.maximized ? Icons.fullscreen_exit : Icons.fullscreen,
|
||||
layout.maximized
|
||||
? CupertinoIcons.fullscreen_exit
|
||||
: CupertinoIcons.fullscreen,
|
||||
() => layout.setMaximized(!layout.maximized),
|
||||
),
|
||||
_button(
|
||||
'Hide terminal',
|
||||
Icons.close,
|
||||
CupertinoIcons.xmark,
|
||||
layout.hide,
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
|
||||
Widget _button(
|
||||
String label,
|
||||
IconData material,
|
||||
IconData cupertinoIcon,
|
||||
VoidCallback onPressed,
|
||||
) => cupertino
|
||||
? CupertinoButton(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 8),
|
||||
onPressed: onPressed,
|
||||
child: Icon(cupertinoIcon, semanticLabel: label),
|
||||
)
|
||||
: IconButton(tooltip: label, onPressed: onPressed, icon: Icon(material));
|
||||
|
||||
Widget _corner() => Semantics(
|
||||
label: 'Resize terminal window',
|
||||
child: MouseRegion(
|
||||
cursor: SystemMouseCursors.resizeDownRight,
|
||||
child: GestureDetector(
|
||||
key: const ValueKey('terminal-float-resize'),
|
||||
behavior: HitTestBehavior.opaque,
|
||||
onPanUpdate: (details) => _resize(details.delta),
|
||||
onPanEnd: (_) => unawaited(layout.save()),
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.all(4),
|
||||
child: Icon(
|
||||
cupertino ? CupertinoIcons.arrow_down_right : Icons.south_east,
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,228 @@
|
||||
import 'dart:async';
|
||||
|
||||
import 'package:flutter/foundation.dart';
|
||||
|
||||
import '../../core/api_gateway.dart';
|
||||
import 'terminal_info.dart';
|
||||
import 'terminal_machines.dart';
|
||||
import 'terminal_tab.dart';
|
||||
|
||||
/// Every machine terminal the app shows, across the connected machines:
|
||||
/// the tabs, the selected one, and their link to each machine's socket.
|
||||
///
|
||||
/// The hub belongs to the app, not to a view: terminals keep running and
|
||||
/// keep their output while the panel is hidden or the window is minimised.
|
||||
/// When a machine connects (first, or again after a drop or a server
|
||||
/// restart) its terminals are listed, new ones get a tab, and every tab
|
||||
/// resumes its output from the last byte it holds.
|
||||
class TerminalHub extends ChangeNotifier {
|
||||
TerminalHub(this.machines) {
|
||||
machines.addListener(_machinesChanged);
|
||||
_machinesChanged();
|
||||
}
|
||||
|
||||
final TerminalMachines machines;
|
||||
final Map<String, _Link> _links = {};
|
||||
final List<TerminalTab> _tabs = [];
|
||||
String? _selected;
|
||||
bool _disposed = false;
|
||||
|
||||
/// The last refusal of an open or close, in the server's words.
|
||||
String? error;
|
||||
|
||||
List<TerminalTab> get tabs => List.unmodifiable(_tabs);
|
||||
List<TerminalMachine> get connected => machines.value;
|
||||
|
||||
TerminalTab? get selected =>
|
||||
_tabs.where((tab) => tab.key == _selected).firstOrNull ??
|
||||
_tabs.firstOrNull;
|
||||
|
||||
/// Whether the tabs come from more than one machine (or more than one
|
||||
/// is connected), so each names its machine.
|
||||
bool get multiMachine =>
|
||||
connected.length > 1 ||
|
||||
_tabs.map((tab) => tab.machineId).toSet().length > 1;
|
||||
|
||||
void select(TerminalTab tab) {
|
||||
if (_selected == tab.key) return;
|
||||
_selected = tab.key;
|
||||
_notify();
|
||||
}
|
||||
|
||||
/// The machine [gateway] belongs to, if it is connected.
|
||||
TerminalMachine? machineFor(String? id) =>
|
||||
connected.where((machine) => machine.id == id).firstOrNull;
|
||||
|
||||
/// Opens a shell on [machineId] (the first connected machine when null)
|
||||
/// in [cwd] (home when empty) and selects its tab. Returns the refusal.
|
||||
Future<String?> open({String? machineId, String cwd = ''}) async {
|
||||
final machine = machineId == null
|
||||
? connected.firstOrNull
|
||||
: machineFor(machineId);
|
||||
if (machine == null) {
|
||||
return error = 'No machine is connected to open a terminal on.';
|
||||
}
|
||||
try {
|
||||
final reply = await machine.gateway.call('terminal_open', {
|
||||
'terminal_request': {'cwd': ?(cwd.isEmpty ? null : cwd)},
|
||||
});
|
||||
final record = reply['terminal'];
|
||||
if (record is! Map) throw StateError('The server sent no terminal.');
|
||||
final tab = _adopt(machine, TerminalInfo.fromJson(record));
|
||||
_selected = tab.key;
|
||||
error = null;
|
||||
_notify();
|
||||
return null;
|
||||
} catch (failure) {
|
||||
error = '$failure';
|
||||
_notify();
|
||||
return error;
|
||||
}
|
||||
}
|
||||
|
||||
/// Ends [tab]'s shell (and its tmux session) and removes the tab. A tab
|
||||
/// whose machine is not connected cannot be closed yet.
|
||||
Future<String?> close(TerminalTab tab) async {
|
||||
if (!tab.connected) {
|
||||
return error = '${tab.machineName} is not connected.';
|
||||
}
|
||||
try {
|
||||
await tab.gateway.call('terminal_close', {
|
||||
'terminal_request': {'terminal_id': tab.info.id},
|
||||
});
|
||||
_remove(tab.key);
|
||||
error = null;
|
||||
return null;
|
||||
} catch (failure) {
|
||||
error = '$failure';
|
||||
_notify();
|
||||
return error;
|
||||
}
|
||||
}
|
||||
|
||||
TerminalTab _adopt(TerminalMachine machine, TerminalInfo info) {
|
||||
final key = terminalKey(machine.id, info.id);
|
||||
final existing = _tabs.where((tab) => tab.key == key).firstOrNull;
|
||||
if (existing != null) {
|
||||
existing.machineName = machine.name;
|
||||
existing.attach(machine.gateway, info);
|
||||
return existing;
|
||||
}
|
||||
final tab = TerminalTab(
|
||||
machineId: machine.id,
|
||||
machineName: machine.name,
|
||||
gateway: machine.gateway,
|
||||
info: info,
|
||||
)..addListener(_notify);
|
||||
_tabs.add(tab);
|
||||
unawaited(tab.resume());
|
||||
return tab;
|
||||
}
|
||||
|
||||
void _remove(String key) {
|
||||
final index = _tabs.indexWhere((tab) => tab.key == key);
|
||||
if (index < 0) return;
|
||||
final tab = _tabs.removeAt(index);
|
||||
if (_selected == key) {
|
||||
_selected = _tabs.isEmpty
|
||||
? null
|
||||
: _tabs[index.clamp(0, _tabs.length - 1)].key;
|
||||
}
|
||||
tab
|
||||
..removeListener(_notify)
|
||||
..dispose();
|
||||
_notify();
|
||||
}
|
||||
|
||||
void _machinesChanged() {
|
||||
if (_disposed) return;
|
||||
final ids = {for (final machine in connected) machine.id};
|
||||
for (final id in _links.keys.where((id) => !ids.contains(id)).toList()) {
|
||||
_links.remove(id)!.cancel();
|
||||
for (final tab in _tabs.where((tab) => tab.machineId == id)) {
|
||||
tab.disconnected();
|
||||
}
|
||||
}
|
||||
for (final machine in connected) {
|
||||
final link = _links[machine.id];
|
||||
if (link != null && identical(link.gateway, machine.gateway)) continue;
|
||||
link?.cancel();
|
||||
_links[machine.id] = _Link(
|
||||
machine.gateway,
|
||||
machine.gateway.frames.listen((frame) => _frame(machine, frame)),
|
||||
);
|
||||
unawaited(_sync(machine));
|
||||
}
|
||||
_notify();
|
||||
}
|
||||
|
||||
/// Lists [machine]'s terminals: each gets (or keeps) a tab, which then
|
||||
/// resumes its output; tabs of terminals the machine no longer has go.
|
||||
Future<void> _sync(TerminalMachine machine) async {
|
||||
final List<TerminalInfo> infos;
|
||||
try {
|
||||
infos = terminalInfos(await machine.gateway.call('terminal_list'));
|
||||
} catch (failure) {
|
||||
// A server without terminals answers with an error; its tabs stay.
|
||||
error = '$failure';
|
||||
_notify();
|
||||
return;
|
||||
}
|
||||
if (_disposed || !identical(_links[machine.id]?.gateway, machine.gateway)) {
|
||||
return;
|
||||
}
|
||||
final listed = <String>{};
|
||||
for (final info in infos.where((info) => !info.closed)) {
|
||||
listed.add(_adopt(machine, info).key);
|
||||
}
|
||||
for (final tab in _tabs.toList()) {
|
||||
if (tab.machineId == machine.id && !listed.contains(tab.key)) {
|
||||
_remove(tab.key);
|
||||
}
|
||||
}
|
||||
_notify();
|
||||
}
|
||||
|
||||
void _frame(TerminalMachine machine, JsonMap frame) {
|
||||
if (frame['type'] != 'terminal_event') return;
|
||||
final event = frame['terminal_event'];
|
||||
if (event is! Map) return;
|
||||
final key = terminalKey(machine.id, '${event['terminal_id'] ?? ''}');
|
||||
final record = event['terminal'];
|
||||
if (record is Map) {
|
||||
final info = TerminalInfo.fromJson(record);
|
||||
if (info.closed) return _remove(key);
|
||||
// A terminal another client opened appears here too.
|
||||
if (!_tabs.any((tab) => tab.key == key)) {
|
||||
_adopt(machine, info);
|
||||
_notify();
|
||||
return;
|
||||
}
|
||||
}
|
||||
_tabs.where((tab) => tab.key == key).firstOrNull?.frame(event);
|
||||
}
|
||||
|
||||
void _notify() {
|
||||
if (!_disposed) notifyListeners();
|
||||
}
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
_disposed = true;
|
||||
machines.removeListener(_machinesChanged);
|
||||
for (final link in _links.values) {
|
||||
link.cancel();
|
||||
}
|
||||
for (final tab in _tabs) {
|
||||
tab.dispose();
|
||||
}
|
||||
super.dispose();
|
||||
}
|
||||
}
|
||||
|
||||
class _Link {
|
||||
_Link(this.gateway, this.frames);
|
||||
final ApiGateway gateway;
|
||||
final StreamSubscription<JsonMap> frames;
|
||||
void cancel() => unawaited(frames.cancel());
|
||||
}
|
||||
@@ -0,0 +1,97 @@
|
||||
import '../../core/api_gateway.dart';
|
||||
|
||||
/// One machine terminal as the server records it (`terminal_list`,
|
||||
/// `terminal_event`): a login shell on that machine, running or ended.
|
||||
class TerminalInfo {
|
||||
const TerminalInfo({
|
||||
required this.id,
|
||||
required this.cwd,
|
||||
required this.status,
|
||||
this.title = '',
|
||||
this.shell = '',
|
||||
this.tmux = '',
|
||||
this.reason = '',
|
||||
this.exitCode,
|
||||
this.createdAt = 0,
|
||||
this.cols = 0,
|
||||
this.rows = 0,
|
||||
this.stream = '',
|
||||
this.outputEnd = 0,
|
||||
});
|
||||
|
||||
factory TerminalInfo.fromJson(Map json) => TerminalInfo(
|
||||
id: '${json['id'] ?? ''}',
|
||||
cwd: '${json['cwd'] ?? ''}',
|
||||
status: '${json['status'] ?? ''}',
|
||||
title: '${json['title'] ?? ''}',
|
||||
shell: '${json['shell'] ?? ''}',
|
||||
tmux: '${json['tmux'] ?? ''}',
|
||||
reason: '${json['reason'] ?? ''}',
|
||||
exitCode: (json['exit_code'] as num?)?.toInt(),
|
||||
createdAt: (json['created_at'] as num?)?.toInt() ?? 0,
|
||||
cols: (json['cols'] as num?)?.toInt() ?? 0,
|
||||
rows: (json['rows'] as num?)?.toInt() ?? 0,
|
||||
stream: '${json['stream'] ?? ''}',
|
||||
outputEnd: (json['output_end'] as num?)?.toInt() ?? 0,
|
||||
);
|
||||
|
||||
final String id;
|
||||
final String cwd;
|
||||
|
||||
/// running, exited or closed.
|
||||
final String status;
|
||||
|
||||
/// The last window title the shell set, or empty.
|
||||
final String title;
|
||||
final String shell;
|
||||
|
||||
/// The tmux session keeping the shell alive across server restarts;
|
||||
/// empty when the shell ends with the server.
|
||||
final String tmux;
|
||||
|
||||
/// Why an ended terminal ended, when it was not its own exit.
|
||||
final String reason;
|
||||
final int? exitCode;
|
||||
final int createdAt;
|
||||
final int cols;
|
||||
final int rows;
|
||||
|
||||
/// Names the server process's output stream: a restarted server starts
|
||||
/// a new one, whose byte offsets begin again at zero.
|
||||
final String stream;
|
||||
final int outputEnd;
|
||||
|
||||
/// This record naming output [stream] (lifecycle frames carry none).
|
||||
TerminalInfo withStream(String stream) => TerminalInfo(
|
||||
id: id,
|
||||
cwd: cwd,
|
||||
status: status,
|
||||
title: title,
|
||||
shell: shell,
|
||||
tmux: tmux,
|
||||
reason: reason,
|
||||
exitCode: exitCode,
|
||||
createdAt: createdAt,
|
||||
cols: cols,
|
||||
rows: rows,
|
||||
stream: stream,
|
||||
outputEnd: outputEnd,
|
||||
);
|
||||
|
||||
bool get running => status == 'running';
|
||||
bool get closed => status == 'closed';
|
||||
bool get persistent => tmux.isNotEmpty;
|
||||
|
||||
/// What an ended terminal shows instead of a prompt.
|
||||
String get endedText {
|
||||
if (reason.isNotEmpty) return reason;
|
||||
final code = exitCode;
|
||||
return code == null ? 'The shell ended.' : 'The shell exited with $code.';
|
||||
}
|
||||
}
|
||||
|
||||
/// The terminal records of a `terminal_list` reply.
|
||||
List<TerminalInfo> terminalInfos(JsonMap reply) => [
|
||||
for (final value in (reply['terminals'] as List?) ?? const [])
|
||||
if (value is Map) TerminalInfo.fromJson(value),
|
||||
];
|
||||
@@ -0,0 +1,161 @@
|
||||
import 'dart:async';
|
||||
import 'dart:convert';
|
||||
import 'dart:ui';
|
||||
|
||||
import 'package:flutter/foundation.dart';
|
||||
import 'package:shared_preferences/shared_preferences.dart';
|
||||
|
||||
const terminalLayoutKey = 'pipelines.terminal-layout.v1';
|
||||
|
||||
/// Where the terminal shows on a wide window.
|
||||
enum TerminalMode {
|
||||
panel('Bottom panel'),
|
||||
float('Floating window');
|
||||
|
||||
const TerminalMode(this.label);
|
||||
final String label;
|
||||
}
|
||||
|
||||
/// The default and smallest heights of the bottom panel, and the smallest
|
||||
/// floating window; layouts clamp to what the window allows.
|
||||
const double terminalPanelDefaultHeight = 300;
|
||||
const double terminalPanelMinHeight = 120;
|
||||
const Size terminalFloatMinSize = Size(320, 200);
|
||||
const Rect terminalFloatDefaultRect = Rect.fromLTWH(80, 80, 720, 420);
|
||||
|
||||
abstract interface class TerminalLayoutStore {
|
||||
Future<String?> load();
|
||||
Future<bool> save(String value);
|
||||
}
|
||||
|
||||
class SharedTerminalLayoutStore implements TerminalLayoutStore {
|
||||
const SharedTerminalLayoutStore();
|
||||
@override
|
||||
Future<String?> load() async {
|
||||
try {
|
||||
return (await SharedPreferences.getInstance()).getString(
|
||||
terminalLayoutKey,
|
||||
);
|
||||
} catch (_) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
Future<bool> save(String value) async {
|
||||
try {
|
||||
return await (await SharedPreferences.getInstance()).setString(
|
||||
terminalLayoutKey,
|
||||
value,
|
||||
);
|
||||
} catch (_) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The terminal surface's device-local layout: the mode, whether it is
|
||||
/// shown, the bottom panel's height and the floating window's frame and
|
||||
/// state. Every change is saved, so a reload reopens it as it was.
|
||||
class TerminalLayout extends ChangeNotifier {
|
||||
TerminalLayout({TerminalLayoutStore? store})
|
||||
: _store = store ?? const SharedTerminalLayoutStore();
|
||||
static final instance = TerminalLayout();
|
||||
final TerminalLayoutStore _store;
|
||||
int _revision = 0;
|
||||
|
||||
TerminalMode mode = TerminalMode.panel;
|
||||
bool visible = false;
|
||||
double panelHeight = terminalPanelDefaultHeight;
|
||||
Rect floatRect = terminalFloatDefaultRect;
|
||||
bool minimized = false;
|
||||
bool maximized = false;
|
||||
|
||||
/// Whether the last change could not be saved.
|
||||
bool saveFailed = false;
|
||||
|
||||
Future<void> restore() async {
|
||||
final revision = _revision;
|
||||
final raw = await _store.load();
|
||||
if (revision != _revision || raw == null) return;
|
||||
try {
|
||||
final json = jsonDecode(raw) as Map;
|
||||
mode = TerminalMode.values.asNameMap()[json['mode']] ?? mode;
|
||||
visible = json['visible'] == true;
|
||||
panelHeight = _finite(json['panel_height']) ?? panelHeight;
|
||||
final rect = json['float'];
|
||||
if (rect is List && rect.length == 4) {
|
||||
final values = rect.map(_finite).toList();
|
||||
if (!values.contains(null)) {
|
||||
floatRect = Rect.fromLTWH(
|
||||
values[0]!,
|
||||
values[1]!,
|
||||
values[2]!,
|
||||
values[3]!,
|
||||
);
|
||||
}
|
||||
}
|
||||
minimized = json['minimized'] == true;
|
||||
maximized = json['maximized'] == true;
|
||||
} catch (_) {
|
||||
return;
|
||||
}
|
||||
notifyListeners();
|
||||
}
|
||||
|
||||
void setMode(TerminalMode value) => _change(() => mode = value);
|
||||
void toggle() => _change(() {
|
||||
visible = !visible;
|
||||
if (visible) minimized = false;
|
||||
});
|
||||
void show() => _change(() {
|
||||
visible = true;
|
||||
minimized = false;
|
||||
});
|
||||
void hide() => _change(() => visible = false);
|
||||
void setPanelHeight(double value, {bool save = true}) =>
|
||||
_change(() => panelHeight = value, save: save);
|
||||
void setFloatRect(Rect value, {bool save = true}) =>
|
||||
_change(() => floatRect = value, save: save);
|
||||
void setMinimized(bool value) => _change(() {
|
||||
minimized = value;
|
||||
if (value) maximized = false;
|
||||
});
|
||||
void setMaximized(bool value) => _change(() {
|
||||
maximized = value;
|
||||
if (value) minimized = false;
|
||||
});
|
||||
|
||||
/// Saves the current layout (a drag saves once, when it ends).
|
||||
Future<void> save() async {
|
||||
final revision = _revision;
|
||||
final saved = await _store.save(
|
||||
jsonEncode({
|
||||
'mode': mode.name,
|
||||
'visible': visible,
|
||||
'panel_height': panelHeight,
|
||||
'float': [
|
||||
floatRect.left,
|
||||
floatRect.top,
|
||||
floatRect.width,
|
||||
floatRect.height,
|
||||
],
|
||||
'minimized': minimized,
|
||||
'maximized': maximized,
|
||||
}),
|
||||
);
|
||||
if (revision != _revision || saved != saveFailed) return;
|
||||
saveFailed = !saved;
|
||||
notifyListeners();
|
||||
}
|
||||
|
||||
void _change(VoidCallback change, {bool save = true}) {
|
||||
_revision++;
|
||||
change();
|
||||
notifyListeners();
|
||||
if (save) unawaited(this.save());
|
||||
}
|
||||
|
||||
static double? _finite(Object? value) =>
|
||||
value is num && value.isFinite ? value.toDouble() : null;
|
||||
}
|
||||
@@ -0,0 +1,90 @@
|
||||
import 'package:flutter/foundation.dart';
|
||||
|
||||
import '../../core/api_gateway.dart';
|
||||
import '../../core/servers/chat/chat_server_pool.dart';
|
||||
|
||||
/// One connected machine terminals can be opened on.
|
||||
@immutable
|
||||
class TerminalMachine {
|
||||
const TerminalMachine({
|
||||
required this.id,
|
||||
required this.name,
|
||||
required this.gateway,
|
||||
});
|
||||
|
||||
/// The saved machine's identity (the chat pool's server id).
|
||||
final String id;
|
||||
final String name;
|
||||
|
||||
/// That machine's own authenticated connection.
|
||||
final ApiGateway gateway;
|
||||
}
|
||||
|
||||
/// The machines connected now, in the saved order.
|
||||
typedef TerminalMachines = ValueListenable<List<TerminalMachine>>;
|
||||
|
||||
/// The chat pool's connected machines: one terminal surface across every
|
||||
/// saved machine, each terminal on its own machine's socket.
|
||||
class PoolTerminalMachines extends ValueNotifier<List<TerminalMachine>> {
|
||||
PoolTerminalMachines(this.pool) : super(const []) {
|
||||
pool.addListener(_update);
|
||||
_update();
|
||||
}
|
||||
|
||||
final ChatServerPool pool;
|
||||
|
||||
void _update() {
|
||||
final next = [
|
||||
for (final machine in pool.machines)
|
||||
if (machine.connected && machine.adapter != null)
|
||||
TerminalMachine(
|
||||
id: machine.server.id,
|
||||
name: machine.server.name,
|
||||
gateway: machine.adapter!,
|
||||
),
|
||||
];
|
||||
if (!_same(next, value)) value = next;
|
||||
}
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
pool.removeListener(_update);
|
||||
super.dispose();
|
||||
}
|
||||
}
|
||||
|
||||
/// The app's one server, while its connection is up.
|
||||
class SingleTerminalMachines extends ValueNotifier<List<TerminalMachine>> {
|
||||
SingleTerminalMachines({
|
||||
required this.connection,
|
||||
required this.machine,
|
||||
required this.connected,
|
||||
}) : super(const []) {
|
||||
connection.addListener(_update);
|
||||
_update();
|
||||
}
|
||||
|
||||
final Listenable connection;
|
||||
final TerminalMachine machine;
|
||||
final bool Function() connected;
|
||||
|
||||
void _update() {
|
||||
final next = connected() ? [machine] : const <TerminalMachine>[];
|
||||
if (!_same(next, value)) value = next;
|
||||
}
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
connection.removeListener(_update);
|
||||
super.dispose();
|
||||
}
|
||||
}
|
||||
|
||||
bool _same(List<TerminalMachine> a, List<TerminalMachine> b) =>
|
||||
a.length == b.length &&
|
||||
[
|
||||
for (var i = 0; i < a.length; i++)
|
||||
a[i].id == b[i].id &&
|
||||
a[i].name == b[i].name &&
|
||||
identical(a[i].gateway, b[i].gateway),
|
||||
].every((same) => same);
|
||||
@@ -0,0 +1,90 @@
|
||||
import 'package:flutter/cupertino.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
/// One choice of a [TerminalMenuButton].
|
||||
class TerminalChoice<T> {
|
||||
const TerminalChoice(this.value, this.label, {this.checked, this.key});
|
||||
final T value;
|
||||
final String label;
|
||||
|
||||
/// Non-null draws the choice as a checkable item.
|
||||
final bool? checked;
|
||||
final Key? key;
|
||||
}
|
||||
|
||||
/// An icon button opening the host's menu: a Material popup menu, or a
|
||||
/// Cupertino action sheet with Cancel.
|
||||
class TerminalMenuButton<T> extends StatelessWidget {
|
||||
const TerminalMenuButton({
|
||||
super.key,
|
||||
required this.cupertino,
|
||||
required this.label,
|
||||
required this.icon,
|
||||
required this.cupertinoIcon,
|
||||
required this.choices,
|
||||
required this.onSelected,
|
||||
});
|
||||
|
||||
final bool cupertino;
|
||||
final String label;
|
||||
final IconData icon;
|
||||
final IconData cupertinoIcon;
|
||||
final List<TerminalChoice<T>> choices;
|
||||
final ValueChanged<T> onSelected;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
if (!cupertino) {
|
||||
return PopupMenuButton<T>(
|
||||
tooltip: label,
|
||||
icon: Icon(icon),
|
||||
onSelected: onSelected,
|
||||
itemBuilder: (_) => [
|
||||
for (final choice in choices)
|
||||
choice.checked == null
|
||||
? PopupMenuItem<T>(
|
||||
key: choice.key,
|
||||
value: choice.value,
|
||||
child: Text(choice.label),
|
||||
)
|
||||
: CheckedPopupMenuItem<T>(
|
||||
key: choice.key,
|
||||
value: choice.value,
|
||||
checked: choice.checked!,
|
||||
child: Text(choice.label),
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
return CupertinoButton(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 8),
|
||||
onPressed: () => _sheet(context),
|
||||
child: Icon(cupertinoIcon, semanticLabel: label),
|
||||
);
|
||||
}
|
||||
|
||||
Future<void> _sheet(BuildContext context) async {
|
||||
final picked = await showCupertinoModalPopup<T>(
|
||||
context: context,
|
||||
builder: (sheet) => CupertinoActionSheet(
|
||||
title: Text(label),
|
||||
actions: [
|
||||
for (final choice in choices)
|
||||
CupertinoActionSheetAction(
|
||||
key: choice.key,
|
||||
isDefaultAction: choice.checked ?? false,
|
||||
onPressed: () => Navigator.of(sheet).pop(choice.value),
|
||||
child: Text(
|
||||
choice.checked ?? false ? '${choice.label} ✓' : choice.label,
|
||||
),
|
||||
),
|
||||
],
|
||||
cancelButton: CupertinoActionSheetAction(
|
||||
onPressed: () => Navigator.of(sheet).pop(),
|
||||
child: const Text('Cancel'),
|
||||
),
|
||||
),
|
||||
);
|
||||
if (picked != null) onSelected(picked);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
import 'dart:async';
|
||||
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
import '../../core/api_gateway.dart';
|
||||
import '../../ui/adaptive/segmented_bar_overflow.dart';
|
||||
import 'terminal_scope.dart';
|
||||
|
||||
const String terminalOpenActionLabel = 'Open in terminal';
|
||||
|
||||
/// Opens a terminal in [directory] on [gateway]'s machine through the app's
|
||||
/// terminal surface; a refusal goes to [onRefused]. Does nothing outside a
|
||||
/// [TerminalScope].
|
||||
void openInTerminal(
|
||||
BuildContext context,
|
||||
ApiGateway gateway,
|
||||
String directory, {
|
||||
void Function(String refusal)? onRefused,
|
||||
}) {
|
||||
final actions = TerminalScope.maybeOf(context);
|
||||
if (actions == null) return;
|
||||
unawaited(
|
||||
actions.openAt(gateway, directory).then((refusal) {
|
||||
if (refusal != null) onRefused?.call(refusal);
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
/// The chat actions menu's "Open in terminal" for the chat's folder, or
|
||||
/// null when the app has no terminal surface or the chat no folder.
|
||||
Widget? terminalOpenMenuAction(
|
||||
BuildContext context, {
|
||||
required ApiGateway gateway,
|
||||
required String directory,
|
||||
void Function(String refusal)? onRefused,
|
||||
}) {
|
||||
if (TerminalScope.maybeOf(context) == null || directory.isEmpty) {
|
||||
return null;
|
||||
}
|
||||
return SegmentedOverflowAction(
|
||||
key: const ValueKey<String>('chat-open-terminal-action'),
|
||||
overflowEntry: SegmentedOverflowEntry(
|
||||
label: terminalOpenActionLabel,
|
||||
icon: Icons.terminal,
|
||||
onPressed: () =>
|
||||
openInTerminal(context, gateway, directory, onRefused: onRefused),
|
||||
),
|
||||
child: const SizedBox.shrink(),
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,71 @@
|
||||
import 'package:flutter/cupertino.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
import 'terminal_body.dart';
|
||||
import 'terminal_hub.dart';
|
||||
import 'terminal_layout.dart';
|
||||
import 'terminal_tab_strip.dart';
|
||||
|
||||
/// Opens the terminals full screen (a narrow window has no room for a
|
||||
/// panel or a window), with the touch key toolbar. Resolves when closed;
|
||||
/// the shells keep running.
|
||||
Future<void> openTerminalPage(
|
||||
BuildContext context, {
|
||||
required TerminalHub hub,
|
||||
required TerminalLayout layout,
|
||||
required bool cupertino,
|
||||
}) {
|
||||
Widget page(BuildContext _) =>
|
||||
TerminalPage(hub: hub, layout: layout, cupertino: cupertino);
|
||||
return Navigator.of(context).push<void>(
|
||||
cupertino
|
||||
? CupertinoPageRoute<void>(builder: page)
|
||||
: MaterialPageRoute<void>(builder: page),
|
||||
);
|
||||
}
|
||||
|
||||
class TerminalPage extends StatelessWidget {
|
||||
const TerminalPage({
|
||||
super.key,
|
||||
required this.hub,
|
||||
required this.layout,
|
||||
required this.cupertino,
|
||||
});
|
||||
|
||||
final TerminalHub hub;
|
||||
final TerminalLayout layout;
|
||||
final bool cupertino;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final body = ListenableBuilder(
|
||||
listenable: hub,
|
||||
builder: (context, _) => SafeArea(
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||
children: [
|
||||
TerminalTabStrip(
|
||||
hub: hub,
|
||||
layout: layout,
|
||||
cupertino: cupertino,
|
||||
showModes: false,
|
||||
),
|
||||
Expanded(
|
||||
child: TerminalBody(hub: hub, cupertino: cupertino, keys: true),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
if (cupertino) {
|
||||
return CupertinoPageScaffold(
|
||||
navigationBar: const CupertinoNavigationBar(middle: Text('Terminal')),
|
||||
child: Material(type: MaterialType.transparency, child: body),
|
||||
);
|
||||
}
|
||||
return Scaffold(
|
||||
appBar: AppBar(title: const Text('Terminal')),
|
||||
body: body,
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,154 @@
|
||||
import 'dart:async';
|
||||
|
||||
import 'package:flutter/cupertino.dart';
|
||||
import 'package:flutter/gestures.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter/services.dart';
|
||||
|
||||
import '../../ui/adaptive/resize_grip.dart';
|
||||
import 'terminal_body.dart';
|
||||
import 'terminal_hub.dart';
|
||||
import 'terminal_layout.dart';
|
||||
import 'terminal_tab_strip.dart';
|
||||
|
||||
/// Arrow-key step of the panel's resize handle.
|
||||
const double terminalPanelKeyStep = 24;
|
||||
|
||||
/// Space the docked panel always leaves the app above it.
|
||||
const double terminalPanelAppMin = 160;
|
||||
|
||||
/// [height] within what a window [available] tall allows the panel.
|
||||
double terminalPanelHeight(double height, double available) {
|
||||
final max = (available - terminalPanelAppMin).clamp(
|
||||
terminalPanelMinHeight,
|
||||
double.infinity,
|
||||
);
|
||||
return height.clamp(terminalPanelMinHeight, max);
|
||||
}
|
||||
|
||||
/// The terminal docked at the bottom of the window, filling the height its
|
||||
/// parent gives it (the layout's, see [terminalPanelHeight]): a resize
|
||||
/// handle on its top edge (drag, or the arrow keys), the tabs and the
|
||||
/// selected terminal.
|
||||
class TerminalPanel extends StatefulWidget {
|
||||
const TerminalPanel({
|
||||
super.key,
|
||||
required this.hub,
|
||||
required this.layout,
|
||||
required this.cupertino,
|
||||
required this.available,
|
||||
});
|
||||
|
||||
final TerminalHub hub;
|
||||
final TerminalLayout layout;
|
||||
final bool cupertino;
|
||||
|
||||
/// The height of the window the panel shares with the app.
|
||||
final double available;
|
||||
|
||||
@override
|
||||
State<TerminalPanel> createState() => _TerminalPanelState();
|
||||
}
|
||||
|
||||
class _TerminalPanelState extends State<TerminalPanel> {
|
||||
bool _active = false;
|
||||
|
||||
double get _height =>
|
||||
terminalPanelHeight(widget.layout.panelHeight, widget.available);
|
||||
|
||||
void _resize(double height, {bool save = true}) =>
|
||||
widget.layout.setPanelHeight(
|
||||
terminalPanelHeight(height, widget.available),
|
||||
save: save,
|
||||
);
|
||||
|
||||
KeyEventResult _key(FocusNode _, KeyEvent event) {
|
||||
if (event is! KeyDownEvent && event is! KeyRepeatEvent) {
|
||||
return KeyEventResult.ignored;
|
||||
}
|
||||
if (event.logicalKey == LogicalKeyboardKey.arrowUp) {
|
||||
_resize(_height + terminalPanelKeyStep);
|
||||
} else if (event.logicalKey == LogicalKeyboardKey.arrowDown) {
|
||||
_resize(_height - terminalPanelKeyStep);
|
||||
} else {
|
||||
return KeyEventResult.ignored;
|
||||
}
|
||||
return KeyEventResult.handled;
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final height = _height;
|
||||
final handle = Semantics(
|
||||
identifier: 'terminal-panel-resize',
|
||||
label: 'Terminal height',
|
||||
hint: 'Drag, or use the arrow keys, to resize the terminal',
|
||||
slider: true,
|
||||
value: '${height.round()} pixels',
|
||||
onIncrease: () => _resize(height + terminalPanelKeyStep),
|
||||
onDecrease: () => _resize(height - terminalPanelKeyStep),
|
||||
child: Focus(
|
||||
onKeyEvent: _key,
|
||||
onFocusChange: (value) => setState(() => _active = value),
|
||||
child: MouseRegion(
|
||||
cursor: SystemMouseCursors.resizeRow,
|
||||
child: GestureDetector(
|
||||
key: const ValueKey('terminal-panel-resize'),
|
||||
behavior: HitTestBehavior.opaque,
|
||||
excludeFromSemantics: true,
|
||||
dragStartBehavior: DragStartBehavior.down,
|
||||
onVerticalDragStart: (_) => setState(() => _active = true),
|
||||
onVerticalDragUpdate: (details) =>
|
||||
_resize(_height - details.delta.dy, save: false),
|
||||
onVerticalDragEnd: (_) {
|
||||
setState(() => _active = false);
|
||||
unawaited(widget.layout.save());
|
||||
},
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.symmetric(vertical: 4),
|
||||
child: Center(
|
||||
child: AdaptiveResizeGrip(compact: true, emphasized: _active),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
final surface = widget.cupertino
|
||||
? CupertinoColors.systemBackground.resolveFrom(context)
|
||||
: Theme.of(context).colorScheme.surfaceContainerLow;
|
||||
final divider = widget.cupertino
|
||||
? CupertinoColors.separator.resolveFrom(context)
|
||||
: Theme.of(context).colorScheme.outlineVariant;
|
||||
return Semantics(
|
||||
container: true,
|
||||
label: 'Terminal panel',
|
||||
child: DecoratedBox(
|
||||
decoration: BoxDecoration(
|
||||
color: surface,
|
||||
border: Border(top: BorderSide(color: divider)),
|
||||
),
|
||||
child: Material(
|
||||
type: MaterialType.transparency,
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||
children: [
|
||||
handle,
|
||||
TerminalTabStrip(
|
||||
hub: widget.hub,
|
||||
layout: widget.layout,
|
||||
cupertino: widget.cupertino,
|
||||
),
|
||||
Expanded(
|
||||
child: TerminalBody(
|
||||
hub: widget.hub,
|
||||
cupertino: widget.cupertino,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
import 'package:flutter/widgets.dart';
|
||||
|
||||
import '../../core/api_gateway.dart';
|
||||
import '../../core/servers/server_scope.dart';
|
||||
|
||||
/// What screens below the app's terminal surface may ask of it.
|
||||
abstract interface class TerminalActions {
|
||||
/// Shows the terminal (panel, window or page) or hides it.
|
||||
void toggle();
|
||||
|
||||
/// Opens a new terminal in [cwd] on the machine [gateway] belongs to and
|
||||
/// shows it. Returns the refusal, or null.
|
||||
Future<String?> openAt(ApiGateway gateway, String cwd);
|
||||
}
|
||||
|
||||
/// Gives screens (a chat's header, the Files panel) the app's terminal
|
||||
/// surface. Absent in standalone screens and tests, which then offer no
|
||||
/// terminal actions.
|
||||
class TerminalScope extends InheritedWidget {
|
||||
const TerminalScope({super.key, required this.actions, required super.child});
|
||||
|
||||
final TerminalActions actions;
|
||||
|
||||
static TerminalActions? maybeOf(BuildContext context) =>
|
||||
context.dependOnInheritedWidgetOfExactType<TerminalScope>()?.actions;
|
||||
|
||||
@override
|
||||
bool updateShouldNotify(TerminalScope oldWidget) =>
|
||||
oldWidget.actions != actions;
|
||||
}
|
||||
|
||||
/// The machine id [gateway] was bound to, for a terminal opened from a
|
||||
/// chat or its Files panel.
|
||||
String? terminalMachineOf(ApiGateway gateway) => serverIdentity(gateway);
|
||||
@@ -0,0 +1,61 @@
|
||||
import 'dart:convert';
|
||||
|
||||
/// Characters of output one tab holds before its oldest are dropped (about
|
||||
/// the server's 1 MiB tail).
|
||||
const int terminalHeldLimit = 1 << 20;
|
||||
|
||||
/// The text of [text] after its first [bytes] UTF-8 bytes (a cut inside a
|
||||
/// character drops that character's remaining bytes).
|
||||
String terminalSkipBytes(String text, int bytes) {
|
||||
if (bytes <= 0) return text;
|
||||
final encoded = utf8.encode(text);
|
||||
if (bytes >= encoded.length) return '';
|
||||
var cut = bytes;
|
||||
while (cut < encoded.length && (encoded[cut] & 0xC0) == 0x80) {
|
||||
cut++;
|
||||
}
|
||||
return utf8.decode(encoded.sublist(cut), allowMalformed: true);
|
||||
}
|
||||
|
||||
/// One terminal's output as the client holds it: the text covering
|
||||
/// absolute bytes [start, end) of the server's stream named [stream].
|
||||
class TerminalStream {
|
||||
String text = '';
|
||||
int start = 0;
|
||||
int end = 0;
|
||||
String stream = '';
|
||||
|
||||
/// Whether nothing was received yet.
|
||||
bool get empty => stream.isEmpty && end == 0;
|
||||
|
||||
/// Replaces the held copy with a read of the server's retained tail.
|
||||
void reset(String output, int outputStart, String name) {
|
||||
text = output;
|
||||
start = outputStart;
|
||||
end = outputStart + utf8.encode(output).length;
|
||||
stream = name;
|
||||
_bound();
|
||||
}
|
||||
|
||||
/// Adds the part of [chunk] (covering [offset, chunkEnd)) past [end] and
|
||||
/// returns it; null when the chunk starts after [end] (a gap).
|
||||
String? add(String chunk, int offset, int chunkEnd) {
|
||||
if (chunkEnd <= end) return '';
|
||||
if (offset > end) return null;
|
||||
final fresh = terminalSkipBytes(chunk, end - offset);
|
||||
text += fresh;
|
||||
end = chunkEnd;
|
||||
_bound();
|
||||
return fresh;
|
||||
}
|
||||
|
||||
void _bound() {
|
||||
if (text.length <= terminalHeldLimit + terminalHeldLimit ~/ 2) return;
|
||||
var cut = text.length - terminalHeldLimit;
|
||||
// Never split a surrogate pair.
|
||||
final unit = text.codeUnitAt(cut);
|
||||
if (unit >= 0xDC00 && unit <= 0xDFFF) cut++;
|
||||
text = text.substring(cut);
|
||||
start = end - utf8.encode(text).length;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,172 @@
|
||||
import 'dart:async';
|
||||
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter/services.dart';
|
||||
|
||||
import '../../core/api_gateway.dart';
|
||||
import 'terminal_float.dart';
|
||||
import 'terminal_hub.dart';
|
||||
import 'terminal_layout.dart';
|
||||
import 'terminal_page.dart';
|
||||
import 'terminal_panel.dart';
|
||||
import 'terminal_scope.dart';
|
||||
|
||||
/// Below this width the terminal opens as a full-screen page.
|
||||
const double terminalNarrowWidth = 600;
|
||||
|
||||
/// Whether [event] is the terminal's toggle shortcut, Ctrl+` on every
|
||||
/// platform (Cmd+` switches windows on macOS).
|
||||
bool terminalToggleShortcut(KeyEvent event, HardwareKeyboard keyboard) =>
|
||||
event is KeyDownEvent &&
|
||||
event.logicalKey == LogicalKeyboardKey.backquote &&
|
||||
keyboard.isControlPressed &&
|
||||
!keyboard.isMetaPressed &&
|
||||
!keyboard.isAltPressed;
|
||||
|
||||
/// The app's one terminal surface around [child] (the shell): the bottom
|
||||
/// panel or the floating window on a wide window, a full-screen page on a
|
||||
/// narrow one. It owns the toggle shortcut and gives screens below it
|
||||
/// [TerminalActions] through [TerminalScope]. [child] keeps its place in
|
||||
/// the tree whatever is shown, so showing the terminal never rebuilds the
|
||||
/// app's state.
|
||||
class TerminalSurface extends StatefulWidget {
|
||||
const TerminalSurface({
|
||||
super.key,
|
||||
required this.hub,
|
||||
required this.layout,
|
||||
required this.cupertino,
|
||||
required this.child,
|
||||
});
|
||||
|
||||
final TerminalHub hub;
|
||||
final TerminalLayout layout;
|
||||
final bool cupertino;
|
||||
final Widget child;
|
||||
|
||||
@override
|
||||
State<TerminalSurface> createState() => _TerminalSurfaceState();
|
||||
}
|
||||
|
||||
class _TerminalSurfaceState extends State<TerminalSurface>
|
||||
implements TerminalActions {
|
||||
bool _pageOpen = false;
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
HardwareKeyboard.instance.addHandler(_key);
|
||||
}
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
HardwareKeyboard.instance.removeHandler(_key);
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
bool get _narrow => MediaQuery.sizeOf(context).width < terminalNarrowWidth;
|
||||
|
||||
/// The shortcut is handled before the focused widget, so it toggles even
|
||||
/// while the terminal itself has the keyboard.
|
||||
bool _key(KeyEvent event) {
|
||||
if (!mounted || !terminalToggleShortcut(event, HardwareKeyboard.instance)) {
|
||||
return false;
|
||||
}
|
||||
toggle();
|
||||
return true;
|
||||
}
|
||||
|
||||
@override
|
||||
void toggle() {
|
||||
if (_narrow) {
|
||||
unawaited(_openPage());
|
||||
} else {
|
||||
widget.layout.toggle();
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
Future<String?> openAt(ApiGateway gateway, String cwd) async {
|
||||
final machine = terminalMachineOf(gateway);
|
||||
final refusal = await widget.hub.open(machineId: machine, cwd: cwd);
|
||||
if (!mounted) return refusal;
|
||||
if (_narrow) {
|
||||
unawaited(_openPage());
|
||||
} else {
|
||||
widget.layout.show();
|
||||
}
|
||||
return refusal;
|
||||
}
|
||||
|
||||
Future<void> _openPage() async {
|
||||
if (_pageOpen) return;
|
||||
_pageOpen = true;
|
||||
try {
|
||||
await openTerminalPage(
|
||||
context,
|
||||
hub: widget.hub,
|
||||
layout: widget.layout,
|
||||
cupertino: widget.cupertino,
|
||||
);
|
||||
} finally {
|
||||
_pageOpen = false;
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) => TerminalScope(
|
||||
actions: this,
|
||||
child: ListenableBuilder(
|
||||
listenable: Listenable.merge([widget.hub, widget.layout]),
|
||||
builder: (context, child) => LayoutBuilder(
|
||||
builder: (context, constraints) {
|
||||
final layout = widget.layout;
|
||||
final shown = layout.visible && !_narrow;
|
||||
final panel = shown && layout.mode == TerminalMode.panel;
|
||||
final float = shown && layout.mode == TerminalMode.float;
|
||||
final height = panel
|
||||
? terminalPanelHeight(layout.panelHeight, constraints.maxHeight)
|
||||
: 0.0;
|
||||
return Stack(
|
||||
children: [
|
||||
Positioned.fill(
|
||||
bottom: height,
|
||||
// The app above a docked panel has no system inset below it.
|
||||
child: MediaQuery.removePadding(
|
||||
context: context,
|
||||
removeBottom: panel,
|
||||
child: child!,
|
||||
),
|
||||
),
|
||||
if (panel)
|
||||
Positioned(
|
||||
left: 0,
|
||||
right: 0,
|
||||
bottom: 0,
|
||||
height: height,
|
||||
child: SafeArea(
|
||||
top: false,
|
||||
child: TerminalPanel(
|
||||
key: const ValueKey('terminal-panel'),
|
||||
hub: widget.hub,
|
||||
layout: layout,
|
||||
cupertino: widget.cupertino,
|
||||
available: constraints.maxHeight,
|
||||
),
|
||||
),
|
||||
),
|
||||
if (float)
|
||||
TerminalFloat(
|
||||
key: const ValueKey('terminal-float'),
|
||||
hub: widget.hub,
|
||||
layout: layout,
|
||||
cupertino: widget.cupertino,
|
||||
bounds: constraints.biggest,
|
||||
),
|
||||
],
|
||||
);
|
||||
},
|
||||
),
|
||||
child: widget.child,
|
||||
),
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,249 @@
|
||||
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;
|
||||
@@ -0,0 +1,181 @@
|
||||
import 'dart:async';
|
||||
|
||||
import 'package:flutter/cupertino.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
import 'terminal_hub.dart';
|
||||
import 'terminal_layout.dart';
|
||||
import 'terminal_menu.dart';
|
||||
import 'terminal_tab.dart';
|
||||
|
||||
/// The terminal's header: one tab per terminal (title, and the machine when
|
||||
/// tabs come from several), New terminal (choosing the machine when more
|
||||
/// than one is connected), the mode menu, and the host's own [trailing]
|
||||
/// window buttons.
|
||||
class TerminalTabStrip extends StatelessWidget {
|
||||
const TerminalTabStrip({
|
||||
super.key,
|
||||
required this.hub,
|
||||
required this.layout,
|
||||
required this.cupertino,
|
||||
this.trailing = const [],
|
||||
this.showModes = true,
|
||||
});
|
||||
|
||||
final TerminalHub hub;
|
||||
final TerminalLayout layout;
|
||||
final bool cupertino;
|
||||
final List<Widget> trailing;
|
||||
|
||||
/// False on the narrow page, which has no panel or window to choose.
|
||||
final bool showModes;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final selected = hub.selected;
|
||||
return Row(
|
||||
children: [
|
||||
Expanded(
|
||||
child: SingleChildScrollView(
|
||||
scrollDirection: Axis.horizontal,
|
||||
padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
|
||||
child: Row(
|
||||
children: [
|
||||
for (final (index, tab) in hub.tabs.indexed)
|
||||
Padding(
|
||||
padding: const EdgeInsetsDirectional.only(end: 4),
|
||||
child: Semantics(
|
||||
identifier: 'terminal-tab-$index',
|
||||
child: _tab(context, tab, tab == selected),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
_newTerminal(context),
|
||||
if (showModes)
|
||||
TerminalMenuButton<_Option>(
|
||||
cupertino: cupertino,
|
||||
label: 'Terminal options',
|
||||
icon: Icons.more_vert,
|
||||
cupertinoIcon: CupertinoIcons.ellipsis,
|
||||
choices: [
|
||||
for (final mode in TerminalMode.values)
|
||||
TerminalChoice(
|
||||
_Option(mode),
|
||||
mode.label,
|
||||
checked: layout.mode == mode,
|
||||
key: ValueKey('terminal-mode-${mode.name}'),
|
||||
),
|
||||
const TerminalChoice(
|
||||
_Option(null),
|
||||
'Hide terminal',
|
||||
key: ValueKey('terminal-hide'),
|
||||
),
|
||||
],
|
||||
onSelected: (option) => option.mode == null
|
||||
? layout.hide()
|
||||
: layout.setMode(option.mode!),
|
||||
),
|
||||
...trailing,
|
||||
],
|
||||
);
|
||||
}
|
||||
|
||||
String _label(TerminalTab tab) =>
|
||||
hub.multiMachine ? '${tab.title} · ${tab.machineName}' : tab.title;
|
||||
|
||||
Widget _tab(BuildContext context, TerminalTab tab, bool selected) {
|
||||
final label = Text(
|
||||
_label(tab),
|
||||
maxLines: 1,
|
||||
overflow: TextOverflow.ellipsis,
|
||||
style: tab.info.running
|
||||
? null
|
||||
: const TextStyle(fontStyle: FontStyle.italic),
|
||||
);
|
||||
void close() => unawaited(hub.close(tab));
|
||||
if (cupertino) {
|
||||
final color = selected
|
||||
? CupertinoTheme.of(context).primaryColor
|
||||
: CupertinoColors.label.resolveFrom(context);
|
||||
return Row(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
CupertinoButton(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 8),
|
||||
onPressed: () => hub.select(tab),
|
||||
child: DefaultTextStyle.merge(
|
||||
style: TextStyle(
|
||||
color: color,
|
||||
fontWeight: selected ? FontWeight.w600 : null,
|
||||
),
|
||||
child: label,
|
||||
),
|
||||
),
|
||||
CupertinoButton(
|
||||
padding: EdgeInsets.zero,
|
||||
onPressed: close,
|
||||
child: const Icon(
|
||||
CupertinoIcons.xmark_circle_fill,
|
||||
semanticLabel: 'Close terminal',
|
||||
),
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
return InputChip(
|
||||
label: label,
|
||||
selected: selected,
|
||||
showCheckmark: false,
|
||||
tooltip: '${tab.machineName}: ${tab.info.cwd}',
|
||||
onSelected: (_) => hub.select(tab),
|
||||
onDeleted: close,
|
||||
deleteButtonTooltipMessage: 'Close terminal',
|
||||
);
|
||||
}
|
||||
|
||||
Widget _newTerminal(BuildContext context) {
|
||||
final machines = hub.connected;
|
||||
if (machines.length > 1) {
|
||||
return TerminalMenuButton<String>(
|
||||
cupertino: cupertino,
|
||||
label: 'New terminal',
|
||||
icon: Icons.add,
|
||||
cupertinoIcon: CupertinoIcons.add,
|
||||
choices: [
|
||||
for (final machine in machines)
|
||||
TerminalChoice(
|
||||
machine.id,
|
||||
machine.name,
|
||||
key: ValueKey('terminal-new-${machine.id}'),
|
||||
),
|
||||
],
|
||||
onSelected: (id) => unawaited(hub.open(machineId: id)),
|
||||
);
|
||||
}
|
||||
final enabled = machines.isNotEmpty;
|
||||
void open() => unawaited(hub.open());
|
||||
return cupertino
|
||||
? CupertinoButton(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 8),
|
||||
onPressed: enabled ? open : null,
|
||||
child: const Icon(
|
||||
CupertinoIcons.add,
|
||||
semanticLabel: 'New terminal',
|
||||
),
|
||||
)
|
||||
: IconButton(
|
||||
tooltip: 'New terminal',
|
||||
onPressed: enabled ? open : null,
|
||||
icon: const Icon(Icons.add),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// A mode to switch to, or (null) hiding the terminal.
|
||||
class _Option {
|
||||
const _Option(this.mode);
|
||||
final TerminalMode? mode;
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
import 'package:flutter/cupertino.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
import 'terminal_layout.dart';
|
||||
import 'terminal_scope.dart';
|
||||
|
||||
/// The shell bar's Terminal button: shows or hides the terminal (Ctrl+`).
|
||||
class TerminalToggleButton extends StatelessWidget {
|
||||
const TerminalToggleButton({
|
||||
super.key,
|
||||
required this.layout,
|
||||
required this.cupertino,
|
||||
});
|
||||
|
||||
final TerminalLayout layout;
|
||||
final bool cupertino;
|
||||
|
||||
static const String label = 'Terminal (Ctrl+`)';
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final actions = TerminalScope.maybeOf(context);
|
||||
if (actions == null) return const SizedBox.shrink();
|
||||
return ListenableBuilder(
|
||||
listenable: layout,
|
||||
builder: (context, _) {
|
||||
final shown = layout.visible;
|
||||
if (cupertino) {
|
||||
return CupertinoButton(
|
||||
key: const ValueKey('shell.terminal'),
|
||||
padding: EdgeInsets.zero,
|
||||
onPressed: actions.toggle,
|
||||
child: Icon(
|
||||
CupertinoIcons.chevron_left_slash_chevron_right,
|
||||
semanticLabel: label,
|
||||
),
|
||||
);
|
||||
}
|
||||
return IconButton(
|
||||
key: const ValueKey('shell.terminal'),
|
||||
tooltip: label,
|
||||
isSelected: shown,
|
||||
onPressed: actions.toggle,
|
||||
icon: const Icon(Icons.terminal),
|
||||
);
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -25,8 +25,13 @@ class AdaptiveShell extends StatefulWidget {
|
||||
this.onSearch,
|
||||
this.attentionCount = 0,
|
||||
this.listPaneWidthStore = const SharedPreferencesListPaneWidthStore(),
|
||||
this.barActions = const [],
|
||||
});
|
||||
|
||||
/// Actions every destination's bar ends with (the Terminal toggle), after
|
||||
/// the screen's own or Search.
|
||||
final List<Widget> barActions;
|
||||
|
||||
/// Where each destination's dragged list-pane width is kept on this device.
|
||||
final ListPaneWidthStore listPaneWidthStore;
|
||||
|
||||
@@ -409,6 +414,7 @@ class _AdaptiveShellState extends State<AdaptiveShell> {
|
||||
tooltip: 'Search',
|
||||
icon: const Icon(Icons.search),
|
||||
),
|
||||
...widget.barActions,
|
||||
],
|
||||
);
|
||||
}
|
||||
|
||||
@@ -92,8 +92,11 @@ type TerminalRecord struct {
|
||||
Reason string `json:"reason,omitempty"`
|
||||
Cols int `json:"cols"`
|
||||
Rows int `json:"rows"`
|
||||
// OutputEnd is the absolute byte count this server process has read;
|
||||
// it restarts at zero when a restarted server reattaches.
|
||||
// Stream names this server process's output stream of the terminal;
|
||||
// OutputEnd is the absolute byte count read into it. A restarted server
|
||||
// that reattaches starts a new stream at zero, so a client holding
|
||||
// another stream reads the terminal again from its start.
|
||||
Stream string `json:"stream,omitempty"`
|
||||
OutputEnd int64 `json:"output_end"`
|
||||
Output string `json:"output,omitempty"`
|
||||
OutputStart int64 `json:"output_start,omitempty"`
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"crypto/rand"
|
||||
"encoding/hex"
|
||||
"errors"
|
||||
"os"
|
||||
"os/exec"
|
||||
@@ -30,6 +32,9 @@ type terminalProcess struct {
|
||||
}
|
||||
|
||||
func newTerminalProcess(record protocol.TerminalRecord) *terminalProcess {
|
||||
var stream [6]byte
|
||||
_, _ = rand.Read(stream[:])
|
||||
record.Stream = hex.EncodeToString(stream[:])
|
||||
return &terminalProcess{
|
||||
record: record,
|
||||
out: newChatShellOutput(protocol.TerminalRetained),
|
||||
|
||||
Reference in New Issue
Block a user