Merge branch 'worktree-agent-ae4ea8a7cf042aa35'

This commit is contained in:
2026-11-09 23:59:28 +00:00
26 changed files with 1280 additions and 168 deletions
@@ -154,10 +154,12 @@ mixin _ChatScreenWorkspace on State<ChatScreen> {
/// Ctrl+Tab cycles retained panes even when the sidebar or toolbar owns
/// focus. Over a single pane it swaps in the chat shown before this one
/// instead, and back again (see [_toggleRecentChat]). Command+Tab stays
/// with the operating system's application switcher.
/// with the operating system's application switcher. While the app's
/// terminal is shown, Ctrl+Tab moves between its tabs instead.
bool _cycleChatKey(KeyEvent event) {
final keyboard = HardwareKeyboard.instance;
if (event is! KeyDownEvent ||
TerminalScope.peek(context)?.claimsTabKeys == true ||
event.logicalKey != LogicalKeyboardKey.tab ||
!keyboard.isControlPressed ||
keyboard.isMetaPressed ||
+1
View File
@@ -40,6 +40,7 @@ import 'conversation/composer_selection_focus.dart';
import 'data/chat_repository.dart';
import 'domain/chat_commands.dart';
import 'domain/chat_cycle.dart';
import '../terminal/terminal_scope.dart';
import 'domain/chat_colors.dart';
import 'ui/sessions/chat_color_palette.dart';
import 'ui/sessions/chat_sessions_body.dart';
+10 -1
View File
@@ -10,21 +10,30 @@ 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.
/// server) and, with [keys], the touch key toolbar. With [focus] it is that
/// focus scope, which the surface focuses whenever the terminal shows.
class TerminalBody extends StatelessWidget {
const TerminalBody({
super.key,
required this.hub,
required this.cupertino,
this.keys = false,
this.focus,
});
final TerminalHub hub;
final bool cupertino;
final bool keys;
final FocusScopeNode? focus;
@override
Widget build(BuildContext context) {
final focus = this.focus;
final body = _body(context);
return focus == null ? body : FocusScope(node: focus, child: body);
}
Widget _body(BuildContext context) {
final tab = hub.selected;
if (tab == null) return _empty(context);
final notes = <String>[
+37 -47
View File
@@ -5,30 +5,17 @@ import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'terminal_body.dart';
import 'terminal_float_frame.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);
}
export 'terminal_float_frame.dart' show fitTerminalFloat, terminalFloatMargin;
/// 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].
/// the app. Its frame is kept in [layout]. It grows and fades in from its
/// place as [reveal] runs forward, and shrinks and fades out in reverse.
class TerminalFloat extends StatelessWidget {
const TerminalFloat({
super.key,
@@ -36,12 +23,25 @@ class TerminalFloat extends StatelessWidget {
required this.layout,
required this.cupertino,
required this.bounds,
this.reveal = kAlwaysCompleteAnimation,
this.focus,
this.hiding = false,
});
final TerminalHub hub;
final TerminalLayout layout;
final bool cupertino;
final Size bounds;
final Animation<double> reveal;
/// The terminal's focus scope (see [TerminalBody.focus]).
final FocusScopeNode? focus;
/// While the window hides it takes no input.
final bool hiding;
/// The scale the window grows from as it shows.
static const double revealScale = 0.92;
/// Where the window is drawn now.
Rect get frame => layout.maximized
@@ -91,7 +91,11 @@ class TerminalFloat extends StatelessWidget {
cupertino: cupertino,
),
Expanded(
child: TerminalBody(hub: hub, cupertino: cupertino),
child: TerminalBody(
hub: hub,
cupertino: cupertino,
focus: focus,
),
),
],
),
@@ -104,36 +108,22 @@ class TerminalFloat extends StatelessWidget {
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),
child: IgnorePointer(
ignoring: hiding,
child: ExcludeFocus(
excluding: hiding,
child: FadeTransition(
opacity: reveal,
child: ScaleTransition(
scale: Tween<double>(begin: revealScale, end: 1).animate(reveal),
child: Semantics(
container: true,
label: 'Terminal window',
child: terminalFloatChrome(context, cupertino, window),
),
),
),
),
boxShadow: const [BoxShadow(blurRadius: 16, color: Color(0x33000000))],
),
child: ClipRRect(
borderRadius: BorderRadius.circular(12),
child: Material(type: MaterialType.transparency, child: child),
),
);
}
@@ -0,0 +1,47 @@
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'terminal_layout.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 window's card: a Material surface with elevation, or a Cupertino
/// rounded box with a hairline and shadow.
Widget terminalFloatChrome(BuildContext context, bool cupertino, 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),
),
);
}
@@ -0,0 +1,51 @@
import 'package:flutter/widgets.dart';
/// The terminal surface's keyboard focus: the selected terminal takes it
/// whenever the terminal shows (or its tab changes), and hiding gives it back
/// to what had it before (the chat composer, a field), else to the screen.
class TerminalFocus {
/// The scope around the selected terminal (see `TerminalBody.focus`). Its
/// emulator autofocuses inside it, so focusing the scope focuses it.
final FocusScopeNode scope = FocusScopeNode(debugLabel: 'terminal');
FocusNode? _previous;
bool _inside(FocusNode node) =>
identical(node, scope) || node.ancestors.contains(scope);
/// Notes what has the keyboard now, before the terminal takes it.
void remember() {
final current = FocusManager.instance.primaryFocus;
if (current == null || _inside(current)) return;
_previous = identical(current, FocusManager.instance.rootScope)
? null
: current;
}
/// Focuses the selected terminal once this frame has built it.
void focusSoon() {
WidgetsBinding.instance
..addPostFrameCallback((_) {
if (scope.context != null && scope.canRequestFocus) {
scope.requestFocus();
}
})
..ensureVisualUpdate();
}
/// Gives the keyboard back to what had it before the terminal showed, if
/// the terminal has it now.
void release() {
final previous = _previous;
_previous = null;
if (!scope.hasFocus) return;
if (previous != null &&
previous.context != null &&
previous.canRequestFocus) {
previous.requestFocus();
} else {
scope.unfocus();
}
}
void dispose() => scope.dispose();
}
+18 -1
View File
@@ -4,6 +4,7 @@ import 'package:flutter/foundation.dart';
import '../../core/api_gateway.dart';
import 'terminal_info.dart';
import 'terminal_listing.dart';
import 'terminal_machines.dart';
import 'terminal_tab.dart';
@@ -61,6 +62,19 @@ class TerminalHub extends ChangeNotifier {
_notify();
}
/// Selects the tab [step] places after the selected one, wrapping round.
void step(int step) {
final current = selected;
if (current == null) return;
final index = _tabs.indexOf(current);
select(_tabs[(index + step) % _tabs.length]);
}
final TerminalListing _listing = TerminalListing();
/// Completes once no machine's terminal list is still being read.
Future<void> listed() => _listing.idle();
/// The machine [gateway] belongs to, if it is connected.
TerminalMachine? machineFor(String? id) =>
connected.where((machine) => machine.id == id).firstOrNull;
@@ -171,7 +185,10 @@ class TerminalHub extends ChangeNotifier {
/// 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 {
Future<void> _sync(TerminalMachine machine) =>
_listing.track(() => _list(machine));
Future<void> _list(TerminalMachine machine) async {
final List<TerminalInfo> infos;
try {
infos = terminalInfos(await machine.gateway.call('terminal_list'));
@@ -0,0 +1,32 @@
import 'dart:async';
/// The machines' terminal lists being read, so the surface can wait until
/// every one has arrived (to start a terminal only when there is none).
class TerminalListing {
int _pending = 0;
final List<Completer<void>> _waiters = [];
/// Runs [read], counted as pending until it ends.
Future<void> track(Future<void> Function() read) async {
_pending++;
try {
await read();
} finally {
_pending--;
if (_pending == 0) {
for (final waiter in _waiters) {
waiter.complete();
}
_waiters.clear();
}
}
}
/// Completes once nothing is pending.
Future<void> idle() {
if (_pending == 0) return Future.value();
final waiter = Completer<void>();
_waiters.add(waiter);
return waiter.future;
}
}
@@ -23,6 +23,7 @@ class TerminalMenuButton<T> extends StatelessWidget {
required this.cupertinoIcon,
required this.choices,
required this.onSelected,
this.info,
});
final bool cupertino;
@@ -32,6 +33,9 @@ class TerminalMenuButton<T> extends StatelessWidget {
final List<TerminalChoice<T>> choices;
final ValueChanged<T> onSelected;
/// A note under the choices (the terminal's shortcuts), not selectable.
final String? info;
@override
Widget build(BuildContext context) {
if (!cupertino) {
@@ -53,6 +57,14 @@ class TerminalMenuButton<T> extends StatelessWidget {
checked: choice.checked!,
child: Text(choice.label),
),
if (info case final info?) ...[
const PopupMenuDivider(),
PopupMenuItem<T>(
key: const ValueKey('terminal-menu-info'),
enabled: false,
child: Text(info),
),
],
],
);
}
@@ -68,6 +80,7 @@ class TerminalMenuButton<T> extends StatelessWidget {
context: context,
builder: (sheet) => CupertinoActionSheet(
title: Text(label),
message: info == null ? null : Text(info!),
actions: [
for (final choice in choices)
CupertinoActionSheetAction(
@@ -4,8 +4,18 @@ import 'package:flutter/material.dart';
import '../../core/api_gateway.dart';
import '../../ui/adaptive/segmented_bar_overflow.dart';
import 'terminal_hub.dart';
import 'terminal_scope.dart';
/// Opening the terminal with none to show starts one, as New terminal
/// does, once every machine's list has arrived.
Future<void> openTerminalIfNone(TerminalHub hub) async {
hub.activate();
await hub.listed();
if (hub.tabs.isNotEmpty || hub.connected.isEmpty) return;
await hub.open();
}
const String terminalOpenActionLabel = 'Open in terminal';
/// Opens a terminal in [directory] on [gateway]'s machine through the app's
+47 -10
View File
@@ -6,22 +6,59 @@ 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, {
/// The terminals full screen (a narrow window has no room for a panel or a
/// window), with the touch key toolbar. The shells keep running when it is
/// closed; the route's own transition animates it and returns focus to
/// whatever had it.
PageRoute<void> terminalPageRoute({
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),
);
return cupertino
? CupertinoPageRoute<void>(builder: page)
: MaterialPageRoute<void>(builder: page);
}
/// The full-screen terminal page of a narrow window, opened and closed by
/// the terminal's toggle.
class TerminalPageToggle {
PageRoute<void>? _route;
bool get open => _route != null;
/// Pushes the page on [context]'s navigator unless it is open; resolves
/// when it closes.
Future<void> show(
BuildContext context, {
required TerminalHub hub,
required TerminalLayout layout,
required bool cupertino,
}) async {
if (_route != null) return;
final route = _route = terminalPageRoute(
hub: hub,
layout: layout,
cupertino: cupertino,
);
try {
await Navigator.of(context).push(route);
} finally {
if (identical(_route, route)) _route = null;
}
}
/// Closes the page, also from under a route above it.
void close() {
final route = _route;
_route = null;
if (route == null) return;
route.isCurrent
? route.navigator?.pop()
: route.navigator?.removeRoute(route);
}
}
class TerminalPage extends StatelessWidget {
@@ -37,6 +37,7 @@ class TerminalPanel extends StatefulWidget {
required this.layout,
required this.cupertino,
required this.available,
this.focus,
});
final TerminalHub hub;
@@ -46,6 +47,9 @@ class TerminalPanel extends StatefulWidget {
/// The height of the window the panel shares with the app.
final double available;
/// The terminal's focus scope (see [TerminalBody.focus]).
final FocusScopeNode? focus;
@override
State<TerminalPanel> createState() => _TerminalPanelState();
}
@@ -148,6 +152,7 @@ class _TerminalPanelState extends State<TerminalPanel> {
child: TerminalBody(
hub: widget.hub,
cupertino: widget.cupertino,
focus: widget.focus,
),
),
],
@@ -8,6 +8,10 @@ abstract interface class TerminalActions {
/// Shows the terminal (panel, window or page) or hides it.
void toggle();
/// Whether the terminal is shown, so Ctrl+Tab and Ctrl+Shift+Tab move
/// between its tabs instead of between chat panes.
bool get claimsTabKeys;
/// 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);
@@ -24,6 +28,10 @@ class TerminalScope extends InheritedWidget {
static TerminalActions? maybeOf(BuildContext context) =>
context.dependOnInheritedWidgetOfExactType<TerminalScope>()?.actions;
/// The actions without depending on them, for a key handler.
static TerminalActions? peek(BuildContext context) =>
context.getInheritedWidgetOfExactType<TerminalScope>()?.actions;
@override
bool updateShouldNotify(TerminalScope oldWidget) =>
oldWidget.actions != actions;
@@ -0,0 +1,80 @@
import 'package:flutter/foundation.dart';
import 'package:flutter/services.dart';
/// Whether [event] shows or hides the terminal: Alt+T, Ctrl+T, Cmd+T
/// (Meta+T) or Ctrl+` (Shift allowed only with Ctrl+`). They are global key
/// handlers, so inside the terminal they toggle rather than reaching the
/// shell (whose Ctrl+T, transpose-chars, is then not available) and inside
/// text fields they toggle rather than type.
///
/// A held chord's repeats match too (and are swallowed); only its first
/// press toggles.
bool terminalToggleShortcut(KeyEvent event, HardwareKeyboard keyboard) {
if (event is KeyUpEvent) return false;
final control = keyboard.isControlPressed;
final meta = keyboard.isMetaPressed;
final alt = keyboard.isAltPressed;
if (event.logicalKey == LogicalKeyboardKey.backquote) {
// Cmd+` is the macOS window switcher.
return control && !meta && !alt;
}
// Option+T types a symbol (†) on a Mac, so with Alt the key is also
// recognised by its position.
final t =
event.logicalKey == LogicalKeyboardKey.keyT ||
alt && event.physicalKey == PhysicalKeyboardKey.keyT;
if (!t || keyboard.isShiftPressed) return false;
return [control, meta, alt].where((pressed) => pressed).length == 1;
}
/// The step Ctrl+Tab (1) or Ctrl+Shift+Tab (-1) moves between terminal
/// tabs (again as it repeats), or null for any other key.
int? terminalTabShortcut(KeyEvent event, HardwareKeyboard keyboard) {
if (event is KeyUpEvent ||
event.logicalKey != LogicalKeyboardKey.tab ||
!keyboard.isControlPressed ||
keyboard.isMetaPressed ||
keyboard.isAltPressed) {
return null;
}
return keyboard.isShiftPressed ? -1 : 1;
}
/// The terminal's shortcuts as they work on this platform, for its tooltip
/// and menu. A browser tab never receives Cmd+T, Ctrl+Tab or Ctrl+Shift+Tab
/// (new tab, next and previous tab), nor Ctrl+T outside macOS, where it
/// also opens a tab; native builds get them all.
class TerminalShortcutLabels {
const TerminalShortcutLabels({required this.web, required this.platform});
TerminalShortcutLabels.current()
: web = kIsWeb,
platform = defaultTargetPlatform;
final bool web;
final TargetPlatform platform;
bool get _apple =>
platform == TargetPlatform.macOS || platform == TargetPlatform.iOS;
/// The keys that show or hide the terminal, most convenient first.
List<String> get toggle => [
if (!web && _apple) 'Cmd+T',
if (!web || _apple) 'Ctrl+T',
_apple ? 'Option+T' : 'Alt+T',
'Ctrl+`',
];
/// The keys that move between tabs, or none where the browser keeps them.
List<String> get tabs =>
web ? const [] : const ['Ctrl+Tab', 'Ctrl+Shift+Tab'];
/// The toggle button's tooltip.
String get button => 'Terminal (${toggle.first})';
/// Every shortcut, one per line, for the terminal's menu.
String get summary => [
'Show or hide: ${toggle.join(', ')}',
if (tabs.isNotEmpty) 'Next or previous tab: ${tabs.join(' / ')}',
].join('\n');
}
@@ -0,0 +1,99 @@
import 'package:flutter/widgets.dart';
import 'terminal_float.dart';
import 'terminal_hub.dart';
import 'terminal_layout.dart';
import 'terminal_panel.dart';
/// The app with the terminal over or below it: the bottom panel slides up
/// from the bottom edge (fading in slightly) as [reveal] runs forward while
/// the app above shrinks with it, and the floating window grows and fades
/// in from its place; in reverse they leave the same way, taking no input
/// meanwhile. [present] is false once hidden (and on a narrow window).
class TerminalStage extends StatelessWidget {
const TerminalStage({
super.key,
required this.hub,
required this.layout,
required this.cupertino,
required this.present,
required this.reveal,
required this.focus,
required this.child,
});
final TerminalHub hub;
final TerminalLayout layout;
final bool cupertino;
final bool present;
final Animation<double> reveal;
final FocusScopeNode focus;
final Widget child;
static final Tween<double> _fade = Tween<double>(begin: 0.4, end: 1);
@override
Widget build(BuildContext context) => LayoutBuilder(
builder: (context, constraints) {
final hiding = !layout.visible;
final panel = present && layout.mode == TerminalMode.panel;
final float = present && layout.mode == TerminalMode.float;
final height = terminalPanelHeight(
layout.panelHeight,
constraints.maxHeight,
);
final inset = panel ? height * reveal.value : 0.0;
Widget inert(Widget child) => IgnorePointer(
ignoring: hiding,
child: ExcludeFocus(excluding: hiding, child: child),
);
return Stack(
children: [
Positioned.fill(
bottom: inset,
// 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: inset - height,
height: height,
child: inert(
FadeTransition(
opacity: _fade.animate(reveal),
child: SafeArea(
top: false,
child: TerminalPanel(
key: const ValueKey('terminal-panel'),
hub: hub,
layout: layout,
cupertino: cupertino,
available: constraints.maxHeight,
focus: focus,
),
),
),
),
),
if (float)
TerminalFloat(
key: const ValueKey('terminal-float'),
hub: hub,
layout: layout,
cupertino: cupertino,
bounds: constraints.biggest,
reveal: reveal,
focus: focus,
hiding: hiding,
),
],
);
},
);
}
+115 -96
View File
@@ -4,31 +4,26 @@ import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import '../../core/api_gateway.dart';
import 'terminal_float.dart';
import '../../ui/motion/motion.dart';
import 'terminal_focus.dart';
import 'terminal_hub.dart';
import 'terminal_layout.dart';
import 'terminal_open_action.dart';
import 'terminal_page.dart';
import 'terminal_panel.dart';
import 'terminal_scope.dart';
import 'terminal_shortcuts.dart';
import 'terminal_stage.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.
/// narrow one. It owns the terminal's shortcuts (see
/// [terminalToggleShortcut], [terminalTabShortcut]), its show and hide
/// motion and its focus, 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,
@@ -48,48 +43,117 @@ class TerminalSurface extends StatefulWidget {
}
class _TerminalSurfaceState extends State<TerminalSurface>
with SingleTickerProviderStateMixin
implements TerminalActions {
bool _pageOpen = false;
late final AnimationController _reveal = AnimationController(
vsync: this,
duration: Motion.standard,
value: widget.layout.visible ? 1 : 0,
);
late final CurvedAnimation _curve = CurvedAnimation(
parent: _reveal,
curve: Motion.curve,
reverseCurve: Curves.easeInCubic,
);
final TerminalFocus _focus = TerminalFocus();
final TerminalPageToggle _page = TerminalPageToggle();
/// What was last acted on: shown on a wide window, the mode, whether the
/// window was minimised and the selected tab.
bool _shown = false;
TerminalMode? _mode;
bool _minimized = false;
String? _selected;
@override
void initState() {
super.initState();
HardwareKeyboard.instance.addHandler(_key);
FocusManager.instance.addEarlyKeyEventHandler(_key);
widget.layout.addListener(_layoutChanged);
// A terminal left shown before a reload reattaches at once.
widget.hub.addListener(_hubChanged);
}
@override
void didChangeDependencies() {
super.didChangeDependencies();
// A terminal left shown before a reload reattaches (and takes the
// keyboard) at once; a window widened past the narrow width shows it.
WidgetsBinding.instance.addPostFrameCallback((_) => _layoutChanged());
}
@override
void dispose() {
HardwareKeyboard.instance.removeHandler(_key);
FocusManager.instance.removeEarlyKeyEventHandler(_key);
widget.layout.removeListener(_layoutChanged);
widget.hub.removeListener(_hubChanged);
_curve.dispose();
_reveal.dispose();
_focus.dispose();
super.dispose();
}
void _layoutChanged() {
if (mounted && widget.layout.visible && !_narrow) widget.hub.activate();
}
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;
@override
bool get claimsTabKeys => _shown || _page.open;
void _layoutChanged() {
if (!mounted) return;
final layout = widget.layout;
final shown = layout.visible && !_narrow;
if (shown) widget.hub.activate();
_reveal.duration = Motion.of(context, Motion.standard);
if (shown != _shown) {
_shown = shown;
if (shown) {
_focus.remember();
unawaited(_reveal.forward());
_focus.focusSoon();
} else {
_focus.release();
unawaited(_reveal.reverse());
}
} else if (shown &&
(layout.mode != _mode || (_minimized && !layout.minimized))) {
_focus.focusSoon();
}
toggle();
return true;
_mode = layout.mode;
_minimized = layout.minimized;
}
void _hubChanged() {
final selected = widget.hub.selected?.key;
if (selected == _selected) return;
_selected = selected;
if (_shown) _focus.focusSoon();
}
/// The shortcuts are handled before any focused widget sees the key, so
/// they work while the terminal itself or a text field has the keyboard,
/// and neither receives them.
KeyEventResult _key(KeyEvent event) {
if (!mounted) return KeyEventResult.ignored;
final keyboard = HardwareKeyboard.instance;
if (terminalToggleShortcut(event, keyboard)) {
if (event is KeyDownEvent) toggle();
return KeyEventResult.handled;
}
final step = terminalTabShortcut(event, keyboard);
if (step == null || !claimsTabKeys) return KeyEventResult.ignored;
widget.hub.step(step);
if (!_page.open) _focus.focusSoon();
return KeyEventResult.handled;
}
@override
void toggle() {
if (_narrow) {
unawaited(_openPage());
} else {
widget.layout.toggle();
_page.open ? _page.close() : unawaited(_openPage());
return;
}
final opening = !widget.layout.visible;
widget.layout.toggle();
if (opening) unawaited(openTerminalIfNone(widget.hub));
}
@override
@@ -105,75 +169,30 @@ class _TerminalSurfaceState extends State<TerminalSurface>
return refusal;
}
Future<void> _openPage() async {
widget.hub.activate();
if (_pageOpen) return;
_pageOpen = true;
try {
await openTerminalPage(
context,
hub: widget.hub,
layout: widget.layout,
cupertino: widget.cupertino,
);
} finally {
_pageOpen = false;
}
Future<void> _openPage() {
unawaited(openTerminalIfNone(widget.hub));
return _page.show(
context,
hub: widget.hub,
layout: widget.layout,
cupertino: widget.cupertino,
);
}
@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,
),
],
);
},
listenable: Listenable.merge([widget.hub, widget.layout, _reveal]),
builder: (context, child) => TerminalStage(
hub: widget.hub,
layout: widget.layout,
cupertino: widget.cupertino,
// Kept while the hide motion runs.
present: !_narrow && (widget.layout.visible || !_reveal.isDismissed),
reveal: _curve,
focus: _focus.scope,
child: child!,
),
child: widget.child,
),
@@ -6,6 +6,7 @@ import 'package:flutter/material.dart';
import 'terminal_hub.dart';
import 'terminal_layout.dart';
import 'terminal_menu.dart';
import 'terminal_shortcuts.dart';
import 'terminal_tab.dart';
/// The terminal's header: one tab per terminal (title, and the machine when
@@ -58,6 +59,7 @@ class TerminalTabStrip extends StatelessWidget {
TerminalMenuButton<_Option>(
cupertino: cupertino,
label: 'Terminal options',
info: TerminalShortcutLabels.current().summary,
icon: Icons.more_vert,
cupertinoIcon: CupertinoIcons.ellipsis,
choices: [
@@ -3,8 +3,10 @@ import 'package:flutter/material.dart';
import 'terminal_layout.dart';
import 'terminal_scope.dart';
import 'terminal_shortcuts.dart';
/// The shell bar's Terminal button: shows or hides the terminal (Ctrl+`).
/// The shell bar's Terminal button: shows or hides the terminal (also
/// Alt+T, Ctrl+T, Cmd+T and Ctrl+`, where the platform delivers them).
class TerminalToggleButton extends StatelessWidget {
const TerminalToggleButton({
super.key,
@@ -15,7 +17,8 @@ class TerminalToggleButton extends StatelessWidget {
final TerminalLayout layout;
final bool cupertino;
static const String label = 'Terminal (Ctrl+`)';
/// The tooltip, naming the platform's most convenient shortcut.
static String get label => TerminalShortcutLabels.current().button;
@override
Widget build(BuildContext context) {