Files
pipelines/app/lib/shell/windows/window_manager.dart
T
alan a99f7014f5 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.
2026-11-10 20:48:31 +00:00

293 lines
8.9 KiB
Dart

import 'dart:async';
import 'dart:ui';
import 'package:flutter/foundation.dart';
import 'window_entry.dart';
import 'window_kind.dart';
import 'window_store.dart';
/// How far each new window of a kind opens from the previous one.
const Offset windowCascadeStep = Offset(32, 32);
/// The app's floating windows, for the app's lifetime: which are open, their
/// order (bottom to top), frames and state. The shell's window host draws
/// them; features open windows of their registered [WindowKind].
///
/// Windows of every server are kept (and saved), but only the current
/// server's and the device-wide ones are listed: [server] selects it.
class WindowManager extends ChangeNotifier {
WindowManager({required this.kinds, this._store, this._server});
final WindowKinds kinds;
final WindowStore? _store;
String? _server;
/// Every server's windows, bottom to top.
final List<WindowEntry> _all = [];
final Set<String> _hiddenGroups = {};
final Map<String, Rect> _frames = {};
int _revision = 0;
int _nextId = 0;
/// Whether the last change could not be saved.
bool saveFailed = false;
/// The server whose windows are listed.
String? get server => _server;
set server(String? value) {
if (_server == value) return;
_server = value;
notifyListeners();
}
bool _here(WindowEntry w) => w.serverKey == null || w.serverKey == _server;
/// The current server's and the device's windows, bottom to top, shown or
/// not.
List<WindowEntry> get windows => List.unmodifiable(_all.where(_here));
WindowEntry? byId(String id) =>
_all.where((w) => w.id == id && _here(w)).firstOrNull;
/// The open window of [kind] showing [contentId] on the current server.
WindowEntry? find(String kind, String contentId) => _all
.where((w) => _here(w) && w.kind == kind && w.contentId == contentId)
.firstOrNull;
Iterable<WindowEntry> inGroup(String groupId) =>
windows.where((w) => w.groupId == groupId);
bool groupShown(String groupId) => !_hiddenGroups.contains(groupId);
/// Whether [entry] is on screen: not minimised and its group not hidden.
bool isVisible(WindowEntry entry) =>
!entry.minimized && groupShown(entry.groupId);
/// The topmost window on screen: the one last opened, pressed or focused.
WindowEntry? get active => windows.where(isVisible).lastOrNull;
/// Opens a window of [kind] for [contentId] on top, or raises and shows
/// the one already open. A new window takes [frame], else the frame this
/// content last had, else the kind's default cascaded past its siblings.
WindowEntry open(
String kind,
String contentId, {
Rect? frame,
String? groupId,
Map<String, Object?> data = const {},
}) {
final spec = kinds[kind];
if (spec == null) throw StateError('window kind $kind is not registered');
final existing = find(kind, contentId);
if (existing != null) {
show(existing.id);
return byId(existing.id)!;
}
final serverKey = spec.serverScoped ? _server : null;
if (spec.serverScoped && serverKey == null) {
throw StateError('a $kind window needs a server');
}
final siblings = windows.where((w) => w.kind == kind).length;
final entry = WindowEntry(
id: _newId(kind),
kind: kind,
contentId: contentId,
serverKey: serverKey,
groupId: groupId,
frame:
frame ??
_frames[windowFrameKey(kind, serverKey, contentId)] ??
spec.defaultFrame.shift(windowCascadeStep * siblings.toDouble()),
data: data,
);
_change(() {
_all.add(entry);
_hiddenGroups.remove(entry.groupId);
});
return entry;
}
String _newId(String kind) {
while (true) {
final id = '$kind-${++_nextId}';
if (!_all.any((w) => w.id == id)) return id;
}
}
/// Closes [id]; its frame is remembered for its content.
void close(String id) {
final entry = byId(id);
if (entry == null) return;
_change(() {
_all.remove(entry);
_remember(entry);
});
kinds[entry.kind]?.closed(entry);
}
void _remember(WindowEntry entry) {
final key = windowFrameKey(entry.kind, entry.serverKey, entry.contentId);
_frames
..remove(key)
..[key] = entry.frame;
while (_frames.length > windowStoreMaxFrames) {
_frames.remove(_frames.keys.first);
}
}
/// Brings [id] to the top. Returns whether the order changed.
bool raise(String id) {
final entry = byId(id);
if (entry == null || identical(_all.last, entry)) return false;
_change(() {
_all
..remove(entry)
..add(entry);
});
return true;
}
/// Shows [id] (un-minimised, its group shown) on top.
void show(String id) {
final entry = byId(id);
if (entry == null) return;
if (isVisible(entry) && identical(_all.last, entry)) return;
_change(() {
_all
..remove(entry)
..add(entry.copyWith(minimized: false));
_hiddenGroups.remove(entry.groupId);
});
}
/// Moves or resizes [id]. A drag passes `save: false` for every pointer
/// event and calls [commit] when it ends.
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());
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));
/// Replaces what [id] shows (a chat that moved to a new session).
void setContent(String id, String contentId, {Map<String, Object?>? data}) =>
_replace(id, (w) => w.copyWith(contentId: contentId, data: data));
void _replace(
String id,
WindowEntry Function(WindowEntry) update, {
bool save = true,
}) {
final at = _all.indexWhere((w) => w.id == id && _here(w));
if (at < 0) return;
final next = update(_all[at]);
final old = _all[at];
if (old.frame == next.frame &&
old.minimized == next.minimized &&
old.maximized == next.maximized &&
old.contentId == next.contentId &&
mapEquals(old.data, next.data)) {
return;
}
_change(() => _all[at] = next, save: save);
}
/// Shows or hides every window of [groupId] together. Showing also brings
/// back the group's minimised windows.
void setGroupShown(String groupId, bool shown) {
final group = inGroup(groupId).toList();
if (group.isEmpty) return;
final visible = group.any(isVisible);
if (shown == visible && !(shown && group.any((w) => w.minimized))) return;
_change(() {
if (shown) {
_hiddenGroups.remove(groupId);
for (var i = 0; i < _all.length; i++) {
final w = _all[i];
if (_here(w) && w.groupId == groupId && w.minimized) {
_all[i] = w.copyWith(minimized: false);
}
}
} else {
_hiddenGroups.add(groupId);
}
});
}
/// Hides the group when any of its windows is on screen, else shows it.
/// Returns false when the group has no window.
bool toggleGroup(String groupId) {
final group = inGroup(groupId);
if (group.isEmpty) return false;
setGroupShown(groupId, !group.any(isVisible));
return true;
}
/// Brings the next ([step] 1) or previous (-1) visible window to the top.
void cycle([int step = 1]) {
final visible = windows.where(isVisible).toList();
if (visible.length < 2) return;
// Forward: the bottom window comes up. Back: the top one goes under.
if (step >= 0) {
raise(visible.first.id);
} else {
final top = visible.last;
_change(() {
_all
..remove(top)
..insert(_all.indexOf(visible.first), top);
});
}
}
/// Loads the saved windows, unless something changed meanwhile.
Future<void> restore() async {
final store = _store;
if (store == null) return;
final revision = _revision;
final raw = await store.read();
if (revision != _revision || raw == null) return;
final record = WindowsRecord.decode(raw, kinds);
if (record == null) return;
_all
..clear()
..addAll(record.windows);
_hiddenGroups
..clear()
..addAll(record.hiddenGroups);
_frames
..clear()
..addAll(record.frames);
notifyListeners();
}
WindowsRecord get record => WindowsRecord(
windows: List.unmodifiable(_all),
hiddenGroups: Set.unmodifiable(_hiddenGroups),
frames: Map.unmodifiable(_frames),
);
Future<void> save() async {
final store = _store;
if (store == null) return;
final revision = _revision;
final saved = await store.write(record.encode(kinds));
if (revision != _revision || saved != saveFailed) return;
saveFailed = !saved;
notifyListeners();
}
void _change(VoidCallback change, {bool save = true}) {
_revision++;
change();
notifyListeners();
if (save) unawaited(this.save());
}
}