Host floating chats on the shell window system

Phase 2.3 and 2.4 of docs/plans/floating-windows.md. A floating chat is a
window of the chat kind over the app's WindowManager, built from the
app-lifetime ChatRuntime, so it shows over every destination and at start
without the Chat destination being built. Float and Dock move the same
keyed view between the tiling and the window host. The pipelines app keeps
one runtime and one ChatWindows; saved chatFloat records (v1 and v2) are
brought over once.

ChatFloatHost, ChatFloatWindow, the float frames and binding, the
controller's float list and FloatingFocusRoot are gone; the workspace only
asks whether a chat is out in a window. Every MenuAnchor targets the root
overlay (guarded by a test), and menus and tooltips name the Alt chords.
This commit is contained in:
2026-11-10 21:17:40 +00:00
parent 9695100faa
commit fdc730422d
44 changed files with 1369 additions and 1792 deletions
+47 -61
View File
@@ -1,81 +1,67 @@
part of 'screen.dart';
/// The floating chats for one Chat destination visit: their menu choices,
/// window frames and persistence (see `notes/chat-floating-pane.md`).
/// Floating a tiled pane into a window and docking it back (see
/// [ChatWindows] and `notes/chat-floating-pane.md`).
mixin _ChatScreenFloat on State<ChatScreen>, _ChatScreenWorkspace {
@override
final ChatFloatFrames _floatFrames = ChatFloatFrames();
ChatFloatBinding? _floatBinding;
ChatTiling? _tiling;
/// Restores and saves the floating chat in [store] once [restored] (the
/// workspace layout's own restore) completes.
@override
void _bindFloat(ChatFloatStore store, Future<void> restored) {
_floatBinding?.dispose();
final binding = _floatBinding = ChatFloatBinding(
controller: _workspace,
frames: _floatFrames,
store: store,
);
unawaited(
restored.then((_) {
if (mounted && identical(_floatBinding, binding)) {
return binding.start();
}
}),
void _bindWindows() {
final windows = widget.windows;
if (windows == null) return;
_workspace.showOutside = windows.show;
windows.tiling = _tiling = ChatTiling(
holds: _workspace.holdsSession,
dock: _dockSession,
canFloatActive: () {
final pane = _workspace.activePane;
return mounted &&
pane != null &&
_floatsHere &&
_workspaceVisible &&
_workspace.canFloat(pane.id) &&
_chatOwnsKeyboard();
},
floatActive: () {
final pane = _workspace.activePane;
if (pane != null) _floatPane(pane.id);
},
);
}
@override
void _unbindFloat() {
_floatBinding?.dispose();
_floatBinding = null;
}
void _disposeFloat() {
_unbindFloat();
_floatFrames.dispose();
void _unbindWindows() {
final windows = widget.windows;
if (windows != null && identical(windows.tiling, _tiling)) {
windows.tiling = null;
}
_workspace.showOutside = null;
}
/// Panes float only on a wide layout, beside the chat list.
bool get _floatsHere => !_pageOpen && showsListBesideDetail(context);
bool get _floatsHere =>
widget.windows != null && !_pageOpen && showsListBesideDetail(context);
void _dockFloat(ChatWorkspacePane pane) {
_workspace.dock(pane.id);
_composerFocus.request(pane.sessionId);
/// The pane leaves the tiling and its live view moves into a window in
/// the same frame.
void _floatPane(String paneId) {
final pane = _workspace.detach(paneId);
if (pane != null) widget.windows?.float(pane.sessionId);
}
/// The pane menu's floating choices: Float on a tiled pane that can, and
/// Dock, Hide and Close on a floating chat.
void _dockSession(String sessionId) {
if (!mounted) return;
_workspaceVisible = true;
if (!_pageOpen && showsListBesideDetail(context)) _usedWorkspace = true;
_workspace.dock(sessionId);
_composerFocus.request(sessionId);
}
/// The pane menu's Float choice, on a tiled pane that can.
List<Widget> _floatControls(ChatWorkspacePane pane) {
final shortcut = chatFloatShortcutLabel();
if (_workspace.isFloating(pane.id)) {
return [
ChatBarAction(
label: 'Dock',
onPressed: () => _dockFloat(pane),
materialIcon: Icons.vertical_split_outlined,
cupertinoIcon: CupertinoIcons.rectangle_split_3x1,
),
ChatBarAction(
label: 'Hide floating chats ($shortcut)',
onPressed: () => _workspace.setFloatShown(false),
materialIcon: Icons.visibility_off_outlined,
cupertinoIcon: CupertinoIcons.eye_slash,
),
ChatBarAction(
label: 'Close pane',
onPressed: () => _closePane(pane.id),
materialIcon: Icons.close,
cupertinoIcon: CupertinoIcons.xmark,
),
];
}
if (!_floatsHere || !_workspace.canFloat(pane.id)) return const [];
return [
ChatBarAction(
label: 'Float ($shortcut)',
onPressed: () => _workspace.float(pane.id),
label: 'Float (${chatFloatShortcutLabel()})',
onPressed: () => _floatPane(pane.id),
materialIcon: Icons.picture_in_picture_alt_outlined,
cupertinoIcon: CupertinoIcons.rectangle_on_rectangle,
),
@@ -11,9 +11,6 @@ mixin _ChatScreenWorkspace on State<ChatScreen> {
JsonMap? _rowFor(String id);
void _back();
bool get _pageOpen;
ChatFloatFrames get _floatFrames;
void _bindFloat(ChatFloatStore store, Future<void> restored);
void _unbindFloat();
Widget _thread(ChatWorkspacePane pane);
ChatSidebarMode _sidebarMode = ChatSidebarMode.expanded;
@@ -112,17 +109,8 @@ mixin _ChatScreenWorkspace on State<ChatScreen> {
_publishWorkspaceRoute();
},
);
final restored = _workspaceBinding!.start(
initialSessionId: widget.initialSessionId,
);
unawaited(restored);
_bindFloat(
SharedPreferencesChatFloatStore(
serverScope: widget.gateway is FederatedChatGateway
? 'all-saved-servers'
: scope,
),
restored,
unawaited(
_workspaceBinding!.start(initialSessionId: widget.initialSessionId),
);
}
@@ -134,7 +122,6 @@ mixin _ChatScreenWorkspace on State<ChatScreen> {
}
_workspaceBinding?.dispose();
_workspaceBinding = null;
_unbindFloat();
if (_workspaceScope != null && scope != _workspaceScope) {
_workspace.restoreLayout(ChatWorkspaceSnapshot.fromLayout(null, null)!);
_forgetRecentSessions();
@@ -323,7 +310,6 @@ mixin _ChatScreenWorkspace on State<ChatScreen> {
controller: _workspace,
onVisibleSessionIdsChanged: _workspaceVisibilityChanged,
shortcutsEnabled: _workspaceVisible,
floatFrames: _floatFrames,
singlePane: !showsListBesideDetail(context),
mobilePeeks: true,
paneTitle: (pane) =>
@@ -159,6 +159,8 @@ class _ChatEffortControlState extends State<ChatEffortControl> {
);
}
return MenuAnchor(
// Above every floating window, and not clipped to one.
useRootOverlay: true,
menuChildren: [
Padding(
padding: const EdgeInsets.fromLTRB(12, 8, 12, 4),
@@ -1,3 +1,4 @@
import '../../../shell/windows/window_scope.dart';
import '../../terminal/terminal_open_action.dart';
import 'dart:async';
@@ -1429,6 +1430,15 @@ class _ChatThreadViewState extends State<ChatThreadView> {
],
moreActions: [
?widget.sidebarControl,
// A window's own title bar names the chat, and its narrow action
// bar has no room for the title that opens the details.
if (WindowScope.maybeOf(context) != null)
ChatBarAction(
label: 'Chat details',
onPressed: _openInfo,
materialIcon: Icons.info_outline,
cupertinoIcon: CupertinoIcons.info,
),
...widget.paneControls,
chatShellRunMenuAction(onPressed: _runShellFromMenu),
if (_shellRuns.finishedIds.isNotEmpty)
+37 -43
View File
@@ -1,5 +1,6 @@
import 'chat_pane_content.dart';
import 'chat_runtime.dart';
import 'windows/chat_windows.dart';
import 'workspace/federated_workspace_store.dart';
import '../../core/servers/chat/federated_chat_gateway.dart';
import '../../shell/destination.dart';
@@ -20,9 +21,7 @@ import 'package:flutter/services.dart';
import '../../core/api_gateway.dart';
import '../../core/servers/server_scope.dart';
import 'workspace/chat_float_binding.dart';
import 'workspace/chat_float_shortcut.dart';
import 'workspace/chat_float_store.dart';
import 'workspace/chat_workspace_binding.dart';
import 'workspace/chat_workspace_snapshot.dart';
import 'workspace/chat_workspace_store.dart';
@@ -74,6 +73,7 @@ class ChatScreen extends StatefulWidget {
this.onAvailableSessionsChanged,
this.persistWorkspace = false,
this.runtime,
this.windows,
});
final ApiGateway gateway;
@@ -83,6 +83,10 @@ class ChatScreen extends StatefulWidget {
/// keeps its own for the visit when null.
final ChatRuntime? runtime;
/// The app's floating chat windows; null offers none (a pane cannot
/// float).
final ChatWindows? windows;
/// The chat session the current route names, or null for the list.
final String? initialSessionId;
@@ -137,6 +141,7 @@ class _ChatScreenState extends State<ChatScreen>
..gateway = widget.gateway
..addListener(_runtimeChanged);
_runtime.addSessionReplacedListener(_replacedElsewhere);
_bindWindows();
final initial = widget.initialSessionId;
if (initial != null && initial.isNotEmpty) {
_workspace.open(initial);
@@ -282,12 +287,6 @@ class _ChatScreenState extends State<ChatScreen>
.toList()) {
_closePane(pane.id);
}
for (final pane
in _workspace.floatingPanes
.where((pane) => pane.sessionId == sessionId)
.toList()) {
_closePane(pane.id);
}
unawaited(_sessions.refresh());
}
@@ -374,7 +373,7 @@ class _ChatScreenState extends State<ChatScreen>
HardwareKeyboard.instance.removeHandler(_slashFocusKey);
_page.dispose();
_workspaceBinding?.dispose();
_disposeFloat();
_unbindWindows();
_workspace.removeListener(_workspaceChanged);
_workspace.dispose();
_sessions.removeListener(_nextChanged);
@@ -402,41 +401,36 @@ class _ChatScreenState extends State<ChatScreen>
: null,
useNativeBack: _page.open,
pasteTarget: _workspaceVisible && pane.id == _workspace.activePaneId,
// A floating chat is never the active pane, so its composer takes a
// paste while it has the keyboard.
ownsPasteWhenFocused: _workspace.isFloating(pane.id),
showBackButton: _page.open || !showsListBesideDetail(context),
paneControls: (paneContext) => _workspace.isFloating(pane.id)
? _floatControls(pane)
: [
ChatBarAction(
label: 'Add chat pane',
onPressed: () => _addPane(paneContext),
materialIcon: Icons.add_box_outlined,
cupertinoIcon: CupertinoIcons.plus_square,
),
if (_workspace.paneCount > 1)
ChatBarAction(
label: 'Open chats (${_workspace.paneCount})',
onPressed: () => _pickPane(paneContext),
materialIcon: Icons.view_quilt_outlined,
cupertinoIcon: CupertinoIcons.square_split_2x2,
),
if (_workspace.paneCount > 1 && showsListBesideDetail(context))
chatCenterStageAction(ChatCenterStageController.instance),
...chatPaneMoveActions(
ChatWorkspacePaneScope.maybeOf(paneContext),
onMove: (target) => _movePane(pane.id, target),
),
..._floatControls(pane),
if (_workspace.paneCount > 1)
ChatBarAction(
label: 'Close pane',
onPressed: () => _closePane(pane.id),
materialIcon: Icons.close,
cupertinoIcon: CupertinoIcons.xmark,
),
],
paneControls: (paneContext) => [
ChatBarAction(
label: 'Add chat pane',
onPressed: () => _addPane(paneContext),
materialIcon: Icons.add_box_outlined,
cupertinoIcon: CupertinoIcons.plus_square,
),
if (_workspace.paneCount > 1)
ChatBarAction(
label: 'Open chats (${_workspace.paneCount})',
onPressed: () => _pickPane(paneContext),
materialIcon: Icons.view_quilt_outlined,
cupertinoIcon: CupertinoIcons.square_split_2x2,
),
if (_workspace.paneCount > 1 && showsListBesideDetail(context))
chatCenterStageAction(ChatCenterStageController.instance),
...chatPaneMoveActions(
ChatWorkspacePaneScope.maybeOf(paneContext),
onMove: (target) => _movePane(pane.id, target),
),
..._floatControls(pane),
if (_workspace.paneCount > 1)
ChatBarAction(
label: 'Close pane',
onPressed: () => _closePane(pane.id),
materialIcon: Icons.close,
cupertinoIcon: CupertinoIcons.xmark,
),
],
),
);
}
@@ -0,0 +1,68 @@
import 'package:flutter/material.dart';
import '../../../shell/windows/window_entry.dart';
import '../../../ui/adaptive/window_margins.dart';
import '../chat_pane_content.dart';
import 'chat_windows.dart';
/// A floating window's chat: the same live view as a tiled pane (see
/// [buildChatPaneContent]), with what a window decides. Before the server
/// has been reached it says so instead of reading a chat.
class ChatWindowContent extends StatelessWidget {
const ChatWindowContent({
super.key,
required this.windows,
required this.entry,
});
final ChatWindows windows;
final WindowEntry entry;
@override
Widget build(BuildContext context) {
final runtime = windows.runtime;
final sessionId = entry.contentId;
return ListenableBuilder(
listenable: Listenable.merge([
runtime,
runtime.syncToken,
windows.readiness,
]),
builder: (context, _) {
// A chat is drawn once: the tiling wins, and this window closes.
if (windows.tiling?.holds(sessionId) ?? false) {
WidgetsBinding.instance.addPostFrameCallback(
(_) => windows.manager.close(entry.id),
);
return const SizedBox.shrink();
}
if (!windows.ready) {
return Center(
child: Text(
'Connecting…',
style: Theme.of(context).textTheme.bodyMedium,
),
);
}
// A small window keeps the compact bar insets.
return WindowMargins.compact(
child: buildChatPaneContent(
runtime: runtime,
sessionId: sessionId,
placement: ChatPanePlacement(
syncToken: runtime.syncToken.value,
onBack: () {},
showBackButton: false,
// Never the active pane: its composer takes a paste while it
// has the keyboard.
ownsPasteWhenFocused: true,
onNewSession: (previousId, session, notice) => windows
.startedNewSession(entry.id, previousId, session, notice),
onSessionClosed: () => windows.sessionClosed(entry.id),
),
),
);
},
);
}
}
@@ -0,0 +1,280 @@
import 'dart:async';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import '../../../core/api_gateway.dart';
import '../../../shell/list_detail_policy.dart';
import '../../../shell/windows/window_entry.dart';
import '../../../shell/windows/window_kind.dart';
import '../../../shell/windows/window_manager.dart';
import '../chat_runtime.dart';
import '../domain/chat_commands.dart';
import '../workspace/chat_float_shortcut.dart';
import '../workspace/chat_float_store.dart';
import 'chat_window_content.dart';
const chatWindowKind = 'chat';
/// What the mounted Chat destination offers the chat windows: its tiling.
class ChatTiling {
const ChatTiling({
required this.holds,
required this.dock,
required this.canFloatActive,
required this.floatActive,
});
/// Whether the tiling shows [sessionId].
final bool Function(String sessionId) holds;
/// Puts a chat back into the tiling.
final void Function(String sessionId) dock;
/// Whether the chord can float the active pane now.
final bool Function() canFloatActive;
final VoidCallback floatActive;
}
/// The floating chat windows, for the app's lifetime: the `chat` window kind
/// over the app's [WindowManager], its chord (see [chatFloatShortcut]), and
/// what `/new` and `/close` do to a chat in a window. The windows are built
/// from [runtime], so they show whatever destination is open, also when the
/// Chat destination has never been built.
class ChatWindows {
ChatWindows({
required this.manager,
required this.runtime,
required this.openInChat,
this._ready,
Listenable? readiness,
}) : readiness = readiness ?? const _Never();
final WindowManager manager;
final ChatRuntime runtime;
/// Opens a chat in the Chat destination (when no tiling is mounted to
/// dock into).
final void Function(String sessionId) openInChat;
final bool Function()? _ready;
/// Notifies when [ready] may have changed.
final Listenable readiness;
/// The mounted Chat destination's tiling, if it is built.
ChatTiling? tiling;
late final ChatWindowKind kind = ChatWindowKind(this);
bool _started = false;
/// Whether the server has been reached, so a chat can be read.
bool get ready => _ready?.call() ?? true;
Iterable<WindowEntry> get windows =>
manager.windows.where((w) => w.kind == chatWindowKind);
/// Registers the kind and starts answering the chord. Call before the
/// manager restores, so saved chat windows are kept.
void start() {
if (_started) return;
_started = true;
manager.kinds.register(kind);
FocusManager.instance.addEarlyKeyEventHandler(_key);
runtime.addSessionReplacedListener(_replacedElsewhere);
runtime.sessions.addListener(_rowsChanged);
manager.addListener(_rowsChanged);
readiness.addListener(_rowsChanged);
}
void dispose() {
if (!_started) return;
_started = false;
FocusManager.instance.removeEarlyKeyEventHandler(_key);
runtime.removeSessionReplacedListener(_replacedElsewhere);
runtime.sessions.removeListener(_rowsChanged);
manager.removeListener(_rowsChanged);
readiness.removeListener(_rowsChanged);
manager.kinds.unregister(chatWindowKind);
}
/// Opens the windows an older build saved (`pipelines.next.chatFloat.v1`,
/// both formats) once, after the manager restored and found none.
Future<void> migrate(ChatFloatStore legacy) async {
final record = await legacy.read();
if (record == null || record.panes.isEmpty || !_started) return;
if (windows.isEmpty) {
for (final pane in record.panes) {
manager.open(
chatWindowKind,
pane.sessionId,
frame: record.frames[pane.id],
);
}
if (!record.shown) manager.setGroupShown(chatWindowKind, false);
}
await legacy.write(const ChatFloatRecord());
}
/// Shows the window [sessionId] is in; false when it is in none.
bool show(String sessionId) {
final entry = manager.find(chatWindowKind, sessionId);
if (entry == null) return false;
manager.show(entry.id);
return true;
}
/// Opens [sessionId] in a window (the caller took it out of the tiling).
void float(String sessionId) => manager.open(chatWindowKind, sessionId);
/// Puts the window's chat back into the tiling, or opens it in the Chat
/// destination when that is not built.
void dock(WindowEntry entry) {
final tiling = this.tiling;
manager.close(entry.id);
if (tiling != null) {
tiling.dock(entry.contentId);
} else {
openInChat(entry.contentId);
}
}
/// `/new` in a window's chat: the window follows the new session, unless
/// that session is already open elsewhere.
void startedNewSession(
String windowId,
String previousId,
JsonMap session,
String notice,
) {
runtime.sessions.replaceSession(previousId, session);
_follow(windowId, previousId, session, notice);
unawaited(runtime.sessions.refresh());
}
void _replacedElsewhere(String previousId, JsonMap session) {
final entry = manager.find(chatWindowKind, previousId);
if (entry == null) return;
_follow(entry.id, previousId, session, chatNewSessionElsewhereNotice);
}
void _follow(
String windowId,
String previousId,
JsonMap session,
String notice,
) {
final id = '${session['id'] ?? ''}';
if (id.isEmpty) return;
final elsewhere =
manager.find(chatWindowKind, id) != null ||
(tiling?.holds(id) ?? false);
if (elsewhere) {
manager.close(windowId);
return;
}
runtime.movedToSession(previousId, session, notice);
manager.setContent(windowId, id);
}
/// `/close` was accepted for a window's chat.
void sessionClosed(String windowId) {
manager.close(windowId);
unawaited(runtime.sessions.refresh());
}
bool _reading = false;
/// The windows' chats take their rows (title, model, mode) from the
/// session list, which nothing else reads while the Chat destination is
/// not built.
void _rowsChanged() {
final ids = {for (final w in windows) w.contentId};
if (ids.isEmpty || !ready) return;
final sessions = runtime.sessions;
if (ids.any((id) => runtime.rowFor(id) == null) && !_reading) {
_reading = true;
unawaited(sessions.refresh().whenComplete(() => _reading = false));
}
final rows = sessions.sessions;
scheduleMicrotask(() {
if (_started) runtime.adoptRows(rows, selected: null, retained: ids);
});
}
bool get _wide {
final view = WidgetsBinding.instance.platformDispatcher.views.firstOrNull;
return view == null ||
view.physicalSize.width / view.devicePixelRatio >= kListDetailMinWidth;
}
/// Handled before any focused widget sees the key, so it works from a
/// composer or the terminal; ignored (left to them) when it does nothing.
KeyEventResult _key(KeyEvent event) {
if (!_wide || !chatFloatShortcut(event, HardwareKeyboard.instance)) {
return KeyEventResult.ignored;
}
if (windows.isEmpty) {
final tiling = this.tiling;
if (tiling == null || !tiling.canFloatActive()) {
return KeyEventResult.ignored;
}
if (event is KeyDownEvent) tiling.floatActive();
return KeyEventResult.handled;
}
if (event is KeyDownEvent) manager.toggleGroup(chatWindowKind);
return KeyEventResult.handled;
}
}
class _Never implements Listenable {
const _Never();
@override
void addListener(VoidCallback listener) {}
@override
void removeListener(VoidCallback listener) {}
}
/// A chat in a floating window.
class ChatWindowKind extends WindowKind {
ChatWindowKind(this.windows);
final ChatWindows windows;
@override
String get key => chatWindowKind;
@override
bool get serverScoped => true;
@override
IconData get icon => Icons.chat_bubble_outline;
@override
Size get minSize => chatFloatMinSize;
@override
Rect get defaultFrame => chatFloatDefaultRect;
/// Chats float beside the chat list, on a wide layout only.
@override
double get minHostWidth => kListDetailMinWidth;
@override
Listenable get changes => windows.runtime;
@override
String title(BuildContext context, WindowEntry entry) =>
windows.runtime.titleFor(entry.contentId);
@override
Widget build(BuildContext context, WindowEntry entry) =>
ChatWindowContent(windows: windows, entry: entry);
@override
List<WindowAction> actions(BuildContext context, WindowEntry entry) => [
WindowAction(
label: 'Dock',
icon: Icons.vertical_split_outlined,
onPressed: () => windows.dock(entry),
),
];
@override
void focusContent(WindowEntry entry) =>
windows.runtime.composerFocus.request(entry.contentId);
}
@@ -1,156 +0,0 @@
import 'dart:async';
import 'dart:ui';
import 'package:flutter/foundation.dart';
import 'chat_float_store.dart';
import 'chat_workspace_controller.dart';
/// The floating chat windows' frames, by pane id. A drag moves a window every
/// pointer event without saving; [commit] marks the end of the drag. A pane
/// keeps its frame while it is docked, so floating it again puts the window
/// back where it was.
class ChatFloatFrames extends ChangeNotifier {
ChatFloatFrames([Map<String, Rect> frames = const {}])
: _frames = {...frames};
final Map<String, Rect> _frames;
int _commits = 0;
Map<String, Rect> get frames => Map.unmodifiable(_frames);
/// Advances when a move or resize ends (the binding saves then).
int get commits => _commits;
/// [paneId]'s frame; a window without one opens at the default frame,
/// stepped down and right by [index] so stacked windows stay visible.
Rect rectFor(String paneId, {int index = 0}) =>
_frames[paneId] ??
chatFloatDefaultRect.shift(Offset(32, 32) * index.toDouble());
/// Gives [paneId] its opening frame ([rectFor] at [index]) unless it has
/// one, so the window stays put when other windows come and go.
void place(String paneId, {required int index}) {
if (_frames.containsKey(paneId)) return;
move(paneId, rectFor(paneId, index: index));
}
void move(String paneId, Rect rect) {
if (_frames[paneId] == rect) return;
_frames[paneId] = rect;
notifyListeners();
}
/// Replaces every frame (a restore).
void restore(Map<String, Rect> frames) {
if (mapEquals(frames, _frames)) return;
_frames
..clear()
..addAll(frames);
notifyListeners();
}
void commit() {
_commits++;
notifyListeners();
}
}
/// Saves which chats float, whether they show and their windows' frames, and
/// restores them once the workspace layout itself has been restored.
class ChatFloatBinding {
ChatFloatBinding({
required this.controller,
required this.frames,
required this.store,
this.debounce = const Duration(milliseconds: 250),
}) {
controller.addListener(_changed);
frames.addListener(_framesChanged);
}
final ChatWorkspaceController controller;
final ChatFloatFrames frames;
final ChatFloatStore store;
final Duration debounce;
ChatFloatRecord? _saved;
bool _loading = true;
bool _disposed = false;
int _commits = 0;
Timer? _timer;
Future<void> _writes = Future.value();
/// Frames of panes still open somewhere (tiled or floating); a closed
/// pane's frame is dropped.
ChatFloatRecord get _current {
final open = {
for (final pane in controller.panes) pane.id,
for (final pane in controller.floatingPanes) pane.id,
};
return ChatFloatRecord(
panes: controller.floatingPanes,
shown: controller.floatShown,
frames: {
for (final MapEntry(:key, :value) in frames.frames.entries)
if (open.contains(key)) key: value,
},
);
}
/// Call after the workspace layout restored, so a saved float can tell
/// whether its chat is already open in the tiling.
Future<void> start() async {
ChatFloatRecord? record;
try {
record = await store.read();
} on Object {
// Unavailable preferences leave the default frames and no float.
}
if (_disposed) return;
if (record != null) {
_saved = record;
_commits = frames.commits;
frames.restore(record.frames);
if (record.panes.isNotEmpty && controller.floatingPanes.isEmpty) {
controller.restoreFloats(record.panes, shown: record.shown);
}
}
_loading = false;
_changed();
}
void _framesChanged() {
if (frames.commits == _commits) return;
_commits = frames.commits;
_changed();
}
void _changed() {
if (_disposed || _loading || _current == _saved) return;
_timer?.cancel();
_timer = Timer(debounce, flush);
}
Future<void> flush() {
_timer?.cancel();
_timer = null;
final record = _current;
if (_loading || record == _saved) return _writes;
_saved = record;
_writes = _writes.then((_) async {
try {
await store.write(record);
} on Object {
// A storage failure must not interrupt the chat.
}
});
return _writes;
}
void dispose() {
if (_disposed) return;
controller.removeListener(_changed);
frames.removeListener(_framesChanged);
unawaited(flush());
_disposed = true;
}
}
@@ -1,337 +0,0 @@
import 'dart:async';
import 'package:flutter/material.dart';
import 'package:flutter/scheduler.dart';
import 'package:flutter/services.dart';
import '../../../ui/floating/floating_layer.dart';
import '../../../ui/motion/motion.dart';
import '../../../ui/motion/surface_visibility.dart';
import '../ui/sessions/chat_adaptive.dart';
import 'chat_float_binding.dart';
import 'chat_float_shortcut.dart';
import 'chat_float_window.dart';
import 'chat_workspace_controller.dart';
/// The split workspace ([child]) with its floating chats over the app: their
/// windows, show and hide motion, focus and shortcut (see
/// [chatFloatShortcut]). [content] is a floating pane's live view, moved here
/// from the tiling rather than rebuilt.
///
/// The windows show while [enabled] (a wide layout), over every destination,
/// like the floating terminal. They show and hide together.
class ChatFloatHost extends StatefulWidget {
const ChatFloatHost({
super.key,
required this.controller,
required this.frames,
required this.enabled,
required this.title,
required this.content,
required this.scope,
required this.focusedPane,
required this.onFocusPane,
required this.child,
});
final ChatWorkspaceController controller;
final ChatFloatFrames frames;
final bool enabled;
final String Function(ChatWorkspacePane pane) title;
final Widget Function(ChatWorkspacePane pane) content;
/// A floating pane's focus scope.
final FocusScopeNode? Function(ChatWorkspacePane pane) scope;
/// The tiled pane with the keyboard, which the shortcut floats when no
/// chat floats yet.
final ChatWorkspacePane? Function() focusedPane;
final ValueChanged<ChatWorkspacePane>? onFocusPane;
final Widget child;
@override
State<ChatFloatHost> createState() => _ChatFloatHostState();
}
class _ChatFloatHostState extends State<ChatFloatHost> {
bool _visible = false;
Set<String> _paneIds = const {};
FocusNode? _previous;
@override
void initState() {
super.initState();
FocusManager.instance.addEarlyKeyEventHandler(_key);
widget.controller.addListener(_sync);
WidgetsBinding.instance.addPostFrameCallback((_) => _sync());
}
@override
void didUpdateWidget(covariant ChatFloatHost oldWidget) {
super.didUpdateWidget(oldWidget);
if (oldWidget.controller != widget.controller) {
oldWidget.controller.removeListener(_sync);
widget.controller.addListener(_sync);
}
if (oldWidget.enabled != widget.enabled) {
WidgetsBinding.instance.addPostFrameCallback((_) => _sync());
}
}
@override
void dispose() {
FocusManager.instance.removeEarlyKeyEventHandler(_key);
widget.controller.removeListener(_sync);
super.dispose();
}
void _sync() {
if (!mounted) return;
final panes = widget.controller.floatingPanes;
final ids = {for (final pane in panes) pane.id};
final visible = widget.enabled && widget.controller.floatShown;
for (final (index, pane) in panes.indexed) {
widget.frames.place(pane.id, index: index);
}
if (panes.isEmpty) {
// Docked or closed: the views went back to the tiling.
_previous = null;
} else if (visible != _visible) {
if (visible) {
_remember();
_focusSoon(panes.last);
} else {
_release();
}
} else if (visible) {
// A newly floated chat takes the keyboard.
final added = panes.where((p) => !_paneIds.contains(p.id)).lastOrNull;
if (added != null) _focusSoon(added);
}
_paneIds = ids;
if (visible != _visible) setState(() => _visible = visible);
}
bool _inside(FocusNode node) => widget.controller.floatingPanes.any((pane) {
final scope = widget.scope(pane);
return scope != null &&
(identical(node, scope) || node.ancestors.contains(scope));
});
void _remember() {
final current = FocusManager.instance.primaryFocus;
if (current == null || _inside(current)) return;
_previous = identical(current, FocusManager.instance.rootScope)
? null
: current;
}
void _focusSoon(ChatWorkspacePane pane) {
WidgetsBinding.instance
..addPostFrameCallback((_) {
if (!mounted || !widget.controller.isFloating(pane.id)) return;
final focus = widget.onFocusPane;
if (focus != null) {
focus(pane);
} else {
widget.scope(pane)?.requestFocus();
}
})
..ensureVisualUpdate();
}
/// Gives the keyboard back to what had it before the chats showed, if a
/// floating chat has it now.
void _release() {
final previous = _previous;
_previous = null;
final current = FocusManager.instance.primaryFocus;
if (current == null || !_inside(current)) return;
if (previous != null &&
previous.context != null &&
previous.canRequestFocus) {
previous.requestFocus();
} else {
current.unfocus();
}
}
/// Handled before any focused widget sees the key, so it works from a
/// composer or the terminal; ignored (left to them) when it does nothing.
KeyEventResult _key(KeyEvent event) {
if (!mounted ||
!widget.enabled ||
!chatFloatShortcut(event, HardwareKeyboard.instance)) {
return KeyEventResult.ignored;
}
final controller = widget.controller;
if (controller.floatingPanes.isEmpty) {
final pane = widget.focusedPane();
if (pane == null || !controller.canFloat(pane.id)) {
return KeyEventResult.ignored;
}
if (event is KeyDownEvent) controller.float(pane.id);
return KeyEventResult.handled;
}
if (event is KeyDownEvent) controller.toggleFloatShown();
return KeyEventResult.handled;
}
@override
Widget build(BuildContext context) {
final panes = widget.controller.floatingPanes;
final cupertino =
chatControlsStyleOf(context) == ChatControlsStyle.cupertino;
return Stack(
fit: StackFit.expand,
children: [
widget.child,
for (final (index, pane) in panes.indexed)
Positioned.fill(
key: ValueKey(pane.id),
// Shown over every destination; the window's motion keeps
// running there (see [_ChatFloatSlot]).
child: FloatingLayer(
open: _visible,
coverOverlay: true,
builder: (context, bounds) => [
ListenableBuilder(
listenable: widget.frames,
builder: (context, _) => _ChatFloatSlot(
visible: _visible,
rect: widget.frames.rectFor(pane.id, index: index),
currentRect: () =>
widget.frames.rectFor(pane.id, index: index),
onMove: (rect) => widget.frames.move(pane.id, rect),
onCommit: widget.frames.commit,
bounds: bounds,
title: widget.title(pane),
cupertino: cupertino,
onDock: () => widget.controller.dock(pane.id),
onHide: () => widget.controller.setFloatShown(false),
child: widget.content(pane),
),
),
],
),
),
],
);
}
}
/// One floating chat's window and its own grow-and-fade motion, so a chat
/// floated while the others show animates in alone.
class _ChatFloatSlot extends StatefulWidget {
const _ChatFloatSlot({
required this.visible,
required this.rect,
required this.currentRect,
required this.onMove,
required this.onCommit,
required this.bounds,
required this.title,
required this.cupertino,
required this.onDock,
required this.onHide,
required this.child,
});
final bool visible;
final Rect rect;
final Rect Function() currentRect;
final ValueChanged<Rect> onMove;
final VoidCallback onCommit;
final Size bounds;
final String title;
final bool cupertino;
final VoidCallback onDock;
final VoidCallback onHide;
final Widget child;
@override
State<_ChatFloatSlot> createState() => _ChatFloatSlotState();
}
class _ChatFloatSlotState extends State<_ChatFloatSlot>
implements TickerProvider {
Ticker? _ticker;
/// A ticker the hidden destination's [TickerMode] does not mute: the
/// window must still show and hide over another destination, and a
/// TickerMode cannot re-enable what an ancestor turned off.
@override
Ticker createTicker(TickerCallback onTick) {
assert(_ticker == null, 'one reveal ticker per window');
return _ticker = Ticker(onTick, debugLabel: 'chat float reveal');
}
late final AnimationController _reveal = AnimationController(
vsync: this,
duration: Motion.standard,
);
late final CurvedAnimation _curve = CurvedAnimation(
parent: _reveal,
curve: Motion.curve,
reverseCurve: Curves.easeInCubic,
);
@override
void initState() {
super.initState();
if (widget.visible) {
WidgetsBinding.instance.addPostFrameCallback((_) => _run());
}
}
@override
void didUpdateWidget(covariant _ChatFloatSlot oldWidget) {
super.didUpdateWidget(oldWidget);
if (oldWidget.visible != widget.visible) _run();
}
void _run() {
if (!mounted) return;
_reveal.duration = Motion.of(context, Motion.standard);
unawaited(widget.visible ? _reveal.forward() : _reveal.reverse());
}
@override
void dispose() {
_curve.dispose();
_reveal.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) => AnimatedBuilder(
animation: _reveal,
builder: (context, _) {
final offstage = !widget.visible && _reveal.isDismissed;
return ChatFloatWindow(
rect: widget.rect,
currentRect: widget.currentRect,
onMove: widget.onMove,
onCommit: widget.onCommit,
bounds: widget.bounds,
title: widget.title,
cupertino: widget.cupertino,
reveal: _curve,
hiding: !widget.visible,
offstage: offstage,
shortcut: chatFloatShortcutLabel(),
onDock: widget.onDock,
onHide: widget.onHide,
// A hidden window's chat pauses its tickers like a hidden tab.
child: TickerMode(
enabled: !offstage,
child: SurfaceVisibility(
shown: !offstage,
current: !offstage,
child: widget.child,
),
),
);
},
);
}
@@ -37,7 +37,7 @@ bool chatFloatShortcut(
bool _apple(TargetPlatform platform) =>
platform == TargetPlatform.macOS || platform == TargetPlatform.iOS;
/// The floating chat's shortcut as it reads on this platform, for menus and
/// tooltips.
/// The floating chats' shortcut as it reads on this platform, for menus and
/// tooltips: the Alt chord, which every platform and browser delivers.
String chatFloatShortcutLabel([TargetPlatform? platform]) =>
_apple(platform ?? defaultTargetPlatform) ? 'Cmd+Y' : 'Ctrl+Y';
_apple(platform ?? defaultTargetPlatform) ? 'Option+Y' : 'Alt+Y';
@@ -1,229 +0,0 @@
import 'package:flutter/cupertino.dart';
import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import '../../../ui/adaptive/window_margins.dart';
import '../../terminal/terminal_float_frame.dart' show terminalFloatChrome;
import 'chat_float_store.dart';
/// [rect] moved and shrunk to fit inside [bounds], at least the smallest
/// window where the bounds allow it.
Rect fitChatFloat(Rect rect, Size bounds) {
final width = rect.width
.clamp(chatFloatMinSize.width, double.infinity)
.clamp(0.0, bounds.width);
final height = rect.height
.clamp(chatFloatMinSize.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,
);
}
/// A floating chat's window: moved by its title bar, resized from its
/// lower right corner, kept inside [bounds]. It grows and fades in from its
/// place as [reveal] runs forward and leaves the same way in reverse.
class ChatFloatWindow extends StatelessWidget {
const ChatFloatWindow({
super.key,
required this.rect,
required this.currentRect,
required this.onMove,
required this.onCommit,
required this.bounds,
required this.title,
required this.cupertino,
required this.reveal,
required this.hiding,
this.offstage = false,
required this.shortcut,
required this.onDock,
required this.onHide,
required this.child,
});
/// The saved frame; it is drawn fitted inside [bounds].
final Rect rect;
/// The frame now: several drag events can arrive before a rebuild.
final Rect Function() currentRect;
final ValueChanged<Rect> onMove;
/// A move or resize ended.
final VoidCallback onCommit;
final Size bounds;
final String title;
final bool cupertino;
final Animation<double> reveal;
/// While the window hides it takes no input.
final bool hiding;
/// Hidden and settled: kept built (the chat keeps its state) but unpainted.
final bool offstage;
final String shortcut;
final VoidCallback onDock;
final VoidCallback onHide;
final Widget child;
static const double revealScale = 0.92;
void _resize(Offset delta) {
final rect = fitChatFloat(currentRect(), bounds);
onMove(
fitChatFloat(
Rect.fromLTWH(
rect.left,
rect.top,
rect.width + delta.dx,
rect.height + delta.dy,
),
bounds,
),
);
}
@override
Widget build(BuildContext context) {
final rect = fitChatFloat(this.rect, bounds);
final window = SizedBox.fromSize(
size: rect.size,
child: Stack(
children: [
Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
_titleBar(context, rect),
Expanded(
child: MediaQuery.removePadding(
context: context,
removeTop: true,
removeBottom: true,
removeLeft: true,
removeRight: true,
// A small window keeps the compact bar insets.
child: WindowMargins.compact(child: child),
),
),
],
),
PositionedDirectional(end: 0, bottom: 0, child: _corner()),
],
),
);
return Positioned(
left: rect.left,
top: rect.top,
child: Offstage(
offstage: offstage,
child: IgnorePointer(
ignoring: hiding,
child: ExcludeFocus(
excluding: hiding,
child: FadeTransition(
opacity: reveal,
child: ScaleTransition(
scale: Tween<double>(
begin: revealScale,
end: 1,
).animate(reveal),
child: Semantics(
container: true,
label: 'Floating chat: $title',
identifier: 'chat-float-window',
child: terminalFloatChrome(context, cupertino, window),
),
),
),
),
),
),
);
}
Widget _titleBar(BuildContext context, Rect rect) {
final label = Text(
title,
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: cupertino
? CupertinoTheme.of(context).textTheme.navTitleTextStyle
: Theme.of(context).textTheme.titleSmall,
);
final drag = MouseRegion(
cursor: SystemMouseCursors.move,
child: GestureDetector(
key: const ValueKey('chat-float-title'),
behavior: HitTestBehavior.opaque,
dragStartBehavior: DragStartBehavior.down,
onPanUpdate: (details) => onMove(
fitChatFloat(
fitChatFloat(currentRect(), bounds).shift(details.delta),
bounds,
),
),
onPanEnd: (_) => onCommit(),
child: Padding(
padding: const EdgeInsetsDirectional.only(start: 12),
child: Align(
alignment: AlignmentDirectional.centerStart,
child: label,
),
),
),
);
return Row(
children: [
Expanded(child: drag),
_button(
'Dock',
Icons.vertical_split_outlined,
CupertinoIcons.rectangle_split_3x1,
onDock,
),
_button(
'Hide floating chats ($shortcut)',
Icons.close,
CupertinoIcons.xmark,
onHide,
),
],
);
}
Widget _button(
String label,
IconData material,
IconData cupertinoIcon,
VoidCallback onPressed,
) => cupertino
? CupertinoButton(
padding: const EdgeInsets.symmetric(horizontal: 8),
onPressed: onPressed,
child: Icon(cupertinoIcon, semanticLabel: label),
)
: IconButton(tooltip: label, onPressed: onPressed, icon: Icon(material));
Widget _corner() => Semantics(
label: 'Resize floating chat',
child: MouseRegion(
cursor: SystemMouseCursors.resizeDownRight,
child: GestureDetector(
key: const ValueKey('chat-float-resize'),
behavior: HitTestBehavior.opaque,
dragStartBehavior: DragStartBehavior.down,
onPanUpdate: (details) => _resize(details.delta),
onPanEnd: (_) => onCommit(),
child: Padding(
padding: const EdgeInsets.all(4),
child: Icon(
cupertino ? CupertinoIcons.arrow_down_right : Icons.south_east,
),
),
),
),
);
}
@@ -3,14 +3,11 @@ import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import '../../../ui/floating/floating_layer.dart';
import '../../../ui/motion/motion.dart';
import '../../../ui/motion/quick_switch_animation.dart';
import 'chat_center_stage_layout.dart';
import 'chat_center_stage_motion.dart';
import 'chat_center_stage_strip.dart';
import 'chat_float_binding.dart';
import 'chat_float_host.dart';
import 'chat_workspace_controller.dart';
import 'chat_workspace_geometry.dart';
import 'chat_mobile_panes.dart';
@@ -45,7 +42,6 @@ class ChatWorkspace extends StatefulWidget {
this.onVisibleSessionIdsChanged,
this.centerStage,
this.paneColor,
this.floatFrames,
});
final ChatWorkspaceController controller;
final ChatWorkspacePaneBuilder paneBuilder;
@@ -65,11 +61,6 @@ class ChatWorkspace extends StatefulWidget {
/// A pane's chat colour, for its strip beside the stage.
final Color? Function(ChatWorkspacePane)? paneColor;
/// Offers floating chats (see [ChatFloatHost]) in these frames; null for a
/// workspace without them. They show only while the panes are not
/// collapsed.
final ChatFloatFrames? floatFrames;
/// Keyboard navigation only: the owner can focus the target composer.
/// Pointer activation leaves text-selection and pointer focus alone.
final ValueChanged<ChatWorkspacePane>? onFocusPane;
@@ -83,8 +74,7 @@ class _ChatWorkspaceState extends State<ChatWorkspace>
final _focus = FocusNode(debugLabel: 'Chat workspace');
final Map<String, FocusScopeNode> _panes = {};
/// Each pane's view keeps its State when it moves into or out of the
/// floating window.
/// Each pane's view keeps its State as the tiling rearranges.
final Map<String, GlobalKey> _views = {};
late final ChatPaneSwitchMotion _motion;
late final ChatCenterStageMotion _stage = ChatCenterStageMotion(vsync: this);
@@ -295,13 +285,7 @@ class _ChatWorkspaceState extends State<ChatWorkspace>
: !collapsed || pane.id == activeId)
pane.sessionId,
});
final floating = widget.floatFrames == null
? const <ChatWorkspacePane>[]
: widget.controller.floatingPanes;
final existing = {
...panes.map((p) => p.id),
...floating.map((p) => p.id),
};
final existing = {...panes.map((p) => p.id)};
_views.removeWhere((id, _) => !existing.contains(id));
for (final id
in _panes.keys.where((id) => !existing.contains(id)).toList()) {
@@ -342,7 +326,7 @@ class _ChatWorkspaceState extends State<ChatWorkspace>
edge,
},
};
final surface = chatWorkspaceSurface(
return chatWorkspaceSurface(
context: context,
backdrop: _backdrop,
motion: _motion,
@@ -364,21 +348,6 @@ class _ChatWorkspaceState extends State<ChatWorkspace>
moveTargets[pane.id],
),
);
final frames = widget.floatFrames;
if (frames == null) return surface;
return ChatFloatHost(
controller: widget.controller,
frames: frames,
enabled: !widget.singlePane,
title: (pane) => widget.paneTitle?.call(pane) ?? pane.sessionId,
content: _floatView,
scope: (pane) => _panes[pane.id],
focusedPane: () => widget.controller.panes
.where((pane) => _panes[pane.id]?.hasFocus ?? false)
.firstOrNull,
onFocusPane: widget.onFocusPane,
child: surface,
);
},
),
),
@@ -441,19 +410,6 @@ class _ChatWorkspaceState extends State<ChatWorkspace>
);
}
/// A floating chat's view: the same keyed content as in the tiling, so
/// floating and docking move it without rebuilding the chat. Its focus
/// hangs from the shell's [FloatingFocusRoot], so it keeps the keyboard
/// while another destination (which excludes this one) shows.
Widget _floatView(ChatWorkspacePane pane) => _paneContent(
pane,
active: true,
peek: false,
mobile: false,
edges: {},
focusParent: FloatingFocusRoot.maybeOf(context),
);
Widget _paneContent(
ChatWorkspacePane pane, {
required bool active,
@@ -461,7 +417,6 @@ class _ChatWorkspaceState extends State<ChatWorkspace>
required bool mobile,
required Set<String> edges,
Map<ChatPaneDirection, String>? moveTargets,
FocusNode? focusParent,
}) {
var actionBarPointerDown = false;
bool preservesStageForActionBar() =>
@@ -469,7 +424,6 @@ class _ChatWorkspaceState extends State<ChatWorkspace>
return KeyedSubtree(
key: _views.putIfAbsent(pane.id, () => GlobalKey(debugLabel: pane.id)),
child: FocusScope(
parentNode: focusParent,
node: _panes.putIfAbsent(
pane.id,
() => FocusScopeNode(debugLabel: pane.id),
@@ -12,10 +12,9 @@ class ChatWorkspaceController extends ChangeNotifier {
ChatWorkspaceNode? _root;
String? _active;
/// The chats taken out of the tiling into floating windows, oldest first.
/// They show and hide together.
final List<ChatWorkspacePane> _floating = [];
bool _floatShown = false;
/// Shows the window [sessionId] is out in and returns true, or returns
/// false when it is in none. Set by whoever hosts floating chats.
bool Function(String sessionId)? showOutside;
double _mobilePeekFraction = .2;
double get mobilePeekFraction => _mobilePeekFraction;
void resizeMobilePeek(double fraction) {
@@ -56,7 +55,6 @@ class ChatWorkspaceController extends ChangeNotifier {
}
collect(_root);
_floating.forEach(collect);
String id;
do {
id = 'chat-$kind-${++_serial}';
@@ -70,7 +68,6 @@ class ChatWorkspaceController extends ChangeNotifier {
_root = snapshot.root;
_active = snapshot.activePaneId;
_mobilePeekFraction = snapshot.mobilePeekFraction;
_floating.clear();
_serial = 0;
_changed();
return true;
@@ -193,12 +190,10 @@ class ChatWorkspaceController extends ChangeNotifier {
}
void close(String paneId) {
if (_closeFloating(paneId)) return;
final before = panes;
final index = before.indexWhere((p) => p.id == paneId);
if (index < 0) return;
_root = _remove(_root!, paneId);
_adoptFloatingIfEmpty();
final after = panes;
if (_active == paneId) {
_active = after.isEmpty
@@ -1,30 +1,21 @@
part of 'chat_workspace_controller.dart';
/// Chats can leave the split tiling for floating windows over the app. They
/// show and hide together. A floating pane keeps its id (and so its live view)
/// while it floats, hides or docks.
/// Chats can leave the split tiling for floating windows over the app (see
/// `ChatWindows`). The tiling keeps none of them: it only asks whether a
/// chat is out in a window before opening it.
extension ChatWorkspaceFloat on ChatWorkspaceController {
/// The floating chats, shown or hidden, oldest first.
List<ChatWorkspacePane> get floatingPanes => List.unmodifiable(_floating);
/// Whether [paneId] floats.
bool isFloating(String paneId) => _floating.any((pane) => pane.id == paneId);
/// Whether the floating chats are shown (rather than hidden by Ctrl+Y).
bool get floatShown => _floating.isNotEmpty && _floatShown;
/// Whether [sessionId] is open in the tiling or a floating window.
/// Whether [sessionId] is open in the tiling.
bool holdsSession(String sessionId) =>
_floating.any((pane) => pane.sessionId == sessionId) ||
panes.any((pane) => pane.sessionId == sessionId);
/// A tiled pane can float while another chat stays in the tiling.
bool canFloat(String paneId) =>
paneCount > 1 && panes.any((pane) => pane.id == paneId);
/// Floats the tiled pane [paneId] and shows every floating chat.
void float(String paneId) {
if (!canFloat(paneId)) return;
/// Takes the tiled pane [paneId] out of the tiling for a window; the pane
/// beside it becomes active. Null when it cannot float.
ChatWorkspacePane? detach(String paneId) {
if (!canFloat(paneId)) return null;
final pane = panes.firstWhere((pane) => pane.id == paneId);
final index = panes.indexWhere((p) => p.id == paneId);
_root = _remove(_root!, paneId);
@@ -32,18 +23,20 @@ extension ChatWorkspaceFloat on ChatWorkspaceController {
final after = panes;
_active = after[index.clamp(0, after.length - 1)].id;
}
_floating.add(pane);
_floatShown = true;
_changed();
return pane;
}
/// Puts the floating chat [paneId] back into the tiling, to the right of
/// the active pane, and makes it the active pane.
void dock(String paneId) {
final at = _floating.indexWhere((pane) => pane.id == paneId);
if (at < 0) return;
final pane = _floating.removeAt(at);
final split = _id('split');
/// Puts the chat [sessionId] back from its window into the tiling, to the
/// right of the active pane, and makes it the active pane.
void dock(String sessionId) {
if (sessionId.isEmpty) return;
final existing = panes.where((p) => p.sessionId == sessionId).firstOrNull;
if (existing != null) {
activate(existing.id);
return;
}
final pane = ChatWorkspacePane(_id('pane'), sessionId);
if (_root == null) {
_root = pane;
} else {
@@ -51,93 +44,27 @@ extension ChatWorkspaceFloat on ChatWorkspaceController {
_root = _replace(
_root!,
target.id,
ChatWorkspaceSplit(split, ChatSplitAxis.horizontal, target, pane),
ChatWorkspaceSplit(
_id('split'),
ChatSplitAxis.horizontal,
target,
pane,
),
);
}
_active = pane.id;
_changed();
}
void setFloatShown(bool shown) {
if (_floating.isEmpty || _floatShown == shown) return;
_floatShown = shown;
_changed();
}
/// Opening a chat that is out in a window shows that window instead.
bool _showFloating(String sessionId) => showOutside?.call(sessionId) ?? false;
void toggleFloatShown() => setFloatShown(!_floatShown);
/// Restores saved floating chats, skipping any whose session is already
/// open or whose pane id is taken. With no tiled pane the first becomes
/// the tiling instead. Returns how many were restored.
int restoreFloats(List<ChatWorkspacePane> saved, {required bool shown}) {
var restored = 0;
for (final pane in saved) {
if (holdsSession(pane.sessionId) || _taken(pane.id)) continue;
if (_root == null) {
_root = pane;
_active = pane.id;
} else {
_floating.add(pane);
}
restored++;
}
if (restored == 0) return 0;
_floatShown = shown;
_changed();
return restored;
}
bool _taken(String id) {
bool inTree(ChatWorkspaceNode? node) =>
node != null &&
(node.id == id ||
node is ChatWorkspaceSplit &&
(inTree(node.first) || inTree(node.second)));
return inTree(_root) || isFloating(id);
}
/// Opening a floating chat (from the list, a link) shows the floats.
bool _showFloating(String sessionId) {
if (!_floating.any((pane) => pane.sessionId == sessionId)) return false;
setFloatShown(true);
return true;
}
bool _closeFloating(String paneId) {
final at = _floating.indexWhere((pane) => pane.id == paneId);
if (at < 0) return false;
_floating.removeAt(at);
_changed();
return true;
}
/// The tiling never empties while a chat floats: the oldest one docks.
void _adoptFloatingIfEmpty() {
if (_root != null || _floating.isEmpty) return;
_root = _floating.removeAt(0);
}
/// `/new` in a floating chat keeps it floating under the new session.
/// A tiled chat moved to a session that is out in a window: the window
/// stays and the tiled pane closes.
bool _replaceFloating(String oldId, String newId) {
final at = _floating.indexWhere((pane) => pane.sessionId == oldId);
if (at >= 0) {
final pane = _floating[at];
final elsewhere =
panes.any((p) => p.sessionId == newId) ||
_floating.any((p) => p.sessionId == newId);
if (elsewhere) {
_closeFloating(pane.id);
} else {
_floating[at] = ChatWorkspacePane(pane.id, newId);
_changed();
}
return true;
}
if (!_floating.any((pane) => pane.sessionId == newId)) return false;
// A tiled chat moved to a session that floats: the float stays.
if (!(showOutside?.call(newId) ?? false)) return false;
final tiled = panes.where((p) => p.sessionId == oldId).firstOrNull;
if (tiled != null) close(tiled.id);
setFloatShown(true);
return true;
}
}
@@ -113,10 +113,7 @@ class _DiscoveredServerRowState extends State<DiscoveredServerRow> {
_choice(context, cupertino, address),
Padding(
padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
child: Align(
alignment: AlignmentDirectional.centerStart,
child: use,
),
child: Align(alignment: AlignmentDirectional.centerStart, child: use),
),
],
);
@@ -109,6 +109,8 @@ class PipelineSortButton extends StatelessWidget {
);
}
return MenuAnchor(
// Above every floating window, and not clipped to one.
useRootOverlay: true,
menuChildren: [
for (final option in PipelineSort.values)
MenuItemButton(
@@ -108,7 +108,9 @@ class _SavedServerSignInStepState extends State<SavedServerSignInStep> {
child: CircularProgressIndicator(strokeWidth: 2),
),
const SizedBox(width: 12),
Expanded(child: Text('Saved. Checking whether $name needs a sign-in…')),
Expanded(
child: Text('Saved. Checking whether $name needs a sign-in…'),
),
],
);
}
@@ -57,11 +57,12 @@ class TerminalShortcutLabels {
bool get _apple =>
platform == TargetPlatform.macOS || platform == TargetPlatform.iOS;
/// The keys that show or hide the terminal, most convenient first.
/// The keys that show or hide the terminal. The Alt chord leads (the
/// button's tooltip names it): every platform and browser delivers it.
List<String> get toggle => [
_apple ? 'Option+T' : 'Alt+T',
if (!web && _apple) 'Cmd+T',
if (!web || _apple) 'Ctrl+T',
_apple ? 'Option+T' : 'Alt+T',
'Ctrl+`',
];