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 = {}; /// The size each kind's windows were last given, for its next new window. final Map _sizes = {}; 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; /// The frame the current server's window of [kind] for [contentId] has, /// or had when it last closed. Rect? lastFrame(String kind, String contentId) => find(kind, contentId)?.frame ?? _frames[windowFrameKey( kind, (kinds[kind]?.serverScoped ?? false) ? _server : null, contentId, )]; Iterable inGroup(String groupId) => windows.where((w) => w.groupId == groupId); 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.topLeft + windowCascadeStep * siblings.toDouble()) & (_sizes[kind] ?? spec.defaultFrame.size), 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, 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)); 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; } /// Hides the group when it is active; otherwise shows and raises its most /// recently used window. A global shortcut should bring a group forward when /// pressed from another window, rather than hide it behind that window. bool toggleOrRaiseGroup(String groupId) { final group = inGroup(groupId).toList(); if (group.isEmpty) return false; if (group.any(isVisible) && active?.groupId == groupId) { setGroupShown(groupId, false); } else { show(group.last.id); } 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); _sizes ..clear() ..addAll(record.sizes); notifyListeners(); } WindowsRecord get record => WindowsRecord( windows: List.unmodifiable(_all), hiddenGroups: Set.unmodifiable(_hiddenGroups), frames: Map.unmodifiable(_frames), sizes: Map.unmodifiable(_sizes), ); 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()); } }