diff --git a/app/lib/features/chat/chat_screen_workspace.dart b/app/lib/features/chat/chat_screen_workspace.dart index 8b14ccc0..1f2b7888 100644 --- a/app/lib/features/chat/chat_screen_workspace.dart +++ b/app/lib/features/chat/chat_screen_workspace.dart @@ -154,10 +154,12 @@ mixin _ChatScreenWorkspace on State { /// 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 || diff --git a/app/lib/features/chat/screen.dart b/app/lib/features/chat/screen.dart index 3fcf98e9..86658bfc 100644 --- a/app/lib/features/chat/screen.dart +++ b/app/lib/features/chat/screen.dart @@ -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'; diff --git a/app/lib/features/terminal/terminal_body.dart b/app/lib/features/terminal/terminal_body.dart index c739dc9a..3e4aa1d0 100644 --- a/app/lib/features/terminal/terminal_body.dart +++ b/app/lib/features/terminal/terminal_body.dart @@ -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 = [ diff --git a/app/lib/features/terminal/terminal_float.dart b/app/lib/features/terminal/terminal_float.dart index 1d7cfd37..127bce45 100644 --- a/app/lib/features/terminal/terminal_float.dart +++ b/app/lib/features/terminal/terminal_float.dart @@ -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 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(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), ), ); } diff --git a/app/lib/features/terminal/terminal_float_frame.dart b/app/lib/features/terminal/terminal_float_frame.dart new file mode 100644 index 00000000..b529e78f --- /dev/null +++ b/app/lib/features/terminal/terminal_float_frame.dart @@ -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), + ), + ); +} diff --git a/app/lib/features/terminal/terminal_focus.dart b/app/lib/features/terminal/terminal_focus.dart new file mode 100644 index 00000000..7db8efbf --- /dev/null +++ b/app/lib/features/terminal/terminal_focus.dart @@ -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(); +} diff --git a/app/lib/features/terminal/terminal_hub.dart b/app/lib/features/terminal/terminal_hub.dart index 32f41efc..40f85bc4 100644 --- a/app/lib/features/terminal/terminal_hub.dart +++ b/app/lib/features/terminal/terminal_hub.dart @@ -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 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 _sync(TerminalMachine machine) async { + Future _sync(TerminalMachine machine) => + _listing.track(() => _list(machine)); + + Future _list(TerminalMachine machine) async { final List infos; try { infos = terminalInfos(await machine.gateway.call('terminal_list')); diff --git a/app/lib/features/terminal/terminal_listing.dart b/app/lib/features/terminal/terminal_listing.dart new file mode 100644 index 00000000..fc62f947 --- /dev/null +++ b/app/lib/features/terminal/terminal_listing.dart @@ -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> _waiters = []; + + /// Runs [read], counted as pending until it ends. + Future track(Future 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 idle() { + if (_pending == 0) return Future.value(); + final waiter = Completer(); + _waiters.add(waiter); + return waiter.future; + } +} diff --git a/app/lib/features/terminal/terminal_menu.dart b/app/lib/features/terminal/terminal_menu.dart index 98dac5c4..20612969 100644 --- a/app/lib/features/terminal/terminal_menu.dart +++ b/app/lib/features/terminal/terminal_menu.dart @@ -23,6 +23,7 @@ class TerminalMenuButton extends StatelessWidget { required this.cupertinoIcon, required this.choices, required this.onSelected, + this.info, }); final bool cupertino; @@ -32,6 +33,9 @@ class TerminalMenuButton extends StatelessWidget { final List> choices; final ValueChanged 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 extends StatelessWidget { checked: choice.checked!, child: Text(choice.label), ), + if (info case final info?) ...[ + const PopupMenuDivider(), + PopupMenuItem( + key: const ValueKey('terminal-menu-info'), + enabled: false, + child: Text(info), + ), + ], ], ); } @@ -68,6 +80,7 @@ class TerminalMenuButton extends StatelessWidget { context: context, builder: (sheet) => CupertinoActionSheet( title: Text(label), + message: info == null ? null : Text(info!), actions: [ for (final choice in choices) CupertinoActionSheetAction( diff --git a/app/lib/features/terminal/terminal_open_action.dart b/app/lib/features/terminal/terminal_open_action.dart index e79d4df2..4760ba27 100644 --- a/app/lib/features/terminal/terminal_open_action.dart +++ b/app/lib/features/terminal/terminal_open_action.dart @@ -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 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 diff --git a/app/lib/features/terminal/terminal_page.dart b/app/lib/features/terminal/terminal_page.dart index beae67a0..fe77a8eb 100644 --- a/app/lib/features/terminal/terminal_page.dart +++ b/app/lib/features/terminal/terminal_page.dart @@ -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 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 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( - cupertino - ? CupertinoPageRoute(builder: page) - : MaterialPageRoute(builder: page), - ); + return cupertino + ? CupertinoPageRoute(builder: page) + : MaterialPageRoute(builder: page); +} + +/// The full-screen terminal page of a narrow window, opened and closed by +/// the terminal's toggle. +class TerminalPageToggle { + PageRoute? _route; + + bool get open => _route != null; + + /// Pushes the page on [context]'s navigator unless it is open; resolves + /// when it closes. + Future 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 { diff --git a/app/lib/features/terminal/terminal_panel.dart b/app/lib/features/terminal/terminal_panel.dart index 5cf17548..42caf512 100644 --- a/app/lib/features/terminal/terminal_panel.dart +++ b/app/lib/features/terminal/terminal_panel.dart @@ -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 createState() => _TerminalPanelState(); } @@ -148,6 +152,7 @@ class _TerminalPanelState extends State { child: TerminalBody( hub: widget.hub, cupertino: widget.cupertino, + focus: widget.focus, ), ), ], diff --git a/app/lib/features/terminal/terminal_scope.dart b/app/lib/features/terminal/terminal_scope.dart index 7d9cb662..dcc7703f 100644 --- a/app/lib/features/terminal/terminal_scope.dart +++ b/app/lib/features/terminal/terminal_scope.dart @@ -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 openAt(ApiGateway gateway, String cwd); @@ -24,6 +28,10 @@ class TerminalScope extends InheritedWidget { static TerminalActions? maybeOf(BuildContext context) => context.dependOnInheritedWidgetOfExactType()?.actions; + /// The actions without depending on them, for a key handler. + static TerminalActions? peek(BuildContext context) => + context.getInheritedWidgetOfExactType()?.actions; + @override bool updateShouldNotify(TerminalScope oldWidget) => oldWidget.actions != actions; diff --git a/app/lib/features/terminal/terminal_shortcuts.dart b/app/lib/features/terminal/terminal_shortcuts.dart new file mode 100644 index 00000000..2e3c169b --- /dev/null +++ b/app/lib/features/terminal/terminal_shortcuts.dart @@ -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 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 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'); +} diff --git a/app/lib/features/terminal/terminal_stage.dart b/app/lib/features/terminal/terminal_stage.dart new file mode 100644 index 00000000..a46b9be5 --- /dev/null +++ b/app/lib/features/terminal/terminal_stage.dart @@ -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 reveal; + final FocusScopeNode focus; + final Widget child; + + static final Tween _fade = Tween(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, + ), + ], + ); + }, + ); +} diff --git a/app/lib/features/terminal/terminal_surface.dart b/app/lib/features/terminal/terminal_surface.dart index 10d78e95..347553ae 100644 --- a/app/lib/features/terminal/terminal_surface.dart +++ b/app/lib/features/terminal/terminal_surface.dart @@ -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 + 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 return refusal; } - Future _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 _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, ), diff --git a/app/lib/features/terminal/terminal_tab_strip.dart b/app/lib/features/terminal/terminal_tab_strip.dart index fe36c94a..1781d283 100644 --- a/app/lib/features/terminal/terminal_tab_strip.dart +++ b/app/lib/features/terminal/terminal_tab_strip.dart @@ -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: [ diff --git a/app/lib/features/terminal/terminal_toggle_button.dart b/app/lib/features/terminal/terminal_toggle_button.dart index b0853224..dd9bcd0e 100644 --- a/app/lib/features/terminal/terminal_toggle_button.dart +++ b/app/lib/features/terminal/terminal_toggle_button.dart @@ -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) { diff --git a/app/notes/terminal-panel.md b/app/notes/terminal-panel.md index dc09a5ed..0deb4f82 100644 --- a/app/notes/terminal-panel.md +++ b/app/notes/terminal-panel.md @@ -10,9 +10,47 @@ keeps running when the panel is hidden, the app navigates or reloads, and menu): *Bottom panel* docks under the app (the app shrinks above it, never hidden under it); *Floating window* is a window over the app. Both are toggled by the bar's Terminal button (every destination's bar ends - with it) and **Ctrl+`** (Cmd+` is the macOS window switcher). The - shortcut is a global key handler, so it toggles even while the terminal - has the keyboard. + with it) and the shortcuts below. Opening it with no terminal yet (once + every machine's list has arrived) starts one, as New terminal does. +- **Shortcuts** (`terminal_shortcuts.dart`, handled by the surface as a + `FocusManager` early key handler, so they work wherever focus is, including + inside the terminal and in the chat composer, and neither receives the key): + - **Alt+T** (Option+T), **Ctrl+T**, **Cmd+T** (Meta+T) and **Ctrl+`** + show or hide the terminal in the selected mode; on a narrow window they + open and close the full-screen page. Only the one modifier counts + (Ctrl+Shift+T, Ctrl+Alt+T pass through); Option+T, which types † on a + Mac, is also matched by key position. Cmd+` stays the macOS window + switcher. **The shell's own Ctrl+T (transpose-chars) no longer reaches + it** while this binding is on. + - **Ctrl+Tab / Ctrl+Shift+Tab**, while the terminal is shown (panel, + window or narrow page), select the next / previous terminal tab, wrapping, + and focus it. This deliberately overrides the chat's Ctrl+Tab pane + cycling while the terminal is open (`TerminalActions.claimsTabKeys`, + checked by `chat_screen_workspace.dart`); hidden, Ctrl+Tab cycles chat + panes as before. + - **Browsers** keep some of these: a normal Chrome/Safari/Firefox tab + never receives Cmd+T (new tab) or Ctrl+Tab / Ctrl+Shift+Tab (switch + tabs), and outside macOS Ctrl+T is new tab too. The web build therefore + lists only Ctrl+T (macOS), Alt/Option+T and Ctrl+` in the button tooltip + and the ⋮ menu (`TerminalShortcutLabels`), and no tab keys; the handlers + stay on, so an installed app window that does deliver a key still works. + Native macOS/Linux/Android-with-keyboard builds get all of them and list + them. +- **Focus:** whenever the terminal shows (shortcut, button, a reload that + restores it, a mode change, un-minimising, a tab change by pointer, key or + New terminal) the selected tab's emulator gets the keyboard: the body is a + `FocusScope` the surface focuses after the frame, and the emulator + autofocuses inside it (`terminal_focus.dart`). Hiding gives the keyboard + back at once to what had it before opening (the composer, a field), if the + terminal still has it; the narrow page's route restores focus itself. +- **Motion:** `Motion.standard` (200 ms, `Motion.curve` in, ease-in-cubic + out), played on the app clock the animation-speed setting dilates, and zero + under reduced motion (`Motion.of`). The bottom panel keeps its full height + and slides up from the bottom edge with a slight fade (opacity 0.4 to 1) + while the app above shrinks with it frame by frame (no jump, and the + emulator is not resized during the motion); the floating window scales + from 92 % and fades in its own place. During the hide motion the terminal + stays mounted but takes no pointer or focus (`terminal_stage.dart`). - **Bottom panel:** resized by dragging its top edge (the app's `AdaptiveResizeGrip`; arrow keys too, slider semantics); its height is remembered. The panel always leaves the app at least 160 px. @@ -40,7 +78,8 @@ keeps running when the panel is hidden, the app navigates or reloads, and from its retained output. A dropped connection resumes after the last byte held; a restarted server (new stream) is read again from its start. - **Keyboard:** a focused terminal gets every key (Ctrl-C, Esc, Tab, arrows, - Ctrl-letters); paste is Cmd-V (Apple) or Ctrl-V/Ctrl-Shift-V. Clicking + Ctrl-letters) except the shortcuts above (Ctrl+T, Alt+T, Cmd+T, Ctrl+`, + and Ctrl+Tab while shown); paste is Cmd-V (Apple) or Ctrl-V/Ctrl-Shift-V. Clicking elsewhere moves focus away normally. - No terminal request is sent until the terminal is first shown (or a terminal is opened): each connection sends one request at a time, so the @@ -129,14 +168,15 @@ data?, after?}`. `internal/server/terminal_{manager,supervise,process,tmux,clients,title,cwd,handlers}.go`, `websocket.go`; tests `terminal_ws_test.go`, `terminal_restart_test.go`, `internal/pipeline/terminals_test.go`; `docs/cli.md`. -- App: `lib/features/terminal/` (`terminal_{info,stream,tab,hub,machines,layout,scope,surface,panel,float,page,body,tab_strip,menu,toggle_button,open_action}.dart`), +- App: `lib/features/terminal/` (`terminal_{info,stream,tab,hub,listing,machines,layout,scope,surface,stage,focus,shortcuts,panel,float,float_frame,page,body,tab_strip,menu,toggle_button,open_action}.dart`), `lib/application/app_terminals.dart`, `pipelines_app.dart`, `bootstrap.dart`, `lib/shell/adaptive_shell.dart` (`barActions`), `lib/features/settings/settings_terminal_section.dart` (+ screen/topic pages), `lib/features/chat/conversation/chat_thread_view.dart` (Open in terminal), `lib/features/chat/files/files_panel.dart` (folder action), `lib/features/chat/shell/chat_shell_terminals.dart` (`ChatShellInputPipe` - made public). Tests `test/features/terminal/`. Probe fixture + made public), `lib/features/chat/chat_screen_workspace.dart` (Ctrl+Tab + yields to a shown terminal). Tests `test/features/terminal/`. Probe fixture `tool/perf/terminal_fixture.dart` (`?terminals=1`, `?terminal=panel|float`). ## Verification @@ -206,3 +246,48 @@ Go 1.x / Flutter 3.44.6, macOS host, tmux 3.7c (/opt/homebrew/bin/tmux). input lines logged: 0 KEEP in log: 0 ``` + +### Toggle shortcuts, focus and motion (2026-11-09) + +- Fixed on the way: the previous Ctrl+` handler was a `HardwareKeyboard` + handler, which does not stop the focus tree, so a focused terminal also + received the backquote. The shortcuts are now `FocusManager` early key + handlers; a widget test asserts no `terminal_input` for each chord and no + input from a held chord's repeats. +- `tool/memwatch/full.sh test/features/terminal`: `PASS: 38 passed` + (each of Alt+T, Ctrl+T, Cmd+T, Ctrl+` toggling the panel and the window + from a text field and from inside the terminal; Option+T (†) by key + position; Shift / second modifier ignored; held chord toggles once; focus + on show, on reload restore and on pointer tab change; focus back to the + field on hide; Ctrl+Tab / Ctrl+Shift+Tab cycling and wrapping only while + shown; auto-start of a terminal when none; narrow page open/close/focus/ + Ctrl+Tab; panel slide with the app shrinking mid-way, window scale+fade, + hide keeps it mounted, animation-speed dilation, reduced motion instant; + labels per platform; with `ChatScreen`: Ctrl+Tab cycles panes when hidden, + terminal tabs when shown, and the composer gets the keyboard back). +- `tool/memwatch/full.sh test/shell`: `PASS: 128 passed`. + `tool/memwatch/full.sh test/features/chat`: `PASS: 1144 passed, 0 failed`. +- `tool/analyze.sh`: clean. `flutter build web`: built. + `FLUTTER_XCODE_ARCHS=arm64 flutter build macos`: built (35.1MB). +- Real Chrome (`tool/capture`, probe `?terminals=1`, 1280x820; the kit's + film step gained `film=press:` to film a key press), inspected: + `/tmp/terminal-toggle/panel/02-panel-show-sheet.png`, + `/tmp/terminal-toggle/panel-warm/01-panel-show-warm-sheet.png` (269 ms + frame: panel half way up, app above shrunk), `panel/07-panel-hide-sheet.png` + (183 ms frame mid-slide), `panel/03-focused-after-alt-t.png`, + `panel/04-typed.png` (`pwd` typed straight after Alt+T), + `panel/05-ctrl-tab.png`, `panel/06-ctrl-shift-tab.png`; + `/tmp/terminal-toggle/float/02-float-hide-sheet.png` (178 ms, scaled and + faded), `float/04-float-show-sheet.png` (164 ms), `float/05-float-focused.png`, + `float/06-menu-shortcuts.png` (web on macOS lists "Show or hide: Ctrl+T, + Option+T, Ctrl+`", no tab keys); `/tmp/terminal-toggle/chat/0{1..4}-*.png` + (composer "draft ", Alt+T, `ls` typed in the terminal, Ctrl+Tab to `~`, + Alt+T, `ok` lands in the composer: "draft ok", no stray `t`/`†`). +- Not verified: CDP key events are delivered to the page directly, past the + browser's own shortcuts, so the captures cannot show which chords a real + browser keeps; the list above follows the browsers' documented reserved + shortcuts (Cmd+T, Ctrl+T outside macOS, Ctrl+Tab, Ctrl+Shift+Tab). OS-level + keys via `osascript`/System Events were not permitted (it waited on the + automation permission), so neither real Chrome nor the native macOS + build's Cmd+T was driven by real keystrokes; native behaviour is verified + by widget tests only. diff --git a/app/test/features/terminal/terminal_app.dart b/app/test/features/terminal/terminal_app.dart new file mode 100644 index 00000000..332c25d1 --- /dev/null +++ b/app/test/features/terminal/terminal_app.dart @@ -0,0 +1,105 @@ +import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/features/chat/shell/chat_shell_terminal_view.dart'; +import 'package:pipelines_app/features/terminal/terminal_hub.dart'; +import 'package:pipelines_app/features/terminal/terminal_layout.dart'; +import 'package:pipelines_app/features/terminal/terminal_surface.dart'; +import 'package:pipelines_app/features/terminal/terminal_toggle_button.dart'; + +const appField = Key('app-field'); + +/// An app with a text field under the terminal surface, [size] logical +/// pixels, optionally asking for reduced motion. +Future pumpTerminalApp( + WidgetTester tester, { + required TerminalHub hub, + required TerminalLayout layout, + Size size = const Size(1200, 800), + bool reduceMotion = false, +}) async { + tester.view.physicalSize = size; + tester.view.devicePixelRatio = 1; + addTearDown(tester.view.reset); + await tester.pumpWidget( + MaterialApp( + builder: (context, child) => MediaQuery( + data: MediaQuery.of(context).copyWith(disableAnimations: reduceMotion), + child: child!, + ), + home: TerminalSurface( + hub: hub, + layout: layout, + cupertino: false, + child: Scaffold( + appBar: AppBar( + title: const Text('App'), + actions: [TerminalToggleButton(layout: layout, cupertino: false)], + ), + body: const TextField(key: appField), + ), + ), + ), + ); + await tester.pump(); +} + +/// Presses [key] with [modifiers] held, then lets the motion finish unless +/// [settle] is false. +Future chord( + WidgetTester tester, + LogicalKeyboardKey key, + List modifiers, { + bool settle = true, +}) async { + for (final modifier in modifiers) { + await tester.sendKeyDownEvent(modifier); + } + await tester.sendKeyEvent(key); + for (final modifier in modifiers.reversed) { + await tester.sendKeyUpEvent(modifier); + } + if (settle) { + await tester.pumpAndSettle(); + } else { + await tester.pump(); + } +} + +Future altT(WidgetTester tester, {bool settle = true}) => chord( + tester, + LogicalKeyboardKey.keyT, + [LogicalKeyboardKey.altLeft], + settle: settle, +); + +Future ctrlTab(WidgetTester tester, {bool reverse = false}) => chord( + tester, + LogicalKeyboardKey.tab, + [LogicalKeyboardKey.controlLeft, if (reverse) LogicalKeyboardKey.shiftLeft], +); + +/// The terminal whose emulator has the keyboard, or null. +ChatShellTerminalView? focusedTerminal() => FocusManager + .instance + .primaryFocus + ?.context + ?.findAncestorWidgetOfExactType(); + +/// Whether [tab]'s emulator has the keyboard. +bool terminalFocused(String key) => + focusedTerminal()?.key == ValueKey('terminal-view-$key'); + +/// Whether the app's text field has the keyboard. +bool appFieldFocused(WidgetTester tester) => tester + .widget( + find.descendant( + of: find.byKey(appField), + matching: find.byType(EditableText), + ), + ) + .focusNode + .hasFocus; + +final Finder panelFinder = find.byKey(const ValueKey('terminal-panel')); +final Finder floatFinder = find.byKey(const ValueKey('terminal-float')); diff --git a/app/test/features/terminal/terminal_chat_tab_test.dart b/app/test/features/terminal/terminal_chat_tab_test.dart new file mode 100644 index 00000000..0b348551 --- /dev/null +++ b/app/test/features/terminal/terminal_chat_tab_test.dart @@ -0,0 +1,117 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:shared_preferences/shared_preferences.dart'; +import 'package:pipelines_app/core/api_gateway.dart'; +import 'package:pipelines_app/features/chat/screen.dart'; +import 'package:pipelines_app/features/chat/ui/sessions/session_actions.dart'; +import 'package:pipelines_app/features/chat/workspace/chat_workspace.dart'; +import 'package:pipelines_app/features/terminal/terminal_hub.dart'; +import 'package:pipelines_app/features/terminal/terminal_layout.dart'; +import 'package:pipelines_app/features/terminal/terminal_surface.dart'; +import 'package:pipelines_app/features/terminal/terminal_tab.dart'; +import 'package:pipelines_app/shell/adaptive_shell.dart'; +import 'package:pipelines_app/shell/destination.dart'; + +import '../chat/conversation/chat_thread_fixtures.dart'; +import 'terminal_app.dart'; +import 'terminal_fixtures.dart'; + +class _Chats extends FakeChatGateway { + @override + Future call(String type, [JsonMap fields = const {}]) { + if (type == 'chat_sessions') { + return Future.value({ + 'chat_sessions': [ + for (final id in ['a', 'b']) {'id': id, 'title': 'Chat $id'}, + ], + }); + } + if (type == 'chat_shells') return Future.value({'chat_shells': []}); + return super.call(type, fields); + } +} + +EditableText _composer(WidgetTester tester, String id) => + tester.widget( + find.descendant( + of: find.byKey(ValueKey('chat-composer-$id')), + matching: find.byType(EditableText), + ), + ); + +void main() { + testWidgets('Ctrl+Tab cycles chat panes while the terminal is hidden and ' + 'terminal tabs while it is shown; hiding returns to the composer', ( + tester, + ) async { + SharedPreferences.setMockInitialValues({}); + tester.view.physicalSize = const Size(1800, 1000); + tester.view.devicePixelRatio = 1; + addTearDown(tester.view.reset); + final chats = _Chats()..history = (_) async => chatPage([]); + addTearDown(chats.close); + final mac = TerminalGateway() + ..add('term_a', cwd: '/Users/op/src') + ..add('term_b', cwd: '/Users/op/docs'); + addTearDown(mac.close); + final hub = TerminalHub(TestMachines([machine('mac', mac)])); + addTearDown(hub.dispose); + final layout = TerminalLayout(store: MemoryLayoutStore()); + await tester.pumpWidget( + MaterialApp( + home: TerminalSurface( + hub: hub, + layout: layout, + cupertino: false, + child: AdaptiveShell( + destination: AppDestination.chat, + destinationBodies: { + AppDestination.chat: (_) => ChatScreen(gateway: chats), + }, + ), + ), + ), + ); + await tester.pumpAndSettle(); + await tester.tap(find.byKey(const Key('chat-row-a'))); + await tester.pumpAndSettle(); + await tester.tap( + find.byWidgetPredicate( + (widget) => + widget is SessionActionsButton && widget.session['id'] == 'b', + ), + ); + await tester.pumpAndSettle(); + await tester.tap(find.text('Open to the right')); + await tester.pumpAndSettle(); + final workspace = tester + .widget(find.byType(ChatWorkspace)) + .controller; + expect(workspace.activePane?.sessionId, 'b'); + + // Hidden: Ctrl+Tab is the chat's. + await ctrlTab(tester); + expect(workspace.activePane?.sessionId, 'a'); + expect(_composer(tester, 'a').focusNode.hasPrimaryFocus, isTrue); + + // Shown: it moves between terminal tabs instead. + await altT(tester); + expect(terminalFocused(terminalKey('mac', 'term_a')), isTrue); + await ctrlTab(tester); + expect(hub.selected!.info.id, 'term_b'); + expect(terminalFocused(terminalKey('mac', 'term_b')), isTrue); + expect(workspace.activePane?.sessionId, 'a'); + await ctrlTab(tester, reverse: true); + expect(hub.selected!.info.id, 'term_a'); + expect(workspace.activePane?.sessionId, 'a'); + + // Hidden again: the composer that had the keyboard gets it back, and + // Ctrl+Tab is the chat's once more. + await altT(tester); + expect(_composer(tester, 'a').focusNode.hasPrimaryFocus, isTrue); + await ctrlTab(tester); + expect(workspace.activePane?.sessionId, 'b'); + expect(hub.selected!.info.id, 'term_a'); + await tester.pumpWidget(const SizedBox.shrink()); + }); +} diff --git a/app/test/features/terminal/terminal_motion_test.dart b/app/test/features/terminal/terminal_motion_test.dart new file mode 100644 index 00000000..ae399040 --- /dev/null +++ b/app/test/features/terminal/terminal_motion_test.dart @@ -0,0 +1,122 @@ +import 'package:flutter/material.dart'; +import 'package:flutter/scheduler.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/features/terminal/terminal_hub.dart'; +import 'package:pipelines_app/features/terminal/terminal_layout.dart'; + +import 'terminal_app.dart'; +import 'terminal_fixtures.dart'; + +void main() { + late TerminalGateway mac; + late TerminalHub hub; + late TerminalLayout layout; + + setUp(() { + mac = TerminalGateway()..add('term_a', cwd: '/Users/op/src'); + hub = TerminalHub(TestMachines([machine('mac', mac, name: 'Mac')])); + layout = TerminalLayout(store: MemoryLayoutStore()); + }); + tearDown(() async { + hub.dispose(); + await mac.close(); + }); + + const shown = 800 - terminalPanelDefaultHeight; + double appBottom(WidgetTester tester) => + tester.getRect(find.byType(Scaffold).first).bottom; + double panelOpacity(WidgetTester tester) => tester + .widget( + find + .ancestor(of: panelFinder, matching: find.byType(FadeTransition)) + .first, + ) + .opacity + .value; + ScaleTransition floatScale(WidgetTester tester) => tester.widget( + find.descendant(of: floatFinder, matching: find.byType(ScaleTransition)), + ); + + testWidgets('the panel slides up from the bottom edge as the app above ' + 'shrinks, and slides away still mounted', (tester) async { + await pumpTerminalApp(tester, hub: hub, layout: layout); + await tester.tap(find.byKey(appField)); + await tester.pump(); + await altT(tester, settle: false); + await tester.pump(const Duration(milliseconds: 100)); + expect(panelFinder, findsOneWidget); + // Midway: the app has given up part of the panel's height, and the + // panel (at its full height) is partly below the window's edge. + expect(appBottom(tester), inExclusiveRange(shown, 800)); + expect(tester.getRect(panelFinder).top, closeTo(appBottom(tester), 1)); + expect(tester.getSize(panelFinder).height, terminalPanelDefaultHeight); + expect(panelOpacity(tester), inExclusiveRange(0.4, 1)); + await tester.pumpAndSettle(); + expect(appBottom(tester), shown); + expect(panelOpacity(tester), 1); + + await altT(tester, settle: false); + // The keyboard is back in the field at once; the panel leaves after. + expect(appFieldFocused(tester), isTrue); + await tester.pump(const Duration(milliseconds: 100)); + expect(panelFinder, findsOneWidget); + expect(appBottom(tester), inExclusiveRange(shown, 800)); + await tester.pumpAndSettle(); + expect(panelFinder, findsNothing); + expect(appBottom(tester), 800); + expect(appFieldFocused(tester), isTrue); + }); + + testWidgets('the floating window grows and fades in from its place, and ' + 'shrinks away', (tester) async { + layout.setMode(TerminalMode.float); + await pumpTerminalApp(tester, hub: hub, layout: layout); + await altT(tester, settle: false); + await tester.pump(const Duration(milliseconds: 100)); + final scale = floatScale(tester).scale.value; + expect(scale, inExclusiveRange(0.92, 1)); + expect(floatScale(tester).alignment, Alignment.center); + // The app underneath never moves for a window. + expect(appBottom(tester), 800); + await tester.pumpAndSettle(); + expect(floatScale(tester).scale.value, 1); + await altT(tester, settle: false); + await tester.pump(const Duration(milliseconds: 100)); + expect(floatFinder, findsOneWidget); + expect(floatScale(tester).scale.value, inExclusiveRange(0.92, 1)); + await tester.pumpAndSettle(); + expect(floatFinder, findsNothing); + }); + + testWidgets('the motion follows the animation speed setting', (tester) async { + // AnimationSpeedController plays animations at half speed this way. + timeDilation = 2; + await pumpTerminalApp(tester, hub: hub, layout: layout); + await altT(tester, settle: false); + await tester.pump(const Duration(milliseconds: 300)); + expect(appBottom(tester), inExclusiveRange(shown, 800)); + await tester.pumpAndSettle(); + expect(appBottom(tester), shown); + timeDilation = 1; + }); + + testWidgets('with reduced motion the terminal shows and hides at once', ( + tester, + ) async { + await pumpTerminalApp(tester, hub: hub, layout: layout, reduceMotion: true); + await altT(tester, settle: false); + await tester.pump(); + expect(appBottom(tester), shown); + expect(panelOpacity(tester), 1); + await altT(tester, settle: false); + await tester.pump(); + expect(panelFinder, findsNothing); + expect(appBottom(tester), 800); + layout.setMode(TerminalMode.float); + await altT(tester, settle: false); + await tester.pump(); + expect(floatScale(tester).scale.value, 1); + // The emulator's size reaches the server after its debounce. + await tester.pump(const Duration(milliseconds: 300)); + }); +} diff --git a/app/test/features/terminal/terminal_shortcuts_test.dart b/app/test/features/terminal/terminal_shortcuts_test.dart new file mode 100644 index 00000000..f703ac73 --- /dev/null +++ b/app/test/features/terminal/terminal_shortcuts_test.dart @@ -0,0 +1,254 @@ +import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/features/terminal/terminal_hub.dart'; +import 'package:pipelines_app/features/terminal/terminal_layout.dart'; +import 'package:pipelines_app/features/terminal/terminal_shortcuts.dart'; +import 'package:pipelines_app/features/terminal/terminal_tab.dart'; +import 'package:xterm/xterm.dart'; + +import 'terminal_app.dart'; +import 'terminal_fixtures.dart'; + +void main() { + late TerminalGateway mac; + late TerminalHub hub; + late TerminalLayout layout; + + setUp(() { + mac = TerminalGateway() + ..add('term_a', cwd: '/Users/op/src') + ..add('term_b', cwd: '/Users/op/docs') + ..add('term_c', cwd: '/Users/op/notes'); + hub = TerminalHub(TestMachines([machine('mac', mac, name: 'Mac')])); + layout = TerminalLayout(store: MemoryLayoutStore()); + }); + tearDown(() async { + hub.dispose(); + await mac.close(); + }); + + String key(String id) => terminalKey('mac', id); + + const toggles = { + 'Alt+T': (LogicalKeyboardKey.keyT, LogicalKeyboardKey.altLeft), + 'Ctrl+T': (LogicalKeyboardKey.keyT, LogicalKeyboardKey.controlLeft), + 'Cmd+T': (LogicalKeyboardKey.keyT, LogicalKeyboardKey.metaLeft), + 'Ctrl+`': (LogicalKeyboardKey.backquote, LogicalKeyboardKey.controlLeft), + }; + + for (final mode in TerminalMode.values) { + for (final MapEntry(key: name, value: (letter, modifier)) + in toggles.entries) { + testWidgets('$name toggles the ${mode.label.toLowerCase()} from a text ' + 'field and from inside the terminal', (tester) async { + layout.setMode(mode); + final surface = mode == TerminalMode.panel ? panelFinder : floatFinder; + await pumpTerminalApp(tester, hub: hub, layout: layout); + await tester.tap(find.byKey(appField)); + await tester.pump(); + await chord(tester, letter, [modifier]); + expect(surface, findsOneWidget); + expect(layout.visible, isTrue); + // The shortcut never types into the field it was pressed in. + expect(find.text('t'), findsNothing); + expect(terminalFocused(key('term_a')), isTrue); + // Inside the terminal the same keys hide it instead of reaching the + // shell (Ctrl+T would be transpose-chars there). + final typed = mac.bodies('terminal_input').length; + await chord(tester, letter, [modifier]); + expect(surface, findsNothing); + expect(layout.visible, isFalse); + expect(mac.bodies('terminal_input'), hasLength(typed)); + expect(hub.tabs, hasLength(3)); + }); + } + } + + test('Option+T on a Mac, which types †, toggles by key position', () { + const event = KeyDownEvent( + physicalKey: PhysicalKeyboardKey.keyT, + logicalKey: LogicalKeyboardKey(0x2020), + character: '†', + timeStamp: Duration.zero, + ); + expect(terminalToggleShortcut(event, _AltHeld()), isTrue); + }); + + testWidgets('holding the chord toggles once and types nothing', ( + tester, + ) async { + await pumpTerminalApp(tester, hub: hub, layout: layout); + await tester.sendKeyDownEvent(LogicalKeyboardKey.altLeft); + await tester.sendKeyDownEvent(LogicalKeyboardKey.keyT); + await tester.pumpAndSettle(); + expect(terminalFocused(key('term_a')), isTrue); + await tester.sendKeyRepeatEvent(LogicalKeyboardKey.keyT); + await tester.sendKeyRepeatEvent(LogicalKeyboardKey.keyT); + await tester.sendKeyUpEvent(LogicalKeyboardKey.keyT); + await tester.sendKeyUpEvent(LogicalKeyboardKey.altLeft); + await tester.pumpAndSettle(); + expect(layout.visible, isTrue); + expect(mac.bodies('terminal_input'), isEmpty); + }); + + testWidgets('Shift or a second modifier leaves T alone', (tester) async { + await pumpTerminalApp(tester, hub: hub, layout: layout); + for (final modifiers in [ + [LogicalKeyboardKey.controlLeft, LogicalKeyboardKey.shiftLeft], + [LogicalKeyboardKey.controlLeft, LogicalKeyboardKey.altLeft], + [LogicalKeyboardKey.metaLeft, LogicalKeyboardKey.shiftLeft], + ]) { + await chord(tester, LogicalKeyboardKey.keyT, modifiers); + expect(layout.visible, isFalse, reason: '$modifiers'); + } + }); + + testWidgets('showing focuses the terminal; hiding gives the keyboard back ' + 'to the field that had it', (tester) async { + await pumpTerminalApp(tester, hub: hub, layout: layout); + await tester.tap(find.byKey(appField)); + await tester.pump(); + expect(appFieldFocused(tester), isTrue); + await altT(tester); + expect(terminalFocused(key('term_a')), isTrue); + expect(appFieldFocused(tester), isFalse); + // Typing goes straight to the shell. + await tester.sendKeyEvent(LogicalKeyboardKey.keyX); + await tester.pump(); + expect(mac.bodies('terminal_input').last['data'], 'x'); + await altT(tester); + expect(appFieldFocused(tester), isTrue); + // The bar button focuses it as well. + await tester.tap(find.byIcon(Icons.terminal)); + await tester.pumpAndSettle(); + expect(terminalFocused(key('term_a')), isTrue); + }); + + testWidgets('a terminal left shown before a reload is focused once it ' + 'lists', (tester) async { + layout.show(); + await pumpTerminalApp(tester, hub: hub, layout: layout); + await tester.pumpAndSettle(); + expect(panelFinder, findsOneWidget); + expect(terminalFocused(key('term_a')), isTrue); + // The emulator's size reaches the server after its debounce. + await tester.pump(const Duration(milliseconds: 300)); + }); + + testWidgets('Ctrl+Tab and Ctrl+Shift+Tab move between terminal tabs, ' + 'wrapping, and focus each; hidden, they do nothing here', (tester) async { + await pumpTerminalApp(tester, hub: hub, layout: layout); + await ctrlTab(tester); + expect(hub.active, isFalse); + await tester.tap(find.byKey(appField)); + await altT(tester); + for (final id in ['term_b', 'term_c', 'term_a', 'term_b']) { + await ctrlTab(tester); + expect(hub.selected!.info.id, id); + expect(terminalFocused(key(id)), isTrue, reason: id); + } + for (final id in ['term_a', 'term_c']) { + await ctrlTab(tester, reverse: true); + expect(hub.selected!.info.id, id); + expect(terminalFocused(key(id)), isTrue, reason: id); + } + // From the field too: the terminal claims the keys while it is shown. + await tester.tap(find.byKey(appField)); + await tester.pump(); + await ctrlTab(tester); + expect(hub.selected!.info.id, 'term_a'); + expect(terminalFocused(key('term_a')), isTrue); + await altT(tester); + await ctrlTab(tester); + expect(hub.selected!.info.id, 'term_a'); + }); + + testWidgets('a tab picked by pointer takes the keyboard', (tester) async { + layout.show(); + await pumpTerminalApp(tester, hub: hub, layout: layout); + await tester.pumpAndSettle(); + await tester.tap(find.text('notes')); + await tester.pumpAndSettle(); + expect(terminalFocused(key('term_c')), isTrue); + }); + + testWidgets('opening with no terminal starts one', (tester) async { + final empty = TerminalGateway(); + final bare = TerminalHub(TestMachines([machine('mac', empty)])); + addTearDown(bare.dispose); + await pumpTerminalApp(tester, hub: bare, layout: layout); + await altT(tester); + expect(empty.bodies('terminal_open'), hasLength(1)); + expect(bare.tabs, hasLength(1)); + expect(terminalFocused(bare.tabs.single.key), isTrue); + await altT(tester); + await altT(tester); + expect(empty.bodies('terminal_open'), hasLength(1)); + }); + + testWidgets('on a narrow window the keys open and close the full-screen ' + 'page, focused, and Ctrl+Tab moves between its tabs', (tester) async { + await pumpTerminalApp( + tester, + hub: hub, + layout: layout, + size: const Size(390, 800), + ); + await tester.tap(find.byKey(appField)); + await tester.pump(); + await chord(tester, LogicalKeyboardKey.keyT, [ + LogicalKeyboardKey.controlLeft, + ]); + expect(find.widgetWithText(AppBar, 'Terminal'), findsOneWidget); + expect(terminalFocused(key('term_a')), isTrue); + await ctrlTab(tester, reverse: true); + expect(hub.selected!.info.id, 'term_c'); + expect(terminalFocused(key('term_c')), isTrue); + await chord(tester, LogicalKeyboardKey.keyT, [ + LogicalKeyboardKey.controlLeft, + ]); + expect(find.widgetWithText(AppBar, 'Terminal'), findsNothing); + expect(find.byType(TerminalView), findsNothing); + expect(appFieldFocused(tester), isTrue); + }); + + test('the listed shortcuts are the ones the platform delivers', () { + const mac = TerminalShortcutLabels( + web: false, + platform: TargetPlatform.macOS, + ); + expect(mac.toggle, ['Cmd+T', 'Ctrl+T', 'Option+T', 'Ctrl+`']); + expect(mac.tabs, ['Ctrl+Tab', 'Ctrl+Shift+Tab']); + const linux = TerminalShortcutLabels( + web: false, + platform: TargetPlatform.linux, + ); + expect(linux.toggle, ['Ctrl+T', 'Alt+T', 'Ctrl+`']); + const macWeb = TerminalShortcutLabels( + web: true, + platform: TargetPlatform.macOS, + ); + expect(macWeb.toggle, ['Ctrl+T', 'Option+T', 'Ctrl+`']); + expect(macWeb.tabs, isEmpty); + expect(macWeb.summary, isNot(contains('Tab'))); + const windowsWeb = TerminalShortcutLabels( + web: true, + platform: TargetPlatform.windows, + ); + expect(windowsWeb.toggle, ['Alt+T', 'Ctrl+`']); + expect(windowsWeb.button, 'Terminal (Alt+T)'); + }); +} + +/// A keyboard on which only Alt (Option) is held. +class _AltHeld extends HardwareKeyboard { + @override + bool get isAltPressed => true; + @override + bool get isControlPressed => false; + @override + bool get isMetaPressed => false; + @override + bool get isShiftPressed => false; +} diff --git a/app/tool/capture/README.md b/app/tool/capture/README.md index 7610ad78..fba6e78d 100644 --- a/app/tool/capture/README.md +++ b/app/tool/capture/README.md @@ -55,7 +55,7 @@ In JSON, a step can also set `wait` (ms), `timeout`, `name`, `ms` and `frames`. | `drag=>dx,dy` | press on the target, move by dx,dy in `steps` (12) moves `gap` (16) ms apart, release (JSON `dx`, `dy`, `steps`, `gap`; `hold: true` keeps the button down to capture mid-drag) | | `size=WxH` | resize without reloading | | `labels=name` | write the visible semantics labels, keys and rects to JSON | -| `film=` | screencast a click for `--film-ms` (900) and write the frames plus a contact sheet | +| `film=` | screencast a click for `--film-ms` (900) and write the frames plus a contact sheet; `film=press:Alt+t` films a key chord (as `press=`) instead | | `wait=ms` | sleep | | `files=a.ttf[,b.ttf]` | answer the next file chooser the page opens with these files (paths relative to the working directory); put it before the click that opens the picker | | `swipe=>dx,dy` | one-finger touch swipe (needs `--touch true`, which emulates a touch screen once semantics is on) | diff --git a/app/tool/capture/capture.mjs b/app/tool/capture/capture.mjs index f0039439..2955dccc 100644 --- a/app/tool/capture/capture.mjs +++ b/app/tool/capture/capture.mjs @@ -175,7 +175,8 @@ try { case 'tabs': await save(file(value || 'tabs', 'json'), JSON.stringify(await browser.targets(), null, 2)); break; case 'labels': await save(file(value || 'labels', 'json'), JSON.stringify(await page.labels(), null, 2)); break; case 'film': { - const name = step.name ?? `film-${describe(parseTarget(value)).replace(/\W+/g, '-').replace(/^-|-$/g, '')}`; + const what = String(value).startsWith('press:') ? String(value) : describe(parseTarget(value)); + const name = step.name ?? `film-${what.replace(/\W+/g, '-').replace(/^-|-$/g, '')}`; const frames = await page.film(value, Number(step.ms ?? opts['film-ms'])); const dir = join(out, name.replace(/[^\w.-]+/g, '_')); await mkdir(dir, { recursive: true }); diff --git a/app/tool/capture/page.mjs b/app/tool/capture/page.mjs index 6dcc692e..f510ae5a 100644 --- a/app/tool/capture/page.mjs +++ b/app/tool/capture/page.mjs @@ -207,7 +207,9 @@ export function flutterPage(browser, log, { touch = false } = {}) { // viewport before another screencast, otherwise Chrome can crop frames. await send('Page.bringToFront'); await resize(viewport.width, viewport.height); - const point = await locate(target); + // `press:Alt+t` films a key chord instead of a click. + const chord = typeof target === 'string' && target.startsWith('press:') ? target.slice(6) : null; + const point = chord ? null : await locate(target); const frames = []; const ack = (p) => { frames.push({ data: p.data, t: p.metadata.timestamp }); @@ -217,7 +219,8 @@ export function flutterPage(browser, log, { touch = false } = {}) { await send('Page.startScreencast', { format: 'png', everyNthFrame: 1, maxWidth: viewport.width, maxHeight: viewport.height }); await delay(300); const clickAt = Date.now() / 1000; - await tap(point); + if (chord) await this.press(chord); + else await tap(point); await delay(ms); await send('Page.stopScreencast'); await delay(100);