Merge commit '4273f9d801f20420be383be90e60cf6b30cfeb58' into pipelines/run-20261110-2013-surfacevisibility-signal-replaces-ticker-a247

This commit is contained in:
2026-11-10 20:28:22 +00:00
6 changed files with 1067 additions and 0 deletions
+101
View File
@@ -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<String, Object?> data;
WindowEntry copyWith({
String? contentId,
Rect? frame,
bool? minimized,
bool? maximized,
Map<String, Object?>? 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);
+74
View File
@@ -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<WindowAction> 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<String, Object?>? 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<String, WindowKind> _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<WindowKind> get all => _kinds.values;
}
+294
View File
@@ -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<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());
}
}
+185
View File
@@ -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<WindowEntry> windows;
final Set<String> hiddenGroups;
final Map<String, Rect> 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 = <WindowEntry>[];
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 = <String, Rect>{};
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<double> _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<String?> read();
Future<bool> write(String record);
}
class SharedPreferencesWindowStore implements WindowStore {
const SharedPreferencesWindowStore();
@override
Future<String?> read() async {
try {
return (await SharedPreferences.getInstance()).getString(
windowsPreferenceKey,
);
} on Object {
return null;
}
}
@override
Future<bool> write(String record) async {
try {
return await (await SharedPreferences.getInstance()).setString(
windowsPreferenceKey,
record,
);
} on Object {
return false;
}
}
}