From 715efab7780a33c5d8f0783c5bb2499144585e3c Mon Sep 17 00:00:00 2001 From: Alan Silva Date: Tue, 10 Nov 2026 20:16:56 +0000 Subject: [PATCH] Add the window manager, kinds and store for floating windows Phase 1.2 of docs/plans/floating-windows.md: an app-lifetime WindowManager with ordered WindowEntry values, a WindowKind registry and a device-local versioned WindowStore whose server-scoped entries carry their server key. Nothing uses it yet. --- app/lib/shell/windows/window_entry.dart | 101 ++++++ app/lib/shell/windows/window_kind.dart | 74 +++++ app/lib/shell/windows/window_manager.dart | 294 ++++++++++++++++++ app/lib/shell/windows/window_store.dart | 185 +++++++++++ .../shell/windows/window_manager_test.dart | 222 +++++++++++++ app/test/shell/windows/window_store_test.dart | 191 ++++++++++++ 6 files changed, 1067 insertions(+) create mode 100644 app/lib/shell/windows/window_entry.dart create mode 100644 app/lib/shell/windows/window_kind.dart create mode 100644 app/lib/shell/windows/window_manager.dart create mode 100644 app/lib/shell/windows/window_store.dart create mode 100644 app/test/shell/windows/window_manager_test.dart create mode 100644 app/test/shell/windows/window_store_test.dart diff --git a/app/lib/shell/windows/window_entry.dart b/app/lib/shell/windows/window_entry.dart new file mode 100644 index 00000000..efaa83af --- /dev/null +++ b/app/lib/shell/windows/window_entry.dart @@ -0,0 +1,101 @@ +import 'dart:ui'; + +/// Margin a maximised window keeps from the edges of the window area. +const double windowMaximizedMargin = 8; + +/// One floating window: what it shows and where. Immutable; the +/// `WindowManager` replaces an entry to change it. +class WindowEntry { + const WindowEntry({ + required this.id, + required this.kind, + required this.contentId, + required this.frame, + this.serverKey, + String? groupId, + this.minimized = false, + this.maximized = false, + this.data = const {}, + }) : groupId = groupId ?? kind; + + /// Unique among all windows on this device. + final String id; + + /// The registered `WindowKind.key` that builds this window. + final String kind; + + /// What the kind shows: a chat session id, a run id, `terminal`. + final String contentId; + + /// The server this window belongs to, or null for a device-wide window + /// (the terminal). + final String? serverKey; + + /// Windows shown and hidden together (by a chord); the kind by default. + final String groupId; + + /// The saved frame; it is drawn fitted inside the window area. + final Rect frame; + + /// Hidden by its minimise button; still listed and shown again with its + /// group. + final bool minimized; + final bool maximized; + + /// The kind's own JSON state (see `WindowKind.decodeData`). + final Map data; + + WindowEntry copyWith({ + String? contentId, + Rect? frame, + bool? minimized, + bool? maximized, + Map? data, + }) => WindowEntry( + id: id, + kind: kind, + contentId: contentId ?? this.contentId, + serverKey: serverKey, + groupId: groupId, + frame: frame ?? this.frame, + minimized: minimized ?? this.minimized, + maximized: maximized ?? this.maximized, + data: data ?? this.data, + ); + + @override + String toString() => + 'WindowEntry($id, $kind:$contentId, server: $serverKey, $frame' + '${minimized ? ', minimized' : ''}${maximized ? ', maximized' : ''})'; +} + +/// The key a window's frame is remembered under after it closes, so the same +/// content re-opens where it was. +String windowFrameKey(String kind, String? serverKey, String contentId) => + '$kind\n${serverKey ?? ''}\n$contentId'; + +/// [rect] moved and shrunk to fit inside [bounds], at least [minSize] where +/// the bounds allow it. +Rect fitWindowFrame(Rect rect, Size bounds, Size minSize) { + final width = rect.width + .clamp(minSize.width, double.infinity) + .clamp(0.0, bounds.width); + final height = rect.height + .clamp(minSize.height, double.infinity) + .clamp(0.0, bounds.height); + return Rect.fromLTWH( + rect.left.clamp(0.0, bounds.width - width), + rect.top.clamp(0.0, bounds.height - height), + width, + height, + ); +} + +/// Where [entry] is drawn inside [bounds]: fitted, or filling the area less +/// a margin when maximised. +Rect drawnWindowFrame(WindowEntry entry, Size bounds, Size minSize) => + entry.maximized + ? (Offset.zero & bounds).deflate( + windowMaximizedMargin.clamp(0.0, bounds.shortestSide / 2), + ) + : fitWindowFrame(entry.frame, bounds, minSize); diff --git a/app/lib/shell/windows/window_kind.dart b/app/lib/shell/windows/window_kind.dart new file mode 100644 index 00000000..78ed7b6b --- /dev/null +++ b/app/lib/shell/windows/window_kind.dart @@ -0,0 +1,74 @@ +import 'package:flutter/widgets.dart'; + +import 'window_entry.dart'; + +/// One action in a window's title bar, before Minimise and Close (Dock on a +/// chat, a kind's own menu). +class WindowAction { + const WindowAction({ + required this.label, + required this.icon, + required this.onPressed, + }); + + /// The tooltip and semantics label. + final String label; + final IconData icon; + final VoidCallback onPressed; +} + +/// What a kind of window is: how its content is built, titled and saved. +/// Kinds register once at app start (see [WindowKinds]); the host and the +/// manager know nothing else about a window's content. +abstract class WindowKind { + const WindowKind(); + + /// Stable identifier, saved with each window. + String get key; + + /// Whether this kind's windows belong to one server (a chat) rather than + /// the device (the terminal). + bool get serverScoped; + + Size get minSize => const Size(320, 240); + + /// The frame of this kind's first window; later ones cascade from it. + Rect get defaultFrame => const Rect.fromLTWH(120, 96, 480, 560); + + IconData get icon; + + String title(BuildContext context, WindowEntry entry); + + /// The window's content, below the title bar. + Widget build(BuildContext context, WindowEntry entry); + + /// Title-bar actions before Minimise and Close. + List actions(BuildContext context, WindowEntry entry) => + const []; + + /// Called after the user closes the window (the X). + void closed(WindowEntry entry) {} + + /// Validates a saved window's [WindowEntry.data]; null drops the window. + /// The default keeps no state. + Map? decodeData(Object? raw) => const {}; + + /// What is saved for [entry] besides its identity and frame. + Object? encodeData(WindowEntry entry) => null; +} + +/// The registered window kinds, by key. +class WindowKinds { + final Map _kinds = {}; + + void register(WindowKind kind) { + assert(!_kinds.containsKey(kind.key), 'window kind ${kind.key} twice'); + _kinds[kind.key] = kind; + } + + void unregister(String key) => _kinds.remove(key); + + WindowKind? operator [](String key) => _kinds[key]; + + Iterable get all => _kinds.values; +} diff --git a/app/lib/shell/windows/window_manager.dart b/app/lib/shell/windows/window_manager.dart new file mode 100644 index 00000000..a6e5249b --- /dev/null +++ b/app/lib/shell/windows/window_manager.dart @@ -0,0 +1,294 @@ +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 _all = []; + final Set _hiddenGroups = {}; + final Map _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 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 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 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? 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 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 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()); + } +} diff --git a/app/lib/shell/windows/window_store.dart b/app/lib/shell/windows/window_store.dart new file mode 100644 index 00000000..9bee763d --- /dev/null +++ b/app/lib/shell/windows/window_store.dart @@ -0,0 +1,185 @@ +import 'dart:convert'; +import 'dart:ui'; + +import 'package:shared_preferences/shared_preferences.dart'; + +import 'window_entry.dart'; +import 'window_kind.dart'; + +const windowsPreferenceKey = 'pipelines.windows.v1'; + +/// The most windows and remembered frames saved (and restored). +const int windowStoreMaxWindows = 48; +const int windowStoreMaxFrames = 256; + +/// The windows as saved on this device, for every server: the open windows +/// bottom to top, the groups hidden by their chord, and the frames of closed +/// windows by [windowFrameKey]. Identities and geometry only. +class WindowsRecord { + const WindowsRecord({ + this.windows = const [], + this.hiddenGroups = const {}, + this.frames = const {}, + }); + + final List windows; + final Set hiddenGroups; + final Map frames; + + String encode(WindowKinds kinds) => jsonEncode({ + 'version': 1, + 'windows': [ + for (final w in windows) + { + 'id': w.id, + 'kind': w.kind, + 'content': w.contentId, + if (w.serverKey != null) 'server': w.serverKey, + 'group': w.groupId, + 'frame': _encodeRect(w.frame), + if (w.minimized) 'minimized': true, + if (w.maximized) 'maximized': true, + 'data': ?kinds[w.kind]?.encodeData(w), + }, + ], + 'hidden_groups': hiddenGroups.toList()..sort(), + 'frames': { + for (final MapEntry(:key, :value) in frames.entries) + key: _encodeRect(value), + }, + }); + + /// Null when [source] is not a record. A window of an unregistered kind, + /// or whose kind rejects its data, is dropped; the rest are kept. + static WindowsRecord? decode(String source, WindowKinds kinds) { + if (source.length > 262144) return null; + try { + final data = jsonDecode(source); + if (data is! Map || data['version'] != 1) return null; + final rawWindows = data['windows']; + final rawHidden = data['hidden_groups'] ?? const []; + final rawFrames = data['frames'] ?? const {}; + if (rawWindows is! List || rawHidden is! List || rawFrames is! Map) { + return null; + } + if (rawWindows.length > windowStoreMaxWindows || + rawFrames.length > windowStoreMaxFrames) { + return null; + } + final windows = []; + for (final raw in rawWindows) { + final window = _window(raw, kinds); + if (window == null || windows.any((w) => w.id == window.id)) continue; + windows.add(window); + } + final frames = {}; + for (final MapEntry(:key, :value) in rawFrames.entries) { + final rect = _rect(value); + if (key is String && key.length <= 1024 && rect != null) { + frames[key] = rect; + } + } + return WindowsRecord( + windows: windows, + hiddenGroups: { + for (final g in rawHidden) + if (_identity(g, 256)) g as String, + }, + frames: frames, + ); + } on Object { + return null; + } + } + + static WindowEntry? _window(Object? raw, WindowKinds kinds) { + if (raw is! Map) return null; + final id = raw['id'], kindKey = raw['kind'], content = raw['content']; + final server = raw['server'], group = raw['group']; + final frame = _rect(raw['frame']); + if (!_identity(id, 256) || + !_identity(kindKey, 64) || + !_identity(content, 512) || + (server != null && !_identity(server, 512)) || + (group != null && !_identity(group, 256)) || + frame == null) { + return null; + } + final kind = kinds[kindKey as String]; + if (kind == null || kind.serverScoped != (server != null)) return null; + final data = kind.decodeData(raw['data']); + if (data == null) return null; + return WindowEntry( + id: id as String, + kind: kindKey, + contentId: content as String, + serverKey: server as String?, + groupId: group as String?, + frame: frame, + minimized: raw['minimized'] == true, + maximized: raw['maximized'] == true, + data: data, + ); + } + + static List _encodeRect(Rect r) => [ + r.left, + r.top, + r.width, + r.height, + ]; + + static Rect? _rect(Object? values) { + if (values is! List || + values.length != 4 || + values.any((v) => v is! num || !v.isFinite)) { + return null; + } + final [left, top, width, height] = [ + for (final v in values) (v as num).toDouble(), + ]; + if (width <= 0 || height <= 0) return null; + return Rect.fromLTWH(left, top, width, height); + } +} + +bool _identity(Object? value, int limit) => + value is String && + value.isNotEmpty && + value.length <= limit && + value.trim() == value && + !value.contains(RegExp(r'[\x00-\x1f\x7f]')); + +/// Where the windows are kept. Device-local: one record for every server, +/// each server-scoped window carrying its server's key. +abstract interface class WindowStore { + Future read(); + Future write(String record); +} + +class SharedPreferencesWindowStore implements WindowStore { + const SharedPreferencesWindowStore(); + + @override + Future read() async { + try { + return (await SharedPreferences.getInstance()).getString( + windowsPreferenceKey, + ); + } on Object { + return null; + } + } + + @override + Future write(String record) async { + try { + return await (await SharedPreferences.getInstance()).setString( + windowsPreferenceKey, + record, + ); + } on Object { + return false; + } + } +} diff --git a/app/test/shell/windows/window_manager_test.dart b/app/test/shell/windows/window_manager_test.dart new file mode 100644 index 00000000..0e0351d3 --- /dev/null +++ b/app/test/shell/windows/window_manager_test.dart @@ -0,0 +1,222 @@ +import 'package:flutter/widgets.dart'; +import 'package:flutter_test/flutter_test.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'; +import 'package:pipelines_app/shell/windows/window_store.dart'; + +class _Kind extends WindowKind { + _Kind(this.key, {this.serverScoped = false}); + @override + final String key; + @override + final bool serverScoped; + final closedIds = []; + @override + IconData get icon => const IconData(0x41); + @override + String title(BuildContext context, WindowEntry entry) => entry.contentId; + @override + Widget build(BuildContext context, WindowEntry entry) => const SizedBox(); + @override + void closed(WindowEntry entry) => closedIds.add(entry.id); + @override + Map? decodeData(Object? raw) => switch (raw) { + null => const {}, + {'pane': final String pane} => {'pane': pane}, + _ => null, + }; + @override + Object? encodeData(WindowEntry entry) => + entry.data.isEmpty ? null : entry.data; +} + +class _Store implements WindowStore { + String? value; + bool fail = false; + int writes = 0; + @override + Future read() async => value; + @override + Future write(String record) async { + writes++; + if (fail) return false; + value = record; + return true; + } +} + +WindowKinds _kinds() => WindowKinds() + ..register(_Kind('chat', serverScoped: true)) + ..register(_Kind('terminal')); + +void main() { + late _Store store; + late WindowManager manager; + + setUp(() { + store = _Store(); + manager = WindowManager(kinds: _kinds(), store: store, server: 'home'); + }); + + List order() => [for (final w in manager.windows) w.contentId]; + + test('open adds on top, cascades siblings and reuses an open window', () { + final a = manager.open('chat', 'a'); + final b = manager.open('chat', 'b'); + final t = manager.open('terminal', 'terminal'); + expect(order(), ['a', 'b', 'terminal']); + expect(b.frame, a.frame.shift(windowCascadeStep)); + expect(t.serverKey, isNull); + expect(a.serverKey, 'home'); + expect(manager.active?.id, t.id); + + final again = manager.open('chat', 'a'); + expect(again.id, a.id); + expect(order(), ['b', 'terminal', 'a']); + expect(() => manager.open('nope', 'x'), throwsStateError); + }); + + test('a server-scoped window needs a server', () { + manager.server = null; + expect(() => manager.open('chat', 'a'), throwsStateError); + expect(manager.open('terminal', 'terminal').serverKey, isNull); + }); + + test('raise, frames, maximise and minimise', () { + final a = manager.open('chat', 'a'); + final b = manager.open('chat', 'b'); + expect(manager.raise(a.id), isTrue); + expect(manager.raise(a.id), isFalse); + expect(order(), ['b', 'a']); + + var notified = 0; + manager.addListener(() => notified++); + final writes = store.writes; + manager.setFrame(a.id, const Rect.fromLTWH(1, 2, 400, 300), save: false); + expect(manager.byId(a.id)!.frame, const Rect.fromLTWH(1, 2, 400, 300)); + expect(store.writes, writes); + manager.setFrame(a.id, const Rect.fromLTWH(1, 2, 400, 300), save: false); + expect(notified, 1); + manager.commit(); + expect(store.writes, writes + 1); + + manager.setMaximized(a.id, true); + expect(manager.byId(a.id)!.maximized, isTrue); + manager.setMinimized(a.id, true); + expect(manager.isVisible(manager.byId(a.id)!), isFalse); + expect(manager.active?.id, b.id); + manager.show(a.id); + expect(manager.active?.id, a.id); + expect(manager.byId(a.id)!.minimized, isFalse); + }); + + test('a group hides and shows together and brings back minimised', () { + final a = manager.open('chat', 'a'); + manager.open('chat', 'b'); + final t = manager.open('terminal', 'terminal'); + manager.setMinimized(a.id, true); + + expect(manager.toggleGroup('chat'), isTrue); + expect(manager.groupShown('chat'), isFalse); + expect(manager.windows.where(manager.isVisible).single.id, t.id); + + manager.toggleGroup('chat'); + expect(manager.windows.where(manager.isVisible), hasLength(3)); + expect(manager.byId(a.id)!.minimized, isFalse); + + // Every window minimised: the chord shows them rather than hiding. + for (final w in manager.inGroup('chat').toList()) { + manager.setMinimized(w.id, true); + } + manager.toggleGroup('chat'); + expect(manager.inGroup('chat').every(manager.isVisible), isTrue); + expect(manager.toggleGroup('run'), isFalse); + + // Opening a window of a hidden group shows the group. + manager.setGroupShown('chat', false); + manager.open('chat', 'c'); + expect(manager.groupShown('chat'), isTrue); + }); + + test('close remembers the frame for the content and tells the kind', () { + final a = manager.open('chat', 'a'); + manager.setFrame(a.id, const Rect.fromLTWH(300, 200, 500, 400)); + manager.close(a.id); + expect(manager.windows, isEmpty); + expect((manager.kinds['chat']! as _Kind).closedIds, [a.id]); + final again = manager.open('chat', 'a'); + expect(again.frame, const Rect.fromLTWH(300, 200, 500, 400)); + expect(again.id, isNot(a.id)); + }); + + test('cycle walks the visible windows both ways', () { + manager.open('chat', 'a'); + manager.open('chat', 'b'); + manager.open('chat', 'c'); + manager.cycle(); + expect(order(), ['b', 'c', 'a']); + manager.cycle(-1); + expect(order(), ['a', 'b', 'c']); + manager.setMinimized(manager.find('chat', 'a')!.id, true); + manager.cycle(); + expect(manager.active?.contentId, 'b'); + }); + + test('windows are listed per server and kept for the others', () { + manager.open('chat', 'a'); + manager.open('terminal', 'terminal'); + manager.server = 'work'; + expect(order(), ['terminal']); + final b = manager.open('chat', 'a'); + expect(b.serverKey, 'work'); + expect(manager.record.windows, hasLength(3)); + manager.server = 'home'; + expect(order(), ['a', 'terminal']); + expect(manager.byId(b.id), isNull); + }); + + test('saves every change and restores order, state and frames', () async { + final a = manager.open('chat', 'a', data: const {'pane': 'p1'}); + manager.open('terminal', 'terminal'); + final c = manager.open('chat', 'c'); + manager.setMaximized(a.id, true); + manager.close(c.id); + manager.setGroupShown('terminal', false); + await pumpEventQueue(); + + final next = WindowManager(kinds: _kinds(), store: store, server: 'home'); + await next.restore(); + expect([for (final w in next.windows) w.contentId], ['a', 'terminal']); + final restored = next.find('chat', 'a')!; + expect(restored.maximized, isTrue); + expect(restored.data, {'pane': 'p1'}); + expect(restored.serverKey, 'home'); + expect(next.groupShown('terminal'), isFalse); + expect(next.open('chat', 'c').frame, c.frame); + // New ids never collide with restored ones. + expect(next.open('chat', 'd').id, isNot(restored.id)); + }); + + test('a restore never overwrites a change made while it loaded', () async { + manager.open('chat', 'a'); + await pumpEventQueue(); + final next = WindowManager(kinds: _kinds(), store: store, server: 'home'); + final restoring = next.restore(); + next.open('chat', 'z'); + await restoring; + expect([for (final w in next.windows) w.contentId], ['z']); + }); + + test('a failed save is reported and clears on the next good one', () async { + store.fail = true; + final a = manager.open('chat', 'a'); + await pumpEventQueue(); + expect(manager.saveFailed, isTrue); + store.fail = false; + manager.raise(a.id); + manager.setMinimized(a.id, true); + await pumpEventQueue(); + expect(manager.saveFailed, isFalse); + }); +} diff --git a/app/test/shell/windows/window_store_test.dart b/app/test/shell/windows/window_store_test.dart new file mode 100644 index 00000000..10d9a613 --- /dev/null +++ b/app/test/shell/windows/window_store_test.dart @@ -0,0 +1,191 @@ +import 'dart:convert'; + +import 'package:flutter/widgets.dart'; +import 'package:flutter_test/flutter_test.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_store.dart'; +import 'package:shared_preferences/shared_preferences.dart'; + +class _Kind extends WindowKind { + _Kind(this.key, {this.serverScoped = false}); + @override + final String key; + @override + final bool serverScoped; + @override + IconData get icon => const IconData(0x41); + @override + String title(BuildContext context, WindowEntry entry) => entry.contentId; + @override + Widget build(BuildContext context, WindowEntry entry) => const SizedBox(); + @override + Map? decodeData(Object? raw) => switch (raw) { + null => const {}, + {'pane': final String pane} => {'pane': pane}, + _ => null, + }; + @override + Object? encodeData(WindowEntry entry) => + entry.data.isEmpty ? null : entry.data; +} + +final _kinds = WindowKinds() + ..register(_Kind('chat', serverScoped: true)) + ..register(_Kind('terminal')); + +Map _window(Map overrides) => { + 'id': 'chat-1', + 'kind': 'chat', + 'content': 's1', + 'server': 'home', + 'group': 'chat', + 'frame': [10, 20, 400, 300], + ...overrides, +}..removeWhere((key, value) => value == '#remove'); + +WindowsRecord? _decode(Object windows, {Object? frames, Object? hidden}) => + WindowsRecord.decode( + jsonEncode({ + 'version': 1, + 'windows': windows, + 'hidden_groups': ?hidden, + 'frames': ?frames, + }), + _kinds, + ); + +void main() { + test('a record round-trips', () { + const record = WindowsRecord( + windows: [ + WindowEntry( + id: 'terminal-1', + kind: 'terminal', + contentId: 'terminal', + frame: Rect.fromLTWH(80, 80, 720, 420), + minimized: true, + ), + WindowEntry( + id: 'chat-2', + kind: 'chat', + contentId: 's2', + serverKey: 'home', + groupId: 'chats', + frame: Rect.fromLTWH(1.5, 2, 480, 560), + maximized: true, + data: {'pane': 'p2'}, + ), + ], + hiddenGroups: {'terminal'}, + frames: {'chat\nhome\ns9': Rect.fromLTWH(5, 6, 700, 800)}, + ); + final decoded = WindowsRecord.decode(record.encode(_kinds), _kinds)!; + expect(decoded.windows.map((w) => w.toString()), [ + for (final w in record.windows) w.toString(), + ]); + expect(decoded.windows.last.groupId, 'chats'); + expect(decoded.windows.last.data, {'pane': 'p2'}); + expect(decoded.hiddenGroups, {'terminal'}); + expect(decoded.frames, record.frames); + }); + + test('not a record', () { + expect(WindowsRecord.decode('nope', _kinds), isNull); + expect(WindowsRecord.decode('[]', _kinds), isNull); + expect(WindowsRecord.decode('{"version":2,"windows":[]}', _kinds), isNull); + expect(WindowsRecord.decode('{"version":1}', _kinds), isNull); + expect(_decode(const [], frames: const []), isNull); + expect( + _decode([for (var i = 0; i <= windowStoreMaxWindows; i++) _window({})]), + isNull, + ); + expect(WindowsRecord.decode('x' * 262145, _kinds), isNull); + }); + + test('a bad window is dropped and the rest kept', () { + final good = _window({'id': 'chat-9', 'content': 's9'}); + for (final bad in [ + _window({'kind': 'run'}), + _window({'id': ''}), + _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({'data': 7}), + 'text', + ]) { + final record = _decode([bad, good])!; + expect(record.windows.single.id, 'chat-9', reason: '$bad'); + } + // A repeated id keeps the first. + expect(_decode([good, good])!.windows, hasLength(1)); + }); + + test('bad frames and groups are skipped', () { + final record = _decode( + const [], + frames: { + 'a': [1, 2, 3, 4], + 'b': [1, 2, -3, 4], + 'c': 'x', + }, + hidden: ['chat', '', 7], + )!; + expect(record.frames.keys, ['a']); + expect(record.hiddenGroups, {'chat'}); + }); + + test('fit keeps a window inside the area at its minimum size', () { + const min = Size(320, 240); + expect( + fitWindowFrame( + const Rect.fromLTWH(900, -50, 100, 100), + const Size(1000, 800), + min, + ), + const Rect.fromLTWH(680, 0, 320, 240), + ); + expect( + fitWindowFrame( + const Rect.fromLTWH(10, 10, 2000, 2000), + const Size(300, 200), + min, + ), + const Rect.fromLTWH(0, 0, 300, 200), + ); + const entry = WindowEntry( + id: 'w', + kind: 'chat', + contentId: 'c', + frame: Rect.fromLTWH(10, 10, 400, 300), + maximized: true, + ); + expect( + drawnWindowFrame(entry, const Size(1000, 800), min), + const Rect.fromLTWH(8, 8, 984, 784), + ); + expect( + drawnWindowFrame( + entry.copyWith(maximized: false), + const Size(1000, 800), + min, + ), + entry.frame, + ); + }); + + test('the shared-preferences store reads what it wrote', () async { + SharedPreferences.setMockInitialValues({}); + const store = SharedPreferencesWindowStore(); + expect(await store.read(), isNull); + expect(await store.write('{"version":1,"windows":[]}'), isTrue); + expect(await store.read(), '{"version":1,"windows":[]}'); + expect( + (await SharedPreferences.getInstance()).getString(windowsPreferenceKey), + isNotNull, + ); + }); +}