Skip to content

The ultimate harness for coding agents and beyond. All your agents. All your machines. One command center. Start with code, then follow your curiosity and build across disciplines: CAD, circuits, robots, games and music.

refactor(mobile): no keymap on the phone

dee6c9667eed07f
diff --git a/mobile/lib/app_shell.dart b/mobile/lib/app_shell.dart
index f9eb6a762..5547683c4 100644
--- a/mobile/lib/app_shell.dart
+++ b/mobile/lib/app_shell.dart
@@ -12,14 +12,12 @@ import 'core/startup.dart';
import 'logging/app_log.dart';
import 'logging/install.dart';
import 'logging/startup_trace.dart';
-import 'shortcuts/app_keymap.dart';
/// A screen the app puts up for one of its states — signed in, signed out, starting.
typedef AuthenticatedScreenBuilder = Widget Function(AppNotifier app);
-/// Everything both entry points do before their first frame: file logs, the
-/// crash log, the keyboard config, the saved appearance, and the native window
-/// where there is one.
+/// Everything the app does before its first frame: file logs, the crash log and
+/// the saved appearance.
///
/// Lives here rather than in either `main.dart` so the two cannot drift — the
/// mobile app is a separate package (`../mobile`) that depends on this one, and
@@ -49,22 +47,14 @@ Future<void> startHarness({
// is an offset into THIS launch. Touched before any awaited work so the origin
// is the entrypoint rather than whatever step happens to mark itself first.
StartupTrace.mark('startHarness');
- final keymap = AppKeymap(store: AppKeymap.fileStore());
- // Keyboard configuration has its own file and watchers. It can load beside
- // the appearance, but both must be ready before the window becomes usable.
- //
- // Timed apart rather than as one `Future.wait`: they finish together by
- // construction, so a single number around the pair would only ever report the
- // slower one and never say WHICH. On a phone that distinction is the whole
- // question — the keymap reads a file nobody on a touchscreen can have edited.
- await Future.wait([
- StartupTrace.time('settings.load', loadPersistedSettings),
- StartupTrace.time('keymap.start', keymap.start),
- ]);
+ // ⚠️ **No keymap.** The desktop loads its keyboard configuration here, a file
+ // and its watchers, beside the appearance. Nothing on the phone reads a keymap
+ // — no key is ever matched against one — so the file a touchscreen could not
+ // have edited is not read either.
+ await StartupTrace.time('settings.load', loadPersistedSettings);
runApp(
ProviderScope(
child: HarnessApp(
- keymap: keymap,
authenticatedScreen: authenticatedScreen,
signedOutScreen: signedOutScreen,
bootScreen: bootScreen,
@@ -84,12 +74,10 @@ Future<void> startHarness({
class HarnessApp extends StatelessWidget {
const HarnessApp({
super.key,
- this.keymap,
required this.authenticatedScreen,
required this.signedOutScreen,
required this.bootScreen,
});
- final AppKeymap? keymap;
final AuthenticatedScreenBuilder authenticatedScreen;
final AuthenticatedScreenBuilder signedOutScreen;
final AuthenticatedScreenBuilder bootScreen;
@@ -167,14 +155,7 @@ class HarnessApp extends StatelessWidget {
builder: (context, child) => MediaQuery.withClampedTextScaling(
minScaleFactor: scale,
maxScaleFactor: scale,
- child: _GridTokenScope(
- child: keymap == null
- ? child ?? const SizedBox.shrink()
- : KeymapProvider(
- keymap: keymap!,
- child: child ?? const SizedBox.shrink(),
- ),
- ),
+ child: _GridTokenScope(child: child ?? const SizedBox.shrink()),
),
home: AnalyticsLifecycle(
child: RootShell(
diff --git a/mobile/lib/shortcuts/app_keymap.dart b/mobile/lib/shortcuts/app_keymap.dart
deleted file mode 100644
index 0a47f5b40..000000000
--- a/mobile/lib/shortcuts/app_keymap.dart
+++ /dev/null
@@ -1,159 +0,0 @@
-import 'dart:io';
-
-import 'package:flutter/widgets.dart';
-
-import '../core/host_platform.dart';
-import 'keymap.dart';
-import 'keymap_commands.dart';
-import 'keymap_store.dart';
-
-/// A window's configuration, injectable so tests never read a user's dotfiles.
-class AppKeymap extends ChangeNotifier {
- AppKeymap({this.store}) {
- store?.addListener(_changed);
- }
- final KeymapStore? store;
- int version = 0;
- ResolvedKeymap get current => store?.current ?? harnessDefaultKeymap;
- String? get error => store?.error;
- String? get path => store?.file.path;
- void _changed() {
- version++;
- notifyListeners();
- }
-
- Future<void> start() async {
- await store?.start();
- }
-
- static KeymapStore fileStore() => KeymapStore(
- file: File(KeymapStore.defaultPath()),
- defaults: harnessDefaultBindings,
- commands: harnessCommandById.keys.toSet(),
- validate: (map) => validateNativeKeys(map, macOS: Platform.isMacOS),
- // ⚠️ **Not watched on a phone, and the file is not editable there either.**
- // Watching costs a symlink walk up the whole path and a `Directory.watch`
- // per parent — and iOS does not implement `Directory.watch` at all, so
- // every one of those throws, each failure schedules another reload, and the
- // walk runs again. That whole sequence is on the critical path before the
- // first frame (see `startHarness`), to notice edits to a dotfile that a
- // touchscreen has no way to produce: there is no shell, no editor, and no
- // sync into the app's sandbox. The file is still READ, so a keyboard
- // attached to an iPad keeps whatever bindings a build ships with.
- watchFiles: !isMobileHost,
- );
-
- Iterable<KeyBinding> bindings(
- String command, {
- KeymapContext context = KeymapContext.workspace,
- }) => current
- .bindingsFor(context)
- .where((binding) => binding.command == command);
-
- String? hint(
- String command, {
- KeymapContext context = KeymapContext.workspace,
- }) {
- final binding = bindings(command, context: context).firstOrNull;
- return binding == null ? null : describeKeyBinding(binding);
- }
-
- /// These are names of actual AppKit commands, not all system shortcuts.
- /// Native editing is dispatched before Flutter, including sequence suffixes.
- static void validateNativeKeys(ResolvedKeymap map, {required bool macOS}) {
- if (!macOS) return;
- final reserved = {
- for (final chord in [
- 'cmd+q',
- 'cmd+m',
- 'cmd+alt+h',
- 'cmd+ctrl+f',
- 'cmd+c',
- 'cmd+v',
- 'cmd+x',
- 'cmd+a',
- 'cmd+z',
- 'cmd+shift+z',
- 'cmd+alt+shift+v',
- 'cmd+backquote',
- 'cmd+shift+backquote',
- 'cmd+0',
- 'cmd+equal',
- 'cmd+shift+equal',
- 'cmd+minus',
- ])
- KeyStroke.parse(chord),
- };
- for (final context in KeymapContext.values) {
- for (final binding in map.bindingsFor(context)) {
- final conflict = binding.keys.where(reserved.contains).firstOrNull;
- if (binding.custom && conflict != null) {
- throw FormatException(
- '$conflict belongs to a native Mac editing, font or window command; choose another key',
- );
- }
- }
- }
- }
-
- @override
- void dispose() {
- store?.removeListener(_changed);
- super.dispose();
- }
-}
-
-/// InheritedTheme lets dialogs/routes carry the same live configuration.
-/// The provider rebuilds only on config changes, never on individual keys.
-class KeymapProvider extends StatelessWidget {
- const KeymapProvider({super.key, required this.keymap, required this.child});
- final AppKeymap keymap;
- final Widget child;
- @override
- Widget build(BuildContext context) => ListenableBuilder(
- listenable: keymap,
- builder: (context, _) =>
- KeymapTheme(keymap: keymap, version: keymap.version, child: child),
- );
-}
-
-class KeymapTheme extends InheritedTheme {
- const KeymapTheme({
- super.key,
- required this.keymap,
- required this.version,
- required super.child,
- });
- final AppKeymap keymap;
- final int version;
- static AppKeymap? of(BuildContext context, {bool listen = true}) =>
- (listen
- ? context.dependOnInheritedWidgetOfExactType<KeymapTheme>()
- : context.getInheritedWidgetOfExactType<KeymapTheme>())
- ?.keymap;
- @override
- bool updateShouldNotify(KeymapTheme oldWidget) =>
- keymap != oldWidget.keymap || version != oldWidget.version;
- @override
- Widget wrap(BuildContext context, Widget child) =>
- KeymapProvider(keymap: keymap, child: child);
-}
-
-/// Pickers provide their own actions. A terminal only changes scope/IME state;
-/// the containing workspace continues to own its navigation commands.
-class KeymapRegion extends InheritedWidget {
- const KeymapRegion({
- super.key,
- required this.contextKind,
- this.actions,
- this.composing,
- required super.child,
- });
- final KeymapContext contextKind;
- final Map<String, VoidCallback>? actions;
- final bool Function()? composing;
- static KeymapRegion? of(BuildContext context) =>
- context.getInheritedWidgetOfExactType<KeymapRegion>();
- @override
- bool updateShouldNotify(KeymapRegion oldWidget) => false;
-}
diff --git a/mobile/lib/shortcuts/app_shortcuts.dart b/mobile/lib/shortcuts/app_shortcuts.dart
deleted file mode 100644
index a645a0ea8..000000000
--- a/mobile/lib/shortcuts/app_shortcuts.dart
+++ /dev/null
@@ -1,448 +0,0 @@
-import 'package:flutter/services.dart';
-import 'package:flutter/widgets.dart';
-
-import '../logging/debug_surface.dart';
-
-/// Harness uses Command as a direct prefix for frequent workspace actions.
-/// T opens a tab, N creates a harness, O finds one, S changes layout,
-/// H/J/K/L and arrows focus panes, B routes a task, D splits down and R splits
-/// right. The same definitions feed live keys, help and search.
-///
-/// Unclaimed input stays with the focused agent or text field. Composition,
-/// copy/paste and the coding agent's own prompt editing must keep working.
-/// AppKit's Edit menu has no competing equivalents for C/V/X/A, and Hide has
-/// no H equivalent: Flutter owns editing and Harness owns Command-H navigation.
-/// Menu clicks still use their usual responder-chain actions.
-
-enum ShortcutAction {
- newSwarm,
- closeSwarm,
- reopenClosedSwarm,
- showHistory,
- renameSwarm,
- nextSwarm,
- previousSwarm,
- showSettings,
- toggleRail,
- nextAgent,
- previousAgent,
- focusPaneLeft,
- focusPaneRight,
- focusPaneAbove,
- focusPaneBelow,
- movePaneLeft,
- movePaneRight,
- movePaneUp,
- movePaneDown,
-
- /// The agent this window was on before the current one — tmux's `prefix ;`.
- lastPane,
-
- /// One pane filling the grid, and back. tmux's `prefix z`.
- zoomPane,
-
- /// Find a live question and jump to the agent waiting for input.
- showAttention,
-
- findTerminal,
- findNext,
- findPrevious,
-
- /// Add an agent to the current swarm, independently of navigation.
- addAgent,
-
- closePane,
- newAgent,
- routeTask,
- reload,
- showLayout,
- pinPane,
- showShortcuts,
- showDebug,
-}
-
-enum ShortcutGroup { navigate, panes, actions }
-
-extension ShortcutGroupLabel on ShortcutGroup {
- String get label => switch (this) {
- ShortcutGroup.navigate => 'Workspace',
- ShortcutGroup.panes => 'Panes',
- ShortcutGroup.actions => 'Actions',
- };
-}
-
-class AppShortcut {
- const AppShortcut({
- required this.action,
- required this.activator,
- required this.label,
- required this.group,
- });
-
- final ShortcutAction action;
- final SingleActivator activator;
- final String label;
- final ShortcutGroup group;
-}
-
-const List<AppShortcut> kAppShortcuts = [
- AppShortcut(
- action: ShortcutAction.findTerminal,
- activator: SingleActivator(LogicalKeyboardKey.keyF, meta: true),
- label: 'Find in the focused terminal',
- group: ShortcutGroup.navigate,
- ),
- AppShortcut(
- action: ShortcutAction.findNext,
- activator: SingleActivator(LogicalKeyboardKey.keyG, meta: true),
- label: 'Next terminal match',
- group: ShortcutGroup.navigate,
- ),
- AppShortcut(
- action: ShortcutAction.findPrevious,
- activator: SingleActivator(
- LogicalKeyboardKey.keyG,
- meta: true,
- shift: true,
- ),
- label: 'Previous terminal match',
- group: ShortcutGroup.navigate,
- ),
- // --- navigate -------------------------------------------------------------
- //
- // Command-arrows and H/J/K/L focus panes; bare keys stay with the terminal.
- AppShortcut(
- action: ShortcutAction.focusPaneLeft,
- activator: SingleActivator(LogicalKeyboardKey.keyH, meta: true),
- label: 'Focus the pane to the left',
- group: ShortcutGroup.navigate,
- ),
- AppShortcut(
- action: ShortcutAction.focusPaneBelow,
- activator: SingleActivator(LogicalKeyboardKey.keyJ, meta: true),
- label: 'Focus the pane below',
- group: ShortcutGroup.navigate,
- ),
- AppShortcut(
- action: ShortcutAction.focusPaneAbove,
- activator: SingleActivator(LogicalKeyboardKey.keyK, meta: true),
- label: 'Focus the pane above',
- group: ShortcutGroup.navigate,
- ),
- AppShortcut(
- action: ShortcutAction.focusPaneRight,
- activator: SingleActivator(LogicalKeyboardKey.keyL, meta: true),
- label: 'Focus the pane to the right',
- group: ShortcutGroup.navigate,
- ),
- AppShortcut(
- action: ShortcutAction.focusPaneLeft,
- activator: SingleActivator(LogicalKeyboardKey.arrowLeft, meta: true),
- label: 'Focus the pane to the left',
- group: ShortcutGroup.navigate,
- ),
- AppShortcut(
- action: ShortcutAction.focusPaneBelow,
- activator: SingleActivator(LogicalKeyboardKey.arrowDown, meta: true),
- label: 'Focus the pane below',
- group: ShortcutGroup.navigate,
- ),
- AppShortcut(
- action: ShortcutAction.focusPaneAbove,
- activator: SingleActivator(LogicalKeyboardKey.arrowUp, meta: true),
- label: 'Focus the pane above',
- group: ShortcutGroup.navigate,
- ),
- AppShortcut(
- action: ShortcutAction.focusPaneRight,
- activator: SingleActivator(LogicalKeyboardKey.arrowRight, meta: true),
- label: 'Focus the pane to the right',
- group: ShortcutGroup.navigate,
- ),
-
- // --- panes ----------------------------------------------------------------
- //
- // Shift-Command-arrows move the pane itself in the same direction.
- AppShortcut(
- action: ShortcutAction.movePaneLeft,
- activator: SingleActivator(
- LogicalKeyboardKey.arrowLeft,
- meta: true,
- shift: true,
- ),
- label: 'Move this pane left',
- group: ShortcutGroup.panes,
- ),
- AppShortcut(
- action: ShortcutAction.movePaneDown,
- activator: SingleActivator(
- LogicalKeyboardKey.arrowDown,
- meta: true,
- shift: true,
- ),
- label: 'Move this pane down',
- group: ShortcutGroup.panes,
- ),
- AppShortcut(
- action: ShortcutAction.movePaneUp,
- activator: SingleActivator(
- LogicalKeyboardKey.arrowUp,
- meta: true,
- shift: true,
- ),
- label: 'Move this pane up',
- group: ShortcutGroup.panes,
- ),
- AppShortcut(
- action: ShortcutAction.movePaneRight,
- activator: SingleActivator(
- LogicalKeyboardKey.arrowRight,
- meta: true,
- shift: true,
- ),
- label: 'Move this pane right',
- group: ShortcutGroup.panes,
- ),
-
- // ⌘⏎ — tmux's `prefix z`, one of the most-pressed keys that multiplexer has.
- // Enter because it reads as "make THIS the thing", and because it is the one
- // chord on this list nobody has to look up twice.
- AppShortcut(
- action: ShortcutAction.zoomPane,
- activator: SingleActivator(LogicalKeyboardKey.enter, meta: true),
- label: 'Zoom this pane, or put it back',
- group: ShortcutGroup.panes,
- ),
- // ⌘; — tmux's `prefix ;`, spelled the same. Two agents at a time is the shape
- // most work actually has, and walking a list to get back to the other one is
- // the wrong motion for it.
- AppShortcut(
- action: ShortcutAction.lastPane,
- activator: SingleActivator(LogicalKeyboardKey.semicolon, meta: true),
- label: 'Back to the pane you were just on',
- group: ShortcutGroup.panes,
- ),
- AppShortcut(
- action: ShortcutAction.closePane,
- activator: SingleActivator(LogicalKeyboardKey.keyW, meta: true),
- label: 'Close the focused pane',
- group: ShortcutGroup.panes,
- ),
- AppShortcut(
- action: ShortcutAction.showLayout,
- activator: SingleActivator(LogicalKeyboardKey.keyS, meta: true),
- label: 'Choose the grid layout',
- group: ShortcutGroup.panes,
- ),
-
- // --- agents ---------------------------------------------------------------
- //
- // In Swarms, brackets follow Chrome's Back/Forward history. Directional
- // pane movement keeps its own keys; Shift-brackets step through tabs.
- AppShortcut(
- action: ShortcutAction.previousAgent,
- activator: SingleActivator(LogicalKeyboardKey.bracketLeft, meta: true),
- label: 'Back',
- group: ShortcutGroup.navigate,
- ),
- AppShortcut(
- action: ShortcutAction.nextAgent,
- activator: SingleActivator(LogicalKeyboardKey.bracketRight, meta: true),
- label: 'Forward',
- group: ShortcutGroup.navigate,
- ),
- // Control-Tab and Shift-brackets move through tabs. Pane directions and
- // agent history have their own shortcuts above.
- AppShortcut(
- action: ShortcutAction.nextAgent,
- activator: SingleActivator(LogicalKeyboardKey.tab, control: true),
- label: 'Next pane',
- group: ShortcutGroup.navigate,
- ),
- AppShortcut(
- action: ShortcutAction.previousAgent,
- activator: SingleActivator(
- LogicalKeyboardKey.tab,
- control: true,
- shift: true,
- ),
- label: 'Previous pane',
- group: ShortcutGroup.navigate,
- ),
- AppShortcut(
- action: ShortcutAction.toggleRail,
- activator: SingleActivator(LogicalKeyboardKey.backslash, meta: true),
- label: 'Show or hide the sidebar',
- group: ShortcutGroup.navigate,
- ),
-
- // --- actions --------------------------------------------------------------
- AppShortcut(
- action: ShortcutAction.newAgent,
- activator: SingleActivator(LogicalKeyboardKey.keyN, meta: true),
- label: 'New Harness',
- group: ShortcutGroup.actions,
- ),
- AppShortcut(
- action: ShortcutAction.routeTask,
- activator: SingleActivator(LogicalKeyboardKey.keyB, meta: true),
- label: 'Describe a task, and let it pick the agent',
- group: ShortcutGroup.actions,
- ),
- AppShortcut(
- action: ShortcutAction.reload,
- activator: SingleActivator(LogicalKeyboardKey.keyR, meta: true),
- label: 'Reload machines and harnesses',
- group: ShortcutGroup.actions,
- ),
- AppShortcut(
- action: ShortcutAction.showShortcuts,
- activator: SingleActivator(LogicalKeyboardKey.slash, meta: true),
- label: 'Show keyboard shortcuts',
- group: ShortcutGroup.actions,
- ),
-];
-
-/// Open Settings ▸ Debug — the app's own log, as this session still holds it.
-///
-/// Kept out of [kAppShortcuts] because it is not always there: a release build
-/// has no Debug screen (see [kDebugSurfaceEnabled]), and a key that opens
-/// nothing is worse than a key that was never taken. Shift keeps it separate
-/// from the everyday Command-D split action.
-const AppShortcut kDebugShortcut = AppShortcut(
- action: ShortcutAction.showDebug,
- activator: SingleActivator(LogicalKeyboardKey.keyD, meta: true, shift: true),
- label: 'Open the debug log',
- group: ShortcutGroup.actions,
-);
-
-/// Every shortcut THIS build has — [kAppShortcuts], plus the developer ones the
-/// build is allowed to show.
-///
-/// The one list the bindings, the ⌘/ sheet and the tooltips all read, so a
-/// build cannot bind a key it does not document or document one it does not
-/// bind.
-List<AppShortcut> appShortcuts({bool swarmMode = true}) => [
- for (final shortcut in kAppShortcuts)
- if (!swarmMode ||
- (!const {
- ShortcutAction.toggleRail,
- ShortcutAction.closePane,
- ShortcutAction.reload,
- }.contains(shortcut.action) &&
- !shortcut.activator.control))
- shortcut,
- if (swarmMode) ...kSwarmShortcuts,
- if (kDebugSurfaceEnabled) kDebugShortcut,
-];
-
-/// Swarm bindings replace the old workspace navigation in the retained legacy
-/// screen. Live Swarm bindings, tooltips, and help all use this same catalog.
-const kSwarmShortcuts = [
- AppShortcut(
- action: ShortcutAction.addAgent,
- activator: SingleActivator(LogicalKeyboardKey.keyO, meta: true),
- label: 'Find Harness',
- group: ShortcutGroup.actions,
- ),
- AppShortcut(
- action: ShortcutAction.showHistory,
- activator: SingleActivator(LogicalKeyboardKey.keyY, meta: true),
- label: 'Show full history',
- group: ShortcutGroup.navigate,
- ),
- AppShortcut(
- action: ShortcutAction.newSwarm,
- activator: SingleActivator(LogicalKeyboardKey.keyT, meta: true),
- label: 'New Tab',
- group: ShortcutGroup.navigate,
- ),
- AppShortcut(
- action: ShortcutAction.reopenClosedSwarm,
- activator: SingleActivator(
- LogicalKeyboardKey.keyT,
- meta: true,
- shift: true,
- ),
- label: 'Reopen last closed harness',
- group: ShortcutGroup.navigate,
- ),
- AppShortcut(
- action: ShortcutAction.closeSwarm,
- activator: SingleActivator(LogicalKeyboardKey.keyW, meta: true),
- label: 'Close Tab',
- group: ShortcutGroup.navigate,
- ),
- AppShortcut(
- action: ShortcutAction.renameSwarm,
- activator: SingleActivator(
- LogicalKeyboardKey.keyR,
- meta: true,
- shift: true,
- ),
- label: 'Rename Tab',
- group: ShortcutGroup.navigate,
- ),
- AppShortcut(
- action: ShortcutAction.nextSwarm,
- activator: SingleActivator(
- LogicalKeyboardKey.bracketRight,
- meta: true,
- shift: true,
- ),
- label: 'Next Harness',
- group: ShortcutGroup.navigate,
- ),
- AppShortcut(
- action: ShortcutAction.previousSwarm,
- activator: SingleActivator(
- LogicalKeyboardKey.bracketLeft,
- meta: true,
- shift: true,
- ),
- label: 'Previous Harness',
- group: ShortcutGroup.navigate,
- ),
- AppShortcut(
- action: ShortcutAction.nextSwarm,
- activator: SingleActivator(LogicalKeyboardKey.tab, control: true),
- label: 'Next Harness',
- group: ShortcutGroup.navigate,
- ),
- AppShortcut(
- action: ShortcutAction.previousSwarm,
- activator: SingleActivator(
- LogicalKeyboardKey.tab,
- control: true,
- shift: true,
- ),
- label: 'Previous Harness',
- group: ShortcutGroup.navigate,
- ),
- AppShortcut(
- action: ShortcutAction.showAttention,
- activator: SingleActivator(
- LogicalKeyboardKey.keyI,
- meta: true,
- shift: true,
- ),
- label: 'Show harnesses needing input',
- group: ShortcutGroup.navigate,
- ),
- AppShortcut(
- action: ShortcutAction.closePane,
- activator: SingleActivator(
- LogicalKeyboardKey.keyW,
- meta: true,
- shift: true,
- ),
- label: 'Close the focused pane',
- group: ShortcutGroup.panes,
- ),
- AppShortcut(
- action: ShortcutAction.showSettings,
- activator: SingleActivator(LogicalKeyboardKey.comma, meta: true),
- label: 'Open Settings',
- group: ShortcutGroup.actions,
- ),
-];
diff --git a/mobile/lib/shortcuts/keymap.dart b/mobile/lib/shortcuts/keymap.dart
deleted file mode 100644
index 9f366bc03..000000000
--- a/mobile/lib/shortcuts/keymap.dart
+++ /dev/null
@@ -1,400 +0,0 @@
-import 'dart:convert';
-
-enum KeymapContext { workspace, terminal, picker }
-
-/// A canonical logical key name and exact modifier set. Parsing happens on reload,
-/// never on the input path. The Flutter adapter supplies the same canonical keys.
-class KeyStroke {
- const KeyStroke(
- this.key, {
- this.control = false,
- this.alt = false,
- this.command = false,
- this.shift = false,
- });
-
- final String key;
- final bool control, alt, command, shift;
-
- static const _modifiers = {
- 'ctrl': 'control',
- 'control': 'control',
- 'alt': 'alt',
- 'option': 'alt',
- 'opt': 'alt',
- 'cmd': 'command',
- 'command': 'command',
- 'super': 'command',
- 'shift': 'shift',
- };
- static const _aliases = {
- 'return': 'enter',
- 'esc': 'escape',
- 'arrowleft': 'left',
- 'arrowright': 'right',
- 'arrowup': 'up',
- 'arrowdown': 'down',
- 'pgup': 'pageup',
- 'pgdn': 'pagedown',
- 'pagedn': 'pagedown',
- 'del': 'delete',
- 'backspace': 'backspace',
- ',': 'comma',
- '.': 'period',
- '/': 'slash',
- '\\': 'backslash',
- ';': 'semicolon',
- "'": 'quote',
- '`': 'backquote',
- '[': 'bracketleft',
- ']': 'bracketright',
- '-': 'minus',
- '=': 'equal',
- 'spacebar': 'space',
- };
- static const _named = {
- 'enter',
- 'escape',
- 'left',
- 'right',
- 'up',
- 'down',
- 'pageup',
- 'pagedown',
- 'home',
- 'end',
- 'delete',
- 'backspace',
- 'tab',
- 'space',
- 'comma',
- 'period',
- 'slash',
- 'backslash',
- 'semicolon',
- 'quote',
- 'backquote',
- 'bracketleft',
- 'bracketright',
- 'minus',
- 'equal',
- 'insert',
- };
-
- factory KeyStroke.parse(String value) {
- final parts = value.toLowerCase().split('+');
- final modifiers = <String>{};
- String? key;
- for (final part in parts) {
- final modifier = _modifiers[part];
- if (modifier != null) {
- if (!modifiers.add(modifier)) {
- throw FormatException('Repeated modifier in "$value"');
- }
- } else {
- if (key != null || part.isEmpty) {
- throw FormatException('Expected one key in "$value"');
- }
- key = _aliases[part] ?? part;
- }
- }
- if (key == null ||
- !(_named.contains(key) ||
- RegExp(r'^[a-z0-9]$').hasMatch(key) ||
- RegExp(r'^f([1-9]|1[0-9]|2[0-4])$').hasMatch(key))) {
- throw FormatException('Unknown key in "$value"');
- }
- return KeyStroke(
- key,
- control: modifiers.contains('control'),
- alt: modifiers.contains('alt'),
- command: modifiers.contains('command'),
- shift: modifiers.contains('shift'),
- );
- }
-
- @override
- String toString() => [
- if (control) 'ctrl',
- if (alt) 'alt',
- if (command) 'cmd',
- if (shift) 'shift',
- key,
- ].join('+');
-
- @override
- bool operator ==(Object other) =>
- other is KeyStroke &&
- key == other.key &&
- control == other.control &&
- alt == other.alt &&
- command == other.command &&
- shift == other.shift;
-
- @override
- int get hashCode => Object.hash(key, control, alt, command, shift);
-}
-
-class KeyBinding {
- KeyBinding({
- required Iterable<KeyStroke> keys,
- required this.command,
- this.context = KeymapContext.workspace,
- this.custom = false,
- }) : keys = List.unmodifiable(keys) {
- if (this.keys.isEmpty || this.keys.length > 4) {
- throw const FormatException('Use one to four keys in a sequence');
- }
- }
-
- final List<KeyStroke> keys;
-
- /// Null explicitly unbinds this sequence, including any longer descendants.
- final String? command;
- final KeymapContext context;
- final bool custom;
- String get sequence => keys.join(' ');
-}
-
-class KeymapConfig {
- const KeymapConfig.empty() : bindings = const [];
- KeymapConfig(Iterable<KeyBinding> bindings)
- : bindings = List.unmodifiable(bindings);
- final List<KeyBinding> bindings;
-
- factory KeymapConfig.parse(String source, {required Set<String> commands}) {
- final cleaned = _cleanJsonc(source);
- if (cleaned.trim().isEmpty) return const KeymapConfig.empty();
- final dynamic value;
- try {
- value = jsonDecode(cleaned);
- } on FormatException catch (error) {
- throw FormatException(error.message, source, error.offset);
- }
- if (value is! Map<String, dynamic>) {
- throw const FormatException('Keyboard config must be an object');
- }
- if (value.keys.any(
- (key) => !{'version', 'bindings', r'$schema'}.contains(key),
- )) {
- throw const FormatException('Unknown keyboard config property');
- }
- if ((value['version'] ?? 1) != 1) {
- throw const FormatException('Unsupported keyboard config version');
- }
- final rows = value['bindings'] ?? [];
- if (rows is! List || rows.length > 512) {
- throw const FormatException(
- 'bindings must be an array of at most 512 entries',
- );
- }
- final result = <KeyBinding>[];
- final seen = <String>{};
- for (var i = 0; i < rows.length; i++) {
- final row = rows[i];
- if (row is! Map<String, dynamic> ||
- row.keys.any((key) => !{'keys', 'command', 'when'}.contains(key)) ||
- row['keys'] is! String ||
- !row.containsKey('command')) {
- throw FormatException(
- 'bindings[$i] needs keys, command, and an optional when',
- );
- }
- final command = row['command'];
- // Retired actions must not invalidate the user's other custom shortcuts.
- if (const {'picker.preview', 'navigation.quick_open'}.contains(command) &&
- !commands.contains(command)) {
- continue;
- }
- if (command != null &&
- (command is! String || !commands.contains(command))) {
- throw FormatException('Unknown command in bindings[$i]: $command');
- }
- final scope = row['when'] ?? 'workspace';
- final contexts = KeymapContext.values.where(
- (context) => context.name == scope,
- );
- if (contexts.isEmpty) {
- throw FormatException('Unknown context in bindings[$i]: $scope');
- }
- final sequence = (row['keys'] as String).trim().replaceAll(
- RegExp(r'\s*\+\s*'),
- '+',
- );
- final binding = KeyBinding(
- keys: sequence.split(RegExp(r'\s+')).map(KeyStroke.parse),
- command: command as String?,
- context: contexts.first,
- custom: true,
- );
- if (!seen.add('${binding.context.name}:${binding.sequence}')) {
- throw FormatException(
- 'Duplicate binding: ${binding.sequence} in $scope',
- );
- }
- result.add(binding);
- }
- return KeymapConfig(result);
- }
-}
-
-class KeymapMatch {
- const KeymapMatch({this.command, this.prefix = false});
- final String? command;
- final bool prefix;
- bool get matched => command != null || prefix;
-}
-
-class _KeyNode {
- final children = <KeyStroke, _KeyNode>{};
- String? command;
-}
-
-/// Immutable lookup tables for each input context. Workspace commands are
-/// inherited by a terminal; a modal picker owns its own keys.
-class ResolvedKeymap {
- ResolvedKeymap(Iterable<KeyBinding> defaults, KeymapConfig config) {
- for (final context in KeymapContext.values) {
- final effective = <String, KeyBinding>{};
- void apply(Iterable<KeyBinding> entries, KeymapContext scope) {
- for (final entry in entries.where(
- (binding) => binding.context == scope,
- )) {
- if (entry.command == null) {
- effective.removeWhere(
- (key, _) =>
- key == entry.sequence || key.startsWith('${entry.sequence} '),
- );
- } else {
- effective[entry.sequence] = entry;
- }
- }
- }
-
- if (context != KeymapContext.workspace) {
- apply(defaults, KeymapContext.workspace);
- }
- apply(defaults, context);
- if (context != KeymapContext.workspace) {
- apply(config.bindings, KeymapContext.workspace);
- }
- apply(config.bindings, context);
- _bindings[context] = List.unmodifiable(effective.values);
- final root = _KeyNode();
- for (final entry in effective.values) {
- var node = root;
- for (final key in entry.keys) {
- if (node.command != null) _ambiguous(entry, context);
- node = node.children.putIfAbsent(key, _KeyNode.new);
- }
- if (node.children.isNotEmpty) _ambiguous(entry, context);
- node.command = entry.command;
- }
- _roots[context] = root;
- }
- }
-
- final _roots = <KeymapContext, _KeyNode>{};
- final _bindings = <KeymapContext, List<KeyBinding>>{};
-
- Never _ambiguous(KeyBinding binding, KeymapContext context) =>
- throw FormatException(
- 'Ambiguous prefix for ${binding.sequence} in ${context.name}; '
- 'unbind the shorter command before defining a sequence',
- );
-
- List<KeyBinding> bindingsFor(KeymapContext context) => _bindings[context]!;
-
- Iterable<KeyBinding> continuations(
- KeymapContext context,
- List<KeyStroke> prefix,
- ) => _bindings[context]!.where(
- (binding) =>
- binding.keys.length > prefix.length &&
- Iterable.generate(prefix.length)
- .every((i) => binding.keys[i] == prefix[i]),
- );
-
- KeymapMatch match(KeymapContext context, Iterable<KeyStroke> keys) {
- var node = _roots[context]!;
- for (final key in keys) {
- final next = node.children[key];
- if (next == null) return const KeymapMatch();
- node = next;
- }
- return KeymapMatch(command: node.command, prefix: node.children.isNotEmpty);
- }
-}
-
-/// Strip comments/trailing commas without shifting JSON decoder error offsets.
-/// String contents, escapes and newlines remain byte-for-byte intact.
-String _cleanJsonc(String source) {
- final chars = source.codeUnits.toList();
- var inString = false;
- for (var i = 0; i < chars.length; i++) {
- final c = chars[i];
- if (inString) {
- if (c == 92) {
- i++;
- } else if (c == 34) {
- inString = false;
- }
- continue;
- }
- if (c == 34) {
- inString = true;
- continue;
- }
- if (c != 47 || i + 1 >= chars.length) continue;
- final next = chars[i + 1];
- if (next == 47) {
- while (i < chars.length && chars[i] != 10 && chars[i] != 13) {
- chars[i++] = 32;
- }
- i--;
- } else if (next == 42) {
- final start = i;
- chars[i++] = 32;
- chars[i++] = 32;
- while (i < chars.length &&
- !(chars[i] == 42 && i + 1 < chars.length && chars[i + 1] == 47)) {
- if (chars[i] != 10 && chars[i] != 13) chars[i] = 32;
- i++;
- }
- if (i + 1 >= chars.length) {
- throw FormatException('Unterminated block comment', source, start);
- }
- chars[i] = 32;
- chars[++i] = 32;
- }
- }
- inString = false;
- for (var i = 0; i < chars.length; i++) {
- if (inString) {
- if (chars[i] == 92) {
- i++;
- } else if (chars[i] == 34) {
- inString = false;
- }
- } else if (chars[i] == 34) {
- inString = true;
- } else if (chars[i] == 44) {
- var next = i + 1;
- while (next < chars.length &&
- const {9, 10, 13, 32}.contains(chars[next])) {
- next++;
- }
- var previous = i - 1;
- while (previous >= 0 && const {9, 10, 13, 32}.contains(chars[previous])) {
- previous--;
- }
- if (previous >= 0 &&
- !const {91, 123, 44, 58}.contains(chars[previous]) &&
- next < chars.length &&
- (chars[next] == 93 || chars[next] == 125)) {
- chars[i] = 32;
- }
- }
- }
- return String.fromCharCodes(chars);
-}
diff --git a/mobile/lib/shortcuts/keymap_commands.dart b/mobile/lib/shortcuts/keymap_commands.dart
deleted file mode 100644
index 3038781e0..000000000
--- a/mobile/lib/shortcuts/keymap_commands.dart
+++ /dev/null
@@ -1,434 +0,0 @@
-import '../logging/debug_surface.dart';
-import 'app_shortcuts.dart';
-import 'keymap.dart';
-import 'keymap_keyboard.dart';
-
-/// Stable identities connect search to workspace actions. The same catalog
-/// supplies the file-remapping foundation; native runtime wiring is separate.
-class HarnessCommand {
- const HarnessCommand(
- this.id,
- this.label,
- this.group, {
- this.extraKeys = const [],
- this.action,
- this.nativeAction,
- this.context = KeymapContext.workspace,
- this.repeatable = false,
- });
- final String id, label;
- final ShortcutGroup group;
- final List<String> extraKeys;
-
- /// Workspace defaults come from the live shortcut table. A command cannot
- /// quietly propose different keys from the ones the user already uses.
- List<String> get keys =>
- action == null ? extraKeys : _workspaceKeys[action] ?? const [];
- final ShortcutAction? action;
- final String? nativeAction;
- final KeymapContext context;
- final bool repeatable;
-}
-
-final _workspaceKeys = _readWorkspaceKeys();
-Map<ShortcutAction, List<String>> _readWorkspaceKeys() {
- final result = <ShortcutAction, List<String>>{};
- for (final shortcut in appShortcuts()) {
- final keys = keyStrokeFor(
- shortcut.activator.trigger,
- command: shortcut.activator.meta,
- control: shortcut.activator.control,
- alt: shortcut.activator.alt,
- shift: shortcut.activator.shift,
- )!.toString();
- (result[shortcut.action] ??= []).add(keys);
- }
- return result;
-}
-
-final harnessCommands = <HarnessCommand>[
- const HarnessCommand(
- 'navigation.commands',
- 'Search commands',
- ShortcutGroup.actions,
- extraKeys: ['cmd+shift+p'],
- nativeAction: 'commands',
- ),
- const HarnessCommand(
- 'swarm.new',
- 'New Tab',
- ShortcutGroup.navigate,
- action: ShortcutAction.newSwarm,
- nativeAction: 'new',
- ),
- const HarnessCommand(
- 'swarm.close',
- 'Close Tab',
- ShortcutGroup.navigate,
- action: ShortcutAction.closeSwarm,
- nativeAction: 'closeActive',
- ),
- const HarnessCommand(
- 'swarm.reopen',
- 'Reopen last closed harness',
- ShortcutGroup.navigate,
- action: ShortcutAction.reopenClosedSwarm,
- nativeAction: 'reopen',
- ),
- const HarnessCommand(
- 'swarm.next',
- 'Next Harness',
- ShortcutGroup.navigate,
- action: ShortcutAction.nextSwarm,
- nativeAction: 'next',
- repeatable: true,
- ),
- const HarnessCommand(
- 'swarm.previous',
- 'Previous Harness',
- ShortcutGroup.navigate,
- action: ShortcutAction.previousSwarm,
- nativeAction: 'previous',
- repeatable: true,
- ),
- const HarnessCommand(
- 'swarm.rename',
- 'Rename Tab',
- ShortcutGroup.actions,
- action: ShortcutAction.renameSwarm,
- nativeAction: 'renameActive',
- ),
- const HarnessCommand(
- 'navigation.back',
- 'Go back',
- ShortcutGroup.navigate,
- action: ShortcutAction.previousAgent,
- nativeAction: 'historyBack',
- repeatable: true,
- ),
- const HarnessCommand(
- 'navigation.forward',
- 'Go forward',
- ShortcutGroup.navigate,
- action: ShortcutAction.nextAgent,
- nativeAction: 'historyForward',
- repeatable: true,
- ),
- const HarnessCommand(
- 'navigation.history',
- 'Show full history',
- ShortcutGroup.navigate,
- action: ShortcutAction.showHistory,
- nativeAction: 'showHistory',
- ),
- const HarnessCommand(
- 'navigation.needs_input',
- 'Show harnesses needing input',
- ShortcutGroup.navigate,
- action: ShortcutAction.showAttention,
- nativeAction: 'notifications',
- ),
- for (var i = 1; i <= 9; i++)
- HarnessCommand(
- 'swarm.select_$i',
- 'Select tab $i',
- ShortcutGroup.navigate,
- extraKeys: ['cmd+$i'],
- ),
- for (var i = 1; i <= 9; i++)
- HarnessCommand('pane.focus_$i', 'Focus pane $i', ShortcutGroup.panes),
- const HarnessCommand(
- 'pane.focus_left',
- 'Focus the pane to the left',
- ShortcutGroup.panes,
- action: ShortcutAction.focusPaneLeft,
- repeatable: true,
- ),
- const HarnessCommand(
- 'pane.focus_right',
- 'Focus the pane to the right',
- ShortcutGroup.panes,
- action: ShortcutAction.focusPaneRight,
- repeatable: true,
- ),
- const HarnessCommand(
- 'pane.focus_above',
- 'Focus the pane above',
- ShortcutGroup.panes,
- action: ShortcutAction.focusPaneAbove,
- repeatable: true,
- ),
- const HarnessCommand(
- 'pane.focus_below',
- 'Focus the pane below',
- ShortcutGroup.panes,
- action: ShortcutAction.focusPaneBelow,
- repeatable: true,
- ),
- const HarnessCommand(
- 'pane.move_left',
- 'Move the pane left',
- ShortcutGroup.panes,
- action: ShortcutAction.movePaneLeft,
- repeatable: true,
- ),
- const HarnessCommand(
- 'pane.move_right',
- 'Move the pane right',
- ShortcutGroup.panes,
- action: ShortcutAction.movePaneRight,
- repeatable: true,
- ),
- const HarnessCommand(
- 'pane.move_up',
- 'Move the pane up',
- ShortcutGroup.panes,
- action: ShortcutAction.movePaneUp,
- repeatable: true,
- ),
- const HarnessCommand(
- 'pane.move_down',
- 'Move the pane down',
- ShortcutGroup.panes,
- action: ShortcutAction.movePaneDown,
- repeatable: true,
- ),
- const HarnessCommand(
- 'pane.zoom',
- 'Zoom or restore the focused pane',
- ShortcutGroup.panes,
- action: ShortcutAction.zoomPane,
- nativeAction: 'zoomPane',
- ),
- const HarnessCommand(
- 'pane.close',
- 'Close the focused pane',
- ShortcutGroup.panes,
- action: ShortcutAction.closePane,
- nativeAction: 'closePane',
- ),
- const HarnessCommand(
- 'pane.last',
- 'Return to the last pane',
- ShortcutGroup.panes,
- action: ShortcutAction.lastPane,
- ),
- const HarnessCommand(
- 'pane.pin',
- 'Pin or unpin the focused pane',
- ShortcutGroup.panes,
- action: ShortcutAction.pinPane,
- nativeAction: 'pinPane',
- ),
- const HarnessCommand(
- 'pane.layout',
- 'Choose a layout',
- ShortcutGroup.panes,
- action: ShortcutAction.showLayout,
- nativeAction: 'layout',
- ),
- const HarnessCommand('pane.resize', 'Resize panes', ShortcutGroup.panes),
- const HarnessCommand(
- 'pane.split_right',
- 'Split right…',
- ShortcutGroup.panes,
- extraKeys: ['cmd+r'],
- nativeAction: 'splitRight',
- ),
- const HarnessCommand(
- 'pane.split_down',
- 'Split down…',
- ShortcutGroup.panes,
- extraKeys: ['cmd+d'],
- nativeAction: 'splitDown',
- ),
- const HarnessCommand(
- 'pane.reset_sizes',
- 'Reset pane sizes',
- ShortcutGroup.panes,
- ),
- const HarnessCommand(
- 'terminal.find',
- 'Find in the focused terminal',
- ShortcutGroup.navigate,
- action: ShortcutAction.findTerminal,
- nativeAction: 'findTerminal',
- ),
- const HarnessCommand(
- 'terminal.find_next',
- 'Next terminal match',
- ShortcutGroup.navigate,
- action: ShortcutAction.findNext,
- nativeAction: 'findNext',
- repeatable: true,
- ),
- const HarnessCommand(
- 'terminal.find_previous',
- 'Previous terminal match',
- ShortcutGroup.navigate,
- action: ShortcutAction.findPrevious,
- nativeAction: 'findPrevious',
- repeatable: true,
- ),
- const HarnessCommand(
- 'agent.add',
- 'Open Harness',
- ShortcutGroup.actions,
- action: ShortcutAction.addAgent,
- nativeAction: 'addAgent',
- ),
- const HarnessCommand(
- 'agent.new',
- 'New Harness',
- ShortcutGroup.actions,
- action: ShortcutAction.newAgent,
- nativeAction: 'newAgent',
- ),
- const HarnessCommand(
- 'machines.manage',
- 'Open Machines Manager',
- ShortcutGroup.actions,
- nativeAction: 'manageMachines',
- ),
- const HarnessCommand(
- 'machine.link',
- 'Link machine',
- ShortcutGroup.actions,
- nativeAction: 'linkMachine',
- ),
- const HarnessCommand(
- 'project.add',
- 'Add project',
- ShortcutGroup.actions,
- nativeAction: 'addProject',
- ),
- const HarnessCommand(
- 'machines.refresh',
- 'Refresh machines and harnesses',
- ShortcutGroup.actions,
- action: ShortcutAction.reload,
- nativeAction: 'reload',
- ),
- const HarnessCommand(
- 'task.route',
- 'Boss mode: route a task',
- ShortcutGroup.actions,
- action: ShortcutAction.routeTask,
- ),
- const HarnessCommand(
- 'app.settings',
- 'Open Settings',
- ShortcutGroup.actions,
- action: ShortcutAction.showSettings,
- nativeAction: 'settings',
- ),
- const HarnessCommand(
- 'keyboard.help',
- 'Keyboard shortcuts',
- ShortcutGroup.actions,
- action: ShortcutAction.showShortcuts,
- nativeAction: 'showShortcuts',
- ),
- const HarnessCommand(
- 'keyboard.open_config',
- 'Open keyboard config',
- ShortcutGroup.actions,
- nativeAction: 'openKeymap',
- ),
- if (kDebugSurfaceEnabled)
- const HarnessCommand(
- 'app.debug',
- 'Open the debug log',
- ShortcutGroup.actions,
- action: ShortcutAction.showDebug,
- ),
- const HarnessCommand(
- 'picker.next',
- 'Next result',
- ShortcutGroup.navigate,
- extraKeys: ['down', 'ctrl+n', 'ctrl+j'],
- context: KeymapContext.picker,
- repeatable: true,
- ),
- const HarnessCommand(
- 'picker.previous',
- 'Previous result',
- ShortcutGroup.navigate,
- extraKeys: ['up', 'ctrl+p', 'ctrl+k'],
- context: KeymapContext.picker,
- repeatable: true,
- ),
- const HarnessCommand(
- 'picker.accept',
- 'Open the selected result',
- ShortcutGroup.navigate,
- extraKeys: ['enter'],
- context: KeymapContext.picker,
- ),
- const HarnessCommand(
- 'picker.add_here',
- 'Add the selected harness',
- ShortcutGroup.actions,
- extraKeys: ['cmd+enter'],
- context: KeymapContext.picker,
- ),
- const HarnessCommand(
- 'picker.cancel',
- 'Close search',
- ShortcutGroup.navigate,
- extraKeys: ['escape', 'ctrl+g'],
- context: KeymapContext.picker,
- ),
-];
-
-final harnessCommandById = {
- for (final command in harnessCommands) command.id: command,
-};
-final harnessDefaultBindings = [
- for (final command in harnessCommands)
- for (final keys in command.keys)
- KeyBinding(
- keys: keys.split(' ').map(KeyStroke.parse),
- command: command.id,
- context: command.context,
- ),
-];
-final harnessDefaultKeymap = ResolvedKeymap(
- harnessDefaultBindings,
- const KeymapConfig.empty(),
-);
-
-List<String> describeKeyStrokeKeys(KeyStroke stroke) => [
- if (stroke.control) '⌃',
- if (stroke.alt) '⌥',
- if (stroke.shift) '⇧',
- if (stroke.command) '⌘',
- const {
- 'left': '←',
- 'right': '→',
- 'up': '↑',
- 'down': '↓',
- 'enter': '↵',
- 'escape': 'Esc',
- 'tab': '⇥',
- 'space': 'Space',
- 'comma': ',',
- 'period': '.',
- 'slash': '/',
- 'backslash': r'\',
- 'semicolon': ';',
- 'quote': "'",
- 'backquote': '`',
- 'bracketleft': '[',
- 'bracketright': ']',
- 'minus': '-',
- 'equal': '=',
- 'backspace': '⌫',
- 'delete': '⌦',
- }[stroke.key] ??
- stroke.key.toUpperCase(),
-];
-String describeKeyStroke(KeyStroke stroke) =>
- describeKeyStrokeKeys(stroke).join();
-String describeKeyBinding(KeyBinding binding) =>
- binding.keys.map(describeKeyStroke).join(' ');
diff --git a/mobile/lib/shortcuts/keymap_keyboard.dart b/mobile/lib/shortcuts/keymap_keyboard.dart
deleted file mode 100644
index 90b6421af..000000000
--- a/mobile/lib/shortcuts/keymap_keyboard.dart
+++ /dev/null
@@ -1,117 +0,0 @@
-import 'package:flutter/services.dart';
-
-import 'keymap.dart';
-
-/// Canonical logical keys, shared by configured bindings and keyboard events.
-/// This does not guess a QWERTY position for a letter on another layout.
-final _logicalKeys = <LogicalKeyboardKey, String>{
- LogicalKeyboardKey.enter: 'enter',
- LogicalKeyboardKey.numpadEnter: 'enter',
- LogicalKeyboardKey.escape: 'escape',
- LogicalKeyboardKey.arrowLeft: 'left',
- LogicalKeyboardKey.arrowRight: 'right',
- LogicalKeyboardKey.arrowUp: 'up',
- LogicalKeyboardKey.arrowDown: 'down',
- LogicalKeyboardKey.pageUp: 'pageup',
- LogicalKeyboardKey.pageDown: 'pagedown',
- LogicalKeyboardKey.home: 'home',
- LogicalKeyboardKey.end: 'end',
- LogicalKeyboardKey.delete: 'delete',
- LogicalKeyboardKey.backspace: 'backspace',
- LogicalKeyboardKey.tab: 'tab',
- LogicalKeyboardKey.space: 'space',
- LogicalKeyboardKey.comma: 'comma',
- LogicalKeyboardKey.period: 'period',
- LogicalKeyboardKey.slash: 'slash',
- LogicalKeyboardKey.backslash: 'backslash',
- LogicalKeyboardKey.semicolon: 'semicolon',
- LogicalKeyboardKey.quote: 'quote',
- LogicalKeyboardKey.backquote: 'backquote',
- LogicalKeyboardKey.bracketLeft: 'bracketleft',
- LogicalKeyboardKey.bracketRight: 'bracketright',
- LogicalKeyboardKey.minus: 'minus',
- LogicalKeyboardKey.equal: 'equal',
- LogicalKeyboardKey.insert: 'insert',
- for (final key in [
- LogicalKeyboardKey.keyA,
- LogicalKeyboardKey.keyB,
- LogicalKeyboardKey.keyC,
- LogicalKeyboardKey.keyD,
- LogicalKeyboardKey.keyE,
- LogicalKeyboardKey.keyF,
- LogicalKeyboardKey.keyG,
- LogicalKeyboardKey.keyH,
- LogicalKeyboardKey.keyI,
- LogicalKeyboardKey.keyJ,
- LogicalKeyboardKey.keyK,
- LogicalKeyboardKey.keyL,
- LogicalKeyboardKey.keyM,
- LogicalKeyboardKey.keyN,
- LogicalKeyboardKey.keyO,
- LogicalKeyboardKey.keyP,
- LogicalKeyboardKey.keyQ,
- LogicalKeyboardKey.keyR,
- LogicalKeyboardKey.keyS,
- LogicalKeyboardKey.keyT,
- LogicalKeyboardKey.keyU,
- LogicalKeyboardKey.keyV,
- LogicalKeyboardKey.keyW,
- LogicalKeyboardKey.keyX,
- LogicalKeyboardKey.keyY,
- LogicalKeyboardKey.keyZ,
- LogicalKeyboardKey.digit0,
- LogicalKeyboardKey.digit1,
- LogicalKeyboardKey.digit2,
- LogicalKeyboardKey.digit3,
- LogicalKeyboardKey.digit4,
- LogicalKeyboardKey.digit5,
- LogicalKeyboardKey.digit6,
- LogicalKeyboardKey.digit7,
- LogicalKeyboardKey.digit8,
- LogicalKeyboardKey.digit9,
- LogicalKeyboardKey.f1,
- LogicalKeyboardKey.f2,
- LogicalKeyboardKey.f3,
- LogicalKeyboardKey.f4,
- LogicalKeyboardKey.f5,
- LogicalKeyboardKey.f6,
- LogicalKeyboardKey.f7,
- LogicalKeyboardKey.f8,
- LogicalKeyboardKey.f9,
- LogicalKeyboardKey.f10,
- LogicalKeyboardKey.f11,
- LogicalKeyboardKey.f12,
- LogicalKeyboardKey.f13,
- LogicalKeyboardKey.f14,
- LogicalKeyboardKey.f15,
- LogicalKeyboardKey.f16,
- LogicalKeyboardKey.f17,
- LogicalKeyboardKey.f18,
- LogicalKeyboardKey.f19,
- LogicalKeyboardKey.f20,
- LogicalKeyboardKey.f21,
- LogicalKeyboardKey.f22,
- LogicalKeyboardKey.f23,
- LogicalKeyboardKey.f24,
- ])
- key: key.keyLabel.toLowerCase(),
-};
-
-KeyStroke? keyStrokeFor(
- LogicalKeyboardKey key, {
- bool control = false,
- bool alt = false,
- bool command = false,
- bool shift = false,
-}) {
- final name = _logicalKeys[key];
- return name == null
- ? null
- : KeyStroke(
- name,
- control: control,
- alt: alt,
- command: command,
- shift: shift,
- );
-}
diff --git a/mobile/lib/shortcuts/keymap_store.dart b/mobile/lib/shortcuts/keymap_store.dart
deleted file mode 100644
index 63d019016..000000000
--- a/mobile/lib/shortcuts/keymap_store.dart
+++ /dev/null
@@ -1,313 +0,0 @@
-import '../core/host_platform.dart';
-import 'dart:async';
-import 'dart:convert';
-import 'dart:io';
-import 'dart:typed_data';
-
-import 'package:flutter/foundation.dart';
-import 'package:path/path.dart' as p;
-
-import 'keymap.dart';
-
-/// Owns one dotfile. Invalid edits retain the last working keymap, and file
-/// activity never performs work on the keyboard event path.
-class KeymapStore extends ChangeNotifier {
- KeymapStore({
- required this.file,
- required Iterable<KeyBinding> defaults,
- required Set<String> commands,
- this.watchFiles = true,
- this.validate,
- }) : _defaults = List.unmodifiable(defaults),
- _commands = Set.unmodifiable(commands) {
- current = ResolvedKeymap(_defaults, const KeymapConfig.empty());
- validate?.call(current);
- _signature = _describe(current);
- }
-
- static const maximumBytes = 128 * 1024;
- final File file;
- final bool watchFiles;
- final void Function(ResolvedKeymap)? validate;
- final List<KeyBinding> _defaults;
- final Set<String> _commands;
- late ResolvedKeymap current;
- late String _signature;
- int revision = 0;
- String? _readError, _watchError;
- String? get error => _readError ?? _watchError;
- bool _disposed = false;
- int _generation = 0, _watchFailures = 0;
- final _watchers = <String, StreamSubscription<FileSystemEvent>>{};
- Set<String> _targets = {};
- Timer? _debounce;
-
- static String defaultPath({Map<String, String>? environment}) {
- final env = environment ?? Platform.environment;
- final xdg = env['XDG_CONFIG_HOME'];
- var home = env['HOME'] ?? env['USERPROFILE'];
- if (home == null || home.isEmpty) home = containerHome;
- final String root;
- if (xdg != null && p.isAbsolute(xdg)) {
- root = xdg;
- } else if (home != null && home.isNotEmpty) {
- root = p.join(home, '.config');
- } else {
- throw const FileSystemException(
- 'No home directory for keyboard configuration',
- );
- }
- return p.join(root, 'harness', 'keybindings.jsonc');
- }
-
- Future<void> start() async {
- if (watchFiles && !_disposed) await _refreshWatches(_generation);
- await reload();
- }
-
- Future<void> reload({bool fromWatcher = false}) async {
- if (_disposed) return;
- if (!fromWatcher) _watchFailures = 0;
- final generation = ++_generation;
- final priorError = error;
- var changed = false;
- try {
- String source;
- try {
- final bytes = await file
- .openRead(0, maximumBytes + 1)
- .fold(
- BytesBuilder(copy: false),
- (builder, chunk) => builder..add(chunk),
- );
- if (bytes.length > maximumBytes) {
- throw const FormatException('Keyboard config exceeds 128 KiB');
- }
- source = utf8.decode(bytes.takeBytes());
- } on FileSystemException catch (error) {
- if (!const {2, 3}.contains(error.osError?.errorCode)) rethrow;
- source = ''; // A missing file inherits defaults.
- }
- final next = ResolvedKeymap(
- _defaults,
- KeymapConfig.parse(source, commands: _commands),
- );
- validate?.call(next);
- if (_disposed || generation != _generation) return;
- final signature = _describe(next);
- if (_signature != signature) {
- current = next;
- _signature = signature;
- revision++;
- changed = true;
- }
- _readError = null;
- } catch (failure) {
- if (_disposed || generation != _generation) return;
- _readError = 'Keyboard config: $failure';
- }
- if (!_disposed &&
- generation == _generation &&
- (changed || priorError != error)) {
- notifyListeners();
- }
- final priorWatchError = error;
- if (watchFiles && !_disposed) await _refreshWatches(generation);
- if (!_disposed && generation == _generation && priorWatchError != error) {
- notifyListeners();
- }
- }
-
- String _describe(ResolvedKeymap map) => [
- for (final context in KeymapContext.values)
- for (final binding in map.bindingsFor(context))
- '${context.name}:${binding.sequence}:${binding.command}:${binding.custom}',
- ].join('\n');
-
- Future<void> _refreshWatches(int generation) async {
- try {
- await _updateWatches(generation);
- } catch (failure) {
- if (_disposed || generation != _generation) return;
- _watchError = 'Could not watch keyboard config: $failure';
- if (++_watchFailures <= 3) {
- _scheduleReload(Duration(milliseconds: 200 * _watchFailures));
- }
- }
- }
-
- Future<void> _updateWatches(int generation) async {
- final targets = {p.normalize(file.absolute.path)};
- var linkPath = targets.first;
- for (var depth = 0; depth < 8; depth++) {
- try {
- if (await FileSystemEntity.type(linkPath, followLinks: false) !=
- FileSystemEntityType.link) {
- break;
- }
- final destination = await Link(linkPath).target();
- final next = p.normalize(
- p.isAbsolute(destination)
- ? destination
- : p.join(p.dirname(linkPath), destination),
- );
- if (!targets.add(next)) break;
- linkPath = next;
- } on FileSystemException {
- break;
- }
- }
- try {
- targets.add(p.normalize(await file.resolveSymbolicLinks()));
- } on FileSystemException {
- /* Missing file or target. */
- }
- final directories = <String>{};
- for (final target in targets.toList()) {
- var directory = Directory(p.dirname(target));
- final original = directory.path;
- while (!await directory.exists()) {
- final parent = directory.parent;
- if (parent.path == directory.path) break;
- directory = parent;
- }
- // Observe creation of missing config directories without watching an
- // entire filesystem root. No recursive subscriptions are needed.
- if (directory.parent.path != directory.path) {
- final canonical = await directory.resolveSymbolicLinks();
- targets.add(
- p.normalize(
- p.join(canonical, p.relative(target, from: directory.path)),
- ),
- );
- directories.add(canonical);
- }
- if (directory.path == original &&
- directory.parent.parent.path != directory.parent.path) {
- directories.add(await directory.parent.resolveSymbolicLinks());
- }
- }
- if (_disposed || generation != _generation) return;
- _targets = targets;
- for (final path
- in _watchers.keys
- .where((path) => !directories.contains(path))
- .toList()) {
- unawaited(_watchers.remove(path)!.cancel());
- }
- _watchError = directories.isEmpty
- ? 'Create the keyboard config directory to enable automatic reload.'
- : null;
- for (final path in directories) {
- if (_watchers.containsKey(path)) continue;
- late StreamSubscription<FileSystemEvent> subscription;
- void lost(Object? failure) {
- if (_disposed || _watchers[path] != subscription) return;
- _watchers.remove(path);
- unawaited(subscription.cancel());
- _watchError =
- 'Keyboard config watch stopped. Reload to retry${failure == null ? '.' : ': $failure'}';
- notifyListeners();
- if (++_watchFailures <= 3) {
- _scheduleReload(Duration(milliseconds: 200 * _watchFailures));
- }
- }
-
- try {
- subscription = Directory(path).watch().listen(
- (event) {
- if (_related(event.path) ||
- event is FileSystemMoveEvent &&
- event.destination != null &&
- _related(event.destination!)) {
- if (event.isDirectory) {
- final changed = p.normalize(p.absolute(event.path));
- for (final watched
- in _watchers.keys
- .where(
- (path) =>
- path == changed || p.isWithin(changed, path),
- )
- .toList()) {
- unawaited(_watchers.remove(watched)!.cancel());
- }
- }
- _watchFailures = 0;
- _scheduleReload(const Duration(milliseconds: 80));
- }
- },
- onError: (Object failure) => lost(failure),
- onDone: () => lost(null),
- cancelOnError: true,
- );
- _watchers[path] = subscription;
- } catch (failure) {
- _watchError = 'Could not watch keyboard config: $failure';
- }
- }
- }
-
- bool _related(String path) {
- final normalized = p.normalize(p.absolute(path));
- return _targets.any(
- (target) => target == normalized || p.isWithin(normalized, target),
- );
- }
-
- void _scheduleReload(Duration delay) {
- if (_disposed) return;
- _debounce?.cancel();
- _debounce = Timer(delay, () {
- _debounce = null;
- unawaited(reload(fromWatcher: true));
- });
- }
-
- /// Invoked only by the explicit Open Keyboard Config action. Starting the
- /// app never creates a dotfile or rewrites existing user configuration.
- Future<File> ensureFile() async {
- await file.parent.create(recursive: true);
- final handle = await file.open(mode: FileMode.append);
- try {
- await handle.lock(FileLock.exclusive);
- if (await handle.length() == 0) {
- await handle.writeString(
- '''// Harness keyboard overrides. Defaults are inherited.
-// Save this file to apply changes. Invalid edits keep the last working keys.
-// A null command unbinds a key or a sequence prefix.
-// "when" can be "workspace" (default), "terminal", or "picker".
-// Workspace bindings are inherited by the other two contexts.
-{
- "version": 1,
- "bindings": [
- // Example: move search from Command-P to Command-O.
- // { "keys": "cmd+p", "command": null },
- // { "keys": "cmd+o", "command": "swarm.new" },
- ],
-}
-
-// Available command names:
-${(_commands.toList()..sort()).map((id) => '// $id').join('\n')}
-''',
- );
- await handle.flush();
- }
- } finally {
- await handle.close();
- }
- await reload();
- return file;
- }
-
- @override
- void dispose() {
- _disposed = true;
- _generation++;
- _debounce?.cancel();
- for (final watcher in _watchers.values) {
- unawaited(watcher.cancel());
- }
- _watchers.clear();
- super.dispose();
- }
-}
diff --git a/mobile/lib/widgets/terminal_panel.dart b/mobile/lib/widgets/terminal_panel.dart
index 9fb127283..a9fda2c1b 100644
--- a/mobile/lib/widgets/terminal_panel.dart
+++ b/mobile/lib/widgets/terminal_panel.dart
@@ -9,8 +9,6 @@ import 'package:xterm/xterm.dart';
import '../clipboard/native_clipboard.dart';
import '../state/app_state.dart';
-import '../shortcuts/app_keymap.dart';
-import '../shortcuts/keymap.dart';
import '../terminal/terminal_snapshot.dart';
import '../terminal/terminal_binary.dart';
import '../terminal/terminal_font_store.dart';
@@ -1068,144 +1066,138 @@ class _TerminalPanelState extends State<TerminalPanel>
grid.AppTheme.watch(context);
final session = widget.session;
_syncTerminal(session.terminal);
- return KeymapRegion(
- contextKind: KeymapContext.terminal,
- composing: () =>
- _focusNode.hasFocus &&
- _terminalViewKey.currentState?.isComposing == true,
- child: ColoredBox(
- color: grid.AppPalette.windowBg,
- child: Column(
- children: [
- Expanded(
- child: Stack(
- children: [
- Positioned.fill(
- child: MouseRegion(
- onEnter: (event) => _hoverLink(event.position),
- onHover: (event) => _hoverLink(event.position),
- onExit: (_) => _hoverLink(null),
- child: _LinkTooltip(
- link: _hoveredLink,
- modifierDown: _linkModifierDown,
- child: TerminalView(
- session.terminal,
- key: _terminalViewKey,
- controller: _controller,
- autoResize: _live,
- resizeBuffer: false,
- scrollController: _scrollController,
- focusNode: _focusNode,
- autofocus: widget.focused,
- readOnly: !session.acceptsInput,
- // iOS answers Backspace over an empty native buffer
- // with nothing at all (`deleteBackward` in
- // FlutterTextInputPlugin.mm), so a line the keyboard
- // did not type — text typed on the desktop, a voice
- // transcript, a recalled command — could not be
- // rubbed out. xterm keeps a padding for Backspace to
- // eat instead — see test/terminal_ime_input_test.dart.
- //
- // Unconditional: this package builds for iOS and
- // Android only. ⚠️ Lost once already in a merge
- // (cb47ba35 → TestFlight build 11), which is why
- // test/terminal_panel_backspace_test.dart pins it.
- deleteDetection: true,
- theme: terminalThemeFor(
- grid.AppTheme.palette.value,
- terminalThemeStore.value,
- ),
- // ⚠️ **Nothing top or bottom, and that is the whole
- // point of writing it out rather than `all(10)`.**
- // This padding is laid OUTSIDE the scroll view (see
- // xterm's `TerminalView.build`: a `Container` wraps
- // the `Scrollable`), so a vertical inset is a strip
- // the terminal can never draw into — scrolled to
- // either end, the last line stopped 10px short of the
- // edge and the gap travelled with the content rather
- // than staying put like a margin. The sides are
- // margins beside chrome, not under it, and stay.
- padding: const EdgeInsets.symmetric(
- horizontal: Tty.origin,
- ),
- textStyle: terminalFontStore.value,
- // ⚠️ The terminal is NOT app chrome, and the user said so:
- // it carries its own font settings (Settings ▸ Terminal,
- // [terminalFontStore]) precisely because its type is a grid
- // a remote program is drawing into, not a label.
- //
- // Without this, `TerminalView` falls back to
- // `MediaQuery.textScalerOf(context)` (xterm's
- // terminal_view.dart:257), so the app-wide UI size would
- // change the cell size — and a changed cell size is not
- // cosmetic here: it re-derives `rows`, which fires
- // `Terminal.resize` → `session.resize` → a `terminal_resize`
- // frame on the wire and a real SIGWINCH at the far end.
- //
- // Read in `createRenderObject`, not only on update, so this
- // holds from the very first frame — no scaled first paint
- // and no startup resize.
- textScaler: TextScaler.noScaling,
- // ⚠️ PNG alone, and not because other types are rare.
- // The daemon writes what it receives to a file it names
- // `<uuid>.png` outright (`cli/src/lib/pasteDropFiles.ts`),
- // so a JPEG would arrive on the far machine under a name
- // that lies about it. Widening this means teaching the
- // CLI the real type first — and an older CLI, which
- // `terminalImagePasteAvailable` already gates on, would
- // still not know it.
- allowedMimeTypes: const ['image/png'],
- onContentInserted: _onContentInserted,
- onKeyEvent: _onTerminalKey,
- onTapDown: _onTerminalTapDown,
- onTapUp: _onTerminalTapUp,
- // Constant on purpose. The click cursor is applied by
- // [_LinkTooltip]'s own MouseRegion, which repaints
- // without rebuilding this view.
- mouseCursor: SystemMouseCursors.text,
- onSecondaryTapDown: (_, _) => _copyOrPaste(),
-
- onAltBufferScroll: session.scrollViaTmuxCopyMode
- ? (up) => session.sendScrollCommand(up, 1)
- : null,
+ return ColoredBox(
+ color: grid.AppPalette.windowBg,
+ child: Column(
+ children: [
+ Expanded(
+ child: Stack(
+ children: [
+ Positioned.fill(
+ child: MouseRegion(
+ onEnter: (event) => _hoverLink(event.position),
+ onHover: (event) => _hoverLink(event.position),
+ onExit: (_) => _hoverLink(null),
+ child: _LinkTooltip(
+ link: _hoveredLink,
+ modifierDown: _linkModifierDown,
+ child: TerminalView(
+ session.terminal,
+ key: _terminalViewKey,
+ controller: _controller,
+ autoResize: _live,
+ resizeBuffer: false,
+ scrollController: _scrollController,
+ focusNode: _focusNode,
+ autofocus: widget.focused,
+ readOnly: !session.acceptsInput,
+ // iOS answers Backspace over an empty native buffer
+ // with nothing at all (`deleteBackward` in
+ // FlutterTextInputPlugin.mm), so a line the keyboard
+ // did not type — text typed on the desktop, a voice
+ // transcript, a recalled command — could not be
+ // rubbed out. xterm keeps a padding for Backspace to
+ // eat instead — see test/terminal_ime_input_test.dart.
+ //
+ // Unconditional: this package builds for iOS and
+ // Android only. ⚠️ Lost once already in a merge
+ // (cb47ba35 → TestFlight build 11), which is why
+ // test/terminal_panel_backspace_test.dart pins it.
+ deleteDetection: true,
+ theme: terminalThemeFor(
+ grid.AppTheme.palette.value,
+ terminalThemeStore.value,
+ ),
+ // ⚠️ **Nothing top or bottom, and that is the whole
+ // point of writing it out rather than `all(10)`.**
+ // This padding is laid OUTSIDE the scroll view (see
+ // xterm's `TerminalView.build`: a `Container` wraps
+ // the `Scrollable`), so a vertical inset is a strip
+ // the terminal can never draw into — scrolled to
+ // either end, the last line stopped 10px short of the
+ // edge and the gap travelled with the content rather
+ // than staying put like a margin. The sides are
+ // margins beside chrome, not under it, and stay.
+ padding: const EdgeInsets.symmetric(
+ horizontal: Tty.origin,
),
+ textStyle: terminalFontStore.value,
+ // ⚠️ The terminal is NOT app chrome, and the user said so:
+ // it carries its own font settings (Settings ▸ Terminal,
+ // [terminalFontStore]) precisely because its type is a grid
+ // a remote program is drawing into, not a label.
+ //
+ // Without this, `TerminalView` falls back to
+ // `MediaQuery.textScalerOf(context)` (xterm's
+ // terminal_view.dart:257), so the app-wide UI size would
+ // change the cell size — and a changed cell size is not
+ // cosmetic here: it re-derives `rows`, which fires
+ // `Terminal.resize` → `session.resize` → a `terminal_resize`
+ // frame on the wire and a real SIGWINCH at the far end.
+ //
+ // Read in `createRenderObject`, not only on update, so this
+ // holds from the very first frame — no scaled first paint
+ // and no startup resize.
+ textScaler: TextScaler.noScaling,
+ // ⚠️ PNG alone, and not because other types are rare.
+ // The daemon writes what it receives to a file it names
+ // `<uuid>.png` outright (`cli/src/lib/pasteDropFiles.ts`),
+ // so a JPEG would arrive on the far machine under a name
+ // that lies about it. Widening this means teaching the
+ // CLI the real type first — and an older CLI, which
+ // `terminalImagePasteAvailable` already gates on, would
+ // still not know it.
+ allowedMimeTypes: const ['image/png'],
+ onContentInserted: _onContentInserted,
+ onKeyEvent: _onTerminalKey,
+ onTapDown: _onTerminalTapDown,
+ onTapUp: _onTerminalTapUp,
+ // Constant on purpose. The click cursor is applied by
+ // [_LinkTooltip]'s own MouseRegion, which repaints
+ // without rebuilding this view.
+ mouseCursor: SystemMouseCursors.text,
+ onSecondaryTapDown: (_, _) => _copyOrPaste(),
+
+ onAltBufferScroll: session.scrollViaTmuxCopyMode
+ ? (up) => session.sendScrollCommand(up, 1)
+ : null,
),
),
),
- // Both bars tick once per transferred chunk. Listening here
- // keeps that traffic off the pane's own element, so a paste
- // or a preview download cannot stutter the live terminal.
- Positioned(
- left: 14,
- right: 14,
- bottom: 12,
- child: _TransferOverlay(
- session: session,
- preview: _previewProgress,
- onCancelPreview: () => _previewCancellation?.cancel(),
- ),
+ ),
+ // Both bars tick once per transferred chunk. Listening here
+ // keeps that traffic off the pane's own element, so a paste
+ // or a preview download cannot stutter the live terminal.
+ Positioned(
+ left: 14,
+ right: 14,
+ bottom: 12,
+ child: _TransferOverlay(
+ session: session,
+ preview: _previewProgress,
+ onCancelPreview: () => _previewCancellation?.cancel(),
),
- // A long press selects on a phone, and nothing else offered to copy what it
- // selected: `Copy` rides the selection, top right, until used or cleared.
- // Under the phone's title (three rows, laid over the pane's top), not behind it.
- Positioned(
- top: 60,
- right: 8,
- child: ListenableBuilder(
- listenable: _controller,
- builder: (context, _) => _controller.selection == null
- ? const SizedBox.shrink()
- : _SelectionActions(
- onCopy: () => unawaited(_copySelection()),
- onClear: _controller.clearSelection,
- ),
- ),
+ ),
+ // A long press selects on a phone, and nothing else offered to copy what it
+ // selected: `Copy` rides the selection, top right, until used or cleared.
+ // Under the phone's title (three rows, laid over the pane's top), not behind it.
+ Positioned(
+ top: 60,
+ right: 8,
+ child: ListenableBuilder(
+ listenable: _controller,
+ builder: (context, _) => _controller.selection == null
+ ? const SizedBox.shrink()
+ : _SelectionActions(
+ onCopy: () => unawaited(_copySelection()),
+ onClear: _controller.clearSelection,
+ ),
),
- ],
- ),
+ ),
+ ],
),
- ],
- ),
+ ),
+ ],
),
);
}