Add the Windows menu, window cycling, edge snapping and size per kind

Phase 4 of docs/plans/floating-windows.md. A bar button lists the app's
windows on every tab (show one, Show all, Minimise all, Close all). Alt+`
and Alt+Shift+` bring the next or previous window to the front. Dropping a
title at the left or right edge fills that half, at the top it maximises.
A new window of a kind opens at the size that kind was last given.
This commit is contained in:
2026-11-11 00:05:16 +00:00
parent e9fa1b6ec9
commit ef1c120f57
12 changed files with 593 additions and 15 deletions
+33
View File
@@ -99,3 +99,36 @@ Rect drawnWindowFrame(WindowEntry entry, Size bounds, Size minSize) =>
windowMaximizedMargin.clamp(0.0, bounds.shortestSide / 2),
)
: fitWindowFrame(entry.frame, bounds, minSize);
/// Where a dragged window snaps when its title is dropped at an edge.
enum WindowSnap { left, right, maximize }
/// How close to an edge of the window area the pointer must be to snap.
const double windowSnapDistance = 6;
/// The snap for a title dropped with the pointer at [pointer] inside
/// [bounds], or null away from the edges.
WindowSnap? windowSnapFor(Offset pointer, Size bounds) {
if (pointer.dy <= windowSnapDistance) return WindowSnap.maximize;
if (pointer.dx <= windowSnapDistance) return WindowSnap.left;
if (pointer.dx >= bounds.width - windowSnapDistance) return WindowSnap.right;
return null;
}
/// The frame of a window snapped to a half of [bounds].
Rect windowSnapRect(WindowSnap snap, Size bounds) {
final area = (Offset.zero & bounds).deflate(
windowMaximizedMargin.clamp(0.0, bounds.shortestSide / 2),
);
final half = (area.width - windowMaximizedMargin) / 2;
return switch (snap) {
WindowSnap.left => Rect.fromLTWH(area.left, area.top, half, area.height),
WindowSnap.right => Rect.fromLTWH(
area.right - half,
area.top,
half,
area.height,
),
WindowSnap.maximize => area,
};
}
+6 -2
View File
@@ -32,7 +32,9 @@ class WindowFrame extends StatelessWidget {
final IconData icon;
final List<WindowAction> actions;
final bool maximized;
final ValueChanged<Offset> onMove;
/// The drag's delta and the pointer's global position.
final void Function(Offset delta, Offset globalPosition) onMove;
final VoidCallback onMoveEnd;
final VoidCallback onMinimize;
final VoidCallback onToggleMaximized;
@@ -100,7 +102,9 @@ class WindowFrame extends StatelessWidget {
behavior: HitTestBehavior.opaque,
// The window follows the pointer from where it went down.
dragStartBehavior: DragStartBehavior.down,
onPanUpdate: maximized ? null : (details) => onMove(details.delta),
onPanUpdate: maximized
? null
: (details) => onMove(details.delta, details.globalPosition),
onPanEnd: maximized ? null : (_) => onMoveEnd(),
onDoubleTap: onToggleMaximized,
child: Padding(
+20
View File
@@ -1,8 +1,10 @@
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'window_focus.dart';
import 'window_layer.dart';
import 'window_manager.dart';
import 'window_shortcuts.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
@@ -33,6 +35,7 @@ class _WindowHostState extends State<WindowHost> {
void initState() {
super.initState();
widget.manager.addListener(_changed);
FocusManager.instance.addEarlyKeyEventHandler(_key);
// The shell page is not the top route while a popup or page covers it.
_focus.covered = () =>
mounted && !(ModalRoute.of(context)?.isCurrent ?? true);
@@ -51,6 +54,7 @@ class _WindowHostState extends State<WindowHost> {
@override
void dispose() {
FocusManager.instance.removeEarlyKeyEventHandler(_key);
widget.manager.removeListener(_changed);
_focus.dispose();
super.dispose();
@@ -81,6 +85,22 @@ class _WindowHostState extends State<WindowHost> {
setState(() {});
}
/// Alt+` and Alt+Shift+` bring the next or previous window to the front,
/// from anywhere (a composer, the terminal). With fewer than two windows
/// showing, or while a popup covers the app, the key is left alone.
KeyEventResult _key(KeyEvent event) {
if (!mounted) return KeyEventResult.ignored;
final step = windowCycleShortcut(event, HardwareKeyboard.instance);
final manager = widget.manager;
if (step == null ||
(_focus.covered?.call() ?? false) ||
manager.windows.where(manager.isVisible).length < 2) {
return KeyEventResult.ignored;
}
manager.cycle(step);
return KeyEventResult.handled;
}
/// The window takes the keyboard, then its content places it.
void _focusWindow(String id) {
_focus.focusSoon(id);
+42 -7
View File
@@ -93,11 +93,46 @@ class _WindowLayerState extends State<WindowLayer>
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,
);
/// Where the pointer is in the host while the title is dragged.
Offset? _pointer;
void _move(Offset delta, Offset globalPosition) {
final box = context.findRenderObject();
_pointer = box is RenderBox ? box.globalToLocal(globalPosition) : null;
widget.manager.setFrame(
_id,
fitWindowFrame(_current.shift(delta), widget.bounds, widget.kind.minSize),
save: false,
);
}
/// Dropping the title at the app's left or right edge fills that half;
/// at the top edge it maximises.
void _moveEnded() {
final pointer = _pointer;
_pointer = null;
final bounds = widget.bounds;
final snap = pointer == null ? null : windowSnapFor(pointer, bounds);
if (snap == WindowSnap.maximize) {
widget.manager.setMaximized(_id, true);
return;
}
if (snap != null) {
widget.manager.setFrame(
_id,
fitWindowFrame(
windowSnapRect(snap, bounds),
bounds,
widget.kind.minSize,
),
save: false,
);
// A snapped half is not the size to give this kind's next window.
widget.manager.commit();
return;
}
widget.manager.commit(_id);
}
void _resize(Offset delta) {
final rect = _current;
@@ -156,7 +191,7 @@ class _WindowLayerState extends State<WindowLayer>
actions: kind.actions(context, entry),
maximized: entry.maximized,
onMove: _move,
onMoveEnd: manager.commit,
onMoveEnd: _moveEnded,
onMinimize: () => manager.setMinimized(_id, true),
onToggleMaximized: () =>
manager.setMaximized(_id, !entry.maximized),
@@ -200,7 +235,7 @@ class _WindowLayerState extends State<WindowLayer>
bottom: widget.bounds.height - frame.bottom,
child: WindowResizeCorner(
onResize: _resize,
onResizeEnd: manager.commit,
onResizeEnd: () => manager.commit(_id),
),
),
],
+57 -3
View File
@@ -27,6 +27,9 @@ class WindowManager extends ChangeNotifier {
final List<WindowEntry> _all = [];
final Set<String> _hiddenGroups = {};
final Map<String, Rect> _frames = {};
/// The size each kind's windows were last given, for its next new window.
final Map<String, Size> _sizes = {};
int _revision = 0;
int _nextId = 0;
@@ -108,7 +111,9 @@ class WindowManager extends ChangeNotifier {
frame:
frame ??
_frames[windowFrameKey(kind, serverKey, contentId)] ??
spec.defaultFrame.shift(windowCascadeStep * siblings.toDouble()),
(spec.defaultFrame.topLeft +
windowCascadeStep * siblings.toDouble()) &
(_sizes[kind] ?? spec.defaultFrame.size),
data: data,
);
_change(() {
@@ -176,8 +181,53 @@ class WindowManager extends ChangeNotifier {
void setFrame(String id, Rect frame, {bool save = true}) =>
_replace(id, (w) => w.copyWith(frame: frame), save: save);
/// Saves after a drag.
void commit() => unawaited(save());
/// Saves after a drag, and remembers the size for the kind's next window.
void commit([String? id]) {
final entry = id == null ? null : byId(id);
if (entry != null && !entry.maximized) {
_sizes[entry.kind] = entry.frame.size;
}
unawaited(save());
}
/// Shows every window (un-minimised, every group shown).
void showAll() {
if (windows.every(isVisible)) return;
_change(() {
for (var i = 0; i < _all.length; i++) {
final w = _all[i];
if (!_here(w)) continue;
_hiddenGroups.remove(w.groupId);
if (w.minimized) _all[i] = w.copyWith(minimized: false);
}
});
}
/// Minimises every window.
void minimizeAll() {
if (!windows.any(isVisible)) return;
_change(() {
for (var i = 0; i < _all.length; i++) {
final w = _all[i];
if (_here(w) && !w.minimized) _all[i] = w.copyWith(minimized: true);
}
});
}
/// Closes every window; each keeps its frame for its content.
void closeAll() {
final closing = windows;
if (closing.isEmpty) return;
_change(() {
for (final entry in closing) {
_all.remove(entry);
_remember(entry);
}
});
for (final entry in closing) {
kinds[entry.kind]?.closed(entry);
}
}
void setMinimized(String id, bool minimized) =>
_replace(id, (w) => w.copyWith(minimized: minimized));
@@ -274,6 +324,9 @@ class WindowManager extends ChangeNotifier {
_frames
..clear()
..addAll(record.frames);
_sizes
..clear()
..addAll(record.sizes);
notifyListeners();
}
@@ -281,6 +334,7 @@ class WindowManager extends ChangeNotifier {
windows: List.unmodifiable(_all),
hiddenGroups: Set.unmodifiable(_hiddenGroups),
frames: Map.unmodifiable(_frames),
sizes: Map.unmodifiable(_sizes),
);
Future<void> save() async {
@@ -0,0 +1,28 @@
import 'package:flutter/foundation.dart';
import 'package:flutter/services.dart';
/// The step Alt+` (1) or Alt+Shift+` (-1) moves between the app's floating
/// windows, or null for any other key. A browser keeps Ctrl+Tab and the
/// system keeps Cmd+`, so the chord is Alt (Option), which every platform
/// delivers; Option+` types a dead key on a Mac, so the key is matched by
/// its position too. Ctrl+` stays the terminal's.
int? windowCycleShortcut(KeyEvent event, HardwareKeyboard keyboard) {
if (event is KeyUpEvent ||
!keyboard.isAltPressed ||
keyboard.isControlPressed ||
keyboard.isMetaPressed) {
return null;
}
final backquote =
event.logicalKey == LogicalKeyboardKey.backquote ||
event.physicalKey == PhysicalKeyboardKey.backquote;
if (!backquote) return null;
return keyboard.isShiftPressed ? -1 : 1;
}
/// The chord as it reads on this platform, for the Windows menu.
String windowCycleShortcutLabel([TargetPlatform? platform]) =>
switch (platform ?? defaultTargetPlatform) {
TargetPlatform.macOS || TargetPlatform.iOS => 'Option+`',
_ => 'Alt+`',
};
+18
View File
@@ -20,12 +20,16 @@ class WindowsRecord {
this.windows = const [],
this.hiddenGroups = const {},
this.frames = const {},
this.sizes = const {},
});
final List<WindowEntry> windows;
final Set<String> hiddenGroups;
final Map<String, Rect> frames;
/// The last size given to a window of each kind.
final Map<String, Size> sizes;
String encode(WindowKinds kinds) => jsonEncode({
'version': 1,
'windows': [
@@ -47,6 +51,10 @@ class WindowsRecord {
for (final MapEntry(:key, :value) in frames.entries)
key: _encodeRect(value),
},
'sizes': {
for (final MapEntry(:key, :value) in sizes.entries)
key: [value.width, value.height],
},
});
/// Null when [source] is not a record. A window of an unregistered kind,
@@ -86,6 +94,16 @@ class WindowsRecord {
if (_identity(g, 256)) g as String,
},
frames: frames,
sizes: {
if (data['sizes'] case final Map raw)
for (final MapEntry(:key, :value) in raw.entries)
if (key is String && _identity(key, 64))
if (value case [
final num w,
final num h,
] when w.isFinite && h.isFinite && w > 0 && h > 0)
key: Size(w.toDouble(), h.toDouble()),
},
);
} on Object {
return null;
@@ -0,0 +1,91 @@
import 'package:flutter/material.dart';
import '../../ui/adaptive/app_menu_anchor.dart';
import 'window_manager.dart';
import 'window_shortcuts.dart';
/// The shell bar's Windows button, shown while the app has floating windows:
/// a menu listing each one (choosing it shows it and brings it to the
/// front), then Show all, Minimise all and Close all.
class WindowsMenuButton extends StatelessWidget {
const WindowsMenuButton({super.key, required this.manager});
final WindowManager manager;
@override
Widget build(BuildContext context) => ListenableBuilder(
listenable: Listenable.merge([
manager,
for (final kind in manager.kinds.all) ?kind.changes,
]),
builder: (context, _) {
final windows = manager.windows
.where((w) => manager.kinds[w.kind] != null)
.toList()
.reversed
.toList();
if (windows.isEmpty) return const SizedBox.shrink();
final active = manager.active?.id;
return AppMenuAnchor(
menuChildren: [
for (final entry in windows)
MenuItemButton(
key: ValueKey('windows-menu-${entry.id}'),
leadingIcon: Icon(manager.kinds[entry.kind]!.icon),
trailingIcon: entry.id == active
? const Icon(Icons.check)
: !manager.isVisible(entry)
? const Icon(Icons.minimize)
: null,
onPressed: () => manager.show(entry.id),
child: ConstrainedBox(
constraints: const BoxConstraints(maxWidth: 280),
child: Text(
manager.kinds[entry.kind]!.title(context, entry),
maxLines: 1,
overflow: TextOverflow.ellipsis,
semanticsLabel:
'${manager.kinds[entry.kind]!.title(context, entry)}'
'${manager.isVisible(entry) ? '' : ', minimised'}',
),
),
),
const Divider(height: 8),
MenuItemButton(
leadingIcon: const Icon(Icons.open_in_full),
onPressed: windows.every(manager.isVisible)
? null
: manager.showAll,
child: const Text('Show all'),
),
MenuItemButton(
leadingIcon: const Icon(Icons.minimize),
onPressed: windows.any(manager.isVisible)
? manager.minimizeAll
: null,
child: const Text('Minimise all'),
),
MenuItemButton(
leadingIcon: const Icon(Icons.close),
onPressed: manager.closeAll,
child: const Text('Close all'),
),
if (windows.length > 1)
Padding(
padding: const EdgeInsets.fromLTRB(12, 8, 12, 4),
child: Text(
'Next window: ${windowCycleShortcutLabel()}',
style: Theme.of(context).textTheme.bodySmall,
),
),
],
builder: (context, menu, _) => IconButton(
key: const ValueKey('shell.windows'),
tooltip: 'Windows (${windows.length})',
onPressed: () => menu.isOpen ? menu.close() : menu.open(),
icon: const Icon(Icons.web_asset_outlined),
),
);
},
);
}