part of 'screen.dart'; /// Pane layout, focus and route publication for one Chat destination visit. mixin _ChatScreenWorkspace on State { Map get _openedSessions; ChatComposerFocusRequests get _composerFocus; bool _chatOwnsKeyboard(); JsonMap? _rowFor(String id); void _back(); bool get _pageOpen; Widget _thread(ChatWorkspacePane pane); ChatSidebarMode _sidebarMode = ChatSidebarMode.expanded; void _setSidebarMode(ChatSidebarMode mode) { if (_sidebarMode == mode) return; setState(() => _sidebarMode = mode); _workspaceBinding?.changed(); } Widget _sidebarList(Widget full, String? selected, bool beside) { final mode = selected == null || !beside ? ChatSidebarMode.expanded : _sidebarMode; final navigation = ShellBarScope.maybeOf(context); return Stack( fit: StackFit.expand, children: [ Offstage( offstage: mode != ChatSidebarMode.expanded, child: ExcludeFocus( excluding: mode != ChatSidebarMode.expanded, child: full, ), ), if (mode == ChatSidebarMode.compact) ChatCompactSidebar( navigation: navigation?.registry.canNavigate == true ? ShellDestinationMenu( current: AppDestination.chat, onSelected: navigation!.registry.navigateTo, ) : null, controller: _sessionsForSidebar, folds: _foldsForSidebar, activeSessionId: selected, visibleSessionIds: _visibleSidebarSessions, onOpen: _openSidebarSession, onExpand: () => _setSidebarMode(ChatSidebarMode.expanded), ), ], ); } Set _visibleWorkspaceSessions = const {}; /// Each pane's move targets as the workspace last laid them out. Read when /// the chat list's row menu opens; it needs no rebuild of its own. Map> _paneMoveTargets = const {}; void _paneMoveTargetsChanged( Map> targets, ) { _paneMoveTargets = targets; } void _workspaceVisibilityChanged(Set sessions) { if (!mounted || setEquals(_visibleWorkspaceSessions, sessions)) return; setState(() => _visibleWorkspaceSessions = Set.unmodifiable(sessions)); } Set get _visibleSidebarSessions { if (!_workspaceVisible) return const {}; final retained = _workspace.panes.map((pane) => pane.sessionId).toSet(); final visible = _visibleWorkspaceSessions.intersection(retained); final active = _workspace.activePane?.sessionId; return visible.isNotEmpty ? visible : {?active}; } ChatSessionsController get _sessionsForSidebar; ChatSectionFolds get _foldsForSidebar; void _openSidebarSession(JsonMap session); final ChatWorkspaceController _workspace = ChatWorkspaceController(); ChatOpenWorkspaceController? _openWorkspace; bool _applyingServerWorkspace = false; ChatWorkspaceBinding? _workspaceBinding; String? _workspaceScope; Iterable _serverWorkspaceEntries() sync* { final floating = widget.windows?.floatingSessionIds.toSet() ?? const {}; for (final pane in _workspace.panes) { yield ChatOpenWorkspaceEntry( pane.sessionId, floating: floating.contains(pane.sessionId), ); } for (final sessionId in floating) { if (!_workspace.holdsSession(sessionId)) { yield ChatOpenWorkspaceEntry(sessionId, floating: true); } } } /// Sends this device's open chats to the server, unless the change is the /// server's own snapshot being applied. void _syncOpenWorkspace() { if (_applyingServerWorkspace) return; _openWorkspace?.replace(_serverWorkspaceEntries()); } /// Binds the server's open-chat set for [widget.gateway], disposing the /// previous binding (its subscription and queued writes) first. A /// federated list spans several servers, so it keeps its local layout. void _bindOpenWorkspace({required Future after}) { _openWorkspace?.dispose(); _openWorkspace = null; _openWorkspaceApplied = false; if (!widget.persistWorkspace || widget.gateway is FederatedChatGateway) { return; } final open = ChatOpenWorkspaceController(gateway: widget.gateway) ..onChanged = _applyOpenWorkspace; _openWorkspace = open; // Seed from the restored local layout once it is restored. unawaited( after.then((_) async { if (!mounted || open.disposed) return; await open.start(local: _serverWorkspaceEntries()); }), ); } void _bindWorkspacePersistence() { if (!widget.persistWorkspace) { _bindOpenWorkspace(after: Future.value()); return; } final scope = serverStorageScope(serverIdentity(widget.gateway)); _workspaceScope = scope; _workspaceBinding = ChatWorkspaceBinding( controller: _workspace, store: widget.gateway is FederatedChatGateway ? FederatedWorkspaceStore( primary: (widget.gateway as FederatedChatGateway).primary(), ) : SharedPreferencesChatWorkspaceStore(serverScope: scope), sidebarMode: () => _sidebarMode.name, onRestored: (snapshot) { if (!mounted) return; setState(() { _sidebarMode = ChatSidebarMode.values.firstWhere( (mode) => mode.name == snapshot.sidebarMode, ); // Older snapshots could hide the rail. Keep their recovery affordance // now that layout changes happen at the divider instead of a menu. if (_sidebarMode == ChatSidebarMode.hidden) { _sidebarMode = ChatSidebarMode.compact; } _usedWorkspace = true; _workspaceVisible = _workspace.paneCount > 0; }); _publishWorkspaceRoute(); }, ); _bindOpenWorkspace( after: _workspaceBinding!.start( initialSessionId: widget.initialSessionId, ), ); } /// Whether a server snapshot was applied since binding. The first one keeps /// the chat this visit was opened on (a deep link) and adds it if absent. bool _openWorkspaceApplied = false; /// Applies the server's membership: windows and panes for chats it no /// longer lists close, floating state follows it, and tiled chats take its /// order while this device's split geometry stays. void _applyOpenWorkspace(ChatOpenWorkspaceSnapshot snapshot) { if (!mounted) return; final initial = widget.initialSessionId ?? ''; final first = !_openWorkspaceApplied; final keepInitial = first && initial.isNotEmpty && !snapshot.entries.any((entry) => entry.sessionId == initial); _openWorkspaceApplied = true; if (keepInitial) { snapshot = ChatOpenWorkspaceSnapshot(snapshot.revision, [ ...snapshot.entries, ChatOpenWorkspaceEntry(initial), ]); } _applyingServerWorkspace = true; try { final windows = widget.windows; if (windows != null) { final entriesBySession = { for (final entry in snapshot.entries) entry.sessionId: entry, }; for (final window in windows.windows.toList()) { if (!entriesBySession.containsKey(window.contentId)) { windows.manager.close(window.id); } } for (final entry in snapshot.entries) { final localWindow = windows.windows .where((window) => window.contentId == entry.sessionId) .firstOrNull; if (entry.floating && localWindow == null) { final pane = _workspace.panes .where((pane) => pane.sessionId == entry.sessionId) .firstOrNull; if (pane != null) _workspace.close(pane.id); windows.float(entry.sessionId); } else if (!entry.floating && localWindow != null) { windows.dock(localWindow); } } } _workspace.reconcileSessions( snapshot.entries .where((entry) => !entry.floating) .map((entry) => entry.sessionId), ); if (keepInitial) { final pane = _workspace.panes .where((pane) => pane.sessionId == initial) .firstOrNull; if (pane != null) _workspace.activate(pane.id); } if (_workspace.paneCount == 0 && _workspaceVisible) _back(); } finally { _applyingServerWorkspace = false; } // The first snapshot shows the server's chats as a restored layout does; // later ones never pull this device into a chat another one opened. if (first && _workspace.paneCount > 0 && !_workspaceVisible) { setState(() { _usedWorkspace = true; _workspaceVisible = true; }); _publishWorkspaceRoute(); } if (keepInitial) _syncOpenWorkspace(); } bool _updateWorkspacePersistence(ChatScreen oldWidget) { final scope = serverStorageScope(serverIdentity(widget.gateway)); if (oldWidget.persistWorkspace == widget.persistWorkspace && (!widget.persistWorkspace || scope == _workspaceScope)) { // Another connection to the same server: only the open-chat sync // follows the gateway. if (widget.persistWorkspace && !identical(oldWidget.gateway, widget.gateway)) { _bindOpenWorkspace(after: Future.value()); } return false; } _workspaceBinding?.dispose(); _workspaceBinding = null; _openWorkspace?.dispose(); _openWorkspace = null; if (_workspaceScope != null && scope != _workspaceScope) { _workspace.restoreLayout(ChatWorkspaceSnapshot.fromLayout(null, null)!); _workspaceVisible = false; _usedWorkspace = true; _sidebarMode = ChatSidebarMode.expanded; _publishedWorkspaceSession = null; final initial = widget.initialSessionId; if (initial != null && initial.isNotEmpty) { _workspace.open(initial); _workspaceVisible = true; } } _workspaceScope = null; _bindWorkspacePersistence(); return true; } final GlobalKey _workspaceKey = GlobalKey(); bool _workspaceVisible = false; bool _usedWorkspace = false; String? _publishedWorkspaceSession; String _workspaceSignature = ''; /// Ctrl+Tab cycles the floating chat windows while any is shown, from the /// tiling as well (see [ChatWindows]). With none shown it cycles the /// retained panes, even when the sidebar or toolbar owns focus, and over a /// single pane it does nothing: it never brings up a chat that is not /// visible in the tiling. Command+Tab stays with the operating system's /// application switcher. While the app's terminal is shown, Ctrl+Tab moves /// between its tabs instead. A floating window that is not a chat, or any /// other window holding the keyboard, keeps the key. bool _cycleChatKey(KeyEvent event) { final keyboard = HardwareKeyboard.instance; if (event is! KeyDownEvent || TerminalScope.peek(context)?.claimsTabKeys == true || keyboardWindow() != null || event.logicalKey != LogicalKeyboardKey.tab || !keyboard.isControlPressed || keyboard.isMetaPressed || keyboard.isAltPressed || !_chatOwnsKeyboard()) { return false; } if (widget.windows?.raiseTopFromTiling() ?? false) return true; if (!_workspaceVisible || _workspace.paneCount < 2) return false; final panes = _workspace.panes; final active = panes.indexWhere( (pane) => pane.id == _workspace.activePaneId, ); final direction = keyboard.isShiftPressed ? -1 : 1; final target = panes[((active < 0 ? 0 : active) + direction) % panes.length]; _workspace.activate(target.id); WidgetsBinding.instance.addPostFrameCallback((_) { if (!mounted || !_workspaceVisible || _workspace.activePaneId != target.id) { return; } final destination = ShellBarScope.maybeOf(context)?.registry.focus; if (destination == null || destination == AppDestination.chat) { _composerFocus.request(target.sessionId); } }); WidgetsBinding.instance.ensureVisualUpdate(); return true; } void _workspaceChanged() { if (!mounted) return; if (_workspaceBinding?.isRestoring == true) return; final signature = '${_workspace.activePaneId}:${_workspace.panes.map((p) => '${p.id}=${p.sessionId}').join(',')}'; if (_workspaceSignature == signature) return; _workspaceSignature = signature; _syncOpenWorkspace(); void update() { if (!mounted) return; setState(() {}); _publishWorkspaceRoute(); } if (SchedulerBinding.instance.schedulerPhase == SchedulerPhase.persistentCallbacks) { WidgetsBinding.instance.addPostFrameCallback((_) => update()); } else { update(); } } void _publishWorkspaceRoute() { if (!mounted) return; final id = _workspace.activePane?.sessionId; final destination = ShellBarScope.maybeOf(context)?.registry.focus; if (!_workspaceVisible || id == null || id == _publishedWorkspaceSession || (destination != null && destination != AppDestination.chat)) { return; } _publishedWorkspaceSession = id; widget.onSessionSelected?.call(id); } void _split(JsonMap session, ChatSplitAxis axis) { final id = '${session['id'] ?? ''}'; if (id.isEmpty) return; _openedSessions[id] = session; _workspaceVisible = true; if (!_pageOpen && showsListBesideDetail(context)) _usedWorkspace = true; _workspace.splitActive(id, axis); if (showsListBesideDetail(context) || chatSelectionFocusesComposer(const {})) { _composerFocus.request(id); } else { _composerFocus.cancel(); FocusManager.instance.primaryFocus?.unfocus(); } } void _openBeside(JsonMap session) => _split(session, ChatSplitAxis.horizontal); void _openBelow(JsonMap session) => _split(session, ChatSplitAxis.vertical); /// The pane's chat trades places with [targetPaneId]'s and keeps focus; the /// retained view moves, so its scroll, draft and running turn stay. void _movePane(String paneId, String targetPaneId) { _workspace.swap(paneId, targetPaneId); final session = _workspace.activePane?.sessionId; if (session != null) _composerFocus.request(session); } void _closePane(String paneId) { _workspace.close(paneId); if (_workspace.paneCount == 0) _back(); } void _pickPane(BuildContext context) => showChatPanePicker( context, panes: [ for (final pane in _workspace.panes) ( id: pane.id, title: '${_rowFor(pane.sessionId)?['title'] ?? pane.sessionId}', ), ], activeId: _workspace.activePaneId, onSelected: (id) { _workspace.activate(id); final session = _workspace.activePane?.sessionId; if (session != null && chatSelectionFocusesComposer(const {})) { _composerFocus.request(session); } }, ); void _addPane(BuildContext context) { // The action normally lives in the pane's More menu. Let that menu finish // closing before pushing the picker, otherwise its root-overlay teardown // can hide the newly opened anchored menu. Future.delayed(Duration.zero, () { if (!context.mounted) return; unawaited( showAddChatPanePicker( context, controller: _sessionsForSidebar, sidebarFolds: _foldsForSidebar, excludedSessionIds: _workspace.panes .map((pane) => pane.sessionId) .toSet(), onSelected: (session) { if (!showsListBesideDetail(context)) { // Save a horizontal desktop layout underneath the phone tape. // Keep the rail compact so unfolding leaves room for the panes. _setSidebarMode(ChatSidebarMode.compact); _openBeside(session); } else { _openBelow(session); } }, ), ); }); } Widget _workspaceView() => SafeArea( top: false, child: ChatCenterStageKeys( controller: ChatCenterStageController.instance, enabled: () => _workspaceVisible && _workspace.paneCount > 0 && showsListBesideDetail(context) && _chatOwnsKeyboard(), child: ChatWorkspace( key: _workspaceKey, centerStage: ChatCenterStageController.instance, paneColor: (pane) => chatColorShade(context, chatSessionColor(_rowFor(pane.sessionId))), controller: _workspace, onVisibleSessionIdsChanged: _workspaceVisibilityChanged, onMoveTargetsChanged: _paneMoveTargetsChanged, shortcutsEnabled: _workspaceVisible, singlePane: !showsListBesideDetail(context), mobilePeeks: true, paneTitle: (pane) => '${_rowFor(pane.sessionId)?['title'] ?? pane.sessionId}', onFocusPane: (pane) => _composerFocus.request(pane.sessionId), paneBuilder: (context, pane, active) { final scope = ChatWorkspacePaneScope.maybeOf(context); final topShared = scope?.topEdgeShared ?? false; final bottomShared = scope?.bottomEdgeShared ?? false; final leftShared = scope?.leftEdgeShared ?? false; final rightShared = scope?.rightEdgeShared ?? false; final activeColor = _workspace.paneCount > 1 && active ? chatColorShade( context, chatSessionColor(_rowFor(pane.sessionId)), ) ?? Theme.of(context).colorScheme.primary : Colors.transparent; return Semantics( selected: active, child: AnimatedContainer( duration: showsListBesideDetail(context) ? Motion.of(context, Motion.standard) : Duration.zero, curve: Motion.curve, foregroundDecoration: BoxDecoration( border: showsListBesideDetail(context) ? Border( top: bottomShared && !topShared ? BorderSide(color: activeColor) : BorderSide.none, bottom: BorderSide( color: bottomShared ? Colors.transparent : activeColor, ), left: bottomShared && topShared && !leftShared ? BorderSide(color: activeColor) : BorderSide.none, right: bottomShared && topShared && leftShared && !rightShared ? BorderSide(color: activeColor) : BorderSide.none, ) : Border( bottom: BorderSide( color: bottomShared ? Colors.transparent : activeColor, ), ), ), // Every pane's bar carries its own chat's colour; beside the // active pane the others fade theirs. child: ChatPaneActivity( inactive: _workspace.paneCount > 1 && !active, child: KeyedSubtree( key: ValueKey('chat-pane-detail-${pane.id}'), child: _thread(pane), ), ), ), ); }, ), ), ); }