From a99f7014f5934ea7ebc0f29364a02ec360f3899e Mon Sep 17 00:00:00 2001 From: Alan Silva Date: Tue, 10 Nov 2026 20:48:31 +0000 Subject: [PATCH] Add the shell window host with layering acceptance tests Phase 1.3 and 1.4 of docs/plans/floating-windows.md. Windows are plain children of the terminal stage's stack in the shell page, outside every destination, so popups opened from one are above all of them. Each window has its own page navigator: pushed pages open inside the window, and popup routes go to the root navigator. One WindowFrame chrome (move, resize, minimise, maximise, close), a focus scope per window, a ScaffoldMessenger per window. No feature uses it yet. The capture fixture opens probe windows with ?windows=N, and window_layering_test.dart covers every popup type from a window over Chat and over another destination. --- app/lib/application/app_terminals.dart | 5 +- app/lib/application/app_windows.dart | 14 + app/lib/application/pipelines_app.dart | 13 + app/lib/features/terminal/terminal_stage.dart | 6 + .../features/terminal/terminal_surface.dart | 5 + app/lib/shell/windows/window_focus.dart | 77 +++++ app/lib/shell/windows/window_frame.dart | 160 +++++++++++ app/lib/shell/windows/window_host.dart | 108 +++++++ app/lib/shell/windows/window_layer.dart | 263 ++++++++++++++++++ app/lib/shell/windows/window_manager.dart | 6 +- app/lib/shell/windows/window_navigator.dart | 180 ++++++++++++ app/lib/shell/windows/window_scope.dart | 35 +++ app/lib/shell/windows/window_store.dart | 7 +- app/notes/floating-windows.md | 51 ++++ app/test/shell/windows/window_host_test.dart | 249 +++++++++++++++++ .../shell/windows/window_layering_test.dart | 242 ++++++++++++++++ app/test/shell/windows/window_store_test.dart | 12 +- .../shell/windows/window_test_harness.dart | 79 ++++++ app/tool/capture/window_probe.dart | 161 +++++++++++ app/tool/search_selection_probe_entry.dart | 9 +- 20 files changed, 1666 insertions(+), 16 deletions(-) create mode 100644 app/lib/application/app_windows.dart create mode 100644 app/lib/shell/windows/window_focus.dart create mode 100644 app/lib/shell/windows/window_frame.dart create mode 100644 app/lib/shell/windows/window_host.dart create mode 100644 app/lib/shell/windows/window_layer.dart create mode 100644 app/lib/shell/windows/window_navigator.dart create mode 100644 app/lib/shell/windows/window_scope.dart create mode 100644 app/notes/floating-windows.md create mode 100644 app/test/shell/windows/window_host_test.dart create mode 100644 app/test/shell/windows/window_layering_test.dart create mode 100644 app/test/shell/windows/window_test_harness.dart create mode 100644 app/tool/capture/window_probe.dart diff --git a/app/lib/application/app_terminals.dart b/app/lib/application/app_terminals.dart index 97e74353..77e55fd7 100644 --- a/app/lib/application/app_terminals.dart +++ b/app/lib/application/app_terminals.dart @@ -38,18 +38,21 @@ class AppTerminals { final TerminalLayout layout; late final TerminalHub hub; - /// [shell] with the terminal panel, window or page around it. + /// [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 /// Chat tab only. Widget surround( Widget shell, { required bool cupertino, bool onChat = true, + Widget? windows, }) => TerminalSurface( hub: hub, layout: layout, cupertino: cupertino, shortcutHere: onChat, + windows: windows, child: shell, ); diff --git a/app/lib/application/app_windows.dart b/app/lib/application/app_windows.dart new file mode 100644 index 00000000..d69c036c --- /dev/null +++ b/app/lib/application/app_windows.dart @@ -0,0 +1,14 @@ +import '../shell/windows/window_kind.dart'; +import '../shell/windows/window_manager.dart'; +import '../shell/windows/window_store.dart'; + +/// The app's floating windows, for the app's lifetime: the kinds features +/// register at start and the one manager the shell's window host draws. +abstract final class AppWindows { + static final WindowKinds kinds = WindowKinds(); + + static final WindowManager manager = WindowManager( + kinds: kinds, + store: const SharedPreferencesWindowStore(), + ); +} diff --git a/app/lib/application/pipelines_app.dart b/app/lib/application/pipelines_app.dart index dc3c9ed8..ce722efc 100644 --- a/app/lib/application/pipelines_app.dart +++ b/app/lib/application/pipelines_app.dart @@ -34,7 +34,10 @@ import '../features/updates/launch_update_dialog.dart'; import '../features/updates/web_release.dart'; import '../features/settings/server_connections.dart'; import 'app.dart'; +import '../shell/windows/window_host.dart'; +import '../shell/windows/window_manager.dart'; import 'app_terminals.dart'; +import 'app_windows.dart'; import '../features/terminal/terminal_layout.dart'; import 'app_route.dart'; import 'app_router.dart'; @@ -88,12 +91,16 @@ class PipelinesApp extends StatefulWidget { this.webRefresher = refreshWebPage, this.tabLocationsStore, this.terminalLayout, + this.windows, }); final TabLocationsStore? tabLocationsStore; /// The terminal surface's saved layout; null is the device's own. final TerminalLayout? terminalLayout; + + /// The floating windows; the app's own ([AppWindows.manager]) when null. + final WindowManager? windows; final ServerEndpoint server; final PipelinesClient? client; final bool? cupertino; @@ -208,6 +215,7 @@ class _PipelinesAppState extends State ); NotificationServiceHandoff? _deliveryHandoff; late final AppTerminals _terminals; + late final WindowManager _windows; @override void initState() { @@ -227,6 +235,10 @@ class _PipelinesAppState extends State ); bindServerIdentity(_session.gateway, widget.serverId); bindServerIdentity(_session.client, widget.serverId); + // One server for now: windows are kept per server, and this one's show. + _windows = (widget.windows ?? AppWindows.manager) + ..server = widget.serverId ?? 'server'; + unawaited(_windows.restore()); _terminals = AppTerminals( pool: widget.chatPool, connection: _session, @@ -729,6 +741,7 @@ class _PipelinesAppState extends State _shellFor(route, count), cupertino: _cupertino, onChat: route.kind == AppRouteKind.chat, + windows: WindowHost(manager: _windows), ), ); diff --git a/app/lib/features/terminal/terminal_stage.dart b/app/lib/features/terminal/terminal_stage.dart index 8e5240b1..0cf37db4 100644 --- a/app/lib/features/terminal/terminal_stage.dart +++ b/app/lib/features/terminal/terminal_stage.dart @@ -21,6 +21,7 @@ class TerminalStage extends StatelessWidget { required this.reveal, required this.focus, required this.child, + this.windows, }); final TerminalHub hub; @@ -31,6 +32,10 @@ class TerminalStage extends StatelessWidget { final FocusScopeNode focus; final Widget child; + /// The app's floating windows, above the app and the panel in this one + /// stack. It takes no input between windows. + final Widget? windows; + static final Tween _fade = Tween(begin: 0.4, end: 1); @override @@ -102,6 +107,7 @@ class TerminalStage extends StatelessWidget { ], ), ), + 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 47d615df..99d63140 100644 --- a/app/lib/features/terminal/terminal_surface.dart +++ b/app/lib/features/terminal/terminal_surface.dart @@ -33,6 +33,7 @@ class TerminalSurface extends StatefulWidget { required this.cupertino, required this.child, this.shortcutHere = true, + this.windows, }); final TerminalHub hub; @@ -44,6 +45,9 @@ class TerminalSurface extends StatefulWidget { /// terminal (the app shows it on Chat only). final bool shortcutHere; + /// The app's floating windows (see [TerminalStage.windows]). + final Widget? windows; + @override State createState() => _TerminalSurfaceState(); } @@ -228,6 +232,7 @@ class _TerminalSurfaceState extends State present: !_narrow && (widget.layout.visible || !_reveal.isDismissed), reveal: _curve, focus: _focus.scope, + windows: widget.windows, child: _withShortcut(child!), ), child: widget.child, diff --git a/app/lib/shell/windows/window_focus.dart b/app/lib/shell/windows/window_focus.dart new file mode 100644 index 00000000..8be7d9ca --- /dev/null +++ b/app/lib/shell/windows/window_focus.dart @@ -0,0 +1,77 @@ +import 'package:flutter/widgets.dart'; + +/// The floating windows' keyboard focus: each window has a focus scope; the +/// window that shows or comes to the top takes the keyboard, and when the +/// last one hides it goes back to what had it before (a composer, a field), +/// else to the screen. +class WindowFocus { + final Map _scopes = {}; + FocusNode? _previous; + + FocusScopeNode scopeFor(String id) => + _scopes[id] ??= FocusScopeNode(debugLabel: 'window $id'); + + /// Forgets the scopes of windows no longer in [ids]. + void retain(Set ids) { + for (final id in _scopes.keys.where((id) => !ids.contains(id)).toList()) { + _scopes.remove(id)!.dispose(); + } + } + + bool _within(FocusNode node, FocusScopeNode scope) => + identical(node, scope) || node.ancestors.contains(scope); + + /// Whether [id]'s window has the keyboard. + bool has(String id) { + final current = FocusManager.instance.primaryFocus; + final scope = _scopes[id]; + return current != null && scope != null && _within(current, scope); + } + + /// The window that has the keyboard, if one does. + String? get focused => _scopes.keys.where(has).firstOrNull; + + /// Notes what has the keyboard now, before a window takes it. + void remember() { + final current = FocusManager.instance.primaryFocus; + if (current == null || focused != null) return; + _previous = identical(current, FocusManager.instance.rootScope) + ? null + : current; + } + + /// Focuses [id]'s window once this frame has built it. + void focusSoon(String id) { + WidgetsBinding.instance + ..addPostFrameCallback((_) { + final scope = _scopes[id]; + if (scope != null && scope.context != null && scope.canRequestFocus) { + scope.requestFocus(); + } + }) + ..ensureVisualUpdate(); + } + + /// Gives the keyboard back to what had it before the windows showed, if + /// a window has it now. + void release() { + final previous = _previous; + _previous = null; + final current = FocusManager.instance.primaryFocus; + if (current == null || focused == null) return; + if (previous != null && + previous.context != null && + previous.canRequestFocus) { + previous.requestFocus(); + } else { + current.unfocus(); + } + } + + void dispose() { + for (final scope in _scopes.values) { + scope.dispose(); + } + _scopes.clear(); + } +} diff --git a/app/lib/shell/windows/window_frame.dart b/app/lib/shell/windows/window_frame.dart new file mode 100644 index 00000000..79789dc4 --- /dev/null +++ b/app/lib/shell/windows/window_frame.dart @@ -0,0 +1,160 @@ +import 'package:flutter/gestures.dart'; +import 'package:flutter/material.dart'; + +import 'window_kind.dart'; + +const double windowCornerRadius = 12; + +/// The height of a window's title bar: a compact row of icon buttons, taller +/// with larger text. +double windowTitleBarHeight(BuildContext context) => + MediaQuery.textScalerOf(context).scale(40).clamp(40.0, 64.0); + +/// A floating window's card and title bar: the title (drag to move, double +/// click to maximise), the kind's actions, then Minimise, Maximise and +/// Close. The content is drawn over the card's body by the window's +/// navigator. +class WindowFrame extends StatelessWidget { + const WindowFrame({ + super.key, + required this.title, + required this.icon, + required this.actions, + required this.maximized, + required this.onMove, + required this.onMoveEnd, + required this.onMinimize, + required this.onToggleMaximized, + required this.onClose, + }); + + final String title; + final IconData icon; + final List actions; + final bool maximized; + final ValueChanged onMove; + final VoidCallback onMoveEnd; + final VoidCallback onMinimize; + final VoidCallback onToggleMaximized; + final VoidCallback onClose; + + @override + Widget build(BuildContext context) { + final theme = Theme.of(context); + final colors = theme.colorScheme; + return Material( + elevation: 8, + clipBehavior: Clip.antiAlias, + borderRadius: BorderRadius.circular(windowCornerRadius), + color: colors.surfaceContainer, + child: Align( + alignment: Alignment.topCenter, + child: SizedBox( + height: windowTitleBarHeight(context), + child: IconButtonTheme( + data: IconButtonThemeData( + style: IconButton.styleFrom( + visualDensity: VisualDensity.compact, + foregroundColor: colors.onSurfaceVariant, + ), + ), + child: Row( + children: [ + Expanded(child: _title(theme)), + for (final action in actions) + IconButton( + tooltip: action.label, + onPressed: action.onPressed, + icon: Icon(action.icon), + ), + IconButton( + tooltip: 'Minimise', + onPressed: onMinimize, + icon: const Icon(Icons.minimize), + ), + IconButton( + tooltip: maximized ? 'Restore size' : 'Maximise', + onPressed: onToggleMaximized, + icon: Icon( + maximized ? Icons.fullscreen_exit : Icons.fullscreen, + ), + ), + IconButton( + tooltip: 'Close', + onPressed: onClose, + icon: const Icon(Icons.close), + ), + const SizedBox(width: 4), + ], + ), + ), + ), + ), + ); + } + + Widget _title(ThemeData theme) => MouseRegion( + cursor: maximized ? SystemMouseCursors.basic : SystemMouseCursors.move, + child: GestureDetector( + key: const ValueKey('window-title'), + behavior: HitTestBehavior.opaque, + // The window follows the pointer from where it went down. + dragStartBehavior: DragStartBehavior.down, + onPanUpdate: maximized ? null : (details) => onMove(details.delta), + onPanEnd: maximized ? null : (_) => onMoveEnd(), + onDoubleTap: onToggleMaximized, + child: Padding( + padding: const EdgeInsetsDirectional.only(start: 12, end: 8), + child: Row( + children: [ + Icon(icon, size: 18, color: theme.colorScheme.onSurfaceVariant), + const SizedBox(width: 8), + Expanded( + child: Text( + title, + maxLines: 1, + overflow: TextOverflow.ellipsis, + style: theme.textTheme.titleSmall, + ), + ), + ], + ), + ), + ), + ); +} + +/// The lower right corner of a window: drag to resize. +class WindowResizeCorner extends StatelessWidget { + const WindowResizeCorner({ + super.key, + required this.onResize, + required this.onResizeEnd, + }); + + final ValueChanged onResize; + final VoidCallback onResizeEnd; + + @override + Widget build(BuildContext context) => Semantics( + label: 'Resize window', + child: MouseRegion( + cursor: SystemMouseCursors.resizeDownRight, + child: GestureDetector( + key: const ValueKey('window-resize'), + behavior: HitTestBehavior.opaque, + dragStartBehavior: DragStartBehavior.down, + onPanUpdate: (details) => onResize(details.delta), + onPanEnd: (_) => onResizeEnd(), + child: Padding( + padding: const EdgeInsets.all(2), + child: Icon( + Icons.south_east, + size: 16, + color: Theme.of(context).colorScheme.onSurfaceVariant, + ), + ), + ), + ), + ); +} diff --git a/app/lib/shell/windows/window_host.dart b/app/lib/shell/windows/window_host.dart new file mode 100644 index 00000000..c7f2a561 --- /dev/null +++ b/app/lib/shell/windows/window_host.dart @@ -0,0 +1,108 @@ +import 'package:flutter/material.dart'; + +import 'window_focus.dart'; +import 'window_layer.dart'; +import 'window_manager.dart'; + +/// The app's floating windows, drawn in the shell page above the +/// destinations and the terminal panel: plain children of one stack, in the +/// manager's order (the last pressed, focused or opened on top). +/// +/// Because the windows are part of the shell page rather than an overlay +/// above it, every popup opened from one (a sheet, dialog, menu or dropdown +/// on the root navigator; a tooltip in the page's overlay) is drawn above +/// all of them. A window is built whatever destination shows, so its +/// tickers, focus and semantics never depend on a hidden tab. +/// +/// The host fills its parent and takes no input between windows. +class WindowHost extends StatefulWidget { + const WindowHost({super.key, required this.manager}); + + final WindowManager manager; + + @override + State createState() => _WindowHostState(); +} + +class _WindowHostState extends State { + final WindowFocus _focus = WindowFocus(); + Set _visible = const {}; + String? _active; + + @override + void initState() { + super.initState(); + widget.manager.addListener(_changed); + WidgetsBinding.instance.addPostFrameCallback((_) => _changed()); + } + + @override + void didUpdateWidget(covariant WindowHost oldWidget) { + super.didUpdateWidget(oldWidget); + if (oldWidget.manager != widget.manager) { + oldWidget.manager.removeListener(_changed); + widget.manager.addListener(_changed); + _changed(); + } + } + + @override + void dispose() { + widget.manager.removeListener(_changed); + _focus.dispose(); + super.dispose(); + } + + /// Moves the keyboard with the windows: a window that shows or comes to + /// the top takes it; when the window that had it hides, the next one down + /// takes it, and after the last one it returns to where it was. + void _changed() { + if (!mounted) return; + final manager = widget.manager; + final visible = { + for (final w in manager.windows) + if (manager.isVisible(w)) w.id, + }; + final active = manager.active?.id; + final focused = _focus.focused; + if (_visible.isEmpty && visible.isNotEmpty) _focus.remember(); + if (active == null) { + if (_visible.isNotEmpty) _focus.release(); + } else if (active != _active || !_visible.contains(active)) { + _focus.focusSoon(active); + } else if (focused != null && !visible.contains(focused)) { + _focus.focusSoon(active); + } + _visible = visible; + _active = active; + setState(() {}); + } + + @override + Widget build(BuildContext context) { + final manager = widget.manager; + final windows = manager.windows; + _focus.retain({for (final w in windows) w.id}); + return LayoutBuilder( + builder: (context, constraints) { + final bounds = constraints.biggest; + return Stack( + fit: StackFit.expand, + children: [ + for (final entry in windows) + if (manager.kinds[entry.kind] case final kind?) + WindowLayer( + key: ValueKey(entry.id), + manager: manager, + kind: kind, + entry: entry, + visible: manager.isVisible(entry), + bounds: bounds, + focus: _focus, + ), + ], + ); + }, + ); + } +} diff --git a/app/lib/shell/windows/window_layer.dart b/app/lib/shell/windows/window_layer.dart new file mode 100644 index 00000000..b30e78b8 --- /dev/null +++ b/app/lib/shell/windows/window_layer.dart @@ -0,0 +1,263 @@ +import 'dart:async'; + +import 'package:flutter/material.dart'; + +import '../../ui/motion/motion.dart'; +import '../../ui/motion/surface_visibility.dart'; +import 'window_entry.dart'; +import 'window_focus.dart'; +import 'window_frame.dart'; +import 'window_kind.dart'; +import 'window_manager.dart'; +import 'window_navigator.dart'; +import 'window_scope.dart'; + +/// One window in the host: its card and title bar, its page navigator over +/// the card's body, and its resize corner, with the grow-and-fade motion as +/// it shows and hides. A hidden window stays built (its content keeps its +/// state) but is not painted and takes no input or focus. +class WindowLayer extends StatefulWidget { + const WindowLayer({ + super.key, + required this.manager, + required this.kind, + required this.entry, + required this.visible, + required this.bounds, + required this.focus, + }); + + final WindowManager manager; + final WindowKind kind; + final WindowEntry entry; + final bool visible; + final Size bounds; + final WindowFocus focus; + + /// The scale a window grows from as it shows. + static const double revealScale = 0.92; + + @override + State createState() => _WindowLayerState(); +} + +class _WindowLayerState extends State + with SingleTickerProviderStateMixin { + late final AnimationController _reveal = AnimationController( + vsync: this, + duration: Motion.standard, + ); + late final CurvedAnimation _curve = CurvedAnimation( + parent: _reveal, + curve: Motion.curve, + reverseCurve: Curves.easeInCubic, + ); + final GlobalKey _navigator = GlobalKey(); + late final LocalKey _rootPage = ValueKey('window-root-${widget.entry.id}'); + + String get _id => widget.entry.id; + + @override + void initState() { + super.initState(); + if (widget.visible) { + WidgetsBinding.instance.addPostFrameCallback((_) => _run()); + } + } + + @override + void didUpdateWidget(covariant WindowLayer oldWidget) { + super.didUpdateWidget(oldWidget); + if (oldWidget.visible != widget.visible) _run(); + } + + void _run() { + if (!mounted) return; + _reveal.duration = Motion.of(context, Motion.standard); + unawaited(widget.visible ? _reveal.forward() : _reveal.reverse()); + } + + @override + void dispose() { + _curve.dispose(); + _reveal.dispose(); + super.dispose(); + } + + Rect get _frame => + drawnWindowFrame(widget.entry, widget.bounds, widget.kind.minSize); + + /// The frame now: several drag events can arrive before a rebuild. + Rect get _current { + final entry = widget.manager.byId(_id) ?? widget.entry; + return drawnWindowFrame(entry, widget.bounds, widget.kind.minSize); + } + + void _move(Offset delta) => widget.manager.setFrame( + _id, + fitWindowFrame(_current.shift(delta), widget.bounds, widget.kind.minSize), + save: false, + ); + + void _resize(Offset delta) { + final rect = _current; + widget.manager.setFrame( + _id, + fitWindowFrame( + Rect.fromLTWH( + rect.left, + rect.top, + rect.width + delta.dx, + rect.height + delta.dy, + ), + widget.bounds, + widget.kind.minSize, + ), + save: false, + ); + } + + void _pressed() { + widget.manager.raise(_id); + if (!widget.focus.has(_id)) widget.focus.focusSoon(_id); + } + + @override + Widget build(BuildContext context) { + final manager = widget.manager; + final entry = widget.entry; + final kind = widget.kind; + final frame = _frame; + final titleHeight = windowTitleBarHeight(context).clamp(0.0, frame.height); + final body = Rect.fromLTRB( + frame.left, + frame.top + titleHeight, + frame.right, + frame.bottom, + ); + final title = kind.title(context, entry); + final hiding = !widget.visible; + final content = Stack( + fit: StackFit.expand, + children: [ + Positioned.fromRect( + rect: frame, + child: Semantics( + container: true, + explicitChildNodes: true, + label: 'Window: $title', + identifier: 'window-${entry.kind}', + child: WindowFrame( + title: title, + icon: kind.icon, + actions: kind.actions(context, entry), + maximized: entry.maximized, + onMove: _move, + onMoveEnd: manager.commit, + onMinimize: () => manager.setMinimized(_id, true), + onToggleMaximized: () => + manager.setMaximized(_id, !entry.maximized), + onClose: () => manager.close(_id), + ), + ), + ), + WindowHitRegion( + region: body, + // Its own semantics container: a route's barrier hides what is + // painted before it in its container, which must not be the + // title bar or the app. + child: Semantics( + container: true, + explicitChildNodes: true, + child: WindowScope( + manager: manager, + entry: entry, + body: body, + child: ScaffoldMessenger( + child: WindowNavigator.theme( + context, + child: WindowNavigator( + key: _navigator, + pages: [ + MaterialPage( + key: _rootPage, + child: _WindowContent(kind: kind), + ), + ], + onDidRemovePage: (_) {}, + ), + ), + ), + ), + ), + ), + if (!entry.maximized) + Positioned( + right: widget.bounds.width - frame.right, + bottom: widget.bounds.height - frame.bottom, + child: WindowResizeCorner( + onResize: _resize, + onResizeEnd: manager.commit, + ), + ), + ], + ); + final center = widget.bounds.center(Offset.zero); + return AnimatedBuilder( + animation: _reveal, + builder: (context, child) { + final offstage = hiding && _reveal.isDismissed; + return Offstage( + offstage: offstage, + child: TickerMode( + enabled: !offstage, + child: SurfaceVisibility( + shown: !offstage, + current: !hiding, + child: IgnorePointer( + ignoring: hiding, + child: ExcludeFocus(excluding: hiding, child: child!), + ), + ), + ), + ); + }, + child: FadeTransition( + opacity: _curve, + child: ScaleTransition( + scale: Tween( + begin: WindowLayer.revealScale, + end: 1, + ).animate(_curve), + // Grows from the window's own centre, not the host's. + alignment: Alignment( + center.dx == 0 ? 0 : (frame.center.dx - center.dx) / center.dx, + center.dy == 0 ? 0 : (frame.center.dy - center.dy) / center.dy, + ), + child: Listener( + behavior: HitTestBehavior.deferToChild, + onPointerDown: (_) => _pressed(), + child: FocusScope( + node: widget.focus.scopeFor(_id), + onFocusChange: (focused) { + if (focused) manager.raise(_id); + }, + child: content, + ), + ), + ), + ), + ); + } +} + +/// The kind's content, rebuilt with the window's current entry. +class _WindowContent extends StatelessWidget { + const _WindowContent({required this.kind}); + + final WindowKind kind; + + @override + Widget build(BuildContext context) => + kind.build(context, WindowScope.of(context).entry); +} diff --git a/app/lib/shell/windows/window_manager.dart b/app/lib/shell/windows/window_manager.dart index a6e5249b..9c5a1167 100644 --- a/app/lib/shell/windows/window_manager.dart +++ b/app/lib/shell/windows/window_manager.dart @@ -172,10 +172,8 @@ class WindowManager extends ChangeNotifier { void setMinimized(String id, bool minimized) => _replace(id, (w) => w.copyWith(minimized: minimized)); - void setMaximized(String id, bool maximized) => _replace( - id, - (w) => w.copyWith(maximized: maximized, minimized: false), - ); + void setMaximized(String id, bool maximized) => + _replace(id, (w) => w.copyWith(maximized: maximized, minimized: false)); /// Replaces what [id] shows (a chat that moved to a new session). void setContent(String id, String contentId, {Map? data}) => diff --git a/app/lib/shell/windows/window_navigator.dart b/app/lib/shell/windows/window_navigator.dart new file mode 100644 index 00000000..5d594c2c --- /dev/null +++ b/app/lib/shell/windows/window_navigator.dart @@ -0,0 +1,180 @@ +import 'package:flutter/material.dart'; +import 'package:flutter/rendering.dart'; + +import 'window_frame.dart' show windowCornerRadius; +import 'window_scope.dart'; + +/// A floating window's own page stack. Pages pushed from the window's +/// content (`Navigator.of(context).push`) open inside the window, with Back +/// inside it. Transient routes (sheets, dialogs, popup menus, dropdowns) go +/// to the app's root navigator instead, so they open above every window and +/// are never clipped to this one. +/// +/// The navigator itself covers the whole window host, sharing the root +/// navigator's coordinates (a popup anchored to a button measures against +/// its navigator) and letting tooltips paint outside the window. Each page +/// is drawn inside the window's content area by [WindowPageBox], and only +/// that area takes input. +class WindowNavigator extends Navigator { + const WindowNavigator({super.key, super.pages, super.onDidRemovePage}); + + /// [child] with page transitions that keep every `MaterialPageRoute` of a + /// window navigator below it inside the window's content area. + static Widget theme(BuildContext context, {required Widget child}) { + final theme = Theme.of(context); + final builders = theme.pageTransitionsTheme.builders; + return Theme( + data: theme.copyWith( + pageTransitionsTheme: PageTransitionsTheme( + builders: { + for (final platform in TargetPlatform.values) + platform: _WindowPageTransitions( + builders[platform] ?? const ZoomPageTransitionsBuilder(), + ), + }, + ), + ), + child: child, + ); + } + + @override + NavigatorState createState() => _WindowNavigatorState(); +} + +class _WindowNavigatorState extends NavigatorState { + /// Transient routes this window sent to the root navigator and that are + /// still open. + final List> _popups = []; + + NavigatorState? get _root => + context.findRootAncestorStateOfType(); + + @override + Future push(Route route) { + final root = _root; + if (route is! PopupRoute || root == null) { + assert( + route is PopupRoute || route is MaterialPageRoute, + 'A window page must be a MaterialPageRoute to be drawn inside its ' + 'window: ${route.runtimeType}', + ); + return super.push(route); + } + _popups.add(route); + return root.push(route).whenComplete(() => _popups.remove(route)); + } + + /// Content that closes its own sheet or menu with this navigator closes + /// the popup, not the window's page. + @override + void pop([T? result]) { + final root = _root; + if (root != null && (_popups.isNotEmpty || !canPop())) { + if (_popups.isNotEmpty) root.pop(result); + return; + } + super.pop(result); + } +} + +class _WindowPageTransitions extends PageTransitionsBuilder { + const _WindowPageTransitions(this.inner); + + final PageTransitionsBuilder inner; + + @override + Duration get transitionDuration => inner.transitionDuration; + + @override + Duration get reverseTransitionDuration => inner.reverseTransitionDuration; + + @override + Widget buildTransitions( + PageRoute route, + BuildContext context, + Animation animation, + Animation secondaryAnimation, + Widget child, + ) => WindowPageBox( + child: inner.buildTransitions( + route, + context, + animation, + secondaryAnimation, + child, + ), + ); +} + +/// One page of a window, drawn inside the window's content area: clipped to +/// it, sized by it (so layout that reads [MediaQuery] sees the window, not +/// the app), with a transparent [Scaffold] for the window's SnackBars. +class WindowPageBox extends StatelessWidget { + const WindowPageBox({super.key, required this.child}); + + final Widget child; + + @override + Widget build(BuildContext context) { + final scope = WindowScope.maybeOf(context); + if (scope == null) return child; + final body = scope.body; + const radius = Radius.circular(windowCornerRadius); + return Stack( + children: [ + Positioned.fromRect( + rect: body, + child: ClipRRect( + borderRadius: const BorderRadius.only( + bottomLeft: radius, + bottomRight: radius, + ), + child: MediaQuery( + data: MediaQuery.of(context).copyWith( + size: body.size, + padding: EdgeInsets.zero, + viewPadding: EdgeInsets.zero, + viewInsets: EdgeInsets.zero, + ), + child: Scaffold( + backgroundColor: Colors.transparent, + primary: false, + body: child, + ), + ), + ), + ), + ], + ); + } +} + +/// Lets [child] take input only inside [region]: a window's navigator covers +/// the whole host (see [WindowNavigator]) and must not swallow what is +/// outside its window. +class WindowHitRegion extends SingleChildRenderObjectWidget { + const WindowHitRegion({super.key, required this.region, super.child}); + + final Rect region; + + @override + RenderObject createRenderObject(BuildContext context) => + _RenderWindowHitRegion(region); + + @override + void updateRenderObject( + BuildContext context, + covariant RenderObject renderObject, + ) => (renderObject as _RenderWindowHitRegion).region = region; +} + +class _RenderWindowHitRegion extends RenderProxyBox { + _RenderWindowHitRegion(this.region); + + Rect region; + + @override + bool hitTest(BoxHitTestResult result, {required Offset position}) => + region.contains(position) && super.hitTest(result, position: position); +} diff --git a/app/lib/shell/windows/window_scope.dart b/app/lib/shell/windows/window_scope.dart new file mode 100644 index 00000000..0bbf7abd --- /dev/null +++ b/app/lib/shell/windows/window_scope.dart @@ -0,0 +1,35 @@ +import 'package:flutter/widgets.dart'; + +import 'window_entry.dart'; +import 'window_manager.dart'; + +/// The floating window some content is in: its entry, the manager, and where +/// the content area is drawn in the window host. Absent outside a window, so +/// shared content can tell the tiled app from a window. +class WindowScope extends InheritedWidget { + const WindowScope({ + super.key, + required this.manager, + required this.entry, + required this.body, + required super.child, + }); + + final WindowManager manager; + final WindowEntry entry; + + /// The content area (the window less its title bar), in the host's + /// coordinates. + final Rect body; + + static WindowScope? maybeOf(BuildContext context) => + context.dependOnInheritedWidgetOfExactType(); + + static WindowScope of(BuildContext context) => maybeOf(context)!; + + @override + bool updateShouldNotify(WindowScope oldWidget) => + oldWidget.manager != manager || + oldWidget.entry != entry || + oldWidget.body != body; +} diff --git a/app/lib/shell/windows/window_store.dart b/app/lib/shell/windows/window_store.dart index 9bee763d..9417e0f0 100644 --- a/app/lib/shell/windows/window_store.dart +++ b/app/lib/shell/windows/window_store.dart @@ -122,12 +122,7 @@ class WindowsRecord { ); } - static List _encodeRect(Rect r) => [ - r.left, - r.top, - r.width, - r.height, - ]; + static List _encodeRect(Rect r) => [r.left, r.top, r.width, r.height]; static Rect? _rect(Object? values) { if (values is! List || diff --git a/app/notes/floating-windows.md b/app/notes/floating-windows.md new file mode 100644 index 00000000..35b7496b --- /dev/null +++ b/app/notes/floating-windows.md @@ -0,0 +1,51 @@ +# Floating windows (window system core) + +Plan: `docs/plans/floating-windows.md`. Phase 1 adds the shell-level window +system; no feature uses it yet (chats move in Phase 2, the terminal in Phase 3). + +## Pieces (`lib/shell/windows/`) + +- `WindowManager` (`AppWindows.manager`): the open windows bottom to top, frames, + minimised/maximised, group show/hide, cycling. Saved through `WindowStore` + (`pipelines.windows.v1`), one record for every server; server-scoped windows + carry their server key and only the current server's are listed. +- `WindowKind` (`AppWindows.kinds`): what a kind of window builds, its title, + icon, title-bar actions, minimum size and saved data. +- `WindowHost`: the windows as plain children of the terminal stage's stack, in + the shell page (not an overlay above it), outside every destination. +- `WindowLayer` / `WindowFrame`: one window's card, title bar (drag, double + click to maximise, kind actions, Minimise, Maximise, Close) and resize corner. +- `WindowNavigator`: each window's own page stack. +- `WindowFocus`: a focus scope per window; the keyboard follows the top window + and returns to what had it when the last one hides. +- `WindowScope.maybeOf(context)`: non-null inside a window. + +## Layering rules + +- A page pushed with `Navigator.of(context).push(MaterialPageRoute)` from window + content opens inside the window (Back inside it). It must be a + `MaterialPageRoute`: the window's page transitions are what draw a page + inside the content area. +- A `PopupRoute` (bottom sheet, dialog, popup menu, dropdown) pushed on the + window's navigator is sent to the root navigator, so it is above every window + and never clipped to one. +- The window's navigator covers the whole host so popups anchored to a button + measure in app coordinates and tooltips paint outside the window; only the + content area takes input. So a `MenuAnchor` in window content needs + `useRootOverlay: true` (its panel may extend past the window). +- Known limit: a tooltip of a window that is not on top can be covered by a + window above it where they overlap (tooltips paint in their own window's + overlay). Pressing a window raises it, so menus are not affected. + +## Checks + +- `test/shell/windows/`: manager, store, host behaviour, and + `window_layering_test.dart`, the acceptance net for every popup type from a + window, over Chat and over another destination. +- Real app: the capture fixture opens probe windows with `?windows=N` + (`tool/capture/window_probe.dart`). Captured 2026-11-10 at 1280x800 and + 1920x1080, light and dark, over `/chat/perf-chat-0` and `/runs/7`: sheet, + dialog, MenuAnchor, popup menu, dropdown, content and title-bar tooltips, + hover, SnackBar, pushed page and Back, raise, move, maximise, minimise. +- Not captured in the browser: the text-selection menu (the kit has no + right-click); covered by the layering test only. diff --git a/app/test/shell/windows/window_host_test.dart b/app/test/shell/windows/window_host_test.dart new file mode 100644 index 00000000..5be9cc6e --- /dev/null +++ b/app/test/shell/windows/window_host_test.dart @@ -0,0 +1,249 @@ +import 'package:flutter/gestures.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/shell/windows/window_frame.dart'; +import 'package:pipelines_app/shell/windows/window_layer.dart'; +import 'package:pipelines_app/shell/windows/window_manager.dart'; + +import 'window_test_harness.dart'; + +void main() { + late WindowManager manager; + setUp(() => manager = probeManager()); + + Finder window(String title) => find.byWidgetPredicate( + (w) => w is WindowLayer && 'Probe ${w.entry.contentId}' == title, + ); + Finder inWindow(String title, Finder what) => + find.descendant(of: window(title), matching: what); + + testWidgets('a window shows its title, actions and content', (tester) async { + manager.open('probe', 'a'); + await pumpProbe(tester, manager); + expect( + windowRect(tester, 'Probe a'), + const Rect.fromLTWH(100, 80, 360, 420), + ); + expect(find.byTooltip('Probe action'), findsOneWidget); + for (final tip in ['Minimise', 'Maximise', 'Close']) { + expect(find.byTooltip(tip), findsOneWidget); + } + expect(find.text('sheet').hitTestable(), findsOneWidget); + // The title bar, the content and the app behind all keep their + // semantics (a page route's barrier hides what is behind it). + final handle = tester.ensureSemantics(); + expect(find.bySemanticsLabel('Window: Probe a'), findsOneWidget); + expect( + tester.getSemantics(find.byTooltip('Minimise')).tooltip, + 'Minimise', + ); + expect(find.bySemanticsLabel('sheet'), findsOneWidget); + expect(find.bySemanticsLabel('Chat'), findsOneWidget); + expect( + tester.getSemantics(find.bySemanticsLabel('Window: Probe a')).rect.size, + const Size(360, 420), + ); + handle.dispose(); + // The content is laid out for the window, not the app. + final content = tester.element(find.byType(ProbeContent)); + expect(MediaQuery.sizeOf(content).width, 360); + expect(tester.getRect(find.byType(ProbeContent)).top, greaterThan(80)); + }); + + testWidgets('the app behind takes input everywhere outside a window', ( + tester, + ) async { + manager.open('probe', 'a'); + await pumpProbe(tester, manager, destination: 1); + expect(find.text('Runs content').hitTestable(), findsOneWidget); + await tester.tap(find.byKey(const ValueKey('a-page'))); + await tester.pumpAndSettle(); + // A page pushed inside the window still leaves the app usable. + expect(find.text('Runs content').hitTestable(), findsOneWidget); + }); + + testWidgets('drag the title to move, the corner to resize, inside the app', ( + tester, + ) async { + final entry = manager.open('probe', 'a'); + await pumpProbe(tester, manager); + await tester.drag( + find.byKey(const ValueKey('window-title')), + const Offset(50, 30), + ); + await tester.pumpAndSettle(); + expect( + windowRect(tester, 'Probe a'), + const Rect.fromLTWH(150, 110, 360, 420), + ); + await tester.drag( + find.byKey(const ValueKey('window-resize')), + const Offset(40, -500), + ); + await tester.pumpAndSettle(); + // Never smaller than the kind's minimum. + expect( + windowRect(tester, 'Probe a'), + const Rect.fromLTWH(150, 110, 400, 160), + ); + await tester.drag( + find.byKey(const ValueKey('window-title')), + const Offset(5000, 5000), + ); + await tester.pumpAndSettle(); + expect( + windowRect(tester, 'Probe a'), + const Rect.fromLTWH(880, 640, 400, 160), + ); + expect( + manager.byId(entry.id)!.frame, + const Rect.fromLTWH(880, 640, 400, 160), + ); + }); + + testWidgets('maximise fills the app and restores; double click toggles', ( + tester, + ) async { + manager.open('probe', 'a'); + await pumpProbe(tester, manager); + await tester.tap(find.byTooltip('Maximise')); + await tester.pumpAndSettle(); + expect(windowRect(tester, 'Probe a'), const Rect.fromLTWH(8, 8, 1264, 784)); + expect(find.byKey(const ValueKey('window-resize')), findsNothing); + await tester.tap(find.byTooltip('Restore size')); + await tester.pumpAndSettle(); + expect( + windowRect(tester, 'Probe a'), + const Rect.fromLTWH(100, 80, 360, 420), + ); + final title = tester.getCenter(find.byKey(const ValueKey('window-title'))); + await tester.tapAt(title); + await tester.pump(kDoubleTapMinTime); + await tester.tapAt(title); + await tester.pumpAndSettle(); + expect(manager.windows.single.maximized, isTrue); + }); + + testWidgets('minimise hides the window and keeps its state; the group ' + 'brings it back', (tester) async { + final entry = manager.open('probe', 'a'); + await pumpProbe(tester, manager); + await tester.enterText(find.byKey(const ValueKey('a-field')), 'typed'); + final state = tester.state(find.byType(ProbeContent)); + await tester.tap(find.byTooltip('Minimise')); + await tester.pumpAndSettle(); + expect(manager.byId(entry.id)!.minimized, isTrue); + expect(find.text('Probe a').hitTestable(), findsNothing); + expect(find.byType(WindowFrame, skipOffstage: false), findsOneWidget); + manager.toggleGroup('probe'); + await tester.pumpAndSettle(); + expect(find.text('Probe a').hitTestable(), findsOneWidget); + expect( + tester.state(find.byType(ProbeContent)), + same(state), + ); + expect(find.text('typed'), findsOneWidget); + }); + + testWidgets('X closes the window', (tester) async { + final entry = manager.open('probe', 'a'); + await pumpProbe(tester, manager); + await tester.tap(find.byTooltip('Close')); + await tester.pumpAndSettle(); + expect(manager.windows, isEmpty); + expect(find.byType(ProbeContent, skipOffstage: false), findsNothing); + expect((manager.kinds['probe']! as ProbeWindowKind).closed_, [entry.id]); + }); + + testWidgets('pressing a window brings it to the top and keeps both alive', ( + tester, + ) async { + final a = manager.open('probe', 'a'); + final b = manager.open('probe', 'b'); + await pumpProbe(tester, manager); + final stateA = tester.state(find.byKey(const ValueKey('a-field'))); + // b covers a where they overlap. + expect(find.byKey(const ValueKey('a-dialog')).hitTestable(), findsNothing); + expect(manager.active!.id, b.id); + // a's title bar shows above b. + await tester.tapAt( + windowRect(tester, 'Probe a').topLeft + const Offset(16, 12), + ); + await tester.pumpAndSettle(); + expect(manager.active!.id, a.id); + expect( + find.byKey(const ValueKey('a-dialog')).hitTestable(), + findsOneWidget, + ); + expect(tester.state(find.byKey(const ValueKey('a-field'))), same(stateA)); + expect(inWindow('Probe b', find.byType(ProbeContent)), findsOneWidget); + }); + + testWidgets('the keyboard goes to the shown window and back when it hides', ( + tester, + ) async { + await pumpProbe(tester, manager); + await tester.tap(find.byKey(const ValueKey('chat-composer'))); + await tester.pump(); + final composer = FocusManager.instance.primaryFocus; + bool focusIn(Finder area) => find + .descendant( + of: area, + matching: find.byWidget( + FocusManager.instance.primaryFocus!.context!.widget, + ), + ) + .evaluate() + .isNotEmpty; + expect(focusIn(find.byKey(const ValueKey('chat-composer'))), isTrue); + + final a = manager.open('probe', 'a'); + await tester.pumpAndSettle(); + bool inside(String title) => focusIn(window(title)); + expect(inside('Probe a'), isTrue); + + final b = manager.open('probe', 'b'); + await tester.pumpAndSettle(); + expect(inside('Probe b'), isTrue); + + // The top window hides: the next one takes the keyboard. + manager.setMinimized(b.id, true); + await tester.pumpAndSettle(); + expect(inside('Probe a'), isTrue); + + manager.setGroupShown('probe', false); + await tester.pumpAndSettle(); + expect(FocusManager.instance.primaryFocus, same(composer)); + expect(manager.byId(a.id), isNotNull); + }); + + testWidgets('a window works and animates over another destination', ( + tester, + ) async { + manager.open('probe', 'a'); + await pumpProbe(tester, manager, destination: 1); + expect(find.text('Probe a').hitTestable(), findsOneWidget); + // Not muted by the hidden destination. + final content = tester.element(find.byType(ProbeContent)); + expect(TickerMode.valuesOf(content).enabled, isTrue); + await tester.tap(find.byKey(const ValueKey('a-field'))); + await tester.pump(); + await tester.enterText(find.byKey(const ValueKey('a-field')), 'over runs'); + expect(find.text('over runs'), findsOneWidget); + }); + + testWidgets('a frame larger than a small app is drawn inside it', ( + tester, + ) async { + manager.open('probe', 'a', frame: const Rect.fromLTWH(900, 600, 800, 700)); + await pumpProbe(tester, manager); + expect( + windowRect(tester, 'Probe a'), + const Rect.fromLTWH(480, 100, 800, 700), + ); + tester.view.physicalSize = const Size(600, 400); + await tester.pumpAndSettle(); + expect(windowRect(tester, 'Probe a'), const Rect.fromLTWH(0, 0, 600, 400)); + expect(tester.takeException(), isNull); + }); +} diff --git a/app/test/shell/windows/window_layering_test.dart b/app/test/shell/windows/window_layering_test.dart new file mode 100644 index 00000000..55fe0163 --- /dev/null +++ b/app/test/shell/windows/window_layering_test.dart @@ -0,0 +1,242 @@ +import 'dart:ui' as ui; + +import 'package:flutter/gestures.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter/rendering.dart'; +import 'package:flutter/services.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/shell/windows/window_manager.dart'; + +import 'window_test_harness.dart'; + +/// Layering acceptance (docs/plans/floating-windows.md, Phase 1.4): every +/// kind of popup opened from inside a window is above every window, over the +/// Chat destination and over another one; a pushed page stays inside its +/// window. "Above" is a hit test at the popup reaching the popup +/// ([Finder.hitTestable]), or its pixels for a tooltip, which takes no input. +void main() { + late WindowManager manager; + + /// Two overlapping windows; `a` is pressed, so it is on top, and `b` + /// covers the area to its lower right. + Future open( + WidgetTester tester, + int destination, { + GlobalKey? boundary, + }) async { + manager = probeManager(); + manager.open('probe', 'b', frame: const Rect.fromLTWH(300, 200, 600, 500)); + manager.open('probe', 'a', frame: const Rect.fromLTWH(100, 80, 360, 640)); + await pumpProbe( + tester, + manager, + destination: destination, + boundary: boundary, + ); + } + + String? picked(WidgetTester tester, String id) => tester + .state(find.byKey(ValueKey('content-$id'))) + .picked; + + NavigatorState root(WidgetTester tester) => + tester.state(find.byType(Navigator).first); + + for (final (destination, where) in [ + (0, 'Chat'), + (1, 'another destination'), + ]) { + group('over $where:', () { + testWidgets('bottom sheet', (tester) async { + await open(tester, destination); + await tester.tap(find.byKey(const ValueKey('a-sheet'))); + await tester.pumpAndSettle(); + expect(find.text('Sheet item').hitTestable(), findsOneWidget); + // On the root navigator: full width, not clipped to the window. + expect( + tester.getSize(find.byType(BottomSheet)).width, + greaterThan(600), + ); + expect(root(tester).canPop(), isTrue); + // The sheet closes itself with its own navigator. + await tester.tap(find.text('Sheet item')); + await tester.pumpAndSettle(); + expect(find.text('Sheet item'), findsNothing); + expect(find.byKey(const ValueKey('a-sheet')), findsOneWidget); + }); + + testWidgets('dialog', (tester) async { + await open(tester, destination); + await tester.tap(find.byKey(const ValueKey('a-dialog'))); + await tester.pumpAndSettle(); + expect(find.text('Dialog title').hitTestable(), findsOneWidget); + // Its barrier covers the windows. + expect( + find.byKey(const ValueKey('b-dialog')).hitTestable(), + findsNothing, + ); + }); + + testWidgets('MenuAnchor', (tester) async { + await open(tester, destination); + await tester.tap(find.byKey(const ValueKey('a-anchor'))); + await tester.pumpAndSettle(); + expect(find.text('Anchor item').hitTestable(), findsOneWidget); + await tester.tap(find.text('Anchor item')); + await tester.pumpAndSettle(); + expect(picked(tester, 'a'), 'anchor'); + }); + + testWidgets('PopupMenuButton opens at its button', (tester) async { + await open(tester, destination); + final button = tester.getRect(find.byKey(const ValueKey('a-popup'))); + await tester.tap(find.byKey(const ValueKey('a-popup'))); + await tester.pumpAndSettle(); + expect(find.text('Popup item').hitTestable(), findsOneWidget); + final item = tester.getRect(find.text('Popup item')); + expect((item.top - button.top).abs(), lessThan(80)); + expect((item.left - button.left).abs(), lessThan(200)); + await tester.tap(find.text('Popup item')); + await tester.pumpAndSettle(); + expect(picked(tester, 'a'), 'popup'); + }); + + testWidgets('DropdownButton opens at its button', (tester) async { + await open(tester, destination); + final button = tester.getRect(find.byKey(const ValueKey('a-dropdown'))); + await tester.tap(find.byKey(const ValueKey('a-dropdown'))); + await tester.pumpAndSettle(); + expect(find.text('Drop two').hitTestable(), findsOneWidget); + final item = tester.getRect(find.text('Drop two').last); + expect((item.top - button.top).abs(), lessThan(120)); + expect((item.left - button.left).abs(), lessThan(40)); + await tester.tap(find.text('Drop two').last); + await tester.pumpAndSettle(); + expect(picked(tester, 'a'), 'two'); + }); + + testWidgets('pushed page opens inside its window, with Back inside', ( + tester, + ) async { + await open(tester, destination); + final window = windowRect(tester, 'Probe a'); + await tester.tap(find.byKey(const ValueKey('a-page'))); + await tester.pumpAndSettle(); + expect(find.text('Page body').hitTestable(), findsOneWidget); + final page = tester.getRect(find.text('Page of a')); + expect(window.contains(page.topLeft), isTrue); + expect(window.contains(page.bottomRight), isTrue); + // The window keeps its title bar; the app has no new page. + expect(find.text('Probe a').hitTestable(), findsOneWidget); + expect(root(tester).canPop(), isFalse); + // The other window is untouched. + expect( + find.byKey(const ValueKey('b-snack')).hitTestable(), + findsOneWidget, + ); + await tester.tap(find.byType(BackButton)); + await tester.pumpAndSettle(); + expect(find.text('Page body'), findsNothing); + expect( + find.byKey(const ValueKey('a-page')).hitTestable(), + findsOneWidget, + ); + }); + + testWidgets('SnackBar shows inside its window', (tester) async { + await open(tester, destination); + await tester.tap(find.byKey(const ValueKey('a-snack'))); + await tester.pumpAndSettle(); + expect(find.text('Snack text').hitTestable(), findsOneWidget); + final window = windowRect(tester, 'Probe a'); + final snack = tester.getRect(find.byType(SnackBar)); + expect(window.contains(snack.topLeft), isTrue); + expect(window.contains(snack.bottomRight - const Offset(1, 1)), isTrue); + }); + + testWidgets('text selection menu', (tester) async { + await open(tester, destination); + // On the text itself, which selects a word. + await tester.longPressAt( + tester.getRect(find.byKey(const ValueKey('a-field'))).centerLeft + + const Offset(30, 0), + ); + await tester.pumpAndSettle(); + expect(find.text('Select all').hitTestable(), findsOneWidget); + }); + + testWidgets('tooltip of content and of the title bar', (tester) async { + final boundary = GlobalKey(); + await open(tester, destination, boundary: boundary); + final mouse = await tester.createGesture(kind: PointerDeviceKind.mouse); + addTearDown(mouse.removePointer); + await mouse.addPointer(location: Offset.zero); + await mouse.moveTo( + tester.getCenter(find.byKey(const ValueKey('a-tip'))), + ); + await tester.pumpAndSettle(const Duration(seconds: 1)); + expect(find.text('Tip text'), findsOneWidget); + // Its own pixels show: nothing is painted over it. + final tip = tester.getRect(find.text('Tip text')); + final image = await _capture(tester, boundary); + expect( + await _pixel(tester, image, tip.topLeft - const Offset(3, 2)), + probeTooltipColor, + ); + + await mouse.moveTo(tester.getCenter(find.byTooltip('Close').last)); + await tester.pumpAndSettle(const Duration(seconds: 1)); + expect(find.text('Close'), findsOneWidget); + // Not clipped to the window: tooltips paint in an overlay as large + // as the app. + final overlay = tester.renderObject( + find + .ancestor(of: find.text('Close'), matching: find.byType(Overlay)) + .first, + ); + expect(overlay.size, const Size(1280, 800)); + }); + }); + } + + testWidgets('a popup from a window under another window is above both', ( + tester, + ) async { + await open(tester, 0); + // b is under a; its sheet button is outside a. + await tester.tap(find.byKey(const ValueKey('b-sheet'))); + await tester.pumpAndSettle(); + expect(manager.active!.contentId, 'b'); + expect(find.text('Sheet item').hitTestable(), findsOneWidget); + }); + + testWidgets('Escape closes the popup, not the window', (tester) async { + await open(tester, 0); + await tester.tap(find.byKey(const ValueKey('a-dialog'))); + await tester.pumpAndSettle(); + await tester.sendKeyEvent(LogicalKeyboardKey.escape); + await tester.pumpAndSettle(); + expect(find.text('Dialog title'), findsNothing); + expect(manager.windows, hasLength(2)); + expect(find.text('Probe a').hitTestable(), findsOneWidget); + }); +} + +Future _capture(WidgetTester tester, GlobalKey boundary) async { + final render = + boundary.currentContext!.findRenderObject()! as RenderRepaintBoundary; + return (await tester.runAsync(() => render.toImage()))!; +} + +Future _pixel(WidgetTester tester, ui.Image image, Offset at) async { + final data = (await tester.runAsync( + () => image.toByteData(format: ui.ImageByteFormat.rawRgba), + ))!; + final i = (at.dy.round() * image.width + at.dx.round()) * 4; + return Color.fromARGB( + data.getUint8(i + 3), + data.getUint8(i), + data.getUint8(i + 1), + data.getUint8(i + 2), + ); +} diff --git a/app/test/shell/windows/window_store_test.dart b/app/test/shell/windows/window_store_test.dart index 10d9a613..7250c6e7 100644 --- a/app/test/shell/windows/window_store_test.dart +++ b/app/test/shell/windows/window_store_test.dart @@ -111,9 +111,15 @@ void main() { _window({'content': ' padded '}), _window({'server': '#remove'}), _window({'kind': 'terminal'}), - _window({'frame': [1, 2, 3]}), - _window({'frame': [1, 2, 0, 5]}), - _window({'frame': [1, 2, 'a', 5]}), + _window({ + 'frame': [1, 2, 3], + }), + _window({ + 'frame': [1, 2, 0, 5], + }), + _window({ + 'frame': [1, 2, 'a', 5], + }), _window({'data': 7}), 'text', ]) { diff --git a/app/test/shell/windows/window_test_harness.dart b/app/test/shell/windows/window_test_harness.dart new file mode 100644 index 00000000..40256b14 --- /dev/null +++ b/app/test/shell/windows/window_test_harness.dart @@ -0,0 +1,79 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/shell/windows/window_frame.dart'; +import 'package:pipelines_app/shell/windows/window_host.dart'; +import 'package:pipelines_app/shell/windows/window_manager.dart'; +import 'package:pipelines_app/ui/motion/fade_through_stack.dart'; + +export '../../../tool/capture/window_probe.dart'; + +/// The shell in miniature: a root navigator whose one page holds two +/// destinations (only one shown, as in the app) and the window host above +/// them. +class ProbeApp extends StatelessWidget { + const ProbeApp({ + super.key, + required this.manager, + this.destination = 0, + this.boundary, + }); + + final WindowManager manager; + final int destination; + final GlobalKey? boundary; + + @override + Widget build(BuildContext context) => RepaintBoundary( + key: boundary, + child: MaterialApp( + home: Scaffold( + body: Stack( + fit: StackFit.expand, + children: [ + FadeThroughStack( + index: destination, + children: [ + Center( + child: TextField( + key: const ValueKey('chat-composer'), + decoration: const InputDecoration(hintText: 'Chat'), + ), + ), + Align( + alignment: Alignment.bottomRight, + child: TextButton( + key: const ValueKey('runs-button'), + onPressed: () {}, + child: const Text('Runs content'), + ), + ), + ], + ), + Positioned.fill(child: WindowHost(manager: manager)), + ], + ), + ), + ), + ); +} + +/// Pumps a 1280x800 app with [manager]'s windows. +Future pumpProbe( + WidgetTester tester, + WindowManager manager, { + int destination = 0, + GlobalKey? boundary, +}) async { + tester.view.physicalSize = const Size(1280, 800); + tester.view.devicePixelRatio = 1; + addTearDown(tester.view.reset); + await tester.pumpWidget( + ProbeApp(manager: manager, destination: destination, boundary: boundary), + ); + await tester.pumpAndSettle(); +} + +/// The window's card (title bar and body) in global coordinates. +Rect windowRect(WidgetTester tester, String title) => tester.getRect( + find.ancestor(of: find.text(title), matching: find.byType(WindowFrame)), +); diff --git a/app/tool/capture/window_probe.dart b/app/tool/capture/window_probe.dart new file mode 100644 index 00000000..03b63c8b --- /dev/null +++ b/app/tool/capture/window_probe.dart @@ -0,0 +1,161 @@ +import 'package:flutter/material.dart'; +import 'package:pipelines_app/shell/windows/window_entry.dart'; +import 'package:pipelines_app/shell/windows/window_kind.dart'; +import 'package:pipelines_app/shell/windows/window_manager.dart'; + +/// A window kind for tests and for the capture fixture (`?windows=N` opens N +/// of them): every kind of popup and a pushed page, opened from inside a +/// window. +class ProbeWindowKind extends WindowKind { + final closed_ = []; + + @override + String get key => 'probe'; + @override + bool get serverScoped => false; + @override + IconData get icon => Icons.science_outlined; + @override + Size get minSize => const Size(240, 160); + @override + Rect get defaultFrame => const Rect.fromLTWH(100, 80, 360, 420); + @override + String title(BuildContext context, WindowEntry entry) => + 'Probe ${entry.contentId}'; + @override + Widget build(BuildContext context, WindowEntry entry) => ProbeContent( + key: ValueKey('content-${entry.contentId}'), + id: entry.contentId, + ); + @override + List actions(BuildContext context, WindowEntry entry) => [ + WindowAction(label: 'Probe action', icon: Icons.star, onPressed: () {}), + ]; + @override + void closed(WindowEntry entry) => closed_.add(entry.id); +} + +const probeTooltipColor = Color(0xFFFF00FF); + +class ProbeContent extends StatefulWidget { + const ProbeContent({super.key, required this.id}); + final String id; + + @override + State createState() => ProbeContentState(); +} + +class ProbeContentState extends State { + final text = TextEditingController(text: 'select me'); + final menu = MenuController(); + int builds = 0; + String? picked; + + @override + void dispose() { + text.dispose(); + super.dispose(); + } + + Widget _button(String label, VoidCallback onPressed) => TextButton( + key: ValueKey('${widget.id}-$label'), + onPressed: onPressed, + child: Text(label), + ); + + @override + Widget build(BuildContext context) { + builds++; + final id = widget.id; + return ListView( + children: [ + TextField(key: ValueKey('$id-field'), controller: text), + Tooltip( + message: 'Tip text', + decoration: const BoxDecoration(color: probeTooltipColor), + child: Icon(Icons.info, key: ValueKey('$id-tip')), + ), + _button( + 'sheet', + () => showModalBottomSheet( + context: context, + builder: (sheet) => SizedBox( + height: 200, + child: TextButton( + onPressed: () => Navigator.of(sheet).pop(), + child: const Text('Sheet item'), + ), + ), + ), + ), + _button( + 'dialog', + () => showDialog( + context: context, + builder: (_) => const AlertDialog(title: Text('Dialog title')), + ), + ), + _button( + 'page', + () => Navigator.of(context).push( + MaterialPageRoute( + builder: (_) => Scaffold( + appBar: AppBar(title: Text('Page of $id')), + body: const Center(child: Text('Page body')), + ), + ), + ), + ), + _button( + 'snack', + () => ScaffoldMessenger.of( + context, + ).showSnackBar(const SnackBar(content: Text('Snack text'))), + ), + MenuAnchor( + controller: menu, + useRootOverlay: true, + menuChildren: [ + MenuItemButton( + onPressed: () => setState(() => picked = 'anchor'), + child: const Text('Anchor item'), + ), + ], + child: _button('anchor', menu.open), + ), + PopupMenuButton( + key: ValueKey('$id-popup'), + onSelected: (value) => setState(() => picked = value), + itemBuilder: (_) => const [ + PopupMenuItem(value: 'popup', child: Text('Popup item')), + ], + ), + DropdownButton( + key: ValueKey('$id-dropdown'), + value: 'one', + onChanged: (value) => setState(() => picked = value), + items: const [ + DropdownMenuItem(value: 'one', child: Text('Drop one')), + DropdownMenuItem(value: 'two', child: Text('Drop two')), + ], + ), + Text('picked: $picked'), + ], + ); + } +} + +WindowManager probeManager() => + WindowManager(kinds: WindowKinds()..register(ProbeWindowKind())); + +/// The capture fixture's windows: `?windows=N` opens N probe windows (not +/// saved); without the parameter the app keeps its own. +WindowManager? probeWindows(Map params) { + final count = int.tryParse(params['windows'] ?? ''); + if (count == null) return null; + final manager = probeManager(); + for (var i = 0; i < count; i++) { + manager.open('probe', String.fromCharCode(0x61 + i)); + } + return manager; +} diff --git a/app/tool/search_selection_probe_entry.dart b/app/tool/search_selection_probe_entry.dart index 330e7100..304ceb76 100644 --- a/app/tool/search_selection_probe_entry.dart +++ b/app/tool/search_selection_probe_entry.dart @@ -41,6 +41,7 @@ import 'package:web_socket_channel/web_socket_channel.dart'; import 'fixture_host/fixture_host.dart'; import 'perf/chat_search_fixture.dart'; import 'perf/chat_question_fixture.dart'; +import 'capture/window_probe.dart'; import 'perf/chat_scroll_fixture.dart'; import 'perf/perf_fixture.dart'; import 'probe_folder_fixture.dart'; @@ -647,8 +648,9 @@ class _FixtureAuthenticator extends ChangeNotifier @override Future probe(SavedServer server) async { await Future.delayed(const Duration(milliseconds: 400)); - return _verdicts[server.id] ??= - const MachineAccessResult(MachineAccess.needsPassword); + return _verdicts[server.id] ??= const MachineAccessResult( + MachineAccess.needsPassword, + ); } @override @@ -784,6 +786,8 @@ class _FixtureSink implements WebSocketSink { /// (tool/perf/perf_fixture.dart); /// `?terminals=1` lists two machine terminals, and `?terminal=panel` or /// `?terminal=float` opens them at launch (tool/perf/terminal_fixture.dart); +/// `?windows=N` opens N floating probe windows whose content opens every +/// kind of popup and a pushed page (tool/capture/window_probe.dart); /// `?theme=dark` / `?theme=light` pins the platform brightness the app's /// `ThemeMode.system` follows (omitted: the browser's color scheme). /// @@ -894,6 +898,7 @@ Future main() async { client: PipelinesClient(channelFactory: (_) => _FixtureChannel()), cupertino: cupertino, routeInformationProvider: fixtureRouteProvider(opensRoute ? route : null), + windows: probeWindows(params), ); final brightness = switch (params['theme']) { 'dark' => Brightness.dark,