From 75a61dbd8cc8ae68f12edc921df66b4272373953 Mon Sep 17 00:00:00 2001 From: Alan Silva Date: Tue, 10 Nov 2026 22:19:30 +0000 Subject: [PATCH] Make the terminal's floating mode a window of the window system Phase 3 of docs/plans/floating-windows.md. The terminal window kind reuses TerminalHub; TerminalWindows keeps the window in step with TerminalLayout (show opens or shows it, hide minimises it, Minimise and Close hide the terminal). The bottom panel stays a shell panel. The first window takes the frame and maximised state pipelines.terminal-layout.v1 saved. The terminal's own float chrome and FloatingLayer are deleted. --- app/lib/application/app_terminals.dart | 13 ++ app/lib/application/pipelines_app.dart | 23 +- app/lib/features/terminal/terminal_float.dart | 220 ------------------ .../terminal/terminal_float_frame.dart | 47 ---- .../features/terminal/terminal_layout.dart | 32 +-- app/lib/features/terminal/terminal_stage.dart | 31 +-- .../features/terminal/terminal_surface.dart | 37 +-- .../features/terminal/terminal_window.dart | 157 +++++++++++++ app/lib/shell/windows/window_manager.dart | 10 + app/lib/ui/floating/floating_layer.dart | 99 -------- app/notes/floating-windows.md | 23 +- app/test/features/terminal/terminal_app.dart | 96 ++++++-- .../terminal/terminal_motion_test.dart | 14 +- .../terminal/terminal_surface_test.dart | 105 +++++---- app/test/ui/floating/floating_layer_test.dart | 80 ------- 15 files changed, 409 insertions(+), 578 deletions(-) delete mode 100644 app/lib/features/terminal/terminal_float.dart delete mode 100644 app/lib/features/terminal/terminal_float_frame.dart create mode 100644 app/lib/features/terminal/terminal_window.dart delete mode 100644 app/lib/ui/floating/floating_layer.dart delete mode 100644 app/test/ui/floating/floating_layer_test.dart diff --git a/app/lib/application/app_terminals.dart b/app/lib/application/app_terminals.dart index 77e55fd7..475ccf6d 100644 --- a/app/lib/application/app_terminals.dart +++ b/app/lib/application/app_terminals.dart @@ -7,6 +7,8 @@ import '../features/terminal/terminal_layout.dart'; import '../features/terminal/terminal_machines.dart'; import '../features/terminal/terminal_surface.dart'; import '../features/terminal/terminal_toggle_button.dart'; +import '../features/terminal/terminal_window.dart'; +import '../shell/windows/window_manager.dart'; /// The app's machine terminals: one hub over every connected machine (the /// chat pool's, else the app's own server), kept for the app's lifetime so @@ -20,6 +22,7 @@ class AppTerminals { required String machineId, required String machineName, required this.layout, + WindowManager? windows, }) : machines = pool != null ? PoolTerminalMachines(pool) : SingleTerminalMachines( @@ -32,12 +35,20 @@ class AppTerminals { ), ) { hub = TerminalHub(machines); + if (windows != null) { + floating = TerminalWindows(manager: windows, hub: hub, layout: layout) + ..start(); + } } final ValueNotifier> machines; final TerminalLayout layout; late final TerminalHub hub; + /// The terminal's floating window in the app's window system; null + /// without one (the float mode then shows nothing). + TerminalWindows? floating; + /// [shell] with the terminal panel, window or page around it, and the /// app's floating [windows] above both. /// [onChat]: the phone shortcut that reopens the terminal shows on the @@ -53,6 +64,7 @@ class AppTerminals { cupertino: cupertino, shortcutHere: onChat, windows: windows, + floating: floating, child: shell, ); @@ -61,6 +73,7 @@ class AppTerminals { TerminalToggleButton(layout: layout, cupertino: cupertino); void dispose() { + floating?.dispose(); hub.dispose(); machines.dispose(); } diff --git a/app/lib/application/pipelines_app.dart b/app/lib/application/pipelines_app.dart index 991c7e40..d8f411ed 100644 --- a/app/lib/application/pipelines_app.dart +++ b/app/lib/application/pipelines_app.dart @@ -265,16 +265,6 @@ class _PipelinesAppState extends State _session.addListener(_chatSyncChanged); widget.chatPool?.addListener(_chatSyncChanged); _chatSyncChanged(); - // Every kind is registered: saved windows can be restored, then the - // floating chats an older build saved are brought over once. - unawaited( - _windows.restore().then((_) { - if (!mounted) return null; - return _chatWindows.migrate( - SharedPreferencesChatFloatStore(serverScope: chatScope), - ); - }), - ); _terminals = AppTerminals( pool: widget.chatPool, connection: _session, @@ -286,6 +276,19 @@ class _PipelinesAppState extends State widget.server.uri?.host ?? 'This server', layout: widget.terminalLayout ?? TerminalLayout.instance, + windows: _windows, + ); + // Every kind is registered: saved windows can be restored. Then the + // terminal may open its window, and the floating chats an older build + // saved are brought over once. + unawaited( + _windows.restore().then((_) { + if (!mounted) return null; + _terminals.floating?.ready(); + return _chatWindows.migrate( + SharedPreferencesChatFloatStore(serverScope: chatScope), + ); + }), ); _ownsProvider = widget.routeInformationProvider == null; _provider = diff --git a/app/lib/features/terminal/terminal_float.dart b/app/lib/features/terminal/terminal_float.dart deleted file mode 100644 index 127bce45..00000000 --- a/app/lib/features/terminal/terminal_float.dart +++ /dev/null @@ -1,220 +0,0 @@ -import 'dart:async'; - -import 'package:flutter/cupertino.dart'; -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'; - -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]. 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, - required this.hub, - 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 - ? (Offset.zero & bounds).deflate(terminalFloatMargin) - : fitTerminalFloat(layout.floatRect, bounds); - - void _move(Offset delta) { - if (layout.maximized) return; - layout.setFloatRect(frame.shift(delta), save: false); - } - - void _resize(Offset delta) { - final rect = frame; - layout.setFloatRect( - fitTerminalFloat( - Rect.fromLTWH( - rect.left, - rect.top, - rect.width + delta.dx, - rect.height + delta.dy, - ), - bounds, - ), - save: false, - ); - } - - @override - Widget build(BuildContext context) { - final rect = frame; - final title = _titleBar(context); - final Widget window; - if (layout.minimized) { - window = SizedBox(width: rect.width, child: title); - } else { - window = SizedBox.fromSize( - size: rect.size, - child: Stack( - children: [ - Column( - crossAxisAlignment: CrossAxisAlignment.stretch, - children: [ - title, - TerminalTabStrip( - hub: hub, - layout: layout, - cupertino: cupertino, - ), - Expanded( - child: TerminalBody( - hub: hub, - cupertino: cupertino, - focus: focus, - ), - ), - ], - ), - if (!layout.maximized) - PositionedDirectional(end: 0, bottom: 0, child: _corner()), - ], - ), - ); - } - return Positioned( - left: rect.left, - top: rect.top, - 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), - ), - ), - ), - ), - ), - ); - } - - Widget _titleBar(BuildContext context) { - final label = Text( - hub.selected?.title ?? 'Terminal', - maxLines: 1, - overflow: TextOverflow.ellipsis, - style: cupertino - ? CupertinoTheme.of(context).textTheme.navTitleTextStyle - : Theme.of(context).textTheme.titleSmall, - ); - final drag = MouseRegion( - cursor: layout.maximized - ? SystemMouseCursors.basic - : SystemMouseCursors.move, - child: GestureDetector( - key: const ValueKey('terminal-float-title'), - behavior: HitTestBehavior.opaque, - // The window follows the pointer from where it went down. - dragStartBehavior: DragStartBehavior.down, - onPanUpdate: (details) => _move(details.delta), - onPanEnd: (_) => unawaited(layout.save()), - onDoubleTap: () => layout.setMaximized(!layout.maximized), - child: Padding( - padding: const EdgeInsetsDirectional.only(start: 12), - child: Align( - alignment: AlignmentDirectional.centerStart, - child: label, - ), - ), - ), - ); - return Row( - children: [ - Expanded(child: drag), - _button( - layout.minimized ? 'Restore' : 'Minimise', - layout.minimized ? Icons.expand_less : Icons.minimize, - layout.minimized ? CupertinoIcons.chevron_up : CupertinoIcons.minus, - () => layout.setMinimized(!layout.minimized), - ), - _button( - layout.maximized ? 'Restore size' : 'Maximise', - layout.maximized ? Icons.fullscreen_exit : Icons.fullscreen, - layout.maximized - ? CupertinoIcons.fullscreen_exit - : CupertinoIcons.fullscreen, - () => layout.setMaximized(!layout.maximized), - ), - _button( - 'Hide terminal', - Icons.close, - CupertinoIcons.xmark, - layout.hide, - ), - ], - ); - } - - Widget _button( - String label, - IconData material, - IconData cupertinoIcon, - VoidCallback onPressed, - ) => cupertino - ? CupertinoButton( - padding: const EdgeInsets.symmetric(horizontal: 8), - onPressed: onPressed, - child: Icon(cupertinoIcon, semanticLabel: label), - ) - : IconButton(tooltip: label, onPressed: onPressed, icon: Icon(material)); - - Widget _corner() => Semantics( - label: 'Resize terminal window', - child: MouseRegion( - cursor: SystemMouseCursors.resizeDownRight, - child: GestureDetector( - key: const ValueKey('terminal-float-resize'), - behavior: HitTestBehavior.opaque, - dragStartBehavior: DragStartBehavior.down, - onPanUpdate: (details) => _resize(details.delta), - onPanEnd: (_) => unawaited(layout.save()), - child: Padding( - padding: const EdgeInsets.all(4), - child: Icon( - cupertino ? CupertinoIcons.arrow_down_right : Icons.south_east, - ), - ), - ), - ), - ); -} diff --git a/app/lib/features/terminal/terminal_float_frame.dart b/app/lib/features/terminal/terminal_float_frame.dart deleted file mode 100644 index b529e78f..00000000 --- a/app/lib/features/terminal/terminal_float_frame.dart +++ /dev/null @@ -1,47 +0,0 @@ -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_layout.dart b/app/lib/features/terminal/terminal_layout.dart index b7a28731..136ca981 100644 --- a/app/lib/features/terminal/terminal_layout.dart +++ b/app/lib/features/terminal/terminal_layout.dart @@ -55,8 +55,9 @@ class SharedTerminalLayoutStore implements TerminalLayoutStore { } /// The terminal surface's device-local layout: the mode, whether it is -/// shown, the bottom panel's height and the floating window's frame and -/// state. Every change is saved, so a reload reopens it as it was. +/// shown and the bottom panel's height. Every change is saved, so a reload +/// reopens it as it was. The floating window's frame is the window +/// system's. class TerminalLayout extends ChangeNotifier { TerminalLayout({TerminalLayoutStore? store}) : _store = store ?? const SharedTerminalLayoutStore(); @@ -67,8 +68,11 @@ class TerminalLayout extends ChangeNotifier { TerminalMode mode = TerminalMode.panel; bool visible = false; double panelHeight = terminalPanelDefaultHeight; + + /// The floating window's frame and maximised state as saved before the + /// window moved to the app's window system (`TerminalWindows`), which takes + /// them for its first window. They are still written back unchanged. Rect floatRect = terminalFloatDefaultRect; - bool minimized = false; bool maximized = false; /// Whether the last change could not be saved. @@ -95,7 +99,6 @@ class TerminalLayout extends ChangeNotifier { ); } } - minimized = json['minimized'] == true; maximized = json['maximized'] == true; } catch (_) { return; @@ -104,27 +107,11 @@ class TerminalLayout extends ChangeNotifier { } void setMode(TerminalMode value) => _change(() => mode = value); - void toggle() => _change(() { - visible = !visible; - if (visible) minimized = false; - }); - void show() => _change(() { - visible = true; - minimized = false; - }); + void toggle() => _change(() => visible = !visible); + void show() => _change(() => visible = true); void hide() => _change(() => visible = false); void setPanelHeight(double value, {bool save = true}) => _change(() => panelHeight = value, save: save); - void setFloatRect(Rect value, {bool save = true}) => - _change(() => floatRect = value, save: save); - void setMinimized(bool value) => _change(() { - minimized = value; - if (value) maximized = false; - }); - void setMaximized(bool value) => _change(() { - maximized = value; - if (value) minimized = false; - }); /// Saves the current layout (a drag saves once, when it ends). Future save() async { @@ -140,7 +127,6 @@ class TerminalLayout extends ChangeNotifier { floatRect.width, floatRect.height, ], - 'minimized': minimized, 'maximized': maximized, }), ); diff --git a/app/lib/features/terminal/terminal_stage.dart b/app/lib/features/terminal/terminal_stage.dart index 0cf37db4..e3063d01 100644 --- a/app/lib/features/terminal/terminal_stage.dart +++ b/app/lib/features/terminal/terminal_stage.dart @@ -1,16 +1,14 @@ import 'package:flutter/widgets.dart'; -import '../../ui/floating/floating_layer.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 +/// The app with the terminal's bottom panel below it: the 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). +/// the app above shrinks with it; in reverse it leaves the same way, taking +/// no input meanwhile. [present] is false once hidden (and on a narrow +/// window). The terminal's floating mode is a window among [windows]. class TerminalStage extends StatelessWidget { const TerminalStage({ super.key, @@ -43,7 +41,6 @@ class TerminalStage extends StatelessWidget { 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, @@ -87,26 +84,6 @@ class TerminalStage extends StatelessWidget { ), ), ), - // The window shares the app's floating layer, so it and a - // floating chat stack by which was used last. - if (float) - Positioned.fill( - child: FloatingLayer( - open: layout.visible, - builder: (context, bounds) => [ - TerminalFloat( - key: const ValueKey('terminal-float'), - hub: hub, - layout: layout, - cupertino: cupertino, - bounds: bounds, - reveal: reveal, - focus: focus, - hiding: hiding, - ), - ], - ), - ), if (windows != null) Positioned.fill(child: windows!), ], ); diff --git a/app/lib/features/terminal/terminal_surface.dart b/app/lib/features/terminal/terminal_surface.dart index 99d63140..b6296f23 100644 --- a/app/lib/features/terminal/terminal_surface.dart +++ b/app/lib/features/terminal/terminal_surface.dart @@ -14,6 +14,7 @@ import 'terminal_scope.dart'; import 'terminal_shortcut_bubble.dart'; import 'terminal_shortcuts.dart'; import 'terminal_stage.dart'; +import 'terminal_window.dart'; /// Below this width the terminal opens as a full-screen page. const double terminalNarrowWidth = 600; @@ -34,6 +35,7 @@ class TerminalSurface extends StatefulWidget { required this.child, this.shortcutHere = true, this.windows, + this.floating, }); final TerminalHub hub; @@ -48,6 +50,10 @@ class TerminalSurface extends StatefulWidget { /// The app's floating windows (see [TerminalStage.windows]). final Widget? windows; + /// The terminal's own floating window among them; without it the float + /// mode shows nothing. + final TerminalWindows? floating; + @override State createState() => _TerminalSurfaceState(); } @@ -58,7 +64,9 @@ class _TerminalSurfaceState extends State late final AnimationController _reveal = AnimationController( vsync: this, duration: Motion.standard, - value: widget.layout.visible ? 1 : 0, + value: widget.layout.visible && widget.layout.mode == TerminalMode.panel + ? 1 + : 0, ); late final CurvedAnimation _curve = CurvedAnimation( parent: _reveal, @@ -68,11 +76,10 @@ class _TerminalSurfaceState extends State 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. + /// What was last acted on: shown on a wide window, the panel shown, and + /// the selected tab. bool _shown = false; - TerminalMode? _mode; - bool _minimized = false; + bool _panelShown = false; String? _selected; @override @@ -112,10 +119,15 @@ class _TerminalSurfaceState extends State final layout = widget.layout; final shown = layout.visible && !_narrow; if (shown) widget.hub.activate(); + widget.floating?.wide = !_narrow; + // The floating window has its own motion and focus (the window + // system's); this surface moves the panel and its keyboard. + final panel = shown && layout.mode == TerminalMode.panel; _reveal.duration = Motion.of(context, Motion.standard); - if (shown != _shown) { - _shown = shown; - if (shown) { + _shown = shown; + if (panel != _panelShown) { + _panelShown = panel; + if (panel) { _focus.remember(); unawaited(_reveal.forward()); _focus.focusSoon(); @@ -123,19 +135,14 @@ class _TerminalSurfaceState extends State _focus.release(); unawaited(_reveal.reverse()); } - } else if (shown && - (layout.mode != _mode || (_minimized && !layout.minimized))) { - _focus.focusSoon(); } - _mode = layout.mode; - _minimized = layout.minimized; } void _hubChanged() { final selected = widget.hub.selected?.key; if (selected == _selected) return; _selected = selected; - if (_shown) _focus.focusSoon(); + if (_panelShown) _focus.focusSoon(); } /// The shortcuts are handled before any focused widget sees the key, so @@ -151,7 +158,7 @@ class _TerminalSurfaceState extends State final step = terminalTabShortcut(event, keyboard); if (step == null || !claimsTabKeys) return KeyEventResult.ignored; widget.hub.step(step); - if (!_page.open) _focus.focusSoon(); + if (!_page.open && _panelShown) _focus.focusSoon(); return KeyEventResult.handled; } diff --git a/app/lib/features/terminal/terminal_window.dart b/app/lib/features/terminal/terminal_window.dart new file mode 100644 index 00000000..6787d2cf --- /dev/null +++ b/app/lib/features/terminal/terminal_window.dart @@ -0,0 +1,157 @@ +import 'package:flutter/material.dart'; + +import '../../shell/windows/window_entry.dart'; +import '../../shell/windows/window_kind.dart'; +import '../../shell/windows/window_manager.dart'; +import 'terminal_body.dart'; +import 'terminal_hub.dart'; +import 'terminal_layout.dart'; +import 'terminal_tab_strip.dart'; + +const terminalWindowKind = 'terminal'; +const _terminalContent = 'terminal'; + +/// The terminal's floating mode as a window of the app's window system. The +/// terminal has one window, for the device (not a server); its tabs and +/// shells live in the [TerminalHub], so closing the window loses nothing. +/// +/// [TerminalLayout] stays the terminal's own state (shown, panel or float): +/// showing it in float mode opens or shows the window, hiding minimises it, +/// and the window's Minimise and Close hide the terminal. +class TerminalWindows { + TerminalWindows({ + required this.manager, + required this.hub, + required this.layout, + }); + + final WindowManager manager; + final TerminalHub hub; + final TerminalLayout layout; + late final TerminalWindowKind kind = TerminalWindowKind(hub, layout); + + bool _started = false; + bool _ready = false; + bool _wide = true; + bool _syncing = false; + + /// Registers the kind. Call before the manager restores, and [ready] + /// after it has, so opening the window never races the saved windows. + void start() { + if (_started) return; + _started = true; + manager.kinds.register(kind); + layout.addListener(sync); + manager.addListener(_windowsChanged); + } + + /// The manager has restored its saved windows. + void ready() { + _ready = true; + sync(); + } + + void dispose() { + if (!_started) return; + _started = false; + layout.removeListener(sync); + manager.removeListener(_windowsChanged); + manager.kinds.unregister(terminalWindowKind); + } + + /// Whether the app is wide enough for the window (a narrow app shows the + /// terminal as a page instead). + set wide(bool value) { + if (_wide == value) return; + _wide = value; + sync(); + } + + WindowEntry? get entry => manager.find(terminalWindowKind, _terminalContent); + + bool get _wanted => + layout.visible && layout.mode == TerminalMode.float && _wide; + + /// Makes the window follow the layout. + void sync() { + if (!_started || !_ready || _syncing) return; + _syncing = true; + try { + final entry = this.entry; + if (_wanted) { + if (entry == null) { + _open(); + } else if (!manager.isVisible(entry) || + manager.active?.id != entry.id) { + manager.show(entry.id); + } + } else if (entry != null) { + if (layout.mode != TerminalMode.float) { + manager.close(entry.id); + } else if (manager.isVisible(entry)) { + manager.setMinimized(entry.id, true); + } + } + } finally { + _syncing = false; + } + } + + /// The first window takes the frame and maximised state the terminal's own + /// layout saved before windows existed (`pipelines.terminal-layout.v1`). + void _open() { + final legacy = + manager.lastFrame(terminalWindowKind, _terminalContent) == null; + final entry = manager.open( + terminalWindowKind, + _terminalContent, + frame: legacy ? layout.floatRect : null, + ); + if (legacy && layout.maximized) manager.setMaximized(entry.id, true); + } + + /// The window's Minimise or Close (or the windows' own show and hide) + /// hides the terminal. + void _windowsChanged() { + if (!_started || !_ready || _syncing || !_wanted) return; + final entry = this.entry; + if (entry == null || !manager.isVisible(entry)) layout.hide(); + } +} + +/// The terminal in a floating window: its tabs and the selected terminal. +class TerminalWindowKind extends WindowKind { + TerminalWindowKind(this.hub, this.layout); + + final TerminalHub hub; + final TerminalLayout layout; + + @override + String get key => terminalWindowKind; + @override + bool get serverScoped => false; + @override + IconData get icon => Icons.terminal; + @override + Size get minSize => terminalFloatMinSize; + @override + Rect get defaultFrame => terminalFloatDefaultRect; + @override + Listenable get changes => hub; + + @override + String title(BuildContext context, WindowEntry entry) => + hub.selected?.title ?? 'Terminal'; + + @override + Widget build(BuildContext context, WindowEntry entry) => ListenableBuilder( + listenable: Listenable.merge([hub, layout]), + builder: (context, _) => Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + TerminalTabStrip(hub: hub, layout: layout, cupertino: false), + Expanded(child: TerminalBody(hub: hub, cupertino: false)), + ], + ), + ); +} diff --git a/app/lib/shell/windows/window_manager.dart b/app/lib/shell/windows/window_manager.dart index 9c5a1167..f2fbd4a8 100644 --- a/app/lib/shell/windows/window_manager.dart +++ b/app/lib/shell/windows/window_manager.dart @@ -55,6 +55,16 @@ class WindowManager extends ChangeNotifier { .where((w) => _here(w) && w.kind == kind && w.contentId == contentId) .firstOrNull; + /// The frame the current server's window of [kind] for [contentId] has, + /// or had when it last closed. + Rect? lastFrame(String kind, String contentId) => + find(kind, contentId)?.frame ?? + _frames[windowFrameKey( + kind, + (kinds[kind]?.serverScoped ?? false) ? _server : null, + contentId, + )]; + Iterable inGroup(String groupId) => windows.where((w) => w.groupId == groupId); diff --git a/app/lib/ui/floating/floating_layer.dart b/app/lib/ui/floating/floating_layer.dart deleted file mode 100644 index 5176e868..00000000 --- a/app/lib/ui/floating/floating_layer.dart +++ /dev/null @@ -1,99 +0,0 @@ -import 'package:flutter/widgets.dart'; - -/// A layer of floating windows painted in the app's root overlay, above the -/// page, while it keeps its place in the tree (its inherited widgets, focus -/// and state stay where it is built). Every [FloatingLayer] shares that one -/// overlay. Only the terminal's floating window still uses it; the app's -/// other windows are in the shell's window host. -/// -/// [builder] returns the windows as [Positioned] children of a [Stack] the -/// size of [bounds]: this widget's own box, or the whole overlay when -/// [coverOverlay] is set. Space between windows takes no input. Without an -/// overlay (a bare widget test) the layer paints in place. -class FloatingLayer extends StatefulWidget { - const FloatingLayer({ - super.key, - required this.builder, - this.open = true, - this.coverOverlay = false, - }); - - final List Function(BuildContext context, Size bounds) builder; - - /// Turning true brings the layer to the top, as its window opens. - final bool open; - - final bool coverOverlay; - - @override - State createState() => _FloatingLayerState(); -} - -class _FloatingLayerState extends State { - final OverlayPortalController _portal = OverlayPortalController( - debugLabel: 'floating layer', - ); - - @override - void initState() { - super.initState(); - _portal.show(); - } - - @override - void didUpdateWidget(covariant FloatingLayer oldWidget) { - super.didUpdateWidget(oldWidget); - if (widget.open && !oldWidget.open) { - WidgetsBinding.instance.addPostFrameCallback((_) => _raise()); - } - } - - void _raise() { - if (mounted) _portal.show(); - } - - Widget _layer(BuildContext context, Size bounds) => Listener( - behavior: HitTestBehavior.deferToChild, - onPointerDown: (_) => _raise(), - child: Focus( - canRequestFocus: false, - skipTraversal: true, - onFocusChange: (focused) { - if (focused) _raise(); - }, - child: SizedBox.fromSize( - size: bounds, - child: Stack( - clipBehavior: Clip.none, - children: widget.builder(context, bounds), - ), - ), - ), - ); - - @override - Widget build(BuildContext context) { - if (Overlay.maybeOf(context, rootOverlay: true) == null) { - return LayoutBuilder( - builder: (context, constraints) => _layer(context, constraints.biggest), - ); - } - return OverlayPortal.overlayChildLayoutBuilder( - controller: _portal, - overlayLocation: OverlayChildLocation.rootOverlay, - overlayChildBuilder: (context, info) => widget.coverOverlay - ? Positioned.fill(child: _layer(context, info.overlaySize)) - : Positioned( - left: 0, - top: 0, - width: info.childSize.width, - height: info.childSize.height, - child: Transform( - transform: info.childPaintTransform, - child: _layer(context, info.childSize), - ), - ), - child: const SizedBox.expand(), - ); - } -} diff --git a/app/notes/floating-windows.md b/app/notes/floating-windows.md index 1af69a1d..068b4cd2 100644 --- a/app/notes/floating-windows.md +++ b/app/notes/floating-windows.md @@ -1,7 +1,8 @@ # Floating windows (window system core) Plan: `docs/plans/floating-windows.md`. The shell-level window system hosts -floating chats (`notes/chat-floating-pane.md`); the terminal moves in Phase 3. +floating chats (`notes/chat-floating-pane.md`) and the terminal's floating +mode (below). `FloatingLayer`, the overlay the old windows used, is gone. ## Pieces (`lib/shell/windows/`) @@ -63,3 +64,23 @@ Both are on the root navigator, so they are above every window, and the app's width decides (`usesDesktopPopups`), not the surface asking: content in a narrow window on a wide app still gets menus and dialogs. The probe window has `choice` and `details` buttons for captures. + +## Terminal window (Phase 3) + +`features/terminal/terminal_window.dart`: the `terminal` kind (one window for +the device, not a server) and `TerminalWindows`, which keeps it in step with +`TerminalLayout`. The layout stays the terminal's own state (shown, panel or +float, panel height); the bottom panel is still a shell panel. + +- Showing the terminal in float mode opens or shows the window; hiding it + (Alt+T, Ctrl+`, the options menu) minimises it. The window's Minimise and + Close both hide the terminal. Its shells and tabs live in `TerminalHub`, so + nothing is lost either way, and the window comes back where it was. +- The frame and maximised state are the window system's. The first window + takes the ones `pipelines.terminal-layout.v1` saved before; that record is + still written back unchanged. +- The window opens only after the manager has restored its saved windows. +- Captured 2026-11-11 at 1280x800 and 1920x1080, light and dark, over Chat and + over Runs: the window, its options menu, tooltips, a second tab, typing, + hide and show by Alt+T, maximise, move, minimise, and the frame after a + reload. diff --git a/app/test/features/terminal/terminal_app.dart b/app/test/features/terminal/terminal_app.dart index 332c25d1..cbfe0189 100644 --- a/app/test/features/terminal/terminal_app.dart +++ b/app/test/features/terminal/terminal_app.dart @@ -6,6 +6,11 @@ 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'; +import 'package:pipelines_app/features/terminal/terminal_window.dart'; +import 'package:pipelines_app/shell/windows/window_host.dart'; +import 'package:pipelines_app/shell/windows/window_kind.dart'; +import 'package:pipelines_app/shell/windows/window_layer.dart'; +import 'package:pipelines_app/shell/windows/window_manager.dart'; const appField = Key('app-field'); @@ -27,23 +32,78 @@ Future pumpTerminalApp( 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), - ), - ), + home: TerminalTestApp(hub: hub, layout: layout), ), ); await tester.pump(); } +/// The terminal surface around an app with a text field, with the app's +/// window system as the real app wires it: the terminal's floating mode is a +/// window in the host above the surface's stage. +class TerminalTestApp extends StatefulWidget { + const TerminalTestApp({ + super.key, + required this.hub, + required this.layout, + this.shortcutHere = true, + }); + + final TerminalHub hub; + final TerminalLayout layout; + final bool shortcutHere; + + @override + State createState() => TerminalTestAppState(); +} + +class TerminalTestAppState extends State { + final WindowManager manager = WindowManager(kinds: WindowKinds()); + late final TerminalWindows floating = TerminalWindows( + manager: manager, + hub: widget.hub, + layout: widget.layout, + ); + + @override + void initState() { + super.initState(); + floating + ..start() + ..ready(); + } + + @override + void dispose() { + floating.dispose(); + manager.dispose(); + super.dispose(); + } + + @override + Widget build(BuildContext context) => TerminalSurface( + hub: widget.hub, + layout: widget.layout, + cupertino: false, + shortcutHere: widget.shortcutHere, + floating: floating, + windows: WindowHost(manager: manager), + child: Scaffold( + appBar: AppBar( + title: const Text('App'), + actions: [ + TerminalToggleButton(layout: widget.layout, cupertino: false), + ], + ), + body: const TextField(key: appField), + ), + ); +} + +/// The test app's window manager. +WindowManager terminalWindowManager(WidgetTester tester) => + tester.state(find.byType(TerminalTestApp)).manager; + /// Presses [key] with [modifiers] held, then lets the motion finish unless /// [settle] is false. Future chord( @@ -102,4 +162,14 @@ bool appFieldFocused(WidgetTester tester) => tester .hasFocus; final Finder panelFinder = find.byKey(const ValueKey('terminal-panel')); -final Finder floatFinder = find.byKey(const ValueKey('terminal-float')); + +/// The terminal's floating window, shown or hiding. +final Finder floatLayer = find.byWidgetPredicate( + (w) => w is WindowLayer && w.entry.kind == terminalWindowKind, + skipOffstage: false, +); + +/// The terminal's floating window while it is shown. +final Finder floatFinder = find.byWidgetPredicate( + (w) => w is WindowLayer && w.entry.kind == terminalWindowKind && w.visible, +); diff --git a/app/test/features/terminal/terminal_motion_test.dart b/app/test/features/terminal/terminal_motion_test.dart index ae399040..381c4648 100644 --- a/app/test/features/terminal/terminal_motion_test.dart +++ b/app/test/features/terminal/terminal_motion_test.dart @@ -34,7 +34,13 @@ void main() { .opacity .value; ScaleTransition floatScale(WidgetTester tester) => tester.widget( - find.descendant(of: floatFinder, matching: find.byType(ScaleTransition)), + find + .descendant( + of: floatLayer, + matching: find.byType(ScaleTransition, skipOffstage: false), + skipOffstage: false, + ) + .first, ); testWidgets('the panel slides up from the bottom edge as the app above ' @@ -72,17 +78,19 @@ void main() { layout.setMode(TerminalMode.float); await pumpTerminalApp(tester, hub: hub, layout: layout); await altT(tester, settle: false); + // The window is built, then its motion starts. + await tester.pump(); 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); + // Hiding: no longer shown, still painted while it shrinks away. + expect(floatFinder, findsNothing); expect(floatScale(tester).scale.value, inExclusiveRange(0.92, 1)); await tester.pumpAndSettle(); expect(floatFinder, findsNothing); diff --git a/app/test/features/terminal/terminal_surface_test.dart b/app/test/features/terminal/terminal_surface_test.dart index 244230dc..fff954a5 100644 --- a/app/test/features/terminal/terminal_surface_test.dart +++ b/app/test/features/terminal/terminal_surface_test.dart @@ -5,13 +5,12 @@ import 'package:flutter/services.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:pipelines_app/features/chat/shell/chat_shell_terminal_keys.dart'; import 'package:pipelines_app/features/settings/settings_terminal_section.dart'; -import 'package:pipelines_app/features/terminal/terminal_float.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'; import 'package:xterm/xterm.dart'; +import 'terminal_app.dart'; import 'terminal_fixtures.dart'; void main() { @@ -43,19 +42,7 @@ void main() { addTearDown(tester.view.reset); await tester.pumpWidget( MaterialApp( - home: TerminalSurface( - hub: hub, - layout: layout, - cupertino: false, - shortcutHere: onChat, - child: Scaffold( - appBar: AppBar( - title: const Text('App'), - actions: [TerminalToggleButton(layout: layout, cupertino: false)], - ), - body: const TextField(key: Key('app-field')), - ), - ), + home: TerminalTestApp(hub: hub, layout: layout, shortcutHere: onChat), ), ); await tester.pump(); @@ -133,47 +120,85 @@ void main() { ); desktopTestWidgets( - 'the floating window moves, resizes, minimises and maximises', + 'the floating terminal is a window: it moves, resizes, maximises, and ' + 'Minimise and Close hide the terminal', (tester) async { layout ..setMode(TerminalMode.float) ..show(); await pumpApp(tester); - await tester.pump(); - final window = find.byKey(const ValueKey('terminal-float')); - expect(window, findsOneWidget); - final start = layout.floatRect; + await tester.pumpAndSettle(); + expect(floatFinder, findsOneWidget); + final manager = terminalWindowManager(tester); + Rect frame() => manager.windows.single.frame; + expect(frame(), terminalFloatDefaultRect); + final start = frame(); await tester.drag( - find.byKey(const ValueKey('terminal-float-title')), + find.byKey(const ValueKey('window-title')), const Offset(60, 40), ); await tester.pumpAndSettle(); - expect(layout.floatRect.topLeft, start.topLeft + const Offset(60, 40)); + expect(frame().topLeft, start.topLeft + const Offset(60, 40)); await tester.drag( - find.byKey(const ValueKey('terminal-float-resize')), + find.byKey(const ValueKey('window-resize')), const Offset(80, 50), ); await tester.pumpAndSettle(); - expect(layout.floatRect.size, start.size + const Offset(80, 50)); - expect(saved()['float'][2], closeTo(start.width + 80, 1)); - await tester.tap(find.byTooltip('Minimise')); - await tester.pumpAndSettle(); - expect(find.byType(TerminalView), findsNothing); - expect(hub.tabs, hasLength(2)); - await tester.tap(find.byTooltip('Restore')); - await tester.pumpAndSettle(); + expect(frame().size, start.size + const Offset(80, 50)); + // The window shows the terminal's tabs and the selected terminal. + expect(find.text('src'), findsWidgets); expect(find.byType(TerminalView), findsOneWidget); + await tester.tap(find.byTooltip('Maximise')); await tester.pumpAndSettle(); - expect( - tester.getRect( - find.descendant(of: window, matching: find.byType(Material)).first, - ), - const Rect.fromLTWH(0, 0, 1200, 800).deflate(terminalFloatMargin), - ); + expect(manager.windows.single.maximized, isTrue); await tester.tap(find.byTooltip('Restore size')); await tester.pumpAndSettle(); - expect(layout.maximized, isFalse); + + // Minimise hides the terminal; the toggle brings the window back + // where it was, with its shells. + await tester.tap(find.byTooltip('Minimise')); + await tester.pumpAndSettle(); + expect(layout.visible, isFalse); + expect(floatFinder, findsNothing); + expect(hub.tabs, hasLength(2)); + await ctrlBacktick(tester); + expect(layout.visible, isTrue); + expect(floatFinder, findsOneWidget); + expect(frame().size, start.size + const Offset(80, 50)); + + await tester.tap(find.byTooltip('Close')); + await tester.pumpAndSettle(); + expect(layout.visible, isFalse); + expect(manager.windows, isEmpty); + expect(hub.tabs, hasLength(2)); + await ctrlBacktick(tester); + expect(floatFinder, findsOneWidget); + expect(frame().size, start.size + const Offset(80, 50)); + }, + ); + + desktopTestWidgets( + 'the first window takes the frame the terminal saved before windows', + (tester) async { + store.saved = jsonEncode({ + 'mode': 'float', + 'visible': true, + 'panel_height': 300, + 'float': [200, 150, 640, 360], + 'minimized': false, + 'maximized': true, + }); + await layout.restore(); + await pumpApp(tester); + await tester.pumpAndSettle(); + final entry = terminalWindowManager(tester).windows.single; + expect(entry.frame, const Rect.fromLTWH(200, 150, 640, 360)); + expect(entry.maximized, isTrue); + // The old record is still written, unchanged, for an older build. + layout.hide(); + await tester.pumpAndSettle(); + expect(saved()['float'], [200, 150, 640, 360]); }, ); @@ -209,14 +234,14 @@ void main() { await tester.tap(find.byKey(const ValueKey('terminal-mode-float'))); await tester.pumpAndSettle(); expect(layout.mode, TerminalMode.float); - expect(find.byKey(const ValueKey('terminal-float')), findsOneWidget); + expect(floatFinder, findsOneWidget); expect(find.byKey(const ValueKey('terminal-panel')), findsNothing); expect(saved()['mode'], 'float'); await tester.tap(find.byTooltip('Terminal options')); await tester.pumpAndSettle(); await tester.tap(find.byKey(const ValueKey('terminal-hide'))); await tester.pumpAndSettle(); - expect(find.byKey(const ValueKey('terminal-float')), findsNothing); + expect(floatFinder, findsNothing); }); desktopTestWidgets('Settings chooses the mode', (tester) async { diff --git a/app/test/ui/floating/floating_layer_test.dart b/app/test/ui/floating/floating_layer_test.dart deleted file mode 100644 index 69148e4a..00000000 --- a/app/test/ui/floating/floating_layer_test.dart +++ /dev/null @@ -1,80 +0,0 @@ -import 'package:flutter/material.dart'; -import 'package:flutter_test/flutter_test.dart'; -import 'package:pipelines_app/ui/floating/floating_layer.dart'; - -void main() { - testWidgets('the layer last pressed or focused paints on top', ( - tester, - ) async { - tester.view.physicalSize = const Size(800, 600); - tester.view.devicePixelRatio = 1; - addTearDown(tester.view.reset); - final hits = []; - final focus = FocusNode(); - addTearDown(focus.dispose); - Widget window(String name, double left, {FocusNode? node}) => Positioned( - left: left, - top: 100, - width: 200, - height: 200, - child: Focus( - focusNode: node, - child: GestureDetector( - behavior: HitTestBehavior.opaque, - onTap: () => hits.add(name), - child: const SizedBox.expand(), - ), - ), - ); - var behind = 0; - await tester.pumpWidget( - MaterialApp( - home: Scaffold( - body: Stack( - children: [ - Positioned.fill( - child: GestureDetector( - onTap: () => behind++, - child: const ColoredBox(color: Colors.white), - ), - ), - // Nested inside a page, like the chat workspace. - Positioned.fill( - child: FloatingLayer( - coverOverlay: true, - builder: (context, bounds) => [ - window('chat', 100, node: focus), - ], - ), - ), - Positioned.fill( - child: FloatingLayer( - builder: (context, bounds) => [window('terminal', 200)], - ), - ), - ], - ), - ), - ), - ); - const overlap = Offset(250, 200); - await tester.tapAt(overlap); - expect(hits.last, 'terminal'); - await tester.tapAt(const Offset(120, 200)); - await tester.pump(); - await tester.tapAt(overlap); - expect(hits.last, 'chat'); - await tester.tapAt(const Offset(380, 200)); - await tester.pump(); - await tester.tapAt(overlap); - expect(hits.last, 'terminal'); - focus.requestFocus(); - await tester.pump(); - await tester.pump(); - await tester.tapAt(overlap); - expect(hits.last, 'chat'); - // Space between windows passes through to the page. - await tester.tapAt(const Offset(700, 500)); - expect(behind, 1); - }); -}