diff --git a/Docs/DESIGN.md b/Docs/DESIGN.md index c5b8097ee..7d6a9c728 100644 --- a/Docs/DESIGN.md +++ b/Docs/DESIGN.md @@ -10,6 +10,7 @@ folder where a subject needs several. A file here is binding, not background. | [design/quick-switcher/lists-and-matching.md](design/quick-switcher/lists-and-matching.md) | What Cmd+P lists empty and typed, ranking, ties and row order, matching places and files, the files it reads and drops, menu commands and which are left out, what a choice opens, Recent. | | [design/quick-switcher/field-keys-and-look.md](design/quick-switcher/field-keys-and-look.md) | Cmd+P and Shift+Cmd+P, scopes and Tab, the AppKit field and prompt, look and position, closing on focus loss, Backspace, Return and scrolling, VoiceOver, hand checks. | | [design/settings.md](design/settings.md) | Project over global, what blank means, a repository's file filling gaps, the paths it names confined to the checkout and the trust guarding what it commits, layering asked of the model, export and the trust answer it carries, integrations per project, help behind an (i), a page split rather than scrolled, one window with a sidebar for All Projects and each project, its scope kept on the model, a project page as a Global and Override table, search, banner toggles and their permission, exports landing in order, an editor's tab selecting as a click does, `config project set` refusing what the decoder would drop. | +| [design/shortcuts.md](design/shortcuts.md) | Changing a command's keys: Default and Yours, only changes stored, what is refused or warned, Replace and reset, the fixed clipboard keys, unbinding default and override, the menu set twice, the recorder | | [design/hooks.md](design/hooks.md) | Only a pre hook refuses, how a hook runs and is stopped, the copy and link lists, their patterns, a repository's list held to the checkout and a user's stray entry named, lists and hook as one pane operation with a Cancel, no timeout on a list, where each hook runs, a list's blank and `#` lines, a failure's stderr, a stage failing once its worktree is gone, `MULTISHELL_PORT` unset without a port block. | | [design/worktrees/watching-and-status-reads.md](design/worktrees/watching-and-status-reads.md) | Watching every worktree with FSEvents, the backstop poll, which rows are read when, pacing slow status reads, git reads that write nothing, ignored directories. | | [design/worktrees/line-count-badge.md](design/worktrees/line-count-badge.md) | The line-count badge, ahead arrows and unpushed counts, untracked files, the per-file list, the Staged Only setting, the diff algorithm. | diff --git a/Docs/design/appearance/themes.md b/Docs/design/appearance/themes.md index aa1383f51..eee182fd5 100644 --- a/Docs/design/appearance/themes.md +++ b/Docs/design/appearance/themes.md @@ -65,8 +65,8 @@ reloaded. Newest at the bottom. does not reach. It allows two steps a channel: a menu button's glyph is colour-matched once more and lands at 254. It runs only under `make theme-audit`: its eight full windows took a minute of the main actor - every UI test waits on, a fifth of `make test`. Run it after touching a - view's colours. + every UI test waits on, a fifth of `make test`. Run it after touching a view's + colours. - **A theme saved in the themes folder is drawn at once**, the folder riding the one FSEvents stream the worktrees use and made before it is armed, as the watcher skips a folder not there yet. The engine keeps its own copy of the diff --git a/Docs/design/settings.md b/Docs/design/settings.md index 9b37da055..b19ec3d1a 100644 --- a/Docs/design/settings.md +++ b/Docs/design/settings.md @@ -106,7 +106,8 @@ the indicators changes nothing there. Project Hooks shows Create, Delete or Environment, six editors being 973 pt; All Projects' Agents shows Agent Settings or Agent hooks, the hooks growing with every agent installed. The - parts are sidebar rows under their page, not a segmented control in the form. + parts are sidebar rows under their page, not a segmented control in the form, + listed only while their page is open (owner, 2026-11-19). - **One settings window, a sidebar of pages, for All Projects and each project.** Chosen over two toolbar-tab windows (2026-11-05) from mockups of four designs. The menu atop the sidebar picks whose settings; Project diff --git a/Docs/design/shortcuts.md b/Docs/design/shortcuts.md new file mode 100644 index 000000000..55593f006 --- /dev/null +++ b/Docs/design/shortcuts.md @@ -0,0 +1,188 @@ +# Shortcuts + +Changing a menu command's keys in Settings > Shortcuts, and what holds the menu +bar, the terminal surface and the text that quotes keys to one answer. Newest at +the bottom. + +- **The page is the project pages' override table turned to shortcuts**, Default + and Yours, picked from mockups on 2026-11-18 for matching the other settings + pages. Not picked: one column of keys per row with no Default column, and a + page listing only the changes with an Add Shortcut… picker. +- **Global only.** A project has no Shortcuts page; keys are the app's, not a + repository's. +- **Four parts, File, Edit, View and Terminal, as the menu bar lists the + commands.** 31 rows at 36 pt do not fit the 608 pt window, and a page is split + rather than scrolled (settings.md). A part's sidebar row counts its changes. +- **Each card is a menu's run of items between two dividers**, `ShortcutGroup` + in AppCore, so the cards read as the menus do. +- **One table of defaults, `ShortcutCommand` in Core.** The menus, the engine's + unbinds, the settings rows and the command line all read it, so a default + changed there reaches all four. +- **The raw value is the state file's key**, `split-right`, and never changes. +- **Only changes are stored**, `"shortcuts": {"split-right": "cmd+backslash"}`, + so a default a later build changes still reaches a command the user left + alone. Blank is "no keys", the menu item staying, as the four blank-is-none + fields read it. +- **Hand-written `Codable`.** A synthesised enum-keyed dictionary encodes as an + array, a nil as `null`, and assigning nil to a dictionary deletes the entry + rather than storing "no keys". +- **Punctuation is spelled by name in the file**, `cmd+backslash`, so `+` never + parts a combination and a quote needs no escape. Modifiers are written in menu + order, ctrl, alt, shift, cmd, and read in any order or case. +- **The decode is tolerant per entry**: an unknown command, unreadable keys, + keys the page would refuse, a fixed command's entry, or a second claim on keys + an earlier command holds (in `ShortcutCommand` order, the fixed commands + first) drops that entry alone. +- **Where a later build's new default lands on an override, the override wins** + and the command with the new default has no keys. The user chose the override; + the default was nobody's choice. +- **Undo, Redo, Find, Cut, Copy, Paste and Select All are fixed**, the owner's + call on 2026-11-19: every Mac app gives them these keys. Their keys count as + held, so no command can take them. +- **Fixed is not kept by the pane.** Only the clipboard four stay bound in a + pane (`surfaceKeepsBinding`), being Ghostty's own copy and paste + (engine-and-config.md); ⌘Z, ⇧⌘Z and ⌘F are still unbound, or Ghostty's own + search bar takes ⌘F. +- **A click on the keys records; the next combination typed replaces them.** + Escape cancels, Delete alone leaves the command with no keys. +- **Refused, the row saying why and still recording**: + - a key with no ⌘, ⌃ or ⌥, F-keys excepted: every text field would lose it; + - ⌥ with a character key and neither ⌘ nor ⌃: it types a character on many + layouts (⌥L is @ on a German one) in every text field; + - the reserved table, `ReservedShortcut`: ⌘Q, ⌘H, ⌥⌘H, ⌘M, ⌥⌘M, ⌘,, ⌥⌘D (the + Dock's hiding, which the WindowServer takes before a menu bar sees it), ⌃⌘F, + ⌘⇥ and ⇧⌘⇥, ⌘Space, ⌘\` and ⇧⌘\`, ⇧⌘N, ⌘↩, which is also the review + composer's Send, the Apple menu's ⇧⌘Q, ⌥⇧⌘Q and ⌃⌘Q, and the system's own + hotkeys, which no menu sees: ⇧⌘3, ⇧⌘4 and ⇧⌘5 for screenshots, ⌃⇧⌘3 and ⌃⇧⌘4 + for them to the clipboard, ⌃←, ⌃→, ⌃↑ and ⌃↓ for Spaces and Mission Control, + ⌥⌘Space for Finder search, ⌘F5 and ⌥⌘F5 for VoiceOver and its panel, ⌃⌘D for + Look Up, and ⌃Space and ⌃⌥Space for input sources. The page cannot record + those, but the command line and a hand edit could set them; + - ⌃C, ⌃D, ⌃Z, ⌃\\ and ⌃[, which a pane's program needs, ⌃[ being Escape; + - ⌃↩ with any other modifier, and ⌃/ alone, which the pane types before any + menu sees them (`GhosttyKeyEquivalent.offer`), so a menu item on them would + never fire over a terminal; + - ⌥ with Delete, Forward Delete, an arrow, Page Up or Down, Return or Tab and + neither ⌘ nor ⌃: they move, delete or break a line in every text field, as ⌥ + with a character types one. ⌥Home and ⌥End do nothing there, so they are + allowed with the pane warning; + - ⌘., AppKit's Cancel for a sheet, an alert or a field's edit; + - ⌘ or ⇧⌘ with an arrow or Delete, and ⌃⇧ with a sideways arrow, which every + text field uses to move, select or delete to a line's or the text's ends; + - AppKit's own items, ⇧⌘\\ for Show All Tabs, ⇧⌘/ for Help's search and + ⌃⌘Space for Emoji & Symbols, which nothing of ours declares. Unproven here: + AppKit adds them as a menu opens, so `multishell ui menu` never lists them. +- **Allowed with a warning: keys without ⌘ are taken from every pane.** The row + says so for as long as the change stands, and names what the shell's emacs + line editor loses where it is known, "⌃R, the shell's history search". +- **Keys another command holds ask first**: Replace leaves that command with no + keys, Cancel keeps both as they were. The reset arrow asks the same where the + default now belongs to another command, so no path leaves two commands on one + key. +- **The judge is one function**, `ShortcutOverrides.judge`, and the page, the + reset arrow and `config global` all go through it. The page's steps + (recording, refused, asking) are `ShortcutEditing`, held on the model, so the + view only forwards keys and buttons. +- **Restore Defaults sits in the page header and asks once, inline**, before + clearing every change in every part. Not per part: a part is a fit to the + window, not a unit anyone restores. +- **The engine is told to unbind every command's default and override but the + clipboard four's.** Unbinding a freed default too keeps a freed ⌘F from + reaching Ghostty's own search bar, which an embedding never shows. The whole + reserved table is unbound as well, replacing the old system-owned list, so the + judge and the unbinds cannot disagree. +- **Re-applied on every change, as a theme is**, so open panes take new keys + without a restart. +- **A character key is unbound twice, by character and by Ghostty's name for the + key** (`bracket_left`, `digit_1`, `key_k`). A character binds the key typed + and a name the physical key, and an unbind removes only the trigger spelled + the same way. Ghostty's defaults use both: `super+[` by character, ⌘1 to ⌘8 + under both. The issue planned names for punctuation alone. +- **`>` has no trigger**: Ghostty reads it as the step between a sequence's + keys. Nothing in its defaults is on it. +- **Every recordable key runs through libghostty's own parser in a test** + (`KeyCombinationGhosttyTests`), libghostty dropping a line it refuses without + a word. +- **The menu items are set twice**: SwiftUI's `.keyboardShortcut` reads the + model, and `MacPlatform.setMenuShortcuts` sets each item's key equivalent by + title after every change, SwiftUI not reliably redrawing `Commands`. The quick + switcher and `multishell ui menu` read the `NSMenuItem`, so they follow. +- **A changed command's keys skip SwiftUI's layout localisation** (`.custom`, + and `allowsAutomaticKeyEquivalentLocalization` off): they were typed on this + layout, and remapping would move them to where the US key sits. +- **The recorder is an `NSEvent` local monitor**, which sees a key before the + menus do and swallows it, so typing ⌘W records ⌘W rather than closing the + window. A click anywhere ends it. +- **A named key's glyph spelled as the key is that key**: `cmd+←` from the + command line is the arrow, not a character no key types. A glyph for a key + with no case here, ⏎ or ⎋, is refused rather than kept as a character. +- **The key is the layout's character with no modifier pressed**, + `characters(byApplyingModifiers: [])`, as a menu's key equivalent matches. + Except an F-key or arrow, where that translation gives a control code (0x10, + 0x1C), not the private-use character AppKit's menus use; those come from + `charactersIgnoringModifiers` (`ShortcutRecorderInputTests`). +- **Text that quotes keys reads them live**: seven strings take ` (⌘T)` as an + argument, and a command with no keys drops the parenthesis. +- **`config global` has a `shortcuts.` row per changeable command**, + taking the state file's spelling or glyphs, `none`, or blank for the default, + refused through the judge. A command left to a default another's change took + reads blank, not `none`, which would write a change back. +- **The three questions the issue left open went as mocked**, pending the owner: + keys without ⌘ are allowed with the warning rather than refused, a bare F-key + is allowed, and Restore Defaults is once for the page. +- **A command whose default another's change holds says so under its row**, or + it read "Same" while having no keys. +- **An open question, a row's or Restore Defaults', ends when the overrides + change**, as Restore Defaults or the command line can change them under it, + and when the page goes. Keypad Enter is not recorded: its key equivalent is + not Return's, so the menu would not fire on it. +- **The recorder takes keys typed in its own window only**; a key in another + window ends recording and goes through, or a Delete in a pane cleared the + command. +- **Reviewed and left as is**: + - ` (⌘T)` is formatted in both halves, `keysInParentheses` in AppUI and + `TabStripButtonText.splitHelp` in AppCore, each from its own catalogue: a + view never reads the libraries' words (translation.md). + - Searching a command's title opens Shortcuts' first part, File, not the part + listing it, as a split Agents or Hooks page opens its first part. + - Keys are judged as spelled: `cmd+?` from the command line or a hand edit is + the character ?, which a US layout types as ⇧/, so it passes where ⇧⌘/ is + refused. Mapping it needs the keyboard layout, which Core cannot read, and + on a German layout # is a key of its own. The recorder writes the unshifted + key with Shift, so the page never makes one. + - Ghostty's names for punctuation repeat the state file's words in a table of + their own: the file's words are fixed with the file, Ghostty's follow its + pinned build, and one table would let an engine rename change the file. + - Shortcuts has no whole-page `--page` word, its four parts each having one, + as Hooks has none (settings.md). + - A ⌘ combination that is Ghostty's own pane action, ⌘K's clear or ⌘='s zoom, + is unbound without a warning: AppCore names no engine, so it cannot know + which keys one binds. + - ⌃ and a letter is allowed with the pane warning, though text fields lose + their emacs key too: the issue allows it, naming "⌃R … history search". + - Unproven: that holding keys just recorded, ⌘W say, lets the key's repeat + reach the menu once the recorder has gone. Holding a key cannot be driven + here, and the fix, committing on the key's release, would go untested. + - Unproven: that a recorder can start with no window key, which would end it + at the first key. A click on Same makes its window key before it acts. + - Unproven: F11 for Show Desktop and ⌃F1 to ⌃F8 for keyboard navigation, which + some Macs turn on, are not reserved; whether they are on by default varies + by machine. + - A bare F-key stays allowed though F5 is completion in a text field: few use + it, and F-keys are the one no-modifier key the issue keeps. + - Unproven: that on AZERTY, whose number row types & é and so on, ⌘& is + unbound as a character but not as the physical `digit_1` Ghostty binds, so a + pane would take it. The fix stores the key code with the keys, and the + layout cannot be switched to show it. + - Unproven: that on a non-Latin layout, Russian say, ⌘ and the K key records + as ⌘к, which a menu matching the layout's command layer, ⌘K, would never + fire. Switching the layout in a test would change the account's input + sources. + - Unproven: that SwiftUI never rebuilds a menu item from a stale `Commands` + body after the AppKit pass. It reads the same model, so a rebuild carries + the same keys. + - Unproven: why the system owns ⇧⌘N. It was on the system-owned list since the + first commit; the refusal says only that macOS keeps it. + - `MenuShortcutText` still draws a menu item's keys from AppKit's own + characters rather than through `KeyCombination.glyphs`: it reads any item, + the system's included, with F-keys to F35 and fn. diff --git a/Docs/design/terminals/engine-and-config.md b/Docs/design/terminals/engine-and-config.md index 28673aac9..ca0ef3702 100644 --- a/Docs/design/terminals/engine-and-config.md +++ b/Docs/design/terminals/engine-and-config.md @@ -77,8 +77,9 @@ it reads. Newest at the bottom. only under the US layout. - **Ghostty keybinds are unbound by name**, not cleared wholesale, which also removes word movement and delete-to-start. -- **Names and menu items come from one shortcuts table**; a shortcut in only one - list was a keystroke that worked everywhere but a pane. +- **Names and menu items come from one shortcuts table**, the defaults with the + user's overrides over them (shortcuts.md); a shortcut in only one list was a + keystroke that worked everywhere but a pane. - **Clipboard binds stay bound**: in a pane the copy key is Ghostty's copy of the terminal's selection, and unbinding it hands the keystroke to a menu item with nothing to copy. diff --git a/Docs/develop/adding/interface.md b/Docs/develop/adding/interface.md index 5518e6634..0b08bc47a 100644 --- a/Docs/develop/adding/interface.md +++ b/Docs/develop/adding/interface.md @@ -66,13 +66,17 @@ shortcuts, dialogs, icons and row orders. brings its sort key and caption wording with it, as the compiler asks for both. Raise the table's width in ems in `DebugTableLayout` by hand. Nothing measures the columns, so one left short crowds them before the rows stack. -- **A keyboard shortcut.** An entry in the shortcuts table, listed in `all`, - which both the menu item and the engine's unbind derive from. +- **A keyboard shortcut.** A `ShortcutCommand` case with its default, its menu + item reading `.keyboardShortcut(command, in: model)`, its title in + `ShortcutCommand+MenuTitle` and a place in a `ShortcutGroup` in the menu's + order, which ShortcutGroupTests checks lists every command once. The engine's + unbind and the `config global` row follow from the case (design/shortcuts.md). - **A key the engine names rather than takes the character of** needs a case in the name mapping, or the config carries a scalar it cannot parse. -- **A combination the system owns goes in the system-owned list**, not on a menu - item: the WindowServer takes it before a menu bar sees it. Declared but left - out of `all` means it works everywhere but a pane. +- **A combination the system owns goes in the reserved table**, + `ReservedShortcut`, not on a menu item: the WindowServer takes it before a + menu bar sees it. The table both refuses it on the Shortcuts page and unbinds + it from the surface. - **The clipboard combinations are kept by the surface**; a plain key the engine binds that must reach the program instead is released by the engine's own key name, nothing of ours being on the key. diff --git a/Docs/develop/state-on-disk.md b/Docs/develop/state-on-disk.md index 28e3c54e2..8f8ee2d14 100644 --- a/Docs/develop/state-on-disk.md +++ b/Docs/develop/state-on-disk.md @@ -21,7 +21,9 @@ Under `~/Library/Application Support/Multishell`. scroll, each worktree's All changes tab with its scroll, the groups they sit in with their widths, order and shown tab, pane trees, worktree names, which worktrees are hidden, creation dates and port blocks, the Agents board's Show - all terminals, whether the Files panel is open, every setting. + all terminals, whether the Files panel is open, every setting, and under + `shortcuts` only the commands whose keys the user changed + (design/shortcuts.md). - **Not in it**: processes, shell titles, the shell a tab resolved to, a branch's last commit time, the sidebar filter or a project collapsed under it, which Hidden sections are expanded, a file tab's text, the All changes tab's diff --git a/Docs/develop/tests/interface-and-terminal.md b/Docs/develop/tests/interface-and-terminal.md index e0fe46635..211ec3a89 100644 --- a/Docs/develop/tests/interface-and-terminal.md +++ b/Docs/develop/tests/interface-and-terminal.md @@ -6,9 +6,11 @@ highlighting. Why each rule holds is in `design/`. ## What catches a breach of the rules -- **A shortcut's two spellings agree**: AppShortcutCatalogueTests. **The - clipboard ones stay with the terminal**: GhosttyUnbindsTests, pinned against - the config the engine was given. +- **No two commands default to one key, and none to a reserved one**: + ShortcutCommandTests. **Every key the recorder takes is one libghostty + parses**: KeyCombinationGhosttyTests. **The clipboard ones stay with the + terminal**: GhosttyUnbindsTests, pinned against the config the engine was + given. - **Identifiers spelled in both Swift and the generated Info.plist still match**: InfoPlistTemplateTests. Nothing at build or run time notices these having parted. diff --git a/README.md b/README.md index c8e340352..c82592851 100644 --- a/README.md +++ b/README.md @@ -245,6 +245,11 @@ been in that state. | ⌘F | Find in the pane or file | | ⇧⌘O | Open the worktree in your editor | +These are the defaults. Settings > Shortcuts changes any command's keys or +removes them, and +`multishell config global set shortcuts.split-right cmd+backslash` does the same +from a script. + ### Scripting The `multishell` command drives the app: projects, worktrees, tabs, panes, diff --git a/Sources/MultishellAppCore/Control/ControlSettingsPage+SettingsSection.swift b/Sources/MultishellAppCore/Control/ControlSettingsPage+SettingsSection.swift index 5e3faf844..568d7eca2 100644 --- a/Sources/MultishellAppCore/Control/ControlSettingsPage+SettingsSection.swift +++ b/Sources/MultishellAppCore/Control/ControlSettingsPage+SettingsSection.swift @@ -1,6 +1,8 @@ import MultishellCore extension ControlSettingsPage { + // One case a word, exhaustive; settings.md says why not raw values. + // swiftlint:disable cyclomatic_complexity /// The command line's word for the section, which a refusal lists. init(_ section: SettingsSection) { self = @@ -15,8 +17,13 @@ extension ControlSettingsPage { case .hooksEnvironment: .hooksEnvironment case .integrations: .integrations case .notifications: .notifications + case .shortcutsEdit: .shortcutsEdit + case .shortcutsFile: .shortcutsFile + case .shortcutsTerminal: .shortcutsTerminal + case .shortcutsView: .shortcutsView case .terminal: .terminal case .worktrees: .worktrees } } + // swiftlint:enable cyclomatic_complexity } diff --git a/Sources/MultishellAppCore/Control/SettingsSection+ControlSettingsPage.swift b/Sources/MultishellAppCore/Control/SettingsSection+ControlSettingsPage.swift index d0d3f3aa2..297f92253 100644 --- a/Sources/MultishellAppCore/Control/SettingsSection+ControlSettingsPage.swift +++ b/Sources/MultishellAppCore/Control/SettingsSection+ControlSettingsPage.swift @@ -1,6 +1,8 @@ import MultishellCore extension SettingsSection { + // One case a word, exhaustive; settings.md says why not raw values. + // swiftlint:disable cyclomatic_complexity /// The section the command line's word names. init(_ page: ControlSettingsPage) { self = @@ -15,8 +17,13 @@ extension SettingsSection { case .hooksEnvironment: .hooksEnvironment case .integrations: .integrations case .notifications: .notifications + case .shortcutsEdit: .shortcutsEdit + case .shortcutsFile: .shortcutsFile + case .shortcutsTerminal: .shortcutsTerminal + case .shortcutsView: .shortcutsView case .terminal: .terminal case .worktrees: .worktrees } } + // swiftlint:enable cyclomatic_complexity } diff --git a/Sources/MultishellAppCore/Model/AppModel+Appearance.swift b/Sources/MultishellAppCore/Model/AppModel+Appearance.swift index 54dc49500..d4d992ba0 100644 --- a/Sources/MultishellAppCore/Model/AppModel+Appearance.swift +++ b/Sources/MultishellAppCore/Model/AppModel+Appearance.swift @@ -31,12 +31,18 @@ extension AppModel { public func setTheme(_ id: Theme.ID) { store.setTheme(id) - host.apply(currentTheme, appearance: workspace.appearance) + applyTerminalConfiguration() } func setTerminalFont(name: String?, size: Double) { store.setTerminalFont(name: name, size: size) - host.apply(currentTheme, appearance: workspace.appearance) + applyTerminalConfiguration() + } + + /// The engine keeps its own copy of the theme, font and unbinds, so each is + /// handed over again whenever one changes. + func applyTerminalConfiguration() { + host.apply(currentTheme, appearance: workspace.appearance, unbinding: surfaceUnbinds) } /// Takes a font picker's row id, keeping the size; the divider is no choice. @@ -100,7 +106,7 @@ extension AppModel { guard reload == themeReloads else { return } let shown = currentTheme take(catalogue) - if currentTheme != shown { host.apply(currentTheme, appearance: workspace.appearance) } + if currentTheme != shown { applyTerminalConfiguration() } } /// Every newly broken file is named in one alert, and each only once, not diff --git a/Sources/MultishellAppCore/Model/AppModel.swift b/Sources/MultishellAppCore/Model/AppModel.swift index 923d7f1dd..4bdb1079b 100644 --- a/Sources/MultishellAppCore/Model/AppModel.swift +++ b/Sources/MultishellAppCore/Model/AppModel.swift @@ -77,6 +77,9 @@ public final class AppModel { public internal(set) var settingsLocation = SettingsLocation.start /// What the settings sidebar's search holds, emptied as the window closes. public internal(set) var settingsSearchText = "" + /// Ended by any change to the shortcuts or the page going, so a question + /// never outlives what it asked about. + var shortcutsPageEdit: ShortcutsPageEdit? /// The worktree showing its name field. Runtime state, so the menu that /// starts a rename and the row that draws it need not know each other. var renamingWorktreeID: Worktree.ID? @@ -469,7 +472,7 @@ public final class AppModel { take(loadThemeCatalogue(themesDirectory)) rebuildNewTabAgents() - host.apply(currentTheme, appearance: store.workspace.appearance) + applyTerminalConfiguration() // A git missing here is said once the login shell's PATH lacks it too. if let loadError { present(loadError) } diff --git a/Sources/MultishellAppCore/Model/Control/AppModel+ControlGlobalSettingTable.swift b/Sources/MultishellAppCore/Model/Control/AppModel+ControlGlobalSettingTable.swift index 842e09b8a..eaebf145d 100644 --- a/Sources/MultishellAppCore/Model/Control/AppModel+ControlGlobalSettingTable.swift +++ b/Sources/MultishellAppCore/Model/Control/AppModel+ControlGlobalSettingTable.swift @@ -2,11 +2,14 @@ import Foundation import MultishellCore extension AppModel { + private static var noShortcutWord: String { "none" } + /// Named as `state.json` names them, a nested one with a dot. var globalSettings: [ControlSetting] { appearanceSettings + agentSettings + worktreeSettings + filesSettings + terminalSettings + editorSettings + NotificationPreference.notifiableStates.map(notificationSetting) + + ShortcutCommand.changeable.map(shortcutSetting) } private var appearanceSettings: [ControlSetting] { @@ -236,6 +239,36 @@ extension AppModel { ) } + /// `shortcuts.split-right`: keys as the state file spells them or as glyphs, + /// `none`, or blank to follow the default; refused where the page would refuse. + private func shortcutSetting(_ command: ShortcutCommand) -> ControlSetting { + ControlSetting( + key: "shortcuts.\(command.rawValue)", + read: { self.shortcutSettingText(command) }, + write: { text in + guard let trimmed = text.trimmedOrNil else { + self.followDefaultShortcut(command) + return true + } + if trimmed.lowercased() == Self.noShortcutWord { + return self.setShortcut(nil, for: command).isAllowed + } + guard let keys = KeyCombination(spelled: trimmed) ?? KeyCombination(glyphs: trimmed) + else { return false } + return self.setShortcut(keys, for: command).isAllowed + }, + ) + } + + /// Blank for a command left to a default another's change took, as writing + /// blank leaves it: `none` would write a change. + private func shortcutSettingText(_ command: ShortcutCommand) -> String { + guard let keys = shortcutKeys(for: command) else { + return isShortcutChanged(command) ? Self.noShortcutWord : "" + } + return keys.spelled + } + private func worktreeDefault( _ name: String, _ field: WritableKeyPath, diff --git a/Sources/MultishellAppCore/Model/Settings/AppModel+ShortcutEditing.swift b/Sources/MultishellAppCore/Model/Settings/AppModel+ShortcutEditing.swift new file mode 100644 index 000000000..44f2a8df6 --- /dev/null +++ b/Sources/MultishellAppCore/Model/Settings/AppModel+ShortcutEditing.swift @@ -0,0 +1,77 @@ +import MultishellCore + +/// The Shortcuts page's steps: recording a row's keys, saying why they were +/// refused, and asking before taking keys another command holds. +extension AppModel { + /// The row being changed, if that is what the page is doing. + var shortcutEditing: ShortcutEditing? { + get { + guard case .row(let editing) = shortcutsPageEdit else { return nil } + return editing + } + set { shortcutsPageEdit = newValue.map(ShortcutsPageEdit.row) } + } + + public var isAskingToRestoreShortcuts: Bool { + shortcutsPageEdit == .restoringDefaults + } + + /// The step a row shows, `nil` for every row but the one being changed. + public func shortcutEditingStep(for command: ShortcutCommand) -> ShortcutEditing.Step? { + shortcutEditing?.command == command ? shortcutEditing?.step : nil + } + + public func startRecordingShortcut(for command: ShortcutCommand) { + shortcutEditing = ShortcutEditing(command: command, step: .recording(nil)) + } + + /// Set where allowed, which ends the edit; otherwise the next step. + public func takeRecordedShortcut(_ keys: KeyCombination, for command: ShortcutCommand) { + switch setShortcut(keys, for: command) { + case .allowed: shortcutEditing = nil + + case .refused(let refusal): + shortcutEditing = ShortcutEditing(command: command, step: .recording(refusal)) + + case .taken(let holder): + shortcutEditing = ShortcutEditing( + command: command, + step: .confirming(keys, takenFrom: holder), + ) + } + } + + /// Delete while recording: no keys, the menu item staying. + public func clearRecordedShortcut(for command: ShortcutCommand) { + setShortcut(nil, for: command) + shortcutEditing = nil + } + + /// The reset arrow, judged as a set is: done, or a question where another + /// command now holds the default. + public func resetShortcut(_ command: ShortcutCommand) { + let keys = command.defaultCombination + guard case .taken(let holder) = setShortcut(keys, for: command) else { return } + shortcutEditing = ShortcutEditing( + command: command, + step: .confirming(keys, takenFrom: holder), + ) + } + + /// Replace, leaving the command that held the keys with none. + public func replaceAskedShortcut() { + guard let editing = shortcutEditing, case .confirming(let keys, _) = editing.step else { + return + } + replaceShortcut(keys, for: editing.command) + shortcutEditing = nil + } + + public func askToRestoreShortcuts() { + shortcutsPageEdit = .restoringDefaults + } + + public func endShortcutsPageEdit() { + shortcutsPageEdit = nil + } +} diff --git a/Sources/MultishellAppCore/Model/Settings/AppModel+Shortcuts.swift b/Sources/MultishellAppCore/Model/Settings/AppModel+Shortcuts.swift new file mode 100644 index 000000000..58603f0d6 --- /dev/null +++ b/Sources/MultishellAppCore/Model/Settings/AppModel+Shortcuts.swift @@ -0,0 +1,122 @@ +import MultishellCore + +extension AppModel { + public var hasChangedShortcuts: Bool { + !workspace.shortcutOverrides.isEmpty + } + + /// Every command's default and override but those the pane keeps. A freed + /// default is unbound too, or Ghostty's own binding, ⌘F's search, takes it. + var surfaceUnbinds: [KeyCombination] { + let overrides = workspace.shortcutOverrides + return ShortcutCommand.allCases.filter { !$0.surfaceKeepsBinding }.flatMap { command in + var keys = [command.defaultCombination] + if case .keys(let override) = overrides[command] { keys.append(override) } + return keys + } + } + + /// The keys in force for the command, `nil` for none. + public func shortcutKeys(for command: ShortcutCommand) -> KeyCombination? { + workspace.shortcutOverrides.keys(for: command) + } + + /// The command whose change took this one's default, which leaves it none, + /// as a later build's new default can; `nil` where it has its keys. + public func commandHoldingDefault(of command: ShortcutCommand) -> ShortcutCommand? { + guard !isShortcutChanged(command) else { return nil } + let holder = workspace.shortcutOverrides.command(holding: command.defaultCombination) + return holder == command ? nil : holder + } + + public func menuShortcut(for command: ShortcutCommand) -> MenuShortcut { + MenuShortcut( + command: command, + keys: shortcutKeys(for: command), + isChanged: isShortcutChanged(command), + ) + } + + public func isShortcutChanged(_ command: ShortcutCommand) -> Bool { + workspace.shortcutOverrides[command] != nil + } + + /// The commands changed in a Shortcuts part, for its sidebar row. + public func changedShortcutCount(in section: SettingsSection) -> Int { + ShortcutGroup.groups(in: section).flatMap(\.commands).count(where: isShortcutChanged) + } + + private func judgeShortcut( + _ keys: KeyCombination, + for command: ShortcutCommand, + ) + -> ShortcutJudgement + { + workspace.shortcutOverrides.judge(keys, for: command) + } + + /// What a pane gives up to a changed command's keys, said under its row + /// for as long as the change stands. + public func shortcutWarning(for command: ShortcutCommand) -> ShortcutWarning? { + guard case .keys(let keys) = workspace.shortcutOverrides[command], + case .allowed(let warning) = judgeShortcut(keys, for: command) + else { return nil } + return warning + } + + /// Sets the keys where the judge allows them, `nil` being none, which only a + /// fixed command refuses. The answer says what stopped it otherwise. + @discardableResult + func setShortcut( + _ keys: KeyCombination?, + for command: ShortcutCommand, + ) + -> ShortcutJudgement + { + guard let keys else { + guard !command.isFixed else { return .refused(.heldByFixed(command)) } + changeShortcutOverrides { $0.set(.noKeys, for: command) } + return .allowed(nil) + } + let judgement = judgeShortcut(keys, for: command) + if case .allowed = judgement { + changeShortcutOverrides { $0.set(.keys(keys), for: command) } + } + return judgement + } + + /// Sets the keys, leaving the command that held them with none: the answer + /// to `taken`. Nothing where the judge refuses them outright. + func replaceShortcut(_ keys: KeyCombination, for command: ShortcutCommand) { + switch judgeShortcut(keys, for: command) { + case .refused: break + case .allowed: changeShortcutOverrides { $0.set(.keys(keys), for: command) } + + case .taken(let holder): + changeShortcutOverrides { overrides in + overrides.set(.noKeys, for: holder) + overrides.set(.keys(keys), for: command) + } + } + } + + /// Drops the command's change, never asking: a default another command now + /// holds leaves it none rather than shared. + func followDefaultShortcut(_ command: ShortcutCommand) { + changeShortcutOverrides { $0.set(nil, for: command) } + } + + public func restoreDefaultShortcuts() { + changeShortcutOverrides { $0 = ShortcutOverrides() } + } + + private func changeShortcutOverrides(_ change: (inout ShortcutOverrides) -> Void) { + var overrides = workspace.shortcutOverrides + change(&overrides) + guard overrides != workspace.shortcutOverrides else { return } + store.setShortcutOverrides(overrides) + endShortcutsPageEdit() + applyTerminalConfiguration() + platform.setMenuShortcuts(ShortcutCommand.allCases.map(menuShortcut)) + } +} diff --git a/Sources/MultishellAppCore/Ports/MenuShortcut.swift b/Sources/MultishellAppCore/Ports/MenuShortcut.swift new file mode 100644 index 000000000..f8e3419f5 --- /dev/null +++ b/Sources/MultishellAppCore/Ports/MenuShortcut.swift @@ -0,0 +1,10 @@ +import MultishellCore + +/// A command's menu item keys as the menu bar is given them. +public struct MenuShortcut: Equatable, Sendable { + public let command: ShortcutCommand + /// `nil` for none, the item staying. + public let keys: KeyCombination? + /// Typed on this layout by the user, so no layout localisation may move them. + public let isChanged: Bool +} diff --git a/Sources/MultishellAppCore/Ports/NullPlatform.swift b/Sources/MultishellAppCore/Ports/NullPlatform.swift index 6518ab4f7..e3f5f0256 100644 --- a/Sources/MultishellAppCore/Ports/NullPlatform.swift +++ b/Sources/MultishellAppCore/Ports/NullPlatform.swift @@ -63,4 +63,5 @@ public final class NullPlatform: Platform { public func performMenuItemOnItsTurn(_ path: [String]) async -> PlatformMenuOutcome { .notFound } public func chooseMenuItem(_ path: [String]) {} public func hasFontFamily(_ family: String) -> Bool { false } + public func setMenuShortcuts(_ shortcuts: [MenuShortcut]) {} } diff --git a/Sources/MultishellAppCore/Ports/Platform.swift b/Sources/MultishellAppCore/Ports/Platform.swift index d76a378fd..ac02fc19a 100644 --- a/Sources/MultishellAppCore/Ports/Platform.swift +++ b/Sources/MultishellAppCore/Ports/Platform.swift @@ -132,4 +132,6 @@ public protocol Platform: AnyObject, Sendable { func chooseMenuItem(_ path: [String]) /// Whether a font family by this name is installed now, as the font picker lists them. func hasFontFamily(_ family: String) -> Bool + /// Each command's menu item given its keys. + func setMenuShortcuts(_ shortcuts: [MenuShortcut]) } diff --git a/Sources/MultishellAppCore/Settings/AppWide/Shortcuts/ShellKeyUse.swift b/Sources/MultishellAppCore/Settings/AppWide/Shortcuts/ShellKeyUse.swift new file mode 100644 index 000000000..1940f7e48 --- /dev/null +++ b/Sources/MultishellAppCore/Settings/AppWide/Shortcuts/ShellKeyUse.swift @@ -0,0 +1,27 @@ +import MultishellCore + +/// What a shell's line editor does with a ⌃ key, emacs mode as zsh, bash and +/// fish all start in, for the warning on keys a pane gives up. +public enum ShellKeyUse: Character, Sendable { + case backOneCharacter = "b" + case clearScreen = "l" + case deleteLine = "u" + case deleteToEndOfLine = "k" + case deleteWord = "w" + case endOfLine = "e" + case forwardOneCharacter = "f" + case historySearch = "r" + case nextCommand = "n" + case pasteDeleted = "y" + case previousCommand = "p" + case startOfLine = "a" + case swapCharacters = "t" + + /// `nil` for keys other than ⌃ and a letter the line editor binds. + init?(_ keys: KeyCombination) { + guard keys.modifiers == .control, case .character(let character) = keys.key else { + return nil + } + self.init(rawValue: character) + } +} diff --git a/Sources/MultishellAppCore/Settings/AppWide/Shortcuts/ShortcutEditing.swift b/Sources/MultishellAppCore/Settings/AppWide/Shortcuts/ShortcutEditing.swift new file mode 100644 index 000000000..7d577f88e --- /dev/null +++ b/Sources/MultishellAppCore/Settings/AppWide/Shortcuts/ShortcutEditing.swift @@ -0,0 +1,13 @@ +import MultishellCore + +/// A Shortcuts row part way through a change: recording keys, saying why the +/// last were refused, or asking before it takes keys another command holds. +public struct ShortcutEditing: Hashable, Sendable { + public enum Step: Hashable, Sendable { + case recording(ShortcutRefusal?) + case confirming(KeyCombination, takenFrom: ShortcutCommand) + } + + let command: ShortcutCommand + let step: Step +} diff --git a/Sources/MultishellAppCore/Settings/AppWide/Shortcuts/ShortcutGroup.swift b/Sources/MultishellAppCore/Settings/AppWide/Shortcuts/ShortcutGroup.swift new file mode 100644 index 000000000..33edea3c4 --- /dev/null +++ b/Sources/MultishellAppCore/Settings/AppWide/Shortcuts/ShortcutGroup.swift @@ -0,0 +1,41 @@ +import MultishellCore + +/// A card on the Shortcuts page, the commands a menu lists between two +/// dividers, under the part named for that menu. +public enum ShortcutGroup: CaseIterable, Sendable { + case closeItems + case editing + case filesPanel + case find + case groups + case newItems + case panes + case show + case tabs + + public var commands: [ShortcutCommand] { + switch self { + case .closeItems: [.closePane, .closeTab] + case .editing: [.undo, .redo, .cut, .copy, .paste, .selectAll] + case .filesPanel: [.filesPane, .changesPane, .reviewPane] + case .find: [.find, .findNext, .findPrevious, .closeFind] + case .groups: [.moveTabToNewGroup, .focusNextGroup, .focusPreviousGroup] + case .newItems: [.newTab, .newShellTab, .newAgentTab, .newWorktree, .addProject, .openInEditor] + case .panes: [.splitRight, .splitDown] + case .show: [.toggleAgentBoard, .quickSwitcher, .quickSwitcherCommands] + case .tabs: [.nextTab, .previousTab] + } + } + + /// The cards of a Shortcuts part, top to bottom as the menu lists them; + /// none for another section. + public static func groups(in section: SettingsSection) -> [Self] { + switch section { + case .shortcutsFile: [.newItems, .closeItems] + case .shortcutsEdit: [.editing, .find] + case .shortcutsView: [.show, .filesPanel] + case .shortcutsTerminal: [.panes, .groups, .tabs] + default: [] + } + } +} diff --git a/Sources/MultishellAppCore/Settings/AppWide/Shortcuts/ShortcutJudgement+IsAllowed.swift b/Sources/MultishellAppCore/Settings/AppWide/Shortcuts/ShortcutJudgement+IsAllowed.swift new file mode 100644 index 000000000..59ed1d4e7 --- /dev/null +++ b/Sources/MultishellAppCore/Settings/AppWide/Shortcuts/ShortcutJudgement+IsAllowed.swift @@ -0,0 +1,5 @@ +extension ShortcutJudgement { + var isAllowed: Bool { + if case .allowed = self { true } else { false } + } +} diff --git a/Sources/MultishellAppCore/Settings/AppWide/Shortcuts/ShortcutJudgement.swift b/Sources/MultishellAppCore/Settings/AppWide/Shortcuts/ShortcutJudgement.swift new file mode 100644 index 000000000..17d1a513c --- /dev/null +++ b/Sources/MultishellAppCore/Settings/AppWide/Shortcuts/ShortcutJudgement.swift @@ -0,0 +1,9 @@ +import MultishellCore + +/// What setting keys on a command would do: refused, a question because +/// another command holds them, or allowed, with what a pane loses. +enum ShortcutJudgement: Hashable, Sendable { + case allowed(ShortcutWarning?) + case refused(ShortcutRefusal) + case taken(holder: ShortcutCommand) +} diff --git a/Sources/MultishellAppCore/Settings/AppWide/Shortcuts/ShortcutOverrides+Judgement.swift b/Sources/MultishellAppCore/Settings/AppWide/Shortcuts/ShortcutOverrides+Judgement.swift new file mode 100644 index 000000000..cced36257 --- /dev/null +++ b/Sources/MultishellAppCore/Settings/AppWide/Shortcuts/ShortcutOverrides+Judgement.swift @@ -0,0 +1,15 @@ +import MultishellCore + +extension ShortcutOverrides { + /// What giving `keys` to `command` would do; Docs/design/shortcuts.md has + /// the rules and why. + func judge(_ keys: KeyCombination, for command: ShortcutCommand) -> ShortcutJudgement { + if command.isFixed { return .refused(.heldByFixed(command)) } + if let refusal = keys.refusal { return .refused(refusal) } + if let holder = self.command(holding: keys), holder != command { + return holder.isFixed ? .refused(.heldByFixed(holder)) : .taken(holder: holder) + } + guard !keys.modifiers.contains(.command) else { return .allowed(nil) } + return .allowed(ShortcutWarning(keys: keys, shellUse: ShellKeyUse(keys))) + } +} diff --git a/Sources/MultishellAppCore/Settings/AppWide/Shortcuts/ShortcutWarning.swift b/Sources/MultishellAppCore/Settings/AppWide/Shortcuts/ShortcutWarning.swift new file mode 100644 index 000000000..c7a65d6ce --- /dev/null +++ b/Sources/MultishellAppCore/Settings/AppWide/Shortcuts/ShortcutWarning.swift @@ -0,0 +1,8 @@ +import MultishellCore + +/// Keys without ⌘, which every pane gives up to the menu, and what the shell +/// used them for where it is known. +public struct ShortcutWarning: Hashable, Sendable { + public let keys: KeyCombination + public let shellUse: ShellKeyUse? +} diff --git a/Sources/MultishellAppCore/Settings/AppWide/Shortcuts/ShortcutsPageEdit.swift b/Sources/MultishellAppCore/Settings/AppWide/Shortcuts/ShortcutsPageEdit.swift new file mode 100644 index 000000000..3ef35cc6e --- /dev/null +++ b/Sources/MultishellAppCore/Settings/AppWide/Shortcuts/ShortcutsPageEdit.swift @@ -0,0 +1,6 @@ +/// What the Shortcuts page is part way through, one thing at a time: a row's +/// change, or Restore Defaults asking. +enum ShortcutsPageEdit: Hashable, Sendable { + case restoringDefaults + case row(ShortcutEditing) +} diff --git a/Sources/MultishellAppCore/Settings/SettingsLocation.swift b/Sources/MultishellAppCore/Settings/SettingsLocation.swift index 8b371c506..e9f061f64 100644 --- a/Sources/MultishellAppCore/Settings/SettingsLocation.swift +++ b/Sources/MultishellAppCore/Settings/SettingsLocation.swift @@ -12,6 +12,12 @@ public struct SettingsLocation: Hashable, Sendable { !section.isPart && section.page == page } + /// Whether the sidebar lists a split page's parts: only while one of them is + /// open, so the pages around it stay one row each. + public func showsParts(of page: SettingsPage) -> Bool { + section.page == page + } + /// The section `offset` rows down the sidebar's `pages`, their parts /// counted, held to the first and last, onto the list where it hides this one. func stepped(by offset: Int, among pages: [SettingsPage]) -> Self { diff --git a/Sources/MultishellAppCore/Settings/SettingsSection.swift b/Sources/MultishellAppCore/Settings/SettingsSection.swift index 7e3ff7b9f..42d60927d 100644 --- a/Sources/MultishellAppCore/Settings/SettingsSection.swift +++ b/Sources/MultishellAppCore/Settings/SettingsSection.swift @@ -13,6 +13,10 @@ public enum SettingsSection: Hashable, Sendable { case hooksEnvironment case integrations case notifications + case shortcutsEdit + case shortcutsFile + case shortcutsTerminal + case shortcutsView case terminal case worktrees @@ -20,6 +24,7 @@ public enum SettingsSection: Hashable, Sendable { public var isPart: Bool { switch self { case .agentHooks, .agentSettings, .hooksCreate, .hooksDelete, .hooksEnvironment: true + case .shortcutsEdit, .shortcutsFile, .shortcutsTerminal, .shortcutsView: true case .agents, .appearance, .general, .integrations, .notifications, .terminal, .worktrees: false } } @@ -32,6 +37,7 @@ public enum SettingsSection: Hashable, Sendable { case .hooksCreate, .hooksDelete, .hooksEnvironment: .hooks case .integrations: .integrations case .notifications: .notifications + case .shortcutsEdit, .shortcutsFile, .shortcutsTerminal, .shortcutsView: .shortcuts case .terminal: .terminal case .worktrees: .worktrees } diff --git a/Sources/MultishellAppCore/Settings/Sidebar/SettingsPage.swift b/Sources/MultishellAppCore/Settings/Sidebar/SettingsPage.swift index a4b87ff21..1aa38cd1d 100644 --- a/Sources/MultishellAppCore/Settings/Sidebar/SettingsPage.swift +++ b/Sources/MultishellAppCore/Settings/Sidebar/SettingsPage.swift @@ -7,11 +7,12 @@ public enum SettingsPage: Hashable, Sendable { case hooks case integrations case notifications + case shortcuts case terminal case worktrees private static let allProjectsOrder: [Self] = [ - .general, .worktrees, .terminal, .agents, .notifications, .appearance, + .general, .worktrees, .terminal, .agents, .notifications, .appearance, .shortcuts, ] private static let projectOrder: [Self] = [ .general, .worktrees, .hooks, .terminal, .agents, .integrations, @@ -33,6 +34,10 @@ public enum SettingsPage: Hashable, Sendable { case .hooks: isAllProjects ? [] : [.hooksCreate, .hooksDelete, .hooksEnvironment] case .integrations: isAllProjects ? [] : [.integrations] case .notifications: isAllProjects ? [.notifications] : [] + + case .shortcuts: + isAllProjects ? [.shortcutsFile, .shortcutsEdit, .shortcutsView, .shortcutsTerminal] : [] + case .terminal: [.terminal] case .worktrees: [.worktrees] } diff --git a/Sources/MultishellAppCore/Terminals/Groups/TabStripButtonText.swift b/Sources/MultishellAppCore/Terminals/Groups/TabStripButtonText.swift index f6706ec90..71ad23bb2 100644 --- a/Sources/MultishellAppCore/Terminals/Groups/TabStripButtonText.swift +++ b/Sources/MultishellAppCore/Terminals/Groups/TabStripButtonText.swift @@ -10,15 +10,26 @@ public enum TabStripButtonText { isFocusedGroup ? t("tab.new") : t("tab.new-in-group") } - public static func splitHelp(_ axis: SplitAxis, isFocusedGroup: Bool) -> String { - switch (axis, isFocusedGroup) { - case (.horizontal, true): t("tab.split-right-here") + /// `keys` are the split's own, in force now; none drops the parenthesis. + public static func splitHelp( + _ axis: SplitAxis, + isFocusedGroup: Bool, + keys: KeyCombination?, + ) -> String { + let named = keys.map { t("shortcuts.in-parentheses", $0.glyphs) } ?? "" + return switch (axis, isFocusedGroup) { + case (.horizontal, true): t("tab.split-right-here", named) case (.horizontal, false): t("tab.split-right-in-group") - case (.vertical, true): t("tab.split-down-here") + case (.vertical, true): t("tab.split-down-here", named) case (.vertical, false): t("tab.split-down-in-group") } } + /// The command whose keys a split button names. + public static func splitCommand(_ axis: SplitAxis) -> ShortcutCommand { + axis == .horizontal ? .splitRight : .splitDown + } + public static func splitLabel(_ axis: SplitAxis) -> String { axis == .horizontal ? t("tab.split-right") : t("tab.split-down") } diff --git a/Sources/MultishellAppUI/App/AppShortcut.swift b/Sources/MultishellAppUI/App/AppShortcut.swift deleted file mode 100644 index 4a1cf4650..000000000 --- a/Sources/MultishellAppUI/App/AppShortcut.swift +++ /dev/null @@ -1,28 +0,0 @@ -import SwiftUI - -/// A keyboard shortcut the app owns, in SwiftUI's spelling and Ghostty's, -/// declared once: a combination nobody unbound is dead in a Ghostty pane. -struct AppShortcut { - let key: KeyEquivalent - let modifiers: EventModifiers - /// Whether the surface keeps its own binding rather than giving it up to - /// the menu bar. True only where Ghostty's action is what a pane wants. - let surfaceKeepsBinding: Bool - - init(_ key: KeyEquivalent, _ extra: EventModifiers = [], surfaceKeepsBinding: Bool = false) { - self.key = key - self.modifiers = extra.union(.command) - self.surfaceKeepsBinding = surfaceKeepsBinding - } - - private init(key: KeyEquivalent, modifiers: EventModifiers, surfaceKeepsBinding: Bool) { - self.key = key - self.modifiers = modifiers - self.surfaceKeepsBinding = surfaceKeepsBinding - } - - /// Control-only, for the tab cycling that does not take Command. - static func control(_ key: KeyEquivalent, _ extra: EventModifiers = []) -> Self { - Self(key: key, modifiers: extra.union(.control), surfaceKeepsBinding: false) - } -} diff --git a/Sources/MultishellAppUI/App/AppShortcutCatalogue.swift b/Sources/MultishellAppUI/App/AppShortcutCatalogue.swift deleted file mode 100644 index c54c3f151..000000000 --- a/Sources/MultishellAppUI/App/AppShortcutCatalogue.swift +++ /dev/null @@ -1,63 +0,0 @@ -import SwiftUI - -/// Every keystroke this app's menus claim. The commands build from these, -/// and `GhosttyUnbinds` from the ones the surface gives up. -enum AppShortcutCatalogue { - static let newTab = AppShortcut("t") - static let newShellTab = AppShortcut("t", .shift) - static let newAgentTab = AppShortcut("t", .option) - static let newWorktree = AppShortcut("n") - static let addProject = AppShortcut("o") - static let openInEditor = AppShortcut("o", .shift) - static let closePane = AppShortcut("w") - static let closeTab = AppShortcut("w", .shift) - static let splitRight = AppShortcut("d") - static let splitDown = AppShortcut("d", .shift) - /// Not Cmd+Option+D, the system's own toggle for hiding the Dock: the - /// WindowServer takes it before a menu bar sees it. - static let moveTabToNewGroup = AppShortcut("g", .option) - /// Alt and an arrow is word movement in a terminal, which stays bound; - /// these carry Command as well, so nothing in a pane wants them. - static let nextGroup = AppShortcut(.rightArrow, .option) - static let previousGroup = AppShortcut(.leftArrow, .option) - /// The Agents board, in place of the selected worktree's terminals. Not - /// Cmd+A, which is Select All in a pane and stays there. - static let toggleAgentBoard = AppShortcut("a", .shift) - static let quickSwitcher = AppShortcut("p") - /// Ghostty's own command palette's key, which an embedding never shows; - /// taken from the surface, as Cmd+F is. - static let quickSwitcherCommands = AppShortcut("p", .shift) - static let undo = AppShortcut("z") - static let redo = AppShortcut("z", .shift) - static let nextTab = AppShortcut.control(.tab) - static let previousTab = AppShortcut.control(.tab, .shift) - /// Ghostty binds Cmd+F to a search bar of its own that an embedding never - /// shows; taken from the surface so the keystroke reaches ours. - static let find = AppShortcut("f") - static let findNext = AppShortcut("g") - static let findPrevious = AppShortcut("g", .shift) - static let closeFind = AppShortcut("f", .option) - /// The Files panel on each page. Cmd+Shift+F is Ghostty's own end-search key, - /// which would otherwise end a search under a bar of ours that stayed up. - static let filesPane = AppShortcut("f", .shift) - static let changesPane = AppShortcut("c", .shift) - static let reviewPane = AppShortcut("r", .shift) - - /// Copy, paste, cut and select-all. The menu carries them and the surface - /// keeps them, a pane's Cmd+C being Ghostty's own clipboard action. - static let cut = AppShortcut("x", surfaceKeepsBinding: true) - static let copy = AppShortcut("c", surfaceKeepsBinding: true) - static let paste = AppShortcut("v", surfaceKeepsBinding: true) - static let selectAll = AppShortcut("a", surfaceKeepsBinding: true) - - /// The one step done by hand: nothing can check a shortcut left out of - /// this list. - static let all: [AppShortcut] = [ - newTab, newShellTab, newAgentTab, closePane, closeTab, newWorktree, - addProject, openInEditor, splitRight, splitDown, - moveTabToNewGroup, nextGroup, previousGroup, - toggleAgentBoard, quickSwitcher, quickSwitcherCommands, undo, redo, nextTab, previousTab, - find, findNext, findPrevious, closeFind, filesPane, changesPane, reviewPane, - cut, copy, paste, selectAll, - ] -} diff --git a/Sources/MultishellAppUI/App/MenuCommandAvailability.swift b/Sources/MultishellAppUI/App/MenuCommandAvailability.swift index f235ef573..cfb8ee9bb 100644 --- a/Sources/MultishellAppUI/App/MenuCommandAvailability.swift +++ b/Sources/MultishellAppUI/App/MenuCommandAvailability.swift @@ -1,29 +1,33 @@ import MultishellAppCore +import MultishellCore /// Which model property says a menu command can act, by the item's title, /// worked out once rather than a lookup per title on each opening. @MainActor enum MenuCommandAvailability { - private static let pairs: [(String, KeyPath)] = [ - (t("menu.new-tab"), \.canOpenTab), - (t("menu.new-shell-tab"), \.canOpenTab), - (t("menu.new-agent-tab"), \.canOpenTab), - (t("menu.new-worktree"), \.canStartNewWorktree), - (t("action.open-in-editor"), \.canOpenWorktreeInEditor), - (t("menu.files-pane"), \.canToggleFilesPanel), - (t("menu.changes-pane"), \.canToggleFilesPanel), - (t("menu.review-pane"), \.canToggleFilesPanel), - (t("menu.close-pane"), \.hasTabToClose), - (t("menu.close-tab"), \.hasTabToClose), - (t("menu.split-right"), \.canSplitPane), - (t("menu.split-down"), \.canSplitPane), - (t("menu.move-tab-to-new-group"), \.canMoveActiveTabToNewGroup), - (t("menu.focus-next-group"), \.canFocusAnotherGroup), - (t("menu.focus-previous-group"), \.canFocusAnotherGroup), - (t("menu.next-tab"), \.canActivateAnotherTab), - (t("menu.previous-tab"), \.canActivateAnotherTab), + private static let pairs: [(command: ShortcutCommand, isAvailable: KeyPath)] = [ + (.newTab, \.canOpenTab), + (.newShellTab, \.canOpenTab), + (.newAgentTab, \.canOpenTab), + (.newWorktree, \.canStartNewWorktree), + (.openInEditor, \.canOpenWorktreeInEditor), + (.filesPane, \.canToggleFilesPanel), + (.changesPane, \.canToggleFilesPanel), + (.reviewPane, \.canToggleFilesPanel), + (.closePane, \.hasTabToClose), + (.closeTab, \.hasTabToClose), + (.splitRight, \.canSplitPane), + (.splitDown, \.canSplitPane), + (.moveTabToNewGroup, \.canMoveActiveTabToNewGroup), + (.focusNextGroup, \.canFocusAnotherGroup), + (.focusPreviousGroup, \.canFocusAnotherGroup), + (.nextTab, \.canActivateAnotherTab), + (.previousTab, \.canActivateAnotherTab), ] /// Two titles a translation makes one keep the first, where a literal traps. - static let byTitle = Dictionary(pairs) { first, _ in first } + static let byTitle = Dictionary(pairs.map { ($0.command.menuTitle, $0.isAvailable) }) { + first, + _ in first + } } diff --git a/Sources/MultishellAppUI/App/MultishellCommands.swift b/Sources/MultishellAppUI/App/MultishellCommands.swift index 165061df3..b281affbe 100644 --- a/Sources/MultishellAppUI/App/MultishellCommands.swift +++ b/Sources/MultishellAppUI/App/MultishellCommands.swift @@ -32,18 +32,18 @@ struct MultishellCommands: Commands { private var newItems: some Commands { CommandGroup(replacing: .newItem) { - Button(t("menu.new-tab")) { model.newTab() } - .keyboardShortcut(AppShortcutCatalogue.newTab) - Button(t("menu.new-shell-tab")) { model.newShellTab() } - .keyboardShortcut(AppShortcutCatalogue.newShellTab) - Button(t("menu.new-agent-tab")) { model.newAgentTab() } - .keyboardShortcut(AppShortcutCatalogue.newAgentTab) - Button(t("menu.new-worktree")) { model.requestNewWorktree() } - .keyboardShortcut(AppShortcutCatalogue.newWorktree) - Button(t("menu.add-project")) { Task { await model.addProjectFromPicker() } } - .keyboardShortcut(AppShortcutCatalogue.addProject) - Button(t("action.open-in-editor")) { model.openWorktreeInViewInEditor() } - .keyboardShortcut(AppShortcutCatalogue.openInEditor) + Button(ShortcutCommand.newTab.menuTitle) { model.newTab() } + .keyboardShortcut(.newTab, in: model) + Button(ShortcutCommand.newShellTab.menuTitle) { model.newShellTab() } + .keyboardShortcut(.newShellTab, in: model) + Button(ShortcutCommand.newAgentTab.menuTitle) { model.newAgentTab() } + .keyboardShortcut(.newAgentTab, in: model) + Button(ShortcutCommand.newWorktree.menuTitle) { model.requestNewWorktree() } + .keyboardShortcut(.newWorktree, in: model) + Button(ShortcutCommand.addProject.menuTitle) { Task { await model.addProjectFromPicker() } } + .keyboardShortcut(.addProject, in: model) + Button(ShortcutCommand.openInEditor.menuTitle) { model.openWorktreeInViewInEditor() } + .keyboardShortcut(.openInEditor, in: model) } } @@ -57,16 +57,22 @@ struct MultishellCommands: Commands { // lags the responder chain. These send the selectors and stay enabled. private var pasteboardItems: some Commands { CommandGroup(replacing: .pasteboard) { - Button(t("menu.cut")) { NSApp.sendAction(#selector(NSText.cut(_:)), to: nil, from: nil) } - .keyboardShortcut(AppShortcutCatalogue.cut) - Button(t("action.copy")) { NSApp.sendAction(#selector(NSText.copy(_:)), to: nil, from: nil) } - .keyboardShortcut(AppShortcutCatalogue.copy) - Button(t("menu.paste")) { NSApp.sendAction(#selector(NSText.paste(_:)), to: nil, from: nil) } - .keyboardShortcut(AppShortcutCatalogue.paste) - Button(t("menu.select-all")) { + Button(ShortcutCommand.cut.menuTitle) { + NSApp.sendAction(#selector(NSText.cut(_:)), to: nil, from: nil) + } + .keyboardShortcut(.cut, in: model) + Button(ShortcutCommand.copy.menuTitle) { + NSApp.sendAction(#selector(NSText.copy(_:)), to: nil, from: nil) + } + .keyboardShortcut(.copy, in: model) + Button(ShortcutCommand.paste.menuTitle) { + NSApp.sendAction(#selector(NSText.paste(_:)), to: nil, from: nil) + } + .keyboardShortcut(.paste, in: model) + Button(ShortcutCommand.selectAll.menuTitle) { NSApp.sendAction(#selector(NSText.selectAll(_:)), to: nil, from: nil) } - .keyboardShortcut(AppShortcutCatalogue.selectAll) + .keyboardShortcut(.selectAll, in: model) } } @@ -74,16 +80,16 @@ struct MultishellCommands: Commands { // editor keeps one the window never sees, and asking covers both. private var undoItems: some Commands { CommandGroup(replacing: .undoRedo) { - Button(t("menu.undo")) { + Button(ShortcutCommand.undo.menuTitle) { guard let manager = Self.focusedUndoManager, manager.canUndo else { return } manager.undo() } - .keyboardShortcut(AppShortcutCatalogue.undo) - Button(t("menu.redo")) { + .keyboardShortcut(.undo, in: model) + Button(ShortcutCommand.redo.menuTitle) { guard let manager = Self.focusedUndoManager, manager.canRedo else { return } manager.redo() } - .keyboardShortcut(AppShortcutCatalogue.redo) + .keyboardShortcut(.redo, in: model) } } @@ -92,18 +98,18 @@ struct MultishellCommands: Commands { private var findMenu: some Commands { CommandGroup(replacing: .textEditing) { Menu(t("menu.find")) { - Button(t("menu.find-item")) { model.showFind() } - .keyboardShortcut(AppShortcutCatalogue.find) + Button(ShortcutCommand.find.menuTitle) { model.showFind() } + .keyboardShortcut(.find, in: model) .disabled(!model.findIsAvailable) - Button(t("menu.find-next")) { model.findNext() } - .keyboardShortcut(AppShortcutCatalogue.findNext) + Button(ShortcutCommand.findNext.menuTitle) { model.findNext() } + .keyboardShortcut(.findNext, in: model) .disabled(!model.findIsOpenInView) - Button(t("menu.find-previous")) { model.findPrevious() } - .keyboardShortcut(AppShortcutCatalogue.findPrevious) + Button(ShortcutCommand.findPrevious.menuTitle) { model.findPrevious() } + .keyboardShortcut(.findPrevious, in: model) .disabled(!model.findIsOpenInView) Divider() - Button(t("menu.close-find")) { model.closeFind() } - .keyboardShortcut(AppShortcutCatalogue.closeFind) + Button(ShortcutCommand.closeFind.menuTitle) { model.closeFind() } + .keyboardShortcut(.closeFind, in: model) .disabled(!model.findIsOpenInView) } } @@ -111,10 +117,10 @@ struct MultishellCommands: Commands { private var closeItems: some Commands { CommandGroup(replacing: .saveItem) { - Button(t("menu.close-pane")) { model.closeActivePane() } - .keyboardShortcut(AppShortcutCatalogue.closePane) - Button(t("menu.close-tab")) { model.closeActiveTab() } - .keyboardShortcut(AppShortcutCatalogue.closeTab) + Button(ShortcutCommand.closePane.menuTitle) { model.closeActivePane() } + .keyboardShortcut(.closePane, in: model) + Button(ShortcutCommand.closeTab.menuTitle) { model.closeActiveTab() } + .keyboardShortcut(.closeTab, in: model) } } @@ -122,18 +128,20 @@ struct MultishellCommands: Commands { // AppKit's: the board and the debug tools change what is shown, not act. private var viewItems: some Commands { CommandGroup(after: .toolbar) { - Button(t("label.agents")) { model.toggleAgentBoard() } - .keyboardShortcut(AppShortcutCatalogue.toggleAgentBoard) - Button(t("menu.quick-switcher")) { model.toggleQuickSwitcher(.all) } - .keyboardShortcut(AppShortcutCatalogue.quickSwitcher) - Button(t("menu.quick-switcher-commands")) { model.toggleQuickSwitcher(.commands) } - .keyboardShortcut(AppShortcutCatalogue.quickSwitcherCommands) - Toggle(t("menu.files-pane"), isOn: model.filesPanelBinding(on: .files)) - .keyboardShortcut(AppShortcutCatalogue.filesPane) - Toggle(t("menu.changes-pane"), isOn: model.filesPanelBinding(on: .changes)) - .keyboardShortcut(AppShortcutCatalogue.changesPane) - Toggle(t("menu.review-pane"), isOn: model.filesPanelBinding(on: .review)) - .keyboardShortcut(AppShortcutCatalogue.reviewPane) + Button(ShortcutCommand.toggleAgentBoard.menuTitle) { model.toggleAgentBoard() } + .keyboardShortcut(.toggleAgentBoard, in: model) + Button(ShortcutCommand.quickSwitcher.menuTitle) { model.toggleQuickSwitcher(.all) } + .keyboardShortcut(.quickSwitcher, in: model) + Button(ShortcutCommand.quickSwitcherCommands.menuTitle) { + model.toggleQuickSwitcher(.commands) + } + .keyboardShortcut(.quickSwitcherCommands, in: model) + Toggle(ShortcutCommand.filesPane.menuTitle, isOn: model.filesPanelBinding(on: .files)) + .keyboardShortcut(.filesPane, in: model) + Toggle(ShortcutCommand.changesPane.menuTitle, isOn: model.filesPanelBinding(on: .changes)) + .keyboardShortcut(.changesPane, in: model) + Toggle(ShortcutCommand.reviewPane.menuTitle, isOn: model.filesPanelBinding(on: .review)) + .keyboardShortcut(.reviewPane, in: model) Toggle( t("menu.show-hidden-files"), isOn: model.settingBinding(\.showsIgnoredFiles, write: model.setShowsIgnoredFiles), @@ -145,24 +153,24 @@ struct MultishellCommands: Commands { private var terminalMenu: some Commands { CommandMenu(t("menu.terminal")) { - Button(t("menu.split-right")) { model.splitActivePane(.horizontal) } - .keyboardShortcut(AppShortcutCatalogue.splitRight) - Button(t("menu.split-down")) { model.splitActivePane(.vertical) } - .keyboardShortcut(AppShortcutCatalogue.splitDown) + Button(ShortcutCommand.splitRight.menuTitle) { model.splitActivePane(.horizontal) } + .keyboardShortcut(.splitRight, in: model) + Button(ShortcutCommand.splitDown.menuTitle) { model.splitActivePane(.vertical) } + .keyboardShortcut(.splitDown, in: model) Divider() // Beside the splits, which is the layout it is a step out from: a // split divides a tab, this divides the worktree. - Button(t("menu.move-tab-to-new-group")) { model.moveActiveTabToNewGroup() } - .keyboardShortcut(AppShortcutCatalogue.moveTabToNewGroup) - Button(t("menu.focus-next-group")) { model.focusNextGroup() } - .keyboardShortcut(AppShortcutCatalogue.nextGroup) - Button(t("menu.focus-previous-group")) { model.focusPreviousGroup() } - .keyboardShortcut(AppShortcutCatalogue.previousGroup) + Button(ShortcutCommand.moveTabToNewGroup.menuTitle) { model.moveActiveTabToNewGroup() } + .keyboardShortcut(.moveTabToNewGroup, in: model) + Button(ShortcutCommand.focusNextGroup.menuTitle) { model.focusNextGroup() } + .keyboardShortcut(.focusNextGroup, in: model) + Button(ShortcutCommand.focusPreviousGroup.menuTitle) { model.focusPreviousGroup() } + .keyboardShortcut(.focusPreviousGroup, in: model) Divider() - Button(t("menu.next-tab")) { model.activateNextTab() } - .keyboardShortcut(AppShortcutCatalogue.nextTab) - Button(t("menu.previous-tab")) { model.activatePreviousTab() } - .keyboardShortcut(AppShortcutCatalogue.previousTab) + Button(ShortcutCommand.nextTab.menuTitle) { model.activateNextTab() } + .keyboardShortcut(.nextTab, in: model) + Button(ShortcutCommand.previousTab.menuTitle) { model.activatePreviousTab() } + .keyboardShortcut(.previousTab, in: model) Divider() ThemePicker(title: t("menu.theme"), model: model) } diff --git a/Sources/MultishellAppUI/App/ShortcutCommand+MenuTitle.swift b/Sources/MultishellAppUI/App/ShortcutCommand+MenuTitle.swift new file mode 100644 index 000000000..63b35e728 --- /dev/null +++ b/Sources/MultishellAppUI/App/ShortcutCommand+MenuTitle.swift @@ -0,0 +1,41 @@ +import MultishellCore + +extension ShortcutCommand { + /// The menu item's title, which the Shortcuts page lists it by and the menu + /// bar's keys are set against. + var menuTitle: String { + switch self { + case .newTab: t("menu.new-tab") + case .newShellTab: t("menu.new-shell-tab") + case .newAgentTab: t("menu.new-agent-tab") + case .newWorktree: t("menu.new-worktree") + case .addProject: t("menu.add-project") + case .openInEditor: t("action.open-in-editor") + case .closePane: t("menu.close-pane") + case .closeTab: t("menu.close-tab") + case .undo: t("menu.undo") + case .redo: t("menu.redo") + case .cut: t("menu.cut") + case .copy: t("action.copy") + case .paste: t("menu.paste") + case .selectAll: t("menu.select-all") + case .find: t("menu.find-item") + case .findNext: t("menu.find-next") + case .findPrevious: t("menu.find-previous") + case .closeFind: t("menu.close-find") + case .toggleAgentBoard: t("label.agents") + case .quickSwitcher: t("menu.quick-switcher") + case .quickSwitcherCommands: t("menu.quick-switcher-commands") + case .filesPane: t("menu.files-pane") + case .changesPane: t("menu.changes-pane") + case .reviewPane: t("menu.review-pane") + case .splitRight: t("menu.split-right") + case .splitDown: t("menu.split-down") + case .moveTabToNewGroup: t("menu.move-tab-to-new-group") + case .focusNextGroup: t("menu.focus-next-group") + case .focusPreviousGroup: t("menu.focus-previous-group") + case .nextTab: t("menu.next-tab") + case .previousTab: t("menu.previous-tab") + } + } +} diff --git a/Sources/MultishellAppUI/App/View+AppShortcut.swift b/Sources/MultishellAppUI/App/View+AppShortcut.swift deleted file mode 100644 index 7b6fd37c2..000000000 --- a/Sources/MultishellAppUI/App/View+AppShortcut.swift +++ /dev/null @@ -1,9 +0,0 @@ -import SwiftUI - -extension View { - /// The menu item's key equivalent. The surface's unbind is the other half, - /// and comes from the shortcut's place in `AppShortcutCatalogue.all`. - func keyboardShortcut(_ shortcut: AppShortcut) -> some View { - keyboardShortcut(shortcut.key, modifiers: shortcut.modifiers) - } -} diff --git a/Sources/MultishellAppUI/App/View+ShortcutCommand.swift b/Sources/MultishellAppUI/App/View+ShortcutCommand.swift new file mode 100644 index 000000000..f41f81a0f --- /dev/null +++ b/Sources/MultishellAppUI/App/View+ShortcutCommand.swift @@ -0,0 +1,12 @@ +import MultishellAppCore +import MultishellCore +import SwiftUI + +extension View { + /// The command's keys in force, none where it has none. The engine's unbind + /// is the other half, `AppModel.surfaceUnbinds`. + func keyboardShortcut(_ command: ShortcutCommand, in model: AppModel) -> some View { + let shortcut = model.menuShortcut(for: command) + return keyboardShortcut(shortcut.keys?.keyboardShortcut(isChanged: shortcut.isChanged)) + } +} diff --git a/Sources/MultishellAppUI/Dialogs/NewWorktree/NewWorktreeForm.swift b/Sources/MultishellAppUI/Dialogs/NewWorktree/NewWorktreeForm.swift index 2517d2df0..d9749c425 100644 --- a/Sources/MultishellAppUI/Dialogs/NewWorktree/NewWorktreeForm.swift +++ b/Sources/MultishellAppUI/Dialogs/NewWorktree/NewWorktreeForm.swift @@ -30,7 +30,7 @@ struct NewWorktreeForm: View { Form { if model.workspace.projects.isEmpty { NewWorktreeFormNote( - text: t("sheet.no-projects"), + text: t("sheet.no-projects", model.keysInParentheses(.addProject)), symbol: "folder.badge.plus", tint: .secondary, ) diff --git a/Sources/MultishellAppUI/Ghostty/Config/AppShortcut+Ghostty.swift b/Sources/MultishellAppUI/Ghostty/Config/AppShortcut+Ghostty.swift deleted file mode 100644 index 6be169caa..000000000 --- a/Sources/MultishellAppUI/Ghostty/Config/AppShortcut+Ghostty.swift +++ /dev/null @@ -1,30 +0,0 @@ -import SwiftUI - -extension AppShortcut { - /// The same combination as Ghostty spells it, in the modifier order its - /// own docs use, so this stays diffable against a config. - var ghosttyCombo: String { - var parts: [String] = [] - if modifiers.contains(.command) { parts.append("super") } - if modifiers.contains(.control) { parts.append("ctrl") } - if modifiers.contains(.option) { parts.append("alt") } - if modifiers.contains(.shift) { parts.append("shift") } - parts.append(Self.ghosttyName(of: key)) - return parts.joined(separator: "+") - } - - /// Ghostty names a few keys rather than taking their character. The arrows - /// arrive as the private-use scalars AppKit gives them. - private static func ghosttyName(of key: KeyEquivalent) -> String { - switch key.character { - case "\t": "tab" - case "\r": "enter" - case ",": "comma" - case KeyEquivalent.leftArrow.character: "left" - case KeyEquivalent.rightArrow.character: "right" - case KeyEquivalent.upArrow.character: "up" - case KeyEquivalent.downArrow.character: "down" - default: String(key.character) - } - } -} diff --git a/Sources/MultishellAppUI/Ghostty/Config/GhosttyAppLayer.swift b/Sources/MultishellAppUI/Ghostty/Config/GhosttyAppLayer.swift index ba7081cf1..2b1802736 100644 --- a/Sources/MultishellAppUI/Ghostty/Config/GhosttyAppLayer.swift +++ b/Sources/MultishellAppUI/Ghostty/Config/GhosttyAppLayer.swift @@ -3,7 +3,11 @@ import MultishellCore /// The layer the app hands libghostty on top of the user's files: the theme, /// the font, the keybinds it unbinds and the integration it leaves to ours. enum GhosttyAppLayer { - static func configuration(_ theme: Theme, _ appearance: Appearance) -> GhosttyConfigText { + static func configuration( + _ theme: Theme, + _ appearance: Appearance, + unbinding keys: [KeyCombination], + ) -> GhosttyConfigText { GhosttyConfigText { config in // libghostty takes no alpha, and drops a line it refuses without a word. func set(_ name: String, _ key: TerminalColorKey) { @@ -32,9 +36,9 @@ enum GhosttyAppLayer { // the engine injects nothing into a shell; see terminals/shell-integration.md. config.set("shell-integration", "none") - // Ghostty's defaults bind our shortcuts to actions this embedding - // cannot perform, so unbind exactly those. - for combo in GhosttyUnbinds.all { + // The menus' keys and the reserved ones, so the surface takes none before + // the menu bar or the system; Docs/design/shortcuts.md. + for combo in GhosttyUnbinds.all(unbinding: keys) { config.set("keybind", "\(combo)=unbind") } } diff --git a/Sources/MultishellAppUI/Ghostty/Config/GhosttyUnbinds.swift b/Sources/MultishellAppUI/Ghostty/Config/GhosttyUnbinds.swift index 244848f4d..914ff1210 100644 --- a/Sources/MultishellAppUI/Ghostty/Config/GhosttyUnbinds.swift +++ b/Sources/MultishellAppUI/Ghostty/Config/GhosttyUnbinds.swift @@ -1,21 +1,16 @@ +import MultishellCore + /// What the terminal surface is told to unbind: shortcuts it would eat before /// the menu bar or the system sees them, and plain keys the program needs. enum GhosttyUnbinds { - /// Hides the Dock. Listed so nothing here claims it, and so the reason Move - /// Tab to New Group is not on it stays written down. - private static let dockToggle = "super+alt+d" - - /// Combinations the system owns over one of our windows. No menu item of - /// ours carries these, and the surface must still give them up. - static let systemOwned = [ - "super+shift+n", "super+comma", "super+q", "super+ctrl+f", "super+enter", dockToggle, - ] - /// Ghostty bindings on plain keys, released so the key reaches the program: /// its performable `esc=end_search` ate Escape under our bar; terminals/find.md. static let surfaceReleases = ["escape"] - static let all: [String] = - AppShortcutCatalogue.all.filter { !$0.surfaceKeepsBinding }.map(\.ghosttyCombo) + systemOwned - + surfaceReleases + /// The menus' keys, then every reserved combination, which no menu item of + /// ours carries and the surface must still give up, then the releases. + static func all(unbinding keys: [KeyCombination]) -> [String] { + let reserved = ReservedShortcut.allCases.map(\.combination) + return (keys + reserved).flatMap(\.ghosttyTriggers).uniqued(by: \.self) + surfaceReleases + } } diff --git a/Sources/MultishellAppUI/Ghostty/Config/KeyCombination+Ghostty.swift b/Sources/MultishellAppUI/Ghostty/Config/KeyCombination+Ghostty.swift new file mode 100644 index 000000000..ffb6370f0 --- /dev/null +++ b/Sources/MultishellAppUI/Ghostty/Config/KeyCombination+Ghostty.swift @@ -0,0 +1,60 @@ +import MultishellCore + +extension KeyCombination { + /// Ghostty's W3C names for punctuation. A name binds the physical key and a + /// character the one typed; its defaults use both, so both are unbound. + private static let ghosttyPunctuationNames: [Character: String] = [ + "`": "backquote", "-": "minus", "=": "equal", "[": "bracket_left", "]": "bracket_right", + "\\": "backslash", ";": "semicolon", "'": "quote", ",": "comma", ".": "period", "/": "slash", + ] + + /// Ghostty reads it as the step between a sequence's keys, so no trigger + /// names that key; nothing Ghostty binds by default is on it. + private static let sequenceStep: Character = ">" + + /// Each keybind trigger Ghostty could hold the combination under, in its docs' + /// modifier order; Docs/design/shortcuts.md says why punctuation has two. + var ghosttyTriggers: [String] { + var parts: [String] = [] + if modifiers.contains(.command) { parts.append("super") } + if modifiers.contains(.control) { parts.append("ctrl") } + if modifiers.contains(.option) { parts.append("alt") } + if modifiers.contains(.shift) { parts.append("shift") } + let prefix = parts.map { $0 + "+" }.joined() + return Self.ghosttyKeyNames(of: key).map { prefix + $0 } + } + + /// The physical key's name, which a binding may use in place of the character. + private static func w3cName(of character: Character) -> String? { + if let punctuation = ghosttyPunctuationNames[character] { return punctuation } + guard character.isASCII else { return nil } + if character.isNumber { return "digit_\(character)" } + return character.isLetter ? "key_\(character)" : nil + } + + // One case a key, exhaustive so a new key cannot go unspelled. + // swiftlint:disable:next cyclomatic_complexity + private static func ghosttyKeyNames(of key: ShortcutKey) -> [String] { + switch key { + case .character(sequenceStep): [] + + case .character(let character): + [String(character)] + (w3cName(of: character).map { [$0] } ?? []) + + case .function(let number): ["f\(number)"] + case .tab: ["tab"] + case .returnKey: ["enter"] + case .space: ["space"] + case .backspace: ["backspace"] + case .forwardDelete: ["delete"] + case .home: ["home"] + case .end: ["end"] + case .pageUp: ["page_up"] + case .pageDown: ["page_down"] + case .leftArrow: ["left"] + case .rightArrow: ["right"] + case .upArrow: ["up"] + case .downArrow: ["down"] + } + } +} diff --git a/Sources/MultishellAppUI/Ghostty/GhosttyTerminalHost.swift b/Sources/MultishellAppUI/Ghostty/GhosttyTerminalHost.swift index 39fe79d5a..9c9aade4d 100644 --- a/Sources/MultishellAppUI/Ghostty/GhosttyTerminalHost.swift +++ b/Sources/MultishellAppUI/Ghostty/GhosttyTerminalHost.swift @@ -183,8 +183,8 @@ final class GhosttyTerminalHost: NSObject, TerminalSurfaceHost { views[id]?.performBindingAction(GhosttySearchActions.action(for: step)) ?? false } - func apply(_ theme: Theme, appearance: Appearance) { - lazyRuntime.apply(theme, appearance: appearance) + func apply(_ theme: Theme, appearance: Appearance, unbinding keys: [KeyCombination]) { + lazyRuntime.apply(theme, appearance: appearance, unbinding: keys) } /// A turn later, and only while still true: a frame raises this inside diff --git a/Sources/MultishellAppUI/Ghostty/Runtime/LazyGhosttyRuntime.swift b/Sources/MultishellAppUI/Ghostty/Runtime/LazyGhosttyRuntime.swift index 126bc96c6..2905524ea 100644 --- a/Sources/MultishellAppUI/Ghostty/Runtime/LazyGhosttyRuntime.swift +++ b/Sources/MultishellAppUI/Ghostty/Runtime/LazyGhosttyRuntime.swift @@ -25,8 +25,8 @@ final class LazyGhosttyRuntime { self.readBase = readBase } - func apply(_ theme: Theme, appearance: Appearance) { - let layer = GhosttyAppLayer.configuration(theme, appearance) + func apply(_ theme: Theme, appearance: Appearance, unbinding keys: [KeyCombination]) { + let layer = GhosttyAppLayer.configuration(theme, appearance, unbinding: keys) latestAppLayer = (layer, theme.isDark) builtRuntime?.apply(appLayer: layer) builtRuntime?.setColorScheme(isDark: theme.isDark) diff --git a/Sources/MultishellAppUI/Platform/MacPlatform+MenuShortcuts.swift b/Sources/MultishellAppUI/Platform/MacPlatform+MenuShortcuts.swift new file mode 100644 index 000000000..c103fe15e --- /dev/null +++ b/Sources/MultishellAppUI/Platform/MacPlatform+MenuShortcuts.swift @@ -0,0 +1,47 @@ +import AppKit +import MultishellAppCore +import MultishellCore + +/// SwiftUI does not reliably redraw a menu bar's `Commands` (MultishellCommands), +/// so a change of keys is also set on the items here, found by title. +extension MacPlatform { + /// Services, Window and Help list other apps' and windows' titles, which + /// may match a command's. + static func setMenuShortcuts( + _ shortcuts: [MenuShortcut], + in menu: NSMenu, + leavingOut menusMacOSFills: [NSMenu] = [], + ) { + let byTitle = Dictionary( + shortcuts.map { ($0.command.menuTitle, $0) }, + uniquingKeysWith: { first, _ in first }, + ) + setKeys(byTitle, in: menu, leavingOut: menusMacOSFills) + } + + private static func setKeys( + _ byTitle: [String: MenuShortcut], + in menu: NSMenu, + leavingOut menusMacOSFills: [NSMenu], + ) { + for item in menu.items { + if let submenu = item.submenu { + // Theme names are the user's own and may match a command's title. + let isThemePicker = item.title == t("menu.theme") + guard !isThemePicker, !menusMacOSFills.contains(where: { $0 === submenu }) else { continue } + setKeys(byTitle, in: submenu, leavingOut: menusMacOSFills) + continue + } + guard let shortcut = byTitle[item.title] else { continue } + item.keyEquivalent = shortcut.keys.map { String($0.menuKeyCharacter) } ?? "" + item.keyEquivalentModifierMask = shortcut.keys?.modifiers.modifierFlags ?? [] + item.allowsAutomaticKeyEquivalentLocalization = !shortcut.isChanged + } + } + + func setMenuShortcuts(_ shortcuts: [MenuShortcut]) { + guard let bar = NSApp.mainMenu else { return } + let menusMacOSFills = [NSApp.servicesMenu, NSApp.windowsMenu, NSApp.helpMenu] + Self.setMenuShortcuts(shortcuts, in: bar, leavingOut: menusMacOSFills.compactMap(\.self)) + } +} diff --git a/Sources/MultishellAppUI/Resources/en.lproj/Localizable.strings b/Sources/MultishellAppUI/Resources/en.lproj/Localizable.strings index 99988488b..9964f58f5 100644 --- a/Sources/MultishellAppUI/Resources/en.lproj/Localizable.strings +++ b/Sources/MultishellAppUI/Resources/en.lproj/Localizable.strings @@ -40,7 +40,7 @@ "agents.auto-start-create" = "Auto-start on worktree creation"; "agents.auto-start-create-info" = "Turns on Start an agent in the New Worktree sheet, so a new worktree's first tab runs the agent. Any project can override this."; "agents.auto-start-tab" = "Auto-start on tab open"; -"agents.auto-start-tab-info" = "New Tab (⌘T), and the first tab of a worktree you turn to, run the agent instead of a shell. New Shell Tab (⇧⌘T) and splits stay shells."; +"agents.auto-start-tab-info" = "New Tab%1$@, and the first tab of a worktree you turn to, run the agent instead of a shell. New Shell Tab%2$@ and splits stay shells."; "agents.command-info" = "Run as typed through your login shell when an agent tab opens. Placeholders such as {{branch}} are filled in from the worktree."; "agents.command-line-tool" = "Command line tool"; "agents.command-prompt" = "my-agent --flag"; @@ -182,7 +182,7 @@ "general.editor" = "Editor:"; "general.editor-command-info" = "Run as a new tab in the worktree through your login shell. {path} is the worktree's path, or a text file's whose link you clicked, inside quotes or out, and is appended if absent."; "general.editor-command-prompt" = "code-insiders {path}"; -"general.editor-info" = "What Open in Editor (⇧⌘O) and a ⌘-clicked text file's link use. Found by bundle identifier, or by a command on the login shell's PATH; a terminal editor opens as a new tab."; +"general.editor-info" = "What Open in Editor%@ and a ⌘-clicked text file's link use. Found by bundle identifier, or by a command on the login shell's PATH; a terminal editor opens as a new tab."; "general.section-editor" = "Open in Editor"; "general.section-files-panel" = "Files Panel"; "general.section-storage" = "Storage"; @@ -291,7 +291,7 @@ "project.override-same" = "Same"; "project.override-start" = "Override"; "project.preferred-agent" = "Preferred agent"; -"project.preferred-agent-info" = "New Agent Tab (⌥⌘T) in this project's worktrees starts this agent instead of the global one. None opts the project out."; +"project.preferred-agent-info" = "New Agent Tab%@ in this project's worktrees starts this agent instead of the global one. None opts the project out."; "project.refresh-from-git" = "Refresh from git"; "project.remove-info" = "Takes the project out of the sidebar and closes its terminals, after asking. Nothing on disk is touched."; "project.repository" = "Repository:"; @@ -361,6 +361,11 @@ "settings.part-title" = "%1$@ › %2$@"; "settings.scope" = "Show settings for"; "settings.search" = "Search"; +"settings.shortcuts" = "Shortcuts"; +"settings.shortcuts-edit" = "Edit"; +"settings.shortcuts-file" = "File"; +"settings.shortcuts-terminal" = "Terminal"; +"settings.shortcuts-view" = "View"; "settings.terminal" = "Terminal"; "settings.worktrees" = "Worktrees"; "sheet.agent" = "Agent:"; @@ -377,12 +382,96 @@ "sheet.new-branch" = "New branch"; "sheet.new-worktree" = "New Worktree"; "sheet.no-commits" = "This repository has no commits yet. A worktree needs a commit to start from; make the first one, then come back."; -"sheet.no-projects" = "No projects yet. Add a repository first (⌘O)."; +"sheet.no-projects" = "No projects yet. Add a repository first%@."; "sheet.project" = "Project:"; "sheet.start-agent" = "Start an agent:"; "sheet.task" = "Task:"; "sheet.task-prompt" = "Optional"; -"sidebar.add-project" = "Add Project (⌘O)"; +"shortcuts.change-help" = "Type new keys for %@"; +"shortcuts.column-default" = "Default"; +"shortcuts.column-yours" = "Yours"; +"shortcuts.default-taken" = "%1$@ is %2$@ now, so this has no shortcut."; +"shortcuts.fixed" = "Fixed"; +"shortcuts.group-close" = "Close"; +"shortcuts.group-edit" = "Edit"; +"shortcuts.group-edit-info" = "These keep the keys every Mac app gives them. In a pane Cut, Copy and Paste are the terminal's own copy and paste."; +"shortcuts.group-files-panel" = "Files Panel"; +"shortcuts.group-find" = "Find"; +"shortcuts.group-groups" = "Groups"; +"shortcuts.group-new" = "New"; +"shortcuts.group-panes" = "Panes"; +"shortcuts.group-show" = "Show"; +"shortcuts.group-tabs" = "Tabs"; +"shortcuts.in-parentheses" = " (%@)"; +"shortcuts.none" = "None"; +"shortcuts.recording-hint" = "Esc cancels, ⌫ removes the shortcut."; +"shortcuts.refused-edits-text" = "These keys move, select or delete in every text field. Add ⌥, or a different modifier."; +"shortcuts.refused-fixed" = "%1$@ is %2$@, which cannot change."; +"shortcuts.refused-needs-modifier" = "A shortcut needs ⌘, ⌃ or ⌥, unless it is an F-key."; +"shortcuts.refused-option-character" = "⌥ with a character types a character on many layouts. Add ⌘ or ⌃."; +"shortcuts.refused-option-edits-text" = "⌥ with this key moves, deletes or breaks a line in every text field. Add ⌘ or ⌃."; +"shortcuts.refused-program-key" = "%@ belongs to the program in a pane, so it cannot be used here."; +"shortcuts.refused-reserved" = "%1$@ is %2$@, so it cannot be used here."; +"shortcuts.replace" = "Replace"; +"shortcuts.reserved-accessibility-shortcuts" = "the Accessibility Shortcuts panel"; +"shortcuts.reserved-app-switcher" = "the app switcher"; +"shortcuts.reserved-app-switcher-backwards" = "the app switcher, backwards"; +"shortcuts.reserved-app-windows" = "the app's windows"; +"shortcuts.reserved-cancel" = "Cancel"; +"shortcuts.reserved-dock-hiding" = "the Dock's hiding"; +"shortcuts.reserved-emoji-and-symbols" = "Emoji & Symbols"; +"shortcuts.reserved-finder-search" = "a Finder search"; +"shortcuts.reserved-full-screen" = "Enter Full Screen"; +"shortcuts.reserved-help-search" = "the Help menu's search"; +"shortcuts.reserved-hide" = "Hide Multishell"; +"shortcuts.reserved-hide-others" = "Hide Others"; +"shortcuts.reserved-lock-screen" = "Lock Screen"; +"shortcuts.reserved-log-out" = "Log Out"; +"shortcuts.reserved-log-out-now" = "Log Out without asking"; +"shortcuts.reserved-look-up" = "Look Up"; +"shortcuts.reserved-minimize" = "Minimize"; +"shortcuts.reserved-minimize-all" = "Minimize All"; +"shortcuts.reserved-mission-control" = "Mission Control"; +"shortcuts.reserved-new-window" = "kept by macOS"; +"shortcuts.reserved-next-input-source" = "the next input source"; +"shortcuts.reserved-previous-input-source" = "the previous input source"; +"shortcuts.reserved-quit" = "Quit Multishell"; +"shortcuts.reserved-screenshot" = "a screenshot"; +"shortcuts.reserved-screenshot-of-area" = "a screenshot of an area"; +"shortcuts.reserved-screenshot-of-area-to-clipboard" = "a screenshot of an area to the clipboard"; +"shortcuts.reserved-screenshot-to-clipboard" = "a screenshot to the clipboard"; +"shortcuts.reserved-screenshot-tools" = "the screenshot tools"; +"shortcuts.reserved-send" = "a review comment's Send"; +"shortcuts.reserved-settings" = "Settings"; +"shortcuts.reserved-show-all-tabs" = "Show All Tabs"; +"shortcuts.reserved-space-left" = "the Space to the left"; +"shortcuts.reserved-space-right" = "the Space to the right"; +"shortcuts.reserved-spotlight" = "Spotlight"; +"shortcuts.reserved-voice-over" = "VoiceOver"; +"shortcuts.reserved-window-cycling" = "the next window"; +"shortcuts.reserved-window-cycling-backwards" = "the previous window"; +"shortcuts.reset-help" = "Back to the default, %@"; +"shortcuts.restore" = "Restore"; +"shortcuts.restore-defaults" = "Restore Defaults"; +"shortcuts.restore-question" = "Restore every shortcut?"; +"shortcuts.shell-back-one-character" = "back one character"; +"shortcuts.shell-clear-screen" = "clear screen"; +"shortcuts.shell-delete-line" = "delete line"; +"shortcuts.shell-delete-to-end-of-line" = "delete to end of line"; +"shortcuts.shell-delete-word" = "delete word"; +"shortcuts.shell-end-of-line" = "end of line"; +"shortcuts.shell-forward-one-character" = "forward one character"; +"shortcuts.shell-history-search" = "history search"; +"shortcuts.shell-next-command" = "next command"; +"shortcuts.shell-paste-deleted" = "paste of deleted text"; +"shortcuts.shell-previous-command" = "previous command"; +"shortcuts.shell-start-of-line" = "start of line"; +"shortcuts.shell-swap-characters" = "swap of two characters"; +"shortcuts.taken" = "%1$@ is %2$@. Replace leaves %2$@ with no shortcut."; +"shortcuts.type" = "Type shortcut"; +"shortcuts.warning" = "Programs in a pane no longer get %@."; +"shortcuts.warning-shell" = "Programs in a pane no longer get %1$@, the shell's %2$@."; +"sidebar.add-project" = "Add Project%@"; "sidebar.auto-rename-failed" = "Auto Rename failed: %@\nClick to clear."; "sidebar.auto-renaming" = "Auto Rename is asking the agent for a name"; "sidebar.clear-filter" = "Clear filter"; diff --git a/Sources/MultishellAppUI/Settings/AppWide/AppAgentSettingsPage.swift b/Sources/MultishellAppUI/Settings/AppWide/AppAgentSettingsPage.swift index b193bdc04..ae4cf6943 100644 --- a/Sources/MultishellAppUI/Settings/AppWide/AppAgentSettingsPage.swift +++ b/Sources/MultishellAppUI/Settings/AppWide/AppAgentSettingsPage.swift @@ -45,7 +45,11 @@ struct AppAgentSettingsPage: View { } InfoToggle( t("agents.auto-start-tab"), - info: t("agents.auto-start-tab-info"), + info: t( + "agents.auto-start-tab-info", + model.keysInParentheses(.newTab), + model.keysInParentheses(.newShellTab), + ), isOn: model.settingBinding(\.autoStartsAgent, write: model.setAutoStartsAgent), ) .disabled(!model.hasPreferredAgent) diff --git a/Sources/MultishellAppUI/Settings/AppWide/AppGeneralPage.swift b/Sources/MultishellAppUI/Settings/AppWide/AppGeneralPage.swift index 58f5287be..dfb09310e 100644 --- a/Sources/MultishellAppUI/Settings/AppWide/AppGeneralPage.swift +++ b/Sources/MultishellAppUI/Settings/AppWide/AppGeneralPage.swift @@ -19,7 +19,7 @@ struct AppGeneralPage: View { ), options: model.editorDetection.options(selected:), refreshing: model, - info: t("general.editor-info"), + info: t("general.editor-info", model.keysInParentheses(.openInEditor)), ) if model.usesCustomEditor { CustomChoiceField( diff --git a/Sources/MultishellAppUI/Settings/AppWide/Shortcuts/AppShortcutsPage.swift b/Sources/MultishellAppUI/Settings/AppWide/Shortcuts/AppShortcutsPage.swift new file mode 100644 index 000000000..1b0f0c4cf --- /dev/null +++ b/Sources/MultishellAppUI/Settings/AppWide/Shortcuts/AppShortcutsPage.swift @@ -0,0 +1,28 @@ +import MultishellAppCore +import MultishellCore +import SwiftUI + +/// Settings > Shortcuts, one part per menu: a card per group of commands, each +/// beside its default keys; Docs/design/shortcuts.md. +struct AppShortcutsPage: View { + let model: AppModel + let section: SettingsSection + + var body: some View { + SettingsForm { + ForEach(ShortcutGroup.groups(in: section), id: \.self) { group in + OverrideTable( + group.title, + info: group.info, + columnTitles: (t("shortcuts.column-default"), t("shortcuts.column-yours")), + ) { + ForEach(group.commands, id: \.self) { command in + ShortcutRow(model: model, command: command) + } + } + } + } + // Another part, or a closed window, ends a row's recording or question. + .onDisappear { model.endShortcutsPageEdit() } + } +} diff --git a/Sources/MultishellAppUI/Settings/AppWide/Shortcuts/ReservedShortcut+Use.swift b/Sources/MultishellAppUI/Settings/AppWide/Shortcuts/ReservedShortcut+Use.swift new file mode 100644 index 000000000..9adc3310b --- /dev/null +++ b/Sources/MultishellAppUI/Settings/AppWide/Shortcuts/ReservedShortcut+Use.swift @@ -0,0 +1,46 @@ +import MultishellCore + +extension ReservedShortcut { + /// What the keys do now, as a refusal names it: "⌘Q is Quit Multishell". + var use: String { + switch self { + case .quit: t("shortcuts.reserved-quit") + case .hide: t("shortcuts.reserved-hide") + case .hideOthers: t("shortcuts.reserved-hide-others") + case .minimize: t("shortcuts.reserved-minimize") + case .minimizeAll: t("shortcuts.reserved-minimize-all") + case .voiceOver: t("shortcuts.reserved-voice-over") + case .accessibilityShortcuts: t("shortcuts.reserved-accessibility-shortcuts") + case .lookUp: t("shortcuts.reserved-look-up") + case .settings: t("shortcuts.reserved-settings") + case .dockHiding: t("shortcuts.reserved-dock-hiding") + case .fullScreen: t("shortcuts.reserved-full-screen") + case .appSwitcher: t("shortcuts.reserved-app-switcher") + case .cancel: t("shortcuts.reserved-cancel") + case .appSwitcherBackwards: t("shortcuts.reserved-app-switcher-backwards") + case .spotlight: t("shortcuts.reserved-spotlight") + case .windowCycling: t("shortcuts.reserved-window-cycling") + case .windowCyclingBackwards: t("shortcuts.reserved-window-cycling-backwards") + case .newWindow: t("shortcuts.reserved-new-window") + case .send: t("shortcuts.reserved-send") + case .lockScreen: t("shortcuts.reserved-lock-screen") + case .logOut: t("shortcuts.reserved-log-out") + case .logOutNow: t("shortcuts.reserved-log-out-now") + case .screenshot: t("shortcuts.reserved-screenshot") + case .screenshotOfArea: t("shortcuts.reserved-screenshot-of-area") + case .screenshotTools: t("shortcuts.reserved-screenshot-tools") + case .screenshotToClipboard: t("shortcuts.reserved-screenshot-to-clipboard") + case .screenshotOfAreaToClipboard: t("shortcuts.reserved-screenshot-of-area-to-clipboard") + case .spaceLeft: t("shortcuts.reserved-space-left") + case .spaceRight: t("shortcuts.reserved-space-right") + case .missionControl: t("shortcuts.reserved-mission-control") + case .appWindows: t("shortcuts.reserved-app-windows") + case .finderSearch: t("shortcuts.reserved-finder-search") + case .previousInputSource: t("shortcuts.reserved-previous-input-source") + case .nextInputSource: t("shortcuts.reserved-next-input-source") + case .emojiAndSymbols: t("shortcuts.reserved-emoji-and-symbols") + case .helpSearch: t("shortcuts.reserved-help-search") + case .showAllTabs: t("shortcuts.reserved-show-all-tabs") + } + } +} diff --git a/Sources/MultishellAppUI/Settings/AppWide/Shortcuts/ShellKeyUse+Name.swift b/Sources/MultishellAppUI/Settings/AppWide/Shortcuts/ShellKeyUse+Name.swift new file mode 100644 index 000000000..30d22d42f --- /dev/null +++ b/Sources/MultishellAppUI/Settings/AppWide/Shortcuts/ShellKeyUse+Name.swift @@ -0,0 +1,22 @@ +import MultishellAppCore + +extension ShellKeyUse { + /// Read mid-sentence: "the shell's history search". + var name: String { + switch self { + case .startOfLine: t("shortcuts.shell-start-of-line") + case .backOneCharacter: t("shortcuts.shell-back-one-character") + case .endOfLine: t("shortcuts.shell-end-of-line") + case .forwardOneCharacter: t("shortcuts.shell-forward-one-character") + case .deleteToEndOfLine: t("shortcuts.shell-delete-to-end-of-line") + case .clearScreen: t("shortcuts.shell-clear-screen") + case .nextCommand: t("shortcuts.shell-next-command") + case .previousCommand: t("shortcuts.shell-previous-command") + case .historySearch: t("shortcuts.shell-history-search") + case .swapCharacters: t("shortcuts.shell-swap-characters") + case .deleteLine: t("shortcuts.shell-delete-line") + case .deleteWord: t("shortcuts.shell-delete-word") + case .pasteDeleted: t("shortcuts.shell-paste-deleted") + } + } +} diff --git a/Sources/MultishellAppUI/Settings/AppWide/Shortcuts/ShortcutGroup+Title.swift b/Sources/MultishellAppUI/Settings/AppWide/Shortcuts/ShortcutGroup+Title.swift new file mode 100644 index 000000000..92e1195c2 --- /dev/null +++ b/Sources/MultishellAppUI/Settings/AppWide/Shortcuts/ShortcutGroup+Title.swift @@ -0,0 +1,22 @@ +import MultishellAppCore + +extension ShortcutGroup { + var title: String { + switch self { + case .newItems: t("shortcuts.group-new") + case .closeItems: t("shortcuts.group-close") + case .editing: t("shortcuts.group-edit") + case .find: t("shortcuts.group-find") + case .show: t("shortcuts.group-show") + case .filesPanel: t("shortcuts.group-files-panel") + case .panes: t("shortcuts.group-panes") + case .groups: t("shortcuts.group-groups") + case .tabs: t("shortcuts.group-tabs") + } + } + + /// Help behind the card title's (i), where its rows need some. + var info: String? { + self == .editing ? t("shortcuts.group-edit-info") : nil + } +} diff --git a/Sources/MultishellAppUI/Settings/AppWide/Shortcuts/ShortcutKeysButton.swift b/Sources/MultishellAppUI/Settings/AppWide/Shortcuts/ShortcutKeysButton.swift new file mode 100644 index 000000000..2efb3f212 --- /dev/null +++ b/Sources/MultishellAppUI/Settings/AppWide/Shortcuts/ShortcutKeysButton.swift @@ -0,0 +1,20 @@ +import SwiftUI + +/// A changed command's keys on the control face; a click records new ones. +struct ShortcutKeysButton: View { + let text: String + let help: String + let record: () -> Void + + var body: some View { + Button(action: record) { + Text(text) + .shortcutKeysFace() + .settingsControlFace() + .contentShape(.rect) + } + .buttonStyle(.plain) + .help(help) + .accessibilityLabel(help) + } +} diff --git a/Sources/MultishellAppUI/Settings/AppWide/Shortcuts/ShortcutRecorder.swift b/Sources/MultishellAppUI/Settings/AppWide/Shortcuts/ShortcutRecorder.swift new file mode 100644 index 000000000..29888ccac --- /dev/null +++ b/Sources/MultishellAppUI/Settings/AppWide/Shortcuts/ShortcutRecorder.swift @@ -0,0 +1,38 @@ +import AppKit +import MultishellCore +import SwiftUI + +/// The Yours cell while a row records: the modifiers pressed so far, or a prompt. +/// It ends when the row's step changes, which takes the view and its monitor away. +struct ShortcutRecorder: View { + let take: (ShortcutRecorderInput) -> Void + + @State private var pressedModifiers: ShortcutModifiers = [] + @State private var monitor: ShortcutRecorderMonitor? + + var body: some View { + Text(pressedModifiers.isEmpty ? t("shortcuts.type") : pressedModifiers.glyphs) + .shortcutKeysFace() + .background(SettingsColors.control, in: .rect(cornerRadius: UIMetrics.settingsControlRadius)) + .overlay { + RoundedRectangle(cornerRadius: UIMetrics.settingsControlRadius) + .strokeBorder(.tint, lineWidth: 2) + } + .accessibilityLabel(t("shortcuts.type")) + .onAppear { + monitor = ShortcutRecorderMonitor( + windowNumber: NSApp.keyWindow?.windowNumber, + onKey: receive, + ) { take(.cancel) } + } + .onDisappear { monitor = nil } + } + + private func receive(_ event: NSEvent) { + if event.type == .flagsChanged { + pressedModifiers = ShortcutModifiers(event.modifierFlags) + return + } + take(ShortcutRecorderInput(event)) + } +} diff --git a/Sources/MultishellAppUI/Settings/AppWide/Shortcuts/ShortcutRecorderInput.swift b/Sources/MultishellAppUI/Settings/AppWide/Shortcuts/ShortcutRecorderInput.swift new file mode 100644 index 000000000..8db784830 --- /dev/null +++ b/Sources/MultishellAppUI/Settings/AppWide/Shortcuts/ShortcutRecorderInput.swift @@ -0,0 +1,63 @@ +import AppKit +import MultishellCore + +/// What a key press means to a Shortcuts row that is recording. +enum ShortcutRecorderInput: Equatable { + case cancel + /// Delete with no modifier pressed: the command keeps its menu item and no keys. + case clear + /// A key no shortcut can be: keypad Enter, Help, F21 and up, or a dead key. + case ignored + case keys(KeyCombination) + + /// The keys that type no character, by what the menus store them as, Delete + /// also arriving as 0x7F. + private static let namedKeysByCharacter: [Int: ShortcutKey] = { + var keys: [Int: ShortcutKey] = [0x7F: .backspace] + for key in ShortcutKey.namedKeys { + guard let scalar = KeyCombination(key).menuKeyCharacter.unicodeScalars.first else { continue } + keys[Int(scalar.value)] = key + } + return keys + }() + private static let escape = 0x1B + + /// The key comes as the layout types it with no modifier pressed, as a menu's key + /// equivalent matches it, so ⇧⌘[ is `[` with Shift, not `{`. + init(_ event: NSEvent) { + guard event.type == .keyDown, let scalar = Self.unshiftedKey(of: event) else { + self = .ignored + return + } + let modifiers = ShortcutModifiers(event.modifierFlags) + let value = Int(scalar.value) + if value == Self.escape { + self = .cancel + } else if let named = Self.namedKeysByCharacter[value] { + self = + named == .backspace && modifiers.isEmpty ? .clear : .keys(KeyCombination(named, modifiers)) + } else if let number = Self.functionNumber(value) { + self = .keys(KeyCombination(.function(number), modifiers)) + } else if KeyCombination.isTypable(Character(scalar)) { + self = .keys(KeyCombination(.character(Character(scalar)), modifiers)) + } else { + self = .ignored + } + } + + /// The layout's translation gives an F-key or an arrow as a control code; + /// AppKit's own character for it is the private-use one the menus use. + private static func unshiftedKey(of event: NSEvent) -> UnicodeScalar? { + if let named = event.charactersIgnoringModifiers?.unicodeScalars.first, + named.properties.generalCategory == .privateUse + { + return named + } + return event.characters(byApplyingModifiers: [])?.unicodeScalars.first + } + + private static func functionNumber(_ value: Int) -> Int? { + let number = value - NSF1FunctionKey + 1 + return ShortcutKey.functionNumbers.contains(number) ? number : nil + } +} diff --git a/Sources/MultishellAppUI/Settings/AppWide/Shortcuts/ShortcutRecorderMonitor.swift b/Sources/MultishellAppUI/Settings/AppWide/Shortcuts/ShortcutRecorderMonitor.swift new file mode 100644 index 000000000..d7e6dda88 --- /dev/null +++ b/Sources/MultishellAppUI/Settings/AppWide/Shortcuts/ShortcutRecorderMonitor.swift @@ -0,0 +1,41 @@ +import AppKit + +/// Takes keys in the recorder's window before the menus do, so ⌘W records ⌘W; a +/// click, or a key in another window, ends recording and goes on as usual. +@MainActor +final class ShortcutRecorderMonitor { + private static let clicks: Set = [ + .leftMouseDown, .rightMouseDown, .otherMouseDown, + ] + + private var monitor: Any? + + init(windowNumber: Int?, onKey: @escaping (NSEvent) -> Void, onEnd: @escaping () -> Void) { + monitor = NSEvent.addLocalMonitorForEvents(matching: [ + .keyDown, .flagsChanged, .leftMouseDown, .rightMouseDown, .otherMouseDown, + ]) { + event in + // A local monitor runs on the main thread, where the event already is. + nonisolated(unsafe) let event = event + let isTaken = MainActor.assumeIsolated { + guard !Self.clicks.contains(event.type), + Self.isTyped(event, inWindowNumbered: windowNumber) + else { + onEnd() + return false + } + onKey(event) + return true + } + return isTaken ? nil : event + } + } + + static func isTyped(_ event: NSEvent, inWindowNumbered windowNumber: Int?) -> Bool { + event.windowNumber == windowNumber + } + + isolated deinit { + if let monitor { NSEvent.removeMonitor(monitor) } + } +} diff --git a/Sources/MultishellAppUI/Settings/AppWide/Shortcuts/ShortcutRefusal+Text.swift b/Sources/MultishellAppUI/Settings/AppWide/Shortcuts/ShortcutRefusal+Text.swift new file mode 100644 index 000000000..dedc1b6f8 --- /dev/null +++ b/Sources/MultishellAppUI/Settings/AppWide/Shortcuts/ShortcutRefusal+Text.swift @@ -0,0 +1,21 @@ +import MultishellAppCore +import MultishellCore + +extension ShortcutRefusal { + var text: String { + switch self { + case .editsText: t("shortcuts.refused-edits-text") + case .needsModifier: t("shortcuts.refused-needs-modifier") + case .optionEditsText: t("shortcuts.refused-option-edits-text") + case .optionTypesCharacter: t("shortcuts.refused-option-character") + + case .reserved(let reserved): + t("shortcuts.refused-reserved", reserved.combination.glyphs, reserved.use) + + case .programKey(let keys): t("shortcuts.refused-program-key", keys.glyphs) + + case .heldByFixed(let command): + t("shortcuts.refused-fixed", command.defaultCombination.glyphs, command.menuTitle) + } + } +} diff --git a/Sources/MultishellAppUI/Settings/AppWide/Shortcuts/ShortcutRow.swift b/Sources/MultishellAppUI/Settings/AppWide/Shortcuts/ShortcutRow.swift new file mode 100644 index 000000000..824b3db15 --- /dev/null +++ b/Sources/MultishellAppUI/Settings/AppWide/Shortcuts/ShortcutRow.swift @@ -0,0 +1,108 @@ +import MultishellAppCore +import MultishellCore +import SwiftUI + +/// A command's row on the Shortcuts page: its menu title, its default keys, +/// and the user's, recorded in place. What a key does is the model's to say. +struct ShortcutRow: View { + let model: AppModel + let command: ShortcutCommand + + var body: some View { + let isChanged = model.isShortcutChanged(command) + VStack(alignment: .leading, spacing: 4) { + OverrideColumns { + Text(command.menuTitle) + .fontWeight(isChanged ? .semibold : .regular) + } global: { + Text(command.defaultCombination.glyphs) + .foregroundStyle(SettingsColors.secondaryText) + } override: { + yours(isChanged: isChanged) + } + notes + } + } + + private var step: ShortcutEditing.Step? { + model.shortcutEditingStep(for: command) + } + + @ViewBuilder private var notes: some View { + switch step { + case .recording(let refusal): + if let refusal { note(refusal.text, color: .red) } + note(t("shortcuts.recording-hint"), color: SettingsColors.secondaryText) + + case .confirming(let keys, let holder): + HStack(spacing: 8) { + note(t("shortcuts.taken", keys.glyphs, holder.menuTitle), color: .orange) + Spacer(minLength: 0) + Button(t("action.cancel"), action: model.endShortcutsPageEdit) + Button(t("shortcuts.replace"), action: model.replaceAskedShortcut) + .buttonStyle(.borderedProminent) + } + + case nil: + if let warning = model.shortcutWarning(for: command) { note(warning.text, color: .orange) } + if let holder = model.commandHoldingDefault(of: command) { + note( + t("shortcuts.default-taken", command.defaultCombination.glyphs, holder.menuTitle), + color: .orange, + ) + } + } + } + + @ViewBuilder + private func yours(isChanged: Bool) -> some View { + if command.isFixed { + Label(t("shortcuts.fixed"), systemImage: "lock") + .font(.system(size: UIMetrics.settingsControlTextSize)) + .foregroundStyle(SettingsColors.secondaryText) + } else if case .recording = step { + ShortcutRecorder(take: take) + } else if case .confirming(let keys, _) = step { + Text(keys.glyphs) + .shortcutKeysFace() + .foregroundStyle(SettingsColors.secondaryText) + } else if isChanged { + ShortcutKeysButton( + text: model.shortcutKeys(for: command)?.glyphs ?? t("shortcuts.none"), + help: t("shortcuts.change-help", command.menuTitle), + record: startRecording, + ) + SettingsSymbolButton( + symbol: "arrow.uturn.backward", + help: t("shortcuts.reset-help", command.defaultCombination.glyphs), + ) { + model.resetShortcut(command) + } + } else { + OverrideStartButton( + help: t("shortcuts.change-help", command.menuTitle), + start: startRecording, + ) + } + } + + private func note(_ text: String, color: Color) -> some View { + Text(text) + .font(.system(size: UIMetrics.settingsSmallTextSize)) + .foregroundStyle(color) + .fixedSize(horizontal: false, vertical: true) + } + + private func startRecording() { + model.startRecordingShortcut(for: command) + } + + private func take(_ input: ShortcutRecorderInput) { + switch input { + case .keys(let keys): model.takeRecordedShortcut(keys, for: command) + case .cancel: model.endShortcutsPageEdit() + case .clear: model.clearRecordedShortcut(for: command) + case .ignored: break + } + } +} diff --git a/Sources/MultishellAppUI/Settings/AppWide/Shortcuts/ShortcutWarning+Text.swift b/Sources/MultishellAppUI/Settings/AppWide/Shortcuts/ShortcutWarning+Text.swift new file mode 100644 index 000000000..042a13064 --- /dev/null +++ b/Sources/MultishellAppUI/Settings/AppWide/Shortcuts/ShortcutWarning+Text.swift @@ -0,0 +1,9 @@ +import MultishellAppCore +import MultishellCore + +extension ShortcutWarning { + var text: String { + guard let shellUse else { return t("shortcuts.warning", keys.glyphs) } + return t("shortcuts.warning-shell", keys.glyphs, shellUse.name) + } +} diff --git a/Sources/MultishellAppUI/Settings/AppWide/Shortcuts/ShortcutsRestoreButton.swift b/Sources/MultishellAppUI/Settings/AppWide/Shortcuts/ShortcutsRestoreButton.swift new file mode 100644 index 000000000..670049eba --- /dev/null +++ b/Sources/MultishellAppUI/Settings/AppWide/Shortcuts/ShortcutsRestoreButton.swift @@ -0,0 +1,25 @@ +import MultishellAppCore +import SwiftUI + +/// Restore Defaults in the Shortcuts page's header, asking once in place +/// before it clears every change. +struct ShortcutsRestoreButton: View { + let model: AppModel + + var body: some View { + HStack(spacing: 6) { + if model.isAskingToRestoreShortcuts { + Text(t("shortcuts.restore-question")) + .font(.system(size: UIMetrics.settingsSmallTextSize)) + .foregroundStyle(SettingsColors.secondaryText) + .lineLimit(1) + Button(t("action.cancel"), action: model.endShortcutsPageEdit) + Button(t("shortcuts.restore"), role: .destructive, action: model.restoreDefaultShortcuts) + } else { + Button(t("shortcuts.restore-defaults"), action: model.askToRestoreShortcuts) + .disabled(!model.hasChangedShortcuts) + } + } + .buttonStyle(SettingsButtonStyle()) + } +} diff --git a/Sources/MultishellAppUI/Settings/AppWide/Shortcuts/View+ShortcutKeysFace.swift b/Sources/MultishellAppUI/Settings/AppWide/Shortcuts/View+ShortcutKeysFace.swift new file mode 100644 index 000000000..fb549b8f5 --- /dev/null +++ b/Sources/MultishellAppUI/Settings/AppWide/Shortcuts/View+ShortcutKeysFace.swift @@ -0,0 +1,13 @@ +import SwiftUI + +extension View { + /// Keys as the Yours cell draws them, so the button, the recorder and a + /// pending answer line up at one width. + func shortcutKeysFace() -> some View { + font(.system(size: UIMetrics.settingsControlTextSize)) + .lineLimit(1) + .padding(.horizontal, UIMetrics.settingsShortcutKeysSideInset) + .padding(.vertical, UIMetrics.settingsControlVerticalInset) + .frame(minWidth: UIMetrics.settingsShortcutKeysWidth) + } +} diff --git a/Sources/MultishellAppUI/Settings/Project/Hooks/ProjectHooksPage.swift b/Sources/MultishellAppUI/Settings/Project/Hooks/ProjectHooksPage.swift index 03fb18cb0..b73eb0476 100644 --- a/Sources/MultishellAppUI/Settings/Project/Hooks/ProjectHooksPage.swift +++ b/Sources/MultishellAppUI/Settings/Project/Hooks/ProjectHooksPage.swift @@ -25,7 +25,8 @@ struct ProjectHooksPage: View { case .hooksEnvironment: HookEnvironmentSection(model: model) case .agentHooks, .agents, .agentSettings, .appearance, .general, .integrations, - .notifications, .terminal, .worktrees: + .notifications, .shortcutsEdit, .shortcutsFile, .shortcutsTerminal, .shortcutsView, + .terminal, .worktrees: EmptyView() } } diff --git a/Sources/MultishellAppUI/Settings/Project/Overrides/OverrideRow.swift b/Sources/MultishellAppUI/Settings/Project/Overrides/OverrideRow.swift index 303f20516..3bfc4dcd5 100644 --- a/Sources/MultishellAppUI/Settings/Project/Overrides/OverrideRow.swift +++ b/Sources/MultishellAppUI/Settings/Project/Overrides/OverrideRow.swift @@ -34,7 +34,9 @@ struct OverrideRow: View { .labelsHidden() SettingsSymbolButton.useGlobal { isOverridden.wrappedValue = false } } else { - OverrideStartButton(label: label) { isOverridden.wrappedValue = true } + OverrideStartButton(help: t("project.override-help", label)) { + isOverridden.wrappedValue = true + } } } if let caption { diff --git a/Sources/MultishellAppUI/Settings/Project/Overrides/OverrideStartButton.swift b/Sources/MultishellAppUI/Settings/Project/Overrides/OverrideStartButton.swift index ff8f3e070..2c58a399b 100644 --- a/Sources/MultishellAppUI/Settings/Project/Overrides/OverrideStartButton.swift +++ b/Sources/MultishellAppUI/Settings/Project/Overrides/OverrideStartButton.swift @@ -1,10 +1,10 @@ import SwiftUI -/// The Override column while the project follows: "Same", reading "Override" under -/// the pointer, and starting an override seeded with the value it followed. +/// "Same", reading "Override" under the pointer, for a value that follows another: +/// a project's setting the global, or a command its default. struct OverrideStartButton: View { - /// The setting's row label, for the tooltip and VoiceOver. - let label: String + /// The tooltip and VoiceOver's label, naming the row's setting. + let help: String let start: () -> Void @State private var isHovered = false @@ -27,7 +27,7 @@ struct OverrideStartButton: View { } .buttonStyle(.plain) .tracksHover($isHovered) - .help(t("project.override-help", label)) - .accessibilityLabel(t("project.override-help", label)) + .help(help) + .accessibilityLabel(help) } } diff --git a/Sources/MultishellAppUI/Settings/Project/Overrides/OverrideTable.swift b/Sources/MultishellAppUI/Settings/Project/Overrides/OverrideTable.swift index 82be07b1e..772101709 100644 --- a/Sources/MultishellAppUI/Settings/Project/Overrides/OverrideTable.swift +++ b/Sources/MultishellAppUI/Settings/Project/Overrides/OverrideTable.swift @@ -4,16 +4,19 @@ import SwiftUI /// under a heading naming the columns. struct OverrideTable: View { let title: String + /// Help behind an (i) beside the title, `nil` for none. + let info: String? + let columnTitles: (global: String, override: String) @ViewBuilder let rows: () -> Rows var body: some View { SettingsGroup { OverrideColumns { - Text(title) + if let info { InfoLabel(sectionHeader: title, info: info) } else { Text(title) } } global: { - Text(t("project.column-global")) + Text(columnTitles.global) } override: { - Text(t("project.column-override")) + Text(columnTitles.override) } .font(.system(size: UIMetrics.settingsSmallTextSize, weight: .semibold)) .foregroundStyle(SettingsColors.secondaryText) @@ -22,8 +25,17 @@ struct OverrideTable: View { } } - init(_ title: String = "", @ViewBuilder rows: @escaping () -> Rows) { + init( + _ title: String = "", + info: String? = nil, + columnTitles: (global: String, override: String) = ( + t("project.column-global"), t("project.column-override"), + ), + @ViewBuilder rows: @escaping () -> Rows, + ) { self.title = title + self.info = info + self.columnTitles = columnTitles self.rows = rows } } diff --git a/Sources/MultishellAppUI/Settings/Project/ProjectAgentsPage.swift b/Sources/MultishellAppUI/Settings/Project/ProjectAgentsPage.swift index 9a8c5b7a5..0db33a38b 100644 --- a/Sources/MultishellAppUI/Settings/Project/ProjectAgentsPage.swift +++ b/Sources/MultishellAppUI/Settings/Project/ProjectAgentsPage.swift @@ -16,7 +16,7 @@ struct ProjectAgentsPage: View { project: project, setting: \.preferredAgentID, label: t("project.preferred-agent"), - info: t("project.preferred-agent-info"), + info: t("project.preferred-agent-info", model.keysInParentheses(.newAgentTab)), options: model.agentDetection.options(selected:), globalValue: model.globalAgentValue, globalID: model.globalAgentID, diff --git a/Sources/MultishellAppUI/Settings/SettingsDetail.swift b/Sources/MultishellAppUI/Settings/SettingsDetail.swift index 2be31d250..91ed5f7f4 100644 --- a/Sources/MultishellAppUI/Settings/SettingsDetail.swift +++ b/Sources/MultishellAppUI/Settings/SettingsDetail.swift @@ -14,7 +14,9 @@ struct SettingsDetail: View { title: location.section.page.title, part: location.section.partTitle, caption: model.settingsHeaderCaption, - ) + ) { + if location.section.page == .shortcuts { ShortcutsRestoreButton(model: model) } + } page // A fresh page per place, so a page reused for another project or // part starts scrolled to the top. @@ -43,6 +45,10 @@ struct SettingsDetail: View { case .appearance: AppAppearancePage(model: model) case .general: AppGeneralPage(model: model) case .notifications: AppNotificationsPage(model: model) + + case .shortcutsEdit, .shortcutsFile, .shortcutsTerminal, .shortcutsView: + AppShortcutsPage(model: model, section: location.section) + case .terminal: AppTerminalPage(model: model) case .worktrees: AppWorktreesPage(model: model) case .agents, .hooksCreate, .hooksDelete, .hooksEnvironment, .integrations: EmptyView() @@ -65,7 +71,9 @@ struct SettingsDetail: View { case .worktrees: ProjectWorktreesPage(model: model, project: project) - case .agentHooks, .agentSettings, .appearance, .notifications: EmptyView() + case .agentHooks, .agentSettings, .appearance, .notifications, .shortcutsEdit, .shortcutsFile, + .shortcutsTerminal, .shortcutsView: + EmptyView() } } } diff --git a/Sources/MultishellAppUI/Settings/SettingsPageHeader.swift b/Sources/MultishellAppUI/Settings/SettingsPageHeader.swift index bd2f7d449..f441ef391 100644 --- a/Sources/MultishellAppUI/Settings/SettingsPageHeader.swift +++ b/Sources/MultishellAppUI/Settings/SettingsPageHeader.swift @@ -1,11 +1,12 @@ import SwiftUI /// The band atop the settings page, where the hidden title bar leaves room: -/// the page, the part shown, and whose settings they are. -struct SettingsPageHeader: View { +/// the page, the part shown, whose settings they are, and the page's own button. +struct SettingsPageHeader: View { let title: String let part: String? let caption: String + @ViewBuilder let accessory: () -> Accessory var body: some View { HStack(spacing: 6) { @@ -22,6 +23,7 @@ struct SettingsPageHeader: View { .foregroundStyle(SettingsColors.secondaryText) .lineLimit(1) .truncationMode(.head) + accessory() } .padding(.horizontal, UIMetrics.settingsHeaderSideInset) .frame(height: UIMetrics.settingsHeaderHeight) diff --git a/Sources/MultishellAppUI/Settings/Sidebar/SettingsPage+Label.swift b/Sources/MultishellAppUI/Settings/Sidebar/SettingsPage+Label.swift index 8a500933e..36362fac4 100644 --- a/Sources/MultishellAppUI/Settings/Sidebar/SettingsPage+Label.swift +++ b/Sources/MultishellAppUI/Settings/Sidebar/SettingsPage+Label.swift @@ -10,6 +10,7 @@ extension SettingsPage { case .hooks: t("settings.hooks") case .integrations: t("settings.integrations") case .notifications: t("settings.notifications") + case .shortcuts: t("settings.shortcuts") case .terminal: t("settings.terminal") case .worktrees: t("settings.worktrees") } @@ -24,6 +25,7 @@ extension SettingsPage { case .hooks: Color(red: 0.878, green: 0.659, blue: 0) case .integrations: Color(red: 0.078, green: 0.639, blue: 0.639) case .notifications: Color(red: 1, green: 0.231, blue: 0.188) + case .shortcuts: Color(red: 0.204, green: 0.78, blue: 0.349) case .terminal: Color(red: 0.227, green: 0.227, blue: 0.235) case .worktrees: Color(red: 0.941, green: 0.541, blue: 0.141) } diff --git a/Sources/MultishellAppUI/Settings/Sidebar/SettingsPage+SearchTerms.swift b/Sources/MultishellAppUI/Settings/Sidebar/SettingsPage+SearchTerms.swift index 15a03d7a7..a59278471 100644 --- a/Sources/MultishellAppUI/Settings/Sidebar/SettingsPage+SearchTerms.swift +++ b/Sources/MultishellAppUI/Settings/Sidebar/SettingsPage+SearchTerms.swift @@ -41,6 +41,10 @@ extension SettingsPage { t("terminal.open-on-create"), ] + case .shortcuts: + [t("shortcuts.restore-defaults")] + ShortcutGroup.allCases.map(\.title) + + ShortcutCommand.allCases.map(\.menuTitle) + case .worktrees: [ t("worktrees.section-creating"), t("worktrees.path"), t("worktrees.branch-prefix"), @@ -92,7 +96,7 @@ extension SettingsPage { t("project.default-branch"), ] - case .appearance, .notifications: [] + case .appearance, .notifications, .shortcuts: [] } } diff --git a/Sources/MultishellAppUI/Settings/Sidebar/SettingsPageGlyph.swift b/Sources/MultishellAppUI/Settings/Sidebar/SettingsPageGlyph.swift index b536743b0..89566536c 100644 --- a/Sources/MultishellAppUI/Settings/Sidebar/SettingsPageGlyph.swift +++ b/Sources/MultishellAppUI/Settings/Sidebar/SettingsPageGlyph.swift @@ -67,6 +67,9 @@ struct SettingsPageGlyph: View { case .notifications: appendBell(to: &path) + case .shortcuts: + appendKeyboard(to: &path) + case .terminal: path.addRoundedRect( in: CGRect(x: 1.5, y: 2.5, width: 13, height: 11), @@ -144,6 +147,22 @@ struct SettingsPageGlyph: View { ) } + /// A keyboard: its body, two rows of keys and the space bar. + private func appendKeyboard(to path: inout Path) { + path.addRoundedRect( + in: CGRect(x: 1.5, y: 3.5, width: 13, height: 9), + cornerSize: CGSize(width: 1.5, height: 1.5), + ) + for x in [4.0, 6.7, 9.3, 12] { + path.move(to: CGPoint(x: x, y: 6)) + path.addLine(to: CGPoint(x: x, y: 6)) + path.move(to: CGPoint(x: x, y: 8)) + path.addLine(to: CGPoint(x: x, y: 8)) + } + path.move(to: CGPoint(x: 5.5, y: 10.3)) + path.addLine(to: CGPoint(x: 10.5, y: 10.3)) + } + /// The palette: a left half circle, a thumb notch, and three paint dots. private func appendPalette(to path: inout Path) { let rim = 6.5 * Self.quarter diff --git a/Sources/MultishellAppUI/Settings/Sidebar/SettingsSection+Title.swift b/Sources/MultishellAppUI/Settings/Sidebar/SettingsSection+Title.swift index ec0eb75f4..31a149230 100644 --- a/Sources/MultishellAppUI/Settings/Sidebar/SettingsSection+Title.swift +++ b/Sources/MultishellAppUI/Settings/Sidebar/SettingsSection+Title.swift @@ -9,6 +9,10 @@ extension SettingsSection { case .hooksCreate: t("hooks.create") case .hooksDelete: t("hooks.delete") case .hooksEnvironment: t("hooks.environment") + case .shortcutsEdit: t("settings.shortcuts-edit") + case .shortcutsFile: t("settings.shortcuts-file") + case .shortcutsTerminal: t("settings.shortcuts-terminal") + case .shortcutsView: t("settings.shortcuts-view") case .agents, .appearance, .general, .integrations, .notifications, .terminal, .worktrees: nil } } diff --git a/Sources/MultishellAppUI/Settings/Sidebar/SettingsSidebar.swift b/Sources/MultishellAppUI/Settings/Sidebar/SettingsSidebar.swift index c6c83d20f..8ff8d5f0e 100644 --- a/Sources/MultishellAppUI/Settings/Sidebar/SettingsSidebar.swift +++ b/Sources/MultishellAppUI/Settings/Sidebar/SettingsSidebar.swift @@ -2,7 +2,7 @@ import MultishellAppCore import SwiftUI /// The settings window's sidebar: whose settings, then their pages. A split -/// page lists its parts beneath it, its own row opening the first. +/// page lists its parts beneath it while open, its own row opening the first. struct SettingsSidebar: View { let model: AppModel let location: SettingsLocation @@ -50,12 +50,13 @@ struct SettingsSidebar: View { SettingsSidebarRow(title: page.title, page: page, isSelected: location.selects(page)) { show(first) } - if first.isPart { + if first.isPart, location.showsParts(of: page) { ForEach(sections, id: \.self) { section in SettingsSidebarRow( title: section.partTitle ?? page.title, page: nil, isSelected: location.section == section, + changes: model.changedShortcutCount(in: section), ) { show(section) } } } diff --git a/Sources/MultishellAppUI/Settings/Sidebar/SettingsSidebarRow.swift b/Sources/MultishellAppUI/Settings/Sidebar/SettingsSidebarRow.swift index 89d117f60..a12179b69 100644 --- a/Sources/MultishellAppUI/Settings/Sidebar/SettingsSidebarRow.swift +++ b/Sources/MultishellAppUI/Settings/Sidebar/SettingsSidebarRow.swift @@ -8,6 +8,8 @@ struct SettingsSidebarRow: View { /// The page whose tile leads the row; `nil` for a part. let page: SettingsPage? let isSelected: Bool + /// Shown at the trailing edge where above zero: a Shortcuts part's changes. + var changes = 0 let select: () -> Void @State private var isHovered = false @@ -33,6 +35,11 @@ struct SettingsSidebarRow: View { .foregroundStyle(textStyle) .lineLimit(1) Spacer(minLength: 0) + if changes != 0 { + Text(changes, format: .number) + .font(.system(size: UIMetrics.settingsSidebarControlFontSize)) + .foregroundStyle(textStyle) + } } .padding(.vertical, 4) .padding( diff --git a/Sources/MultishellAppUI/Sidebar/SidebarHeader.swift b/Sources/MultishellAppUI/Sidebar/SidebarHeader.swift index 54d8536c4..8a550f177 100644 --- a/Sources/MultishellAppUI/Sidebar/SidebarHeader.swift +++ b/Sources/MultishellAppUI/Sidebar/SidebarHeader.swift @@ -5,6 +5,8 @@ import SwiftUI /// bar is hidden. Add Project is a folder-plus so it does not read as a row's +. struct SidebarHeader: View { let showsFilterField: Bool + /// The Add Project button's tooltip, naming its keys in force. + let addProjectHelp: String let theme: Theme let toggleFilter: () -> Void let addProject: () -> Void @@ -21,7 +23,7 @@ struct SidebarHeader: View { ) HeaderGlyphButton( symbol: "folder.badge.plus", - help: t("sidebar.add-project"), + help: addProjectHelp, palette: theme.projectsPanel, resting: theme.projectsPanel.textSecondary, opensAWindow: true, diff --git a/Sources/MultishellAppUI/Sidebar/SidebarView.swift b/Sources/MultishellAppUI/Sidebar/SidebarView.swift index 861d2485e..ba1ce2a2d 100644 --- a/Sources/MultishellAppUI/Sidebar/SidebarView.swift +++ b/Sources/MultishellAppUI/Sidebar/SidebarView.swift @@ -25,6 +25,7 @@ struct SidebarView: View { VStack(spacing: 0) { SidebarHeader( showsFilterField: model.showsSidebarFilter, + addProjectHelp: t("sidebar.add-project", model.keysInParentheses(.addProject)), theme: theme, toggleFilter: model.toggleSidebarFilter, addProject: { Task { await model.addProjectFromPicker() } }, diff --git a/Sources/MultishellAppUI/Support/AppModel+KeysInParentheses.swift b/Sources/MultishellAppUI/Support/AppModel+KeysInParentheses.swift new file mode 100644 index 000000000..60e0ad64a --- /dev/null +++ b/Sources/MultishellAppUI/Support/AppModel+KeysInParentheses.swift @@ -0,0 +1,10 @@ +import MultishellAppCore +import MultishellCore + +extension AppModel { + /// ` (⌘T)` for a sentence naming the command's keys in force, and nothing + /// where it has none, so no empty parenthesis is left. + func keysInParentheses(_ command: ShortcutCommand) -> String { + shortcutKeys(for: command).map { t("shortcuts.in-parentheses", $0.glyphs) } ?? "" + } +} diff --git a/Sources/MultishellAppUI/Support/Appearance/UIMetrics.swift b/Sources/MultishellAppUI/Support/Appearance/UIMetrics.swift index d310b22d7..02448a7d8 100644 --- a/Sources/MultishellAppUI/Support/Appearance/UIMetrics.swift +++ b/Sources/MultishellAppUI/Support/Appearance/UIMetrics.swift @@ -113,6 +113,9 @@ struct UIMetrics: Equatable { static let settingsGlobalColumnWidth: Double = 140 static let settingsOverrideColumnWidth: Double = 210 static let settingsColumnSpacing: Double = 10 + /// A Shortcuts row's keys and its recorder, as wide as the mockup's "Same". + static let settingsShortcutKeysWidth: Double = 76 + static let settingsShortcutKeysSideInset: Double = 8 static let newWorktreeSheetWidth: Double = 520 let bodySize: Double diff --git a/Sources/MultishellAppUI/Support/KeyCombination+KeyboardShortcut.swift b/Sources/MultishellAppUI/Support/KeyCombination+KeyboardShortcut.swift new file mode 100644 index 000000000..679dae46d --- /dev/null +++ b/Sources/MultishellAppUI/Support/KeyCombination+KeyboardShortcut.swift @@ -0,0 +1,14 @@ +import MultishellCore +import SwiftUI + +extension KeyCombination { + /// A changed command's keys were typed on this layout, so SwiftUI must not + /// move them to where its US equivalent sits on another. + func keyboardShortcut(isChanged: Bool) -> KeyboardShortcut { + KeyboardShortcut( + KeyEquivalent(menuKeyCharacter), + modifiers: modifiers.eventModifiers, + localization: isChanged ? .custom : .automatic, + ) + } +} diff --git a/Sources/MultishellAppUI/Support/KeyCombination+MenuKey.swift b/Sources/MultishellAppUI/Support/KeyCombination+MenuKey.swift new file mode 100644 index 000000000..20e63d291 --- /dev/null +++ b/Sources/MultishellAppUI/Support/KeyCombination+MenuKey.swift @@ -0,0 +1,30 @@ +import AppKit +import MultishellCore + +extension KeyCombination { + /// The character a menu item's key equivalent holds for the key: the + /// character itself, or the code or private-use character AppKit names it by. + var menuKeyCharacter: Character { + switch key { + case .character(let character): character + case .function(let number): Self.scalar(NSF1FunctionKey + number - 1) + case .tab: "\t" + case .returnKey: "\r" + case .space: " " + case .backspace: "\u{8}" + case .forwardDelete: Self.scalar(NSDeleteFunctionKey) + case .home: Self.scalar(NSHomeFunctionKey) + case .end: Self.scalar(NSEndFunctionKey) + case .pageUp: Self.scalar(NSPageUpFunctionKey) + case .pageDown: Self.scalar(NSPageDownFunctionKey) + case .leftArrow: Self.scalar(NSLeftArrowFunctionKey) + case .rightArrow: Self.scalar(NSRightArrowFunctionKey) + case .upArrow: Self.scalar(NSUpArrowFunctionKey) + case .downArrow: Self.scalar(NSDownArrowFunctionKey) + } + } + + private static func scalar(_ value: Int) -> Character { + UnicodeScalar(UInt32(value)).map(Character.init) ?? " " + } +} diff --git a/Sources/MultishellAppUI/Support/ShortcutModifiers+Platform.swift b/Sources/MultishellAppUI/Support/ShortcutModifiers+Platform.swift new file mode 100644 index 000000000..a86022884 --- /dev/null +++ b/Sources/MultishellAppUI/Support/ShortcutModifiers+Platform.swift @@ -0,0 +1,25 @@ +import AppKit +import MultishellCore +import SwiftUI + +extension ShortcutModifiers { + /// Each modifier as AppKit's event flags and SwiftUI's shortcut name it. + private static let platformNames: + [(modifier: Self, flag: NSEvent.ModifierFlags, eventModifier: EventModifiers)] = [ + (.control, .control, .control), (.option, .option, .option), (.shift, .shift, .shift), + (.command, .command, .command), + ] + + var modifierFlags: NSEvent.ModifierFlags { + NSEvent.ModifierFlags(Self.platformNames.filter { contains($0.modifier) }.map(\.flag)) + } + + var eventModifiers: EventModifiers { + EventModifiers(Self.platformNames.filter { contains($0.modifier) }.map(\.eventModifier)) + } + + /// The modifiers among an event's flags, Caps Lock, fn and the rest left out. + init(_ flags: NSEvent.ModifierFlags) { + self.init(Self.platformNames.filter { flags.contains($0.flag) }.map(\.modifier)) + } +} diff --git a/Sources/MultishellAppUI/Terminals/Groups/TabStripSplitButton.swift b/Sources/MultishellAppUI/Terminals/Groups/TabStripSplitButton.swift index 6bcc8cbd1..0043baed2 100644 --- a/Sources/MultishellAppUI/Terminals/Groups/TabStripSplitButton.swift +++ b/Sources/MultishellAppUI/Terminals/Groups/TabStripSplitButton.swift @@ -34,7 +34,13 @@ struct TabStripSplitButton: View { .disabled(!model.canSplitShownTab(in: groupID)) // Outside `disabled`, so a split enabled under a resting pointer hears it. .tracksHover($isHovered) - .help(TabStripButtonText.splitHelp(axis, isFocusedGroup: isFocusedGroup)) + .help( + TabStripButtonText.splitHelp( + axis, + isFocusedGroup: isFocusedGroup, + keys: model.shortcutKeys(for: TabStripButtonText.splitCommand(axis)), + ) + ) .accessibilityLabel(TabStripButtonText.splitLabel(axis)) } } diff --git a/Sources/MultishellCLI/Usage/Helper+ConfigUsage.swift b/Sources/MultishellCLI/Usage/Helper+ConfigUsage.swift index 50b7fc6b1..8e1376497 100644 --- a/Sources/MultishellCLI/Usage/Helper+ConfigUsage.swift +++ b/Sources/MultishellCLI/Usage/Helper+ConfigUsage.swift @@ -10,7 +10,11 @@ extension Helper { defaultShell takes a shell's full path, login or custom. renameModel and renameEffort take only what renameAgentID's agent lists, and are cleared when it changes; renameEffort is also cleared - by a renameModel that does not take it. + by a renameModel that does not take it. shortcuts.split-right and + the rest take keys as the state file spells them, cmd+backslash, or + as a menu draws them, ⌘\\, or none; an empty VALUE is the default. + Keys the Settings page would refuse or another command holds are + refused. usage: multishell config project PROJECT_ID list usage: multishell config project PROJECT_ID get KEY usage: multishell config project PROJECT_ID set KEY VALUE diff --git a/Sources/MultishellCLI/Usage/Helper+UIUsage.swift b/Sources/MultishellCLI/Usage/Helper+UIUsage.swift index 01fe9ac01..9d05d21d2 100644 --- a/Sources/MultishellCLI/Usage/Helper+UIUsage.swift +++ b/Sources/MultishellCLI/Usage/Helper+UIUsage.swift @@ -7,8 +7,9 @@ extension Helper { all terminals, or the Settings window on All Projects or on a project, turned to PAGE as its sidebar's row would. All Projects has general, worktrees, terminal, agent-settings, agent-hooks, - notifications and appearance, and agents opens its first part. A - project has general, worktrees, hooks-create, hooks-delete, + notifications, appearance, shortcuts-file, shortcuts-edit, + shortcuts-view and shortcuts-terminal, and agents opens its first + part. A project has general, worktrees, hooks-create, hooks-delete, hooks-environment, terminal, agents and integrations. usage: multishell ui show pull-request|ci [WORKTREE_ID] Open the Files panel on the worktree's pull request or CI page, the diff --git a/Sources/MultishellCore/Control/ControlSettingsPage.swift b/Sources/MultishellCore/Control/ControlSettingsPage.swift index 73258070e..9fc98e265 100644 --- a/Sources/MultishellCore/Control/ControlSettingsPage.swift +++ b/Sources/MultishellCore/Control/ControlSettingsPage.swift @@ -12,6 +12,10 @@ public enum ControlSettingsPage: String, Codable, CaseIterable, Sendable { case hooksEnvironment = "hooks-environment" case integrations case notifications + case shortcutsEdit = "shortcuts-edit" + case shortcutsFile = "shortcuts-file" + case shortcutsTerminal = "shortcuts-terminal" + case shortcutsView = "shortcuts-view" case terminal case worktrees } diff --git a/Sources/MultishellCore/Model/Settings/Shortcuts/KeyCombination+Glyphs.swift b/Sources/MultishellCore/Model/Settings/Shortcuts/KeyCombination+Glyphs.swift new file mode 100644 index 000000000..c71a348bd --- /dev/null +++ b/Sources/MultishellCore/Model/Settings/Shortcuts/KeyCombination+Glyphs.swift @@ -0,0 +1,49 @@ +extension KeyCombination { + /// As a menu draws it, `⇧⌘K`, `⌃⇥`. + public var glyphs: String { + modifiers.glyphs + Self.glyph(for: key) + } + + /// Reads what `glyphs` writes, a capital letter being that letter alone: + /// `⇧⌘K` holds Shift because of its `⇧`. + public init?(glyphs text: String) { + var modifiers: ShortcutModifiers = [] + var rest = Substring(text) + while let first = rest.first, + let modifier = ShortcutModifiers.menuOrder.first(where: { $0.glyph == first })?.modifier + { + guard !modifiers.contains(modifier) else { return nil } + modifiers.insert(modifier) + rest = rest.dropFirst() + } + guard let key = Self.key(glyph: String(rest)) else { return nil } + self.init(key, modifiers) + } + + private static func glyph(for key: ShortcutKey) -> String { + switch key { + case .character(let character): capital(of: character) + case .function(let number): "F\(number)" + default: ShortcutKey.named.first { $0.key == key }?.glyph ?? "" + } + } + + /// The character itself where its capital would read back as another key: + /// ß capitalises to SS, and Turkish ı to I, which is i's. + private static func capital(of character: Character) -> String { + let capital = character.uppercased() + let readsBack = capital.count == 1 && capital.lowercased() == String(character) + return readsBack ? capital : String(character) + } + + private static func key(glyph: String) -> ShortcutKey? { + if let named = ShortcutKey.named.first(where: { $0.glyph == glyph }) { return named.key } + if glyph.count > 1, glyph.hasPrefix("F"), let number = Int(glyph.dropFirst()), + ShortcutKey.functionNumbers.contains(number) + { + return .function(number) + } + guard glyph.count == 1, let character = glyph.first, isTypable(character) else { return nil } + return .character(character) + } +} diff --git a/Sources/MultishellCore/Model/Settings/Shortcuts/KeyCombination+Refusal.swift b/Sources/MultishellCore/Model/Settings/Shortcuts/KeyCombination+Refusal.swift new file mode 100644 index 000000000..92a5416e4 --- /dev/null +++ b/Sources/MultishellCore/Model/Settings/Shortcuts/KeyCombination+Refusal.swift @@ -0,0 +1,58 @@ +extension KeyCombination { + /// Interrupt, end of input, suspend, quit and Escape, which a pane's program + /// needs, and ⌃/, which the pane types as ⌃_ before any menu sees it. + private static let programKeys: Set = Set( + ["c", "d", "z", "\\", "[", "/"].map { KeyCombination(.character($0), .control) } + ) + + /// Keys a text field moves or deletes by with ⌘, Shift also selecting. + private static let commandEditingKeys: Set = [ + .leftArrow, .rightArrow, .upArrow, .downArrow, .backspace, + ] + /// ⌃⇧← and ⌃⇧→ select to a line's ends, ⌃← and ⌃→ being Spaces'. + private static let controlEditingKeys: Set = [.leftArrow, .rightArrow] + + /// Keys a text field moves, deletes or breaks a line by with ⌥; it does + /// nothing with ⌥Home or ⌥End. + private static let optionEditingKeys: Set = [ + .leftArrow, .rightArrow, .upArrow, .downArrow, .backspace, .forwardDelete, .returnKey, .tab, + .pageUp, .pageDown, + ] + + /// Why no command may have these keys, whoever holds them; `nil` where one + /// may. Docs/design/shortcuts.md has the rules. + public var refusal: ShortcutRefusal? { + if modifiers.isDisjoint(with: [.command, .control]), let refusal = refusalWithoutCommand { + return refusal + } + if isTextEditing { return .editsText } + if let reserved = ReservedShortcut.holding(self) { return .reserved(reserved) } + // The pane types ⌃↩ with any other modifier before any menu sees it. + if Self.programKeys.contains(self) || (key == .returnKey && modifiers.contains(.control)) { + return .programKey(self) + } + return nil + } + + /// Without ⌘ or ⌃ every text field sees the key first, F-keys aside. + private var refusalWithoutCommand: ShortcutRefusal? { + if case .function = key { return nil } + guard modifiers.contains(.option) else { return .needsModifier } + if typesCharacter { return .optionTypesCharacter } + return Self.optionEditingKeys.contains(key) ? .optionEditsText : nil + } + + private var isTextEditing: Bool { + let byCommand = [[.command], [.command, .shift]].contains(modifiers) + let byControl = modifiers == [.control, .shift] + return (byCommand && Self.commandEditingKeys.contains(key)) + || (byControl && Self.controlEditingKeys.contains(key)) + } + + private var typesCharacter: Bool { + switch key { + case .character, .space: true + default: false + } + } +} diff --git a/Sources/MultishellCore/Model/Settings/Shortcuts/KeyCombination+Spelling.swift b/Sources/MultishellCore/Model/Settings/Shortcuts/KeyCombination+Spelling.swift new file mode 100644 index 000000000..17af0a53b --- /dev/null +++ b/Sources/MultishellCore/Model/Settings/Shortcuts/KeyCombination+Spelling.swift @@ -0,0 +1,70 @@ +extension KeyCombination { + /// Glyphs naming keys this has no case for, which no key types as a character. + private static let keyNameGlyphs: Set = ["⏎", "⌤", "⎋", "⇪", "⏏", "⌽"] + + /// Punctuation by name in the state file, so `+` never parts a combination + /// and a quote needs no escaping. + private static let punctuationWords: [Character: String] = [ + "`": "backquote", "-": "minus", "=": "equal", "[": "bracket_left", "]": "bracket_right", + "\\": "backslash", ";": "semicolon", "'": "quote", ",": "comma", ".": "period", "/": "slash", + "+": "plus", + ] + + /// As the state file keeps it, modifiers in menu order: `ctrl+shift+tab`, + /// `cmd+backslash`. + public var spelled: String { + let words = ShortcutModifiers.menuOrder.filter { modifiers.contains($0.modifier) }.map(\.word) + return (words + [Self.word(for: key)]).joined(separator: "+") + } + + /// `nil` for a word this does not know or a modifier given twice. Any case, + /// any order of modifiers, and a key may be its own character: `cmd+\`. + public init?(spelled text: String) { + let lowered = text.lowercased() + var parts = lowered.split(separator: "+", omittingEmptySubsequences: false).map(String.init) + if lowered.hasSuffix("++") { parts = Array(parts.dropLast(2)) + ["+"] } + guard let keyWord = parts.last, let key = Self.key(named: keyWord) else { return nil } + var modifiers: ShortcutModifiers = [] + for word in parts.dropLast() { + guard let modifier = ShortcutModifiers.menuOrder.first(where: { $0.word == word })?.modifier, + !modifiers.contains(modifier) + else { return nil } + modifiers.insert(modifier) + } + self.init(key, modifiers) + } + + private static func word(for key: ShortcutKey) -> String { + switch key { + case .character(let character): punctuationWords[character] ?? String(character) + case .function(let number): "f\(number)" + default: ShortcutKey.named.first { $0.key == key }?.word ?? "" + } + } + + private static func key(named word: String) -> ShortcutKey? { + if let named = ShortcutKey.named.first(where: { $0.word == word }) { return named.key } + // A glyph pasted from the page, ⌘←, names its key, not a character no key types. + if let named = ShortcutKey.named.first(where: { $0.glyph == word }) { return named.key } + if let character = punctuationWords.first(where: { $0.value == word })?.key { + return .character(character) + } + if word.count > 1, word.hasPrefix("f"), let number = Int(word.dropFirst()), + ShortcutKey.functionNumbers.contains(number) + { + return .function(number) + } + guard word.count == 1, let character = word.first, isTypable(character) else { return nil } + return .character(character) + } + + /// A space, a modifier's or a key's glyph, a control code or one of AppKit's + /// private-use keys is no character key; the named keys stand for those with a word. + public static func isTypable(_ character: Character) -> Bool { + !character.isWhitespace && !keyNameGlyphs.contains(character) + && !ShortcutModifiers.menuOrder.contains { $0.glyph == character } + && character.unicodeScalars.allSatisfy { scalar in + ![.control, .privateUse, .format].contains(scalar.properties.generalCategory) + } + } +} diff --git a/Sources/MultishellCore/Model/Settings/Shortcuts/KeyCombination.swift b/Sources/MultishellCore/Model/Settings/Shortcuts/KeyCombination.swift new file mode 100644 index 000000000..4949ca746 --- /dev/null +++ b/Sources/MultishellCore/Model/Settings/Shortcuts/KeyCombination.swift @@ -0,0 +1,21 @@ +/// A key and the modifiers held with it, as a menu item's key equivalent +/// matches it. It names no engine; the app spells it for the terminal's. +public struct KeyCombination: Hashable, Sendable { + public let key: ShortcutKey + public let modifiers: ShortcutModifiers + + /// A character is kept lowercase, Shift being a modifier of its own. + public init(_ key: ShortcutKey, _ modifiers: ShortcutModifiers = []) { + if case .character(let character) = key, let lower = character.lowercased().first { + self.key = .character(lower) + } else { + self.key = key + } + self.modifiers = modifiers + } + + /// Command and a character, with any other modifiers, as most defaults are. + static func command(_ character: Character, _ extra: ShortcutModifiers = []) -> Self { + Self(.character(character), extra.union(.command)) + } +} diff --git a/Sources/MultishellCore/Model/Settings/Shortcuts/ReservedShortcut.swift b/Sources/MultishellCore/Model/Settings/Shortcuts/ReservedShortcut.swift new file mode 100644 index 000000000..d81b18a3b --- /dev/null +++ b/Sources/MultishellCore/Model/Settings/Shortcuts/ReservedShortcut.swift @@ -0,0 +1,95 @@ +/// A combination macOS or the app keeps over its windows, which no command +/// may take and the terminal surface gives up; Docs/design/shortcuts.md. +public enum ReservedShortcut: CaseIterable, Sendable { + case accessibilityShortcuts + case appSwitcher + case appSwitcherBackwards + case appWindows + /// AppKit's Cancel, which closes a sheet or an alert and stops a field's edit. + case cancel + /// The WindowServer takes it before a menu bar sees it. + case dockHiding + /// Edit > Emoji & Symbols, which AppKit adds. + case emojiAndSymbols + case finderSearch + case fullScreen + /// The Help menu's search field, which AppKit adds. + case helpSearch + case hide + case hideOthers + case lockScreen + case logOut + case logOutNow + case lookUp + case minimize + /// Window > Minimize All, the alternate AppKit shows with ⌥. + case minimizeAll + case missionControl + /// On the system-owned list since the first build, for a reason not recorded. + case newWindow + case nextInputSource + case previousInputSource + case quit + case screenshot + case screenshotOfArea + case screenshotOfAreaToClipboard + case screenshotToClipboard + case screenshotTools + /// Sends a review comment from its composer. + case send + case settings + /// View > Show All Tabs, which AppKit adds for window tabbing. + case showAllTabs + case spaceLeft + case spaceRight + case spotlight + case voiceOver + case windowCycling + case windowCyclingBackwards + + public var combination: KeyCombination { + switch self { + case .quit: .command("q") + case .hide: .command("h") + case .hideOthers: .command("h", .option) + case .minimize: .command("m") + case .minimizeAll: .command("m", .option) + case .voiceOver: KeyCombination(.function(5), .command) + case .accessibilityShortcuts: KeyCombination(.function(5), [.option, .command]) + case .lookUp: .command("d", .control) + case .settings: .command(",") + case .dockHiding: .command("d", .option) + case .fullScreen: .command("f", .control) + case .appSwitcher: KeyCombination(.tab, .command) + case .cancel: .command(".") + case .appSwitcherBackwards: KeyCombination(.tab, [.shift, .command]) + case .spotlight: KeyCombination(.space, .command) + case .windowCycling: .command("`") + case .windowCyclingBackwards: .command("`", .shift) + case .newWindow: .command("n", .shift) + case .send: KeyCombination(.returnKey, .command) + case .lockScreen: .command("q", .control) + case .logOut: .command("q", .shift) + case .logOutNow: .command("q", [.option, .shift]) + case .screenshot: .command("3", .shift) + case .screenshotOfArea: .command("4", .shift) + case .screenshotTools: .command("5", .shift) + case .screenshotToClipboard: .command("3", [.control, .shift]) + case .screenshotOfAreaToClipboard: .command("4", [.control, .shift]) + case .spaceLeft: KeyCombination(.leftArrow, .control) + case .spaceRight: KeyCombination(.rightArrow, .control) + case .missionControl: KeyCombination(.upArrow, .control) + case .appWindows: KeyCombination(.downArrow, .control) + case .finderSearch: KeyCombination(.space, [.option, .command]) + case .previousInputSource: KeyCombination(.space, .control) + case .nextInputSource: KeyCombination(.space, [.control, .option]) + case .emojiAndSymbols: KeyCombination(.space, [.control, .command]) + case .helpSearch: .command("/", .shift) + case .showAllTabs: .command("\\", .shift) + } + } + + static func holding(_ combination: KeyCombination) -> Self? { + allCases.first { $0.combination == combination } + } +} diff --git a/Sources/MultishellCore/Model/Settings/Shortcuts/ShortcutCommand.swift b/Sources/MultishellCore/Model/Settings/Shortcuts/ShortcutCommand.swift new file mode 100644 index 000000000..7fe88b8ce --- /dev/null +++ b/Sources/MultishellCore/Model/Settings/Shortcuts/ShortcutCommand.swift @@ -0,0 +1,100 @@ +/// A menu command whose keys the user may change; `ShortcutGroup` holds the +/// menus' order. The raw value is the state file's key, so it never changes. +public enum ShortcutCommand: String, CaseIterable, Sendable { + case addProject = "add-project" + case changesPane = "changes-pane" + case closeFind = "close-find" + case closePane = "close-pane" + case closeTab = "close-tab" + case copy + case cut + case filesPane = "files-pane" + case find + case findNext = "find-next" + case findPrevious = "find-previous" + case focusNextGroup = "focus-next-group" + case focusPreviousGroup = "focus-previous-group" + case moveTabToNewGroup = "move-tab-to-new-group" + case newAgentTab = "new-agent-tab" + case newShellTab = "new-shell-tab" + case newTab = "new-tab" + case newWorktree = "new-worktree" + case nextTab = "next-tab" + case openInEditor = "open-in-editor" + case paste + case previousTab = "previous-tab" + case quickSwitcher = "quick-switcher" + case quickSwitcherCommands = "quick-switcher-commands" + case redo + case reviewPane = "review-pane" + case selectAll = "select-all" + case splitDown = "split-down" + case splitRight = "split-right" + case toggleAgentBoard = "agents" + case undo + + /// Every command but the fixed ones: the Shortcuts page's and the command line's. + public static let changeable = allCases.filter { !$0.isFixed } + + /// Cut, Copy, Paste and Select All. In a pane the same keys are the + /// engine's own clipboard actions, which the surface keeps. + public var surfaceKeepsBinding: Bool { + [.cut, .copy, .paste, .selectAll].contains(self) + } + + /// The clipboard four, and Undo, Redo and Find, whose keys every Mac app + /// shares; the owner's choice, Docs/design/shortcuts.md. + public var isFixed: Bool { + surfaceKeepsBinding || [.undo, .redo, .find].contains(self) + } + + public var defaultCombination: KeyCombination { + switch self { + case .newTab: .command("t") + case .newShellTab: .command("t", .shift) + case .newAgentTab: .command("t", .option) + case .newWorktree: .command("n") + case .addProject: .command("o") + case .openInEditor: .command("o", .shift) + case .closePane: .command("w") + case .closeTab: .command("w", .shift) + case .undo: .command("z") + case .redo: .command("z", .shift) + case .cut: .command("x") + case .copy: .command("c") + case .paste: .command("v") + case .selectAll: .command("a") + + // Ghostty binds Cmd+F to a search bar an embedding never shows. + case .find: .command("f") + + case .findNext: .command("g") + case .findPrevious: .command("g", .shift) + case .closeFind: .command("f", .option) + + // Not Cmd+A, which is Select All in a pane and stays there. + case .toggleAgentBoard: .command("a", .shift) + + case .quickSwitcher: .command("p") + case .quickSwitcherCommands: .command("p", .shift) + + // Cmd+Shift+F is Ghostty's end-search key, which would end a search under a bar of ours. + case .filesPane: .command("f", .shift) + + case .changesPane: .command("c", .shift) + case .reviewPane: .command("r", .shift) + case .splitRight: .command("d") + case .splitDown: .command("d", .shift) + + // Not Cmd+Option+D, the system's Dock hiding, which a menu bar never sees. + case .moveTabToNewGroup: .command("g", .option) + + // Alt and an arrow is word movement in a terminal; Command keeps both steps out of a pane's way. + case .focusNextGroup: KeyCombination(.rightArrow, [.command, .option]) + + case .focusPreviousGroup: KeyCombination(.leftArrow, [.command, .option]) + case .nextTab: KeyCombination(.tab, .control) + case .previousTab: KeyCombination(.tab, [.control, .shift]) + } + } +} diff --git a/Sources/MultishellCore/Model/Settings/Shortcuts/ShortcutKey.swift b/Sources/MultishellCore/Model/Settings/Shortcuts/ShortcutKey.swift new file mode 100644 index 000000000..364d772d3 --- /dev/null +++ b/Sources/MultishellCore/Model/Settings/Shortcuts/ShortcutKey.swift @@ -0,0 +1,35 @@ +/// The key a shortcut presses: a character as the keyboard layout types it +/// unshifted, lowercase, or a key that types none. +public enum ShortcutKey: Hashable, Sendable { + case backspace + case character(Character) + case downArrow + case end + case forwardDelete + /// F1 to F20, by number. + case function(Int) + case home + case leftArrow + case pageDown + case pageUp + case returnKey + case rightArrow + case space + case tab + case upArrow + + /// AppKit's function keys run to F35; past F20 no Mac keyboard has one. + public static let functionNumbers = 1...20 + + public static var namedKeys: [Self] { named.map(\.key) } + + /// Each key without a character, with its word in the state file and its + /// glyph. The words are `ControlKey`'s where it names the same key. + static let named: [(key: Self, word: String, glyph: String)] = [ + (.tab, "tab", "⇥"), (.returnKey, "enter", "↩"), (.space, "space", "Space"), + (.backspace, "backspace", "⌫"), (.forwardDelete, "delete", "⌦"), (.home, "home", "↖"), + (.end, "end", "↘"), (.pageUp, "pageup", "⇞"), (.pageDown, "pagedown", "⇟"), + (.leftArrow, "left", "←"), (.rightArrow, "right", "→"), (.upArrow, "up", "↑"), + (.downArrow, "down", "↓"), + ] +} diff --git a/Sources/MultishellCore/Model/Settings/Shortcuts/ShortcutModifiers+Glyphs.swift b/Sources/MultishellCore/Model/Settings/Shortcuts/ShortcutModifiers+Glyphs.swift new file mode 100644 index 000000000..a2ef9f147 --- /dev/null +++ b/Sources/MultishellCore/Model/Settings/Shortcuts/ShortcutModifiers+Glyphs.swift @@ -0,0 +1,6 @@ +extension ShortcutModifiers { + /// The modifiers alone, `⌃⌥`, as a recorder shows them while they are held. + public var glyphs: String { + String(Self.menuOrder.filter { contains($0.modifier) }.map(\.glyph)) + } +} diff --git a/Sources/MultishellCore/Model/Settings/Shortcuts/ShortcutModifiers.swift b/Sources/MultishellCore/Model/Settings/Shortcuts/ShortcutModifiers.swift new file mode 100644 index 000000000..da33ff57c --- /dev/null +++ b/Sources/MultishellCore/Model/Settings/Shortcuts/ShortcutModifiers.swift @@ -0,0 +1,19 @@ +/// The modifier keys held for a shortcut. +public struct ShortcutModifiers: OptionSet, Hashable, Sendable { + public static let control = Self(rawValue: 1 << 0) + public static let option = Self(rawValue: 1 << 1) + public static let shift = Self(rawValue: 1 << 2) + public static let command = Self(rawValue: 1 << 3) + + /// Each modifier with its glyph and its word in the state file, in the order + /// a menu draws them, ⌃⌥⇧⌘. + static let menuOrder: [(modifier: Self, glyph: Character, word: String)] = [ + (.control, "⌃", "ctrl"), (.option, "⌥", "alt"), (.shift, "⇧", "shift"), (.command, "⌘", "cmd"), + ] + + public let rawValue: Int + + public init(rawValue: Int) { + self.rawValue = rawValue + } +} diff --git a/Sources/MultishellCore/Model/Settings/Shortcuts/ShortcutOverride.swift b/Sources/MultishellCore/Model/Settings/Shortcuts/ShortcutOverride.swift new file mode 100644 index 000000000..030035e0b --- /dev/null +++ b/Sources/MultishellCore/Model/Settings/Shortcuts/ShortcutOverride.swift @@ -0,0 +1,6 @@ +/// What the user chose for a command in place of its default: other keys, or +/// none, its menu item staying. +public enum ShortcutOverride: Hashable, Sendable { + case keys(KeyCombination) + case noKeys +} diff --git a/Sources/MultishellCore/Model/Settings/Shortcuts/ShortcutOverrides+Codable.swift b/Sources/MultishellCore/Model/Settings/Shortcuts/ShortcutOverrides+Codable.swift new file mode 100644 index 000000000..d3f45462d --- /dev/null +++ b/Sources/MultishellCore/Model/Settings/Shortcuts/ShortcutOverrides+Codable.swift @@ -0,0 +1,40 @@ +/// An object of command to keys, `"split-right": "cmd+backslash"`, blank for +/// none. A synthesised dictionary would be an array, and a nil `null`. +extension ShortcutOverrides: Codable { + public init(from decoder: any Decoder) throws { + let container = try decoder.container(keyedBy: RawCodingKey.self) + self.init() + var held = Set(ShortcutCommand.allCases.filter(\.isFixed).map(\.defaultCombination)) + // Tolerated per entry, in `allCases` order: an unknown command, unreadable or + // refused keys, or a claim on keys an earlier one holds costs that entry alone. + for command in ShortcutCommand.changeable { + guard + let text = container.decodeTolerantly( + String.self, + forKey: RawCodingKey(stringValue: command.rawValue), + ) + else { continue } + guard let spelled = text.trimmedOfAllWhitespaceOrNil else { + set(.noKeys, for: command) + continue + } + guard let keys = KeyCombination(spelled: spelled), keys.refusal == nil, + held.insert(keys).inserted + else { continue } + set(.keys(keys), for: command) + } + } + + public func encode(to encoder: any Encoder) throws { + var container = encoder.container(keyedBy: RawCodingKey.self) + for command in ShortcutCommand.allCases { + guard let override = self[command] else { continue } + let text = + switch override { + case .keys(let keys): keys.spelled + case .noKeys: "" + } + try container.encode(text, forKey: RawCodingKey(stringValue: command.rawValue)) + } + } +} diff --git a/Sources/MultishellCore/Model/Settings/Shortcuts/ShortcutOverrides.swift b/Sources/MultishellCore/Model/Settings/Shortcuts/ShortcutOverrides.swift new file mode 100644 index 000000000..17ba0e3e7 --- /dev/null +++ b/Sources/MultishellCore/Model/Settings/Shortcuts/ShortcutOverrides.swift @@ -0,0 +1,41 @@ +/// The commands whose keys the user changed, and what to. Only changes are +/// kept, so a default a later build changes reaches every command left alone. +public struct ShortcutOverrides: Hashable, Sendable { + private var entries: [ShortcutCommand: ShortcutOverride] = [:] + + public var isEmpty: Bool { entries.isEmpty } + + public init() {} + + /// The keys in force. A default another command's override now holds, as a + /// later build's new default can be, leaves this command none. + public func keys(for command: ShortcutCommand) -> KeyCombination? { + if command.isFixed { return command.defaultCombination } + switch entries[command] { + case .keys(let keys): return keys + case .noKeys: return nil + + case nil: + let isTaken = entries.values.contains(.keys(command.defaultCombination)) + return isTaken ? nil : command.defaultCombination + } + } + + /// The command whose keys these are now, if any. + public func command(holding keys: KeyCombination) -> ShortcutCommand? { + ShortcutCommand.allCases.first { self.keys(for: $0) == keys } + } + + /// `nil`, or the default itself, puts the command back on its default. + public mutating func set(_ override: ShortcutOverride?, for command: ShortcutCommand) { + guard !command.isFixed, override != .keys(command.defaultCombination) else { + entries[command] = nil + return + } + entries[command] = override + } + + public subscript(command: ShortcutCommand) -> ShortcutOverride? { + entries[command] + } +} diff --git a/Sources/MultishellCore/Model/Settings/Shortcuts/ShortcutRefusal.swift b/Sources/MultishellCore/Model/Settings/Shortcuts/ShortcutRefusal.swift new file mode 100644 index 000000000..a8d3e5ae4 --- /dev/null +++ b/Sources/MultishellCore/Model/Settings/Shortcuts/ShortcutRefusal.swift @@ -0,0 +1,19 @@ +/// Why keys cannot be a command's, said under the row while it records. +public enum ShortcutRefusal: Hashable, Sendable { + /// ⌘ with an arrow or Delete, or ⌃⇧ with a sideways arrow, moves, selects or + /// deletes to a line's or a text's ends in every text field. + case editsText + /// Cut, Copy, Paste or Select All hold the keys and cannot let them go. + case heldByFixed(ShortcutCommand) + /// No ⌘, ⌃ or ⌥, and not an F-key: every text field would lose the key. + case needsModifier + /// ⌥ with a key `KeyCombination+Refusal` lists moves or deletes by word, or + /// breaks a line, in every text field. + case optionEditsText + /// ⌥ and a character types a character on many layouts, ⌥L being @ on a + /// German one, in every text field. + case optionTypesCharacter + /// A key a pane's program needs, or one the pane types before the menus see it. + case programKey(KeyCombination) + case reserved(ReservedShortcut) +} diff --git a/Sources/MultishellCore/Model/Workspace.swift b/Sources/MultishellCore/Model/Workspace.swift index a265564f0..95e2c2083 100644 --- a/Sources/MultishellCore/Model/Workspace.swift +++ b/Sources/MultishellCore/Model/Workspace.swift @@ -22,6 +22,7 @@ public struct Workspace: Codable, Hashable, Sendable { case gitStatusIndicator, diffAlgorithm, fileTabLayout, filesPanelMode, changeScope case showsFilesPanel, showsIgnoredFiles, showsAllTerminals case portBlockStart, portBlockSize, portBlocks + case shortcutOverrides = "shortcuts" } /// Keys no property answers to any more, read only to carry what an older @@ -137,6 +138,7 @@ public struct Workspace: Codable, Hashable, Sendable { /// block's ports; only a worktree left without a port changes block. public internal(set) var portBlockStart = PortBlock.defaultStart public internal(set) var portBlockSize = PortBlock.defaultSize + public internal(set) var shortcutOverrides = ShortcutOverrides() /// `projectHookTimeoutSeconds` as the runner takes it; `nil` for no limit. public var projectHookTimeout: Duration? { @@ -296,6 +298,11 @@ public struct Workspace: Codable, Hashable, Sendable { guard case .integer(let index) = value else { return nil } return index } + shortcutOverrides = container.decodeTolerantly( + ShortcutOverrides.self, + forKey: .shortcutOverrides, + or: ShortcutOverrides(), + ) // A file written before groups names no group but says which tab was // active. Read here, or `repair` falls back to the last tab. diff --git a/Sources/MultishellCore/Ports/TerminalHost.swift b/Sources/MultishellCore/Ports/TerminalHost.swift index c222b0c4a..80eaa42ee 100644 --- a/Sources/MultishellCore/Ports/TerminalHost.swift +++ b/Sources/MultishellCore/Ports/TerminalHost.swift @@ -27,8 +27,9 @@ public protocol TerminalHost: AnyObject { @discardableResult func press(_ keys: [ControlKey], in id: TerminalSession.ID) -> Bool - /// Applied to every open terminal and to any opened afterwards. - func apply(_ theme: Theme, appearance: Appearance) + /// Applied to every open terminal and to any opened afterwards. `unbinding` + /// are the menus' keys, which the engine must not take first. + func apply(_ theme: Theme, appearance: Appearance, unbinding: [KeyCombination]) /// A step of the engine's own search over the session's scrollback. /// `false` where the engine has no such session, or no search at all. diff --git a/Sources/MultishellCore/Resources/en.lproj/Localizable.strings b/Sources/MultishellCore/Resources/en.lproj/Localizable.strings index c360e7451..d4a34044b 100644 --- a/Sources/MultishellCore/Resources/en.lproj/Localizable.strings +++ b/Sources/MultishellCore/Resources/en.lproj/Localizable.strings @@ -536,6 +536,7 @@ "shell.named-login-shell" = "the login shell (%@)"; "shell.path-blank" = "Blank, so tabs run the login shell, %@."; "shell.path-not-executable" = "Nothing executable at that path; a new tab would fail to start."; +"shortcuts.in-parentheses" = " (%@)"; "sidebar.counts" = "%1$@ · %2$@"; "sidebar.no-projects" = "No projects yet"; "sidebar.nothing-matches" = "Nothing matches"; @@ -662,10 +663,10 @@ "tab.new-named-agent" = "New %@ Tab"; "tab.shell" = "Shell"; "tab.split-down" = "Split Down"; -"tab.split-down-here" = "Split Down (⇧⌘D)"; +"tab.split-down-here" = "Split Down%@"; "tab.split-down-in-group" = "Split Down in This Group"; "tab.split-right" = "Split Right"; -"tab.split-right-here" = "Split Right (⌘D)"; +"tab.split-right-here" = "Split Right%@"; "tab.split-right-in-group" = "Split Right in This Group"; "worker.background-shell" = "background shell"; "worker.occurrences" = "×%d"; diff --git a/Sources/MultishellCore/Store/WorkspaceStore.swift b/Sources/MultishellCore/Store/WorkspaceStore.swift index 6a2e7e77e..f3184e64f 100644 --- a/Sources/MultishellCore/Store/WorkspaceStore.swift +++ b/Sources/MultishellCore/Store/WorkspaceStore.swift @@ -856,5 +856,9 @@ extension WorkspaceStore { public func setShowsAllTerminals(_ shows: Bool) { workspace.showsAllTerminals = shows } + + public func setShortcutOverrides(_ overrides: ShortcutOverrides) { + workspace.shortcutOverrides = overrides + } } // swiftlint:enable no_grouping_extension diff --git a/Tests/MultishellAppCoreTests/FakeEngine.swift b/Tests/MultishellAppCoreTests/FakeEngine.swift index 530425c51..096a9ed35 100644 --- a/Tests/MultishellAppCoreTests/FakeEngine.swift +++ b/Tests/MultishellAppCoreTests/FakeEngine.swift @@ -32,6 +32,8 @@ final class FakeEngine: TerminalSurfaceHost { var frames: [TerminalSession.ID: CGRect] = [:] /// Every theme handed to the engine, in order. var appliedThemes: [Theme] = [] + /// The keys the engine was last told to unbind. + var unbound: [KeyCombination] = [] func open(_ session: TerminalSession) throws { if refusesToOpen { throw OpenRefused() } @@ -76,5 +78,8 @@ final class FakeEngine: TerminalSurfaceHost { } func screenshot(of id: TerminalSession.ID) -> Data? { screenshots[id] } func frame(of id: TerminalSession.ID) -> CGRect? { frames[id] } - func apply(_ theme: Theme, appearance: Appearance) { appliedThemes.append(theme) } + func apply(_ theme: Theme, appearance: Appearance, unbinding: [KeyCombination]) { + appliedThemes.append(theme) + unbound = unbinding + } } diff --git a/Tests/MultishellAppCoreTests/FakePlatform.swift b/Tests/MultishellAppCoreTests/FakePlatform.swift index 0dbcd7c55..8e5d90893 100644 --- a/Tests/MultishellAppCoreTests/FakePlatform.swift +++ b/Tests/MultishellAppCoreTests/FakePlatform.swift @@ -54,6 +54,8 @@ final class FakePlatform: Platform { var commandMenuItems: [PlatformMenuItem] { menuItems } var performedMenuItems: [[String]] = [] var chosenMenuItems: [[String]] = [] + /// The keys each command's menu item was last given. + var menuShortcuts: [ShortcutCommand: KeyCombination?] = [:] var shownWindows: [AuxiliaryWindow] = [] var closedWindows: [AuxiliaryWindow] = [] /// `nil` stands for a closed main window. @@ -140,6 +142,9 @@ final class FakePlatform: Platform { func screenshotSettingsWindow() -> Data? { settingsWindowScreenshot } func signpost(_ name: String) { signposts.append(name) } func hasFontFamily(_ family: String) -> Bool { fontFamilies.contains(family) } + func setMenuShortcuts(_ shortcuts: [MenuShortcut]) { + for shortcut in shortcuts { menuShortcuts[shortcut.command] = .some(shortcut.keys) } + } func performMenuItem(_ path: [String]) -> PlatformMenuOutcome { guard let item = menuItems.first(where: { $0.path == path }) else { return .notFound } guard item.isEnabled else { return .disabled } diff --git a/Tests/MultishellAppCoreTests/Model/Control/AppModel+ControlGlobalSettingTableTests.swift b/Tests/MultishellAppCoreTests/Model/Control/AppModel+ControlGlobalSettingTableTests.swift new file mode 100644 index 000000000..9fd094ac7 --- /dev/null +++ b/Tests/MultishellAppCoreTests/Model/Control/AppModel+ControlGlobalSettingTableTests.swift @@ -0,0 +1,75 @@ +import Foundation +import Testing + +@testable import MultishellAppCore +@testable import MultishellCore + +@Suite @MainActor +struct AppModelControlGlobalSettingTableTests { + private func write(_ harness: Harness, _ key: String, _ value: String) async -> ControlReply? { + await harness.messageSource.ask(.writeGlobalSetting(key: key, value: value)) + } + + @Test func eachChangeableCommandHasARowReadInTheStateFilesSpelling() async throws { + let harness = Harness() + + let reply = try #require(await harness.messageSource.ask(.readGlobalSettings(key: nil))) + + #expect(reply.outputFields["shortcuts.split-right"] as? String == "cmd+d") + #expect(reply.outputFields["shortcuts.copy"] == nil, "Copy cannot change") + } + + @Test func aRowTakesTheStoredSpellingGlyphsOrNone() async { + let harness = Harness() + + #expect(await write(harness, "shortcuts.split-right", "cmd+backslash") == .done) + #expect(await write(harness, "shortcuts.split-down", "⌥⌘\\") == .done) + #expect(await write(harness, "shortcuts.close-find", "none") == .done) + + #expect( + harness.model.shortcutKeys(for: .splitRight) == KeyCombination(.character("\\"), .command) + ) + #expect( + harness.model.shortcutKeys(for: .splitDown) + == KeyCombination(.character("\\"), [.command, .option]) + ) + #expect(harness.model.shortcutKeys(for: .closeFind) == nil) + } + + @Test func aRowRefusesWhatTheJudgeRefusesOrAnotherCommandHolds() async { + let harness = Harness() + + #expect( + await write(harness, "shortcuts.split-right", "cmd+q") + == .refused(.invalidValue(key: "shortcuts.split-right", value: "cmd+q")) + ) + #expect( + await write(harness, "shortcuts.split-right", "cmd+p") + == .refused(.invalidValue(key: "shortcuts.split-right", value: "cmd+p")) + ) + #expect(!harness.model.hasChangedShortcuts) + } + + @Test func aCommandWhoseDefaultAnotherHoldsReadsBlankSoWritingItBackChangesNothing() async throws + { + let harness = Harness() + var overrides = ShortcutOverrides() + overrides.set(.keys(ShortcutCommand.newTab.defaultCombination), for: .findNext) + harness.store.setShortcutOverrides(overrides) + + let reply = try #require(await harness.messageSource.ask(.readGlobalSettings(key: nil))) + let read = try #require(reply.outputFields["shortcuts.new-tab"] as? String) + #expect(read.isEmpty) + #expect(await write(harness, "shortcuts.new-tab", read) == .done) + #expect(!harness.model.isShortcutChanged(.newTab)) + } + + @Test func aBlankValueResetsTheCommand() async { + let harness = Harness() + harness.model.setShortcut(nil, for: .closeFind) + + #expect(await write(harness, "shortcuts.close-find", "") == .done) + + #expect(!harness.model.isShortcutChanged(.closeFind)) + } +} diff --git a/Tests/MultishellAppCoreTests/Model/Control/AppModel+ControlViewsTests.swift b/Tests/MultishellAppCoreTests/Model/Control/AppModel+ControlViewsTests.swift index 18cfce9c5..9da0cabe9 100644 --- a/Tests/MultishellAppCoreTests/Model/Control/AppModel+ControlViewsTests.swift +++ b/Tests/MultishellAppCoreTests/Model/Control/AppModel+ControlViewsTests.swift @@ -104,7 +104,8 @@ struct AppModelControlViewsTests { .hooksCreate, pages: [ .general, .worktrees, .terminal, .agents, .agentSettings, .agentHooks, - .notifications, .appearance, + .notifications, .appearance, .shortcutsFile, .shortcutsEdit, .shortcutsView, + .shortcutsTerminal, ], ) ) diff --git a/Tests/MultishellAppCoreTests/Model/Settings/AppModel+ShortcutEditingTests.swift b/Tests/MultishellAppCoreTests/Model/Settings/AppModel+ShortcutEditingTests.swift new file mode 100644 index 000000000..6cdf085f1 --- /dev/null +++ b/Tests/MultishellAppCoreTests/Model/Settings/AppModel+ShortcutEditingTests.swift @@ -0,0 +1,121 @@ +import MultishellCore +import Testing + +@testable import MultishellAppCore + +@Suite @MainActor +struct AppModelShortcutEditingTests { + private let backslash = KeyCombination(.character("\\"), .command) + private let commandK = KeyCombination(.character("k"), .command) + + @Test func recordedKeysAreSetOrTurnedIntoTheNextStep() { + let harness = Harness() + harness.model.startRecordingShortcut(for: .splitRight) + + harness.model.takeRecordedShortcut(backslash, for: .splitRight) + #expect(harness.model.shortcutEditing == nil) + #expect(harness.model.shortcutKeys(for: .splitRight) == backslash) + + harness.model.takeRecordedShortcut(ReservedShortcut.quit.combination, for: .splitDown) + #expect( + harness.model.shortcutEditing + == ShortcutEditing(command: .splitDown, step: .recording(.reserved(.quit))) + ) + + harness.model.takeRecordedShortcut(backslash, for: .splitDown) + #expect( + harness.model.shortcutEditing + == ShortcutEditing( + command: .splitDown, + step: .confirming(backslash, takenFrom: .splitRight), + ) + ) + } + + @Test func onlyTheRowBeingEditedHasAStep() { + let harness = Harness() + harness.model.startRecordingShortcut(for: .splitRight) + + #expect(harness.model.shortcutEditingStep(for: .splitRight) == .recording(nil)) + #expect(harness.model.shortcutEditingStep(for: .splitDown) == nil) + } + + @Test func replaceAnswersTheOpenQuestionLeavingTheHolderNone() { + let harness = Harness() + harness.model.takeRecordedShortcut(backslash, for: .splitRight) + harness.model.takeRecordedShortcut(backslash, for: .splitDown) + + harness.model.replaceAskedShortcut() + + #expect(harness.model.shortcutEditing == nil) + #expect(harness.model.shortcutKeys(for: .splitDown) == backslash) + #expect(harness.model.shortcutKeys(for: .splitRight) == nil) + } + + @Test func anOpenQuestionEndsWhenTheShortcutsChangeUnderIt() { + let harness = Harness() + harness.model.takeRecordedShortcut(backslash, for: .splitRight) + harness.model.takeRecordedShortcut(backslash, for: .splitDown) + + harness.model.restoreDefaultShortcuts() + + #expect(harness.model.shortcutEditing == nil, "Replace would undo part of the restore") + harness.model.replaceAskedShortcut() + #expect(!harness.model.hasChangedShortcuts) + } + + @Test func theRestoreQuestionEndsWhenTheShortcutsChangeOrThePageGoes() { + let harness = Harness() + harness.model.setShortcut(backslash, for: .splitRight) + harness.model.askToRestoreShortcuts() + #expect(harness.model.isAskingToRestoreShortcuts) + + harness.model.setShortcut(nil, for: .splitRight) + #expect(!harness.model.isAskingToRestoreShortcuts) + + harness.model.askToRestoreShortcuts() + harness.model.endShortcutsPageEdit() + #expect(!harness.model.isAskingToRestoreShortcuts) + } + + @Test func resetOntoADefaultAnotherCommandNowHoldsAsksFirst() { + let harness = Harness() + let splitDownKeys = ShortcutCommand.splitDown.defaultCombination + harness.model.setShortcut(commandK, for: .splitDown) + harness.model.setShortcut(splitDownKeys, for: .quickSwitcher) + + harness.model.resetShortcut(.splitDown) + + #expect( + harness.model.shortcutEditing + == ShortcutEditing( + command: .splitDown, + step: .confirming(splitDownKeys, takenFrom: .quickSwitcher), + ) + ) + #expect( + harness.model.shortcutKeys(for: .splitDown) == commandK, + "nothing changes until Replace", + ) + } + + @Test func resettingACommandToAFreeDefaultRemovesTheChangeWithoutAsking() { + let harness = Harness() + harness.model.setShortcut(backslash, for: .splitRight) + + harness.model.resetShortcut(.splitRight) + + #expect(harness.model.shortcutEditing == nil) + #expect(!harness.model.isShortcutChanged(.splitRight)) + } + + @Test func deleteWhileRecordingLeavesTheCommandNoKeysAndEndsTheEdit() { + let harness = Harness() + harness.model.startRecordingShortcut(for: .closeFind) + + harness.model.clearRecordedShortcut(for: .closeFind) + + #expect(harness.model.shortcutEditing == nil) + #expect(harness.model.shortcutKeys(for: .closeFind) == nil) + } +} diff --git a/Tests/MultishellAppCoreTests/Model/Settings/AppModel+ShortcutsTests.swift b/Tests/MultishellAppCoreTests/Model/Settings/AppModel+ShortcutsTests.swift new file mode 100644 index 000000000..ed82ed23b --- /dev/null +++ b/Tests/MultishellAppCoreTests/Model/Settings/AppModel+ShortcutsTests.swift @@ -0,0 +1,107 @@ +import MultishellCore +import Testing + +@testable import MultishellAppCore + +@Suite @MainActor +struct AppModelShortcutsTests { + private let backslash = KeyCombination(.character("\\"), .command) + private let commandK = KeyCombination(.character("k"), .command) + + @Test func anAllowedSetChangesTheKeysTheMenuAndTheEngine() { + let harness = Harness() + + #expect(harness.model.setShortcut(backslash, for: .splitRight) == .allowed(nil)) + + #expect(harness.model.shortcutKeys(for: .splitRight) == backslash) + #expect(harness.platform.menuShortcuts[.splitRight] == .some(backslash)) + #expect(harness.engine.unbound.contains(backslash)) + } + + @Test func aRefusedOrTakenSetChangesNothing() { + let harness = Harness() + let quit = ReservedShortcut.quit.combination + + #expect(harness.model.setShortcut(quit, for: .splitRight) == .refused(.reserved(.quit))) + #expect( + harness.model.setShortcut(KeyCombination(.character("p"), .command), for: .splitRight) + == .taken(holder: .quickSwitcher) + ) + #expect(!harness.model.hasChangedShortcuts) + } + + @Test func replaceLeavesTheCommandThatHeldTheKeysWithNone() { + let harness = Harness() + let switcherKeys = ShortcutCommand.quickSwitcher.defaultCombination + + harness.model.replaceShortcut(switcherKeys, for: .splitDown) + + #expect(harness.model.shortcutKeys(for: .splitDown) == switcherKeys) + #expect(harness.model.shortcutKeys(for: .quickSwitcher) == nil) + #expect(harness.platform.menuShortcuts[.quickSwitcher] == .some(nil)) + } + + @Test func restoreDefaultsClearsEveryChange() { + let harness = Harness() + harness.model.setShortcut(backslash, for: .splitRight) + harness.model.setShortcut(nil, for: .closeFind) + + harness.model.restoreDefaultShortcuts() + + #expect(!harness.model.hasChangedShortcuts) + #expect( + harness.model.shortcutKeys(for: .closeFind) == ShortcutCommand.closeFind.defaultCombination + ) + } + + @Test func theUnbindListHoldsTheDefaultAndTheOverrideButNoClipboardKeys() { + let harness = Harness() + harness.model.setShortcut(backslash, for: .splitRight) + + let unbinds = harness.model.surfaceUnbinds + + #expect(unbinds.contains(backslash)) + #expect(unbinds.contains(ShortcutCommand.splitRight.defaultCombination)) + for command in [ShortcutCommand.undo, .redo, .find] { + #expect(unbinds.contains(command.defaultCombination), "fixed, yet a pane must give it up") + } + for command in ShortcutCommand.allCases where command.surfaceKeepsBinding { + #expect(!unbinds.contains(command.defaultCombination), "\(command)") + } + } + + @Test func aCommandLeftAloneWhoseDefaultAnotherOverrideHoldsNamesThatCommand() { + let harness = Harness() + var overrides = ShortcutOverrides() + overrides.set(.keys(ShortcutCommand.newTab.defaultCombination), for: .findNext) + harness.store.setShortcutOverrides(overrides) + + #expect(harness.model.shortcutKeys(for: .newTab) == nil) + #expect(harness.model.commandHoldingDefault(of: .newTab) == .findNext) + #expect( + harness.model.commandHoldingDefault(of: .findNext) == nil, + "Find Next holds its own keys", + ) + } + + @Test func aPartCountsItsChangedCommands() { + let harness = Harness() + harness.model.setShortcut(backslash, for: .splitRight) + harness.model.setShortcut(nil, for: .nextTab) + + #expect(harness.model.changedShortcutCount(in: .shortcutsTerminal) == 2) + #expect(harness.model.changedShortcutCount(in: .shortcutsFile) == 0) + } + + @Test func aChangeWithoutCommandWarnsForAsLongAsItStands() { + let harness = Harness() + let controlR = KeyCombination(.character("r"), .control) + harness.model.setShortcut(controlR, for: .quickSwitcher) + + #expect( + harness.model.shortcutWarning(for: .quickSwitcher) + == ShortcutWarning(keys: controlR, shellUse: .historySearch) + ) + #expect(harness.model.shortcutWarning(for: .nextTab) == nil, "a default says nothing") + } +} diff --git a/Tests/MultishellAppCoreTests/Settings/AppWide/Shortcuts/ShortcutGroupTests.swift b/Tests/MultishellAppCoreTests/Settings/AppWide/Shortcuts/ShortcutGroupTests.swift new file mode 100644 index 000000000..4798c0e77 --- /dev/null +++ b/Tests/MultishellAppCoreTests/Settings/AppWide/Shortcuts/ShortcutGroupTests.swift @@ -0,0 +1,19 @@ +import MultishellCore +import Testing + +@testable import MultishellAppCore + +@Suite +struct ShortcutGroupTests { + @Test func everyCommandIsOnExactlyOneCard() { + let listed = ShortcutGroup.allCases.flatMap(\.commands) + #expect(listed.count == ShortcutCommand.allCases.count) + #expect(Set(listed) == Set(ShortcutCommand.allCases)) + } + + @Test func everyShortcutsPartHasCards() { + for section in SettingsPage.shortcuts.sections(in: .allProjects) { + #expect(!ShortcutGroup.groups(in: section).isEmpty, "\(section)") + } + } +} diff --git a/Tests/MultishellAppCoreTests/Settings/AppWide/Shortcuts/ShortcutOverrides+JudgementTests.swift b/Tests/MultishellAppCoreTests/Settings/AppWide/Shortcuts/ShortcutOverrides+JudgementTests.swift new file mode 100644 index 000000000..1ff52d070 --- /dev/null +++ b/Tests/MultishellAppCoreTests/Settings/AppWide/Shortcuts/ShortcutOverrides+JudgementTests.swift @@ -0,0 +1,198 @@ +import MultishellCore +import Testing + +@testable import MultishellAppCore + +@Suite +struct ShortcutOverridesJudgementTests { + private let overrides = ShortcutOverrides() + + private func keys(_ character: Character, _ modifiers: ShortcutModifiers) -> KeyCombination { + KeyCombination(.character(character), modifiers) + } + + @Test func aKeyWithNoCommandControlOrOptionIsRefusedUnlessItIsAnFKey() { + #expect(overrides.judge(keys("k", []), for: .findNext) == .refused(.needsModifier)) + #expect(overrides.judge(keys("k", .shift), for: .findNext) == .refused(.needsModifier)) + #expect( + overrides.judge(KeyCombination(.function(5)), for: .findNext) + == .allowed(ShortcutWarning(keys: KeyCombination(.function(5)), shellUse: nil)) + ) + } + + @Test func optionWithACharacterIsRefusedAsItTypesOneOnManyLayouts() { + #expect( + overrides.judge(keys("l", .option), for: .findNext) == .refused(.optionTypesCharacter) + ) + #expect( + overrides.judge(keys("l", [.option, .shift]), for: .findNext) + == .refused(.optionTypesCharacter) + ) + #expect(overrides.judge(keys("l", [.option, .command]), for: .findNext) == .allowed(nil)) + } + + @Test func optionWithAKeyThatEditsTextIsRefusedWithoutCommandOrControl() { + for key in [ShortcutKey.backspace, .leftArrow, .rightArrow, .returnKey, .tab] { + let combination = KeyCombination(key, .option) + #expect( + overrides.judge(combination, for: .findNext) == .refused(.optionEditsText), + "\(key)", + ) + } + #expect( + overrides.judge(KeyCombination(.space, .option), for: .findNext) + == .refused(.optionTypesCharacter) + ) + #expect( + overrides.judge(KeyCombination(.backspace, [.option, .command]), for: .findNext) + == .allowed(nil) + ) + } + + @Test func controlShiftWithASidewaysArrowSelectsToALinesEndAndIsRefused() { + for key in [ShortcutKey.leftArrow, .rightArrow] { + let combination = KeyCombination(key, [.control, .shift]) + #expect(overrides.judge(combination, for: .findNext) == .refused(.editsText), "\(key)") + } + } + + @Test func commandWithAnArrowOrDeleteIsRefusedAsEveryTextFieldUsesIt() { + for key in [ShortcutKey.leftArrow, .rightArrow, .upArrow, .downArrow, .backspace] { + for modifiers in [ShortcutModifiers.command, [.command, .shift]] { + let combination = KeyCombination(key, modifiers) + #expect(overrides.judge(combination, for: .findNext) == .refused(.editsText), "\(key)") + } + } + #expect( + overrides.judge(KeyCombination(.rightArrow, [.command, .option]), for: .findNext) + == .taken(holder: .focusNextGroup) + ) + } + + @Test func optionWithAKeyTextFieldsDoNothingWithIsAllowedWithTheWarning() { + for key in [ShortcutKey.home, .end] { + let combination = KeyCombination(key, .option) + #expect( + overrides.judge(combination, for: .findNext) + == .allowed(ShortcutWarning(keys: combination, shellUse: nil)), + "\(key)", + ) + } + for key in [ShortcutKey.forwardDelete, .pageUp, .pageDown] { + #expect( + overrides.judge(KeyCombination(key, .option), for: .findNext) == .refused(.optionEditsText) + ) + } + } + + @Test func commandPeriodIsAppKitsCancelAndReserved() { + #expect(overrides.judge(keys(".", .command), for: .findNext) == .refused(.reserved(.cancel))) + } + + @Test func keysThePaneTypesBeforeTheMenusSeeThemAreRefused() { + let controlReturn = KeyCombination(.returnKey, .control) + let controlSlash = keys("/", .control) + let commandControlReturn = KeyCombination(.returnKey, [.control, .command]) + #expect(overrides.judge(controlReturn, for: .findNext) == .refused(.programKey(controlReturn))) + #expect(overrides.judge(controlSlash, for: .findNext) == .refused(.programKey(controlSlash))) + #expect( + overrides.judge(commandControlReturn, for: .findNext) + == .refused(.programKey(commandControlReturn)) + ) + #expect(overrides.judge(keys("/", [.control, .command]), for: .findNext) == .allowed(nil)) + } + + @Test func appKitsOwnTabOverviewAndHelpSearchKeysAreReserved() { + #expect( + overrides.judge(keys("\\", [.shift, .command]), for: .findNext) + == .refused(.reserved(.showAllTabs)) + ) + #expect( + overrides.judge(keys("/", [.shift, .command]), for: .findNext) + == .refused(.reserved(.helpSearch)) + ) + } + + @Test func theAppleMenusLogOutAndLockScreenKeysAreReserved() { + #expect( + overrides.judge(keys("q", [.shift, .command]), for: .findNext) == .refused(.reserved(.logOut)) + ) + #expect( + overrides.judge(keys("q", [.option, .shift, .command]), for: .findNext) + == .refused(.reserved(.logOutNow)) + ) + #expect( + overrides.judge(keys("q", [.control, .command]), for: .findNext) + == .refused(.reserved(.lockScreen)) + ) + } + + @Test func theSystemsScreenshotSpacesSearchAndInputSourceKeysAreReserved() { + let systemKeys = [ + keys("3", [.shift, .command]), keys("4", [.shift, .command]), keys("5", [.shift, .command]), + keys("3", [.control, .shift, .command]), keys("4", [.control, .shift, .command]), + KeyCombination(.leftArrow, .control), KeyCombination(.rightArrow, .control), + KeyCombination(.upArrow, .control), KeyCombination(.downArrow, .control), + KeyCombination(.space, [.option, .command]), KeyCombination(.space, .control), + KeyCombination(.space, [.control, .option]), KeyCombination(.space, [.control, .command]), + KeyCombination(.tab, [.shift, .command]), keys("`", [.shift, .command]), + KeyCombination(.function(5), .command), KeyCombination(.function(5), [.option, .command]), + keys("d", [.control, .command]), keys("m", [.option, .command]), + ] + for combination in systemKeys { + guard case .refused(.reserved) = overrides.judge(combination, for: .findNext) else { + Issue.record("\(combination.glyphs) is the system's") + continue + } + } + } + + @Test func controlBracketIsAPanesEscapeAndRefused() { + let controlBracket = keys("[", .control) + #expect( + overrides.judge(controlBracket, for: .findNext) == .refused(.programKey(controlBracket)) + ) + } + + @Test func everyReservedCombinationIsRefusedAsTheSystems() { + for reserved in ReservedShortcut.allCases { + #expect( + overrides.judge(reserved.combination, for: .findNext) == .refused(.reserved(reserved)) + ) + } + } + + @Test func theControlKeysAProgramNeedsAreRefused() { + for character in ["c", "d", "z", "\\"] as [Character] { + let combination = keys(character, .control) + #expect(overrides.judge(combination, for: .findNext) == .refused(.programKey(combination))) + } + } + + @Test func keysWithoutCommandAreAllowedNamingWhatTheShellLoses() { + #expect( + overrides.judge(keys("r", .control), for: .findNext) + == .allowed(ShortcutWarning(keys: keys("r", .control), shellUse: .historySearch)) + ) + #expect( + overrides.judge(keys("g", [.control, .option]), for: .findNext) + == .allowed(ShortcutWarning(keys: keys("g", [.control, .option]), shellUse: nil)) + ) + } + + @Test func anotherCommandsKeysAreTakenAndAFixedCommandsRefused() { + #expect( + overrides.judge(keys("p", .command), for: .findNext) == .taken(holder: .quickSwitcher) + ) + #expect(overrides.judge(keys("c", .command), for: .findNext) == .refused(.heldByFixed(.copy))) + #expect(overrides.judge(keys("f", .command), for: .findNext) == .refused(.heldByFixed(.find))) + #expect( + overrides.judge(keys("z", [.shift, .command]), for: .findNext) + == .refused(.heldByFixed(.redo)) + ) + } + + @Test func aCommandsOwnKeysAreAllowed() { + #expect(overrides.judge(keys("g", .command), for: .findNext) == .allowed(nil)) + } +} diff --git a/Tests/MultishellAppCoreTests/Settings/SettingsLocationTests.swift b/Tests/MultishellAppCoreTests/Settings/SettingsLocationTests.swift index c38b3f9d6..eb19b247d 100644 --- a/Tests/MultishellAppCoreTests/Settings/SettingsLocationTests.swift +++ b/Tests/MultishellAppCoreTests/Settings/SettingsLocationTests.swift @@ -38,13 +38,23 @@ struct SettingsLocationTests { ) } + @Test func aSplitPagesPartsShowOnlyWhileThatPageIsOpen() { + let general = SettingsLocation(scope: .allProjects, section: .general) + #expect(!general.showsParts(of: .agents)) + #expect(!general.showsParts(of: .shortcuts)) + + let terminalPart = SettingsLocation(scope: .allProjects, section: .shortcutsTerminal) + #expect(terminalPart.showsParts(of: .shortcuts)) + #expect(!terminalPart.showsParts(of: .agents)) + } + @Test func theArrowsStepThroughPagesAndPartsAndStopAtEitherEnd() { let general = SettingsLocation(scope: .allProjects, section: .general) let pages = SettingsPage.pages(in: .allProjects) #expect(general.stepped(by: -1, among: pages) == general) #expect(general.stepped(by: 3, among: pages).section == .agentSettings) #expect(general.stepped(by: 4, among: pages).section == .agentHooks) - #expect(general.stepped(by: 99, among: pages).section == .appearance) + #expect(general.stepped(by: 99, among: pages).section == .shortcutsTerminal) let terminal = SettingsLocation(scope: Self.project, section: .terminal) #expect( diff --git a/Tests/MultishellAppCoreTests/Settings/Sidebar/SettingsPageTests.swift b/Tests/MultishellAppCoreTests/Settings/Sidebar/SettingsPageTests.swift index b3c1061ab..ac3231abf 100644 --- a/Tests/MultishellAppCoreTests/Settings/Sidebar/SettingsPageTests.swift +++ b/Tests/MultishellAppCoreTests/Settings/Sidebar/SettingsPageTests.swift @@ -10,7 +10,7 @@ struct SettingsPageTests { @Test func eachScopeListsItsOwnPagesInTheWindowsOrder() { #expect( SettingsPage.pages(in: .allProjects) - == [.general, .worktrees, .terminal, .agents, .notifications, .appearance] + == [.general, .worktrees, .terminal, .agents, .notifications, .appearance, .shortcuts] ) #expect( SettingsPage.pages(in: Self.project) @@ -33,6 +33,11 @@ struct SettingsPageTests { @Test func onlyAllProjectsAgentsAndAProjectsHooksAreSplitIntoParts() { #expect(SettingsPage.agents.sections(in: .allProjects) == [.agentSettings, .agentHooks]) #expect(SettingsPage.agents.sections(in: Self.project) == [.agents]) + #expect( + SettingsPage.shortcuts.sections(in: .allProjects) + == [.shortcutsFile, .shortcutsEdit, .shortcutsView, .shortcutsTerminal] + ) + #expect(SettingsPage.shortcuts.sections(in: Self.project).isEmpty, "global only") #expect( SettingsPage.hooks.sections(in: Self.project) == [.hooksCreate, .hooksDelete, .hooksEnvironment] diff --git a/Tests/MultishellAppCoreTests/Terminals/Groups/TabStripButtonTextTests.swift b/Tests/MultishellAppCoreTests/Terminals/Groups/TabStripButtonTextTests.swift index e10a30ec9..2230cd07d 100644 --- a/Tests/MultishellAppCoreTests/Terminals/Groups/TabStripButtonTextTests.swift +++ b/Tests/MultishellAppCoreTests/Terminals/Groups/TabStripButtonTextTests.swift @@ -6,17 +6,42 @@ import Testing @Suite struct TabStripButtonTextTests { @Test func onlyTheFocusedGroupsSplitButtonsNameTheKeystroke() { - #expect(TabStripButtonText.splitHelp(.horizontal, isFocusedGroup: true) == "Split Right (⌘D)") - #expect(TabStripButtonText.splitHelp(.vertical, isFocusedGroup: true) == "Split Down (⇧⌘D)") + let right = ShortcutCommand.splitRight.defaultCombination + let down = ShortcutCommand.splitDown.defaultCombination #expect( - TabStripButtonText.splitHelp(.horizontal, isFocusedGroup: false) + TabStripButtonText.splitHelp(.horizontal, isFocusedGroup: true, keys: right) + == "Split Right (⌘D)" + ) + #expect( + TabStripButtonText.splitHelp(.vertical, isFocusedGroup: true, keys: down) + == "Split Down (⇧⌘D)" + ) + #expect( + TabStripButtonText.splitHelp(.horizontal, isFocusedGroup: false, keys: right) == "Split Right in This Group" ) #expect( - TabStripButtonText.splitHelp(.vertical, isFocusedGroup: false) == "Split Down in This Group" + TabStripButtonText.splitHelp(.vertical, isFocusedGroup: false, keys: down) + == "Split Down in This Group" + ) + } + + @Test func aSplitWithChangedKeysNamesThemAndOneWithNoneNamesNothing() { + let changed = KeyCombination(.character("\\"), .command) + #expect( + TabStripButtonText.splitHelp(.horizontal, isFocusedGroup: true, keys: changed) + == "Split Right (⌘\\)" + ) + #expect( + TabStripButtonText.splitHelp(.vertical, isFocusedGroup: true, keys: nil) == "Split Down" ) } + @Test func eachSplitButtonNamesItsOwnCommandsKeys() { + #expect(TabStripButtonText.splitCommand(.horizontal) == .splitRight) + #expect(TabStripButtonText.splitCommand(.vertical) == .splitDown) + } + @Test func anotherGroupsNewTabMenuSaysItOpensThere() { #expect(TabStripButtonText.newTabHelp(isFocusedGroup: true) == "New Tab") #expect(TabStripButtonText.newTabHelp(isFocusedGroup: false) == "New Tab in This Group") diff --git a/Tests/MultishellAppUITests/App/AppShortcutCatalogueTests.swift b/Tests/MultishellAppUITests/App/AppShortcutCatalogueTests.swift deleted file mode 100644 index 598e6e304..000000000 --- a/Tests/MultishellAppUITests/App/AppShortcutCatalogueTests.swift +++ /dev/null @@ -1,50 +0,0 @@ -import SwiftUI -import Testing - -@testable import MultishellAppUI - -@Suite -struct AppShortcutCatalogueTests { - @Test func aShortcutSpellsItselfForBothTheMenuAndGhostty() { - #expect(AppShortcutCatalogue.newTab.modifiers == .command) - #expect(AppShortcutCatalogue.newTab.ghosttyCombo == "super+t") - - #expect(AppShortcutCatalogue.newShellTab.modifiers == [.command, .shift]) - #expect(AppShortcutCatalogue.newShellTab.ghosttyCombo == "super+shift+t") - - #expect( - AppShortcutCatalogue.newAgentTab.ghosttyCombo == "super+alt+t", - "option is alt to Ghostty", - ) - - // Control-only, and a key Ghostty names rather than taking its - // character: `\t` would be an unparsable keybind. - #expect(AppShortcutCatalogue.nextTab.modifiers == .control) - #expect(AppShortcutCatalogue.nextTab.ghosttyCombo == "ctrl+tab") - #expect(AppShortcutCatalogue.previousTab.ghosttyCombo == "ctrl+shift+tab") - - // Ghostty cannot parse the arrows' private-use scalars, so it names them. Alt - // and a bare arrow is word movement in a terminal, so these add Command. - #expect(AppShortcutCatalogue.nextGroup.ghosttyCombo == "super+alt+right") - #expect(AppShortcutCatalogue.previousGroup.ghosttyCombo == "super+alt+left") - // Not super+alt+d: the system's Dock toggle, which the - // WindowServer takes before a menu item can see it. - #expect(AppShortcutCatalogue.moveTabToNewGroup.ghosttyCombo == "super+alt+g") - #expect(AppShortcutCatalogue.findPrevious.ghosttyCombo == "super+shift+g") - #expect(AppShortcutCatalogue.closeFind.ghosttyCombo == "super+alt+f") - #expect(AppShortcutCatalogue.filesPane.ghosttyCombo == "super+shift+f") - } - - /// Two menu items on one combination is one of them never firing, and - /// nothing in SwiftUI says which. - @Test func noTwoShortcutsClaimTheSameKeystroke() { - let combos = AppShortcutCatalogue.all.map(\.ghosttyCombo) - #expect(Set(combos).count == combos.count, "\(combos)") - for combo in combos { - #expect( - !GhosttyUnbinds.systemOwned.contains(combo), - "\(combo) is claimed by both a menu item of ours and the system", - ) - } - } -} diff --git a/Tests/MultishellAppUITests/Ghostty/Config/GhosttyAppLayerTests.swift b/Tests/MultishellAppUITests/Ghostty/Config/GhosttyAppLayerTests.swift index 40f0c7729..33fbbce79 100644 --- a/Tests/MultishellAppUITests/Ghostty/Config/GhosttyAppLayerTests.swift +++ b/Tests/MultishellAppUITests/Ghostty/Config/GhosttyAppLayerTests.swift @@ -10,7 +10,7 @@ struct GhosttyAppLayerTests { /// search colour or an unbind gone. Readable is WCAG's 3:1 for large text. @Test func everyBuiltInThemeSetsReadableSearchColoursInAConfigurationLibghosttyAccepts() throws { for theme in Theme.builtins { - let rendered = GhosttyAppLayer.configuration(theme, Appearance()).rendered + let rendered = GhosttyAppLayer.configuration(theme, Appearance(), unbinding: []).rendered #expect(rendered.contains("search-background = #"), "\(theme.name)") #expect(rendered.contains("search-selected-background = #"), "\(theme.name)") #expect(rendered.contains("search-foreground = #"), "\(theme.name)") @@ -31,7 +31,8 @@ struct GhosttyAppLayerTests { /// `font-family` is a list in Ghostty; appended to a user's, ours was only a fallback. @Test func theFontChosenInSettingsEmptiesTheFontListBeforeNamingItself() throws { let appearance = Appearance(terminalFontName: "Menlo") - let rendered = GhosttyAppLayer.configuration(Theme.builtins[0], appearance).rendered + let rendered = GhosttyAppLayer.configuration(Theme.builtins[0], appearance, unbinding: []) + .rendered let cleared = try #require(rendered.range(of: "font-family = \"\"\n")) let ours = try #require(rendered.range(of: "font-family = Menlo")) #expect(cleared.upperBound <= ours.lowerBound) @@ -40,7 +41,8 @@ struct GhosttyAppLayerTests { } @Test func theAppLayerTurnsTheEnginesShellIntegrationOff() { - let rendered = GhosttyAppLayer.configuration(Theme.builtins[0], Appearance()).rendered + let rendered = GhosttyAppLayer.configuration(Theme.builtins[0], Appearance(), unbinding: []) + .rendered #expect(rendered.contains("shell-integration = none")) } @@ -55,7 +57,7 @@ struct GhosttyAppLayerTests { """##.utf8 ), ) - let rendered = GhosttyAppLayer.configuration(theme, Appearance()).rendered + let rendered = GhosttyAppLayer.configuration(theme, Appearance(), unbinding: []).rendered #expect(rendered.contains("background = #102030\n")) #expect(rendered.contains("cursor-text = #a0f0c0")) #expect(rendered.contains("search-selected-foreground = #a0f0c0")) diff --git a/Tests/MultishellAppUITests/Ghostty/Config/GhosttyUnbindsTests.swift b/Tests/MultishellAppUITests/Ghostty/Config/GhosttyUnbindsTests.swift index 66fe9a680..880e95a1d 100644 --- a/Tests/MultishellAppUITests/Ghostty/Config/GhosttyUnbindsTests.swift +++ b/Tests/MultishellAppUITests/Ghostty/Config/GhosttyUnbindsTests.swift @@ -1,3 +1,4 @@ +import MultishellCore import Testing @testable import MultishellAppUI @@ -6,22 +7,36 @@ import Testing /// the surface eats the keystroke before the menu bar sees it. @Suite struct GhosttyUnbindsTests { - @Test func theDerivedUnbindListIsTheOneGhosttyWasAlwaysGiven() { + private let defaults = ShortcutCommand.allCases.filter { !$0.surfaceKeepsBinding } + .map(\.defaultCombination) + + @Test func theDefaultsUnbindWhatGhosttyWasAlwaysGivenAndTheWholeReservedTable() { #expect( - Set(GhosttyUnbinds.all) == [ - "super+t", "super+shift+t", "super+alt+t", "super+w", "super+shift+w", "super+n", - "super+shift+n", - "super+o", "super+shift+o", "super+d", "super+shift+d", "super+comma", "super+q", - "super+z", "super+shift+z", - "super+alt+g", "super+alt+left", "super+alt+right", - "super+shift+a", - "super+p", "super+shift+p", - "super+shift+c", "super+shift+r", "super+alt+f", - "super+alt+d", - "ctrl+tab", "ctrl+shift+tab", - "super+f", "super+g", "super+shift+g", "super+shift+f", - "super+ctrl+f", "super+enter", - "escape", + Set(GhosttyUnbinds.all(unbinding: defaults)) == [ + "super+t", "super+key_t", "super+shift+t", "super+shift+key_t", "super+alt+t", + "super+alt+key_t", "super+w", "super+key_w", "super+shift+w", "super+shift+key_w", + "super+n", "super+key_n", "super+shift+n", "super+shift+key_n", "super+o", "super+key_o", + "super+shift+o", "super+shift+key_o", "super+d", "super+key_d", "super+shift+d", + "super+shift+key_d", "super+,", "super+comma", "super+q", "super+key_q", "super+z", + "super+key_z", "super+shift+z", "super+shift+key_z", "super+alt+g", "super+alt+key_g", + "super+alt+left", "super+alt+right", "super+shift+a", "super+shift+key_a", "super+p", + "super+key_p", "super+shift+p", "super+shift+key_p", "super+shift+c", "super+shift+key_c", + "super+shift+r", "super+shift+key_r", "super+alt+f", "super+alt+key_f", "super+alt+d", + "super+alt+key_d", "ctrl+tab", "ctrl+shift+tab", "super+f", "super+key_f", "super+g", + "super+key_g", "super+shift+g", "super+shift+key_g", "super+shift+f", "super+shift+key_f", + "super+ctrl+f", "super+ctrl+key_f", "super+enter", "super+h", "super+key_h", "super+alt+h", + "super+alt+key_h", "super+m", "super+key_m", "super+tab", "super+space", "super+`", + "super+backquote", "super+shift+\\", "super+shift+backslash", "super+shift+/", + "super+shift+slash", "super+shift+q", "super+shift+key_q", "super+alt+shift+q", + "super+alt+shift+key_q", + "super+ctrl+q", "super+ctrl+key_q", "super+shift+3", "super+shift+digit_3", + "super+shift+4", "super+shift+digit_4", "super+shift+5", "super+shift+digit_5", "ctrl+left", + "ctrl+right", "ctrl+up", "ctrl+down", "super+alt+space", "ctrl+space", "ctrl+alt+space", + "super+ctrl+space", "super+shift+tab", "super+shift+`", "super+shift+backquote", "super+.", + "super+period", "super+ctrl+shift+3", "super+ctrl+shift+digit_3", "super+ctrl+shift+4", + "super+ctrl+shift+digit_4", "super+alt+m", "super+alt+key_m", "super+f5", "super+alt+f5", + "super+ctrl+d", + "super+ctrl+key_d", "escape", ] ) } @@ -29,24 +44,25 @@ struct GhosttyUnbindsTests { /// Ghostty binds Cmd+F to its own search, whose bar this embedding cannot /// show; unbound, the keystroke reaches the Edit menu and ours. @Test func theFindShortcutsAreTakenFromTheSurface() { - let unbound = Set(GhosttyUnbinds.all) - for shortcut in [ - AppShortcutCatalogue.find, AppShortcutCatalogue.findNext, AppShortcutCatalogue.findPrevious, - AppShortcutCatalogue.closeFind, - ] { - #expect(unbound.contains(shortcut.ghosttyCombo)) + let unbound = Set(GhosttyUnbinds.all(unbinding: defaults)) + for command in [ShortcutCommand.find, .findNext, .findPrevious, .closeFind] { + #expect(unbound.isSuperset(of: command.defaultCombination.ghosttyTriggers)) } } - /// The WindowServer takes the Dock toggle before a menu item can see it. - @Test func theDockToggleIsGivenUpAsTheSystems() { - #expect(GhosttyUnbinds.systemOwned.contains("super+alt+d")) + @Test func anOverridesKeysAreUnboundAlongsideTheDefaults() { + let backslash = KeyCombination(.character("\\"), .command) + + let unbound = GhosttyUnbinds.all(unbinding: defaults + [backslash]) + + #expect(unbound.contains("super+\\")) + #expect(unbound.contains("super+backslash")) } /// libghostty drops a line it refuses without a word, so a key name it lacks /// would leave that shortcut to Ghostty rather than the menu. @Test func everyUnbindIsALineThePinnedLibghosttyAccepts() throws { - let unbinds = GhosttyUnbinds.all.map { "keybind = \($0)=unbind" } + let unbinds = GhosttyUnbinds.all(unbinding: defaults).map { "keybind = \($0)=unbind" } .joined(separator: "\n") let diagnostics = try libghosttyDiagnostics( GhosttyUserConfig.defaults.rendered + "\n" + unbinds @@ -58,19 +74,15 @@ struct GhosttyUnbindsTests { /// Escape in the pane. Released, Escape is a plain key and only the bar ends one. @Test func escapeIsReleasedToTheProgramInThePane() { #expect(GhosttyUnbinds.surfaceReleases == ["escape"]) - #expect(GhosttyUnbinds.all.contains("escape")) + #expect(GhosttyUnbinds.all(unbinding: []).contains("escape")) } /// In a pane Cmd+C is Ghostty's copy of the terminal selection, and unbinding /// it sends it to a menu item that has no selection to copy. @Test func theClipboardShortcutsStayWithTheTerminal() { - let unbound = Set(GhosttyUnbinds.all) - for shortcut in [ - AppShortcutCatalogue.cut, AppShortcutCatalogue.copy, AppShortcutCatalogue.paste, - AppShortcutCatalogue.selectAll, - ] { - #expect(shortcut.surfaceKeepsBinding, "\(shortcut.ghosttyCombo) is the terminal's to handle") - #expect(!unbound.contains(shortcut.ghosttyCombo)) + let unbound = Set(GhosttyUnbinds.all(unbinding: defaults)) + for command in ShortcutCommand.allCases where command.surfaceKeepsBinding { + #expect(unbound.isDisjoint(with: command.defaultCombination.ghosttyTriggers), "\(command)") } } } diff --git a/Tests/MultishellAppUITests/Ghostty/Config/KeyCombination+GhosttyTests.swift b/Tests/MultishellAppUITests/Ghostty/Config/KeyCombination+GhosttyTests.swift new file mode 100644 index 000000000..cea7e33d7 --- /dev/null +++ b/Tests/MultishellAppUITests/Ghostty/Config/KeyCombination+GhosttyTests.swift @@ -0,0 +1,66 @@ +import Testing + +@testable import MultishellAppUI +@testable import MultishellCore + +@Suite +struct KeyCombinationGhosttyTests { + @Test func aCombinationIsSpelledAsGhosttysDocsSpellIt() { + #expect( + ShortcutCommand.newTab.defaultCombination.ghosttyTriggers == ["super+t", "super+key_t"] + ) + #expect( + ShortcutCommand.newAgentTab.defaultCombination.ghosttyTriggers + == ["super+alt+t", "super+alt+key_t"] + ) + #expect(ShortcutCommand.nextTab.defaultCombination.ghosttyTriggers == ["ctrl+tab"]) + #expect(ShortcutCommand.previousTab.defaultCombination.ghosttyTriggers == ["ctrl+shift+tab"]) + #expect( + ShortcutCommand.focusNextGroup.defaultCombination.ghosttyTriggers == ["super+alt+right"] + ) + } + + /// Ghostty's defaults bind `super+[` by character, and a user's file may + /// bind `super+bracket_left` by key; each unbinds only its own. + @Test func punctuationIsSpelledByCharacterAndByName() { + #expect( + KeyCombination(.character("["), .command).ghosttyTriggers + == ["super+[", "super+bracket_left"] + ) + } + + /// Ghostty binds ⌘1 to ⌘8 under both the digit and the physical key. + @Test func aDigitOrLetterIsSpelledByCharacterAndByItsKeysName() { + #expect( + KeyCombination(.character("1"), .command).ghosttyTriggers == ["super+1", "super+digit_1"] + ) + #expect( + KeyCombination(.character("k"), .command).ghosttyTriggers == ["super+k", "super+key_k"] + ) + } + + /// Ghostty reads `>` as the step between a sequence's keys, so no trigger can + /// name it; nothing in its defaults is on it either. + @Test func theGreaterThanKeyHasNoTrigger() { + #expect(KeyCombination(.character(">"), .command).ghosttyTriggers.isEmpty) + } + + /// libghostty drops a line it refuses without a word, so a key the recorder + /// takes and Ghostty cannot name would stay Ghostty's in a pane. + @Test func everyRecordableKeyIsALineThePinnedLibghosttyAccepts() throws { + let ascii = (0x21...0x7E).compactMap(UnicodeScalar.init).map(Character.init) + let printable = ascii + Array("öäüßéèàçñ§°²µ") + let keys: [ShortcutKey] = + ShortcutKey.named.map(\.key) + ShortcutKey.functionNumbers.map(ShortcutKey.function) + + printable.map(ShortcutKey.character) + let lines = keys.flatMap { key in + KeyCombination(key, [.command, .control, .option, .shift]).ghosttyTriggers.map { trigger in + "keybind = \(trigger)=unbind" + } + } + let diagnostics = try libghosttyDiagnostics( + GhosttyUserConfig.defaults.rendered + "\n" + lines.joined(separator: "\n") + ) + #expect(diagnostics.isEmpty, "\(diagnostics)") + } +} diff --git a/Tests/MultishellAppUITests/Ghostty/Runtime/LazyGhosttyRuntimeTests.swift b/Tests/MultishellAppUITests/Ghostty/Runtime/LazyGhosttyRuntimeTests.swift index de14c921c..46e1073ac 100644 --- a/Tests/MultishellAppUITests/Ghostty/Runtime/LazyGhosttyRuntimeTests.swift +++ b/Tests/MultishellAppUITests/Ghostty/Runtime/LazyGhosttyRuntimeTests.swift @@ -20,7 +20,7 @@ struct LazyGhosttyRuntimeTests { let reads = BaseReads() let lazyRuntime = LazyGhosttyRuntime(readBase: reads.read) - lazyRuntime.apply(Theme.builtins[0], appearance: Appearance()) + lazyRuntime.apply(Theme.builtins[0], appearance: Appearance(), unbinding: []) #expect(reads.count == 0) } diff --git a/Tests/MultishellAppUITests/NullEngine.swift b/Tests/MultishellAppUITests/NullEngine.swift index 90701d366..fcf2b69e0 100644 --- a/Tests/MultishellAppUITests/NullEngine.swift +++ b/Tests/MultishellAppUITests/NullEngine.swift @@ -20,6 +20,6 @@ final class NullEngine: TerminalSurfaceHost { func selectionText(of id: TerminalSession.ID) -> String? { nil } func screenshot(of id: TerminalSession.ID) -> Data? { nil } func frame(of id: TerminalSession.ID) -> CGRect? { nil } - func apply(_ theme: Theme, appearance: Appearance) {} + func apply(_ theme: Theme, appearance: Appearance, unbinding: [KeyCombination]) {} func search(_ step: TerminalSearch, in id: TerminalSession.ID) -> Bool { false } } diff --git a/Tests/MultishellAppUITests/Platform/MacPlatform+MenuShortcutsTests.swift b/Tests/MultishellAppUITests/Platform/MacPlatform+MenuShortcutsTests.swift new file mode 100644 index 000000000..1243814bb --- /dev/null +++ b/Tests/MultishellAppUITests/Platform/MacPlatform+MenuShortcutsTests.swift @@ -0,0 +1,104 @@ +import AppKit +import MultishellCore +import Testing + +@testable import MultishellAppCore +@testable import MultishellAppUI + +@Suite @MainActor +struct MacPlatformMenuShortcutsTests { + private static let nextTabDefault = MenuShortcut( + command: .nextTab, + keys: ShortcutCommand.nextTab.defaultCombination, + isChanged: false, + ) + + private func bar(holding titles: [String]) -> NSMenu { + let terminal = NSMenu(title: "Terminal") + for title in titles { + terminal.addItem(NSMenuItem(title: title, action: nil, keyEquivalent: "x")) + } + let bar = NSMenu(title: "") + let item = NSMenuItem(title: "Terminal", action: nil, keyEquivalent: "") + item.submenu = terminal + bar.addItem(item) + return bar + } + + @Test func aChangedCommandsItemCarriesItsNewKeysAndAClearedOneNone() throws { + let menu = bar(holding: [ + ShortcutCommand.splitRight.menuTitle, ShortcutCommand.splitDown.menuTitle, + ]) + let backslash = KeyCombination(.character("\\"), [.command, .option]) + + MacPlatform.setMenuShortcuts( + [ + MenuShortcut(command: .splitRight, keys: backslash, isChanged: true), + MenuShortcut(command: .splitDown, keys: nil, isChanged: true), + ], + in: menu, + ) + + let items = try #require(menu.items.first?.submenu?.items) + #expect(items[0].keyEquivalent == "\\") + #expect(items[0].keyEquivalentModifierMask == [.command, .option]) + #expect(!items[0].allowsAutomaticKeyEquivalentLocalization, "typed on this layout") + #expect(items[1].keyEquivalent.isEmpty) + #expect(MenuShortcutText.of(items[0]) == "⌥⌘\\") + } + + @Test func aMenuMacOSFillsIsLeftAloneEvenWhereAnItemSharesACommandsTitle() throws { + let services = NSMenu(title: "Services") + services.addItem( + NSMenuItem(title: ShortcutCommand.newTab.menuTitle, action: nil, keyEquivalent: "") + ) + let menu = bar(holding: []) + let item = NSMenuItem(title: "Services", action: nil, keyEquivalent: "") + item.submenu = services + menu.addItem(item) + + MacPlatform.setMenuShortcuts( + [ + MenuShortcut( + command: .newTab, + keys: ShortcutCommand.newTab.defaultCombination, + isChanged: false, + ) + ], + in: menu, + leavingOut: [services], + ) + + #expect(services.items[0].keyEquivalent.isEmpty) + } + + @Test func aThemeNamedAsACommandKeepsNoKeys() throws { + let themes = NSMenu(title: ShortcutCommand.nextTab.menuTitle) + themes.addItem( + NSMenuItem(title: ShortcutCommand.nextTab.menuTitle, action: nil, keyEquivalent: "") + ) + let menu = bar(holding: []) + let terminal = try #require(menu.items.first?.submenu) + let picker = NSMenuItem(title: MultishellAppUI.t("menu.theme"), action: nil, keyEquivalent: "") + picker.submenu = themes + terminal.addItem(picker) + + MacPlatform.setMenuShortcuts([Self.nextTabDefault], in: menu) + + #expect(themes.items[0].keyEquivalent.isEmpty) + } + + @Test func aDefaultKeepsTheSystemsLayoutLocalization() throws { + let menu = bar(holding: [ShortcutCommand.nextTab.menuTitle]) + + MacPlatform.setMenuShortcuts( + [Self.nextTabDefault], + in: menu, + ) + + let item = try #require(menu.items.first?.submenu?.items.first) + #expect(item.keyEquivalent == "\t") + #expect(item.keyEquivalentModifierMask == .control) + #expect(item.allowsAutomaticKeyEquivalentLocalization) + } +} diff --git a/Tests/MultishellAppUITests/Settings/AppWide/Shortcuts/ShortcutRecorderInputTests.swift b/Tests/MultishellAppUITests/Settings/AppWide/Shortcuts/ShortcutRecorderInputTests.swift new file mode 100644 index 000000000..379e38f63 --- /dev/null +++ b/Tests/MultishellAppUITests/Settings/AppWide/Shortcuts/ShortcutRecorderInputTests.swift @@ -0,0 +1,49 @@ +import AppKit +import Carbon.HIToolbox +import MultishellCore +import Testing + +@testable import MultishellAppUI + +/// The key comes from the layout in use, so these hold a US keyboard's keys. +@Suite(.enabled(if: KeyboardInputSource.currentID == "com.apple.keylayout.US")) +@MainActor +struct ShortcutRecorderInputTests { + private func input( + _ characters: String, + _ keyCode: Int, + _ flags: NSEvent.ModifierFlags = [], + ) throws -> ShortcutRecorderInput { + ShortcutRecorderInput(try keyDown(characters, keyCode: UInt16(keyCode), flags: flags)) + } + + @Test func aKeyIsRecordedWithTheModifiersHeld() throws { + #expect( + try input("w", kVK_ANSI_W, .command) == .keys(KeyCombination(.character("w"), .command)) + ) + } + + @Test func shiftedPunctuationIsTheUnshiftedKeyWithShift() throws { + #expect( + try input("{", kVK_ANSI_LeftBracket, [.command, .shift]) + == .keys(KeyCombination(.character("["), [.command, .shift])) + ) + } + + @Test func keysThatTypeNoCharacterAreRecordedByName() throws { + #expect(try input("\u{F708}", kVK_F5, .function) == .keys(KeyCombination(.function(5)))) + #expect( + try input("\u{F702}", kVK_LeftArrow, [.command, .option, .numericPad, .function]) + == .keys(KeyCombination(.leftArrow, [.command, .option])) + ) + #expect(try input("\t", kVK_Tab, .control) == .keys(KeyCombination(.tab, .control))) + } + + @Test func escapeCancelsAndDeleteAloneClears() throws { + #expect(try input("\u{1B}", kVK_Escape) == .cancel) + #expect(try input("\u{7F}", kVK_Delete) == .clear) + #expect( + try input("\u{7F}", kVK_Delete, .command) == .keys(KeyCombination(.backspace, .command)) + ) + } +} diff --git a/Tests/MultishellAppUITests/Settings/AppWide/Shortcuts/ShortcutRecorderMonitorTests.swift b/Tests/MultishellAppUITests/Settings/AppWide/Shortcuts/ShortcutRecorderMonitorTests.swift new file mode 100644 index 000000000..b87b44f7a --- /dev/null +++ b/Tests/MultishellAppUITests/Settings/AppWide/Shortcuts/ShortcutRecorderMonitorTests.swift @@ -0,0 +1,49 @@ +import AppKit +import Testing + +@testable import MultishellAppUI + +@Suite @MainActor +struct ShortcutRecorderMonitorTests { + private func keyDown(inWindowNumbered number: Int) throws -> NSEvent { + try #require( + NSEvent.keyEvent( + with: .keyDown, + location: .zero, + modifierFlags: [], + timestamp: 1, + windowNumber: number, + context: nil, + characters: "\u{7F}", + charactersIgnoringModifiers: "\u{7F}", + isARepeat: false, + keyCode: 51, + ) + ) + } + + @Test func aKeyCountsAsTypedForTheRecorderOnlyInItsOwnWindow() throws { + let window = NSWindow( + contentRect: NSRect(x: 0, y: 0, width: 10, height: 10), + styleMask: [], + backing: .buffered, + defer: false, + ) + let number = window.windowNumber + try #require(number > 0) + + #expect( + ShortcutRecorderMonitor.isTyped( + try keyDown(inWindowNumbered: number), + inWindowNumbered: number, + ) + ) + #expect( + !ShortcutRecorderMonitor.isTyped( + try keyDown(inWindowNumbered: number + 1), + inWindowNumbered: number, + ), + "a Delete typed in a pane must not clear the command", + ) + } +} diff --git a/Tests/MultishellAppUITests/Settings/View+SettingsWindowTests.swift b/Tests/MultishellAppUITests/Settings/View+SettingsWindowTests.swift index b314efebc..478ee0db1 100644 --- a/Tests/MultishellAppUITests/Settings/View+SettingsWindowTests.swift +++ b/Tests/MultishellAppUITests/Settings/View+SettingsWindowTests.swift @@ -26,6 +26,22 @@ struct ViewSettingsWindowTests { Page(name: "Agents, Agent settings", view: AnyView(AppAgentSettingsPage(model: model))), Page(name: "Notifications", view: AnyView(AppNotificationsPage(model: model))), Page(name: "Appearance", view: AnyView(AppAppearancePage(model: model))), + Page( + name: "Shortcuts, File", + view: AnyView(AppShortcutsPage(model: model, section: .shortcutsFile)), + ), + Page( + name: "Shortcuts, Edit", + view: AnyView(AppShortcutsPage(model: model, section: .shortcutsEdit)), + ), + Page( + name: "Shortcuts, View", + view: AnyView(AppShortcutsPage(model: model, section: .shortcutsView)), + ), + Page( + name: "Shortcuts, Terminal", + view: AnyView(AppShortcutsPage(model: model, section: .shortcutsTerminal)), + ), Page( name: "Project General", view: AnyView(ProjectGeneralPage(model: model, project: project)), diff --git a/Tests/MultishellCoreTests/FakeTerminalHost.swift b/Tests/MultishellCoreTests/FakeTerminalHost.swift index 5599df24e..08f0d4a76 100644 --- a/Tests/MultishellCoreTests/FakeTerminalHost.swift +++ b/Tests/MultishellCoreTests/FakeTerminalHost.swift @@ -43,6 +43,6 @@ final class FakeTerminalHost: TerminalHost { return true } - func apply(_ theme: Theme, appearance: Appearance) {} + func apply(_ theme: Theme, appearance: Appearance, unbinding: [KeyCombination]) {} func search(_ step: TerminalSearch, in id: TerminalSession.ID) -> Bool { false } } diff --git a/Tests/MultishellCoreTests/Model/Settings/Shortcuts/KeyCombination+GlyphsTests.swift b/Tests/MultishellCoreTests/Model/Settings/Shortcuts/KeyCombination+GlyphsTests.swift new file mode 100644 index 000000000..72a0dc9b2 --- /dev/null +++ b/Tests/MultishellCoreTests/Model/Settings/Shortcuts/KeyCombination+GlyphsTests.swift @@ -0,0 +1,26 @@ +import Testing + +@testable import MultishellCore + +@Suite +struct KeyCombinationGlyphsTests { + @Test func glyphsAreDrawnAsAMenuDrawsThem() { + #expect(KeyCombination(.character("k"), [.shift, .command]).glyphs == "⇧⌘K") + #expect(KeyCombination(.tab, [.control, .shift]).glyphs == "⌃⇧⇥") + #expect(KeyCombination(.rightArrow, [.command, .option]).glyphs == "⌥⌘→") + } + @Test func everyCombinationsGlyphsReadBackAsTheSameCombination() { + let keys: [ShortcutKey] = + ShortcutKey.named.map(\.key) + ShortcutKey.functionNumbers.map(ShortcutKey.function) + + Array("abz09`-=[]\\;',./+ößı").map(ShortcutKey.character) + for key in keys { + let combination = KeyCombination(key, [.command, .option, .shift, .control]) + #expect(KeyCombination(glyphs: combination.glyphs) == combination, "\(combination)") + } + } + + @Test func aCapitalInGlyphsIsTheLetterWithoutShiftUnlessShiftIsDrawn() { + #expect(KeyCombination(glyphs: "⌘K") == KeyCombination(.character("k"), .command)) + #expect(KeyCombination(glyphs: "⌘⌘K") == nil) + } +} diff --git a/Tests/MultishellCoreTests/Model/Settings/Shortcuts/KeyCombination+SpellingTests.swift b/Tests/MultishellCoreTests/Model/Settings/Shortcuts/KeyCombination+SpellingTests.swift new file mode 100644 index 000000000..f65907ebe --- /dev/null +++ b/Tests/MultishellCoreTests/Model/Settings/Shortcuts/KeyCombination+SpellingTests.swift @@ -0,0 +1,48 @@ +import Testing + +@testable import MultishellCore + +@Suite +struct KeyCombinationSpellingTests { + @Test func aCombinationIsSpelledWithItsModifiersInMenuOrder() { + #expect(KeyCombination(.character("k"), [.command, .shift]).spelled == "shift+cmd+k") + #expect(KeyCombination(.tab, [.shift, .control]).spelled == "ctrl+shift+tab") + #expect(KeyCombination(.character("\\"), .command).spelled == "cmd+backslash") + #expect(KeyCombination(.character("+"), .command).spelled == "cmd+plus") + #expect(KeyCombination(.function(5), []).spelled == "f5") + } + @Test func everySpellingReadsBackAsTheSameCombination() { + let keys: [ShortcutKey] = + ShortcutKey.named.map(\.key) + ShortcutKey.functionNumbers.map(ShortcutKey.function) + + Array("abz09`-=[]\\;',./+ößı").map(ShortcutKey.character) + for key in keys { + let combination = KeyCombination(key, [.command, .option, .shift, .control]) + #expect(KeyCombination(spelled: combination.spelled) == combination, "\(combination)") + } + } + + @Test func aSpellingTakesAnyCaseAnyOrderAndAKeysOwnCharacter() { + #expect( + KeyCombination(spelled: "CMD+Shift+K") + == KeyCombination(.character("k"), [.command, .shift]) + ) + #expect(KeyCombination(spelled: "cmd+\\") == KeyCombination(.character("\\"), .command)) + #expect(KeyCombination(spelled: "cmd++") == KeyCombination(.character("+"), .command)) + } + @Test func aNamedKeysGlyphSpelledAsItsKeyIsThatKeyNotACharacter() { + #expect(KeyCombination(spelled: "cmd+←") == KeyCombination(.leftArrow, .command)) + #expect(KeyCombination(spelled: "cmd+⌫") == KeyCombination(.backspace, .command)) + #expect(KeyCombination(spelled: "cmd+⌘") == nil, "a modifier is no key") + for glyph in ["⏎", "⌤", "⎋", "⇪"] { + #expect(KeyCombination(spelled: "cmd+\(glyph)") == nil, "no key types \(glyph)") + } + } + + @Test func aSpellingWithAnUnknownWordOrARepeatedModifierIsNoCombination() { + #expect(KeyCombination(spelled: "hyper+k") == nil) + #expect(KeyCombination(spelled: "cmd+cmd+k") == nil) + #expect(KeyCombination(spelled: "cmd+") == nil) + #expect(KeyCombination(spelled: "cmd+f21") == nil) + #expect(KeyCombination(spelled: "cmd+ab") == nil) + } +} diff --git a/Tests/MultishellCoreTests/Model/Settings/Shortcuts/KeyCombinationTests.swift b/Tests/MultishellCoreTests/Model/Settings/Shortcuts/KeyCombinationTests.swift new file mode 100644 index 000000000..c251d292d --- /dev/null +++ b/Tests/MultishellCoreTests/Model/Settings/Shortcuts/KeyCombinationTests.swift @@ -0,0 +1,12 @@ +import Testing + +@testable import MultishellCore + +@Suite +struct KeyCombinationTests { + @Test func aCharacterIsKeptLowercaseShiftBeingAModifierOfItsOwn() { + #expect( + KeyCombination(.character("K"), .command) == KeyCombination(.character("k"), .command) + ) + } +} diff --git a/Tests/MultishellCoreTests/Model/Settings/Shortcuts/ReservedShortcutTests.swift b/Tests/MultishellCoreTests/Model/Settings/Shortcuts/ReservedShortcutTests.swift new file mode 100644 index 000000000..98ca0c259 --- /dev/null +++ b/Tests/MultishellCoreTests/Model/Settings/Shortcuts/ReservedShortcutTests.swift @@ -0,0 +1,17 @@ +import Testing + +@testable import MultishellCore + +@Suite +struct ReservedShortcutTests { + @Test func theDocksHidingKeysAreReservedSoNoCommandSitsOnThem() { + #expect( + ReservedShortcut.holding(KeyCombination(.character("d"), [.command, .option])) == .dockHiding + ) + } + + @Test func noTwoReservedEntriesNameTheSameKeys() { + let combinations = ReservedShortcut.allCases.map(\.combination) + #expect(Set(combinations).count == combinations.count) + } +} diff --git a/Tests/MultishellCoreTests/Model/Settings/Shortcuts/ShortcutCommandTests.swift b/Tests/MultishellCoreTests/Model/Settings/Shortcuts/ShortcutCommandTests.swift new file mode 100644 index 000000000..78c36b3d3 --- /dev/null +++ b/Tests/MultishellCoreTests/Model/Settings/Shortcuts/ShortcutCommandTests.swift @@ -0,0 +1,31 @@ +import Testing + +@testable import MultishellCore + +@Suite +struct ShortcutCommandTests { + @Test func noTwoCommandsDefaultToTheSameKeys() { + let defaults = ShortcutCommand.allCases.map(\.defaultCombination) + #expect(Set(defaults).count == defaults.count, "\(defaults.map(\.glyphs))") + } + + @Test func noDefaultIsOnKeysTheSystemKeeps() { + for command in ShortcutCommand.allCases { + #expect(ReservedShortcut.holding(command.defaultCombination) == nil, "\(command)") + } + } + + @Test func theEditMenusUniversalCommandsAreFixed() { + #expect( + Set(ShortcutCommand.allCases.filter(\.isFixed)) + == [.undo, .redo, .find, .cut, .copy, .paste, .selectAll] + ) + } + + @Test func onlyTheClipboardCommandsKeepTheirKeysInAPane() { + #expect( + Set(ShortcutCommand.allCases.filter(\.surfaceKeepsBinding)) + == [.cut, .copy, .paste, .selectAll] + ) + } +} diff --git a/Tests/MultishellCoreTests/Model/Settings/Shortcuts/ShortcutOverrides+CodableTests.swift b/Tests/MultishellCoreTests/Model/Settings/Shortcuts/ShortcutOverrides+CodableTests.swift new file mode 100644 index 000000000..0e1b1f728 --- /dev/null +++ b/Tests/MultishellCoreTests/Model/Settings/Shortcuts/ShortcutOverrides+CodableTests.swift @@ -0,0 +1,77 @@ +import Foundation +import Testing + +@testable import MultishellCore + +@Suite +struct ShortcutOverridesCodableTests { + @Test func overridesAreWrittenAsCommandToKeysWithBlankForNone() throws { + var overrides = ShortcutOverrides() + overrides.set(.keys(KeyCombination(.character("\\"), .command)), for: .splitRight) + overrides.set(.noKeys, for: .closeFind) + let object = try JSONSerialization.jsonObject(with: JSONEncoder().encode(overrides)) + + #expect(object as? [String: String] == ["split-right": "cmd+backslash", "close-find": ""]) + } + + @Test func blankAndWhitespaceReadAsNoKeys() throws { + let overrides = try decodeJSON( + ShortcutOverrides.self, + #"{ "close-find": "", "find-next": " " }"#, + ) + #expect(overrides[.closeFind] == .noKeys) + #expect(overrides[.findNext] == .noKeys) + } + + @Test func anUnknownCommandOrUnreadableKeysCostsThatEntryAlone() throws { + let overrides = try decodeJSON( + ShortcutOverrides.self, + #"{ "warp-drive": "cmd+k", "split-right": "hyper+k", "split-down": 3, "find-next": "cmd+k" }"#, + ) + #expect(overrides[.splitRight] == nil) + #expect(overrides[.splitDown] == nil) + #expect(overrides[.findNext] == .keys(KeyCombination(.character("k"), .command))) + } + + @Test func aSecondOverrideOnKeysAnEarlierOneHoldsIsDropped() throws { + let overrides = try decodeJSON( + ShortcutOverrides.self, + #"{ "split-down": "cmd+k", "new-tab": "cmd+k", "find-next": "cmd+c" }"#, + ) + #expect(overrides[.newTab] == .keys(KeyCombination(.character("k"), .command))) + #expect(overrides[.splitDown] == nil, "new-tab comes first among the commands") + #expect(overrides[.findNext] == nil, "Copy holds ⌘C and cannot let it go") + } + + @Test func keysTheSettingsPageWouldRefuseAreDroppedOnLoad() throws { + let overrides = try decodeJSON( + ShortcutOverrides.self, + #"{ "split-right": "q", "split-down": "cmd+q", "find": "ctrl+c", "close-find": "alt+left" }"#, + ) + #expect(overrides.isEmpty, "a hand edit must not bind a plain q or take ⌘Q") + } + + @Test func spacesAroundAHandEditedSpellingAreIgnored() throws { + let overrides = try decodeJSON( + ShortcutOverrides.self, + #"{ "split-right": " cmd+backslash " }"#, + ) + #expect(overrides[.splitRight] == .keys(KeyCombination(.character("\\"), .command))) + } + + @Test func aFixedCommandsOverrideIsDropped() throws { + let overrides = try decodeJSON( + ShortcutOverrides.self, + #"{ "copy": "cmd+k", "undo": "cmd+u", "find": "cmd+j" }"#, + ) + #expect(overrides.isEmpty) + } + + @Test func aStateFileWithoutShortcutsOrWithABrokenValueKeepsTheDefaults() throws { + #expect(try decodeJSON(Workspace.self, #"{ "projects": [] }"#).shortcutOverrides.isEmpty) + #expect( + try decodeJSON(Workspace.self, #"{ "projects": [], "shortcuts": [1] }"#).shortcutOverrides + .isEmpty + ) + } +} diff --git a/Tests/MultishellCoreTests/Model/Settings/Shortcuts/ShortcutOverridesTests.swift b/Tests/MultishellCoreTests/Model/Settings/Shortcuts/ShortcutOverridesTests.swift new file mode 100644 index 000000000..4dfd1e44a --- /dev/null +++ b/Tests/MultishellCoreTests/Model/Settings/Shortcuts/ShortcutOverridesTests.swift @@ -0,0 +1,45 @@ +import Testing + +@testable import MultishellCore + +@Suite +struct ShortcutOverridesTests { + private let backslash = KeyCombination(.character("\\"), .command) + + @Test func aCommandLeftAloneHasItsDefault() { + #expect( + ShortcutOverrides().keys(for: .splitRight) + == ShortcutCommand.splitRight.defaultCombination + ) + } + + @Test func anOverrideOfNoKeysLeavesTheCommandNone() { + var overrides = ShortcutOverrides() + overrides.set(.noKeys, for: .closeFind) + #expect(overrides.keys(for: .closeFind) == nil) + #expect(overrides[.closeFind] == .noKeys) + } + + @Test func settingACommandBackToItsDefaultRemovesTheOverride() { + var overrides = ShortcutOverrides() + overrides.set(.keys(backslash), for: .splitRight) + overrides.set(.keys(ShortcutCommand.splitRight.defaultCombination), for: .splitRight) + #expect(overrides.isEmpty) + } + + @Test func aDefaultAnotherCommandsOverrideHoldsLeavesItsCommandNone() { + var overrides = ShortcutOverrides() + overrides.set(.keys(ShortcutCommand.splitDown.defaultCombination), for: .quickSwitcher) + #expect(overrides.keys(for: .splitDown) == nil) + #expect( + overrides.command(holding: ShortcutCommand.splitDown.defaultCombination) == .quickSwitcher + ) + } + + @Test func aFixedCommandKeepsItsKeys() { + var overrides = ShortcutOverrides() + overrides.set(.noKeys, for: .copy) + #expect(overrides.isEmpty) + #expect(overrides.keys(for: .copy) == ShortcutCommand.copy.defaultCombination) + } +}