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.

feat(desktop): change shortcuts from the shortcuts list

bubu-dudue8005207b3cf
diff --git a/desktop/lib/shortcuts/app_shortcuts.dart b/desktop/lib/shortcuts/app_shortcuts.dart
index eb78207cd..a5bf01897 100644
--- a/desktop/lib/shortcuts/app_shortcuts.dart
+++ b/desktop/lib/shortcuts/app_shortcuts.dart
@@ -447,11 +447,30 @@ SingleActivator _platformActivator(SingleActivator keys) {
);
}
+/// ⌥⌘←/→ is the Mac's tab key, as in Safari and Chrome. With Alt as the
+/// prefix it would be Alt+arrows — the shell's word motions and the
+/// browser's Back/Forward — so Linux and the web keep Alt-Shift-brackets.
+const _altPrefixTabShortcuts = <ShortcutAction, SingleActivator>{
+ ShortcutAction.nextSwarm: SingleActivator(
+ LogicalKeyboardKey.bracketRight,
+ alt: true,
+ shift: true,
+ ),
+ ShortcutAction.previousSwarm: SingleActivator(
+ LogicalKeyboardKey.bracketLeft,
+ alt: true,
+ shift: true,
+ ),
+};
+
AppShortcut _platformShortcut(AppShortcut shortcut) => !altWorkspacePrefix
? shortcut
: AppShortcut(
action: shortcut.action,
activator:
+ (shortcut.activator.meta
+ ? _altPrefixTabShortcuts[shortcut.action]
+ : null) ??
(kIsWeb ? null : _linuxAltShortcuts[shortcut.action]) ??
_platformActivator(shortcut.activator),
label: shortcut.label,
@@ -540,9 +559,9 @@ const kSwarmShortcuts = [
AppShortcut(
action: ShortcutAction.nextSwarm,
activator: SingleActivator(
- LogicalKeyboardKey.bracketRight,
+ LogicalKeyboardKey.arrowRight,
meta: true,
- shift: true,
+ alt: true,
),
label: 'Next Tab',
group: ShortcutGroup.navigate,
@@ -550,9 +569,9 @@ const kSwarmShortcuts = [
AppShortcut(
action: ShortcutAction.previousSwarm,
activator: SingleActivator(
- LogicalKeyboardKey.bracketLeft,
+ LogicalKeyboardKey.arrowLeft,
meta: true,
- shift: true,
+ alt: true,
),
label: 'Previous Tab',
group: ShortcutGroup.navigate,
diff --git a/desktop/lib/shortcuts/keymap_edit.dart b/desktop/lib/shortcuts/keymap_edit.dart
new file mode 100644
index 000000000..15d516416
--- /dev/null
+++ b/desktop/lib/shortcuts/keymap_edit.dart
@@ -0,0 +1,218 @@
+import 'dart:convert';
+
+import 'keymap.dart';
+
+/// Changing a shortcut from the app rather than from the dotfile.
+///
+/// Pure: every function here takes the bindings it works on and returns new
+/// ones, so the store owns the file and the dialog owns the keys, and neither
+/// has to agree with the other about how a remap is spelled in JSON.
+
+/// Where a binding written for [context] also answers. Workspace keys are
+/// inherited by every other context, and picker keys by the project menu.
+Iterable<KeymapContext> contextsReachedFrom(KeymapContext context) =>
+ switch (context) {
+ KeymapContext.workspace => KeymapContext.values,
+ KeymapContext.picker => const [
+ KeymapContext.picker,
+ KeymapContext.project,
+ ],
+ KeymapContext.terminal || KeymapContext.project => [context],
+ };
+
+/// A key the app already gives to something else.
+class ShortcutConflict {
+ const ShortcutConflict({required this.label, this.context, this.command});
+
+ /// What the key does today, as the user reads it.
+ final String label;
+
+ /// Null when the key belongs to a whole-app behaviour rather than a context.
+ final KeymapContext? context;
+
+ /// Null for a key the app keeps for the terminal (copy, paste…).
+ final String? command;
+}
+
+/// Keys the terminal keeps for itself — the same set the shortcuts screen
+/// prints under "Kept for the terminal". Taking one for a command would make
+/// copy or paste stop working in every pane.
+List<(KeyStroke, String)> terminalOwnedStrokes({required bool linux}) => [
+ for (final (keys, label)
+ in linux
+ ? const [
+ ('ctrl+shift+c', 'Copy'),
+ ('ctrl+shift+v', 'Paste'),
+ ('ctrl+shift+a', 'Select all'),
+ ('alt+enter', "Newline in the engine's prompt"),
+ ('alt+backspace', 'Delete the previous word'),
+ ('ctrl+c', 'Cancel / interrupt in the agent'),
+ ]
+ : const [
+ ('cmd+c', 'Copy'),
+ ('cmd+v', 'Paste'),
+ ('cmd+a', 'Select all'),
+ ('alt+enter', "Newline in the engine's prompt"),
+ ('alt+backspace', 'Delete the previous word'),
+ ('cmd+backspace', "Delete to the line's start"),
+ ('ctrl+c', 'Cancel / interrupt in the agent'),
+ ])
+ (KeyStroke.parse(keys), label),
+];
+
+/// Who already answers [keys] wherever a binding of [command] in [context]
+/// would, or null when nobody does.
+///
+/// Read from the RESOLVED map, so a default the user unbound is free and a
+/// key they moved somewhere else is taken. A key that starts a longer
+/// sequence, or a sequence whose start is already a shortcut, collides too —
+/// the keymap could not tell the two apart.
+ShortcutConflict? findShortcutConflict(
+ ResolvedKeymap map, {
+ required String command,
+ required KeymapContext context,
+ required List<KeyStroke> keys,
+ required String Function(String command) label,
+ bool linux = false,
+}) {
+ final reached = contextsReachedFrom(context).toList();
+ if (keys.length == 1 &&
+ reached.any(
+ (scope) =>
+ scope == KeymapContext.workspace || scope == KeymapContext.terminal,
+ )) {
+ for (final (stroke, owner) in terminalOwnedStrokes(linux: linux)) {
+ if (stroke == keys.single) return ShortcutConflict(label: owner);
+ }
+ }
+ for (final scope in reached) {
+ for (var length = 1; length <= keys.length; length++) {
+ final match = map.match(scope, keys.sublist(0, length));
+ final owner = match.command;
+ if (owner != null && owner != command) {
+ return ShortcutConflict(
+ label: label(owner),
+ context: scope,
+ command: owner,
+ );
+ }
+ if (length == keys.length && match.prefix) {
+ final longer = map
+ .continuations(scope, keys)
+ .where((binding) => binding.command != command)
+ .firstOrNull;
+ if (longer?.command case final owner?) {
+ return ShortcutConflict(
+ label: label(owner),
+ context: scope,
+ command: owner,
+ );
+ }
+ }
+ }
+ }
+ return null;
+}
+
+/// [custom] after [command] in [context] answers to [stroke] and nothing else.
+///
+/// Its defaults in that context are unbound by sequence, so the old key stops
+/// firing; any earlier remap of the same command is replaced rather than
+/// stacked. An unbind or binding already written for [stroke] in [context] is
+/// dropped — the new row takes that sequence.
+List<KeyBinding> rebindBindings(
+ List<KeyBinding> custom,
+ Iterable<KeyBinding> defaults, {
+ required String command,
+ required KeymapContext context,
+ required KeyStroke stroke,
+}) {
+ final sequence = stroke.toString();
+ final own = defaults
+ .where((b) => b.context == context && b.command == command)
+ .toList();
+ return _deduplicated([
+ for (final binding in custom)
+ if (binding.context != context ||
+ (binding.command != command &&
+ binding.sequence != sequence &&
+ !(binding.command == null &&
+ own.any((d) => d.sequence == binding.sequence))))
+ binding,
+ for (final binding in own)
+ if (binding.sequence != sequence)
+ KeyBinding(
+ keys: binding.keys,
+ command: null,
+ context: context,
+ custom: true,
+ ),
+ KeyBinding(
+ keys: [stroke],
+ command: command,
+ context: context,
+ custom: true,
+ ),
+ ]);
+}
+
+/// [custom] with every remap of [command] in [context] taken out, so its
+/// defaults answer again.
+List<KeyBinding> resetBindings(
+ List<KeyBinding> custom,
+ Iterable<KeyBinding> defaults, {
+ required String command,
+ required KeymapContext context,
+}) {
+ final own = defaults
+ .where((b) => b.context == context && b.command == command)
+ .map((b) => b.sequence)
+ .toSet();
+ return [
+ for (final binding in custom)
+ if (binding.context != context ||
+ (binding.command != command &&
+ !(binding.command == null && own.contains(binding.sequence))))
+ binding,
+ ];
+}
+
+/// The parser refuses two rows for one sequence in one context; the last
+/// write wins, as it would have in the resolved map.
+List<KeyBinding> _deduplicated(List<KeyBinding> bindings) {
+ final byKey = <String, KeyBinding>{};
+ for (final binding in bindings) {
+ final key = '${binding.context.name}:${binding.sequence}';
+ byKey.remove(key);
+ byKey[key] = binding;
+ }
+ return byKey.values.toList();
+}
+
+/// The dotfile's text: the explanation [KeymapStore.ensureFile] writes, the
+/// bindings, and the command names to choose from.
+String keymapFileSource(List<KeyBinding> bindings, Iterable<String> commands) {
+ final rows = [
+ for (final binding in bindings)
+ ' { "keys": ${jsonEncode(binding.sequence)}, '
+ '"command": ${jsonEncode(binding.command)}'
+ '${binding.context == KeymapContext.workspace ? '' : ', "when": ${jsonEncode(binding.context.name)}'} },',
+ ];
+ return '''// 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", "picker", or "project".
+// Workspace bindings are inherited by the other contexts.
+{
+ "version": 1,
+ "bindings": [
+${rows.isEmpty ? ''' // Example: move New Tab from Command-T to Command-O.
+ // { "keys": "cmd+t", "command": null },
+ // { "keys": "cmd+o", "command": "swarm.new" },
+''' : '${rows.join('\n')}\n'} ],
+}
+
+// Available command names:
+${(commands.toList()..sort()).map((id) => '// $id').join('\n')}
+''';
+}
diff --git a/desktop/lib/shortcuts/keymap_keyboard.dart b/desktop/lib/shortcuts/keymap_keyboard.dart
index c4941e211..9aec8c11d 100644
--- a/desktop/lib/shortcuts/keymap_keyboard.dart
+++ b/desktop/lib/shortcuts/keymap_keyboard.dart
@@ -97,6 +97,33 @@ final _logicalKeys = <LogicalKeyboardKey, String>{
key: key.keyLabel.toLowerCase(),
};
+/// macOS reports the SHIFTED character as the logical key of a symbol: ⇧⌘]
+/// arrives as `}`, not `]`. The binding names the key, and the shift is
+/// already in the stroke, so read the shifted symbol back as the key under it
+/// (US positions, the only ones the binding names can spell).
+final _shiftedKeys = <LogicalKeyboardKey, String>{
+ LogicalKeyboardKey.braceLeft: 'bracketleft',
+ LogicalKeyboardKey.braceRight: 'bracketright',
+ LogicalKeyboardKey.bar: 'backslash',
+ LogicalKeyboardKey.colon: 'semicolon',
+ LogicalKeyboardKey.less: 'comma',
+ LogicalKeyboardKey.greater: 'period',
+ LogicalKeyboardKey.question: 'slash',
+ LogicalKeyboardKey.tilde: 'backquote',
+ LogicalKeyboardKey.underscore: 'minus',
+ LogicalKeyboardKey.add: 'equal',
+ LogicalKeyboardKey.exclamation: '1',
+ LogicalKeyboardKey.at: '2',
+ LogicalKeyboardKey.numberSign: '3',
+ LogicalKeyboardKey.dollar: '4',
+ LogicalKeyboardKey.percent: '5',
+ LogicalKeyboardKey.caret: '6',
+ LogicalKeyboardKey.ampersand: '7',
+ LogicalKeyboardKey.asterisk: '8',
+ LogicalKeyboardKey.parenthesisLeft: '9',
+ LogicalKeyboardKey.parenthesisRight: '0',
+};
+
KeyStroke? keyStrokeFor(
LogicalKeyboardKey key, {
bool control = false,
@@ -104,7 +131,7 @@ KeyStroke? keyStrokeFor(
bool command = false,
bool shift = false,
}) {
- final name = _logicalKeys[key];
+ final name = _logicalKeys[key] ?? (shift ? _shiftedKeys[key] : null);
return name == null
? null
: KeyStroke(
diff --git a/desktop/lib/shortcuts/keymap_store.dart b/desktop/lib/shortcuts/keymap_store.dart
index 70baff20f..46effa0ff 100644
--- a/desktop/lib/shortcuts/keymap_store.dart
+++ b/desktop/lib/shortcuts/keymap_store.dart
@@ -9,6 +9,7 @@ import 'package:flutter/foundation.dart';
import 'package:path/path.dart' as p;
import 'keymap.dart';
+import 'keymap_edit.dart';
/// Owns one dotfile. Invalid edits retain the last working keymap, and file
/// activity never performs work on the keyboard event path.
@@ -76,29 +77,16 @@ class KeymapStore extends ChangeNotifier {
if (_disposed || generation != _generation) return;
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),
- );
+ final source = await _readSource();
+ final config = KeymapConfig.parse(source, commands: _commands);
+ final next = ResolvedKeymap(_defaults, config);
validate?.call(next);
if (_disposed || generation != _generation) return;
final signature = _describe(next);
+ if (hasOverrides != config.bindings.isNotEmpty) {
+ hasOverrides = config.bindings.isNotEmpty;
+ changed = true;
+ }
if (_signature != signature) {
current = next;
_signature = signature;
@@ -117,6 +105,81 @@ class KeymapStore extends ChangeNotifier {
}
}
+ Future<String> _readSource() async {
+ 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');
+ }
+ return utf8.decode(bytes.takeBytes());
+ } on FileSystemException catch (error) {
+ if (!const {2, 3}.contains(error.osError?.errorCode)) rethrow;
+ return ''; // A missing file inherits defaults.
+ }
+ }
+
+ /// Whether the file changes any key — a remap or an unbind. The resolved map
+ /// cannot say: an unbound default simply is not in it.
+ bool hasOverrides = false;
+
+ Future<void> _editing = Future.value();
+
+ /// Puts every key back to its default by emptying the file's bindings.
+ ///
+ /// Unlike [editBindings] this does not need the file to parse: resetting is
+ /// how a person gets out of a config they broke. Anything other than the
+ /// file this app writes is copied to `.bak` first.
+ Future<void> resetAll() {
+ final edit = _editing.then((_) async {
+ final source = await _readSource();
+ final blank = keymapFileSource(const [], _commands);
+ if (source.trim().isNotEmpty && source != blank) {
+ await File('${file.path}.bak').writeAsString(source, flush: true);
+ await file.writeAsString(blank, flush: true);
+ }
+ await reload();
+ });
+ _editing = edit.catchError((Object _) {});
+ return edit;
+ }
+
+ /// Rewrites the dotfile with [change] applied to its bindings, then reloads.
+ ///
+ /// The file is read again rather than trusting [current], so an edit made
+ /// in an editor a moment ago is kept. Nothing is written when that file does
+ /// not parse or the result would not resolve — the error is thrown for the
+ /// caller to show. Comments a person wrote into the file are not carried
+ /// into the rewrite, so a hand-edited file is copied to `.bak` first.
+ Future<void> editBindings(
+ List<KeyBinding> Function(
+ List<KeyBinding> custom,
+ List<KeyBinding> defaults,
+ )
+ change,
+ ) {
+ final edit = _editing.then((_) async {
+ final source = await _readSource();
+ final config = KeymapConfig.parse(source, commands: _commands);
+ final next = change(config.bindings, _defaults);
+ final resolved = ResolvedKeymap(_defaults, KeymapConfig(next));
+ validate?.call(resolved);
+ await file.parent.create(recursive: true);
+ if (source.trim().isNotEmpty &&
+ source != keymapFileSource(config.bindings, _commands)) {
+ await File('${file.path}.bak').writeAsString(source, flush: true);
+ }
+ await file.writeAsString(keymapFileSource(next, _commands), flush: true);
+ await reload();
+ });
+ _editing = edit.catchError((Object _) {});
+ return edit;
+ }
+
String _describe(ResolvedKeymap map) => [
for (final context in KeymapContext.values)
for (final binding in map.bindingsFor(context))
@@ -270,25 +333,7 @@ class KeymapStore extends ChangeNotifier {
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", "picker", or "project".
-// Workspace bindings are inherited by the other contexts.
-{
- "version": 1,
- "bindings": [
- // Example: move New Tab from Command-T to Command-O.
- // { "keys": "cmd+t", "command": null },
- // { "keys": "cmd+o", "command": "swarm.new" },
- ],
-}
-
-// Available command names:
-${(_commands.toList()..sort()).map((id) => '// $id').join('\n')}
-''',
- );
+ await handle.writeString(keymapFileSource(const [], _commands));
await handle.flush();
}
} finally {
diff --git a/desktop/lib/shortcuts/shortcut_recorder.dart b/desktop/lib/shortcuts/shortcut_recorder.dart
new file mode 100644
index 000000000..bc6fd5c31
--- /dev/null
+++ b/desktop/lib/shortcuts/shortcut_recorder.dart
@@ -0,0 +1,388 @@
+import 'dart:async';
+
+import 'package:flutter/foundation.dart';
+import 'package:flutter/material.dart';
+import 'package:flutter/services.dart';
+
+import '../shared/theme/app_theme.dart' as grid;
+import '../shared/widgets/app_dialog.dart';
+import '../widgets/desktop_chrome.dart';
+import '../widgets/desktop_prompt_surface.dart';
+import 'app_keymap.dart';
+import 'key_cap.dart';
+import 'keyboard_practice.dart';
+import 'keymap.dart';
+import 'keymap_commands.dart';
+import 'keymap_edit.dart';
+import 'keymap_host.dart';
+import 'keymap_keyboard.dart';
+
+/// A row of the shortcuts list, turned into the place its key is changed.
+///
+/// The keys pressed here are recorded, never run: the recorder is its own
+/// [KeymapHost] with nothing enabled, which is how shortcut practice keeps
+/// the workspace from answering ⌘T with a new tab while you are typing it.
+///
+/// Return saves, Escape cancels and Tab leaves, so those three are not
+/// recordable on their own — with a modifier they are.
+class ShortcutRecorder extends StatefulWidget {
+ const ShortcutRecorder({
+ super.key,
+ required this.keymap,
+ required this.lesson,
+ required this.onClose,
+ });
+ final AppKeymap keymap;
+ final KeyboardLesson lesson;
+ final VoidCallback onClose;
+
+ @override
+ State<ShortcutRecorder> createState() => _ShortcutRecorderState();
+}
+
+/// Keys that may stand alone in a picker: they move or accept, and a search
+/// field has no text use for them. Everywhere else a lone key would be typed
+/// into the terminal or the query, so it needs ⌘, ⌃ or ⌥.
+const _pickerBareKeys = {'up', 'down', 'pageup', 'pagedown'};
+
+String contextPhrase(KeymapContext context) => switch (context) {
+ KeymapContext.workspace => '',
+ KeymapContext.terminal => ' in agent input',
+ KeymapContext.picker => ' in search',
+ KeymapContext.project => ' in the project menu',
+};
+
+class _ShortcutRecorderState extends State<ShortcutRecorder> {
+ late final _capture = FocusNode(
+ debugLabel: 'Record a shortcut',
+ onKeyEvent: _key,
+ );
+ KeyStroke? _stroke;
+ String? _problem;
+ bool _saving = false;
+
+ String get _command => widget.lesson.command;
+ KeymapContext get _context => widget.lesson.context;
+ bool get _linux => !kIsWeb && defaultTargetPlatform == TargetPlatform.linux;
+ bool get _customized =>
+ widget.lesson.bindings.any((binding) => binding.custom) ||
+ widget.keymap.current
+ .bindingsFor(_context)
+ .every((b) => b.command != _command) &&
+ harnessDefaultBindings.any(
+ (b) => b.context == _context && b.command == _command,
+ );
+
+ @override
+ void initState() {
+ super.initState();
+ WidgetsBinding.instance.addPostFrameCallback((_) {
+ if (mounted) _capture.requestFocus();
+ });
+ }
+
+ @override
+ void dispose() {
+ _capture.dispose();
+ super.dispose();
+ }
+
+ String _label(String command) =>
+ harnessCommandById[command]?.label ?? command;
+
+ String? _check(KeyStroke stroke) {
+ final modified = stroke.command || stroke.control || stroke.alt;
+ final function = RegExp(r'^f\d+$').hasMatch(stroke.key);
+ if (!modified &&
+ !function &&
+ !(_context.isPicker && _pickerBareKeys.contains(stroke.key))) {
+ return 'Add ${_linux ? 'Ctrl or Alt' : '⌘, ⌃ or ⌥'} — a key on its own '
+ 'would type instead.';
+ }
+ if (widget.lesson.bindings.length == 1 &&
+ widget.lesson.bindings.single.keys.length == 1 &&
+ widget.lesson.bindings.single.keys.single == stroke) {
+ return null;
+ }
+ final conflict = findShortcutConflict(
+ widget.keymap.current,
+ command: _command,
+ context: _context,
+ keys: [stroke],
+ label: _label,
+ linux: _linux,
+ );
+ if (conflict == null) return null;
+ final where = conflict.context == null
+ ? ' in the terminal'
+ : contextPhrase(conflict.context!);
+ return '${describeKeyStroke(stroke)} is already used by '
+ '${conflict.label}$where.';
+ }
+
+ KeyEventResult _key(FocusNode node, KeyEvent event) {
+ if (event is KeyRepeatEvent) return KeyEventResult.handled;
+ if (event is! KeyDownEvent) return KeyEventResult.ignored;
+ final stroke = keyStrokeForEvent(event);
+ if (stroke == null) return KeyEventResult.handled; // A modifier alone.
+ final bare = !stroke.command && !stroke.control && !stroke.alt;
+ if (bare && !stroke.shift && stroke.key == 'escape') {
+ widget.onClose();
+ return KeyEventResult.handled;
+ }
+ if (bare && stroke.key == 'tab') return KeyEventResult.ignored;
+ if (bare && !stroke.shift && stroke.key == 'enter') {
+ unawaited(_save());
+ return KeyEventResult.handled;
+ }
+ setState(() {
+ _stroke = stroke;
+ _problem = _check(stroke);
+ });
+ return KeyEventResult.handled;
+ }
+
+ bool get _canSave => _stroke != null && _problem == null && !_saving;
+
+ Future<void> _save() async {
+ final stroke = _stroke;
+ if (!_canSave || stroke == null) return;
+ await _write(
+ (custom, defaults) => rebindBindings(
+ custom,
+ defaults,
+ command: _command,
+ context: _context,
+ stroke: stroke,
+ ),
+ );
+ }
+
+ Future<void> _reset() async {
+ final current = widget.keymap.current;
+ for (final binding in harnessDefaultBindings.where(
+ (b) => b.context == _context && b.command == _command,
+ )) {
+ final conflict = findShortcutConflict(
+ current,
+ command: _command,
+ context: _context,
+ keys: binding.keys,
+ label: _label,
+ linux: _linux,
+ );
+ if (conflict != null) {
+ setState(
+ () => _problem =
+ 'The default, ${describeKeyBinding(binding)}, is now used by '
+ '${conflict.label}${conflict.context == null ? '' : contextPhrase(conflict.context!)}. '
+ 'Change that one first.',
+ );
+ _capture.requestFocus();
+ return;
+ }
+ }
+ await _write(
+ (custom, defaults) =>
+ resetBindings(custom, defaults, command: _command, context: _context),
+ );
+ }
+
+ Future<void> _write(
+ List<KeyBinding> Function(List<KeyBinding>, List<KeyBinding>) change,
+ ) async {
+ final store = widget.keymap.store;
+ if (store == null) return;
+ setState(() => _saving = true);
+ try {
+ await store.editBindings(change);
+ if (mounted) widget.onClose();
+ } catch (error) {
+ if (!mounted) return;
+ setState(() {
+ _saving = false;
+ _problem =
+ 'Could not save: ${error is FormatException ? error.message : error}';
+ });
+ _capture.requestFocus();
+ }
+ }
+
+ @override
+ Widget build(BuildContext context) {
+ grid.AppTheme.watch(context);
+ final stroke = _stroke;
+ final error = Theme.of(context).colorScheme.error;
+ final focused = _capture.hasFocus;
+ return KeymapHost(
+ keymap: widget.keymap,
+ enabled: () => false,
+ actions: const {},
+ child: Padding(
+ padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 8),
+ child: Column(
+ crossAxisAlignment: CrossAxisAlignment.stretch,
+ children: [
+ Row(
+ children: [
+ Expanded(
+ child: Text(
+ widget.lesson.label,
+ style: DesktopChrome.control(),
+ ),
+ ),
+ const SizedBox(width: 12),
+ Semantics(
+ label:
+ 'New shortcut for ${widget.lesson.label}. Press the keys.',
+ value: stroke == null ? null : describeKeyStroke(stroke),
+ child: Focus(
+ focusNode: _capture,
+ onFocusChange: (_) => setState(() {}),
+ child: GestureDetector(
+ onTap: _capture.requestFocus,
+ child: Container(
+ key: const ValueKey('shortcut-recorder'),
+ constraints: const BoxConstraints(minWidth: 150),
+ padding: const EdgeInsets.symmetric(
+ horizontal: 10,
+ vertical: 6,
+ ),
+ decoration: BoxDecoration(
+ color: DesktopChrome.field,
+ borderRadius: BorderRadius.circular(
+ DesktopChrome.controlRadius,
+ ),
+ border: Border.all(
+ color: _problem != null && stroke != null
+ ? error
+ : focused
+ ? DesktopChrome.focusRing
+ : DesktopChrome.rim,
+ width: 1.5,
+ ),
+ ),
+ child: stroke == null
+ ? Text(
+ 'Press keys…',
+ style: DesktopChrome.control(
+ color: DesktopChrome.muted,
+ ),
+ )
+ : KeyChordView(
+ chords: [describeKeyStrokeKeys(stroke)],
+ textStyle: DesktopChrome.control(),
+ ),
+ ),
+ ),
+ ),
+ ),
+ ],
+ ),
+ const SizedBox(height: 8),
+ Semantics(
+ liveRegion: true,
+ child: Text(
+ _problem ??
+ (stroke == null
+ ? 'Return saves · Esc cancels'
+ : '${describeKeyStroke(stroke)} is free.'),
+ style: DesktopChrome.metadata(
+ color: _problem == null ? DesktopChrome.muted : error,
+ ),
+ ),
+ ),
+ const SizedBox(height: 4),
+ Wrap(
+ alignment: WrapAlignment.end,
+ spacing: 4,
+ runSpacing: 4,
+ children: [
+ if (_customized)
+ TextButton(
+ onPressed: _saving ? null : _reset,
+ child: const Text('Reset to default'),
+ ),
+ TextButton(
+ onPressed: _saving ? null : widget.onClose,
+ child: const Text('Cancel'),
+ ),
+ FilledButton(
+ onPressed: _canSave ? _save : null,
+ child: Text(_saving ? 'Saving…' : 'Save'),
+ ),
+ ],
+ ),
+ ],
+ ),
+ ),
+ );
+ }
+}
+
+/// "Reset all shortcuts?" before every remap is dropped. True only for the
+/// button that says so; Cancel holds the focus, so a stray Return keeps them.
+Future<bool> confirmResetAllShortcuts(BuildContext context) async =>
+ await showAppDialog<bool>(
+ context: context,
+ builder: (_) => const _ResetAllPrompt(),
+ ) ??
+ false;
+
+class _ResetAllPrompt extends StatefulWidget {
+ const _ResetAllPrompt();
+
+ @override
+ State<_ResetAllPrompt> createState() => _ResetAllPromptState();
+}
+
+class _ResetAllPromptState extends State<_ResetAllPrompt> {
+ final _cancel = FocusNode(debugLabel: 'Cancel reset all shortcuts');
+
+ @override
+ void initState() {
+ super.initState();
+ WidgetsBinding.instance.addPostFrameCallback((_) {
+ if (mounted && ModalRoute.of(context)?.isCurrent != false) {
+ _cancel.requestFocus();
+ }
+ });
+ }
+
+ @override
+ void dispose() {
+ _cancel.dispose();
+ super.dispose();
+ }
+
+ @override
+ Widget build(BuildContext context) {
+ grid.AppTheme.watch(context);
+ return DesktopPromptSurface(
+ body: DesktopPromptScrollBody(
+ child: Column(
+ crossAxisAlignment: CrossAxisAlignment.stretch,
+ children: [
+ Text('Reset all shortcuts?', style: DesktopChrome.heading()),
+ const SizedBox(height: DesktopChrome.groupGap),
+ Text(
+ 'Every shortcut you changed goes back to its default.',
+ style: DesktopChrome.text(size: 13),
+ ),
+ ],
+ ),
+ ),
+ actions: [
+ TextButton(
+ focusNode: _cancel,
+ onPressed: () => Navigator.pop(context, false),
+ child: const Text('Cancel'),
+ ),
+ FilledButton(
+ onPressed: () => Navigator.pop(context, true),
+ child: const Text('Reset all'),
+ ),
+ ],
+ );
+ }
+}
diff --git a/desktop/lib/shortcuts/shortcuts_browser.dart b/desktop/lib/shortcuts/shortcuts_browser.dart
index db5a719f2..a7c2372f6 100644
--- a/desktop/lib/shortcuts/shortcuts_browser.dart
+++ b/desktop/lib/shortcuts/shortcuts_browser.dart
@@ -12,6 +12,7 @@ import 'key_cap.dart';
import 'keymap_commands.dart';
import 'keymap_settings.dart';
import 'keyboard_practice.dart';
+import 'shortcut_recorder.dart';
/// Searchable help built from the same resolved bindings that handle input.
/// Shared by the shortcut dialog and Settings; no separate shortcut catalog.
@@ -123,12 +124,57 @@ class _ShortcutsBrowserState extends State<ShortcutsBrowser> {
if (_scroll.hasClients) _scroll.jumpTo(0);
}
- Widget _lessonRow(KeyboardLesson lesson) => _ShortcutBrowserRow(
- key: _rowKeys.putIfAbsent(lesson.id, GlobalKey.new),
- lesson: lesson,
- selected: _cursor >= 0 && _visible[_cursor].id == lesson.id,
- onTap: () => _practice(lesson),
- );
+ /// The row whose key is being changed, by command and context — not by
+ /// [KeyboardLesson.id], which spells the keys and so changes on save.
+ String? _editing;
+
+ String _editKey(KeyboardLesson lesson) =>
+ '${lesson.context.name}:${lesson.command}';
+
+ void _closeEditor() {
+ setState(() => _editing = null);
+ _input.requestFocus();
+ }
+
+ Future<void> _resetAll() async {
+ final store = _keymap.store;
+ if (store == null || !await confirmResetAllShortcuts(context)) return;
+ if (!mounted) return;
+ setState(() => _editing = null);
+ try {
+ await store.resetAll();
+ } catch (error) {
+ if (mounted) {
+ ScaffoldMessenger.maybeOf(context)?.showSnackBar(
+ SnackBar(content: Text('Couldn’t reset shortcuts. $error')),
+ );
+ }
+ }
+ if (mounted) _input.requestFocus();
+ }
+
+ Widget _lessonRow(KeyboardLesson lesson) {
+ final keymap = _keymap;
+ final editable =
+ keymap.store != null && harnessCommandById.containsKey(lesson.command);
+ if (editable && _editing == _editKey(lesson)) {
+ return ShortcutRecorder(
+ key: _rowKeys.putIfAbsent(lesson.id, GlobalKey.new),
+ keymap: keymap,
+ lesson: lesson,
+ onClose: _closeEditor,
+ );
+ }
+ return _ShortcutBrowserRow(
+ key: _rowKeys.putIfAbsent(lesson.id, GlobalKey.new),
+ lesson: lesson,
+ selected: _cursor >= 0 && _visible[_cursor].id == lesson.id,
+ onTap: () => _practice(lesson),
+ onEdit: editable
+ ? () => setState(() => _editing = _editKey(lesson))
+ : null,
+ );
+ }
@override
Widget build(BuildContext context) {
@@ -187,6 +233,13 @@ class _ShortcutsBrowserState extends State<ShortcutsBrowser> {
),
),
),
+ if (keymap.store case final store?
+ when store.hasOverrides || keymap.error != null)
+ TextButton(
+ key: const ValueKey('shortcuts-reset-all'),
+ onPressed: _resetAll,
+ child: const Text('Reset all'),
+ ),
if (keymap.store != null)
IconButton(
tooltip: 'Edit keyboard shortcuts',
@@ -386,13 +439,37 @@ class _ShortcutBrowserRow extends StatelessWidget {
required this.lesson,
required this.selected,
required this.onTap,
+ this.onEdit,
});
final KeyboardLesson lesson;
final bool selected;
final VoidCallback onTap;
+ /// Null where keys cannot be changed from here: the browser build, and the
+ /// practice-only rows that are not app commands.
+ final VoidCallback? onEdit;
+
@override
Widget build(BuildContext context) {
+ final row = _practiceButton(context);
+ final edit = onEdit;
+ if (edit == null) return row;
+ return Row(
+ children: [
+ Expanded(child: row),
+ IconButton(
+ key: ValueKey(
+ 'shortcut-edit-${lesson.context.name}:${lesson.command}',
+ ),
+ tooltip: 'Change shortcut',
+ icon: Icon(AppIcons.pencil, size: 16, color: DesktopChrome.muted),
+ onPressed: edit,
+ ),
+ ],
+ );
+ }
+
+ Widget _practiceButton(BuildContext context) {
final chords = [
for (final binding in lesson.bindings)
binding.keys.length == 1
diff --git a/desktop/test/keymap_dispatch_test.dart b/desktop/test/keymap_dispatch_test.dart
index 774eb65e1..0ff51c60f 100644
--- a/desktop/test/keymap_dispatch_test.dart
+++ b/desktop/test/keymap_dispatch_test.dart
@@ -204,4 +204,26 @@ void main() {
expect(keyStrokeFor(LogicalKeyboardKey.shiftLeft, shift: true), isNull);
},
);
+
+ test('macOS shifted symbols read as the key under them', () {
+ // A real ⇧⌘] on a Mac arrives with `}` as its logical key.
+ expect(
+ keyStrokeFor(LogicalKeyboardKey.braceRight, command: true, shift: true),
+ KeyStroke.parse('cmd+shift+]'),
+ );
+ expect(
+ keyStrokeFor(LogicalKeyboardKey.braceLeft, command: true, shift: true),
+ KeyStroke.parse('cmd+shift+['),
+ );
+ expect(
+ keyStrokeFor(LogicalKeyboardKey.question, command: true, shift: true),
+ KeyStroke.parse('cmd+shift+/'),
+ );
+ expect(
+ keyStrokeFor(LogicalKeyboardKey.exclamation, command: true, shift: true),
+ KeyStroke.parse('cmd+shift+1'),
+ );
+ // Without shift a brace is not a key the bindings can name.
+ expect(keyStrokeFor(LogicalKeyboardKey.braceRight, command: true), isNull);
+ });
}
diff --git a/desktop/test/keymap_edit_test.dart b/desktop/test/keymap_edit_test.dart
new file mode 100644
index 000000000..6355e3e43
--- /dev/null
+++ b/desktop/test/keymap_edit_test.dart
@@ -0,0 +1,256 @@
+import 'package:flutter_test/flutter_test.dart';
+import 'package:harness/shortcuts/keymap.dart';
+import 'package:harness/shortcuts/keymap_edit.dart';
+
+KeyBinding binding(
+ String sequence,
+ String? command, {
+ KeymapContext context = KeymapContext.workspace,
+ bool custom = false,
+}) => KeyBinding(
+ keys: sequence.split(' ').map(KeyStroke.parse),
+ command: command,
+ context: context,
+ custom: custom,
+);
+
+final defaults = [
+ binding('cmd+t', 'swarm.new'),
+ binding('cmd+p', 'search.open'),
+ binding('cmd+k cmd+s', 'keyboard.help'),
+ binding('cmd+j', 'picker.preview', context: KeymapContext.picker),
+];
+
+const commands = {
+ 'swarm.new',
+ 'search.open',
+ 'keyboard.help',
+ 'picker.preview',
+ 'pane.zoom',
+};
+
+ResolvedKeymap resolve(List<KeyBinding> custom) =>
+ ResolvedKeymap(defaults, KeymapConfig(custom));
+
+ShortcutConflict? conflict(
+ List<KeyBinding> custom,
+ String command,
+ String keys, {
+ KeymapContext context = KeymapContext.workspace,
+ bool linux = false,
+}) => findShortcutConflict(
+ resolve(custom),
+ command: command,
+ context: context,
+ keys: keys.split(' ').map(KeyStroke.parse).toList(),
+ label: (id) => id,
+ linux: linux,
+);
+
+void main() {
+ group('findShortcutConflict', () {
+ test('a key another command owns is taken', () {
+ final found = conflict(const [], 'pane.zoom', 'cmd+t');
+ expect(found?.command, 'swarm.new');
+ expect(found?.context, KeymapContext.workspace);
+ });
+
+ test('a free key and the command\'s own key are not', () {
+ expect(conflict(const [], 'pane.zoom', 'cmd+e'), isNull);
+ expect(conflict(const [], 'swarm.new', 'cmd+t'), isNull);
+ });
+
+ test('a key that starts a longer sequence is taken', () {
+ expect(
+ conflict(const [], 'pane.zoom', 'cmd+k')?.command,
+ 'keyboard.help',
+ );
+ });
+
+ test('a workspace key is checked where a picker overrides it', () {
+ final found = conflict(const [], 'pane.zoom', 'cmd+j');
+ expect(found?.command, 'picker.preview');
+ expect(found?.context, KeymapContext.picker);
+ });
+
+ test('a picker key does not collide with the terminal', () {
+ expect(
+ conflict(
+ const [],
+ 'picker.preview',
+ 'cmd+e',
+ context: KeymapContext.picker,
+ ),
+ isNull,
+ );
+ });
+
+ test('a default the user unbound is free again', () {
+ expect(
+ conflict([binding('cmd+t', null, custom: true)], 'pane.zoom', 'cmd+t'),
+ isNull,
+ );
+ });
+
+ test('a key a remap moved elsewhere is taken by its new owner', () {
+ final found = conflict(
+ [binding('cmd+e', 'search.open', custom: true)],
+ 'pane.zoom',
+ 'cmd+e',
+ );
+ expect(found?.command, 'search.open');
+ });
+
+ test('copy and paste stay with the terminal', () {
+ expect(conflict(const [], 'pane.zoom', 'cmd+c')?.label, 'Copy');
+ expect(conflict(const [], 'pane.zoom', 'cmd+c')?.command, isNull);
+ expect(
+ conflict(const [], 'pane.zoom', 'ctrl+shift+v', linux: true)?.label,
+ 'Paste',
+ );
+ expect(
+ conflict(
+ const [],
+ 'picker.preview',
+ 'cmd+c',
+ context: KeymapContext.picker,
+ ),
+ isNull,
+ );
+ });
+ });
+
+ group('rebindBindings', () {
+ test('moves a command to a new key and unbinds its default', () {
+ final next = rebindBindings(
+ const [],
+ defaults,
+ command: 'swarm.new',
+ context: KeymapContext.workspace,
+ stroke: KeyStroke.parse('cmd+o'),
+ );
+ final map = resolve(next);
+ expect(
+ map.match(KeymapContext.workspace, [KeyStroke.parse('cmd+o')]).command,
+ 'swarm.new',
+ );
+ expect(
+ map.match(KeymapContext.workspace, [KeyStroke.parse('cmd+t')]).matched,
+ isFalse,
+ );
+ });
+
+ test('a second change replaces the first instead of stacking', () {
+ final first = rebindBindings(
+ const [],
+ defaults,
+ command: 'swarm.new',
+ context: KeymapContext.workspace,
+ stroke: KeyStroke.parse('cmd+o'),
+ );
+ final second = rebindBindings(
+ first,
+ defaults,
+ command: 'swarm.new',
+ context: KeymapContext.workspace,
+ stroke: KeyStroke.parse('cmd+y'),
+ );
+ final map = resolve(second);
+ expect(
+ map.match(KeymapContext.workspace, [KeyStroke.parse('cmd+o')]).matched,
+ isFalse,
+ );
+ expect(
+ map
+ .bindingsFor(KeymapContext.workspace)
+ .where((b) => b.command == 'swarm.new'),
+ hasLength(1),
+ );
+ });
+
+ test('taking back the default key leaves no unbind for it', () {
+ final moved = rebindBindings(
+ const [],
+ defaults,
+ command: 'swarm.new',
+ context: KeymapContext.workspace,
+ stroke: KeyStroke.parse('cmd+o'),
+ );
+ final back = rebindBindings(
+ moved,
+ defaults,
+ command: 'swarm.new',
+ context: KeymapContext.workspace,
+ stroke: KeyStroke.parse('cmd+t'),
+ );
+ expect(back.where((b) => b.command == null), isEmpty);
+ expect(
+ resolve(back)
+ .match(KeymapContext.workspace, [KeyStroke.parse('cmd+t')])
+ .command,
+ 'swarm.new',
+ );
+ });
+
+ test('keeps the user\'s other remaps', () {
+ final next = rebindBindings(
+ [binding('cmd+e', 'search.open', custom: true)],
+ defaults,
+ command: 'swarm.new',
+ context: KeymapContext.workspace,
+ stroke: KeyStroke.parse('cmd+o'),
+ );
+ expect(
+ resolve(next)
+ .match(KeymapContext.workspace, [KeyStroke.parse('cmd+e')])
+ .command,
+ 'search.open',
+ );
+ });
+ });
+
+ test('resetBindings brings the default back', () {
+ final moved = rebindBindings(
+ const [],
+ defaults,
+ command: 'swarm.new',
+ context: KeymapContext.workspace,
+ stroke: KeyStroke.parse('cmd+o'),
+ );
+ final reset = resetBindings(
+ moved,
+ defaults,
+ command: 'swarm.new',
+ context: KeymapContext.workspace,
+ );
+ expect(reset, isEmpty);
+ });
+
+ test('the written file parses back to the same bindings', () {
+ final bindings = [
+ binding('cmd+t', null, custom: true),
+ binding('cmd+o', 'swarm.new', custom: true),
+ binding(
+ 'cmd+e',
+ 'picker.preview',
+ context: KeymapContext.picker,
+ custom: true,
+ ),
+ ];
+ final parsed = KeymapConfig.parse(
+ keymapFileSource(bindings, commands),
+ commands: commands,
+ ).bindings;
+ expect(
+ parsed.map((b) => '${b.context.name}:${b.sequence}:${b.command}'),
+ bindings.map((b) => '${b.context.name}:${b.sequence}:${b.command}'),
+ );
+ expect(
+ KeymapConfig.parse(
+ keymapFileSource(const [], commands),
+ commands: commands,
+ ).bindings,
+ isEmpty,
+ );
+ });
+}
diff --git a/desktop/test/keymap_host_test.dart b/desktop/test/keymap_host_test.dart
index b89efb392..aac4fb53d 100644
--- a/desktop/test/keymap_host_test.dart
+++ b/desktop/test/keymap_host_test.dart
@@ -122,7 +122,10 @@ void main() {
for (final retired in ['cmd+shift+h', 'cmd+shift+k', 'cmd+u', 'cmd+y']) {
expect(command(retired), isNull, reason: retired);
}
- expect(command('cmd+alt+left'), isNull);
+ // ⌥⌘←/→ walk tabs, as in Safari and Chrome; ⇧⌘[ ] no longer do.
+ expect(command('cmd+alt+left'), 'swarm.previous');
+ expect(command('cmd+alt+right'), 'swarm.next');
+ expect(command('cmd+shift+['), isNull);
expect(command('cmd+shift+enter'), isNull);
expect(command('ctrl+n', KeymapContext.picker), 'picker.next');
expect(command('cmd+t', KeymapContext.picker), 'swarm.new');
diff --git a/desktop/test/shortcuts_test.dart b/desktop/test/shortcuts_test.dart
index 76edda7bb..6381cc9e5 100644
--- a/desktop/test/shortcuts_test.dart
+++ b/desktop/test/shortcuts_test.dart
@@ -241,10 +241,11 @@ void main() {
expect(chordsFor(ShortcutAction.movePaneRight), ['⇧⌘→']);
});
- test('brackets walk agents, and Shift walks tabs', () {
+ test('brackets walk agents, and ⌥⌘ arrows walk tabs', () {
// They used to carry three verbs told apart only by modifiers: ⌘[ ] walked
// panes, ⇧⌘[ ] walked agents, ⌥⌘[ ] moved panes. Panes use arrows, so
- // the brackets keep the one job a bracket is good at.
+ // the brackets keep the one job a bracket is good at. Tabs moved off
+ // ⇧⌘[ ] to ⌥⌘←/→, the key Safari and Chrome walk tabs with.
final bracketed = <ShortcutAction>{};
for (final s in appShortcuts()) {
final chord = describeShortcut(s.activator);
@@ -253,9 +254,9 @@ void main() {
expect(bracketed, {
ShortcutAction.previousAgent,
ShortcutAction.nextAgent,
- ShortcutAction.previousSwarm,
- ShortcutAction.nextSwarm,
});
+ expect(chordsFor(ShortcutAction.nextSwarm), contains('⌥⌘→'));
+ expect(chordsFor(ShortcutAction.previousSwarm), contains('⌥⌘←'));
});
test('the terminal verbs tmux trained people on are all here', () {
@@ -300,7 +301,7 @@ void main() {
final next = rows.firstWhere((row) => row.label == 'Next Tab');
expect(next.chords, [
- ['⇧', '⌘', ']'],
+ ['⌥', '⌘', '→'],
['⌃', '⇥'],
]);
});