diff --git a/Leader Key.xcodeproj/project.pbxproj b/Leader Key.xcodeproj/project.pbxproj index 141cebf6..4c057d3f 100644 --- a/Leader Key.xcodeproj/project.pbxproj +++ b/Leader Key.xcodeproj/project.pbxproj @@ -7,6 +7,7 @@ objects = { /* Begin PBXBuildFile section */ + 0A27E0A22EF7616100731753 /* CustomIconRenderer.swift in Sources */ = {isa = PBXBuildFile; fileRef = 0A27E0A12EF7616100731753 /* CustomIconRenderer.swift */; }; 115AA5BF2DA521C600C17E18 /* ActionIcon.swift in Sources */ = {isa = PBXBuildFile; fileRef = 115AA5BE2DA521C200C17E18 /* ActionIcon.swift */; }; 115AA5C22DA546D500C17E18 /* SymbolPicker in Frameworks */ = {isa = PBXBuildFile; productRef = 115AA5C12DA546D500C17E18 /* SymbolPicker */; }; 130196C62D73B3DE0093148B /* Breadcrumbs.swift in Sources */ = {isa = PBXBuildFile; fileRef = 130196C52D73B3DC0093148B /* Breadcrumbs.swift */; }; @@ -15,7 +16,6 @@ 423632282D6A806700878D92 /* Theme.swift in Sources */ = {isa = PBXBuildFile; fileRef = 423632272D6A806700878D92 /* Theme.swift */; }; 42454DDB2D71CB39004E1374 /* ConfigValidator.swift in Sources */ = {isa = PBXBuildFile; fileRef = 42454DDA2D71CB39004E1374 /* ConfigValidator.swift */; }; 42454DDD2D71CBAB004E1374 /* ConfigValidatorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 42454DDC2D71CBAB004E1374 /* ConfigValidatorTests.swift */; }; - EC5CEBC4C47B4C5DB2258813 /* URLSchemeTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = EC5CEBC4C47B4C5DB2258814 /* URLSchemeTests.swift */; }; 425495402D75EFAD0020300E /* ForTheHorde.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4254953F2D75EFAD0020300E /* ForTheHorde.swift */; }; 426E625B2D2E6A98009FD2F2 /* CommandRunner.swift in Sources */ = {isa = PBXBuildFile; fileRef = 426E625A2D2E6A98009FD2F2 /* CommandRunner.swift */; }; 4279AFED2C6A175500952A83 /* LaunchAtLogin in Frameworks */ = {isa = PBXBuildFile; productRef = 4279AFEC2C6A175500952A83 /* LaunchAtLogin */; }; @@ -26,7 +26,6 @@ 427C181A2BD3123C00955B98 /* Defaults in Frameworks */ = {isa = PBXBuildFile; productRef = 427C18192BD3123C00955B98 /* Defaults */; }; 427C181C2BD314B500955B98 /* Constants.swift in Sources */ = {isa = PBXBuildFile; fileRef = 427C181B2BD314B500955B98 /* Constants.swift */; }; 427C18202BD31C3D00955B98 /* AppDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 427C181F2BD31C3D00955B98 /* AppDelegate.swift */; }; - 73192AF63CAF425397D7C0D1 /* URLSchemeHandler.swift in Sources */ = {isa = PBXBuildFile; fileRef = 73192AF63CAF425397D7C0D2 /* URLSchemeHandler.swift */; }; 427C18232BD31DF100955B98 /* Settings in Frameworks */ = {isa = PBXBuildFile; productRef = 427C18222BD31DF100955B98 /* Settings */; }; 427C18282BD31E2E00955B98 /* GeneralPane.swift in Sources */ = {isa = PBXBuildFile; fileRef = 427C18242BD31E2E00955B98 /* GeneralPane.swift */; }; 427C18292BD31E2E00955B98 /* MainWindow.swift in Sources */ = {isa = PBXBuildFile; fileRef = 427C18252BD31E2E00955B98 /* MainWindow.swift */; }; @@ -41,6 +40,13 @@ 427C18502BD6652500955B98 /* Util.swift in Sources */ = {isa = PBXBuildFile; fileRef = 427C184F2BD6652500955B98 /* Util.swift */; }; 427C18542BD6E59300955B98 /* NSWindow+Animations.swift in Sources */ = {isa = PBXBuildFile; fileRef = 427C18532BD6E59300955B98 /* NSWindow+Animations.swift */; }; 4284834C2E813212009D7EEF /* KeyboardLayoutTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4284834B2E813212009D7EEF /* KeyboardLayoutTests.swift */; }; + 4284834E2E813214009D7EEF /* KeyboardCheatsheetView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4284834D2E813213009D7EEF /* KeyboardCheatsheetView.swift */; }; + 428483502E813216009D7EEF /* KeyboardLayoutModel.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4284834F2E813215009D7EEF /* KeyboardLayoutModel.swift */; }; + 428483522E813218009D7EEF /* KeyboardLayoutView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 428483512E813217009D7EEF /* KeyboardLayoutView.swift */; }; + 428483542E81321A009D7EEF /* KeyboardPane.swift in Sources */ = {isa = PBXBuildFile; fileRef = 428483532E813219009D7EEF /* KeyboardPane.swift */; }; + 428483562E81321C009D7EEF /* KeyView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 428483572E81321D009D7EEF /* KeyView.swift */; }; + 428483582E81321E009D7EEF /* KeyBadge.swift in Sources */ = {isa = PBXBuildFile; fileRef = 428483592E81321F009D7EEF /* KeyBadge.swift */; }; + 4284835A2E813220009D7EEF /* CheatsheetRows.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4284835B2E813221009D7EEF /* CheatsheetRows.swift */; }; 42B21FBC2D67566100F4A2C7 /* Alerts.swift in Sources */ = {isa = PBXBuildFile; fileRef = 42B21FBB2D67566100F4A2C7 /* Alerts.swift */; }; 42CCB5A32DAD257700356FC0 /* Kingfisher in Frameworks */ = {isa = PBXBuildFile; productRef = FBCA04D82D9F02F700271163 /* Kingfisher */; }; 42DFCD722D5B7D48002EA111 /* Events.swift in Sources */ = {isa = PBXBuildFile; fileRef = 42DFCD712D5B7D46002EA111 /* Events.swift */; }; @@ -55,6 +61,11 @@ 6D9B9C012DBA000000000001 /* ConfigOutlineEditorView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6D9B9C002DBA000000000001 /* ConfigOutlineEditorView.swift */; }; 6D9B9C042DBA000000000002 /* KeyCapture.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6D9B9C032DBA000000000002 /* KeyCapture.swift */; }; 6D9B9C062DBA000000000003 /* ConfigEditorShared.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6D9B9C052DBA000000000003 /* ConfigEditorShared.swift */; }; + CC0000012E9A000000000008 /* StatsManager.swift in Sources */ = {isa = PBXBuildFile; fileRef = CC0000012E9A000000000007 /* StatsManager.swift */; }; + CC0000012E9A00000000000A /* StatsPane.swift in Sources */ = {isa = PBXBuildFile; fileRef = CC0000012E9A000000000009 /* StatsPane.swift */; }; + 73192AF63CAF425397D7C0D1 /* URLSchemeHandler.swift in Sources */ = {isa = PBXBuildFile; fileRef = 73192AF63CAF425397D7C0D2 /* URLSchemeHandler.swift */; }; + EC5CEBC4C47B4C5DB2258813 /* URLSchemeTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = EC5CEBC4C47B4C5DB2258814 /* URLSchemeTests.swift */; }; + /* End PBXBuildFile section */ /* Begin PBXContainerItemProxy section */ @@ -68,6 +79,7 @@ /* End PBXContainerItemProxy section */ /* Begin PBXFileReference section */ + 0A27E0A12EF7616100731753 /* CustomIconRenderer.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CustomIconRenderer.swift; sourceTree = ""; }; 115AA5BE2DA521C200C17E18 /* ActionIcon.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ActionIcon.swift; sourceTree = ""; }; 130196C52D73B3DC0093148B /* Breadcrumbs.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Breadcrumbs.swift; sourceTree = ""; }; 423632142D678F4400878D92 /* TestPlan.xctestplan */ = {isa = PBXFileReference; lastKnownFileType = text; path = TestPlan.xctestplan; sourceTree = ""; }; @@ -76,7 +88,6 @@ 423632272D6A806700878D92 /* Theme.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Theme.swift; sourceTree = ""; }; 42454DDA2D71CB39004E1374 /* ConfigValidator.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ConfigValidator.swift; sourceTree = ""; }; 42454DDC2D71CBAB004E1374 /* ConfigValidatorTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ConfigValidatorTests.swift; sourceTree = ""; }; - EC5CEBC4C47B4C5DB2258814 /* URLSchemeTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = URLSchemeTests.swift; sourceTree = ""; }; 4254953F2D75EFAD0020300E /* ForTheHorde.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ForTheHorde.swift; sourceTree = ""; }; 426E625A2D2E6A98009FD2F2 /* CommandRunner.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CommandRunner.swift; sourceTree = ""; }; 4279AFEA2C6A08B100952A83 /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; name = Info.plist; path = "Leader Key/Support/Info.plist"; sourceTree = SOURCE_ROOT; }; @@ -88,7 +99,6 @@ 427C17FC2BD311B500955B98 /* UserConfigTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = UserConfigTests.swift; sourceTree = ""; }; 427C181B2BD314B500955B98 /* Constants.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Constants.swift; sourceTree = ""; }; 427C181F2BD31C3D00955B98 /* AppDelegate.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AppDelegate.swift; sourceTree = ""; }; - 73192AF63CAF425397D7C0D2 /* URLSchemeHandler.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = URLSchemeHandler.swift; sourceTree = ""; }; 427C18242BD31E2E00955B98 /* GeneralPane.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = GeneralPane.swift; sourceTree = ""; }; 427C18252BD31E2E00955B98 /* MainWindow.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = MainWindow.swift; sourceTree = ""; }; 427C18262BD31E2E00955B98 /* StatusItem.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = StatusItem.swift; sourceTree = ""; }; @@ -102,6 +112,13 @@ 427C184F2BD6652500955B98 /* Util.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Util.swift; sourceTree = ""; }; 427C18532BD6E59300955B98 /* NSWindow+Animations.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "NSWindow+Animations.swift"; sourceTree = ""; }; 4284834B2E813212009D7EEF /* KeyboardLayoutTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = KeyboardLayoutTests.swift; sourceTree = ""; }; + 4284834D2E813213009D7EEF /* KeyboardCheatsheetView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = KeyboardCheatsheetView.swift; sourceTree = ""; }; + 4284834F2E813215009D7EEF /* KeyboardLayoutModel.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = KeyboardLayoutModel.swift; sourceTree = ""; }; + 428483512E813217009D7EEF /* KeyboardLayoutView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = KeyboardLayoutView.swift; sourceTree = ""; }; + 428483532E813219009D7EEF /* KeyboardPane.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = KeyboardPane.swift; sourceTree = ""; }; + 428483572E81321D009D7EEF /* KeyView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = KeyView.swift; sourceTree = ""; }; + 428483592E81321F009D7EEF /* KeyBadge.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = KeyBadge.swift; sourceTree = ""; }; + 4284835B2E813221009D7EEF /* CheatsheetRows.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CheatsheetRows.swift; sourceTree = ""; }; 42B21FBB2D67566100F4A2C7 /* Alerts.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Alerts.swift; sourceTree = ""; }; 42DFCD712D5B7D46002EA111 /* Events.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Events.swift; sourceTree = ""; }; 42F4CDC82D458FF700D0DD76 /* MainMenu.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = MainMenu.swift; sourceTree = ""; }; @@ -114,6 +131,11 @@ 6D9B9C002DBA000000000001 /* ConfigOutlineEditorView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ConfigOutlineEditorView.swift; sourceTree = ""; }; 6D9B9C032DBA000000000002 /* KeyCapture.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = KeyCapture.swift; sourceTree = ""; }; 6D9B9C052DBA000000000003 /* ConfigEditorShared.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ConfigEditorShared.swift; sourceTree = ""; }; + CC0000012E9A000000000007 /* StatsManager.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = StatsManager.swift; sourceTree = ""; }; + CC0000012E9A000000000009 /* StatsPane.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = StatsPane.swift; sourceTree = ""; }; + 73192AF63CAF425397D7C0D2 /* URLSchemeHandler.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = URLSchemeHandler.swift; sourceTree = ""; }; + EC5CEBC4C47B4C5DB2258814 /* URLSchemeTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = URLSchemeTests.swift; sourceTree = ""; }; + /* End PBXFileReference section */ /* Begin PBXFrameworksBuildPhase section */ @@ -158,10 +180,40 @@ children = ( 427C18242BD31E2E00955B98 /* GeneralPane.swift */, 42FDC3192D51687B004F5C5C /* AdvancedPane.swift */, + 428483532E813219009D7EEF /* KeyboardPane.swift */, + CC0000012E9A000000000009 /* StatsPane.swift */, ); path = Settings; sourceTree = ""; }; + 428483552E81321B009D7EEF /* KeyboardLayout */ = { + isa = PBXGroup; + children = ( + 4284834D2E813213009D7EEF /* KeyboardCheatsheetView.swift */, + 4284834F2E813215009D7EEF /* KeyboardLayoutModel.swift */, + 428483512E813217009D7EEF /* KeyboardLayoutView.swift */, + 428483572E81321D009D7EEF /* KeyView.swift */, + ); + path = KeyboardLayout; + sourceTree = ""; + }; + 4284835C2E813222009D7EEF /* Cheatsheet */ = { + isa = PBXGroup; + children = ( + 428483592E81321F009D7EEF /* KeyBadge.swift */, + 4284835B2E813221009D7EEF /* CheatsheetRows.swift */, + ); + path = Cheatsheet; + sourceTree = ""; + }; + CC0000012E9A000000000004 /* Stats */ = { + isa = PBXGroup; + children = ( + CC0000012E9A000000000007 /* StatsManager.swift */, + ); + path = Stats; + sourceTree = ""; + }; 427C17DE2BD311B400955B98 = { isa = PBXGroup; children = ( @@ -205,7 +257,10 @@ 427C182E2BD3206200955B98 /* UserState.swift */, 427C184F2BD6652500955B98 /* Util.swift */, 427C17EE2BD311B500955B98 /* Assets.xcassets */, + 4284835C2E813222009D7EEF /* Cheatsheet */, + 428483552E81321B009D7EEF /* KeyboardLayout */, 423632242D68CC5D00878D92 /* Settings */, + CC0000012E9A000000000004 /* Stats */, 427C18362BD3243C00955B98 /* Support */, 423632232D68CB0F00878D92 /* Themes */, 427C18392BD3268000955B98 /* Views */, @@ -247,6 +302,7 @@ 427C18392BD3268000955B98 /* Views */ = { isa = PBXGroup; children = ( + 0A27E0A12EF7616100731753 /* CustomIconRenderer.swift */, 605385A22D523CAD00BEDB4B /* Pulsate.swift */, 6D9B9C002DBA000000000001 /* ConfigOutlineEditorView.swift */, 427C18372BD3262100955B98 /* VisualEffectBackground.swift */, @@ -414,6 +470,7 @@ 605385A32D523CAD00BEDB4B /* Pulsate.swift in Sources */, 42F4CDC92D458FF700D0DD76 /* MainMenu.swift in Sources */, 42454DDB2D71CB39004E1374 /* ConfigValidator.swift in Sources */, + 0A27E0A22EF7616100731753 /* CustomIconRenderer.swift in Sources */, 427C184D2BD65C5C00955B98 /* Defaults.swift in Sources */, 427C18292BD31E2E00955B98 /* MainWindow.swift in Sources */, 42FDC31A2D51687B004F5C5C /* AdvancedPane.swift in Sources */, @@ -443,6 +500,15 @@ 42F4CDCD2D45B13600D0DD76 /* KeyButton.swift in Sources */, 606C56EF2DAB875A00198B9F /* Cheater.swift in Sources */, 427C181C2BD314B500955B98 /* Constants.swift in Sources */, + 4284834E2E813214009D7EEF /* KeyboardCheatsheetView.swift in Sources */, + 428483502E813216009D7EEF /* KeyboardLayoutModel.swift in Sources */, + 428483522E813218009D7EEF /* KeyboardLayoutView.swift in Sources */, + 428483542E81321A009D7EEF /* KeyboardPane.swift in Sources */, + 428483562E81321C009D7EEF /* KeyView.swift in Sources */, + 428483582E81321E009D7EEF /* KeyBadge.swift in Sources */, + 4284835A2E813220009D7EEF /* CheatsheetRows.swift in Sources */, + CC0000012E9A000000000008 /* StatsManager.swift in Sources */, + CC0000012E9A00000000000A /* StatsPane.swift in Sources */, ); runOnlyForDeploymentPostprocessing = 0; }; diff --git a/Leader Key.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolved b/Leader Key.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolved index b9760019..19f91d27 100644 --- a/Leader Key.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolved +++ b/Leader Key.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolved @@ -1,5 +1,5 @@ { - "originHash" : "da47d6e5ab6b8a19e07061424069e09f3c36abd019782617be344b153679c7b4", + "originHash" : "27cd159b3de48393390ccc7adbcd2855f25c1f1b5d8088fa165248f7c52f23e1", "pins" : [ { "identity" : "defaults", diff --git a/Leader Key/AppDelegate.swift b/Leader Key/AppDelegate.swift index 36411839..13518e2f 100644 --- a/Leader Key/AppDelegate.swift +++ b/Leader Key/AppDelegate.swift @@ -35,6 +35,20 @@ class AppDelegate: NSObject, NSApplicationDelegate, contentView: { AdvancedPane().environmentObject(self.config) }), + Settings.Pane( + identifier: .keyboard, title: "Keyboard", + toolbarIcon: NSImage( + systemSymbolName: "keyboard", accessibilityDescription: "Keyboard")!, + contentView: { + KeyboardPane().environmentObject(self.config) + }), + Settings.Pane( + identifier: .stats, title: "Stats", + toolbarIcon: NSImage( + systemSymbolName: "chart.bar.fill", accessibilityDescription: "Stats")!, + contentView: { + StatsPane().environmentObject(self.config) + }), ], style: .segmentedControl, ) @@ -271,6 +285,9 @@ class AppDelegate: NSObject, NSApplicationDelegate, private func showSettings() { // Behave like a normal app while Settings is open NSApp.setActivationPolicy(.regular) + // The segmented control already names each pane; without this the toolbar + // repeats every title as a label underneath it. + settingsWindowController.window?.toolbar?.displayMode = .iconOnly settingsWindowController.show() NSApp.activate(ignoringOtherApps: true) settingsWindowController.window?.delegate = self diff --git a/Leader Key/Cheatsheet.swift b/Leader Key/Cheatsheet.swift index 1dc54bda..9205c5d3 100644 --- a/Leader Key/Cheatsheet.swift +++ b/Leader Key/Cheatsheet.swift @@ -3,195 +3,116 @@ import Kingfisher import SwiftUI enum Cheatsheet { - private static let iconSize = NSSize(width: 24, height: 24) + static func createWindow(for userState: UserState) -> NSWindow { + let view = CheatsheetView() + .environmentObject(userState) + .environmentObject(userState.userConfig as UserConfig) + let controller = NSHostingController(rootView: view) + controller.sizingOptions = .preferredContentSize + let cheatsheet = PanelWindow( + contentRect: NSRect(x: 0, y: 0, width: 700, height: 640) + ) + cheatsheet.contentViewController = controller + return cheatsheet + } +} - struct KeyBadge: SwiftUI.View { - let key: String +struct CheatsheetView: SwiftUI.View { + @EnvironmentObject var userState: UserState + @Default(.cheatsheetStyle) var cheatsheetStyle + @State private var contentHeight: CGFloat = 0 - var body: some SwiftUI.View { - Text(KeyMaps.glyph(for: key) ?? key) - .font(.system(.body, design: .rounded)) - .multilineTextAlignment(.center) - .fontWeight(.bold) - .padding(.vertical, 4) - .frame(width: 24) - .background(.white.opacity(0.1)) - .clipShape(RoundedRectangle(cornerRadius: 5.0, style: .continuous)) + var maxHeight: CGFloat { + if let screen = NSScreen.main { + return screen.visibleFrame.height - 40 } + return 640 } - struct ActionRow: SwiftUI.View { - let action: Action - let indent: Int - @Default(.showDetailsInCheatsheet) var showDetails - @Default(.showAppIconsInCheatsheet) var showIcons - - var body: some SwiftUI.View { - HStack { - HStack { - ForEach(0.. screenHalf ? screenHalf - margin : desiredWidth } + return 700 } - struct GroupRow: SwiftUI.View { - @Default(.expandGroupsInCheatsheet) var expand - @Default(.showDetailsInCheatsheet) var showDetails - @Default(.showAppIconsInCheatsheet) var showIcons + var actions: [ActionOrGroup] { + (userState.currentGroup != nil) + ? userState.currentGroup!.actions : userState.userConfig.root.actions + } - let group: Group - let indent: Int + var body: some SwiftUI.View { + switch cheatsheetStyle { + case .list: + listView + case .keyboard: + KeyboardCheatsheetView() + .fixedSize() + .clipShape(RoundedRectangle(cornerRadius: 12, style: .continuous)) + } + } - var body: some SwiftUI.View { + var listView: some View { + ScrollView { VStack(alignment: .leading, spacing: 4) { - HStack { - ForEach(0.. screenHalf ? screenHalf - margin : desiredWidth - } - return 580 - } - - var actions: [ActionOrGroup] { - (userState.currentGroup != nil) - ? userState.currentGroup!.actions : userState.userConfig.root.actions - } - - var body: some SwiftUI.View { - ScrollView { - SwiftUI.VStack(alignment: .leading, spacing: 4) { - if let group = userState.currentGroup { - HStack { - KeyBadge(key: group.key ?? "•") - Text(group.key == nil ? "Leader Key" : group.displayName) - .foregroundStyle(.secondary) - } + .padding(.bottom, 8) + Divider() .padding(.bottom, 8) - Divider() - .padding(.bottom, 8) - } + } - ForEach(Array(actions.enumerated()), id: \.offset) { _, item in - switch item { - case .action(let action): - Cheatsheet.ActionRow(action: action, indent: 0) - case .group(let group): - Cheatsheet.GroupRow(group: group, indent: 0) - } + ForEach(Array(actions.enumerated()), id: \.offset) { _, item in + switch item { + case .action(let action): + ActionRow(action: action, indent: 0) + case .group(let group): + GroupRow(group: group, indent: 0) } } - .padding() - .overlay( - GeometryReader { geo in - Color.clear.preference( - key: HeightPreferenceKey.self, - value: geo.size.height - ) - } - ) } - .frame(width: Cheatsheet.CheatsheetView.preferredWidth) - .frame(height: min(contentHeight, maxHeight)) - .background( - VisualEffectView(material: .hudWindow, blendingMode: .behindWindow) + .padding() + .overlay( + GeometryReader { geo in + Color.clear.preference( + key: HeightPreferenceKey.self, + value: geo.size.height + ) + } ) - .onPreferenceChange(HeightPreferenceKey.self) { height in - self.contentHeight = height - } } - } - - struct HeightPreferenceKey: PreferenceKey { - static var defaultValue: CGFloat = 0 - static func reduce(value: inout CGFloat, nextValue: () -> CGFloat) { - value = nextValue() + .frame(width: CheatsheetView.preferredWidth) + .frame(height: min(contentHeight, maxHeight)) + .background( + ZStack { + VisualEffectView(material: .popover, blendingMode: .behindWindow) + Color(NSColor.windowBackgroundColor).opacity(0.7) + } + ) + .onPreferenceChange(HeightPreferenceKey.self) { height in + self.contentHeight = height } } +} - static func createWindow(for userState: UserState) -> NSWindow { - let view = CheatsheetView().environmentObject(userState) - let controller = NSHostingController(rootView: view) - let cheatsheet = PanelWindow( - contentRect: NSRect(x: 0, y: 0, width: 580, height: 640) - ) - cheatsheet.contentViewController = controller - return cheatsheet +struct HeightPreferenceKey: PreferenceKey { + static var defaultValue: CGFloat = 0 + static func reduce(value: inout CGFloat, nextValue: () -> CGFloat) { + value = nextValue() } } struct CheatsheetView_Previews: PreviewProvider { static var previews: some View { - Cheatsheet.CheatsheetView() + CheatsheetView() .environmentObject(UserState(userConfig: UserConfig())) } -} +} \ No newline at end of file diff --git a/Leader Key/Cheatsheet/CheatsheetRows.swift b/Leader Key/Cheatsheet/CheatsheetRows.swift new file mode 100644 index 00000000..59e9237d --- /dev/null +++ b/Leader Key/Cheatsheet/CheatsheetRows.swift @@ -0,0 +1,84 @@ +import SwiftUI +import Defaults + +private let iconSize = NSSize(width: 24, height: 24) + +struct ActionRow: View { + let action: Action + let indent: Int + @Default(.showDetailsInCheatsheet) var showDetails + @Default(.showAppIconsInCheatsheet) var showIcons + + var body: some View { + HStack { + HStack { + ForEach(0..() @@ -39,6 +41,7 @@ class Controller { Events.sink { event in switch event { case .didReload: + IconCache.removeAll() // This should all be handled by the themes self.userState.isShowingRefreshState = true self.show() @@ -56,6 +59,7 @@ class Controller { func show() { Events.send(.willActivate) + startModifierMonitoring() let screen = Defaults[.screen].getNSScreen() ?? NSScreen() window.show(on: screen) { @@ -68,7 +72,7 @@ class Controller { switch Defaults[.autoOpenCheatsheet] { case .always: - showCheatsheet() + showCheatsheet(centered: Defaults[.cheatsheetStyle] == .keyboard) case .delay: scheduleCheatsheet() default: break @@ -77,6 +81,11 @@ class Controller { func hide(afterClose: (() -> Void)? = nil) { Events.send(.willDeactivate) + stopModifierMonitoring() + + // Reset centered mode state + window.alphaValue = 1 + isCheatsheetCentered = false window.hide { self.clear() @@ -89,8 +98,8 @@ class Controller { } func keyDown(with event: NSEvent) { - // Reset the delay timer - if Defaults[.autoOpenCheatsheet] == .delay { + // Reset the delay timer only if not already in centered mode + if Defaults[.autoOpenCheatsheet] == .delay && !isCheatsheetCentered { scheduleCheatsheet() } @@ -116,20 +125,30 @@ class Controller { switch event.keyCode { case KeyHelpers.backspace.rawValue: clear() - delay(1) { - self.positionCheatsheetWindow() + if !isCheatsheetCentered { + delay(1) { + self.positionCheatsheetWindow() + } } case KeyHelpers.escape.rawValue: - window.resignKey() + // If in a subgroup, go back one level; otherwise close + if !userState.navigateBack() { + window.resignKey() + } default: guard let char = charForEvent(event) else { return } handleKey(char, withModifiers: event.modifierFlags) } } - func handleKey(_ key: String, withModifiers modifiers: NSEvent.ModifierFlags? = nil, execute: Bool = true) { + func handleKey( + _ key: String, + withModifiers modifiers: NSEvent.ModifierFlags? = nil, + execute: Bool = true + ) { if key == "?" { - showCheatsheet() + let centered = Defaults[.cheatsheetStyle] == .keyboard + showCheatsheet(centered: centered) return } @@ -160,31 +179,46 @@ class Controller { switch hit { case .action(let action): if execute { + // Capture keyPath BEFORE hiding (which clears navigation state) + let keyPath = statsKeyPath(leafKey: action.key) + if let mods = modifiers, isInStickyMode(mods) { - runAction(action) + runAction(action, keyPath: keyPath) } else { hide { - self.runAction(action) + self.runAction(action, keyPath: keyPath) } } } - // If execute is false, just stay visible showing the matched action case .group(let group): if execute, let mods = modifiers, shouldRunGroupSequenceWithModifiers(mods) { + // Capture keyPath BEFORE hiding + let parentPath = statsKeyPath(leafKey: nil) hide { - self.runGroup(group) + self.runGroup(group, parentPath: parentPath) } } else { - userState.display = group.key + // Record group navigation for stats + if let keyPath = statsKeyPath(leafKey: group.key) { + StatsManager.shared.recordGroupNavigation(group: group, keyPath: keyPath) + } + + // Only update display hint when not in centered cheatsheet mode + // (the keyboard cheatsheet already shows navigation via breadcrumbs) + if !isCheatsheetCentered { + userState.display = group.key + } userState.navigateToGroup(group) } case .none: window.notFound() } - // Why do we need to wait here? - delay(1) { - self.positionCheatsheetWindow() + // Reposition cheatsheet only if not in centered mode + if !isCheatsheetCentered { + delay(1) { + self.positionCheatsheetWindow() + } } } @@ -192,7 +226,9 @@ class Controller { return shouldRunGroupSequenceWithModifiers(event.modifierFlags) } - private func shouldRunGroupSequenceWithModifiers(_ modifierFlags: NSEvent.ModifierFlags) -> Bool { + private func shouldRunGroupSequenceWithModifiers( + _ modifierFlags: NSEvent.ModifierFlags + ) -> Bool { let config = Defaults[.modifierKeyConfiguration] switch config { @@ -226,7 +262,8 @@ class Controller { // 2. For special keys like Enter, always use the mapped glyph if let entry = KeyMaps.entry(for: event.keyCode) { // For Enter, Space, Tab, arrows, etc. - use the glyph representation - if event.keyCode == KeyHelpers.enter.rawValue || event.keyCode == KeyHelpers.space.rawValue + if event.keyCode == KeyHelpers.enter.rawValue + || event.keyCode == KeyHelpers.space.rawValue || event.keyCode == KeyHelpers.tab.rawValue || event.keyCode == KeyHelpers.leftArrow.rawValue || event.keyCode == KeyHelpers.rightArrow.rawValue @@ -270,12 +307,88 @@ class Controller { mainWindow.cheatsheetOrigin(cheatsheetSize: cheatsheet.frame.size)) } - private func showCheatsheet() { + private func centerCheatsheetWindow() { + guard let cheatsheet = cheatsheetWindow, + let screen = cheatsheetDisplayScreen() + else { + return + } + + let screenCenter = screen.center() + let cheatsheetFrame = cheatsheet.frame + + // Match the vertical offset used by themes (slightly above center) + // Most themes use: center.y + windowSize / 8 + let verticalOffset: CGFloat = cheatsheetFrame.height / 8 + + let x = screenCenter.x - cheatsheetFrame.width / 2 + let y = screenCenter.y - cheatsheetFrame.height / 2 + verticalOffset + + cheatsheet.setFrameOrigin(NSPoint(x: x, y: y)) + } + + private func cheatsheetDisplayScreen() -> NSScreen? { + return window?.screen + ?? Defaults[.screen].getNSScreen() + ?? NSScreen.main + } + + private func sizeCheatsheetWindowToFitContent() { + guard let cheatsheet = cheatsheetWindow, + let contentView = cheatsheet.contentView + else { + return + } + + contentView.layoutSubtreeIfNeeded() + + let fittingSize = contentView.fittingSize + guard fittingSize.width > 0, fittingSize.height > 0 else { + return + } + + cheatsheet.setContentSize(fittingSize) + } + + private func showCheatsheet(centered: Bool = false) { if !window.hasCheatsheet { return } - positionCheatsheetWindow() - cheatsheetWindow?.orderFront(nil) + + if centered { + // Hide the main window visually but keep it as key window for input + window.alphaValue = 0 + isCheatsheetCentered = true + sizeCheatsheetWindowToFitContent() + centerCheatsheetWindow() + cheatsheetWindow?.orderFront(nil) + + // Re-center after SwiftUI has finished laying out + DispatchQueue.main.async { [weak self] in + self?.sizeCheatsheetWindowToFitContent() + self?.centerCheatsheetWindow() + + // Final centering pass to ensure accuracy + DispatchQueue.main.asyncAfter(deadline: .now() + 0.05) { [weak self] in + self?.sizeCheatsheetWindowToFitContent() + self?.centerCheatsheetWindow() + } + } + } else { + cheatsheetWindow?.setContentSize( + NSSize(width: CheatsheetView.preferredWidth, height: 640) + ) + positionCheatsheetWindow() + cheatsheetWindow?.orderFront(nil) + } + } + + private func exitCenteredMode() { + if isCheatsheetCentered { + window.alphaValue = 1 + isCheatsheetCentered = false + cheatsheetWindow?.orderOut(nil) + } } private func scheduleCheatsheet() { @@ -284,24 +397,53 @@ class Controller { cheatsheetTimer = Timer.scheduledTimer( withTimeInterval: Double(Defaults[.cheatsheetDelayMS]) / 1000.0, repeats: false ) { [weak self] _ in - self?.showCheatsheet() + // Show centered cheatsheet when using keyboard style, regular position for list + let centered = Defaults[.cheatsheetStyle] == .keyboard + self?.showCheatsheet(centered: centered) } } - private func runGroup(_ group: Group) { - for groupOrAction in group.actions { - switch groupOrAction { - case .group(let group): - runGroup(group) + private func runGroup(_ group: Group, parentPath: String? = nil) { + let currentPath: String + if let parent = parentPath, let groupKey = group.key { + currentPath = parent + "/" + groupKey + } else if let groupKey = group.key { + currentPath = groupKey + } else { + currentPath = "" + } + + for groupOrAction in group.actions { + switch groupOrAction { + case .group(let subGroup): + runGroup(subGroup, parentPath: currentPath) case .action(let action): - runAction(action) + let actionPath: String? + if !currentPath.isEmpty, let actionKey = action.key { + actionPath = currentPath + "/" + actionKey + } else if let actionKey = action.key { + actionPath = actionKey + } else { + actionPath = nil + } + runAction(action, keyPath: actionPath) } - } - } - - private func runAction(_ action: Action) { - switch action.type { - case .application: + } + } + + private func statsKeyPath(leafKey: String?) -> String? { + guard let leafKey, !leafKey.isEmpty else { return nil } + let components = userState.navigationPath.compactMap(\.key).filter { !$0.isEmpty } + [leafKey] + return components.joined(separator: "/") + } + + private func runAction(_ action: Action, keyPath: String?) { + if let keyPath = keyPath { + StatsManager.shared.recordExecution(action: action, keyPath: keyPath) + } + + switch action.type { + case .application: NSWorkspace.shared.openApplication( at: URL(fileURLWithPath: action.value), configuration: NSWorkspace.OpenConfiguration()) @@ -360,6 +502,23 @@ class Controller { alert.addButton(withTitle: "OK") alert.runModal() } + + private func startModifierMonitoring() { + modifierMonitor = NSEvent.addLocalMonitorForEvents( + matching: .flagsChanged + ) { [weak self] event in + self?.userState.shiftHeld = event.modifierFlags.contains(.shift) + return event + } + } + + private func stopModifierMonitoring() { + if let monitor = modifierMonitor { + NSEvent.removeMonitor(monitor) + modifierMonitor = nil + } + userState.shiftHeld = false + } } class DontActivateConfiguration { diff --git a/Leader Key/Defaults.swift b/Leader Key/Defaults.swift index 66703047..a079337a 100644 --- a/Leader Key/Defaults.swift +++ b/Leader Key/Defaults.swift @@ -31,6 +31,8 @@ extension Defaults.Keys { "showDetailsInCheatsheet", default: true, suite: defaultsSuite) static let showFaviconsInCheatsheet = Key( "showFaviconsInCheatsheet", default: true, suite: defaultsSuite) + static let cheatsheetStyle = Key( + "cheatsheetStyle", default: .list, suite: defaultsSuite) static let reactivateBehavior = Key( "reactivateBehavior", default: .hide, suite: defaultsSuite) static let screen = Key( @@ -74,3 +76,8 @@ enum Screen: String, Defaults.Serializable { case mouse case activeWindow } + +enum CheatsheetStyle: String, Defaults.Serializable { + case list + case keyboard +} diff --git a/Leader Key/KeyboardLayout/KeyView.swift b/Leader Key/KeyboardLayout/KeyView.swift new file mode 100644 index 00000000..7cf15535 --- /dev/null +++ b/Leader Key/KeyboardLayout/KeyView.swift @@ -0,0 +1,291 @@ +import AppKit +import SwiftUI +import UniformTypeIdentifiers + +struct KeyView: View { + let keyDef: KeyDefinition + let binding: ActionOrGroup? + let shiftHeld: Bool + var scale: CGFloat = 1.0 + var showLabels: Bool = false + var onSelect: (() -> Void)? = nil + /// Called when a drag of this key's binding starts. Non-nil makes the key draggable. + var onDragStart: (() -> Void)? = nil + /// Accepts or rejects a binding dragged onto this key. Non-nil makes the key a drop target. + var dropDelegate: KeyDropDelegate? = nil + /// Shown when the key is right-clicked. Empty means no menu. + var menuItems: [KeyMenuItem] = [] + + @State private var isHovered = false + @State private var isCursorPushed = false + @State private var isDropTargeted = false + + private var iconSize: NSSize { + NSSize(width: 20 * scale, height: 20 * scale) + } + + var body: some View { + let width = KeyboardLayout.keyWidth(for: keyDef, scale: scale) + let height = KeyboardLayout.scaledKeySize(scale) + let cornerRadius = 6 * scale + + ZStack { + // Key background + RoundedRectangle(cornerRadius: cornerRadius, style: .continuous) + .fill(keyBackground) + .shadow(color: .black.opacity(0.1), radius: 2 * scale, x: 0, y: 1 * scale) + + // Content + ZStack { + // Key label at top-left + VStack { + HStack { + Text(displayLabel) + .font(.system(size: 10 * scale, weight: .medium)) + .foregroundColor(keyDef.isModifier ? .secondary : .primary) + .opacity(keyDef.isModifier ? 0.3 : 0.6) + .padding(.leading, 4 * scale) + .padding(.top, 4 * scale) + Spacer() + } + Spacer() + } + + // Binding icon (centered) + if let binding = binding { + VStack { + actionIcon(item: binding, iconSize: iconSize, loadFavicons: true) + } + .offset(y: showLabels ? -4 * scale : 0) + .overlay { + if isHovered, !showLabels, let label = bindingLabel { + Text(label) + .font(.system(size: 9 * scale)) + .lineLimit(1) + .truncationMode(.middle) + .foregroundColor(.primary) + .padding(.horizontal, 2 * scale) + .background(Color(nsColor: .windowBackgroundColor).opacity(0.9)) + .cornerRadius(4 * scale) + .fixedSize() + .offset(y: (iconSize.height / 2) + (5 * scale)) + } + } + } + + // Always-visible binding name along the bottom + if showLabels, let label = bindingLabel { + VStack { + Spacer() + Text(label) + .font(.system(size: 7 * scale)) + .lineLimit(1) + .truncationMode(.tail) + .foregroundColor(.primary) + .opacity(0.8) + .padding(.leading, 3 * scale) + .padding(.trailing, (isGroup ? 12 : 3) * scale) + .padding(.bottom, 2 * scale) + } + } + + // Group indicator at bottom-right + if case .group = binding { + VStack { + Spacer() + HStack { + Spacer() + Image(systemName: "chevron.right") + .font(.system(size: 8 * scale)) + .foregroundColor(.secondary) + .padding(.trailing, 4 * scale) + .padding(.bottom, 4 * scale) + } + } + } + } + + // Hover overlay + if isHovered && !keyDef.isModifier && onSelect != nil { + RoundedRectangle(cornerRadius: cornerRadius, style: .continuous) + .fill(Color.accentColor.opacity(0.2)) + } + + // Drop target outline + if isDropTargeted { + RoundedRectangle(cornerRadius: cornerRadius, style: .continuous) + .strokeBorder(Color.accentColor, lineWidth: 2 * scale) + } + } + .frame(width: width, height: height) + .contentShape(Rectangle()) + .onHover { hovering in + isHovered = hovering + + let shouldUsePointingHand = hovering && (!keyDef.isModifier || isShiftKey) && onSelect != nil + if shouldUsePointingHand { + if !isCursorPushed { + NSCursor.pointingHand.push() + isCursorPushed = true + } + } else if isCursorPushed { + NSCursor.pop() + isCursorPushed = false + } + } + .onDisappear { + if isCursorPushed { + NSCursor.pop() + isCursorPushed = false + } + } + .onTapGesture { + if !keyDef.isModifier || isShiftKey { + onSelect?() + } + } + .modifier( + KeyDragDrop( + onDragStart: binding == nil ? nil : onDragStart, + dropDelegate: dropDelegate, + isDropTargeted: $isDropTargeted + ) { + if let binding = binding { + actionIcon(item: binding, iconSize: iconSize, loadFavicons: true) + } + } + ) + .contextMenu { + ForEach(menuItems) { item in + Button(role: item.isDestructive ? .destructive : nil, action: item.action) { + Label(item.title, systemImage: item.systemImage) + } + } + } + .zIndex(isHovered ? 1 : 0) + } + + private var displayLabel: String { + if shiftHeld && !keyDef.isModifier { + let shiftedKey = KeyboardLayout.bindingKey(for: keyDef, shifted: true) + return KeyMaps.glyph(for: shiftedKey) ?? shiftedKey.uppercased() + } + + let displayKey: String + if keyDef.key.hasSuffix("_r") { + displayKey = String(keyDef.key.dropLast(2)) + } else { + displayKey = KeyboardLayout.bindingKey(for: keyDef, shifted: false) + } + + return KeyMaps.glyph(for: displayKey) ?? keyDef.label + } + + private var isGroup: Bool { + if case .group = binding { return true } + return false + } + + private var isShiftKey: Bool { + keyDef.key == "shift" || keyDef.key == "shift_r" + } + + private var keyBackground: Color { + if isShiftKey { + return shiftHeld ? Color.accentColor.opacity(0.4) : Color.gray.opacity(0.1) + } else if keyDef.isModifier { + return Color.gray.opacity(0.05) + } else if binding != nil { + return Color.accentColor.opacity(0.15) + } else { + return Color.gray.opacity(0.1) + } + } + + private var bindingLabel: String? { + switch binding { + case .action(let action): + return action.displayName + case .group(let group): + return group.displayName + case .none: + return nil + } + } +} + +/// One entry in the menu shown when a key is right-clicked. +struct KeyMenuItem: Identifiable { + let title: String + let systemImage: String + var isDestructive: Bool = false + let action: () -> Void + + var id: String { title } +} + +/// Decides what happens when a dragged binding is dropped on a key. +struct KeyDropDelegate { + /// Whether a drag that this keyboard started is in progress and may land here. + let canDrop: () -> Bool + let onDrop: () -> Void +} + +private struct KeyDragDrop: ViewModifier { + let onDragStart: (() -> Void)? + let dropDelegate: KeyDropDelegate? + @Binding var isDropTargeted: Bool + @ViewBuilder let preview: () -> Preview + + func body(content: Content) -> some View { + draggable(content) + .onDrop( + of: dropDelegate == nil ? [] : [KeyDragDrop.payloadType], + delegate: Delegate(dropDelegate: dropDelegate, isDropTargeted: $isDropTargeted) + ) + } + + @ViewBuilder + private func draggable(_ content: Content) -> some View { + if let onDragStart = onDragStart { + content.onDrag { + onDragStart() + return NSItemProvider(object: "" as NSString) + } preview: { + preview() + } + } else { + content + } + } + + private static var payloadType: UTType { .plainText } + + private struct Delegate: DropDelegate { + let dropDelegate: KeyDropDelegate? + @Binding var isDropTargeted: Bool + + func validateDrop(info: DropInfo) -> Bool { + dropDelegate?.canDrop() ?? false + } + + func dropEntered(info: DropInfo) { + isDropTargeted = true + } + + func dropExited(info: DropInfo) { + isDropTargeted = false + } + + func dropUpdated(info: DropInfo) -> DropProposal? { + DropProposal(operation: .move) + } + + func performDrop(info: DropInfo) -> Bool { + isDropTargeted = false + guard let dropDelegate = dropDelegate, dropDelegate.canDrop() else { return false } + dropDelegate.onDrop() + return true + } + } +} diff --git a/Leader Key/KeyboardLayout/KeyboardCheatsheetView.swift b/Leader Key/KeyboardLayout/KeyboardCheatsheetView.swift new file mode 100644 index 00000000..82674a3c --- /dev/null +++ b/Leader Key/KeyboardLayout/KeyboardCheatsheetView.swift @@ -0,0 +1,90 @@ +import SwiftUI + +struct KeyboardCheatsheetView: View { + @EnvironmentObject var userState: UserState + // Observed so edits made while the cheatsheet is hidden are drawn on the next open + @EnvironmentObject var userConfig: UserConfig + + // The keyboard cheatsheet is only ever shown centered. Keeping the scale fixed + // means opening it reuses the existing layout instead of rebuilding every key. + private let scale: CGFloat = KeyboardLayout.centeredScale + + var bindings: [String: ActionOrGroup] { + var result: [String: ActionOrGroup] = [:] + + let actions = + (userState.currentGroup != nil) + ? userState.currentGroup!.actions + : userConfig.root.actions + + for item in actions { + switch item { + case .action(let action): + if let key = action.key { + result[KeyMaps.text(for: key) ?? key] = item + } + case .group(let group): + if let key = group.key { + result[KeyMaps.text(for: key) ?? key] = item + } + } + } + + return result + } + + var body: some View { + VStack(alignment: .leading, spacing: 8 * scale) { + // Breadcrumbs navigation + HStack(spacing: 4 * scale) { + if !userState.navigationPath.isEmpty { + ScrollView(.horizontal, showsIndicators: false) { + HStack(spacing: 4 * scale) { + // Path breadcrumbs + ForEach(0.. 0 { + Text(">") + .foregroundColor(.secondary) + .font(.system(size: 12 * scale)) + } + + let group = userState.navigationPath[index] + let isLast = index == userState.navigationPath.count - 1 + + Text(group.displayName) + .font(.system(size: 12 * scale, weight: isLast ? .bold : .regular)) + } + } + } + } + Spacer() + } + .frame(height: 28 * scale) + + // Keyboard layout + KeyboardLayoutView( + bindings: bindings, + shiftHeld: userState.shiftHeld, + scale: scale, + showLabels: true + ) + } + .padding(16 * scale) + .background( + ZStack { + VisualEffectView(material: .popover, blendingMode: .behindWindow) + Color(NSColor.windowBackgroundColor).opacity(0.7) + } + ) + } +} + +#Preview { + let config = UserConfig() + let state = UserState(userConfig: config) + + return KeyboardCheatsheetView() + .environmentObject(state) + .environmentObject(config) + .frame(width: 700, height: 350) +} diff --git a/Leader Key/KeyboardLayout/KeyboardLayoutModel.swift b/Leader Key/KeyboardLayout/KeyboardLayoutModel.swift new file mode 100644 index 00000000..454036a6 --- /dev/null +++ b/Leader Key/KeyboardLayout/KeyboardLayoutModel.swift @@ -0,0 +1,273 @@ +import Carbon.HIToolbox +import Defaults +import Foundation + +/// Defines a single key on the keyboard +struct KeyDefinition: Identifiable { + let id = UUID() + let label: String // Display label ("Q", "Tab", "Space") + let key: String // US QWERTY config key for binding lookup ("q", "tab", "space") + let keyCode: UInt16 // Virtual key code of the physical key + let width: CGFloat // Key width multiplier (1.0 = standard key) + let isModifier: Bool // Whether this is a non-bindable modifier key + + init(label: String, key: String, keyCode: Int, width: CGFloat = 1.0, isModifier: Bool = false) { + self.label = label + self.key = key + self.keyCode = UInt16(keyCode) + self.width = width + self.isModifier = isModifier + } + + /// Keys whose character depends on the input source. Tab, enter, space and + /// the modifiers all have multi-character static keys. + var isCharacterKey: Bool { + !isModifier && key.count == 1 + } +} + +/// QWERTY keyboard layout definition +enum KeyboardLayout { + static let keySize: CGFloat = 40 + static let keySpacing: CGFloat = 4 + static let rowSpacing: CGFloat = 4 + + /// Scale factor for centered cheatsheet mode (larger display) + static let centeredScale: CGFloat = 1.4 + + /// Get scaled key size + static func scaledKeySize(_ scale: CGFloat) -> CGFloat { + keySize * scale + } + + /// Get scaled key spacing + static func scaledKeySpacing(_ scale: CGFloat) -> CGFloat { + keySpacing * scale + } + + /// Get scaled row spacing + static func scaledRowSpacing(_ scale: CGFloat) -> CGFloat { + rowSpacing * scale + } + + /// Maps keys to their shifted versions for display and binding lookup + static let shiftedKeys: [String: String] = [ + "`": "~", + "1": "!", + "2": "@", + "3": "#", + "4": "$", + "5": "%", + "6": "^", + "7": "&", + "8": "*", + "9": "(", + "0": ")", + "-": "_", + "=": "+", + "[": "{", + "]": "}", + "\\": "|", + ";": ":", + "'": "\"", + ",": "<", + ".": ">", + "/": "?", + ] + + /// Get the shifted version of a key (for both display and binding lookup) + static func shiftedKey(for key: String) -> String { + // Letters just uppercase + if key.count == 1, let char = key.first, char.isLetter { + return key.uppercased() + } + // Special characters use the mapping + return shiftedKeys[key] ?? key + } + + /// The key string the controller produces for a physical key, and so the key + /// its binding is stored under. Mirrors `Controller.charForEvent`: character + /// keys follow the active input source unless `forceEnglishKeyboardLayout` is + /// on; everything else, and any failed translation, uses the static key. + /// `inputSource` defaults to the active keyboard layout. + static func bindingKey( + for keyDef: KeyDefinition, shifted: Bool, inputSource: TISInputSource? = nil + ) -> String { + let staticKey = shifted ? shiftedKey(for: keyDef.key) : keyDef.key + + guard keyDef.isCharacterKey, !Defaults[.forceEnglishKeyboardLayout], + let translated = translatedCharacter( + keyCode: keyDef.keyCode, shifted: shifted, inputSource: inputSource) + else { + return staticKey + } + + if translated.unicodeScalars.first?.isASCII ?? false { + return translated + } + + // The controller only accepts ASCII from the input source. Otherwise it + // uses the KeyMaps glyph (letters and digits), or the character itself. + guard let entry = KeyMaps.entry(for: keyDef.keyCode) else { + return translated + } + if entry.glyph.first?.isLetter == true && !entry.isReserved { + return shifted ? entry.glyph.uppercased() : entry.glyph + } + return entry.glyph + } + + /// `bindingKey` for a key identified by its static key ("q", "shift_r") + static func bindingKey(forStaticKey key: String, shifted: Bool) -> String { + for row in rows { + if let keyDef = row.first(where: { $0.key == key }) { + return bindingKey(for: keyDef, shifted: shifted) + } + } + return shifted ? shiftedKey(for: key) : key + } + + /// What a keyboard layout types for a key code, or nil if it can't be + /// translated or isn't printable. Dead keys yield their own character, as + /// `NSEvent.charactersIgnoringModifiers` does. + private static func translatedCharacter( + keyCode: UInt16, shifted: Bool, inputSource: TISInputSource? + ) -> String? { + guard + let source = inputSource ?? TISCopyCurrentKeyboardLayoutInputSource()?.takeRetainedValue(), + let property = TISGetInputSourceProperty(source, kTISPropertyUnicodeKeyLayoutData) + else { + return nil + } + let layoutData = Unmanaged.fromOpaque(property).takeUnretainedValue() as Data + + var deadKeyState: UInt32 = 0 + var length = 0 + var chars = [UniChar](repeating: 0, count: 4) + let modifiers = shifted ? UInt32(shiftKey >> 8) & 0xFF : 0 + + let status = layoutData.withUnsafeBytes { buffer -> OSStatus in + guard let layout = buffer.bindMemory(to: UCKeyboardLayout.self).baseAddress else { + return OSStatus(paramErr) + } + return UCKeyTranslate( + layout, keyCode, UInt16(kUCKeyActionDisplay), modifiers, UInt32(LMGetKbdType()), + OptionBits(kUCKeyTranslateNoDeadKeysMask), &deadKeyState, chars.count, &length, &chars) + } + + guard status == noErr, length > 0 else { return nil } + let result = String(utf16CodeUnits: chars, count: length) + guard let first = result.unicodeScalars.first, + !CharacterSet.controlCharacters.union(.whitespacesAndNewlines).contains(first) + else { + return nil + } + return result + } + + /// Rendered width of a key in points + static func keyWidth(for keyDef: KeyDefinition, scale: CGFloat = 1.0) -> CGFloat { + // A wide key also covers the gaps between the unit keys it spans + keyDef.width * scaledKeySize(scale) + (keyDef.width - 1) * scaledKeySpacing(scale) + } + + /// Calculate total keyboard width based on widest row + static var totalWidth: CGFloat { + rows.map { rowWidth($0) }.max() ?? 0 + } + + /// Rendered width of a row in points + static func rowWidth(_ row: [KeyDefinition], scale: CGFloat = 1.0) -> CGFloat { + let keys = row.reduce(0) { $0 + keyWidth(for: $1, scale: scale) } + let gaps = CGFloat(max(0, row.count - 1)) + return keys + gaps * scaledKeySpacing(scale) + } + + /// All keyboard rows + static let rows: [[KeyDefinition]] = [ + row0, row1, row2, row3, row4, + ] + + // Row 0: ` 1 2 3 4 5 6 7 8 9 0 - = Backspace (total: 15u) + static let row0: [KeyDefinition] = [ + KeyDefinition(label: "`", key: "`", keyCode: kVK_ANSI_Grave), + KeyDefinition(label: "1", key: "1", keyCode: kVK_ANSI_1), + KeyDefinition(label: "2", key: "2", keyCode: kVK_ANSI_2), + KeyDefinition(label: "3", key: "3", keyCode: kVK_ANSI_3), + KeyDefinition(label: "4", key: "4", keyCode: kVK_ANSI_4), + KeyDefinition(label: "5", key: "5", keyCode: kVK_ANSI_5), + KeyDefinition(label: "6", key: "6", keyCode: kVK_ANSI_6), + KeyDefinition(label: "7", key: "7", keyCode: kVK_ANSI_7), + KeyDefinition(label: "8", key: "8", keyCode: kVK_ANSI_8), + KeyDefinition(label: "9", key: "9", keyCode: kVK_ANSI_9), + KeyDefinition(label: "0", key: "0", keyCode: kVK_ANSI_0), + KeyDefinition(label: "-", key: "-", keyCode: kVK_ANSI_Minus), + KeyDefinition(label: "=", key: "=", keyCode: kVK_ANSI_Equal), + KeyDefinition(label: "⌫", key: "backspace", keyCode: kVK_Delete, width: 2.0, isModifier: true), + ] + + // Row 1: Tab Q W E R T Y U I O P [ ] \ (total: 15u) + static let row1: [KeyDefinition] = [ + KeyDefinition(label: "⇥", key: "tab", keyCode: kVK_Tab, width: 1.5), + KeyDefinition(label: "Q", key: "q", keyCode: kVK_ANSI_Q), + KeyDefinition(label: "W", key: "w", keyCode: kVK_ANSI_W), + KeyDefinition(label: "E", key: "e", keyCode: kVK_ANSI_E), + KeyDefinition(label: "R", key: "r", keyCode: kVK_ANSI_R), + KeyDefinition(label: "T", key: "t", keyCode: kVK_ANSI_T), + KeyDefinition(label: "Y", key: "y", keyCode: kVK_ANSI_Y), + KeyDefinition(label: "U", key: "u", keyCode: kVK_ANSI_U), + KeyDefinition(label: "I", key: "i", keyCode: kVK_ANSI_I), + KeyDefinition(label: "O", key: "o", keyCode: kVK_ANSI_O), + KeyDefinition(label: "P", key: "p", keyCode: kVK_ANSI_P), + KeyDefinition(label: "[", key: "[", keyCode: kVK_ANSI_LeftBracket), + KeyDefinition(label: "]", key: "]", keyCode: kVK_ANSI_RightBracket), + KeyDefinition(label: "\\", key: "\\", keyCode: kVK_ANSI_Backslash, width: 1.5), + ] + + // Row 2: Caps A S D F G H J K L ; ' Enter (total: 15u) + static let row2: [KeyDefinition] = [ + KeyDefinition(label: "⇪", key: "caps", keyCode: kVK_CapsLock, width: 1.75, isModifier: true), + KeyDefinition(label: "A", key: "a", keyCode: kVK_ANSI_A), + KeyDefinition(label: "S", key: "s", keyCode: kVK_ANSI_S), + KeyDefinition(label: "D", key: "d", keyCode: kVK_ANSI_D), + KeyDefinition(label: "F", key: "f", keyCode: kVK_ANSI_F), + KeyDefinition(label: "G", key: "g", keyCode: kVK_ANSI_G), + KeyDefinition(label: "H", key: "h", keyCode: kVK_ANSI_H), + KeyDefinition(label: "J", key: "j", keyCode: kVK_ANSI_J), + KeyDefinition(label: "K", key: "k", keyCode: kVK_ANSI_K), + KeyDefinition(label: "L", key: "l", keyCode: kVK_ANSI_L), + KeyDefinition(label: ";", key: ";", keyCode: kVK_ANSI_Semicolon), + KeyDefinition(label: "'", key: "'", keyCode: kVK_ANSI_Quote), + KeyDefinition(label: "⏎", key: "enter", keyCode: kVK_Return, width: 2.25), + ] + + // Row 3: Shift Z X C V B N M , . / Shift (total: 15u) + static let row3: [KeyDefinition] = [ + KeyDefinition(label: "⇧", key: "shift", keyCode: kVK_Shift, width: 2.25, isModifier: true), + KeyDefinition(label: "Z", key: "z", keyCode: kVK_ANSI_Z), + KeyDefinition(label: "X", key: "x", keyCode: kVK_ANSI_X), + KeyDefinition(label: "C", key: "c", keyCode: kVK_ANSI_C), + KeyDefinition(label: "V", key: "v", keyCode: kVK_ANSI_V), + KeyDefinition(label: "B", key: "b", keyCode: kVK_ANSI_B), + KeyDefinition(label: "N", key: "n", keyCode: kVK_ANSI_N), + KeyDefinition(label: "M", key: "m", keyCode: kVK_ANSI_M), + KeyDefinition(label: ",", key: ",", keyCode: kVK_ANSI_Comma), + KeyDefinition(label: ".", key: ".", keyCode: kVK_ANSI_Period), + KeyDefinition(label: "/", key: "/", keyCode: kVK_ANSI_Slash), + KeyDefinition(label: "⇧", key: "shift_r", keyCode: kVK_RightShift, width: 2.75, isModifier: true), + ] + + // Row 4: Ctrl Opt Cmd Space Cmd Opt Ctrl (total: 15u) + // Spacebar aligned with C key (left edge) and comma key (right edge) + // Right Cmd and Opt meet under center of slash key + static let row4: [KeyDefinition] = [ + KeyDefinition(label: "⌃", key: "ctrl", keyCode: kVK_Control, width: 1.5, isModifier: true), + KeyDefinition(label: "⌥", key: "opt", keyCode: kVK_Option, width: 1.25, isModifier: true), + KeyDefinition(label: "⌘", key: "cmd", keyCode: kVK_Command, width: 1.5, isModifier: true), + KeyDefinition(label: "", key: "space", keyCode: kVK_Space, width: 6.0), + KeyDefinition(label: "⌘", key: "cmd_r", keyCode: kVK_RightCommand, width: 1.5, isModifier: true), + KeyDefinition(label: "⌥", key: "opt_r", keyCode: kVK_RightOption, width: 1.5, isModifier: true), + KeyDefinition( + label: "⌃", key: "ctrl_r", keyCode: kVK_RightControl, width: 1.75, isModifier: true), + ] +} diff --git a/Leader Key/KeyboardLayout/KeyboardLayoutView.swift b/Leader Key/KeyboardLayout/KeyboardLayoutView.swift new file mode 100644 index 00000000..ede8561a --- /dev/null +++ b/Leader Key/KeyboardLayout/KeyboardLayoutView.swift @@ -0,0 +1,114 @@ +import AppKit +import Carbon.HIToolbox +import Defaults +import SwiftUI + +struct KeyboardLayoutView: View { + let bindings: [String: ActionOrGroup] + let shiftHeld: Bool + var scale: CGFloat = 1.0 + var showLabels: Bool = false + var onKeySelected: ((String) -> Void)? = nil + /// Called with the source and target binding keys when a binding is dragged onto another key. + var onBindingMoved: ((String, String) -> Void)? = nil + /// Builds the right-click menu for a bound key, given its binding key and binding. + var menuItems: ((String, ActionOrGroup) -> [KeyMenuItem])? = nil + + @State private var draggedBindingKey: String? + + // Key labels and binding keys depend on both of these, so redraw when either changes + @Default(.forceEnglishKeyboardLayout) private var forceEnglishKeyboardLayout + @State private var inputSourceRevision = 0 + + var body: some View { + VStack(alignment: .leading, spacing: KeyboardLayout.scaledRowSpacing(scale)) { + ForEach(Array(KeyboardLayout.rows.enumerated()), id: \.offset) { _, row in + HStack(spacing: KeyboardLayout.scaledKeySpacing(scale)) { + ForEach(row) { keyDef in + KeyView( + keyDef: keyDef, + binding: getBinding(for: keyDef), + shiftHeld: shiftHeld, + scale: scale, + showLabels: showLabels, + onSelect: { + onKeySelected?(keyDef.key) + }, + onDragStart: canRearrange(keyDef) + ? { draggedBindingKey = bindingKey(for: keyDef) } : nil, + dropDelegate: canRearrange(keyDef) ? dropDelegate(for: keyDef) : nil, + menuItems: menuItems(for: keyDef) + ) + } + } + .fixedSize() + } + } + .fixedSize() + .id("\(forceEnglishKeyboardLayout)-\(inputSourceRevision)") + .onReceive( + DistributedNotificationCenter.default().publisher( + for: Notification.Name(kTISNotifySelectedKeyboardInputSourceChanged as String)) + ) { _ in + inputSourceRevision += 1 + } + } + + private func getBinding(for keyDef: KeyDefinition) -> ActionOrGroup? { + bindings[bindingKey(for: keyDef)] + } + + private func bindingKey(for keyDef: KeyDefinition) -> String { + KeyboardLayout.bindingKey(for: keyDef, shifted: shiftHeld) + } + + private func menuItems(for keyDef: KeyDefinition) -> [KeyMenuItem] { + guard let menuItems = menuItems, !keyDef.isModifier, let binding = getBinding(for: keyDef) + else { return [] } + return menuItems(bindingKey(for: keyDef), binding) + } + + private func canRearrange(_ keyDef: KeyDefinition) -> Bool { + onBindingMoved != nil && !keyDef.isModifier + } + + private func dropDelegate(for keyDef: KeyDefinition) -> KeyDropDelegate { + let targetKey = bindingKey(for: keyDef) + return KeyDropDelegate( + canDrop: { + guard let source = draggedBindingKey else { return false } + return source != targetKey && bindings[source] != nil + }, + onDrop: { + guard let source = draggedBindingKey else { return } + draggedBindingKey = nil + onBindingMoved?(source, targetKey) + } + ) + } +} + +#Preview { + let sampleBindings: [String: ActionOrGroup] = [ + "s": .action( + Action( + key: "s", + type: .application, + label: "Safari", + value: "/Applications/Safari.app" + )), + "v": .group( + Group( + key: "v", + label: "VSCode", + actions: [] + )), + ] + + KeyboardLayoutView( + bindings: sampleBindings, + shiftHeld: false + ) + .frame(width: 700, height: 300) + .padding() +} diff --git a/Leader Key/Settings.swift b/Leader Key/Settings.swift index 1eb1af27..1e580715 100644 --- a/Leader Key/Settings.swift +++ b/Leader Key/Settings.swift @@ -3,4 +3,6 @@ import Settings extension Settings.PaneIdentifier { static let general = Self("general") static let advanced = Self("advanced") + static let keyboard = Self("keyboard") + static let stats = Self("stats") } diff --git a/Leader Key/Settings/AdvancedPane.swift b/Leader Key/Settings/AdvancedPane.swift index 62cdfb26..25e41602 100644 --- a/Leader Key/Settings/AdvancedPane.swift +++ b/Leader Key/Settings/AdvancedPane.swift @@ -13,6 +13,7 @@ struct AdvancedPane: View { @Default(.modifierKeyConfiguration) var modifierKeyConfiguration @Default(.autoOpenCheatsheet) var autoOpenCheatsheet @Default(.cheatsheetDelayMS) var cheatsheetDelayMS + @Default(.cheatsheetStyle) var cheatsheetStyle @Default(.reactivateBehavior) var reactivateBehavior @Default(.showAppIconsInCheatsheet) var showAppIconsInCheatsheet @Default(.screen) var screen @@ -115,6 +116,26 @@ struct AdvancedPane: View { Defaults.Toggle( "Show item details in cheatsheet", key: .showDetailsInCheatsheet) + Divider() + .padding(.vertical, 8) + + HStack(alignment: .firstTextBaseline) { + Text("Cheatsheet Style:") + Picker("", selection: $cheatsheetStyle) { + Text("List").tag(CheatsheetStyle.list) + Text("Keyboard").tag(CheatsheetStyle.keyboard) + } + .pickerStyle(.segmented) + .frame(width: 200) + .labelsHidden() + + Spacer() + } + + Text("Choose how shortcuts are displayed in the cheatsheet overlay") + .foregroundColor(.secondary) + .font(.callout) + } Settings.Section(title: "Activation", bottomDivider: true) { diff --git a/Leader Key/Settings/KeyboardPane.swift b/Leader Key/Settings/KeyboardPane.swift new file mode 100644 index 00000000..ddc19fb7 --- /dev/null +++ b/Leader Key/Settings/KeyboardPane.swift @@ -0,0 +1,927 @@ +import AppKit +import Defaults +import KeyboardShortcuts +import Settings +import SwiftUI +import UniformTypeIdentifiers + +struct EditorWrapper: Identifiable { + var id: String { item.uiid.uuidString } + var item: ActionOrGroup + var keyName: String + var isNew: Bool = false +} + +struct UnifiedEditorView: View { + @Binding var item: ActionOrGroup + var keyName: String + var isNew: Bool + var onSave: (ActionOrGroup) -> Void + var onDelete: (ActionOrGroup) -> Void + var onOpenLayout: (ActionOrGroup) -> Void + + @Environment(\.dismiss) private var dismiss + @State private var showIconPicker = false + + // Temporary state to hold values when switching types + @State private var actionType: Type = .application + @State private var label: String = "" + @State private var value: String = "" + @State private var iconPath: String? + + @FocusState private var isValueFieldFocused: Bool + + // Type selection for the segmented control + enum ItemType: String, CaseIterable { + case action = "Action" + case group = "Group" + } + + @State private var selectedType: ItemType = .action + + init( + item: Binding, + keyName: String, + isNew: Bool, + onSave: @escaping (ActionOrGroup) -> Void, + onDelete: @escaping (ActionOrGroup) -> Void, + onOpenLayout: @escaping (ActionOrGroup) -> Void + ) { + self._item = item + self.keyName = keyName + self.isNew = isNew + self.onSave = onSave + self.onDelete = onDelete + self.onOpenLayout = onOpenLayout + + // Initialize local state based on input item + switch item.wrappedValue { + case .action(let action): + _selectedType = State(initialValue: .action) + _actionType = State(initialValue: action.type) + _label = State(initialValue: action.label ?? "") + _value = State(initialValue: action.value) + _iconPath = State(initialValue: action.iconPath) + case .group(let group): + _selectedType = State(initialValue: .group) + _label = State(initialValue: group.label ?? "") + _iconPath = State(initialValue: group.iconPath) + } + } + + var body: some View { + VStack(spacing: 20) { + // Key being edited indicator + Text("Editing '\(keyName)'") + .font(.title2) + .foregroundColor(.secondary) + .padding(.top, 12) + + // Header: Icon & Label + VStack(spacing: 12) { + // Icon Picker + Button { + showIconPicker = true + } label: { + if let icon = resolveIcon() { + Image(nsImage: icon) + .resizable() + .aspectRatio(contentMode: .fit) + .frame(width: 64, height: 64) + .shadow(radius: 2) + } else { + ZStack { + Circle().fill(Color.secondary.opacity(0.1)) + .frame(width: 64, height: 64) + Image(systemName: "photo") + .font(.system(size: 24)) + .foregroundColor(.secondary) + } + } + } + .buttonStyle(.plain) + .overlay(alignment: .topTrailing) { + if iconPath != nil { + Button { + iconPath = nil + updateItem() + } label: { + Image(systemName: "xmark.circle.fill") + .foregroundColor(.secondary) + .background(Circle().fill(Color(nsColor: .windowBackgroundColor))) + } + .buttonStyle(.plain) + .offset(x: 4, y: -4) + } + } + + // Label Input + TextField("Label", text: $label) + .textFieldStyle(.plain) + .font(.title2) + .multilineTextAlignment(.center) + .padding(6) + .overlay( + RoundedRectangle(cornerRadius: 8) + .stroke(Color.secondary.opacity(0.3), lineWidth: 1) + ) + .frame(maxWidth: 220) + .onChange(of: label) { _ in updateItem() } + } + .padding(.top, 24) + + // Type Switcher + Picker("", selection: $selectedType) { + ForEach(ItemType.allCases, id: \.self) { type in + Text(type.rawValue).tag(type) + } + } + .pickerStyle(.segmented) + .padding(.horizontal, 32) + .onChange(of: selectedType) { newType in + updateItemType(newType) + } + + // Content Area + VStack(alignment: .leading, spacing: 16) { + if selectedType == .action { + // Action Type Picker + HStack { + Text("Action Type") + .font(.subheadline) + .foregroundColor(.secondary) + Spacer() + Picker("", selection: $actionType) { + Text("Application").tag(Type.application) + Text("URL").tag(Type.url) + Text("Command").tag(Type.command) + Text("Folder").tag(Type.folder) + } + .labelsHidden() + .fixedSize() + } + .onChange(of: actionType) { _ in updateItem() } + + // Value Input + VStack(alignment: .leading, spacing: 6) { + Text(valueLabel) + .font(.caption) + .fontWeight(.semibold) + .foregroundColor(.secondary) + + HStack { + TextField("Enter value...", text: $value) + .textFieldStyle(.roundedBorder) + .focused($isValueFieldFocused) + .onTapGesture { + isValueFieldFocused = true + } + .onChange(of: value) { _ in updateItem() } + + if actionType == .application || actionType == .folder { + Button { + openFilePicker() + } label: { + Image(systemName: "folder") + } + .buttonStyle(.bordered) + } + } + } + } else { + // Group Mode + Spacer() + } + } + .padding(.horizontal, 24) + + Spacer() + + // Footer + HStack { + if selectedType == .group { + // Group mode: Cancel button + Button("Cancel") { + dismiss() + } + .keyboardShortcut(.cancelAction) + .buttonStyle(.bordered) + .controlSize(.regular) + } else if !isNew { + // Action mode: Delete button + Button(role: .destructive) { + onDelete(item) + } label: { + Image(systemName: "trash") + .font(.system(size: 16)) + .foregroundColor(.secondary) + } + .buttonStyle(.plain) + .help("Delete Item") + } + + Spacer() + + Button(selectedType == .group ? "Assign Actions" : "Done") { + let updated = getUpdatedItem() + item = updated + onSave(updated) + if selectedType == .group { + onOpenLayout(updated) + } + } + .keyboardShortcut(.defaultAction) + .buttonStyle(.borderedProminent) + .controlSize(.regular) + } + .padding(20) + .background(Color(nsColor: .controlBackgroundColor)) + } + .frame(width: 320, height: 480) + .fileImporter( + isPresented: $showIconPicker, + allowedContentTypes: [.image, .icns], + allowsMultipleSelection: false + ) { result in + switch result { + case .success(let urls): + if let url = urls.first { + iconPath = url.path + updateItem() + } + case .failure(let error): + print("Icon selection error: \(error.localizedDescription)") + } + } + } + + private func updateItemType(_ type: ItemType) { + let key = item.key + if type == .action { + item = .action( + Action( + uiid: item.uiid, + key: key, + type: actionType, + label: label.isEmpty ? nil : label, + value: value, + iconPath: iconPath + ) + ) + } else { + let existingActions: [ActionOrGroup] + if case .group(let existingGroup) = item { + existingActions = existingGroup.actions + } else { + existingActions = [] + } + item = .group( + Group( + uiid: item.uiid, + key: key, + label: label.isEmpty ? nil : label, + iconPath: iconPath, + actions: existingActions + ) + ) + } + } + + private func updateItem() { + item = getUpdatedItem() + } + + private func getUpdatedItem() -> ActionOrGroup { + let key = item.key + let currentLabel = label.isEmpty ? nil : label + + switch selectedType { + case .action: + if case .action(let existingAction) = item { + var updated = existingAction + updated.key = key + updated.type = actionType + updated.label = currentLabel + updated.value = value + updated.iconPath = iconPath + return .action(updated) + } else { + return .action( + Action( + uiid: item.uiid, + key: key, + type: actionType, + label: currentLabel, + value: value, + iconPath: iconPath + ) + ) + } + case .group: + if case .group(let existingGroup) = item { + var newGroup = existingGroup + newGroup.label = currentLabel + newGroup.iconPath = iconPath + return .group(newGroup) + } else { + return .group( + Group( + uiid: item.uiid, + key: key, + label: currentLabel, + iconPath: iconPath, + actions: [] + ) + ) + } + } + } + + private func resolveIcon() -> NSImage? { + switch item { + case .action(let action): return action.resolvedIcon() + case .group(let group): return group.resolvedIcon() + } + } + + private var valueLabel: String { + switch actionType { + case .application: return "Application Path" + case .url: return "URL" + case .command: return "Shell Command" + case .folder: return "Folder Path" + default: return "Value" + } + } + + private var allowedFileTypes: [UTType] { + switch actionType { + case .application: return [.application, .applicationBundle] + case .folder: return [.folder] + default: return [] + } + } + + private func openFilePicker() { + let panel = NSOpenPanel() + panel.allowsMultipleSelection = false + panel.canChooseDirectories = actionType == .folder + panel.canChooseFiles = actionType != .folder + panel.allowedContentTypes = allowedFileTypes + + if actionType == .application { + panel.directoryURL = URL(fileURLWithPath: "/Applications") + } + + panel.begin { response in + if response == .OK, let url = panel.url { + self.value = url.path + self.updateItem() + } + } + } +} + +struct GroupWrapper: Identifiable { + var id: String { group.uiid.uuidString } + var group: KeyGroup +} + +struct GroupEditorView: View { + @Binding var group: KeyGroup + var onSave: () -> Void + var onDelete: () -> Void + var onOpenLayout: () -> Void + + @State private var showIconPicker = false + + var body: some View { + VStack(spacing: 20) { + // Header: Icon & Label + VStack(spacing: 12) { + // Icon Picker + Button { + showIconPicker = true + } label: { + if let icon = group.resolvedIcon() { + Image(nsImage: icon) + .resizable() + .aspectRatio(contentMode: .fit) + .frame(width: 64, height: 64) + .shadow(radius: 2) + } else { + ZStack { + Circle().fill(Color.secondary.opacity(0.1)) + .frame(width: 64, height: 64) + Image(systemName: "folder") + .font(.system(size: 24)) + .foregroundColor(.secondary) + } + } + } + .buttonStyle(.plain) + .overlay(alignment: .topTrailing) { + if group.iconPath != nil { + Button { + group.iconPath = nil + } label: { + Image(systemName: "xmark.circle.fill") + .foregroundColor(.secondary) + .background(Circle().fill(Color(nsColor: .windowBackgroundColor))) + } + .buttonStyle(.plain) + .offset(x: 4, y: -4) + } + } + + // Label Input + TextField( + "Label", + text: Binding( + get: { group.label ?? "" }, + set: { group.label = $0.isEmpty ? nil : $0 } + ) + ) + .textFieldStyle(.plain) + .font(.title2) + .multilineTextAlignment(.center) + .padding(6) + .overlay( + RoundedRectangle(cornerRadius: 8) + .stroke(Color.secondary.opacity(0.3), lineWidth: 1) + ) + .frame(maxWidth: 220) + } + .padding(.top, 24) + + Text("Edit group settings") + .font(.subheadline) + .foregroundColor(.secondary) + + Spacer() + + // Footer + HStack { + Button(role: .destructive) { + onDelete() + } label: { + Image(systemName: "trash") + .font(.system(size: 16)) + .foregroundColor(.secondary) + } + .buttonStyle(.plain) + .help("Delete Group") + + Spacer() + + Button("Done") { + onSave() + } + .keyboardShortcut(.defaultAction) + .buttonStyle(.borderedProminent) + .controlSize(.regular) + } + .padding(20) + .background(Color(nsColor: .controlBackgroundColor)) + } + .frame(width: 320, height: 350) + .fileImporter( + isPresented: $showIconPicker, + allowedContentTypes: [.image, .icns], + allowsMultipleSelection: false + ) { result in + switch result { + case .success(let urls): + if let url = urls.first { + group.iconPath = url.path + } + case .failure(let error): + print("Icon selection error: \(error.localizedDescription)") + } + } + } +} + +struct KeyboardPane: View { + private let contentWidth = 950.0 + private let maxKeyboardScale: CGFloat = 1.4 + @EnvironmentObject private var config: UserConfig + + @State private var editingItem: EditorWrapper? + @State private var editingGroupWrapper: GroupWrapper? + @State private var groupPendingDelete: KeyGroup? + @State private var currentGroupPath: [UUID] = [] + @State private var shiftHeld = false + @State private var stickyShiftMode = false // Persists after editing capital letter keys + @State private var monitor: Any? + + var currentGroup: KeyGroup { + if let id = currentGroupPath.last { + return config.root.find(id: id) ?? config.root + } + return config.root + } + + var bindings: [String: ActionOrGroup] { + var result: [String: ActionOrGroup] = [:] + + for item in currentGroup.actions { + switch item { + case .action(let action): + if let key = action.key { + result[KeyMaps.text(for: key) ?? key] = item + } + case .group(let group): + if let key = group.key { + result[KeyMaps.text(for: key) ?? key] = item + } + } + } + + return result + } + + var body: some View { + Settings.Container(contentWidth: contentWidth) { + Settings.Section(title: "", bottomDivider: true) { + VStack(alignment: .center, spacing: 12) { + // Breadcrumbs & Header + HStack(spacing: 0) { + let keyboardWidth = KeyboardLayout.totalWidth * maxKeyboardScale + + HStack(spacing: 4) { + if !currentGroupPath.isEmpty { + ScrollView(.horizontal, showsIndicators: false) { + HStack(spacing: 4) { + // Root breadcrumb + Button { + currentGroupPath.removeAll() + } label: { + Image(systemName: "house.fill") + } + + // Path breadcrumbs + ForEach(0..") + .foregroundColor(.secondary) + + let id = currentGroupPath[index] + let name = getGroupName(for: id) + let isLast = index == currentGroupPath.count - 1 + + if isLast { + // Current location - show as bold text, not a button + Text(name) + .fontWeight(.bold) + } else { + Button { + currentGroupPath = Array( + (currentGroupPath as [UUID]).prefix(index + 1) + ) + } label: { + Text(name) + } + } + } + } + } + + Spacer() + + // Edit Current Group Button + Button { + editingGroupWrapper = GroupWrapper(group: currentGroup) + } label: { + Image(systemName: "gearshape") + .foregroundColor(.secondary) + } + .buttonStyle(.borderless) + .help("Edit Group Settings") + } else { + // Invisible button to maintain consistent height with breadcrumb view + Button { + } label: { + Image(systemName: "house.fill") + } + .opacity(0) + .disabled(true) + + Spacer() + } + } + .frame(width: keyboardWidth) + } + .frame(height: 24) + + KeyboardLayoutView( + bindings: bindings, + shiftHeld: shiftHeld || stickyShiftMode, + scale: maxKeyboardScale, + onKeySelected: { key in + if key == "shift" || key == "shift_r" { + stickyShiftMode.toggle() + return + } + + // Determine if we're in shift mode + let isShiftActive = shiftHeld || stickyShiftMode + + // If shift is active, persist it (sticky mode) + if isShiftActive { + stickyShiftMode = true + } + + // Use the same key the keyboard draws for lookup and creation + let lookupKey = KeyboardLayout.bindingKey( + forStaticKey: key, shifted: isShiftActive) + + if let existing = bindings[lookupKey] { + switch existing { + case .action(let action): + editingItem = EditorWrapper( + item: .action(action), + keyName: lookupKey, + isNew: false + ) + case .group(let group): + // Direct navigation into group + currentGroupPath.append(group.uiid) + } + } else { + // Default to empty application action + editingItem = EditorWrapper( + item: .action( + Action(key: lookupKey, type: .application, value: "") + ), + keyName: lookupKey, + isNew: true + ) + } + }, + onBindingMoved: { sourceKey, targetKey in + moveBinding(from: sourceKey, to: targetKey) + }, + menuItems: { key, item in + menuItems(for: item, on: key) + } + ) + + Text("Click a key to configure, drag to move or swap, right-click for more") + .font(.body) + .foregroundColor(.secondary) + .frame(maxWidth: .infinity, alignment: .center) + .padding(.vertical, 24) + } + } + } + .sheet( + item: $editingItem, + onDismiss: { + stickyShiftMode = false + } + ) { wrapper in + UnifiedEditorView( + item: Binding( + get: { wrapper.item }, + set: { editingItem?.item = $0 } + ), + keyName: wrapper.keyName, + isNew: wrapper.isNew, + onSave: { updatedItem in + saveItem(updatedItem) + editingItem = nil + }, + onDelete: { itemToDelete in + deleteItem(itemToDelete) + editingItem = nil + }, + onOpenLayout: { updatedItem in + if case .group(let group) = updatedItem { + currentGroupPath.append(group.uiid) + editingItem = nil + } + } + ) + } + .sheet( + item: $editingGroupWrapper, + onDismiss: { + stickyShiftMode = false + } + ) { wrapper in + GroupEditorView( + group: Binding( + get: { wrapper.group }, + set: { editingGroupWrapper?.group = $0 } + ), + onSave: { + if let group = editingGroupWrapper?.group { + saveGroup(group) + } + editingGroupWrapper = nil + }, + onDelete: { + if let group = editingGroupWrapper?.group { + if group.uiid == currentGroupPath.last { + deleteGroup(group) + // We deleted the group being shown, so pop back + currentGroupPath.removeLast() + } else { + // A group edited from its key's right-click menu + deleteItem(.group(group)) + } + } + editingGroupWrapper = nil + }, + onOpenLayout: { + editingGroupWrapper = nil + } + ) + } + .confirmationDialog( + "Delete “\(groupPendingDelete?.displayName ?? "")”?", + isPresented: Binding( + get: { groupPendingDelete != nil }, + set: { if !$0 { groupPendingDelete = nil } } + ), + presenting: groupPendingDelete + ) { group in + Button("Delete Group", role: .destructive) { + deleteItem(.group(group)) + } + } message: { group in + Text("This also deletes the \(group.actions.count) bindings inside it.") + } + .onAppear { + monitor = NSEvent.addLocalMonitorForEvents( + matching: .flagsChanged + ) { event in + let wasShiftHeld = shiftHeld + let isShiftHeld = event.modifierFlags.contains(.shift) + shiftHeld = isShiftHeld + + // If physical shift was released while in sticky mode, exit sticky mode + // BUT only if we're not currently editing (keep shift while editor is open) + if wasShiftHeld && !isShiftHeld && stickyShiftMode && editingItem == nil { + stickyShiftMode = false + } + return event + } + } + .onDisappear { + if let monitor = monitor { + NSEvent.removeMonitor(monitor) + } + monitor = nil + // Reset to root when closing settings + currentGroupPath.removeAll() + stickyShiftMode = false + } + } + + private func saveItem(_ item: ActionOrGroup) { + var group = currentGroup + let newActions = group.actions.filter { existing in + // Use UUID match if updating same item, OR Key match if replacing/colliding + existing.uiid != item.uiid && existing.key != item.key + } + group.actions = newActions + [item] + + updateConfig(with: group) + } + + private func deleteItem(_ item: ActionOrGroup) { + var group = currentGroup + let newActions = group.actions.filter { existing in + existing.uiid != item.uiid + } + group.actions = newActions + + updateConfig(with: group) + + if currentGroupPath.isEmpty, case .group(let deleted) = item, let key = deleted.key { + removeGroupShortcut(KeyMaps.text(for: key) ?? key) + } + } + + private func menuItems(for item: ActionOrGroup, on key: String) -> [KeyMenuItem] { + switch item { + case .action(let action): + return [ + KeyMenuItem(title: "Edit…", systemImage: "pencil") { + editingItem = EditorWrapper(item: .action(action), keyName: key, isNew: false) + }, + KeyMenuItem(title: "Delete", systemImage: "trash", isDestructive: true) { + deleteItem(item) + }, + ] + case .group(let group): + return [ + KeyMenuItem(title: "Open", systemImage: "chevron.right") { + currentGroupPath.append(group.uiid) + }, + KeyMenuItem(title: "Edit…", systemImage: "pencil") { + editingGroupWrapper = GroupWrapper(group: group) + }, + KeyMenuItem(title: "Delete", systemImage: "trash", isDestructive: true) { + if group.actions.isEmpty { + deleteItem(item) + } else { + groupPendingDelete = group + } + }, + ] + } + } + + /// A deleted root group must not leave its global shortcut behind for the next binding on that key. + private func removeGroupShortcut(_ key: String) { + guard Defaults[.groupShortcuts].contains(key) else { return } + Defaults[.groupShortcuts].remove(key) + KeyboardShortcuts.reset([KeyboardShortcuts.Name("group-\(key)")]) + (NSApplication.shared.delegate as? AppDelegate)?.registerGlobalShortcuts() + } + + /// Moves the binding on `sourceKey` to `targetKey`, swapping if the target is already bound. + private func moveBinding(from sourceKey: String, to targetKey: String) { + // Look items up through `bindings` so stored glyphs ("⇥") match drawn keys ("tab") + let current = bindings + var group = currentGroup + guard sourceKey != targetKey, + let sourceID = current[sourceKey]?.uiid, + let sourceIndex = group.actions.firstIndex(where: { $0.uiid == sourceID }) + else { return } + + let targetID = current[targetKey]?.uiid + let targetIndex = group.actions.firstIndex(where: { $0.uiid == targetID }) + group.actions[sourceIndex] = group.actions[sourceIndex].withKey(targetKey) + if let targetIndex = targetIndex { + group.actions[targetIndex] = group.actions[targetIndex].withKey(sourceKey) + } + + updateConfig(with: group) + + if currentGroupPath.isEmpty { + swapGroupShortcuts(sourceKey, targetKey) + } + } + + /// Global group shortcuts are stored by root key, so they have to follow a moved binding. + private func swapGroupShortcuts(_ firstKey: String, _ secondKey: String) { + let firstName = KeyboardShortcuts.Name("group-\(firstKey)") + let secondName = KeyboardShortcuts.Name("group-\(secondKey)") + let firstShortcut = KeyboardShortcuts.getShortcut(for: firstName) + let secondShortcut = KeyboardShortcuts.getShortcut(for: secondName) + guard firstShortcut != nil || secondShortcut != nil else { return } + + KeyboardShortcuts.setShortcut(secondShortcut, for: firstName) + KeyboardShortcuts.setShortcut(firstShortcut, for: secondName) + + var shortcuts = Defaults[.groupShortcuts] + if secondShortcut != nil { shortcuts.insert(firstKey) } else { shortcuts.remove(firstKey) } + if firstShortcut != nil { shortcuts.insert(secondKey) } else { shortcuts.remove(secondKey) } + Defaults[.groupShortcuts] = shortcuts + + (NSApplication.shared.delegate as? AppDelegate)?.registerGlobalShortcuts() + } + + private func saveGroup(_ group: KeyGroup) { + updateConfig(with: group) + } + + private func deleteGroup(_ group: KeyGroup) { + if currentGroupPath.isEmpty { + return + } + + // Find parent + let parentId = currentGroupPath.dropLast().last + let parent = parentId != nil ? config.root.find(id: parentId!) : config.root + + if var p = parent { + p.actions.removeAll { $0.uiid == group.uiid } + updateConfig(with: p) + } + } + + private func updateConfig(with modifiedGroup: KeyGroup) { + // Matches by id, so this works for the shown group and for one of its child groups + var root = config.root + if root.update(group: modifiedGroup) { + config.root = root + } + } + + private func getGroupName(for id: UUID) -> String { + if let group = config.root.find(id: id) { + return group.displayName + } + return "Unknown" + } +} + +#Preview { + let config = UserConfig() + return KeyboardPane() + .environmentObject(config) +} diff --git a/Leader Key/Settings/StatsPane.swift b/Leader Key/Settings/StatsPane.swift new file mode 100644 index 00000000..1e8a9c8b --- /dev/null +++ b/Leader Key/Settings/StatsPane.swift @@ -0,0 +1,497 @@ +import AppKit +import Settings +import SwiftUI +import Kingfisher + +struct StatsPane: View { + private let contentWidth = 550.0 + + @EnvironmentObject private var userConfig: UserConfig + + @State private var groupedStats: [GroupStats] = [] + @State private var expandedGroups: Set = [] + @State private var totalExecutions: Int = 0 + + var body: some View { + Settings.Container(contentWidth: contentWidth) { + Settings.Section(title: "") { + VStack(alignment: .leading, spacing: 16) { + // Header + HStack(alignment: .center) { + Text("Usage Stats") + .font(.headline) + Spacer() + Text("\(totalExecutions) total") + .foregroundColor(.primary) + .font(.system(.body, design: .rounded)) + .fontWeight(.medium) + .monospacedDigit() + } + .padding(.bottom, 8) + + // Stats list + if groupedStats.isEmpty { + Text("No actions recorded yet") + .foregroundColor(.secondary) + .padding(.vertical, 20) + } else { + ScrollView { + VStack(spacing: 2) { + ForEach(groupedStats) { group in + GroupStatsRow( + group: group, + isExpanded: expandedGroups.contains(group.id), + maxCount: groupedStats.first?.totalCount ?? 1, + depth: 0, + expandedGroups: $expandedGroups + ) + } + } + } + .scrollIndicators(.hidden) + .frame(height: 400) + } + } + } + + Settings.Section(title: "") { + VStack { + Spacer() + .frame(height: 24) + + HStack { + Spacer() + Button("Clear Stats") { + showClearConfirmation() + } + Spacer() + } + } + } + } + .onAppear { + loadStats() + } + } + + private func loadStats() { + let rawActions = StatsManager.shared.getMostUsedActions(limit: 50) + + // Build tree structure + let allDisplays = rawActions.map { stat in + ActionStatsDisplay( + action: stat, + pathComponents: stat.keyPath.split(separator: "/").map(String.init) + ) + } + + groupedStats = buildGroupTree(displays: allDisplays, pathPrefix: []) + .sorted { $0.totalCount > $1.totalCount } + + totalExecutions = StatsManager.shared.getTotalExecutions() + } + + private func buildGroupTree(displays: [ActionStatsDisplay], pathPrefix: [String]) -> [GroupStats] { + var result: [GroupStats] = [] + + // Group by next path component + var grouped: [String: [ActionStatsDisplay]] = [:] + var leafActions: [ActionStatsDisplay] = [] + + for display in displays { + let remainingPath = Array(display.pathComponents.dropFirst(pathPrefix.count)) + + if remainingPath.count == 1 { + // This is a leaf action at this level + leafActions.append(display) + } else if remainingPath.count > 1 { + // This belongs to a subgroup + let nextKey = remainingPath[0] + grouped[nextKey, default: []].append(display) + } + } + + // Create GroupStats for each subgroup + for (key, items) in grouped { + let fullPath = (pathPrefix + [key]).joined(separator: "/") + let totalCount = items.reduce(0) { $0 + $1.action.executionCount } + let groupLabel = findGroupLabel(for: key, at: pathPrefix) ?? key.capitalized + + // Recursively build children + let nestedGroups = buildGroupTree(displays: items, pathPrefix: pathPrefix + [key]) + let children: [GroupStatsChild] = nestedGroups.map { .group($0) } + + result.append(GroupStats( + fullPath: fullPath, + groupKey: key, + groupLabel: groupLabel, + totalCount: totalCount, + children: children, + isGroup: true + )) + } + + // Add leaf actions + for action in leafActions { + result.append(GroupStats( + fullPath: action.action.keyPath, + groupKey: action.pathComponents.last ?? "", + groupLabel: action.action.actionLabel ?? action.action.actionValue, + totalCount: action.action.executionCount, + children: [.action(action)], + isGroup: false + )) + } + + return result.sorted { $0.totalCount > $1.totalCount } + } + + private func findGroupLabel(for key: String, at pathPrefix: [String]) -> String? { + // Navigate to the right level in the config + var current: Group = userConfig.root + + for component in pathPrefix { + guard let nextGroup = current.actions.first(where: { item in + if case .group(let g) = item, g.key == component { + return true + } + return false + }) else { + return nil + } + + if case .group(let g) = nextGroup { + current = g + } + } + + // Find the group at this level + for item in current.actions { + if case .group(let group) = item, group.key == key { + return group.label ?? group.key + } + } + + return nil + } + + + private func showClearConfirmation() { + let alert = NSAlert() + alert.messageText = "Clear All Stats?" + alert.informativeText = + "This will permanently delete all recorded action history." + alert.alertStyle = .warning + alert.addButton(withTitle: "Clear") + alert.addButton(withTitle: "Cancel") + + if alert.runModal() == .alertFirstButtonReturn { + StatsManager.shared.clearAllStats() + loadStats() + } + } +} + +private struct GroupStats: Identifiable { + var id: String { fullPath } + let fullPath: String // Full path for unique ID + let groupKey: String // Just this level's key + let groupLabel: String + let totalCount: Int + let children: [GroupStatsChild] + let isGroup: Bool +} + +private enum GroupStatsChild: Identifiable { + case action(ActionStatsDisplay) + case group(GroupStats) + + var id: String { + switch self { + case .action(let display): + return display.id.uuidString + case .group(let group): + return group.id + } + } + + var executionCount: Int { + switch self { + case .action(let display): + return display.action.executionCount + case .group(let group): + return group.totalCount + } + } +} + +private struct ActionStatsDisplay: Identifiable { + let id = UUID() + let action: ActionStats + let pathComponents: [String] +} + +private struct GroupStatsRow: View { + let group: GroupStats + let isExpanded: Bool + let maxCount: Int + let depth: Int + @Binding var expandedGroups: Set + + private let indentPerLevel: CGFloat = 16 + + var body: some View { + if group.isGroup { + // Collapsible group with children + VStack(spacing: 2) { + // Group header + HStack(spacing: 0) { + // Indent spacer outside the button + if depth > 0 { + Spacer() + .frame(width: indentPerLevel * CGFloat(depth)) + } + + Button(action: { + if expandedGroups.contains(group.id) { + expandedGroups.remove(group.id) + } else { + expandedGroups.insert(group.id) + } + }) { + HStack(alignment: .center, spacing: 0) { + // Chevron + Image(systemName: "chevron.right") + .font(.system(size: 12, weight: .semibold)) + .foregroundColor(.secondary) + .rotationEffect(.degrees(isExpanded ? 90 : 0)) + .animation(.easeInOut(duration: 0.2), value: isExpanded) + .frame(width: 14) + + // Key badge + KeyBadgeView(key: group.groupKey) + .padding(.leading, 4) + + // Group name + Text(group.groupLabel) + .font(.system(.body)) + .foregroundColor(.primary) + .padding(.leading, 8) + + Spacer(minLength: 16) + + // Right-aligned section (always same position) + HStack(spacing: 0) { + // Progress bar + ProgressBarView(value: group.totalCount, max: maxCount) + .padding(.trailing, 20) + + // Folder icon + Image(systemName: "folder") + .resizable() + .scaledToFit() + .foregroundColor(.secondary) + .frame(width: 24, height: 24) + + // Count + Text("\(group.totalCount)") + .foregroundColor(.primary) + .font(.system(.body, design: .rounded)) + .fontWeight(.medium) + .monospacedDigit() + .frame(width: 36, alignment: .trailing) + } + } + .padding(.trailing, 18) + .padding(.vertical, 8) + .padding(.horizontal, 8) + .background( RoundedRectangle(cornerRadius: 8) + .fill(Color.secondary.opacity(0.1)) + ) + .contentShape(Rectangle()) + } + .buttonStyle(PlainButtonStyle()) + } + + // Expanded children + if isExpanded { + VStack(spacing: 2) { + ForEach(group.children) { child in + switch child { + case .action(let stat): + ActionStatsRow( + stat: stat, + maxCount: group.children.map(\.executionCount).max() ?? 1, + depth: depth + 1, + expandedGroups: $expandedGroups + ) + case .group(let subGroup): + GroupStatsRow( + group: subGroup, + isExpanded: expandedGroups.contains(subGroup.id), + maxCount: group.children.map(\.executionCount).max() ?? 1, + depth: depth + 1, + expandedGroups: $expandedGroups + ) + } + } + } + } + } + } else { + // Top-level individual action + if case .action(let stat) = group.children.first { + ActionStatsRow( + stat: stat, + maxCount: maxCount, + depth: depth, + expandedGroups: $expandedGroups + ) + } + } + } +} + +private struct ActionStatsRow: View { + let stat: ActionStatsDisplay + let maxCount: Int + let depth: Int + @Binding var expandedGroups: Set + + private let indentPerLevel: CGFloat = 16 + + var body: some View { + HStack(alignment: .center, spacing: 0) { + // Indent spacer (add extra indent since no chevron) + Spacer() + .frame(width: indentPerLevel * CGFloat(depth) + 14) + + // Key badge + if let lastKey = stat.pathComponents.last { + KeyBadgeView(key: lastKey) + .padding(.leading, 4) + } + + // Action name + Text(displayName) + .font(.system(.body)) + .lineLimit(1) + .truncationMode(.tail) + .padding(.leading, 8) + + Spacer(minLength: 16) + + // Right-aligned section (always same position) + HStack(spacing: 0) { + // Progress bar + ProgressBarView(value: stat.action.executionCount, max: maxCount) + .padding(.trailing, 20) + + // Icon + ActionIconView(actionType: stat.action.actionType, actionValue: stat.action.actionValue) + + // Count + Text("\(stat.action.executionCount)") + .foregroundColor(.primary) + .font(.system(.body, design: .rounded)) + .fontWeight(.medium) + .monospacedDigit() + .frame(width: 36, alignment: .trailing) + } + } + .padding(.trailing, 18) + .padding(.vertical, 8) + .padding(.horizontal, 8) + .contentShape(Rectangle()) + } + + private var displayName: String { + if let label = stat.action.actionLabel, !label.isEmpty { + return label + } + switch stat.action.actionType { + case "application": + return + (stat.action.actionValue as NSString).lastPathComponent + .replacingOccurrences(of: ".app", with: "") + case "folder": + return (stat.action.actionValue as NSString).lastPathComponent + default: + return stat.action.actionValue + } + } +} + +private struct ProgressBarView: View { + let value: Int + let max: Int + + var body: some View { + GeometryReader { geometry in + ZStack(alignment: .leading) { + RoundedRectangle(cornerRadius: 2) + .fill(Color.secondary.opacity(0.15)) + .frame(height: 6) + + RoundedRectangle(cornerRadius: 2) + .fill(Color.accentColor) + .frame( + width: geometry.size.width * CGFloat(value) / CGFloat(max), + height: 6 + ) + } + } + .frame(width: 100, height: 6) + } +} + +private struct KeyBadgeView: View { + let key: String + + var body: some View { + Text(KeyMaps.glyph(for: key) ?? key) + .font(.system(.callout, design: .monospaced)) + .fontWeight(.medium) + .foregroundColor(.primary) + .frame(width: 28, height: 28) + .background(Color.secondary.opacity(0.15)) + .clipShape(RoundedRectangle(cornerRadius: 6, style: .continuous)) + } +} + +private struct ActionIconView: View { + let actionType: String + let actionValue: String + + private let iconSize: CGFloat = 24 + + var body: some View { + iconContent + .frame(width: iconSize, height: iconSize) + } + + @ViewBuilder + private var iconContent: some View { + switch actionType { + case "application": + AppIconImage(appPath: actionValue, size: NSSize(width: iconSize, height: iconSize)) + case "url": + FavIconImage(url: actionValue, icon: "link", size: NSSize(width: iconSize, height: iconSize)) + case "folder", "group": + Image(systemName: "folder") + .resizable() + .scaledToFit() + .foregroundColor(.secondary) + case "command": + Image(systemName: "terminal") + .resizable() + .scaledToFit() + .foregroundColor(.secondary) + default: + Image(systemName: "questionmark.circle") + .resizable() + .scaledToFit() + .foregroundColor(.secondary) + } + } +} diff --git a/Leader Key/Stats/StatsManager.swift b/Leader Key/Stats/StatsManager.swift new file mode 100644 index 00000000..beb6d71c --- /dev/null +++ b/Leader Key/Stats/StatsManager.swift @@ -0,0 +1,349 @@ +import Foundation + +class StatsManager { + static let shared = StatsManager() + + // Optimization: Only keep recent executions in memory + private var recentExecutions: [ActionExecution] = [] + private let maxRecentExecutions = 50 + + // Optimization: Pre-aggregate daily counts + private var dailyExecutions: [Date: Int] = [:] + + private var actionStatsCache: [String: ActionStats] = [:] + private var groupStatsCache: [String: GroupNavigationStats] = [:] + + private var totalExecutions: Int = 0 + private var totalNavigations: Int = 0 + + private let statsFilePath: String + private var fileHandle: FileHandle? + private let ioQueue = DispatchQueue(label: "com.leaderkey.StatsIO", qos: .utility) + private let lock = NSLock() + private let encoder = JSONEncoder() + + private init() { + let supportDir = UserConfig.defaultDirectory() + statsFilePath = (supportDir as NSString).appendingPathComponent("stats.jsonl") + setupStatsFile() + loadFromDisk() + } + + private func setupStatsFile() { + let fileManager = FileManager.default + + do { + try fileHandle?.close() + } catch { + print("Failed to close stats file: \(error)") + } + fileHandle = nil + + if !fileManager.fileExists(atPath: statsFilePath) { + fileManager.createFile(atPath: statsFilePath, contents: nil) + } + + do { + fileHandle = try FileHandle(forUpdating: URL(fileURLWithPath: statsFilePath)) + try fileHandle?.seekToEnd() + } catch { + print("Failed to open stats file: \(error)") + } + } + + private func actionStatsKey(for record: ActionExecution) -> String { + if !record.keyPath.isEmpty { + return record.keyPath + } + return "\(record.actionType)|\(record.actionValue)" + } + + private func groupStatsKey(for record: ActionExecution) -> String { + if !record.keyPath.isEmpty { + return record.keyPath + } + return record.actionValue + } + + private func loadFromDisk() { + guard let data = try? Data(contentsOf: URL(fileURLWithPath: statsFilePath)) else { + return + } + + // TODO: For very large files, stream line-by-line instead of loading all at once + let lines = String(data: data, encoding: .utf8)?.components(separatedBy: .newlines) ?? [] + let decoder = JSONDecoder() + let calendar = Calendar.current + + for line in lines { + guard !line.isEmpty else { continue } + + do { + let record = try decoder.decode(ActionExecution.self, from: Data(line.utf8)) + updateAggregates(record) + + // Track daily stats + let day = calendar.startOfDay(for: record.timestamp) + dailyExecutions[day, default: 0] += 1 + + // Maintain fixed-size recent history + recentExecutions.append(record) + if recentExecutions.count > maxRecentExecutions { + recentExecutions.removeFirst() + } + } catch { + print("Failed to parse stats line: \(error)") + } + } + } + + private func updateAggregates(_ record: ActionExecution) { + if record.eventType == "action" { + totalExecutions += 1 + + let key = actionStatsKey(for: record) + if var existing = actionStatsCache[key] { + existing.executionCount += 1 + if record.timestamp > existing.lastExecuted { + existing.lastExecuted = record.timestamp + } + if (existing.actionLabel?.isEmpty ?? true), !(record.actionLabel?.isEmpty ?? true) { + existing.actionLabel = record.actionLabel + } + actionStatsCache[key] = existing + } else { + actionStatsCache[key] = ActionStats( + actionValue: record.actionValue, + actionType: record.actionType, + actionLabel: record.actionLabel, + keyPath: record.keyPath, + executionCount: 1, + lastExecuted: record.timestamp + ) + } + } else if record.eventType == "group" { + totalNavigations += 1 + + let key = groupStatsKey(for: record) + if var existing = groupStatsCache[key] { + existing.navigationCount += 1 + if record.timestamp > existing.lastNavigated { + existing.lastNavigated = record.timestamp + } + if (existing.groupLabel?.isEmpty ?? true), !(record.actionLabel?.isEmpty ?? true) { + existing.groupLabel = record.actionLabel + } + groupStatsCache[key] = existing + } else { + groupStatsCache[key] = GroupNavigationStats( + groupKey: record.actionValue, + groupLabel: record.actionLabel, + keyPath: record.keyPath, + navigationCount: 1, + lastNavigated: record.timestamp + ) + } + } + } + + private func appendToFile(_ record: ActionExecution) { + ioQueue.async { [weak self] in + guard let self = self else { return } + + guard let jsonData = try? self.encoder.encode(record) else { + print("Failed to encode stats record") + return + } + + guard let jsonString = String(data: jsonData, encoding: .utf8) else { + return + } + + let line = jsonString + "\n" + guard let lineData = line.data(using: .utf8) else { return } + + do { + try self.fileHandle?.write(contentsOf: lineData) + } catch { + print("Failed to write stats record: \(error)") + } + } + } + + // MARK: - Recording + + func recordExecution(action: Action, keyPath: String) { + let record = ActionExecution( + actionType: action.type.rawValue, + actionValue: action.value, + actionLabel: action.label, + keyPath: keyPath, + eventType: "action", + timestamp: Date() + ) + + lock.lock() + updateAggregates(record) + + let calendar = Calendar.current + let day = calendar.startOfDay(for: record.timestamp) + dailyExecutions[day, default: 0] += 1 + + recentExecutions.append(record) + if recentExecutions.count > maxRecentExecutions { + recentExecutions.removeFirst() + } + lock.unlock() + + appendToFile(record) + } + + func recordGroupNavigation(group: Group, keyPath: String) { + let record = ActionExecution( + actionType: "group", + actionValue: group.key ?? "", + actionLabel: group.label, + keyPath: keyPath, + eventType: "group", + timestamp: Date() + ) + + lock.lock() + updateAggregates(record) + + // Also track navigations in daily stats? + // The previous implementation included everything in 'executions' array but getExecutionsPerDay iterated all. + // Let's include them to maintain behavior. + let calendar = Calendar.current + let day = calendar.startOfDay(for: record.timestamp) + dailyExecutions[day, default: 0] += 1 + + recentExecutions.append(record) + if recentExecutions.count > maxRecentExecutions { + recentExecutions.removeFirst() + } + lock.unlock() + + appendToFile(record) + } + + // MARK: - Queries + + func getMostUsedActions(limit: Int = 20) -> [ActionStats] { + lock.lock() + defer { lock.unlock() } + + return Array(actionStatsCache.values) + .sorted { $0.executionCount > $1.executionCount } + .prefix(limit) + .map { $0 } + } + + func getMostNavigatedGroups(limit: Int = 20) -> [GroupNavigationStats] { + lock.lock() + defer { lock.unlock() } + + return Array(groupStatsCache.values) + .sorted { $0.navigationCount > $1.navigationCount } + .prefix(limit) + .map { $0 } + } + + func getRecentActivity(limit: Int = 50) -> [ActionExecution] { + lock.lock() + defer { lock.unlock() } + + // Return reversed so newest is first + return Array(recentExecutions.suffix(limit).reversed()) + } + + func getTotalExecutions() -> Int { + lock.lock() + defer { lock.unlock() } + + return totalExecutions + } + + func getTotalNavigations() -> Int { + lock.lock() + defer { lock.unlock() } + + return totalNavigations + } + + func getExecutionsPerDay(days: Int = 30) -> [(date: Date, count: Int)] { + lock.lock() + defer { lock.unlock() } + + let calendar = Calendar.current + guard let cutoffDate = calendar.date(byAdding: .day, value: -days, to: Date()) else { + return [] + } + + // Filter from pre-aggregated dictionary + return dailyExecutions + .filter { $0.key >= cutoffDate } + .sorted { $0.key < $1.key } + .map { (date: $0.key, count: $0.value) } + } + + func getTodayCount() -> Int { + lock.lock() + defer { lock.unlock() } + + let calendar = Calendar.current + let today = calendar.startOfDay(for: Date()) + return dailyExecutions[today] ?? 0 + } + + func clearAllStats() { + lock.lock() + recentExecutions.removeAll() + dailyExecutions.removeAll() + actionStatsCache.removeAll() + groupStatsCache.removeAll() + totalExecutions = 0 + totalNavigations = 0 + lock.unlock() + + ioQueue.async { [weak self] in + guard let self = self else { return } + + do { + try self.fileHandle?.close() + } catch { + print("Failed to close stats file: \(error)") + } + self.fileHandle = nil + + try? FileManager.default.removeItem(atPath: self.statsFilePath) + self.setupStatsFile() + } + } +} + +struct ActionExecution: Codable { + var actionType: String + var actionValue: String + var actionLabel: String? + var keyPath: String + var eventType: String + var timestamp: Date +} + +struct ActionStats { + var actionValue: String + var actionType: String + var actionLabel: String? + var keyPath: String + var executionCount: Int + var lastExecuted: Date +} + +struct GroupNavigationStats { + var groupKey: String + var groupLabel: String? + var keyPath: String + var navigationCount: Int + var lastNavigated: Date +} diff --git a/Leader Key/Themes/Cheater.swift b/Leader Key/Themes/Cheater.swift index 30af3f40..fbbb9721 100644 --- a/Leader Key/Themes/Cheater.swift +++ b/Leader Key/Themes/Cheater.swift @@ -7,7 +7,7 @@ enum Cheater { required init(controller: Controller) { super.init(controller: controller, contentRect: NSRect(x: 0, y: 0, width: 0, height: 0)) - let view = Cheatsheet.CheatsheetView() + let view = CheatsheetView() contentView = NSHostingView(rootView: view.environmentObject(self.controller.userState)) } diff --git a/Leader Key/Themes/MysteryBox.swift b/Leader Key/Themes/MysteryBox.swift index 2c2b9116..a982710b 100644 --- a/Leader Key/Themes/MysteryBox.swift +++ b/Leader Key/Themes/MysteryBox.swift @@ -58,6 +58,15 @@ enum MysteryBox { if userState.isShowingRefreshState { text.pulsate() + } else if let group = userState.currentGroup, group.iconPath?.isEmpty == false { + // Inside a group with its own icon, lead with the icon and keep the key as a caption + VStack(spacing: 10) { + actionIcon(item: .group(group), iconSize: NSSize(width: 80, height: 80)) + .font(.system(size: 56)) + Text(glyphText) + .font(.system(size: 17, weight: .semibold, design: .rounded)) + .foregroundStyle(.secondary) + } } else { text } diff --git a/Leader Key/URLSchemeHandler.swift b/Leader Key/URLSchemeHandler.swift index fc1d8522..954698b9 100644 --- a/Leader Key/URLSchemeHandler.swift +++ b/Leader Key/URLSchemeHandler.swift @@ -36,8 +36,8 @@ class URLSchemeHandler { return .reset case "navigate": guard let components = URLComponents(url: url, resolvingAgainstBaseURL: false), - let queryItems = components.queryItems, - let keysParam = queryItems.first(where: { $0.name == "keys" })?.value + let queryItems = components.queryItems, + let keysParam = queryItems.first(where: { $0.name == "keys" })?.value else { return .show } diff --git a/Leader Key/UserConfig.swift b/Leader Key/UserConfig.swift index c339d028..bd8560b0 100644 --- a/Leader Key/UserConfig.swift +++ b/Leader Key/UserConfig.swift @@ -372,6 +372,34 @@ extension UserConfig { } } +extension Group { + func find(id: UUID) -> Group? { + if self.uiid == id { return self } + for action in actions { + if case .group(let g) = action { + if let found = g.find(id: id) { return found } + } + } + return nil + } + + mutating func update(group: Group) -> Bool { + if self.uiid == group.uiid { + self = group + return true + } + for i in 0.. ActionOrGroup { + switch self { + case .action(var a): + a.key = key + return .action(a) + case .group(var g): + g.key = key + return .group(g) + } + } + init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) let key = try container.decode(String?.self, forKey: .key) diff --git a/Leader Key/UserState.swift b/Leader Key/UserState.swift index b8ac1a2c..148ad2c5 100644 --- a/Leader Key/UserState.swift +++ b/Leader Key/UserState.swift @@ -8,6 +8,7 @@ final class UserState: ObservableObject { @Published var display: String? @Published var isShowingRefreshState: Bool @Published var navigationPath: [Group] = [] + @Published var shiftHeld: Bool = false var currentGroup: Group? { return navigationPath.last @@ -33,4 +34,12 @@ final class UserState: ObservableObject { func navigateToGroup(_ group: Group) { navigationPath.append(group) } + + func navigateBack() -> Bool { + if navigationPath.isEmpty { + return false + } + navigationPath.removeLast() + return true + } } diff --git a/Leader Key/Views/ActionIcon.swift b/Leader Key/Views/ActionIcon.swift index 74d37e9a..8e056574 100644 --- a/Leader Key/Views/ActionIcon.swift +++ b/Leader Key/Views/ActionIcon.swift @@ -16,6 +16,9 @@ func actionIcon(item: ActionOrGroup, iconSize: NSSize, loadFavicons: Bool = true if let iconPath = iconPath, !iconPath.isEmpty { if iconPath.hasSuffix(".app") { return AnyView(AppIconImage(appPath: iconPath, size: iconSize)) + } else if CustomIconRenderer.isCustomImagePath(iconPath) { + // Custom image file path + return AnyView(CustomIconImage(imagePath: iconPath, size: iconSize)) } else { return AnyView( Image(systemName: iconPath) @@ -32,7 +35,7 @@ func actionIcon(item: ActionOrGroup, iconSize: NSSize, loadFavicons: Bool = true return AnyView(AppIconImage(appPath: value ?? "", size: iconSize)) case .url: if loadFavicons { - return AnyView(FavIconImage(url: value ?? "", icon: "link")) + return AnyView(FavIconImage(url: value ?? "", icon: "link", size: iconSize)) } else { return AnyView( Image(systemName: "link") @@ -66,6 +69,26 @@ func actionIcon(item: ActionOrGroup, iconSize: NSSize, loadFavicons: Bool = true ) } +/// Rendered icons, kept so redrawing a key does not hit the disk again. +/// Cleared when the config reloads, which is when icon paths can change. +enum IconCache { + private static let cache = NSCache() + + static func image(kind: String, path: String, size: NSSize, make: () -> NSImage?) -> NSImage? { + let key = "\(kind)|\(size.width)x\(size.height)|\(path)" as NSString + if let cached = cache.object(forKey: key) { + return cached + } + guard let image = make() else { return nil } + cache.setObject(image, forKey: key) + return image + } + + static func removeAll() { + cache.removeAllObjects() + } +} + struct AppIconImage: View { let appPath: String let size: NSSize @@ -89,6 +112,10 @@ struct AppIconImage: View { } private func getAppIcon(path: String) -> NSImage? { + IconCache.image(kind: "app", path: path, size: size) { renderAppIcon(path: path) } + } + + private func renderAppIcon(path: String) -> NSImage? { guard FileManager.default.fileExists(atPath: path) else { return nil } @@ -103,6 +130,35 @@ struct AppIconImage: View { } } +struct CustomIconImage: View { + let imagePath: String + let size: NSSize + let defaultSystemName: String = "photo" + + init(imagePath: String, size: NSSize = NSSize(width: 24, height: 24)) { + self.imagePath = imagePath + self.size = size + } + + var body: some View { + let image = + if let nsImage = loadImage(path: imagePath) { + Image(nsImage: nsImage) + } else { + Image(systemName: defaultSystemName) + } + image.resizable() + .scaledToFit() + .frame(width: size.width, height: size.height) + } + + private func loadImage(path: String) -> NSImage? { + IconCache.image(kind: "custom", path: path, size: size) { + CustomIconRenderer.renderCustomIcon(from: path, size: size) + } + } +} + struct FavIconImage: View { let url: String let icon: String @@ -124,8 +180,9 @@ struct FavIconImage: View { KFImage.url(URL(string: url)).placeholder({ fallback }).resizable() - .padding(4) + .aspectRatio(contentMode: .fit) .frame(width: size.width, height: size.height, alignment: .center) + .clipShape(RoundedRectangle(cornerRadius: size.width * 0.2, style: .continuous)) } else { fallback } diff --git a/Leader Key/Views/ConfigEditorShared.swift b/Leader Key/Views/ConfigEditorShared.swift index 2da726fc..7b01143c 100644 --- a/Leader Key/Views/ConfigEditorShared.swift +++ b/Leader Key/Views/ConfigEditorShared.swift @@ -44,6 +44,7 @@ enum ConfigEditorUI { anchor: NSView?, onPickAppIcon: @escaping () -> Void, onPickSymbol: @escaping () -> Void, + onPickCustomImage: @escaping () -> Void, onClear: @escaping () -> Void ) { guard let anchor else { return } @@ -58,11 +59,17 @@ enum ConfigEditorUI { action: #selector(MenuHandler.pickSymbol), keyEquivalent: "" ) + menu.addItem( + withTitle: "Custom Icon…", + action: #selector(MenuHandler.pickCustomImage), + keyEquivalent: "" + ) menu.addItem(NSMenuItem.separator()) menu.addItem(withTitle: "Clear", action: #selector(MenuHandler.clearIcon), keyEquivalent: "") let handler = MenuHandler( onPickAppIcon: onPickAppIcon, onPickSymbol: onPickSymbol, + onPickCustomImage: onPickCustomImage, onClearIcon: onClear, onDuplicate: {}, onDelete: {} @@ -83,6 +90,7 @@ enum ConfigEditorUI { private final class MenuHandler: NSObject { let onPickAppIcon: (() -> Void)? let onPickSymbol: (() -> Void)? + let onPickCustomImage: (() -> Void)? let onClearIcon: (() -> Void)? let onDuplicate: () -> Void let onDelete: () -> Void @@ -90,12 +98,14 @@ enum ConfigEditorUI { init( onPickAppIcon: (() -> Void)? = nil, onPickSymbol: (() -> Void)? = nil, + onPickCustomImage: (() -> Void)? = nil, onClearIcon: (() -> Void)? = nil, onDuplicate: @escaping () -> Void, onDelete: @escaping () -> Void ) { self.onPickAppIcon = onPickAppIcon self.onPickSymbol = onPickSymbol + self.onPickCustomImage = onPickCustomImage self.onClearIcon = onClearIcon self.onDuplicate = onDuplicate self.onDelete = onDelete @@ -103,17 +113,32 @@ enum ConfigEditorUI { @objc func pickAppIcon() { onPickAppIcon?() } @objc func pickSymbol() { onPickSymbol?() } + @objc func pickCustomImage() { onPickCustomImage?() } @objc func clearIcon() { onClearIcon?() } @objc func duplicate() { onDuplicate() } @objc func delete() { onDelete() } } + + static func resizeAndRoundImage(_ image: NSImage, size: CGFloat) -> NSImage { + CustomIconRenderer.render(image, size: NSSize(width: size, height: size)) + } } extension Action { func resolvedIcon() -> NSImage? { if let iconPath = iconPath, !iconPath.isEmpty { - if iconPath.hasSuffix(".app") { return NSWorkspace.shared.icon(forFile: iconPath) } - if let img = NSImage(systemSymbolName: iconPath, accessibilityDescription: nil) { return img } + if iconPath.hasSuffix(".app") { + return NSWorkspace.shared.icon(forFile: iconPath) + } + if let customImage = CustomIconRenderer.renderCustomIcon( + from: iconPath, + size: NSSize(width: 28, height: 28) + ) { + return customImage + } + if let img = NSImage(systemSymbolName: iconPath, accessibilityDescription: nil) { + return img + } } switch type { case .application: @@ -134,6 +159,12 @@ extension Group { func resolvedIcon() -> NSImage? { if let iconPath = iconPath, !iconPath.isEmpty { if iconPath.hasSuffix(".app") { return NSWorkspace.shared.icon(forFile: iconPath) } + if let customImage = CustomIconRenderer.renderCustomIcon( + from: iconPath, + size: NSSize(width: 28, height: 28) + ) { + return customImage + } if let img = NSImage(systemSymbolName: iconPath, accessibilityDescription: nil) { return img } } return NSImage(systemSymbolName: "folder", accessibilityDescription: nil) diff --git a/Leader Key/Views/ConfigOutlineEditorView.swift b/Leader Key/Views/ConfigOutlineEditorView.swift index 5838cc5b..e946cd22 100644 --- a/Leader Key/Views/ConfigOutlineEditorView.swift +++ b/Leader Key/Views/ConfigOutlineEditorView.swift @@ -893,6 +893,7 @@ private class ActionCellView: NSTableCellView, NSWindowDelegate { anchor: anchor, onPickAppIcon: { self.handlePickAppIcon() }, onPickSymbol: { self.handlePickSymbol() }, + onPickCustomImage: { self.handlePickCustomImage() }, onClear: { self.handleClearIcon() } ) } @@ -933,6 +934,36 @@ private class ActionCellView: NSTableCellView, NSWindowDelegate { ) } + @objc private func handlePickCustomImage() { + guard var a = currentAction() else { return } + let panel = NSOpenPanel() + panel.allowedContentTypes = [.png, .jpeg, .icns] + panel.canChooseFiles = true + panel.canChooseDirectories = false + panel.allowsMultipleSelection = false + panel.directoryURL = FileManager.default.homeDirectoryForCurrentUser + panel.message = "Choose a custom icon image" + if panel.runModal() == .OK { + guard let path = panel.url?.path else { return } + + // Validate that the file can actually be loaded as an image + guard NSImage(contentsOfFile: path) != nil else { + let alert = NSAlert() + alert.messageText = "Invalid Image File" + alert.informativeText = "The selected file could not be loaded as an image. Please choose a valid PNG, JPEG, or ICNS file." + alert.alertStyle = .warning + alert.runModal() + return + } + + DispatchQueue.main.async { + a.iconPath = path + self.onChange?(.action(a)) + self.updateIcon(for: a) + } + } + } + @objc private func handleClearIcon() { guard var a = currentAction() else { return } DispatchQueue.main.async { @@ -1239,6 +1270,7 @@ private class GroupCellView: NSTableCellView, NSWindowDelegate { anchor: anchor, onPickAppIcon: { self.handlePickAppIcon() }, onPickSymbol: { self.handlePickSymbol() }, + onPickCustomImage: { self.handlePickCustomImage() }, onClear: { self.handleClearIcon() } ) } @@ -1279,6 +1311,36 @@ private class GroupCellView: NSTableCellView, NSWindowDelegate { ) } + @objc private func handlePickCustomImage() { + guard var g = currentGroup() else { return } + let panel = NSOpenPanel() + panel.allowedContentTypes = [.png, .jpeg, .icns] + panel.canChooseFiles = true + panel.canChooseDirectories = false + panel.allowsMultipleSelection = false + panel.directoryURL = FileManager.default.homeDirectoryForCurrentUser + panel.message = "Choose a custom icon image" + if panel.runModal() == .OK { + guard let path = panel.url?.path else { return } + + // Validate that the file can actually be loaded as an image + guard NSImage(contentsOfFile: path) != nil else { + let alert = NSAlert() + alert.messageText = "Invalid Image File" + alert.informativeText = "The selected file could not be loaded as an image. Please choose a valid PNG, JPEG, or ICNS file." + alert.alertStyle = .warning + alert.runModal() + return + } + + DispatchQueue.main.async { + g.iconPath = path + self.onChange?(.group(g)) + self.updateIcon(for: g) + } + } + } + @objc private func handleClearIcon() { guard var g = currentGroup() else { return } DispatchQueue.main.async { diff --git a/Leader Key/Views/CustomIconRenderer.swift b/Leader Key/Views/CustomIconRenderer.swift new file mode 100644 index 00000000..d104bb98 --- /dev/null +++ b/Leader Key/Views/CustomIconRenderer.swift @@ -0,0 +1,63 @@ +import AppKit + +enum CustomIconRenderer { + static let cornerRadiusFactor: CGFloat = 0.2237 + static let contentScale: CGFloat = 0.84 + + static func isCustomImagePath(_ path: String) -> Bool { + var isDirectory: ObjCBool = false + let exists = FileManager.default.fileExists(atPath: path, isDirectory: &isDirectory) + return exists && !isDirectory.boolValue + } + + static func renderCustomIcon(from path: String, size: NSSize) -> NSImage? { + guard isCustomImagePath(path), + let image = NSImage(contentsOfFile: path) else { + return nil + } + return render(image, size: size) + } + + static func render(_ image: NSImage, size: NSSize) -> NSImage { + let targetSize = NSSize(width: size.width, height: size.height) + let outputImage = NSImage(size: targetSize) + + outputImage.lockFocus() + defer { outputImage.unlockFocus() } + + // Scale down the icon content to match app bundle icon sizing + let scaledWidth = size.width * contentScale + let scaledHeight = size.height * contentScale + let inset = (size.width - scaledWidth) / 2 + let destRect = NSRect(x: inset, y: inset, width: scaledWidth, height: scaledHeight) + + let cornerRadius = min(scaledWidth, scaledHeight) * cornerRadiusFactor + let clipPath = NSBezierPath(roundedRect: destRect, xRadius: cornerRadius, yRadius: cornerRadius) + clipPath.addClip() + + let drawRect = aspectFillRect(for: image.size, in: destRect) + image.draw( + in: drawRect, + from: NSRect(origin: .zero, size: image.size), + operation: .sourceOver, + fraction: 1.0 + ) + + return outputImage + } + + private static func aspectFillRect(for sourceSize: NSSize, in destRect: NSRect) -> NSRect { + guard sourceSize.width > 0, sourceSize.height > 0 else { return destRect } + + let widthScale = destRect.width / sourceSize.width + let heightScale = destRect.height / sourceSize.height + let scale = max(widthScale, heightScale) + let scaledSize = NSSize(width: sourceSize.width * scale, height: sourceSize.height * scale) + let origin = NSPoint( + x: destRect.midX - scaledSize.width / 2, + y: destRect.midY - scaledSize.height / 2 + ) + + return NSRect(origin: origin, size: scaledSize) + } +} diff --git a/Leader KeyTests/KeyboardLayoutTests.swift b/Leader KeyTests/KeyboardLayoutTests.swift index 9c898b09..d9a92f30 100644 --- a/Leader KeyTests/KeyboardLayoutTests.swift +++ b/Leader KeyTests/KeyboardLayoutTests.swift @@ -1,3 +1,4 @@ +import Carbon.HIToolbox import Combine import Defaults import XCTest @@ -138,3 +139,165 @@ class KeyboardLayoutTests: XCTestCase { XCTAssertEqual(result, "←", "Special keys should always use KeyMaps") } } + +class KeyboardLayoutModelTests: XCTestCase { + private var originalForceEnglish: Bool! + + override func setUp() { + super.setUp() + originalForceEnglish = Defaults[.forceEnglishKeyboardLayout] + } + + override func tearDown() { + Defaults[.forceEnglishKeyboardLayout] = originalForceEnglish + super.tearDown() + } + + func testEveryRowHasTheSameWidthAsTotalWidth() { + XCTAssertEqual(KeyboardLayout.totalWidth, 656, accuracy: 0.001) + for (index, row) in KeyboardLayout.rows.enumerated() { + XCTAssertEqual( + KeyboardLayout.rowWidth(row), KeyboardLayout.totalWidth, accuracy: 0.001, + "Row \(index) should be as wide as the keyboard") + } + } + + func testRowWidthIsSumOfKeyWidthsPlusGaps() { + for scale: CGFloat in [1.0, KeyboardLayout.centeredScale] { + for (index, row) in KeyboardLayout.rows.enumerated() { + let keys = row.reduce(0) { $0 + KeyboardLayout.keyWidth(for: $1, scale: scale) } + let gaps = CGFloat(row.count - 1) * KeyboardLayout.scaledKeySpacing(scale) + XCTAssertEqual( + KeyboardLayout.rowWidth(row, scale: scale), keys + gaps, accuracy: 0.001, + "Row \(index) at scale \(scale)") + } + } + } + + func testKeyWidthCoversSpannedGaps() { + let single = KeyboardLayout.row0[0] + let backspace = KeyboardLayout.row0.last! + XCTAssertEqual(KeyboardLayout.keyWidth(for: single), 40, accuracy: 0.001) + XCTAssertEqual(KeyboardLayout.keyWidth(for: backspace), 84, accuracy: 0.001) + XCTAssertEqual(KeyboardLayout.keyWidth(for: backspace, scale: 2), 168, accuracy: 0.001) + } + + func testShiftedKeyForLetters() { + XCTAssertEqual(KeyboardLayout.shiftedKey(for: "a"), "A") + XCTAssertEqual(KeyboardLayout.shiftedKey(for: "z"), "Z") + } + + func testShiftedKeyForDigits() { + let expected = [ + "1": "!", "2": "@", "3": "#", "4": "$", "5": "%", + "6": "^", "7": "&", "8": "*", "9": "(", "0": ")", + ] + for (key, shifted) in expected { + XCTAssertEqual(KeyboardLayout.shiftedKey(for: key), shifted) + } + } + + func testShiftedKeyForPunctuation() { + let expected = [ + "`": "~", "-": "_", "=": "+", "[": "{", "]": "}", "\\": "|", + ";": ":", "'": "\"", ",": "<", ".": ">", "/": "?", + ] + for (key, shifted) in expected { + XCTAssertEqual(KeyboardLayout.shiftedKey(for: key), shifted) + } + } + + func testShiftedKeyLeavesNamedKeysAlone() { + XCTAssertEqual(KeyboardLayout.shiftedKey(for: "tab"), "tab") + XCTAssertEqual(KeyboardLayout.shiftedKey(for: "space"), "space") + } + + func testBindingKeyIsStaticWhenForcingEnglishLayout() { + Defaults[.forceEnglishKeyboardLayout] = true + + for keyDef in KeyboardLayout.rows.joined() { + XCTAssertEqual(KeyboardLayout.bindingKey(for: keyDef, shifted: false), keyDef.key) + XCTAssertEqual( + KeyboardLayout.bindingKey(for: keyDef, shifted: true), + KeyboardLayout.shiftedKey(for: keyDef.key)) + XCTAssertEqual( + KeyboardLayout.bindingKey(forStaticKey: keyDef.key, shifted: true), + KeyboardLayout.bindingKey(for: keyDef, shifted: true)) + } + } + + func testNonCharacterKeysAreStaticForAnyLayout() { + Defaults[.forceEnglishKeyboardLayout] = false + + for keyDef in KeyboardLayout.rows.joined() where !keyDef.isCharacterKey { + XCTAssertEqual(KeyboardLayout.bindingKey(for: keyDef, shifted: false), keyDef.key) + XCTAssertEqual(KeyboardLayout.bindingKey(for: keyDef, shifted: true), keyDef.key) + } + } + + private func inputSource(id: String) -> TISInputSource? { + let filter = [kTISPropertyInputSourceID as String: id] as CFDictionary + let sources = TISCreateInputSourceList(filter, true)?.takeRetainedValue() as? [TISInputSource] + return sources?.first + } + + private func keyDef(_ keyCode: Int) -> KeyDefinition { + KeyboardLayout.rows.joined().first { $0.keyCode == UInt16(keyCode) }! + } + + func testBindingKeyFollowsInputSource() throws { + guard let french = inputSource(id: "com.apple.keylayout.French") else { + throw XCTSkip("French keyboard layout is not installed") + } + Defaults[.forceEnglishKeyboardLayout] = false + + func key(_ keyCode: Int, shifted: Bool = false) -> String { + KeyboardLayout.bindingKey(for: keyDef(keyCode), shifted: shifted, inputSource: french) + } + + // AZERTY swaps A/Q and moves M + XCTAssertEqual(key(kVK_ANSI_Q), "a") + XCTAssertEqual(key(kVK_ANSI_A), "q") + XCTAssertEqual(key(kVK_ANSI_Q, shifted: true), "A") + XCTAssertEqual(key(kVK_ANSI_Semicolon), "m") + XCTAssertEqual(key(kVK_ANSI_Semicolon, shifted: true), "M") + XCTAssertEqual(key(kVK_ANSI_M), ",") + XCTAssertEqual(key(kVK_ANSI_M, shifted: true), "?") + + // Digit row: symbols unshifted, digits shifted + XCTAssertEqual(key(kVK_ANSI_1), "&") + XCTAssertEqual(key(kVK_ANSI_1, shifted: true), "1") + // "é" is not ASCII, so the controller falls back to the KeyMaps glyph + XCTAssertEqual(key(kVK_ANSI_2), "2") + XCTAssertEqual(key(kVK_ANSI_2, shifted: true), "2") + + // Dead key yields its own character + XCTAssertEqual(key(kVK_ANSI_LeftBracket), "^") + + // Non-character keys never follow the layout + XCTAssertEqual(key(kVK_Tab), "tab") + XCTAssertEqual(key(kVK_Space), "space") + } + + func testBindingKeyIgnoresInputSourceWhenForcingEnglishLayout() throws { + guard let french = inputSource(id: "com.apple.keylayout.French") else { + throw XCTSkip("French keyboard layout is not installed") + } + Defaults[.forceEnglishKeyboardLayout] = true + + XCTAssertEqual( + KeyboardLayout.bindingKey(for: keyDef(kVK_ANSI_Q), shifted: false, inputSource: french), "q") + } + + func testCharacterKeyCodesMatchKeyMaps() { + // Letters and digits are the keys KeyMaps knows by code; the layout must agree + for keyDef in KeyboardLayout.rows.joined() where keyDef.isCharacterKey { + guard let entry = KeyMaps.entry(for: keyDef.keyCode) else { continue } + XCTAssertEqual(entry.glyph, keyDef.key, "Key code mismatch for \(keyDef.key)") + } + for key in ["tab", "enter", "space"] { + let keyDef = KeyboardLayout.rows.joined().first { $0.key == key } + XCTAssertEqual(keyDef.flatMap { KeyMaps.entry(for: $0.keyCode)?.text }, key) + } + } +}