diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index a6f7bd17..3dc5683c 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -101,6 +101,7 @@ jobs: capture dark -ShowPreferencesAtStartUp NO -CalendarSize 2 -Appearance 2 capture light -ShowPreferencesAtStartUp NO -CalendarSize 2 -Appearance 1 capture settings -ShowPreferencesAtStartUp YES -CalendarSize 1 + capture shortcuts -ShowPreferencesAtStartUp YES -CalendarSize 1 -BlotterSettingsPane 1 capture german -ShowPreferencesAtStartUp YES -CalendarSize 1 -AppleLanguages '(de)' -AppleLocale de_DE capture japanese -ShowPreferencesAtStartUp NO -CalendarSize 2 -AppleLanguages '(ja)' -AppleLocale ja_JP diff --git a/Blotter.xcodeproj/project.pbxproj b/Blotter.xcodeproj/project.pbxproj index 79515bdb..42916660 100644 --- a/Blotter.xcodeproj/project.pbxproj +++ b/Blotter.xcodeproj/project.pbxproj @@ -9,28 +9,31 @@ /* Begin PBXBuildFile section */ 0F067637F911CF1DDC9A3C5D /* AppDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 80C499315086814D391D635A /* AppDelegate.swift */; }; 100B504297BA7059B4E2EC40 /* InfoPlist.xcstrings in Resources */ = {isa = PBXBuildFile; fileRef = 9B6889B3E2DEF68A35EEC29A /* InfoPlist.xcstrings */; }; + 2259160724D8D7DA438C541E /* HotkeyCenter.swift in Sources */ = {isa = PBXBuildFile; fileRef = F226DBE68F9BACBB08BF3513 /* HotkeyCenter.swift */; }; 25F8097CC5B71C517B410C1A /* Localizable.xcstrings in Resources */ = {isa = PBXBuildFile; fileRef = 8613B4D32EB797DCEADA9EBA /* Localizable.xcstrings */; }; 3C8EA796A679C613BD1C448D /* CalendarView.swift in Sources */ = {isa = PBXBuildFile; fileRef = D66A7A9DC1B15CDD7E970CA6 /* CalendarView.swift */; }; - 442D214084AF2836CF976F75 /* Hotkeys.swift in Sources */ = {isa = PBXBuildFile; fileRef = B211D3CFF1CF666A5F50D14C /* Hotkeys.swift */; }; 48B139E9DCFBDE48B2C62CFD /* DemoData.swift in Sources */ = {isa = PBXBuildFile; fileRef = FB7A450502CE85C6BF89C323 /* DemoData.swift */; }; 589284774E0F9533914DBCBF /* LegacyMigrationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 20900949505E9C73E04E0F5B /* LegacyMigrationTests.swift */; }; 62E5BD8B91F24BBE502341D4 /* ComposerWindowController.swift in Sources */ = {isa = PBXBuildFile; fileRef = B2F95875A337A64EF513DDB9 /* ComposerWindowController.swift */; }; 649567E2B91E6D41ACCCFB17 /* Clock.swift in Sources */ = {isa = PBXBuildFile; fileRef = 90F72FD8B73B39494A9C9FE9 /* Clock.swift */; }; 74C6F98F86BDE2069821F3CB /* CalendarStateTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 81CE91210C85B61F088A0AC4 /* CalendarStateTests.swift */; }; 76B8D9596745BE7BCFBF5AD8 /* Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = 29CD7860A7C064170B3BC70A /* Assets.xcassets */; }; + 7F2217B81DFF4859B64BC3EF /* HotkeyStoreTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = AB45FEF8F88436D9CCC33C00 /* HotkeyStoreTests.swift */; }; 8047A43C7378E43FC4250379 /* SettingsWindowController.swift in Sources */ = {isa = PBXBuildFile; fileRef = EAB683E77DDC787880B51001 /* SettingsWindowController.swift */; }; 89FFC6AE9E0F45805D1F4D8B /* LegacyMigration.swift in Sources */ = {isa = PBXBuildFile; fileRef = B6D0D42B1162F2BFFD870E82 /* LegacyMigration.swift */; }; 8B730ECAEBDB0E789EB49529 /* ComposerViews.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7CBA1F507173A58E28FD0006 /* ComposerViews.swift */; }; 8B8F993846BC3DB10860C6CA /* InfoViews.swift in Sources */ = {isa = PBXBuildFile; fileRef = 91B70DC5796F2B4D55503295 /* InfoViews.swift */; }; 9F1874D017783F8E938059E1 /* WeekView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4F275E2017E8E1506200D7B7 /* WeekView.swift */; }; + A06C756DA1FEF9036405FE7B /* KeyDisplay.swift in Sources */ = {isa = PBXBuildFile; fileRef = F295C55491DEEBCD13265AA7 /* KeyDisplay.swift */; }; A5C39BC08481288BE9563EAD /* Theme.swift in Sources */ = {isa = PBXBuildFile; fileRef = ACC0D721D056789B08A7C0DE /* Theme.swift */; }; B3DE0A8BF9FDD5C65C1E21FC /* AppDefaults.swift in Sources */ = {isa = PBXBuildFile; fileRef = 30C967ACBAB06423F7509CB1 /* AppDefaults.swift */; }; B460AA9811021F708D266309 /* BlotterKit in Frameworks */ = {isa = PBXBuildFile; productRef = A05D578AF9F493704490E60A /* BlotterKit */; }; BD012D4BBD49E5A642CF76F7 /* BlotterMain.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5719D4CC691B0544A94AC097 /* BlotterMain.swift */; }; + BD74D6850EE8C07A670FCF67 /* ShortcutRecorder.swift in Sources */ = {isa = PBXBuildFile; fileRef = A39698276C7238569CDCC103 /* ShortcutRecorder.swift */; }; E13EDFD8F4F82C977321ED53 /* StatusItemController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 47AC6B698EAA0DC67950116E /* StatusItemController.swift */; }; - EC1BC7C15297CB1756BC2998 /* KeyboardShortcuts in Frameworks */ = {isa = PBXBuildFile; productRef = 98098395C7A5423B6F6F05E6 /* KeyboardShortcuts */; }; F09447040C05C93E8A3474C8 /* SettingsPanes.swift in Sources */ = {isa = PBXBuildFile; fileRef = A5BD3CEA2ED40D9181113154 /* SettingsPanes.swift */; }; F47715D32AB8DB8C35B5835C /* CalendarState.swift in Sources */ = {isa = PBXBuildFile; fileRef = 214B34242C2F6721CFC12155 /* CalendarState.swift */; }; + F4BB0039B457AD3889DB733F /* HotkeyStore.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6B60C660B24FCF34477469B7 /* HotkeyStore.swift */; }; F778A8F301C3B001F00160A1 /* CalendarStore.swift in Sources */ = {isa = PBXBuildFile; fileRef = 099D7023BF02F6A4AFCC7DC5 /* CalendarStore.swift */; }; F948C6E955A84B0DB0DACB6C /* DesktopWindowController.swift in Sources */ = {isa = PBXBuildFile; fileRef = A457F5005D2B31C85D1B396B /* DesktopWindowController.swift */; }; /* End PBXBuildFile section */ @@ -57,6 +60,7 @@ 5719D4CC691B0544A94AC097 /* BlotterMain.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = BlotterMain.swift; sourceTree = ""; }; 5B826CB6F57FDC8DC10CBAF5 /* BlotterKit */ = {isa = PBXFileReference; lastKnownFileType = folder; name = BlotterKit; path = BlotterKit; sourceTree = SOURCE_ROOT; }; 68D711593EEC0A6D2F558722 /* Blotter.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = Blotter.app; sourceTree = BUILT_PRODUCTS_DIR; }; + 6B60C660B24FCF34477469B7 /* HotkeyStore.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = HotkeyStore.swift; sourceTree = ""; }; 7CBA1F507173A58E28FD0006 /* ComposerViews.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ComposerViews.swift; sourceTree = ""; }; 80C499315086814D391D635A /* AppDelegate.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AppDelegate.swift; sourceTree = ""; }; 81CE91210C85B61F088A0AC4 /* CalendarStateTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CalendarStateTests.swift; sourceTree = ""; }; @@ -64,15 +68,18 @@ 90F72FD8B73B39494A9C9FE9 /* Clock.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Clock.swift; sourceTree = ""; }; 91B70DC5796F2B4D55503295 /* InfoViews.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = InfoViews.swift; sourceTree = ""; }; 9B6889B3E2DEF68A35EEC29A /* InfoPlist.xcstrings */ = {isa = PBXFileReference; lastKnownFileType = text.json.xcstrings; path = InfoPlist.xcstrings; sourceTree = ""; }; + A39698276C7238569CDCC103 /* ShortcutRecorder.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ShortcutRecorder.swift; sourceTree = ""; }; A457F5005D2B31C85D1B396B /* DesktopWindowController.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DesktopWindowController.swift; sourceTree = ""; }; A5BD3CEA2ED40D9181113154 /* SettingsPanes.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SettingsPanes.swift; sourceTree = ""; }; + AB45FEF8F88436D9CCC33C00 /* HotkeyStoreTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = HotkeyStoreTests.swift; sourceTree = ""; }; ACC0D721D056789B08A7C0DE /* Theme.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Theme.swift; sourceTree = ""; }; - B211D3CFF1CF666A5F50D14C /* Hotkeys.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Hotkeys.swift; sourceTree = ""; }; B2F95875A337A64EF513DDB9 /* ComposerWindowController.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ComposerWindowController.swift; sourceTree = ""; }; B6D0D42B1162F2BFFD870E82 /* LegacyMigration.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = LegacyMigration.swift; sourceTree = ""; }; D66A7A9DC1B15CDD7E970CA6 /* CalendarView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CalendarView.swift; sourceTree = ""; }; E63D7226AC881AAA873202DA /* Signing.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; path = Signing.xcconfig; sourceTree = ""; }; EAB683E77DDC787880B51001 /* SettingsWindowController.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SettingsWindowController.swift; sourceTree = ""; }; + F226DBE68F9BACBB08BF3513 /* HotkeyCenter.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = HotkeyCenter.swift; sourceTree = ""; }; + F295C55491DEEBCD13265AA7 /* KeyDisplay.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = KeyDisplay.swift; sourceTree = ""; }; FB7A450502CE85C6BF89C323 /* DemoData.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DemoData.swift; sourceTree = ""; }; /* End PBXFileReference section */ @@ -82,7 +89,6 @@ buildActionMask = 2147483647; files = ( B460AA9811021F708D266309 /* BlotterKit in Frameworks */, - EC1BC7C15297CB1756BC2998 /* KeyboardShortcuts in Frameworks */, ); runOnlyForDeploymentPostprocessing = 0; }; @@ -102,11 +108,23 @@ isa = PBXGroup; children = ( 81CE91210C85B61F088A0AC4 /* CalendarStateTests.swift */, + AB45FEF8F88436D9CCC33C00 /* HotkeyStoreTests.swift */, 20900949505E9C73E04E0F5B /* LegacyMigrationTests.swift */, ); path = BlotterTests; sourceTree = ""; }; + 343DFA2E11E28DD752B369BB /* Hotkeys */ = { + isa = PBXGroup; + children = ( + F226DBE68F9BACBB08BF3513 /* HotkeyCenter.swift */, + 6B60C660B24FCF34477469B7 /* HotkeyStore.swift */, + F295C55491DEEBCD13265AA7 /* KeyDisplay.swift */, + A39698276C7238569CDCC103 /* ShortcutRecorder.swift */, + ); + path = Hotkeys; + sourceTree = ""; + }; 3A9DB0295A512720FAA772B8 /* Packages */ = { isa = PBXGroup; children = ( @@ -122,6 +140,7 @@ 79D433668AE6E7346B5300E2 /* Calendar */, 041961520AA3B1CA7F14D59A /* Composer */, 78147C34C97A52FBF66B4F8C /* Desktop */, + 343DFA2E11E28DD752B369BB /* Hotkeys */, C6E5478AEC73A419F93421C3 /* Resources */, AB103A4A20F55DFF2852C558 /* Settings */, 5CDA618EF0B2547C7FC33531 /* Views */, @@ -144,7 +163,6 @@ isa = PBXGroup; children = ( A457F5005D2B31C85D1B396B /* DesktopWindowController.swift */, - B211D3CFF1CF666A5F50D14C /* Hotkeys.swift */, 47AC6B698EAA0DC67950116E /* StatusItemController.swift */, ); path = Desktop; @@ -255,7 +273,6 @@ name = Blotter; packageProductDependencies = ( A05D578AF9F493704490E60A /* BlotterKit */, - 98098395C7A5423B6F6F05E6 /* KeyboardShortcuts */, ); productName = Blotter; productReference = 68D711593EEC0A6D2F558722 /* Blotter.app */; @@ -298,7 +315,6 @@ mainGroup = 8369A2CF3DFCCED04249107F; minimizedProjectReferenceProxies = 1; packageReferences = ( - DE91A13C0C0E8CE6B438FA0E /* XCRemoteSwiftPackageReference "KeyboardShortcuts" */, 7CFD05BFCEF3B5A7D4C8B93D /* XCLocalSwiftPackageReference "BlotterKit" */, ); preferredProjectObjectVersion = 77; @@ -330,6 +346,7 @@ buildActionMask = 2147483647; files = ( 74C6F98F86BDE2069821F3CB /* CalendarStateTests.swift in Sources */, + 7F2217B81DFF4859B64BC3EF /* HotkeyStoreTests.swift in Sources */, 589284774E0F9533914DBCBF /* LegacyMigrationTests.swift in Sources */, ); runOnlyForDeploymentPostprocessing = 0; @@ -349,11 +366,14 @@ 62E5BD8B91F24BBE502341D4 /* ComposerWindowController.swift in Sources */, 48B139E9DCFBDE48B2C62CFD /* DemoData.swift in Sources */, F948C6E955A84B0DB0DACB6C /* DesktopWindowController.swift in Sources */, - 442D214084AF2836CF976F75 /* Hotkeys.swift in Sources */, + 2259160724D8D7DA438C541E /* HotkeyCenter.swift in Sources */, + F4BB0039B457AD3889DB733F /* HotkeyStore.swift in Sources */, 8B8F993846BC3DB10860C6CA /* InfoViews.swift in Sources */, + A06C756DA1FEF9036405FE7B /* KeyDisplay.swift in Sources */, 89FFC6AE9E0F45805D1F4D8B /* LegacyMigration.swift in Sources */, F09447040C05C93E8A3474C8 /* SettingsPanes.swift in Sources */, 8047A43C7378E43FC4250379 /* SettingsWindowController.swift in Sources */, + BD74D6850EE8C07A670FCF67 /* ShortcutRecorder.swift in Sources */, E13EDFD8F4F82C977321ED53 /* StatusItemController.swift in Sources */, A5C39BC08481288BE9563EAD /* Theme.swift in Sources */, 9F1874D017783F8E938059E1 /* WeekView.swift in Sources */, @@ -619,23 +639,7 @@ }; /* End XCLocalSwiftPackageReference section */ -/* Begin XCRemoteSwiftPackageReference section */ - DE91A13C0C0E8CE6B438FA0E /* XCRemoteSwiftPackageReference "KeyboardShortcuts" */ = { - isa = XCRemoteSwiftPackageReference; - repositoryURL = "https://github.com/sindresorhus/KeyboardShortcuts"; - requirement = { - kind = upToNextMajorVersion; - minimumVersion = 3.1.0; - }; - }; -/* End XCRemoteSwiftPackageReference section */ - /* Begin XCSwiftPackageProductDependency section */ - 98098395C7A5423B6F6F05E6 /* KeyboardShortcuts */ = { - isa = XCSwiftPackageProductDependency; - package = DE91A13C0C0E8CE6B438FA0E /* XCRemoteSwiftPackageReference "KeyboardShortcuts" */; - productName = KeyboardShortcuts; - }; A05D578AF9F493704490E60A /* BlotterKit */ = { isa = XCSwiftPackageProductDependency; productName = BlotterKit; diff --git a/Blotter.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolved b/Blotter.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolved deleted file mode 100644 index 35632258..00000000 --- a/Blotter.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolved +++ /dev/null @@ -1,15 +0,0 @@ -{ - "originHash" : "c8fe1f66694a7f0289902bd4004b5a772b8bf8cff84a3d965c6cddc52f492548", - "pins" : [ - { - "identity" : "keyboardshortcuts", - "kind" : "remoteSourceControl", - "location" : "https://github.com/sindresorhus/KeyboardShortcuts", - "state" : { - "revision" : "772133d9dbe800fdac0473226822994c5c162c58", - "version" : "3.1.0" - } - } - ], - "version" : 3 -} diff --git a/Blotter/App/AppDelegate.swift b/Blotter/App/AppDelegate.swift index f120b8e7..f0cb2c47 100644 --- a/Blotter/App/AppDelegate.swift +++ b/Blotter/App/AppDelegate.swift @@ -33,7 +33,9 @@ final class AppDelegate: NSObject, NSApplicationDelegate { self.desktopWindow = desktopWindow statusItem = StatusItemController(actions: self, state: state) - Hotkeys.install(actions: self) + HotkeyCenter.shared.start(store: HotkeyStore.shared) { [weak self] action in + self?.perform(action) + } state.noteActivity() store.requestAccess() @@ -41,7 +43,11 @@ final class AppDelegate: NSObject, NSApplicationDelegate { let defaults = UserDefaults.standard if defaults.bool(forKey: AppDefaults.showsSettingsAtLaunch) { defaults.set(false, forKey: AppDefaults.showsSettingsAtLaunch) - showSettings() + // `-BlotterSettingsPane ` opens a specific pane, for screenshots. + let pane = SettingsWindowController.Pane(rawValue: defaults.integer(forKey: "BlotterSettingsPane")) + state.noteActivity() + settingsWindow.show(pane: pane) + activate() } } @@ -116,6 +122,17 @@ extension AppDelegate: CalendarActions { } } + private func perform(_ action: HotkeyAction) { + switch action { + case .toggleFront: toggleFront() + case .newEvent: showNewEvent() + case .newReminder: showNewReminder() + case .nextWeek: showNextWeek() + case .previousWeek: showPreviousWeek() + case .currentWeek: showCurrentWeek() + } + } + func showNextWeek() { state.navigate(to: state.weekOffset + 1) } func showPreviousWeek() { state.navigate(to: state.weekOffset - 1) } diff --git a/Blotter/App/LegacyMigration.swift b/Blotter/App/LegacyMigration.swift index c6fa475d..04abf42b 100644 --- a/Blotter/App/LegacyMigration.swift +++ b/Blotter/App/LegacyMigration.swift @@ -1,6 +1,5 @@ import AppKit import BlotterKit -import KeyboardShortcuts import OSLog import ServiceManagement @@ -40,7 +39,7 @@ enum LegacyMigration { // MARK: Shortcuts - private static let legacyShortcuts: [(key: String, name: KeyboardShortcuts.Name)] = [ + private static let legacyShortcuts: [(key: String, action: HotkeyAction)] = [ ("shortcutBringToFront", .toggleFront), ("shortcutNewEvent", .newEvent), ("shortcutNewTask", .newReminder), @@ -50,18 +49,15 @@ enum LegacyMigration { ] /// 2.x stored ShortcutRecorder's `SRShortcut`, keyed-archived, under the same names. - static func migrateShortcuts(defaults: UserDefaults) { - for (key, name) in legacyShortcuts { - guard KeyboardShortcuts.getShortcut(for: name) == nil, + static func migrateShortcuts(defaults: UserDefaults, store: HotkeyStore = .shared) { + for (key, action) in legacyShortcuts { + guard store.combo(for: action) == nil, let data = defaults.data(forKey: key), - let legacy = LegacyShortcut.unarchive(data) + let legacy = LegacyShortcut.unarchive(data), + let combo = KeyCombo(legacyKeyCode: legacy.keyCode, modifierFlags: legacy.modifierFlags), + KeyCombo.conflict(for: combo, assigningTo: action, in: store.combos) == nil else { continue } - KeyboardShortcuts.setShortcut( - KeyboardShortcuts.Shortcut( - KeyboardShortcuts.Key(rawValue: legacy.keyCode), - modifiers: NSEvent.ModifierFlags(rawValue: legacy.modifierFlags) - .intersection(.deviceIndependentFlagsMask)), - for: name) + store.set(combo, for: action) } } diff --git a/Blotter/Desktop/Hotkeys.swift b/Blotter/Desktop/Hotkeys.swift deleted file mode 100644 index 530a454c..00000000 --- a/Blotter/Desktop/Hotkeys.swift +++ /dev/null @@ -1,22 +0,0 @@ -import KeyboardShortcuts - -extension KeyboardShortcuts.Name { - static let toggleFront = Self("shortcutBringToFront") - static let newEvent = Self("shortcutNewEvent") - static let newReminder = Self("shortcutNewTask") - static let nextWeek = Self("shortcutShowNextWeek") - static let previousWeek = Self("shortcutShowPreviousWeek") - static let currentWeek = Self("shortcutShowCurrentWeek") -} - -/// Global keyboard shortcuts. None are assigned by default; the user records them in Settings. -enum Hotkeys { - static func install(actions: any CalendarActions) { - KeyboardShortcuts.onKeyUp(for: .toggleFront) { [weak actions] in actions?.toggleFront() } - KeyboardShortcuts.onKeyUp(for: .newEvent) { [weak actions] in actions?.showNewEvent() } - KeyboardShortcuts.onKeyUp(for: .newReminder) { [weak actions] in actions?.showNewReminder() } - KeyboardShortcuts.onKeyUp(for: .nextWeek) { [weak actions] in actions?.showNextWeek() } - KeyboardShortcuts.onKeyUp(for: .previousWeek) { [weak actions] in actions?.showPreviousWeek() } - KeyboardShortcuts.onKeyUp(for: .currentWeek) { [weak actions] in actions?.showCurrentWeek() } - } -} diff --git a/Blotter/Desktop/StatusItemController.swift b/Blotter/Desktop/StatusItemController.swift index bb5ddf08..caa934d8 100644 --- a/Blotter/Desktop/StatusItemController.swift +++ b/Blotter/Desktop/StatusItemController.swift @@ -1,6 +1,5 @@ import AppKit import BlotterKit -import KeyboardShortcuts /// The menu bar item and its menu. final class StatusItemController: NSObject, NSMenuDelegate { @@ -8,6 +7,7 @@ final class StatusItemController: NSObject, NSMenuDelegate { private weak var actions: (any CalendarActions)? private let state: CalendarState private var frontItem: NSMenuItem? + private var shortcutItems: [(item: NSMenuItem, action: HotkeyAction)] = [] private var visibilityObservation: NSKeyValueObservation? private var defaultsObserver: (any NSObjectProtocol)? @@ -75,20 +75,35 @@ final class StatusItemController: NSObject, NSMenuDelegate { return menu } - private func item(_ title: String, _ action: Selector, shortcut: KeyboardShortcuts.Name? = nil) -> NSMenuItem { + private func item(_ title: String, _ action: Selector, shortcut: HotkeyAction? = nil) -> NSMenuItem { let item = NSMenuItem(title: title, action: action, keyEquivalent: "") item.target = self if let shortcut { - item.setShortcut(for: shortcut) + shortcutItems.append((item, shortcut)) } return item } + /// Shows each action's global shortcut next to it. + private func updateShortcuts() { + for (item, action) in shortcutItems { + if let combo = HotkeyStore.shared.combo(for: action) { + let equivalent = KeyDisplay.menuEquivalent(for: combo) + item.keyEquivalent = equivalent.key + item.keyEquivalentModifierMask = equivalent.modifiers + } else { + item.keyEquivalent = "" + item.keyEquivalentModifierMask = [] + } + } + } + func menuWillOpen(_ menu: NSMenu) { state.noteActivity() } func menuNeedsUpdate(_ menu: NSMenu) { + updateShortcuts() frontItem?.title = state.presentation == .front ? String(localized: "Send to Back") : String(localized: "Bring to Front") } diff --git a/Blotter/Hotkeys/HotkeyCenter.swift b/Blotter/Hotkeys/HotkeyCenter.swift new file mode 100644 index 00000000..c48481e2 --- /dev/null +++ b/Blotter/Hotkeys/HotkeyCenter.swift @@ -0,0 +1,108 @@ +import AppKit +import BlotterKit +import Carbon.HIToolbox +import OSLog + +/// Registers the global shortcuts with the system. +/// +/// Uses Carbon's `RegisterEventHotKey`: it is the only API that delivers system-wide shortcuts to a sandboxed app +/// without asking for Accessibility access, and the system consumes the key press so it does not reach other apps. +final class HotkeyCenter { + static let shared = HotkeyCenter() + + /// Shortcuts that could not be registered, typically because another app already uses them. + private(set) var failed: Set = [] + + private var perform: ((HotkeyAction) -> Void)? + private var registered: [HotkeyAction: EventHotKeyRef] = [:] + private var handler: EventHandlerRef? + private var isPaused = false + private let log = Logger(subsystem: "net.wireload.blotter.mac", category: "Hotkeys") + + /// 'BLTR', identifying Blotter's shortcuts in hot key events. + private static let signature: OSType = 0x424C_5452 + + /// Starts listening, and registers the stored shortcuts. `perform` runs when one is pressed. + func start(store: HotkeyStore, perform: @escaping (HotkeyAction) -> Void) { + self.perform = perform + var eventType = EventTypeSpec(eventClass: OSType(kEventClassKeyboard), eventKind: UInt32(kEventHotKeyPressed)) + InstallEventHandler(GetApplicationEventTarget(), hotkeyEventHandler, 1, &eventType, nil, &handler) + store.onChange = { [weak self, weak store] in + guard let store else { return } + self?.register(store.combos) + } + register(store.combos) + } + + /// Stops the shortcuts from firing, while the user records a new one. + func pause() { + isPaused = true + unregisterAll() + } + + func resume(store: HotkeyStore) { + isPaused = false + register(store.combos) + } + + fileprivate func handle(id: UInt32) { + guard !isPaused, Int(id) < HotkeyAction.allCases.count else { return } + perform?(HotkeyAction.allCases[Int(id)]) + } + + private func register(_ combos: [HotkeyAction: KeyCombo]) { + unregisterAll() + guard !isPaused else { return } + failed = [] + for (index, action) in HotkeyAction.allCases.enumerated() { + guard let combo = combos[action] else { continue } + var ref: EventHotKeyRef? + let status = RegisterEventHotKey( + UInt32(combo.keyCode), combo.carbonModifiers, + EventHotKeyID(signature: Self.signature, id: UInt32(index)), + GetApplicationEventTarget(), 0, &ref) + if status == noErr, let ref { + registered[action] = ref + } else { + failed.insert(action) + log.error("Could not register the shortcut for \(action.rawValue, privacy: .public): \(status)") + } + } + } + + private func unregisterAll() { + for ref in registered.values { + UnregisterEventHotKey(ref) + } + registered = [:] + } + + /// Whether macOS reserves `combo` for one of its own shortcuts (Spotlight, Mission Control, screenshots, …). + static func isReservedBySystem(_ combo: KeyCombo) -> Bool { + var unmanaged: Unmanaged? + guard CopySymbolicHotKeys(&unmanaged) == noErr, + let hotkeys = unmanaged?.takeRetainedValue() as? [[String: Any]] + else { return false } + return hotkeys.contains { hotkey in + (hotkey["kHISymbolicHotKeyEnabled"] as? Bool) == true + && (hotkey["kHISymbolicHotKeyCode"] as? Int) == Int(combo.keyCode) + && (hotkey["kHISymbolicHotKeyModifiers"] as? Int).map { UInt32($0) & 0x1B00 } == combo.carbonModifiers + } + } +} + +/// Carbon calls this on the main thread for every hot key press. +private nonisolated func hotkeyEventHandler( + _ next: EventHandlerCallRef?, _ event: EventRef?, _ userData: UnsafeMutableRawPointer? +) -> OSStatus { + guard let event else { return OSStatus(eventNotHandledErr) } + var id = EventHotKeyID() + let status = GetEventParameter( + event, EventParamName(kEventParamDirectObject), EventParamType(typeEventHotKeyID), nil, + MemoryLayout.size, nil, &id) + guard status == noErr, id.signature == 0x424C_5452 else { return OSStatus(eventNotHandledErr) } + MainActor.assumeIsolated { + HotkeyCenter.shared.handle(id: id.id) + } + return noErr +} diff --git a/Blotter/Hotkeys/HotkeyStore.swift b/Blotter/Hotkeys/HotkeyStore.swift new file mode 100644 index 00000000..14def031 --- /dev/null +++ b/Blotter/Hotkeys/HotkeyStore.swift @@ -0,0 +1,57 @@ +import BlotterKit +import Foundation +import Observation + +/// The user's global shortcuts, persisted in user defaults. None are assigned by default. +@Observable +final class HotkeyStore { + static let shared = HotkeyStore() + + enum AssignmentError: Error, Equatable { + /// Needs ⌘, ⌥ or ⌃ (or a function key). + case needsModifier + /// Already used by another Blotter action. + case usedBy(HotkeyAction) + /// macOS or another app has claimed the shortcut. + case unavailable + } + + private(set) var combos: [HotkeyAction: KeyCombo] = [:] + + /// Called after any change, to register the new set of shortcuts. + @ObservationIgnored var onChange: (() -> Void)? + + @ObservationIgnored private let defaults: UserDefaults + + init(defaults: UserDefaults = .standard) { + self.defaults = defaults + for action in HotkeyAction.allCases { + if let data = defaults.data(forKey: action.defaultsKey), + let combo = try? JSONDecoder().decode(KeyCombo.self, from: data) + { + combos[action] = combo + } + } + } + + func combo(for action: HotkeyAction) -> KeyCombo? { combos[action] } + + /// Checks a shortcut before it is assigned to `action`. + func validate(_ combo: KeyCombo, for action: HotkeyAction) -> AssignmentError? { + if !combo.isValid { return .needsModifier } + if let other = KeyCombo.conflict(for: combo, assigningTo: action, in: combos) { return .usedBy(other) } + if HotkeyCenter.isReservedBySystem(combo) { return .unavailable } + return nil + } + + /// Assigns (or, with `nil`, clears) the shortcut for `action`. Validation is the caller's job. + func set(_ combo: KeyCombo?, for action: HotkeyAction) { + combos[action] = combo + if let combo, let data = try? JSONEncoder().encode(combo) { + defaults.set(data, forKey: action.defaultsKey) + } else { + defaults.removeObject(forKey: action.defaultsKey) + } + onChange?() + } +} diff --git a/Blotter/Hotkeys/KeyDisplay.swift b/Blotter/Hotkeys/KeyDisplay.swift new file mode 100644 index 00000000..42931161 --- /dev/null +++ b/Blotter/Hotkeys/KeyDisplay.swift @@ -0,0 +1,70 @@ +import AppKit +import BlotterKit +import Carbon.HIToolbox + +/// How a shortcut looks: the symbols shown in Settings, and the key equivalent shown in menus. +enum KeyDisplay { + /// For example "⌃⌥B" or "⌘F5", using the character the key types on the current keyboard layout. + static func string(for combo: KeyCombo) -> String { + combo.modifierSymbols + keyName(for: combo) + } + + static func keyName(for combo: KeyCombo) -> String { + if let name = combo.specialKeyName { + return name == "Space" ? String(localized: "Space") : name + } + return character(for: combo.keyCode)?.uppercased() ?? "#\(combo.keyCode)" + } + + /// The key equivalent and modifier mask for an `NSMenuItem`. + static func menuEquivalent(for combo: KeyCombo) -> (key: String, modifiers: NSEvent.ModifierFlags) { + let modifiers = NSEvent.ModifierFlags(rawValue: combo.modifiers.rawValue) + if let special = menuKeys[combo.keyCode] { + return (String(Character(UnicodeScalar(special) ?? " ")), modifiers) + } + return (character(for: combo.keyCode)?.lowercased() ?? "", modifiers) + } + + /// The character a key types without modifiers, on the current layout (or an ASCII-capable one, for input + /// methods such as Japanese that have no key layout of their own). + static func character(for keyCode: UInt16) -> String? { + for source in [ + TISCopyCurrentKeyboardLayoutInputSource(), TISCopyCurrentASCIICapableKeyboardLayoutInputSource(), + ] { + guard let source = source?.takeRetainedValue(), + let pointer = TISGetInputSourceProperty(source, kTISPropertyUnicodeKeyLayoutData) + else { continue } + let layout = Unmanaged.fromOpaque(pointer).takeUnretainedValue() as Data + var deadKeyState: UInt32 = 0 + var characters = [UniChar](repeating: 0, count: 4) + var length = 0 + let status = layout.withUnsafeBytes { bytes -> OSStatus in + guard let keyboard = bytes.bindMemory(to: UCKeyboardLayout.self).baseAddress else { return -1 } + return UCKeyTranslate( + keyboard, keyCode, UInt16(kUCKeyActionDisplay), 0, UInt32(LMGetKbdType()), + OptionBits(kUCKeyTranslateNoDeadKeysMask), &deadKeyState, characters.count, &length, + &characters) + } + if status == noErr, length > 0 { + let string = String(utf16CodeUnits: characters, count: length) + if !string.trimmingCharacters(in: .controlCharacters).isEmpty { + return string + } + } + } + return nil + } + + /// Key equivalents for keys that do not type a character, as AppKit's function-key code points. + private static let menuKeys: [UInt16: Int] = [ + 0x7A: NSF1FunctionKey, 0x78: NSF2FunctionKey, 0x63: NSF3FunctionKey, 0x76: NSF4FunctionKey, + 0x60: NSF5FunctionKey, 0x61: NSF6FunctionKey, 0x62: NSF7FunctionKey, 0x64: NSF8FunctionKey, + 0x65: NSF9FunctionKey, 0x6D: NSF10FunctionKey, 0x67: NSF11FunctionKey, 0x6F: NSF12FunctionKey, + 0x69: NSF13FunctionKey, 0x6B: NSF14FunctionKey, 0x71: NSF15FunctionKey, 0x6A: NSF16FunctionKey, + 0x40: NSF17FunctionKey, 0x4F: NSF18FunctionKey, 0x50: NSF19FunctionKey, 0x5A: NSF20FunctionKey, + 0x7B: NSLeftArrowFunctionKey, 0x7C: NSRightArrowFunctionKey, 0x7D: NSDownArrowFunctionKey, + 0x7E: NSUpArrowFunctionKey, 0x73: NSHomeFunctionKey, 0x77: NSEndFunctionKey, + 0x74: NSPageUpFunctionKey, 0x79: NSPageDownFunctionKey, 0x75: NSDeleteFunctionKey, + 0x24: 0x0D, 0x4C: 0x03, 0x30: 0x09, 0x31: 0x20, 0x33: 0x08, 0x35: 0x1B, + ] +} diff --git a/Blotter/Hotkeys/ShortcutRecorder.swift b/Blotter/Hotkeys/ShortcutRecorder.swift new file mode 100644 index 00000000..5cfca960 --- /dev/null +++ b/Blotter/Hotkeys/ShortcutRecorder.swift @@ -0,0 +1,132 @@ +import AppKit +import BlotterKit +import SwiftUI + +/// A field that records a global shortcut for one action: click it, then press the shortcut. +/// +/// Escape cancels, and Delete clears the shortcut. +struct ShortcutRecorder: View { + let action: HotkeyAction + + @State private var store = HotkeyStore.shared + @State private var isRecording = false + @State private var monitor: Any? + @State private var problem: HotkeyStore.AssignmentError? + + var body: some View { + VStack(alignment: .trailing, spacing: 4) { + HStack(spacing: 4) { + Button(action: toggleRecording) { + Text(label) + .monospacedDigit() + .foregroundStyle(isRecording || store.combo(for: action) == nil ? .secondary : .primary) + .frame(minWidth: 110) + } + .accessibilityLabel(accessibilityLabel) + .accessibilityHint(Text("Click, then press the shortcut.")) + + if store.combo(for: action) != nil, !isRecording { + Button { + store.set(nil, for: action) + } label: { + Image(systemName: "xmark.circle.fill") + .foregroundStyle(.secondary) + } + .buttonStyle(.plain) + .accessibilityLabel(Text("Clear shortcut")) + } + } + if let problem { + Text(message(for: problem)) + .font(.caption) + .foregroundStyle(.red) + } + } + .onDisappear(perform: stopRecording) + } + + private var label: String { + if isRecording { return String(localized: "Press shortcut…") } + guard let combo = store.combo(for: action) else { return String(localized: "Record Shortcut") } + return KeyDisplay.string(for: combo) + } + + private var accessibilityLabel: String { + guard let combo = store.combo(for: action) else { return String(localized: "Record Shortcut") } + return KeyDisplay.string(for: combo) + } + + private func toggleRecording() { + isRecording ? stopRecording() : startRecording() + } + + private func startRecording() { + problem = nil + isRecording = true + // Existing shortcuts would fire instead of being recorded. + HotkeyCenter.shared.pause() + monitor = NSEvent.addLocalMonitorForEvents(matching: .keyDown) { event in + MainActor.assumeIsolated { record(event) } ? nil : event + } + } + + private func stopRecording() { + guard isRecording else { return } + isRecording = false + if let monitor { + NSEvent.removeMonitor(monitor) + } + monitor = nil + HotkeyCenter.shared.resume(store: store) + } + + /// Returns whether the event was consumed. + private func record(_ event: NSEvent) -> Bool { + let modifiers = event.modifierFlags.intersection(.deviceIndependentFlagsMask) + let plain = modifiers.isDisjoint(with: [.command, .option, .control, .shift]) + switch event.keyCode { + case 0x35 where plain: // Escape + stopRecording() + return true + case 0x33 where plain, 0x75 where plain: // Delete, Forward Delete + store.set(nil, for: action) + stopRecording() + return true + default: + break + } + + let combo = KeyCombo(keyCode: event.keyCode, modifiers: KeyCombo.Modifiers(rawValue: modifiers.rawValue)) + if let problem = store.validate(combo, for: action) { + self.problem = problem + NSSound.beep() + return true + } + problem = nil + stopRecording() + store.set(combo, for: action) + return true + } + + private func message(for problem: HotkeyStore.AssignmentError) -> String { + switch problem { + case .needsModifier: + String(localized: "Use at least one of ⌘, ⌥ or ⌃.") + case .usedBy(let other): + String(localized: "Already used for “\(Self.name(of: other))”.") + case .unavailable: + String(localized: "macOS already uses this shortcut.") + } + } + + static func name(of action: HotkeyAction) -> String { + switch action { + case .toggleFront: String(localized: "Bring to Front") + case .newEvent: String(localized: "New Event") + case .newReminder: String(localized: "New Reminder") + case .nextWeek: String(localized: "Next Week") + case .previousWeek: String(localized: "Previous Week") + case .currentWeek: String(localized: "Current Week") + } + } +} diff --git a/Blotter/Resources/Localizable.xcstrings b/Blotter/Resources/Localizable.xcstrings index bfd9d768..cb74077b 100644 --- a/Blotter/Resources/Localizable.xcstrings +++ b/Blotter/Resources/Localizable.xcstrings @@ -553,6 +553,52 @@ } } }, + "Already used for “%@”.": { + "localizations": { + "de": { + "stringUnit": { + "state": "translated", + "value": "Wird bereits für „%@“ verwendet." + } + }, + "es": { + "stringUnit": { + "state": "translated", + "value": "Ya se usa para «%@»." + } + }, + "fr": { + "stringUnit": { + "state": "translated", + "value": "Déjà utilisé pour « %@ »." + } + }, + "ja": { + "stringUnit": { + "state": "translated", + "value": "「%@」で既に使用されています。" + } + }, + "ko": { + "stringUnit": { + "state": "translated", + "value": "이미 “%@”에 사용 중입니다." + } + }, + "ru": { + "stringUnit": { + "state": "translated", + "value": "Уже используется для «%@»." + } + }, + "sv": { + "stringUnit": { + "state": "translated", + "value": "Används redan för ”%@”." + } + } + } + }, "Appearance": { "localizations": { "de": { @@ -1338,6 +1384,98 @@ } } }, + "Clear shortcut": { + "localizations": { + "de": { + "stringUnit": { + "state": "translated", + "value": "Kurzbefehl entfernen" + } + }, + "es": { + "stringUnit": { + "state": "translated", + "value": "Borrar función rápida" + } + }, + "fr": { + "stringUnit": { + "state": "translated", + "value": "Effacer le raccourci" + } + }, + "ja": { + "stringUnit": { + "state": "translated", + "value": "ショートカットを消去" + } + }, + "ko": { + "stringUnit": { + "state": "translated", + "value": "단축키 지우기" + } + }, + "ru": { + "stringUnit": { + "state": "translated", + "value": "Удалить сочетание" + } + }, + "sv": { + "stringUnit": { + "state": "translated", + "value": "Rensa kortkommando" + } + } + } + }, + "Click, then press the shortcut.": { + "localizations": { + "de": { + "stringUnit": { + "state": "translated", + "value": "Klicke und drücke dann den Kurzbefehl." + } + }, + "es": { + "stringUnit": { + "state": "translated", + "value": "Haz clic y pulsa la función rápida." + } + }, + "fr": { + "stringUnit": { + "state": "translated", + "value": "Cliquez, puis appuyez sur le raccourci." + } + }, + "ja": { + "stringUnit": { + "state": "translated", + "value": "クリックしてからショートカットを押します。" + } + }, + "ko": { + "stringUnit": { + "state": "translated", + "value": "클릭한 다음 단축키를 누르십시오." + } + }, + "ru": { + "stringUnit": { + "state": "translated", + "value": "Нажмите, затем введите сочетание клавиш." + } + }, + "sv": { + "stringUnit": { + "state": "translated", + "value": "Klicka och tryck sedan på kortkommandot." + } + } + } + }, "Current Week": { "localizations": { "de": { @@ -3316,6 +3454,52 @@ } } }, + "Press shortcut…": { + "localizations": { + "de": { + "stringUnit": { + "state": "translated", + "value": "Kurzbefehl drücken …" + } + }, + "es": { + "stringUnit": { + "state": "translated", + "value": "Pulsa la función rápida…" + } + }, + "fr": { + "stringUnit": { + "state": "translated", + "value": "Appuyez sur le raccourci…" + } + }, + "ja": { + "stringUnit": { + "state": "translated", + "value": "ショートカットを押してください…" + } + }, + "ko": { + "stringUnit": { + "state": "translated", + "value": "단축키를 누르십시오…" + } + }, + "ru": { + "stringUnit": { + "state": "translated", + "value": "Нажмите сочетание…" + } + }, + "sv": { + "stringUnit": { + "state": "translated", + "value": "Tryck på kortkommando…" + } + } + } + }, "Previous Week": { "localizations": { "de": { @@ -3500,6 +3684,52 @@ } } }, + "Record Shortcut": { + "localizations": { + "de": { + "stringUnit": { + "state": "translated", + "value": "Kurzbefehl aufnehmen" + } + }, + "es": { + "stringUnit": { + "state": "translated", + "value": "Grabar función rápida" + } + }, + "fr": { + "stringUnit": { + "state": "translated", + "value": "Enregistrer le raccourci" + } + }, + "ja": { + "stringUnit": { + "state": "translated", + "value": "ショートカットを記録" + } + }, + "ko": { + "stringUnit": { + "state": "translated", + "value": "단축키 기록" + } + }, + "ru": { + "stringUnit": { + "state": "translated", + "value": "Записать сочетание" + } + }, + "sv": { + "stringUnit": { + "state": "translated", + "value": "Spela in kortkommando" + } + } + } + }, "Remind me on a day": { "localizations": { "de": { @@ -4236,6 +4466,52 @@ } } }, + "Space": { + "localizations": { + "de": { + "stringUnit": { + "state": "translated", + "value": "Leertaste" + } + }, + "es": { + "stringUnit": { + "state": "translated", + "value": "Espacio" + } + }, + "fr": { + "stringUnit": { + "state": "translated", + "value": "Espace" + } + }, + "ja": { + "stringUnit": { + "state": "translated", + "value": "スペース" + } + }, + "ko": { + "stringUnit": { + "state": "translated", + "value": "스페이스" + } + }, + "ru": { + "stringUnit": { + "state": "translated", + "value": "Пробел" + } + }, + "sv": { + "stringUnit": { + "state": "translated", + "value": "Mellanslag" + } + } + } + }, "Starts": { "localizations": { "de": { @@ -4696,6 +4972,52 @@ } } }, + "Use at least one of ⌘, ⌥ or ⌃.": { + "localizations": { + "de": { + "stringUnit": { + "state": "translated", + "value": "Verwende mindestens eine der Tasten ⌘, ⌥ oder ⌃." + } + }, + "es": { + "stringUnit": { + "state": "translated", + "value": "Usa al menos una de las teclas ⌘, ⌥ o ⌃." + } + }, + "fr": { + "stringUnit": { + "state": "translated", + "value": "Utilisez au moins l’une des touches ⌘, ⌥ ou ⌃." + } + }, + "ja": { + "stringUnit": { + "state": "translated", + "value": "⌘、⌥、⌃のいずれかを含めてください。" + } + }, + "ko": { + "stringUnit": { + "state": "translated", + "value": "⌘, ⌥ 또는 ⌃ 중 하나 이상을 사용하십시오." + } + }, + "ru": { + "stringUnit": { + "state": "translated", + "value": "Используйте хотя бы одну из клавиш ⌘, ⌥ или ⌃." + } + }, + "sv": { + "stringUnit": { + "state": "translated", + "value": "Använd minst en av ⌘, ⌥ eller ⌃." + } + } + } + }, "Version %@ (%@)": { "localizations": { "de": { @@ -4879,6 +5201,52 @@ } } } + }, + "macOS already uses this shortcut.": { + "localizations": { + "de": { + "stringUnit": { + "state": "translated", + "value": "macOS verwendet diesen Kurzbefehl bereits." + } + }, + "es": { + "stringUnit": { + "state": "translated", + "value": "macOS ya usa esta función rápida." + } + }, + "fr": { + "stringUnit": { + "state": "translated", + "value": "macOS utilise déjà ce raccourci." + } + }, + "ja": { + "stringUnit": { + "state": "translated", + "value": "このショートカットはmacOSで既に使用されています。" + } + }, + "ko": { + "stringUnit": { + "state": "translated", + "value": "macOS에서 이미 이 단축키를 사용하고 있습니다." + } + }, + "ru": { + "stringUnit": { + "state": "translated", + "value": "Это сочетание уже используется macOS." + } + }, + "sv": { + "stringUnit": { + "state": "translated", + "value": "macOS använder redan det här kortkommandot." + } + } + } } }, "version": "1.0" diff --git a/Blotter/Settings/SettingsPanes.swift b/Blotter/Settings/SettingsPanes.swift index f78704c8..21468825 100644 --- a/Blotter/Settings/SettingsPanes.swift +++ b/Blotter/Settings/SettingsPanes.swift @@ -1,7 +1,6 @@ import AppKit import BlotterKit import EventKit -import KeyboardShortcuts import OSLog import ServiceManagement import SwiftUI @@ -101,14 +100,14 @@ struct ShortcutSettings: View { var body: some View { Form { Section { - KeyboardShortcuts.Recorder(String(localized: "Bring to front:"), name: .toggleFront) - KeyboardShortcuts.Recorder(String(localized: "New event:"), name: .newEvent) - KeyboardShortcuts.Recorder(String(localized: "New reminder:"), name: .newReminder) + LabeledContent("Bring to front:") { ShortcutRecorder(action: .toggleFront) } + LabeledContent("New event:") { ShortcutRecorder(action: .newEvent) } + LabeledContent("New reminder:") { ShortcutRecorder(action: .newReminder) } } Section { - KeyboardShortcuts.Recorder(String(localized: "Next week:"), name: .nextWeek) - KeyboardShortcuts.Recorder(String(localized: "Previous week:"), name: .previousWeek) - KeyboardShortcuts.Recorder(String(localized: "Current week:"), name: .currentWeek) + LabeledContent("Next week:") { ShortcutRecorder(action: .nextWeek) } + LabeledContent("Previous week:") { ShortcutRecorder(action: .previousWeek) } + LabeledContent("Current week:") { ShortcutRecorder(action: .currentWeek) } } footer: { Text("Shortcuts work from any app.") .foregroundStyle(.secondary) diff --git a/BlotterKit/Sources/BlotterKit/Hotkey.swift b/BlotterKit/Sources/BlotterKit/Hotkey.swift new file mode 100644 index 00000000..9c0bed56 --- /dev/null +++ b/BlotterKit/Sources/BlotterKit/Hotkey.swift @@ -0,0 +1,103 @@ +import Foundation + +/// The actions that can have a global keyboard shortcut. +public enum HotkeyAction: String, CaseIterable, Codable, Sendable { + case toggleFront + case newEvent + case newReminder + case nextWeek + case previousWeek + case currentWeek + + /// Where the shortcut is stored in user defaults. + public var defaultsKey: String { "Hotkey." + rawValue } +} + +/// A key and its modifiers, as pressed on the keyboard. +public struct KeyCombo: Codable, Hashable, Sendable { + /// Modifier keys. Raw values match AppKit's device-independent `NSEvent.ModifierFlags`. + public struct Modifiers: OptionSet, Codable, Hashable, Sendable { + public let rawValue: UInt + + public init(rawValue: UInt) { + self.rawValue = rawValue + } + + public static let shift = Modifiers(rawValue: 1 << 17) + public static let control = Modifiers(rawValue: 1 << 18) + public static let option = Modifiers(rawValue: 1 << 19) + public static let command = Modifiers(rawValue: 1 << 20) + + public static let all: Modifiers = [.shift, .control, .option, .command] + } + + /// Virtual key code (`kVK_…`), independent of the keyboard layout. + public var keyCode: UInt16 + public var modifiers: Modifiers + + public init(keyCode: UInt16, modifiers: Modifiers) { + self.keyCode = keyCode + self.modifiers = modifiers.intersection(.all) + } + + /// Converts a ShortcutRecorder shortcut stored by Blotter 2.x (key code and Cocoa modifier flags). + public init?(legacyKeyCode keyCode: Int, modifierFlags: UInt) { + guard let code = UInt16(exactly: keyCode) else { return nil } + self.init(keyCode: code, modifiers: Modifiers(rawValue: modifierFlags)) + guard isValid else { return nil } + } + + /// Modifiers in Carbon's format, for `RegisterEventHotKey`. + public var carbonModifiers: UInt32 { + var flags: UInt32 = 0 + if modifiers.contains(.command) { flags |= 0x0100 } // cmdKey + if modifiers.contains(.shift) { flags |= 0x0200 } // shiftKey + if modifiers.contains(.option) { flags |= 0x0800 } // optionKey + if modifiers.contains(.control) { flags |= 0x1000 } // controlKey + return flags + } + + /// Modifier symbols in the order macOS shows them: ⌃⌥⇧⌘. + public var modifierSymbols: String { + var symbols = "" + if modifiers.contains(.control) { symbols += "⌃" } + if modifiers.contains(.option) { symbols += "⌥" } + if modifiers.contains(.shift) { symbols += "⇧" } + if modifiers.contains(.command) { symbols += "⌘" } + return symbols + } + + /// Whether the key is a function key (F1–F20), which may be used without modifiers. + public var isFunctionKey: Bool { Self.functionKeys.keys.contains(keyCode) } + + /// A global shortcut needs ⌘, ⌥ or ⌃ (Shift alone would block typing capitals), unless it is a function key. + public var isValid: Bool { + isFunctionKey || !modifiers.isDisjoint(with: [.command, .option, .control]) + } + + /// The symbol or name printed on keys that do not type a character, or `nil` for character keys. + public var specialKeyName: String? { + Self.functionKeys[keyCode] ?? Self.specialKeys[keyCode] + } + + static let functionKeys: [UInt16: String] = [ + 0x7A: "F1", 0x78: "F2", 0x63: "F3", 0x76: "F4", 0x60: "F5", 0x61: "F6", 0x62: "F7", 0x64: "F8", + 0x65: "F9", 0x6D: "F10", 0x67: "F11", 0x6F: "F12", 0x69: "F13", 0x6B: "F14", 0x71: "F15", + 0x6A: "F16", 0x40: "F17", 0x4F: "F18", 0x50: "F19", 0x5A: "F20", + ] + + static let specialKeys: [UInt16: String] = [ + 0x24: "↩", 0x4C: "⌤", 0x30: "⇥", 0x31: "Space", 0x33: "⌫", 0x75: "⌦", 0x35: "⎋", + 0x73: "↖", 0x77: "↘", 0x74: "⇞", 0x79: "⇟", + 0x7B: "←", 0x7C: "→", 0x7D: "↓", 0x7E: "↑", + ] +} + +extension KeyCombo { + /// The other action already using `combo`, if any. + public static func conflict( + for combo: KeyCombo, assigningTo action: HotkeyAction, in assignments: [HotkeyAction: KeyCombo] + ) -> HotkeyAction? { + HotkeyAction.allCases.first { $0 != action && assignments[$0] == combo } + } +} diff --git a/BlotterKit/Tests/BlotterKitTests/HotkeyTests.swift b/BlotterKit/Tests/BlotterKitTests/HotkeyTests.swift new file mode 100644 index 00000000..bd834f61 --- /dev/null +++ b/BlotterKit/Tests/BlotterKitTests/HotkeyTests.swift @@ -0,0 +1,55 @@ +import Foundation +import Testing + +@testable import BlotterKit + +@Suite struct HotkeyTests { + let commandShiftB = KeyCombo(keyCode: 0x0B, modifiers: [.command, .shift]) + + @Test func modifierSymbolsInMacOrder() { + #expect(KeyCombo(keyCode: 0x0B, modifiers: [.command, .shift, .option, .control]).modifierSymbols == "⌃⌥⇧⌘") + #expect(commandShiftB.modifierSymbols == "⇧⌘") + } + + @Test func carbonModifiers() { + #expect(commandShiftB.carbonModifiers == 0x0100 | 0x0200) + #expect(KeyCombo(keyCode: 0, modifiers: [.option, .control]).carbonModifiers == 0x0800 | 0x1000) + } + + @Test func validity() { + #expect(commandShiftB.isValid) + #expect(!KeyCombo(keyCode: 0x0B, modifiers: []).isValid) + #expect(!KeyCombo(keyCode: 0x0B, modifiers: [.shift]).isValid) + #expect(KeyCombo(keyCode: 0x60, modifiers: []).isValid) // F5 + } + + @Test func ignoresOtherModifierBits() { + // Caps Lock (1 << 16) and device-dependent bits are dropped. + let combo = KeyCombo(keyCode: 0x0B, modifiers: KeyCombo.Modifiers(rawValue: 1 << 16 | 1 << 20 | 0x8)) + #expect(combo.modifiers == [.command]) + } + + @Test func specialKeyNames() { + #expect(KeyCombo(keyCode: 0x7A, modifiers: []).specialKeyName == "F1") + #expect(KeyCombo(keyCode: 0x7E, modifiers: [.command]).specialKeyName == "↑") + #expect(commandShiftB.specialKeyName == nil) + } + + @Test func legacyShortcutRecorderValues() { + // ⌘⇧B as stored by ShortcutRecorder: key code 11, Cocoa flags for Shift and Command. + #expect(KeyCombo(legacyKeyCode: 11, modifierFlags: 1_179_648) == commandShiftB) + #expect(KeyCombo(legacyKeyCode: 11, modifierFlags: 0) == nil) + #expect(KeyCombo(legacyKeyCode: -1, modifierFlags: 1_179_648) == nil) + } + + @Test func codableRoundTrip() throws { + let data = try JSONEncoder().encode(commandShiftB) + #expect(try JSONDecoder().decode(KeyCombo.self, from: data) == commandShiftB) + } + + @Test func conflicts() { + let assignments: [HotkeyAction: KeyCombo] = [.newEvent: commandShiftB] + #expect(KeyCombo.conflict(for: commandShiftB, assigningTo: .toggleFront, in: assignments) == .newEvent) + #expect(KeyCombo.conflict(for: commandShiftB, assigningTo: .newEvent, in: assignments) == nil) + } +} diff --git a/BlotterTests/HotkeyStoreTests.swift b/BlotterTests/HotkeyStoreTests.swift new file mode 100644 index 00000000..4479e160 --- /dev/null +++ b/BlotterTests/HotkeyStoreTests.swift @@ -0,0 +1,52 @@ +import BlotterKit +import Foundation +import Testing + +@testable import Blotter + +@MainActor +@Suite struct HotkeyStoreTests { + let commandShiftB = KeyCombo(keyCode: 0x0B, modifiers: [.command, .shift]) + + private func scratchDefaults() throws -> (UserDefaults, String) { + let suite = "BlotterTests.\(UUID().uuidString)" + return (try #require(UserDefaults(suiteName: suite)), suite) + } + + @Test func persistsAndClears() throws { + let (defaults, suite) = try scratchDefaults() + defer { defaults.removePersistentDomain(forName: suite) } + + HotkeyStore(defaults: defaults).set(commandShiftB, for: .newEvent) + #expect(HotkeyStore(defaults: defaults).combo(for: .newEvent) == commandShiftB) + + HotkeyStore(defaults: defaults).set(nil, for: .newEvent) + #expect(HotkeyStore(defaults: defaults).combo(for: .newEvent) == nil) + } + + @Test func validation() throws { + let (defaults, suite) = try scratchDefaults() + defer { defaults.removePersistentDomain(forName: suite) } + let store = HotkeyStore(defaults: defaults) + store.set(commandShiftB, for: .newEvent) + + #expect(store.validate(KeyCombo(keyCode: 0x0B, modifiers: [.shift]), for: .toggleFront) == .needsModifier) + #expect(store.validate(commandShiftB, for: .toggleFront) == .usedBy(.newEvent)) + #expect(store.validate(commandShiftB, for: .newEvent) == nil) + } + + @Test func migratesShortcutRecorderShortcuts() throws { + let (defaults, suite) = try scratchDefaults() + defer { defaults.removePersistentDomain(forName: suite) } + let archiver = NSKeyedArchiver(requiringSecureCoding: false) + archiver.setClassName("SRShortcut", for: LegacyShortcut.self) + archiver.encode(LegacyShortcut(keyCode: 11, modifierFlags: 1_179_648), forKey: NSKeyedArchiveRootObjectKey) + archiver.finishEncoding() + defaults.set(archiver.encodedData, forKey: "shortcutBringToFront") + + let store = HotkeyStore(defaults: defaults) + LegacyMigration.migrateShortcuts(defaults: defaults, store: store) + + #expect(store.combo(for: .toggleFront) == commandShiftB) + } +} diff --git a/project.yml b/project.yml index 894cf0bb..33eca294 100644 --- a/project.yml +++ b/project.yml @@ -26,9 +26,6 @@ settings: packages: BlotterKit: path: BlotterKit - KeyboardShortcuts: - url: https://github.com/sindresorhus/KeyboardShortcuts - from: "3.1.0" configFiles: Debug: Configs/Signing.xcconfig @@ -45,7 +42,6 @@ targets: - Blotter.entitlements dependencies: - package: BlotterKit - - package: KeyboardShortcuts info: path: Blotter/Info.plist properties: